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.

270162 lines
8.0MB

  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. #ifdef __JUCE_JUCEHEADER__
  29. /* When you add the amalgamated cpp file to your project, you mustn't include it in
  30. a file where you've already included juce.h - just put it inside a file on its own,
  31. possibly with your config flags preceding it, but don't include anything else. */
  32. #error
  33. #endif
  34. /********* Start of inlined file: juce_Config.h *********/
  35. #ifndef __JUCE_CONFIG_JUCEHEADER__
  36. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  37. /*
  38. This file contains macros that enable/disable various JUCE features.
  39. */
  40. /** The name of the namespace that all Juce classes and functions will be
  41. put inside. If this is not defined, no namespace will be used.
  42. */
  43. #ifndef JUCE_NAMESPACE
  44. #define JUCE_NAMESPACE juce
  45. #endif
  46. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  47. but if you define this value, you can override this can force it to be true or
  48. false.
  49. */
  50. #ifndef JUCE_FORCE_DEBUG
  51. //#define JUCE_FORCE_DEBUG 1
  52. #endif
  53. /** If this flag is enabled, the the jassert and jassertfalse macros will
  54. always use Logger::writeToLog() to write a message when an assertion happens.
  55. Enabling it will also leave this turned on in release builds. When it's disabled,
  56. however, the jassert and jassertfalse macros will not be compiled in a
  57. release build.
  58. @see jassert, jassertfalse, Logger
  59. */
  60. #ifndef JUCE_LOG_ASSERTIONS
  61. // #define JUCE_LOG_ASSERTIONS 1
  62. #endif
  63. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  64. which the ASIOAudioIODevice class can't be built. See the comments in the
  65. ASIOAudioIODevice class's header file for more info about this.
  66. (This only affects a Win32 build)
  67. */
  68. #ifndef JUCE_ASIO
  69. #define JUCE_ASIO 1
  70. #endif
  71. /** Comment out this macro to disable building of ALSA device support on Linux.
  72. */
  73. #ifndef JUCE_ALSA
  74. #define JUCE_ALSA 1
  75. #endif
  76. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  77. have the SDK installed.
  78. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  79. classes will be unavailable.
  80. On Windows, if you enable this, you'll need to have the QuickTime SDK
  81. installed, and its header files will need to be on your include path.
  82. */
  83. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  84. #define JUCE_QUICKTIME 1
  85. #endif
  86. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  87. have the appropriate headers and libraries available. If it's not enabled, the
  88. OpenGLComponent class will be unavailable.
  89. */
  90. #ifndef JUCE_OPENGL
  91. #define JUCE_OPENGL 1
  92. #endif
  93. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  94. If you're not going to need either of these formats, turn off the flags to
  95. avoid bloating your codebase with them.
  96. */
  97. #ifndef JUCE_USE_FLAC
  98. #define JUCE_USE_FLAC 1
  99. #endif
  100. #ifndef JUCE_USE_OGGVORBIS
  101. #define JUCE_USE_OGGVORBIS 1
  102. #endif
  103. /** This flag lets you enable support for CD-burning. You might want to disable
  104. it to build without the MS SDK under windows.
  105. */
  106. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  107. #define JUCE_USE_CDBURNER 1
  108. #endif
  109. /** Enabling this macro means that all regions that get repainted will have a coloured
  110. line drawn around them.
  111. This is handy if you're trying to optimise drawing, because it lets you easily see
  112. when anything is being repainted unnecessarily.
  113. */
  114. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  115. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  116. #endif
  117. /** Enable this under Linux to use Xinerama for multi-monitor support.
  118. */
  119. #ifndef JUCE_USE_XINERAMA
  120. #define JUCE_USE_XINERAMA 1
  121. #endif
  122. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  123. */
  124. #ifndef JUCE_USE_XSHM
  125. #define JUCE_USE_XSHM 1
  126. #endif
  127. /** Enabling this builds support for VST audio plugins.
  128. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  129. */
  130. #ifndef JUCE_PLUGINHOST_VST
  131. // #define JUCE_PLUGINHOST_VST 1
  132. #endif
  133. /** Enabling this builds support for AudioUnit audio plugins.
  134. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  135. */
  136. #ifndef JUCE_PLUGINHOST_AU
  137. // #define JUCE_PLUGINHOST_AU 1
  138. #endif
  139. /** Disabling this will avoid linking to any UI code. This is handy for
  140. writing command-line utilities, e.g. on linux boxes which don't have some
  141. of the UI libraries installed.
  142. (On mac and windows, this won't generally make much difference to the build).
  143. */
  144. #ifndef JUCE_BUILD_GUI_CLASSES
  145. #define JUCE_BUILD_GUI_CLASSES 1
  146. #endif
  147. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  148. */
  149. #ifndef JUCE_WEB_BROWSER
  150. #define JUCE_WEB_BROWSER 1
  151. #endif
  152. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  153. codebase - you might need to use this if you're linking to some of these libraries
  154. yourself.
  155. */
  156. #ifndef JUCE_INCLUDE_ZLIB_CODE
  157. #define JUCE_INCLUDE_ZLIB_CODE 1
  158. #endif
  159. #ifndef JUCE_INCLUDE_FLAC_CODE
  160. #define JUCE_INCLUDE_FLAC_CODE 1
  161. #endif
  162. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  163. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  164. #endif
  165. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  166. #define JUCE_INCLUDE_PNGLIB_CODE 1
  167. #endif
  168. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  169. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  170. #endif
  171. /** Enable this to add extra memory-leak info to the new and delete operators.
  172. (Currently, this only affects Windows builds in debug mode).
  173. */
  174. #ifndef JUCE_CHECK_MEMORY_LEAKS
  175. #define JUCE_CHECK_MEMORY_LEAKS 1
  176. #endif
  177. /** Enable this to turn on juce's internal catching of exceptions.
  178. Turning it off will avoid any exception catching. With it on, all exceptions
  179. are passed to the JUCEApplication::unhandledException() callback for logging.
  180. */
  181. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  182. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  183. #endif
  184. /** If this macro is set, the Juce String class will use unicode as its
  185. internal representation. If it isn't set, it'll use ANSI.
  186. */
  187. #ifndef JUCE_STRINGS_ARE_UNICODE
  188. #define JUCE_STRINGS_ARE_UNICODE 1
  189. #endif
  190. #endif
  191. /********* End of inlined file: juce_Config.h *********/
  192. //==============================================================================
  193. #ifdef _WIN32
  194. /********* Start of inlined file: juce_win32_NativeIncludes.h *********/
  195. #ifndef __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  196. #define __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  197. /********* Start of inlined file: juce_Config.h *********/
  198. #ifndef __JUCE_CONFIG_JUCEHEADER__
  199. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  200. /*
  201. This file contains macros that enable/disable various JUCE features.
  202. */
  203. /** The name of the namespace that all Juce classes and functions will be
  204. put inside. If this is not defined, no namespace will be used.
  205. */
  206. #ifndef JUCE_NAMESPACE
  207. #define JUCE_NAMESPACE juce
  208. #endif
  209. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  210. but if you define this value, you can override this can force it to be true or
  211. false.
  212. */
  213. #ifndef JUCE_FORCE_DEBUG
  214. //#define JUCE_FORCE_DEBUG 1
  215. #endif
  216. /** If this flag is enabled, the the jassert and jassertfalse macros will
  217. always use Logger::writeToLog() to write a message when an assertion happens.
  218. Enabling it will also leave this turned on in release builds. When it's disabled,
  219. however, the jassert and jassertfalse macros will not be compiled in a
  220. release build.
  221. @see jassert, jassertfalse, Logger
  222. */
  223. #ifndef JUCE_LOG_ASSERTIONS
  224. // #define JUCE_LOG_ASSERTIONS 1
  225. #endif
  226. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  227. which the ASIOAudioIODevice class can't be built. See the comments in the
  228. ASIOAudioIODevice class's header file for more info about this.
  229. (This only affects a Win32 build)
  230. */
  231. #ifndef JUCE_ASIO
  232. #define JUCE_ASIO 1
  233. #endif
  234. /** Comment out this macro to disable building of ALSA device support on Linux.
  235. */
  236. #ifndef JUCE_ALSA
  237. #define JUCE_ALSA 1
  238. #endif
  239. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  240. have the SDK installed.
  241. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  242. classes will be unavailable.
  243. On Windows, if you enable this, you'll need to have the QuickTime SDK
  244. installed, and its header files will need to be on your include path.
  245. */
  246. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  247. #define JUCE_QUICKTIME 1
  248. #endif
  249. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  250. have the appropriate headers and libraries available. If it's not enabled, the
  251. OpenGLComponent class will be unavailable.
  252. */
  253. #ifndef JUCE_OPENGL
  254. #define JUCE_OPENGL 1
  255. #endif
  256. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  257. If you're not going to need either of these formats, turn off the flags to
  258. avoid bloating your codebase with them.
  259. */
  260. #ifndef JUCE_USE_FLAC
  261. #define JUCE_USE_FLAC 1
  262. #endif
  263. #ifndef JUCE_USE_OGGVORBIS
  264. #define JUCE_USE_OGGVORBIS 1
  265. #endif
  266. /** This flag lets you enable support for CD-burning. You might want to disable
  267. it to build without the MS SDK under windows.
  268. */
  269. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  270. #define JUCE_USE_CDBURNER 1
  271. #endif
  272. /** Enabling this macro means that all regions that get repainted will have a coloured
  273. line drawn around them.
  274. This is handy if you're trying to optimise drawing, because it lets you easily see
  275. when anything is being repainted unnecessarily.
  276. */
  277. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  278. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  279. #endif
  280. /** Enable this under Linux to use Xinerama for multi-monitor support.
  281. */
  282. #ifndef JUCE_USE_XINERAMA
  283. #define JUCE_USE_XINERAMA 1
  284. #endif
  285. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  286. */
  287. #ifndef JUCE_USE_XSHM
  288. #define JUCE_USE_XSHM 1
  289. #endif
  290. /** Enabling this builds support for VST audio plugins.
  291. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  292. */
  293. #ifndef JUCE_PLUGINHOST_VST
  294. // #define JUCE_PLUGINHOST_VST 1
  295. #endif
  296. /** Enabling this builds support for AudioUnit audio plugins.
  297. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  298. */
  299. #ifndef JUCE_PLUGINHOST_AU
  300. // #define JUCE_PLUGINHOST_AU 1
  301. #endif
  302. /** Disabling this will avoid linking to any UI code. This is handy for
  303. writing command-line utilities, e.g. on linux boxes which don't have some
  304. of the UI libraries installed.
  305. (On mac and windows, this won't generally make much difference to the build).
  306. */
  307. #ifndef JUCE_BUILD_GUI_CLASSES
  308. #define JUCE_BUILD_GUI_CLASSES 1
  309. #endif
  310. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  311. */
  312. #ifndef JUCE_WEB_BROWSER
  313. #define JUCE_WEB_BROWSER 1
  314. #endif
  315. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  316. codebase - you might need to use this if you're linking to some of these libraries
  317. yourself.
  318. */
  319. #ifndef JUCE_INCLUDE_ZLIB_CODE
  320. #define JUCE_INCLUDE_ZLIB_CODE 1
  321. #endif
  322. #ifndef JUCE_INCLUDE_FLAC_CODE
  323. #define JUCE_INCLUDE_FLAC_CODE 1
  324. #endif
  325. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  326. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  327. #endif
  328. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  329. #define JUCE_INCLUDE_PNGLIB_CODE 1
  330. #endif
  331. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  332. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  333. #endif
  334. /** Enable this to add extra memory-leak info to the new and delete operators.
  335. (Currently, this only affects Windows builds in debug mode).
  336. */
  337. #ifndef JUCE_CHECK_MEMORY_LEAKS
  338. #define JUCE_CHECK_MEMORY_LEAKS 1
  339. #endif
  340. /** Enable this to turn on juce's internal catching of exceptions.
  341. Turning it off will avoid any exception catching. With it on, all exceptions
  342. are passed to the JUCEApplication::unhandledException() callback for logging.
  343. */
  344. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  345. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  346. #endif
  347. /** If this macro is set, the Juce String class will use unicode as its
  348. internal representation. If it isn't set, it'll use ANSI.
  349. */
  350. #ifndef JUCE_STRINGS_ARE_UNICODE
  351. #define JUCE_STRINGS_ARE_UNICODE 1
  352. #endif
  353. #endif
  354. /********* End of inlined file: juce_Config.h *********/
  355. #ifndef STRICT
  356. #define STRICT 1
  357. #endif
  358. #undef WIN32_LEAN_AND_MEAN
  359. #define WIN32_LEAN_AND_MEAN 1
  360. #ifdef _MSC_VER
  361. #pragma warning (push)
  362. #pragma warning (disable : 4100 4201 4514 4312)
  363. #endif
  364. #define _WIN32_WINNT 0x0500
  365. #define _UNICODE 1
  366. #define UNICODE 1
  367. #ifndef _WIN32_IE
  368. #define _WIN32_IE 0x0400
  369. #endif
  370. #include <windows.h>
  371. #include <windowsx.h>
  372. #include <commdlg.h>
  373. #include <shellapi.h>
  374. #include <mmsystem.h>
  375. #include <vfw.h>
  376. #include <tchar.h>
  377. #include <stddef.h>
  378. #include <ctime>
  379. #include <wininet.h>
  380. #include <nb30.h>
  381. #include <iphlpapi.h>
  382. #include <mapi.h>
  383. #include <float.h>
  384. #include <crtdbg.h>
  385. #include <process.h>
  386. #include <comutil.h>
  387. #include <Exdisp.h>
  388. #include <exdispid.h>
  389. #include <shlobj.h>
  390. #if JUCE_OPENGL
  391. #include <gl/gl.h>
  392. #endif
  393. #undef PACKED
  394. #if JUCE_ASIO
  395. /*
  396. This is very frustrating - we only need to use a handful of definitions from
  397. a couple of the header files in Steinberg's ASIO SDK, and it'd be easy to copy
  398. about 30 lines of code into this cpp file to create a fully stand-alone ASIO
  399. implementation...
  400. ..unfortunately that would break Steinberg's license agreement for use of
  401. their SDK, so I'm not allowed to do this.
  402. This means that anyone who wants to use JUCE's ASIO abilities will have to:
  403. 1) Agree to Steinberg's licensing terms and download the ASIO SDK
  404. (see www.steinberg.net/Steinberg/Developers.asp).
  405. 2) Rebuild the whole of JUCE, setting the global definition JUCE_ASIO (you
  406. can un-comment the "#define JUCE_ASIO" line in juce_Config.h
  407. if you prefer). Make sure that your header search path will find the
  408. iasiodrv.h file that comes with the SDK. (Only about 2-3 of the SDK header
  409. files are actually needed - so to simplify things, you could just copy
  410. these into your JUCE directory).
  411. If you're compiling and you get an error here because you don't have the
  412. ASIO SDK installed, you can disable ASIO support by commenting-out the
  413. "#define JUCE_ASIO" line in juce_Config.h, and rebuild your Juce library.
  414. */
  415. #include "iasiodrv.h"
  416. #endif
  417. #if JUCE_USE_CDBURNER
  418. /* You'll need the Platform SDK for these headers - if you don't have it and don't
  419. need to use CD-burning, then you might just want to disable the JUCE_USE_CDBURNER
  420. flag in juce_Config.h to avoid these includes.
  421. */
  422. #include <imapi.h>
  423. #include <imapierror.h>
  424. #endif
  425. #if JUCE_QUICKTIME
  426. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  427. add its header directory to your include path.
  428. Alternatively, if you don't need any QuickTime services, just turn off the JUCE_QUICKTIME
  429. flag in juce_Config.h
  430. */
  431. #include <Movies.h>
  432. #include <QTML.h>
  433. #include <QuickTimeComponents.h>
  434. #include <MediaHandlers.h>
  435. #include <ImageCodec.h>
  436. /* If you've got QuickTime 7 installed, then these COM objects should be found in
  437. the "\Program Files\Quicktime" directory. You'll need to add this directory to
  438. your include search path to make these import statements work.
  439. */
  440. #import <QTOLibrary.dll>
  441. #import <QTOControl.dll>
  442. #endif
  443. #ifdef _MSC_VER
  444. #pragma warning (pop)
  445. #endif
  446. #endif // __JUCE_WIN32_NATIVEINCLUDES_JUCEHEADER__
  447. /********* End of inlined file: juce_win32_NativeIncludes.h *********/
  448. #elif defined (LINUX)
  449. //
  450. #else
  451. /********* Start of inlined file: juce_mac_NativeIncludes.h *********/
  452. #ifndef __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  453. #define __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  454. /*
  455. This file wraps together all the mac-specific code, so that
  456. we can include all the native headers just once, and compile all our
  457. platform-specific stuff in one big lump, keeping it out of the way of
  458. the rest of the codebase.
  459. */
  460. #import <Cocoa/Cocoa.h>
  461. #import <CoreAudio/HostTime.h>
  462. #import <CoreAudio/AudioHardware.h>
  463. #import <CoreMIDI/MIDIServices.h>
  464. #import <QTKit/QTKit.h>
  465. #import <WebKit/WebKit.h>
  466. #import <DiscRecording/DiscRecording.h>
  467. #import <ApplicationServices/ApplicationServices.h>
  468. #import <IOKit/IOKitLib.h>
  469. #import <IOKit/IOCFPlugIn.h>
  470. #import <IOKit/hid/IOHIDLib.h>
  471. #import <IOKit/hid/IOHIDKeys.h>
  472. #import <IOKit/network/IOEthernetInterface.h>
  473. #import <IOKit/network/IONetworkInterface.h>
  474. #import <IOKit/network/IOEthernetController.h>
  475. #import <IOKit/pwr_mgt/IOPMLib.h>
  476. #include <sys/sysctl.h>
  477. #include <sys/stat.h>
  478. #include <sys/dir.h>
  479. #include <sys/param.h>
  480. #include <sys/mount.h>
  481. #include <fnmatch.h>
  482. #include <utime.h>
  483. #if MACOS_10_4_OR_EARLIER
  484. #include <GLUT/glut.h>
  485. #endif
  486. #endif // __JUCE_MAC_NATIVEINCLUDES_JUCEHEADER__
  487. /********* End of inlined file: juce_mac_NativeIncludes.h *********/
  488. #endif
  489. //==============================================================================
  490. #define DONT_SET_USING_JUCE_NAMESPACE 1
  491. #include "juce_amalgamated.h"
  492. #define NO_DUMMY_DECL
  493. #if (defined(_MSC_VER) && (_MSC_VER <= 1200))
  494. #pragma warning (disable: 4309 4305)
  495. #endif
  496. //==============================================================================
  497. /********* Start of inlined file: juce_FileLogger.cpp *********/
  498. BEGIN_JUCE_NAMESPACE
  499. FileLogger::FileLogger (const File& logFile_,
  500. const String& welcomeMessage,
  501. const int maxInitialFileSizeBytes)
  502. : logFile (logFile_)
  503. {
  504. if (maxInitialFileSizeBytes >= 0)
  505. trimFileSize (maxInitialFileSizeBytes);
  506. if (! logFile_.exists())
  507. {
  508. // do this so that the parent directories get created..
  509. logFile_.create();
  510. }
  511. logStream = logFile_.createOutputStream (256);
  512. jassert (logStream != 0);
  513. String welcome;
  514. welcome << "\r\n**********************************************************\r\n"
  515. << welcomeMessage
  516. << "\r\nLog started: " << Time::getCurrentTime().toString (true, true)
  517. << "\r\n";
  518. logMessage (welcome);
  519. }
  520. FileLogger::~FileLogger()
  521. {
  522. deleteAndZero (logStream);
  523. }
  524. void FileLogger::logMessage (const String& message)
  525. {
  526. if (logStream != 0)
  527. {
  528. Logger::outputDebugString (message);
  529. const ScopedLock sl (logLock);
  530. (*logStream) << message << T("\r\n");
  531. logStream->flush();
  532. }
  533. }
  534. void FileLogger::trimFileSize (int maxFileSizeBytes) const
  535. {
  536. if (maxFileSizeBytes <= 0)
  537. {
  538. logFile.deleteFile();
  539. }
  540. else
  541. {
  542. const int64 fileSize = logFile.getSize();
  543. if (fileSize > maxFileSizeBytes)
  544. {
  545. FileInputStream* const in = logFile.createInputStream();
  546. jassert (in != 0);
  547. if (in != 0)
  548. {
  549. in->setPosition (fileSize - maxFileSizeBytes);
  550. String content;
  551. {
  552. MemoryBlock contentToSave;
  553. contentToSave.setSize (maxFileSizeBytes + 4);
  554. contentToSave.fillWith (0);
  555. in->read (contentToSave.getData(), maxFileSizeBytes);
  556. delete in;
  557. content = contentToSave.toString();
  558. }
  559. int newStart = 0;
  560. while (newStart < fileSize
  561. && content[newStart] != '\n'
  562. && content[newStart] != '\r')
  563. ++newStart;
  564. logFile.deleteFile();
  565. logFile.appendText (content.substring (newStart), false, false);
  566. }
  567. }
  568. }
  569. }
  570. FileLogger* FileLogger::createDefaultAppLogger (const String& logFileSubDirectoryName,
  571. const String& logFileName,
  572. const String& welcomeMessage,
  573. const int maxInitialFileSizeBytes)
  574. {
  575. #if JUCE_MAC
  576. File logFile ("~/Library/Logs");
  577. logFile = logFile.getChildFile (logFileName);
  578. #else
  579. File logFile (File::getSpecialLocation (File::userApplicationDataDirectory));
  580. if (logFile.isDirectory())
  581. {
  582. logFile = logFile.getChildFile (logFileSubDirectoryName)
  583. .getChildFile (logFileName);
  584. }
  585. #endif
  586. return new FileLogger (logFile, welcomeMessage, maxInitialFileSizeBytes);
  587. }
  588. END_JUCE_NAMESPACE
  589. /********* End of inlined file: juce_FileLogger.cpp *********/
  590. /********* Start of inlined file: juce_Logger.cpp *********/
  591. BEGIN_JUCE_NAMESPACE
  592. Logger::Logger()
  593. {
  594. }
  595. Logger::~Logger()
  596. {
  597. }
  598. static Logger* currentLogger = 0;
  599. void Logger::setCurrentLogger (Logger* const newLogger,
  600. const bool deleteOldLogger)
  601. {
  602. Logger* const oldLogger = currentLogger;
  603. currentLogger = newLogger;
  604. if (deleteOldLogger && (oldLogger != 0))
  605. delete oldLogger;
  606. }
  607. void Logger::writeToLog (const String& message)
  608. {
  609. if (currentLogger != 0)
  610. currentLogger->logMessage (message);
  611. else
  612. outputDebugString (message);
  613. }
  614. #if JUCE_LOG_ASSERTIONS
  615. void JUCE_API juce_LogAssertion (const char* filename, const int lineNum) throw()
  616. {
  617. String m ("JUCE Assertion failure in ");
  618. m << filename << ", line " << lineNum;
  619. Logger::writeToLog (m);
  620. }
  621. #endif
  622. END_JUCE_NAMESPACE
  623. /********* End of inlined file: juce_Logger.cpp *********/
  624. /********* Start of inlined file: juce_Random.cpp *********/
  625. BEGIN_JUCE_NAMESPACE
  626. Random::Random (const int64 seedValue) throw()
  627. : seed (seedValue)
  628. {
  629. }
  630. Random::~Random() throw()
  631. {
  632. }
  633. void Random::setSeed (const int64 newSeed) throw()
  634. {
  635. seed = newSeed;
  636. }
  637. int Random::nextInt() throw()
  638. {
  639. seed = (seed * literal64bit (0x5deece66d) + 11) & literal64bit (0xffffffffffff);
  640. return (int) (seed >> 16);
  641. }
  642. int Random::nextInt (const int maxValue) throw()
  643. {
  644. jassert (maxValue > 0);
  645. return (nextInt() & 0x7fffffff) % maxValue;
  646. }
  647. int64 Random::nextInt64() throw()
  648. {
  649. return (((int64) nextInt()) << 32) | (int64) (uint64) (uint32) nextInt();
  650. }
  651. bool Random::nextBool() throw()
  652. {
  653. return (nextInt() & 0x80000000) != 0;
  654. }
  655. float Random::nextFloat() throw()
  656. {
  657. return ((uint32) nextInt()) / (float) 0xffffffff;
  658. }
  659. double Random::nextDouble() throw()
  660. {
  661. return ((uint32) nextInt()) / (double) 0xffffffff;
  662. }
  663. static Random sysRand (1);
  664. Random& Random::getSystemRandom() throw()
  665. {
  666. return sysRand;
  667. }
  668. END_JUCE_NAMESPACE
  669. /********* End of inlined file: juce_Random.cpp *********/
  670. /********* Start of inlined file: juce_RelativeTime.cpp *********/
  671. BEGIN_JUCE_NAMESPACE
  672. RelativeTime::RelativeTime (const double seconds_) throw()
  673. : seconds (seconds_)
  674. {
  675. }
  676. RelativeTime::RelativeTime (const RelativeTime& other) throw()
  677. : seconds (other.seconds)
  678. {
  679. }
  680. RelativeTime::~RelativeTime() throw()
  681. {
  682. }
  683. const RelativeTime RelativeTime::milliseconds (const int milliseconds) throw()
  684. {
  685. return RelativeTime (milliseconds * 0.001);
  686. }
  687. const RelativeTime RelativeTime::milliseconds (const int64 milliseconds) throw()
  688. {
  689. return RelativeTime (milliseconds * 0.001);
  690. }
  691. const RelativeTime RelativeTime::minutes (const double numberOfMinutes) throw()
  692. {
  693. return RelativeTime (numberOfMinutes * 60.0);
  694. }
  695. const RelativeTime RelativeTime::hours (const double numberOfHours) throw()
  696. {
  697. return RelativeTime (numberOfHours * (60.0 * 60.0));
  698. }
  699. const RelativeTime RelativeTime::days (const double numberOfDays) throw()
  700. {
  701. return RelativeTime (numberOfDays * (60.0 * 60.0 * 24.0));
  702. }
  703. const RelativeTime RelativeTime::weeks (const double numberOfWeeks) throw()
  704. {
  705. return RelativeTime (numberOfWeeks * (60.0 * 60.0 * 24.0 * 7.0));
  706. }
  707. int64 RelativeTime::inMilliseconds() const throw()
  708. {
  709. return (int64)(seconds * 1000.0);
  710. }
  711. double RelativeTime::inMinutes() const throw()
  712. {
  713. return seconds / 60.0;
  714. }
  715. double RelativeTime::inHours() const throw()
  716. {
  717. return seconds / (60.0 * 60.0);
  718. }
  719. double RelativeTime::inDays() const throw()
  720. {
  721. return seconds / (60.0 * 60.0 * 24.0);
  722. }
  723. double RelativeTime::inWeeks() const throw()
  724. {
  725. return seconds / (60.0 * 60.0 * 24.0 * 7.0);
  726. }
  727. const String RelativeTime::getDescription (const String& returnValueForZeroTime) const throw()
  728. {
  729. if (seconds < 0.001 && seconds > -0.001)
  730. return returnValueForZeroTime;
  731. String result;
  732. if (seconds < 0)
  733. result = T("-");
  734. int fieldsShown = 0;
  735. int n = abs ((int) inWeeks());
  736. if (n > 0)
  737. {
  738. result << n << ((n == 1) ? TRANS(" week ")
  739. : TRANS(" weeks "));
  740. ++fieldsShown;
  741. }
  742. n = abs ((int) inDays()) % 7;
  743. if (n > 0)
  744. {
  745. result << n << ((n == 1) ? TRANS(" day ")
  746. : TRANS(" days "));
  747. ++fieldsShown;
  748. }
  749. if (fieldsShown < 2)
  750. {
  751. n = abs ((int) inHours()) % 24;
  752. if (n > 0)
  753. {
  754. result << n << ((n == 1) ? TRANS(" hr ")
  755. : TRANS(" hrs "));
  756. ++fieldsShown;
  757. }
  758. if (fieldsShown < 2)
  759. {
  760. n = abs ((int) inMinutes()) % 60;
  761. if (n > 0)
  762. {
  763. result << n << ((n == 1) ? TRANS(" min ")
  764. : TRANS(" mins "));
  765. ++fieldsShown;
  766. }
  767. if (fieldsShown < 2)
  768. {
  769. n = abs ((int) inSeconds()) % 60;
  770. if (n > 0)
  771. {
  772. result << n << ((n == 1) ? TRANS(" sec ")
  773. : TRANS(" secs "));
  774. ++fieldsShown;
  775. }
  776. if (fieldsShown < 1)
  777. {
  778. n = abs ((int) inMilliseconds()) % 1000;
  779. if (n > 0)
  780. {
  781. result << n << TRANS(" ms");
  782. ++fieldsShown;
  783. }
  784. }
  785. }
  786. }
  787. }
  788. return result.trimEnd();
  789. }
  790. const RelativeTime& RelativeTime::operator= (const RelativeTime& other) throw()
  791. {
  792. seconds = other.seconds;
  793. return *this;
  794. }
  795. bool RelativeTime::operator== (const RelativeTime& other) const throw()
  796. {
  797. return seconds == other.seconds;
  798. }
  799. bool RelativeTime::operator!= (const RelativeTime& other) const throw()
  800. {
  801. return seconds != other.seconds;
  802. }
  803. bool RelativeTime::operator> (const RelativeTime& other) const throw()
  804. {
  805. return seconds > other.seconds;
  806. }
  807. bool RelativeTime::operator< (const RelativeTime& other) const throw()
  808. {
  809. return seconds < other.seconds;
  810. }
  811. bool RelativeTime::operator>= (const RelativeTime& other) const throw()
  812. {
  813. return seconds >= other.seconds;
  814. }
  815. bool RelativeTime::operator<= (const RelativeTime& other) const throw()
  816. {
  817. return seconds <= other.seconds;
  818. }
  819. const RelativeTime RelativeTime::operator+ (const RelativeTime& timeToAdd) const throw()
  820. {
  821. return RelativeTime (seconds + timeToAdd.seconds);
  822. }
  823. const RelativeTime RelativeTime::operator- (const RelativeTime& timeToSubtract) const throw()
  824. {
  825. return RelativeTime (seconds - timeToSubtract.seconds);
  826. }
  827. const RelativeTime RelativeTime::operator+ (const double secondsToAdd) const throw()
  828. {
  829. return RelativeTime (seconds + secondsToAdd);
  830. }
  831. const RelativeTime RelativeTime::operator- (const double secondsToSubtract) const throw()
  832. {
  833. return RelativeTime (seconds - secondsToSubtract);
  834. }
  835. const RelativeTime& RelativeTime::operator+= (const RelativeTime& timeToAdd) throw()
  836. {
  837. seconds += timeToAdd.seconds;
  838. return *this;
  839. }
  840. const RelativeTime& RelativeTime::operator-= (const RelativeTime& timeToSubtract) throw()
  841. {
  842. seconds -= timeToSubtract.seconds;
  843. return *this;
  844. }
  845. const RelativeTime& RelativeTime::operator+= (const double secondsToAdd) throw()
  846. {
  847. seconds += secondsToAdd;
  848. return *this;
  849. }
  850. const RelativeTime& RelativeTime::operator-= (const double secondsToSubtract) throw()
  851. {
  852. seconds -= secondsToSubtract;
  853. return *this;
  854. }
  855. END_JUCE_NAMESPACE
  856. /********* End of inlined file: juce_RelativeTime.cpp *********/
  857. /********* Start of inlined file: juce_SystemStats.cpp *********/
  858. BEGIN_JUCE_NAMESPACE
  859. void juce_initialiseStrings();
  860. const String SystemStats::getJUCEVersion() throw()
  861. {
  862. return "JUCE v" + String (JUCE_MAJOR_VERSION) + "." + String (JUCE_MINOR_VERSION);
  863. }
  864. static bool juceInitialisedNonGUI = false;
  865. void JUCE_PUBLIC_FUNCTION initialiseJuce_NonGUI()
  866. {
  867. if (! juceInitialisedNonGUI)
  868. {
  869. #if JUCE_MAC
  870. const ScopedAutoReleasePool pool;
  871. #endif
  872. #ifdef JUCE_DEBUG
  873. // Some simple test code to keep an eye on things and make sure these functions
  874. // work ok on all platforms. Let me know if any of these assertions fail!
  875. int n = 1;
  876. atomicIncrement (n);
  877. jassert (atomicIncrementAndReturn (n) == 3);
  878. atomicDecrement (n);
  879. jassert (atomicDecrementAndReturn (n) == 1);
  880. jassert (swapByteOrder ((uint32) 0x11223344) == 0x44332211);
  881. // quick test to make sure the run-time lib doesn't crash on freeing a null-pointer.
  882. SystemStats* nullPointer = 0;
  883. juce_free (nullPointer);
  884. delete[] nullPointer;
  885. delete nullPointer;
  886. #endif
  887. // Now the real initialisation..
  888. juceInitialisedNonGUI = true;
  889. DBG (SystemStats::getJUCEVersion());
  890. juce_initialiseStrings();
  891. SystemStats::initialiseStats();
  892. Random::getSystemRandom().setSeed (Time::currentTimeMillis());
  893. }
  894. }
  895. #if JUCE_WIN32
  896. // This is imported from the sockets code..
  897. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  898. extern juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib;
  899. #endif
  900. #if JUCE_DEBUG
  901. extern void juce_CheckForDanglingStreams();
  902. #endif
  903. void JUCE_PUBLIC_FUNCTION shutdownJuce_NonGUI()
  904. {
  905. if (juceInitialisedNonGUI)
  906. {
  907. #if JUCE_MAC
  908. const ScopedAutoReleasePool pool;
  909. #endif
  910. #if JUCE_WIN32
  911. // need to shut down sockets if they were used..
  912. if (juce_CloseWin32SocketLib != 0)
  913. (*juce_CloseWin32SocketLib)();
  914. #endif
  915. LocalisedStrings::setCurrentMappings (0);
  916. Thread::stopAllThreads (3000);
  917. #if JUCE_DEBUG
  918. juce_CheckForDanglingStreams();
  919. #endif
  920. juceInitialisedNonGUI = false;
  921. }
  922. }
  923. #ifdef JUCE_DLL
  924. void* juce_Malloc (const int size)
  925. {
  926. return malloc (size);
  927. }
  928. void* juce_Calloc (const int size)
  929. {
  930. return calloc (1, size);
  931. }
  932. void* juce_Realloc (void* const block, const int size)
  933. {
  934. return realloc (block, size);
  935. }
  936. void juce_Free (void* const block)
  937. {
  938. free (block);
  939. }
  940. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  941. void* juce_DebugMalloc (const int size, const char* file, const int line)
  942. {
  943. return _malloc_dbg (size, _NORMAL_BLOCK, file, line);
  944. }
  945. void* juce_DebugCalloc (const int size, const char* file, const int line)
  946. {
  947. return _calloc_dbg (1, size, _NORMAL_BLOCK, file, line);
  948. }
  949. void* juce_DebugRealloc (void* const block, const int size, const char* file, const int line)
  950. {
  951. return _realloc_dbg (block, size, _NORMAL_BLOCK, file, line);
  952. }
  953. void juce_DebugFree (void* const block)
  954. {
  955. _free_dbg (block, _NORMAL_BLOCK);
  956. }
  957. #endif
  958. #endif
  959. END_JUCE_NAMESPACE
  960. /********* End of inlined file: juce_SystemStats.cpp *********/
  961. /********* Start of inlined file: juce_Time.cpp *********/
  962. #ifdef _MSC_VER
  963. #pragma warning (disable: 4514)
  964. #pragma warning (push)
  965. #endif
  966. #ifndef JUCE_WIN32
  967. #include <sys/time.h>
  968. #else
  969. #include <ctime>
  970. #endif
  971. #include <sys/timeb.h>
  972. BEGIN_JUCE_NAMESPACE
  973. #ifdef _MSC_VER
  974. #pragma warning (pop)
  975. #ifdef _INC_TIME_INL
  976. #define USE_NEW_SECURE_TIME_FNS
  977. #endif
  978. #endif
  979. static void millisToLocal (const int64 millis, struct tm& result) throw()
  980. {
  981. const int64 seconds = millis / 1000;
  982. if (seconds < literal64bit (86400) || seconds >= literal64bit (2145916800))
  983. {
  984. // use extended maths for dates beyond 1970 to 2037..
  985. const int timeZoneAdjustment = 31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000);
  986. const int64 jdm = seconds + timeZoneAdjustment + literal64bit (210866803200);
  987. const int days = (int) (jdm / literal64bit (86400));
  988. const int a = 32044 + days;
  989. const int b = (4 * a + 3) / 146097;
  990. const int c = a - (b * 146097) / 4;
  991. const int d = (4 * c + 3) / 1461;
  992. const int e = c - (d * 1461) / 4;
  993. const int m = (5 * e + 2) / 153;
  994. result.tm_mday = e - (153 * m + 2) / 5 + 1;
  995. result.tm_mon = m + 2 - 12 * (m / 10);
  996. result.tm_year = b * 100 + d - 6700 + (m / 10);
  997. result.tm_wday = (days + 1) % 7;
  998. result.tm_yday = -1;
  999. int t = (int) (jdm % literal64bit (86400));
  1000. result.tm_hour = t / 3600;
  1001. t %= 3600;
  1002. result.tm_min = t / 60;
  1003. result.tm_sec = t % 60;
  1004. result.tm_isdst = -1;
  1005. }
  1006. else
  1007. {
  1008. time_t now = (time_t) (seconds);
  1009. #if JUCE_WIN32
  1010. #ifdef USE_NEW_SECURE_TIME_FNS
  1011. if (now >= 0 && now <= 0x793406fff)
  1012. localtime_s (&result, &now);
  1013. else
  1014. zeromem (&result, sizeof (result));
  1015. #else
  1016. result = *localtime (&now);
  1017. #endif
  1018. #else
  1019. // more thread-safe
  1020. localtime_r (&now, &result);
  1021. #endif
  1022. }
  1023. }
  1024. Time::Time() throw()
  1025. : millisSinceEpoch (0)
  1026. {
  1027. }
  1028. Time::Time (const Time& other) throw()
  1029. : millisSinceEpoch (other.millisSinceEpoch)
  1030. {
  1031. }
  1032. Time::Time (const int64 ms) throw()
  1033. : millisSinceEpoch (ms)
  1034. {
  1035. }
  1036. Time::Time (const int year,
  1037. const int month,
  1038. const int day,
  1039. const int hours,
  1040. const int minutes,
  1041. const int seconds,
  1042. const int milliseconds,
  1043. const bool useLocalTime) throw()
  1044. {
  1045. jassert (year > 100); // year must be a 4-digit version
  1046. if (year < 1971 || year >= 2038 || ! useLocalTime)
  1047. {
  1048. // use extended maths for dates beyond 1970 to 2037..
  1049. const int timeZoneAdjustment = useLocalTime ? (31536000 - (int) (Time (1971, 0, 1, 0, 0).toMilliseconds() / 1000))
  1050. : 0;
  1051. const int a = (13 - month) / 12;
  1052. const int y = year + 4800 - a;
  1053. const int jd = day + (153 * (month + 12 * a - 2) + 2) / 5
  1054. + (y * 365) + (y / 4) - (y / 100) + (y / 400)
  1055. - 32045;
  1056. const int64 s = ((int64) jd) * literal64bit (86400) - literal64bit (210866803200);
  1057. millisSinceEpoch = 1000 * (s + (hours * 3600 + minutes * 60 + seconds - timeZoneAdjustment))
  1058. + milliseconds;
  1059. }
  1060. else
  1061. {
  1062. struct tm t;
  1063. t.tm_year = year - 1900;
  1064. t.tm_mon = month;
  1065. t.tm_mday = day;
  1066. t.tm_hour = hours;
  1067. t.tm_min = minutes;
  1068. t.tm_sec = seconds;
  1069. t.tm_isdst = -1;
  1070. millisSinceEpoch = 1000 * (int64) mktime (&t);
  1071. if (millisSinceEpoch < 0)
  1072. millisSinceEpoch = 0;
  1073. else
  1074. millisSinceEpoch += milliseconds;
  1075. }
  1076. }
  1077. Time::~Time() throw()
  1078. {
  1079. }
  1080. const Time& Time::operator= (const Time& other) throw()
  1081. {
  1082. millisSinceEpoch = other.millisSinceEpoch;
  1083. return *this;
  1084. }
  1085. int64 Time::currentTimeMillis() throw()
  1086. {
  1087. static uint32 lastCounterResult = 0xffffffff;
  1088. static int64 correction = 0;
  1089. const uint32 now = getMillisecondCounter();
  1090. // check the counter hasn't wrapped (also triggered the first time this function is called)
  1091. if (now < lastCounterResult)
  1092. {
  1093. // double-check it's actually wrapped, in case multi-cpu machines have timers that drift a bit.
  1094. if (lastCounterResult == 0xffffffff || now < lastCounterResult - 10)
  1095. {
  1096. // get the time once using normal library calls, and store the difference needed to
  1097. // turn the millisecond counter into a real time.
  1098. #if JUCE_WIN32
  1099. struct _timeb t;
  1100. #ifdef USE_NEW_SECURE_TIME_FNS
  1101. _ftime_s (&t);
  1102. #else
  1103. _ftime (&t);
  1104. #endif
  1105. correction = (((int64) t.time) * 1000 + t.millitm) - now;
  1106. #else
  1107. struct timeval tv;
  1108. struct timezone tz;
  1109. gettimeofday (&tv, &tz);
  1110. correction = (((int64) tv.tv_sec) * 1000 + tv.tv_usec / 1000) - now;
  1111. #endif
  1112. }
  1113. }
  1114. lastCounterResult = now;
  1115. return correction + now;
  1116. }
  1117. uint32 juce_millisecondsSinceStartup() throw();
  1118. static uint32 lastMSCounterValue = 0;
  1119. uint32 Time::getMillisecondCounter() throw()
  1120. {
  1121. const uint32 now = juce_millisecondsSinceStartup();
  1122. if (now < lastMSCounterValue)
  1123. {
  1124. // in multi-threaded apps this might be called concurrently, so
  1125. // make sure that our last counter value only increases and doesn't
  1126. // go backwards..
  1127. if (now < lastMSCounterValue - 1000)
  1128. lastMSCounterValue = now;
  1129. }
  1130. else
  1131. {
  1132. lastMSCounterValue = now;
  1133. }
  1134. return now;
  1135. }
  1136. uint32 Time::getApproximateMillisecondCounter() throw()
  1137. {
  1138. jassert (lastMSCounterValue != 0);
  1139. return lastMSCounterValue;
  1140. }
  1141. void Time::waitForMillisecondCounter (const uint32 targetTime) throw()
  1142. {
  1143. for (;;)
  1144. {
  1145. const uint32 now = getMillisecondCounter();
  1146. if (now >= targetTime)
  1147. break;
  1148. const int toWait = targetTime - now;
  1149. if (toWait > 2)
  1150. {
  1151. Thread::sleep (jmin (20, toWait >> 1));
  1152. }
  1153. else
  1154. {
  1155. // xxx should consider using mutex_pause on the mac as it apparently
  1156. // makes it seem less like a spinlock and avoids lowering the thread pri.
  1157. for (int i = 10; --i >= 0;)
  1158. Thread::yield();
  1159. }
  1160. }
  1161. }
  1162. double Time::highResolutionTicksToSeconds (const int64 ticks) throw()
  1163. {
  1164. return ticks / (double) getHighResolutionTicksPerSecond();
  1165. }
  1166. int64 Time::secondsToHighResolutionTicks (const double seconds) throw()
  1167. {
  1168. return (int64) (seconds * (double) getHighResolutionTicksPerSecond());
  1169. }
  1170. const Time JUCE_CALLTYPE Time::getCurrentTime() throw()
  1171. {
  1172. return Time (currentTimeMillis());
  1173. }
  1174. const String Time::toString (const bool includeDate,
  1175. const bool includeTime,
  1176. const bool includeSeconds,
  1177. const bool use24HourClock) const throw()
  1178. {
  1179. String result;
  1180. if (includeDate)
  1181. {
  1182. result << getDayOfMonth() << ' '
  1183. << getMonthName (true) << ' '
  1184. << getYear();
  1185. if (includeTime)
  1186. result << ' ';
  1187. }
  1188. if (includeTime)
  1189. {
  1190. if (includeSeconds)
  1191. {
  1192. result += String::formatted (T("%d:%02d:%02d "),
  1193. (use24HourClock) ? getHours()
  1194. : getHoursInAmPmFormat(),
  1195. getMinutes(),
  1196. getSeconds());
  1197. }
  1198. else
  1199. {
  1200. result += String::formatted (T("%d.%02d"),
  1201. (use24HourClock) ? getHours()
  1202. : getHoursInAmPmFormat(),
  1203. getMinutes());
  1204. }
  1205. if (! use24HourClock)
  1206. result << (isAfternoon() ? "pm" : "am");
  1207. }
  1208. return result.trimEnd();
  1209. }
  1210. const String Time::formatted (const tchar* const format) const throw()
  1211. {
  1212. tchar buffer[80];
  1213. struct tm t;
  1214. millisToLocal (millisSinceEpoch, t);
  1215. if (CharacterFunctions::ftime (buffer, 79, format, &t) <= 0)
  1216. {
  1217. int bufferSize = 128;
  1218. for (;;)
  1219. {
  1220. MemoryBlock mb (bufferSize * sizeof (tchar));
  1221. tchar* const b = (tchar*) mb.getData();
  1222. if (CharacterFunctions::ftime (b, bufferSize, format, &t) > 0)
  1223. return String (b);
  1224. bufferSize += 128;
  1225. }
  1226. }
  1227. return String (buffer);
  1228. }
  1229. int Time::getYear() const throw()
  1230. {
  1231. struct tm t;
  1232. millisToLocal (millisSinceEpoch, t);
  1233. return t.tm_year + 1900;
  1234. }
  1235. int Time::getMonth() const throw()
  1236. {
  1237. struct tm t;
  1238. millisToLocal (millisSinceEpoch, t);
  1239. return t.tm_mon;
  1240. }
  1241. int Time::getDayOfMonth() const throw()
  1242. {
  1243. struct tm t;
  1244. millisToLocal (millisSinceEpoch, t);
  1245. return t.tm_mday;
  1246. }
  1247. int Time::getDayOfWeek() const throw()
  1248. {
  1249. struct tm t;
  1250. millisToLocal (millisSinceEpoch, t);
  1251. return t.tm_wday;
  1252. }
  1253. int Time::getHours() const throw()
  1254. {
  1255. struct tm t;
  1256. millisToLocal (millisSinceEpoch, t);
  1257. return t.tm_hour;
  1258. }
  1259. int Time::getHoursInAmPmFormat() const throw()
  1260. {
  1261. const int hours = getHours();
  1262. if (hours == 0)
  1263. return 12;
  1264. else if (hours <= 12)
  1265. return hours;
  1266. else
  1267. return hours - 12;
  1268. }
  1269. bool Time::isAfternoon() const throw()
  1270. {
  1271. return getHours() >= 12;
  1272. }
  1273. static int extendedModulo (const int64 value, const int modulo) throw()
  1274. {
  1275. return (int) (value >= 0 ? (value % modulo)
  1276. : (value - ((value / modulo) + 1) * modulo));
  1277. }
  1278. int Time::getMinutes() const throw()
  1279. {
  1280. struct tm t;
  1281. millisToLocal (millisSinceEpoch, t);
  1282. return t.tm_min;
  1283. }
  1284. int Time::getSeconds() const throw()
  1285. {
  1286. return extendedModulo (millisSinceEpoch / 1000, 60);
  1287. }
  1288. int Time::getMilliseconds() const throw()
  1289. {
  1290. return extendedModulo (millisSinceEpoch, 1000);
  1291. }
  1292. bool Time::isDaylightSavingTime() const throw()
  1293. {
  1294. struct tm t;
  1295. millisToLocal (millisSinceEpoch, t);
  1296. return t.tm_isdst != 0;
  1297. }
  1298. const String Time::getTimeZone() const throw()
  1299. {
  1300. String zone[2];
  1301. #if JUCE_WIN32
  1302. _tzset();
  1303. #ifdef USE_NEW_SECURE_TIME_FNS
  1304. {
  1305. char name [128];
  1306. size_t length;
  1307. for (int i = 0; i < 2; ++i)
  1308. {
  1309. zeromem (name, sizeof (name));
  1310. _get_tzname (&length, name, 127, i);
  1311. zone[i] = name;
  1312. }
  1313. }
  1314. #else
  1315. const char** const zonePtr = (const char**) _tzname;
  1316. zone[0] = zonePtr[0];
  1317. zone[1] = zonePtr[1];
  1318. #endif
  1319. #else
  1320. tzset();
  1321. const char** const zonePtr = (const char**) tzname;
  1322. zone[0] = zonePtr[0];
  1323. zone[1] = zonePtr[1];
  1324. #endif
  1325. if (isDaylightSavingTime())
  1326. {
  1327. zone[0] = zone[1];
  1328. if (zone[0].length() > 3
  1329. && zone[0].containsIgnoreCase (T("daylight"))
  1330. && zone[0].contains (T("GMT")))
  1331. zone[0] = "BST";
  1332. }
  1333. return zone[0].substring (0, 3);
  1334. }
  1335. const String Time::getMonthName (const bool threeLetterVersion) const throw()
  1336. {
  1337. return getMonthName (getMonth(), threeLetterVersion);
  1338. }
  1339. const String Time::getWeekdayName (const bool threeLetterVersion) const throw()
  1340. {
  1341. return getWeekdayName (getDayOfWeek(), threeLetterVersion);
  1342. }
  1343. const String Time::getMonthName (int monthNumber,
  1344. const bool threeLetterVersion) throw()
  1345. {
  1346. const char* const shortMonthNames[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
  1347. const char* const longMonthNames[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
  1348. monthNumber %= 12;
  1349. return TRANS (threeLetterVersion ? shortMonthNames [monthNumber]
  1350. : longMonthNames [monthNumber]);
  1351. }
  1352. const String Time::getWeekdayName (int day,
  1353. const bool threeLetterVersion) throw()
  1354. {
  1355. const char* const shortDayNames[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
  1356. const char* const longDayNames[] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };
  1357. day %= 7;
  1358. return TRANS (threeLetterVersion ? shortDayNames [day]
  1359. : longDayNames [day]);
  1360. }
  1361. END_JUCE_NAMESPACE
  1362. /********* End of inlined file: juce_Time.cpp *********/
  1363. /********* Start of inlined file: juce_BitArray.cpp *********/
  1364. BEGIN_JUCE_NAMESPACE
  1365. BitArray::BitArray() throw()
  1366. : numValues (4),
  1367. highestBit (-1),
  1368. negative (false)
  1369. {
  1370. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1371. }
  1372. BitArray::BitArray (const int value) throw()
  1373. : numValues (4),
  1374. highestBit (31),
  1375. negative (value < 0)
  1376. {
  1377. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1378. values[0] = abs (value);
  1379. highestBit = getHighestBit();
  1380. }
  1381. BitArray::BitArray (int64 value) throw()
  1382. : numValues (4),
  1383. highestBit (63),
  1384. negative (value < 0)
  1385. {
  1386. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1387. if (value < 0)
  1388. value = -value;
  1389. values[0] = (unsigned int) value;
  1390. values[1] = (unsigned int) (value >> 32);
  1391. highestBit = getHighestBit();
  1392. }
  1393. BitArray::BitArray (const unsigned int value) throw()
  1394. : numValues (4),
  1395. highestBit (31),
  1396. negative (false)
  1397. {
  1398. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1399. values[0] = value;
  1400. highestBit = getHighestBit();
  1401. }
  1402. BitArray::BitArray (const BitArray& other) throw()
  1403. : numValues (jmax (4, (other.highestBit >> 5) + 1)),
  1404. highestBit (other.getHighestBit()),
  1405. negative (other.negative)
  1406. {
  1407. const int bytes = sizeof (unsigned int) * (numValues + 1);
  1408. values = (unsigned int*) juce_malloc (bytes);
  1409. memcpy (values, other.values, bytes);
  1410. }
  1411. BitArray::~BitArray() throw()
  1412. {
  1413. juce_free (values);
  1414. }
  1415. const BitArray& BitArray::operator= (const BitArray& other) throw()
  1416. {
  1417. if (this != &other)
  1418. {
  1419. juce_free (values);
  1420. highestBit = other.getHighestBit();
  1421. numValues = jmax (4, (highestBit >> 5) + 1);
  1422. negative = other.negative;
  1423. const int memSize = sizeof (unsigned int) * (numValues + 1);
  1424. values = (unsigned int*)juce_malloc (memSize);
  1425. memcpy (values, other.values, memSize);
  1426. }
  1427. return *this;
  1428. }
  1429. // result == 0 = the same
  1430. // result < 0 = this number is smaller
  1431. // result > 0 = this number is bigger
  1432. int BitArray::compare (const BitArray& other) const throw()
  1433. {
  1434. if (isNegative() == other.isNegative())
  1435. {
  1436. const int absComp = compareAbsolute (other);
  1437. return isNegative() ? -absComp : absComp;
  1438. }
  1439. else
  1440. {
  1441. return isNegative() ? -1 : 1;
  1442. }
  1443. }
  1444. int BitArray::compareAbsolute (const BitArray& other) const throw()
  1445. {
  1446. const int h1 = getHighestBit();
  1447. const int h2 = other.getHighestBit();
  1448. if (h1 > h2)
  1449. return 1;
  1450. else if (h1 < h2)
  1451. return -1;
  1452. for (int i = (h1 >> 5) + 1; --i >= 0;)
  1453. if (values[i] != other.values[i])
  1454. return (values[i] > other.values[i]) ? 1 : -1;
  1455. return 0;
  1456. }
  1457. bool BitArray::operator== (const BitArray& other) const throw()
  1458. {
  1459. return compare (other) == 0;
  1460. }
  1461. bool BitArray::operator!= (const BitArray& other) const throw()
  1462. {
  1463. return compare (other) != 0;
  1464. }
  1465. bool BitArray::operator[] (const int bit) const throw()
  1466. {
  1467. return bit >= 0 && bit <= highestBit
  1468. && ((values [bit >> 5] & (1 << (bit & 31))) != 0);
  1469. }
  1470. bool BitArray::isEmpty() const throw()
  1471. {
  1472. return getHighestBit() < 0;
  1473. }
  1474. void BitArray::clear() throw()
  1475. {
  1476. if (numValues > 16)
  1477. {
  1478. juce_free (values);
  1479. numValues = 4;
  1480. values = (unsigned int*) juce_calloc (sizeof (unsigned int) * (numValues + 1));
  1481. }
  1482. else
  1483. {
  1484. zeromem (values, sizeof (unsigned int) * (numValues + 1));
  1485. }
  1486. highestBit = -1;
  1487. negative = false;
  1488. }
  1489. void BitArray::setBit (const int bit) throw()
  1490. {
  1491. if (bit >= 0)
  1492. {
  1493. if (bit > highestBit)
  1494. {
  1495. ensureSize (bit >> 5);
  1496. highestBit = bit;
  1497. }
  1498. values [bit >> 5] |= (1 << (bit & 31));
  1499. }
  1500. }
  1501. void BitArray::setBit (const int bit,
  1502. const bool shouldBeSet) throw()
  1503. {
  1504. if (shouldBeSet)
  1505. setBit (bit);
  1506. else
  1507. clearBit (bit);
  1508. }
  1509. void BitArray::clearBit (const int bit) throw()
  1510. {
  1511. if (bit >= 0 && bit <= highestBit)
  1512. values [bit >> 5] &= ~(1 << (bit & 31));
  1513. }
  1514. void BitArray::setRange (int startBit,
  1515. int numBits,
  1516. const bool shouldBeSet) throw()
  1517. {
  1518. while (--numBits >= 0)
  1519. setBit (startBit++, shouldBeSet);
  1520. }
  1521. void BitArray::insertBit (const int bit,
  1522. const bool shouldBeSet) throw()
  1523. {
  1524. if (bit >= 0)
  1525. shiftBits (1, bit);
  1526. setBit (bit, shouldBeSet);
  1527. }
  1528. void BitArray::andWith (const BitArray& other) throw()
  1529. {
  1530. // this operation will only work with the absolute values
  1531. jassert (isNegative() == other.isNegative());
  1532. int n = numValues;
  1533. while (n > other.numValues)
  1534. values[--n] = 0;
  1535. while (--n >= 0)
  1536. values[n] &= other.values[n];
  1537. if (other.highestBit < highestBit)
  1538. highestBit = other.highestBit;
  1539. highestBit = getHighestBit();
  1540. }
  1541. void BitArray::orWith (const BitArray& other) throw()
  1542. {
  1543. if (other.highestBit < 0)
  1544. return;
  1545. // this operation will only work with the absolute values
  1546. jassert (isNegative() == other.isNegative());
  1547. ensureSize (other.highestBit >> 5);
  1548. int n = (other.highestBit >> 5) + 1;
  1549. while (--n >= 0)
  1550. values[n] |= other.values[n];
  1551. if (other.highestBit > highestBit)
  1552. highestBit = other.highestBit;
  1553. highestBit = getHighestBit();
  1554. }
  1555. void BitArray::xorWith (const BitArray& other) throw()
  1556. {
  1557. if (other.highestBit < 0)
  1558. return;
  1559. // this operation will only work with the absolute values
  1560. jassert (isNegative() == other.isNegative());
  1561. ensureSize (other.highestBit >> 5);
  1562. int n = (other.highestBit >> 5) + 1;
  1563. while (--n >= 0)
  1564. values[n] ^= other.values[n];
  1565. if (other.highestBit > highestBit)
  1566. highestBit = other.highestBit;
  1567. highestBit = getHighestBit();
  1568. }
  1569. void BitArray::add (const BitArray& other) throw()
  1570. {
  1571. if (other.isNegative())
  1572. {
  1573. BitArray o (other);
  1574. o.negate();
  1575. subtract (o);
  1576. return;
  1577. }
  1578. if (isNegative())
  1579. {
  1580. if (compareAbsolute (other) < 0)
  1581. {
  1582. BitArray temp (*this);
  1583. temp.negate();
  1584. *this = other;
  1585. subtract (temp);
  1586. }
  1587. else
  1588. {
  1589. negate();
  1590. subtract (other);
  1591. negate();
  1592. }
  1593. return;
  1594. }
  1595. if (other.highestBit > highestBit)
  1596. highestBit = other.highestBit;
  1597. ++highestBit;
  1598. const int numInts = (highestBit >> 5) + 1;
  1599. ensureSize (numInts);
  1600. int64 remainder = 0;
  1601. for (int i = 0; i <= numInts; ++i)
  1602. {
  1603. if (i < numValues)
  1604. remainder += values[i];
  1605. if (i < other.numValues)
  1606. remainder += other.values[i];
  1607. values[i] = (unsigned int) remainder;
  1608. remainder >>= 32;
  1609. }
  1610. jassert (remainder == 0);
  1611. highestBit = getHighestBit();
  1612. }
  1613. void BitArray::subtract (const BitArray& other) throw()
  1614. {
  1615. if (other.isNegative())
  1616. {
  1617. BitArray o (other);
  1618. o.negate();
  1619. add (o);
  1620. return;
  1621. }
  1622. if (! isNegative())
  1623. {
  1624. if (compareAbsolute (other) < 0)
  1625. {
  1626. BitArray temp (*this);
  1627. *this = other;
  1628. subtract (temp);
  1629. negate();
  1630. return;
  1631. }
  1632. }
  1633. else
  1634. {
  1635. negate();
  1636. add (other);
  1637. negate();
  1638. return;
  1639. }
  1640. const int numInts = (highestBit >> 5) + 1;
  1641. const int maxOtherInts = (other.highestBit >> 5) + 1;
  1642. int64 amountToSubtract = 0;
  1643. for (int i = 0; i <= numInts; ++i)
  1644. {
  1645. if (i <= maxOtherInts)
  1646. amountToSubtract += (int64)other.values[i];
  1647. if (values[i] >= amountToSubtract)
  1648. {
  1649. values[i] = (unsigned int) (values[i] - amountToSubtract);
  1650. amountToSubtract = 0;
  1651. }
  1652. else
  1653. {
  1654. const int64 n = ((int64) values[i] + (((int64) 1) << 32)) - amountToSubtract;
  1655. values[i] = (unsigned int) n;
  1656. amountToSubtract = 1;
  1657. }
  1658. }
  1659. }
  1660. void BitArray::multiplyBy (const BitArray& other) throw()
  1661. {
  1662. BitArray total;
  1663. highestBit = getHighestBit();
  1664. const bool wasNegative = isNegative();
  1665. setNegative (false);
  1666. for (int i = 0; i <= highestBit; ++i)
  1667. {
  1668. if (operator[](i))
  1669. {
  1670. BitArray n (other);
  1671. n.setNegative (false);
  1672. n.shiftBits (i);
  1673. total.add (n);
  1674. }
  1675. }
  1676. *this = total;
  1677. negative = wasNegative ^ other.isNegative();
  1678. }
  1679. void BitArray::divideBy (const BitArray& divisor, BitArray& remainder) throw()
  1680. {
  1681. jassert (this != &remainder); // (can't handle passing itself in to get the remainder)
  1682. const int divHB = divisor.getHighestBit();
  1683. const int ourHB = getHighestBit();
  1684. if (divHB < 0 || ourHB < 0)
  1685. {
  1686. // division by zero
  1687. remainder.clear();
  1688. clear();
  1689. }
  1690. else
  1691. {
  1692. remainder = *this;
  1693. remainder.setNegative (false);
  1694. const bool wasNegative = isNegative();
  1695. clear();
  1696. BitArray temp (divisor);
  1697. temp.setNegative (false);
  1698. int leftShift = ourHB - divHB;
  1699. temp.shiftBits (leftShift);
  1700. while (leftShift >= 0)
  1701. {
  1702. if (remainder.compareAbsolute (temp) >= 0)
  1703. {
  1704. remainder.subtract (temp);
  1705. setBit (leftShift);
  1706. }
  1707. if (--leftShift >= 0)
  1708. temp.shiftBits (-1);
  1709. }
  1710. negative = wasNegative ^ divisor.isNegative();
  1711. remainder.setNegative (wasNegative);
  1712. }
  1713. }
  1714. void BitArray::modulo (const BitArray& divisor) throw()
  1715. {
  1716. BitArray remainder;
  1717. divideBy (divisor, remainder);
  1718. *this = remainder;
  1719. }
  1720. static const BitArray simpleGCD (BitArray* m, BitArray* n) throw()
  1721. {
  1722. while (! m->isEmpty())
  1723. {
  1724. if (n->compareAbsolute (*m) > 0)
  1725. swapVariables (m, n);
  1726. m->subtract (*n);
  1727. }
  1728. return *n;
  1729. }
  1730. const BitArray BitArray::findGreatestCommonDivisor (BitArray n) const throw()
  1731. {
  1732. BitArray m (*this);
  1733. while (! n.isEmpty())
  1734. {
  1735. if (abs (m.getHighestBit() - n.getHighestBit()) <= 16)
  1736. return simpleGCD (&m, &n);
  1737. BitArray temp1 (m), temp2;
  1738. temp1.divideBy (n, temp2);
  1739. m = n;
  1740. n = temp2;
  1741. }
  1742. return m;
  1743. }
  1744. void BitArray::exponentModulo (const BitArray& exponent,
  1745. const BitArray& modulus) throw()
  1746. {
  1747. BitArray exp (exponent);
  1748. exp.modulo (modulus);
  1749. BitArray value (*this);
  1750. value.modulo (modulus);
  1751. clear();
  1752. setBit (0);
  1753. while (! exp.isEmpty())
  1754. {
  1755. if (exp [0])
  1756. {
  1757. multiplyBy (value);
  1758. this->modulo (modulus);
  1759. }
  1760. value.multiplyBy (value);
  1761. value.modulo (modulus);
  1762. exp.shiftBits (-1);
  1763. }
  1764. }
  1765. void BitArray::inverseModulo (const BitArray& modulus) throw()
  1766. {
  1767. const BitArray one (1);
  1768. if (modulus == one || modulus.isNegative())
  1769. {
  1770. clear();
  1771. return;
  1772. }
  1773. if (isNegative() || compareAbsolute (modulus) >= 0)
  1774. this->modulo (modulus);
  1775. if (*this == one)
  1776. return;
  1777. if (! (*this)[0])
  1778. {
  1779. // not invertible
  1780. clear();
  1781. return;
  1782. }
  1783. BitArray a1 (modulus);
  1784. BitArray a2 (*this);
  1785. BitArray b1 (modulus);
  1786. BitArray b2 (1);
  1787. while (a2 != one)
  1788. {
  1789. BitArray temp1, temp2, multiplier (a1);
  1790. multiplier.divideBy (a2, temp1);
  1791. temp1 = a2;
  1792. temp1.multiplyBy (multiplier);
  1793. temp2 = a1;
  1794. temp2.subtract (temp1);
  1795. a1 = a2;
  1796. a2 = temp2;
  1797. temp1 = b2;
  1798. temp1.multiplyBy (multiplier);
  1799. temp2 = b1;
  1800. temp2.subtract (temp1);
  1801. b1 = b2;
  1802. b2 = temp2;
  1803. }
  1804. while (b2.isNegative())
  1805. b2.add (modulus);
  1806. b2.modulo (modulus);
  1807. *this = b2;
  1808. }
  1809. void BitArray::shiftBits (int bits, const int startBit) throw()
  1810. {
  1811. if (highestBit < 0)
  1812. return;
  1813. if (startBit > 0)
  1814. {
  1815. if (bits < 0)
  1816. {
  1817. // right shift
  1818. for (int i = startBit; i <= highestBit; ++i)
  1819. setBit (i, operator[] (i - bits));
  1820. highestBit = getHighestBit();
  1821. }
  1822. else if (bits > 0)
  1823. {
  1824. // left shift
  1825. for (int i = highestBit + 1; --i >= startBit;)
  1826. setBit (i + bits, operator[] (i));
  1827. while (--bits >= 0)
  1828. clearBit (bits + startBit);
  1829. }
  1830. }
  1831. else
  1832. {
  1833. if (bits < 0)
  1834. {
  1835. // right shift
  1836. bits = -bits;
  1837. if (bits > highestBit)
  1838. {
  1839. clear();
  1840. }
  1841. else
  1842. {
  1843. const int wordsToMove = bits >> 5;
  1844. int top = 1 + (highestBit >> 5) - wordsToMove;
  1845. highestBit -= bits;
  1846. if (wordsToMove > 0)
  1847. {
  1848. int i;
  1849. for (i = 0; i < top; ++i)
  1850. values [i] = values [i + wordsToMove];
  1851. for (i = 0; i < wordsToMove; ++i)
  1852. values [top + i] = 0;
  1853. bits &= 31;
  1854. }
  1855. if (bits != 0)
  1856. {
  1857. const int invBits = 32 - bits;
  1858. --top;
  1859. for (int i = 0; i < top; ++i)
  1860. values[i] = (values[i] >> bits) | (values [i + 1] << invBits);
  1861. values[top] = (values[top] >> bits);
  1862. }
  1863. highestBit = getHighestBit();
  1864. }
  1865. }
  1866. else if (bits > 0)
  1867. {
  1868. // left shift
  1869. ensureSize (((highestBit + bits) >> 5) + 1);
  1870. const int wordsToMove = bits >> 5;
  1871. int top = 1 + (highestBit >> 5);
  1872. highestBit += bits;
  1873. if (wordsToMove > 0)
  1874. {
  1875. int i;
  1876. for (i = top; --i >= 0;)
  1877. values [i + wordsToMove] = values [i];
  1878. for (i = 0; i < wordsToMove; ++i)
  1879. values [i] = 0;
  1880. bits &= 31;
  1881. }
  1882. if (bits != 0)
  1883. {
  1884. const int invBits = 32 - bits;
  1885. for (int i = top + 1 + wordsToMove; --i > wordsToMove;)
  1886. values[i] = (values[i] << bits) | (values [i - 1] >> invBits);
  1887. values [wordsToMove] = values [wordsToMove] << bits;
  1888. }
  1889. highestBit = getHighestBit();
  1890. }
  1891. }
  1892. }
  1893. int BitArray::getBitRangeAsInt (const int startBit, int numBits) const throw()
  1894. {
  1895. if (numBits > 32)
  1896. {
  1897. jassertfalse
  1898. numBits = 32;
  1899. }
  1900. if (startBit == 0)
  1901. {
  1902. if (numBits < 32)
  1903. return values[0] & ((1 << numBits) - 1);
  1904. return values[0];
  1905. }
  1906. int n = 0;
  1907. for (int i = numBits; --i >= 0;)
  1908. {
  1909. n <<= 1;
  1910. if (operator[] (startBit + i))
  1911. n |= 1;
  1912. }
  1913. return n;
  1914. }
  1915. void BitArray::setBitRangeAsInt (const int startBit, int numBits, unsigned int valueToSet) throw()
  1916. {
  1917. if (numBits > 32)
  1918. {
  1919. jassertfalse
  1920. numBits = 32;
  1921. }
  1922. for (int i = 0; i < numBits; ++i)
  1923. {
  1924. setBit (startBit + i, (valueToSet & 1) != 0);
  1925. valueToSet >>= 1;
  1926. }
  1927. }
  1928. void BitArray::fillBitsRandomly (int startBit, int numBits) throw()
  1929. {
  1930. highestBit = jmax (highestBit, startBit + numBits);
  1931. ensureSize (((startBit + numBits) >> 5) + 1);
  1932. while ((startBit & 31) != 0 && numBits > 0)
  1933. {
  1934. setBit (startBit++, Random::getSystemRandom().nextBool());
  1935. --numBits;
  1936. }
  1937. while (numBits >= 32)
  1938. {
  1939. values [startBit >> 5] = (unsigned int) Random::getSystemRandom().nextInt();
  1940. startBit += 32;
  1941. numBits -= 32;
  1942. }
  1943. while (--numBits >= 0)
  1944. {
  1945. setBit (startBit + numBits, Random::getSystemRandom().nextBool());
  1946. }
  1947. highestBit = getHighestBit();
  1948. }
  1949. void BitArray::createRandomNumber (const BitArray& maximumValue) throw()
  1950. {
  1951. clear();
  1952. do
  1953. {
  1954. fillBitsRandomly (0, maximumValue.getHighestBit() + 1);
  1955. }
  1956. while (compare (maximumValue) >= 0);
  1957. }
  1958. bool BitArray::isNegative() const throw()
  1959. {
  1960. return negative && ! isEmpty();
  1961. }
  1962. void BitArray::setNegative (const bool neg) throw()
  1963. {
  1964. negative = neg;
  1965. }
  1966. void BitArray::negate() throw()
  1967. {
  1968. negative = (! negative) && ! isEmpty();
  1969. }
  1970. int BitArray::countNumberOfSetBits() const throw()
  1971. {
  1972. int total = 0;
  1973. for (int i = (highestBit >> 5) + 1; --i >= 0;)
  1974. {
  1975. unsigned int n = values[i];
  1976. if (n == 0xffffffff)
  1977. {
  1978. total += 32;
  1979. }
  1980. else
  1981. {
  1982. while (n != 0)
  1983. {
  1984. total += (n & 1);
  1985. n >>= 1;
  1986. }
  1987. }
  1988. }
  1989. return total;
  1990. }
  1991. int BitArray::getHighestBit() const throw()
  1992. {
  1993. for (int i = highestBit + 1; --i >= 0;)
  1994. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  1995. return i;
  1996. return -1;
  1997. }
  1998. int BitArray::findNextSetBit (int i) const throw()
  1999. {
  2000. for (; i <= highestBit; ++i)
  2001. if ((values [i >> 5] & (1 << (i & 31))) != 0)
  2002. return i;
  2003. return -1;
  2004. }
  2005. int BitArray::findNextClearBit (int i) const throw()
  2006. {
  2007. for (; i <= highestBit; ++i)
  2008. if ((values [i >> 5] & (1 << (i & 31))) == 0)
  2009. break;
  2010. return i;
  2011. }
  2012. void BitArray::ensureSize (const int numVals) throw()
  2013. {
  2014. if (numVals + 2 >= numValues)
  2015. {
  2016. int oldSize = numValues;
  2017. numValues = ((numVals + 2) * 3) / 2;
  2018. values = (unsigned int*) juce_realloc (values, sizeof (unsigned int) * numValues + 4);
  2019. while (oldSize < numValues)
  2020. values [oldSize++] = 0;
  2021. }
  2022. }
  2023. const String BitArray::toString (const int base) const throw()
  2024. {
  2025. String s;
  2026. BitArray v (*this);
  2027. if (base == 2 || base == 8 || base == 16)
  2028. {
  2029. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2030. static const tchar* const hexDigits = T("0123456789abcdef");
  2031. for (;;)
  2032. {
  2033. const int remainder = v.getBitRangeAsInt (0, bits);
  2034. v.shiftBits (-bits);
  2035. if (remainder == 0 && v.isEmpty())
  2036. break;
  2037. s = String::charToString (hexDigits [remainder]) + s;
  2038. }
  2039. }
  2040. else if (base == 10)
  2041. {
  2042. const BitArray ten (10);
  2043. BitArray remainder;
  2044. for (;;)
  2045. {
  2046. v.divideBy (ten, remainder);
  2047. if (remainder.isEmpty() && v.isEmpty())
  2048. break;
  2049. s = String (remainder.getBitRangeAsInt (0, 8)) + s;
  2050. }
  2051. }
  2052. else
  2053. {
  2054. jassertfalse // can't do the specified base
  2055. return String::empty;
  2056. }
  2057. if (s.isEmpty())
  2058. return T("0");
  2059. return isNegative() ? T("-") + s : s;
  2060. }
  2061. void BitArray::parseString (const String& text,
  2062. const int base) throw()
  2063. {
  2064. clear();
  2065. const tchar* t = (const tchar*) text;
  2066. if (base == 2 || base == 8 || base == 16)
  2067. {
  2068. const int bits = (base == 2) ? 1 : (base == 8 ? 3 : 4);
  2069. for (;;)
  2070. {
  2071. const tchar c = *t++;
  2072. const int digit = CharacterFunctions::getHexDigitValue (c);
  2073. if (((unsigned int) digit) < (unsigned int) base)
  2074. {
  2075. shiftBits (bits);
  2076. add (digit);
  2077. }
  2078. else if (c == 0)
  2079. {
  2080. break;
  2081. }
  2082. }
  2083. }
  2084. else if (base == 10)
  2085. {
  2086. const BitArray ten ((unsigned int) 10);
  2087. for (;;)
  2088. {
  2089. const tchar c = *t++;
  2090. if (c >= T('0') && c <= T('9'))
  2091. {
  2092. multiplyBy (ten);
  2093. add ((int) (c - T('0')));
  2094. }
  2095. else if (c == 0)
  2096. {
  2097. break;
  2098. }
  2099. }
  2100. }
  2101. setNegative (text.trimStart().startsWithChar (T('-')));
  2102. }
  2103. const MemoryBlock BitArray::toMemoryBlock() const throw()
  2104. {
  2105. const int numBytes = (getHighestBit() + 8) >> 3;
  2106. MemoryBlock mb (numBytes);
  2107. for (int i = 0; i < numBytes; ++i)
  2108. mb[i] = (uint8) getBitRangeAsInt (i << 3, 8);
  2109. return mb;
  2110. }
  2111. void BitArray::loadFromMemoryBlock (const MemoryBlock& data) throw()
  2112. {
  2113. clear();
  2114. for (int i = data.getSize(); --i >= 0;)
  2115. this->setBitRangeAsInt (i << 3, 8, data [i]);
  2116. }
  2117. END_JUCE_NAMESPACE
  2118. /********* End of inlined file: juce_BitArray.cpp *********/
  2119. /********* Start of inlined file: juce_MemoryBlock.cpp *********/
  2120. BEGIN_JUCE_NAMESPACE
  2121. MemoryBlock::MemoryBlock() throw()
  2122. : data (0),
  2123. size (0)
  2124. {
  2125. }
  2126. MemoryBlock::MemoryBlock (const int initialSize,
  2127. const bool initialiseToZero) throw()
  2128. {
  2129. if (initialSize > 0)
  2130. {
  2131. size = initialSize;
  2132. if (initialiseToZero)
  2133. data = (char*) juce_calloc (initialSize);
  2134. else
  2135. data = (char*) juce_malloc (initialSize);
  2136. }
  2137. else
  2138. {
  2139. data = 0;
  2140. size = 0;
  2141. }
  2142. }
  2143. MemoryBlock::MemoryBlock (const MemoryBlock& other) throw()
  2144. : data (0),
  2145. size (other.size)
  2146. {
  2147. if (size > 0)
  2148. {
  2149. jassert (other.data != 0);
  2150. data = (char*) juce_malloc (size);
  2151. memcpy (data, other.data, size);
  2152. }
  2153. }
  2154. MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom,
  2155. const int sizeInBytes) throw()
  2156. : data (0),
  2157. size (jmax (0, sizeInBytes))
  2158. {
  2159. jassert (sizeInBytes >= 0);
  2160. if (size > 0)
  2161. {
  2162. jassert (dataToInitialiseFrom != 0); // non-zero size, but a zero pointer passed-in?
  2163. data = (char*) juce_malloc (size);
  2164. if (dataToInitialiseFrom != 0)
  2165. memcpy (data, dataToInitialiseFrom, size);
  2166. }
  2167. }
  2168. MemoryBlock::~MemoryBlock() throw()
  2169. {
  2170. jassert (size >= 0); // should never happen
  2171. jassert (size == 0 || data != 0); // non-zero size but no data allocated?
  2172. juce_free (data);
  2173. }
  2174. const MemoryBlock& MemoryBlock::operator= (const MemoryBlock& other) throw()
  2175. {
  2176. if (this != &other)
  2177. {
  2178. setSize (other.size, false);
  2179. memcpy (data, other.data, size);
  2180. }
  2181. return *this;
  2182. }
  2183. bool MemoryBlock::operator== (const MemoryBlock& other) const throw()
  2184. {
  2185. return (size == other.size)
  2186. && (memcmp (data, other.data, size) == 0);
  2187. }
  2188. bool MemoryBlock::operator!= (const MemoryBlock& other) const throw()
  2189. {
  2190. return ! operator== (other);
  2191. }
  2192. // this will resize the block to this size
  2193. void MemoryBlock::setSize (const int newSize,
  2194. const bool initialiseToZero) throw()
  2195. {
  2196. if (size != newSize)
  2197. {
  2198. if (newSize <= 0)
  2199. {
  2200. juce_free (data);
  2201. data = 0;
  2202. size = 0;
  2203. }
  2204. else
  2205. {
  2206. if (data != 0)
  2207. {
  2208. data = (char*) juce_realloc (data, newSize);
  2209. if (initialiseToZero && (newSize > size))
  2210. zeromem (data + size, newSize - size);
  2211. }
  2212. else
  2213. {
  2214. if (initialiseToZero)
  2215. data = (char*) juce_calloc (newSize);
  2216. else
  2217. data = (char*) juce_malloc (newSize);
  2218. }
  2219. size = newSize;
  2220. }
  2221. }
  2222. }
  2223. void MemoryBlock::ensureSize (const int minimumSize,
  2224. const bool initialiseToZero) throw()
  2225. {
  2226. if (size < minimumSize)
  2227. setSize (minimumSize, initialiseToZero);
  2228. }
  2229. void MemoryBlock::fillWith (const uint8 value) throw()
  2230. {
  2231. memset (data, (int) value, size);
  2232. }
  2233. void MemoryBlock::append (const void* const srcData,
  2234. const int numBytes) throw()
  2235. {
  2236. if (numBytes > 0)
  2237. {
  2238. const int oldSize = size;
  2239. setSize (size + numBytes);
  2240. memcpy (data + oldSize, srcData, numBytes);
  2241. }
  2242. }
  2243. void MemoryBlock::copyFrom (const void* const src, int offset, int num) throw()
  2244. {
  2245. const char* d = (const char*) src;
  2246. if (offset < 0)
  2247. {
  2248. d -= offset;
  2249. num -= offset;
  2250. offset = 0;
  2251. }
  2252. if (offset + num > size)
  2253. num = size - offset;
  2254. if (num > 0)
  2255. memcpy (data + offset, d, num);
  2256. }
  2257. void MemoryBlock::copyTo (void* const dst, int offset, int num) const throw()
  2258. {
  2259. char* d = (char*) dst;
  2260. if (offset < 0)
  2261. {
  2262. zeromem (d, -offset);
  2263. d -= offset;
  2264. num += offset;
  2265. offset = 0;
  2266. }
  2267. if (offset + num > size)
  2268. {
  2269. const int newNum = size - offset;
  2270. zeromem (d + newNum, num - newNum);
  2271. num = newNum;
  2272. }
  2273. if (num > 0)
  2274. memcpy (d, data + offset, num);
  2275. }
  2276. void MemoryBlock::removeSection (int startByte, int numBytesToRemove) throw()
  2277. {
  2278. if (startByte < 0)
  2279. {
  2280. numBytesToRemove += startByte;
  2281. startByte = 0;
  2282. }
  2283. if (startByte + numBytesToRemove >= size)
  2284. {
  2285. setSize (startByte);
  2286. }
  2287. else if (numBytesToRemove > 0)
  2288. {
  2289. memmove (data + startByte,
  2290. data + startByte + numBytesToRemove,
  2291. size - (startByte + numBytesToRemove));
  2292. setSize (size - numBytesToRemove);
  2293. }
  2294. }
  2295. const String MemoryBlock::toString() const throw()
  2296. {
  2297. return String (data, size);
  2298. }
  2299. int MemoryBlock::getBitRange (const int bitRangeStart, int numBits) const throw()
  2300. {
  2301. int res = 0;
  2302. int byte = bitRangeStart >> 3;
  2303. int offsetInByte = bitRangeStart & 7;
  2304. int bitsSoFar = 0;
  2305. while (numBits > 0 && byte < size)
  2306. {
  2307. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  2308. const int mask = (0xff >> (8 - bitsThisTime)) << offsetInByte;
  2309. res |= (((data[byte] & mask) >> offsetInByte) << bitsSoFar);
  2310. bitsSoFar += bitsThisTime;
  2311. numBits -= bitsThisTime;
  2312. ++byte;
  2313. offsetInByte = 0;
  2314. }
  2315. return res;
  2316. }
  2317. void MemoryBlock::setBitRange (const int bitRangeStart, int numBits, int bitsToSet) throw()
  2318. {
  2319. int byte = bitRangeStart >> 3;
  2320. int offsetInByte = bitRangeStart & 7;
  2321. unsigned int mask = ~((((unsigned int)0xffffffff) << (32 - numBits)) >> (32 - numBits));
  2322. while (numBits > 0 && byte < size)
  2323. {
  2324. const int bitsThisTime = jmin (numBits, 8 - offsetInByte);
  2325. const unsigned int tempMask = (mask << offsetInByte) | ~((((unsigned int)0xffffffff) >> offsetInByte) << offsetInByte);
  2326. const unsigned int tempBits = bitsToSet << offsetInByte;
  2327. data[byte] = (char)((data[byte] & tempMask) | tempBits);
  2328. ++byte;
  2329. numBits -= bitsThisTime;
  2330. bitsToSet >>= bitsThisTime;
  2331. mask >>= bitsThisTime;
  2332. offsetInByte = 0;
  2333. }
  2334. }
  2335. void MemoryBlock::loadFromHexString (const String& hex) throw()
  2336. {
  2337. ensureSize (hex.length() >> 1);
  2338. char* dest = data;
  2339. int i = 0;
  2340. for (;;)
  2341. {
  2342. int byte = 0;
  2343. for (int loop = 2; --loop >= 0;)
  2344. {
  2345. byte <<= 4;
  2346. for (;;)
  2347. {
  2348. const tchar c = hex [i++];
  2349. if (c >= T('0') && c <= T('9'))
  2350. {
  2351. byte |= c - T('0');
  2352. break;
  2353. }
  2354. else if (c >= T('a') && c <= T('z'))
  2355. {
  2356. byte |= c - (T('a') - 10);
  2357. break;
  2358. }
  2359. else if (c >= T('A') && c <= T('Z'))
  2360. {
  2361. byte |= c - (T('A') - 10);
  2362. break;
  2363. }
  2364. else if (c == 0)
  2365. {
  2366. setSize ((int) (dest - data));
  2367. return;
  2368. }
  2369. }
  2370. }
  2371. *dest++ = (char) byte;
  2372. }
  2373. }
  2374. static const char* const encodingTable
  2375. = ".ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+";
  2376. const String MemoryBlock::toBase64Encoding() const throw()
  2377. {
  2378. const int numChars = ((size << 3) + 5) / 6;
  2379. String destString (size); // store the length, followed by a '.', and then the data.
  2380. const int initialLen = destString.length();
  2381. destString.preallocateStorage (initialLen + 2 + numChars);
  2382. tchar* d = const_cast <tchar*> (((const tchar*) destString) + initialLen);
  2383. *d++ = T('.');
  2384. for (int i = 0; i < numChars; ++i)
  2385. *d++ = encodingTable [getBitRange (i * 6, 6)];
  2386. *d++ = 0;
  2387. return destString;
  2388. }
  2389. bool MemoryBlock::fromBase64Encoding (const String& s) throw()
  2390. {
  2391. const int startPos = s.indexOfChar (T('.')) + 1;
  2392. if (startPos <= 0)
  2393. return false;
  2394. const int numBytesNeeded = s.substring (0, startPos - 1).getIntValue();
  2395. setSize (numBytesNeeded, true);
  2396. const int numChars = s.length() - startPos;
  2397. const tchar* const srcChars = ((const tchar*) s) + startPos;
  2398. for (int i = 0; i < numChars; ++i)
  2399. {
  2400. const char c = (char) srcChars[i];
  2401. for (int j = 0; j < 64; ++j)
  2402. {
  2403. if (encodingTable[j] == c)
  2404. {
  2405. setBitRange (i * 6, 6, j);
  2406. break;
  2407. }
  2408. }
  2409. }
  2410. return true;
  2411. }
  2412. END_JUCE_NAMESPACE
  2413. /********* End of inlined file: juce_MemoryBlock.cpp *********/
  2414. /********* Start of inlined file: juce_PropertySet.cpp *********/
  2415. BEGIN_JUCE_NAMESPACE
  2416. PropertySet::PropertySet (const bool ignoreCaseOfKeyNames) throw()
  2417. : properties (ignoreCaseOfKeyNames),
  2418. fallbackProperties (0),
  2419. ignoreCaseOfKeys (ignoreCaseOfKeyNames)
  2420. {
  2421. }
  2422. PropertySet::PropertySet (const PropertySet& other) throw()
  2423. : properties (other.properties),
  2424. fallbackProperties (other.fallbackProperties),
  2425. ignoreCaseOfKeys (other.ignoreCaseOfKeys)
  2426. {
  2427. }
  2428. const PropertySet& PropertySet::operator= (const PropertySet& other) throw()
  2429. {
  2430. properties = other.properties;
  2431. fallbackProperties = other.fallbackProperties;
  2432. ignoreCaseOfKeys = other.ignoreCaseOfKeys;
  2433. propertyChanged();
  2434. return *this;
  2435. }
  2436. PropertySet::~PropertySet()
  2437. {
  2438. }
  2439. void PropertySet::clear()
  2440. {
  2441. const ScopedLock sl (lock);
  2442. if (properties.size() > 0)
  2443. {
  2444. properties.clear();
  2445. propertyChanged();
  2446. }
  2447. }
  2448. const String PropertySet::getValue (const String& keyName,
  2449. const String& defaultValue) const throw()
  2450. {
  2451. const ScopedLock sl (lock);
  2452. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2453. if (index >= 0)
  2454. return properties.getAllValues() [index];
  2455. return fallbackProperties != 0 ? fallbackProperties->getValue (keyName, defaultValue)
  2456. : defaultValue;
  2457. }
  2458. int PropertySet::getIntValue (const String& keyName,
  2459. const int defaultValue) const throw()
  2460. {
  2461. const ScopedLock sl (lock);
  2462. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2463. if (index >= 0)
  2464. return properties.getAllValues() [index].getIntValue();
  2465. return fallbackProperties != 0 ? fallbackProperties->getIntValue (keyName, defaultValue)
  2466. : defaultValue;
  2467. }
  2468. double PropertySet::getDoubleValue (const String& keyName,
  2469. const double defaultValue) const throw()
  2470. {
  2471. const ScopedLock sl (lock);
  2472. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2473. if (index >= 0)
  2474. return properties.getAllValues()[index].getDoubleValue();
  2475. return fallbackProperties != 0 ? fallbackProperties->getDoubleValue (keyName, defaultValue)
  2476. : defaultValue;
  2477. }
  2478. bool PropertySet::getBoolValue (const String& keyName,
  2479. const bool defaultValue) const throw()
  2480. {
  2481. const ScopedLock sl (lock);
  2482. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2483. if (index >= 0)
  2484. return properties.getAllValues() [index].getIntValue() != 0;
  2485. return fallbackProperties != 0 ? fallbackProperties->getBoolValue (keyName, defaultValue)
  2486. : defaultValue;
  2487. }
  2488. XmlElement* PropertySet::getXmlValue (const String& keyName) const
  2489. {
  2490. XmlDocument doc (getValue (keyName));
  2491. return doc.getDocumentElement();
  2492. }
  2493. void PropertySet::setValue (const String& keyName,
  2494. const String& value) throw()
  2495. {
  2496. jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
  2497. if (keyName.isNotEmpty())
  2498. {
  2499. const ScopedLock sl (lock);
  2500. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2501. if (index < 0 || properties.getAllValues() [index] != value)
  2502. {
  2503. properties.set (keyName, value);
  2504. propertyChanged();
  2505. }
  2506. }
  2507. }
  2508. void PropertySet::removeValue (const String& keyName) throw()
  2509. {
  2510. if (keyName.isNotEmpty())
  2511. {
  2512. const ScopedLock sl (lock);
  2513. const int index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
  2514. if (index >= 0)
  2515. {
  2516. properties.remove (keyName);
  2517. propertyChanged();
  2518. }
  2519. }
  2520. }
  2521. void PropertySet::setValue (const String& keyName, const tchar* const value) throw()
  2522. {
  2523. setValue (keyName, String (value));
  2524. }
  2525. void PropertySet::setValue (const String& keyName, const int value) throw()
  2526. {
  2527. setValue (keyName, String (value));
  2528. }
  2529. void PropertySet::setValue (const String& keyName, const double value) throw()
  2530. {
  2531. setValue (keyName, String (value));
  2532. }
  2533. void PropertySet::setValue (const String& keyName, const bool value) throw()
  2534. {
  2535. setValue (keyName, String ((value) ? T("1") : T("0")));
  2536. }
  2537. void PropertySet::setValue (const String& keyName, const XmlElement* const xml)
  2538. {
  2539. setValue (keyName, (xml == 0) ? String::empty
  2540. : xml->createDocument (String::empty, true));
  2541. }
  2542. bool PropertySet::containsKey (const String& keyName) const throw()
  2543. {
  2544. const ScopedLock sl (lock);
  2545. return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
  2546. }
  2547. void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) throw()
  2548. {
  2549. const ScopedLock sl (lock);
  2550. fallbackProperties = fallbackProperties_;
  2551. }
  2552. XmlElement* PropertySet::createXml (const String& nodeName) const throw()
  2553. {
  2554. const ScopedLock sl (lock);
  2555. XmlElement* const xml = new XmlElement (nodeName);
  2556. for (int i = 0; i < properties.getAllKeys().size(); ++i)
  2557. {
  2558. XmlElement* const e = new XmlElement (T("VALUE"));
  2559. e->setAttribute (T("name"), properties.getAllKeys()[i]);
  2560. e->setAttribute (T("val"), properties.getAllValues()[i]);
  2561. xml->addChildElement (e);
  2562. }
  2563. return xml;
  2564. }
  2565. void PropertySet::restoreFromXml (const XmlElement& xml) throw()
  2566. {
  2567. const ScopedLock sl (lock);
  2568. clear();
  2569. forEachXmlChildElementWithTagName (xml, e, T("VALUE"))
  2570. {
  2571. if (e->hasAttribute (T("name"))
  2572. && e->hasAttribute (T("val")))
  2573. {
  2574. properties.set (e->getStringAttribute (T("name")),
  2575. e->getStringAttribute (T("val")));
  2576. }
  2577. }
  2578. if (properties.size() > 0)
  2579. propertyChanged();
  2580. }
  2581. void PropertySet::propertyChanged()
  2582. {
  2583. }
  2584. END_JUCE_NAMESPACE
  2585. /********* End of inlined file: juce_PropertySet.cpp *********/
  2586. /********* Start of inlined file: juce_BlowFish.cpp *********/
  2587. BEGIN_JUCE_NAMESPACE
  2588. static const uint32 initialPValues [18] =
  2589. {
  2590. 0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,
  2591. 0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,
  2592. 0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,
  2593. 0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,
  2594. 0x9216d5d9, 0x8979fb1b
  2595. };
  2596. static const uint32 initialSValues [4 * 256] =
  2597. {
  2598. 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7,
  2599. 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
  2600. 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16,
  2601. 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
  2602. 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee,
  2603. 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
  2604. 0xc5d1b023, 0x286085f0, 0xca417918, 0xb8db38ef,
  2605. 0x8e79dcb0, 0x603a180e, 0x6c9e0e8b, 0xb01e8a3e,
  2606. 0xd71577c1, 0xbd314b27, 0x78af2fda, 0x55605c60,
  2607. 0xe65525f3, 0xaa55ab94, 0x57489862, 0x63e81440,
  2608. 0x55ca396a, 0x2aab10b6, 0xb4cc5c34, 0x1141e8ce,
  2609. 0xa15486af, 0x7c72e993, 0xb3ee1411, 0x636fbc2a,
  2610. 0x2ba9c55d, 0x741831f6, 0xce5c3e16, 0x9b87931e,
  2611. 0xafd6ba33, 0x6c24cf5c, 0x7a325381, 0x28958677,
  2612. 0x3b8f4898, 0x6b4bb9af, 0xc4bfe81b, 0x66282193,
  2613. 0x61d809cc, 0xfb21a991, 0x487cac60, 0x5dec8032,
  2614. 0xef845d5d, 0xe98575b1, 0xdc262302, 0xeb651b88,
  2615. 0x23893e81, 0xd396acc5, 0x0f6d6ff3, 0x83f44239,
  2616. 0x2e0b4482, 0xa4842004, 0x69c8f04a, 0x9e1f9b5e,
  2617. 0x21c66842, 0xf6e96c9a, 0x670c9c61, 0xabd388f0,
  2618. 0x6a51a0d2, 0xd8542f68, 0x960fa728, 0xab5133a3,
  2619. 0x6eef0b6c, 0x137a3be4, 0xba3bf050, 0x7efb2a98,
  2620. 0xa1f1651d, 0x39af0176, 0x66ca593e, 0x82430e88,
  2621. 0x8cee8619, 0x456f9fb4, 0x7d84a5c3, 0x3b8b5ebe,
  2622. 0xe06f75d8, 0x85c12073, 0x401a449f, 0x56c16aa6,
  2623. 0x4ed3aa62, 0x363f7706, 0x1bfedf72, 0x429b023d,
  2624. 0x37d0d724, 0xd00a1248, 0xdb0fead3, 0x49f1c09b,
  2625. 0x075372c9, 0x80991b7b, 0x25d479d8, 0xf6e8def7,
  2626. 0xe3fe501a, 0xb6794c3b, 0x976ce0bd, 0x04c006ba,
  2627. 0xc1a94fb6, 0x409f60c4, 0x5e5c9ec2, 0x196a2463,
  2628. 0x68fb6faf, 0x3e6c53b5, 0x1339b2eb, 0x3b52ec6f,
  2629. 0x6dfc511f, 0x9b30952c, 0xcc814544, 0xaf5ebd09,
  2630. 0xbee3d004, 0xde334afd, 0x660f2807, 0x192e4bb3,
  2631. 0xc0cba857, 0x45c8740f, 0xd20b5f39, 0xb9d3fbdb,
  2632. 0x5579c0bd, 0x1a60320a, 0xd6a100c6, 0x402c7279,
  2633. 0x679f25fe, 0xfb1fa3cc, 0x8ea5e9f8, 0xdb3222f8,
  2634. 0x3c7516df, 0xfd616b15, 0x2f501ec8, 0xad0552ab,
  2635. 0x323db5fa, 0xfd238760, 0x53317b48, 0x3e00df82,
  2636. 0x9e5c57bb, 0xca6f8ca0, 0x1a87562e, 0xdf1769db,
  2637. 0xd542a8f6, 0x287effc3, 0xac6732c6, 0x8c4f5573,
  2638. 0x695b27b0, 0xbbca58c8, 0xe1ffa35d, 0xb8f011a0,
  2639. 0x10fa3d98, 0xfd2183b8, 0x4afcb56c, 0x2dd1d35b,
  2640. 0x9a53e479, 0xb6f84565, 0xd28e49bc, 0x4bfb9790,
  2641. 0xe1ddf2da, 0xa4cb7e33, 0x62fb1341, 0xcee4c6e8,
  2642. 0xef20cada, 0x36774c01, 0xd07e9efe, 0x2bf11fb4,
  2643. 0x95dbda4d, 0xae909198, 0xeaad8e71, 0x6b93d5a0,
  2644. 0xd08ed1d0, 0xafc725e0, 0x8e3c5b2f, 0x8e7594b7,
  2645. 0x8ff6e2fb, 0xf2122b64, 0x8888b812, 0x900df01c,
  2646. 0x4fad5ea0, 0x688fc31c, 0xd1cff191, 0xb3a8c1ad,
  2647. 0x2f2f2218, 0xbe0e1777, 0xea752dfe, 0x8b021fa1,
  2648. 0xe5a0cc0f, 0xb56f74e8, 0x18acf3d6, 0xce89e299,
  2649. 0xb4a84fe0, 0xfd13e0b7, 0x7cc43b81, 0xd2ada8d9,
  2650. 0x165fa266, 0x80957705, 0x93cc7314, 0x211a1477,
  2651. 0xe6ad2065, 0x77b5fa86, 0xc75442f5, 0xfb9d35cf,
  2652. 0xebcdaf0c, 0x7b3e89a0, 0xd6411bd3, 0xae1e7e49,
  2653. 0x00250e2d, 0x2071b35e, 0x226800bb, 0x57b8e0af,
  2654. 0x2464369b, 0xf009b91e, 0x5563911d, 0x59dfa6aa,
  2655. 0x78c14389, 0xd95a537f, 0x207d5ba2, 0x02e5b9c5,
  2656. 0x83260376, 0x6295cfa9, 0x11c81968, 0x4e734a41,
  2657. 0xb3472dca, 0x7b14a94a, 0x1b510052, 0x9a532915,
  2658. 0xd60f573f, 0xbc9bc6e4, 0x2b60a476, 0x81e67400,
  2659. 0x08ba6fb5, 0x571be91f, 0xf296ec6b, 0x2a0dd915,
  2660. 0xb6636521, 0xe7b9f9b6, 0xff34052e, 0xc5855664,
  2661. 0x53b02d5d, 0xa99f8fa1, 0x08ba4799, 0x6e85076a,
  2662. 0x4b7a70e9, 0xb5b32944, 0xdb75092e, 0xc4192623,
  2663. 0xad6ea6b0, 0x49a7df7d, 0x9cee60b8, 0x8fedb266,
  2664. 0xecaa8c71, 0x699a17ff, 0x5664526c, 0xc2b19ee1,
  2665. 0x193602a5, 0x75094c29, 0xa0591340, 0xe4183a3e,
  2666. 0x3f54989a, 0x5b429d65, 0x6b8fe4d6, 0x99f73fd6,
  2667. 0xa1d29c07, 0xefe830f5, 0x4d2d38e6, 0xf0255dc1,
  2668. 0x4cdd2086, 0x8470eb26, 0x6382e9c6, 0x021ecc5e,
  2669. 0x09686b3f, 0x3ebaefc9, 0x3c971814, 0x6b6a70a1,
  2670. 0x687f3584, 0x52a0e286, 0xb79c5305, 0xaa500737,
  2671. 0x3e07841c, 0x7fdeae5c, 0x8e7d44ec, 0x5716f2b8,
  2672. 0xb03ada37, 0xf0500c0d, 0xf01c1f04, 0x0200b3ff,
  2673. 0xae0cf51a, 0x3cb574b2, 0x25837a58, 0xdc0921bd,
  2674. 0xd19113f9, 0x7ca92ff6, 0x94324773, 0x22f54701,
  2675. 0x3ae5e581, 0x37c2dadc, 0xc8b57634, 0x9af3dda7,
  2676. 0xa9446146, 0x0fd0030e, 0xecc8c73e, 0xa4751e41,
  2677. 0xe238cd99, 0x3bea0e2f, 0x3280bba1, 0x183eb331,
  2678. 0x4e548b38, 0x4f6db908, 0x6f420d03, 0xf60a04bf,
  2679. 0x2cb81290, 0x24977c79, 0x5679b072, 0xbcaf89af,
  2680. 0xde9a771f, 0xd9930810, 0xb38bae12, 0xdccf3f2e,
  2681. 0x5512721f, 0x2e6b7124, 0x501adde6, 0x9f84cd87,
  2682. 0x7a584718, 0x7408da17, 0xbc9f9abc, 0xe94b7d8c,
  2683. 0xec7aec3a, 0xdb851dfa, 0x63094366, 0xc464c3d2,
  2684. 0xef1c1847, 0x3215d908, 0xdd433b37, 0x24c2ba16,
  2685. 0x12a14d43, 0x2a65c451, 0x50940002, 0x133ae4dd,
  2686. 0x71dff89e, 0x10314e55, 0x81ac77d6, 0x5f11199b,
  2687. 0x043556f1, 0xd7a3c76b, 0x3c11183b, 0x5924a509,
  2688. 0xf28fe6ed, 0x97f1fbfa, 0x9ebabf2c, 0x1e153c6e,
  2689. 0x86e34570, 0xeae96fb1, 0x860e5e0a, 0x5a3e2ab3,
  2690. 0x771fe71c, 0x4e3d06fa, 0x2965dcb9, 0x99e71d0f,
  2691. 0x803e89d6, 0x5266c825, 0x2e4cc978, 0x9c10b36a,
  2692. 0xc6150eba, 0x94e2ea78, 0xa5fc3c53, 0x1e0a2df4,
  2693. 0xf2f74ea7, 0x361d2b3d, 0x1939260f, 0x19c27960,
  2694. 0x5223a708, 0xf71312b6, 0xebadfe6e, 0xeac31f66,
  2695. 0xe3bc4595, 0xa67bc883, 0xb17f37d1, 0x018cff28,
  2696. 0xc332ddef, 0xbe6c5aa5, 0x65582185, 0x68ab9802,
  2697. 0xeecea50f, 0xdb2f953b, 0x2aef7dad, 0x5b6e2f84,
  2698. 0x1521b628, 0x29076170, 0xecdd4775, 0x619f1510,
  2699. 0x13cca830, 0xeb61bd96, 0x0334fe1e, 0xaa0363cf,
  2700. 0xb5735c90, 0x4c70a239, 0xd59e9e0b, 0xcbaade14,
  2701. 0xeecc86bc, 0x60622ca7, 0x9cab5cab, 0xb2f3846e,
  2702. 0x648b1eaf, 0x19bdf0ca, 0xa02369b9, 0x655abb50,
  2703. 0x40685a32, 0x3c2ab4b3, 0x319ee9d5, 0xc021b8f7,
  2704. 0x9b540b19, 0x875fa099, 0x95f7997e, 0x623d7da8,
  2705. 0xf837889a, 0x97e32d77, 0x11ed935f, 0x16681281,
  2706. 0x0e358829, 0xc7e61fd6, 0x96dedfa1, 0x7858ba99,
  2707. 0x57f584a5, 0x1b227263, 0x9b83c3ff, 0x1ac24696,
  2708. 0xcdb30aeb, 0x532e3054, 0x8fd948e4, 0x6dbc3128,
  2709. 0x58ebf2ef, 0x34c6ffea, 0xfe28ed61, 0xee7c3c73,
  2710. 0x5d4a14d9, 0xe864b7e3, 0x42105d14, 0x203e13e0,
  2711. 0x45eee2b6, 0xa3aaabea, 0xdb6c4f15, 0xfacb4fd0,
  2712. 0xc742f442, 0xef6abbb5, 0x654f3b1d, 0x41cd2105,
  2713. 0xd81e799e, 0x86854dc7, 0xe44b476a, 0x3d816250,
  2714. 0xcf62a1f2, 0x5b8d2646, 0xfc8883a0, 0xc1c7b6a3,
  2715. 0x7f1524c3, 0x69cb7492, 0x47848a0b, 0x5692b285,
  2716. 0x095bbf00, 0xad19489d, 0x1462b174, 0x23820e00,
  2717. 0x58428d2a, 0x0c55f5ea, 0x1dadf43e, 0x233f7061,
  2718. 0x3372f092, 0x8d937e41, 0xd65fecf1, 0x6c223bdb,
  2719. 0x7cde3759, 0xcbee7460, 0x4085f2a7, 0xce77326e,
  2720. 0xa6078084, 0x19f8509e, 0xe8efd855, 0x61d99735,
  2721. 0xa969a7aa, 0xc50c06c2, 0x5a04abfc, 0x800bcadc,
  2722. 0x9e447a2e, 0xc3453484, 0xfdd56705, 0x0e1e9ec9,
  2723. 0xdb73dbd3, 0x105588cd, 0x675fda79, 0xe3674340,
  2724. 0xc5c43465, 0x713e38d8, 0x3d28f89e, 0xf16dff20,
  2725. 0x153e21e7, 0x8fb03d4a, 0xe6e39f2b, 0xdb83adf7,
  2726. 0xe93d5a68, 0x948140f7, 0xf64c261c, 0x94692934,
  2727. 0x411520f7, 0x7602d4f7, 0xbcf46b2e, 0xd4a20068,
  2728. 0xd4082471, 0x3320f46a, 0x43b7d4b7, 0x500061af,
  2729. 0x1e39f62e, 0x97244546, 0x14214f74, 0xbf8b8840,
  2730. 0x4d95fc1d, 0x96b591af, 0x70f4ddd3, 0x66a02f45,
  2731. 0xbfbc09ec, 0x03bd9785, 0x7fac6dd0, 0x31cb8504,
  2732. 0x96eb27b3, 0x55fd3941, 0xda2547e6, 0xabca0a9a,
  2733. 0x28507825, 0x530429f4, 0x0a2c86da, 0xe9b66dfb,
  2734. 0x68dc1462, 0xd7486900, 0x680ec0a4, 0x27a18dee,
  2735. 0x4f3ffea2, 0xe887ad8c, 0xb58ce006, 0x7af4d6b6,
  2736. 0xaace1e7c, 0xd3375fec, 0xce78a399, 0x406b2a42,
  2737. 0x20fe9e35, 0xd9f385b9, 0xee39d7ab, 0x3b124e8b,
  2738. 0x1dc9faf7, 0x4b6d1856, 0x26a36631, 0xeae397b2,
  2739. 0x3a6efa74, 0xdd5b4332, 0x6841e7f7, 0xca7820fb,
  2740. 0xfb0af54e, 0xd8feb397, 0x454056ac, 0xba489527,
  2741. 0x55533a3a, 0x20838d87, 0xfe6ba9b7, 0xd096954b,
  2742. 0x55a867bc, 0xa1159a58, 0xcca92963, 0x99e1db33,
  2743. 0xa62a4a56, 0x3f3125f9, 0x5ef47e1c, 0x9029317c,
  2744. 0xfdf8e802, 0x04272f70, 0x80bb155c, 0x05282ce3,
  2745. 0x95c11548, 0xe4c66d22, 0x48c1133f, 0xc70f86dc,
  2746. 0x07f9c9ee, 0x41041f0f, 0x404779a4, 0x5d886e17,
  2747. 0x325f51eb, 0xd59bc0d1, 0xf2bcc18f, 0x41113564,
  2748. 0x257b7834, 0x602a9c60, 0xdff8e8a3, 0x1f636c1b,
  2749. 0x0e12b4c2, 0x02e1329e, 0xaf664fd1, 0xcad18115,
  2750. 0x6b2395e0, 0x333e92e1, 0x3b240b62, 0xeebeb922,
  2751. 0x85b2a20e, 0xe6ba0d99, 0xde720c8c, 0x2da2f728,
  2752. 0xd0127845, 0x95b794fd, 0x647d0862, 0xe7ccf5f0,
  2753. 0x5449a36f, 0x877d48fa, 0xc39dfd27, 0xf33e8d1e,
  2754. 0x0a476341, 0x992eff74, 0x3a6f6eab, 0xf4f8fd37,
  2755. 0xa812dc60, 0xa1ebddf8, 0x991be14c, 0xdb6e6b0d,
  2756. 0xc67b5510, 0x6d672c37, 0x2765d43b, 0xdcd0e804,
  2757. 0xf1290dc7, 0xcc00ffa3, 0xb5390f92, 0x690fed0b,
  2758. 0x667b9ffb, 0xcedb7d9c, 0xa091cf0b, 0xd9155ea3,
  2759. 0xbb132f88, 0x515bad24, 0x7b9479bf, 0x763bd6eb,
  2760. 0x37392eb3, 0xcc115979, 0x8026e297, 0xf42e312d,
  2761. 0x6842ada7, 0xc66a2b3b, 0x12754ccc, 0x782ef11c,
  2762. 0x6a124237, 0xb79251e7, 0x06a1bbe6, 0x4bfb6350,
  2763. 0x1a6b1018, 0x11caedfa, 0x3d25bdd8, 0xe2e1c3c9,
  2764. 0x44421659, 0x0a121386, 0xd90cec6e, 0xd5abea2a,
  2765. 0x64af674e, 0xda86a85f, 0xbebfe988, 0x64e4c3fe,
  2766. 0x9dbc8057, 0xf0f7c086, 0x60787bf8, 0x6003604d,
  2767. 0xd1fd8346, 0xf6381fb0, 0x7745ae04, 0xd736fccc,
  2768. 0x83426b33, 0xf01eab71, 0xb0804187, 0x3c005e5f,
  2769. 0x77a057be, 0xbde8ae24, 0x55464299, 0xbf582e61,
  2770. 0x4e58f48f, 0xf2ddfda2, 0xf474ef38, 0x8789bdc2,
  2771. 0x5366f9c3, 0xc8b38e74, 0xb475f255, 0x46fcd9b9,
  2772. 0x7aeb2661, 0x8b1ddf84, 0x846a0e79, 0x915f95e2,
  2773. 0x466e598e, 0x20b45770, 0x8cd55591, 0xc902de4c,
  2774. 0xb90bace1, 0xbb8205d0, 0x11a86248, 0x7574a99e,
  2775. 0xb77f19b6, 0xe0a9dc09, 0x662d09a1, 0xc4324633,
  2776. 0xe85a1f02, 0x09f0be8c, 0x4a99a025, 0x1d6efe10,
  2777. 0x1ab93d1d, 0x0ba5a4df, 0xa186f20f, 0x2868f169,
  2778. 0xdcb7da83, 0x573906fe, 0xa1e2ce9b, 0x4fcd7f52,
  2779. 0x50115e01, 0xa70683fa, 0xa002b5c4, 0x0de6d027,
  2780. 0x9af88c27, 0x773f8641, 0xc3604c06, 0x61a806b5,
  2781. 0xf0177a28, 0xc0f586e0, 0x006058aa, 0x30dc7d62,
  2782. 0x11e69ed7, 0x2338ea63, 0x53c2dd94, 0xc2c21634,
  2783. 0xbbcbee56, 0x90bcb6de, 0xebfc7da1, 0xce591d76,
  2784. 0x6f05e409, 0x4b7c0188, 0x39720a3d, 0x7c927c24,
  2785. 0x86e3725f, 0x724d9db9, 0x1ac15bb4, 0xd39eb8fc,
  2786. 0xed545578, 0x08fca5b5, 0xd83d7cd3, 0x4dad0fc4,
  2787. 0x1e50ef5e, 0xb161e6f8, 0xa28514d9, 0x6c51133c,
  2788. 0x6fd5c7e7, 0x56e14ec4, 0x362abfce, 0xddc6c837,
  2789. 0xd79a3234, 0x92638212, 0x670efa8e, 0x406000e0,
  2790. 0x3a39ce37, 0xd3faf5cf, 0xabc27737, 0x5ac52d1b,
  2791. 0x5cb0679e, 0x4fa33742, 0xd3822740, 0x99bc9bbe,
  2792. 0xd5118e9d, 0xbf0f7315, 0xd62d1c7e, 0xc700c47b,
  2793. 0xb78c1b6b, 0x21a19045, 0xb26eb1be, 0x6a366eb4,
  2794. 0x5748ab2f, 0xbc946e79, 0xc6a376d2, 0x6549c2c8,
  2795. 0x530ff8ee, 0x468dde7d, 0xd5730a1d, 0x4cd04dc6,
  2796. 0x2939bbdb, 0xa9ba4650, 0xac9526e8, 0xbe5ee304,
  2797. 0xa1fad5f0, 0x6a2d519a, 0x63ef8ce2, 0x9a86ee22,
  2798. 0xc089c2b8, 0x43242ef6, 0xa51e03aa, 0x9cf2d0a4,
  2799. 0x83c061ba, 0x9be96a4d, 0x8fe51550, 0xba645bd6,
  2800. 0x2826a2f9, 0xa73a3ae1, 0x4ba99586, 0xef5562e9,
  2801. 0xc72fefd3, 0xf752f7da, 0x3f046f69, 0x77fa0a59,
  2802. 0x80e4a915, 0x87b08601, 0x9b09e6ad, 0x3b3ee593,
  2803. 0xe990fd5a, 0x9e34d797, 0x2cf0b7d9, 0x022b8b51,
  2804. 0x96d5ac3a, 0x017da67d, 0xd1cf3ed6, 0x7c7d2d28,
  2805. 0x1f9f25cf, 0xadf2b89b, 0x5ad6b472, 0x5a88f54c,
  2806. 0xe029ac71, 0xe019a5e6, 0x47b0acfd, 0xed93fa9b,
  2807. 0xe8d3c48d, 0x283b57cc, 0xf8d56629, 0x79132e28,
  2808. 0x785f0191, 0xed756055, 0xf7960e44, 0xe3d35e8c,
  2809. 0x15056dd4, 0x88f46dba, 0x03a16125, 0x0564f0bd,
  2810. 0xc3eb9e15, 0x3c9057a2, 0x97271aec, 0xa93a072a,
  2811. 0x1b3f6d9b, 0x1e6321f5, 0xf59c66fb, 0x26dcf319,
  2812. 0x7533d928, 0xb155fdf5, 0x03563482, 0x8aba3cbb,
  2813. 0x28517711, 0xc20ad9f8, 0xabcc5167, 0xccad925f,
  2814. 0x4de81751, 0x3830dc8e, 0x379d5862, 0x9320f991,
  2815. 0xea7a90c2, 0xfb3e7bce, 0x5121ce64, 0x774fbe32,
  2816. 0xa8b6e37e, 0xc3293d46, 0x48de5369, 0x6413e680,
  2817. 0xa2ae0810, 0xdd6db224, 0x69852dfd, 0x09072166,
  2818. 0xb39a460a, 0x6445c0dd, 0x586cdecf, 0x1c20c8ae,
  2819. 0x5bbef7dd, 0x1b588d40, 0xccd2017f, 0x6bb4e3bb,
  2820. 0xdda26a7e, 0x3a59ff45, 0x3e350a44, 0xbcb4cdd5,
  2821. 0x72eacea8, 0xfa6484bb, 0x8d6612ae, 0xbf3c6f47,
  2822. 0xd29be463, 0x542f5d9e, 0xaec2771b, 0xf64e6370,
  2823. 0x740e0d8d, 0xe75b1357, 0xf8721671, 0xaf537d5d,
  2824. 0x4040cb08, 0x4eb4e2cc, 0x34d2466a, 0x0115af84,
  2825. 0xe1b00428, 0x95983a1d, 0x06b89fb4, 0xce6ea048,
  2826. 0x6f3f3b82, 0x3520ab82, 0x011a1d4b, 0x277227f8,
  2827. 0x611560b1, 0xe7933fdc, 0xbb3a792b, 0x344525bd,
  2828. 0xa08839e1, 0x51ce794b, 0x2f32c9b7, 0xa01fbac9,
  2829. 0xe01cc87e, 0xbcc7d1f6, 0xcf0111c3, 0xa1e8aac7,
  2830. 0x1a908749, 0xd44fbd9a, 0xd0dadecb, 0xd50ada38,
  2831. 0x0339c32a, 0xc6913667, 0x8df9317c, 0xe0b12b4f,
  2832. 0xf79e59b7, 0x43f5bb3a, 0xf2d519ff, 0x27d9459c,
  2833. 0xbf97222c, 0x15e6fc2a, 0x0f91fc71, 0x9b941525,
  2834. 0xfae59361, 0xceb69ceb, 0xc2a86459, 0x12baa8d1,
  2835. 0xb6c1075e, 0xe3056a0c, 0x10d25065, 0xcb03a442,
  2836. 0xe0ec6e0e, 0x1698db3b, 0x4c98a0be, 0x3278e964,
  2837. 0x9f1f9532, 0xe0d392df, 0xd3a0342b, 0x8971f21e,
  2838. 0x1b0a7441, 0x4ba3348c, 0xc5be7120, 0xc37632d8,
  2839. 0xdf359f8d, 0x9b992f2e, 0xe60b6f47, 0x0fe3f11d,
  2840. 0xe54cda54, 0x1edad891, 0xce6279cf, 0xcd3e7e6f,
  2841. 0x1618b166, 0xfd2c1d05, 0x848fd2c5, 0xf6fb2299,
  2842. 0xf523f357, 0xa6327623, 0x93a83531, 0x56cccd02,
  2843. 0xacf08162, 0x5a75ebb5, 0x6e163697, 0x88d273cc,
  2844. 0xde966292, 0x81b949d0, 0x4c50901b, 0x71c65614,
  2845. 0xe6c6c7bd, 0x327a140a, 0x45e1d006, 0xc3f27b9a,
  2846. 0xc9aa53fd, 0x62a80f00, 0xbb25bfe2, 0x35bdd2f6,
  2847. 0x71126905, 0xb2040222, 0xb6cbcf7c, 0xcd769c2b,
  2848. 0x53113ec0, 0x1640e3d3, 0x38abbd60, 0x2547adf0,
  2849. 0xba38209c, 0xf746ce76, 0x77afa1c5, 0x20756060,
  2850. 0x85cbfe4e, 0x8ae88dd8, 0x7aaaf9b0, 0x4cf9aa7e,
  2851. 0x1948c25c, 0x02fb8a8c, 0x01c36ae4, 0xd6ebe1f9,
  2852. 0x90d4f869, 0xa65cdea0, 0x3f09252d, 0xc208e69f,
  2853. 0xb74e6132, 0xce77e25b, 0x578fdfe3, 0x3ac372e6
  2854. };
  2855. BlowFish::BlowFish (const uint8* keyData, int keyBytes)
  2856. {
  2857. memcpy (p, initialPValues, sizeof (p));
  2858. int i, j;
  2859. for (i = 4; --i >= 0;)
  2860. {
  2861. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  2862. memcpy (s[i], initialSValues + i * 256, 256 * sizeof (uint32));
  2863. }
  2864. j = 0;
  2865. for (i = 0; i < 18; ++i)
  2866. {
  2867. uint32 d = 0;
  2868. for (int k = 0; k < 4; ++k)
  2869. {
  2870. d = (d << 8) | keyData[j];
  2871. if (++j >= keyBytes)
  2872. j = 0;
  2873. }
  2874. p[i] = initialPValues[i] ^ d;
  2875. }
  2876. uint32 l = 0, r = 0;
  2877. for (i = 0; i < 18; i += 2)
  2878. {
  2879. encrypt (l, r);
  2880. p[i] = l;
  2881. p[i + 1] = r;
  2882. }
  2883. for (i = 0; i < 4; ++i)
  2884. {
  2885. for (j = 0; j < 256; j += 2)
  2886. {
  2887. encrypt (l, r);
  2888. s[i][j] = l;
  2889. s[i][j + 1] = r;
  2890. }
  2891. }
  2892. }
  2893. BlowFish::BlowFish (const BlowFish& other)
  2894. {
  2895. for (int i = 4; --i >= 0;)
  2896. s[i] = (uint32*) juce_malloc (256 * sizeof (uint32));
  2897. operator= (other);
  2898. }
  2899. const BlowFish& BlowFish::operator= (const BlowFish& other)
  2900. {
  2901. memcpy (p, other.p, sizeof (p));
  2902. for (int i = 4; --i >= 0;)
  2903. memcpy (s[i], other.s[i], 256 * sizeof (uint32));
  2904. return *this;
  2905. }
  2906. BlowFish::~BlowFish()
  2907. {
  2908. for (int i = 4; --i >= 0;)
  2909. juce_free (s[i]);
  2910. }
  2911. uint32 BlowFish::F (uint32 x) const
  2912. {
  2913. uint16 a, b, c, d;
  2914. uint32 y;
  2915. d = (uint16) (x & 0xff);
  2916. x >>= 8;
  2917. c = (uint16) (x & 0xff);
  2918. x >>= 8;
  2919. b = (uint16) (x & 0xff);
  2920. x >>= 8;
  2921. a = (uint16) (x & 0xff);
  2922. y = s[0][a] + s[1][b];
  2923. y = y ^ s[2][c];
  2924. y = y + s[3][d];
  2925. return y;
  2926. }
  2927. void BlowFish::encrypt (uint32& data1,
  2928. uint32& data2) const
  2929. {
  2930. uint32 l = data1;
  2931. uint32 r = data2;
  2932. for (int i = 0; i < 16; ++i)
  2933. {
  2934. l = l ^ p[i];
  2935. r = F (l) ^ r;
  2936. const uint32 temp = l;
  2937. l = r;
  2938. r = temp;
  2939. }
  2940. const uint32 temp = l;
  2941. l = r;
  2942. r = temp;
  2943. r = r ^ p[16];
  2944. l = l ^ p[17];
  2945. data1 = l;
  2946. data2 = r;
  2947. }
  2948. void BlowFish::decrypt (uint32& data1,
  2949. uint32& data2) const
  2950. {
  2951. uint32 l = data1;
  2952. uint32 r = data2;
  2953. for (int i = 17; i > 1; --i)
  2954. {
  2955. l =l ^ p[i];
  2956. r = F (l) ^ r;
  2957. const uint32 temp = l;
  2958. l = r;
  2959. r = temp;
  2960. }
  2961. const uint32 temp = l;
  2962. l = r;
  2963. r = temp;
  2964. r = r ^ p[1];
  2965. l = l ^ p[0];
  2966. data1 = l;
  2967. data2 = r;
  2968. }
  2969. END_JUCE_NAMESPACE
  2970. /********* End of inlined file: juce_BlowFish.cpp *********/
  2971. /********* Start of inlined file: juce_MD5.cpp *********/
  2972. BEGIN_JUCE_NAMESPACE
  2973. MD5::MD5()
  2974. {
  2975. zeromem (result, sizeof (result));
  2976. }
  2977. MD5::MD5 (const MD5& other)
  2978. {
  2979. memcpy (result, other.result, sizeof (result));
  2980. }
  2981. const MD5& MD5::operator= (const MD5& other)
  2982. {
  2983. memcpy (result, other.result, sizeof (result));
  2984. return *this;
  2985. }
  2986. MD5::MD5 (const MemoryBlock& data)
  2987. {
  2988. ProcessContext context;
  2989. context.processBlock ((const uint8*) data.getData(), data.getSize());
  2990. context.finish (result);
  2991. }
  2992. MD5::MD5 (const char* data, const int numBytes)
  2993. {
  2994. ProcessContext context;
  2995. context.processBlock ((const uint8*) data, numBytes);
  2996. context.finish (result);
  2997. }
  2998. MD5::MD5 (const String& text)
  2999. {
  3000. ProcessContext context;
  3001. const int len = text.length();
  3002. const juce_wchar* const t = text;
  3003. for (int i = 0; i < len; ++i)
  3004. {
  3005. // force the string into integer-sized unicode characters, to try to make it
  3006. // get the same results on all platforms + compilers.
  3007. uint32 unicodeChar = (uint32) t[i];
  3008. swapIfBigEndian (unicodeChar);
  3009. context.processBlock ((const uint8*) &unicodeChar,
  3010. sizeof (unicodeChar));
  3011. }
  3012. context.finish (result);
  3013. }
  3014. void MD5::processStream (InputStream& input, int numBytesToRead)
  3015. {
  3016. ProcessContext context;
  3017. if (numBytesToRead < 0)
  3018. numBytesToRead = INT_MAX;
  3019. while (numBytesToRead > 0)
  3020. {
  3021. char tempBuffer [512];
  3022. const int bytesRead = input.read (tempBuffer, jmin (numBytesToRead, sizeof (tempBuffer)));
  3023. if (bytesRead <= 0)
  3024. break;
  3025. numBytesToRead -= bytesRead;
  3026. context.processBlock ((const uint8*) tempBuffer, bytesRead);
  3027. }
  3028. context.finish (result);
  3029. }
  3030. MD5::MD5 (InputStream& input, int numBytesToRead)
  3031. {
  3032. processStream (input, numBytesToRead);
  3033. }
  3034. MD5::MD5 (const File& file)
  3035. {
  3036. FileInputStream* const fin = file.createInputStream();
  3037. if (fin != 0)
  3038. {
  3039. processStream (*fin, -1);
  3040. delete fin;
  3041. }
  3042. else
  3043. {
  3044. zeromem (result, sizeof (result));
  3045. }
  3046. }
  3047. MD5::~MD5()
  3048. {
  3049. }
  3050. MD5::ProcessContext::ProcessContext()
  3051. {
  3052. state[0] = 0x67452301;
  3053. state[1] = 0xefcdab89;
  3054. state[2] = 0x98badcfe;
  3055. state[3] = 0x10325476;
  3056. count[0] = 0;
  3057. count[1] = 0;
  3058. }
  3059. void MD5::ProcessContext::processBlock (const uint8* const data, int dataSize)
  3060. {
  3061. int bufferPos = ((count[0] >> 3) & 0x3F);
  3062. count[0] += (dataSize << 3);
  3063. if (count[0] < ((uint32) dataSize << 3))
  3064. count[1]++;
  3065. count[1] += (dataSize >> 29);
  3066. const int spaceLeft = 64 - bufferPos;
  3067. int i = 0;
  3068. if (dataSize >= spaceLeft)
  3069. {
  3070. memcpy (buffer + bufferPos, data, spaceLeft);
  3071. transform (buffer);
  3072. i = spaceLeft;
  3073. while (i < dataSize - 63)
  3074. {
  3075. transform (data + i);
  3076. i += 64;
  3077. }
  3078. bufferPos = 0;
  3079. }
  3080. memcpy (buffer + bufferPos, data + i, dataSize - i);
  3081. }
  3082. static void encode (uint8* const output,
  3083. const uint32* const input,
  3084. const int numBytes)
  3085. {
  3086. uint32* const o = (uint32*) output;
  3087. for (int i = 0; i < (numBytes >> 2); ++i)
  3088. o[i] = swapIfBigEndian (input [i]);
  3089. }
  3090. static void decode (uint32* const output,
  3091. const uint8* const input,
  3092. const int numBytes)
  3093. {
  3094. for (int i = 0; i < (numBytes >> 2); ++i)
  3095. output[i] = littleEndianInt ((const char*) input + (i << 2));
  3096. }
  3097. void MD5::ProcessContext::finish (uint8* const result)
  3098. {
  3099. unsigned char encodedLength[8];
  3100. encode (encodedLength, count, 8);
  3101. // Pad out to 56 mod 64.
  3102. const int index = (uint32) ((count[0] >> 3) & 0x3f);
  3103. const int paddingLength = (index < 56) ? (56 - index)
  3104. : (120 - index);
  3105. uint8 paddingBuffer [64];
  3106. zeromem (paddingBuffer, paddingLength);
  3107. paddingBuffer [0] = 0x80;
  3108. processBlock (paddingBuffer, paddingLength);
  3109. processBlock (encodedLength, 8);
  3110. encode (result, state, 16);
  3111. zeromem (buffer, sizeof (buffer));
  3112. }
  3113. #define S11 7
  3114. #define S12 12
  3115. #define S13 17
  3116. #define S14 22
  3117. #define S21 5
  3118. #define S22 9
  3119. #define S23 14
  3120. #define S24 20
  3121. #define S31 4
  3122. #define S32 11
  3123. #define S33 16
  3124. #define S34 23
  3125. #define S41 6
  3126. #define S42 10
  3127. #define S43 15
  3128. #define S44 21
  3129. static inline uint32 F (const uint32 x, const uint32 y, const uint32 z) { return (x & y) | (~x & z); }
  3130. static inline uint32 G (const uint32 x, const uint32 y, const uint32 z) { return (x & z) | (y & ~z); }
  3131. static inline uint32 H (const uint32 x, const uint32 y, const uint32 z) { return x ^ y ^ z; }
  3132. static inline uint32 I (const uint32 x, const uint32 y, const uint32 z) { return y ^ (x | ~z); }
  3133. static inline uint32 rotateLeft (const uint32 x, const uint32 n) { return (x << n) | (x >> (32 - n)); }
  3134. static inline void FF (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3135. {
  3136. a += F (b, c, d) + x + ac;
  3137. a = rotateLeft (a, s) + b;
  3138. }
  3139. static inline void GG (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3140. {
  3141. a += G (b, c, d) + x + ac;
  3142. a = rotateLeft (a, s) + b;
  3143. }
  3144. static inline void HH (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3145. {
  3146. a += H (b, c, d) + x + ac;
  3147. a = rotateLeft (a, s) + b;
  3148. }
  3149. static inline void II (uint32& a, const uint32 b, const uint32 c, const uint32 d, const uint32 x, const uint32 s, const uint32 ac)
  3150. {
  3151. a += I (b, c, d) + x + ac;
  3152. a = rotateLeft (a, s) + b;
  3153. }
  3154. void MD5::ProcessContext::transform (const uint8* const buffer)
  3155. {
  3156. uint32 a = state[0];
  3157. uint32 b = state[1];
  3158. uint32 c = state[2];
  3159. uint32 d = state[3];
  3160. uint32 x[16];
  3161. decode (x, buffer, 64);
  3162. FF (a, b, c, d, x[ 0], S11, 0xd76aa478); /* 1 */
  3163. FF (d, a, b, c, x[ 1], S12, 0xe8c7b756); /* 2 */
  3164. FF (c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
  3165. FF (b, c, d, a, x[ 3], S14, 0xc1bdceee); /* 4 */
  3166. FF (a, b, c, d, x[ 4], S11, 0xf57c0faf); /* 5 */
  3167. FF (d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
  3168. FF (c, d, a, b, x[ 6], S13, 0xa8304613); /* 7 */
  3169. FF (b, c, d, a, x[ 7], S14, 0xfd469501); /* 8 */
  3170. FF (a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
  3171. FF (d, a, b, c, x[ 9], S12, 0x8b44f7af); /* 10 */
  3172. FF (c, d, a, b, x[10], S13, 0xffff5bb1); /* 11 */
  3173. FF (b, c, d, a, x[11], S14, 0x895cd7be); /* 12 */
  3174. FF (a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
  3175. FF (d, a, b, c, x[13], S12, 0xfd987193); /* 14 */
  3176. FF (c, d, a, b, x[14], S13, 0xa679438e); /* 15 */
  3177. FF (b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
  3178. GG (a, b, c, d, x[ 1], S21, 0xf61e2562); /* 17 */
  3179. GG (d, a, b, c, x[ 6], S22, 0xc040b340); /* 18 */
  3180. GG (c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
  3181. GG (b, c, d, a, x[ 0], S24, 0xe9b6c7aa); /* 20 */
  3182. GG (a, b, c, d, x[ 5], S21, 0xd62f105d); /* 21 */
  3183. GG (d, a, b, c, x[10], S22, 0x2441453); /* 22 */
  3184. GG (c, d, a, b, x[15], S23, 0xd8a1e681); /* 23 */
  3185. GG (b, c, d, a, x[ 4], S24, 0xe7d3fbc8); /* 24 */
  3186. GG (a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
  3187. GG (d, a, b, c, x[14], S22, 0xc33707d6); /* 26 */
  3188. GG (c, d, a, b, x[ 3], S23, 0xf4d50d87); /* 27 */
  3189. GG (b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
  3190. GG (a, b, c, d, x[13], S21, 0xa9e3e905); /* 29 */
  3191. GG (d, a, b, c, x[ 2], S22, 0xfcefa3f8); /* 30 */
  3192. GG (c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
  3193. GG (b, c, d, a, x[12], S24, 0x8d2a4c8a); /* 32 */
  3194. HH (a, b, c, d, x[ 5], S31, 0xfffa3942); /* 33 */
  3195. HH (d, a, b, c, x[ 8], S32, 0x8771f681); /* 34 */
  3196. HH (c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
  3197. HH (b, c, d, a, x[14], S34, 0xfde5380c); /* 36 */
  3198. HH (a, b, c, d, x[ 1], S31, 0xa4beea44); /* 37 */
  3199. HH (d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
  3200. HH (c, d, a, b, x[ 7], S33, 0xf6bb4b60); /* 39 */
  3201. HH (b, c, d, a, x[10], S34, 0xbebfbc70); /* 40 */
  3202. HH (a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
  3203. HH (d, a, b, c, x[ 0], S32, 0xeaa127fa); /* 42 */
  3204. HH (c, d, a, b, x[ 3], S33, 0xd4ef3085); /* 43 */
  3205. HH (b, c, d, a, x[ 6], S34, 0x4881d05); /* 44 */
  3206. HH (a, b, c, d, x[ 9], S31, 0xd9d4d039); /* 45 */
  3207. HH (d, a, b, c, x[12], S32, 0xe6db99e5); /* 46 */
  3208. HH (c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
  3209. HH (b, c, d, a, x[ 2], S34, 0xc4ac5665); /* 48 */
  3210. II (a, b, c, d, x[ 0], S41, 0xf4292244); /* 49 */
  3211. II (d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
  3212. II (c, d, a, b, x[14], S43, 0xab9423a7); /* 51 */
  3213. II (b, c, d, a, x[ 5], S44, 0xfc93a039); /* 52 */
  3214. II (a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
  3215. II (d, a, b, c, x[ 3], S42, 0x8f0ccc92); /* 54 */
  3216. II (c, d, a, b, x[10], S43, 0xffeff47d); /* 55 */
  3217. II (b, c, d, a, x[ 1], S44, 0x85845dd1); /* 56 */
  3218. II (a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
  3219. II (d, a, b, c, x[15], S42, 0xfe2ce6e0); /* 58 */
  3220. II (c, d, a, b, x[ 6], S43, 0xa3014314); /* 59 */
  3221. II (b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
  3222. II (a, b, c, d, x[ 4], S41, 0xf7537e82); /* 61 */
  3223. II (d, a, b, c, x[11], S42, 0xbd3af235); /* 62 */
  3224. II (c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
  3225. II (b, c, d, a, x[ 9], S44, 0xeb86d391); /* 64 */
  3226. state[0] += a;
  3227. state[1] += b;
  3228. state[2] += c;
  3229. state[3] += d;
  3230. zeromem (x, sizeof (x));
  3231. }
  3232. const MemoryBlock MD5::getRawChecksumData() const
  3233. {
  3234. return MemoryBlock (result, 16);
  3235. }
  3236. const String MD5::toHexString() const
  3237. {
  3238. return String::toHexString (result, 16, 0);
  3239. }
  3240. bool MD5::operator== (const MD5& other) const
  3241. {
  3242. return memcmp (result, other.result, 16) == 0;
  3243. }
  3244. bool MD5::operator!= (const MD5& other) const
  3245. {
  3246. return ! operator== (other);
  3247. }
  3248. END_JUCE_NAMESPACE
  3249. /********* End of inlined file: juce_MD5.cpp *********/
  3250. /********* Start of inlined file: juce_Primes.cpp *********/
  3251. BEGIN_JUCE_NAMESPACE
  3252. static void createSmallSieve (const int numBits, BitArray& result) throw()
  3253. {
  3254. result.setBit (numBits);
  3255. result.clearBit (numBits); // to enlarge the array
  3256. result.setBit (0);
  3257. int n = 2;
  3258. do
  3259. {
  3260. for (int i = n + n; i < numBits; i += n)
  3261. result.setBit (i);
  3262. n = result.findNextClearBit (n + 1);
  3263. }
  3264. while (n <= (numBits >> 1));
  3265. }
  3266. static void bigSieve (const BitArray& base,
  3267. const int numBits,
  3268. BitArray& result,
  3269. const BitArray& smallSieve,
  3270. const int smallSieveSize) throw()
  3271. {
  3272. jassert (! base[0]); // must be even!
  3273. result.setBit (numBits);
  3274. result.clearBit (numBits); // to enlarge the array
  3275. int index = smallSieve.findNextClearBit (0);
  3276. do
  3277. {
  3278. const int prime = (index << 1) + 1;
  3279. BitArray r (base);
  3280. BitArray remainder;
  3281. r.divideBy (prime, remainder);
  3282. int i = prime - remainder.getBitRangeAsInt (0, 32);
  3283. if (r.isEmpty())
  3284. i += prime;
  3285. if ((i & 1) == 0)
  3286. i += prime;
  3287. i = (i - 1) >> 1;
  3288. while (i < numBits)
  3289. {
  3290. result.setBit (i);
  3291. i += prime;
  3292. }
  3293. index = smallSieve.findNextClearBit (index + 1);
  3294. }
  3295. while (index < smallSieveSize);
  3296. }
  3297. static bool findCandidate (const BitArray& base,
  3298. const BitArray& sieve,
  3299. const int numBits,
  3300. BitArray& result,
  3301. const int certainty) throw()
  3302. {
  3303. for (int i = 0; i < numBits; ++i)
  3304. {
  3305. if (! sieve[i])
  3306. {
  3307. result = base;
  3308. result.add (BitArray ((unsigned int) ((i << 1) + 1)));
  3309. if (Primes::isProbablyPrime (result, certainty))
  3310. return true;
  3311. }
  3312. }
  3313. return false;
  3314. }
  3315. const BitArray Primes::createProbablePrime (const int bitLength,
  3316. const int certainty) throw()
  3317. {
  3318. BitArray smallSieve;
  3319. const int smallSieveSize = 15000;
  3320. createSmallSieve (smallSieveSize, smallSieve);
  3321. BitArray p;
  3322. p.fillBitsRandomly (0, bitLength);
  3323. p.setBit (bitLength - 1);
  3324. p.clearBit (0);
  3325. const int searchLen = jmax (1024, (bitLength / 20) * 64);
  3326. while (p.getHighestBit() < bitLength)
  3327. {
  3328. p.add (2 * searchLen);
  3329. BitArray sieve;
  3330. bigSieve (p, searchLen, sieve,
  3331. smallSieve, smallSieveSize);
  3332. BitArray candidate;
  3333. if (findCandidate (p, sieve, searchLen, candidate, certainty))
  3334. return candidate;
  3335. }
  3336. jassertfalse
  3337. return BitArray();
  3338. }
  3339. static bool passesMillerRabin (const BitArray& n, int iterations) throw()
  3340. {
  3341. const BitArray one (1);
  3342. const BitArray two (2);
  3343. BitArray nMinusOne (n);
  3344. nMinusOne.subtract (one);
  3345. BitArray d (nMinusOne);
  3346. const int s = d.findNextSetBit (0);
  3347. d.shiftBits (-s);
  3348. BitArray smallPrimes;
  3349. int numBitsInSmallPrimes = 0;
  3350. for (;;)
  3351. {
  3352. numBitsInSmallPrimes += 256;
  3353. createSmallSieve (numBitsInSmallPrimes, smallPrimes);
  3354. const int numPrimesFound = numBitsInSmallPrimes - smallPrimes.countNumberOfSetBits();
  3355. if (numPrimesFound > iterations + 1)
  3356. break;
  3357. }
  3358. int smallPrime = 2;
  3359. while (--iterations >= 0)
  3360. {
  3361. smallPrime = smallPrimes.findNextClearBit (smallPrime + 1);
  3362. BitArray r (smallPrime);
  3363. //r.createRandomNumber (nMinusOne);
  3364. r.exponentModulo (d, n);
  3365. if (! (r == one || r == nMinusOne))
  3366. {
  3367. for (int j = 0; j < s; ++j)
  3368. {
  3369. r.exponentModulo (two, n);
  3370. if (r == nMinusOne)
  3371. break;
  3372. }
  3373. if (r != nMinusOne)
  3374. return false;
  3375. }
  3376. }
  3377. return true;
  3378. }
  3379. bool Primes::isProbablyPrime (const BitArray& number,
  3380. const int certainty) throw()
  3381. {
  3382. if (! number[0])
  3383. return false;
  3384. if (number.getHighestBit() <= 10)
  3385. {
  3386. const int num = number.getBitRangeAsInt (0, 10);
  3387. for (int i = num / 2; --i > 1;)
  3388. if (num % i == 0)
  3389. return false;
  3390. return true;
  3391. }
  3392. else
  3393. {
  3394. const BitArray screen (2 * 3 * 5 * 7 * 11 * 13 * 17 * 19 * 23);
  3395. if (number.findGreatestCommonDivisor (screen) != BitArray (1))
  3396. return false;
  3397. return passesMillerRabin (number, certainty);
  3398. }
  3399. }
  3400. END_JUCE_NAMESPACE
  3401. /********* End of inlined file: juce_Primes.cpp *********/
  3402. /********* Start of inlined file: juce_RSAKey.cpp *********/
  3403. BEGIN_JUCE_NAMESPACE
  3404. RSAKey::RSAKey() throw()
  3405. {
  3406. }
  3407. RSAKey::RSAKey (const String& s) throw()
  3408. {
  3409. if (s.containsChar (T(',')))
  3410. {
  3411. part1.parseString (s.upToFirstOccurrenceOf (T(","), false, false), 16);
  3412. part2.parseString (s.fromFirstOccurrenceOf (T(","), false, false), 16);
  3413. }
  3414. else
  3415. {
  3416. // the string needs to be two hex numbers, comma-separated..
  3417. jassertfalse;
  3418. }
  3419. }
  3420. RSAKey::~RSAKey() throw()
  3421. {
  3422. }
  3423. const String RSAKey::toString() const throw()
  3424. {
  3425. return part1.toString (16) + T(",") + part2.toString (16);
  3426. }
  3427. bool RSAKey::applyToValue (BitArray& value) const throw()
  3428. {
  3429. if (part1.isEmpty() || part2.isEmpty()
  3430. || value.compare (0) <= 0)
  3431. {
  3432. jassertfalse // using an uninitialised key
  3433. value.clear();
  3434. return false;
  3435. }
  3436. BitArray result;
  3437. while (! value.isEmpty())
  3438. {
  3439. result.multiplyBy (part2);
  3440. BitArray remainder;
  3441. value.divideBy (part2, remainder);
  3442. remainder.exponentModulo (part1, part2);
  3443. result.add (remainder);
  3444. }
  3445. value = result;
  3446. return true;
  3447. }
  3448. static const BitArray findBestCommonDivisor (const BitArray& p,
  3449. const BitArray& q) throw()
  3450. {
  3451. const BitArray one (1);
  3452. // try 3, 5, 9, 17, etc first because these only contain 2 bits and so
  3453. // are fast to divide + multiply
  3454. for (int i = 2; i <= 65536; i *= 2)
  3455. {
  3456. const BitArray e (1 + i);
  3457. if (e.findGreatestCommonDivisor (p) == one
  3458. && e.findGreatestCommonDivisor (q) == one)
  3459. {
  3460. return e;
  3461. }
  3462. }
  3463. BitArray e (4);
  3464. while (! (e.findGreatestCommonDivisor (p) == one
  3465. && e.findGreatestCommonDivisor (q) == one))
  3466. {
  3467. e.add (one);
  3468. }
  3469. return e;
  3470. }
  3471. void RSAKey::createKeyPair (RSAKey& publicKey,
  3472. RSAKey& privateKey,
  3473. const int numBits) throw()
  3474. {
  3475. jassert (numBits > 16); // not much point using less than this..
  3476. BitArray p (Primes::createProbablePrime (numBits / 2, 30));
  3477. BitArray q (Primes::createProbablePrime (numBits - numBits / 2, 30));
  3478. BitArray n (p);
  3479. n.multiplyBy (q); // n = pq
  3480. const BitArray one (1);
  3481. p.subtract (one);
  3482. q.subtract (one);
  3483. BitArray m (p);
  3484. m.multiplyBy (q); // m = (p - 1)(q - 1)
  3485. const BitArray e (findBestCommonDivisor (p, q));
  3486. BitArray d (e);
  3487. d.inverseModulo (m);
  3488. publicKey.part1 = e;
  3489. publicKey.part2 = n;
  3490. privateKey.part1 = d;
  3491. privateKey.part2 = n;
  3492. }
  3493. END_JUCE_NAMESPACE
  3494. /********* End of inlined file: juce_RSAKey.cpp *********/
  3495. /********* Start of inlined file: juce_InputStream.cpp *********/
  3496. BEGIN_JUCE_NAMESPACE
  3497. char InputStream::readByte()
  3498. {
  3499. char temp = 0;
  3500. read (&temp, 1);
  3501. return temp;
  3502. }
  3503. bool InputStream::readBool()
  3504. {
  3505. return readByte() != 0;
  3506. }
  3507. short InputStream::readShort()
  3508. {
  3509. char temp [2];
  3510. if (read (temp, 2) == 2)
  3511. return (short) littleEndianShort (temp);
  3512. else
  3513. return 0;
  3514. }
  3515. short InputStream::readShortBigEndian()
  3516. {
  3517. char temp [2];
  3518. if (read (temp, 2) == 2)
  3519. return (short) bigEndianShort (temp);
  3520. else
  3521. return 0;
  3522. }
  3523. int InputStream::readInt()
  3524. {
  3525. char temp [4];
  3526. if (read (temp, 4) == 4)
  3527. return (int) littleEndianInt (temp);
  3528. else
  3529. return 0;
  3530. }
  3531. int InputStream::readIntBigEndian()
  3532. {
  3533. char temp [4];
  3534. if (read (temp, 4) == 4)
  3535. return (int) bigEndianInt (temp);
  3536. else
  3537. return 0;
  3538. }
  3539. int InputStream::readCompressedInt()
  3540. {
  3541. int num = 0;
  3542. if (! isExhausted())
  3543. {
  3544. unsigned char numBytes = readByte();
  3545. const bool negative = (numBytes & 0x80) != 0;
  3546. numBytes &= 0x7f;
  3547. if (numBytes <= 4)
  3548. {
  3549. if (read (&num, numBytes) != numBytes)
  3550. return 0;
  3551. if (negative)
  3552. num = -num;
  3553. }
  3554. }
  3555. return num;
  3556. }
  3557. int64 InputStream::readInt64()
  3558. {
  3559. char temp [8];
  3560. if (read (temp, 8) == 8)
  3561. return (int64) swapIfBigEndian (*(uint64*)temp);
  3562. else
  3563. return 0;
  3564. }
  3565. int64 InputStream::readInt64BigEndian()
  3566. {
  3567. char temp [8];
  3568. if (read (temp, 8) == 8)
  3569. return (int64) swapIfLittleEndian (*(uint64*)temp);
  3570. else
  3571. return 0;
  3572. }
  3573. float InputStream::readFloat()
  3574. {
  3575. union { int asInt; float asFloat; } n;
  3576. n.asInt = readInt();
  3577. return n.asFloat;
  3578. }
  3579. float InputStream::readFloatBigEndian()
  3580. {
  3581. union { int asInt; float asFloat; } n;
  3582. n.asInt = readIntBigEndian();
  3583. return n.asFloat;
  3584. }
  3585. double InputStream::readDouble()
  3586. {
  3587. union { int64 asInt; double asDouble; } n;
  3588. n.asInt = readInt64();
  3589. return n.asDouble;
  3590. }
  3591. double InputStream::readDoubleBigEndian()
  3592. {
  3593. union { int64 asInt; double asDouble; } n;
  3594. n.asInt = readInt64BigEndian();
  3595. return n.asDouble;
  3596. }
  3597. const String InputStream::readString()
  3598. {
  3599. const int tempBufferSize = 256;
  3600. uint8 temp [tempBufferSize];
  3601. int i = 0;
  3602. while ((temp [i++] = readByte()) != 0)
  3603. {
  3604. if (i == tempBufferSize)
  3605. {
  3606. // too big for our quick buffer, so read it in blocks..
  3607. String result (String::fromUTF8 (temp, i));
  3608. i = 0;
  3609. for (;;)
  3610. {
  3611. if ((temp [i++] = readByte()) == 0)
  3612. {
  3613. result += String::fromUTF8 (temp, i - 1);
  3614. break;
  3615. }
  3616. else if (i == tempBufferSize)
  3617. {
  3618. result += String::fromUTF8 (temp, i);
  3619. i = 0;
  3620. }
  3621. }
  3622. return result;
  3623. }
  3624. }
  3625. return String::fromUTF8 (temp, i - 1);
  3626. }
  3627. const String InputStream::readNextLine()
  3628. {
  3629. String s;
  3630. const int maxChars = 256;
  3631. tchar buffer [maxChars];
  3632. int charsInBuffer = 0;
  3633. while (! isExhausted())
  3634. {
  3635. const uint8 c = readByte();
  3636. const int64 lastPos = getPosition();
  3637. if (c == '\n')
  3638. {
  3639. break;
  3640. }
  3641. else if (c == '\r')
  3642. {
  3643. if (readByte() != '\n')
  3644. setPosition (lastPos);
  3645. break;
  3646. }
  3647. buffer [charsInBuffer++] = c;
  3648. if (charsInBuffer == maxChars)
  3649. {
  3650. s.append (buffer, maxChars);
  3651. charsInBuffer = 0;
  3652. }
  3653. }
  3654. if (charsInBuffer > 0)
  3655. s.append (buffer, charsInBuffer);
  3656. return s;
  3657. }
  3658. int InputStream::readIntoMemoryBlock (MemoryBlock& block,
  3659. int numBytes)
  3660. {
  3661. const int64 totalLength = getTotalLength();
  3662. if (totalLength >= 0)
  3663. {
  3664. const int totalBytesRemaining = (int) jmin ((int64) 0x7fffffff,
  3665. totalLength - getPosition());
  3666. if (numBytes < 0)
  3667. numBytes = totalBytesRemaining;
  3668. else if (numBytes > 0)
  3669. numBytes = jmin (numBytes, totalBytesRemaining);
  3670. else
  3671. return 0;
  3672. }
  3673. const int originalBlockSize = block.getSize();
  3674. int totalBytesRead = 0;
  3675. if (numBytes > 0)
  3676. {
  3677. // know how many bytes we want, so we can resize the block first..
  3678. block.setSize (originalBlockSize + numBytes, false);
  3679. totalBytesRead = read (((char*) block.getData()) + originalBlockSize, numBytes);
  3680. }
  3681. else
  3682. {
  3683. // read until end of stram..
  3684. const int chunkSize = 32768;
  3685. for (;;)
  3686. {
  3687. block.ensureSize (originalBlockSize + totalBytesRead + chunkSize, false);
  3688. const int bytesJustIn = read (((char*) block.getData())
  3689. + originalBlockSize
  3690. + totalBytesRead,
  3691. chunkSize);
  3692. if (bytesJustIn == 0)
  3693. break;
  3694. totalBytesRead += bytesJustIn;
  3695. }
  3696. }
  3697. // trim off any excess left at the end
  3698. block.setSize (originalBlockSize + totalBytesRead, false);
  3699. return totalBytesRead;
  3700. }
  3701. const String InputStream::readEntireStreamAsString()
  3702. {
  3703. MemoryBlock mb;
  3704. const int size = readIntoMemoryBlock (mb);
  3705. return String::createStringFromData ((const char*) mb.getData(), size);
  3706. }
  3707. void InputStream::skipNextBytes (int64 numBytesToSkip)
  3708. {
  3709. if (numBytesToSkip > 0)
  3710. {
  3711. const int skipBufferSize = (int) jmin (numBytesToSkip, (int64) 16384);
  3712. MemoryBlock temp (skipBufferSize);
  3713. while ((numBytesToSkip > 0) && ! isExhausted())
  3714. {
  3715. numBytesToSkip -= read (temp.getData(), (int) jmin (numBytesToSkip, (int64) skipBufferSize));
  3716. }
  3717. }
  3718. }
  3719. END_JUCE_NAMESPACE
  3720. /********* End of inlined file: juce_InputStream.cpp *********/
  3721. /********* Start of inlined file: juce_OutputStream.cpp *********/
  3722. BEGIN_JUCE_NAMESPACE
  3723. #if JUCE_DEBUG
  3724. static CriticalSection activeStreamLock;
  3725. static VoidArray activeStreams;
  3726. void juce_CheckForDanglingStreams()
  3727. {
  3728. /*
  3729. It's always a bad idea to leak any object, but if you're leaking output
  3730. streams, then there's a good chance that you're failing to flush a file
  3731. to disk properly, which could result in corrupted data and other similar
  3732. nastiness..
  3733. */
  3734. jassert (activeStreams.size() == 0);
  3735. };
  3736. #endif
  3737. OutputStream::OutputStream() throw()
  3738. {
  3739. #if JUCE_DEBUG
  3740. activeStreamLock.enter();
  3741. activeStreams.add (this);
  3742. activeStreamLock.exit();
  3743. #endif
  3744. }
  3745. OutputStream::~OutputStream()
  3746. {
  3747. #if JUCE_DEBUG
  3748. activeStreamLock.enter();
  3749. activeStreams.removeValue (this);
  3750. activeStreamLock.exit();
  3751. #endif
  3752. }
  3753. void OutputStream::writeBool (bool b)
  3754. {
  3755. writeByte ((b) ? (char) 1
  3756. : (char) 0);
  3757. }
  3758. void OutputStream::writeByte (char byte)
  3759. {
  3760. write (&byte, 1);
  3761. }
  3762. void OutputStream::writeShort (short value)
  3763. {
  3764. const unsigned short v = swapIfBigEndian ((unsigned short) value);
  3765. write (&v, 2);
  3766. }
  3767. void OutputStream::writeShortBigEndian (short value)
  3768. {
  3769. const unsigned short v = swapIfLittleEndian ((unsigned short) value);
  3770. write (&v, 2);
  3771. }
  3772. void OutputStream::writeInt (int value)
  3773. {
  3774. const unsigned int v = swapIfBigEndian ((unsigned int) value);
  3775. write (&v, 4);
  3776. }
  3777. void OutputStream::writeIntBigEndian (int value)
  3778. {
  3779. const unsigned int v = swapIfLittleEndian ((unsigned int) value);
  3780. write (&v, 4);
  3781. }
  3782. void OutputStream::writeCompressedInt (int value)
  3783. {
  3784. unsigned int un = (value < 0) ? (unsigned int) -value
  3785. : (unsigned int) value;
  3786. unsigned int tn = un;
  3787. int numSigBytes = 0;
  3788. do
  3789. {
  3790. tn >>= 8;
  3791. numSigBytes++;
  3792. } while (tn & 0xff);
  3793. if (value < 0)
  3794. numSigBytes |= 0x80;
  3795. writeByte ((char) numSigBytes);
  3796. write (&un, numSigBytes);
  3797. }
  3798. void OutputStream::writeInt64 (int64 value)
  3799. {
  3800. const uint64 v = swapIfBigEndian ((uint64) value);
  3801. write (&v, 8);
  3802. }
  3803. void OutputStream::writeInt64BigEndian (int64 value)
  3804. {
  3805. const uint64 v = swapIfLittleEndian ((uint64) value);
  3806. write (&v, 8);
  3807. }
  3808. void OutputStream::writeFloat (float value)
  3809. {
  3810. union { int asInt; float asFloat; } n;
  3811. n.asFloat = value;
  3812. writeInt (n.asInt);
  3813. }
  3814. void OutputStream::writeFloatBigEndian (float value)
  3815. {
  3816. union { int asInt; float asFloat; } n;
  3817. n.asFloat = value;
  3818. writeIntBigEndian (n.asInt);
  3819. }
  3820. void OutputStream::writeDouble (double value)
  3821. {
  3822. union { int64 asInt; double asDouble; } n;
  3823. n.asDouble = value;
  3824. writeInt64 (n.asInt);
  3825. }
  3826. void OutputStream::writeDoubleBigEndian (double value)
  3827. {
  3828. union { int64 asInt; double asDouble; } n;
  3829. n.asDouble = value;
  3830. writeInt64BigEndian (n.asInt);
  3831. }
  3832. void OutputStream::writeString (const String& text)
  3833. {
  3834. const int numBytes = text.copyToUTF8 (0);
  3835. uint8* const temp = (uint8*) juce_malloc (numBytes);
  3836. text.copyToUTF8 (temp);
  3837. write (temp, numBytes); // (numBytes includes the terminating null).
  3838. juce_free (temp);
  3839. }
  3840. void OutputStream::printf (const char* pf, ...)
  3841. {
  3842. unsigned int bufSize = 256;
  3843. char* buf = (char*) juce_malloc (bufSize);
  3844. for (;;)
  3845. {
  3846. va_list list;
  3847. va_start (list, pf);
  3848. const int num = CharacterFunctions::vprintf (buf, bufSize, pf, list);
  3849. va_end (list);
  3850. if (num > 0)
  3851. {
  3852. write (buf, num);
  3853. break;
  3854. }
  3855. else if (num == 0)
  3856. {
  3857. break;
  3858. }
  3859. juce_free (buf);
  3860. bufSize += 256;
  3861. buf = (char*) juce_malloc (bufSize);
  3862. }
  3863. juce_free (buf);
  3864. }
  3865. OutputStream& OutputStream::operator<< (const int number)
  3866. {
  3867. const String s (number);
  3868. write ((const char*) s, s.length());
  3869. return *this;
  3870. }
  3871. OutputStream& OutputStream::operator<< (const double number)
  3872. {
  3873. const String s (number);
  3874. write ((const char*) s, s.length());
  3875. return *this;
  3876. }
  3877. OutputStream& OutputStream::operator<< (const char character)
  3878. {
  3879. writeByte (character);
  3880. return *this;
  3881. }
  3882. OutputStream& OutputStream::operator<< (const char* const text)
  3883. {
  3884. write (text, (int) strlen (text));
  3885. return *this;
  3886. }
  3887. OutputStream& OutputStream::operator<< (const juce_wchar* const text)
  3888. {
  3889. const String s (text);
  3890. write ((const char*) s, s.length());
  3891. return *this;
  3892. }
  3893. OutputStream& OutputStream::operator<< (const String& text)
  3894. {
  3895. write ((const char*) text,
  3896. text.length());
  3897. return *this;
  3898. }
  3899. void OutputStream::writeText (const String& text,
  3900. const bool asUnicode,
  3901. const bool writeUnicodeHeaderBytes)
  3902. {
  3903. if (asUnicode)
  3904. {
  3905. if (writeUnicodeHeaderBytes)
  3906. write ("\x0ff\x0fe", 2);
  3907. const juce_wchar* src = (const juce_wchar*) text;
  3908. bool lastCharWasReturn = false;
  3909. while (*src != 0)
  3910. {
  3911. if (*src == L'\n' && ! lastCharWasReturn)
  3912. writeShort ((short) L'\r');
  3913. lastCharWasReturn = (*src == L'\r');
  3914. writeShort ((short) *src++);
  3915. }
  3916. }
  3917. else
  3918. {
  3919. const char* src = (const char*) text;
  3920. const char* t = src;
  3921. for (;;)
  3922. {
  3923. if (*t == '\n')
  3924. {
  3925. if (t > src)
  3926. write (src, (int) (t - src));
  3927. write ("\r\n", 2);
  3928. src = t + 1;
  3929. }
  3930. else if (*t == '\r')
  3931. {
  3932. if (t[1] == '\n')
  3933. ++t;
  3934. }
  3935. else if (*t == 0)
  3936. {
  3937. if (t > src)
  3938. write (src, (int) (t - src));
  3939. break;
  3940. }
  3941. ++t;
  3942. }
  3943. }
  3944. }
  3945. int OutputStream::writeFromInputStream (InputStream& source,
  3946. int numBytesToWrite)
  3947. {
  3948. if (numBytesToWrite < 0)
  3949. numBytesToWrite = 0x7fffffff;
  3950. int numWritten = 0;
  3951. while (numBytesToWrite > 0 && ! source.isExhausted())
  3952. {
  3953. char buffer [8192];
  3954. const int num = source.read (buffer, jmin (numBytesToWrite, sizeof (buffer)));
  3955. if (num == 0)
  3956. break;
  3957. write (buffer, num);
  3958. numBytesToWrite -= num;
  3959. numWritten += num;
  3960. }
  3961. return numWritten;
  3962. }
  3963. END_JUCE_NAMESPACE
  3964. /********* End of inlined file: juce_OutputStream.cpp *********/
  3965. /********* Start of inlined file: juce_DirectoryIterator.cpp *********/
  3966. BEGIN_JUCE_NAMESPACE
  3967. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  3968. bool* isDirectory, bool* isHidden, int64* fileSize,
  3969. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  3970. bool juce_findFileNext (void* handle, String& resultFile,
  3971. bool* isDirectory, bool* isHidden, int64* fileSize,
  3972. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  3973. void juce_findFileClose (void* handle) throw();
  3974. DirectoryIterator::DirectoryIterator (const File& directory,
  3975. bool isRecursive,
  3976. const String& wc,
  3977. const int whatToLookFor_) throw()
  3978. : wildCard (wc),
  3979. index (-1),
  3980. whatToLookFor (whatToLookFor_),
  3981. subIterator (0)
  3982. {
  3983. // you have to specify the type of files you're looking for!
  3984. jassert ((whatToLookFor_ & (File::findFiles | File::findDirectories)) != 0);
  3985. jassert (whatToLookFor_ > 0 && whatToLookFor_ <= 7);
  3986. String path (directory.getFullPathName());
  3987. if (! path.endsWithChar (File::separator))
  3988. path += File::separator;
  3989. String filename;
  3990. bool isDirectory, isHidden;
  3991. void* const handle = juce_findFileStart (path,
  3992. isRecursive ? T("*") : wc,
  3993. filename, &isDirectory, &isHidden, 0, 0, 0, 0);
  3994. if (handle != 0)
  3995. {
  3996. do
  3997. {
  3998. if (! filename.containsOnly (T(".")))
  3999. {
  4000. bool addToList = false;
  4001. if (isDirectory)
  4002. {
  4003. if (isRecursive
  4004. && ((whatToLookFor_ & File::ignoreHiddenFiles) == 0
  4005. || ! isHidden))
  4006. {
  4007. dirsFound.add (new File (path + filename, 0));
  4008. }
  4009. addToList = (whatToLookFor_ & File::findDirectories) != 0;
  4010. }
  4011. else
  4012. {
  4013. addToList = (whatToLookFor_ & File::findFiles) != 0;
  4014. }
  4015. // if it's recursive, we're not relying on the OS iterator
  4016. // to do the wildcard match, so do it now..
  4017. if (isRecursive && addToList)
  4018. addToList = filename.matchesWildcard (wc, true);
  4019. if (addToList && (whatToLookFor_ & File::ignoreHiddenFiles) != 0)
  4020. addToList = ! isHidden;
  4021. if (addToList)
  4022. filesFound.add (new File (path + filename, 0));
  4023. }
  4024. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  4025. juce_findFileClose (handle);
  4026. }
  4027. }
  4028. DirectoryIterator::~DirectoryIterator() throw()
  4029. {
  4030. if (subIterator != 0)
  4031. delete subIterator;
  4032. }
  4033. bool DirectoryIterator::next() throw()
  4034. {
  4035. if (subIterator != 0)
  4036. {
  4037. if (subIterator->next())
  4038. return true;
  4039. deleteAndZero (subIterator);
  4040. }
  4041. if (index >= filesFound.size() + dirsFound.size() - 1)
  4042. return false;
  4043. ++index;
  4044. if (index >= filesFound.size())
  4045. {
  4046. subIterator = new DirectoryIterator (*(dirsFound [index - filesFound.size()]),
  4047. true, wildCard, whatToLookFor);
  4048. return next();
  4049. }
  4050. return true;
  4051. }
  4052. const File DirectoryIterator::getFile() const throw()
  4053. {
  4054. if (subIterator != 0)
  4055. return subIterator->getFile();
  4056. const File* const f = filesFound [index];
  4057. return (f != 0) ? *f
  4058. : File::nonexistent;
  4059. }
  4060. float DirectoryIterator::getEstimatedProgress() const throw()
  4061. {
  4062. if (filesFound.size() + dirsFound.size() == 0)
  4063. {
  4064. return 0.0f;
  4065. }
  4066. else
  4067. {
  4068. const float detailedIndex = (subIterator != 0) ? index + subIterator->getEstimatedProgress()
  4069. : (float) index;
  4070. return detailedIndex / (filesFound.size() + dirsFound.size());
  4071. }
  4072. }
  4073. END_JUCE_NAMESPACE
  4074. /********* End of inlined file: juce_DirectoryIterator.cpp *********/
  4075. /********* Start of inlined file: juce_File.cpp *********/
  4076. #ifdef _MSC_VER
  4077. #pragma warning (disable: 4514)
  4078. #pragma warning (push)
  4079. #endif
  4080. #ifndef JUCE_WIN32
  4081. #include <pwd.h>
  4082. #endif
  4083. BEGIN_JUCE_NAMESPACE
  4084. #ifdef _MSC_VER
  4085. #pragma warning (pop)
  4086. #endif
  4087. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4088. void juce_fileClose (void* handle) throw();
  4089. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  4090. int64 juce_fileGetPosition (void* handle) throw();
  4091. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4092. void juce_fileFlush (void* handle) throw();
  4093. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw();
  4094. bool juce_isDirectory (const String& fileName) throw();
  4095. int64 juce_getFileSize (const String& fileName) throw();
  4096. bool juce_canWriteToFile (const String& fileName) throw();
  4097. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw();
  4098. void juce_getFileTimes (const String& fileName, int64& modificationTime, int64& accessTime, int64& creationTime) throw();
  4099. bool juce_setFileTimes (const String& fileName, int64 modificationTime, int64 accessTime, int64 creationTime) throw();
  4100. bool juce_deleteFile (const String& fileName) throw();
  4101. bool juce_copyFile (const String& source, const String& dest) throw();
  4102. bool juce_moveFile (const String& source, const String& dest) throw();
  4103. // this must also create all paths involved in the directory.
  4104. void juce_createDirectory (const String& fileName) throw();
  4105. bool juce_launchFile (const String& fileName, const String& parameters) throw();
  4106. const StringArray juce_getFileSystemRoots() throw();
  4107. const String juce_getVolumeLabel (const String& filenameOnVolume, int& volumeSerialNumber) throw();
  4108. // starts a directory search operation with a wildcard, returning a handle for
  4109. // use in calls to juce_findFileNext.
  4110. // juce_firstResultFile gets the name of the file (not the whole pathname) and
  4111. // the other pointers, if non-null, are set based on the properties of the file.
  4112. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  4113. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  4114. Time* creationTime, bool* isReadOnly) throw();
  4115. // returns false when no more files are found
  4116. bool juce_findFileNext (void* handle, String& resultFile,
  4117. bool* isDirectory, bool* isHidden, int64* fileSize,
  4118. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  4119. void juce_findFileClose (void* handle) throw();
  4120. static const String parseAbsolutePath (String path) throw()
  4121. {
  4122. if (path.isEmpty())
  4123. return String::empty;
  4124. #if JUCE_WIN32
  4125. // Windows..
  4126. path = path.replaceCharacter (T('/'), T('\\')).unquoted();
  4127. if (path.startsWithChar (File::separator))
  4128. {
  4129. if (path[1] != File::separator)
  4130. {
  4131. jassertfalse // using a filename that starts with a slash is a bit dodgy on
  4132. // Windows, because it needs a drive letter, which in this case
  4133. // we'll take from the CWD.. but this is a bit of an assumption that
  4134. // could be wrong..
  4135. path = File::getCurrentWorkingDirectory().getFullPathName().substring (0, 2) + path;
  4136. }
  4137. }
  4138. else if (path.indexOfChar (T(':')) < 0)
  4139. {
  4140. if (path.isEmpty())
  4141. return String::empty;
  4142. jassertfalse // using a partial filename is a bad way to initialise a file, because
  4143. // we don't know what directory to put it in.
  4144. // Here we'll assume it's in the CWD, but this might not be what was
  4145. // intended..
  4146. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4147. }
  4148. #else
  4149. // Mac or Linux..
  4150. path = path.replaceCharacter (T('\\'), T('/')).unquoted();
  4151. if (path.startsWithChar (T('~')))
  4152. {
  4153. const char* homeDir = 0;
  4154. if (path[1] == File::separator || path[1] == 0)
  4155. {
  4156. // expand a name of the form "~/abc"
  4157. path = File::getSpecialLocation (File::userHomeDirectory).getFullPathName()
  4158. + path.substring (1);
  4159. }
  4160. else
  4161. {
  4162. // expand a name of type "~dave/abc"
  4163. const String userName (path.substring (1)
  4164. .upToFirstOccurrenceOf (T("/"), false, false));
  4165. struct passwd* const pw = getpwnam (userName);
  4166. if (pw != 0)
  4167. {
  4168. String home (homeDir);
  4169. if (home.endsWithChar (File::separator))
  4170. home [home.length() - 1] = 0;
  4171. path = String (pw->pw_dir)
  4172. + path.substring (userName.length());
  4173. }
  4174. }
  4175. }
  4176. else if (! path.startsWithChar (File::separator))
  4177. {
  4178. while (path.startsWith (T("./")))
  4179. path = path.substring (2);
  4180. if (path.isEmpty())
  4181. return String::empty;
  4182. jassertfalse // using a partial filename is a bad way to initialise a file, because
  4183. // we don't know what directory to put it in.
  4184. // Here we'll assume it's in the CWD, but this might not be what was
  4185. // intended..
  4186. return File::getCurrentWorkingDirectory().getChildFile (path).getFullPathName();
  4187. }
  4188. #endif
  4189. int len = path.length();
  4190. while (--len > 0 && path [len] == File::separator)
  4191. path [len] = 0;
  4192. return path;
  4193. }
  4194. const File File::nonexistent;
  4195. File::File (const String& fullPathName) throw()
  4196. : fullPath (parseAbsolutePath (fullPathName))
  4197. {
  4198. }
  4199. File::File (const String& path, int) throw()
  4200. : fullPath (path)
  4201. {
  4202. }
  4203. File::File (const File& other) throw()
  4204. : fullPath (other.fullPath)
  4205. {
  4206. }
  4207. const File& File::operator= (const String& newPath) throw()
  4208. {
  4209. fullPath = parseAbsolutePath (newPath);
  4210. return *this;
  4211. }
  4212. const File& File::operator= (const File& other) throw()
  4213. {
  4214. fullPath = other.fullPath;
  4215. return *this;
  4216. }
  4217. #if JUCE_LINUX
  4218. #define NAMES_ARE_CASE_SENSITIVE 1
  4219. #endif
  4220. bool File::areFileNamesCaseSensitive()
  4221. {
  4222. #if NAMES_ARE_CASE_SENSITIVE
  4223. return true;
  4224. #else
  4225. return false;
  4226. #endif
  4227. }
  4228. bool File::operator== (const File& other) const throw()
  4229. {
  4230. // case-insensitive on Windows, but not on linux.
  4231. #if NAMES_ARE_CASE_SENSITIVE
  4232. return fullPath == other.fullPath;
  4233. #else
  4234. return fullPath.equalsIgnoreCase (other.fullPath);
  4235. #endif
  4236. }
  4237. bool File::operator!= (const File& other) const throw()
  4238. {
  4239. return ! operator== (other);
  4240. }
  4241. bool File::exists() const throw()
  4242. {
  4243. return juce_fileExists (fullPath, false);
  4244. }
  4245. bool File::existsAsFile() const throw()
  4246. {
  4247. return juce_fileExists (fullPath, true);
  4248. }
  4249. bool File::isDirectory() const throw()
  4250. {
  4251. return juce_isDirectory (fullPath);
  4252. }
  4253. bool File::hasWriteAccess() const throw()
  4254. {
  4255. if (exists())
  4256. return juce_canWriteToFile (fullPath);
  4257. #ifndef JUCE_WIN32
  4258. else if ((! isDirectory()) && fullPath.containsChar (separator))
  4259. return getParentDirectory().hasWriteAccess();
  4260. else
  4261. return false;
  4262. #else
  4263. // on windows, it seems that even read-only directories can still be written into,
  4264. // so checking the parent directory's permissions would return the wrong result..
  4265. else
  4266. return true;
  4267. #endif
  4268. }
  4269. bool File::setReadOnly (const bool shouldBeReadOnly,
  4270. const bool applyRecursively) const throw()
  4271. {
  4272. bool worked = true;
  4273. if (applyRecursively && isDirectory())
  4274. {
  4275. OwnedArray <File> subFiles;
  4276. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4277. for (int i = subFiles.size(); --i >= 0;)
  4278. worked = subFiles[i]->setReadOnly (shouldBeReadOnly, true) && worked;
  4279. }
  4280. return juce_setFileReadOnly (fullPath, shouldBeReadOnly) && worked;
  4281. }
  4282. bool File::deleteFile() const throw()
  4283. {
  4284. return (! exists())
  4285. || juce_deleteFile (fullPath);
  4286. }
  4287. bool File::deleteRecursively() const throw()
  4288. {
  4289. bool worked = true;
  4290. if (isDirectory())
  4291. {
  4292. OwnedArray<File> subFiles;
  4293. findChildFiles (subFiles, File::findFilesAndDirectories, false);
  4294. for (int i = subFiles.size(); --i >= 0;)
  4295. worked = subFiles[i]->deleteRecursively() && worked;
  4296. }
  4297. return deleteFile() && worked;
  4298. }
  4299. bool File::moveFileTo (const File& newFile) const throw()
  4300. {
  4301. if (newFile.fullPath == fullPath)
  4302. return true;
  4303. #if ! NAMES_ARE_CASE_SENSITIVE
  4304. if (*this != newFile)
  4305. #endif
  4306. if (! newFile.deleteFile())
  4307. return false;
  4308. return juce_moveFile (fullPath, newFile.fullPath);
  4309. }
  4310. bool File::copyFileTo (const File& newFile) const throw()
  4311. {
  4312. if (*this == newFile)
  4313. return true;
  4314. if (! newFile.deleteFile())
  4315. return false;
  4316. return juce_copyFile (fullPath, newFile.fullPath);
  4317. }
  4318. bool File::copyDirectoryTo (const File& newDirectory) const throw()
  4319. {
  4320. if (isDirectory() && newDirectory.createDirectory())
  4321. {
  4322. OwnedArray<File> subFiles;
  4323. findChildFiles (subFiles, File::findFiles, false);
  4324. int i;
  4325. for (i = 0; i < subFiles.size(); ++i)
  4326. if (! subFiles[i]->copyFileTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  4327. return false;
  4328. subFiles.clear();
  4329. findChildFiles (subFiles, File::findDirectories, false);
  4330. for (i = 0; i < subFiles.size(); ++i)
  4331. if (! subFiles[i]->copyDirectoryTo (newDirectory.getChildFile (subFiles[i]->getFileName())))
  4332. return false;
  4333. return true;
  4334. }
  4335. return false;
  4336. }
  4337. const String File::getPathUpToLastSlash() const throw()
  4338. {
  4339. const int lastSlash = fullPath.lastIndexOfChar (separator);
  4340. if (lastSlash > 0)
  4341. return fullPath.substring (0, lastSlash);
  4342. else if (lastSlash == 0)
  4343. return separatorString;
  4344. else
  4345. return fullPath;
  4346. }
  4347. const File File::getParentDirectory() const throw()
  4348. {
  4349. return File (getPathUpToLastSlash());
  4350. }
  4351. const String File::getFileName() const throw()
  4352. {
  4353. return fullPath.substring (fullPath.lastIndexOfChar (separator) + 1);
  4354. }
  4355. int File::hashCode() const throw()
  4356. {
  4357. return fullPath.hashCode();
  4358. }
  4359. int64 File::hashCode64() const throw()
  4360. {
  4361. return fullPath.hashCode64();
  4362. }
  4363. const String File::getFileNameWithoutExtension() const throw()
  4364. {
  4365. const int lastSlash = fullPath.lastIndexOfChar (separator) + 1;
  4366. const int lastDot = fullPath.lastIndexOfChar (T('.'));
  4367. if (lastDot > lastSlash)
  4368. return fullPath.substring (lastSlash, lastDot);
  4369. else
  4370. return fullPath.substring (lastSlash);
  4371. }
  4372. bool File::isAChildOf (const File& potentialParent) const throw()
  4373. {
  4374. const String ourPath (getPathUpToLastSlash());
  4375. #if NAMES_ARE_CASE_SENSITIVE
  4376. if (potentialParent.fullPath == ourPath)
  4377. #else
  4378. if (potentialParent.fullPath.equalsIgnoreCase (ourPath))
  4379. #endif
  4380. {
  4381. return true;
  4382. }
  4383. else if (potentialParent.fullPath.length() >= ourPath.length())
  4384. {
  4385. return false;
  4386. }
  4387. else
  4388. {
  4389. return getParentDirectory().isAChildOf (potentialParent);
  4390. }
  4391. }
  4392. bool File::isAbsolutePath (const String& path) throw()
  4393. {
  4394. return path.startsWithChar (T('/')) || path.startsWithChar (T('\\'))
  4395. #if JUCE_WIN32
  4396. || (path.isNotEmpty() && ((const String&) path)[1] == T(':'));
  4397. #else
  4398. || path.startsWithChar (T('~'));
  4399. #endif
  4400. }
  4401. const File File::getChildFile (String relativePath) const throw()
  4402. {
  4403. if (isAbsolutePath (relativePath))
  4404. {
  4405. // the path is really absolute..
  4406. return File (relativePath);
  4407. }
  4408. else
  4409. {
  4410. // it's relative, so remove any ../ or ./ bits at the start.
  4411. String path (fullPath);
  4412. if (relativePath[0] == T('.'))
  4413. {
  4414. #if JUCE_WIN32
  4415. relativePath = relativePath.replaceCharacter (T('/'), T('\\')).trimStart();
  4416. #else
  4417. relativePath = relativePath.replaceCharacter (T('\\'), T('/')).trimStart();
  4418. #endif
  4419. while (relativePath[0] == T('.'))
  4420. {
  4421. if (relativePath[1] == T('.'))
  4422. {
  4423. if (relativePath [2] == 0 || relativePath[2] == separator)
  4424. {
  4425. const int lastSlash = path.lastIndexOfChar (separator);
  4426. if (lastSlash > 0)
  4427. path = path.substring (0, lastSlash);
  4428. relativePath = relativePath.substring (3);
  4429. }
  4430. else
  4431. {
  4432. break;
  4433. }
  4434. }
  4435. else if (relativePath[1] == separator)
  4436. {
  4437. relativePath = relativePath.substring (2);
  4438. }
  4439. else
  4440. {
  4441. break;
  4442. }
  4443. }
  4444. }
  4445. if (! path.endsWithChar (separator))
  4446. path += separator;
  4447. return File (path + relativePath);
  4448. }
  4449. }
  4450. const File File::getSiblingFile (const String& fileName) const throw()
  4451. {
  4452. return getParentDirectory().getChildFile (fileName);
  4453. }
  4454. int64 File::getSize() const throw()
  4455. {
  4456. return juce_getFileSize (fullPath);
  4457. }
  4458. const String File::descriptionOfSizeInBytes (const int64 bytes)
  4459. {
  4460. if (bytes == 1)
  4461. {
  4462. return "1 byte";
  4463. }
  4464. else if (bytes < 1024)
  4465. {
  4466. return String ((int) bytes) + " bytes";
  4467. }
  4468. else if (bytes < 1024 * 1024)
  4469. {
  4470. return String (bytes / 1024.0, 1) + " KB";
  4471. }
  4472. else if (bytes < 1024 * 1024 * 1024)
  4473. {
  4474. return String (bytes / (1024.0 * 1024.0), 1) + " MB";
  4475. }
  4476. else
  4477. {
  4478. return String (bytes / (1024.0 * 1024.0 * 1024.0), 1) + " GB";
  4479. }
  4480. }
  4481. bool File::create() const throw()
  4482. {
  4483. if (! exists())
  4484. {
  4485. const File parentDir (getParentDirectory());
  4486. if (parentDir == *this || ! parentDir.createDirectory())
  4487. return false;
  4488. void* const fh = juce_fileOpen (fullPath, true);
  4489. if (fh == 0)
  4490. return false;
  4491. juce_fileClose (fh);
  4492. }
  4493. return true;
  4494. }
  4495. bool File::createDirectory() const throw()
  4496. {
  4497. if (! isDirectory())
  4498. {
  4499. const File parentDir (getParentDirectory());
  4500. if (parentDir == *this || ! parentDir.createDirectory())
  4501. return false;
  4502. String dir (fullPath);
  4503. while (dir.endsWithChar (separator))
  4504. dir [dir.length() - 1] = 0;
  4505. juce_createDirectory (dir);
  4506. return isDirectory();
  4507. }
  4508. return true;
  4509. }
  4510. const Time File::getCreationTime() const throw()
  4511. {
  4512. int64 m, a, c;
  4513. juce_getFileTimes (fullPath, m, a, c);
  4514. return Time (c);
  4515. }
  4516. bool File::setCreationTime (const Time& t) const throw()
  4517. {
  4518. return juce_setFileTimes (fullPath, 0, 0, t.toMilliseconds());
  4519. }
  4520. const Time File::getLastModificationTime() const throw()
  4521. {
  4522. int64 m, a, c;
  4523. juce_getFileTimes (fullPath, m, a, c);
  4524. return Time (m);
  4525. }
  4526. bool File::setLastModificationTime (const Time& t) const throw()
  4527. {
  4528. return juce_setFileTimes (fullPath, t.toMilliseconds(), 0, 0);
  4529. }
  4530. const Time File::getLastAccessTime() const throw()
  4531. {
  4532. int64 m, a, c;
  4533. juce_getFileTimes (fullPath, m, a, c);
  4534. return Time (a);
  4535. }
  4536. bool File::setLastAccessTime (const Time& t) const throw()
  4537. {
  4538. return juce_setFileTimes (fullPath, 0, t.toMilliseconds(), 0);
  4539. }
  4540. bool File::loadFileAsData (MemoryBlock& destBlock) const throw()
  4541. {
  4542. if (! existsAsFile())
  4543. return false;
  4544. FileInputStream in (*this);
  4545. return getSize() == in.readIntoMemoryBlock (destBlock);
  4546. }
  4547. const String File::loadFileAsString() const throw()
  4548. {
  4549. if (! existsAsFile())
  4550. return String::empty;
  4551. FileInputStream in (*this);
  4552. return in.readEntireStreamAsString();
  4553. }
  4554. static inline bool fileTypeMatches (const int whatToLookFor,
  4555. const bool isDir,
  4556. const bool isHidden)
  4557. {
  4558. return (whatToLookFor & (isDir ? File::findDirectories
  4559. : File::findFiles)) != 0
  4560. && ((! isHidden)
  4561. || (whatToLookFor & File::ignoreHiddenFiles) == 0);
  4562. }
  4563. int File::findChildFiles (OwnedArray<File>& results,
  4564. const int whatToLookFor,
  4565. const bool searchRecursively,
  4566. const String& wildCardPattern) const throw()
  4567. {
  4568. // you have to specify the type of files you're looking for!
  4569. jassert ((whatToLookFor & (findFiles | findDirectories)) != 0);
  4570. int total = 0;
  4571. // find child files or directories in this directory first..
  4572. if (isDirectory())
  4573. {
  4574. String path (fullPath);
  4575. if (! path.endsWithChar (separator))
  4576. path += separator;
  4577. String filename;
  4578. bool isDirectory, isHidden;
  4579. void* const handle = juce_findFileStart (path,
  4580. wildCardPattern,
  4581. filename,
  4582. &isDirectory, &isHidden,
  4583. 0, 0, 0, 0);
  4584. if (handle != 0)
  4585. {
  4586. do
  4587. {
  4588. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  4589. && ! filename.containsOnly (T(".")))
  4590. {
  4591. results.add (new File (path + filename, 0));
  4592. ++total;
  4593. }
  4594. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  4595. juce_findFileClose (handle);
  4596. }
  4597. }
  4598. else
  4599. {
  4600. // trying to search for files inside a non-directory?
  4601. //jassertfalse
  4602. }
  4603. // and recurse down if required.
  4604. if (searchRecursively)
  4605. {
  4606. OwnedArray <File> subDirectories;
  4607. findChildFiles (subDirectories, File::findDirectories, false);
  4608. for (int i = 0; i < subDirectories.size(); ++i)
  4609. {
  4610. total += subDirectories.getUnchecked(i)
  4611. ->findChildFiles (results,
  4612. whatToLookFor,
  4613. true,
  4614. wildCardPattern);
  4615. }
  4616. }
  4617. return total;
  4618. }
  4619. int File::getNumberOfChildFiles (const int whatToLookFor,
  4620. const String& wildCardPattern) const throw()
  4621. {
  4622. // you have to specify the type of files you're looking for!
  4623. jassert (whatToLookFor > 0 && whatToLookFor <= 3);
  4624. int count = 0;
  4625. if (isDirectory())
  4626. {
  4627. String filename;
  4628. bool isDirectory, isHidden;
  4629. void* const handle = juce_findFileStart (fullPath,
  4630. wildCardPattern,
  4631. filename,
  4632. &isDirectory, &isHidden,
  4633. 0, 0, 0, 0);
  4634. if (handle != 0)
  4635. {
  4636. do
  4637. {
  4638. if (fileTypeMatches (whatToLookFor, isDirectory, isHidden)
  4639. && ! filename.containsOnly (T(".")))
  4640. {
  4641. ++count;
  4642. }
  4643. } while (juce_findFileNext (handle, filename, &isDirectory, &isHidden, 0, 0, 0, 0));
  4644. juce_findFileClose (handle);
  4645. }
  4646. }
  4647. else
  4648. {
  4649. // trying to search for files inside a non-directory?
  4650. jassertfalse
  4651. }
  4652. return count;
  4653. }
  4654. const File File::getNonexistentChildFile (const String& prefix_,
  4655. const String& suffix,
  4656. bool putNumbersInBrackets) const throw()
  4657. {
  4658. File f (getChildFile (prefix_ + suffix));
  4659. if (f.exists())
  4660. {
  4661. int num = 2;
  4662. String prefix (prefix_);
  4663. // remove any bracketed numbers that may already be on the end..
  4664. if (prefix.trim().endsWithChar (T(')')))
  4665. {
  4666. putNumbersInBrackets = true;
  4667. const int openBracks = prefix.lastIndexOfChar (T('('));
  4668. const int closeBracks = prefix.lastIndexOfChar (T(')'));
  4669. if (openBracks > 0
  4670. && closeBracks > openBracks
  4671. && prefix.substring (openBracks + 1, closeBracks).containsOnly (T("0123456789")))
  4672. {
  4673. num = prefix.substring (openBracks + 1, closeBracks).getIntValue() + 1;
  4674. prefix = prefix.substring (0, openBracks);
  4675. }
  4676. }
  4677. // also use brackets if it ends in a digit.
  4678. putNumbersInBrackets = putNumbersInBrackets
  4679. || CharacterFunctions::isDigit (prefix.getLastCharacter());
  4680. do
  4681. {
  4682. if (putNumbersInBrackets)
  4683. f = getChildFile (prefix + T('(') + String (num++) + T(')') + suffix);
  4684. else
  4685. f = getChildFile (prefix + String (num++) + suffix);
  4686. } while (f.exists());
  4687. }
  4688. return f;
  4689. }
  4690. const File File::getNonexistentSibling (const bool putNumbersInBrackets) const throw()
  4691. {
  4692. if (exists())
  4693. {
  4694. return getParentDirectory()
  4695. .getNonexistentChildFile (getFileNameWithoutExtension(),
  4696. getFileExtension(),
  4697. putNumbersInBrackets);
  4698. }
  4699. else
  4700. {
  4701. return *this;
  4702. }
  4703. }
  4704. const String File::getFileExtension() const throw()
  4705. {
  4706. String ext;
  4707. if (! isDirectory())
  4708. {
  4709. const int indexOfDot = fullPath.lastIndexOfChar (T('.'));
  4710. if (indexOfDot > fullPath.lastIndexOfChar (separator))
  4711. ext = fullPath.substring (indexOfDot);
  4712. }
  4713. return ext;
  4714. }
  4715. bool File::hasFileExtension (const String& possibleSuffix) const throw()
  4716. {
  4717. if (possibleSuffix.isEmpty())
  4718. return fullPath.lastIndexOfChar (T('.')) <= fullPath.lastIndexOfChar (separator);
  4719. if (fullPath.endsWithIgnoreCase (possibleSuffix))
  4720. {
  4721. if (possibleSuffix.startsWithChar (T('.')))
  4722. return true;
  4723. const int dotPos = fullPath.length() - possibleSuffix.length() - 1;
  4724. if (dotPos >= 0)
  4725. return fullPath [dotPos] == T('.');
  4726. }
  4727. return false;
  4728. }
  4729. const File File::withFileExtension (const String& newExtension) const throw()
  4730. {
  4731. if (fullPath.isEmpty())
  4732. return File::nonexistent;
  4733. String filePart (getFileName());
  4734. int i = filePart.lastIndexOfChar (T('.'));
  4735. if (i < 0)
  4736. i = filePart.length();
  4737. String newExt (newExtension);
  4738. if (newExt.isNotEmpty() && ! newExt.startsWithChar (T('.')))
  4739. newExt = T(".") + newExt;
  4740. return getSiblingFile (filePart.substring (0, i) + newExt);
  4741. }
  4742. bool File::startAsProcess (const String& parameters) const throw()
  4743. {
  4744. return exists()
  4745. && juce_launchFile (fullPath, parameters);
  4746. }
  4747. FileInputStream* File::createInputStream() const throw()
  4748. {
  4749. if (existsAsFile())
  4750. return new FileInputStream (*this);
  4751. else
  4752. return 0;
  4753. }
  4754. FileOutputStream* File::createOutputStream (const int bufferSize) const throw()
  4755. {
  4756. FileOutputStream* const out = new FileOutputStream (*this, bufferSize);
  4757. if (out->failedToOpen())
  4758. {
  4759. delete out;
  4760. return 0;
  4761. }
  4762. else
  4763. {
  4764. return out;
  4765. }
  4766. }
  4767. bool File::appendData (const void* const dataToAppend,
  4768. const int numberOfBytes) const throw()
  4769. {
  4770. if (numberOfBytes > 0)
  4771. {
  4772. FileOutputStream* const out = createOutputStream();
  4773. if (out == 0)
  4774. return false;
  4775. out->write (dataToAppend, numberOfBytes);
  4776. delete out;
  4777. }
  4778. return true;
  4779. }
  4780. bool File::replaceWithData (const void* const dataToWrite,
  4781. const int numberOfBytes) const throw()
  4782. {
  4783. jassert (numberOfBytes >= 0); // a negative number of bytes??
  4784. if (numberOfBytes <= 0)
  4785. return deleteFile();
  4786. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  4787. if (tempFile.appendData (dataToWrite, numberOfBytes)
  4788. && tempFile.moveFileTo (*this))
  4789. {
  4790. return true;
  4791. }
  4792. tempFile.deleteFile();
  4793. return false;
  4794. }
  4795. bool File::appendText (const String& text,
  4796. const bool asUnicode,
  4797. const bool writeUnicodeHeaderBytes) const throw()
  4798. {
  4799. FileOutputStream* const out = createOutputStream();
  4800. if (out != 0)
  4801. {
  4802. out->writeText (text, asUnicode, writeUnicodeHeaderBytes);
  4803. delete out;
  4804. return true;
  4805. }
  4806. return false;
  4807. }
  4808. bool File::printf (const tchar* pf, ...) const throw()
  4809. {
  4810. va_list list;
  4811. va_start (list, pf);
  4812. String text;
  4813. text.vprintf (pf, list);
  4814. return appendData ((const char*) text, text.length());
  4815. }
  4816. bool File::replaceWithText (const String& textToWrite,
  4817. const bool asUnicode,
  4818. const bool writeUnicodeHeaderBytes) const throw()
  4819. {
  4820. const File tempFile (getSiblingFile (T(".") + getFileName()).getNonexistentSibling (false));
  4821. if (tempFile.appendText (textToWrite, asUnicode, writeUnicodeHeaderBytes)
  4822. && tempFile.moveFileTo (*this))
  4823. {
  4824. return true;
  4825. }
  4826. tempFile.deleteFile();
  4827. return false;
  4828. }
  4829. const String File::createLegalPathName (const String& original) throw()
  4830. {
  4831. String s (original);
  4832. String start;
  4833. if (s[1] == T(':'))
  4834. {
  4835. start = s.substring (0, 2);
  4836. s = s.substring (2);
  4837. }
  4838. return start + s.removeCharacters (T("\"#@,;:<>*^|?"))
  4839. .substring (0, 1024);
  4840. }
  4841. const String File::createLegalFileName (const String& original) throw()
  4842. {
  4843. String s (original.removeCharacters (T("\"#@,;:<>*^|?\\/")));
  4844. const int maxLength = 128; // only the length of the filename, not the whole path
  4845. const int len = s.length();
  4846. if (len > maxLength)
  4847. {
  4848. const int lastDot = s.lastIndexOfChar (T('.'));
  4849. if (lastDot > jmax (0, len - 12))
  4850. {
  4851. s = s.substring (0, maxLength - (len - lastDot))
  4852. + s.substring (lastDot);
  4853. }
  4854. else
  4855. {
  4856. s = s.substring (0, maxLength);
  4857. }
  4858. }
  4859. return s;
  4860. }
  4861. const String File::getRelativePathFrom (const File& dir) const throw()
  4862. {
  4863. String thisPath (fullPath);
  4864. {
  4865. int len = thisPath.length();
  4866. while (--len >= 0 && thisPath [len] == File::separator)
  4867. thisPath [len] = 0;
  4868. }
  4869. String dirPath ((dir.existsAsFile()) ? dir.getParentDirectory().getFullPathName()
  4870. : dir.fullPath);
  4871. if (! dirPath.endsWithChar (separator))
  4872. dirPath += separator;
  4873. const int len = jmin (thisPath.length(), dirPath.length());
  4874. int commonBitLength = 0;
  4875. for (int i = 0; i < len; ++i)
  4876. {
  4877. #if NAMES_ARE_CASE_SENSITIVE
  4878. if (thisPath[i] != dirPath[i])
  4879. #else
  4880. if (CharacterFunctions::toLowerCase (thisPath[i])
  4881. != CharacterFunctions::toLowerCase (dirPath[i]))
  4882. #endif
  4883. {
  4884. break;
  4885. }
  4886. ++commonBitLength;
  4887. }
  4888. while (commonBitLength > 0 && thisPath [commonBitLength - 1] != File::separator)
  4889. --commonBitLength;
  4890. // if the only common bit is the root, then just return the full path..
  4891. if (commonBitLength <= 0
  4892. || (commonBitLength == 1 && thisPath [1] == File::separator))
  4893. return fullPath;
  4894. thisPath = thisPath.substring (commonBitLength);
  4895. dirPath = dirPath.substring (commonBitLength);
  4896. while (dirPath.isNotEmpty())
  4897. {
  4898. #if JUCE_WIN32
  4899. thisPath = T("..\\") + thisPath;
  4900. #else
  4901. thisPath = T("../") + thisPath;
  4902. #endif
  4903. const int sep = dirPath.indexOfChar (separator);
  4904. if (sep >= 0)
  4905. dirPath = dirPath.substring (sep + 1);
  4906. else
  4907. dirPath = String::empty;
  4908. }
  4909. return thisPath;
  4910. }
  4911. void File::findFileSystemRoots (OwnedArray<File>& destArray) throw()
  4912. {
  4913. const StringArray roots (juce_getFileSystemRoots());
  4914. for (int i = 0; i < roots.size(); ++i)
  4915. destArray.add (new File (roots[i]));
  4916. }
  4917. const String File::getVolumeLabel() const throw()
  4918. {
  4919. int serialNum;
  4920. return juce_getVolumeLabel (fullPath, serialNum);
  4921. }
  4922. int File::getVolumeSerialNumber() const throw()
  4923. {
  4924. int serialNum;
  4925. juce_getVolumeLabel (fullPath, serialNum);
  4926. return serialNum;
  4927. }
  4928. const File File::createTempFile (const String& fileNameEnding) throw()
  4929. {
  4930. String tempName (T("temp"));
  4931. static int tempNum = 0;
  4932. tempName << tempNum++ << fileNameEnding;
  4933. const File tempFile (getSpecialLocation (tempDirectory)
  4934. .getChildFile (tempName));
  4935. if (tempFile.exists())
  4936. return createTempFile (fileNameEnding);
  4937. else
  4938. return tempFile;
  4939. }
  4940. END_JUCE_NAMESPACE
  4941. /********* End of inlined file: juce_File.cpp *********/
  4942. /********* Start of inlined file: juce_FileInputStream.cpp *********/
  4943. BEGIN_JUCE_NAMESPACE
  4944. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4945. void juce_fileClose (void* handle) throw();
  4946. int juce_fileRead (void* handle, void* buffer, int size) throw();
  4947. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  4948. FileInputStream::FileInputStream (const File& f)
  4949. : file (f),
  4950. currentPosition (0),
  4951. needToSeek (true)
  4952. {
  4953. totalSize = f.getSize();
  4954. fileHandle = juce_fileOpen (f.getFullPathName(), false);
  4955. }
  4956. FileInputStream::~FileInputStream()
  4957. {
  4958. juce_fileClose (fileHandle);
  4959. }
  4960. int64 FileInputStream::getTotalLength()
  4961. {
  4962. return totalSize;
  4963. }
  4964. int FileInputStream::read (void* buffer, int bytesToRead)
  4965. {
  4966. int num = 0;
  4967. if (needToSeek)
  4968. {
  4969. if (juce_fileSetPosition (fileHandle, currentPosition) < 0)
  4970. return 0;
  4971. needToSeek = false;
  4972. }
  4973. num = juce_fileRead (fileHandle, buffer, bytesToRead);
  4974. currentPosition += num;
  4975. return num;
  4976. }
  4977. bool FileInputStream::isExhausted()
  4978. {
  4979. return currentPosition >= totalSize;
  4980. }
  4981. int64 FileInputStream::getPosition()
  4982. {
  4983. return currentPosition;
  4984. }
  4985. bool FileInputStream::setPosition (int64 pos)
  4986. {
  4987. pos = jlimit ((int64) 0, totalSize, pos);
  4988. needToSeek |= (currentPosition != pos);
  4989. currentPosition = pos;
  4990. return true;
  4991. }
  4992. END_JUCE_NAMESPACE
  4993. /********* End of inlined file: juce_FileInputStream.cpp *********/
  4994. /********* Start of inlined file: juce_FileOutputStream.cpp *********/
  4995. BEGIN_JUCE_NAMESPACE
  4996. void* juce_fileOpen (const String& path, bool forWriting) throw();
  4997. void juce_fileClose (void* handle) throw();
  4998. int juce_fileWrite (void* handle, const void* buffer, int size) throw();
  4999. void juce_fileFlush (void* handle) throw();
  5000. int64 juce_fileGetPosition (void* handle) throw();
  5001. int64 juce_fileSetPosition (void* handle, int64 pos) throw();
  5002. FileOutputStream::FileOutputStream (const File& f,
  5003. const int bufferSize_)
  5004. : file (f),
  5005. bufferSize (bufferSize_),
  5006. bytesInBuffer (0)
  5007. {
  5008. fileHandle = juce_fileOpen (f.getFullPathName(), true);
  5009. if (fileHandle != 0)
  5010. {
  5011. currentPosition = juce_fileGetPosition (fileHandle);
  5012. if (currentPosition < 0)
  5013. {
  5014. jassertfalse
  5015. juce_fileClose (fileHandle);
  5016. fileHandle = 0;
  5017. }
  5018. }
  5019. buffer = (char*) juce_malloc (jmax (bufferSize_, 16));
  5020. }
  5021. FileOutputStream::~FileOutputStream()
  5022. {
  5023. flush();
  5024. juce_fileClose (fileHandle);
  5025. juce_free (buffer);
  5026. }
  5027. int64 FileOutputStream::getPosition()
  5028. {
  5029. return currentPosition;
  5030. }
  5031. bool FileOutputStream::setPosition (int64 newPosition)
  5032. {
  5033. if (newPosition != currentPosition)
  5034. {
  5035. flush();
  5036. currentPosition = juce_fileSetPosition (fileHandle, newPosition);
  5037. }
  5038. return newPosition == currentPosition;
  5039. }
  5040. void FileOutputStream::flush()
  5041. {
  5042. if (bytesInBuffer > 0)
  5043. {
  5044. juce_fileWrite (fileHandle, buffer, bytesInBuffer);
  5045. bytesInBuffer = 0;
  5046. }
  5047. juce_fileFlush (fileHandle);
  5048. }
  5049. bool FileOutputStream::write (const void* const src, const int numBytes)
  5050. {
  5051. if (bytesInBuffer + numBytes < bufferSize)
  5052. {
  5053. memcpy (buffer + bytesInBuffer, src, numBytes);
  5054. bytesInBuffer += numBytes;
  5055. currentPosition += numBytes;
  5056. }
  5057. else
  5058. {
  5059. if (bytesInBuffer > 0)
  5060. {
  5061. // flush the reservoir
  5062. const bool wroteOk = (juce_fileWrite (fileHandle, buffer, bytesInBuffer) == bytesInBuffer);
  5063. bytesInBuffer = 0;
  5064. if (! wroteOk)
  5065. return false;
  5066. }
  5067. if (numBytes < bufferSize)
  5068. {
  5069. memcpy (buffer + bytesInBuffer, src, numBytes);
  5070. bytesInBuffer += numBytes;
  5071. currentPosition += numBytes;
  5072. }
  5073. else
  5074. {
  5075. const int bytesWritten = juce_fileWrite (fileHandle, src, numBytes);
  5076. currentPosition += bytesWritten;
  5077. return bytesWritten == numBytes;
  5078. }
  5079. }
  5080. return true;
  5081. }
  5082. END_JUCE_NAMESPACE
  5083. /********* End of inlined file: juce_FileOutputStream.cpp *********/
  5084. /********* Start of inlined file: juce_FileSearchPath.cpp *********/
  5085. BEGIN_JUCE_NAMESPACE
  5086. FileSearchPath::FileSearchPath()
  5087. {
  5088. }
  5089. FileSearchPath::FileSearchPath (const String& path)
  5090. {
  5091. init (path);
  5092. }
  5093. FileSearchPath::FileSearchPath (const FileSearchPath& other)
  5094. : directories (other.directories)
  5095. {
  5096. }
  5097. FileSearchPath::~FileSearchPath()
  5098. {
  5099. }
  5100. const FileSearchPath& FileSearchPath::operator= (const String& path)
  5101. {
  5102. init (path);
  5103. return *this;
  5104. }
  5105. void FileSearchPath::init (const String& path)
  5106. {
  5107. directories.clear();
  5108. directories.addTokens (path, T(";"), T("\""));
  5109. directories.trim();
  5110. directories.removeEmptyStrings();
  5111. for (int i = directories.size(); --i >= 0;)
  5112. directories.set (i, directories[i].unquoted());
  5113. }
  5114. int FileSearchPath::getNumPaths() const
  5115. {
  5116. return directories.size();
  5117. }
  5118. const File FileSearchPath::operator[] (const int index) const
  5119. {
  5120. return File (directories [index]);
  5121. }
  5122. const String FileSearchPath::toString() const
  5123. {
  5124. StringArray directories2 (directories);
  5125. for (int i = directories2.size(); --i >= 0;)
  5126. if (directories2[i].containsChar (T(';')))
  5127. directories2.set (i, directories2[i].quoted());
  5128. return directories2.joinIntoString (T(";"));
  5129. }
  5130. void FileSearchPath::add (const File& dir, const int insertIndex)
  5131. {
  5132. directories.insert (insertIndex, dir.getFullPathName());
  5133. }
  5134. void FileSearchPath::addIfNotAlreadyThere (const File& dir)
  5135. {
  5136. for (int i = 0; i < directories.size(); ++i)
  5137. if (File (directories[i]) == dir)
  5138. return;
  5139. add (dir);
  5140. }
  5141. void FileSearchPath::remove (const int index)
  5142. {
  5143. directories.remove (index);
  5144. }
  5145. void FileSearchPath::addPath (const FileSearchPath& other)
  5146. {
  5147. for (int i = 0; i < other.getNumPaths(); ++i)
  5148. addIfNotAlreadyThere (other[i]);
  5149. }
  5150. void FileSearchPath::removeRedundantPaths()
  5151. {
  5152. for (int i = directories.size(); --i >= 0;)
  5153. {
  5154. const File d1 (directories[i]);
  5155. for (int j = directories.size(); --j >= 0;)
  5156. {
  5157. const File d2 (directories[j]);
  5158. if ((i != j) && (d1.isAChildOf (d2) || d1 == d2))
  5159. {
  5160. directories.remove (i);
  5161. break;
  5162. }
  5163. }
  5164. }
  5165. }
  5166. void FileSearchPath::removeNonExistentPaths()
  5167. {
  5168. for (int i = directories.size(); --i >= 0;)
  5169. if (! File (directories[i]).isDirectory())
  5170. directories.remove (i);
  5171. }
  5172. int FileSearchPath::findChildFiles (OwnedArray<File>& results,
  5173. const int whatToLookFor,
  5174. const bool searchRecursively,
  5175. const String& wildCardPattern) const
  5176. {
  5177. int total = 0;
  5178. for (int i = 0; i < directories.size(); ++i)
  5179. total += operator[] (i).findChildFiles (results,
  5180. whatToLookFor,
  5181. searchRecursively,
  5182. wildCardPattern);
  5183. return total;
  5184. }
  5185. bool FileSearchPath::isFileInPath (const File& fileToCheck,
  5186. const bool checkRecursively) const
  5187. {
  5188. for (int i = directories.size(); --i >= 0;)
  5189. {
  5190. const File d (directories[i]);
  5191. if (checkRecursively)
  5192. {
  5193. if (fileToCheck.isAChildOf (d))
  5194. return true;
  5195. }
  5196. else
  5197. {
  5198. if (fileToCheck.getParentDirectory() == d)
  5199. return true;
  5200. }
  5201. }
  5202. return false;
  5203. }
  5204. END_JUCE_NAMESPACE
  5205. /********* End of inlined file: juce_FileSearchPath.cpp *********/
  5206. /********* Start of inlined file: juce_NamedPipe.cpp *********/
  5207. BEGIN_JUCE_NAMESPACE
  5208. NamedPipe::NamedPipe()
  5209. : internal (0)
  5210. {
  5211. }
  5212. NamedPipe::~NamedPipe()
  5213. {
  5214. close();
  5215. }
  5216. bool NamedPipe::openExisting (const String& pipeName)
  5217. {
  5218. currentPipeName = pipeName;
  5219. return openInternal (pipeName, false);
  5220. }
  5221. bool NamedPipe::createNewPipe (const String& pipeName)
  5222. {
  5223. currentPipeName = pipeName;
  5224. return openInternal (pipeName, true);
  5225. }
  5226. bool NamedPipe::isOpen() const throw()
  5227. {
  5228. return internal != 0;
  5229. }
  5230. const String NamedPipe::getName() const throw()
  5231. {
  5232. return currentPipeName;
  5233. }
  5234. // other methods for this class are implemented in the platform-specific files
  5235. END_JUCE_NAMESPACE
  5236. /********* End of inlined file: juce_NamedPipe.cpp *********/
  5237. /********* Start of inlined file: juce_Socket.cpp *********/
  5238. #ifdef _WIN32
  5239. #include <winsock2.h>
  5240. #ifdef _MSC_VER
  5241. #pragma warning (disable : 4127 4389 4018)
  5242. #endif
  5243. #else
  5244. #ifdef LINUX
  5245. #include <sys/types.h>
  5246. #include <sys/socket.h>
  5247. #include <sys/errno.h>
  5248. #include <unistd.h>
  5249. #include <fcntl.h>
  5250. #include <netinet/in.h>
  5251. #else
  5252. #include <CoreServices/CoreServices.h>
  5253. #endif
  5254. #include <netdb.h>
  5255. #include <arpa/inet.h>
  5256. #include <netinet/tcp.h>
  5257. #endif
  5258. BEGIN_JUCE_NAMESPACE
  5259. #if JUCE_WIN32
  5260. typedef int (__stdcall juce_CloseWin32SocketLibCall) (void);
  5261. juce_CloseWin32SocketLibCall* juce_CloseWin32SocketLib = 0;
  5262. static void initWin32Sockets()
  5263. {
  5264. static CriticalSection lock;
  5265. const ScopedLock sl (lock);
  5266. if (juce_CloseWin32SocketLib == 0)
  5267. {
  5268. WSADATA wsaData;
  5269. const WORD wVersionRequested = MAKEWORD (1, 1);
  5270. WSAStartup (wVersionRequested, &wsaData);
  5271. juce_CloseWin32SocketLib = &WSACleanup;
  5272. }
  5273. }
  5274. #endif
  5275. static bool resetSocketOptions (const int handle, const bool isDatagram) throw()
  5276. {
  5277. if (handle <= 0)
  5278. return false;
  5279. const int sndBufSize = 65536;
  5280. const int rcvBufSize = 65536;
  5281. const int one = 1;
  5282. return setsockopt (handle, SOL_SOCKET, SO_RCVBUF, (const char*) &rcvBufSize, sizeof (int)) == 0
  5283. && setsockopt (handle, SOL_SOCKET, SO_SNDBUF, (const char*) &sndBufSize, sizeof (int)) == 0
  5284. && (isDatagram || (setsockopt (handle, IPPROTO_TCP, TCP_NODELAY, (const char*) &one, sizeof (int)) == 0));
  5285. }
  5286. static bool bindSocketToPort (const int handle, const int port) throw()
  5287. {
  5288. if (handle == 0 || port <= 0)
  5289. return false;
  5290. struct sockaddr_in servTmpAddr;
  5291. zerostruct (servTmpAddr);
  5292. servTmpAddr.sin_family = PF_INET;
  5293. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5294. servTmpAddr.sin_port = htons ((uint16) port);
  5295. return bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) >= 0;
  5296. }
  5297. static int readSocket (const int handle,
  5298. void* const destBuffer, const int maxBytesToRead,
  5299. bool volatile& connected) throw()
  5300. {
  5301. int bytesRead = 0;
  5302. while (bytesRead < maxBytesToRead)
  5303. {
  5304. int bytesThisTime;
  5305. #if JUCE_WIN32
  5306. bytesThisTime = recv (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead, 0);
  5307. #else
  5308. while ((bytesThisTime = ::read (handle, ((char*) destBuffer) + bytesRead, maxBytesToRead - bytesRead)) < 0
  5309. && errno == EINTR
  5310. && connected)
  5311. {
  5312. }
  5313. #endif
  5314. if (bytesThisTime <= 0 || ! connected)
  5315. {
  5316. if (bytesRead == 0)
  5317. bytesRead = -1;
  5318. break;
  5319. }
  5320. bytesRead += bytesThisTime;
  5321. }
  5322. return bytesRead;
  5323. }
  5324. static int waitForReadiness (const int handle, const bool forReading,
  5325. const int timeoutMsecs) throw()
  5326. {
  5327. struct timeval timeout;
  5328. struct timeval* timeoutp;
  5329. if (timeoutMsecs >= 0)
  5330. {
  5331. timeout.tv_sec = timeoutMsecs / 1000;
  5332. timeout.tv_usec = (timeoutMsecs % 1000) * 1000;
  5333. timeoutp = &timeout;
  5334. }
  5335. else
  5336. {
  5337. timeoutp = 0;
  5338. }
  5339. fd_set rset, wset;
  5340. FD_ZERO (&rset);
  5341. FD_SET (handle, &rset);
  5342. FD_ZERO (&wset);
  5343. FD_SET (handle, &wset);
  5344. fd_set* const prset = forReading ? &rset : 0;
  5345. fd_set* const pwset = forReading ? 0 : &wset;
  5346. #if JUCE_WIN32
  5347. if (select (handle + 1, prset, pwset, 0, timeoutp) < 0)
  5348. return -1;
  5349. #else
  5350. {
  5351. int result;
  5352. while ((result = select (handle + 1, prset, pwset, 0, timeoutp)) < 0
  5353. && errno == EINTR)
  5354. {
  5355. }
  5356. if (result < 0)
  5357. return -1;
  5358. }
  5359. #endif
  5360. {
  5361. int opt;
  5362. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  5363. socklen_t len = sizeof (opt);
  5364. #else
  5365. int len = sizeof (opt);
  5366. #endif
  5367. if (getsockopt (handle, SOL_SOCKET, SO_ERROR, (char*) &opt, &len) < 0
  5368. || opt != 0)
  5369. return -1;
  5370. }
  5371. if ((forReading && FD_ISSET (handle, &rset))
  5372. || ((! forReading) && FD_ISSET (handle, &wset)))
  5373. return 1;
  5374. return 0;
  5375. }
  5376. static bool setSocketBlockingState (const int handle, const bool shouldBlock) throw()
  5377. {
  5378. #if JUCE_WIN32
  5379. u_long nonBlocking = shouldBlock ? 0 : 1;
  5380. if (ioctlsocket (handle, FIONBIO, &nonBlocking) != 0)
  5381. return false;
  5382. #else
  5383. int socketFlags = fcntl (handle, F_GETFL, 0);
  5384. if (socketFlags == -1)
  5385. return false;
  5386. if (shouldBlock)
  5387. socketFlags &= ~O_NONBLOCK;
  5388. else
  5389. socketFlags |= O_NONBLOCK;
  5390. if (fcntl (handle, F_SETFL, socketFlags) != 0)
  5391. return false;
  5392. #endif
  5393. return true;
  5394. }
  5395. static bool connectSocket (int volatile& handle,
  5396. const bool isDatagram,
  5397. void** serverAddress,
  5398. const String& hostName,
  5399. const int portNumber,
  5400. const int timeOutMillisecs) throw()
  5401. {
  5402. struct hostent* const hostEnt = gethostbyname (hostName);
  5403. if (hostEnt == 0)
  5404. return false;
  5405. struct in_addr targetAddress;
  5406. memcpy (&targetAddress.s_addr,
  5407. *(hostEnt->h_addr_list),
  5408. sizeof (targetAddress.s_addr));
  5409. struct sockaddr_in servTmpAddr;
  5410. zerostruct (servTmpAddr);
  5411. servTmpAddr.sin_family = PF_INET;
  5412. servTmpAddr.sin_addr = targetAddress;
  5413. servTmpAddr.sin_port = htons ((uint16) portNumber);
  5414. if (handle < 0)
  5415. handle = (int) socket (AF_INET, isDatagram ? SOCK_DGRAM : SOCK_STREAM, 0);
  5416. if (handle < 0)
  5417. return false;
  5418. if (isDatagram)
  5419. {
  5420. *serverAddress = new struct sockaddr_in();
  5421. *((struct sockaddr_in*) *serverAddress) = servTmpAddr;
  5422. return true;
  5423. }
  5424. setSocketBlockingState (handle, false);
  5425. const int result = ::connect (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in));
  5426. if (result < 0)
  5427. {
  5428. #if JUCE_WIN32
  5429. if (result == SOCKET_ERROR && WSAGetLastError() == WSAEWOULDBLOCK)
  5430. #else
  5431. if (errno == EINPROGRESS)
  5432. #endif
  5433. {
  5434. if (waitForReadiness (handle, false, timeOutMillisecs) != 1)
  5435. {
  5436. setSocketBlockingState (handle, true);
  5437. return false;
  5438. }
  5439. }
  5440. }
  5441. setSocketBlockingState (handle, true);
  5442. resetSocketOptions (handle, false);
  5443. return true;
  5444. }
  5445. StreamingSocket::StreamingSocket()
  5446. : portNumber (0),
  5447. handle (-1),
  5448. connected (false),
  5449. isListener (false)
  5450. {
  5451. #if JUCE_WIN32
  5452. initWin32Sockets();
  5453. #endif
  5454. }
  5455. StreamingSocket::StreamingSocket (const String& hostName_,
  5456. const int portNumber_,
  5457. const int handle_)
  5458. : hostName (hostName_),
  5459. portNumber (portNumber_),
  5460. handle (handle_),
  5461. connected (true),
  5462. isListener (false)
  5463. {
  5464. #if JUCE_WIN32
  5465. initWin32Sockets();
  5466. #endif
  5467. resetSocketOptions (handle_, false);
  5468. }
  5469. StreamingSocket::~StreamingSocket()
  5470. {
  5471. close();
  5472. }
  5473. int StreamingSocket::read (void* destBuffer, const int maxBytesToRead)
  5474. {
  5475. return (connected && ! isListener) ? readSocket (handle, destBuffer, maxBytesToRead, connected)
  5476. : -1;
  5477. }
  5478. int StreamingSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  5479. {
  5480. if (isListener || ! connected)
  5481. return -1;
  5482. #if JUCE_WIN32
  5483. return send (handle, (const char*) sourceBuffer, numBytesToWrite, 0);
  5484. #else
  5485. int result;
  5486. while ((result = ::write (handle, sourceBuffer, numBytesToWrite)) < 0
  5487. && errno == EINTR)
  5488. {
  5489. }
  5490. return result;
  5491. #endif
  5492. }
  5493. int StreamingSocket::waitUntilReady (const bool readyForReading,
  5494. const int timeoutMsecs) const
  5495. {
  5496. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  5497. : -1;
  5498. }
  5499. bool StreamingSocket::bindToPort (const int port)
  5500. {
  5501. return bindSocketToPort (handle, port);
  5502. }
  5503. bool StreamingSocket::connect (const String& remoteHostName,
  5504. const int remotePortNumber,
  5505. const int timeOutMillisecs)
  5506. {
  5507. if (isListener)
  5508. {
  5509. jassertfalse // a listener socket can't connect to another one!
  5510. return false;
  5511. }
  5512. if (connected)
  5513. close();
  5514. hostName = remoteHostName;
  5515. portNumber = remotePortNumber;
  5516. isListener = false;
  5517. connected = connectSocket (handle, false, 0, remoteHostName,
  5518. remotePortNumber, timeOutMillisecs);
  5519. if (! (connected && resetSocketOptions (handle, false)))
  5520. {
  5521. close();
  5522. return false;
  5523. }
  5524. return true;
  5525. }
  5526. void StreamingSocket::close()
  5527. {
  5528. #if JUCE_WIN32
  5529. closesocket (handle);
  5530. connected = false;
  5531. #else
  5532. if (connected)
  5533. {
  5534. connected = false;
  5535. if (isListener)
  5536. {
  5537. // need to do this to interrupt the accept() function..
  5538. StreamingSocket temp;
  5539. temp.connect ("localhost", portNumber, 1000);
  5540. }
  5541. }
  5542. ::close (handle);
  5543. #endif
  5544. hostName = String::empty;
  5545. portNumber = 0;
  5546. handle = -1;
  5547. isListener = false;
  5548. }
  5549. bool StreamingSocket::createListener (const int newPortNumber)
  5550. {
  5551. if (connected)
  5552. close();
  5553. hostName = "listener";
  5554. portNumber = newPortNumber;
  5555. isListener = true;
  5556. struct sockaddr_in servTmpAddr;
  5557. zerostruct (servTmpAddr);
  5558. servTmpAddr.sin_family = PF_INET;
  5559. servTmpAddr.sin_addr.s_addr = htonl (INADDR_ANY);
  5560. servTmpAddr.sin_port = htons ((uint16) portNumber);
  5561. handle = (int) socket (AF_INET, SOCK_STREAM, 0);
  5562. if (handle < 0)
  5563. return false;
  5564. const int reuse = 1;
  5565. setsockopt (handle, SOL_SOCKET, SO_REUSEADDR, (const char*) &reuse, sizeof (reuse));
  5566. if (bind (handle, (struct sockaddr*) &servTmpAddr, sizeof (struct sockaddr_in)) < 0
  5567. || listen (handle, SOMAXCONN) < 0)
  5568. {
  5569. close();
  5570. return false;
  5571. }
  5572. connected = true;
  5573. return true;
  5574. }
  5575. StreamingSocket* StreamingSocket::waitForNextConnection() const
  5576. {
  5577. jassert (isListener || ! connected); // to call this method, you first have to use createListener() to
  5578. // prepare this socket as a listener.
  5579. if (connected && isListener)
  5580. {
  5581. struct sockaddr address;
  5582. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  5583. socklen_t len = sizeof (sockaddr);
  5584. #else
  5585. int len = sizeof (sockaddr);
  5586. #endif
  5587. const int newSocket = (int) accept (handle, &address, &len);
  5588. if (newSocket >= 0 && connected)
  5589. return new StreamingSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  5590. portNumber, newSocket);
  5591. }
  5592. return 0;
  5593. }
  5594. bool StreamingSocket::isLocal() const throw()
  5595. {
  5596. return hostName == T("127.0.0.1");
  5597. }
  5598. DatagramSocket::DatagramSocket (const int localPortNumber)
  5599. : portNumber (0),
  5600. handle (-1),
  5601. connected (false),
  5602. serverAddress (0)
  5603. {
  5604. #if JUCE_WIN32
  5605. initWin32Sockets();
  5606. #endif
  5607. handle = (int) socket (AF_INET, SOCK_DGRAM, 0);
  5608. bindToPort (localPortNumber);
  5609. }
  5610. DatagramSocket::DatagramSocket (const String& hostName_, const int portNumber_,
  5611. const int handle_, const int localPortNumber)
  5612. : hostName (hostName_),
  5613. portNumber (portNumber_),
  5614. handle (handle_),
  5615. connected (true),
  5616. serverAddress (0)
  5617. {
  5618. #if JUCE_WIN32
  5619. initWin32Sockets();
  5620. #endif
  5621. resetSocketOptions (handle_, true);
  5622. bindToPort (localPortNumber);
  5623. }
  5624. DatagramSocket::~DatagramSocket()
  5625. {
  5626. close();
  5627. delete ((struct sockaddr_in*) serverAddress);
  5628. serverAddress = 0;
  5629. }
  5630. void DatagramSocket::close()
  5631. {
  5632. #if JUCE_WIN32
  5633. closesocket (handle);
  5634. connected = false;
  5635. #else
  5636. connected = false;
  5637. ::close (handle);
  5638. #endif
  5639. hostName = String::empty;
  5640. portNumber = 0;
  5641. handle = -1;
  5642. }
  5643. bool DatagramSocket::bindToPort (const int port)
  5644. {
  5645. return bindSocketToPort (handle, port);
  5646. }
  5647. bool DatagramSocket::connect (const String& remoteHostName,
  5648. const int remotePortNumber,
  5649. const int timeOutMillisecs)
  5650. {
  5651. if (connected)
  5652. close();
  5653. hostName = remoteHostName;
  5654. portNumber = remotePortNumber;
  5655. connected = connectSocket (handle, true, &serverAddress,
  5656. remoteHostName, remotePortNumber,
  5657. timeOutMillisecs);
  5658. if (! (connected && resetSocketOptions (handle, true)))
  5659. {
  5660. close();
  5661. return false;
  5662. }
  5663. return true;
  5664. }
  5665. DatagramSocket* DatagramSocket::waitForNextConnection() const
  5666. {
  5667. struct sockaddr address;
  5668. #if defined (JUCE_LINUX) || (defined (JUCE_MAC) && ! MACOS_10_2_OR_EARLIER)
  5669. socklen_t len = sizeof (sockaddr);
  5670. #else
  5671. int len = sizeof (sockaddr);
  5672. #endif
  5673. while (waitUntilReady (true, -1) == 1)
  5674. {
  5675. char buf[1];
  5676. if (recvfrom (handle, buf, 0, 0, &address, &len) > 0)
  5677. {
  5678. return new DatagramSocket (inet_ntoa (((struct sockaddr_in*) &address)->sin_addr),
  5679. ntohs (((struct sockaddr_in*) &address)->sin_port),
  5680. -1, -1);
  5681. }
  5682. }
  5683. return 0;
  5684. }
  5685. int DatagramSocket::waitUntilReady (const bool readyForReading,
  5686. const int timeoutMsecs) const
  5687. {
  5688. return connected ? waitForReadiness (handle, readyForReading, timeoutMsecs)
  5689. : -1;
  5690. }
  5691. int DatagramSocket::read (void* destBuffer, const int maxBytesToRead)
  5692. {
  5693. return connected ? readSocket (handle, destBuffer, maxBytesToRead, connected)
  5694. : -1;
  5695. }
  5696. int DatagramSocket::write (const void* sourceBuffer, const int numBytesToWrite)
  5697. {
  5698. // You need to call connect() first to set the server address..
  5699. jassert (serverAddress != 0 && connected);
  5700. return connected ? sendto (handle, (const char*) sourceBuffer,
  5701. numBytesToWrite, 0,
  5702. (const struct sockaddr*) serverAddress,
  5703. sizeof (struct sockaddr_in))
  5704. : -1;
  5705. }
  5706. bool DatagramSocket::isLocal() const throw()
  5707. {
  5708. return hostName == T("127.0.0.1");
  5709. }
  5710. END_JUCE_NAMESPACE
  5711. /********* End of inlined file: juce_Socket.cpp *********/
  5712. /********* Start of inlined file: juce_URL.cpp *********/
  5713. BEGIN_JUCE_NAMESPACE
  5714. URL::URL() throw()
  5715. {
  5716. }
  5717. URL::URL (const String& url_)
  5718. : url (url_)
  5719. {
  5720. int i = url.indexOfChar (T('?'));
  5721. if (i >= 0)
  5722. {
  5723. do
  5724. {
  5725. const int nextAmp = url.indexOfChar (i + 1, T('&'));
  5726. const int equalsPos = url.indexOfChar (i + 1, T('='));
  5727. if (equalsPos > i + 1)
  5728. {
  5729. if (nextAmp < 0)
  5730. {
  5731. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  5732. removeEscapeChars (url.substring (equalsPos + 1)));
  5733. }
  5734. else if (nextAmp > 0 && equalsPos < nextAmp)
  5735. {
  5736. parameters.set (removeEscapeChars (url.substring (i + 1, equalsPos)),
  5737. removeEscapeChars (url.substring (equalsPos + 1, nextAmp)));
  5738. }
  5739. }
  5740. i = nextAmp;
  5741. }
  5742. while (i >= 0);
  5743. url = url.upToFirstOccurrenceOf (T("?"), false, false);
  5744. }
  5745. }
  5746. URL::URL (const URL& other)
  5747. : url (other.url),
  5748. parameters (other.parameters),
  5749. filesToUpload (other.filesToUpload),
  5750. mimeTypes (other.mimeTypes)
  5751. {
  5752. }
  5753. const URL& URL::operator= (const URL& other)
  5754. {
  5755. url = other.url;
  5756. parameters = other.parameters;
  5757. filesToUpload = other.filesToUpload;
  5758. mimeTypes = other.mimeTypes;
  5759. return *this;
  5760. }
  5761. URL::~URL() throw()
  5762. {
  5763. }
  5764. static const String getMangledParameters (const StringPairArray& parameters)
  5765. {
  5766. String p;
  5767. for (int i = 0; i < parameters.size(); ++i)
  5768. {
  5769. if (i > 0)
  5770. p += T("&");
  5771. p << URL::addEscapeChars (parameters.getAllKeys() [i], true)
  5772. << T("=")
  5773. << URL::addEscapeChars (parameters.getAllValues() [i], true);
  5774. }
  5775. return p;
  5776. }
  5777. const String URL::toString (const bool includeGetParameters) const
  5778. {
  5779. if (includeGetParameters && parameters.size() > 0)
  5780. return url + T("?") + getMangledParameters (parameters);
  5781. else
  5782. return url;
  5783. }
  5784. bool URL::isWellFormed() const
  5785. {
  5786. //xxx TODO
  5787. return url.isNotEmpty();
  5788. }
  5789. bool URL::isProbablyAWebsiteURL (const String& possibleURL)
  5790. {
  5791. return (possibleURL.containsChar (T('.'))
  5792. && (! possibleURL.containsChar (T('@')))
  5793. && (! possibleURL.endsWithChar (T('.')))
  5794. && (possibleURL.startsWithIgnoreCase (T("www."))
  5795. || possibleURL.startsWithIgnoreCase (T("http:"))
  5796. || possibleURL.startsWithIgnoreCase (T("ftp:"))
  5797. || possibleURL.endsWithIgnoreCase (T(".com"))
  5798. || possibleURL.endsWithIgnoreCase (T(".net"))
  5799. || possibleURL.endsWithIgnoreCase (T(".org"))
  5800. || possibleURL.endsWithIgnoreCase (T(".co.uk")))
  5801. || possibleURL.startsWithIgnoreCase (T("file:")));
  5802. }
  5803. bool URL::isProbablyAnEmailAddress (const String& possibleEmailAddress)
  5804. {
  5805. const int atSign = possibleEmailAddress.indexOfChar (T('@'));
  5806. return atSign > 0
  5807. && possibleEmailAddress.lastIndexOfChar (T('.')) > (atSign + 1)
  5808. && (! possibleEmailAddress.endsWithChar (T('.')));
  5809. }
  5810. void* juce_openInternetFile (const String& url,
  5811. const String& headers,
  5812. const MemoryBlock& optionalPostData,
  5813. const bool isPost,
  5814. URL::OpenStreamProgressCallback* callback,
  5815. void* callbackContext,
  5816. int timeOutMs);
  5817. void juce_closeInternetFile (void* handle);
  5818. int juce_readFromInternetFile (void* handle, void* dest, int bytesToRead);
  5819. int juce_seekInInternetFile (void* handle, int newPosition);
  5820. class WebInputStream : public InputStream
  5821. {
  5822. public:
  5823. WebInputStream (const URL& url,
  5824. const bool isPost_,
  5825. URL::OpenStreamProgressCallback* const progressCallback_,
  5826. void* const progressCallbackContext_,
  5827. const String& extraHeaders,
  5828. int timeOutMs_)
  5829. : position (0),
  5830. finished (false),
  5831. isPost (isPost_),
  5832. progressCallback (progressCallback_),
  5833. progressCallbackContext (progressCallbackContext_),
  5834. timeOutMs (timeOutMs_)
  5835. {
  5836. server = url.toString (! isPost);
  5837. if (isPost_)
  5838. createHeadersAndPostData (url);
  5839. headers += extraHeaders;
  5840. if (! headers.endsWithChar (T('\n')))
  5841. headers << "\r\n";
  5842. handle = juce_openInternetFile (server, headers, postData, isPost,
  5843. progressCallback_, progressCallbackContext_,
  5844. timeOutMs);
  5845. }
  5846. ~WebInputStream()
  5847. {
  5848. juce_closeInternetFile (handle);
  5849. }
  5850. bool isError() const throw()
  5851. {
  5852. return handle == 0;
  5853. }
  5854. int64 getTotalLength()
  5855. {
  5856. return -1;
  5857. }
  5858. bool isExhausted()
  5859. {
  5860. return finished;
  5861. }
  5862. int read (void* dest, int bytes)
  5863. {
  5864. if (finished || isError())
  5865. {
  5866. return 0;
  5867. }
  5868. else
  5869. {
  5870. const int bytesRead = juce_readFromInternetFile (handle, dest, bytes);
  5871. position += bytesRead;
  5872. if (bytesRead == 0)
  5873. finished = true;
  5874. return bytesRead;
  5875. }
  5876. }
  5877. int64 getPosition()
  5878. {
  5879. return position;
  5880. }
  5881. bool setPosition (int64 wantedPos)
  5882. {
  5883. if (wantedPos != position)
  5884. {
  5885. finished = false;
  5886. const int actualPos = juce_seekInInternetFile (handle, (int) wantedPos);
  5887. if (actualPos == wantedPos)
  5888. {
  5889. position = wantedPos;
  5890. }
  5891. else
  5892. {
  5893. if (wantedPos < position)
  5894. {
  5895. juce_closeInternetFile (handle);
  5896. position = 0;
  5897. finished = false;
  5898. handle = juce_openInternetFile (server, headers, postData, isPost,
  5899. progressCallback, progressCallbackContext,
  5900. timeOutMs);
  5901. }
  5902. skipNextBytes (wantedPos - position);
  5903. }
  5904. }
  5905. return true;
  5906. }
  5907. juce_UseDebuggingNewOperator
  5908. private:
  5909. String server, headers;
  5910. MemoryBlock postData;
  5911. int64 position;
  5912. bool finished;
  5913. const bool isPost;
  5914. void* handle;
  5915. URL::OpenStreamProgressCallback* const progressCallback;
  5916. void* const progressCallbackContext;
  5917. const int timeOutMs;
  5918. void createHeadersAndPostData (const URL& url)
  5919. {
  5920. if (url.getFilesToUpload().size() > 0)
  5921. {
  5922. // need to upload some files, so do it as multi-part...
  5923. String boundary (String::toHexString (Random::getSystemRandom().nextInt64()));
  5924. headers << "Content-Type: multipart/form-data; boundary=" << boundary << "\r\n";
  5925. appendUTF8ToPostData ("--" + boundary);
  5926. int i;
  5927. for (i = 0; i < url.getParameters().size(); ++i)
  5928. {
  5929. String s;
  5930. s << "\r\nContent-Disposition: form-data; name=\""
  5931. << url.getParameters().getAllKeys() [i]
  5932. << "\"\r\n\r\n"
  5933. << url.getParameters().getAllValues() [i]
  5934. << "\r\n--"
  5935. << boundary;
  5936. appendUTF8ToPostData (s);
  5937. }
  5938. for (i = 0; i < url.getFilesToUpload().size(); ++i)
  5939. {
  5940. const File f (url.getFilesToUpload().getAllValues() [i]);
  5941. const String paramName (url.getFilesToUpload().getAllKeys() [i]);
  5942. String s;
  5943. s << "\r\nContent-Disposition: form-data; name=\""
  5944. << paramName
  5945. << "\"; filename=\""
  5946. << f.getFileName()
  5947. << "\"\r\n";
  5948. const String mimeType (url.getMimeTypesOfUploadFiles()
  5949. .getValue (paramName, String::empty));
  5950. if (mimeType.isNotEmpty())
  5951. s << "Content-Type: " << mimeType << "\r\n";
  5952. s << "Content-Transfer-Encoding: binary\r\n\r\n";
  5953. appendUTF8ToPostData (s);
  5954. f.loadFileAsData (postData);
  5955. s = "\r\n--" + boundary;
  5956. appendUTF8ToPostData (s);
  5957. }
  5958. appendUTF8ToPostData ("--\r\n");
  5959. }
  5960. else
  5961. {
  5962. // just a short text attachment, so use simple url encoding..
  5963. const String params (getMangledParameters (url.getParameters()));
  5964. headers = "Content-Type: application/x-www-form-urlencoded\r\nContent-length: "
  5965. + String ((int) strlen (params.toUTF8()))
  5966. + "\r\n";
  5967. appendUTF8ToPostData (params);
  5968. }
  5969. }
  5970. void appendUTF8ToPostData (const String& text) throw()
  5971. {
  5972. postData.append (text.toUTF8(),
  5973. (int) strlen (text.toUTF8()));
  5974. }
  5975. WebInputStream (const WebInputStream&);
  5976. const WebInputStream& operator= (const WebInputStream&);
  5977. };
  5978. InputStream* URL::createInputStream (const bool usePostCommand,
  5979. OpenStreamProgressCallback* const progressCallback,
  5980. void* const progressCallbackContext,
  5981. const String& extraHeaders,
  5982. const int timeOutMs) const
  5983. {
  5984. WebInputStream* wi = new WebInputStream (*this, usePostCommand,
  5985. progressCallback, progressCallbackContext,
  5986. extraHeaders,
  5987. timeOutMs);
  5988. if (wi->isError())
  5989. {
  5990. delete wi;
  5991. wi = 0;
  5992. }
  5993. return wi;
  5994. }
  5995. bool URL::readEntireBinaryStream (MemoryBlock& destData,
  5996. const bool usePostCommand) const
  5997. {
  5998. InputStream* const in = createInputStream (usePostCommand);
  5999. if (in != 0)
  6000. {
  6001. in->readIntoMemoryBlock (destData, -1);
  6002. delete in;
  6003. return true;
  6004. }
  6005. return false;
  6006. }
  6007. const String URL::readEntireTextStream (const bool usePostCommand) const
  6008. {
  6009. String result;
  6010. InputStream* const in = createInputStream (usePostCommand);
  6011. if (in != 0)
  6012. {
  6013. result = in->readEntireStreamAsString();
  6014. delete in;
  6015. }
  6016. return result;
  6017. }
  6018. XmlElement* URL::readEntireXmlStream (const bool usePostCommand) const
  6019. {
  6020. XmlDocument doc (readEntireTextStream (usePostCommand));
  6021. return doc.getDocumentElement();
  6022. }
  6023. const URL URL::withParameter (const String& parameterName,
  6024. const String& parameterValue) const
  6025. {
  6026. URL u (*this);
  6027. u.parameters.set (parameterName, parameterValue);
  6028. return u;
  6029. }
  6030. const URL URL::withFileToUpload (const String& parameterName,
  6031. const File& fileToUpload,
  6032. const String& mimeType) const
  6033. {
  6034. URL u (*this);
  6035. u.filesToUpload.set (parameterName, fileToUpload.getFullPathName());
  6036. u.mimeTypes.set (parameterName, mimeType);
  6037. return u;
  6038. }
  6039. const StringPairArray& URL::getParameters() const throw()
  6040. {
  6041. return parameters;
  6042. }
  6043. const StringPairArray& URL::getFilesToUpload() const throw()
  6044. {
  6045. return filesToUpload;
  6046. }
  6047. const StringPairArray& URL::getMimeTypesOfUploadFiles() const throw()
  6048. {
  6049. return mimeTypes;
  6050. }
  6051. const String URL::removeEscapeChars (const String& s)
  6052. {
  6053. const int len = s.length();
  6054. uint8* const resultUTF8 = (uint8*) juce_calloc (len * 4);
  6055. uint8* r = resultUTF8;
  6056. for (int i = 0; i < len; ++i)
  6057. {
  6058. char c = (char) s[i];
  6059. if (c == 0)
  6060. break;
  6061. if (c == '+')
  6062. {
  6063. c = ' ';
  6064. }
  6065. else if (c == '%')
  6066. {
  6067. c = (char) s.substring (i + 1, i + 3).getHexValue32();
  6068. i += 2;
  6069. }
  6070. *r++ = c;
  6071. }
  6072. const String stringResult (String::fromUTF8 (resultUTF8));
  6073. juce_free (resultUTF8);
  6074. return stringResult;
  6075. }
  6076. const String URL::addEscapeChars (const String& s, const bool isParameter)
  6077. {
  6078. String result;
  6079. result.preallocateStorage (s.length() + 8);
  6080. const char* utf8 = s.toUTF8();
  6081. const char* legalChars = isParameter ? "_-.*!'()"
  6082. : "_-$.*!'(),";
  6083. while (*utf8 != 0)
  6084. {
  6085. const char c = *utf8++;
  6086. if (c == ' ')
  6087. {
  6088. result += T('+');
  6089. }
  6090. else if (CharacterFunctions::isLetterOrDigit (c)
  6091. || CharacterFunctions::indexOfChar (legalChars, c, false) >= 0)
  6092. {
  6093. result << c;
  6094. }
  6095. else
  6096. {
  6097. const int v = (int) (uint8) c;
  6098. if (v < 0x10)
  6099. result << T("%0");
  6100. else
  6101. result << T('%');
  6102. result << String::toHexString (v);
  6103. }
  6104. }
  6105. return result;
  6106. }
  6107. extern bool juce_launchFile (const String& fileName,
  6108. const String& parameters) throw();
  6109. bool URL::launchInDefaultBrowser() const
  6110. {
  6111. String u (toString (true));
  6112. if (u.contains (T("@")) && ! u.contains (T(":")))
  6113. u = "mailto:" + u;
  6114. return juce_launchFile (u, String::empty);
  6115. }
  6116. END_JUCE_NAMESPACE
  6117. /********* End of inlined file: juce_URL.cpp *********/
  6118. /********* Start of inlined file: juce_BufferedInputStream.cpp *********/
  6119. BEGIN_JUCE_NAMESPACE
  6120. BufferedInputStream::BufferedInputStream (InputStream* const source_,
  6121. const int bufferSize_,
  6122. const bool deleteSourceWhenDestroyed_) throw()
  6123. : source (source_),
  6124. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  6125. bufferSize (jmax (256, bufferSize_)),
  6126. position (source_->getPosition()),
  6127. lastReadPos (0),
  6128. bufferOverlap (128)
  6129. {
  6130. const int sourceSize = (int) source_->getTotalLength();
  6131. if (sourceSize >= 0)
  6132. bufferSize = jmin (jmax (32, sourceSize), bufferSize);
  6133. bufferStart = position;
  6134. buffer = (char*) juce_malloc (bufferSize);
  6135. }
  6136. BufferedInputStream::~BufferedInputStream() throw()
  6137. {
  6138. if (deleteSourceWhenDestroyed)
  6139. delete source;
  6140. juce_free (buffer);
  6141. }
  6142. int64 BufferedInputStream::getTotalLength()
  6143. {
  6144. return source->getTotalLength();
  6145. }
  6146. int64 BufferedInputStream::getPosition()
  6147. {
  6148. return position;
  6149. }
  6150. bool BufferedInputStream::setPosition (int64 newPosition)
  6151. {
  6152. position = jmax ((int64) 0, newPosition);
  6153. return true;
  6154. }
  6155. bool BufferedInputStream::isExhausted()
  6156. {
  6157. return (position >= lastReadPos)
  6158. && source->isExhausted();
  6159. }
  6160. void BufferedInputStream::ensureBuffered()
  6161. {
  6162. const int64 bufferEndOverlap = lastReadPos - bufferOverlap;
  6163. if (position < bufferStart || position >= bufferEndOverlap)
  6164. {
  6165. int bytesRead;
  6166. if (position < lastReadPos
  6167. && position >= bufferEndOverlap
  6168. && position >= bufferStart)
  6169. {
  6170. const int bytesToKeep = (int) (lastReadPos - position);
  6171. memmove (buffer, buffer + position - bufferStart, bytesToKeep);
  6172. bufferStart = position;
  6173. bytesRead = source->read (buffer + bytesToKeep,
  6174. bufferSize - bytesToKeep);
  6175. lastReadPos += bytesRead;
  6176. bytesRead += bytesToKeep;
  6177. }
  6178. else
  6179. {
  6180. bufferStart = position;
  6181. source->setPosition (bufferStart);
  6182. bytesRead = source->read (buffer, bufferSize);
  6183. lastReadPos = bufferStart + bytesRead;
  6184. }
  6185. while (bytesRead < bufferSize)
  6186. buffer [bytesRead++] = 0;
  6187. }
  6188. }
  6189. int BufferedInputStream::read (void* destBuffer, int maxBytesToRead)
  6190. {
  6191. if (position >= bufferStart
  6192. && position + maxBytesToRead <= lastReadPos)
  6193. {
  6194. memcpy (destBuffer, buffer + (position - bufferStart), maxBytesToRead);
  6195. position += maxBytesToRead;
  6196. return maxBytesToRead;
  6197. }
  6198. else
  6199. {
  6200. if (position < bufferStart || position >= lastReadPos)
  6201. ensureBuffered();
  6202. int bytesRead = 0;
  6203. while (maxBytesToRead > 0)
  6204. {
  6205. const int bytesAvailable = jmin (maxBytesToRead, (int) (lastReadPos - position));
  6206. if (bytesAvailable > 0)
  6207. {
  6208. memcpy (destBuffer, buffer + (position - bufferStart), bytesAvailable);
  6209. maxBytesToRead -= bytesAvailable;
  6210. bytesRead += bytesAvailable;
  6211. position += bytesAvailable;
  6212. destBuffer = (void*) (((char*) destBuffer) + bytesAvailable);
  6213. }
  6214. ensureBuffered();
  6215. if (isExhausted())
  6216. break;
  6217. }
  6218. return bytesRead;
  6219. }
  6220. }
  6221. const String BufferedInputStream::readString()
  6222. {
  6223. if (position >= bufferStart
  6224. && position < lastReadPos)
  6225. {
  6226. const int maxChars = (int) (lastReadPos - position);
  6227. const char* const src = buffer + (position - bufferStart);
  6228. for (int i = 0; i < maxChars; ++i)
  6229. {
  6230. if (src[i] == 0)
  6231. {
  6232. position += i + 1;
  6233. return String::fromUTF8 ((const uint8*) src, i);
  6234. }
  6235. }
  6236. }
  6237. return InputStream::readString();
  6238. }
  6239. END_JUCE_NAMESPACE
  6240. /********* End of inlined file: juce_BufferedInputStream.cpp *********/
  6241. /********* Start of inlined file: juce_FileInputSource.cpp *********/
  6242. BEGIN_JUCE_NAMESPACE
  6243. FileInputSource::FileInputSource (const File& file_) throw()
  6244. : file (file_)
  6245. {
  6246. }
  6247. FileInputSource::~FileInputSource()
  6248. {
  6249. }
  6250. InputStream* FileInputSource::createInputStream()
  6251. {
  6252. return file.createInputStream();
  6253. }
  6254. InputStream* FileInputSource::createInputStreamFor (const String& relatedItemPath)
  6255. {
  6256. return file.getSiblingFile (relatedItemPath).createInputStream();
  6257. }
  6258. int64 FileInputSource::hashCode() const
  6259. {
  6260. return file.hashCode();
  6261. }
  6262. END_JUCE_NAMESPACE
  6263. /********* End of inlined file: juce_FileInputSource.cpp *********/
  6264. /********* Start of inlined file: juce_MemoryInputStream.cpp *********/
  6265. BEGIN_JUCE_NAMESPACE
  6266. MemoryInputStream::MemoryInputStream (const void* const sourceData,
  6267. const int sourceDataSize,
  6268. const bool keepInternalCopy) throw()
  6269. : data ((const char*) sourceData),
  6270. dataSize (sourceDataSize),
  6271. position (0)
  6272. {
  6273. if (keepInternalCopy)
  6274. {
  6275. internalCopy.append (data, sourceDataSize);
  6276. data = (const char*) internalCopy.getData();
  6277. }
  6278. }
  6279. MemoryInputStream::~MemoryInputStream() throw()
  6280. {
  6281. }
  6282. int64 MemoryInputStream::getTotalLength()
  6283. {
  6284. return dataSize;
  6285. }
  6286. int MemoryInputStream::read (void* buffer, int howMany)
  6287. {
  6288. const int num = jmin (howMany, dataSize - position);
  6289. memcpy (buffer, data + position, num);
  6290. position += num;
  6291. return num;
  6292. }
  6293. bool MemoryInputStream::isExhausted()
  6294. {
  6295. return (position >= dataSize);
  6296. }
  6297. bool MemoryInputStream::setPosition (int64 pos)
  6298. {
  6299. position = (int) jlimit ((int64) 0, (int64) dataSize, pos);
  6300. return true;
  6301. }
  6302. int64 MemoryInputStream::getPosition()
  6303. {
  6304. return position;
  6305. }
  6306. END_JUCE_NAMESPACE
  6307. /********* End of inlined file: juce_MemoryInputStream.cpp *********/
  6308. /********* Start of inlined file: juce_MemoryOutputStream.cpp *********/
  6309. BEGIN_JUCE_NAMESPACE
  6310. MemoryOutputStream::MemoryOutputStream (const int initialSize,
  6311. const int blockSizeToIncreaseBy,
  6312. MemoryBlock* const memoryBlockToWriteTo) throw()
  6313. : data (memoryBlockToWriteTo),
  6314. position (0),
  6315. size (0),
  6316. blockSize (jmax (16, blockSizeToIncreaseBy)),
  6317. ownsMemoryBlock (memoryBlockToWriteTo == 0)
  6318. {
  6319. if (memoryBlockToWriteTo == 0)
  6320. data = new MemoryBlock (initialSize);
  6321. else
  6322. memoryBlockToWriteTo->setSize (initialSize, false);
  6323. }
  6324. MemoryOutputStream::~MemoryOutputStream() throw()
  6325. {
  6326. if (ownsMemoryBlock)
  6327. delete data;
  6328. else
  6329. flush();
  6330. }
  6331. void MemoryOutputStream::flush()
  6332. {
  6333. if (! ownsMemoryBlock)
  6334. data->setSize (size, false);
  6335. }
  6336. void MemoryOutputStream::reset() throw()
  6337. {
  6338. position = 0;
  6339. size = 0;
  6340. }
  6341. bool MemoryOutputStream::write (const void* buffer, int howMany)
  6342. {
  6343. int storageNeeded = position + howMany + 1;
  6344. storageNeeded = storageNeeded - (storageNeeded % blockSize) + blockSize;
  6345. data->ensureSize (storageNeeded);
  6346. data->copyFrom (buffer, position, howMany);
  6347. position += howMany;
  6348. size = jmax (size, position);
  6349. return true;
  6350. }
  6351. const char* MemoryOutputStream::getData() throw()
  6352. {
  6353. if (data->getSize() > size)
  6354. ((char*) data->getData()) [size] = 0;
  6355. return (const char*) data->getData();
  6356. }
  6357. int MemoryOutputStream::getDataSize() const throw()
  6358. {
  6359. return size;
  6360. }
  6361. int64 MemoryOutputStream::getPosition()
  6362. {
  6363. return position;
  6364. }
  6365. bool MemoryOutputStream::setPosition (int64 newPosition)
  6366. {
  6367. if (newPosition <= size)
  6368. {
  6369. // ok to seek backwards
  6370. position = jlimit (0, size, (int) newPosition);
  6371. return true;
  6372. }
  6373. else
  6374. {
  6375. // trying to make it bigger isn't a good thing to do..
  6376. return false;
  6377. }
  6378. }
  6379. END_JUCE_NAMESPACE
  6380. /********* End of inlined file: juce_MemoryOutputStream.cpp *********/
  6381. /********* Start of inlined file: juce_SubregionStream.cpp *********/
  6382. BEGIN_JUCE_NAMESPACE
  6383. SubregionStream::SubregionStream (InputStream* const sourceStream,
  6384. const int64 startPositionInSourceStream_,
  6385. const int64 lengthOfSourceStream_,
  6386. const bool deleteSourceWhenDestroyed_) throw()
  6387. : source (sourceStream),
  6388. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  6389. startPositionInSourceStream (startPositionInSourceStream_),
  6390. lengthOfSourceStream (lengthOfSourceStream_)
  6391. {
  6392. setPosition (0);
  6393. }
  6394. SubregionStream::~SubregionStream() throw()
  6395. {
  6396. if (deleteSourceWhenDestroyed)
  6397. delete source;
  6398. }
  6399. int64 SubregionStream::getTotalLength()
  6400. {
  6401. const int64 srcLen = source->getTotalLength() - startPositionInSourceStream;
  6402. return (lengthOfSourceStream >= 0) ? jmin (lengthOfSourceStream, srcLen)
  6403. : srcLen;
  6404. }
  6405. int64 SubregionStream::getPosition()
  6406. {
  6407. return source->getPosition() - startPositionInSourceStream;
  6408. }
  6409. bool SubregionStream::setPosition (int64 newPosition)
  6410. {
  6411. return source->setPosition (jmax ((int64) 0, newPosition + startPositionInSourceStream));
  6412. }
  6413. int SubregionStream::read (void* destBuffer, int maxBytesToRead)
  6414. {
  6415. if (lengthOfSourceStream < 0)
  6416. {
  6417. return source->read (destBuffer, maxBytesToRead);
  6418. }
  6419. else
  6420. {
  6421. maxBytesToRead = (int) jmin ((int64) maxBytesToRead, lengthOfSourceStream - getPosition());
  6422. if (maxBytesToRead <= 0)
  6423. return 0;
  6424. return source->read (destBuffer, maxBytesToRead);
  6425. }
  6426. }
  6427. bool SubregionStream::isExhausted()
  6428. {
  6429. if (lengthOfSourceStream >= 0)
  6430. return (getPosition() >= lengthOfSourceStream) || source->isExhausted();
  6431. else
  6432. return source->isExhausted();
  6433. }
  6434. END_JUCE_NAMESPACE
  6435. /********* End of inlined file: juce_SubregionStream.cpp *********/
  6436. /********* Start of inlined file: juce_PerformanceCounter.cpp *********/
  6437. BEGIN_JUCE_NAMESPACE
  6438. PerformanceCounter::PerformanceCounter (const String& name_,
  6439. int runsPerPrintout,
  6440. const File& loggingFile)
  6441. : name (name_),
  6442. numRuns (0),
  6443. runsPerPrint (runsPerPrintout),
  6444. totalTime (0),
  6445. outputFile (loggingFile)
  6446. {
  6447. if (outputFile != File::nonexistent)
  6448. {
  6449. String s ("**** Counter for \"");
  6450. s << name_ << "\" started at: "
  6451. << Time::getCurrentTime().toString (true, true)
  6452. << "\r\n";
  6453. outputFile.appendText (s, false, false);
  6454. }
  6455. }
  6456. PerformanceCounter::~PerformanceCounter()
  6457. {
  6458. printStatistics();
  6459. }
  6460. void PerformanceCounter::start()
  6461. {
  6462. started = Time::getHighResolutionTicks();
  6463. }
  6464. void PerformanceCounter::stop()
  6465. {
  6466. const int64 now = Time::getHighResolutionTicks();
  6467. totalTime += 1000.0 * Time::highResolutionTicksToSeconds (now - started);
  6468. if (++numRuns == runsPerPrint)
  6469. printStatistics();
  6470. }
  6471. void PerformanceCounter::printStatistics()
  6472. {
  6473. if (numRuns > 0)
  6474. {
  6475. String s ("Performance count for \"");
  6476. s << name << "\" - average over " << numRuns << " run(s) = ";
  6477. const int micros = (int) (totalTime * (1000.0 / numRuns));
  6478. if (micros > 10000)
  6479. s << (micros/1000) << " millisecs";
  6480. else
  6481. s << micros << " microsecs";
  6482. s << ", total = " << String (totalTime / 1000, 5) << " seconds";
  6483. Logger::outputDebugString (s);
  6484. s << "\r\n";
  6485. if (outputFile != File::nonexistent)
  6486. outputFile.appendText (s, false, false);
  6487. numRuns = 0;
  6488. totalTime = 0;
  6489. }
  6490. }
  6491. END_JUCE_NAMESPACE
  6492. /********* End of inlined file: juce_PerformanceCounter.cpp *********/
  6493. /********* Start of inlined file: juce_Uuid.cpp *********/
  6494. BEGIN_JUCE_NAMESPACE
  6495. Uuid::Uuid()
  6496. {
  6497. // do some serious mixing up of our MAC addresses and different types of time info,
  6498. // plus a couple of passes of pseudo-random numbers over the whole thing.
  6499. SystemStats::getMACAddresses (value.asInt64, 2);
  6500. int i;
  6501. for (i = 16; --i >= 0;)
  6502. {
  6503. Random r (Time::getHighResolutionTicks()
  6504. + Random::getSystemRandom().nextInt()
  6505. + value.asInt [i & 3]);
  6506. value.asBytes[i] ^= (uint8) r.nextInt();
  6507. }
  6508. value.asInt64 [0] ^= Time::getHighResolutionTicks();
  6509. value.asInt64 [1] ^= Time::currentTimeMillis();
  6510. for (i = 4; --i >= 0;)
  6511. {
  6512. Random r (Time::getHighResolutionTicks() ^ value.asInt[i]);
  6513. value.asInt[i] ^= r.nextInt();
  6514. }
  6515. }
  6516. Uuid::~Uuid() throw()
  6517. {
  6518. }
  6519. Uuid::Uuid (const Uuid& other)
  6520. : value (other.value)
  6521. {
  6522. }
  6523. Uuid& Uuid::operator= (const Uuid& other)
  6524. {
  6525. if (this != &other)
  6526. value = other.value;
  6527. return *this;
  6528. }
  6529. bool Uuid::operator== (const Uuid& other) const
  6530. {
  6531. return memcmp (value.asBytes, other.value.asBytes, 16) == 0;
  6532. }
  6533. bool Uuid::operator!= (const Uuid& other) const
  6534. {
  6535. return ! operator== (other);
  6536. }
  6537. bool Uuid::isNull() const throw()
  6538. {
  6539. return (value.asInt64 [0] == 0) && (value.asInt64 [1] == 0);
  6540. }
  6541. const String Uuid::toString() const
  6542. {
  6543. return String::toHexString (value.asBytes, 16, 0);
  6544. }
  6545. Uuid::Uuid (const String& uuidString)
  6546. {
  6547. operator= (uuidString);
  6548. }
  6549. Uuid& Uuid::operator= (const String& uuidString)
  6550. {
  6551. int destIndex = 0;
  6552. int i = 0;
  6553. for (;;)
  6554. {
  6555. int byte = 0;
  6556. for (int loop = 2; --loop >= 0;)
  6557. {
  6558. byte <<= 4;
  6559. for (;;)
  6560. {
  6561. const tchar c = uuidString [i++];
  6562. if (c >= T('0') && c <= T('9'))
  6563. {
  6564. byte |= c - T('0');
  6565. break;
  6566. }
  6567. else if (c >= T('a') && c <= T('z'))
  6568. {
  6569. byte |= c - (T('a') - 10);
  6570. break;
  6571. }
  6572. else if (c >= T('A') && c <= T('Z'))
  6573. {
  6574. byte |= c - (T('A') - 10);
  6575. break;
  6576. }
  6577. else if (c == 0)
  6578. {
  6579. while (destIndex < 16)
  6580. value.asBytes [destIndex++] = 0;
  6581. return *this;
  6582. }
  6583. }
  6584. }
  6585. value.asBytes [destIndex++] = (uint8) byte;
  6586. }
  6587. }
  6588. Uuid::Uuid (const uint8* const rawData)
  6589. {
  6590. operator= (rawData);
  6591. }
  6592. Uuid& Uuid::operator= (const uint8* const rawData)
  6593. {
  6594. if (rawData != 0)
  6595. memcpy (value.asBytes, rawData, 16);
  6596. else
  6597. zeromem (value.asBytes, 16);
  6598. return *this;
  6599. }
  6600. END_JUCE_NAMESPACE
  6601. /********* End of inlined file: juce_Uuid.cpp *********/
  6602. /********* Start of inlined file: juce_ZipFile.cpp *********/
  6603. BEGIN_JUCE_NAMESPACE
  6604. struct ZipEntryInfo
  6605. {
  6606. ZipFile::ZipEntry entry;
  6607. int streamOffset;
  6608. int compressedSize;
  6609. bool compressed;
  6610. };
  6611. class ZipInputStream : public InputStream
  6612. {
  6613. public:
  6614. ZipInputStream (ZipFile& file_,
  6615. ZipEntryInfo& zei) throw()
  6616. : file (file_),
  6617. zipEntryInfo (zei),
  6618. pos (0),
  6619. headerSize (0),
  6620. inputStream (0)
  6621. {
  6622. inputStream = file_.inputStream;
  6623. if (file_.inputSource != 0)
  6624. {
  6625. inputStream = file.inputSource->createInputStream();
  6626. }
  6627. else
  6628. {
  6629. #ifdef JUCE_DEBUG
  6630. file_.numOpenStreams++;
  6631. #endif
  6632. }
  6633. char buffer [30];
  6634. if (inputStream != 0
  6635. && inputStream->setPosition (zei.streamOffset)
  6636. && inputStream->read (buffer, 30) == 30
  6637. && littleEndianInt (buffer) == 0x04034b50)
  6638. {
  6639. headerSize = 30 + littleEndianShort (buffer + 26)
  6640. + littleEndianShort (buffer + 28);
  6641. }
  6642. }
  6643. ~ZipInputStream() throw()
  6644. {
  6645. #ifdef JUCE_DEBUG
  6646. if (inputStream != 0 && inputStream == file.inputStream)
  6647. file.numOpenStreams--;
  6648. #endif
  6649. if (inputStream != file.inputStream)
  6650. delete inputStream;
  6651. }
  6652. int64 getTotalLength() throw()
  6653. {
  6654. return zipEntryInfo.compressedSize;
  6655. }
  6656. int read (void* buffer, int howMany) throw()
  6657. {
  6658. if (headerSize <= 0)
  6659. return 0;
  6660. howMany = (int) jmin ((int64) howMany, zipEntryInfo.compressedSize - pos);
  6661. if (inputStream == 0)
  6662. return 0;
  6663. int num;
  6664. if (inputStream == file.inputStream)
  6665. {
  6666. const ScopedLock sl (file.lock);
  6667. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  6668. num = inputStream->read (buffer, howMany);
  6669. }
  6670. else
  6671. {
  6672. inputStream->setPosition (pos + zipEntryInfo.streamOffset + headerSize);
  6673. num = inputStream->read (buffer, howMany);
  6674. }
  6675. pos += num;
  6676. return num;
  6677. }
  6678. bool isExhausted() throw()
  6679. {
  6680. return pos >= zipEntryInfo.compressedSize;
  6681. }
  6682. int64 getPosition() throw()
  6683. {
  6684. return pos;
  6685. }
  6686. bool setPosition (int64 newPos) throw()
  6687. {
  6688. pos = jlimit ((int64) 0, (int64) zipEntryInfo.compressedSize, newPos);
  6689. return true;
  6690. }
  6691. private:
  6692. ZipFile& file;
  6693. ZipEntryInfo zipEntryInfo;
  6694. int64 pos;
  6695. int headerSize;
  6696. InputStream* inputStream;
  6697. ZipInputStream (const ZipInputStream&);
  6698. const ZipInputStream& operator= (const ZipInputStream&);
  6699. };
  6700. ZipFile::ZipFile (InputStream* const source_,
  6701. const bool deleteStreamWhenDestroyed_) throw()
  6702. : inputStream (source_),
  6703. inputSource (0),
  6704. deleteStreamWhenDestroyed (deleteStreamWhenDestroyed_)
  6705. #ifdef JUCE_DEBUG
  6706. , numOpenStreams (0)
  6707. #endif
  6708. {
  6709. init();
  6710. }
  6711. ZipFile::ZipFile (const File& file)
  6712. : inputStream (0),
  6713. deleteStreamWhenDestroyed (false)
  6714. #ifdef JUCE_DEBUG
  6715. , numOpenStreams (0)
  6716. #endif
  6717. {
  6718. inputSource = new FileInputSource (file);
  6719. init();
  6720. }
  6721. ZipFile::ZipFile (InputSource* const inputSource_)
  6722. : inputStream (0),
  6723. inputSource (inputSource_),
  6724. deleteStreamWhenDestroyed (false)
  6725. #ifdef JUCE_DEBUG
  6726. , numOpenStreams (0)
  6727. #endif
  6728. {
  6729. init();
  6730. }
  6731. ZipFile::~ZipFile() throw()
  6732. {
  6733. for (int i = entries.size(); --i >= 0;)
  6734. {
  6735. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [i];
  6736. delete zei;
  6737. }
  6738. if (deleteStreamWhenDestroyed)
  6739. delete inputStream;
  6740. delete inputSource;
  6741. #ifdef JUCE_DEBUG
  6742. // If you hit this assertion, it means you've created a stream to read
  6743. // one of the items in the zipfile, but you've forgotten to delete that
  6744. // stream object before deleting the file.. Streams can't be kept open
  6745. // after the file is deleted because they need to share the input
  6746. // stream that the file uses to read itself.
  6747. jassert (numOpenStreams == 0);
  6748. #endif
  6749. }
  6750. int ZipFile::getNumEntries() const throw()
  6751. {
  6752. return entries.size();
  6753. }
  6754. const ZipFile::ZipEntry* ZipFile::getEntry (const int index) const throw()
  6755. {
  6756. ZipEntryInfo* const zei = (ZipEntryInfo*) entries [index];
  6757. return (zei != 0) ? &(zei->entry)
  6758. : 0;
  6759. }
  6760. int ZipFile::getIndexOfFileName (const String& fileName) const throw()
  6761. {
  6762. for (int i = 0; i < entries.size(); ++i)
  6763. if (((ZipEntryInfo*) entries.getUnchecked (i))->entry.filename == fileName)
  6764. return i;
  6765. return -1;
  6766. }
  6767. const ZipFile::ZipEntry* ZipFile::getEntry (const String& fileName) const throw()
  6768. {
  6769. return getEntry (getIndexOfFileName (fileName));
  6770. }
  6771. InputStream* ZipFile::createStreamForEntry (const int index)
  6772. {
  6773. ZipEntryInfo* const zei = (ZipEntryInfo*) entries[index];
  6774. InputStream* stream = 0;
  6775. if (zei != 0)
  6776. {
  6777. stream = new ZipInputStream (*this, *zei);
  6778. if (zei->compressed)
  6779. {
  6780. stream = new GZIPDecompressorInputStream (stream, true, true,
  6781. zei->entry.uncompressedSize);
  6782. // (much faster to unzip in big blocks using a buffer..)
  6783. stream = new BufferedInputStream (stream, 32768, true);
  6784. }
  6785. }
  6786. return stream;
  6787. }
  6788. class ZipFilenameComparator
  6789. {
  6790. public:
  6791. static int compareElements (const void* const first, const void* const second) throw()
  6792. {
  6793. return ((const ZipEntryInfo*) first)->entry.filename
  6794. .compare (((const ZipEntryInfo*) second)->entry.filename);
  6795. }
  6796. };
  6797. void ZipFile::sortEntriesByFilename()
  6798. {
  6799. ZipFilenameComparator sorter;
  6800. entries.sort (sorter);
  6801. }
  6802. void ZipFile::init()
  6803. {
  6804. InputStream* in = inputStream;
  6805. bool deleteInput = false;
  6806. if (inputSource != 0)
  6807. {
  6808. deleteInput = true;
  6809. in = inputSource->createInputStream();
  6810. }
  6811. if (in != 0)
  6812. {
  6813. numEntries = 0;
  6814. int pos = findEndOfZipEntryTable (in);
  6815. if (pos >= 0 && pos < in->getTotalLength())
  6816. {
  6817. const int size = (int) (in->getTotalLength() - pos);
  6818. in->setPosition (pos);
  6819. MemoryBlock headerData;
  6820. if (in->readIntoMemoryBlock (headerData, size) == size)
  6821. {
  6822. pos = 0;
  6823. for (int i = 0; i < numEntries; ++i)
  6824. {
  6825. if (pos + 46 > size)
  6826. break;
  6827. const char* const buffer = ((const char*) headerData.getData()) + pos;
  6828. const int fileNameLen = littleEndianShort (buffer + 28);
  6829. if (pos + 46 + fileNameLen > size)
  6830. break;
  6831. ZipEntryInfo* const zei = new ZipEntryInfo();
  6832. zei->entry.filename = String (buffer + 46, fileNameLen);
  6833. const int time = littleEndianShort (buffer + 12);
  6834. const int date = littleEndianShort (buffer + 14);
  6835. const int year = 1980 + (date >> 9);
  6836. const int month = ((date >> 5) & 15) - 1;
  6837. const int day = date & 31;
  6838. const int hours = time >> 11;
  6839. const int minutes = (time >> 5) & 63;
  6840. const int seconds = (time & 31) << 1;
  6841. zei->entry.fileTime = Time (year, month, day, hours, minutes, seconds);
  6842. zei->compressed = littleEndianShort (buffer + 10) != 0;
  6843. zei->compressedSize = littleEndianInt (buffer + 20);
  6844. zei->entry.uncompressedSize = littleEndianInt (buffer + 24);
  6845. zei->streamOffset = littleEndianInt (buffer + 42);
  6846. entries.add (zei);
  6847. pos += 46 + fileNameLen
  6848. + littleEndianShort (buffer + 30)
  6849. + littleEndianShort (buffer + 32);
  6850. }
  6851. }
  6852. }
  6853. if (deleteInput)
  6854. delete in;
  6855. }
  6856. }
  6857. int ZipFile::findEndOfZipEntryTable (InputStream* input)
  6858. {
  6859. BufferedInputStream in (input, 8192, false);
  6860. in.setPosition (in.getTotalLength());
  6861. int64 pos = in.getPosition();
  6862. const int64 lowestPos = jmax ((int64) 0, pos - 1024);
  6863. char buffer [32];
  6864. zeromem (buffer, sizeof (buffer));
  6865. while (pos > lowestPos)
  6866. {
  6867. in.setPosition (pos - 22);
  6868. pos = in.getPosition();
  6869. memcpy (buffer + 22, buffer, 4);
  6870. if (in.read (buffer, 22) != 22)
  6871. return 0;
  6872. for (int i = 0; i < 22; ++i)
  6873. {
  6874. if (littleEndianInt (buffer + i) == 0x06054b50)
  6875. {
  6876. in.setPosition (pos + i);
  6877. in.read (buffer, 22);
  6878. numEntries = littleEndianShort (buffer + 10);
  6879. return littleEndianInt (buffer + 16);
  6880. }
  6881. }
  6882. }
  6883. return 0;
  6884. }
  6885. void ZipFile::uncompressTo (const File& targetDirectory,
  6886. const bool shouldOverwriteFiles)
  6887. {
  6888. for (int i = 0; i < entries.size(); ++i)
  6889. {
  6890. const ZipEntryInfo& zei = *(ZipEntryInfo*) entries[i];
  6891. const File targetFile (targetDirectory.getChildFile (zei.entry.filename));
  6892. if (zei.entry.filename.endsWithChar (T('/')))
  6893. {
  6894. targetFile.createDirectory(); // (entry is a directory, not a file)
  6895. }
  6896. else
  6897. {
  6898. InputStream* const in = createStreamForEntry (i);
  6899. if (in != 0)
  6900. {
  6901. if (shouldOverwriteFiles)
  6902. targetFile.deleteFile();
  6903. if ((! targetFile.exists())
  6904. && targetFile.getParentDirectory().createDirectory())
  6905. {
  6906. FileOutputStream* const out = targetFile.createOutputStream();
  6907. if (out != 0)
  6908. {
  6909. out->writeFromInputStream (*in, -1);
  6910. delete out;
  6911. targetFile.setCreationTime (zei.entry.fileTime);
  6912. targetFile.setLastModificationTime (zei.entry.fileTime);
  6913. targetFile.setLastAccessTime (zei.entry.fileTime);
  6914. }
  6915. }
  6916. delete in;
  6917. }
  6918. }
  6919. }
  6920. }
  6921. END_JUCE_NAMESPACE
  6922. /********* End of inlined file: juce_ZipFile.cpp *********/
  6923. /********* Start of inlined file: juce_CharacterFunctions.cpp *********/
  6924. #ifdef _MSC_VER
  6925. #pragma warning (disable: 4514 4996)
  6926. #pragma warning (push)
  6927. #endif
  6928. #include <cwctype>
  6929. #include <cctype>
  6930. #include <ctime>
  6931. #ifdef _MSC_VER
  6932. #pragma warning (pop)
  6933. #endif
  6934. BEGIN_JUCE_NAMESPACE
  6935. int CharacterFunctions::length (const char* const s) throw()
  6936. {
  6937. return (int) strlen (s);
  6938. }
  6939. int CharacterFunctions::length (const juce_wchar* const s) throw()
  6940. {
  6941. #if MACOS_10_2_OR_EARLIER
  6942. int n = 0;
  6943. while (s[n] != 0)
  6944. ++n;
  6945. return n;
  6946. #else
  6947. return (int) wcslen (s);
  6948. #endif
  6949. }
  6950. void CharacterFunctions::copy (char* dest, const char* src, const int maxChars) throw()
  6951. {
  6952. strncpy (dest, src, maxChars);
  6953. }
  6954. void CharacterFunctions::copy (juce_wchar* dest, const juce_wchar* src, int maxChars) throw()
  6955. {
  6956. #if MACOS_10_2_OR_EARLIER
  6957. while (--maxChars >= 0 && *src != 0)
  6958. *dest++ = *src++;
  6959. *dest = 0;
  6960. #else
  6961. wcsncpy (dest, src, maxChars);
  6962. #endif
  6963. }
  6964. void CharacterFunctions::copy (juce_wchar* dest, const char* src, const int maxChars) throw()
  6965. {
  6966. mbstowcs (dest, src, maxChars);
  6967. }
  6968. void CharacterFunctions::copy (char* dest, const juce_wchar* src, const int maxChars) throw()
  6969. {
  6970. wcstombs (dest, src, maxChars);
  6971. }
  6972. int CharacterFunctions::bytesRequiredForCopy (const juce_wchar* src) throw()
  6973. {
  6974. return (int) wcstombs (0, src, 0);
  6975. }
  6976. void CharacterFunctions::append (char* dest, const char* src) throw()
  6977. {
  6978. strcat (dest, src);
  6979. }
  6980. void CharacterFunctions::append (juce_wchar* dest, const juce_wchar* src) throw()
  6981. {
  6982. #if MACOS_10_2_OR_EARLIER
  6983. while (*dest != 0)
  6984. ++dest;
  6985. while (*src != 0)
  6986. *dest++ = *src++;
  6987. *dest = 0;
  6988. #else
  6989. wcscat (dest, src);
  6990. #endif
  6991. }
  6992. int CharacterFunctions::compare (const char* const s1, const char* const s2) throw()
  6993. {
  6994. return strcmp (s1, s2);
  6995. }
  6996. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2) throw()
  6997. {
  6998. jassert (s1 != 0 && s2 != 0);
  6999. #if MACOS_10_2_OR_EARLIER
  7000. for (;;)
  7001. {
  7002. if (*s1 != *s2)
  7003. {
  7004. const int diff = *s1 - *s2;
  7005. if (diff != 0)
  7006. return diff < 0 ? -1 : 1;
  7007. }
  7008. else if (*s1 == 0)
  7009. break;
  7010. ++s1;
  7011. ++s2;
  7012. }
  7013. return 0;
  7014. #else
  7015. return wcscmp (s1, s2);
  7016. #endif
  7017. }
  7018. int CharacterFunctions::compare (const char* const s1, const char* const s2, const int maxChars) throw()
  7019. {
  7020. jassert (s1 != 0 && s2 != 0);
  7021. return strncmp (s1, s2, maxChars);
  7022. }
  7023. int CharacterFunctions::compare (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7024. {
  7025. jassert (s1 != 0 && s2 != 0);
  7026. #if MACOS_10_2_OR_EARLIER
  7027. while (--maxChars >= 0)
  7028. {
  7029. if (*s1 != *s2)
  7030. return (*s1 < *s2) ? -1 : 1;
  7031. else if (*s1 == 0)
  7032. break;
  7033. ++s1;
  7034. ++s2;
  7035. }
  7036. return 0;
  7037. #else
  7038. return wcsncmp (s1, s2, maxChars);
  7039. #endif
  7040. }
  7041. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2) throw()
  7042. {
  7043. jassert (s1 != 0 && s2 != 0);
  7044. #if JUCE_WIN32
  7045. return stricmp (s1, s2);
  7046. #else
  7047. return strcasecmp (s1, s2);
  7048. #endif
  7049. }
  7050. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2) throw()
  7051. {
  7052. jassert (s1 != 0 && s2 != 0);
  7053. #if JUCE_WIN32
  7054. return _wcsicmp (s1, s2);
  7055. #else
  7056. for (;;)
  7057. {
  7058. if (*s1 != *s2)
  7059. {
  7060. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7061. if (diff != 0)
  7062. return diff < 0 ? -1 : 1;
  7063. }
  7064. else if (*s1 == 0)
  7065. break;
  7066. ++s1;
  7067. ++s2;
  7068. }
  7069. return 0;
  7070. #endif
  7071. }
  7072. int CharacterFunctions::compareIgnoreCase (const char* const s1, const char* const s2, const int maxChars) throw()
  7073. {
  7074. jassert (s1 != 0 && s2 != 0);
  7075. #if JUCE_WIN32
  7076. return strnicmp (s1, s2, maxChars);
  7077. #else
  7078. return strncasecmp (s1, s2, maxChars);
  7079. #endif
  7080. }
  7081. int CharacterFunctions::compareIgnoreCase (const juce_wchar* s1, const juce_wchar* s2, int maxChars) throw()
  7082. {
  7083. jassert (s1 != 0 && s2 != 0);
  7084. #if JUCE_WIN32
  7085. return _wcsnicmp (s1, s2, maxChars);
  7086. #else
  7087. while (--maxChars >= 0)
  7088. {
  7089. if (*s1 != *s2)
  7090. {
  7091. const int diff = toUpperCase (*s1) - toUpperCase (*s2);
  7092. if (diff != 0)
  7093. return diff < 0 ? -1 : 1;
  7094. }
  7095. else if (*s1 == 0)
  7096. break;
  7097. ++s1;
  7098. ++s2;
  7099. }
  7100. return 0;
  7101. #endif
  7102. }
  7103. const char* CharacterFunctions::find (const char* const haystack, const char* const needle) throw()
  7104. {
  7105. return strstr (haystack, needle);
  7106. }
  7107. const juce_wchar* CharacterFunctions::find (const juce_wchar* haystack, const juce_wchar* const needle) throw()
  7108. {
  7109. #if MACOS_10_2_OR_EARLIER
  7110. while (*haystack != 0)
  7111. {
  7112. const juce_wchar* s1 = haystack;
  7113. const juce_wchar* s2 = needle;
  7114. for (;;)
  7115. {
  7116. if (*s2 == 0)
  7117. return haystack;
  7118. if (*s1 != *s2 || *s2 == 0)
  7119. break;
  7120. ++s1;
  7121. ++s2;
  7122. }
  7123. ++haystack;
  7124. }
  7125. return 0;
  7126. #else
  7127. return wcsstr (haystack, needle);
  7128. #endif
  7129. }
  7130. int CharacterFunctions::indexOfChar (const char* const haystack, const char needle, const bool ignoreCase) throw()
  7131. {
  7132. if (haystack != 0)
  7133. {
  7134. int i = 0;
  7135. if (ignoreCase)
  7136. {
  7137. const char n1 = toLowerCase (needle);
  7138. const char n2 = toUpperCase (needle);
  7139. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7140. {
  7141. while (haystack[i] != 0)
  7142. {
  7143. if (haystack[i] == n1 || haystack[i] == n2)
  7144. return i;
  7145. ++i;
  7146. }
  7147. return -1;
  7148. }
  7149. jassert (n1 == needle);
  7150. }
  7151. while (haystack[i] != 0)
  7152. {
  7153. if (haystack[i] == needle)
  7154. return i;
  7155. ++i;
  7156. }
  7157. }
  7158. return -1;
  7159. }
  7160. int CharacterFunctions::indexOfChar (const juce_wchar* const haystack, const juce_wchar needle, const bool ignoreCase) throw()
  7161. {
  7162. if (haystack != 0)
  7163. {
  7164. int i = 0;
  7165. if (ignoreCase)
  7166. {
  7167. const juce_wchar n1 = toLowerCase (needle);
  7168. const juce_wchar n2 = toUpperCase (needle);
  7169. if (n1 != n2) // if the char is the same in upper/lower case, fall through to the normal search
  7170. {
  7171. while (haystack[i] != 0)
  7172. {
  7173. if (haystack[i] == n1 || haystack[i] == n2)
  7174. return i;
  7175. ++i;
  7176. }
  7177. return -1;
  7178. }
  7179. jassert (n1 == needle);
  7180. }
  7181. while (haystack[i] != 0)
  7182. {
  7183. if (haystack[i] == needle)
  7184. return i;
  7185. ++i;
  7186. }
  7187. }
  7188. return -1;
  7189. }
  7190. int CharacterFunctions::indexOfCharFast (const char* const haystack, const char needle) throw()
  7191. {
  7192. jassert (haystack != 0);
  7193. int i = 0;
  7194. while (haystack[i] != 0)
  7195. {
  7196. if (haystack[i] == needle)
  7197. return i;
  7198. ++i;
  7199. }
  7200. return -1;
  7201. }
  7202. int CharacterFunctions::indexOfCharFast (const juce_wchar* const haystack, const juce_wchar needle) throw()
  7203. {
  7204. jassert (haystack != 0);
  7205. int i = 0;
  7206. while (haystack[i] != 0)
  7207. {
  7208. if (haystack[i] == needle)
  7209. return i;
  7210. ++i;
  7211. }
  7212. return -1;
  7213. }
  7214. int CharacterFunctions::getIntialSectionContainingOnly (const char* const text, const char* const allowedChars) throw()
  7215. {
  7216. return allowedChars == 0 ? 0 : (int) strspn (text, allowedChars);
  7217. }
  7218. int CharacterFunctions::getIntialSectionContainingOnly (const juce_wchar* const text, const juce_wchar* const allowedChars) throw()
  7219. {
  7220. if (allowedChars == 0)
  7221. return 0;
  7222. int i = 0;
  7223. for (;;)
  7224. {
  7225. if (indexOfCharFast (allowedChars, text[i]) < 0)
  7226. break;
  7227. ++i;
  7228. }
  7229. return i;
  7230. }
  7231. int CharacterFunctions::ftime (char* const dest, const int maxChars, const char* const format, const struct tm* const tm) throw()
  7232. {
  7233. return (int) strftime (dest, maxChars, format, tm);
  7234. }
  7235. int CharacterFunctions::ftime (juce_wchar* const dest, const int maxChars, const juce_wchar* const format, const struct tm* const tm) throw()
  7236. {
  7237. #if MACOS_10_2_OR_EARLIER
  7238. const String formatTemp (format);
  7239. size_t num = strftime ((char*) dest, maxChars, (const char*) formatTemp, tm);
  7240. String temp ((char*) dest);
  7241. temp.copyToBuffer (dest, num);
  7242. dest [num] = 0;
  7243. return (int) num;
  7244. #else
  7245. return (int) wcsftime (dest, maxChars, format, tm);
  7246. #endif
  7247. }
  7248. int CharacterFunctions::getIntValue (const char* const s) throw()
  7249. {
  7250. return atoi (s);
  7251. }
  7252. int CharacterFunctions::getIntValue (const juce_wchar* s) throw()
  7253. {
  7254. #if JUCE_WIN32
  7255. return _wtoi (s);
  7256. #else
  7257. int v = 0;
  7258. while (isWhitespace (*s))
  7259. ++s;
  7260. const bool isNeg = *s == T('-');
  7261. if (isNeg)
  7262. ++s;
  7263. for (;;)
  7264. {
  7265. const wchar_t c = *s++;
  7266. if (c >= T('0') && c <= T('9'))
  7267. v = v * 10 + (int) (c - T('0'));
  7268. else
  7269. break;
  7270. }
  7271. return isNeg ? -v : v;
  7272. #endif
  7273. }
  7274. int64 CharacterFunctions::getInt64Value (const char* s) throw()
  7275. {
  7276. #if JUCE_LINUX
  7277. return atoll (s);
  7278. #elif defined (JUCE_WIN32)
  7279. return _atoi64 (s);
  7280. #else
  7281. int64 v = 0;
  7282. while (isWhitespace (*s))
  7283. ++s;
  7284. const bool isNeg = *s == T('-');
  7285. if (isNeg)
  7286. ++s;
  7287. for (;;)
  7288. {
  7289. const char c = *s++;
  7290. if (c >= '0' && c <= '9')
  7291. v = v * 10 + (int64) (c - '0');
  7292. else
  7293. break;
  7294. }
  7295. return isNeg ? -v : v;
  7296. #endif
  7297. }
  7298. int64 CharacterFunctions::getInt64Value (const juce_wchar* s) throw()
  7299. {
  7300. #if JUCE_WIN32
  7301. return _wtoi64 (s);
  7302. #else
  7303. int64 v = 0;
  7304. while (isWhitespace (*s))
  7305. ++s;
  7306. const bool isNeg = *s == T('-');
  7307. if (isNeg)
  7308. ++s;
  7309. for (;;)
  7310. {
  7311. const juce_wchar c = *s++;
  7312. if (c >= T('0') && c <= T('9'))
  7313. v = v * 10 + (int64) (c - T('0'));
  7314. else
  7315. break;
  7316. }
  7317. return isNeg ? -v : v;
  7318. #endif
  7319. }
  7320. double CharacterFunctions::getDoubleValue (const char* const s) throw()
  7321. {
  7322. return atof (s);
  7323. }
  7324. double CharacterFunctions::getDoubleValue (const juce_wchar* const s) throw()
  7325. {
  7326. #if MACOS_10_2_OR_EARLIER
  7327. String temp (s);
  7328. return atof ((const char*) temp);
  7329. #else
  7330. wchar_t* endChar;
  7331. return wcstod (s, &endChar);
  7332. #endif
  7333. }
  7334. char CharacterFunctions::toUpperCase (const char character) throw()
  7335. {
  7336. return (char) toupper (character);
  7337. }
  7338. juce_wchar CharacterFunctions::toUpperCase (const juce_wchar character) throw()
  7339. {
  7340. #if MACOS_10_2_OR_EARLIER
  7341. return toupper ((char) character);
  7342. #else
  7343. return towupper (character);
  7344. #endif
  7345. }
  7346. void CharacterFunctions::toUpperCase (char* s) throw()
  7347. {
  7348. #if JUCE_WIN32
  7349. strupr (s);
  7350. #else
  7351. while (*s != 0)
  7352. {
  7353. *s = toUpperCase (*s);
  7354. ++s;
  7355. }
  7356. #endif
  7357. }
  7358. void CharacterFunctions::toUpperCase (juce_wchar* s) throw()
  7359. {
  7360. #if JUCE_WIN32
  7361. _wcsupr (s);
  7362. #else
  7363. while (*s != 0)
  7364. {
  7365. *s = toUpperCase (*s);
  7366. ++s;
  7367. }
  7368. #endif
  7369. }
  7370. bool CharacterFunctions::isUpperCase (const char character) throw()
  7371. {
  7372. return isupper (character) != 0;
  7373. }
  7374. bool CharacterFunctions::isUpperCase (const juce_wchar character) throw()
  7375. {
  7376. #if JUCE_WIN32
  7377. return iswupper (character) != 0;
  7378. #else
  7379. return toLowerCase (character) != character;
  7380. #endif
  7381. }
  7382. char CharacterFunctions::toLowerCase (const char character) throw()
  7383. {
  7384. return (char) tolower (character);
  7385. }
  7386. juce_wchar CharacterFunctions::toLowerCase (const juce_wchar character) throw()
  7387. {
  7388. #if MACOS_10_2_OR_EARLIER
  7389. return tolower ((char) character);
  7390. #else
  7391. return towlower (character);
  7392. #endif
  7393. }
  7394. void CharacterFunctions::toLowerCase (char* s) throw()
  7395. {
  7396. #if JUCE_WIN32
  7397. strlwr (s);
  7398. #else
  7399. while (*s != 0)
  7400. {
  7401. *s = toLowerCase (*s);
  7402. ++s;
  7403. }
  7404. #endif
  7405. }
  7406. void CharacterFunctions::toLowerCase (juce_wchar* s) throw()
  7407. {
  7408. #if JUCE_WIN32
  7409. _wcslwr (s);
  7410. #else
  7411. while (*s != 0)
  7412. {
  7413. *s = toLowerCase (*s);
  7414. ++s;
  7415. }
  7416. #endif
  7417. }
  7418. bool CharacterFunctions::isLowerCase (const char character) throw()
  7419. {
  7420. return islower (character) != 0;
  7421. }
  7422. bool CharacterFunctions::isLowerCase (const juce_wchar character) throw()
  7423. {
  7424. #if JUCE_WIN32
  7425. return iswlower (character) != 0;
  7426. #else
  7427. return toUpperCase (character) != character;
  7428. #endif
  7429. }
  7430. bool CharacterFunctions::isWhitespace (const char character) throw()
  7431. {
  7432. return character == T(' ') || (character <= 13 && character >= 9);
  7433. }
  7434. bool CharacterFunctions::isWhitespace (const juce_wchar character) throw()
  7435. {
  7436. #if MACOS_10_2_OR_EARLIER
  7437. return isWhitespace ((char) character);
  7438. #else
  7439. return iswspace (character) != 0;
  7440. #endif
  7441. }
  7442. bool CharacterFunctions::isDigit (const char character) throw()
  7443. {
  7444. return (character >= '0' && character <= '9');
  7445. }
  7446. bool CharacterFunctions::isDigit (const juce_wchar character) throw()
  7447. {
  7448. #if MACOS_10_2_OR_EARLIER
  7449. return isdigit ((char) character) != 0;
  7450. #else
  7451. return iswdigit (character) != 0;
  7452. #endif
  7453. }
  7454. bool CharacterFunctions::isLetter (const char character) throw()
  7455. {
  7456. return (character >= 'a' && character <= 'z')
  7457. || (character >= 'A' && character <= 'Z');
  7458. }
  7459. bool CharacterFunctions::isLetter (const juce_wchar character) throw()
  7460. {
  7461. #if MACOS_10_2_OR_EARLIER
  7462. return isLetter ((char) character);
  7463. #else
  7464. return iswalpha (character) != 0;
  7465. #endif
  7466. }
  7467. bool CharacterFunctions::isLetterOrDigit (const char character) throw()
  7468. {
  7469. return (character >= 'a' && character <= 'z')
  7470. || (character >= 'A' && character <= 'Z')
  7471. || (character >= '0' && character <= '9');
  7472. }
  7473. bool CharacterFunctions::isLetterOrDigit (const juce_wchar character) throw()
  7474. {
  7475. #if MACOS_10_2_OR_EARLIER
  7476. return isLetterOrDigit ((char) character);
  7477. #else
  7478. return iswalnum (character) != 0;
  7479. #endif
  7480. }
  7481. int CharacterFunctions::getHexDigitValue (const tchar digit) throw()
  7482. {
  7483. if (digit >= T('0') && digit <= T('9'))
  7484. return digit - T('0');
  7485. else if (digit >= T('a') && digit <= T('f'))
  7486. return digit - (T('a') - 10);
  7487. else if (digit >= T('A') && digit <= T('F'))
  7488. return digit - (T('A') - 10);
  7489. return -1;
  7490. }
  7491. int CharacterFunctions::printf (char* const dest, const int maxLength, const char* const format, ...) throw()
  7492. {
  7493. va_list list;
  7494. va_start (list, format);
  7495. return vprintf (dest, maxLength, format, list);
  7496. }
  7497. int CharacterFunctions::printf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, ...) throw()
  7498. {
  7499. va_list list;
  7500. va_start (list, format);
  7501. return vprintf (dest, maxLength, format, list);
  7502. }
  7503. int CharacterFunctions::vprintf (char* const dest, const int maxLength, const char* const format, va_list& args) throw()
  7504. {
  7505. #if JUCE_WIN32
  7506. return (int) _vsnprintf (dest, maxLength, format, args);
  7507. #else
  7508. return (int) vsnprintf (dest, maxLength, format, args);
  7509. #endif
  7510. }
  7511. int CharacterFunctions::vprintf (juce_wchar* const dest, const int maxLength, const juce_wchar* const format, va_list& args) throw()
  7512. {
  7513. #if MACOS_10_3_OR_EARLIER
  7514. const String formatTemp (format);
  7515. size_t num = vprintf ((char*) dest, maxLength, formatTemp, args);
  7516. String temp ((char*) dest);
  7517. temp.copyToBuffer (dest, num);
  7518. dest [num] = 0;
  7519. return (int) num;
  7520. #elif defined (JUCE_WIN32)
  7521. return (int) _vsnwprintf (dest, maxLength, format, args);
  7522. #else
  7523. return (int) vswprintf (dest, maxLength, format, args);
  7524. #endif
  7525. }
  7526. END_JUCE_NAMESPACE
  7527. /********* End of inlined file: juce_CharacterFunctions.cpp *********/
  7528. /********* Start of inlined file: juce_LocalisedStrings.cpp *********/
  7529. BEGIN_JUCE_NAMESPACE
  7530. LocalisedStrings::LocalisedStrings (const String& fileContents) throw()
  7531. {
  7532. loadFromText (fileContents);
  7533. }
  7534. LocalisedStrings::LocalisedStrings (const File& fileToLoad) throw()
  7535. {
  7536. loadFromText (fileToLoad.loadFileAsString());
  7537. }
  7538. LocalisedStrings::~LocalisedStrings() throw()
  7539. {
  7540. }
  7541. const String LocalisedStrings::translate (const String& text) const throw()
  7542. {
  7543. return translations.getValue (text, text);
  7544. }
  7545. static int findCloseQuote (const String& text, int startPos) throw()
  7546. {
  7547. tchar lastChar = 0;
  7548. for (;;)
  7549. {
  7550. const tchar c = text [startPos];
  7551. if (c == 0 || (c == T('"') && lastChar != T('\\')))
  7552. break;
  7553. lastChar = c;
  7554. ++startPos;
  7555. }
  7556. return startPos;
  7557. }
  7558. static const String unescapeString (const String& s) throw()
  7559. {
  7560. return s.replace (T("\\\""), T("\""))
  7561. .replace (T("\\\'"), T("\'"))
  7562. .replace (T("\\t"), T("\t"))
  7563. .replace (T("\\r"), T("\r"))
  7564. .replace (T("\\n"), T("\n"));
  7565. }
  7566. void LocalisedStrings::loadFromText (const String& fileContents) throw()
  7567. {
  7568. StringArray lines;
  7569. lines.addLines (fileContents);
  7570. for (int i = 0; i < lines.size(); ++i)
  7571. {
  7572. String line (lines[i].trim());
  7573. if (line.startsWithChar (T('"')))
  7574. {
  7575. int closeQuote = findCloseQuote (line, 1);
  7576. const String originalText (unescapeString (line.substring (1, closeQuote)));
  7577. if (originalText.isNotEmpty())
  7578. {
  7579. const int openingQuote = findCloseQuote (line, closeQuote + 1);
  7580. closeQuote = findCloseQuote (line, openingQuote + 1);
  7581. const String newText (unescapeString (line.substring (openingQuote + 1, closeQuote)));
  7582. if (newText.isNotEmpty())
  7583. translations.set (originalText, newText);
  7584. }
  7585. }
  7586. else if (line.startsWithIgnoreCase (T("language:")))
  7587. {
  7588. languageName = line.substring (9).trim();
  7589. }
  7590. else if (line.startsWithIgnoreCase (T("countries:")))
  7591. {
  7592. countryCodes.addTokens (line.substring (10).trim(), true);
  7593. countryCodes.trim();
  7594. countryCodes.removeEmptyStrings();
  7595. }
  7596. }
  7597. }
  7598. static CriticalSection currentMappingsLock;
  7599. static LocalisedStrings* currentMappings = 0;
  7600. void LocalisedStrings::setCurrentMappings (LocalisedStrings* newTranslations) throw()
  7601. {
  7602. const ScopedLock sl (currentMappingsLock);
  7603. delete currentMappings;
  7604. currentMappings = newTranslations;
  7605. }
  7606. LocalisedStrings* LocalisedStrings::getCurrentMappings() throw()
  7607. {
  7608. return currentMappings;
  7609. }
  7610. const String LocalisedStrings::translateWithCurrentMappings (const String& text) throw()
  7611. {
  7612. const ScopedLock sl (currentMappingsLock);
  7613. if (currentMappings != 0)
  7614. return currentMappings->translate (text);
  7615. return text;
  7616. }
  7617. const String LocalisedStrings::translateWithCurrentMappings (const char* text) throw()
  7618. {
  7619. return translateWithCurrentMappings (String (text));
  7620. }
  7621. END_JUCE_NAMESPACE
  7622. /********* End of inlined file: juce_LocalisedStrings.cpp *********/
  7623. /********* Start of inlined file: juce_String.cpp *********/
  7624. #ifdef _MSC_VER
  7625. #pragma warning (disable: 4514)
  7626. #pragma warning (push)
  7627. #endif
  7628. #include <locale>
  7629. #if JUCE_MSVC
  7630. #include <float.h>
  7631. #endif
  7632. BEGIN_JUCE_NAMESPACE
  7633. #ifdef _MSC_VER
  7634. #pragma warning (pop)
  7635. #endif
  7636. static const char* const emptyCharString = "\0\0\0\0JUCE";
  7637. static const int safeEmptyStringRefCount = 0x3fffffff;
  7638. String::InternalRefCountedStringHolder String::emptyString = { safeEmptyStringRefCount, 0, { 0 } };
  7639. static tchar decimalPoint = T('.');
  7640. void juce_initialiseStrings()
  7641. {
  7642. decimalPoint = String::fromUTF8 ((const uint8*) localeconv()->decimal_point) [0];
  7643. }
  7644. void String::deleteInternal() throw()
  7645. {
  7646. if (atomicDecrementAndReturn (text->refCount) == 0)
  7647. juce_free (text);
  7648. }
  7649. void String::createInternal (const int numChars) throw()
  7650. {
  7651. jassert (numChars > 0);
  7652. text = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7653. + numChars * sizeof (tchar));
  7654. text->refCount = 1;
  7655. text->allocatedNumChars = numChars;
  7656. text->text[0] = 0;
  7657. }
  7658. void String::createInternal (const tchar* const t, const tchar* const textEnd) throw()
  7659. {
  7660. jassert (*(textEnd - 1) == 0); // must have a null terminator
  7661. const int numChars = (int) (textEnd - t);
  7662. createInternal (numChars - 1);
  7663. memcpy (text->text, t, numChars * sizeof (tchar));
  7664. }
  7665. void String::appendInternal (const tchar* const newText,
  7666. const int numExtraChars) throw()
  7667. {
  7668. if (numExtraChars > 0)
  7669. {
  7670. const int oldLen = CharacterFunctions::length (text->text);
  7671. const int newTotalLen = oldLen + numExtraChars;
  7672. if (text->refCount > 1)
  7673. {
  7674. // it's in use by other strings as well, so we need to make a private copy before messing with it..
  7675. InternalRefCountedStringHolder* const newTextHolder
  7676. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7677. + newTotalLen * sizeof (tchar));
  7678. newTextHolder->refCount = 1;
  7679. newTextHolder->allocatedNumChars = newTotalLen;
  7680. memcpy (newTextHolder->text, text->text, oldLen * sizeof (tchar));
  7681. memcpy (newTextHolder->text + oldLen, newText, numExtraChars * sizeof (tchar));
  7682. InternalRefCountedStringHolder* const old = text;
  7683. text = newTextHolder;
  7684. if (atomicDecrementAndReturn (old->refCount) == 0)
  7685. juce_free (old);
  7686. }
  7687. else
  7688. {
  7689. // no other strings using it, so just expand it if needed..
  7690. if (newTotalLen > text->allocatedNumChars)
  7691. {
  7692. text = (InternalRefCountedStringHolder*)
  7693. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7694. + newTotalLen * sizeof (tchar));
  7695. text->allocatedNumChars = newTotalLen;
  7696. }
  7697. memcpy (text->text + oldLen, newText, numExtraChars * sizeof (tchar));
  7698. }
  7699. text->text [newTotalLen] = 0;
  7700. }
  7701. }
  7702. void String::dupeInternalIfMultiplyReferenced() throw()
  7703. {
  7704. if (text->refCount > 1)
  7705. {
  7706. InternalRefCountedStringHolder* const old = text;
  7707. const int len = old->allocatedNumChars;
  7708. InternalRefCountedStringHolder* const newTextHolder
  7709. = (InternalRefCountedStringHolder*) juce_malloc (sizeof (InternalRefCountedStringHolder)
  7710. + len * sizeof (tchar));
  7711. newTextHolder->refCount = 1;
  7712. newTextHolder->allocatedNumChars = len;
  7713. memcpy (newTextHolder->text, old->text, (len + 1) * sizeof (tchar));
  7714. text = newTextHolder;
  7715. if (atomicDecrementAndReturn (old->refCount) == 0)
  7716. juce_free (old);
  7717. }
  7718. }
  7719. const String String::empty;
  7720. String::String() throw()
  7721. : text (&emptyString)
  7722. {
  7723. }
  7724. String::String (const String& other) throw()
  7725. : text (other.text)
  7726. {
  7727. atomicIncrement (text->refCount);
  7728. }
  7729. String::String (const int numChars,
  7730. const int /*dummyVariable*/) throw()
  7731. {
  7732. createInternal (numChars);
  7733. }
  7734. String::String (const char* const t) throw()
  7735. {
  7736. if (t != 0 && *t != 0)
  7737. {
  7738. const int len = CharacterFunctions::length (t);
  7739. createInternal (len);
  7740. #if JUCE_STRINGS_ARE_UNICODE
  7741. CharacterFunctions::copy (text->text, t, len + 1);
  7742. #else
  7743. memcpy (text->text, t, len + 1);
  7744. #endif
  7745. }
  7746. else
  7747. {
  7748. text = &emptyString;
  7749. emptyString.refCount = safeEmptyStringRefCount;
  7750. }
  7751. }
  7752. String::String (const juce_wchar* const t) throw()
  7753. {
  7754. if (t != 0 && *t != 0)
  7755. {
  7756. #if JUCE_STRINGS_ARE_UNICODE
  7757. const int len = CharacterFunctions::length (t);
  7758. createInternal (len);
  7759. memcpy (text->text, t, (len + 1) * sizeof (tchar));
  7760. #else
  7761. const int len = CharacterFunctions::bytesRequiredForCopy (t);
  7762. createInternal (len);
  7763. CharacterFunctions::copy (text->text, t, len + 1);
  7764. #endif
  7765. }
  7766. else
  7767. {
  7768. text = &emptyString;
  7769. emptyString.refCount = safeEmptyStringRefCount;
  7770. }
  7771. }
  7772. String::String (const char* const t,
  7773. const int maxChars) throw()
  7774. {
  7775. int i;
  7776. for (i = 0; i < maxChars; ++i)
  7777. if (t[i] == 0)
  7778. break;
  7779. if (i > 0)
  7780. {
  7781. createInternal (i);
  7782. #if JUCE_STRINGS_ARE_UNICODE
  7783. CharacterFunctions::copy (text->text, t, i);
  7784. #else
  7785. memcpy (text->text, t, i);
  7786. #endif
  7787. text->text [i] = 0;
  7788. }
  7789. else
  7790. {
  7791. text = &emptyString;
  7792. emptyString.refCount = safeEmptyStringRefCount;
  7793. }
  7794. }
  7795. String::String (const juce_wchar* const t,
  7796. const int maxChars) throw()
  7797. {
  7798. int i;
  7799. for (i = 0; i < maxChars; ++i)
  7800. if (t[i] == 0)
  7801. break;
  7802. if (i > 0)
  7803. {
  7804. createInternal (i);
  7805. #if JUCE_STRINGS_ARE_UNICODE
  7806. memcpy (text->text, t, i * sizeof (tchar));
  7807. #else
  7808. CharacterFunctions::copy (text->text, t, i);
  7809. #endif
  7810. text->text [i] = 0;
  7811. }
  7812. else
  7813. {
  7814. text = &emptyString;
  7815. emptyString.refCount = safeEmptyStringRefCount;
  7816. }
  7817. }
  7818. const String String::charToString (const tchar character) throw()
  7819. {
  7820. tchar temp[2];
  7821. temp[0] = character;
  7822. temp[1] = 0;
  7823. return String (temp);
  7824. }
  7825. // pass in a pointer to the END of a buffer..
  7826. static tchar* int64ToCharString (tchar* t, const int64 n) throw()
  7827. {
  7828. *--t = 0;
  7829. int64 v = (n >= 0) ? n : -n;
  7830. do
  7831. {
  7832. *--t = (tchar) (T('0') + (int) (v % 10));
  7833. v /= 10;
  7834. } while (v > 0);
  7835. if (n < 0)
  7836. *--t = T('-');
  7837. return t;
  7838. }
  7839. static tchar* intToCharString (tchar* t, const int n) throw()
  7840. {
  7841. if (n == (int) 0x80000000) // (would cause an overflow)
  7842. return int64ToCharString (t, n);
  7843. *--t = 0;
  7844. int v = abs (n);
  7845. do
  7846. {
  7847. *--t = (tchar) (T('0') + (v % 10));
  7848. v /= 10;
  7849. } while (v > 0);
  7850. if (n < 0)
  7851. *--t = T('-');
  7852. return t;
  7853. }
  7854. static tchar* uintToCharString (tchar* t, unsigned int v) throw()
  7855. {
  7856. *--t = 0;
  7857. do
  7858. {
  7859. *--t = (tchar) (T('0') + (v % 10));
  7860. v /= 10;
  7861. } while (v > 0);
  7862. return t;
  7863. }
  7864. String::String (const int number) throw()
  7865. {
  7866. tchar buffer [16];
  7867. tchar* const end = buffer + 16;
  7868. createInternal (intToCharString (end, number), end);
  7869. }
  7870. String::String (const unsigned int number) throw()
  7871. {
  7872. tchar buffer [16];
  7873. tchar* const end = buffer + 16;
  7874. createInternal (uintToCharString (end, number), end);
  7875. }
  7876. String::String (const short number) throw()
  7877. {
  7878. tchar buffer [16];
  7879. tchar* const end = buffer + 16;
  7880. createInternal (intToCharString (end, (int) number), end);
  7881. }
  7882. String::String (const unsigned short number) throw()
  7883. {
  7884. tchar buffer [16];
  7885. tchar* const end = buffer + 16;
  7886. createInternal (uintToCharString (end, (unsigned int) number), end);
  7887. }
  7888. String::String (const int64 number) throw()
  7889. {
  7890. tchar buffer [32];
  7891. tchar* const end = buffer + 32;
  7892. createInternal (int64ToCharString (end, number), end);
  7893. }
  7894. String::String (const uint64 number) throw()
  7895. {
  7896. tchar buffer [32];
  7897. tchar* const end = buffer + 32;
  7898. tchar* t = end;
  7899. *--t = 0;
  7900. int64 v = number;
  7901. do
  7902. {
  7903. *--t = (tchar) (T('0') + (int) (v % 10));
  7904. v /= 10;
  7905. } while (v > 0);
  7906. createInternal (t, end);
  7907. }
  7908. // a double-to-string routine that actually uses the number of dec. places you asked for
  7909. // without resorting to exponent notation if the number's too big or small (which is what printf does).
  7910. void String::doubleToStringWithDecPlaces (double n, int numDecPlaces) throw()
  7911. {
  7912. const int bufSize = 80;
  7913. tchar buffer [bufSize];
  7914. int len;
  7915. tchar* t;
  7916. if (numDecPlaces > 0 && n > -1.0e20 && n < 1.0e20)
  7917. {
  7918. int64 v = (int64) (pow (10.0, numDecPlaces) * fabs (n) + 0.5);
  7919. t = buffer + bufSize;
  7920. *--t = (tchar) 0;
  7921. while (numDecPlaces >= 0 || v > 0)
  7922. {
  7923. if (numDecPlaces == 0)
  7924. *--t = decimalPoint;
  7925. *--t = (tchar) (T('0') + (v % 10));
  7926. v /= 10;
  7927. --numDecPlaces;
  7928. }
  7929. if (n < 0)
  7930. *--t = T('-');
  7931. len = (int) ((buffer + bufSize) - t);
  7932. }
  7933. else
  7934. {
  7935. len = CharacterFunctions::printf (buffer, bufSize, T("%.9g"), n) + 1;
  7936. t = buffer;
  7937. }
  7938. if (len > 1)
  7939. {
  7940. jassert (len < numElementsInArray (buffer));
  7941. createInternal (len - 1);
  7942. memcpy (text->text, t, len * sizeof (tchar));
  7943. }
  7944. else
  7945. {
  7946. jassert (*t == 0);
  7947. text = &emptyString;
  7948. emptyString.refCount = safeEmptyStringRefCount;
  7949. }
  7950. }
  7951. String::String (const float number,
  7952. const int numberOfDecimalPlaces) throw()
  7953. {
  7954. doubleToStringWithDecPlaces ((double) number,
  7955. numberOfDecimalPlaces);
  7956. }
  7957. String::String (const double number,
  7958. const int numberOfDecimalPlaces) throw()
  7959. {
  7960. doubleToStringWithDecPlaces (number,
  7961. numberOfDecimalPlaces);
  7962. }
  7963. String::~String() throw()
  7964. {
  7965. emptyString.refCount = safeEmptyStringRefCount;
  7966. if (atomicDecrementAndReturn (text->refCount) == 0)
  7967. juce_free (text);
  7968. }
  7969. void String::preallocateStorage (const int numChars) throw()
  7970. {
  7971. if (numChars > text->allocatedNumChars)
  7972. {
  7973. dupeInternalIfMultiplyReferenced();
  7974. text = (InternalRefCountedStringHolder*) juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7975. + numChars * sizeof (tchar));
  7976. text->allocatedNumChars = numChars;
  7977. }
  7978. }
  7979. #if JUCE_STRINGS_ARE_UNICODE
  7980. String::operator const char*() const throw()
  7981. {
  7982. if (isEmpty())
  7983. {
  7984. return (const char*) emptyCharString;
  7985. }
  7986. else
  7987. {
  7988. String* const mutableThis = const_cast <String*> (this);
  7989. mutableThis->dupeInternalIfMultiplyReferenced();
  7990. int len = CharacterFunctions::bytesRequiredForCopy (text->text) + 1;
  7991. mutableThis->text = (InternalRefCountedStringHolder*)
  7992. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  7993. + (len * sizeof (juce_wchar) + len));
  7994. char* otherCopy = (char*) (text->text + len);
  7995. --len;
  7996. CharacterFunctions::copy (otherCopy, text->text, len);
  7997. otherCopy [len] = 0;
  7998. return otherCopy;
  7999. }
  8000. }
  8001. #else
  8002. String::operator const juce_wchar*() const throw()
  8003. {
  8004. if (isEmpty())
  8005. {
  8006. return (const juce_wchar*) emptyCharString;
  8007. }
  8008. else
  8009. {
  8010. String* const mutableThis = const_cast <String*> (this);
  8011. mutableThis->dupeInternalIfMultiplyReferenced();
  8012. int len = CharacterFunctions::length (text->text) + 1;
  8013. mutableThis->text = (InternalRefCountedStringHolder*)
  8014. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  8015. + (len * sizeof (juce_wchar) + len));
  8016. juce_wchar* otherCopy = (juce_wchar*) (text->text + len);
  8017. --len;
  8018. CharacterFunctions::copy (otherCopy, text->text, len);
  8019. otherCopy [len] = 0;
  8020. return otherCopy;
  8021. }
  8022. }
  8023. #endif
  8024. void String::copyToBuffer (char* const destBuffer,
  8025. const int bufferSizeBytes) const throw()
  8026. {
  8027. #if JUCE_STRINGS_ARE_UNICODE
  8028. const int len = jmin (bufferSizeBytes, CharacterFunctions::bytesRequiredForCopy (text->text));
  8029. CharacterFunctions::copy (destBuffer, text->text, len);
  8030. #else
  8031. const int len = jmin (bufferSizeBytes, length());
  8032. memcpy (destBuffer, text->text, len * sizeof (tchar));
  8033. #endif
  8034. destBuffer [len] = 0;
  8035. }
  8036. void String::copyToBuffer (juce_wchar* const destBuffer,
  8037. const int maxCharsToCopy) const throw()
  8038. {
  8039. const int len = jmin (maxCharsToCopy, length());
  8040. #if JUCE_STRINGS_ARE_UNICODE
  8041. memcpy (destBuffer, text->text, len * sizeof (juce_wchar));
  8042. #else
  8043. CharacterFunctions::copy (destBuffer, text->text, len);
  8044. #endif
  8045. destBuffer [len] = 0;
  8046. }
  8047. int String::length() const throw()
  8048. {
  8049. return CharacterFunctions::length (text->text);
  8050. }
  8051. int String::hashCode() const throw()
  8052. {
  8053. const tchar* t = text->text;
  8054. int result = 0;
  8055. while (*t != (tchar) 0)
  8056. result = 31 * result + *t++;
  8057. return result;
  8058. }
  8059. int64 String::hashCode64() const throw()
  8060. {
  8061. const tchar* t = text->text;
  8062. int64 result = 0;
  8063. while (*t != (tchar) 0)
  8064. result = 101 * result + *t++;
  8065. return result;
  8066. }
  8067. const String& String::operator= (const tchar* const otherText) throw()
  8068. {
  8069. if (otherText != 0 && *otherText != 0)
  8070. {
  8071. const int otherLen = CharacterFunctions::length (otherText);
  8072. if (otherLen > 0)
  8073. {
  8074. // avoid resizing the memory block if the string is
  8075. // shrinking..
  8076. if (text->refCount > 1
  8077. || otherLen > text->allocatedNumChars
  8078. || otherLen <= (text->allocatedNumChars >> 1))
  8079. {
  8080. deleteInternal();
  8081. createInternal (otherLen);
  8082. }
  8083. memcpy (text->text, otherText, (otherLen + 1) * sizeof (tchar));
  8084. return *this;
  8085. }
  8086. }
  8087. deleteInternal();
  8088. text = &emptyString;
  8089. emptyString.refCount = safeEmptyStringRefCount;
  8090. return *this;
  8091. }
  8092. const String& String::operator= (const String& other) throw()
  8093. {
  8094. if (this != &other)
  8095. {
  8096. atomicIncrement (other.text->refCount);
  8097. if (atomicDecrementAndReturn (text->refCount) == 0)
  8098. juce_free (text);
  8099. text = other.text;
  8100. }
  8101. return *this;
  8102. }
  8103. bool String::operator== (const String& other) const throw()
  8104. {
  8105. return text == other.text
  8106. || CharacterFunctions::compare (text->text, other.text->text) == 0;
  8107. }
  8108. bool String::operator== (const tchar* const t) const throw()
  8109. {
  8110. return t != 0 ? CharacterFunctions::compare (text->text, t) == 0
  8111. : isEmpty();
  8112. }
  8113. bool String::equalsIgnoreCase (const tchar* t) const throw()
  8114. {
  8115. return t != 0 ? CharacterFunctions::compareIgnoreCase (text->text, t) == 0
  8116. : isEmpty();
  8117. }
  8118. bool String::equalsIgnoreCase (const String& other) const throw()
  8119. {
  8120. return text == other.text
  8121. || CharacterFunctions::compareIgnoreCase (text->text, other.text->text) == 0;
  8122. }
  8123. bool String::operator!= (const String& other) const throw()
  8124. {
  8125. return text != other.text
  8126. && CharacterFunctions::compare (text->text, other.text->text) != 0;
  8127. }
  8128. bool String::operator!= (const tchar* const t) const throw()
  8129. {
  8130. return t != 0 ? (CharacterFunctions::compare (text->text, t) != 0)
  8131. : isNotEmpty();
  8132. }
  8133. bool String::operator> (const String& other) const throw()
  8134. {
  8135. return compare (other) > 0;
  8136. }
  8137. bool String::operator< (const tchar* const other) const throw()
  8138. {
  8139. return compare (other) < 0;
  8140. }
  8141. bool String::operator>= (const String& other) const throw()
  8142. {
  8143. return compare (other) >= 0;
  8144. }
  8145. bool String::operator<= (const tchar* const other) const throw()
  8146. {
  8147. return compare (other) <= 0;
  8148. }
  8149. int String::compare (const tchar* const other) const throw()
  8150. {
  8151. return other != 0 ? CharacterFunctions::compare (text->text, other)
  8152. : isEmpty();
  8153. }
  8154. int String::compareIgnoreCase (const tchar* const other) const throw()
  8155. {
  8156. return other != 0 ? CharacterFunctions::compareIgnoreCase (text->text, other)
  8157. : isEmpty();
  8158. }
  8159. int String::compareLexicographically (const tchar* other) const throw()
  8160. {
  8161. if (other == 0)
  8162. return isEmpty();
  8163. const tchar* s1 = text->text;
  8164. while (*s1 != 0 && ! CharacterFunctions::isLetterOrDigit (*s1))
  8165. ++s1;
  8166. while (*other != 0 && ! CharacterFunctions::isLetterOrDigit (*other))
  8167. ++other;
  8168. return CharacterFunctions::compareIgnoreCase (s1, other);
  8169. }
  8170. const String String::operator+ (const String& other) const throw()
  8171. {
  8172. if (*(other.text->text) == 0)
  8173. return *this;
  8174. if (isEmpty())
  8175. return other;
  8176. const int len = CharacterFunctions::length (text->text);
  8177. const int otherLen = CharacterFunctions::length (other.text->text);
  8178. String result (len + otherLen, (int) 0);
  8179. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8180. memcpy (result.text->text + len, other.text->text, otherLen * sizeof (tchar));
  8181. result.text->text [len + otherLen] = 0;
  8182. return result;
  8183. }
  8184. const String String::operator+ (const tchar* const textToAppend) const throw()
  8185. {
  8186. if (textToAppend == 0 || *textToAppend == 0)
  8187. return *this;
  8188. const int len = CharacterFunctions::length (text->text);
  8189. const int otherLen = CharacterFunctions::length (textToAppend);
  8190. String result (len + otherLen, (int) 0);
  8191. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8192. memcpy (result.text->text + len, textToAppend, otherLen * sizeof (tchar));
  8193. result.text->text [len + otherLen] = 0;
  8194. return result;
  8195. }
  8196. const String String::operator+ (const tchar characterToAppend) const throw()
  8197. {
  8198. if (characterToAppend == 0)
  8199. return *this;
  8200. const int len = CharacterFunctions::length (text->text);
  8201. String result ((int) (len + 1), (int) 0);
  8202. memcpy (result.text->text, text->text, len * sizeof (tchar));
  8203. result.text->text[len] = characterToAppend;
  8204. result.text->text[len + 1] = 0;
  8205. return result;
  8206. }
  8207. const String JUCE_PUBLIC_FUNCTION operator+ (const char* const string1,
  8208. const String& string2) throw()
  8209. {
  8210. String s (string1);
  8211. s += string2;
  8212. return s;
  8213. }
  8214. const String JUCE_PUBLIC_FUNCTION operator+ (const juce_wchar* const string1,
  8215. const String& string2) throw()
  8216. {
  8217. String s (string1);
  8218. s += string2;
  8219. return s;
  8220. }
  8221. const String& String::operator+= (const tchar* const t) throw()
  8222. {
  8223. if (t != 0)
  8224. appendInternal (t, CharacterFunctions::length (t));
  8225. return *this;
  8226. }
  8227. const String& String::operator+= (const String& other) throw()
  8228. {
  8229. if (isEmpty())
  8230. operator= (other);
  8231. else
  8232. appendInternal (other.text->text,
  8233. CharacterFunctions::length (other.text->text));
  8234. return *this;
  8235. }
  8236. const String& String::operator+= (const char ch) throw()
  8237. {
  8238. char asString[2];
  8239. asString[0] = ch;
  8240. asString[1] = 0;
  8241. #if JUCE_STRINGS_ARE_UNICODE
  8242. operator+= (String (asString));
  8243. #else
  8244. appendInternal (asString, 1);
  8245. #endif
  8246. return *this;
  8247. }
  8248. const String& String::operator+= (const juce_wchar ch) throw()
  8249. {
  8250. juce_wchar asString[2];
  8251. asString[0] = ch;
  8252. asString[1] = 0;
  8253. #if JUCE_STRINGS_ARE_UNICODE
  8254. appendInternal (asString, 1);
  8255. #else
  8256. operator+= (String (asString));
  8257. #endif
  8258. return *this;
  8259. }
  8260. void String::append (const tchar* const other,
  8261. const int howMany) throw()
  8262. {
  8263. if (howMany > 0)
  8264. {
  8265. int i;
  8266. for (i = 0; i < howMany; ++i)
  8267. if (other[i] == 0)
  8268. break;
  8269. appendInternal (other, i);
  8270. }
  8271. }
  8272. String& String::operator<< (const int number) throw()
  8273. {
  8274. tchar buffer [64];
  8275. tchar* const end = buffer + 64;
  8276. const tchar* const t = intToCharString (end, number);
  8277. appendInternal (t, (int) (end - t) - 1);
  8278. return *this;
  8279. }
  8280. String& String::operator<< (const unsigned int number) throw()
  8281. {
  8282. tchar buffer [64];
  8283. tchar* const end = buffer + 64;
  8284. const tchar* const t = uintToCharString (end, number);
  8285. appendInternal (t, (int) (end - t) - 1);
  8286. return *this;
  8287. }
  8288. String& String::operator<< (const short number) throw()
  8289. {
  8290. tchar buffer [64];
  8291. tchar* const end = buffer + 64;
  8292. const tchar* const t = intToCharString (end, (int) number);
  8293. appendInternal (t, (int) (end - t) - 1);
  8294. return *this;
  8295. }
  8296. String& String::operator<< (const double number) throw()
  8297. {
  8298. operator+= (String (number));
  8299. return *this;
  8300. }
  8301. String& String::operator<< (const float number) throw()
  8302. {
  8303. operator+= (String (number));
  8304. return *this;
  8305. }
  8306. String& String::operator<< (const char character) throw()
  8307. {
  8308. operator+= (character);
  8309. return *this;
  8310. }
  8311. String& String::operator<< (const juce_wchar character) throw()
  8312. {
  8313. operator+= (character);
  8314. return *this;
  8315. }
  8316. String& String::operator<< (const char* const t) throw()
  8317. {
  8318. #if JUCE_STRINGS_ARE_UNICODE
  8319. operator+= (String (t));
  8320. #else
  8321. operator+= (t);
  8322. #endif
  8323. return *this;
  8324. }
  8325. String& String::operator<< (const juce_wchar* const t) throw()
  8326. {
  8327. #if JUCE_STRINGS_ARE_UNICODE
  8328. operator+= (t);
  8329. #else
  8330. operator+= (String (t));
  8331. #endif
  8332. return *this;
  8333. }
  8334. String& String::operator<< (const String& t) throw()
  8335. {
  8336. operator+= (t);
  8337. return *this;
  8338. }
  8339. int String::indexOfChar (const tchar character) const throw()
  8340. {
  8341. const tchar* t = text->text;
  8342. for (;;)
  8343. {
  8344. if (*t == character)
  8345. return (int) (t - text->text);
  8346. if (*t++ == 0)
  8347. return -1;
  8348. }
  8349. }
  8350. int String::lastIndexOfChar (const tchar character) const throw()
  8351. {
  8352. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  8353. if (text->text[i] == character)
  8354. return i;
  8355. return -1;
  8356. }
  8357. int String::indexOf (const tchar* const t) const throw()
  8358. {
  8359. const tchar* const r = CharacterFunctions::find (text->text, t);
  8360. return (r == 0) ? -1
  8361. : (int) (r - text->text);
  8362. }
  8363. int String::indexOfChar (const int startIndex,
  8364. const tchar character) const throw()
  8365. {
  8366. if (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text))
  8367. return -1;
  8368. const tchar* t = text->text + jmax (0, startIndex);
  8369. for (;;)
  8370. {
  8371. if (*t == character)
  8372. return (int) (t - text->text);
  8373. if (*t++ == 0)
  8374. return -1;
  8375. }
  8376. }
  8377. int String::indexOfAnyOf (const tchar* const charactersToLookFor,
  8378. const int startIndex,
  8379. const bool ignoreCase) const throw()
  8380. {
  8381. if (charactersToLookFor == 0
  8382. || (startIndex >= 0 && startIndex >= CharacterFunctions::length (text->text)))
  8383. return -1;
  8384. const tchar* t = text->text + jmax (0, startIndex);
  8385. while (*t != 0)
  8386. {
  8387. if (CharacterFunctions::indexOfChar (charactersToLookFor, *t, ignoreCase) >= 0)
  8388. return (int) (t - text->text);
  8389. ++t;
  8390. }
  8391. return -1;
  8392. }
  8393. int String::indexOf (const int startIndex,
  8394. const tchar* const other) const throw()
  8395. {
  8396. if (other == 0 || startIndex >= CharacterFunctions::length (text->text))
  8397. return -1;
  8398. const tchar* const found = CharacterFunctions::find (text->text + jmax (0, startIndex),
  8399. other);
  8400. return (found == 0) ? -1
  8401. : (int) (found - text->text);
  8402. }
  8403. int String::indexOfIgnoreCase (const tchar* const other) const throw()
  8404. {
  8405. if (other != 0 && *other != 0)
  8406. {
  8407. const int len = CharacterFunctions::length (other);
  8408. const int end = CharacterFunctions::length (text->text) - len;
  8409. for (int i = 0; i <= end; ++i)
  8410. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  8411. return i;
  8412. }
  8413. return -1;
  8414. }
  8415. int String::indexOfIgnoreCase (const int startIndex,
  8416. const tchar* const other) const throw()
  8417. {
  8418. if (other != 0 && *other != 0)
  8419. {
  8420. const int len = CharacterFunctions::length (other);
  8421. const int end = length() - len;
  8422. for (int i = jmax (0, startIndex); i <= end; ++i)
  8423. if (CharacterFunctions::compareIgnoreCase (text->text + i, other, len) == 0)
  8424. return i;
  8425. }
  8426. return -1;
  8427. }
  8428. int String::lastIndexOf (const tchar* const other) const throw()
  8429. {
  8430. if (other != 0 && *other != 0)
  8431. {
  8432. const int len = CharacterFunctions::length (other);
  8433. int i = length() - len;
  8434. if (i >= 0)
  8435. {
  8436. const tchar* n = text->text + i;
  8437. while (i >= 0)
  8438. {
  8439. if (CharacterFunctions::compare (n--, other, len) == 0)
  8440. return i;
  8441. --i;
  8442. }
  8443. }
  8444. }
  8445. return -1;
  8446. }
  8447. int String::lastIndexOfIgnoreCase (const tchar* const other) const throw()
  8448. {
  8449. if (other != 0 && *other != 0)
  8450. {
  8451. const int len = CharacterFunctions::length (other);
  8452. int i = length() - len;
  8453. if (i >= 0)
  8454. {
  8455. const tchar* n = text->text + i;
  8456. while (i >= 0)
  8457. {
  8458. if (CharacterFunctions::compareIgnoreCase (n--, other, len) == 0)
  8459. return i;
  8460. --i;
  8461. }
  8462. }
  8463. }
  8464. return -1;
  8465. }
  8466. int String::lastIndexOfAnyOf (const tchar* const charactersToLookFor,
  8467. const bool ignoreCase) const throw()
  8468. {
  8469. for (int i = CharacterFunctions::length (text->text); --i >= 0;)
  8470. if (CharacterFunctions::indexOfChar (charactersToLookFor, text->text [i], ignoreCase) >= 0)
  8471. return i;
  8472. return -1;
  8473. }
  8474. bool String::contains (const tchar* const other) const throw()
  8475. {
  8476. return indexOf (other) >= 0;
  8477. }
  8478. bool String::containsChar (const tchar character) const throw()
  8479. {
  8480. return indexOfChar (character) >= 0;
  8481. }
  8482. bool String::containsIgnoreCase (const tchar* const t) const throw()
  8483. {
  8484. return indexOfIgnoreCase (t) >= 0;
  8485. }
  8486. int String::indexOfWholeWord (const tchar* const word) const throw()
  8487. {
  8488. if (word != 0 && *word != 0)
  8489. {
  8490. const int wordLen = CharacterFunctions::length (word);
  8491. const int end = length() - wordLen;
  8492. const tchar* t = text->text;
  8493. for (int i = 0; i <= end; ++i)
  8494. {
  8495. if (CharacterFunctions::compare (t, word, wordLen) == 0
  8496. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8497. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8498. {
  8499. return i;
  8500. }
  8501. ++t;
  8502. }
  8503. }
  8504. return -1;
  8505. }
  8506. int String::indexOfWholeWordIgnoreCase (const tchar* const word) const throw()
  8507. {
  8508. if (word != 0 && *word != 0)
  8509. {
  8510. const int wordLen = CharacterFunctions::length (word);
  8511. const int end = length() - wordLen;
  8512. const tchar* t = text->text;
  8513. for (int i = 0; i <= end; ++i)
  8514. {
  8515. if (CharacterFunctions::compareIgnoreCase (t, word, wordLen) == 0
  8516. && (i == 0 || ! CharacterFunctions::isLetterOrDigit (* (t - 1)))
  8517. && ! CharacterFunctions::isLetterOrDigit (t [wordLen]))
  8518. {
  8519. return i;
  8520. }
  8521. ++t;
  8522. }
  8523. }
  8524. return -1;
  8525. }
  8526. bool String::containsWholeWord (const tchar* const wordToLookFor) const throw()
  8527. {
  8528. return indexOfWholeWord (wordToLookFor) >= 0;
  8529. }
  8530. bool String::containsWholeWordIgnoreCase (const tchar* const wordToLookFor) const throw()
  8531. {
  8532. return indexOfWholeWordIgnoreCase (wordToLookFor) >= 0;
  8533. }
  8534. static int indexOfMatch (const tchar* const wildcard,
  8535. const tchar* const test,
  8536. const bool ignoreCase) throw()
  8537. {
  8538. int start = 0;
  8539. while (test [start] != 0)
  8540. {
  8541. int i = 0;
  8542. for (;;)
  8543. {
  8544. const tchar wc = wildcard [i];
  8545. const tchar c = test [i + start];
  8546. if (wc == c
  8547. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  8548. || (wc == T('?') && c != 0))
  8549. {
  8550. if (wc == 0)
  8551. return start;
  8552. ++i;
  8553. }
  8554. else
  8555. {
  8556. if (wc == T('*') && (wildcard [i + 1] == 0
  8557. || indexOfMatch (wildcard + i + 1,
  8558. test + start + i,
  8559. ignoreCase) >= 0))
  8560. {
  8561. return start;
  8562. }
  8563. break;
  8564. }
  8565. }
  8566. ++start;
  8567. }
  8568. return -1;
  8569. }
  8570. bool String::matchesWildcard (const tchar* wildcard, const bool ignoreCase) const throw()
  8571. {
  8572. int i = 0;
  8573. for (;;)
  8574. {
  8575. const tchar wc = wildcard [i];
  8576. const tchar c = text->text [i];
  8577. if (wc == c
  8578. || (ignoreCase && CharacterFunctions::toLowerCase (wc) == CharacterFunctions::toLowerCase (c))
  8579. || (wc == T('?') && c != 0))
  8580. {
  8581. if (wc == 0)
  8582. return true;
  8583. ++i;
  8584. }
  8585. else
  8586. {
  8587. return wc == T('*') && (wildcard [i + 1] == 0
  8588. || indexOfMatch (wildcard + i + 1,
  8589. text->text + i,
  8590. ignoreCase) >= 0);
  8591. }
  8592. }
  8593. }
  8594. void String::printf (const tchar* const pf, ...) throw()
  8595. {
  8596. va_list list;
  8597. va_start (list, pf);
  8598. vprintf (pf, list);
  8599. }
  8600. const String String::formatted (const tchar* const pf, ...) throw()
  8601. {
  8602. va_list list;
  8603. va_start (list, pf);
  8604. String result;
  8605. result.vprintf (pf, list);
  8606. return result;
  8607. }
  8608. void String::vprintf (const tchar* const pf, va_list& args) throw()
  8609. {
  8610. tchar stackBuf [256];
  8611. unsigned int bufSize = 256;
  8612. tchar* buf = stackBuf;
  8613. deleteInternal();
  8614. do
  8615. {
  8616. #if JUCE_LINUX && JUCE_64BIT
  8617. va_list tempArgs;
  8618. va_copy (tempArgs, args);
  8619. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, tempArgs);
  8620. va_end (tempArgs);
  8621. #else
  8622. const int num = CharacterFunctions::vprintf (buf, bufSize - 1, pf, args);
  8623. #endif
  8624. if (num > 0)
  8625. {
  8626. createInternal (num);
  8627. memcpy (text->text, buf, (num + 1) * sizeof (tchar));
  8628. break;
  8629. }
  8630. else if (num == 0)
  8631. {
  8632. text = &emptyString;
  8633. emptyString.refCount = safeEmptyStringRefCount;
  8634. break;
  8635. }
  8636. if (buf != stackBuf)
  8637. juce_free (buf);
  8638. bufSize += 256;
  8639. buf = (tchar*) juce_malloc (bufSize * sizeof (tchar));
  8640. }
  8641. while (bufSize < 65536); // this is a sanity check to avoid situations where vprintf repeatedly
  8642. // returns -1 because of an error rather than because it needs more space.
  8643. if (buf != stackBuf)
  8644. juce_free (buf);
  8645. }
  8646. const String String::repeatedString (const tchar* const stringToRepeat,
  8647. int numberOfTimesToRepeat) throw()
  8648. {
  8649. const int len = CharacterFunctions::length (stringToRepeat);
  8650. String result ((int) (len * numberOfTimesToRepeat + 1), (int) 0);
  8651. tchar* n = result.text->text;
  8652. n[0] = 0;
  8653. while (--numberOfTimesToRepeat >= 0)
  8654. {
  8655. CharacterFunctions::append (n, stringToRepeat);
  8656. n += len;
  8657. }
  8658. return result;
  8659. }
  8660. const String String::replaceSection (int index,
  8661. int numCharsToReplace,
  8662. const tchar* const stringToInsert) const throw()
  8663. {
  8664. if (index < 0)
  8665. {
  8666. // a negative index to replace from?
  8667. jassertfalse
  8668. index = 0;
  8669. }
  8670. if (numCharsToReplace < 0)
  8671. {
  8672. // replacing a negative number of characters?
  8673. numCharsToReplace = 0;
  8674. jassertfalse;
  8675. }
  8676. const int len = length();
  8677. if (index + numCharsToReplace > len)
  8678. {
  8679. if (index > len)
  8680. {
  8681. // replacing beyond the end of the string?
  8682. index = len;
  8683. jassertfalse
  8684. }
  8685. numCharsToReplace = len - index;
  8686. }
  8687. const int newStringLen = (stringToInsert != 0) ? CharacterFunctions::length (stringToInsert) : 0;
  8688. const int newTotalLen = len + newStringLen - numCharsToReplace;
  8689. String result (newTotalLen, (int) 0);
  8690. memcpy (result.text->text,
  8691. text->text,
  8692. index * sizeof (tchar));
  8693. if (newStringLen > 0)
  8694. memcpy (result.text->text + index,
  8695. stringToInsert,
  8696. newStringLen * sizeof (tchar));
  8697. const int endStringLen = newTotalLen - (index + newStringLen);
  8698. if (endStringLen > 0)
  8699. memcpy (result.text->text + (index + newStringLen),
  8700. text->text + (index + numCharsToReplace),
  8701. endStringLen * sizeof (tchar));
  8702. result.text->text [newTotalLen] = 0;
  8703. return result;
  8704. }
  8705. const String String::replace (const tchar* const stringToReplace,
  8706. const tchar* const stringToInsert,
  8707. const bool ignoreCase) const throw()
  8708. {
  8709. const int stringToReplaceLen = CharacterFunctions::length (stringToReplace);
  8710. const int stringToInsertLen = CharacterFunctions::length (stringToInsert);
  8711. int i = 0;
  8712. String result (*this);
  8713. while ((i = (ignoreCase ? result.indexOfIgnoreCase (i, stringToReplace)
  8714. : result.indexOf (i, stringToReplace))) >= 0)
  8715. {
  8716. result = result.replaceSection (i, stringToReplaceLen, stringToInsert);
  8717. i += stringToInsertLen;
  8718. }
  8719. return result;
  8720. }
  8721. const String String::replaceCharacter (const tchar charToReplace,
  8722. const tchar charToInsert) const throw()
  8723. {
  8724. const int index = indexOfChar (charToReplace);
  8725. if (index < 0)
  8726. return *this;
  8727. String result (*this);
  8728. result.dupeInternalIfMultiplyReferenced();
  8729. tchar* t = result.text->text + index;
  8730. while (*t != 0)
  8731. {
  8732. if (*t == charToReplace)
  8733. *t = charToInsert;
  8734. ++t;
  8735. }
  8736. return result;
  8737. }
  8738. const String String::replaceCharacters (const String& charactersToReplace,
  8739. const tchar* const charactersToInsertInstead) const throw()
  8740. {
  8741. String result (*this);
  8742. result.dupeInternalIfMultiplyReferenced();
  8743. tchar* t = result.text->text;
  8744. const int len2 = CharacterFunctions::length (charactersToInsertInstead);
  8745. // the two strings passed in are supposed to be the same length!
  8746. jassert (len2 == charactersToReplace.length());
  8747. while (*t != 0)
  8748. {
  8749. const int index = charactersToReplace.indexOfChar (*t);
  8750. if (((unsigned int) index) < (unsigned int) len2)
  8751. *t = charactersToInsertInstead [index];
  8752. ++t;
  8753. }
  8754. return result;
  8755. }
  8756. bool String::startsWith (const tchar* const other) const throw()
  8757. {
  8758. return other != 0
  8759. && CharacterFunctions::compare (text->text, other, CharacterFunctions::length (other)) == 0;
  8760. }
  8761. bool String::startsWithIgnoreCase (const tchar* const other) const throw()
  8762. {
  8763. return other != 0
  8764. && CharacterFunctions::compareIgnoreCase (text->text, other, CharacterFunctions::length (other)) == 0;
  8765. }
  8766. bool String::startsWithChar (const tchar character) const throw()
  8767. {
  8768. return text->text[0] == character;
  8769. }
  8770. bool String::endsWithChar (const tchar character) const throw()
  8771. {
  8772. return text->text[0] != 0
  8773. && text->text [length() - 1] == character;
  8774. }
  8775. bool String::endsWith (const tchar* const other) const throw()
  8776. {
  8777. if (other == 0)
  8778. return false;
  8779. const int thisLen = length();
  8780. const int otherLen = CharacterFunctions::length (other);
  8781. return thisLen >= otherLen
  8782. && CharacterFunctions::compare (text->text + thisLen - otherLen, other) == 0;
  8783. }
  8784. bool String::endsWithIgnoreCase (const tchar* const other) const throw()
  8785. {
  8786. if (other == 0)
  8787. return false;
  8788. const int thisLen = length();
  8789. const int otherLen = CharacterFunctions::length (other);
  8790. return thisLen >= otherLen
  8791. && CharacterFunctions::compareIgnoreCase (text->text + thisLen - otherLen, other) == 0;
  8792. }
  8793. const String String::toUpperCase() const throw()
  8794. {
  8795. String result (*this);
  8796. result.dupeInternalIfMultiplyReferenced();
  8797. CharacterFunctions::toUpperCase (result.text->text);
  8798. return result;
  8799. }
  8800. const String String::toLowerCase() const throw()
  8801. {
  8802. String result (*this);
  8803. result.dupeInternalIfMultiplyReferenced();
  8804. CharacterFunctions::toLowerCase (result.text->text);
  8805. return result;
  8806. }
  8807. tchar& String::operator[] (const int index) throw()
  8808. {
  8809. jassert (((unsigned int) index) <= (unsigned int) length());
  8810. dupeInternalIfMultiplyReferenced();
  8811. return text->text [index];
  8812. }
  8813. tchar String::getLastCharacter() const throw()
  8814. {
  8815. return (isEmpty()) ? ((tchar) 0)
  8816. : text->text [CharacterFunctions::length (text->text) - 1];
  8817. }
  8818. const String String::substring (int start, int end) const throw()
  8819. {
  8820. if (start < 0)
  8821. start = 0;
  8822. else if (end <= start)
  8823. return empty;
  8824. int len = 0;
  8825. const tchar* const t = text->text;
  8826. while (len <= end && t [len] != 0)
  8827. ++len;
  8828. if (end >= len)
  8829. {
  8830. if (start == 0)
  8831. return *this;
  8832. end = len;
  8833. }
  8834. return String (text->text + start,
  8835. end - start);
  8836. }
  8837. const String String::substring (const int start) const throw()
  8838. {
  8839. if (start <= 0)
  8840. return *this;
  8841. const int len = CharacterFunctions::length (text->text);
  8842. if (start >= len)
  8843. return empty;
  8844. else
  8845. return String (text->text + start,
  8846. len - start);
  8847. }
  8848. const String String::dropLastCharacters (const int numberToDrop) const throw()
  8849. {
  8850. return String (text->text,
  8851. jmax (0, CharacterFunctions::length (text->text) - numberToDrop));
  8852. }
  8853. const String String::fromFirstOccurrenceOf (const tchar* const sub,
  8854. const bool includeSubString,
  8855. const bool ignoreCase) const throw()
  8856. {
  8857. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  8858. : indexOf (sub);
  8859. if (i < 0)
  8860. return empty;
  8861. else
  8862. return substring (includeSubString ? i : i + CharacterFunctions::length (sub));
  8863. }
  8864. const String String::fromLastOccurrenceOf (const tchar* const sub,
  8865. const bool includeSubString,
  8866. const bool ignoreCase) const throw()
  8867. {
  8868. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  8869. : lastIndexOf (sub);
  8870. if (i < 0)
  8871. return *this;
  8872. else
  8873. return substring (includeSubString ? i : i + CharacterFunctions::length (sub));
  8874. }
  8875. const String String::upToFirstOccurrenceOf (const tchar* const sub,
  8876. const bool includeSubString,
  8877. const bool ignoreCase) const throw()
  8878. {
  8879. const int i = ignoreCase ? indexOfIgnoreCase (sub)
  8880. : indexOf (sub);
  8881. if (i < 0)
  8882. return *this;
  8883. else
  8884. return substring (0, includeSubString ? i + CharacterFunctions::length (sub) : i);
  8885. }
  8886. const String String::upToLastOccurrenceOf (const tchar* const sub,
  8887. const bool includeSubString,
  8888. const bool ignoreCase) const throw()
  8889. {
  8890. const int i = ignoreCase ? lastIndexOfIgnoreCase (sub)
  8891. : lastIndexOf (sub);
  8892. if (i < 0)
  8893. return *this;
  8894. return substring (0, includeSubString ? i + CharacterFunctions::length (sub) : i);
  8895. }
  8896. bool String::isQuotedString() const throw()
  8897. {
  8898. const String trimmed (trimStart());
  8899. return trimmed[0] == T('"')
  8900. || trimmed[0] == T('\'');
  8901. }
  8902. const String String::unquoted() const throw()
  8903. {
  8904. String s (*this);
  8905. if (s[0] == T('"') || s[0] == T('\''))
  8906. s = s.substring (1);
  8907. const int lastCharIndex = s.length() - 1;
  8908. if (lastCharIndex >= 0
  8909. && (s [lastCharIndex] == T('"') || s[lastCharIndex] == T('\'')))
  8910. s [lastCharIndex] = 0;
  8911. return s;
  8912. }
  8913. const String String::quoted (const tchar quoteCharacter) const throw()
  8914. {
  8915. if (isEmpty())
  8916. return charToString (quoteCharacter) + quoteCharacter;
  8917. String t (*this);
  8918. if (! t.startsWithChar (quoteCharacter))
  8919. t = charToString (quoteCharacter) + t;
  8920. if (! t.endsWithChar (quoteCharacter))
  8921. t += quoteCharacter;
  8922. return t;
  8923. }
  8924. const String String::trim() const throw()
  8925. {
  8926. if (isEmpty())
  8927. return empty;
  8928. int start = 0;
  8929. while (CharacterFunctions::isWhitespace (text->text [start]))
  8930. ++start;
  8931. const int len = CharacterFunctions::length (text->text);
  8932. int end = len - 1;
  8933. while ((end >= start) && CharacterFunctions::isWhitespace (text->text [end]))
  8934. --end;
  8935. ++end;
  8936. if (end <= start)
  8937. return empty;
  8938. else if (start > 0 || end < len)
  8939. return String (text->text + start, end - start);
  8940. else
  8941. return *this;
  8942. }
  8943. const String String::trimStart() const throw()
  8944. {
  8945. if (isEmpty())
  8946. return empty;
  8947. const tchar* t = text->text;
  8948. while (CharacterFunctions::isWhitespace (*t))
  8949. ++t;
  8950. if (t == text->text)
  8951. return *this;
  8952. else
  8953. return String (t);
  8954. }
  8955. const String String::trimEnd() const throw()
  8956. {
  8957. if (isEmpty())
  8958. return empty;
  8959. const tchar* endT = text->text + (CharacterFunctions::length (text->text) - 1);
  8960. while ((endT >= text->text) && CharacterFunctions::isWhitespace (*endT))
  8961. --endT;
  8962. return String (text->text, (int) (++endT - text->text));
  8963. }
  8964. const String String::retainCharacters (const tchar* const charactersToRetain) const throw()
  8965. {
  8966. jassert (charactersToRetain != 0);
  8967. if (isEmpty())
  8968. return empty;
  8969. String result (text->allocatedNumChars, (int) 0);
  8970. tchar* dst = result.text->text;
  8971. const tchar* src = text->text;
  8972. while (*src != 0)
  8973. {
  8974. if (CharacterFunctions::indexOfCharFast (charactersToRetain, *src) >= 0)
  8975. *dst++ = *src;
  8976. ++src;
  8977. }
  8978. *dst = 0;
  8979. return result;
  8980. }
  8981. const String String::removeCharacters (const tchar* const charactersToRemove) const throw()
  8982. {
  8983. jassert (charactersToRemove != 0);
  8984. if (isEmpty())
  8985. return empty;
  8986. String result (text->allocatedNumChars, (int) 0);
  8987. tchar* dst = result.text->text;
  8988. const tchar* src = text->text;
  8989. while (*src != 0)
  8990. {
  8991. if (CharacterFunctions::indexOfCharFast (charactersToRemove, *src) < 0)
  8992. *dst++ = *src;
  8993. ++src;
  8994. }
  8995. *dst = 0;
  8996. return result;
  8997. }
  8998. const String String::initialSectionContainingOnly (const tchar* const permittedCharacters) const throw()
  8999. {
  9000. return substring (0, CharacterFunctions::getIntialSectionContainingOnly (text->text, permittedCharacters));
  9001. }
  9002. const String String::initialSectionNotContaining (const tchar* const charactersToStopAt) const throw()
  9003. {
  9004. jassert (charactersToStopAt != 0);
  9005. const tchar* const t = text->text;
  9006. int i = 0;
  9007. while (t[i] != 0)
  9008. {
  9009. if (CharacterFunctions::indexOfCharFast (charactersToStopAt, t[i]) >= 0)
  9010. return String (text->text, i);
  9011. ++i;
  9012. }
  9013. return empty;
  9014. }
  9015. bool String::containsOnly (const tchar* const chars) const throw()
  9016. {
  9017. jassert (chars != 0);
  9018. const tchar* t = text->text;
  9019. while (*t != 0)
  9020. if (CharacterFunctions::indexOfCharFast (chars, *t++) < 0)
  9021. return false;
  9022. return true;
  9023. }
  9024. bool String::containsAnyOf (const tchar* const chars) const throw()
  9025. {
  9026. jassert (chars != 0);
  9027. const tchar* t = text->text;
  9028. while (*t != 0)
  9029. if (CharacterFunctions::indexOfCharFast (chars, *t++) >= 0)
  9030. return true;
  9031. return false;
  9032. }
  9033. int String::getIntValue() const throw()
  9034. {
  9035. return CharacterFunctions::getIntValue (text->text);
  9036. }
  9037. int String::getTrailingIntValue() const throw()
  9038. {
  9039. int n = 0;
  9040. int mult = 1;
  9041. const tchar* t = text->text + length();
  9042. while (--t >= text->text)
  9043. {
  9044. const tchar c = *t;
  9045. if (! CharacterFunctions::isDigit (c))
  9046. {
  9047. if (c == T('-'))
  9048. n = -n;
  9049. break;
  9050. }
  9051. n += mult * (c - T('0'));
  9052. mult *= 10;
  9053. }
  9054. return n;
  9055. }
  9056. int64 String::getLargeIntValue() const throw()
  9057. {
  9058. return CharacterFunctions::getInt64Value (text->text);
  9059. }
  9060. float String::getFloatValue() const throw()
  9061. {
  9062. return (float) CharacterFunctions::getDoubleValue (text->text);
  9063. }
  9064. double String::getDoubleValue() const throw()
  9065. {
  9066. return CharacterFunctions::getDoubleValue (text->text);
  9067. }
  9068. static const tchar* const hexDigits = T("0123456789abcdef");
  9069. const String String::toHexString (const int number) throw()
  9070. {
  9071. tchar buffer[32];
  9072. tchar* const end = buffer + 32;
  9073. tchar* t = end;
  9074. *--t = 0;
  9075. unsigned int v = (unsigned int) number;
  9076. do
  9077. {
  9078. *--t = hexDigits [v & 15];
  9079. v >>= 4;
  9080. } while (v != 0);
  9081. return String (t, (int) (((char*) end) - (char*) t) - 1);
  9082. }
  9083. const String String::toHexString (const int64 number) throw()
  9084. {
  9085. tchar buffer[32];
  9086. tchar* const end = buffer + 32;
  9087. tchar* t = end;
  9088. *--t = 0;
  9089. uint64 v = (uint64) number;
  9090. do
  9091. {
  9092. *--t = hexDigits [(int) (v & 15)];
  9093. v >>= 4;
  9094. } while (v != 0);
  9095. return String (t, (int) (((char*) end) - (char*) t));
  9096. }
  9097. const String String::toHexString (const short number) throw()
  9098. {
  9099. return toHexString ((int) (unsigned short) number);
  9100. }
  9101. const String String::toHexString (const unsigned char* data,
  9102. const int size,
  9103. const int groupSize) throw()
  9104. {
  9105. if (size <= 0)
  9106. return empty;
  9107. int numChars = (size * 2) + 2;
  9108. if (groupSize > 0)
  9109. numChars += size / groupSize;
  9110. String s (numChars, (int) 0);
  9111. tchar* d = s.text->text;
  9112. for (int i = 0; i < size; ++i)
  9113. {
  9114. *d++ = hexDigits [(*data) >> 4];
  9115. *d++ = hexDigits [(*data) & 0xf];
  9116. ++data;
  9117. if (groupSize > 0 && (i % groupSize) == (groupSize - 1) && i < (size - 1))
  9118. *d++ = T(' ');
  9119. }
  9120. *d = 0;
  9121. return s;
  9122. }
  9123. int String::getHexValue32() const throw()
  9124. {
  9125. int result = 0;
  9126. const tchar* c = text->text;
  9127. for (;;)
  9128. {
  9129. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9130. if (hexValue >= 0)
  9131. result = (result << 4) | hexValue;
  9132. else if (*c == 0)
  9133. break;
  9134. ++c;
  9135. }
  9136. return result;
  9137. }
  9138. int64 String::getHexValue64() const throw()
  9139. {
  9140. int64 result = 0;
  9141. const tchar* c = text->text;
  9142. for (;;)
  9143. {
  9144. const int hexValue = CharacterFunctions::getHexDigitValue (*c);
  9145. if (hexValue >= 0)
  9146. result = (result << 4) | hexValue;
  9147. else if (*c == 0)
  9148. break;
  9149. ++c;
  9150. }
  9151. return result;
  9152. }
  9153. const String String::createStringFromData (const void* const data_,
  9154. const int size) throw()
  9155. {
  9156. const char* const data = (const char*) data_;
  9157. if (size <= 0 || data == 0)
  9158. {
  9159. return empty;
  9160. }
  9161. else if (size < 2)
  9162. {
  9163. return charToString (data[0]);
  9164. }
  9165. else if ((data[0] == (char)-2 && data[1] == (char)-1)
  9166. || (data[0] == (char)-1 && data[1] == (char)-2))
  9167. {
  9168. // assume it's 16-bit unicode
  9169. const bool bigEndian = (data[0] == (char)-2);
  9170. const int numChars = size / 2 - 1;
  9171. String result;
  9172. result.preallocateStorage (numChars + 2);
  9173. const uint16* const src = (const uint16*) (data + 2);
  9174. tchar* const dst = const_cast <tchar*> ((const tchar*) result);
  9175. if (bigEndian)
  9176. {
  9177. for (int i = 0; i < numChars; ++i)
  9178. dst[i] = (tchar) swapIfLittleEndian (src[i]);
  9179. }
  9180. else
  9181. {
  9182. for (int i = 0; i < numChars; ++i)
  9183. dst[i] = (tchar) swapIfBigEndian (src[i]);
  9184. }
  9185. dst [numChars] = 0;
  9186. return result;
  9187. }
  9188. else
  9189. {
  9190. return String::fromUTF8 ((const uint8*) data, size);
  9191. }
  9192. }
  9193. const char* String::toUTF8() const throw()
  9194. {
  9195. if (isEmpty())
  9196. {
  9197. return (const char*) emptyCharString;
  9198. }
  9199. else
  9200. {
  9201. String* const mutableThis = const_cast <String*> (this);
  9202. mutableThis->dupeInternalIfMultiplyReferenced();
  9203. const int currentLen = CharacterFunctions::length (text->text) + 1;
  9204. const int utf8BytesNeeded = copyToUTF8 (0);
  9205. mutableThis->text = (InternalRefCountedStringHolder*)
  9206. juce_realloc (text, sizeof (InternalRefCountedStringHolder)
  9207. + (currentLen * sizeof (juce_wchar) + utf8BytesNeeded));
  9208. char* const otherCopy = (char*) (text->text + currentLen);
  9209. copyToUTF8 ((uint8*) otherCopy);
  9210. return otherCopy;
  9211. }
  9212. }
  9213. int String::copyToUTF8 (uint8* const buffer) const throw()
  9214. {
  9215. #if JUCE_STRINGS_ARE_UNICODE
  9216. int num = 0, index = 0;
  9217. for (;;)
  9218. {
  9219. const uint32 c = (uint32) text->text [index++];
  9220. if (c >= 0x80)
  9221. {
  9222. int numExtraBytes = 1;
  9223. if (c >= 0x800)
  9224. {
  9225. ++numExtraBytes;
  9226. if (c >= 0x10000)
  9227. {
  9228. ++numExtraBytes;
  9229. if (c >= 0x200000)
  9230. {
  9231. ++numExtraBytes;
  9232. if (c >= 0x4000000)
  9233. ++numExtraBytes;
  9234. }
  9235. }
  9236. }
  9237. if (buffer != 0)
  9238. {
  9239. buffer [num++] = (uint8) ((0xff << (7 - numExtraBytes)) | (c >> (numExtraBytes * 6)));
  9240. while (--numExtraBytes >= 0)
  9241. buffer [num++] = (uint8) (0x80 | (0x3f & (c >> (numExtraBytes * 6))));
  9242. }
  9243. else
  9244. {
  9245. num += numExtraBytes + 1;
  9246. }
  9247. }
  9248. else
  9249. {
  9250. if (buffer != 0)
  9251. buffer [num] = (uint8) c;
  9252. ++num;
  9253. }
  9254. if (c == 0)
  9255. break;
  9256. }
  9257. return num;
  9258. #else
  9259. const int numBytes = length() + 1;
  9260. if (buffer != 0)
  9261. copyToBuffer ((char*) buffer, numBytes);
  9262. return numBytes;
  9263. #endif
  9264. }
  9265. const String String::fromUTF8 (const uint8* const buffer, int bufferSizeBytes) throw()
  9266. {
  9267. if (buffer == 0)
  9268. return empty;
  9269. if (bufferSizeBytes < 0)
  9270. bufferSizeBytes = INT_MAX;
  9271. int numBytes;
  9272. for (numBytes = 0; numBytes < bufferSizeBytes; ++numBytes)
  9273. if (buffer [numBytes] == 0)
  9274. break;
  9275. String result (numBytes + 1, 0);
  9276. tchar* dest = result.text->text;
  9277. int i = 0;
  9278. while (i < numBytes)
  9279. {
  9280. const uint8 c = buffer [i++];
  9281. if ((c & 0x80) != 0)
  9282. {
  9283. int mask = 0x7f;
  9284. int bit = 0x40;
  9285. int numExtraValues = 0;
  9286. while (bit != 0 && (c & bit) != 0)
  9287. {
  9288. bit >>= 1;
  9289. mask >>= 1;
  9290. ++numExtraValues;
  9291. }
  9292. int n = (c & mask);
  9293. while (--numExtraValues >= 0 && i < bufferSizeBytes)
  9294. {
  9295. const uint8 c = buffer[i];
  9296. if ((c & 0xc0) != 0x80)
  9297. break;
  9298. n <<= 6;
  9299. n |= (c & 0x3f);
  9300. ++i;
  9301. }
  9302. *dest++ = (tchar) n;
  9303. }
  9304. else
  9305. {
  9306. *dest++ = (tchar) c;
  9307. }
  9308. }
  9309. *dest = 0;
  9310. return result;
  9311. }
  9312. END_JUCE_NAMESPACE
  9313. /********* End of inlined file: juce_String.cpp *********/
  9314. /********* Start of inlined file: juce_StringArray.cpp *********/
  9315. BEGIN_JUCE_NAMESPACE
  9316. StringArray::StringArray() throw()
  9317. {
  9318. }
  9319. StringArray::StringArray (const StringArray& other) throw()
  9320. {
  9321. addArray (other);
  9322. }
  9323. StringArray::StringArray (const juce_wchar** const strings,
  9324. const int numberOfStrings) throw()
  9325. {
  9326. for (int i = 0; i < numberOfStrings; ++i)
  9327. add (strings [i]);
  9328. }
  9329. StringArray::StringArray (const char** const strings,
  9330. const int numberOfStrings) throw()
  9331. {
  9332. for (int i = 0; i < numberOfStrings; ++i)
  9333. add (strings [i]);
  9334. }
  9335. StringArray::StringArray (const juce_wchar** const strings) throw()
  9336. {
  9337. int i = 0;
  9338. while (strings[i] != 0)
  9339. add (strings [i++]);
  9340. }
  9341. StringArray::StringArray (const char** const strings) throw()
  9342. {
  9343. int i = 0;
  9344. while (strings[i] != 0)
  9345. add (strings [i++]);
  9346. }
  9347. const StringArray& StringArray::operator= (const StringArray& other) throw()
  9348. {
  9349. if (this != &other)
  9350. {
  9351. clear();
  9352. addArray (other);
  9353. }
  9354. return *this;
  9355. }
  9356. StringArray::~StringArray() throw()
  9357. {
  9358. clear();
  9359. }
  9360. bool StringArray::operator== (const StringArray& other) const throw()
  9361. {
  9362. if (other.size() != size())
  9363. return false;
  9364. for (int i = size(); --i >= 0;)
  9365. {
  9366. if (*(String*) other.strings.getUnchecked(i)
  9367. != *(String*) strings.getUnchecked(i))
  9368. {
  9369. return false;
  9370. }
  9371. }
  9372. return true;
  9373. }
  9374. bool StringArray::operator!= (const StringArray& other) const throw()
  9375. {
  9376. return ! operator== (other);
  9377. }
  9378. void StringArray::clear() throw()
  9379. {
  9380. for (int i = size(); --i >= 0;)
  9381. {
  9382. String* const s = (String*) strings.getUnchecked(i);
  9383. delete s;
  9384. }
  9385. strings.clear();
  9386. }
  9387. const String& StringArray::operator[] (const int index) const throw()
  9388. {
  9389. if (((unsigned int) index) < (unsigned int) strings.size())
  9390. return *(const String*) (strings.getUnchecked (index));
  9391. return String::empty;
  9392. }
  9393. void StringArray::add (const String& newString) throw()
  9394. {
  9395. strings.add (new String (newString));
  9396. }
  9397. void StringArray::insert (const int index,
  9398. const String& newString) throw()
  9399. {
  9400. strings.insert (index, new String (newString));
  9401. }
  9402. void StringArray::addIfNotAlreadyThere (const String& newString,
  9403. const bool ignoreCase) throw()
  9404. {
  9405. if (! contains (newString, ignoreCase))
  9406. add (newString);
  9407. }
  9408. void StringArray::addArray (const StringArray& otherArray,
  9409. int startIndex,
  9410. int numElementsToAdd) throw()
  9411. {
  9412. if (startIndex < 0)
  9413. {
  9414. jassertfalse
  9415. startIndex = 0;
  9416. }
  9417. if (numElementsToAdd < 0 || startIndex + numElementsToAdd > otherArray.size())
  9418. numElementsToAdd = otherArray.size() - startIndex;
  9419. while (--numElementsToAdd >= 0)
  9420. strings.add (new String (*(const String*) otherArray.strings.getUnchecked (startIndex++)));
  9421. }
  9422. void StringArray::set (const int index,
  9423. const String& newString) throw()
  9424. {
  9425. String* const s = (String*) strings [index];
  9426. if (s != 0)
  9427. {
  9428. *s = newString;
  9429. }
  9430. else if (index >= 0)
  9431. {
  9432. add (newString);
  9433. }
  9434. }
  9435. bool StringArray::contains (const String& stringToLookFor,
  9436. const bool ignoreCase) const throw()
  9437. {
  9438. if (ignoreCase)
  9439. {
  9440. for (int i = size(); --i >= 0;)
  9441. if (stringToLookFor.equalsIgnoreCase (*(const String*)(strings.getUnchecked(i))))
  9442. return true;
  9443. }
  9444. else
  9445. {
  9446. for (int i = size(); --i >= 0;)
  9447. if (stringToLookFor == *(const String*)(strings.getUnchecked(i)))
  9448. return true;
  9449. }
  9450. return false;
  9451. }
  9452. int StringArray::indexOf (const String& stringToLookFor,
  9453. const bool ignoreCase,
  9454. int i) const throw()
  9455. {
  9456. if (i < 0)
  9457. i = 0;
  9458. const int numElements = size();
  9459. if (ignoreCase)
  9460. {
  9461. while (i < numElements)
  9462. {
  9463. if (stringToLookFor.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  9464. return i;
  9465. ++i;
  9466. }
  9467. }
  9468. else
  9469. {
  9470. while (i < numElements)
  9471. {
  9472. if (stringToLookFor == *(const String*) strings.getUnchecked (i))
  9473. return i;
  9474. ++i;
  9475. }
  9476. }
  9477. return -1;
  9478. }
  9479. void StringArray::remove (const int index) throw()
  9480. {
  9481. String* const s = (String*) strings [index];
  9482. if (s != 0)
  9483. {
  9484. strings.remove (index);
  9485. delete s;
  9486. }
  9487. }
  9488. void StringArray::removeString (const String& stringToRemove,
  9489. const bool ignoreCase) throw()
  9490. {
  9491. if (ignoreCase)
  9492. {
  9493. for (int i = size(); --i >= 0;)
  9494. if (stringToRemove.equalsIgnoreCase (*(const String*) strings.getUnchecked (i)))
  9495. remove (i);
  9496. }
  9497. else
  9498. {
  9499. for (int i = size(); --i >= 0;)
  9500. if (stringToRemove == *(const String*) strings.getUnchecked (i))
  9501. remove (i);
  9502. }
  9503. }
  9504. void StringArray::removeEmptyStrings (const bool removeWhitespaceStrings) throw()
  9505. {
  9506. if (removeWhitespaceStrings)
  9507. {
  9508. for (int i = size(); --i >= 0;)
  9509. if (((const String*) strings.getUnchecked(i))->trim().isEmpty())
  9510. remove (i);
  9511. }
  9512. else
  9513. {
  9514. for (int i = size(); --i >= 0;)
  9515. if (((const String*) strings.getUnchecked(i))->isEmpty())
  9516. remove (i);
  9517. }
  9518. }
  9519. void StringArray::trim() throw()
  9520. {
  9521. for (int i = size(); --i >= 0;)
  9522. {
  9523. String& s = *(String*) strings.getUnchecked(i);
  9524. s = s.trim();
  9525. }
  9526. }
  9527. class InternalStringArrayComparator
  9528. {
  9529. public:
  9530. static int compareElements (void* const first, void* const second) throw()
  9531. {
  9532. return ((const String*) first)->compare (*(const String*) second);
  9533. }
  9534. };
  9535. class InsensitiveInternalStringArrayComparator
  9536. {
  9537. public:
  9538. static int compareElements (void* const first, void* const second) throw()
  9539. {
  9540. return ((const String*) first)->compareIgnoreCase (*(const String*) second);
  9541. }
  9542. };
  9543. void StringArray::sort (const bool ignoreCase) throw()
  9544. {
  9545. if (ignoreCase)
  9546. {
  9547. InsensitiveInternalStringArrayComparator comp;
  9548. strings.sort (comp);
  9549. }
  9550. else
  9551. {
  9552. InternalStringArrayComparator comp;
  9553. strings.sort (comp);
  9554. }
  9555. }
  9556. void StringArray::move (const int currentIndex, int newIndex) throw()
  9557. {
  9558. strings.move (currentIndex, newIndex);
  9559. }
  9560. const String StringArray::joinIntoString (const String& separator,
  9561. int start,
  9562. int numberToJoin) const throw()
  9563. {
  9564. const int last = (numberToJoin < 0) ? size()
  9565. : jmin (size(), start + numberToJoin);
  9566. if (start < 0)
  9567. start = 0;
  9568. if (start >= last)
  9569. return String::empty;
  9570. if (start == last - 1)
  9571. return *(const String*) strings.getUnchecked (start);
  9572. const int separatorLen = separator.length();
  9573. int charsNeeded = separatorLen * (last - start - 1);
  9574. for (int i = start; i < last; ++i)
  9575. charsNeeded += ((const String*) strings.getUnchecked(i))->length();
  9576. String result;
  9577. result.preallocateStorage (charsNeeded);
  9578. tchar* dest = (tchar*) (const tchar*) result;
  9579. while (start < last)
  9580. {
  9581. const String& s = *(const String*) strings.getUnchecked (start);
  9582. const int len = s.length();
  9583. if (len > 0)
  9584. {
  9585. s.copyToBuffer (dest, len);
  9586. dest += len;
  9587. }
  9588. if (++start < last && separatorLen > 0)
  9589. {
  9590. separator.copyToBuffer (dest, separatorLen);
  9591. dest += separatorLen;
  9592. }
  9593. }
  9594. *dest = 0;
  9595. return result;
  9596. }
  9597. int StringArray::addTokens (const tchar* const text,
  9598. const bool preserveQuotedStrings) throw()
  9599. {
  9600. return addTokens (text,
  9601. T(" \n\r\t"),
  9602. preserveQuotedStrings ? T("\"") : 0);
  9603. }
  9604. int StringArray::addTokens (const tchar* const text,
  9605. const tchar* breakCharacters,
  9606. const tchar* quoteCharacters) throw()
  9607. {
  9608. int num = 0;
  9609. if (text != 0 && *text != 0)
  9610. {
  9611. if (breakCharacters == 0)
  9612. breakCharacters = T("");
  9613. if (quoteCharacters == 0)
  9614. quoteCharacters = T("");
  9615. bool insideQuotes = false;
  9616. tchar currentQuoteChar = 0;
  9617. int i = 0;
  9618. int tokenStart = 0;
  9619. for (;;)
  9620. {
  9621. const tchar c = text[i];
  9622. bool isBreak = (c == 0);
  9623. if (! (insideQuotes || isBreak))
  9624. {
  9625. const tchar* b = breakCharacters;
  9626. while (*b != 0)
  9627. {
  9628. if (*b++ == c)
  9629. {
  9630. isBreak = true;
  9631. break;
  9632. }
  9633. }
  9634. }
  9635. if (! isBreak)
  9636. {
  9637. bool isQuote = false;
  9638. const tchar* q = quoteCharacters;
  9639. while (*q != 0)
  9640. {
  9641. if (*q++ == c)
  9642. {
  9643. isQuote = true;
  9644. break;
  9645. }
  9646. }
  9647. if (isQuote)
  9648. {
  9649. if (insideQuotes)
  9650. {
  9651. // only break out of quotes-mode if we find a matching quote to the
  9652. // one that we opened with..
  9653. if (currentQuoteChar == c)
  9654. insideQuotes = false;
  9655. }
  9656. else
  9657. {
  9658. insideQuotes = true;
  9659. currentQuoteChar = c;
  9660. }
  9661. }
  9662. }
  9663. else
  9664. {
  9665. add (String (text + tokenStart, i - tokenStart));
  9666. ++num;
  9667. tokenStart = i + 1;
  9668. }
  9669. if (c == 0)
  9670. break;
  9671. ++i;
  9672. }
  9673. }
  9674. return num;
  9675. }
  9676. int StringArray::addLines (const tchar* text) throw()
  9677. {
  9678. int numLines = 0;
  9679. if (text != 0)
  9680. {
  9681. while (*text != 0)
  9682. {
  9683. const tchar* const startOfLine = text;
  9684. while (*text != 0)
  9685. {
  9686. if (*text == T('\r'))
  9687. {
  9688. ++text;
  9689. if (*text == T('\n'))
  9690. ++text;
  9691. break;
  9692. }
  9693. if (*text == T('\n'))
  9694. {
  9695. ++text;
  9696. break;
  9697. }
  9698. ++text;
  9699. }
  9700. const tchar* endOfLine = text;
  9701. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  9702. --endOfLine;
  9703. if (endOfLine > startOfLine && (*(endOfLine - 1) == T('\r') || *(endOfLine - 1) == T('\n')))
  9704. --endOfLine;
  9705. add (String (startOfLine, jmax (0, (int) (endOfLine - startOfLine))));
  9706. ++numLines;
  9707. }
  9708. }
  9709. return numLines;
  9710. }
  9711. void StringArray::removeDuplicates (const bool ignoreCase) throw()
  9712. {
  9713. for (int i = 0; i < size() - 1; ++i)
  9714. {
  9715. const String& s = *(String*) strings.getUnchecked(i);
  9716. int nextIndex = i + 1;
  9717. for (;;)
  9718. {
  9719. nextIndex = indexOf (s, ignoreCase, nextIndex);
  9720. if (nextIndex < 0)
  9721. break;
  9722. remove (nextIndex);
  9723. }
  9724. }
  9725. }
  9726. void StringArray::appendNumbersToDuplicates (const bool ignoreCase,
  9727. const bool appendNumberToFirstInstance,
  9728. const tchar* const preNumberString,
  9729. const tchar* const postNumberString) throw()
  9730. {
  9731. for (int i = 0; i < size() - 1; ++i)
  9732. {
  9733. String& s = *(String*) strings.getUnchecked(i);
  9734. int nextIndex = indexOf (s, ignoreCase, i + 1);
  9735. if (nextIndex >= 0)
  9736. {
  9737. const String original (s);
  9738. int number = 0;
  9739. if (appendNumberToFirstInstance)
  9740. s = original + preNumberString + String (++number) + postNumberString;
  9741. else
  9742. ++number;
  9743. while (nextIndex >= 0)
  9744. {
  9745. set (nextIndex, (*this)[nextIndex] + preNumberString + String (++number) + postNumberString);
  9746. nextIndex = indexOf (original, ignoreCase, nextIndex + 1);
  9747. }
  9748. }
  9749. }
  9750. }
  9751. void StringArray::minimiseStorageOverheads() throw()
  9752. {
  9753. strings.minimiseStorageOverheads();
  9754. }
  9755. END_JUCE_NAMESPACE
  9756. /********* End of inlined file: juce_StringArray.cpp *********/
  9757. /********* Start of inlined file: juce_StringPairArray.cpp *********/
  9758. BEGIN_JUCE_NAMESPACE
  9759. StringPairArray::StringPairArray (const bool ignoreCase_) throw()
  9760. : ignoreCase (ignoreCase_)
  9761. {
  9762. }
  9763. StringPairArray::StringPairArray (const StringPairArray& other) throw()
  9764. : keys (other.keys),
  9765. values (other.values),
  9766. ignoreCase (other.ignoreCase)
  9767. {
  9768. }
  9769. StringPairArray::~StringPairArray() throw()
  9770. {
  9771. }
  9772. const StringPairArray& StringPairArray::operator= (const StringPairArray& other) throw()
  9773. {
  9774. keys = other.keys;
  9775. values = other.values;
  9776. return *this;
  9777. }
  9778. bool StringPairArray::operator== (const StringPairArray& other) const throw()
  9779. {
  9780. for (int i = keys.size(); --i >= 0;)
  9781. if (other [keys[i]] != values[i])
  9782. return false;
  9783. return true;
  9784. }
  9785. bool StringPairArray::operator!= (const StringPairArray& other) const throw()
  9786. {
  9787. return ! operator== (other);
  9788. }
  9789. const String& StringPairArray::operator[] (const String& key) const throw()
  9790. {
  9791. return values [keys.indexOf (key, ignoreCase)];
  9792. }
  9793. const String StringPairArray::getValue (const String& key, const String& defaultReturnValue) const
  9794. {
  9795. const int i = keys.indexOf (key, ignoreCase);
  9796. if (i >= 0)
  9797. return values[i];
  9798. return defaultReturnValue;
  9799. }
  9800. void StringPairArray::set (const String& key,
  9801. const String& value) throw()
  9802. {
  9803. const int i = keys.indexOf (key, ignoreCase);
  9804. if (i >= 0)
  9805. {
  9806. values.set (i, value);
  9807. }
  9808. else
  9809. {
  9810. keys.add (key);
  9811. values.add (value);
  9812. }
  9813. }
  9814. void StringPairArray::addArray (const StringPairArray& other)
  9815. {
  9816. for (int i = 0; i < other.size(); ++i)
  9817. set (other.keys[i], other.values[i]);
  9818. }
  9819. void StringPairArray::clear() throw()
  9820. {
  9821. keys.clear();
  9822. values.clear();
  9823. }
  9824. void StringPairArray::remove (const String& key) throw()
  9825. {
  9826. remove (keys.indexOf (key, ignoreCase));
  9827. }
  9828. void StringPairArray::remove (const int index) throw()
  9829. {
  9830. keys.remove (index);
  9831. values.remove (index);
  9832. }
  9833. void StringPairArray::minimiseStorageOverheads() throw()
  9834. {
  9835. keys.minimiseStorageOverheads();
  9836. values.minimiseStorageOverheads();
  9837. }
  9838. END_JUCE_NAMESPACE
  9839. /********* End of inlined file: juce_StringPairArray.cpp *********/
  9840. /********* Start of inlined file: juce_XmlDocument.cpp *********/
  9841. BEGIN_JUCE_NAMESPACE
  9842. static bool isXmlIdentifierChar_Slow (const tchar c) throw()
  9843. {
  9844. return CharacterFunctions::isLetterOrDigit (c)
  9845. || c == T('_')
  9846. || c == T('-')
  9847. || c == T(':')
  9848. || c == T('.');
  9849. }
  9850. #define isXmlIdentifierChar(c) \
  9851. ((c > 0 && c <= 127) ? identifierLookupTable [(int) c] : isXmlIdentifierChar_Slow (c))
  9852. XmlDocument::XmlDocument (const String& documentText) throw()
  9853. : originalText (documentText),
  9854. inputSource (0)
  9855. {
  9856. }
  9857. XmlDocument::XmlDocument (const File& file)
  9858. {
  9859. inputSource = new FileInputSource (file);
  9860. }
  9861. XmlDocument::~XmlDocument() throw()
  9862. {
  9863. delete inputSource;
  9864. }
  9865. void XmlDocument::setInputSource (InputSource* const newSource) throw()
  9866. {
  9867. if (inputSource != newSource)
  9868. {
  9869. delete inputSource;
  9870. inputSource = newSource;
  9871. }
  9872. }
  9873. XmlElement* XmlDocument::getDocumentElement (const bool onlyReadOuterDocumentElement)
  9874. {
  9875. String textToParse (originalText);
  9876. if (textToParse.isEmpty() && inputSource != 0)
  9877. {
  9878. InputStream* const in = inputSource->createInputStream();
  9879. if (in != 0)
  9880. {
  9881. MemoryBlock data;
  9882. in->readIntoMemoryBlock (data, onlyReadOuterDocumentElement ? 8192 : -1);
  9883. delete in;
  9884. if (data.getSize() >= 2
  9885. && ((data[0] == (char)-2 && data[1] == (char)-1)
  9886. || (data[0] == (char)-1 && data[1] == (char)-2)))
  9887. {
  9888. textToParse = String::createStringFromData ((const char*) data.getData(), data.getSize());
  9889. }
  9890. else
  9891. {
  9892. textToParse = String::fromUTF8 ((const uint8*) data.getData(), data.getSize());
  9893. }
  9894. if (! onlyReadOuterDocumentElement)
  9895. originalText = textToParse;
  9896. }
  9897. }
  9898. input = textToParse;
  9899. lastError = String::empty;
  9900. errorOccurred = false;
  9901. outOfData = false;
  9902. needToLoadDTD = true;
  9903. for (int i = 0; i < 128; ++i)
  9904. identifierLookupTable[i] = isXmlIdentifierChar_Slow ((tchar) i);
  9905. if (textToParse.isEmpty())
  9906. {
  9907. lastError = "not enough input";
  9908. }
  9909. else
  9910. {
  9911. skipHeader();
  9912. if (input != 0)
  9913. {
  9914. XmlElement* const result = readNextElement (! onlyReadOuterDocumentElement);
  9915. if (errorOccurred)
  9916. delete result;
  9917. else
  9918. return result;
  9919. }
  9920. else
  9921. {
  9922. lastError = "incorrect xml header";
  9923. }
  9924. }
  9925. return 0;
  9926. }
  9927. const String& XmlDocument::getLastParseError() const throw()
  9928. {
  9929. return lastError;
  9930. }
  9931. void XmlDocument::setLastError (const String& desc, const bool carryOn) throw()
  9932. {
  9933. lastError = desc;
  9934. errorOccurred = ! carryOn;
  9935. }
  9936. const String XmlDocument::getFileContents (const String& filename) const
  9937. {
  9938. String result;
  9939. if (inputSource != 0)
  9940. {
  9941. InputStream* const in = inputSource->createInputStreamFor (filename.trim().unquoted());
  9942. if (in != 0)
  9943. {
  9944. result = in->readEntireStreamAsString();
  9945. delete in;
  9946. }
  9947. }
  9948. return result;
  9949. }
  9950. tchar XmlDocument::readNextChar() throw()
  9951. {
  9952. if (*input != 0)
  9953. {
  9954. return *input++;
  9955. }
  9956. else
  9957. {
  9958. outOfData = true;
  9959. return 0;
  9960. }
  9961. }
  9962. int XmlDocument::findNextTokenLength() throw()
  9963. {
  9964. int len = 0;
  9965. tchar c = *input;
  9966. while (isXmlIdentifierChar (c))
  9967. c = input [++len];
  9968. return len;
  9969. }
  9970. void XmlDocument::skipHeader() throw()
  9971. {
  9972. const tchar* const found = CharacterFunctions::find (input, T("<?xml"));
  9973. if (found != 0)
  9974. {
  9975. input = found;
  9976. input = CharacterFunctions::find (input, T("?>"));
  9977. if (input == 0)
  9978. return;
  9979. input += 2;
  9980. }
  9981. skipNextWhiteSpace();
  9982. const tchar* docType = CharacterFunctions::find (input, T("<!DOCTYPE"));
  9983. if (docType == 0)
  9984. return;
  9985. input = docType + 9;
  9986. int n = 1;
  9987. while (n > 0)
  9988. {
  9989. const tchar c = readNextChar();
  9990. if (outOfData)
  9991. return;
  9992. if (c == T('<'))
  9993. ++n;
  9994. else if (c == T('>'))
  9995. --n;
  9996. }
  9997. docType += 9;
  9998. dtdText = String (docType, (int) (input - (docType + 1))).trim();
  9999. }
  10000. void XmlDocument::skipNextWhiteSpace() throw()
  10001. {
  10002. for (;;)
  10003. {
  10004. tchar c = *input;
  10005. while (CharacterFunctions::isWhitespace (c))
  10006. c = *++input;
  10007. if (c == 0)
  10008. {
  10009. outOfData = true;
  10010. break;
  10011. }
  10012. else if (c == T('<'))
  10013. {
  10014. if (input[1] == T('!')
  10015. && input[2] == T('-')
  10016. && input[3] == T('-'))
  10017. {
  10018. const tchar* const closeComment = CharacterFunctions::find (input, T("-->"));
  10019. if (closeComment == 0)
  10020. {
  10021. outOfData = true;
  10022. break;
  10023. }
  10024. input = closeComment + 3;
  10025. continue;
  10026. }
  10027. else if (input[1] == T('?'))
  10028. {
  10029. const tchar* const closeBracket = CharacterFunctions::find (input, T("?>"));
  10030. if (closeBracket == 0)
  10031. {
  10032. outOfData = true;
  10033. break;
  10034. }
  10035. input = closeBracket + 2;
  10036. continue;
  10037. }
  10038. }
  10039. break;
  10040. }
  10041. }
  10042. void XmlDocument::readQuotedString (String& result) throw()
  10043. {
  10044. const tchar quote = readNextChar();
  10045. while (! outOfData)
  10046. {
  10047. const tchar character = readNextChar();
  10048. if (character == quote)
  10049. break;
  10050. if (character == T('&'))
  10051. {
  10052. --input;
  10053. readEntity (result);
  10054. }
  10055. else
  10056. {
  10057. --input;
  10058. const tchar* const start = input;
  10059. for (;;)
  10060. {
  10061. const tchar character = *input;
  10062. if (character == quote)
  10063. {
  10064. result.append (start, (int) (input - start));
  10065. ++input;
  10066. return;
  10067. }
  10068. else if (character == T('&'))
  10069. {
  10070. result.append (start, (int) (input - start));
  10071. break;
  10072. }
  10073. else if (character == 0)
  10074. {
  10075. outOfData = true;
  10076. setLastError ("unmatched quotes", false);
  10077. break;
  10078. }
  10079. ++input;
  10080. }
  10081. }
  10082. }
  10083. }
  10084. XmlElement* XmlDocument::readNextElement (const bool alsoParseSubElements) throw()
  10085. {
  10086. XmlElement* node = 0;
  10087. skipNextWhiteSpace();
  10088. if (outOfData)
  10089. return 0;
  10090. input = CharacterFunctions::find (input, T("<"));
  10091. if (input != 0)
  10092. {
  10093. ++input;
  10094. int tagLen = findNextTokenLength();
  10095. if (tagLen == 0)
  10096. {
  10097. // no tag name - but allow for a gap after the '<' before giving an error
  10098. skipNextWhiteSpace();
  10099. tagLen = findNextTokenLength();
  10100. if (tagLen == 0)
  10101. {
  10102. setLastError ("tag name missing", false);
  10103. return node;
  10104. }
  10105. }
  10106. node = new XmlElement (input, tagLen);
  10107. input += tagLen;
  10108. XmlElement::XmlAttributeNode* lastAttribute = 0;
  10109. // look for attributes
  10110. for (;;)
  10111. {
  10112. skipNextWhiteSpace();
  10113. const tchar c = *input;
  10114. // empty tag..
  10115. if (c == T('/') && input[1] == T('>'))
  10116. {
  10117. input += 2;
  10118. break;
  10119. }
  10120. // parse the guts of the element..
  10121. if (c == T('>'))
  10122. {
  10123. ++input;
  10124. skipNextWhiteSpace();
  10125. if (alsoParseSubElements)
  10126. readChildElements (node);
  10127. break;
  10128. }
  10129. // get an attribute..
  10130. if (isXmlIdentifierChar (c))
  10131. {
  10132. const int attNameLen = findNextTokenLength();
  10133. if (attNameLen > 0)
  10134. {
  10135. const tchar* attNameStart = input;
  10136. input += attNameLen;
  10137. skipNextWhiteSpace();
  10138. if (readNextChar() == T('='))
  10139. {
  10140. skipNextWhiteSpace();
  10141. const tchar c = *input;
  10142. if (c == T('"') || c == T('\''))
  10143. {
  10144. XmlElement::XmlAttributeNode* const newAtt
  10145. = new XmlElement::XmlAttributeNode (String (attNameStart, attNameLen),
  10146. String::empty);
  10147. readQuotedString (newAtt->value);
  10148. if (lastAttribute == 0)
  10149. node->attributes = newAtt;
  10150. else
  10151. lastAttribute->next = newAtt;
  10152. lastAttribute = newAtt;
  10153. continue;
  10154. }
  10155. }
  10156. }
  10157. }
  10158. else
  10159. {
  10160. if (! outOfData)
  10161. setLastError ("illegal character found in " + node->getTagName() + ": '" + c + "'", false);
  10162. }
  10163. break;
  10164. }
  10165. }
  10166. return node;
  10167. }
  10168. void XmlDocument::readChildElements (XmlElement* parent) throw()
  10169. {
  10170. XmlElement* lastChildNode = 0;
  10171. for (;;)
  10172. {
  10173. skipNextWhiteSpace();
  10174. if (outOfData)
  10175. {
  10176. setLastError ("unmatched tags", false);
  10177. break;
  10178. }
  10179. if (*input == T('<'))
  10180. {
  10181. if (input[1] == T('/'))
  10182. {
  10183. // our close tag..
  10184. input = CharacterFunctions::find (input, T(">"));
  10185. ++input;
  10186. break;
  10187. }
  10188. else if (input[1] == T('!')
  10189. && input[2] == T('[')
  10190. && input[3] == T('C')
  10191. && input[4] == T('D')
  10192. && input[5] == T('A')
  10193. && input[6] == T('T')
  10194. && input[7] == T('A')
  10195. && input[8] == T('['))
  10196. {
  10197. input += 9;
  10198. const tchar* const inputStart = input;
  10199. int len = 0;
  10200. for (;;)
  10201. {
  10202. if (*input == 0)
  10203. {
  10204. setLastError ("unterminated CDATA section", false);
  10205. outOfData = true;
  10206. break;
  10207. }
  10208. else if (input[0] == T(']')
  10209. && input[1] == T(']')
  10210. && input[2] == T('>'))
  10211. {
  10212. input += 3;
  10213. break;
  10214. }
  10215. ++input;
  10216. ++len;
  10217. }
  10218. XmlElement* const e = new XmlElement ((int) 0);
  10219. e->setText (String (inputStart, len));
  10220. if (lastChildNode != 0)
  10221. lastChildNode->nextElement = e;
  10222. else
  10223. parent->addChildElement (e);
  10224. lastChildNode = e;
  10225. }
  10226. else
  10227. {
  10228. // this is some other element, so parse and add it..
  10229. XmlElement* const n = readNextElement (true);
  10230. if (n != 0)
  10231. {
  10232. if (lastChildNode == 0)
  10233. parent->addChildElement (n);
  10234. else
  10235. lastChildNode->nextElement = n;
  10236. lastChildNode = n;
  10237. }
  10238. else
  10239. {
  10240. return;
  10241. }
  10242. }
  10243. }
  10244. else
  10245. {
  10246. // read character block..
  10247. XmlElement* const e = new XmlElement ((int)0);
  10248. if (lastChildNode != 0)
  10249. lastChildNode->nextElement = e;
  10250. else
  10251. parent->addChildElement (e);
  10252. lastChildNode = e;
  10253. String textElementContent;
  10254. for (;;)
  10255. {
  10256. const tchar c = *input;
  10257. if (c == T('<'))
  10258. break;
  10259. if (c == 0)
  10260. {
  10261. setLastError ("unmatched tags", false);
  10262. outOfData = true;
  10263. return;
  10264. }
  10265. if (c == T('&'))
  10266. {
  10267. String entity;
  10268. readEntity (entity);
  10269. if (entity.startsWithChar (T('<')) && entity [1] != 0)
  10270. {
  10271. const tchar* const oldInput = input;
  10272. const bool oldOutOfData = outOfData;
  10273. input = (const tchar*) entity;
  10274. outOfData = false;
  10275. for (;;)
  10276. {
  10277. XmlElement* const n = readNextElement (true);
  10278. if (n == 0)
  10279. break;
  10280. if (lastChildNode == 0)
  10281. parent->addChildElement (n);
  10282. else
  10283. lastChildNode->nextElement = n;
  10284. lastChildNode = n;
  10285. }
  10286. input = oldInput;
  10287. outOfData = oldOutOfData;
  10288. }
  10289. else
  10290. {
  10291. textElementContent += entity;
  10292. }
  10293. }
  10294. else
  10295. {
  10296. const tchar* start = input;
  10297. int len = 0;
  10298. for (;;)
  10299. {
  10300. const tchar c = *input;
  10301. if (c == T('<') || c == T('&'))
  10302. {
  10303. break;
  10304. }
  10305. else if (c == 0)
  10306. {
  10307. setLastError ("unmatched tags", false);
  10308. outOfData = true;
  10309. return;
  10310. }
  10311. ++input;
  10312. ++len;
  10313. }
  10314. textElementContent.append (start, len);
  10315. }
  10316. }
  10317. textElementContent = textElementContent.trim();
  10318. if (textElementContent.isNotEmpty())
  10319. e->setText (textElementContent);
  10320. }
  10321. }
  10322. }
  10323. void XmlDocument::readEntity (String& result) throw()
  10324. {
  10325. // skip over the ampersand
  10326. ++input;
  10327. if (CharacterFunctions::compareIgnoreCase (input, T("amp;"), 4) == 0)
  10328. {
  10329. input += 4;
  10330. result += T("&");
  10331. }
  10332. else if (CharacterFunctions::compareIgnoreCase (input, T("quot;"), 5) == 0)
  10333. {
  10334. input += 5;
  10335. result += T("\"");
  10336. }
  10337. else if (CharacterFunctions::compareIgnoreCase (input, T("apos;"), 5) == 0)
  10338. {
  10339. input += 5;
  10340. result += T("\'");
  10341. }
  10342. else if (CharacterFunctions::compareIgnoreCase (input, T("lt;"), 3) == 0)
  10343. {
  10344. input += 3;
  10345. result += T("<");
  10346. }
  10347. else if (CharacterFunctions::compareIgnoreCase (input, T("gt;"), 3) == 0)
  10348. {
  10349. input += 3;
  10350. result += T(">");
  10351. }
  10352. else if (*input == T('#'))
  10353. {
  10354. int charCode = 0;
  10355. ++input;
  10356. if (*input == T('x') || *input == T('X'))
  10357. {
  10358. ++input;
  10359. int numChars = 0;
  10360. while (input[0] != T(';'))
  10361. {
  10362. const int hexValue = CharacterFunctions::getHexDigitValue (input[0]);
  10363. if (hexValue < 0 || ++numChars > 8)
  10364. {
  10365. setLastError ("illegal escape sequence", true);
  10366. break;
  10367. }
  10368. charCode = (charCode << 4) | hexValue;
  10369. ++input;
  10370. }
  10371. ++input;
  10372. }
  10373. else if (input[0] >= T('0') && input[0] <= T('9'))
  10374. {
  10375. int numChars = 0;
  10376. while (input[0] != T(';'))
  10377. {
  10378. if (++numChars > 12)
  10379. {
  10380. setLastError ("illegal escape sequence", true);
  10381. break;
  10382. }
  10383. charCode = charCode * 10 + (input[0] - T('0'));
  10384. ++input;
  10385. }
  10386. ++input;
  10387. }
  10388. else
  10389. {
  10390. setLastError ("illegal escape sequence", true);
  10391. result += T("&");
  10392. return;
  10393. }
  10394. result << (tchar) charCode;
  10395. }
  10396. else
  10397. {
  10398. const tchar* const entityNameStart = input;
  10399. const tchar* const closingSemiColon = CharacterFunctions::find (input, T(";"));
  10400. if (closingSemiColon == 0)
  10401. {
  10402. outOfData = true;
  10403. result += T("&");
  10404. }
  10405. else
  10406. {
  10407. input = closingSemiColon + 1;
  10408. result += expandExternalEntity (String (entityNameStart,
  10409. (int) (closingSemiColon - entityNameStart)));
  10410. }
  10411. }
  10412. }
  10413. const String XmlDocument::expandEntity (const String& ent)
  10414. {
  10415. if (ent.equalsIgnoreCase (T("amp")))
  10416. {
  10417. return T("&");
  10418. }
  10419. else if (ent.equalsIgnoreCase (T("quot")))
  10420. {
  10421. return T("\"");
  10422. }
  10423. else if (ent.equalsIgnoreCase (T("apos")))
  10424. {
  10425. return T("\'");
  10426. }
  10427. else if (ent.equalsIgnoreCase (T("lt")))
  10428. {
  10429. return T("<");
  10430. }
  10431. else if (ent.equalsIgnoreCase (T("gt")))
  10432. {
  10433. return T(">");
  10434. }
  10435. else if (ent[0] == T('#'))
  10436. {
  10437. if (ent[1] == T('x') || ent[1] == T('X'))
  10438. {
  10439. return String::charToString ((tchar) ent.substring (2).getHexValue32());
  10440. }
  10441. else if (ent[1] >= T('0') && ent[1] <= T('9'))
  10442. {
  10443. return String::charToString ((tchar) ent.substring (1).getIntValue());
  10444. }
  10445. setLastError ("illegal escape sequence", false);
  10446. return T("&");
  10447. }
  10448. else
  10449. {
  10450. return expandExternalEntity (ent);
  10451. }
  10452. }
  10453. const String XmlDocument::expandExternalEntity (const String& entity)
  10454. {
  10455. if (needToLoadDTD)
  10456. {
  10457. if (dtdText.isNotEmpty())
  10458. {
  10459. while (dtdText.endsWithChar (T('>')))
  10460. dtdText = dtdText.dropLastCharacters (1);
  10461. tokenisedDTD.addTokens (dtdText, true);
  10462. if (tokenisedDTD [tokenisedDTD.size() - 2].equalsIgnoreCase (T("system"))
  10463. && tokenisedDTD [tokenisedDTD.size() - 1].isQuotedString())
  10464. {
  10465. const String fn (tokenisedDTD [tokenisedDTD.size() - 1]);
  10466. tokenisedDTD.clear();
  10467. tokenisedDTD.addTokens (getFileContents (fn), true);
  10468. }
  10469. else
  10470. {
  10471. tokenisedDTD.clear();
  10472. const int openBracket = dtdText.indexOfChar (T('['));
  10473. if (openBracket > 0)
  10474. {
  10475. const int closeBracket = dtdText.lastIndexOfChar (T(']'));
  10476. if (closeBracket > openBracket)
  10477. tokenisedDTD.addTokens (dtdText.substring (openBracket + 1,
  10478. closeBracket), true);
  10479. }
  10480. }
  10481. for (int i = tokenisedDTD.size(); --i >= 0;)
  10482. {
  10483. if (tokenisedDTD[i].startsWithChar (T('%'))
  10484. && tokenisedDTD[i].endsWithChar (T(';')))
  10485. {
  10486. const String parsed (getParameterEntity (tokenisedDTD[i].substring (1, tokenisedDTD[i].length() - 1)));
  10487. StringArray newToks;
  10488. newToks.addTokens (parsed, true);
  10489. tokenisedDTD.remove (i);
  10490. for (int j = newToks.size(); --j >= 0;)
  10491. tokenisedDTD.insert (i, newToks[j]);
  10492. }
  10493. }
  10494. }
  10495. needToLoadDTD = false;
  10496. }
  10497. for (int i = 0; i < tokenisedDTD.size(); ++i)
  10498. {
  10499. if (tokenisedDTD[i] == entity)
  10500. {
  10501. if (tokenisedDTD[i - 1].equalsIgnoreCase (T("<!entity")))
  10502. {
  10503. String ent (tokenisedDTD [i + 1]);
  10504. while (ent.endsWithChar (T('>')))
  10505. ent = ent.dropLastCharacters (1);
  10506. ent = ent.trim().unquoted();
  10507. // check for sub-entities..
  10508. int ampersand = ent.indexOfChar (T('&'));
  10509. while (ampersand >= 0)
  10510. {
  10511. const int semiColon = ent.indexOf (i + 1, T(";"));
  10512. if (semiColon < 0)
  10513. {
  10514. setLastError ("entity without terminating semi-colon", false);
  10515. break;
  10516. }
  10517. const String resolved (expandEntity (ent.substring (i + 1, semiColon)));
  10518. ent = ent.substring (0, ampersand)
  10519. + resolved
  10520. + ent.substring (semiColon + 1);
  10521. ampersand = ent.indexOfChar (semiColon + 1, T('&'));
  10522. }
  10523. return ent;
  10524. }
  10525. }
  10526. }
  10527. setLastError ("unknown entity", true);
  10528. return entity;
  10529. }
  10530. const String XmlDocument::getParameterEntity (const String& entity)
  10531. {
  10532. for (int i = 0; i < tokenisedDTD.size(); ++i)
  10533. {
  10534. if (tokenisedDTD[i] == entity)
  10535. {
  10536. if (tokenisedDTD [i - 1] == T("%")
  10537. && tokenisedDTD [i - 2].equalsIgnoreCase (T("<!entity")))
  10538. {
  10539. String ent (tokenisedDTD [i + 1]);
  10540. while (ent.endsWithChar (T('>')))
  10541. ent = ent.dropLastCharacters (1);
  10542. if (ent.equalsIgnoreCase (T("system")))
  10543. {
  10544. String filename (tokenisedDTD [i + 2]);
  10545. while (filename.endsWithChar (T('>')))
  10546. filename = filename.dropLastCharacters (1);
  10547. return getFileContents (filename);
  10548. }
  10549. else
  10550. {
  10551. return ent.trim().unquoted();
  10552. }
  10553. }
  10554. }
  10555. }
  10556. return entity;
  10557. }
  10558. END_JUCE_NAMESPACE
  10559. /********* End of inlined file: juce_XmlDocument.cpp *********/
  10560. /********* Start of inlined file: juce_XmlElement.cpp *********/
  10561. BEGIN_JUCE_NAMESPACE
  10562. XmlElement::XmlAttributeNode::XmlAttributeNode (const XmlAttributeNode& other) throw()
  10563. : name (other.name),
  10564. value (other.value),
  10565. next (0)
  10566. {
  10567. }
  10568. XmlElement::XmlAttributeNode::XmlAttributeNode (const String& name_,
  10569. const String& value_) throw()
  10570. : name (name_),
  10571. value (value_),
  10572. next (0)
  10573. {
  10574. }
  10575. XmlElement::XmlElement (const String& tagName_) throw()
  10576. : tagName (tagName_),
  10577. firstChildElement (0),
  10578. nextElement (0),
  10579. attributes (0)
  10580. {
  10581. // the tag name mustn't be empty, or it'll look like a text element!
  10582. jassert (tagName_.trim().isNotEmpty())
  10583. }
  10584. XmlElement::XmlElement (int /*dummy*/) throw()
  10585. : firstChildElement (0),
  10586. nextElement (0),
  10587. attributes (0)
  10588. {
  10589. }
  10590. XmlElement::XmlElement (const tchar* const tagName_,
  10591. const int nameLen) throw()
  10592. : tagName (tagName_, nameLen),
  10593. firstChildElement (0),
  10594. nextElement (0),
  10595. attributes (0)
  10596. {
  10597. }
  10598. XmlElement::XmlElement (const XmlElement& other) throw()
  10599. : tagName (other.tagName),
  10600. firstChildElement (0),
  10601. nextElement (0),
  10602. attributes (0)
  10603. {
  10604. copyChildrenAndAttributesFrom (other);
  10605. }
  10606. const XmlElement& XmlElement::operator= (const XmlElement& other) throw()
  10607. {
  10608. if (this != &other)
  10609. {
  10610. removeAllAttributes();
  10611. deleteAllChildElements();
  10612. tagName = other.tagName;
  10613. copyChildrenAndAttributesFrom (other);
  10614. }
  10615. return *this;
  10616. }
  10617. void XmlElement::copyChildrenAndAttributesFrom (const XmlElement& other) throw()
  10618. {
  10619. XmlElement* child = other.firstChildElement;
  10620. XmlElement* lastChild = 0;
  10621. while (child != 0)
  10622. {
  10623. XmlElement* const copiedChild = new XmlElement (*child);
  10624. if (lastChild != 0)
  10625. lastChild->nextElement = copiedChild;
  10626. else
  10627. firstChildElement = copiedChild;
  10628. lastChild = copiedChild;
  10629. child = child->nextElement;
  10630. }
  10631. const XmlAttributeNode* att = other.attributes;
  10632. XmlAttributeNode* lastAtt = 0;
  10633. while (att != 0)
  10634. {
  10635. XmlAttributeNode* const newAtt = new XmlAttributeNode (*att);
  10636. if (lastAtt != 0)
  10637. lastAtt->next = newAtt;
  10638. else
  10639. attributes = newAtt;
  10640. lastAtt = newAtt;
  10641. att = att->next;
  10642. }
  10643. }
  10644. XmlElement::~XmlElement() throw()
  10645. {
  10646. XmlElement* child = firstChildElement;
  10647. while (child != 0)
  10648. {
  10649. XmlElement* const nextChild = child->nextElement;
  10650. delete child;
  10651. child = nextChild;
  10652. }
  10653. XmlAttributeNode* att = attributes;
  10654. while (att != 0)
  10655. {
  10656. XmlAttributeNode* const nextAtt = att->next;
  10657. delete att;
  10658. att = nextAtt;
  10659. }
  10660. }
  10661. static bool isLegalXmlChar (const juce_wchar character)
  10662. {
  10663. if ((character >= 'a' && character <= 'z')
  10664. || (character >= 'A' && character <= 'Z')
  10665. || (character >= '0' && character <= '9'))
  10666. return true;
  10667. const char* t = " .,;:-()_+=?!'#@[]/\\*%~{}";
  10668. do
  10669. {
  10670. if (((juce_wchar) (uint8) *t) == character)
  10671. return true;
  10672. }
  10673. while (*++t != 0);
  10674. return false;
  10675. }
  10676. static void escapeIllegalXmlChars (OutputStream& outputStream,
  10677. const String& text,
  10678. const bool changeNewLines) throw()
  10679. {
  10680. const juce_wchar* t = (const juce_wchar*) text;
  10681. for (;;)
  10682. {
  10683. const juce_wchar character = *t++;
  10684. if (character == 0)
  10685. {
  10686. break;
  10687. }
  10688. else if (isLegalXmlChar (character))
  10689. {
  10690. outputStream.writeByte ((char) character);
  10691. }
  10692. else
  10693. {
  10694. switch (character)
  10695. {
  10696. case '&':
  10697. outputStream.write ("&amp;", 5);
  10698. break;
  10699. case '"':
  10700. outputStream.write ("&quot;", 6);
  10701. break;
  10702. case '>':
  10703. outputStream.write ("&gt;", 4);
  10704. break;
  10705. case '<':
  10706. outputStream.write ("&lt;", 4);
  10707. break;
  10708. case '\n':
  10709. if (changeNewLines)
  10710. outputStream.write ("&#10;", 5);
  10711. else
  10712. outputStream.writeByte ((char) character);
  10713. break;
  10714. case '\r':
  10715. if (changeNewLines)
  10716. outputStream.write ("&#13;", 5);
  10717. else
  10718. outputStream.writeByte ((char) character);
  10719. break;
  10720. default:
  10721. {
  10722. String encoded (T("&#"));
  10723. encoded << String ((int) (unsigned int) character).trim()
  10724. << T(';');
  10725. outputStream.write ((const char*) encoded, encoded.length());
  10726. }
  10727. }
  10728. }
  10729. }
  10730. }
  10731. static void writeSpaces (OutputStream& out, int numSpaces) throw()
  10732. {
  10733. if (numSpaces > 0)
  10734. {
  10735. const char* const blanks = " ";
  10736. const int blankSize = (int) sizeof (blanks) - 1;
  10737. while (numSpaces > blankSize)
  10738. {
  10739. out.write (blanks, blankSize);
  10740. numSpaces -= blankSize;
  10741. }
  10742. out.write (blanks, numSpaces);
  10743. }
  10744. }
  10745. void XmlElement::writeElementAsText (OutputStream& outputStream,
  10746. const int indentationLevel,
  10747. const int lineWrapLength) const throw()
  10748. {
  10749. writeSpaces (outputStream, indentationLevel);
  10750. if (! isTextElement())
  10751. {
  10752. outputStream.writeByte ('<');
  10753. const int nameLen = tagName.length();
  10754. outputStream.write ((const char*) tagName, nameLen);
  10755. const int attIndent = indentationLevel + nameLen + 1;
  10756. int lineLen = 0;
  10757. const XmlAttributeNode* att = attributes;
  10758. while (att != 0)
  10759. {
  10760. if (lineLen > lineWrapLength && indentationLevel >= 0)
  10761. {
  10762. outputStream.write ("\r\n", 2);
  10763. writeSpaces (outputStream, attIndent);
  10764. lineLen = 0;
  10765. }
  10766. const int attNameLen = att->name.length();
  10767. outputStream.writeByte (' ');
  10768. outputStream.write ((const char*) (att->name), attNameLen);
  10769. outputStream.write ("=\"", 2);
  10770. escapeIllegalXmlChars (outputStream, att->value, true);
  10771. outputStream.writeByte ('"');
  10772. lineLen += 4 + attNameLen + att->value.length();
  10773. att = att->next;
  10774. }
  10775. if (firstChildElement != 0)
  10776. {
  10777. XmlElement* child = firstChildElement;
  10778. if (child->nextElement == 0 && child->isTextElement())
  10779. {
  10780. outputStream.writeByte ('>');
  10781. escapeIllegalXmlChars (outputStream, child->getText(), false);
  10782. }
  10783. else
  10784. {
  10785. if (indentationLevel >= 0)
  10786. outputStream.write (">\r\n", 3);
  10787. else
  10788. outputStream.writeByte ('>');
  10789. bool lastWasTextNode = false;
  10790. while (child != 0)
  10791. {
  10792. if (child->isTextElement())
  10793. {
  10794. if ((! lastWasTextNode) && (indentationLevel >= 0))
  10795. writeSpaces (outputStream, indentationLevel + 2);
  10796. escapeIllegalXmlChars (outputStream, child->getText(), false);
  10797. lastWasTextNode = true;
  10798. }
  10799. else
  10800. {
  10801. if (indentationLevel >= 0)
  10802. {
  10803. if (lastWasTextNode)
  10804. outputStream.write ("\r\n", 2);
  10805. child->writeElementAsText (outputStream, indentationLevel + 2, lineWrapLength);
  10806. }
  10807. else
  10808. {
  10809. child->writeElementAsText (outputStream, indentationLevel, lineWrapLength);
  10810. }
  10811. lastWasTextNode = false;
  10812. }
  10813. child = child->nextElement;
  10814. }
  10815. if (indentationLevel >= 0)
  10816. {
  10817. if (lastWasTextNode)
  10818. outputStream.write ("\r\n", 2);
  10819. writeSpaces (outputStream, indentationLevel);
  10820. }
  10821. }
  10822. outputStream.write ("</", 2);
  10823. outputStream.write ((const char*) tagName, nameLen);
  10824. if (indentationLevel >= 0)
  10825. outputStream.write (">\r\n", 3);
  10826. else
  10827. outputStream.writeByte ('>');
  10828. }
  10829. else
  10830. {
  10831. if (indentationLevel >= 0)
  10832. outputStream.write ("/>\r\n", 4);
  10833. else
  10834. outputStream.write ("/>", 2);
  10835. }
  10836. }
  10837. else
  10838. {
  10839. if (indentationLevel >= 0)
  10840. writeSpaces (outputStream, indentationLevel + 2);
  10841. escapeIllegalXmlChars (outputStream, getText(), false);
  10842. }
  10843. }
  10844. const String XmlElement::createDocument (const String& dtd,
  10845. const bool allOnOneLine,
  10846. const bool includeXmlHeader,
  10847. const tchar* const encoding,
  10848. const int lineWrapLength) const throw()
  10849. {
  10850. String doc;
  10851. doc.preallocateStorage (1024);
  10852. if (includeXmlHeader)
  10853. {
  10854. doc << "<?xml version=\"1.0\" encoding=\""
  10855. << encoding;
  10856. if (allOnOneLine)
  10857. doc += "\"?> ";
  10858. else
  10859. doc += "\"?>\n\n";
  10860. }
  10861. if (dtd.isNotEmpty())
  10862. {
  10863. if (allOnOneLine)
  10864. doc << dtd << " ";
  10865. else
  10866. doc << dtd << "\r\n";
  10867. }
  10868. MemoryOutputStream mem (2048, 4096);
  10869. writeElementAsText (mem, allOnOneLine ? -1 : 0, lineWrapLength);
  10870. return doc + String (mem.getData(),
  10871. mem.getDataSize());
  10872. }
  10873. bool XmlElement::writeToFile (const File& f,
  10874. const String& dtd,
  10875. const tchar* const encoding,
  10876. const int lineWrapLength) const throw()
  10877. {
  10878. if (f.hasWriteAccess())
  10879. {
  10880. const File tempFile (f.getNonexistentSibling());
  10881. FileOutputStream* const out = tempFile.createOutputStream();
  10882. if (out != 0)
  10883. {
  10884. *out << "<?xml version=\"1.0\" encoding=\"" << encoding << "\"?>\r\n\r\n"
  10885. << dtd << "\r\n";
  10886. writeElementAsText (*out, 0, lineWrapLength);
  10887. delete out;
  10888. if (tempFile.moveFileTo (f))
  10889. return true;
  10890. tempFile.deleteFile();
  10891. }
  10892. }
  10893. return false;
  10894. }
  10895. bool XmlElement::hasTagName (const tchar* const tagNameWanted) const throw()
  10896. {
  10897. #ifdef JUCE_DEBUG
  10898. // if debugging, check that the case is actually the same, because
  10899. // valid xml is case-sensitive, and although this lets it pass, it's
  10900. // better not to..
  10901. if (tagName.equalsIgnoreCase (tagNameWanted))
  10902. {
  10903. jassert (tagName == tagNameWanted);
  10904. return true;
  10905. }
  10906. else
  10907. {
  10908. return false;
  10909. }
  10910. #else
  10911. return tagName.equalsIgnoreCase (tagNameWanted);
  10912. #endif
  10913. }
  10914. XmlElement* XmlElement::getNextElementWithTagName (const tchar* const requiredTagName) const
  10915. {
  10916. XmlElement* e = nextElement;
  10917. while (e != 0 && ! e->hasTagName (requiredTagName))
  10918. e = e->nextElement;
  10919. return e;
  10920. }
  10921. int XmlElement::getNumAttributes() const throw()
  10922. {
  10923. const XmlAttributeNode* att = attributes;
  10924. int count = 0;
  10925. while (att != 0)
  10926. {
  10927. att = att->next;
  10928. ++count;
  10929. }
  10930. return count;
  10931. }
  10932. const String& XmlElement::getAttributeName (const int index) const throw()
  10933. {
  10934. const XmlAttributeNode* att = attributes;
  10935. int count = 0;
  10936. while (att != 0)
  10937. {
  10938. if (count == index)
  10939. return att->name;
  10940. att = att->next;
  10941. ++count;
  10942. }
  10943. return String::empty;
  10944. }
  10945. const String& XmlElement::getAttributeValue (const int index) const throw()
  10946. {
  10947. const XmlAttributeNode* att = attributes;
  10948. int count = 0;
  10949. while (att != 0)
  10950. {
  10951. if (count == index)
  10952. return att->value;
  10953. att = att->next;
  10954. ++count;
  10955. }
  10956. return String::empty;
  10957. }
  10958. bool XmlElement::hasAttribute (const tchar* const attributeName) const throw()
  10959. {
  10960. const XmlAttributeNode* att = attributes;
  10961. while (att != 0)
  10962. {
  10963. if (att->name.equalsIgnoreCase (attributeName))
  10964. return true;
  10965. att = att->next;
  10966. }
  10967. return false;
  10968. }
  10969. const String XmlElement::getStringAttribute (const tchar* const attributeName,
  10970. const tchar* const defaultReturnValue) const throw()
  10971. {
  10972. const XmlAttributeNode* att = attributes;
  10973. while (att != 0)
  10974. {
  10975. if (att->name.equalsIgnoreCase (attributeName))
  10976. return att->value;
  10977. att = att->next;
  10978. }
  10979. return defaultReturnValue;
  10980. }
  10981. int XmlElement::getIntAttribute (const tchar* const attributeName,
  10982. const int defaultReturnValue) const throw()
  10983. {
  10984. const XmlAttributeNode* att = attributes;
  10985. while (att != 0)
  10986. {
  10987. if (att->name.equalsIgnoreCase (attributeName))
  10988. return att->value.getIntValue();
  10989. att = att->next;
  10990. }
  10991. return defaultReturnValue;
  10992. }
  10993. double XmlElement::getDoubleAttribute (const tchar* const attributeName,
  10994. const double defaultReturnValue) const throw()
  10995. {
  10996. const XmlAttributeNode* att = attributes;
  10997. while (att != 0)
  10998. {
  10999. if (att->name.equalsIgnoreCase (attributeName))
  11000. return att->value.getDoubleValue();
  11001. att = att->next;
  11002. }
  11003. return defaultReturnValue;
  11004. }
  11005. bool XmlElement::getBoolAttribute (const tchar* const attributeName,
  11006. const bool defaultReturnValue) const throw()
  11007. {
  11008. const XmlAttributeNode* att = attributes;
  11009. while (att != 0)
  11010. {
  11011. if (att->name.equalsIgnoreCase (attributeName))
  11012. {
  11013. tchar firstChar = att->value[0];
  11014. if (CharacterFunctions::isWhitespace (firstChar))
  11015. firstChar = att->value.trimStart() [0];
  11016. return firstChar == T('1')
  11017. || firstChar == T('t')
  11018. || firstChar == T('y')
  11019. || firstChar == T('T')
  11020. || firstChar == T('Y');
  11021. }
  11022. att = att->next;
  11023. }
  11024. return defaultReturnValue;
  11025. }
  11026. bool XmlElement::compareAttribute (const tchar* const attributeName,
  11027. const tchar* const stringToCompareAgainst,
  11028. const bool ignoreCase) const throw()
  11029. {
  11030. const XmlAttributeNode* att = attributes;
  11031. while (att != 0)
  11032. {
  11033. if (att->name.equalsIgnoreCase (attributeName))
  11034. {
  11035. if (ignoreCase)
  11036. return att->value.equalsIgnoreCase (stringToCompareAgainst);
  11037. else
  11038. return att->value == stringToCompareAgainst;
  11039. }
  11040. att = att->next;
  11041. }
  11042. return false;
  11043. }
  11044. void XmlElement::setAttribute (const tchar* const attributeName,
  11045. const String& value) throw()
  11046. {
  11047. #ifdef JUCE_DEBUG
  11048. // check the identifier being passed in is legal..
  11049. const tchar* t = attributeName;
  11050. while (*t != 0)
  11051. {
  11052. jassert (CharacterFunctions::isLetterOrDigit (*t)
  11053. || *t == T('_')
  11054. || *t == T('-')
  11055. || *t == T(':'));
  11056. ++t;
  11057. }
  11058. #endif
  11059. if (attributes == 0)
  11060. {
  11061. attributes = new XmlAttributeNode (attributeName, value);
  11062. }
  11063. else
  11064. {
  11065. XmlAttributeNode* att = attributes;
  11066. for (;;)
  11067. {
  11068. if (att->name.equalsIgnoreCase (attributeName))
  11069. {
  11070. att->value = value;
  11071. break;
  11072. }
  11073. else if (att->next == 0)
  11074. {
  11075. att->next = new XmlAttributeNode (attributeName, value);
  11076. break;
  11077. }
  11078. att = att->next;
  11079. }
  11080. }
  11081. }
  11082. void XmlElement::setAttribute (const tchar* const attributeName,
  11083. const tchar* const text) throw()
  11084. {
  11085. setAttribute (attributeName, String (text));
  11086. }
  11087. void XmlElement::setAttribute (const tchar* const attributeName,
  11088. const int number) throw()
  11089. {
  11090. setAttribute (attributeName, String (number));
  11091. }
  11092. void XmlElement::setAttribute (const tchar* const attributeName,
  11093. const double number) throw()
  11094. {
  11095. tchar buffer [40];
  11096. CharacterFunctions::printf (buffer, numElementsInArray (buffer), T("%.9g"), number);
  11097. setAttribute (attributeName, buffer);
  11098. }
  11099. void XmlElement::removeAttribute (const tchar* const attributeName) throw()
  11100. {
  11101. XmlAttributeNode* att = attributes;
  11102. XmlAttributeNode* lastAtt = 0;
  11103. while (att != 0)
  11104. {
  11105. if (att->name.equalsIgnoreCase (attributeName))
  11106. {
  11107. if (lastAtt == 0)
  11108. attributes = att->next;
  11109. else
  11110. lastAtt->next = att->next;
  11111. delete att;
  11112. break;
  11113. }
  11114. lastAtt = att;
  11115. att = att->next;
  11116. }
  11117. }
  11118. void XmlElement::removeAllAttributes() throw()
  11119. {
  11120. while (attributes != 0)
  11121. {
  11122. XmlAttributeNode* const nextAtt = attributes->next;
  11123. delete attributes;
  11124. attributes = nextAtt;
  11125. }
  11126. }
  11127. int XmlElement::getNumChildElements() const throw()
  11128. {
  11129. int count = 0;
  11130. const XmlElement* child = firstChildElement;
  11131. while (child != 0)
  11132. {
  11133. ++count;
  11134. child = child->nextElement;
  11135. }
  11136. return count;
  11137. }
  11138. XmlElement* XmlElement::getChildElement (const int index) const throw()
  11139. {
  11140. int count = 0;
  11141. XmlElement* child = firstChildElement;
  11142. while (child != 0 && count < index)
  11143. {
  11144. child = child->nextElement;
  11145. ++count;
  11146. }
  11147. return child;
  11148. }
  11149. XmlElement* XmlElement::getChildByName (const tchar* const childName) const throw()
  11150. {
  11151. XmlElement* child = firstChildElement;
  11152. while (child != 0)
  11153. {
  11154. if (child->hasTagName (childName))
  11155. break;
  11156. child = child->nextElement;
  11157. }
  11158. return child;
  11159. }
  11160. void XmlElement::addChildElement (XmlElement* const newNode) throw()
  11161. {
  11162. if (newNode != 0)
  11163. {
  11164. if (firstChildElement == 0)
  11165. {
  11166. firstChildElement = newNode;
  11167. }
  11168. else
  11169. {
  11170. XmlElement* child = firstChildElement;
  11171. while (child->nextElement != 0)
  11172. child = child->nextElement;
  11173. child->nextElement = newNode;
  11174. // if this is non-zero, then something's probably
  11175. // gone wrong..
  11176. jassert (newNode->nextElement == 0);
  11177. }
  11178. }
  11179. }
  11180. void XmlElement::insertChildElement (XmlElement* const newNode,
  11181. int indexToInsertAt) throw()
  11182. {
  11183. if (newNode != 0)
  11184. {
  11185. removeChildElement (newNode, false);
  11186. if (indexToInsertAt == 0)
  11187. {
  11188. newNode->nextElement = firstChildElement;
  11189. firstChildElement = newNode;
  11190. }
  11191. else
  11192. {
  11193. if (firstChildElement == 0)
  11194. {
  11195. firstChildElement = newNode;
  11196. }
  11197. else
  11198. {
  11199. if (indexToInsertAt < 0)
  11200. indexToInsertAt = INT_MAX;
  11201. XmlElement* child = firstChildElement;
  11202. while (child->nextElement != 0 && --indexToInsertAt > 0)
  11203. child = child->nextElement;
  11204. newNode->nextElement = child->nextElement;
  11205. child->nextElement = newNode;
  11206. }
  11207. }
  11208. }
  11209. }
  11210. bool XmlElement::replaceChildElement (XmlElement* const currentChildElement,
  11211. XmlElement* const newNode) throw()
  11212. {
  11213. if (newNode != 0)
  11214. {
  11215. XmlElement* child = firstChildElement;
  11216. XmlElement* previousNode = 0;
  11217. while (child != 0)
  11218. {
  11219. if (child == currentChildElement)
  11220. {
  11221. if (child != newNode)
  11222. {
  11223. if (previousNode == 0)
  11224. firstChildElement = newNode;
  11225. else
  11226. previousNode->nextElement = newNode;
  11227. newNode->nextElement = child->nextElement;
  11228. delete child;
  11229. }
  11230. return true;
  11231. }
  11232. previousNode = child;
  11233. child = child->nextElement;
  11234. }
  11235. }
  11236. return false;
  11237. }
  11238. void XmlElement::removeChildElement (XmlElement* const childToRemove,
  11239. const bool shouldDeleteTheChild) throw()
  11240. {
  11241. if (childToRemove != 0)
  11242. {
  11243. if (firstChildElement == childToRemove)
  11244. {
  11245. firstChildElement = childToRemove->nextElement;
  11246. childToRemove->nextElement = 0;
  11247. }
  11248. else
  11249. {
  11250. XmlElement* child = firstChildElement;
  11251. XmlElement* last = 0;
  11252. while (child != 0)
  11253. {
  11254. if (child == childToRemove)
  11255. {
  11256. if (last == 0)
  11257. firstChildElement = child->nextElement;
  11258. else
  11259. last->nextElement = child->nextElement;
  11260. childToRemove->nextElement = 0;
  11261. break;
  11262. }
  11263. last = child;
  11264. child = child->nextElement;
  11265. }
  11266. }
  11267. if (shouldDeleteTheChild)
  11268. delete childToRemove;
  11269. }
  11270. }
  11271. bool XmlElement::isEquivalentTo (const XmlElement* const other,
  11272. const bool ignoreOrderOfAttributes) const throw()
  11273. {
  11274. if (this != other)
  11275. {
  11276. if (other == 0 || tagName != other->tagName)
  11277. {
  11278. return false;
  11279. }
  11280. if (ignoreOrderOfAttributes)
  11281. {
  11282. int totalAtts = 0;
  11283. const XmlAttributeNode* att = attributes;
  11284. while (att != 0)
  11285. {
  11286. if (! other->compareAttribute (att->name, att->value))
  11287. return false;
  11288. att = att->next;
  11289. ++totalAtts;
  11290. }
  11291. if (totalAtts != other->getNumAttributes())
  11292. return false;
  11293. }
  11294. else
  11295. {
  11296. const XmlAttributeNode* thisAtt = attributes;
  11297. const XmlAttributeNode* otherAtt = other->attributes;
  11298. for (;;)
  11299. {
  11300. if (thisAtt == 0 || otherAtt == 0)
  11301. {
  11302. if (thisAtt == otherAtt) // both 0, so it's a match
  11303. break;
  11304. return false;
  11305. }
  11306. if (thisAtt->name != otherAtt->name
  11307. || thisAtt->value != otherAtt->value)
  11308. {
  11309. return false;
  11310. }
  11311. thisAtt = thisAtt->next;
  11312. otherAtt = otherAtt->next;
  11313. }
  11314. }
  11315. const XmlElement* thisChild = firstChildElement;
  11316. const XmlElement* otherChild = other->firstChildElement;
  11317. for (;;)
  11318. {
  11319. if (thisChild == 0 || otherChild == 0)
  11320. {
  11321. if (thisChild == otherChild) // both 0, so it's a match
  11322. break;
  11323. return false;
  11324. }
  11325. if (! thisChild->isEquivalentTo (otherChild, ignoreOrderOfAttributes))
  11326. return false;
  11327. thisChild = thisChild->nextElement;
  11328. otherChild = otherChild->nextElement;
  11329. }
  11330. }
  11331. return true;
  11332. }
  11333. void XmlElement::deleteAllChildElements() throw()
  11334. {
  11335. while (firstChildElement != 0)
  11336. {
  11337. XmlElement* const nextChild = firstChildElement->nextElement;
  11338. delete firstChildElement;
  11339. firstChildElement = nextChild;
  11340. }
  11341. }
  11342. void XmlElement::deleteAllChildElementsWithTagName (const tchar* const name) throw()
  11343. {
  11344. XmlElement* child = firstChildElement;
  11345. while (child != 0)
  11346. {
  11347. if (child->hasTagName (name))
  11348. {
  11349. XmlElement* const nextChild = child->nextElement;
  11350. removeChildElement (child, true);
  11351. child = nextChild;
  11352. }
  11353. else
  11354. {
  11355. child = child->nextElement;
  11356. }
  11357. }
  11358. }
  11359. bool XmlElement::containsChildElement (const XmlElement* const possibleChild) const throw()
  11360. {
  11361. const XmlElement* child = firstChildElement;
  11362. while (child != 0)
  11363. {
  11364. if (child == possibleChild)
  11365. return true;
  11366. child = child->nextElement;
  11367. }
  11368. return false;
  11369. }
  11370. XmlElement* XmlElement::findParentElementOf (const XmlElement* const elementToLookFor) throw()
  11371. {
  11372. if (this == elementToLookFor || elementToLookFor == 0)
  11373. return 0;
  11374. XmlElement* child = firstChildElement;
  11375. while (child != 0)
  11376. {
  11377. if (elementToLookFor == child)
  11378. return this;
  11379. XmlElement* const found = child->findParentElementOf (elementToLookFor);
  11380. if (found != 0)
  11381. return found;
  11382. child = child->nextElement;
  11383. }
  11384. return 0;
  11385. }
  11386. XmlElement** XmlElement::getChildElementsAsArray (const int num) const throw()
  11387. {
  11388. XmlElement** const elems = new XmlElement* [num];
  11389. XmlElement* e = firstChildElement;
  11390. int i = 0;
  11391. while (e != 0)
  11392. {
  11393. elems [i++] = e;
  11394. e = e->nextElement;
  11395. }
  11396. return elems;
  11397. }
  11398. void XmlElement::reorderChildElements (XmlElement** const elems, const int num) throw()
  11399. {
  11400. XmlElement* e = firstChildElement = elems[0];
  11401. for (int i = 1; i < num; ++i)
  11402. {
  11403. e->nextElement = elems[i];
  11404. e = e->nextElement;
  11405. }
  11406. e->nextElement = 0;
  11407. }
  11408. bool XmlElement::isTextElement() const throw()
  11409. {
  11410. return tagName.isEmpty();
  11411. }
  11412. static const tchar* const juce_xmltextContentAttributeName = T("text");
  11413. const String XmlElement::getText() const throw()
  11414. {
  11415. jassert (isTextElement()); // you're trying to get the text from an element that
  11416. // isn't actually a text element.. If this contains text sub-nodes, you
  11417. // can use getAllSubText instead to
  11418. return getStringAttribute (juce_xmltextContentAttributeName);
  11419. }
  11420. void XmlElement::setText (const String& newText) throw()
  11421. {
  11422. if (isTextElement())
  11423. {
  11424. setAttribute (juce_xmltextContentAttributeName, newText);
  11425. }
  11426. else
  11427. {
  11428. jassertfalse // you can only change the text in a text element, not a normal one.
  11429. }
  11430. }
  11431. const String XmlElement::getAllSubText() const throw()
  11432. {
  11433. String result;
  11434. const XmlElement* child = firstChildElement;
  11435. while (child != 0)
  11436. {
  11437. if (child->isTextElement())
  11438. result += child->getText();
  11439. child = child->nextElement;
  11440. }
  11441. return result;
  11442. }
  11443. const String XmlElement::getChildElementAllSubText (const tchar* const childTagName,
  11444. const String& defaultReturnValue) const throw()
  11445. {
  11446. const XmlElement* const child = getChildByName (childTagName);
  11447. if (child != 0)
  11448. return child->getAllSubText();
  11449. return defaultReturnValue;
  11450. }
  11451. XmlElement* XmlElement::createTextElement (const String& text) throw()
  11452. {
  11453. XmlElement* const e = new XmlElement ((int) 0);
  11454. e->setAttribute (juce_xmltextContentAttributeName, text);
  11455. return e;
  11456. }
  11457. void XmlElement::addTextElement (const String& text) throw()
  11458. {
  11459. addChildElement (createTextElement (text));
  11460. }
  11461. void XmlElement::deleteAllTextElements() throw()
  11462. {
  11463. XmlElement* child = firstChildElement;
  11464. while (child != 0)
  11465. {
  11466. XmlElement* const next = child->nextElement;
  11467. if (child->isTextElement())
  11468. removeChildElement (child, true);
  11469. child = next;
  11470. }
  11471. }
  11472. END_JUCE_NAMESPACE
  11473. /********* End of inlined file: juce_XmlElement.cpp *********/
  11474. /********* Start of inlined file: juce_InterProcessLock.cpp *********/
  11475. BEGIN_JUCE_NAMESPACE
  11476. // (implemented in the platform-specific code files)
  11477. END_JUCE_NAMESPACE
  11478. /********* End of inlined file: juce_InterProcessLock.cpp *********/
  11479. /********* Start of inlined file: juce_ReadWriteLock.cpp *********/
  11480. BEGIN_JUCE_NAMESPACE
  11481. ReadWriteLock::ReadWriteLock() throw()
  11482. : numWaitingWriters (0),
  11483. numWriters (0),
  11484. writerThreadId (0)
  11485. {
  11486. }
  11487. ReadWriteLock::~ReadWriteLock() throw()
  11488. {
  11489. jassert (readerThreads.size() == 0);
  11490. jassert (numWriters == 0);
  11491. }
  11492. void ReadWriteLock::enterRead() const throw()
  11493. {
  11494. const int64 threadId = Thread::getCurrentThreadId();
  11495. const ScopedLock sl (accessLock);
  11496. for (;;)
  11497. {
  11498. jassert (readerThreads.size() % 2 == 0);
  11499. int i;
  11500. for (i = 0; i < readerThreads.size(); i += 2)
  11501. if (readerThreads.getUnchecked(i) == threadId)
  11502. break;
  11503. if (i < readerThreads.size()
  11504. || numWriters + numWaitingWriters == 0
  11505. || (threadId == writerThreadId && numWriters > 0))
  11506. {
  11507. if (i < readerThreads.size())
  11508. {
  11509. readerThreads.set (i + 1, readerThreads.getUnchecked (i + 1) + 1);
  11510. }
  11511. else
  11512. {
  11513. readerThreads.add (threadId);
  11514. readerThreads.add (1);
  11515. }
  11516. return;
  11517. }
  11518. const ScopedUnlock ul (accessLock);
  11519. waitEvent.wait (100);
  11520. }
  11521. }
  11522. void ReadWriteLock::exitRead() const throw()
  11523. {
  11524. const int64 threadId = Thread::getCurrentThreadId();
  11525. const ScopedLock sl (accessLock);
  11526. for (int i = 0; i < readerThreads.size(); i += 2)
  11527. {
  11528. if (readerThreads.getUnchecked(i) == threadId)
  11529. {
  11530. const int newCount = ((int) readerThreads.getUnchecked (i + 1)) - 1;
  11531. if (newCount == 0)
  11532. {
  11533. readerThreads.removeRange (i, 2);
  11534. waitEvent.signal();
  11535. }
  11536. else
  11537. {
  11538. readerThreads.set (i + 1, newCount);
  11539. }
  11540. return;
  11541. }
  11542. }
  11543. jassertfalse // unlocking a lock that wasn't locked..
  11544. }
  11545. void ReadWriteLock::enterWrite() const throw()
  11546. {
  11547. const int64 threadId = Thread::getCurrentThreadId();
  11548. const ScopedLock sl (accessLock);
  11549. for (;;)
  11550. {
  11551. if (readerThreads.size() + numWriters == 0
  11552. || threadId == writerThreadId
  11553. || (readerThreads.size() == 2
  11554. && readerThreads.getUnchecked(0) == threadId))
  11555. {
  11556. writerThreadId = threadId;
  11557. ++numWriters;
  11558. break;
  11559. }
  11560. ++numWaitingWriters;
  11561. accessLock.exit();
  11562. waitEvent.wait (100);
  11563. accessLock.enter();
  11564. --numWaitingWriters;
  11565. }
  11566. }
  11567. bool ReadWriteLock::tryEnterWrite() const throw()
  11568. {
  11569. const int64 threadId = Thread::getCurrentThreadId();
  11570. const ScopedLock sl (accessLock);
  11571. if (readerThreads.size() + numWriters == 0
  11572. || threadId == writerThreadId
  11573. || (readerThreads.size() == 2
  11574. && readerThreads.getUnchecked(0) == threadId))
  11575. {
  11576. writerThreadId = threadId;
  11577. ++numWriters;
  11578. return true;
  11579. }
  11580. return false;
  11581. }
  11582. void ReadWriteLock::exitWrite() const throw()
  11583. {
  11584. const ScopedLock sl (accessLock);
  11585. // check this thread actually had the lock..
  11586. jassert (numWriters > 0 && writerThreadId == Thread::getCurrentThreadId());
  11587. if (--numWriters == 0)
  11588. {
  11589. writerThreadId = 0;
  11590. waitEvent.signal();
  11591. }
  11592. }
  11593. END_JUCE_NAMESPACE
  11594. /********* End of inlined file: juce_ReadWriteLock.cpp *********/
  11595. /********* Start of inlined file: juce_Thread.cpp *********/
  11596. BEGIN_JUCE_NAMESPACE
  11597. // these functions are implemented in the platform-specific code.
  11598. void* juce_createThread (void* userData) throw();
  11599. void juce_killThread (void* handle) throw();
  11600. void juce_setThreadPriority (void* handle, int priority) throw();
  11601. void juce_setCurrentThreadName (const String& name) throw();
  11602. #if JUCE_WIN32
  11603. void juce_CloseThreadHandle (void* handle) throw();
  11604. #endif
  11605. static VoidArray runningThreads (4);
  11606. static CriticalSection runningThreadsLock;
  11607. void Thread::threadEntryPoint (Thread* const thread) throw()
  11608. {
  11609. runningThreadsLock.enter();
  11610. runningThreads.add (thread);
  11611. runningThreadsLock.exit();
  11612. JUCE_TRY
  11613. {
  11614. thread->threadId_ = Thread::getCurrentThreadId();
  11615. if (thread->threadName_.isNotEmpty())
  11616. juce_setCurrentThreadName (thread->threadName_);
  11617. if (thread->startSuspensionEvent_.wait (10000))
  11618. {
  11619. if (thread->affinityMask_ != 0)
  11620. setCurrentThreadAffinityMask (thread->affinityMask_);
  11621. thread->run();
  11622. }
  11623. }
  11624. JUCE_CATCH_ALL_ASSERT
  11625. runningThreadsLock.enter();
  11626. jassert (runningThreads.contains (thread));
  11627. runningThreads.removeValue (thread);
  11628. runningThreadsLock.exit();
  11629. #if JUCE_WIN32
  11630. juce_CloseThreadHandle (thread->threadHandle_);
  11631. #endif
  11632. thread->threadHandle_ = 0;
  11633. thread->threadId_ = 0;
  11634. }
  11635. // used to wrap the incoming call from the platform-specific code
  11636. void JUCE_API juce_threadEntryPoint (void* userData)
  11637. {
  11638. Thread::threadEntryPoint ((Thread*) userData);
  11639. }
  11640. Thread::Thread (const String& threadName)
  11641. : threadName_ (threadName),
  11642. threadHandle_ (0),
  11643. threadPriority_ (5),
  11644. threadId_ (0),
  11645. affinityMask_ (0),
  11646. threadShouldExit_ (false)
  11647. {
  11648. }
  11649. Thread::~Thread()
  11650. {
  11651. stopThread (100);
  11652. }
  11653. void Thread::startThread() throw()
  11654. {
  11655. const ScopedLock sl (startStopLock);
  11656. threadShouldExit_ = false;
  11657. if (threadHandle_ == 0)
  11658. {
  11659. threadHandle_ = juce_createThread ((void*) this);
  11660. juce_setThreadPriority (threadHandle_, threadPriority_);
  11661. startSuspensionEvent_.signal();
  11662. }
  11663. }
  11664. void Thread::startThread (const int priority) throw()
  11665. {
  11666. const ScopedLock sl (startStopLock);
  11667. if (threadHandle_ == 0)
  11668. {
  11669. threadPriority_ = priority;
  11670. startThread();
  11671. }
  11672. else
  11673. {
  11674. setPriority (priority);
  11675. }
  11676. }
  11677. bool Thread::isThreadRunning() const throw()
  11678. {
  11679. return threadHandle_ != 0;
  11680. }
  11681. void Thread::signalThreadShouldExit() throw()
  11682. {
  11683. threadShouldExit_ = true;
  11684. }
  11685. bool Thread::waitForThreadToExit (const int timeOutMilliseconds) const throw()
  11686. {
  11687. // Doh! So how exactly do you expect this thread to wait for itself to stop??
  11688. jassert (getThreadId() != getCurrentThreadId());
  11689. const int sleepMsPerIteration = 5;
  11690. int count = timeOutMilliseconds / sleepMsPerIteration;
  11691. while (isThreadRunning())
  11692. {
  11693. if (timeOutMilliseconds > 0 && --count < 0)
  11694. return false;
  11695. sleep (sleepMsPerIteration);
  11696. }
  11697. return true;
  11698. }
  11699. void Thread::stopThread (const int timeOutMilliseconds) throw()
  11700. {
  11701. // agh! You can't stop the thread that's calling this method! How on earth
  11702. // would that work??
  11703. jassert (getCurrentThreadId() != getThreadId());
  11704. const ScopedLock sl (startStopLock);
  11705. if (isThreadRunning())
  11706. {
  11707. signalThreadShouldExit();
  11708. notify();
  11709. if (timeOutMilliseconds != 0)
  11710. waitForThreadToExit (timeOutMilliseconds);
  11711. if (isThreadRunning())
  11712. {
  11713. // very bad karma if this point is reached, as
  11714. // there are bound to be locks and events left in
  11715. // silly states when a thread is killed by force..
  11716. jassertfalse
  11717. Logger::writeToLog ("!! killing thread by force !!");
  11718. juce_killThread (threadHandle_);
  11719. threadHandle_ = 0;
  11720. threadId_ = 0;
  11721. const ScopedLock sl (runningThreadsLock);
  11722. runningThreads.removeValue (this);
  11723. }
  11724. }
  11725. }
  11726. void Thread::setPriority (const int priority) throw()
  11727. {
  11728. const ScopedLock sl (startStopLock);
  11729. threadPriority_ = priority;
  11730. juce_setThreadPriority (threadHandle_, priority);
  11731. }
  11732. void Thread::setCurrentThreadPriority (const int priority) throw()
  11733. {
  11734. juce_setThreadPriority (0, priority);
  11735. }
  11736. void Thread::setAffinityMask (const uint32 affinityMask) throw()
  11737. {
  11738. affinityMask_ = affinityMask;
  11739. }
  11740. int64 Thread::getThreadId() const throw()
  11741. {
  11742. return threadId_;
  11743. }
  11744. bool Thread::wait (const int timeOutMilliseconds) const throw()
  11745. {
  11746. return defaultEvent_.wait (timeOutMilliseconds);
  11747. }
  11748. void Thread::notify() const throw()
  11749. {
  11750. defaultEvent_.signal();
  11751. }
  11752. int Thread::getNumRunningThreads() throw()
  11753. {
  11754. return runningThreads.size();
  11755. }
  11756. Thread* Thread::getCurrentThread() throw()
  11757. {
  11758. const int64 thisId = getCurrentThreadId();
  11759. Thread* result = 0;
  11760. runningThreadsLock.enter();
  11761. for (int i = runningThreads.size(); --i >= 0;)
  11762. {
  11763. Thread* const t = (Thread*) (runningThreads.getUnchecked(i));
  11764. if (t->threadId_ == thisId)
  11765. {
  11766. result = t;
  11767. break;
  11768. }
  11769. }
  11770. runningThreadsLock.exit();
  11771. return result;
  11772. }
  11773. void Thread::stopAllThreads (const int timeOutMilliseconds) throw()
  11774. {
  11775. runningThreadsLock.enter();
  11776. for (int i = runningThreads.size(); --i >= 0;)
  11777. ((Thread*) runningThreads.getUnchecked(i))->signalThreadShouldExit();
  11778. runningThreadsLock.exit();
  11779. for (;;)
  11780. {
  11781. runningThreadsLock.enter();
  11782. Thread* const t = (Thread*) runningThreads[0];
  11783. runningThreadsLock.exit();
  11784. if (t == 0)
  11785. break;
  11786. t->stopThread (timeOutMilliseconds);
  11787. }
  11788. }
  11789. END_JUCE_NAMESPACE
  11790. /********* End of inlined file: juce_Thread.cpp *********/
  11791. /********* Start of inlined file: juce_ThreadPool.cpp *********/
  11792. BEGIN_JUCE_NAMESPACE
  11793. ThreadPoolJob::ThreadPoolJob (const String& name)
  11794. : jobName (name),
  11795. pool (0),
  11796. shouldStop (false),
  11797. isActive (false),
  11798. shouldBeDeleted (false)
  11799. {
  11800. }
  11801. ThreadPoolJob::~ThreadPoolJob()
  11802. {
  11803. // you mustn't delete a job while it's still in a pool! Use ThreadPool::removeJob()
  11804. // to remove it first!
  11805. jassert (pool == 0 || ! pool->contains (this));
  11806. }
  11807. const String ThreadPoolJob::getJobName() const
  11808. {
  11809. return jobName;
  11810. }
  11811. void ThreadPoolJob::setJobName (const String& newName)
  11812. {
  11813. jobName = newName;
  11814. }
  11815. void ThreadPoolJob::signalJobShouldExit()
  11816. {
  11817. shouldStop = true;
  11818. }
  11819. class ThreadPoolThread : public Thread
  11820. {
  11821. ThreadPool& pool;
  11822. bool volatile busy;
  11823. ThreadPoolThread (const ThreadPoolThread&);
  11824. const ThreadPoolThread& operator= (const ThreadPoolThread&);
  11825. public:
  11826. ThreadPoolThread (ThreadPool& pool_)
  11827. : Thread (T("Pool")),
  11828. pool (pool_),
  11829. busy (false)
  11830. {
  11831. }
  11832. ~ThreadPoolThread()
  11833. {
  11834. }
  11835. void run()
  11836. {
  11837. while (! threadShouldExit())
  11838. {
  11839. if (! pool.runNextJob())
  11840. wait (500);
  11841. }
  11842. }
  11843. };
  11844. ThreadPool::ThreadPool (const int numThreads_,
  11845. const bool startThreadsOnlyWhenNeeded,
  11846. const int stopThreadsWhenNotUsedTimeoutMs)
  11847. : numThreads (jmax (1, numThreads_)),
  11848. threadStopTimeout (stopThreadsWhenNotUsedTimeoutMs),
  11849. priority (5)
  11850. {
  11851. jassert (numThreads_ > 0); // not much point having one of these with no threads in it.
  11852. threads = (Thread**) juce_calloc (sizeof (Thread*) * numThreads);
  11853. for (int i = numThreads; --i >= 0;)
  11854. {
  11855. threads[i] = new ThreadPoolThread (*this);
  11856. if (! startThreadsOnlyWhenNeeded)
  11857. threads[i]->startThread();
  11858. }
  11859. }
  11860. ThreadPool::~ThreadPool()
  11861. {
  11862. removeAllJobs (true, 4000);
  11863. int i;
  11864. for (i = numThreads; --i >= 0;)
  11865. threads[i]->signalThreadShouldExit();
  11866. for (i = numThreads; --i >= 0;)
  11867. {
  11868. threads[i]->stopThread (500);
  11869. delete threads[i];
  11870. }
  11871. juce_free (threads);
  11872. }
  11873. void ThreadPool::addJob (ThreadPoolJob* const job)
  11874. {
  11875. jassert (job->pool == 0);
  11876. if (job->pool == 0)
  11877. {
  11878. job->pool = this;
  11879. job->shouldStop = false;
  11880. job->isActive = false;
  11881. lock.enter();
  11882. jobs.add (job);
  11883. int numRunning = 0;
  11884. int i;
  11885. for (i = numThreads; --i >= 0;)
  11886. if (threads[i]->isThreadRunning() && ! threads[i]->threadShouldExit())
  11887. ++numRunning;
  11888. if (numRunning < numThreads)
  11889. {
  11890. bool startedOne = false;
  11891. int n = 1000;
  11892. while (--n >= 0 && ! startedOne)
  11893. {
  11894. for (int i = numThreads; --i >= 0;)
  11895. {
  11896. if (! threads[i]->isThreadRunning())
  11897. {
  11898. threads[i]->startThread();
  11899. startedOne = true;
  11900. }
  11901. }
  11902. if (! startedOne)
  11903. Thread::sleep (5);
  11904. }
  11905. }
  11906. lock.exit();
  11907. for (i = numThreads; --i >= 0;)
  11908. threads[i]->notify();
  11909. }
  11910. }
  11911. int ThreadPool::getNumJobs() const throw()
  11912. {
  11913. return jobs.size();
  11914. }
  11915. ThreadPoolJob* ThreadPool::getJob (const int index) const
  11916. {
  11917. const ScopedLock sl (lock);
  11918. return (ThreadPoolJob*) jobs [index];
  11919. }
  11920. bool ThreadPool::contains (const ThreadPoolJob* const job) const throw()
  11921. {
  11922. const ScopedLock sl (lock);
  11923. return jobs.contains ((void*) job);
  11924. }
  11925. bool ThreadPool::isJobRunning (const ThreadPoolJob* const job) const
  11926. {
  11927. const ScopedLock sl (lock);
  11928. return jobs.contains ((void*) job) && job->isActive;
  11929. }
  11930. bool ThreadPool::waitForJobToFinish (const ThreadPoolJob* const job,
  11931. const int timeOutMs) const
  11932. {
  11933. if (job != 0)
  11934. {
  11935. const uint32 start = Time::getMillisecondCounter();
  11936. while (contains (job))
  11937. {
  11938. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  11939. return false;
  11940. Thread::sleep (2);
  11941. }
  11942. }
  11943. return true;
  11944. }
  11945. bool ThreadPool::removeJob (ThreadPoolJob* const job,
  11946. const bool interruptIfRunning,
  11947. const int timeOutMs)
  11948. {
  11949. if (job != 0)
  11950. {
  11951. lock.enter();
  11952. if (jobs.contains (job))
  11953. {
  11954. if (job->isActive)
  11955. {
  11956. if (interruptIfRunning)
  11957. job->signalJobShouldExit();
  11958. lock.exit();
  11959. return waitForJobToFinish (job, timeOutMs);
  11960. }
  11961. else
  11962. {
  11963. jobs.removeValue (job);
  11964. }
  11965. }
  11966. lock.exit();
  11967. }
  11968. return true;
  11969. }
  11970. bool ThreadPool::removeAllJobs (const bool interruptRunningJobs,
  11971. const int timeOutMs)
  11972. {
  11973. lock.enter();
  11974. for (int i = jobs.size(); --i >= 0;)
  11975. {
  11976. ThreadPoolJob* const job = (ThreadPoolJob*) jobs.getUnchecked(i);
  11977. if (job->isActive)
  11978. {
  11979. if (interruptRunningJobs)
  11980. job->signalJobShouldExit();
  11981. }
  11982. else
  11983. {
  11984. jobs.remove (i);
  11985. }
  11986. }
  11987. lock.exit();
  11988. const uint32 start = Time::getMillisecondCounter();
  11989. while (jobs.size() > 0)
  11990. {
  11991. if (timeOutMs >= 0 && Time::getMillisecondCounter() >= start + timeOutMs)
  11992. return false;
  11993. Thread::sleep (2);
  11994. }
  11995. return true;
  11996. }
  11997. const StringArray ThreadPool::getNamesOfAllJobs (const bool onlyReturnActiveJobs) const
  11998. {
  11999. StringArray s;
  12000. const ScopedLock sl (lock);
  12001. for (int i = 0; i < jobs.size(); ++i)
  12002. {
  12003. const ThreadPoolJob* const job = (const ThreadPoolJob*) jobs.getUnchecked(i);
  12004. if (job->isActive || ! onlyReturnActiveJobs)
  12005. s.add (job->getJobName());
  12006. }
  12007. return s;
  12008. }
  12009. void ThreadPool::setThreadPriorities (const int newPriority)
  12010. {
  12011. if (priority != newPriority)
  12012. {
  12013. priority = newPriority;
  12014. for (int i = numThreads; --i >= 0;)
  12015. threads[i]->setPriority (newPriority);
  12016. }
  12017. }
  12018. bool ThreadPool::runNextJob()
  12019. {
  12020. lock.enter();
  12021. ThreadPoolJob* job = 0;
  12022. for (int i = 0; i < jobs.size(); ++i)
  12023. {
  12024. job = (ThreadPoolJob*) jobs [i];
  12025. if (job != 0 && ! (job->isActive || job->shouldStop))
  12026. break;
  12027. job = 0;
  12028. }
  12029. if (job != 0)
  12030. {
  12031. job->isActive = true;
  12032. lock.exit();
  12033. JUCE_TRY
  12034. {
  12035. ThreadPoolJob::JobStatus result = job->runJob();
  12036. lastJobEndTime = Time::getApproximateMillisecondCounter();
  12037. const ScopedLock sl (lock);
  12038. if (jobs.contains (job))
  12039. {
  12040. job->isActive = false;
  12041. if (result != ThreadPoolJob::jobNeedsRunningAgain || job->shouldStop)
  12042. {
  12043. job->pool = 0;
  12044. job->shouldStop = true;
  12045. jobs.removeValue (job);
  12046. if (result == ThreadPoolJob::jobHasFinishedAndShouldBeDeleted)
  12047. delete job;
  12048. }
  12049. else
  12050. {
  12051. // move the job to the end of the queue if it wants another go
  12052. jobs.move (jobs.indexOf (job), -1);
  12053. }
  12054. }
  12055. }
  12056. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12057. catch (...)
  12058. {
  12059. lock.enter();
  12060. jobs.removeValue (job);
  12061. lock.exit();
  12062. }
  12063. #endif
  12064. }
  12065. else
  12066. {
  12067. lock.exit();
  12068. if (threadStopTimeout > 0
  12069. && Time::getApproximateMillisecondCounter() > lastJobEndTime + threadStopTimeout)
  12070. {
  12071. lock.enter();
  12072. if (jobs.size() == 0)
  12073. {
  12074. for (int i = numThreads; --i >= 0;)
  12075. threads[i]->signalThreadShouldExit();
  12076. }
  12077. lock.exit();
  12078. }
  12079. else
  12080. {
  12081. return false;
  12082. }
  12083. }
  12084. return true;
  12085. }
  12086. END_JUCE_NAMESPACE
  12087. /********* End of inlined file: juce_ThreadPool.cpp *********/
  12088. /********* Start of inlined file: juce_TimeSliceThread.cpp *********/
  12089. BEGIN_JUCE_NAMESPACE
  12090. TimeSliceThread::TimeSliceThread (const String& threadName)
  12091. : Thread (threadName),
  12092. index (0),
  12093. clientBeingCalled (0),
  12094. clientsChanged (false)
  12095. {
  12096. }
  12097. TimeSliceThread::~TimeSliceThread()
  12098. {
  12099. stopThread (2000);
  12100. }
  12101. void TimeSliceThread::addTimeSliceClient (TimeSliceClient* const client)
  12102. {
  12103. const ScopedLock sl (listLock);
  12104. clients.addIfNotAlreadyThere (client);
  12105. clientsChanged = true;
  12106. notify();
  12107. }
  12108. void TimeSliceThread::removeTimeSliceClient (TimeSliceClient* const client)
  12109. {
  12110. const ScopedLock sl1 (listLock);
  12111. clientsChanged = true;
  12112. // if there's a chance we're in the middle of calling this client, we need to
  12113. // also lock the outer lock..
  12114. if (clientBeingCalled == client)
  12115. {
  12116. const ScopedUnlock ul (listLock); // unlock first to get the order right..
  12117. const ScopedLock sl1 (callbackLock);
  12118. const ScopedLock sl2 (listLock);
  12119. clients.removeValue (client);
  12120. }
  12121. else
  12122. {
  12123. clients.removeValue (client);
  12124. }
  12125. }
  12126. int TimeSliceThread::getNumClients() const throw()
  12127. {
  12128. return clients.size();
  12129. }
  12130. TimeSliceClient* TimeSliceThread::getClient (const int index) const throw()
  12131. {
  12132. const ScopedLock sl (listLock);
  12133. return clients [index];
  12134. }
  12135. void TimeSliceThread::run()
  12136. {
  12137. int numCallsSinceBusy = 0;
  12138. while (! threadShouldExit())
  12139. {
  12140. int timeToWait = 500;
  12141. {
  12142. const ScopedLock sl (callbackLock);
  12143. {
  12144. const ScopedLock sl (listLock);
  12145. if (clients.size() > 0)
  12146. {
  12147. index = (index + 1) % clients.size();
  12148. clientBeingCalled = clients [index];
  12149. }
  12150. else
  12151. {
  12152. index = 0;
  12153. clientBeingCalled = 0;
  12154. }
  12155. if (clientsChanged)
  12156. {
  12157. clientsChanged = false;
  12158. numCallsSinceBusy = 0;
  12159. }
  12160. }
  12161. if (clientBeingCalled != 0)
  12162. {
  12163. if (clientBeingCalled->useTimeSlice())
  12164. numCallsSinceBusy = 0;
  12165. else
  12166. ++numCallsSinceBusy;
  12167. if (numCallsSinceBusy >= clients.size())
  12168. timeToWait = 500;
  12169. else if (index == 0)
  12170. timeToWait = 1; // throw in an occasional pause, to stop everything locking up
  12171. else
  12172. timeToWait = 0;
  12173. }
  12174. }
  12175. if (timeToWait > 0)
  12176. wait (timeToWait);
  12177. }
  12178. }
  12179. END_JUCE_NAMESPACE
  12180. /********* End of inlined file: juce_TimeSliceThread.cpp *********/
  12181. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  12182. /********* Start of inlined file: juce_Application.cpp *********/
  12183. #if JUCE_MSVC
  12184. #pragma warning (push)
  12185. #pragma warning (disable: 4245 4514 4100)
  12186. #include <crtdbg.h>
  12187. #pragma warning (pop)
  12188. #endif
  12189. BEGIN_JUCE_NAMESPACE
  12190. void juce_setCurrentExecutableFileName (const String& filename) throw();
  12191. void juce_setCurrentThreadName (const String& name) throw();
  12192. static JUCEApplication* appInstance = 0;
  12193. JUCEApplication::JUCEApplication()
  12194. : appReturnValue (0),
  12195. stillInitialising (true)
  12196. {
  12197. }
  12198. JUCEApplication::~JUCEApplication()
  12199. {
  12200. }
  12201. JUCEApplication* JUCEApplication::getInstance() throw()
  12202. {
  12203. return appInstance;
  12204. }
  12205. bool JUCEApplication::isInitialising() const throw()
  12206. {
  12207. return stillInitialising;
  12208. }
  12209. const String JUCEApplication::getApplicationVersion()
  12210. {
  12211. return String::empty;
  12212. }
  12213. bool JUCEApplication::moreThanOneInstanceAllowed()
  12214. {
  12215. return true;
  12216. }
  12217. void JUCEApplication::anotherInstanceStarted (const String&)
  12218. {
  12219. }
  12220. void JUCEApplication::systemRequestedQuit()
  12221. {
  12222. quit();
  12223. }
  12224. void JUCEApplication::quit()
  12225. {
  12226. MessageManager::getInstance()->stopDispatchLoop();
  12227. }
  12228. void JUCEApplication::setApplicationReturnValue (const int newReturnValue) throw()
  12229. {
  12230. appReturnValue = newReturnValue;
  12231. }
  12232. void JUCEApplication::unhandledException (const std::exception*,
  12233. const String&,
  12234. const int)
  12235. {
  12236. jassertfalse
  12237. }
  12238. void JUCEApplication::sendUnhandledException (const std::exception* const e,
  12239. const char* const sourceFile,
  12240. const int lineNumber)
  12241. {
  12242. if (appInstance != 0)
  12243. appInstance->unhandledException (e, sourceFile, lineNumber);
  12244. }
  12245. ApplicationCommandTarget* JUCEApplication::getNextCommandTarget()
  12246. {
  12247. return 0;
  12248. }
  12249. void JUCEApplication::getAllCommands (Array <CommandID>& commands)
  12250. {
  12251. commands.add (StandardApplicationCommandIDs::quit);
  12252. }
  12253. void JUCEApplication::getCommandInfo (const CommandID commandID, ApplicationCommandInfo& result)
  12254. {
  12255. if (commandID == StandardApplicationCommandIDs::quit)
  12256. {
  12257. result.setInfo ("Quit",
  12258. "Quits the application",
  12259. "Application",
  12260. 0);
  12261. result.defaultKeypresses.add (KeyPress (T('q'), ModifierKeys::commandModifier, 0));
  12262. }
  12263. }
  12264. bool JUCEApplication::perform (const InvocationInfo& info)
  12265. {
  12266. if (info.commandID == StandardApplicationCommandIDs::quit)
  12267. {
  12268. systemRequestedQuit();
  12269. return true;
  12270. }
  12271. return false;
  12272. }
  12273. int JUCEApplication::main (String& commandLine, JUCEApplication* const app)
  12274. {
  12275. jassert (appInstance == 0);
  12276. appInstance = app;
  12277. initialiseJuce_GUI();
  12278. InterProcessLock* appLock = 0;
  12279. if (! app->moreThanOneInstanceAllowed())
  12280. {
  12281. appLock = new InterProcessLock ("juceAppLock_" + app->getApplicationName());
  12282. if (! appLock->enter(0))
  12283. {
  12284. MessageManager::broadcastMessage (app->getApplicationName() + "/" + commandLine);
  12285. delete appInstance;
  12286. appInstance = 0;
  12287. commandLine = String::empty;
  12288. DBG ("Another instance is running - quitting...");
  12289. return 0;
  12290. }
  12291. }
  12292. JUCE_TRY
  12293. {
  12294. juce_setCurrentThreadName ("Juce Message Thread");
  12295. // let the app do its setting-up..
  12296. app->initialise (commandLine.trim());
  12297. commandLine = String::empty;
  12298. // register for broadcast new app messages
  12299. MessageManager::getInstance()->registerBroadcastListener (app);
  12300. app->stillInitialising = false;
  12301. // now loop until a quit message is received..
  12302. MessageManager::getInstance()->runDispatchLoop();
  12303. MessageManager::getInstance()->deregisterBroadcastListener (app);
  12304. if (appLock != 0)
  12305. {
  12306. appLock->exit();
  12307. delete appLock;
  12308. }
  12309. }
  12310. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12311. catch (const std::exception& e)
  12312. {
  12313. app->unhandledException (&e, __FILE__, __LINE__);
  12314. }
  12315. catch (...)
  12316. {
  12317. app->unhandledException (0, __FILE__, __LINE__);
  12318. }
  12319. #endif
  12320. return shutdownAppAndClearUp();
  12321. }
  12322. int JUCEApplication::shutdownAppAndClearUp()
  12323. {
  12324. jassert (appInstance != 0);
  12325. JUCEApplication* const app = appInstance;
  12326. int returnValue = 0;
  12327. static bool reentrancyCheck = false;
  12328. if (! reentrancyCheck)
  12329. {
  12330. reentrancyCheck = true;
  12331. JUCE_TRY
  12332. {
  12333. // give the app a chance to clean up..
  12334. app->shutdown();
  12335. }
  12336. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  12337. catch (const std::exception& e)
  12338. {
  12339. app->unhandledException (&e, __FILE__, __LINE__);
  12340. }
  12341. catch (...)
  12342. {
  12343. app->unhandledException (0, __FILE__, __LINE__);
  12344. }
  12345. #endif
  12346. JUCE_TRY
  12347. {
  12348. shutdownJuce_GUI();
  12349. returnValue = app->getApplicationReturnValue();
  12350. appInstance = 0;
  12351. delete app;
  12352. }
  12353. JUCE_CATCH_ALL_ASSERT
  12354. reentrancyCheck = false;
  12355. }
  12356. return returnValue;
  12357. }
  12358. int JUCEApplication::main (int argc, char* argv[],
  12359. JUCEApplication* const newApp)
  12360. {
  12361. #if JUCE_MAC
  12362. const ScopedAutoReleasePool pool;
  12363. #endif
  12364. juce_setCurrentExecutableFileName (String::fromUTF8 ((const uint8*) argv[0]));
  12365. String cmd;
  12366. for (int i = 1; i < argc; ++i)
  12367. cmd << String::fromUTF8 ((const uint8*) argv[i]) << T(' ');
  12368. return JUCEApplication::main (cmd, newApp);
  12369. }
  12370. void JUCEApplication::actionListenerCallback (const String& message)
  12371. {
  12372. if (message.startsWith (getApplicationName() + "/"))
  12373. anotherInstanceStarted (message.substring (getApplicationName().length() + 1));
  12374. }
  12375. static bool juceInitialisedGUI = false;
  12376. void JUCE_PUBLIC_FUNCTION initialiseJuce_GUI()
  12377. {
  12378. if (! juceInitialisedGUI)
  12379. {
  12380. #if JUCE_MAC
  12381. const ScopedAutoReleasePool pool;
  12382. #endif
  12383. juceInitialisedGUI = true;
  12384. initialiseJuce_NonGUI();
  12385. MessageManager::getInstance();
  12386. Font::initialiseDefaultFontNames();
  12387. LookAndFeel::setDefaultLookAndFeel (0);
  12388. #if JUCE_WIN32 && JUCE_DEBUG
  12389. // This section is just for catching people who mess up their project settings and
  12390. // turn RTTI off..
  12391. try
  12392. {
  12393. TextButton tb (String::empty);
  12394. Component* c = &tb;
  12395. // Got an exception here? Then TURN ON RTTI in your compiler settings!!
  12396. c = dynamic_cast <Button*> (c);
  12397. }
  12398. catch (...)
  12399. {
  12400. // Ended up here? If so, TURN ON RTTI in your compiler settings!! And if you
  12401. // got as far as this catch statement, then why haven't you got exception catching
  12402. // turned on in the debugger???
  12403. jassertfalse
  12404. }
  12405. #endif
  12406. }
  12407. }
  12408. void JUCE_PUBLIC_FUNCTION shutdownJuce_GUI()
  12409. {
  12410. if (juceInitialisedGUI)
  12411. {
  12412. #if JUCE_MAC
  12413. const ScopedAutoReleasePool pool;
  12414. #endif
  12415. DeletedAtShutdown::deleteAll();
  12416. LookAndFeel::clearDefaultLookAndFeel();
  12417. shutdownJuce_NonGUI();
  12418. juceInitialisedGUI = false;
  12419. }
  12420. }
  12421. END_JUCE_NAMESPACE
  12422. /********* End of inlined file: juce_Application.cpp *********/
  12423. /********* Start of inlined file: juce_ApplicationCommandInfo.cpp *********/
  12424. BEGIN_JUCE_NAMESPACE
  12425. ApplicationCommandInfo::ApplicationCommandInfo (const CommandID commandID_) throw()
  12426. : commandID (commandID_),
  12427. flags (0)
  12428. {
  12429. }
  12430. void ApplicationCommandInfo::setInfo (const String& shortName_,
  12431. const String& description_,
  12432. const String& categoryName_,
  12433. const int flags_) throw()
  12434. {
  12435. shortName = shortName_;
  12436. description = description_;
  12437. categoryName = categoryName_;
  12438. flags = flags_;
  12439. }
  12440. void ApplicationCommandInfo::setActive (const bool b) throw()
  12441. {
  12442. if (b)
  12443. flags &= ~isDisabled;
  12444. else
  12445. flags |= isDisabled;
  12446. }
  12447. void ApplicationCommandInfo::setTicked (const bool b) throw()
  12448. {
  12449. if (b)
  12450. flags |= isTicked;
  12451. else
  12452. flags &= ~isTicked;
  12453. }
  12454. void ApplicationCommandInfo::addDefaultKeypress (const int keyCode, const ModifierKeys& modifiers) throw()
  12455. {
  12456. defaultKeypresses.add (KeyPress (keyCode, modifiers, 0));
  12457. }
  12458. END_JUCE_NAMESPACE
  12459. /********* End of inlined file: juce_ApplicationCommandInfo.cpp *********/
  12460. /********* Start of inlined file: juce_ApplicationCommandManager.cpp *********/
  12461. BEGIN_JUCE_NAMESPACE
  12462. ApplicationCommandManager::ApplicationCommandManager()
  12463. : listeners (8),
  12464. firstTarget (0)
  12465. {
  12466. keyMappings = new KeyPressMappingSet (this);
  12467. Desktop::getInstance().addFocusChangeListener (this);
  12468. }
  12469. ApplicationCommandManager::~ApplicationCommandManager()
  12470. {
  12471. Desktop::getInstance().removeFocusChangeListener (this);
  12472. deleteAndZero (keyMappings);
  12473. }
  12474. void ApplicationCommandManager::clearCommands()
  12475. {
  12476. commands.clear();
  12477. keyMappings->clearAllKeyPresses();
  12478. triggerAsyncUpdate();
  12479. }
  12480. void ApplicationCommandManager::registerCommand (const ApplicationCommandInfo& newCommand)
  12481. {
  12482. // zero isn't a valid command ID!
  12483. jassert (newCommand.commandID != 0);
  12484. // the name isn't optional!
  12485. jassert (newCommand.shortName.isNotEmpty());
  12486. if (getCommandForID (newCommand.commandID) == 0)
  12487. {
  12488. ApplicationCommandInfo* const newInfo = new ApplicationCommandInfo (newCommand);
  12489. newInfo->flags &= ~ApplicationCommandInfo::isTicked;
  12490. commands.add (newInfo);
  12491. keyMappings->resetToDefaultMapping (newCommand.commandID);
  12492. triggerAsyncUpdate();
  12493. }
  12494. else
  12495. {
  12496. // trying to re-register the same command with different parameters?
  12497. jassert (newCommand.shortName == getCommandForID (newCommand.commandID)->shortName
  12498. && (newCommand.description == getCommandForID (newCommand.commandID)->description || newCommand.description.isEmpty())
  12499. && newCommand.categoryName == getCommandForID (newCommand.commandID)->categoryName
  12500. && newCommand.defaultKeypresses == getCommandForID (newCommand.commandID)->defaultKeypresses
  12501. && (newCommand.flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor))
  12502. == (getCommandForID (newCommand.commandID)->flags & (ApplicationCommandInfo::wantsKeyUpDownCallbacks | ApplicationCommandInfo::hiddenFromKeyEditor | ApplicationCommandInfo::readOnlyInKeyEditor)));
  12503. }
  12504. }
  12505. void ApplicationCommandManager::registerAllCommandsForTarget (ApplicationCommandTarget* target)
  12506. {
  12507. if (target != 0)
  12508. {
  12509. Array <CommandID> commandIDs;
  12510. target->getAllCommands (commandIDs);
  12511. for (int i = 0; i < commandIDs.size(); ++i)
  12512. {
  12513. ApplicationCommandInfo info (commandIDs.getUnchecked(i));
  12514. target->getCommandInfo (info.commandID, info);
  12515. registerCommand (info);
  12516. }
  12517. }
  12518. }
  12519. void ApplicationCommandManager::removeCommand (const CommandID commandID)
  12520. {
  12521. for (int i = commands.size(); --i >= 0;)
  12522. {
  12523. if (commands.getUnchecked (i)->commandID == commandID)
  12524. {
  12525. commands.remove (i);
  12526. triggerAsyncUpdate();
  12527. const Array <KeyPress> keys (keyMappings->getKeyPressesAssignedToCommand (commandID));
  12528. for (int j = keys.size(); --j >= 0;)
  12529. keyMappings->removeKeyPress (keys.getReference (j));
  12530. }
  12531. }
  12532. }
  12533. void ApplicationCommandManager::commandStatusChanged()
  12534. {
  12535. triggerAsyncUpdate();
  12536. }
  12537. const ApplicationCommandInfo* ApplicationCommandManager::getCommandForID (const CommandID commandID) const throw()
  12538. {
  12539. for (int i = commands.size(); --i >= 0;)
  12540. if (commands.getUnchecked(i)->commandID == commandID)
  12541. return commands.getUnchecked(i);
  12542. return 0;
  12543. }
  12544. const String ApplicationCommandManager::getNameOfCommand (const CommandID commandID) const throw()
  12545. {
  12546. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  12547. return (ci != 0) ? ci->shortName : String::empty;
  12548. }
  12549. const String ApplicationCommandManager::getDescriptionOfCommand (const CommandID commandID) const throw()
  12550. {
  12551. const ApplicationCommandInfo* const ci = getCommandForID (commandID);
  12552. return (ci != 0) ? (ci->description.isNotEmpty() ? ci->description : ci->shortName)
  12553. : String::empty;
  12554. }
  12555. const StringArray ApplicationCommandManager::getCommandCategories() const throw()
  12556. {
  12557. StringArray s;
  12558. for (int i = 0; i < commands.size(); ++i)
  12559. s.addIfNotAlreadyThere (commands.getUnchecked(i)->categoryName, false);
  12560. return s;
  12561. }
  12562. const Array <CommandID> ApplicationCommandManager::getCommandsInCategory (const String& categoryName) const throw()
  12563. {
  12564. Array <CommandID> results (4);
  12565. for (int i = 0; i < commands.size(); ++i)
  12566. if (commands.getUnchecked(i)->categoryName == categoryName)
  12567. results.add (commands.getUnchecked(i)->commandID);
  12568. return results;
  12569. }
  12570. bool ApplicationCommandManager::invokeDirectly (const CommandID commandID, const bool asynchronously)
  12571. {
  12572. ApplicationCommandTarget::InvocationInfo info (commandID);
  12573. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  12574. return invoke (info, asynchronously);
  12575. }
  12576. bool ApplicationCommandManager::invoke (const ApplicationCommandTarget::InvocationInfo& info_, const bool asynchronously)
  12577. {
  12578. // This call isn't thread-safe for use from a non-UI thread without locking the message
  12579. // manager first..
  12580. jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  12581. ApplicationCommandTarget* const target = getFirstCommandTarget (info_.commandID);
  12582. if (target == 0)
  12583. return false;
  12584. ApplicationCommandInfo commandInfo (0);
  12585. target->getCommandInfo (info_.commandID, commandInfo);
  12586. ApplicationCommandTarget::InvocationInfo info (info_);
  12587. info.commandFlags = commandInfo.flags;
  12588. sendListenerInvokeCallback (info);
  12589. const bool ok = target->invoke (info, asynchronously);
  12590. commandStatusChanged();
  12591. return ok;
  12592. }
  12593. ApplicationCommandTarget* ApplicationCommandManager::getFirstCommandTarget (const CommandID)
  12594. {
  12595. return firstTarget != 0 ? firstTarget
  12596. : findDefaultComponentTarget();
  12597. }
  12598. void ApplicationCommandManager::setFirstCommandTarget (ApplicationCommandTarget* const newTarget) throw()
  12599. {
  12600. firstTarget = newTarget;
  12601. }
  12602. ApplicationCommandTarget* ApplicationCommandManager::getTargetForCommand (const CommandID commandID,
  12603. ApplicationCommandInfo& upToDateInfo)
  12604. {
  12605. ApplicationCommandTarget* target = getFirstCommandTarget (commandID);
  12606. if (target == 0)
  12607. target = JUCEApplication::getInstance();
  12608. if (target != 0)
  12609. target = target->getTargetForCommand (commandID);
  12610. if (target != 0)
  12611. target->getCommandInfo (commandID, upToDateInfo);
  12612. return target;
  12613. }
  12614. ApplicationCommandTarget* ApplicationCommandManager::findTargetForComponent (Component* c)
  12615. {
  12616. ApplicationCommandTarget* target = dynamic_cast <ApplicationCommandTarget*> (c);
  12617. if (target == 0 && c != 0)
  12618. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  12619. target = c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  12620. return target;
  12621. }
  12622. ApplicationCommandTarget* ApplicationCommandManager::findDefaultComponentTarget()
  12623. {
  12624. Component* c = Component::getCurrentlyFocusedComponent();
  12625. if (c == 0)
  12626. {
  12627. TopLevelWindow* const activeWindow = TopLevelWindow::getActiveTopLevelWindow();
  12628. if (activeWindow != 0)
  12629. {
  12630. c = activeWindow->getPeer()->getLastFocusedSubcomponent();
  12631. if (c == 0)
  12632. c = activeWindow;
  12633. }
  12634. }
  12635. if (c == 0 && Process::isForegroundProcess())
  12636. {
  12637. // getting a bit desperate now - try all desktop comps..
  12638. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  12639. {
  12640. ApplicationCommandTarget* const target
  12641. = findTargetForComponent (Desktop::getInstance().getComponent (i)
  12642. ->getPeer()->getLastFocusedSubcomponent());
  12643. if (target != 0)
  12644. return target;
  12645. }
  12646. }
  12647. if (c != 0)
  12648. {
  12649. ResizableWindow* const resizableWindow = dynamic_cast <ResizableWindow*> (c);
  12650. // if we're focused on a ResizableWindow, chances are that it's the content
  12651. // component that really should get the event. And if not, the event will
  12652. // still be passed up to the top level window anyway, so let's send it to the
  12653. // content comp.
  12654. if (resizableWindow != 0 && resizableWindow->getContentComponent() != 0)
  12655. c = resizableWindow->getContentComponent();
  12656. ApplicationCommandTarget* const target = findTargetForComponent (c);
  12657. if (target != 0)
  12658. return target;
  12659. }
  12660. return JUCEApplication::getInstance();
  12661. }
  12662. void ApplicationCommandManager::addListener (ApplicationCommandManagerListener* const listener) throw()
  12663. {
  12664. jassert (listener != 0);
  12665. if (listener != 0)
  12666. listeners.add (listener);
  12667. }
  12668. void ApplicationCommandManager::removeListener (ApplicationCommandManagerListener* const listener) throw()
  12669. {
  12670. listeners.removeValue (listener);
  12671. }
  12672. void ApplicationCommandManager::sendListenerInvokeCallback (const ApplicationCommandTarget::InvocationInfo& info) const
  12673. {
  12674. for (int i = listeners.size(); --i >= 0;)
  12675. {
  12676. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandInvoked (info);
  12677. i = jmin (i, listeners.size());
  12678. }
  12679. }
  12680. void ApplicationCommandManager::handleAsyncUpdate()
  12681. {
  12682. for (int i = listeners.size(); --i >= 0;)
  12683. {
  12684. ((ApplicationCommandManagerListener*) listeners.getUnchecked (i))->applicationCommandListChanged();
  12685. i = jmin (i, listeners.size());
  12686. }
  12687. }
  12688. void ApplicationCommandManager::globalFocusChanged (Component*)
  12689. {
  12690. commandStatusChanged();
  12691. }
  12692. END_JUCE_NAMESPACE
  12693. /********* End of inlined file: juce_ApplicationCommandManager.cpp *********/
  12694. /********* Start of inlined file: juce_ApplicationCommandTarget.cpp *********/
  12695. BEGIN_JUCE_NAMESPACE
  12696. ApplicationCommandTarget::ApplicationCommandTarget()
  12697. : messageInvoker (0)
  12698. {
  12699. }
  12700. ApplicationCommandTarget::~ApplicationCommandTarget()
  12701. {
  12702. deleteAndZero (messageInvoker);
  12703. }
  12704. bool ApplicationCommandTarget::tryToInvoke (const InvocationInfo& info, const bool async)
  12705. {
  12706. if (isCommandActive (info.commandID))
  12707. {
  12708. if (async)
  12709. {
  12710. if (messageInvoker == 0)
  12711. messageInvoker = new CommandTargetMessageInvoker (this);
  12712. messageInvoker->postMessage (new Message (0, 0, 0, new ApplicationCommandTarget::InvocationInfo (info)));
  12713. return true;
  12714. }
  12715. else
  12716. {
  12717. const bool success = perform (info);
  12718. jassert (success); // hmm - your target should have been able to perform this command. If it can't
  12719. // do it at the moment for some reason, it should clear the 'isActive' flag when it
  12720. // returns the command's info.
  12721. return success;
  12722. }
  12723. }
  12724. return false;
  12725. }
  12726. ApplicationCommandTarget* ApplicationCommandTarget::findFirstTargetParentComponent()
  12727. {
  12728. Component* c = dynamic_cast <Component*> (this);
  12729. if (c != 0)
  12730. // (unable to use the syntax findParentComponentOfClass <ApplicationCommandTarget> () because of a VC6 compiler bug)
  12731. return c->findParentComponentOfClass ((ApplicationCommandTarget*) 0);
  12732. return 0;
  12733. }
  12734. ApplicationCommandTarget* ApplicationCommandTarget::getTargetForCommand (const CommandID commandID)
  12735. {
  12736. ApplicationCommandTarget* target = this;
  12737. int depth = 0;
  12738. while (target != 0)
  12739. {
  12740. Array <CommandID> commandIDs;
  12741. target->getAllCommands (commandIDs);
  12742. if (commandIDs.contains (commandID))
  12743. return target;
  12744. target = target->getNextCommandTarget();
  12745. ++depth;
  12746. jassert (depth < 100); // could be a recursive command chain??
  12747. jassert (target != this); // definitely a recursive command chain!
  12748. if (depth > 100 || target == this)
  12749. break;
  12750. }
  12751. if (target == 0)
  12752. {
  12753. target = JUCEApplication::getInstance();
  12754. if (target != 0)
  12755. {
  12756. Array <CommandID> commandIDs;
  12757. target->getAllCommands (commandIDs);
  12758. if (commandIDs.contains (commandID))
  12759. return target;
  12760. }
  12761. }
  12762. return 0;
  12763. }
  12764. bool ApplicationCommandTarget::isCommandActive (const CommandID commandID)
  12765. {
  12766. ApplicationCommandInfo info (commandID);
  12767. info.flags = ApplicationCommandInfo::isDisabled;
  12768. getCommandInfo (commandID, info);
  12769. return (info.flags & ApplicationCommandInfo::isDisabled) == 0;
  12770. }
  12771. bool ApplicationCommandTarget::invoke (const InvocationInfo& info, const bool async)
  12772. {
  12773. ApplicationCommandTarget* target = this;
  12774. int depth = 0;
  12775. while (target != 0)
  12776. {
  12777. if (target->tryToInvoke (info, async))
  12778. return true;
  12779. target = target->getNextCommandTarget();
  12780. ++depth;
  12781. jassert (depth < 100); // could be a recursive command chain??
  12782. jassert (target != this); // definitely a recursive command chain!
  12783. if (depth > 100 || target == this)
  12784. break;
  12785. }
  12786. if (target == 0)
  12787. {
  12788. target = JUCEApplication::getInstance();
  12789. if (target != 0)
  12790. return target->tryToInvoke (info, async);
  12791. }
  12792. return false;
  12793. }
  12794. bool ApplicationCommandTarget::invokeDirectly (const CommandID commandID, const bool asynchronously)
  12795. {
  12796. ApplicationCommandTarget::InvocationInfo info (commandID);
  12797. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::direct;
  12798. return invoke (info, asynchronously);
  12799. }
  12800. ApplicationCommandTarget::InvocationInfo::InvocationInfo (const CommandID commandID_) throw()
  12801. : commandID (commandID_),
  12802. commandFlags (0),
  12803. invocationMethod (direct),
  12804. originatingComponent (0),
  12805. isKeyDown (false),
  12806. millisecsSinceKeyPressed (0)
  12807. {
  12808. }
  12809. ApplicationCommandTarget::CommandTargetMessageInvoker::CommandTargetMessageInvoker (ApplicationCommandTarget* const owner_)
  12810. : owner (owner_)
  12811. {
  12812. }
  12813. ApplicationCommandTarget::CommandTargetMessageInvoker::~CommandTargetMessageInvoker()
  12814. {
  12815. }
  12816. void ApplicationCommandTarget::CommandTargetMessageInvoker::handleMessage (const Message& message)
  12817. {
  12818. InvocationInfo* const info = (InvocationInfo*) message.pointerParameter;
  12819. owner->tryToInvoke (*info, false);
  12820. delete info;
  12821. }
  12822. END_JUCE_NAMESPACE
  12823. /********* End of inlined file: juce_ApplicationCommandTarget.cpp *********/
  12824. /********* Start of inlined file: juce_ApplicationProperties.cpp *********/
  12825. BEGIN_JUCE_NAMESPACE
  12826. juce_ImplementSingleton (ApplicationProperties)
  12827. ApplicationProperties::ApplicationProperties() throw()
  12828. : userProps (0),
  12829. commonProps (0),
  12830. msBeforeSaving (3000),
  12831. options (PropertiesFile::storeAsBinary),
  12832. commonSettingsAreReadOnly (0)
  12833. {
  12834. }
  12835. ApplicationProperties::~ApplicationProperties()
  12836. {
  12837. closeFiles();
  12838. clearSingletonInstance();
  12839. }
  12840. void ApplicationProperties::setStorageParameters (const String& applicationName,
  12841. const String& fileNameSuffix,
  12842. const String& folderName_,
  12843. const int millisecondsBeforeSaving,
  12844. const int propertiesFileOptions) throw()
  12845. {
  12846. appName = applicationName;
  12847. fileSuffix = fileNameSuffix;
  12848. folderName = folderName_;
  12849. msBeforeSaving = millisecondsBeforeSaving;
  12850. options = propertiesFileOptions;
  12851. }
  12852. bool ApplicationProperties::testWriteAccess (const bool testUserSettings,
  12853. const bool testCommonSettings,
  12854. const bool showWarningDialogOnFailure)
  12855. {
  12856. const bool userOk = (! testUserSettings) || getUserSettings()->save();
  12857. const bool commonOk = (! testCommonSettings) || getCommonSettings (false)->save();
  12858. if (! (userOk && commonOk))
  12859. {
  12860. if (showWarningDialogOnFailure)
  12861. {
  12862. String filenames;
  12863. if (userProps != 0 && ! userOk)
  12864. filenames << '\n' << userProps->getFile().getFullPathName();
  12865. if (commonProps != 0 && ! commonOk)
  12866. filenames << '\n' << commonProps->getFile().getFullPathName();
  12867. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  12868. appName + TRANS(" - Unable to save settings"),
  12869. TRANS("An error occurred when trying to save the application's settings file...\n\nIn order to save and restore its settings, ")
  12870. + appName + TRANS(" needs to be able to write to the following files:\n")
  12871. + filenames
  12872. + TRANS("\n\nMake sure that these files aren't read-only, and that the disk isn't full."));
  12873. }
  12874. return false;
  12875. }
  12876. return true;
  12877. }
  12878. void ApplicationProperties::openFiles() throw()
  12879. {
  12880. // You need to call setStorageParameters() before trying to get hold of the
  12881. // properties!
  12882. jassert (appName.isNotEmpty());
  12883. if (appName.isNotEmpty())
  12884. {
  12885. if (userProps == 0)
  12886. userProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  12887. false, msBeforeSaving, options);
  12888. if (commonProps == 0)
  12889. commonProps = PropertiesFile::createDefaultAppPropertiesFile (appName, fileSuffix, folderName,
  12890. true, msBeforeSaving, options);
  12891. userProps->setFallbackPropertySet (commonProps);
  12892. }
  12893. }
  12894. PropertiesFile* ApplicationProperties::getUserSettings() throw()
  12895. {
  12896. if (userProps == 0)
  12897. openFiles();
  12898. return userProps;
  12899. }
  12900. PropertiesFile* ApplicationProperties::getCommonSettings (const bool returnUserPropsIfReadOnly) throw()
  12901. {
  12902. if (commonProps == 0)
  12903. openFiles();
  12904. if (returnUserPropsIfReadOnly)
  12905. {
  12906. if (commonSettingsAreReadOnly == 0)
  12907. commonSettingsAreReadOnly = commonProps->save() ? -1 : 1;
  12908. if (commonSettingsAreReadOnly > 0)
  12909. return userProps;
  12910. }
  12911. return commonProps;
  12912. }
  12913. bool ApplicationProperties::saveIfNeeded()
  12914. {
  12915. return (userProps == 0 || userProps->saveIfNeeded())
  12916. && (commonProps == 0 || commonProps->saveIfNeeded());
  12917. }
  12918. void ApplicationProperties::closeFiles()
  12919. {
  12920. deleteAndZero (userProps);
  12921. deleteAndZero (commonProps);
  12922. }
  12923. END_JUCE_NAMESPACE
  12924. /********* End of inlined file: juce_ApplicationProperties.cpp *********/
  12925. /********* Start of inlined file: juce_DeletedAtShutdown.cpp *********/
  12926. BEGIN_JUCE_NAMESPACE
  12927. static VoidArray objectsToDelete (16);
  12928. static CriticalSection lock;
  12929. DeletedAtShutdown::DeletedAtShutdown() throw()
  12930. {
  12931. const ScopedLock sl (lock);
  12932. objectsToDelete.add (this);
  12933. }
  12934. DeletedAtShutdown::~DeletedAtShutdown()
  12935. {
  12936. const ScopedLock sl (lock);
  12937. objectsToDelete.removeValue (this);
  12938. }
  12939. void DeletedAtShutdown::deleteAll()
  12940. {
  12941. // make a local copy of the array, so it can't get into a loop if something
  12942. // creates another DeletedAtShutdown object during its destructor.
  12943. lock.enter();
  12944. const VoidArray localCopy (objectsToDelete);
  12945. lock.exit();
  12946. for (int i = localCopy.size(); --i >= 0;)
  12947. {
  12948. JUCE_TRY
  12949. {
  12950. DeletedAtShutdown* const deletee = (DeletedAtShutdown*) localCopy.getUnchecked(i);
  12951. // double-check that it's not already been deleted during another object's destructor.
  12952. lock.enter();
  12953. const bool okToDelete = objectsToDelete.contains (deletee);
  12954. lock.exit();
  12955. if (okToDelete)
  12956. delete deletee;
  12957. }
  12958. JUCE_CATCH_EXCEPTION
  12959. }
  12960. // if no objects got re-created during shutdown, this should have been emptied by their
  12961. // destructors
  12962. jassert (objectsToDelete.size() == 0);
  12963. objectsToDelete.clear(); // just to make sure the array doesn't have any memory still allocated
  12964. }
  12965. END_JUCE_NAMESPACE
  12966. /********* End of inlined file: juce_DeletedAtShutdown.cpp *********/
  12967. /********* Start of inlined file: juce_PropertiesFile.cpp *********/
  12968. BEGIN_JUCE_NAMESPACE
  12969. static const int propFileMagicNumber = ((int) littleEndianInt ("PROP"));
  12970. static const int propFileMagicNumberCompressed = ((int) littleEndianInt ("CPRP"));
  12971. static const tchar* const propertyFileXmlTag = T("PROPERTIES");
  12972. static const tchar* const propertyTagName = T("VALUE");
  12973. PropertiesFile::PropertiesFile (const File& f,
  12974. const int millisecondsBeforeSaving,
  12975. const int options_) throw()
  12976. : PropertySet (ignoreCaseOfKeyNames),
  12977. file (f),
  12978. timerInterval (millisecondsBeforeSaving),
  12979. options (options_),
  12980. needsWriting (false)
  12981. {
  12982. // You need to correctly specify just one storage format for the file
  12983. jassert ((options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsBinary
  12984. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsCompressedBinary
  12985. || (options_ & (storeAsBinary | storeAsCompressedBinary | storeAsXML)) == storeAsXML);
  12986. InputStream* fileStream = f.createInputStream();
  12987. if (fileStream != 0)
  12988. {
  12989. int magicNumber = fileStream->readInt();
  12990. if (magicNumber == propFileMagicNumberCompressed)
  12991. {
  12992. fileStream = new SubregionStream (fileStream, 4, -1, true);
  12993. fileStream = new GZIPDecompressorInputStream (fileStream, true);
  12994. magicNumber = propFileMagicNumber;
  12995. }
  12996. if (magicNumber == propFileMagicNumber)
  12997. {
  12998. BufferedInputStream in (fileStream, 2048, true);
  12999. int numValues = in.readInt();
  13000. while (--numValues >= 0 && ! in.isExhausted())
  13001. {
  13002. const String key (in.readString());
  13003. const String value (in.readString());
  13004. jassert (key.isNotEmpty());
  13005. if (key.isNotEmpty())
  13006. getAllProperties().set (key, value);
  13007. }
  13008. }
  13009. else
  13010. {
  13011. // Not a binary props file - let's see if it's XML..
  13012. delete fileStream;
  13013. XmlDocument parser (f);
  13014. XmlElement* doc = parser.getDocumentElement (true);
  13015. if (doc != 0 && doc->hasTagName (propertyFileXmlTag))
  13016. {
  13017. delete doc;
  13018. doc = parser.getDocumentElement();
  13019. if (doc != 0)
  13020. {
  13021. forEachXmlChildElementWithTagName (*doc, e, propertyTagName)
  13022. {
  13023. const String name (e->getStringAttribute (T("name")));
  13024. if (name.isNotEmpty())
  13025. {
  13026. getAllProperties().set (name,
  13027. e->getFirstChildElement() != 0
  13028. ? e->getFirstChildElement()->createDocument (String::empty, true)
  13029. : e->getStringAttribute (T("val")));
  13030. }
  13031. }
  13032. }
  13033. else
  13034. {
  13035. // must be a pretty broken XML file we're trying to parse here!
  13036. jassertfalse
  13037. }
  13038. delete doc;
  13039. }
  13040. }
  13041. }
  13042. }
  13043. PropertiesFile::~PropertiesFile()
  13044. {
  13045. saveIfNeeded();
  13046. }
  13047. bool PropertiesFile::saveIfNeeded()
  13048. {
  13049. const ScopedLock sl (getLock());
  13050. return (! needsWriting) || save();
  13051. }
  13052. bool PropertiesFile::needsToBeSaved() const throw()
  13053. {
  13054. const ScopedLock sl (getLock());
  13055. return needsWriting;
  13056. }
  13057. bool PropertiesFile::save()
  13058. {
  13059. const ScopedLock sl (getLock());
  13060. stopTimer();
  13061. if (file == File::nonexistent
  13062. || file.isDirectory()
  13063. || ! file.getParentDirectory().createDirectory())
  13064. return false;
  13065. if ((options & storeAsXML) != 0)
  13066. {
  13067. XmlElement* const doc = new XmlElement (propertyFileXmlTag);
  13068. for (int i = 0; i < getAllProperties().size(); ++i)
  13069. {
  13070. XmlElement* const e = new XmlElement (propertyTagName);
  13071. e->setAttribute (T("name"), getAllProperties().getAllKeys() [i]);
  13072. // if the value seems to contain xml, store it as such..
  13073. XmlDocument xmlContent (getAllProperties().getAllValues() [i]);
  13074. XmlElement* const childElement = xmlContent.getDocumentElement();
  13075. if (childElement != 0)
  13076. e->addChildElement (childElement);
  13077. else
  13078. e->setAttribute (T("val"), getAllProperties().getAllValues() [i]);
  13079. doc->addChildElement (e);
  13080. }
  13081. const bool ok = doc->writeToFile (file, String::empty);
  13082. delete doc;
  13083. return ok;
  13084. }
  13085. else
  13086. {
  13087. const File tempFile (file.getNonexistentSibling (false));
  13088. OutputStream* out = tempFile.createOutputStream();
  13089. if (out != 0)
  13090. {
  13091. if ((options & storeAsCompressedBinary) != 0)
  13092. {
  13093. out->writeInt (propFileMagicNumberCompressed);
  13094. out->flush();
  13095. out = new GZIPCompressorOutputStream (out, 9, true);
  13096. }
  13097. else
  13098. {
  13099. // have you set up the storage option flags correctly?
  13100. jassert ((options & storeAsBinary) != 0);
  13101. out->writeInt (propFileMagicNumber);
  13102. }
  13103. const int numProperties = getAllProperties().size();
  13104. out->writeInt (numProperties);
  13105. for (int i = 0; i < numProperties; ++i)
  13106. {
  13107. out->writeString (getAllProperties().getAllKeys() [i]);
  13108. out->writeString (getAllProperties().getAllValues() [i]);
  13109. }
  13110. out->flush();
  13111. delete out;
  13112. if (tempFile.moveFileTo (file))
  13113. {
  13114. needsWriting = false;
  13115. return true;
  13116. }
  13117. tempFile.deleteFile();
  13118. }
  13119. }
  13120. return false;
  13121. }
  13122. void PropertiesFile::timerCallback()
  13123. {
  13124. saveIfNeeded();
  13125. }
  13126. void PropertiesFile::propertyChanged()
  13127. {
  13128. sendChangeMessage (this);
  13129. needsWriting = true;
  13130. if (timerInterval > 0)
  13131. startTimer (timerInterval);
  13132. else if (timerInterval == 0)
  13133. saveIfNeeded();
  13134. }
  13135. const File PropertiesFile::getFile() const throw()
  13136. {
  13137. return file;
  13138. }
  13139. const File PropertiesFile::getDefaultAppSettingsFile (const String& applicationName,
  13140. const String& fileNameSuffix,
  13141. const String& folderName,
  13142. const bool commonToAllUsers)
  13143. {
  13144. // mustn't have illegal characters in this name..
  13145. jassert (applicationName == File::createLegalFileName (applicationName));
  13146. #if JUCE_MAC
  13147. File dir (commonToAllUsers ? "/Library/Preferences"
  13148. : "~/Library/Preferences");
  13149. if (folderName.isNotEmpty())
  13150. dir = dir.getChildFile (folderName);
  13151. #endif
  13152. #ifdef JUCE_LINUX
  13153. const File dir ((commonToAllUsers ? T("/var/") : T("~/"))
  13154. + (folderName.isNotEmpty() ? folderName
  13155. : (T(".") + applicationName)));
  13156. #endif
  13157. #if JUCE_WIN32
  13158. File dir (File::getSpecialLocation (commonToAllUsers ? File::commonApplicationDataDirectory
  13159. : File::userApplicationDataDirectory));
  13160. if (dir == File::nonexistent)
  13161. return File::nonexistent;
  13162. dir = dir.getChildFile (folderName.isNotEmpty() ? folderName
  13163. : applicationName);
  13164. #endif
  13165. return dir.getChildFile (applicationName)
  13166. .withFileExtension (fileNameSuffix);
  13167. }
  13168. PropertiesFile* PropertiesFile::createDefaultAppPropertiesFile (const String& applicationName,
  13169. const String& fileNameSuffix,
  13170. const String& folderName,
  13171. const bool commonToAllUsers,
  13172. const int millisecondsBeforeSaving,
  13173. const int propertiesFileOptions)
  13174. {
  13175. const File file (getDefaultAppSettingsFile (applicationName,
  13176. fileNameSuffix,
  13177. folderName,
  13178. commonToAllUsers));
  13179. jassert (file != File::nonexistent);
  13180. if (file == File::nonexistent)
  13181. return 0;
  13182. return new PropertiesFile (file, millisecondsBeforeSaving, propertiesFileOptions);
  13183. }
  13184. END_JUCE_NAMESPACE
  13185. /********* End of inlined file: juce_PropertiesFile.cpp *********/
  13186. /********* Start of inlined file: juce_AiffAudioFormat.cpp *********/
  13187. BEGIN_JUCE_NAMESPACE
  13188. #undef chunkName
  13189. #define chunkName(a) (int)littleEndianInt(a)
  13190. #define aiffFormatName TRANS("AIFF file")
  13191. static const tchar* const aiffExtensions[] = { T(".aiff"), T(".aif"), 0 };
  13192. class AiffAudioFormatReader : public AudioFormatReader
  13193. {
  13194. public:
  13195. int bytesPerFrame;
  13196. int64 dataChunkStart;
  13197. bool littleEndian;
  13198. AiffAudioFormatReader (InputStream* in)
  13199. : AudioFormatReader (in, aiffFormatName)
  13200. {
  13201. if (input->readInt() == chunkName ("FORM"))
  13202. {
  13203. const int len = input->readIntBigEndian();
  13204. const int64 end = input->getPosition() + len;
  13205. const int nextType = input->readInt();
  13206. if (nextType == chunkName ("AIFF") || nextType == chunkName ("AIFC"))
  13207. {
  13208. bool hasGotVer = false;
  13209. bool hasGotData = false;
  13210. bool hasGotType = false;
  13211. while (input->getPosition() < end)
  13212. {
  13213. const int type = input->readInt();
  13214. const uint32 length = (uint32) input->readIntBigEndian();
  13215. const int64 chunkEnd = input->getPosition() + length;
  13216. if (type == chunkName ("FVER"))
  13217. {
  13218. hasGotVer = true;
  13219. const int ver = input->readIntBigEndian();
  13220. if (ver != 0 && ver != (int)0xa2805140)
  13221. break;
  13222. }
  13223. else if (type == chunkName ("COMM"))
  13224. {
  13225. hasGotType = true;
  13226. numChannels = (unsigned int)input->readShortBigEndian();
  13227. lengthInSamples = input->readIntBigEndian();
  13228. bitsPerSample = input->readShortBigEndian();
  13229. bytesPerFrame = (numChannels * bitsPerSample) >> 3;
  13230. unsigned char sampleRateBytes[10];
  13231. input->read (sampleRateBytes, 10);
  13232. const int byte0 = sampleRateBytes[0];
  13233. if ((byte0 & 0x80) != 0
  13234. || byte0 <= 0x3F || byte0 > 0x40
  13235. || (byte0 == 0x40 && sampleRateBytes[1] > 0x1C))
  13236. break;
  13237. unsigned int sampRate = bigEndianInt ((char*) sampleRateBytes + 2);
  13238. sampRate >>= (16414 - bigEndianShort ((char*) sampleRateBytes));
  13239. sampleRate = (int)sampRate;
  13240. if (length <= 18)
  13241. {
  13242. // some types don't have a chunk large enough to include a compression
  13243. // type, so assume it's just big-endian pcm
  13244. littleEndian = false;
  13245. }
  13246. else
  13247. {
  13248. const int compType = input->readInt();
  13249. if (compType == chunkName ("NONE") || compType == chunkName ("twos"))
  13250. {
  13251. littleEndian = false;
  13252. }
  13253. else if (compType == chunkName ("sowt"))
  13254. {
  13255. littleEndian = true;
  13256. }
  13257. else
  13258. {
  13259. sampleRate = 0;
  13260. break;
  13261. }
  13262. }
  13263. }
  13264. else if (type == chunkName ("SSND"))
  13265. {
  13266. hasGotData = true;
  13267. const int offset = input->readIntBigEndian();
  13268. dataChunkStart = input->getPosition() + 4 + offset;
  13269. lengthInSamples = (bytesPerFrame > 0) ? jmin (lengthInSamples, (int64) (length / bytesPerFrame)) : 0;
  13270. }
  13271. else if ((hasGotVer && hasGotData && hasGotType)
  13272. || chunkEnd < input->getPosition()
  13273. || input->isExhausted())
  13274. {
  13275. break;
  13276. }
  13277. input->setPosition (chunkEnd);
  13278. }
  13279. }
  13280. }
  13281. }
  13282. ~AiffAudioFormatReader()
  13283. {
  13284. }
  13285. bool read (int** destSamples,
  13286. int64 startSampleInFile,
  13287. int numSamples)
  13288. {
  13289. int64 start = startSampleInFile;
  13290. int startOffsetInDestBuffer = 0;
  13291. if (startSampleInFile < 0)
  13292. {
  13293. const int silence = (int) jmin (-startSampleInFile, (int64) numSamples);
  13294. int** destChan = destSamples;
  13295. for (int i = 2; --i >= 0;)
  13296. {
  13297. if (*destChan != 0)
  13298. {
  13299. zeromem (*destChan, sizeof (int) * silence);
  13300. ++destChan;
  13301. }
  13302. }
  13303. startOffsetInDestBuffer += silence;
  13304. numSamples -= silence;
  13305. start = 0;
  13306. }
  13307. int numToDo = jlimit (0, numSamples, (int) (lengthInSamples - start));
  13308. if (numToDo > 0)
  13309. {
  13310. input->setPosition (dataChunkStart + start * bytesPerFrame);
  13311. int num = numToDo;
  13312. int* left = destSamples[0];
  13313. if (left != 0)
  13314. left += startOffsetInDestBuffer;
  13315. int* right = destSamples[1];
  13316. if (right != 0)
  13317. right += startOffsetInDestBuffer;
  13318. // (keep this a multiple of 3)
  13319. const int tempBufSize = 1440 * 4;
  13320. char tempBuffer [tempBufSize];
  13321. while (num > 0)
  13322. {
  13323. const int numThisTime = jmin (tempBufSize / bytesPerFrame, num);
  13324. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  13325. if (bytesRead < numThisTime * bytesPerFrame)
  13326. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  13327. if (bitsPerSample == 16)
  13328. {
  13329. if (littleEndian)
  13330. {
  13331. const short* src = (const short*) tempBuffer;
  13332. if (numChannels > 1)
  13333. {
  13334. if (left == 0)
  13335. {
  13336. for (int i = numThisTime; --i >= 0;)
  13337. {
  13338. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  13339. ++src;
  13340. }
  13341. }
  13342. else if (right == 0)
  13343. {
  13344. for (int i = numThisTime; --i >= 0;)
  13345. {
  13346. ++src;
  13347. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  13348. }
  13349. }
  13350. else
  13351. {
  13352. for (int i = numThisTime; --i >= 0;)
  13353. {
  13354. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  13355. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  13356. }
  13357. }
  13358. }
  13359. else
  13360. {
  13361. for (int i = numThisTime; --i >= 0;)
  13362. {
  13363. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  13364. }
  13365. }
  13366. }
  13367. else
  13368. {
  13369. const char* src = (const char*) tempBuffer;
  13370. if (numChannels > 1)
  13371. {
  13372. if (left == 0)
  13373. {
  13374. for (int i = numThisTime; --i >= 0;)
  13375. {
  13376. *right++ = bigEndianShort (src) << 16;
  13377. src += 4;
  13378. }
  13379. }
  13380. else if (right == 0)
  13381. {
  13382. for (int i = numThisTime; --i >= 0;)
  13383. {
  13384. src += 2;
  13385. *left++ = bigEndianShort (src) << 16;
  13386. src += 2;
  13387. }
  13388. }
  13389. else
  13390. {
  13391. for (int i = numThisTime; --i >= 0;)
  13392. {
  13393. *left++ = bigEndianShort (src) << 16;
  13394. src += 2;
  13395. *right++ = bigEndianShort (src) << 16;
  13396. src += 2;
  13397. }
  13398. }
  13399. }
  13400. else
  13401. {
  13402. for (int i = numThisTime; --i >= 0;)
  13403. {
  13404. *left++ = bigEndianShort (src) << 16;
  13405. src += 2;
  13406. }
  13407. }
  13408. }
  13409. }
  13410. else if (bitsPerSample == 24)
  13411. {
  13412. const char* src = (const char*)tempBuffer;
  13413. if (littleEndian)
  13414. {
  13415. if (numChannels > 1)
  13416. {
  13417. if (left == 0)
  13418. {
  13419. for (int i = numThisTime; --i >= 0;)
  13420. {
  13421. *right++ = littleEndian24Bit (src) << 8;
  13422. src += 6;
  13423. }
  13424. }
  13425. else if (right == 0)
  13426. {
  13427. for (int i = numThisTime; --i >= 0;)
  13428. {
  13429. src += 3;
  13430. *left++ = littleEndian24Bit (src) << 8;
  13431. src += 3;
  13432. }
  13433. }
  13434. else
  13435. {
  13436. for (int i = numThisTime; --i >= 0;)
  13437. {
  13438. *left++ = littleEndian24Bit (src) << 8;
  13439. src += 3;
  13440. *right++ = littleEndian24Bit (src) << 8;
  13441. src += 3;
  13442. }
  13443. }
  13444. }
  13445. else
  13446. {
  13447. for (int i = numThisTime; --i >= 0;)
  13448. {
  13449. *left++ = littleEndian24Bit (src) << 8;
  13450. src += 3;
  13451. }
  13452. }
  13453. }
  13454. else
  13455. {
  13456. if (numChannels > 1)
  13457. {
  13458. if (left == 0)
  13459. {
  13460. for (int i = numThisTime; --i >= 0;)
  13461. {
  13462. *right++ = bigEndian24Bit (src) << 8;
  13463. src += 6;
  13464. }
  13465. }
  13466. else if (right == 0)
  13467. {
  13468. for (int i = numThisTime; --i >= 0;)
  13469. {
  13470. src += 3;
  13471. *left++ = bigEndian24Bit (src) << 8;
  13472. src += 3;
  13473. }
  13474. }
  13475. else
  13476. {
  13477. for (int i = numThisTime; --i >= 0;)
  13478. {
  13479. *left++ = bigEndian24Bit (src) << 8;
  13480. src += 3;
  13481. *right++ = bigEndian24Bit (src) << 8;
  13482. src += 3;
  13483. }
  13484. }
  13485. }
  13486. else
  13487. {
  13488. for (int i = numThisTime; --i >= 0;)
  13489. {
  13490. *left++ = bigEndian24Bit (src) << 8;
  13491. src += 3;
  13492. }
  13493. }
  13494. }
  13495. }
  13496. else if (bitsPerSample == 32)
  13497. {
  13498. const unsigned int* src = (const unsigned int*) tempBuffer;
  13499. unsigned int* l = (unsigned int*) left;
  13500. unsigned int* r = (unsigned int*) right;
  13501. if (littleEndian)
  13502. {
  13503. if (numChannels > 1)
  13504. {
  13505. if (l == 0)
  13506. {
  13507. for (int i = numThisTime; --i >= 0;)
  13508. {
  13509. ++src;
  13510. *r++ = swapIfBigEndian (*src++);
  13511. }
  13512. }
  13513. else if (r == 0)
  13514. {
  13515. for (int i = numThisTime; --i >= 0;)
  13516. {
  13517. *l++ = swapIfBigEndian (*src++);
  13518. ++src;
  13519. }
  13520. }
  13521. else
  13522. {
  13523. for (int i = numThisTime; --i >= 0;)
  13524. {
  13525. *l++ = swapIfBigEndian (*src++);
  13526. *r++ = swapIfBigEndian (*src++);
  13527. }
  13528. }
  13529. }
  13530. else
  13531. {
  13532. for (int i = numThisTime; --i >= 0;)
  13533. {
  13534. *l++ = swapIfBigEndian (*src++);
  13535. }
  13536. }
  13537. }
  13538. else
  13539. {
  13540. if (numChannels > 1)
  13541. {
  13542. if (l == 0)
  13543. {
  13544. for (int i = numThisTime; --i >= 0;)
  13545. {
  13546. ++src;
  13547. *r++ = swapIfLittleEndian (*src++);
  13548. }
  13549. }
  13550. else if (r == 0)
  13551. {
  13552. for (int i = numThisTime; --i >= 0;)
  13553. {
  13554. *l++ = swapIfLittleEndian (*src++);
  13555. ++src;
  13556. }
  13557. }
  13558. else
  13559. {
  13560. for (int i = numThisTime; --i >= 0;)
  13561. {
  13562. *l++ = swapIfLittleEndian (*src++);
  13563. *r++ = swapIfLittleEndian (*src++);
  13564. }
  13565. }
  13566. }
  13567. else
  13568. {
  13569. for (int i = numThisTime; --i >= 0;)
  13570. {
  13571. *l++ = swapIfLittleEndian (*src++);
  13572. }
  13573. }
  13574. }
  13575. left = (int*) l;
  13576. right = (int*) r;
  13577. }
  13578. else if (bitsPerSample == 8)
  13579. {
  13580. const char* src = (const char*) tempBuffer;
  13581. if (numChannels > 1)
  13582. {
  13583. if (left == 0)
  13584. {
  13585. for (int i = numThisTime; --i >= 0;)
  13586. {
  13587. *right++ = ((int) *src++) << 24;
  13588. ++src;
  13589. }
  13590. }
  13591. else if (right == 0)
  13592. {
  13593. for (int i = numThisTime; --i >= 0;)
  13594. {
  13595. ++src;
  13596. *left++ = ((int) *src++) << 24;
  13597. }
  13598. }
  13599. else
  13600. {
  13601. for (int i = numThisTime; --i >= 0;)
  13602. {
  13603. *left++ = ((int) *src++) << 24;
  13604. *right++ = ((int) *src++) << 24;
  13605. }
  13606. }
  13607. }
  13608. else
  13609. {
  13610. for (int i = numThisTime; --i >= 0;)
  13611. {
  13612. *left++ = ((int) *src++) << 24;
  13613. }
  13614. }
  13615. }
  13616. num -= numThisTime;
  13617. }
  13618. }
  13619. if (numToDo < numSamples)
  13620. {
  13621. int** destChan = destSamples;
  13622. while (*destChan != 0)
  13623. {
  13624. zeromem ((*destChan) + (startOffsetInDestBuffer + numToDo),
  13625. sizeof (int) * (numSamples - numToDo));
  13626. ++destChan;
  13627. }
  13628. }
  13629. return true;
  13630. }
  13631. juce_UseDebuggingNewOperator
  13632. private:
  13633. AiffAudioFormatReader (const AiffAudioFormatReader&);
  13634. const AiffAudioFormatReader& operator= (const AiffAudioFormatReader&);
  13635. };
  13636. class AiffAudioFormatWriter : public AudioFormatWriter
  13637. {
  13638. MemoryBlock tempBlock;
  13639. uint32 lengthInSamples, bytesWritten;
  13640. int64 headerPosition;
  13641. bool writeFailed;
  13642. AiffAudioFormatWriter (const AiffAudioFormatWriter&);
  13643. const AiffAudioFormatWriter& operator= (const AiffAudioFormatWriter&);
  13644. void writeHeader()
  13645. {
  13646. const bool couldSeekOk = output->setPosition (headerPosition);
  13647. (void) couldSeekOk;
  13648. // if this fails, you've given it an output stream that can't seek! It needs
  13649. // to be able to seek back to write the header
  13650. jassert (couldSeekOk);
  13651. const int headerLen = 54;
  13652. int audioBytes = lengthInSamples * ((bitsPerSample * numChannels) / 8);
  13653. audioBytes += (audioBytes & 1);
  13654. output->writeInt (chunkName ("FORM"));
  13655. output->writeIntBigEndian (headerLen + audioBytes - 8);
  13656. output->writeInt (chunkName ("AIFF"));
  13657. output->writeInt (chunkName ("COMM"));
  13658. output->writeIntBigEndian (18);
  13659. output->writeShortBigEndian ((short) numChannels);
  13660. output->writeIntBigEndian (lengthInSamples);
  13661. output->writeShortBigEndian ((short) bitsPerSample);
  13662. uint8 sampleRateBytes[10];
  13663. zeromem (sampleRateBytes, 10);
  13664. if (sampleRate <= 1)
  13665. {
  13666. sampleRateBytes[0] = 0x3f;
  13667. sampleRateBytes[1] = 0xff;
  13668. sampleRateBytes[2] = 0x80;
  13669. }
  13670. else
  13671. {
  13672. int mask = 0x40000000;
  13673. sampleRateBytes[0] = 0x40;
  13674. if (sampleRate >= mask)
  13675. {
  13676. jassertfalse
  13677. sampleRateBytes[1] = 0x1d;
  13678. }
  13679. else
  13680. {
  13681. int n = (int) sampleRate;
  13682. int i;
  13683. for (i = 0; i <= 32 ; ++i)
  13684. {
  13685. if ((n & mask) != 0)
  13686. break;
  13687. mask >>= 1;
  13688. }
  13689. n = n << (i + 1);
  13690. sampleRateBytes[1] = (uint8) (29 - i);
  13691. sampleRateBytes[2] = (uint8) ((n >> 24) & 0xff);
  13692. sampleRateBytes[3] = (uint8) ((n >> 16) & 0xff);
  13693. sampleRateBytes[4] = (uint8) ((n >> 8) & 0xff);
  13694. sampleRateBytes[5] = (uint8) (n & 0xff);
  13695. }
  13696. }
  13697. output->write (sampleRateBytes, 10);
  13698. output->writeInt (chunkName ("SSND"));
  13699. output->writeIntBigEndian (audioBytes + 8);
  13700. output->writeInt (0);
  13701. output->writeInt (0);
  13702. jassert (output->getPosition() == headerLen);
  13703. }
  13704. public:
  13705. AiffAudioFormatWriter (OutputStream* out,
  13706. const double sampleRate,
  13707. const unsigned int chans,
  13708. const int bits)
  13709. : AudioFormatWriter (out,
  13710. aiffFormatName,
  13711. sampleRate,
  13712. chans,
  13713. bits),
  13714. lengthInSamples (0),
  13715. bytesWritten (0),
  13716. writeFailed (false)
  13717. {
  13718. headerPosition = out->getPosition();
  13719. writeHeader();
  13720. }
  13721. ~AiffAudioFormatWriter()
  13722. {
  13723. if ((bytesWritten & 1) != 0)
  13724. output->writeByte (0);
  13725. writeHeader();
  13726. }
  13727. bool write (const int** data, int numSamples)
  13728. {
  13729. if (writeFailed)
  13730. return false;
  13731. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  13732. tempBlock.ensureSize (bytes, false);
  13733. char* buffer = (char*) tempBlock.getData();
  13734. const int* left = data[0];
  13735. const int* right = data[1];
  13736. if (right == 0)
  13737. right = left;
  13738. if (bitsPerSample == 16)
  13739. {
  13740. short* b = (short*) buffer;
  13741. if (numChannels > 1)
  13742. {
  13743. for (int i = numSamples; --i >= 0;)
  13744. {
  13745. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  13746. *b++ = (short) swapIfLittleEndian ((unsigned short) (*right++ >> 16));
  13747. }
  13748. }
  13749. else
  13750. {
  13751. for (int i = numSamples; --i >= 0;)
  13752. {
  13753. *b++ = (short) swapIfLittleEndian ((unsigned short) (*left++ >> 16));
  13754. }
  13755. }
  13756. }
  13757. else if (bitsPerSample == 24)
  13758. {
  13759. char* b = (char*) buffer;
  13760. if (numChannels > 1)
  13761. {
  13762. for (int i = numSamples; --i >= 0;)
  13763. {
  13764. bigEndian24BitToChars (*left++ >> 8, b);
  13765. b += 3;
  13766. bigEndian24BitToChars (*right++ >> 8, b);
  13767. b += 3;
  13768. }
  13769. }
  13770. else
  13771. {
  13772. for (int i = numSamples; --i >= 0;)
  13773. {
  13774. bigEndian24BitToChars (*left++ >> 8, b);
  13775. b += 3;
  13776. }
  13777. }
  13778. }
  13779. else if (bitsPerSample == 32)
  13780. {
  13781. unsigned int* b = (unsigned int*) buffer;
  13782. if (numChannels > 1)
  13783. {
  13784. for (int i = numSamples; --i >= 0;)
  13785. {
  13786. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  13787. *b++ = swapIfLittleEndian ((unsigned int) *right++);
  13788. }
  13789. }
  13790. else
  13791. {
  13792. for (int i = numSamples; --i >= 0;)
  13793. {
  13794. *b++ = swapIfLittleEndian ((unsigned int) *left++);
  13795. }
  13796. }
  13797. }
  13798. else if (bitsPerSample == 8)
  13799. {
  13800. char* b = (char*)buffer;
  13801. if (numChannels > 1)
  13802. {
  13803. for (int i = numSamples; --i >= 0;)
  13804. {
  13805. *b++ = (char) (*left++ >> 24);
  13806. *b++ = (char) (*right++ >> 24);
  13807. }
  13808. }
  13809. else
  13810. {
  13811. for (int i = numSamples; --i >= 0;)
  13812. {
  13813. *b++ = (char) (*left++ >> 24);
  13814. }
  13815. }
  13816. }
  13817. if (bytesWritten + bytes >= (uint32) 0xfff00000
  13818. || ! output->write (buffer, bytes))
  13819. {
  13820. // failed to write to disk, so let's try writing the header.
  13821. // If it's just run out of disk space, then if it does manage
  13822. // to write the header, we'll still have a useable file..
  13823. writeHeader();
  13824. writeFailed = true;
  13825. return false;
  13826. }
  13827. else
  13828. {
  13829. bytesWritten += bytes;
  13830. lengthInSamples += numSamples;
  13831. return true;
  13832. }
  13833. }
  13834. juce_UseDebuggingNewOperator
  13835. };
  13836. AiffAudioFormat::AiffAudioFormat()
  13837. : AudioFormat (aiffFormatName, (const tchar**) aiffExtensions)
  13838. {
  13839. }
  13840. AiffAudioFormat::~AiffAudioFormat()
  13841. {
  13842. }
  13843. const Array <int> AiffAudioFormat::getPossibleSampleRates()
  13844. {
  13845. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  13846. return Array <int> (rates);
  13847. }
  13848. const Array <int> AiffAudioFormat::getPossibleBitDepths()
  13849. {
  13850. const int depths[] = { 8, 16, 24, 0 };
  13851. return Array <int> (depths);
  13852. }
  13853. bool AiffAudioFormat::canDoStereo()
  13854. {
  13855. return true;
  13856. }
  13857. bool AiffAudioFormat::canDoMono()
  13858. {
  13859. return true;
  13860. }
  13861. #if JUCE_MAC
  13862. bool AiffAudioFormat::canHandleFile (const File& f)
  13863. {
  13864. if (AudioFormat::canHandleFile (f))
  13865. return true;
  13866. const OSType type = PlatformUtilities::getTypeOfFile (f.getFullPathName());
  13867. return type == 'AIFF' || type == 'AIFC'
  13868. || type == 'aiff' || type == 'aifc';
  13869. }
  13870. #endif
  13871. AudioFormatReader* AiffAudioFormat::createReaderFor (InputStream* sourceStream,
  13872. const bool deleteStreamIfOpeningFails)
  13873. {
  13874. AiffAudioFormatReader* w = new AiffAudioFormatReader (sourceStream);
  13875. if (w->sampleRate == 0)
  13876. {
  13877. if (! deleteStreamIfOpeningFails)
  13878. w->input = 0;
  13879. deleteAndZero (w);
  13880. }
  13881. return w;
  13882. }
  13883. AudioFormatWriter* AiffAudioFormat::createWriterFor (OutputStream* out,
  13884. double sampleRate,
  13885. unsigned int chans,
  13886. int bitsPerSample,
  13887. const StringPairArray& /*metadataValues*/,
  13888. int /*qualityOptionIndex*/)
  13889. {
  13890. if (getPossibleBitDepths().contains (bitsPerSample))
  13891. {
  13892. return new AiffAudioFormatWriter (out,
  13893. sampleRate,
  13894. chans,
  13895. bitsPerSample);
  13896. }
  13897. return 0;
  13898. }
  13899. END_JUCE_NAMESPACE
  13900. /********* End of inlined file: juce_AiffAudioFormat.cpp *********/
  13901. /********* Start of inlined file: juce_AudioCDReader.cpp *********/
  13902. BEGIN_JUCE_NAMESPACE
  13903. #if JUCE_MAC
  13904. // Mac version doesn't need any native code because it's all done with files..
  13905. // Windows + Linux versions are in the platform-dependent code sections.
  13906. static void findCDs (OwnedArray<File>& cds)
  13907. {
  13908. File volumes ("/Volumes");
  13909. volumes.findChildFiles (cds, File::findDirectories, false);
  13910. for (int i = cds.size(); --i >= 0;)
  13911. if (! cds[i]->getChildFile (".TOC.plist").exists())
  13912. cds.remove (i);
  13913. }
  13914. const StringArray AudioCDReader::getAvailableCDNames()
  13915. {
  13916. OwnedArray<File> cds;
  13917. findCDs (cds);
  13918. StringArray names;
  13919. for (int i = 0; i < cds.size(); ++i)
  13920. names.add (cds[i]->getFileName());
  13921. return names;
  13922. }
  13923. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  13924. {
  13925. OwnedArray<File> cds;
  13926. findCDs (cds);
  13927. if (cds[index] != 0)
  13928. return new AudioCDReader (*cds[index]);
  13929. else
  13930. return 0;
  13931. }
  13932. AudioCDReader::AudioCDReader (const File& volume)
  13933. : AudioFormatReader (0, "CD Audio"),
  13934. volumeDir (volume),
  13935. currentReaderTrack (-1),
  13936. reader (0)
  13937. {
  13938. sampleRate = 44100.0;
  13939. bitsPerSample = 16;
  13940. numChannels = 2;
  13941. usesFloatingPointData = false;
  13942. refreshTrackLengths();
  13943. }
  13944. AudioCDReader::~AudioCDReader()
  13945. {
  13946. if (reader != 0)
  13947. delete reader;
  13948. }
  13949. static int getTrackNumber (const File& file)
  13950. {
  13951. return file.getFileName()
  13952. .initialSectionContainingOnly (T("0123456789"))
  13953. .getIntValue();
  13954. }
  13955. int AudioCDReader::compareElements (const File* const first, const File* const second) throw()
  13956. {
  13957. const int firstTrack = getTrackNumber (*first);
  13958. const int secondTrack = getTrackNumber (*second);
  13959. jassert (firstTrack > 0 && secondTrack > 0);
  13960. return firstTrack - secondTrack;
  13961. }
  13962. void AudioCDReader::refreshTrackLengths()
  13963. {
  13964. tracks.clear();
  13965. trackStartSamples.clear();
  13966. volumeDir.findChildFiles (tracks, File::findFiles | File::ignoreHiddenFiles, false, T("*.aiff"));
  13967. tracks.sort (*this);
  13968. AiffAudioFormat format;
  13969. int sample = 0;
  13970. for (int i = 0; i < tracks.size(); ++i)
  13971. {
  13972. trackStartSamples.add (sample);
  13973. FileInputStream* const in = tracks[i]->createInputStream();
  13974. if (in != 0)
  13975. {
  13976. AudioFormatReader* const r = format.createReaderFor (in, true);
  13977. if (r != 0)
  13978. {
  13979. sample += r->lengthInSamples;
  13980. delete r;
  13981. }
  13982. }
  13983. }
  13984. trackStartSamples.add (sample);
  13985. lengthInSamples = sample;
  13986. }
  13987. bool AudioCDReader::read (int** destSamples,
  13988. int64 startSampleInFile,
  13989. int numSamples)
  13990. {
  13991. while (numSamples > 0)
  13992. {
  13993. int track = -1;
  13994. for (int i = 0; i < trackStartSamples.size() - 1; ++i)
  13995. {
  13996. if (startSampleInFile < trackStartSamples.getUnchecked (i + 1))
  13997. {
  13998. track = i;
  13999. break;
  14000. }
  14001. }
  14002. if (track < 0)
  14003. return false;
  14004. if (track != currentReaderTrack)
  14005. {
  14006. deleteAndZero (reader);
  14007. if (tracks [track] != 0)
  14008. {
  14009. FileInputStream* const in = tracks [track]->createInputStream();
  14010. if (in != 0)
  14011. {
  14012. BufferedInputStream* const bin = new BufferedInputStream (in, 65536, true);
  14013. AiffAudioFormat format;
  14014. reader = format.createReaderFor (bin, true);
  14015. if (reader == 0)
  14016. currentReaderTrack = -1;
  14017. else
  14018. currentReaderTrack = track;
  14019. }
  14020. }
  14021. }
  14022. if (reader == 0)
  14023. return false;
  14024. const int startPos = (int) (startSampleInFile - trackStartSamples.getUnchecked (track));
  14025. const int numAvailable = (int) jmin ((int64) numSamples, reader->lengthInSamples - startPos);
  14026. reader->read (destSamples, startPos, numAvailable);
  14027. numSamples -= numAvailable;
  14028. startSampleInFile += numAvailable;
  14029. }
  14030. return true;
  14031. }
  14032. bool AudioCDReader::isCDStillPresent() const
  14033. {
  14034. return volumeDir.exists();
  14035. }
  14036. int AudioCDReader::getNumTracks() const
  14037. {
  14038. return tracks.size();
  14039. }
  14040. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  14041. {
  14042. return trackStartSamples [trackNum];
  14043. }
  14044. bool AudioCDReader::isTrackAudio (int trackNum) const
  14045. {
  14046. return tracks [trackNum] != 0;
  14047. }
  14048. void AudioCDReader::enableIndexScanning (bool b)
  14049. {
  14050. // any way to do this on a Mac??
  14051. }
  14052. int AudioCDReader::getLastIndex() const
  14053. {
  14054. return 0;
  14055. }
  14056. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  14057. {
  14058. return Array <int>();
  14059. }
  14060. int AudioCDReader::getCDDBId()
  14061. {
  14062. return 0; //xxx
  14063. }
  14064. #endif
  14065. END_JUCE_NAMESPACE
  14066. /********* End of inlined file: juce_AudioCDReader.cpp *********/
  14067. /********* Start of inlined file: juce_AudioFormat.cpp *********/
  14068. BEGIN_JUCE_NAMESPACE
  14069. AudioFormatReader::AudioFormatReader (InputStream* const in,
  14070. const String& formatName_)
  14071. : sampleRate (0),
  14072. bitsPerSample (0),
  14073. lengthInSamples (0),
  14074. numChannels (0),
  14075. usesFloatingPointData (false),
  14076. input (in),
  14077. formatName (formatName_)
  14078. {
  14079. }
  14080. AudioFormatReader::~AudioFormatReader()
  14081. {
  14082. delete input;
  14083. }
  14084. static void findMaxMin (const float* src, const int num,
  14085. float& maxVal, float& minVal)
  14086. {
  14087. float mn = src[0];
  14088. float mx = mn;
  14089. for (int i = 1; i < num; ++i)
  14090. {
  14091. const float s = src[i];
  14092. if (s > mx)
  14093. mx = s;
  14094. if (s < mn)
  14095. mn = s;
  14096. }
  14097. maxVal = mx;
  14098. minVal = mn;
  14099. }
  14100. void AudioFormatReader::readMaxLevels (int64 startSampleInFile,
  14101. int64 numSamples,
  14102. float& lowestLeft, float& highestLeft,
  14103. float& lowestRight, float& highestRight)
  14104. {
  14105. if (numSamples <= 0)
  14106. {
  14107. lowestLeft = 0;
  14108. lowestRight = 0;
  14109. highestLeft = 0;
  14110. highestRight = 0;
  14111. return;
  14112. }
  14113. const int bufferSize = (int) jmin (numSamples, (int64) 4096);
  14114. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  14115. int* tempBuffer[3];
  14116. tempBuffer[0] = (int*) tempSpace.getData();
  14117. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  14118. tempBuffer[2] = 0;
  14119. if (usesFloatingPointData)
  14120. {
  14121. float lmin = 1.0e6;
  14122. float lmax = -lmin;
  14123. float rmin = lmin;
  14124. float rmax = lmax;
  14125. while (numSamples > 0)
  14126. {
  14127. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  14128. read ((int**) tempBuffer, startSampleInFile, numToDo);
  14129. numSamples -= numToDo;
  14130. float bufmin, bufmax;
  14131. findMaxMin ((float*) tempBuffer[0], numToDo, bufmax, bufmin);
  14132. lmin = jmin (lmin, bufmin);
  14133. lmax = jmax (lmax, bufmax);
  14134. if (numChannels > 1)
  14135. {
  14136. findMaxMin ((float*) tempBuffer[1], numToDo, bufmax, bufmin);
  14137. rmin = jmin (rmin, bufmin);
  14138. rmax = jmax (rmax, bufmax);
  14139. }
  14140. }
  14141. if (numChannels <= 1)
  14142. {
  14143. rmax = lmax;
  14144. rmin = lmin;
  14145. }
  14146. lowestLeft = lmin;
  14147. highestLeft = lmax;
  14148. lowestRight = rmin;
  14149. highestRight = rmax;
  14150. }
  14151. else
  14152. {
  14153. int lmax = INT_MIN;
  14154. int lmin = INT_MAX;
  14155. int rmax = INT_MIN;
  14156. int rmin = INT_MAX;
  14157. while (numSamples > 0)
  14158. {
  14159. const int numToDo = (int) jmin (numSamples, (int64) bufferSize);
  14160. read ((int**) tempBuffer, startSampleInFile, numToDo);
  14161. numSamples -= numToDo;
  14162. for (int j = numChannels; --j >= 0;)
  14163. {
  14164. int bufMax = INT_MIN;
  14165. int bufMin = INT_MAX;
  14166. const int* const b = tempBuffer[j];
  14167. for (int i = 0; i < numToDo; ++i)
  14168. {
  14169. const int samp = b[i];
  14170. if (samp < bufMin)
  14171. bufMin = samp;
  14172. if (samp > bufMax)
  14173. bufMax = samp;
  14174. }
  14175. if (j == 0)
  14176. {
  14177. lmax = jmax (lmax, bufMax);
  14178. lmin = jmin (lmin, bufMin);
  14179. }
  14180. else
  14181. {
  14182. rmax = jmax (rmax, bufMax);
  14183. rmin = jmin (rmin, bufMin);
  14184. }
  14185. }
  14186. }
  14187. if (numChannels <= 1)
  14188. {
  14189. rmax = lmax;
  14190. rmin = lmin;
  14191. }
  14192. lowestLeft = lmin / (float)INT_MAX;
  14193. highestLeft = lmax / (float)INT_MAX;
  14194. lowestRight = rmin / (float)INT_MAX;
  14195. highestRight = rmax / (float)INT_MAX;
  14196. }
  14197. }
  14198. int64 AudioFormatReader::searchForLevel (int64 startSample,
  14199. int64 numSamplesToSearch,
  14200. const double magnitudeRangeMinimum,
  14201. const double magnitudeRangeMaximum,
  14202. const int minimumConsecutiveSamples)
  14203. {
  14204. if (numSamplesToSearch == 0)
  14205. return -1;
  14206. const int bufferSize = 4096;
  14207. MemoryBlock tempSpace (bufferSize * sizeof (int) * 2 + 64);
  14208. int* tempBuffer[3];
  14209. tempBuffer[0] = (int*) tempSpace.getData();
  14210. tempBuffer[1] = ((int*) tempSpace.getData()) + bufferSize;
  14211. tempBuffer[2] = 0;
  14212. int consecutive = 0;
  14213. int64 firstMatchPos = -1;
  14214. jassert (magnitudeRangeMaximum > magnitudeRangeMinimum);
  14215. const double doubleMin = jlimit (0.0, (double) INT_MAX, magnitudeRangeMinimum * INT_MAX);
  14216. const double doubleMax = jlimit (doubleMin, (double) INT_MAX, magnitudeRangeMaximum * INT_MAX);
  14217. const int intMagnitudeRangeMinimum = roundDoubleToInt (doubleMin);
  14218. const int intMagnitudeRangeMaximum = roundDoubleToInt (doubleMax);
  14219. while (numSamplesToSearch != 0)
  14220. {
  14221. const int numThisTime = (int) jmin (abs64 (numSamplesToSearch), (int64) bufferSize);
  14222. int64 bufferStart = startSample;
  14223. if (numSamplesToSearch < 0)
  14224. bufferStart -= numThisTime;
  14225. if (bufferStart >= (int) lengthInSamples)
  14226. break;
  14227. read ((int**) tempBuffer, bufferStart, numThisTime);
  14228. int num = numThisTime;
  14229. while (--num >= 0)
  14230. {
  14231. if (numSamplesToSearch < 0)
  14232. --startSample;
  14233. bool matches = false;
  14234. const int index = (int) (startSample - bufferStart);
  14235. if (usesFloatingPointData)
  14236. {
  14237. const float sample1 = fabsf (((float*) tempBuffer[0]) [index]);
  14238. if (sample1 >= magnitudeRangeMinimum
  14239. && sample1 <= magnitudeRangeMaximum)
  14240. {
  14241. matches = true;
  14242. }
  14243. else if (numChannels > 1)
  14244. {
  14245. const float sample2 = fabsf (((float*) tempBuffer[1]) [index]);
  14246. matches = (sample2 >= magnitudeRangeMinimum
  14247. && sample2 <= magnitudeRangeMaximum);
  14248. }
  14249. }
  14250. else
  14251. {
  14252. const int sample1 = abs (tempBuffer[0] [index]);
  14253. if (sample1 >= intMagnitudeRangeMinimum
  14254. && sample1 <= intMagnitudeRangeMaximum)
  14255. {
  14256. matches = true;
  14257. }
  14258. else if (numChannels > 1)
  14259. {
  14260. const int sample2 = abs (tempBuffer[1][index]);
  14261. matches = (sample2 >= intMagnitudeRangeMinimum
  14262. && sample2 <= intMagnitudeRangeMaximum);
  14263. }
  14264. }
  14265. if (matches)
  14266. {
  14267. if (firstMatchPos < 0)
  14268. firstMatchPos = startSample;
  14269. if (++consecutive >= minimumConsecutiveSamples)
  14270. {
  14271. if (firstMatchPos < 0 || firstMatchPos >= lengthInSamples)
  14272. return -1;
  14273. return firstMatchPos;
  14274. }
  14275. }
  14276. else
  14277. {
  14278. consecutive = 0;
  14279. firstMatchPos = -1;
  14280. }
  14281. if (numSamplesToSearch > 0)
  14282. ++startSample;
  14283. }
  14284. if (numSamplesToSearch > 0)
  14285. numSamplesToSearch -= numThisTime;
  14286. else
  14287. numSamplesToSearch += numThisTime;
  14288. }
  14289. return -1;
  14290. }
  14291. AudioFormatWriter::AudioFormatWriter (OutputStream* const out,
  14292. const String& formatName_,
  14293. const double rate,
  14294. const unsigned int numChannels_,
  14295. const unsigned int bitsPerSample_)
  14296. : sampleRate (rate),
  14297. numChannels (numChannels_),
  14298. bitsPerSample (bitsPerSample_),
  14299. usesFloatingPointData (false),
  14300. output (out),
  14301. formatName (formatName_)
  14302. {
  14303. }
  14304. AudioFormatWriter::~AudioFormatWriter()
  14305. {
  14306. delete output;
  14307. }
  14308. bool AudioFormatWriter::writeFromAudioReader (AudioFormatReader& reader,
  14309. int64 startSample,
  14310. int numSamplesToRead)
  14311. {
  14312. const int bufferSize = 16384;
  14313. const int maxChans = 128;
  14314. AudioSampleBuffer tempBuffer (reader.numChannels, bufferSize);
  14315. int* buffers [maxChans];
  14316. for (int i = maxChans; --i >= 0;)
  14317. buffers[i] = 0;
  14318. while (numSamplesToRead > 0)
  14319. {
  14320. const int numToDo = jmin (numSamplesToRead, bufferSize);
  14321. for (int i = tempBuffer.getNumChannels(); --i >= 0;)
  14322. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  14323. if (! reader.read (buffers, startSample, numToDo))
  14324. return false;
  14325. if (reader.usesFloatingPointData != isFloatingPoint())
  14326. {
  14327. int** bufferChan = buffers;
  14328. while (*bufferChan != 0)
  14329. {
  14330. int* b = *bufferChan++;
  14331. if (isFloatingPoint())
  14332. {
  14333. // int -> float
  14334. const double factor = 1.0 / INT_MAX;
  14335. for (int i = 0; i < numToDo; ++i)
  14336. ((float*)b)[i] = (float) (factor * b[i]);
  14337. }
  14338. else
  14339. {
  14340. // float -> int
  14341. for (int i = 0; i < numToDo; ++i)
  14342. {
  14343. const double samp = *(const float*) b;
  14344. if (samp <= -1.0)
  14345. *b++ = INT_MIN;
  14346. else if (samp >= 1.0)
  14347. *b++ = INT_MAX;
  14348. else
  14349. *b++ = roundDoubleToInt (INT_MAX * samp);
  14350. }
  14351. }
  14352. }
  14353. }
  14354. if (! write ((const int**) buffers, numToDo))
  14355. return false;
  14356. numSamplesToRead -= numToDo;
  14357. startSample += numToDo;
  14358. }
  14359. return true;
  14360. }
  14361. bool AudioFormatWriter::writeFromAudioSource (AudioSource& source,
  14362. int numSamplesToRead,
  14363. const int samplesPerBlock)
  14364. {
  14365. const int maxChans = 128;
  14366. AudioSampleBuffer tempBuffer (getNumChannels(), samplesPerBlock);
  14367. int* buffers [maxChans];
  14368. while (numSamplesToRead > 0)
  14369. {
  14370. const int numToDo = jmin (numSamplesToRead, samplesPerBlock);
  14371. AudioSourceChannelInfo info;
  14372. info.buffer = &tempBuffer;
  14373. info.startSample = 0;
  14374. info.numSamples = numToDo;
  14375. info.clearActiveBufferRegion();
  14376. source.getNextAudioBlock (info);
  14377. int i;
  14378. for (i = maxChans; --i >= 0;)
  14379. buffers[i] = 0;
  14380. for (i = tempBuffer.getNumChannels(); --i >= 0;)
  14381. buffers[i] = (int*) tempBuffer.getSampleData (i, 0);
  14382. if (! isFloatingPoint())
  14383. {
  14384. int** bufferChan = buffers;
  14385. while (*bufferChan != 0)
  14386. {
  14387. int* b = *bufferChan++;
  14388. // float -> int
  14389. for (int j = numToDo; --j >= 0;)
  14390. {
  14391. const double samp = *(const float*) b;
  14392. if (samp <= -1.0)
  14393. *b++ = INT_MIN;
  14394. else if (samp >= 1.0)
  14395. *b++ = INT_MAX;
  14396. else
  14397. *b++ = roundDoubleToInt (INT_MAX * samp);
  14398. }
  14399. }
  14400. }
  14401. if (! write ((const int**) buffers, numToDo))
  14402. return false;
  14403. numSamplesToRead -= numToDo;
  14404. }
  14405. return true;
  14406. }
  14407. AudioFormat::AudioFormat (const String& name,
  14408. const tchar** const extensions)
  14409. : formatName (name),
  14410. fileExtensions (extensions)
  14411. {
  14412. }
  14413. AudioFormat::~AudioFormat()
  14414. {
  14415. }
  14416. const String& AudioFormat::getFormatName() const
  14417. {
  14418. return formatName;
  14419. }
  14420. const StringArray& AudioFormat::getFileExtensions() const
  14421. {
  14422. return fileExtensions;
  14423. }
  14424. bool AudioFormat::canHandleFile (const File& f)
  14425. {
  14426. for (int i = 0; i < fileExtensions.size(); ++i)
  14427. if (f.hasFileExtension (fileExtensions[i]))
  14428. return true;
  14429. return false;
  14430. }
  14431. bool AudioFormat::isCompressed()
  14432. {
  14433. return false;
  14434. }
  14435. const StringArray AudioFormat::getQualityOptions()
  14436. {
  14437. return StringArray();
  14438. }
  14439. END_JUCE_NAMESPACE
  14440. /********* End of inlined file: juce_AudioFormat.cpp *********/
  14441. /********* Start of inlined file: juce_AudioFormatManager.cpp *********/
  14442. BEGIN_JUCE_NAMESPACE
  14443. AudioFormatManager::AudioFormatManager()
  14444. : knownFormats (4),
  14445. defaultFormatIndex (0)
  14446. {
  14447. }
  14448. AudioFormatManager::~AudioFormatManager()
  14449. {
  14450. clearFormats();
  14451. clearSingletonInstance();
  14452. }
  14453. juce_ImplementSingleton (AudioFormatManager);
  14454. void AudioFormatManager::registerFormat (AudioFormat* newFormat,
  14455. const bool makeThisTheDefaultFormat)
  14456. {
  14457. jassert (newFormat != 0);
  14458. if (newFormat != 0)
  14459. {
  14460. #ifdef JUCE_DEBUG
  14461. for (int i = getNumKnownFormats(); --i >= 0;)
  14462. {
  14463. if (getKnownFormat (i)->getFormatName() == newFormat->getFormatName())
  14464. {
  14465. jassertfalse // trying to add the same format twice!
  14466. }
  14467. }
  14468. #endif
  14469. if (makeThisTheDefaultFormat)
  14470. defaultFormatIndex = knownFormats.size();
  14471. knownFormats.add (newFormat);
  14472. }
  14473. }
  14474. void AudioFormatManager::registerBasicFormats()
  14475. {
  14476. #if JUCE_MAC
  14477. registerFormat (new AiffAudioFormat(), true);
  14478. registerFormat (new WavAudioFormat(), false);
  14479. #else
  14480. registerFormat (new WavAudioFormat(), true);
  14481. registerFormat (new AiffAudioFormat(), false);
  14482. #endif
  14483. #if JUCE_USE_FLAC
  14484. registerFormat (new FlacAudioFormat(), false);
  14485. #endif
  14486. #if JUCE_USE_OGGVORBIS
  14487. registerFormat (new OggVorbisAudioFormat(), false);
  14488. #endif
  14489. }
  14490. void AudioFormatManager::clearFormats()
  14491. {
  14492. for (int i = getNumKnownFormats(); --i >= 0;)
  14493. {
  14494. AudioFormat* const af = getKnownFormat(i);
  14495. delete af;
  14496. }
  14497. knownFormats.clear();
  14498. defaultFormatIndex = 0;
  14499. }
  14500. int AudioFormatManager::getNumKnownFormats() const
  14501. {
  14502. return knownFormats.size();
  14503. }
  14504. AudioFormat* AudioFormatManager::getKnownFormat (const int index) const
  14505. {
  14506. return (AudioFormat*) knownFormats [index];
  14507. }
  14508. AudioFormat* AudioFormatManager::getDefaultFormat() const
  14509. {
  14510. return getKnownFormat (defaultFormatIndex);
  14511. }
  14512. AudioFormat* AudioFormatManager::findFormatForFileExtension (const String& fileExtension) const
  14513. {
  14514. String e (fileExtension);
  14515. if (! e.startsWithChar (T('.')))
  14516. e = T(".") + e;
  14517. for (int i = 0; i < getNumKnownFormats(); ++i)
  14518. if (getKnownFormat(i)->getFileExtensions().contains (e, true))
  14519. return getKnownFormat(i);
  14520. return 0;
  14521. }
  14522. const String AudioFormatManager::getWildcardForAllFormats() const
  14523. {
  14524. StringArray allExtensions;
  14525. int i;
  14526. for (i = 0; i < getNumKnownFormats(); ++i)
  14527. allExtensions.addArray (getKnownFormat (i)->getFileExtensions());
  14528. allExtensions.trim();
  14529. allExtensions.removeEmptyStrings();
  14530. String s;
  14531. for (i = 0; i < allExtensions.size(); ++i)
  14532. {
  14533. s << T('*');
  14534. if (! allExtensions[i].startsWithChar (T('.')))
  14535. s << T('.');
  14536. s << allExtensions[i];
  14537. if (i < allExtensions.size() - 1)
  14538. s << T(';');
  14539. }
  14540. return s;
  14541. }
  14542. AudioFormatReader* AudioFormatManager::createReaderFor (const File& file)
  14543. {
  14544. // you need to actually register some formats before the manager can
  14545. // use them to open a file!
  14546. jassert (knownFormats.size() > 0);
  14547. for (int i = 0; i < getNumKnownFormats(); ++i)
  14548. {
  14549. AudioFormat* const af = getKnownFormat(i);
  14550. if (af->canHandleFile (file))
  14551. {
  14552. InputStream* const in = file.createInputStream();
  14553. if (in != 0)
  14554. {
  14555. AudioFormatReader* const r = af->createReaderFor (in, true);
  14556. if (r != 0)
  14557. return r;
  14558. }
  14559. }
  14560. }
  14561. return 0;
  14562. }
  14563. AudioFormatReader* AudioFormatManager::createReaderFor (InputStream* in)
  14564. {
  14565. // you need to actually register some formats before the manager can
  14566. // use them to open a file!
  14567. jassert (knownFormats.size() > 0);
  14568. if (in != 0)
  14569. {
  14570. const int64 originalStreamPos = in->getPosition();
  14571. for (int i = 0; i < getNumKnownFormats(); ++i)
  14572. {
  14573. AudioFormatReader* const r = getKnownFormat(i)->createReaderFor (in, false);
  14574. if (r != 0)
  14575. return r;
  14576. in->setPosition (originalStreamPos);
  14577. // the stream that is passed-in must be capable of being repositioned so
  14578. // that all the formats can have a go at opening it.
  14579. jassert (in->getPosition() == originalStreamPos);
  14580. }
  14581. delete in;
  14582. }
  14583. return 0;
  14584. }
  14585. END_JUCE_NAMESPACE
  14586. /********* End of inlined file: juce_AudioFormatManager.cpp *********/
  14587. /********* Start of inlined file: juce_AudioSubsectionReader.cpp *********/
  14588. BEGIN_JUCE_NAMESPACE
  14589. AudioSubsectionReader::AudioSubsectionReader (AudioFormatReader* const source_,
  14590. const int64 startSample_,
  14591. const int64 length_,
  14592. const bool deleteSourceWhenDeleted_)
  14593. : AudioFormatReader (0, source_->getFormatName()),
  14594. source (source_),
  14595. startSample (startSample_),
  14596. deleteSourceWhenDeleted (deleteSourceWhenDeleted_)
  14597. {
  14598. length = jmin (jmax ((int64) 0, source->lengthInSamples - startSample), length_);
  14599. sampleRate = source->sampleRate;
  14600. bitsPerSample = source->bitsPerSample;
  14601. lengthInSamples = length;
  14602. numChannels = source->numChannels;
  14603. usesFloatingPointData = source->usesFloatingPointData;
  14604. }
  14605. AudioSubsectionReader::~AudioSubsectionReader()
  14606. {
  14607. if (deleteSourceWhenDeleted)
  14608. delete source;
  14609. }
  14610. bool AudioSubsectionReader::read (int** destSamples,
  14611. int64 startSampleInFile,
  14612. int numSamples)
  14613. {
  14614. if (startSampleInFile < 0 || startSampleInFile + numSamples > length)
  14615. {
  14616. int** d = destSamples;
  14617. while (*d != 0)
  14618. {
  14619. zeromem (*d, sizeof (int) * numSamples);
  14620. ++d;
  14621. }
  14622. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  14623. numSamples = jmax (0, jmin (numSamples, (int) (length - startSampleInFile)));
  14624. }
  14625. return source->read (destSamples,
  14626. startSampleInFile + startSample,
  14627. numSamples);
  14628. }
  14629. void AudioSubsectionReader::readMaxLevels (int64 startSampleInFile,
  14630. int64 numSamples,
  14631. float& lowestLeft,
  14632. float& highestLeft,
  14633. float& lowestRight,
  14634. float& highestRight)
  14635. {
  14636. startSampleInFile = jmax ((int64) 0, startSampleInFile);
  14637. numSamples = jmax ((int64) 0, jmin (numSamples, length - startSampleInFile));
  14638. source->readMaxLevels (startSampleInFile + startSample,
  14639. numSamples,
  14640. lowestLeft,
  14641. highestLeft,
  14642. lowestRight,
  14643. highestRight);
  14644. }
  14645. END_JUCE_NAMESPACE
  14646. /********* End of inlined file: juce_AudioSubsectionReader.cpp *********/
  14647. /********* Start of inlined file: juce_AudioThumbnail.cpp *********/
  14648. BEGIN_JUCE_NAMESPACE
  14649. const int timeBeforeDeletingReader = 2000;
  14650. struct AudioThumbnailDataFormat
  14651. {
  14652. char thumbnailMagic[4];
  14653. int samplesPerThumbSample;
  14654. int64 totalSamples; // source samples
  14655. int64 numFinishedSamples; // source samples
  14656. int numThumbnailSamples;
  14657. int numChannels;
  14658. int sampleRate;
  14659. char future[16];
  14660. char data[1];
  14661. };
  14662. #if JUCE_BIG_ENDIAN
  14663. static void swap (int& n) { n = (int) swapByteOrder ((uint32) n); }
  14664. static void swap (int64& n) { n = (int64) swapByteOrder ((uint64) n); }
  14665. #endif
  14666. static void swapEndiannessIfNeeded (AudioThumbnailDataFormat* const d)
  14667. {
  14668. (void) d;
  14669. #if JUCE_BIG_ENDIAN
  14670. swap (d->samplesPerThumbSample);
  14671. swap (d->totalSamples);
  14672. swap (d->numFinishedSamples);
  14673. swap (d->numThumbnailSamples);
  14674. swap (d->numChannels);
  14675. swap (d->sampleRate);
  14676. #endif
  14677. }
  14678. AudioThumbnail::AudioThumbnail (const int orginalSamplesPerThumbnailSample_,
  14679. AudioFormatManager& formatManagerToUse_,
  14680. AudioThumbnailCache& cacheToUse)
  14681. : formatManagerToUse (formatManagerToUse_),
  14682. cache (cacheToUse),
  14683. source (0),
  14684. reader (0),
  14685. orginalSamplesPerThumbnailSample (orginalSamplesPerThumbnailSample_)
  14686. {
  14687. clear();
  14688. }
  14689. AudioThumbnail::~AudioThumbnail()
  14690. {
  14691. cache.removeThumbnail (this);
  14692. const ScopedLock sl (readerLock);
  14693. deleteAndZero (reader);
  14694. delete source;
  14695. }
  14696. void AudioThumbnail::setSource (InputSource* const newSource)
  14697. {
  14698. cache.removeThumbnail (this);
  14699. timerCallback(); // stops the timer and deletes the reader
  14700. delete source;
  14701. source = newSource;
  14702. clear();
  14703. if (! (cache.loadThumb (*this, newSource->hashCode())
  14704. && isFullyLoaded()))
  14705. {
  14706. {
  14707. const ScopedLock sl (readerLock);
  14708. reader = createReader();
  14709. }
  14710. if (reader != 0)
  14711. {
  14712. initialiseFromAudioFile (*reader);
  14713. cache.addThumbnail (this);
  14714. }
  14715. }
  14716. sendChangeMessage (this);
  14717. }
  14718. bool AudioThumbnail::useTimeSlice()
  14719. {
  14720. const ScopedLock sl (readerLock);
  14721. if (isFullyLoaded())
  14722. {
  14723. if (reader != 0)
  14724. startTimer (timeBeforeDeletingReader);
  14725. cache.removeThumbnail (this);
  14726. return false;
  14727. }
  14728. if (reader == 0)
  14729. reader = createReader();
  14730. if (reader != 0)
  14731. {
  14732. readNextBlockFromAudioFile (*reader);
  14733. stopTimer();
  14734. sendChangeMessage (this);
  14735. const bool justFinished = isFullyLoaded();
  14736. if (justFinished)
  14737. cache.storeThumb (*this, source->hashCode());
  14738. return ! justFinished;
  14739. }
  14740. return false;
  14741. }
  14742. AudioFormatReader* AudioThumbnail::createReader() const
  14743. {
  14744. if (source != 0)
  14745. {
  14746. InputStream* const audioFileStream = source->createInputStream();
  14747. if (audioFileStream != 0)
  14748. return formatManagerToUse.createReaderFor (audioFileStream);
  14749. }
  14750. return 0;
  14751. }
  14752. void AudioThumbnail::timerCallback()
  14753. {
  14754. stopTimer();
  14755. const ScopedLock sl (readerLock);
  14756. deleteAndZero (reader);
  14757. }
  14758. void AudioThumbnail::clear()
  14759. {
  14760. data.setSize (sizeof (AudioThumbnailDataFormat) + 3);
  14761. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14762. d->thumbnailMagic[0] = 'j';
  14763. d->thumbnailMagic[1] = 'a';
  14764. d->thumbnailMagic[2] = 't';
  14765. d->thumbnailMagic[3] = 'm';
  14766. d->samplesPerThumbSample = orginalSamplesPerThumbnailSample;
  14767. d->totalSamples = 0;
  14768. d->numFinishedSamples = 0;
  14769. d->numThumbnailSamples = 0;
  14770. d->numChannels = 0;
  14771. d->sampleRate = 0;
  14772. numSamplesCached = 0;
  14773. cacheNeedsRefilling = true;
  14774. }
  14775. void AudioThumbnail::loadFrom (InputStream& input)
  14776. {
  14777. data.setSize (0);
  14778. input.readIntoMemoryBlock (data);
  14779. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14780. swapEndiannessIfNeeded (d);
  14781. if (! (d->thumbnailMagic[0] == 'j'
  14782. && d->thumbnailMagic[1] == 'a'
  14783. && d->thumbnailMagic[2] == 't'
  14784. && d->thumbnailMagic[3] == 'm'))
  14785. {
  14786. clear();
  14787. }
  14788. numSamplesCached = 0;
  14789. cacheNeedsRefilling = true;
  14790. }
  14791. void AudioThumbnail::saveTo (OutputStream& output) const
  14792. {
  14793. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14794. swapEndiannessIfNeeded (d);
  14795. output.write (data.getData(), data.getSize());
  14796. swapEndiannessIfNeeded (d);
  14797. }
  14798. bool AudioThumbnail::initialiseFromAudioFile (AudioFormatReader& reader)
  14799. {
  14800. AudioThumbnailDataFormat* d = (AudioThumbnailDataFormat*) data.getData();
  14801. d->totalSamples = reader.lengthInSamples;
  14802. d->numChannels = jmin (2, reader.numChannels);
  14803. d->numFinishedSamples = 0;
  14804. d->sampleRate = roundDoubleToInt (reader.sampleRate);
  14805. d->numThumbnailSamples = (int) (d->totalSamples / d->samplesPerThumbSample) + 1;
  14806. data.setSize (sizeof (AudioThumbnailDataFormat) + 3 + d->numThumbnailSamples * d->numChannels * 2);
  14807. d = (AudioThumbnailDataFormat*) data.getData();
  14808. zeromem (&(d->data[0]), d->numThumbnailSamples * d->numChannels * 2);
  14809. return d->totalSamples > 0;
  14810. }
  14811. bool AudioThumbnail::readNextBlockFromAudioFile (AudioFormatReader& reader)
  14812. {
  14813. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14814. if (d->numFinishedSamples < d->totalSamples)
  14815. {
  14816. const int numToDo = (int) jmin ((int64) 65536, d->totalSamples - d->numFinishedSamples);
  14817. generateSection (reader,
  14818. d->numFinishedSamples,
  14819. numToDo);
  14820. d->numFinishedSamples += numToDo;
  14821. }
  14822. cacheNeedsRefilling = true;
  14823. return (d->numFinishedSamples < d->totalSamples);
  14824. }
  14825. int AudioThumbnail::getNumChannels() const throw()
  14826. {
  14827. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14828. jassert (d != 0);
  14829. return d->numChannels;
  14830. }
  14831. double AudioThumbnail::getTotalLength() const throw()
  14832. {
  14833. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14834. jassert (d != 0);
  14835. if (d->sampleRate > 0)
  14836. return d->totalSamples / (double)d->sampleRate;
  14837. else
  14838. return 0.0;
  14839. }
  14840. void AudioThumbnail::generateSection (AudioFormatReader& reader,
  14841. int64 startSample,
  14842. int numSamples)
  14843. {
  14844. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14845. jassert (d != 0);
  14846. int firstDataPos = (int) (startSample / d->samplesPerThumbSample);
  14847. int lastDataPos = (int) ((startSample + numSamples) / d->samplesPerThumbSample);
  14848. char* l = getChannelData (0);
  14849. char* r = getChannelData (1);
  14850. for (int i = firstDataPos; i < lastDataPos; ++i)
  14851. {
  14852. const int sourceStart = i * d->samplesPerThumbSample;
  14853. const int sourceEnd = sourceStart + d->samplesPerThumbSample;
  14854. float lowestLeft, highestLeft, lowestRight, highestRight;
  14855. reader.readMaxLevels (sourceStart,
  14856. sourceEnd - sourceStart,
  14857. lowestLeft,
  14858. highestLeft,
  14859. lowestRight,
  14860. highestRight);
  14861. int n = i * 2;
  14862. if (r != 0)
  14863. {
  14864. l [n] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  14865. r [n++] = (char) jlimit (-128.0f, 127.0f, lowestRight * 127.0f);
  14866. l [n] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  14867. r [n++] = (char) jlimit (-128.0f, 127.0f, highestRight * 127.0f);
  14868. }
  14869. else
  14870. {
  14871. l [n++] = (char) jlimit (-128.0f, 127.0f, lowestLeft * 127.0f);
  14872. l [n++] = (char) jlimit (-128.0f, 127.0f, highestLeft * 127.0f);
  14873. }
  14874. }
  14875. }
  14876. char* AudioThumbnail::getChannelData (int channel) const
  14877. {
  14878. AudioThumbnailDataFormat* const d = (AudioThumbnailDataFormat*) data.getData();
  14879. jassert (d != 0);
  14880. if (channel >= 0 && channel < d->numChannels)
  14881. return d->data + (channel * 2 * d->numThumbnailSamples);
  14882. return 0;
  14883. }
  14884. bool AudioThumbnail::isFullyLoaded() const throw()
  14885. {
  14886. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14887. jassert (d != 0);
  14888. return d->numFinishedSamples >= d->totalSamples;
  14889. }
  14890. void AudioThumbnail::refillCache (const int numSamples,
  14891. double startTime,
  14892. const double timePerPixel)
  14893. {
  14894. const AudioThumbnailDataFormat* const d = (const AudioThumbnailDataFormat*) data.getData();
  14895. jassert (d != 0);
  14896. if (numSamples <= 0
  14897. || timePerPixel <= 0.0
  14898. || d->sampleRate <= 0)
  14899. {
  14900. numSamplesCached = 0;
  14901. cacheNeedsRefilling = true;
  14902. return;
  14903. }
  14904. if (numSamples == numSamplesCached
  14905. && numChannelsCached == d->numChannels
  14906. && startTime == cachedStart
  14907. && timePerPixel == cachedTimePerPixel
  14908. && ! cacheNeedsRefilling)
  14909. {
  14910. return;
  14911. }
  14912. numSamplesCached = numSamples;
  14913. numChannelsCached = d->numChannels;
  14914. cachedStart = startTime;
  14915. cachedTimePerPixel = timePerPixel;
  14916. cachedLevels.ensureSize (2 * numChannelsCached * numSamples);
  14917. const bool needExtraDetail = (timePerPixel * d->sampleRate <= d->samplesPerThumbSample);
  14918. const ScopedLock sl (readerLock);
  14919. cacheNeedsRefilling = false;
  14920. if (needExtraDetail && reader == 0)
  14921. reader = createReader();
  14922. if (reader != 0 && timePerPixel * d->sampleRate <= d->samplesPerThumbSample)
  14923. {
  14924. startTimer (timeBeforeDeletingReader);
  14925. char* cacheData = (char*) cachedLevels.getData();
  14926. int sample = roundDoubleToInt (startTime * d->sampleRate);
  14927. for (int i = numSamples; --i >= 0;)
  14928. {
  14929. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * d->sampleRate);
  14930. if (sample >= 0)
  14931. {
  14932. if (sample >= reader->lengthInSamples)
  14933. break;
  14934. float lmin, lmax, rmin, rmax;
  14935. reader->readMaxLevels (sample,
  14936. jmax (1, nextSample - sample),
  14937. lmin, lmax, rmin, rmax);
  14938. cacheData[0] = (char) jlimit (-128, 127, roundFloatToInt (lmin * 127.0f));
  14939. cacheData[1] = (char) jlimit (-128, 127, roundFloatToInt (lmax * 127.0f));
  14940. if (numChannelsCached > 1)
  14941. {
  14942. cacheData[2] = (char) jlimit (-128, 127, roundFloatToInt (rmin * 127.0f));
  14943. cacheData[3] = (char) jlimit (-128, 127, roundFloatToInt (rmax * 127.0f));
  14944. }
  14945. cacheData += 2 * numChannelsCached;
  14946. }
  14947. startTime += timePerPixel;
  14948. sample = nextSample;
  14949. }
  14950. }
  14951. else
  14952. {
  14953. for (int channelNum = 0; channelNum < numChannelsCached; ++channelNum)
  14954. {
  14955. char* const data = getChannelData (channelNum);
  14956. char* cacheData = ((char*) cachedLevels.getData()) + channelNum * 2;
  14957. const double timeToThumbSampleFactor = d->sampleRate / (double) d->samplesPerThumbSample;
  14958. startTime = cachedStart;
  14959. int sample = roundDoubleToInt (startTime * timeToThumbSampleFactor);
  14960. const int numFinished = (int) (d->numFinishedSamples / d->samplesPerThumbSample);
  14961. for (int i = numSamples; --i >= 0;)
  14962. {
  14963. const int nextSample = roundDoubleToInt ((startTime + timePerPixel) * timeToThumbSampleFactor);
  14964. if (sample >= 0 && data != 0)
  14965. {
  14966. char mx = -128;
  14967. char mn = 127;
  14968. while (sample <= nextSample)
  14969. {
  14970. if (sample >= numFinished)
  14971. break;
  14972. const int n = sample << 1;
  14973. const char sampMin = data [n];
  14974. const char sampMax = data [n + 1];
  14975. if (sampMin < mn)
  14976. mn = sampMin;
  14977. if (sampMax > mx)
  14978. mx = sampMax;
  14979. ++sample;
  14980. }
  14981. if (mn <= mx)
  14982. {
  14983. cacheData[0] = mn;
  14984. cacheData[1] = mx;
  14985. }
  14986. else
  14987. {
  14988. cacheData[0] = 1;
  14989. cacheData[1] = 0;
  14990. }
  14991. }
  14992. else
  14993. {
  14994. cacheData[0] = 1;
  14995. cacheData[1] = 0;
  14996. }
  14997. cacheData += numChannelsCached * 2;
  14998. startTime += timePerPixel;
  14999. sample = nextSample;
  15000. }
  15001. }
  15002. }
  15003. }
  15004. void AudioThumbnail::drawChannel (Graphics& g,
  15005. int x, int y, int w, int h,
  15006. double startTime,
  15007. double endTime,
  15008. int channelNum,
  15009. const float verticalZoomFactor)
  15010. {
  15011. refillCache (w, startTime, (endTime - startTime) / w);
  15012. if (numSamplesCached >= w
  15013. && channelNum >= 0
  15014. && channelNum < numChannelsCached)
  15015. {
  15016. const float topY = (float) y;
  15017. const float bottomY = topY + h;
  15018. const float midY = topY + h * 0.5f;
  15019. const float vscale = verticalZoomFactor * h / 256.0f;
  15020. const Rectangle clip (g.getClipBounds());
  15021. const int skipLeft = clip.getX() - x;
  15022. w -= skipLeft;
  15023. x += skipLeft;
  15024. const char* cacheData = ((const char*) cachedLevels.getData())
  15025. + (channelNum << 1)
  15026. + skipLeft * (numChannelsCached << 1);
  15027. while (--w >= 0)
  15028. {
  15029. const char mn = cacheData[0];
  15030. const char mx = cacheData[1];
  15031. cacheData += numChannelsCached << 1;
  15032. if (mn <= mx) // if the wrong way round, signifies that the sample's not yet known
  15033. g.drawLine ((float) x, jmax (midY - mx * vscale - 0.3f, topY),
  15034. (float) x, jmin (midY - mn * vscale + 0.3f, bottomY));
  15035. ++x;
  15036. if (x >= clip.getRight())
  15037. break;
  15038. }
  15039. }
  15040. }
  15041. END_JUCE_NAMESPACE
  15042. /********* End of inlined file: juce_AudioThumbnail.cpp *********/
  15043. /********* Start of inlined file: juce_AudioThumbnailCache.cpp *********/
  15044. BEGIN_JUCE_NAMESPACE
  15045. struct ThumbnailCacheEntry
  15046. {
  15047. int64 hash;
  15048. uint32 lastUsed;
  15049. MemoryBlock data;
  15050. juce_UseDebuggingNewOperator
  15051. };
  15052. AudioThumbnailCache::AudioThumbnailCache (const int maxNumThumbsToStore_)
  15053. : TimeSliceThread (T("thumb cache")),
  15054. maxNumThumbsToStore (maxNumThumbsToStore_)
  15055. {
  15056. startThread (2);
  15057. }
  15058. AudioThumbnailCache::~AudioThumbnailCache()
  15059. {
  15060. }
  15061. bool AudioThumbnailCache::loadThumb (AudioThumbnail& thumb, const int64 hashCode)
  15062. {
  15063. for (int i = thumbs.size(); --i >= 0;)
  15064. {
  15065. if (thumbs[i]->hash == hashCode)
  15066. {
  15067. MemoryInputStream in ((const char*) thumbs[i]->data.getData(),
  15068. thumbs[i]->data.getSize(),
  15069. false);
  15070. thumb.loadFrom (in);
  15071. thumbs[i]->lastUsed = Time::getMillisecondCounter();
  15072. return true;
  15073. }
  15074. }
  15075. return false;
  15076. }
  15077. void AudioThumbnailCache::storeThumb (const AudioThumbnail& thumb,
  15078. const int64 hashCode)
  15079. {
  15080. MemoryOutputStream out;
  15081. thumb.saveTo (out);
  15082. ThumbnailCacheEntry* te = 0;
  15083. for (int i = thumbs.size(); --i >= 0;)
  15084. {
  15085. if (thumbs[i]->hash == hashCode)
  15086. {
  15087. te = thumbs[i];
  15088. break;
  15089. }
  15090. }
  15091. if (te == 0)
  15092. {
  15093. te = new ThumbnailCacheEntry();
  15094. te->hash = hashCode;
  15095. if (thumbs.size() < maxNumThumbsToStore)
  15096. {
  15097. thumbs.add (te);
  15098. }
  15099. else
  15100. {
  15101. int oldest = 0;
  15102. unsigned int oldestTime = Time::getMillisecondCounter() + 1;
  15103. int i;
  15104. for (i = thumbs.size(); --i >= 0;)
  15105. if (thumbs[i]->lastUsed < oldestTime)
  15106. oldest = i;
  15107. thumbs.set (i, te);
  15108. }
  15109. }
  15110. te->lastUsed = Time::getMillisecondCounter();
  15111. te->data.setSize (0);
  15112. te->data.append (out.getData(), out.getDataSize());
  15113. }
  15114. void AudioThumbnailCache::clear()
  15115. {
  15116. thumbs.clear();
  15117. }
  15118. void AudioThumbnailCache::addThumbnail (AudioThumbnail* const thumb)
  15119. {
  15120. addTimeSliceClient (thumb);
  15121. }
  15122. void AudioThumbnailCache::removeThumbnail (AudioThumbnail* const thumb)
  15123. {
  15124. removeTimeSliceClient (thumb);
  15125. }
  15126. END_JUCE_NAMESPACE
  15127. /********* End of inlined file: juce_AudioThumbnailCache.cpp *********/
  15128. /********* Start of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  15129. /********* Start of inlined file: juce_Config.h *********/
  15130. #ifndef __JUCE_CONFIG_JUCEHEADER__
  15131. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  15132. /*
  15133. This file contains macros that enable/disable various JUCE features.
  15134. */
  15135. /** The name of the namespace that all Juce classes and functions will be
  15136. put inside. If this is not defined, no namespace will be used.
  15137. */
  15138. #ifndef JUCE_NAMESPACE
  15139. #define JUCE_NAMESPACE juce
  15140. #endif
  15141. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  15142. but if you define this value, you can override this can force it to be true or
  15143. false.
  15144. */
  15145. #ifndef JUCE_FORCE_DEBUG
  15146. //#define JUCE_FORCE_DEBUG 1
  15147. #endif
  15148. /** If this flag is enabled, the the jassert and jassertfalse macros will
  15149. always use Logger::writeToLog() to write a message when an assertion happens.
  15150. Enabling it will also leave this turned on in release builds. When it's disabled,
  15151. however, the jassert and jassertfalse macros will not be compiled in a
  15152. release build.
  15153. @see jassert, jassertfalse, Logger
  15154. */
  15155. #ifndef JUCE_LOG_ASSERTIONS
  15156. // #define JUCE_LOG_ASSERTIONS 1
  15157. #endif
  15158. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  15159. which the ASIOAudioIODevice class can't be built. See the comments in the
  15160. ASIOAudioIODevice class's header file for more info about this.
  15161. (This only affects a Win32 build)
  15162. */
  15163. #ifndef JUCE_ASIO
  15164. #define JUCE_ASIO 1
  15165. #endif
  15166. /** Comment out this macro to disable building of ALSA device support on Linux.
  15167. */
  15168. #ifndef JUCE_ALSA
  15169. #define JUCE_ALSA 1
  15170. #endif
  15171. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  15172. have the SDK installed.
  15173. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  15174. classes will be unavailable.
  15175. On Windows, if you enable this, you'll need to have the QuickTime SDK
  15176. installed, and its header files will need to be on your include path.
  15177. */
  15178. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  15179. #define JUCE_QUICKTIME 1
  15180. #endif
  15181. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  15182. have the appropriate headers and libraries available. If it's not enabled, the
  15183. OpenGLComponent class will be unavailable.
  15184. */
  15185. #ifndef JUCE_OPENGL
  15186. #define JUCE_OPENGL 1
  15187. #endif
  15188. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  15189. If you're not going to need either of these formats, turn off the flags to
  15190. avoid bloating your codebase with them.
  15191. */
  15192. #ifndef JUCE_USE_FLAC
  15193. #define JUCE_USE_FLAC 1
  15194. #endif
  15195. #ifndef JUCE_USE_OGGVORBIS
  15196. #define JUCE_USE_OGGVORBIS 1
  15197. #endif
  15198. /** This flag lets you enable support for CD-burning. You might want to disable
  15199. it to build without the MS SDK under windows.
  15200. */
  15201. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  15202. #define JUCE_USE_CDBURNER 1
  15203. #endif
  15204. /** Enabling this macro means that all regions that get repainted will have a coloured
  15205. line drawn around them.
  15206. This is handy if you're trying to optimise drawing, because it lets you easily see
  15207. when anything is being repainted unnecessarily.
  15208. */
  15209. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  15210. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  15211. #endif
  15212. /** Enable this under Linux to use Xinerama for multi-monitor support.
  15213. */
  15214. #ifndef JUCE_USE_XINERAMA
  15215. #define JUCE_USE_XINERAMA 1
  15216. #endif
  15217. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  15218. */
  15219. #ifndef JUCE_USE_XSHM
  15220. #define JUCE_USE_XSHM 1
  15221. #endif
  15222. /** Enabling this builds support for VST audio plugins.
  15223. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  15224. */
  15225. #ifndef JUCE_PLUGINHOST_VST
  15226. // #define JUCE_PLUGINHOST_VST 1
  15227. #endif
  15228. /** Enabling this builds support for AudioUnit audio plugins.
  15229. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  15230. */
  15231. #ifndef JUCE_PLUGINHOST_AU
  15232. // #define JUCE_PLUGINHOST_AU 1
  15233. #endif
  15234. /** Disabling this will avoid linking to any UI code. This is handy for
  15235. writing command-line utilities, e.g. on linux boxes which don't have some
  15236. of the UI libraries installed.
  15237. (On mac and windows, this won't generally make much difference to the build).
  15238. */
  15239. #ifndef JUCE_BUILD_GUI_CLASSES
  15240. #define JUCE_BUILD_GUI_CLASSES 1
  15241. #endif
  15242. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  15243. */
  15244. #ifndef JUCE_WEB_BROWSER
  15245. #define JUCE_WEB_BROWSER 1
  15246. #endif
  15247. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  15248. codebase - you might need to use this if you're linking to some of these libraries
  15249. yourself.
  15250. */
  15251. #ifndef JUCE_INCLUDE_ZLIB_CODE
  15252. #define JUCE_INCLUDE_ZLIB_CODE 1
  15253. #endif
  15254. #ifndef JUCE_INCLUDE_FLAC_CODE
  15255. #define JUCE_INCLUDE_FLAC_CODE 1
  15256. #endif
  15257. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  15258. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  15259. #endif
  15260. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  15261. #define JUCE_INCLUDE_PNGLIB_CODE 1
  15262. #endif
  15263. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  15264. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  15265. #endif
  15266. /** Enable this to add extra memory-leak info to the new and delete operators.
  15267. (Currently, this only affects Windows builds in debug mode).
  15268. */
  15269. #ifndef JUCE_CHECK_MEMORY_LEAKS
  15270. #define JUCE_CHECK_MEMORY_LEAKS 1
  15271. #endif
  15272. /** Enable this to turn on juce's internal catching of exceptions.
  15273. Turning it off will avoid any exception catching. With it on, all exceptions
  15274. are passed to the JUCEApplication::unhandledException() callback for logging.
  15275. */
  15276. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  15277. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  15278. #endif
  15279. /** If this macro is set, the Juce String class will use unicode as its
  15280. internal representation. If it isn't set, it'll use ANSI.
  15281. */
  15282. #ifndef JUCE_STRINGS_ARE_UNICODE
  15283. #define JUCE_STRINGS_ARE_UNICODE 1
  15284. #endif
  15285. #endif
  15286. /********* End of inlined file: juce_Config.h *********/
  15287. #if JUCE_QUICKTIME
  15288. #if ! defined (_WIN32)
  15289. #include <Quicktime/Movies.h>
  15290. #include <Quicktime/QTML.h>
  15291. #include <Quicktime/QuickTimeComponents.h>
  15292. #include <Quicktime/MediaHandlers.h>
  15293. #include <Quicktime/ImageCodec.h>
  15294. #else
  15295. #ifdef _MSC_VER
  15296. #pragma warning (push)
  15297. #pragma warning (disable : 4100)
  15298. #endif
  15299. /* If you've got an include error here, you probably need to install the QuickTime SDK and
  15300. add its header directory to your include path.
  15301. Alternatively, if you don't need any QuickTime services, just turn off the JUC_QUICKTIME
  15302. flag in juce_Config.h
  15303. */
  15304. #include <Movies.h>
  15305. #include <QTML.h>
  15306. #include <QuickTimeComponents.h>
  15307. #include <MediaHandlers.h>
  15308. #include <ImageCodec.h>
  15309. #ifdef _MSC_VER
  15310. #pragma warning (pop)
  15311. #endif
  15312. #endif
  15313. #if ! (JUCE_MAC && JUCE_64BIT)
  15314. BEGIN_JUCE_NAMESPACE
  15315. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  15316. #define quickTimeFormatName TRANS("QuickTime file")
  15317. static const tchar* const quickTimeExtensions[] = { T(".mov"), T(".mp3"), T(".mp4"), 0 };
  15318. class QTAudioReader : public AudioFormatReader
  15319. {
  15320. public:
  15321. QTAudioReader (InputStream* const input_, const int trackNum_)
  15322. : AudioFormatReader (input_, quickTimeFormatName),
  15323. ok (false),
  15324. movie (0),
  15325. trackNum (trackNum_),
  15326. extractor (0),
  15327. lastSampleRead (0),
  15328. lastThreadId (0),
  15329. dataHandle (0)
  15330. {
  15331. bufferList = (AudioBufferList*) juce_calloc (256);
  15332. #ifdef WIN32
  15333. if (InitializeQTML (0) != noErr)
  15334. return;
  15335. #elif JUCE_MAC
  15336. EnterMoviesOnThread (0);
  15337. #endif
  15338. if (EnterMovies() != noErr)
  15339. return;
  15340. bool opened = juce_OpenQuickTimeMovieFromStream (input_, movie, dataHandle);
  15341. if (! opened)
  15342. return;
  15343. {
  15344. const int numTracks = GetMovieTrackCount (movie);
  15345. int trackCount = 0;
  15346. for (int i = 1; i <= numTracks; ++i)
  15347. {
  15348. track = GetMovieIndTrack (movie, i);
  15349. media = GetTrackMedia (track);
  15350. OSType mediaType;
  15351. GetMediaHandlerDescription (media, &mediaType, 0, 0);
  15352. if (mediaType == SoundMediaType
  15353. && trackCount++ == trackNum_)
  15354. {
  15355. ok = true;
  15356. break;
  15357. }
  15358. }
  15359. }
  15360. if (! ok)
  15361. return;
  15362. ok = false;
  15363. lengthInSamples = GetMediaDecodeDuration (media);
  15364. usesFloatingPointData = false;
  15365. samplesPerFrame = (int) (GetMediaDecodeDuration (media) / GetMediaSampleCount (media));
  15366. trackUnitsPerFrame = GetMovieTimeScale (movie) * samplesPerFrame
  15367. / GetMediaTimeScale (media);
  15368. OSStatus err = MovieAudioExtractionBegin (movie, 0, &extractor);
  15369. unsigned long output_layout_size;
  15370. err = MovieAudioExtractionGetPropertyInfo (extractor,
  15371. kQTPropertyClass_MovieAudioExtraction_Audio,
  15372. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  15373. 0, &output_layout_size, 0);
  15374. if (err != noErr)
  15375. return;
  15376. AudioChannelLayout* const qt_audio_channel_layout
  15377. = (AudioChannelLayout*) juce_calloc (output_layout_size);
  15378. err = MovieAudioExtractionGetProperty (extractor,
  15379. kQTPropertyClass_MovieAudioExtraction_Audio,
  15380. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  15381. output_layout_size, qt_audio_channel_layout, 0);
  15382. qt_audio_channel_layout->mChannelLayoutTag = kAudioChannelLayoutTag_Stereo;
  15383. err = MovieAudioExtractionSetProperty (extractor,
  15384. kQTPropertyClass_MovieAudioExtraction_Audio,
  15385. kQTMovieAudioExtractionAudioPropertyID_AudioChannelLayout,
  15386. sizeof (qt_audio_channel_layout),
  15387. qt_audio_channel_layout);
  15388. juce_free (qt_audio_channel_layout);
  15389. err = MovieAudioExtractionGetProperty (extractor,
  15390. kQTPropertyClass_MovieAudioExtraction_Audio,
  15391. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  15392. sizeof (inputStreamDesc),
  15393. &inputStreamDesc, 0);
  15394. if (err != noErr)
  15395. return;
  15396. inputStreamDesc.mFormatFlags = kAudioFormatFlagIsSignedInteger
  15397. | kAudioFormatFlagIsPacked
  15398. | kAudioFormatFlagsNativeEndian;
  15399. inputStreamDesc.mBitsPerChannel = sizeof (SInt16) * 8;
  15400. inputStreamDesc.mChannelsPerFrame = jmin (2, inputStreamDesc.mChannelsPerFrame);
  15401. inputStreamDesc.mBytesPerFrame = sizeof (SInt16) * inputStreamDesc.mChannelsPerFrame;
  15402. inputStreamDesc.mBytesPerPacket = inputStreamDesc.mBytesPerFrame;
  15403. err = MovieAudioExtractionSetProperty (extractor,
  15404. kQTPropertyClass_MovieAudioExtraction_Audio,
  15405. kQTMovieAudioExtractionAudioPropertyID_AudioStreamBasicDescription,
  15406. sizeof (inputStreamDesc),
  15407. &inputStreamDesc);
  15408. if (err != noErr)
  15409. return;
  15410. Boolean allChannelsDiscrete = false;
  15411. err = MovieAudioExtractionSetProperty (extractor,
  15412. kQTPropertyClass_MovieAudioExtraction_Movie,
  15413. kQTMovieAudioExtractionMoviePropertyID_AllChannelsDiscrete,
  15414. sizeof (allChannelsDiscrete),
  15415. &allChannelsDiscrete);
  15416. if (err != noErr)
  15417. return;
  15418. bufferList->mNumberBuffers = 1;
  15419. bufferList->mBuffers[0].mNumberChannels = inputStreamDesc.mChannelsPerFrame;
  15420. bufferList->mBuffers[0].mDataByteSize = (UInt32) (samplesPerFrame * inputStreamDesc.mBytesPerFrame) + 16;
  15421. bufferList->mBuffers[0].mData = malloc (bufferList->mBuffers[0].mDataByteSize);
  15422. sampleRate = inputStreamDesc.mSampleRate;
  15423. bitsPerSample = 16;
  15424. numChannels = inputStreamDesc.mChannelsPerFrame;
  15425. detachThread();
  15426. ok = true;
  15427. }
  15428. ~QTAudioReader()
  15429. {
  15430. if (dataHandle != 0)
  15431. DisposeHandle (dataHandle);
  15432. if (extractor != 0)
  15433. {
  15434. MovieAudioExtractionEnd (extractor);
  15435. extractor = 0;
  15436. }
  15437. checkThreadIsAttached();
  15438. DisposeMovie (movie);
  15439. juce_free (bufferList->mBuffers[0].mData);
  15440. juce_free (bufferList);
  15441. #if JUCE_MAC
  15442. ExitMoviesOnThread ();
  15443. #endif
  15444. }
  15445. bool read (int** destSamples,
  15446. int64 startSample,
  15447. int numSamples)
  15448. {
  15449. checkThreadIsAttached();
  15450. int done = 0;
  15451. while (numSamples > 0)
  15452. {
  15453. if (! loadFrame ((int) startSample))
  15454. return false;
  15455. const int numToDo = jmin (numSamples, samplesPerFrame);
  15456. for (unsigned int j = 0; j < inputStreamDesc.mChannelsPerFrame; ++j)
  15457. {
  15458. if (destSamples[j] != 0)
  15459. {
  15460. const short* const src = ((const short*) bufferList->mBuffers[0].mData) + j;
  15461. for (int i = 0; i < numToDo; ++i)
  15462. destSamples[j][done + i] = src [i << 1] << 16;
  15463. }
  15464. }
  15465. done += numToDo;
  15466. startSample += numToDo;
  15467. numSamples -= numToDo;
  15468. }
  15469. detachThread();
  15470. return true;
  15471. }
  15472. bool loadFrame (const int sampleNum)
  15473. {
  15474. if (lastSampleRead != sampleNum)
  15475. {
  15476. TimeRecord time;
  15477. time.scale = (TimeScale) inputStreamDesc.mSampleRate;
  15478. time.base = 0;
  15479. time.value.hi = 0;
  15480. time.value.lo = (UInt32) sampleNum;
  15481. OSStatus err = MovieAudioExtractionSetProperty (extractor,
  15482. kQTPropertyClass_MovieAudioExtraction_Movie,
  15483. kQTMovieAudioExtractionMoviePropertyID_CurrentTime,
  15484. sizeof (time), &time);
  15485. if (err != noErr)
  15486. return false;
  15487. }
  15488. bufferList->mBuffers[0].mDataByteSize = inputStreamDesc.mBytesPerFrame * samplesPerFrame;
  15489. UInt32 outFlags = 0;
  15490. UInt32 actualNumSamples = samplesPerFrame;
  15491. OSStatus err = MovieAudioExtractionFillBuffer (extractor, &actualNumSamples,
  15492. bufferList, &outFlags);
  15493. lastSampleRead = sampleNum + samplesPerFrame;
  15494. return err == noErr;
  15495. }
  15496. juce_UseDebuggingNewOperator
  15497. bool ok;
  15498. private:
  15499. Movie movie;
  15500. Media media;
  15501. Track track;
  15502. const int trackNum;
  15503. double trackUnitsPerFrame;
  15504. int samplesPerFrame;
  15505. int lastSampleRead, lastThreadId;
  15506. MovieAudioExtractionRef extractor;
  15507. AudioStreamBasicDescription inputStreamDesc;
  15508. AudioBufferList* bufferList;
  15509. Handle dataHandle;
  15510. /*OSErr readMovieStream (long offset, long size, void* dataPtr)
  15511. {
  15512. input->setPosition (offset);
  15513. input->read (dataPtr, size);
  15514. return noErr;
  15515. }
  15516. static OSErr readMovieStreamProc (long offset, long size, void* dataPtr, void* userRef)
  15517. {
  15518. return ((QTAudioReader*) userRef)->readMovieStream (offset, size, dataPtr);
  15519. }*/
  15520. void checkThreadIsAttached()
  15521. {
  15522. #if JUCE_MAC
  15523. if (Thread::getCurrentThreadId() != lastThreadId)
  15524. EnterMoviesOnThread (0);
  15525. AttachMovieToCurrentThread (movie);
  15526. #endif
  15527. }
  15528. void detachThread()
  15529. {
  15530. #if JUCE_MAC
  15531. DetachMovieFromCurrentThread (movie);
  15532. #endif
  15533. }
  15534. };
  15535. QuickTimeAudioFormat::QuickTimeAudioFormat()
  15536. : AudioFormat (quickTimeFormatName, (const tchar**) quickTimeExtensions)
  15537. {
  15538. }
  15539. QuickTimeAudioFormat::~QuickTimeAudioFormat()
  15540. {
  15541. }
  15542. const Array <int> QuickTimeAudioFormat::getPossibleSampleRates()
  15543. {
  15544. return Array<int>();
  15545. }
  15546. const Array <int> QuickTimeAudioFormat::getPossibleBitDepths()
  15547. {
  15548. return Array<int>();
  15549. }
  15550. bool QuickTimeAudioFormat::canDoStereo()
  15551. {
  15552. return true;
  15553. }
  15554. bool QuickTimeAudioFormat::canDoMono()
  15555. {
  15556. return true;
  15557. }
  15558. AudioFormatReader* QuickTimeAudioFormat::createReaderFor (InputStream* sourceStream,
  15559. const bool deleteStreamIfOpeningFails)
  15560. {
  15561. QTAudioReader* r = new QTAudioReader (sourceStream, 0);
  15562. if (! r->ok)
  15563. {
  15564. if (! deleteStreamIfOpeningFails)
  15565. r->input = 0;
  15566. deleteAndZero (r);
  15567. }
  15568. return r;
  15569. }
  15570. AudioFormatWriter* QuickTimeAudioFormat::createWriterFor (OutputStream* /*streamToWriteTo*/,
  15571. double /*sampleRateToUse*/,
  15572. unsigned int /*numberOfChannels*/,
  15573. int /*bitsPerSample*/,
  15574. const StringPairArray& /*metadataValues*/,
  15575. int /*qualityOptionIndex*/)
  15576. {
  15577. jassertfalse // not yet implemented!
  15578. return 0;
  15579. }
  15580. END_JUCE_NAMESPACE
  15581. #endif
  15582. #endif
  15583. /********* End of inlined file: juce_QuickTimeAudioFormat.cpp *********/
  15584. /********* Start of inlined file: juce_WavAudioFormat.cpp *********/
  15585. BEGIN_JUCE_NAMESPACE
  15586. #define wavFormatName TRANS("WAV file")
  15587. static const tchar* const wavExtensions[] = { T(".wav"), T(".bwf"), 0 };
  15588. const tchar* const WavAudioFormat::bwavDescription = T("bwav description");
  15589. const tchar* const WavAudioFormat::bwavOriginator = T("bwav originator");
  15590. const tchar* const WavAudioFormat::bwavOriginatorRef = T("bwav originator ref");
  15591. const tchar* const WavAudioFormat::bwavOriginationDate = T("bwav origination date");
  15592. const tchar* const WavAudioFormat::bwavOriginationTime = T("bwav origination time");
  15593. const tchar* const WavAudioFormat::bwavTimeReference = T("bwav time reference");
  15594. const tchar* const WavAudioFormat::bwavCodingHistory = T("bwav coding history");
  15595. const StringPairArray WavAudioFormat::createBWAVMetadata (const String& description,
  15596. const String& originator,
  15597. const String& originatorRef,
  15598. const Time& date,
  15599. const int64 timeReferenceSamples,
  15600. const String& codingHistory)
  15601. {
  15602. StringPairArray m;
  15603. m.set (bwavDescription, description);
  15604. m.set (bwavOriginator, originator);
  15605. m.set (bwavOriginatorRef, originatorRef);
  15606. m.set (bwavOriginationDate, date.formatted (T("%Y-%m-%d")));
  15607. m.set (bwavOriginationTime, date.formatted (T("%H:%M:%S")));
  15608. m.set (bwavTimeReference, String (timeReferenceSamples));
  15609. m.set (bwavCodingHistory, codingHistory);
  15610. return m;
  15611. }
  15612. #if JUCE_MSVC
  15613. #pragma pack (push, 1)
  15614. #define PACKED
  15615. #elif defined (JUCE_GCC)
  15616. #define PACKED __attribute__((packed))
  15617. #else
  15618. #define PACKED
  15619. #endif
  15620. struct BWAVChunk
  15621. {
  15622. char description [256];
  15623. char originator [32];
  15624. char originatorRef [32];
  15625. char originationDate [10];
  15626. char originationTime [8];
  15627. uint32 timeRefLow;
  15628. uint32 timeRefHigh;
  15629. uint16 version;
  15630. uint8 umid[64];
  15631. uint8 reserved[190];
  15632. char codingHistory[1];
  15633. void copyTo (StringPairArray& values) const
  15634. {
  15635. values.set (WavAudioFormat::bwavDescription, String (description, 256));
  15636. values.set (WavAudioFormat::bwavOriginator, String (originator, 32));
  15637. values.set (WavAudioFormat::bwavOriginatorRef, String (originatorRef, 32));
  15638. values.set (WavAudioFormat::bwavOriginationDate, String (originationDate, 10));
  15639. values.set (WavAudioFormat::bwavOriginationTime, String (originationTime, 8));
  15640. const uint32 timeLow = swapIfBigEndian (timeRefLow);
  15641. const uint32 timeHigh = swapIfBigEndian (timeRefHigh);
  15642. const int64 time = (((int64)timeHigh) << 32) + timeLow;
  15643. values.set (WavAudioFormat::bwavTimeReference, String (time));
  15644. values.set (WavAudioFormat::bwavCodingHistory, String (codingHistory));
  15645. }
  15646. static MemoryBlock createFrom (const StringPairArray& values)
  15647. {
  15648. const int sizeNeeded = sizeof (BWAVChunk) + values [WavAudioFormat::bwavCodingHistory].length();
  15649. MemoryBlock data ((sizeNeeded + 3) & ~3);
  15650. data.fillWith (0);
  15651. BWAVChunk* b = (BWAVChunk*) data.getData();
  15652. // although copyToBuffer may overrun by one byte, that's ok as long as these
  15653. // operations get done in the right order
  15654. values [WavAudioFormat::bwavDescription].copyToBuffer (b->description, 256);
  15655. values [WavAudioFormat::bwavOriginator].copyToBuffer (b->originator, 32);
  15656. values [WavAudioFormat::bwavOriginatorRef].copyToBuffer (b->originatorRef, 32);
  15657. values [WavAudioFormat::bwavOriginationDate].copyToBuffer (b->originationDate, 10);
  15658. values [WavAudioFormat::bwavOriginationTime].copyToBuffer (b->originationTime, 8);
  15659. const int64 time = values [WavAudioFormat::bwavTimeReference].getLargeIntValue();
  15660. b->timeRefLow = swapIfBigEndian ((uint32) (time & 0xffffffff));
  15661. b->timeRefHigh = swapIfBigEndian ((uint32) (time >> 32));
  15662. values [WavAudioFormat::bwavCodingHistory].copyToBuffer (b->codingHistory, 256 * 1024);
  15663. if (b->description[0] != 0
  15664. || b->originator[0] != 0
  15665. || b->originationDate[0] != 0
  15666. || b->originationTime[0] != 0
  15667. || b->codingHistory[0] != 0
  15668. || time != 0)
  15669. {
  15670. return data;
  15671. }
  15672. return MemoryBlock();
  15673. }
  15674. } PACKED;
  15675. #if JUCE_MSVC
  15676. #pragma pack (pop)
  15677. #endif
  15678. #undef PACKED
  15679. #undef chunkName
  15680. #define chunkName(a) ((int) littleEndianInt(a))
  15681. class WavAudioFormatReader : public AudioFormatReader
  15682. {
  15683. int bytesPerFrame;
  15684. int64 dataChunkStart, dataLength;
  15685. WavAudioFormatReader (const WavAudioFormatReader&);
  15686. const WavAudioFormatReader& operator= (const WavAudioFormatReader&);
  15687. public:
  15688. WavAudioFormatReader (InputStream* const in)
  15689. : AudioFormatReader (in, wavFormatName),
  15690. dataLength (0)
  15691. {
  15692. if (input->readInt() == chunkName ("RIFF"))
  15693. {
  15694. const uint32 len = (uint32) input->readInt();
  15695. const int64 end = input->getPosition() + len;
  15696. bool hasGotType = false;
  15697. bool hasGotData = false;
  15698. if (input->readInt() == chunkName ("WAVE"))
  15699. {
  15700. while (input->getPosition() < end
  15701. && ! input->isExhausted())
  15702. {
  15703. const int chunkType = input->readInt();
  15704. uint32 length = (uint32) input->readInt();
  15705. const int64 chunkEnd = input->getPosition() + length + (length & 1);
  15706. if (chunkType == chunkName ("fmt "))
  15707. {
  15708. // read the format chunk
  15709. const short format = input->readShort();
  15710. const short numChans = input->readShort();
  15711. sampleRate = input->readInt();
  15712. const int bytesPerSec = input->readInt();
  15713. numChannels = numChans;
  15714. bytesPerFrame = bytesPerSec / (int)sampleRate;
  15715. bitsPerSample = 8 * bytesPerFrame / numChans;
  15716. if (format == 3)
  15717. usesFloatingPointData = true;
  15718. else if (format != 1)
  15719. bytesPerFrame = 0;
  15720. hasGotType = true;
  15721. }
  15722. else if (chunkType == chunkName ("data"))
  15723. {
  15724. // get the data chunk's position
  15725. dataLength = length;
  15726. dataChunkStart = input->getPosition();
  15727. lengthInSamples = (bytesPerFrame > 0) ? (dataLength / bytesPerFrame) : 0;
  15728. hasGotData = true;
  15729. }
  15730. else if (chunkType == chunkName ("bext"))
  15731. {
  15732. // Broadcast-wav extension chunk..
  15733. BWAVChunk* const bwav = (BWAVChunk*) juce_calloc (jmax (length + 1, (int) sizeof (BWAVChunk)));
  15734. if (bwav != 0)
  15735. {
  15736. input->read (bwav, length);
  15737. bwav->copyTo (metadataValues);
  15738. juce_free (bwav);
  15739. }
  15740. }
  15741. else if ((hasGotType && hasGotData) || chunkEnd <= input->getPosition())
  15742. {
  15743. break;
  15744. }
  15745. input->setPosition (chunkEnd);
  15746. }
  15747. }
  15748. }
  15749. }
  15750. ~WavAudioFormatReader()
  15751. {
  15752. }
  15753. bool read (int** destSamples,
  15754. int64 startSampleInFile,
  15755. int numSamples)
  15756. {
  15757. int64 start = startSampleInFile;
  15758. int startOffsetInDestBuffer = 0;
  15759. if (startSampleInFile < 0)
  15760. {
  15761. const int silence = (int) jmin (-startSampleInFile, (int64) numSamples);
  15762. int** destChan = destSamples;
  15763. for (int i = 2; --i >= 0;)
  15764. {
  15765. if (*destChan != 0)
  15766. {
  15767. zeromem (*destChan, sizeof (int) * silence);
  15768. ++destChan;
  15769. }
  15770. }
  15771. startOffsetInDestBuffer += silence;
  15772. numSamples -= silence;
  15773. start = 0;
  15774. }
  15775. const int numToDo = (int) jlimit ((int64) 0, (int64) numSamples, lengthInSamples - start);
  15776. if (numToDo > 0)
  15777. {
  15778. input->setPosition (dataChunkStart + start * bytesPerFrame);
  15779. int num = numToDo;
  15780. int* left = destSamples[0];
  15781. if (left != 0)
  15782. left += startOffsetInDestBuffer;
  15783. int* right = destSamples[1];
  15784. if (right != 0)
  15785. right += startOffsetInDestBuffer;
  15786. // (keep this a multiple of 3)
  15787. const int tempBufSize = 1440 * 4;
  15788. char tempBuffer [tempBufSize];
  15789. while (num > 0)
  15790. {
  15791. const int numThisTime = jmin (tempBufSize / bytesPerFrame, num);
  15792. const int bytesRead = input->read (tempBuffer, numThisTime * bytesPerFrame);
  15793. if (bytesRead < numThisTime * bytesPerFrame)
  15794. zeromem (tempBuffer + bytesRead, numThisTime * bytesPerFrame - bytesRead);
  15795. if (bitsPerSample == 16)
  15796. {
  15797. const short* src = (const short*) tempBuffer;
  15798. if (numChannels > 1)
  15799. {
  15800. if (left == 0)
  15801. {
  15802. for (int i = numThisTime; --i >= 0;)
  15803. {
  15804. ++src;
  15805. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15806. }
  15807. }
  15808. else if (right == 0)
  15809. {
  15810. for (int i = numThisTime; --i >= 0;)
  15811. {
  15812. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15813. ++src;
  15814. }
  15815. }
  15816. else
  15817. {
  15818. for (int i = numThisTime; --i >= 0;)
  15819. {
  15820. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15821. *right++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15822. }
  15823. }
  15824. }
  15825. else
  15826. {
  15827. for (int i = numThisTime; --i >= 0;)
  15828. {
  15829. *left++ = (int) swapIfBigEndian ((unsigned short) *src++) << 16;
  15830. }
  15831. }
  15832. }
  15833. else if (bitsPerSample == 24)
  15834. {
  15835. const char* src = (const char*) tempBuffer;
  15836. if (numChannels > 1)
  15837. {
  15838. if (left == 0)
  15839. {
  15840. for (int i = numThisTime; --i >= 0;)
  15841. {
  15842. src += 6;
  15843. *right++ = littleEndian24Bit (src) << 8;
  15844. }
  15845. }
  15846. else if (right == 0)
  15847. {
  15848. for (int i = numThisTime; --i >= 0;)
  15849. {
  15850. *left++ = littleEndian24Bit (src) << 8;
  15851. src += 6;
  15852. }
  15853. }
  15854. else
  15855. {
  15856. for (int i = 0; i < numThisTime; ++i)
  15857. {
  15858. *left++ = littleEndian24Bit (src) << 8;
  15859. src += 3;
  15860. *right++ = littleEndian24Bit (src) << 8;
  15861. src += 3;
  15862. }
  15863. }
  15864. }
  15865. else
  15866. {
  15867. for (int i = 0; i < numThisTime; ++i)
  15868. {
  15869. *left++ = littleEndian24Bit (src) << 8;
  15870. src += 3;
  15871. }
  15872. }
  15873. }
  15874. else if (bitsPerSample == 32)
  15875. {
  15876. const unsigned int* src = (const unsigned int*) tempBuffer;
  15877. unsigned int* l = (unsigned int*) left;
  15878. unsigned int* r = (unsigned int*) right;
  15879. if (numChannels > 1)
  15880. {
  15881. if (l == 0)
  15882. {
  15883. for (int i = numThisTime; --i >= 0;)
  15884. {
  15885. ++src;
  15886. *r++ = swapIfBigEndian (*src++);
  15887. }
  15888. }
  15889. else if (r == 0)
  15890. {
  15891. for (int i = numThisTime; --i >= 0;)
  15892. {
  15893. *l++ = swapIfBigEndian (*src++);
  15894. ++src;
  15895. }
  15896. }
  15897. else
  15898. {
  15899. for (int i = numThisTime; --i >= 0;)
  15900. {
  15901. *l++ = swapIfBigEndian (*src++);
  15902. *r++ = swapIfBigEndian (*src++);
  15903. }
  15904. }
  15905. }
  15906. else
  15907. {
  15908. for (int i = numThisTime; --i >= 0;)
  15909. {
  15910. *l++ = swapIfBigEndian (*src++);
  15911. }
  15912. }
  15913. left = (int*)l;
  15914. right = (int*)r;
  15915. }
  15916. else if (bitsPerSample == 8)
  15917. {
  15918. const unsigned char* src = (const unsigned char*) tempBuffer;
  15919. if (numChannels > 1)
  15920. {
  15921. if (left == 0)
  15922. {
  15923. for (int i = numThisTime; --i >= 0;)
  15924. {
  15925. ++src;
  15926. *right++ = ((int) *src++ - 128) << 24;
  15927. }
  15928. }
  15929. else if (right == 0)
  15930. {
  15931. for (int i = numThisTime; --i >= 0;)
  15932. {
  15933. *left++ = ((int) *src++ - 128) << 24;
  15934. ++src;
  15935. }
  15936. }
  15937. else
  15938. {
  15939. for (int i = numThisTime; --i >= 0;)
  15940. {
  15941. *left++ = ((int) *src++ - 128) << 24;
  15942. *right++ = ((int) *src++ - 128) << 24;
  15943. }
  15944. }
  15945. }
  15946. else
  15947. {
  15948. for (int i = numThisTime; --i >= 0;)
  15949. {
  15950. *left++ = ((int)*src++ - 128) << 24;
  15951. }
  15952. }
  15953. }
  15954. num -= numThisTime;
  15955. }
  15956. }
  15957. if (numToDo < numSamples)
  15958. {
  15959. int** destChan = destSamples;
  15960. while (*destChan != 0)
  15961. {
  15962. zeromem ((*destChan) + (startOffsetInDestBuffer + numToDo),
  15963. sizeof (int) * (numSamples - numToDo));
  15964. ++destChan;
  15965. }
  15966. }
  15967. return true;
  15968. }
  15969. juce_UseDebuggingNewOperator
  15970. };
  15971. class WavAudioFormatWriter : public AudioFormatWriter
  15972. {
  15973. MemoryBlock tempBlock, bwavChunk;
  15974. uint32 lengthInSamples, bytesWritten;
  15975. int64 headerPosition;
  15976. bool writeFailed;
  15977. WavAudioFormatWriter (const WavAudioFormatWriter&);
  15978. const WavAudioFormatWriter& operator= (const WavAudioFormatWriter&);
  15979. void writeHeader()
  15980. {
  15981. const bool seekedOk = output->setPosition (headerPosition);
  15982. (void) seekedOk;
  15983. // if this fails, you've given it an output stream that can't seek! It needs
  15984. // to be able to seek back to write the header
  15985. jassert (seekedOk);
  15986. const int bytesPerFrame = numChannels * bitsPerSample / 8;
  15987. output->writeInt (chunkName ("RIFF"));
  15988. output->writeInt (lengthInSamples * bytesPerFrame
  15989. + ((bwavChunk.getSize() > 0) ? (44 + bwavChunk.getSize()) : 36));
  15990. output->writeInt (chunkName ("WAVE"));
  15991. output->writeInt (chunkName ("fmt "));
  15992. output->writeInt (16);
  15993. output->writeShort ((bitsPerSample < 32) ? (short) 1 /*WAVE_FORMAT_PCM*/
  15994. : (short) 3 /*WAVE_FORMAT_IEEE_FLOAT*/);
  15995. output->writeShort ((short) numChannels);
  15996. output->writeInt ((int) sampleRate);
  15997. output->writeInt (bytesPerFrame * (int) sampleRate);
  15998. output->writeShort ((short) bytesPerFrame);
  15999. output->writeShort ((short) bitsPerSample);
  16000. if (bwavChunk.getSize() > 0)
  16001. {
  16002. output->writeInt (chunkName ("bext"));
  16003. output->writeInt (bwavChunk.getSize());
  16004. output->write (bwavChunk.getData(), bwavChunk.getSize());
  16005. }
  16006. output->writeInt (chunkName ("data"));
  16007. output->writeInt (lengthInSamples * bytesPerFrame);
  16008. usesFloatingPointData = (bitsPerSample == 32);
  16009. }
  16010. public:
  16011. WavAudioFormatWriter (OutputStream* const out,
  16012. const double sampleRate,
  16013. const unsigned int numChannels_,
  16014. const int bits,
  16015. const StringPairArray& metadataValues)
  16016. : AudioFormatWriter (out,
  16017. wavFormatName,
  16018. sampleRate,
  16019. numChannels_,
  16020. bits),
  16021. lengthInSamples (0),
  16022. bytesWritten (0),
  16023. writeFailed (false)
  16024. {
  16025. if (metadataValues.size() > 0)
  16026. bwavChunk = BWAVChunk::createFrom (metadataValues);
  16027. headerPosition = out->getPosition();
  16028. writeHeader();
  16029. }
  16030. ~WavAudioFormatWriter()
  16031. {
  16032. writeHeader();
  16033. }
  16034. bool write (const int** data, int numSamples)
  16035. {
  16036. if (writeFailed)
  16037. return false;
  16038. const int bytes = numChannels * numSamples * bitsPerSample / 8;
  16039. tempBlock.ensureSize (bytes, false);
  16040. char* buffer = (char*) tempBlock.getData();
  16041. const int* left = data[0];
  16042. const int* right = data[1];
  16043. if (right == 0)
  16044. right = left;
  16045. if (bitsPerSample == 16)
  16046. {
  16047. short* b = (short*) buffer;
  16048. if (numChannels > 1)
  16049. {
  16050. for (int i = numSamples; --i >= 0;)
  16051. {
  16052. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  16053. *b++ = (short) swapIfBigEndian ((unsigned short) (*right++ >> 16));
  16054. }
  16055. }
  16056. else
  16057. {
  16058. for (int i = numSamples; --i >= 0;)
  16059. {
  16060. *b++ = (short) swapIfBigEndian ((unsigned short) (*left++ >> 16));
  16061. }
  16062. }
  16063. }
  16064. else if (bitsPerSample == 24)
  16065. {
  16066. char* b = (char*) buffer;
  16067. if (numChannels > 1)
  16068. {
  16069. for (int i = numSamples; --i >= 0;)
  16070. {
  16071. littleEndian24BitToChars ((*left++) >> 8, b);
  16072. b += 3;
  16073. littleEndian24BitToChars ((*right++) >> 8, b);
  16074. b += 3;
  16075. }
  16076. }
  16077. else
  16078. {
  16079. for (int i = numSamples; --i >= 0;)
  16080. {
  16081. littleEndian24BitToChars ((*left++) >> 8, b);
  16082. b += 3;
  16083. }
  16084. }
  16085. }
  16086. else if (bitsPerSample == 32)
  16087. {
  16088. unsigned int* b = (unsigned int*) buffer;
  16089. if (numChannels > 1)
  16090. {
  16091. for (int i = numSamples; --i >= 0;)
  16092. {
  16093. *b++ = swapIfBigEndian ((unsigned int) *left++);
  16094. *b++ = swapIfBigEndian ((unsigned int) *right++);
  16095. }
  16096. }
  16097. else
  16098. {
  16099. for (int i = numSamples; --i >= 0;)
  16100. {
  16101. *b++ = swapIfBigEndian ((unsigned int) *left++);
  16102. }
  16103. }
  16104. }
  16105. else if (bitsPerSample == 8)
  16106. {
  16107. unsigned char* b = (unsigned char*) buffer;
  16108. if (numChannels > 1)
  16109. {
  16110. for (int i = numSamples; --i >= 0;)
  16111. {
  16112. *b++ = (unsigned char) (128 + (*left++ >> 24));
  16113. *b++ = (unsigned char) (128 + (*right++ >> 24));
  16114. }
  16115. }
  16116. else
  16117. {
  16118. for (int i = numSamples; --i >= 0;)
  16119. {
  16120. *b++ = (unsigned char) (128 + (*left++ >> 24));
  16121. }
  16122. }
  16123. }
  16124. if (bytesWritten + bytes >= (uint32) 0xfff00000
  16125. || ! output->write (buffer, bytes))
  16126. {
  16127. // failed to write to disk, so let's try writing the header.
  16128. // If it's just run out of disk space, then if it does manage
  16129. // to write the header, we'll still have a useable file..
  16130. writeHeader();
  16131. writeFailed = true;
  16132. return false;
  16133. }
  16134. else
  16135. {
  16136. bytesWritten += bytes;
  16137. lengthInSamples += numSamples;
  16138. return true;
  16139. }
  16140. }
  16141. juce_UseDebuggingNewOperator
  16142. };
  16143. WavAudioFormat::WavAudioFormat()
  16144. : AudioFormat (wavFormatName, (const tchar**) wavExtensions)
  16145. {
  16146. }
  16147. WavAudioFormat::~WavAudioFormat()
  16148. {
  16149. }
  16150. const Array <int> WavAudioFormat::getPossibleSampleRates()
  16151. {
  16152. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  16153. return Array <int> (rates);
  16154. }
  16155. const Array <int> WavAudioFormat::getPossibleBitDepths()
  16156. {
  16157. const int depths[] = { 8, 16, 24, 32, 0 };
  16158. return Array <int> (depths);
  16159. }
  16160. bool WavAudioFormat::canDoStereo()
  16161. {
  16162. return true;
  16163. }
  16164. bool WavAudioFormat::canDoMono()
  16165. {
  16166. return true;
  16167. }
  16168. AudioFormatReader* WavAudioFormat::createReaderFor (InputStream* sourceStream,
  16169. const bool deleteStreamIfOpeningFails)
  16170. {
  16171. WavAudioFormatReader* r = new WavAudioFormatReader (sourceStream);
  16172. if (r->sampleRate == 0)
  16173. {
  16174. if (! deleteStreamIfOpeningFails)
  16175. r->input = 0;
  16176. deleteAndZero (r);
  16177. }
  16178. return r;
  16179. }
  16180. AudioFormatWriter* WavAudioFormat::createWriterFor (OutputStream* out,
  16181. double sampleRate,
  16182. unsigned int numChannels,
  16183. int bitsPerSample,
  16184. const StringPairArray& metadataValues,
  16185. int /*qualityOptionIndex*/)
  16186. {
  16187. if (getPossibleBitDepths().contains (bitsPerSample))
  16188. {
  16189. return new WavAudioFormatWriter (out,
  16190. sampleRate,
  16191. numChannels,
  16192. bitsPerSample,
  16193. metadataValues);
  16194. }
  16195. return 0;
  16196. }
  16197. END_JUCE_NAMESPACE
  16198. /********* End of inlined file: juce_WavAudioFormat.cpp *********/
  16199. /********* Start of inlined file: juce_AudioFormatReaderSource.cpp *********/
  16200. BEGIN_JUCE_NAMESPACE
  16201. AudioFormatReaderSource::AudioFormatReaderSource (AudioFormatReader* const reader_,
  16202. const bool deleteReaderWhenThisIsDeleted)
  16203. : reader (reader_),
  16204. deleteReader (deleteReaderWhenThisIsDeleted),
  16205. nextPlayPos (0),
  16206. looping (false)
  16207. {
  16208. jassert (reader != 0);
  16209. }
  16210. AudioFormatReaderSource::~AudioFormatReaderSource()
  16211. {
  16212. releaseResources();
  16213. if (deleteReader)
  16214. delete reader;
  16215. }
  16216. void AudioFormatReaderSource::setNextReadPosition (int newPosition)
  16217. {
  16218. nextPlayPos = newPosition;
  16219. }
  16220. void AudioFormatReaderSource::setLooping (const bool shouldLoop) throw()
  16221. {
  16222. looping = shouldLoop;
  16223. }
  16224. int AudioFormatReaderSource::getNextReadPosition() const
  16225. {
  16226. return (looping) ? (nextPlayPos % (int) reader->lengthInSamples)
  16227. : nextPlayPos;
  16228. }
  16229. int AudioFormatReaderSource::getTotalLength() const
  16230. {
  16231. return (int) reader->lengthInSamples;
  16232. }
  16233. void AudioFormatReaderSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  16234. double /*sampleRate*/)
  16235. {
  16236. }
  16237. void AudioFormatReaderSource::releaseResources()
  16238. {
  16239. }
  16240. void AudioFormatReaderSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16241. {
  16242. if (info.numSamples > 0)
  16243. {
  16244. const int start = nextPlayPos;
  16245. if (looping)
  16246. {
  16247. const int newStart = start % (int) reader->lengthInSamples;
  16248. const int newEnd = (start + info.numSamples) % (int) reader->lengthInSamples;
  16249. if (newEnd > newStart)
  16250. {
  16251. info.buffer->readFromAudioReader (reader,
  16252. info.startSample,
  16253. newEnd - newStart,
  16254. newStart,
  16255. true, true);
  16256. }
  16257. else
  16258. {
  16259. const int endSamps = (int) reader->lengthInSamples - newStart;
  16260. info.buffer->readFromAudioReader (reader,
  16261. info.startSample,
  16262. endSamps,
  16263. newStart,
  16264. true, true);
  16265. info.buffer->readFromAudioReader (reader,
  16266. info.startSample + endSamps,
  16267. newEnd,
  16268. 0,
  16269. true, true);
  16270. }
  16271. nextPlayPos = newEnd;
  16272. }
  16273. else
  16274. {
  16275. info.buffer->readFromAudioReader (reader,
  16276. info.startSample,
  16277. info.numSamples,
  16278. start,
  16279. true, true);
  16280. nextPlayPos += info.numSamples;
  16281. }
  16282. }
  16283. }
  16284. END_JUCE_NAMESPACE
  16285. /********* End of inlined file: juce_AudioFormatReaderSource.cpp *********/
  16286. /********* Start of inlined file: juce_AudioSourcePlayer.cpp *********/
  16287. BEGIN_JUCE_NAMESPACE
  16288. AudioSourcePlayer::AudioSourcePlayer()
  16289. : source (0),
  16290. sampleRate (0),
  16291. bufferSize (0),
  16292. tempBuffer (2, 8),
  16293. lastGain (1.0f),
  16294. gain (1.0f)
  16295. {
  16296. }
  16297. AudioSourcePlayer::~AudioSourcePlayer()
  16298. {
  16299. setSource (0);
  16300. }
  16301. void AudioSourcePlayer::setSource (AudioSource* newSource)
  16302. {
  16303. if (source != newSource)
  16304. {
  16305. AudioSource* const oldSource = source;
  16306. if (newSource != 0 && bufferSize > 0 && sampleRate > 0)
  16307. newSource->prepareToPlay (bufferSize, sampleRate);
  16308. {
  16309. const ScopedLock sl (readLock);
  16310. source = newSource;
  16311. }
  16312. if (oldSource != 0)
  16313. oldSource->releaseResources();
  16314. }
  16315. }
  16316. void AudioSourcePlayer::setGain (const float newGain) throw()
  16317. {
  16318. gain = newGain;
  16319. }
  16320. void AudioSourcePlayer::audioDeviceIOCallback (const float** inputChannelData,
  16321. int totalNumInputChannels,
  16322. float** outputChannelData,
  16323. int totalNumOutputChannels,
  16324. int numSamples)
  16325. {
  16326. // these should have been prepared by audioDeviceAboutToStart()...
  16327. jassert (sampleRate > 0 && bufferSize > 0);
  16328. const ScopedLock sl (readLock);
  16329. if (source != 0)
  16330. {
  16331. AudioSourceChannelInfo info;
  16332. int i, numActiveChans = 0, numInputs = 0, numOutputs = 0;
  16333. // messy stuff needed to compact the channels down into an array
  16334. // of non-zero pointers..
  16335. for (i = 0; i < totalNumInputChannels; ++i)
  16336. {
  16337. if (inputChannelData[i] != 0)
  16338. {
  16339. inputChans [numInputs++] = inputChannelData[i];
  16340. if (numInputs >= numElementsInArray (inputChans))
  16341. break;
  16342. }
  16343. }
  16344. for (i = 0; i < totalNumOutputChannels; ++i)
  16345. {
  16346. if (outputChannelData[i] != 0)
  16347. {
  16348. outputChans [numOutputs++] = outputChannelData[i];
  16349. if (numOutputs >= numElementsInArray (outputChans))
  16350. break;
  16351. }
  16352. }
  16353. if (numInputs > numOutputs)
  16354. {
  16355. // if there aren't enough output channels for the number of
  16356. // inputs, we need to create some temporary extra ones (can't
  16357. // use the input data in case it gets written to)
  16358. tempBuffer.setSize (numInputs - numOutputs, numSamples,
  16359. false, false, true);
  16360. for (i = 0; i < numOutputs; ++i)
  16361. {
  16362. channels[numActiveChans] = outputChans[i];
  16363. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  16364. ++numActiveChans;
  16365. }
  16366. for (i = numOutputs; i < numInputs; ++i)
  16367. {
  16368. channels[numActiveChans] = tempBuffer.getSampleData (i - numOutputs, 0);
  16369. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  16370. ++numActiveChans;
  16371. }
  16372. }
  16373. else
  16374. {
  16375. for (i = 0; i < numInputs; ++i)
  16376. {
  16377. channels[numActiveChans] = outputChans[i];
  16378. memcpy (channels[numActiveChans], inputChans[i], sizeof (float) * numSamples);
  16379. ++numActiveChans;
  16380. }
  16381. for (i = numInputs; i < numOutputs; ++i)
  16382. {
  16383. channels[numActiveChans] = outputChans[i];
  16384. zeromem (channels[numActiveChans], sizeof (float) * numSamples);
  16385. ++numActiveChans;
  16386. }
  16387. }
  16388. AudioSampleBuffer buffer (channels, numActiveChans, numSamples);
  16389. info.buffer = &buffer;
  16390. info.startSample = 0;
  16391. info.numSamples = numSamples;
  16392. source->getNextAudioBlock (info);
  16393. for (i = info.buffer->getNumChannels(); --i >= 0;)
  16394. info.buffer->applyGainRamp (i, info.startSample, info.numSamples, lastGain, gain);
  16395. lastGain = gain;
  16396. }
  16397. else
  16398. {
  16399. for (int i = 0; i < totalNumOutputChannels; ++i)
  16400. if (outputChannelData[i] != 0)
  16401. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  16402. }
  16403. }
  16404. void AudioSourcePlayer::audioDeviceAboutToStart (AudioIODevice* device)
  16405. {
  16406. sampleRate = device->getCurrentSampleRate();
  16407. bufferSize = device->getCurrentBufferSizeSamples();
  16408. zeromem (channels, sizeof (channels));
  16409. if (source != 0)
  16410. source->prepareToPlay (bufferSize, sampleRate);
  16411. }
  16412. void AudioSourcePlayer::audioDeviceStopped()
  16413. {
  16414. if (source != 0)
  16415. source->releaseResources();
  16416. sampleRate = 0.0;
  16417. bufferSize = 0;
  16418. tempBuffer.setSize (2, 8);
  16419. }
  16420. END_JUCE_NAMESPACE
  16421. /********* End of inlined file: juce_AudioSourcePlayer.cpp *********/
  16422. /********* Start of inlined file: juce_AudioTransportSource.cpp *********/
  16423. BEGIN_JUCE_NAMESPACE
  16424. AudioTransportSource::AudioTransportSource()
  16425. : source (0),
  16426. resamplerSource (0),
  16427. bufferingSource (0),
  16428. positionableSource (0),
  16429. masterSource (0),
  16430. gain (1.0f),
  16431. lastGain (1.0f),
  16432. playing (false),
  16433. stopped (true),
  16434. sampleRate (44100.0),
  16435. sourceSampleRate (0.0),
  16436. blockSize (128),
  16437. readAheadBufferSize (0),
  16438. isPrepared (false),
  16439. inputStreamEOF (false)
  16440. {
  16441. }
  16442. AudioTransportSource::~AudioTransportSource()
  16443. {
  16444. setSource (0);
  16445. releaseResources();
  16446. }
  16447. void AudioTransportSource::setSource (PositionableAudioSource* const newSource,
  16448. int readAheadBufferSize_,
  16449. double sourceSampleRateToCorrectFor)
  16450. {
  16451. if (source == newSource)
  16452. {
  16453. if (source == 0)
  16454. return;
  16455. setSource (0, 0, 0); // deselect and reselect to avoid releasing resources wrongly
  16456. }
  16457. readAheadBufferSize = readAheadBufferSize_;
  16458. sourceSampleRate = sourceSampleRateToCorrectFor;
  16459. ResamplingAudioSource* newResamplerSource = 0;
  16460. BufferingAudioSource* newBufferingSource = 0;
  16461. PositionableAudioSource* newPositionableSource = 0;
  16462. AudioSource* newMasterSource = 0;
  16463. ResamplingAudioSource* oldResamplerSource = resamplerSource;
  16464. BufferingAudioSource* oldBufferingSource = bufferingSource;
  16465. AudioSource* oldMasterSource = masterSource;
  16466. if (newSource != 0)
  16467. {
  16468. newPositionableSource = newSource;
  16469. if (readAheadBufferSize_ > 0)
  16470. newPositionableSource = newBufferingSource
  16471. = new BufferingAudioSource (newPositionableSource, false, readAheadBufferSize_);
  16472. newPositionableSource->setNextReadPosition (0);
  16473. if (sourceSampleRateToCorrectFor != 0)
  16474. newMasterSource = newResamplerSource
  16475. = new ResamplingAudioSource (newPositionableSource, false);
  16476. else
  16477. newMasterSource = newPositionableSource;
  16478. if (isPrepared)
  16479. {
  16480. if (newResamplerSource != 0 && sourceSampleRate > 0 && sampleRate > 0)
  16481. newResamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  16482. newMasterSource->prepareToPlay (blockSize, sampleRate);
  16483. }
  16484. }
  16485. {
  16486. const ScopedLock sl (callbackLock);
  16487. source = newSource;
  16488. resamplerSource = newResamplerSource;
  16489. bufferingSource = newBufferingSource;
  16490. masterSource = newMasterSource;
  16491. positionableSource = newPositionableSource;
  16492. playing = false;
  16493. }
  16494. if (oldMasterSource != 0)
  16495. oldMasterSource->releaseResources();
  16496. if (oldResamplerSource != 0)
  16497. delete oldResamplerSource;
  16498. if (oldBufferingSource != 0)
  16499. delete oldBufferingSource;
  16500. }
  16501. void AudioTransportSource::start()
  16502. {
  16503. if ((! playing) && masterSource != 0)
  16504. {
  16505. callbackLock.enter();
  16506. playing = true;
  16507. stopped = false;
  16508. inputStreamEOF = false;
  16509. callbackLock.exit();
  16510. sendChangeMessage (this);
  16511. }
  16512. }
  16513. void AudioTransportSource::stop()
  16514. {
  16515. if (playing)
  16516. {
  16517. callbackLock.enter();
  16518. playing = false;
  16519. callbackLock.exit();
  16520. int n = 500;
  16521. while (--n >= 0 && ! stopped)
  16522. Thread::sleep (2);
  16523. sendChangeMessage (this);
  16524. }
  16525. }
  16526. void AudioTransportSource::setPosition (double newPosition)
  16527. {
  16528. if (sampleRate > 0.0)
  16529. setNextReadPosition (roundDoubleToInt (newPosition * sampleRate));
  16530. }
  16531. double AudioTransportSource::getCurrentPosition() const
  16532. {
  16533. if (sampleRate > 0.0)
  16534. return getNextReadPosition() / sampleRate;
  16535. else
  16536. return 0.0;
  16537. }
  16538. void AudioTransportSource::setNextReadPosition (int newPosition)
  16539. {
  16540. if (positionableSource != 0)
  16541. {
  16542. if (sampleRate > 0 && sourceSampleRate > 0)
  16543. newPosition = roundDoubleToInt (newPosition * sourceSampleRate / sampleRate);
  16544. positionableSource->setNextReadPosition (newPosition);
  16545. }
  16546. }
  16547. int AudioTransportSource::getNextReadPosition() const
  16548. {
  16549. if (positionableSource != 0)
  16550. {
  16551. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  16552. return roundDoubleToInt (positionableSource->getNextReadPosition() * ratio);
  16553. }
  16554. return 0;
  16555. }
  16556. int AudioTransportSource::getTotalLength() const
  16557. {
  16558. const ScopedLock sl (callbackLock);
  16559. if (positionableSource != 0)
  16560. {
  16561. const double ratio = (sampleRate > 0 && sourceSampleRate > 0) ? sampleRate / sourceSampleRate : 1.0;
  16562. return roundDoubleToInt (positionableSource->getTotalLength() * ratio);
  16563. }
  16564. return 0;
  16565. }
  16566. bool AudioTransportSource::isLooping() const
  16567. {
  16568. const ScopedLock sl (callbackLock);
  16569. return positionableSource != 0
  16570. && positionableSource->isLooping();
  16571. }
  16572. void AudioTransportSource::setGain (const float newGain) throw()
  16573. {
  16574. gain = newGain;
  16575. }
  16576. void AudioTransportSource::prepareToPlay (int samplesPerBlockExpected,
  16577. double sampleRate_)
  16578. {
  16579. const ScopedLock sl (callbackLock);
  16580. sampleRate = sampleRate_;
  16581. blockSize = samplesPerBlockExpected;
  16582. if (masterSource != 0)
  16583. masterSource->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16584. if (resamplerSource != 0 && sourceSampleRate != 0)
  16585. resamplerSource->setResamplingRatio (sourceSampleRate / sampleRate);
  16586. isPrepared = true;
  16587. }
  16588. void AudioTransportSource::releaseResources()
  16589. {
  16590. const ScopedLock sl (callbackLock);
  16591. if (masterSource != 0)
  16592. masterSource->releaseResources();
  16593. isPrepared = false;
  16594. }
  16595. void AudioTransportSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16596. {
  16597. const ScopedLock sl (callbackLock);
  16598. inputStreamEOF = false;
  16599. if (masterSource != 0 && ! stopped)
  16600. {
  16601. masterSource->getNextAudioBlock (info);
  16602. if (! playing)
  16603. {
  16604. // just stopped playing, so fade out the last block..
  16605. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  16606. info.buffer->applyGainRamp (i, info.startSample, jmin (256, info.numSamples), 1.0f, 0.0f);
  16607. if (info.numSamples > 256)
  16608. info.buffer->clear (info.startSample + 256, info.numSamples - 256);
  16609. }
  16610. if (positionableSource->getNextReadPosition() > positionableSource->getTotalLength() + 1
  16611. && ! positionableSource->isLooping())
  16612. {
  16613. playing = false;
  16614. inputStreamEOF = true;
  16615. sendChangeMessage (this);
  16616. }
  16617. stopped = ! playing;
  16618. for (int i = info.buffer->getNumChannels(); --i >= 0;)
  16619. {
  16620. info.buffer->applyGainRamp (i, info.startSample, info.numSamples,
  16621. lastGain, gain);
  16622. }
  16623. }
  16624. else
  16625. {
  16626. info.clearActiveBufferRegion();
  16627. stopped = true;
  16628. }
  16629. lastGain = gain;
  16630. }
  16631. END_JUCE_NAMESPACE
  16632. /********* End of inlined file: juce_AudioTransportSource.cpp *********/
  16633. /********* Start of inlined file: juce_BufferingAudioSource.cpp *********/
  16634. BEGIN_JUCE_NAMESPACE
  16635. class SharedBufferingAudioSourceThread : public DeletedAtShutdown,
  16636. public Thread,
  16637. private Timer
  16638. {
  16639. public:
  16640. SharedBufferingAudioSourceThread()
  16641. : Thread ("Audio Buffer"),
  16642. sources (8)
  16643. {
  16644. }
  16645. ~SharedBufferingAudioSourceThread()
  16646. {
  16647. stopThread (10000);
  16648. clearSingletonInstance();
  16649. }
  16650. juce_DeclareSingleton (SharedBufferingAudioSourceThread, false)
  16651. void addSource (BufferingAudioSource* source)
  16652. {
  16653. const ScopedLock sl (lock);
  16654. if (! sources.contains ((void*) source))
  16655. {
  16656. sources.add ((void*) source);
  16657. startThread();
  16658. stopTimer();
  16659. }
  16660. notify();
  16661. }
  16662. void removeSource (BufferingAudioSource* source)
  16663. {
  16664. const ScopedLock sl (lock);
  16665. sources.removeValue ((void*) source);
  16666. if (sources.size() == 0)
  16667. startTimer (5000);
  16668. }
  16669. private:
  16670. VoidArray sources;
  16671. CriticalSection lock;
  16672. void run()
  16673. {
  16674. while (! threadShouldExit())
  16675. {
  16676. bool busy = false;
  16677. for (int i = sources.size(); --i >= 0;)
  16678. {
  16679. if (threadShouldExit())
  16680. return;
  16681. const ScopedLock sl (lock);
  16682. BufferingAudioSource* const b = (BufferingAudioSource*) sources[i];
  16683. if (b != 0 && b->readNextBufferChunk())
  16684. busy = true;
  16685. }
  16686. if (! busy)
  16687. wait (500);
  16688. }
  16689. }
  16690. void timerCallback()
  16691. {
  16692. stopTimer();
  16693. if (sources.size() == 0)
  16694. deleteInstance();
  16695. }
  16696. SharedBufferingAudioSourceThread (const SharedBufferingAudioSourceThread&);
  16697. const SharedBufferingAudioSourceThread& operator= (const SharedBufferingAudioSourceThread&);
  16698. };
  16699. juce_ImplementSingleton (SharedBufferingAudioSourceThread)
  16700. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* source_,
  16701. const bool deleteSourceWhenDeleted_,
  16702. int numberOfSamplesToBuffer_)
  16703. : source (source_),
  16704. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  16705. numberOfSamplesToBuffer (jmax (1024, numberOfSamplesToBuffer_)),
  16706. buffer (2, 0),
  16707. bufferValidStart (0),
  16708. bufferValidEnd (0),
  16709. nextPlayPos (0),
  16710. wasSourceLooping (false)
  16711. {
  16712. jassert (source_ != 0);
  16713. jassert (numberOfSamplesToBuffer_ > 1024); // not much point using this class if you're
  16714. // not using a larger buffer..
  16715. }
  16716. BufferingAudioSource::~BufferingAudioSource()
  16717. {
  16718. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16719. if (thread != 0)
  16720. thread->removeSource (this);
  16721. if (deleteSourceWhenDeleted)
  16722. delete source;
  16723. }
  16724. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate_)
  16725. {
  16726. source->prepareToPlay (samplesPerBlockExpected, sampleRate_);
  16727. sampleRate = sampleRate_;
  16728. buffer.setSize (2, jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer));
  16729. buffer.clear();
  16730. bufferValidStart = 0;
  16731. bufferValidEnd = 0;
  16732. SharedBufferingAudioSourceThread::getInstance()->addSource (this);
  16733. while (bufferValidEnd - bufferValidStart < jmin (((int) sampleRate_) / 4,
  16734. buffer.getNumSamples() / 2))
  16735. {
  16736. SharedBufferingAudioSourceThread::getInstance()->notify();
  16737. Thread::sleep (5);
  16738. }
  16739. }
  16740. void BufferingAudioSource::releaseResources()
  16741. {
  16742. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16743. if (thread != 0)
  16744. thread->removeSource (this);
  16745. buffer.setSize (2, 0);
  16746. source->releaseResources();
  16747. }
  16748. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  16749. {
  16750. const ScopedLock sl (bufferStartPosLock);
  16751. const int validStart = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos;
  16752. const int validEnd = jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos;
  16753. if (validStart == validEnd)
  16754. {
  16755. // total cache miss
  16756. info.clearActiveBufferRegion();
  16757. }
  16758. else
  16759. {
  16760. if (validStart > 0)
  16761. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  16762. if (validEnd < info.numSamples)
  16763. info.buffer->clear (info.startSample + validEnd,
  16764. info.numSamples - validEnd); // partial cache miss at end
  16765. if (validStart < validEnd)
  16766. {
  16767. for (int chan = jmin (2, info.buffer->getNumChannels()); --chan >= 0;)
  16768. {
  16769. const int startBufferIndex = (validStart + nextPlayPos) % buffer.getNumSamples();
  16770. const int endBufferIndex = (validEnd + nextPlayPos) % buffer.getNumSamples();
  16771. if (startBufferIndex < endBufferIndex)
  16772. {
  16773. info.buffer->copyFrom (chan, info.startSample + validStart,
  16774. buffer,
  16775. chan, startBufferIndex,
  16776. validEnd - validStart);
  16777. }
  16778. else
  16779. {
  16780. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  16781. info.buffer->copyFrom (chan, info.startSample + validStart,
  16782. buffer,
  16783. chan, startBufferIndex,
  16784. initialSize);
  16785. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  16786. buffer,
  16787. chan, 0,
  16788. (validEnd - validStart) - initialSize);
  16789. }
  16790. }
  16791. }
  16792. nextPlayPos += info.numSamples;
  16793. }
  16794. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16795. if (thread != 0)
  16796. thread->notify();
  16797. }
  16798. int BufferingAudioSource::getNextReadPosition() const
  16799. {
  16800. return (source->isLooping() && nextPlayPos > 0)
  16801. ? nextPlayPos % source->getTotalLength()
  16802. : nextPlayPos;
  16803. }
  16804. void BufferingAudioSource::setNextReadPosition (int newPosition)
  16805. {
  16806. const ScopedLock sl (bufferStartPosLock);
  16807. nextPlayPos = newPosition;
  16808. SharedBufferingAudioSourceThread* const thread = SharedBufferingAudioSourceThread::getInstanceWithoutCreating();
  16809. if (thread != 0)
  16810. thread->notify();
  16811. }
  16812. bool BufferingAudioSource::readNextBufferChunk()
  16813. {
  16814. bufferStartPosLock.enter();
  16815. if (wasSourceLooping != isLooping())
  16816. {
  16817. wasSourceLooping = isLooping();
  16818. bufferValidStart = 0;
  16819. bufferValidEnd = 0;
  16820. }
  16821. int newBVS = jmax (0, nextPlayPos);
  16822. int newBVE = newBVS + buffer.getNumSamples() - 4;
  16823. int sectionToReadStart = 0;
  16824. int sectionToReadEnd = 0;
  16825. const int maxChunkSize = 2048;
  16826. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  16827. {
  16828. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  16829. sectionToReadStart = newBVS;
  16830. sectionToReadEnd = newBVE;
  16831. bufferValidStart = 0;
  16832. bufferValidEnd = 0;
  16833. }
  16834. else if (abs (newBVS - bufferValidStart) > 512
  16835. || abs (newBVE - bufferValidEnd) > 512)
  16836. {
  16837. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  16838. sectionToReadStart = bufferValidEnd;
  16839. sectionToReadEnd = newBVE;
  16840. bufferValidStart = newBVS;
  16841. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  16842. }
  16843. bufferStartPosLock.exit();
  16844. if (sectionToReadStart != sectionToReadEnd)
  16845. {
  16846. const int bufferIndexStart = sectionToReadStart % buffer.getNumSamples();
  16847. const int bufferIndexEnd = sectionToReadEnd % buffer.getNumSamples();
  16848. if (bufferIndexStart < bufferIndexEnd)
  16849. {
  16850. readBufferSection (sectionToReadStart,
  16851. sectionToReadEnd - sectionToReadStart,
  16852. bufferIndexStart);
  16853. }
  16854. else
  16855. {
  16856. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  16857. readBufferSection (sectionToReadStart,
  16858. initialSize,
  16859. bufferIndexStart);
  16860. readBufferSection (sectionToReadStart + initialSize,
  16861. (sectionToReadEnd - sectionToReadStart) - initialSize,
  16862. 0);
  16863. }
  16864. const ScopedLock sl2 (bufferStartPosLock);
  16865. bufferValidStart = newBVS;
  16866. bufferValidEnd = newBVE;
  16867. return true;
  16868. }
  16869. else
  16870. {
  16871. return false;
  16872. }
  16873. }
  16874. void BufferingAudioSource::readBufferSection (int start, int length, int bufferOffset)
  16875. {
  16876. if (source->getNextReadPosition() != start)
  16877. source->setNextReadPosition (start);
  16878. AudioSourceChannelInfo info;
  16879. info.buffer = &buffer;
  16880. info.startSample = bufferOffset;
  16881. info.numSamples = length;
  16882. source->getNextAudioBlock (info);
  16883. }
  16884. END_JUCE_NAMESPACE
  16885. /********* End of inlined file: juce_BufferingAudioSource.cpp *********/
  16886. /********* Start of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  16887. BEGIN_JUCE_NAMESPACE
  16888. ChannelRemappingAudioSource::ChannelRemappingAudioSource (AudioSource* const source_,
  16889. const bool deleteSourceWhenDeleted_)
  16890. : requiredNumberOfChannels (2),
  16891. source (source_),
  16892. deleteSourceWhenDeleted (deleteSourceWhenDeleted_),
  16893. buffer (2, 16)
  16894. {
  16895. remappedInfo.buffer = &buffer;
  16896. remappedInfo.startSample = 0;
  16897. }
  16898. ChannelRemappingAudioSource::~ChannelRemappingAudioSource()
  16899. {
  16900. if (deleteSourceWhenDeleted)
  16901. delete source;
  16902. }
  16903. void ChannelRemappingAudioSource::setNumberOfChannelsToProduce (const int requiredNumberOfChannels_) throw()
  16904. {
  16905. const ScopedLock sl (lock);
  16906. requiredNumberOfChannels = requiredNumberOfChannels_;
  16907. }
  16908. void ChannelRemappingAudioSource::clearAllMappings() throw()
  16909. {
  16910. const ScopedLock sl (lock);
  16911. remappedInputs.clear();
  16912. remappedOutputs.clear();
  16913. }
  16914. void ChannelRemappingAudioSource::setInputChannelMapping (const int destIndex, const int sourceIndex) throw()
  16915. {
  16916. const ScopedLock sl (lock);
  16917. while (remappedInputs.size() < destIndex)
  16918. remappedInputs.add (-1);
  16919. remappedInputs.set (destIndex, sourceIndex);
  16920. }
  16921. void ChannelRemappingAudioSource::setOutputChannelMapping (const int sourceIndex, const int destIndex) throw()
  16922. {
  16923. const ScopedLock sl (lock);
  16924. while (remappedOutputs.size() < sourceIndex)
  16925. remappedOutputs.add (-1);
  16926. remappedOutputs.set (sourceIndex, destIndex);
  16927. }
  16928. int ChannelRemappingAudioSource::getRemappedInputChannel (const int inputChannelIndex) const throw()
  16929. {
  16930. const ScopedLock sl (lock);
  16931. if (inputChannelIndex >= 0 && inputChannelIndex < remappedInputs.size())
  16932. return remappedInputs.getUnchecked (inputChannelIndex);
  16933. return -1;
  16934. }
  16935. int ChannelRemappingAudioSource::getRemappedOutputChannel (const int outputChannelIndex) const throw()
  16936. {
  16937. const ScopedLock sl (lock);
  16938. if (outputChannelIndex >= 0 && outputChannelIndex < remappedOutputs.size())
  16939. return remappedOutputs .getUnchecked (outputChannelIndex);
  16940. return -1;
  16941. }
  16942. void ChannelRemappingAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  16943. {
  16944. source->prepareToPlay (samplesPerBlockExpected, sampleRate);
  16945. }
  16946. void ChannelRemappingAudioSource::releaseResources()
  16947. {
  16948. source->releaseResources();
  16949. }
  16950. void ChannelRemappingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  16951. {
  16952. const ScopedLock sl (lock);
  16953. buffer.setSize (requiredNumberOfChannels, bufferToFill.numSamples, false, false, true);
  16954. const int numChans = bufferToFill.buffer->getNumChannels();
  16955. int i;
  16956. for (i = 0; i < buffer.getNumChannels(); ++i)
  16957. {
  16958. const int remappedChan = getRemappedInputChannel (i);
  16959. if (remappedChan >= 0 && remappedChan < numChans)
  16960. {
  16961. buffer.copyFrom (i, 0, *bufferToFill.buffer,
  16962. remappedChan,
  16963. bufferToFill.startSample,
  16964. bufferToFill.numSamples);
  16965. }
  16966. else
  16967. {
  16968. buffer.clear (i, 0, bufferToFill.numSamples);
  16969. }
  16970. }
  16971. remappedInfo.numSamples = bufferToFill.numSamples;
  16972. source->getNextAudioBlock (remappedInfo);
  16973. bufferToFill.clearActiveBufferRegion();
  16974. for (i = 0; i < requiredNumberOfChannels; ++i)
  16975. {
  16976. const int remappedChan = getRemappedOutputChannel (i);
  16977. if (remappedChan >= 0 && remappedChan < numChans)
  16978. {
  16979. bufferToFill.buffer->addFrom (remappedChan, bufferToFill.startSample,
  16980. buffer, i, 0, bufferToFill.numSamples);
  16981. }
  16982. }
  16983. }
  16984. XmlElement* ChannelRemappingAudioSource::createXml() const throw()
  16985. {
  16986. XmlElement* e = new XmlElement (T("MAPPINGS"));
  16987. String ins, outs;
  16988. int i;
  16989. const ScopedLock sl (lock);
  16990. for (i = 0; i < remappedInputs.size(); ++i)
  16991. ins << remappedInputs.getUnchecked(i) << T(' ');
  16992. for (i = 0; i < remappedOutputs.size(); ++i)
  16993. outs << remappedOutputs.getUnchecked(i) << T(' ');
  16994. e->setAttribute (T("inputs"), ins.trimEnd());
  16995. e->setAttribute (T("outputs"), outs.trimEnd());
  16996. return e;
  16997. }
  16998. void ChannelRemappingAudioSource::restoreFromXml (const XmlElement& e) throw()
  16999. {
  17000. if (e.hasTagName (T("MAPPINGS")))
  17001. {
  17002. const ScopedLock sl (lock);
  17003. clearAllMappings();
  17004. StringArray ins, outs;
  17005. ins.addTokens (e.getStringAttribute (T("inputs")), false);
  17006. outs.addTokens (e.getStringAttribute (T("outputs")), false);
  17007. int i;
  17008. for (i = 0; i < ins.size(); ++i)
  17009. remappedInputs.add (ins[i].getIntValue());
  17010. for (i = 0; i < outs.size(); ++i)
  17011. remappedOutputs.add (outs[i].getIntValue());
  17012. }
  17013. }
  17014. END_JUCE_NAMESPACE
  17015. /********* End of inlined file: juce_ChannelRemappingAudioSource.cpp *********/
  17016. /********* Start of inlined file: juce_IIRFilterAudioSource.cpp *********/
  17017. BEGIN_JUCE_NAMESPACE
  17018. IIRFilterAudioSource::IIRFilterAudioSource (AudioSource* const inputSource,
  17019. const bool deleteInputWhenDeleted_)
  17020. : input (inputSource),
  17021. deleteInputWhenDeleted (deleteInputWhenDeleted_)
  17022. {
  17023. jassert (inputSource != 0);
  17024. for (int i = 2; --i >= 0;)
  17025. iirFilters.add (new IIRFilter());
  17026. }
  17027. IIRFilterAudioSource::~IIRFilterAudioSource()
  17028. {
  17029. if (deleteInputWhenDeleted)
  17030. delete input;
  17031. }
  17032. void IIRFilterAudioSource::setFilterParameters (const IIRFilter& newSettings)
  17033. {
  17034. for (int i = iirFilters.size(); --i >= 0;)
  17035. iirFilters.getUnchecked(i)->copyCoefficientsFrom (newSettings);
  17036. }
  17037. void IIRFilterAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  17038. {
  17039. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  17040. for (int i = iirFilters.size(); --i >= 0;)
  17041. iirFilters.getUnchecked(i)->reset();
  17042. }
  17043. void IIRFilterAudioSource::releaseResources()
  17044. {
  17045. input->releaseResources();
  17046. }
  17047. void IIRFilterAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill)
  17048. {
  17049. input->getNextAudioBlock (bufferToFill);
  17050. const int numChannels = bufferToFill.buffer->getNumChannels();
  17051. while (numChannels > iirFilters.size())
  17052. iirFilters.add (new IIRFilter (*iirFilters.getUnchecked (0)));
  17053. for (int i = 0; i < numChannels; ++i)
  17054. iirFilters.getUnchecked(i)
  17055. ->processSamples (bufferToFill.buffer->getSampleData (i, bufferToFill.startSample),
  17056. bufferToFill.numSamples);
  17057. }
  17058. END_JUCE_NAMESPACE
  17059. /********* End of inlined file: juce_IIRFilterAudioSource.cpp *********/
  17060. /********* Start of inlined file: juce_MixerAudioSource.cpp *********/
  17061. BEGIN_JUCE_NAMESPACE
  17062. MixerAudioSource::MixerAudioSource()
  17063. : tempBuffer (2, 0),
  17064. currentSampleRate (0.0),
  17065. bufferSizeExpected (0)
  17066. {
  17067. }
  17068. MixerAudioSource::~MixerAudioSource()
  17069. {
  17070. removeAllInputs();
  17071. }
  17072. void MixerAudioSource::addInputSource (AudioSource* input, const bool deleteWhenRemoved)
  17073. {
  17074. if (input != 0 && ! inputs.contains (input))
  17075. {
  17076. lock.enter();
  17077. double localRate = currentSampleRate;
  17078. int localBufferSize = bufferSizeExpected;
  17079. lock.exit();
  17080. if (localRate != 0.0)
  17081. input->prepareToPlay (localBufferSize, localRate);
  17082. const ScopedLock sl (lock);
  17083. inputsToDelete.setBit (inputs.size(), deleteWhenRemoved);
  17084. inputs.add (input);
  17085. }
  17086. }
  17087. void MixerAudioSource::removeInputSource (AudioSource* input, const bool deleteInput)
  17088. {
  17089. if (input != 0)
  17090. {
  17091. lock.enter();
  17092. const int index = inputs.indexOf ((void*) input);
  17093. if (index >= 0)
  17094. {
  17095. inputsToDelete.shiftBits (index, 1);
  17096. inputs.remove (index);
  17097. }
  17098. lock.exit();
  17099. if (index >= 0)
  17100. {
  17101. input->releaseResources();
  17102. if (deleteInput)
  17103. delete input;
  17104. }
  17105. }
  17106. }
  17107. void MixerAudioSource::removeAllInputs()
  17108. {
  17109. lock.enter();
  17110. VoidArray inputsCopy (inputs);
  17111. BitArray inputsToDeleteCopy (inputsToDelete);
  17112. inputs.clear();
  17113. lock.exit();
  17114. for (int i = inputsCopy.size(); --i >= 0;)
  17115. if (inputsToDeleteCopy[i])
  17116. delete (AudioSource*) inputsCopy[i];
  17117. }
  17118. void MixerAudioSource::prepareToPlay (int samplesPerBlockExpected, double sampleRate)
  17119. {
  17120. tempBuffer.setSize (2, samplesPerBlockExpected);
  17121. const ScopedLock sl (lock);
  17122. currentSampleRate = sampleRate;
  17123. bufferSizeExpected = samplesPerBlockExpected;
  17124. for (int i = inputs.size(); --i >= 0;)
  17125. ((AudioSource*) inputs.getUnchecked(i))->prepareToPlay (samplesPerBlockExpected,
  17126. sampleRate);
  17127. }
  17128. void MixerAudioSource::releaseResources()
  17129. {
  17130. const ScopedLock sl (lock);
  17131. for (int i = inputs.size(); --i >= 0;)
  17132. ((AudioSource*) inputs.getUnchecked(i))->releaseResources();
  17133. tempBuffer.setSize (2, 0);
  17134. currentSampleRate = 0;
  17135. bufferSizeExpected = 0;
  17136. }
  17137. void MixerAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17138. {
  17139. const ScopedLock sl (lock);
  17140. if (inputs.size() > 0)
  17141. {
  17142. ((AudioSource*) inputs.getUnchecked(0))->getNextAudioBlock (info);
  17143. if (inputs.size() > 1)
  17144. {
  17145. tempBuffer.setSize (jmax (1, info.buffer->getNumChannels()),
  17146. info.buffer->getNumSamples());
  17147. AudioSourceChannelInfo info2;
  17148. info2.buffer = &tempBuffer;
  17149. info2.numSamples = info.numSamples;
  17150. info2.startSample = 0;
  17151. for (int i = 1; i < inputs.size(); ++i)
  17152. {
  17153. ((AudioSource*) inputs.getUnchecked(i))->getNextAudioBlock (info2);
  17154. for (int chan = 0; chan < info.buffer->getNumChannels(); ++chan)
  17155. info.buffer->addFrom (chan, info.startSample, tempBuffer, chan, 0, info.numSamples);
  17156. }
  17157. }
  17158. }
  17159. else
  17160. {
  17161. info.clearActiveBufferRegion();
  17162. }
  17163. }
  17164. END_JUCE_NAMESPACE
  17165. /********* End of inlined file: juce_MixerAudioSource.cpp *********/
  17166. /********* Start of inlined file: juce_ResamplingAudioSource.cpp *********/
  17167. BEGIN_JUCE_NAMESPACE
  17168. ResamplingAudioSource::ResamplingAudioSource (AudioSource* const inputSource,
  17169. const bool deleteInputWhenDeleted_)
  17170. : input (inputSource),
  17171. deleteInputWhenDeleted (deleteInputWhenDeleted_),
  17172. ratio (1.0),
  17173. lastRatio (1.0),
  17174. buffer (2, 0),
  17175. sampsInBuffer (0)
  17176. {
  17177. jassert (input != 0);
  17178. }
  17179. ResamplingAudioSource::~ResamplingAudioSource()
  17180. {
  17181. if (deleteInputWhenDeleted)
  17182. delete input;
  17183. }
  17184. void ResamplingAudioSource::setResamplingRatio (const double samplesInPerOutputSample)
  17185. {
  17186. jassert (samplesInPerOutputSample > 0);
  17187. const ScopedLock sl (ratioLock);
  17188. ratio = jmax (0.0, samplesInPerOutputSample);
  17189. }
  17190. void ResamplingAudioSource::prepareToPlay (int samplesPerBlockExpected,
  17191. double sampleRate)
  17192. {
  17193. const ScopedLock sl (ratioLock);
  17194. input->prepareToPlay (samplesPerBlockExpected, sampleRate);
  17195. buffer.setSize (2, roundDoubleToInt (samplesPerBlockExpected * ratio) + 32);
  17196. buffer.clear();
  17197. sampsInBuffer = 0;
  17198. bufferPos = 0;
  17199. subSampleOffset = 0.0;
  17200. createLowPass (ratio);
  17201. resetFilters();
  17202. }
  17203. void ResamplingAudioSource::releaseResources()
  17204. {
  17205. input->releaseResources();
  17206. buffer.setSize (2, 0);
  17207. }
  17208. void ResamplingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17209. {
  17210. const ScopedLock sl (ratioLock);
  17211. if (lastRatio != ratio)
  17212. {
  17213. createLowPass (ratio);
  17214. lastRatio = ratio;
  17215. }
  17216. const int sampsNeeded = roundDoubleToInt (info.numSamples * ratio) + 2;
  17217. int bufferSize = buffer.getNumSamples();
  17218. if (bufferSize < sampsNeeded + 8)
  17219. {
  17220. bufferPos %= bufferSize;
  17221. bufferSize = sampsNeeded + 32;
  17222. buffer.setSize (buffer.getNumChannels(), bufferSize, true, true);
  17223. }
  17224. bufferPos %= bufferSize;
  17225. int endOfBufferPos = bufferPos + sampsInBuffer;
  17226. while (sampsNeeded > sampsInBuffer)
  17227. {
  17228. endOfBufferPos %= bufferSize;
  17229. int numToDo = jmin (sampsNeeded - sampsInBuffer,
  17230. bufferSize - endOfBufferPos);
  17231. AudioSourceChannelInfo readInfo;
  17232. readInfo.buffer = &buffer;
  17233. readInfo.numSamples = numToDo;
  17234. readInfo.startSample = endOfBufferPos;
  17235. input->getNextAudioBlock (readInfo);
  17236. if (ratio > 1.0)
  17237. {
  17238. // for down-sampling, pre-apply the filter..
  17239. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  17240. applyFilter (buffer.getSampleData (i, endOfBufferPos), numToDo, filterStates[i]);
  17241. }
  17242. sampsInBuffer += numToDo;
  17243. endOfBufferPos += numToDo;
  17244. }
  17245. float* dl = info.buffer->getSampleData (0, info.startSample);
  17246. float* dr = (info.buffer->getNumChannels() > 1) ? info.buffer->getSampleData (1, info.startSample) : 0;
  17247. const float* const bl = buffer.getSampleData (0, 0);
  17248. const float* const br = buffer.getSampleData (1, 0);
  17249. int nextPos = (bufferPos + 1) % bufferSize;
  17250. for (int m = info.numSamples; --m >= 0;)
  17251. {
  17252. const float alpha = (float) subSampleOffset;
  17253. const float invAlpha = 1.0f - alpha;
  17254. *dl++ = bl [bufferPos] * invAlpha + bl [nextPos] * alpha;
  17255. if (dr != 0)
  17256. *dr++ = br [bufferPos] * invAlpha + br [nextPos] * alpha;
  17257. subSampleOffset += ratio;
  17258. jassert (sampsInBuffer > 0);
  17259. while (subSampleOffset >= 1.0)
  17260. {
  17261. if (++bufferPos >= bufferSize)
  17262. bufferPos = 0;
  17263. --sampsInBuffer;
  17264. nextPos = (bufferPos + 1) % bufferSize;
  17265. subSampleOffset -= 1.0;
  17266. }
  17267. }
  17268. if (ratio < 1.0)
  17269. {
  17270. // for up-sampling, apply the filter after transposing..
  17271. for (int i = jmin (2, info.buffer->getNumChannels()); --i >= 0;)
  17272. applyFilter (info.buffer->getSampleData (i, info.startSample), info.numSamples, filterStates[i]);
  17273. }
  17274. jassert (sampsInBuffer >= 0);
  17275. }
  17276. void ResamplingAudioSource::createLowPass (const double ratio)
  17277. {
  17278. const double proportionalRate = (ratio > 1.0) ? 0.5 / ratio
  17279. : 0.5 * ratio;
  17280. const double n = 1.0 / tan (double_Pi * jmax (0.001, proportionalRate));
  17281. const double nSquared = n * n;
  17282. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  17283. setFilterCoefficients (c1,
  17284. c1 * 2.0f,
  17285. c1,
  17286. 1.0,
  17287. c1 * 2.0 * (1.0 - nSquared),
  17288. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  17289. }
  17290. void ResamplingAudioSource::setFilterCoefficients (double c1, double c2, double c3, double c4, double c5, double c6)
  17291. {
  17292. const double a = 1.0 / c4;
  17293. c1 *= a;
  17294. c2 *= a;
  17295. c3 *= a;
  17296. c5 *= a;
  17297. c6 *= a;
  17298. coefficients[0] = c1;
  17299. coefficients[1] = c2;
  17300. coefficients[2] = c3;
  17301. coefficients[3] = c4;
  17302. coefficients[4] = c5;
  17303. coefficients[5] = c6;
  17304. }
  17305. void ResamplingAudioSource::resetFilters()
  17306. {
  17307. zeromem (filterStates, sizeof (filterStates));
  17308. }
  17309. void ResamplingAudioSource::applyFilter (float* samples, int num, FilterState& fs)
  17310. {
  17311. while (--num >= 0)
  17312. {
  17313. const double in = *samples;
  17314. double out = coefficients[0] * in
  17315. + coefficients[1] * fs.x1
  17316. + coefficients[2] * fs.x2
  17317. - coefficients[4] * fs.y1
  17318. - coefficients[5] * fs.y2;
  17319. #if JUCE_INTEL
  17320. if (! (out < -1.0e-8 || out > 1.0e-8))
  17321. out = 0;
  17322. #endif
  17323. fs.x2 = fs.x1;
  17324. fs.x1 = in;
  17325. fs.y2 = fs.y1;
  17326. fs.y1 = out;
  17327. *samples++ = (float) out;
  17328. }
  17329. }
  17330. END_JUCE_NAMESPACE
  17331. /********* End of inlined file: juce_ResamplingAudioSource.cpp *********/
  17332. /********* Start of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  17333. BEGIN_JUCE_NAMESPACE
  17334. ToneGeneratorAudioSource::ToneGeneratorAudioSource()
  17335. : frequency (1000.0),
  17336. sampleRate (44100.0),
  17337. currentPhase (0.0),
  17338. phasePerSample (0.0),
  17339. amplitude (0.5f)
  17340. {
  17341. }
  17342. ToneGeneratorAudioSource::~ToneGeneratorAudioSource()
  17343. {
  17344. }
  17345. void ToneGeneratorAudioSource::setAmplitude (const float newAmplitude)
  17346. {
  17347. amplitude = newAmplitude;
  17348. }
  17349. void ToneGeneratorAudioSource::setFrequency (const double newFrequencyHz)
  17350. {
  17351. frequency = newFrequencyHz;
  17352. phasePerSample = 0.0;
  17353. }
  17354. void ToneGeneratorAudioSource::prepareToPlay (int /*samplesPerBlockExpected*/,
  17355. double sampleRate_)
  17356. {
  17357. currentPhase = 0.0;
  17358. phasePerSample = 0.0;
  17359. sampleRate = sampleRate_;
  17360. }
  17361. void ToneGeneratorAudioSource::releaseResources()
  17362. {
  17363. }
  17364. void ToneGeneratorAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  17365. {
  17366. if (phasePerSample == 0.0)
  17367. phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  17368. for (int i = 0; i < info.numSamples; ++i)
  17369. {
  17370. const float sample = amplitude * (float) sin (currentPhase);
  17371. currentPhase += phasePerSample;
  17372. for (int j = info.buffer->getNumChannels(); --j >= 0;)
  17373. *info.buffer->getSampleData (j, info.startSample + i) = sample;
  17374. }
  17375. }
  17376. END_JUCE_NAMESPACE
  17377. /********* End of inlined file: juce_ToneGeneratorAudioSource.cpp *********/
  17378. /********* Start of inlined file: juce_AudioDeviceManager.cpp *********/
  17379. BEGIN_JUCE_NAMESPACE
  17380. AudioDeviceManager::AudioDeviceSetup::AudioDeviceSetup()
  17381. : sampleRate (0),
  17382. bufferSize (0),
  17383. useDefaultInputChannels (true),
  17384. useDefaultOutputChannels (true)
  17385. {
  17386. }
  17387. bool AudioDeviceManager::AudioDeviceSetup::operator== (const AudioDeviceManager::AudioDeviceSetup& other) const
  17388. {
  17389. return outputDeviceName == other.outputDeviceName
  17390. && inputDeviceName == other.inputDeviceName
  17391. && sampleRate == other.sampleRate
  17392. && bufferSize == other.bufferSize
  17393. && inputChannels == other.inputChannels
  17394. && useDefaultInputChannels == other.useDefaultInputChannels
  17395. && outputChannels == other.outputChannels
  17396. && useDefaultOutputChannels == other.useDefaultOutputChannels;
  17397. }
  17398. AudioDeviceManager::AudioDeviceManager()
  17399. : currentAudioDevice (0),
  17400. currentCallback (0),
  17401. numInputChansNeeded (0),
  17402. numOutputChansNeeded (2),
  17403. lastExplicitSettings (0),
  17404. listNeedsScanning (true),
  17405. useInputNames (false),
  17406. inputLevelMeasurementEnabled (false),
  17407. inputLevel (0),
  17408. testSound (0),
  17409. enabledMidiInputs (4),
  17410. midiCallbacks (4),
  17411. midiCallbackDevices (4),
  17412. defaultMidiOutput (0),
  17413. cpuUsageMs (0),
  17414. timeToCpuScale (0)
  17415. {
  17416. callbackHandler.owner = this;
  17417. }
  17418. AudioDeviceManager::~AudioDeviceManager()
  17419. {
  17420. deleteAndZero (currentAudioDevice);
  17421. deleteAndZero (defaultMidiOutput);
  17422. delete lastExplicitSettings;
  17423. delete testSound;
  17424. }
  17425. void AudioDeviceManager::createDeviceTypesIfNeeded()
  17426. {
  17427. if (availableDeviceTypes.size() == 0)
  17428. {
  17429. createAudioDeviceTypes (availableDeviceTypes);
  17430. while (lastDeviceTypeConfigs.size() < availableDeviceTypes.size())
  17431. lastDeviceTypeConfigs.add (new AudioDeviceSetup());
  17432. if (availableDeviceTypes.size() > 0)
  17433. currentDeviceType = availableDeviceTypes.getUnchecked(0)->getTypeName();
  17434. }
  17435. }
  17436. const OwnedArray <AudioIODeviceType>& AudioDeviceManager::getAvailableDeviceTypes()
  17437. {
  17438. scanDevicesIfNeeded();
  17439. return availableDeviceTypes;
  17440. }
  17441. extern AudioIODeviceType* juce_createDefaultAudioIODeviceType();
  17442. #if JUCE_WIN32 && JUCE_ASIO
  17443. extern AudioIODeviceType* juce_createASIOAudioIODeviceType();
  17444. #endif
  17445. #if JUCE_WIN32 && JUCE_WDM_AUDIO
  17446. extern AudioIODeviceType* juce_createWDMAudioIODeviceType();
  17447. #endif
  17448. void AudioDeviceManager::createAudioDeviceTypes (OwnedArray <AudioIODeviceType>& list)
  17449. {
  17450. AudioIODeviceType* const defaultDeviceType = juce_createDefaultAudioIODeviceType();
  17451. if (defaultDeviceType != 0)
  17452. list.add (defaultDeviceType);
  17453. #if JUCE_WIN32 && JUCE_ASIO
  17454. list.add (juce_createASIOAudioIODeviceType());
  17455. #endif
  17456. #if JUCE_WIN32 && JUCE_WDM_AUDIO
  17457. list.add (juce_createWDMAudioIODeviceType());
  17458. #endif
  17459. }
  17460. const String AudioDeviceManager::initialise (const int numInputChannelsNeeded,
  17461. const int numOutputChannelsNeeded,
  17462. const XmlElement* const e,
  17463. const bool selectDefaultDeviceOnFailure,
  17464. const String& preferredDefaultDeviceName)
  17465. {
  17466. scanDevicesIfNeeded();
  17467. numInputChansNeeded = numInputChannelsNeeded;
  17468. numOutputChansNeeded = numOutputChannelsNeeded;
  17469. if (e != 0 && e->hasTagName (T("DEVICESETUP")))
  17470. {
  17471. delete lastExplicitSettings;
  17472. lastExplicitSettings = new XmlElement (*e);
  17473. String error;
  17474. AudioDeviceSetup setup;
  17475. if (e->getStringAttribute (T("audioDeviceName")).isNotEmpty())
  17476. {
  17477. setup.inputDeviceName = setup.outputDeviceName
  17478. = e->getStringAttribute (T("audioDeviceName"));
  17479. }
  17480. else
  17481. {
  17482. setup.inputDeviceName = e->getStringAttribute (T("audioInputDeviceName"));
  17483. setup.outputDeviceName = e->getStringAttribute (T("audioOutputDeviceName"));
  17484. }
  17485. currentDeviceType = e->getStringAttribute (T("deviceType"));
  17486. if (currentDeviceType.isEmpty())
  17487. {
  17488. AudioIODeviceType* const type = findType (setup.inputDeviceName, setup.outputDeviceName);
  17489. if (type != 0)
  17490. currentDeviceType = type->getTypeName();
  17491. else if (availableDeviceTypes.size() > 0)
  17492. currentDeviceType = availableDeviceTypes[0]->getTypeName();
  17493. }
  17494. setup.bufferSize = e->getIntAttribute (T("audioDeviceBufferSize"));
  17495. setup.sampleRate = e->getDoubleAttribute (T("audioDeviceRate"));
  17496. setup.inputChannels.parseString (e->getStringAttribute (T("audioDeviceInChans"), T("11")), 2);
  17497. setup.outputChannels.parseString (e->getStringAttribute (T("audioDeviceOutChans"), T("11")), 2);
  17498. setup.useDefaultInputChannels = ! e->hasAttribute (T("audioDeviceInChans"));
  17499. setup.useDefaultOutputChannels = ! e->hasAttribute (T("audioDeviceOutChans"));
  17500. error = setAudioDeviceSetup (setup, true);
  17501. midiInsFromXml.clear();
  17502. forEachXmlChildElementWithTagName (*e, c, T("MIDIINPUT"))
  17503. midiInsFromXml.add (c->getStringAttribute (T("name")));
  17504. const StringArray allMidiIns (MidiInput::getDevices());
  17505. for (int i = allMidiIns.size(); --i >= 0;)
  17506. setMidiInputEnabled (allMidiIns[i], midiInsFromXml.contains (allMidiIns[i]));
  17507. if (error.isNotEmpty() && selectDefaultDeviceOnFailure)
  17508. error = initialise (numInputChannelsNeeded, numOutputChannelsNeeded, 0,
  17509. false, preferredDefaultDeviceName);
  17510. setDefaultMidiOutput (e->getStringAttribute (T("defaultMidiOutput")));
  17511. return error;
  17512. }
  17513. else
  17514. {
  17515. AudioDeviceSetup setup;
  17516. if (preferredDefaultDeviceName.isNotEmpty())
  17517. {
  17518. for (int j = availableDeviceTypes.size(); --j >= 0;)
  17519. {
  17520. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(j);
  17521. StringArray outs (type->getDeviceNames (false));
  17522. int i;
  17523. for (i = 0; i < outs.size(); ++i)
  17524. {
  17525. if (outs[i].matchesWildcard (preferredDefaultDeviceName, true))
  17526. {
  17527. setup.outputDeviceName = outs[i];
  17528. break;
  17529. }
  17530. }
  17531. StringArray ins (type->getDeviceNames (true));
  17532. for (i = 0; i < ins.size(); ++i)
  17533. {
  17534. if (ins[i].matchesWildcard (preferredDefaultDeviceName, true))
  17535. {
  17536. setup.inputDeviceName = ins[i];
  17537. break;
  17538. }
  17539. }
  17540. }
  17541. }
  17542. insertDefaultDeviceNames (setup);
  17543. return setAudioDeviceSetup (setup, false);
  17544. }
  17545. }
  17546. void AudioDeviceManager::insertDefaultDeviceNames (AudioDeviceSetup& setup) const
  17547. {
  17548. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  17549. if (type != 0)
  17550. {
  17551. if (setup.outputDeviceName.isEmpty())
  17552. setup.outputDeviceName = type->getDeviceNames (false) [type->getDefaultDeviceIndex (false)];
  17553. if (setup.inputDeviceName.isEmpty())
  17554. setup.inputDeviceName = type->getDeviceNames (true) [type->getDefaultDeviceIndex (true)];
  17555. }
  17556. }
  17557. XmlElement* AudioDeviceManager::createStateXml() const
  17558. {
  17559. return lastExplicitSettings != 0 ? new XmlElement (*lastExplicitSettings) : 0;
  17560. }
  17561. void AudioDeviceManager::scanDevicesIfNeeded()
  17562. {
  17563. if (listNeedsScanning)
  17564. {
  17565. listNeedsScanning = false;
  17566. createDeviceTypesIfNeeded();
  17567. for (int i = availableDeviceTypes.size(); --i >= 0;)
  17568. availableDeviceTypes.getUnchecked(i)->scanForDevices();
  17569. }
  17570. }
  17571. AudioIODeviceType* AudioDeviceManager::findType (const String& inputName, const String& outputName)
  17572. {
  17573. scanDevicesIfNeeded();
  17574. for (int i = availableDeviceTypes.size(); --i >= 0;)
  17575. {
  17576. AudioIODeviceType* const type = availableDeviceTypes.getUnchecked(i);
  17577. if ((inputName.isNotEmpty() && type->getDeviceNames (true).contains (inputName, true))
  17578. || (outputName.isNotEmpty() && type->getDeviceNames (false).contains (outputName, true)))
  17579. {
  17580. return type;
  17581. }
  17582. }
  17583. return 0;
  17584. }
  17585. void AudioDeviceManager::getAudioDeviceSetup (AudioDeviceSetup& setup)
  17586. {
  17587. setup = currentSetup;
  17588. }
  17589. void AudioDeviceManager::deleteCurrentDevice()
  17590. {
  17591. deleteAndZero (currentAudioDevice);
  17592. currentSetup.inputDeviceName = String::empty;
  17593. currentSetup.outputDeviceName = String::empty;
  17594. }
  17595. void AudioDeviceManager::setCurrentAudioDeviceType (const String& type,
  17596. const bool treatAsChosenDevice)
  17597. {
  17598. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  17599. {
  17600. if (availableDeviceTypes.getUnchecked(i)->getTypeName() == type
  17601. && currentDeviceType != type)
  17602. {
  17603. currentDeviceType = type;
  17604. AudioDeviceSetup s (*lastDeviceTypeConfigs.getUnchecked(i));
  17605. insertDefaultDeviceNames (s);
  17606. setAudioDeviceSetup (s, treatAsChosenDevice);
  17607. sendChangeMessage (this);
  17608. break;
  17609. }
  17610. }
  17611. }
  17612. AudioIODeviceType* AudioDeviceManager::getCurrentDeviceTypeObject() const
  17613. {
  17614. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  17615. if (availableDeviceTypes[i]->getTypeName() == currentDeviceType)
  17616. return availableDeviceTypes[i];
  17617. return availableDeviceTypes[0];
  17618. }
  17619. const String AudioDeviceManager::setAudioDeviceSetup (const AudioDeviceSetup& newSetup,
  17620. const bool treatAsChosenDevice)
  17621. {
  17622. jassert (&newSetup != &currentSetup); // this will have no effect
  17623. if (newSetup == currentSetup && currentAudioDevice != 0)
  17624. return String::empty;
  17625. if (! (newSetup == currentSetup))
  17626. sendChangeMessage (this);
  17627. stopDevice();
  17628. String error;
  17629. AudioIODeviceType* type = getCurrentDeviceTypeObject();
  17630. if (type == 0 || (newSetup.inputDeviceName.isEmpty()
  17631. && newSetup.outputDeviceName.isEmpty()))
  17632. {
  17633. deleteCurrentDevice();
  17634. if (treatAsChosenDevice)
  17635. updateXml();
  17636. return String::empty;
  17637. }
  17638. if (currentSetup.inputDeviceName != newSetup.inputDeviceName
  17639. || currentSetup.outputDeviceName != newSetup.outputDeviceName
  17640. || currentAudioDevice == 0)
  17641. {
  17642. deleteCurrentDevice();
  17643. scanDevicesIfNeeded();
  17644. if (newSetup.outputDeviceName.isNotEmpty()
  17645. && ! type->getDeviceNames (false).contains (newSetup.outputDeviceName))
  17646. {
  17647. return "No such device: " + newSetup.outputDeviceName;
  17648. }
  17649. if (newSetup.inputDeviceName.isNotEmpty()
  17650. && ! type->getDeviceNames (true).contains (newSetup.inputDeviceName))
  17651. {
  17652. return "No such device: " + newSetup.outputDeviceName;
  17653. }
  17654. currentAudioDevice = type->createDevice (newSetup.outputDeviceName,
  17655. newSetup.inputDeviceName);
  17656. if (currentAudioDevice == 0)
  17657. error = "Can't open the audio device!\n\nThis may be because another application is currently using the same device - if so, you should close any other applications and try again!";
  17658. else
  17659. error = currentAudioDevice->getLastError();
  17660. if (error.isNotEmpty())
  17661. {
  17662. deleteCurrentDevice();
  17663. return error;
  17664. }
  17665. if (newSetup.useDefaultInputChannels)
  17666. {
  17667. inputChannels.clear();
  17668. inputChannels.setRange (0, numInputChansNeeded, true);
  17669. }
  17670. if (newSetup.useDefaultOutputChannels)
  17671. {
  17672. outputChannels.clear();
  17673. outputChannels.setRange (0, numOutputChansNeeded, true);
  17674. }
  17675. if (newSetup.inputDeviceName.isEmpty())
  17676. inputChannels.clear();
  17677. if (newSetup.outputDeviceName.isEmpty())
  17678. outputChannels.clear();
  17679. }
  17680. if (! newSetup.useDefaultInputChannels)
  17681. inputChannels = newSetup.inputChannels;
  17682. if (! newSetup.useDefaultOutputChannels)
  17683. outputChannels = newSetup.outputChannels;
  17684. currentSetup = newSetup;
  17685. currentSetup.sampleRate = chooseBestSampleRate (newSetup.sampleRate);
  17686. error = currentAudioDevice->open (inputChannels,
  17687. outputChannels,
  17688. currentSetup.sampleRate,
  17689. currentSetup.bufferSize);
  17690. if (error.isEmpty())
  17691. {
  17692. currentDeviceType = currentAudioDevice->getTypeName();
  17693. currentAudioDevice->start (&callbackHandler);
  17694. currentSetup.sampleRate = currentAudioDevice->getCurrentSampleRate();
  17695. currentSetup.bufferSize = currentAudioDevice->getCurrentBufferSizeSamples();
  17696. currentSetup.inputChannels = currentAudioDevice->getActiveInputChannels();
  17697. currentSetup.outputChannels = currentAudioDevice->getActiveOutputChannels();
  17698. for (int i = 0; i < availableDeviceTypes.size(); ++i)
  17699. if (availableDeviceTypes.getUnchecked (i)->getTypeName() == currentDeviceType)
  17700. *(lastDeviceTypeConfigs.getUnchecked (i)) = currentSetup;
  17701. if (treatAsChosenDevice)
  17702. updateXml();
  17703. }
  17704. else
  17705. {
  17706. deleteCurrentDevice();
  17707. }
  17708. return error;
  17709. }
  17710. double AudioDeviceManager::chooseBestSampleRate (double rate) const
  17711. {
  17712. jassert (currentAudioDevice != 0);
  17713. if (rate > 0)
  17714. {
  17715. bool ok = false;
  17716. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  17717. {
  17718. const double sr = currentAudioDevice->getSampleRate (i);
  17719. if (sr == rate)
  17720. ok = true;
  17721. }
  17722. if (! ok)
  17723. rate = 0;
  17724. }
  17725. if (rate == 0)
  17726. {
  17727. double lowestAbove44 = 0.0;
  17728. for (int i = currentAudioDevice->getNumSampleRates(); --i >= 0;)
  17729. {
  17730. const double sr = currentAudioDevice->getSampleRate (i);
  17731. if (sr >= 44100.0 && (lowestAbove44 == 0 || sr < lowestAbove44))
  17732. lowestAbove44 = sr;
  17733. }
  17734. if (lowestAbove44 == 0.0)
  17735. rate = currentAudioDevice->getSampleRate (0);
  17736. else
  17737. rate = lowestAbove44;
  17738. }
  17739. return rate;
  17740. }
  17741. void AudioDeviceManager::stopDevice()
  17742. {
  17743. if (currentAudioDevice != 0)
  17744. currentAudioDevice->stop();
  17745. }
  17746. void AudioDeviceManager::closeAudioDevice()
  17747. {
  17748. stopDevice();
  17749. deleteAndZero (currentAudioDevice);
  17750. }
  17751. void AudioDeviceManager::restartLastAudioDevice()
  17752. {
  17753. if (currentAudioDevice == 0)
  17754. {
  17755. if (currentSetup.inputDeviceName.isEmpty()
  17756. && currentSetup.outputDeviceName.isEmpty())
  17757. {
  17758. // This method will only reload the last device that was running
  17759. // before closeAudioDevice() was called - you need to actually open
  17760. // one first, with setAudioDevice().
  17761. jassertfalse
  17762. return;
  17763. }
  17764. AudioDeviceSetup s (currentSetup);
  17765. setAudioDeviceSetup (s, false);
  17766. }
  17767. }
  17768. void AudioDeviceManager::updateXml()
  17769. {
  17770. delete lastExplicitSettings;
  17771. lastExplicitSettings = new XmlElement (T("DEVICESETUP"));
  17772. lastExplicitSettings->setAttribute (T("deviceType"), currentDeviceType);
  17773. lastExplicitSettings->setAttribute (T("audioOutputDeviceName"), currentSetup.outputDeviceName);
  17774. lastExplicitSettings->setAttribute (T("audioInputDeviceName"), currentSetup.inputDeviceName);
  17775. if (currentAudioDevice != 0)
  17776. {
  17777. lastExplicitSettings->setAttribute (T("audioDeviceRate"), currentAudioDevice->getCurrentSampleRate());
  17778. if (currentAudioDevice->getDefaultBufferSize() != currentAudioDevice->getCurrentBufferSizeSamples())
  17779. lastExplicitSettings->setAttribute (T("audioDeviceBufferSize"), currentAudioDevice->getCurrentBufferSizeSamples());
  17780. if (! currentSetup.useDefaultInputChannels)
  17781. lastExplicitSettings->setAttribute (T("audioDeviceInChans"), currentSetup.inputChannels.toString (2));
  17782. if (! currentSetup.useDefaultOutputChannels)
  17783. lastExplicitSettings->setAttribute (T("audioDeviceOutChans"), currentSetup.outputChannels.toString (2));
  17784. }
  17785. for (int i = 0; i < enabledMidiInputs.size(); ++i)
  17786. {
  17787. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  17788. m->setAttribute (T("name"), enabledMidiInputs[i]->getName());
  17789. lastExplicitSettings->addChildElement (m);
  17790. }
  17791. if (midiInsFromXml.size() > 0)
  17792. {
  17793. // Add any midi devices that have been enabled before, but which aren't currently
  17794. // open because the device has been disconnected.
  17795. const StringArray availableMidiDevices (MidiInput::getDevices());
  17796. for (int i = 0; i < midiInsFromXml.size(); ++i)
  17797. {
  17798. if (! availableMidiDevices.contains (midiInsFromXml[i], true))
  17799. {
  17800. XmlElement* const m = new XmlElement (T("MIDIINPUT"));
  17801. m->setAttribute (T("name"), midiInsFromXml[i]);
  17802. lastExplicitSettings->addChildElement (m);
  17803. }
  17804. }
  17805. }
  17806. if (defaultMidiOutputName.isNotEmpty())
  17807. lastExplicitSettings->setAttribute (T("defaultMidiOutput"), defaultMidiOutputName);
  17808. }
  17809. void AudioDeviceManager::setAudioCallback (AudioIODeviceCallback* newCallback)
  17810. {
  17811. if (newCallback != currentCallback)
  17812. {
  17813. AudioIODeviceCallback* lastCallback = currentCallback;
  17814. audioCallbackLock.enter();
  17815. currentCallback = 0;
  17816. audioCallbackLock.exit();
  17817. if (currentAudioDevice != 0)
  17818. {
  17819. if (lastCallback != 0)
  17820. lastCallback->audioDeviceStopped();
  17821. if (newCallback != 0)
  17822. newCallback->audioDeviceAboutToStart (currentAudioDevice);
  17823. }
  17824. currentCallback = newCallback;
  17825. }
  17826. }
  17827. void AudioDeviceManager::audioDeviceIOCallbackInt (const float** inputChannelData,
  17828. int numInputChannels,
  17829. float** outputChannelData,
  17830. int numOutputChannels,
  17831. int numSamples)
  17832. {
  17833. const ScopedLock sl (audioCallbackLock);
  17834. if (inputLevelMeasurementEnabled)
  17835. {
  17836. for (int j = 0; j < numSamples; ++j)
  17837. {
  17838. float s = 0;
  17839. for (int i = 0; i < numInputChannels; ++i)
  17840. s += fabsf (inputChannelData[i][j]);
  17841. s /= numInputChannels;
  17842. const double decayFactor = 0.99992;
  17843. if (s > inputLevel)
  17844. inputLevel = s;
  17845. else if (inputLevel > 0.001f)
  17846. inputLevel *= decayFactor;
  17847. else
  17848. inputLevel = 0;
  17849. }
  17850. }
  17851. if (currentCallback != 0)
  17852. {
  17853. const double callbackStartTime = Time::getMillisecondCounterHiRes();
  17854. currentCallback->audioDeviceIOCallback (inputChannelData,
  17855. numInputChannels,
  17856. outputChannelData,
  17857. numOutputChannels,
  17858. numSamples);
  17859. const double msTaken = Time::getMillisecondCounterHiRes() - callbackStartTime;
  17860. const double filterAmount = 0.2;
  17861. cpuUsageMs += filterAmount * (msTaken - cpuUsageMs);
  17862. }
  17863. else
  17864. {
  17865. for (int i = 0; i < numOutputChannels; ++i)
  17866. zeromem (outputChannelData[i], sizeof (float) * numSamples);
  17867. }
  17868. if (testSound != 0)
  17869. {
  17870. const int numSamps = jmin (numSamples, testSound->getNumSamples() - testSoundPosition);
  17871. const float* const src = testSound->getSampleData (0, testSoundPosition);
  17872. for (int i = 0; i < numOutputChannels; ++i)
  17873. for (int j = 0; j < numSamps; ++j)
  17874. outputChannelData [i][j] += src[j];
  17875. testSoundPosition += numSamps;
  17876. if (testSoundPosition >= testSound->getNumSamples())
  17877. {
  17878. delete testSound;
  17879. testSound = 0;
  17880. }
  17881. }
  17882. }
  17883. void AudioDeviceManager::audioDeviceAboutToStartInt (AudioIODevice* const device)
  17884. {
  17885. cpuUsageMs = 0;
  17886. const double sampleRate = device->getCurrentSampleRate();
  17887. const int blockSize = device->getCurrentBufferSizeSamples();
  17888. if (sampleRate > 0.0 && blockSize > 0)
  17889. {
  17890. const double msPerBlock = 1000.0 * blockSize / sampleRate;
  17891. timeToCpuScale = (msPerBlock > 0.0) ? (1.0 / msPerBlock) : 0.0;
  17892. }
  17893. if (currentCallback != 0)
  17894. currentCallback->audioDeviceAboutToStart (device);
  17895. sendChangeMessage (this);
  17896. }
  17897. void AudioDeviceManager::audioDeviceStoppedInt()
  17898. {
  17899. cpuUsageMs = 0;
  17900. timeToCpuScale = 0;
  17901. sendChangeMessage (this);
  17902. if (currentCallback != 0)
  17903. currentCallback->audioDeviceStopped();
  17904. }
  17905. double AudioDeviceManager::getCpuUsage() const
  17906. {
  17907. return jlimit (0.0, 1.0, timeToCpuScale * cpuUsageMs);
  17908. }
  17909. void AudioDeviceManager::setMidiInputEnabled (const String& name,
  17910. const bool enabled)
  17911. {
  17912. if (enabled != isMidiInputEnabled (name))
  17913. {
  17914. if (enabled)
  17915. {
  17916. const int index = MidiInput::getDevices().indexOf (name);
  17917. if (index >= 0)
  17918. {
  17919. MidiInput* const min = MidiInput::openDevice (index, &callbackHandler);
  17920. if (min != 0)
  17921. {
  17922. enabledMidiInputs.add (min);
  17923. min->start();
  17924. }
  17925. }
  17926. }
  17927. else
  17928. {
  17929. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17930. if (enabledMidiInputs[i]->getName() == name)
  17931. enabledMidiInputs.remove (i);
  17932. }
  17933. updateXml();
  17934. sendChangeMessage (this);
  17935. }
  17936. }
  17937. bool AudioDeviceManager::isMidiInputEnabled (const String& name) const
  17938. {
  17939. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17940. if (enabledMidiInputs[i]->getName() == name)
  17941. return true;
  17942. return false;
  17943. }
  17944. void AudioDeviceManager::addMidiInputCallback (const String& name,
  17945. MidiInputCallback* callback)
  17946. {
  17947. removeMidiInputCallback (name, callback);
  17948. if (name.isEmpty())
  17949. {
  17950. midiCallbacks.add (callback);
  17951. midiCallbackDevices.add (0);
  17952. }
  17953. else
  17954. {
  17955. for (int i = enabledMidiInputs.size(); --i >= 0;)
  17956. {
  17957. if (enabledMidiInputs[i]->getName() == name)
  17958. {
  17959. const ScopedLock sl (midiCallbackLock);
  17960. midiCallbacks.add (callback);
  17961. midiCallbackDevices.add (enabledMidiInputs[i]);
  17962. break;
  17963. }
  17964. }
  17965. }
  17966. }
  17967. void AudioDeviceManager::removeMidiInputCallback (const String& name,
  17968. MidiInputCallback* /*callback*/)
  17969. {
  17970. const ScopedLock sl (midiCallbackLock);
  17971. for (int i = midiCallbacks.size(); --i >= 0;)
  17972. {
  17973. String devName;
  17974. if (midiCallbackDevices.getUnchecked(i) != 0)
  17975. devName = midiCallbackDevices.getUnchecked(i)->getName();
  17976. if (devName == name)
  17977. {
  17978. midiCallbacks.remove (i);
  17979. midiCallbackDevices.remove (i);
  17980. }
  17981. }
  17982. }
  17983. void AudioDeviceManager::handleIncomingMidiMessageInt (MidiInput* source,
  17984. const MidiMessage& message)
  17985. {
  17986. if (! message.isActiveSense())
  17987. {
  17988. const bool isDefaultSource = (source == 0 || source == enabledMidiInputs.getFirst());
  17989. const ScopedLock sl (midiCallbackLock);
  17990. for (int i = midiCallbackDevices.size(); --i >= 0;)
  17991. {
  17992. MidiInput* const md = midiCallbackDevices.getUnchecked(i);
  17993. if (md == source || (md == 0 && isDefaultSource))
  17994. midiCallbacks.getUnchecked(i)->handleIncomingMidiMessage (source, message);
  17995. }
  17996. }
  17997. }
  17998. void AudioDeviceManager::setDefaultMidiOutput (const String& deviceName)
  17999. {
  18000. if (defaultMidiOutputName != deviceName)
  18001. {
  18002. deleteAndZero (defaultMidiOutput);
  18003. defaultMidiOutputName = deviceName;
  18004. if (deviceName.isNotEmpty())
  18005. defaultMidiOutput = MidiOutput::openDevice (MidiOutput::getDevices().indexOf (deviceName));
  18006. updateXml();
  18007. sendChangeMessage (this);
  18008. }
  18009. }
  18010. void AudioDeviceManager::CallbackHandler::audioDeviceIOCallback (const float** inputChannelData,
  18011. int numInputChannels,
  18012. float** outputChannelData,
  18013. int numOutputChannels,
  18014. int numSamples)
  18015. {
  18016. owner->audioDeviceIOCallbackInt (inputChannelData, numInputChannels, outputChannelData, numOutputChannels, numSamples);
  18017. }
  18018. void AudioDeviceManager::CallbackHandler::audioDeviceAboutToStart (AudioIODevice* device)
  18019. {
  18020. owner->audioDeviceAboutToStartInt (device);
  18021. }
  18022. void AudioDeviceManager::CallbackHandler::audioDeviceStopped()
  18023. {
  18024. owner->audioDeviceStoppedInt();
  18025. }
  18026. void AudioDeviceManager::CallbackHandler::handleIncomingMidiMessage (MidiInput* source, const MidiMessage& message)
  18027. {
  18028. owner->handleIncomingMidiMessageInt (source, message);
  18029. }
  18030. void AudioDeviceManager::playTestSound()
  18031. {
  18032. audioCallbackLock.enter();
  18033. AudioSampleBuffer* oldSound = testSound;
  18034. testSound = 0;
  18035. audioCallbackLock.exit();
  18036. delete oldSound;
  18037. testSoundPosition = 0;
  18038. if (currentAudioDevice != 0)
  18039. {
  18040. const double sampleRate = currentAudioDevice->getCurrentSampleRate();
  18041. const int soundLength = (int) sampleRate;
  18042. AudioSampleBuffer* const newSound = new AudioSampleBuffer (1, soundLength);
  18043. float* samples = newSound->getSampleData (0);
  18044. const double frequency = MidiMessage::getMidiNoteInHertz (80);
  18045. const float amplitude = 0.5f;
  18046. const double phasePerSample = double_Pi * 2.0 / (sampleRate / frequency);
  18047. for (int i = 0; i < soundLength; ++i)
  18048. samples[i] = amplitude * (float) sin (i * phasePerSample);
  18049. newSound->applyGainRamp (0, 0, soundLength / 10, 0.0f, 1.0f);
  18050. newSound->applyGainRamp (0, soundLength - soundLength / 4, soundLength / 4, 1.0f, 0.0f);
  18051. const ScopedLock sl (audioCallbackLock);
  18052. testSound = newSound;
  18053. }
  18054. }
  18055. void AudioDeviceManager::enableInputLevelMeasurement (const bool enableMeasurement)
  18056. {
  18057. if (inputLevelMeasurementEnabled != enableMeasurement)
  18058. {
  18059. const ScopedLock sl (audioCallbackLock);
  18060. inputLevelMeasurementEnabled = enableMeasurement;
  18061. inputLevel = 0;
  18062. }
  18063. }
  18064. double AudioDeviceManager::getCurrentInputLevel() const
  18065. {
  18066. jassert (inputLevelMeasurementEnabled); // you need to call enableInputLevelMeasurement() before using this!
  18067. return inputLevel;
  18068. }
  18069. END_JUCE_NAMESPACE
  18070. /********* End of inlined file: juce_AudioDeviceManager.cpp *********/
  18071. /********* Start of inlined file: juce_AudioIODevice.cpp *********/
  18072. BEGIN_JUCE_NAMESPACE
  18073. AudioIODevice::AudioIODevice (const String& deviceName, const String& typeName_)
  18074. : name (deviceName),
  18075. typeName (typeName_)
  18076. {
  18077. }
  18078. AudioIODevice::~AudioIODevice()
  18079. {
  18080. }
  18081. bool AudioIODevice::hasControlPanel() const
  18082. {
  18083. return false;
  18084. }
  18085. bool AudioIODevice::showControlPanel()
  18086. {
  18087. jassertfalse // this should only be called for devices which return true from
  18088. // their hasControlPanel() method.
  18089. return false;
  18090. }
  18091. END_JUCE_NAMESPACE
  18092. /********* End of inlined file: juce_AudioIODevice.cpp *********/
  18093. /********* Start of inlined file: juce_AudioIODeviceType.cpp *********/
  18094. BEGIN_JUCE_NAMESPACE
  18095. AudioIODeviceType::AudioIODeviceType (const tchar* const name)
  18096. : typeName (name)
  18097. {
  18098. }
  18099. AudioIODeviceType::~AudioIODeviceType()
  18100. {
  18101. }
  18102. END_JUCE_NAMESPACE
  18103. /********* End of inlined file: juce_AudioIODeviceType.cpp *********/
  18104. /********* Start of inlined file: juce_MidiOutput.cpp *********/
  18105. BEGIN_JUCE_NAMESPACE
  18106. MidiOutput::MidiOutput() throw()
  18107. : Thread ("midi out"),
  18108. internal (0),
  18109. firstMessage (0)
  18110. {
  18111. }
  18112. MidiOutput::PendingMessage::PendingMessage (const uint8* const data,
  18113. const int len,
  18114. const double sampleNumber) throw()
  18115. : message (data, len, sampleNumber)
  18116. {
  18117. }
  18118. void MidiOutput::sendBlockOfMessages (const MidiBuffer& buffer,
  18119. const double millisecondCounterToStartAt,
  18120. double samplesPerSecondForBuffer) throw()
  18121. {
  18122. // You've got to call startBackgroundThread() for this to actually work..
  18123. jassert (isThreadRunning());
  18124. // this needs to be a value in the future - RTFM for this method!
  18125. jassert (millisecondCounterToStartAt > 0);
  18126. samplesPerSecondForBuffer *= 0.001;
  18127. MidiBuffer::Iterator i (buffer);
  18128. const uint8* data;
  18129. int len, time;
  18130. while (i.getNextEvent (data, len, time))
  18131. {
  18132. const double eventTime = millisecondCounterToStartAt + samplesPerSecondForBuffer * time;
  18133. PendingMessage* const m
  18134. = new PendingMessage (data, len, eventTime);
  18135. const ScopedLock sl (lock);
  18136. if (firstMessage == 0 || firstMessage->message.getTimeStamp() > eventTime)
  18137. {
  18138. m->next = firstMessage;
  18139. firstMessage = m;
  18140. }
  18141. else
  18142. {
  18143. PendingMessage* mm = firstMessage;
  18144. while (mm->next != 0 && mm->next->message.getTimeStamp() <= eventTime)
  18145. mm = mm->next;
  18146. m->next = mm->next;
  18147. mm->next = m;
  18148. }
  18149. }
  18150. notify();
  18151. }
  18152. void MidiOutput::clearAllPendingMessages() throw()
  18153. {
  18154. const ScopedLock sl (lock);
  18155. while (firstMessage != 0)
  18156. {
  18157. PendingMessage* const m = firstMessage;
  18158. firstMessage = firstMessage->next;
  18159. delete m;
  18160. }
  18161. }
  18162. void MidiOutput::startBackgroundThread() throw()
  18163. {
  18164. startThread (9);
  18165. }
  18166. void MidiOutput::stopBackgroundThread() throw()
  18167. {
  18168. stopThread (5000);
  18169. }
  18170. void MidiOutput::run()
  18171. {
  18172. while (! threadShouldExit())
  18173. {
  18174. uint32 now = Time::getMillisecondCounter();
  18175. uint32 eventTime = 0;
  18176. uint32 timeToWait = 500;
  18177. lock.enter();
  18178. PendingMessage* message = firstMessage;
  18179. if (message != 0)
  18180. {
  18181. eventTime = roundDoubleToInt (message->message.getTimeStamp());
  18182. if (eventTime > now + 20)
  18183. {
  18184. timeToWait = jmax (10, eventTime - now - 100);
  18185. message = 0;
  18186. }
  18187. else
  18188. {
  18189. firstMessage = message->next;
  18190. }
  18191. }
  18192. lock.exit();
  18193. if (message != 0)
  18194. {
  18195. if (eventTime > now)
  18196. {
  18197. Time::waitForMillisecondCounter (eventTime);
  18198. if (threadShouldExit())
  18199. break;
  18200. }
  18201. if (eventTime > now - 200)
  18202. sendMessageNow (message->message);
  18203. delete message;
  18204. }
  18205. else
  18206. {
  18207. jassert (timeToWait < 1000 * 30);
  18208. wait (timeToWait);
  18209. }
  18210. }
  18211. clearAllPendingMessages();
  18212. }
  18213. END_JUCE_NAMESPACE
  18214. /********* End of inlined file: juce_MidiOutput.cpp *********/
  18215. /********* Start of inlined file: juce_AudioDataConverters.cpp *********/
  18216. BEGIN_JUCE_NAMESPACE
  18217. void AudioDataConverters::convertFloatToInt16LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  18218. {
  18219. const double maxVal = (double) 0x7fff;
  18220. char* intData = (char*) dest;
  18221. for (int i = 0; i < numSamples; ++i)
  18222. {
  18223. *(uint16*)intData = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  18224. intData += destBytesPerSample;
  18225. }
  18226. }
  18227. void AudioDataConverters::convertFloatToInt16BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  18228. {
  18229. const double maxVal = (double) 0x7fff;
  18230. char* intData = (char*) dest;
  18231. for (int i = 0; i < numSamples; ++i)
  18232. {
  18233. *(uint16*)intData = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  18234. intData += destBytesPerSample;
  18235. }
  18236. }
  18237. void AudioDataConverters::convertFloatToInt24LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  18238. {
  18239. const double maxVal = (double) 0x7fffff;
  18240. char* intData = (char*) dest;
  18241. for (int i = 0; i < numSamples; ++i)
  18242. {
  18243. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  18244. intData += destBytesPerSample;
  18245. }
  18246. }
  18247. void AudioDataConverters::convertFloatToInt24BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  18248. {
  18249. const double maxVal = (double) 0x7fffff;
  18250. char* intData = (char*) dest;
  18251. for (int i = 0; i < numSamples; ++i)
  18252. {
  18253. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])), intData);
  18254. intData += destBytesPerSample;
  18255. }
  18256. }
  18257. void AudioDataConverters::convertFloatToInt32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  18258. {
  18259. const double maxVal = (double) 0x7fffffff;
  18260. char* intData = (char*) dest;
  18261. for (int i = 0; i < numSamples; ++i)
  18262. {
  18263. *(uint32*)intData = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  18264. intData += destBytesPerSample;
  18265. }
  18266. }
  18267. void AudioDataConverters::convertFloatToInt32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  18268. {
  18269. const double maxVal = (double) 0x7fffffff;
  18270. char* intData = (char*) dest;
  18271. for (int i = 0; i < numSamples; ++i)
  18272. {
  18273. *(uint32*)intData = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * source[i])));
  18274. intData += destBytesPerSample;
  18275. }
  18276. }
  18277. void AudioDataConverters::convertFloatToFloat32LE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  18278. {
  18279. char* d = (char*) dest;
  18280. for (int i = 0; i < numSamples; ++i)
  18281. {
  18282. *(float*)d = source[i];
  18283. #if JUCE_BIG_ENDIAN
  18284. *(uint32*)d = swapByteOrder (*(uint32*)d);
  18285. #endif
  18286. d += destBytesPerSample;
  18287. }
  18288. }
  18289. void AudioDataConverters::convertFloatToFloat32BE (const float* source, void* dest, int numSamples, const int destBytesPerSample)
  18290. {
  18291. char* d = (char*) dest;
  18292. for (int i = 0; i < numSamples; ++i)
  18293. {
  18294. *(float*)d = source[i];
  18295. #if JUCE_LITTLE_ENDIAN
  18296. *(uint32*)d = swapByteOrder (*(uint32*)d);
  18297. #endif
  18298. d += destBytesPerSample;
  18299. }
  18300. }
  18301. void AudioDataConverters::convertInt16LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  18302. {
  18303. const float scale = 1.0f / 0x7fff;
  18304. const char* intData = (const char*) source;
  18305. for (int i = 0; i < numSamples; ++i)
  18306. {
  18307. dest[i] = scale * (short) swapIfBigEndian (*(uint16*)intData);
  18308. intData += srcBytesPerSample;
  18309. }
  18310. }
  18311. void AudioDataConverters::convertInt16BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  18312. {
  18313. const float scale = 1.0f / 0x7fff;
  18314. const char* intData = (const char*) source;
  18315. for (int i = 0; i < numSamples; ++i)
  18316. {
  18317. dest[i] = scale * (short) swapIfLittleEndian (*(uint16*)intData);
  18318. intData += srcBytesPerSample;
  18319. }
  18320. }
  18321. void AudioDataConverters::convertInt24LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  18322. {
  18323. const float scale = 1.0f / 0x7fffff;
  18324. const char* intData = (const char*) source;
  18325. for (int i = 0; i < numSamples; ++i)
  18326. {
  18327. dest[i] = scale * (short) littleEndian24Bit (intData);
  18328. intData += srcBytesPerSample;
  18329. }
  18330. }
  18331. void AudioDataConverters::convertInt24BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  18332. {
  18333. const float scale = 1.0f / 0x7fffff;
  18334. const char* intData = (const char*) source;
  18335. for (int i = 0; i < numSamples; ++i)
  18336. {
  18337. dest[i] = scale * (short) bigEndian24Bit (intData);
  18338. intData += srcBytesPerSample;
  18339. }
  18340. }
  18341. void AudioDataConverters::convertInt32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  18342. {
  18343. const float scale = 1.0f / 0x7fffffff;
  18344. const char* intData = (const char*) source;
  18345. for (int i = 0; i < numSamples; ++i)
  18346. {
  18347. dest[i] = scale * (int) swapIfBigEndian (*(uint32*) intData);
  18348. intData += srcBytesPerSample;
  18349. }
  18350. }
  18351. void AudioDataConverters::convertInt32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  18352. {
  18353. const float scale = 1.0f / 0x7fffffff;
  18354. const char* intData = (const char*) source;
  18355. for (int i = 0; i < numSamples; ++i)
  18356. {
  18357. dest[i] = scale * (int) (swapIfLittleEndian (*(uint32*) intData));
  18358. intData += srcBytesPerSample;
  18359. }
  18360. }
  18361. void AudioDataConverters::convertFloat32LEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  18362. {
  18363. const char* s = (const char*) source;
  18364. for (int i = 0; i < numSamples; ++i)
  18365. {
  18366. dest[i] = *(float*)s;
  18367. #if JUCE_BIG_ENDIAN
  18368. uint32* const d = (uint32*) (dest + i);
  18369. *d = swapByteOrder (*d);
  18370. #endif
  18371. s += srcBytesPerSample;
  18372. }
  18373. }
  18374. void AudioDataConverters::convertFloat32BEToFloat (const void* const source, float* const dest, int numSamples, const int srcBytesPerSample)
  18375. {
  18376. const char* s = (const char*) source;
  18377. for (int i = 0; i < numSamples; ++i)
  18378. {
  18379. dest[i] = *(float*)s;
  18380. #if JUCE_LITTLE_ENDIAN
  18381. uint32* const d = (uint32*) (dest + i);
  18382. *d = swapByteOrder (*d);
  18383. #endif
  18384. s += srcBytesPerSample;
  18385. }
  18386. }
  18387. void AudioDataConverters::convertFloatToFormat (const DataFormat destFormat,
  18388. const float* const source,
  18389. void* const dest,
  18390. const int numSamples)
  18391. {
  18392. switch (destFormat)
  18393. {
  18394. case int16LE:
  18395. convertFloatToInt16LE (source, dest, numSamples);
  18396. break;
  18397. case int16BE:
  18398. convertFloatToInt16BE (source, dest, numSamples);
  18399. break;
  18400. case int24LE:
  18401. convertFloatToInt24LE (source, dest, numSamples);
  18402. break;
  18403. case int24BE:
  18404. convertFloatToInt24BE (source, dest, numSamples);
  18405. break;
  18406. case int32LE:
  18407. convertFloatToInt32LE (source, dest, numSamples);
  18408. break;
  18409. case int32BE:
  18410. convertFloatToInt32BE (source, dest, numSamples);
  18411. break;
  18412. case float32LE:
  18413. convertFloatToFloat32LE (source, dest, numSamples);
  18414. break;
  18415. case float32BE:
  18416. convertFloatToFloat32BE (source, dest, numSamples);
  18417. break;
  18418. default:
  18419. jassertfalse
  18420. break;
  18421. }
  18422. }
  18423. void AudioDataConverters::convertFormatToFloat (const DataFormat sourceFormat,
  18424. const void* const source,
  18425. float* const dest,
  18426. const int numSamples)
  18427. {
  18428. switch (sourceFormat)
  18429. {
  18430. case int16LE:
  18431. convertInt16LEToFloat (source, dest, numSamples);
  18432. break;
  18433. case int16BE:
  18434. convertInt16BEToFloat (source, dest, numSamples);
  18435. break;
  18436. case int24LE:
  18437. convertInt24LEToFloat (source, dest, numSamples);
  18438. break;
  18439. case int24BE:
  18440. convertInt24BEToFloat (source, dest, numSamples);
  18441. break;
  18442. case int32LE:
  18443. convertInt32LEToFloat (source, dest, numSamples);
  18444. break;
  18445. case int32BE:
  18446. convertInt32BEToFloat (source, dest, numSamples);
  18447. break;
  18448. case float32LE:
  18449. convertFloat32LEToFloat (source, dest, numSamples);
  18450. break;
  18451. case float32BE:
  18452. convertFloat32BEToFloat (source, dest, numSamples);
  18453. break;
  18454. default:
  18455. jassertfalse
  18456. break;
  18457. }
  18458. }
  18459. void AudioDataConverters::interleaveSamples (const float** const source,
  18460. float* const dest,
  18461. const int numSamples,
  18462. const int numChannels)
  18463. {
  18464. for (int chan = 0; chan < numChannels; ++chan)
  18465. {
  18466. int i = chan;
  18467. const float* src = source [chan];
  18468. for (int j = 0; j < numSamples; ++j)
  18469. {
  18470. dest [i] = src [j];
  18471. i += numChannels;
  18472. }
  18473. }
  18474. }
  18475. void AudioDataConverters::deinterleaveSamples (const float* const source,
  18476. float** const dest,
  18477. const int numSamples,
  18478. const int numChannels)
  18479. {
  18480. for (int chan = 0; chan < numChannels; ++chan)
  18481. {
  18482. int i = chan;
  18483. float* dst = dest [chan];
  18484. for (int j = 0; j < numSamples; ++j)
  18485. {
  18486. dst [j] = source [i];
  18487. i += numChannels;
  18488. }
  18489. }
  18490. }
  18491. END_JUCE_NAMESPACE
  18492. /********* End of inlined file: juce_AudioDataConverters.cpp *********/
  18493. /********* Start of inlined file: juce_AudioSampleBuffer.cpp *********/
  18494. BEGIN_JUCE_NAMESPACE
  18495. AudioSampleBuffer::AudioSampleBuffer (const int numChannels_,
  18496. const int numSamples) throw()
  18497. : numChannels (numChannels_),
  18498. size (numSamples)
  18499. {
  18500. jassert (numSamples >= 0);
  18501. jassert (numChannels_ > 0);
  18502. allocatedBytes = numChannels * numSamples * sizeof (float) + 32;
  18503. allocatedData = (float*) juce_malloc (allocatedBytes);
  18504. channels = (float**) juce_malloc ((numChannels_ + 1) * sizeof (float*));
  18505. float* chan = allocatedData;
  18506. for (int i = 0; i < numChannels_; ++i)
  18507. {
  18508. channels[i] = chan;
  18509. chan += numSamples;
  18510. }
  18511. channels [numChannels_] = 0;
  18512. }
  18513. AudioSampleBuffer::AudioSampleBuffer (float** dataToReferTo,
  18514. const int numChannels_,
  18515. const int numSamples) throw()
  18516. : numChannels (numChannels_),
  18517. size (numSamples),
  18518. allocatedBytes (0),
  18519. allocatedData (0)
  18520. {
  18521. jassert (numChannels_ > 0);
  18522. channels = (float**) juce_malloc ((numChannels_ + 1) * sizeof (float*));
  18523. for (int i = 0; i < numChannels_; ++i)
  18524. {
  18525. // you have to pass in the same number of valid pointers as numChannels
  18526. jassert (dataToReferTo[i] != 0);
  18527. channels[i] = dataToReferTo[i];
  18528. }
  18529. channels [numChannels_] = 0;
  18530. }
  18531. void AudioSampleBuffer::setDataToReferTo (float** dataToReferTo,
  18532. const int numChannels_,
  18533. const int numSamples) throw()
  18534. {
  18535. jassert (numChannels_ > 0);
  18536. juce_free (allocatedData);
  18537. allocatedData = 0;
  18538. allocatedBytes = 0;
  18539. if (numChannels_ > numChannels)
  18540. channels = (float**) juce_realloc (channels, (numChannels_ + 1) * sizeof (float*));
  18541. numChannels = numChannels_;
  18542. size = numSamples;
  18543. for (int i = 0; i < numChannels_; ++i)
  18544. {
  18545. // you have to pass in the same number of valid pointers as numChannels
  18546. jassert (dataToReferTo[i] != 0);
  18547. channels[i] = dataToReferTo[i];
  18548. }
  18549. channels [numChannels_] = 0;
  18550. }
  18551. AudioSampleBuffer::AudioSampleBuffer (const AudioSampleBuffer& other) throw()
  18552. : numChannels (other.numChannels),
  18553. size (other.size)
  18554. {
  18555. channels = (float**) juce_malloc ((other.numChannels + 1) * sizeof (float*));
  18556. if (other.allocatedData != 0)
  18557. {
  18558. allocatedBytes = numChannels * size * sizeof (float) + 32;
  18559. allocatedData = (float*) juce_malloc (allocatedBytes);
  18560. memcpy (allocatedData, other.allocatedData, allocatedBytes);
  18561. float* chan = allocatedData;
  18562. for (int i = 0; i < numChannels; ++i)
  18563. {
  18564. channels[i] = chan;
  18565. chan += size;
  18566. }
  18567. channels [numChannels] = 0;
  18568. }
  18569. else
  18570. {
  18571. allocatedData = 0;
  18572. allocatedBytes = 0;
  18573. memcpy (channels, other.channels, sizeof (channels));
  18574. }
  18575. }
  18576. const AudioSampleBuffer& AudioSampleBuffer::operator= (const AudioSampleBuffer& other) throw()
  18577. {
  18578. if (this != &other)
  18579. {
  18580. setSize (other.getNumChannels(), other.getNumSamples(), false, false, false);
  18581. const int numBytes = size * sizeof (float);
  18582. for (int i = 0; i < numChannels; ++i)
  18583. memcpy (channels[i], other.channels[i], numBytes);
  18584. }
  18585. return *this;
  18586. }
  18587. AudioSampleBuffer::~AudioSampleBuffer() throw()
  18588. {
  18589. juce_free (allocatedData);
  18590. juce_free (channels);
  18591. }
  18592. float* AudioSampleBuffer::getSampleData (const int channelNumber,
  18593. const int sampleOffset) const throw()
  18594. {
  18595. jassert (((unsigned int) channelNumber) < (unsigned int) numChannels);
  18596. jassert (((unsigned int) sampleOffset) < (unsigned int) size);
  18597. return channels [channelNumber] + sampleOffset;
  18598. }
  18599. void AudioSampleBuffer::setSize (const int newNumChannels,
  18600. const int newNumSamples,
  18601. const bool keepExistingContent,
  18602. const bool clearExtraSpace,
  18603. const bool avoidReallocating) throw()
  18604. {
  18605. jassert (newNumChannels > 0);
  18606. if (newNumSamples != size || newNumChannels != numChannels)
  18607. {
  18608. const int newTotalBytes = newNumChannels * newNumSamples * sizeof (float) + 32;
  18609. if (keepExistingContent)
  18610. {
  18611. float* const newData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  18612. : (float*) juce_malloc (newTotalBytes);
  18613. const int sizeToCopy = sizeof (float) * jmin (newNumSamples, size);
  18614. for (int i = jmin (newNumChannels, numChannels); --i >= 0;)
  18615. {
  18616. memcpy (newData + i * newNumSamples,
  18617. channels[i],
  18618. sizeToCopy);
  18619. }
  18620. juce_free (allocatedData);
  18621. allocatedData = newData;
  18622. allocatedBytes = newTotalBytes;
  18623. }
  18624. else
  18625. {
  18626. if (avoidReallocating && allocatedBytes >= newTotalBytes)
  18627. {
  18628. if (clearExtraSpace)
  18629. zeromem (allocatedData, newTotalBytes);
  18630. }
  18631. else
  18632. {
  18633. juce_free (allocatedData);
  18634. allocatedData = (clearExtraSpace) ? (float*) juce_calloc (newTotalBytes)
  18635. : (float*) juce_malloc (newTotalBytes);
  18636. allocatedBytes = newTotalBytes;
  18637. }
  18638. }
  18639. size = newNumSamples;
  18640. if (newNumChannels > numChannels)
  18641. channels = (float**) juce_realloc (channels, newNumChannels * sizeof (float*));
  18642. numChannels = newNumChannels;
  18643. float* chan = allocatedData;
  18644. for (int i = 0; i < newNumChannels; ++i)
  18645. {
  18646. channels[i] = chan;
  18647. chan += size;
  18648. }
  18649. channels [newNumChannels] = 0;
  18650. }
  18651. }
  18652. void AudioSampleBuffer::clear() throw()
  18653. {
  18654. for (int i = 0; i < numChannels; ++i)
  18655. zeromem (channels[i], size * sizeof (float));
  18656. }
  18657. void AudioSampleBuffer::clear (const int startSample,
  18658. const int numSamples) throw()
  18659. {
  18660. jassert (startSample >= 0 && startSample + numSamples <= size);
  18661. for (int i = 0; i < numChannels; ++i)
  18662. zeromem (channels [i] + startSample, numSamples * sizeof (float));
  18663. }
  18664. void AudioSampleBuffer::clear (const int channel,
  18665. const int startSample,
  18666. const int numSamples) throw()
  18667. {
  18668. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18669. jassert (startSample >= 0 && startSample + numSamples <= size);
  18670. zeromem (channels [channel] + startSample, numSamples * sizeof (float));
  18671. }
  18672. void AudioSampleBuffer::applyGain (const int channel,
  18673. const int startSample,
  18674. int numSamples,
  18675. const float gain) throw()
  18676. {
  18677. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18678. jassert (startSample >= 0 && startSample + numSamples <= size);
  18679. if (gain != 1.0f)
  18680. {
  18681. float* d = channels [channel] + startSample;
  18682. if (gain == 0.0f)
  18683. {
  18684. zeromem (d, sizeof (float) * numSamples);
  18685. }
  18686. else
  18687. {
  18688. while (--numSamples >= 0)
  18689. *d++ *= gain;
  18690. }
  18691. }
  18692. }
  18693. void AudioSampleBuffer::applyGainRamp (const int channel,
  18694. const int startSample,
  18695. int numSamples,
  18696. float startGain,
  18697. float endGain) throw()
  18698. {
  18699. if (startGain == endGain)
  18700. {
  18701. applyGain (channel, startSample, numSamples, startGain);
  18702. }
  18703. else
  18704. {
  18705. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18706. jassert (startSample >= 0 && startSample + numSamples <= size);
  18707. const float increment = (endGain - startGain) / numSamples;
  18708. float* d = channels [channel] + startSample;
  18709. while (--numSamples >= 0)
  18710. {
  18711. *d++ *= startGain;
  18712. startGain += increment;
  18713. }
  18714. }
  18715. }
  18716. void AudioSampleBuffer::applyGain (const int startSample,
  18717. const int numSamples,
  18718. const float gain) throw()
  18719. {
  18720. for (int i = 0; i < numChannels; ++i)
  18721. applyGain (i, startSample, numSamples, gain);
  18722. }
  18723. void AudioSampleBuffer::addFrom (const int destChannel,
  18724. const int destStartSample,
  18725. const AudioSampleBuffer& source,
  18726. const int sourceChannel,
  18727. const int sourceStartSample,
  18728. int numSamples,
  18729. const float gain) throw()
  18730. {
  18731. jassert (&source != this || sourceChannel != destChannel);
  18732. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18733. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18734. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  18735. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  18736. if (gain != 0.0f && numSamples > 0)
  18737. {
  18738. float* d = channels [destChannel] + destStartSample;
  18739. const float* s = source.channels [sourceChannel] + sourceStartSample;
  18740. if (gain != 1.0f)
  18741. {
  18742. while (--numSamples >= 0)
  18743. *d++ += gain * *s++;
  18744. }
  18745. else
  18746. {
  18747. while (--numSamples >= 0)
  18748. *d++ += *s++;
  18749. }
  18750. }
  18751. }
  18752. void AudioSampleBuffer::addFrom (const int destChannel,
  18753. const int destStartSample,
  18754. const float* source,
  18755. int numSamples,
  18756. const float gain) throw()
  18757. {
  18758. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18759. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18760. jassert (source != 0);
  18761. if (gain != 0.0f && numSamples > 0)
  18762. {
  18763. float* d = channels [destChannel] + destStartSample;
  18764. if (gain != 1.0f)
  18765. {
  18766. while (--numSamples >= 0)
  18767. *d++ += gain * *source++;
  18768. }
  18769. else
  18770. {
  18771. while (--numSamples >= 0)
  18772. *d++ += *source++;
  18773. }
  18774. }
  18775. }
  18776. void AudioSampleBuffer::addFromWithRamp (const int destChannel,
  18777. const int destStartSample,
  18778. const float* source,
  18779. int numSamples,
  18780. float startGain,
  18781. const float endGain) throw()
  18782. {
  18783. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18784. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18785. jassert (source != 0);
  18786. if (startGain == endGain)
  18787. {
  18788. addFrom (destChannel,
  18789. destStartSample,
  18790. source,
  18791. numSamples,
  18792. startGain);
  18793. }
  18794. else
  18795. {
  18796. if (numSamples > 0 && (startGain != 0.0f || endGain != 0.0f))
  18797. {
  18798. const float increment = (endGain - startGain) / numSamples;
  18799. float* d = channels [destChannel] + destStartSample;
  18800. while (--numSamples >= 0)
  18801. {
  18802. *d++ += startGain * *source++;
  18803. startGain += increment;
  18804. }
  18805. }
  18806. }
  18807. }
  18808. void AudioSampleBuffer::copyFrom (const int destChannel,
  18809. const int destStartSample,
  18810. const AudioSampleBuffer& source,
  18811. const int sourceChannel,
  18812. const int sourceStartSample,
  18813. int numSamples) throw()
  18814. {
  18815. jassert (&source != this || sourceChannel != destChannel);
  18816. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18817. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18818. jassert (((unsigned int) sourceChannel) < (unsigned int) source.numChannels);
  18819. jassert (sourceStartSample >= 0 && sourceStartSample + numSamples <= source.size);
  18820. if (numSamples > 0)
  18821. {
  18822. memcpy (channels [destChannel] + destStartSample,
  18823. source.channels [sourceChannel] + sourceStartSample,
  18824. sizeof (float) * numSamples);
  18825. }
  18826. }
  18827. void AudioSampleBuffer::copyFrom (const int destChannel,
  18828. const int destStartSample,
  18829. const float* source,
  18830. int numSamples) throw()
  18831. {
  18832. jassert (((unsigned int) destChannel) < (unsigned int) numChannels);
  18833. jassert (destStartSample >= 0 && destStartSample + numSamples <= size);
  18834. jassert (source != 0);
  18835. if (numSamples > 0)
  18836. {
  18837. memcpy (channels [destChannel] + destStartSample,
  18838. source,
  18839. sizeof (float) * numSamples);
  18840. }
  18841. }
  18842. void AudioSampleBuffer::findMinMax (const int channel,
  18843. const int startSample,
  18844. int numSamples,
  18845. float& minVal,
  18846. float& maxVal) const throw()
  18847. {
  18848. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18849. jassert (startSample >= 0 && startSample + numSamples <= size);
  18850. if (numSamples <= 0)
  18851. {
  18852. minVal = 0.0f;
  18853. maxVal = 0.0f;
  18854. }
  18855. else
  18856. {
  18857. const float* d = channels [channel] + startSample;
  18858. float mn = *d++;
  18859. float mx = mn;
  18860. while (--numSamples > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  18861. {
  18862. const float samp = *d++;
  18863. if (samp > mx)
  18864. mx = samp;
  18865. if (samp < mn)
  18866. mn = samp;
  18867. }
  18868. maxVal = mx;
  18869. minVal = mn;
  18870. }
  18871. }
  18872. float AudioSampleBuffer::getMagnitude (const int channel,
  18873. const int startSample,
  18874. const int numSamples) const throw()
  18875. {
  18876. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18877. jassert (startSample >= 0 && startSample + numSamples <= size);
  18878. float mn, mx;
  18879. findMinMax (channel, startSample, numSamples, mn, mx);
  18880. return jmax (mn, -mn, mx, -mx);
  18881. }
  18882. float AudioSampleBuffer::getMagnitude (const int startSample,
  18883. const int numSamples) const throw()
  18884. {
  18885. float mag = 0.0f;
  18886. for (int i = 0; i < numChannels; ++i)
  18887. mag = jmax (mag, getMagnitude (i, startSample, numSamples));
  18888. return mag;
  18889. }
  18890. float AudioSampleBuffer::getRMSLevel (const int channel,
  18891. const int startSample,
  18892. const int numSamples) const throw()
  18893. {
  18894. jassert (((unsigned int) channel) < (unsigned int) numChannels);
  18895. jassert (startSample >= 0 && startSample + numSamples <= size);
  18896. if (numSamples <= 0 || channel < 0 || channel >= numChannels)
  18897. return 0.0f;
  18898. const float* const data = channels [channel] + startSample;
  18899. double sum = 0.0;
  18900. for (int i = 0; i < numSamples; ++i)
  18901. {
  18902. const float sample = data [i];
  18903. sum += sample * sample;
  18904. }
  18905. return (float) sqrt (sum / numSamples);
  18906. }
  18907. void AudioSampleBuffer::readFromAudioReader (AudioFormatReader* reader,
  18908. const int startSample,
  18909. const int numSamples,
  18910. const int readerStartSample,
  18911. const bool useLeftChan,
  18912. const bool useRightChan) throw()
  18913. {
  18914. jassert (reader != 0);
  18915. jassert (startSample >= 0 && startSample + numSamples <= size);
  18916. if (numSamples > 0)
  18917. {
  18918. int* chans[3];
  18919. if (useLeftChan == useRightChan)
  18920. {
  18921. chans[0] = (int*) getSampleData (0, startSample);
  18922. chans[1] = (reader->numChannels > 1 && getNumChannels() > 1) ? (int*) getSampleData (1, startSample) : 0;
  18923. }
  18924. else if (useLeftChan || (reader->numChannels == 1))
  18925. {
  18926. chans[0] = (int*) getSampleData (0, startSample);
  18927. chans[1] = 0;
  18928. }
  18929. else if (useRightChan)
  18930. {
  18931. chans[0] = 0;
  18932. chans[1] = (int*) getSampleData (0, startSample);
  18933. }
  18934. chans[2] = 0;
  18935. reader->read (chans, readerStartSample, numSamples);
  18936. if (! reader->usesFloatingPointData)
  18937. {
  18938. for (int j = 0; j < 2; ++j)
  18939. {
  18940. float* const d = (float*) (chans[j]);
  18941. if (d != 0)
  18942. {
  18943. const float multiplier = 1.0f / 0x7fffffff;
  18944. for (int i = 0; i < numSamples; ++i)
  18945. d[i] = *(int*)(d + i) * multiplier;
  18946. }
  18947. }
  18948. }
  18949. if (numChannels > 1 && (chans[0] == 0 || chans[1] == 0))
  18950. {
  18951. // if this is a stereo buffer and the source was mono, dupe the first channel..
  18952. memcpy (getSampleData (1, startSample),
  18953. getSampleData (0, startSample),
  18954. sizeof (float) * numSamples);
  18955. }
  18956. }
  18957. }
  18958. void AudioSampleBuffer::writeToAudioWriter (AudioFormatWriter* writer,
  18959. const int startSample,
  18960. const int numSamples) const throw()
  18961. {
  18962. jassert (startSample >= 0 && startSample + numSamples <= size);
  18963. if (numSamples > 0)
  18964. {
  18965. int* chans [3];
  18966. if (writer->isFloatingPoint())
  18967. {
  18968. chans[0] = (int*) getSampleData (0, startSample);
  18969. if (numChannels > 1)
  18970. chans[1] = (int*) getSampleData (1, startSample);
  18971. else
  18972. chans[1] = 0;
  18973. chans[2] = 0;
  18974. writer->write ((const int**) chans, numSamples);
  18975. }
  18976. else
  18977. {
  18978. chans[0] = (int*) juce_malloc (sizeof (int) * numSamples * 2);
  18979. if (numChannels > 1)
  18980. chans[1] = chans[0] + numSamples;
  18981. else
  18982. chans[1] = 0;
  18983. chans[2] = 0;
  18984. for (int j = 0; j < 2; ++j)
  18985. {
  18986. int* const dest = chans[j];
  18987. if (dest != 0)
  18988. {
  18989. const float* const src = channels [j] + startSample;
  18990. for (int i = 0; i < numSamples; ++i)
  18991. {
  18992. const double samp = src[i];
  18993. if (samp <= -1.0)
  18994. dest[i] = INT_MIN;
  18995. else if (samp >= 1.0)
  18996. dest[i] = INT_MAX;
  18997. else
  18998. dest[i] = roundDoubleToInt (INT_MAX * samp);
  18999. }
  19000. }
  19001. }
  19002. writer->write ((const int**) chans, numSamples);
  19003. juce_free (chans[0]);
  19004. }
  19005. }
  19006. }
  19007. END_JUCE_NAMESPACE
  19008. /********* End of inlined file: juce_AudioSampleBuffer.cpp *********/
  19009. /********* Start of inlined file: juce_IIRFilter.cpp *********/
  19010. BEGIN_JUCE_NAMESPACE
  19011. IIRFilter::IIRFilter() throw()
  19012. : active (false)
  19013. {
  19014. reset();
  19015. }
  19016. IIRFilter::IIRFilter (const IIRFilter& other) throw()
  19017. : active (other.active)
  19018. {
  19019. const ScopedLock sl (other.processLock);
  19020. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  19021. reset();
  19022. }
  19023. IIRFilter::~IIRFilter() throw()
  19024. {
  19025. }
  19026. void IIRFilter::reset() throw()
  19027. {
  19028. const ScopedLock sl (processLock);
  19029. x1 = 0;
  19030. x2 = 0;
  19031. y1 = 0;
  19032. y2 = 0;
  19033. }
  19034. float IIRFilter::processSingleSampleRaw (const float in) throw()
  19035. {
  19036. float out = coefficients[0] * in
  19037. + coefficients[1] * x1
  19038. + coefficients[2] * x2
  19039. - coefficients[4] * y1
  19040. - coefficients[5] * y2;
  19041. #if JUCE_INTEL
  19042. if (! (out < -1.0e-8 || out > 1.0e-8))
  19043. out = 0;
  19044. #endif
  19045. x2 = x1;
  19046. x1 = in;
  19047. y2 = y1;
  19048. y1 = out;
  19049. return out;
  19050. }
  19051. void IIRFilter::processSamples (float* const samples,
  19052. const int numSamples) throw()
  19053. {
  19054. const ScopedLock sl (processLock);
  19055. if (active)
  19056. {
  19057. for (int i = 0; i < numSamples; ++i)
  19058. {
  19059. const float in = samples[i];
  19060. float out = coefficients[0] * in
  19061. + coefficients[1] * x1
  19062. + coefficients[2] * x2
  19063. - coefficients[4] * y1
  19064. - coefficients[5] * y2;
  19065. #if JUCE_INTEL
  19066. if (! (out < -1.0e-8 || out > 1.0e-8))
  19067. out = 0;
  19068. #endif
  19069. x2 = x1;
  19070. x1 = in;
  19071. y2 = y1;
  19072. y1 = out;
  19073. samples[i] = out;
  19074. }
  19075. }
  19076. }
  19077. void IIRFilter::makeLowPass (const double sampleRate,
  19078. const double frequency) throw()
  19079. {
  19080. jassert (sampleRate > 0);
  19081. const double n = 1.0 / tan (double_Pi * frequency / sampleRate);
  19082. const double nSquared = n * n;
  19083. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  19084. setCoefficients (c1,
  19085. c1 * 2.0f,
  19086. c1,
  19087. 1.0,
  19088. c1 * 2.0 * (1.0 - nSquared),
  19089. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  19090. }
  19091. void IIRFilter::makeHighPass (const double sampleRate,
  19092. const double frequency) throw()
  19093. {
  19094. const double n = tan (double_Pi * frequency / sampleRate);
  19095. const double nSquared = n * n;
  19096. const double c1 = 1.0 / (1.0 + sqrt (2.0) * n + nSquared);
  19097. setCoefficients (c1,
  19098. c1 * -2.0f,
  19099. c1,
  19100. 1.0,
  19101. c1 * 2.0 * (nSquared - 1.0),
  19102. c1 * (1.0 - sqrt (2.0) * n + nSquared));
  19103. }
  19104. void IIRFilter::makeLowShelf (const double sampleRate,
  19105. const double cutOffFrequency,
  19106. const double Q,
  19107. const float gainFactor) throw()
  19108. {
  19109. jassert (sampleRate > 0);
  19110. jassert (Q > 0);
  19111. const double A = jmax (0.0f, gainFactor);
  19112. const double aminus1 = A - 1.0;
  19113. const double aplus1 = A + 1.0;
  19114. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  19115. const double coso = cos (omega);
  19116. const double beta = sin (omega) * sqrt (A) / Q;
  19117. const double aminus1TimesCoso = aminus1 * coso;
  19118. setCoefficients (A * (aplus1 - aminus1TimesCoso + beta),
  19119. A * 2.0 * (aminus1 - aplus1 * coso),
  19120. A * (aplus1 - aminus1TimesCoso - beta),
  19121. aplus1 + aminus1TimesCoso + beta,
  19122. -2.0 * (aminus1 + aplus1 * coso),
  19123. aplus1 + aminus1TimesCoso - beta);
  19124. }
  19125. void IIRFilter::makeHighShelf (const double sampleRate,
  19126. const double cutOffFrequency,
  19127. const double Q,
  19128. const float gainFactor) throw()
  19129. {
  19130. jassert (sampleRate > 0);
  19131. jassert (Q > 0);
  19132. const double A = jmax (0.0f, gainFactor);
  19133. const double aminus1 = A - 1.0;
  19134. const double aplus1 = A + 1.0;
  19135. const double omega = (double_Pi * 2.0 * jmax (cutOffFrequency, 2.0)) / sampleRate;
  19136. const double coso = cos (omega);
  19137. const double beta = sin (omega) * sqrt (A) / Q;
  19138. const double aminus1TimesCoso = aminus1 * coso;
  19139. setCoefficients (A * (aplus1 + aminus1TimesCoso + beta),
  19140. A * -2.0 * (aminus1 + aplus1 * coso),
  19141. A * (aplus1 + aminus1TimesCoso - beta),
  19142. aplus1 - aminus1TimesCoso + beta,
  19143. 2.0 * (aminus1 - aplus1 * coso),
  19144. aplus1 - aminus1TimesCoso - beta);
  19145. }
  19146. void IIRFilter::makeBandPass (const double sampleRate,
  19147. const double centreFrequency,
  19148. const double Q,
  19149. const float gainFactor) throw()
  19150. {
  19151. jassert (sampleRate > 0);
  19152. jassert (Q > 0);
  19153. const double A = jmax (0.0f, gainFactor);
  19154. const double omega = (double_Pi * 2.0 * jmax (centreFrequency, 2.0)) / sampleRate;
  19155. const double alpha = 0.5 * sin (omega) / Q;
  19156. const double c2 = -2.0 * cos (omega);
  19157. const double alphaTimesA = alpha * A;
  19158. const double alphaOverA = alpha / A;
  19159. setCoefficients (1.0 + alphaTimesA,
  19160. c2,
  19161. 1.0 - alphaTimesA,
  19162. 1.0 + alphaOverA,
  19163. c2,
  19164. 1.0 - alphaOverA);
  19165. }
  19166. void IIRFilter::makeInactive() throw()
  19167. {
  19168. const ScopedLock sl (processLock);
  19169. active = false;
  19170. }
  19171. void IIRFilter::copyCoefficientsFrom (const IIRFilter& other) throw()
  19172. {
  19173. const ScopedLock sl (processLock);
  19174. memcpy (coefficients, other.coefficients, sizeof (coefficients));
  19175. active = other.active;
  19176. }
  19177. void IIRFilter::setCoefficients (double c1,
  19178. double c2,
  19179. double c3,
  19180. double c4,
  19181. double c5,
  19182. double c6) throw()
  19183. {
  19184. const double a = 1.0 / c4;
  19185. c1 *= a;
  19186. c2 *= a;
  19187. c3 *= a;
  19188. c5 *= a;
  19189. c6 *= a;
  19190. const ScopedLock sl (processLock);
  19191. coefficients[0] = (float) c1;
  19192. coefficients[1] = (float) c2;
  19193. coefficients[2] = (float) c3;
  19194. coefficients[3] = (float) c4;
  19195. coefficients[4] = (float) c5;
  19196. coefficients[5] = (float) c6;
  19197. active = true;
  19198. }
  19199. END_JUCE_NAMESPACE
  19200. /********* End of inlined file: juce_IIRFilter.cpp *********/
  19201. /********* Start of inlined file: juce_MidiBuffer.cpp *********/
  19202. BEGIN_JUCE_NAMESPACE
  19203. MidiBuffer::MidiBuffer() throw()
  19204. : ArrayAllocationBase <uint8> (32),
  19205. bytesUsed (0)
  19206. {
  19207. }
  19208. MidiBuffer::MidiBuffer (const MidiBuffer& other) throw()
  19209. : ArrayAllocationBase <uint8> (32),
  19210. bytesUsed (other.bytesUsed)
  19211. {
  19212. ensureAllocatedSize (bytesUsed);
  19213. memcpy (elements, other.elements, bytesUsed);
  19214. }
  19215. const MidiBuffer& MidiBuffer::operator= (const MidiBuffer& other) throw()
  19216. {
  19217. if (this != &other)
  19218. {
  19219. bytesUsed = other.bytesUsed;
  19220. ensureAllocatedSize (bytesUsed);
  19221. if (bytesUsed > 0)
  19222. memcpy (elements, other.elements, bytesUsed);
  19223. }
  19224. return *this;
  19225. }
  19226. MidiBuffer::~MidiBuffer() throw()
  19227. {
  19228. }
  19229. void MidiBuffer::clear() throw()
  19230. {
  19231. bytesUsed = 0;
  19232. }
  19233. void MidiBuffer::clear (const int startSample,
  19234. const int numSamples) throw()
  19235. {
  19236. uint8* const start = findEventAfter (elements, startSample - 1);
  19237. uint8* const end = findEventAfter (start, startSample + numSamples - 1);
  19238. if (end > start)
  19239. {
  19240. const size_t bytesToMove = (size_t) (bytesUsed - (end - elements));
  19241. if (bytesToMove > 0)
  19242. memmove (start, end, bytesToMove);
  19243. bytesUsed -= (int) (end - start);
  19244. }
  19245. }
  19246. void MidiBuffer::addEvent (const MidiMessage& m,
  19247. const int sampleNumber) throw()
  19248. {
  19249. addEvent (m.getRawData(), m.getRawDataSize(), sampleNumber);
  19250. }
  19251. static int findActualEventLength (const uint8* const data,
  19252. const int maxBytes) throw()
  19253. {
  19254. unsigned int byte = (unsigned int) *data;
  19255. int size = 0;
  19256. if (byte == 0xf0 || byte == 0xf7)
  19257. {
  19258. const uint8* d = data + 1;
  19259. while (d < data + maxBytes)
  19260. if (*d++ == 0xf7)
  19261. break;
  19262. size = (int) (d - data);
  19263. }
  19264. else if (byte == 0xff)
  19265. {
  19266. int n;
  19267. const int bytesLeft = MidiMessage::readVariableLengthVal (data + 1, n);
  19268. size = jmin (maxBytes, n + 2 + bytesLeft);
  19269. }
  19270. else if (byte >= 0x80)
  19271. {
  19272. size = jmin (maxBytes, MidiMessage::getMessageLengthFromFirstByte ((uint8) byte));
  19273. }
  19274. return size;
  19275. }
  19276. void MidiBuffer::addEvent (const uint8* const newData,
  19277. const int maxBytes,
  19278. const int sampleNumber) throw()
  19279. {
  19280. const int numBytes = findActualEventLength (newData, maxBytes);
  19281. if (numBytes > 0)
  19282. {
  19283. ensureAllocatedSize (bytesUsed + numBytes + 6);
  19284. uint8* d = findEventAfter (elements, sampleNumber);
  19285. const size_t bytesToMove = (size_t) (bytesUsed - (d - elements));
  19286. if (bytesToMove > 0)
  19287. memmove (d + numBytes + 6,
  19288. d,
  19289. bytesToMove);
  19290. *(int*) d = sampleNumber;
  19291. d += 4;
  19292. *(uint16*) d = (uint16) numBytes;
  19293. d += 2;
  19294. memcpy (d, newData, numBytes);
  19295. bytesUsed += numBytes + 6;
  19296. }
  19297. }
  19298. void MidiBuffer::addEvents (const MidiBuffer& otherBuffer,
  19299. const int startSample,
  19300. const int numSamples,
  19301. const int sampleDeltaToAdd) throw()
  19302. {
  19303. Iterator i (otherBuffer);
  19304. i.setNextSamplePosition (startSample);
  19305. const uint8* data;
  19306. int size, position;
  19307. while (i.getNextEvent (data, size, position)
  19308. && (position < startSample + numSamples || numSamples < 0))
  19309. {
  19310. addEvent (data, size, position + sampleDeltaToAdd);
  19311. }
  19312. }
  19313. bool MidiBuffer::isEmpty() const throw()
  19314. {
  19315. return bytesUsed == 0;
  19316. }
  19317. int MidiBuffer::getNumEvents() const throw()
  19318. {
  19319. int n = 0;
  19320. const uint8* d = elements;
  19321. const uint8* const end = elements + bytesUsed;
  19322. while (d < end)
  19323. {
  19324. d += 4;
  19325. d += 2 + *(const uint16*) d;
  19326. ++n;
  19327. }
  19328. return n;
  19329. }
  19330. int MidiBuffer::getFirstEventTime() const throw()
  19331. {
  19332. return (bytesUsed > 0) ? *(const int*) elements : 0;
  19333. }
  19334. int MidiBuffer::getLastEventTime() const throw()
  19335. {
  19336. if (bytesUsed == 0)
  19337. return 0;
  19338. const uint8* d = elements;
  19339. const uint8* const endData = d + bytesUsed;
  19340. for (;;)
  19341. {
  19342. const uint8* nextOne = d + 6 + * (const uint16*) (d + 4);
  19343. if (nextOne >= endData)
  19344. return *(const int*) d;
  19345. d = nextOne;
  19346. }
  19347. }
  19348. uint8* MidiBuffer::findEventAfter (uint8* d, const int samplePosition) const throw()
  19349. {
  19350. const uint8* const endData = elements + bytesUsed;
  19351. while (d < endData && *(int*) d <= samplePosition)
  19352. {
  19353. d += 4;
  19354. d += 2 + *(uint16*) d;
  19355. }
  19356. return d;
  19357. }
  19358. MidiBuffer::Iterator::Iterator (const MidiBuffer& buffer) throw()
  19359. : buffer (buffer),
  19360. data (buffer.elements)
  19361. {
  19362. }
  19363. MidiBuffer::Iterator::~Iterator() throw()
  19364. {
  19365. }
  19366. void MidiBuffer::Iterator::setNextSamplePosition (const int samplePosition) throw()
  19367. {
  19368. data = buffer.elements;
  19369. const uint8* dataEnd = buffer.elements + buffer.bytesUsed;
  19370. while (data < dataEnd && *(int*) data < samplePosition)
  19371. {
  19372. data += 4;
  19373. data += 2 + *(uint16*) data;
  19374. }
  19375. }
  19376. bool MidiBuffer::Iterator::getNextEvent (const uint8* &midiData,
  19377. int& numBytes,
  19378. int& samplePosition) throw()
  19379. {
  19380. if (data >= buffer.elements + buffer.bytesUsed)
  19381. return false;
  19382. samplePosition = *(int*) data;
  19383. data += 4;
  19384. numBytes = *(uint16*) data;
  19385. data += 2;
  19386. midiData = data;
  19387. data += numBytes;
  19388. return true;
  19389. }
  19390. bool MidiBuffer::Iterator::getNextEvent (MidiMessage& result,
  19391. int& samplePosition) throw()
  19392. {
  19393. if (data >= buffer.elements + buffer.bytesUsed)
  19394. return false;
  19395. samplePosition = *(int*) data;
  19396. data += 4;
  19397. const int numBytes = *(uint16*) data;
  19398. data += 2;
  19399. result = MidiMessage (data, numBytes, samplePosition);
  19400. data += numBytes;
  19401. return true;
  19402. }
  19403. END_JUCE_NAMESPACE
  19404. /********* End of inlined file: juce_MidiBuffer.cpp *********/
  19405. /********* Start of inlined file: juce_MidiFile.cpp *********/
  19406. BEGIN_JUCE_NAMESPACE
  19407. struct TempoInfo
  19408. {
  19409. double bpm, timestamp;
  19410. };
  19411. struct TimeSigInfo
  19412. {
  19413. int numerator, denominator;
  19414. double timestamp;
  19415. };
  19416. MidiFile::MidiFile() throw()
  19417. : numTracks (0),
  19418. timeFormat ((short)(unsigned short)0xe728)
  19419. {
  19420. }
  19421. MidiFile::~MidiFile() throw()
  19422. {
  19423. clear();
  19424. }
  19425. void MidiFile::clear() throw()
  19426. {
  19427. while (numTracks > 0)
  19428. delete tracks [--numTracks];
  19429. }
  19430. int MidiFile::getNumTracks() const throw()
  19431. {
  19432. return numTracks;
  19433. }
  19434. const MidiMessageSequence* MidiFile::getTrack (const int index) const throw()
  19435. {
  19436. return (((unsigned int) index) < (unsigned int) numTracks) ? tracks[index] : 0;
  19437. }
  19438. void MidiFile::addTrack (const MidiMessageSequence& trackSequence) throw()
  19439. {
  19440. jassert (numTracks < numElementsInArray (tracks));
  19441. if (numTracks < numElementsInArray (tracks))
  19442. tracks [numTracks++] = new MidiMessageSequence (trackSequence);
  19443. }
  19444. short MidiFile::getTimeFormat() const throw()
  19445. {
  19446. return timeFormat;
  19447. }
  19448. void MidiFile::setTicksPerQuarterNote (const int ticks) throw()
  19449. {
  19450. timeFormat = (short)ticks;
  19451. }
  19452. void MidiFile::setSmpteTimeFormat (const int framesPerSecond,
  19453. const int subframeResolution) throw()
  19454. {
  19455. timeFormat = (short) (((-framesPerSecond) << 8) | subframeResolution);
  19456. }
  19457. void MidiFile::findAllTempoEvents (MidiMessageSequence& tempoChangeEvents) const
  19458. {
  19459. for (int i = numTracks; --i >= 0;)
  19460. {
  19461. const int numEvents = tracks[i]->getNumEvents();
  19462. for (int j = 0; j < numEvents; ++j)
  19463. {
  19464. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  19465. if (m.isTempoMetaEvent())
  19466. tempoChangeEvents.addEvent (m);
  19467. }
  19468. }
  19469. }
  19470. void MidiFile::findAllTimeSigEvents (MidiMessageSequence& timeSigEvents) const
  19471. {
  19472. for (int i = numTracks; --i >= 0;)
  19473. {
  19474. const int numEvents = tracks[i]->getNumEvents();
  19475. for (int j = 0; j < numEvents; ++j)
  19476. {
  19477. const MidiMessage& m = tracks[i]->getEventPointer (j)->message;
  19478. if (m.isTimeSignatureMetaEvent())
  19479. timeSigEvents.addEvent (m);
  19480. }
  19481. }
  19482. }
  19483. double MidiFile::getLastTimestamp() const
  19484. {
  19485. double t = 0.0;
  19486. for (int i = numTracks; --i >= 0;)
  19487. t = jmax (t, tracks[i]->getEndTime());
  19488. return t;
  19489. }
  19490. static bool parseMidiHeader (const char* &data,
  19491. short& timeFormat,
  19492. short& fileType,
  19493. short& numberOfTracks)
  19494. {
  19495. unsigned int ch = (int) bigEndianInt (data);
  19496. data += 4;
  19497. if (ch != bigEndianInt ("MThd"))
  19498. {
  19499. bool ok = false;
  19500. if (ch == bigEndianInt ("RIFF"))
  19501. {
  19502. for (int i = 0; i < 8; ++i)
  19503. {
  19504. ch = bigEndianInt (data);
  19505. data += 4;
  19506. if (ch == bigEndianInt ("MThd"))
  19507. {
  19508. ok = true;
  19509. break;
  19510. }
  19511. }
  19512. }
  19513. if (! ok)
  19514. return false;
  19515. }
  19516. unsigned int bytesRemaining = bigEndianInt (data);
  19517. data += 4;
  19518. fileType = (short)bigEndianShort (data);
  19519. data += 2;
  19520. numberOfTracks = (short)bigEndianShort (data);
  19521. data += 2;
  19522. timeFormat = (short)bigEndianShort (data);
  19523. data += 2;
  19524. bytesRemaining -= 6;
  19525. data += bytesRemaining;
  19526. return true;
  19527. }
  19528. bool MidiFile::readFrom (InputStream& sourceStream)
  19529. {
  19530. clear();
  19531. MemoryBlock data;
  19532. const int maxSensibleMidiFileSize = 2 * 1024 * 1024;
  19533. // (put a sanity-check on the file size, as midi files are generally small)
  19534. if (sourceStream.readIntoMemoryBlock (data, maxSensibleMidiFileSize))
  19535. {
  19536. int size = data.getSize();
  19537. const char* d = (char*) data.getData();
  19538. short fileType, expectedTracks;
  19539. if (size > 16 && parseMidiHeader (d, timeFormat, fileType, expectedTracks))
  19540. {
  19541. size -= (int) (d - (char*) data.getData());
  19542. int track = 0;
  19543. while (size > 0 && track < expectedTracks)
  19544. {
  19545. const int chunkType = (int)bigEndianInt (d);
  19546. d += 4;
  19547. const int chunkSize = (int)bigEndianInt (d);
  19548. d += 4;
  19549. if (chunkSize <= 0)
  19550. break;
  19551. if (size < 0)
  19552. return false;
  19553. if (chunkType == (int)bigEndianInt ("MTrk"))
  19554. {
  19555. readNextTrack (d, chunkSize);
  19556. }
  19557. size -= chunkSize + 8;
  19558. d += chunkSize;
  19559. ++track;
  19560. }
  19561. return true;
  19562. }
  19563. }
  19564. return false;
  19565. }
  19566. // a comparator that puts all the note-offs before note-ons that have the same time
  19567. int MidiFile::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  19568. const MidiMessageSequence::MidiEventHolder* const second) throw()
  19569. {
  19570. const double diff = (first->message.getTimeStamp() - second->message.getTimeStamp());
  19571. if (diff == 0)
  19572. {
  19573. if (first->message.isNoteOff() && second->message.isNoteOn())
  19574. return -1;
  19575. else if (first->message.isNoteOn() && second->message.isNoteOff())
  19576. return 1;
  19577. else
  19578. return 0;
  19579. }
  19580. else
  19581. {
  19582. return (diff > 0) ? 1 : -1;
  19583. }
  19584. }
  19585. void MidiFile::readNextTrack (const char* data, int size)
  19586. {
  19587. double time = 0;
  19588. char lastStatusByte = 0;
  19589. MidiMessageSequence result;
  19590. while (size > 0)
  19591. {
  19592. int bytesUsed;
  19593. const int delay = MidiMessage::readVariableLengthVal ((const uint8*) data, bytesUsed);
  19594. data += bytesUsed;
  19595. size -= bytesUsed;
  19596. time += delay;
  19597. int messSize = 0;
  19598. const MidiMessage mm ((const uint8*) data, size, messSize, lastStatusByte, time);
  19599. if (messSize <= 0)
  19600. break;
  19601. size -= messSize;
  19602. data += messSize;
  19603. result.addEvent (mm);
  19604. const char firstByte = *(mm.getRawData());
  19605. if ((firstByte & 0xf0) != 0xf0)
  19606. lastStatusByte = firstByte;
  19607. }
  19608. // use a sort that puts all the note-offs before note-ons that have the same time
  19609. result.list.sort (*this, true);
  19610. result.updateMatchedPairs();
  19611. addTrack (result);
  19612. }
  19613. static double convertTicksToSeconds (const double time,
  19614. const MidiMessageSequence& tempoEvents,
  19615. const int timeFormat)
  19616. {
  19617. if (timeFormat > 0)
  19618. {
  19619. int numer = 4, denom = 4;
  19620. double tempoTime = 0.0, correctedTempoTime = 0.0;
  19621. const double tickLen = 1.0 / (timeFormat & 0x7fff);
  19622. double secsPerTick = 0.5 * tickLen;
  19623. const int numEvents = tempoEvents.getNumEvents();
  19624. for (int i = 0; i < numEvents; ++i)
  19625. {
  19626. const MidiMessage& m = tempoEvents.getEventPointer(i)->message;
  19627. if (time <= m.getTimeStamp())
  19628. break;
  19629. if (timeFormat > 0)
  19630. {
  19631. correctedTempoTime = correctedTempoTime
  19632. + (m.getTimeStamp() - tempoTime) * secsPerTick;
  19633. }
  19634. else
  19635. {
  19636. correctedTempoTime = tickLen * m.getTimeStamp() / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  19637. }
  19638. tempoTime = m.getTimeStamp();
  19639. if (m.isTempoMetaEvent())
  19640. secsPerTick = tickLen * m.getTempoSecondsPerQuarterNote();
  19641. else if (m.isTimeSignatureMetaEvent())
  19642. m.getTimeSignatureInfo (numer, denom);
  19643. while (i + 1 < numEvents)
  19644. {
  19645. const MidiMessage& m2 = tempoEvents.getEventPointer(i + 1)->message;
  19646. if (m2.getTimeStamp() == tempoTime)
  19647. {
  19648. ++i;
  19649. if (m2.isTempoMetaEvent())
  19650. secsPerTick = tickLen * m2.getTempoSecondsPerQuarterNote();
  19651. else if (m2.isTimeSignatureMetaEvent())
  19652. m2.getTimeSignatureInfo (numer, denom);
  19653. }
  19654. else
  19655. {
  19656. break;
  19657. }
  19658. }
  19659. }
  19660. return correctedTempoTime + (time - tempoTime) * secsPerTick;
  19661. }
  19662. else
  19663. {
  19664. return time / (((timeFormat & 0x7fff) >> 8) * (timeFormat & 0xff));
  19665. }
  19666. }
  19667. void MidiFile::convertTimestampTicksToSeconds()
  19668. {
  19669. MidiMessageSequence tempoEvents;
  19670. findAllTempoEvents (tempoEvents);
  19671. findAllTimeSigEvents (tempoEvents);
  19672. for (int i = 0; i < numTracks; ++i)
  19673. {
  19674. MidiMessageSequence& ms = *tracks[i];
  19675. for (int j = ms.getNumEvents(); --j >= 0;)
  19676. {
  19677. MidiMessage& m = ms.getEventPointer(j)->message;
  19678. m.setTimeStamp (convertTicksToSeconds (m.getTimeStamp(),
  19679. tempoEvents,
  19680. timeFormat));
  19681. }
  19682. }
  19683. }
  19684. static void writeVariableLengthInt (OutputStream& out, unsigned int v)
  19685. {
  19686. unsigned int buffer = v & 0x7F;
  19687. while ((v >>= 7) != 0)
  19688. {
  19689. buffer <<= 8;
  19690. buffer |= ((v & 0x7F) | 0x80);
  19691. }
  19692. for (;;)
  19693. {
  19694. out.writeByte ((char) buffer);
  19695. if (buffer & 0x80)
  19696. buffer >>= 8;
  19697. else
  19698. break;
  19699. }
  19700. }
  19701. bool MidiFile::writeTo (OutputStream& out)
  19702. {
  19703. out.writeIntBigEndian ((int) bigEndianInt ("MThd"));
  19704. out.writeIntBigEndian (6);
  19705. out.writeShortBigEndian (1); // type
  19706. out.writeShortBigEndian (numTracks);
  19707. out.writeShortBigEndian (timeFormat);
  19708. for (int i = 0; i < numTracks; ++i)
  19709. writeTrack (out, i);
  19710. out.flush();
  19711. return true;
  19712. }
  19713. void MidiFile::writeTrack (OutputStream& mainOut,
  19714. const int trackNum)
  19715. {
  19716. MemoryOutputStream out;
  19717. const MidiMessageSequence& ms = *tracks[trackNum];
  19718. int lastTick = 0;
  19719. char lastStatusByte = 0;
  19720. for (int i = 0; i < ms.getNumEvents(); ++i)
  19721. {
  19722. const MidiMessage& mm = ms.getEventPointer(i)->message;
  19723. const int tick = roundDoubleToInt (mm.getTimeStamp());
  19724. const int delta = jmax (0, tick - lastTick);
  19725. writeVariableLengthInt (out, delta);
  19726. lastTick = tick;
  19727. const char statusByte = *(mm.getRawData());
  19728. if ((statusByte == lastStatusByte)
  19729. && ((statusByte & 0xf0) != 0xf0)
  19730. && i > 0
  19731. && mm.getRawDataSize() > 1)
  19732. {
  19733. out.write (mm.getRawData() + 1, mm.getRawDataSize() - 1);
  19734. }
  19735. else
  19736. {
  19737. out.write (mm.getRawData(), mm.getRawDataSize());
  19738. }
  19739. lastStatusByte = statusByte;
  19740. }
  19741. out.writeByte (0);
  19742. const MidiMessage m (MidiMessage::endOfTrack());
  19743. out.write (m.getRawData(),
  19744. m.getRawDataSize());
  19745. mainOut.writeIntBigEndian ((int)bigEndianInt ("MTrk"));
  19746. mainOut.writeIntBigEndian (out.getDataSize());
  19747. mainOut.write (out.getData(), out.getDataSize());
  19748. }
  19749. END_JUCE_NAMESPACE
  19750. /********* End of inlined file: juce_MidiFile.cpp *********/
  19751. /********* Start of inlined file: juce_MidiKeyboardState.cpp *********/
  19752. BEGIN_JUCE_NAMESPACE
  19753. MidiKeyboardState::MidiKeyboardState()
  19754. : listeners (2)
  19755. {
  19756. zeromem (noteStates, sizeof (noteStates));
  19757. }
  19758. MidiKeyboardState::~MidiKeyboardState()
  19759. {
  19760. }
  19761. void MidiKeyboardState::reset()
  19762. {
  19763. const ScopedLock sl (lock);
  19764. zeromem (noteStates, sizeof (noteStates));
  19765. eventsToAdd.clear();
  19766. }
  19767. bool MidiKeyboardState::isNoteOn (const int midiChannel, const int n) const throw()
  19768. {
  19769. jassert (midiChannel >= 0 && midiChannel <= 16);
  19770. return ((unsigned int) n) < 128
  19771. && (noteStates[n] & (1 << (midiChannel - 1))) != 0;
  19772. }
  19773. bool MidiKeyboardState::isNoteOnForChannels (const int midiChannelMask, const int n) const throw()
  19774. {
  19775. return ((unsigned int) n) < 128
  19776. && (noteStates[n] & midiChannelMask) != 0;
  19777. }
  19778. void MidiKeyboardState::noteOn (const int midiChannel, const int midiNoteNumber, const float velocity)
  19779. {
  19780. jassert (midiChannel >= 0 && midiChannel <= 16);
  19781. jassert (((unsigned int) midiNoteNumber) < 128);
  19782. const ScopedLock sl (lock);
  19783. if (((unsigned int) midiNoteNumber) < 128)
  19784. {
  19785. const int timeNow = (int) Time::getMillisecondCounter();
  19786. eventsToAdd.addEvent (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity), timeNow);
  19787. eventsToAdd.clear (0, timeNow - 500);
  19788. noteOnInternal (midiChannel, midiNoteNumber, velocity);
  19789. }
  19790. }
  19791. void MidiKeyboardState::noteOnInternal (const int midiChannel, const int midiNoteNumber, const float velocity)
  19792. {
  19793. if (((unsigned int) midiNoteNumber) < 128)
  19794. {
  19795. noteStates [midiNoteNumber] |= (1 << (midiChannel - 1));
  19796. for (int i = listeners.size(); --i >= 0;)
  19797. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  19798. ->handleNoteOn (this, midiChannel, midiNoteNumber, velocity);
  19799. }
  19800. }
  19801. void MidiKeyboardState::noteOff (const int midiChannel, const int midiNoteNumber)
  19802. {
  19803. const ScopedLock sl (lock);
  19804. if (isNoteOn (midiChannel, midiNoteNumber))
  19805. {
  19806. const int timeNow = (int) Time::getMillisecondCounter();
  19807. eventsToAdd.addEvent (MidiMessage::noteOff (midiChannel, midiNoteNumber), timeNow);
  19808. eventsToAdd.clear (0, timeNow - 500);
  19809. noteOffInternal (midiChannel, midiNoteNumber);
  19810. }
  19811. }
  19812. void MidiKeyboardState::noteOffInternal (const int midiChannel, const int midiNoteNumber)
  19813. {
  19814. if (isNoteOn (midiChannel, midiNoteNumber))
  19815. {
  19816. noteStates [midiNoteNumber] &= ~(1 << (midiChannel - 1));
  19817. for (int i = listeners.size(); --i >= 0;)
  19818. ((MidiKeyboardStateListener*) listeners.getUnchecked(i))
  19819. ->handleNoteOff (this, midiChannel, midiNoteNumber);
  19820. }
  19821. }
  19822. void MidiKeyboardState::allNotesOff (const int midiChannel)
  19823. {
  19824. const ScopedLock sl (lock);
  19825. if (midiChannel <= 0)
  19826. {
  19827. for (int i = 1; i <= 16; ++i)
  19828. allNotesOff (i);
  19829. }
  19830. else
  19831. {
  19832. for (int i = 0; i < 128; ++i)
  19833. noteOff (midiChannel, i);
  19834. }
  19835. }
  19836. void MidiKeyboardState::processNextMidiEvent (const MidiMessage& message)
  19837. {
  19838. if (message.isNoteOn())
  19839. {
  19840. noteOnInternal (message.getChannel(), message.getNoteNumber(), message.getFloatVelocity());
  19841. }
  19842. else if (message.isNoteOff())
  19843. {
  19844. noteOffInternal (message.getChannel(), message.getNoteNumber());
  19845. }
  19846. else if (message.isAllNotesOff())
  19847. {
  19848. for (int i = 0; i < 128; ++i)
  19849. noteOffInternal (message.getChannel(), i);
  19850. }
  19851. }
  19852. void MidiKeyboardState::processNextMidiBuffer (MidiBuffer& buffer,
  19853. const int startSample,
  19854. const int numSamples,
  19855. const bool injectIndirectEvents)
  19856. {
  19857. MidiBuffer::Iterator i (buffer);
  19858. MidiMessage message (0xf4, 0.0);
  19859. int time;
  19860. const ScopedLock sl (lock);
  19861. while (i.getNextEvent (message, time))
  19862. processNextMidiEvent (message);
  19863. if (injectIndirectEvents)
  19864. {
  19865. MidiBuffer::Iterator i2 (eventsToAdd);
  19866. const int firstEventToAdd = eventsToAdd.getFirstEventTime();
  19867. const double scaleFactor = numSamples / (double) (eventsToAdd.getLastEventTime() + 1 - firstEventToAdd);
  19868. while (i2.getNextEvent (message, time))
  19869. {
  19870. const int pos = jlimit (0, numSamples - 1, roundDoubleToInt ((time - firstEventToAdd) * scaleFactor));
  19871. buffer.addEvent (message, startSample + pos);
  19872. }
  19873. }
  19874. eventsToAdd.clear();
  19875. }
  19876. void MidiKeyboardState::addListener (MidiKeyboardStateListener* const listener) throw()
  19877. {
  19878. const ScopedLock sl (lock);
  19879. listeners.addIfNotAlreadyThere (listener);
  19880. }
  19881. void MidiKeyboardState::removeListener (MidiKeyboardStateListener* const listener) throw()
  19882. {
  19883. const ScopedLock sl (lock);
  19884. listeners.removeValue (listener);
  19885. }
  19886. END_JUCE_NAMESPACE
  19887. /********* End of inlined file: juce_MidiKeyboardState.cpp *********/
  19888. /********* Start of inlined file: juce_MidiMessage.cpp *********/
  19889. BEGIN_JUCE_NAMESPACE
  19890. int MidiMessage::readVariableLengthVal (const uint8* data,
  19891. int& numBytesUsed) throw()
  19892. {
  19893. numBytesUsed = 0;
  19894. int v = 0;
  19895. int i;
  19896. do
  19897. {
  19898. i = (int) *data++;
  19899. if (++numBytesUsed > 6)
  19900. break;
  19901. v = (v << 7) + (i & 0x7f);
  19902. } while (i & 0x80);
  19903. return v;
  19904. }
  19905. int MidiMessage::getMessageLengthFromFirstByte (const uint8 firstByte) throw()
  19906. {
  19907. // this method only works for valid starting bytes of a short midi message
  19908. jassert (firstByte >= 0x80
  19909. && firstByte != 0xf0
  19910. && firstByte != 0xf7);
  19911. static const char messageLengths[] =
  19912. {
  19913. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19914. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19915. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19916. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19917. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  19918. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  19919. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  19920. 1, 2, 3, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1
  19921. };
  19922. return messageLengths [firstByte & 0x7f];
  19923. }
  19924. MidiMessage::MidiMessage (const uint8* const d,
  19925. const int dataSize,
  19926. const double t) throw()
  19927. : timeStamp (t),
  19928. message (0),
  19929. size (dataSize)
  19930. {
  19931. jassert (dataSize > 0);
  19932. if (dataSize <= 4)
  19933. data = (uint8*) &message;
  19934. else
  19935. data = (uint8*) juce_malloc (dataSize);
  19936. memcpy (data, d, dataSize);
  19937. // check that the length matches the data..
  19938. jassert (size > 3 || *d >= 0xf0 || getMessageLengthFromFirstByte (*d) == size);
  19939. }
  19940. MidiMessage::MidiMessage (const int byte1,
  19941. const double t) throw()
  19942. : timeStamp (t),
  19943. data ((uint8*) &message),
  19944. size (1)
  19945. {
  19946. data[0] = (uint8) byte1;
  19947. // check that the length matches the data..
  19948. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 1);
  19949. }
  19950. MidiMessage::MidiMessage (const int byte1,
  19951. const int byte2,
  19952. const double t) throw()
  19953. : timeStamp (t),
  19954. data ((uint8*) &message),
  19955. size (2)
  19956. {
  19957. data[0] = (uint8) byte1;
  19958. data[1] = (uint8) byte2;
  19959. // check that the length matches the data..
  19960. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 2);
  19961. }
  19962. MidiMessage::MidiMessage (const int byte1,
  19963. const int byte2,
  19964. const int byte3,
  19965. const double t) throw()
  19966. : timeStamp (t),
  19967. data ((uint8*) &message),
  19968. size (3)
  19969. {
  19970. data[0] = (uint8) byte1;
  19971. data[1] = (uint8) byte2;
  19972. data[2] = (uint8) byte3;
  19973. // check that the length matches the data..
  19974. jassert (byte1 >= 0xf0 || getMessageLengthFromFirstByte ((uint8) byte1) == 3);
  19975. }
  19976. MidiMessage::MidiMessage (const MidiMessage& other) throw()
  19977. : timeStamp (other.timeStamp),
  19978. message (other.message),
  19979. size (other.size)
  19980. {
  19981. if (other.data != (uint8*) &other.message)
  19982. {
  19983. data = (uint8*) juce_malloc (size);
  19984. memcpy (data, other.data, size);
  19985. }
  19986. else
  19987. {
  19988. data = (uint8*) &message;
  19989. }
  19990. }
  19991. MidiMessage::MidiMessage (const MidiMessage& other,
  19992. const double newTimeStamp) throw()
  19993. : timeStamp (newTimeStamp),
  19994. message (other.message),
  19995. size (other.size)
  19996. {
  19997. if (other.data != (uint8*) &other.message)
  19998. {
  19999. data = (uint8*) juce_malloc (size);
  20000. memcpy (data, other.data, size);
  20001. }
  20002. else
  20003. {
  20004. data = (uint8*) &message;
  20005. }
  20006. }
  20007. MidiMessage::MidiMessage (const uint8* src,
  20008. int sz,
  20009. int& numBytesUsed,
  20010. const uint8 lastStatusByte,
  20011. double t) throw()
  20012. : timeStamp (t),
  20013. data ((uint8*) &message),
  20014. message (0)
  20015. {
  20016. unsigned int byte = (unsigned int) *src;
  20017. if (byte < 0x80)
  20018. {
  20019. byte = (unsigned int) (uint8) lastStatusByte;
  20020. numBytesUsed = -1;
  20021. }
  20022. else
  20023. {
  20024. numBytesUsed = 0;
  20025. --sz;
  20026. ++src;
  20027. }
  20028. if (byte >= 0x80)
  20029. {
  20030. if (byte == 0xf0)
  20031. {
  20032. const uint8* d = (const uint8*) src;
  20033. while (d < src + sz)
  20034. {
  20035. if (*d >= 0x80) // stop if we hit a status byte, and don't include it in this message
  20036. {
  20037. if (*d == 0xf7) // include an 0xf7 if we hit one
  20038. ++d;
  20039. break;
  20040. }
  20041. ++d;
  20042. }
  20043. size = 1 + (int) (d - src);
  20044. data = (uint8*) juce_malloc (size);
  20045. *data = (uint8) byte;
  20046. memcpy (data + 1, src, size - 1);
  20047. }
  20048. else if (byte == 0xff)
  20049. {
  20050. int n;
  20051. const int bytesLeft = readVariableLengthVal (src + 1, n);
  20052. size = jmin (sz + 1, n + 2 + bytesLeft);
  20053. data = (uint8*) juce_malloc (size);
  20054. *data = (uint8) byte;
  20055. memcpy (data + 1, src, size - 1);
  20056. }
  20057. else
  20058. {
  20059. size = getMessageLengthFromFirstByte ((uint8) byte);
  20060. *data = (uint8) byte;
  20061. if (size > 1)
  20062. {
  20063. data[1] = src[0];
  20064. if (size > 2)
  20065. data[2] = src[1];
  20066. }
  20067. }
  20068. numBytesUsed += size;
  20069. }
  20070. else
  20071. {
  20072. message = 0;
  20073. size = 0;
  20074. }
  20075. }
  20076. const MidiMessage& MidiMessage::operator= (const MidiMessage& other) throw()
  20077. {
  20078. if (this == &other)
  20079. return *this;
  20080. timeStamp = other.timeStamp;
  20081. size = other.size;
  20082. message = other.message;
  20083. if (data != (uint8*) &message)
  20084. juce_free (data);
  20085. if (other.data != (uint8*) &other.message)
  20086. {
  20087. data = (uint8*) juce_malloc (size);
  20088. memcpy (data, other.data, size);
  20089. }
  20090. else
  20091. {
  20092. data = (uint8*) &message;
  20093. }
  20094. return *this;
  20095. }
  20096. MidiMessage::~MidiMessage() throw()
  20097. {
  20098. if (data != (uint8*) &message)
  20099. juce_free (data);
  20100. }
  20101. int MidiMessage::getChannel() const throw()
  20102. {
  20103. if ((data[0] & 0xf0) != 0xf0)
  20104. return (data[0] & 0xf) + 1;
  20105. else
  20106. return 0;
  20107. }
  20108. bool MidiMessage::isForChannel (const int channel) const throw()
  20109. {
  20110. return ((data[0] & 0xf) == channel - 1)
  20111. && ((data[0] & 0xf0) != 0xf0);
  20112. }
  20113. void MidiMessage::setChannel (const int channel) throw()
  20114. {
  20115. if ((data[0] & 0xf0) != (uint8) 0xf0)
  20116. data[0] = (uint8) ((data[0] & (uint8)0xf0)
  20117. | (uint8)(channel - 1));
  20118. }
  20119. bool MidiMessage::isNoteOn() const throw()
  20120. {
  20121. return ((data[0] & 0xf0) == 0x90)
  20122. && (data[2] != 0);
  20123. }
  20124. bool MidiMessage::isNoteOff() const throw()
  20125. {
  20126. return ((data[0] & 0xf0) == 0x80)
  20127. || ((data[2] == 0) && ((data[0] & 0xf0) == 0x90));
  20128. }
  20129. bool MidiMessage::isNoteOnOrOff() const throw()
  20130. {
  20131. const int d = data[0] & 0xf0;
  20132. return (d == 0x90) || (d == 0x80);
  20133. }
  20134. int MidiMessage::getNoteNumber() const throw()
  20135. {
  20136. return data[1];
  20137. }
  20138. void MidiMessage::setNoteNumber (const int newNoteNumber) throw()
  20139. {
  20140. if (isNoteOnOrOff())
  20141. data[1] = (uint8) jlimit (0, 127, newNoteNumber);
  20142. }
  20143. uint8 MidiMessage::getVelocity() const throw()
  20144. {
  20145. if (isNoteOnOrOff())
  20146. return data[2];
  20147. else
  20148. return 0;
  20149. }
  20150. float MidiMessage::getFloatVelocity() const throw()
  20151. {
  20152. return getVelocity() * (1.0f / 127.0f);
  20153. }
  20154. void MidiMessage::setVelocity (const float newVelocity) throw()
  20155. {
  20156. if (isNoteOnOrOff())
  20157. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (newVelocity * 127.0f));
  20158. }
  20159. void MidiMessage::multiplyVelocity (const float scaleFactor) throw()
  20160. {
  20161. if (isNoteOnOrOff())
  20162. data[2] = (uint8) jlimit (0, 0x7f, roundFloatToInt (scaleFactor * data[2]));
  20163. }
  20164. bool MidiMessage::isAftertouch() const throw()
  20165. {
  20166. return (data[0] & 0xf0) == 0xa0;
  20167. }
  20168. int MidiMessage::getAfterTouchValue() const throw()
  20169. {
  20170. return data[2];
  20171. }
  20172. const MidiMessage MidiMessage::aftertouchChange (const int channel,
  20173. const int noteNum,
  20174. const int aftertouchValue) throw()
  20175. {
  20176. jassert (channel > 0 && channel <= 16);
  20177. jassert (((unsigned int) noteNum) <= 127);
  20178. jassert (((unsigned int) aftertouchValue) <= 127);
  20179. return MidiMessage (0xa0 | jlimit (0, 15, channel - 1),
  20180. noteNum & 0x7f,
  20181. aftertouchValue & 0x7f);
  20182. }
  20183. bool MidiMessage::isChannelPressure() const throw()
  20184. {
  20185. return (data[0] & 0xf0) == 0xd0;
  20186. }
  20187. int MidiMessage::getChannelPressureValue() const throw()
  20188. {
  20189. jassert (isChannelPressure());
  20190. return data[1];
  20191. }
  20192. const MidiMessage MidiMessage::channelPressureChange (const int channel,
  20193. const int pressure) throw()
  20194. {
  20195. jassert (channel > 0 && channel <= 16);
  20196. jassert (((unsigned int) pressure) <= 127);
  20197. return MidiMessage (0xd0 | jlimit (0, 15, channel - 1),
  20198. pressure & 0x7f);
  20199. }
  20200. bool MidiMessage::isProgramChange() const throw()
  20201. {
  20202. return (data[0] & 0xf0) == 0xc0;
  20203. }
  20204. int MidiMessage::getProgramChangeNumber() const throw()
  20205. {
  20206. return data[1];
  20207. }
  20208. const MidiMessage MidiMessage::programChange (const int channel,
  20209. const int programNumber) throw()
  20210. {
  20211. jassert (channel > 0 && channel <= 16);
  20212. return MidiMessage (0xc0 | jlimit (0, 15, channel - 1),
  20213. programNumber & 0x7f);
  20214. }
  20215. bool MidiMessage::isPitchWheel() const throw()
  20216. {
  20217. return (data[0] & 0xf0) == 0xe0;
  20218. }
  20219. int MidiMessage::getPitchWheelValue() const throw()
  20220. {
  20221. return data[1] | (data[2] << 7);
  20222. }
  20223. const MidiMessage MidiMessage::pitchWheel (const int channel,
  20224. const int position) throw()
  20225. {
  20226. jassert (channel > 0 && channel <= 16);
  20227. jassert (((unsigned int) position) <= 0x3fff);
  20228. return MidiMessage (0xe0 | jlimit (0, 15, channel - 1),
  20229. position & 127,
  20230. (position >> 7) & 127);
  20231. }
  20232. bool MidiMessage::isController() const throw()
  20233. {
  20234. return (data[0] & 0xf0) == 0xb0;
  20235. }
  20236. int MidiMessage::getControllerNumber() const throw()
  20237. {
  20238. jassert (isController());
  20239. return data[1];
  20240. }
  20241. int MidiMessage::getControllerValue() const throw()
  20242. {
  20243. jassert (isController());
  20244. return data[2];
  20245. }
  20246. const MidiMessage MidiMessage::controllerEvent (const int channel,
  20247. const int controllerType,
  20248. const int value) throw()
  20249. {
  20250. // the channel must be between 1 and 16 inclusive
  20251. jassert (channel > 0 && channel <= 16);
  20252. return MidiMessage (0xb0 | jlimit (0, 15, channel - 1),
  20253. controllerType & 127,
  20254. value & 127);
  20255. }
  20256. const MidiMessage MidiMessage::noteOn (const int channel,
  20257. const int noteNumber,
  20258. const float velocity) throw()
  20259. {
  20260. return noteOn (channel, noteNumber, (uint8)(velocity * 127.0f));
  20261. }
  20262. const MidiMessage MidiMessage::noteOn (const int channel,
  20263. const int noteNumber,
  20264. const uint8 velocity) throw()
  20265. {
  20266. jassert (channel > 0 && channel <= 16);
  20267. jassert (((unsigned int) noteNumber) <= 127);
  20268. return MidiMessage (0x90 | jlimit (0, 15, channel - 1),
  20269. noteNumber & 127,
  20270. jlimit (0, 127, roundFloatToInt (velocity)));
  20271. }
  20272. const MidiMessage MidiMessage::noteOff (const int channel,
  20273. const int noteNumber) throw()
  20274. {
  20275. jassert (channel > 0 && channel <= 16);
  20276. jassert (((unsigned int) noteNumber) <= 127);
  20277. return MidiMessage (0x80 | jlimit (0, 15, channel - 1), noteNumber & 127, 0);
  20278. }
  20279. const MidiMessage MidiMessage::allNotesOff (const int channel) throw()
  20280. {
  20281. jassert (channel > 0 && channel <= 16);
  20282. return controllerEvent (channel, 123, 0);
  20283. }
  20284. bool MidiMessage::isAllNotesOff() const throw()
  20285. {
  20286. return (data[0] & 0xf0) == 0xb0
  20287. && data[1] == 123;
  20288. }
  20289. const MidiMessage MidiMessage::allSoundOff (const int channel) throw()
  20290. {
  20291. return controllerEvent (channel, 120, 0);
  20292. }
  20293. bool MidiMessage::isAllSoundOff() const throw()
  20294. {
  20295. return (data[0] & 0xf0) == 0xb0
  20296. && data[1] == 120;
  20297. }
  20298. const MidiMessage MidiMessage::allControllersOff (const int channel) throw()
  20299. {
  20300. return controllerEvent (channel, 121, 0);
  20301. }
  20302. const MidiMessage MidiMessage::masterVolume (const float volume) throw()
  20303. {
  20304. const int vol = jlimit (0, 0x3fff, roundFloatToInt (volume * 0x4000));
  20305. uint8 buf[8];
  20306. buf[0] = 0xf0;
  20307. buf[1] = 0x7f;
  20308. buf[2] = 0x7f;
  20309. buf[3] = 0x04;
  20310. buf[4] = 0x01;
  20311. buf[5] = (uint8) (vol & 0x7f);
  20312. buf[6] = (uint8) (vol >> 7);
  20313. buf[7] = 0xf7;
  20314. return MidiMessage (buf, 8);
  20315. }
  20316. bool MidiMessage::isSysEx() const throw()
  20317. {
  20318. return *data == 0xf0;
  20319. }
  20320. const MidiMessage MidiMessage::createSysExMessage (const uint8* sysexData,
  20321. const int dataSize) throw()
  20322. {
  20323. MemoryBlock mm (dataSize + 2);
  20324. uint8* const m = (uint8*) mm.getData();
  20325. m[0] = 0xf0;
  20326. memcpy (m + 1, sysexData, dataSize);
  20327. m[dataSize + 1] = 0xf7;
  20328. return MidiMessage (m, dataSize + 2);
  20329. }
  20330. const uint8* MidiMessage::getSysExData() const throw()
  20331. {
  20332. return (isSysEx()) ? getRawData() + 1
  20333. : 0;
  20334. }
  20335. int MidiMessage::getSysExDataSize() const throw()
  20336. {
  20337. return (isSysEx()) ? size - 2
  20338. : 0;
  20339. }
  20340. bool MidiMessage::isMetaEvent() const throw()
  20341. {
  20342. return *data == 0xff;
  20343. }
  20344. bool MidiMessage::isActiveSense() const throw()
  20345. {
  20346. return *data == 0xfe;
  20347. }
  20348. int MidiMessage::getMetaEventType() const throw()
  20349. {
  20350. if (*data != 0xff)
  20351. return -1;
  20352. else
  20353. return data[1];
  20354. }
  20355. int MidiMessage::getMetaEventLength() const throw()
  20356. {
  20357. if (*data == 0xff)
  20358. {
  20359. int n;
  20360. return jmin (size - 2, readVariableLengthVal (data + 2, n));
  20361. }
  20362. return 0;
  20363. }
  20364. const uint8* MidiMessage::getMetaEventData() const throw()
  20365. {
  20366. int n;
  20367. const uint8* d = data + 2;
  20368. readVariableLengthVal (d, n);
  20369. return d + n;
  20370. }
  20371. bool MidiMessage::isTrackMetaEvent() const throw()
  20372. {
  20373. return getMetaEventType() == 0;
  20374. }
  20375. bool MidiMessage::isEndOfTrackMetaEvent() const throw()
  20376. {
  20377. return getMetaEventType() == 47;
  20378. }
  20379. bool MidiMessage::isTextMetaEvent() const throw()
  20380. {
  20381. const int t = getMetaEventType();
  20382. return t > 0 && t < 16;
  20383. }
  20384. const String MidiMessage::getTextFromTextMetaEvent() const throw()
  20385. {
  20386. return String ((const char*) getMetaEventData(),
  20387. getMetaEventLength());
  20388. }
  20389. bool MidiMessage::isTrackNameEvent() const throw()
  20390. {
  20391. return (data[1] == 3)
  20392. && (*data == 0xff);
  20393. }
  20394. bool MidiMessage::isTempoMetaEvent() const throw()
  20395. {
  20396. return (data[1] == 81)
  20397. && (*data == 0xff);
  20398. }
  20399. bool MidiMessage::isMidiChannelMetaEvent() const throw()
  20400. {
  20401. return (data[1] == 0x20)
  20402. && (*data == 0xff)
  20403. && (data[2] == 1);
  20404. }
  20405. int MidiMessage::getMidiChannelMetaEventChannel() const throw()
  20406. {
  20407. return data[3] + 1;
  20408. }
  20409. double MidiMessage::getTempoSecondsPerQuarterNote() const throw()
  20410. {
  20411. if (! isTempoMetaEvent())
  20412. return 0.0;
  20413. const uint8* const d = getMetaEventData();
  20414. return (((unsigned int) d[0] << 16)
  20415. | ((unsigned int) d[1] << 8)
  20416. | d[2])
  20417. / 1000000.0;
  20418. }
  20419. double MidiMessage::getTempoMetaEventTickLength (const short timeFormat) const throw()
  20420. {
  20421. if (timeFormat > 0)
  20422. {
  20423. if (! isTempoMetaEvent())
  20424. return 0.5 / timeFormat;
  20425. return getTempoSecondsPerQuarterNote() / timeFormat;
  20426. }
  20427. else
  20428. {
  20429. const int frameCode = (-timeFormat) >> 8;
  20430. double framesPerSecond;
  20431. switch (frameCode)
  20432. {
  20433. case 24: framesPerSecond = 24.0; break;
  20434. case 25: framesPerSecond = 25.0; break;
  20435. case 29: framesPerSecond = 29.97; break;
  20436. case 30: framesPerSecond = 30.0; break;
  20437. default: framesPerSecond = 30.0; break;
  20438. }
  20439. return (1.0 / framesPerSecond) / (timeFormat & 0xff);
  20440. }
  20441. }
  20442. const MidiMessage MidiMessage::tempoMetaEvent (int microsecondsPerQuarterNote) throw()
  20443. {
  20444. uint8 d[8];
  20445. d[0] = 0xff;
  20446. d[1] = 81;
  20447. d[2] = 3;
  20448. d[3] = (uint8) (microsecondsPerQuarterNote >> 16);
  20449. d[4] = (uint8) ((microsecondsPerQuarterNote >> 8) & 0xff);
  20450. d[5] = (uint8) (microsecondsPerQuarterNote & 0xff);
  20451. return MidiMessage (d, 6, 0.0);
  20452. }
  20453. bool MidiMessage::isTimeSignatureMetaEvent() const throw()
  20454. {
  20455. return (data[1] == 0x58)
  20456. && (*data == (uint8) 0xff);
  20457. }
  20458. void MidiMessage::getTimeSignatureInfo (int& numerator,
  20459. int& denominator) const throw()
  20460. {
  20461. if (isTimeSignatureMetaEvent())
  20462. {
  20463. const uint8* const d = getMetaEventData();
  20464. numerator = d[0];
  20465. denominator = 1 << d[1];
  20466. }
  20467. else
  20468. {
  20469. numerator = 4;
  20470. denominator = 4;
  20471. }
  20472. }
  20473. const MidiMessage MidiMessage::timeSignatureMetaEvent (const int numerator,
  20474. const int denominator) throw()
  20475. {
  20476. uint8 d[8];
  20477. d[0] = 0xff;
  20478. d[1] = 0x58;
  20479. d[2] = 0x04;
  20480. d[3] = (uint8) numerator;
  20481. int n = 1;
  20482. int powerOfTwo = 0;
  20483. while (n < denominator)
  20484. {
  20485. n <<= 1;
  20486. ++powerOfTwo;
  20487. }
  20488. d[4] = (uint8) powerOfTwo;
  20489. d[5] = 0x01;
  20490. d[6] = 96;
  20491. return MidiMessage (d, 7, 0.0);
  20492. }
  20493. const MidiMessage MidiMessage::midiChannelMetaEvent (const int channel) throw()
  20494. {
  20495. uint8 d[8];
  20496. d[0] = 0xff;
  20497. d[1] = 0x20;
  20498. d[2] = 0x01;
  20499. d[3] = (uint8) jlimit (0, 0xff, channel - 1);
  20500. return MidiMessage (d, 4, 0.0);
  20501. }
  20502. bool MidiMessage::isKeySignatureMetaEvent() const throw()
  20503. {
  20504. return getMetaEventType() == 89;
  20505. }
  20506. int MidiMessage::getKeySignatureNumberOfSharpsOrFlats() const throw()
  20507. {
  20508. return (int) *getMetaEventData();
  20509. }
  20510. const MidiMessage MidiMessage::endOfTrack() throw()
  20511. {
  20512. return MidiMessage (0xff, 0x2f, 0, 0.0);
  20513. }
  20514. bool MidiMessage::isSongPositionPointer() const throw()
  20515. {
  20516. return *data == 0xf2;
  20517. }
  20518. int MidiMessage::getSongPositionPointerMidiBeat() const throw()
  20519. {
  20520. return data[1] | (data[2] << 7);
  20521. }
  20522. const MidiMessage MidiMessage::songPositionPointer (const int positionInMidiBeats) throw()
  20523. {
  20524. return MidiMessage (0xf2,
  20525. positionInMidiBeats & 127,
  20526. (positionInMidiBeats >> 7) & 127);
  20527. }
  20528. bool MidiMessage::isMidiStart() const throw()
  20529. {
  20530. return *data == 0xfa;
  20531. }
  20532. const MidiMessage MidiMessage::midiStart() throw()
  20533. {
  20534. return MidiMessage (0xfa);
  20535. }
  20536. bool MidiMessage::isMidiContinue() const throw()
  20537. {
  20538. return *data == 0xfb;
  20539. }
  20540. const MidiMessage MidiMessage::midiContinue() throw()
  20541. {
  20542. return MidiMessage (0xfb);
  20543. }
  20544. bool MidiMessage::isMidiStop() const throw()
  20545. {
  20546. return *data == 0xfc;
  20547. }
  20548. const MidiMessage MidiMessage::midiStop() throw()
  20549. {
  20550. return MidiMessage (0xfc);
  20551. }
  20552. bool MidiMessage::isMidiClock() const throw()
  20553. {
  20554. return *data == 0xf8;
  20555. }
  20556. const MidiMessage MidiMessage::midiClock() throw()
  20557. {
  20558. return MidiMessage (0xf8);
  20559. }
  20560. bool MidiMessage::isQuarterFrame() const throw()
  20561. {
  20562. return *data == 0xf1;
  20563. }
  20564. int MidiMessage::getQuarterFrameSequenceNumber() const throw()
  20565. {
  20566. return ((int) data[1]) >> 4;
  20567. }
  20568. int MidiMessage::getQuarterFrameValue() const throw()
  20569. {
  20570. return ((int) data[1]) & 0x0f;
  20571. }
  20572. const MidiMessage MidiMessage::quarterFrame (const int sequenceNumber,
  20573. const int value) throw()
  20574. {
  20575. return MidiMessage (0xf1, (sequenceNumber << 4) | value);
  20576. }
  20577. bool MidiMessage::isFullFrame() const throw()
  20578. {
  20579. return data[0] == 0xf0
  20580. && data[1] == 0x7f
  20581. && size >= 10
  20582. && data[3] == 0x01
  20583. && data[4] == 0x01;
  20584. }
  20585. void MidiMessage::getFullFrameParameters (int& hours,
  20586. int& minutes,
  20587. int& seconds,
  20588. int& frames,
  20589. MidiMessage::SmpteTimecodeType& timecodeType) const throw()
  20590. {
  20591. jassert (isFullFrame());
  20592. timecodeType = (SmpteTimecodeType) (data[5] >> 5);
  20593. hours = data[5] & 0x1f;
  20594. minutes = data[6];
  20595. seconds = data[7];
  20596. frames = data[8];
  20597. }
  20598. const MidiMessage MidiMessage::fullFrame (const int hours,
  20599. const int minutes,
  20600. const int seconds,
  20601. const int frames,
  20602. MidiMessage::SmpteTimecodeType timecodeType)
  20603. {
  20604. uint8 d[10];
  20605. d[0] = 0xf0;
  20606. d[1] = 0x7f;
  20607. d[2] = 0x7f;
  20608. d[3] = 0x01;
  20609. d[4] = 0x01;
  20610. d[5] = (uint8) ((hours & 0x01f) | (timecodeType << 5));
  20611. d[6] = (uint8) minutes;
  20612. d[7] = (uint8) seconds;
  20613. d[8] = (uint8) frames;
  20614. d[9] = 0xf7;
  20615. return MidiMessage (d, 10, 0.0);
  20616. }
  20617. bool MidiMessage::isMidiMachineControlMessage() const throw()
  20618. {
  20619. return data[0] == 0xf0
  20620. && data[1] == 0x7f
  20621. && data[3] == 0x06
  20622. && size > 5;
  20623. }
  20624. MidiMessage::MidiMachineControlCommand MidiMessage::getMidiMachineControlCommand() const throw()
  20625. {
  20626. jassert (isMidiMachineControlMessage());
  20627. return (MidiMachineControlCommand) data[4];
  20628. }
  20629. const MidiMessage MidiMessage::midiMachineControlCommand (MidiMessage::MidiMachineControlCommand command)
  20630. {
  20631. uint8 d[6];
  20632. d[0] = 0xf0;
  20633. d[1] = 0x7f;
  20634. d[2] = 0x00;
  20635. d[3] = 0x06;
  20636. d[4] = (uint8) command;
  20637. d[5] = 0xf7;
  20638. return MidiMessage (d, 6, 0.0);
  20639. }
  20640. bool MidiMessage::isMidiMachineControlGoto (int& hours,
  20641. int& minutes,
  20642. int& seconds,
  20643. int& frames) const throw()
  20644. {
  20645. if (size >= 12
  20646. && data[0] == 0xf0
  20647. && data[1] == 0x7f
  20648. && data[3] == 0x06
  20649. && data[4] == 0x44
  20650. && data[5] == 0x06
  20651. && data[6] == 0x01)
  20652. {
  20653. hours = data[7] % 24; // (that some machines send out hours > 24)
  20654. minutes = data[8];
  20655. seconds = data[9];
  20656. frames = data[10];
  20657. return true;
  20658. }
  20659. return false;
  20660. }
  20661. const MidiMessage MidiMessage::midiMachineControlGoto (int hours,
  20662. int minutes,
  20663. int seconds,
  20664. int frames)
  20665. {
  20666. uint8 d[12];
  20667. d[0] = 0xf0;
  20668. d[1] = 0x7f;
  20669. d[2] = 0x00;
  20670. d[3] = 0x06;
  20671. d[4] = 0x44;
  20672. d[5] = 0x06;
  20673. d[6] = 0x01;
  20674. d[7] = (uint8) hours;
  20675. d[8] = (uint8) minutes;
  20676. d[9] = (uint8) seconds;
  20677. d[10] = (uint8) frames;
  20678. d[11] = 0xf7;
  20679. return MidiMessage (d, 12, 0.0);
  20680. }
  20681. const String MidiMessage::getMidiNoteName (int note,
  20682. bool useSharps,
  20683. bool includeOctaveNumber,
  20684. int octaveNumForMiddleC) throw()
  20685. {
  20686. static const char* const sharpNoteNames[] = { "C", "C#", "D", "D#", "E",
  20687. "F", "F#", "G", "G#", "A",
  20688. "A#", "B" };
  20689. static const char* const flatNoteNames[] = { "C", "Db", "D", "Eb", "E",
  20690. "F", "Gb", "G", "Ab", "A",
  20691. "Bb", "B" };
  20692. if (((unsigned int) note) < 128)
  20693. {
  20694. const String s ((useSharps) ? sharpNoteNames [note % 12]
  20695. : flatNoteNames [note % 12]);
  20696. if (includeOctaveNumber)
  20697. return s + String (note / 12 + (octaveNumForMiddleC - 5));
  20698. else
  20699. return s;
  20700. }
  20701. return String::empty;
  20702. }
  20703. const double MidiMessage::getMidiNoteInHertz (int noteNumber) throw()
  20704. {
  20705. noteNumber -= 12 * 6 + 9; // now 0 = A440
  20706. return 440.0 * pow (2.0, noteNumber / 12.0);
  20707. }
  20708. const String MidiMessage::getGMInstrumentName (int n) throw()
  20709. {
  20710. const char *names[] =
  20711. {
  20712. "Acoustic Grand Piano", "Bright Acoustic Piano", "Electric Grand Piano", "Honky-tonk Piano",
  20713. "Electric Piano 1", "Electric Piano 2", "Harpsichord", "Clavinet", "Celesta", "Glockenspiel",
  20714. "Music Box", "Vibraphone", "Marimba", "Xylophone", "Tubular Bells", "Dulcimer", "Drawbar Organ",
  20715. "Percussive Organ", "Rock Organ", "Church Organ", "Reed Organ", "Accordion", "Harmonica",
  20716. "Tango Accordion", "Acoustic Guitar (nylon)", "Acoustic Guitar (steel)", "Electric Guitar (jazz)",
  20717. "Electric Guitar (clean)", "Electric Guitar (mute)", "Overdriven Guitar", "Distortion Guitar",
  20718. "Guitar Harmonics", "Acoustic Bass", "Electric Bass (finger)", "Electric Bass (pick)",
  20719. "Fretless Bass", "Slap Bass 1", "Slap Bass 2", "Synth Bass 1", "Synth Bass 2", "Violin",
  20720. "Viola", "Cello", "Contrabass", "Tremolo Strings", "Pizzicato Strings", "Orchestral Harp",
  20721. "Timpani", "String Ensemble 1", "String Ensemble 2", "SynthStrings 1", "SynthStrings 2",
  20722. "Choir Aahs", "Voice Oohs", "Synth Voice", "Orchestra Hit", "Trumpet", "Trombone", "Tuba",
  20723. "Muted Trumpet", "French Horn", "Brass Section", "SynthBrass 1", "SynthBrass 2", "Soprano Sax",
  20724. "Alto Sax", "Tenor Sax", "Baritone Sax", "Oboe", "English Horn", "Bassoon", "Clarinet",
  20725. "Piccolo", "Flute", "Recorder", "Pan Flute", "Blown Bottle", "Shakuhachi", "Whistle",
  20726. "Ocarina", "Lead 1 (square)", "Lead 2 (sawtooth)", "Lead 3 (calliope)", "Lead 4 (chiff)",
  20727. "Lead 5 (charang)", "Lead 6 (voice)", "Lead 7 (fifths)", "Lead 8 (bass+lead)", "Pad 1 (new age)",
  20728. "Pad 2 (warm)", "Pad 3 (polysynth)", "Pad 4 (choir)", "Pad 5 (bowed)", "Pad 6 (metallic)",
  20729. "Pad 7 (halo)", "Pad 8 (sweep)", "FX 1 (rain)", "FX 2 (soundtrack)", "FX 3 (crystal)",
  20730. "FX 4 (atmosphere)", "FX 5 (brightness)", "FX 6 (goblins)", "FX 7 (echoes)", "FX 8 (sci-fi)",
  20731. "Sitar", "Banjo", "Shamisen", "Koto", "Kalimba", "Bag pipe", "Fiddle", "Shanai", "Tinkle Bell",
  20732. "Agogo", "Steel Drums", "Woodblock", "Taiko Drum", "Melodic Tom", "Synth Drum", "Reverse Cymbal",
  20733. "Guitar Fret Noise", "Breath Noise", "Seashore", "Bird Tweet", "Telephone Ring", "Helicopter",
  20734. "Applause", "Gunshot"
  20735. };
  20736. return (((unsigned int) n) < 128) ? names[n]
  20737. : (const char*)0;
  20738. }
  20739. const String MidiMessage::getGMInstrumentBankName (int n) throw()
  20740. {
  20741. const char* names[] =
  20742. {
  20743. "Piano", "Chromatic Percussion", "Organ", "Guitar",
  20744. "Bass", "Strings", "Ensemble", "Brass",
  20745. "Reed", "Pipe", "Synth Lead", "Synth Pad",
  20746. "Synth Effects", "Ethnic", "Percussive", "Sound Effects"
  20747. };
  20748. return (((unsigned int) n) <= 15) ? names[n]
  20749. : (const char*)0;
  20750. }
  20751. const String MidiMessage::getRhythmInstrumentName (int n) throw()
  20752. {
  20753. const char* names[] =
  20754. {
  20755. "Acoustic Bass Drum", "Bass Drum 1", "Side Stick", "Acoustic Snare",
  20756. "Hand Clap", "Electric Snare", "Low Floor Tom", "Closed Hi-Hat", "High Floor Tom",
  20757. "Pedal Hi-Hat", "Low Tom", "Open Hi-Hat", "Low-Mid Tom", "Hi-Mid Tom", "Crash Cymbal 1",
  20758. "High Tom", "Ride Cymbal 1", "Chinese Cymbal", "Ride Bell", "Tambourine", "Splash Cymbal",
  20759. "Cowbell", "Crash Cymbal 2", "Vibraslap", "Ride Cymbal 2", "Hi Bongo", "Low Bongo",
  20760. "Mute Hi Conga", "Open Hi Conga", "Low Conga", "High Timbale", "Low Timbale", "High Agogo",
  20761. "Low Agogo", "Cabasa", "Maracas", "Short Whistle", "Long Whistle", "Short Guiro",
  20762. "Long Guiro", "Claves", "Hi Wood Block", "Low Wood Block", "Mute Cuica", "Open Cuica",
  20763. "Mute Triangle", "Open Triangle"
  20764. };
  20765. return (n >= 35 && n <= 81) ? names [n - 35]
  20766. : (const char*)0;
  20767. }
  20768. const String MidiMessage::getControllerName (int n) throw()
  20769. {
  20770. const char* names[] =
  20771. {
  20772. "Bank Select", "Modulation Wheel (coarse)", "Breath controller (coarse)",
  20773. 0, "Foot Pedal (coarse)", "Portamento Time (coarse)",
  20774. "Data Entry (coarse)", "Volume (coarse)", "Balance (coarse)",
  20775. 0, "Pan position (coarse)", "Expression (coarse)", "Effect Control 1 (coarse)",
  20776. "Effect Control 2 (coarse)", 0, 0, "General Purpose Slider 1", "General Purpose Slider 2",
  20777. "General Purpose Slider 3", "General Purpose Slider 4", 0, 0, 0, 0, 0, 0, 0, 0,
  20778. 0, 0, 0, 0, "Bank Select (fine)", "Modulation Wheel (fine)", "Breath controller (fine)",
  20779. 0, "Foot Pedal (fine)", "Portamento Time (fine)", "Data Entry (fine)", "Volume (fine)",
  20780. "Balance (fine)", 0, "Pan position (fine)", "Expression (fine)", "Effect Control 1 (fine)",
  20781. "Effect Control 2 (fine)", 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  20782. "Hold Pedal (on/off)", "Portamento (on/off)", "Sustenuto Pedal (on/off)", "Soft Pedal (on/off)",
  20783. "Legato Pedal (on/off)", "Hold 2 Pedal (on/off)", "Sound Variation", "Sound Timbre",
  20784. "Sound Release Time", "Sound Attack Time", "Sound Brightness", "Sound Control 6",
  20785. "Sound Control 7", "Sound Control 8", "Sound Control 9", "Sound Control 10",
  20786. "General Purpose Button 1 (on/off)", "General Purpose Button 2 (on/off)",
  20787. "General Purpose Button 3 (on/off)", "General Purpose Button 4 (on/off)",
  20788. 0, 0, 0, 0, 0, 0, 0, "Reverb Level", "Tremolo Level", "Chorus Level", "Celeste Level",
  20789. "Phaser Level", "Data Button increment", "Data Button decrement", "Non-registered Parameter (fine)",
  20790. "Non-registered Parameter (coarse)", "Registered Parameter (fine)", "Registered Parameter (coarse)",
  20791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, "All Sound Off", "All Controllers Off",
  20792. "Local Keyboard (on/off)", "All Notes Off", "Omni Mode Off", "Omni Mode On", "Mono Operation",
  20793. "Poly Operation"
  20794. };
  20795. return (((unsigned int) n) < 128) ? names[n]
  20796. : (const char*)0;
  20797. }
  20798. END_JUCE_NAMESPACE
  20799. /********* End of inlined file: juce_MidiMessage.cpp *********/
  20800. /********* Start of inlined file: juce_MidiMessageCollector.cpp *********/
  20801. BEGIN_JUCE_NAMESPACE
  20802. MidiMessageCollector::MidiMessageCollector()
  20803. : lastCallbackTime (0),
  20804. sampleRate (44100.0001)
  20805. {
  20806. }
  20807. MidiMessageCollector::~MidiMessageCollector()
  20808. {
  20809. }
  20810. void MidiMessageCollector::reset (const double sampleRate_)
  20811. {
  20812. jassert (sampleRate_ > 0);
  20813. const ScopedLock sl (midiCallbackLock);
  20814. sampleRate = sampleRate_;
  20815. incomingMessages.clear();
  20816. lastCallbackTime = Time::getMillisecondCounterHiRes();
  20817. }
  20818. void MidiMessageCollector::addMessageToQueue (const MidiMessage& message)
  20819. {
  20820. // you need to call reset() to set the correct sample rate before using this object
  20821. jassert (sampleRate != 44100.0001);
  20822. // the messages that come in here need to be time-stamped correctly - see MidiInput
  20823. // for details of what the number should be.
  20824. jassert (message.getTimeStamp() != 0);
  20825. const ScopedLock sl (midiCallbackLock);
  20826. const int sampleNumber
  20827. = (int) ((message.getTimeStamp() - 0.001 * lastCallbackTime) * sampleRate);
  20828. incomingMessages.addEvent (message, sampleNumber);
  20829. // if the messages don't get used for over a second, we'd better
  20830. // get rid of any old ones to avoid the queue getting too big
  20831. if (sampleNumber > sampleRate)
  20832. incomingMessages.clear (0, sampleNumber - (int) sampleRate);
  20833. }
  20834. void MidiMessageCollector::removeNextBlockOfMessages (MidiBuffer& destBuffer,
  20835. const int numSamples)
  20836. {
  20837. // you need to call reset() to set the correct sample rate before using this object
  20838. jassert (sampleRate != 44100.0001);
  20839. const double timeNow = Time::getMillisecondCounterHiRes();
  20840. const double msElapsed = timeNow - lastCallbackTime;
  20841. const ScopedLock sl (midiCallbackLock);
  20842. lastCallbackTime = timeNow;
  20843. if (! incomingMessages.isEmpty())
  20844. {
  20845. int numSourceSamples = jmax (1, roundDoubleToInt (msElapsed * 0.001 * sampleRate));
  20846. int startSample = 0;
  20847. int scale = 1 << 16;
  20848. const uint8* midiData;
  20849. int numBytes, samplePosition;
  20850. MidiBuffer::Iterator iter (incomingMessages);
  20851. if (numSourceSamples > numSamples)
  20852. {
  20853. // if our list of events is longer than the buffer we're being
  20854. // asked for, scale them down to squeeze them all in..
  20855. const int maxBlockLengthToUse = numSamples << 5;
  20856. if (numSourceSamples > maxBlockLengthToUse)
  20857. {
  20858. startSample = numSourceSamples - maxBlockLengthToUse;
  20859. numSourceSamples = maxBlockLengthToUse;
  20860. iter.setNextSamplePosition (startSample);
  20861. }
  20862. scale = (numSamples << 10) / numSourceSamples;
  20863. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  20864. {
  20865. samplePosition = ((samplePosition - startSample) * scale) >> 10;
  20866. destBuffer.addEvent (midiData, numBytes,
  20867. jlimit (0, numSamples - 1, samplePosition));
  20868. }
  20869. }
  20870. else
  20871. {
  20872. // if our event list is shorter than the number we need, put them
  20873. // towards the end of the buffer
  20874. startSample = numSamples - numSourceSamples;
  20875. while (iter.getNextEvent (midiData, numBytes, samplePosition))
  20876. {
  20877. destBuffer.addEvent (midiData, numBytes,
  20878. jlimit (0, numSamples - 1, samplePosition + startSample));
  20879. }
  20880. }
  20881. incomingMessages.clear();
  20882. }
  20883. }
  20884. void MidiMessageCollector::handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity)
  20885. {
  20886. MidiMessage m (MidiMessage::noteOn (midiChannel, midiNoteNumber, velocity));
  20887. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  20888. addMessageToQueue (m);
  20889. }
  20890. void MidiMessageCollector::handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber)
  20891. {
  20892. MidiMessage m (MidiMessage::noteOff (midiChannel, midiNoteNumber));
  20893. m.setTimeStamp (Time::getMillisecondCounterHiRes() * 0.001);
  20894. addMessageToQueue (m);
  20895. }
  20896. void MidiMessageCollector::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  20897. {
  20898. addMessageToQueue (message);
  20899. }
  20900. END_JUCE_NAMESPACE
  20901. /********* End of inlined file: juce_MidiMessageCollector.cpp *********/
  20902. /********* Start of inlined file: juce_MidiMessageSequence.cpp *********/
  20903. BEGIN_JUCE_NAMESPACE
  20904. MidiMessageSequence::MidiMessageSequence()
  20905. {
  20906. }
  20907. MidiMessageSequence::MidiMessageSequence (const MidiMessageSequence& other)
  20908. {
  20909. list.ensureStorageAllocated (other.list.size());
  20910. for (int i = 0; i < other.list.size(); ++i)
  20911. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  20912. }
  20913. const MidiMessageSequence& MidiMessageSequence::operator= (const MidiMessageSequence& other)
  20914. {
  20915. if (this != &other)
  20916. {
  20917. clear();
  20918. for (int i = 0; i < other.list.size(); ++i)
  20919. list.add (new MidiEventHolder (other.list.getUnchecked(i)->message));
  20920. }
  20921. return *this;
  20922. }
  20923. MidiMessageSequence::~MidiMessageSequence()
  20924. {
  20925. }
  20926. void MidiMessageSequence::clear()
  20927. {
  20928. list.clear();
  20929. }
  20930. int MidiMessageSequence::getNumEvents() const
  20931. {
  20932. return list.size();
  20933. }
  20934. MidiMessageSequence::MidiEventHolder* MidiMessageSequence::getEventPointer (const int index) const
  20935. {
  20936. return list [index];
  20937. }
  20938. double MidiMessageSequence::getTimeOfMatchingKeyUp (const int index) const
  20939. {
  20940. const MidiEventHolder* const meh = list [index];
  20941. if (meh != 0 && meh->noteOffObject != 0)
  20942. return meh->noteOffObject->message.getTimeStamp();
  20943. else
  20944. return 0.0;
  20945. }
  20946. int MidiMessageSequence::getIndexOfMatchingKeyUp (const int index) const
  20947. {
  20948. const MidiEventHolder* const meh = list [index];
  20949. return (meh != 0) ? list.indexOf (meh->noteOffObject) : -1;
  20950. }
  20951. int MidiMessageSequence::getIndexOf (MidiEventHolder* const event) const
  20952. {
  20953. return list.indexOf (event);
  20954. }
  20955. int MidiMessageSequence::getNextIndexAtTime (const double timeStamp) const
  20956. {
  20957. const int numEvents = list.size();
  20958. int i;
  20959. for (i = 0; i < numEvents; ++i)
  20960. if (list.getUnchecked(i)->message.getTimeStamp() >= timeStamp)
  20961. break;
  20962. return i;
  20963. }
  20964. double MidiMessageSequence::getStartTime() const
  20965. {
  20966. if (list.size() > 0)
  20967. return list.getUnchecked(0)->message.getTimeStamp();
  20968. else
  20969. return 0;
  20970. }
  20971. double MidiMessageSequence::getEndTime() const
  20972. {
  20973. if (list.size() > 0)
  20974. return list.getLast()->message.getTimeStamp();
  20975. else
  20976. return 0;
  20977. }
  20978. double MidiMessageSequence::getEventTime (const int index) const
  20979. {
  20980. if (((unsigned int) index) < (unsigned int) list.size())
  20981. return list.getUnchecked (index)->message.getTimeStamp();
  20982. return 0.0;
  20983. }
  20984. void MidiMessageSequence::addEvent (const MidiMessage& newMessage,
  20985. double timeAdjustment)
  20986. {
  20987. MidiEventHolder* const newOne = new MidiEventHolder (newMessage);
  20988. timeAdjustment += newMessage.getTimeStamp();
  20989. newOne->message.setTimeStamp (timeAdjustment);
  20990. int i;
  20991. for (i = list.size(); --i >= 0;)
  20992. if (list.getUnchecked(i)->message.getTimeStamp() <= timeAdjustment)
  20993. break;
  20994. list.insert (i + 1, newOne);
  20995. }
  20996. void MidiMessageSequence::deleteEvent (const int index,
  20997. const bool deleteMatchingNoteUp)
  20998. {
  20999. if (((unsigned int) index) < (unsigned int) list.size())
  21000. {
  21001. if (deleteMatchingNoteUp)
  21002. deleteEvent (getIndexOfMatchingKeyUp (index), false);
  21003. list.remove (index);
  21004. }
  21005. }
  21006. void MidiMessageSequence::addSequence (const MidiMessageSequence& other,
  21007. double timeAdjustment,
  21008. double firstAllowableTime,
  21009. double endOfAllowableDestTimes)
  21010. {
  21011. firstAllowableTime -= timeAdjustment;
  21012. endOfAllowableDestTimes -= timeAdjustment;
  21013. for (int i = 0; i < other.list.size(); ++i)
  21014. {
  21015. const MidiMessage& m = other.list.getUnchecked(i)->message;
  21016. const double t = m.getTimeStamp();
  21017. if (t >= firstAllowableTime && t < endOfAllowableDestTimes)
  21018. {
  21019. MidiEventHolder* const newOne = new MidiEventHolder (m);
  21020. newOne->message.setTimeStamp (timeAdjustment + t);
  21021. list.add (newOne);
  21022. }
  21023. }
  21024. sort();
  21025. }
  21026. int MidiMessageSequence::compareElements (const MidiMessageSequence::MidiEventHolder* const first,
  21027. const MidiMessageSequence::MidiEventHolder* const second) throw()
  21028. {
  21029. const double diff = first->message.getTimeStamp()
  21030. - second->message.getTimeStamp();
  21031. return (diff == 0) ? 0
  21032. : ((diff > 0) ? 1
  21033. : -1);
  21034. }
  21035. void MidiMessageSequence::sort()
  21036. {
  21037. list.sort (*this, true);
  21038. }
  21039. void MidiMessageSequence::updateMatchedPairs()
  21040. {
  21041. for (int i = 0; i < list.size(); ++i)
  21042. {
  21043. const MidiMessage& m1 = list.getUnchecked(i)->message;
  21044. if (m1.isNoteOn())
  21045. {
  21046. list.getUnchecked(i)->noteOffObject = 0;
  21047. const int note = m1.getNoteNumber();
  21048. const int chan = m1.getChannel();
  21049. const int len = list.size();
  21050. for (int j = i + 1; j < len; ++j)
  21051. {
  21052. const MidiMessage& m = list.getUnchecked(j)->message;
  21053. if (m.getNoteNumber() == note && m.getChannel() == chan)
  21054. {
  21055. if (m.isNoteOff())
  21056. {
  21057. list.getUnchecked(i)->noteOffObject = list[j];
  21058. break;
  21059. }
  21060. else if (m.isNoteOn())
  21061. {
  21062. list.insert (j, new MidiEventHolder (MidiMessage::noteOff (chan, note)));
  21063. list.getUnchecked(j)->message.setTimeStamp (m.getTimeStamp());
  21064. list.getUnchecked(i)->noteOffObject = list[j];
  21065. break;
  21066. }
  21067. }
  21068. }
  21069. }
  21070. }
  21071. }
  21072. void MidiMessageSequence::addTimeToMessages (const double delta)
  21073. {
  21074. for (int i = list.size(); --i >= 0;)
  21075. list.getUnchecked (i)->message.setTimeStamp (list.getUnchecked (i)->message.getTimeStamp()
  21076. + delta);
  21077. }
  21078. void MidiMessageSequence::extractMidiChannelMessages (const int channelNumberToExtract,
  21079. MidiMessageSequence& destSequence,
  21080. const bool alsoIncludeMetaEvents) const
  21081. {
  21082. for (int i = 0; i < list.size(); ++i)
  21083. {
  21084. const MidiMessage& mm = list.getUnchecked(i)->message;
  21085. if (mm.isForChannel (channelNumberToExtract)
  21086. || (alsoIncludeMetaEvents && mm.isMetaEvent()))
  21087. {
  21088. destSequence.addEvent (mm);
  21089. }
  21090. }
  21091. }
  21092. void MidiMessageSequence::extractSysExMessages (MidiMessageSequence& destSequence) const
  21093. {
  21094. for (int i = 0; i < list.size(); ++i)
  21095. {
  21096. const MidiMessage& mm = list.getUnchecked(i)->message;
  21097. if (mm.isSysEx())
  21098. destSequence.addEvent (mm);
  21099. }
  21100. }
  21101. void MidiMessageSequence::deleteMidiChannelMessages (const int channelNumberToRemove)
  21102. {
  21103. for (int i = list.size(); --i >= 0;)
  21104. if (list.getUnchecked(i)->message.isForChannel (channelNumberToRemove))
  21105. list.remove(i);
  21106. }
  21107. void MidiMessageSequence::deleteSysExMessages()
  21108. {
  21109. for (int i = list.size(); --i >= 0;)
  21110. if (list.getUnchecked(i)->message.isSysEx())
  21111. list.remove(i);
  21112. }
  21113. void MidiMessageSequence::createControllerUpdatesForTime (const int channelNumber,
  21114. const double time,
  21115. OwnedArray<MidiMessage>& dest)
  21116. {
  21117. bool doneProg = false;
  21118. bool donePitchWheel = false;
  21119. Array <int> doneControllers (32);
  21120. for (int i = list.size(); --i >= 0;)
  21121. {
  21122. const MidiMessage& mm = list.getUnchecked(i)->message;
  21123. if (mm.isForChannel (channelNumber)
  21124. && mm.getTimeStamp() <= time)
  21125. {
  21126. if (mm.isProgramChange())
  21127. {
  21128. if (! doneProg)
  21129. {
  21130. dest.add (new MidiMessage (mm, 0.0));
  21131. doneProg = true;
  21132. }
  21133. }
  21134. else if (mm.isController())
  21135. {
  21136. if (! doneControllers.contains (mm.getControllerNumber()))
  21137. {
  21138. dest.add (new MidiMessage (mm, 0.0));
  21139. doneControllers.add (mm.getControllerNumber());
  21140. }
  21141. }
  21142. else if (mm.isPitchWheel())
  21143. {
  21144. if (! donePitchWheel)
  21145. {
  21146. dest.add (new MidiMessage (mm, 0.0));
  21147. donePitchWheel = true;
  21148. }
  21149. }
  21150. }
  21151. }
  21152. }
  21153. MidiMessageSequence::MidiEventHolder::MidiEventHolder (const MidiMessage& message_)
  21154. : message (message_),
  21155. noteOffObject (0)
  21156. {
  21157. }
  21158. MidiMessageSequence::MidiEventHolder::~MidiEventHolder()
  21159. {
  21160. }
  21161. END_JUCE_NAMESPACE
  21162. /********* End of inlined file: juce_MidiMessageSequence.cpp *********/
  21163. /********* Start of inlined file: juce_AudioPluginFormat.cpp *********/
  21164. BEGIN_JUCE_NAMESPACE
  21165. AudioPluginFormat::AudioPluginFormat() throw()
  21166. {
  21167. }
  21168. AudioPluginFormat::~AudioPluginFormat()
  21169. {
  21170. }
  21171. END_JUCE_NAMESPACE
  21172. /********* End of inlined file: juce_AudioPluginFormat.cpp *********/
  21173. /********* Start of inlined file: juce_AudioPluginFormatManager.cpp *********/
  21174. BEGIN_JUCE_NAMESPACE
  21175. AudioPluginFormatManager::AudioPluginFormatManager() throw()
  21176. {
  21177. }
  21178. AudioPluginFormatManager::~AudioPluginFormatManager() throw()
  21179. {
  21180. }
  21181. juce_ImplementSingleton_SingleThreaded (AudioPluginFormatManager);
  21182. void AudioPluginFormatManager::addDefaultFormats()
  21183. {
  21184. #ifdef JUCE_DEBUG
  21185. // you should only call this method once!
  21186. for (int i = formats.size(); --i >= 0;)
  21187. {
  21188. #if JUCE_PLUGINHOST_VST
  21189. jassert (dynamic_cast <VSTPluginFormat*> (formats[i]) == 0);
  21190. #endif
  21191. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  21192. jassert (dynamic_cast <AudioUnitPluginFormat*> (formats[i]) == 0);
  21193. #endif
  21194. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  21195. jassert (dynamic_cast <DirectXPluginFormat*> (formats[i]) == 0);
  21196. #endif
  21197. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  21198. jassert (dynamic_cast <LADSPAPluginFormat*> (formats[i]) == 0);
  21199. #endif
  21200. }
  21201. #endif
  21202. #if JUCE_PLUGINHOST_VST
  21203. formats.add (new VSTPluginFormat());
  21204. #endif
  21205. #if JUCE_PLUGINHOST_AU && JUCE_MAC
  21206. formats.add (new AudioUnitPluginFormat());
  21207. #endif
  21208. #if JUCE_PLUGINHOST_DX && JUCE_WIN32
  21209. formats.add (new DirectXPluginFormat());
  21210. #endif
  21211. #if JUCE_PLUGINHOST_LADSPA && JUCE_LINUX
  21212. formats.add (new LADSPAPluginFormat());
  21213. #endif
  21214. }
  21215. int AudioPluginFormatManager::getNumFormats() throw()
  21216. {
  21217. return formats.size();
  21218. }
  21219. AudioPluginFormat* AudioPluginFormatManager::getFormat (const int index) throw()
  21220. {
  21221. return formats [index];
  21222. }
  21223. void AudioPluginFormatManager::addFormat (AudioPluginFormat* const format) throw()
  21224. {
  21225. formats.add (format);
  21226. }
  21227. AudioPluginInstance* AudioPluginFormatManager::createPluginInstance (const PluginDescription& description,
  21228. String& errorMessage) const
  21229. {
  21230. AudioPluginInstance* result = 0;
  21231. for (int i = 0; i < formats.size(); ++i)
  21232. {
  21233. result = formats.getUnchecked(i)->createInstanceFromDescription (description);
  21234. if (result != 0)
  21235. break;
  21236. }
  21237. if (result == 0)
  21238. {
  21239. if (description.file != File::nonexistent && ! description.file.exists())
  21240. errorMessage = TRANS ("This plug-in file no longer exists");
  21241. else
  21242. errorMessage = TRANS ("This plug-in failed to load correctly");
  21243. }
  21244. return result;
  21245. }
  21246. END_JUCE_NAMESPACE
  21247. /********* End of inlined file: juce_AudioPluginFormatManager.cpp *********/
  21248. /********* Start of inlined file: juce_AudioPluginInstance.cpp *********/
  21249. #define JUCE_PLUGIN_HOST 1
  21250. BEGIN_JUCE_NAMESPACE
  21251. AudioPluginInstance::AudioPluginInstance()
  21252. {
  21253. }
  21254. AudioPluginInstance::~AudioPluginInstance()
  21255. {
  21256. }
  21257. END_JUCE_NAMESPACE
  21258. /********* End of inlined file: juce_AudioPluginInstance.cpp *********/
  21259. /********* Start of inlined file: juce_KnownPluginList.cpp *********/
  21260. BEGIN_JUCE_NAMESPACE
  21261. KnownPluginList::KnownPluginList()
  21262. {
  21263. }
  21264. KnownPluginList::~KnownPluginList()
  21265. {
  21266. }
  21267. void KnownPluginList::clear()
  21268. {
  21269. if (types.size() > 0)
  21270. {
  21271. types.clear();
  21272. sendChangeMessage (this);
  21273. }
  21274. }
  21275. PluginDescription* KnownPluginList::getTypeForFile (const File& file) const throw()
  21276. {
  21277. for (int i = 0; i < types.size(); ++i)
  21278. if (types.getUnchecked(i)->file == file)
  21279. return types.getUnchecked(i);
  21280. return 0;
  21281. }
  21282. PluginDescription* KnownPluginList::getTypeForIdentifierString (const String& identifierString) const throw()
  21283. {
  21284. for (int i = 0; i < types.size(); ++i)
  21285. if (types.getUnchecked(i)->createIdentifierString() == identifierString)
  21286. return types.getUnchecked(i);
  21287. return 0;
  21288. }
  21289. bool KnownPluginList::addType (const PluginDescription& type)
  21290. {
  21291. for (int i = types.size(); --i >= 0;)
  21292. {
  21293. if (types.getUnchecked(i)->isDuplicateOf (type))
  21294. {
  21295. // strange - found a duplicate plugin with different info..
  21296. jassert (types.getUnchecked(i)->name == type.name);
  21297. jassert (types.getUnchecked(i)->isInstrument == type.isInstrument);
  21298. *types.getUnchecked(i) = type;
  21299. return false;
  21300. }
  21301. }
  21302. types.add (new PluginDescription (type));
  21303. sendChangeMessage (this);
  21304. return true;
  21305. }
  21306. void KnownPluginList::removeType (const int index) throw()
  21307. {
  21308. types.remove (index);
  21309. sendChangeMessage (this);
  21310. }
  21311. bool KnownPluginList::isListingUpToDate (const File& possiblePluginFile) const throw()
  21312. {
  21313. if (getTypeForFile (possiblePluginFile) == 0)
  21314. return false;
  21315. for (int i = types.size(); --i >= 0;)
  21316. {
  21317. const PluginDescription* const d = types.getUnchecked(i);
  21318. if (d->file == possiblePluginFile
  21319. && d->lastFileModTime != possiblePluginFile.getLastModificationTime())
  21320. {
  21321. return false;
  21322. }
  21323. }
  21324. return true;
  21325. }
  21326. bool KnownPluginList::scanAndAddFile (const File& possiblePluginFile,
  21327. const bool dontRescanIfAlreadyInList,
  21328. OwnedArray <PluginDescription>& typesFound)
  21329. {
  21330. bool addedOne = false;
  21331. if (dontRescanIfAlreadyInList
  21332. && getTypeForFile (possiblePluginFile) != 0)
  21333. {
  21334. bool needsRescanning = false;
  21335. for (int i = types.size(); --i >= 0;)
  21336. {
  21337. const PluginDescription* const d = types.getUnchecked(i);
  21338. if (d->file == possiblePluginFile)
  21339. {
  21340. if (d->lastFileModTime != possiblePluginFile.getLastModificationTime())
  21341. needsRescanning = true;
  21342. else
  21343. typesFound.add (new PluginDescription (*d));
  21344. }
  21345. }
  21346. if (! needsRescanning)
  21347. return false;
  21348. }
  21349. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  21350. {
  21351. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  21352. OwnedArray <PluginDescription> found;
  21353. format->findAllTypesForFile (found, possiblePluginFile);
  21354. for (int i = 0; i < found.size(); ++i)
  21355. {
  21356. PluginDescription* const desc = found.getUnchecked(i);
  21357. jassert (desc != 0);
  21358. if (addType (*desc))
  21359. addedOne = true;
  21360. typesFound.add (new PluginDescription (*desc));
  21361. }
  21362. }
  21363. return addedOne;
  21364. }
  21365. void KnownPluginList::scanAndAddDragAndDroppedFiles (const StringArray& files,
  21366. OwnedArray <PluginDescription>& typesFound)
  21367. {
  21368. for (int i = 0; i < files.size(); ++i)
  21369. {
  21370. const File f (files [i]);
  21371. if (! scanAndAddFile (f, true, typesFound))
  21372. {
  21373. if (f.isDirectory())
  21374. {
  21375. StringArray s;
  21376. {
  21377. OwnedArray <File> subFiles;
  21378. f.findChildFiles (subFiles, File::findFilesAndDirectories, false);
  21379. for (int j = 0; j < subFiles.size(); ++j)
  21380. s.add (subFiles.getUnchecked (j)->getFullPathName());
  21381. }
  21382. scanAndAddDragAndDroppedFiles (s, typesFound);
  21383. }
  21384. }
  21385. }
  21386. }
  21387. class PluginSorter
  21388. {
  21389. public:
  21390. KnownPluginList::SortMethod method;
  21391. PluginSorter() throw() {}
  21392. int compareElements (const PluginDescription* const first,
  21393. const PluginDescription* const second) const throw()
  21394. {
  21395. int diff = 0;
  21396. if (method == KnownPluginList::sortByCategory)
  21397. diff = first->category.compareLexicographically (second->category);
  21398. else if (method == KnownPluginList::sortByManufacturer)
  21399. diff = first->manufacturerName.compareLexicographically (second->manufacturerName);
  21400. else if (method == KnownPluginList::sortByFileSystemLocation)
  21401. diff = first->file.getParentDirectory().getFullPathName().compare (second->file.getParentDirectory().getFullPathName());
  21402. if (diff == 0)
  21403. diff = first->name.compareLexicographically (second->name);
  21404. return diff;
  21405. }
  21406. };
  21407. void KnownPluginList::sort (const SortMethod method)
  21408. {
  21409. if (method != defaultOrder)
  21410. {
  21411. PluginSorter sorter;
  21412. sorter.method = method;
  21413. types.sort (sorter, true);
  21414. sendChangeMessage (this);
  21415. }
  21416. }
  21417. XmlElement* KnownPluginList::createXml() const
  21418. {
  21419. XmlElement* const e = new XmlElement (T("KNOWNPLUGINS"));
  21420. for (int i = 0; i < types.size(); ++i)
  21421. e->addChildElement (types.getUnchecked(i)->createXml());
  21422. return e;
  21423. }
  21424. void KnownPluginList::recreateFromXml (const XmlElement& xml)
  21425. {
  21426. clear();
  21427. if (xml.hasTagName (T("KNOWNPLUGINS")))
  21428. {
  21429. forEachXmlChildElement (xml, e)
  21430. {
  21431. PluginDescription info;
  21432. if (info.loadFromXml (*e))
  21433. addType (info);
  21434. }
  21435. }
  21436. }
  21437. const int menuIdBase = 0x324503f4;
  21438. // This is used to turn a bunch of paths into a nested menu structure.
  21439. struct PluginFilesystemTree
  21440. {
  21441. private:
  21442. String folder;
  21443. OwnedArray <PluginFilesystemTree> subFolders;
  21444. Array <PluginDescription*> plugins;
  21445. void addPlugin (PluginDescription* const pd, const String& path)
  21446. {
  21447. if (path.isEmpty())
  21448. {
  21449. plugins.add (pd);
  21450. }
  21451. else
  21452. {
  21453. const String firstSubFolder (path.upToFirstOccurrenceOf (T("/"), false, false));
  21454. const String remainingPath (path.fromFirstOccurrenceOf (T("/"), false, false));
  21455. for (int i = subFolders.size(); --i >= 0;)
  21456. {
  21457. if (subFolders.getUnchecked(i)->folder.equalsIgnoreCase (firstSubFolder))
  21458. {
  21459. subFolders.getUnchecked(i)->addPlugin (pd, remainingPath);
  21460. return;
  21461. }
  21462. }
  21463. PluginFilesystemTree* const newFolder = new PluginFilesystemTree();
  21464. newFolder->folder = firstSubFolder;
  21465. subFolders.add (newFolder);
  21466. newFolder->addPlugin (pd, remainingPath);
  21467. }
  21468. }
  21469. // removes any deeply nested folders that don't contain any actual plugins
  21470. void optimise()
  21471. {
  21472. for (int i = subFolders.size(); --i >= 0;)
  21473. {
  21474. PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  21475. sub->optimise();
  21476. if (sub->plugins.size() == 0)
  21477. {
  21478. for (int j = 0; j < sub->subFolders.size(); ++j)
  21479. subFolders.add (sub->subFolders.getUnchecked(j));
  21480. sub->subFolders.clear (false);
  21481. subFolders.remove (i);
  21482. }
  21483. }
  21484. }
  21485. public:
  21486. void buildTree (const Array <PluginDescription*>& allPlugins)
  21487. {
  21488. for (int i = 0; i < allPlugins.size(); ++i)
  21489. {
  21490. String path (allPlugins.getUnchecked(i)->file.getParentDirectory().getFullPathName());
  21491. if (path.substring (1, 2) == T(":"))
  21492. path = path.substring (2);
  21493. path = path.replaceCharacter (T('\\'), T('/'));
  21494. addPlugin (allPlugins.getUnchecked(i), path);
  21495. }
  21496. optimise();
  21497. }
  21498. void addToMenu (PopupMenu& m, const OwnedArray <PluginDescription>& allPlugins) const
  21499. {
  21500. int i;
  21501. for (i = 0; i < subFolders.size(); ++i)
  21502. {
  21503. const PluginFilesystemTree* const sub = subFolders.getUnchecked(i);
  21504. PopupMenu subMenu;
  21505. sub->addToMenu (subMenu, allPlugins);
  21506. m.addSubMenu (sub->folder, subMenu);
  21507. }
  21508. for (i = 0; i < plugins.size(); ++i)
  21509. {
  21510. PluginDescription* const plugin = plugins.getUnchecked(i);
  21511. m.addItem (allPlugins.indexOf (plugin) + menuIdBase,
  21512. plugin->name, true, false);
  21513. }
  21514. }
  21515. };
  21516. void KnownPluginList::addToMenu (PopupMenu& menu, const SortMethod sortMethod) const
  21517. {
  21518. Array <PluginDescription*> sorted;
  21519. {
  21520. PluginSorter sorter;
  21521. sorter.method = sortMethod;
  21522. for (int i = 0; i < types.size(); ++i)
  21523. sorted.addSorted (sorter, types.getUnchecked(i));
  21524. }
  21525. if (sortMethod == sortByCategory
  21526. || sortMethod == sortByManufacturer)
  21527. {
  21528. String lastSubMenuName;
  21529. PopupMenu sub;
  21530. for (int i = 0; i < sorted.size(); ++i)
  21531. {
  21532. const PluginDescription* const pd = sorted.getUnchecked(i);
  21533. String thisSubMenuName (sortMethod == sortByCategory ? pd->category
  21534. : pd->manufacturerName);
  21535. if (thisSubMenuName.trim().isEmpty())
  21536. thisSubMenuName = T("Other");
  21537. if (thisSubMenuName != lastSubMenuName)
  21538. {
  21539. if (sub.getNumItems() > 0)
  21540. {
  21541. menu.addSubMenu (lastSubMenuName, sub);
  21542. sub.clear();
  21543. }
  21544. lastSubMenuName = thisSubMenuName;
  21545. }
  21546. sub.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  21547. }
  21548. if (sub.getNumItems() > 0)
  21549. menu.addSubMenu (lastSubMenuName, sub);
  21550. }
  21551. else if (sortMethod == sortByFileSystemLocation)
  21552. {
  21553. PluginFilesystemTree root;
  21554. root.buildTree (sorted);
  21555. root.addToMenu (menu, types);
  21556. }
  21557. else
  21558. {
  21559. for (int i = 0; i < sorted.size(); ++i)
  21560. {
  21561. const PluginDescription* const pd = sorted.getUnchecked(i);
  21562. menu.addItem (types.indexOf (pd) + menuIdBase, pd->name, true, false);
  21563. }
  21564. }
  21565. }
  21566. int KnownPluginList::getIndexChosenByMenu (const int menuResultCode) const
  21567. {
  21568. const int i = menuResultCode - menuIdBase;
  21569. return (((unsigned int) i) < (unsigned int) types.size()) ? i : -1;
  21570. }
  21571. END_JUCE_NAMESPACE
  21572. /********* End of inlined file: juce_KnownPluginList.cpp *********/
  21573. /********* Start of inlined file: juce_PluginDescription.cpp *********/
  21574. BEGIN_JUCE_NAMESPACE
  21575. PluginDescription::PluginDescription() throw()
  21576. : uid (0),
  21577. isInstrument (false),
  21578. numInputChannels (0),
  21579. numOutputChannels (0)
  21580. {
  21581. }
  21582. PluginDescription::~PluginDescription() throw()
  21583. {
  21584. }
  21585. PluginDescription::PluginDescription (const PluginDescription& other) throw()
  21586. : name (other.name),
  21587. pluginFormatName (other.pluginFormatName),
  21588. category (other.category),
  21589. manufacturerName (other.manufacturerName),
  21590. version (other.version),
  21591. file (other.file),
  21592. lastFileModTime (other.lastFileModTime),
  21593. uid (other.uid),
  21594. isInstrument (other.isInstrument),
  21595. numInputChannels (other.numInputChannels),
  21596. numOutputChannels (other.numOutputChannels)
  21597. {
  21598. }
  21599. const PluginDescription& PluginDescription::operator= (const PluginDescription& other) throw()
  21600. {
  21601. name = other.name;
  21602. pluginFormatName = other.pluginFormatName;
  21603. category = other.category;
  21604. manufacturerName = other.manufacturerName;
  21605. version = other.version;
  21606. file = other.file;
  21607. uid = other.uid;
  21608. isInstrument = other.isInstrument;
  21609. lastFileModTime = other.lastFileModTime;
  21610. numInputChannels = other.numInputChannels;
  21611. numOutputChannels = other.numOutputChannels;
  21612. return *this;
  21613. }
  21614. bool PluginDescription::isDuplicateOf (const PluginDescription& other) const
  21615. {
  21616. return file == other.file
  21617. && uid == other.uid;
  21618. }
  21619. const String PluginDescription::createIdentifierString() const throw()
  21620. {
  21621. return pluginFormatName
  21622. + T("-") + name
  21623. + T("-") + String::toHexString (file.getFileName().hashCode())
  21624. + T("-") + String::toHexString (uid);
  21625. }
  21626. XmlElement* PluginDescription::createXml() const
  21627. {
  21628. XmlElement* const e = new XmlElement (T("PLUGIN"));
  21629. e->setAttribute (T("name"), name);
  21630. e->setAttribute (T("format"), pluginFormatName);
  21631. e->setAttribute (T("category"), category);
  21632. e->setAttribute (T("manufacturer"), manufacturerName);
  21633. e->setAttribute (T("version"), version);
  21634. e->setAttribute (T("file"), file.getFullPathName());
  21635. e->setAttribute (T("uid"), String::toHexString (uid));
  21636. e->setAttribute (T("isInstrument"), isInstrument);
  21637. e->setAttribute (T("fileTime"), String::toHexString (lastFileModTime.toMilliseconds()));
  21638. e->setAttribute (T("numInputs"), numInputChannels);
  21639. e->setAttribute (T("numOutputs"), numOutputChannels);
  21640. return e;
  21641. }
  21642. bool PluginDescription::loadFromXml (const XmlElement& xml)
  21643. {
  21644. if (xml.hasTagName (T("PLUGIN")))
  21645. {
  21646. name = xml.getStringAttribute (T("name"));
  21647. pluginFormatName = xml.getStringAttribute (T("format"));
  21648. category = xml.getStringAttribute (T("category"));
  21649. manufacturerName = xml.getStringAttribute (T("manufacturer"));
  21650. version = xml.getStringAttribute (T("version"));
  21651. file = File (xml.getStringAttribute (T("file")));
  21652. uid = xml.getStringAttribute (T("uid")).getHexValue32();
  21653. isInstrument = xml.getBoolAttribute (T("isInstrument"), false);
  21654. lastFileModTime = Time (xml.getStringAttribute (T("fileTime")).getHexValue64());
  21655. numInputChannels = xml.getIntAttribute (T("numInputs"));
  21656. numOutputChannels = xml.getIntAttribute (T("numOutputs"));
  21657. return true;
  21658. }
  21659. return false;
  21660. }
  21661. END_JUCE_NAMESPACE
  21662. /********* End of inlined file: juce_PluginDescription.cpp *********/
  21663. /********* Start of inlined file: juce_PluginDirectoryScanner.cpp *********/
  21664. BEGIN_JUCE_NAMESPACE
  21665. PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
  21666. AudioPluginFormat& formatToLookFor,
  21667. FileSearchPath directoriesToSearch,
  21668. const bool recursive,
  21669. const File& deadMansPedalFile_)
  21670. : list (listToAddTo),
  21671. format (formatToLookFor),
  21672. deadMansPedalFile (deadMansPedalFile_),
  21673. nextIndex (0),
  21674. progress (0)
  21675. {
  21676. directoriesToSearch.removeRedundantPaths();
  21677. for (int j = 0; j < directoriesToSearch.getNumPaths(); ++j)
  21678. recursiveFileSearch (directoriesToSearch [j], recursive);
  21679. // If any plugins have crashed recently when being loaded, move them to the
  21680. // end of the list to give the others a chance to load correctly..
  21681. const StringArray crashedPlugins (getDeadMansPedalFile());
  21682. for (int i = 0; i < crashedPlugins.size(); ++i)
  21683. {
  21684. const File f (crashedPlugins[i]);
  21685. for (int j = filesToScan.size(); --j >= 0;)
  21686. if (f == *filesToScan.getUnchecked (j))
  21687. filesToScan.move (j, -1);
  21688. }
  21689. }
  21690. void PluginDirectoryScanner::recursiveFileSearch (const File& dir, const bool recursive)
  21691. {
  21692. // avoid allowing the dir iterator to be recursive, because we want to avoid letting it delve inside
  21693. // .component or .vst directories.
  21694. DirectoryIterator iter (dir, false, "*", File::findFilesAndDirectories);
  21695. while (iter.next())
  21696. {
  21697. const File f (iter.getFile());
  21698. bool isPlugin = false;
  21699. if (format.fileMightContainThisPluginType (f))
  21700. {
  21701. isPlugin = true;
  21702. filesToScan.add (new File (f));
  21703. }
  21704. if (recursive && (! isPlugin) && f.isDirectory())
  21705. recursiveFileSearch (f, true);
  21706. }
  21707. }
  21708. PluginDirectoryScanner::~PluginDirectoryScanner()
  21709. {
  21710. }
  21711. const File PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const throw()
  21712. {
  21713. File* const file = filesToScan [nextIndex];
  21714. if (file != 0)
  21715. return *file;
  21716. return File::nonexistent;
  21717. }
  21718. bool PluginDirectoryScanner::scanNextFile (const bool dontRescanIfAlreadyInList)
  21719. {
  21720. File* const file = filesToScan [nextIndex];
  21721. if (file != 0)
  21722. {
  21723. if (! list.isListingUpToDate (*file))
  21724. {
  21725. OwnedArray <PluginDescription> typesFound;
  21726. // Add this plugin to the end of the dead-man's pedal list in case it crashes...
  21727. StringArray crashedPlugins (getDeadMansPedalFile());
  21728. crashedPlugins.removeString (file->getFullPathName());
  21729. crashedPlugins.add (file->getFullPathName());
  21730. setDeadMansPedalFile (crashedPlugins);
  21731. list.scanAndAddFile (*file,
  21732. dontRescanIfAlreadyInList,
  21733. typesFound);
  21734. // Managed to load without crashing, so remove it from the dead-man's-pedal..
  21735. crashedPlugins.removeString (file->getFullPathName());
  21736. setDeadMansPedalFile (crashedPlugins);
  21737. if (typesFound.size() == 0)
  21738. failedFiles.add (file->getFullPathName());
  21739. }
  21740. ++nextIndex;
  21741. progress = nextIndex / (float) filesToScan.size();
  21742. }
  21743. return nextIndex < filesToScan.size();
  21744. }
  21745. const StringArray PluginDirectoryScanner::getDeadMansPedalFile() throw()
  21746. {
  21747. StringArray lines;
  21748. if (deadMansPedalFile != File::nonexistent)
  21749. {
  21750. lines.addLines (deadMansPedalFile.loadFileAsString());
  21751. lines.removeEmptyStrings();
  21752. }
  21753. return lines;
  21754. }
  21755. void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents) throw()
  21756. {
  21757. if (deadMansPedalFile != File::nonexistent)
  21758. deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
  21759. }
  21760. END_JUCE_NAMESPACE
  21761. /********* End of inlined file: juce_PluginDirectoryScanner.cpp *********/
  21762. /********* Start of inlined file: juce_PluginListComponent.cpp *********/
  21763. BEGIN_JUCE_NAMESPACE
  21764. PluginListComponent::PluginListComponent (KnownPluginList& listToEdit,
  21765. const File& deadMansPedalFile_,
  21766. PropertiesFile* const propertiesToUse_)
  21767. : list (listToEdit),
  21768. deadMansPedalFile (deadMansPedalFile_),
  21769. propertiesToUse (propertiesToUse_)
  21770. {
  21771. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  21772. addAndMakeVisible (optionsButton = new TextButton ("Options..."));
  21773. optionsButton->addButtonListener (this);
  21774. optionsButton->setTriggeredOnMouseDown (true);
  21775. setSize (400, 600);
  21776. list.addChangeListener (this);
  21777. }
  21778. PluginListComponent::~PluginListComponent()
  21779. {
  21780. list.removeChangeListener (this);
  21781. deleteAllChildren();
  21782. }
  21783. void PluginListComponent::resized()
  21784. {
  21785. listBox->setBounds (0, 0, getWidth(), getHeight() - 30);
  21786. optionsButton->changeWidthToFitText (24);
  21787. optionsButton->setTopLeftPosition (8, getHeight() - 28);
  21788. }
  21789. void PluginListComponent::changeListenerCallback (void*)
  21790. {
  21791. listBox->updateContent();
  21792. listBox->repaint();
  21793. }
  21794. int PluginListComponent::getNumRows()
  21795. {
  21796. return list.getNumTypes();
  21797. }
  21798. void PluginListComponent::paintListBoxItem (int row,
  21799. Graphics& g,
  21800. int width, int height,
  21801. bool rowIsSelected)
  21802. {
  21803. if (rowIsSelected)
  21804. g.fillAll (findColour (TextEditor::highlightColourId));
  21805. const PluginDescription* const pd = list.getType (row);
  21806. if (pd != 0)
  21807. {
  21808. GlyphArrangement ga;
  21809. ga.addCurtailedLineOfText (Font (height * 0.7f, Font::bold), pd->name, 8.0f, height * 0.8f, width - 10.0f, true);
  21810. g.setColour (Colours::black);
  21811. ga.draw (g);
  21812. float x, y, r, b;
  21813. ga.getBoundingBox (0, -1, x, y, r, b, false);
  21814. String desc;
  21815. desc << pd->pluginFormatName
  21816. << (pd->isInstrument ? " instrument" : " effect")
  21817. << " - "
  21818. << pd->numInputChannels << (pd->numInputChannels == 1 ? " in" : " ins")
  21819. << " / "
  21820. << pd->numOutputChannels << (pd->numOutputChannels == 1 ? " out" : " outs");
  21821. if (pd->manufacturerName.isNotEmpty())
  21822. desc << " - " << pd->manufacturerName;
  21823. if (pd->version.isNotEmpty())
  21824. desc << " - " << pd->version;
  21825. if (pd->category.isNotEmpty())
  21826. desc << " - category: '" << pd->category << '\'';
  21827. g.setColour (Colours::grey);
  21828. ga.clear();
  21829. ga.addCurtailedLineOfText (Font (height * 0.6f), desc, r + 10.0f, height * 0.8f, width - r - 12.0f, true);
  21830. ga.draw (g);
  21831. }
  21832. }
  21833. void PluginListComponent::deleteKeyPressed (int lastRowSelected)
  21834. {
  21835. list.removeType (lastRowSelected);
  21836. }
  21837. void PluginListComponent::buttonClicked (Button* b)
  21838. {
  21839. if (optionsButton == b)
  21840. {
  21841. PopupMenu menu;
  21842. menu.addItem (1, TRANS("Clear list"));
  21843. menu.addItem (5, TRANS("Remove selected plugin from list"), listBox->getNumSelectedRows() > 0);
  21844. menu.addItem (6, TRANS("Show folder containing selected plugin"), listBox->getNumSelectedRows() > 0);
  21845. menu.addItem (7, TRANS("Remove any plugins whose files no longer exist"));
  21846. menu.addSeparator();
  21847. menu.addItem (2, TRANS("Sort alphabetically"));
  21848. menu.addItem (3, TRANS("Sort by category"));
  21849. menu.addItem (4, TRANS("Sort by manufacturer"));
  21850. menu.addSeparator();
  21851. for (int i = 0; i < AudioPluginFormatManager::getInstance()->getNumFormats(); ++i)
  21852. {
  21853. AudioPluginFormat* const format = AudioPluginFormatManager::getInstance()->getFormat (i);
  21854. if (format->getDefaultLocationsToSearch().getNumPaths() > 0)
  21855. menu.addItem (10 + i, "Scan for new or updated " + format->getName() + " plugins...");
  21856. }
  21857. const int r = menu.showAt (optionsButton);
  21858. if (r == 1)
  21859. {
  21860. list.clear();
  21861. }
  21862. else if (r == 2)
  21863. {
  21864. list.sort (KnownPluginList::sortAlphabetically);
  21865. }
  21866. else if (r == 3)
  21867. {
  21868. list.sort (KnownPluginList::sortByCategory);
  21869. }
  21870. else if (r == 4)
  21871. {
  21872. list.sort (KnownPluginList::sortByManufacturer);
  21873. }
  21874. else if (r == 5)
  21875. {
  21876. const SparseSet <int> selected (listBox->getSelectedRows());
  21877. for (int i = list.getNumTypes(); --i >= 0;)
  21878. if (selected.contains (i))
  21879. list.removeType (i);
  21880. }
  21881. else if (r == 6)
  21882. {
  21883. const PluginDescription* const desc = list.getType (listBox->getSelectedRow());
  21884. if (desc != 0)
  21885. desc->file.getParentDirectory().startAsProcess();
  21886. }
  21887. else if (r == 7)
  21888. {
  21889. for (int i = list.getNumTypes(); --i >= 0;)
  21890. {
  21891. if (list.getType (i)->file != File::nonexistent
  21892. && ! list.getType (i)->file.exists())
  21893. {
  21894. list.removeType (i);
  21895. }
  21896. }
  21897. }
  21898. else if (r != 0)
  21899. {
  21900. typeToScan = r - 10;
  21901. startTimer (1);
  21902. }
  21903. }
  21904. }
  21905. void PluginListComponent::timerCallback()
  21906. {
  21907. stopTimer();
  21908. scanFor (AudioPluginFormatManager::getInstance()->getFormat (typeToScan));
  21909. }
  21910. bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
  21911. {
  21912. return true;
  21913. }
  21914. void PluginListComponent::filesDropped (const StringArray& files, int, int)
  21915. {
  21916. OwnedArray <PluginDescription> typesFound;
  21917. list.scanAndAddDragAndDroppedFiles (files, typesFound);
  21918. }
  21919. void PluginListComponent::scanFor (AudioPluginFormat* format)
  21920. {
  21921. if (format == 0)
  21922. return;
  21923. FileSearchPath path (format->getDefaultLocationsToSearch());
  21924. if (propertiesToUse != 0)
  21925. path = propertiesToUse->getValue ("lastPluginScanPath_" + format->getName(), path.toString());
  21926. {
  21927. AlertWindow aw (TRANS("Select folders to scan..."), String::empty, AlertWindow::NoIcon);
  21928. FileSearchPathListComponent pathList;
  21929. pathList.setSize (500, 300);
  21930. pathList.setPath (path);
  21931. aw.addCustomComponent (&pathList);
  21932. aw.addButton (TRANS("Scan"), 1, KeyPress::returnKey);
  21933. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  21934. if (aw.runModalLoop() == 0)
  21935. return;
  21936. path = pathList.getPath();
  21937. }
  21938. if (propertiesToUse != 0)
  21939. {
  21940. propertiesToUse->setValue ("lastPluginScanPath_" + format->getName(), path.toString());
  21941. propertiesToUse->saveIfNeeded();
  21942. }
  21943. double progress = 0.0;
  21944. AlertWindow aw (TRANS("Scanning for plugins..."),
  21945. TRANS("Searching for all possible plugin files..."), AlertWindow::NoIcon);
  21946. aw.addButton (TRANS("Cancel"), 0, KeyPress (KeyPress::escapeKey));
  21947. aw.addProgressBarComponent (progress);
  21948. aw.enterModalState();
  21949. MessageManager::getInstance()->runDispatchLoopUntil (300);
  21950. PluginDirectoryScanner scanner (list, *format, path, true, deadMansPedalFile);
  21951. for (;;)
  21952. {
  21953. aw.setMessage (TRANS("Testing:\n\n")
  21954. + scanner.getNextPluginFileThatWillBeScanned().getFileName());
  21955. MessageManager::getInstance()->runDispatchLoopUntil (20);
  21956. if (! scanner.scanNextFile (true))
  21957. break;
  21958. if (! aw.isCurrentlyModal())
  21959. break;
  21960. progress = scanner.getProgress();
  21961. }
  21962. if (scanner.getFailedFiles().size() > 0)
  21963. {
  21964. StringArray shortNames;
  21965. for (int i = 0; i < scanner.getFailedFiles().size(); ++i)
  21966. shortNames.add (File (scanner.getFailedFiles()[i]).getFileName());
  21967. AlertWindow::showMessageBox (AlertWindow::InfoIcon,
  21968. TRANS("Scan complete"),
  21969. TRANS("Note that the following files appeared to be plugin files, but failed to load correctly:\n\n")
  21970. + shortNames.joinIntoString (", "));
  21971. }
  21972. }
  21973. END_JUCE_NAMESPACE
  21974. /********* End of inlined file: juce_PluginListComponent.cpp *********/
  21975. /********* Start of inlined file: juce_AudioUnitPluginFormat.cpp *********/
  21976. /********* Start of inlined file: juce_Config.h *********/
  21977. #ifndef __JUCE_CONFIG_JUCEHEADER__
  21978. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  21979. /*
  21980. This file contains macros that enable/disable various JUCE features.
  21981. */
  21982. /** The name of the namespace that all Juce classes and functions will be
  21983. put inside. If this is not defined, no namespace will be used.
  21984. */
  21985. #ifndef JUCE_NAMESPACE
  21986. #define JUCE_NAMESPACE juce
  21987. #endif
  21988. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  21989. but if you define this value, you can override this can force it to be true or
  21990. false.
  21991. */
  21992. #ifndef JUCE_FORCE_DEBUG
  21993. //#define JUCE_FORCE_DEBUG 1
  21994. #endif
  21995. /** If this flag is enabled, the the jassert and jassertfalse macros will
  21996. always use Logger::writeToLog() to write a message when an assertion happens.
  21997. Enabling it will also leave this turned on in release builds. When it's disabled,
  21998. however, the jassert and jassertfalse macros will not be compiled in a
  21999. release build.
  22000. @see jassert, jassertfalse, Logger
  22001. */
  22002. #ifndef JUCE_LOG_ASSERTIONS
  22003. // #define JUCE_LOG_ASSERTIONS 1
  22004. #endif
  22005. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  22006. which the ASIOAudioIODevice class can't be built. See the comments in the
  22007. ASIOAudioIODevice class's header file for more info about this.
  22008. (This only affects a Win32 build)
  22009. */
  22010. #ifndef JUCE_ASIO
  22011. #define JUCE_ASIO 1
  22012. #endif
  22013. /** Comment out this macro to disable building of ALSA device support on Linux.
  22014. */
  22015. #ifndef JUCE_ALSA
  22016. #define JUCE_ALSA 1
  22017. #endif
  22018. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  22019. have the SDK installed.
  22020. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  22021. classes will be unavailable.
  22022. On Windows, if you enable this, you'll need to have the QuickTime SDK
  22023. installed, and its header files will need to be on your include path.
  22024. */
  22025. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  22026. #define JUCE_QUICKTIME 1
  22027. #endif
  22028. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  22029. have the appropriate headers and libraries available. If it's not enabled, the
  22030. OpenGLComponent class will be unavailable.
  22031. */
  22032. #ifndef JUCE_OPENGL
  22033. #define JUCE_OPENGL 1
  22034. #endif
  22035. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  22036. If you're not going to need either of these formats, turn off the flags to
  22037. avoid bloating your codebase with them.
  22038. */
  22039. #ifndef JUCE_USE_FLAC
  22040. #define JUCE_USE_FLAC 1
  22041. #endif
  22042. #ifndef JUCE_USE_OGGVORBIS
  22043. #define JUCE_USE_OGGVORBIS 1
  22044. #endif
  22045. /** This flag lets you enable support for CD-burning. You might want to disable
  22046. it to build without the MS SDK under windows.
  22047. */
  22048. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  22049. #define JUCE_USE_CDBURNER 1
  22050. #endif
  22051. /** Enabling this macro means that all regions that get repainted will have a coloured
  22052. line drawn around them.
  22053. This is handy if you're trying to optimise drawing, because it lets you easily see
  22054. when anything is being repainted unnecessarily.
  22055. */
  22056. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  22057. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  22058. #endif
  22059. /** Enable this under Linux to use Xinerama for multi-monitor support.
  22060. */
  22061. #ifndef JUCE_USE_XINERAMA
  22062. #define JUCE_USE_XINERAMA 1
  22063. #endif
  22064. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  22065. */
  22066. #ifndef JUCE_USE_XSHM
  22067. #define JUCE_USE_XSHM 1
  22068. #endif
  22069. /** Enabling this builds support for VST audio plugins.
  22070. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  22071. */
  22072. #ifndef JUCE_PLUGINHOST_VST
  22073. // #define JUCE_PLUGINHOST_VST 1
  22074. #endif
  22075. /** Enabling this builds support for AudioUnit audio plugins.
  22076. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  22077. */
  22078. #ifndef JUCE_PLUGINHOST_AU
  22079. // #define JUCE_PLUGINHOST_AU 1
  22080. #endif
  22081. /** Disabling this will avoid linking to any UI code. This is handy for
  22082. writing command-line utilities, e.g. on linux boxes which don't have some
  22083. of the UI libraries installed.
  22084. (On mac and windows, this won't generally make much difference to the build).
  22085. */
  22086. #ifndef JUCE_BUILD_GUI_CLASSES
  22087. #define JUCE_BUILD_GUI_CLASSES 1
  22088. #endif
  22089. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  22090. */
  22091. #ifndef JUCE_WEB_BROWSER
  22092. #define JUCE_WEB_BROWSER 1
  22093. #endif
  22094. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  22095. codebase - you might need to use this if you're linking to some of these libraries
  22096. yourself.
  22097. */
  22098. #ifndef JUCE_INCLUDE_ZLIB_CODE
  22099. #define JUCE_INCLUDE_ZLIB_CODE 1
  22100. #endif
  22101. #ifndef JUCE_INCLUDE_FLAC_CODE
  22102. #define JUCE_INCLUDE_FLAC_CODE 1
  22103. #endif
  22104. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  22105. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  22106. #endif
  22107. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  22108. #define JUCE_INCLUDE_PNGLIB_CODE 1
  22109. #endif
  22110. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  22111. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  22112. #endif
  22113. /** Enable this to add extra memory-leak info to the new and delete operators.
  22114. (Currently, this only affects Windows builds in debug mode).
  22115. */
  22116. #ifndef JUCE_CHECK_MEMORY_LEAKS
  22117. #define JUCE_CHECK_MEMORY_LEAKS 1
  22118. #endif
  22119. /** Enable this to turn on juce's internal catching of exceptions.
  22120. Turning it off will avoid any exception catching. With it on, all exceptions
  22121. are passed to the JUCEApplication::unhandledException() callback for logging.
  22122. */
  22123. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  22124. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  22125. #endif
  22126. /** If this macro is set, the Juce String class will use unicode as its
  22127. internal representation. If it isn't set, it'll use ANSI.
  22128. */
  22129. #ifndef JUCE_STRINGS_ARE_UNICODE
  22130. #define JUCE_STRINGS_ARE_UNICODE 1
  22131. #endif
  22132. #endif
  22133. /********* End of inlined file: juce_Config.h *********/
  22134. #if JUCE_PLUGINHOST_AU && (! (defined (LINUX) || defined (_WIN32)))
  22135. #include <Carbon/Carbon.h>
  22136. #include <AudioToolbox/AudioToolbox.h>
  22137. #include <AudioUnit/AudioUnitCarbonView.h>
  22138. BEGIN_JUCE_NAMESPACE
  22139. #if JUCE_MAC
  22140. extern void juce_callAnyTimersSynchronously();
  22141. extern bool juce_isHIViewCreatedByJuce (HIViewRef view);
  22142. extern bool juce_isWindowCreatedByJuce (WindowRef window);
  22143. #if MACOS_10_3_OR_EARLIER
  22144. #define kAudioUnitType_Generator 'augn'
  22145. #endif
  22146. // Change this to disable logging of various activities
  22147. #ifndef AU_LOGGING
  22148. #define AU_LOGGING 1
  22149. #endif
  22150. #if AU_LOGGING
  22151. #define log(a) Logger::writeToLog(a);
  22152. #else
  22153. #define log(a)
  22154. #endif
  22155. static int insideCallback = 0;
  22156. class AudioUnitPluginWindow;
  22157. class AudioUnitPluginInstance : public AudioPluginInstance
  22158. {
  22159. public:
  22160. ~AudioUnitPluginInstance();
  22161. // AudioPluginInstance methods:
  22162. void fillInPluginDescription (PluginDescription& desc) const
  22163. {
  22164. desc.name = pluginName;
  22165. desc.file = file;
  22166. desc.uid = ((int) componentDesc.componentType)
  22167. ^ ((int) componentDesc.componentSubType)
  22168. ^ ((int) componentDesc.componentManufacturer);
  22169. desc.lastFileModTime = file.getLastModificationTime();
  22170. desc.pluginFormatName = "AudioUnit";
  22171. desc.category = getCategory();
  22172. desc.manufacturerName = manufacturer;
  22173. desc.version = version;
  22174. desc.numInputChannels = getNumInputChannels();
  22175. desc.numOutputChannels = getNumOutputChannels();
  22176. desc.isInstrument = (componentDesc.componentType == kAudioUnitType_MusicDevice);
  22177. }
  22178. const String getName() const { return pluginName; }
  22179. bool acceptsMidi() const { return wantsMidiMessages; }
  22180. bool producesMidi() const { return false; }
  22181. // AudioProcessor methods:
  22182. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  22183. void releaseResources();
  22184. void processBlock (AudioSampleBuffer& buffer,
  22185. MidiBuffer& midiMessages);
  22186. AudioProcessorEditor* createEditor();
  22187. const String getInputChannelName (const int index) const;
  22188. bool isInputChannelStereoPair (int index) const;
  22189. const String getOutputChannelName (const int index) const;
  22190. bool isOutputChannelStereoPair (int index) const;
  22191. int getNumParameters();
  22192. float getParameter (int index);
  22193. void setParameter (int index, float newValue);
  22194. const String getParameterName (int index);
  22195. const String getParameterText (int index);
  22196. bool isParameterAutomatable (int index) const;
  22197. int getNumPrograms();
  22198. int getCurrentProgram();
  22199. void setCurrentProgram (int index);
  22200. const String getProgramName (int index);
  22201. void changeProgramName (int index, const String& newName);
  22202. void getStateInformation (MemoryBlock& destData);
  22203. void getCurrentProgramStateInformation (MemoryBlock& destData);
  22204. void setStateInformation (const void* data, int sizeInBytes);
  22205. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  22206. juce_UseDebuggingNewOperator
  22207. private:
  22208. friend class AudioUnitPluginWindow;
  22209. friend class AudioUnitPluginFormat;
  22210. ComponentDescription componentDesc;
  22211. String pluginName, manufacturer, version;
  22212. File file;
  22213. CriticalSection lock;
  22214. bool initialised, wantsMidiMessages, wasPlaying;
  22215. AudioBufferList* outputBufferList;
  22216. AudioTimeStamp timeStamp;
  22217. AudioSampleBuffer* currentBuffer;
  22218. AudioUnit audioUnit;
  22219. Array <int> parameterIds;
  22220. bool getComponentDescFromFile (const File& file);
  22221. void initialise();
  22222. OSStatus renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  22223. const AudioTimeStamp* inTimeStamp,
  22224. UInt32 inBusNumber,
  22225. UInt32 inNumberFrames,
  22226. AudioBufferList* ioData) const;
  22227. static OSStatus renderGetInputCallback (void* inRefCon,
  22228. AudioUnitRenderActionFlags* ioActionFlags,
  22229. const AudioTimeStamp* inTimeStamp,
  22230. UInt32 inBusNumber,
  22231. UInt32 inNumberFrames,
  22232. AudioBufferList* ioData)
  22233. {
  22234. return ((AudioUnitPluginInstance*) inRefCon)
  22235. ->renderGetInput (ioActionFlags, inTimeStamp, inBusNumber, inNumberFrames, ioData);
  22236. }
  22237. OSStatus getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const;
  22238. OSStatus getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat, Float32* outTimeSig_Numerator,
  22239. UInt32* outTimeSig_Denominator, Float64* outCurrentMeasureDownBeat) const;
  22240. OSStatus getTransportState (Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  22241. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  22242. Float64* outCycleStartBeat, Float64* outCycleEndBeat);
  22243. static OSStatus getBeatAndTempoCallback (void* inHostUserData, Float64* outCurrentBeat, Float64* outCurrentTempo)
  22244. {
  22245. return ((AudioUnitPluginInstance*) inHostUserData)->getBeatAndTempo (outCurrentBeat, outCurrentTempo);
  22246. }
  22247. static OSStatus getMusicalTimeLocationCallback (void* inHostUserData, UInt32* outDeltaSampleOffsetToNextBeat,
  22248. Float32* outTimeSig_Numerator, UInt32* outTimeSig_Denominator,
  22249. Float64* outCurrentMeasureDownBeat)
  22250. {
  22251. return ((AudioUnitPluginInstance*) inHostUserData)
  22252. ->getMusicalTimeLocation (outDeltaSampleOffsetToNextBeat, outTimeSig_Numerator,
  22253. outTimeSig_Denominator, outCurrentMeasureDownBeat);
  22254. }
  22255. static OSStatus getTransportStateCallback (void* inHostUserData, Boolean* outIsPlaying, Boolean* outTransportStateChanged,
  22256. Float64* outCurrentSampleInTimeLine, Boolean* outIsCycling,
  22257. Float64* outCycleStartBeat, Float64* outCycleEndBeat)
  22258. {
  22259. return ((AudioUnitPluginInstance*) inHostUserData)
  22260. ->getTransportState (outIsPlaying, outTransportStateChanged,
  22261. outCurrentSampleInTimeLine, outIsCycling,
  22262. outCycleStartBeat, outCycleEndBeat);
  22263. }
  22264. void getNumChannels (int& numIns, int& numOuts)
  22265. {
  22266. numIns = 0;
  22267. numOuts = 0;
  22268. AUChannelInfo supportedChannels [128];
  22269. UInt32 supportedChannelsSize = sizeof (supportedChannels);
  22270. if (AudioUnitGetProperty (audioUnit, kAudioUnitProperty_SupportedNumChannels, kAudioUnitScope_Global,
  22271. 0, supportedChannels, &supportedChannelsSize) == noErr
  22272. && supportedChannelsSize > 0)
  22273. {
  22274. for (int i = 0; i < supportedChannelsSize / sizeof (AUChannelInfo); ++i)
  22275. {
  22276. numIns = jmax (numIns, supportedChannels[i].inChannels);
  22277. numOuts = jmax (numOuts, supportedChannels[i].outChannels);
  22278. }
  22279. }
  22280. else
  22281. {
  22282. // (this really means the plugin will take any number of ins/outs as long
  22283. // as they are the same)
  22284. numIns = numOuts = 2;
  22285. }
  22286. }
  22287. const String getCategory() const;
  22288. AudioUnitPluginInstance (const File& file);
  22289. };
  22290. AudioUnitPluginInstance::AudioUnitPluginInstance (const File& file_)
  22291. : file (file_),
  22292. initialised (false),
  22293. wantsMidiMessages (false),
  22294. audioUnit (0),
  22295. outputBufferList (0),
  22296. currentBuffer (0)
  22297. {
  22298. try
  22299. {
  22300. ++insideCallback;
  22301. log (T("Opening AU: ") + file.getFullPathName());
  22302. if (getComponentDescFromFile (file))
  22303. {
  22304. ComponentRecord* const comp = FindNextComponent (0, &componentDesc);
  22305. if (comp != 0)
  22306. {
  22307. audioUnit = (AudioUnit) OpenComponent (comp);
  22308. wantsMidiMessages = componentDesc.componentType == kAudioUnitType_MusicDevice
  22309. || componentDesc.componentType == kAudioUnitType_MusicEffect;
  22310. }
  22311. }
  22312. --insideCallback;
  22313. }
  22314. catch (...)
  22315. {
  22316. --insideCallback;
  22317. }
  22318. }
  22319. AudioUnitPluginInstance::~AudioUnitPluginInstance()
  22320. {
  22321. {
  22322. const ScopedLock sl (lock);
  22323. jassert (insideCallback == 0);
  22324. if (audioUnit != 0)
  22325. {
  22326. AudioUnitUninitialize (audioUnit);
  22327. CloseComponent (audioUnit);
  22328. audioUnit = 0;
  22329. }
  22330. }
  22331. juce_free (outputBufferList);
  22332. }
  22333. bool AudioUnitPluginInstance::getComponentDescFromFile (const File& file)
  22334. {
  22335. zerostruct (componentDesc);
  22336. if (! file.hasFileExtension (T(".component")))
  22337. return false;
  22338. const String filename (file.getFullPathName());
  22339. const char* const utf8 = filename.toUTF8();
  22340. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  22341. strlen (utf8), file.isDirectory());
  22342. if (url != 0)
  22343. {
  22344. CFBundleRef bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  22345. CFRelease (url);
  22346. if (bundleRef != 0)
  22347. {
  22348. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  22349. if (name != 0 && CFGetTypeID (name) == CFStringGetTypeID())
  22350. pluginName = PlatformUtilities::cfStringToJuceString ((CFStringRef) name);
  22351. if (pluginName.isEmpty())
  22352. pluginName = file.getFileNameWithoutExtension();
  22353. CFTypeRef versionString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleVersion"));
  22354. if (versionString != 0 && CFGetTypeID (versionString) == CFStringGetTypeID())
  22355. version = PlatformUtilities::cfStringToJuceString ((CFStringRef) versionString);
  22356. CFTypeRef manuString = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleGetInfoString"));
  22357. if (manuString != 0 && CFGetTypeID (manuString) == CFStringGetTypeID())
  22358. manufacturer = PlatformUtilities::cfStringToJuceString ((CFStringRef) manuString);
  22359. short resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  22360. UseResFile (resFileId);
  22361. for (int i = 1; i <= Count1Resources ('thng'); ++i)
  22362. {
  22363. Handle h = Get1IndResource ('thng', i);
  22364. if (h != 0)
  22365. {
  22366. HLock (h);
  22367. const uint32* const types = (const uint32*) *h;
  22368. if (types[0] == kAudioUnitType_MusicDevice
  22369. || types[0] == kAudioUnitType_MusicEffect
  22370. || types[0] == kAudioUnitType_Effect
  22371. || types[0] == kAudioUnitType_Generator
  22372. || types[0] == kAudioUnitType_Panner)
  22373. {
  22374. componentDesc.componentType = types[0];
  22375. componentDesc.componentSubType = types[1];
  22376. componentDesc.componentManufacturer = types[2];
  22377. break;
  22378. }
  22379. HUnlock (h);
  22380. ReleaseResource (h);
  22381. }
  22382. }
  22383. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  22384. CFRelease (bundleRef);
  22385. }
  22386. }
  22387. return componentDesc.componentType != 0 && componentDesc.componentSubType != 0;
  22388. }
  22389. void AudioUnitPluginInstance::initialise()
  22390. {
  22391. if (initialised || audioUnit == 0)
  22392. return;
  22393. log (T("Initialising AU: ") + pluginName);
  22394. parameterIds.clear();
  22395. {
  22396. UInt32 paramListSize = 0;
  22397. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  22398. 0, 0, &paramListSize);
  22399. if (paramListSize > 0)
  22400. {
  22401. parameterIds.insertMultiple (0, 0, paramListSize / sizeof (int));
  22402. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_ParameterList, kAudioUnitScope_Global,
  22403. 0, &parameterIds.getReference(0), &paramListSize);
  22404. }
  22405. }
  22406. {
  22407. AURenderCallbackStruct info;
  22408. zerostruct (info);
  22409. info.inputProcRefCon = this;
  22410. info.inputProc = renderGetInputCallback;
  22411. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_SetRenderCallback, kAudioUnitScope_Input,
  22412. 0, &info, sizeof (info));
  22413. }
  22414. {
  22415. HostCallbackInfo info;
  22416. zerostruct (info);
  22417. info.hostUserData = this;
  22418. info.beatAndTempoProc = getBeatAndTempoCallback;
  22419. info.musicalTimeLocationProc = getMusicalTimeLocationCallback;
  22420. info.transportStateProc = getTransportStateCallback;
  22421. AudioUnitSetProperty (audioUnit, kAudioUnitProperty_HostCallbacks, kAudioUnitScope_Global,
  22422. 0, &info, sizeof (info));
  22423. }
  22424. int numIns, numOuts;
  22425. getNumChannels (numIns, numOuts);
  22426. setPlayConfigDetails (numIns, numOuts, 0, 0);
  22427. initialised = AudioUnitInitialize (audioUnit) == noErr;
  22428. setLatencySamples (0);
  22429. }
  22430. void AudioUnitPluginInstance::prepareToPlay (double sampleRate_,
  22431. int samplesPerBlockExpected)
  22432. {
  22433. initialise();
  22434. if (initialised)
  22435. {
  22436. int numIns, numOuts;
  22437. getNumChannels (numIns, numOuts);
  22438. setPlayConfigDetails (numIns, numOuts, sampleRate_, samplesPerBlockExpected);
  22439. Float64 latencySecs = 0.0;
  22440. UInt32 latencySize = sizeof (latencySecs);
  22441. AudioUnitGetProperty (audioUnit, kAudioUnitProperty_Latency, kAudioUnitScope_Global,
  22442. 0, &latencySecs, &latencySize);
  22443. setLatencySamples (roundDoubleToInt (latencySecs * sampleRate_));
  22444. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  22445. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  22446. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  22447. AudioStreamBasicDescription stream;
  22448. zerostruct (stream);
  22449. stream.mSampleRate = sampleRate_;
  22450. stream.mFormatID = kAudioFormatLinearPCM;
  22451. stream.mFormatFlags = kAudioFormatFlagsNativeFloatPacked | kAudioFormatFlagIsNonInterleaved;
  22452. stream.mFramesPerPacket = 1;
  22453. stream.mBytesPerPacket = 4;
  22454. stream.mBytesPerFrame = 4;
  22455. stream.mBitsPerChannel = 32;
  22456. stream.mChannelsPerFrame = numIns;
  22457. OSStatus err = AudioUnitSetProperty (audioUnit,
  22458. kAudioUnitProperty_StreamFormat,
  22459. kAudioUnitScope_Input,
  22460. 0, &stream, sizeof (stream));
  22461. stream.mChannelsPerFrame = numOuts;
  22462. err = AudioUnitSetProperty (audioUnit,
  22463. kAudioUnitProperty_StreamFormat,
  22464. kAudioUnitScope_Output,
  22465. 0, &stream, sizeof (stream));
  22466. juce_free (outputBufferList);
  22467. outputBufferList = (AudioBufferList*) juce_calloc (sizeof (AudioBufferList) + sizeof (AudioBuffer) * (numOuts + 1));
  22468. outputBufferList->mNumberBuffers = numOuts;
  22469. for (int i = numOuts; --i >= 0;)
  22470. outputBufferList->mBuffers[i].mNumberChannels = 1;
  22471. zerostruct (timeStamp);
  22472. timeStamp.mSampleTime = 0;
  22473. timeStamp.mHostTime = AudioGetCurrentHostTime();
  22474. timeStamp.mFlags = kAudioTimeStampSampleTimeValid | kAudioTimeStampHostTimeValid;
  22475. currentBuffer = 0;
  22476. wasPlaying = false;
  22477. }
  22478. }
  22479. void AudioUnitPluginInstance::releaseResources()
  22480. {
  22481. if (initialised)
  22482. {
  22483. AudioUnitReset (audioUnit, kAudioUnitScope_Input, 0);
  22484. AudioUnitReset (audioUnit, kAudioUnitScope_Output, 0);
  22485. AudioUnitReset (audioUnit, kAudioUnitScope_Global, 0);
  22486. juce_free (outputBufferList);
  22487. outputBufferList = 0;
  22488. currentBuffer = 0;
  22489. }
  22490. }
  22491. OSStatus AudioUnitPluginInstance::renderGetInput (AudioUnitRenderActionFlags* ioActionFlags,
  22492. const AudioTimeStamp* inTimeStamp,
  22493. UInt32 inBusNumber,
  22494. UInt32 inNumberFrames,
  22495. AudioBufferList* ioData) const
  22496. {
  22497. if (inBusNumber == 0
  22498. && currentBuffer != 0)
  22499. {
  22500. jassert (inNumberFrames == currentBuffer->getNumSamples()); // if this ever happens, might need to add extra handling
  22501. for (int i = 0; i < ioData->mNumberBuffers; ++i)
  22502. {
  22503. if (i < currentBuffer->getNumChannels())
  22504. {
  22505. memcpy (ioData->mBuffers[i].mData,
  22506. currentBuffer->getSampleData (i, 0),
  22507. sizeof (float) * inNumberFrames);
  22508. }
  22509. else
  22510. {
  22511. zeromem (ioData->mBuffers[i].mData, sizeof (float) * inNumberFrames);
  22512. }
  22513. }
  22514. }
  22515. return noErr;
  22516. }
  22517. void AudioUnitPluginInstance::processBlock (AudioSampleBuffer& buffer,
  22518. MidiBuffer& midiMessages)
  22519. {
  22520. const int numSamples = buffer.getNumSamples();
  22521. if (initialised)
  22522. {
  22523. AudioUnitRenderActionFlags flags = 0;
  22524. timeStamp.mHostTime = AudioGetCurrentHostTime();
  22525. for (int i = getNumOutputChannels(); --i >= 0;)
  22526. {
  22527. outputBufferList->mBuffers[i].mDataByteSize = sizeof (float) * numSamples;
  22528. outputBufferList->mBuffers[i].mData = buffer.getSampleData (i, 0);
  22529. }
  22530. currentBuffer = &buffer;
  22531. if (wantsMidiMessages)
  22532. {
  22533. const uint8* midiEventData;
  22534. int midiEventSize, midiEventPosition;
  22535. MidiBuffer::Iterator i (midiMessages);
  22536. while (i.getNextEvent (midiEventData, midiEventSize, midiEventPosition))
  22537. {
  22538. if (midiEventSize <= 3)
  22539. MusicDeviceMIDIEvent (audioUnit,
  22540. midiEventData[0], midiEventData[1], midiEventData[2],
  22541. midiEventPosition);
  22542. else
  22543. MusicDeviceSysEx (audioUnit, midiEventData, midiEventSize);
  22544. }
  22545. midiMessages.clear();
  22546. }
  22547. AudioUnitRender (audioUnit, &flags, &timeStamp,
  22548. 0, numSamples, outputBufferList);
  22549. timeStamp.mSampleTime += numSamples;
  22550. }
  22551. else
  22552. {
  22553. // Not initialised, so just bypass..
  22554. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  22555. buffer.clear (i, 0, buffer.getNumSamples());
  22556. }
  22557. }
  22558. OSStatus AudioUnitPluginInstance::getBeatAndTempo (Float64* outCurrentBeat, Float64* outCurrentTempo) const
  22559. {
  22560. AudioPlayHead* const ph = getPlayHead();
  22561. AudioPlayHead::CurrentPositionInfo result;
  22562. if (ph != 0 && ph->getCurrentPosition (result))
  22563. {
  22564. *outCurrentBeat = result.ppqPosition;
  22565. *outCurrentTempo = result.bpm;
  22566. }
  22567. else
  22568. {
  22569. *outCurrentBeat = 0;
  22570. *outCurrentTempo = 120.0;
  22571. }
  22572. return noErr;
  22573. }
  22574. OSStatus AudioUnitPluginInstance::getMusicalTimeLocation (UInt32* outDeltaSampleOffsetToNextBeat,
  22575. Float32* outTimeSig_Numerator,
  22576. UInt32* outTimeSig_Denominator,
  22577. Float64* outCurrentMeasureDownBeat) const
  22578. {
  22579. AudioPlayHead* const ph = getPlayHead();
  22580. AudioPlayHead::CurrentPositionInfo result;
  22581. if (ph != 0 && ph->getCurrentPosition (result))
  22582. {
  22583. *outTimeSig_Numerator = result.timeSigNumerator;
  22584. *outTimeSig_Denominator = result.timeSigDenominator;
  22585. *outDeltaSampleOffsetToNextBeat = 0; //xxx
  22586. *outCurrentMeasureDownBeat = result.ppqPositionOfLastBarStart; //xxx wrong
  22587. }
  22588. else
  22589. {
  22590. *outDeltaSampleOffsetToNextBeat = 0;
  22591. *outTimeSig_Numerator = 4;
  22592. *outTimeSig_Denominator = 4;
  22593. *outCurrentMeasureDownBeat = 0;
  22594. }
  22595. return noErr;
  22596. }
  22597. OSStatus AudioUnitPluginInstance::getTransportState (Boolean* outIsPlaying,
  22598. Boolean* outTransportStateChanged,
  22599. Float64* outCurrentSampleInTimeLine,
  22600. Boolean* outIsCycling,
  22601. Float64* outCycleStartBeat,
  22602. Float64* outCycleEndBeat)
  22603. {
  22604. AudioPlayHead* const ph = getPlayHead();
  22605. AudioPlayHead::CurrentPositionInfo result;
  22606. if (ph != 0 && ph->getCurrentPosition (result))
  22607. {
  22608. *outIsPlaying = result.isPlaying;
  22609. *outTransportStateChanged = result.isPlaying != wasPlaying;
  22610. wasPlaying = result.isPlaying;
  22611. *outCurrentSampleInTimeLine = roundDoubleToInt (result.timeInSeconds * getSampleRate());
  22612. *outIsCycling = false;
  22613. *outCycleStartBeat = 0;
  22614. *outCycleEndBeat = 0;
  22615. }
  22616. else
  22617. {
  22618. *outIsPlaying = false;
  22619. *outTransportStateChanged = false;
  22620. *outCurrentSampleInTimeLine = 0;
  22621. *outIsCycling = false;
  22622. *outCycleStartBeat = 0;
  22623. *outCycleEndBeat = 0;
  22624. }
  22625. return noErr;
  22626. }
  22627. static VoidArray activeWindows;
  22628. class AudioUnitPluginWindow : public AudioProcessorEditor,
  22629. public Timer
  22630. {
  22631. public:
  22632. AudioUnitPluginWindow (AudioUnitPluginInstance& plugin_)
  22633. : AudioProcessorEditor (&plugin_),
  22634. plugin (plugin_),
  22635. isOpen (false),
  22636. pluginWantsKeys (false),
  22637. wasShowing (false),
  22638. recursiveResize (false),
  22639. viewComponent (0),
  22640. pluginViewRef (0)
  22641. {
  22642. movementWatcher = new CompMovementWatcher (this);
  22643. activeWindows.add (this);
  22644. setOpaque (true);
  22645. setVisible (true);
  22646. setSize (1, 1);
  22647. ComponentDescription viewList [16];
  22648. UInt32 viewListSize = sizeof (viewList);
  22649. AudioUnitGetProperty (plugin.audioUnit, kAudioUnitProperty_GetUIComponentList, kAudioUnitScope_Global,
  22650. 0, &viewList, &viewListSize);
  22651. componentRecord = FindNextComponent (0, &viewList[0]);
  22652. }
  22653. ~AudioUnitPluginWindow()
  22654. {
  22655. deleteAndZero (movementWatcher);
  22656. closePluginWindow();
  22657. activeWindows.removeValue (this);
  22658. plugin.editorBeingDeleted (this);
  22659. }
  22660. bool isValid() const throw() { return componentRecord != 0; }
  22661. void componentMovedOrResized()
  22662. {
  22663. if (recursiveResize)
  22664. return;
  22665. Component* const topComp = getTopLevelComponent();
  22666. if (topComp->getPeer() != 0)
  22667. {
  22668. int x = 0, y = 0;
  22669. relativePositionToOtherComponent (topComp, x, y);
  22670. recursiveResize = true;
  22671. if (pluginViewRef != 0)
  22672. {
  22673. HIRect r;
  22674. r.origin.x = (float) x;
  22675. r.origin.y = (float) y;
  22676. r.size.width = (float) getWidth();
  22677. r.size.height = (float) getHeight();
  22678. HIViewSetFrame (pluginViewRef, &r);
  22679. }
  22680. recursiveResize = false;
  22681. }
  22682. }
  22683. void componentVisibilityChanged()
  22684. {
  22685. const bool isShowingNow = isShowing();
  22686. if (wasShowing != isShowingNow)
  22687. {
  22688. wasShowing = isShowingNow;
  22689. if (isShowingNow)
  22690. openPluginWindow();
  22691. else
  22692. closePluginWindow();
  22693. }
  22694. componentMovedOrResized();
  22695. }
  22696. void componentPeerChanged()
  22697. {
  22698. closePluginWindow();
  22699. openPluginWindow();
  22700. }
  22701. void timerCallback()
  22702. {
  22703. if (pluginViewRef != 0)
  22704. {
  22705. HIRect bounds;
  22706. HIViewGetBounds (pluginViewRef, &bounds);
  22707. const int w = jmax (32, (int) bounds.size.width);
  22708. const int h = jmax (32, (int) bounds.size.height);
  22709. if (w != getWidth() || h != getHeight())
  22710. {
  22711. setSize (w, h);
  22712. startTimer (50);
  22713. }
  22714. else
  22715. {
  22716. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  22717. }
  22718. }
  22719. }
  22720. bool keyStateChanged()
  22721. {
  22722. return pluginWantsKeys;
  22723. }
  22724. bool keyPressed (const KeyPress&)
  22725. {
  22726. return pluginWantsKeys;
  22727. }
  22728. void paint (Graphics& g)
  22729. {
  22730. if (isOpen)
  22731. {
  22732. ComponentPeer* const peer = getPeer();
  22733. if (peer != 0)
  22734. {
  22735. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  22736. getScreenY() - peer->getScreenY(),
  22737. getWidth(), getHeight());
  22738. }
  22739. }
  22740. else
  22741. {
  22742. g.fillAll (Colours::black);
  22743. }
  22744. }
  22745. void broughtToFront()
  22746. {
  22747. activeWindows.removeValue (this);
  22748. activeWindows.add (this);
  22749. }
  22750. juce_UseDebuggingNewOperator
  22751. private:
  22752. AudioUnitPluginInstance& plugin;
  22753. bool isOpen, wasShowing, recursiveResize;
  22754. bool pluginWantsKeys;
  22755. ComponentRecord* componentRecord;
  22756. AudioUnitCarbonView viewComponent;
  22757. HIViewRef pluginViewRef;
  22758. void openPluginWindow()
  22759. {
  22760. if (isOpen || getWindowHandle() == 0 || componentRecord == 0)
  22761. return;
  22762. log (T("Opening AU GUI: ") + plugin.getName());
  22763. isOpen = true;
  22764. pluginWantsKeys = true; //xxx any way to find this out? Does it matter?
  22765. viewComponent = (AudioUnitCarbonView) OpenComponent (componentRecord);
  22766. if (viewComponent != 0)
  22767. {
  22768. Float32Point pos = { getScreenX() - getTopLevelComponent()->getScreenX(),
  22769. getScreenY() - getTopLevelComponent()->getScreenY() };
  22770. Float32Point size = { 250, 200 };
  22771. AudioUnitCarbonViewCreate (viewComponent,
  22772. plugin.audioUnit,
  22773. (WindowRef) getWindowHandle(),
  22774. HIViewGetRoot ((WindowRef) getWindowHandle()),
  22775. &pos, &size,
  22776. (ControlRef*) &pluginViewRef);
  22777. }
  22778. timerCallback(); // to set our comp to the right size
  22779. repaint();
  22780. }
  22781. void closePluginWindow()
  22782. {
  22783. stopTimer();
  22784. if (isOpen)
  22785. {
  22786. log (T("Closing AU GUI: ") + plugin.getName());
  22787. isOpen = false;
  22788. if (viewComponent != 0)
  22789. CloseComponent (viewComponent);
  22790. pluginViewRef = 0;
  22791. }
  22792. }
  22793. class CompMovementWatcher : public ComponentMovementWatcher
  22794. {
  22795. public:
  22796. CompMovementWatcher (AudioUnitPluginWindow* const owner_)
  22797. : ComponentMovementWatcher (owner_),
  22798. owner (owner_)
  22799. {
  22800. }
  22801. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  22802. {
  22803. owner->componentMovedOrResized();
  22804. }
  22805. void componentPeerChanged()
  22806. {
  22807. owner->componentPeerChanged();
  22808. }
  22809. void componentVisibilityChanged (Component&)
  22810. {
  22811. owner->componentVisibilityChanged();
  22812. }
  22813. private:
  22814. AudioUnitPluginWindow* const owner;
  22815. };
  22816. CompMovementWatcher* movementWatcher;
  22817. };
  22818. AudioProcessorEditor* AudioUnitPluginInstance::createEditor()
  22819. {
  22820. AudioUnitPluginWindow* w = new AudioUnitPluginWindow (*this);
  22821. if (! w->isValid())
  22822. deleteAndZero (w);
  22823. return w;
  22824. }
  22825. const String AudioUnitPluginInstance::getCategory() const
  22826. {
  22827. const char* result = 0;
  22828. switch (componentDesc.componentType)
  22829. {
  22830. case kAudioUnitType_Effect:
  22831. case kAudioUnitType_MusicEffect:
  22832. result = "Effect";
  22833. break;
  22834. case kAudioUnitType_MusicDevice:
  22835. result = "Synth";
  22836. break;
  22837. case kAudioUnitType_Generator:
  22838. result = "Generator";
  22839. break;
  22840. case kAudioUnitType_Panner:
  22841. result = "Panner";
  22842. break;
  22843. default:
  22844. break;
  22845. }
  22846. return result;
  22847. }
  22848. int AudioUnitPluginInstance::getNumParameters()
  22849. {
  22850. return parameterIds.size();
  22851. }
  22852. float AudioUnitPluginInstance::getParameter (int index)
  22853. {
  22854. const ScopedLock sl (lock);
  22855. Float32 value = 0.0f;
  22856. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  22857. {
  22858. AudioUnitGetParameter (audioUnit,
  22859. (UInt32) parameterIds.getUnchecked (index),
  22860. kAudioUnitScope_Global, 0,
  22861. &value);
  22862. }
  22863. return value;
  22864. }
  22865. void AudioUnitPluginInstance::setParameter (int index, float newValue)
  22866. {
  22867. const ScopedLock sl (lock);
  22868. if (audioUnit != 0 && ((unsigned int) index) < (unsigned int) parameterIds.size())
  22869. {
  22870. AudioUnitSetParameter (audioUnit,
  22871. (UInt32) parameterIds.getUnchecked (index),
  22872. kAudioUnitScope_Global, 0,
  22873. newValue, 0);
  22874. }
  22875. }
  22876. const String AudioUnitPluginInstance::getParameterName (int index)
  22877. {
  22878. AudioUnitParameterInfo info;
  22879. zerostruct (info);
  22880. UInt32 sz = sizeof (info);
  22881. String name;
  22882. if (AudioUnitGetProperty (audioUnit,
  22883. kAudioUnitProperty_ParameterInfo,
  22884. kAudioUnitScope_Global,
  22885. parameterIds [index], &info, &sz) == noErr)
  22886. {
  22887. if ((info.flags & kAudioUnitParameterFlag_HasCFNameString) != 0)
  22888. name = PlatformUtilities::cfStringToJuceString (info.cfNameString);
  22889. else
  22890. name = String (info.name, sizeof (info.name));
  22891. }
  22892. return name;
  22893. }
  22894. const String AudioUnitPluginInstance::getParameterText (int index)
  22895. {
  22896. return String (getParameter (index));
  22897. }
  22898. bool AudioUnitPluginInstance::isParameterAutomatable (int index) const
  22899. {
  22900. AudioUnitParameterInfo info;
  22901. UInt32 sz = sizeof (info);
  22902. if (AudioUnitGetProperty (audioUnit,
  22903. kAudioUnitProperty_ParameterInfo,
  22904. kAudioUnitScope_Global,
  22905. parameterIds [index], &info, &sz) == noErr)
  22906. {
  22907. return (info.flags & kAudioUnitParameterFlag_NonRealTime) == 0;
  22908. }
  22909. return true;
  22910. }
  22911. int AudioUnitPluginInstance::getNumPrograms()
  22912. {
  22913. CFArrayRef presets;
  22914. UInt32 sz = sizeof (CFArrayRef);
  22915. int num = 0;
  22916. if (AudioUnitGetProperty (audioUnit,
  22917. kAudioUnitProperty_FactoryPresets,
  22918. kAudioUnitScope_Global,
  22919. 0, &presets, &sz) == noErr)
  22920. {
  22921. num = (int) CFArrayGetCount (presets);
  22922. CFRelease (presets);
  22923. }
  22924. return num;
  22925. }
  22926. int AudioUnitPluginInstance::getCurrentProgram()
  22927. {
  22928. AUPreset current;
  22929. current.presetNumber = 0;
  22930. UInt32 sz = sizeof (AUPreset);
  22931. AudioUnitGetProperty (audioUnit,
  22932. kAudioUnitProperty_FactoryPresets,
  22933. kAudioUnitScope_Global,
  22934. 0, &current, &sz);
  22935. return current.presetNumber;
  22936. }
  22937. void AudioUnitPluginInstance::setCurrentProgram (int newIndex)
  22938. {
  22939. AUPreset current;
  22940. current.presetNumber = newIndex;
  22941. current.presetName = 0;
  22942. AudioUnitSetProperty (audioUnit,
  22943. kAudioUnitProperty_FactoryPresets,
  22944. kAudioUnitScope_Global,
  22945. 0, &current, sizeof (AUPreset));
  22946. }
  22947. const String AudioUnitPluginInstance::getProgramName (int index)
  22948. {
  22949. String s;
  22950. CFArrayRef presets;
  22951. UInt32 sz = sizeof (CFArrayRef);
  22952. if (AudioUnitGetProperty (audioUnit,
  22953. kAudioUnitProperty_FactoryPresets,
  22954. kAudioUnitScope_Global,
  22955. 0, &presets, &sz) == noErr)
  22956. {
  22957. for (CFIndex i = 0; i < CFArrayGetCount (presets); ++i)
  22958. {
  22959. const AUPreset* p = (const AUPreset*) CFArrayGetValueAtIndex (presets, i);
  22960. if (p != 0 && p->presetNumber == index)
  22961. {
  22962. s = PlatformUtilities::cfStringToJuceString (p->presetName);
  22963. break;
  22964. }
  22965. }
  22966. CFRelease (presets);
  22967. }
  22968. return s;
  22969. }
  22970. void AudioUnitPluginInstance::changeProgramName (int index, const String& newName)
  22971. {
  22972. jassertfalse // xxx not implemented!
  22973. }
  22974. const String AudioUnitPluginInstance::getInputChannelName (const int index) const
  22975. {
  22976. if (((unsigned int) index) < (unsigned int) getNumInputChannels())
  22977. return T("Input ") + String (index + 1);
  22978. return String::empty;
  22979. }
  22980. bool AudioUnitPluginInstance::isInputChannelStereoPair (int index) const
  22981. {
  22982. if (((unsigned int) index) >= (unsigned int) getNumInputChannels())
  22983. return false;
  22984. return true;
  22985. }
  22986. const String AudioUnitPluginInstance::getOutputChannelName (const int index) const
  22987. {
  22988. if (((unsigned int) index) < (unsigned int) getNumOutputChannels())
  22989. return T("Output ") + String (index + 1);
  22990. return String::empty;
  22991. }
  22992. bool AudioUnitPluginInstance::isOutputChannelStereoPair (int index) const
  22993. {
  22994. if (((unsigned int) index) >= (unsigned int) getNumOutputChannels())
  22995. return false;
  22996. return true;
  22997. }
  22998. void AudioUnitPluginInstance::getStateInformation (MemoryBlock& destData)
  22999. {
  23000. getCurrentProgramStateInformation (destData);
  23001. }
  23002. void AudioUnitPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  23003. {
  23004. CFPropertyListRef propertyList = 0;
  23005. UInt32 sz = sizeof (CFPropertyListRef);
  23006. if (AudioUnitGetProperty (audioUnit,
  23007. kAudioUnitProperty_ClassInfo,
  23008. kAudioUnitScope_Global,
  23009. 0, &propertyList, &sz) == noErr)
  23010. {
  23011. CFWriteStreamRef stream = CFWriteStreamCreateWithAllocatedBuffers (kCFAllocatorDefault, kCFAllocatorDefault);
  23012. CFWriteStreamOpen (stream);
  23013. CFIndex bytesWritten = CFPropertyListWriteToStream (propertyList, stream, kCFPropertyListBinaryFormat_v1_0, 0);
  23014. CFWriteStreamClose (stream);
  23015. CFDataRef data = (CFDataRef) CFWriteStreamCopyProperty (stream, kCFStreamPropertyDataWritten);
  23016. destData.setSize (bytesWritten);
  23017. destData.copyFrom (CFDataGetBytePtr (data), 0, destData.getSize());
  23018. CFRelease (data);
  23019. CFRelease (stream);
  23020. CFRelease (propertyList);
  23021. }
  23022. }
  23023. void AudioUnitPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  23024. {
  23025. setCurrentProgramStateInformation (data, sizeInBytes);
  23026. }
  23027. void AudioUnitPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  23028. {
  23029. CFReadStreamRef stream = CFReadStreamCreateWithBytesNoCopy (kCFAllocatorDefault,
  23030. (const UInt8*) data,
  23031. sizeInBytes,
  23032. kCFAllocatorNull);
  23033. CFReadStreamOpen (stream);
  23034. CFPropertyListFormat format = kCFPropertyListBinaryFormat_v1_0;
  23035. CFPropertyListRef propertyList = CFPropertyListCreateFromStream (kCFAllocatorDefault,
  23036. stream,
  23037. 0,
  23038. kCFPropertyListImmutable,
  23039. &format,
  23040. 0);
  23041. CFRelease (stream);
  23042. if (propertyList != 0)
  23043. AudioUnitSetProperty (audioUnit,
  23044. kAudioUnitProperty_ClassInfo,
  23045. kAudioUnitScope_Global,
  23046. 0, &propertyList, sizeof (propertyList));
  23047. }
  23048. AudioUnitPluginFormat::AudioUnitPluginFormat()
  23049. {
  23050. }
  23051. AudioUnitPluginFormat::~AudioUnitPluginFormat()
  23052. {
  23053. }
  23054. void AudioUnitPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  23055. const File& file)
  23056. {
  23057. if (! fileMightContainThisPluginType (file))
  23058. return;
  23059. PluginDescription desc;
  23060. desc.file = file;
  23061. desc.uid = 0;
  23062. AudioUnitPluginInstance* instance = dynamic_cast <AudioUnitPluginInstance*> (createInstanceFromDescription (desc));
  23063. if (instance == 0)
  23064. return;
  23065. try
  23066. {
  23067. instance->fillInPluginDescription (desc);
  23068. results.add (new PluginDescription (desc));
  23069. }
  23070. catch (...)
  23071. {
  23072. // crashed while loading...
  23073. }
  23074. deleteAndZero (instance);
  23075. }
  23076. AudioPluginInstance* AudioUnitPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  23077. {
  23078. AudioUnitPluginInstance* result = 0;
  23079. if (fileMightContainThisPluginType (desc.file))
  23080. {
  23081. result = new AudioUnitPluginInstance (desc.file);
  23082. if (result->audioUnit != 0)
  23083. {
  23084. result->initialise();
  23085. }
  23086. else
  23087. {
  23088. deleteAndZero (result);
  23089. }
  23090. }
  23091. return result;
  23092. }
  23093. bool AudioUnitPluginFormat::fileMightContainThisPluginType (const File& f)
  23094. {
  23095. return f.hasFileExtension (T(".component"))
  23096. && f.isDirectory();
  23097. }
  23098. const FileSearchPath AudioUnitPluginFormat::getDefaultLocationsToSearch()
  23099. {
  23100. return FileSearchPath ("~/Library/Audio/Plug-Ins/Components;/Library/Audio/Plug-Ins/Components");
  23101. }
  23102. #endif
  23103. END_JUCE_NAMESPACE
  23104. #undef log
  23105. #endif
  23106. /********* End of inlined file: juce_AudioUnitPluginFormat.cpp *********/
  23107. /********* Start of inlined file: juce_VSTPluginFormat.mm *********/
  23108. // This file just wraps juce_VSTPluginFormat.cpp in an objective-C wrapper
  23109. #define JUCE_MAC_VST_INCLUDED 1
  23110. /********* Start of inlined file: juce_VSTPluginFormat.cpp *********/
  23111. /********* Start of inlined file: juce_Config.h *********/
  23112. #ifndef __JUCE_CONFIG_JUCEHEADER__
  23113. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  23114. /*
  23115. This file contains macros that enable/disable various JUCE features.
  23116. */
  23117. /** The name of the namespace that all Juce classes and functions will be
  23118. put inside. If this is not defined, no namespace will be used.
  23119. */
  23120. #ifndef JUCE_NAMESPACE
  23121. #define JUCE_NAMESPACE juce
  23122. #endif
  23123. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  23124. but if you define this value, you can override this can force it to be true or
  23125. false.
  23126. */
  23127. #ifndef JUCE_FORCE_DEBUG
  23128. //#define JUCE_FORCE_DEBUG 1
  23129. #endif
  23130. /** If this flag is enabled, the the jassert and jassertfalse macros will
  23131. always use Logger::writeToLog() to write a message when an assertion happens.
  23132. Enabling it will also leave this turned on in release builds. When it's disabled,
  23133. however, the jassert and jassertfalse macros will not be compiled in a
  23134. release build.
  23135. @see jassert, jassertfalse, Logger
  23136. */
  23137. #ifndef JUCE_LOG_ASSERTIONS
  23138. // #define JUCE_LOG_ASSERTIONS 1
  23139. #endif
  23140. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  23141. which the ASIOAudioIODevice class can't be built. See the comments in the
  23142. ASIOAudioIODevice class's header file for more info about this.
  23143. (This only affects a Win32 build)
  23144. */
  23145. #ifndef JUCE_ASIO
  23146. #define JUCE_ASIO 1
  23147. #endif
  23148. /** Comment out this macro to disable building of ALSA device support on Linux.
  23149. */
  23150. #ifndef JUCE_ALSA
  23151. #define JUCE_ALSA 1
  23152. #endif
  23153. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  23154. have the SDK installed.
  23155. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  23156. classes will be unavailable.
  23157. On Windows, if you enable this, you'll need to have the QuickTime SDK
  23158. installed, and its header files will need to be on your include path.
  23159. */
  23160. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  23161. #define JUCE_QUICKTIME 1
  23162. #endif
  23163. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  23164. have the appropriate headers and libraries available. If it's not enabled, the
  23165. OpenGLComponent class will be unavailable.
  23166. */
  23167. #ifndef JUCE_OPENGL
  23168. #define JUCE_OPENGL 1
  23169. #endif
  23170. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  23171. If you're not going to need either of these formats, turn off the flags to
  23172. avoid bloating your codebase with them.
  23173. */
  23174. #ifndef JUCE_USE_FLAC
  23175. #define JUCE_USE_FLAC 1
  23176. #endif
  23177. #ifndef JUCE_USE_OGGVORBIS
  23178. #define JUCE_USE_OGGVORBIS 1
  23179. #endif
  23180. /** This flag lets you enable support for CD-burning. You might want to disable
  23181. it to build without the MS SDK under windows.
  23182. */
  23183. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  23184. #define JUCE_USE_CDBURNER 1
  23185. #endif
  23186. /** Enabling this macro means that all regions that get repainted will have a coloured
  23187. line drawn around them.
  23188. This is handy if you're trying to optimise drawing, because it lets you easily see
  23189. when anything is being repainted unnecessarily.
  23190. */
  23191. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  23192. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  23193. #endif
  23194. /** Enable this under Linux to use Xinerama for multi-monitor support.
  23195. */
  23196. #ifndef JUCE_USE_XINERAMA
  23197. #define JUCE_USE_XINERAMA 1
  23198. #endif
  23199. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  23200. */
  23201. #ifndef JUCE_USE_XSHM
  23202. #define JUCE_USE_XSHM 1
  23203. #endif
  23204. /** Enabling this builds support for VST audio plugins.
  23205. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  23206. */
  23207. #ifndef JUCE_PLUGINHOST_VST
  23208. // #define JUCE_PLUGINHOST_VST 1
  23209. #endif
  23210. /** Enabling this builds support for AudioUnit audio plugins.
  23211. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  23212. */
  23213. #ifndef JUCE_PLUGINHOST_AU
  23214. // #define JUCE_PLUGINHOST_AU 1
  23215. #endif
  23216. /** Disabling this will avoid linking to any UI code. This is handy for
  23217. writing command-line utilities, e.g. on linux boxes which don't have some
  23218. of the UI libraries installed.
  23219. (On mac and windows, this won't generally make much difference to the build).
  23220. */
  23221. #ifndef JUCE_BUILD_GUI_CLASSES
  23222. #define JUCE_BUILD_GUI_CLASSES 1
  23223. #endif
  23224. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  23225. */
  23226. #ifndef JUCE_WEB_BROWSER
  23227. #define JUCE_WEB_BROWSER 1
  23228. #endif
  23229. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  23230. codebase - you might need to use this if you're linking to some of these libraries
  23231. yourself.
  23232. */
  23233. #ifndef JUCE_INCLUDE_ZLIB_CODE
  23234. #define JUCE_INCLUDE_ZLIB_CODE 1
  23235. #endif
  23236. #ifndef JUCE_INCLUDE_FLAC_CODE
  23237. #define JUCE_INCLUDE_FLAC_CODE 1
  23238. #endif
  23239. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  23240. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  23241. #endif
  23242. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  23243. #define JUCE_INCLUDE_PNGLIB_CODE 1
  23244. #endif
  23245. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  23246. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  23247. #endif
  23248. /** Enable this to add extra memory-leak info to the new and delete operators.
  23249. (Currently, this only affects Windows builds in debug mode).
  23250. */
  23251. #ifndef JUCE_CHECK_MEMORY_LEAKS
  23252. #define JUCE_CHECK_MEMORY_LEAKS 1
  23253. #endif
  23254. /** Enable this to turn on juce's internal catching of exceptions.
  23255. Turning it off will avoid any exception catching. With it on, all exceptions
  23256. are passed to the JUCEApplication::unhandledException() callback for logging.
  23257. */
  23258. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  23259. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  23260. #endif
  23261. /** If this macro is set, the Juce String class will use unicode as its
  23262. internal representation. If it isn't set, it'll use ANSI.
  23263. */
  23264. #ifndef JUCE_STRINGS_ARE_UNICODE
  23265. #define JUCE_STRINGS_ARE_UNICODE 1
  23266. #endif
  23267. #endif
  23268. /********* End of inlined file: juce_Config.h *********/
  23269. #if JUCE_PLUGINHOST_VST && (JUCE_MAC || JUCE_WIN32)
  23270. #ifdef _WIN32
  23271. #undef _WIN32_WINNT
  23272. #define _WIN32_WINNT 0x500
  23273. #undef STRICT
  23274. #define STRICT
  23275. #include <windows.h>
  23276. #include <float.h>
  23277. #pragma warning (disable : 4312 4355)
  23278. #elif defined (LINUX)
  23279. #include <float.h>
  23280. #include <sys/time.h>
  23281. #include <X11/Xlib.h>
  23282. #include <X11/Xutil.h>
  23283. #include <X11/Xatom.h>
  23284. #undef Font
  23285. #undef KeyPress
  23286. #undef Drawable
  23287. #undef Time
  23288. #else
  23289. #ifndef JUCE_MAC_VST_INCLUDED
  23290. // On the mac, this file needs to be compiled indirectly, by using
  23291. // juce_VSTPluginFormat.mm instead - that wraps it as an objective-C file for cocoa
  23292. #error
  23293. #endif
  23294. #include <Cocoa/Cocoa.h>
  23295. #include <Carbon/Carbon.h>
  23296. #endif
  23297. #if ! (JUCE_MAC && JUCE_64BIT)
  23298. BEGIN_JUCE_NAMESPACE
  23299. #if JUCE_MAC
  23300. /********* Start of inlined file: juce_mac_CarbonViewWrapperComponent.h *********/
  23301. /** Creates a floating carbon window that can be used to hold a carbon UI.
  23302. This is a handy class that's designed to be inlined where needed, e.g.
  23303. in the audio plugin hosting code.
  23304. */
  23305. class CarbonViewWrapperComponent : public Component,
  23306. public ComponentMovementWatcher,
  23307. public Timer
  23308. {
  23309. public:
  23310. CarbonViewWrapperComponent()
  23311. : ComponentMovementWatcher (this),
  23312. wrapperWindow (0),
  23313. embeddedView (0),
  23314. recursiveResize (false)
  23315. {
  23316. }
  23317. virtual ~CarbonViewWrapperComponent()
  23318. {
  23319. jassert (embeddedView == 0); // must call deleteWindow() in the subclass's destructor!
  23320. }
  23321. virtual HIViewRef attachView (WindowRef windowRef, HIViewRef rootView) = 0;
  23322. virtual void removeView (HIViewRef embeddedView) = 0;
  23323. virtual void mouseDown (int x, int y) {}
  23324. virtual void paint() {}
  23325. virtual bool getEmbeddedViewSize (int& w, int& h)
  23326. {
  23327. if (embeddedView == 0)
  23328. return false;
  23329. HIRect bounds;
  23330. HIViewGetBounds (embeddedView, &bounds);
  23331. w = jmax (1, roundFloatToInt (bounds.size.width));
  23332. h = jmax (1, roundFloatToInt (bounds.size.height));
  23333. return true;
  23334. }
  23335. void createWindow()
  23336. {
  23337. if (wrapperWindow == 0)
  23338. {
  23339. Rect r;
  23340. r.left = getScreenX();
  23341. r.top = getScreenY();
  23342. r.right = r.left + getWidth();
  23343. r.bottom = r.top + getHeight();
  23344. CreateNewWindow (kDocumentWindowClass,
  23345. (WindowAttributes) (kWindowStandardHandlerAttribute | kWindowCompositingAttribute
  23346. | kWindowNoShadowAttribute | kWindowNoTitleBarAttribute),
  23347. &r, &wrapperWindow);
  23348. jassert (wrapperWindow != 0);
  23349. if (wrapperWindow == 0)
  23350. return;
  23351. NSWindow* carbonWindow = [[NSWindow alloc] initWithWindowRef: wrapperWindow];
  23352. NSWindow* ownerWindow = [((NSView*) getWindowHandle()) window];
  23353. [ownerWindow addChildWindow: carbonWindow
  23354. ordered: NSWindowAbove];
  23355. embeddedView = attachView (wrapperWindow, HIViewGetRoot (wrapperWindow));
  23356. EventTypeSpec windowEventTypes[] = { { kEventClassWindow, kEventWindowGetClickActivation },
  23357. { kEventClassWindow, kEventWindowHandleDeactivate } };
  23358. EventHandlerUPP upp = NewEventHandlerUPP (carbonEventCallback);
  23359. InstallWindowEventHandler (wrapperWindow, upp,
  23360. sizeof (windowEventTypes) / sizeof (EventTypeSpec),
  23361. windowEventTypes, this, &eventHandlerRef);
  23362. setOurSizeToEmbeddedViewSize();
  23363. setEmbeddedWindowToOurSize();
  23364. }
  23365. }
  23366. void deleteWindow()
  23367. {
  23368. removeView (embeddedView);
  23369. embeddedView = 0;
  23370. if (wrapperWindow != 0)
  23371. {
  23372. RemoveEventHandler (eventHandlerRef);
  23373. DisposeWindow (wrapperWindow);
  23374. wrapperWindow = 0;
  23375. }
  23376. }
  23377. void setOurSizeToEmbeddedViewSize()
  23378. {
  23379. int w, h;
  23380. if (getEmbeddedViewSize (w, h))
  23381. {
  23382. if (w != getWidth() || h != getHeight())
  23383. {
  23384. startTimer (50);
  23385. setSize (w, h);
  23386. if (getParentComponent() != 0)
  23387. getParentComponent()->setSize (w, h);
  23388. }
  23389. else
  23390. {
  23391. startTimer (jlimit (50, 500, getTimerInterval() + 20));
  23392. }
  23393. }
  23394. else
  23395. {
  23396. stopTimer();
  23397. }
  23398. }
  23399. void setEmbeddedWindowToOurSize()
  23400. {
  23401. if (! recursiveResize)
  23402. {
  23403. recursiveResize = true;
  23404. if (embeddedView != 0)
  23405. {
  23406. HIRect r;
  23407. r.origin.x = 0;
  23408. r.origin.y = 0;
  23409. r.size.width = (float) getWidth();
  23410. r.size.height = (float) getHeight();
  23411. HIViewSetFrame (embeddedView, &r);
  23412. }
  23413. if (wrapperWindow != 0)
  23414. {
  23415. Rect wr;
  23416. wr.left = getScreenX();
  23417. wr.top = getScreenY();
  23418. wr.right = wr.left + getWidth();
  23419. wr.bottom = wr.top + getHeight();
  23420. SetWindowBounds (wrapperWindow, kWindowContentRgn, &wr);
  23421. ShowWindow (wrapperWindow);
  23422. }
  23423. recursiveResize = false;
  23424. }
  23425. }
  23426. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  23427. {
  23428. setEmbeddedWindowToOurSize();
  23429. }
  23430. void componentPeerChanged()
  23431. {
  23432. deleteWindow();
  23433. createWindow();
  23434. }
  23435. void componentVisibilityChanged (Component&)
  23436. {
  23437. if (isShowing())
  23438. createWindow();
  23439. else
  23440. deleteWindow();
  23441. setEmbeddedWindowToOurSize();
  23442. }
  23443. void timerCallback()
  23444. {
  23445. setOurSizeToEmbeddedViewSize();
  23446. }
  23447. OSStatus carbonEventHandler (EventHandlerCallRef nextHandlerRef,
  23448. EventRef event)
  23449. {
  23450. switch (GetEventKind (event))
  23451. {
  23452. case kEventWindowHandleDeactivate:
  23453. ActivateWindow (wrapperWindow, TRUE);
  23454. break;
  23455. case kEventWindowGetClickActivation:
  23456. {
  23457. getTopLevelComponent()->toFront (false);
  23458. ClickActivationResult howToHandleClick = kActivateAndHandleClick;
  23459. SetEventParameter (event, kEventParamClickActivation, typeClickActivationResult,
  23460. sizeof (ClickActivationResult), &howToHandleClick);
  23461. }
  23462. break;
  23463. }
  23464. return noErr;
  23465. }
  23466. static pascal OSStatus carbonEventCallback (EventHandlerCallRef nextHandlerRef,
  23467. EventRef event, void* userData)
  23468. {
  23469. return ((CarbonViewWrapperComponent*) userData)->carbonEventHandler (nextHandlerRef, event);
  23470. }
  23471. protected:
  23472. WindowRef wrapperWindow;
  23473. HIViewRef embeddedView;
  23474. bool recursiveResize;
  23475. EventHandlerRef eventHandlerRef;
  23476. };
  23477. /********* End of inlined file: juce_mac_CarbonViewWrapperComponent.h *********/
  23478. #endif
  23479. #undef PRAGMA_ALIGN_SUPPORTED
  23480. #define VST_FORCE_DEPRECATED 0
  23481. #ifdef _MSC_VER
  23482. #pragma warning (push)
  23483. #pragma warning (disable: 4996)
  23484. #endif
  23485. /* Obviously you're going to need the Steinberg vstsdk2.4 folder in
  23486. your include path if you want to add VST support.
  23487. If you're not interested in VSTs, you can disable them by changing the
  23488. JUCE_PLUGINHOST_VST flag in juce_Config.h
  23489. */
  23490. #include "pluginterfaces/vst2.x/aeffectx.h"
  23491. #ifdef _MSC_VER
  23492. #pragma warning (pop)
  23493. #endif
  23494. #if JUCE_LINUX
  23495. #define Font JUCE_NAMESPACE::Font
  23496. #define KeyPress JUCE_NAMESPACE::KeyPress
  23497. #define Drawable JUCE_NAMESPACE::Drawable
  23498. #define Time JUCE_NAMESPACE::Time
  23499. #endif
  23500. #if ! JUCE_WIN32
  23501. #define _fpreset()
  23502. #define _clearfp()
  23503. #endif
  23504. extern void juce_callAnyTimersSynchronously();
  23505. const int fxbVersionNum = 1;
  23506. struct fxProgram
  23507. {
  23508. long chunkMagic; // 'CcnK'
  23509. long byteSize; // of this chunk, excl. magic + byteSize
  23510. long fxMagic; // 'FxCk'
  23511. long version;
  23512. long fxID; // fx unique id
  23513. long fxVersion;
  23514. long numParams;
  23515. char prgName[28];
  23516. float params[1]; // variable no. of parameters
  23517. };
  23518. struct fxSet
  23519. {
  23520. long chunkMagic; // 'CcnK'
  23521. long byteSize; // of this chunk, excl. magic + byteSize
  23522. long fxMagic; // 'FxBk'
  23523. long version;
  23524. long fxID; // fx unique id
  23525. long fxVersion;
  23526. long numPrograms;
  23527. char future[128];
  23528. fxProgram programs[1]; // variable no. of programs
  23529. };
  23530. struct fxChunkSet
  23531. {
  23532. long chunkMagic; // 'CcnK'
  23533. long byteSize; // of this chunk, excl. magic + byteSize
  23534. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  23535. long version;
  23536. long fxID; // fx unique id
  23537. long fxVersion;
  23538. long numPrograms;
  23539. char future[128];
  23540. long chunkSize;
  23541. char chunk[8]; // variable
  23542. };
  23543. struct fxProgramSet
  23544. {
  23545. long chunkMagic; // 'CcnK'
  23546. long byteSize; // of this chunk, excl. magic + byteSize
  23547. long fxMagic; // 'FxCh', 'FPCh', or 'FBCh'
  23548. long version;
  23549. long fxID; // fx unique id
  23550. long fxVersion;
  23551. long numPrograms;
  23552. char name[28];
  23553. long chunkSize;
  23554. char chunk[8]; // variable
  23555. };
  23556. #ifdef JUCE_LITTLE_ENDIAN
  23557. static long vst_swap (const long x) throw() { return (long) swapByteOrder ((uint32) x); }
  23558. static float vst_swapFloat (const float x) throw()
  23559. {
  23560. union { uint32 asInt; float asFloat; } n;
  23561. n.asFloat = x;
  23562. n.asInt = swapByteOrder (n.asInt);
  23563. return n.asFloat;
  23564. }
  23565. #else
  23566. #define vst_swap(x) (x)
  23567. #define vst_swapFloat(x) (x)
  23568. #endif
  23569. typedef AEffect* (*MainCall) (audioMasterCallback);
  23570. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt);
  23571. static int shellUIDToCreate = 0;
  23572. static int insideVSTCallback = 0;
  23573. class VSTPluginWindow;
  23574. // Change this to disable logging of various VST activities
  23575. #ifndef VST_LOGGING
  23576. #define VST_LOGGING 1
  23577. #endif
  23578. #if VST_LOGGING
  23579. #define log(a) Logger::writeToLog(a);
  23580. #else
  23581. #define log(a)
  23582. #endif
  23583. #if JUCE_MAC && JUCE_PPC
  23584. static void* NewCFMFromMachO (void* const machofp) throw()
  23585. {
  23586. void* result = juce_malloc (8);
  23587. ((void**) result)[0] = machofp;
  23588. ((void**) result)[1] = result;
  23589. return result;
  23590. }
  23591. #endif
  23592. #if JUCE_LINUX
  23593. extern Display* display;
  23594. extern XContext improbableNumber;
  23595. typedef void (*EventProcPtr) (XEvent* ev);
  23596. static bool xErrorTriggered;
  23597. static int temporaryErrorHandler (Display*, XErrorEvent*)
  23598. {
  23599. xErrorTriggered = true;
  23600. return 0;
  23601. }
  23602. static int getPropertyFromXWindow (Window handle, Atom atom)
  23603. {
  23604. XErrorHandler oldErrorHandler = XSetErrorHandler (temporaryErrorHandler);
  23605. xErrorTriggered = false;
  23606. int userSize;
  23607. unsigned long bytes, userCount;
  23608. unsigned char* data;
  23609. Atom userType;
  23610. XGetWindowProperty (display, handle, atom, 0, 1, false, AnyPropertyType,
  23611. &userType, &userSize, &userCount, &bytes, &data);
  23612. XSetErrorHandler (oldErrorHandler);
  23613. return (userCount == 1 && ! xErrorTriggered) ? *(int*) data
  23614. : 0;
  23615. }
  23616. static Window getChildWindow (Window windowToCheck)
  23617. {
  23618. Window rootWindow, parentWindow;
  23619. Window* childWindows;
  23620. unsigned int numChildren;
  23621. XQueryTree (display,
  23622. windowToCheck,
  23623. &rootWindow,
  23624. &parentWindow,
  23625. &childWindows,
  23626. &numChildren);
  23627. if (numChildren > 0)
  23628. return childWindows [0];
  23629. return 0;
  23630. }
  23631. static void translateJuceToXButtonModifiers (const MouseEvent& e, XEvent& ev) throw()
  23632. {
  23633. if (e.mods.isLeftButtonDown())
  23634. {
  23635. ev.xbutton.button = Button1;
  23636. ev.xbutton.state |= Button1Mask;
  23637. }
  23638. else if (e.mods.isRightButtonDown())
  23639. {
  23640. ev.xbutton.button = Button3;
  23641. ev.xbutton.state |= Button3Mask;
  23642. }
  23643. else if (e.mods.isMiddleButtonDown())
  23644. {
  23645. ev.xbutton.button = Button2;
  23646. ev.xbutton.state |= Button2Mask;
  23647. }
  23648. }
  23649. static void translateJuceToXMotionModifiers (const MouseEvent& e, XEvent& ev) throw()
  23650. {
  23651. if (e.mods.isLeftButtonDown())
  23652. ev.xmotion.state |= Button1Mask;
  23653. else if (e.mods.isRightButtonDown())
  23654. ev.xmotion.state |= Button3Mask;
  23655. else if (e.mods.isMiddleButtonDown())
  23656. ev.xmotion.state |= Button2Mask;
  23657. }
  23658. static void translateJuceToXCrossingModifiers (const MouseEvent& e, XEvent& ev) throw()
  23659. {
  23660. if (e.mods.isLeftButtonDown())
  23661. ev.xcrossing.state |= Button1Mask;
  23662. else if (e.mods.isRightButtonDown())
  23663. ev.xcrossing.state |= Button3Mask;
  23664. else if (e.mods.isMiddleButtonDown())
  23665. ev.xcrossing.state |= Button2Mask;
  23666. }
  23667. static void translateJuceToXMouseWheelModifiers (const MouseEvent& e, const float increment, XEvent& ev) throw()
  23668. {
  23669. if (increment < 0)
  23670. {
  23671. ev.xbutton.button = Button5;
  23672. ev.xbutton.state |= Button5Mask;
  23673. }
  23674. else if (increment > 0)
  23675. {
  23676. ev.xbutton.button = Button4;
  23677. ev.xbutton.state |= Button4Mask;
  23678. }
  23679. }
  23680. #endif
  23681. static VoidArray activeModules;
  23682. class ModuleHandle : public ReferenceCountedObject
  23683. {
  23684. public:
  23685. File file;
  23686. MainCall moduleMain;
  23687. String pluginName;
  23688. static ModuleHandle* findOrCreateModule (const File& file)
  23689. {
  23690. for (int i = activeModules.size(); --i >= 0;)
  23691. {
  23692. ModuleHandle* const module = (ModuleHandle*) activeModules.getUnchecked(i);
  23693. if (module->file == file)
  23694. return module;
  23695. }
  23696. _fpreset(); // (doesn't do any harm)
  23697. ++insideVSTCallback;
  23698. shellUIDToCreate = 0;
  23699. log ("Attempting to load VST: " + file.getFullPathName());
  23700. ModuleHandle* m = new ModuleHandle (file);
  23701. if (! m->open())
  23702. deleteAndZero (m);
  23703. --insideVSTCallback;
  23704. _fpreset(); // (doesn't do any harm)
  23705. return m;
  23706. }
  23707. ModuleHandle (const File& file_)
  23708. : file (file_),
  23709. moduleMain (0),
  23710. #if JUCE_WIN32 || JUCE_LINUX
  23711. hModule (0)
  23712. #elif JUCE_MAC
  23713. fragId (0),
  23714. resHandle (0),
  23715. bundleRef (0),
  23716. resFileId (0)
  23717. #endif
  23718. {
  23719. activeModules.add (this);
  23720. #if JUCE_WIN32 || JUCE_LINUX
  23721. fullParentDirectoryPathName = file_.getParentDirectory().getFullPathName();
  23722. #elif JUCE_MAC
  23723. FSRef ref;
  23724. PlatformUtilities::makeFSRefFromPath (&ref, file_.getParentDirectory().getFullPathName());
  23725. FSGetCatalogInfo (&ref, kFSCatInfoNone, 0, 0, &parentDirFSSpec, 0);
  23726. #endif
  23727. }
  23728. ~ModuleHandle()
  23729. {
  23730. activeModules.removeValue (this);
  23731. close();
  23732. }
  23733. juce_UseDebuggingNewOperator
  23734. #if JUCE_WIN32 || JUCE_LINUX
  23735. void* hModule;
  23736. String fullParentDirectoryPathName;
  23737. bool open()
  23738. {
  23739. #if JUCE_WIN32
  23740. static bool timePeriodSet = false;
  23741. if (! timePeriodSet)
  23742. {
  23743. timePeriodSet = true;
  23744. timeBeginPeriod (2);
  23745. }
  23746. #endif
  23747. pluginName = file.getFileNameWithoutExtension();
  23748. hModule = PlatformUtilities::loadDynamicLibrary (file.getFullPathName());
  23749. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "VSTPluginMain");
  23750. if (moduleMain == 0)
  23751. moduleMain = (MainCall) PlatformUtilities::getProcedureEntryPoint (hModule, "main");
  23752. return moduleMain != 0;
  23753. }
  23754. void close()
  23755. {
  23756. _fpreset(); // (doesn't do any harm)
  23757. PlatformUtilities::freeDynamicLibrary (hModule);
  23758. }
  23759. void closeEffect (AEffect* eff)
  23760. {
  23761. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  23762. }
  23763. #else
  23764. CFragConnectionID fragId;
  23765. Handle resHandle;
  23766. CFBundleRef bundleRef;
  23767. FSSpec parentDirFSSpec;
  23768. short resFileId;
  23769. bool open()
  23770. {
  23771. bool ok = false;
  23772. const String filename (file.getFullPathName());
  23773. if (file.hasFileExtension (T(".vst")))
  23774. {
  23775. const char* const utf8 = filename.toUTF8();
  23776. CFURLRef url = CFURLCreateFromFileSystemRepresentation (0, (const UInt8*) utf8,
  23777. strlen (utf8), file.isDirectory());
  23778. if (url != 0)
  23779. {
  23780. bundleRef = CFBundleCreate (kCFAllocatorDefault, url);
  23781. CFRelease (url);
  23782. if (bundleRef != 0)
  23783. {
  23784. if (CFBundleLoadExecutable (bundleRef))
  23785. {
  23786. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("main_macho"));
  23787. if (moduleMain == 0)
  23788. moduleMain = (MainCall) CFBundleGetFunctionPointerForName (bundleRef, CFSTR("VSTPluginMain"));
  23789. if (moduleMain != 0)
  23790. {
  23791. CFTypeRef name = CFBundleGetValueForInfoDictionaryKey (bundleRef, CFSTR("CFBundleName"));
  23792. if (name != 0)
  23793. {
  23794. if (CFGetTypeID (name) == CFStringGetTypeID())
  23795. {
  23796. char buffer[1024];
  23797. if (CFStringGetCString ((CFStringRef) name, buffer, sizeof (buffer), CFStringGetSystemEncoding()))
  23798. pluginName = buffer;
  23799. }
  23800. }
  23801. if (pluginName.isEmpty())
  23802. pluginName = file.getFileNameWithoutExtension();
  23803. resFileId = CFBundleOpenBundleResourceMap (bundleRef);
  23804. ok = true;
  23805. }
  23806. }
  23807. if (! ok)
  23808. {
  23809. CFBundleUnloadExecutable (bundleRef);
  23810. CFRelease (bundleRef);
  23811. bundleRef = 0;
  23812. }
  23813. }
  23814. }
  23815. }
  23816. #if JUCE_PPC
  23817. else
  23818. {
  23819. FSRef fn;
  23820. if (FSPathMakeRef ((UInt8*) (const char*) filename, &fn, 0) == noErr)
  23821. {
  23822. resFileId = FSOpenResFile (&fn, fsRdPerm);
  23823. if (resFileId != -1)
  23824. {
  23825. const int numEffs = Count1Resources ('aEff');
  23826. for (int i = 0; i < numEffs; ++i)
  23827. {
  23828. resHandle = Get1IndResource ('aEff', i + 1);
  23829. if (resHandle != 0)
  23830. {
  23831. OSType type;
  23832. Str255 name;
  23833. SInt16 id;
  23834. GetResInfo (resHandle, &id, &type, name);
  23835. pluginName = String ((const char*) name + 1, name[0]);
  23836. DetachResource (resHandle);
  23837. HLock (resHandle);
  23838. Ptr ptr;
  23839. Str255 errorText;
  23840. OSErr err = GetMemFragment (*resHandle, GetHandleSize (resHandle),
  23841. name, kPrivateCFragCopy,
  23842. &fragId, &ptr, errorText);
  23843. if (err == noErr)
  23844. {
  23845. moduleMain = (MainCall) newMachOFromCFM (ptr);
  23846. ok = true;
  23847. }
  23848. else
  23849. {
  23850. HUnlock (resHandle);
  23851. }
  23852. break;
  23853. }
  23854. }
  23855. if (! ok)
  23856. CloseResFile (resFileId);
  23857. }
  23858. }
  23859. }
  23860. #endif
  23861. return ok;
  23862. }
  23863. void close()
  23864. {
  23865. #if JUCE_PPC
  23866. if (fragId != 0)
  23867. {
  23868. if (moduleMain != 0)
  23869. disposeMachOFromCFM ((void*) moduleMain);
  23870. CloseConnection (&fragId);
  23871. HUnlock (resHandle);
  23872. if (resFileId != 0)
  23873. CloseResFile (resFileId);
  23874. }
  23875. else
  23876. #endif
  23877. if (bundleRef != 0)
  23878. {
  23879. CFBundleCloseBundleResourceMap (bundleRef, resFileId);
  23880. if (CFGetRetainCount (bundleRef) == 1)
  23881. CFBundleUnloadExecutable (bundleRef);
  23882. if (CFGetRetainCount (bundleRef) > 0)
  23883. CFRelease (bundleRef);
  23884. }
  23885. }
  23886. void closeEffect (AEffect* eff)
  23887. {
  23888. #if JUCE_PPC
  23889. if (fragId != 0)
  23890. {
  23891. VoidArray thingsToDelete;
  23892. thingsToDelete.add ((void*) eff->dispatcher);
  23893. thingsToDelete.add ((void*) eff->process);
  23894. thingsToDelete.add ((void*) eff->setParameter);
  23895. thingsToDelete.add ((void*) eff->getParameter);
  23896. thingsToDelete.add ((void*) eff->processReplacing);
  23897. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  23898. for (int i = thingsToDelete.size(); --i >= 0;)
  23899. disposeMachOFromCFM (thingsToDelete[i]);
  23900. }
  23901. else
  23902. #endif
  23903. {
  23904. eff->dispatcher (eff, effClose, 0, 0, 0, 0);
  23905. }
  23906. }
  23907. #if JUCE_PPC
  23908. static void* newMachOFromCFM (void* cfmfp)
  23909. {
  23910. if (cfmfp == 0)
  23911. return 0;
  23912. UInt32* const mfp = (UInt32*) juce_malloc (sizeof (UInt32) * 6);
  23913. mfp[0] = 0x3d800000 | ((UInt32) cfmfp >> 16);
  23914. mfp[1] = 0x618c0000 | ((UInt32) cfmfp & 0xffff);
  23915. mfp[2] = 0x800c0000;
  23916. mfp[3] = 0x804c0004;
  23917. mfp[4] = 0x7c0903a6;
  23918. mfp[5] = 0x4e800420;
  23919. MakeDataExecutable (mfp, sizeof (UInt32) * 6);
  23920. return mfp;
  23921. }
  23922. static void disposeMachOFromCFM (void* ptr)
  23923. {
  23924. juce_free (ptr);
  23925. }
  23926. void coerceAEffectFunctionCalls (AEffect* eff)
  23927. {
  23928. if (fragId != 0)
  23929. {
  23930. eff->dispatcher = (AEffectDispatcherProc) newMachOFromCFM ((void*) eff->dispatcher);
  23931. eff->process = (AEffectProcessProc) newMachOFromCFM ((void*) eff->process);
  23932. eff->setParameter = (AEffectSetParameterProc) newMachOFromCFM ((void*) eff->setParameter);
  23933. eff->getParameter = (AEffectGetParameterProc) newMachOFromCFM ((void*) eff->getParameter);
  23934. eff->processReplacing = (AEffectProcessProc) newMachOFromCFM ((void*) eff->processReplacing);
  23935. }
  23936. }
  23937. #endif
  23938. #endif
  23939. };
  23940. /**
  23941. An instance of a plugin, created by a VSTPluginFormat.
  23942. */
  23943. class VSTPluginInstance : public AudioPluginInstance,
  23944. private Timer,
  23945. private AsyncUpdater
  23946. {
  23947. public:
  23948. ~VSTPluginInstance();
  23949. // AudioPluginInstance methods:
  23950. void fillInPluginDescription (PluginDescription& desc) const
  23951. {
  23952. desc.name = name;
  23953. desc.file = module->file;
  23954. desc.uid = getUID();
  23955. desc.lastFileModTime = desc.file.getLastModificationTime();
  23956. desc.pluginFormatName = "VST";
  23957. desc.category = getCategory();
  23958. {
  23959. char buffer [kVstMaxVendorStrLen + 8];
  23960. zerostruct (buffer);
  23961. dispatch (effGetVendorString, 0, 0, buffer, 0);
  23962. desc.manufacturerName = buffer;
  23963. }
  23964. desc.version = getVersion();
  23965. desc.numInputChannels = getNumInputChannels();
  23966. desc.numOutputChannels = getNumOutputChannels();
  23967. desc.isInstrument = (effect != 0 && (effect->flags & effFlagsIsSynth) != 0);
  23968. }
  23969. const String getName() const { return name; }
  23970. int getUID() const throw();
  23971. bool acceptsMidi() const { return wantsMidiMessages; }
  23972. bool producesMidi() const { return dispatch (effCanDo, 0, 0, (void*) "sendVstMidiEvent", 0) > 0; }
  23973. // AudioProcessor methods:
  23974. void prepareToPlay (double sampleRate, int estimatedSamplesPerBlock);
  23975. void releaseResources();
  23976. void processBlock (AudioSampleBuffer& buffer,
  23977. MidiBuffer& midiMessages);
  23978. AudioProcessorEditor* createEditor();
  23979. const String getInputChannelName (const int index) const;
  23980. bool isInputChannelStereoPair (int index) const;
  23981. const String getOutputChannelName (const int index) const;
  23982. bool isOutputChannelStereoPair (int index) const;
  23983. int getNumParameters() { return effect != 0 ? effect->numParams : 0; }
  23984. float getParameter (int index);
  23985. void setParameter (int index, float newValue);
  23986. const String getParameterName (int index);
  23987. const String getParameterText (int index);
  23988. bool isParameterAutomatable (int index) const;
  23989. int getNumPrograms() { return effect != 0 ? effect->numPrograms : 0; }
  23990. int getCurrentProgram() { return dispatch (effGetProgram, 0, 0, 0, 0); }
  23991. void setCurrentProgram (int index);
  23992. const String getProgramName (int index);
  23993. void changeProgramName (int index, const String& newName);
  23994. void getStateInformation (MemoryBlock& destData);
  23995. void getCurrentProgramStateInformation (MemoryBlock& destData);
  23996. void setStateInformation (const void* data, int sizeInBytes);
  23997. void setCurrentProgramStateInformation (const void* data, int sizeInBytes);
  23998. void timerCallback();
  23999. void handleAsyncUpdate();
  24000. VstIntPtr handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt);
  24001. juce_UseDebuggingNewOperator
  24002. private:
  24003. friend class VSTPluginWindow;
  24004. friend class VSTPluginFormat;
  24005. AEffect* effect;
  24006. String name;
  24007. CriticalSection lock;
  24008. bool wantsMidiMessages, initialised, isPowerOn;
  24009. mutable StringArray programNames;
  24010. AudioSampleBuffer tempBuffer;
  24011. CriticalSection midiInLock;
  24012. MidiBuffer incomingMidi;
  24013. void* midiEventsToSend;
  24014. int numAllocatedMidiEvents;
  24015. VstTimeInfo vstHostTime;
  24016. float** channels;
  24017. ReferenceCountedObjectPtr <ModuleHandle> module;
  24018. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const;
  24019. bool restoreProgramSettings (const fxProgram* const prog);
  24020. const String getCurrentProgramName();
  24021. void setParamsInProgramBlock (fxProgram* const prog) throw();
  24022. void updateStoredProgramNames();
  24023. void initialise();
  24024. void ensureMidiEventSize (int numEventsNeeded);
  24025. void freeMidiEvents();
  24026. void handleMidiFromPlugin (const VstEvents* const events);
  24027. void createTempParameterStore (MemoryBlock& dest);
  24028. void restoreFromTempParameterStore (const MemoryBlock& mb);
  24029. const String getParameterLabel (int index) const;
  24030. bool usesChunks() const throw() { return effect != 0 && (effect->flags & effFlagsProgramChunks) != 0; }
  24031. void getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const;
  24032. void setChunkData (const char* data, int size, bool isPreset);
  24033. bool loadFromFXBFile (const void* data, int numBytes);
  24034. bool saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB);
  24035. int getVersionNumber() const throw() { return effect != 0 ? effect->version : 0; }
  24036. const String getVersion() const throw();
  24037. const String getCategory() const throw();
  24038. bool hasEditor() const throw() { return effect != 0 && (effect->flags & effFlagsHasEditor) != 0; }
  24039. void setPower (const bool on);
  24040. VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module);
  24041. };
  24042. VSTPluginInstance::VSTPluginInstance (const ReferenceCountedObjectPtr <ModuleHandle>& module_)
  24043. : effect (0),
  24044. wantsMidiMessages (false),
  24045. initialised (false),
  24046. isPowerOn (false),
  24047. numAllocatedMidiEvents (0),
  24048. midiEventsToSend (0),
  24049. tempBuffer (1, 1),
  24050. channels (0),
  24051. module (module_)
  24052. {
  24053. try
  24054. {
  24055. _fpreset();
  24056. ++insideVSTCallback;
  24057. name = module->pluginName;
  24058. log (T("Creating VST instance: ") + name);
  24059. #if JUCE_MAC
  24060. if (module->resFileId != 0)
  24061. UseResFile (module->resFileId);
  24062. #if JUCE_PPC
  24063. if (module->fragId != 0)
  24064. {
  24065. static void* audioMasterCoerced = 0;
  24066. if (audioMasterCoerced == 0)
  24067. audioMasterCoerced = NewCFMFromMachO ((void*) &audioMaster);
  24068. effect = module->moduleMain ((audioMasterCallback) audioMasterCoerced);
  24069. }
  24070. else
  24071. #endif
  24072. #endif
  24073. {
  24074. effect = module->moduleMain (&audioMaster);
  24075. }
  24076. --insideVSTCallback;
  24077. if (effect != 0 && effect->magic == kEffectMagic)
  24078. {
  24079. #if JUCE_PPC
  24080. module->coerceAEffectFunctionCalls (effect);
  24081. #endif
  24082. jassert (effect->resvd2 == 0);
  24083. jassert (effect->object != 0);
  24084. _fpreset(); // some dodgy plugs fuck around with this
  24085. }
  24086. else
  24087. {
  24088. effect = 0;
  24089. }
  24090. }
  24091. catch (...)
  24092. {
  24093. --insideVSTCallback;
  24094. }
  24095. }
  24096. VSTPluginInstance::~VSTPluginInstance()
  24097. {
  24098. {
  24099. const ScopedLock sl (lock);
  24100. jassert (insideVSTCallback == 0);
  24101. if (effect != 0 && effect->magic == kEffectMagic)
  24102. {
  24103. try
  24104. {
  24105. #if JUCE_MAC
  24106. if (module->resFileId != 0)
  24107. UseResFile (module->resFileId);
  24108. #endif
  24109. // Must delete any editors before deleting the plugin instance!
  24110. jassert (getActiveEditor() == 0);
  24111. _fpreset(); // some dodgy plugs fuck around with this
  24112. module->closeEffect (effect);
  24113. }
  24114. catch (...)
  24115. {}
  24116. }
  24117. module = 0;
  24118. effect = 0;
  24119. }
  24120. freeMidiEvents();
  24121. juce_free (channels);
  24122. channels = 0;
  24123. }
  24124. void VSTPluginInstance::initialise()
  24125. {
  24126. if (initialised || effect == 0)
  24127. return;
  24128. log (T("Initialising VST: ") + module->pluginName);
  24129. initialised = true;
  24130. dispatch (effIdentify, 0, 0, 0, 0);
  24131. // this code would ask the plugin for its name, but so few plugins
  24132. // actually bother implementing this correctly, that it's better to
  24133. // just ignore it and use the file name instead.
  24134. /* {
  24135. char buffer [256];
  24136. zerostruct (buffer);
  24137. dispatch (effGetEffectName, 0, 0, buffer, 0);
  24138. name = String (buffer).trim();
  24139. if (name.isEmpty())
  24140. name = module->pluginName;
  24141. }
  24142. */
  24143. if (getSampleRate() > 0)
  24144. dispatch (effSetSampleRate, 0, 0, 0, (float) getSampleRate());
  24145. if (getBlockSize() > 0)
  24146. dispatch (effSetBlockSize, 0, jmax (32, getBlockSize()), 0, 0);
  24147. dispatch (effOpen, 0, 0, 0, 0);
  24148. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  24149. getSampleRate(), getBlockSize());
  24150. if (getNumPrograms() > 1)
  24151. setCurrentProgram (0);
  24152. else
  24153. dispatch (effSetProgram, 0, 0, 0, 0);
  24154. int i;
  24155. for (i = effect->numInputs; --i >= 0;)
  24156. dispatch (effConnectInput, i, 1, 0, 0);
  24157. for (i = effect->numOutputs; --i >= 0;)
  24158. dispatch (effConnectOutput, i, 1, 0, 0);
  24159. updateStoredProgramNames();
  24160. wantsMidiMessages = dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0;
  24161. setLatencySamples (effect->initialDelay);
  24162. }
  24163. void VSTPluginInstance::prepareToPlay (double sampleRate_,
  24164. int samplesPerBlockExpected)
  24165. {
  24166. setPlayConfigDetails (effect->numInputs, effect->numOutputs,
  24167. sampleRate_, samplesPerBlockExpected);
  24168. setLatencySamples (effect->initialDelay);
  24169. juce_free (channels);
  24170. channels = (float**) juce_calloc (sizeof (float*) * jmax (16, getNumOutputChannels() + 2, getNumInputChannels() + 2));
  24171. vstHostTime.tempo = 120.0;
  24172. vstHostTime.timeSigNumerator = 4;
  24173. vstHostTime.timeSigDenominator = 4;
  24174. vstHostTime.sampleRate = sampleRate_;
  24175. vstHostTime.samplePos = 0;
  24176. vstHostTime.flags = kVstNanosValid; /*| kVstTransportPlaying | kVstTempoValid | kVstTimeSigValid*/;
  24177. initialise();
  24178. if (initialised)
  24179. {
  24180. wantsMidiMessages = wantsMidiMessages
  24181. || (dispatch (effCanDo, 0, 0, (void*) "receiveVstMidiEvent", 0) > 0);
  24182. if (wantsMidiMessages)
  24183. ensureMidiEventSize (256);
  24184. else
  24185. freeMidiEvents();
  24186. incomingMidi.clear();
  24187. dispatch (effSetSampleRate, 0, 0, 0, (float) sampleRate_);
  24188. dispatch (effSetBlockSize, 0, jmax (16, samplesPerBlockExpected), 0, 0);
  24189. tempBuffer.setSize (jmax (1, effect->numOutputs), samplesPerBlockExpected);
  24190. if (! isPowerOn)
  24191. setPower (true);
  24192. // dodgy hack to force some plugins to initialise the sample rate..
  24193. if ((! hasEditor()) && getNumParameters() > 0)
  24194. {
  24195. const float old = getParameter (0);
  24196. setParameter (0, (old < 0.5f) ? 1.0f : 0.0f);
  24197. setParameter (0, old);
  24198. }
  24199. dispatch (effStartProcess, 0, 0, 0, 0);
  24200. }
  24201. }
  24202. void VSTPluginInstance::releaseResources()
  24203. {
  24204. if (initialised)
  24205. {
  24206. dispatch (effStopProcess, 0, 0, 0, 0);
  24207. setPower (false);
  24208. }
  24209. tempBuffer.setSize (1, 1);
  24210. incomingMidi.clear();
  24211. freeMidiEvents();
  24212. juce_free (channels);
  24213. channels = 0;
  24214. }
  24215. void VSTPluginInstance::processBlock (AudioSampleBuffer& buffer,
  24216. MidiBuffer& midiMessages)
  24217. {
  24218. const int numSamples = buffer.getNumSamples();
  24219. if (initialised)
  24220. {
  24221. AudioPlayHead* playHead = getPlayHead();
  24222. if (playHead != 0)
  24223. {
  24224. AudioPlayHead::CurrentPositionInfo position;
  24225. playHead->getCurrentPosition (position);
  24226. vstHostTime.tempo = position.bpm;
  24227. vstHostTime.timeSigNumerator = position.timeSigNumerator;
  24228. vstHostTime.timeSigDenominator = position.timeSigDenominator;
  24229. vstHostTime.ppqPos = position.ppqPosition;
  24230. vstHostTime.barStartPos = position.ppqPositionOfLastBarStart;
  24231. vstHostTime.flags |= kVstTempoValid | kVstTimeSigValid | kVstPpqPosValid | kVstBarsValid;
  24232. if (position.isPlaying)
  24233. vstHostTime.flags |= kVstTransportPlaying;
  24234. else
  24235. vstHostTime.flags &= ~kVstTransportPlaying;
  24236. }
  24237. #if JUCE_WIN32
  24238. vstHostTime.nanoSeconds = timeGetTime() * 1000000.0;
  24239. #elif JUCE_LINUX
  24240. timeval micro;
  24241. gettimeofday (&micro, 0);
  24242. vstHostTime.nanoSeconds = micro.tv_usec * 1000.0;
  24243. #elif JUCE_MAC
  24244. UnsignedWide micro;
  24245. Microseconds (&micro);
  24246. vstHostTime.nanoSeconds = micro.lo * 1000.0;
  24247. #endif
  24248. if (wantsMidiMessages)
  24249. {
  24250. MidiBuffer::Iterator iter (midiMessages);
  24251. int eventIndex = 0;
  24252. const uint8* midiData;
  24253. int numBytesOfMidiData, samplePosition;
  24254. while (iter.getNextEvent (midiData, numBytesOfMidiData, samplePosition))
  24255. {
  24256. if (numBytesOfMidiData < 4)
  24257. {
  24258. ensureMidiEventSize (eventIndex + 1);
  24259. VstMidiEvent* const e
  24260. = (VstMidiEvent*) ((VstEvents*) midiEventsToSend)->events [eventIndex++];
  24261. // check that some plugin hasn't messed up our objects
  24262. jassert (e->type == kVstMidiType);
  24263. jassert (e->byteSize == 24);
  24264. e->deltaFrames = jlimit (0, numSamples - 1, samplePosition);
  24265. e->noteLength = 0;
  24266. e->noteOffset = 0;
  24267. e->midiData[0] = midiData[0];
  24268. e->midiData[1] = midiData[1];
  24269. e->midiData[2] = midiData[2];
  24270. e->detune = 0;
  24271. e->noteOffVelocity = 0;
  24272. }
  24273. }
  24274. if (midiEventsToSend == 0)
  24275. ensureMidiEventSize (1);
  24276. ((VstEvents*) midiEventsToSend)->numEvents = eventIndex;
  24277. try
  24278. {
  24279. effect->dispatcher (effect, effProcessEvents, 0, 0, midiEventsToSend, 0);
  24280. }
  24281. catch (...)
  24282. {}
  24283. }
  24284. int i;
  24285. const int maxChans = jmax (effect->numInputs, effect->numOutputs);
  24286. for (i = 0; i < maxChans; ++i)
  24287. channels[i] = buffer.getSampleData (i);
  24288. channels [maxChans] = 0;
  24289. _clearfp();
  24290. if ((effect->flags & effFlagsCanReplacing) != 0)
  24291. {
  24292. try
  24293. {
  24294. effect->processReplacing (effect, channels, channels, numSamples);
  24295. }
  24296. catch (...)
  24297. {}
  24298. }
  24299. else
  24300. {
  24301. tempBuffer.setSize (effect->numOutputs, numSamples);
  24302. tempBuffer.clear();
  24303. float* outs [64];
  24304. for (i = effect->numOutputs; --i >= 0;)
  24305. outs[i] = tempBuffer.getSampleData (i);
  24306. outs [effect->numOutputs] = 0;
  24307. try
  24308. {
  24309. effect->process (effect, channels, outs, numSamples);
  24310. }
  24311. catch (...)
  24312. {}
  24313. for (i = effect->numOutputs; --i >= 0;)
  24314. buffer.copyFrom (i, 0, outs[i], numSamples);
  24315. }
  24316. }
  24317. else
  24318. {
  24319. // Not initialised, so just bypass..
  24320. for (int i = getNumInputChannels(); i < getNumOutputChannels(); ++i)
  24321. buffer.clear (i, 0, buffer.getNumSamples());
  24322. }
  24323. {
  24324. // copy any incoming midi..
  24325. const ScopedLock sl (midiInLock);
  24326. midiMessages = incomingMidi;
  24327. incomingMidi.clear();
  24328. }
  24329. }
  24330. void VSTPluginInstance::ensureMidiEventSize (int numEventsNeeded)
  24331. {
  24332. if (numEventsNeeded > numAllocatedMidiEvents)
  24333. {
  24334. numEventsNeeded = (numEventsNeeded + 32) & ~31;
  24335. const int size = 20 + sizeof (VstEvent*) * numEventsNeeded;
  24336. if (midiEventsToSend == 0)
  24337. midiEventsToSend = juce_calloc (size);
  24338. else
  24339. midiEventsToSend = juce_realloc (midiEventsToSend, size);
  24340. for (int i = numAllocatedMidiEvents; i < numEventsNeeded; ++i)
  24341. {
  24342. VstMidiEvent* const e = (VstMidiEvent*) juce_calloc (sizeof (VstMidiEvent));
  24343. e->type = kVstMidiType;
  24344. e->byteSize = 24;
  24345. ((VstEvents*) midiEventsToSend)->events[i] = (VstEvent*) e;
  24346. }
  24347. numAllocatedMidiEvents = numEventsNeeded;
  24348. }
  24349. }
  24350. void VSTPluginInstance::freeMidiEvents()
  24351. {
  24352. if (midiEventsToSend != 0)
  24353. {
  24354. for (int i = numAllocatedMidiEvents; --i >= 0;)
  24355. juce_free (((VstEvents*) midiEventsToSend)->events[i]);
  24356. juce_free (midiEventsToSend);
  24357. midiEventsToSend = 0;
  24358. numAllocatedMidiEvents = 0;
  24359. }
  24360. }
  24361. void VSTPluginInstance::handleMidiFromPlugin (const VstEvents* const events)
  24362. {
  24363. if (events != 0)
  24364. {
  24365. const ScopedLock sl (midiInLock);
  24366. for (int i = 0; i < events->numEvents; ++i)
  24367. {
  24368. const VstEvent* const e = events->events[i];
  24369. if (e->type == kVstMidiType)
  24370. {
  24371. incomingMidi.addEvent ((const uint8*) ((const VstMidiEvent*) e)->midiData,
  24372. 3, e->deltaFrames);
  24373. }
  24374. }
  24375. }
  24376. }
  24377. static Array <VSTPluginWindow*> activeVSTWindows;
  24378. class VSTPluginWindow : public AudioProcessorEditor,
  24379. #if ! JUCE_MAC
  24380. public ComponentMovementWatcher,
  24381. #endif
  24382. public Timer
  24383. {
  24384. public:
  24385. VSTPluginWindow (VSTPluginInstance& plugin_)
  24386. : AudioProcessorEditor (&plugin_),
  24387. #if ! JUCE_MAC
  24388. ComponentMovementWatcher (this),
  24389. #endif
  24390. plugin (plugin_),
  24391. isOpen (false),
  24392. wasShowing (false),
  24393. pluginRefusesToResize (false),
  24394. pluginWantsKeys (false),
  24395. alreadyInside (false),
  24396. recursiveResize (false)
  24397. {
  24398. #if JUCE_WIN32
  24399. sizeCheckCount = 0;
  24400. pluginHWND = 0;
  24401. #elif JUCE_LINUX
  24402. pluginWindow = None;
  24403. pluginProc = None;
  24404. #else
  24405. addAndMakeVisible (innerWrapper = new InnerWrapperComponent (this));
  24406. #endif
  24407. activeVSTWindows.add (this);
  24408. setSize (1, 1);
  24409. setOpaque (true);
  24410. setVisible (true);
  24411. }
  24412. ~VSTPluginWindow()
  24413. {
  24414. #if JUCE_MAC
  24415. deleteAndZero (innerWrapper);
  24416. #else
  24417. closePluginWindow();
  24418. #endif
  24419. activeVSTWindows.removeValue (this);
  24420. plugin.editorBeingDeleted (this);
  24421. }
  24422. #if ! JUCE_MAC
  24423. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  24424. {
  24425. if (recursiveResize)
  24426. return;
  24427. Component* const topComp = getTopLevelComponent();
  24428. if (topComp->getPeer() != 0)
  24429. {
  24430. int x = 0, y = 0;
  24431. relativePositionToOtherComponent (topComp, x, y);
  24432. recursiveResize = true;
  24433. #if JUCE_WIN32
  24434. if (pluginHWND != 0)
  24435. MoveWindow (pluginHWND, x, y, getWidth(), getHeight(), TRUE);
  24436. #elif JUCE_LINUX
  24437. if (pluginWindow != 0)
  24438. {
  24439. XResizeWindow (display, pluginWindow, getWidth(), getHeight());
  24440. XMoveWindow (display, pluginWindow, x, y);
  24441. XMapRaised (display, pluginWindow);
  24442. }
  24443. #endif
  24444. recursiveResize = false;
  24445. }
  24446. }
  24447. void componentVisibilityChanged (Component&)
  24448. {
  24449. const bool isShowingNow = isShowing();
  24450. if (wasShowing != isShowingNow)
  24451. {
  24452. wasShowing = isShowingNow;
  24453. if (isShowingNow)
  24454. openPluginWindow();
  24455. else
  24456. closePluginWindow();
  24457. }
  24458. componentMovedOrResized (true, true);
  24459. }
  24460. void componentPeerChanged()
  24461. {
  24462. closePluginWindow();
  24463. openPluginWindow();
  24464. }
  24465. #endif
  24466. bool keyStateChanged()
  24467. {
  24468. return pluginWantsKeys;
  24469. }
  24470. bool keyPressed (const KeyPress&)
  24471. {
  24472. return pluginWantsKeys;
  24473. }
  24474. #if JUCE_MAC
  24475. void paint (Graphics& g)
  24476. {
  24477. g.fillAll (Colours::black);
  24478. }
  24479. #else
  24480. void paint (Graphics& g)
  24481. {
  24482. if (isOpen)
  24483. {
  24484. ComponentPeer* const peer = getPeer();
  24485. if (peer != 0)
  24486. {
  24487. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  24488. getScreenY() - peer->getScreenY(),
  24489. getWidth(), getHeight());
  24490. #if JUCE_LINUX
  24491. if (pluginWindow != 0)
  24492. {
  24493. const Rectangle clip (g.getClipBounds());
  24494. XEvent ev;
  24495. zerostruct (ev);
  24496. ev.xexpose.type = Expose;
  24497. ev.xexpose.display = display;
  24498. ev.xexpose.window = pluginWindow;
  24499. ev.xexpose.x = clip.getX();
  24500. ev.xexpose.y = clip.getY();
  24501. ev.xexpose.width = clip.getWidth();
  24502. ev.xexpose.height = clip.getHeight();
  24503. sendEventToChild (&ev);
  24504. }
  24505. #endif
  24506. }
  24507. }
  24508. else
  24509. {
  24510. g.fillAll (Colours::black);
  24511. }
  24512. }
  24513. #endif
  24514. void timerCallback()
  24515. {
  24516. #if JUCE_WIN32
  24517. if (--sizeCheckCount <= 0)
  24518. {
  24519. sizeCheckCount = 10;
  24520. checkPluginWindowSize();
  24521. }
  24522. #endif
  24523. try
  24524. {
  24525. static bool reentrant = false;
  24526. if (! reentrant)
  24527. {
  24528. reentrant = true;
  24529. plugin.dispatch (effEditIdle, 0, 0, 0, 0);
  24530. reentrant = false;
  24531. }
  24532. }
  24533. catch (...)
  24534. {}
  24535. }
  24536. void mouseDown (const MouseEvent& e)
  24537. {
  24538. #if JUCE_LINUX
  24539. if (pluginWindow == 0)
  24540. return;
  24541. toFront (true);
  24542. XEvent ev;
  24543. zerostruct (ev);
  24544. ev.xbutton.display = display;
  24545. ev.xbutton.type = ButtonPress;
  24546. ev.xbutton.window = pluginWindow;
  24547. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  24548. ev.xbutton.time = CurrentTime;
  24549. ev.xbutton.x = e.x;
  24550. ev.xbutton.y = e.y;
  24551. ev.xbutton.x_root = e.getScreenX();
  24552. ev.xbutton.y_root = e.getScreenY();
  24553. translateJuceToXButtonModifiers (e, ev);
  24554. sendEventToChild (&ev);
  24555. #elif JUCE_WIN32
  24556. (void) e;
  24557. toFront (true);
  24558. #endif
  24559. }
  24560. void broughtToFront()
  24561. {
  24562. activeVSTWindows.removeValue (this);
  24563. activeVSTWindows.add (this);
  24564. #if JUCE_MAC
  24565. dispatch (effEditTop, 0, 0, 0, 0);
  24566. #endif
  24567. }
  24568. juce_UseDebuggingNewOperator
  24569. private:
  24570. VSTPluginInstance& plugin;
  24571. bool isOpen, wasShowing, recursiveResize;
  24572. bool pluginWantsKeys, pluginRefusesToResize, alreadyInside;
  24573. #if JUCE_WIN32
  24574. HWND pluginHWND;
  24575. void* originalWndProc;
  24576. int sizeCheckCount;
  24577. #elif JUCE_LINUX
  24578. Window pluginWindow;
  24579. EventProcPtr pluginProc;
  24580. #endif
  24581. #if JUCE_MAC
  24582. void openPluginWindow (WindowRef parentWindow)
  24583. {
  24584. if (isOpen || parentWindow == 0)
  24585. return;
  24586. isOpen = true;
  24587. ERect* rect = 0;
  24588. dispatch (effEditGetRect, 0, 0, &rect, 0);
  24589. dispatch (effEditOpen, 0, 0, parentWindow, 0);
  24590. // do this before and after like in the steinberg example
  24591. dispatch (effEditGetRect, 0, 0, &rect, 0);
  24592. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  24593. // Install keyboard hooks
  24594. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  24595. // double-check it's not too tiny
  24596. int w = 250, h = 150;
  24597. if (rect != 0)
  24598. {
  24599. w = rect->right - rect->left;
  24600. h = rect->bottom - rect->top;
  24601. if (w == 0 || h == 0)
  24602. {
  24603. w = 250;
  24604. h = 150;
  24605. }
  24606. }
  24607. w = jmax (w, 32);
  24608. h = jmax (h, 32);
  24609. setSize (w, h);
  24610. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  24611. repaint();
  24612. }
  24613. #else
  24614. void openPluginWindow()
  24615. {
  24616. if (isOpen || getWindowHandle() == 0)
  24617. return;
  24618. log (T("Opening VST UI: ") + plugin.name);
  24619. isOpen = true;
  24620. ERect* rect = 0;
  24621. dispatch (effEditGetRect, 0, 0, &rect, 0);
  24622. dispatch (effEditOpen, 0, 0, getWindowHandle(), 0);
  24623. // do this before and after like in the steinberg example
  24624. dispatch (effEditGetRect, 0, 0, &rect, 0);
  24625. dispatch (effGetProgram, 0, 0, 0, 0); // also in steinberg code
  24626. // Install keyboard hooks
  24627. pluginWantsKeys = (dispatch (effKeysRequired, 0, 0, 0, 0) == 0);
  24628. #if JUCE_WIN32
  24629. originalWndProc = 0;
  24630. pluginHWND = GetWindow ((HWND) getWindowHandle(), GW_CHILD);
  24631. if (pluginHWND == 0)
  24632. {
  24633. isOpen = false;
  24634. setSize (300, 150);
  24635. return;
  24636. }
  24637. #pragma warning (push)
  24638. #pragma warning (disable: 4244)
  24639. originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWL_WNDPROC);
  24640. if (! pluginWantsKeys)
  24641. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) vstHookWndProc);
  24642. #pragma warning (pop)
  24643. int w, h;
  24644. RECT r;
  24645. GetWindowRect (pluginHWND, &r);
  24646. w = r.right - r.left;
  24647. h = r.bottom - r.top;
  24648. if (rect != 0)
  24649. {
  24650. const int rw = rect->right - rect->left;
  24651. const int rh = rect->bottom - rect->top;
  24652. if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && rw != w && rh != h)
  24653. || ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
  24654. {
  24655. // very dodgy logic to decide which size is right.
  24656. if (abs (rw - w) > 350 || abs (rh - h) > 350)
  24657. {
  24658. SetWindowPos (pluginHWND, 0,
  24659. 0, 0, rw, rh,
  24660. SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  24661. GetWindowRect (pluginHWND, &r);
  24662. w = r.right - r.left;
  24663. h = r.bottom - r.top;
  24664. pluginRefusesToResize = (w != rw) || (h != rh);
  24665. w = rw;
  24666. h = rh;
  24667. }
  24668. }
  24669. }
  24670. #elif JUCE_LINUX
  24671. pluginWindow = getChildWindow ((Window) getWindowHandle());
  24672. if (pluginWindow != 0)
  24673. pluginProc = (EventProcPtr) getPropertyFromXWindow (pluginWindow,
  24674. XInternAtom (display, "_XEventProc", False));
  24675. int w = 250, h = 150;
  24676. if (rect != 0)
  24677. {
  24678. w = rect->right - rect->left;
  24679. h = rect->bottom - rect->top;
  24680. if (w == 0 || h == 0)
  24681. {
  24682. w = 250;
  24683. h = 150;
  24684. }
  24685. }
  24686. if (pluginWindow != 0)
  24687. XMapRaised (display, pluginWindow);
  24688. #endif
  24689. // double-check it's not too tiny
  24690. w = jmax (w, 32);
  24691. h = jmax (h, 32);
  24692. setSize (w, h);
  24693. #if JUCE_WIN32
  24694. checkPluginWindowSize();
  24695. #endif
  24696. startTimer (18 + JUCE_NAMESPACE::Random::getSystemRandom().nextInt (5));
  24697. repaint();
  24698. }
  24699. #endif
  24700. #if ! JUCE_MAC
  24701. void closePluginWindow()
  24702. {
  24703. if (isOpen)
  24704. {
  24705. log (T("Closing VST UI: ") + plugin.getName());
  24706. isOpen = false;
  24707. dispatch (effEditClose, 0, 0, 0, 0);
  24708. #if JUCE_WIN32
  24709. #pragma warning (push)
  24710. #pragma warning (disable: 4244)
  24711. if (pluginHWND != 0 && IsWindow (pluginHWND))
  24712. SetWindowLongPtr (pluginHWND, GWL_WNDPROC, (LONG_PTR) originalWndProc);
  24713. #pragma warning (pop)
  24714. stopTimer();
  24715. if (pluginHWND != 0 && IsWindow (pluginHWND))
  24716. DestroyWindow (pluginHWND);
  24717. pluginHWND = 0;
  24718. #elif JUCE_LINUX
  24719. stopTimer();
  24720. pluginWindow = 0;
  24721. pluginProc = 0;
  24722. #endif
  24723. }
  24724. }
  24725. #endif
  24726. int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
  24727. {
  24728. return plugin.dispatch (opcode, index, value, ptr, opt);
  24729. }
  24730. #if JUCE_WIN32
  24731. void checkPluginWindowSize() throw()
  24732. {
  24733. RECT r;
  24734. GetWindowRect (pluginHWND, &r);
  24735. const int w = r.right - r.left;
  24736. const int h = r.bottom - r.top;
  24737. if (isShowing() && w > 0 && h > 0
  24738. && (w != getWidth() || h != getHeight())
  24739. && ! pluginRefusesToResize)
  24740. {
  24741. setSize (w, h);
  24742. sizeCheckCount = 0;
  24743. }
  24744. }
  24745. // hooks to get keyboard events from VST windows..
  24746. static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
  24747. {
  24748. for (int i = activeVSTWindows.size(); --i >= 0;)
  24749. {
  24750. const VSTPluginWindow* const w = (const VSTPluginWindow*) activeVSTWindows.getUnchecked (i);
  24751. if (w->pluginHWND == hW)
  24752. {
  24753. if (message == WM_CHAR
  24754. || message == WM_KEYDOWN
  24755. || message == WM_SYSKEYDOWN
  24756. || message == WM_KEYUP
  24757. || message == WM_SYSKEYUP
  24758. || message == WM_APPCOMMAND)
  24759. {
  24760. SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
  24761. message, wParam, lParam);
  24762. }
  24763. return CallWindowProc ((WNDPROC) (w->originalWndProc),
  24764. (HWND) w->pluginHWND,
  24765. message,
  24766. wParam,
  24767. lParam);
  24768. }
  24769. }
  24770. return DefWindowProc (hW, message, wParam, lParam);
  24771. }
  24772. #endif
  24773. #if JUCE_LINUX
  24774. // overload mouse/keyboard events to forward them to the plugin's inner window..
  24775. void sendEventToChild (XEvent* event)
  24776. {
  24777. if (pluginProc != 0)
  24778. {
  24779. // if the plugin publishes an event procedure, pass the event directly..
  24780. pluginProc (event);
  24781. }
  24782. else if (pluginWindow != 0)
  24783. {
  24784. // if the plugin has a window, then send the event to the window so that
  24785. // its message thread will pick it up..
  24786. XSendEvent (display, pluginWindow, False, 0L, event);
  24787. XFlush (display);
  24788. }
  24789. }
  24790. void mouseEnter (const MouseEvent& e)
  24791. {
  24792. if (pluginWindow != 0)
  24793. {
  24794. XEvent ev;
  24795. zerostruct (ev);
  24796. ev.xcrossing.display = display;
  24797. ev.xcrossing.type = EnterNotify;
  24798. ev.xcrossing.window = pluginWindow;
  24799. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  24800. ev.xcrossing.time = CurrentTime;
  24801. ev.xcrossing.x = e.x;
  24802. ev.xcrossing.y = e.y;
  24803. ev.xcrossing.x_root = e.getScreenX();
  24804. ev.xcrossing.y_root = e.getScreenY();
  24805. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  24806. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  24807. translateJuceToXCrossingModifiers (e, ev);
  24808. sendEventToChild (&ev);
  24809. }
  24810. }
  24811. void mouseExit (const MouseEvent& e)
  24812. {
  24813. if (pluginWindow != 0)
  24814. {
  24815. XEvent ev;
  24816. zerostruct (ev);
  24817. ev.xcrossing.display = display;
  24818. ev.xcrossing.type = LeaveNotify;
  24819. ev.xcrossing.window = pluginWindow;
  24820. ev.xcrossing.root = RootWindow (display, DefaultScreen (display));
  24821. ev.xcrossing.time = CurrentTime;
  24822. ev.xcrossing.x = e.x;
  24823. ev.xcrossing.y = e.y;
  24824. ev.xcrossing.x_root = e.getScreenX();
  24825. ev.xcrossing.y_root = e.getScreenY();
  24826. ev.xcrossing.mode = NotifyNormal; // NotifyGrab, NotifyUngrab
  24827. ev.xcrossing.detail = NotifyAncestor; // NotifyVirtual, NotifyInferior, NotifyNonlinear,NotifyNonlinearVirtual
  24828. ev.xcrossing.focus = hasKeyboardFocus (true); // TODO - yes ?
  24829. translateJuceToXCrossingModifiers (e, ev);
  24830. sendEventToChild (&ev);
  24831. }
  24832. }
  24833. void mouseMove (const MouseEvent& e)
  24834. {
  24835. if (pluginWindow != 0)
  24836. {
  24837. XEvent ev;
  24838. zerostruct (ev);
  24839. ev.xmotion.display = display;
  24840. ev.xmotion.type = MotionNotify;
  24841. ev.xmotion.window = pluginWindow;
  24842. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  24843. ev.xmotion.time = CurrentTime;
  24844. ev.xmotion.is_hint = NotifyNormal;
  24845. ev.xmotion.x = e.x;
  24846. ev.xmotion.y = e.y;
  24847. ev.xmotion.x_root = e.getScreenX();
  24848. ev.xmotion.y_root = e.getScreenY();
  24849. sendEventToChild (&ev);
  24850. }
  24851. }
  24852. void mouseDrag (const MouseEvent& e)
  24853. {
  24854. if (pluginWindow != 0)
  24855. {
  24856. XEvent ev;
  24857. zerostruct (ev);
  24858. ev.xmotion.display = display;
  24859. ev.xmotion.type = MotionNotify;
  24860. ev.xmotion.window = pluginWindow;
  24861. ev.xmotion.root = RootWindow (display, DefaultScreen (display));
  24862. ev.xmotion.time = CurrentTime;
  24863. ev.xmotion.x = e.x ;
  24864. ev.xmotion.y = e.y;
  24865. ev.xmotion.x_root = e.getScreenX();
  24866. ev.xmotion.y_root = e.getScreenY();
  24867. ev.xmotion.is_hint = NotifyNormal;
  24868. translateJuceToXMotionModifiers (e, ev);
  24869. sendEventToChild (&ev);
  24870. }
  24871. }
  24872. void mouseUp (const MouseEvent& e)
  24873. {
  24874. if (pluginWindow != 0)
  24875. {
  24876. XEvent ev;
  24877. zerostruct (ev);
  24878. ev.xbutton.display = display;
  24879. ev.xbutton.type = ButtonRelease;
  24880. ev.xbutton.window = pluginWindow;
  24881. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  24882. ev.xbutton.time = CurrentTime;
  24883. ev.xbutton.x = e.x;
  24884. ev.xbutton.y = e.y;
  24885. ev.xbutton.x_root = e.getScreenX();
  24886. ev.xbutton.y_root = e.getScreenY();
  24887. translateJuceToXButtonModifiers (e, ev);
  24888. sendEventToChild (&ev);
  24889. }
  24890. }
  24891. void mouseWheelMove (const MouseEvent& e,
  24892. float incrementX,
  24893. float incrementY)
  24894. {
  24895. if (pluginWindow != 0)
  24896. {
  24897. XEvent ev;
  24898. zerostruct (ev);
  24899. ev.xbutton.display = display;
  24900. ev.xbutton.type = ButtonPress;
  24901. ev.xbutton.window = pluginWindow;
  24902. ev.xbutton.root = RootWindow (display, DefaultScreen (display));
  24903. ev.xbutton.time = CurrentTime;
  24904. ev.xbutton.x = e.x;
  24905. ev.xbutton.y = e.y;
  24906. ev.xbutton.x_root = e.getScreenX();
  24907. ev.xbutton.y_root = e.getScreenY();
  24908. translateJuceToXMouseWheelModifiers (e, incrementY, ev);
  24909. sendEventToChild (&ev);
  24910. // TODO - put a usleep here ?
  24911. ev.xbutton.type = ButtonRelease;
  24912. sendEventToChild (&ev);
  24913. }
  24914. }
  24915. #endif
  24916. #if JUCE_MAC
  24917. class InnerWrapperComponent : public CarbonViewWrapperComponent
  24918. {
  24919. public:
  24920. InnerWrapperComponent (VSTPluginWindow* const owner_)
  24921. : owner (owner_),
  24922. alreadyInside (false)
  24923. {
  24924. }
  24925. ~InnerWrapperComponent()
  24926. {
  24927. deleteWindow();
  24928. }
  24929. HIViewRef attachView (WindowRef windowRef, HIViewRef rootView)
  24930. {
  24931. owner->openPluginWindow (windowRef);
  24932. return 0;
  24933. }
  24934. void removeView (HIViewRef)
  24935. {
  24936. owner->dispatch (effEditClose, 0, 0, 0, 0);
  24937. owner->dispatch (effEditSleep, 0, 0, 0, 0);
  24938. }
  24939. bool getEmbeddedViewSize (int& w, int& h)
  24940. {
  24941. ERect* rect = 0;
  24942. owner->dispatch (effEditGetRect, 0, 0, &rect, 0);
  24943. w = rect->right - rect->left;
  24944. h = rect->bottom - rect->top;
  24945. return true;
  24946. }
  24947. void mouseDown (int x, int y)
  24948. {
  24949. if (! alreadyInside)
  24950. {
  24951. alreadyInside = true;
  24952. getTopLevelComponent()->toFront (true);
  24953. owner->dispatch (effEditMouse, x, y, 0, 0);
  24954. alreadyInside = false;
  24955. }
  24956. else
  24957. {
  24958. PostEvent (::mouseDown, 0);
  24959. }
  24960. }
  24961. void paint()
  24962. {
  24963. ComponentPeer* const peer = getPeer();
  24964. if (peer != 0)
  24965. {
  24966. ERect r;
  24967. r.left = getScreenX() - peer->getScreenX();
  24968. r.right = r.left + getWidth();
  24969. r.top = getScreenY() - peer->getScreenY();
  24970. r.bottom = r.top + getHeight();
  24971. owner->dispatch (effEditDraw, 0, 0, &r, 0);
  24972. }
  24973. }
  24974. private:
  24975. VSTPluginWindow* const owner;
  24976. bool alreadyInside;
  24977. };
  24978. friend class InnerWrapperComponent;
  24979. InnerWrapperComponent* innerWrapper;
  24980. void resized()
  24981. {
  24982. innerWrapper->setSize (getWidth(), getHeight());
  24983. }
  24984. #endif
  24985. };
  24986. AudioProcessorEditor* VSTPluginInstance::createEditor()
  24987. {
  24988. if (hasEditor())
  24989. return new VSTPluginWindow (*this);
  24990. return 0;
  24991. }
  24992. void VSTPluginInstance::handleAsyncUpdate()
  24993. {
  24994. // indicates that something about the plugin has changed..
  24995. updateHostDisplay();
  24996. }
  24997. bool VSTPluginInstance::restoreProgramSettings (const fxProgram* const prog)
  24998. {
  24999. if (vst_swap (prog->chunkMagic) == 'CcnK' && vst_swap (prog->fxMagic) == 'FxCk')
  25000. {
  25001. changeProgramName (getCurrentProgram(), prog->prgName);
  25002. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  25003. setParameter (i, vst_swapFloat (prog->params[i]));
  25004. return true;
  25005. }
  25006. return false;
  25007. }
  25008. bool VSTPluginInstance::loadFromFXBFile (const void* const data,
  25009. const int dataSize)
  25010. {
  25011. if (dataSize < 28)
  25012. return false;
  25013. const fxSet* const set = (const fxSet*) data;
  25014. if ((vst_swap (set->chunkMagic) != 'CcnK' && vst_swap (set->chunkMagic) != 'KncC')
  25015. || vst_swap (set->version) > fxbVersionNum)
  25016. return false;
  25017. if (vst_swap (set->fxMagic) == 'FxBk')
  25018. {
  25019. // bank of programs
  25020. if (vst_swap (set->numPrograms) >= 0)
  25021. {
  25022. const int oldProg = getCurrentProgram();
  25023. const int numParams = vst_swap (((const fxProgram*) (set->programs))->numParams);
  25024. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  25025. for (int i = 0; i < vst_swap (set->numPrograms); ++i)
  25026. {
  25027. if (i != oldProg)
  25028. {
  25029. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + i * progLen);
  25030. if (((const char*) prog) - ((const char*) set) >= dataSize)
  25031. return false;
  25032. if (vst_swap (set->numPrograms) > 0)
  25033. setCurrentProgram (i);
  25034. if (! restoreProgramSettings (prog))
  25035. return false;
  25036. }
  25037. }
  25038. if (vst_swap (set->numPrograms) > 0)
  25039. setCurrentProgram (oldProg);
  25040. const fxProgram* const prog = (const fxProgram*) (((const char*) (set->programs)) + oldProg * progLen);
  25041. if (((const char*) prog) - ((const char*) set) >= dataSize)
  25042. return false;
  25043. if (! restoreProgramSettings (prog))
  25044. return false;
  25045. }
  25046. }
  25047. else if (vst_swap (set->fxMagic) == 'FxCk')
  25048. {
  25049. // single program
  25050. const fxProgram* const prog = (const fxProgram*) data;
  25051. if (vst_swap (prog->chunkMagic) != 'CcnK')
  25052. return false;
  25053. changeProgramName (getCurrentProgram(), prog->prgName);
  25054. for (int i = 0; i < vst_swap (prog->numParams); ++i)
  25055. setParameter (i, vst_swapFloat (prog->params[i]));
  25056. }
  25057. else if (vst_swap (set->fxMagic) == 'FBCh' || vst_swap (set->fxMagic) == 'hCBF')
  25058. {
  25059. // non-preset chunk
  25060. const fxChunkSet* const cset = (const fxChunkSet*) data;
  25061. if (vst_swap (cset->chunkSize) + sizeof (fxChunkSet) - 8 > (unsigned int) dataSize)
  25062. return false;
  25063. setChunkData (cset->chunk, vst_swap (cset->chunkSize), false);
  25064. }
  25065. else if (vst_swap (set->fxMagic) == 'FPCh' || vst_swap (set->fxMagic) == 'hCPF')
  25066. {
  25067. // preset chunk
  25068. const fxProgramSet* const cset = (const fxProgramSet*) data;
  25069. if (vst_swap (cset->chunkSize) + sizeof (fxProgramSet) - 8 > (unsigned int) dataSize)
  25070. return false;
  25071. setChunkData (cset->chunk, vst_swap (cset->chunkSize), true);
  25072. changeProgramName (getCurrentProgram(), cset->name);
  25073. }
  25074. else
  25075. {
  25076. return false;
  25077. }
  25078. return true;
  25079. }
  25080. void VSTPluginInstance::setParamsInProgramBlock (fxProgram* const prog) throw()
  25081. {
  25082. const int numParams = getNumParameters();
  25083. prog->chunkMagic = vst_swap ('CcnK');
  25084. prog->byteSize = 0;
  25085. prog->fxMagic = vst_swap ('FxCk');
  25086. prog->version = vst_swap (fxbVersionNum);
  25087. prog->fxID = vst_swap (getUID());
  25088. prog->fxVersion = vst_swap (getVersionNumber());
  25089. prog->numParams = vst_swap (numParams);
  25090. getCurrentProgramName().copyToBuffer (prog->prgName, sizeof (prog->prgName) - 1);
  25091. for (int i = 0; i < numParams; ++i)
  25092. prog->params[i] = vst_swapFloat (getParameter (i));
  25093. }
  25094. bool VSTPluginInstance::saveToFXBFile (MemoryBlock& dest, bool isFXB, int maxSizeMB)
  25095. {
  25096. const int numPrograms = getNumPrograms();
  25097. const int numParams = getNumParameters();
  25098. if (usesChunks())
  25099. {
  25100. if (isFXB)
  25101. {
  25102. MemoryBlock chunk;
  25103. getChunkData (chunk, false, maxSizeMB);
  25104. const int totalLen = sizeof (fxChunkSet) + chunk.getSize() - 8;
  25105. dest.setSize (totalLen, true);
  25106. fxChunkSet* const set = (fxChunkSet*) dest.getData();
  25107. set->chunkMagic = vst_swap ('CcnK');
  25108. set->byteSize = 0;
  25109. set->fxMagic = vst_swap ('FBCh');
  25110. set->version = vst_swap (fxbVersionNum);
  25111. set->fxID = vst_swap (getUID());
  25112. set->fxVersion = vst_swap (getVersionNumber());
  25113. set->numPrograms = vst_swap (numPrograms);
  25114. set->chunkSize = vst_swap (chunk.getSize());
  25115. chunk.copyTo (set->chunk, 0, chunk.getSize());
  25116. }
  25117. else
  25118. {
  25119. MemoryBlock chunk;
  25120. getChunkData (chunk, true, maxSizeMB);
  25121. const int totalLen = sizeof (fxProgramSet) + chunk.getSize() - 8;
  25122. dest.setSize (totalLen, true);
  25123. fxProgramSet* const set = (fxProgramSet*) dest.getData();
  25124. set->chunkMagic = vst_swap ('CcnK');
  25125. set->byteSize = 0;
  25126. set->fxMagic = vst_swap ('FPCh');
  25127. set->version = vst_swap (fxbVersionNum);
  25128. set->fxID = vst_swap (getUID());
  25129. set->fxVersion = vst_swap (getVersionNumber());
  25130. set->numPrograms = vst_swap (numPrograms);
  25131. set->chunkSize = vst_swap (chunk.getSize());
  25132. getCurrentProgramName().copyToBuffer (set->name, sizeof (set->name) - 1);
  25133. chunk.copyTo (set->chunk, 0, chunk.getSize());
  25134. }
  25135. }
  25136. else
  25137. {
  25138. if (isFXB)
  25139. {
  25140. const int progLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  25141. const int len = (sizeof (fxSet) - sizeof (fxProgram)) + progLen * jmax (1, numPrograms);
  25142. dest.setSize (len, true);
  25143. fxSet* const set = (fxSet*) dest.getData();
  25144. set->chunkMagic = vst_swap ('CcnK');
  25145. set->byteSize = 0;
  25146. set->fxMagic = vst_swap ('FxBk');
  25147. set->version = vst_swap (fxbVersionNum);
  25148. set->fxID = vst_swap (getUID());
  25149. set->fxVersion = vst_swap (getVersionNumber());
  25150. set->numPrograms = vst_swap (numPrograms);
  25151. const int oldProgram = getCurrentProgram();
  25152. MemoryBlock oldSettings;
  25153. createTempParameterStore (oldSettings);
  25154. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + oldProgram * progLen));
  25155. for (int i = 0; i < numPrograms; ++i)
  25156. {
  25157. if (i != oldProgram)
  25158. {
  25159. setCurrentProgram (i);
  25160. setParamsInProgramBlock ((fxProgram*) (((char*) (set->programs)) + i * progLen));
  25161. }
  25162. }
  25163. setCurrentProgram (oldProgram);
  25164. restoreFromTempParameterStore (oldSettings);
  25165. }
  25166. else
  25167. {
  25168. const int totalLen = sizeof (fxProgram) + (numParams - 1) * sizeof (float);
  25169. dest.setSize (totalLen, true);
  25170. setParamsInProgramBlock ((fxProgram*) dest.getData());
  25171. }
  25172. }
  25173. return true;
  25174. }
  25175. void VSTPluginInstance::getChunkData (MemoryBlock& mb, bool isPreset, int maxSizeMB) const
  25176. {
  25177. if (usesChunks())
  25178. {
  25179. void* data = 0;
  25180. const int bytes = dispatch (effGetChunk, isPreset ? 1 : 0, 0, &data, 0.0f);
  25181. if (data != 0 && bytes <= maxSizeMB * 1024 * 1024)
  25182. {
  25183. mb.setSize (bytes);
  25184. mb.copyFrom (data, 0, bytes);
  25185. }
  25186. }
  25187. }
  25188. void VSTPluginInstance::setChunkData (const char* data, int size, bool isPreset)
  25189. {
  25190. if (size > 0 && usesChunks())
  25191. {
  25192. dispatch (effSetChunk, isPreset ? 1 : 0, size, (void*) data, 0.0f);
  25193. if (! isPreset)
  25194. updateStoredProgramNames();
  25195. }
  25196. }
  25197. void VSTPluginInstance::timerCallback()
  25198. {
  25199. if (dispatch (effIdle, 0, 0, 0, 0) == 0)
  25200. stopTimer();
  25201. }
  25202. int VSTPluginInstance::dispatch (const int opcode, const int index, const int value, void* const ptr, float opt) const
  25203. {
  25204. const ScopedLock sl (lock);
  25205. ++insideVSTCallback;
  25206. int result = 0;
  25207. try
  25208. {
  25209. if (effect != 0)
  25210. {
  25211. #if JUCE_MAC
  25212. if (module->resFileId != 0)
  25213. UseResFile (module->resFileId);
  25214. CGrafPtr oldPort;
  25215. if (getActiveEditor() != 0)
  25216. {
  25217. int x = 0, y = 0;
  25218. getActiveEditor()->relativePositionToOtherComponent (getActiveEditor()->getTopLevelComponent(), x, y);
  25219. GetPort (&oldPort);
  25220. SetPortWindowPort ((WindowRef) getActiveEditor()->getWindowHandle());
  25221. SetOrigin (-x, -y);
  25222. }
  25223. #endif
  25224. result = effect->dispatcher (effect, opcode, index, value, ptr, opt);
  25225. #if JUCE_MAC
  25226. if (getActiveEditor() != 0)
  25227. SetPort (oldPort);
  25228. module->resFileId = CurResFile();
  25229. #endif
  25230. --insideVSTCallback;
  25231. return result;
  25232. }
  25233. }
  25234. catch (...)
  25235. {
  25236. //char s[512];
  25237. //sprintf (s, "dispatcher (%d, %d, %d, %x, %f)", opcode, index, value, (int)ptr, opt);
  25238. }
  25239. --insideVSTCallback;
  25240. return result;
  25241. }
  25242. // handles non plugin-specific callbacks..
  25243. static VstIntPtr handleGeneralCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  25244. {
  25245. (void) index;
  25246. (void) value;
  25247. (void) opt;
  25248. switch (opcode)
  25249. {
  25250. case audioMasterCanDo:
  25251. {
  25252. static const char* canDos[] = { "supplyIdle",
  25253. "sendVstEvents",
  25254. "sendVstMidiEvent",
  25255. "sendVstTimeInfo",
  25256. "receiveVstEvents",
  25257. "receiveVstMidiEvent",
  25258. "supportShell",
  25259. "shellCategory" };
  25260. for (int i = 0; i < numElementsInArray (canDos); ++i)
  25261. if (strcmp (canDos[i], (const char*) ptr) == 0)
  25262. return 1;
  25263. return 0;
  25264. }
  25265. case audioMasterVersion:
  25266. return 0x2400;
  25267. case audioMasterCurrentId:
  25268. return shellUIDToCreate;
  25269. case audioMasterGetNumAutomatableParameters:
  25270. return 0;
  25271. case audioMasterGetAutomationState:
  25272. return 1;
  25273. case audioMasterGetVendorVersion:
  25274. return 0x0101;
  25275. case audioMasterGetVendorString:
  25276. case audioMasterGetProductString:
  25277. {
  25278. String hostName ("Juce VST Host");
  25279. if (JUCEApplication::getInstance() != 0)
  25280. hostName = JUCEApplication::getInstance()->getApplicationName();
  25281. hostName.copyToBuffer ((char*) ptr, jmin (kVstMaxVendorStrLen, kVstMaxProductStrLen) - 1);
  25282. }
  25283. break;
  25284. case audioMasterGetSampleRate:
  25285. return 44100;
  25286. case audioMasterGetBlockSize:
  25287. return 512;
  25288. case audioMasterSetOutputSampleRate:
  25289. return 0;
  25290. default:
  25291. DBG ("*** Unhandled VST Callback: " + String ((int) opcode));
  25292. break;
  25293. }
  25294. return 0;
  25295. }
  25296. // handles callbacks for a specific plugin
  25297. VstIntPtr VSTPluginInstance::handleCallback (VstInt32 opcode, VstInt32 index, VstInt32 value, void *ptr, float opt)
  25298. {
  25299. switch (opcode)
  25300. {
  25301. case audioMasterAutomate:
  25302. sendParamChangeMessageToListeners (index, opt);
  25303. break;
  25304. case audioMasterProcessEvents:
  25305. handleMidiFromPlugin ((const VstEvents*) ptr);
  25306. break;
  25307. case audioMasterGetTime:
  25308. #ifdef _MSC_VER
  25309. #pragma warning (push)
  25310. #pragma warning (disable: 4311)
  25311. #endif
  25312. return (VstIntPtr) &vstHostTime;
  25313. #ifdef _MSC_VER
  25314. #pragma warning (pop)
  25315. #endif
  25316. break;
  25317. case audioMasterIdle:
  25318. if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
  25319. {
  25320. ++insideVSTCallback;
  25321. #if JUCE_MAC
  25322. if (getActiveEditor() != 0)
  25323. dispatch (effEditIdle, 0, 0, 0, 0);
  25324. #endif
  25325. const MessageManagerLock mml;
  25326. juce_callAnyTimersSynchronously();
  25327. handleUpdateNowIfNeeded();
  25328. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  25329. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  25330. --insideVSTCallback;
  25331. }
  25332. break;
  25333. case audioMasterUpdateDisplay:
  25334. triggerAsyncUpdate();
  25335. break;
  25336. case audioMasterTempoAt:
  25337. // returns (10000 * bpm)
  25338. break;
  25339. case audioMasterNeedIdle:
  25340. startTimer (50);
  25341. break;
  25342. case audioMasterSizeWindow:
  25343. if (getActiveEditor() != 0)
  25344. getActiveEditor()->setSize (index, value);
  25345. return 1;
  25346. case audioMasterGetSampleRate:
  25347. return (VstIntPtr) getSampleRate();
  25348. case audioMasterGetBlockSize:
  25349. return (VstIntPtr) getBlockSize();
  25350. case audioMasterWantMidi:
  25351. wantsMidiMessages = true;
  25352. break;
  25353. case audioMasterGetDirectory:
  25354. #if JUCE_MAC
  25355. return (VstIntPtr) (void*) &module->parentDirFSSpec;
  25356. #else
  25357. return (VstIntPtr) (pointer_sized_uint) (const char*) module->fullParentDirectoryPathName;
  25358. #endif
  25359. case audioMasterGetAutomationState:
  25360. // returns 0: not supported, 1: off, 2:read, 3:write, 4:read/write
  25361. break;
  25362. // none of these are handled (yet)..
  25363. case audioMasterBeginEdit:
  25364. case audioMasterEndEdit:
  25365. case audioMasterSetTime:
  25366. case audioMasterPinConnected:
  25367. case audioMasterGetParameterQuantization:
  25368. case audioMasterIOChanged:
  25369. case audioMasterGetInputLatency:
  25370. case audioMasterGetOutputLatency:
  25371. case audioMasterGetPreviousPlug:
  25372. case audioMasterGetNextPlug:
  25373. case audioMasterWillReplaceOrAccumulate:
  25374. case audioMasterGetCurrentProcessLevel:
  25375. case audioMasterOfflineStart:
  25376. case audioMasterOfflineRead:
  25377. case audioMasterOfflineWrite:
  25378. case audioMasterOfflineGetCurrentPass:
  25379. case audioMasterOfflineGetCurrentMetaPass:
  25380. case audioMasterVendorSpecific:
  25381. case audioMasterSetIcon:
  25382. case audioMasterGetLanguage:
  25383. case audioMasterOpenWindow:
  25384. case audioMasterCloseWindow:
  25385. break;
  25386. default:
  25387. return handleGeneralCallback (opcode, index, value, ptr, opt);
  25388. }
  25389. return 0;
  25390. }
  25391. // entry point for all callbacks from the plugin
  25392. static VstIntPtr VSTCALLBACK audioMaster (AEffect* effect, VstInt32 opcode, VstInt32 index, VstIntPtr value, void* ptr, float opt)
  25393. {
  25394. try
  25395. {
  25396. if (effect != 0 && effect->resvd2 != 0)
  25397. {
  25398. return ((VSTPluginInstance*)(effect->resvd2))
  25399. ->handleCallback (opcode, index, value, ptr, opt);
  25400. }
  25401. return handleGeneralCallback (opcode, index, value, ptr, opt);
  25402. }
  25403. catch (...)
  25404. {
  25405. return 0;
  25406. }
  25407. }
  25408. const String VSTPluginInstance::getVersion() const throw()
  25409. {
  25410. int v = dispatch (effGetVendorVersion, 0, 0, 0, 0);
  25411. String s;
  25412. if (v != 0)
  25413. {
  25414. int versionBits[4];
  25415. int n = 0;
  25416. while (v != 0)
  25417. {
  25418. versionBits [n++] = (v & 0xff);
  25419. v >>= 8;
  25420. }
  25421. s << 'V';
  25422. while (n > 0)
  25423. {
  25424. s << versionBits [--n];
  25425. if (n > 0)
  25426. s << '.';
  25427. }
  25428. }
  25429. return s;
  25430. }
  25431. int VSTPluginInstance::getUID() const throw()
  25432. {
  25433. int uid = effect != 0 ? effect->uniqueID : 0;
  25434. if (uid == 0)
  25435. uid = module->file.hashCode();
  25436. return uid;
  25437. }
  25438. const String VSTPluginInstance::getCategory() const throw()
  25439. {
  25440. const char* result = 0;
  25441. switch (dispatch (effGetPlugCategory, 0, 0, 0, 0))
  25442. {
  25443. case kPlugCategEffect:
  25444. result = "Effect";
  25445. break;
  25446. case kPlugCategSynth:
  25447. result = "Synth";
  25448. break;
  25449. case kPlugCategAnalysis:
  25450. result = "Anaylsis";
  25451. break;
  25452. case kPlugCategMastering:
  25453. result = "Mastering";
  25454. break;
  25455. case kPlugCategSpacializer:
  25456. result = "Spacial";
  25457. break;
  25458. case kPlugCategRoomFx:
  25459. result = "Reverb";
  25460. break;
  25461. case kPlugSurroundFx:
  25462. result = "Surround";
  25463. break;
  25464. case kPlugCategRestoration:
  25465. result = "Restoration";
  25466. break;
  25467. case kPlugCategGenerator:
  25468. result = "Tone generation";
  25469. break;
  25470. default:
  25471. break;
  25472. }
  25473. return result;
  25474. }
  25475. float VSTPluginInstance::getParameter (int index)
  25476. {
  25477. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  25478. {
  25479. try
  25480. {
  25481. const ScopedLock sl (lock);
  25482. return effect->getParameter (effect, index);
  25483. }
  25484. catch (...)
  25485. {
  25486. }
  25487. }
  25488. return 0.0f;
  25489. }
  25490. void VSTPluginInstance::setParameter (int index, float newValue)
  25491. {
  25492. if (effect != 0 && ((unsigned int) index) < (unsigned int) effect->numParams)
  25493. {
  25494. try
  25495. {
  25496. const ScopedLock sl (lock);
  25497. if (effect->getParameter (effect, index) != newValue)
  25498. effect->setParameter (effect, index, newValue);
  25499. }
  25500. catch (...)
  25501. {
  25502. }
  25503. }
  25504. }
  25505. const String VSTPluginInstance::getParameterName (int index)
  25506. {
  25507. if (effect != 0)
  25508. {
  25509. jassert (index >= 0 && index < effect->numParams);
  25510. char nm [256];
  25511. zerostruct (nm);
  25512. dispatch (effGetParamName, index, 0, nm, 0);
  25513. return String (nm).trim();
  25514. }
  25515. return String::empty;
  25516. }
  25517. const String VSTPluginInstance::getParameterLabel (int index) const
  25518. {
  25519. if (effect != 0)
  25520. {
  25521. jassert (index >= 0 && index < effect->numParams);
  25522. char nm [256];
  25523. zerostruct (nm);
  25524. dispatch (effGetParamLabel, index, 0, nm, 0);
  25525. return String (nm).trim();
  25526. }
  25527. return String::empty;
  25528. }
  25529. const String VSTPluginInstance::getParameterText (int index)
  25530. {
  25531. if (effect != 0)
  25532. {
  25533. jassert (index >= 0 && index < effect->numParams);
  25534. char nm [256];
  25535. zerostruct (nm);
  25536. dispatch (effGetParamDisplay, index, 0, nm, 0);
  25537. return String (nm).trim();
  25538. }
  25539. return String::empty;
  25540. }
  25541. bool VSTPluginInstance::isParameterAutomatable (int index) const
  25542. {
  25543. if (effect != 0)
  25544. {
  25545. jassert (index >= 0 && index < effect->numParams);
  25546. return dispatch (effCanBeAutomated, index, 0, 0, 0) != 0;
  25547. }
  25548. return false;
  25549. }
  25550. void VSTPluginInstance::createTempParameterStore (MemoryBlock& dest)
  25551. {
  25552. dest.setSize (64 + 4 * getNumParameters());
  25553. dest.fillWith (0);
  25554. getCurrentProgramName().copyToBuffer ((char*) dest.getData(), 63);
  25555. float* const p = (float*) (((char*) dest.getData()) + 64);
  25556. for (int i = 0; i < getNumParameters(); ++i)
  25557. p[i] = getParameter(i);
  25558. }
  25559. void VSTPluginInstance::restoreFromTempParameterStore (const MemoryBlock& m)
  25560. {
  25561. changeProgramName (getCurrentProgram(), (const char*) m.getData());
  25562. float* p = (float*) (((char*) m.getData()) + 64);
  25563. for (int i = 0; i < getNumParameters(); ++i)
  25564. setParameter (i, p[i]);
  25565. }
  25566. void VSTPluginInstance::setCurrentProgram (int newIndex)
  25567. {
  25568. if (getNumPrograms() > 0 && newIndex != getCurrentProgram())
  25569. dispatch (effSetProgram, 0, jlimit (0, getNumPrograms() - 1, newIndex), 0, 0);
  25570. }
  25571. const String VSTPluginInstance::getProgramName (int index)
  25572. {
  25573. if (index == getCurrentProgram())
  25574. {
  25575. return getCurrentProgramName();
  25576. }
  25577. else if (effect != 0)
  25578. {
  25579. char nm [256];
  25580. zerostruct (nm);
  25581. if (dispatch (effGetProgramNameIndexed,
  25582. jlimit (0, getNumPrograms(), index),
  25583. -1, nm, 0) != 0)
  25584. {
  25585. return String (nm).trim();
  25586. }
  25587. }
  25588. return programNames [index];
  25589. }
  25590. void VSTPluginInstance::changeProgramName (int index, const String& newName)
  25591. {
  25592. if (index == getCurrentProgram())
  25593. {
  25594. if (getNumPrograms() > 0 && newName != getCurrentProgramName())
  25595. dispatch (effSetProgramName, 0, 0, (void*) (const char*) newName.substring (0, 24), 0.0f);
  25596. }
  25597. else
  25598. {
  25599. jassertfalse // xxx not implemented!
  25600. }
  25601. }
  25602. void VSTPluginInstance::updateStoredProgramNames()
  25603. {
  25604. if (effect != 0 && getNumPrograms() > 0)
  25605. {
  25606. char nm [256];
  25607. zerostruct (nm);
  25608. // only do this if the plugin can't use indexed names..
  25609. if (dispatch (effGetProgramNameIndexed, 0, -1, nm, 0) == 0)
  25610. {
  25611. const int oldProgram = getCurrentProgram();
  25612. MemoryBlock oldSettings;
  25613. createTempParameterStore (oldSettings);
  25614. for (int i = 0; i < getNumPrograms(); ++i)
  25615. {
  25616. setCurrentProgram (i);
  25617. getCurrentProgramName(); // (this updates the list)
  25618. }
  25619. setCurrentProgram (oldProgram);
  25620. restoreFromTempParameterStore (oldSettings);
  25621. }
  25622. }
  25623. }
  25624. const String VSTPluginInstance::getCurrentProgramName()
  25625. {
  25626. if (effect != 0)
  25627. {
  25628. char nm [256];
  25629. zerostruct (nm);
  25630. dispatch (effGetProgramName, 0, 0, nm, 0);
  25631. const int index = getCurrentProgram();
  25632. if (programNames[index].isEmpty())
  25633. {
  25634. while (programNames.size() < index)
  25635. programNames.add (String::empty);
  25636. programNames.set (index, String (nm).trim());
  25637. }
  25638. return String (nm).trim();
  25639. }
  25640. return String::empty;
  25641. }
  25642. const String VSTPluginInstance::getInputChannelName (const int index) const
  25643. {
  25644. if (index >= 0 && index < getNumInputChannels())
  25645. {
  25646. VstPinProperties pinProps;
  25647. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  25648. return String (pinProps.label, sizeof (pinProps.label));
  25649. }
  25650. return String::empty;
  25651. }
  25652. bool VSTPluginInstance::isInputChannelStereoPair (int index) const
  25653. {
  25654. if (index < 0 || index >= getNumInputChannels())
  25655. return false;
  25656. VstPinProperties pinProps;
  25657. if (dispatch (effGetInputProperties, index, 0, &pinProps, 0.0f) != 0)
  25658. return (pinProps.flags & kVstPinIsStereo) != 0;
  25659. return true;
  25660. }
  25661. const String VSTPluginInstance::getOutputChannelName (const int index) const
  25662. {
  25663. if (index >= 0 && index < getNumOutputChannels())
  25664. {
  25665. VstPinProperties pinProps;
  25666. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  25667. return String (pinProps.label, sizeof (pinProps.label));
  25668. }
  25669. return String::empty;
  25670. }
  25671. bool VSTPluginInstance::isOutputChannelStereoPair (int index) const
  25672. {
  25673. if (index < 0 || index >= getNumOutputChannels())
  25674. return false;
  25675. VstPinProperties pinProps;
  25676. if (dispatch (effGetOutputProperties, index, 0, &pinProps, 0.0f) != 0)
  25677. return (pinProps.flags & kVstPinIsStereo) != 0;
  25678. return true;
  25679. }
  25680. void VSTPluginInstance::setPower (const bool on)
  25681. {
  25682. dispatch (effMainsChanged, 0, on ? 1 : 0, 0, 0);
  25683. isPowerOn = on;
  25684. }
  25685. const int defaultMaxSizeMB = 64;
  25686. void VSTPluginInstance::getStateInformation (MemoryBlock& destData)
  25687. {
  25688. saveToFXBFile (destData, true, defaultMaxSizeMB);
  25689. }
  25690. void VSTPluginInstance::getCurrentProgramStateInformation (MemoryBlock& destData)
  25691. {
  25692. saveToFXBFile (destData, false, defaultMaxSizeMB);
  25693. }
  25694. void VSTPluginInstance::setStateInformation (const void* data, int sizeInBytes)
  25695. {
  25696. loadFromFXBFile (data, sizeInBytes);
  25697. }
  25698. void VSTPluginInstance::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  25699. {
  25700. loadFromFXBFile (data, sizeInBytes);
  25701. }
  25702. VSTPluginFormat::VSTPluginFormat()
  25703. {
  25704. }
  25705. VSTPluginFormat::~VSTPluginFormat()
  25706. {
  25707. }
  25708. void VSTPluginFormat::findAllTypesForFile (OwnedArray <PluginDescription>& results,
  25709. const File& file)
  25710. {
  25711. if (! fileMightContainThisPluginType (file))
  25712. return;
  25713. PluginDescription desc;
  25714. desc.file = file;
  25715. desc.uid = 0;
  25716. VSTPluginInstance* instance = dynamic_cast <VSTPluginInstance*> (createInstanceFromDescription (desc));
  25717. if (instance == 0)
  25718. return;
  25719. try
  25720. {
  25721. #if JUCE_MAC
  25722. if (instance->module->resFileId != 0)
  25723. UseResFile (instance->module->resFileId);
  25724. #endif
  25725. instance->fillInPluginDescription (desc);
  25726. VstPlugCategory category = (VstPlugCategory) instance->dispatch (effGetPlugCategory, 0, 0, 0, 0);
  25727. if (category != kPlugCategShell)
  25728. {
  25729. // Normal plugin...
  25730. results.add (new PluginDescription (desc));
  25731. ++insideVSTCallback;
  25732. instance->dispatch (effOpen, 0, 0, 0, 0);
  25733. --insideVSTCallback;
  25734. }
  25735. else
  25736. {
  25737. // It's a shell plugin, so iterate all the subtypes...
  25738. char shellEffectName [64];
  25739. for (;;)
  25740. {
  25741. zerostruct (shellEffectName);
  25742. const int uid = instance->dispatch (effShellGetNextPlugin, 0, 0, shellEffectName, 0);
  25743. if (uid == 0)
  25744. {
  25745. break;
  25746. }
  25747. else
  25748. {
  25749. desc.uid = uid;
  25750. desc.name = shellEffectName;
  25751. bool alreadyThere = false;
  25752. for (int i = results.size(); --i >= 0;)
  25753. {
  25754. PluginDescription* const d = results.getUnchecked(i);
  25755. if (d->isDuplicateOf (desc))
  25756. {
  25757. alreadyThere = true;
  25758. break;
  25759. }
  25760. }
  25761. if (! alreadyThere)
  25762. results.add (new PluginDescription (desc));
  25763. }
  25764. }
  25765. }
  25766. }
  25767. catch (...)
  25768. {
  25769. // crashed while loading...
  25770. }
  25771. deleteAndZero (instance);
  25772. }
  25773. AudioPluginInstance* VSTPluginFormat::createInstanceFromDescription (const PluginDescription& desc)
  25774. {
  25775. VSTPluginInstance* result = 0;
  25776. if (fileMightContainThisPluginType (desc.file))
  25777. {
  25778. const File previousWorkingDirectory (File::getCurrentWorkingDirectory());
  25779. desc.file.getParentDirectory().setAsCurrentWorkingDirectory();
  25780. const ReferenceCountedObjectPtr <ModuleHandle> module (ModuleHandle::findOrCreateModule (desc.file));
  25781. if (module != 0)
  25782. {
  25783. shellUIDToCreate = desc.uid;
  25784. result = new VSTPluginInstance (module);
  25785. if (result->effect != 0)
  25786. {
  25787. result->effect->resvd2 = (VstIntPtr) (pointer_sized_int) result;
  25788. result->initialise();
  25789. }
  25790. else
  25791. {
  25792. deleteAndZero (result);
  25793. }
  25794. }
  25795. previousWorkingDirectory.setAsCurrentWorkingDirectory();
  25796. }
  25797. return result;
  25798. }
  25799. bool VSTPluginFormat::fileMightContainThisPluginType (const File& f)
  25800. {
  25801. #if JUCE_MAC
  25802. if (f.isDirectory() && f.hasFileExtension (T(".vst")))
  25803. return true;
  25804. #if JUCE_PPC
  25805. FSRef fileRef;
  25806. if (PlatformUtilities::makeFSRefFromPath (&fileRef, f.getFullPathName()))
  25807. {
  25808. const short resFileId = FSOpenResFile (&fileRef, fsRdPerm);
  25809. if (resFileId != -1)
  25810. {
  25811. const int numEffects = Count1Resources ('aEff');
  25812. CloseResFile (resFileId);
  25813. if (numEffects > 0)
  25814. return true;
  25815. }
  25816. }
  25817. #endif
  25818. return false;
  25819. #elif JUCE_WIN32
  25820. return f.existsAsFile()
  25821. && f.hasFileExtension (T(".dll"));
  25822. #elif JUCE_LINUX
  25823. return f.existsAsFile()
  25824. && f.hasFileExtension (T(".so"));
  25825. #endif
  25826. }
  25827. const FileSearchPath VSTPluginFormat::getDefaultLocationsToSearch()
  25828. {
  25829. #if JUCE_MAC
  25830. return FileSearchPath ("~/Library/Audio/Plug-Ins/VST;/Library/Audio/Plug-Ins/VST");
  25831. #elif JUCE_WIN32
  25832. const String programFiles (File::getSpecialLocation (File::globalApplicationsDirectory).getFullPathName());
  25833. return FileSearchPath (programFiles + "\\Steinberg\\VstPlugins");
  25834. #elif JUCE_LINUX
  25835. return FileSearchPath ("/usr/lib/vst");
  25836. #endif
  25837. }
  25838. END_JUCE_NAMESPACE
  25839. #endif
  25840. #undef log
  25841. #endif
  25842. /********* End of inlined file: juce_VSTPluginFormat.cpp *********/
  25843. /********* End of inlined file: juce_VSTPluginFormat.mm *********/
  25844. /********* Start of inlined file: juce_AudioProcessor.cpp *********/
  25845. BEGIN_JUCE_NAMESPACE
  25846. AudioProcessor::AudioProcessor()
  25847. : playHead (0),
  25848. activeEditor (0),
  25849. sampleRate (0),
  25850. blockSize (0),
  25851. numInputChannels (0),
  25852. numOutputChannels (0),
  25853. latencySamples (0),
  25854. suspended (false),
  25855. nonRealtime (false)
  25856. {
  25857. }
  25858. AudioProcessor::~AudioProcessor()
  25859. {
  25860. // ooh, nasty - the editor should have been deleted before the filter
  25861. // that it refers to is deleted..
  25862. jassert (activeEditor == 0);
  25863. #ifdef JUCE_DEBUG
  25864. // This will fail if you've called beginParameterChangeGesture() for one
  25865. // or more parameters without having made a corresponding call to endParameterChangeGesture...
  25866. jassert (changingParams.countNumberOfSetBits() == 0);
  25867. #endif
  25868. }
  25869. void AudioProcessor::setPlayHead (AudioPlayHead* const newPlayHead) throw()
  25870. {
  25871. playHead = newPlayHead;
  25872. }
  25873. void AudioProcessor::addListener (AudioProcessorListener* const newListener) throw()
  25874. {
  25875. const ScopedLock sl (listenerLock);
  25876. listeners.addIfNotAlreadyThere (newListener);
  25877. }
  25878. void AudioProcessor::removeListener (AudioProcessorListener* const listenerToRemove) throw()
  25879. {
  25880. const ScopedLock sl (listenerLock);
  25881. listeners.removeValue (listenerToRemove);
  25882. }
  25883. void AudioProcessor::setPlayConfigDetails (const int numIns,
  25884. const int numOuts,
  25885. const double sampleRate_,
  25886. const int blockSize_) throw()
  25887. {
  25888. numInputChannels = numIns;
  25889. numOutputChannels = numOuts;
  25890. sampleRate = sampleRate_;
  25891. blockSize = blockSize_;
  25892. }
  25893. void AudioProcessor::setNonRealtime (const bool nonRealtime_) throw()
  25894. {
  25895. nonRealtime = nonRealtime_;
  25896. }
  25897. void AudioProcessor::setLatencySamples (const int newLatency)
  25898. {
  25899. if (latencySamples != newLatency)
  25900. {
  25901. latencySamples = newLatency;
  25902. updateHostDisplay();
  25903. }
  25904. }
  25905. void AudioProcessor::setParameterNotifyingHost (const int parameterIndex,
  25906. const float newValue)
  25907. {
  25908. setParameter (parameterIndex, newValue);
  25909. sendParamChangeMessageToListeners (parameterIndex, newValue);
  25910. }
  25911. void AudioProcessor::sendParamChangeMessageToListeners (const int parameterIndex, const float newValue)
  25912. {
  25913. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  25914. for (int i = listeners.size(); --i >= 0;)
  25915. {
  25916. listenerLock.enter();
  25917. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  25918. listenerLock.exit();
  25919. if (l != 0)
  25920. l->audioProcessorParameterChanged (this, parameterIndex, newValue);
  25921. }
  25922. }
  25923. void AudioProcessor::beginParameterChangeGesture (int parameterIndex)
  25924. {
  25925. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  25926. #ifdef JUCE_DEBUG
  25927. // This means you've called beginParameterChangeGesture twice in succession without a matching
  25928. // call to endParameterChangeGesture. That might be fine in most hosts, but better to avoid doing it.
  25929. jassert (! changingParams [parameterIndex]);
  25930. changingParams.setBit (parameterIndex);
  25931. #endif
  25932. for (int i = listeners.size(); --i >= 0;)
  25933. {
  25934. listenerLock.enter();
  25935. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  25936. listenerLock.exit();
  25937. if (l != 0)
  25938. l->audioProcessorParameterChangeGestureBegin (this, parameterIndex);
  25939. }
  25940. }
  25941. void AudioProcessor::endParameterChangeGesture (int parameterIndex)
  25942. {
  25943. jassert (((unsigned int) parameterIndex) < (unsigned int) getNumParameters());
  25944. #ifdef JUCE_DEBUG
  25945. // This means you've called endParameterChangeGesture without having previously called
  25946. // endParameterChangeGesture. That might be fine in most hosts, but better to keep the
  25947. // calls matched correctly.
  25948. jassert (changingParams [parameterIndex]);
  25949. changingParams.clearBit (parameterIndex);
  25950. #endif
  25951. for (int i = listeners.size(); --i >= 0;)
  25952. {
  25953. listenerLock.enter();
  25954. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  25955. listenerLock.exit();
  25956. if (l != 0)
  25957. l->audioProcessorParameterChangeGestureEnd (this, parameterIndex);
  25958. }
  25959. }
  25960. void AudioProcessor::updateHostDisplay()
  25961. {
  25962. for (int i = listeners.size(); --i >= 0;)
  25963. {
  25964. listenerLock.enter();
  25965. AudioProcessorListener* const l = (AudioProcessorListener*) listeners [i];
  25966. listenerLock.exit();
  25967. if (l != 0)
  25968. l->audioProcessorChanged (this);
  25969. }
  25970. }
  25971. bool AudioProcessor::isParameterAutomatable (int /*parameterIndex*/) const
  25972. {
  25973. return true;
  25974. }
  25975. bool AudioProcessor::isMetaParameter (int /*parameterIndex*/) const
  25976. {
  25977. return false;
  25978. }
  25979. void AudioProcessor::suspendProcessing (const bool shouldBeSuspended)
  25980. {
  25981. const ScopedLock sl (callbackLock);
  25982. suspended = shouldBeSuspended;
  25983. }
  25984. void AudioProcessor::reset()
  25985. {
  25986. }
  25987. void AudioProcessor::editorBeingDeleted (AudioProcessorEditor* const editor) throw()
  25988. {
  25989. const ScopedLock sl (callbackLock);
  25990. jassert (activeEditor == editor);
  25991. if (activeEditor == editor)
  25992. activeEditor = 0;
  25993. }
  25994. AudioProcessorEditor* AudioProcessor::createEditorIfNeeded()
  25995. {
  25996. if (activeEditor != 0)
  25997. return activeEditor;
  25998. AudioProcessorEditor* const ed = createEditor();
  25999. if (ed != 0)
  26000. {
  26001. // you must give your editor comp a size before returning it..
  26002. jassert (ed->getWidth() > 0 && ed->getHeight() > 0);
  26003. const ScopedLock sl (callbackLock);
  26004. activeEditor = ed;
  26005. }
  26006. return ed;
  26007. }
  26008. void AudioProcessor::getCurrentProgramStateInformation (JUCE_NAMESPACE::MemoryBlock& destData)
  26009. {
  26010. getStateInformation (destData);
  26011. }
  26012. void AudioProcessor::setCurrentProgramStateInformation (const void* data, int sizeInBytes)
  26013. {
  26014. setStateInformation (data, sizeInBytes);
  26015. }
  26016. // magic number to identify memory blocks that we've stored as XML
  26017. const uint32 magicXmlNumber = 0x21324356;
  26018. void AudioProcessor::copyXmlToBinary (const XmlElement& xml,
  26019. JUCE_NAMESPACE::MemoryBlock& destData)
  26020. {
  26021. const String xmlString (xml.createDocument (String::empty, true, false));
  26022. const int stringLength = xmlString.length();
  26023. destData.setSize (stringLength + 10);
  26024. char* const d = (char*) destData.getData();
  26025. *(uint32*) d = swapIfBigEndian ((const uint32) magicXmlNumber);
  26026. *(uint32*) (d + 4) = swapIfBigEndian ((const uint32) stringLength);
  26027. xmlString.copyToBuffer (d + 8, stringLength);
  26028. }
  26029. XmlElement* AudioProcessor::getXmlFromBinary (const void* data,
  26030. const int sizeInBytes)
  26031. {
  26032. if (sizeInBytes > 8
  26033. && littleEndianInt ((const char*) data) == magicXmlNumber)
  26034. {
  26035. const uint32 stringLength = littleEndianInt (((const char*) data) + 4);
  26036. if (stringLength > 0)
  26037. {
  26038. XmlDocument doc (String (((const char*) data) + 8,
  26039. jmin ((sizeInBytes - 8), stringLength)));
  26040. return doc.getDocumentElement();
  26041. }
  26042. }
  26043. return 0;
  26044. }
  26045. void AudioProcessorListener::audioProcessorParameterChangeGestureBegin (AudioProcessor*, int)
  26046. {
  26047. }
  26048. void AudioProcessorListener::audioProcessorParameterChangeGestureEnd (AudioProcessor*, int)
  26049. {
  26050. }
  26051. END_JUCE_NAMESPACE
  26052. /********* End of inlined file: juce_AudioProcessor.cpp *********/
  26053. /********* Start of inlined file: juce_AudioProcessorEditor.cpp *********/
  26054. BEGIN_JUCE_NAMESPACE
  26055. AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* const owner_)
  26056. : owner (owner_)
  26057. {
  26058. // the filter must be valid..
  26059. jassert (owner != 0);
  26060. }
  26061. AudioProcessorEditor::~AudioProcessorEditor()
  26062. {
  26063. // if this fails, then the wrapper hasn't called editorBeingDeleted() on the
  26064. // filter for some reason..
  26065. jassert (owner->getActiveEditor() != this);
  26066. }
  26067. END_JUCE_NAMESPACE
  26068. /********* End of inlined file: juce_AudioProcessorEditor.cpp *********/
  26069. /********* Start of inlined file: juce_AudioProcessorGraph.cpp *********/
  26070. BEGIN_JUCE_NAMESPACE
  26071. const int AudioProcessorGraph::midiChannelIndex = 0x1000;
  26072. AudioProcessorGraph::Node::Node (const uint32 id_,
  26073. AudioProcessor* const processor_) throw()
  26074. : id (id_),
  26075. processor (processor_),
  26076. isPrepared (false)
  26077. {
  26078. jassert (processor_ != 0);
  26079. }
  26080. AudioProcessorGraph::Node::~Node()
  26081. {
  26082. delete processor;
  26083. }
  26084. void AudioProcessorGraph::Node::prepare (const double sampleRate, const int blockSize,
  26085. AudioProcessorGraph* const graph)
  26086. {
  26087. if (! isPrepared)
  26088. {
  26089. isPrepared = true;
  26090. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  26091. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (processor);
  26092. if (ioProc != 0)
  26093. ioProc->setParentGraph (graph);
  26094. processor->setPlayConfigDetails (processor->getNumInputChannels(),
  26095. processor->getNumOutputChannels(),
  26096. sampleRate, blockSize);
  26097. processor->prepareToPlay (sampleRate, blockSize);
  26098. }
  26099. }
  26100. void AudioProcessorGraph::Node::unprepare()
  26101. {
  26102. if (isPrepared)
  26103. {
  26104. isPrepared = false;
  26105. processor->releaseResources();
  26106. }
  26107. }
  26108. AudioProcessorGraph::AudioProcessorGraph()
  26109. : lastNodeId (0),
  26110. renderingBuffers (1, 1),
  26111. currentAudioOutputBuffer (1, 1)
  26112. {
  26113. }
  26114. AudioProcessorGraph::~AudioProcessorGraph()
  26115. {
  26116. clearRenderingSequence();
  26117. clear();
  26118. }
  26119. const String AudioProcessorGraph::getName() const
  26120. {
  26121. return "Audio Graph";
  26122. }
  26123. void AudioProcessorGraph::clear()
  26124. {
  26125. nodes.clear();
  26126. connections.clear();
  26127. triggerAsyncUpdate();
  26128. }
  26129. AudioProcessorGraph::Node* AudioProcessorGraph::getNodeForId (const uint32 nodeId) const throw()
  26130. {
  26131. for (int i = nodes.size(); --i >= 0;)
  26132. if (nodes.getUnchecked(i)->id == nodeId)
  26133. return nodes.getUnchecked(i);
  26134. return 0;
  26135. }
  26136. AudioProcessorGraph::Node* AudioProcessorGraph::addNode (AudioProcessor* const newProcessor,
  26137. uint32 nodeId)
  26138. {
  26139. if (newProcessor == 0)
  26140. {
  26141. jassertfalse
  26142. return 0;
  26143. }
  26144. if (nodeId == 0)
  26145. {
  26146. nodeId = ++lastNodeId;
  26147. }
  26148. else
  26149. {
  26150. // you can't add a node with an id that already exists in the graph..
  26151. jassert (getNodeForId (nodeId) == 0);
  26152. removeNode (nodeId);
  26153. }
  26154. lastNodeId = nodeId;
  26155. Node* const n = new Node (nodeId, newProcessor);
  26156. nodes.add (n);
  26157. triggerAsyncUpdate();
  26158. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  26159. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (n->processor);
  26160. if (ioProc != 0)
  26161. ioProc->setParentGraph (this);
  26162. return n;
  26163. }
  26164. bool AudioProcessorGraph::removeNode (const uint32 nodeId)
  26165. {
  26166. disconnectNode (nodeId);
  26167. for (int i = nodes.size(); --i >= 0;)
  26168. {
  26169. if (nodes.getUnchecked(i)->id == nodeId)
  26170. {
  26171. AudioProcessorGraph::AudioGraphIOProcessor* const ioProc
  26172. = dynamic_cast <AudioProcessorGraph::AudioGraphIOProcessor*> (nodes.getUnchecked(i)->processor);
  26173. if (ioProc != 0)
  26174. ioProc->setParentGraph (0);
  26175. nodes.remove (i);
  26176. triggerAsyncUpdate();
  26177. return true;
  26178. }
  26179. }
  26180. return false;
  26181. }
  26182. const AudioProcessorGraph::Connection* AudioProcessorGraph::getConnectionBetween (const uint32 sourceNodeId,
  26183. const int sourceChannelIndex,
  26184. const uint32 destNodeId,
  26185. const int destChannelIndex) const throw()
  26186. {
  26187. for (int i = connections.size(); --i >= 0;)
  26188. {
  26189. const Connection* const c = connections.getUnchecked(i);
  26190. if (c->sourceNodeId == sourceNodeId
  26191. && c->destNodeId == destNodeId
  26192. && c->sourceChannelIndex == sourceChannelIndex
  26193. && c->destChannelIndex == destChannelIndex)
  26194. {
  26195. return c;
  26196. }
  26197. }
  26198. return 0;
  26199. }
  26200. bool AudioProcessorGraph::isConnected (const uint32 possibleSourceNodeId,
  26201. const uint32 possibleDestNodeId) const throw()
  26202. {
  26203. for (int i = connections.size(); --i >= 0;)
  26204. {
  26205. const Connection* const c = connections.getUnchecked(i);
  26206. if (c->sourceNodeId == possibleSourceNodeId
  26207. && c->destNodeId == possibleDestNodeId)
  26208. {
  26209. return true;
  26210. }
  26211. }
  26212. return false;
  26213. }
  26214. bool AudioProcessorGraph::canConnect (const uint32 sourceNodeId,
  26215. const int sourceChannelIndex,
  26216. const uint32 destNodeId,
  26217. const int destChannelIndex) const throw()
  26218. {
  26219. if (sourceChannelIndex < 0
  26220. || destChannelIndex < 0
  26221. || sourceNodeId == destNodeId
  26222. || (destChannelIndex == midiChannelIndex) != (sourceChannelIndex == midiChannelIndex))
  26223. return false;
  26224. const Node* const source = getNodeForId (sourceNodeId);
  26225. if (source == 0
  26226. || (sourceChannelIndex != midiChannelIndex && sourceChannelIndex >= source->processor->getNumOutputChannels())
  26227. || (sourceChannelIndex == midiChannelIndex && ! source->processor->producesMidi()))
  26228. return false;
  26229. const Node* const dest = getNodeForId (destNodeId);
  26230. if (dest == 0
  26231. || (destChannelIndex != midiChannelIndex && destChannelIndex >= dest->processor->getNumInputChannels())
  26232. || (destChannelIndex == midiChannelIndex && ! dest->processor->acceptsMidi()))
  26233. return false;
  26234. return getConnectionBetween (sourceNodeId, sourceChannelIndex,
  26235. destNodeId, destChannelIndex) == 0;
  26236. }
  26237. bool AudioProcessorGraph::addConnection (const uint32 sourceNodeId,
  26238. const int sourceChannelIndex,
  26239. const uint32 destNodeId,
  26240. const int destChannelIndex)
  26241. {
  26242. if (! canConnect (sourceNodeId, sourceChannelIndex, destNodeId, destChannelIndex))
  26243. return false;
  26244. Connection* const c = new Connection();
  26245. c->sourceNodeId = sourceNodeId;
  26246. c->sourceChannelIndex = sourceChannelIndex;
  26247. c->destNodeId = destNodeId;
  26248. c->destChannelIndex = destChannelIndex;
  26249. connections.add (c);
  26250. triggerAsyncUpdate();
  26251. return true;
  26252. }
  26253. void AudioProcessorGraph::removeConnection (const int index)
  26254. {
  26255. connections.remove (index);
  26256. triggerAsyncUpdate();
  26257. }
  26258. bool AudioProcessorGraph::removeConnection (const uint32 sourceNodeId, const int sourceChannelIndex,
  26259. const uint32 destNodeId, const int destChannelIndex)
  26260. {
  26261. bool doneAnything = false;
  26262. for (int i = connections.size(); --i >= 0;)
  26263. {
  26264. const Connection* const c = connections.getUnchecked(i);
  26265. if (c->sourceNodeId == sourceNodeId
  26266. && c->destNodeId == destNodeId
  26267. && c->sourceChannelIndex == sourceChannelIndex
  26268. && c->destChannelIndex == destChannelIndex)
  26269. {
  26270. removeConnection (i);
  26271. doneAnything = true;
  26272. triggerAsyncUpdate();
  26273. }
  26274. }
  26275. return doneAnything;
  26276. }
  26277. bool AudioProcessorGraph::disconnectNode (const uint32 nodeId)
  26278. {
  26279. bool doneAnything = false;
  26280. for (int i = connections.size(); --i >= 0;)
  26281. {
  26282. const Connection* const c = connections.getUnchecked(i);
  26283. if (c->sourceNodeId == nodeId || c->destNodeId == nodeId)
  26284. {
  26285. removeConnection (i);
  26286. doneAnything = true;
  26287. triggerAsyncUpdate();
  26288. }
  26289. }
  26290. return doneAnything;
  26291. }
  26292. bool AudioProcessorGraph::removeIllegalConnections()
  26293. {
  26294. bool doneAnything = false;
  26295. for (int i = connections.size(); --i >= 0;)
  26296. {
  26297. const Connection* const c = connections.getUnchecked(i);
  26298. const Node* const source = getNodeForId (c->sourceNodeId);
  26299. const Node* const dest = getNodeForId (c->destNodeId);
  26300. if (source == 0 || dest == 0
  26301. || (c->sourceChannelIndex != midiChannelIndex
  26302. && (((unsigned int) c->sourceChannelIndex) >= (unsigned int) source->processor->getNumOutputChannels()))
  26303. || (c->sourceChannelIndex == midiChannelIndex
  26304. && ! source->processor->producesMidi())
  26305. || (c->destChannelIndex != midiChannelIndex
  26306. && (((unsigned int) c->destChannelIndex) >= (unsigned int) dest->processor->getNumInputChannels()))
  26307. || (c->destChannelIndex == midiChannelIndex
  26308. && ! dest->processor->acceptsMidi()))
  26309. {
  26310. removeConnection (i);
  26311. doneAnything = true;
  26312. triggerAsyncUpdate();
  26313. }
  26314. }
  26315. return doneAnything;
  26316. }
  26317. namespace GraphRenderingOps
  26318. {
  26319. class AudioGraphRenderingOp
  26320. {
  26321. public:
  26322. AudioGraphRenderingOp() throw() {}
  26323. virtual ~AudioGraphRenderingOp() throw() {}
  26324. virtual void perform (AudioSampleBuffer& sharedBufferChans,
  26325. const OwnedArray <MidiBuffer>& sharedMidiBuffers,
  26326. const int numSamples) throw() = 0;
  26327. juce_UseDebuggingNewOperator
  26328. };
  26329. class ClearChannelOp : public AudioGraphRenderingOp
  26330. {
  26331. public:
  26332. ClearChannelOp (const int channelNum_) throw()
  26333. : channelNum (channelNum_)
  26334. {}
  26335. ~ClearChannelOp() throw() {}
  26336. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  26337. {
  26338. sharedBufferChans.clear (channelNum, 0, numSamples);
  26339. }
  26340. private:
  26341. const int channelNum;
  26342. ClearChannelOp (const ClearChannelOp&);
  26343. const ClearChannelOp& operator= (const ClearChannelOp&);
  26344. };
  26345. class CopyChannelOp : public AudioGraphRenderingOp
  26346. {
  26347. public:
  26348. CopyChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  26349. : srcChannelNum (srcChannelNum_),
  26350. dstChannelNum (dstChannelNum_)
  26351. {}
  26352. ~CopyChannelOp() throw() {}
  26353. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  26354. {
  26355. sharedBufferChans.copyFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  26356. }
  26357. private:
  26358. const int srcChannelNum, dstChannelNum;
  26359. CopyChannelOp (const CopyChannelOp&);
  26360. const CopyChannelOp& operator= (const CopyChannelOp&);
  26361. };
  26362. class AddChannelOp : public AudioGraphRenderingOp
  26363. {
  26364. public:
  26365. AddChannelOp (const int srcChannelNum_, const int dstChannelNum_) throw()
  26366. : srcChannelNum (srcChannelNum_),
  26367. dstChannelNum (dstChannelNum_)
  26368. {}
  26369. ~AddChannelOp() throw() {}
  26370. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>&, const int numSamples) throw()
  26371. {
  26372. sharedBufferChans.addFrom (dstChannelNum, 0, sharedBufferChans, srcChannelNum, 0, numSamples);
  26373. }
  26374. private:
  26375. const int srcChannelNum, dstChannelNum;
  26376. AddChannelOp (const AddChannelOp&);
  26377. const AddChannelOp& operator= (const AddChannelOp&);
  26378. };
  26379. class ClearMidiBufferOp : public AudioGraphRenderingOp
  26380. {
  26381. public:
  26382. ClearMidiBufferOp (const int bufferNum_) throw()
  26383. : bufferNum (bufferNum_)
  26384. {}
  26385. ~ClearMidiBufferOp() throw() {}
  26386. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  26387. {
  26388. sharedMidiBuffers.getUnchecked (bufferNum)->clear();
  26389. }
  26390. private:
  26391. const int bufferNum;
  26392. ClearMidiBufferOp (const ClearMidiBufferOp&);
  26393. const ClearMidiBufferOp& operator= (const ClearMidiBufferOp&);
  26394. };
  26395. class CopyMidiBufferOp : public AudioGraphRenderingOp
  26396. {
  26397. public:
  26398. CopyMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  26399. : srcBufferNum (srcBufferNum_),
  26400. dstBufferNum (dstBufferNum_)
  26401. {}
  26402. ~CopyMidiBufferOp() throw() {}
  26403. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int) throw()
  26404. {
  26405. *sharedMidiBuffers.getUnchecked (dstBufferNum) = *sharedMidiBuffers.getUnchecked (srcBufferNum);
  26406. }
  26407. private:
  26408. const int srcBufferNum, dstBufferNum;
  26409. CopyMidiBufferOp (const CopyMidiBufferOp&);
  26410. const CopyMidiBufferOp& operator= (const CopyMidiBufferOp&);
  26411. };
  26412. class AddMidiBufferOp : public AudioGraphRenderingOp
  26413. {
  26414. public:
  26415. AddMidiBufferOp (const int srcBufferNum_, const int dstBufferNum_) throw()
  26416. : srcBufferNum (srcBufferNum_),
  26417. dstBufferNum (dstBufferNum_)
  26418. {}
  26419. ~AddMidiBufferOp() throw() {}
  26420. void perform (AudioSampleBuffer&, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  26421. {
  26422. sharedMidiBuffers.getUnchecked (dstBufferNum)
  26423. ->addEvents (*sharedMidiBuffers.getUnchecked (srcBufferNum), 0, numSamples, 0);
  26424. }
  26425. private:
  26426. const int srcBufferNum, dstBufferNum;
  26427. AddMidiBufferOp (const AddMidiBufferOp&);
  26428. const AddMidiBufferOp& operator= (const AddMidiBufferOp&);
  26429. };
  26430. class ProcessBufferOp : public AudioGraphRenderingOp
  26431. {
  26432. public:
  26433. ProcessBufferOp (const AudioProcessorGraph::Node::Ptr& node_,
  26434. const Array <int>& audioChannelsToUse_,
  26435. const int totalChans_,
  26436. const int midiBufferToUse_) throw()
  26437. : node (node_),
  26438. processor (node_->processor),
  26439. audioChannelsToUse (audioChannelsToUse_),
  26440. totalChans (totalChans_),
  26441. midiBufferToUse (midiBufferToUse_)
  26442. {
  26443. channels = (float**) juce_calloc (sizeof (float*) * totalChans_);
  26444. }
  26445. ~ProcessBufferOp() throw()
  26446. {
  26447. juce_free (channels);
  26448. }
  26449. void perform (AudioSampleBuffer& sharedBufferChans, const OwnedArray <MidiBuffer>& sharedMidiBuffers, const int numSamples) throw()
  26450. {
  26451. for (int i = totalChans; --i >= 0;)
  26452. channels[i] = sharedBufferChans.getSampleData (audioChannelsToUse.getUnchecked (i), 0);
  26453. AudioSampleBuffer buffer (channels, totalChans, numSamples);
  26454. processor->processBlock (buffer, *sharedMidiBuffers.getUnchecked (midiBufferToUse));
  26455. }
  26456. const AudioProcessorGraph::Node::Ptr node;
  26457. AudioProcessor* const processor;
  26458. private:
  26459. Array <int> audioChannelsToUse;
  26460. float** channels;
  26461. int totalChans;
  26462. int midiBufferToUse;
  26463. ProcessBufferOp (const ProcessBufferOp&);
  26464. const ProcessBufferOp& operator= (const ProcessBufferOp&);
  26465. };
  26466. /** Used to calculate the correct sequence of rendering ops needed, based on
  26467. the best re-use of shared buffers at each stage.
  26468. */
  26469. class RenderingOpSequenceCalculator
  26470. {
  26471. public:
  26472. RenderingOpSequenceCalculator (AudioProcessorGraph& graph_,
  26473. const VoidArray& orderedNodes_,
  26474. VoidArray& renderingOps)
  26475. : graph (graph_),
  26476. orderedNodes (orderedNodes_)
  26477. {
  26478. nodeIds.add (-2); // first buffer is read-only zeros
  26479. channels.add (0);
  26480. midiNodeIds.add (-2);
  26481. for (int i = 0; i < orderedNodes.size(); ++i)
  26482. {
  26483. createRenderingOpsForNode ((AudioProcessorGraph::Node*) orderedNodes.getUnchecked(i),
  26484. renderingOps, i);
  26485. markAnyUnusedBuffersAsFree (i);
  26486. }
  26487. }
  26488. int getNumBuffersNeeded() const throw() { return nodeIds.size(); }
  26489. int getNumMidiBuffersNeeded() const throw() { return midiNodeIds.size(); }
  26490. juce_UseDebuggingNewOperator
  26491. private:
  26492. AudioProcessorGraph& graph;
  26493. const VoidArray& orderedNodes;
  26494. Array <int> nodeIds, channels, midiNodeIds;
  26495. void createRenderingOpsForNode (AudioProcessorGraph::Node* const node,
  26496. VoidArray& renderingOps,
  26497. const int ourRenderingIndex)
  26498. {
  26499. const int numIns = node->processor->getNumInputChannels();
  26500. const int numOuts = node->processor->getNumOutputChannels();
  26501. const int totalChans = jmax (numIns, numOuts);
  26502. Array <int> audioChannelsToUse;
  26503. int midiBufferToUse = -1;
  26504. for (int inputChan = 0; inputChan < numIns; ++inputChan)
  26505. {
  26506. // get a list of all the inputs to this node
  26507. Array <int> sourceNodes, sourceOutputChans;
  26508. for (int i = graph.getNumConnections(); --i >= 0;)
  26509. {
  26510. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  26511. if (c->destNodeId == node->id && c->destChannelIndex == inputChan)
  26512. {
  26513. sourceNodes.add (c->sourceNodeId);
  26514. sourceOutputChans.add (c->sourceChannelIndex);
  26515. }
  26516. }
  26517. int bufIndex = -1;
  26518. if (sourceNodes.size() == 0)
  26519. {
  26520. // unconnected input channel
  26521. if (inputChan >= numOuts)
  26522. {
  26523. bufIndex = getReadOnlyEmptyBuffer();
  26524. jassert (bufIndex >= 0);
  26525. }
  26526. else
  26527. {
  26528. bufIndex = getFreeBuffer (false);
  26529. renderingOps.add (new ClearChannelOp (bufIndex));
  26530. }
  26531. }
  26532. else if (sourceNodes.size() == 1)
  26533. {
  26534. // channel with a straightforward single input..
  26535. const int srcNode = sourceNodes.getUnchecked(0);
  26536. const int srcChan = sourceOutputChans.getUnchecked(0);
  26537. bufIndex = getBufferContaining (srcNode, srcChan);
  26538. if (bufIndex < 0)
  26539. {
  26540. // if not found, this is probably a feedback loop
  26541. bufIndex = getReadOnlyEmptyBuffer();
  26542. jassert (bufIndex >= 0);
  26543. }
  26544. if (inputChan < numOuts
  26545. && isBufferNeededLater (ourRenderingIndex,
  26546. inputChan,
  26547. srcNode, srcChan))
  26548. {
  26549. // can't mess up this channel because it's needed later by another node, so we
  26550. // need to use a copy of it..
  26551. const int newFreeBuffer = getFreeBuffer (false);
  26552. renderingOps.add (new CopyChannelOp (bufIndex, newFreeBuffer));
  26553. bufIndex = newFreeBuffer;
  26554. }
  26555. }
  26556. else
  26557. {
  26558. // channel with a mix of several inputs..
  26559. // try to find a re-usable channel from our inputs..
  26560. int reusableInputIndex = -1;
  26561. for (int i = 0; i < sourceNodes.size(); ++i)
  26562. {
  26563. const int sourceBufIndex = getBufferContaining (sourceNodes.getUnchecked(i),
  26564. sourceOutputChans.getUnchecked(i));
  26565. if (sourceBufIndex >= 0
  26566. && ! isBufferNeededLater (ourRenderingIndex,
  26567. inputChan,
  26568. sourceNodes.getUnchecked(i),
  26569. sourceOutputChans.getUnchecked(i)))
  26570. {
  26571. // we've found one of our input chans that can be re-used..
  26572. reusableInputIndex = i;
  26573. bufIndex = sourceBufIndex;
  26574. break;
  26575. }
  26576. }
  26577. if (reusableInputIndex < 0)
  26578. {
  26579. // can't re-use any of our input chans, so get a new one and copy everything into it..
  26580. bufIndex = getFreeBuffer (false);
  26581. jassert (bufIndex != 0);
  26582. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked (0),
  26583. sourceOutputChans.getUnchecked (0));
  26584. if (srcIndex < 0)
  26585. {
  26586. // if not found, this is probably a feedback loop
  26587. renderingOps.add (new ClearChannelOp (bufIndex));
  26588. }
  26589. else
  26590. {
  26591. renderingOps.add (new CopyChannelOp (srcIndex, bufIndex));
  26592. }
  26593. reusableInputIndex = 0;
  26594. }
  26595. for (int j = 0; j < sourceNodes.size(); ++j)
  26596. {
  26597. if (j != reusableInputIndex)
  26598. {
  26599. const int srcIndex = getBufferContaining (sourceNodes.getUnchecked(j),
  26600. sourceOutputChans.getUnchecked(j));
  26601. if (srcIndex >= 0)
  26602. renderingOps.add (new AddChannelOp (srcIndex, bufIndex));
  26603. }
  26604. }
  26605. }
  26606. jassert (bufIndex >= 0);
  26607. audioChannelsToUse.add (bufIndex);
  26608. if (inputChan < numOuts)
  26609. markBufferAsContaining (bufIndex, node->id, inputChan);
  26610. }
  26611. for (int outputChan = numIns; outputChan < numOuts; ++outputChan)
  26612. {
  26613. const int bufIndex = getFreeBuffer (false);
  26614. jassert (bufIndex != 0);
  26615. audioChannelsToUse.add (bufIndex);
  26616. markBufferAsContaining (bufIndex, node->id, outputChan);
  26617. }
  26618. // Now the same thing for midi..
  26619. Array <int> midiSourceNodes;
  26620. for (int i = graph.getNumConnections(); --i >= 0;)
  26621. {
  26622. const AudioProcessorGraph::Connection* const c = graph.getConnection (i);
  26623. if (c->destNodeId == node->id && c->destChannelIndex == AudioProcessorGraph::midiChannelIndex)
  26624. midiSourceNodes.add (c->sourceNodeId);
  26625. }
  26626. if (midiSourceNodes.size() == 0)
  26627. {
  26628. // No midi inputs..
  26629. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  26630. if (node->processor->acceptsMidi() || node->processor->producesMidi())
  26631. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  26632. }
  26633. else if (midiSourceNodes.size() == 1)
  26634. {
  26635. // One midi input..
  26636. midiBufferToUse = getBufferContaining (midiSourceNodes.getUnchecked(0),
  26637. AudioProcessorGraph::midiChannelIndex);
  26638. if (midiBufferToUse >= 0)
  26639. {
  26640. if (isBufferNeededLater (ourRenderingIndex,
  26641. AudioProcessorGraph::midiChannelIndex,
  26642. midiSourceNodes.getUnchecked(0),
  26643. AudioProcessorGraph::midiChannelIndex))
  26644. {
  26645. // can't mess up this channel because it's needed later by another node, so we
  26646. // need to use a copy of it..
  26647. const int newFreeBuffer = getFreeBuffer (true);
  26648. renderingOps.add (new CopyMidiBufferOp (midiBufferToUse, newFreeBuffer));
  26649. midiBufferToUse = newFreeBuffer;
  26650. }
  26651. }
  26652. else
  26653. {
  26654. // probably a feedback loop, so just use an empty one..
  26655. midiBufferToUse = getFreeBuffer (true); // need to pick a buffer even if the processor doesn't use midi
  26656. }
  26657. }
  26658. else
  26659. {
  26660. // More than one midi input being mixed..
  26661. int reusableInputIndex = -1;
  26662. for (int i = 0; i < midiSourceNodes.size(); ++i)
  26663. {
  26664. const int sourceBufIndex = getBufferContaining (midiSourceNodes.getUnchecked(i),
  26665. AudioProcessorGraph::midiChannelIndex);
  26666. if (sourceBufIndex >= 0
  26667. && ! isBufferNeededLater (ourRenderingIndex,
  26668. AudioProcessorGraph::midiChannelIndex,
  26669. midiSourceNodes.getUnchecked(i),
  26670. AudioProcessorGraph::midiChannelIndex))
  26671. {
  26672. // we've found one of our input buffers that can be re-used..
  26673. reusableInputIndex = i;
  26674. midiBufferToUse = sourceBufIndex;
  26675. break;
  26676. }
  26677. }
  26678. if (reusableInputIndex < 0)
  26679. {
  26680. // can't re-use any of our input buffers, so get a new one and copy everything into it..
  26681. midiBufferToUse = getFreeBuffer (true);
  26682. jassert (midiBufferToUse >= 0);
  26683. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(0),
  26684. AudioProcessorGraph::midiChannelIndex);
  26685. if (srcIndex >= 0)
  26686. renderingOps.add (new CopyMidiBufferOp (srcIndex, midiBufferToUse));
  26687. else
  26688. renderingOps.add (new ClearMidiBufferOp (midiBufferToUse));
  26689. reusableInputIndex = 0;
  26690. }
  26691. for (int j = 0; j < midiSourceNodes.size(); ++j)
  26692. {
  26693. if (j != reusableInputIndex)
  26694. {
  26695. const int srcIndex = getBufferContaining (midiSourceNodes.getUnchecked(j),
  26696. AudioProcessorGraph::midiChannelIndex);
  26697. if (srcIndex >= 0)
  26698. renderingOps.add (new AddMidiBufferOp (srcIndex, midiBufferToUse));
  26699. }
  26700. }
  26701. }
  26702. if (node->processor->producesMidi())
  26703. markBufferAsContaining (midiBufferToUse, node->id,
  26704. AudioProcessorGraph::midiChannelIndex);
  26705. renderingOps.add (new ProcessBufferOp (node, audioChannelsToUse,
  26706. totalChans, midiBufferToUse));
  26707. }
  26708. int getFreeBuffer (const bool forMidi)
  26709. {
  26710. if (forMidi)
  26711. {
  26712. for (int i = 1; i < midiNodeIds.size(); ++i)
  26713. if (midiNodeIds.getUnchecked(i) < 0)
  26714. return i;
  26715. midiNodeIds.add (-1);
  26716. return midiNodeIds.size() - 1;
  26717. }
  26718. else
  26719. {
  26720. for (int i = 1; i < nodeIds.size(); ++i)
  26721. if (nodeIds.getUnchecked(i) < 0)
  26722. return i;
  26723. nodeIds.add (-1);
  26724. channels.add (0);
  26725. return nodeIds.size() - 1;
  26726. }
  26727. }
  26728. int getReadOnlyEmptyBuffer() const throw()
  26729. {
  26730. return 0;
  26731. }
  26732. int getBufferContaining (const int nodeId, const int outputChannel) const throw()
  26733. {
  26734. if (outputChannel == AudioProcessorGraph::midiChannelIndex)
  26735. {
  26736. for (int i = midiNodeIds.size(); --i >= 0;)
  26737. if (midiNodeIds.getUnchecked(i) == nodeId)
  26738. return i;
  26739. }
  26740. else
  26741. {
  26742. for (int i = nodeIds.size(); --i >= 0;)
  26743. if (nodeIds.getUnchecked(i) == nodeId
  26744. && channels.getUnchecked(i) == outputChannel)
  26745. return i;
  26746. }
  26747. return -1;
  26748. }
  26749. void markAnyUnusedBuffersAsFree (const int stepIndex)
  26750. {
  26751. int i;
  26752. for (i = 0; i < nodeIds.size(); ++i)
  26753. {
  26754. if (nodeIds.getUnchecked(i) >= 0
  26755. && ! isBufferNeededLater (stepIndex, -1,
  26756. nodeIds.getUnchecked(i),
  26757. channels.getUnchecked(i)))
  26758. {
  26759. nodeIds.set (i, -1);
  26760. }
  26761. }
  26762. for (i = 0; i < midiNodeIds.size(); ++i)
  26763. {
  26764. if (midiNodeIds.getUnchecked(i) >= 0
  26765. && ! isBufferNeededLater (stepIndex, -1,
  26766. midiNodeIds.getUnchecked(i),
  26767. AudioProcessorGraph::midiChannelIndex))
  26768. {
  26769. midiNodeIds.set (i, -1);
  26770. }
  26771. }
  26772. }
  26773. bool isBufferNeededLater (int stepIndexToSearchFrom,
  26774. int inputChannelOfIndexToIgnore,
  26775. const int nodeId,
  26776. const int outputChanIndex) const throw()
  26777. {
  26778. while (stepIndexToSearchFrom < orderedNodes.size())
  26779. {
  26780. const AudioProcessorGraph::Node* const node = (const AudioProcessorGraph::Node*) orderedNodes.getUnchecked (stepIndexToSearchFrom);
  26781. if (outputChanIndex == AudioProcessorGraph::midiChannelIndex)
  26782. {
  26783. if (inputChannelOfIndexToIgnore != AudioProcessorGraph::midiChannelIndex
  26784. && graph.getConnectionBetween (nodeId, AudioProcessorGraph::midiChannelIndex,
  26785. node->id, AudioProcessorGraph::midiChannelIndex) != 0)
  26786. return true;
  26787. }
  26788. else
  26789. {
  26790. for (int i = 0; i < node->processor->getNumInputChannels(); ++i)
  26791. if (i != inputChannelOfIndexToIgnore
  26792. && graph.getConnectionBetween (nodeId, outputChanIndex,
  26793. node->id, i) != 0)
  26794. return true;
  26795. }
  26796. inputChannelOfIndexToIgnore = -1;
  26797. ++stepIndexToSearchFrom;
  26798. }
  26799. return false;
  26800. }
  26801. void markBufferAsContaining (int bufferNum, int nodeId, int outputIndex)
  26802. {
  26803. if (outputIndex == AudioProcessorGraph::midiChannelIndex)
  26804. {
  26805. jassert (bufferNum > 0 && bufferNum < midiNodeIds.size());
  26806. midiNodeIds.set (bufferNum, nodeId);
  26807. }
  26808. else
  26809. {
  26810. jassert (bufferNum >= 0 && bufferNum < nodeIds.size());
  26811. nodeIds.set (bufferNum, nodeId);
  26812. channels.set (bufferNum, outputIndex);
  26813. }
  26814. }
  26815. RenderingOpSequenceCalculator (const RenderingOpSequenceCalculator&);
  26816. const RenderingOpSequenceCalculator& operator= (const RenderingOpSequenceCalculator&);
  26817. };
  26818. }
  26819. void AudioProcessorGraph::clearRenderingSequence()
  26820. {
  26821. const ScopedLock sl (renderLock);
  26822. for (int i = renderingOps.size(); --i >= 0;)
  26823. {
  26824. GraphRenderingOps::AudioGraphRenderingOp* const r
  26825. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  26826. renderingOps.remove (i);
  26827. delete r;
  26828. }
  26829. }
  26830. bool AudioProcessorGraph::isAnInputTo (const uint32 possibleInputId,
  26831. const uint32 possibleDestinationId,
  26832. const int recursionCheck) const throw()
  26833. {
  26834. if (recursionCheck > 0)
  26835. {
  26836. for (int i = connections.size(); --i >= 0;)
  26837. {
  26838. const AudioProcessorGraph::Connection* const c = connections.getUnchecked (i);
  26839. if (c->destNodeId == possibleDestinationId
  26840. && (c->sourceNodeId == possibleInputId
  26841. || isAnInputTo (possibleInputId, c->sourceNodeId, recursionCheck - 1)))
  26842. return true;
  26843. }
  26844. }
  26845. return false;
  26846. }
  26847. void AudioProcessorGraph::buildRenderingSequence()
  26848. {
  26849. VoidArray newRenderingOps;
  26850. int numRenderingBuffersNeeded = 2;
  26851. int numMidiBuffersNeeded = 1;
  26852. {
  26853. MessageManagerLock mml;
  26854. VoidArray orderedNodes;
  26855. int i;
  26856. for (i = 0; i < nodes.size(); ++i)
  26857. {
  26858. Node* const node = nodes.getUnchecked(i);
  26859. node->prepare (getSampleRate(), getBlockSize(), this);
  26860. int j = 0;
  26861. for (; j < orderedNodes.size(); ++j)
  26862. if (isAnInputTo (node->id,
  26863. ((Node*) orderedNodes.getUnchecked (j))->id,
  26864. nodes.size() + 1))
  26865. break;
  26866. orderedNodes.insert (j, node);
  26867. }
  26868. GraphRenderingOps::RenderingOpSequenceCalculator calculator (*this, orderedNodes, newRenderingOps);
  26869. numRenderingBuffersNeeded = calculator.getNumBuffersNeeded();
  26870. numMidiBuffersNeeded = calculator.getNumMidiBuffersNeeded();
  26871. }
  26872. VoidArray oldRenderingOps (renderingOps);
  26873. {
  26874. // swap over to the new rendering sequence..
  26875. const ScopedLock sl (renderLock);
  26876. renderingBuffers.setSize (numRenderingBuffersNeeded, getBlockSize());
  26877. renderingBuffers.clear();
  26878. for (int i = midiBuffers.size(); --i >= 0;)
  26879. midiBuffers.getUnchecked(i)->clear();
  26880. while (midiBuffers.size() < numMidiBuffersNeeded)
  26881. midiBuffers.add (new MidiBuffer());
  26882. renderingOps = newRenderingOps;
  26883. }
  26884. for (int i = oldRenderingOps.size(); --i >= 0;)
  26885. delete (GraphRenderingOps::AudioGraphRenderingOp*) oldRenderingOps.getUnchecked(i);
  26886. }
  26887. void AudioProcessorGraph::handleAsyncUpdate()
  26888. {
  26889. buildRenderingSequence();
  26890. }
  26891. void AudioProcessorGraph::prepareToPlay (double /*sampleRate*/, int estimatedSamplesPerBlock)
  26892. {
  26893. currentAudioInputBuffer = 0;
  26894. currentAudioOutputBuffer.setSize (jmax (1, getNumOutputChannels()), estimatedSamplesPerBlock);
  26895. currentMidiInputBuffer = 0;
  26896. currentMidiOutputBuffer.clear();
  26897. clearRenderingSequence();
  26898. buildRenderingSequence();
  26899. }
  26900. void AudioProcessorGraph::releaseResources()
  26901. {
  26902. for (int i = 0; i < nodes.size(); ++i)
  26903. nodes.getUnchecked(i)->unprepare();
  26904. renderingBuffers.setSize (1, 1);
  26905. midiBuffers.clear();
  26906. currentAudioInputBuffer = 0;
  26907. currentAudioOutputBuffer.setSize (1, 1);
  26908. currentMidiInputBuffer = 0;
  26909. currentMidiOutputBuffer.clear();
  26910. }
  26911. void AudioProcessorGraph::processBlock (AudioSampleBuffer& buffer, MidiBuffer& midiMessages)
  26912. {
  26913. const int numSamples = buffer.getNumSamples();
  26914. const ScopedLock sl (renderLock);
  26915. currentAudioInputBuffer = &buffer;
  26916. currentAudioOutputBuffer.setSize (jmax (1, buffer.getNumChannels()), numSamples);
  26917. currentAudioOutputBuffer.clear();
  26918. currentMidiInputBuffer = &midiMessages;
  26919. currentMidiOutputBuffer.clear();
  26920. int i;
  26921. for (i = 0; i < renderingOps.size(); ++i)
  26922. {
  26923. GraphRenderingOps::AudioGraphRenderingOp* const op
  26924. = (GraphRenderingOps::AudioGraphRenderingOp*) renderingOps.getUnchecked(i);
  26925. op->perform (renderingBuffers, midiBuffers, numSamples);
  26926. }
  26927. for (i = 0; i < buffer.getNumChannels(); ++i)
  26928. buffer.copyFrom (i, 0, currentAudioOutputBuffer, i, 0, numSamples);
  26929. }
  26930. const String AudioProcessorGraph::getInputChannelName (const int channelIndex) const
  26931. {
  26932. return "Input " + String (channelIndex + 1);
  26933. }
  26934. const String AudioProcessorGraph::getOutputChannelName (const int channelIndex) const
  26935. {
  26936. return "Output " + String (channelIndex + 1);
  26937. }
  26938. bool AudioProcessorGraph::isInputChannelStereoPair (int /*index*/) const
  26939. {
  26940. return true;
  26941. }
  26942. bool AudioProcessorGraph::isOutputChannelStereoPair (int /*index*/) const
  26943. {
  26944. return true;
  26945. }
  26946. bool AudioProcessorGraph::acceptsMidi() const
  26947. {
  26948. return true;
  26949. }
  26950. bool AudioProcessorGraph::producesMidi() const
  26951. {
  26952. return true;
  26953. }
  26954. void AudioProcessorGraph::getStateInformation (JUCE_NAMESPACE::MemoryBlock& /*destData*/)
  26955. {
  26956. }
  26957. void AudioProcessorGraph::setStateInformation (const void* /*data*/, int /*sizeInBytes*/)
  26958. {
  26959. }
  26960. AudioProcessorGraph::AudioGraphIOProcessor::AudioGraphIOProcessor (const IODeviceType type_)
  26961. : type (type_),
  26962. graph (0)
  26963. {
  26964. }
  26965. AudioProcessorGraph::AudioGraphIOProcessor::~AudioGraphIOProcessor()
  26966. {
  26967. }
  26968. const String AudioProcessorGraph::AudioGraphIOProcessor::getName() const
  26969. {
  26970. switch (type)
  26971. {
  26972. case audioOutputNode:
  26973. return "Audio Output";
  26974. case audioInputNode:
  26975. return "Audio Input";
  26976. case midiOutputNode:
  26977. return "Midi Output";
  26978. case midiInputNode:
  26979. return "Midi Input";
  26980. default:
  26981. break;
  26982. }
  26983. return String::empty;
  26984. }
  26985. void AudioProcessorGraph::AudioGraphIOProcessor::fillInPluginDescription (PluginDescription& d) const
  26986. {
  26987. d.name = getName();
  26988. d.uid = d.name.hashCode();
  26989. d.category = "I/O devices";
  26990. d.pluginFormatName = "Internal";
  26991. d.manufacturerName = "Raw Material Software";
  26992. d.version = "1.0";
  26993. d.isInstrument = false;
  26994. d.numInputChannels = getNumInputChannels();
  26995. if (type == audioOutputNode && graph != 0)
  26996. d.numInputChannels = graph->getNumInputChannels();
  26997. d.numOutputChannels = getNumOutputChannels();
  26998. if (type == audioInputNode && graph != 0)
  26999. d.numOutputChannels = graph->getNumOutputChannels();
  27000. }
  27001. void AudioProcessorGraph::AudioGraphIOProcessor::prepareToPlay (double, int)
  27002. {
  27003. jassert (graph != 0);
  27004. }
  27005. void AudioProcessorGraph::AudioGraphIOProcessor::releaseResources()
  27006. {
  27007. }
  27008. void AudioProcessorGraph::AudioGraphIOProcessor::processBlock (AudioSampleBuffer& buffer,
  27009. MidiBuffer& midiMessages)
  27010. {
  27011. jassert (graph != 0);
  27012. switch (type)
  27013. {
  27014. case audioOutputNode:
  27015. {
  27016. for (int i = jmin (graph->currentAudioOutputBuffer.getNumChannels(),
  27017. buffer.getNumChannels()); --i >= 0;)
  27018. {
  27019. graph->currentAudioOutputBuffer.addFrom (i, 0, buffer, i, 0, buffer.getNumSamples());
  27020. }
  27021. break;
  27022. }
  27023. case audioInputNode:
  27024. {
  27025. for (int i = jmin (graph->currentAudioInputBuffer->getNumChannels(),
  27026. buffer.getNumChannels()); --i >= 0;)
  27027. {
  27028. buffer.copyFrom (i, 0, *graph->currentAudioInputBuffer, i, 0, buffer.getNumSamples());
  27029. }
  27030. break;
  27031. }
  27032. case midiOutputNode:
  27033. graph->currentMidiOutputBuffer.addEvents (midiMessages, 0, buffer.getNumSamples(), 0);
  27034. break;
  27035. case midiInputNode:
  27036. midiMessages.addEvents (*graph->currentMidiInputBuffer, 0, buffer.getNumSamples(), 0);
  27037. break;
  27038. default:
  27039. break;
  27040. }
  27041. }
  27042. bool AudioProcessorGraph::AudioGraphIOProcessor::acceptsMidi() const
  27043. {
  27044. return type == midiOutputNode;
  27045. }
  27046. bool AudioProcessorGraph::AudioGraphIOProcessor::producesMidi() const
  27047. {
  27048. return type == midiInputNode;
  27049. }
  27050. const String AudioProcessorGraph::AudioGraphIOProcessor::getInputChannelName (const int channelIndex) const
  27051. {
  27052. switch (type)
  27053. {
  27054. case audioOutputNode:
  27055. return "Output " + String (channelIndex + 1);
  27056. case midiOutputNode:
  27057. return "Midi Output";
  27058. default:
  27059. break;
  27060. }
  27061. return String::empty;
  27062. }
  27063. const String AudioProcessorGraph::AudioGraphIOProcessor::getOutputChannelName (const int channelIndex) const
  27064. {
  27065. switch (type)
  27066. {
  27067. case audioInputNode:
  27068. return "Input " + String (channelIndex + 1);
  27069. case midiInputNode:
  27070. return "Midi Input";
  27071. default:
  27072. break;
  27073. }
  27074. return String::empty;
  27075. }
  27076. bool AudioProcessorGraph::AudioGraphIOProcessor::isInputChannelStereoPair (int /*index*/) const
  27077. {
  27078. return type == audioInputNode || type == audioOutputNode;
  27079. }
  27080. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutputChannelStereoPair (int index) const
  27081. {
  27082. return isInputChannelStereoPair (index);
  27083. }
  27084. bool AudioProcessorGraph::AudioGraphIOProcessor::isInput() const throw()
  27085. {
  27086. return type == audioInputNode || type == midiInputNode;
  27087. }
  27088. bool AudioProcessorGraph::AudioGraphIOProcessor::isOutput() const throw()
  27089. {
  27090. return type == audioOutputNode || type == midiOutputNode;
  27091. }
  27092. AudioProcessorEditor* AudioProcessorGraph::AudioGraphIOProcessor::createEditor()
  27093. {
  27094. return 0;
  27095. }
  27096. int AudioProcessorGraph::AudioGraphIOProcessor::getNumParameters() { return 0; }
  27097. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterName (int) { return String::empty; }
  27098. float AudioProcessorGraph::AudioGraphIOProcessor::getParameter (int) { return 0.0f; }
  27099. const String AudioProcessorGraph::AudioGraphIOProcessor::getParameterText (int) { return String::empty; }
  27100. void AudioProcessorGraph::AudioGraphIOProcessor::setParameter (int, float) { }
  27101. int AudioProcessorGraph::AudioGraphIOProcessor::getNumPrograms() { return 0; }
  27102. int AudioProcessorGraph::AudioGraphIOProcessor::getCurrentProgram() { return 0; }
  27103. void AudioProcessorGraph::AudioGraphIOProcessor::setCurrentProgram (int) { }
  27104. const String AudioProcessorGraph::AudioGraphIOProcessor::getProgramName (int) { return String::empty; }
  27105. void AudioProcessorGraph::AudioGraphIOProcessor::changeProgramName (int, const String&) { }
  27106. void AudioProcessorGraph::AudioGraphIOProcessor::getStateInformation (JUCE_NAMESPACE::MemoryBlock&)
  27107. {
  27108. }
  27109. void AudioProcessorGraph::AudioGraphIOProcessor::setStateInformation (const void*, int)
  27110. {
  27111. }
  27112. void AudioProcessorGraph::AudioGraphIOProcessor::setParentGraph (AudioProcessorGraph* const newGraph) throw()
  27113. {
  27114. graph = newGraph;
  27115. if (graph != 0)
  27116. {
  27117. setPlayConfigDetails (type == audioOutputNode ? graph->getNumOutputChannels() : 0,
  27118. type == audioInputNode ? graph->getNumInputChannels() : 0,
  27119. getSampleRate(),
  27120. getBlockSize());
  27121. updateHostDisplay();
  27122. }
  27123. }
  27124. END_JUCE_NAMESPACE
  27125. /********* End of inlined file: juce_AudioProcessorGraph.cpp *********/
  27126. /********* Start of inlined file: juce_AudioProcessorPlayer.cpp *********/
  27127. BEGIN_JUCE_NAMESPACE
  27128. AudioProcessorPlayer::AudioProcessorPlayer()
  27129. : processor (0),
  27130. sampleRate (0),
  27131. blockSize (0),
  27132. isPrepared (false),
  27133. numInputChans (0),
  27134. numOutputChans (0),
  27135. tempBuffer (1, 1)
  27136. {
  27137. }
  27138. AudioProcessorPlayer::~AudioProcessorPlayer()
  27139. {
  27140. setProcessor (0);
  27141. }
  27142. void AudioProcessorPlayer::setProcessor (AudioProcessor* const processorToPlay)
  27143. {
  27144. if (processor != processorToPlay)
  27145. {
  27146. if (processorToPlay != 0 && sampleRate > 0 && blockSize > 0)
  27147. {
  27148. processorToPlay->setPlayConfigDetails (numInputChans, numOutputChans,
  27149. sampleRate, blockSize);
  27150. processorToPlay->prepareToPlay (sampleRate, blockSize);
  27151. }
  27152. lock.enter();
  27153. AudioProcessor* const oldOne = isPrepared ? processor : 0;
  27154. processor = processorToPlay;
  27155. isPrepared = true;
  27156. lock.exit();
  27157. if (oldOne != 0)
  27158. oldOne->releaseResources();
  27159. }
  27160. }
  27161. void AudioProcessorPlayer::audioDeviceIOCallback (const float** inputChannelData,
  27162. int numInputChannels,
  27163. float** outputChannelData,
  27164. int numOutputChannels,
  27165. int numSamples)
  27166. {
  27167. // these should have been prepared by audioDeviceAboutToStart()...
  27168. jassert (sampleRate > 0 && blockSize > 0);
  27169. incomingMidi.clear();
  27170. messageCollector.removeNextBlockOfMessages (incomingMidi, numSamples);
  27171. int i, totalNumChans = 0;
  27172. if (numInputChannels > numOutputChannels)
  27173. {
  27174. // if there aren't enough output channels for the number of
  27175. // inputs, we need to create some temporary extra ones (can't
  27176. // use the input data in case it gets written to)
  27177. tempBuffer.setSize (numInputChannels - numOutputChannels, numSamples,
  27178. false, false, true);
  27179. for (i = 0; i < numOutputChannels; ++i)
  27180. {
  27181. channels[totalNumChans] = outputChannelData[i];
  27182. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  27183. ++totalNumChans;
  27184. }
  27185. for (i = numOutputChannels; i < numInputChannels; ++i)
  27186. {
  27187. channels[totalNumChans] = tempBuffer.getSampleData (i - numOutputChannels, 0);
  27188. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  27189. ++totalNumChans;
  27190. }
  27191. }
  27192. else
  27193. {
  27194. for (i = 0; i < numInputChannels; ++i)
  27195. {
  27196. channels[totalNumChans] = outputChannelData[i];
  27197. memcpy (channels[totalNumChans], inputChannelData[i], sizeof (float) * numSamples);
  27198. ++totalNumChans;
  27199. }
  27200. for (i = numInputChannels; i < numOutputChannels; ++i)
  27201. {
  27202. channels[totalNumChans] = outputChannelData[i];
  27203. zeromem (channels[totalNumChans], sizeof (float) * numSamples);
  27204. ++totalNumChans;
  27205. }
  27206. }
  27207. AudioSampleBuffer buffer (channels, totalNumChans, numSamples);
  27208. const ScopedLock sl (lock);
  27209. if (processor != 0)
  27210. processor->processBlock (buffer, incomingMidi);
  27211. }
  27212. void AudioProcessorPlayer::audioDeviceAboutToStart (AudioIODevice* device)
  27213. {
  27214. const ScopedLock sl (lock);
  27215. sampleRate = device->getCurrentSampleRate();
  27216. blockSize = device->getCurrentBufferSizeSamples();
  27217. numInputChans = device->getActiveInputChannels().countNumberOfSetBits();
  27218. numOutputChans = device->getActiveOutputChannels().countNumberOfSetBits();
  27219. messageCollector.reset (sampleRate);
  27220. zeromem (channels, sizeof (channels));
  27221. if (processor != 0)
  27222. {
  27223. if (isPrepared)
  27224. processor->releaseResources();
  27225. AudioProcessor* const oldProcessor = processor;
  27226. setProcessor (0);
  27227. setProcessor (oldProcessor);
  27228. }
  27229. }
  27230. void AudioProcessorPlayer::audioDeviceStopped()
  27231. {
  27232. const ScopedLock sl (lock);
  27233. if (processor != 0 && isPrepared)
  27234. processor->releaseResources();
  27235. sampleRate = 0.0;
  27236. blockSize = 0;
  27237. isPrepared = false;
  27238. tempBuffer.setSize (1, 1);
  27239. }
  27240. void AudioProcessorPlayer::handleIncomingMidiMessage (MidiInput*, const MidiMessage& message)
  27241. {
  27242. messageCollector.addMessageToQueue (message);
  27243. }
  27244. END_JUCE_NAMESPACE
  27245. /********* End of inlined file: juce_AudioProcessorPlayer.cpp *********/
  27246. /********* Start of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  27247. BEGIN_JUCE_NAMESPACE
  27248. class ProcessorParameterPropertyComp : public PropertyComponent,
  27249. public AudioProcessorListener,
  27250. public AsyncUpdater
  27251. {
  27252. public:
  27253. ProcessorParameterPropertyComp (const String& name,
  27254. AudioProcessor* const owner_,
  27255. const int index_)
  27256. : PropertyComponent (name),
  27257. owner (owner_),
  27258. index (index_)
  27259. {
  27260. addAndMakeVisible (slider = new ParamSlider (owner_, index_));
  27261. owner_->addListener (this);
  27262. }
  27263. ~ProcessorParameterPropertyComp()
  27264. {
  27265. owner->removeListener (this);
  27266. deleteAllChildren();
  27267. }
  27268. void refresh()
  27269. {
  27270. slider->setValue (owner->getParameter (index), false);
  27271. }
  27272. void audioProcessorChanged (AudioProcessor*) {}
  27273. void audioProcessorParameterChanged (AudioProcessor*, int parameterIndex, float)
  27274. {
  27275. if (parameterIndex == index)
  27276. triggerAsyncUpdate();
  27277. }
  27278. void handleAsyncUpdate()
  27279. {
  27280. refresh();
  27281. }
  27282. juce_UseDebuggingNewOperator
  27283. private:
  27284. AudioProcessor* const owner;
  27285. const int index;
  27286. Slider* slider;
  27287. class ParamSlider : public Slider
  27288. {
  27289. public:
  27290. ParamSlider (AudioProcessor* const owner_, const int index_)
  27291. : Slider (String::empty),
  27292. owner (owner_),
  27293. index (index_)
  27294. {
  27295. setRange (0.0, 1.0, 0.0);
  27296. setSliderStyle (Slider::LinearBar);
  27297. setTextBoxIsEditable (false);
  27298. setScrollWheelEnabled (false);
  27299. }
  27300. ~ParamSlider()
  27301. {
  27302. }
  27303. void valueChanged()
  27304. {
  27305. const float newVal = (float) getValue();
  27306. if (owner->getParameter (index) != newVal)
  27307. owner->setParameter (index, newVal);
  27308. }
  27309. const String getTextFromValue (double /*value*/)
  27310. {
  27311. return owner->getParameterText (index);
  27312. }
  27313. juce_UseDebuggingNewOperator
  27314. private:
  27315. AudioProcessor* const owner;
  27316. const int index;
  27317. };
  27318. };
  27319. GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor* const owner)
  27320. : AudioProcessorEditor (owner)
  27321. {
  27322. setOpaque (true);
  27323. addAndMakeVisible (panel = new PropertyPanel());
  27324. Array <PropertyComponent*> params;
  27325. const int numParams = owner->getNumParameters();
  27326. int totalHeight = 0;
  27327. for (int i = 0; i < numParams; ++i)
  27328. {
  27329. String name (owner->getParameterName (i));
  27330. if (name.trim().isEmpty())
  27331. name = "Unnamed";
  27332. ProcessorParameterPropertyComp* const pc = new ProcessorParameterPropertyComp (name, owner, i);
  27333. params.add (pc);
  27334. totalHeight += pc->getPreferredHeight();
  27335. }
  27336. panel->addProperties (params);
  27337. setSize (400, jlimit (25, 400, totalHeight));
  27338. }
  27339. GenericAudioProcessorEditor::~GenericAudioProcessorEditor()
  27340. {
  27341. deleteAllChildren();
  27342. }
  27343. void GenericAudioProcessorEditor::paint (Graphics& g)
  27344. {
  27345. g.fillAll (Colours::white);
  27346. }
  27347. void GenericAudioProcessorEditor::resized()
  27348. {
  27349. panel->setSize (getWidth(), getHeight());
  27350. }
  27351. END_JUCE_NAMESPACE
  27352. /********* End of inlined file: juce_GenericAudioProcessorEditor.cpp *********/
  27353. /********* Start of inlined file: juce_Sampler.cpp *********/
  27354. BEGIN_JUCE_NAMESPACE
  27355. SamplerSound::SamplerSound (const String& name_,
  27356. AudioFormatReader& source,
  27357. const BitArray& midiNotes_,
  27358. const int midiNoteForNormalPitch,
  27359. const double attackTimeSecs,
  27360. const double releaseTimeSecs,
  27361. const double maxSampleLengthSeconds)
  27362. : name (name_),
  27363. midiNotes (midiNotes_),
  27364. midiRootNote (midiNoteForNormalPitch)
  27365. {
  27366. sourceSampleRate = source.sampleRate;
  27367. if (sourceSampleRate <= 0 || source.lengthInSamples <= 0)
  27368. {
  27369. data = 0;
  27370. length = 0;
  27371. attackSamples = 0;
  27372. releaseSamples = 0;
  27373. }
  27374. else
  27375. {
  27376. length = jmin ((int) source.lengthInSamples,
  27377. (int) (maxSampleLengthSeconds * sourceSampleRate));
  27378. data = new AudioSampleBuffer (jmin (2, source.numChannels), length + 4);
  27379. data->readFromAudioReader (&source, 0, length + 4, 0, true, true);
  27380. attackSamples = roundDoubleToInt (attackTimeSecs * sourceSampleRate);
  27381. releaseSamples = roundDoubleToInt (releaseTimeSecs * sourceSampleRate);
  27382. }
  27383. }
  27384. SamplerSound::~SamplerSound()
  27385. {
  27386. delete data;
  27387. data = 0;
  27388. }
  27389. bool SamplerSound::appliesToNote (const int midiNoteNumber)
  27390. {
  27391. return midiNotes [midiNoteNumber];
  27392. }
  27393. bool SamplerSound::appliesToChannel (const int /*midiChannel*/)
  27394. {
  27395. return true;
  27396. }
  27397. SamplerVoice::SamplerVoice()
  27398. : pitchRatio (0.0),
  27399. sourceSamplePosition (0.0),
  27400. lgain (0.0f),
  27401. rgain (0.0f),
  27402. isInAttack (false),
  27403. isInRelease (false)
  27404. {
  27405. }
  27406. SamplerVoice::~SamplerVoice()
  27407. {
  27408. }
  27409. bool SamplerVoice::canPlaySound (SynthesiserSound* sound)
  27410. {
  27411. return dynamic_cast <const SamplerSound*> (sound) != 0;
  27412. }
  27413. void SamplerVoice::startNote (const int midiNoteNumber,
  27414. const float velocity,
  27415. SynthesiserSound* s,
  27416. const int /*currentPitchWheelPosition*/)
  27417. {
  27418. const SamplerSound* const sound = dynamic_cast <const SamplerSound*> (s);
  27419. jassert (sound != 0); // this object can only play SamplerSounds!
  27420. if (sound != 0)
  27421. {
  27422. const double targetFreq = MidiMessage::getMidiNoteInHertz (midiNoteNumber);
  27423. const double naturalFreq = MidiMessage::getMidiNoteInHertz (sound->midiRootNote);
  27424. pitchRatio = (targetFreq * sound->sourceSampleRate) / (naturalFreq * getSampleRate());
  27425. sourceSamplePosition = 0.0;
  27426. lgain = velocity;
  27427. rgain = velocity;
  27428. isInAttack = (sound->attackSamples > 0);
  27429. isInRelease = false;
  27430. if (isInAttack)
  27431. {
  27432. attackReleaseLevel = 0.0f;
  27433. attackDelta = (float) (pitchRatio / sound->attackSamples);
  27434. }
  27435. else
  27436. {
  27437. attackReleaseLevel = 1.0f;
  27438. attackDelta = 0.0f;
  27439. }
  27440. if (sound->releaseSamples > 0)
  27441. {
  27442. releaseDelta = (float) (-pitchRatio / sound->releaseSamples);
  27443. }
  27444. else
  27445. {
  27446. releaseDelta = 0.0f;
  27447. }
  27448. }
  27449. }
  27450. void SamplerVoice::stopNote (const bool allowTailOff)
  27451. {
  27452. if (allowTailOff)
  27453. {
  27454. isInAttack = false;
  27455. isInRelease = true;
  27456. }
  27457. else
  27458. {
  27459. clearCurrentNote();
  27460. }
  27461. }
  27462. void SamplerVoice::pitchWheelMoved (const int /*newValue*/)
  27463. {
  27464. }
  27465. void SamplerVoice::controllerMoved (const int /*controllerNumber*/,
  27466. const int /*newValue*/)
  27467. {
  27468. }
  27469. void SamplerVoice::renderNextBlock (AudioSampleBuffer& outputBuffer, int startSample, int numSamples)
  27470. {
  27471. const SamplerSound* const playingSound = (SamplerSound*) (SynthesiserSound*) getCurrentlyPlayingSound();
  27472. if (playingSound != 0)
  27473. {
  27474. const float* const inL = playingSound->data->getSampleData (0, 0);
  27475. const float* const inR = playingSound->data->getNumChannels() > 1
  27476. ? playingSound->data->getSampleData (1, 0) : 0;
  27477. float* outL = outputBuffer.getSampleData (0, startSample);
  27478. float* outR = outputBuffer.getNumChannels() > 1 ? outputBuffer.getSampleData (1, startSample) : 0;
  27479. while (--numSamples >= 0)
  27480. {
  27481. const int pos = (int) sourceSamplePosition;
  27482. const float alpha = (float) (sourceSamplePosition - pos);
  27483. const float invAlpha = 1.0f - alpha;
  27484. // just using a very simple linear interpolation here..
  27485. float l = (inL [pos] * invAlpha + inL [pos + 1] * alpha);
  27486. float r = (inR != 0) ? (inR [pos] * invAlpha + inR [pos + 1] * alpha)
  27487. : l;
  27488. l *= lgain;
  27489. r *= rgain;
  27490. if (isInAttack)
  27491. {
  27492. l *= attackReleaseLevel;
  27493. r *= attackReleaseLevel;
  27494. attackReleaseLevel += attackDelta;
  27495. if (attackReleaseLevel >= 1.0f)
  27496. {
  27497. attackReleaseLevel = 1.0f;
  27498. isInAttack = false;
  27499. }
  27500. }
  27501. else if (isInRelease)
  27502. {
  27503. l *= attackReleaseLevel;
  27504. r *= attackReleaseLevel;
  27505. attackReleaseLevel += releaseDelta;
  27506. if (attackReleaseLevel <= 0.0f)
  27507. {
  27508. stopNote (false);
  27509. break;
  27510. }
  27511. }
  27512. if (outR != 0)
  27513. {
  27514. *outL++ += l;
  27515. *outR++ += r;
  27516. }
  27517. else
  27518. {
  27519. *outL++ += (l + r) * 0.5f;
  27520. }
  27521. sourceSamplePosition += pitchRatio;
  27522. if (sourceSamplePosition > playingSound->length)
  27523. {
  27524. stopNote (false);
  27525. break;
  27526. }
  27527. }
  27528. }
  27529. }
  27530. END_JUCE_NAMESPACE
  27531. /********* End of inlined file: juce_Sampler.cpp *********/
  27532. /********* Start of inlined file: juce_Synthesiser.cpp *********/
  27533. BEGIN_JUCE_NAMESPACE
  27534. SynthesiserSound::SynthesiserSound()
  27535. {
  27536. }
  27537. SynthesiserSound::~SynthesiserSound()
  27538. {
  27539. }
  27540. SynthesiserVoice::SynthesiserVoice()
  27541. : currentSampleRate (44100.0),
  27542. currentlyPlayingNote (-1),
  27543. noteOnTime (0),
  27544. currentlyPlayingSound (0)
  27545. {
  27546. }
  27547. SynthesiserVoice::~SynthesiserVoice()
  27548. {
  27549. }
  27550. bool SynthesiserVoice::isPlayingChannel (const int midiChannel) const
  27551. {
  27552. return currentlyPlayingSound != 0
  27553. && currentlyPlayingSound->appliesToChannel (midiChannel);
  27554. }
  27555. void SynthesiserVoice::setCurrentPlaybackSampleRate (const double newRate)
  27556. {
  27557. currentSampleRate = newRate;
  27558. }
  27559. void SynthesiserVoice::clearCurrentNote()
  27560. {
  27561. currentlyPlayingNote = -1;
  27562. currentlyPlayingSound = 0;
  27563. }
  27564. Synthesiser::Synthesiser()
  27565. : voices (2),
  27566. sounds (2),
  27567. sampleRate (0),
  27568. lastNoteOnCounter (0),
  27569. shouldStealNotes (true)
  27570. {
  27571. for (int i = 0; i < numElementsInArray (lastPitchWheelValues); ++i)
  27572. lastPitchWheelValues[i] = 0x2000;
  27573. }
  27574. Synthesiser::~Synthesiser()
  27575. {
  27576. }
  27577. SynthesiserVoice* Synthesiser::getVoice (const int index) const throw()
  27578. {
  27579. const ScopedLock sl (lock);
  27580. return voices [index];
  27581. }
  27582. void Synthesiser::clearVoices()
  27583. {
  27584. const ScopedLock sl (lock);
  27585. voices.clear();
  27586. }
  27587. void Synthesiser::addVoice (SynthesiserVoice* const newVoice)
  27588. {
  27589. const ScopedLock sl (lock);
  27590. voices.add (newVoice);
  27591. }
  27592. void Synthesiser::removeVoice (const int index)
  27593. {
  27594. const ScopedLock sl (lock);
  27595. voices.remove (index);
  27596. }
  27597. void Synthesiser::clearSounds()
  27598. {
  27599. const ScopedLock sl (lock);
  27600. sounds.clear();
  27601. }
  27602. void Synthesiser::addSound (const SynthesiserSound::Ptr& newSound)
  27603. {
  27604. const ScopedLock sl (lock);
  27605. sounds.add (newSound);
  27606. }
  27607. void Synthesiser::removeSound (const int index)
  27608. {
  27609. const ScopedLock sl (lock);
  27610. sounds.remove (index);
  27611. }
  27612. void Synthesiser::setNoteStealingEnabled (const bool shouldStealNotes_)
  27613. {
  27614. shouldStealNotes = shouldStealNotes_;
  27615. }
  27616. void Synthesiser::setCurrentPlaybackSampleRate (const double newRate)
  27617. {
  27618. if (sampleRate != newRate)
  27619. {
  27620. const ScopedLock sl (lock);
  27621. allNotesOff (0, false);
  27622. sampleRate = newRate;
  27623. for (int i = voices.size(); --i >= 0;)
  27624. voices.getUnchecked (i)->setCurrentPlaybackSampleRate (newRate);
  27625. }
  27626. }
  27627. void Synthesiser::renderNextBlock (AudioSampleBuffer& outputBuffer,
  27628. const MidiBuffer& midiData,
  27629. int startSample,
  27630. int numSamples)
  27631. {
  27632. // must set the sample rate before using this!
  27633. jassert (sampleRate != 0);
  27634. const ScopedLock sl (lock);
  27635. MidiBuffer::Iterator midiIterator (midiData);
  27636. midiIterator.setNextSamplePosition (startSample);
  27637. MidiMessage m (0xf4, 0.0);
  27638. while (numSamples > 0)
  27639. {
  27640. int midiEventPos;
  27641. const bool useEvent = midiIterator.getNextEvent (m, midiEventPos)
  27642. && midiEventPos < startSample + numSamples;
  27643. const int numThisTime = useEvent ? midiEventPos - startSample
  27644. : numSamples;
  27645. if (numThisTime > 0)
  27646. {
  27647. for (int i = voices.size(); --i >= 0;)
  27648. voices.getUnchecked (i)->renderNextBlock (outputBuffer, startSample, numThisTime);
  27649. }
  27650. if (useEvent)
  27651. {
  27652. if (m.isNoteOn())
  27653. {
  27654. const int channel = m.getChannel();
  27655. noteOn (channel,
  27656. m.getNoteNumber(),
  27657. m.getFloatVelocity());
  27658. }
  27659. else if (m.isNoteOff())
  27660. {
  27661. noteOff (m.getChannel(),
  27662. m.getNoteNumber(),
  27663. true);
  27664. }
  27665. else if (m.isAllNotesOff() || m.isAllSoundOff())
  27666. {
  27667. allNotesOff (m.getChannel(), true);
  27668. }
  27669. else if (m.isPitchWheel())
  27670. {
  27671. const int channel = m.getChannel();
  27672. const int wheelPos = m.getPitchWheelValue();
  27673. lastPitchWheelValues [channel - 1] = wheelPos;
  27674. handlePitchWheel (channel, wheelPos);
  27675. }
  27676. else if (m.isController())
  27677. {
  27678. handleController (m.getChannel(),
  27679. m.getControllerNumber(),
  27680. m.getControllerValue());
  27681. }
  27682. }
  27683. startSample += numThisTime;
  27684. numSamples -= numThisTime;
  27685. }
  27686. }
  27687. void Synthesiser::noteOn (const int midiChannel,
  27688. const int midiNoteNumber,
  27689. const float velocity)
  27690. {
  27691. const ScopedLock sl (lock);
  27692. for (int i = sounds.size(); --i >= 0;)
  27693. {
  27694. SynthesiserSound* const sound = sounds.getUnchecked(i);
  27695. if (sound->appliesToNote (midiNoteNumber)
  27696. && sound->appliesToChannel (midiChannel))
  27697. {
  27698. startVoice (findFreeVoice (sound, shouldStealNotes),
  27699. sound, midiChannel, midiNoteNumber, velocity);
  27700. }
  27701. }
  27702. }
  27703. void Synthesiser::startVoice (SynthesiserVoice* const voice,
  27704. SynthesiserSound* const sound,
  27705. const int midiChannel,
  27706. const int midiNoteNumber,
  27707. const float velocity)
  27708. {
  27709. if (voice != 0 && sound != 0)
  27710. {
  27711. if (voice->currentlyPlayingSound != 0)
  27712. voice->stopNote (false);
  27713. voice->startNote (midiNoteNumber,
  27714. velocity,
  27715. sound,
  27716. lastPitchWheelValues [midiChannel - 1]);
  27717. voice->currentlyPlayingNote = midiNoteNumber;
  27718. voice->noteOnTime = ++lastNoteOnCounter;
  27719. voice->currentlyPlayingSound = sound;
  27720. }
  27721. }
  27722. void Synthesiser::noteOff (const int midiChannel,
  27723. const int midiNoteNumber,
  27724. const bool allowTailOff)
  27725. {
  27726. const ScopedLock sl (lock);
  27727. for (int i = voices.size(); --i >= 0;)
  27728. {
  27729. SynthesiserVoice* const voice = voices.getUnchecked (i);
  27730. if (voice->getCurrentlyPlayingNote() == midiNoteNumber)
  27731. {
  27732. SynthesiserSound* const sound = voice->getCurrentlyPlayingSound();
  27733. if (sound != 0
  27734. && sound->appliesToNote (midiNoteNumber)
  27735. && sound->appliesToChannel (midiChannel))
  27736. {
  27737. voice->stopNote (allowTailOff);
  27738. // the subclass MUST call clearCurrentNote() if it's not tailing off! RTFM for stopNote()!
  27739. jassert (allowTailOff || (voice->getCurrentlyPlayingNote() < 0 && voice->getCurrentlyPlayingSound() == 0));
  27740. }
  27741. }
  27742. }
  27743. }
  27744. void Synthesiser::allNotesOff (const int midiChannel,
  27745. const bool allowTailOff)
  27746. {
  27747. const ScopedLock sl (lock);
  27748. for (int i = voices.size(); --i >= 0;)
  27749. {
  27750. SynthesiserVoice* const voice = voices.getUnchecked (i);
  27751. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  27752. voice->stopNote (allowTailOff);
  27753. }
  27754. }
  27755. void Synthesiser::handlePitchWheel (const int midiChannel,
  27756. const int wheelValue)
  27757. {
  27758. const ScopedLock sl (lock);
  27759. for (int i = voices.size(); --i >= 0;)
  27760. {
  27761. SynthesiserVoice* const voice = voices.getUnchecked (i);
  27762. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  27763. {
  27764. voice->pitchWheelMoved (wheelValue);
  27765. }
  27766. }
  27767. }
  27768. void Synthesiser::handleController (const int midiChannel,
  27769. const int controllerNumber,
  27770. const int controllerValue)
  27771. {
  27772. const ScopedLock sl (lock);
  27773. for (int i = voices.size(); --i >= 0;)
  27774. {
  27775. SynthesiserVoice* const voice = voices.getUnchecked (i);
  27776. if (midiChannel <= 0 || voice->isPlayingChannel (midiChannel))
  27777. voice->controllerMoved (controllerNumber, controllerValue);
  27778. }
  27779. }
  27780. SynthesiserVoice* Synthesiser::findFreeVoice (SynthesiserSound* soundToPlay,
  27781. const bool stealIfNoneAvailable) const
  27782. {
  27783. const ScopedLock sl (lock);
  27784. for (int i = voices.size(); --i >= 0;)
  27785. if (voices.getUnchecked (i)->getCurrentlyPlayingNote() < 0
  27786. && voices.getUnchecked (i)->canPlaySound (soundToPlay))
  27787. return voices.getUnchecked (i);
  27788. if (stealIfNoneAvailable)
  27789. {
  27790. // currently this just steals the one that's been playing the longest, but could be made a bit smarter..
  27791. SynthesiserVoice* oldest = 0;
  27792. for (int i = voices.size(); --i >= 0;)
  27793. {
  27794. SynthesiserVoice* const voice = voices.getUnchecked (i);
  27795. if (voice->canPlaySound (soundToPlay)
  27796. && (oldest == 0 || oldest->noteOnTime > voice->noteOnTime))
  27797. oldest = voice;
  27798. }
  27799. jassert (oldest != 0);
  27800. return oldest;
  27801. }
  27802. return 0;
  27803. }
  27804. END_JUCE_NAMESPACE
  27805. /********* End of inlined file: juce_Synthesiser.cpp *********/
  27806. /********* Start of inlined file: juce_FileBasedDocument.cpp *********/
  27807. BEGIN_JUCE_NAMESPACE
  27808. FileBasedDocument::FileBasedDocument (const String& fileExtension_,
  27809. const String& fileWildcard_,
  27810. const String& openFileDialogTitle_,
  27811. const String& saveFileDialogTitle_)
  27812. : changedSinceSave (false),
  27813. fileExtension (fileExtension_),
  27814. fileWildcard (fileWildcard_),
  27815. openFileDialogTitle (openFileDialogTitle_),
  27816. saveFileDialogTitle (saveFileDialogTitle_)
  27817. {
  27818. }
  27819. FileBasedDocument::~FileBasedDocument()
  27820. {
  27821. }
  27822. void FileBasedDocument::setChangedFlag (const bool hasChanged)
  27823. {
  27824. changedSinceSave = hasChanged;
  27825. }
  27826. void FileBasedDocument::changed()
  27827. {
  27828. changedSinceSave = true;
  27829. sendChangeMessage (this);
  27830. }
  27831. void FileBasedDocument::setFile (const File& newFile)
  27832. {
  27833. if (documentFile != newFile)
  27834. {
  27835. documentFile = newFile;
  27836. changedSinceSave = true;
  27837. }
  27838. }
  27839. bool FileBasedDocument::loadFrom (const File& newFile,
  27840. const bool showMessageOnFailure)
  27841. {
  27842. MouseCursor::showWaitCursor();
  27843. const File oldFile (documentFile);
  27844. documentFile = newFile;
  27845. String error;
  27846. if (newFile.existsAsFile())
  27847. {
  27848. error = loadDocument (newFile);
  27849. if (error.isEmpty())
  27850. {
  27851. setChangedFlag (false);
  27852. MouseCursor::hideWaitCursor();
  27853. setLastDocumentOpened (newFile);
  27854. return true;
  27855. }
  27856. }
  27857. else
  27858. {
  27859. error = "The file doesn't exist";
  27860. }
  27861. documentFile = oldFile;
  27862. MouseCursor::hideWaitCursor();
  27863. if (showMessageOnFailure)
  27864. {
  27865. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  27866. TRANS("Failed to open file..."),
  27867. TRANS("There was an error while trying to load the file:\n\n")
  27868. + newFile.getFullPathName()
  27869. + T("\n\n")
  27870. + error);
  27871. }
  27872. return false;
  27873. }
  27874. bool FileBasedDocument::loadFromUserSpecifiedFile (const bool showMessageOnFailure)
  27875. {
  27876. FileChooser fc (openFileDialogTitle,
  27877. getLastDocumentOpened(),
  27878. fileWildcard);
  27879. if (fc.browseForFileToOpen())
  27880. return loadFrom (fc.getResult(), showMessageOnFailure);
  27881. return false;
  27882. }
  27883. FileBasedDocument::SaveResult FileBasedDocument::save (const bool askUserForFileIfNotSpecified,
  27884. const bool showMessageOnFailure)
  27885. {
  27886. return saveAs (documentFile,
  27887. false,
  27888. askUserForFileIfNotSpecified,
  27889. showMessageOnFailure);
  27890. }
  27891. FileBasedDocument::SaveResult FileBasedDocument::saveAs (const File& newFile,
  27892. const bool warnAboutOverwritingExistingFiles,
  27893. const bool askUserForFileIfNotSpecified,
  27894. const bool showMessageOnFailure)
  27895. {
  27896. if (newFile == File::nonexistent)
  27897. {
  27898. if (askUserForFileIfNotSpecified)
  27899. {
  27900. return saveAsInteractive (true);
  27901. }
  27902. else
  27903. {
  27904. // can't save to an unspecified file
  27905. jassertfalse
  27906. return failedToWriteToFile;
  27907. }
  27908. }
  27909. if (warnAboutOverwritingExistingFiles && newFile.exists())
  27910. {
  27911. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  27912. TRANS("File already exists"),
  27913. TRANS("There's already a file called:\n\n")
  27914. + newFile.getFullPathName()
  27915. + TRANS("\n\nAre you sure you want to overwrite it?"),
  27916. TRANS("overwrite"),
  27917. TRANS("cancel")))
  27918. {
  27919. return userCancelledSave;
  27920. }
  27921. }
  27922. MouseCursor::showWaitCursor();
  27923. const File oldFile (documentFile);
  27924. documentFile = newFile;
  27925. String error (saveDocument (newFile));
  27926. if (error.isEmpty())
  27927. {
  27928. setChangedFlag (false);
  27929. MouseCursor::hideWaitCursor();
  27930. return savedOk;
  27931. }
  27932. documentFile = oldFile;
  27933. MouseCursor::hideWaitCursor();
  27934. if (showMessageOnFailure)
  27935. {
  27936. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  27937. TRANS("Error writing to file..."),
  27938. TRANS("An error occurred while trying to save \"")
  27939. + getDocumentTitle()
  27940. + TRANS("\" to the file:\n\n")
  27941. + newFile.getFullPathName()
  27942. + T("\n\n")
  27943. + error);
  27944. }
  27945. return failedToWriteToFile;
  27946. }
  27947. FileBasedDocument::SaveResult FileBasedDocument::saveIfNeededAndUserAgrees()
  27948. {
  27949. if (! hasChangedSinceSaved())
  27950. return savedOk;
  27951. const int r = AlertWindow::showYesNoCancelBox (AlertWindow::QuestionIcon,
  27952. TRANS("Closing document..."),
  27953. TRANS("Do you want to save the changes to \"")
  27954. + getDocumentTitle() + T("\"?"),
  27955. TRANS("save"),
  27956. TRANS("discard changes"),
  27957. TRANS("cancel"));
  27958. if (r == 1)
  27959. {
  27960. // save changes
  27961. return save (true, true);
  27962. }
  27963. else if (r == 2)
  27964. {
  27965. // discard changes
  27966. return savedOk;
  27967. }
  27968. return userCancelledSave;
  27969. }
  27970. FileBasedDocument::SaveResult FileBasedDocument::saveAsInteractive (const bool warnAboutOverwritingExistingFiles)
  27971. {
  27972. File f;
  27973. if (documentFile.existsAsFile())
  27974. f = documentFile;
  27975. else
  27976. f = getLastDocumentOpened();
  27977. String legalFilename (File::createLegalFileName (getDocumentTitle()));
  27978. if (legalFilename.isEmpty())
  27979. legalFilename = "unnamed";
  27980. if (f.existsAsFile() || f.getParentDirectory().isDirectory())
  27981. f = f.getSiblingFile (legalFilename);
  27982. else
  27983. f = File::getSpecialLocation (File::userDocumentsDirectory).getChildFile (legalFilename);
  27984. f = f.withFileExtension (fileExtension)
  27985. .getNonexistentSibling (true);
  27986. FileChooser fc (saveFileDialogTitle, f, fileWildcard);
  27987. if (fc.browseForFileToSave (warnAboutOverwritingExistingFiles))
  27988. {
  27989. setLastDocumentOpened (fc.getResult());
  27990. File chosen (fc.getResult());
  27991. if (chosen.getFileExtension().isEmpty())
  27992. chosen = chosen.withFileExtension (fileExtension);
  27993. return saveAs (chosen, false, false, true);
  27994. }
  27995. return userCancelledSave;
  27996. }
  27997. END_JUCE_NAMESPACE
  27998. /********* End of inlined file: juce_FileBasedDocument.cpp *********/
  27999. /********* Start of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  28000. BEGIN_JUCE_NAMESPACE
  28001. RecentlyOpenedFilesList::RecentlyOpenedFilesList()
  28002. : maxNumberOfItems (10)
  28003. {
  28004. }
  28005. RecentlyOpenedFilesList::~RecentlyOpenedFilesList()
  28006. {
  28007. }
  28008. void RecentlyOpenedFilesList::setMaxNumberOfItems (const int newMaxNumber)
  28009. {
  28010. maxNumberOfItems = jmax (1, newMaxNumber);
  28011. while (getNumFiles() > maxNumberOfItems)
  28012. files.remove (getNumFiles() - 1);
  28013. }
  28014. int RecentlyOpenedFilesList::getNumFiles() const
  28015. {
  28016. return files.size();
  28017. }
  28018. const File RecentlyOpenedFilesList::getFile (const int index) const
  28019. {
  28020. return File (files [index]);
  28021. }
  28022. void RecentlyOpenedFilesList::clear()
  28023. {
  28024. files.clear();
  28025. }
  28026. void RecentlyOpenedFilesList::addFile (const File& file)
  28027. {
  28028. const String path (file.getFullPathName());
  28029. files.removeString (path, true);
  28030. files.insert (0, path);
  28031. setMaxNumberOfItems (maxNumberOfItems);
  28032. }
  28033. void RecentlyOpenedFilesList::removeNonExistentFiles()
  28034. {
  28035. for (int i = getNumFiles(); --i >= 0;)
  28036. if (! getFile(i).exists())
  28037. files.remove (i);
  28038. }
  28039. int RecentlyOpenedFilesList::createPopupMenuItems (PopupMenu& menuToAddTo,
  28040. const int baseItemId,
  28041. const bool showFullPaths,
  28042. const bool dontAddNonExistentFiles,
  28043. const File** filesToAvoid)
  28044. {
  28045. int num = 0;
  28046. for (int i = 0; i < getNumFiles(); ++i)
  28047. {
  28048. const File f (getFile(i));
  28049. if ((! dontAddNonExistentFiles) || f.exists())
  28050. {
  28051. bool needsAvoiding = false;
  28052. if (filesToAvoid != 0)
  28053. {
  28054. const File** files = filesToAvoid;
  28055. while (*files != 0)
  28056. {
  28057. if (f == **files)
  28058. {
  28059. needsAvoiding = true;
  28060. break;
  28061. }
  28062. ++files;
  28063. }
  28064. }
  28065. if (! needsAvoiding)
  28066. {
  28067. menuToAddTo.addItem (baseItemId + i,
  28068. showFullPaths ? f.getFullPathName()
  28069. : f.getFileName());
  28070. ++num;
  28071. }
  28072. }
  28073. }
  28074. return num;
  28075. }
  28076. const String RecentlyOpenedFilesList::toString() const
  28077. {
  28078. return files.joinIntoString (T("\n"));
  28079. }
  28080. void RecentlyOpenedFilesList::restoreFromString (const String& stringifiedVersion)
  28081. {
  28082. clear();
  28083. files.addLines (stringifiedVersion);
  28084. setMaxNumberOfItems (maxNumberOfItems);
  28085. }
  28086. END_JUCE_NAMESPACE
  28087. /********* End of inlined file: juce_RecentlyOpenedFilesList.cpp *********/
  28088. /********* Start of inlined file: juce_UndoManager.cpp *********/
  28089. BEGIN_JUCE_NAMESPACE
  28090. UndoManager::UndoManager (const int maxNumberOfUnitsToKeep,
  28091. const int minimumTransactions)
  28092. : totalUnitsStored (0),
  28093. nextIndex (0),
  28094. newTransaction (true),
  28095. reentrancyCheck (false)
  28096. {
  28097. setMaxNumberOfStoredUnits (maxNumberOfUnitsToKeep,
  28098. minimumTransactions);
  28099. }
  28100. UndoManager::~UndoManager()
  28101. {
  28102. clearUndoHistory();
  28103. }
  28104. void UndoManager::clearUndoHistory()
  28105. {
  28106. transactions.clear();
  28107. transactionNames.clear();
  28108. totalUnitsStored = 0;
  28109. nextIndex = 0;
  28110. sendChangeMessage (this);
  28111. }
  28112. int UndoManager::getNumberOfUnitsTakenUpByStoredCommands() const
  28113. {
  28114. return totalUnitsStored;
  28115. }
  28116. void UndoManager::setMaxNumberOfStoredUnits (const int maxNumberOfUnitsToKeep,
  28117. const int minimumTransactions)
  28118. {
  28119. maxNumUnitsToKeep = jmax (1, maxNumberOfUnitsToKeep);
  28120. minimumTransactionsToKeep = jmax (1, minimumTransactions);
  28121. }
  28122. bool UndoManager::perform (UndoableAction* const command, const String& actionName)
  28123. {
  28124. if (command != 0)
  28125. {
  28126. if (actionName.isNotEmpty())
  28127. currentTransactionName = actionName;
  28128. if (reentrancyCheck)
  28129. {
  28130. jassertfalse // don't call perform() recursively from the UndoableAction::perform() or
  28131. // undo() methods, or else these actions won't actually get done.
  28132. return false;
  28133. }
  28134. else
  28135. {
  28136. bool success = false;
  28137. JUCE_TRY
  28138. {
  28139. success = command->perform();
  28140. }
  28141. JUCE_CATCH_EXCEPTION
  28142. jassert (success);
  28143. if (success)
  28144. {
  28145. if (nextIndex > 0 && ! newTransaction)
  28146. {
  28147. OwnedArray<UndoableAction>* commandSet = transactions [nextIndex - 1];
  28148. jassert (commandSet != 0);
  28149. if (commandSet == 0)
  28150. return false;
  28151. commandSet->add (command);
  28152. }
  28153. else
  28154. {
  28155. OwnedArray<UndoableAction>* commandSet = new OwnedArray<UndoableAction>();
  28156. commandSet->add (command);
  28157. transactions.insert (nextIndex, commandSet);
  28158. transactionNames.insert (nextIndex, currentTransactionName);
  28159. ++nextIndex;
  28160. }
  28161. totalUnitsStored += command->getSizeInUnits();
  28162. newTransaction = false;
  28163. }
  28164. while (nextIndex < transactions.size())
  28165. {
  28166. const OwnedArray <UndoableAction>* const lastSet = transactions.getLast();
  28167. for (int i = lastSet->size(); --i >= 0;)
  28168. totalUnitsStored -= lastSet->getUnchecked (i)->getSizeInUnits();
  28169. transactions.removeLast();
  28170. transactionNames.remove (transactionNames.size() - 1);
  28171. }
  28172. while (nextIndex > 0
  28173. && totalUnitsStored > maxNumUnitsToKeep
  28174. && transactions.size() > minimumTransactionsToKeep)
  28175. {
  28176. const OwnedArray <UndoableAction>* const firstSet = transactions.getFirst();
  28177. for (int i = firstSet->size(); --i >= 0;)
  28178. totalUnitsStored -= firstSet->getUnchecked (i)->getSizeInUnits();
  28179. jassert (totalUnitsStored >= 0); // something fishy going on if this fails!
  28180. transactions.remove (0);
  28181. transactionNames.remove (0);
  28182. --nextIndex;
  28183. }
  28184. sendChangeMessage (this);
  28185. return success;
  28186. }
  28187. }
  28188. return false;
  28189. }
  28190. void UndoManager::beginNewTransaction (const String& actionName)
  28191. {
  28192. newTransaction = true;
  28193. currentTransactionName = actionName;
  28194. }
  28195. void UndoManager::setCurrentTransactionName (const String& newName)
  28196. {
  28197. currentTransactionName = newName;
  28198. }
  28199. bool UndoManager::canUndo() const
  28200. {
  28201. return nextIndex > 0;
  28202. }
  28203. bool UndoManager::canRedo() const
  28204. {
  28205. return nextIndex < transactions.size();
  28206. }
  28207. const String UndoManager::getUndoDescription() const
  28208. {
  28209. return transactionNames [nextIndex - 1];
  28210. }
  28211. const String UndoManager::getRedoDescription() const
  28212. {
  28213. return transactionNames [nextIndex];
  28214. }
  28215. bool UndoManager::undo()
  28216. {
  28217. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex - 1];
  28218. if (commandSet == 0)
  28219. return false;
  28220. reentrancyCheck = true;
  28221. bool failed = false;
  28222. for (int i = commandSet->size(); --i >= 0;)
  28223. {
  28224. if (! commandSet->getUnchecked(i)->undo())
  28225. {
  28226. jassertfalse
  28227. failed = true;
  28228. break;
  28229. }
  28230. }
  28231. reentrancyCheck = false;
  28232. if (failed)
  28233. {
  28234. clearUndoHistory();
  28235. }
  28236. else
  28237. {
  28238. --nextIndex;
  28239. }
  28240. beginNewTransaction();
  28241. sendChangeMessage (this);
  28242. return true;
  28243. }
  28244. bool UndoManager::redo()
  28245. {
  28246. const OwnedArray<UndoableAction>* const commandSet = transactions [nextIndex];
  28247. if (commandSet == 0)
  28248. return false;
  28249. reentrancyCheck = true;
  28250. bool failed = false;
  28251. for (int i = 0; i < commandSet->size(); ++i)
  28252. {
  28253. if (! commandSet->getUnchecked(i)->perform())
  28254. {
  28255. jassertfalse
  28256. failed = true;
  28257. break;
  28258. }
  28259. }
  28260. reentrancyCheck = false;
  28261. if (failed)
  28262. {
  28263. clearUndoHistory();
  28264. }
  28265. else
  28266. {
  28267. ++nextIndex;
  28268. }
  28269. beginNewTransaction();
  28270. sendChangeMessage (this);
  28271. return true;
  28272. }
  28273. bool UndoManager::undoCurrentTransactionOnly()
  28274. {
  28275. return newTransaction ? false
  28276. : undo();
  28277. }
  28278. void UndoManager::getActionsInCurrentTransaction (Array <const UndoableAction*>& actionsFound) const
  28279. {
  28280. const OwnedArray <UndoableAction>* const commandSet = transactions [nextIndex - 1];
  28281. if (commandSet != 0 && ! newTransaction)
  28282. {
  28283. for (int i = 0; i < commandSet->size(); ++i)
  28284. actionsFound.add (commandSet->getUnchecked(i));
  28285. }
  28286. }
  28287. END_JUCE_NAMESPACE
  28288. /********* End of inlined file: juce_UndoManager.cpp *********/
  28289. /********* Start of inlined file: juce_ActionBroadcaster.cpp *********/
  28290. BEGIN_JUCE_NAMESPACE
  28291. ActionBroadcaster::ActionBroadcaster() throw()
  28292. {
  28293. // are you trying to create this object before or after juce has been intialised??
  28294. jassert (MessageManager::instance != 0);
  28295. }
  28296. ActionBroadcaster::~ActionBroadcaster()
  28297. {
  28298. // all event-based objects must be deleted BEFORE juce is shut down!
  28299. jassert (MessageManager::instance != 0);
  28300. }
  28301. void ActionBroadcaster::addActionListener (ActionListener* const listener)
  28302. {
  28303. actionListenerList.addActionListener (listener);
  28304. }
  28305. void ActionBroadcaster::removeActionListener (ActionListener* const listener)
  28306. {
  28307. jassert (actionListenerList.isValidMessageListener());
  28308. if (actionListenerList.isValidMessageListener())
  28309. actionListenerList.removeActionListener (listener);
  28310. }
  28311. void ActionBroadcaster::removeAllActionListeners()
  28312. {
  28313. actionListenerList.removeAllActionListeners();
  28314. }
  28315. void ActionBroadcaster::sendActionMessage (const String& message) const
  28316. {
  28317. actionListenerList.sendActionMessage (message);
  28318. }
  28319. END_JUCE_NAMESPACE
  28320. /********* End of inlined file: juce_ActionBroadcaster.cpp *********/
  28321. /********* Start of inlined file: juce_ActionListenerList.cpp *********/
  28322. BEGIN_JUCE_NAMESPACE
  28323. // special message of our own with a string in it
  28324. class ActionMessage : public Message
  28325. {
  28326. public:
  28327. const String message;
  28328. ActionMessage (const String& messageText,
  28329. void* const listener_) throw()
  28330. : message (messageText)
  28331. {
  28332. pointerParameter = listener_;
  28333. }
  28334. ~ActionMessage() throw()
  28335. {
  28336. }
  28337. private:
  28338. ActionMessage (const ActionMessage&);
  28339. const ActionMessage& operator= (const ActionMessage&);
  28340. };
  28341. ActionListenerList::ActionListenerList() throw()
  28342. {
  28343. }
  28344. ActionListenerList::~ActionListenerList() throw()
  28345. {
  28346. }
  28347. void ActionListenerList::addActionListener (ActionListener* const listener) throw()
  28348. {
  28349. const ScopedLock sl (actionListenerLock_);
  28350. jassert (listener != 0);
  28351. jassert (! actionListeners_.contains (listener)); // trying to add a listener to the list twice!
  28352. if (listener != 0)
  28353. actionListeners_.add (listener);
  28354. }
  28355. void ActionListenerList::removeActionListener (ActionListener* const listener) throw()
  28356. {
  28357. const ScopedLock sl (actionListenerLock_);
  28358. jassert (actionListeners_.contains (listener)); // trying to remove a listener that isn't on the list!
  28359. actionListeners_.removeValue (listener);
  28360. }
  28361. void ActionListenerList::removeAllActionListeners() throw()
  28362. {
  28363. const ScopedLock sl (actionListenerLock_);
  28364. actionListeners_.clear();
  28365. }
  28366. void ActionListenerList::sendActionMessage (const String& message) const
  28367. {
  28368. const ScopedLock sl (actionListenerLock_);
  28369. for (int i = actionListeners_.size(); --i >= 0;)
  28370. {
  28371. postMessage (new ActionMessage (message,
  28372. (ActionListener*) actionListeners_.getUnchecked(i)));
  28373. }
  28374. }
  28375. void ActionListenerList::handleMessage (const Message& message)
  28376. {
  28377. const ActionMessage& am = (const ActionMessage&) message;
  28378. if (actionListeners_.contains (am.pointerParameter))
  28379. ((ActionListener*) am.pointerParameter)->actionListenerCallback (am.message);
  28380. }
  28381. END_JUCE_NAMESPACE
  28382. /********* End of inlined file: juce_ActionListenerList.cpp *********/
  28383. /********* Start of inlined file: juce_AsyncUpdater.cpp *********/
  28384. BEGIN_JUCE_NAMESPACE
  28385. AsyncUpdater::AsyncUpdater() throw()
  28386. : asyncMessagePending (false)
  28387. {
  28388. internalAsyncHandler.owner = this;
  28389. }
  28390. AsyncUpdater::~AsyncUpdater()
  28391. {
  28392. }
  28393. void AsyncUpdater::triggerAsyncUpdate() throw()
  28394. {
  28395. if (! asyncMessagePending)
  28396. {
  28397. asyncMessagePending = true;
  28398. internalAsyncHandler.postMessage (new Message());
  28399. }
  28400. }
  28401. void AsyncUpdater::cancelPendingUpdate() throw()
  28402. {
  28403. asyncMessagePending = false;
  28404. }
  28405. void AsyncUpdater::handleUpdateNowIfNeeded()
  28406. {
  28407. if (asyncMessagePending)
  28408. {
  28409. asyncMessagePending = false;
  28410. handleAsyncUpdate();
  28411. }
  28412. }
  28413. void AsyncUpdater::AsyncUpdaterInternal::handleMessage (const Message&)
  28414. {
  28415. owner->handleUpdateNowIfNeeded();
  28416. }
  28417. END_JUCE_NAMESPACE
  28418. /********* End of inlined file: juce_AsyncUpdater.cpp *********/
  28419. /********* Start of inlined file: juce_ChangeBroadcaster.cpp *********/
  28420. BEGIN_JUCE_NAMESPACE
  28421. ChangeBroadcaster::ChangeBroadcaster() throw()
  28422. {
  28423. // are you trying to create this object before or after juce has been intialised??
  28424. jassert (MessageManager::instance != 0);
  28425. }
  28426. ChangeBroadcaster::~ChangeBroadcaster()
  28427. {
  28428. // all event-based objects must be deleted BEFORE juce is shut down!
  28429. jassert (MessageManager::instance != 0);
  28430. }
  28431. void ChangeBroadcaster::addChangeListener (ChangeListener* const listener) throw()
  28432. {
  28433. changeListenerList.addChangeListener (listener);
  28434. }
  28435. void ChangeBroadcaster::removeChangeListener (ChangeListener* const listener) throw()
  28436. {
  28437. jassert (changeListenerList.isValidMessageListener());
  28438. if (changeListenerList.isValidMessageListener())
  28439. changeListenerList.removeChangeListener (listener);
  28440. }
  28441. void ChangeBroadcaster::removeAllChangeListeners() throw()
  28442. {
  28443. changeListenerList.removeAllChangeListeners();
  28444. }
  28445. void ChangeBroadcaster::sendChangeMessage (void* objectThatHasChanged) throw()
  28446. {
  28447. changeListenerList.sendChangeMessage (objectThatHasChanged);
  28448. }
  28449. void ChangeBroadcaster::sendSynchronousChangeMessage (void* objectThatHasChanged)
  28450. {
  28451. changeListenerList.sendSynchronousChangeMessage (objectThatHasChanged);
  28452. }
  28453. void ChangeBroadcaster::dispatchPendingMessages()
  28454. {
  28455. changeListenerList.dispatchPendingMessages();
  28456. }
  28457. END_JUCE_NAMESPACE
  28458. /********* End of inlined file: juce_ChangeBroadcaster.cpp *********/
  28459. /********* Start of inlined file: juce_ChangeListenerList.cpp *********/
  28460. BEGIN_JUCE_NAMESPACE
  28461. ChangeListenerList::ChangeListenerList() throw()
  28462. : lastChangedObject (0),
  28463. messagePending (false)
  28464. {
  28465. }
  28466. ChangeListenerList::~ChangeListenerList() throw()
  28467. {
  28468. }
  28469. void ChangeListenerList::addChangeListener (ChangeListener* const listener) throw()
  28470. {
  28471. const ScopedLock sl (lock);
  28472. jassert (listener != 0);
  28473. if (listener != 0)
  28474. listeners.add (listener);
  28475. }
  28476. void ChangeListenerList::removeChangeListener (ChangeListener* const listener) throw()
  28477. {
  28478. const ScopedLock sl (lock);
  28479. listeners.removeValue (listener);
  28480. }
  28481. void ChangeListenerList::removeAllChangeListeners() throw()
  28482. {
  28483. const ScopedLock sl (lock);
  28484. listeners.clear();
  28485. }
  28486. void ChangeListenerList::sendChangeMessage (void* const objectThatHasChanged) throw()
  28487. {
  28488. const ScopedLock sl (lock);
  28489. if ((! messagePending) && (listeners.size() > 0))
  28490. {
  28491. lastChangedObject = objectThatHasChanged;
  28492. postMessage (new Message (0, 0, 0, objectThatHasChanged));
  28493. messagePending = true;
  28494. }
  28495. }
  28496. void ChangeListenerList::handleMessage (const Message& message)
  28497. {
  28498. sendSynchronousChangeMessage (message.pointerParameter);
  28499. }
  28500. void ChangeListenerList::sendSynchronousChangeMessage (void* const objectThatHasChanged)
  28501. {
  28502. const ScopedLock sl (lock);
  28503. messagePending = false;
  28504. for (int i = listeners.size(); --i >= 0;)
  28505. {
  28506. ChangeListener* const l = (ChangeListener*) listeners.getUnchecked (i);
  28507. {
  28508. const ScopedUnlock tempUnlocker (lock);
  28509. l->changeListenerCallback (objectThatHasChanged);
  28510. }
  28511. i = jmin (i, listeners.size());
  28512. }
  28513. }
  28514. void ChangeListenerList::dispatchPendingMessages()
  28515. {
  28516. if (messagePending)
  28517. sendSynchronousChangeMessage (lastChangedObject);
  28518. }
  28519. END_JUCE_NAMESPACE
  28520. /********* End of inlined file: juce_ChangeListenerList.cpp *********/
  28521. /********* Start of inlined file: juce_InterprocessConnection.cpp *********/
  28522. BEGIN_JUCE_NAMESPACE
  28523. InterprocessConnection::InterprocessConnection (const bool callbacksOnMessageThread,
  28524. const uint32 magicMessageHeaderNumber)
  28525. : Thread ("Juce IPC connection"),
  28526. socket (0),
  28527. pipe (0),
  28528. callbackConnectionState (false),
  28529. useMessageThread (callbacksOnMessageThread),
  28530. magicMessageHeader (magicMessageHeaderNumber),
  28531. pipeReceiveMessageTimeout (-1)
  28532. {
  28533. }
  28534. InterprocessConnection::~InterprocessConnection()
  28535. {
  28536. callbackConnectionState = false;
  28537. disconnect();
  28538. }
  28539. bool InterprocessConnection::connectToSocket (const String& hostName,
  28540. const int portNumber,
  28541. const int timeOutMillisecs)
  28542. {
  28543. disconnect();
  28544. const ScopedLock sl (pipeAndSocketLock);
  28545. socket = new StreamingSocket();
  28546. if (socket->connect (hostName, portNumber, timeOutMillisecs))
  28547. {
  28548. connectionMadeInt();
  28549. startThread();
  28550. return true;
  28551. }
  28552. else
  28553. {
  28554. deleteAndZero (socket);
  28555. return false;
  28556. }
  28557. }
  28558. bool InterprocessConnection::connectToPipe (const String& pipeName,
  28559. const int pipeReceiveMessageTimeoutMs)
  28560. {
  28561. disconnect();
  28562. NamedPipe* const newPipe = new NamedPipe();
  28563. if (newPipe->openExisting (pipeName))
  28564. {
  28565. const ScopedLock sl (pipeAndSocketLock);
  28566. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  28567. initialiseWithPipe (newPipe);
  28568. return true;
  28569. }
  28570. else
  28571. {
  28572. delete newPipe;
  28573. return false;
  28574. }
  28575. }
  28576. bool InterprocessConnection::createPipe (const String& pipeName,
  28577. const int pipeReceiveMessageTimeoutMs)
  28578. {
  28579. disconnect();
  28580. NamedPipe* const newPipe = new NamedPipe();
  28581. if (newPipe->createNewPipe (pipeName))
  28582. {
  28583. const ScopedLock sl (pipeAndSocketLock);
  28584. pipeReceiveMessageTimeout = pipeReceiveMessageTimeoutMs;
  28585. initialiseWithPipe (newPipe);
  28586. return true;
  28587. }
  28588. else
  28589. {
  28590. delete newPipe;
  28591. return false;
  28592. }
  28593. }
  28594. void InterprocessConnection::disconnect()
  28595. {
  28596. if (socket != 0)
  28597. socket->close();
  28598. if (pipe != 0)
  28599. {
  28600. pipe->cancelPendingReads();
  28601. pipe->close();
  28602. }
  28603. stopThread (4000);
  28604. {
  28605. const ScopedLock sl (pipeAndSocketLock);
  28606. deleteAndZero (socket);
  28607. deleteAndZero (pipe);
  28608. }
  28609. connectionLostInt();
  28610. }
  28611. bool InterprocessConnection::isConnected() const
  28612. {
  28613. const ScopedLock sl (pipeAndSocketLock);
  28614. return ((socket != 0 && socket->isConnected())
  28615. || (pipe != 0 && pipe->isOpen()))
  28616. && isThreadRunning();
  28617. }
  28618. const String InterprocessConnection::getConnectedHostName() const
  28619. {
  28620. if (pipe != 0)
  28621. {
  28622. return "localhost";
  28623. }
  28624. else if (socket != 0)
  28625. {
  28626. if (! socket->isLocal())
  28627. return socket->getHostName();
  28628. return "localhost";
  28629. }
  28630. return String::empty;
  28631. }
  28632. bool InterprocessConnection::sendMessage (const MemoryBlock& message)
  28633. {
  28634. uint32 messageHeader[2];
  28635. messageHeader [0] = swapIfBigEndian (magicMessageHeader);
  28636. messageHeader [1] = swapIfBigEndian ((uint32) message.getSize());
  28637. MemoryBlock messageData (sizeof (messageHeader) + message.getSize());
  28638. messageData.copyFrom (messageHeader, 0, sizeof (messageHeader));
  28639. messageData.copyFrom (message.getData(), sizeof (messageHeader), message.getSize());
  28640. int bytesWritten = 0;
  28641. const ScopedLock sl (pipeAndSocketLock);
  28642. if (socket != 0)
  28643. {
  28644. bytesWritten = socket->write (messageData.getData(), messageData.getSize());
  28645. }
  28646. else if (pipe != 0)
  28647. {
  28648. bytesWritten = pipe->write (messageData.getData(), messageData.getSize());
  28649. }
  28650. if (bytesWritten < 0)
  28651. {
  28652. // error..
  28653. return false;
  28654. }
  28655. return (bytesWritten == messageData.getSize());
  28656. }
  28657. void InterprocessConnection::initialiseWithSocket (StreamingSocket* const socket_)
  28658. {
  28659. jassert (socket == 0);
  28660. socket = socket_;
  28661. connectionMadeInt();
  28662. startThread();
  28663. }
  28664. void InterprocessConnection::initialiseWithPipe (NamedPipe* const pipe_)
  28665. {
  28666. jassert (pipe == 0);
  28667. pipe = pipe_;
  28668. connectionMadeInt();
  28669. startThread();
  28670. }
  28671. const int messageMagicNumber = 0xb734128b;
  28672. void InterprocessConnection::handleMessage (const Message& message)
  28673. {
  28674. if (message.intParameter1 == messageMagicNumber)
  28675. {
  28676. switch (message.intParameter2)
  28677. {
  28678. case 0:
  28679. {
  28680. MemoryBlock* const data = (MemoryBlock*) message.pointerParameter;
  28681. messageReceived (*data);
  28682. delete data;
  28683. break;
  28684. }
  28685. case 1:
  28686. connectionMade();
  28687. break;
  28688. case 2:
  28689. connectionLost();
  28690. break;
  28691. }
  28692. }
  28693. }
  28694. void InterprocessConnection::connectionMadeInt()
  28695. {
  28696. if (! callbackConnectionState)
  28697. {
  28698. callbackConnectionState = true;
  28699. if (useMessageThread)
  28700. postMessage (new Message (messageMagicNumber, 1, 0, 0));
  28701. else
  28702. connectionMade();
  28703. }
  28704. }
  28705. void InterprocessConnection::connectionLostInt()
  28706. {
  28707. if (callbackConnectionState)
  28708. {
  28709. callbackConnectionState = false;
  28710. if (useMessageThread)
  28711. postMessage (new Message (messageMagicNumber, 2, 0, 0));
  28712. else
  28713. connectionLost();
  28714. }
  28715. }
  28716. void InterprocessConnection::deliverDataInt (const MemoryBlock& data)
  28717. {
  28718. jassert (callbackConnectionState);
  28719. if (useMessageThread)
  28720. postMessage (new Message (messageMagicNumber, 0, 0, new MemoryBlock (data)));
  28721. else
  28722. messageReceived (data);
  28723. }
  28724. bool InterprocessConnection::readNextMessageInt()
  28725. {
  28726. const int maximumMessageSize = 1024 * 1024 * 10; // sanity check
  28727. uint32 messageHeader[2];
  28728. const int bytes = (socket != 0) ? socket->read (messageHeader, sizeof (messageHeader))
  28729. : pipe->read (messageHeader, sizeof (messageHeader), pipeReceiveMessageTimeout);
  28730. if (bytes == sizeof (messageHeader)
  28731. && swapIfBigEndian (messageHeader[0]) == magicMessageHeader)
  28732. {
  28733. const int bytesInMessage = (int) swapIfBigEndian (messageHeader[1]);
  28734. if (bytesInMessage > 0 && bytesInMessage < maximumMessageSize)
  28735. {
  28736. MemoryBlock messageData (bytesInMessage, true);
  28737. int bytesRead = 0;
  28738. while (bytesRead < bytesInMessage)
  28739. {
  28740. if (threadShouldExit())
  28741. return false;
  28742. const int numThisTime = jmin (bytesInMessage, 65536);
  28743. const int bytesIn = (socket != 0) ? socket->read (((char*) messageData.getData()) + bytesRead, numThisTime)
  28744. : pipe->read (((char*) messageData.getData()) + bytesRead, numThisTime,
  28745. pipeReceiveMessageTimeout);
  28746. if (bytesIn <= 0)
  28747. break;
  28748. bytesRead += bytesIn;
  28749. }
  28750. if (bytesRead >= 0)
  28751. deliverDataInt (messageData);
  28752. }
  28753. }
  28754. else if (bytes < 0)
  28755. {
  28756. {
  28757. const ScopedLock sl (pipeAndSocketLock);
  28758. deleteAndZero (socket);
  28759. }
  28760. connectionLostInt();
  28761. return false;
  28762. }
  28763. return true;
  28764. }
  28765. void InterprocessConnection::run()
  28766. {
  28767. while (! threadShouldExit())
  28768. {
  28769. if (socket != 0)
  28770. {
  28771. const int ready = socket->waitUntilReady (true, 0);
  28772. if (ready < 0)
  28773. {
  28774. {
  28775. const ScopedLock sl (pipeAndSocketLock);
  28776. deleteAndZero (socket);
  28777. }
  28778. connectionLostInt();
  28779. break;
  28780. }
  28781. else if (ready > 0)
  28782. {
  28783. if (! readNextMessageInt())
  28784. break;
  28785. }
  28786. else
  28787. {
  28788. Thread::sleep (2);
  28789. }
  28790. }
  28791. else if (pipe != 0)
  28792. {
  28793. if (! pipe->isOpen())
  28794. {
  28795. {
  28796. const ScopedLock sl (pipeAndSocketLock);
  28797. deleteAndZero (pipe);
  28798. }
  28799. connectionLostInt();
  28800. break;
  28801. }
  28802. else
  28803. {
  28804. if (! readNextMessageInt())
  28805. break;
  28806. }
  28807. }
  28808. else
  28809. {
  28810. break;
  28811. }
  28812. }
  28813. }
  28814. END_JUCE_NAMESPACE
  28815. /********* End of inlined file: juce_InterprocessConnection.cpp *********/
  28816. /********* Start of inlined file: juce_InterprocessConnectionServer.cpp *********/
  28817. BEGIN_JUCE_NAMESPACE
  28818. InterprocessConnectionServer::InterprocessConnectionServer()
  28819. : Thread ("Juce IPC server"),
  28820. socket (0)
  28821. {
  28822. }
  28823. InterprocessConnectionServer::~InterprocessConnectionServer()
  28824. {
  28825. stop();
  28826. }
  28827. bool InterprocessConnectionServer::beginWaitingForSocket (const int portNumber)
  28828. {
  28829. stop();
  28830. socket = new StreamingSocket();
  28831. if (socket->createListener (portNumber))
  28832. {
  28833. startThread();
  28834. return true;
  28835. }
  28836. deleteAndZero (socket);
  28837. return false;
  28838. }
  28839. void InterprocessConnectionServer::stop()
  28840. {
  28841. signalThreadShouldExit();
  28842. if (socket != 0)
  28843. socket->close();
  28844. stopThread (4000);
  28845. deleteAndZero (socket);
  28846. }
  28847. void InterprocessConnectionServer::run()
  28848. {
  28849. while ((! threadShouldExit()) && socket != 0)
  28850. {
  28851. StreamingSocket* const clientSocket = socket->waitForNextConnection();
  28852. if (clientSocket != 0)
  28853. {
  28854. InterprocessConnection* newConnection = createConnectionObject();
  28855. if (newConnection != 0)
  28856. {
  28857. newConnection->initialiseWithSocket (clientSocket);
  28858. }
  28859. else
  28860. {
  28861. delete clientSocket;
  28862. }
  28863. }
  28864. }
  28865. }
  28866. END_JUCE_NAMESPACE
  28867. /********* End of inlined file: juce_InterprocessConnectionServer.cpp *********/
  28868. /********* Start of inlined file: juce_Message.cpp *********/
  28869. BEGIN_JUCE_NAMESPACE
  28870. Message::Message() throw()
  28871. {
  28872. }
  28873. Message::~Message() throw()
  28874. {
  28875. }
  28876. Message::Message (const int intParameter1_,
  28877. const int intParameter2_,
  28878. const int intParameter3_,
  28879. void* const pointerParameter_) throw()
  28880. : intParameter1 (intParameter1_),
  28881. intParameter2 (intParameter2_),
  28882. intParameter3 (intParameter3_),
  28883. pointerParameter (pointerParameter_)
  28884. {
  28885. }
  28886. END_JUCE_NAMESPACE
  28887. /********* End of inlined file: juce_Message.cpp *********/
  28888. /********* Start of inlined file: juce_MessageListener.cpp *********/
  28889. BEGIN_JUCE_NAMESPACE
  28890. MessageListener::MessageListener() throw()
  28891. {
  28892. // are you trying to create a messagelistener before or after juce has been intialised??
  28893. jassert (MessageManager::instance != 0);
  28894. if (MessageManager::instance != 0)
  28895. MessageManager::instance->messageListeners.add (this);
  28896. }
  28897. MessageListener::~MessageListener()
  28898. {
  28899. if (MessageManager::instance != 0)
  28900. MessageManager::instance->messageListeners.removeValue (this);
  28901. }
  28902. void MessageListener::postMessage (Message* const message) const throw()
  28903. {
  28904. message->messageRecipient = const_cast <MessageListener*> (this);
  28905. if (MessageManager::instance == 0)
  28906. MessageManager::getInstance();
  28907. MessageManager::instance->postMessageToQueue (message);
  28908. }
  28909. bool MessageListener::isValidMessageListener() const throw()
  28910. {
  28911. return (MessageManager::instance != 0)
  28912. && MessageManager::instance->messageListeners.contains (this);
  28913. }
  28914. END_JUCE_NAMESPACE
  28915. /********* End of inlined file: juce_MessageListener.cpp *********/
  28916. /********* Start of inlined file: juce_MessageManager.cpp *********/
  28917. BEGIN_JUCE_NAMESPACE
  28918. // platform-specific functions..
  28919. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages);
  28920. bool juce_postMessageToSystemQueue (void* message);
  28921. MessageManager* MessageManager::instance = 0;
  28922. static const int quitMessageId = 0xfffff321;
  28923. MessageManager::MessageManager() throw()
  28924. : broadcastListeners (0),
  28925. quitMessagePosted (false),
  28926. quitMessageReceived (false)
  28927. {
  28928. currentLockingThreadId = messageThreadId = Thread::getCurrentThreadId();
  28929. }
  28930. MessageManager::~MessageManager() throw()
  28931. {
  28932. jassert (instance == this);
  28933. instance = 0;
  28934. deleteAndZero (broadcastListeners);
  28935. doPlatformSpecificShutdown();
  28936. }
  28937. MessageManager* MessageManager::getInstance() throw()
  28938. {
  28939. if (instance == 0)
  28940. {
  28941. instance = new MessageManager();
  28942. doPlatformSpecificInitialisation();
  28943. }
  28944. return instance;
  28945. }
  28946. void MessageManager::postMessageToQueue (Message* const message)
  28947. {
  28948. if (quitMessagePosted || ! juce_postMessageToSystemQueue (message))
  28949. delete message;
  28950. }
  28951. // not for public use..
  28952. void MessageManager::deliverMessage (void* message)
  28953. {
  28954. const MessageManagerLock lock;
  28955. Message* const m = (Message*) message;
  28956. MessageListener* const recipient = m->messageRecipient;
  28957. if (messageListeners.contains (recipient))
  28958. {
  28959. JUCE_TRY
  28960. {
  28961. recipient->handleMessage (*m);
  28962. }
  28963. JUCE_CATCH_EXCEPTION
  28964. }
  28965. else if (recipient == 0 && m->intParameter1 == quitMessageId)
  28966. {
  28967. quitMessageReceived = true;
  28968. }
  28969. delete m;
  28970. }
  28971. #if ! JUCE_MAC
  28972. void MessageManager::runDispatchLoop()
  28973. {
  28974. jassert (isThisTheMessageThread()); // must only be called by the message thread
  28975. runDispatchLoopUntil (-1);
  28976. }
  28977. void MessageManager::stopDispatchLoop()
  28978. {
  28979. Message* const m = new Message (quitMessageId, 0, 0, 0);
  28980. m->messageRecipient = 0;
  28981. postMessageToQueue (m);
  28982. quitMessagePosted = true;
  28983. }
  28984. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  28985. {
  28986. jassert (isThisTheMessageThread()); // must only be called by the message thread
  28987. const int64 endTime = Time::currentTimeMillis() + millisecondsToRunFor;
  28988. while ((millisecondsToRunFor < 0 || endTime > Time::currentTimeMillis())
  28989. && ! quitMessageReceived)
  28990. {
  28991. JUCE_TRY
  28992. {
  28993. juce_dispatchNextMessageOnSystemQueue (millisecondsToRunFor >= 0);
  28994. }
  28995. JUCE_CATCH_EXCEPTION
  28996. }
  28997. return ! quitMessageReceived;
  28998. }
  28999. #endif
  29000. void MessageManager::deliverBroadcastMessage (const String& value)
  29001. {
  29002. if (broadcastListeners != 0)
  29003. broadcastListeners->sendActionMessage (value);
  29004. }
  29005. void MessageManager::registerBroadcastListener (ActionListener* const listener) throw()
  29006. {
  29007. if (broadcastListeners == 0)
  29008. broadcastListeners = new ActionListenerList();
  29009. broadcastListeners->addActionListener (listener);
  29010. }
  29011. void MessageManager::deregisterBroadcastListener (ActionListener* const listener) throw()
  29012. {
  29013. if (broadcastListeners != 0)
  29014. broadcastListeners->removeActionListener (listener);
  29015. }
  29016. bool MessageManager::isThisTheMessageThread() const throw()
  29017. {
  29018. return Thread::getCurrentThreadId() == messageThreadId;
  29019. }
  29020. void MessageManager::setCurrentMessageThread (const int64 threadId) throw()
  29021. {
  29022. messageThreadId = threadId;
  29023. }
  29024. bool MessageManager::currentThreadHasLockedMessageManager() const throw()
  29025. {
  29026. return Thread::getCurrentThreadId() == currentLockingThreadId;
  29027. }
  29028. MessageManagerLock::MessageManagerLock() throw()
  29029. : locked (false)
  29030. {
  29031. if (MessageManager::instance != 0)
  29032. {
  29033. MessageManager::instance->messageDispatchLock.enter();
  29034. lastLockingThreadId = MessageManager::instance->currentLockingThreadId;
  29035. MessageManager::instance->currentLockingThreadId = Thread::getCurrentThreadId();
  29036. locked = true;
  29037. }
  29038. }
  29039. MessageManagerLock::MessageManagerLock (Thread* const thread) throw()
  29040. : locked (false)
  29041. {
  29042. jassert (thread != 0); // This will only work if you give it a valid thread!
  29043. if (MessageManager::instance != 0)
  29044. {
  29045. for (;;)
  29046. {
  29047. if (MessageManager::instance->messageDispatchLock.tryEnter())
  29048. {
  29049. locked = true;
  29050. lastLockingThreadId = MessageManager::instance->currentLockingThreadId;
  29051. MessageManager::instance->currentLockingThreadId = Thread::getCurrentThreadId();
  29052. break;
  29053. }
  29054. if (thread != 0 && thread->threadShouldExit())
  29055. break;
  29056. Thread::sleep (1);
  29057. }
  29058. }
  29059. }
  29060. MessageManagerLock::~MessageManagerLock() throw()
  29061. {
  29062. if (locked && MessageManager::instance != 0)
  29063. {
  29064. MessageManager::instance->currentLockingThreadId = lastLockingThreadId;
  29065. MessageManager::instance->messageDispatchLock.exit();
  29066. }
  29067. }
  29068. END_JUCE_NAMESPACE
  29069. /********* End of inlined file: juce_MessageManager.cpp *********/
  29070. /********* Start of inlined file: juce_MultiTimer.cpp *********/
  29071. BEGIN_JUCE_NAMESPACE
  29072. class InternalMultiTimerCallback : public Timer
  29073. {
  29074. public:
  29075. InternalMultiTimerCallback (const int timerId_, MultiTimer& owner_)
  29076. : timerId (timerId_),
  29077. owner (owner_)
  29078. {
  29079. }
  29080. ~InternalMultiTimerCallback()
  29081. {
  29082. }
  29083. void timerCallback()
  29084. {
  29085. owner.timerCallback (timerId);
  29086. }
  29087. const int timerId;
  29088. private:
  29089. MultiTimer& owner;
  29090. };
  29091. MultiTimer::MultiTimer() throw()
  29092. {
  29093. }
  29094. MultiTimer::MultiTimer (const MultiTimer&) throw()
  29095. {
  29096. }
  29097. MultiTimer::~MultiTimer()
  29098. {
  29099. const ScopedLock sl (timerListLock);
  29100. for (int i = timers.size(); --i >= 0;)
  29101. delete (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29102. timers.clear();
  29103. }
  29104. void MultiTimer::startTimer (const int timerId, const int intervalInMilliseconds) throw()
  29105. {
  29106. const ScopedLock sl (timerListLock);
  29107. for (int i = timers.size(); --i >= 0;)
  29108. {
  29109. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29110. if (t->timerId == timerId)
  29111. {
  29112. t->startTimer (intervalInMilliseconds);
  29113. return;
  29114. }
  29115. }
  29116. InternalMultiTimerCallback* const newTimer = new InternalMultiTimerCallback (timerId, *this);
  29117. timers.add (newTimer);
  29118. newTimer->startTimer (intervalInMilliseconds);
  29119. }
  29120. void MultiTimer::stopTimer (const int timerId) throw()
  29121. {
  29122. const ScopedLock sl (timerListLock);
  29123. for (int i = timers.size(); --i >= 0;)
  29124. {
  29125. InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29126. if (t->timerId == timerId)
  29127. t->stopTimer();
  29128. }
  29129. }
  29130. bool MultiTimer::isTimerRunning (const int timerId) const throw()
  29131. {
  29132. const ScopedLock sl (timerListLock);
  29133. for (int i = timers.size(); --i >= 0;)
  29134. {
  29135. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29136. if (t->timerId == timerId)
  29137. return t->isTimerRunning();
  29138. }
  29139. return false;
  29140. }
  29141. int MultiTimer::getTimerInterval (const int timerId) const throw()
  29142. {
  29143. const ScopedLock sl (timerListLock);
  29144. for (int i = timers.size(); --i >= 0;)
  29145. {
  29146. const InternalMultiTimerCallback* const t = (InternalMultiTimerCallback*) timers.getUnchecked(i);
  29147. if (t->timerId == timerId)
  29148. return t->getTimerInterval();
  29149. }
  29150. return 0;
  29151. }
  29152. END_JUCE_NAMESPACE
  29153. /********* End of inlined file: juce_MultiTimer.cpp *********/
  29154. /********* Start of inlined file: juce_Timer.cpp *********/
  29155. BEGIN_JUCE_NAMESPACE
  29156. class InternalTimerThread : private Thread,
  29157. private MessageListener,
  29158. private DeletedAtShutdown,
  29159. private AsyncUpdater
  29160. {
  29161. private:
  29162. friend class Timer;
  29163. static InternalTimerThread* instance;
  29164. static CriticalSection lock;
  29165. Timer* volatile firstTimer;
  29166. bool volatile callbackNeeded;
  29167. InternalTimerThread (const InternalTimerThread&);
  29168. const InternalTimerThread& operator= (const InternalTimerThread&);
  29169. void addTimer (Timer* const t) throw()
  29170. {
  29171. #ifdef JUCE_DEBUG
  29172. Timer* tt = firstTimer;
  29173. while (tt != 0)
  29174. {
  29175. // trying to add a timer that's already here - shouldn't get to this point,
  29176. // so if you get this assertion, let me know!
  29177. jassert (tt != t);
  29178. tt = tt->next;
  29179. }
  29180. jassert (t->previous == 0 && t->next == 0);
  29181. #endif
  29182. Timer* i = firstTimer;
  29183. if (i == 0 || i->countdownMs > t->countdownMs)
  29184. {
  29185. t->next = firstTimer;
  29186. firstTimer = t;
  29187. }
  29188. else
  29189. {
  29190. while (i->next != 0 && i->next->countdownMs <= t->countdownMs)
  29191. i = i->next;
  29192. jassert (i != 0);
  29193. t->next = i->next;
  29194. t->previous = i;
  29195. i->next = t;
  29196. }
  29197. if (t->next != 0)
  29198. t->next->previous = t;
  29199. jassert ((t->next == 0 || t->next->countdownMs >= t->countdownMs)
  29200. && (t->previous == 0 || t->previous->countdownMs <= t->countdownMs));
  29201. notify();
  29202. }
  29203. void removeTimer (Timer* const t) throw()
  29204. {
  29205. #ifdef JUCE_DEBUG
  29206. Timer* tt = firstTimer;
  29207. bool found = false;
  29208. while (tt != 0)
  29209. {
  29210. if (tt == t)
  29211. {
  29212. found = true;
  29213. break;
  29214. }
  29215. tt = tt->next;
  29216. }
  29217. // trying to remove a timer that's not here - shouldn't get to this point,
  29218. // so if you get this assertion, let me know!
  29219. jassert (found);
  29220. #endif
  29221. if (t->previous != 0)
  29222. {
  29223. jassert (firstTimer != t);
  29224. t->previous->next = t->next;
  29225. }
  29226. else
  29227. {
  29228. jassert (firstTimer == t);
  29229. firstTimer = t->next;
  29230. }
  29231. if (t->next != 0)
  29232. t->next->previous = t->previous;
  29233. t->next = 0;
  29234. t->previous = 0;
  29235. }
  29236. void decrementAllCounters (const int numMillisecs) const
  29237. {
  29238. Timer* t = firstTimer;
  29239. while (t != 0)
  29240. {
  29241. t->countdownMs -= numMillisecs;
  29242. t = t->next;
  29243. }
  29244. }
  29245. void handleAsyncUpdate()
  29246. {
  29247. startThread (7);
  29248. }
  29249. public:
  29250. InternalTimerThread()
  29251. : Thread ("Juce Timer"),
  29252. firstTimer (0),
  29253. callbackNeeded (false)
  29254. {
  29255. triggerAsyncUpdate();
  29256. }
  29257. ~InternalTimerThread() throw()
  29258. {
  29259. stopThread (4000);
  29260. jassert (instance == this || instance == 0);
  29261. if (instance == this)
  29262. instance = 0;
  29263. }
  29264. void run()
  29265. {
  29266. uint32 lastTime = Time::getMillisecondCounter();
  29267. while (! threadShouldExit())
  29268. {
  29269. uint32 now = Time::getMillisecondCounter();
  29270. if (now <= lastTime)
  29271. {
  29272. wait (2);
  29273. continue;
  29274. }
  29275. const int elapsed = now - lastTime;
  29276. lastTime = now;
  29277. lock.enter();
  29278. decrementAllCounters (elapsed);
  29279. const int timeUntilFirstTimer = (firstTimer != 0) ? firstTimer->countdownMs
  29280. : 1000;
  29281. lock.exit();
  29282. if (timeUntilFirstTimer <= 0)
  29283. {
  29284. callbackNeeded = true;
  29285. postMessage (new Message());
  29286. // sometimes, our message could get discarded by the OS (particularly when running as an RTAS when the app has a modal loop),
  29287. // so this is how long to wait before assuming the message has been lost and trying again.
  29288. const uint32 messageDeliveryTimeout = now + 2000;
  29289. while (callbackNeeded)
  29290. {
  29291. wait (4);
  29292. if (threadShouldExit())
  29293. return;
  29294. now = Time::getMillisecondCounter();
  29295. if (now > messageDeliveryTimeout)
  29296. break;
  29297. }
  29298. }
  29299. else
  29300. {
  29301. // don't wait for too long because running this loop also helps keep the
  29302. // Time::getApproximateMillisecondTimer value stay up-to-date
  29303. wait (jlimit (1, 50, timeUntilFirstTimer));
  29304. }
  29305. }
  29306. }
  29307. void handleMessage (const Message&)
  29308. {
  29309. const ScopedLock sl (lock);
  29310. while (firstTimer != 0 && firstTimer->countdownMs <= 0)
  29311. {
  29312. Timer* const t = firstTimer;
  29313. t->countdownMs = t->periodMs;
  29314. removeTimer (t);
  29315. addTimer (t);
  29316. const ScopedUnlock ul (lock);
  29317. callbackNeeded = false;
  29318. JUCE_TRY
  29319. {
  29320. t->timerCallback();
  29321. }
  29322. JUCE_CATCH_EXCEPTION
  29323. }
  29324. callbackNeeded = false;
  29325. }
  29326. static void callAnyTimersSynchronously()
  29327. {
  29328. if (InternalTimerThread::instance != 0)
  29329. {
  29330. const Message m;
  29331. InternalTimerThread::instance->handleMessage (m);
  29332. }
  29333. }
  29334. static inline void add (Timer* const tim) throw()
  29335. {
  29336. if (instance == 0)
  29337. instance = new InternalTimerThread();
  29338. instance->addTimer (tim);
  29339. }
  29340. static inline void remove (Timer* const tim) throw()
  29341. {
  29342. if (instance != 0)
  29343. instance->removeTimer (tim);
  29344. }
  29345. static inline void resetCounter (Timer* const tim,
  29346. const int newCounter) throw()
  29347. {
  29348. if (instance != 0)
  29349. {
  29350. tim->countdownMs = newCounter;
  29351. tim->periodMs = newCounter;
  29352. if ((tim->next != 0 && tim->next->countdownMs < tim->countdownMs)
  29353. || (tim->previous != 0 && tim->previous->countdownMs > tim->countdownMs))
  29354. {
  29355. instance->removeTimer (tim);
  29356. instance->addTimer (tim);
  29357. }
  29358. }
  29359. }
  29360. };
  29361. InternalTimerThread* InternalTimerThread::instance = 0;
  29362. CriticalSection InternalTimerThread::lock;
  29363. void juce_callAnyTimersSynchronously()
  29364. {
  29365. InternalTimerThread::callAnyTimersSynchronously();
  29366. }
  29367. #ifdef JUCE_DEBUG
  29368. static SortedSet <Timer*> activeTimers;
  29369. #endif
  29370. Timer::Timer() throw()
  29371. : countdownMs (0),
  29372. periodMs (0),
  29373. previous (0),
  29374. next (0)
  29375. {
  29376. #ifdef JUCE_DEBUG
  29377. activeTimers.add (this);
  29378. #endif
  29379. }
  29380. Timer::Timer (const Timer&) throw()
  29381. : countdownMs (0),
  29382. periodMs (0),
  29383. previous (0),
  29384. next (0)
  29385. {
  29386. #ifdef JUCE_DEBUG
  29387. activeTimers.add (this);
  29388. #endif
  29389. }
  29390. Timer::~Timer()
  29391. {
  29392. stopTimer();
  29393. #ifdef JUCE_DEBUG
  29394. activeTimers.removeValue (this);
  29395. #endif
  29396. }
  29397. void Timer::startTimer (const int interval) throw()
  29398. {
  29399. const ScopedLock sl (InternalTimerThread::lock);
  29400. #ifdef JUCE_DEBUG
  29401. // this isn't a valid object! Your timer might be a dangling pointer or something..
  29402. jassert (activeTimers.contains (this));
  29403. #endif
  29404. if (periodMs == 0)
  29405. {
  29406. countdownMs = interval;
  29407. periodMs = jmax (1, interval);
  29408. InternalTimerThread::add (this);
  29409. }
  29410. else
  29411. {
  29412. InternalTimerThread::resetCounter (this, interval);
  29413. }
  29414. }
  29415. void Timer::stopTimer() throw()
  29416. {
  29417. const ScopedLock sl (InternalTimerThread::lock);
  29418. #ifdef JUCE_DEBUG
  29419. // this isn't a valid object! Your timer might be a dangling pointer or something..
  29420. jassert (activeTimers.contains (this));
  29421. #endif
  29422. if (periodMs > 0)
  29423. {
  29424. InternalTimerThread::remove (this);
  29425. periodMs = 0;
  29426. }
  29427. }
  29428. END_JUCE_NAMESPACE
  29429. /********* End of inlined file: juce_Timer.cpp *********/
  29430. /********* Start of inlined file: juce_Component.cpp *********/
  29431. BEGIN_JUCE_NAMESPACE
  29432. Component* Component::componentUnderMouse = 0;
  29433. Component* Component::currentlyFocusedComponent = 0;
  29434. static Array <Component*> modalComponentStack (4), modalComponentReturnValueKeys (4);
  29435. static Array <int> modalReturnValues (4);
  29436. static const int customCommandMessage = 0x7fff0001;
  29437. static const int exitModalStateMessage = 0x7fff0002;
  29438. // these are also used by ComponentPeer
  29439. int64 juce_recentMouseDownTimes [4] = { 0, 0, 0, 0 };
  29440. int juce_recentMouseDownX [4] = { 0, 0, 0, 0 };
  29441. int juce_recentMouseDownY [4] = { 0, 0, 0, 0 };
  29442. Component* juce_recentMouseDownComponent [4] = { 0, 0, 0, 0 };
  29443. int juce_LastMousePosX = 0;
  29444. int juce_LastMousePosY = 0;
  29445. int juce_MouseClickCounter = 0;
  29446. bool juce_MouseHasMovedSignificantlySincePressed = false;
  29447. static int countMouseClicks() throw()
  29448. {
  29449. int numClicks = 0;
  29450. if (juce_recentMouseDownTimes[0] != 0)
  29451. {
  29452. if (! juce_MouseHasMovedSignificantlySincePressed)
  29453. ++numClicks;
  29454. for (int i = 1; i < numElementsInArray (juce_recentMouseDownTimes); ++i)
  29455. {
  29456. if (juce_recentMouseDownTimes[0] - juce_recentMouseDownTimes [i]
  29457. < (int) (MouseEvent::getDoubleClickTimeout() * (1.0 + 0.25 * (i - 1)))
  29458. && abs (juce_recentMouseDownX[0] - juce_recentMouseDownX[i]) < 8
  29459. && abs (juce_recentMouseDownY[0] - juce_recentMouseDownY[i]) < 8
  29460. && juce_recentMouseDownComponent[0] == juce_recentMouseDownComponent [i])
  29461. {
  29462. ++numClicks;
  29463. }
  29464. else
  29465. {
  29466. break;
  29467. }
  29468. }
  29469. }
  29470. return numClicks;
  29471. }
  29472. static int unboundedMouseOffsetX = 0;
  29473. static int unboundedMouseOffsetY = 0;
  29474. static bool isUnboundedMouseModeOn = false;
  29475. static bool isCursorVisibleUntilOffscreen;
  29476. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  29477. static uint32 nextComponentUID = 0;
  29478. Component::Component() throw()
  29479. : parentComponent_ (0),
  29480. componentUID (++nextComponentUID),
  29481. numDeepMouseListeners (0),
  29482. childComponentList_ (16),
  29483. lookAndFeel_ (0),
  29484. effect_ (0),
  29485. bufferedImage_ (0),
  29486. mouseListeners_ (0),
  29487. keyListeners_ (0),
  29488. componentListeners_ (0),
  29489. propertySet_ (0),
  29490. componentFlags_ (0)
  29491. {
  29492. }
  29493. Component::Component (const String& name) throw()
  29494. : componentName_ (name),
  29495. parentComponent_ (0),
  29496. componentUID (++nextComponentUID),
  29497. numDeepMouseListeners (0),
  29498. childComponentList_ (16),
  29499. lookAndFeel_ (0),
  29500. effect_ (0),
  29501. bufferedImage_ (0),
  29502. mouseListeners_ (0),
  29503. keyListeners_ (0),
  29504. componentListeners_ (0),
  29505. propertySet_ (0),
  29506. componentFlags_ (0)
  29507. {
  29508. }
  29509. Component::~Component()
  29510. {
  29511. if (parentComponent_ != 0)
  29512. {
  29513. parentComponent_->removeChildComponent (this);
  29514. }
  29515. else if ((currentlyFocusedComponent == this)
  29516. || isParentOf (currentlyFocusedComponent))
  29517. {
  29518. giveAwayFocus();
  29519. }
  29520. if (componentUnderMouse == this)
  29521. componentUnderMouse = 0;
  29522. if (flags.hasHeavyweightPeerFlag)
  29523. removeFromDesktop();
  29524. modalComponentStack.removeValue (this);
  29525. for (int i = childComponentList_.size(); --i >= 0;)
  29526. childComponentList_.getUnchecked(i)->parentComponent_ = 0;
  29527. delete bufferedImage_;
  29528. delete mouseListeners_;
  29529. delete keyListeners_;
  29530. delete componentListeners_;
  29531. delete propertySet_;
  29532. }
  29533. void Component::setName (const String& name)
  29534. {
  29535. // if component methods are being called from threads other than the message
  29536. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29537. checkMessageManagerIsLocked
  29538. if (componentName_ != name)
  29539. {
  29540. componentName_ = name;
  29541. if (flags.hasHeavyweightPeerFlag)
  29542. {
  29543. ComponentPeer* const peer = getPeer();
  29544. jassert (peer != 0);
  29545. if (peer != 0)
  29546. peer->setTitle (name);
  29547. }
  29548. if (componentListeners_ != 0)
  29549. {
  29550. const ComponentDeletionWatcher deletionChecker (this);
  29551. for (int i = componentListeners_->size(); --i >= 0;)
  29552. {
  29553. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29554. ->componentNameChanged (*this);
  29555. if (deletionChecker.hasBeenDeleted())
  29556. return;
  29557. i = jmin (i, componentListeners_->size());
  29558. }
  29559. }
  29560. }
  29561. }
  29562. void Component::setVisible (bool shouldBeVisible)
  29563. {
  29564. if (flags.visibleFlag != shouldBeVisible)
  29565. {
  29566. // if component methods are being called from threads other than the message
  29567. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29568. checkMessageManagerIsLocked
  29569. const ComponentDeletionWatcher deletionChecker (this);
  29570. flags.visibleFlag = shouldBeVisible;
  29571. internalRepaint (0, 0, getWidth(), getHeight());
  29572. sendFakeMouseMove();
  29573. if (! shouldBeVisible)
  29574. {
  29575. if (currentlyFocusedComponent == this
  29576. || isParentOf (currentlyFocusedComponent))
  29577. {
  29578. if (parentComponent_ != 0)
  29579. parentComponent_->grabKeyboardFocus();
  29580. else
  29581. giveAwayFocus();
  29582. }
  29583. }
  29584. sendVisibilityChangeMessage();
  29585. if ((! deletionChecker.hasBeenDeleted()) && flags.hasHeavyweightPeerFlag)
  29586. {
  29587. ComponentPeer* const peer = getPeer();
  29588. jassert (peer != 0);
  29589. if (peer != 0)
  29590. {
  29591. peer->setVisible (shouldBeVisible);
  29592. internalHierarchyChanged();
  29593. }
  29594. }
  29595. }
  29596. }
  29597. void Component::visibilityChanged()
  29598. {
  29599. }
  29600. void Component::sendVisibilityChangeMessage()
  29601. {
  29602. const ComponentDeletionWatcher deletionChecker (this);
  29603. visibilityChanged();
  29604. if ((! deletionChecker.hasBeenDeleted()) && componentListeners_ != 0)
  29605. {
  29606. for (int i = componentListeners_->size(); --i >= 0;)
  29607. {
  29608. ((ComponentListener*) componentListeners_->getUnchecked (i))
  29609. ->componentVisibilityChanged (*this);
  29610. if (deletionChecker.hasBeenDeleted())
  29611. return;
  29612. i = jmin (i, componentListeners_->size());
  29613. }
  29614. }
  29615. }
  29616. bool Component::isShowing() const throw()
  29617. {
  29618. if (flags.visibleFlag)
  29619. {
  29620. if (parentComponent_ != 0)
  29621. {
  29622. return parentComponent_->isShowing();
  29623. }
  29624. else
  29625. {
  29626. const ComponentPeer* const peer = getPeer();
  29627. return peer != 0 && ! peer->isMinimised();
  29628. }
  29629. }
  29630. return false;
  29631. }
  29632. class FadeOutProxyComponent : public Component,
  29633. public Timer
  29634. {
  29635. public:
  29636. FadeOutProxyComponent (Component* comp,
  29637. const int fadeLengthMs,
  29638. const int deltaXToMove,
  29639. const int deltaYToMove,
  29640. const float scaleFactorAtEnd)
  29641. : lastTime (0),
  29642. alpha (1.0f),
  29643. scale (1.0f)
  29644. {
  29645. image = comp->createComponentSnapshot (Rectangle (0, 0, comp->getWidth(), comp->getHeight()));
  29646. setBounds (comp->getBounds());
  29647. comp->getParentComponent()->addAndMakeVisible (this);
  29648. toBehind (comp);
  29649. alphaChangePerMs = -1.0f / (float)fadeLengthMs;
  29650. centreX = comp->getX() + comp->getWidth() * 0.5f;
  29651. xChangePerMs = deltaXToMove / (float)fadeLengthMs;
  29652. centreY = comp->getY() + comp->getHeight() * 0.5f;
  29653. yChangePerMs = deltaYToMove / (float)fadeLengthMs;
  29654. scaleChangePerMs = (scaleFactorAtEnd - 1.0f) / (float)fadeLengthMs;
  29655. setInterceptsMouseClicks (false, false);
  29656. // 30 fps is enough for a fade, but we need a higher rate if it's moving as well..
  29657. startTimer (1000 / ((deltaXToMove == 0 && deltaYToMove == 0) ? 30 : 50));
  29658. }
  29659. ~FadeOutProxyComponent()
  29660. {
  29661. delete image;
  29662. }
  29663. void paint (Graphics& g)
  29664. {
  29665. g.setOpacity (alpha);
  29666. g.drawImage (image,
  29667. 0, 0, getWidth(), getHeight(),
  29668. 0, 0, image->getWidth(), image->getHeight());
  29669. }
  29670. void timerCallback()
  29671. {
  29672. const uint32 now = Time::getMillisecondCounter();
  29673. if (lastTime == 0)
  29674. lastTime = now;
  29675. const int msPassed = (now > lastTime) ? now - lastTime : 0;
  29676. lastTime = now;
  29677. alpha += alphaChangePerMs * msPassed;
  29678. if (alpha > 0)
  29679. {
  29680. if (xChangePerMs != 0.0f || yChangePerMs != 0.0f || scaleChangePerMs != 0.0f)
  29681. {
  29682. centreX += xChangePerMs * msPassed;
  29683. centreY += yChangePerMs * msPassed;
  29684. scale += scaleChangePerMs * msPassed;
  29685. const int w = roundFloatToInt (image->getWidth() * scale);
  29686. const int h = roundFloatToInt (image->getHeight() * scale);
  29687. setBounds (roundFloatToInt (centreX) - w / 2,
  29688. roundFloatToInt (centreY) - h / 2,
  29689. w, h);
  29690. }
  29691. repaint();
  29692. }
  29693. else
  29694. {
  29695. delete this;
  29696. }
  29697. }
  29698. juce_UseDebuggingNewOperator
  29699. private:
  29700. Image* image;
  29701. uint32 lastTime;
  29702. float alpha, alphaChangePerMs;
  29703. float centreX, xChangePerMs;
  29704. float centreY, yChangePerMs;
  29705. float scale, scaleChangePerMs;
  29706. FadeOutProxyComponent (const FadeOutProxyComponent&);
  29707. const FadeOutProxyComponent& operator= (const FadeOutProxyComponent&);
  29708. };
  29709. void Component::fadeOutComponent (const int millisecondsToFade,
  29710. const int deltaXToMove,
  29711. const int deltaYToMove,
  29712. const float scaleFactorAtEnd)
  29713. {
  29714. //xxx won't work for comps without parents
  29715. if (isShowing() && millisecondsToFade > 0)
  29716. new FadeOutProxyComponent (this, millisecondsToFade,
  29717. deltaXToMove, deltaYToMove, scaleFactorAtEnd);
  29718. setVisible (false);
  29719. }
  29720. bool Component::isValidComponent() const throw()
  29721. {
  29722. return (this != 0) && isValidMessageListener();
  29723. }
  29724. void* Component::getWindowHandle() const throw()
  29725. {
  29726. const ComponentPeer* const peer = getPeer();
  29727. if (peer != 0)
  29728. return peer->getNativeHandle();
  29729. return 0;
  29730. }
  29731. void Component::addToDesktop (int styleWanted, void* nativeWindowToAttachTo)
  29732. {
  29733. // if component methods are being called from threads other than the message
  29734. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29735. checkMessageManagerIsLocked
  29736. if (! isOpaque())
  29737. styleWanted |= ComponentPeer::windowIsSemiTransparent;
  29738. int currentStyleFlags = 0;
  29739. // don't use getPeer(), so that we only get the peer that's specifically
  29740. // for this comp, and not for one of its parents.
  29741. ComponentPeer* peer = ComponentPeer::getPeerFor (this);
  29742. if (peer != 0)
  29743. currentStyleFlags = peer->getStyleFlags();
  29744. if (styleWanted != currentStyleFlags || ! flags.hasHeavyweightPeerFlag)
  29745. {
  29746. const ComponentDeletionWatcher deletionChecker (this);
  29747. #if JUCE_LINUX
  29748. // it's wise to give the component a non-zero size before
  29749. // putting it on the desktop, as X windows get confused by this, and
  29750. // a (1, 1) minimum size is enforced here.
  29751. setSize (jmax (1, getWidth()),
  29752. jmax (1, getHeight()));
  29753. #endif
  29754. int x = 0, y = 0;
  29755. relativePositionToGlobal (x, y);
  29756. bool wasFullscreen = false;
  29757. bool wasMinimised = false;
  29758. ComponentBoundsConstrainer* currentConstainer = 0;
  29759. Rectangle oldNonFullScreenBounds;
  29760. if (peer != 0)
  29761. {
  29762. wasFullscreen = peer->isFullScreen();
  29763. wasMinimised = peer->isMinimised();
  29764. currentConstainer = peer->getConstrainer();
  29765. oldNonFullScreenBounds = peer->getNonFullScreenBounds();
  29766. removeFromDesktop();
  29767. setTopLeftPosition (x, y);
  29768. }
  29769. if (parentComponent_ != 0)
  29770. parentComponent_->removeChildComponent (this);
  29771. if (! deletionChecker.hasBeenDeleted())
  29772. {
  29773. flags.hasHeavyweightPeerFlag = true;
  29774. peer = createNewPeer (styleWanted, nativeWindowToAttachTo);
  29775. Desktop::getInstance().addDesktopComponent (this);
  29776. bounds_.setPosition (x, y);
  29777. peer->setBounds (x, y, getWidth(), getHeight(), false);
  29778. peer->setVisible (isVisible());
  29779. if (wasFullscreen)
  29780. {
  29781. peer->setFullScreen (true);
  29782. peer->setNonFullScreenBounds (oldNonFullScreenBounds);
  29783. }
  29784. if (wasMinimised)
  29785. peer->setMinimised (true);
  29786. if (isAlwaysOnTop())
  29787. peer->setAlwaysOnTop (true);
  29788. peer->setConstrainer (currentConstainer);
  29789. repaint();
  29790. }
  29791. internalHierarchyChanged();
  29792. }
  29793. }
  29794. void Component::removeFromDesktop()
  29795. {
  29796. // if component methods are being called from threads other than the message
  29797. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29798. checkMessageManagerIsLocked
  29799. if (flags.hasHeavyweightPeerFlag)
  29800. {
  29801. ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  29802. flags.hasHeavyweightPeerFlag = false;
  29803. jassert (peer != 0);
  29804. delete peer;
  29805. Desktop::getInstance().removeDesktopComponent (this);
  29806. }
  29807. }
  29808. bool Component::isOnDesktop() const throw()
  29809. {
  29810. return flags.hasHeavyweightPeerFlag;
  29811. }
  29812. void Component::userTriedToCloseWindow()
  29813. {
  29814. /* This means that the user's trying to get rid of your window with the 'close window' system
  29815. menu option (on windows) or possibly the task manager - you should really handle this
  29816. and delete or hide your component in an appropriate way.
  29817. If you want to ignore the event and don't want to trigger this assertion, just override
  29818. this method and do nothing.
  29819. */
  29820. jassertfalse
  29821. }
  29822. void Component::minimisationStateChanged (bool)
  29823. {
  29824. }
  29825. void Component::setOpaque (const bool shouldBeOpaque) throw()
  29826. {
  29827. if (shouldBeOpaque != flags.opaqueFlag)
  29828. {
  29829. flags.opaqueFlag = shouldBeOpaque;
  29830. if (flags.hasHeavyweightPeerFlag)
  29831. {
  29832. const ComponentPeer* const peer = ComponentPeer::getPeerFor (this);
  29833. if (peer != 0)
  29834. {
  29835. // to make it recreate the heavyweight window
  29836. addToDesktop (peer->getStyleFlags());
  29837. }
  29838. }
  29839. repaint();
  29840. }
  29841. }
  29842. bool Component::isOpaque() const throw()
  29843. {
  29844. return flags.opaqueFlag;
  29845. }
  29846. void Component::setBufferedToImage (const bool shouldBeBuffered) throw()
  29847. {
  29848. if (shouldBeBuffered != flags.bufferToImageFlag)
  29849. {
  29850. deleteAndZero (bufferedImage_);
  29851. flags.bufferToImageFlag = shouldBeBuffered;
  29852. }
  29853. }
  29854. void Component::toFront (const bool setAsForeground)
  29855. {
  29856. // if component methods are being called from threads other than the message
  29857. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  29858. checkMessageManagerIsLocked
  29859. if (flags.hasHeavyweightPeerFlag)
  29860. {
  29861. ComponentPeer* const peer = getPeer();
  29862. if (peer != 0)
  29863. {
  29864. peer->toFront (setAsForeground);
  29865. if (setAsForeground && ! hasKeyboardFocus (true))
  29866. grabKeyboardFocus();
  29867. }
  29868. }
  29869. else if (parentComponent_ != 0)
  29870. {
  29871. if (parentComponent_->childComponentList_.getLast() != this)
  29872. {
  29873. const int index = parentComponent_->childComponentList_.indexOf (this);
  29874. if (index >= 0)
  29875. {
  29876. int insertIndex = -1;
  29877. if (! flags.alwaysOnTopFlag)
  29878. {
  29879. insertIndex = parentComponent_->childComponentList_.size() - 1;
  29880. while (insertIndex > 0
  29881. && parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  29882. {
  29883. --insertIndex;
  29884. }
  29885. }
  29886. if (index != insertIndex)
  29887. {
  29888. parentComponent_->childComponentList_.move (index, insertIndex);
  29889. sendFakeMouseMove();
  29890. repaintParent();
  29891. }
  29892. }
  29893. }
  29894. if (setAsForeground)
  29895. {
  29896. internalBroughtToFront();
  29897. grabKeyboardFocus();
  29898. }
  29899. }
  29900. }
  29901. void Component::toBehind (Component* const other)
  29902. {
  29903. if (other != 0)
  29904. {
  29905. // the two components must belong to the same parent..
  29906. jassert (parentComponent_ == other->parentComponent_);
  29907. if (parentComponent_ != 0)
  29908. {
  29909. const int index = parentComponent_->childComponentList_.indexOf (this);
  29910. int otherIndex = parentComponent_->childComponentList_.indexOf (other);
  29911. if (index >= 0
  29912. && otherIndex >= 0
  29913. && index != otherIndex - 1
  29914. && other != this)
  29915. {
  29916. if (index < otherIndex)
  29917. --otherIndex;
  29918. parentComponent_->childComponentList_.move (index, otherIndex);
  29919. sendFakeMouseMove();
  29920. repaintParent();
  29921. }
  29922. }
  29923. else if (isOnDesktop())
  29924. {
  29925. jassert (other->isOnDesktop());
  29926. if (other->isOnDesktop())
  29927. {
  29928. ComponentPeer* const us = getPeer();
  29929. ComponentPeer* const them = other->getPeer();
  29930. jassert (us != 0 && them != 0);
  29931. if (us != 0 && them != 0)
  29932. us->toBehind (them);
  29933. }
  29934. }
  29935. }
  29936. }
  29937. void Component::toBack()
  29938. {
  29939. if (isOnDesktop())
  29940. {
  29941. jassertfalse //xxx need to add this to native window
  29942. }
  29943. else if (parentComponent_ != 0
  29944. && parentComponent_->childComponentList_.getFirst() != this)
  29945. {
  29946. const int index = parentComponent_->childComponentList_.indexOf (this);
  29947. if (index > 0)
  29948. {
  29949. int insertIndex = 0;
  29950. if (flags.alwaysOnTopFlag)
  29951. {
  29952. while (insertIndex < parentComponent_->childComponentList_.size()
  29953. && ! parentComponent_->childComponentList_.getUnchecked (insertIndex)->isAlwaysOnTop())
  29954. {
  29955. ++insertIndex;
  29956. }
  29957. }
  29958. if (index != insertIndex)
  29959. {
  29960. parentComponent_->childComponentList_.move (index, insertIndex);
  29961. sendFakeMouseMove();
  29962. repaintParent();
  29963. }
  29964. }
  29965. }
  29966. }
  29967. void Component::setAlwaysOnTop (const bool shouldStayOnTop)
  29968. {
  29969. if (shouldStayOnTop != flags.alwaysOnTopFlag)
  29970. {
  29971. flags.alwaysOnTopFlag = shouldStayOnTop;
  29972. if (isOnDesktop())
  29973. {
  29974. ComponentPeer* const peer = getPeer();
  29975. jassert (peer != 0);
  29976. if (peer != 0)
  29977. {
  29978. if (! peer->setAlwaysOnTop (shouldStayOnTop))
  29979. {
  29980. // some kinds of peer can't change their always-on-top status, so
  29981. // for these, we'll need to create a new window
  29982. const int oldFlags = peer->getStyleFlags();
  29983. removeFromDesktop();
  29984. addToDesktop (oldFlags);
  29985. }
  29986. }
  29987. }
  29988. if (shouldStayOnTop)
  29989. toFront (false);
  29990. internalHierarchyChanged();
  29991. }
  29992. }
  29993. bool Component::isAlwaysOnTop() const throw()
  29994. {
  29995. return flags.alwaysOnTopFlag;
  29996. }
  29997. int Component::proportionOfWidth (const float proportion) const throw()
  29998. {
  29999. return roundDoubleToInt (proportion * bounds_.getWidth());
  30000. }
  30001. int Component::proportionOfHeight (const float proportion) const throw()
  30002. {
  30003. return roundDoubleToInt (proportion * bounds_.getHeight());
  30004. }
  30005. int Component::getParentWidth() const throw()
  30006. {
  30007. return (parentComponent_ != 0) ? parentComponent_->getWidth()
  30008. : getParentMonitorArea().getWidth();
  30009. }
  30010. int Component::getParentHeight() const throw()
  30011. {
  30012. return (parentComponent_ != 0) ? parentComponent_->getHeight()
  30013. : getParentMonitorArea().getHeight();
  30014. }
  30015. int Component::getScreenX() const throw()
  30016. {
  30017. return (parentComponent_ != 0) ? parentComponent_->getScreenX() + getX()
  30018. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenX()
  30019. : getX());
  30020. }
  30021. int Component::getScreenY() const throw()
  30022. {
  30023. return (parentComponent_ != 0) ? parentComponent_->getScreenY() + getY()
  30024. : (flags.hasHeavyweightPeerFlag ? getPeer()->getScreenY()
  30025. : getY());
  30026. }
  30027. void Component::relativePositionToGlobal (int& x, int& y) const throw()
  30028. {
  30029. const Component* c = this;
  30030. do
  30031. {
  30032. if (c->flags.hasHeavyweightPeerFlag)
  30033. {
  30034. c->getPeer()->relativePositionToGlobal (x, y);
  30035. break;
  30036. }
  30037. x += c->getX();
  30038. y += c->getY();
  30039. c = c->parentComponent_;
  30040. }
  30041. while (c != 0);
  30042. }
  30043. void Component::globalPositionToRelative (int& x, int& y) const throw()
  30044. {
  30045. if (flags.hasHeavyweightPeerFlag)
  30046. {
  30047. getPeer()->globalPositionToRelative (x, y);
  30048. }
  30049. else
  30050. {
  30051. if (parentComponent_ != 0)
  30052. parentComponent_->globalPositionToRelative (x, y);
  30053. x -= getX();
  30054. y -= getY();
  30055. }
  30056. }
  30057. void Component::relativePositionToOtherComponent (const Component* const targetComponent, int& x, int& y) const throw()
  30058. {
  30059. if (targetComponent != 0)
  30060. {
  30061. const Component* c = this;
  30062. do
  30063. {
  30064. if (c == targetComponent)
  30065. return;
  30066. if (c->flags.hasHeavyweightPeerFlag)
  30067. {
  30068. c->getPeer()->relativePositionToGlobal (x, y);
  30069. break;
  30070. }
  30071. x += c->getX();
  30072. y += c->getY();
  30073. c = c->parentComponent_;
  30074. }
  30075. while (c != 0);
  30076. targetComponent->globalPositionToRelative (x, y);
  30077. }
  30078. }
  30079. void Component::setBounds (int x, int y, int w, int h)
  30080. {
  30081. // if component methods are being called from threads other than the message
  30082. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30083. checkMessageManagerIsLocked
  30084. if (w < 0) w = 0;
  30085. if (h < 0) h = 0;
  30086. const bool wasResized = (getWidth() != w || getHeight() != h);
  30087. const bool wasMoved = (getX() != x || getY() != y);
  30088. #ifdef JUCE_DEBUG
  30089. // It's a very bad idea to try to resize a window during its paint() method!
  30090. jassert (! (flags.isInsidePaintCall && wasResized && isOnDesktop()));
  30091. #endif
  30092. if (wasMoved || wasResized)
  30093. {
  30094. if (flags.visibleFlag)
  30095. {
  30096. // send a fake mouse move to trigger enter/exit messages if needed..
  30097. sendFakeMouseMove();
  30098. if (! flags.hasHeavyweightPeerFlag)
  30099. repaintParent();
  30100. }
  30101. bounds_.setBounds (x, y, w, h);
  30102. if (wasResized)
  30103. repaint();
  30104. else if (! flags.hasHeavyweightPeerFlag)
  30105. repaintParent();
  30106. if (flags.hasHeavyweightPeerFlag)
  30107. {
  30108. ComponentPeer* const peer = getPeer();
  30109. if (peer != 0)
  30110. {
  30111. if (wasMoved && wasResized)
  30112. peer->setBounds (getX(), getY(), getWidth(), getHeight(), false);
  30113. else if (wasMoved)
  30114. peer->setPosition (getX(), getY());
  30115. else if (wasResized)
  30116. peer->setSize (getWidth(), getHeight());
  30117. }
  30118. }
  30119. sendMovedResizedMessages (wasMoved, wasResized);
  30120. }
  30121. }
  30122. void Component::sendMovedResizedMessages (const bool wasMoved, const bool wasResized)
  30123. {
  30124. JUCE_TRY
  30125. {
  30126. if (wasMoved)
  30127. moved();
  30128. if (wasResized)
  30129. {
  30130. resized();
  30131. for (int i = childComponentList_.size(); --i >= 0;)
  30132. {
  30133. childComponentList_.getUnchecked(i)->parentSizeChanged();
  30134. i = jmin (i, childComponentList_.size());
  30135. }
  30136. }
  30137. if (parentComponent_ != 0)
  30138. parentComponent_->childBoundsChanged (this);
  30139. if (componentListeners_ != 0)
  30140. {
  30141. const ComponentDeletionWatcher deletionChecker (this);
  30142. for (int i = componentListeners_->size(); --i >= 0;)
  30143. {
  30144. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30145. ->componentMovedOrResized (*this, wasMoved, wasResized);
  30146. if (deletionChecker.hasBeenDeleted())
  30147. return;
  30148. i = jmin (i, componentListeners_->size());
  30149. }
  30150. }
  30151. }
  30152. JUCE_CATCH_EXCEPTION
  30153. }
  30154. void Component::setSize (const int w, const int h)
  30155. {
  30156. setBounds (getX(), getY(), w, h);
  30157. }
  30158. void Component::setTopLeftPosition (const int x, const int y)
  30159. {
  30160. setBounds (x, y, getWidth(), getHeight());
  30161. }
  30162. void Component::setTopRightPosition (const int x, const int y)
  30163. {
  30164. setTopLeftPosition (x - getWidth(), y);
  30165. }
  30166. void Component::setBounds (const Rectangle& r)
  30167. {
  30168. setBounds (r.getX(),
  30169. r.getY(),
  30170. r.getWidth(),
  30171. r.getHeight());
  30172. }
  30173. void Component::setBoundsRelative (const float x, const float y,
  30174. const float w, const float h)
  30175. {
  30176. const int pw = getParentWidth();
  30177. const int ph = getParentHeight();
  30178. setBounds (roundFloatToInt (x * pw),
  30179. roundFloatToInt (y * ph),
  30180. roundFloatToInt (w * pw),
  30181. roundFloatToInt (h * ph));
  30182. }
  30183. void Component::setCentrePosition (const int x, const int y)
  30184. {
  30185. setTopLeftPosition (x - getWidth() / 2,
  30186. y - getHeight() / 2);
  30187. }
  30188. void Component::setCentreRelative (const float x, const float y)
  30189. {
  30190. setCentrePosition (roundFloatToInt (getParentWidth() * x),
  30191. roundFloatToInt (getParentHeight() * y));
  30192. }
  30193. void Component::centreWithSize (const int width, const int height)
  30194. {
  30195. setBounds ((getParentWidth() - width) / 2,
  30196. (getParentHeight() - height) / 2,
  30197. width,
  30198. height);
  30199. }
  30200. void Component::setBoundsInset (const BorderSize& borders)
  30201. {
  30202. setBounds (borders.getLeft(),
  30203. borders.getTop(),
  30204. getParentWidth() - (borders.getLeftAndRight()),
  30205. getParentHeight() - (borders.getTopAndBottom()));
  30206. }
  30207. void Component::setBoundsToFit (int x, int y, int width, int height,
  30208. const Justification& justification,
  30209. const bool onlyReduceInSize)
  30210. {
  30211. // it's no good calling this method unless both the component and
  30212. // target rectangle have a finite size.
  30213. jassert (getWidth() > 0 && getHeight() > 0 && width > 0 && height > 0);
  30214. if (getWidth() > 0 && getHeight() > 0
  30215. && width > 0 && height > 0)
  30216. {
  30217. int newW, newH;
  30218. if (onlyReduceInSize && getWidth() <= width && getHeight() <= height)
  30219. {
  30220. newW = getWidth();
  30221. newH = getHeight();
  30222. }
  30223. else
  30224. {
  30225. const double imageRatio = getHeight() / (double) getWidth();
  30226. const double targetRatio = height / (double) width;
  30227. if (imageRatio <= targetRatio)
  30228. {
  30229. newW = width;
  30230. newH = jmin (height, roundDoubleToInt (newW * imageRatio));
  30231. }
  30232. else
  30233. {
  30234. newH = height;
  30235. newW = jmin (width, roundDoubleToInt (newH / imageRatio));
  30236. }
  30237. }
  30238. if (newW > 0 && newH > 0)
  30239. {
  30240. int newX, newY;
  30241. justification.applyToRectangle (newX, newY, newW, newH,
  30242. x, y, width, height);
  30243. setBounds (newX, newY, newW, newH);
  30244. }
  30245. }
  30246. }
  30247. bool Component::hitTest (int x, int y)
  30248. {
  30249. if (! flags.ignoresMouseClicksFlag)
  30250. return true;
  30251. if (flags.allowChildMouseClicksFlag)
  30252. {
  30253. for (int i = getNumChildComponents(); --i >= 0;)
  30254. {
  30255. Component* const c = getChildComponent (i);
  30256. if (c->isVisible()
  30257. && c->bounds_.contains (x, y)
  30258. && c->hitTest (x - c->getX(),
  30259. y - c->getY()))
  30260. {
  30261. return true;
  30262. }
  30263. }
  30264. }
  30265. return false;
  30266. }
  30267. void Component::setInterceptsMouseClicks (const bool allowClicks,
  30268. const bool allowClicksOnChildComponents) throw()
  30269. {
  30270. flags.ignoresMouseClicksFlag = ! allowClicks;
  30271. flags.allowChildMouseClicksFlag = allowClicksOnChildComponents;
  30272. }
  30273. void Component::getInterceptsMouseClicks (bool& allowsClicksOnThisComponent,
  30274. bool& allowsClicksOnChildComponents) const throw()
  30275. {
  30276. allowsClicksOnThisComponent = ! flags.ignoresMouseClicksFlag;
  30277. allowsClicksOnChildComponents = flags.allowChildMouseClicksFlag;
  30278. }
  30279. bool Component::contains (const int x, const int y)
  30280. {
  30281. if (((unsigned int) x) < (unsigned int) getWidth()
  30282. && ((unsigned int) y) < (unsigned int) getHeight()
  30283. && hitTest (x, y))
  30284. {
  30285. if (parentComponent_ != 0)
  30286. {
  30287. return parentComponent_->contains (x + getX(),
  30288. y + getY());
  30289. }
  30290. else if (flags.hasHeavyweightPeerFlag)
  30291. {
  30292. const ComponentPeer* const peer = getPeer();
  30293. if (peer != 0)
  30294. return peer->contains (x, y, true);
  30295. }
  30296. }
  30297. return false;
  30298. }
  30299. bool Component::reallyContains (int x, int y, const bool returnTrueIfWithinAChild)
  30300. {
  30301. if (! contains (x, y))
  30302. return false;
  30303. Component* p = this;
  30304. while (p->parentComponent_ != 0)
  30305. {
  30306. x += p->getX();
  30307. y += p->getY();
  30308. p = p->parentComponent_;
  30309. }
  30310. const Component* const c = p->getComponentAt (x, y);
  30311. return (c == this) || (returnTrueIfWithinAChild && isParentOf (c));
  30312. }
  30313. Component* Component::getComponentAt (const int x, const int y)
  30314. {
  30315. if (flags.visibleFlag
  30316. && ((unsigned int) x) < (unsigned int) getWidth()
  30317. && ((unsigned int) y) < (unsigned int) getHeight()
  30318. && hitTest (x, y))
  30319. {
  30320. for (int i = childComponentList_.size(); --i >= 0;)
  30321. {
  30322. Component* const child = childComponentList_.getUnchecked(i);
  30323. Component* const c = child->getComponentAt (x - child->getX(),
  30324. y - child->getY());
  30325. if (c != 0)
  30326. return c;
  30327. }
  30328. return this;
  30329. }
  30330. return 0;
  30331. }
  30332. void Component::addChildComponent (Component* const child, int zOrder)
  30333. {
  30334. // if component methods are being called from threads other than the message
  30335. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30336. checkMessageManagerIsLocked
  30337. if (child != 0 && child->parentComponent_ != this)
  30338. {
  30339. if (child->parentComponent_ != 0)
  30340. child->parentComponent_->removeChildComponent (child);
  30341. else
  30342. child->removeFromDesktop();
  30343. child->parentComponent_ = this;
  30344. if (child->isVisible())
  30345. child->repaintParent();
  30346. if (! child->isAlwaysOnTop())
  30347. {
  30348. if (zOrder < 0 || zOrder > childComponentList_.size())
  30349. zOrder = childComponentList_.size();
  30350. while (zOrder > 0)
  30351. {
  30352. if (! childComponentList_.getUnchecked (zOrder - 1)->isAlwaysOnTop())
  30353. break;
  30354. --zOrder;
  30355. }
  30356. }
  30357. childComponentList_.insert (zOrder, child);
  30358. child->internalHierarchyChanged();
  30359. internalChildrenChanged();
  30360. }
  30361. }
  30362. void Component::addAndMakeVisible (Component* const child, int zOrder)
  30363. {
  30364. if (child != 0)
  30365. {
  30366. child->setVisible (true);
  30367. addChildComponent (child, zOrder);
  30368. }
  30369. }
  30370. void Component::removeChildComponent (Component* const child)
  30371. {
  30372. removeChildComponent (childComponentList_.indexOf (child));
  30373. }
  30374. Component* Component::removeChildComponent (const int index)
  30375. {
  30376. // if component methods are being called from threads other than the message
  30377. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30378. checkMessageManagerIsLocked
  30379. Component* const child = childComponentList_ [index];
  30380. if (child != 0)
  30381. {
  30382. sendFakeMouseMove();
  30383. child->repaintParent();
  30384. childComponentList_.remove (index);
  30385. child->parentComponent_ = 0;
  30386. JUCE_TRY
  30387. {
  30388. if ((currentlyFocusedComponent == child)
  30389. || child->isParentOf (currentlyFocusedComponent))
  30390. {
  30391. // get rid first to force the grabKeyboardFocus to change to us.
  30392. giveAwayFocus();
  30393. grabKeyboardFocus();
  30394. }
  30395. }
  30396. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  30397. catch (const std::exception& e)
  30398. {
  30399. currentlyFocusedComponent = 0;
  30400. Desktop::getInstance().triggerFocusCallback();
  30401. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  30402. }
  30403. catch (...)
  30404. {
  30405. currentlyFocusedComponent = 0;
  30406. Desktop::getInstance().triggerFocusCallback();
  30407. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  30408. }
  30409. #endif
  30410. child->internalHierarchyChanged();
  30411. internalChildrenChanged();
  30412. }
  30413. return child;
  30414. }
  30415. void Component::removeAllChildren()
  30416. {
  30417. for (int i = childComponentList_.size(); --i >= 0;)
  30418. removeChildComponent (i);
  30419. }
  30420. void Component::deleteAllChildren()
  30421. {
  30422. for (int i = childComponentList_.size(); --i >= 0;)
  30423. delete (removeChildComponent (i));
  30424. }
  30425. int Component::getNumChildComponents() const throw()
  30426. {
  30427. return childComponentList_.size();
  30428. }
  30429. Component* Component::getChildComponent (const int index) const throw()
  30430. {
  30431. return childComponentList_ [index];
  30432. }
  30433. int Component::getIndexOfChildComponent (const Component* const child) const throw()
  30434. {
  30435. return childComponentList_.indexOf (const_cast <Component*> (child));
  30436. }
  30437. Component* Component::getTopLevelComponent() const throw()
  30438. {
  30439. const Component* comp = this;
  30440. while (comp->parentComponent_ != 0)
  30441. comp = comp->parentComponent_;
  30442. return (Component*) comp;
  30443. }
  30444. bool Component::isParentOf (const Component* possibleChild) const throw()
  30445. {
  30446. while (possibleChild->isValidComponent())
  30447. {
  30448. possibleChild = possibleChild->parentComponent_;
  30449. if (possibleChild == this)
  30450. return true;
  30451. }
  30452. return false;
  30453. }
  30454. void Component::parentHierarchyChanged()
  30455. {
  30456. }
  30457. void Component::childrenChanged()
  30458. {
  30459. }
  30460. void Component::internalChildrenChanged()
  30461. {
  30462. const ComponentDeletionWatcher deletionChecker (this);
  30463. const bool hasListeners = componentListeners_ != 0;
  30464. childrenChanged();
  30465. if (hasListeners)
  30466. {
  30467. if (deletionChecker.hasBeenDeleted())
  30468. return;
  30469. for (int i = componentListeners_->size(); --i >= 0;)
  30470. {
  30471. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30472. ->componentChildrenChanged (*this);
  30473. if (deletionChecker.hasBeenDeleted())
  30474. return;
  30475. i = jmin (i, componentListeners_->size());
  30476. }
  30477. }
  30478. }
  30479. void Component::internalHierarchyChanged()
  30480. {
  30481. parentHierarchyChanged();
  30482. const ComponentDeletionWatcher deletionChecker (this);
  30483. if (componentListeners_ != 0)
  30484. {
  30485. for (int i = componentListeners_->size(); --i >= 0;)
  30486. {
  30487. ((ComponentListener*) componentListeners_->getUnchecked (i))
  30488. ->componentParentHierarchyChanged (*this);
  30489. if (deletionChecker.hasBeenDeleted())
  30490. return;
  30491. i = jmin (i, componentListeners_->size());
  30492. }
  30493. }
  30494. for (int i = childComponentList_.size(); --i >= 0;)
  30495. {
  30496. childComponentList_.getUnchecked (i)->internalHierarchyChanged();
  30497. // you really shouldn't delete the parent component during a callback telling you
  30498. // that it's changed..
  30499. jassert (! deletionChecker.hasBeenDeleted());
  30500. if (deletionChecker.hasBeenDeleted())
  30501. return;
  30502. i = jmin (i, childComponentList_.size());
  30503. }
  30504. }
  30505. void* Component::runModalLoopCallback (void* userData)
  30506. {
  30507. return (void*) (pointer_sized_int) ((Component*) userData)->runModalLoop();
  30508. }
  30509. int Component::runModalLoop()
  30510. {
  30511. if (! MessageManager::getInstance()->isThisTheMessageThread())
  30512. {
  30513. // use a callback so this can be called from non-gui threads
  30514. return (int) (pointer_sized_int)
  30515. MessageManager::getInstance()
  30516. ->callFunctionOnMessageThread (&runModalLoopCallback, (void*) this);
  30517. }
  30518. Component* const prevFocused = getCurrentlyFocusedComponent();
  30519. ComponentDeletionWatcher* deletionChecker = 0;
  30520. if (prevFocused != 0)
  30521. deletionChecker = new ComponentDeletionWatcher (prevFocused);
  30522. if (! isCurrentlyModal())
  30523. enterModalState();
  30524. JUCE_TRY
  30525. {
  30526. while (flags.currentlyModalFlag && flags.visibleFlag)
  30527. {
  30528. if (! MessageManager::getInstance()->runDispatchLoopUntil (20))
  30529. break;
  30530. // check whether this component was deleted during the last message
  30531. if (! isValidMessageListener())
  30532. break;
  30533. }
  30534. }
  30535. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  30536. catch (const std::exception& e)
  30537. {
  30538. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  30539. return 0;
  30540. }
  30541. catch (...)
  30542. {
  30543. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  30544. return 0;
  30545. }
  30546. #endif
  30547. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  30548. int returnValue = 0;
  30549. if (modalIndex >= 0)
  30550. {
  30551. modalComponentReturnValueKeys.remove (modalIndex);
  30552. returnValue = modalReturnValues.remove (modalIndex);
  30553. }
  30554. modalComponentStack.removeValue (this);
  30555. if (deletionChecker != 0)
  30556. {
  30557. if (! deletionChecker->hasBeenDeleted())
  30558. prevFocused->grabKeyboardFocus();
  30559. delete deletionChecker;
  30560. }
  30561. return returnValue;
  30562. }
  30563. void Component::enterModalState (const bool takeKeyboardFocus)
  30564. {
  30565. // if component methods are being called from threads other than the message
  30566. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30567. checkMessageManagerIsLocked
  30568. // Check for an attempt to make a component modal when it already is!
  30569. // This can cause nasty problems..
  30570. jassert (! flags.currentlyModalFlag);
  30571. if (! isCurrentlyModal())
  30572. {
  30573. modalComponentStack.add (this);
  30574. modalComponentReturnValueKeys.add (this);
  30575. modalReturnValues.add (0);
  30576. flags.currentlyModalFlag = true;
  30577. setVisible (true);
  30578. if (takeKeyboardFocus)
  30579. grabKeyboardFocus();
  30580. }
  30581. }
  30582. void Component::exitModalState (const int returnValue)
  30583. {
  30584. if (isCurrentlyModal())
  30585. {
  30586. if (MessageManager::getInstance()->isThisTheMessageThread())
  30587. {
  30588. const int modalIndex = modalComponentReturnValueKeys.indexOf (this);
  30589. if (modalIndex >= 0)
  30590. {
  30591. modalReturnValues.set (modalIndex, returnValue);
  30592. }
  30593. else
  30594. {
  30595. modalComponentReturnValueKeys.add (this);
  30596. modalReturnValues.add (returnValue);
  30597. }
  30598. modalComponentStack.removeValue (this);
  30599. flags.currentlyModalFlag = false;
  30600. }
  30601. else
  30602. {
  30603. postMessage (new Message (exitModalStateMessage, returnValue, 0, 0));
  30604. }
  30605. }
  30606. }
  30607. bool Component::isCurrentlyModal() const throw()
  30608. {
  30609. return flags.currentlyModalFlag
  30610. && getCurrentlyModalComponent() == this;
  30611. }
  30612. bool Component::isCurrentlyBlockedByAnotherModalComponent() const throw()
  30613. {
  30614. Component* const mc = getCurrentlyModalComponent();
  30615. return mc != 0
  30616. && mc != this
  30617. && (! mc->isParentOf (this))
  30618. && ! mc->canModalEventBeSentToComponent (this);
  30619. }
  30620. Component* JUCE_CALLTYPE Component::getCurrentlyModalComponent() throw()
  30621. {
  30622. Component* const c = (Component*) modalComponentStack.getLast();
  30623. return c->isValidComponent() ? c : 0;
  30624. }
  30625. void Component::setBroughtToFrontOnMouseClick (const bool shouldBeBroughtToFront) throw()
  30626. {
  30627. flags.bringToFrontOnClickFlag = shouldBeBroughtToFront;
  30628. }
  30629. bool Component::isBroughtToFrontOnMouseClick() const throw()
  30630. {
  30631. return flags.bringToFrontOnClickFlag;
  30632. }
  30633. void Component::setMouseCursor (const MouseCursor& cursor) throw()
  30634. {
  30635. cursor_ = cursor;
  30636. if (flags.visibleFlag)
  30637. {
  30638. int mx, my;
  30639. getMouseXYRelative (mx, my);
  30640. if (flags.draggingFlag || reallyContains (mx, my, false))
  30641. {
  30642. internalUpdateMouseCursor (false);
  30643. }
  30644. }
  30645. }
  30646. const MouseCursor Component::getMouseCursor()
  30647. {
  30648. return cursor_;
  30649. }
  30650. void Component::updateMouseCursor() const throw()
  30651. {
  30652. sendFakeMouseMove();
  30653. }
  30654. void Component::internalUpdateMouseCursor (const bool forcedUpdate) throw()
  30655. {
  30656. ComponentPeer* const peer = getPeer();
  30657. if (peer != 0)
  30658. {
  30659. MouseCursor mc (getMouseCursor());
  30660. if (isUnboundedMouseModeOn && (unboundedMouseOffsetX != 0
  30661. || unboundedMouseOffsetY != 0
  30662. || ! isCursorVisibleUntilOffscreen))
  30663. {
  30664. mc = MouseCursor::NoCursor;
  30665. }
  30666. static void* currentCursorHandle = 0;
  30667. if (forcedUpdate || mc.getHandle() != currentCursorHandle)
  30668. {
  30669. currentCursorHandle = mc.getHandle();
  30670. mc.showInWindow (peer);
  30671. }
  30672. }
  30673. }
  30674. void Component::setRepaintsOnMouseActivity (const bool shouldRepaint) throw()
  30675. {
  30676. flags.repaintOnMouseActivityFlag = shouldRepaint;
  30677. }
  30678. void Component::repaintParent() throw()
  30679. {
  30680. if (flags.visibleFlag)
  30681. internalRepaint (0, 0, getWidth(), getHeight());
  30682. }
  30683. void Component::repaint() throw()
  30684. {
  30685. repaint (0, 0, getWidth(), getHeight());
  30686. }
  30687. void Component::repaint (const int x, const int y,
  30688. const int w, const int h) throw()
  30689. {
  30690. deleteAndZero (bufferedImage_);
  30691. if (flags.visibleFlag)
  30692. internalRepaint (x, y, w, h);
  30693. }
  30694. void Component::internalRepaint (int x, int y, int w, int h)
  30695. {
  30696. // if component methods are being called from threads other than the message
  30697. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  30698. checkMessageManagerIsLocked
  30699. if (x < 0)
  30700. {
  30701. w += x;
  30702. x = 0;
  30703. }
  30704. if (x + w > getWidth())
  30705. w = getWidth() - x;
  30706. if (w > 0)
  30707. {
  30708. if (y < 0)
  30709. {
  30710. h += y;
  30711. y = 0;
  30712. }
  30713. if (y + h > getHeight())
  30714. h = getHeight() - y;
  30715. if (h > 0)
  30716. {
  30717. if (parentComponent_ != 0)
  30718. {
  30719. x += getX();
  30720. y += getY();
  30721. if (parentComponent_->flags.visibleFlag)
  30722. parentComponent_->internalRepaint (x, y, w, h);
  30723. }
  30724. else if (flags.hasHeavyweightPeerFlag)
  30725. {
  30726. ComponentPeer* const peer = getPeer();
  30727. if (peer != 0)
  30728. peer->repaint (x, y, w, h);
  30729. }
  30730. }
  30731. }
  30732. }
  30733. void Component::paintEntireComponent (Graphics& originalContext)
  30734. {
  30735. jassert (! originalContext.isClipEmpty());
  30736. #ifdef JUCE_DEBUG
  30737. flags.isInsidePaintCall = true;
  30738. #endif
  30739. Graphics* g = &originalContext;
  30740. Image* effectImage = 0;
  30741. if (effect_ != 0)
  30742. {
  30743. effectImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  30744. getWidth(), getHeight(),
  30745. ! flags.opaqueFlag);
  30746. g = new Graphics (*effectImage);
  30747. }
  30748. g->saveState();
  30749. clipObscuredRegions (*g, g->getClipBounds(), 0, 0);
  30750. if (! g->isClipEmpty())
  30751. {
  30752. if (bufferedImage_ != 0)
  30753. {
  30754. g->setColour (Colours::black);
  30755. g->drawImageAt (bufferedImage_, 0, 0);
  30756. }
  30757. else
  30758. {
  30759. if (flags.bufferToImageFlag)
  30760. {
  30761. if (bufferedImage_ == 0)
  30762. {
  30763. bufferedImage_ = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  30764. getWidth(), getHeight(), ! flags.opaqueFlag);
  30765. Graphics imG (*bufferedImage_);
  30766. paint (imG);
  30767. }
  30768. g->setColour (Colours::black);
  30769. g->drawImageAt (bufferedImage_, 0, 0);
  30770. }
  30771. else
  30772. {
  30773. paint (*g);
  30774. g->resetToDefaultState();
  30775. }
  30776. }
  30777. }
  30778. g->restoreState();
  30779. for (int i = 0; i < childComponentList_.size(); ++i)
  30780. {
  30781. Component* const child = childComponentList_.getUnchecked (i);
  30782. if (child->isVisible())
  30783. {
  30784. g->saveState();
  30785. if (g->reduceClipRegion (child->getX(), child->getY(),
  30786. child->getWidth(), child->getHeight()))
  30787. {
  30788. for (int j = i + 1; j < childComponentList_.size(); ++j)
  30789. {
  30790. const Component* const sibling = childComponentList_.getUnchecked (j);
  30791. if (sibling->flags.opaqueFlag && sibling->isVisible())
  30792. g->excludeClipRegion (sibling->getX(), sibling->getY(),
  30793. sibling->getWidth(), sibling->getHeight());
  30794. }
  30795. if (! g->isClipEmpty())
  30796. {
  30797. g->setOrigin (child->getX(), child->getY());
  30798. child->paintEntireComponent (*g);
  30799. }
  30800. }
  30801. g->restoreState();
  30802. }
  30803. }
  30804. JUCE_TRY
  30805. {
  30806. g->saveState();
  30807. paintOverChildren (*g);
  30808. g->restoreState();
  30809. }
  30810. JUCE_CATCH_EXCEPTION
  30811. if (effect_ != 0)
  30812. {
  30813. delete g;
  30814. effect_->applyEffect (*effectImage, originalContext);
  30815. delete effectImage;
  30816. }
  30817. #ifdef JUCE_DEBUG
  30818. flags.isInsidePaintCall = false;
  30819. #endif
  30820. }
  30821. Image* Component::createComponentSnapshot (const Rectangle& areaToGrab,
  30822. const bool clipImageToComponentBounds)
  30823. {
  30824. Rectangle r (areaToGrab);
  30825. if (clipImageToComponentBounds)
  30826. r = r.getIntersection (Rectangle (0, 0, getWidth(), getHeight()));
  30827. Image* const componentImage = new Image (flags.opaqueFlag ? Image::RGB : Image::ARGB,
  30828. jmax (1, r.getWidth()),
  30829. jmax (1, r.getHeight()),
  30830. true);
  30831. Graphics imageContext (*componentImage);
  30832. imageContext.setOrigin (-r.getX(),
  30833. -r.getY());
  30834. paintEntireComponent (imageContext);
  30835. return componentImage;
  30836. }
  30837. void Component::setComponentEffect (ImageEffectFilter* const effect)
  30838. {
  30839. if (effect_ != effect)
  30840. {
  30841. effect_ = effect;
  30842. repaint();
  30843. }
  30844. }
  30845. LookAndFeel& Component::getLookAndFeel() const throw()
  30846. {
  30847. const Component* c = this;
  30848. do
  30849. {
  30850. if (c->lookAndFeel_ != 0)
  30851. return *(c->lookAndFeel_);
  30852. c = c->parentComponent_;
  30853. }
  30854. while (c != 0);
  30855. return LookAndFeel::getDefaultLookAndFeel();
  30856. }
  30857. void Component::setLookAndFeel (LookAndFeel* const newLookAndFeel)
  30858. {
  30859. if (lookAndFeel_ != newLookAndFeel)
  30860. {
  30861. lookAndFeel_ = newLookAndFeel;
  30862. sendLookAndFeelChange();
  30863. }
  30864. }
  30865. void Component::lookAndFeelChanged()
  30866. {
  30867. }
  30868. void Component::sendLookAndFeelChange()
  30869. {
  30870. repaint();
  30871. lookAndFeelChanged();
  30872. // (it's not a great idea to do anything that would delete this component
  30873. // during the lookAndFeelChanged() callback)
  30874. jassert (isValidComponent());
  30875. const ComponentDeletionWatcher deletionChecker (this);
  30876. for (int i = childComponentList_.size(); --i >= 0;)
  30877. {
  30878. childComponentList_.getUnchecked (i)->sendLookAndFeelChange();
  30879. if (deletionChecker.hasBeenDeleted())
  30880. return;
  30881. i = jmin (i, childComponentList_.size());
  30882. }
  30883. }
  30884. static const String getColourPropertyName (const int colourId) throw()
  30885. {
  30886. String s;
  30887. s.preallocateStorage (18);
  30888. s << T("jcclr_") << colourId;
  30889. return s;
  30890. }
  30891. const Colour Component::findColour (const int colourId, const bool inheritFromParent) const throw()
  30892. {
  30893. const String customColour (getComponentProperty (getColourPropertyName (colourId),
  30894. inheritFromParent,
  30895. String::empty));
  30896. if (customColour.isNotEmpty())
  30897. return Colour (customColour.getIntValue());
  30898. return getLookAndFeel().findColour (colourId);
  30899. }
  30900. bool Component::isColourSpecified (const int colourId) const throw()
  30901. {
  30902. return getComponentProperty (getColourPropertyName (colourId),
  30903. false,
  30904. String::empty).isNotEmpty();
  30905. }
  30906. void Component::removeColour (const int colourId)
  30907. {
  30908. if (isColourSpecified (colourId))
  30909. {
  30910. removeComponentProperty (getColourPropertyName (colourId));
  30911. colourChanged();
  30912. }
  30913. }
  30914. void Component::setColour (const int colourId, const Colour& colour)
  30915. {
  30916. const String colourName (getColourPropertyName (colourId));
  30917. const String customColour (getComponentProperty (colourName, false, String::empty));
  30918. if (customColour.isEmpty() || Colour (customColour.getIntValue()) != colour)
  30919. {
  30920. setComponentProperty (colourName, colour);
  30921. colourChanged();
  30922. }
  30923. }
  30924. void Component::copyAllExplicitColoursTo (Component& target) const throw()
  30925. {
  30926. if (propertySet_ != 0)
  30927. {
  30928. const StringPairArray& props = propertySet_->getAllProperties();
  30929. const StringArray& keys = props.getAllKeys();
  30930. for (int i = 0; i < keys.size(); ++i)
  30931. {
  30932. if (keys[i].startsWith (T("jcclr_")))
  30933. {
  30934. target.setComponentProperty (keys[i],
  30935. props.getAllValues() [i]);
  30936. }
  30937. }
  30938. target.colourChanged();
  30939. }
  30940. }
  30941. void Component::colourChanged()
  30942. {
  30943. }
  30944. const Rectangle Component::getUnclippedArea() const
  30945. {
  30946. int x = 0, y = 0, w = getWidth(), h = getHeight();
  30947. Component* p = parentComponent_;
  30948. int px = getX();
  30949. int py = getY();
  30950. while (p != 0)
  30951. {
  30952. if (! Rectangle::intersectRectangles (x, y, w, h, -px, -py, p->getWidth(), p->getHeight()))
  30953. return Rectangle();
  30954. px += p->getX();
  30955. py += p->getY();
  30956. p = p->parentComponent_;
  30957. }
  30958. return Rectangle (x, y, w, h);
  30959. }
  30960. void Component::clipObscuredRegions (Graphics& g, const Rectangle& clipRect,
  30961. const int deltaX, const int deltaY) const throw()
  30962. {
  30963. for (int i = childComponentList_.size(); --i >= 0;)
  30964. {
  30965. const Component* const c = childComponentList_.getUnchecked(i);
  30966. if (c->isVisible())
  30967. {
  30968. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  30969. if (! newClip.isEmpty())
  30970. {
  30971. if (c->isOpaque())
  30972. {
  30973. g.excludeClipRegion (deltaX + newClip.getX(),
  30974. deltaY + newClip.getY(),
  30975. newClip.getWidth(),
  30976. newClip.getHeight());
  30977. }
  30978. else
  30979. {
  30980. newClip.translate (-c->getX(), -c->getY());
  30981. c->clipObscuredRegions (g, newClip,
  30982. c->getX() + deltaX,
  30983. c->getY() + deltaY);
  30984. }
  30985. }
  30986. }
  30987. }
  30988. }
  30989. void Component::getVisibleArea (RectangleList& result,
  30990. const bool includeSiblings) const
  30991. {
  30992. result.clear();
  30993. const Rectangle unclipped (getUnclippedArea());
  30994. if (! unclipped.isEmpty())
  30995. {
  30996. result.add (unclipped);
  30997. if (includeSiblings)
  30998. {
  30999. const Component* const c = getTopLevelComponent();
  31000. int x = 0, y = 0;
  31001. c->relativePositionToOtherComponent (this, x, y);
  31002. c->subtractObscuredRegions (result, x, y,
  31003. Rectangle (0, 0, c->getWidth(), c->getHeight()),
  31004. this);
  31005. }
  31006. subtractObscuredRegions (result, 0, 0, unclipped, 0);
  31007. result.consolidate();
  31008. }
  31009. }
  31010. void Component::subtractObscuredRegions (RectangleList& result,
  31011. const int deltaX,
  31012. const int deltaY,
  31013. const Rectangle& clipRect,
  31014. const Component* const compToAvoid) const throw()
  31015. {
  31016. for (int i = childComponentList_.size(); --i >= 0;)
  31017. {
  31018. const Component* const c = childComponentList_.getUnchecked(i);
  31019. if (c != compToAvoid && c->isVisible())
  31020. {
  31021. if (c->isOpaque())
  31022. {
  31023. Rectangle childBounds (c->bounds_.getIntersection (clipRect));
  31024. childBounds.translate (deltaX, deltaY);
  31025. result.subtract (childBounds);
  31026. }
  31027. else
  31028. {
  31029. Rectangle newClip (clipRect.getIntersection (c->bounds_));
  31030. newClip.translate (-c->getX(), -c->getY());
  31031. c->subtractObscuredRegions (result,
  31032. c->getX() + deltaX,
  31033. c->getY() + deltaY,
  31034. newClip,
  31035. compToAvoid);
  31036. }
  31037. }
  31038. }
  31039. }
  31040. void Component::mouseEnter (const MouseEvent&)
  31041. {
  31042. // base class does nothing
  31043. }
  31044. void Component::mouseExit (const MouseEvent&)
  31045. {
  31046. // base class does nothing
  31047. }
  31048. void Component::mouseDown (const MouseEvent&)
  31049. {
  31050. // base class does nothing
  31051. }
  31052. void Component::mouseUp (const MouseEvent&)
  31053. {
  31054. // base class does nothing
  31055. }
  31056. void Component::mouseDrag (const MouseEvent&)
  31057. {
  31058. // base class does nothing
  31059. }
  31060. void Component::mouseMove (const MouseEvent&)
  31061. {
  31062. // base class does nothing
  31063. }
  31064. void Component::mouseDoubleClick (const MouseEvent&)
  31065. {
  31066. // base class does nothing
  31067. }
  31068. void Component::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  31069. {
  31070. // the base class just passes this event up to its parent..
  31071. if (parentComponent_ != 0)
  31072. parentComponent_->mouseWheelMove (e.getEventRelativeTo (parentComponent_),
  31073. wheelIncrementX, wheelIncrementY);
  31074. }
  31075. void Component::resized()
  31076. {
  31077. // base class does nothing
  31078. }
  31079. void Component::moved()
  31080. {
  31081. // base class does nothing
  31082. }
  31083. void Component::childBoundsChanged (Component*)
  31084. {
  31085. // base class does nothing
  31086. }
  31087. void Component::parentSizeChanged()
  31088. {
  31089. // base class does nothing
  31090. }
  31091. void Component::addComponentListener (ComponentListener* const newListener) throw()
  31092. {
  31093. if (componentListeners_ == 0)
  31094. componentListeners_ = new VoidArray (4);
  31095. componentListeners_->addIfNotAlreadyThere (newListener);
  31096. }
  31097. void Component::removeComponentListener (ComponentListener* const listenerToRemove) throw()
  31098. {
  31099. jassert (isValidComponent());
  31100. if (componentListeners_ != 0)
  31101. componentListeners_->removeValue (listenerToRemove);
  31102. }
  31103. void Component::inputAttemptWhenModal()
  31104. {
  31105. getTopLevelComponent()->toFront (true);
  31106. getLookAndFeel().playAlertSound();
  31107. }
  31108. bool Component::canModalEventBeSentToComponent (const Component*)
  31109. {
  31110. return false;
  31111. }
  31112. void Component::internalModalInputAttempt()
  31113. {
  31114. Component* const current = getCurrentlyModalComponent();
  31115. if (current != 0)
  31116. current->inputAttemptWhenModal();
  31117. }
  31118. void Component::paint (Graphics&)
  31119. {
  31120. // all painting is done in the subclasses
  31121. jassert (! isOpaque()); // if your component's opaque, you've gotta paint it!
  31122. }
  31123. void Component::paintOverChildren (Graphics&)
  31124. {
  31125. // all painting is done in the subclasses
  31126. }
  31127. void Component::handleMessage (const Message& message)
  31128. {
  31129. if (message.intParameter1 == exitModalStateMessage)
  31130. {
  31131. exitModalState (message.intParameter2);
  31132. }
  31133. else if (message.intParameter1 == customCommandMessage)
  31134. {
  31135. handleCommandMessage (message.intParameter2);
  31136. }
  31137. }
  31138. void Component::postCommandMessage (const int commandId) throw()
  31139. {
  31140. postMessage (new Message (customCommandMessage, commandId, 0, 0));
  31141. }
  31142. void Component::handleCommandMessage (int)
  31143. {
  31144. // used by subclasses
  31145. }
  31146. void Component::addMouseListener (MouseListener* const newListener,
  31147. const bool wantsEventsForAllNestedChildComponents) throw()
  31148. {
  31149. // if component methods are being called from threads other than the message
  31150. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31151. checkMessageManagerIsLocked
  31152. if (mouseListeners_ == 0)
  31153. mouseListeners_ = new VoidArray (4);
  31154. if (! mouseListeners_->contains (newListener))
  31155. {
  31156. if (wantsEventsForAllNestedChildComponents)
  31157. {
  31158. mouseListeners_->insert (0, newListener);
  31159. ++numDeepMouseListeners;
  31160. }
  31161. else
  31162. {
  31163. mouseListeners_->add (newListener);
  31164. }
  31165. }
  31166. }
  31167. void Component::removeMouseListener (MouseListener* const listenerToRemove) throw()
  31168. {
  31169. // if component methods are being called from threads other than the message
  31170. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  31171. checkMessageManagerIsLocked
  31172. if (mouseListeners_ != 0)
  31173. {
  31174. const int index = mouseListeners_->indexOf (listenerToRemove);
  31175. if (index >= 0)
  31176. {
  31177. if (index < numDeepMouseListeners)
  31178. --numDeepMouseListeners;
  31179. mouseListeners_->remove (index);
  31180. }
  31181. }
  31182. }
  31183. void Component::internalMouseEnter (int x, int y, int64 time)
  31184. {
  31185. if (isCurrentlyBlockedByAnotherModalComponent())
  31186. {
  31187. // if something else is modal, always just show a normal mouse cursor
  31188. if (componentUnderMouse == this)
  31189. {
  31190. ComponentPeer* const peer = getPeer();
  31191. if (peer != 0)
  31192. {
  31193. MouseCursor mc (MouseCursor::NormalCursor);
  31194. mc.showInWindow (peer);
  31195. }
  31196. }
  31197. return;
  31198. }
  31199. if (! flags.mouseInsideFlag)
  31200. {
  31201. flags.mouseInsideFlag = true;
  31202. flags.mouseOverFlag = true;
  31203. flags.draggingFlag = false;
  31204. if (isValidComponent())
  31205. {
  31206. const ComponentDeletionWatcher deletionChecker (this);
  31207. if (flags.repaintOnMouseActivityFlag)
  31208. repaint();
  31209. const MouseEvent me (x, y,
  31210. ModifierKeys::getCurrentModifiers(),
  31211. this,
  31212. Time (time),
  31213. x, y,
  31214. Time (time),
  31215. 0, false);
  31216. mouseEnter (me);
  31217. if (deletionChecker.hasBeenDeleted())
  31218. return;
  31219. Desktop::getInstance().resetTimer();
  31220. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  31221. {
  31222. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseEnter (me);
  31223. if (deletionChecker.hasBeenDeleted())
  31224. return;
  31225. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  31226. }
  31227. if (mouseListeners_ != 0)
  31228. {
  31229. for (int i = mouseListeners_->size(); --i >= 0;)
  31230. {
  31231. ((MouseListener*) mouseListeners_->getUnchecked(i))->mouseEnter (me);
  31232. if (deletionChecker.hasBeenDeleted())
  31233. return;
  31234. i = jmin (i, mouseListeners_->size());
  31235. }
  31236. }
  31237. const Component* p = parentComponent_;
  31238. while (p != 0)
  31239. {
  31240. const ComponentDeletionWatcher parentDeletionChecker (p);
  31241. for (int i = p->numDeepMouseListeners; --i >= 0;)
  31242. {
  31243. ((MouseListener*) (p->mouseListeners_->getUnchecked(i)))->mouseEnter (me);
  31244. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  31245. return;
  31246. i = jmin (i, p->numDeepMouseListeners);
  31247. }
  31248. p = p->parentComponent_;
  31249. }
  31250. }
  31251. }
  31252. if (componentUnderMouse == this)
  31253. internalUpdateMouseCursor (true);
  31254. }
  31255. void Component::internalMouseExit (int x, int y, int64 time)
  31256. {
  31257. const ComponentDeletionWatcher deletionChecker (this);
  31258. if (flags.draggingFlag)
  31259. {
  31260. internalMouseUp (ModifierKeys::getCurrentModifiers().getRawFlags(), x, y, time);
  31261. if (deletionChecker.hasBeenDeleted())
  31262. return;
  31263. }
  31264. enableUnboundedMouseMovement (false);
  31265. if (flags.mouseInsideFlag || flags.mouseOverFlag)
  31266. {
  31267. flags.mouseInsideFlag = false;
  31268. flags.mouseOverFlag = false;
  31269. flags.draggingFlag = false;
  31270. if (flags.repaintOnMouseActivityFlag)
  31271. repaint();
  31272. const MouseEvent me (x, y,
  31273. ModifierKeys::getCurrentModifiers(),
  31274. this,
  31275. Time (time),
  31276. x, y,
  31277. Time (time),
  31278. 0, false);
  31279. mouseExit (me);
  31280. if (deletionChecker.hasBeenDeleted())
  31281. return;
  31282. Desktop::getInstance().resetTimer();
  31283. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  31284. {
  31285. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseExit (me);
  31286. if (deletionChecker.hasBeenDeleted())
  31287. return;
  31288. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  31289. }
  31290. if (mouseListeners_ != 0)
  31291. {
  31292. for (int i = mouseListeners_->size(); --i >= 0;)
  31293. {
  31294. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseExit (me);
  31295. if (deletionChecker.hasBeenDeleted())
  31296. return;
  31297. i = jmin (i, mouseListeners_->size());
  31298. }
  31299. }
  31300. const Component* p = parentComponent_;
  31301. while (p != 0)
  31302. {
  31303. const ComponentDeletionWatcher parentDeletionChecker (p);
  31304. for (int i = p->numDeepMouseListeners; --i >= 0;)
  31305. {
  31306. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseExit (me);
  31307. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  31308. return;
  31309. i = jmin (i, p->numDeepMouseListeners);
  31310. }
  31311. p = p->parentComponent_;
  31312. }
  31313. }
  31314. }
  31315. class InternalDragRepeater : public Timer
  31316. {
  31317. public:
  31318. InternalDragRepeater()
  31319. {}
  31320. ~InternalDragRepeater()
  31321. {}
  31322. void timerCallback()
  31323. {
  31324. Component* const c = Component::getComponentUnderMouse();
  31325. if (c != 0 && c->isMouseButtonDown())
  31326. {
  31327. int x, y;
  31328. c->getMouseXYRelative (x, y);
  31329. // the offsets have been added on, so must be taken off before calling the
  31330. // drag.. otherwise they'll be added twice
  31331. x -= unboundedMouseOffsetX;
  31332. y -= unboundedMouseOffsetY;
  31333. c->internalMouseDrag (x, y, Time::currentTimeMillis());
  31334. }
  31335. }
  31336. juce_UseDebuggingNewOperator
  31337. };
  31338. static InternalDragRepeater* dragRepeater = 0;
  31339. void Component::beginDragAutoRepeat (const int interval)
  31340. {
  31341. if (interval > 0)
  31342. {
  31343. if (dragRepeater == 0)
  31344. dragRepeater = new InternalDragRepeater();
  31345. if (dragRepeater->getTimerInterval() != interval)
  31346. dragRepeater->startTimer (interval);
  31347. }
  31348. else
  31349. {
  31350. deleteAndZero (dragRepeater);
  31351. }
  31352. }
  31353. void Component::internalMouseDown (const int x, const int y)
  31354. {
  31355. const ComponentDeletionWatcher deletionChecker (this);
  31356. if (isCurrentlyBlockedByAnotherModalComponent())
  31357. {
  31358. internalModalInputAttempt();
  31359. if (deletionChecker.hasBeenDeleted())
  31360. return;
  31361. // If processing the input attempt has exited the modal loop, we'll allow the event
  31362. // to be delivered..
  31363. if (isCurrentlyBlockedByAnotherModalComponent())
  31364. {
  31365. // allow blocked mouse-events to go to global listeners..
  31366. const MouseEvent me (x, y,
  31367. ModifierKeys::getCurrentModifiers(),
  31368. this,
  31369. Time (juce_recentMouseDownTimes[0]),
  31370. x, y,
  31371. Time (juce_recentMouseDownTimes[0]),
  31372. countMouseClicks(),
  31373. false);
  31374. Desktop::getInstance().resetTimer();
  31375. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  31376. {
  31377. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  31378. if (deletionChecker.hasBeenDeleted())
  31379. return;
  31380. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  31381. }
  31382. return;
  31383. }
  31384. }
  31385. {
  31386. Component* c = this;
  31387. while (c != 0)
  31388. {
  31389. if (c->isBroughtToFrontOnMouseClick())
  31390. {
  31391. c->toFront (true);
  31392. if (deletionChecker.hasBeenDeleted())
  31393. return;
  31394. }
  31395. c = c->parentComponent_;
  31396. }
  31397. }
  31398. if (! flags.dontFocusOnMouseClickFlag)
  31399. grabFocusInternal (focusChangedByMouseClick);
  31400. if (! deletionChecker.hasBeenDeleted())
  31401. {
  31402. flags.draggingFlag = true;
  31403. flags.mouseOverFlag = true;
  31404. if (flags.repaintOnMouseActivityFlag)
  31405. repaint();
  31406. const MouseEvent me (x, y,
  31407. ModifierKeys::getCurrentModifiers(),
  31408. this,
  31409. Time (juce_recentMouseDownTimes[0]),
  31410. x, y,
  31411. Time (juce_recentMouseDownTimes[0]),
  31412. countMouseClicks(),
  31413. false);
  31414. mouseDown (me);
  31415. if (deletionChecker.hasBeenDeleted())
  31416. return;
  31417. Desktop::getInstance().resetTimer();
  31418. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  31419. {
  31420. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDown (me);
  31421. if (deletionChecker.hasBeenDeleted())
  31422. return;
  31423. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  31424. }
  31425. if (mouseListeners_ != 0)
  31426. {
  31427. for (int i = mouseListeners_->size(); --i >= 0;)
  31428. {
  31429. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDown (me);
  31430. if (deletionChecker.hasBeenDeleted())
  31431. return;
  31432. i = jmin (i, mouseListeners_->size());
  31433. }
  31434. }
  31435. const Component* p = parentComponent_;
  31436. while (p != 0)
  31437. {
  31438. const ComponentDeletionWatcher parentDeletionChecker (p);
  31439. for (int i = p->numDeepMouseListeners; --i >= 0;)
  31440. {
  31441. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDown (me);
  31442. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  31443. return;
  31444. i = jmin (i, p->numDeepMouseListeners);
  31445. }
  31446. p = p->parentComponent_;
  31447. }
  31448. }
  31449. }
  31450. void Component::internalMouseUp (const int oldModifiers, int x, int y, const int64 time)
  31451. {
  31452. if (isValidComponent() && flags.draggingFlag)
  31453. {
  31454. flags.draggingFlag = false;
  31455. deleteAndZero (dragRepeater);
  31456. x += unboundedMouseOffsetX;
  31457. y += unboundedMouseOffsetY;
  31458. juce_LastMousePosX = x;
  31459. juce_LastMousePosY = y;
  31460. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  31461. const ComponentDeletionWatcher deletionChecker (this);
  31462. if (flags.repaintOnMouseActivityFlag)
  31463. repaint();
  31464. int mdx = juce_recentMouseDownX[0];
  31465. int mdy = juce_recentMouseDownY[0];
  31466. globalPositionToRelative (mdx, mdy);
  31467. const MouseEvent me (x, y,
  31468. oldModifiers,
  31469. this,
  31470. Time (time),
  31471. mdx, mdy,
  31472. Time (juce_recentMouseDownTimes [0]),
  31473. countMouseClicks(),
  31474. juce_MouseHasMovedSignificantlySincePressed
  31475. || juce_recentMouseDownTimes[0] + 300 < time);
  31476. mouseUp (me);
  31477. if (deletionChecker.hasBeenDeleted())
  31478. return;
  31479. Desktop::getInstance().resetTimer();
  31480. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  31481. {
  31482. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseUp (me);
  31483. if (deletionChecker.hasBeenDeleted())
  31484. return;
  31485. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  31486. }
  31487. if (mouseListeners_ != 0)
  31488. {
  31489. for (int i = mouseListeners_->size(); --i >= 0;)
  31490. {
  31491. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseUp (me);
  31492. if (deletionChecker.hasBeenDeleted())
  31493. return;
  31494. i = jmin (i, mouseListeners_->size());
  31495. }
  31496. }
  31497. {
  31498. const Component* p = parentComponent_;
  31499. while (p != 0)
  31500. {
  31501. const ComponentDeletionWatcher parentDeletionChecker (p);
  31502. for (int i = p->numDeepMouseListeners; --i >= 0;)
  31503. {
  31504. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseUp (me);
  31505. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  31506. return;
  31507. i = jmin (i, p->numDeepMouseListeners);
  31508. }
  31509. p = p->parentComponent_;
  31510. }
  31511. }
  31512. // check for double-click
  31513. if (me.getNumberOfClicks() >= 2)
  31514. {
  31515. const int numListeners = (mouseListeners_ != 0) ? mouseListeners_->size() : 0;
  31516. mouseDoubleClick (me);
  31517. int i;
  31518. for (i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  31519. {
  31520. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDoubleClick (me);
  31521. if (deletionChecker.hasBeenDeleted())
  31522. return;
  31523. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  31524. }
  31525. for (i = numListeners; --i >= 0;)
  31526. {
  31527. if (deletionChecker.hasBeenDeleted() || mouseListeners_ == 0)
  31528. return;
  31529. MouseListener* const ml = (MouseListener*)((*mouseListeners_)[i]);
  31530. if (ml != 0)
  31531. ml->mouseDoubleClick (me);
  31532. }
  31533. if (deletionChecker.hasBeenDeleted())
  31534. return;
  31535. const Component* p = parentComponent_;
  31536. while (p != 0)
  31537. {
  31538. const ComponentDeletionWatcher parentDeletionChecker (p);
  31539. for (i = p->numDeepMouseListeners; --i >= 0;)
  31540. {
  31541. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDoubleClick (me);
  31542. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  31543. return;
  31544. i = jmin (i, p->numDeepMouseListeners);
  31545. }
  31546. p = p->parentComponent_;
  31547. }
  31548. }
  31549. }
  31550. enableUnboundedMouseMovement (false);
  31551. }
  31552. void Component::internalMouseDrag (int x, int y, const int64 time)
  31553. {
  31554. if (isValidComponent() && flags.draggingFlag)
  31555. {
  31556. flags.mouseOverFlag = reallyContains (x, y, false);
  31557. x += unboundedMouseOffsetX;
  31558. y += unboundedMouseOffsetY;
  31559. juce_LastMousePosX = x;
  31560. juce_LastMousePosY = y;
  31561. relativePositionToGlobal (juce_LastMousePosX, juce_LastMousePosY);
  31562. juce_MouseHasMovedSignificantlySincePressed
  31563. = juce_MouseHasMovedSignificantlySincePressed
  31564. || abs (juce_recentMouseDownX[0] - juce_LastMousePosX) >= 4
  31565. || abs (juce_recentMouseDownY[0] - juce_LastMousePosY) >= 4;
  31566. const ComponentDeletionWatcher deletionChecker (this);
  31567. int mdx = juce_recentMouseDownX[0];
  31568. int mdy = juce_recentMouseDownY[0];
  31569. globalPositionToRelative (mdx, mdy);
  31570. const MouseEvent me (x, y,
  31571. ModifierKeys::getCurrentModifiers(),
  31572. this,
  31573. Time (time),
  31574. mdx, mdy,
  31575. Time (juce_recentMouseDownTimes[0]),
  31576. countMouseClicks(),
  31577. juce_MouseHasMovedSignificantlySincePressed
  31578. || juce_recentMouseDownTimes[0] + 300 < time);
  31579. mouseDrag (me);
  31580. if (deletionChecker.hasBeenDeleted())
  31581. return;
  31582. Desktop::getInstance().resetTimer();
  31583. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  31584. {
  31585. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseDrag (me);
  31586. if (deletionChecker.hasBeenDeleted())
  31587. return;
  31588. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  31589. }
  31590. if (mouseListeners_ != 0)
  31591. {
  31592. for (int i = mouseListeners_->size(); --i >= 0;)
  31593. {
  31594. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseDrag (me);
  31595. if (deletionChecker.hasBeenDeleted())
  31596. return;
  31597. i = jmin (i, mouseListeners_->size());
  31598. }
  31599. }
  31600. const Component* p = parentComponent_;
  31601. while (p != 0)
  31602. {
  31603. const ComponentDeletionWatcher parentDeletionChecker (p);
  31604. for (int i = p->numDeepMouseListeners; --i >= 0;)
  31605. {
  31606. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseDrag (me);
  31607. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  31608. return;
  31609. i = jmin (i, p->numDeepMouseListeners);
  31610. }
  31611. p = p->parentComponent_;
  31612. }
  31613. if (this == componentUnderMouse)
  31614. {
  31615. if (isUnboundedMouseModeOn)
  31616. {
  31617. Rectangle screenArea (getParentMonitorArea().expanded (-2, -2));
  31618. int mx, my;
  31619. Desktop::getMousePosition (mx, my);
  31620. if (! screenArea.contains (mx, my))
  31621. {
  31622. int deltaX = 0, deltaY = 0;
  31623. if (mx <= screenArea.getX() || mx >= screenArea.getRight())
  31624. deltaX = getScreenX() + getWidth() / 2 - mx;
  31625. if (my <= screenArea.getY() || my >= screenArea.getBottom())
  31626. deltaY = getScreenY() + getHeight() / 2 - my;
  31627. unboundedMouseOffsetX -= deltaX;
  31628. unboundedMouseOffsetY -= deltaY;
  31629. Desktop::setMousePosition (mx + deltaX,
  31630. my + deltaY);
  31631. }
  31632. else if (isCursorVisibleUntilOffscreen
  31633. && (unboundedMouseOffsetX != 0 || unboundedMouseOffsetY != 0)
  31634. && screenArea.contains (mx + unboundedMouseOffsetX,
  31635. my + unboundedMouseOffsetY))
  31636. {
  31637. mx += unboundedMouseOffsetX;
  31638. my += unboundedMouseOffsetY;
  31639. unboundedMouseOffsetX = 0;
  31640. unboundedMouseOffsetY = 0;
  31641. Desktop::setMousePosition (mx, my);
  31642. }
  31643. }
  31644. internalUpdateMouseCursor (false);
  31645. }
  31646. }
  31647. }
  31648. void Component::internalMouseMove (const int x, const int y, const int64 time)
  31649. {
  31650. const ComponentDeletionWatcher deletionChecker (this);
  31651. if (isValidComponent())
  31652. {
  31653. const MouseEvent me (x, y,
  31654. ModifierKeys::getCurrentModifiers(),
  31655. this,
  31656. Time (time),
  31657. x, y,
  31658. Time (time),
  31659. 0, false);
  31660. if (isCurrentlyBlockedByAnotherModalComponent())
  31661. {
  31662. // allow blocked mouse-events to go to global listeners..
  31663. Desktop::getInstance().sendMouseMove();
  31664. }
  31665. else
  31666. {
  31667. if (this == componentUnderMouse)
  31668. internalUpdateMouseCursor (false);
  31669. flags.mouseOverFlag = true;
  31670. mouseMove (me);
  31671. if (deletionChecker.hasBeenDeleted())
  31672. return;
  31673. Desktop::getInstance().resetTimer();
  31674. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  31675. {
  31676. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseMove (me);
  31677. if (deletionChecker.hasBeenDeleted())
  31678. return;
  31679. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  31680. }
  31681. if (mouseListeners_ != 0)
  31682. {
  31683. for (int i = mouseListeners_->size(); --i >= 0;)
  31684. {
  31685. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseMove (me);
  31686. if (deletionChecker.hasBeenDeleted())
  31687. return;
  31688. i = jmin (i, mouseListeners_->size());
  31689. }
  31690. }
  31691. const Component* p = parentComponent_;
  31692. while (p != 0)
  31693. {
  31694. const ComponentDeletionWatcher parentDeletionChecker (p);
  31695. for (int i = p->numDeepMouseListeners; --i >= 0;)
  31696. {
  31697. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseMove (me);
  31698. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  31699. return;
  31700. i = jmin (i, p->numDeepMouseListeners);
  31701. }
  31702. p = p->parentComponent_;
  31703. }
  31704. }
  31705. }
  31706. }
  31707. void Component::internalMouseWheel (const int intAmountX, const int intAmountY, const int64 time)
  31708. {
  31709. const ComponentDeletionWatcher deletionChecker (this);
  31710. const float wheelIncrementX = intAmountX * (1.0f / 256.0f);
  31711. const float wheelIncrementY = intAmountY * (1.0f / 256.0f);
  31712. int mx, my;
  31713. getMouseXYRelative (mx, my);
  31714. const MouseEvent me (mx, my,
  31715. ModifierKeys::getCurrentModifiers(),
  31716. this,
  31717. Time (time),
  31718. mx, my,
  31719. Time (time),
  31720. 0, false);
  31721. if (isCurrentlyBlockedByAnotherModalComponent())
  31722. {
  31723. // allow blocked mouse-events to go to global listeners..
  31724. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  31725. {
  31726. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  31727. if (deletionChecker.hasBeenDeleted())
  31728. return;
  31729. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  31730. }
  31731. }
  31732. else
  31733. {
  31734. mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  31735. if (deletionChecker.hasBeenDeleted())
  31736. return;
  31737. for (int i = Desktop::getInstance().mouseListeners.size(); --i >= 0;)
  31738. {
  31739. ((MouseListener*) Desktop::getInstance().mouseListeners[i])->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  31740. if (deletionChecker.hasBeenDeleted())
  31741. return;
  31742. i = jmin (i, Desktop::getInstance().mouseListeners.size());
  31743. }
  31744. if (mouseListeners_ != 0)
  31745. {
  31746. for (int i = mouseListeners_->size(); --i >= 0;)
  31747. {
  31748. ((MouseListener*) mouseListeners_->getUnchecked (i))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  31749. if (deletionChecker.hasBeenDeleted())
  31750. return;
  31751. i = jmin (i, mouseListeners_->size());
  31752. }
  31753. }
  31754. const Component* p = parentComponent_;
  31755. while (p != 0)
  31756. {
  31757. const ComponentDeletionWatcher parentDeletionChecker (p);
  31758. for (int i = p->numDeepMouseListeners; --i >= 0;)
  31759. {
  31760. ((MouseListener*) (p->mouseListeners_->getUnchecked (i)))->mouseWheelMove (me, wheelIncrementX, wheelIncrementY);
  31761. if (deletionChecker.hasBeenDeleted() || parentDeletionChecker.hasBeenDeleted())
  31762. return;
  31763. i = jmin (i, p->numDeepMouseListeners);
  31764. }
  31765. p = p->parentComponent_;
  31766. }
  31767. sendFakeMouseMove();
  31768. }
  31769. }
  31770. void Component::sendFakeMouseMove() const
  31771. {
  31772. ComponentPeer* const peer = getPeer();
  31773. if (peer != 0)
  31774. peer->sendFakeMouseMove();
  31775. }
  31776. void Component::broughtToFront()
  31777. {
  31778. }
  31779. void Component::internalBroughtToFront()
  31780. {
  31781. if (isValidComponent())
  31782. {
  31783. if (flags.hasHeavyweightPeerFlag)
  31784. Desktop::getInstance().componentBroughtToFront (this);
  31785. const ComponentDeletionWatcher deletionChecker (this);
  31786. broughtToFront();
  31787. if (deletionChecker.hasBeenDeleted())
  31788. return;
  31789. if (componentListeners_ != 0)
  31790. {
  31791. for (int i = componentListeners_->size(); --i >= 0;)
  31792. {
  31793. ((ComponentListener*) componentListeners_->getUnchecked (i))
  31794. ->componentBroughtToFront (*this);
  31795. if (deletionChecker.hasBeenDeleted())
  31796. return;
  31797. i = jmin (i, componentListeners_->size());
  31798. }
  31799. }
  31800. // when brought to the front and there's a modal component blocking this one,
  31801. // we need to bring the modal one to the front instead..
  31802. Component* const cm = getCurrentlyModalComponent();
  31803. if (cm != 0 && cm->getTopLevelComponent() != getTopLevelComponent())
  31804. {
  31805. cm->getTopLevelComponent()->toFront (true);
  31806. }
  31807. }
  31808. }
  31809. void Component::focusGained (FocusChangeType)
  31810. {
  31811. // base class does nothing
  31812. }
  31813. void Component::internalFocusGain (const FocusChangeType cause)
  31814. {
  31815. const ComponentDeletionWatcher deletionChecker (this);
  31816. focusGained (cause);
  31817. if (! deletionChecker.hasBeenDeleted())
  31818. internalChildFocusChange (cause);
  31819. }
  31820. void Component::focusLost (FocusChangeType)
  31821. {
  31822. // base class does nothing
  31823. }
  31824. void Component::internalFocusLoss (const FocusChangeType cause)
  31825. {
  31826. const ComponentDeletionWatcher deletionChecker (this);
  31827. focusLost (focusChangedDirectly);
  31828. if (! deletionChecker.hasBeenDeleted())
  31829. internalChildFocusChange (cause);
  31830. }
  31831. void Component::focusOfChildComponentChanged (FocusChangeType /*cause*/)
  31832. {
  31833. // base class does nothing
  31834. }
  31835. void Component::internalChildFocusChange (FocusChangeType cause)
  31836. {
  31837. const bool childIsNowFocused = hasKeyboardFocus (true);
  31838. if (flags.childCompFocusedFlag != childIsNowFocused)
  31839. {
  31840. flags.childCompFocusedFlag = childIsNowFocused;
  31841. const ComponentDeletionWatcher deletionChecker (this);
  31842. focusOfChildComponentChanged (cause);
  31843. if (deletionChecker.hasBeenDeleted())
  31844. return;
  31845. }
  31846. if (parentComponent_ != 0)
  31847. parentComponent_->internalChildFocusChange (cause);
  31848. }
  31849. bool Component::isEnabled() const throw()
  31850. {
  31851. return (! flags.isDisabledFlag)
  31852. && (parentComponent_ == 0 || parentComponent_->isEnabled());
  31853. }
  31854. void Component::setEnabled (const bool shouldBeEnabled)
  31855. {
  31856. if (flags.isDisabledFlag == shouldBeEnabled)
  31857. {
  31858. flags.isDisabledFlag = ! shouldBeEnabled;
  31859. // if any parent components are disabled, setting our flag won't make a difference,
  31860. // so no need to send a change message
  31861. if (parentComponent_ == 0 || parentComponent_->isEnabled())
  31862. sendEnablementChangeMessage();
  31863. }
  31864. }
  31865. void Component::sendEnablementChangeMessage()
  31866. {
  31867. const ComponentDeletionWatcher deletionChecker (this);
  31868. enablementChanged();
  31869. if (deletionChecker.hasBeenDeleted())
  31870. return;
  31871. for (int i = getNumChildComponents(); --i >= 0;)
  31872. {
  31873. Component* const c = getChildComponent (i);
  31874. if (c != 0)
  31875. {
  31876. c->sendEnablementChangeMessage();
  31877. if (deletionChecker.hasBeenDeleted())
  31878. return;
  31879. }
  31880. }
  31881. }
  31882. void Component::enablementChanged()
  31883. {
  31884. }
  31885. void Component::setWantsKeyboardFocus (const bool wantsFocus) throw()
  31886. {
  31887. flags.wantsFocusFlag = wantsFocus;
  31888. }
  31889. void Component::setMouseClickGrabsKeyboardFocus (const bool shouldGrabFocus)
  31890. {
  31891. flags.dontFocusOnMouseClickFlag = ! shouldGrabFocus;
  31892. }
  31893. bool Component::getMouseClickGrabsKeyboardFocus() const throw()
  31894. {
  31895. return ! flags.dontFocusOnMouseClickFlag;
  31896. }
  31897. bool Component::getWantsKeyboardFocus() const throw()
  31898. {
  31899. return flags.wantsFocusFlag && ! flags.isDisabledFlag;
  31900. }
  31901. void Component::setFocusContainer (const bool isFocusContainer) throw()
  31902. {
  31903. flags.isFocusContainerFlag = isFocusContainer;
  31904. }
  31905. bool Component::isFocusContainer() const throw()
  31906. {
  31907. return flags.isFocusContainerFlag;
  31908. }
  31909. int Component::getExplicitFocusOrder() const throw()
  31910. {
  31911. return getComponentPropertyInt (T("_jexfo"), false, 0);
  31912. }
  31913. void Component::setExplicitFocusOrder (const int newFocusOrderIndex) throw()
  31914. {
  31915. setComponentProperty (T("_jexfo"), newFocusOrderIndex);
  31916. }
  31917. KeyboardFocusTraverser* Component::createFocusTraverser()
  31918. {
  31919. if (flags.isFocusContainerFlag || parentComponent_ == 0)
  31920. return new KeyboardFocusTraverser();
  31921. return parentComponent_->createFocusTraverser();
  31922. }
  31923. void Component::takeKeyboardFocus (const FocusChangeType cause)
  31924. {
  31925. // give the focus to this component
  31926. if (currentlyFocusedComponent != this)
  31927. {
  31928. JUCE_TRY
  31929. {
  31930. // get the focus onto our desktop window
  31931. ComponentPeer* const peer = getPeer();
  31932. if (peer != 0)
  31933. {
  31934. const ComponentDeletionWatcher deletionChecker (this);
  31935. peer->grabFocus();
  31936. if (peer->isFocused() && currentlyFocusedComponent != this)
  31937. {
  31938. Component* const componentLosingFocus = currentlyFocusedComponent;
  31939. currentlyFocusedComponent = this;
  31940. Desktop::getInstance().triggerFocusCallback();
  31941. // call this after setting currentlyFocusedComponent so that the one that's
  31942. // losing it has a chance to see where focus is going
  31943. if (componentLosingFocus->isValidComponent())
  31944. componentLosingFocus->internalFocusLoss (cause);
  31945. if (currentlyFocusedComponent == this)
  31946. {
  31947. focusGained (cause);
  31948. if (! deletionChecker.hasBeenDeleted())
  31949. internalChildFocusChange (cause);
  31950. }
  31951. }
  31952. }
  31953. }
  31954. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  31955. catch (const std::exception& e)
  31956. {
  31957. currentlyFocusedComponent = 0;
  31958. Desktop::getInstance().triggerFocusCallback();
  31959. JUCEApplication::sendUnhandledException (&e, __FILE__, __LINE__);
  31960. }
  31961. catch (...)
  31962. {
  31963. currentlyFocusedComponent = 0;
  31964. Desktop::getInstance().triggerFocusCallback();
  31965. JUCEApplication::sendUnhandledException (0, __FILE__, __LINE__);
  31966. }
  31967. #endif
  31968. }
  31969. }
  31970. void Component::grabFocusInternal (const FocusChangeType cause, const bool canTryParent)
  31971. {
  31972. if (isShowing())
  31973. {
  31974. if (flags.wantsFocusFlag && (isEnabled() || parentComponent_ == 0))
  31975. {
  31976. takeKeyboardFocus (cause);
  31977. }
  31978. else
  31979. {
  31980. if (isParentOf (currentlyFocusedComponent)
  31981. && currentlyFocusedComponent->isShowing())
  31982. {
  31983. // do nothing if the focused component is actually a child of ours..
  31984. }
  31985. else
  31986. {
  31987. // find the default child component..
  31988. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  31989. if (traverser != 0)
  31990. {
  31991. Component* const defaultComp = traverser->getDefaultComponent (this);
  31992. delete traverser;
  31993. if (defaultComp != 0)
  31994. {
  31995. defaultComp->grabFocusInternal (cause, false);
  31996. return;
  31997. }
  31998. }
  31999. if (canTryParent && parentComponent_ != 0)
  32000. {
  32001. // if no children want it and we're allowed to try our parent comp,
  32002. // then pass up to parent, which will try our siblings.
  32003. parentComponent_->grabFocusInternal (cause, true);
  32004. }
  32005. }
  32006. }
  32007. }
  32008. }
  32009. void Component::grabKeyboardFocus()
  32010. {
  32011. // if component methods are being called from threads other than the message
  32012. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32013. checkMessageManagerIsLocked
  32014. grabFocusInternal (focusChangedDirectly);
  32015. }
  32016. void Component::moveKeyboardFocusToSibling (const bool moveToNext)
  32017. {
  32018. // if component methods are being called from threads other than the message
  32019. // thread, you'll need to use a MessageManagerLock object to make sure it's thread-safe.
  32020. checkMessageManagerIsLocked
  32021. if (parentComponent_ != 0)
  32022. {
  32023. KeyboardFocusTraverser* const traverser = createFocusTraverser();
  32024. if (traverser != 0)
  32025. {
  32026. Component* const nextComp = moveToNext ? traverser->getNextComponent (this)
  32027. : traverser->getPreviousComponent (this);
  32028. delete traverser;
  32029. if (nextComp != 0)
  32030. {
  32031. if (nextComp->isCurrentlyBlockedByAnotherModalComponent())
  32032. {
  32033. const ComponentDeletionWatcher deletionChecker (nextComp);
  32034. internalModalInputAttempt();
  32035. if (deletionChecker.hasBeenDeleted()
  32036. || nextComp->isCurrentlyBlockedByAnotherModalComponent())
  32037. return;
  32038. }
  32039. nextComp->grabFocusInternal (focusChangedByTabKey);
  32040. return;
  32041. }
  32042. }
  32043. parentComponent_->moveKeyboardFocusToSibling (moveToNext);
  32044. }
  32045. }
  32046. bool Component::hasKeyboardFocus (const bool trueIfChildIsFocused) const throw()
  32047. {
  32048. return (currentlyFocusedComponent == this)
  32049. || (trueIfChildIsFocused && isParentOf (currentlyFocusedComponent));
  32050. }
  32051. Component* JUCE_CALLTYPE Component::getCurrentlyFocusedComponent() throw()
  32052. {
  32053. return currentlyFocusedComponent;
  32054. }
  32055. void Component::giveAwayFocus()
  32056. {
  32057. // use a copy so we can clear the value before the call
  32058. Component* const componentLosingFocus = currentlyFocusedComponent;
  32059. currentlyFocusedComponent = 0;
  32060. Desktop::getInstance().triggerFocusCallback();
  32061. if (componentLosingFocus->isValidComponent())
  32062. componentLosingFocus->internalFocusLoss (focusChangedDirectly);
  32063. }
  32064. bool Component::isMouseOver() const throw()
  32065. {
  32066. return flags.mouseOverFlag;
  32067. }
  32068. bool Component::isMouseButtonDown() const throw()
  32069. {
  32070. return flags.draggingFlag;
  32071. }
  32072. bool Component::isMouseOverOrDragging() const throw()
  32073. {
  32074. return flags.mouseOverFlag || flags.draggingFlag;
  32075. }
  32076. bool JUCE_CALLTYPE Component::isMouseButtonDownAnywhere() throw()
  32077. {
  32078. return ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown();
  32079. }
  32080. void Component::getMouseXYRelative (int& mx, int& my) const throw()
  32081. {
  32082. Desktop::getMousePosition (mx, my);
  32083. globalPositionToRelative (mx, my);
  32084. mx += unboundedMouseOffsetX;
  32085. my += unboundedMouseOffsetY;
  32086. }
  32087. void Component::enableUnboundedMouseMovement (bool enable,
  32088. bool keepCursorVisibleUntilOffscreen) throw()
  32089. {
  32090. enable = enable && isMouseButtonDown();
  32091. isCursorVisibleUntilOffscreen = keepCursorVisibleUntilOffscreen;
  32092. if (enable != isUnboundedMouseModeOn)
  32093. {
  32094. if ((! enable) && ((! isCursorVisibleUntilOffscreen)
  32095. || unboundedMouseOffsetX != 0
  32096. || unboundedMouseOffsetY != 0))
  32097. {
  32098. // when released, return the mouse to within the component's bounds
  32099. int mx, my;
  32100. getMouseXYRelative (mx, my);
  32101. mx = jlimit (0, getWidth(), mx);
  32102. my = jlimit (0, getHeight(), my);
  32103. relativePositionToGlobal (mx, my);
  32104. Desktop::setMousePosition (mx, my);
  32105. }
  32106. isUnboundedMouseModeOn = enable;
  32107. unboundedMouseOffsetX = 0;
  32108. unboundedMouseOffsetY = 0;
  32109. internalUpdateMouseCursor (true);
  32110. }
  32111. }
  32112. Component* JUCE_CALLTYPE Component::getComponentUnderMouse() throw()
  32113. {
  32114. return componentUnderMouse;
  32115. }
  32116. const Rectangle Component::getParentMonitorArea() const throw()
  32117. {
  32118. int centreX = getWidth() / 2;
  32119. int centreY = getHeight() / 2;
  32120. relativePositionToGlobal (centreX, centreY);
  32121. return Desktop::getInstance().getMonitorAreaContaining (centreX, centreY);
  32122. }
  32123. void Component::addKeyListener (KeyListener* const newListener) throw()
  32124. {
  32125. if (keyListeners_ == 0)
  32126. keyListeners_ = new VoidArray (4);
  32127. keyListeners_->addIfNotAlreadyThere (newListener);
  32128. }
  32129. void Component::removeKeyListener (KeyListener* const listenerToRemove) throw()
  32130. {
  32131. if (keyListeners_ != 0)
  32132. keyListeners_->removeValue (listenerToRemove);
  32133. }
  32134. bool Component::keyPressed (const KeyPress&)
  32135. {
  32136. return false;
  32137. }
  32138. bool Component::keyStateChanged()
  32139. {
  32140. return false;
  32141. }
  32142. void Component::modifierKeysChanged (const ModifierKeys& modifiers)
  32143. {
  32144. if (parentComponent_ != 0)
  32145. parentComponent_->modifierKeysChanged (modifiers);
  32146. }
  32147. void Component::internalModifierKeysChanged()
  32148. {
  32149. sendFakeMouseMove();
  32150. modifierKeysChanged (ModifierKeys::getCurrentModifiers());
  32151. }
  32152. ComponentPeer* Component::getPeer() const throw()
  32153. {
  32154. if (flags.hasHeavyweightPeerFlag)
  32155. return ComponentPeer::getPeerFor (this);
  32156. else if (parentComponent_ != 0)
  32157. return parentComponent_->getPeer();
  32158. else
  32159. return 0;
  32160. }
  32161. const String Component::getComponentProperty (const String& keyName,
  32162. const bool useParentComponentIfNotFound,
  32163. const String& defaultReturnValue) const throw()
  32164. {
  32165. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  32166. return propertySet_->getValue (keyName, defaultReturnValue);
  32167. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  32168. return parentComponent_->getComponentProperty (keyName, true, defaultReturnValue);
  32169. return defaultReturnValue;
  32170. }
  32171. int Component::getComponentPropertyInt (const String& keyName,
  32172. const bool useParentComponentIfNotFound,
  32173. const int defaultReturnValue) const throw()
  32174. {
  32175. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  32176. return propertySet_->getIntValue (keyName, defaultReturnValue);
  32177. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  32178. return parentComponent_->getComponentPropertyInt (keyName, true, defaultReturnValue);
  32179. return defaultReturnValue;
  32180. }
  32181. double Component::getComponentPropertyDouble (const String& keyName,
  32182. const bool useParentComponentIfNotFound,
  32183. const double defaultReturnValue) const throw()
  32184. {
  32185. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  32186. return propertySet_->getDoubleValue (keyName, defaultReturnValue);
  32187. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  32188. return parentComponent_->getComponentPropertyDouble (keyName, true, defaultReturnValue);
  32189. return defaultReturnValue;
  32190. }
  32191. bool Component::getComponentPropertyBool (const String& keyName,
  32192. const bool useParentComponentIfNotFound,
  32193. const bool defaultReturnValue) const throw()
  32194. {
  32195. if (propertySet_ != 0 && ((! useParentComponentIfNotFound) || propertySet_->containsKey (keyName)))
  32196. return propertySet_->getBoolValue (keyName, defaultReturnValue);
  32197. if (useParentComponentIfNotFound && (parentComponent_ != 0))
  32198. return parentComponent_->getComponentPropertyBool (keyName, true, defaultReturnValue);
  32199. return defaultReturnValue;
  32200. }
  32201. const Colour Component::getComponentPropertyColour (const String& keyName,
  32202. const bool useParentComponentIfNotFound,
  32203. const Colour& defaultReturnValue) const throw()
  32204. {
  32205. return Colour ((uint32) getComponentPropertyInt (keyName,
  32206. useParentComponentIfNotFound,
  32207. defaultReturnValue.getARGB()));
  32208. }
  32209. void Component::setComponentProperty (const String& keyName, const String& value) throw()
  32210. {
  32211. if (propertySet_ == 0)
  32212. propertySet_ = new PropertySet();
  32213. propertySet_->setValue (keyName, value);
  32214. }
  32215. void Component::setComponentProperty (const String& keyName, const int value) throw()
  32216. {
  32217. if (propertySet_ == 0)
  32218. propertySet_ = new PropertySet();
  32219. propertySet_->setValue (keyName, value);
  32220. }
  32221. void Component::setComponentProperty (const String& keyName, const double value) throw()
  32222. {
  32223. if (propertySet_ == 0)
  32224. propertySet_ = new PropertySet();
  32225. propertySet_->setValue (keyName, value);
  32226. }
  32227. void Component::setComponentProperty (const String& keyName, const bool value) throw()
  32228. {
  32229. if (propertySet_ == 0)
  32230. propertySet_ = new PropertySet();
  32231. propertySet_->setValue (keyName, value);
  32232. }
  32233. void Component::setComponentProperty (const String& keyName, const Colour& colour) throw()
  32234. {
  32235. setComponentProperty (keyName, (int) colour.getARGB());
  32236. }
  32237. void Component::removeComponentProperty (const String& keyName) throw()
  32238. {
  32239. if (propertySet_ != 0)
  32240. propertySet_->removeValue (keyName);
  32241. }
  32242. ComponentDeletionWatcher::ComponentDeletionWatcher (const Component* const componentToWatch_) throw()
  32243. : componentToWatch (componentToWatch_),
  32244. componentUID (componentToWatch_->getComponentUID())
  32245. {
  32246. // not possible to check on an already-deleted object..
  32247. jassert (componentToWatch_->isValidComponent());
  32248. }
  32249. ComponentDeletionWatcher::~ComponentDeletionWatcher() throw() {}
  32250. bool ComponentDeletionWatcher::hasBeenDeleted() const throw()
  32251. {
  32252. return ! (componentToWatch->isValidComponent()
  32253. && componentToWatch->getComponentUID() == componentUID);
  32254. }
  32255. const Component* ComponentDeletionWatcher::getComponent() const throw()
  32256. {
  32257. return hasBeenDeleted() ? 0 : componentToWatch;
  32258. }
  32259. END_JUCE_NAMESPACE
  32260. /********* End of inlined file: juce_Component.cpp *********/
  32261. /********* Start of inlined file: juce_ComponentListener.cpp *********/
  32262. BEGIN_JUCE_NAMESPACE
  32263. void ComponentListener::componentMovedOrResized (Component&, bool, bool)
  32264. {
  32265. }
  32266. void ComponentListener::componentBroughtToFront (Component&)
  32267. {
  32268. }
  32269. void ComponentListener::componentVisibilityChanged (Component&)
  32270. {
  32271. }
  32272. void ComponentListener::componentChildrenChanged (Component&)
  32273. {
  32274. }
  32275. void ComponentListener::componentParentHierarchyChanged (Component&)
  32276. {
  32277. }
  32278. void ComponentListener::componentNameChanged (Component&)
  32279. {
  32280. }
  32281. END_JUCE_NAMESPACE
  32282. /********* End of inlined file: juce_ComponentListener.cpp *********/
  32283. /********* Start of inlined file: juce_Desktop.cpp *********/
  32284. BEGIN_JUCE_NAMESPACE
  32285. extern void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords,
  32286. const bool clipToWorkArea) throw();
  32287. static Desktop* juce_desktopInstance = 0;
  32288. Desktop::Desktop() throw()
  32289. : mouseListeners (2),
  32290. desktopComponents (4),
  32291. monitorCoordsClipped (2),
  32292. monitorCoordsUnclipped (2),
  32293. lastMouseX (0),
  32294. lastMouseY (0)
  32295. {
  32296. refreshMonitorSizes();
  32297. }
  32298. Desktop::~Desktop() throw()
  32299. {
  32300. jassert (juce_desktopInstance == this);
  32301. juce_desktopInstance = 0;
  32302. // doh! If you don't delete all your windows before exiting, you're going to
  32303. // be leaking memory!
  32304. jassert (desktopComponents.size() == 0);
  32305. }
  32306. Desktop& JUCE_CALLTYPE Desktop::getInstance() throw()
  32307. {
  32308. if (juce_desktopInstance == 0)
  32309. juce_desktopInstance = new Desktop();
  32310. return *juce_desktopInstance;
  32311. }
  32312. void Desktop::refreshMonitorSizes() throw()
  32313. {
  32314. const Array <Rectangle> oldClipped (monitorCoordsClipped);
  32315. const Array <Rectangle> oldUnclipped (monitorCoordsUnclipped);
  32316. monitorCoordsClipped.clear();
  32317. monitorCoordsUnclipped.clear();
  32318. juce_updateMultiMonitorInfo (monitorCoordsClipped, true);
  32319. juce_updateMultiMonitorInfo (monitorCoordsUnclipped, false);
  32320. jassert (monitorCoordsClipped.size() > 0
  32321. && monitorCoordsClipped.size() == monitorCoordsUnclipped.size());
  32322. if (oldClipped != monitorCoordsClipped
  32323. || oldUnclipped != monitorCoordsUnclipped)
  32324. {
  32325. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  32326. {
  32327. ComponentPeer* const p = ComponentPeer::getPeer (i);
  32328. if (p != 0)
  32329. p->handleScreenSizeChange();
  32330. }
  32331. }
  32332. }
  32333. int Desktop::getNumDisplayMonitors() const throw()
  32334. {
  32335. return monitorCoordsClipped.size();
  32336. }
  32337. const Rectangle Desktop::getDisplayMonitorCoordinates (const int index, const bool clippedToWorkArea) const throw()
  32338. {
  32339. return clippedToWorkArea ? monitorCoordsClipped [index]
  32340. : monitorCoordsUnclipped [index];
  32341. }
  32342. const RectangleList Desktop::getAllMonitorDisplayAreas (const bool clippedToWorkArea) const throw()
  32343. {
  32344. RectangleList rl;
  32345. for (int i = 0; i < getNumDisplayMonitors(); ++i)
  32346. rl.addWithoutMerging (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  32347. return rl;
  32348. }
  32349. const Rectangle Desktop::getMainMonitorArea (const bool clippedToWorkArea) const throw()
  32350. {
  32351. return getDisplayMonitorCoordinates (0, clippedToWorkArea);
  32352. }
  32353. const Rectangle Desktop::getMonitorAreaContaining (int cx, int cy, const bool clippedToWorkArea) const throw()
  32354. {
  32355. Rectangle best (getMainMonitorArea (clippedToWorkArea));
  32356. double bestDistance = 1.0e10;
  32357. for (int i = getNumDisplayMonitors(); --i >= 0;)
  32358. {
  32359. const Rectangle rect (getDisplayMonitorCoordinates (i, clippedToWorkArea));
  32360. if (rect.contains (cx, cy))
  32361. return rect;
  32362. const double distance = juce_hypot ((double) (rect.getCentreX() - cx),
  32363. (double) (rect.getCentreY() - cy));
  32364. if (distance < bestDistance)
  32365. {
  32366. bestDistance = distance;
  32367. best = rect;
  32368. }
  32369. }
  32370. return best;
  32371. }
  32372. int Desktop::getNumComponents() const throw()
  32373. {
  32374. return desktopComponents.size();
  32375. }
  32376. Component* Desktop::getComponent (const int index) const throw()
  32377. {
  32378. return (Component*) desktopComponents [index];
  32379. }
  32380. Component* Desktop::findComponentAt (const int screenX,
  32381. const int screenY) const
  32382. {
  32383. for (int i = desktopComponents.size(); --i >= 0;)
  32384. {
  32385. Component* const c = (Component*) desktopComponents.getUnchecked(i);
  32386. int x = screenX, y = screenY;
  32387. c->globalPositionToRelative (x, y);
  32388. if (c->contains (x, y))
  32389. return c->getComponentAt (x, y);
  32390. }
  32391. return 0;
  32392. }
  32393. void Desktop::addDesktopComponent (Component* const c) throw()
  32394. {
  32395. jassert (c != 0);
  32396. jassert (! desktopComponents.contains (c));
  32397. desktopComponents.addIfNotAlreadyThere (c);
  32398. }
  32399. void Desktop::removeDesktopComponent (Component* const c) throw()
  32400. {
  32401. desktopComponents.removeValue (c);
  32402. }
  32403. void Desktop::componentBroughtToFront (Component* const c) throw()
  32404. {
  32405. const int index = desktopComponents.indexOf (c);
  32406. jassert (index >= 0);
  32407. if (index >= 0)
  32408. desktopComponents.move (index, -1);
  32409. }
  32410. // from Component.cpp
  32411. extern int juce_recentMouseDownX [4];
  32412. extern int juce_recentMouseDownY [4];
  32413. extern int juce_MouseClickCounter;
  32414. void Desktop::getLastMouseDownPosition (int& x, int& y) throw()
  32415. {
  32416. x = juce_recentMouseDownX [0];
  32417. y = juce_recentMouseDownY [0];
  32418. }
  32419. int Desktop::getMouseButtonClickCounter() throw()
  32420. {
  32421. return juce_MouseClickCounter;
  32422. }
  32423. void Desktop::addGlobalMouseListener (MouseListener* const listener) throw()
  32424. {
  32425. jassert (listener != 0);
  32426. if (listener != 0)
  32427. {
  32428. mouseListeners.add (listener);
  32429. resetTimer();
  32430. }
  32431. }
  32432. void Desktop::removeGlobalMouseListener (MouseListener* const listener) throw()
  32433. {
  32434. mouseListeners.removeValue (listener);
  32435. resetTimer();
  32436. }
  32437. void Desktop::addFocusChangeListener (FocusChangeListener* const listener) throw()
  32438. {
  32439. jassert (listener != 0);
  32440. if (listener != 0)
  32441. focusListeners.add (listener);
  32442. }
  32443. void Desktop::removeFocusChangeListener (FocusChangeListener* const listener) throw()
  32444. {
  32445. focusListeners.removeValue (listener);
  32446. }
  32447. void Desktop::triggerFocusCallback() throw()
  32448. {
  32449. triggerAsyncUpdate();
  32450. }
  32451. void Desktop::handleAsyncUpdate()
  32452. {
  32453. for (int i = focusListeners.size(); --i >= 0;)
  32454. {
  32455. ((FocusChangeListener*) focusListeners.getUnchecked (i))->globalFocusChanged (Component::getCurrentlyFocusedComponent());
  32456. i = jmin (i, focusListeners.size());
  32457. }
  32458. }
  32459. void Desktop::timerCallback()
  32460. {
  32461. int x, y;
  32462. getMousePosition (x, y);
  32463. if (lastMouseX != x || lastMouseY != y)
  32464. sendMouseMove();
  32465. }
  32466. void Desktop::sendMouseMove()
  32467. {
  32468. if (mouseListeners.size() > 0)
  32469. {
  32470. startTimer (20);
  32471. int x, y;
  32472. getMousePosition (x, y);
  32473. lastMouseX = x;
  32474. lastMouseY = y;
  32475. Component* const target = findComponentAt (x, y);
  32476. if (target != 0)
  32477. {
  32478. target->globalPositionToRelative (x, y);
  32479. ComponentDeletionWatcher deletionChecker (target);
  32480. const MouseEvent me (x, y,
  32481. ModifierKeys::getCurrentModifiers(),
  32482. target,
  32483. Time::getCurrentTime(),
  32484. x, y,
  32485. Time::getCurrentTime(),
  32486. 0, false);
  32487. for (int i = mouseListeners.size(); --i >= 0;)
  32488. {
  32489. if (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  32490. ((MouseListener*) mouseListeners[i])->mouseDrag (me);
  32491. else
  32492. ((MouseListener*) mouseListeners[i])->mouseMove (me);
  32493. if (deletionChecker.hasBeenDeleted())
  32494. return;
  32495. i = jmin (i, mouseListeners.size());
  32496. }
  32497. }
  32498. }
  32499. }
  32500. void Desktop::resetTimer() throw()
  32501. {
  32502. if (mouseListeners.size() == 0)
  32503. stopTimer();
  32504. else
  32505. startTimer (100);
  32506. getMousePosition (lastMouseX, lastMouseY);
  32507. }
  32508. END_JUCE_NAMESPACE
  32509. /********* End of inlined file: juce_Desktop.cpp *********/
  32510. /********* Start of inlined file: juce_ArrowButton.cpp *********/
  32511. BEGIN_JUCE_NAMESPACE
  32512. ArrowButton::ArrowButton (const String& name,
  32513. float arrowDirectionInRadians,
  32514. const Colour& arrowColour)
  32515. : Button (name),
  32516. colour (arrowColour)
  32517. {
  32518. path.lineTo (0.0f, 1.0f);
  32519. path.lineTo (1.0f, 0.5f);
  32520. path.closeSubPath();
  32521. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * arrowDirectionInRadians,
  32522. 0.5f, 0.5f));
  32523. setComponentEffect (&shadow);
  32524. buttonStateChanged();
  32525. }
  32526. ArrowButton::~ArrowButton()
  32527. {
  32528. }
  32529. void ArrowButton::paintButton (Graphics& g,
  32530. bool /*isMouseOverButton*/,
  32531. bool /*isButtonDown*/)
  32532. {
  32533. g.setColour (colour);
  32534. g.fillPath (path, path.getTransformToScaleToFit ((float) offset,
  32535. (float) offset,
  32536. (float) (getWidth() - 3),
  32537. (float) (getHeight() - 3),
  32538. false));
  32539. }
  32540. void ArrowButton::buttonStateChanged()
  32541. {
  32542. offset = (isDown()) ? 1 : 0;
  32543. shadow.setShadowProperties ((isDown()) ? 1.2f : 3.0f,
  32544. 0.3f, -1, 0);
  32545. }
  32546. END_JUCE_NAMESPACE
  32547. /********* End of inlined file: juce_ArrowButton.cpp *********/
  32548. /********* Start of inlined file: juce_Button.cpp *********/
  32549. BEGIN_JUCE_NAMESPACE
  32550. Button::Button (const String& name)
  32551. : Component (name),
  32552. shortcuts (2),
  32553. keySource (0),
  32554. text (name),
  32555. buttonListeners (2),
  32556. repeatTimer (0),
  32557. buttonPressTime (0),
  32558. lastTimeCallbackTime (0),
  32559. commandManagerToUse (0),
  32560. autoRepeatDelay (-1),
  32561. autoRepeatSpeed (0),
  32562. autoRepeatMinimumDelay (-1),
  32563. radioGroupId (0),
  32564. commandID (0),
  32565. connectedEdgeFlags (0),
  32566. buttonState (buttonNormal),
  32567. isOn (false),
  32568. clickTogglesState (false),
  32569. needsToRelease (false),
  32570. needsRepainting (false),
  32571. isKeyDown (false),
  32572. triggerOnMouseDown (false),
  32573. generateTooltip (false)
  32574. {
  32575. setWantsKeyboardFocus (true);
  32576. }
  32577. Button::~Button()
  32578. {
  32579. if (commandManagerToUse != 0)
  32580. commandManagerToUse->removeListener (this);
  32581. delete repeatTimer;
  32582. clearShortcuts();
  32583. }
  32584. void Button::setButtonText (const String& newText) throw()
  32585. {
  32586. if (text != newText)
  32587. {
  32588. text = newText;
  32589. repaint();
  32590. }
  32591. }
  32592. void Button::setTooltip (const String& newTooltip)
  32593. {
  32594. SettableTooltipClient::setTooltip (newTooltip);
  32595. generateTooltip = false;
  32596. }
  32597. const String Button::getTooltip()
  32598. {
  32599. if (generateTooltip && commandManagerToUse != 0 && commandID != 0)
  32600. {
  32601. String tt (commandManagerToUse->getDescriptionOfCommand (commandID));
  32602. Array <KeyPress> keyPresses (commandManagerToUse->getKeyMappings()->getKeyPressesAssignedToCommand (commandID));
  32603. for (int i = 0; i < keyPresses.size(); ++i)
  32604. {
  32605. const String key (keyPresses.getReference(i).getTextDescription());
  32606. if (key.length() == 1)
  32607. tt << " [shortcut: '" << key << "']";
  32608. else
  32609. tt << " [" << key << ']';
  32610. }
  32611. return tt;
  32612. }
  32613. return SettableTooltipClient::getTooltip();
  32614. }
  32615. void Button::setConnectedEdges (const int connectedEdgeFlags_) throw()
  32616. {
  32617. if (connectedEdgeFlags != connectedEdgeFlags_)
  32618. {
  32619. connectedEdgeFlags = connectedEdgeFlags_;
  32620. repaint();
  32621. }
  32622. }
  32623. void Button::setToggleState (const bool shouldBeOn,
  32624. const bool sendChangeNotification)
  32625. {
  32626. if (shouldBeOn != isOn)
  32627. {
  32628. const ComponentDeletionWatcher deletionWatcher (this);
  32629. isOn = shouldBeOn;
  32630. repaint();
  32631. if (sendChangeNotification)
  32632. sendClickMessage (ModifierKeys());
  32633. if ((! deletionWatcher.hasBeenDeleted()) && isOn)
  32634. turnOffOtherButtonsInGroup (sendChangeNotification);
  32635. }
  32636. }
  32637. void Button::setClickingTogglesState (const bool shouldToggle) throw()
  32638. {
  32639. clickTogglesState = shouldToggle;
  32640. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  32641. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  32642. // it is that this button represents, and the button will update its state to reflect this
  32643. // in the applicationCommandListChanged() method.
  32644. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  32645. }
  32646. bool Button::getClickingTogglesState() const throw()
  32647. {
  32648. return clickTogglesState;
  32649. }
  32650. void Button::setRadioGroupId (const int newGroupId)
  32651. {
  32652. if (radioGroupId != newGroupId)
  32653. {
  32654. radioGroupId = newGroupId;
  32655. if (isOn)
  32656. turnOffOtherButtonsInGroup (true);
  32657. }
  32658. }
  32659. void Button::turnOffOtherButtonsInGroup (const bool sendChangeNotification)
  32660. {
  32661. Component* const p = getParentComponent();
  32662. if (p != 0 && radioGroupId != 0)
  32663. {
  32664. const ComponentDeletionWatcher deletionWatcher (this);
  32665. for (int i = p->getNumChildComponents(); --i >= 0;)
  32666. {
  32667. Component* const c = p->getChildComponent (i);
  32668. if (c != this)
  32669. {
  32670. Button* const b = dynamic_cast <Button*> (c);
  32671. if (b != 0 && b->getRadioGroupId() == radioGroupId)
  32672. {
  32673. b->setToggleState (false, sendChangeNotification);
  32674. if (deletionWatcher.hasBeenDeleted())
  32675. return;
  32676. }
  32677. }
  32678. }
  32679. }
  32680. }
  32681. void Button::enablementChanged()
  32682. {
  32683. updateState (0);
  32684. repaint();
  32685. }
  32686. Button::ButtonState Button::updateState (const MouseEvent* const e) throw()
  32687. {
  32688. ButtonState state = buttonNormal;
  32689. if (isEnabled() && isVisible() && ! isCurrentlyBlockedByAnotherModalComponent())
  32690. {
  32691. int mx, my;
  32692. if (e == 0)
  32693. {
  32694. getMouseXYRelative (mx, my);
  32695. }
  32696. else
  32697. {
  32698. const MouseEvent e2 (e->getEventRelativeTo (this));
  32699. mx = e2.x;
  32700. my = e2.y;
  32701. }
  32702. const bool over = reallyContains (mx, my, true);
  32703. const bool down = isMouseButtonDown();
  32704. if ((down && (over || (triggerOnMouseDown && buttonState == buttonDown))) || isKeyDown)
  32705. state = buttonDown;
  32706. else if (over)
  32707. state = buttonOver;
  32708. }
  32709. setState (state);
  32710. return state;
  32711. }
  32712. void Button::setState (const ButtonState newState)
  32713. {
  32714. if (buttonState != newState)
  32715. {
  32716. buttonState = newState;
  32717. repaint();
  32718. if (buttonState == buttonDown)
  32719. {
  32720. buttonPressTime = Time::getApproximateMillisecondCounter();
  32721. lastTimeCallbackTime = buttonPressTime;
  32722. }
  32723. sendStateMessage();
  32724. }
  32725. }
  32726. bool Button::isDown() const throw()
  32727. {
  32728. return buttonState == buttonDown;
  32729. }
  32730. bool Button::isOver() const throw()
  32731. {
  32732. return buttonState != buttonNormal;
  32733. }
  32734. void Button::buttonStateChanged()
  32735. {
  32736. }
  32737. uint32 Button::getMillisecondsSinceButtonDown() const throw()
  32738. {
  32739. const uint32 now = Time::getApproximateMillisecondCounter();
  32740. return now > buttonPressTime ? now - buttonPressTime : 0;
  32741. }
  32742. void Button::setTriggeredOnMouseDown (const bool isTriggeredOnMouseDown) throw()
  32743. {
  32744. triggerOnMouseDown = isTriggeredOnMouseDown;
  32745. }
  32746. void Button::clicked()
  32747. {
  32748. }
  32749. void Button::clicked (const ModifierKeys& /*modifiers*/)
  32750. {
  32751. clicked();
  32752. }
  32753. static const int clickMessageId = 0x2f3f4f99;
  32754. void Button::triggerClick()
  32755. {
  32756. postCommandMessage (clickMessageId);
  32757. }
  32758. void Button::internalClickCallback (const ModifierKeys& modifiers)
  32759. {
  32760. if (clickTogglesState)
  32761. setToggleState ((radioGroupId != 0) || ! isOn, false);
  32762. sendClickMessage (modifiers);
  32763. }
  32764. void Button::flashButtonState() throw()
  32765. {
  32766. if (isEnabled())
  32767. {
  32768. needsToRelease = true;
  32769. setState (buttonDown);
  32770. getRepeatTimer().startTimer (100);
  32771. }
  32772. }
  32773. void Button::handleCommandMessage (int commandId)
  32774. {
  32775. if (commandId == clickMessageId)
  32776. {
  32777. if (isEnabled())
  32778. {
  32779. flashButtonState();
  32780. internalClickCallback (ModifierKeys::getCurrentModifiers());
  32781. }
  32782. }
  32783. else
  32784. {
  32785. Component::handleCommandMessage (commandId);
  32786. }
  32787. }
  32788. void Button::addButtonListener (ButtonListener* const newListener) throw()
  32789. {
  32790. jassert (newListener != 0);
  32791. jassert (! buttonListeners.contains (newListener)); // trying to add a listener to the list twice!
  32792. if (newListener != 0)
  32793. buttonListeners.add (newListener);
  32794. }
  32795. void Button::removeButtonListener (ButtonListener* const listener) throw()
  32796. {
  32797. jassert (buttonListeners.contains (listener)); // trying to remove a listener that isn't on the list!
  32798. buttonListeners.removeValue (listener);
  32799. }
  32800. void Button::sendClickMessage (const ModifierKeys& modifiers)
  32801. {
  32802. const ComponentDeletionWatcher cdw (this);
  32803. if (commandManagerToUse != 0 && commandID != 0)
  32804. {
  32805. ApplicationCommandTarget::InvocationInfo info (commandID);
  32806. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromButton;
  32807. info.originatingComponent = this;
  32808. commandManagerToUse->invoke (info, true);
  32809. }
  32810. clicked (modifiers);
  32811. if (! cdw.hasBeenDeleted())
  32812. {
  32813. for (int i = buttonListeners.size(); --i >= 0;)
  32814. {
  32815. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  32816. if (bl != 0)
  32817. {
  32818. bl->buttonClicked (this);
  32819. if (cdw.hasBeenDeleted())
  32820. return;
  32821. }
  32822. }
  32823. }
  32824. }
  32825. void Button::sendStateMessage()
  32826. {
  32827. const ComponentDeletionWatcher cdw (this);
  32828. buttonStateChanged();
  32829. if (cdw.hasBeenDeleted())
  32830. return;
  32831. for (int i = buttonListeners.size(); --i >= 0;)
  32832. {
  32833. ButtonListener* const bl = (ButtonListener*) buttonListeners[i];
  32834. if (bl != 0)
  32835. {
  32836. bl->buttonStateChanged (this);
  32837. if (cdw.hasBeenDeleted())
  32838. return;
  32839. }
  32840. }
  32841. }
  32842. void Button::paint (Graphics& g)
  32843. {
  32844. if (needsToRelease && isEnabled())
  32845. {
  32846. needsToRelease = false;
  32847. needsRepainting = true;
  32848. }
  32849. paintButton (g, isOver(), isDown());
  32850. }
  32851. void Button::mouseEnter (const MouseEvent& e)
  32852. {
  32853. updateState (&e);
  32854. }
  32855. void Button::mouseExit (const MouseEvent& e)
  32856. {
  32857. updateState (&e);
  32858. }
  32859. void Button::mouseDown (const MouseEvent& e)
  32860. {
  32861. updateState (&e);
  32862. if (isDown())
  32863. {
  32864. if (autoRepeatDelay >= 0)
  32865. getRepeatTimer().startTimer (autoRepeatDelay);
  32866. if (triggerOnMouseDown)
  32867. internalClickCallback (e.mods);
  32868. }
  32869. }
  32870. void Button::mouseUp (const MouseEvent& e)
  32871. {
  32872. const bool wasDown = isDown();
  32873. updateState (&e);
  32874. if (wasDown && isOver() && ! triggerOnMouseDown)
  32875. internalClickCallback (e.mods);
  32876. }
  32877. void Button::mouseDrag (const MouseEvent& e)
  32878. {
  32879. const ButtonState oldState = buttonState;
  32880. updateState (&e);
  32881. if (autoRepeatDelay >= 0 && buttonState != oldState && isDown())
  32882. getRepeatTimer().startTimer (autoRepeatSpeed);
  32883. }
  32884. void Button::focusGained (FocusChangeType)
  32885. {
  32886. updateState (0);
  32887. repaint();
  32888. }
  32889. void Button::focusLost (FocusChangeType)
  32890. {
  32891. updateState (0);
  32892. repaint();
  32893. }
  32894. void Button::setVisible (bool shouldBeVisible)
  32895. {
  32896. if (shouldBeVisible != isVisible())
  32897. {
  32898. Component::setVisible (shouldBeVisible);
  32899. if (! shouldBeVisible)
  32900. needsToRelease = false;
  32901. updateState (0);
  32902. }
  32903. else
  32904. {
  32905. Component::setVisible (shouldBeVisible);
  32906. }
  32907. }
  32908. void Button::parentHierarchyChanged()
  32909. {
  32910. Component* const newKeySource = (shortcuts.size() == 0) ? 0 : getTopLevelComponent();
  32911. if (newKeySource != keySource)
  32912. {
  32913. if (keySource->isValidComponent())
  32914. keySource->removeKeyListener (this);
  32915. keySource = newKeySource;
  32916. if (keySource->isValidComponent())
  32917. keySource->addKeyListener (this);
  32918. }
  32919. }
  32920. void Button::setCommandToTrigger (ApplicationCommandManager* const commandManagerToUse_,
  32921. const int commandID_,
  32922. const bool generateTooltip_)
  32923. {
  32924. commandID = commandID_;
  32925. generateTooltip = generateTooltip_;
  32926. if (commandManagerToUse != commandManagerToUse_)
  32927. {
  32928. if (commandManagerToUse != 0)
  32929. commandManagerToUse->removeListener (this);
  32930. commandManagerToUse = commandManagerToUse_;
  32931. if (commandManagerToUse != 0)
  32932. commandManagerToUse->addListener (this);
  32933. // if you've got clickTogglesState turned on, you shouldn't also connect the button
  32934. // up to be a command invoker. Instead, your command handler must flip the state of whatever
  32935. // it is that this button represents, and the button will update its state to reflect this
  32936. // in the applicationCommandListChanged() method.
  32937. jassert (commandManagerToUse == 0 || ! clickTogglesState);
  32938. }
  32939. if (commandManagerToUse != 0)
  32940. applicationCommandListChanged();
  32941. else
  32942. setEnabled (true);
  32943. }
  32944. void Button::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  32945. {
  32946. if (info.commandID == commandID
  32947. && (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) == 0)
  32948. {
  32949. flashButtonState();
  32950. }
  32951. }
  32952. void Button::applicationCommandListChanged()
  32953. {
  32954. if (commandManagerToUse != 0)
  32955. {
  32956. ApplicationCommandInfo info (0);
  32957. ApplicationCommandTarget* const target = commandManagerToUse->getTargetForCommand (commandID, info);
  32958. setEnabled (target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0);
  32959. if (target != 0)
  32960. setToggleState ((info.flags & ApplicationCommandInfo::isTicked) != 0, false);
  32961. }
  32962. }
  32963. void Button::addShortcut (const KeyPress& key)
  32964. {
  32965. if (key.isValid())
  32966. {
  32967. jassert (! isRegisteredForShortcut (key)); // already registered!
  32968. shortcuts.add (key);
  32969. parentHierarchyChanged();
  32970. }
  32971. }
  32972. void Button::clearShortcuts()
  32973. {
  32974. shortcuts.clear();
  32975. parentHierarchyChanged();
  32976. }
  32977. bool Button::isShortcutPressed() const throw()
  32978. {
  32979. if (! isCurrentlyBlockedByAnotherModalComponent())
  32980. {
  32981. for (int i = shortcuts.size(); --i >= 0;)
  32982. if (shortcuts.getReference(i).isCurrentlyDown())
  32983. return true;
  32984. }
  32985. return false;
  32986. }
  32987. bool Button::isRegisteredForShortcut (const KeyPress& key) const throw()
  32988. {
  32989. for (int i = shortcuts.size(); --i >= 0;)
  32990. if (key == shortcuts.getReference(i))
  32991. return true;
  32992. return false;
  32993. }
  32994. bool Button::keyStateChanged (Component*)
  32995. {
  32996. if (! isEnabled())
  32997. return false;
  32998. const bool wasDown = isKeyDown;
  32999. isKeyDown = isShortcutPressed();
  33000. if (autoRepeatDelay >= 0 && (isKeyDown && ! wasDown))
  33001. getRepeatTimer().startTimer (autoRepeatDelay);
  33002. updateState (0);
  33003. if (isEnabled() && wasDown && ! isKeyDown)
  33004. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33005. return isKeyDown || wasDown;
  33006. }
  33007. bool Button::keyPressed (const KeyPress&, Component*)
  33008. {
  33009. // returning true will avoid forwarding events for keys that we're using as shortcuts
  33010. return isShortcutPressed();
  33011. }
  33012. bool Button::keyPressed (const KeyPress& key)
  33013. {
  33014. if (isEnabled() && key.isKeyCode (KeyPress::returnKey))
  33015. {
  33016. triggerClick();
  33017. return true;
  33018. }
  33019. return false;
  33020. }
  33021. void Button::setRepeatSpeed (const int initialDelayMillisecs,
  33022. const int repeatMillisecs,
  33023. const int minimumDelayInMillisecs) throw()
  33024. {
  33025. autoRepeatDelay = initialDelayMillisecs;
  33026. autoRepeatSpeed = repeatMillisecs;
  33027. autoRepeatMinimumDelay = jmin (autoRepeatSpeed, minimumDelayInMillisecs);
  33028. }
  33029. void Button::repeatTimerCallback() throw()
  33030. {
  33031. if (needsRepainting)
  33032. {
  33033. getRepeatTimer().stopTimer();
  33034. updateState (0);
  33035. needsRepainting = false;
  33036. }
  33037. else if (autoRepeatSpeed > 0 && (isKeyDown || (updateState (0) == buttonDown)))
  33038. {
  33039. int repeatSpeed = autoRepeatSpeed;
  33040. if (autoRepeatMinimumDelay >= 0)
  33041. {
  33042. double timeHeldDown = jmin (1.0, getMillisecondsSinceButtonDown() / 4000.0);
  33043. timeHeldDown *= timeHeldDown;
  33044. repeatSpeed = repeatSpeed + (int) (timeHeldDown * (autoRepeatMinimumDelay - repeatSpeed));
  33045. }
  33046. repeatSpeed = jmax (1, repeatSpeed);
  33047. getRepeatTimer().startTimer (repeatSpeed);
  33048. const uint32 now = Time::getApproximateMillisecondCounter();
  33049. const int numTimesToCallback
  33050. = (now > lastTimeCallbackTime) ? jmax (1, (now - lastTimeCallbackTime) / repeatSpeed) : 1;
  33051. lastTimeCallbackTime = now;
  33052. const ComponentDeletionWatcher cdw (this);
  33053. for (int i = numTimesToCallback; --i >= 0;)
  33054. {
  33055. internalClickCallback (ModifierKeys::getCurrentModifiers());
  33056. if (cdw.hasBeenDeleted() || ! isDown())
  33057. return;
  33058. }
  33059. }
  33060. else if (! needsToRelease)
  33061. {
  33062. getRepeatTimer().stopTimer();
  33063. }
  33064. }
  33065. class InternalButtonRepeatTimer : public Timer
  33066. {
  33067. public:
  33068. InternalButtonRepeatTimer (Button& owner_) throw()
  33069. : owner (owner_)
  33070. {
  33071. }
  33072. ~InternalButtonRepeatTimer()
  33073. {
  33074. }
  33075. void timerCallback()
  33076. {
  33077. owner.repeatTimerCallback();
  33078. }
  33079. private:
  33080. Button& owner;
  33081. InternalButtonRepeatTimer (const InternalButtonRepeatTimer&);
  33082. const InternalButtonRepeatTimer& operator= (const InternalButtonRepeatTimer&);
  33083. };
  33084. Timer& Button::getRepeatTimer() throw()
  33085. {
  33086. if (repeatTimer == 0)
  33087. repeatTimer = new InternalButtonRepeatTimer (*this);
  33088. return *repeatTimer;
  33089. }
  33090. END_JUCE_NAMESPACE
  33091. /********* End of inlined file: juce_Button.cpp *********/
  33092. /********* Start of inlined file: juce_DrawableButton.cpp *********/
  33093. BEGIN_JUCE_NAMESPACE
  33094. DrawableButton::DrawableButton (const String& name,
  33095. const DrawableButton::ButtonStyle buttonStyle)
  33096. : Button (name),
  33097. style (buttonStyle),
  33098. normalImage (0),
  33099. overImage (0),
  33100. downImage (0),
  33101. disabledImage (0),
  33102. normalImageOn (0),
  33103. overImageOn (0),
  33104. downImageOn (0),
  33105. disabledImageOn (0),
  33106. edgeIndent (3)
  33107. {
  33108. if (buttonStyle == ImageOnButtonBackground)
  33109. {
  33110. backgroundOff = Colour (0xffbbbbff);
  33111. backgroundOn = Colour (0xff3333ff);
  33112. }
  33113. else
  33114. {
  33115. backgroundOff = Colours::transparentBlack;
  33116. backgroundOn = Colour (0xaabbbbff);
  33117. }
  33118. }
  33119. DrawableButton::~DrawableButton()
  33120. {
  33121. deleteImages();
  33122. }
  33123. void DrawableButton::deleteImages()
  33124. {
  33125. deleteAndZero (normalImage);
  33126. deleteAndZero (overImage);
  33127. deleteAndZero (downImage);
  33128. deleteAndZero (disabledImage);
  33129. deleteAndZero (normalImageOn);
  33130. deleteAndZero (overImageOn);
  33131. deleteAndZero (downImageOn);
  33132. deleteAndZero (disabledImageOn);
  33133. }
  33134. void DrawableButton::setImages (const Drawable* normal,
  33135. const Drawable* over,
  33136. const Drawable* down,
  33137. const Drawable* disabled,
  33138. const Drawable* normalOn,
  33139. const Drawable* overOn,
  33140. const Drawable* downOn,
  33141. const Drawable* disabledOn)
  33142. {
  33143. deleteImages();
  33144. jassert (normal != 0); // you really need to give it at least a normal image..
  33145. if (normal != 0)
  33146. normalImage = normal->createCopy();
  33147. if (over != 0)
  33148. overImage = over->createCopy();
  33149. if (down != 0)
  33150. downImage = down->createCopy();
  33151. if (disabled != 0)
  33152. disabledImage = disabled->createCopy();
  33153. if (normalOn != 0)
  33154. normalImageOn = normalOn->createCopy();
  33155. if (overOn != 0)
  33156. overImageOn = overOn->createCopy();
  33157. if (downOn != 0)
  33158. downImageOn = downOn->createCopy();
  33159. if (disabledOn != 0)
  33160. disabledImageOn = disabledOn->createCopy();
  33161. repaint();
  33162. }
  33163. void DrawableButton::setButtonStyle (const DrawableButton::ButtonStyle newStyle)
  33164. {
  33165. if (style != newStyle)
  33166. {
  33167. style = newStyle;
  33168. repaint();
  33169. }
  33170. }
  33171. void DrawableButton::setBackgroundColours (const Colour& toggledOffColour,
  33172. const Colour& toggledOnColour)
  33173. {
  33174. if (backgroundOff != toggledOffColour
  33175. || backgroundOn != toggledOnColour)
  33176. {
  33177. backgroundOff = toggledOffColour;
  33178. backgroundOn = toggledOnColour;
  33179. repaint();
  33180. }
  33181. }
  33182. const Colour& DrawableButton::getBackgroundColour() const throw()
  33183. {
  33184. return getToggleState() ? backgroundOn
  33185. : backgroundOff;
  33186. }
  33187. void DrawableButton::setEdgeIndent (const int numPixelsIndent)
  33188. {
  33189. edgeIndent = numPixelsIndent;
  33190. repaint();
  33191. }
  33192. void DrawableButton::paintButton (Graphics& g,
  33193. bool isMouseOverButton,
  33194. bool isButtonDown)
  33195. {
  33196. Rectangle imageSpace;
  33197. if (style == ImageOnButtonBackground)
  33198. {
  33199. const int insetX = getWidth() / 4;
  33200. const int insetY = getHeight() / 4;
  33201. imageSpace.setBounds (insetX, insetY, getWidth() - insetX * 2, getHeight() - insetY * 2);
  33202. getLookAndFeel().drawButtonBackground (g, *this,
  33203. getBackgroundColour(),
  33204. isMouseOverButton,
  33205. isButtonDown);
  33206. }
  33207. else
  33208. {
  33209. g.fillAll (getBackgroundColour());
  33210. const int textH = (style == ImageAboveTextLabel)
  33211. ? jmin (16, proportionOfHeight (0.25f))
  33212. : 0;
  33213. const int indentX = jmin (edgeIndent, proportionOfWidth (0.3f));
  33214. const int indentY = jmin (edgeIndent, proportionOfHeight (0.3f));
  33215. imageSpace.setBounds (indentX, indentY,
  33216. getWidth() - indentX * 2,
  33217. getHeight() - indentY * 2 - textH);
  33218. if (textH > 0)
  33219. {
  33220. g.setFont ((float) textH);
  33221. g.setColour (Colours::black.withAlpha (isEnabled() ? 1.0f : 0.4f));
  33222. g.drawFittedText (getName(),
  33223. 2, getHeight() - textH - 1,
  33224. getWidth() - 4, textH,
  33225. Justification::centred, 1);
  33226. }
  33227. }
  33228. g.setImageResamplingQuality (Graphics::mediumResamplingQuality);
  33229. g.setOpacity (1.0f);
  33230. const Drawable* imageToDraw = 0;
  33231. if (isEnabled())
  33232. {
  33233. imageToDraw = getCurrentImage();
  33234. }
  33235. else
  33236. {
  33237. imageToDraw = getToggleState() ? disabledImageOn
  33238. : disabledImage;
  33239. if (imageToDraw == 0)
  33240. {
  33241. g.setOpacity (0.4f);
  33242. imageToDraw = getNormalImage();
  33243. }
  33244. }
  33245. if (imageToDraw != 0)
  33246. {
  33247. if (style == ImageRaw)
  33248. {
  33249. imageToDraw->draw (g);
  33250. }
  33251. else
  33252. {
  33253. imageToDraw->drawWithin (g,
  33254. imageSpace.getX(),
  33255. imageSpace.getY(),
  33256. imageSpace.getWidth(),
  33257. imageSpace.getHeight(),
  33258. RectanglePlacement::centred);
  33259. }
  33260. }
  33261. }
  33262. const Drawable* DrawableButton::getCurrentImage() const throw()
  33263. {
  33264. if (isDown())
  33265. return getDownImage();
  33266. if (isOver())
  33267. return getOverImage();
  33268. return getNormalImage();
  33269. }
  33270. const Drawable* DrawableButton::getNormalImage() const throw()
  33271. {
  33272. return (getToggleState() && normalImageOn != 0) ? normalImageOn
  33273. : normalImage;
  33274. }
  33275. const Drawable* DrawableButton::getOverImage() const throw()
  33276. {
  33277. const Drawable* d = normalImage;
  33278. if (getToggleState())
  33279. {
  33280. if (overImageOn != 0)
  33281. d = overImageOn;
  33282. else if (normalImageOn != 0)
  33283. d = normalImageOn;
  33284. else if (overImage != 0)
  33285. d = overImage;
  33286. }
  33287. else
  33288. {
  33289. if (overImage != 0)
  33290. d = overImage;
  33291. }
  33292. return d;
  33293. }
  33294. const Drawable* DrawableButton::getDownImage() const throw()
  33295. {
  33296. const Drawable* d = normalImage;
  33297. if (getToggleState())
  33298. {
  33299. if (downImageOn != 0)
  33300. d = downImageOn;
  33301. else if (overImageOn != 0)
  33302. d = overImageOn;
  33303. else if (normalImageOn != 0)
  33304. d = normalImageOn;
  33305. else if (downImage != 0)
  33306. d = downImage;
  33307. else
  33308. d = getOverImage();
  33309. }
  33310. else
  33311. {
  33312. if (downImage != 0)
  33313. d = downImage;
  33314. else
  33315. d = getOverImage();
  33316. }
  33317. return d;
  33318. }
  33319. END_JUCE_NAMESPACE
  33320. /********* End of inlined file: juce_DrawableButton.cpp *********/
  33321. /********* Start of inlined file: juce_HyperlinkButton.cpp *********/
  33322. BEGIN_JUCE_NAMESPACE
  33323. HyperlinkButton::HyperlinkButton (const String& linkText,
  33324. const URL& linkURL)
  33325. : Button (linkText),
  33326. url (linkURL),
  33327. font (14.0f, Font::underlined),
  33328. resizeFont (true),
  33329. justification (Justification::centred)
  33330. {
  33331. setMouseCursor (MouseCursor::PointingHandCursor);
  33332. setTooltip (linkURL.toString (false));
  33333. }
  33334. HyperlinkButton::~HyperlinkButton()
  33335. {
  33336. }
  33337. void HyperlinkButton::setFont (const Font& newFont,
  33338. const bool resizeToMatchComponentHeight,
  33339. const Justification& justificationType)
  33340. {
  33341. font = newFont;
  33342. resizeFont = resizeToMatchComponentHeight;
  33343. justification = justificationType;
  33344. repaint();
  33345. }
  33346. void HyperlinkButton::setURL (const URL& newURL) throw()
  33347. {
  33348. url = newURL;
  33349. setTooltip (newURL.toString (false));
  33350. }
  33351. const Font HyperlinkButton::getFontToUse() const
  33352. {
  33353. Font f (font);
  33354. if (resizeFont)
  33355. f.setHeight (getHeight() * 0.7f);
  33356. return f;
  33357. }
  33358. void HyperlinkButton::changeWidthToFitText()
  33359. {
  33360. setSize (getFontToUse().getStringWidth (getName()) + 6, getHeight());
  33361. }
  33362. void HyperlinkButton::colourChanged()
  33363. {
  33364. repaint();
  33365. }
  33366. void HyperlinkButton::clicked()
  33367. {
  33368. if (url.isWellFormed())
  33369. url.launchInDefaultBrowser();
  33370. }
  33371. void HyperlinkButton::paintButton (Graphics& g,
  33372. bool isMouseOverButton,
  33373. bool isButtonDown)
  33374. {
  33375. const Colour textColour (findColour (textColourId));
  33376. if (isEnabled())
  33377. g.setColour ((isMouseOverButton) ? textColour.darker ((isButtonDown) ? 1.3f : 0.4f)
  33378. : textColour);
  33379. else
  33380. g.setColour (textColour.withMultipliedAlpha (0.4f));
  33381. g.setFont (getFontToUse());
  33382. g.drawText (getButtonText(),
  33383. 2, 0, getWidth() - 2, getHeight(),
  33384. justification.getOnlyHorizontalFlags() | Justification::verticallyCentred,
  33385. true);
  33386. }
  33387. END_JUCE_NAMESPACE
  33388. /********* End of inlined file: juce_HyperlinkButton.cpp *********/
  33389. /********* Start of inlined file: juce_ImageButton.cpp *********/
  33390. BEGIN_JUCE_NAMESPACE
  33391. ImageButton::ImageButton (const String& text)
  33392. : Button (text),
  33393. scaleImageToFit (true),
  33394. preserveProportions (true),
  33395. alphaThreshold (0),
  33396. imageX (0),
  33397. imageY (0),
  33398. imageW (0),
  33399. imageH (0),
  33400. normalImage (0),
  33401. overImage (0),
  33402. downImage (0)
  33403. {
  33404. }
  33405. ImageButton::~ImageButton()
  33406. {
  33407. deleteImages();
  33408. }
  33409. void ImageButton::deleteImages()
  33410. {
  33411. if (normalImage != 0)
  33412. {
  33413. if (ImageCache::isImageInCache (normalImage))
  33414. ImageCache::release (normalImage);
  33415. else
  33416. delete normalImage;
  33417. }
  33418. if (overImage != 0)
  33419. {
  33420. if (ImageCache::isImageInCache (overImage))
  33421. ImageCache::release (overImage);
  33422. else
  33423. delete overImage;
  33424. }
  33425. if (downImage != 0)
  33426. {
  33427. if (ImageCache::isImageInCache (downImage))
  33428. ImageCache::release (downImage);
  33429. else
  33430. delete downImage;
  33431. }
  33432. }
  33433. void ImageButton::setImages (const bool resizeButtonNowToFitThisImage,
  33434. const bool rescaleImagesWhenButtonSizeChanges,
  33435. const bool preserveImageProportions,
  33436. Image* const normalImage_,
  33437. const float imageOpacityWhenNormal,
  33438. const Colour& overlayColourWhenNormal,
  33439. Image* const overImage_,
  33440. const float imageOpacityWhenOver,
  33441. const Colour& overlayColourWhenOver,
  33442. Image* const downImage_,
  33443. const float imageOpacityWhenDown,
  33444. const Colour& overlayColourWhenDown,
  33445. const float hitTestAlphaThreshold)
  33446. {
  33447. deleteImages();
  33448. normalImage = normalImage_;
  33449. overImage = overImage_;
  33450. downImage = downImage_;
  33451. if (resizeButtonNowToFitThisImage && normalImage != 0)
  33452. {
  33453. imageW = normalImage->getWidth();
  33454. imageH = normalImage->getHeight();
  33455. setSize (imageW, imageH);
  33456. }
  33457. scaleImageToFit = rescaleImagesWhenButtonSizeChanges;
  33458. preserveProportions = preserveImageProportions;
  33459. normalOpacity = imageOpacityWhenNormal;
  33460. normalOverlay = overlayColourWhenNormal;
  33461. overOpacity = imageOpacityWhenOver;
  33462. overOverlay = overlayColourWhenOver;
  33463. downOpacity = imageOpacityWhenDown;
  33464. downOverlay = overlayColourWhenDown;
  33465. alphaThreshold = (unsigned char) jlimit (0, 0xff, roundFloatToInt (255.0f * hitTestAlphaThreshold));
  33466. repaint();
  33467. }
  33468. Image* ImageButton::getCurrentImage() const
  33469. {
  33470. if (isDown())
  33471. return getDownImage();
  33472. if (isOver())
  33473. return getOverImage();
  33474. return getNormalImage();
  33475. }
  33476. Image* ImageButton::getNormalImage() const throw()
  33477. {
  33478. return normalImage;
  33479. }
  33480. Image* ImageButton::getOverImage() const throw()
  33481. {
  33482. return (overImage != 0) ? overImage
  33483. : normalImage;
  33484. }
  33485. Image* ImageButton::getDownImage() const throw()
  33486. {
  33487. return (downImage != 0) ? downImage
  33488. : getOverImage();
  33489. }
  33490. void ImageButton::paintButton (Graphics& g,
  33491. bool isMouseOverButton,
  33492. bool isButtonDown)
  33493. {
  33494. if (! isEnabled())
  33495. {
  33496. isMouseOverButton = false;
  33497. isButtonDown = false;
  33498. }
  33499. Image* const im = getCurrentImage();
  33500. if (im != 0)
  33501. {
  33502. const int iw = im->getWidth();
  33503. const int ih = im->getHeight();
  33504. imageW = getWidth();
  33505. imageH = getHeight();
  33506. imageX = (imageW - iw) >> 1;
  33507. imageY = (imageH - ih) >> 1;
  33508. if (scaleImageToFit)
  33509. {
  33510. if (preserveProportions)
  33511. {
  33512. int newW, newH;
  33513. const float imRatio = ih / (float)iw;
  33514. const float destRatio = imageH / (float)imageW;
  33515. if (imRatio > destRatio)
  33516. {
  33517. newW = roundFloatToInt (imageH / imRatio);
  33518. newH = imageH;
  33519. }
  33520. else
  33521. {
  33522. newW = imageW;
  33523. newH = roundFloatToInt (imageW * imRatio);
  33524. }
  33525. imageX = (imageW - newW) / 2;
  33526. imageY = (imageH - newH) / 2;
  33527. imageW = newW;
  33528. imageH = newH;
  33529. }
  33530. else
  33531. {
  33532. imageX = 0;
  33533. imageY = 0;
  33534. }
  33535. }
  33536. const Colour& overlayColour = (isButtonDown) ? downOverlay
  33537. : ((isMouseOverButton) ? overOverlay
  33538. : normalOverlay);
  33539. if (! overlayColour.isOpaque())
  33540. {
  33541. g.setOpacity ((isButtonDown) ? downOpacity
  33542. : ((isMouseOverButton) ? overOpacity
  33543. : normalOpacity));
  33544. if (scaleImageToFit)
  33545. g.drawImage (im, imageX, imageY, imageW, imageH, 0, 0, iw, ih, false);
  33546. else
  33547. g.drawImageAt (im, imageX, imageY, false);
  33548. }
  33549. if (! overlayColour.isTransparent())
  33550. {
  33551. g.setColour (overlayColour);
  33552. if (scaleImageToFit)
  33553. g.drawImage (im, imageX, imageY, imageW, imageH, 0, 0, iw, ih, true);
  33554. else
  33555. g.drawImageAt (im, imageX, imageY, true);
  33556. }
  33557. }
  33558. }
  33559. bool ImageButton::hitTest (int x, int y)
  33560. {
  33561. if (alphaThreshold == 0)
  33562. return true;
  33563. Image* const im = getCurrentImage();
  33564. return im == 0
  33565. || (imageW > 0 && imageH > 0
  33566. && alphaThreshold < im->getPixelAt (((x - imageX) * im->getWidth()) / imageW,
  33567. ((y - imageY) * im->getHeight()) / imageH).getAlpha());
  33568. }
  33569. END_JUCE_NAMESPACE
  33570. /********* End of inlined file: juce_ImageButton.cpp *********/
  33571. /********* Start of inlined file: juce_ShapeButton.cpp *********/
  33572. BEGIN_JUCE_NAMESPACE
  33573. ShapeButton::ShapeButton (const String& text,
  33574. const Colour& normalColour_,
  33575. const Colour& overColour_,
  33576. const Colour& downColour_)
  33577. : Button (text),
  33578. normalColour (normalColour_),
  33579. overColour (overColour_),
  33580. downColour (downColour_),
  33581. maintainShapeProportions (false),
  33582. outlineWidth (0.0f)
  33583. {
  33584. }
  33585. ShapeButton::~ShapeButton()
  33586. {
  33587. }
  33588. void ShapeButton::setColours (const Colour& newNormalColour,
  33589. const Colour& newOverColour,
  33590. const Colour& newDownColour)
  33591. {
  33592. normalColour = newNormalColour;
  33593. overColour = newOverColour;
  33594. downColour = newDownColour;
  33595. }
  33596. void ShapeButton::setOutline (const Colour& newOutlineColour,
  33597. const float newOutlineWidth)
  33598. {
  33599. outlineColour = newOutlineColour;
  33600. outlineWidth = newOutlineWidth;
  33601. }
  33602. void ShapeButton::setShape (const Path& newShape,
  33603. const bool resizeNowToFitThisShape,
  33604. const bool maintainShapeProportions_,
  33605. const bool hasShadow)
  33606. {
  33607. shape = newShape;
  33608. maintainShapeProportions = maintainShapeProportions_;
  33609. shadow.setShadowProperties (3.0f, 0.5f, 0, 0);
  33610. setComponentEffect ((hasShadow) ? &shadow : 0);
  33611. if (resizeNowToFitThisShape)
  33612. {
  33613. float x, y, w, h;
  33614. shape.getBounds (x, y, w, h);
  33615. shape.applyTransform (AffineTransform::translation (-x, -y));
  33616. if (hasShadow)
  33617. {
  33618. w += 4.0f;
  33619. h += 4.0f;
  33620. shape.applyTransform (AffineTransform::translation (2.0f, 2.0f));
  33621. }
  33622. setSize (1 + (int) (w + outlineWidth),
  33623. 1 + (int) (h + outlineWidth));
  33624. }
  33625. }
  33626. void ShapeButton::paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  33627. {
  33628. if (! isEnabled())
  33629. {
  33630. isMouseOverButton = false;
  33631. isButtonDown = false;
  33632. }
  33633. g.setColour ((isButtonDown) ? downColour
  33634. : (isMouseOverButton) ? overColour
  33635. : normalColour);
  33636. int w = getWidth();
  33637. int h = getHeight();
  33638. if (getComponentEffect() != 0)
  33639. {
  33640. w -= 4;
  33641. h -= 4;
  33642. }
  33643. const float offset = (outlineWidth * 0.5f) + (isButtonDown ? 1.5f : 0.0f);
  33644. const AffineTransform trans (shape.getTransformToScaleToFit (offset, offset,
  33645. w - offset - outlineWidth,
  33646. h - offset - outlineWidth,
  33647. maintainShapeProportions));
  33648. g.fillPath (shape, trans);
  33649. if (outlineWidth > 0.0f)
  33650. {
  33651. g.setColour (outlineColour);
  33652. g.strokePath (shape, PathStrokeType (outlineWidth), trans);
  33653. }
  33654. }
  33655. END_JUCE_NAMESPACE
  33656. /********* End of inlined file: juce_ShapeButton.cpp *********/
  33657. /********* Start of inlined file: juce_TextButton.cpp *********/
  33658. BEGIN_JUCE_NAMESPACE
  33659. TextButton::TextButton (const String& name,
  33660. const String& toolTip)
  33661. : Button (name)
  33662. {
  33663. setTooltip (toolTip);
  33664. }
  33665. TextButton::~TextButton()
  33666. {
  33667. }
  33668. void TextButton::paintButton (Graphics& g,
  33669. bool isMouseOverButton,
  33670. bool isButtonDown)
  33671. {
  33672. getLookAndFeel().drawButtonBackground (g, *this,
  33673. findColour (getToggleState() ? buttonOnColourId
  33674. : buttonColourId),
  33675. isMouseOverButton,
  33676. isButtonDown);
  33677. getLookAndFeel().drawButtonText (g, *this,
  33678. isMouseOverButton,
  33679. isButtonDown);
  33680. }
  33681. void TextButton::colourChanged()
  33682. {
  33683. repaint();
  33684. }
  33685. const Font TextButton::getFont()
  33686. {
  33687. return Font (jmin (15.0f, getHeight() * 0.6f));
  33688. }
  33689. void TextButton::changeWidthToFitText (const int newHeight)
  33690. {
  33691. if (newHeight >= 0)
  33692. setSize (jmax (1, getWidth()), newHeight);
  33693. setSize (getFont().getStringWidth (getButtonText()) + getHeight(),
  33694. getHeight());
  33695. }
  33696. END_JUCE_NAMESPACE
  33697. /********* End of inlined file: juce_TextButton.cpp *********/
  33698. /********* Start of inlined file: juce_ToggleButton.cpp *********/
  33699. BEGIN_JUCE_NAMESPACE
  33700. ToggleButton::ToggleButton (const String& buttonText)
  33701. : Button (buttonText)
  33702. {
  33703. setClickingTogglesState (true);
  33704. }
  33705. ToggleButton::~ToggleButton()
  33706. {
  33707. }
  33708. void ToggleButton::paintButton (Graphics& g,
  33709. bool isMouseOverButton,
  33710. bool isButtonDown)
  33711. {
  33712. getLookAndFeel().drawToggleButton (g, *this,
  33713. isMouseOverButton,
  33714. isButtonDown);
  33715. }
  33716. void ToggleButton::changeWidthToFitText()
  33717. {
  33718. getLookAndFeel().changeToggleButtonWidthToFitText (*this);
  33719. }
  33720. void ToggleButton::colourChanged()
  33721. {
  33722. repaint();
  33723. }
  33724. END_JUCE_NAMESPACE
  33725. /********* End of inlined file: juce_ToggleButton.cpp *********/
  33726. /********* Start of inlined file: juce_ToolbarButton.cpp *********/
  33727. BEGIN_JUCE_NAMESPACE
  33728. ToolbarButton::ToolbarButton (const int itemId,
  33729. const String& buttonText,
  33730. Drawable* const normalImage_,
  33731. Drawable* const toggledOnImage_)
  33732. : ToolbarItemComponent (itemId, buttonText, true),
  33733. normalImage (normalImage_),
  33734. toggledOnImage (toggledOnImage_)
  33735. {
  33736. }
  33737. ToolbarButton::~ToolbarButton()
  33738. {
  33739. delete normalImage;
  33740. delete toggledOnImage;
  33741. }
  33742. bool ToolbarButton::getToolbarItemSizes (int toolbarDepth,
  33743. bool /*isToolbarVertical*/,
  33744. int& preferredSize,
  33745. int& minSize, int& maxSize)
  33746. {
  33747. preferredSize = minSize = maxSize = toolbarDepth;
  33748. return true;
  33749. }
  33750. void ToolbarButton::paintButtonArea (Graphics& g,
  33751. int width, int height,
  33752. bool /*isMouseOver*/,
  33753. bool /*isMouseDown*/)
  33754. {
  33755. Drawable* d = normalImage;
  33756. if (getToggleState() && toggledOnImage != 0)
  33757. d = toggledOnImage;
  33758. if (! isEnabled())
  33759. {
  33760. Image im (Image::ARGB, width, height, true);
  33761. Graphics g2 (im);
  33762. d->drawWithin (g2, 0, 0, width, height, RectanglePlacement::centred);
  33763. im.desaturate();
  33764. g.drawImageAt (&im, 0, 0);
  33765. }
  33766. else
  33767. {
  33768. d->drawWithin (g, 0, 0, width, height, RectanglePlacement::centred);
  33769. }
  33770. }
  33771. void ToolbarButton::contentAreaChanged (const Rectangle&)
  33772. {
  33773. }
  33774. END_JUCE_NAMESPACE
  33775. /********* End of inlined file: juce_ToolbarButton.cpp *********/
  33776. /********* Start of inlined file: juce_ComboBox.cpp *********/
  33777. BEGIN_JUCE_NAMESPACE
  33778. ComboBox::ComboBox (const String& name)
  33779. : Component (name),
  33780. items (4),
  33781. currentIndex (-1),
  33782. isButtonDown (false),
  33783. separatorPending (false),
  33784. menuActive (false),
  33785. listeners (2),
  33786. label (0)
  33787. {
  33788. noChoicesMessage = TRANS("(no choices)");
  33789. setRepaintsOnMouseActivity (true);
  33790. lookAndFeelChanged();
  33791. }
  33792. ComboBox::~ComboBox()
  33793. {
  33794. if (menuActive)
  33795. PopupMenu::dismissAllActiveMenus();
  33796. deleteAllChildren();
  33797. }
  33798. void ComboBox::setEditableText (const bool isEditable)
  33799. {
  33800. label->setEditable (isEditable, isEditable, false);
  33801. setWantsKeyboardFocus (! isEditable);
  33802. resized();
  33803. }
  33804. bool ComboBox::isTextEditable() const throw()
  33805. {
  33806. return label->isEditable();
  33807. }
  33808. void ComboBox::setJustificationType (const Justification& justification) throw()
  33809. {
  33810. label->setJustificationType (justification);
  33811. }
  33812. const Justification ComboBox::getJustificationType() const throw()
  33813. {
  33814. return label->getJustificationType();
  33815. }
  33816. void ComboBox::setTooltip (const String& newTooltip)
  33817. {
  33818. SettableTooltipClient::setTooltip (newTooltip);
  33819. label->setTooltip (newTooltip);
  33820. }
  33821. void ComboBox::addItem (const String& newItemText,
  33822. const int newItemId) throw()
  33823. {
  33824. // you can't add empty strings to the list..
  33825. jassert (newItemText.isNotEmpty());
  33826. // IDs must be non-zero, as zero is used to indicate a lack of selecion.
  33827. jassert (newItemId != 0);
  33828. // you shouldn't use duplicate item IDs!
  33829. jassert (getItemForId (newItemId) == 0);
  33830. if (newItemText.isNotEmpty() && newItemId != 0)
  33831. {
  33832. if (separatorPending)
  33833. {
  33834. separatorPending = false;
  33835. ItemInfo* const item = new ItemInfo();
  33836. item->itemId = 0;
  33837. item->isEnabled = false;
  33838. item->isHeading = false;
  33839. items.add (item);
  33840. }
  33841. ItemInfo* const item = new ItemInfo();
  33842. item->name = newItemText;
  33843. item->itemId = newItemId;
  33844. item->isEnabled = true;
  33845. item->isHeading = false;
  33846. items.add (item);
  33847. }
  33848. }
  33849. void ComboBox::addSeparator() throw()
  33850. {
  33851. separatorPending = (items.size() > 0);
  33852. }
  33853. void ComboBox::addSectionHeading (const String& headingName) throw()
  33854. {
  33855. // you can't add empty strings to the list..
  33856. jassert (headingName.isNotEmpty());
  33857. if (headingName.isNotEmpty())
  33858. {
  33859. if (separatorPending)
  33860. {
  33861. separatorPending = false;
  33862. ItemInfo* const item = new ItemInfo();
  33863. item->itemId = 0;
  33864. item->isEnabled = false;
  33865. item->isHeading = false;
  33866. items.add (item);
  33867. }
  33868. ItemInfo* const item = new ItemInfo();
  33869. item->name = headingName;
  33870. item->itemId = 0;
  33871. item->isEnabled = true;
  33872. item->isHeading = true;
  33873. items.add (item);
  33874. }
  33875. }
  33876. void ComboBox::setItemEnabled (const int itemId,
  33877. const bool isEnabled) throw()
  33878. {
  33879. ItemInfo* const item = getItemForId (itemId);
  33880. if (item != 0)
  33881. item->isEnabled = isEnabled;
  33882. }
  33883. void ComboBox::changeItemText (const int itemId,
  33884. const String& newText) throw()
  33885. {
  33886. ItemInfo* const item = getItemForId (itemId);
  33887. jassert (item != 0);
  33888. if (item != 0)
  33889. item->name = newText;
  33890. }
  33891. void ComboBox::clear (const bool dontSendChangeMessage)
  33892. {
  33893. items.clear();
  33894. separatorPending = false;
  33895. if (! label->isEditable())
  33896. setSelectedItemIndex (-1, dontSendChangeMessage);
  33897. }
  33898. ComboBox::ItemInfo* ComboBox::getItemForId (const int itemId) const throw()
  33899. {
  33900. jassert (itemId != 0);
  33901. if (itemId != 0)
  33902. {
  33903. for (int i = items.size(); --i >= 0;)
  33904. if (items.getUnchecked(i)->itemId == itemId)
  33905. return items.getUnchecked(i);
  33906. }
  33907. return 0;
  33908. }
  33909. ComboBox::ItemInfo* ComboBox::getItemForIndex (const int index) const throw()
  33910. {
  33911. int n = 0;
  33912. for (int i = 0; i < items.size(); ++i)
  33913. {
  33914. ItemInfo* const item = items.getUnchecked(i);
  33915. if (item->isRealItem())
  33916. {
  33917. if (n++ == index)
  33918. return item;
  33919. }
  33920. }
  33921. return 0;
  33922. }
  33923. int ComboBox::getNumItems() const throw()
  33924. {
  33925. int n = 0;
  33926. for (int i = items.size(); --i >= 0;)
  33927. {
  33928. ItemInfo* const item = items.getUnchecked(i);
  33929. if (item->isRealItem())
  33930. ++n;
  33931. }
  33932. return n;
  33933. }
  33934. const String ComboBox::getItemText (const int index) const throw()
  33935. {
  33936. ItemInfo* const item = getItemForIndex (index);
  33937. if (item != 0)
  33938. return item->name;
  33939. return String::empty;
  33940. }
  33941. int ComboBox::getItemId (const int index) const throw()
  33942. {
  33943. ItemInfo* const item = getItemForIndex (index);
  33944. return (item != 0) ? item->itemId : 0;
  33945. }
  33946. bool ComboBox::ItemInfo::isSeparator() const throw()
  33947. {
  33948. return name.isEmpty();
  33949. }
  33950. bool ComboBox::ItemInfo::isRealItem() const throw()
  33951. {
  33952. return ! (isHeading || name.isEmpty());
  33953. }
  33954. int ComboBox::getSelectedItemIndex() const throw()
  33955. {
  33956. return (currentIndex >= 0 && getText() == getItemText (currentIndex))
  33957. ? currentIndex
  33958. : -1;
  33959. }
  33960. void ComboBox::setSelectedItemIndex (const int index,
  33961. const bool dontSendChangeMessage) throw()
  33962. {
  33963. if (currentIndex != index || label->getText() != getItemText (currentIndex))
  33964. {
  33965. if (((unsigned int) index) < (unsigned int) getNumItems())
  33966. currentIndex = index;
  33967. else
  33968. currentIndex = -1;
  33969. label->setText (getItemText (currentIndex), false);
  33970. if (! dontSendChangeMessage)
  33971. triggerAsyncUpdate();
  33972. }
  33973. }
  33974. void ComboBox::setSelectedId (const int newItemId,
  33975. const bool dontSendChangeMessage) throw()
  33976. {
  33977. for (int i = getNumItems(); --i >= 0;)
  33978. {
  33979. if (getItemId(i) == newItemId)
  33980. {
  33981. setSelectedItemIndex (i, dontSendChangeMessage);
  33982. break;
  33983. }
  33984. }
  33985. }
  33986. int ComboBox::getSelectedId() const throw()
  33987. {
  33988. const ItemInfo* const item = getItemForIndex (currentIndex);
  33989. return (item != 0 && getText() == item->name)
  33990. ? item->itemId
  33991. : 0;
  33992. }
  33993. void ComboBox::addListener (ComboBoxListener* const listener) throw()
  33994. {
  33995. jassert (listener != 0);
  33996. if (listener != 0)
  33997. listeners.add (listener);
  33998. }
  33999. void ComboBox::removeListener (ComboBoxListener* const listener) throw()
  34000. {
  34001. listeners.removeValue (listener);
  34002. }
  34003. void ComboBox::handleAsyncUpdate()
  34004. {
  34005. for (int i = listeners.size(); --i >= 0;)
  34006. {
  34007. ((ComboBoxListener*) listeners.getUnchecked (i))->comboBoxChanged (this);
  34008. i = jmin (i, listeners.size());
  34009. }
  34010. }
  34011. const String ComboBox::getText() const throw()
  34012. {
  34013. return label->getText();
  34014. }
  34015. void ComboBox::setText (const String& newText,
  34016. const bool dontSendChangeMessage) throw()
  34017. {
  34018. for (int i = items.size(); --i >= 0;)
  34019. {
  34020. ItemInfo* const item = items.getUnchecked(i);
  34021. if (item->isRealItem()
  34022. && item->name == newText)
  34023. {
  34024. setSelectedId (item->itemId, dontSendChangeMessage);
  34025. return;
  34026. }
  34027. }
  34028. currentIndex = -1;
  34029. if (label->getText() != newText)
  34030. {
  34031. label->setText (newText, false);
  34032. if (! dontSendChangeMessage)
  34033. triggerAsyncUpdate();
  34034. }
  34035. repaint();
  34036. }
  34037. void ComboBox::showEditor()
  34038. {
  34039. jassert (isTextEditable()); // you probably shouldn't do this to a non-editable combo box?
  34040. label->showEditor();
  34041. }
  34042. void ComboBox::setTextWhenNothingSelected (const String& newMessage) throw()
  34043. {
  34044. textWhenNothingSelected = newMessage;
  34045. repaint();
  34046. }
  34047. const String ComboBox::getTextWhenNothingSelected() const throw()
  34048. {
  34049. return textWhenNothingSelected;
  34050. }
  34051. void ComboBox::setTextWhenNoChoicesAvailable (const String& newMessage) throw()
  34052. {
  34053. noChoicesMessage = newMessage;
  34054. }
  34055. const String ComboBox::getTextWhenNoChoicesAvailable() const throw()
  34056. {
  34057. return noChoicesMessage;
  34058. }
  34059. void ComboBox::paint (Graphics& g)
  34060. {
  34061. getLookAndFeel().drawComboBox (g,
  34062. getWidth(),
  34063. getHeight(),
  34064. isButtonDown,
  34065. label->getRight(),
  34066. 0,
  34067. getWidth() - label->getRight(),
  34068. getHeight(),
  34069. *this);
  34070. if (textWhenNothingSelected.isNotEmpty()
  34071. && label->getText().isEmpty()
  34072. && ! label->isBeingEdited())
  34073. {
  34074. g.setColour (findColour (textColourId).withMultipliedAlpha (0.5f));
  34075. g.setFont (label->getFont());
  34076. g.drawFittedText (textWhenNothingSelected,
  34077. label->getX() + 2, label->getY() + 1,
  34078. label->getWidth() - 4, label->getHeight() - 2,
  34079. label->getJustificationType(),
  34080. jmax (1, (int) (label->getHeight() / label->getFont().getHeight())));
  34081. }
  34082. }
  34083. void ComboBox::resized()
  34084. {
  34085. if (getHeight() > 0 && getWidth() > 0)
  34086. getLookAndFeel().positionComboBoxText (*this, *label);
  34087. }
  34088. void ComboBox::enablementChanged()
  34089. {
  34090. repaint();
  34091. }
  34092. void ComboBox::lookAndFeelChanged()
  34093. {
  34094. repaint();
  34095. Label* const newLabel = getLookAndFeel().createComboBoxTextBox (*this);
  34096. if (label != 0)
  34097. {
  34098. newLabel->setEditable (label->isEditable());
  34099. newLabel->setJustificationType (label->getJustificationType());
  34100. newLabel->setTooltip (label->getTooltip());
  34101. newLabel->setText (label->getText(), false);
  34102. }
  34103. delete label;
  34104. label = newLabel;
  34105. addAndMakeVisible (newLabel);
  34106. newLabel->addListener (this);
  34107. newLabel->addMouseListener (this, false);
  34108. newLabel->setColour (Label::backgroundColourId, Colours::transparentBlack);
  34109. newLabel->setColour (Label::textColourId, findColour (ComboBox::textColourId));
  34110. newLabel->setColour (TextEditor::textColourId, findColour (ComboBox::textColourId));
  34111. newLabel->setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  34112. newLabel->setColour (TextEditor::highlightColourId, findColour (TextEditor::highlightColourId));
  34113. newLabel->setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  34114. resized();
  34115. }
  34116. void ComboBox::colourChanged()
  34117. {
  34118. lookAndFeelChanged();
  34119. }
  34120. bool ComboBox::keyPressed (const KeyPress& key)
  34121. {
  34122. bool used = false;
  34123. if (key.isKeyCode (KeyPress::upKey)
  34124. || key.isKeyCode (KeyPress::leftKey))
  34125. {
  34126. setSelectedItemIndex (jmax (0, currentIndex - 1));
  34127. used = true;
  34128. }
  34129. else if (key.isKeyCode (KeyPress::downKey)
  34130. || key.isKeyCode (KeyPress::rightKey))
  34131. {
  34132. setSelectedItemIndex (jmin (currentIndex + 1, getNumItems() - 1));
  34133. used = true;
  34134. }
  34135. else if (key.isKeyCode (KeyPress::returnKey))
  34136. {
  34137. showPopup();
  34138. used = true;
  34139. }
  34140. return used;
  34141. }
  34142. bool ComboBox::keyStateChanged()
  34143. {
  34144. // only forward key events that aren't used by this component
  34145. return KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  34146. || KeyPress::isKeyCurrentlyDown (KeyPress::leftKey)
  34147. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  34148. || KeyPress::isKeyCurrentlyDown (KeyPress::rightKey);
  34149. }
  34150. void ComboBox::focusGained (FocusChangeType)
  34151. {
  34152. repaint();
  34153. }
  34154. void ComboBox::focusLost (FocusChangeType)
  34155. {
  34156. repaint();
  34157. }
  34158. void ComboBox::labelTextChanged (Label*)
  34159. {
  34160. triggerAsyncUpdate();
  34161. }
  34162. void ComboBox::showPopup()
  34163. {
  34164. if (! menuActive)
  34165. {
  34166. const int currentId = getSelectedId();
  34167. ComponentDeletionWatcher deletionWatcher (this);
  34168. PopupMenu menu;
  34169. menu.setLookAndFeel (&getLookAndFeel());
  34170. for (int i = 0; i < items.size(); ++i)
  34171. {
  34172. const ItemInfo* const item = items.getUnchecked(i);
  34173. if (item->isSeparator())
  34174. menu.addSeparator();
  34175. else if (item->isHeading)
  34176. menu.addSectionHeader (item->name);
  34177. else
  34178. menu.addItem (item->itemId, item->name,
  34179. item->isEnabled, item->itemId == currentId);
  34180. }
  34181. if (items.size() == 0)
  34182. menu.addItem (1, noChoicesMessage, false);
  34183. const int itemHeight = jlimit (12, 24, getHeight());
  34184. menuActive = true;
  34185. const int resultId = menu.showAt (this, currentId,
  34186. getWidth(), 1, itemHeight);
  34187. if (deletionWatcher.hasBeenDeleted())
  34188. return;
  34189. menuActive = false;
  34190. if (resultId != 0)
  34191. setSelectedId (resultId);
  34192. }
  34193. }
  34194. void ComboBox::mouseDown (const MouseEvent& e)
  34195. {
  34196. beginDragAutoRepeat (300);
  34197. isButtonDown = isEnabled();
  34198. if (isButtonDown
  34199. && (e.eventComponent == this || ! label->isEditable()))
  34200. {
  34201. showPopup();
  34202. }
  34203. }
  34204. void ComboBox::mouseDrag (const MouseEvent& e)
  34205. {
  34206. beginDragAutoRepeat (50);
  34207. if (isButtonDown && ! e.mouseWasClicked())
  34208. showPopup();
  34209. }
  34210. void ComboBox::mouseUp (const MouseEvent& e2)
  34211. {
  34212. if (isButtonDown)
  34213. {
  34214. isButtonDown = false;
  34215. repaint();
  34216. const MouseEvent e (e2.getEventRelativeTo (this));
  34217. if (reallyContains (e.x, e.y, true)
  34218. && (e2.eventComponent == this || ! label->isEditable()))
  34219. {
  34220. showPopup();
  34221. }
  34222. }
  34223. }
  34224. END_JUCE_NAMESPACE
  34225. /********* End of inlined file: juce_ComboBox.cpp *********/
  34226. /********* Start of inlined file: juce_Label.cpp *********/
  34227. BEGIN_JUCE_NAMESPACE
  34228. Label::Label (const String& componentName,
  34229. const String& labelText)
  34230. : Component (componentName),
  34231. text (labelText),
  34232. font (15.0f),
  34233. justification (Justification::centredLeft),
  34234. editor (0),
  34235. listeners (2),
  34236. ownerComponent (0),
  34237. deletionWatcher (0),
  34238. horizontalBorderSize (3),
  34239. verticalBorderSize (1),
  34240. minimumHorizontalScale (0.7f),
  34241. editSingleClick (false),
  34242. editDoubleClick (false),
  34243. lossOfFocusDiscardsChanges (false)
  34244. {
  34245. setColour (TextEditor::textColourId, Colours::black);
  34246. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  34247. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  34248. }
  34249. Label::~Label()
  34250. {
  34251. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  34252. ownerComponent->removeComponentListener (this);
  34253. deleteAndZero (deletionWatcher);
  34254. if (editor != 0)
  34255. delete editor;
  34256. }
  34257. void Label::setText (const String& newText,
  34258. const bool broadcastChangeMessage)
  34259. {
  34260. hideEditor (true);
  34261. if (text != newText)
  34262. {
  34263. text = newText;
  34264. if (broadcastChangeMessage)
  34265. triggerAsyncUpdate();
  34266. repaint();
  34267. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  34268. componentMovedOrResized (*ownerComponent, true, true);
  34269. }
  34270. }
  34271. const String Label::getText (const bool returnActiveEditorContents) const throw()
  34272. {
  34273. return (returnActiveEditorContents && isBeingEdited())
  34274. ? editor->getText()
  34275. : text;
  34276. }
  34277. void Label::setFont (const Font& newFont) throw()
  34278. {
  34279. font = newFont;
  34280. repaint();
  34281. }
  34282. const Font& Label::getFont() const throw()
  34283. {
  34284. return font;
  34285. }
  34286. void Label::setEditable (const bool editOnSingleClick,
  34287. const bool editOnDoubleClick,
  34288. const bool lossOfFocusDiscardsChanges_) throw()
  34289. {
  34290. editSingleClick = editOnSingleClick;
  34291. editDoubleClick = editOnDoubleClick;
  34292. lossOfFocusDiscardsChanges = lossOfFocusDiscardsChanges_;
  34293. setWantsKeyboardFocus (editOnSingleClick || editOnDoubleClick);
  34294. setFocusContainer (editOnSingleClick || editOnDoubleClick);
  34295. }
  34296. void Label::setJustificationType (const Justification& justification_) throw()
  34297. {
  34298. justification = justification_;
  34299. repaint();
  34300. }
  34301. void Label::setBorderSize (int h, int v)
  34302. {
  34303. horizontalBorderSize = h;
  34304. verticalBorderSize = v;
  34305. repaint();
  34306. }
  34307. void Label::attachToComponent (Component* owner,
  34308. const bool onLeft)
  34309. {
  34310. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  34311. ownerComponent->removeComponentListener (this);
  34312. deleteAndZero (deletionWatcher);
  34313. ownerComponent = owner;
  34314. leftOfOwnerComp = onLeft;
  34315. if (ownerComponent != 0)
  34316. {
  34317. deletionWatcher = new ComponentDeletionWatcher (owner);
  34318. setVisible (owner->isVisible());
  34319. ownerComponent->addComponentListener (this);
  34320. componentParentHierarchyChanged (*ownerComponent);
  34321. componentMovedOrResized (*ownerComponent, true, true);
  34322. }
  34323. }
  34324. void Label::componentMovedOrResized (Component& component,
  34325. bool /*wasMoved*/,
  34326. bool /*wasResized*/)
  34327. {
  34328. if (leftOfOwnerComp)
  34329. {
  34330. setSize (jmin (getFont().getStringWidth (text) + 8, component.getX()),
  34331. component.getHeight());
  34332. setTopRightPosition (component.getX(), component.getY());
  34333. }
  34334. else
  34335. {
  34336. setSize (component.getWidth(),
  34337. 8 + roundFloatToInt (getFont().getHeight()));
  34338. setTopLeftPosition (component.getX(), component.getY() - getHeight());
  34339. }
  34340. }
  34341. void Label::componentParentHierarchyChanged (Component& component)
  34342. {
  34343. if (component.getParentComponent() != 0)
  34344. component.getParentComponent()->addChildComponent (this);
  34345. }
  34346. void Label::componentVisibilityChanged (Component& component)
  34347. {
  34348. setVisible (component.isVisible());
  34349. }
  34350. void Label::textWasEdited()
  34351. {
  34352. }
  34353. void Label::showEditor()
  34354. {
  34355. if (editor == 0)
  34356. {
  34357. addAndMakeVisible (editor = createEditorComponent());
  34358. editor->setText (getText());
  34359. editor->addListener (this);
  34360. editor->grabKeyboardFocus();
  34361. editor->setHighlightedRegion (0, text.length());
  34362. editor->addListener (this);
  34363. resized();
  34364. repaint();
  34365. enterModalState();
  34366. editor->grabKeyboardFocus();
  34367. }
  34368. }
  34369. bool Label::updateFromTextEditorContents()
  34370. {
  34371. jassert (editor != 0);
  34372. const String newText (editor->getText());
  34373. if (text != newText)
  34374. {
  34375. text = newText;
  34376. triggerAsyncUpdate();
  34377. repaint();
  34378. if (ownerComponent != 0 && ! deletionWatcher->hasBeenDeleted())
  34379. componentMovedOrResized (*ownerComponent, true, true);
  34380. return true;
  34381. }
  34382. return false;
  34383. }
  34384. void Label::hideEditor (const bool discardCurrentEditorContents)
  34385. {
  34386. if (editor != 0)
  34387. {
  34388. const bool changed = (! discardCurrentEditorContents)
  34389. && updateFromTextEditorContents();
  34390. deleteAndZero (editor);
  34391. repaint();
  34392. if (changed)
  34393. textWasEdited();
  34394. exitModalState (0);
  34395. }
  34396. }
  34397. void Label::inputAttemptWhenModal()
  34398. {
  34399. if (editor != 0)
  34400. {
  34401. if (lossOfFocusDiscardsChanges)
  34402. textEditorEscapeKeyPressed (*editor);
  34403. else
  34404. textEditorReturnKeyPressed (*editor);
  34405. }
  34406. }
  34407. bool Label::isBeingEdited() const throw()
  34408. {
  34409. return editor != 0;
  34410. }
  34411. TextEditor* Label::createEditorComponent()
  34412. {
  34413. TextEditor* const ed = new TextEditor (getName());
  34414. ed->setFont (font);
  34415. // copy these colours from our own settings..
  34416. const int cols[] = { TextEditor::backgroundColourId,
  34417. TextEditor::textColourId,
  34418. TextEditor::highlightColourId,
  34419. TextEditor::highlightedTextColourId,
  34420. TextEditor::caretColourId,
  34421. TextEditor::outlineColourId,
  34422. TextEditor::focusedOutlineColourId,
  34423. TextEditor::shadowColourId };
  34424. for (int i = 0; i < numElementsInArray (cols); ++i)
  34425. ed->setColour (cols[i], findColour (cols[i]));
  34426. return ed;
  34427. }
  34428. void Label::paint (Graphics& g)
  34429. {
  34430. getLookAndFeel().drawLabel (g, *this);
  34431. }
  34432. void Label::mouseUp (const MouseEvent& e)
  34433. {
  34434. if (editSingleClick
  34435. && e.mouseWasClicked()
  34436. && contains (e.x, e.y)
  34437. && ! e.mods.isPopupMenu())
  34438. {
  34439. showEditor();
  34440. }
  34441. }
  34442. void Label::mouseDoubleClick (const MouseEvent& e)
  34443. {
  34444. if (editDoubleClick && ! e.mods.isPopupMenu())
  34445. showEditor();
  34446. }
  34447. void Label::resized()
  34448. {
  34449. if (editor != 0)
  34450. editor->setBoundsInset (BorderSize (0));
  34451. }
  34452. void Label::focusGained (FocusChangeType cause)
  34453. {
  34454. if (editSingleClick && cause == focusChangedByTabKey)
  34455. showEditor();
  34456. }
  34457. void Label::enablementChanged()
  34458. {
  34459. repaint();
  34460. }
  34461. void Label::colourChanged()
  34462. {
  34463. repaint();
  34464. }
  34465. // We'll use a custom focus traverser here to make sure focus goes from the
  34466. // text editor to another component rather than back to the label itself.
  34467. class LabelKeyboardFocusTraverser : public KeyboardFocusTraverser
  34468. {
  34469. public:
  34470. LabelKeyboardFocusTraverser() {}
  34471. Component* getNextComponent (Component* current)
  34472. {
  34473. return KeyboardFocusTraverser::getNextComponent (dynamic_cast <TextEditor*> (current) != 0
  34474. ? current->getParentComponent() : current);
  34475. }
  34476. Component* getPreviousComponent (Component* current)
  34477. {
  34478. return KeyboardFocusTraverser::getPreviousComponent (dynamic_cast <TextEditor*> (current) != 0
  34479. ? current->getParentComponent() : current);
  34480. }
  34481. };
  34482. KeyboardFocusTraverser* Label::createFocusTraverser()
  34483. {
  34484. return new LabelKeyboardFocusTraverser();
  34485. }
  34486. void Label::addListener (LabelListener* const listener) throw()
  34487. {
  34488. jassert (listener != 0);
  34489. if (listener != 0)
  34490. listeners.add (listener);
  34491. }
  34492. void Label::removeListener (LabelListener* const listener) throw()
  34493. {
  34494. listeners.removeValue (listener);
  34495. }
  34496. void Label::handleAsyncUpdate()
  34497. {
  34498. for (int i = listeners.size(); --i >= 0;)
  34499. {
  34500. ((LabelListener*) listeners.getUnchecked (i))->labelTextChanged (this);
  34501. i = jmin (i, listeners.size());
  34502. }
  34503. }
  34504. void Label::textEditorTextChanged (TextEditor& ed)
  34505. {
  34506. if (editor != 0)
  34507. {
  34508. jassert (&ed == editor);
  34509. if (! (hasKeyboardFocus (true) || isCurrentlyBlockedByAnotherModalComponent()))
  34510. {
  34511. if (lossOfFocusDiscardsChanges)
  34512. textEditorEscapeKeyPressed (ed);
  34513. else
  34514. textEditorReturnKeyPressed (ed);
  34515. }
  34516. }
  34517. }
  34518. void Label::textEditorReturnKeyPressed (TextEditor& ed)
  34519. {
  34520. if (editor != 0)
  34521. {
  34522. jassert (&ed == editor);
  34523. (void) ed;
  34524. const bool changed = updateFromTextEditorContents();
  34525. hideEditor (true);
  34526. if (changed)
  34527. textWasEdited();
  34528. }
  34529. }
  34530. void Label::textEditorEscapeKeyPressed (TextEditor& ed)
  34531. {
  34532. if (editor != 0)
  34533. {
  34534. jassert (&ed == editor);
  34535. (void) ed;
  34536. editor->setText (text, false);
  34537. hideEditor (true);
  34538. }
  34539. }
  34540. void Label::textEditorFocusLost (TextEditor& ed)
  34541. {
  34542. textEditorTextChanged (ed);
  34543. }
  34544. END_JUCE_NAMESPACE
  34545. /********* End of inlined file: juce_Label.cpp *********/
  34546. /********* Start of inlined file: juce_ListBox.cpp *********/
  34547. BEGIN_JUCE_NAMESPACE
  34548. class ListBoxRowComponent : public Component
  34549. {
  34550. public:
  34551. ListBoxRowComponent (ListBox& owner_)
  34552. : owner (owner_),
  34553. row (-1),
  34554. selected (false),
  34555. isDragging (false)
  34556. {
  34557. }
  34558. ~ListBoxRowComponent()
  34559. {
  34560. deleteAllChildren();
  34561. }
  34562. void paint (Graphics& g)
  34563. {
  34564. if (owner.getModel() != 0)
  34565. owner.getModel()->paintListBoxItem (row, g, getWidth(), getHeight(), selected);
  34566. }
  34567. void update (const int row_, const bool selected_)
  34568. {
  34569. if (row != row_ || selected != selected_)
  34570. {
  34571. repaint();
  34572. row = row_;
  34573. selected = selected_;
  34574. }
  34575. if (owner.getModel() != 0)
  34576. {
  34577. Component* const customComp = owner.getModel()->refreshComponentForRow (row_, selected_, getChildComponent (0));
  34578. if (customComp != 0)
  34579. {
  34580. addAndMakeVisible (customComp);
  34581. customComp->setBounds (0, 0, getWidth(), getHeight());
  34582. for (int i = getNumChildComponents(); --i >= 0;)
  34583. if (getChildComponent (i) != customComp)
  34584. delete getChildComponent (i);
  34585. }
  34586. else
  34587. {
  34588. deleteAllChildren();
  34589. }
  34590. }
  34591. }
  34592. void mouseDown (const MouseEvent& e)
  34593. {
  34594. isDragging = false;
  34595. selectRowOnMouseUp = false;
  34596. if (isEnabled())
  34597. {
  34598. if (! selected)
  34599. {
  34600. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  34601. if (owner.getModel() != 0)
  34602. owner.getModel()->listBoxItemClicked (row, e);
  34603. }
  34604. else
  34605. {
  34606. selectRowOnMouseUp = true;
  34607. }
  34608. }
  34609. }
  34610. void mouseUp (const MouseEvent& e)
  34611. {
  34612. if (isEnabled() && selectRowOnMouseUp && ! isDragging)
  34613. {
  34614. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  34615. if (owner.getModel() != 0)
  34616. owner.getModel()->listBoxItemClicked (row, e);
  34617. }
  34618. }
  34619. void mouseDoubleClick (const MouseEvent& e)
  34620. {
  34621. if (owner.getModel() != 0 && isEnabled())
  34622. owner.getModel()->listBoxItemDoubleClicked (row, e);
  34623. }
  34624. void mouseDrag (const MouseEvent& e)
  34625. {
  34626. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  34627. {
  34628. const SparseSet <int> selectedRows (owner.getSelectedRows());
  34629. if (selectedRows.size() > 0)
  34630. {
  34631. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  34632. if (dragDescription.isNotEmpty())
  34633. {
  34634. isDragging = true;
  34635. DragAndDropContainer* const dragContainer
  34636. = DragAndDropContainer::findParentDragContainerFor (this);
  34637. if (dragContainer != 0)
  34638. {
  34639. Image* dragImage = owner.createSnapshotOfSelectedRows();
  34640. dragImage->multiplyAllAlphas (0.6f);
  34641. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  34642. }
  34643. else
  34644. {
  34645. // to be able to do a drag-and-drop operation, the listbox needs to
  34646. // be inside a component which is also a DragAndDropContainer.
  34647. jassertfalse
  34648. }
  34649. }
  34650. }
  34651. }
  34652. }
  34653. void resized()
  34654. {
  34655. if (getNumChildComponents() > 0)
  34656. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  34657. }
  34658. juce_UseDebuggingNewOperator
  34659. bool neededFlag;
  34660. private:
  34661. ListBox& owner;
  34662. int row;
  34663. bool selected, isDragging, selectRowOnMouseUp;
  34664. ListBoxRowComponent (const ListBoxRowComponent&);
  34665. const ListBoxRowComponent& operator= (const ListBoxRowComponent&);
  34666. };
  34667. class ListViewport : public Viewport
  34668. {
  34669. public:
  34670. int firstIndex, firstWholeIndex, lastWholeIndex;
  34671. bool hasUpdated;
  34672. ListViewport (ListBox& owner_)
  34673. : owner (owner_)
  34674. {
  34675. setWantsKeyboardFocus (false);
  34676. setViewedComponent (new Component());
  34677. getViewedComponent()->addMouseListener (this, false);
  34678. getViewedComponent()->setWantsKeyboardFocus (false);
  34679. }
  34680. ~ListViewport()
  34681. {
  34682. getViewedComponent()->removeMouseListener (this);
  34683. getViewedComponent()->deleteAllChildren();
  34684. }
  34685. ListBoxRowComponent* getComponentForRow (const int row) const throw()
  34686. {
  34687. return (ListBoxRowComponent*) getViewedComponent()
  34688. ->getChildComponent (row % jmax (1, getViewedComponent()->getNumChildComponents()));
  34689. }
  34690. int getRowNumberOfComponent (Component* const rowComponent) const throw()
  34691. {
  34692. const int index = getIndexOfChildComponent (rowComponent);
  34693. const int num = getViewedComponent()->getNumChildComponents();
  34694. for (int i = num; --i >= 0;)
  34695. if (((firstIndex + i) % jmax (1, num)) == index)
  34696. return firstIndex + i;
  34697. return -1;
  34698. }
  34699. Component* getComponentForRowIfOnscreen (const int row) const throw()
  34700. {
  34701. return (row >= firstIndex && row < firstIndex + getViewedComponent()->getNumChildComponents())
  34702. ? getComponentForRow (row) : 0;
  34703. }
  34704. void visibleAreaChanged (int, int, int, int)
  34705. {
  34706. updateVisibleArea (true);
  34707. if (owner.getModel() != 0)
  34708. owner.getModel()->listWasScrolled();
  34709. }
  34710. void updateVisibleArea (const bool makeSureItUpdatesContent)
  34711. {
  34712. hasUpdated = false;
  34713. const int newX = getViewedComponent()->getX();
  34714. int newY = getViewedComponent()->getY();
  34715. const int newW = jmax (owner.minimumRowWidth, getMaximumVisibleWidth());
  34716. const int newH = owner.totalItems * owner.getRowHeight();
  34717. if (newY + newH < getMaximumVisibleHeight() && newH > getMaximumVisibleHeight())
  34718. newY = getMaximumVisibleHeight() - newH;
  34719. getViewedComponent()->setBounds (newX, newY, newW, newH);
  34720. if (makeSureItUpdatesContent && ! hasUpdated)
  34721. updateContents();
  34722. }
  34723. void updateContents()
  34724. {
  34725. hasUpdated = true;
  34726. const int rowHeight = owner.getRowHeight();
  34727. if (rowHeight > 0)
  34728. {
  34729. const int y = getViewPositionY();
  34730. const int w = getViewedComponent()->getWidth();
  34731. const int numNeeded = 2 + getMaximumVisibleHeight() / rowHeight;
  34732. while (numNeeded > getViewedComponent()->getNumChildComponents())
  34733. getViewedComponent()->addAndMakeVisible (new ListBoxRowComponent (owner));
  34734. jassert (numNeeded >= 0);
  34735. while (numNeeded < getViewedComponent()->getNumChildComponents())
  34736. {
  34737. Component* const rowToRemove
  34738. = getViewedComponent()->getChildComponent (getViewedComponent()->getNumChildComponents() - 1);
  34739. delete rowToRemove;
  34740. }
  34741. firstIndex = y / rowHeight;
  34742. firstWholeIndex = (y + rowHeight - 1) / rowHeight;
  34743. lastWholeIndex = (y + getMaximumVisibleHeight() - 1) / rowHeight;
  34744. for (int i = 0; i < numNeeded; ++i)
  34745. {
  34746. const int row = i + firstIndex;
  34747. ListBoxRowComponent* const rowComp = getComponentForRow (row);
  34748. if (rowComp != 0)
  34749. {
  34750. rowComp->setBounds (0, row * rowHeight, w, rowHeight);
  34751. rowComp->update (row, owner.isRowSelected (row));
  34752. }
  34753. }
  34754. }
  34755. if (owner.headerComponent != 0)
  34756. owner.headerComponent->setBounds (owner.outlineThickness + getViewedComponent()->getX(),
  34757. owner.outlineThickness,
  34758. jmax (owner.getWidth() - owner.outlineThickness * 2,
  34759. getViewedComponent()->getWidth()),
  34760. owner.headerComponent->getHeight());
  34761. }
  34762. void paint (Graphics& g)
  34763. {
  34764. if (isOpaque())
  34765. g.fillAll (owner.findColour (ListBox::backgroundColourId));
  34766. }
  34767. bool keyPressed (const KeyPress& key)
  34768. {
  34769. if (key.isKeyCode (KeyPress::upKey)
  34770. || key.isKeyCode (KeyPress::downKey)
  34771. || key.isKeyCode (KeyPress::pageUpKey)
  34772. || key.isKeyCode (KeyPress::pageDownKey)
  34773. || key.isKeyCode (KeyPress::homeKey)
  34774. || key.isKeyCode (KeyPress::endKey))
  34775. {
  34776. // we want to avoid these keypresses going to the viewport, and instead allow
  34777. // them to pass up to our listbox..
  34778. return false;
  34779. }
  34780. return Viewport::keyPressed (key);
  34781. }
  34782. juce_UseDebuggingNewOperator
  34783. private:
  34784. ListBox& owner;
  34785. ListViewport (const ListViewport&);
  34786. const ListViewport& operator= (const ListViewport&);
  34787. };
  34788. ListBox::ListBox (const String& name, ListBoxModel* const model_)
  34789. : Component (name),
  34790. model (model_),
  34791. headerComponent (0),
  34792. totalItems (0),
  34793. rowHeight (22),
  34794. minimumRowWidth (0),
  34795. outlineThickness (0),
  34796. lastRowSelected (-1),
  34797. mouseMoveSelects (false),
  34798. multipleSelection (false),
  34799. hasDoneInitialUpdate (false)
  34800. {
  34801. addAndMakeVisible (viewport = new ListViewport (*this));
  34802. setWantsKeyboardFocus (true);
  34803. }
  34804. ListBox::~ListBox()
  34805. {
  34806. deleteAllChildren();
  34807. }
  34808. void ListBox::setModel (ListBoxModel* const newModel)
  34809. {
  34810. if (model != newModel)
  34811. {
  34812. model = newModel;
  34813. updateContent();
  34814. }
  34815. }
  34816. void ListBox::setMultipleSelectionEnabled (bool b)
  34817. {
  34818. multipleSelection = b;
  34819. }
  34820. void ListBox::setMouseMoveSelectsRows (bool b)
  34821. {
  34822. mouseMoveSelects = b;
  34823. if (b)
  34824. addMouseListener (this, true);
  34825. }
  34826. void ListBox::paint (Graphics& g)
  34827. {
  34828. if (! hasDoneInitialUpdate)
  34829. updateContent();
  34830. g.fillAll (findColour (backgroundColourId));
  34831. }
  34832. void ListBox::paintOverChildren (Graphics& g)
  34833. {
  34834. if (outlineThickness > 0)
  34835. {
  34836. g.setColour (findColour (outlineColourId));
  34837. g.drawRect (0, 0, getWidth(), getHeight(), outlineThickness);
  34838. }
  34839. }
  34840. void ListBox::resized()
  34841. {
  34842. viewport->setBoundsInset (BorderSize (outlineThickness + ((headerComponent != 0) ? headerComponent->getHeight() : 0),
  34843. outlineThickness,
  34844. outlineThickness,
  34845. outlineThickness));
  34846. viewport->setSingleStepSizes (20, getRowHeight());
  34847. viewport->updateVisibleArea (false);
  34848. }
  34849. void ListBox::visibilityChanged()
  34850. {
  34851. viewport->updateVisibleArea (true);
  34852. }
  34853. Viewport* ListBox::getViewport() const throw()
  34854. {
  34855. return viewport;
  34856. }
  34857. void ListBox::updateContent()
  34858. {
  34859. hasDoneInitialUpdate = true;
  34860. totalItems = (model != 0) ? model->getNumRows() : 0;
  34861. bool selectionChanged = false;
  34862. if (selected [selected.size() - 1] >= totalItems)
  34863. {
  34864. selected.removeRange (totalItems, INT_MAX - totalItems);
  34865. lastRowSelected = getSelectedRow (0);
  34866. selectionChanged = true;
  34867. }
  34868. viewport->updateVisibleArea (isVisible());
  34869. viewport->resized();
  34870. if (selectionChanged && model != 0)
  34871. model->selectedRowsChanged (lastRowSelected);
  34872. }
  34873. void ListBox::selectRow (const int row,
  34874. bool dontScroll,
  34875. bool deselectOthersFirst)
  34876. {
  34877. selectRowInternal (row, dontScroll, deselectOthersFirst, false);
  34878. }
  34879. void ListBox::selectRowInternal (const int row,
  34880. bool dontScroll,
  34881. bool deselectOthersFirst,
  34882. bool isMouseClick)
  34883. {
  34884. if (! multipleSelection)
  34885. deselectOthersFirst = true;
  34886. if ((! isRowSelected (row))
  34887. || (deselectOthersFirst && getNumSelectedRows() > 1))
  34888. {
  34889. if (((unsigned int) row) < (unsigned int) totalItems)
  34890. {
  34891. if (deselectOthersFirst)
  34892. selected.clear();
  34893. selected.addRange (row, 1);
  34894. if (getHeight() == 0 || getWidth() == 0)
  34895. dontScroll = true;
  34896. viewport->hasUpdated = false;
  34897. if (row < viewport->firstWholeIndex && ! dontScroll)
  34898. {
  34899. viewport->setViewPosition (viewport->getViewPositionX(),
  34900. row * getRowHeight());
  34901. }
  34902. else if (row >= viewport->lastWholeIndex && ! dontScroll)
  34903. {
  34904. const int rowsOnScreen = viewport->lastWholeIndex - viewport->firstWholeIndex;
  34905. if (row >= lastRowSelected + rowsOnScreen
  34906. && rowsOnScreen < totalItems - 1
  34907. && ! isMouseClick)
  34908. {
  34909. viewport->setViewPosition (viewport->getViewPositionX(),
  34910. jlimit (0, jmax (0, totalItems - rowsOnScreen), row)
  34911. * getRowHeight());
  34912. }
  34913. else
  34914. {
  34915. viewport->setViewPosition (viewport->getViewPositionX(),
  34916. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  34917. }
  34918. }
  34919. if (! viewport->hasUpdated)
  34920. viewport->updateContents();
  34921. lastRowSelected = row;
  34922. model->selectedRowsChanged (row);
  34923. }
  34924. else
  34925. {
  34926. if (deselectOthersFirst)
  34927. deselectAllRows();
  34928. }
  34929. }
  34930. }
  34931. void ListBox::deselectRow (const int row)
  34932. {
  34933. if (selected.contains (row))
  34934. {
  34935. selected.removeRange (row, 1);
  34936. if (row == lastRowSelected)
  34937. lastRowSelected = getSelectedRow (0);
  34938. viewport->updateContents();
  34939. model->selectedRowsChanged (lastRowSelected);
  34940. }
  34941. }
  34942. void ListBox::setSelectedRows (const SparseSet<int>& setOfRowsToBeSelected,
  34943. const bool sendNotificationEventToModel)
  34944. {
  34945. selected = setOfRowsToBeSelected;
  34946. selected.removeRange (totalItems, INT_MAX - totalItems);
  34947. if (! isRowSelected (lastRowSelected))
  34948. lastRowSelected = getSelectedRow (0);
  34949. viewport->updateContents();
  34950. if ((model != 0) && sendNotificationEventToModel)
  34951. model->selectedRowsChanged (lastRowSelected);
  34952. }
  34953. const SparseSet<int> ListBox::getSelectedRows() const
  34954. {
  34955. return selected;
  34956. }
  34957. void ListBox::selectRangeOfRows (int firstRow, int lastRow)
  34958. {
  34959. if (multipleSelection && (firstRow != lastRow))
  34960. {
  34961. const int numRows = totalItems - 1;
  34962. firstRow = jlimit (0, jmax (0, numRows), firstRow);
  34963. lastRow = jlimit (0, jmax (0, numRows), lastRow);
  34964. selected.addRange (jmin (firstRow, lastRow),
  34965. abs (firstRow - lastRow) + 1);
  34966. selected.removeRange (lastRow, 1);
  34967. }
  34968. selectRowInternal (lastRow, false, false, true);
  34969. }
  34970. void ListBox::flipRowSelection (const int row)
  34971. {
  34972. if (isRowSelected (row))
  34973. deselectRow (row);
  34974. else
  34975. selectRowInternal (row, false, false, true);
  34976. }
  34977. void ListBox::deselectAllRows()
  34978. {
  34979. if (! selected.isEmpty())
  34980. {
  34981. selected.clear();
  34982. lastRowSelected = -1;
  34983. viewport->updateContents();
  34984. if (model != 0)
  34985. model->selectedRowsChanged (lastRowSelected);
  34986. }
  34987. }
  34988. void ListBox::selectRowsBasedOnModifierKeys (const int row,
  34989. const ModifierKeys& mods)
  34990. {
  34991. if (multipleSelection && mods.isCommandDown())
  34992. {
  34993. flipRowSelection (row);
  34994. }
  34995. else if (multipleSelection && mods.isShiftDown() && lastRowSelected >= 0)
  34996. {
  34997. selectRangeOfRows (lastRowSelected, row);
  34998. }
  34999. else if ((! mods.isPopupMenu()) || ! isRowSelected (row))
  35000. {
  35001. selectRowInternal (row, false, true, true);
  35002. }
  35003. }
  35004. int ListBox::getNumSelectedRows() const
  35005. {
  35006. return selected.size();
  35007. }
  35008. int ListBox::getSelectedRow (const int index) const
  35009. {
  35010. return (((unsigned int) index) < (unsigned int) selected.size())
  35011. ? selected [index] : -1;
  35012. }
  35013. bool ListBox::isRowSelected (const int row) const
  35014. {
  35015. return selected.contains (row);
  35016. }
  35017. int ListBox::getLastRowSelected() const
  35018. {
  35019. return (isRowSelected (lastRowSelected)) ? lastRowSelected : -1;
  35020. }
  35021. int ListBox::getRowContainingPosition (const int x, const int y) const throw()
  35022. {
  35023. if (((unsigned int) x) < (unsigned int) getWidth())
  35024. {
  35025. const int row = (viewport->getViewPositionY() + y - viewport->getY()) / rowHeight;
  35026. if (((unsigned int) row) < (unsigned int) totalItems)
  35027. return row;
  35028. }
  35029. return -1;
  35030. }
  35031. int ListBox::getInsertionIndexForPosition (const int x, const int y) const throw()
  35032. {
  35033. if (((unsigned int) x) < (unsigned int) getWidth())
  35034. {
  35035. const int row = (viewport->getViewPositionY() + y + rowHeight / 2 - viewport->getY()) / rowHeight;
  35036. return jlimit (0, totalItems, row);
  35037. }
  35038. return -1;
  35039. }
  35040. Component* ListBox::getComponentForRowNumber (const int row) const throw()
  35041. {
  35042. Component* const listRowComp = viewport->getComponentForRowIfOnscreen (row);
  35043. return listRowComp != 0 ? listRowComp->getChildComponent (0) : 0;
  35044. }
  35045. int ListBox::getRowNumberOfComponent (Component* const rowComponent) const throw()
  35046. {
  35047. return viewport->getRowNumberOfComponent (rowComponent);
  35048. }
  35049. const Rectangle ListBox::getRowPosition (const int rowNumber,
  35050. const bool relativeToComponentTopLeft) const throw()
  35051. {
  35052. const int rowHeight = getRowHeight();
  35053. int y = viewport->getY() + rowHeight * rowNumber;
  35054. if (relativeToComponentTopLeft)
  35055. y -= viewport->getViewPositionY();
  35056. return Rectangle (viewport->getX(), y,
  35057. viewport->getViewedComponent()->getWidth(), rowHeight);
  35058. }
  35059. void ListBox::setVerticalPosition (const double proportion)
  35060. {
  35061. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  35062. viewport->setViewPosition (viewport->getViewPositionX(),
  35063. jmax (0, roundDoubleToInt (proportion * offscreen)));
  35064. }
  35065. double ListBox::getVerticalPosition() const
  35066. {
  35067. const int offscreen = viewport->getViewedComponent()->getHeight() - viewport->getHeight();
  35068. return (offscreen > 0) ? viewport->getViewPositionY() / (double) offscreen
  35069. : 0;
  35070. }
  35071. int ListBox::getVisibleRowWidth() const throw()
  35072. {
  35073. return viewport->getViewWidth();
  35074. }
  35075. void ListBox::scrollToEnsureRowIsOnscreen (const int row)
  35076. {
  35077. if (row < viewport->firstWholeIndex)
  35078. {
  35079. viewport->setViewPosition (viewport->getViewPositionX(),
  35080. row * getRowHeight());
  35081. }
  35082. else if (row >= viewport->lastWholeIndex)
  35083. {
  35084. viewport->setViewPosition (viewport->getViewPositionX(),
  35085. jmax (0, (row + 1) * getRowHeight() - viewport->getMaximumVisibleHeight()));
  35086. }
  35087. }
  35088. bool ListBox::keyPressed (const KeyPress& key)
  35089. {
  35090. const int numVisibleRows = viewport->getHeight() / getRowHeight();
  35091. const bool multiple = multipleSelection
  35092. && (lastRowSelected >= 0)
  35093. && (key.getModifiers().isShiftDown()
  35094. || key.getModifiers().isCtrlDown()
  35095. || key.getModifiers().isCommandDown());
  35096. if (key.isKeyCode (KeyPress::upKey))
  35097. {
  35098. if (multiple)
  35099. selectRangeOfRows (lastRowSelected, lastRowSelected - 1);
  35100. else
  35101. selectRow (jmax (0, lastRowSelected - 1));
  35102. }
  35103. else if (key.isKeyCode (KeyPress::returnKey)
  35104. && isRowSelected (lastRowSelected))
  35105. {
  35106. if (model != 0)
  35107. model->returnKeyPressed (lastRowSelected);
  35108. }
  35109. else if (key.isKeyCode (KeyPress::pageUpKey))
  35110. {
  35111. if (multiple)
  35112. selectRangeOfRows (lastRowSelected, lastRowSelected - numVisibleRows);
  35113. else
  35114. selectRow (jmax (0, jmax (0, lastRowSelected) - numVisibleRows));
  35115. }
  35116. else if (key.isKeyCode (KeyPress::pageDownKey))
  35117. {
  35118. if (multiple)
  35119. selectRangeOfRows (lastRowSelected, lastRowSelected + numVisibleRows);
  35120. else
  35121. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + numVisibleRows));
  35122. }
  35123. else if (key.isKeyCode (KeyPress::homeKey))
  35124. {
  35125. if (multiple && key.getModifiers().isShiftDown())
  35126. selectRangeOfRows (lastRowSelected, 0);
  35127. else
  35128. selectRow (0);
  35129. }
  35130. else if (key.isKeyCode (KeyPress::endKey))
  35131. {
  35132. if (multiple && key.getModifiers().isShiftDown())
  35133. selectRangeOfRows (lastRowSelected, totalItems - 1);
  35134. else
  35135. selectRow (totalItems - 1);
  35136. }
  35137. else if (key.isKeyCode (KeyPress::downKey))
  35138. {
  35139. if (multiple)
  35140. selectRangeOfRows (lastRowSelected, lastRowSelected + 1);
  35141. else
  35142. selectRow (jmin (totalItems - 1, jmax (0, lastRowSelected) + 1));
  35143. }
  35144. else if ((key.isKeyCode (KeyPress::deleteKey) || key.isKeyCode (KeyPress::backspaceKey))
  35145. && isRowSelected (lastRowSelected))
  35146. {
  35147. if (model != 0)
  35148. model->deleteKeyPressed (lastRowSelected);
  35149. }
  35150. else if (multiple && key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  35151. {
  35152. selectRangeOfRows (0, INT_MAX);
  35153. }
  35154. else
  35155. {
  35156. return false;
  35157. }
  35158. return true;
  35159. }
  35160. bool ListBox::keyStateChanged()
  35161. {
  35162. return KeyPress::isKeyCurrentlyDown (KeyPress::upKey)
  35163. || KeyPress::isKeyCurrentlyDown (KeyPress::pageUpKey)
  35164. || KeyPress::isKeyCurrentlyDown (KeyPress::downKey)
  35165. || KeyPress::isKeyCurrentlyDown (KeyPress::pageDownKey)
  35166. || KeyPress::isKeyCurrentlyDown (KeyPress::homeKey)
  35167. || KeyPress::isKeyCurrentlyDown (KeyPress::endKey)
  35168. || KeyPress::isKeyCurrentlyDown (KeyPress::returnKey);
  35169. }
  35170. void ListBox::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  35171. {
  35172. getHorizontalScrollBar()->mouseWheelMove (e, wheelIncrementX, 0);
  35173. getVerticalScrollBar()->mouseWheelMove (e, 0, wheelIncrementY);
  35174. }
  35175. void ListBox::mouseMove (const MouseEvent& e)
  35176. {
  35177. if (mouseMoveSelects)
  35178. {
  35179. const MouseEvent e2 (e.getEventRelativeTo (this));
  35180. selectRow (getRowContainingPosition (e2.x, e2.y), true);
  35181. lastMouseX = e2.x;
  35182. lastMouseY = e2.y;
  35183. }
  35184. }
  35185. void ListBox::mouseExit (const MouseEvent& e)
  35186. {
  35187. mouseMove (e);
  35188. }
  35189. void ListBox::mouseUp (const MouseEvent& e)
  35190. {
  35191. if (e.mouseWasClicked() && model != 0)
  35192. model->backgroundClicked();
  35193. }
  35194. void ListBox::setRowHeight (const int newHeight)
  35195. {
  35196. rowHeight = jmax (1, newHeight);
  35197. viewport->setSingleStepSizes (20, rowHeight);
  35198. updateContent();
  35199. }
  35200. int ListBox::getNumRowsOnScreen() const throw()
  35201. {
  35202. return viewport->getMaximumVisibleHeight() / rowHeight;
  35203. }
  35204. void ListBox::setMinimumContentWidth (const int newMinimumWidth)
  35205. {
  35206. minimumRowWidth = newMinimumWidth;
  35207. updateContent();
  35208. }
  35209. int ListBox::getVisibleContentWidth() const throw()
  35210. {
  35211. return viewport->getMaximumVisibleWidth();
  35212. }
  35213. ScrollBar* ListBox::getVerticalScrollBar() const throw()
  35214. {
  35215. return viewport->getVerticalScrollBar();
  35216. }
  35217. ScrollBar* ListBox::getHorizontalScrollBar() const throw()
  35218. {
  35219. return viewport->getHorizontalScrollBar();
  35220. }
  35221. void ListBox::colourChanged()
  35222. {
  35223. setOpaque (findColour (backgroundColourId).isOpaque());
  35224. viewport->setOpaque (isOpaque());
  35225. repaint();
  35226. }
  35227. void ListBox::setOutlineThickness (const int outlineThickness_)
  35228. {
  35229. outlineThickness = outlineThickness_;
  35230. resized();
  35231. }
  35232. void ListBox::setHeaderComponent (Component* const newHeaderComponent)
  35233. {
  35234. if (headerComponent != newHeaderComponent)
  35235. {
  35236. if (headerComponent != 0)
  35237. delete headerComponent;
  35238. headerComponent = newHeaderComponent;
  35239. addAndMakeVisible (newHeaderComponent);
  35240. ListBox::resized();
  35241. }
  35242. }
  35243. void ListBox::repaintRow (const int rowNumber) throw()
  35244. {
  35245. const Rectangle r (getRowPosition (rowNumber, true));
  35246. repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  35247. }
  35248. Image* ListBox::createSnapshotOfSelectedRows()
  35249. {
  35250. Image* snapshot = new Image (Image::ARGB, getWidth(), getHeight(), true);
  35251. Graphics g (*snapshot);
  35252. const int firstRow = getRowContainingPosition (0, 0);
  35253. for (int i = getNumRowsOnScreen() + 2; --i >= 0;)
  35254. {
  35255. Component* rowComp = viewport->getComponentForRowIfOnscreen (firstRow + i);
  35256. if (rowComp != 0 && isRowSelected (firstRow + i))
  35257. {
  35258. g.saveState();
  35259. int x = 0, y = 0;
  35260. rowComp->relativePositionToOtherComponent (this, x, y);
  35261. g.setOrigin (x, y);
  35262. g.reduceClipRegion (0, 0, rowComp->getWidth(), rowComp->getHeight());
  35263. rowComp->paintEntireComponent (g);
  35264. g.restoreState();
  35265. }
  35266. }
  35267. return snapshot;
  35268. }
  35269. Component* ListBoxModel::refreshComponentForRow (int, bool, Component* existingComponentToUpdate)
  35270. {
  35271. (void) existingComponentToUpdate;
  35272. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  35273. return 0;
  35274. }
  35275. void ListBoxModel::listBoxItemClicked (int, const MouseEvent&)
  35276. {
  35277. }
  35278. void ListBoxModel::listBoxItemDoubleClicked (int, const MouseEvent&)
  35279. {
  35280. }
  35281. void ListBoxModel::backgroundClicked()
  35282. {
  35283. }
  35284. void ListBoxModel::selectedRowsChanged (int)
  35285. {
  35286. }
  35287. void ListBoxModel::deleteKeyPressed (int)
  35288. {
  35289. }
  35290. void ListBoxModel::returnKeyPressed (int)
  35291. {
  35292. }
  35293. void ListBoxModel::listWasScrolled()
  35294. {
  35295. }
  35296. const String ListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  35297. {
  35298. return String::empty;
  35299. }
  35300. END_JUCE_NAMESPACE
  35301. /********* End of inlined file: juce_ListBox.cpp *********/
  35302. /********* Start of inlined file: juce_ProgressBar.cpp *********/
  35303. BEGIN_JUCE_NAMESPACE
  35304. ProgressBar::ProgressBar (double& progress_)
  35305. : progress (progress_),
  35306. displayPercentage (true)
  35307. {
  35308. currentValue = jlimit (0.0, 1.0, progress);
  35309. }
  35310. ProgressBar::~ProgressBar()
  35311. {
  35312. }
  35313. void ProgressBar::setPercentageDisplay (const bool shouldDisplayPercentage)
  35314. {
  35315. displayPercentage = shouldDisplayPercentage;
  35316. repaint();
  35317. }
  35318. void ProgressBar::setTextToDisplay (const String& text)
  35319. {
  35320. displayPercentage = false;
  35321. displayedMessage = text;
  35322. }
  35323. void ProgressBar::lookAndFeelChanged()
  35324. {
  35325. setOpaque (findColour (backgroundColourId).isOpaque());
  35326. }
  35327. void ProgressBar::colourChanged()
  35328. {
  35329. lookAndFeelChanged();
  35330. }
  35331. void ProgressBar::paint (Graphics& g)
  35332. {
  35333. String text;
  35334. if (displayPercentage)
  35335. {
  35336. if (currentValue >= 0 && currentValue <= 1.0)
  35337. text << roundDoubleToInt (currentValue * 100.0) << T("%");
  35338. }
  35339. else
  35340. {
  35341. text = displayedMessage;
  35342. }
  35343. getLookAndFeel().drawProgressBar (g, *this,
  35344. getWidth(), getHeight(),
  35345. currentValue, text);
  35346. }
  35347. void ProgressBar::visibilityChanged()
  35348. {
  35349. if (isVisible())
  35350. startTimer (30);
  35351. else
  35352. stopTimer();
  35353. }
  35354. void ProgressBar::timerCallback()
  35355. {
  35356. double newProgress = progress;
  35357. if (currentValue != newProgress
  35358. || newProgress < 0 || newProgress >= 1.0
  35359. || currentMessage != displayedMessage)
  35360. {
  35361. if (currentValue < newProgress
  35362. && newProgress >= 0 && newProgress < 1.0
  35363. && currentValue >= 0 && newProgress < 1.0)
  35364. {
  35365. newProgress = jmin (currentValue + 0.02, newProgress);
  35366. }
  35367. currentValue = newProgress;
  35368. currentMessage = displayedMessage;
  35369. repaint();
  35370. }
  35371. }
  35372. END_JUCE_NAMESPACE
  35373. /********* End of inlined file: juce_ProgressBar.cpp *********/
  35374. /********* Start of inlined file: juce_Slider.cpp *********/
  35375. BEGIN_JUCE_NAMESPACE
  35376. class SliderPopupDisplayComponent : public BubbleComponent
  35377. {
  35378. public:
  35379. SliderPopupDisplayComponent (Slider* const owner_)
  35380. : owner (owner_),
  35381. font (15.0f, Font::bold)
  35382. {
  35383. setAlwaysOnTop (true);
  35384. }
  35385. ~SliderPopupDisplayComponent()
  35386. {
  35387. }
  35388. void paintContent (Graphics& g, int w, int h)
  35389. {
  35390. g.setFont (font);
  35391. g.setColour (Colours::black);
  35392. g.drawFittedText (text, 0, 0, w, h, Justification::centred, 1);
  35393. }
  35394. void getContentSize (int& w, int& h)
  35395. {
  35396. w = font.getStringWidth (text) + 18;
  35397. h = (int) (font.getHeight() * 1.6f);
  35398. }
  35399. void updatePosition (const String& newText)
  35400. {
  35401. if (text != newText)
  35402. {
  35403. text = newText;
  35404. repaint();
  35405. }
  35406. BubbleComponent::setPosition (owner);
  35407. }
  35408. juce_UseDebuggingNewOperator
  35409. private:
  35410. Slider* owner;
  35411. Font font;
  35412. String text;
  35413. SliderPopupDisplayComponent (const SliderPopupDisplayComponent&);
  35414. const SliderPopupDisplayComponent& operator= (const SliderPopupDisplayComponent&);
  35415. };
  35416. Slider::Slider (const String& name)
  35417. : Component (name),
  35418. listeners (2),
  35419. currentValue (0.0),
  35420. valueMin (0.0),
  35421. valueMax (0.0),
  35422. minimum (0),
  35423. maximum (10),
  35424. interval (0),
  35425. skewFactor (1.0),
  35426. velocityModeSensitivity (1.0),
  35427. velocityModeOffset (0.0),
  35428. velocityModeThreshold (1),
  35429. rotaryStart (float_Pi * 1.2f),
  35430. rotaryEnd (float_Pi * 2.8f),
  35431. numDecimalPlaces (7),
  35432. sliderRegionStart (0),
  35433. sliderRegionSize (1),
  35434. sliderBeingDragged (-1),
  35435. pixelsForFullDragExtent (250),
  35436. style (LinearHorizontal),
  35437. textBoxPos (TextBoxLeft),
  35438. textBoxWidth (80),
  35439. textBoxHeight (20),
  35440. incDecButtonMode (incDecButtonsNotDraggable),
  35441. editableText (true),
  35442. doubleClickToValue (false),
  35443. isVelocityBased (false),
  35444. userKeyOverridesVelocity (true),
  35445. rotaryStop (true),
  35446. incDecButtonsSideBySide (false),
  35447. sendChangeOnlyOnRelease (false),
  35448. popupDisplayEnabled (false),
  35449. menuEnabled (false),
  35450. menuShown (false),
  35451. scrollWheelEnabled (true),
  35452. snapsToMousePos (true),
  35453. valueBox (0),
  35454. incButton (0),
  35455. decButton (0),
  35456. popupDisplay (0),
  35457. parentForPopupDisplay (0)
  35458. {
  35459. setWantsKeyboardFocus (false);
  35460. setRepaintsOnMouseActivity (true);
  35461. lookAndFeelChanged();
  35462. updateText();
  35463. }
  35464. Slider::~Slider()
  35465. {
  35466. deleteAndZero (popupDisplay);
  35467. deleteAllChildren();
  35468. }
  35469. void Slider::handleAsyncUpdate()
  35470. {
  35471. cancelPendingUpdate();
  35472. for (int i = listeners.size(); --i >= 0;)
  35473. {
  35474. ((SliderListener*) listeners.getUnchecked (i))->sliderValueChanged (this);
  35475. i = jmin (i, listeners.size());
  35476. }
  35477. }
  35478. void Slider::sendDragStart()
  35479. {
  35480. startedDragging();
  35481. for (int i = listeners.size(); --i >= 0;)
  35482. {
  35483. ((SliderListener*) listeners.getUnchecked (i))->sliderDragStarted (this);
  35484. i = jmin (i, listeners.size());
  35485. }
  35486. }
  35487. void Slider::sendDragEnd()
  35488. {
  35489. stoppedDragging();
  35490. sliderBeingDragged = -1;
  35491. for (int i = listeners.size(); --i >= 0;)
  35492. {
  35493. ((SliderListener*) listeners.getUnchecked (i))->sliderDragEnded (this);
  35494. i = jmin (i, listeners.size());
  35495. }
  35496. }
  35497. void Slider::addListener (SliderListener* const listener) throw()
  35498. {
  35499. jassert (listener != 0);
  35500. if (listener != 0)
  35501. listeners.add (listener);
  35502. }
  35503. void Slider::removeListener (SliderListener* const listener) throw()
  35504. {
  35505. listeners.removeValue (listener);
  35506. }
  35507. void Slider::setSliderStyle (const SliderStyle newStyle)
  35508. {
  35509. if (style != newStyle)
  35510. {
  35511. style = newStyle;
  35512. repaint();
  35513. lookAndFeelChanged();
  35514. }
  35515. }
  35516. void Slider::setRotaryParameters (const float startAngleRadians,
  35517. const float endAngleRadians,
  35518. const bool stopAtEnd)
  35519. {
  35520. // make sure the values are sensible..
  35521. jassert (rotaryStart >= 0 && rotaryEnd >= 0);
  35522. jassert (rotaryStart < float_Pi * 4.0f && rotaryEnd < float_Pi * 4.0f);
  35523. jassert (rotaryStart < rotaryEnd);
  35524. rotaryStart = startAngleRadians;
  35525. rotaryEnd = endAngleRadians;
  35526. rotaryStop = stopAtEnd;
  35527. }
  35528. void Slider::setVelocityBasedMode (const bool velBased) throw()
  35529. {
  35530. isVelocityBased = velBased;
  35531. }
  35532. void Slider::setVelocityModeParameters (const double sensitivity,
  35533. const int threshold,
  35534. const double offset,
  35535. const bool userCanPressKeyToSwapMode) throw()
  35536. {
  35537. jassert (threshold >= 0);
  35538. jassert (sensitivity > 0);
  35539. jassert (offset >= 0);
  35540. velocityModeSensitivity = sensitivity;
  35541. velocityModeOffset = offset;
  35542. velocityModeThreshold = threshold;
  35543. userKeyOverridesVelocity = userCanPressKeyToSwapMode;
  35544. }
  35545. void Slider::setSkewFactor (const double factor) throw()
  35546. {
  35547. skewFactor = factor;
  35548. }
  35549. void Slider::setSkewFactorFromMidPoint (const double sliderValueToShowAtMidPoint) throw()
  35550. {
  35551. if (maximum > minimum)
  35552. skewFactor = log (0.5) / log ((sliderValueToShowAtMidPoint - minimum)
  35553. / (maximum - minimum));
  35554. }
  35555. void Slider::setMouseDragSensitivity (const int distanceForFullScaleDrag)
  35556. {
  35557. jassert (distanceForFullScaleDrag > 0);
  35558. pixelsForFullDragExtent = distanceForFullScaleDrag;
  35559. }
  35560. void Slider::setIncDecButtonsMode (const IncDecButtonMode mode)
  35561. {
  35562. if (incDecButtonMode != mode)
  35563. {
  35564. incDecButtonMode = mode;
  35565. lookAndFeelChanged();
  35566. }
  35567. }
  35568. void Slider::setTextBoxStyle (const TextEntryBoxPosition newPosition,
  35569. const bool isReadOnly,
  35570. const int textEntryBoxWidth,
  35571. const int textEntryBoxHeight)
  35572. {
  35573. textBoxPos = newPosition;
  35574. editableText = ! isReadOnly;
  35575. textBoxWidth = textEntryBoxWidth;
  35576. textBoxHeight = textEntryBoxHeight;
  35577. repaint();
  35578. lookAndFeelChanged();
  35579. }
  35580. void Slider::setTextBoxIsEditable (const bool shouldBeEditable) throw()
  35581. {
  35582. editableText = shouldBeEditable;
  35583. if (valueBox != 0)
  35584. valueBox->setEditable (shouldBeEditable && isEnabled());
  35585. }
  35586. void Slider::showTextBox()
  35587. {
  35588. jassert (editableText); // this should probably be avoided in read-only sliders.
  35589. if (valueBox != 0)
  35590. valueBox->showEditor();
  35591. }
  35592. void Slider::hideTextBox (const bool discardCurrentEditorContents)
  35593. {
  35594. if (valueBox != 0)
  35595. {
  35596. valueBox->hideEditor (discardCurrentEditorContents);
  35597. if (discardCurrentEditorContents)
  35598. updateText();
  35599. }
  35600. }
  35601. void Slider::setChangeNotificationOnlyOnRelease (const bool onlyNotifyOnRelease) throw()
  35602. {
  35603. sendChangeOnlyOnRelease = onlyNotifyOnRelease;
  35604. }
  35605. void Slider::setSliderSnapsToMousePosition (const bool shouldSnapToMouse) throw()
  35606. {
  35607. snapsToMousePos = shouldSnapToMouse;
  35608. }
  35609. void Slider::setPopupDisplayEnabled (const bool enabled,
  35610. Component* const parentComponentToUse) throw()
  35611. {
  35612. popupDisplayEnabled = enabled;
  35613. parentForPopupDisplay = parentComponentToUse;
  35614. }
  35615. void Slider::colourChanged()
  35616. {
  35617. lookAndFeelChanged();
  35618. }
  35619. void Slider::lookAndFeelChanged()
  35620. {
  35621. const String previousTextBoxContent (valueBox != 0 ? valueBox->getText()
  35622. : getTextFromValue (currentValue));
  35623. deleteAllChildren();
  35624. valueBox = 0;
  35625. LookAndFeel& lf = getLookAndFeel();
  35626. if (textBoxPos != NoTextBox)
  35627. {
  35628. addAndMakeVisible (valueBox = getLookAndFeel().createSliderTextBox (*this));
  35629. valueBox->setWantsKeyboardFocus (false);
  35630. valueBox->setText (previousTextBoxContent, false);
  35631. valueBox->setEditable (editableText && isEnabled());
  35632. valueBox->addListener (this);
  35633. if (style == LinearBar)
  35634. valueBox->addMouseListener (this, false);
  35635. }
  35636. if (style == IncDecButtons)
  35637. {
  35638. addAndMakeVisible (incButton = lf.createSliderButton (true));
  35639. incButton->addButtonListener (this);
  35640. addAndMakeVisible (decButton = lf.createSliderButton (false));
  35641. decButton->addButtonListener (this);
  35642. if (incDecButtonMode != incDecButtonsNotDraggable)
  35643. {
  35644. incButton->addMouseListener (this, false);
  35645. decButton->addMouseListener (this, false);
  35646. }
  35647. else
  35648. {
  35649. incButton->setRepeatSpeed (300, 100, 20);
  35650. incButton->addMouseListener (decButton, false);
  35651. decButton->setRepeatSpeed (300, 100, 20);
  35652. decButton->addMouseListener (incButton, false);
  35653. }
  35654. }
  35655. setComponentEffect (lf.getSliderEffect());
  35656. resized();
  35657. repaint();
  35658. }
  35659. void Slider::setRange (const double newMin,
  35660. const double newMax,
  35661. const double newInt)
  35662. {
  35663. if (minimum != newMin
  35664. || maximum != newMax
  35665. || interval != newInt)
  35666. {
  35667. minimum = newMin;
  35668. maximum = newMax;
  35669. interval = newInt;
  35670. // figure out the number of DPs needed to display all values at this
  35671. // interval setting.
  35672. numDecimalPlaces = 7;
  35673. if (newInt != 0)
  35674. {
  35675. int v = abs ((int) (newInt * 10000000));
  35676. while ((v % 10) == 0)
  35677. {
  35678. --numDecimalPlaces;
  35679. v /= 10;
  35680. }
  35681. }
  35682. // keep the current values inside the new range..
  35683. if (style != TwoValueHorizontal && style != TwoValueVertical)
  35684. {
  35685. setValue (currentValue, false, false);
  35686. }
  35687. else
  35688. {
  35689. setMinValue (getMinValue(), false, false);
  35690. setMaxValue (getMaxValue(), false, false);
  35691. }
  35692. updateText();
  35693. }
  35694. }
  35695. void Slider::triggerChangeMessage (const bool synchronous)
  35696. {
  35697. if (synchronous)
  35698. handleAsyncUpdate();
  35699. else
  35700. triggerAsyncUpdate();
  35701. valueChanged();
  35702. }
  35703. double Slider::getValue() const throw()
  35704. {
  35705. // for a two-value style slider, you should use the getMinValue() and getMaxValue()
  35706. // methods to get the two values.
  35707. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  35708. return currentValue;
  35709. }
  35710. void Slider::setValue (double newValue,
  35711. const bool sendUpdateMessage,
  35712. const bool sendMessageSynchronously)
  35713. {
  35714. // for a two-value style slider, you should use the setMinValue() and setMaxValue()
  35715. // methods to set the two values.
  35716. jassert (style != TwoValueHorizontal && style != TwoValueVertical);
  35717. newValue = constrainedValue (newValue);
  35718. if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  35719. {
  35720. jassert (valueMin <= valueMax);
  35721. newValue = jlimit (valueMin, valueMax, newValue);
  35722. }
  35723. if (currentValue != newValue)
  35724. {
  35725. if (valueBox != 0)
  35726. valueBox->hideEditor (true);
  35727. currentValue = newValue;
  35728. updateText();
  35729. repaint();
  35730. if (popupDisplay != 0)
  35731. {
  35732. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (currentValue));
  35733. popupDisplay->repaint();
  35734. }
  35735. if (sendUpdateMessage)
  35736. triggerChangeMessage (sendMessageSynchronously);
  35737. }
  35738. }
  35739. double Slider::getMinValue() const throw()
  35740. {
  35741. // The minimum value only applies to sliders that are in two- or three-value mode.
  35742. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  35743. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  35744. return valueMin;
  35745. }
  35746. double Slider::getMaxValue() const throw()
  35747. {
  35748. // The maximum value only applies to sliders that are in two- or three-value mode.
  35749. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  35750. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  35751. return valueMax;
  35752. }
  35753. void Slider::setMinValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously)
  35754. {
  35755. // The minimum value only applies to sliders that are in two- or three-value mode.
  35756. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  35757. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  35758. newValue = constrainedValue (newValue);
  35759. if (style == TwoValueHorizontal || style == TwoValueVertical)
  35760. newValue = jmin (valueMax, newValue);
  35761. else
  35762. newValue = jmin (currentValue, newValue);
  35763. if (valueMin != newValue)
  35764. {
  35765. valueMin = newValue;
  35766. repaint();
  35767. if (popupDisplay != 0)
  35768. {
  35769. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMin));
  35770. popupDisplay->repaint();
  35771. }
  35772. if (sendUpdateMessage)
  35773. triggerChangeMessage (sendMessageSynchronously);
  35774. }
  35775. }
  35776. void Slider::setMaxValue (double newValue, const bool sendUpdateMessage, const bool sendMessageSynchronously)
  35777. {
  35778. // The maximum value only applies to sliders that are in two- or three-value mode.
  35779. jassert (style == TwoValueHorizontal || style == TwoValueVertical
  35780. || style == ThreeValueHorizontal || style == ThreeValueVertical);
  35781. newValue = constrainedValue (newValue);
  35782. if (style == TwoValueHorizontal || style == TwoValueVertical)
  35783. newValue = jmax (valueMin, newValue);
  35784. else
  35785. newValue = jmax (currentValue, newValue);
  35786. if (valueMax != newValue)
  35787. {
  35788. valueMax = newValue;
  35789. repaint();
  35790. if (popupDisplay != 0)
  35791. {
  35792. ((SliderPopupDisplayComponent*) popupDisplay)->updatePosition (getTextFromValue (valueMax));
  35793. popupDisplay->repaint();
  35794. }
  35795. if (sendUpdateMessage)
  35796. triggerChangeMessage (sendMessageSynchronously);
  35797. }
  35798. }
  35799. void Slider::setDoubleClickReturnValue (const bool isDoubleClickEnabled,
  35800. const double valueToSetOnDoubleClick) throw()
  35801. {
  35802. doubleClickToValue = isDoubleClickEnabled;
  35803. doubleClickReturnValue = valueToSetOnDoubleClick;
  35804. }
  35805. double Slider::getDoubleClickReturnValue (bool& isEnabled_) const throw()
  35806. {
  35807. isEnabled_ = doubleClickToValue;
  35808. return doubleClickReturnValue;
  35809. }
  35810. void Slider::updateText()
  35811. {
  35812. if (valueBox != 0)
  35813. valueBox->setText (getTextFromValue (currentValue), false);
  35814. }
  35815. void Slider::setTextValueSuffix (const String& suffix)
  35816. {
  35817. if (textSuffix != suffix)
  35818. {
  35819. textSuffix = suffix;
  35820. updateText();
  35821. }
  35822. }
  35823. const String Slider::getTextFromValue (double v)
  35824. {
  35825. if (numDecimalPlaces > 0)
  35826. return String (v, numDecimalPlaces) + textSuffix;
  35827. else
  35828. return String (roundDoubleToInt (v)) + textSuffix;
  35829. }
  35830. double Slider::getValueFromText (const String& text)
  35831. {
  35832. String t (text.trimStart());
  35833. if (t.endsWith (textSuffix))
  35834. t = t.substring (0, t.length() - textSuffix.length());
  35835. while (t.startsWithChar (T('+')))
  35836. t = t.substring (1).trimStart();
  35837. return t.initialSectionContainingOnly (T("0123456789.,-"))
  35838. .getDoubleValue();
  35839. }
  35840. double Slider::proportionOfLengthToValue (double proportion)
  35841. {
  35842. if (skewFactor != 1.0 && proportion > 0.0)
  35843. proportion = exp (log (proportion) / skewFactor);
  35844. return minimum + (maximum - minimum) * proportion;
  35845. }
  35846. double Slider::valueToProportionOfLength (double value)
  35847. {
  35848. const double n = (value - minimum) / (maximum - minimum);
  35849. return skewFactor == 1.0 ? n : pow (n, skewFactor);
  35850. }
  35851. double Slider::snapValue (double attemptedValue, const bool)
  35852. {
  35853. return attemptedValue;
  35854. }
  35855. void Slider::startedDragging()
  35856. {
  35857. }
  35858. void Slider::stoppedDragging()
  35859. {
  35860. }
  35861. void Slider::valueChanged()
  35862. {
  35863. }
  35864. void Slider::enablementChanged()
  35865. {
  35866. repaint();
  35867. }
  35868. void Slider::setPopupMenuEnabled (const bool menuEnabled_) throw()
  35869. {
  35870. menuEnabled = menuEnabled_;
  35871. }
  35872. void Slider::setScrollWheelEnabled (const bool enabled) throw()
  35873. {
  35874. scrollWheelEnabled = enabled;
  35875. }
  35876. void Slider::labelTextChanged (Label* label)
  35877. {
  35878. const double newValue = snapValue (getValueFromText (label->getText()), false);
  35879. if (getValue() != newValue)
  35880. {
  35881. sendDragStart();
  35882. setValue (newValue, true, true);
  35883. sendDragEnd();
  35884. }
  35885. updateText(); // force a clean-up of the text, needed in case setValue() hasn't done this.
  35886. }
  35887. void Slider::buttonClicked (Button* button)
  35888. {
  35889. if (style == IncDecButtons)
  35890. {
  35891. sendDragStart();
  35892. if (button == incButton)
  35893. setValue (snapValue (getValue() + interval, false), true, true);
  35894. else if (button == decButton)
  35895. setValue (snapValue (getValue() - interval, false), true, true);
  35896. sendDragEnd();
  35897. }
  35898. }
  35899. double Slider::constrainedValue (double value) const throw()
  35900. {
  35901. if (interval > 0)
  35902. value = minimum + interval * floor ((value - minimum) / interval + 0.5);
  35903. if (value <= minimum || maximum <= minimum)
  35904. value = minimum;
  35905. else if (value >= maximum)
  35906. value = maximum;
  35907. return value;
  35908. }
  35909. float Slider::getLinearSliderPos (const double value)
  35910. {
  35911. double sliderPosProportional;
  35912. if (maximum > minimum)
  35913. {
  35914. if (value < minimum)
  35915. {
  35916. sliderPosProportional = 0.0;
  35917. }
  35918. else if (value > maximum)
  35919. {
  35920. sliderPosProportional = 1.0;
  35921. }
  35922. else
  35923. {
  35924. sliderPosProportional = valueToProportionOfLength (value);
  35925. jassert (sliderPosProportional >= 0 && sliderPosProportional <= 1.0);
  35926. }
  35927. }
  35928. else
  35929. {
  35930. sliderPosProportional = 0.5;
  35931. }
  35932. if (isVertical() || style == IncDecButtons)
  35933. sliderPosProportional = 1.0 - sliderPosProportional;
  35934. return (float) (sliderRegionStart + sliderPosProportional * sliderRegionSize);
  35935. }
  35936. bool Slider::isHorizontal() const throw()
  35937. {
  35938. return style == LinearHorizontal
  35939. || style == LinearBar
  35940. || style == TwoValueHorizontal
  35941. || style == ThreeValueHorizontal;
  35942. }
  35943. bool Slider::isVertical() const throw()
  35944. {
  35945. return style == LinearVertical
  35946. || style == TwoValueVertical
  35947. || style == ThreeValueVertical;
  35948. }
  35949. bool Slider::incDecDragDirectionIsHorizontal() const throw()
  35950. {
  35951. return incDecButtonMode == incDecButtonsDraggable_Horizontal
  35952. || (incDecButtonMode == incDecButtonsDraggable_AutoDirection && incDecButtonsSideBySide);
  35953. }
  35954. float Slider::getPositionOfValue (const double value)
  35955. {
  35956. if (isHorizontal() || isVertical())
  35957. {
  35958. return getLinearSliderPos (value);
  35959. }
  35960. else
  35961. {
  35962. jassertfalse // not a valid call on a slider that doesn't work linearly!
  35963. return 0.0f;
  35964. }
  35965. }
  35966. void Slider::paint (Graphics& g)
  35967. {
  35968. if (style != IncDecButtons)
  35969. {
  35970. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  35971. {
  35972. const float sliderPos = (float) valueToProportionOfLength (currentValue);
  35973. jassert (sliderPos >= 0 && sliderPos <= 1.0f);
  35974. getLookAndFeel().drawRotarySlider (g,
  35975. sliderRect.getX(),
  35976. sliderRect.getY(),
  35977. sliderRect.getWidth(),
  35978. sliderRect.getHeight(),
  35979. sliderPos,
  35980. rotaryStart, rotaryEnd,
  35981. *this);
  35982. }
  35983. else
  35984. {
  35985. getLookAndFeel().drawLinearSlider (g,
  35986. sliderRect.getX(),
  35987. sliderRect.getY(),
  35988. sliderRect.getWidth(),
  35989. sliderRect.getHeight(),
  35990. getLinearSliderPos (currentValue),
  35991. getLinearSliderPos (valueMin),
  35992. getLinearSliderPos (valueMax),
  35993. style,
  35994. *this);
  35995. }
  35996. if (style == LinearBar && valueBox == 0)
  35997. {
  35998. g.setColour (findColour (Slider::textBoxOutlineColourId));
  35999. g.drawRect (0, 0, getWidth(), getHeight(), 1);
  36000. }
  36001. }
  36002. }
  36003. void Slider::resized()
  36004. {
  36005. int minXSpace = 0;
  36006. int minYSpace = 0;
  36007. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  36008. minXSpace = 30;
  36009. else
  36010. minYSpace = 15;
  36011. const int tbw = jmax (0, jmin (textBoxWidth, getWidth() - minXSpace));
  36012. const int tbh = jmax (0, jmin (textBoxHeight, getHeight() - minYSpace));
  36013. if (style == LinearBar)
  36014. {
  36015. if (valueBox != 0)
  36016. valueBox->setBounds (0, 0, getWidth(), getHeight());
  36017. }
  36018. else
  36019. {
  36020. if (textBoxPos == NoTextBox)
  36021. {
  36022. sliderRect.setBounds (0, 0, getWidth(), getHeight());
  36023. }
  36024. else if (textBoxPos == TextBoxLeft)
  36025. {
  36026. valueBox->setBounds (0, (getHeight() - tbh) / 2, tbw, tbh);
  36027. sliderRect.setBounds (tbw, 0, getWidth() - tbw, getHeight());
  36028. }
  36029. else if (textBoxPos == TextBoxRight)
  36030. {
  36031. valueBox->setBounds (getWidth() - tbw, (getHeight() - tbh) / 2, tbw, tbh);
  36032. sliderRect.setBounds (0, 0, getWidth() - tbw, getHeight());
  36033. }
  36034. else if (textBoxPos == TextBoxAbove)
  36035. {
  36036. valueBox->setBounds ((getWidth() - tbw) / 2, 0, tbw, tbh);
  36037. sliderRect.setBounds (0, tbh, getWidth(), getHeight() - tbh);
  36038. }
  36039. else if (textBoxPos == TextBoxBelow)
  36040. {
  36041. valueBox->setBounds ((getWidth() - tbw) / 2, getHeight() - tbh, tbw, tbh);
  36042. sliderRect.setBounds (0, 0, getWidth(), getHeight() - tbh);
  36043. }
  36044. }
  36045. const int indent = getLookAndFeel().getSliderThumbRadius (*this);
  36046. if (style == LinearBar)
  36047. {
  36048. const int barIndent = 1;
  36049. sliderRegionStart = barIndent;
  36050. sliderRegionSize = getWidth() - barIndent * 2;
  36051. sliderRect.setBounds (sliderRegionStart, barIndent,
  36052. sliderRegionSize, getHeight() - barIndent * 2);
  36053. }
  36054. else if (isHorizontal())
  36055. {
  36056. sliderRegionStart = sliderRect.getX() + indent;
  36057. sliderRegionSize = jmax (1, sliderRect.getWidth() - indent * 2);
  36058. sliderRect.setBounds (sliderRegionStart, sliderRect.getY(),
  36059. sliderRegionSize, sliderRect.getHeight());
  36060. }
  36061. else if (isVertical())
  36062. {
  36063. sliderRegionStart = sliderRect.getY() + indent;
  36064. sliderRegionSize = jmax (1, sliderRect.getHeight() - indent * 2);
  36065. sliderRect.setBounds (sliderRect.getX(), sliderRegionStart,
  36066. sliderRect.getWidth(), sliderRegionSize);
  36067. }
  36068. else
  36069. {
  36070. sliderRegionStart = 0;
  36071. sliderRegionSize = 100;
  36072. }
  36073. if (style == IncDecButtons)
  36074. {
  36075. Rectangle buttonRect (sliderRect);
  36076. if (textBoxPos == TextBoxLeft || textBoxPos == TextBoxRight)
  36077. buttonRect.expand (-2, 0);
  36078. else
  36079. buttonRect.expand (0, -2);
  36080. incDecButtonsSideBySide = buttonRect.getWidth() > buttonRect.getHeight();
  36081. if (incDecButtonsSideBySide)
  36082. {
  36083. decButton->setBounds (buttonRect.getX(),
  36084. buttonRect.getY(),
  36085. buttonRect.getWidth() / 2,
  36086. buttonRect.getHeight());
  36087. decButton->setConnectedEdges (Button::ConnectedOnRight);
  36088. incButton->setBounds (buttonRect.getCentreX(),
  36089. buttonRect.getY(),
  36090. buttonRect.getWidth() / 2,
  36091. buttonRect.getHeight());
  36092. incButton->setConnectedEdges (Button::ConnectedOnLeft);
  36093. }
  36094. else
  36095. {
  36096. incButton->setBounds (buttonRect.getX(),
  36097. buttonRect.getY(),
  36098. buttonRect.getWidth(),
  36099. buttonRect.getHeight() / 2);
  36100. incButton->setConnectedEdges (Button::ConnectedOnBottom);
  36101. decButton->setBounds (buttonRect.getX(),
  36102. buttonRect.getCentreY(),
  36103. buttonRect.getWidth(),
  36104. buttonRect.getHeight() / 2);
  36105. decButton->setConnectedEdges (Button::ConnectedOnTop);
  36106. }
  36107. }
  36108. }
  36109. void Slider::focusOfChildComponentChanged (FocusChangeType)
  36110. {
  36111. repaint();
  36112. }
  36113. void Slider::mouseDown (const MouseEvent& e)
  36114. {
  36115. mouseWasHidden = false;
  36116. incDecDragged = false;
  36117. if (isEnabled())
  36118. {
  36119. if (e.mods.isPopupMenu() && menuEnabled)
  36120. {
  36121. menuShown = true;
  36122. PopupMenu m;
  36123. m.addItem (1, TRANS ("velocity-sensitive mode"), true, isVelocityBased);
  36124. m.addSeparator();
  36125. if (style == Rotary || style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  36126. {
  36127. PopupMenu rotaryMenu;
  36128. rotaryMenu.addItem (2, TRANS ("use circular dragging"), true, style == Rotary);
  36129. rotaryMenu.addItem (3, TRANS ("use left-right dragging"), true, style == RotaryHorizontalDrag);
  36130. rotaryMenu.addItem (4, TRANS ("use up-down dragging"), true, style == RotaryVerticalDrag);
  36131. m.addSubMenu (TRANS ("rotary mode"), rotaryMenu);
  36132. }
  36133. const int r = m.show();
  36134. if (r == 1)
  36135. {
  36136. setVelocityBasedMode (! isVelocityBased);
  36137. }
  36138. else if (r == 2)
  36139. {
  36140. setSliderStyle (Rotary);
  36141. }
  36142. else if (r == 3)
  36143. {
  36144. setSliderStyle (RotaryHorizontalDrag);
  36145. }
  36146. else if (r == 4)
  36147. {
  36148. setSliderStyle (RotaryVerticalDrag);
  36149. }
  36150. }
  36151. else if (maximum > minimum)
  36152. {
  36153. menuShown = false;
  36154. if (valueBox != 0)
  36155. valueBox->hideEditor (true);
  36156. sliderBeingDragged = 0;
  36157. if (style == TwoValueHorizontal
  36158. || style == TwoValueVertical
  36159. || style == ThreeValueHorizontal
  36160. || style == ThreeValueVertical)
  36161. {
  36162. const float mousePos = (float) (isVertical() ? e.y : e.x);
  36163. const float normalPosDistance = fabsf (getLinearSliderPos (currentValue) - mousePos);
  36164. const float minPosDistance = fabsf (getLinearSliderPos (valueMin) - 0.1f - mousePos);
  36165. const float maxPosDistance = fabsf (getLinearSliderPos (valueMax) + 0.1f - mousePos);
  36166. if (style == TwoValueHorizontal || style == TwoValueVertical)
  36167. {
  36168. if (maxPosDistance <= minPosDistance)
  36169. sliderBeingDragged = 2;
  36170. else
  36171. sliderBeingDragged = 1;
  36172. }
  36173. else if (style == ThreeValueHorizontal || style == ThreeValueVertical)
  36174. {
  36175. if (normalPosDistance >= minPosDistance && maxPosDistance >= minPosDistance)
  36176. sliderBeingDragged = 1;
  36177. else if (normalPosDistance >= maxPosDistance)
  36178. sliderBeingDragged = 2;
  36179. }
  36180. }
  36181. minMaxDiff = valueMax - valueMin;
  36182. mouseXWhenLastDragged = e.x;
  36183. mouseYWhenLastDragged = e.y;
  36184. lastAngle = rotaryStart + (rotaryEnd - rotaryStart)
  36185. * valueToProportionOfLength (currentValue);
  36186. if (sliderBeingDragged == 2)
  36187. valueWhenLastDragged = valueMax;
  36188. else if (sliderBeingDragged == 1)
  36189. valueWhenLastDragged = valueMin;
  36190. else
  36191. valueWhenLastDragged = currentValue;
  36192. valueOnMouseDown = valueWhenLastDragged;
  36193. if (popupDisplayEnabled)
  36194. {
  36195. SliderPopupDisplayComponent* const popup = new SliderPopupDisplayComponent (this);
  36196. popupDisplay = popup;
  36197. if (parentForPopupDisplay != 0)
  36198. {
  36199. parentForPopupDisplay->addChildComponent (popup);
  36200. }
  36201. else
  36202. {
  36203. popup->addToDesktop (0);
  36204. }
  36205. popup->setVisible (true);
  36206. }
  36207. sendDragStart();
  36208. mouseDrag (e);
  36209. }
  36210. }
  36211. }
  36212. void Slider::mouseUp (const MouseEvent&)
  36213. {
  36214. if (isEnabled()
  36215. && (! menuShown)
  36216. && (maximum > minimum)
  36217. && (style != IncDecButtons || incDecDragged))
  36218. {
  36219. restoreMouseIfHidden();
  36220. if (sendChangeOnlyOnRelease && valueOnMouseDown != currentValue)
  36221. triggerChangeMessage (false);
  36222. sendDragEnd();
  36223. deleteAndZero (popupDisplay);
  36224. if (style == IncDecButtons)
  36225. {
  36226. incButton->setState (Button::buttonNormal);
  36227. decButton->setState (Button::buttonNormal);
  36228. }
  36229. }
  36230. }
  36231. void Slider::restoreMouseIfHidden()
  36232. {
  36233. if (mouseWasHidden)
  36234. {
  36235. mouseWasHidden = false;
  36236. Component* c = Component::getComponentUnderMouse();
  36237. if (c == 0)
  36238. c = this;
  36239. c->enableUnboundedMouseMovement (false);
  36240. const double pos = (sliderBeingDragged == 2) ? getMaxValue()
  36241. : ((sliderBeingDragged == 1) ? getMinValue()
  36242. : currentValue);
  36243. if (style == RotaryHorizontalDrag || style == RotaryVerticalDrag)
  36244. {
  36245. int x, y, downX, downY;
  36246. Desktop::getMousePosition (x, y);
  36247. Desktop::getLastMouseDownPosition (downX, downY);
  36248. if (style == RotaryHorizontalDrag)
  36249. {
  36250. const double posDiff = valueToProportionOfLength (pos) - valueToProportionOfLength (valueOnMouseDown);
  36251. x = roundDoubleToInt (pixelsForFullDragExtent * posDiff + downX);
  36252. y = downY;
  36253. }
  36254. else
  36255. {
  36256. const double posDiff = valueToProportionOfLength (valueOnMouseDown) - valueToProportionOfLength (pos);
  36257. x = downX;
  36258. y = roundDoubleToInt (pixelsForFullDragExtent * posDiff + downY);
  36259. }
  36260. Desktop::setMousePosition (x, y);
  36261. }
  36262. else
  36263. {
  36264. const int pixelPos = (int) getLinearSliderPos (pos);
  36265. int x = isHorizontal() ? pixelPos : (getWidth() / 2);
  36266. int y = isVertical() ? pixelPos : (getHeight() / 2);
  36267. relativePositionToGlobal (x, y);
  36268. Desktop::setMousePosition (x, y);
  36269. }
  36270. }
  36271. }
  36272. void Slider::modifierKeysChanged (const ModifierKeys& modifiers)
  36273. {
  36274. if (isEnabled()
  36275. && style != IncDecButtons
  36276. && style != Rotary
  36277. && isVelocityBased == modifiers.isAnyModifierKeyDown())
  36278. {
  36279. restoreMouseIfHidden();
  36280. }
  36281. }
  36282. static double smallestAngleBetween (double a1, double a2)
  36283. {
  36284. return jmin (fabs (a1 - a2),
  36285. fabs (a1 + double_Pi * 2.0 - a2),
  36286. fabs (a2 + double_Pi * 2.0 - a1));
  36287. }
  36288. void Slider::mouseDrag (const MouseEvent& e)
  36289. {
  36290. if (isEnabled()
  36291. && (! menuShown)
  36292. && (maximum > minimum))
  36293. {
  36294. if (style == Rotary)
  36295. {
  36296. int dx = e.x - sliderRect.getCentreX();
  36297. int dy = e.y - sliderRect.getCentreY();
  36298. if (dx * dx + dy * dy > 25)
  36299. {
  36300. double angle = atan2 ((double) dx, (double) -dy);
  36301. while (angle < 0.0)
  36302. angle += double_Pi * 2.0;
  36303. if (rotaryStop && ! e.mouseWasClicked())
  36304. {
  36305. if (fabs (angle - lastAngle) > double_Pi)
  36306. {
  36307. if (angle >= lastAngle)
  36308. angle -= double_Pi * 2.0;
  36309. else
  36310. angle += double_Pi * 2.0;
  36311. }
  36312. if (angle >= lastAngle)
  36313. angle = jmin (angle, (double) jmax (rotaryStart, rotaryEnd));
  36314. else
  36315. angle = jmax (angle, (double) jmin (rotaryStart, rotaryEnd));
  36316. }
  36317. else
  36318. {
  36319. while (angle < rotaryStart)
  36320. angle += double_Pi * 2.0;
  36321. if (angle > rotaryEnd)
  36322. {
  36323. if (smallestAngleBetween (angle, rotaryStart) <= smallestAngleBetween (angle, rotaryEnd))
  36324. angle = rotaryStart;
  36325. else
  36326. angle = rotaryEnd;
  36327. }
  36328. }
  36329. const double proportion = (angle - rotaryStart) / (rotaryEnd - rotaryStart);
  36330. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, proportion));
  36331. lastAngle = angle;
  36332. }
  36333. }
  36334. else
  36335. {
  36336. if (style == LinearBar && e.mouseWasClicked()
  36337. && valueBox != 0 && valueBox->isEditable())
  36338. return;
  36339. if (style == IncDecButtons)
  36340. {
  36341. if (! incDecDragged)
  36342. incDecDragged = e.getDistanceFromDragStart() > 10 && ! e.mouseWasClicked();
  36343. if (! incDecDragged)
  36344. return;
  36345. }
  36346. if ((isVelocityBased == (userKeyOverridesVelocity ? e.mods.testFlags (ModifierKeys::ctrlModifier | ModifierKeys::commandModifier | ModifierKeys::altModifier)
  36347. : false))
  36348. || ((maximum - minimum) / sliderRegionSize < interval))
  36349. {
  36350. const int mousePos = (isHorizontal() || style == RotaryHorizontalDrag) ? e.x : e.y;
  36351. double scaledMousePos = (mousePos - sliderRegionStart) / (double) sliderRegionSize;
  36352. if (style == RotaryHorizontalDrag
  36353. || style == RotaryVerticalDrag
  36354. || style == IncDecButtons
  36355. || ((style == LinearHorizontal || style == LinearVertical || style == LinearBar)
  36356. && ! snapsToMousePos))
  36357. {
  36358. const int mouseDiff = (style == RotaryHorizontalDrag
  36359. || style == LinearHorizontal
  36360. || style == LinearBar
  36361. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  36362. ? e.getDistanceFromDragStartX()
  36363. : -e.getDistanceFromDragStartY();
  36364. double newPos = valueToProportionOfLength (valueOnMouseDown)
  36365. + mouseDiff * (1.0 / pixelsForFullDragExtent);
  36366. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, newPos));
  36367. if (style == IncDecButtons)
  36368. {
  36369. incButton->setState (mouseDiff < 0 ? Button::buttonNormal : Button::buttonDown);
  36370. decButton->setState (mouseDiff > 0 ? Button::buttonNormal : Button::buttonDown);
  36371. }
  36372. }
  36373. else
  36374. {
  36375. if (isVertical())
  36376. scaledMousePos = 1.0 - scaledMousePos;
  36377. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, scaledMousePos));
  36378. }
  36379. }
  36380. else
  36381. {
  36382. const int mouseDiff = (isHorizontal() || style == RotaryHorizontalDrag
  36383. || (style == IncDecButtons && incDecDragDirectionIsHorizontal()))
  36384. ? e.x - mouseXWhenLastDragged
  36385. : e.y - mouseYWhenLastDragged;
  36386. const double maxSpeed = jmax (200, sliderRegionSize);
  36387. double speed = jlimit (0.0, maxSpeed, (double) abs (mouseDiff));
  36388. if (speed != 0)
  36389. {
  36390. speed = 0.2 * velocityModeSensitivity
  36391. * (1.0 + sin (double_Pi * (1.5 + jmin (0.5, velocityModeOffset
  36392. + jmax (0.0, (double) (speed - velocityModeThreshold))
  36393. / maxSpeed))));
  36394. if (mouseDiff < 0)
  36395. speed = -speed;
  36396. if (isVertical() || style == RotaryVerticalDrag
  36397. || (style == IncDecButtons && ! incDecDragDirectionIsHorizontal()))
  36398. speed = -speed;
  36399. const double currentPos = valueToProportionOfLength (valueWhenLastDragged);
  36400. valueWhenLastDragged = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + speed));
  36401. e.originalComponent->enableUnboundedMouseMovement (true, false);
  36402. mouseWasHidden = true;
  36403. }
  36404. }
  36405. }
  36406. valueWhenLastDragged = jlimit (minimum, maximum, valueWhenLastDragged);
  36407. if (sliderBeingDragged == 0)
  36408. {
  36409. setValue (snapValue (valueWhenLastDragged, true),
  36410. ! sendChangeOnlyOnRelease, true);
  36411. }
  36412. else if (sliderBeingDragged == 1)
  36413. {
  36414. setMinValue (snapValue (valueWhenLastDragged, true),
  36415. ! sendChangeOnlyOnRelease, false);
  36416. if (e.mods.isShiftDown())
  36417. setMaxValue (getMinValue() + minMaxDiff, false);
  36418. else
  36419. minMaxDiff = valueMax - valueMin;
  36420. }
  36421. else
  36422. {
  36423. jassert (sliderBeingDragged == 2);
  36424. setMaxValue (snapValue (valueWhenLastDragged, true),
  36425. ! sendChangeOnlyOnRelease, false);
  36426. if (e.mods.isShiftDown())
  36427. setMinValue (getMaxValue() - minMaxDiff, false);
  36428. else
  36429. minMaxDiff = valueMax - valueMin;
  36430. }
  36431. mouseXWhenLastDragged = e.x;
  36432. mouseYWhenLastDragged = e.y;
  36433. }
  36434. }
  36435. void Slider::mouseDoubleClick (const MouseEvent&)
  36436. {
  36437. if (doubleClickToValue
  36438. && isEnabled()
  36439. && style != IncDecButtons
  36440. && minimum <= doubleClickReturnValue
  36441. && maximum >= doubleClickReturnValue)
  36442. {
  36443. sendDragStart();
  36444. setValue (doubleClickReturnValue, true, true);
  36445. sendDragEnd();
  36446. }
  36447. }
  36448. void Slider::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  36449. {
  36450. if (scrollWheelEnabled && isEnabled()
  36451. && style != TwoValueHorizontal
  36452. && style != TwoValueVertical)
  36453. {
  36454. if (maximum > minimum && ! isMouseButtonDownAnywhere())
  36455. {
  36456. if (valueBox != 0)
  36457. valueBox->hideEditor (false);
  36458. const double proportionDelta = (wheelIncrementX != 0 ? -wheelIncrementX : wheelIncrementY) * 0.15f;
  36459. const double currentPos = valueToProportionOfLength (currentValue);
  36460. const double newValue = proportionOfLengthToValue (jlimit (0.0, 1.0, currentPos + proportionDelta));
  36461. double delta = (newValue != currentValue)
  36462. ? jmax (fabs (newValue - currentValue), interval) : 0;
  36463. if (currentValue > newValue)
  36464. delta = -delta;
  36465. sendDragStart();
  36466. setValue (snapValue (currentValue + delta, false), true, true);
  36467. sendDragEnd();
  36468. }
  36469. }
  36470. else
  36471. {
  36472. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  36473. }
  36474. }
  36475. void SliderListener::sliderDragStarted (Slider*)
  36476. {
  36477. }
  36478. void SliderListener::sliderDragEnded (Slider*)
  36479. {
  36480. }
  36481. END_JUCE_NAMESPACE
  36482. /********* End of inlined file: juce_Slider.cpp *********/
  36483. /********* Start of inlined file: juce_TableHeaderComponent.cpp *********/
  36484. BEGIN_JUCE_NAMESPACE
  36485. class DragOverlayComp : public Component
  36486. {
  36487. public:
  36488. DragOverlayComp (Image* const image_)
  36489. : image (image_)
  36490. {
  36491. image->multiplyAllAlphas (0.8f);
  36492. setAlwaysOnTop (true);
  36493. }
  36494. ~DragOverlayComp()
  36495. {
  36496. delete image;
  36497. }
  36498. void paint (Graphics& g)
  36499. {
  36500. g.drawImageAt (image, 0, 0);
  36501. }
  36502. private:
  36503. Image* image;
  36504. DragOverlayComp (const DragOverlayComp&);
  36505. const DragOverlayComp& operator= (const DragOverlayComp&);
  36506. };
  36507. TableHeaderComponent::TableHeaderComponent()
  36508. : listeners (2),
  36509. dragOverlayComp (0),
  36510. columnsChanged (false),
  36511. columnsResized (false),
  36512. sortChanged (false),
  36513. menuActive (true),
  36514. stretchToFit (false),
  36515. columnIdBeingResized (0),
  36516. columnIdBeingDragged (0),
  36517. columnIdUnderMouse (0),
  36518. lastDeliberateWidth (0)
  36519. {
  36520. }
  36521. TableHeaderComponent::~TableHeaderComponent()
  36522. {
  36523. delete dragOverlayComp;
  36524. }
  36525. void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
  36526. {
  36527. menuActive = hasMenu;
  36528. }
  36529. bool TableHeaderComponent::isPopupMenuActive() const throw() { return menuActive; }
  36530. int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const throw()
  36531. {
  36532. if (onlyCountVisibleColumns)
  36533. {
  36534. int num = 0;
  36535. for (int i = columns.size(); --i >= 0;)
  36536. if (columns.getUnchecked(i)->isVisible())
  36537. ++num;
  36538. return num;
  36539. }
  36540. else
  36541. {
  36542. return columns.size();
  36543. }
  36544. }
  36545. const String TableHeaderComponent::getColumnName (const int columnId) const throw()
  36546. {
  36547. const ColumnInfo* const ci = getInfoForId (columnId);
  36548. return ci != 0 ? ci->name : String::empty;
  36549. }
  36550. void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
  36551. {
  36552. ColumnInfo* const ci = getInfoForId (columnId);
  36553. if (ci != 0 && ci->name != newName)
  36554. {
  36555. ci->name = newName;
  36556. sendColumnsChanged();
  36557. }
  36558. }
  36559. void TableHeaderComponent::addColumn (const String& columnName,
  36560. const int columnId,
  36561. const int width,
  36562. const int minimumWidth,
  36563. const int maximumWidth,
  36564. const int propertyFlags,
  36565. const int insertIndex)
  36566. {
  36567. // can't have a duplicate or null ID!
  36568. jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
  36569. jassert (width > 0);
  36570. ColumnInfo* const ci = new ColumnInfo();
  36571. ci->name = columnName;
  36572. ci->id = columnId;
  36573. ci->width = width;
  36574. ci->lastDeliberateWidth = width;
  36575. ci->minimumWidth = minimumWidth;
  36576. ci->maximumWidth = maximumWidth;
  36577. if (ci->maximumWidth < 0)
  36578. ci->maximumWidth = INT_MAX;
  36579. jassert (ci->maximumWidth >= ci->minimumWidth);
  36580. ci->propertyFlags = propertyFlags;
  36581. columns.insert (insertIndex, ci);
  36582. sendColumnsChanged();
  36583. }
  36584. void TableHeaderComponent::removeColumn (const int columnIdToRemove)
  36585. {
  36586. const int index = getIndexOfColumnId (columnIdToRemove, false);
  36587. if (index >= 0)
  36588. {
  36589. columns.remove (index);
  36590. sortChanged = true;
  36591. sendColumnsChanged();
  36592. }
  36593. }
  36594. void TableHeaderComponent::removeAllColumns()
  36595. {
  36596. if (columns.size() > 0)
  36597. {
  36598. columns.clear();
  36599. sendColumnsChanged();
  36600. }
  36601. }
  36602. void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
  36603. {
  36604. const int currentIndex = getIndexOfColumnId (columnId, false);
  36605. newIndex = visibleIndexToTotalIndex (newIndex);
  36606. if (columns [currentIndex] != 0 && currentIndex != newIndex)
  36607. {
  36608. columns.move (currentIndex, newIndex);
  36609. sendColumnsChanged();
  36610. }
  36611. }
  36612. void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
  36613. {
  36614. ColumnInfo* const ci = getInfoForId (columnId);
  36615. if (ci != 0 && ci->width != newWidth)
  36616. {
  36617. const int numColumns = getNumColumns (true);
  36618. ci->lastDeliberateWidth = ci->width
  36619. = jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
  36620. if (stretchToFit)
  36621. {
  36622. const int index = getIndexOfColumnId (columnId, true) + 1;
  36623. if (((unsigned int) index) < (unsigned int) numColumns)
  36624. {
  36625. const int x = getColumnPosition (index).getX();
  36626. if (lastDeliberateWidth == 0)
  36627. lastDeliberateWidth = getTotalWidth();
  36628. resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
  36629. }
  36630. }
  36631. repaint();
  36632. columnsResized = true;
  36633. triggerAsyncUpdate();
  36634. }
  36635. }
  36636. int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const throw()
  36637. {
  36638. int n = 0;
  36639. for (int i = 0; i < columns.size(); ++i)
  36640. {
  36641. if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
  36642. {
  36643. if (columns.getUnchecked(i)->id == columnId)
  36644. return n;
  36645. ++n;
  36646. }
  36647. }
  36648. return -1;
  36649. }
  36650. int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const throw()
  36651. {
  36652. if (onlyCountVisibleColumns)
  36653. index = visibleIndexToTotalIndex (index);
  36654. const ColumnInfo* const ci = columns [index];
  36655. return (ci != 0) ? ci->id : 0;
  36656. }
  36657. const Rectangle TableHeaderComponent::getColumnPosition (const int index) const throw()
  36658. {
  36659. int x = 0, width = 0, n = 0;
  36660. for (int i = 0; i < columns.size(); ++i)
  36661. {
  36662. x += width;
  36663. if (columns.getUnchecked(i)->isVisible())
  36664. {
  36665. width = columns.getUnchecked(i)->width;
  36666. if (n++ == index)
  36667. break;
  36668. }
  36669. else
  36670. {
  36671. width = 0;
  36672. }
  36673. }
  36674. return Rectangle (x, 0, width, getHeight());
  36675. }
  36676. int TableHeaderComponent::getColumnIdAtX (const int xToFind) const throw()
  36677. {
  36678. if (xToFind >= 0)
  36679. {
  36680. int x = 0;
  36681. for (int i = 0; i < columns.size(); ++i)
  36682. {
  36683. const ColumnInfo* const ci = columns.getUnchecked(i);
  36684. if (ci->isVisible())
  36685. {
  36686. x += ci->width;
  36687. if (xToFind < x)
  36688. return ci->id;
  36689. }
  36690. }
  36691. }
  36692. return 0;
  36693. }
  36694. int TableHeaderComponent::getTotalWidth() const throw()
  36695. {
  36696. int w = 0;
  36697. for (int i = columns.size(); --i >= 0;)
  36698. if (columns.getUnchecked(i)->isVisible())
  36699. w += columns.getUnchecked(i)->width;
  36700. return w;
  36701. }
  36702. void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
  36703. {
  36704. stretchToFit = shouldStretchToFit;
  36705. lastDeliberateWidth = getTotalWidth();
  36706. resized();
  36707. }
  36708. bool TableHeaderComponent::isStretchToFitActive() const throw()
  36709. {
  36710. return stretchToFit;
  36711. }
  36712. void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
  36713. {
  36714. if (stretchToFit && getWidth() > 0
  36715. && columnIdBeingResized == 0 && columnIdBeingDragged == 0)
  36716. {
  36717. lastDeliberateWidth = targetTotalWidth;
  36718. resizeColumnsToFit (0, targetTotalWidth);
  36719. }
  36720. }
  36721. void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
  36722. {
  36723. targetTotalWidth = jmax (targetTotalWidth, 0);
  36724. StretchableObjectResizer sor;
  36725. int i;
  36726. for (i = firstColumnIndex; i < columns.size(); ++i)
  36727. {
  36728. ColumnInfo* const ci = columns.getUnchecked(i);
  36729. if (ci->isVisible())
  36730. sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
  36731. }
  36732. sor.resizeToFit (targetTotalWidth);
  36733. int visIndex = 0;
  36734. for (i = firstColumnIndex; i < columns.size(); ++i)
  36735. {
  36736. ColumnInfo* const ci = columns.getUnchecked(i);
  36737. if (ci->isVisible())
  36738. {
  36739. const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
  36740. (int) floor (sor.getItemSize (visIndex++)));
  36741. if (newWidth != ci->width)
  36742. {
  36743. ci->width = newWidth;
  36744. repaint();
  36745. columnsResized = true;
  36746. triggerAsyncUpdate();
  36747. }
  36748. }
  36749. }
  36750. }
  36751. void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
  36752. {
  36753. ColumnInfo* const ci = getInfoForId (columnId);
  36754. if (ci != 0 && shouldBeVisible != ci->isVisible())
  36755. {
  36756. if (shouldBeVisible)
  36757. ci->propertyFlags |= visible;
  36758. else
  36759. ci->propertyFlags &= ~visible;
  36760. sendColumnsChanged();
  36761. resized();
  36762. }
  36763. }
  36764. bool TableHeaderComponent::isColumnVisible (const int columnId) const
  36765. {
  36766. const ColumnInfo* const ci = getInfoForId (columnId);
  36767. return ci != 0 && ci->isVisible();
  36768. }
  36769. void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
  36770. {
  36771. if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
  36772. {
  36773. for (int i = columns.size(); --i >= 0;)
  36774. columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
  36775. ColumnInfo* const ci = getInfoForId (columnId);
  36776. if (ci != 0)
  36777. ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
  36778. reSortTable();
  36779. }
  36780. }
  36781. int TableHeaderComponent::getSortColumnId() const throw()
  36782. {
  36783. for (int i = columns.size(); --i >= 0;)
  36784. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  36785. return columns.getUnchecked(i)->id;
  36786. return 0;
  36787. }
  36788. bool TableHeaderComponent::isSortedForwards() const throw()
  36789. {
  36790. for (int i = columns.size(); --i >= 0;)
  36791. if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
  36792. return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
  36793. return true;
  36794. }
  36795. void TableHeaderComponent::reSortTable()
  36796. {
  36797. sortChanged = true;
  36798. repaint();
  36799. triggerAsyncUpdate();
  36800. }
  36801. const String TableHeaderComponent::toString() const
  36802. {
  36803. String s;
  36804. XmlElement doc (T("TABLELAYOUT"));
  36805. doc.setAttribute (T("sortedCol"), getSortColumnId());
  36806. doc.setAttribute (T("sortForwards"), isSortedForwards());
  36807. for (int i = 0; i < columns.size(); ++i)
  36808. {
  36809. const ColumnInfo* const ci = columns.getUnchecked (i);
  36810. XmlElement* const e = new XmlElement (T("COLUMN"));
  36811. doc.addChildElement (e);
  36812. e->setAttribute (T("id"), ci->id);
  36813. e->setAttribute (T("visible"), ci->isVisible());
  36814. e->setAttribute (T("width"), ci->width);
  36815. }
  36816. return doc.createDocument (String::empty, true, false);
  36817. }
  36818. void TableHeaderComponent::restoreFromString (const String& storedVersion)
  36819. {
  36820. XmlDocument doc (storedVersion);
  36821. XmlElement* const storedXml = doc.getDocumentElement();
  36822. int index = 0;
  36823. if (storedXml != 0 && storedXml->hasTagName (T("TABLELAYOUT")))
  36824. {
  36825. forEachXmlChildElement (*storedXml, col)
  36826. {
  36827. const int tabId = col->getIntAttribute (T("id"));
  36828. ColumnInfo* const ci = getInfoForId (tabId);
  36829. if (ci != 0)
  36830. {
  36831. columns.move (columns.indexOf (ci), index);
  36832. ci->width = col->getIntAttribute (T("width"));
  36833. setColumnVisible (tabId, col->getBoolAttribute (T("visible")));
  36834. }
  36835. ++index;
  36836. }
  36837. columnsResized = true;
  36838. sendColumnsChanged();
  36839. setSortColumnId (storedXml->getIntAttribute (T("sortedCol")),
  36840. storedXml->getBoolAttribute (T("sortForwards"), true));
  36841. }
  36842. delete storedXml;
  36843. }
  36844. void TableHeaderComponent::addListener (TableHeaderListener* const newListener) throw()
  36845. {
  36846. listeners.addIfNotAlreadyThere (newListener);
  36847. }
  36848. void TableHeaderComponent::removeListener (TableHeaderListener* const listenerToRemove) throw()
  36849. {
  36850. listeners.removeValue (listenerToRemove);
  36851. }
  36852. void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
  36853. {
  36854. const ColumnInfo* const ci = getInfoForId (columnId);
  36855. if (ci != 0 && (ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
  36856. setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
  36857. }
  36858. void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
  36859. {
  36860. for (int i = 0; i < columns.size(); ++i)
  36861. {
  36862. const ColumnInfo* const ci = columns.getUnchecked(i);
  36863. if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
  36864. menu.addItem (ci->id, ci->name,
  36865. (ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
  36866. isColumnVisible (ci->id));
  36867. }
  36868. }
  36869. void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
  36870. {
  36871. if (getIndexOfColumnId (menuReturnId, false) >= 0)
  36872. setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
  36873. }
  36874. void TableHeaderComponent::paint (Graphics& g)
  36875. {
  36876. LookAndFeel& lf = getLookAndFeel();
  36877. lf.drawTableHeaderBackground (g, *this);
  36878. const Rectangle clip (g.getClipBounds());
  36879. int x = 0;
  36880. for (int i = 0; i < columns.size(); ++i)
  36881. {
  36882. const ColumnInfo* const ci = columns.getUnchecked(i);
  36883. if (ci->isVisible())
  36884. {
  36885. if (x + ci->width > clip.getX()
  36886. && (ci->id != columnIdBeingDragged
  36887. || dragOverlayComp == 0
  36888. || ! dragOverlayComp->isVisible()))
  36889. {
  36890. g.saveState();
  36891. g.setOrigin (x, 0);
  36892. g.reduceClipRegion (0, 0, ci->width, getHeight());
  36893. lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
  36894. ci->id == columnIdUnderMouse,
  36895. ci->id == columnIdUnderMouse && isMouseButtonDown(),
  36896. ci->propertyFlags);
  36897. g.restoreState();
  36898. }
  36899. x += ci->width;
  36900. if (x >= clip.getRight())
  36901. break;
  36902. }
  36903. }
  36904. }
  36905. void TableHeaderComponent::resized()
  36906. {
  36907. }
  36908. void TableHeaderComponent::mouseMove (const MouseEvent& e)
  36909. {
  36910. updateColumnUnderMouse (e.x, e.y);
  36911. }
  36912. void TableHeaderComponent::mouseEnter (const MouseEvent& e)
  36913. {
  36914. updateColumnUnderMouse (e.x, e.y);
  36915. }
  36916. void TableHeaderComponent::mouseExit (const MouseEvent& e)
  36917. {
  36918. updateColumnUnderMouse (e.x, e.y);
  36919. }
  36920. void TableHeaderComponent::mouseDown (const MouseEvent& e)
  36921. {
  36922. repaint();
  36923. columnIdBeingResized = 0;
  36924. columnIdBeingDragged = 0;
  36925. if (columnIdUnderMouse != 0)
  36926. {
  36927. draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
  36928. if (e.mods.isPopupMenu())
  36929. columnClicked (columnIdUnderMouse, e.mods);
  36930. }
  36931. if (menuActive && e.mods.isPopupMenu())
  36932. showColumnChooserMenu (columnIdUnderMouse);
  36933. }
  36934. void TableHeaderComponent::mouseDrag (const MouseEvent& e)
  36935. {
  36936. if (columnIdBeingResized == 0
  36937. && columnIdBeingDragged == 0
  36938. && ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
  36939. {
  36940. deleteAndZero (dragOverlayComp);
  36941. columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
  36942. if (columnIdBeingResized != 0)
  36943. {
  36944. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  36945. initialColumnWidth = ci->width;
  36946. }
  36947. else
  36948. {
  36949. beginDrag (e);
  36950. }
  36951. }
  36952. if (columnIdBeingResized != 0)
  36953. {
  36954. const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
  36955. if (ci != 0)
  36956. {
  36957. int w = jlimit (ci->minimumWidth, ci->maximumWidth,
  36958. initialColumnWidth + e.getDistanceFromDragStartX());
  36959. if (stretchToFit)
  36960. {
  36961. // prevent us dragging a column too far right if we're in stretch-to-fit mode
  36962. int minWidthOnRight = 0;
  36963. for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
  36964. if (columns.getUnchecked (i)->isVisible())
  36965. minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
  36966. const Rectangle currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
  36967. w = jmax (ci->minimumWidth, jmin (w, getWidth() - minWidthOnRight - currentPos.getX()));
  36968. }
  36969. setColumnWidth (columnIdBeingResized, w);
  36970. }
  36971. }
  36972. else if (columnIdBeingDragged != 0)
  36973. {
  36974. if (e.y >= -50 && e.y < getHeight() + 50)
  36975. {
  36976. beginDrag (e);
  36977. if (dragOverlayComp != 0)
  36978. {
  36979. dragOverlayComp->setVisible (true);
  36980. dragOverlayComp->setBounds (jlimit (0,
  36981. jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
  36982. e.x - draggingColumnOffset),
  36983. 0,
  36984. dragOverlayComp->getWidth(),
  36985. getHeight());
  36986. for (int i = columns.size(); --i >= 0;)
  36987. {
  36988. const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  36989. int newIndex = currentIndex;
  36990. if (newIndex > 0)
  36991. {
  36992. // if the previous column isn't draggable, we can't move our column
  36993. // past it, because that'd change the undraggable column's position..
  36994. const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
  36995. if ((previous->propertyFlags & draggable) != 0)
  36996. {
  36997. const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
  36998. const int rightOfCurrent = getColumnPosition (newIndex).getRight();
  36999. if (abs (dragOverlayComp->getX() - leftOfPrevious)
  37000. < abs (dragOverlayComp->getRight() - rightOfCurrent))
  37001. {
  37002. --newIndex;
  37003. }
  37004. }
  37005. }
  37006. if (newIndex < columns.size() - 1)
  37007. {
  37008. // if the next column isn't draggable, we can't move our column
  37009. // past it, because that'd change the undraggable column's position..
  37010. const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
  37011. if ((nextCol->propertyFlags & draggable) != 0)
  37012. {
  37013. const int leftOfCurrent = getColumnPosition (newIndex).getX();
  37014. const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
  37015. if (abs (dragOverlayComp->getX() - leftOfCurrent)
  37016. > abs (dragOverlayComp->getRight() - rightOfNext))
  37017. {
  37018. ++newIndex;
  37019. }
  37020. }
  37021. }
  37022. if (newIndex != currentIndex)
  37023. moveColumn (columnIdBeingDragged, newIndex);
  37024. else
  37025. break;
  37026. }
  37027. }
  37028. }
  37029. else
  37030. {
  37031. endDrag (draggingColumnOriginalIndex);
  37032. }
  37033. }
  37034. }
  37035. void TableHeaderComponent::beginDrag (const MouseEvent& e)
  37036. {
  37037. if (columnIdBeingDragged == 0)
  37038. {
  37039. columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
  37040. const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
  37041. if (ci == 0 || (ci->propertyFlags & draggable) == 0)
  37042. {
  37043. columnIdBeingDragged = 0;
  37044. }
  37045. else
  37046. {
  37047. draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
  37048. const Rectangle columnRect (getColumnPosition (draggingColumnOriginalIndex));
  37049. const int temp = columnIdBeingDragged;
  37050. columnIdBeingDragged = 0;
  37051. addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
  37052. columnIdBeingDragged = temp;
  37053. dragOverlayComp->setBounds (columnRect);
  37054. for (int i = listeners.size(); --i >= 0;)
  37055. {
  37056. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
  37057. i = jmin (i, listeners.size() - 1);
  37058. }
  37059. }
  37060. }
  37061. }
  37062. void TableHeaderComponent::endDrag (const int finalIndex)
  37063. {
  37064. if (columnIdBeingDragged != 0)
  37065. {
  37066. moveColumn (columnIdBeingDragged, finalIndex);
  37067. columnIdBeingDragged = 0;
  37068. repaint();
  37069. for (int i = listeners.size(); --i >= 0;)
  37070. {
  37071. listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
  37072. i = jmin (i, listeners.size() - 1);
  37073. }
  37074. }
  37075. }
  37076. void TableHeaderComponent::mouseUp (const MouseEvent& e)
  37077. {
  37078. mouseDrag (e);
  37079. for (int i = columns.size(); --i >= 0;)
  37080. if (columns.getUnchecked (i)->isVisible())
  37081. columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
  37082. columnIdBeingResized = 0;
  37083. repaint();
  37084. endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
  37085. updateColumnUnderMouse (e.x, e.y);
  37086. if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
  37087. columnClicked (columnIdUnderMouse, e.mods);
  37088. deleteAndZero (dragOverlayComp);
  37089. }
  37090. const MouseCursor TableHeaderComponent::getMouseCursor()
  37091. {
  37092. int x, y;
  37093. getMouseXYRelative (x, y);
  37094. if (columnIdBeingResized != 0 || (getResizeDraggerAt (x) != 0 && ! isMouseButtonDown()))
  37095. return MouseCursor (MouseCursor::LeftRightResizeCursor);
  37096. return Component::getMouseCursor();
  37097. }
  37098. bool TableHeaderComponent::ColumnInfo::isVisible() const throw()
  37099. {
  37100. return (propertyFlags & TableHeaderComponent::visible) != 0;
  37101. }
  37102. TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const throw()
  37103. {
  37104. for (int i = columns.size(); --i >= 0;)
  37105. if (columns.getUnchecked(i)->id == id)
  37106. return columns.getUnchecked(i);
  37107. return 0;
  37108. }
  37109. int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const throw()
  37110. {
  37111. int n = 0;
  37112. for (int i = 0; i < columns.size(); ++i)
  37113. {
  37114. if (columns.getUnchecked(i)->isVisible())
  37115. {
  37116. if (n == visibleIndex)
  37117. return i;
  37118. ++n;
  37119. }
  37120. }
  37121. return -1;
  37122. }
  37123. void TableHeaderComponent::sendColumnsChanged()
  37124. {
  37125. if (stretchToFit && lastDeliberateWidth > 0)
  37126. resizeAllColumnsToFit (lastDeliberateWidth);
  37127. repaint();
  37128. columnsChanged = true;
  37129. triggerAsyncUpdate();
  37130. }
  37131. void TableHeaderComponent::handleAsyncUpdate()
  37132. {
  37133. const bool changed = columnsChanged || sortChanged;
  37134. const bool sized = columnsResized || changed;
  37135. const bool sorted = sortChanged;
  37136. columnsChanged = false;
  37137. columnsResized = false;
  37138. sortChanged = false;
  37139. if (sorted)
  37140. {
  37141. for (int i = listeners.size(); --i >= 0;)
  37142. {
  37143. listeners.getUnchecked(i)->tableSortOrderChanged (this);
  37144. i = jmin (i, listeners.size() - 1);
  37145. }
  37146. }
  37147. if (changed)
  37148. {
  37149. for (int i = listeners.size(); --i >= 0;)
  37150. {
  37151. listeners.getUnchecked(i)->tableColumnsChanged (this);
  37152. i = jmin (i, listeners.size() - 1);
  37153. }
  37154. }
  37155. if (sized)
  37156. {
  37157. for (int i = listeners.size(); --i >= 0;)
  37158. {
  37159. listeners.getUnchecked(i)->tableColumnsResized (this);
  37160. i = jmin (i, listeners.size() - 1);
  37161. }
  37162. }
  37163. }
  37164. int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const throw()
  37165. {
  37166. if (((unsigned int) mouseX) < (unsigned int) getWidth())
  37167. {
  37168. const int draggableDistance = 3;
  37169. int x = 0;
  37170. for (int i = 0; i < columns.size(); ++i)
  37171. {
  37172. const ColumnInfo* const ci = columns.getUnchecked(i);
  37173. if (ci->isVisible())
  37174. {
  37175. if (abs (mouseX - (x + ci->width)) <= draggableDistance
  37176. && (ci->propertyFlags & resizable) != 0)
  37177. return ci->id;
  37178. x += ci->width;
  37179. }
  37180. }
  37181. }
  37182. return 0;
  37183. }
  37184. void TableHeaderComponent::updateColumnUnderMouse (int x, int y)
  37185. {
  37186. const int newCol = (reallyContains (x, y, true) && getResizeDraggerAt (x) == 0)
  37187. ? getColumnIdAtX (x) : 0;
  37188. if (newCol != columnIdUnderMouse)
  37189. {
  37190. columnIdUnderMouse = newCol;
  37191. repaint();
  37192. }
  37193. }
  37194. void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
  37195. {
  37196. PopupMenu m;
  37197. addMenuItems (m, columnIdClicked);
  37198. if (m.getNumItems() > 0)
  37199. {
  37200. const int result = m.show();
  37201. if (result != 0)
  37202. reactToMenuItem (result, columnIdClicked);
  37203. }
  37204. }
  37205. void TableHeaderListener::tableColumnDraggingChanged (TableHeaderComponent*, int)
  37206. {
  37207. }
  37208. END_JUCE_NAMESPACE
  37209. /********* End of inlined file: juce_TableHeaderComponent.cpp *********/
  37210. /********* Start of inlined file: juce_TableListBox.cpp *********/
  37211. BEGIN_JUCE_NAMESPACE
  37212. static const tchar* const tableColumnPropertyTag = T("_tableColumnID");
  37213. class TableListRowComp : public Component
  37214. {
  37215. public:
  37216. TableListRowComp (TableListBox& owner_)
  37217. : owner (owner_),
  37218. row (-1),
  37219. isSelected (false)
  37220. {
  37221. }
  37222. ~TableListRowComp()
  37223. {
  37224. deleteAllChildren();
  37225. }
  37226. void paint (Graphics& g)
  37227. {
  37228. TableListBoxModel* const model = owner.getModel();
  37229. if (model != 0)
  37230. {
  37231. const TableHeaderComponent* const header = owner.getHeader();
  37232. model->paintRowBackground (g, row, getWidth(), getHeight(), isSelected);
  37233. const int numColumns = header->getNumColumns (true);
  37234. for (int i = 0; i < numColumns; ++i)
  37235. {
  37236. if (! columnsWithComponents [i])
  37237. {
  37238. const int columnId = header->getColumnIdOfIndex (i, true);
  37239. Rectangle columnRect (header->getColumnPosition (i));
  37240. columnRect.setSize (columnRect.getWidth(), getHeight());
  37241. g.saveState();
  37242. g.reduceClipRegion (columnRect);
  37243. g.setOrigin (columnRect.getX(), 0);
  37244. model->paintCell (g, row, columnId, columnRect.getWidth(), columnRect.getHeight(), isSelected);
  37245. g.restoreState();
  37246. }
  37247. }
  37248. }
  37249. }
  37250. void update (const int newRow, const bool isNowSelected)
  37251. {
  37252. if (newRow != row || isNowSelected != isSelected)
  37253. {
  37254. row = newRow;
  37255. isSelected = isNowSelected;
  37256. repaint();
  37257. }
  37258. if (row < owner.getNumRows())
  37259. {
  37260. jassert (row >= 0);
  37261. const tchar* const tagPropertyName = T("_tableLastUseNum");
  37262. const int newTag = Random::getSystemRandom().nextInt();
  37263. const TableHeaderComponent* const header = owner.getHeader();
  37264. const int numColumns = header->getNumColumns (true);
  37265. int i;
  37266. columnsWithComponents.clear();
  37267. if (owner.getModel() != 0)
  37268. {
  37269. for (i = 0; i < numColumns; ++i)
  37270. {
  37271. const int columnId = header->getColumnIdOfIndex (i, true);
  37272. Component* const newComp
  37273. = owner.getModel()->refreshComponentForCell (row, columnId, isSelected,
  37274. findChildComponentForColumn (columnId));
  37275. if (newComp != 0)
  37276. {
  37277. addAndMakeVisible (newComp);
  37278. newComp->setComponentProperty (tagPropertyName, newTag);
  37279. newComp->setComponentProperty (tableColumnPropertyTag, columnId);
  37280. const Rectangle columnRect (header->getColumnPosition (i));
  37281. newComp->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  37282. columnsWithComponents.setBit (i);
  37283. }
  37284. }
  37285. }
  37286. for (i = getNumChildComponents(); --i >= 0;)
  37287. {
  37288. Component* const c = getChildComponent (i);
  37289. if (c->getComponentPropertyInt (tagPropertyName, false, 0) != newTag)
  37290. delete c;
  37291. }
  37292. }
  37293. else
  37294. {
  37295. columnsWithComponents.clear();
  37296. deleteAllChildren();
  37297. }
  37298. }
  37299. void resized()
  37300. {
  37301. for (int i = getNumChildComponents(); --i >= 0;)
  37302. {
  37303. Component* const c = getChildComponent (i);
  37304. const int columnId = c->getComponentPropertyInt (tableColumnPropertyTag, false, 0);
  37305. if (columnId != 0)
  37306. {
  37307. const Rectangle columnRect (owner.getHeader()->getColumnPosition (owner.getHeader()->getIndexOfColumnId (columnId, true)));
  37308. c->setBounds (columnRect.getX(), 0, columnRect.getWidth(), getHeight());
  37309. }
  37310. }
  37311. }
  37312. void mouseDown (const MouseEvent& e)
  37313. {
  37314. isDragging = false;
  37315. selectRowOnMouseUp = false;
  37316. if (isEnabled())
  37317. {
  37318. if (! isSelected)
  37319. {
  37320. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  37321. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  37322. if (columnId != 0 && owner.getModel() != 0)
  37323. owner.getModel()->cellClicked (row, columnId, e);
  37324. }
  37325. else
  37326. {
  37327. selectRowOnMouseUp = true;
  37328. }
  37329. }
  37330. }
  37331. void mouseDrag (const MouseEvent& e)
  37332. {
  37333. if (isEnabled() && owner.getModel() != 0 && ! (e.mouseWasClicked() || isDragging))
  37334. {
  37335. const SparseSet <int> selectedRows (owner.getSelectedRows());
  37336. if (selectedRows.size() > 0)
  37337. {
  37338. const String dragDescription (owner.getModel()->getDragSourceDescription (selectedRows));
  37339. if (dragDescription.isNotEmpty())
  37340. {
  37341. isDragging = true;
  37342. DragAndDropContainer* const dragContainer
  37343. = DragAndDropContainer::findParentDragContainerFor (this);
  37344. if (dragContainer != 0)
  37345. {
  37346. Image* dragImage = owner.createSnapshotOfSelectedRows();
  37347. dragImage->multiplyAllAlphas (0.6f);
  37348. dragContainer->startDragging (dragDescription, &owner, dragImage, true);
  37349. }
  37350. else
  37351. {
  37352. // to be able to do a drag-and-drop operation, the listbox needs to
  37353. // be inside a component which is also a DragAndDropContainer.
  37354. jassertfalse
  37355. }
  37356. }
  37357. }
  37358. }
  37359. }
  37360. void mouseUp (const MouseEvent& e)
  37361. {
  37362. if (selectRowOnMouseUp && e.mouseWasClicked() && isEnabled())
  37363. {
  37364. owner.selectRowsBasedOnModifierKeys (row, e.mods);
  37365. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  37366. if (columnId != 0 && owner.getModel() != 0)
  37367. owner.getModel()->cellClicked (row, columnId, e);
  37368. }
  37369. }
  37370. void mouseDoubleClick (const MouseEvent& e)
  37371. {
  37372. const int columnId = owner.getHeader()->getColumnIdAtX (e.x);
  37373. if (columnId != 0 && owner.getModel() != 0)
  37374. owner.getModel()->cellDoubleClicked (row, columnId, e);
  37375. }
  37376. juce_UseDebuggingNewOperator
  37377. private:
  37378. TableListBox& owner;
  37379. int row;
  37380. bool isSelected, isDragging, selectRowOnMouseUp;
  37381. BitArray columnsWithComponents;
  37382. Component* findChildComponentForColumn (const int columnId) const
  37383. {
  37384. for (int i = getNumChildComponents(); --i >= 0;)
  37385. {
  37386. Component* const c = getChildComponent (i);
  37387. if (c->getComponentPropertyInt (tableColumnPropertyTag, false, 0) == columnId)
  37388. return c;
  37389. }
  37390. return 0;
  37391. }
  37392. TableListRowComp (const TableListRowComp&);
  37393. const TableListRowComp& operator= (const TableListRowComp&);
  37394. };
  37395. class TableListBoxHeader : public TableHeaderComponent
  37396. {
  37397. public:
  37398. TableListBoxHeader (TableListBox& owner_)
  37399. : owner (owner_)
  37400. {
  37401. }
  37402. ~TableListBoxHeader()
  37403. {
  37404. }
  37405. void addMenuItems (PopupMenu& menu, const int columnIdClicked)
  37406. {
  37407. if (owner.isAutoSizeMenuOptionShown())
  37408. {
  37409. menu.addItem (0xf836743, TRANS("Auto-size this column"), columnIdClicked != 0);
  37410. menu.addItem (0xf836744, TRANS("Auto-size all columns"), owner.getHeader()->getNumColumns (true) > 0);
  37411. menu.addSeparator();
  37412. }
  37413. TableHeaderComponent::addMenuItems (menu, columnIdClicked);
  37414. }
  37415. void reactToMenuItem (const int menuReturnId, const int columnIdClicked)
  37416. {
  37417. if (menuReturnId == 0xf836743)
  37418. {
  37419. owner.autoSizeColumn (columnIdClicked);
  37420. }
  37421. else if (menuReturnId == 0xf836744)
  37422. {
  37423. owner.autoSizeAllColumns();
  37424. }
  37425. else
  37426. {
  37427. TableHeaderComponent::reactToMenuItem (menuReturnId, columnIdClicked);
  37428. }
  37429. }
  37430. juce_UseDebuggingNewOperator
  37431. private:
  37432. TableListBox& owner;
  37433. TableListBoxHeader (const TableListBoxHeader&);
  37434. const TableListBoxHeader& operator= (const TableListBoxHeader&);
  37435. };
  37436. TableListBox::TableListBox (const String& name, TableListBoxModel* const model_)
  37437. : ListBox (name, 0),
  37438. model (model_),
  37439. autoSizeOptionsShown (true)
  37440. {
  37441. ListBox::model = this;
  37442. header = new TableListBoxHeader (*this);
  37443. header->setSize (100, 28);
  37444. header->addListener (this);
  37445. setHeaderComponent (header);
  37446. }
  37447. TableListBox::~TableListBox()
  37448. {
  37449. deleteAllChildren();
  37450. }
  37451. void TableListBox::setModel (TableListBoxModel* const newModel)
  37452. {
  37453. if (model != newModel)
  37454. {
  37455. model = newModel;
  37456. updateContent();
  37457. }
  37458. }
  37459. int TableListBox::getHeaderHeight() const throw()
  37460. {
  37461. return header->getHeight();
  37462. }
  37463. void TableListBox::setHeaderHeight (const int newHeight)
  37464. {
  37465. header->setSize (header->getWidth(), newHeight);
  37466. resized();
  37467. }
  37468. void TableListBox::autoSizeColumn (const int columnId)
  37469. {
  37470. const int width = model != 0 ? model->getColumnAutoSizeWidth (columnId) : 0;
  37471. if (width > 0)
  37472. header->setColumnWidth (columnId, width);
  37473. }
  37474. void TableListBox::autoSizeAllColumns()
  37475. {
  37476. for (int i = 0; i < header->getNumColumns (true); ++i)
  37477. autoSizeColumn (header->getColumnIdOfIndex (i, true));
  37478. }
  37479. void TableListBox::setAutoSizeMenuOptionShown (const bool shouldBeShown)
  37480. {
  37481. autoSizeOptionsShown = shouldBeShown;
  37482. }
  37483. bool TableListBox::isAutoSizeMenuOptionShown() const throw()
  37484. {
  37485. return autoSizeOptionsShown;
  37486. }
  37487. const Rectangle TableListBox::getCellPosition (const int columnId,
  37488. const int rowNumber,
  37489. const bool relativeToComponentTopLeft) const
  37490. {
  37491. Rectangle headerCell (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  37492. if (relativeToComponentTopLeft)
  37493. headerCell.translate (header->getX(), 0);
  37494. const Rectangle row (getRowPosition (rowNumber, relativeToComponentTopLeft));
  37495. return Rectangle (headerCell.getX(), row.getY(),
  37496. headerCell.getWidth(), row.getHeight());
  37497. }
  37498. void TableListBox::scrollToEnsureColumnIsOnscreen (const int columnId)
  37499. {
  37500. ScrollBar* const scrollbar = getHorizontalScrollBar();
  37501. if (scrollbar != 0)
  37502. {
  37503. const Rectangle pos (header->getColumnPosition (header->getIndexOfColumnId (columnId, true)));
  37504. double x = scrollbar->getCurrentRangeStart();
  37505. const double w = scrollbar->getCurrentRangeSize();
  37506. if (pos.getX() < x)
  37507. x = pos.getX();
  37508. else if (pos.getRight() > x + w)
  37509. x += jmax (0.0, pos.getRight() - (x + w));
  37510. scrollbar->setCurrentRangeStart (x);
  37511. }
  37512. }
  37513. int TableListBox::getNumRows()
  37514. {
  37515. return model != 0 ? model->getNumRows() : 0;
  37516. }
  37517. void TableListBox::paintListBoxItem (int, Graphics&, int, int, bool)
  37518. {
  37519. }
  37520. Component* TableListBox::refreshComponentForRow (int rowNumber, bool isRowSelected, Component* existingComponentToUpdate)
  37521. {
  37522. if (existingComponentToUpdate == 0)
  37523. existingComponentToUpdate = new TableListRowComp (*this);
  37524. ((TableListRowComp*) existingComponentToUpdate)->update (rowNumber, isRowSelected);
  37525. return existingComponentToUpdate;
  37526. }
  37527. void TableListBox::selectedRowsChanged (int row)
  37528. {
  37529. if (model != 0)
  37530. model->selectedRowsChanged (row);
  37531. }
  37532. void TableListBox::deleteKeyPressed (int row)
  37533. {
  37534. if (model != 0)
  37535. model->deleteKeyPressed (row);
  37536. }
  37537. void TableListBox::returnKeyPressed (int row)
  37538. {
  37539. if (model != 0)
  37540. model->returnKeyPressed (row);
  37541. }
  37542. void TableListBox::backgroundClicked()
  37543. {
  37544. if (model != 0)
  37545. model->backgroundClicked();
  37546. }
  37547. void TableListBox::listWasScrolled()
  37548. {
  37549. if (model != 0)
  37550. model->listWasScrolled();
  37551. }
  37552. void TableListBox::tableColumnsChanged (TableHeaderComponent*)
  37553. {
  37554. setMinimumContentWidth (header->getTotalWidth());
  37555. repaint();
  37556. updateColumnComponents();
  37557. }
  37558. void TableListBox::tableColumnsResized (TableHeaderComponent*)
  37559. {
  37560. setMinimumContentWidth (header->getTotalWidth());
  37561. repaint();
  37562. updateColumnComponents();
  37563. }
  37564. void TableListBox::tableSortOrderChanged (TableHeaderComponent*)
  37565. {
  37566. if (model != 0)
  37567. model->sortOrderChanged (header->getSortColumnId(),
  37568. header->isSortedForwards());
  37569. }
  37570. void TableListBox::tableColumnDraggingChanged (TableHeaderComponent*, int columnIdNowBeingDragged_)
  37571. {
  37572. columnIdNowBeingDragged = columnIdNowBeingDragged_;
  37573. repaint();
  37574. }
  37575. void TableListBox::resized()
  37576. {
  37577. ListBox::resized();
  37578. header->resizeAllColumnsToFit (getVisibleContentWidth());
  37579. setMinimumContentWidth (header->getTotalWidth());
  37580. }
  37581. void TableListBox::updateColumnComponents() const
  37582. {
  37583. const int firstRow = getRowContainingPosition (0, 0);
  37584. for (int i = firstRow + getNumRowsOnScreen() + 2; --i >= firstRow;)
  37585. {
  37586. TableListRowComp* const rowComp = dynamic_cast <TableListRowComp*> (getComponentForRowNumber (i));
  37587. if (rowComp != 0)
  37588. rowComp->resized();
  37589. }
  37590. }
  37591. void TableListBoxModel::cellClicked (int, int, const MouseEvent&)
  37592. {
  37593. }
  37594. void TableListBoxModel::cellDoubleClicked (int, int, const MouseEvent&)
  37595. {
  37596. }
  37597. void TableListBoxModel::backgroundClicked()
  37598. {
  37599. }
  37600. void TableListBoxModel::sortOrderChanged (int, const bool)
  37601. {
  37602. }
  37603. int TableListBoxModel::getColumnAutoSizeWidth (int)
  37604. {
  37605. return 0;
  37606. }
  37607. void TableListBoxModel::selectedRowsChanged (int)
  37608. {
  37609. }
  37610. void TableListBoxModel::deleteKeyPressed (int)
  37611. {
  37612. }
  37613. void TableListBoxModel::returnKeyPressed (int)
  37614. {
  37615. }
  37616. void TableListBoxModel::listWasScrolled()
  37617. {
  37618. }
  37619. const String TableListBoxModel::getDragSourceDescription (const SparseSet<int>&)
  37620. {
  37621. return String::empty;
  37622. }
  37623. Component* TableListBoxModel::refreshComponentForCell (int, int, bool, Component* existingComponentToUpdate)
  37624. {
  37625. (void) existingComponentToUpdate;
  37626. jassert (existingComponentToUpdate == 0); // indicates a failure in the code the recycles the components
  37627. return 0;
  37628. }
  37629. END_JUCE_NAMESPACE
  37630. /********* End of inlined file: juce_TableListBox.cpp *********/
  37631. /********* Start of inlined file: juce_TextEditor.cpp *********/
  37632. BEGIN_JUCE_NAMESPACE
  37633. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  37634. // a word or space that can't be broken down any further
  37635. struct TextAtom
  37636. {
  37637. String atomText;
  37638. float width;
  37639. uint16 numChars;
  37640. bool isWhitespace() const throw() { return CharacterFunctions::isWhitespace (atomText[0]); }
  37641. bool isNewLine() const throw() { return atomText[0] == T('\r') || atomText[0] == T('\n'); }
  37642. const String getText (const tchar passwordCharacter) const throw()
  37643. {
  37644. if (passwordCharacter == 0)
  37645. return atomText;
  37646. else
  37647. return String::repeatedString (String::charToString (passwordCharacter),
  37648. atomText.length());
  37649. }
  37650. const String getTrimmedText (const tchar passwordCharacter) const throw()
  37651. {
  37652. if (passwordCharacter == 0)
  37653. return atomText.substring (0, numChars);
  37654. else if (isNewLine())
  37655. return String::empty;
  37656. else
  37657. return String::repeatedString (String::charToString (passwordCharacter), numChars);
  37658. }
  37659. };
  37660. // a run of text with a single font and colour
  37661. class UniformTextSection
  37662. {
  37663. public:
  37664. UniformTextSection (const String& text,
  37665. const Font& font_,
  37666. const Colour& colour_,
  37667. const tchar passwordCharacter) throw()
  37668. : font (font_),
  37669. colour (colour_),
  37670. atoms (64)
  37671. {
  37672. initialiseAtoms (text, passwordCharacter);
  37673. }
  37674. UniformTextSection (const UniformTextSection& other) throw()
  37675. : font (other.font),
  37676. colour (other.colour),
  37677. atoms (64)
  37678. {
  37679. for (int i = 0; i < other.atoms.size(); ++i)
  37680. atoms.add (new TextAtom (*(const TextAtom*) other.atoms.getUnchecked(i)));
  37681. }
  37682. ~UniformTextSection() throw()
  37683. {
  37684. // (no need to delete the atoms, as they're explicitly deleted by the caller)
  37685. }
  37686. void clear() throw()
  37687. {
  37688. for (int i = atoms.size(); --i >= 0;)
  37689. {
  37690. TextAtom* const atom = getAtom(i);
  37691. delete atom;
  37692. }
  37693. atoms.clear();
  37694. }
  37695. int getNumAtoms() const throw()
  37696. {
  37697. return atoms.size();
  37698. }
  37699. TextAtom* getAtom (const int index) const throw()
  37700. {
  37701. return (TextAtom*) atoms.getUnchecked (index);
  37702. }
  37703. void append (const UniformTextSection& other, const tchar passwordCharacter) throw()
  37704. {
  37705. if (other.atoms.size() > 0)
  37706. {
  37707. TextAtom* const lastAtom = (TextAtom*) atoms.getLast();
  37708. int i = 0;
  37709. if (lastAtom != 0)
  37710. {
  37711. if (! CharacterFunctions::isWhitespace (lastAtom->atomText.getLastCharacter()))
  37712. {
  37713. TextAtom* const first = other.getAtom(0);
  37714. if (! CharacterFunctions::isWhitespace (first->atomText[0]))
  37715. {
  37716. lastAtom->atomText += first->atomText;
  37717. lastAtom->numChars = (uint16) (lastAtom->numChars + first->numChars);
  37718. lastAtom->width = font.getStringWidthFloat (lastAtom->getText (passwordCharacter));
  37719. delete first;
  37720. ++i;
  37721. }
  37722. }
  37723. }
  37724. while (i < other.atoms.size())
  37725. {
  37726. atoms.add (other.getAtom(i));
  37727. ++i;
  37728. }
  37729. }
  37730. }
  37731. UniformTextSection* split (const int indexToBreakAt,
  37732. const tchar passwordCharacter) throw()
  37733. {
  37734. UniformTextSection* const section2 = new UniformTextSection (String::empty,
  37735. font, colour,
  37736. passwordCharacter);
  37737. int index = 0;
  37738. for (int i = 0; i < atoms.size(); ++i)
  37739. {
  37740. TextAtom* const atom = getAtom(i);
  37741. const int nextIndex = index + atom->numChars;
  37742. if (index == indexToBreakAt)
  37743. {
  37744. int j;
  37745. for (j = i; j < atoms.size(); ++j)
  37746. section2->atoms.add (getAtom (j));
  37747. for (j = atoms.size(); --j >= i;)
  37748. atoms.remove (j);
  37749. break;
  37750. }
  37751. else if (indexToBreakAt >= index && indexToBreakAt < nextIndex)
  37752. {
  37753. TextAtom* const secondAtom = new TextAtom();
  37754. secondAtom->atomText = atom->atomText.substring (indexToBreakAt - index);
  37755. secondAtom->width = font.getStringWidthFloat (secondAtom->getText (passwordCharacter));
  37756. secondAtom->numChars = (uint16) secondAtom->atomText.length();
  37757. section2->atoms.add (secondAtom);
  37758. atom->atomText = atom->atomText.substring (0, indexToBreakAt - index);
  37759. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  37760. atom->numChars = (uint16) (indexToBreakAt - index);
  37761. int j;
  37762. for (j = i + 1; j < atoms.size(); ++j)
  37763. section2->atoms.add (getAtom (j));
  37764. for (j = atoms.size(); --j > i;)
  37765. atoms.remove (j);
  37766. break;
  37767. }
  37768. index = nextIndex;
  37769. }
  37770. return section2;
  37771. }
  37772. const String getAllText() const throw()
  37773. {
  37774. String s;
  37775. s.preallocateStorage (getTotalLength());
  37776. tchar* endOfString = (tchar*) &(s[0]);
  37777. for (int i = 0; i < atoms.size(); ++i)
  37778. {
  37779. const TextAtom* const atom = getAtom(i);
  37780. memcpy (endOfString, &(atom->atomText[0]), atom->numChars * sizeof (tchar));
  37781. endOfString += atom->numChars;
  37782. }
  37783. *endOfString = 0;
  37784. jassert ((endOfString - (tchar*) &(s[0])) <= getTotalLength());
  37785. return s;
  37786. }
  37787. const String getTextSubstring (const int startCharacter,
  37788. const int endCharacter) const throw()
  37789. {
  37790. int index = 0;
  37791. int totalLen = 0;
  37792. int i;
  37793. for (i = 0; i < atoms.size(); ++i)
  37794. {
  37795. const TextAtom* const atom = getAtom (i);
  37796. const int nextIndex = index + atom->numChars;
  37797. if (startCharacter < nextIndex)
  37798. {
  37799. if (endCharacter <= index)
  37800. break;
  37801. const int start = jmax (0, startCharacter - index);
  37802. const int end = jmin (endCharacter - index, atom->numChars);
  37803. jassert (end >= start);
  37804. totalLen += end - start;
  37805. }
  37806. index = nextIndex;
  37807. }
  37808. String s;
  37809. s.preallocateStorage (totalLen + 1);
  37810. tchar* psz = (tchar*) (const tchar*) s;
  37811. index = 0;
  37812. for (i = 0; i < atoms.size(); ++i)
  37813. {
  37814. const TextAtom* const atom = getAtom (i);
  37815. const int nextIndex = index + atom->numChars;
  37816. if (startCharacter < nextIndex)
  37817. {
  37818. if (endCharacter <= index)
  37819. break;
  37820. const int start = jmax (0, startCharacter - index);
  37821. const int len = jmin (endCharacter - index, atom->numChars) - start;
  37822. memcpy (psz, ((const tchar*) atom->atomText) + start, len * sizeof (tchar));
  37823. psz += len;
  37824. *psz = 0;
  37825. }
  37826. index = nextIndex;
  37827. }
  37828. return s;
  37829. }
  37830. int getTotalLength() const throw()
  37831. {
  37832. int c = 0;
  37833. for (int i = atoms.size(); --i >= 0;)
  37834. c += getAtom(i)->numChars;
  37835. return c;
  37836. }
  37837. void setFont (const Font& newFont,
  37838. const tchar passwordCharacter) throw()
  37839. {
  37840. if (font != newFont)
  37841. {
  37842. font = newFont;
  37843. for (int i = atoms.size(); --i >= 0;)
  37844. {
  37845. TextAtom* const atom = (TextAtom*) atoms.getUnchecked(i);
  37846. atom->width = newFont.getStringWidthFloat (atom->getText (passwordCharacter));
  37847. }
  37848. }
  37849. }
  37850. juce_UseDebuggingNewOperator
  37851. Font font;
  37852. Colour colour;
  37853. private:
  37854. VoidArray atoms;
  37855. void initialiseAtoms (const String& textToParse,
  37856. const tchar passwordCharacter) throw()
  37857. {
  37858. int i = 0;
  37859. const int len = textToParse.length();
  37860. const tchar* const text = (const tchar*) textToParse;
  37861. while (i < len)
  37862. {
  37863. int start = i;
  37864. // create a whitespace atom unless it starts with non-ws
  37865. if (CharacterFunctions::isWhitespace (text[i])
  37866. && text[i] != T('\r')
  37867. && text[i] != T('\n'))
  37868. {
  37869. while (i < len
  37870. && CharacterFunctions::isWhitespace (text[i])
  37871. && text[i] != T('\r')
  37872. && text[i] != T('\n'))
  37873. {
  37874. ++i;
  37875. }
  37876. }
  37877. else
  37878. {
  37879. if (text[i] == T('\r'))
  37880. {
  37881. ++i;
  37882. if ((i < len) && (text[i] == T('\n')))
  37883. {
  37884. ++start;
  37885. ++i;
  37886. }
  37887. }
  37888. else if (text[i] == T('\n'))
  37889. {
  37890. ++i;
  37891. }
  37892. else
  37893. {
  37894. while ((i < len) && ! CharacterFunctions::isWhitespace (text[i]))
  37895. ++i;
  37896. }
  37897. }
  37898. TextAtom* const atom = new TextAtom();
  37899. atom->atomText = String (text + start, i - start);
  37900. atom->width = font.getStringWidthFloat (atom->getText (passwordCharacter));
  37901. atom->numChars = (uint16) (i - start);
  37902. atoms.add (atom);
  37903. }
  37904. }
  37905. const UniformTextSection& operator= (const UniformTextSection& other);
  37906. };
  37907. class TextEditorIterator
  37908. {
  37909. public:
  37910. TextEditorIterator (const VoidArray& sections_,
  37911. const float wordWrapWidth_,
  37912. const tchar passwordCharacter_) throw()
  37913. : indexInText (0),
  37914. lineY (0),
  37915. lineHeight (0),
  37916. maxDescent (0),
  37917. atomX (0),
  37918. atomRight (0),
  37919. atom (0),
  37920. currentSection (0),
  37921. sections (sections_),
  37922. sectionIndex (0),
  37923. atomIndex (0),
  37924. wordWrapWidth (wordWrapWidth_),
  37925. passwordCharacter (passwordCharacter_)
  37926. {
  37927. jassert (wordWrapWidth_ > 0);
  37928. if (sections.size() > 0)
  37929. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  37930. if (currentSection != 0)
  37931. {
  37932. lineHeight = currentSection->font.getHeight();
  37933. maxDescent = currentSection->font.getDescent();
  37934. }
  37935. }
  37936. TextEditorIterator (const TextEditorIterator& other) throw()
  37937. : indexInText (other.indexInText),
  37938. lineY (other.lineY),
  37939. lineHeight (other.lineHeight),
  37940. maxDescent (other.maxDescent),
  37941. atomX (other.atomX),
  37942. atomRight (other.atomRight),
  37943. atom (other.atom),
  37944. currentSection (other.currentSection),
  37945. sections (other.sections),
  37946. sectionIndex (other.sectionIndex),
  37947. atomIndex (other.atomIndex),
  37948. wordWrapWidth (other.wordWrapWidth),
  37949. passwordCharacter (other.passwordCharacter),
  37950. tempAtom (other.tempAtom)
  37951. {
  37952. }
  37953. ~TextEditorIterator() throw()
  37954. {
  37955. }
  37956. bool next() throw()
  37957. {
  37958. if (atom == &tempAtom)
  37959. {
  37960. const int numRemaining = tempAtom.atomText.length() - tempAtom.numChars;
  37961. if (numRemaining > 0)
  37962. {
  37963. tempAtom.atomText = tempAtom.atomText.substring (tempAtom.numChars);
  37964. atomX = 0;
  37965. if (tempAtom.numChars > 0)
  37966. lineY += lineHeight;
  37967. indexInText += tempAtom.numChars;
  37968. GlyphArrangement g;
  37969. g.addLineOfText (currentSection->font, atom->getText (passwordCharacter), 0.0f, 0.0f);
  37970. int split;
  37971. for (split = 0; split < g.getNumGlyphs(); ++split)
  37972. if (SHOULD_WRAP (g.getGlyph (split).getRight(), wordWrapWidth))
  37973. break;
  37974. if (split > 0 && split <= numRemaining)
  37975. {
  37976. tempAtom.numChars = (uint16) split;
  37977. tempAtom.width = g.getGlyph (split - 1).getRight();
  37978. atomRight = atomX + tempAtom.width;
  37979. return true;
  37980. }
  37981. }
  37982. }
  37983. bool forceNewLine = false;
  37984. if (sectionIndex >= sections.size())
  37985. {
  37986. moveToEndOfLastAtom();
  37987. return false;
  37988. }
  37989. else if (atomIndex >= currentSection->getNumAtoms() - 1)
  37990. {
  37991. if (atomIndex >= currentSection->getNumAtoms())
  37992. {
  37993. if (++sectionIndex >= sections.size())
  37994. {
  37995. moveToEndOfLastAtom();
  37996. return false;
  37997. }
  37998. atomIndex = 0;
  37999. currentSection = (const UniformTextSection*) sections.getUnchecked (sectionIndex);
  38000. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  38001. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  38002. }
  38003. else
  38004. {
  38005. const TextAtom* const lastAtom = currentSection->getAtom (atomIndex);
  38006. if (! lastAtom->isWhitespace())
  38007. {
  38008. // handle the case where the last atom in a section is actually part of the same
  38009. // word as the first atom of the next section...
  38010. float right = atomRight + lastAtom->width;
  38011. float lineHeight2 = lineHeight;
  38012. float maxDescent2 = maxDescent;
  38013. for (int section = sectionIndex + 1; section < sections.size(); ++section)
  38014. {
  38015. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked (section);
  38016. if (s->getNumAtoms() == 0)
  38017. break;
  38018. const TextAtom* const nextAtom = s->getAtom (0);
  38019. if (nextAtom->isWhitespace())
  38020. break;
  38021. right += nextAtom->width;
  38022. lineHeight2 = jmax (lineHeight2, s->font.getHeight());
  38023. maxDescent2 = jmax (maxDescent2, s->font.getDescent());
  38024. if (SHOULD_WRAP (right, wordWrapWidth))
  38025. {
  38026. lineHeight = lineHeight2;
  38027. maxDescent = maxDescent2;
  38028. forceNewLine = true;
  38029. break;
  38030. }
  38031. if (s->getNumAtoms() > 1)
  38032. break;
  38033. }
  38034. }
  38035. }
  38036. }
  38037. if (atom != 0)
  38038. {
  38039. atomX = atomRight;
  38040. indexInText += atom->numChars;
  38041. if (atom->isNewLine())
  38042. {
  38043. atomX = 0;
  38044. lineY += lineHeight;
  38045. }
  38046. }
  38047. atom = currentSection->getAtom (atomIndex);
  38048. atomRight = atomX + atom->width;
  38049. ++atomIndex;
  38050. if (SHOULD_WRAP (atomRight, wordWrapWidth) || forceNewLine)
  38051. {
  38052. if (atom->isWhitespace())
  38053. {
  38054. // leave whitespace at the end of a line, but truncate it to avoid scrolling
  38055. atomRight = jmin (atomRight, wordWrapWidth);
  38056. }
  38057. else
  38058. {
  38059. return wrapCurrentAtom();
  38060. }
  38061. }
  38062. return true;
  38063. }
  38064. bool wrapCurrentAtom() throw()
  38065. {
  38066. atomRight = atom->width;
  38067. if (SHOULD_WRAP (atomRight, wordWrapWidth)) // atom too big to fit on a line, so break it up..
  38068. {
  38069. tempAtom = *atom;
  38070. tempAtom.width = 0;
  38071. tempAtom.numChars = 0;
  38072. atom = &tempAtom;
  38073. if (atomX > 0)
  38074. {
  38075. atomX = 0;
  38076. lineY += lineHeight;
  38077. }
  38078. return next();
  38079. }
  38080. atomX = 0;
  38081. lineY += lineHeight;
  38082. return true;
  38083. }
  38084. void draw (Graphics& g, const UniformTextSection*& lastSection) const throw()
  38085. {
  38086. if (passwordCharacter != 0 || ! atom->isWhitespace())
  38087. {
  38088. if (lastSection != currentSection)
  38089. {
  38090. lastSection = currentSection;
  38091. g.setColour (currentSection->colour);
  38092. g.setFont (currentSection->font);
  38093. }
  38094. jassert (atom->getTrimmedText (passwordCharacter).isNotEmpty());
  38095. GlyphArrangement ga;
  38096. ga.addLineOfText (currentSection->font,
  38097. atom->getTrimmedText (passwordCharacter),
  38098. atomX,
  38099. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  38100. ga.draw (g);
  38101. }
  38102. }
  38103. void drawSelection (Graphics& g,
  38104. const int selectionStart,
  38105. const int selectionEnd) const throw()
  38106. {
  38107. const int startX = roundFloatToInt (indexToX (selectionStart));
  38108. const int endX = roundFloatToInt (indexToX (selectionEnd));
  38109. const int y = roundFloatToInt (lineY);
  38110. const int nextY = roundFloatToInt (lineY + lineHeight);
  38111. g.fillRect (startX, y, endX - startX, nextY - y);
  38112. }
  38113. void drawSelectedText (Graphics& g,
  38114. const int selectionStart,
  38115. const int selectionEnd,
  38116. const Colour& selectedTextColour) const throw()
  38117. {
  38118. if (passwordCharacter != 0 || ! atom->isWhitespace())
  38119. {
  38120. GlyphArrangement ga;
  38121. ga.addLineOfText (currentSection->font,
  38122. atom->getTrimmedText (passwordCharacter),
  38123. atomX,
  38124. (float) roundFloatToInt (lineY + lineHeight - maxDescent));
  38125. if (selectionEnd < indexInText + atom->numChars)
  38126. {
  38127. GlyphArrangement ga2 (ga);
  38128. ga2.removeRangeOfGlyphs (0, selectionEnd - indexInText);
  38129. ga.removeRangeOfGlyphs (selectionEnd - indexInText, -1);
  38130. g.setColour (currentSection->colour);
  38131. ga2.draw (g);
  38132. }
  38133. if (selectionStart > indexInText)
  38134. {
  38135. GlyphArrangement ga2 (ga);
  38136. ga2.removeRangeOfGlyphs (selectionStart - indexInText, -1);
  38137. ga.removeRangeOfGlyphs (0, selectionStart - indexInText);
  38138. g.setColour (currentSection->colour);
  38139. ga2.draw (g);
  38140. }
  38141. g.setColour (selectedTextColour);
  38142. ga.draw (g);
  38143. }
  38144. }
  38145. float indexToX (const int indexToFind) const throw()
  38146. {
  38147. if (indexToFind <= indexInText)
  38148. return atomX;
  38149. if (indexToFind >= indexInText + atom->numChars)
  38150. return atomRight;
  38151. GlyphArrangement g;
  38152. g.addLineOfText (currentSection->font,
  38153. atom->getText (passwordCharacter),
  38154. atomX, 0.0f);
  38155. return jmin (atomRight, g.getGlyph (indexToFind - indexInText).getLeft());
  38156. }
  38157. int xToIndex (const float xToFind) const throw()
  38158. {
  38159. if (xToFind <= atomX || atom->isNewLine())
  38160. return indexInText;
  38161. if (xToFind >= atomRight)
  38162. return indexInText + atom->numChars;
  38163. GlyphArrangement g;
  38164. g.addLineOfText (currentSection->font,
  38165. atom->getText (passwordCharacter),
  38166. atomX, 0.0f);
  38167. int j;
  38168. for (j = 0; j < atom->numChars; ++j)
  38169. if ((g.getGlyph(j).getLeft() + g.getGlyph(j).getRight()) / 2 > xToFind)
  38170. break;
  38171. return indexInText + j;
  38172. }
  38173. void updateLineHeight() throw()
  38174. {
  38175. float x = atomRight;
  38176. int tempSectionIndex = sectionIndex;
  38177. int tempAtomIndex = atomIndex;
  38178. const UniformTextSection* currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  38179. while (! SHOULD_WRAP (x, wordWrapWidth))
  38180. {
  38181. if (tempSectionIndex >= sections.size())
  38182. break;
  38183. bool checkSize = false;
  38184. if (tempAtomIndex >= currentSection->getNumAtoms())
  38185. {
  38186. if (++tempSectionIndex >= sections.size())
  38187. break;
  38188. tempAtomIndex = 0;
  38189. currentSection = (const UniformTextSection*) sections.getUnchecked (tempSectionIndex);
  38190. checkSize = true;
  38191. }
  38192. const TextAtom* const atom = currentSection->getAtom (tempAtomIndex);
  38193. if (atom == 0)
  38194. break;
  38195. x += atom->width;
  38196. if (SHOULD_WRAP (x, wordWrapWidth) || atom->isNewLine())
  38197. break;
  38198. if (checkSize)
  38199. {
  38200. lineHeight = jmax (lineHeight, currentSection->font.getHeight());
  38201. maxDescent = jmax (maxDescent, currentSection->font.getDescent());
  38202. }
  38203. ++tempAtomIndex;
  38204. }
  38205. }
  38206. bool getCharPosition (const int index, float& cx, float& cy, float& lineHeight_) throw()
  38207. {
  38208. while (next())
  38209. {
  38210. if (indexInText + atom->numChars >= index)
  38211. {
  38212. updateLineHeight();
  38213. if (indexInText + atom->numChars > index)
  38214. {
  38215. cx = indexToX (index);
  38216. cy = lineY;
  38217. lineHeight_ = lineHeight;
  38218. return true;
  38219. }
  38220. }
  38221. }
  38222. cx = atomX;
  38223. cy = lineY;
  38224. lineHeight_ = lineHeight;
  38225. return false;
  38226. }
  38227. juce_UseDebuggingNewOperator
  38228. int indexInText;
  38229. float lineY, lineHeight, maxDescent;
  38230. float atomX, atomRight;
  38231. const TextAtom* atom;
  38232. const UniformTextSection* currentSection;
  38233. private:
  38234. const VoidArray& sections;
  38235. int sectionIndex, atomIndex;
  38236. const float wordWrapWidth;
  38237. const tchar passwordCharacter;
  38238. TextAtom tempAtom;
  38239. const TextEditorIterator& operator= (const TextEditorIterator&);
  38240. void moveToEndOfLastAtom() throw()
  38241. {
  38242. if (atom != 0)
  38243. {
  38244. atomX = atomRight;
  38245. if (atom->isNewLine())
  38246. {
  38247. atomX = 0.0f;
  38248. lineY += lineHeight;
  38249. }
  38250. }
  38251. }
  38252. };
  38253. class TextEditorInsertAction : public UndoableAction
  38254. {
  38255. TextEditor& owner;
  38256. const String text;
  38257. const int insertIndex, oldCaretPos, newCaretPos;
  38258. const Font font;
  38259. const Colour colour;
  38260. TextEditorInsertAction (const TextEditorInsertAction&);
  38261. const TextEditorInsertAction& operator= (const TextEditorInsertAction&);
  38262. public:
  38263. TextEditorInsertAction (TextEditor& owner_,
  38264. const String& text_,
  38265. const int insertIndex_,
  38266. const Font& font_,
  38267. const Colour& colour_,
  38268. const int oldCaretPos_,
  38269. const int newCaretPos_) throw()
  38270. : owner (owner_),
  38271. text (text_),
  38272. insertIndex (insertIndex_),
  38273. oldCaretPos (oldCaretPos_),
  38274. newCaretPos (newCaretPos_),
  38275. font (font_),
  38276. colour (colour_)
  38277. {
  38278. }
  38279. ~TextEditorInsertAction()
  38280. {
  38281. }
  38282. bool perform()
  38283. {
  38284. owner.insert (text, insertIndex, font, colour, 0, newCaretPos);
  38285. return true;
  38286. }
  38287. bool undo()
  38288. {
  38289. owner.remove (insertIndex, insertIndex + text.length(), 0, oldCaretPos);
  38290. return true;
  38291. }
  38292. int getSizeInUnits()
  38293. {
  38294. return text.length() + 16;
  38295. }
  38296. };
  38297. class TextEditorRemoveAction : public UndoableAction
  38298. {
  38299. TextEditor& owner;
  38300. const int startIndex, endIndex, oldCaretPos, newCaretPos;
  38301. VoidArray removedSections;
  38302. TextEditorRemoveAction (const TextEditorRemoveAction&);
  38303. const TextEditorRemoveAction& operator= (const TextEditorRemoveAction&);
  38304. public:
  38305. TextEditorRemoveAction (TextEditor& owner_,
  38306. const int startIndex_,
  38307. const int endIndex_,
  38308. const int oldCaretPos_,
  38309. const int newCaretPos_,
  38310. const VoidArray& removedSections_) throw()
  38311. : owner (owner_),
  38312. startIndex (startIndex_),
  38313. endIndex (endIndex_),
  38314. oldCaretPos (oldCaretPos_),
  38315. newCaretPos (newCaretPos_),
  38316. removedSections (removedSections_)
  38317. {
  38318. }
  38319. ~TextEditorRemoveAction()
  38320. {
  38321. for (int i = removedSections.size(); --i >= 0;)
  38322. {
  38323. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  38324. section->clear();
  38325. delete section;
  38326. }
  38327. }
  38328. bool perform()
  38329. {
  38330. owner.remove (startIndex, endIndex, 0, newCaretPos);
  38331. return true;
  38332. }
  38333. bool undo()
  38334. {
  38335. owner.reinsert (startIndex, removedSections);
  38336. owner.moveCursorTo (oldCaretPos, false);
  38337. return true;
  38338. }
  38339. int getSizeInUnits()
  38340. {
  38341. int n = 0;
  38342. for (int i = removedSections.size(); --i >= 0;)
  38343. {
  38344. UniformTextSection* const section = (UniformTextSection*) removedSections.getUnchecked (i);
  38345. n += section->getTotalLength();
  38346. }
  38347. return n + 16;
  38348. }
  38349. };
  38350. class TextHolderComponent : public Component,
  38351. public Timer
  38352. {
  38353. TextEditor* const owner;
  38354. TextHolderComponent (const TextHolderComponent&);
  38355. const TextHolderComponent& operator= (const TextHolderComponent&);
  38356. public:
  38357. TextHolderComponent (TextEditor* const owner_)
  38358. : owner (owner_)
  38359. {
  38360. setWantsKeyboardFocus (false);
  38361. setInterceptsMouseClicks (false, true);
  38362. }
  38363. ~TextHolderComponent()
  38364. {
  38365. }
  38366. void paint (Graphics& g)
  38367. {
  38368. owner->drawContent (g);
  38369. }
  38370. void timerCallback()
  38371. {
  38372. owner->timerCallbackInt();
  38373. }
  38374. const MouseCursor getMouseCursor()
  38375. {
  38376. return owner->getMouseCursor();
  38377. }
  38378. };
  38379. class TextEditorViewport : public Viewport
  38380. {
  38381. TextEditor* const owner;
  38382. float lastWordWrapWidth;
  38383. TextEditorViewport (const TextEditorViewport&);
  38384. const TextEditorViewport& operator= (const TextEditorViewport&);
  38385. public:
  38386. TextEditorViewport (TextEditor* const owner_)
  38387. : owner (owner_),
  38388. lastWordWrapWidth (0)
  38389. {
  38390. }
  38391. ~TextEditorViewport()
  38392. {
  38393. }
  38394. void visibleAreaChanged (int, int, int, int)
  38395. {
  38396. const float wordWrapWidth = owner->getWordWrapWidth();
  38397. if (wordWrapWidth != lastWordWrapWidth)
  38398. {
  38399. lastWordWrapWidth = wordWrapWidth;
  38400. owner->updateTextHolderSize();
  38401. }
  38402. }
  38403. };
  38404. const int flashSpeedIntervalMs = 380;
  38405. const int textChangeMessageId = 0x10003001;
  38406. const int returnKeyMessageId = 0x10003002;
  38407. const int escapeKeyMessageId = 0x10003003;
  38408. const int focusLossMessageId = 0x10003004;
  38409. TextEditor::TextEditor (const String& name,
  38410. const tchar passwordCharacter_)
  38411. : Component (name),
  38412. borderSize (1, 1, 1, 3),
  38413. readOnly (false),
  38414. multiline (false),
  38415. wordWrap (false),
  38416. returnKeyStartsNewLine (false),
  38417. caretVisible (true),
  38418. popupMenuEnabled (true),
  38419. selectAllTextWhenFocused (false),
  38420. scrollbarVisible (true),
  38421. wasFocused (false),
  38422. caretFlashState (true),
  38423. keepCursorOnScreen (true),
  38424. tabKeyUsed (false),
  38425. menuActive (false),
  38426. cursorX (0),
  38427. cursorY (0),
  38428. cursorHeight (0),
  38429. maxTextLength (0),
  38430. selectionStart (0),
  38431. selectionEnd (0),
  38432. leftIndent (4),
  38433. topIndent (4),
  38434. lastTransactionTime (0),
  38435. currentFont (14.0f),
  38436. totalNumChars (0),
  38437. caretPosition (0),
  38438. sections (8),
  38439. passwordCharacter (passwordCharacter_),
  38440. dragType (notDragging),
  38441. listeners (2)
  38442. {
  38443. setOpaque (true);
  38444. addAndMakeVisible (viewport = new TextEditorViewport (this));
  38445. viewport->setViewedComponent (textHolder = new TextHolderComponent (this));
  38446. viewport->setWantsKeyboardFocus (false);
  38447. viewport->setScrollBarsShown (false, false);
  38448. setMouseCursor (MouseCursor::IBeamCursor);
  38449. setWantsKeyboardFocus (true);
  38450. }
  38451. TextEditor::~TextEditor()
  38452. {
  38453. clearInternal (0);
  38454. delete viewport;
  38455. }
  38456. void TextEditor::newTransaction() throw()
  38457. {
  38458. lastTransactionTime = Time::getApproximateMillisecondCounter();
  38459. undoManager.beginNewTransaction();
  38460. }
  38461. void TextEditor::doUndoRedo (const bool isRedo)
  38462. {
  38463. if (! isReadOnly())
  38464. {
  38465. if ((isRedo) ? undoManager.redo()
  38466. : undoManager.undo())
  38467. {
  38468. scrollToMakeSureCursorIsVisible();
  38469. repaint();
  38470. textChanged();
  38471. }
  38472. }
  38473. }
  38474. void TextEditor::setMultiLine (const bool shouldBeMultiLine,
  38475. const bool shouldWordWrap)
  38476. {
  38477. multiline = shouldBeMultiLine;
  38478. wordWrap = shouldWordWrap && shouldBeMultiLine;
  38479. setScrollbarsShown (scrollbarVisible);
  38480. viewport->setViewPosition (0, 0);
  38481. resized();
  38482. scrollToMakeSureCursorIsVisible();
  38483. }
  38484. bool TextEditor::isMultiLine() const throw()
  38485. {
  38486. return multiline;
  38487. }
  38488. void TextEditor::setScrollbarsShown (bool enabled) throw()
  38489. {
  38490. scrollbarVisible = enabled;
  38491. enabled = enabled && isMultiLine();
  38492. viewport->setScrollBarsShown (enabled, enabled);
  38493. }
  38494. void TextEditor::setReadOnly (const bool shouldBeReadOnly)
  38495. {
  38496. readOnly = shouldBeReadOnly;
  38497. enablementChanged();
  38498. }
  38499. bool TextEditor::isReadOnly() const throw()
  38500. {
  38501. return readOnly || ! isEnabled();
  38502. }
  38503. void TextEditor::setReturnKeyStartsNewLine (const bool shouldStartNewLine)
  38504. {
  38505. returnKeyStartsNewLine = shouldStartNewLine;
  38506. }
  38507. void TextEditor::setTabKeyUsedAsCharacter (const bool shouldTabKeyBeUsed) throw()
  38508. {
  38509. tabKeyUsed = shouldTabKeyBeUsed;
  38510. }
  38511. void TextEditor::setPopupMenuEnabled (const bool b) throw()
  38512. {
  38513. popupMenuEnabled = b;
  38514. }
  38515. void TextEditor::setSelectAllWhenFocused (const bool b) throw()
  38516. {
  38517. selectAllTextWhenFocused = b;
  38518. }
  38519. const Font TextEditor::getFont() const throw()
  38520. {
  38521. return currentFont;
  38522. }
  38523. void TextEditor::setFont (const Font& newFont) throw()
  38524. {
  38525. currentFont = newFont;
  38526. scrollToMakeSureCursorIsVisible();
  38527. }
  38528. void TextEditor::applyFontToAllText (const Font& newFont)
  38529. {
  38530. currentFont = newFont;
  38531. const Colour overallColour (findColour (textColourId));
  38532. for (int i = sections.size(); --i >= 0;)
  38533. {
  38534. UniformTextSection* const uts = (UniformTextSection*) sections.getUnchecked(i);
  38535. uts->setFont (newFont, passwordCharacter);
  38536. uts->colour = overallColour;
  38537. }
  38538. coalesceSimilarSections();
  38539. updateTextHolderSize();
  38540. scrollToMakeSureCursorIsVisible();
  38541. repaint();
  38542. }
  38543. void TextEditor::colourChanged()
  38544. {
  38545. setOpaque (findColour (backgroundColourId).isOpaque());
  38546. repaint();
  38547. }
  38548. void TextEditor::setCaretVisible (const bool shouldCaretBeVisible) throw()
  38549. {
  38550. caretVisible = shouldCaretBeVisible;
  38551. if (shouldCaretBeVisible)
  38552. textHolder->startTimer (flashSpeedIntervalMs);
  38553. setMouseCursor (shouldCaretBeVisible ? MouseCursor::IBeamCursor
  38554. : MouseCursor::NormalCursor);
  38555. }
  38556. void TextEditor::setInputRestrictions (const int maxLen,
  38557. const String& chars) throw()
  38558. {
  38559. maxTextLength = jmax (0, maxLen);
  38560. allowedCharacters = chars;
  38561. }
  38562. void TextEditor::setTextToShowWhenEmpty (const String& text, const Colour& colourToUse) throw()
  38563. {
  38564. textToShowWhenEmpty = text;
  38565. colourForTextWhenEmpty = colourToUse;
  38566. }
  38567. void TextEditor::setPasswordCharacter (const tchar newPasswordCharacter) throw()
  38568. {
  38569. if (passwordCharacter != newPasswordCharacter)
  38570. {
  38571. passwordCharacter = newPasswordCharacter;
  38572. resized();
  38573. repaint();
  38574. }
  38575. }
  38576. void TextEditor::setScrollBarThickness (const int newThicknessPixels)
  38577. {
  38578. viewport->setScrollBarThickness (newThicknessPixels);
  38579. }
  38580. void TextEditor::setScrollBarButtonVisibility (const bool buttonsVisible)
  38581. {
  38582. viewport->setScrollBarButtonVisibility (buttonsVisible);
  38583. }
  38584. void TextEditor::clear()
  38585. {
  38586. clearInternal (0);
  38587. updateTextHolderSize();
  38588. undoManager.clearUndoHistory();
  38589. }
  38590. void TextEditor::setText (const String& newText,
  38591. const bool sendTextChangeMessage)
  38592. {
  38593. const int newLength = newText.length();
  38594. if (newLength != getTotalNumChars() || getText() != newText)
  38595. {
  38596. const int oldCursorPos = caretPosition;
  38597. const bool cursorWasAtEnd = oldCursorPos >= getTotalNumChars();
  38598. clearInternal (0);
  38599. insert (newText, 0, currentFont, findColour (textColourId), 0, caretPosition);
  38600. // if you're adding text with line-feeds to a single-line text editor, it
  38601. // ain't gonna look right!
  38602. jassert (multiline || ! newText.containsAnyOf (T("\r\n")));
  38603. if (cursorWasAtEnd && ! isMultiLine())
  38604. moveCursorTo (getTotalNumChars(), false);
  38605. else
  38606. moveCursorTo (oldCursorPos, false);
  38607. if (sendTextChangeMessage)
  38608. textChanged();
  38609. repaint();
  38610. }
  38611. updateTextHolderSize();
  38612. scrollToMakeSureCursorIsVisible();
  38613. undoManager.clearUndoHistory();
  38614. }
  38615. void TextEditor::textChanged() throw()
  38616. {
  38617. updateTextHolderSize();
  38618. postCommandMessage (textChangeMessageId);
  38619. }
  38620. void TextEditor::returnPressed()
  38621. {
  38622. postCommandMessage (returnKeyMessageId);
  38623. }
  38624. void TextEditor::escapePressed()
  38625. {
  38626. postCommandMessage (escapeKeyMessageId);
  38627. }
  38628. void TextEditor::addListener (TextEditorListener* const newListener) throw()
  38629. {
  38630. jassert (newListener != 0)
  38631. if (newListener != 0)
  38632. listeners.add (newListener);
  38633. }
  38634. void TextEditor::removeListener (TextEditorListener* const listenerToRemove) throw()
  38635. {
  38636. listeners.removeValue (listenerToRemove);
  38637. }
  38638. void TextEditor::timerCallbackInt()
  38639. {
  38640. const bool newState = (! caretFlashState) && ! isCurrentlyBlockedByAnotherModalComponent();
  38641. if (caretFlashState != newState)
  38642. {
  38643. caretFlashState = newState;
  38644. if (caretFlashState)
  38645. wasFocused = true;
  38646. if (caretVisible
  38647. && hasKeyboardFocus (false)
  38648. && ! isReadOnly())
  38649. {
  38650. repaintCaret();
  38651. }
  38652. }
  38653. const unsigned int now = Time::getApproximateMillisecondCounter();
  38654. if (now > lastTransactionTime + 200)
  38655. newTransaction();
  38656. }
  38657. void TextEditor::repaintCaret()
  38658. {
  38659. if (! findColour (caretColourId).isTransparent())
  38660. repaint (borderSize.getLeft() + textHolder->getX() + leftIndent + roundFloatToInt (cursorX) - 1,
  38661. borderSize.getTop() + textHolder->getY() + topIndent + roundFloatToInt (cursorY) - 1,
  38662. 4,
  38663. roundFloatToInt (cursorHeight) + 2);
  38664. }
  38665. void TextEditor::repaintText (int textStartIndex, int textEndIndex)
  38666. {
  38667. if (textStartIndex > textEndIndex && textEndIndex > 0)
  38668. swapVariables (textStartIndex, textEndIndex);
  38669. float x = 0, y = 0, lh = currentFont.getHeight();
  38670. const float wordWrapWidth = getWordWrapWidth();
  38671. if (wordWrapWidth > 0)
  38672. {
  38673. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  38674. i.getCharPosition (textStartIndex, x, y, lh);
  38675. const int y1 = (int) y;
  38676. int y2;
  38677. if (textEndIndex >= 0)
  38678. {
  38679. i.getCharPosition (textEndIndex, x, y, lh);
  38680. y2 = (int) (y + lh * 2.0f);
  38681. }
  38682. else
  38683. {
  38684. y2 = textHolder->getHeight();
  38685. }
  38686. textHolder->repaint (0, y1, textHolder->getWidth(), y2 - y1);
  38687. }
  38688. }
  38689. void TextEditor::moveCaret (int newCaretPos) throw()
  38690. {
  38691. if (newCaretPos < 0)
  38692. newCaretPos = 0;
  38693. else if (newCaretPos > getTotalNumChars())
  38694. newCaretPos = getTotalNumChars();
  38695. if (newCaretPos != getCaretPosition())
  38696. {
  38697. repaintCaret();
  38698. caretFlashState = true;
  38699. caretPosition = newCaretPos;
  38700. textHolder->startTimer (flashSpeedIntervalMs);
  38701. scrollToMakeSureCursorIsVisible();
  38702. repaintCaret();
  38703. }
  38704. }
  38705. void TextEditor::setCaretPosition (const int newIndex) throw()
  38706. {
  38707. moveCursorTo (newIndex, false);
  38708. }
  38709. int TextEditor::getCaretPosition() const throw()
  38710. {
  38711. return caretPosition;
  38712. }
  38713. void TextEditor::scrollEditorToPositionCaret (const int desiredCaretX,
  38714. const int desiredCaretY) throw()
  38715. {
  38716. updateCaretPosition();
  38717. int vx = roundFloatToInt (cursorX) - desiredCaretX;
  38718. int vy = roundFloatToInt (cursorY) - desiredCaretY;
  38719. if (desiredCaretX < jmax (1, proportionOfWidth (0.05f)))
  38720. {
  38721. vx += desiredCaretX - proportionOfWidth (0.2f);
  38722. }
  38723. else if (desiredCaretX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  38724. {
  38725. vx += desiredCaretX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  38726. }
  38727. vx = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), vx);
  38728. if (! isMultiLine())
  38729. {
  38730. vy = viewport->getViewPositionY();
  38731. }
  38732. else
  38733. {
  38734. vy = jlimit (0, jmax (0, textHolder->getHeight() - viewport->getMaximumVisibleHeight()), vy);
  38735. const int curH = roundFloatToInt (cursorHeight);
  38736. if (desiredCaretY < 0)
  38737. {
  38738. vy = jmax (0, desiredCaretY + vy);
  38739. }
  38740. else if (desiredCaretY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  38741. {
  38742. vy += desiredCaretY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  38743. }
  38744. }
  38745. viewport->setViewPosition (vx, vy);
  38746. }
  38747. const Rectangle TextEditor::getCaretRectangle() throw()
  38748. {
  38749. updateCaretPosition();
  38750. return Rectangle (roundFloatToInt (cursorX) - viewport->getX(),
  38751. roundFloatToInt (cursorY) - viewport->getY(),
  38752. 1, roundFloatToInt (cursorHeight));
  38753. }
  38754. float TextEditor::getWordWrapWidth() const throw()
  38755. {
  38756. return (wordWrap) ? (float) (viewport->getMaximumVisibleWidth() - leftIndent - leftIndent / 2)
  38757. : 1.0e10f;
  38758. }
  38759. void TextEditor::updateTextHolderSize() throw()
  38760. {
  38761. const float wordWrapWidth = getWordWrapWidth();
  38762. if (wordWrapWidth > 0)
  38763. {
  38764. float maxWidth = 0.0f;
  38765. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  38766. while (i.next())
  38767. maxWidth = jmax (maxWidth, i.atomRight);
  38768. const int w = leftIndent + roundFloatToInt (maxWidth);
  38769. const int h = topIndent + roundFloatToInt (jmax (i.lineY + i.lineHeight,
  38770. currentFont.getHeight()));
  38771. textHolder->setSize (w + 1, h + 1);
  38772. }
  38773. }
  38774. int TextEditor::getTextWidth() const throw()
  38775. {
  38776. return textHolder->getWidth();
  38777. }
  38778. int TextEditor::getTextHeight() const throw()
  38779. {
  38780. return textHolder->getHeight();
  38781. }
  38782. void TextEditor::setIndents (const int newLeftIndent,
  38783. const int newTopIndent) throw()
  38784. {
  38785. leftIndent = newLeftIndent;
  38786. topIndent = newTopIndent;
  38787. }
  38788. void TextEditor::setBorder (const BorderSize& border) throw()
  38789. {
  38790. borderSize = border;
  38791. resized();
  38792. }
  38793. const BorderSize TextEditor::getBorder() const throw()
  38794. {
  38795. return borderSize;
  38796. }
  38797. void TextEditor::setScrollToShowCursor (const bool shouldScrollToShowCursor) throw()
  38798. {
  38799. keepCursorOnScreen = shouldScrollToShowCursor;
  38800. }
  38801. void TextEditor::updateCaretPosition() throw()
  38802. {
  38803. cursorHeight = currentFont.getHeight(); // (in case the text is empty and the call below doesn't set this value)
  38804. getCharPosition (caretPosition, cursorX, cursorY, cursorHeight);
  38805. }
  38806. void TextEditor::scrollToMakeSureCursorIsVisible() throw()
  38807. {
  38808. updateCaretPosition();
  38809. if (keepCursorOnScreen)
  38810. {
  38811. int x = viewport->getViewPositionX();
  38812. int y = viewport->getViewPositionY();
  38813. const int relativeCursorX = roundFloatToInt (cursorX) - x;
  38814. const int relativeCursorY = roundFloatToInt (cursorY) - y;
  38815. if (relativeCursorX < jmax (1, proportionOfWidth (0.05f)))
  38816. {
  38817. x += relativeCursorX - proportionOfWidth (0.2f);
  38818. }
  38819. else if (relativeCursorX > jmax (0, viewport->getMaximumVisibleWidth() - (wordWrap ? 2 : 10)))
  38820. {
  38821. x += relativeCursorX + (isMultiLine() ? proportionOfWidth (0.2f) : 10) - viewport->getMaximumVisibleWidth();
  38822. }
  38823. x = jlimit (0, jmax (0, textHolder->getWidth() + 8 - viewport->getMaximumVisibleWidth()), x);
  38824. if (! isMultiLine())
  38825. {
  38826. y = (getHeight() - textHolder->getHeight() - topIndent) / -2;
  38827. }
  38828. else
  38829. {
  38830. const int curH = roundFloatToInt (cursorHeight);
  38831. if (relativeCursorY < 0)
  38832. {
  38833. y = jmax (0, relativeCursorY + y);
  38834. }
  38835. else if (relativeCursorY > jmax (0, viewport->getMaximumVisibleHeight() - topIndent - curH))
  38836. {
  38837. y += relativeCursorY + 2 + curH + topIndent - viewport->getMaximumVisibleHeight();
  38838. }
  38839. }
  38840. viewport->setViewPosition (x, y);
  38841. }
  38842. }
  38843. void TextEditor::moveCursorTo (const int newPosition,
  38844. const bool isSelecting) throw()
  38845. {
  38846. if (isSelecting)
  38847. {
  38848. moveCaret (newPosition);
  38849. const int oldSelStart = selectionStart;
  38850. const int oldSelEnd = selectionEnd;
  38851. if (dragType == notDragging)
  38852. {
  38853. if (abs (getCaretPosition() - selectionStart) < abs (getCaretPosition() - selectionEnd))
  38854. dragType = draggingSelectionStart;
  38855. else
  38856. dragType = draggingSelectionEnd;
  38857. }
  38858. if (dragType == draggingSelectionStart)
  38859. {
  38860. selectionStart = getCaretPosition();
  38861. if (selectionEnd < selectionStart)
  38862. {
  38863. swapVariables (selectionStart, selectionEnd);
  38864. dragType = draggingSelectionEnd;
  38865. }
  38866. }
  38867. else
  38868. {
  38869. selectionEnd = getCaretPosition();
  38870. if (selectionEnd < selectionStart)
  38871. {
  38872. swapVariables (selectionStart, selectionEnd);
  38873. dragType = draggingSelectionStart;
  38874. }
  38875. }
  38876. jassert (selectionStart <= selectionEnd);
  38877. jassert (oldSelStart <= oldSelEnd);
  38878. repaintText (jmin (oldSelStart, selectionStart),
  38879. jmax (oldSelEnd, selectionEnd));
  38880. }
  38881. else
  38882. {
  38883. dragType = notDragging;
  38884. if (selectionEnd > selectionStart)
  38885. repaintText (selectionStart, selectionEnd);
  38886. moveCaret (newPosition);
  38887. selectionStart = getCaretPosition();
  38888. selectionEnd = getCaretPosition();
  38889. }
  38890. }
  38891. int TextEditor::getTextIndexAt (const int x,
  38892. const int y) throw()
  38893. {
  38894. return indexAtPosition ((float) (x + viewport->getViewPositionX() - leftIndent),
  38895. (float) (y + viewport->getViewPositionY() - topIndent));
  38896. }
  38897. void TextEditor::insertTextAtCursor (String newText)
  38898. {
  38899. if (allowedCharacters.isNotEmpty())
  38900. newText = newText.retainCharacters (allowedCharacters);
  38901. if (! isMultiLine())
  38902. newText = newText.replaceCharacters (T("\r\n"), T(" "));
  38903. else
  38904. newText = newText.replace (T("\r\n"), T("\n"));
  38905. const int newCaretPos = selectionStart + newText.length();
  38906. const int insertIndex = selectionStart;
  38907. remove (selectionStart, selectionEnd,
  38908. &undoManager,
  38909. newText.isNotEmpty() ? newCaretPos - 1 : newCaretPos);
  38910. if (maxTextLength > 0)
  38911. newText = newText.substring (0, maxTextLength - getTotalNumChars());
  38912. if (newText.isNotEmpty())
  38913. insert (newText,
  38914. insertIndex,
  38915. currentFont,
  38916. findColour (textColourId),
  38917. &undoManager,
  38918. newCaretPos);
  38919. textChanged();
  38920. }
  38921. void TextEditor::setHighlightedRegion (int startPos, int numChars) throw()
  38922. {
  38923. moveCursorTo (startPos, false);
  38924. moveCursorTo (startPos + numChars, true);
  38925. }
  38926. void TextEditor::copy()
  38927. {
  38928. if (passwordCharacter == 0)
  38929. {
  38930. const String selection (getTextSubstring (selectionStart, selectionEnd));
  38931. if (selection.isNotEmpty())
  38932. SystemClipboard::copyTextToClipboard (selection);
  38933. }
  38934. }
  38935. void TextEditor::paste()
  38936. {
  38937. if (! isReadOnly())
  38938. {
  38939. const String clip (SystemClipboard::getTextFromClipboard());
  38940. if (clip.isNotEmpty())
  38941. insertTextAtCursor (clip);
  38942. }
  38943. }
  38944. void TextEditor::cut()
  38945. {
  38946. if (! isReadOnly())
  38947. {
  38948. moveCaret (selectionEnd);
  38949. insertTextAtCursor (String::empty);
  38950. }
  38951. }
  38952. void TextEditor::drawContent (Graphics& g)
  38953. {
  38954. const float wordWrapWidth = getWordWrapWidth();
  38955. if (wordWrapWidth > 0)
  38956. {
  38957. g.setOrigin (leftIndent, topIndent);
  38958. const Rectangle clip (g.getClipBounds());
  38959. Colour selectedTextColour;
  38960. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  38961. while (i.lineY + 200.0 < clip.getY() && i.next())
  38962. {}
  38963. if (selectionStart < selectionEnd)
  38964. {
  38965. g.setColour (findColour (highlightColourId)
  38966. .withMultipliedAlpha (hasKeyboardFocus (true) ? 1.0f : 0.5f));
  38967. selectedTextColour = findColour (highlightedTextColourId);
  38968. TextEditorIterator i2 (i);
  38969. while (i2.next() && i2.lineY < clip.getBottom())
  38970. {
  38971. i2.updateLineHeight();
  38972. if (i2.lineY + i2.lineHeight >= clip.getY()
  38973. && selectionEnd >= i2.indexInText
  38974. && selectionStart <= i2.indexInText + i2.atom->numChars)
  38975. {
  38976. i2.drawSelection (g, selectionStart, selectionEnd);
  38977. }
  38978. }
  38979. }
  38980. const UniformTextSection* lastSection = 0;
  38981. while (i.next() && i.lineY < clip.getBottom())
  38982. {
  38983. i.updateLineHeight();
  38984. if (i.lineY + i.lineHeight >= clip.getY())
  38985. {
  38986. if (selectionEnd >= i.indexInText
  38987. && selectionStart <= i.indexInText + i.atom->numChars)
  38988. {
  38989. i.drawSelectedText (g, selectionStart, selectionEnd, selectedTextColour);
  38990. lastSection = 0;
  38991. }
  38992. else
  38993. {
  38994. i.draw (g, lastSection);
  38995. }
  38996. }
  38997. }
  38998. }
  38999. }
  39000. void TextEditor::paint (Graphics& g)
  39001. {
  39002. getLookAndFeel().fillTextEditorBackground (g, getWidth(), getHeight(), *this);
  39003. }
  39004. void TextEditor::paintOverChildren (Graphics& g)
  39005. {
  39006. if (caretFlashState
  39007. && hasKeyboardFocus (false)
  39008. && caretVisible
  39009. && ! isReadOnly())
  39010. {
  39011. g.setColour (findColour (caretColourId));
  39012. g.fillRect (borderSize.getLeft() + textHolder->getX() + leftIndent + cursorX,
  39013. borderSize.getTop() + textHolder->getY() + topIndent + cursorY,
  39014. 2.0f, cursorHeight);
  39015. }
  39016. if (textToShowWhenEmpty.isNotEmpty()
  39017. && (! hasKeyboardFocus (false))
  39018. && getTotalNumChars() == 0)
  39019. {
  39020. g.setColour (colourForTextWhenEmpty);
  39021. g.setFont (getFont());
  39022. if (isMultiLine())
  39023. {
  39024. g.drawText (textToShowWhenEmpty,
  39025. 0, 0, getWidth(), getHeight(),
  39026. Justification::centred, true);
  39027. }
  39028. else
  39029. {
  39030. g.drawText (textToShowWhenEmpty,
  39031. leftIndent, topIndent,
  39032. viewport->getWidth() - leftIndent,
  39033. viewport->getHeight() - topIndent,
  39034. Justification::centredLeft, true);
  39035. }
  39036. }
  39037. getLookAndFeel().drawTextEditorOutline (g, getWidth(), getHeight(), *this);
  39038. }
  39039. void TextEditor::mouseDown (const MouseEvent& e)
  39040. {
  39041. beginDragAutoRepeat (100);
  39042. newTransaction();
  39043. if (wasFocused || ! selectAllTextWhenFocused)
  39044. {
  39045. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  39046. {
  39047. moveCursorTo (getTextIndexAt (e.x, e.y),
  39048. e.mods.isShiftDown());
  39049. }
  39050. else
  39051. {
  39052. PopupMenu m;
  39053. addPopupMenuItems (m, &e);
  39054. menuActive = true;
  39055. const int result = m.show();
  39056. menuActive = false;
  39057. if (result != 0)
  39058. performPopupMenuAction (result);
  39059. }
  39060. }
  39061. }
  39062. void TextEditor::mouseDrag (const MouseEvent& e)
  39063. {
  39064. if (wasFocused || ! selectAllTextWhenFocused)
  39065. {
  39066. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  39067. {
  39068. moveCursorTo (getTextIndexAt (e.x, e.y), true);
  39069. }
  39070. }
  39071. }
  39072. void TextEditor::mouseUp (const MouseEvent& e)
  39073. {
  39074. newTransaction();
  39075. textHolder->startTimer (flashSpeedIntervalMs);
  39076. if (wasFocused || ! selectAllTextWhenFocused)
  39077. {
  39078. if (! (popupMenuEnabled && e.mods.isPopupMenu()))
  39079. {
  39080. moveCaret (getTextIndexAt (e.x, e.y));
  39081. }
  39082. }
  39083. wasFocused = true;
  39084. }
  39085. void TextEditor::mouseDoubleClick (const MouseEvent& e)
  39086. {
  39087. int tokenEnd = getTextIndexAt (e.x, e.y);
  39088. int tokenStart = tokenEnd;
  39089. if (e.getNumberOfClicks() > 3)
  39090. {
  39091. tokenStart = 0;
  39092. tokenEnd = getTotalNumChars();
  39093. }
  39094. else
  39095. {
  39096. const String t (getText());
  39097. const int totalLength = getTotalNumChars();
  39098. while (tokenEnd < totalLength)
  39099. {
  39100. if (CharacterFunctions::isLetterOrDigit (t [tokenEnd]))
  39101. ++tokenEnd;
  39102. else
  39103. break;
  39104. }
  39105. tokenStart = tokenEnd;
  39106. while (tokenStart > 0)
  39107. {
  39108. if (CharacterFunctions::isLetterOrDigit (t [tokenStart - 1]))
  39109. --tokenStart;
  39110. else
  39111. break;
  39112. }
  39113. if (e.getNumberOfClicks() > 2)
  39114. {
  39115. while (tokenEnd < totalLength)
  39116. {
  39117. if (t [tokenEnd] != T('\r') && t [tokenEnd] != T('\n'))
  39118. ++tokenEnd;
  39119. else
  39120. break;
  39121. }
  39122. while (tokenStart > 0)
  39123. {
  39124. if (t [tokenStart - 1] != T('\r') && t [tokenStart - 1] != T('\n'))
  39125. --tokenStart;
  39126. else
  39127. break;
  39128. }
  39129. }
  39130. }
  39131. moveCursorTo (tokenEnd, false);
  39132. moveCursorTo (tokenStart, true);
  39133. }
  39134. void TextEditor::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  39135. {
  39136. if (! viewport->useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  39137. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  39138. }
  39139. bool TextEditor::keyPressed (const KeyPress& key)
  39140. {
  39141. if (isReadOnly() && key != KeyPress (T('c'), ModifierKeys::commandModifier, 0))
  39142. return false;
  39143. const bool moveInWholeWordSteps = key.getModifiers().isCtrlDown() || key.getModifiers().isAltDown();
  39144. if (key.isKeyCode (KeyPress::leftKey)
  39145. || key.isKeyCode (KeyPress::upKey))
  39146. {
  39147. newTransaction();
  39148. int newPos;
  39149. if (isMultiLine() && key.isKeyCode (KeyPress::upKey))
  39150. newPos = indexAtPosition (cursorX, cursorY - 1);
  39151. else if (moveInWholeWordSteps)
  39152. newPos = findWordBreakBefore (getCaretPosition());
  39153. else
  39154. newPos = getCaretPosition() - 1;
  39155. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  39156. }
  39157. else if (key.isKeyCode (KeyPress::rightKey)
  39158. || key.isKeyCode (KeyPress::downKey))
  39159. {
  39160. newTransaction();
  39161. int newPos;
  39162. if (isMultiLine() && key.isKeyCode (KeyPress::downKey))
  39163. newPos = indexAtPosition (cursorX, cursorY + cursorHeight + 1);
  39164. else if (moveInWholeWordSteps)
  39165. newPos = findWordBreakAfter (getCaretPosition());
  39166. else
  39167. newPos = getCaretPosition() + 1;
  39168. moveCursorTo (newPos, key.getModifiers().isShiftDown());
  39169. }
  39170. else if (key.isKeyCode (KeyPress::pageDownKey) && isMultiLine())
  39171. {
  39172. newTransaction();
  39173. moveCursorTo (indexAtPosition (cursorX, cursorY + cursorHeight + viewport->getViewHeight()),
  39174. key.getModifiers().isShiftDown());
  39175. }
  39176. else if (key.isKeyCode (KeyPress::pageUpKey) && isMultiLine())
  39177. {
  39178. newTransaction();
  39179. moveCursorTo (indexAtPosition (cursorX, cursorY - viewport->getViewHeight()),
  39180. key.getModifiers().isShiftDown());
  39181. }
  39182. else if (key.isKeyCode (KeyPress::homeKey))
  39183. {
  39184. newTransaction();
  39185. if (isMultiLine() && ! moveInWholeWordSteps)
  39186. moveCursorTo (indexAtPosition (0.0f, cursorY),
  39187. key.getModifiers().isShiftDown());
  39188. else
  39189. moveCursorTo (0, key.getModifiers().isShiftDown());
  39190. }
  39191. else if (key.isKeyCode (KeyPress::endKey))
  39192. {
  39193. newTransaction();
  39194. if (isMultiLine() && ! moveInWholeWordSteps)
  39195. moveCursorTo (indexAtPosition ((float) textHolder->getWidth(), cursorY),
  39196. key.getModifiers().isShiftDown());
  39197. else
  39198. moveCursorTo (getTotalNumChars(), key.getModifiers().isShiftDown());
  39199. }
  39200. else if (key.isKeyCode (KeyPress::backspaceKey))
  39201. {
  39202. if (moveInWholeWordSteps)
  39203. {
  39204. moveCursorTo (findWordBreakBefore (getCaretPosition()), true);
  39205. }
  39206. else
  39207. {
  39208. if (selectionStart == selectionEnd && selectionStart > 0)
  39209. --selectionStart;
  39210. }
  39211. cut();
  39212. }
  39213. else if (key.isKeyCode (KeyPress::deleteKey))
  39214. {
  39215. if (key.getModifiers().isShiftDown())
  39216. copy();
  39217. if (selectionStart == selectionEnd
  39218. && selectionEnd < getTotalNumChars())
  39219. {
  39220. ++selectionEnd;
  39221. }
  39222. cut();
  39223. }
  39224. else if (key == KeyPress (T('c'), ModifierKeys::commandModifier, 0)
  39225. || key == KeyPress (KeyPress::insertKey, ModifierKeys::ctrlModifier, 0))
  39226. {
  39227. newTransaction();
  39228. copy();
  39229. }
  39230. else if (key == KeyPress (T('x'), ModifierKeys::commandModifier, 0))
  39231. {
  39232. newTransaction();
  39233. copy();
  39234. cut();
  39235. }
  39236. else if (key == KeyPress (T('v'), ModifierKeys::commandModifier, 0)
  39237. || key == KeyPress (KeyPress::insertKey, ModifierKeys::shiftModifier, 0))
  39238. {
  39239. newTransaction();
  39240. paste();
  39241. }
  39242. else if (key == KeyPress (T('z'), ModifierKeys::commandModifier, 0))
  39243. {
  39244. newTransaction();
  39245. doUndoRedo (false);
  39246. }
  39247. else if (key == KeyPress (T('y'), ModifierKeys::commandModifier, 0))
  39248. {
  39249. newTransaction();
  39250. doUndoRedo (true);
  39251. }
  39252. else if (key == KeyPress (T('a'), ModifierKeys::commandModifier, 0))
  39253. {
  39254. newTransaction();
  39255. moveCursorTo (getTotalNumChars(), false);
  39256. moveCursorTo (0, true);
  39257. }
  39258. else if (key == KeyPress::returnKey)
  39259. {
  39260. newTransaction();
  39261. if (returnKeyStartsNewLine)
  39262. insertTextAtCursor (T("\n"));
  39263. else
  39264. returnPressed();
  39265. }
  39266. else if (key.isKeyCode (KeyPress::escapeKey))
  39267. {
  39268. newTransaction();
  39269. moveCursorTo (getCaretPosition(), false);
  39270. escapePressed();
  39271. }
  39272. else if (key.getTextCharacter() >= ' '
  39273. || (tabKeyUsed && (key.getTextCharacter() == '\t')))
  39274. {
  39275. insertTextAtCursor (String::charToString (key.getTextCharacter()));
  39276. lastTransactionTime = Time::getApproximateMillisecondCounter();
  39277. }
  39278. else
  39279. {
  39280. return false;
  39281. }
  39282. return true;
  39283. }
  39284. bool TextEditor::keyStateChanged()
  39285. {
  39286. // (overridden to avoid forwarding key events to the parent)
  39287. return true;
  39288. }
  39289. const int baseMenuItemID = 0x7fff0000;
  39290. void TextEditor::addPopupMenuItems (PopupMenu& m, const MouseEvent*)
  39291. {
  39292. const bool writable = ! isReadOnly();
  39293. if (passwordCharacter == 0)
  39294. {
  39295. m.addItem (baseMenuItemID + 1, TRANS("cut"), writable);
  39296. m.addItem (baseMenuItemID + 2, TRANS("copy"), selectionStart < selectionEnd);
  39297. m.addItem (baseMenuItemID + 3, TRANS("paste"), writable);
  39298. }
  39299. m.addItem (baseMenuItemID + 4, TRANS("delete"), writable);
  39300. m.addSeparator();
  39301. m.addItem (baseMenuItemID + 5, TRANS("select all"));
  39302. m.addSeparator();
  39303. m.addItem (baseMenuItemID + 6, TRANS("undo"), undoManager.canUndo());
  39304. m.addItem (baseMenuItemID + 7, TRANS("redo"), undoManager.canRedo());
  39305. }
  39306. void TextEditor::performPopupMenuAction (const int menuItemID)
  39307. {
  39308. switch (menuItemID)
  39309. {
  39310. case baseMenuItemID + 1:
  39311. copy();
  39312. cut();
  39313. break;
  39314. case baseMenuItemID + 2:
  39315. copy();
  39316. break;
  39317. case baseMenuItemID + 3:
  39318. paste();
  39319. break;
  39320. case baseMenuItemID + 4:
  39321. cut();
  39322. break;
  39323. case baseMenuItemID + 5:
  39324. moveCursorTo (getTotalNumChars(), false);
  39325. moveCursorTo (0, true);
  39326. break;
  39327. case baseMenuItemID + 6:
  39328. doUndoRedo (false);
  39329. break;
  39330. case baseMenuItemID + 7:
  39331. doUndoRedo (true);
  39332. break;
  39333. default:
  39334. break;
  39335. }
  39336. }
  39337. void TextEditor::focusGained (FocusChangeType)
  39338. {
  39339. newTransaction();
  39340. caretFlashState = true;
  39341. if (selectAllTextWhenFocused)
  39342. {
  39343. moveCursorTo (0, false);
  39344. moveCursorTo (getTotalNumChars(), true);
  39345. }
  39346. repaint();
  39347. if (caretVisible)
  39348. textHolder->startTimer (flashSpeedIntervalMs);
  39349. ComponentPeer* const peer = getPeer();
  39350. if (peer != 0)
  39351. peer->textInputRequired (getScreenX() - peer->getScreenX(),
  39352. getScreenY() - peer->getScreenY());
  39353. }
  39354. void TextEditor::focusLost (FocusChangeType)
  39355. {
  39356. newTransaction();
  39357. wasFocused = false;
  39358. textHolder->stopTimer();
  39359. caretFlashState = false;
  39360. postCommandMessage (focusLossMessageId);
  39361. repaint();
  39362. }
  39363. void TextEditor::resized()
  39364. {
  39365. viewport->setBoundsInset (borderSize);
  39366. viewport->setSingleStepSizes (16, roundFloatToInt (currentFont.getHeight()));
  39367. updateTextHolderSize();
  39368. if (! isMultiLine())
  39369. {
  39370. scrollToMakeSureCursorIsVisible();
  39371. }
  39372. else
  39373. {
  39374. updateCaretPosition();
  39375. }
  39376. }
  39377. void TextEditor::handleCommandMessage (const int commandId)
  39378. {
  39379. const ComponentDeletionWatcher deletionChecker (this);
  39380. for (int i = listeners.size(); --i >= 0;)
  39381. {
  39382. TextEditorListener* const tl = (TextEditorListener*) listeners [i];
  39383. if (tl != 0)
  39384. {
  39385. switch (commandId)
  39386. {
  39387. case textChangeMessageId:
  39388. tl->textEditorTextChanged (*this);
  39389. break;
  39390. case returnKeyMessageId:
  39391. tl->textEditorReturnKeyPressed (*this);
  39392. break;
  39393. case escapeKeyMessageId:
  39394. tl->textEditorEscapeKeyPressed (*this);
  39395. break;
  39396. case focusLossMessageId:
  39397. tl->textEditorFocusLost (*this);
  39398. break;
  39399. default:
  39400. jassertfalse
  39401. break;
  39402. }
  39403. if (i > 0 && deletionChecker.hasBeenDeleted())
  39404. return;
  39405. }
  39406. }
  39407. }
  39408. void TextEditor::enablementChanged()
  39409. {
  39410. setMouseCursor (MouseCursor (isReadOnly() ? MouseCursor::NormalCursor
  39411. : MouseCursor::IBeamCursor));
  39412. repaint();
  39413. }
  39414. void TextEditor::clearInternal (UndoManager* const um) throw()
  39415. {
  39416. remove (0, getTotalNumChars(), um, caretPosition);
  39417. }
  39418. void TextEditor::insert (const String& text,
  39419. const int insertIndex,
  39420. const Font& font,
  39421. const Colour& colour,
  39422. UndoManager* const um,
  39423. const int caretPositionToMoveTo) throw()
  39424. {
  39425. if (text.isNotEmpty())
  39426. {
  39427. if (um != 0)
  39428. {
  39429. um->perform (new TextEditorInsertAction (*this,
  39430. text,
  39431. insertIndex,
  39432. font,
  39433. colour,
  39434. caretPosition,
  39435. caretPositionToMoveTo));
  39436. }
  39437. else
  39438. {
  39439. repaintText (insertIndex, -1); // must do this before and after changing the data, in case
  39440. // a line gets moved due to word wrap
  39441. int index = 0;
  39442. int nextIndex = 0;
  39443. for (int i = 0; i < sections.size(); ++i)
  39444. {
  39445. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  39446. if (insertIndex == index)
  39447. {
  39448. sections.insert (i, new UniformTextSection (text,
  39449. font, colour,
  39450. passwordCharacter));
  39451. break;
  39452. }
  39453. else if (insertIndex > index && insertIndex < nextIndex)
  39454. {
  39455. splitSection (i, insertIndex - index);
  39456. sections.insert (i + 1, new UniformTextSection (text,
  39457. font, colour,
  39458. passwordCharacter));
  39459. break;
  39460. }
  39461. index = nextIndex;
  39462. }
  39463. if (nextIndex == insertIndex)
  39464. sections.add (new UniformTextSection (text,
  39465. font, colour,
  39466. passwordCharacter));
  39467. coalesceSimilarSections();
  39468. totalNumChars = -1;
  39469. moveCursorTo (caretPositionToMoveTo, false);
  39470. repaintText (insertIndex, -1);
  39471. }
  39472. }
  39473. }
  39474. void TextEditor::reinsert (const int insertIndex,
  39475. const VoidArray& sectionsToInsert) throw()
  39476. {
  39477. int index = 0;
  39478. int nextIndex = 0;
  39479. for (int i = 0; i < sections.size(); ++i)
  39480. {
  39481. nextIndex = index + ((UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  39482. if (insertIndex == index)
  39483. {
  39484. for (int j = sectionsToInsert.size(); --j >= 0;)
  39485. sections.insert (i, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  39486. break;
  39487. }
  39488. else if (insertIndex > index && insertIndex < nextIndex)
  39489. {
  39490. splitSection (i, insertIndex - index);
  39491. for (int j = sectionsToInsert.size(); --j >= 0;)
  39492. sections.insert (i + 1, new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  39493. break;
  39494. }
  39495. index = nextIndex;
  39496. }
  39497. if (nextIndex == insertIndex)
  39498. {
  39499. for (int j = 0; j < sectionsToInsert.size(); ++j)
  39500. sections.add (new UniformTextSection (*(UniformTextSection*) sectionsToInsert.getUnchecked(j)));
  39501. }
  39502. coalesceSimilarSections();
  39503. totalNumChars = -1;
  39504. }
  39505. void TextEditor::remove (const int startIndex,
  39506. int endIndex,
  39507. UndoManager* const um,
  39508. const int caretPositionToMoveTo) throw()
  39509. {
  39510. if (endIndex > startIndex)
  39511. {
  39512. int index = 0;
  39513. for (int i = 0; i < sections.size(); ++i)
  39514. {
  39515. const int nextIndex = index + ((UniformTextSection*) sections[i])->getTotalLength();
  39516. if (startIndex > index && startIndex < nextIndex)
  39517. {
  39518. splitSection (i, startIndex - index);
  39519. --i;
  39520. }
  39521. else if (endIndex > index && endIndex < nextIndex)
  39522. {
  39523. splitSection (i, endIndex - index);
  39524. --i;
  39525. }
  39526. else
  39527. {
  39528. index = nextIndex;
  39529. if (index > endIndex)
  39530. break;
  39531. }
  39532. }
  39533. index = 0;
  39534. if (um != 0)
  39535. {
  39536. VoidArray removedSections;
  39537. for (int i = 0; i < sections.size(); ++i)
  39538. {
  39539. if (endIndex <= startIndex)
  39540. break;
  39541. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  39542. const int nextIndex = index + section->getTotalLength();
  39543. if (startIndex <= index && endIndex >= nextIndex)
  39544. removedSections.add (new UniformTextSection (*section));
  39545. index = nextIndex;
  39546. }
  39547. um->perform (new TextEditorRemoveAction (*this,
  39548. startIndex,
  39549. endIndex,
  39550. caretPosition,
  39551. caretPositionToMoveTo,
  39552. removedSections));
  39553. }
  39554. else
  39555. {
  39556. for (int i = 0; i < sections.size(); ++i)
  39557. {
  39558. if (endIndex <= startIndex)
  39559. break;
  39560. UniformTextSection* const section = (UniformTextSection*) sections.getUnchecked (i);
  39561. const int nextIndex = index + section->getTotalLength();
  39562. if (startIndex <= index && endIndex >= nextIndex)
  39563. {
  39564. sections.remove(i);
  39565. endIndex -= (nextIndex - index);
  39566. section->clear();
  39567. delete section;
  39568. --i;
  39569. }
  39570. else
  39571. {
  39572. index = nextIndex;
  39573. }
  39574. }
  39575. coalesceSimilarSections();
  39576. totalNumChars = -1;
  39577. moveCursorTo (caretPositionToMoveTo, false);
  39578. repaintText (startIndex, -1);
  39579. }
  39580. }
  39581. }
  39582. const String TextEditor::getText() const throw()
  39583. {
  39584. String t;
  39585. for (int i = 0; i < sections.size(); ++i)
  39586. t += ((const UniformTextSection*) sections.getUnchecked(i))->getAllText();
  39587. return t;
  39588. }
  39589. const String TextEditor::getTextSubstring (const int startCharacter, const int endCharacter) const throw()
  39590. {
  39591. String t;
  39592. int index = 0;
  39593. for (int i = 0; i < sections.size(); ++i)
  39594. {
  39595. const UniformTextSection* const s = (const UniformTextSection*) sections.getUnchecked(i);
  39596. const int nextIndex = index + s->getTotalLength();
  39597. if (startCharacter < nextIndex)
  39598. {
  39599. if (endCharacter <= index)
  39600. break;
  39601. const int start = jmax (index, startCharacter);
  39602. t += s->getTextSubstring (start - index, endCharacter - index);
  39603. }
  39604. index = nextIndex;
  39605. }
  39606. return t;
  39607. }
  39608. const String TextEditor::getHighlightedText() const throw()
  39609. {
  39610. return getTextSubstring (getHighlightedRegionStart(),
  39611. getHighlightedRegionStart() + getHighlightedRegionLength());
  39612. }
  39613. int TextEditor::getTotalNumChars() throw()
  39614. {
  39615. if (totalNumChars < 0)
  39616. {
  39617. totalNumChars = 0;
  39618. for (int i = sections.size(); --i >= 0;)
  39619. totalNumChars += ((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength();
  39620. }
  39621. return totalNumChars;
  39622. }
  39623. bool TextEditor::isEmpty() const throw()
  39624. {
  39625. if (totalNumChars != 0)
  39626. {
  39627. for (int i = sections.size(); --i >= 0;)
  39628. if (((const UniformTextSection*) sections.getUnchecked(i))->getTotalLength() > 0)
  39629. return false;
  39630. }
  39631. return true;
  39632. }
  39633. void TextEditor::getCharPosition (const int index, float& cx, float& cy, float& lineHeight) const throw()
  39634. {
  39635. const float wordWrapWidth = getWordWrapWidth();
  39636. if (wordWrapWidth > 0 && sections.size() > 0)
  39637. {
  39638. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39639. i.getCharPosition (index, cx, cy, lineHeight);
  39640. }
  39641. else
  39642. {
  39643. cx = cy = 0;
  39644. lineHeight = currentFont.getHeight();
  39645. }
  39646. }
  39647. int TextEditor::indexAtPosition (const float x, const float y) throw()
  39648. {
  39649. const float wordWrapWidth = getWordWrapWidth();
  39650. if (wordWrapWidth > 0)
  39651. {
  39652. TextEditorIterator i (sections, wordWrapWidth, passwordCharacter);
  39653. while (i.next())
  39654. {
  39655. if (i.lineY + getHeight() > y)
  39656. i.updateLineHeight();
  39657. if (i.lineY + i.lineHeight > y)
  39658. {
  39659. if (i.lineY > y)
  39660. return jmax (0, i.indexInText - 1);
  39661. if (i.atomX >= x)
  39662. return i.indexInText;
  39663. if (x < i.atomRight)
  39664. return i.xToIndex (x);
  39665. }
  39666. }
  39667. }
  39668. return getTotalNumChars();
  39669. }
  39670. static int getCharacterCategory (const tchar character) throw()
  39671. {
  39672. return CharacterFunctions::isLetterOrDigit (character)
  39673. ? 2 : (CharacterFunctions::isWhitespace (character) ? 0 : 1);
  39674. }
  39675. int TextEditor::findWordBreakAfter (const int position) const throw()
  39676. {
  39677. const String t (getTextSubstring (position, position + 512));
  39678. const int totalLength = t.length();
  39679. int i = 0;
  39680. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  39681. ++i;
  39682. const int type = getCharacterCategory (t[i]);
  39683. while (i < totalLength && type == getCharacterCategory (t[i]))
  39684. ++i;
  39685. while (i < totalLength && CharacterFunctions::isWhitespace (t[i]))
  39686. ++i;
  39687. return position + i;
  39688. }
  39689. int TextEditor::findWordBreakBefore (const int position) const throw()
  39690. {
  39691. if (position <= 0)
  39692. return 0;
  39693. const int startOfBuffer = jmax (0, position - 512);
  39694. const String t (getTextSubstring (startOfBuffer, position));
  39695. int i = position - startOfBuffer;
  39696. while (i > 0 && CharacterFunctions::isWhitespace (t [i - 1]))
  39697. --i;
  39698. if (i > 0)
  39699. {
  39700. const int type = getCharacterCategory (t [i - 1]);
  39701. while (i > 0 && type == getCharacterCategory (t [i - 1]))
  39702. --i;
  39703. }
  39704. jassert (startOfBuffer + i >= 0);
  39705. return startOfBuffer + i;
  39706. }
  39707. void TextEditor::splitSection (const int sectionIndex,
  39708. const int charToSplitAt) throw()
  39709. {
  39710. jassert (sections[sectionIndex] != 0);
  39711. sections.insert (sectionIndex + 1,
  39712. ((UniformTextSection*) sections.getUnchecked (sectionIndex))
  39713. ->split (charToSplitAt, passwordCharacter));
  39714. }
  39715. void TextEditor::coalesceSimilarSections() throw()
  39716. {
  39717. for (int i = 0; i < sections.size() - 1; ++i)
  39718. {
  39719. UniformTextSection* const s1 = (UniformTextSection*) (sections.getUnchecked (i));
  39720. UniformTextSection* const s2 = (UniformTextSection*) (sections.getUnchecked (i + 1));
  39721. if (s1->font == s2->font
  39722. && s1->colour == s2->colour)
  39723. {
  39724. s1->append (*s2, passwordCharacter);
  39725. sections.remove (i + 1);
  39726. delete s2;
  39727. --i;
  39728. }
  39729. }
  39730. }
  39731. END_JUCE_NAMESPACE
  39732. /********* End of inlined file: juce_TextEditor.cpp *********/
  39733. /********* Start of inlined file: juce_Toolbar.cpp *********/
  39734. BEGIN_JUCE_NAMESPACE
  39735. const tchar* const Toolbar::toolbarDragDescriptor = T("_toolbarItem_");
  39736. class ToolbarSpacerComp : public ToolbarItemComponent
  39737. {
  39738. public:
  39739. ToolbarSpacerComp (const int itemId, const float fixedSize_, const bool drawBar_)
  39740. : ToolbarItemComponent (itemId, String::empty, false),
  39741. fixedSize (fixedSize_),
  39742. drawBar (drawBar_)
  39743. {
  39744. }
  39745. ~ToolbarSpacerComp()
  39746. {
  39747. }
  39748. bool getToolbarItemSizes (int toolbarThickness, bool /*isToolbarVertical*/,
  39749. int& preferredSize, int& minSize, int& maxSize)
  39750. {
  39751. if (fixedSize <= 0)
  39752. {
  39753. preferredSize = toolbarThickness * 2;
  39754. minSize = 4;
  39755. maxSize = 32768;
  39756. }
  39757. else
  39758. {
  39759. maxSize = roundFloatToInt (toolbarThickness * fixedSize);
  39760. minSize = drawBar ? maxSize : jmin (4, maxSize);
  39761. preferredSize = maxSize;
  39762. if (getEditingMode() == editableOnPalette)
  39763. preferredSize = maxSize = toolbarThickness / (drawBar ? 3 : 2);
  39764. }
  39765. return true;
  39766. }
  39767. void paintButtonArea (Graphics&, int, int, bool, bool)
  39768. {
  39769. }
  39770. void contentAreaChanged (const Rectangle&)
  39771. {
  39772. }
  39773. int getResizeOrder() const throw()
  39774. {
  39775. return fixedSize <= 0 ? 0 : 1;
  39776. }
  39777. void paint (Graphics& g)
  39778. {
  39779. const int w = getWidth();
  39780. const int h = getHeight();
  39781. if (drawBar)
  39782. {
  39783. g.setColour (findColour (Toolbar::separatorColourId, true));
  39784. const float thickness = 0.2f;
  39785. if (isToolbarVertical())
  39786. g.fillRect (w * 0.1f, h * (0.5f - thickness * 0.5f), w * 0.8f, h * thickness);
  39787. else
  39788. g.fillRect (w * (0.5f - thickness * 0.5f), h * 0.1f, w * thickness, h * 0.8f);
  39789. }
  39790. if (getEditingMode() != normalMode && ! drawBar)
  39791. {
  39792. g.setColour (findColour (Toolbar::separatorColourId, true));
  39793. const int indentX = jmin (2, (w - 3) / 2);
  39794. const int indentY = jmin (2, (h - 3) / 2);
  39795. g.drawRect (indentX, indentY, w - indentX * 2, h - indentY * 2, 1);
  39796. if (fixedSize <= 0)
  39797. {
  39798. float x1, y1, x2, y2, x3, y3, x4, y4, hw, hl;
  39799. if (isToolbarVertical())
  39800. {
  39801. x1 = w * 0.5f;
  39802. y1 = h * 0.4f;
  39803. x2 = x1;
  39804. y2 = indentX * 2.0f;
  39805. x3 = x1;
  39806. y3 = h * 0.6f;
  39807. x4 = x1;
  39808. y4 = h - y2;
  39809. hw = w * 0.15f;
  39810. hl = w * 0.2f;
  39811. }
  39812. else
  39813. {
  39814. x1 = w * 0.4f;
  39815. y1 = h * 0.5f;
  39816. x2 = indentX * 2.0f;
  39817. y2 = y1;
  39818. x3 = w * 0.6f;
  39819. y3 = y1;
  39820. x4 = w - x2;
  39821. y4 = y1;
  39822. hw = h * 0.15f;
  39823. hl = h * 0.2f;
  39824. }
  39825. Path p;
  39826. p.addArrow (x1, y1, x2, y2, 1.5f, hw, hl);
  39827. p.addArrow (x3, y3, x4, y4, 1.5f, hw, hl);
  39828. g.fillPath (p);
  39829. }
  39830. }
  39831. }
  39832. juce_UseDebuggingNewOperator
  39833. private:
  39834. const float fixedSize;
  39835. const bool drawBar;
  39836. ToolbarSpacerComp (const ToolbarSpacerComp&);
  39837. const ToolbarSpacerComp& operator= (const ToolbarSpacerComp&);
  39838. };
  39839. class MissingItemsComponent : public PopupMenuCustomComponent
  39840. {
  39841. public:
  39842. MissingItemsComponent (Toolbar& owner_, const int height_)
  39843. : PopupMenuCustomComponent (true),
  39844. owner (owner_),
  39845. height (height_)
  39846. {
  39847. for (int i = owner_.items.size(); --i >= 0;)
  39848. {
  39849. ToolbarItemComponent* const tc = owner_.items.getUnchecked(i);
  39850. if (dynamic_cast <ToolbarSpacerComp*> (tc) == 0 && ! tc->isVisible())
  39851. {
  39852. oldIndexes.insert (0, i);
  39853. addAndMakeVisible (tc, 0);
  39854. }
  39855. }
  39856. layout (400);
  39857. }
  39858. ~MissingItemsComponent()
  39859. {
  39860. // deleting the toolbar while its menu it open??
  39861. jassert (owner.isValidComponent());
  39862. for (int i = 0; i < getNumChildComponents(); ++i)
  39863. {
  39864. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  39865. if (tc != 0)
  39866. {
  39867. tc->setVisible (false);
  39868. const int index = oldIndexes.remove (i);
  39869. owner.addChildComponent (tc, index);
  39870. --i;
  39871. }
  39872. }
  39873. owner.resized();
  39874. }
  39875. void layout (const int preferredWidth)
  39876. {
  39877. const int indent = 8;
  39878. int x = indent;
  39879. int y = indent;
  39880. int maxX = 0;
  39881. for (int i = 0; i < getNumChildComponents(); ++i)
  39882. {
  39883. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getChildComponent (i));
  39884. if (tc != 0)
  39885. {
  39886. int preferredSize = 1, minSize = 1, maxSize = 1;
  39887. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  39888. {
  39889. if (x + preferredSize > preferredWidth && x > indent)
  39890. {
  39891. x = indent;
  39892. y += height;
  39893. }
  39894. tc->setBounds (x, y, preferredSize, height);
  39895. x += preferredSize;
  39896. maxX = jmax (maxX, x);
  39897. }
  39898. }
  39899. }
  39900. setSize (maxX + 8, y + height + 8);
  39901. }
  39902. void getIdealSize (int& idealWidth, int& idealHeight)
  39903. {
  39904. idealWidth = getWidth();
  39905. idealHeight = getHeight();
  39906. }
  39907. juce_UseDebuggingNewOperator
  39908. private:
  39909. Toolbar& owner;
  39910. const int height;
  39911. Array <int> oldIndexes;
  39912. MissingItemsComponent (const MissingItemsComponent&);
  39913. const MissingItemsComponent& operator= (const MissingItemsComponent&);
  39914. };
  39915. Toolbar::Toolbar()
  39916. : vertical (false),
  39917. isEditingActive (false),
  39918. toolbarStyle (Toolbar::iconsOnly)
  39919. {
  39920. addChildComponent (missingItemsButton = getLookAndFeel().createToolbarMissingItemsButton (*this));
  39921. missingItemsButton->setAlwaysOnTop (true);
  39922. missingItemsButton->addButtonListener (this);
  39923. }
  39924. Toolbar::~Toolbar()
  39925. {
  39926. animator.cancelAllAnimations (true);
  39927. deleteAllChildren();
  39928. }
  39929. void Toolbar::setVertical (const bool shouldBeVertical)
  39930. {
  39931. if (vertical != shouldBeVertical)
  39932. {
  39933. vertical = shouldBeVertical;
  39934. resized();
  39935. }
  39936. }
  39937. void Toolbar::clear()
  39938. {
  39939. for (int i = items.size(); --i >= 0;)
  39940. {
  39941. ToolbarItemComponent* const tc = items.getUnchecked(i);
  39942. items.remove (i);
  39943. delete tc;
  39944. }
  39945. resized();
  39946. }
  39947. ToolbarItemComponent* Toolbar::createItem (ToolbarItemFactory& factory, const int itemId)
  39948. {
  39949. if (itemId == ToolbarItemFactory::separatorBarId)
  39950. return new ToolbarSpacerComp (itemId, 0.1f, true);
  39951. else if (itemId == ToolbarItemFactory::spacerId)
  39952. return new ToolbarSpacerComp (itemId, 0.5f, false);
  39953. else if (itemId == ToolbarItemFactory::flexibleSpacerId)
  39954. return new ToolbarSpacerComp (itemId, 0, false);
  39955. return factory.createItem (itemId);
  39956. }
  39957. void Toolbar::addItemInternal (ToolbarItemFactory& factory,
  39958. const int itemId,
  39959. const int insertIndex)
  39960. {
  39961. // An ID can't be zero - this might indicate a mistake somewhere?
  39962. jassert (itemId != 0);
  39963. ToolbarItemComponent* const tc = createItem (factory, itemId);
  39964. if (tc != 0)
  39965. {
  39966. #ifdef JUCE_DEBUG
  39967. Array <int> allowedIds;
  39968. factory.getAllToolbarItemIds (allowedIds);
  39969. // If your factory can create an item for a given ID, it must also return
  39970. // that ID from its getAllToolbarItemIds() method!
  39971. jassert (allowedIds.contains (itemId));
  39972. #endif
  39973. items.insert (insertIndex, tc);
  39974. addAndMakeVisible (tc, insertIndex);
  39975. }
  39976. }
  39977. void Toolbar::addItem (ToolbarItemFactory& factory,
  39978. const int itemId,
  39979. const int insertIndex)
  39980. {
  39981. addItemInternal (factory, itemId, insertIndex);
  39982. resized();
  39983. }
  39984. void Toolbar::addDefaultItems (ToolbarItemFactory& factoryToUse)
  39985. {
  39986. Array <int> ids;
  39987. factoryToUse.getDefaultItemSet (ids);
  39988. clear();
  39989. for (int i = 0; i < ids.size(); ++i)
  39990. addItemInternal (factoryToUse, ids.getUnchecked (i), -1);
  39991. resized();
  39992. }
  39993. void Toolbar::removeToolbarItem (const int itemIndex)
  39994. {
  39995. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  39996. if (tc != 0)
  39997. {
  39998. items.removeValue (tc);
  39999. delete tc;
  40000. resized();
  40001. }
  40002. }
  40003. int Toolbar::getNumItems() const throw()
  40004. {
  40005. return items.size();
  40006. }
  40007. int Toolbar::getItemId (const int itemIndex) const throw()
  40008. {
  40009. ToolbarItemComponent* const tc = getItemComponent (itemIndex);
  40010. return tc != 0 ? tc->getItemId() : 0;
  40011. }
  40012. ToolbarItemComponent* Toolbar::getItemComponent (const int itemIndex) const throw()
  40013. {
  40014. return items [itemIndex];
  40015. }
  40016. ToolbarItemComponent* Toolbar::getNextActiveComponent (int index, const int delta) const
  40017. {
  40018. for (;;)
  40019. {
  40020. index += delta;
  40021. ToolbarItemComponent* const tc = getItemComponent (index);
  40022. if (tc == 0)
  40023. break;
  40024. if (tc->isActive)
  40025. return tc;
  40026. }
  40027. return 0;
  40028. }
  40029. void Toolbar::setStyle (const ToolbarItemStyle& newStyle)
  40030. {
  40031. if (toolbarStyle != newStyle)
  40032. {
  40033. toolbarStyle = newStyle;
  40034. updateAllItemPositions (false);
  40035. }
  40036. }
  40037. const String Toolbar::toString() const
  40038. {
  40039. String s (T("TB:"));
  40040. for (int i = 0; i < getNumItems(); ++i)
  40041. s << getItemId(i) << T(' ');
  40042. return s.trimEnd();
  40043. }
  40044. bool Toolbar::restoreFromString (ToolbarItemFactory& factoryToUse,
  40045. const String& savedVersion)
  40046. {
  40047. if (! savedVersion.startsWith (T("TB:")))
  40048. return false;
  40049. StringArray tokens;
  40050. tokens.addTokens (savedVersion.substring (3), false);
  40051. clear();
  40052. for (int i = 0; i < tokens.size(); ++i)
  40053. addItemInternal (factoryToUse, tokens[i].getIntValue(), -1);
  40054. resized();
  40055. return true;
  40056. }
  40057. void Toolbar::paint (Graphics& g)
  40058. {
  40059. getLookAndFeel().paintToolbarBackground (g, getWidth(), getHeight(), *this);
  40060. }
  40061. int Toolbar::getThickness() const throw()
  40062. {
  40063. return vertical ? getWidth() : getHeight();
  40064. }
  40065. int Toolbar::getLength() const throw()
  40066. {
  40067. return vertical ? getHeight() : getWidth();
  40068. }
  40069. void Toolbar::setEditingActive (const bool active)
  40070. {
  40071. if (isEditingActive != active)
  40072. {
  40073. isEditingActive = active;
  40074. updateAllItemPositions (false);
  40075. }
  40076. }
  40077. void Toolbar::resized()
  40078. {
  40079. updateAllItemPositions (false);
  40080. }
  40081. void Toolbar::updateAllItemPositions (const bool animate)
  40082. {
  40083. if (getWidth() > 0 && getHeight() > 0)
  40084. {
  40085. StretchableObjectResizer resizer;
  40086. int i;
  40087. for (i = 0; i < items.size(); ++i)
  40088. {
  40089. ToolbarItemComponent* const tc = items.getUnchecked(i);
  40090. tc->setEditingMode (isEditingActive ? ToolbarItemComponent::editableOnToolbar
  40091. : ToolbarItemComponent::normalMode);
  40092. tc->setStyle (toolbarStyle);
  40093. ToolbarSpacerComp* const spacer = dynamic_cast <ToolbarSpacerComp*> (tc);
  40094. int preferredSize = 1, minSize = 1, maxSize = 1;
  40095. if (tc->getToolbarItemSizes (getThickness(), isVertical(),
  40096. preferredSize, minSize, maxSize))
  40097. {
  40098. tc->isActive = true;
  40099. resizer.addItem (preferredSize, minSize, maxSize,
  40100. spacer != 0 ? spacer->getResizeOrder() : 2);
  40101. }
  40102. else
  40103. {
  40104. tc->isActive = false;
  40105. tc->setVisible (false);
  40106. }
  40107. }
  40108. resizer.resizeToFit (getLength());
  40109. int totalLength = 0;
  40110. for (i = 0; i < resizer.getNumItems(); ++i)
  40111. totalLength += (int) resizer.getItemSize (i);
  40112. const bool itemsOffTheEnd = totalLength > getLength();
  40113. const int extrasButtonSize = getThickness() / 2;
  40114. missingItemsButton->setSize (extrasButtonSize, extrasButtonSize);
  40115. missingItemsButton->setVisible (itemsOffTheEnd);
  40116. missingItemsButton->setEnabled (! isEditingActive);
  40117. if (vertical)
  40118. missingItemsButton->setCentrePosition (getWidth() / 2,
  40119. getHeight() - 4 - extrasButtonSize / 2);
  40120. else
  40121. missingItemsButton->setCentrePosition (getWidth() - 4 - extrasButtonSize / 2,
  40122. getHeight() / 2);
  40123. const int maxLength = itemsOffTheEnd ? (vertical ? missingItemsButton->getY()
  40124. : missingItemsButton->getX()) - 4
  40125. : getLength();
  40126. int pos = 0, activeIndex = 0;
  40127. for (i = 0; i < items.size(); ++i)
  40128. {
  40129. ToolbarItemComponent* const tc = items.getUnchecked(i);
  40130. if (tc->isActive)
  40131. {
  40132. const int size = (int) resizer.getItemSize (activeIndex++);
  40133. Rectangle newBounds;
  40134. if (vertical)
  40135. newBounds.setBounds (0, pos, getWidth(), size);
  40136. else
  40137. newBounds.setBounds (pos, 0, size, getHeight());
  40138. if (animate)
  40139. {
  40140. animator.animateComponent (tc, newBounds, 200, 3.0, 0.0);
  40141. }
  40142. else
  40143. {
  40144. animator.cancelAnimation (tc, false);
  40145. tc->setBounds (newBounds);
  40146. }
  40147. pos += size;
  40148. tc->setVisible (pos <= maxLength
  40149. && ((! tc->isBeingDragged)
  40150. || tc->getEditingMode() == ToolbarItemComponent::editableOnPalette));
  40151. }
  40152. }
  40153. }
  40154. }
  40155. void Toolbar::buttonClicked (Button*)
  40156. {
  40157. jassert (missingItemsButton->isShowing());
  40158. if (missingItemsButton->isShowing())
  40159. {
  40160. PopupMenu m;
  40161. m.addCustomItem (1, new MissingItemsComponent (*this, getThickness()));
  40162. m.showAt (missingItemsButton);
  40163. }
  40164. }
  40165. bool Toolbar::isInterestedInDragSource (const String& sourceDescription,
  40166. Component* /*sourceComponent*/)
  40167. {
  40168. return sourceDescription == toolbarDragDescriptor && isEditingActive;
  40169. }
  40170. void Toolbar::itemDragMove (const String&, Component* sourceComponent, int x, int y)
  40171. {
  40172. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  40173. if (tc != 0)
  40174. {
  40175. if (getNumItems() == 0)
  40176. {
  40177. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  40178. {
  40179. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  40180. if (palette != 0)
  40181. palette->replaceComponent (tc);
  40182. }
  40183. else
  40184. {
  40185. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  40186. }
  40187. items.add (tc);
  40188. addChildComponent (tc);
  40189. updateAllItemPositions (false);
  40190. }
  40191. else
  40192. {
  40193. for (int i = getNumItems(); --i >= 0;)
  40194. {
  40195. int currentIndex = getIndexOfChildComponent (tc);
  40196. if (currentIndex < 0)
  40197. {
  40198. if (tc->getEditingMode() == ToolbarItemComponent::editableOnPalette)
  40199. {
  40200. ToolbarItemPalette* const palette = tc->findParentComponentOfClass ((ToolbarItemPalette*) 0);
  40201. if (palette != 0)
  40202. palette->replaceComponent (tc);
  40203. }
  40204. else
  40205. {
  40206. jassert (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar);
  40207. }
  40208. items.add (tc);
  40209. addChildComponent (tc);
  40210. currentIndex = getIndexOfChildComponent (tc);
  40211. updateAllItemPositions (true);
  40212. }
  40213. int newIndex = currentIndex;
  40214. const int dragObjectLeft = vertical ? (y - tc->dragOffsetY) : (x - tc->dragOffsetX);
  40215. const int dragObjectRight = dragObjectLeft + (vertical ? tc->getHeight() : tc->getWidth());
  40216. const Rectangle current (animator.getComponentDestination (getChildComponent (newIndex)));
  40217. ToolbarItemComponent* const prev = getNextActiveComponent (newIndex, -1);
  40218. if (prev != 0)
  40219. {
  40220. const Rectangle previousPos (animator.getComponentDestination (prev));
  40221. if (abs (dragObjectLeft - (vertical ? previousPos.getY() : previousPos.getX())
  40222. < abs (dragObjectRight - (vertical ? current.getBottom() : current.getRight()))))
  40223. {
  40224. newIndex = getIndexOfChildComponent (prev);
  40225. }
  40226. }
  40227. ToolbarItemComponent* const next = getNextActiveComponent (newIndex, 1);
  40228. if (next != 0)
  40229. {
  40230. const Rectangle nextPos (animator.getComponentDestination (next));
  40231. if (abs (dragObjectLeft - (vertical ? current.getY() : current.getX())
  40232. > abs (dragObjectRight - (vertical ? nextPos.getBottom() : nextPos.getRight()))))
  40233. {
  40234. newIndex = getIndexOfChildComponent (next) + 1;
  40235. }
  40236. }
  40237. if (newIndex != currentIndex)
  40238. {
  40239. items.removeValue (tc);
  40240. removeChildComponent (tc);
  40241. addChildComponent (tc, newIndex);
  40242. items.insert (newIndex, tc);
  40243. updateAllItemPositions (true);
  40244. }
  40245. else
  40246. {
  40247. break;
  40248. }
  40249. }
  40250. }
  40251. }
  40252. }
  40253. void Toolbar::itemDragExit (const String&, Component* sourceComponent)
  40254. {
  40255. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (sourceComponent);
  40256. if (tc != 0)
  40257. {
  40258. if (isParentOf (tc))
  40259. {
  40260. items.removeValue (tc);
  40261. removeChildComponent (tc);
  40262. updateAllItemPositions (true);
  40263. }
  40264. }
  40265. }
  40266. void Toolbar::itemDropped (const String&, Component*, int, int)
  40267. {
  40268. }
  40269. void Toolbar::mouseDown (const MouseEvent& e)
  40270. {
  40271. if (e.mods.isPopupMenu())
  40272. {
  40273. }
  40274. }
  40275. class ToolbarCustomisationDialog : public DialogWindow
  40276. {
  40277. public:
  40278. ToolbarCustomisationDialog (ToolbarItemFactory& factory,
  40279. Toolbar* const toolbar_,
  40280. const int optionFlags)
  40281. : DialogWindow (TRANS("Add/remove items from toolbar"), Colours::white, true, true),
  40282. toolbar (toolbar_)
  40283. {
  40284. setContentComponent (new CustomiserPanel (factory, toolbar, optionFlags), true, true);
  40285. setResizable (true, true);
  40286. setResizeLimits (400, 300, 1500, 1000);
  40287. positionNearBar();
  40288. }
  40289. ~ToolbarCustomisationDialog()
  40290. {
  40291. setContentComponent (0, true);
  40292. }
  40293. void closeButtonPressed()
  40294. {
  40295. setVisible (false);
  40296. }
  40297. bool canModalEventBeSentToComponent (const Component* comp)
  40298. {
  40299. return toolbar->isParentOf (comp);
  40300. }
  40301. void positionNearBar()
  40302. {
  40303. const Rectangle screenSize (toolbar->getParentMonitorArea());
  40304. const int tbx = toolbar->getScreenX();
  40305. const int tby = toolbar->getScreenY();
  40306. const int gap = 8;
  40307. int x, y;
  40308. if (toolbar->isVertical())
  40309. {
  40310. y = tby;
  40311. if (tbx > screenSize.getCentreX())
  40312. x = tbx - getWidth() - gap;
  40313. else
  40314. x = tbx + toolbar->getWidth() + gap;
  40315. }
  40316. else
  40317. {
  40318. x = tbx + (toolbar->getWidth() - getWidth()) / 2;
  40319. if (tby > screenSize.getCentreY())
  40320. y = tby - getHeight() - gap;
  40321. else
  40322. y = tby + toolbar->getHeight() + gap;
  40323. }
  40324. setTopLeftPosition (x, y);
  40325. }
  40326. private:
  40327. Toolbar* const toolbar;
  40328. class CustomiserPanel : public Component,
  40329. private ComboBoxListener,
  40330. private ButtonListener
  40331. {
  40332. public:
  40333. CustomiserPanel (ToolbarItemFactory& factory_,
  40334. Toolbar* const toolbar_,
  40335. const int optionFlags)
  40336. : factory (factory_),
  40337. toolbar (toolbar_),
  40338. styleBox (0),
  40339. defaultButton (0)
  40340. {
  40341. addAndMakeVisible (palette = new ToolbarItemPalette (factory, toolbar));
  40342. if ((optionFlags & (Toolbar::allowIconsOnlyChoice
  40343. | Toolbar::allowIconsWithTextChoice
  40344. | Toolbar::allowTextOnlyChoice)) != 0)
  40345. {
  40346. addAndMakeVisible (styleBox = new ComboBox (String::empty));
  40347. styleBox->setEditableText (false);
  40348. if ((optionFlags & Toolbar::allowIconsOnlyChoice) != 0)
  40349. styleBox->addItem (TRANS("Show icons only"), 1);
  40350. if ((optionFlags & Toolbar::allowIconsWithTextChoice) != 0)
  40351. styleBox->addItem (TRANS("Show icons and descriptions"), 2);
  40352. if ((optionFlags & Toolbar::allowTextOnlyChoice) != 0)
  40353. styleBox->addItem (TRANS("Show descriptions only"), 3);
  40354. if (toolbar_->getStyle() == Toolbar::iconsOnly)
  40355. styleBox->setSelectedId (1);
  40356. else if (toolbar_->getStyle() == Toolbar::iconsWithText)
  40357. styleBox->setSelectedId (2);
  40358. else if (toolbar_->getStyle() == Toolbar::textOnly)
  40359. styleBox->setSelectedId (3);
  40360. styleBox->addListener (this);
  40361. }
  40362. if ((optionFlags & Toolbar::showResetToDefaultsButton) != 0)
  40363. {
  40364. addAndMakeVisible (defaultButton = new TextButton (TRANS ("Restore to default set of items")));
  40365. defaultButton->addButtonListener (this);
  40366. }
  40367. addAndMakeVisible (instructions = new Label (String::empty,
  40368. 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.")));
  40369. instructions->setFont (Font (13.0f));
  40370. setSize (500, 300);
  40371. }
  40372. ~CustomiserPanel()
  40373. {
  40374. deleteAllChildren();
  40375. }
  40376. void comboBoxChanged (ComboBox*)
  40377. {
  40378. if (styleBox->getSelectedId() == 1)
  40379. toolbar->setStyle (Toolbar::iconsOnly);
  40380. else if (styleBox->getSelectedId() == 2)
  40381. toolbar->setStyle (Toolbar::iconsWithText);
  40382. else if (styleBox->getSelectedId() == 3)
  40383. toolbar->setStyle (Toolbar::textOnly);
  40384. palette->resized(); // to make it update the styles
  40385. }
  40386. void buttonClicked (Button*)
  40387. {
  40388. toolbar->addDefaultItems (factory);
  40389. }
  40390. void paint (Graphics& g)
  40391. {
  40392. Colour background;
  40393. DialogWindow* const dw = findParentComponentOfClass ((DialogWindow*) 0);
  40394. if (dw != 0)
  40395. background = dw->getBackgroundColour();
  40396. g.setColour (background.contrasting().withAlpha (0.3f));
  40397. g.fillRect (palette->getX(), palette->getBottom() - 1, palette->getWidth(), 1);
  40398. }
  40399. void resized()
  40400. {
  40401. palette->setBounds (0, 0, getWidth(), getHeight() - 120);
  40402. if (styleBox != 0)
  40403. styleBox->setBounds (10, getHeight() - 110, 200, 22);
  40404. if (defaultButton != 0)
  40405. {
  40406. defaultButton->changeWidthToFitText (22);
  40407. defaultButton->setTopLeftPosition (240, getHeight() - 110);
  40408. }
  40409. instructions->setBounds (10, getHeight() - 80, getWidth() - 20, 80);
  40410. }
  40411. private:
  40412. ToolbarItemFactory& factory;
  40413. Toolbar* const toolbar;
  40414. Label* instructions;
  40415. ToolbarItemPalette* palette;
  40416. ComboBox* styleBox;
  40417. TextButton* defaultButton;
  40418. };
  40419. };
  40420. void Toolbar::showCustomisationDialog (ToolbarItemFactory& factory, const int optionFlags)
  40421. {
  40422. setEditingActive (true);
  40423. ToolbarCustomisationDialog dw (factory, this, optionFlags);
  40424. dw.runModalLoop();
  40425. jassert (isValidComponent()); // ? deleting the toolbar while it's being edited?
  40426. setEditingActive (false);
  40427. }
  40428. END_JUCE_NAMESPACE
  40429. /********* End of inlined file: juce_Toolbar.cpp *********/
  40430. /********* Start of inlined file: juce_ToolbarItemComponent.cpp *********/
  40431. BEGIN_JUCE_NAMESPACE
  40432. ToolbarItemFactory::ToolbarItemFactory()
  40433. {
  40434. }
  40435. ToolbarItemFactory::~ToolbarItemFactory()
  40436. {
  40437. }
  40438. class ItemDragAndDropOverlayComponent : public Component
  40439. {
  40440. public:
  40441. ItemDragAndDropOverlayComponent()
  40442. : isDragging (false)
  40443. {
  40444. setAlwaysOnTop (true);
  40445. setRepaintsOnMouseActivity (true);
  40446. setMouseCursor (MouseCursor::DraggingHandCursor);
  40447. }
  40448. ~ItemDragAndDropOverlayComponent()
  40449. {
  40450. }
  40451. void paint (Graphics& g)
  40452. {
  40453. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  40454. if (isMouseOverOrDragging()
  40455. && tc != 0
  40456. && tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  40457. {
  40458. g.setColour (findColour (Toolbar::editingModeOutlineColourId, true));
  40459. g.drawRect (0, 0, getWidth(), getHeight(),
  40460. jmin (2, (getWidth() - 1) / 2, (getHeight() - 1) / 2));
  40461. }
  40462. }
  40463. void mouseDown (const MouseEvent& e)
  40464. {
  40465. isDragging = false;
  40466. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  40467. if (tc != 0)
  40468. {
  40469. tc->dragOffsetX = e.x;
  40470. tc->dragOffsetY = e.y;
  40471. }
  40472. }
  40473. void mouseDrag (const MouseEvent& e)
  40474. {
  40475. if (! (isDragging || e.mouseWasClicked()))
  40476. {
  40477. isDragging = true;
  40478. DragAndDropContainer* const dnd = DragAndDropContainer::findParentDragContainerFor (this);
  40479. if (dnd != 0)
  40480. {
  40481. dnd->startDragging (Toolbar::toolbarDragDescriptor, getParentComponent(), 0, true);
  40482. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  40483. if (tc != 0)
  40484. {
  40485. tc->isBeingDragged = true;
  40486. if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  40487. tc->setVisible (false);
  40488. }
  40489. }
  40490. }
  40491. }
  40492. void mouseUp (const MouseEvent&)
  40493. {
  40494. isDragging = false;
  40495. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (getParentComponent());
  40496. if (tc != 0)
  40497. {
  40498. tc->isBeingDragged = false;
  40499. Toolbar* const tb = tc->getToolbar();
  40500. if (tb != 0)
  40501. tb->updateAllItemPositions (true);
  40502. else if (tc->getEditingMode() == ToolbarItemComponent::editableOnToolbar)
  40503. delete tc;
  40504. }
  40505. }
  40506. void parentSizeChanged()
  40507. {
  40508. setBounds (0, 0, getParentWidth(), getParentHeight());
  40509. }
  40510. juce_UseDebuggingNewOperator
  40511. private:
  40512. bool isDragging;
  40513. ItemDragAndDropOverlayComponent (const ItemDragAndDropOverlayComponent&);
  40514. const ItemDragAndDropOverlayComponent& operator= (const ItemDragAndDropOverlayComponent&);
  40515. };
  40516. ToolbarItemComponent::ToolbarItemComponent (const int itemId_,
  40517. const String& labelText,
  40518. const bool isBeingUsedAsAButton_)
  40519. : Button (labelText),
  40520. itemId (itemId_),
  40521. mode (normalMode),
  40522. toolbarStyle (Toolbar::iconsOnly),
  40523. overlayComp (0),
  40524. dragOffsetX (0),
  40525. dragOffsetY (0),
  40526. isActive (true),
  40527. isBeingDragged (false),
  40528. isBeingUsedAsAButton (isBeingUsedAsAButton_)
  40529. {
  40530. // Your item ID can't be 0!
  40531. jassert (itemId_ != 0);
  40532. }
  40533. ToolbarItemComponent::~ToolbarItemComponent()
  40534. {
  40535. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  40536. delete overlayComp;
  40537. }
  40538. Toolbar* ToolbarItemComponent::getToolbar() const
  40539. {
  40540. return dynamic_cast <Toolbar*> (getParentComponent());
  40541. }
  40542. bool ToolbarItemComponent::isToolbarVertical() const
  40543. {
  40544. const Toolbar* const t = getToolbar();
  40545. return t != 0 && t->isVertical();
  40546. }
  40547. void ToolbarItemComponent::setStyle (const Toolbar::ToolbarItemStyle& newStyle)
  40548. {
  40549. if (toolbarStyle != newStyle)
  40550. {
  40551. toolbarStyle = newStyle;
  40552. repaint();
  40553. resized();
  40554. }
  40555. }
  40556. void ToolbarItemComponent::paintButton (Graphics& g, bool isMouseOver, bool isMouseDown)
  40557. {
  40558. if (isBeingUsedAsAButton)
  40559. getLookAndFeel().paintToolbarButtonBackground (g, getWidth(), getHeight(),
  40560. isMouseOver, isMouseDown, *this);
  40561. if (toolbarStyle != Toolbar::iconsOnly)
  40562. {
  40563. const int indent = contentArea.getX();
  40564. int y = indent;
  40565. int h = getHeight() - indent * 2;
  40566. if (toolbarStyle == Toolbar::iconsWithText)
  40567. {
  40568. y = contentArea.getBottom() + indent / 2;
  40569. h -= contentArea.getHeight();
  40570. }
  40571. getLookAndFeel().paintToolbarButtonLabel (g, indent, y, getWidth() - indent * 2, h,
  40572. getButtonText(), *this);
  40573. }
  40574. if (! contentArea.isEmpty())
  40575. {
  40576. g.saveState();
  40577. g.setOrigin (contentArea.getX(), contentArea.getY());
  40578. g.reduceClipRegion (0, 0, contentArea.getWidth(), contentArea.getHeight());
  40579. paintButtonArea (g, contentArea.getWidth(), contentArea.getHeight(), isMouseOver, isMouseDown);
  40580. g.restoreState();
  40581. }
  40582. }
  40583. void ToolbarItemComponent::resized()
  40584. {
  40585. if (toolbarStyle != Toolbar::textOnly)
  40586. {
  40587. const int indent = jmin (proportionOfWidth (0.08f),
  40588. proportionOfHeight (0.08f));
  40589. contentArea = Rectangle (indent, indent,
  40590. getWidth() - indent * 2,
  40591. toolbarStyle == Toolbar::iconsWithText ? proportionOfHeight (0.55f)
  40592. : (getHeight() - indent * 2));
  40593. }
  40594. else
  40595. {
  40596. contentArea = Rectangle();
  40597. }
  40598. contentAreaChanged (contentArea);
  40599. }
  40600. void ToolbarItemComponent::setEditingMode (const ToolbarEditingMode newMode)
  40601. {
  40602. if (mode != newMode)
  40603. {
  40604. mode = newMode;
  40605. repaint();
  40606. if (mode == normalMode)
  40607. {
  40608. jassert (overlayComp == 0 || overlayComp->isValidComponent());
  40609. delete overlayComp;
  40610. overlayComp = 0;
  40611. }
  40612. else if (overlayComp == 0)
  40613. {
  40614. addAndMakeVisible (overlayComp = new ItemDragAndDropOverlayComponent());
  40615. overlayComp->parentSizeChanged();
  40616. }
  40617. resized();
  40618. }
  40619. }
  40620. END_JUCE_NAMESPACE
  40621. /********* End of inlined file: juce_ToolbarItemComponent.cpp *********/
  40622. /********* Start of inlined file: juce_ToolbarItemPalette.cpp *********/
  40623. BEGIN_JUCE_NAMESPACE
  40624. ToolbarItemPalette::ToolbarItemPalette (ToolbarItemFactory& factory_,
  40625. Toolbar* const toolbar_)
  40626. : factory (factory_),
  40627. toolbar (toolbar_)
  40628. {
  40629. Component* const itemHolder = new Component();
  40630. Array <int> allIds;
  40631. factory_.getAllToolbarItemIds (allIds);
  40632. for (int i = 0; i < allIds.size(); ++i)
  40633. {
  40634. ToolbarItemComponent* const tc = Toolbar::createItem (factory_, allIds.getUnchecked (i));
  40635. jassert (tc != 0);
  40636. if (tc != 0)
  40637. {
  40638. itemHolder->addAndMakeVisible (tc);
  40639. tc->setEditingMode (ToolbarItemComponent::editableOnPalette);
  40640. }
  40641. }
  40642. viewport = new Viewport();
  40643. viewport->setViewedComponent (itemHolder);
  40644. addAndMakeVisible (viewport);
  40645. }
  40646. ToolbarItemPalette::~ToolbarItemPalette()
  40647. {
  40648. viewport->getViewedComponent()->deleteAllChildren();
  40649. deleteAllChildren();
  40650. }
  40651. void ToolbarItemPalette::resized()
  40652. {
  40653. viewport->setBoundsInset (BorderSize (1));
  40654. Component* const itemHolder = viewport->getViewedComponent();
  40655. const int indent = 8;
  40656. const int preferredWidth = viewport->getWidth() - viewport->getScrollBarThickness() - indent;
  40657. const int height = toolbar->getThickness();
  40658. int x = indent;
  40659. int y = indent;
  40660. int maxX = 0;
  40661. for (int i = 0; i < itemHolder->getNumChildComponents(); ++i)
  40662. {
  40663. ToolbarItemComponent* const tc = dynamic_cast <ToolbarItemComponent*> (itemHolder->getChildComponent (i));
  40664. if (tc != 0)
  40665. {
  40666. tc->setStyle (toolbar->getStyle());
  40667. int preferredSize = 1, minSize = 1, maxSize = 1;
  40668. if (tc->getToolbarItemSizes (height, false, preferredSize, minSize, maxSize))
  40669. {
  40670. if (x + preferredSize > preferredWidth && x > indent)
  40671. {
  40672. x = indent;
  40673. y += height;
  40674. }
  40675. tc->setBounds (x, y, preferredSize, height);
  40676. x += preferredSize + 8;
  40677. maxX = jmax (maxX, x);
  40678. }
  40679. }
  40680. }
  40681. itemHolder->setSize (maxX, y + height + 8);
  40682. }
  40683. void ToolbarItemPalette::replaceComponent (ToolbarItemComponent* const comp)
  40684. {
  40685. ToolbarItemComponent* const tc = Toolbar::createItem (factory, comp->getItemId());
  40686. jassert (tc != 0);
  40687. if (tc != 0)
  40688. {
  40689. tc->setBounds (comp->getBounds());
  40690. tc->setStyle (toolbar->getStyle());
  40691. tc->setEditingMode (comp->getEditingMode());
  40692. viewport->getViewedComponent()->addAndMakeVisible (tc, getIndexOfChildComponent (comp));
  40693. }
  40694. }
  40695. END_JUCE_NAMESPACE
  40696. /********* End of inlined file: juce_ToolbarItemPalette.cpp *********/
  40697. /********* Start of inlined file: juce_TreeView.cpp *********/
  40698. BEGIN_JUCE_NAMESPACE
  40699. class TreeViewContentComponent : public Component
  40700. {
  40701. public:
  40702. TreeViewContentComponent (TreeView* const owner_)
  40703. : owner (owner_),
  40704. isDragging (false)
  40705. {
  40706. }
  40707. ~TreeViewContentComponent()
  40708. {
  40709. deleteAllChildren();
  40710. }
  40711. void mouseDown (const MouseEvent& e)
  40712. {
  40713. isDragging = false;
  40714. needSelectionOnMouseUp = false;
  40715. Rectangle pos;
  40716. TreeViewItem* const item = findItemAt (e.y, pos);
  40717. if (item != 0 && e.x >= pos.getX())
  40718. {
  40719. if (! owner->isMultiSelectEnabled())
  40720. item->setSelected (true, true);
  40721. else if (item->isSelected())
  40722. needSelectionOnMouseUp = ! e.mods.isPopupMenu();
  40723. else
  40724. selectBasedOnModifiers (item, e.mods);
  40725. MouseEvent e2 (e);
  40726. e2.x -= pos.getX();
  40727. e2.y -= pos.getY();
  40728. item->itemClicked (e2);
  40729. }
  40730. }
  40731. void mouseUp (const MouseEvent& e)
  40732. {
  40733. Rectangle pos;
  40734. TreeViewItem* const item = findItemAt (e.y, pos);
  40735. if (item != 0 && e.mouseWasClicked())
  40736. {
  40737. if (needSelectionOnMouseUp)
  40738. {
  40739. selectBasedOnModifiers (item, e.mods);
  40740. }
  40741. else if (e.mouseWasClicked())
  40742. {
  40743. if (e.x >= pos.getX() - owner->getIndentSize()
  40744. && e.x < pos.getX())
  40745. {
  40746. item->setOpen (! item->isOpen());
  40747. }
  40748. }
  40749. }
  40750. }
  40751. void mouseDoubleClick (const MouseEvent& e)
  40752. {
  40753. if (e.getNumberOfClicks() != 3) // ignore triple clicks
  40754. {
  40755. Rectangle pos;
  40756. TreeViewItem* const item = findItemAt (e.y, pos);
  40757. if (item != 0 && e.x >= pos.getX())
  40758. {
  40759. MouseEvent e2 (e);
  40760. e2.x -= pos.getX();
  40761. e2.y -= pos.getY();
  40762. item->itemDoubleClicked (e2);
  40763. }
  40764. }
  40765. }
  40766. void mouseDrag (const MouseEvent& e)
  40767. {
  40768. if (isEnabled() && ! (e.mouseWasClicked() || isDragging))
  40769. {
  40770. isDragging = true;
  40771. Rectangle pos;
  40772. TreeViewItem* const item = findItemAt (e.getMouseDownY(), pos);
  40773. if (item != 0 && e.getMouseDownX() >= pos.getX())
  40774. {
  40775. const String dragDescription (item->getDragSourceDescription());
  40776. if (dragDescription.isNotEmpty())
  40777. {
  40778. DragAndDropContainer* const dragContainer
  40779. = DragAndDropContainer::findParentDragContainerFor (this);
  40780. if (dragContainer != 0)
  40781. {
  40782. pos.setSize (pos.getWidth(), item->itemHeight);
  40783. Image* dragImage = Component::createComponentSnapshot (pos, true);
  40784. dragImage->multiplyAllAlphas (0.6f);
  40785. dragContainer->startDragging (dragDescription, owner, dragImage, true);
  40786. }
  40787. else
  40788. {
  40789. // to be able to do a drag-and-drop operation, the treeview needs to
  40790. // be inside a component which is also a DragAndDropContainer.
  40791. jassertfalse
  40792. }
  40793. }
  40794. }
  40795. }
  40796. }
  40797. void paint (Graphics& g);
  40798. TreeViewItem* findItemAt (int y, Rectangle& itemPosition) const;
  40799. void updateComponents()
  40800. {
  40801. int xAdjust = 0, yAdjust = 0;
  40802. if ((! owner->rootItemVisible) && owner->rootItem != 0)
  40803. {
  40804. yAdjust = owner->rootItem->itemHeight;
  40805. xAdjust = owner->getIndentSize();
  40806. }
  40807. const int visibleTop = -getY();
  40808. const int visibleBottom = visibleTop + getParentHeight();
  40809. BitArray itemsToKeep;
  40810. TreeViewItem* item = owner->rootItem;
  40811. int y = -yAdjust;
  40812. while (item != 0 && y < visibleBottom)
  40813. {
  40814. y += item->itemHeight;
  40815. if (y >= visibleTop)
  40816. {
  40817. const int index = rowComponentIds.indexOf (item->uid);
  40818. if (index < 0)
  40819. {
  40820. Component* const comp = item->createItemComponent();
  40821. if (comp != 0)
  40822. {
  40823. addAndMakeVisible (comp);
  40824. itemsToKeep.setBit (rowComponentItems.size());
  40825. rowComponentItems.add (item);
  40826. rowComponentIds.add (item->uid);
  40827. rowComponents.add (comp);
  40828. }
  40829. }
  40830. else
  40831. {
  40832. itemsToKeep.setBit (index);
  40833. }
  40834. }
  40835. item = item->getNextVisibleItem (true);
  40836. }
  40837. for (int i = rowComponentItems.size(); --i >= 0;)
  40838. {
  40839. Component* const comp = (Component*) (rowComponents.getUnchecked(i));
  40840. bool keep = false;
  40841. if ((itemsToKeep[i] || (comp == Component::getComponentUnderMouse() && comp->isMouseButtonDown()))
  40842. && isParentOf (comp))
  40843. {
  40844. if (itemsToKeep[i])
  40845. {
  40846. const TreeViewItem* const item = (TreeViewItem*) rowComponentItems.getUnchecked(i);
  40847. Rectangle pos (item->getItemPosition (false));
  40848. pos.translate (-xAdjust, -yAdjust);
  40849. pos.setSize (pos.getWidth() + xAdjust, item->itemHeight);
  40850. if (pos.getBottom() >= visibleTop && pos.getY() < visibleBottom)
  40851. {
  40852. keep = true;
  40853. comp->setBounds (pos);
  40854. }
  40855. }
  40856. else
  40857. {
  40858. comp->setSize (0, 0);
  40859. }
  40860. }
  40861. if (! keep)
  40862. {
  40863. delete comp;
  40864. rowComponents.remove (i);
  40865. rowComponentIds.remove (i);
  40866. rowComponentItems.remove (i);
  40867. }
  40868. }
  40869. }
  40870. void resized()
  40871. {
  40872. owner->itemsChanged();
  40873. }
  40874. juce_UseDebuggingNewOperator
  40875. private:
  40876. TreeView* const owner;
  40877. VoidArray rowComponentItems;
  40878. Array <int> rowComponentIds;
  40879. VoidArray rowComponents;
  40880. bool isDragging, needSelectionOnMouseUp;
  40881. TreeViewContentComponent (const TreeViewContentComponent&);
  40882. const TreeViewContentComponent& operator= (const TreeViewContentComponent&);
  40883. void selectBasedOnModifiers (TreeViewItem* const item, const ModifierKeys& modifiers)
  40884. {
  40885. TreeViewItem* firstSelected = 0;
  40886. if (modifiers.isShiftDown() && ((firstSelected = owner->getSelectedItem (0)) != 0))
  40887. {
  40888. TreeViewItem* const lastSelected = owner->getSelectedItem (owner->getNumSelectedItems() - 1);
  40889. jassert (lastSelected != 0);
  40890. int rowStart = firstSelected->getRowNumberInTree();
  40891. int rowEnd = lastSelected->getRowNumberInTree();
  40892. if (rowStart > rowEnd)
  40893. swapVariables (rowStart, rowEnd);
  40894. int ourRow = item->getRowNumberInTree();
  40895. int otherEnd = ourRow < rowEnd ? rowStart : rowEnd;
  40896. if (ourRow > otherEnd)
  40897. swapVariables (ourRow, otherEnd);
  40898. for (int i = ourRow; i <= otherEnd; ++i)
  40899. owner->getItemOnRow (i)->setSelected (true, false);
  40900. }
  40901. else
  40902. {
  40903. const bool cmd = modifiers.isCommandDown();
  40904. item->setSelected ((! cmd) || (! item->isSelected()), ! cmd);
  40905. }
  40906. }
  40907. };
  40908. class TreeViewport : public Viewport
  40909. {
  40910. public:
  40911. TreeViewport() throw() {}
  40912. ~TreeViewport() throw() {}
  40913. void updateComponents()
  40914. {
  40915. if (getViewedComponent() != 0)
  40916. ((TreeViewContentComponent*) getViewedComponent())->updateComponents();
  40917. repaint();
  40918. }
  40919. void visibleAreaChanged (int, int, int, int)
  40920. {
  40921. updateComponents();
  40922. }
  40923. juce_UseDebuggingNewOperator
  40924. private:
  40925. TreeViewport (const TreeViewport&);
  40926. const TreeViewport& operator= (const TreeViewport&);
  40927. };
  40928. TreeView::TreeView (const String& componentName)
  40929. : Component (componentName),
  40930. rootItem (0),
  40931. indentSize (24),
  40932. defaultOpenness (false),
  40933. needsRecalculating (true),
  40934. rootItemVisible (true),
  40935. multiSelectEnabled (false)
  40936. {
  40937. addAndMakeVisible (viewport = new TreeViewport());
  40938. viewport->setViewedComponent (new TreeViewContentComponent (this));
  40939. viewport->setWantsKeyboardFocus (false);
  40940. setWantsKeyboardFocus (true);
  40941. }
  40942. TreeView::~TreeView()
  40943. {
  40944. if (rootItem != 0)
  40945. rootItem->setOwnerView (0);
  40946. deleteAllChildren();
  40947. }
  40948. void TreeView::setRootItem (TreeViewItem* const newRootItem)
  40949. {
  40950. if (rootItem != newRootItem)
  40951. {
  40952. if (newRootItem != 0)
  40953. {
  40954. jassert (newRootItem->ownerView == 0); // can't use a tree item in more than one tree at once..
  40955. if (newRootItem->ownerView != 0)
  40956. newRootItem->ownerView->setRootItem (0);
  40957. }
  40958. if (rootItem != 0)
  40959. rootItem->setOwnerView (0);
  40960. rootItem = newRootItem;
  40961. if (newRootItem != 0)
  40962. newRootItem->setOwnerView (this);
  40963. needsRecalculating = true;
  40964. handleAsyncUpdate();
  40965. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  40966. {
  40967. rootItem->setOpen (false); // force a re-open
  40968. rootItem->setOpen (true);
  40969. }
  40970. }
  40971. }
  40972. void TreeView::setRootItemVisible (const bool shouldBeVisible)
  40973. {
  40974. rootItemVisible = shouldBeVisible;
  40975. if (rootItem != 0 && (defaultOpenness || ! rootItemVisible))
  40976. {
  40977. rootItem->setOpen (false); // force a re-open
  40978. rootItem->setOpen (true);
  40979. }
  40980. itemsChanged();
  40981. }
  40982. void TreeView::colourChanged()
  40983. {
  40984. setOpaque (findColour (backgroundColourId).isOpaque());
  40985. repaint();
  40986. }
  40987. void TreeView::setIndentSize (const int newIndentSize)
  40988. {
  40989. if (indentSize != newIndentSize)
  40990. {
  40991. indentSize = newIndentSize;
  40992. resized();
  40993. }
  40994. }
  40995. void TreeView::setDefaultOpenness (const bool isOpenByDefault)
  40996. {
  40997. if (defaultOpenness != isOpenByDefault)
  40998. {
  40999. defaultOpenness = isOpenByDefault;
  41000. itemsChanged();
  41001. }
  41002. }
  41003. void TreeView::setMultiSelectEnabled (const bool canMultiSelect)
  41004. {
  41005. multiSelectEnabled = canMultiSelect;
  41006. }
  41007. void TreeView::clearSelectedItems()
  41008. {
  41009. if (rootItem != 0)
  41010. rootItem->deselectAllRecursively();
  41011. }
  41012. int TreeView::getNumSelectedItems() const throw()
  41013. {
  41014. return (rootItem != 0) ? rootItem->countSelectedItemsRecursively() : 0;
  41015. }
  41016. TreeViewItem* TreeView::getSelectedItem (const int index) const throw()
  41017. {
  41018. return (rootItem != 0) ? rootItem->getSelectedItemWithIndex (index) : 0;
  41019. }
  41020. int TreeView::getNumRowsInTree() const
  41021. {
  41022. if (rootItem != 0)
  41023. return rootItem->getNumRows() - (rootItemVisible ? 0 : 1);
  41024. return 0;
  41025. }
  41026. TreeViewItem* TreeView::getItemOnRow (int index) const
  41027. {
  41028. if (! rootItemVisible)
  41029. ++index;
  41030. if (rootItem != 0 && index >= 0)
  41031. return rootItem->getItemOnRow (index);
  41032. return 0;
  41033. }
  41034. XmlElement* TreeView::getOpennessState (const bool alsoIncludeScrollPosition) const
  41035. {
  41036. XmlElement* e = 0;
  41037. if (rootItem != 0)
  41038. {
  41039. e = rootItem->createXmlOpenness();
  41040. if (e != 0 && alsoIncludeScrollPosition)
  41041. e->setAttribute (T("scrollPos"), viewport->getViewPositionY());
  41042. }
  41043. return e;
  41044. }
  41045. void TreeView::restoreOpennessState (const XmlElement& newState)
  41046. {
  41047. if (rootItem != 0)
  41048. {
  41049. rootItem->restoreFromXml (newState);
  41050. if (newState.hasAttribute (T("scrollPos")))
  41051. viewport->setViewPosition (viewport->getViewPositionX(),
  41052. newState.getIntAttribute (T("scrollPos")));
  41053. }
  41054. }
  41055. void TreeView::paint (Graphics& g)
  41056. {
  41057. g.fillAll (findColour (backgroundColourId));
  41058. }
  41059. void TreeView::resized()
  41060. {
  41061. viewport->setBounds (0, 0, getWidth(), getHeight());
  41062. itemsChanged();
  41063. }
  41064. void TreeView::moveSelectedRow (int delta)
  41065. {
  41066. int rowSelected = 0;
  41067. TreeViewItem* const firstSelected = getSelectedItem (0);
  41068. if (firstSelected != 0)
  41069. rowSelected = firstSelected->getRowNumberInTree();
  41070. rowSelected = jlimit (0, getNumRowsInTree() - 1, rowSelected + delta);
  41071. TreeViewItem* item = getItemOnRow (rowSelected);
  41072. if (item != 0)
  41073. {
  41074. item->setSelected (true, true);
  41075. scrollToKeepItemVisible (item);
  41076. }
  41077. }
  41078. void TreeView::scrollToKeepItemVisible (TreeViewItem* item)
  41079. {
  41080. if (item != 0 && item->ownerView == this)
  41081. {
  41082. handleAsyncUpdate();
  41083. item = item->getDeepestOpenParentItem();
  41084. int y = item->y;
  41085. if (! rootItemVisible)
  41086. y -= rootItem->itemHeight;
  41087. int viewTop = viewport->getViewPositionY();
  41088. if (y < viewTop)
  41089. {
  41090. viewport->setViewPosition (viewport->getViewPositionX(), y);
  41091. }
  41092. else if (y + item->itemHeight > viewTop + viewport->getViewHeight())
  41093. {
  41094. viewport->setViewPosition (viewport->getViewPositionX(),
  41095. (y + item->itemHeight) - viewport->getViewHeight());
  41096. }
  41097. }
  41098. }
  41099. bool TreeView::keyPressed (const KeyPress& key)
  41100. {
  41101. if (key.isKeyCode (KeyPress::upKey))
  41102. {
  41103. moveSelectedRow (-1);
  41104. }
  41105. else if (key.isKeyCode (KeyPress::downKey))
  41106. {
  41107. moveSelectedRow (1);
  41108. }
  41109. else if (key.isKeyCode (KeyPress::pageDownKey) || key.isKeyCode (KeyPress::pageUpKey))
  41110. {
  41111. if (rootItem != 0)
  41112. {
  41113. int rowsOnScreen = getHeight() / jmax (1, rootItem->itemHeight);
  41114. if (key.isKeyCode (KeyPress::pageUpKey))
  41115. rowsOnScreen = -rowsOnScreen;
  41116. moveSelectedRow (rowsOnScreen);
  41117. }
  41118. }
  41119. else if (key.isKeyCode (KeyPress::homeKey))
  41120. {
  41121. moveSelectedRow (-0x3fffffff);
  41122. }
  41123. else if (key.isKeyCode (KeyPress::endKey))
  41124. {
  41125. moveSelectedRow (0x3fffffff);
  41126. }
  41127. else if (key.isKeyCode (KeyPress::returnKey))
  41128. {
  41129. TreeViewItem* const firstSelected = getSelectedItem (0);
  41130. if (firstSelected != 0)
  41131. firstSelected->setOpen (! firstSelected->isOpen());
  41132. }
  41133. else if (key.isKeyCode (KeyPress::leftKey))
  41134. {
  41135. TreeViewItem* const firstSelected = getSelectedItem (0);
  41136. if (firstSelected != 0)
  41137. {
  41138. if (firstSelected->isOpen())
  41139. {
  41140. firstSelected->setOpen (false);
  41141. }
  41142. else
  41143. {
  41144. TreeViewItem* parent = firstSelected->parentItem;
  41145. if ((! rootItemVisible) && parent == rootItem)
  41146. parent = 0;
  41147. if (parent != 0)
  41148. {
  41149. parent->setSelected (true, true);
  41150. scrollToKeepItemVisible (parent);
  41151. }
  41152. }
  41153. }
  41154. }
  41155. else if (key.isKeyCode (KeyPress::rightKey))
  41156. {
  41157. TreeViewItem* const firstSelected = getSelectedItem (0);
  41158. if (firstSelected != 0)
  41159. {
  41160. if (firstSelected->isOpen() || ! firstSelected->mightContainSubItems())
  41161. moveSelectedRow (1);
  41162. else
  41163. firstSelected->setOpen (true);
  41164. }
  41165. }
  41166. else
  41167. {
  41168. return false;
  41169. }
  41170. return true;
  41171. }
  41172. void TreeView::itemsChanged() throw()
  41173. {
  41174. needsRecalculating = true;
  41175. repaint();
  41176. triggerAsyncUpdate();
  41177. }
  41178. void TreeView::handleAsyncUpdate()
  41179. {
  41180. if (needsRecalculating)
  41181. {
  41182. needsRecalculating = false;
  41183. const ScopedLock sl (nodeAlterationLock);
  41184. if (rootItem != 0)
  41185. rootItem->updatePositions (0);
  41186. ((TreeViewport*) viewport)->updateComponents();
  41187. if (rootItem != 0)
  41188. {
  41189. viewport->getViewedComponent()
  41190. ->setSize (jmax (viewport->getMaximumVisibleWidth(), rootItem->totalWidth),
  41191. rootItem->totalHeight - (rootItemVisible ? 0 : rootItem->itemHeight));
  41192. }
  41193. else
  41194. {
  41195. viewport->getViewedComponent()->setSize (0, 0);
  41196. }
  41197. }
  41198. }
  41199. void TreeViewContentComponent::paint (Graphics& g)
  41200. {
  41201. if (owner->rootItem != 0)
  41202. {
  41203. owner->handleAsyncUpdate();
  41204. int w = getWidth();
  41205. if (! owner->rootItemVisible)
  41206. {
  41207. const int indentWidth = owner->getIndentSize();
  41208. g.setOrigin (-indentWidth, -owner->rootItem->itemHeight);
  41209. w += indentWidth;
  41210. }
  41211. owner->rootItem->paintRecursively (g, w);
  41212. }
  41213. }
  41214. TreeViewItem* TreeViewContentComponent::findItemAt (int y, Rectangle& itemPosition) const
  41215. {
  41216. if (owner->rootItem != 0)
  41217. {
  41218. owner->handleAsyncUpdate();
  41219. if (! owner->rootItemVisible)
  41220. y += owner->rootItem->itemHeight;
  41221. TreeViewItem* const ti = owner->rootItem->findItemRecursively (y);
  41222. if (ti != 0)
  41223. {
  41224. itemPosition = ti->getItemPosition (false);
  41225. if (! owner->rootItemVisible)
  41226. itemPosition.translate (-owner->getIndentSize(),
  41227. -owner->rootItem->itemHeight);
  41228. }
  41229. return ti;
  41230. }
  41231. return 0;
  41232. }
  41233. #define opennessDefault 0
  41234. #define opennessClosed 1
  41235. #define opennessOpen 2
  41236. TreeViewItem::TreeViewItem()
  41237. : ownerView (0),
  41238. parentItem (0),
  41239. subItems (8),
  41240. y (0),
  41241. itemHeight (0),
  41242. totalHeight (0),
  41243. selected (false),
  41244. redrawNeeded (true),
  41245. drawLinesInside (true),
  41246. openness (opennessDefault)
  41247. {
  41248. static int nextUID = 0;
  41249. uid = nextUID++;
  41250. }
  41251. TreeViewItem::~TreeViewItem()
  41252. {
  41253. }
  41254. const String TreeViewItem::getUniqueName() const
  41255. {
  41256. return String::empty;
  41257. }
  41258. void TreeViewItem::itemOpennessChanged (bool)
  41259. {
  41260. }
  41261. int TreeViewItem::getNumSubItems() const throw()
  41262. {
  41263. return subItems.size();
  41264. }
  41265. TreeViewItem* TreeViewItem::getSubItem (const int index) const throw()
  41266. {
  41267. return subItems [index];
  41268. }
  41269. void TreeViewItem::clearSubItems()
  41270. {
  41271. if (subItems.size() > 0)
  41272. {
  41273. if (ownerView != 0)
  41274. {
  41275. const ScopedLock sl (ownerView->nodeAlterationLock);
  41276. subItems.clear();
  41277. treeHasChanged();
  41278. }
  41279. else
  41280. {
  41281. subItems.clear();
  41282. }
  41283. }
  41284. }
  41285. void TreeViewItem::addSubItem (TreeViewItem* const newItem, const int insertPosition)
  41286. {
  41287. if (newItem != 0)
  41288. {
  41289. newItem->parentItem = this;
  41290. newItem->setOwnerView (ownerView);
  41291. newItem->y = 0;
  41292. newItem->itemHeight = newItem->getItemHeight();
  41293. newItem->totalHeight = 0;
  41294. newItem->itemWidth = newItem->getItemWidth();
  41295. newItem->totalWidth = 0;
  41296. if (ownerView != 0)
  41297. {
  41298. const ScopedLock sl (ownerView->nodeAlterationLock);
  41299. subItems.insert (insertPosition, newItem);
  41300. treeHasChanged();
  41301. if (newItem->isOpen())
  41302. newItem->itemOpennessChanged (true);
  41303. }
  41304. else
  41305. {
  41306. subItems.insert (insertPosition, newItem);
  41307. if (newItem->isOpen())
  41308. newItem->itemOpennessChanged (true);
  41309. }
  41310. }
  41311. }
  41312. void TreeViewItem::removeSubItem (const int index, const bool deleteItem)
  41313. {
  41314. if (ownerView != 0)
  41315. ownerView->nodeAlterationLock.enter();
  41316. if (((unsigned int) index) < (unsigned int) subItems.size())
  41317. {
  41318. subItems.remove (index, deleteItem);
  41319. treeHasChanged();
  41320. }
  41321. if (ownerView != 0)
  41322. ownerView->nodeAlterationLock.exit();
  41323. }
  41324. bool TreeViewItem::isOpen() const throw()
  41325. {
  41326. if (openness == opennessDefault)
  41327. return ownerView != 0 && ownerView->defaultOpenness;
  41328. else
  41329. return openness == opennessOpen;
  41330. }
  41331. void TreeViewItem::setOpen (const bool shouldBeOpen)
  41332. {
  41333. if (isOpen() != shouldBeOpen)
  41334. {
  41335. openness = shouldBeOpen ? opennessOpen
  41336. : opennessClosed;
  41337. treeHasChanged();
  41338. itemOpennessChanged (isOpen());
  41339. }
  41340. }
  41341. bool TreeViewItem::isSelected() const throw()
  41342. {
  41343. return selected;
  41344. }
  41345. void TreeViewItem::deselectAllRecursively()
  41346. {
  41347. setSelected (false, false);
  41348. for (int i = 0; i < subItems.size(); ++i)
  41349. subItems.getUnchecked(i)->deselectAllRecursively();
  41350. }
  41351. void TreeViewItem::setSelected (const bool shouldBeSelected,
  41352. const bool deselectOtherItemsFirst)
  41353. {
  41354. if (deselectOtherItemsFirst)
  41355. getTopLevelItem()->deselectAllRecursively();
  41356. if (shouldBeSelected != selected)
  41357. {
  41358. selected = shouldBeSelected;
  41359. if (ownerView != 0)
  41360. ownerView->repaint();
  41361. itemSelectionChanged (shouldBeSelected);
  41362. }
  41363. }
  41364. void TreeViewItem::paintItem (Graphics&, int, int)
  41365. {
  41366. }
  41367. void TreeViewItem::itemClicked (const MouseEvent&)
  41368. {
  41369. }
  41370. void TreeViewItem::itemDoubleClicked (const MouseEvent&)
  41371. {
  41372. if (mightContainSubItems())
  41373. setOpen (! isOpen());
  41374. }
  41375. void TreeViewItem::itemSelectionChanged (bool)
  41376. {
  41377. }
  41378. const String TreeViewItem::getDragSourceDescription()
  41379. {
  41380. return String::empty;
  41381. }
  41382. const Rectangle TreeViewItem::getItemPosition (const bool relativeToTreeViewTopLeft) const throw()
  41383. {
  41384. const int indentX = getIndentX();
  41385. int width = itemWidth;
  41386. if (ownerView != 0 && width < 0)
  41387. width = ownerView->viewport->getViewWidth() - indentX;
  41388. Rectangle r (indentX, y, jmax (0, width), totalHeight);
  41389. if (relativeToTreeViewTopLeft)
  41390. r.setPosition (r.getX() - ownerView->viewport->getViewPositionX(),
  41391. r.getY() - ownerView->viewport->getViewPositionY());
  41392. return r;
  41393. }
  41394. void TreeViewItem::treeHasChanged() const throw()
  41395. {
  41396. if (ownerView != 0)
  41397. ownerView->itemsChanged();
  41398. }
  41399. void TreeViewItem::updatePositions (int newY)
  41400. {
  41401. y = newY;
  41402. itemHeight = getItemHeight();
  41403. totalHeight = itemHeight;
  41404. itemWidth = getItemWidth();
  41405. totalWidth = jmax (itemWidth, 0);
  41406. if (isOpen())
  41407. {
  41408. const int ourIndent = getIndentX();
  41409. newY += totalHeight;
  41410. for (int i = 0; i < subItems.size(); ++i)
  41411. {
  41412. TreeViewItem* const ti = subItems.getUnchecked(i);
  41413. ti->updatePositions (newY);
  41414. newY += ti->totalHeight;
  41415. totalHeight += ti->totalHeight;
  41416. totalWidth = jmax (totalWidth, ti->totalWidth + ourIndent);
  41417. }
  41418. }
  41419. }
  41420. TreeViewItem* TreeViewItem::getDeepestOpenParentItem() throw()
  41421. {
  41422. TreeViewItem* result = this;
  41423. TreeViewItem* item = this;
  41424. while (item->parentItem != 0)
  41425. {
  41426. item = item->parentItem;
  41427. if (! item->isOpen())
  41428. result = item;
  41429. }
  41430. return result;
  41431. }
  41432. void TreeViewItem::setOwnerView (TreeView* const newOwner) throw()
  41433. {
  41434. ownerView = newOwner;
  41435. for (int i = subItems.size(); --i >= 0;)
  41436. subItems.getUnchecked(i)->setOwnerView (newOwner);
  41437. }
  41438. int TreeViewItem::getIndentX() const throw()
  41439. {
  41440. const int indentWidth = ownerView->getIndentSize();
  41441. int x = indentWidth;
  41442. TreeViewItem* p = parentItem;
  41443. while (p != 0)
  41444. {
  41445. x += indentWidth;
  41446. p = p->parentItem;
  41447. }
  41448. return x;
  41449. }
  41450. void TreeViewItem::paintRecursively (Graphics& g, int width)
  41451. {
  41452. jassert (ownerView != 0);
  41453. if (ownerView == 0)
  41454. return;
  41455. const int indent = getIndentX();
  41456. const int itemW = itemWidth < 0 ? width - indent : itemWidth;
  41457. g.setColour (ownerView->findColour (TreeView::linesColourId));
  41458. const float halfH = itemHeight * 0.5f;
  41459. int depth = 0;
  41460. TreeViewItem* p = parentItem;
  41461. while (p != 0)
  41462. {
  41463. ++depth;
  41464. p = p->parentItem;
  41465. }
  41466. const int indentWidth = ownerView->getIndentSize();
  41467. float x = (depth + 0.5f) * indentWidth;
  41468. if (x > 0)
  41469. {
  41470. if (depth >= 0)
  41471. {
  41472. if (parentItem != 0 && parentItem->drawLinesInside)
  41473. g.drawLine (x, 0, x, isLastOfSiblings() ? halfH : (float) itemHeight);
  41474. if ((parentItem != 0 && parentItem->drawLinesInside)
  41475. || (parentItem == 0 && drawLinesInside))
  41476. g.drawLine (x, halfH, x + indentWidth / 2, halfH);
  41477. }
  41478. p = parentItem;
  41479. int d = depth;
  41480. while (p != 0 && --d >= 0)
  41481. {
  41482. x -= (float) indentWidth;
  41483. if ((p->parentItem == 0 || p->parentItem->drawLinesInside)
  41484. && ! p->isLastOfSiblings())
  41485. {
  41486. g.drawLine (x, 0, x, (float) itemHeight);
  41487. }
  41488. p = p->parentItem;
  41489. }
  41490. if (mightContainSubItems())
  41491. {
  41492. ownerView->getLookAndFeel()
  41493. .drawTreeviewPlusMinusBox (g,
  41494. depth * indentWidth, 0,
  41495. indentWidth, itemHeight,
  41496. ! isOpen());
  41497. }
  41498. }
  41499. {
  41500. g.saveState();
  41501. g.setOrigin (indent, 0);
  41502. if (g.reduceClipRegion (0, 0, itemW, itemHeight))
  41503. paintItem (g, itemW, itemHeight);
  41504. g.restoreState();
  41505. }
  41506. if (isOpen())
  41507. {
  41508. const Rectangle clip (g.getClipBounds());
  41509. for (int i = 0; i < subItems.size(); ++i)
  41510. {
  41511. TreeViewItem* const ti = subItems.getUnchecked(i);
  41512. const int relY = ti->y - y;
  41513. if (relY >= clip.getBottom())
  41514. break;
  41515. if (relY + ti->totalHeight >= clip.getY())
  41516. {
  41517. g.saveState();
  41518. g.setOrigin (0, relY);
  41519. if (g.reduceClipRegion (0, 0, width, ti->totalHeight))
  41520. ti->paintRecursively (g, width);
  41521. g.restoreState();
  41522. }
  41523. }
  41524. }
  41525. }
  41526. bool TreeViewItem::isLastOfSiblings() const throw()
  41527. {
  41528. return parentItem == 0
  41529. || parentItem->subItems.getLast() == this;
  41530. }
  41531. TreeViewItem* TreeViewItem::getTopLevelItem() throw()
  41532. {
  41533. return (parentItem == 0) ? this
  41534. : parentItem->getTopLevelItem();
  41535. }
  41536. int TreeViewItem::getNumRows() const throw()
  41537. {
  41538. int num = 1;
  41539. if (isOpen())
  41540. {
  41541. for (int i = subItems.size(); --i >= 0;)
  41542. num += subItems.getUnchecked(i)->getNumRows();
  41543. }
  41544. return num;
  41545. }
  41546. TreeViewItem* TreeViewItem::getItemOnRow (int index) throw()
  41547. {
  41548. if (index == 0)
  41549. return this;
  41550. if (index > 0 && isOpen())
  41551. {
  41552. --index;
  41553. for (int i = 0; i < subItems.size(); ++i)
  41554. {
  41555. TreeViewItem* const item = subItems.getUnchecked(i);
  41556. if (index == 0)
  41557. return item;
  41558. const int numRows = item->getNumRows();
  41559. if (numRows > index)
  41560. return item->getItemOnRow (index);
  41561. index -= numRows;
  41562. }
  41563. }
  41564. return 0;
  41565. }
  41566. TreeViewItem* TreeViewItem::findItemRecursively (int y) throw()
  41567. {
  41568. if (((unsigned int) y) < (unsigned int) totalHeight)
  41569. {
  41570. const int h = itemHeight;
  41571. if (y < h)
  41572. return this;
  41573. if (isOpen())
  41574. {
  41575. y -= h;
  41576. for (int i = 0; i < subItems.size(); ++i)
  41577. {
  41578. TreeViewItem* const ti = subItems.getUnchecked(i);
  41579. if (ti->totalHeight >= y)
  41580. return ti->findItemRecursively (y);
  41581. y -= ti->totalHeight;
  41582. }
  41583. }
  41584. }
  41585. return 0;
  41586. }
  41587. int TreeViewItem::countSelectedItemsRecursively() const throw()
  41588. {
  41589. int total = 0;
  41590. if (isSelected())
  41591. ++total;
  41592. for (int i = subItems.size(); --i >= 0;)
  41593. total += subItems.getUnchecked(i)->countSelectedItemsRecursively();
  41594. return total;
  41595. }
  41596. TreeViewItem* TreeViewItem::getSelectedItemWithIndex (int index) throw()
  41597. {
  41598. if (isSelected())
  41599. {
  41600. if (index == 0)
  41601. return this;
  41602. --index;
  41603. }
  41604. if (index >= 0)
  41605. {
  41606. for (int i = 0; i < subItems.size(); ++i)
  41607. {
  41608. TreeViewItem* const item = subItems.getUnchecked(i);
  41609. TreeViewItem* const found = item->getSelectedItemWithIndex (index);
  41610. if (found != 0)
  41611. return found;
  41612. index -= item->countSelectedItemsRecursively();
  41613. }
  41614. }
  41615. return 0;
  41616. }
  41617. int TreeViewItem::getRowNumberInTree() const throw()
  41618. {
  41619. if (parentItem != 0 && ownerView != 0)
  41620. {
  41621. int n = 1 + parentItem->getRowNumberInTree();
  41622. int ourIndex = parentItem->subItems.indexOf (this);
  41623. jassert (ourIndex >= 0);
  41624. while (--ourIndex >= 0)
  41625. n += parentItem->subItems [ourIndex]->getNumRows();
  41626. if (parentItem->parentItem == 0
  41627. && ! ownerView->rootItemVisible)
  41628. --n;
  41629. return n;
  41630. }
  41631. else
  41632. {
  41633. return 0;
  41634. }
  41635. }
  41636. void TreeViewItem::setLinesDrawnForSubItems (const bool drawLines) throw()
  41637. {
  41638. drawLinesInside = drawLines;
  41639. }
  41640. TreeViewItem* TreeViewItem::getNextVisibleItem (const bool recurse) const throw()
  41641. {
  41642. if (recurse && isOpen() && subItems.size() > 0)
  41643. return subItems [0];
  41644. if (parentItem != 0)
  41645. {
  41646. const int nextIndex = parentItem->subItems.indexOf (this) + 1;
  41647. if (nextIndex >= parentItem->subItems.size())
  41648. return parentItem->getNextVisibleItem (false);
  41649. return parentItem->subItems [nextIndex];
  41650. }
  41651. return 0;
  41652. }
  41653. void TreeViewItem::restoreFromXml (const XmlElement& e)
  41654. {
  41655. if (e.hasTagName (T("CLOSED")))
  41656. {
  41657. setOpen (false);
  41658. }
  41659. else if (e.hasTagName (T("OPEN")))
  41660. {
  41661. setOpen (true);
  41662. forEachXmlChildElement (e, n)
  41663. {
  41664. const String id (n->getStringAttribute (T("id")));
  41665. for (int i = 0; i < subItems.size(); ++i)
  41666. {
  41667. TreeViewItem* const ti = subItems.getUnchecked(i);
  41668. if (ti->getUniqueName() == id)
  41669. {
  41670. ti->restoreFromXml (*n);
  41671. break;
  41672. }
  41673. }
  41674. }
  41675. }
  41676. }
  41677. XmlElement* TreeViewItem::createXmlOpenness() const
  41678. {
  41679. if (openness != opennessDefault)
  41680. {
  41681. const String name (getUniqueName());
  41682. if (name.isNotEmpty())
  41683. {
  41684. XmlElement* e;
  41685. if (isOpen())
  41686. {
  41687. e = new XmlElement (T("OPEN"));
  41688. for (int i = 0; i < subItems.size(); ++i)
  41689. e->addChildElement (subItems.getUnchecked(i)->createXmlOpenness());
  41690. }
  41691. else
  41692. {
  41693. e = new XmlElement (T("CLOSED"));
  41694. }
  41695. e->setAttribute (T("id"), name);
  41696. return e;
  41697. }
  41698. else
  41699. {
  41700. // trying to save the openness for an element that has no name - this won't
  41701. // work because it needs the names to identify what to open.
  41702. jassertfalse
  41703. }
  41704. }
  41705. return 0;
  41706. }
  41707. END_JUCE_NAMESPACE
  41708. /********* End of inlined file: juce_TreeView.cpp *********/
  41709. /********* Start of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  41710. BEGIN_JUCE_NAMESPACE
  41711. DirectoryContentsDisplayComponent::DirectoryContentsDisplayComponent (DirectoryContentsList& listToShow)
  41712. : fileList (listToShow),
  41713. listeners (2)
  41714. {
  41715. }
  41716. DirectoryContentsDisplayComponent::~DirectoryContentsDisplayComponent()
  41717. {
  41718. }
  41719. FileBrowserListener::~FileBrowserListener()
  41720. {
  41721. }
  41722. void DirectoryContentsDisplayComponent::addListener (FileBrowserListener* const listener) throw()
  41723. {
  41724. jassert (listener != 0);
  41725. if (listener != 0)
  41726. listeners.add (listener);
  41727. }
  41728. void DirectoryContentsDisplayComponent::removeListener (FileBrowserListener* const listener) throw()
  41729. {
  41730. listeners.removeValue (listener);
  41731. }
  41732. void DirectoryContentsDisplayComponent::sendSelectionChangeMessage()
  41733. {
  41734. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  41735. for (int i = listeners.size(); --i >= 0;)
  41736. {
  41737. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  41738. if (deletionWatcher.hasBeenDeleted())
  41739. return;
  41740. i = jmin (i, listeners.size() - 1);
  41741. }
  41742. }
  41743. void DirectoryContentsDisplayComponent::sendMouseClickMessage (const File& file, const MouseEvent& e)
  41744. {
  41745. if (fileList.getDirectory().exists())
  41746. {
  41747. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  41748. for (int i = listeners.size(); --i >= 0;)
  41749. {
  41750. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (file, e);
  41751. if (deletionWatcher.hasBeenDeleted())
  41752. return;
  41753. i = jmin (i, listeners.size() - 1);
  41754. }
  41755. }
  41756. }
  41757. void DirectoryContentsDisplayComponent::sendDoubleClickMessage (const File& file)
  41758. {
  41759. if (fileList.getDirectory().exists())
  41760. {
  41761. const ComponentDeletionWatcher deletionWatcher (dynamic_cast <Component*> (this));
  41762. for (int i = listeners.size(); --i >= 0;)
  41763. {
  41764. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (file);
  41765. if (deletionWatcher.hasBeenDeleted())
  41766. return;
  41767. i = jmin (i, listeners.size() - 1);
  41768. }
  41769. }
  41770. }
  41771. END_JUCE_NAMESPACE
  41772. /********* End of inlined file: juce_DirectoryContentsDisplayComponent.cpp *********/
  41773. /********* Start of inlined file: juce_DirectoryContentsList.cpp *********/
  41774. BEGIN_JUCE_NAMESPACE
  41775. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  41776. bool* isDirectory, bool* isHidden, int64* fileSize, Time* modTime,
  41777. Time* creationTime, bool* isReadOnly) throw();
  41778. bool juce_findFileNext (void* handle, String& resultFile,
  41779. bool* isDirectory, bool* isHidden, int64* fileSize,
  41780. Time* modTime, Time* creationTime, bool* isReadOnly) throw();
  41781. void juce_findFileClose (void* handle) throw();
  41782. DirectoryContentsList::DirectoryContentsList (const FileFilter* const fileFilter_,
  41783. TimeSliceThread& thread_)
  41784. : fileFilter (fileFilter_),
  41785. thread (thread_),
  41786. includeDirectories (false),
  41787. includeFiles (false),
  41788. ignoreHiddenFiles (true),
  41789. fileFindHandle (0),
  41790. shouldStop (true)
  41791. {
  41792. }
  41793. DirectoryContentsList::~DirectoryContentsList()
  41794. {
  41795. clear();
  41796. }
  41797. void DirectoryContentsList::setIgnoresHiddenFiles (const bool shouldIgnoreHiddenFiles)
  41798. {
  41799. ignoreHiddenFiles = shouldIgnoreHiddenFiles;
  41800. }
  41801. const File& DirectoryContentsList::getDirectory() const throw()
  41802. {
  41803. return root;
  41804. }
  41805. void DirectoryContentsList::setDirectory (const File& directory,
  41806. const bool includeDirectories_,
  41807. const bool includeFiles_)
  41808. {
  41809. if (directory != root
  41810. || includeDirectories != includeDirectories_
  41811. || includeFiles != includeFiles_)
  41812. {
  41813. clear();
  41814. root = directory;
  41815. includeDirectories = includeDirectories_;
  41816. includeFiles = includeFiles_;
  41817. refresh();
  41818. }
  41819. }
  41820. void DirectoryContentsList::clear()
  41821. {
  41822. shouldStop = true;
  41823. thread.removeTimeSliceClient (this);
  41824. if (fileFindHandle != 0)
  41825. {
  41826. juce_findFileClose (fileFindHandle);
  41827. fileFindHandle = 0;
  41828. }
  41829. if (files.size() > 0)
  41830. {
  41831. files.clear();
  41832. changed();
  41833. }
  41834. }
  41835. void DirectoryContentsList::refresh()
  41836. {
  41837. clear();
  41838. if (root.isDirectory())
  41839. {
  41840. String fileFound;
  41841. bool fileFoundIsDir, isHidden, isReadOnly;
  41842. int64 fileSize;
  41843. Time modTime, creationTime;
  41844. String path (root.getFullPathName());
  41845. if (! path.endsWithChar (File::separator))
  41846. path += File::separator;
  41847. jassert (fileFindHandle == 0);
  41848. fileFindHandle = juce_findFileStart (path, T("*"), fileFound,
  41849. &fileFoundIsDir,
  41850. &isHidden,
  41851. &fileSize,
  41852. &modTime,
  41853. &creationTime,
  41854. &isReadOnly);
  41855. if (fileFindHandle != 0 && fileFound.isNotEmpty())
  41856. {
  41857. if (addFile (fileFound, fileFoundIsDir, isHidden,
  41858. fileSize, modTime, creationTime, isReadOnly))
  41859. {
  41860. changed();
  41861. }
  41862. }
  41863. shouldStop = false;
  41864. thread.addTimeSliceClient (this);
  41865. }
  41866. }
  41867. int DirectoryContentsList::getNumFiles() const
  41868. {
  41869. return files.size();
  41870. }
  41871. bool DirectoryContentsList::getFileInfo (const int index,
  41872. FileInfo& result) const
  41873. {
  41874. const ScopedLock sl (fileListLock);
  41875. const FileInfo* const info = files [index];
  41876. if (info != 0)
  41877. {
  41878. result = *info;
  41879. return true;
  41880. }
  41881. return false;
  41882. }
  41883. const File DirectoryContentsList::getFile (const int index) const
  41884. {
  41885. const ScopedLock sl (fileListLock);
  41886. const FileInfo* const info = files [index];
  41887. if (info != 0)
  41888. return root.getChildFile (info->filename);
  41889. return File::nonexistent;
  41890. }
  41891. bool DirectoryContentsList::isStillLoading() const
  41892. {
  41893. return fileFindHandle != 0;
  41894. }
  41895. void DirectoryContentsList::changed()
  41896. {
  41897. sendChangeMessage (this);
  41898. }
  41899. bool DirectoryContentsList::useTimeSlice()
  41900. {
  41901. const uint32 startTime = Time::getApproximateMillisecondCounter();
  41902. bool hasChanged = false;
  41903. for (int i = 100; --i >= 0;)
  41904. {
  41905. if (! checkNextFile (hasChanged))
  41906. {
  41907. if (hasChanged)
  41908. changed();
  41909. return false;
  41910. }
  41911. if (shouldStop || (Time::getApproximateMillisecondCounter() > startTime + 150))
  41912. break;
  41913. }
  41914. if (hasChanged)
  41915. changed();
  41916. return true;
  41917. }
  41918. bool DirectoryContentsList::checkNextFile (bool& hasChanged)
  41919. {
  41920. if (fileFindHandle != 0)
  41921. {
  41922. String fileFound;
  41923. bool fileFoundIsDir, isHidden, isReadOnly;
  41924. int64 fileSize;
  41925. Time modTime, creationTime;
  41926. if (juce_findFileNext (fileFindHandle, fileFound,
  41927. &fileFoundIsDir, &isHidden,
  41928. &fileSize,
  41929. &modTime,
  41930. &creationTime,
  41931. &isReadOnly))
  41932. {
  41933. if (addFile (fileFound, fileFoundIsDir, isHidden, fileSize,
  41934. modTime, creationTime, isReadOnly))
  41935. {
  41936. hasChanged = true;
  41937. }
  41938. return true;
  41939. }
  41940. else
  41941. {
  41942. juce_findFileClose (fileFindHandle);
  41943. fileFindHandle = 0;
  41944. }
  41945. }
  41946. return false;
  41947. }
  41948. int DirectoryContentsList::compareElements (const DirectoryContentsList::FileInfo* const first,
  41949. const DirectoryContentsList::FileInfo* const second) throw()
  41950. {
  41951. #if JUCE_WIN32
  41952. if (first->isDirectory != second->isDirectory)
  41953. return first->isDirectory ? -1 : 1;
  41954. #endif
  41955. return first->filename.compareIgnoreCase (second->filename);
  41956. }
  41957. bool DirectoryContentsList::addFile (const String& filename,
  41958. const bool isDir,
  41959. const bool isHidden,
  41960. const int64 fileSize,
  41961. const Time& modTime,
  41962. const Time& creationTime,
  41963. const bool isReadOnly)
  41964. {
  41965. if (filename == T("..")
  41966. || filename == T(".")
  41967. || (ignoreHiddenFiles && isHidden))
  41968. return false;
  41969. const File file (root.getChildFile (filename));
  41970. if (((isDir && includeDirectories) || ((! isDir) && includeFiles))
  41971. && (fileFilter == 0
  41972. || ((! isDir) && fileFilter->isFileSuitable (file))
  41973. || (isDir && fileFilter->isDirectorySuitable (file))))
  41974. {
  41975. FileInfo* const info = new FileInfo();
  41976. info->filename = filename;
  41977. info->fileSize = fileSize;
  41978. info->modificationTime = modTime;
  41979. info->creationTime = creationTime;
  41980. info->isDirectory = isDir;
  41981. info->isReadOnly = isReadOnly;
  41982. const ScopedLock sl (fileListLock);
  41983. for (int i = files.size(); --i >= 0;)
  41984. {
  41985. if (files.getUnchecked(i)->filename == info->filename)
  41986. {
  41987. delete info;
  41988. return false;
  41989. }
  41990. }
  41991. files.addSorted (*this, info);
  41992. return true;
  41993. }
  41994. return false;
  41995. }
  41996. END_JUCE_NAMESPACE
  41997. /********* End of inlined file: juce_DirectoryContentsList.cpp *********/
  41998. /********* Start of inlined file: juce_FileBrowserComponent.cpp *********/
  41999. BEGIN_JUCE_NAMESPACE
  42000. class DirectoriesOnlyFilter : public FileFilter
  42001. {
  42002. public:
  42003. DirectoriesOnlyFilter() : FileFilter (String::empty) {}
  42004. bool isFileSuitable (const File&) const { return false; }
  42005. bool isDirectorySuitable (const File&) const { return true; }
  42006. };
  42007. FileBrowserComponent::FileBrowserComponent (FileChooserMode mode_,
  42008. const File& initialFileOrDirectory,
  42009. const FileFilter* fileFilter,
  42010. FilePreviewComponent* previewComp_,
  42011. const bool useTreeView,
  42012. const bool filenameTextBoxIsReadOnly)
  42013. : directoriesOnlyFilter (0),
  42014. mode (mode_),
  42015. listeners (2),
  42016. previewComp (previewComp_),
  42017. thread ("Juce FileBrowser")
  42018. {
  42019. String filename;
  42020. if (initialFileOrDirectory == File::nonexistent)
  42021. {
  42022. currentRoot = File::getCurrentWorkingDirectory();
  42023. }
  42024. else if (initialFileOrDirectory.isDirectory())
  42025. {
  42026. currentRoot = initialFileOrDirectory;
  42027. }
  42028. else
  42029. {
  42030. currentRoot = initialFileOrDirectory.getParentDirectory();
  42031. filename = initialFileOrDirectory.getFileName();
  42032. }
  42033. if (mode_ == chooseDirectoryMode)
  42034. fileFilter = directoriesOnlyFilter = new DirectoriesOnlyFilter();
  42035. fileList = new DirectoryContentsList (fileFilter, thread);
  42036. if (useTreeView)
  42037. {
  42038. FileTreeComponent* const tree = new FileTreeComponent (*fileList);
  42039. addAndMakeVisible (tree);
  42040. fileListComponent = tree;
  42041. }
  42042. else
  42043. {
  42044. FileListComponent* const list = new FileListComponent (*fileList);
  42045. list->setOutlineThickness (1);
  42046. addAndMakeVisible (list);
  42047. fileListComponent = list;
  42048. }
  42049. fileListComponent->addListener (this);
  42050. addAndMakeVisible (currentPathBox = new ComboBox ("path"));
  42051. currentPathBox->setEditableText (true);
  42052. StringArray rootNames, rootPaths;
  42053. const BitArray separators (getRoots (rootNames, rootPaths));
  42054. for (int i = 0; i < rootNames.size(); ++i)
  42055. {
  42056. if (separators [i])
  42057. currentPathBox->addSeparator();
  42058. currentPathBox->addItem (rootNames[i], i + 1);
  42059. }
  42060. currentPathBox->addSeparator();
  42061. currentPathBox->addListener (this);
  42062. addAndMakeVisible (filenameBox = new TextEditor());
  42063. filenameBox->setMultiLine (false);
  42064. filenameBox->setSelectAllWhenFocused (true);
  42065. filenameBox->setText (filename, false);
  42066. filenameBox->addListener (this);
  42067. filenameBox->setReadOnly (filenameTextBoxIsReadOnly);
  42068. Label* label = new Label ("f", (mode == chooseDirectoryMode) ? TRANS("folder:")
  42069. : TRANS("file:"));
  42070. addAndMakeVisible (label);
  42071. label->attachToComponent (filenameBox, true);
  42072. addAndMakeVisible (goUpButton = getLookAndFeel().createFileBrowserGoUpButton());
  42073. goUpButton->addButtonListener (this);
  42074. goUpButton->setTooltip (TRANS ("go up to parent directory"));
  42075. if (previewComp != 0)
  42076. addAndMakeVisible (previewComp);
  42077. setRoot (currentRoot);
  42078. thread.startThread (4);
  42079. }
  42080. FileBrowserComponent::~FileBrowserComponent()
  42081. {
  42082. if (previewComp != 0)
  42083. removeChildComponent (previewComp);
  42084. deleteAllChildren();
  42085. deleteAndZero (fileList);
  42086. delete directoriesOnlyFilter;
  42087. thread.stopThread (10000);
  42088. }
  42089. void FileBrowserComponent::addListener (FileBrowserListener* const newListener) throw()
  42090. {
  42091. jassert (newListener != 0)
  42092. if (newListener != 0)
  42093. listeners.add (newListener);
  42094. }
  42095. void FileBrowserComponent::removeListener (FileBrowserListener* const listener) throw()
  42096. {
  42097. listeners.removeValue (listener);
  42098. }
  42099. const File FileBrowserComponent::getCurrentFile() const throw()
  42100. {
  42101. return currentRoot.getChildFile (filenameBox->getText());
  42102. }
  42103. bool FileBrowserComponent::currentFileIsValid() const
  42104. {
  42105. if (mode == saveFileMode)
  42106. return ! getCurrentFile().isDirectory();
  42107. else if (mode == loadFileMode)
  42108. return getCurrentFile().existsAsFile();
  42109. else if (mode == chooseDirectoryMode)
  42110. return getCurrentFile().isDirectory();
  42111. jassertfalse
  42112. return false;
  42113. }
  42114. const File FileBrowserComponent::getRoot() const
  42115. {
  42116. return currentRoot;
  42117. }
  42118. void FileBrowserComponent::setRoot (const File& newRootDirectory)
  42119. {
  42120. if (currentRoot != newRootDirectory)
  42121. {
  42122. fileListComponent->scrollToTop();
  42123. if (mode == chooseDirectoryMode)
  42124. filenameBox->setText (String::empty, false);
  42125. String path (newRootDirectory.getFullPathName());
  42126. if (path.isEmpty())
  42127. path += File::separator;
  42128. StringArray rootNames, rootPaths;
  42129. getRoots (rootNames, rootPaths);
  42130. if (! rootPaths.contains (path, true))
  42131. {
  42132. bool alreadyListed = false;
  42133. for (int i = currentPathBox->getNumItems(); --i >= 0;)
  42134. {
  42135. if (currentPathBox->getItemText (i).equalsIgnoreCase (path))
  42136. {
  42137. alreadyListed = true;
  42138. break;
  42139. }
  42140. }
  42141. if (! alreadyListed)
  42142. currentPathBox->addItem (path, currentPathBox->getNumItems() + 2);
  42143. }
  42144. }
  42145. currentRoot = newRootDirectory;
  42146. fileList->setDirectory (currentRoot, true, true);
  42147. String currentRootName (currentRoot.getFullPathName());
  42148. if (currentRootName.isEmpty())
  42149. currentRootName += File::separator;
  42150. currentPathBox->setText (currentRootName, true);
  42151. goUpButton->setEnabled (currentRoot.getParentDirectory().isDirectory()
  42152. && currentRoot.getParentDirectory() != currentRoot);
  42153. }
  42154. void FileBrowserComponent::goUp()
  42155. {
  42156. setRoot (getRoot().getParentDirectory());
  42157. }
  42158. void FileBrowserComponent::refresh()
  42159. {
  42160. fileList->refresh();
  42161. }
  42162. const String FileBrowserComponent::getActionVerb() const
  42163. {
  42164. return (mode == chooseDirectoryMode) ? TRANS("Choose")
  42165. : ((mode == saveFileMode) ? TRANS("Save") : TRANS("Open"));
  42166. }
  42167. FilePreviewComponent* FileBrowserComponent::getPreviewComponent() const throw()
  42168. {
  42169. return previewComp;
  42170. }
  42171. void FileBrowserComponent::resized()
  42172. {
  42173. getLookAndFeel()
  42174. .layoutFileBrowserComponent (*this, fileListComponent,
  42175. previewComp, currentPathBox,
  42176. filenameBox, goUpButton);
  42177. }
  42178. void FileBrowserComponent::sendListenerChangeMessage()
  42179. {
  42180. ComponentDeletionWatcher deletionWatcher (this);
  42181. if (previewComp != 0)
  42182. previewComp->selectedFileChanged (getCurrentFile());
  42183. jassert (! deletionWatcher.hasBeenDeleted());
  42184. for (int i = listeners.size(); --i >= 0;)
  42185. {
  42186. ((FileBrowserListener*) listeners.getUnchecked (i))->selectionChanged();
  42187. if (deletionWatcher.hasBeenDeleted())
  42188. return;
  42189. i = jmin (i, listeners.size() - 1);
  42190. }
  42191. }
  42192. void FileBrowserComponent::selectionChanged()
  42193. {
  42194. const File selected (fileListComponent->getSelectedFile());
  42195. if ((mode == chooseDirectoryMode && selected.isDirectory())
  42196. || selected.existsAsFile())
  42197. {
  42198. filenameBox->setText (selected.getRelativePathFrom (getRoot()), false);
  42199. }
  42200. sendListenerChangeMessage();
  42201. }
  42202. void FileBrowserComponent::fileClicked (const File& f, const MouseEvent& e)
  42203. {
  42204. ComponentDeletionWatcher deletionWatcher (this);
  42205. for (int i = listeners.size(); --i >= 0;)
  42206. {
  42207. ((FileBrowserListener*) listeners.getUnchecked (i))->fileClicked (f, e);
  42208. if (deletionWatcher.hasBeenDeleted())
  42209. return;
  42210. i = jmin (i, listeners.size() - 1);
  42211. }
  42212. }
  42213. void FileBrowserComponent::fileDoubleClicked (const File& f)
  42214. {
  42215. if (f.isDirectory())
  42216. {
  42217. setRoot (f);
  42218. }
  42219. else
  42220. {
  42221. ComponentDeletionWatcher deletionWatcher (this);
  42222. for (int i = listeners.size(); --i >= 0;)
  42223. {
  42224. ((FileBrowserListener*) listeners.getUnchecked (i))->fileDoubleClicked (f);
  42225. if (deletionWatcher.hasBeenDeleted())
  42226. return;
  42227. i = jmin (i, listeners.size() - 1);
  42228. }
  42229. }
  42230. }
  42231. void FileBrowserComponent::textEditorTextChanged (TextEditor&)
  42232. {
  42233. sendListenerChangeMessage();
  42234. }
  42235. void FileBrowserComponent::textEditorReturnKeyPressed (TextEditor&)
  42236. {
  42237. if (filenameBox->getText().containsChar (File::separator))
  42238. {
  42239. const File f (currentRoot.getChildFile (filenameBox->getText()));
  42240. if (f.isDirectory())
  42241. {
  42242. setRoot (f);
  42243. filenameBox->setText (String::empty);
  42244. }
  42245. else
  42246. {
  42247. setRoot (f.getParentDirectory());
  42248. filenameBox->setText (f.getFileName());
  42249. }
  42250. }
  42251. else
  42252. {
  42253. fileDoubleClicked (getCurrentFile());
  42254. }
  42255. }
  42256. void FileBrowserComponent::textEditorEscapeKeyPressed (TextEditor&)
  42257. {
  42258. }
  42259. void FileBrowserComponent::textEditorFocusLost (TextEditor&)
  42260. {
  42261. if (mode != saveFileMode)
  42262. selectionChanged();
  42263. }
  42264. void FileBrowserComponent::buttonClicked (Button*)
  42265. {
  42266. goUp();
  42267. }
  42268. void FileBrowserComponent::comboBoxChanged (ComboBox*)
  42269. {
  42270. const String newText (currentPathBox->getText().trim().unquoted());
  42271. if (newText.isNotEmpty())
  42272. {
  42273. const int index = currentPathBox->getSelectedId() - 1;
  42274. StringArray rootNames, rootPaths;
  42275. getRoots (rootNames, rootPaths);
  42276. if (rootPaths [index].isNotEmpty())
  42277. {
  42278. setRoot (File (rootPaths [index]));
  42279. }
  42280. else
  42281. {
  42282. File f (newText);
  42283. for (;;)
  42284. {
  42285. if (f.isDirectory())
  42286. {
  42287. setRoot (f);
  42288. break;
  42289. }
  42290. if (f.getParentDirectory() == f)
  42291. break;
  42292. f = f.getParentDirectory();
  42293. }
  42294. }
  42295. }
  42296. }
  42297. const BitArray FileBrowserComponent::getRoots (StringArray& rootNames, StringArray& rootPaths)
  42298. {
  42299. BitArray separators;
  42300. #if JUCE_WIN32
  42301. OwnedArray<File> roots;
  42302. File::findFileSystemRoots (roots);
  42303. rootPaths.clear();
  42304. for (int i = 0; i < roots.size(); ++i)
  42305. {
  42306. const File* const drive = roots.getUnchecked(i);
  42307. String name (drive->getFullPathName());
  42308. rootPaths.add (name);
  42309. if (drive->isOnHardDisk())
  42310. {
  42311. String volume (drive->getVolumeLabel());
  42312. if (volume.isEmpty())
  42313. volume = TRANS("Hard Drive");
  42314. name << " [" << drive->getVolumeLabel() << ']';
  42315. }
  42316. else if (drive->isOnCDRomDrive())
  42317. {
  42318. name << TRANS(" [CD/DVD drive]");
  42319. }
  42320. rootNames.add (name);
  42321. }
  42322. separators.setBit (rootPaths.size());
  42323. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  42324. rootNames.add ("Documents");
  42325. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  42326. rootNames.add ("Desktop");
  42327. #endif
  42328. #if JUCE_MAC
  42329. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  42330. rootNames.add ("Home folder");
  42331. rootPaths.add (File::getSpecialLocation (File::userDocumentsDirectory).getFullPathName());
  42332. rootNames.add ("Documents");
  42333. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  42334. rootNames.add ("Desktop");
  42335. separators.setBit (rootPaths.size());
  42336. OwnedArray <File> volumes;
  42337. File vol ("/Volumes");
  42338. vol.findChildFiles (volumes, File::findDirectories, false);
  42339. for (int i = 0; i < volumes.size(); ++i)
  42340. {
  42341. const File* const volume = volumes.getUnchecked(i);
  42342. if (volume->isDirectory() && ! volume->getFileName().startsWithChar (T('.')))
  42343. {
  42344. rootPaths.add (volume->getFullPathName());
  42345. rootNames.add (volume->getFileName());
  42346. }
  42347. }
  42348. #endif
  42349. #if JUCE_LINUX
  42350. rootPaths.add ("/");
  42351. rootNames.add ("/");
  42352. rootPaths.add (File::getSpecialLocation (File::userHomeDirectory).getFullPathName());
  42353. rootNames.add ("Home folder");
  42354. rootPaths.add (File::getSpecialLocation (File::userDesktopDirectory).getFullPathName());
  42355. rootNames.add ("Desktop");
  42356. #endif
  42357. return separators;
  42358. }
  42359. END_JUCE_NAMESPACE
  42360. /********* End of inlined file: juce_FileBrowserComponent.cpp *********/
  42361. /********* Start of inlined file: juce_FileChooser.cpp *********/
  42362. BEGIN_JUCE_NAMESPACE
  42363. FileChooser::FileChooser (const String& chooserBoxTitle,
  42364. const File& currentFileOrDirectory,
  42365. const String& fileFilters,
  42366. const bool useNativeDialogBox_)
  42367. : title (chooserBoxTitle),
  42368. filters (fileFilters),
  42369. startingFile (currentFileOrDirectory),
  42370. useNativeDialogBox (useNativeDialogBox_)
  42371. {
  42372. #if JUCE_LINUX
  42373. useNativeDialogBox = false;
  42374. #endif
  42375. if (fileFilters.trim().isEmpty())
  42376. filters = T("*");
  42377. }
  42378. FileChooser::~FileChooser()
  42379. {
  42380. }
  42381. bool FileChooser::browseForFileToOpen (FilePreviewComponent* previewComponent)
  42382. {
  42383. return showDialog (false, false, false, false, previewComponent);
  42384. }
  42385. bool FileChooser::browseForMultipleFilesToOpen (FilePreviewComponent* previewComponent)
  42386. {
  42387. return showDialog (false, false, false, true, previewComponent);
  42388. }
  42389. bool FileChooser::browseForFileToSave (const bool warnAboutOverwritingExistingFiles)
  42390. {
  42391. return showDialog (false, true, warnAboutOverwritingExistingFiles, false, 0);
  42392. }
  42393. bool FileChooser::browseForDirectory()
  42394. {
  42395. return showDialog (true, false, false, false, 0);
  42396. }
  42397. const File FileChooser::getResult() const
  42398. {
  42399. // if you've used a multiple-file select, you should use the getResults() method
  42400. // to retrieve all the files that were chosen.
  42401. jassert (results.size() <= 1);
  42402. const File* const f = results.getFirst();
  42403. if (f != 0)
  42404. return *f;
  42405. return File::nonexistent;
  42406. }
  42407. const OwnedArray <File>& FileChooser::getResults() const
  42408. {
  42409. return results;
  42410. }
  42411. bool FileChooser::showDialog (const bool isDirectory,
  42412. const bool isSave,
  42413. const bool warnAboutOverwritingExistingFiles,
  42414. const bool selectMultipleFiles,
  42415. FilePreviewComponent* const previewComponent)
  42416. {
  42417. ComponentDeletionWatcher* currentlyFocusedChecker = 0;
  42418. Component* const currentlyFocused = Component::getCurrentlyFocusedComponent();
  42419. if (currentlyFocused != 0)
  42420. currentlyFocusedChecker = new ComponentDeletionWatcher (currentlyFocused);
  42421. results.clear();
  42422. // the preview component needs to be the right size before you pass it in here..
  42423. jassert (previewComponent == 0 || (previewComponent->getWidth() > 10
  42424. && previewComponent->getHeight() > 10));
  42425. #if JUCE_WIN32
  42426. if (useNativeDialogBox)
  42427. #else
  42428. if (useNativeDialogBox && (previewComponent == 0))
  42429. #endif
  42430. {
  42431. showPlatformDialog (results, title, startingFile, filters,
  42432. isDirectory, isSave,
  42433. warnAboutOverwritingExistingFiles,
  42434. selectMultipleFiles,
  42435. previewComponent);
  42436. }
  42437. else
  42438. {
  42439. jassert (! selectMultipleFiles); // not yet implemented for juce dialogs!
  42440. WildcardFileFilter wildcard (filters, String::empty);
  42441. FileBrowserComponent browserComponent (isDirectory ? FileBrowserComponent::chooseDirectoryMode
  42442. : (isSave ? FileBrowserComponent::saveFileMode
  42443. : FileBrowserComponent::loadFileMode),
  42444. startingFile, &wildcard, previewComponent);
  42445. FileChooserDialogBox box (title, String::empty,
  42446. browserComponent,
  42447. warnAboutOverwritingExistingFiles,
  42448. browserComponent.findColour (AlertWindow::backgroundColourId));
  42449. if (box.show())
  42450. results.add (new File (browserComponent.getCurrentFile()));
  42451. }
  42452. if (currentlyFocused != 0 && ! currentlyFocusedChecker->hasBeenDeleted())
  42453. currentlyFocused->grabKeyboardFocus();
  42454. delete currentlyFocusedChecker;
  42455. return results.size() > 0;
  42456. }
  42457. FilePreviewComponent::FilePreviewComponent()
  42458. {
  42459. }
  42460. FilePreviewComponent::~FilePreviewComponent()
  42461. {
  42462. }
  42463. END_JUCE_NAMESPACE
  42464. /********* End of inlined file: juce_FileChooser.cpp *********/
  42465. /********* Start of inlined file: juce_FileChooserDialogBox.cpp *********/
  42466. BEGIN_JUCE_NAMESPACE
  42467. FileChooserDialogBox::FileChooserDialogBox (const String& name,
  42468. const String& instructions,
  42469. FileBrowserComponent& chooserComponent,
  42470. const bool warnAboutOverwritingExistingFiles_,
  42471. const Colour& backgroundColour)
  42472. : ResizableWindow (name, backgroundColour, true),
  42473. warnAboutOverwritingExistingFiles (warnAboutOverwritingExistingFiles_)
  42474. {
  42475. content = new ContentComponent();
  42476. content->setName (name);
  42477. content->instructions = instructions;
  42478. content->chooserComponent = &chooserComponent;
  42479. content->addAndMakeVisible (&chooserComponent);
  42480. content->okButton = new TextButton (chooserComponent.getActionVerb());
  42481. content->addAndMakeVisible (content->okButton);
  42482. content->okButton->addButtonListener (this);
  42483. content->okButton->setEnabled (chooserComponent.currentFileIsValid());
  42484. content->okButton->addShortcut (KeyPress (KeyPress::returnKey, 0, 0));
  42485. content->cancelButton = new TextButton (TRANS("Cancel"));
  42486. content->addAndMakeVisible (content->cancelButton);
  42487. content->cancelButton->addButtonListener (this);
  42488. content->cancelButton->addShortcut (KeyPress (KeyPress::escapeKey, 0, 0));
  42489. setContentComponent (content);
  42490. setResizable (true, true);
  42491. setResizeLimits (300, 300, 1200, 1000);
  42492. content->chooserComponent->addListener (this);
  42493. }
  42494. FileChooserDialogBox::~FileChooserDialogBox()
  42495. {
  42496. content->chooserComponent->removeListener (this);
  42497. }
  42498. bool FileChooserDialogBox::show (int w, int h)
  42499. {
  42500. if (w <= 0)
  42501. {
  42502. Component* const previewComp = content->chooserComponent->getPreviewComponent();
  42503. if (previewComp != 0)
  42504. w = 400 + previewComp->getWidth();
  42505. else
  42506. w = 600;
  42507. }
  42508. if (h <= 0)
  42509. h = 500;
  42510. centreWithSize (w, h);
  42511. const bool ok = (runModalLoop() != 0);
  42512. setVisible (false);
  42513. return ok;
  42514. }
  42515. void FileChooserDialogBox::buttonClicked (Button* button)
  42516. {
  42517. if (button == content->okButton)
  42518. {
  42519. if (warnAboutOverwritingExistingFiles
  42520. && content->chooserComponent->getMode() == FileBrowserComponent::saveFileMode
  42521. && content->chooserComponent->getCurrentFile().exists())
  42522. {
  42523. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  42524. TRANS("File already exists"),
  42525. TRANS("There's already a file called:\n\n")
  42526. + content->chooserComponent->getCurrentFile().getFullPathName()
  42527. + T("\n\nAre you sure you want to overwrite it?"),
  42528. TRANS("overwrite"),
  42529. TRANS("cancel")))
  42530. {
  42531. return;
  42532. }
  42533. }
  42534. exitModalState (1);
  42535. }
  42536. else if (button == content->cancelButton)
  42537. closeButtonPressed();
  42538. }
  42539. void FileChooserDialogBox::closeButtonPressed()
  42540. {
  42541. setVisible (false);
  42542. }
  42543. void FileChooserDialogBox::selectionChanged()
  42544. {
  42545. content->okButton->setEnabled (content->chooserComponent->currentFileIsValid());
  42546. }
  42547. void FileChooserDialogBox::fileClicked (const File&, const MouseEvent&)
  42548. {
  42549. }
  42550. void FileChooserDialogBox::fileDoubleClicked (const File&)
  42551. {
  42552. selectionChanged();
  42553. content->okButton->triggerClick();
  42554. }
  42555. FileChooserDialogBox::ContentComponent::ContentComponent()
  42556. {
  42557. setInterceptsMouseClicks (false, true);
  42558. }
  42559. FileChooserDialogBox::ContentComponent::~ContentComponent()
  42560. {
  42561. delete okButton;
  42562. delete cancelButton;
  42563. }
  42564. void FileChooserDialogBox::ContentComponent::paint (Graphics& g)
  42565. {
  42566. g.setColour (Colours::black);
  42567. text.draw (g);
  42568. }
  42569. void FileChooserDialogBox::ContentComponent::resized()
  42570. {
  42571. getLookAndFeel().createFileChooserHeaderText (getName(), instructions, text, getWidth());
  42572. float left, top, right, bottom;
  42573. text.getBoundingBox (0, text.getNumGlyphs(), left, top, right, bottom, false);
  42574. const int y = roundFloatToInt (bottom) + 10;
  42575. const int buttonHeight = 26;
  42576. const int buttonY = getHeight() - buttonHeight - 8;
  42577. chooserComponent->setBounds (0, y, getWidth(), buttonY - y - 20);
  42578. okButton->setBounds (proportionOfWidth (0.25f), buttonY,
  42579. proportionOfWidth (0.2f), buttonHeight);
  42580. cancelButton->setBounds (proportionOfWidth (0.55f), buttonY,
  42581. proportionOfWidth (0.2f), buttonHeight);
  42582. }
  42583. END_JUCE_NAMESPACE
  42584. /********* End of inlined file: juce_FileChooserDialogBox.cpp *********/
  42585. /********* Start of inlined file: juce_FileFilter.cpp *********/
  42586. BEGIN_JUCE_NAMESPACE
  42587. FileFilter::FileFilter (const String& filterDescription)
  42588. : description (filterDescription)
  42589. {
  42590. }
  42591. FileFilter::~FileFilter()
  42592. {
  42593. }
  42594. const String& FileFilter::getDescription() const throw()
  42595. {
  42596. return description;
  42597. }
  42598. END_JUCE_NAMESPACE
  42599. /********* End of inlined file: juce_FileFilter.cpp *********/
  42600. /********* Start of inlined file: juce_FileListComponent.cpp *********/
  42601. BEGIN_JUCE_NAMESPACE
  42602. Image* juce_createIconForFile (const File& file);
  42603. FileListComponent::FileListComponent (DirectoryContentsList& listToShow)
  42604. : ListBox (String::empty, 0),
  42605. DirectoryContentsDisplayComponent (listToShow)
  42606. {
  42607. setModel (this);
  42608. fileList.addChangeListener (this);
  42609. }
  42610. FileListComponent::~FileListComponent()
  42611. {
  42612. fileList.removeChangeListener (this);
  42613. deleteAllChildren();
  42614. }
  42615. const File FileListComponent::getSelectedFile() const
  42616. {
  42617. return fileList.getFile (getSelectedRow());
  42618. }
  42619. void FileListComponent::scrollToTop()
  42620. {
  42621. getVerticalScrollBar()->setCurrentRangeStart (0);
  42622. }
  42623. void FileListComponent::changeListenerCallback (void*)
  42624. {
  42625. updateContent();
  42626. if (lastDirectory != fileList.getDirectory())
  42627. {
  42628. lastDirectory = fileList.getDirectory();
  42629. deselectAllRows();
  42630. }
  42631. }
  42632. class FileListItemComponent : public Component,
  42633. public TimeSliceClient,
  42634. public AsyncUpdater
  42635. {
  42636. public:
  42637. FileListItemComponent (FileListComponent& owner_,
  42638. TimeSliceThread& thread_) throw()
  42639. : owner (owner_),
  42640. thread (thread_),
  42641. icon (0)
  42642. {
  42643. }
  42644. ~FileListItemComponent() throw()
  42645. {
  42646. thread.removeTimeSliceClient (this);
  42647. clearIcon();
  42648. }
  42649. void paint (Graphics& g)
  42650. {
  42651. getLookAndFeel().drawFileBrowserRow (g, getWidth(), getHeight(),
  42652. file.getFileName(),
  42653. icon,
  42654. fileSize, modTime,
  42655. isDirectory, highlighted,
  42656. index);
  42657. }
  42658. void mouseDown (const MouseEvent& e)
  42659. {
  42660. owner.selectRowsBasedOnModifierKeys (index, e.mods);
  42661. owner.sendMouseClickMessage (file, e);
  42662. }
  42663. void mouseDoubleClick (const MouseEvent&)
  42664. {
  42665. owner.sendDoubleClickMessage (file);
  42666. }
  42667. void update (const File& root,
  42668. const DirectoryContentsList::FileInfo* const fileInfo,
  42669. const int index_,
  42670. const bool highlighted_) throw()
  42671. {
  42672. thread.removeTimeSliceClient (this);
  42673. if (highlighted_ != highlighted
  42674. || index_ != index)
  42675. {
  42676. index = index_;
  42677. highlighted = highlighted_;
  42678. repaint();
  42679. }
  42680. File newFile;
  42681. String newFileSize;
  42682. String newModTime;
  42683. if (fileInfo != 0)
  42684. {
  42685. newFile = root.getChildFile (fileInfo->filename);
  42686. newFileSize = File::descriptionOfSizeInBytes (fileInfo->fileSize);
  42687. newModTime = fileInfo->modificationTime.formatted (T("%d %b '%y %H:%M"));
  42688. }
  42689. if (newFile != file
  42690. || fileSize != newFileSize
  42691. || modTime != newModTime)
  42692. {
  42693. file = newFile;
  42694. fileSize = newFileSize;
  42695. modTime = newModTime;
  42696. isDirectory = fileInfo != 0 && fileInfo->isDirectory;
  42697. repaint();
  42698. clearIcon();
  42699. }
  42700. if (file != File::nonexistent
  42701. && icon == 0 && ! isDirectory)
  42702. {
  42703. updateIcon (true);
  42704. if (icon == 0)
  42705. thread.addTimeSliceClient (this);
  42706. }
  42707. }
  42708. bool useTimeSlice()
  42709. {
  42710. updateIcon (false);
  42711. return false;
  42712. }
  42713. void handleAsyncUpdate()
  42714. {
  42715. repaint();
  42716. }
  42717. juce_UseDebuggingNewOperator
  42718. private:
  42719. FileListComponent& owner;
  42720. TimeSliceThread& thread;
  42721. bool highlighted;
  42722. int index;
  42723. File file;
  42724. String fileSize;
  42725. String modTime;
  42726. Image* icon;
  42727. bool isDirectory;
  42728. void clearIcon() throw()
  42729. {
  42730. ImageCache::release (icon);
  42731. icon = 0;
  42732. }
  42733. void updateIcon (const bool onlyUpdateIfCached) throw()
  42734. {
  42735. if (icon == 0)
  42736. {
  42737. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  42738. Image* im = ImageCache::getFromHashCode (hashCode);
  42739. if (im == 0 && ! onlyUpdateIfCached)
  42740. {
  42741. im = juce_createIconForFile (file);
  42742. if (im != 0)
  42743. ImageCache::addImageToCache (im, hashCode);
  42744. }
  42745. if (im != 0)
  42746. {
  42747. icon = im;
  42748. triggerAsyncUpdate();
  42749. }
  42750. }
  42751. }
  42752. };
  42753. int FileListComponent::getNumRows()
  42754. {
  42755. return fileList.getNumFiles();
  42756. }
  42757. void FileListComponent::paintListBoxItem (int, Graphics&, int, int, bool)
  42758. {
  42759. }
  42760. Component* FileListComponent::refreshComponentForRow (int row, bool isSelected, Component* existingComponentToUpdate)
  42761. {
  42762. FileListItemComponent* comp = dynamic_cast <FileListItemComponent*> (existingComponentToUpdate);
  42763. if (comp == 0)
  42764. {
  42765. delete existingComponentToUpdate;
  42766. existingComponentToUpdate = comp = new FileListItemComponent (*this, fileList.getTimeSliceThread());
  42767. }
  42768. DirectoryContentsList::FileInfo fileInfo;
  42769. if (fileList.getFileInfo (row, fileInfo))
  42770. comp->update (fileList.getDirectory(), &fileInfo, row, isSelected);
  42771. else
  42772. comp->update (fileList.getDirectory(), 0, row, isSelected);
  42773. return comp;
  42774. }
  42775. void FileListComponent::selectedRowsChanged (int /*lastRowSelected*/)
  42776. {
  42777. sendSelectionChangeMessage();
  42778. }
  42779. void FileListComponent::deleteKeyPressed (int /*currentSelectedRow*/)
  42780. {
  42781. }
  42782. void FileListComponent::returnKeyPressed (int currentSelectedRow)
  42783. {
  42784. sendDoubleClickMessage (fileList.getFile (currentSelectedRow));
  42785. }
  42786. END_JUCE_NAMESPACE
  42787. /********* End of inlined file: juce_FileListComponent.cpp *********/
  42788. /********* Start of inlined file: juce_FilenameComponent.cpp *********/
  42789. BEGIN_JUCE_NAMESPACE
  42790. FilenameComponent::FilenameComponent (const String& name,
  42791. const File& currentFile,
  42792. const bool canEditFilename,
  42793. const bool isDirectory,
  42794. const bool isForSaving,
  42795. const String& fileBrowserWildcard,
  42796. const String& enforcedSuffix_,
  42797. const String& textWhenNothingSelected)
  42798. : Component (name),
  42799. maxRecentFiles (30),
  42800. isDir (isDirectory),
  42801. isSaving (isForSaving),
  42802. isFileDragOver (false),
  42803. wildcard (fileBrowserWildcard),
  42804. enforcedSuffix (enforcedSuffix_)
  42805. {
  42806. addAndMakeVisible (filenameBox = new ComboBox (T("fn")));
  42807. filenameBox->setEditableText (canEditFilename);
  42808. filenameBox->addListener (this);
  42809. filenameBox->setTextWhenNothingSelected (textWhenNothingSelected);
  42810. filenameBox->setTextWhenNoChoicesAvailable (TRANS("(no recently seleced files)"));
  42811. browseButton = 0;
  42812. setBrowseButtonText (T("..."));
  42813. setCurrentFile (currentFile, true);
  42814. }
  42815. FilenameComponent::~FilenameComponent()
  42816. {
  42817. deleteAllChildren();
  42818. }
  42819. void FilenameComponent::paintOverChildren (Graphics& g)
  42820. {
  42821. if (isFileDragOver)
  42822. {
  42823. g.setColour (Colours::red.withAlpha (0.2f));
  42824. g.drawRect (0, 0, getWidth(), getHeight(), 3);
  42825. }
  42826. }
  42827. void FilenameComponent::resized()
  42828. {
  42829. getLookAndFeel().layoutFilenameComponent (*this, filenameBox, browseButton);
  42830. }
  42831. void FilenameComponent::setBrowseButtonText (const String& newBrowseButtonText)
  42832. {
  42833. browseButtonText = newBrowseButtonText;
  42834. lookAndFeelChanged();
  42835. }
  42836. void FilenameComponent::lookAndFeelChanged()
  42837. {
  42838. deleteAndZero (browseButton);
  42839. addAndMakeVisible (browseButton = getLookAndFeel().createFilenameComponentBrowseButton (browseButtonText));
  42840. browseButton->setConnectedEdges (Button::ConnectedOnLeft);
  42841. resized();
  42842. browseButton->addButtonListener (this);
  42843. }
  42844. void FilenameComponent::setTooltip (const String& newTooltip)
  42845. {
  42846. SettableTooltipClient::setTooltip (newTooltip);
  42847. filenameBox->setTooltip (newTooltip);
  42848. }
  42849. void FilenameComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  42850. {
  42851. defaultBrowseFile = newDefaultDirectory;
  42852. }
  42853. void FilenameComponent::buttonClicked (Button*)
  42854. {
  42855. FileChooser fc (TRANS("Choose a new file"),
  42856. getCurrentFile() == File::nonexistent ? defaultBrowseFile
  42857. : getCurrentFile(),
  42858. wildcard);
  42859. if (isDir ? fc.browseForDirectory()
  42860. : (isSaving ? fc.browseForFileToSave (false)
  42861. : fc.browseForFileToOpen()))
  42862. {
  42863. setCurrentFile (fc.getResult(), true);
  42864. }
  42865. }
  42866. void FilenameComponent::comboBoxChanged (ComboBox*)
  42867. {
  42868. setCurrentFile (getCurrentFile(), true);
  42869. }
  42870. bool FilenameComponent::isInterestedInFileDrag (const StringArray&)
  42871. {
  42872. return true;
  42873. }
  42874. void FilenameComponent::filesDropped (const StringArray& filenames, int, int)
  42875. {
  42876. isFileDragOver = false;
  42877. repaint();
  42878. const File f (filenames[0]);
  42879. if (f.exists() && (f.isDirectory() == isDir))
  42880. setCurrentFile (f, true);
  42881. }
  42882. void FilenameComponent::fileDragEnter (const StringArray&, int, int)
  42883. {
  42884. isFileDragOver = true;
  42885. repaint();
  42886. }
  42887. void FilenameComponent::fileDragExit (const StringArray&)
  42888. {
  42889. isFileDragOver = false;
  42890. repaint();
  42891. }
  42892. const File FilenameComponent::getCurrentFile() const
  42893. {
  42894. File f (filenameBox->getText());
  42895. if (enforcedSuffix.isNotEmpty())
  42896. f = f.withFileExtension (enforcedSuffix);
  42897. return f;
  42898. }
  42899. void FilenameComponent::setCurrentFile (File newFile,
  42900. const bool addToRecentlyUsedList,
  42901. const bool sendChangeNotification)
  42902. {
  42903. if (enforcedSuffix.isNotEmpty())
  42904. newFile = newFile.withFileExtension (enforcedSuffix);
  42905. if (newFile.getFullPathName() != lastFilename)
  42906. {
  42907. lastFilename = newFile.getFullPathName();
  42908. if (addToRecentlyUsedList)
  42909. addRecentlyUsedFile (newFile);
  42910. filenameBox->setText (lastFilename, true);
  42911. if (sendChangeNotification)
  42912. triggerAsyncUpdate();
  42913. }
  42914. }
  42915. void FilenameComponent::setFilenameIsEditable (const bool shouldBeEditable)
  42916. {
  42917. filenameBox->setEditableText (shouldBeEditable);
  42918. }
  42919. const StringArray FilenameComponent::getRecentlyUsedFilenames() const
  42920. {
  42921. StringArray names;
  42922. for (int i = 0; i < filenameBox->getNumItems(); ++i)
  42923. names.add (filenameBox->getItemText (i));
  42924. return names;
  42925. }
  42926. void FilenameComponent::setRecentlyUsedFilenames (const StringArray& filenames)
  42927. {
  42928. if (filenames != getRecentlyUsedFilenames())
  42929. {
  42930. filenameBox->clear();
  42931. for (int i = 0; i < jmin (filenames.size(), maxRecentFiles); ++i)
  42932. filenameBox->addItem (filenames[i], i + 1);
  42933. }
  42934. }
  42935. void FilenameComponent::setMaxNumberOfRecentFiles (const int newMaximum)
  42936. {
  42937. maxRecentFiles = jmax (1, newMaximum);
  42938. setRecentlyUsedFilenames (getRecentlyUsedFilenames());
  42939. }
  42940. void FilenameComponent::addRecentlyUsedFile (const File& file)
  42941. {
  42942. StringArray files (getRecentlyUsedFilenames());
  42943. if (file.getFullPathName().isNotEmpty())
  42944. {
  42945. files.removeString (file.getFullPathName(), true);
  42946. files.insert (0, file.getFullPathName());
  42947. setRecentlyUsedFilenames (files);
  42948. }
  42949. }
  42950. void FilenameComponent::addListener (FilenameComponentListener* const listener) throw()
  42951. {
  42952. jassert (listener != 0);
  42953. if (listener != 0)
  42954. listeners.add (listener);
  42955. }
  42956. void FilenameComponent::removeListener (FilenameComponentListener* const listener) throw()
  42957. {
  42958. listeners.removeValue (listener);
  42959. }
  42960. void FilenameComponent::handleAsyncUpdate()
  42961. {
  42962. for (int i = listeners.size(); --i >= 0;)
  42963. {
  42964. ((FilenameComponentListener*) listeners.getUnchecked (i))->filenameComponentChanged (this);
  42965. i = jmin (i, listeners.size());
  42966. }
  42967. }
  42968. END_JUCE_NAMESPACE
  42969. /********* End of inlined file: juce_FilenameComponent.cpp *********/
  42970. /********* Start of inlined file: juce_FileSearchPathListComponent.cpp *********/
  42971. BEGIN_JUCE_NAMESPACE
  42972. FileSearchPathListComponent::FileSearchPathListComponent()
  42973. {
  42974. addAndMakeVisible (listBox = new ListBox (String::empty, this));
  42975. listBox->setColour (ListBox::backgroundColourId, Colours::black.withAlpha (0.02f));
  42976. listBox->setColour (ListBox::outlineColourId, Colours::black.withAlpha (0.1f));
  42977. listBox->setOutlineThickness (1);
  42978. addAndMakeVisible (addButton = new TextButton ("+"));
  42979. addButton->addButtonListener (this);
  42980. addButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  42981. addAndMakeVisible (removeButton = new TextButton ("-"));
  42982. removeButton->addButtonListener (this);
  42983. removeButton->setConnectedEdges (Button::ConnectedOnLeft | Button::ConnectedOnRight | Button::ConnectedOnBottom | Button::ConnectedOnTop);
  42984. addAndMakeVisible (changeButton = new TextButton (TRANS("change...")));
  42985. changeButton->addButtonListener (this);
  42986. addAndMakeVisible (upButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  42987. upButton->addButtonListener (this);
  42988. {
  42989. Path arrowPath;
  42990. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  42991. DrawablePath arrowImage;
  42992. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  42993. arrowImage.setPath (arrowPath);
  42994. ((DrawableButton*) upButton)->setImages (&arrowImage);
  42995. }
  42996. addAndMakeVisible (downButton = new DrawableButton (String::empty, DrawableButton::ImageOnButtonBackground));
  42997. downButton->addButtonListener (this);
  42998. {
  42999. Path arrowPath;
  43000. arrowPath.addArrow (50.0f, 0.0f, 50.0f, 100.0f, 40.0f, 100.0f, 50.0f);
  43001. DrawablePath arrowImage;
  43002. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  43003. arrowImage.setPath (arrowPath);
  43004. ((DrawableButton*) downButton)->setImages (&arrowImage);
  43005. }
  43006. updateButtons();
  43007. }
  43008. FileSearchPathListComponent::~FileSearchPathListComponent()
  43009. {
  43010. deleteAllChildren();
  43011. }
  43012. void FileSearchPathListComponent::updateButtons() throw()
  43013. {
  43014. const bool anythingSelected = listBox->getNumSelectedRows() > 0;
  43015. removeButton->setEnabled (anythingSelected);
  43016. changeButton->setEnabled (anythingSelected);
  43017. upButton->setEnabled (anythingSelected);
  43018. downButton->setEnabled (anythingSelected);
  43019. }
  43020. void FileSearchPathListComponent::changed() throw()
  43021. {
  43022. listBox->updateContent();
  43023. listBox->repaint();
  43024. updateButtons();
  43025. }
  43026. void FileSearchPathListComponent::setPath (const FileSearchPath& newPath)
  43027. {
  43028. if (newPath.toString() != path.toString())
  43029. {
  43030. path = newPath;
  43031. changed();
  43032. }
  43033. }
  43034. void FileSearchPathListComponent::setDefaultBrowseTarget (const File& newDefaultDirectory) throw()
  43035. {
  43036. defaultBrowseTarget = newDefaultDirectory;
  43037. }
  43038. int FileSearchPathListComponent::getNumRows()
  43039. {
  43040. return path.getNumPaths();
  43041. }
  43042. void FileSearchPathListComponent::paintListBoxItem (int rowNumber, Graphics& g, int width, int height, bool rowIsSelected)
  43043. {
  43044. if (rowIsSelected)
  43045. g.fillAll (findColour (TextEditor::highlightColourId));
  43046. g.setColour (findColour (ListBox::textColourId));
  43047. Font f (height * 0.7f);
  43048. f.setHorizontalScale (0.9f);
  43049. g.setFont (f);
  43050. g.drawText (path [rowNumber].getFullPathName(),
  43051. 4, 0, width - 6, height,
  43052. Justification::centredLeft, true);
  43053. }
  43054. void FileSearchPathListComponent::deleteKeyPressed (int row)
  43055. {
  43056. if (((unsigned int) row) < (unsigned int) path.getNumPaths())
  43057. {
  43058. path.remove (row);
  43059. changed();
  43060. }
  43061. }
  43062. void FileSearchPathListComponent::returnKeyPressed (int row)
  43063. {
  43064. FileChooser chooser (TRANS("Change folder..."), path [row], T("*"));
  43065. if (chooser.browseForDirectory())
  43066. {
  43067. path.remove (row);
  43068. path.add (chooser.getResult(), row);
  43069. changed();
  43070. }
  43071. }
  43072. void FileSearchPathListComponent::listBoxItemDoubleClicked (int row, const MouseEvent&)
  43073. {
  43074. returnKeyPressed (row);
  43075. }
  43076. void FileSearchPathListComponent::selectedRowsChanged (int)
  43077. {
  43078. updateButtons();
  43079. }
  43080. void FileSearchPathListComponent::paint (Graphics& g)
  43081. {
  43082. g.fillAll (findColour (backgroundColourId));
  43083. }
  43084. void FileSearchPathListComponent::resized()
  43085. {
  43086. const int buttonH = 22;
  43087. const int buttonY = getHeight() - buttonH - 4;
  43088. listBox->setBounds (2, 2, getWidth() - 4, buttonY - 5);
  43089. addButton->setBounds (2, buttonY, buttonH, buttonH);
  43090. removeButton->setBounds (addButton->getRight(), buttonY, buttonH, buttonH);
  43091. ((TextButton*) changeButton)->changeWidthToFitText (buttonH);
  43092. downButton->setSize (buttonH * 2, buttonH);
  43093. upButton->setSize (buttonH * 2, buttonH);
  43094. downButton->setTopRightPosition (getWidth() - 2, buttonY);
  43095. upButton->setTopRightPosition (downButton->getX() - 4, buttonY);
  43096. changeButton->setTopRightPosition (upButton->getX() - 8, buttonY);
  43097. }
  43098. bool FileSearchPathListComponent::isInterestedInFileDrag (const StringArray&)
  43099. {
  43100. return true;
  43101. }
  43102. void FileSearchPathListComponent::filesDropped (const StringArray& filenames, int, int mouseY)
  43103. {
  43104. for (int i = filenames.size(); --i >= 0;)
  43105. {
  43106. const File f (filenames[i]);
  43107. if (f.isDirectory())
  43108. {
  43109. const int row = listBox->getRowContainingPosition (0, mouseY - listBox->getY());
  43110. path.add (f, row);
  43111. changed();
  43112. }
  43113. }
  43114. }
  43115. void FileSearchPathListComponent::buttonClicked (Button* button)
  43116. {
  43117. const int currentRow = listBox->getSelectedRow();
  43118. if (button == removeButton)
  43119. {
  43120. deleteKeyPressed (currentRow);
  43121. }
  43122. else if (button == addButton)
  43123. {
  43124. File start (defaultBrowseTarget);
  43125. if (start == File::nonexistent)
  43126. start = path [0];
  43127. if (start == File::nonexistent)
  43128. start = File::getCurrentWorkingDirectory();
  43129. FileChooser chooser (TRANS("Add a folder..."), start, T("*"));
  43130. if (chooser.browseForDirectory())
  43131. {
  43132. path.add (chooser.getResult(), currentRow);
  43133. }
  43134. }
  43135. else if (button == changeButton)
  43136. {
  43137. returnKeyPressed (currentRow);
  43138. }
  43139. else if (button == upButton)
  43140. {
  43141. if (currentRow > 0 && currentRow < path.getNumPaths())
  43142. {
  43143. const File f (path[currentRow]);
  43144. path.remove (currentRow);
  43145. path.add (f, currentRow - 1);
  43146. listBox->selectRow (currentRow - 1);
  43147. }
  43148. }
  43149. else if (button == downButton)
  43150. {
  43151. if (currentRow >= 0 && currentRow < path.getNumPaths() - 1)
  43152. {
  43153. const File f (path[currentRow]);
  43154. path.remove (currentRow);
  43155. path.add (f, currentRow + 1);
  43156. listBox->selectRow (currentRow + 1);
  43157. }
  43158. }
  43159. changed();
  43160. }
  43161. END_JUCE_NAMESPACE
  43162. /********* End of inlined file: juce_FileSearchPathListComponent.cpp *********/
  43163. /********* Start of inlined file: juce_FileTreeComponent.cpp *********/
  43164. BEGIN_JUCE_NAMESPACE
  43165. Image* juce_createIconForFile (const File& file);
  43166. class FileListTreeItem : public TreeViewItem,
  43167. public TimeSliceClient,
  43168. public AsyncUpdater,
  43169. public ChangeListener
  43170. {
  43171. public:
  43172. FileListTreeItem (FileTreeComponent& owner_,
  43173. DirectoryContentsList* const parentContentsList_,
  43174. const int indexInContentsList_,
  43175. const File& file_,
  43176. TimeSliceThread& thread_) throw()
  43177. : file (file_),
  43178. owner (owner_),
  43179. parentContentsList (parentContentsList_),
  43180. indexInContentsList (indexInContentsList_),
  43181. subContentsList (0),
  43182. canDeleteSubContentsList (false),
  43183. thread (thread_),
  43184. icon (0)
  43185. {
  43186. DirectoryContentsList::FileInfo fileInfo;
  43187. if (parentContentsList_ != 0
  43188. && parentContentsList_->getFileInfo (indexInContentsList_, fileInfo))
  43189. {
  43190. fileSize = File::descriptionOfSizeInBytes (fileInfo.fileSize);
  43191. modTime = fileInfo.modificationTime.formatted (T("%d %b '%y %H:%M"));
  43192. isDirectory = fileInfo.isDirectory;
  43193. }
  43194. else
  43195. {
  43196. isDirectory = true;
  43197. }
  43198. }
  43199. ~FileListTreeItem() throw()
  43200. {
  43201. thread.removeTimeSliceClient (this);
  43202. clearSubItems();
  43203. ImageCache::release (icon);
  43204. if (canDeleteSubContentsList)
  43205. delete subContentsList;
  43206. }
  43207. bool mightContainSubItems() { return isDirectory; }
  43208. const String getUniqueName() const { return file.getFullPathName(); }
  43209. int getItemHeight() const { return 22; }
  43210. const String getDragSourceDescription() { return owner.getDragAndDropDescription(); }
  43211. void itemOpennessChanged (bool isNowOpen)
  43212. {
  43213. if (isNowOpen)
  43214. {
  43215. clearSubItems();
  43216. isDirectory = file.isDirectory();
  43217. if (isDirectory)
  43218. {
  43219. if (subContentsList == 0)
  43220. {
  43221. jassert (parentContentsList != 0);
  43222. DirectoryContentsList* const l = new DirectoryContentsList (parentContentsList->getFilter(), thread);
  43223. l->setDirectory (file, true, true);
  43224. setSubContentsList (l);
  43225. canDeleteSubContentsList = true;
  43226. }
  43227. changeListenerCallback (0);
  43228. }
  43229. }
  43230. }
  43231. void setSubContentsList (DirectoryContentsList* newList) throw()
  43232. {
  43233. jassert (subContentsList == 0);
  43234. subContentsList = newList;
  43235. newList->addChangeListener (this);
  43236. }
  43237. void changeListenerCallback (void*)
  43238. {
  43239. clearSubItems();
  43240. if (isOpen() && subContentsList != 0)
  43241. {
  43242. for (int i = 0; i < subContentsList->getNumFiles(); ++i)
  43243. {
  43244. FileListTreeItem* const item
  43245. = new FileListTreeItem (owner, subContentsList, i, subContentsList->getFile(i), thread);
  43246. addSubItem (item);
  43247. }
  43248. }
  43249. }
  43250. void paintItem (Graphics& g, int width, int height)
  43251. {
  43252. if (file != File::nonexistent && ! isDirectory)
  43253. {
  43254. updateIcon (true);
  43255. if (icon == 0)
  43256. thread.addTimeSliceClient (this);
  43257. }
  43258. owner.getLookAndFeel()
  43259. .drawFileBrowserRow (g, width, height,
  43260. file.getFileName(),
  43261. icon,
  43262. fileSize, modTime,
  43263. isDirectory, isSelected(),
  43264. indexInContentsList);
  43265. }
  43266. void itemClicked (const MouseEvent& e)
  43267. {
  43268. owner.sendMouseClickMessage (file, e);
  43269. }
  43270. void itemDoubleClicked (const MouseEvent& e)
  43271. {
  43272. TreeViewItem::itemDoubleClicked (e);
  43273. owner.sendDoubleClickMessage (file);
  43274. }
  43275. void itemSelectionChanged (bool)
  43276. {
  43277. owner.sendSelectionChangeMessage();
  43278. }
  43279. bool useTimeSlice()
  43280. {
  43281. updateIcon (false);
  43282. thread.removeTimeSliceClient (this);
  43283. return false;
  43284. }
  43285. void handleAsyncUpdate()
  43286. {
  43287. owner.repaint();
  43288. }
  43289. const File file;
  43290. juce_UseDebuggingNewOperator
  43291. private:
  43292. FileTreeComponent& owner;
  43293. DirectoryContentsList* parentContentsList;
  43294. int indexInContentsList;
  43295. DirectoryContentsList* subContentsList;
  43296. bool isDirectory, canDeleteSubContentsList;
  43297. TimeSliceThread& thread;
  43298. Image* icon;
  43299. String fileSize;
  43300. String modTime;
  43301. void updateIcon (const bool onlyUpdateIfCached) throw()
  43302. {
  43303. if (icon == 0)
  43304. {
  43305. const int hashCode = (file.getFullPathName() + T("_iconCacheSalt")).hashCode();
  43306. Image* im = ImageCache::getFromHashCode (hashCode);
  43307. if (im == 0 && ! onlyUpdateIfCached)
  43308. {
  43309. im = juce_createIconForFile (file);
  43310. if (im != 0)
  43311. ImageCache::addImageToCache (im, hashCode);
  43312. }
  43313. if (im != 0)
  43314. {
  43315. icon = im;
  43316. triggerAsyncUpdate();
  43317. }
  43318. }
  43319. }
  43320. };
  43321. FileTreeComponent::FileTreeComponent (DirectoryContentsList& listToShow)
  43322. : DirectoryContentsDisplayComponent (listToShow)
  43323. {
  43324. FileListTreeItem* const root
  43325. = new FileListTreeItem (*this, 0, 0, listToShow.getDirectory(),
  43326. listToShow.getTimeSliceThread());
  43327. root->setSubContentsList (&listToShow);
  43328. setRootItemVisible (false);
  43329. setRootItem (root);
  43330. }
  43331. FileTreeComponent::~FileTreeComponent()
  43332. {
  43333. TreeViewItem* const root = getRootItem();
  43334. setRootItem (0);
  43335. delete root;
  43336. }
  43337. const File FileTreeComponent::getSelectedFile() const
  43338. {
  43339. return getSelectedFile (0);
  43340. }
  43341. const File FileTreeComponent::getSelectedFile (const int index) const throw()
  43342. {
  43343. const FileListTreeItem* const item = dynamic_cast <const FileListTreeItem*> (getSelectedItem (index));
  43344. if (item != 0)
  43345. return item->file;
  43346. return File::nonexistent;
  43347. }
  43348. void FileTreeComponent::scrollToTop()
  43349. {
  43350. getViewport()->getVerticalScrollBar()->setCurrentRangeStart (0);
  43351. }
  43352. void FileTreeComponent::setDragAndDropDescription (const String& description) throw()
  43353. {
  43354. dragAndDropDescription = description;
  43355. }
  43356. END_JUCE_NAMESPACE
  43357. /********* End of inlined file: juce_FileTreeComponent.cpp *********/
  43358. /********* Start of inlined file: juce_ImagePreviewComponent.cpp *********/
  43359. BEGIN_JUCE_NAMESPACE
  43360. ImagePreviewComponent::ImagePreviewComponent()
  43361. : currentThumbnail (0)
  43362. {
  43363. }
  43364. ImagePreviewComponent::~ImagePreviewComponent()
  43365. {
  43366. delete currentThumbnail;
  43367. }
  43368. void ImagePreviewComponent::getThumbSize (int& w, int& h) const
  43369. {
  43370. const int availableW = proportionOfWidth (0.97f);
  43371. const int availableH = getHeight() - 13 * 4;
  43372. const double scale = jmin (1.0,
  43373. availableW / (double) w,
  43374. availableH / (double) h);
  43375. w = roundDoubleToInt (scale * w);
  43376. h = roundDoubleToInt (scale * h);
  43377. }
  43378. void ImagePreviewComponent::selectedFileChanged (const File& file)
  43379. {
  43380. if (fileToLoad != file)
  43381. {
  43382. fileToLoad = file;
  43383. startTimer (100);
  43384. }
  43385. }
  43386. void ImagePreviewComponent::timerCallback()
  43387. {
  43388. stopTimer();
  43389. deleteAndZero (currentThumbnail);
  43390. currentDetails = String::empty;
  43391. repaint();
  43392. FileInputStream* const in = fileToLoad.createInputStream();
  43393. if (in != 0)
  43394. {
  43395. ImageFileFormat* const format = ImageFileFormat::findImageFormatForStream (*in);
  43396. if (format != 0)
  43397. {
  43398. currentThumbnail = format->decodeImage (*in);
  43399. if (currentThumbnail != 0)
  43400. {
  43401. int w = currentThumbnail->getWidth();
  43402. int h = currentThumbnail->getHeight();
  43403. currentDetails
  43404. << fileToLoad.getFileName() << "\n"
  43405. << format->getFormatName() << "\n"
  43406. << w << " x " << h << " pixels\n"
  43407. << File::descriptionOfSizeInBytes (fileToLoad.getSize());
  43408. getThumbSize (w, h);
  43409. Image* const reduced = currentThumbnail->createCopy (w, h);
  43410. delete currentThumbnail;
  43411. currentThumbnail = reduced;
  43412. }
  43413. }
  43414. delete in;
  43415. }
  43416. }
  43417. void ImagePreviewComponent::paint (Graphics& g)
  43418. {
  43419. if (currentThumbnail != 0)
  43420. {
  43421. g.setFont (13.0f);
  43422. int w = currentThumbnail->getWidth();
  43423. int h = currentThumbnail->getHeight();
  43424. getThumbSize (w, h);
  43425. const int numLines = 4;
  43426. const int totalH = 13 * numLines + h + 4;
  43427. const int y = (getHeight() - totalH) / 2;
  43428. g.drawImageWithin (currentThumbnail,
  43429. (getWidth() - w) / 2, y, w, h,
  43430. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  43431. false);
  43432. g.drawFittedText (currentDetails,
  43433. 0, y + h + 4, getWidth(), 100,
  43434. Justification::centredTop, numLines);
  43435. }
  43436. }
  43437. END_JUCE_NAMESPACE
  43438. /********* End of inlined file: juce_ImagePreviewComponent.cpp *********/
  43439. /********* Start of inlined file: juce_WildcardFileFilter.cpp *********/
  43440. BEGIN_JUCE_NAMESPACE
  43441. WildcardFileFilter::WildcardFileFilter (const String& wildcardPatterns,
  43442. const String& description)
  43443. : FileFilter (description.isEmpty() ? wildcardPatterns
  43444. : (description + T(" (") + wildcardPatterns + T(")")))
  43445. {
  43446. wildcards.addTokens (wildcardPatterns.toLowerCase(), T(";,"), T("\"'"));
  43447. wildcards.trim();
  43448. wildcards.removeEmptyStrings();
  43449. // special case for *.*, because people use it to mean "any file", but it
  43450. // would actually ignore files with no extension.
  43451. for (int i = wildcards.size(); --i >= 0;)
  43452. if (wildcards[i] == T("*.*"))
  43453. wildcards.set (i, T("*"));
  43454. }
  43455. WildcardFileFilter::~WildcardFileFilter()
  43456. {
  43457. }
  43458. bool WildcardFileFilter::isFileSuitable (const File& file) const
  43459. {
  43460. const String filename (file.getFileName());
  43461. for (int i = wildcards.size(); --i >= 0;)
  43462. if (filename.matchesWildcard (wildcards[i], true))
  43463. return true;
  43464. return false;
  43465. }
  43466. bool WildcardFileFilter::isDirectorySuitable (const File&) const
  43467. {
  43468. return true;
  43469. }
  43470. END_JUCE_NAMESPACE
  43471. /********* End of inlined file: juce_WildcardFileFilter.cpp *********/
  43472. /********* Start of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  43473. BEGIN_JUCE_NAMESPACE
  43474. KeyboardFocusTraverser::KeyboardFocusTraverser()
  43475. {
  43476. }
  43477. KeyboardFocusTraverser::~KeyboardFocusTraverser()
  43478. {
  43479. }
  43480. // This will sort a set of components, so that they are ordered in terms of
  43481. // left-to-right and then top-to-bottom.
  43482. class ScreenPositionComparator
  43483. {
  43484. public:
  43485. ScreenPositionComparator() {}
  43486. static int compareElements (const Component* const first, const Component* const second) throw()
  43487. {
  43488. int explicitOrder1 = first->getExplicitFocusOrder();
  43489. if (explicitOrder1 <= 0)
  43490. explicitOrder1 = INT_MAX / 2;
  43491. int explicitOrder2 = second->getExplicitFocusOrder();
  43492. if (explicitOrder2 <= 0)
  43493. explicitOrder2 = INT_MAX / 2;
  43494. if (explicitOrder1 != explicitOrder2)
  43495. return explicitOrder1 - explicitOrder2;
  43496. const int diff = first->getY() - second->getY();
  43497. return (diff == 0) ? first->getX() - second->getX()
  43498. : diff;
  43499. }
  43500. };
  43501. static void findAllFocusableComponents (Component* const parent, Array <Component*>& comps)
  43502. {
  43503. if (parent->getNumChildComponents() > 0)
  43504. {
  43505. Array <Component*> localComps;
  43506. ScreenPositionComparator comparator;
  43507. int i;
  43508. for (i = parent->getNumChildComponents(); --i >= 0;)
  43509. {
  43510. Component* const c = parent->getChildComponent (i);
  43511. if (c->isVisible() && c->isEnabled())
  43512. localComps.addSorted (comparator, c);
  43513. }
  43514. for (i = 0; i < localComps.size(); ++i)
  43515. {
  43516. Component* const c = localComps.getUnchecked (i);
  43517. if (c->getWantsKeyboardFocus())
  43518. comps.add (c);
  43519. if (! c->isFocusContainer())
  43520. findAllFocusableComponents (c, comps);
  43521. }
  43522. }
  43523. }
  43524. static Component* getIncrementedComponent (Component* const current, const int delta) throw()
  43525. {
  43526. Component* focusContainer = current->getParentComponent();
  43527. if (focusContainer != 0)
  43528. {
  43529. while (focusContainer->getParentComponent() != 0 && ! focusContainer->isFocusContainer())
  43530. focusContainer = focusContainer->getParentComponent();
  43531. if (focusContainer != 0)
  43532. {
  43533. Array <Component*> comps;
  43534. findAllFocusableComponents (focusContainer, comps);
  43535. if (comps.size() > 0)
  43536. {
  43537. const int index = comps.indexOf (current);
  43538. return comps [(index + comps.size() + delta) % comps.size()];
  43539. }
  43540. }
  43541. }
  43542. return 0;
  43543. }
  43544. Component* KeyboardFocusTraverser::getNextComponent (Component* current)
  43545. {
  43546. return getIncrementedComponent (current, 1);
  43547. }
  43548. Component* KeyboardFocusTraverser::getPreviousComponent (Component* current)
  43549. {
  43550. return getIncrementedComponent (current, -1);
  43551. }
  43552. Component* KeyboardFocusTraverser::getDefaultComponent (Component* parentComponent)
  43553. {
  43554. Array <Component*> comps;
  43555. if (parentComponent != 0)
  43556. findAllFocusableComponents (parentComponent, comps);
  43557. return comps.getFirst();
  43558. }
  43559. END_JUCE_NAMESPACE
  43560. /********* End of inlined file: juce_KeyboardFocusTraverser.cpp *********/
  43561. /********* Start of inlined file: juce_KeyListener.cpp *********/
  43562. BEGIN_JUCE_NAMESPACE
  43563. bool KeyListener::keyStateChanged (Component*)
  43564. {
  43565. return false;
  43566. }
  43567. END_JUCE_NAMESPACE
  43568. /********* End of inlined file: juce_KeyListener.cpp *********/
  43569. /********* Start of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  43570. BEGIN_JUCE_NAMESPACE
  43571. // N.B. these two includes are put here deliberately to avoid problems with
  43572. // old GCCs failing on long include paths
  43573. const int maxKeys = 3;
  43574. class KeyMappingChangeButton : public Button
  43575. {
  43576. public:
  43577. KeyMappingChangeButton (KeyMappingEditorComponent* const owner_,
  43578. const CommandID commandID_,
  43579. const String& keyName,
  43580. const int keyNum_)
  43581. : Button (keyName),
  43582. owner (owner_),
  43583. commandID (commandID_),
  43584. keyNum (keyNum_)
  43585. {
  43586. setWantsKeyboardFocus (false);
  43587. setTriggeredOnMouseDown (keyNum >= 0);
  43588. if (keyNum_ < 0)
  43589. setTooltip (TRANS("adds a new key-mapping"));
  43590. else
  43591. setTooltip (TRANS("click to change this key-mapping"));
  43592. }
  43593. ~KeyMappingChangeButton()
  43594. {
  43595. }
  43596. void paintButton (Graphics& g, bool isOver, bool isDown)
  43597. {
  43598. if (keyNum >= 0)
  43599. {
  43600. if (isEnabled())
  43601. {
  43602. const float alpha = isDown ? 0.3f : (isOver ? 0.15f : 0.08f);
  43603. g.fillAll (owner->textColour.withAlpha (alpha));
  43604. g.setOpacity (0.3f);
  43605. g.drawBevel (0, 0, getWidth(), getHeight(), 2);
  43606. }
  43607. g.setColour (owner->textColour);
  43608. g.setFont (getHeight() * 0.6f);
  43609. g.drawFittedText (getName(),
  43610. 3, 0, getWidth() - 6, getHeight(),
  43611. Justification::centred, 1);
  43612. }
  43613. else
  43614. {
  43615. const float thickness = 7.0f;
  43616. const float indent = 22.0f;
  43617. Path p;
  43618. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  43619. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  43620. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  43621. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  43622. p.setUsingNonZeroWinding (false);
  43623. g.setColour (owner->textColour.withAlpha (isDown ? 0.7f : (isOver ? 0.5f : 0.3f)));
  43624. g.fillPath (p, p.getTransformToScaleToFit (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, true));
  43625. }
  43626. if (hasKeyboardFocus (false))
  43627. {
  43628. g.setColour (owner->textColour.withAlpha (0.4f));
  43629. g.drawRect (0, 0, getWidth(), getHeight());
  43630. }
  43631. }
  43632. void clicked()
  43633. {
  43634. if (keyNum >= 0)
  43635. {
  43636. // existing key clicked..
  43637. PopupMenu m;
  43638. m.addItem (1, TRANS("change this key-mapping"));
  43639. m.addSeparator();
  43640. m.addItem (2, TRANS("remove this key-mapping"));
  43641. const int res = m.show();
  43642. if (res == 1)
  43643. {
  43644. owner->assignNewKey (commandID, keyNum);
  43645. }
  43646. else if (res == 2)
  43647. {
  43648. owner->getMappings()->removeKeyPress (commandID, keyNum);
  43649. }
  43650. }
  43651. else
  43652. {
  43653. // + button pressed..
  43654. owner->assignNewKey (commandID, -1);
  43655. }
  43656. }
  43657. void fitToContent (const int h) throw()
  43658. {
  43659. if (keyNum < 0)
  43660. {
  43661. setSize (h, h);
  43662. }
  43663. else
  43664. {
  43665. Font f (h * 0.6f);
  43666. setSize (jlimit (h * 4, h * 8, 6 + f.getStringWidth (getName())), h);
  43667. }
  43668. }
  43669. juce_UseDebuggingNewOperator
  43670. private:
  43671. KeyMappingEditorComponent* const owner;
  43672. const CommandID commandID;
  43673. const int keyNum;
  43674. KeyMappingChangeButton (const KeyMappingChangeButton&);
  43675. const KeyMappingChangeButton& operator= (const KeyMappingChangeButton&);
  43676. };
  43677. class KeyMappingItemComponent : public Component
  43678. {
  43679. public:
  43680. KeyMappingItemComponent (KeyMappingEditorComponent* const owner_,
  43681. const CommandID commandID_)
  43682. : owner (owner_),
  43683. commandID (commandID_)
  43684. {
  43685. setInterceptsMouseClicks (false, true);
  43686. const bool isReadOnly = owner_->isCommandReadOnly (commandID);
  43687. const Array <KeyPress> keyPresses (owner_->getMappings()->getKeyPressesAssignedToCommand (commandID));
  43688. for (int i = 0; i < jmin (maxKeys, keyPresses.size()); ++i)
  43689. {
  43690. KeyMappingChangeButton* const kb
  43691. = new KeyMappingChangeButton (owner_, commandID,
  43692. owner_->getDescriptionForKeyPress (keyPresses.getReference (i)), i);
  43693. kb->setEnabled (! isReadOnly);
  43694. addAndMakeVisible (kb);
  43695. }
  43696. KeyMappingChangeButton* const kb
  43697. = new KeyMappingChangeButton (owner_, commandID, String::empty, -1);
  43698. addChildComponent (kb);
  43699. kb->setVisible (keyPresses.size() < maxKeys && ! isReadOnly);
  43700. }
  43701. ~KeyMappingItemComponent()
  43702. {
  43703. deleteAllChildren();
  43704. }
  43705. void paint (Graphics& g)
  43706. {
  43707. g.setFont (getHeight() * 0.7f);
  43708. g.setColour (owner->textColour);
  43709. g.drawFittedText (owner->getMappings()->getCommandManager()->getNameOfCommand (commandID),
  43710. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  43711. Justification::centredLeft, true);
  43712. }
  43713. void resized()
  43714. {
  43715. int x = getWidth() - 4;
  43716. for (int i = getNumChildComponents(); --i >= 0;)
  43717. {
  43718. KeyMappingChangeButton* const kb = dynamic_cast <KeyMappingChangeButton*> (getChildComponent (i));
  43719. kb->fitToContent (getHeight() - 2);
  43720. kb->setTopRightPosition (x, 1);
  43721. x -= kb->getWidth() + 5;
  43722. }
  43723. }
  43724. juce_UseDebuggingNewOperator
  43725. private:
  43726. KeyMappingEditorComponent* const owner;
  43727. const CommandID commandID;
  43728. KeyMappingItemComponent (const KeyMappingItemComponent&);
  43729. const KeyMappingItemComponent& operator= (const KeyMappingItemComponent&);
  43730. };
  43731. class KeyMappingTreeViewItem : public TreeViewItem
  43732. {
  43733. public:
  43734. KeyMappingTreeViewItem (KeyMappingEditorComponent* const owner_,
  43735. const CommandID commandID_)
  43736. : owner (owner_),
  43737. commandID (commandID_)
  43738. {
  43739. }
  43740. ~KeyMappingTreeViewItem()
  43741. {
  43742. }
  43743. const String getUniqueName() const { return String ((int) commandID) + "_id"; }
  43744. bool mightContainSubItems() { return false; }
  43745. int getItemHeight() const { return 20; }
  43746. Component* createItemComponent()
  43747. {
  43748. return new KeyMappingItemComponent (owner, commandID);
  43749. }
  43750. juce_UseDebuggingNewOperator
  43751. private:
  43752. KeyMappingEditorComponent* const owner;
  43753. const CommandID commandID;
  43754. KeyMappingTreeViewItem (const KeyMappingTreeViewItem&);
  43755. const KeyMappingTreeViewItem& operator= (const KeyMappingTreeViewItem&);
  43756. };
  43757. class KeyCategoryTreeViewItem : public TreeViewItem
  43758. {
  43759. public:
  43760. KeyCategoryTreeViewItem (KeyMappingEditorComponent* const owner_,
  43761. const String& name)
  43762. : owner (owner_),
  43763. categoryName (name)
  43764. {
  43765. }
  43766. ~KeyCategoryTreeViewItem()
  43767. {
  43768. }
  43769. const String getUniqueName() const { return categoryName + "_cat"; }
  43770. bool mightContainSubItems() { return true; }
  43771. int getItemHeight() const { return 28; }
  43772. void paintItem (Graphics& g, int width, int height)
  43773. {
  43774. g.setFont (height * 0.6f, Font::bold);
  43775. g.setColour (owner->textColour);
  43776. g.drawText (categoryName,
  43777. 2, 0, width - 2, height,
  43778. Justification::centredLeft, true);
  43779. }
  43780. void itemOpennessChanged (bool isNowOpen)
  43781. {
  43782. if (isNowOpen)
  43783. {
  43784. if (getNumSubItems() == 0)
  43785. {
  43786. Array <CommandID> commands (owner->getMappings()->getCommandManager()->getCommandsInCategory (categoryName));
  43787. for (int i = 0; i < commands.size(); ++i)
  43788. {
  43789. if (owner->shouldCommandBeIncluded (commands[i]))
  43790. addSubItem (new KeyMappingTreeViewItem (owner, commands[i]));
  43791. }
  43792. }
  43793. }
  43794. else
  43795. {
  43796. clearSubItems();
  43797. }
  43798. }
  43799. juce_UseDebuggingNewOperator
  43800. private:
  43801. KeyMappingEditorComponent* owner;
  43802. String categoryName;
  43803. KeyCategoryTreeViewItem (const KeyCategoryTreeViewItem&);
  43804. const KeyCategoryTreeViewItem& operator= (const KeyCategoryTreeViewItem&);
  43805. };
  43806. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet* const mappingManager,
  43807. const bool showResetToDefaultButton)
  43808. : mappings (mappingManager),
  43809. textColour (Colours::black)
  43810. {
  43811. jassert (mappingManager != 0); // can't be null!
  43812. mappingManager->addChangeListener (this);
  43813. setLinesDrawnForSubItems (false);
  43814. resetButton = 0;
  43815. if (showResetToDefaultButton)
  43816. {
  43817. addAndMakeVisible (resetButton = new TextButton (TRANS("reset to defaults")));
  43818. resetButton->addButtonListener (this);
  43819. }
  43820. addAndMakeVisible (tree = new TreeView());
  43821. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  43822. tree->setRootItemVisible (false);
  43823. tree->setDefaultOpenness (true);
  43824. tree->setRootItem (this);
  43825. }
  43826. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  43827. {
  43828. mappings->removeChangeListener (this);
  43829. deleteAllChildren();
  43830. }
  43831. bool KeyMappingEditorComponent::mightContainSubItems()
  43832. {
  43833. return true;
  43834. }
  43835. const String KeyMappingEditorComponent::getUniqueName() const
  43836. {
  43837. return T("keys");
  43838. }
  43839. void KeyMappingEditorComponent::setColours (const Colour& mainBackground,
  43840. const Colour& textColour_)
  43841. {
  43842. backgroundColour = mainBackground;
  43843. textColour = textColour_;
  43844. tree->setColour (TreeView::backgroundColourId, backgroundColour);
  43845. }
  43846. void KeyMappingEditorComponent::parentHierarchyChanged()
  43847. {
  43848. changeListenerCallback (0);
  43849. }
  43850. void KeyMappingEditorComponent::resized()
  43851. {
  43852. int h = getHeight();
  43853. if (resetButton != 0)
  43854. {
  43855. const int buttonHeight = 20;
  43856. h -= buttonHeight + 8;
  43857. int x = getWidth() - 8;
  43858. const int y = h + 6;
  43859. resetButton->changeWidthToFitText (buttonHeight);
  43860. resetButton->setTopRightPosition (x, y);
  43861. }
  43862. tree->setBounds (0, 0, getWidth(), h);
  43863. }
  43864. void KeyMappingEditorComponent::buttonClicked (Button* button)
  43865. {
  43866. if (button == resetButton)
  43867. {
  43868. if (AlertWindow::showOkCancelBox (AlertWindow::QuestionIcon,
  43869. TRANS("Reset to defaults"),
  43870. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  43871. TRANS("Reset")))
  43872. {
  43873. mappings->resetToDefaultMappings();
  43874. }
  43875. }
  43876. }
  43877. void KeyMappingEditorComponent::changeListenerCallback (void*)
  43878. {
  43879. XmlElement* openness = tree->getOpennessState (true);
  43880. clearSubItems();
  43881. const StringArray categories (mappings->getCommandManager()->getCommandCategories());
  43882. for (int i = 0; i < categories.size(); ++i)
  43883. {
  43884. const Array <CommandID> commands (mappings->getCommandManager()->getCommandsInCategory (categories[i]));
  43885. int count = 0;
  43886. for (int j = 0; j < commands.size(); ++j)
  43887. if (shouldCommandBeIncluded (commands[j]))
  43888. ++count;
  43889. if (count > 0)
  43890. addSubItem (new KeyCategoryTreeViewItem (this, categories[i]));
  43891. }
  43892. if (openness != 0)
  43893. {
  43894. tree->restoreOpennessState (*openness);
  43895. delete openness;
  43896. }
  43897. }
  43898. class KeyEntryWindow : public AlertWindow
  43899. {
  43900. public:
  43901. KeyEntryWindow (KeyMappingEditorComponent* const owner_)
  43902. : AlertWindow (TRANS("New key-mapping"),
  43903. TRANS("Please press a key combination now..."),
  43904. AlertWindow::NoIcon),
  43905. owner (owner_)
  43906. {
  43907. addButton (TRANS("ok"), 1);
  43908. addButton (TRANS("cancel"), 0);
  43909. // (avoid return + escape keys getting processed by the buttons..)
  43910. for (int i = getNumChildComponents(); --i >= 0;)
  43911. getChildComponent (i)->setWantsKeyboardFocus (false);
  43912. setWantsKeyboardFocus (true);
  43913. grabKeyboardFocus();
  43914. }
  43915. ~KeyEntryWindow()
  43916. {
  43917. }
  43918. bool keyPressed (const KeyPress& key)
  43919. {
  43920. lastPress = key;
  43921. String message (TRANS("Key: ") + owner->getDescriptionForKeyPress (key));
  43922. const CommandID previousCommand = owner->getMappings()->findCommandForKeyPress (key);
  43923. if (previousCommand != 0)
  43924. {
  43925. message << "\n\n"
  43926. << TRANS("(Currently assigned to \"")
  43927. << owner->getMappings()->getCommandManager()->getNameOfCommand (previousCommand)
  43928. << "\")";
  43929. }
  43930. setMessage (message);
  43931. return true;
  43932. }
  43933. bool keyStateChanged()
  43934. {
  43935. return true;
  43936. }
  43937. KeyPress lastPress;
  43938. juce_UseDebuggingNewOperator
  43939. private:
  43940. KeyMappingEditorComponent* owner;
  43941. KeyEntryWindow (const KeyEntryWindow&);
  43942. const KeyEntryWindow& operator= (const KeyEntryWindow&);
  43943. };
  43944. void KeyMappingEditorComponent::assignNewKey (const CommandID commandID, const int index)
  43945. {
  43946. KeyEntryWindow entryWindow (this);
  43947. if (entryWindow.runModalLoop() != 0)
  43948. {
  43949. entryWindow.setVisible (false);
  43950. if (entryWindow.lastPress.isValid())
  43951. {
  43952. const CommandID previousCommand = mappings->findCommandForKeyPress (entryWindow.lastPress);
  43953. if (previousCommand != 0)
  43954. {
  43955. if (! AlertWindow::showOkCancelBox (AlertWindow::WarningIcon,
  43956. TRANS("Change key-mapping"),
  43957. TRANS("This key is already assigned to the command \"")
  43958. + mappings->getCommandManager()->getNameOfCommand (previousCommand)
  43959. + TRANS("\"\n\nDo you want to re-assign it to this new command instead?"),
  43960. TRANS("re-assign"),
  43961. TRANS("cancel")))
  43962. {
  43963. return;
  43964. }
  43965. }
  43966. mappings->removeKeyPress (entryWindow.lastPress);
  43967. if (index >= 0)
  43968. mappings->removeKeyPress (commandID, index);
  43969. mappings->addKeyPress (commandID, entryWindow.lastPress, index);
  43970. }
  43971. }
  43972. }
  43973. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  43974. {
  43975. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  43976. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0);
  43977. }
  43978. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  43979. {
  43980. const ApplicationCommandInfo* const ci = mappings->getCommandManager()->getCommandForID (commandID);
  43981. return (ci != 0) && ((ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0);
  43982. }
  43983. const String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  43984. {
  43985. return key.getTextDescription();
  43986. }
  43987. END_JUCE_NAMESPACE
  43988. /********* End of inlined file: juce_KeyMappingEditorComponent.cpp *********/
  43989. /********* Start of inlined file: juce_KeyPress.cpp *********/
  43990. BEGIN_JUCE_NAMESPACE
  43991. KeyPress::KeyPress() throw()
  43992. : keyCode (0),
  43993. mods (0),
  43994. textCharacter (0)
  43995. {
  43996. }
  43997. KeyPress::KeyPress (const int keyCode_,
  43998. const ModifierKeys& mods_,
  43999. const juce_wchar textCharacter_) throw()
  44000. : keyCode (keyCode_),
  44001. mods (mods_),
  44002. textCharacter (textCharacter_)
  44003. {
  44004. }
  44005. KeyPress::KeyPress (const int keyCode_) throw()
  44006. : keyCode (keyCode_),
  44007. textCharacter (0)
  44008. {
  44009. }
  44010. KeyPress::KeyPress (const KeyPress& other) throw()
  44011. : keyCode (other.keyCode),
  44012. mods (other.mods),
  44013. textCharacter (other.textCharacter)
  44014. {
  44015. }
  44016. const KeyPress& KeyPress::operator= (const KeyPress& other) throw()
  44017. {
  44018. keyCode = other.keyCode;
  44019. mods = other.mods;
  44020. textCharacter = other.textCharacter;
  44021. return *this;
  44022. }
  44023. bool KeyPress::operator== (const KeyPress& other) const throw()
  44024. {
  44025. return mods.getRawFlags() == other.mods.getRawFlags()
  44026. && (textCharacter == other.textCharacter
  44027. || textCharacter == 0
  44028. || other.textCharacter == 0)
  44029. && (keyCode == other.keyCode
  44030. || (keyCode < 256
  44031. && other.keyCode < 256
  44032. && CharacterFunctions::toLowerCase ((tchar) keyCode)
  44033. == CharacterFunctions::toLowerCase ((tchar) other.keyCode)));
  44034. }
  44035. bool KeyPress::operator!= (const KeyPress& other) const throw()
  44036. {
  44037. return ! operator== (other);
  44038. }
  44039. bool KeyPress::isCurrentlyDown() const throw()
  44040. {
  44041. return isKeyCurrentlyDown (keyCode)
  44042. && (ModifierKeys::getCurrentModifiers().getRawFlags() & ModifierKeys::allKeyboardModifiers)
  44043. == (mods.getRawFlags() & ModifierKeys::allKeyboardModifiers);
  44044. }
  44045. struct KeyNameAndCode
  44046. {
  44047. const char* name;
  44048. int code;
  44049. };
  44050. static const KeyNameAndCode keyNameTranslations[] =
  44051. {
  44052. { "spacebar", KeyPress::spaceKey },
  44053. { "return", KeyPress::returnKey },
  44054. { "escape", KeyPress::escapeKey },
  44055. { "backspace", KeyPress::backspaceKey },
  44056. { "cursor left", KeyPress::leftKey },
  44057. { "cursor right", KeyPress::rightKey },
  44058. { "cursor up", KeyPress::upKey },
  44059. { "cursor down", KeyPress::downKey },
  44060. { "page up", KeyPress::pageUpKey },
  44061. { "page down", KeyPress::pageDownKey },
  44062. { "home", KeyPress::homeKey },
  44063. { "end", KeyPress::endKey },
  44064. { "delete", KeyPress::deleteKey },
  44065. { "insert", KeyPress::insertKey },
  44066. { "tab", KeyPress::tabKey },
  44067. { "play", KeyPress::playKey },
  44068. { "stop", KeyPress::stopKey },
  44069. { "fast forward", KeyPress::fastForwardKey },
  44070. { "rewind", KeyPress::rewindKey }
  44071. };
  44072. static const tchar* const numberPadPrefix = T("numpad ");
  44073. const KeyPress KeyPress::createFromDescription (const String& desc) throw()
  44074. {
  44075. int modifiers = 0;
  44076. if (desc.containsWholeWordIgnoreCase (T("ctrl"))
  44077. || desc.containsWholeWordIgnoreCase (T("control"))
  44078. || desc.containsWholeWordIgnoreCase (T("ctl")))
  44079. modifiers |= ModifierKeys::ctrlModifier;
  44080. if (desc.containsWholeWordIgnoreCase (T("shift"))
  44081. || desc.containsWholeWordIgnoreCase (T("shft")))
  44082. modifiers |= ModifierKeys::shiftModifier;
  44083. if (desc.containsWholeWordIgnoreCase (T("alt"))
  44084. || desc.containsWholeWordIgnoreCase (T("option")))
  44085. modifiers |= ModifierKeys::altModifier;
  44086. if (desc.containsWholeWordIgnoreCase (T("command"))
  44087. || desc.containsWholeWordIgnoreCase (T("cmd")))
  44088. modifiers |= ModifierKeys::commandModifier;
  44089. int key = 0;
  44090. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  44091. {
  44092. if (desc.containsWholeWordIgnoreCase (String (keyNameTranslations[i].name)))
  44093. {
  44094. key = keyNameTranslations[i].code;
  44095. break;
  44096. }
  44097. }
  44098. if (key == 0)
  44099. {
  44100. // see if it's a numpad key..
  44101. if (desc.containsIgnoreCase (numberPadPrefix))
  44102. {
  44103. const tchar lastChar = desc.trimEnd().getLastCharacter();
  44104. if (lastChar >= T('0') && lastChar <= T('9'))
  44105. key = numberPad0 + lastChar - T('0');
  44106. else if (lastChar == T('+'))
  44107. key = numberPadAdd;
  44108. else if (lastChar == T('-'))
  44109. key = numberPadSubtract;
  44110. else if (lastChar == T('*'))
  44111. key = numberPadMultiply;
  44112. else if (lastChar == T('/'))
  44113. key = numberPadDivide;
  44114. else if (lastChar == T('.'))
  44115. key = numberPadDecimalPoint;
  44116. else if (lastChar == T('='))
  44117. key = numberPadEquals;
  44118. else if (desc.endsWith (T("separator")))
  44119. key = numberPadSeparator;
  44120. else if (desc.endsWith (T("delete")))
  44121. key = numberPadDelete;
  44122. }
  44123. if (key == 0)
  44124. {
  44125. // see if it's a function key..
  44126. for (int i = 1; i <= 12; ++i)
  44127. if (desc.containsWholeWordIgnoreCase (T("f") + String (i)))
  44128. key = F1Key + i - 1;
  44129. if (key == 0)
  44130. {
  44131. // give up and use the hex code..
  44132. const int hexCode = desc.fromFirstOccurrenceOf (T("#"), false, false)
  44133. .toLowerCase()
  44134. .retainCharacters (T("0123456789abcdef"))
  44135. .getHexValue32();
  44136. if (hexCode > 0)
  44137. key = hexCode;
  44138. else
  44139. key = CharacterFunctions::toUpperCase (desc.getLastCharacter());
  44140. }
  44141. }
  44142. }
  44143. return KeyPress (key, ModifierKeys (modifiers), 0);
  44144. }
  44145. const String KeyPress::getTextDescription() const throw()
  44146. {
  44147. String desc;
  44148. if (keyCode > 0)
  44149. {
  44150. // some keyboard layouts use a shift-key to get the slash, but in those cases, we
  44151. // want to store it as being a slash, not shift+whatever.
  44152. if (textCharacter == T('/'))
  44153. return "/";
  44154. if (mods.isCtrlDown())
  44155. desc << "ctrl + ";
  44156. if (mods.isShiftDown())
  44157. desc << "shift + ";
  44158. #if JUCE_MAC
  44159. // only do this on the mac, because on Windows ctrl and command are the same,
  44160. // and this would get confusing
  44161. if (mods.isCommandDown())
  44162. desc << "command + ";
  44163. if (mods.isAltDown())
  44164. desc << "option + ";
  44165. #else
  44166. if (mods.isAltDown())
  44167. desc << "alt + ";
  44168. #endif
  44169. for (int i = 0; i < numElementsInArray (keyNameTranslations); ++i)
  44170. if (keyCode == keyNameTranslations[i].code)
  44171. return desc + keyNameTranslations[i].name;
  44172. if (keyCode >= F1Key && keyCode <= F16Key)
  44173. desc << 'F' << (1 + keyCode - F1Key);
  44174. else if (keyCode >= numberPad0 && keyCode <= numberPad9)
  44175. desc << numberPadPrefix << (keyCode - numberPad0);
  44176. else if (keyCode >= 33 && keyCode < 176)
  44177. desc += CharacterFunctions::toUpperCase ((tchar) keyCode);
  44178. else if (keyCode == numberPadAdd)
  44179. desc << numberPadPrefix << '+';
  44180. else if (keyCode == numberPadSubtract)
  44181. desc << numberPadPrefix << '-';
  44182. else if (keyCode == numberPadMultiply)
  44183. desc << numberPadPrefix << '*';
  44184. else if (keyCode == numberPadDivide)
  44185. desc << numberPadPrefix << '/';
  44186. else if (keyCode == numberPadSeparator)
  44187. desc << numberPadPrefix << "separator";
  44188. else if (keyCode == numberPadDecimalPoint)
  44189. desc << numberPadPrefix << '.';
  44190. else if (keyCode == numberPadDelete)
  44191. desc << numberPadPrefix << "delete";
  44192. else
  44193. desc << '#' << String::toHexString (keyCode);
  44194. }
  44195. return desc;
  44196. }
  44197. END_JUCE_NAMESPACE
  44198. /********* End of inlined file: juce_KeyPress.cpp *********/
  44199. /********* Start of inlined file: juce_KeyPressMappingSet.cpp *********/
  44200. BEGIN_JUCE_NAMESPACE
  44201. KeyPressMappingSet::KeyPressMappingSet (ApplicationCommandManager* const commandManager_) throw()
  44202. : commandManager (commandManager_)
  44203. {
  44204. // A manager is needed to get the descriptions of commands, and will be called when
  44205. // a command is invoked. So you can't leave this null..
  44206. jassert (commandManager_ != 0);
  44207. Desktop::getInstance().addFocusChangeListener (this);
  44208. }
  44209. KeyPressMappingSet::KeyPressMappingSet (const KeyPressMappingSet& other) throw()
  44210. : commandManager (other.commandManager)
  44211. {
  44212. Desktop::getInstance().addFocusChangeListener (this);
  44213. }
  44214. KeyPressMappingSet::~KeyPressMappingSet()
  44215. {
  44216. Desktop::getInstance().removeFocusChangeListener (this);
  44217. }
  44218. const Array <KeyPress> KeyPressMappingSet::getKeyPressesAssignedToCommand (const CommandID commandID) const throw()
  44219. {
  44220. for (int i = 0; i < mappings.size(); ++i)
  44221. if (mappings.getUnchecked(i)->commandID == commandID)
  44222. return mappings.getUnchecked (i)->keypresses;
  44223. return Array <KeyPress> ();
  44224. }
  44225. void KeyPressMappingSet::addKeyPress (const CommandID commandID,
  44226. const KeyPress& newKeyPress,
  44227. int insertIndex) throw()
  44228. {
  44229. if (findCommandForKeyPress (newKeyPress) != commandID)
  44230. {
  44231. removeKeyPress (newKeyPress);
  44232. if (newKeyPress.isValid())
  44233. {
  44234. for (int i = mappings.size(); --i >= 0;)
  44235. {
  44236. if (mappings.getUnchecked(i)->commandID == commandID)
  44237. {
  44238. mappings.getUnchecked(i)->keypresses.insert (insertIndex, newKeyPress);
  44239. sendChangeMessage (this);
  44240. return;
  44241. }
  44242. }
  44243. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  44244. if (ci != 0)
  44245. {
  44246. CommandMapping* const cm = new CommandMapping();
  44247. cm->commandID = commandID;
  44248. cm->keypresses.add (newKeyPress);
  44249. cm->wantsKeyUpDownCallbacks = (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) != 0;
  44250. mappings.add (cm);
  44251. sendChangeMessage (this);
  44252. }
  44253. }
  44254. }
  44255. }
  44256. void KeyPressMappingSet::resetToDefaultMappings() throw()
  44257. {
  44258. mappings.clear();
  44259. for (int i = 0; i < commandManager->getNumCommands(); ++i)
  44260. {
  44261. const ApplicationCommandInfo* const ci = commandManager->getCommandForIndex (i);
  44262. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  44263. {
  44264. addKeyPress (ci->commandID,
  44265. ci->defaultKeypresses.getReference (j));
  44266. }
  44267. }
  44268. sendChangeMessage (this);
  44269. }
  44270. void KeyPressMappingSet::resetToDefaultMapping (const CommandID commandID) throw()
  44271. {
  44272. clearAllKeyPresses (commandID);
  44273. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  44274. for (int j = 0; j < ci->defaultKeypresses.size(); ++j)
  44275. {
  44276. addKeyPress (ci->commandID,
  44277. ci->defaultKeypresses.getReference (j));
  44278. }
  44279. }
  44280. void KeyPressMappingSet::clearAllKeyPresses() throw()
  44281. {
  44282. if (mappings.size() > 0)
  44283. {
  44284. sendChangeMessage (this);
  44285. mappings.clear();
  44286. }
  44287. }
  44288. void KeyPressMappingSet::clearAllKeyPresses (const CommandID commandID) throw()
  44289. {
  44290. for (int i = mappings.size(); --i >= 0;)
  44291. {
  44292. if (mappings.getUnchecked(i)->commandID == commandID)
  44293. {
  44294. mappings.remove (i);
  44295. sendChangeMessage (this);
  44296. }
  44297. }
  44298. }
  44299. void KeyPressMappingSet::removeKeyPress (const KeyPress& keypress) throw()
  44300. {
  44301. if (keypress.isValid())
  44302. {
  44303. for (int i = mappings.size(); --i >= 0;)
  44304. {
  44305. CommandMapping* const cm = mappings.getUnchecked(i);
  44306. for (int j = cm->keypresses.size(); --j >= 0;)
  44307. {
  44308. if (keypress == cm->keypresses [j])
  44309. {
  44310. cm->keypresses.remove (j);
  44311. sendChangeMessage (this);
  44312. }
  44313. }
  44314. }
  44315. }
  44316. }
  44317. void KeyPressMappingSet::removeKeyPress (const CommandID commandID,
  44318. const int keyPressIndex) throw()
  44319. {
  44320. for (int i = mappings.size(); --i >= 0;)
  44321. {
  44322. if (mappings.getUnchecked(i)->commandID == commandID)
  44323. {
  44324. mappings.getUnchecked(i)->keypresses.remove (keyPressIndex);
  44325. sendChangeMessage (this);
  44326. break;
  44327. }
  44328. }
  44329. }
  44330. CommandID KeyPressMappingSet::findCommandForKeyPress (const KeyPress& keyPress) const throw()
  44331. {
  44332. for (int i = 0; i < mappings.size(); ++i)
  44333. if (mappings.getUnchecked(i)->keypresses.contains (keyPress))
  44334. return mappings.getUnchecked(i)->commandID;
  44335. return 0;
  44336. }
  44337. bool KeyPressMappingSet::containsMapping (const CommandID commandID,
  44338. const KeyPress& keyPress) const throw()
  44339. {
  44340. for (int i = mappings.size(); --i >= 0;)
  44341. if (mappings.getUnchecked(i)->commandID == commandID)
  44342. return mappings.getUnchecked(i)->keypresses.contains (keyPress);
  44343. return false;
  44344. }
  44345. void KeyPressMappingSet::invokeCommand (const CommandID commandID,
  44346. const KeyPress& key,
  44347. const bool isKeyDown,
  44348. const int millisecsSinceKeyPressed,
  44349. Component* const originatingComponent) const
  44350. {
  44351. ApplicationCommandTarget::InvocationInfo info (commandID);
  44352. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromKeyPress;
  44353. info.isKeyDown = isKeyDown;
  44354. info.keyPress = key;
  44355. info.millisecsSinceKeyPressed = millisecsSinceKeyPressed;
  44356. info.originatingComponent = originatingComponent;
  44357. commandManager->invoke (info, false);
  44358. }
  44359. bool KeyPressMappingSet::restoreFromXml (const XmlElement& xmlVersion)
  44360. {
  44361. if (xmlVersion.hasTagName (T("KEYMAPPINGS")))
  44362. {
  44363. if (xmlVersion.getBoolAttribute (T("basedOnDefaults"), true))
  44364. {
  44365. // if the XML was created as a set of differences from the default mappings,
  44366. // (i.e. by calling createXml (true)), then we need to first restore the defaults.
  44367. resetToDefaultMappings();
  44368. }
  44369. else
  44370. {
  44371. // if the XML was created calling createXml (false), then we need to clear all
  44372. // the keys and treat the xml as describing the entire set of mappings.
  44373. clearAllKeyPresses();
  44374. }
  44375. forEachXmlChildElement (xmlVersion, map)
  44376. {
  44377. const CommandID commandId = map->getStringAttribute (T("commandId")).getHexValue32();
  44378. if (commandId != 0)
  44379. {
  44380. const KeyPress key (KeyPress::createFromDescription (map->getStringAttribute (T("key"))));
  44381. if (map->hasTagName (T("MAPPING")))
  44382. {
  44383. addKeyPress (commandId, key);
  44384. }
  44385. else if (map->hasTagName (T("UNMAPPING")))
  44386. {
  44387. if (containsMapping (commandId, key))
  44388. removeKeyPress (key);
  44389. }
  44390. }
  44391. }
  44392. return true;
  44393. }
  44394. return false;
  44395. }
  44396. XmlElement* KeyPressMappingSet::createXml (const bool saveDifferencesFromDefaultSet) const
  44397. {
  44398. KeyPressMappingSet* defaultSet = 0;
  44399. if (saveDifferencesFromDefaultSet)
  44400. {
  44401. defaultSet = new KeyPressMappingSet (commandManager);
  44402. defaultSet->resetToDefaultMappings();
  44403. }
  44404. XmlElement* const doc = new XmlElement (T("KEYMAPPINGS"));
  44405. doc->setAttribute (T("basedOnDefaults"), saveDifferencesFromDefaultSet);
  44406. int i;
  44407. for (i = 0; i < mappings.size(); ++i)
  44408. {
  44409. const CommandMapping* const cm = mappings.getUnchecked(i);
  44410. for (int j = 0; j < cm->keypresses.size(); ++j)
  44411. {
  44412. if (defaultSet == 0
  44413. || ! defaultSet->containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  44414. {
  44415. XmlElement* const map = new XmlElement (T("MAPPING"));
  44416. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  44417. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  44418. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  44419. doc->addChildElement (map);
  44420. }
  44421. }
  44422. }
  44423. if (defaultSet != 0)
  44424. {
  44425. for (i = 0; i < defaultSet->mappings.size(); ++i)
  44426. {
  44427. const CommandMapping* const cm = defaultSet->mappings.getUnchecked(i);
  44428. for (int j = 0; j < cm->keypresses.size(); ++j)
  44429. {
  44430. if (! containsMapping (cm->commandID, cm->keypresses.getReference (j)))
  44431. {
  44432. XmlElement* const map = new XmlElement (T("UNMAPPING"));
  44433. map->setAttribute (T("commandId"), String::toHexString ((int) cm->commandID));
  44434. map->setAttribute (T("description"), commandManager->getDescriptionOfCommand (cm->commandID));
  44435. map->setAttribute (T("key"), cm->keypresses.getReference (j).getTextDescription());
  44436. doc->addChildElement (map);
  44437. }
  44438. }
  44439. }
  44440. delete defaultSet;
  44441. }
  44442. return doc;
  44443. }
  44444. bool KeyPressMappingSet::keyPressed (const KeyPress& key,
  44445. Component* originatingComponent)
  44446. {
  44447. bool used = false;
  44448. const CommandID commandID = findCommandForKeyPress (key);
  44449. const ApplicationCommandInfo* const ci = commandManager->getCommandForID (commandID);
  44450. if (ci != 0
  44451. && (ci->flags & ApplicationCommandInfo::wantsKeyUpDownCallbacks) == 0)
  44452. {
  44453. ApplicationCommandInfo info (0);
  44454. if (commandManager->getTargetForCommand (commandID, info) != 0
  44455. && (info.flags & ApplicationCommandInfo::isDisabled) == 0)
  44456. {
  44457. invokeCommand (commandID, key, true, 0, originatingComponent);
  44458. used = true;
  44459. }
  44460. else
  44461. {
  44462. if (originatingComponent != 0)
  44463. originatingComponent->getLookAndFeel().playAlertSound();
  44464. }
  44465. }
  44466. return used;
  44467. }
  44468. bool KeyPressMappingSet::keyStateChanged (Component* originatingComponent)
  44469. {
  44470. bool used = false;
  44471. const uint32 now = Time::getMillisecondCounter();
  44472. for (int i = mappings.size(); --i >= 0;)
  44473. {
  44474. CommandMapping* const cm = mappings.getUnchecked(i);
  44475. if (cm->wantsKeyUpDownCallbacks)
  44476. {
  44477. for (int j = cm->keypresses.size(); --j >= 0;)
  44478. {
  44479. const KeyPress key (cm->keypresses.getReference (j));
  44480. const bool isDown = key.isCurrentlyDown();
  44481. int keyPressEntryIndex = 0;
  44482. bool wasDown = false;
  44483. for (int k = keysDown.size(); --k >= 0;)
  44484. {
  44485. if (key == keysDown.getUnchecked(k)->key)
  44486. {
  44487. keyPressEntryIndex = k;
  44488. wasDown = true;
  44489. break;
  44490. }
  44491. }
  44492. if (isDown != wasDown)
  44493. {
  44494. int millisecs = 0;
  44495. if (isDown)
  44496. {
  44497. KeyPressTime* const k = new KeyPressTime();
  44498. k->key = key;
  44499. k->timeWhenPressed = now;
  44500. keysDown.add (k);
  44501. }
  44502. else
  44503. {
  44504. const uint32 pressTime = keysDown.getUnchecked (keyPressEntryIndex)->timeWhenPressed;
  44505. if (now > pressTime)
  44506. millisecs = now - pressTime;
  44507. keysDown.remove (keyPressEntryIndex);
  44508. }
  44509. invokeCommand (cm->commandID, key, isDown, millisecs, originatingComponent);
  44510. used = true;
  44511. }
  44512. }
  44513. }
  44514. }
  44515. return used;
  44516. }
  44517. void KeyPressMappingSet::globalFocusChanged (Component* focusedComponent)
  44518. {
  44519. if (focusedComponent != 0)
  44520. focusedComponent->keyStateChanged();
  44521. }
  44522. END_JUCE_NAMESPACE
  44523. /********* End of inlined file: juce_KeyPressMappingSet.cpp *********/
  44524. /********* Start of inlined file: juce_ModifierKeys.cpp *********/
  44525. BEGIN_JUCE_NAMESPACE
  44526. ModifierKeys::ModifierKeys (const int flags_) throw()
  44527. : flags (flags_)
  44528. {
  44529. }
  44530. ModifierKeys::ModifierKeys (const ModifierKeys& other) throw()
  44531. : flags (other.flags)
  44532. {
  44533. }
  44534. const ModifierKeys& ModifierKeys::operator= (const ModifierKeys& other) throw()
  44535. {
  44536. flags = other.flags;
  44537. return *this;
  44538. }
  44539. int ModifierKeys::currentModifierFlags = 0;
  44540. const ModifierKeys ModifierKeys::getCurrentModifiers() throw()
  44541. {
  44542. return ModifierKeys (currentModifierFlags);
  44543. }
  44544. END_JUCE_NAMESPACE
  44545. /********* End of inlined file: juce_ModifierKeys.cpp *********/
  44546. /********* Start of inlined file: juce_ComponentAnimator.cpp *********/
  44547. BEGIN_JUCE_NAMESPACE
  44548. struct AnimationTask
  44549. {
  44550. AnimationTask (Component* const comp)
  44551. : component (comp),
  44552. watcher (comp)
  44553. {
  44554. }
  44555. Component* component;
  44556. ComponentDeletionWatcher watcher;
  44557. Rectangle destination;
  44558. int msElapsed, msTotal;
  44559. double startSpeed, midSpeed, endSpeed, lastProgress;
  44560. double left, top, right, bottom;
  44561. bool useTimeslice (const int elapsed)
  44562. {
  44563. if (watcher.hasBeenDeleted())
  44564. return false;
  44565. msElapsed += elapsed;
  44566. double newProgress = msElapsed / (double) msTotal;
  44567. if (newProgress >= 0 && newProgress < 1.0)
  44568. {
  44569. newProgress = timeToDistance (newProgress);
  44570. const double delta = (newProgress - lastProgress) / (1.0 - lastProgress);
  44571. jassert (newProgress >= lastProgress);
  44572. lastProgress = newProgress;
  44573. left += (destination.getX() - left) * delta;
  44574. top += (destination.getY() - top) * delta;
  44575. right += (destination.getRight() - right) * delta;
  44576. bottom += (destination.getBottom() - bottom) * delta;
  44577. if (delta < 1.0)
  44578. {
  44579. const Rectangle newBounds (roundDoubleToInt (left),
  44580. roundDoubleToInt (top),
  44581. roundDoubleToInt (right - left),
  44582. roundDoubleToInt (bottom - top));
  44583. if (newBounds != destination)
  44584. {
  44585. component->setBounds (newBounds);
  44586. return true;
  44587. }
  44588. }
  44589. }
  44590. component->setBounds (destination);
  44591. return false;
  44592. }
  44593. void moveToFinalDestination()
  44594. {
  44595. if (! watcher.hasBeenDeleted())
  44596. component->setBounds (destination);
  44597. }
  44598. private:
  44599. inline double timeToDistance (const double time) const
  44600. {
  44601. return (time < 0.5) ? time * (startSpeed + time * (midSpeed - startSpeed))
  44602. : 0.5 * (startSpeed + 0.5 * (midSpeed - startSpeed))
  44603. + (time - 0.5) * (midSpeed + (time - 0.5) * (endSpeed - midSpeed));
  44604. }
  44605. };
  44606. ComponentAnimator::ComponentAnimator()
  44607. : lastTime (0)
  44608. {
  44609. }
  44610. ComponentAnimator::~ComponentAnimator()
  44611. {
  44612. cancelAllAnimations (false);
  44613. jassert (tasks.size() == 0);
  44614. }
  44615. void* ComponentAnimator::findTaskFor (Component* const component) const
  44616. {
  44617. for (int i = tasks.size(); --i >= 0;)
  44618. if (component == ((AnimationTask*) tasks.getUnchecked(i))->component)
  44619. return tasks.getUnchecked(i);
  44620. return 0;
  44621. }
  44622. void ComponentAnimator::animateComponent (Component* const component,
  44623. const Rectangle& finalPosition,
  44624. const int millisecondsToSpendMoving,
  44625. const double startSpeed,
  44626. const double endSpeed)
  44627. {
  44628. if (component != 0)
  44629. {
  44630. AnimationTask* at = (AnimationTask*) findTaskFor (component);
  44631. if (at == 0)
  44632. {
  44633. at = new AnimationTask (component);
  44634. tasks.add (at);
  44635. }
  44636. at->msElapsed = 0;
  44637. at->lastProgress = 0;
  44638. at->msTotal = jmax (1, millisecondsToSpendMoving);
  44639. at->destination = finalPosition;
  44640. // the speeds must be 0 or greater!
  44641. jassert (startSpeed >= 0 && endSpeed >= 0)
  44642. const double invTotalDistance = 4.0 / (startSpeed + endSpeed + 2.0);
  44643. at->startSpeed = jmax (0.0, startSpeed * invTotalDistance);
  44644. at->midSpeed = invTotalDistance;
  44645. at->endSpeed = jmax (0.0, endSpeed * invTotalDistance);
  44646. at->left = component->getX();
  44647. at->top = component->getY();
  44648. at->right = component->getRight();
  44649. at->bottom = component->getBottom();
  44650. if (! isTimerRunning())
  44651. {
  44652. lastTime = Time::getMillisecondCounter();
  44653. startTimer (1000 / 50);
  44654. }
  44655. }
  44656. }
  44657. void ComponentAnimator::cancelAllAnimations (const bool moveComponentsToTheirFinalPositions)
  44658. {
  44659. for (int i = tasks.size(); --i >= 0;)
  44660. {
  44661. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  44662. if (moveComponentsToTheirFinalPositions)
  44663. at->moveToFinalDestination();
  44664. delete at;
  44665. tasks.remove (i);
  44666. }
  44667. }
  44668. void ComponentAnimator::cancelAnimation (Component* const component,
  44669. const bool moveComponentToItsFinalPosition)
  44670. {
  44671. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  44672. if (at != 0)
  44673. {
  44674. if (moveComponentToItsFinalPosition)
  44675. at->moveToFinalDestination();
  44676. tasks.removeValue (at);
  44677. delete at;
  44678. }
  44679. }
  44680. const Rectangle ComponentAnimator::getComponentDestination (Component* const component)
  44681. {
  44682. AnimationTask* const at = (AnimationTask*) findTaskFor (component);
  44683. if (at != 0)
  44684. return at->destination;
  44685. else if (component != 0)
  44686. return component->getBounds();
  44687. return Rectangle();
  44688. }
  44689. void ComponentAnimator::timerCallback()
  44690. {
  44691. const uint32 timeNow = Time::getMillisecondCounter();
  44692. if (lastTime == 0 || lastTime == timeNow)
  44693. lastTime = timeNow;
  44694. const int elapsed = timeNow - lastTime;
  44695. for (int i = tasks.size(); --i >= 0;)
  44696. {
  44697. AnimationTask* const at = (AnimationTask*) tasks.getUnchecked(i);
  44698. if (! at->useTimeslice (elapsed))
  44699. {
  44700. tasks.remove (i);
  44701. delete at;
  44702. }
  44703. }
  44704. lastTime = timeNow;
  44705. if (tasks.size() == 0)
  44706. stopTimer();
  44707. }
  44708. END_JUCE_NAMESPACE
  44709. /********* End of inlined file: juce_ComponentAnimator.cpp *********/
  44710. /********* Start of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  44711. BEGIN_JUCE_NAMESPACE
  44712. ComponentBoundsConstrainer::ComponentBoundsConstrainer() throw()
  44713. : minW (0),
  44714. maxW (0x3fffffff),
  44715. minH (0),
  44716. maxH (0x3fffffff),
  44717. minOffTop (0),
  44718. minOffLeft (0),
  44719. minOffBottom (0),
  44720. minOffRight (0),
  44721. aspectRatio (0.0)
  44722. {
  44723. }
  44724. ComponentBoundsConstrainer::~ComponentBoundsConstrainer()
  44725. {
  44726. }
  44727. void ComponentBoundsConstrainer::setMinimumWidth (const int minimumWidth) throw()
  44728. {
  44729. minW = minimumWidth;
  44730. }
  44731. void ComponentBoundsConstrainer::setMaximumWidth (const int maximumWidth) throw()
  44732. {
  44733. maxW = maximumWidth;
  44734. }
  44735. void ComponentBoundsConstrainer::setMinimumHeight (const int minimumHeight) throw()
  44736. {
  44737. minH = minimumHeight;
  44738. }
  44739. void ComponentBoundsConstrainer::setMaximumHeight (const int maximumHeight) throw()
  44740. {
  44741. maxH = maximumHeight;
  44742. }
  44743. void ComponentBoundsConstrainer::setMinimumSize (const int minimumWidth, const int minimumHeight) throw()
  44744. {
  44745. jassert (maxW >= minimumWidth);
  44746. jassert (maxH >= minimumHeight);
  44747. jassert (minimumWidth > 0 && minimumHeight > 0);
  44748. minW = minimumWidth;
  44749. minH = minimumHeight;
  44750. if (minW > maxW)
  44751. maxW = minW;
  44752. if (minH > maxH)
  44753. maxH = minH;
  44754. }
  44755. void ComponentBoundsConstrainer::setMaximumSize (const int maximumWidth, const int maximumHeight) throw()
  44756. {
  44757. jassert (maximumWidth >= minW);
  44758. jassert (maximumHeight >= minH);
  44759. jassert (maximumWidth > 0 && maximumHeight > 0);
  44760. maxW = jmax (minW, maximumWidth);
  44761. maxH = jmax (minH, maximumHeight);
  44762. }
  44763. void ComponentBoundsConstrainer::setSizeLimits (const int minimumWidth,
  44764. const int minimumHeight,
  44765. const int maximumWidth,
  44766. const int maximumHeight) throw()
  44767. {
  44768. jassert (maximumWidth >= minimumWidth);
  44769. jassert (maximumHeight >= minimumHeight);
  44770. jassert (maximumWidth > 0 && maximumHeight > 0);
  44771. jassert (minimumWidth > 0 && minimumHeight > 0);
  44772. minW = jmax (0, minimumWidth);
  44773. minH = jmax (0, minimumHeight);
  44774. maxW = jmax (minW, maximumWidth);
  44775. maxH = jmax (minH, maximumHeight);
  44776. }
  44777. void ComponentBoundsConstrainer::setMinimumOnscreenAmounts (const int minimumWhenOffTheTop,
  44778. const int minimumWhenOffTheLeft,
  44779. const int minimumWhenOffTheBottom,
  44780. const int minimumWhenOffTheRight) throw()
  44781. {
  44782. minOffTop = minimumWhenOffTheTop;
  44783. minOffLeft = minimumWhenOffTheLeft;
  44784. minOffBottom = minimumWhenOffTheBottom;
  44785. minOffRight = minimumWhenOffTheRight;
  44786. }
  44787. void ComponentBoundsConstrainer::setFixedAspectRatio (const double widthOverHeight) throw()
  44788. {
  44789. aspectRatio = jmax (0.0, widthOverHeight);
  44790. }
  44791. double ComponentBoundsConstrainer::getFixedAspectRatio() const throw()
  44792. {
  44793. return aspectRatio;
  44794. }
  44795. void ComponentBoundsConstrainer::setBoundsForComponent (Component* const component,
  44796. int x, int y, int w, int h,
  44797. const bool isStretchingTop,
  44798. const bool isStretchingLeft,
  44799. const bool isStretchingBottom,
  44800. const bool isStretchingRight)
  44801. {
  44802. jassert (component != 0);
  44803. Rectangle limits;
  44804. Component* const p = component->getParentComponent();
  44805. if (p == 0)
  44806. limits = Desktop::getInstance().getAllMonitorDisplayAreas().getBounds();
  44807. else
  44808. limits.setSize (p->getWidth(), p->getHeight());
  44809. if (component->isOnDesktop())
  44810. {
  44811. ComponentPeer* const peer = component->getPeer();
  44812. const BorderSize border (peer->getFrameSize());
  44813. x -= border.getLeft();
  44814. y -= border.getTop();
  44815. w += border.getLeftAndRight();
  44816. h += border.getTopAndBottom();
  44817. checkBounds (x, y, w, h,
  44818. border.addedTo (component->getBounds()), limits,
  44819. isStretchingTop, isStretchingLeft,
  44820. isStretchingBottom, isStretchingRight);
  44821. x += border.getLeft();
  44822. y += border.getTop();
  44823. w -= border.getLeftAndRight();
  44824. h -= border.getTopAndBottom();
  44825. }
  44826. else
  44827. {
  44828. checkBounds (x, y, w, h,
  44829. component->getBounds(), limits,
  44830. isStretchingTop, isStretchingLeft,
  44831. isStretchingBottom, isStretchingRight);
  44832. }
  44833. applyBoundsToComponent (component, x, y, w, h);
  44834. }
  44835. void ComponentBoundsConstrainer::applyBoundsToComponent (Component* component,
  44836. int x, int y, int w, int h)
  44837. {
  44838. component->setBounds (x, y, w, h);
  44839. }
  44840. void ComponentBoundsConstrainer::resizeStart()
  44841. {
  44842. }
  44843. void ComponentBoundsConstrainer::resizeEnd()
  44844. {
  44845. }
  44846. void ComponentBoundsConstrainer::checkBounds (int& x, int& y, int& w, int& h,
  44847. const Rectangle& old,
  44848. const Rectangle& limits,
  44849. const bool isStretchingTop,
  44850. const bool isStretchingLeft,
  44851. const bool isStretchingBottom,
  44852. const bool isStretchingRight)
  44853. {
  44854. // constrain the size if it's being stretched..
  44855. if (isStretchingLeft)
  44856. {
  44857. x = jlimit (old.getRight() - maxW, old.getRight() - minW, x);
  44858. w = old.getRight() - x;
  44859. }
  44860. if (isStretchingRight)
  44861. {
  44862. w = jlimit (minW, maxW, w);
  44863. }
  44864. if (isStretchingTop)
  44865. {
  44866. y = jlimit (old.getBottom() - maxH, old.getBottom() - minH, y);
  44867. h = old.getBottom() - y;
  44868. }
  44869. if (isStretchingBottom)
  44870. {
  44871. h = jlimit (minH, maxH, h);
  44872. }
  44873. // constrain the aspect ratio if one has been specified..
  44874. if (aspectRatio > 0.0 && w > 0 && h > 0)
  44875. {
  44876. bool adjustWidth;
  44877. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  44878. {
  44879. adjustWidth = true;
  44880. }
  44881. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  44882. {
  44883. adjustWidth = false;
  44884. }
  44885. else
  44886. {
  44887. const double oldRatio = (old.getHeight() > 0) ? fabs (old.getWidth() / (double) old.getHeight()) : 0.0;
  44888. const double newRatio = fabs (w / (double) h);
  44889. adjustWidth = (oldRatio > newRatio);
  44890. }
  44891. if (adjustWidth)
  44892. {
  44893. w = roundDoubleToInt (h * aspectRatio);
  44894. if (w > maxW || w < minW)
  44895. {
  44896. w = jlimit (minW, maxW, w);
  44897. h = roundDoubleToInt (w / aspectRatio);
  44898. }
  44899. }
  44900. else
  44901. {
  44902. h = roundDoubleToInt (w / aspectRatio);
  44903. if (h > maxH || h < minH)
  44904. {
  44905. h = jlimit (minH, maxH, h);
  44906. w = roundDoubleToInt (h * aspectRatio);
  44907. }
  44908. }
  44909. if ((isStretchingTop || isStretchingBottom) && ! (isStretchingLeft || isStretchingRight))
  44910. {
  44911. x = old.getX() + (old.getWidth() - w) / 2;
  44912. }
  44913. else if ((isStretchingLeft || isStretchingRight) && ! (isStretchingTop || isStretchingBottom))
  44914. {
  44915. y = old.getY() + (old.getHeight() - h) / 2;
  44916. }
  44917. else
  44918. {
  44919. if (isStretchingLeft)
  44920. x = old.getRight() - w;
  44921. if (isStretchingTop)
  44922. y = old.getBottom() - h;
  44923. }
  44924. }
  44925. // ...and constrain the position if limits have been set for that.
  44926. if (minOffTop > 0 || minOffLeft > 0 || minOffBottom > 0 || minOffRight > 0)
  44927. {
  44928. if (minOffTop > 0)
  44929. {
  44930. const int limit = limits.getY() + jmin (minOffTop - h, 0);
  44931. if (y < limit)
  44932. {
  44933. if (isStretchingTop)
  44934. h -= (limit - y);
  44935. y = limit;
  44936. }
  44937. }
  44938. if (minOffLeft > 0)
  44939. {
  44940. const int limit = limits.getX() + jmin (minOffLeft - w, 0);
  44941. if (x < limit)
  44942. {
  44943. if (isStretchingLeft)
  44944. w -= (limit - x);
  44945. x = limit;
  44946. }
  44947. }
  44948. if (minOffBottom > 0)
  44949. {
  44950. const int limit = limits.getBottom() - jmin (minOffBottom, h);
  44951. if (y > limit)
  44952. {
  44953. if (isStretchingBottom)
  44954. h += (limit - y);
  44955. else
  44956. y = limit;
  44957. }
  44958. }
  44959. if (minOffRight > 0)
  44960. {
  44961. const int limit = limits.getRight() - jmin (minOffRight, w);
  44962. if (x > limit)
  44963. {
  44964. if (isStretchingRight)
  44965. w += (limit - x);
  44966. else
  44967. x = limit;
  44968. }
  44969. }
  44970. }
  44971. jassert (w >= 0 && h >= 0);
  44972. }
  44973. END_JUCE_NAMESPACE
  44974. /********* End of inlined file: juce_ComponentBoundsConstrainer.cpp *********/
  44975. /********* Start of inlined file: juce_ComponentMovementWatcher.cpp *********/
  44976. BEGIN_JUCE_NAMESPACE
  44977. ComponentMovementWatcher::ComponentMovementWatcher (Component* const component_)
  44978. : component (component_),
  44979. lastPeer (0),
  44980. registeredParentComps (4),
  44981. reentrant (false)
  44982. {
  44983. jassert (component != 0); // can't use this with a null pointer..
  44984. #ifdef JUCE_DEBUG
  44985. deletionWatcher = new ComponentDeletionWatcher (component_);
  44986. #endif
  44987. component->addComponentListener (this);
  44988. registerWithParentComps();
  44989. }
  44990. ComponentMovementWatcher::~ComponentMovementWatcher()
  44991. {
  44992. component->removeComponentListener (this);
  44993. unregister();
  44994. #ifdef JUCE_DEBUG
  44995. delete deletionWatcher;
  44996. #endif
  44997. }
  44998. void ComponentMovementWatcher::componentParentHierarchyChanged (Component&)
  44999. {
  45000. #ifdef JUCE_DEBUG
  45001. // agh! don't delete the target component without deleting this object first!
  45002. jassert (! deletionWatcher->hasBeenDeleted());
  45003. #endif
  45004. if (! reentrant)
  45005. {
  45006. reentrant = true;
  45007. ComponentPeer* const peer = component->getPeer();
  45008. if (peer != lastPeer)
  45009. {
  45010. ComponentDeletionWatcher watcher (component);
  45011. componentPeerChanged();
  45012. if (watcher.hasBeenDeleted())
  45013. return;
  45014. lastPeer = peer;
  45015. }
  45016. unregister();
  45017. registerWithParentComps();
  45018. reentrant = false;
  45019. componentMovedOrResized (*component, true, true);
  45020. }
  45021. }
  45022. void ComponentMovementWatcher::componentMovedOrResized (Component&, bool wasMoved, bool wasResized)
  45023. {
  45024. #ifdef JUCE_DEBUG
  45025. // agh! don't delete the target component without deleting this object first!
  45026. jassert (! deletionWatcher->hasBeenDeleted());
  45027. #endif
  45028. if (wasMoved)
  45029. {
  45030. int x = 0, y = 0;
  45031. component->relativePositionToOtherComponent (component->getTopLevelComponent(), x, y);
  45032. wasMoved = (lastX != x || lastY != y);
  45033. lastX = x;
  45034. lastY = y;
  45035. }
  45036. wasResized = (lastWidth != component->getWidth() || lastHeight != component->getHeight());
  45037. lastWidth = component->getWidth();
  45038. lastHeight = component->getHeight();
  45039. if (wasMoved || wasResized)
  45040. componentMovedOrResized (wasMoved, wasResized);
  45041. }
  45042. void ComponentMovementWatcher::registerWithParentComps() throw()
  45043. {
  45044. Component* p = component->getParentComponent();
  45045. while (p != 0)
  45046. {
  45047. p->addComponentListener (this);
  45048. registeredParentComps.add (p);
  45049. p = p->getParentComponent();
  45050. }
  45051. }
  45052. void ComponentMovementWatcher::unregister() throw()
  45053. {
  45054. for (int i = registeredParentComps.size(); --i >= 0;)
  45055. ((Component*) registeredParentComps.getUnchecked(i))->removeComponentListener (this);
  45056. registeredParentComps.clear();
  45057. }
  45058. END_JUCE_NAMESPACE
  45059. /********* End of inlined file: juce_ComponentMovementWatcher.cpp *********/
  45060. /********* Start of inlined file: juce_GroupComponent.cpp *********/
  45061. BEGIN_JUCE_NAMESPACE
  45062. GroupComponent::GroupComponent (const String& componentName,
  45063. const String& labelText)
  45064. : Component (componentName),
  45065. text (labelText),
  45066. justification (Justification::left)
  45067. {
  45068. setInterceptsMouseClicks (false, true);
  45069. }
  45070. GroupComponent::~GroupComponent()
  45071. {
  45072. }
  45073. void GroupComponent::setText (const String& newText) throw()
  45074. {
  45075. if (text != newText)
  45076. {
  45077. text = newText;
  45078. repaint();
  45079. }
  45080. }
  45081. const String GroupComponent::getText() const throw()
  45082. {
  45083. return text;
  45084. }
  45085. void GroupComponent::setTextLabelPosition (const Justification& newJustification)
  45086. {
  45087. if (justification.getFlags() != newJustification.getFlags())
  45088. {
  45089. justification = newJustification;
  45090. repaint();
  45091. }
  45092. }
  45093. void GroupComponent::paint (Graphics& g)
  45094. {
  45095. getLookAndFeel()
  45096. .drawGroupComponentOutline (g, getWidth(), getHeight(),
  45097. text, justification,
  45098. *this);
  45099. }
  45100. void GroupComponent::enablementChanged()
  45101. {
  45102. repaint();
  45103. }
  45104. void GroupComponent::colourChanged()
  45105. {
  45106. repaint();
  45107. }
  45108. END_JUCE_NAMESPACE
  45109. /********* End of inlined file: juce_GroupComponent.cpp *********/
  45110. /********* Start of inlined file: juce_MultiDocumentPanel.cpp *********/
  45111. BEGIN_JUCE_NAMESPACE
  45112. MultiDocumentPanelWindow::MultiDocumentPanelWindow (const Colour& backgroundColour)
  45113. : DocumentWindow (String::empty, backgroundColour,
  45114. DocumentWindow::maximiseButton | DocumentWindow::closeButton, false)
  45115. {
  45116. }
  45117. MultiDocumentPanelWindow::~MultiDocumentPanelWindow()
  45118. {
  45119. }
  45120. void MultiDocumentPanelWindow::maximiseButtonPressed()
  45121. {
  45122. MultiDocumentPanel* const owner = getOwner();
  45123. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  45124. if (owner != 0)
  45125. owner->setLayoutMode (MultiDocumentPanel::MaximisedWindowsWithTabs);
  45126. }
  45127. void MultiDocumentPanelWindow::closeButtonPressed()
  45128. {
  45129. MultiDocumentPanel* const owner = getOwner();
  45130. jassert (owner != 0); // these windows are only designed to be used inside a MultiDocumentPanel!
  45131. if (owner != 0)
  45132. owner->closeDocument (getContentComponent(), true);
  45133. }
  45134. void MultiDocumentPanelWindow::activeWindowStatusChanged()
  45135. {
  45136. DocumentWindow::activeWindowStatusChanged();
  45137. updateOrder();
  45138. }
  45139. void MultiDocumentPanelWindow::broughtToFront()
  45140. {
  45141. DocumentWindow::broughtToFront();
  45142. updateOrder();
  45143. }
  45144. void MultiDocumentPanelWindow::updateOrder()
  45145. {
  45146. MultiDocumentPanel* const owner = getOwner();
  45147. if (owner != 0)
  45148. owner->updateOrder();
  45149. }
  45150. MultiDocumentPanel* MultiDocumentPanelWindow::getOwner() const throw()
  45151. {
  45152. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  45153. return findParentComponentOfClass ((MultiDocumentPanel*) 0);
  45154. }
  45155. class MDITabbedComponentInternal : public TabbedComponent
  45156. {
  45157. public:
  45158. MDITabbedComponentInternal()
  45159. : TabbedComponent (TabbedButtonBar::TabsAtTop)
  45160. {
  45161. }
  45162. ~MDITabbedComponentInternal()
  45163. {
  45164. }
  45165. void currentTabChanged (const int, const String&)
  45166. {
  45167. // (unable to use the syntax findParentComponentOfClass <MultiDocumentPanel> () because of a VC6 compiler bug)
  45168. MultiDocumentPanel* const owner = findParentComponentOfClass ((MultiDocumentPanel*) 0);
  45169. if (owner != 0)
  45170. owner->updateOrder();
  45171. }
  45172. };
  45173. MultiDocumentPanel::MultiDocumentPanel()
  45174. : mode (MaximisedWindowsWithTabs),
  45175. tabComponent (0),
  45176. backgroundColour (Colours::lightblue),
  45177. maximumNumDocuments (0),
  45178. numDocsBeforeTabsUsed (0)
  45179. {
  45180. setOpaque (true);
  45181. }
  45182. MultiDocumentPanel::~MultiDocumentPanel()
  45183. {
  45184. closeAllDocuments (false);
  45185. }
  45186. static bool shouldDeleteComp (Component* const c)
  45187. {
  45188. return c->getComponentPropertyBool (T("mdiDocumentDelete_"), false);
  45189. }
  45190. bool MultiDocumentPanel::closeAllDocuments (const bool checkItsOkToCloseFirst)
  45191. {
  45192. while (components.size() > 0)
  45193. if (! closeDocument (components.getLast(), checkItsOkToCloseFirst))
  45194. return false;
  45195. return true;
  45196. }
  45197. MultiDocumentPanelWindow* MultiDocumentPanel::createNewDocumentWindow()
  45198. {
  45199. return new MultiDocumentPanelWindow (backgroundColour);
  45200. }
  45201. void MultiDocumentPanel::addWindow (Component* component)
  45202. {
  45203. MultiDocumentPanelWindow* const dw = createNewDocumentWindow();
  45204. dw->setResizable (true, false);
  45205. dw->setContentComponent (component, false, true);
  45206. dw->setName (component->getName());
  45207. dw->setBackgroundColour (component->getComponentPropertyColour (T("mdiDocumentBkg_"), false, backgroundColour));
  45208. int x = 4;
  45209. Component* const topComp = getChildComponent (getNumChildComponents() - 1);
  45210. if (topComp != 0 && topComp->getX() == x && topComp->getY() == x)
  45211. x += 16;
  45212. dw->setTopLeftPosition (x, x);
  45213. if (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty).isNotEmpty())
  45214. dw->restoreWindowStateFromString (component->getComponentProperty (T("mdiDocumentPos_"), false, String::empty));
  45215. addAndMakeVisible (dw);
  45216. dw->toFront (true);
  45217. }
  45218. bool MultiDocumentPanel::addDocument (Component* const component,
  45219. const Colour& backgroundColour,
  45220. const bool deleteWhenRemoved)
  45221. {
  45222. // If you try passing a full DocumentWindow or ResizableWindow in here, you'll end up
  45223. // with a frame-within-a-frame! Just pass in the bare content component.
  45224. jassert (dynamic_cast <ResizableWindow*> (component) == 0);
  45225. if (component == 0 || (maximumNumDocuments > 0 && components.size() >= maximumNumDocuments))
  45226. return false;
  45227. components.add (component);
  45228. component->setComponentProperty (T("mdiDocumentDelete_"), deleteWhenRemoved);
  45229. component->setComponentProperty (T("mdiDocumentBkg_"), backgroundColour);
  45230. component->addComponentListener (this);
  45231. if (mode == FloatingWindows)
  45232. {
  45233. if (isFullscreenWhenOneDocument())
  45234. {
  45235. if (components.size() == 1)
  45236. {
  45237. addAndMakeVisible (component);
  45238. }
  45239. else
  45240. {
  45241. if (components.size() == 2)
  45242. addWindow (components.getFirst());
  45243. addWindow (component);
  45244. }
  45245. }
  45246. else
  45247. {
  45248. addWindow (component);
  45249. }
  45250. }
  45251. else
  45252. {
  45253. if (tabComponent == 0 && components.size() > numDocsBeforeTabsUsed)
  45254. {
  45255. addAndMakeVisible (tabComponent = new MDITabbedComponentInternal());
  45256. Array <Component*> temp (components);
  45257. for (int i = 0; i < temp.size(); ++i)
  45258. tabComponent->addTab (temp[i]->getName(), backgroundColour, temp[i], false);
  45259. resized();
  45260. }
  45261. else
  45262. {
  45263. if (tabComponent != 0)
  45264. tabComponent->addTab (component->getName(), backgroundColour, component, false);
  45265. else
  45266. addAndMakeVisible (component);
  45267. }
  45268. setActiveDocument (component);
  45269. }
  45270. resized();
  45271. activeDocumentChanged();
  45272. return true;
  45273. }
  45274. bool MultiDocumentPanel::closeDocument (Component* component,
  45275. const bool checkItsOkToCloseFirst)
  45276. {
  45277. if (components.contains (component))
  45278. {
  45279. if (checkItsOkToCloseFirst && ! tryToCloseDocument (component))
  45280. return false;
  45281. component->removeComponentListener (this);
  45282. const bool shouldDelete = shouldDeleteComp (component);
  45283. component->removeComponentProperty (T("mdiDocumentDelete_"));
  45284. component->removeComponentProperty (T("mdiDocumentBkg_"));
  45285. if (mode == FloatingWindows)
  45286. {
  45287. for (int i = getNumChildComponents(); --i >= 0;)
  45288. {
  45289. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  45290. if (dw != 0 && dw->getContentComponent() == component)
  45291. {
  45292. dw->setContentComponent (0, false);
  45293. delete dw;
  45294. break;
  45295. }
  45296. }
  45297. if (shouldDelete)
  45298. delete component;
  45299. components.removeValue (component);
  45300. if (isFullscreenWhenOneDocument() && components.size() == 1)
  45301. {
  45302. for (int i = getNumChildComponents(); --i >= 0;)
  45303. {
  45304. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  45305. if (dw != 0)
  45306. {
  45307. dw->setContentComponent (0, false);
  45308. delete dw;
  45309. }
  45310. }
  45311. addAndMakeVisible (components.getFirst());
  45312. }
  45313. }
  45314. else
  45315. {
  45316. jassert (components.indexOf (component) >= 0);
  45317. if (tabComponent != 0)
  45318. {
  45319. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  45320. if (tabComponent->getTabContentComponent (i) == component)
  45321. tabComponent->removeTab (i);
  45322. }
  45323. else
  45324. {
  45325. removeChildComponent (component);
  45326. }
  45327. if (shouldDelete)
  45328. delete component;
  45329. if (tabComponent != 0 && tabComponent->getNumTabs() <= numDocsBeforeTabsUsed)
  45330. deleteAndZero (tabComponent);
  45331. components.removeValue (component);
  45332. if (components.size() > 0 && tabComponent == 0)
  45333. addAndMakeVisible (components.getFirst());
  45334. }
  45335. resized();
  45336. activeDocumentChanged();
  45337. }
  45338. else
  45339. {
  45340. jassertfalse
  45341. }
  45342. return true;
  45343. }
  45344. int MultiDocumentPanel::getNumDocuments() const throw()
  45345. {
  45346. return components.size();
  45347. }
  45348. Component* MultiDocumentPanel::getDocument (const int index) const throw()
  45349. {
  45350. return components [index];
  45351. }
  45352. Component* MultiDocumentPanel::getActiveDocument() const throw()
  45353. {
  45354. if (mode == FloatingWindows)
  45355. {
  45356. for (int i = getNumChildComponents(); --i >= 0;)
  45357. {
  45358. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  45359. if (dw != 0 && dw->isActiveWindow())
  45360. return dw->getContentComponent();
  45361. }
  45362. }
  45363. return components.getLast();
  45364. }
  45365. void MultiDocumentPanel::setActiveDocument (Component* component)
  45366. {
  45367. if (mode == FloatingWindows)
  45368. {
  45369. component = getContainerComp (component);
  45370. if (component != 0)
  45371. component->toFront (true);
  45372. }
  45373. else if (tabComponent != 0)
  45374. {
  45375. jassert (components.indexOf (component) >= 0);
  45376. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  45377. {
  45378. if (tabComponent->getTabContentComponent (i) == component)
  45379. {
  45380. tabComponent->setCurrentTabIndex (i);
  45381. break;
  45382. }
  45383. }
  45384. }
  45385. else
  45386. {
  45387. component->grabKeyboardFocus();
  45388. }
  45389. }
  45390. void MultiDocumentPanel::activeDocumentChanged()
  45391. {
  45392. }
  45393. void MultiDocumentPanel::setMaximumNumDocuments (const int newNumber)
  45394. {
  45395. maximumNumDocuments = newNumber;
  45396. }
  45397. void MultiDocumentPanel::useFullscreenWhenOneDocument (const bool shouldUseTabs)
  45398. {
  45399. numDocsBeforeTabsUsed = shouldUseTabs ? 1 : 0;
  45400. }
  45401. bool MultiDocumentPanel::isFullscreenWhenOneDocument() const throw()
  45402. {
  45403. return numDocsBeforeTabsUsed != 0;
  45404. }
  45405. void MultiDocumentPanel::setLayoutMode (const LayoutMode newLayoutMode)
  45406. {
  45407. if (mode != newLayoutMode)
  45408. {
  45409. mode = newLayoutMode;
  45410. if (mode == FloatingWindows)
  45411. {
  45412. deleteAndZero (tabComponent);
  45413. }
  45414. else
  45415. {
  45416. for (int i = getNumChildComponents(); --i >= 0;)
  45417. {
  45418. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  45419. if (dw != 0)
  45420. {
  45421. dw->getContentComponent()->setComponentProperty (T("mdiDocumentPos_"), dw->getWindowStateAsString());
  45422. dw->setContentComponent (0, false);
  45423. delete dw;
  45424. }
  45425. }
  45426. }
  45427. resized();
  45428. const Array <Component*> tempComps (components);
  45429. components.clear();
  45430. for (int i = 0; i < tempComps.size(); ++i)
  45431. {
  45432. Component* const c = tempComps.getUnchecked(i);
  45433. addDocument (c,
  45434. c->getComponentPropertyColour (T("mdiDocumentBkg_"), false, Colours::white),
  45435. shouldDeleteComp (c));
  45436. }
  45437. }
  45438. }
  45439. void MultiDocumentPanel::setBackgroundColour (const Colour& newBackgroundColour)
  45440. {
  45441. if (backgroundColour != newBackgroundColour)
  45442. {
  45443. backgroundColour = newBackgroundColour;
  45444. setOpaque (newBackgroundColour.isOpaque());
  45445. repaint();
  45446. }
  45447. }
  45448. void MultiDocumentPanel::paint (Graphics& g)
  45449. {
  45450. g.fillAll (backgroundColour);
  45451. }
  45452. void MultiDocumentPanel::resized()
  45453. {
  45454. if (mode == MaximisedWindowsWithTabs || components.size() == numDocsBeforeTabsUsed)
  45455. {
  45456. for (int i = getNumChildComponents(); --i >= 0;)
  45457. getChildComponent (i)->setBounds (0, 0, getWidth(), getHeight());
  45458. }
  45459. setWantsKeyboardFocus (components.size() == 0);
  45460. }
  45461. Component* MultiDocumentPanel::getContainerComp (Component* c) const
  45462. {
  45463. if (mode == FloatingWindows)
  45464. {
  45465. for (int i = 0; i < getNumChildComponents(); ++i)
  45466. {
  45467. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  45468. if (dw != 0 && dw->getContentComponent() == c)
  45469. {
  45470. c = dw;
  45471. break;
  45472. }
  45473. }
  45474. }
  45475. return c;
  45476. }
  45477. void MultiDocumentPanel::componentNameChanged (Component&)
  45478. {
  45479. if (mode == FloatingWindows)
  45480. {
  45481. for (int i = 0; i < getNumChildComponents(); ++i)
  45482. {
  45483. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  45484. if (dw != 0)
  45485. dw->setName (dw->getContentComponent()->getName());
  45486. }
  45487. }
  45488. else if (tabComponent != 0)
  45489. {
  45490. for (int i = tabComponent->getNumTabs(); --i >= 0;)
  45491. tabComponent->setTabName (i, tabComponent->getTabContentComponent (i)->getName());
  45492. }
  45493. }
  45494. void MultiDocumentPanel::updateOrder()
  45495. {
  45496. const Array <Component*> oldList (components);
  45497. if (mode == FloatingWindows)
  45498. {
  45499. components.clear();
  45500. for (int i = 0; i < getNumChildComponents(); ++i)
  45501. {
  45502. MultiDocumentPanelWindow* const dw = dynamic_cast <MultiDocumentPanelWindow*> (getChildComponent (i));
  45503. if (dw != 0)
  45504. components.add (dw->getContentComponent());
  45505. }
  45506. }
  45507. else
  45508. {
  45509. if (tabComponent != 0)
  45510. {
  45511. Component* const current = tabComponent->getCurrentContentComponent();
  45512. if (current != 0)
  45513. {
  45514. components.removeValue (current);
  45515. components.add (current);
  45516. }
  45517. }
  45518. }
  45519. if (components != oldList)
  45520. activeDocumentChanged();
  45521. }
  45522. END_JUCE_NAMESPACE
  45523. /********* End of inlined file: juce_MultiDocumentPanel.cpp *********/
  45524. /********* Start of inlined file: juce_ResizableBorderComponent.cpp *********/
  45525. BEGIN_JUCE_NAMESPACE
  45526. const int zoneL = 1;
  45527. const int zoneR = 2;
  45528. const int zoneT = 4;
  45529. const int zoneB = 8;
  45530. ResizableBorderComponent::ResizableBorderComponent (Component* const componentToResize,
  45531. ComponentBoundsConstrainer* const constrainer_)
  45532. : component (componentToResize),
  45533. constrainer (constrainer_),
  45534. borderSize (5),
  45535. mouseZone (0)
  45536. {
  45537. }
  45538. ResizableBorderComponent::~ResizableBorderComponent()
  45539. {
  45540. }
  45541. void ResizableBorderComponent::paint (Graphics& g)
  45542. {
  45543. getLookAndFeel().drawResizableFrame (g, getWidth(), getHeight(), borderSize);
  45544. }
  45545. void ResizableBorderComponent::mouseEnter (const MouseEvent& e)
  45546. {
  45547. updateMouseZone (e);
  45548. }
  45549. void ResizableBorderComponent::mouseMove (const MouseEvent& e)
  45550. {
  45551. updateMouseZone (e);
  45552. }
  45553. void ResizableBorderComponent::mouseDown (const MouseEvent& e)
  45554. {
  45555. if (component->isValidComponent())
  45556. {
  45557. updateMouseZone (e);
  45558. originalX = component->getX();
  45559. originalY = component->getY();
  45560. originalW = component->getWidth();
  45561. originalH = component->getHeight();
  45562. if (constrainer != 0)
  45563. constrainer->resizeStart();
  45564. }
  45565. else
  45566. {
  45567. jassertfalse
  45568. }
  45569. }
  45570. void ResizableBorderComponent::mouseDrag (const MouseEvent& e)
  45571. {
  45572. if (! component->isValidComponent())
  45573. {
  45574. jassertfalse
  45575. return;
  45576. }
  45577. int x = originalX;
  45578. int y = originalY;
  45579. int w = originalW;
  45580. int h = originalH;
  45581. const int dx = e.getDistanceFromDragStartX();
  45582. const int dy = e.getDistanceFromDragStartY();
  45583. if ((mouseZone & zoneL) != 0)
  45584. {
  45585. x += dx;
  45586. w -= dx;
  45587. }
  45588. if ((mouseZone & zoneT) != 0)
  45589. {
  45590. y += dy;
  45591. h -= dy;
  45592. }
  45593. if ((mouseZone & zoneR) != 0)
  45594. w += dx;
  45595. if ((mouseZone & zoneB) != 0)
  45596. h += dy;
  45597. if (constrainer != 0)
  45598. constrainer->setBoundsForComponent (component,
  45599. x, y, w, h,
  45600. (mouseZone & zoneT) != 0,
  45601. (mouseZone & zoneL) != 0,
  45602. (mouseZone & zoneB) != 0,
  45603. (mouseZone & zoneR) != 0);
  45604. else
  45605. component->setBounds (x, y, w, h);
  45606. }
  45607. void ResizableBorderComponent::mouseUp (const MouseEvent&)
  45608. {
  45609. if (constrainer != 0)
  45610. constrainer->resizeEnd();
  45611. }
  45612. bool ResizableBorderComponent::hitTest (int x, int y)
  45613. {
  45614. return x < borderSize.getLeft()
  45615. || x >= getWidth() - borderSize.getRight()
  45616. || y < borderSize.getTop()
  45617. || y >= getHeight() - borderSize.getBottom();
  45618. }
  45619. void ResizableBorderComponent::setBorderThickness (const BorderSize& newBorderSize) throw()
  45620. {
  45621. if (borderSize != newBorderSize)
  45622. {
  45623. borderSize = newBorderSize;
  45624. repaint();
  45625. }
  45626. }
  45627. const BorderSize ResizableBorderComponent::getBorderThickness() const throw()
  45628. {
  45629. return borderSize;
  45630. }
  45631. void ResizableBorderComponent::updateMouseZone (const MouseEvent& e) throw()
  45632. {
  45633. int newZone = 0;
  45634. if (ResizableBorderComponent::hitTest (e.x, e.y))
  45635. {
  45636. if (e.x < jmax (borderSize.getLeft(), proportionOfWidth (0.1f)))
  45637. newZone |= zoneL;
  45638. else if (e.x >= jmin (getWidth() - borderSize.getRight(), proportionOfWidth (0.9f)))
  45639. newZone |= zoneR;
  45640. if (e.y < jmax (borderSize.getTop(), proportionOfHeight (0.1f)))
  45641. newZone |= zoneT;
  45642. else if (e.y >= jmin (getHeight() - borderSize.getBottom(), proportionOfHeight (0.9f)))
  45643. newZone |= zoneB;
  45644. }
  45645. if (mouseZone != newZone)
  45646. {
  45647. mouseZone = newZone;
  45648. MouseCursor::StandardCursorType mc = MouseCursor::NormalCursor;
  45649. switch (newZone)
  45650. {
  45651. case (zoneL | zoneT):
  45652. mc = MouseCursor::TopLeftCornerResizeCursor;
  45653. break;
  45654. case zoneT:
  45655. mc = MouseCursor::TopEdgeResizeCursor;
  45656. break;
  45657. case (zoneR | zoneT):
  45658. mc = MouseCursor::TopRightCornerResizeCursor;
  45659. break;
  45660. case zoneL:
  45661. mc = MouseCursor::LeftEdgeResizeCursor;
  45662. break;
  45663. case zoneR:
  45664. mc = MouseCursor::RightEdgeResizeCursor;
  45665. break;
  45666. case (zoneL | zoneB):
  45667. mc = MouseCursor::BottomLeftCornerResizeCursor;
  45668. break;
  45669. case zoneB:
  45670. mc = MouseCursor::BottomEdgeResizeCursor;
  45671. break;
  45672. case (zoneR | zoneB):
  45673. mc = MouseCursor::BottomRightCornerResizeCursor;
  45674. break;
  45675. default:
  45676. break;
  45677. }
  45678. setMouseCursor (mc);
  45679. }
  45680. }
  45681. END_JUCE_NAMESPACE
  45682. /********* End of inlined file: juce_ResizableBorderComponent.cpp *********/
  45683. /********* Start of inlined file: juce_ResizableCornerComponent.cpp *********/
  45684. BEGIN_JUCE_NAMESPACE
  45685. ResizableCornerComponent::ResizableCornerComponent (Component* const componentToResize,
  45686. ComponentBoundsConstrainer* const constrainer_)
  45687. : component (componentToResize),
  45688. constrainer (constrainer_)
  45689. {
  45690. setRepaintsOnMouseActivity (true);
  45691. setMouseCursor (MouseCursor::BottomRightCornerResizeCursor);
  45692. }
  45693. ResizableCornerComponent::~ResizableCornerComponent()
  45694. {
  45695. }
  45696. void ResizableCornerComponent::paint (Graphics& g)
  45697. {
  45698. getLookAndFeel()
  45699. .drawCornerResizer (g, getWidth(), getHeight(),
  45700. isMouseOverOrDragging(),
  45701. isMouseButtonDown());
  45702. }
  45703. void ResizableCornerComponent::mouseDown (const MouseEvent&)
  45704. {
  45705. if (component->isValidComponent())
  45706. {
  45707. originalX = component->getX();
  45708. originalY = component->getY();
  45709. originalW = component->getWidth();
  45710. originalH = component->getHeight();
  45711. if (constrainer != 0)
  45712. constrainer->resizeStart();
  45713. }
  45714. else
  45715. {
  45716. jassertfalse
  45717. }
  45718. }
  45719. void ResizableCornerComponent::mouseDrag (const MouseEvent& e)
  45720. {
  45721. if (! component->isValidComponent())
  45722. {
  45723. jassertfalse
  45724. return;
  45725. }
  45726. int x = originalX;
  45727. int y = originalY;
  45728. int w = originalW + e.getDistanceFromDragStartX();
  45729. int h = originalH + e.getDistanceFromDragStartY();
  45730. if (constrainer != 0)
  45731. constrainer->setBoundsForComponent (component, x, y, w, h,
  45732. false, false, true, true);
  45733. else
  45734. component->setBounds (x, y, w, h);
  45735. }
  45736. void ResizableCornerComponent::mouseUp (const MouseEvent&)
  45737. {
  45738. if (constrainer != 0)
  45739. constrainer->resizeStart();
  45740. }
  45741. bool ResizableCornerComponent::hitTest (int x, int y)
  45742. {
  45743. if (getWidth() <= 0)
  45744. return false;
  45745. const int yAtX = getHeight() - (getHeight() * x / getWidth());
  45746. return y >= yAtX - getHeight() / 4;
  45747. }
  45748. END_JUCE_NAMESPACE
  45749. /********* End of inlined file: juce_ResizableCornerComponent.cpp *********/
  45750. /********* Start of inlined file: juce_ScrollBar.cpp *********/
  45751. BEGIN_JUCE_NAMESPACE
  45752. class ScrollbarButton : public Button
  45753. {
  45754. public:
  45755. int direction;
  45756. ScrollbarButton (const int direction_,
  45757. ScrollBar& owner_) throw()
  45758. : Button (String::empty),
  45759. direction (direction_),
  45760. owner (owner_)
  45761. {
  45762. setWantsKeyboardFocus (false);
  45763. }
  45764. ~ScrollbarButton()
  45765. {
  45766. }
  45767. void paintButton (Graphics& g,
  45768. bool isMouseOver,
  45769. bool isMouseDown)
  45770. {
  45771. getLookAndFeel()
  45772. .drawScrollbarButton (g, owner,
  45773. getWidth(), getHeight(),
  45774. direction,
  45775. owner.isVertical(),
  45776. isMouseOver, isMouseDown);
  45777. }
  45778. void clicked()
  45779. {
  45780. owner.moveScrollbarInSteps ((direction == 1 || direction == 2) ? 1 : -1);
  45781. }
  45782. juce_UseDebuggingNewOperator
  45783. private:
  45784. ScrollBar& owner;
  45785. ScrollbarButton (const ScrollbarButton&);
  45786. const ScrollbarButton& operator= (const ScrollbarButton&);
  45787. };
  45788. ScrollBar::ScrollBar (const bool vertical_,
  45789. const bool buttonsAreVisible)
  45790. : minimum (0.0),
  45791. maximum (1.0),
  45792. rangeStart (0.0),
  45793. rangeSize (0.1),
  45794. singleStepSize (0.1),
  45795. thumbAreaStart (0),
  45796. thumbAreaSize (0),
  45797. thumbStart (0),
  45798. thumbSize (0),
  45799. initialDelayInMillisecs (100),
  45800. repeatDelayInMillisecs (50),
  45801. minimumDelayInMillisecs (10),
  45802. vertical (vertical_),
  45803. isDraggingThumb (false),
  45804. alwaysVisible (false),
  45805. upButton (0),
  45806. downButton (0),
  45807. listeners (2)
  45808. {
  45809. setButtonVisibility (buttonsAreVisible);
  45810. setRepaintsOnMouseActivity (true);
  45811. setFocusContainer (true);
  45812. }
  45813. ScrollBar::~ScrollBar()
  45814. {
  45815. deleteAllChildren();
  45816. }
  45817. void ScrollBar::setRangeLimits (const double newMinimum,
  45818. const double newMaximum) throw()
  45819. {
  45820. minimum = newMinimum;
  45821. maximum = newMaximum;
  45822. jassert (maximum >= minimum); // these can't be the wrong way round!
  45823. setCurrentRangeStart (rangeStart);
  45824. updateThumbPosition();
  45825. }
  45826. void ScrollBar::setCurrentRange (double newStart,
  45827. double newSize) throw()
  45828. {
  45829. newSize = jlimit (0.0, maximum - minimum, newSize);
  45830. newStart = jlimit (minimum, maximum - newSize, newStart);
  45831. if (rangeStart != newStart
  45832. || rangeSize != newSize)
  45833. {
  45834. rangeStart = newStart;
  45835. rangeSize = newSize;
  45836. updateThumbPosition();
  45837. triggerAsyncUpdate();
  45838. }
  45839. }
  45840. void ScrollBar::setCurrentRangeStart (double newStart) throw()
  45841. {
  45842. setCurrentRange (newStart, rangeSize);
  45843. }
  45844. void ScrollBar::setSingleStepSize (const double newSingleStepSize) throw()
  45845. {
  45846. singleStepSize = newSingleStepSize;
  45847. }
  45848. void ScrollBar::moveScrollbarInSteps (const int howManySteps) throw()
  45849. {
  45850. setCurrentRangeStart (rangeStart + howManySteps * singleStepSize);
  45851. }
  45852. void ScrollBar::moveScrollbarInPages (const int howManyPages) throw()
  45853. {
  45854. setCurrentRangeStart (rangeStart + howManyPages * rangeSize);
  45855. }
  45856. void ScrollBar::scrollToTop() throw()
  45857. {
  45858. setCurrentRangeStart (minimum);
  45859. }
  45860. void ScrollBar::scrollToBottom() throw()
  45861. {
  45862. setCurrentRangeStart (maximum - rangeSize);
  45863. }
  45864. void ScrollBar::setButtonRepeatSpeed (const int initialDelayInMillisecs_,
  45865. const int repeatDelayInMillisecs_,
  45866. const int minimumDelayInMillisecs_) throw()
  45867. {
  45868. initialDelayInMillisecs = initialDelayInMillisecs_;
  45869. repeatDelayInMillisecs = repeatDelayInMillisecs_;
  45870. minimumDelayInMillisecs = minimumDelayInMillisecs_;
  45871. if (upButton != 0)
  45872. {
  45873. upButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  45874. downButton->setRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  45875. }
  45876. }
  45877. void ScrollBar::addListener (ScrollBarListener* const listener) throw()
  45878. {
  45879. jassert (listener != 0);
  45880. if (listener != 0)
  45881. listeners.add (listener);
  45882. }
  45883. void ScrollBar::removeListener (ScrollBarListener* const listener) throw()
  45884. {
  45885. listeners.removeValue (listener);
  45886. }
  45887. void ScrollBar::handleAsyncUpdate()
  45888. {
  45889. const double value = getCurrentRangeStart();
  45890. for (int i = listeners.size(); --i >= 0;)
  45891. {
  45892. ((ScrollBarListener*) listeners.getUnchecked (i))->scrollBarMoved (this, value);
  45893. i = jmin (i, listeners.size());
  45894. }
  45895. }
  45896. void ScrollBar::updateThumbPosition() throw()
  45897. {
  45898. int newThumbSize = roundDoubleToInt ((maximum > minimum) ? (rangeSize * thumbAreaSize) / (maximum - minimum)
  45899. : thumbAreaSize);
  45900. if (newThumbSize < getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  45901. newThumbSize = jmin (getLookAndFeel().getMinimumScrollbarThumbSize (*this), thumbAreaSize - 1);
  45902. if (newThumbSize > thumbAreaSize)
  45903. newThumbSize = thumbAreaSize;
  45904. int newThumbStart = thumbAreaStart;
  45905. if (maximum - minimum > rangeSize)
  45906. newThumbStart += roundDoubleToInt (((rangeStart - minimum) * (thumbAreaSize - newThumbSize))
  45907. / ((maximum - minimum) - rangeSize));
  45908. setVisible (alwaysVisible || (maximum - minimum > rangeSize && rangeSize > 0.0));
  45909. if (thumbStart != newThumbStart || thumbSize != newThumbSize)
  45910. {
  45911. const int repaintStart = jmin (thumbStart, newThumbStart) - 4;
  45912. const int repaintSize = jmax (thumbStart + thumbSize, newThumbStart + newThumbSize) + 8 - repaintStart;
  45913. if (vertical)
  45914. repaint (0, repaintStart, getWidth(), repaintSize);
  45915. else
  45916. repaint (repaintStart, 0, repaintSize, getHeight());
  45917. thumbStart = newThumbStart;
  45918. thumbSize = newThumbSize;
  45919. }
  45920. }
  45921. void ScrollBar::setOrientation (const bool shouldBeVertical) throw()
  45922. {
  45923. if (vertical != shouldBeVertical)
  45924. {
  45925. vertical = shouldBeVertical;
  45926. if (upButton != 0)
  45927. {
  45928. ((ScrollbarButton*) upButton)->direction = (vertical) ? 0 : 3;
  45929. ((ScrollbarButton*) downButton)->direction = (vertical) ? 2 : 1;
  45930. }
  45931. updateThumbPosition();
  45932. }
  45933. }
  45934. void ScrollBar::setButtonVisibility (const bool buttonsAreVisible)
  45935. {
  45936. deleteAndZero (upButton);
  45937. deleteAndZero (downButton);
  45938. if (buttonsAreVisible)
  45939. {
  45940. addAndMakeVisible (upButton = new ScrollbarButton ((vertical) ? 0 : 3, *this));
  45941. addAndMakeVisible (downButton = new ScrollbarButton ((vertical) ? 2 : 1, *this));
  45942. setButtonRepeatSpeed (initialDelayInMillisecs, repeatDelayInMillisecs, minimumDelayInMillisecs);
  45943. }
  45944. updateThumbPosition();
  45945. }
  45946. void ScrollBar::setAutoHide (const bool shouldHideWhenFullRange)
  45947. {
  45948. alwaysVisible = ! shouldHideWhenFullRange;
  45949. updateThumbPosition();
  45950. }
  45951. void ScrollBar::paint (Graphics& g)
  45952. {
  45953. if (thumbAreaSize > 0)
  45954. {
  45955. LookAndFeel& lf = getLookAndFeel();
  45956. const int thumb = (thumbAreaSize > lf.getMinimumScrollbarThumbSize (*this))
  45957. ? thumbSize : 0;
  45958. if (vertical)
  45959. {
  45960. lf.drawScrollbar (g, *this,
  45961. 0, thumbAreaStart,
  45962. getWidth(), thumbAreaSize,
  45963. vertical,
  45964. thumbStart, thumb,
  45965. isMouseOver(), isMouseButtonDown());
  45966. }
  45967. else
  45968. {
  45969. lf.drawScrollbar (g, *this,
  45970. thumbAreaStart, 0,
  45971. thumbAreaSize, getHeight(),
  45972. vertical,
  45973. thumbStart, thumb,
  45974. isMouseOver(), isMouseButtonDown());
  45975. }
  45976. }
  45977. }
  45978. void ScrollBar::lookAndFeelChanged()
  45979. {
  45980. setComponentEffect (getLookAndFeel().getScrollbarEffect());
  45981. }
  45982. void ScrollBar::resized()
  45983. {
  45984. const int length = ((vertical) ? getHeight() : getWidth());
  45985. const int buttonSize = (upButton != 0) ? jmin (getLookAndFeel().getScrollbarButtonSize (*this), (length >> 1))
  45986. : 0;
  45987. if (length < 32 + getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  45988. {
  45989. thumbAreaStart = length >> 1;
  45990. thumbAreaSize = 0;
  45991. }
  45992. else
  45993. {
  45994. thumbAreaStart = buttonSize;
  45995. thumbAreaSize = length - (buttonSize << 1);
  45996. }
  45997. if (upButton != 0)
  45998. {
  45999. if (vertical)
  46000. {
  46001. upButton->setBounds (0, 0, getWidth(), buttonSize);
  46002. downButton->setBounds (0, thumbAreaStart + thumbAreaSize, getWidth(), buttonSize);
  46003. }
  46004. else
  46005. {
  46006. upButton->setBounds (0, 0, buttonSize, getHeight());
  46007. downButton->setBounds (thumbAreaStart + thumbAreaSize, 0, buttonSize, getHeight());
  46008. }
  46009. }
  46010. updateThumbPosition();
  46011. }
  46012. void ScrollBar::mouseDown (const MouseEvent& e)
  46013. {
  46014. isDraggingThumb = false;
  46015. lastMousePos = vertical ? e.y : e.x;
  46016. dragStartMousePos = lastMousePos;
  46017. dragStartRange = rangeStart;
  46018. if (dragStartMousePos < thumbStart)
  46019. {
  46020. moveScrollbarInPages (-1);
  46021. startTimer (400);
  46022. }
  46023. else if (dragStartMousePos >= thumbStart + thumbSize)
  46024. {
  46025. moveScrollbarInPages (1);
  46026. startTimer (400);
  46027. }
  46028. else
  46029. {
  46030. isDraggingThumb = (thumbAreaSize > getLookAndFeel().getMinimumScrollbarThumbSize (*this))
  46031. && (thumbAreaSize > thumbSize);
  46032. }
  46033. }
  46034. void ScrollBar::mouseDrag (const MouseEvent& e)
  46035. {
  46036. if (isDraggingThumb)
  46037. {
  46038. const int deltaPixels = ((vertical) ? e.y : e.x) - dragStartMousePos;
  46039. setCurrentRangeStart (dragStartRange
  46040. + deltaPixels * ((maximum - minimum) - rangeSize)
  46041. / (thumbAreaSize - thumbSize));
  46042. }
  46043. else
  46044. {
  46045. lastMousePos = (vertical) ? e.y : e.x;
  46046. }
  46047. }
  46048. void ScrollBar::mouseUp (const MouseEvent&)
  46049. {
  46050. isDraggingThumb = false;
  46051. stopTimer();
  46052. repaint();
  46053. }
  46054. void ScrollBar::mouseWheelMove (const MouseEvent&,
  46055. float wheelIncrementX,
  46056. float wheelIncrementY)
  46057. {
  46058. float increment = vertical ? wheelIncrementY : wheelIncrementX;
  46059. if (increment < 0)
  46060. increment = jmin (increment * 10.0f, -1.0f);
  46061. else if (increment > 0)
  46062. increment = jmax (increment * 10.0f, 1.0f);
  46063. setCurrentRangeStart (rangeStart - singleStepSize * increment);
  46064. }
  46065. void ScrollBar::timerCallback()
  46066. {
  46067. if (isMouseButtonDown())
  46068. {
  46069. startTimer (40);
  46070. if (lastMousePos < thumbStart)
  46071. setCurrentRangeStart (rangeStart - rangeSize);
  46072. else if (lastMousePos > thumbStart + thumbSize)
  46073. setCurrentRangeStart (rangeStart + rangeSize);
  46074. }
  46075. else
  46076. {
  46077. stopTimer();
  46078. }
  46079. }
  46080. bool ScrollBar::keyPressed (const KeyPress& key)
  46081. {
  46082. if (! isVisible())
  46083. return false;
  46084. if (key.isKeyCode (KeyPress::upKey) || key.isKeyCode (KeyPress::leftKey))
  46085. moveScrollbarInSteps (-1);
  46086. else if (key.isKeyCode (KeyPress::downKey) || key.isKeyCode (KeyPress::rightKey))
  46087. moveScrollbarInSteps (1);
  46088. else if (key.isKeyCode (KeyPress::pageUpKey))
  46089. moveScrollbarInPages (-1);
  46090. else if (key.isKeyCode (KeyPress::pageDownKey))
  46091. moveScrollbarInPages (1);
  46092. else if (key.isKeyCode (KeyPress::homeKey))
  46093. scrollToTop();
  46094. else if (key.isKeyCode (KeyPress::endKey))
  46095. scrollToBottom();
  46096. else
  46097. return false;
  46098. return true;
  46099. }
  46100. END_JUCE_NAMESPACE
  46101. /********* End of inlined file: juce_ScrollBar.cpp *********/
  46102. /********* Start of inlined file: juce_StretchableLayoutManager.cpp *********/
  46103. BEGIN_JUCE_NAMESPACE
  46104. StretchableLayoutManager::StretchableLayoutManager()
  46105. : totalSize (0)
  46106. {
  46107. }
  46108. StretchableLayoutManager::~StretchableLayoutManager()
  46109. {
  46110. }
  46111. void StretchableLayoutManager::clearAllItems()
  46112. {
  46113. items.clear();
  46114. totalSize = 0;
  46115. }
  46116. void StretchableLayoutManager::setItemLayout (const int itemIndex,
  46117. const double minimumSize,
  46118. const double maximumSize,
  46119. const double preferredSize)
  46120. {
  46121. ItemLayoutProperties* layout = getInfoFor (itemIndex);
  46122. if (layout == 0)
  46123. {
  46124. layout = new ItemLayoutProperties();
  46125. layout->itemIndex = itemIndex;
  46126. int i;
  46127. for (i = 0; i < items.size(); ++i)
  46128. if (items.getUnchecked (i)->itemIndex > itemIndex)
  46129. break;
  46130. items.insert (i, layout);
  46131. }
  46132. layout->minSize = minimumSize;
  46133. layout->maxSize = maximumSize;
  46134. layout->preferredSize = preferredSize;
  46135. layout->currentSize = 0;
  46136. }
  46137. bool StretchableLayoutManager::getItemLayout (const int itemIndex,
  46138. double& minimumSize,
  46139. double& maximumSize,
  46140. double& preferredSize) const
  46141. {
  46142. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  46143. if (layout != 0)
  46144. {
  46145. minimumSize = layout->minSize;
  46146. maximumSize = layout->maxSize;
  46147. preferredSize = layout->preferredSize;
  46148. return true;
  46149. }
  46150. return false;
  46151. }
  46152. void StretchableLayoutManager::setTotalSize (const int newTotalSize)
  46153. {
  46154. totalSize = newTotalSize;
  46155. fitComponentsIntoSpace (0, items.size(), totalSize, 0);
  46156. }
  46157. int StretchableLayoutManager::getItemCurrentPosition (const int itemIndex) const
  46158. {
  46159. int pos = 0;
  46160. for (int i = 0; i < itemIndex; ++i)
  46161. {
  46162. const ItemLayoutProperties* const layout = getInfoFor (i);
  46163. if (layout != 0)
  46164. pos += layout->currentSize;
  46165. }
  46166. return pos;
  46167. }
  46168. int StretchableLayoutManager::getItemCurrentAbsoluteSize (const int itemIndex) const
  46169. {
  46170. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  46171. if (layout != 0)
  46172. return layout->currentSize;
  46173. return 0;
  46174. }
  46175. double StretchableLayoutManager::getItemCurrentRelativeSize (const int itemIndex) const
  46176. {
  46177. const ItemLayoutProperties* const layout = getInfoFor (itemIndex);
  46178. if (layout != 0)
  46179. return -layout->currentSize / (double) totalSize;
  46180. return 0;
  46181. }
  46182. void StretchableLayoutManager::setItemPosition (const int itemIndex,
  46183. int newPosition)
  46184. {
  46185. for (int i = items.size(); --i >= 0;)
  46186. {
  46187. const ItemLayoutProperties* const layout = items.getUnchecked(i);
  46188. if (layout->itemIndex == itemIndex)
  46189. {
  46190. int realTotalSize = jmax (totalSize, getMinimumSizeOfItems (0, items.size()));
  46191. const int minSizeAfterThisComp = getMinimumSizeOfItems (i, items.size());
  46192. const int maxSizeAfterThisComp = getMaximumSizeOfItems (i + 1, items.size());
  46193. newPosition = jmax (newPosition, totalSize - maxSizeAfterThisComp - layout->currentSize);
  46194. newPosition = jmin (newPosition, realTotalSize - minSizeAfterThisComp);
  46195. int endPos = fitComponentsIntoSpace (0, i, newPosition, 0);
  46196. endPos += layout->currentSize;
  46197. fitComponentsIntoSpace (i + 1, items.size(), totalSize - endPos, endPos);
  46198. updatePrefSizesToMatchCurrentPositions();
  46199. break;
  46200. }
  46201. }
  46202. }
  46203. void StretchableLayoutManager::layOutComponents (Component** const components,
  46204. int numComponents,
  46205. int x, int y, int w, int h,
  46206. const bool vertically,
  46207. const bool resizeOtherDimension)
  46208. {
  46209. setTotalSize (vertically ? h : w);
  46210. int pos = vertically ? y : x;
  46211. for (int i = 0; i < numComponents; ++i)
  46212. {
  46213. const ItemLayoutProperties* const layout = getInfoFor (i);
  46214. if (layout != 0)
  46215. {
  46216. Component* const c = components[i];
  46217. if (c != 0)
  46218. {
  46219. if (i == numComponents - 1)
  46220. {
  46221. // if it's the last item, crop it to exactly fit the available space..
  46222. if (resizeOtherDimension)
  46223. {
  46224. if (vertically)
  46225. c->setBounds (x, pos, w, jmax (layout->currentSize, h - pos));
  46226. else
  46227. c->setBounds (pos, y, jmax (layout->currentSize, w - pos), h);
  46228. }
  46229. else
  46230. {
  46231. if (vertically)
  46232. c->setBounds (c->getX(), pos, c->getWidth(), jmax (layout->currentSize, h - pos));
  46233. else
  46234. c->setBounds (pos, c->getY(), jmax (layout->currentSize, w - pos), c->getHeight());
  46235. }
  46236. }
  46237. else
  46238. {
  46239. if (resizeOtherDimension)
  46240. {
  46241. if (vertically)
  46242. c->setBounds (x, pos, w, layout->currentSize);
  46243. else
  46244. c->setBounds (pos, y, layout->currentSize, h);
  46245. }
  46246. else
  46247. {
  46248. if (vertically)
  46249. c->setBounds (c->getX(), pos, c->getWidth(), layout->currentSize);
  46250. else
  46251. c->setBounds (pos, c->getY(), layout->currentSize, c->getHeight());
  46252. }
  46253. }
  46254. }
  46255. pos += layout->currentSize;
  46256. }
  46257. }
  46258. }
  46259. StretchableLayoutManager::ItemLayoutProperties* StretchableLayoutManager::getInfoFor (const int itemIndex) const
  46260. {
  46261. for (int i = items.size(); --i >= 0;)
  46262. if (items.getUnchecked(i)->itemIndex == itemIndex)
  46263. return items.getUnchecked(i);
  46264. return 0;
  46265. }
  46266. int StretchableLayoutManager::fitComponentsIntoSpace (const int startIndex,
  46267. const int endIndex,
  46268. const int availableSpace,
  46269. int startPos)
  46270. {
  46271. // calculate the total sizes
  46272. int i;
  46273. double totalIdealSize = 0.0;
  46274. int totalMinimums = 0;
  46275. for (i = startIndex; i < endIndex; ++i)
  46276. {
  46277. ItemLayoutProperties* const layout = items.getUnchecked (i);
  46278. layout->currentSize = sizeToRealSize (layout->minSize, totalSize);
  46279. totalMinimums += layout->currentSize;
  46280. totalIdealSize += sizeToRealSize (layout->preferredSize, availableSpace);
  46281. }
  46282. if (totalIdealSize <= 0)
  46283. totalIdealSize = 1.0;
  46284. // now calc the best sizes..
  46285. int extraSpace = availableSpace - totalMinimums;
  46286. while (extraSpace > 0)
  46287. {
  46288. int numWantingMoreSpace = 0;
  46289. int numHavingTakenExtraSpace = 0;
  46290. // first figure out how many comps want a slice of the extra space..
  46291. for (i = startIndex; i < endIndex; ++i)
  46292. {
  46293. ItemLayoutProperties* const layout = items.getUnchecked (i);
  46294. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  46295. const int bestSize = jlimit (layout->currentSize,
  46296. jmax (layout->currentSize,
  46297. sizeToRealSize (layout->maxSize, totalSize)),
  46298. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  46299. if (bestSize > layout->currentSize)
  46300. ++numWantingMoreSpace;
  46301. }
  46302. // ..share out the extra space..
  46303. for (i = startIndex; i < endIndex; ++i)
  46304. {
  46305. ItemLayoutProperties* const layout = items.getUnchecked (i);
  46306. double sizeWanted = sizeToRealSize (layout->preferredSize, availableSpace);
  46307. int bestSize = jlimit (layout->currentSize,
  46308. jmax (layout->currentSize, sizeToRealSize (layout->maxSize, totalSize)),
  46309. roundDoubleToInt (sizeWanted * availableSpace / totalIdealSize));
  46310. const int extraWanted = bestSize - layout->currentSize;
  46311. if (extraWanted > 0)
  46312. {
  46313. const int extraAllowed = jmin (extraWanted,
  46314. extraSpace / jmax (1, numWantingMoreSpace));
  46315. if (extraAllowed > 0)
  46316. {
  46317. ++numHavingTakenExtraSpace;
  46318. --numWantingMoreSpace;
  46319. layout->currentSize += extraAllowed;
  46320. extraSpace -= extraAllowed;
  46321. }
  46322. }
  46323. }
  46324. if (numHavingTakenExtraSpace <= 0)
  46325. break;
  46326. }
  46327. // ..and calculate the end position
  46328. for (i = startIndex; i < endIndex; ++i)
  46329. {
  46330. ItemLayoutProperties* const layout = items.getUnchecked(i);
  46331. startPos += layout->currentSize;
  46332. }
  46333. return startPos;
  46334. }
  46335. int StretchableLayoutManager::getMinimumSizeOfItems (const int startIndex,
  46336. const int endIndex) const
  46337. {
  46338. int totalMinimums = 0;
  46339. for (int i = startIndex; i < endIndex; ++i)
  46340. totalMinimums += sizeToRealSize (items.getUnchecked (i)->minSize, totalSize);
  46341. return totalMinimums;
  46342. }
  46343. int StretchableLayoutManager::getMaximumSizeOfItems (const int startIndex, const int endIndex) const
  46344. {
  46345. int totalMaximums = 0;
  46346. for (int i = startIndex; i < endIndex; ++i)
  46347. totalMaximums += sizeToRealSize (items.getUnchecked (i)->maxSize, totalSize);
  46348. return totalMaximums;
  46349. }
  46350. void StretchableLayoutManager::updatePrefSizesToMatchCurrentPositions()
  46351. {
  46352. for (int i = 0; i < items.size(); ++i)
  46353. {
  46354. ItemLayoutProperties* const layout = items.getUnchecked (i);
  46355. layout->preferredSize
  46356. = (layout->preferredSize < 0) ? getItemCurrentRelativeSize (i)
  46357. : getItemCurrentAbsoluteSize (i);
  46358. }
  46359. }
  46360. int StretchableLayoutManager::sizeToRealSize (double size, int totalSpace)
  46361. {
  46362. if (size < 0)
  46363. size *= -totalSpace;
  46364. return roundDoubleToInt (size);
  46365. }
  46366. END_JUCE_NAMESPACE
  46367. /********* End of inlined file: juce_StretchableLayoutManager.cpp *********/
  46368. /********* Start of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  46369. BEGIN_JUCE_NAMESPACE
  46370. StretchableLayoutResizerBar::StretchableLayoutResizerBar (StretchableLayoutManager* layout_,
  46371. const int itemIndex_,
  46372. const bool isVertical_)
  46373. : layout (layout_),
  46374. itemIndex (itemIndex_),
  46375. isVertical (isVertical_)
  46376. {
  46377. setRepaintsOnMouseActivity (true);
  46378. setMouseCursor (MouseCursor (isVertical_ ? MouseCursor::LeftRightResizeCursor
  46379. : MouseCursor::UpDownResizeCursor));
  46380. }
  46381. StretchableLayoutResizerBar::~StretchableLayoutResizerBar()
  46382. {
  46383. }
  46384. void StretchableLayoutResizerBar::paint (Graphics& g)
  46385. {
  46386. getLookAndFeel().drawStretchableLayoutResizerBar (g,
  46387. getWidth(), getHeight(),
  46388. isVertical,
  46389. isMouseOver(),
  46390. isMouseButtonDown());
  46391. }
  46392. void StretchableLayoutResizerBar::mouseDown (const MouseEvent&)
  46393. {
  46394. mouseDownPos = layout->getItemCurrentPosition (itemIndex);
  46395. }
  46396. void StretchableLayoutResizerBar::mouseDrag (const MouseEvent& e)
  46397. {
  46398. const int desiredPos = mouseDownPos + (isVertical ? e.getDistanceFromDragStartX()
  46399. : e.getDistanceFromDragStartY());
  46400. layout->setItemPosition (itemIndex, desiredPos);
  46401. hasBeenMoved();
  46402. }
  46403. void StretchableLayoutResizerBar::hasBeenMoved()
  46404. {
  46405. if (getParentComponent() != 0)
  46406. getParentComponent()->resized();
  46407. }
  46408. END_JUCE_NAMESPACE
  46409. /********* End of inlined file: juce_StretchableLayoutResizerBar.cpp *********/
  46410. /********* Start of inlined file: juce_StretchableObjectResizer.cpp *********/
  46411. BEGIN_JUCE_NAMESPACE
  46412. StretchableObjectResizer::StretchableObjectResizer()
  46413. {
  46414. }
  46415. StretchableObjectResizer::~StretchableObjectResizer()
  46416. {
  46417. }
  46418. void StretchableObjectResizer::addItem (const double size,
  46419. const double minSize, const double maxSize,
  46420. const int order)
  46421. {
  46422. jassert (order >= 0 && order < INT_MAX); // the order must be >= 0 and less than INT_MAX
  46423. Item* const item = new Item();
  46424. item->size = size;
  46425. item->minSize = minSize;
  46426. item->maxSize = maxSize;
  46427. item->order = order;
  46428. items.add (item);
  46429. }
  46430. double StretchableObjectResizer::getItemSize (const int index) const throw()
  46431. {
  46432. const Item* const it = items [index];
  46433. return it != 0 ? it->size : 0;
  46434. }
  46435. void StretchableObjectResizer::resizeToFit (const double targetSize)
  46436. {
  46437. int order = 0;
  46438. for (;;)
  46439. {
  46440. double currentSize = 0;
  46441. double minSize = 0;
  46442. double maxSize = 0;
  46443. int nextHighestOrder = INT_MAX;
  46444. for (int i = 0; i < items.size(); ++i)
  46445. {
  46446. const Item* const it = items.getUnchecked(i);
  46447. currentSize += it->size;
  46448. if (it->order <= order)
  46449. {
  46450. minSize += it->minSize;
  46451. maxSize += it->maxSize;
  46452. }
  46453. else
  46454. {
  46455. minSize += it->size;
  46456. maxSize += it->size;
  46457. nextHighestOrder = jmin (nextHighestOrder, it->order);
  46458. }
  46459. }
  46460. const double thisIterationTarget = jlimit (minSize, maxSize, targetSize);
  46461. if (thisIterationTarget >= currentSize)
  46462. {
  46463. const double availableExtraSpace = maxSize - currentSize;
  46464. const double targetAmountOfExtraSpace = thisIterationTarget - currentSize;
  46465. const double scale = targetAmountOfExtraSpace / availableExtraSpace;
  46466. for (int i = 0; i < items.size(); ++i)
  46467. {
  46468. Item* const it = items.getUnchecked(i);
  46469. if (it->order <= order)
  46470. it->size = jmin (it->maxSize, it->size + (it->maxSize - it->size) * scale);
  46471. }
  46472. }
  46473. else
  46474. {
  46475. const double amountOfSlack = currentSize - minSize;
  46476. const double targetAmountOfSlack = thisIterationTarget - minSize;
  46477. const double scale = targetAmountOfSlack / amountOfSlack;
  46478. for (int i = 0; i < items.size(); ++i)
  46479. {
  46480. Item* const it = items.getUnchecked(i);
  46481. if (it->order <= order)
  46482. it->size = jmax (it->minSize, it->minSize + (it->size - it->minSize) * scale);
  46483. }
  46484. }
  46485. if (nextHighestOrder < INT_MAX)
  46486. order = nextHighestOrder;
  46487. else
  46488. break;
  46489. }
  46490. }
  46491. END_JUCE_NAMESPACE
  46492. /********* End of inlined file: juce_StretchableObjectResizer.cpp *********/
  46493. /********* Start of inlined file: juce_TabbedButtonBar.cpp *********/
  46494. BEGIN_JUCE_NAMESPACE
  46495. TabBarButton::TabBarButton (const String& name,
  46496. TabbedButtonBar* const owner_,
  46497. const int index)
  46498. : Button (name),
  46499. owner (owner_),
  46500. tabIndex (index),
  46501. overlapPixels (0)
  46502. {
  46503. shadow.setShadowProperties (2.2f, 0.7f, 0, 0);
  46504. setComponentEffect (&shadow);
  46505. setWantsKeyboardFocus (false);
  46506. }
  46507. TabBarButton::~TabBarButton()
  46508. {
  46509. }
  46510. void TabBarButton::paintButton (Graphics& g,
  46511. bool isMouseOverButton,
  46512. bool isButtonDown)
  46513. {
  46514. int x, y, w, h;
  46515. getActiveArea (x, y, w, h);
  46516. g.setOrigin (x, y);
  46517. getLookAndFeel()
  46518. .drawTabButton (g, w, h,
  46519. owner->getTabBackgroundColour (tabIndex),
  46520. tabIndex, getButtonText(), *this,
  46521. owner->getOrientation(),
  46522. isMouseOverButton, isButtonDown,
  46523. getToggleState());
  46524. }
  46525. void TabBarButton::clicked (const ModifierKeys& mods)
  46526. {
  46527. if (mods.isPopupMenu())
  46528. owner->popupMenuClickOnTab (tabIndex, getButtonText());
  46529. else
  46530. owner->setCurrentTabIndex (tabIndex);
  46531. }
  46532. bool TabBarButton::hitTest (int mx, int my)
  46533. {
  46534. int x, y, w, h;
  46535. getActiveArea (x, y, w, h);
  46536. if (owner->getOrientation() == TabbedButtonBar::TabsAtLeft
  46537. || owner->getOrientation() == TabbedButtonBar::TabsAtRight)
  46538. {
  46539. if (((unsigned int) mx) < (unsigned int) getWidth()
  46540. && my >= y + overlapPixels
  46541. && my < y + h - overlapPixels)
  46542. return true;
  46543. }
  46544. else
  46545. {
  46546. if (mx >= x + overlapPixels && mx < x + w - overlapPixels
  46547. && ((unsigned int) my) < (unsigned int) getHeight())
  46548. return true;
  46549. }
  46550. Path p;
  46551. getLookAndFeel()
  46552. .createTabButtonShape (p, w, h, tabIndex, getButtonText(), *this,
  46553. owner->getOrientation(),
  46554. false, false, getToggleState());
  46555. return p.contains ((float) (mx - x),
  46556. (float) (my - y));
  46557. }
  46558. int TabBarButton::getBestTabLength (const int depth)
  46559. {
  46560. return jlimit (depth * 2,
  46561. depth * 7,
  46562. getLookAndFeel().getTabButtonBestWidth (tabIndex, getButtonText(), depth, *this));
  46563. }
  46564. void TabBarButton::getActiveArea (int& x, int& y, int& w, int& h)
  46565. {
  46566. x = 0;
  46567. y = 0;
  46568. int r = getWidth();
  46569. int b = getHeight();
  46570. const int spaceAroundImage = getLookAndFeel().getTabButtonSpaceAroundImage();
  46571. if (owner->getOrientation() != TabbedButtonBar::TabsAtLeft)
  46572. r -= spaceAroundImage;
  46573. if (owner->getOrientation() != TabbedButtonBar::TabsAtRight)
  46574. x += spaceAroundImage;
  46575. if (owner->getOrientation() != TabbedButtonBar::TabsAtBottom)
  46576. y += spaceAroundImage;
  46577. if (owner->getOrientation() != TabbedButtonBar::TabsAtTop)
  46578. b -= spaceAroundImage;
  46579. w = r - x;
  46580. h = b - y;
  46581. }
  46582. class TabAreaBehindFrontButtonComponent : public Component
  46583. {
  46584. public:
  46585. TabAreaBehindFrontButtonComponent (TabbedButtonBar* const owner_)
  46586. : owner (owner_)
  46587. {
  46588. setInterceptsMouseClicks (false, false);
  46589. }
  46590. ~TabAreaBehindFrontButtonComponent()
  46591. {
  46592. }
  46593. void paint (Graphics& g)
  46594. {
  46595. getLookAndFeel()
  46596. .drawTabAreaBehindFrontButton (g, getWidth(), getHeight(),
  46597. *owner, owner->getOrientation());
  46598. }
  46599. void enablementChanged()
  46600. {
  46601. repaint();
  46602. }
  46603. private:
  46604. TabbedButtonBar* const owner;
  46605. TabAreaBehindFrontButtonComponent (const TabAreaBehindFrontButtonComponent&);
  46606. const TabAreaBehindFrontButtonComponent& operator= (const TabAreaBehindFrontButtonComponent&);
  46607. };
  46608. TabbedButtonBar::TabbedButtonBar (const Orientation orientation_)
  46609. : orientation (orientation_),
  46610. currentTabIndex (-1),
  46611. extraTabsButton (0)
  46612. {
  46613. setInterceptsMouseClicks (false, true);
  46614. addAndMakeVisible (behindFrontTab = new TabAreaBehindFrontButtonComponent (this));
  46615. setFocusContainer (true);
  46616. }
  46617. TabbedButtonBar::~TabbedButtonBar()
  46618. {
  46619. deleteAllChildren();
  46620. }
  46621. void TabbedButtonBar::setOrientation (const Orientation newOrientation)
  46622. {
  46623. orientation = newOrientation;
  46624. for (int i = getNumChildComponents(); --i >= 0;)
  46625. getChildComponent (i)->resized();
  46626. resized();
  46627. }
  46628. TabBarButton* TabbedButtonBar::createTabButton (const String& name, const int index)
  46629. {
  46630. return new TabBarButton (name, this, index);
  46631. }
  46632. void TabbedButtonBar::clearTabs()
  46633. {
  46634. tabs.clear();
  46635. tabColours.clear();
  46636. currentTabIndex = -1;
  46637. deleteAndZero (extraTabsButton);
  46638. removeChildComponent (behindFrontTab);
  46639. deleteAllChildren();
  46640. addChildComponent (behindFrontTab);
  46641. setCurrentTabIndex (-1);
  46642. }
  46643. void TabbedButtonBar::addTab (const String& tabName,
  46644. const Colour& tabBackgroundColour,
  46645. int insertIndex)
  46646. {
  46647. jassert (tabName.isNotEmpty()); // you have to give them all a name..
  46648. if (tabName.isNotEmpty())
  46649. {
  46650. if (((unsigned int) insertIndex) > (unsigned int) tabs.size())
  46651. insertIndex = tabs.size();
  46652. for (int i = tabs.size(); --i >= insertIndex;)
  46653. {
  46654. TabBarButton* const tb = getTabButton (i);
  46655. if (tb != 0)
  46656. tb->tabIndex++;
  46657. }
  46658. tabs.insert (insertIndex, tabName);
  46659. tabColours.insert (insertIndex, tabBackgroundColour);
  46660. TabBarButton* const tb = createTabButton (tabName, insertIndex);
  46661. jassert (tb != 0); // your createTabButton() mustn't return zero!
  46662. addAndMakeVisible (tb, insertIndex);
  46663. resized();
  46664. if (currentTabIndex < 0)
  46665. setCurrentTabIndex (0);
  46666. }
  46667. }
  46668. void TabbedButtonBar::setTabName (const int tabIndex,
  46669. const String& newName)
  46670. {
  46671. if (((unsigned int) tabIndex) < (unsigned int) tabs.size()
  46672. && tabs[tabIndex] != newName)
  46673. {
  46674. tabs.set (tabIndex, newName);
  46675. TabBarButton* const tb = getTabButton (tabIndex);
  46676. if (tb != 0)
  46677. tb->setButtonText (newName);
  46678. resized();
  46679. }
  46680. }
  46681. void TabbedButtonBar::removeTab (const int tabIndex)
  46682. {
  46683. if (((unsigned int) tabIndex) < (unsigned int) tabs.size())
  46684. {
  46685. const int oldTabIndex = currentTabIndex;
  46686. if (currentTabIndex == tabIndex)
  46687. currentTabIndex = -1;
  46688. tabs.remove (tabIndex);
  46689. tabColours.remove (tabIndex);
  46690. TabBarButton* const tb = getTabButton (tabIndex);
  46691. if (tb != 0)
  46692. delete tb;
  46693. for (int i = tabIndex + 1; i <= tabs.size(); ++i)
  46694. {
  46695. TabBarButton* const tb = getTabButton (i);
  46696. if (tb != 0)
  46697. tb->tabIndex--;
  46698. }
  46699. resized();
  46700. setCurrentTabIndex (jlimit (0, jmax (0, tabs.size() - 1), oldTabIndex));
  46701. }
  46702. }
  46703. void TabbedButtonBar::moveTab (const int currentIndex,
  46704. const int newIndex)
  46705. {
  46706. tabs.move (currentIndex, newIndex);
  46707. tabColours.move (currentIndex, newIndex);
  46708. resized();
  46709. }
  46710. int TabbedButtonBar::getNumTabs() const
  46711. {
  46712. return tabs.size();
  46713. }
  46714. const StringArray TabbedButtonBar::getTabNames() const
  46715. {
  46716. return tabs;
  46717. }
  46718. void TabbedButtonBar::setCurrentTabIndex (int newIndex)
  46719. {
  46720. if (currentTabIndex != newIndex)
  46721. {
  46722. if (((unsigned int) newIndex) >= (unsigned int) tabs.size())
  46723. newIndex = -1;
  46724. currentTabIndex = newIndex;
  46725. for (int i = 0; i < getNumChildComponents(); ++i)
  46726. {
  46727. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  46728. if (tb != 0)
  46729. tb->setToggleState (tb->tabIndex == newIndex, false);
  46730. }
  46731. resized();
  46732. sendChangeMessage (this);
  46733. currentTabChanged (newIndex, newIndex >= 0 ? tabs [newIndex] : String::empty);
  46734. }
  46735. }
  46736. TabBarButton* TabbedButtonBar::getTabButton (const int index) const
  46737. {
  46738. for (int i = getNumChildComponents(); --i >= 0;)
  46739. {
  46740. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  46741. if (tb != 0 && tb->tabIndex == index)
  46742. return tb;
  46743. }
  46744. return 0;
  46745. }
  46746. void TabbedButtonBar::lookAndFeelChanged()
  46747. {
  46748. deleteAndZero (extraTabsButton);
  46749. resized();
  46750. }
  46751. void TabbedButtonBar::resized()
  46752. {
  46753. const double minimumScale = 0.7;
  46754. int depth = getWidth();
  46755. int length = getHeight();
  46756. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  46757. swapVariables (depth, length);
  46758. const int overlap = getLookAndFeel().getTabButtonOverlap (depth)
  46759. + getLookAndFeel().getTabButtonSpaceAroundImage() * 2;
  46760. int i, totalLength = overlap;
  46761. int numVisibleButtons = tabs.size();
  46762. for (i = 0; i < getNumChildComponents(); ++i)
  46763. {
  46764. TabBarButton* const tb = dynamic_cast <TabBarButton*> (getChildComponent (i));
  46765. if (tb != 0)
  46766. {
  46767. totalLength += tb->getBestTabLength (depth) - overlap;
  46768. tb->overlapPixels = overlap / 2;
  46769. }
  46770. }
  46771. double scale = 1.0;
  46772. if (totalLength > length)
  46773. scale = jmax (minimumScale, length / (double) totalLength);
  46774. const bool isTooBig = totalLength * scale > length;
  46775. int tabsButtonPos = 0;
  46776. if (isTooBig)
  46777. {
  46778. if (extraTabsButton == 0)
  46779. {
  46780. addAndMakeVisible (extraTabsButton = getLookAndFeel().createTabBarExtrasButton());
  46781. extraTabsButton->addButtonListener (this);
  46782. extraTabsButton->setAlwaysOnTop (true);
  46783. extraTabsButton->setTriggeredOnMouseDown (true);
  46784. }
  46785. const int buttonSize = jmin (proportionOfWidth (0.7f), proportionOfHeight (0.7f));
  46786. extraTabsButton->setSize (buttonSize, buttonSize);
  46787. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  46788. {
  46789. tabsButtonPos = getWidth() - buttonSize / 2 - 1;
  46790. extraTabsButton->setCentrePosition (tabsButtonPos, getHeight() / 2);
  46791. }
  46792. else
  46793. {
  46794. tabsButtonPos = getHeight() - buttonSize / 2 - 1;
  46795. extraTabsButton->setCentrePosition (getWidth() / 2, tabsButtonPos);
  46796. }
  46797. totalLength = 0;
  46798. for (i = 0; i < tabs.size(); ++i)
  46799. {
  46800. TabBarButton* const tb = getTabButton (i);
  46801. if (tb != 0)
  46802. {
  46803. const int newLength = totalLength + tb->getBestTabLength (depth);
  46804. if (i > 0 && newLength * minimumScale > tabsButtonPos)
  46805. {
  46806. totalLength += overlap;
  46807. break;
  46808. }
  46809. numVisibleButtons = i + 1;
  46810. totalLength = newLength - overlap;
  46811. }
  46812. }
  46813. scale = jmax (minimumScale, tabsButtonPos / (double) totalLength);
  46814. }
  46815. else
  46816. {
  46817. deleteAndZero (extraTabsButton);
  46818. }
  46819. int pos = 0;
  46820. TabBarButton* frontTab = 0;
  46821. for (i = 0; i < tabs.size(); ++i)
  46822. {
  46823. TabBarButton* const tb = getTabButton (i);
  46824. if (tb != 0)
  46825. {
  46826. const int bestLength = roundDoubleToInt (scale * tb->getBestTabLength (depth));
  46827. if (i < numVisibleButtons)
  46828. {
  46829. if (orientation == TabsAtTop || orientation == TabsAtBottom)
  46830. tb->setBounds (pos, 0, bestLength, getHeight());
  46831. else
  46832. tb->setBounds (0, pos, getWidth(), bestLength);
  46833. tb->toBack();
  46834. if (tb->tabIndex == currentTabIndex)
  46835. frontTab = tb;
  46836. tb->setVisible (true);
  46837. }
  46838. else
  46839. {
  46840. tb->setVisible (false);
  46841. }
  46842. pos += bestLength - overlap;
  46843. }
  46844. }
  46845. behindFrontTab->setBounds (0, 0, getWidth(), getHeight());
  46846. if (frontTab != 0)
  46847. {
  46848. frontTab->toFront (false);
  46849. behindFrontTab->toBehind (frontTab);
  46850. }
  46851. }
  46852. const Colour TabbedButtonBar::getTabBackgroundColour (const int tabIndex)
  46853. {
  46854. return tabColours [tabIndex];
  46855. }
  46856. void TabbedButtonBar::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  46857. {
  46858. if (((unsigned int) tabIndex) < (unsigned int) tabColours.size()
  46859. && tabColours [tabIndex] != newColour)
  46860. {
  46861. tabColours.set (tabIndex, newColour);
  46862. repaint();
  46863. }
  46864. }
  46865. void TabbedButtonBar::buttonClicked (Button* button)
  46866. {
  46867. if (extraTabsButton == button)
  46868. {
  46869. PopupMenu m;
  46870. for (int i = 0; i < tabs.size(); ++i)
  46871. {
  46872. TabBarButton* const tb = getTabButton (i);
  46873. if (tb != 0 && ! tb->isVisible())
  46874. m.addItem (tb->tabIndex + 1, tabs[i], true, i == currentTabIndex);
  46875. }
  46876. const int res = m.showAt (extraTabsButton);
  46877. if (res != 0)
  46878. setCurrentTabIndex (res - 1);
  46879. }
  46880. }
  46881. void TabbedButtonBar::currentTabChanged (const int, const String&)
  46882. {
  46883. }
  46884. void TabbedButtonBar::popupMenuClickOnTab (const int, const String&)
  46885. {
  46886. }
  46887. END_JUCE_NAMESPACE
  46888. /********* End of inlined file: juce_TabbedButtonBar.cpp *********/
  46889. /********* Start of inlined file: juce_TabbedComponent.cpp *********/
  46890. BEGIN_JUCE_NAMESPACE
  46891. class TabCompButtonBar : public TabbedButtonBar
  46892. {
  46893. public:
  46894. TabCompButtonBar (TabbedComponent* const owner_,
  46895. const TabbedButtonBar::Orientation orientation)
  46896. : TabbedButtonBar (orientation),
  46897. owner (owner_)
  46898. {
  46899. }
  46900. ~TabCompButtonBar()
  46901. {
  46902. }
  46903. void currentTabChanged (const int newCurrentTabIndex,
  46904. const String& newTabName)
  46905. {
  46906. owner->changeCallback (newCurrentTabIndex, newTabName);
  46907. }
  46908. void popupMenuClickOnTab (const int tabIndex,
  46909. const String& tabName)
  46910. {
  46911. owner->popupMenuClickOnTab (tabIndex, tabName);
  46912. }
  46913. const Colour getTabBackgroundColour (const int tabIndex)
  46914. {
  46915. return owner->tabs->getTabBackgroundColour (tabIndex);
  46916. }
  46917. TabBarButton* createTabButton (const String& tabName, const int tabIndex)
  46918. {
  46919. return owner->createTabButton (tabName, tabIndex);
  46920. }
  46921. juce_UseDebuggingNewOperator
  46922. private:
  46923. TabbedComponent* const owner;
  46924. TabCompButtonBar (const TabCompButtonBar&);
  46925. const TabCompButtonBar& operator= (const TabCompButtonBar&);
  46926. };
  46927. TabbedComponent::TabbedComponent (const TabbedButtonBar::Orientation orientation)
  46928. : panelComponent (0),
  46929. tabDepth (30),
  46930. outlineColour (Colours::grey),
  46931. outlineThickness (1),
  46932. edgeIndent (0)
  46933. {
  46934. addAndMakeVisible (tabs = new TabCompButtonBar (this, orientation));
  46935. }
  46936. TabbedComponent::~TabbedComponent()
  46937. {
  46938. clearTabs();
  46939. delete tabs;
  46940. }
  46941. void TabbedComponent::setOrientation (const TabbedButtonBar::Orientation orientation)
  46942. {
  46943. tabs->setOrientation (orientation);
  46944. resized();
  46945. }
  46946. TabbedButtonBar::Orientation TabbedComponent::getOrientation() const throw()
  46947. {
  46948. return tabs->getOrientation();
  46949. }
  46950. void TabbedComponent::setTabBarDepth (const int newDepth)
  46951. {
  46952. if (tabDepth != newDepth)
  46953. {
  46954. tabDepth = newDepth;
  46955. resized();
  46956. }
  46957. }
  46958. TabBarButton* TabbedComponent::createTabButton (const String& tabName, const int tabIndex)
  46959. {
  46960. return new TabBarButton (tabName, tabs, tabIndex);
  46961. }
  46962. void TabbedComponent::clearTabs()
  46963. {
  46964. if (panelComponent != 0)
  46965. {
  46966. panelComponent->setVisible (false);
  46967. removeChildComponent (panelComponent);
  46968. panelComponent = 0;
  46969. }
  46970. tabs->clearTabs();
  46971. for (int i = contentComponents.size(); --i >= 0;)
  46972. {
  46973. Component* const c = contentComponents.getUnchecked(i);
  46974. // be careful not to delete these components until they've been removed from the tab component
  46975. jassert (c == 0 || c->isValidComponent());
  46976. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  46977. delete c;
  46978. }
  46979. contentComponents.clear();
  46980. }
  46981. void TabbedComponent::addTab (const String& tabName,
  46982. const Colour& tabBackgroundColour,
  46983. Component* const contentComponent,
  46984. const bool deleteComponentWhenNotNeeded,
  46985. const int insertIndex)
  46986. {
  46987. contentComponents.insert (insertIndex, contentComponent);
  46988. if (contentComponent != 0)
  46989. contentComponent->setComponentProperty (T("deleteByTabComp_"), deleteComponentWhenNotNeeded);
  46990. tabs->addTab (tabName, tabBackgroundColour, insertIndex);
  46991. }
  46992. void TabbedComponent::setTabName (const int tabIndex,
  46993. const String& newName)
  46994. {
  46995. tabs->setTabName (tabIndex, newName);
  46996. }
  46997. void TabbedComponent::removeTab (const int tabIndex)
  46998. {
  46999. Component* const c = contentComponents [tabIndex];
  47000. if (c != 0 && c->getComponentPropertyBool (T("deleteByTabComp_"), false, false))
  47001. {
  47002. if (c == panelComponent)
  47003. panelComponent = 0;
  47004. delete c;
  47005. }
  47006. contentComponents.remove (tabIndex);
  47007. tabs->removeTab (tabIndex);
  47008. }
  47009. int TabbedComponent::getNumTabs() const
  47010. {
  47011. return tabs->getNumTabs();
  47012. }
  47013. const StringArray TabbedComponent::getTabNames() const
  47014. {
  47015. return tabs->getTabNames();
  47016. }
  47017. Component* TabbedComponent::getTabContentComponent (const int tabIndex) const throw()
  47018. {
  47019. return contentComponents [tabIndex];
  47020. }
  47021. const Colour TabbedComponent::getTabBackgroundColour (const int tabIndex) const throw()
  47022. {
  47023. return tabs->getTabBackgroundColour (tabIndex);
  47024. }
  47025. void TabbedComponent::setTabBackgroundColour (const int tabIndex, const Colour& newColour)
  47026. {
  47027. tabs->setTabBackgroundColour (tabIndex, newColour);
  47028. if (getCurrentTabIndex() == tabIndex)
  47029. repaint();
  47030. }
  47031. void TabbedComponent::setCurrentTabIndex (const int newTabIndex)
  47032. {
  47033. tabs->setCurrentTabIndex (newTabIndex);
  47034. }
  47035. int TabbedComponent::getCurrentTabIndex() const
  47036. {
  47037. return tabs->getCurrentTabIndex();
  47038. }
  47039. const String& TabbedComponent::getCurrentTabName() const
  47040. {
  47041. return tabs->getCurrentTabName();
  47042. }
  47043. void TabbedComponent::setOutline (const Colour& colour, int thickness)
  47044. {
  47045. outlineColour = colour;
  47046. outlineThickness = thickness;
  47047. repaint();
  47048. }
  47049. void TabbedComponent::setIndent (const int indentThickness)
  47050. {
  47051. edgeIndent = indentThickness;
  47052. }
  47053. void TabbedComponent::paint (Graphics& g)
  47054. {
  47055. const TabbedButtonBar::Orientation o = getOrientation();
  47056. int x = 0;
  47057. int y = 0;
  47058. int r = getWidth();
  47059. int b = getHeight();
  47060. if (o == TabbedButtonBar::TabsAtTop)
  47061. y += tabDepth;
  47062. else if (o == TabbedButtonBar::TabsAtBottom)
  47063. b -= tabDepth;
  47064. else if (o == TabbedButtonBar::TabsAtLeft)
  47065. x += tabDepth;
  47066. else if (o == TabbedButtonBar::TabsAtRight)
  47067. r -= tabDepth;
  47068. g.reduceClipRegion (x, y, r - x, b - y);
  47069. g.fillAll (tabs->getTabBackgroundColour (getCurrentTabIndex()));
  47070. if (outlineThickness > 0)
  47071. {
  47072. if (o == TabbedButtonBar::TabsAtTop)
  47073. --y;
  47074. else if (o == TabbedButtonBar::TabsAtBottom)
  47075. ++b;
  47076. else if (o == TabbedButtonBar::TabsAtLeft)
  47077. --x;
  47078. else if (o == TabbedButtonBar::TabsAtRight)
  47079. ++r;
  47080. g.setColour (outlineColour);
  47081. g.drawRect (x, y, r - x, b - y, outlineThickness);
  47082. }
  47083. }
  47084. void TabbedComponent::resized()
  47085. {
  47086. const TabbedButtonBar::Orientation o = getOrientation();
  47087. const int indent = edgeIndent + outlineThickness;
  47088. BorderSize indents (indent);
  47089. if (o == TabbedButtonBar::TabsAtTop)
  47090. {
  47091. tabs->setBounds (0, 0, getWidth(), tabDepth);
  47092. indents.setTop (tabDepth + edgeIndent);
  47093. }
  47094. else if (o == TabbedButtonBar::TabsAtBottom)
  47095. {
  47096. tabs->setBounds (0, getHeight() - tabDepth, getWidth(), tabDepth);
  47097. indents.setBottom (tabDepth + edgeIndent);
  47098. }
  47099. else if (o == TabbedButtonBar::TabsAtLeft)
  47100. {
  47101. tabs->setBounds (0, 0, tabDepth, getHeight());
  47102. indents.setLeft (tabDepth + edgeIndent);
  47103. }
  47104. else if (o == TabbedButtonBar::TabsAtRight)
  47105. {
  47106. tabs->setBounds (getWidth() - tabDepth, 0, tabDepth, getHeight());
  47107. indents.setRight (tabDepth + edgeIndent);
  47108. }
  47109. const Rectangle bounds (indents.subtractedFrom (Rectangle (0, 0, getWidth(), getHeight())));
  47110. for (int i = contentComponents.size(); --i >= 0;)
  47111. if (contentComponents.getUnchecked (i) != 0)
  47112. contentComponents.getUnchecked (i)->setBounds (bounds);
  47113. }
  47114. void TabbedComponent::lookAndFeelChanged()
  47115. {
  47116. for (int i = contentComponents.size(); --i >= 0;)
  47117. if (contentComponents.getUnchecked (i) != 0)
  47118. contentComponents.getUnchecked (i)->lookAndFeelChanged();
  47119. }
  47120. void TabbedComponent::changeCallback (const int newCurrentTabIndex,
  47121. const String& newTabName)
  47122. {
  47123. if (panelComponent != 0)
  47124. {
  47125. panelComponent->setVisible (false);
  47126. removeChildComponent (panelComponent);
  47127. panelComponent = 0;
  47128. }
  47129. if (getCurrentTabIndex() >= 0)
  47130. {
  47131. panelComponent = contentComponents [getCurrentTabIndex()];
  47132. if (panelComponent != 0)
  47133. {
  47134. // do these ops as two stages instead of addAndMakeVisible() so that the
  47135. // component has always got a parent when it gets the visibilityChanged() callback
  47136. addChildComponent (panelComponent);
  47137. panelComponent->setVisible (true);
  47138. panelComponent->toFront (true);
  47139. }
  47140. repaint();
  47141. }
  47142. resized();
  47143. currentTabChanged (newCurrentTabIndex, newTabName);
  47144. }
  47145. void TabbedComponent::currentTabChanged (const int, const String&)
  47146. {
  47147. }
  47148. void TabbedComponent::popupMenuClickOnTab (const int, const String&)
  47149. {
  47150. }
  47151. END_JUCE_NAMESPACE
  47152. /********* End of inlined file: juce_TabbedComponent.cpp *********/
  47153. /********* Start of inlined file: juce_Viewport.cpp *********/
  47154. BEGIN_JUCE_NAMESPACE
  47155. Viewport::Viewport (const String& componentName)
  47156. : Component (componentName),
  47157. contentComp (0),
  47158. lastVX (0),
  47159. lastVY (0),
  47160. lastVW (0),
  47161. lastVH (0),
  47162. scrollBarThickness (0),
  47163. singleStepX (16),
  47164. singleStepY (16),
  47165. showHScrollbar (true),
  47166. showVScrollbar (true)
  47167. {
  47168. // content holder is used to clip the contents so they don't overlap the scrollbars
  47169. addAndMakeVisible (contentHolder = new Component());
  47170. contentHolder->setInterceptsMouseClicks (false, true);
  47171. verticalScrollBar = new ScrollBar (true);
  47172. horizontalScrollBar = new ScrollBar (false);
  47173. addChildComponent (verticalScrollBar);
  47174. addChildComponent (horizontalScrollBar);
  47175. verticalScrollBar->addListener (this);
  47176. horizontalScrollBar->addListener (this);
  47177. setInterceptsMouseClicks (false, true);
  47178. setWantsKeyboardFocus (true);
  47179. }
  47180. Viewport::~Viewport()
  47181. {
  47182. contentHolder->deleteAllChildren();
  47183. deleteAllChildren();
  47184. }
  47185. void Viewport::visibleAreaChanged (int, int, int, int)
  47186. {
  47187. }
  47188. void Viewport::setViewedComponent (Component* const newViewedComponent)
  47189. {
  47190. if (contentComp != newViewedComponent)
  47191. {
  47192. if (contentComp->isValidComponent())
  47193. {
  47194. Component* const oldComp = contentComp;
  47195. contentComp = 0;
  47196. delete oldComp;
  47197. }
  47198. contentComp = newViewedComponent;
  47199. if (contentComp != 0)
  47200. {
  47201. contentComp->setTopLeftPosition (0, 0);
  47202. contentHolder->addAndMakeVisible (contentComp);
  47203. contentComp->addComponentListener (this);
  47204. }
  47205. updateVisibleRegion();
  47206. }
  47207. }
  47208. int Viewport::getMaximumVisibleWidth() const throw()
  47209. {
  47210. return jmax (0, getWidth() - (verticalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  47211. }
  47212. int Viewport::getMaximumVisibleHeight() const throw()
  47213. {
  47214. return jmax (0, getHeight() - (horizontalScrollBar->isVisible() ? getScrollBarThickness() : 0));
  47215. }
  47216. void Viewport::setViewPosition (const int xPixelsOffset,
  47217. const int yPixelsOffset)
  47218. {
  47219. if (contentComp != 0)
  47220. contentComp->setTopLeftPosition (-xPixelsOffset,
  47221. -yPixelsOffset);
  47222. }
  47223. void Viewport::setViewPositionProportionately (const double x,
  47224. const double y)
  47225. {
  47226. if (contentComp != 0)
  47227. setViewPosition (jmax (0, roundDoubleToInt (x * (contentComp->getWidth() - getWidth()))),
  47228. jmax (0, roundDoubleToInt (y * (contentComp->getHeight() - getHeight()))));
  47229. }
  47230. void Viewport::componentMovedOrResized (Component&, bool, bool)
  47231. {
  47232. updateVisibleRegion();
  47233. }
  47234. void Viewport::resized()
  47235. {
  47236. updateVisibleRegion();
  47237. }
  47238. void Viewport::updateVisibleRegion()
  47239. {
  47240. if (contentComp != 0)
  47241. {
  47242. const int newVX = -contentComp->getX();
  47243. const int newVY = -contentComp->getY();
  47244. if (newVX == 0 && newVY == 0
  47245. && contentComp->getWidth() <= getWidth()
  47246. && contentComp->getHeight() <= getHeight())
  47247. {
  47248. horizontalScrollBar->setVisible (false);
  47249. verticalScrollBar->setVisible (false);
  47250. }
  47251. if ((contentComp->getWidth() > 0) && showHScrollbar
  47252. && getHeight() > getScrollBarThickness())
  47253. {
  47254. horizontalScrollBar->setRangeLimits (0.0, contentComp->getWidth());
  47255. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  47256. horizontalScrollBar->setSingleStepSize (singleStepX);
  47257. }
  47258. else
  47259. {
  47260. horizontalScrollBar->setVisible (false);
  47261. }
  47262. if ((contentComp->getHeight() > 0) && showVScrollbar
  47263. && getWidth() > getScrollBarThickness())
  47264. {
  47265. verticalScrollBar->setRangeLimits (0.0, contentComp->getHeight());
  47266. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  47267. verticalScrollBar->setSingleStepSize (singleStepY);
  47268. }
  47269. else
  47270. {
  47271. verticalScrollBar->setVisible (false);
  47272. }
  47273. if (verticalScrollBar->isVisible())
  47274. {
  47275. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  47276. verticalScrollBar->setCurrentRange (newVY, getMaximumVisibleHeight());
  47277. verticalScrollBar
  47278. ->setBounds (getMaximumVisibleWidth(), 0,
  47279. getScrollBarThickness(), getMaximumVisibleHeight());
  47280. }
  47281. if (horizontalScrollBar->isVisible())
  47282. {
  47283. horizontalScrollBar->setCurrentRange (newVX, getMaximumVisibleWidth());
  47284. horizontalScrollBar
  47285. ->setBounds (0, getMaximumVisibleHeight(),
  47286. getMaximumVisibleWidth(), getScrollBarThickness());
  47287. }
  47288. contentHolder->setSize (getMaximumVisibleWidth(),
  47289. getMaximumVisibleHeight());
  47290. const int newVW = jmin (contentComp->getRight(), getMaximumVisibleWidth());
  47291. const int newVH = jmin (contentComp->getBottom(), getMaximumVisibleHeight());
  47292. if (newVX != lastVX
  47293. || newVY != lastVY
  47294. || newVW != lastVW
  47295. || newVH != lastVH)
  47296. {
  47297. lastVX = newVX;
  47298. lastVY = newVY;
  47299. lastVW = newVW;
  47300. lastVH = newVH;
  47301. visibleAreaChanged (newVX, newVY, newVW, newVH);
  47302. }
  47303. horizontalScrollBar->handleUpdateNowIfNeeded();
  47304. verticalScrollBar->handleUpdateNowIfNeeded();
  47305. }
  47306. else
  47307. {
  47308. horizontalScrollBar->setVisible (false);
  47309. verticalScrollBar->setVisible (false);
  47310. }
  47311. }
  47312. void Viewport::setSingleStepSizes (const int stepX,
  47313. const int stepY)
  47314. {
  47315. singleStepX = stepX;
  47316. singleStepY = stepY;
  47317. updateVisibleRegion();
  47318. }
  47319. void Viewport::setScrollBarsShown (const bool showVerticalScrollbarIfNeeded,
  47320. const bool showHorizontalScrollbarIfNeeded)
  47321. {
  47322. showVScrollbar = showVerticalScrollbarIfNeeded;
  47323. showHScrollbar = showHorizontalScrollbarIfNeeded;
  47324. updateVisibleRegion();
  47325. }
  47326. void Viewport::setScrollBarThickness (const int thickness)
  47327. {
  47328. scrollBarThickness = thickness;
  47329. updateVisibleRegion();
  47330. }
  47331. int Viewport::getScrollBarThickness() const throw()
  47332. {
  47333. return (scrollBarThickness > 0) ? scrollBarThickness
  47334. : getLookAndFeel().getDefaultScrollbarWidth();
  47335. }
  47336. void Viewport::setScrollBarButtonVisibility (const bool buttonsVisible)
  47337. {
  47338. verticalScrollBar->setButtonVisibility (buttonsVisible);
  47339. horizontalScrollBar->setButtonVisibility (buttonsVisible);
  47340. }
  47341. void Viewport::scrollBarMoved (ScrollBar* scrollBarThatHasMoved, const double newRangeStart)
  47342. {
  47343. if (scrollBarThatHasMoved == horizontalScrollBar)
  47344. {
  47345. setViewPosition (roundDoubleToInt (newRangeStart), getViewPositionY());
  47346. }
  47347. else if (scrollBarThatHasMoved == verticalScrollBar)
  47348. {
  47349. setViewPosition (getViewPositionX(), roundDoubleToInt (newRangeStart));
  47350. }
  47351. }
  47352. void Viewport::mouseWheelMove (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  47353. {
  47354. if (! useMouseWheelMoveIfNeeded (e, wheelIncrementX, wheelIncrementY))
  47355. Component::mouseWheelMove (e, wheelIncrementX, wheelIncrementY);
  47356. }
  47357. bool Viewport::useMouseWheelMoveIfNeeded (const MouseEvent& e, float wheelIncrementX, float wheelIncrementY)
  47358. {
  47359. if (! (e.mods.isAltDown() || e.mods.isCtrlDown()))
  47360. {
  47361. const bool hasVertBar = verticalScrollBar->isVisible();
  47362. const bool hasHorzBar = horizontalScrollBar->isVisible();
  47363. if (hasHorzBar && (wheelIncrementX != 0 || e.mods.isShiftDown() || ! hasVertBar))
  47364. {
  47365. horizontalScrollBar->mouseWheelMove (e.getEventRelativeTo (horizontalScrollBar),
  47366. wheelIncrementX, wheelIncrementY);
  47367. return true;
  47368. }
  47369. else if (hasVertBar && wheelIncrementY != 0)
  47370. {
  47371. verticalScrollBar->mouseWheelMove (e.getEventRelativeTo (verticalScrollBar),
  47372. wheelIncrementX, wheelIncrementY);
  47373. return true;
  47374. }
  47375. }
  47376. return false;
  47377. }
  47378. bool Viewport::keyPressed (const KeyPress& key)
  47379. {
  47380. const bool isUpDownKey = key.isKeyCode (KeyPress::upKey)
  47381. || key.isKeyCode (KeyPress::downKey)
  47382. || key.isKeyCode (KeyPress::pageUpKey)
  47383. || key.isKeyCode (KeyPress::pageDownKey)
  47384. || key.isKeyCode (KeyPress::homeKey)
  47385. || key.isKeyCode (KeyPress::endKey);
  47386. if (verticalScrollBar->isVisible() && isUpDownKey)
  47387. return verticalScrollBar->keyPressed (key);
  47388. const bool isLeftRightKey = key.isKeyCode (KeyPress::leftKey)
  47389. || key.isKeyCode (KeyPress::rightKey);
  47390. if (horizontalScrollBar->isVisible() && (isUpDownKey || isLeftRightKey))
  47391. return horizontalScrollBar->keyPressed (key);
  47392. return false;
  47393. }
  47394. END_JUCE_NAMESPACE
  47395. /********* End of inlined file: juce_Viewport.cpp *********/
  47396. /********* Start of inlined file: juce_LookAndFeel.cpp *********/
  47397. BEGIN_JUCE_NAMESPACE
  47398. static const Colour createBaseColour (const Colour& buttonColour,
  47399. const bool hasKeyboardFocus,
  47400. const bool isMouseOverButton,
  47401. const bool isButtonDown) throw()
  47402. {
  47403. const float sat = hasKeyboardFocus ? 1.3f : 0.9f;
  47404. const Colour baseColour (buttonColour.withMultipliedSaturation (sat));
  47405. if (isButtonDown)
  47406. return baseColour.contrasting (0.2f);
  47407. else if (isMouseOverButton)
  47408. return baseColour.contrasting (0.1f);
  47409. return baseColour;
  47410. }
  47411. LookAndFeel::LookAndFeel()
  47412. {
  47413. /* if this fails it means you're trying to create a LookAndFeel object before
  47414. the static Colours have been initialised. That ain't gonna work. It probably
  47415. means that you're using a static LookAndFeel object and that your compiler has
  47416. decided to intialise it before the Colours class.
  47417. */
  47418. jassert (Colours::white == Colour (0xffffffff));
  47419. // set up the standard set of colours..
  47420. #define textButtonColour 0xffbbbbff
  47421. #define textHighlightColour 0x401111ee
  47422. #define standardOutlineColour 0xb2808080
  47423. static const int standardColours[] =
  47424. {
  47425. TextButton::buttonColourId, textButtonColour,
  47426. TextButton::buttonOnColourId, 0xff4444ff,
  47427. TextButton::textColourId, 0xff000000,
  47428. ComboBox::buttonColourId, 0xffbbbbff,
  47429. ComboBox::outlineColourId, standardOutlineColour,
  47430. ToggleButton::textColourId, 0xff000000,
  47431. TextEditor::backgroundColourId, 0xffffffff,
  47432. TextEditor::textColourId, 0xff000000,
  47433. TextEditor::highlightColourId, textHighlightColour,
  47434. TextEditor::highlightedTextColourId, 0xff000000,
  47435. TextEditor::caretColourId, 0xff000000,
  47436. TextEditor::outlineColourId, 0x00000000,
  47437. TextEditor::focusedOutlineColourId, textButtonColour,
  47438. TextEditor::shadowColourId, 0x38000000,
  47439. Label::backgroundColourId, 0x00000000,
  47440. Label::textColourId, 0xff000000,
  47441. Label::outlineColourId, 0x00000000,
  47442. ScrollBar::backgroundColourId, 0x00000000,
  47443. ScrollBar::thumbColourId, 0xffffffff,
  47444. ScrollBar::trackColourId, 0xffffffff,
  47445. TreeView::linesColourId, 0x4c000000,
  47446. TreeView::backgroundColourId, 0x00000000,
  47447. PopupMenu::backgroundColourId, 0xffffffff,
  47448. PopupMenu::textColourId, 0xff000000,
  47449. PopupMenu::headerTextColourId, 0xff000000,
  47450. PopupMenu::highlightedTextColourId, 0xffffffff,
  47451. PopupMenu::highlightedBackgroundColourId, 0x991111aa,
  47452. ComboBox::textColourId, 0xff000000,
  47453. ComboBox::backgroundColourId, 0xffffffff,
  47454. ComboBox::arrowColourId, 0x99000000,
  47455. ListBox::backgroundColourId, 0xffffffff,
  47456. ListBox::outlineColourId, standardOutlineColour,
  47457. ListBox::textColourId, 0xff000000,
  47458. Slider::backgroundColourId, 0x00000000,
  47459. Slider::thumbColourId, textButtonColour,
  47460. Slider::trackColourId, 0x7fffffff,
  47461. Slider::rotarySliderFillColourId, 0x7f0000ff,
  47462. Slider::rotarySliderOutlineColourId, 0x66000000,
  47463. Slider::textBoxTextColourId, 0xff000000,
  47464. Slider::textBoxBackgroundColourId, 0xffffffff,
  47465. Slider::textBoxHighlightColourId, textHighlightColour,
  47466. Slider::textBoxOutlineColourId, standardOutlineColour,
  47467. AlertWindow::backgroundColourId, 0xffededed,
  47468. AlertWindow::textColourId, 0xff000000,
  47469. AlertWindow::outlineColourId, 0xff666666,
  47470. ProgressBar::backgroundColourId, 0xffeeeeee,
  47471. ProgressBar::foregroundColourId, 0xffaaaaee,
  47472. TooltipWindow::backgroundColourId, 0xffeeeebb,
  47473. TooltipWindow::textColourId, 0xff000000,
  47474. TooltipWindow::outlineColourId, 0x4c000000,
  47475. Toolbar::backgroundColourId, 0xfff6f8f9,
  47476. Toolbar::separatorColourId, 0x4c000000,
  47477. Toolbar::buttonMouseOverBackgroundColourId, 0x4c0000ff,
  47478. Toolbar::buttonMouseDownBackgroundColourId, 0x800000ff,
  47479. Toolbar::labelTextColourId, 0xff000000,
  47480. Toolbar::editingModeOutlineColourId, 0xffff0000,
  47481. HyperlinkButton::textColourId, 0xcc1111ee,
  47482. GroupComponent::outlineColourId, 0x66000000,
  47483. GroupComponent::textColourId, 0xff000000,
  47484. DirectoryContentsDisplayComponent::highlightColourId, textHighlightColour,
  47485. DirectoryContentsDisplayComponent::textColourId, 0xff000000,
  47486. 0x1000440, /*LassoComponent::lassoFillColourId*/ 0x66dddddd,
  47487. 0x1000441, /*LassoComponent::lassoOutlineColourId*/ 0x99111111,
  47488. MidiKeyboardComponent::whiteNoteColourId, 0xffffffff,
  47489. MidiKeyboardComponent::blackNoteColourId, 0xff000000,
  47490. MidiKeyboardComponent::keySeparatorLineColourId, 0x66000000,
  47491. MidiKeyboardComponent::mouseOverKeyOverlayColourId, 0x80ffff00,
  47492. MidiKeyboardComponent::keyDownOverlayColourId, 0xffb6b600,
  47493. MidiKeyboardComponent::textLabelColourId, 0xff000000,
  47494. MidiKeyboardComponent::upDownButtonBackgroundColourId, 0xffd3d3d3,
  47495. MidiKeyboardComponent::upDownButtonArrowColourId, 0xff000000,
  47496. ColourSelector::backgroundColourId, 0xffe5e5e5,
  47497. ColourSelector::labelTextColourId, 0xff000000,
  47498. FileSearchPathListComponent::backgroundColourId, 0xffffffff,
  47499. };
  47500. for (int i = 0; i < numElementsInArray (standardColours); i += 2)
  47501. setColour (standardColours [i], Colour (standardColours [i + 1]));
  47502. }
  47503. LookAndFeel::~LookAndFeel()
  47504. {
  47505. }
  47506. const Colour LookAndFeel::findColour (const int colourId) const throw()
  47507. {
  47508. const int index = colourIds.indexOf (colourId);
  47509. if (index >= 0)
  47510. return colours [index];
  47511. jassertfalse
  47512. return Colours::black;
  47513. }
  47514. void LookAndFeel::setColour (const int colourId, const Colour& colour) throw()
  47515. {
  47516. const int index = colourIds.indexOf (colourId);
  47517. if (index >= 0)
  47518. colours.set (index, colour);
  47519. colourIds.add (colourId);
  47520. colours.add (colour);
  47521. }
  47522. static LookAndFeel* defaultLF = 0;
  47523. static LookAndFeel* currentDefaultLF = 0;
  47524. LookAndFeel& LookAndFeel::getDefaultLookAndFeel() throw()
  47525. {
  47526. // if this happens, your app hasn't initialised itself properly.. if you're
  47527. // trying to hack your own main() function, have a look at
  47528. // JUCEApplication::initialiseForGUI()
  47529. jassert (currentDefaultLF != 0);
  47530. return *currentDefaultLF;
  47531. }
  47532. void LookAndFeel::setDefaultLookAndFeel (LookAndFeel* newDefaultLookAndFeel) throw()
  47533. {
  47534. if (newDefaultLookAndFeel == 0)
  47535. {
  47536. if (defaultLF == 0)
  47537. defaultLF = new LookAndFeel();
  47538. newDefaultLookAndFeel = defaultLF;
  47539. }
  47540. currentDefaultLF = newDefaultLookAndFeel;
  47541. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  47542. {
  47543. Component* const c = Desktop::getInstance().getComponent (i);
  47544. if (c != 0)
  47545. c->sendLookAndFeelChange();
  47546. }
  47547. }
  47548. void LookAndFeel::clearDefaultLookAndFeel() throw()
  47549. {
  47550. if (currentDefaultLF == defaultLF)
  47551. currentDefaultLF = 0;
  47552. deleteAndZero (defaultLF);
  47553. }
  47554. void LookAndFeel::drawButtonBackground (Graphics& g,
  47555. Button& button,
  47556. const Colour& backgroundColour,
  47557. bool isMouseOverButton,
  47558. bool isButtonDown)
  47559. {
  47560. const int width = button.getWidth();
  47561. const int height = button.getHeight();
  47562. const float outlineThickness = button.isEnabled() ? ((isButtonDown || isMouseOverButton) ? 1.2f : 0.7f) : 0.4f;
  47563. const float halfThickness = outlineThickness * 0.5f;
  47564. const float indentL = button.isConnectedOnLeft() ? 0.1f : halfThickness;
  47565. const float indentR = button.isConnectedOnRight() ? 0.1f : halfThickness;
  47566. const float indentT = button.isConnectedOnTop() ? 0.1f : halfThickness;
  47567. const float indentB = button.isConnectedOnBottom() ? 0.1f : halfThickness;
  47568. const Colour baseColour (createBaseColour (backgroundColour,
  47569. button.hasKeyboardFocus (true),
  47570. isMouseOverButton, isButtonDown)
  47571. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  47572. drawGlassLozenge (g,
  47573. indentL,
  47574. indentT,
  47575. width - indentL - indentR,
  47576. height - indentT - indentB,
  47577. baseColour, outlineThickness, -1.0f,
  47578. button.isConnectedOnLeft(),
  47579. button.isConnectedOnRight(),
  47580. button.isConnectedOnTop(),
  47581. button.isConnectedOnBottom());
  47582. }
  47583. void LookAndFeel::drawButtonText (Graphics& g, TextButton& button,
  47584. bool /*isMouseOverButton*/, bool /*isButtonDown*/)
  47585. {
  47586. g.setFont (button.getFont());
  47587. g.setColour (button.findColour (TextButton::textColourId)
  47588. .withMultipliedAlpha (button.isEnabled() ? 1.0f : 0.5f));
  47589. const int yIndent = jmin (4, button.proportionOfHeight (0.3f));
  47590. const int cornerSize = jmin (button.getHeight(), button.getWidth()) / 2;
  47591. const int fontHeight = roundFloatToInt (g.getCurrentFont().getHeight() * 0.6f);
  47592. const int leftIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnLeft() ? 4 : 2));
  47593. const int rightIndent = jmin (fontHeight, 2 + cornerSize / (button.isConnectedOnRight() ? 4 : 2));
  47594. g.drawFittedText (button.getButtonText(),
  47595. leftIndent,
  47596. yIndent,
  47597. button.getWidth() - leftIndent - rightIndent,
  47598. button.getHeight() - yIndent * 2,
  47599. Justification::centred, 2);
  47600. }
  47601. void LookAndFeel::drawTickBox (Graphics& g,
  47602. Component& component,
  47603. int x, int y, int w, int h,
  47604. const bool ticked,
  47605. const bool isEnabled,
  47606. const bool isMouseOverButton,
  47607. const bool isButtonDown)
  47608. {
  47609. const float boxSize = w * 0.7f;
  47610. drawGlassSphere (g, (float) x, y + (h - boxSize) * 0.5f, boxSize,
  47611. createBaseColour (component.findColour (TextButton::buttonColourId)
  47612. .withMultipliedAlpha (isEnabled ? 1.0f : 0.5f),
  47613. true,
  47614. isMouseOverButton,
  47615. isButtonDown),
  47616. isEnabled ? ((isButtonDown || isMouseOverButton) ? 1.1f : 0.5f) : 0.3f);
  47617. if (ticked)
  47618. {
  47619. Path tick;
  47620. tick.startNewSubPath (1.5f, 3.0f);
  47621. tick.lineTo (3.0f, 6.0f);
  47622. tick.lineTo (6.0f, 0.0f);
  47623. g.setColour (isEnabled ? Colours::black : Colours::grey);
  47624. const AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  47625. .translated ((float) x, (float) y));
  47626. g.strokePath (tick, PathStrokeType (2.5f), trans);
  47627. }
  47628. }
  47629. void LookAndFeel::drawToggleButton (Graphics& g,
  47630. ToggleButton& button,
  47631. bool isMouseOverButton,
  47632. bool isButtonDown)
  47633. {
  47634. if (button.hasKeyboardFocus (true))
  47635. {
  47636. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  47637. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  47638. }
  47639. const int tickWidth = jmin (20, button.getHeight() - 4);
  47640. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  47641. tickWidth, tickWidth,
  47642. button.getToggleState(),
  47643. button.isEnabled(),
  47644. isMouseOverButton,
  47645. isButtonDown);
  47646. g.setColour (button.findColour (ToggleButton::textColourId));
  47647. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  47648. if (! button.isEnabled())
  47649. g.setOpacity (0.5f);
  47650. const int textX = tickWidth + 5;
  47651. g.drawFittedText (button.getButtonText(),
  47652. textX, 4,
  47653. button.getWidth() - textX - 2, button.getHeight() - 8,
  47654. Justification::centredLeft, 10);
  47655. }
  47656. void LookAndFeel::changeToggleButtonWidthToFitText (ToggleButton& button)
  47657. {
  47658. Font font (jmin (15.0f, button.getHeight() * 0.6f));
  47659. const int tickWidth = jmin (24, button.getHeight());
  47660. button.setSize (font.getStringWidth (button.getButtonText()) + tickWidth + 8,
  47661. button.getHeight());
  47662. }
  47663. void LookAndFeel::drawAlertBox (Graphics& g,
  47664. AlertWindow& alert,
  47665. const Rectangle& textArea,
  47666. TextLayout& textLayout)
  47667. {
  47668. const int iconWidth = 80;
  47669. const Colour background (alert.findColour (AlertWindow::backgroundColourId));
  47670. g.fillAll (background);
  47671. int iconSpaceUsed = 0;
  47672. Justification alignment (Justification::horizontallyCentred);
  47673. int iconSize = jmin (iconWidth + 50, alert.getHeight() + 20);
  47674. if (alert.containsAnyExtraComponents() || alert.getNumButtons() > 2)
  47675. iconSize = jmin (iconSize, textArea.getHeight() + 50);
  47676. const Rectangle iconRect (iconSize / -10,
  47677. iconSize / -10,
  47678. iconSize,
  47679. iconSize);
  47680. if (alert.getAlertType() == AlertWindow::QuestionIcon
  47681. || alert.getAlertType() == AlertWindow::InfoIcon)
  47682. {
  47683. if (alert.getAlertType() == AlertWindow::InfoIcon)
  47684. g.setColour (background.overlaidWith (Colour (0x280000ff)));
  47685. else
  47686. g.setColour (background.overlaidWith (Colours::gold.darker().withAlpha (0.25f)));
  47687. g.fillEllipse ((float) iconRect.getX(),
  47688. (float) iconRect.getY(),
  47689. (float) iconRect.getWidth(),
  47690. (float) iconRect.getHeight());
  47691. g.setColour (background);
  47692. g.setFont (iconRect.getHeight() * 0.9f, Font::bold);
  47693. g.drawText ((alert.getAlertType() == AlertWindow::InfoIcon) ? "i"
  47694. : "?",
  47695. iconRect.getX(),
  47696. iconRect.getY(),
  47697. iconRect.getWidth(),
  47698. iconRect.getHeight(),
  47699. Justification::centred, false);
  47700. iconSpaceUsed = iconWidth;
  47701. alignment = Justification::left;
  47702. }
  47703. else if (alert.getAlertType() == AlertWindow::WarningIcon)
  47704. {
  47705. Path p;
  47706. p.addTriangle (iconRect.getX() + iconRect.getWidth() * 0.5f,
  47707. (float) iconRect.getY(),
  47708. (float) iconRect.getRight(),
  47709. (float) iconRect.getBottom(),
  47710. (float) iconRect.getX(),
  47711. (float) iconRect.getBottom());
  47712. g.setColour (background.overlaidWith (Colour (0x33ff0000)));
  47713. g.fillPath (p.createPathWithRoundedCorners (5.0f));
  47714. g.setColour (background);
  47715. g.setFont (iconRect.getHeight() * 0.9f, Font::bold);
  47716. g.drawText (T("!"),
  47717. iconRect.getX(),
  47718. iconRect.getY(),
  47719. iconRect.getWidth(),
  47720. iconRect.getHeight() + iconRect.getHeight() / 8,
  47721. Justification::centred, false);
  47722. iconSpaceUsed = iconWidth;
  47723. alignment = Justification::left;
  47724. }
  47725. g.setColour (alert.findColour (AlertWindow::textColourId));
  47726. textLayout.drawWithin (g,
  47727. textArea.getX() + iconSpaceUsed,
  47728. textArea.getY(),
  47729. textArea.getWidth() - iconSpaceUsed,
  47730. textArea.getHeight(),
  47731. alignment.getFlags() | Justification::top);
  47732. g.setColour (alert.findColour (AlertWindow::outlineColourId));
  47733. g.drawRect (0, 0, alert.getWidth(), alert.getHeight());
  47734. }
  47735. int LookAndFeel::getAlertBoxWindowFlags()
  47736. {
  47737. return ComponentPeer::windowAppearsOnTaskbar
  47738. | ComponentPeer::windowHasDropShadow;
  47739. }
  47740. int LookAndFeel::getAlertWindowButtonHeight()
  47741. {
  47742. return 28;
  47743. }
  47744. const Font LookAndFeel::getAlertWindowFont()
  47745. {
  47746. return Font (12.0f);
  47747. }
  47748. void LookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  47749. int width, int height,
  47750. double progress, const String& textToShow)
  47751. {
  47752. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  47753. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  47754. g.fillAll (background);
  47755. if (progress >= 0.0f && progress < 1.0f)
  47756. {
  47757. drawGlassLozenge (g, 1.0f, 1.0f,
  47758. (float) jlimit (0.0, width - 2.0, progress * (width - 2.0)),
  47759. (float) (height - 2),
  47760. foreground,
  47761. 0.5f, 0.0f,
  47762. true, true, true, true);
  47763. }
  47764. else
  47765. {
  47766. // spinning bar..
  47767. g.setColour (foreground);
  47768. const int stripeWidth = height * 2;
  47769. const int position = (Time::getMillisecondCounter() / 15) % stripeWidth;
  47770. Path p;
  47771. for (float x = (float) (-stripeWidth - position); x < width + stripeWidth; x += stripeWidth)
  47772. p.addQuadrilateral (x, 0.0f,
  47773. x + stripeWidth * 0.5f, 0.0f,
  47774. x, (float) height,
  47775. x - stripeWidth * 0.5f, (float) height);
  47776. Image im (Image::ARGB, width, height, true);
  47777. {
  47778. Graphics g (im);
  47779. drawGlassLozenge (g, 1.0f, 1.0f,
  47780. (float) (width - 2),
  47781. (float) (height - 2),
  47782. foreground,
  47783. 0.5f, 0.0f,
  47784. true, true, true, true);
  47785. }
  47786. ImageBrush ib (&im, 0, 0, 0.85f);
  47787. g.setBrush (&ib);
  47788. g.fillPath (p);
  47789. }
  47790. if (textToShow.isNotEmpty())
  47791. {
  47792. g.setColour (Colour::contrasting (background, foreground));
  47793. g.setFont (height * 0.6f);
  47794. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  47795. }
  47796. }
  47797. void LookAndFeel::drawScrollbarButton (Graphics& g,
  47798. ScrollBar& scrollbar,
  47799. int width, int height,
  47800. int buttonDirection,
  47801. bool /*isScrollbarVertical*/,
  47802. bool /*isMouseOverButton*/,
  47803. bool isButtonDown)
  47804. {
  47805. Path p;
  47806. if (buttonDirection == 0)
  47807. p.addTriangle (width * 0.5f, height * 0.2f,
  47808. width * 0.1f, height * 0.7f,
  47809. width * 0.9f, height * 0.7f);
  47810. else if (buttonDirection == 1)
  47811. p.addTriangle (width * 0.8f, height * 0.5f,
  47812. width * 0.3f, height * 0.1f,
  47813. width * 0.3f, height * 0.9f);
  47814. else if (buttonDirection == 2)
  47815. p.addTriangle (width * 0.5f, height * 0.8f,
  47816. width * 0.1f, height * 0.3f,
  47817. width * 0.9f, height * 0.3f);
  47818. else if (buttonDirection == 3)
  47819. p.addTriangle (width * 0.2f, height * 0.5f,
  47820. width * 0.7f, height * 0.1f,
  47821. width * 0.7f, height * 0.9f);
  47822. if (isButtonDown)
  47823. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId).contrasting (0.2f));
  47824. else
  47825. g.setColour (scrollbar.findColour (ScrollBar::thumbColourId));
  47826. g.fillPath (p);
  47827. g.setColour (Colour (0x80000000));
  47828. g.strokePath (p, PathStrokeType (0.5f));
  47829. }
  47830. void LookAndFeel::drawScrollbar (Graphics& g,
  47831. ScrollBar& scrollbar,
  47832. int x, int y,
  47833. int width, int height,
  47834. bool isScrollbarVertical,
  47835. int thumbStartPosition,
  47836. int thumbSize,
  47837. bool /*isMouseOver*/,
  47838. bool /*isMouseDown*/)
  47839. {
  47840. g.fillAll (scrollbar.findColour (ScrollBar::backgroundColourId));
  47841. Path slotPath, thumbPath;
  47842. const float slotIndent = jmin (width, height) > 15 ? 1.0f : 0.0f;
  47843. const float slotIndentx2 = slotIndent * 2.0f;
  47844. const float thumbIndent = slotIndent + 1.0f;
  47845. const float thumbIndentx2 = thumbIndent * 2.0f;
  47846. float gx1 = 0.0f, gy1 = 0.0f, gx2 = 0.0f, gy2 = 0.0f;
  47847. if (isScrollbarVertical)
  47848. {
  47849. slotPath.addRoundedRectangle (x + slotIndent,
  47850. y + slotIndent,
  47851. width - slotIndentx2,
  47852. height - slotIndentx2,
  47853. (width - slotIndentx2) * 0.5f);
  47854. if (thumbSize > 0)
  47855. thumbPath.addRoundedRectangle (x + thumbIndent,
  47856. thumbStartPosition + thumbIndent,
  47857. width - thumbIndentx2,
  47858. thumbSize - thumbIndentx2,
  47859. (width - thumbIndentx2) * 0.5f);
  47860. gx1 = (float) x;
  47861. gx2 = x + width * 0.7f;
  47862. }
  47863. else
  47864. {
  47865. slotPath.addRoundedRectangle (x + slotIndent,
  47866. y + slotIndent,
  47867. width - slotIndentx2,
  47868. height - slotIndentx2,
  47869. (height - slotIndentx2) * 0.5f);
  47870. if (thumbSize > 0)
  47871. thumbPath.addRoundedRectangle (thumbStartPosition + thumbIndent,
  47872. y + thumbIndent,
  47873. thumbSize - thumbIndentx2,
  47874. height - thumbIndentx2,
  47875. (height - thumbIndentx2) * 0.5f);
  47876. gy1 = (float) y;
  47877. gy2 = y + height * 0.7f;
  47878. }
  47879. const Colour thumbColour (scrollbar.findColour (ScrollBar::trackColourId));
  47880. GradientBrush gb (thumbColour.overlaidWith (Colour (0x44000000)),
  47881. gx1, gy1,
  47882. thumbColour.overlaidWith (Colour (0x19000000)),
  47883. gx2, gy2, false);
  47884. g.setBrush (&gb);
  47885. g.fillPath (slotPath);
  47886. if (isScrollbarVertical)
  47887. {
  47888. gx1 = x + width * 0.6f;
  47889. gx2 = (float) x + width;
  47890. }
  47891. else
  47892. {
  47893. gy1 = y + height * 0.6f;
  47894. gy2 = (float) y + height;
  47895. }
  47896. GradientBrush gb2 (Colours::transparentBlack,
  47897. gx1, gy1,
  47898. Colour (0x19000000),
  47899. gx2, gy2, false);
  47900. g.setBrush (&gb2);
  47901. g.fillPath (slotPath);
  47902. g.setColour (thumbColour);
  47903. g.fillPath (thumbPath);
  47904. GradientBrush gb3 (Colour (0x10000000),
  47905. gx1, gy1,
  47906. Colours::transparentBlack,
  47907. gx2, gy2, false);
  47908. g.saveState();
  47909. g.setBrush (&gb3);
  47910. if (isScrollbarVertical)
  47911. g.reduceClipRegion (x + width / 2, y, width, height);
  47912. else
  47913. g.reduceClipRegion (x, y + height / 2, width, height);
  47914. g.fillPath (thumbPath);
  47915. g.restoreState();
  47916. g.setColour (Colour (0x4c000000));
  47917. g.strokePath (thumbPath, PathStrokeType (0.4f));
  47918. }
  47919. ImageEffectFilter* LookAndFeel::getScrollbarEffect()
  47920. {
  47921. return 0;
  47922. }
  47923. int LookAndFeel::getMinimumScrollbarThumbSize (ScrollBar& scrollbar)
  47924. {
  47925. return jmin (scrollbar.getWidth(), scrollbar.getHeight()) * 2;
  47926. }
  47927. int LookAndFeel::getDefaultScrollbarWidth()
  47928. {
  47929. return 18;
  47930. }
  47931. int LookAndFeel::getScrollbarButtonSize (ScrollBar& scrollbar)
  47932. {
  47933. return 2 + (scrollbar.isVertical() ? scrollbar.getWidth()
  47934. : scrollbar.getHeight());
  47935. }
  47936. const Path LookAndFeel::getTickShape (const float height)
  47937. {
  47938. static const unsigned char tickShapeData[] =
  47939. {
  47940. 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,
  47941. 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,
  47942. 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,
  47943. 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,
  47944. 96,140,68,0,128,188,67,0,224,168,68,0,0,119,67,99,101
  47945. };
  47946. Path p;
  47947. p.loadPathFromData (tickShapeData, sizeof (tickShapeData));
  47948. p.scaleToFit (0, 0, height * 2.0f, height, true);
  47949. return p;
  47950. }
  47951. const Path LookAndFeel::getCrossShape (const float height)
  47952. {
  47953. static const unsigned char crossShapeData[] =
  47954. {
  47955. 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,
  47956. 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,
  47957. 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,
  47958. 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,
  47959. 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,
  47960. 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,
  47961. 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
  47962. };
  47963. Path p;
  47964. p.loadPathFromData (crossShapeData, sizeof (crossShapeData));
  47965. p.scaleToFit (0, 0, height * 2.0f, height, true);
  47966. return p;
  47967. }
  47968. void LookAndFeel::drawTreeviewPlusMinusBox (Graphics& g, int x, int y, int w, int h, bool isPlus)
  47969. {
  47970. const int boxSize = ((jmin (16, w, h) << 1) / 3) | 1;
  47971. x += (w - boxSize) >> 1;
  47972. y += (h - boxSize) >> 1;
  47973. w = boxSize;
  47974. h = boxSize;
  47975. g.setColour (Colour (0xe5ffffff));
  47976. g.fillRect (x, y, w, h);
  47977. g.setColour (Colour (0x80000000));
  47978. g.drawRect (x, y, w, h);
  47979. const float size = boxSize / 2 + 1.0f;
  47980. const float centre = (float) (boxSize / 2);
  47981. g.fillRect (x + (w - size) * 0.5f, y + centre, size, 1.0f);
  47982. if (isPlus)
  47983. g.fillRect (x + centre, y + (h - size) * 0.5f, 1.0f, size);
  47984. }
  47985. void LookAndFeel::drawBubble (Graphics& g,
  47986. float tipX, float tipY,
  47987. float boxX, float boxY,
  47988. float boxW, float boxH)
  47989. {
  47990. int side = 0;
  47991. if (tipX < boxX)
  47992. side = 1;
  47993. else if (tipX > boxX + boxW)
  47994. side = 3;
  47995. else if (tipY > boxY + boxH)
  47996. side = 2;
  47997. const float indent = 2.0f;
  47998. Path p;
  47999. p.addBubble (boxX + indent,
  48000. boxY + indent,
  48001. boxW - indent * 2.0f,
  48002. boxH - indent * 2.0f,
  48003. 5.0f,
  48004. tipX, tipY,
  48005. side,
  48006. 0.5f,
  48007. jmin (15.0f, boxW * 0.3f, boxH * 0.3f));
  48008. //xxx need to take comp as param for colour
  48009. g.setColour (findColour (TooltipWindow::backgroundColourId).withAlpha (0.9f));
  48010. g.fillPath (p);
  48011. //xxx as above
  48012. g.setColour (findColour (TooltipWindow::textColourId).withAlpha (0.4f));
  48013. g.strokePath (p, PathStrokeType (1.33f));
  48014. }
  48015. const Font LookAndFeel::getPopupMenuFont()
  48016. {
  48017. return Font (17.0f);
  48018. }
  48019. void LookAndFeel::getIdealPopupMenuItemSize (const String& text,
  48020. const bool isSeparator,
  48021. int standardMenuItemHeight,
  48022. int& idealWidth,
  48023. int& idealHeight)
  48024. {
  48025. if (isSeparator)
  48026. {
  48027. idealWidth = 50;
  48028. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight / 2 : 10;
  48029. }
  48030. else
  48031. {
  48032. Font font (getPopupMenuFont());
  48033. if (standardMenuItemHeight > 0 && font.getHeight() > standardMenuItemHeight / 1.3f)
  48034. font.setHeight (standardMenuItemHeight / 1.3f);
  48035. idealHeight = standardMenuItemHeight > 0 ? standardMenuItemHeight : roundFloatToInt (font.getHeight() * 1.3f);
  48036. idealWidth = font.getStringWidth (text) + idealHeight * 2;
  48037. }
  48038. }
  48039. void LookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  48040. {
  48041. const Colour background (findColour (PopupMenu::backgroundColourId));
  48042. g.fillAll (background);
  48043. g.setColour (background.overlaidWith (Colour (0x2badd8e6)));
  48044. for (int i = 0; i < height; i += 3)
  48045. g.fillRect (0, i, width, 1);
  48046. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.6f));
  48047. g.drawRect (0, 0, width, height);
  48048. }
  48049. void LookAndFeel::drawPopupMenuUpDownArrow (Graphics& g,
  48050. int width, int height,
  48051. bool isScrollUpArrow)
  48052. {
  48053. const Colour background (findColour (PopupMenu::backgroundColourId));
  48054. GradientBrush gb (background,
  48055. 0.0f, height * 0.5f,
  48056. background.withAlpha (0.0f),
  48057. 0.0f, isScrollUpArrow ? ((float) height) : 0.0f,
  48058. false);
  48059. g.setBrush (&gb);
  48060. g.fillRect (1, 1, width - 2, height - 2);
  48061. const float hw = width * 0.5f;
  48062. const float arrowW = height * 0.3f;
  48063. const float y1 = height * (isScrollUpArrow ? 0.6f : 0.3f);
  48064. const float y2 = height * (isScrollUpArrow ? 0.3f : 0.6f);
  48065. Path p;
  48066. p.addTriangle (hw - arrowW, y1,
  48067. hw + arrowW, y1,
  48068. hw, y2);
  48069. g.setColour (findColour (PopupMenu::textColourId).withAlpha (0.5f));
  48070. g.fillPath (p);
  48071. }
  48072. void LookAndFeel::drawPopupMenuItem (Graphics& g,
  48073. int width, int height,
  48074. const bool isSeparator,
  48075. const bool isActive,
  48076. const bool isHighlighted,
  48077. const bool isTicked,
  48078. const bool hasSubMenu,
  48079. const String& text,
  48080. const String& shortcutKeyText,
  48081. Image* image,
  48082. const Colour* const textColourToUse)
  48083. {
  48084. const float halfH = height * 0.5f;
  48085. if (isSeparator)
  48086. {
  48087. const float separatorIndent = 5.5f;
  48088. g.setColour (Colour (0x33000000));
  48089. g.drawLine (separatorIndent, halfH, width - separatorIndent, halfH);
  48090. g.setColour (Colour (0x66ffffff));
  48091. g.drawLine (separatorIndent, halfH + 1.0f, width - separatorIndent, halfH + 1.0f);
  48092. }
  48093. else
  48094. {
  48095. Colour textColour (findColour (PopupMenu::textColourId));
  48096. if (textColourToUse != 0)
  48097. textColour = *textColourToUse;
  48098. if (isHighlighted)
  48099. {
  48100. g.setColour (findColour (PopupMenu::highlightedBackgroundColourId));
  48101. g.fillRect (1, 1, width - 2, height - 2);
  48102. g.setColour (findColour (PopupMenu::highlightedTextColourId));
  48103. }
  48104. else
  48105. {
  48106. g.setColour (textColour);
  48107. }
  48108. if (! isActive)
  48109. g.setOpacity (0.3f);
  48110. Font font (getPopupMenuFont());
  48111. if (font.getHeight() > height / 1.3f)
  48112. font.setHeight (height / 1.3f);
  48113. g.setFont (font);
  48114. const int leftBorder = (height * 5) / 4;
  48115. const int rightBorder = 4;
  48116. if (image != 0)
  48117. {
  48118. g.drawImageWithin (image,
  48119. 2, 1, leftBorder - 4, height - 2,
  48120. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize, false);
  48121. }
  48122. else if (isTicked)
  48123. {
  48124. const Path tick (getTickShape (1.0f));
  48125. const float th = font.getAscent();
  48126. const float ty = halfH - th * 0.5f;
  48127. g.fillPath (tick, tick.getTransformToScaleToFit (2.0f, ty, (float) (leftBorder - 4),
  48128. th, true));
  48129. }
  48130. g.drawFittedText (text,
  48131. leftBorder, 0,
  48132. width - (leftBorder + rightBorder), height,
  48133. Justification::centredLeft, 1);
  48134. if (shortcutKeyText.isNotEmpty())
  48135. {
  48136. Font f2 (g.getCurrentFont());
  48137. f2.setHeight (f2.getHeight() * 0.75f);
  48138. f2.setHorizontalScale (0.95f);
  48139. g.setFont (f2);
  48140. g.drawText (shortcutKeyText,
  48141. leftBorder,
  48142. 0,
  48143. width - (leftBorder + rightBorder + 4),
  48144. height,
  48145. Justification::centredRight,
  48146. true);
  48147. }
  48148. if (hasSubMenu)
  48149. {
  48150. const float arrowH = 0.6f * getPopupMenuFont().getAscent();
  48151. const float x = width - height * 0.6f;
  48152. Path p;
  48153. p.addTriangle (x, halfH - arrowH * 0.5f,
  48154. x, halfH + arrowH * 0.5f,
  48155. x + arrowH * 0.6f, halfH);
  48156. g.fillPath (p);
  48157. }
  48158. }
  48159. }
  48160. int LookAndFeel::getMenuWindowFlags()
  48161. {
  48162. return ComponentPeer::windowHasDropShadow;
  48163. }
  48164. void LookAndFeel::drawMenuBarBackground (Graphics& g, int width, int height,
  48165. bool, MenuBarComponent& menuBar)
  48166. {
  48167. const Colour baseColour (createBaseColour (menuBar.findColour (PopupMenu::backgroundColourId), false, false, false));
  48168. if (menuBar.isEnabled())
  48169. {
  48170. drawShinyButtonShape (g,
  48171. -4.0f, 0.0f,
  48172. width + 8.0f, (float) height,
  48173. 0.0f,
  48174. baseColour,
  48175. 0.4f,
  48176. true, true, true, true);
  48177. }
  48178. else
  48179. {
  48180. g.fillAll (baseColour);
  48181. }
  48182. }
  48183. const Font LookAndFeel::getMenuBarFont (MenuBarComponent& menuBar, int /*itemIndex*/, const String& /*itemText*/)
  48184. {
  48185. return Font (menuBar.getHeight() * 0.7f);
  48186. }
  48187. int LookAndFeel::getMenuBarItemWidth (MenuBarComponent& menuBar, int itemIndex, const String& itemText)
  48188. {
  48189. return getMenuBarFont (menuBar, itemIndex, itemText)
  48190. .getStringWidth (itemText) + menuBar.getHeight();
  48191. }
  48192. void LookAndFeel::drawMenuBarItem (Graphics& g,
  48193. int width, int height,
  48194. int itemIndex,
  48195. const String& itemText,
  48196. bool isMouseOverItem,
  48197. bool isMenuOpen,
  48198. bool /*isMouseOverBar*/,
  48199. MenuBarComponent& menuBar)
  48200. {
  48201. if (! menuBar.isEnabled())
  48202. {
  48203. g.setColour (menuBar.findColour (PopupMenu::textColourId)
  48204. .withMultipliedAlpha (0.5f));
  48205. }
  48206. else if (isMenuOpen || isMouseOverItem)
  48207. {
  48208. g.fillAll (menuBar.findColour (PopupMenu::highlightedBackgroundColourId));
  48209. g.setColour (menuBar.findColour (PopupMenu::highlightedTextColourId));
  48210. }
  48211. else
  48212. {
  48213. g.setColour (menuBar.findColour (PopupMenu::textColourId));
  48214. }
  48215. g.setFont (getMenuBarFont (menuBar, itemIndex, itemText));
  48216. g.drawFittedText (itemText, 0, 0, width, height, Justification::centred, 1);
  48217. }
  48218. void LookAndFeel::fillTextEditorBackground (Graphics& g, int /*width*/, int /*height*/,
  48219. TextEditor& textEditor)
  48220. {
  48221. g.fillAll (textEditor.findColour (TextEditor::backgroundColourId));
  48222. }
  48223. void LookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  48224. {
  48225. if (textEditor.isEnabled())
  48226. {
  48227. if (textEditor.hasKeyboardFocus (true) && ! textEditor.isReadOnly())
  48228. {
  48229. const int border = 2;
  48230. g.setColour (textEditor.findColour (TextEditor::focusedOutlineColourId));
  48231. g.drawRect (0, 0, width, height, border);
  48232. g.setOpacity (1.0f);
  48233. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId).withMultipliedAlpha (0.75f));
  48234. g.drawBevel (0, 0, width, height + 2, border + 2, shadowColour, shadowColour);
  48235. }
  48236. else
  48237. {
  48238. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  48239. g.drawRect (0, 0, width, height);
  48240. g.setOpacity (1.0f);
  48241. const Colour shadowColour (textEditor.findColour (TextEditor::shadowColourId));
  48242. g.drawBevel (0, 0, width, height + 2, 3, shadowColour, shadowColour);
  48243. }
  48244. }
  48245. }
  48246. void LookAndFeel::drawComboBox (Graphics& g, int width, int height,
  48247. const bool isButtonDown,
  48248. int buttonX, int buttonY,
  48249. int buttonW, int buttonH,
  48250. ComboBox& box)
  48251. {
  48252. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  48253. if (box.isEnabled() && box.hasKeyboardFocus (false))
  48254. {
  48255. g.setColour (box.findColour (TextButton::buttonColourId));
  48256. g.drawRect (0, 0, width, height, 2);
  48257. }
  48258. else
  48259. {
  48260. g.setColour (box.findColour (ComboBox::outlineColourId));
  48261. g.drawRect (0, 0, width, height);
  48262. }
  48263. const float outlineThickness = box.isEnabled() ? (isButtonDown ? 1.2f : 0.5f) : 0.3f;
  48264. const Colour baseColour (createBaseColour (box.findColour (ComboBox::buttonColourId),
  48265. box.hasKeyboardFocus (true),
  48266. false, isButtonDown)
  48267. .withMultipliedAlpha (box.isEnabled() ? 1.0f : 0.5f));
  48268. drawGlassLozenge (g,
  48269. buttonX + outlineThickness, buttonY + outlineThickness,
  48270. buttonW - outlineThickness * 2.0f, buttonH - outlineThickness * 2.0f,
  48271. baseColour, outlineThickness, -1.0f,
  48272. true, true, true, true);
  48273. if (box.isEnabled())
  48274. {
  48275. const float arrowX = 0.3f;
  48276. const float arrowH = 0.2f;
  48277. Path p;
  48278. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  48279. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  48280. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  48281. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  48282. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  48283. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  48284. g.setColour (box.findColour (ComboBox::arrowColourId));
  48285. g.fillPath (p);
  48286. }
  48287. }
  48288. const Font LookAndFeel::getComboBoxFont (ComboBox& box)
  48289. {
  48290. return Font (jmin (15.0f, box.getHeight() * 0.85f));
  48291. }
  48292. Label* LookAndFeel::createComboBoxTextBox (ComboBox&)
  48293. {
  48294. return new Label (String::empty, String::empty);
  48295. }
  48296. void LookAndFeel::positionComboBoxText (ComboBox& box, Label& label)
  48297. {
  48298. label.setBounds (1, 1,
  48299. box.getWidth() + 3 - box.getHeight(),
  48300. box.getHeight() - 2);
  48301. label.setFont (getComboBoxFont (box));
  48302. }
  48303. void LookAndFeel::drawLabel (Graphics& g, Label& label)
  48304. {
  48305. g.fillAll (label.findColour (Label::backgroundColourId));
  48306. if (! label.isBeingEdited())
  48307. {
  48308. const float alpha = label.isEnabled() ? 1.0f : 0.5f;
  48309. g.setColour (label.findColour (Label::textColourId).withMultipliedAlpha (alpha));
  48310. g.setFont (label.getFont());
  48311. g.drawFittedText (label.getText(),
  48312. label.getHorizontalBorderSize(),
  48313. label.getVerticalBorderSize(),
  48314. label.getWidth() - 2 * label.getHorizontalBorderSize(),
  48315. label.getHeight() - 2 * label.getVerticalBorderSize(),
  48316. label.getJustificationType(),
  48317. jmax (1, (int) (label.getHeight() / label.getFont().getHeight())),
  48318. label.getMinimumHorizontalScale());
  48319. g.setColour (label.findColour (Label::outlineColourId).withMultipliedAlpha (alpha));
  48320. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  48321. }
  48322. else if (label.isEnabled())
  48323. {
  48324. g.setColour (label.findColour (Label::outlineColourId));
  48325. g.drawRect (0, 0, label.getWidth(), label.getHeight());
  48326. }
  48327. }
  48328. void LookAndFeel::drawLinearSliderBackground (Graphics& g,
  48329. int x, int y,
  48330. int width, int height,
  48331. float /*sliderPos*/,
  48332. float /*minSliderPos*/,
  48333. float /*maxSliderPos*/,
  48334. const Slider::SliderStyle /*style*/,
  48335. Slider& slider)
  48336. {
  48337. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  48338. const Colour trackColour (slider.findColour (Slider::trackColourId));
  48339. const Colour gradCol1 (trackColour.overlaidWith (Colours::black.withAlpha (slider.isEnabled() ? 0.25f : 0.13f)));
  48340. const Colour gradCol2 (trackColour.overlaidWith (Colour (0x14000000)));
  48341. Path indent;
  48342. if (slider.isHorizontal())
  48343. {
  48344. const float iy = y + height * 0.5f - sliderRadius * 0.5f;
  48345. const float ih = sliderRadius;
  48346. GradientBrush gb (gradCol1, 0.0f, iy,
  48347. gradCol2, 0.0f, iy + ih, false);
  48348. g.setBrush (&gb);
  48349. indent.addRoundedRectangle (x - sliderRadius * 0.5f, iy,
  48350. width + sliderRadius, ih,
  48351. 5.0f);
  48352. g.fillPath (indent);
  48353. }
  48354. else
  48355. {
  48356. const float ix = x + width * 0.5f - sliderRadius * 0.5f;
  48357. const float iw = sliderRadius;
  48358. GradientBrush gb (gradCol1, ix, 0.0f,
  48359. gradCol2, ix + iw, 0.0f, false);
  48360. g.setBrush (&gb);
  48361. indent.addRoundedRectangle (ix, y - sliderRadius * 0.5f,
  48362. iw, height + sliderRadius,
  48363. 5.0f);
  48364. g.fillPath (indent);
  48365. }
  48366. g.setColour (Colour (0x4c000000));
  48367. g.strokePath (indent, PathStrokeType (0.5f));
  48368. }
  48369. void LookAndFeel::drawLinearSliderThumb (Graphics& g,
  48370. int x, int y,
  48371. int width, int height,
  48372. float sliderPos,
  48373. float minSliderPos,
  48374. float maxSliderPos,
  48375. const Slider::SliderStyle style,
  48376. Slider& slider)
  48377. {
  48378. const float sliderRadius = (float) (getSliderThumbRadius (slider) - 2);
  48379. Colour knobColour (createBaseColour (slider.findColour (Slider::thumbColourId),
  48380. slider.hasKeyboardFocus (false) && slider.isEnabled(),
  48381. slider.isMouseOverOrDragging() && slider.isEnabled(),
  48382. slider.isMouseButtonDown() && slider.isEnabled()));
  48383. const float outlineThickness = slider.isEnabled() ? 0.8f : 0.3f;
  48384. if (style == Slider::LinearHorizontal || style == Slider::LinearVertical)
  48385. {
  48386. float kx, ky;
  48387. if (style == Slider::LinearVertical)
  48388. {
  48389. kx = x + width * 0.5f;
  48390. ky = sliderPos;
  48391. }
  48392. else
  48393. {
  48394. kx = sliderPos;
  48395. ky = y + height * 0.5f;
  48396. }
  48397. drawGlassSphere (g,
  48398. kx - sliderRadius,
  48399. ky - sliderRadius,
  48400. sliderRadius * 2.0f,
  48401. knobColour, outlineThickness);
  48402. }
  48403. else
  48404. {
  48405. if (style == Slider::ThreeValueVertical)
  48406. {
  48407. drawGlassSphere (g, x + width * 0.5f - sliderRadius,
  48408. sliderPos - sliderRadius,
  48409. sliderRadius * 2.0f,
  48410. knobColour, outlineThickness);
  48411. }
  48412. else if (style == Slider::ThreeValueHorizontal)
  48413. {
  48414. drawGlassSphere (g,sliderPos - sliderRadius,
  48415. y + height * 0.5f - sliderRadius,
  48416. sliderRadius * 2.0f,
  48417. knobColour, outlineThickness);
  48418. }
  48419. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  48420. {
  48421. const float sr = jmin (sliderRadius, width * 0.4f);
  48422. drawGlassPointer (g, jmax (0.0f, x + width * 0.5f - sliderRadius * 2.0f),
  48423. minSliderPos - sliderRadius,
  48424. sliderRadius * 2.0f, knobColour, outlineThickness, 1);
  48425. drawGlassPointer (g, jmin (x + width - sliderRadius * 2.0f, x + width * 0.5f), maxSliderPos - sr,
  48426. sliderRadius * 2.0f, knobColour, outlineThickness, 3);
  48427. }
  48428. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  48429. {
  48430. const float sr = jmin (sliderRadius, height * 0.4f);
  48431. drawGlassPointer (g, minSliderPos - sr,
  48432. jmax (0.0f, y + height * 0.5f - sliderRadius * 2.0f),
  48433. sliderRadius * 2.0f, knobColour, outlineThickness, 2);
  48434. drawGlassPointer (g, maxSliderPos - sliderRadius,
  48435. jmin (y + height - sliderRadius * 2.0f, y + height * 0.5f),
  48436. sliderRadius * 2.0f, knobColour, outlineThickness, 4);
  48437. }
  48438. }
  48439. }
  48440. void LookAndFeel::drawLinearSlider (Graphics& g,
  48441. int x, int y,
  48442. int width, int height,
  48443. float sliderPos,
  48444. float minSliderPos,
  48445. float maxSliderPos,
  48446. const Slider::SliderStyle style,
  48447. Slider& slider)
  48448. {
  48449. g.fillAll (slider.findColour (Slider::backgroundColourId));
  48450. if (style == Slider::LinearBar)
  48451. {
  48452. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  48453. Colour baseColour (createBaseColour (slider.findColour (Slider::thumbColourId)
  48454. .withMultipliedSaturation (slider.isEnabled() ? 1.0f : 0.5f),
  48455. false,
  48456. isMouseOver,
  48457. isMouseOver || slider.isMouseButtonDown()));
  48458. drawShinyButtonShape (g,
  48459. (float) x, (float) y, sliderPos - (float) x, (float) height, 0.0f,
  48460. baseColour,
  48461. slider.isEnabled() ? 0.9f : 0.3f,
  48462. true, true, true, true);
  48463. }
  48464. else
  48465. {
  48466. drawLinearSliderBackground (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  48467. drawLinearSliderThumb (g, x, y, width, height, sliderPos, minSliderPos, maxSliderPos, style, slider);
  48468. }
  48469. }
  48470. int LookAndFeel::getSliderThumbRadius (Slider& slider)
  48471. {
  48472. return jmin (7,
  48473. slider.getHeight() / 2,
  48474. slider.getWidth() / 2) + 2;
  48475. }
  48476. void LookAndFeel::drawRotarySlider (Graphics& g,
  48477. int x, int y,
  48478. int width, int height,
  48479. float sliderPos,
  48480. const float rotaryStartAngle,
  48481. const float rotaryEndAngle,
  48482. Slider& slider)
  48483. {
  48484. const float radius = jmin (width / 2, height / 2) - 2.0f;
  48485. const float centreX = x + width * 0.5f;
  48486. const float centreY = y + height * 0.5f;
  48487. const float rx = centreX - radius;
  48488. const float ry = centreY - radius;
  48489. const float rw = radius * 2.0f;
  48490. const float angle = rotaryStartAngle + sliderPos * (rotaryEndAngle - rotaryStartAngle);
  48491. const bool isMouseOver = slider.isMouseOverOrDragging() && slider.isEnabled();
  48492. if (radius > 12.0f)
  48493. {
  48494. if (slider.isEnabled())
  48495. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  48496. else
  48497. g.setColour (Colour (0x80808080));
  48498. const float thickness = 0.7f;
  48499. {
  48500. Path filledArc;
  48501. filledArc.addPieSegment (rx, ry, rw, rw,
  48502. rotaryStartAngle,
  48503. angle,
  48504. thickness);
  48505. g.fillPath (filledArc);
  48506. }
  48507. if (thickness > 0)
  48508. {
  48509. const float innerRadius = radius * 0.2f;
  48510. Path p;
  48511. p.addTriangle (-innerRadius, 0.0f,
  48512. 0.0f, -radius * thickness * 1.1f,
  48513. innerRadius, 0.0f);
  48514. p.addEllipse (-innerRadius, -innerRadius, innerRadius * 2.0f, innerRadius * 2.0f);
  48515. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  48516. }
  48517. if (slider.isEnabled())
  48518. {
  48519. g.setColour (slider.findColour (Slider::rotarySliderOutlineColourId));
  48520. Path outlineArc;
  48521. outlineArc.addPieSegment (rx, ry, rw, rw, rotaryStartAngle, rotaryEndAngle, thickness);
  48522. outlineArc.closeSubPath();
  48523. g.strokePath (outlineArc, PathStrokeType (slider.isEnabled() ? (isMouseOver ? 2.0f : 1.2f) : 0.3f));
  48524. }
  48525. }
  48526. else
  48527. {
  48528. if (slider.isEnabled())
  48529. g.setColour (slider.findColour (Slider::rotarySliderFillColourId).withAlpha (isMouseOver ? 1.0f : 0.7f));
  48530. else
  48531. g.setColour (Colour (0x80808080));
  48532. Path p;
  48533. p.addEllipse (-0.4f * rw, -0.4f * rw, rw * 0.8f, rw * 0.8f);
  48534. PathStrokeType (rw * 0.1f).createStrokedPath (p, p);
  48535. p.addLineSegment (0.0f, 0.0f, 0.0f, -radius, rw * 0.2f);
  48536. g.fillPath (p, AffineTransform::rotation (angle).translated (centreX, centreY));
  48537. }
  48538. }
  48539. Button* LookAndFeel::createSliderButton (const bool isIncrement)
  48540. {
  48541. return new TextButton (isIncrement ? "+" : "-", String::empty);
  48542. }
  48543. Label* LookAndFeel::createSliderTextBox (Slider& slider)
  48544. {
  48545. Label* const l = new Label (T("n"), String::empty);
  48546. l->setJustificationType (Justification::centred);
  48547. l->setColour (Label::textColourId, slider.findColour (Slider::textBoxTextColourId));
  48548. l->setColour (Label::backgroundColourId,
  48549. (slider.getSliderStyle() == Slider::LinearBar) ? Colours::transparentBlack
  48550. : slider.findColour (Slider::textBoxBackgroundColourId));
  48551. l->setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  48552. l->setColour (TextEditor::textColourId, slider.findColour (Slider::textBoxTextColourId));
  48553. l->setColour (TextEditor::backgroundColourId,
  48554. slider.findColour (Slider::textBoxBackgroundColourId)
  48555. .withAlpha (slider.getSliderStyle() == Slider::LinearBar ? 0.7f : 1.0f));
  48556. l->setColour (TextEditor::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
  48557. return l;
  48558. }
  48559. ImageEffectFilter* LookAndFeel::getSliderEffect()
  48560. {
  48561. return 0;
  48562. }
  48563. static const TextLayout layoutTooltipText (const String& text) throw()
  48564. {
  48565. const float tooltipFontSize = 15.0f;
  48566. const int maxToolTipWidth = 400;
  48567. const Font f (tooltipFontSize, Font::bold);
  48568. TextLayout tl (text, f);
  48569. tl.layout (maxToolTipWidth, Justification::left, true);
  48570. return tl;
  48571. }
  48572. void LookAndFeel::getTooltipSize (const String& tipText, int& width, int& height)
  48573. {
  48574. const TextLayout tl (layoutTooltipText (tipText));
  48575. width = tl.getWidth() + 14;
  48576. height = tl.getHeight() + 10;
  48577. }
  48578. void LookAndFeel::drawTooltip (Graphics& g, const String& text, int width, int height)
  48579. {
  48580. g.fillAll (findColour (TooltipWindow::backgroundColourId));
  48581. const Colour textCol (findColour (TooltipWindow::textColourId));
  48582. g.setColour (findColour (TooltipWindow::outlineColourId));
  48583. g.drawRect (0, 0, width, height);
  48584. const TextLayout tl (layoutTooltipText (text));
  48585. g.setColour (findColour (TooltipWindow::textColourId));
  48586. tl.drawWithin (g, 0, 0, width, height, Justification::centred);
  48587. }
  48588. Button* LookAndFeel::createFilenameComponentBrowseButton (const String& text)
  48589. {
  48590. return new TextButton (text, TRANS("click to browse for a different file"));
  48591. }
  48592. void LookAndFeel::layoutFilenameComponent (FilenameComponent& filenameComp,
  48593. ComboBox* filenameBox,
  48594. Button* browseButton)
  48595. {
  48596. browseButton->setSize (80, filenameComp.getHeight());
  48597. TextButton* const tb = dynamic_cast <TextButton*> (browseButton);
  48598. if (tb != 0)
  48599. tb->changeWidthToFitText();
  48600. browseButton->setTopRightPosition (filenameComp.getWidth(), 0);
  48601. filenameBox->setBounds (0, 0, browseButton->getX(), filenameComp.getHeight());
  48602. }
  48603. void LookAndFeel::drawCornerResizer (Graphics& g,
  48604. int w, int h,
  48605. bool /*isMouseOver*/,
  48606. bool /*isMouseDragging*/)
  48607. {
  48608. const float lineThickness = jmin (w, h) * 0.075f;
  48609. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  48610. {
  48611. g.setColour (Colours::lightgrey);
  48612. g.drawLine (w * i,
  48613. h + 1.0f,
  48614. w + 1.0f,
  48615. h * i,
  48616. lineThickness);
  48617. g.setColour (Colours::darkgrey);
  48618. g.drawLine (w * i + lineThickness,
  48619. h + 1.0f,
  48620. w + 1.0f,
  48621. h * i + lineThickness,
  48622. lineThickness);
  48623. }
  48624. }
  48625. void LookAndFeel::drawResizableFrame (Graphics&, int /*w*/, int /*h*/,
  48626. const BorderSize& /*borders*/)
  48627. {
  48628. }
  48629. void LookAndFeel::drawResizableWindowBorder (Graphics& g, int w, int h,
  48630. const BorderSize& border, ResizableWindow&)
  48631. {
  48632. g.setColour (Colour (0x80000000));
  48633. g.drawRect (0, 0, w, h);
  48634. g.setColour (Colour (0x19000000));
  48635. g.drawRect (border.getLeft() - 1,
  48636. border.getTop() - 1,
  48637. w + 2 - border.getLeftAndRight(),
  48638. h + 2 - border.getTopAndBottom());
  48639. }
  48640. void LookAndFeel::drawDocumentWindowTitleBar (DocumentWindow& window,
  48641. Graphics& g, int w, int h,
  48642. int titleSpaceX, int titleSpaceW,
  48643. const Image* icon,
  48644. bool drawTitleTextOnLeft)
  48645. {
  48646. const bool isActive = window.isActiveWindow();
  48647. GradientBrush gb (window.getBackgroundColour(),
  48648. 0.0f, 0.0f,
  48649. window.getBackgroundColour().contrasting (isActive ? 0.15f : 0.05f),
  48650. 0.0f, (float) h, false);
  48651. g.setBrush (&gb);
  48652. g.fillAll();
  48653. g.setFont (h * 0.65f, Font::bold);
  48654. int textW = g.getCurrentFont().getStringWidth (window.getName());
  48655. int iconW = 0;
  48656. int iconH = 0;
  48657. if (icon != 0)
  48658. {
  48659. iconH = (int) g.getCurrentFont().getHeight();
  48660. iconW = icon->getWidth() * iconH / icon->getHeight() + 4;
  48661. }
  48662. textW = jmin (titleSpaceW, textW + iconW);
  48663. int textX = drawTitleTextOnLeft ? titleSpaceX
  48664. : jmax (titleSpaceX, (w - textW) / 2);
  48665. if (textX + textW > titleSpaceX + titleSpaceW)
  48666. textX = titleSpaceX + titleSpaceW - textW;
  48667. if (icon != 0)
  48668. {
  48669. g.setOpacity (isActive ? 1.0f : 0.6f);
  48670. g.drawImageWithin (icon, textX, (h - iconH) / 2, iconW, iconH,
  48671. RectanglePlacement::centred, false);
  48672. textX += iconW;
  48673. textW -= iconW;
  48674. }
  48675. g.setColour (window.getBackgroundColour().contrasting (isActive ? 0.7f : 0.4f));
  48676. g.drawText (window.getName(), textX, 0, textW, h, Justification::centredLeft, true);
  48677. }
  48678. class GlassWindowButton : public Button
  48679. {
  48680. public:
  48681. GlassWindowButton (const String& name, const Colour& col,
  48682. const Path& normalShape_,
  48683. const Path& toggledShape_) throw()
  48684. : Button (name),
  48685. colour (col),
  48686. normalShape (normalShape_),
  48687. toggledShape (toggledShape_)
  48688. {
  48689. }
  48690. ~GlassWindowButton()
  48691. {
  48692. }
  48693. void paintButton (Graphics& g, bool isMouseOverButton, bool isButtonDown)
  48694. {
  48695. float alpha = isMouseOverButton ? (isButtonDown ? 1.0f : 0.8f) : 0.55f;
  48696. if (! isEnabled())
  48697. alpha *= 0.5f;
  48698. float x = 0, y = 0, diam;
  48699. if (getWidth() < getHeight())
  48700. {
  48701. diam = (float) getWidth();
  48702. y = (getHeight() - getWidth()) * 0.5f;
  48703. }
  48704. else
  48705. {
  48706. diam = (float) getHeight();
  48707. y = (getWidth() - getHeight()) * 0.5f;
  48708. }
  48709. x += diam * 0.05f;
  48710. y += diam * 0.05f;
  48711. diam *= 0.9f;
  48712. GradientBrush gb1 (Colour::greyLevel (0.9f).withAlpha (alpha), 0, y + diam,
  48713. Colour::greyLevel (0.6f).withAlpha (alpha), 0, y, false);
  48714. g.setBrush (&gb1);
  48715. g.fillEllipse (x, y, diam, diam);
  48716. x += 2.0f;
  48717. y += 2.0f;
  48718. diam -= 4.0f;
  48719. LookAndFeel::drawGlassSphere (g, x, y, diam, colour.withAlpha (alpha), 1.0f);
  48720. Path& p = getToggleState() ? toggledShape : normalShape;
  48721. const AffineTransform t (p.getTransformToScaleToFit (x + diam * 0.3f, y + diam * 0.3f,
  48722. diam * 0.4f, diam * 0.4f, true));
  48723. g.setColour (Colours::black.withAlpha (alpha * 0.6f));
  48724. g.fillPath (p, t);
  48725. }
  48726. juce_UseDebuggingNewOperator
  48727. private:
  48728. Colour colour;
  48729. Path normalShape, toggledShape;
  48730. GlassWindowButton (const GlassWindowButton&);
  48731. const GlassWindowButton& operator= (const GlassWindowButton&);
  48732. };
  48733. Button* LookAndFeel::createDocumentWindowButton (int buttonType)
  48734. {
  48735. Path shape;
  48736. const float crossThickness = 0.25f;
  48737. if (buttonType == DocumentWindow::closeButton)
  48738. {
  48739. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, crossThickness * 1.4f);
  48740. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, crossThickness * 1.4f);
  48741. return new GlassWindowButton ("close", Colour (0xffdd1100), shape, shape);
  48742. }
  48743. else if (buttonType == DocumentWindow::minimiseButton)
  48744. {
  48745. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  48746. return new GlassWindowButton ("minimise", Colour (0xffaa8811), shape, shape);
  48747. }
  48748. else if (buttonType == DocumentWindow::maximiseButton)
  48749. {
  48750. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, crossThickness);
  48751. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, crossThickness);
  48752. Path fullscreenShape;
  48753. fullscreenShape.startNewSubPath (45.0f, 100.0f);
  48754. fullscreenShape.lineTo (0.0f, 100.0f);
  48755. fullscreenShape.lineTo (0.0f, 0.0f);
  48756. fullscreenShape.lineTo (100.0f, 0.0f);
  48757. fullscreenShape.lineTo (100.0f, 45.0f);
  48758. fullscreenShape.addRectangle (45.0f, 45.0f, 100.0f, 100.0f);
  48759. PathStrokeType (30.0f).createStrokedPath (fullscreenShape, fullscreenShape);
  48760. return new GlassWindowButton ("maximise", Colour (0xff119911), shape, fullscreenShape);
  48761. }
  48762. jassertfalse
  48763. return 0;
  48764. }
  48765. void LookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  48766. int titleBarX,
  48767. int titleBarY,
  48768. int titleBarW,
  48769. int titleBarH,
  48770. Button* minimiseButton,
  48771. Button* maximiseButton,
  48772. Button* closeButton,
  48773. bool positionTitleBarButtonsOnLeft)
  48774. {
  48775. const int buttonW = titleBarH - titleBarH / 8;
  48776. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  48777. : titleBarX + titleBarW - buttonW - buttonW / 4;
  48778. if (closeButton != 0)
  48779. {
  48780. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  48781. x += positionTitleBarButtonsOnLeft ? buttonW : -(buttonW + buttonW / 4);
  48782. }
  48783. if (positionTitleBarButtonsOnLeft)
  48784. swapVariables (minimiseButton, maximiseButton);
  48785. if (maximiseButton != 0)
  48786. {
  48787. maximiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  48788. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  48789. }
  48790. if (minimiseButton != 0)
  48791. minimiseButton->setBounds (x, titleBarY, buttonW, titleBarH);
  48792. }
  48793. int LookAndFeel::getDefaultMenuBarHeight()
  48794. {
  48795. return 24;
  48796. }
  48797. DropShadower* LookAndFeel::createDropShadowerForComponent (Component*)
  48798. {
  48799. return new DropShadower (0.4f, 1, 5, 10);
  48800. }
  48801. void LookAndFeel::drawStretchableLayoutResizerBar (Graphics& g,
  48802. int w, int h,
  48803. bool /*isVerticalBar*/,
  48804. bool isMouseOver,
  48805. bool isMouseDragging)
  48806. {
  48807. float alpha = 0.5f;
  48808. if (isMouseOver || isMouseDragging)
  48809. {
  48810. g.fillAll (Colour (0x190000ff));
  48811. alpha = 1.0f;
  48812. }
  48813. const float cx = w * 0.5f;
  48814. const float cy = h * 0.5f;
  48815. const float cr = jmin (w, h) * 0.4f;
  48816. GradientBrush gb (Colours::white.withAlpha (alpha), cx + cr * 0.1f, cy + cr,
  48817. Colours::black.withAlpha (alpha), cx, cy - cr * 4.0f,
  48818. true);
  48819. g.setBrush (&gb);
  48820. g.fillEllipse (cx - cr, cy - cr, cr * 2.0f, cr * 2.0f);
  48821. }
  48822. void LookAndFeel::drawGroupComponentOutline (Graphics& g, int width, int height,
  48823. const String& text,
  48824. const Justification& position,
  48825. GroupComponent& group)
  48826. {
  48827. const float textH = 15.0f;
  48828. const float indent = 3.0f;
  48829. const float textEdgeGap = 4.0f;
  48830. float cs = 5.0f;
  48831. Font f (textH);
  48832. Path p;
  48833. float x = indent;
  48834. float y = f.getAscent() - 3.0f;
  48835. float w = jmax (0.0f, width - x * 2.0f);
  48836. float h = jmax (0.0f, height - y - indent);
  48837. cs = jmin (cs, w * 0.5f, h * 0.5f);
  48838. const float cs2 = 2.0f * cs;
  48839. float textW = text.isEmpty() ? 0 : jlimit (0.0f, jmax (0.0f, w - cs2 - textEdgeGap * 2), f.getStringWidth (text) + textEdgeGap * 2.0f);
  48840. float textX = cs + textEdgeGap;
  48841. if (position.testFlags (Justification::horizontallyCentred))
  48842. textX = cs + (w - cs2 - textW) * 0.5f;
  48843. else if (position.testFlags (Justification::right))
  48844. textX = w - cs - textW - textEdgeGap;
  48845. p.startNewSubPath (x + textX + textW, y);
  48846. p.lineTo (x + w - cs, y);
  48847. p.addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  48848. p.lineTo (x + w, y + h - cs);
  48849. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  48850. p.lineTo (x + cs, y + h);
  48851. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  48852. p.lineTo (x, y + cs);
  48853. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  48854. p.lineTo (x + textX, y);
  48855. const float alpha = group.isEnabled() ? 1.0f : 0.5f;
  48856. g.setColour (group.findColour (GroupComponent::outlineColourId)
  48857. .withMultipliedAlpha (alpha));
  48858. g.strokePath (p, PathStrokeType (2.0f));
  48859. g.setColour (group.findColour (GroupComponent::textColourId)
  48860. .withMultipliedAlpha (alpha));
  48861. g.setFont (f);
  48862. g.drawText (text,
  48863. roundFloatToInt (x + textX), 0,
  48864. roundFloatToInt (textW),
  48865. roundFloatToInt (textH),
  48866. Justification::centred, true);
  48867. }
  48868. int LookAndFeel::getTabButtonOverlap (int tabDepth)
  48869. {
  48870. return 1 + tabDepth / 3;
  48871. }
  48872. int LookAndFeel::getTabButtonSpaceAroundImage()
  48873. {
  48874. return 4;
  48875. }
  48876. void LookAndFeel::createTabButtonShape (Path& p,
  48877. int width, int height,
  48878. int /*tabIndex*/,
  48879. const String& /*text*/,
  48880. Button& /*button*/,
  48881. TabbedButtonBar::Orientation orientation,
  48882. const bool /*isMouseOver*/,
  48883. const bool /*isMouseDown*/,
  48884. const bool /*isFrontTab*/)
  48885. {
  48886. const float w = (float) width;
  48887. const float h = (float) height;
  48888. float length = w;
  48889. float depth = h;
  48890. if (orientation == TabbedButtonBar::TabsAtLeft
  48891. || orientation == TabbedButtonBar::TabsAtRight)
  48892. {
  48893. swapVariables (length, depth);
  48894. }
  48895. const float indent = (float) getTabButtonOverlap ((int) depth);
  48896. const float overhang = 4.0f;
  48897. if (orientation == TabbedButtonBar::TabsAtLeft)
  48898. {
  48899. p.startNewSubPath (w, 0.0f);
  48900. p.lineTo (0.0f, indent);
  48901. p.lineTo (0.0f, h - indent);
  48902. p.lineTo (w, h);
  48903. p.lineTo (w + overhang, h + overhang);
  48904. p.lineTo (w + overhang, -overhang);
  48905. }
  48906. else if (orientation == TabbedButtonBar::TabsAtRight)
  48907. {
  48908. p.startNewSubPath (0.0f, 0.0f);
  48909. p.lineTo (w, indent);
  48910. p.lineTo (w, h - indent);
  48911. p.lineTo (0.0f, h);
  48912. p.lineTo (-overhang, h + overhang);
  48913. p.lineTo (-overhang, -overhang);
  48914. }
  48915. else if (orientation == TabbedButtonBar::TabsAtBottom)
  48916. {
  48917. p.startNewSubPath (0.0f, 0.0f);
  48918. p.lineTo (indent, h);
  48919. p.lineTo (w - indent, h);
  48920. p.lineTo (w, 0.0f);
  48921. p.lineTo (w + overhang, -overhang);
  48922. p.lineTo (-overhang, -overhang);
  48923. }
  48924. else
  48925. {
  48926. p.startNewSubPath (0.0f, h);
  48927. p.lineTo (indent, 0.0f);
  48928. p.lineTo (w - indent, 0.0f);
  48929. p.lineTo (w, h);
  48930. p.lineTo (w + overhang, h + overhang);
  48931. p.lineTo (-overhang, h + overhang);
  48932. }
  48933. p.closeSubPath();
  48934. p = p.createPathWithRoundedCorners (3.0f);
  48935. }
  48936. void LookAndFeel::fillTabButtonShape (Graphics& g,
  48937. const Path& path,
  48938. const Colour& preferredColour,
  48939. int /*tabIndex*/,
  48940. const String& /*text*/,
  48941. Button& button,
  48942. TabbedButtonBar::Orientation /*orientation*/,
  48943. const bool /*isMouseOver*/,
  48944. const bool /*isMouseDown*/,
  48945. const bool isFrontTab)
  48946. {
  48947. g.setColour (isFrontTab ? preferredColour
  48948. : preferredColour.withMultipliedAlpha (0.9f));
  48949. g.fillPath (path);
  48950. g.setColour (Colours::black.withAlpha (button.isEnabled() ? 0.5f : 0.25f));
  48951. g.strokePath (path, PathStrokeType (isFrontTab ? 1.0f : 0.5f));
  48952. }
  48953. void LookAndFeel::drawTabButtonText (Graphics& g,
  48954. int x, int y, int w, int h,
  48955. const Colour& preferredBackgroundColour,
  48956. int /*tabIndex*/,
  48957. const String& text,
  48958. Button& button,
  48959. TabbedButtonBar::Orientation orientation,
  48960. const bool isMouseOver,
  48961. const bool isMouseDown,
  48962. const bool /*isFrontTab*/)
  48963. {
  48964. int length = w;
  48965. int depth = h;
  48966. if (orientation == TabbedButtonBar::TabsAtLeft
  48967. || orientation == TabbedButtonBar::TabsAtRight)
  48968. {
  48969. swapVariables (length, depth);
  48970. }
  48971. Font font (depth * 0.6f);
  48972. font.setUnderline (button.hasKeyboardFocus (false));
  48973. GlyphArrangement textLayout;
  48974. textLayout.addFittedText (font, text.trim(),
  48975. 0.0f, 0.0f, (float) length, (float) depth,
  48976. Justification::centred,
  48977. jmax (1, depth / 12));
  48978. AffineTransform transform;
  48979. if (orientation == TabbedButtonBar::TabsAtLeft)
  48980. {
  48981. transform = transform.rotated (float_Pi * -0.5f)
  48982. .translated ((float) x, (float) (y + h));
  48983. }
  48984. else if (orientation == TabbedButtonBar::TabsAtRight)
  48985. {
  48986. transform = transform.rotated (float_Pi * 0.5f)
  48987. .translated ((float) (x + w), (float) y);
  48988. }
  48989. else
  48990. {
  48991. transform = transform.translated ((float) x, (float) y);
  48992. }
  48993. g.setColour (preferredBackgroundColour.contrasting());
  48994. if (! (isMouseOver || isMouseDown))
  48995. g.setOpacity (0.8f);
  48996. if (! button.isEnabled())
  48997. g.setOpacity (0.3f);
  48998. textLayout.draw (g, transform);
  48999. }
  49000. int LookAndFeel::getTabButtonBestWidth (int /*tabIndex*/,
  49001. const String& text,
  49002. int tabDepth,
  49003. Button&)
  49004. {
  49005. Font f (tabDepth * 0.6f);
  49006. return f.getStringWidth (text.trim()) + getTabButtonOverlap (tabDepth) * 2;
  49007. }
  49008. void LookAndFeel::drawTabButton (Graphics& g,
  49009. int w, int h,
  49010. const Colour& preferredColour,
  49011. int tabIndex,
  49012. const String& text,
  49013. Button& button,
  49014. TabbedButtonBar::Orientation orientation,
  49015. const bool isMouseOver,
  49016. const bool isMouseDown,
  49017. const bool isFrontTab)
  49018. {
  49019. int length = w;
  49020. int depth = h;
  49021. if (orientation == TabbedButtonBar::TabsAtLeft
  49022. || orientation == TabbedButtonBar::TabsAtRight)
  49023. {
  49024. swapVariables (length, depth);
  49025. }
  49026. Path tabShape;
  49027. createTabButtonShape (tabShape, w, h,
  49028. tabIndex, text, button, orientation,
  49029. isMouseOver, isMouseDown, isFrontTab);
  49030. fillTabButtonShape (g, tabShape, preferredColour,
  49031. tabIndex, text, button, orientation,
  49032. isMouseOver, isMouseDown, isFrontTab);
  49033. const int indent = getTabButtonOverlap (depth);
  49034. int x = 0, y = 0;
  49035. if (orientation == TabbedButtonBar::TabsAtLeft
  49036. || orientation == TabbedButtonBar::TabsAtRight)
  49037. {
  49038. y += indent;
  49039. h -= indent * 2;
  49040. }
  49041. else
  49042. {
  49043. x += indent;
  49044. w -= indent * 2;
  49045. }
  49046. drawTabButtonText (g, x, y, w, h, preferredColour,
  49047. tabIndex, text, button, orientation,
  49048. isMouseOver, isMouseDown, isFrontTab);
  49049. }
  49050. void LookAndFeel::drawTabAreaBehindFrontButton (Graphics& g,
  49051. int w, int h,
  49052. TabbedButtonBar& tabBar,
  49053. TabbedButtonBar::Orientation orientation)
  49054. {
  49055. const float shadowSize = 0.2f;
  49056. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  49057. Rectangle shadowRect;
  49058. if (orientation == TabbedButtonBar::TabsAtLeft)
  49059. {
  49060. x1 = (float) w;
  49061. x2 = w * (1.0f - shadowSize);
  49062. shadowRect.setBounds ((int) x2, 0, w - (int) x2, h);
  49063. }
  49064. else if (orientation == TabbedButtonBar::TabsAtRight)
  49065. {
  49066. x2 = w * shadowSize;
  49067. shadowRect.setBounds (0, 0, (int) x2, h);
  49068. }
  49069. else if (orientation == TabbedButtonBar::TabsAtBottom)
  49070. {
  49071. y2 = h * shadowSize;
  49072. shadowRect.setBounds (0, 0, w, (int) y2);
  49073. }
  49074. else
  49075. {
  49076. y1 = (float) h;
  49077. y2 = h * (1.0f - shadowSize);
  49078. shadowRect.setBounds (0, (int) y2, w, h - (int) y2);
  49079. }
  49080. GradientBrush gb (Colours::black.withAlpha (tabBar.isEnabled() ? 0.3f : 0.15f), x1, y1,
  49081. Colours::transparentBlack, x2, y2,
  49082. false);
  49083. g.setBrush (&gb);
  49084. shadowRect.expand (2, 2);
  49085. g.fillRect (shadowRect);
  49086. g.setColour (Colour (0x80000000));
  49087. if (orientation == TabbedButtonBar::TabsAtLeft)
  49088. {
  49089. g.fillRect (w - 1, 0, 1, h);
  49090. }
  49091. else if (orientation == TabbedButtonBar::TabsAtRight)
  49092. {
  49093. g.fillRect (0, 0, 1, h);
  49094. }
  49095. else if (orientation == TabbedButtonBar::TabsAtBottom)
  49096. {
  49097. g.fillRect (0, 0, w, 1);
  49098. }
  49099. else
  49100. {
  49101. g.fillRect (0, h - 1, w, 1);
  49102. }
  49103. }
  49104. Button* LookAndFeel::createTabBarExtrasButton()
  49105. {
  49106. const float thickness = 7.0f;
  49107. const float indent = 22.0f;
  49108. Path p;
  49109. p.addEllipse (-10.0f, -10.0f, 120.0f, 120.0f);
  49110. DrawablePath ellipse;
  49111. ellipse.setPath (p);
  49112. ellipse.setSolidFill (Colour (0x99ffffff));
  49113. p.clear();
  49114. p.addEllipse (0.0f, 0.0f, 100.0f, 100.0f);
  49115. p.addRectangle (indent, 50.0f - thickness, 100.0f - indent * 2.0f, thickness * 2.0f);
  49116. p.addRectangle (50.0f - thickness, indent, thickness * 2.0f, 50.0f - indent - thickness);
  49117. p.addRectangle (50.0f - thickness, 50.0f + thickness, thickness * 2.0f, 50.0f - indent - thickness);
  49118. p.setUsingNonZeroWinding (false);
  49119. DrawablePath dp;
  49120. dp.setPath (p);
  49121. dp.setSolidFill (Colour (0x59000000));
  49122. DrawableComposite normalImage;
  49123. normalImage.insertDrawable (ellipse);
  49124. normalImage.insertDrawable (dp);
  49125. dp.setSolidFill (Colour (0xcc000000));
  49126. DrawableComposite overImage;
  49127. overImage.insertDrawable (ellipse);
  49128. overImage.insertDrawable (dp);
  49129. DrawableButton* db = new DrawableButton (T("tabs"), DrawableButton::ImageFitted);
  49130. db->setImages (&normalImage, &overImage, 0);
  49131. return db;
  49132. }
  49133. void LookAndFeel::drawTableHeaderBackground (Graphics& g, TableHeaderComponent& header)
  49134. {
  49135. g.fillAll (Colours::white);
  49136. const int w = header.getWidth();
  49137. const int h = header.getHeight();
  49138. GradientBrush gb (Colour (0xffe8ebf9), 0.0f, h * 0.5f,
  49139. Colour (0xfff6f8f9), 0.0f, h - 1.0f,
  49140. false);
  49141. g.setBrush (&gb);
  49142. g.fillRect (0, h / 2, w, h);
  49143. g.setColour (Colour (0x33000000));
  49144. g.fillRect (0, h - 1, w, 1);
  49145. for (int i = header.getNumColumns (true); --i >= 0;)
  49146. g.fillRect (header.getColumnPosition (i).getRight() - 1, 0, 1, h - 1);
  49147. }
  49148. void LookAndFeel::drawTableHeaderColumn (Graphics& g, const String& columnName, int /*columnId*/,
  49149. int width, int height,
  49150. bool isMouseOver, bool isMouseDown,
  49151. int columnFlags)
  49152. {
  49153. if (isMouseDown)
  49154. g.fillAll (Colour (0x8899aadd));
  49155. else if (isMouseOver)
  49156. g.fillAll (Colour (0x5599aadd));
  49157. int rightOfText = width - 4;
  49158. if ((columnFlags & (TableHeaderComponent::sortedForwards | TableHeaderComponent::sortedBackwards)) != 0)
  49159. {
  49160. const float top = height * ((columnFlags & TableHeaderComponent::sortedForwards) != 0 ? 0.35f : (1.0f - 0.35f));
  49161. const float bottom = height - top;
  49162. const float w = height * 0.5f;
  49163. const float x = rightOfText - (w * 1.25f);
  49164. rightOfText = (int) x;
  49165. Path sortArrow;
  49166. sortArrow.addTriangle (x, bottom, x + w * 0.5f, top, x + w, bottom);
  49167. g.setColour (Colour (0x99000000));
  49168. g.fillPath (sortArrow);
  49169. }
  49170. g.setColour (Colours::black);
  49171. g.setFont (height * 0.5f, Font::bold);
  49172. const int textX = 4;
  49173. g.drawFittedText (columnName, textX, 0, rightOfText - textX, height, Justification::centredLeft, 1);
  49174. }
  49175. void LookAndFeel::paintToolbarBackground (Graphics& g, int w, int h, Toolbar& toolbar)
  49176. {
  49177. const Colour background (toolbar.findColour (Toolbar::backgroundColourId));
  49178. GradientBrush gb (background, 0.0f, 0.0f,
  49179. background.darker (0.1f),
  49180. toolbar.isVertical() ? w - 1.0f : 0.0f,
  49181. toolbar.isVertical() ? 0.0f : h - 1.0f,
  49182. false);
  49183. g.setBrush (&gb);
  49184. g.fillAll();
  49185. }
  49186. Button* LookAndFeel::createToolbarMissingItemsButton (Toolbar& /*toolbar*/)
  49187. {
  49188. return createTabBarExtrasButton();
  49189. }
  49190. void LookAndFeel::paintToolbarButtonBackground (Graphics& g, int /*width*/, int /*height*/,
  49191. bool isMouseOver, bool isMouseDown,
  49192. ToolbarItemComponent& component)
  49193. {
  49194. if (isMouseDown)
  49195. g.fillAll (component.findColour (Toolbar::buttonMouseDownBackgroundColourId, true));
  49196. else if (isMouseOver)
  49197. g.fillAll (component.findColour (Toolbar::buttonMouseOverBackgroundColourId, true));
  49198. }
  49199. void LookAndFeel::paintToolbarButtonLabel (Graphics& g, int x, int y, int width, int height,
  49200. const String& text, ToolbarItemComponent& component)
  49201. {
  49202. g.setColour (component.findColour (Toolbar::labelTextColourId, true)
  49203. .withAlpha (component.isEnabled() ? 1.0f : 0.25f));
  49204. const float fontHeight = jmin (14.0f, height * 0.85f);
  49205. g.setFont (fontHeight);
  49206. g.drawFittedText (text,
  49207. x, y, width, height,
  49208. Justification::centred,
  49209. jmax (1, height / (int) fontHeight));
  49210. }
  49211. void LookAndFeel::drawPropertyPanelSectionHeader (Graphics& g, const String& name,
  49212. bool isOpen, int width, int height)
  49213. {
  49214. const int buttonSize = (height * 3) / 4;
  49215. const int buttonIndent = (height - buttonSize) / 2;
  49216. drawTreeviewPlusMinusBox (g, buttonIndent, buttonIndent, buttonSize, buttonSize, ! isOpen);
  49217. const int textX = buttonIndent * 2 + buttonSize + 2;
  49218. g.setColour (Colours::black);
  49219. g.setFont (height * 0.7f, Font::bold);
  49220. g.drawText (name, textX, 0, width - textX - 4, height, Justification::centredLeft, true);
  49221. }
  49222. void LookAndFeel::drawPropertyComponentBackground (Graphics& g, int width, int height,
  49223. PropertyComponent&)
  49224. {
  49225. g.setColour (Colour (0x66ffffff));
  49226. g.fillRect (0, 0, width, height - 1);
  49227. }
  49228. void LookAndFeel::drawPropertyComponentLabel (Graphics& g, int, int height,
  49229. PropertyComponent& component)
  49230. {
  49231. g.setColour (Colours::black);
  49232. if (! component.isEnabled())
  49233. g.setOpacity (g.getCurrentColour().getAlpha() * 0.6f);
  49234. g.setFont (jmin (height, 24) * 0.65f);
  49235. const Rectangle r (getPropertyComponentContentPosition (component));
  49236. g.drawFittedText (component.getName(),
  49237. 3, r.getY(), r.getX() - 5, r.getHeight(),
  49238. Justification::centredLeft, 2);
  49239. }
  49240. const Rectangle LookAndFeel::getPropertyComponentContentPosition (PropertyComponent& component)
  49241. {
  49242. return Rectangle (component.getWidth() / 3, 1,
  49243. component.getWidth() - component.getWidth() / 3 - 1, component.getHeight() - 3);
  49244. }
  49245. void LookAndFeel::createFileChooserHeaderText (const String& title,
  49246. const String& instructions,
  49247. GlyphArrangement& text,
  49248. int width)
  49249. {
  49250. text.clear();
  49251. text.addJustifiedText (Font (17.0f, Font::bold), title,
  49252. 8.0f, 22.0f, width - 16.0f,
  49253. Justification::centred);
  49254. text.addJustifiedText (Font (14.0f), instructions,
  49255. 8.0f, 24.0f + 16.0f, width - 16.0f,
  49256. Justification::centred);
  49257. }
  49258. void LookAndFeel::drawFileBrowserRow (Graphics& g, int width, int height,
  49259. const String& filename, Image* icon,
  49260. const String& fileSizeDescription,
  49261. const String& fileTimeDescription,
  49262. const bool isDirectory,
  49263. const bool isItemSelected,
  49264. const int /*itemIndex*/)
  49265. {
  49266. if (isItemSelected)
  49267. g.fillAll (findColour (DirectoryContentsDisplayComponent::highlightColourId));
  49268. g.setColour (findColour (DirectoryContentsDisplayComponent::textColourId));
  49269. g.setFont (height * 0.7f);
  49270. Image* im = icon;
  49271. Image* toRelease = 0;
  49272. if (im == 0)
  49273. {
  49274. toRelease = im = (isDirectory ? getDefaultFolderImage()
  49275. : getDefaultDocumentFileImage());
  49276. }
  49277. const int x = 32;
  49278. if (im != 0)
  49279. {
  49280. g.drawImageWithin (im, 2, 2, x - 4, height - 4,
  49281. RectanglePlacement::centred | RectanglePlacement::onlyReduceInSize,
  49282. false);
  49283. ImageCache::release (toRelease);
  49284. }
  49285. if (width > 450 && ! isDirectory)
  49286. {
  49287. const int sizeX = roundFloatToInt (width * 0.7f);
  49288. const int dateX = roundFloatToInt (width * 0.8f);
  49289. g.drawFittedText (filename,
  49290. x, 0, sizeX - x, height,
  49291. Justification::centredLeft, 1);
  49292. g.setFont (height * 0.5f);
  49293. g.setColour (Colours::darkgrey);
  49294. if (! isDirectory)
  49295. {
  49296. g.drawFittedText (fileSizeDescription,
  49297. sizeX, 0, dateX - sizeX - 8, height,
  49298. Justification::centredRight, 1);
  49299. g.drawFittedText (fileTimeDescription,
  49300. dateX, 0, width - 8 - dateX, height,
  49301. Justification::centredRight, 1);
  49302. }
  49303. }
  49304. else
  49305. {
  49306. g.drawFittedText (filename,
  49307. x, 0, width - x, height,
  49308. Justification::centredLeft, 1);
  49309. }
  49310. }
  49311. Button* LookAndFeel::createFileBrowserGoUpButton()
  49312. {
  49313. DrawableButton* goUpButton = new DrawableButton ("up", DrawableButton::ImageOnButtonBackground);
  49314. Path arrowPath;
  49315. arrowPath.addArrow (50.0f, 100.0f, 50.0f, 0.0, 40.0f, 100.0f, 50.0f);
  49316. DrawablePath arrowImage;
  49317. arrowImage.setSolidFill (Colours::black.withAlpha (0.4f));
  49318. arrowImage.setPath (arrowPath);
  49319. goUpButton->setImages (&arrowImage);
  49320. return goUpButton;
  49321. }
  49322. void LookAndFeel::layoutFileBrowserComponent (FileBrowserComponent& browserComp,
  49323. DirectoryContentsDisplayComponent* fileListComponent,
  49324. FilePreviewComponent* previewComp,
  49325. ComboBox* currentPathBox,
  49326. TextEditor* filenameBox,
  49327. Button* goUpButton)
  49328. {
  49329. const int x = 8;
  49330. int w = browserComp.getWidth() - x - x;
  49331. if (previewComp != 0)
  49332. {
  49333. const int previewWidth = w / 3;
  49334. previewComp->setBounds (x + w - previewWidth, 0, previewWidth, browserComp.getHeight());
  49335. w -= previewWidth + 4;
  49336. }
  49337. int y = 4;
  49338. const int controlsHeight = 22;
  49339. const int bottomSectionHeight = controlsHeight + 8;
  49340. const int upButtonWidth = 50;
  49341. currentPathBox->setBounds (x, y, w - upButtonWidth - 6, controlsHeight);
  49342. goUpButton->setBounds (x + w - upButtonWidth, y, upButtonWidth, controlsHeight);
  49343. y += controlsHeight + 4;
  49344. Component* const listAsComp = dynamic_cast <Component*> (fileListComponent);
  49345. listAsComp->setBounds (x, y, w, browserComp.getHeight() - y - bottomSectionHeight);
  49346. y = listAsComp->getBottom() + 4;
  49347. filenameBox->setBounds (x + 50, y, w - 50, controlsHeight);
  49348. }
  49349. Image* LookAndFeel::getDefaultFolderImage()
  49350. {
  49351. 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,
  49352. 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,
  49353. 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,
  49354. 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,
  49355. 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,
  49356. 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,
  49357. 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,
  49358. 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,
  49359. 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,
  49360. 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,
  49361. 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,
  49362. 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,
  49363. 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,
  49364. 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,
  49365. 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,
  49366. 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,
  49367. 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,
  49368. 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,
  49369. 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,
  49370. 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,
  49371. 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,
  49372. 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,
  49373. 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,
  49374. 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,
  49375. 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,
  49376. 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,
  49377. 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,
  49378. 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,
  49379. 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,
  49380. 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,
  49381. 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,
  49382. 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,
  49383. 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,
  49384. 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,
  49385. 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,
  49386. 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,
  49387. 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,
  49388. 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,
  49389. 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,
  49390. 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,
  49391. 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,
  49392. 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,
  49393. 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,
  49394. 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};
  49395. return ImageCache::getFromMemory (foldericon_png, sizeof (foldericon_png));
  49396. }
  49397. Image* LookAndFeel::getDefaultDocumentFileImage()
  49398. {
  49399. 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,
  49400. 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,
  49401. 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,
  49402. 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,
  49403. 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,
  49404. 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,
  49405. 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,
  49406. 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,
  49407. 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,
  49408. 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,
  49409. 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,
  49410. 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,
  49411. 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,
  49412. 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,
  49413. 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,
  49414. 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,
  49415. 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,
  49416. 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,
  49417. 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,
  49418. 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,
  49419. 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,
  49420. 174,66,96,130,0,0};
  49421. return ImageCache::getFromMemory (fileicon_png, sizeof (fileicon_png));
  49422. }
  49423. void LookAndFeel::playAlertSound()
  49424. {
  49425. PlatformUtilities::beep();
  49426. }
  49427. void LookAndFeel::drawLevelMeter (Graphics& g, int width, int height, float level)
  49428. {
  49429. g.setColour (Colours::white.withAlpha (0.7f));
  49430. g.fillRoundedRectangle (0.0f, 0.0f, (float) width, (float) height, 3.0f);
  49431. g.setColour (Colours::black.withAlpha (0.2f));
  49432. g.drawRoundedRectangle (1.0f, 1.0f, width - 2.0f, height - 2.0f, 3.0f, 1.0f);
  49433. const int totalBlocks = 7;
  49434. const int numBlocks = roundDoubleToInt (totalBlocks * level);
  49435. const float w = (width - 6.0f) / (float) totalBlocks;
  49436. for (int i = 0; i < totalBlocks; ++i)
  49437. {
  49438. if (i >= numBlocks)
  49439. g.setColour (Colours::lightblue.withAlpha (0.6f));
  49440. else
  49441. g.setColour (i < totalBlocks - 1 ? Colours::blue.withAlpha (0.5f)
  49442. : Colours::red);
  49443. g.fillRoundedRectangle (3.0f + i * w + w * 0.1f, 3.0f, w * 0.8f, height - 6.0f, w * 0.4f);
  49444. }
  49445. }
  49446. static void createRoundedPath (Path& p,
  49447. const float x, const float y,
  49448. const float w, const float h,
  49449. const float cs,
  49450. const bool curveTopLeft, const bool curveTopRight,
  49451. const bool curveBottomLeft, const bool curveBottomRight) throw()
  49452. {
  49453. const float cs2 = 2.0f * cs;
  49454. if (curveTopLeft)
  49455. {
  49456. p.startNewSubPath (x, y + cs);
  49457. p.addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f);
  49458. }
  49459. else
  49460. {
  49461. p.startNewSubPath (x, y);
  49462. }
  49463. if (curveTopRight)
  49464. {
  49465. p.lineTo (x + w - cs, y);
  49466. p.addArc (x + w - cs2, y, cs2, cs2, 0.0f, float_Pi * 0.5f);
  49467. }
  49468. else
  49469. {
  49470. p.lineTo (x + w, y);
  49471. }
  49472. if (curveBottomRight)
  49473. {
  49474. p.lineTo (x + w, y + h - cs);
  49475. p.addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  49476. }
  49477. else
  49478. {
  49479. p.lineTo (x + w, y + h);
  49480. }
  49481. if (curveBottomLeft)
  49482. {
  49483. p.lineTo (x + cs, y + h);
  49484. p.addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  49485. }
  49486. else
  49487. {
  49488. p.lineTo (x, y + h);
  49489. }
  49490. p.closeSubPath();
  49491. }
  49492. void LookAndFeel::drawShinyButtonShape (Graphics& g,
  49493. float x, float y, float w, float h,
  49494. float maxCornerSize,
  49495. const Colour& baseColour,
  49496. const float strokeWidth,
  49497. const bool flatOnLeft,
  49498. const bool flatOnRight,
  49499. const bool flatOnTop,
  49500. const bool flatOnBottom) throw()
  49501. {
  49502. if (w <= strokeWidth * 1.1f || h <= strokeWidth * 1.1f)
  49503. return;
  49504. const float cs = jmin (maxCornerSize, w * 0.5f, h * 0.5f);
  49505. Path outline;
  49506. createRoundedPath (outline, x, y, w, h, cs,
  49507. ! (flatOnLeft || flatOnTop),
  49508. ! (flatOnRight || flatOnTop),
  49509. ! (flatOnLeft || flatOnBottom),
  49510. ! (flatOnRight || flatOnBottom));
  49511. ColourGradient cg (baseColour, 0.0f, y,
  49512. baseColour.overlaidWith (Colour (0x070000ff)), 0.0f, y + h,
  49513. false);
  49514. cg.addColour (0.5, baseColour.overlaidWith (Colour (0x33ffffff)));
  49515. cg.addColour (0.51, baseColour.overlaidWith (Colour (0x110000ff)));
  49516. GradientBrush gb (cg);
  49517. g.setBrush (&gb);
  49518. g.fillPath (outline);
  49519. g.setColour (Colour (0x80000000));
  49520. g.strokePath (outline, PathStrokeType (strokeWidth));
  49521. }
  49522. void LookAndFeel::drawGlassSphere (Graphics& g,
  49523. const float x, const float y,
  49524. const float diameter,
  49525. const Colour& colour,
  49526. const float outlineThickness) throw()
  49527. {
  49528. if (diameter <= outlineThickness)
  49529. return;
  49530. Path p;
  49531. p.addEllipse (x, y, diameter, diameter);
  49532. {
  49533. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  49534. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  49535. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  49536. GradientBrush gb (cg);
  49537. g.setBrush (&gb);
  49538. g.fillPath (p);
  49539. }
  49540. {
  49541. GradientBrush gb (Colours::white, 0, y + diameter * 0.06f,
  49542. Colours::transparentWhite, 0, y + diameter * 0.3f, false);
  49543. g.setBrush (&gb);
  49544. g.fillEllipse (x + diameter * 0.2f, y + diameter * 0.05f, diameter * 0.6f, diameter * 0.4f);
  49545. }
  49546. {
  49547. ColourGradient cg (Colours::transparentBlack,
  49548. x + diameter * 0.5f, y + diameter * 0.5f,
  49549. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  49550. x, y + diameter * 0.5f, true);
  49551. cg.addColour (0.7, Colours::transparentBlack);
  49552. cg.addColour (0.8, Colours::black.withAlpha (0.1f * outlineThickness));
  49553. GradientBrush gb (cg);
  49554. g.setBrush (&gb);
  49555. g.fillPath (p);
  49556. }
  49557. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  49558. g.drawEllipse (x, y, diameter, diameter, outlineThickness);
  49559. }
  49560. void LookAndFeel::drawGlassPointer (Graphics& g,
  49561. const float x, const float y,
  49562. const float diameter,
  49563. const Colour& colour, const float outlineThickness,
  49564. const int direction) throw()
  49565. {
  49566. if (diameter <= outlineThickness)
  49567. return;
  49568. Path p;
  49569. p.startNewSubPath (x + diameter * 0.5f, y);
  49570. p.lineTo (x + diameter, y + diameter * 0.6f);
  49571. p.lineTo (x + diameter, y + diameter);
  49572. p.lineTo (x, y + diameter);
  49573. p.lineTo (x, y + diameter * 0.6f);
  49574. p.closeSubPath();
  49575. p.applyTransform (AffineTransform::rotation (direction * (float_Pi * 0.5f), x + diameter * 0.5f, y + diameter * 0.5f));
  49576. {
  49577. ColourGradient cg (Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y,
  49578. Colours::white.overlaidWith (colour.withMultipliedAlpha (0.3f)), 0, y + diameter, false);
  49579. cg.addColour (0.4, Colours::white.overlaidWith (colour));
  49580. GradientBrush gb (cg);
  49581. g.setBrush (&gb);
  49582. g.fillPath (p);
  49583. }
  49584. {
  49585. ColourGradient cg (Colours::transparentBlack,
  49586. x + diameter * 0.5f, y + diameter * 0.5f,
  49587. Colours::black.withAlpha (0.5f * outlineThickness * colour.getFloatAlpha()),
  49588. x - diameter * 0.2f, y + diameter * 0.5f, true);
  49589. cg.addColour (0.5, Colours::transparentBlack);
  49590. cg.addColour (0.7, Colours::black.withAlpha (0.07f * outlineThickness));
  49591. GradientBrush gb (cg);
  49592. g.setBrush (&gb);
  49593. g.fillPath (p);
  49594. }
  49595. g.setColour (Colours::black.withAlpha (0.5f * colour.getFloatAlpha()));
  49596. g.strokePath (p, PathStrokeType (outlineThickness));
  49597. }
  49598. void LookAndFeel::drawGlassLozenge (Graphics& g,
  49599. const float x, const float y,
  49600. const float width, const float height,
  49601. const Colour& colour,
  49602. const float outlineThickness,
  49603. const float cornerSize,
  49604. const bool flatOnLeft,
  49605. const bool flatOnRight,
  49606. const bool flatOnTop,
  49607. const bool flatOnBottom) throw()
  49608. {
  49609. if (width <= outlineThickness || height <= outlineThickness)
  49610. return;
  49611. const int intX = (int) x;
  49612. const int intY = (int) y;
  49613. const int intW = (int) width;
  49614. const int intH = (int) height;
  49615. const float cs = cornerSize < 0 ? jmin (width * 0.5f, height * 0.5f) : cornerSize;
  49616. const float edgeBlurRadius = height * 0.75f + (height - cs * 2.0f);
  49617. const int intEdge = (int) edgeBlurRadius;
  49618. Path outline;
  49619. createRoundedPath (outline, x, y, width, height, cs,
  49620. ! (flatOnLeft || flatOnTop),
  49621. ! (flatOnRight || flatOnTop),
  49622. ! (flatOnLeft || flatOnBottom),
  49623. ! (flatOnRight || flatOnBottom));
  49624. {
  49625. ColourGradient cg (colour.darker (0.2f), 0, y,
  49626. colour.darker (0.2f), 0, y + height, false);
  49627. cg.addColour (0.03, colour.withMultipliedAlpha (0.3f));
  49628. cg.addColour (0.4, colour);
  49629. cg.addColour (0.97, colour.withMultipliedAlpha (0.3f));
  49630. GradientBrush gb (cg);
  49631. g.setBrush (&gb);
  49632. g.fillPath (outline);
  49633. }
  49634. ColourGradient cg (Colours::transparentBlack, x + edgeBlurRadius, y + height * 0.5f,
  49635. colour.darker (0.2f), x, y + height * 0.5f, true);
  49636. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.5f) / edgeBlurRadius), Colours::transparentBlack);
  49637. cg.addColour (jlimit (0.0, 1.0, 1.0 - (cs * 0.25f) / edgeBlurRadius), colour.darker (0.2f).withMultipliedAlpha (0.3f));
  49638. if (! (flatOnLeft || flatOnTop || flatOnBottom))
  49639. {
  49640. GradientBrush gb (cg);
  49641. g.saveState();
  49642. g.setBrush (&gb);
  49643. g.reduceClipRegion (intX, intY, intEdge, intH);
  49644. g.fillPath (outline);
  49645. g.restoreState();
  49646. }
  49647. if (! (flatOnRight || flatOnTop || flatOnBottom))
  49648. {
  49649. cg.x1 = x + width - edgeBlurRadius;
  49650. cg.x2 = x + width;
  49651. GradientBrush gb (cg);
  49652. g.saveState();
  49653. g.setBrush (&gb);
  49654. g.reduceClipRegion (intX + intW - intEdge, intY, 2 + intEdge, intH);
  49655. g.fillPath (outline);
  49656. g.restoreState();
  49657. }
  49658. {
  49659. const float leftIndent = flatOnLeft ? 0.0f : cs * 0.4f;
  49660. const float rightIndent = flatOnRight ? 0.0f : cs * 0.4f;
  49661. Path highlight;
  49662. createRoundedPath (highlight,
  49663. x + leftIndent,
  49664. y + cs * 0.1f,
  49665. width - (leftIndent + rightIndent),
  49666. height * 0.4f, cs * 0.4f,
  49667. ! (flatOnLeft || flatOnTop),
  49668. ! (flatOnRight || flatOnTop),
  49669. ! (flatOnLeft || flatOnBottom),
  49670. ! (flatOnRight || flatOnBottom));
  49671. GradientBrush gb (colour.brighter (10.0f), 0, y + height * 0.06f,
  49672. Colours::transparentWhite, 0, y + height * 0.4f, false);
  49673. g.setBrush (&gb);
  49674. g.fillPath (highlight);
  49675. }
  49676. g.setColour (colour.darker().withMultipliedAlpha (1.5f));
  49677. g.strokePath (outline, PathStrokeType (outlineThickness));
  49678. }
  49679. END_JUCE_NAMESPACE
  49680. /********* End of inlined file: juce_LookAndFeel.cpp *********/
  49681. /********* Start of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  49682. BEGIN_JUCE_NAMESPACE
  49683. OldSchoolLookAndFeel::OldSchoolLookAndFeel()
  49684. {
  49685. setColour (TextButton::buttonColourId, Colour (0xffbbbbff));
  49686. setColour (ListBox::outlineColourId, findColour (ComboBox::outlineColourId));
  49687. setColour (ScrollBar::thumbColourId, Colour (0xffbbbbdd));
  49688. setColour (ScrollBar::backgroundColourId, Colours::transparentBlack);
  49689. setColour (Slider::thumbColourId, Colours::white);
  49690. setColour (Slider::trackColourId, Colour (0x7f000000));
  49691. setColour (Slider::textBoxOutlineColourId, Colours::grey);
  49692. setColour (ProgressBar::backgroundColourId, Colours::white.withAlpha (0.6f));
  49693. setColour (ProgressBar::foregroundColourId, Colours::green.withAlpha (0.7f));
  49694. setColour (PopupMenu::backgroundColourId, Colour (0xffeef5f8));
  49695. setColour (PopupMenu::highlightedBackgroundColourId, Colour (0xbfa4c2ce));
  49696. setColour (PopupMenu::highlightedTextColourId, Colours::black);
  49697. setColour (TextEditor::focusedOutlineColourId, findColour (TextButton::buttonColourId));
  49698. scrollbarShadow.setShadowProperties (2.2f, 0.5f, 0, 0);
  49699. }
  49700. OldSchoolLookAndFeel::~OldSchoolLookAndFeel()
  49701. {
  49702. }
  49703. void OldSchoolLookAndFeel::drawButtonBackground (Graphics& g,
  49704. Button& button,
  49705. const Colour& backgroundColour,
  49706. bool isMouseOverButton,
  49707. bool isButtonDown)
  49708. {
  49709. const int width = button.getWidth();
  49710. const int height = button.getHeight();
  49711. const float indent = 2.0f;
  49712. const int cornerSize = jmin (roundFloatToInt (width * 0.4f),
  49713. roundFloatToInt (height * 0.4f));
  49714. Path p;
  49715. p.addRoundedRectangle (indent, indent,
  49716. width - indent * 2.0f,
  49717. height - indent * 2.0f,
  49718. (float) cornerSize);
  49719. Colour bc (backgroundColour.withMultipliedSaturation (0.3f));
  49720. if (isMouseOverButton)
  49721. {
  49722. if (isButtonDown)
  49723. bc = bc.brighter();
  49724. else if (bc.getBrightness() > 0.5f)
  49725. bc = bc.darker (0.1f);
  49726. else
  49727. bc = bc.brighter (0.1f);
  49728. }
  49729. g.setColour (bc);
  49730. g.fillPath (p);
  49731. g.setColour (bc.contrasting().withAlpha ((isMouseOverButton) ? 0.6f : 0.4f));
  49732. g.strokePath (p, PathStrokeType ((isMouseOverButton) ? 2.0f : 1.4f));
  49733. }
  49734. void OldSchoolLookAndFeel::drawTickBox (Graphics& g,
  49735. Component& /*component*/,
  49736. int x, int y, int w, int h,
  49737. const bool ticked,
  49738. const bool isEnabled,
  49739. const bool /*isMouseOverButton*/,
  49740. const bool isButtonDown)
  49741. {
  49742. Path box;
  49743. box.addRoundedRectangle (0.0f, 2.0f, 6.0f, 6.0f, 1.0f);
  49744. g.setColour (isEnabled ? Colours::blue.withAlpha (isButtonDown ? 0.3f : 0.1f)
  49745. : Colours::lightgrey.withAlpha (0.1f));
  49746. AffineTransform trans (AffineTransform::scale (w / 9.0f, h / 9.0f)
  49747. .translated ((float) x, (float) y));
  49748. g.fillPath (box, trans);
  49749. g.setColour (Colours::black.withAlpha (0.6f));
  49750. g.strokePath (box, PathStrokeType (0.9f), trans);
  49751. if (ticked)
  49752. {
  49753. Path tick;
  49754. tick.startNewSubPath (1.5f, 3.0f);
  49755. tick.lineTo (3.0f, 6.0f);
  49756. tick.lineTo (6.0f, 0.0f);
  49757. g.setColour (isEnabled ? Colours::black : Colours::grey);
  49758. g.strokePath (tick, PathStrokeType (2.5f), trans);
  49759. }
  49760. }
  49761. void OldSchoolLookAndFeel::drawToggleButton (Graphics& g,
  49762. ToggleButton& button,
  49763. bool isMouseOverButton,
  49764. bool isButtonDown)
  49765. {
  49766. if (button.hasKeyboardFocus (true))
  49767. {
  49768. g.setColour (button.findColour (TextEditor::focusedOutlineColourId));
  49769. g.drawRect (0, 0, button.getWidth(), button.getHeight());
  49770. }
  49771. const int tickWidth = jmin (20, button.getHeight() - 4);
  49772. drawTickBox (g, button, 4, (button.getHeight() - tickWidth) / 2,
  49773. tickWidth, tickWidth,
  49774. button.getToggleState(),
  49775. button.isEnabled(),
  49776. isMouseOverButton,
  49777. isButtonDown);
  49778. g.setColour (button.findColour (ToggleButton::textColourId));
  49779. g.setFont (jmin (15.0f, button.getHeight() * 0.6f));
  49780. if (! button.isEnabled())
  49781. g.setOpacity (0.5f);
  49782. const int textX = tickWidth + 5;
  49783. g.drawFittedText (button.getButtonText(),
  49784. textX, 4,
  49785. button.getWidth() - textX - 2, button.getHeight() - 8,
  49786. Justification::centredLeft, 10);
  49787. }
  49788. void OldSchoolLookAndFeel::drawProgressBar (Graphics& g, ProgressBar& progressBar,
  49789. int width, int height,
  49790. double progress, const String& textToShow)
  49791. {
  49792. if (progress < 0 || progress >= 1.0)
  49793. {
  49794. LookAndFeel::drawProgressBar (g, progressBar, width, height, progress, textToShow);
  49795. }
  49796. else
  49797. {
  49798. const Colour background (progressBar.findColour (ProgressBar::backgroundColourId));
  49799. const Colour foreground (progressBar.findColour (ProgressBar::foregroundColourId));
  49800. g.fillAll (background);
  49801. g.setColour (foreground);
  49802. g.fillRect (1, 1,
  49803. jlimit (0, width - 2, roundDoubleToInt (progress * (width - 2))),
  49804. height - 2);
  49805. if (textToShow.isNotEmpty())
  49806. {
  49807. g.setColour (Colour::contrasting (background, foreground));
  49808. g.setFont (height * 0.6f);
  49809. g.drawText (textToShow, 0, 0, width, height, Justification::centred, false);
  49810. }
  49811. }
  49812. }
  49813. void OldSchoolLookAndFeel::drawScrollbarButton (Graphics& g,
  49814. ScrollBar& bar,
  49815. int width, int height,
  49816. int buttonDirection,
  49817. bool isScrollbarVertical,
  49818. bool isMouseOverButton,
  49819. bool isButtonDown)
  49820. {
  49821. if (isScrollbarVertical)
  49822. width -= 2;
  49823. else
  49824. height -= 2;
  49825. Path p;
  49826. if (buttonDirection == 0)
  49827. p.addTriangle (width * 0.5f, height * 0.2f,
  49828. width * 0.1f, height * 0.7f,
  49829. width * 0.9f, height * 0.7f);
  49830. else if (buttonDirection == 1)
  49831. p.addTriangle (width * 0.8f, height * 0.5f,
  49832. width * 0.3f, height * 0.1f,
  49833. width * 0.3f, height * 0.9f);
  49834. else if (buttonDirection == 2)
  49835. p.addTriangle (width * 0.5f, height * 0.8f,
  49836. width * 0.1f, height * 0.3f,
  49837. width * 0.9f, height * 0.3f);
  49838. else if (buttonDirection == 3)
  49839. p.addTriangle (width * 0.2f, height * 0.5f,
  49840. width * 0.7f, height * 0.1f,
  49841. width * 0.7f, height * 0.9f);
  49842. if (isButtonDown)
  49843. g.setColour (Colours::white);
  49844. else if (isMouseOverButton)
  49845. g.setColour (Colours::white.withAlpha (0.7f));
  49846. else
  49847. g.setColour (bar.findColour (ScrollBar::thumbColourId).withAlpha (0.5f));
  49848. g.fillPath (p);
  49849. g.setColour (Colours::black.withAlpha (0.5f));
  49850. g.strokePath (p, PathStrokeType (0.5f));
  49851. }
  49852. void OldSchoolLookAndFeel::drawScrollbar (Graphics& g,
  49853. ScrollBar& bar,
  49854. int x, int y,
  49855. int width, int height,
  49856. bool isScrollbarVertical,
  49857. int thumbStartPosition,
  49858. int thumbSize,
  49859. bool isMouseOver,
  49860. bool isMouseDown)
  49861. {
  49862. g.fillAll (bar.findColour (ScrollBar::backgroundColourId));
  49863. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  49864. .withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.15f));
  49865. if (thumbSize > 0.0f)
  49866. {
  49867. Rectangle thumb;
  49868. if (isScrollbarVertical)
  49869. {
  49870. width -= 2;
  49871. g.fillRect (x + roundFloatToInt (width * 0.35f), y,
  49872. roundFloatToInt (width * 0.3f), height);
  49873. thumb.setBounds (x + 1, thumbStartPosition,
  49874. width - 2, thumbSize);
  49875. }
  49876. else
  49877. {
  49878. height -= 2;
  49879. g.fillRect (x, y + roundFloatToInt (height * 0.35f),
  49880. width, roundFloatToInt (height * 0.3f));
  49881. thumb.setBounds (thumbStartPosition, y + 1,
  49882. thumbSize, height - 2);
  49883. }
  49884. g.setColour (bar.findColour (ScrollBar::thumbColourId)
  49885. .withAlpha ((isMouseOver || isMouseDown) ? 0.95f : 0.7f));
  49886. g.fillRect (thumb);
  49887. g.setColour (Colours::black.withAlpha ((isMouseOver || isMouseDown) ? 0.4f : 0.25f));
  49888. g.drawRect (thumb.getX(), thumb.getY(), thumb.getWidth(), thumb.getHeight());
  49889. if (thumbSize > 16)
  49890. {
  49891. for (int i = 3; --i >= 0;)
  49892. {
  49893. const float linePos = thumbStartPosition + thumbSize / 2 + (i - 1) * 4.0f;
  49894. g.setColour (Colours::black.withAlpha (0.15f));
  49895. if (isScrollbarVertical)
  49896. {
  49897. g.drawLine (x + width * 0.2f, linePos, width * 0.8f, linePos);
  49898. g.setColour (Colours::white.withAlpha (0.15f));
  49899. g.drawLine (width * 0.2f, linePos - 1, width * 0.8f, linePos - 1);
  49900. }
  49901. else
  49902. {
  49903. g.drawLine (linePos, height * 0.2f, linePos, height * 0.8f);
  49904. g.setColour (Colours::white.withAlpha (0.15f));
  49905. g.drawLine (linePos - 1, height * 0.2f, linePos - 1, height * 0.8f);
  49906. }
  49907. }
  49908. }
  49909. }
  49910. }
  49911. ImageEffectFilter* OldSchoolLookAndFeel::getScrollbarEffect()
  49912. {
  49913. return &scrollbarShadow;
  49914. }
  49915. void OldSchoolLookAndFeel::drawPopupMenuBackground (Graphics& g, int width, int height)
  49916. {
  49917. g.fillAll (findColour (PopupMenu::backgroundColourId));
  49918. g.setColour (Colours::black.withAlpha (0.6f));
  49919. g.drawRect (0, 0, width, height);
  49920. }
  49921. void OldSchoolLookAndFeel::drawMenuBarBackground (Graphics& g, int /*width*/, int /*height*/,
  49922. bool, MenuBarComponent& menuBar)
  49923. {
  49924. g.fillAll (menuBar.findColour (PopupMenu::backgroundColourId));
  49925. }
  49926. void OldSchoolLookAndFeel::drawTextEditorOutline (Graphics& g, int width, int height, TextEditor& textEditor)
  49927. {
  49928. if (textEditor.isEnabled())
  49929. {
  49930. g.setColour (textEditor.findColour (TextEditor::outlineColourId));
  49931. g.drawRect (0, 0, width, height);
  49932. }
  49933. }
  49934. void OldSchoolLookAndFeel::drawComboBox (Graphics& g, int width, int height,
  49935. const bool isButtonDown,
  49936. int buttonX, int buttonY,
  49937. int buttonW, int buttonH,
  49938. ComboBox& box)
  49939. {
  49940. g.fillAll (box.findColour (ComboBox::backgroundColourId));
  49941. g.setColour (box.findColour ((isButtonDown) ? ComboBox::buttonColourId
  49942. : ComboBox::backgroundColourId));
  49943. g.fillRect (buttonX, buttonY, buttonW, buttonH);
  49944. g.setColour (box.findColour (ComboBox::outlineColourId));
  49945. g.drawRect (0, 0, width, height);
  49946. const float arrowX = 0.2f;
  49947. const float arrowH = 0.3f;
  49948. if (box.isEnabled())
  49949. {
  49950. Path p;
  49951. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.45f - arrowH),
  49952. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.45f,
  49953. buttonX + buttonW * arrowX, buttonY + buttonH * 0.45f);
  49954. p.addTriangle (buttonX + buttonW * 0.5f, buttonY + buttonH * (0.55f + arrowH),
  49955. buttonX + buttonW * (1.0f - arrowX), buttonY + buttonH * 0.55f,
  49956. buttonX + buttonW * arrowX, buttonY + buttonH * 0.55f);
  49957. g.setColour (box.findColour ((isButtonDown) ? ComboBox::backgroundColourId
  49958. : ComboBox::buttonColourId));
  49959. g.fillPath (p);
  49960. }
  49961. }
  49962. const Font OldSchoolLookAndFeel::getComboBoxFont (ComboBox& box)
  49963. {
  49964. Font f (jmin (15.0f, box.getHeight() * 0.85f));
  49965. f.setHorizontalScale (0.9f);
  49966. return f;
  49967. }
  49968. static void drawTriangle (Graphics& g, float x1, float y1, float x2, float y2, float x3, float y3, const Colour& fill, const Colour& outline) throw()
  49969. {
  49970. Path p;
  49971. p.addTriangle (x1, y1, x2, y2, x3, y3);
  49972. g.setColour (fill);
  49973. g.fillPath (p);
  49974. g.setColour (outline);
  49975. g.strokePath (p, PathStrokeType (0.3f));
  49976. }
  49977. void OldSchoolLookAndFeel::drawLinearSlider (Graphics& g,
  49978. int x, int y,
  49979. int w, int h,
  49980. float sliderPos,
  49981. float minSliderPos,
  49982. float maxSliderPos,
  49983. const Slider::SliderStyle style,
  49984. Slider& slider)
  49985. {
  49986. g.fillAll (slider.findColour (Slider::backgroundColourId));
  49987. if (style == Slider::LinearBar)
  49988. {
  49989. g.setColour (slider.findColour (Slider::thumbColourId));
  49990. g.fillRect (x, y, (int) sliderPos - x, h);
  49991. g.setColour (slider.findColour (Slider::textBoxTextColourId).withMultipliedAlpha (0.5f));
  49992. g.drawRect (x, y, (int) sliderPos - x, h);
  49993. }
  49994. else
  49995. {
  49996. g.setColour (slider.findColour (Slider::trackColourId)
  49997. .withMultipliedAlpha (slider.isEnabled() ? 1.0f : 0.3f));
  49998. if (slider.isHorizontal())
  49999. {
  50000. g.fillRect (x, y + roundFloatToInt (h * 0.6f),
  50001. w, roundFloatToInt (h * 0.2f));
  50002. }
  50003. else
  50004. {
  50005. g.fillRect (x + roundFloatToInt (w * 0.5f - jmin (3.0f, w * 0.1f)), y,
  50006. jmin (4, roundFloatToInt (w * 0.2f)), h);
  50007. }
  50008. float alpha = 0.35f;
  50009. if (slider.isEnabled())
  50010. alpha = slider.isMouseOverOrDragging() ? 1.0f : 0.7f;
  50011. const Colour fill (slider.findColour (Slider::thumbColourId).withAlpha (alpha));
  50012. const Colour outline (Colours::black.withAlpha (slider.isEnabled() ? 0.7f : 0.35f));
  50013. if (style == Slider::TwoValueVertical || style == Slider::ThreeValueVertical)
  50014. {
  50015. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), minSliderPos,
  50016. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos - 7.0f,
  50017. x + w * 0.5f - jmin (8.0f, w * 0.4f), minSliderPos,
  50018. fill, outline);
  50019. drawTriangle (g, x + w * 0.5f + jmin (4.0f, w * 0.3f), maxSliderPos,
  50020. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos,
  50021. x + w * 0.5f - jmin (8.0f, w * 0.4f), maxSliderPos + 7.0f,
  50022. fill, outline);
  50023. }
  50024. else if (style == Slider::TwoValueHorizontal || style == Slider::ThreeValueHorizontal)
  50025. {
  50026. drawTriangle (g, minSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  50027. minSliderPos - 7.0f, y + h * 0.9f ,
  50028. minSliderPos, y + h * 0.9f,
  50029. fill, outline);
  50030. drawTriangle (g, maxSliderPos, y + h * 0.6f - jmin (4.0f, h * 0.3f),
  50031. maxSliderPos, y + h * 0.9f,
  50032. maxSliderPos + 7.0f, y + h * 0.9f,
  50033. fill, outline);
  50034. }
  50035. if (style == Slider::LinearHorizontal || style == Slider::ThreeValueHorizontal)
  50036. {
  50037. drawTriangle (g, sliderPos, y + h * 0.9f,
  50038. sliderPos - 7.0f, y + h * 0.2f,
  50039. sliderPos + 7.0f, y + h * 0.2f,
  50040. fill, outline);
  50041. }
  50042. else if (style == Slider::LinearVertical || style == Slider::ThreeValueVertical)
  50043. {
  50044. drawTriangle (g, x + w * 0.5f - jmin (4.0f, w * 0.3f), sliderPos,
  50045. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos - 7.0f,
  50046. x + w * 0.5f + jmin (8.0f, w * 0.4f), sliderPos + 7.0f,
  50047. fill, outline);
  50048. }
  50049. }
  50050. }
  50051. Button* OldSchoolLookAndFeel::createSliderButton (const bool isIncrement)
  50052. {
  50053. if (isIncrement)
  50054. return new ArrowButton ("u", 0.75f, Colours::white.withAlpha (0.8f));
  50055. else
  50056. return new ArrowButton ("d", 0.25f, Colours::white.withAlpha (0.8f));
  50057. }
  50058. ImageEffectFilter* OldSchoolLookAndFeel::getSliderEffect()
  50059. {
  50060. return &scrollbarShadow;
  50061. }
  50062. int OldSchoolLookAndFeel::getSliderThumbRadius (Slider&)
  50063. {
  50064. return 8;
  50065. }
  50066. void OldSchoolLookAndFeel::drawCornerResizer (Graphics& g,
  50067. int w, int h,
  50068. bool isMouseOver,
  50069. bool isMouseDragging)
  50070. {
  50071. g.setColour ((isMouseOver || isMouseDragging) ? Colours::lightgrey
  50072. : Colours::darkgrey);
  50073. const float lineThickness = jmin (w, h) * 0.1f;
  50074. for (float i = 0.0f; i < 1.0f; i += 0.3f)
  50075. {
  50076. g.drawLine (w * i,
  50077. h + 1.0f,
  50078. w + 1.0f,
  50079. h * i,
  50080. lineThickness);
  50081. }
  50082. }
  50083. Button* OldSchoolLookAndFeel::createDocumentWindowButton (int buttonType)
  50084. {
  50085. Path shape;
  50086. if (buttonType == DocumentWindow::closeButton)
  50087. {
  50088. shape.addLineSegment (0.0f, 0.0f, 1.0f, 1.0f, 0.35f);
  50089. shape.addLineSegment (1.0f, 0.0f, 0.0f, 1.0f, 0.35f);
  50090. ShapeButton* const b = new ShapeButton ("close",
  50091. Colour (0x7fff3333),
  50092. Colour (0xd7ff3333),
  50093. Colour (0xf7ff3333));
  50094. b->setShape (shape, true, true, true);
  50095. return b;
  50096. }
  50097. else if (buttonType == DocumentWindow::minimiseButton)
  50098. {
  50099. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  50100. DrawableButton* b = new DrawableButton ("minimise", DrawableButton::ImageFitted);
  50101. DrawablePath dp;
  50102. dp.setPath (shape);
  50103. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  50104. b->setImages (&dp);
  50105. return b;
  50106. }
  50107. else if (buttonType == DocumentWindow::maximiseButton)
  50108. {
  50109. shape.addLineSegment (0.5f, 0.0f, 0.5f, 1.0f, 0.25f);
  50110. shape.addLineSegment (0.0f, 0.5f, 1.0f, 0.5f, 0.25f);
  50111. DrawableButton* b = new DrawableButton ("maximise", DrawableButton::ImageFitted);
  50112. DrawablePath dp;
  50113. dp.setPath (shape);
  50114. dp.setSolidFill (Colours::black.withAlpha (0.3f));
  50115. b->setImages (&dp);
  50116. return b;
  50117. }
  50118. jassertfalse
  50119. return 0;
  50120. }
  50121. void OldSchoolLookAndFeel::positionDocumentWindowButtons (DocumentWindow&,
  50122. int titleBarX,
  50123. int titleBarY,
  50124. int titleBarW,
  50125. int titleBarH,
  50126. Button* minimiseButton,
  50127. Button* maximiseButton,
  50128. Button* closeButton,
  50129. bool positionTitleBarButtonsOnLeft)
  50130. {
  50131. titleBarY += titleBarH / 8;
  50132. titleBarH -= titleBarH / 4;
  50133. const int buttonW = titleBarH;
  50134. int x = positionTitleBarButtonsOnLeft ? titleBarX + 4
  50135. : titleBarX + titleBarW - buttonW - 4;
  50136. if (closeButton != 0)
  50137. {
  50138. closeButton->setBounds (x, titleBarY, buttonW, titleBarH);
  50139. x += positionTitleBarButtonsOnLeft ? buttonW + buttonW / 5
  50140. : -(buttonW + buttonW / 5);
  50141. }
  50142. if (positionTitleBarButtonsOnLeft)
  50143. swapVariables (minimiseButton, maximiseButton);
  50144. if (maximiseButton != 0)
  50145. {
  50146. maximiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  50147. x += positionTitleBarButtonsOnLeft ? buttonW : -buttonW;
  50148. }
  50149. if (minimiseButton != 0)
  50150. minimiseButton->setBounds (x, titleBarY - 2, buttonW, titleBarH);
  50151. }
  50152. END_JUCE_NAMESPACE
  50153. /********* End of inlined file: juce_OldSchoolLookAndFeel.cpp *********/
  50154. /********* Start of inlined file: juce_MenuBarComponent.cpp *********/
  50155. BEGIN_JUCE_NAMESPACE
  50156. class DummyMenuComponent : public Component
  50157. {
  50158. DummyMenuComponent (const DummyMenuComponent&);
  50159. const DummyMenuComponent& operator= (const DummyMenuComponent&);
  50160. public:
  50161. DummyMenuComponent() {}
  50162. ~DummyMenuComponent() {}
  50163. void inputAttemptWhenModal()
  50164. {
  50165. exitModalState (0);
  50166. }
  50167. };
  50168. MenuBarComponent::MenuBarComponent (MenuBarModel* model_)
  50169. : model (0),
  50170. itemUnderMouse (-1),
  50171. currentPopupIndex (-1),
  50172. indexToShowAgain (-1),
  50173. lastMouseX (0),
  50174. lastMouseY (0),
  50175. inModalState (false),
  50176. currentPopup (0)
  50177. {
  50178. setRepaintsOnMouseActivity (true);
  50179. setWantsKeyboardFocus (false);
  50180. setMouseClickGrabsKeyboardFocus (false);
  50181. setModel (model_);
  50182. }
  50183. MenuBarComponent::~MenuBarComponent()
  50184. {
  50185. setModel (0);
  50186. Desktop::getInstance().removeGlobalMouseListener (this);
  50187. deleteAndZero (currentPopup);
  50188. }
  50189. void MenuBarComponent::setModel (MenuBarModel* const newModel)
  50190. {
  50191. if (model != newModel)
  50192. {
  50193. if (model != 0)
  50194. model->removeListener (this);
  50195. model = newModel;
  50196. if (model != 0)
  50197. model->addListener (this);
  50198. repaint();
  50199. menuBarItemsChanged (0);
  50200. }
  50201. }
  50202. void MenuBarComponent::paint (Graphics& g)
  50203. {
  50204. const bool isMouseOverBar = currentPopupIndex >= 0 || itemUnderMouse >= 0 || isMouseOver();
  50205. getLookAndFeel().drawMenuBarBackground (g,
  50206. getWidth(),
  50207. getHeight(),
  50208. isMouseOverBar,
  50209. *this);
  50210. if (model != 0)
  50211. {
  50212. for (int i = 0; i < menuNames.size(); ++i)
  50213. {
  50214. g.saveState();
  50215. g.setOrigin (xPositions [i], 0);
  50216. g.reduceClipRegion (0, 0, xPositions[i + 1] - xPositions[i], getHeight());
  50217. getLookAndFeel().drawMenuBarItem (g,
  50218. xPositions[i + 1] - xPositions[i],
  50219. getHeight(),
  50220. i,
  50221. menuNames[i],
  50222. i == itemUnderMouse,
  50223. i == currentPopupIndex,
  50224. isMouseOverBar,
  50225. *this);
  50226. g.restoreState();
  50227. }
  50228. }
  50229. }
  50230. void MenuBarComponent::resized()
  50231. {
  50232. xPositions.clear();
  50233. int x = 2;
  50234. xPositions.add (x);
  50235. for (int i = 0; i < menuNames.size(); ++i)
  50236. {
  50237. x += getLookAndFeel().getMenuBarItemWidth (*this, i, menuNames[i]);
  50238. xPositions.add (x);
  50239. }
  50240. }
  50241. int MenuBarComponent::getItemAt (const int x, const int y)
  50242. {
  50243. for (int i = 0; i < xPositions.size(); ++i)
  50244. if (x >= xPositions[i] && x < xPositions[i + 1])
  50245. return reallyContains (x, y, true) ? i : -1;
  50246. return -1;
  50247. }
  50248. void MenuBarComponent::repaintMenuItem (int index)
  50249. {
  50250. if (((unsigned int) index) < (unsigned int) xPositions.size())
  50251. {
  50252. const int x1 = xPositions [index];
  50253. const int x2 = xPositions [index + 1];
  50254. repaint (x1 - 2, 0, x2 - x1 + 4, getHeight());
  50255. }
  50256. }
  50257. void MenuBarComponent::updateItemUnderMouse (int x, int y)
  50258. {
  50259. const int newItem = getItemAt (x, y);
  50260. if (itemUnderMouse != newItem)
  50261. {
  50262. repaintMenuItem (itemUnderMouse);
  50263. itemUnderMouse = newItem;
  50264. repaintMenuItem (itemUnderMouse);
  50265. }
  50266. }
  50267. void MenuBarComponent::hideCurrentMenu()
  50268. {
  50269. deleteAndZero (currentPopup);
  50270. repaint();
  50271. }
  50272. void MenuBarComponent::showMenu (int index)
  50273. {
  50274. if (index != currentPopupIndex)
  50275. {
  50276. if (inModalState)
  50277. {
  50278. hideCurrentMenu();
  50279. indexToShowAgain = index;
  50280. return;
  50281. }
  50282. indexToShowAgain = -1;
  50283. currentPopupIndex = -1;
  50284. itemUnderMouse = index;
  50285. deleteAndZero (currentPopup);
  50286. menuBarItemsChanged (0);
  50287. Component* const prevFocused = getCurrentlyFocusedComponent();
  50288. ComponentDeletionWatcher* prevCompDeletionChecker = 0;
  50289. if (prevFocused != 0)
  50290. prevCompDeletionChecker = new ComponentDeletionWatcher (prevFocused);
  50291. ComponentDeletionWatcher deletionChecker (this);
  50292. enterModalState (false);
  50293. inModalState = true;
  50294. int result = 0;
  50295. ApplicationCommandManager* managerOfChosenCommand = 0;
  50296. Desktop::getInstance().addGlobalMouseListener (this);
  50297. for (;;)
  50298. {
  50299. const int x = getScreenX() + xPositions [itemUnderMouse];
  50300. const int w = xPositions [itemUnderMouse + 1] - xPositions [itemUnderMouse];
  50301. currentPopupIndex = itemUnderMouse;
  50302. indexToShowAgain = -1;
  50303. repaint();
  50304. if (((unsigned int) itemUnderMouse) < (unsigned int) menuNames.size())
  50305. {
  50306. PopupMenu m (model->getMenuForIndex (itemUnderMouse,
  50307. menuNames [itemUnderMouse]));
  50308. currentPopup = m.createMenuComponent (x, getScreenY(),
  50309. w, getHeight(),
  50310. 0, w, 0, 0,
  50311. true, this,
  50312. &managerOfChosenCommand,
  50313. this);
  50314. }
  50315. if (currentPopup == 0)
  50316. {
  50317. currentPopup = new DummyMenuComponent();
  50318. addAndMakeVisible (currentPopup);
  50319. }
  50320. currentPopup->enterModalState (false);
  50321. currentPopup->toFront (false); // need to do this after making it modal, or it could
  50322. // be stuck behind other comps that are already modal..
  50323. result = currentPopup->runModalLoop();
  50324. if (deletionChecker.hasBeenDeleted())
  50325. {
  50326. delete prevCompDeletionChecker;
  50327. return;
  50328. }
  50329. const int lastPopupIndex = currentPopupIndex;
  50330. deleteAndZero (currentPopup);
  50331. currentPopupIndex = -1;
  50332. if (result != 0)
  50333. {
  50334. topLevelIndexClicked = lastPopupIndex;
  50335. break;
  50336. }
  50337. else if (indexToShowAgain >= 0)
  50338. {
  50339. menuBarItemsChanged (0);
  50340. repaint();
  50341. itemUnderMouse = indexToShowAgain;
  50342. if (((unsigned int) itemUnderMouse) >= (unsigned int) menuNames.size())
  50343. break;
  50344. }
  50345. else
  50346. {
  50347. break;
  50348. }
  50349. }
  50350. Desktop::getInstance().removeGlobalMouseListener (this);
  50351. inModalState = false;
  50352. exitModalState (0);
  50353. if (prevCompDeletionChecker != 0)
  50354. {
  50355. if (! prevCompDeletionChecker->hasBeenDeleted())
  50356. prevFocused->grabKeyboardFocus();
  50357. delete prevCompDeletionChecker;
  50358. }
  50359. int mx, my;
  50360. getMouseXYRelative (mx, my);
  50361. updateItemUnderMouse (mx, my);
  50362. repaint();
  50363. if (result != 0)
  50364. {
  50365. if (managerOfChosenCommand != 0)
  50366. {
  50367. ApplicationCommandTarget::InvocationInfo info (result);
  50368. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  50369. managerOfChosenCommand->invoke (info, true);
  50370. }
  50371. postCommandMessage (result);
  50372. }
  50373. }
  50374. }
  50375. void MenuBarComponent::handleCommandMessage (int commandId)
  50376. {
  50377. if (model != 0)
  50378. model->menuItemSelected (commandId, topLevelIndexClicked);
  50379. }
  50380. void MenuBarComponent::mouseEnter (const MouseEvent& e)
  50381. {
  50382. if (e.eventComponent == this)
  50383. updateItemUnderMouse (e.x, e.y);
  50384. }
  50385. void MenuBarComponent::mouseExit (const MouseEvent& e)
  50386. {
  50387. if (e.eventComponent == this)
  50388. updateItemUnderMouse (e.x, e.y);
  50389. }
  50390. void MenuBarComponent::mouseDown (const MouseEvent& e)
  50391. {
  50392. const MouseEvent e2 (e.getEventRelativeTo (this));
  50393. if (currentPopupIndex < 0)
  50394. {
  50395. updateItemUnderMouse (e2.x, e2.y);
  50396. currentPopupIndex = -2;
  50397. showMenu (itemUnderMouse);
  50398. }
  50399. }
  50400. void MenuBarComponent::mouseDrag (const MouseEvent& e)
  50401. {
  50402. const MouseEvent e2 (e.getEventRelativeTo (this));
  50403. const int item = getItemAt (e2.x, e2.y);
  50404. if (item >= 0)
  50405. showMenu (item);
  50406. }
  50407. void MenuBarComponent::mouseUp (const MouseEvent& e)
  50408. {
  50409. const MouseEvent e2 (e.getEventRelativeTo (this));
  50410. updateItemUnderMouse (e2.x, e2.y);
  50411. if (itemUnderMouse < 0 && dynamic_cast <DummyMenuComponent*> (currentPopup) != 0)
  50412. hideCurrentMenu();
  50413. }
  50414. void MenuBarComponent::mouseMove (const MouseEvent& e)
  50415. {
  50416. const MouseEvent e2 (e.getEventRelativeTo (this));
  50417. if (lastMouseX != e2.x || lastMouseY != e2.y)
  50418. {
  50419. if (currentPopupIndex >= 0)
  50420. {
  50421. const int item = getItemAt (e2.x, e2.y);
  50422. if (item >= 0)
  50423. showMenu (item);
  50424. }
  50425. else
  50426. {
  50427. updateItemUnderMouse (e2.x, e2.y);
  50428. }
  50429. lastMouseX = e2.x;
  50430. lastMouseY = e2.y;
  50431. }
  50432. }
  50433. bool MenuBarComponent::keyPressed (const KeyPress& key)
  50434. {
  50435. bool used = false;
  50436. const int numMenus = menuNames.size();
  50437. const int currentIndex = jlimit (0, menuNames.size() - 1, currentPopupIndex);
  50438. if (key.isKeyCode (KeyPress::leftKey))
  50439. {
  50440. showMenu ((currentIndex + numMenus - 1) % numMenus);
  50441. used = true;
  50442. }
  50443. else if (key.isKeyCode (KeyPress::rightKey))
  50444. {
  50445. showMenu ((currentIndex + 1) % numMenus);
  50446. used = true;
  50447. }
  50448. return used;
  50449. }
  50450. void MenuBarComponent::inputAttemptWhenModal()
  50451. {
  50452. hideCurrentMenu();
  50453. }
  50454. void MenuBarComponent::menuBarItemsChanged (MenuBarModel* /*menuBarModel*/)
  50455. {
  50456. StringArray newNames;
  50457. if (model != 0)
  50458. newNames = model->getMenuBarNames();
  50459. if (newNames != menuNames)
  50460. {
  50461. menuNames = newNames;
  50462. repaint();
  50463. resized();
  50464. }
  50465. }
  50466. void MenuBarComponent::menuCommandInvoked (MenuBarModel* /*menuBarModel*/,
  50467. const ApplicationCommandTarget::InvocationInfo& info)
  50468. {
  50469. if (model == 0
  50470. || (info.commandFlags & ApplicationCommandInfo::dontTriggerVisualFeedback) != 0)
  50471. return;
  50472. for (int i = 0; i < menuNames.size(); ++i)
  50473. {
  50474. const PopupMenu menu (model->getMenuForIndex (i, menuNames [i]));
  50475. if (menu.containsCommandItem (info.commandID))
  50476. {
  50477. itemUnderMouse = i;
  50478. repaintMenuItem (i);
  50479. startTimer (200);
  50480. break;
  50481. }
  50482. }
  50483. }
  50484. void MenuBarComponent::timerCallback()
  50485. {
  50486. stopTimer();
  50487. int mx, my;
  50488. getMouseXYRelative (mx, my);
  50489. updateItemUnderMouse (mx, my);
  50490. }
  50491. END_JUCE_NAMESPACE
  50492. /********* End of inlined file: juce_MenuBarComponent.cpp *********/
  50493. /********* Start of inlined file: juce_MenuBarModel.cpp *********/
  50494. BEGIN_JUCE_NAMESPACE
  50495. MenuBarModel::MenuBarModel() throw()
  50496. : manager (0)
  50497. {
  50498. }
  50499. MenuBarModel::~MenuBarModel()
  50500. {
  50501. setApplicationCommandManagerToWatch (0);
  50502. }
  50503. void MenuBarModel::menuItemsChanged()
  50504. {
  50505. triggerAsyncUpdate();
  50506. }
  50507. void MenuBarModel::setApplicationCommandManagerToWatch (ApplicationCommandManager* const newManager) throw()
  50508. {
  50509. if (manager != newManager)
  50510. {
  50511. if (manager != 0)
  50512. manager->removeListener (this);
  50513. manager = newManager;
  50514. if (manager != 0)
  50515. manager->addListener (this);
  50516. }
  50517. }
  50518. void MenuBarModel::addListener (MenuBarModelListener* const newListener) throw()
  50519. {
  50520. jassert (newListener != 0);
  50521. jassert (! listeners.contains (newListener)); // trying to add a listener to the list twice!
  50522. if (newListener != 0)
  50523. listeners.add (newListener);
  50524. }
  50525. void MenuBarModel::removeListener (MenuBarModelListener* const listenerToRemove) throw()
  50526. {
  50527. // Trying to remove a listener that isn't on the list!
  50528. // If this assertion happens because this object is a dangling pointer, make sure you've not
  50529. // deleted this menu model while it's still being used by something (e.g. by a MenuBarComponent)
  50530. jassert (listeners.contains (listenerToRemove));
  50531. listeners.removeValue (listenerToRemove);
  50532. }
  50533. void MenuBarModel::handleAsyncUpdate()
  50534. {
  50535. for (int i = listeners.size(); --i >= 0;)
  50536. {
  50537. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuBarItemsChanged (this);
  50538. i = jmin (i, listeners.size());
  50539. }
  50540. }
  50541. void MenuBarModel::applicationCommandInvoked (const ApplicationCommandTarget::InvocationInfo& info)
  50542. {
  50543. for (int i = listeners.size(); --i >= 0;)
  50544. {
  50545. ((MenuBarModelListener*) listeners.getUnchecked (i))->menuCommandInvoked (this, info);
  50546. i = jmin (i, listeners.size());
  50547. }
  50548. }
  50549. void MenuBarModel::applicationCommandListChanged()
  50550. {
  50551. menuItemsChanged();
  50552. }
  50553. END_JUCE_NAMESPACE
  50554. /********* End of inlined file: juce_MenuBarModel.cpp *********/
  50555. /********* Start of inlined file: juce_PopupMenu.cpp *********/
  50556. BEGIN_JUCE_NAMESPACE
  50557. static VoidArray activeMenuWindows;
  50558. class MenuItemInfo
  50559. {
  50560. public:
  50561. const int itemId;
  50562. String text;
  50563. const Colour textColour;
  50564. const bool active, isSeparator, isTicked, usesColour;
  50565. Image* image;
  50566. PopupMenuCustomComponent* const customComp;
  50567. PopupMenu* subMenu;
  50568. ApplicationCommandManager* const commandManager;
  50569. MenuItemInfo() throw()
  50570. : itemId (0),
  50571. active (true),
  50572. isSeparator (true),
  50573. isTicked (false),
  50574. usesColour (false),
  50575. image (0),
  50576. customComp (0),
  50577. subMenu (0),
  50578. commandManager (0)
  50579. {
  50580. }
  50581. MenuItemInfo (const int itemId_,
  50582. const String& text_,
  50583. const bool active_,
  50584. const bool isTicked_,
  50585. const Image* im,
  50586. const Colour& textColour_,
  50587. const bool usesColour_,
  50588. PopupMenuCustomComponent* const customComp_,
  50589. const PopupMenu* const subMenu_,
  50590. ApplicationCommandManager* const commandManager_) throw()
  50591. : itemId (itemId_),
  50592. text (text_),
  50593. textColour (textColour_),
  50594. active (active_),
  50595. isSeparator (false),
  50596. isTicked (isTicked_),
  50597. usesColour (usesColour_),
  50598. image (0),
  50599. customComp (customComp_),
  50600. commandManager (commandManager_)
  50601. {
  50602. subMenu = (subMenu_ != 0) ? new PopupMenu (*subMenu_) : 0;
  50603. if (customComp != 0)
  50604. customComp->refCount_++;
  50605. if (im != 0)
  50606. image = im->createCopy();
  50607. if (commandManager_ != 0 && itemId_ != 0)
  50608. {
  50609. String shortcutKey;
  50610. Array <KeyPress> keyPresses (commandManager_->getKeyMappings()
  50611. ->getKeyPressesAssignedToCommand (itemId_));
  50612. for (int i = 0; i < keyPresses.size(); ++i)
  50613. {
  50614. const String key (keyPresses.getReference(i).getTextDescription());
  50615. if (shortcutKey.isNotEmpty())
  50616. shortcutKey << ", ";
  50617. if (key.length() == 1)
  50618. shortcutKey << "shortcut: '" << key << '\'';
  50619. else
  50620. shortcutKey << key;
  50621. }
  50622. shortcutKey = shortcutKey.trim();
  50623. if (shortcutKey.isNotEmpty())
  50624. text << "<end>" << shortcutKey;
  50625. }
  50626. }
  50627. MenuItemInfo (const MenuItemInfo& other) throw()
  50628. : itemId (other.itemId),
  50629. text (other.text),
  50630. textColour (other.textColour),
  50631. active (other.active),
  50632. isSeparator (other.isSeparator),
  50633. isTicked (other.isTicked),
  50634. usesColour (other.usesColour),
  50635. customComp (other.customComp),
  50636. commandManager (other.commandManager)
  50637. {
  50638. if (other.subMenu != 0)
  50639. subMenu = new PopupMenu (*(other.subMenu));
  50640. else
  50641. subMenu = 0;
  50642. if (other.image != 0)
  50643. image = other.image->createCopy();
  50644. else
  50645. image = 0;
  50646. if (customComp != 0)
  50647. customComp->refCount_++;
  50648. }
  50649. ~MenuItemInfo() throw()
  50650. {
  50651. delete subMenu;
  50652. delete image;
  50653. if (customComp != 0 && --(customComp->refCount_) == 0)
  50654. delete customComp;
  50655. }
  50656. bool canBeTriggered() const throw()
  50657. {
  50658. return active && ! (isSeparator || (subMenu != 0));
  50659. }
  50660. bool hasActiveSubMenu() const throw()
  50661. {
  50662. return active && (subMenu != 0);
  50663. }
  50664. juce_UseDebuggingNewOperator
  50665. private:
  50666. const MenuItemInfo& operator= (const MenuItemInfo&);
  50667. };
  50668. class MenuItemComponent : public Component
  50669. {
  50670. bool isHighlighted;
  50671. public:
  50672. MenuItemInfo itemInfo;
  50673. MenuItemComponent (const MenuItemInfo& itemInfo_)
  50674. : isHighlighted (false),
  50675. itemInfo (itemInfo_)
  50676. {
  50677. if (itemInfo.customComp != 0)
  50678. addAndMakeVisible (itemInfo.customComp);
  50679. }
  50680. ~MenuItemComponent()
  50681. {
  50682. if (itemInfo.customComp != 0)
  50683. removeChildComponent (itemInfo.customComp);
  50684. }
  50685. void getIdealSize (int& idealWidth,
  50686. int& idealHeight,
  50687. const int standardItemHeight)
  50688. {
  50689. if (itemInfo.customComp != 0)
  50690. {
  50691. itemInfo.customComp->getIdealSize (idealWidth, idealHeight);
  50692. }
  50693. else
  50694. {
  50695. getLookAndFeel().getIdealPopupMenuItemSize (itemInfo.text,
  50696. itemInfo.isSeparator,
  50697. standardItemHeight,
  50698. idealWidth,
  50699. idealHeight);
  50700. }
  50701. }
  50702. void paint (Graphics& g)
  50703. {
  50704. if (itemInfo.customComp == 0)
  50705. {
  50706. String mainText (itemInfo.text);
  50707. String endText;
  50708. const int endIndex = mainText.indexOf (T("<end>"));
  50709. if (endIndex >= 0)
  50710. {
  50711. endText = mainText.substring (endIndex + 5).trim();
  50712. mainText = mainText.substring (0, endIndex);
  50713. }
  50714. getLookAndFeel()
  50715. .drawPopupMenuItem (g, getWidth(), getHeight(),
  50716. itemInfo.isSeparator,
  50717. itemInfo.active,
  50718. isHighlighted,
  50719. itemInfo.isTicked,
  50720. itemInfo.subMenu != 0,
  50721. mainText, endText,
  50722. itemInfo.image,
  50723. itemInfo.usesColour ? &(itemInfo.textColour) : 0);
  50724. }
  50725. }
  50726. void resized()
  50727. {
  50728. if (getNumChildComponents() > 0)
  50729. getChildComponent(0)->setBounds (2, 0, getWidth() - 4, getHeight());
  50730. }
  50731. void setHighlighted (bool shouldBeHighlighted)
  50732. {
  50733. shouldBeHighlighted = shouldBeHighlighted && itemInfo.active;
  50734. if (isHighlighted != shouldBeHighlighted)
  50735. {
  50736. isHighlighted = shouldBeHighlighted;
  50737. if (itemInfo.customComp != 0)
  50738. {
  50739. itemInfo.customComp->isHighlighted = shouldBeHighlighted;
  50740. itemInfo.customComp->repaint();
  50741. }
  50742. repaint();
  50743. }
  50744. }
  50745. private:
  50746. MenuItemComponent (const MenuItemComponent&);
  50747. const MenuItemComponent& operator= (const MenuItemComponent&);
  50748. };
  50749. static const int scrollZone = 24;
  50750. static const int borderSize = 2;
  50751. static const int timerInterval = 50;
  50752. static const int dismissCommandId = 0x6287345f;
  50753. static bool wasHiddenBecauseOfAppChange = false;
  50754. class PopupMenuWindow : public Component,
  50755. private Timer
  50756. {
  50757. public:
  50758. PopupMenuWindow() throw()
  50759. : Component (T("menu")),
  50760. owner (0),
  50761. currentChild (0),
  50762. activeSubMenu (0),
  50763. menuBarComponent (0),
  50764. managerOfChosenCommand (0),
  50765. componentAttachedTo (0),
  50766. attachedCompWatcher (0),
  50767. lastMouseX (0),
  50768. lastMouseY (0),
  50769. minimumWidth (0),
  50770. maximumNumColumns (7),
  50771. standardItemHeight (0),
  50772. isOver (false),
  50773. hasBeenOver (false),
  50774. isDown (false),
  50775. needsToScroll (false),
  50776. hideOnExit (false),
  50777. disableMouseMoves (false),
  50778. hasAnyJuceCompHadFocus (false),
  50779. numColumns (0),
  50780. contentHeight (0),
  50781. childYOffset (0),
  50782. timeEnteredCurrentChildComp (0),
  50783. scrollAcceleration (1.0)
  50784. {
  50785. menuCreationTime = lastFocused = lastScroll = Time::getMillisecondCounter();
  50786. setWantsKeyboardFocus (true);
  50787. setMouseClickGrabsKeyboardFocus (false);
  50788. setOpaque (true);
  50789. setAlwaysOnTop (true);
  50790. Desktop::getInstance().addGlobalMouseListener (this);
  50791. activeMenuWindows.add (this);
  50792. }
  50793. ~PopupMenuWindow()
  50794. {
  50795. activeMenuWindows.removeValue (this);
  50796. Desktop::getInstance().removeGlobalMouseListener (this);
  50797. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  50798. delete activeSubMenu;
  50799. deleteAllChildren();
  50800. delete attachedCompWatcher;
  50801. }
  50802. static PopupMenuWindow* create (const PopupMenu& menu,
  50803. const bool dismissOnMouseUp,
  50804. PopupMenuWindow* const owner_,
  50805. const int minX, const int maxX,
  50806. const int minY, const int maxY,
  50807. const int minimumWidth,
  50808. const int maximumNumColumns,
  50809. const int standardItemHeight,
  50810. const bool alignToRectangle,
  50811. const int itemIdThatMustBeVisible,
  50812. Component* const menuBarComponent,
  50813. ApplicationCommandManager** managerOfChosenCommand,
  50814. Component* const componentAttachedTo) throw()
  50815. {
  50816. if (menu.items.size() > 0)
  50817. {
  50818. int totalItems = 0;
  50819. PopupMenuWindow* const mw = new PopupMenuWindow();
  50820. mw->setLookAndFeel (menu.lookAndFeel);
  50821. mw->setWantsKeyboardFocus (false);
  50822. mw->minimumWidth = minimumWidth;
  50823. mw->maximumNumColumns = maximumNumColumns;
  50824. mw->standardItemHeight = standardItemHeight;
  50825. mw->dismissOnMouseUp = dismissOnMouseUp;
  50826. for (int i = 0; i < menu.items.size(); ++i)
  50827. {
  50828. MenuItemInfo* const item = (MenuItemInfo*) menu.items.getUnchecked(i);
  50829. mw->addItem (*item);
  50830. ++totalItems;
  50831. }
  50832. if (totalItems == 0)
  50833. {
  50834. delete mw;
  50835. }
  50836. else
  50837. {
  50838. mw->owner = owner_;
  50839. mw->menuBarComponent = menuBarComponent;
  50840. mw->managerOfChosenCommand = managerOfChosenCommand;
  50841. mw->componentAttachedTo = componentAttachedTo;
  50842. delete mw->attachedCompWatcher;
  50843. mw->attachedCompWatcher = componentAttachedTo != 0 ? new ComponentDeletionWatcher (componentAttachedTo) : 0;
  50844. mw->calculateWindowPos (minX, maxX, minY, maxY, alignToRectangle);
  50845. mw->setTopLeftPosition (mw->windowPos.getX(),
  50846. mw->windowPos.getY());
  50847. mw->updateYPositions();
  50848. if (itemIdThatMustBeVisible != 0)
  50849. {
  50850. const int y = minY - mw->windowPos.getY();
  50851. mw->ensureItemIsVisible (itemIdThatMustBeVisible,
  50852. (((unsigned int) y) < (unsigned int) mw->windowPos.getHeight()) ? y : -1);
  50853. }
  50854. mw->resizeToBestWindowPos();
  50855. mw->addToDesktop (ComponentPeer::windowIsTemporary
  50856. | mw->getLookAndFeel().getMenuWindowFlags());
  50857. return mw;
  50858. }
  50859. }
  50860. return 0;
  50861. }
  50862. void paint (Graphics& g)
  50863. {
  50864. getLookAndFeel().drawPopupMenuBackground (g, getWidth(), getHeight());
  50865. }
  50866. void paintOverChildren (Graphics& g)
  50867. {
  50868. if (isScrolling())
  50869. {
  50870. LookAndFeel& lf = getLookAndFeel();
  50871. if (isScrollZoneActive (false))
  50872. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, true);
  50873. if (isScrollZoneActive (true))
  50874. {
  50875. g.setOrigin (0, getHeight() - scrollZone);
  50876. lf.drawPopupMenuUpDownArrow (g, getWidth(), scrollZone, false);
  50877. }
  50878. }
  50879. }
  50880. bool isScrollZoneActive (bool bottomOne) const
  50881. {
  50882. return isScrolling()
  50883. && (bottomOne
  50884. ? childYOffset < contentHeight - windowPos.getHeight()
  50885. : childYOffset > 0);
  50886. }
  50887. void addItem (const MenuItemInfo& item) throw()
  50888. {
  50889. MenuItemComponent* const mic = new MenuItemComponent (item);
  50890. addAndMakeVisible (mic);
  50891. int itemW = 80;
  50892. int itemH = 16;
  50893. mic->getIdealSize (itemW, itemH, standardItemHeight);
  50894. mic->setSize (itemW, jlimit (2, 600, itemH));
  50895. mic->addMouseListener (this, false);
  50896. }
  50897. // hide this and all sub-comps
  50898. void hide (const MenuItemInfo* const item) throw()
  50899. {
  50900. if (isVisible())
  50901. {
  50902. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  50903. deleteAndZero (activeSubMenu);
  50904. currentChild = 0;
  50905. exitModalState (item != 0 ? item->itemId : 0);
  50906. setVisible (false);
  50907. if (item != 0
  50908. && item->commandManager != 0
  50909. && item->itemId != 0)
  50910. {
  50911. *managerOfChosenCommand = item->commandManager;
  50912. }
  50913. }
  50914. }
  50915. void dismissMenu (const MenuItemInfo* const item) throw()
  50916. {
  50917. if (owner != 0)
  50918. {
  50919. owner->dismissMenu (item);
  50920. }
  50921. else
  50922. {
  50923. if (item != 0)
  50924. {
  50925. // need a copy of this on the stack as the one passed in will get deleted during this call
  50926. const MenuItemInfo mi (*item);
  50927. hide (&mi);
  50928. }
  50929. else
  50930. {
  50931. hide (0);
  50932. }
  50933. }
  50934. }
  50935. void mouseMove (const MouseEvent&)
  50936. {
  50937. timerCallback();
  50938. }
  50939. void mouseDown (const MouseEvent&)
  50940. {
  50941. timerCallback();
  50942. }
  50943. void mouseDrag (const MouseEvent&)
  50944. {
  50945. timerCallback();
  50946. }
  50947. void mouseUp (const MouseEvent&)
  50948. {
  50949. timerCallback();
  50950. }
  50951. void mouseWheelMove (const MouseEvent&, float /*amountX*/, float amountY)
  50952. {
  50953. alterChildYPos (roundFloatToInt (-10.0f * amountY * scrollZone));
  50954. lastMouseX = -1;
  50955. }
  50956. bool keyPressed (const KeyPress& key)
  50957. {
  50958. if (key.isKeyCode (KeyPress::downKey))
  50959. {
  50960. selectNextItem (1);
  50961. }
  50962. else if (key.isKeyCode (KeyPress::upKey))
  50963. {
  50964. selectNextItem (-1);
  50965. }
  50966. else if (key.isKeyCode (KeyPress::leftKey))
  50967. {
  50968. PopupMenuWindow* parentWindow = owner;
  50969. if (parentWindow != 0)
  50970. {
  50971. MenuItemComponent* currentChildOfParent
  50972. = (parentWindow != 0) ? parentWindow->currentChild : 0;
  50973. hide (0);
  50974. if (parentWindow->isValidComponent())
  50975. parentWindow->setCurrentlyHighlightedChild (currentChildOfParent);
  50976. disableTimerUntilMouseMoves();
  50977. }
  50978. else if (menuBarComponent != 0)
  50979. {
  50980. menuBarComponent->keyPressed (key);
  50981. }
  50982. }
  50983. else if (key.isKeyCode (KeyPress::rightKey))
  50984. {
  50985. disableTimerUntilMouseMoves();
  50986. if (showSubMenuFor (currentChild))
  50987. {
  50988. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  50989. if (activeSubMenu != 0 && activeSubMenu->isVisible())
  50990. activeSubMenu->selectNextItem (1);
  50991. }
  50992. else if (menuBarComponent != 0)
  50993. {
  50994. menuBarComponent->keyPressed (key);
  50995. }
  50996. }
  50997. else if (key.isKeyCode (KeyPress::returnKey))
  50998. {
  50999. triggerCurrentlyHighlightedItem();
  51000. }
  51001. else if (key.isKeyCode (KeyPress::escapeKey))
  51002. {
  51003. dismissMenu (0);
  51004. }
  51005. else
  51006. {
  51007. return false;
  51008. }
  51009. return true;
  51010. }
  51011. void inputAttemptWhenModal()
  51012. {
  51013. timerCallback();
  51014. if (! isOverAnyMenu())
  51015. {
  51016. if (componentAttachedTo != 0 && ! attachedCompWatcher->hasBeenDeleted())
  51017. {
  51018. // we want to dismiss the menu, but if we do it synchronously, then
  51019. // the mouse-click will be allowed to pass through. That's good, except
  51020. // when the user clicks on the button that orginally popped the menu up,
  51021. // as they'll expect the menu to go away, and in fact it'll just
  51022. // come back. So only dismiss synchronously if they're not on the original
  51023. // comp that we're attached to.
  51024. int mx, my;
  51025. componentAttachedTo->getMouseXYRelative (mx, my);
  51026. if (componentAttachedTo->reallyContains (mx, my, true))
  51027. {
  51028. postCommandMessage (dismissCommandId); // dismiss asynchrounously
  51029. return;
  51030. }
  51031. }
  51032. dismissMenu (0);
  51033. }
  51034. }
  51035. void handleCommandMessage (int commandId)
  51036. {
  51037. Component::handleCommandMessage (commandId);
  51038. if (commandId == dismissCommandId)
  51039. dismissMenu (0);
  51040. }
  51041. void timerCallback()
  51042. {
  51043. if (! isVisible())
  51044. return;
  51045. if (attachedCompWatcher != 0 && attachedCompWatcher->hasBeenDeleted())
  51046. {
  51047. dismissMenu (0);
  51048. return;
  51049. }
  51050. PopupMenuWindow* currentlyModalWindow = dynamic_cast <PopupMenuWindow*> (Component::getCurrentlyModalComponent());
  51051. if (currentlyModalWindow != 0 && ! treeContains (currentlyModalWindow))
  51052. return;
  51053. startTimer (timerInterval); // do this in case it was called from a mouse
  51054. // move rather than a real timer callback
  51055. int mx, my;
  51056. Desktop::getMousePosition (mx, my);
  51057. int x = mx, y = my;
  51058. globalPositionToRelative (x, y);
  51059. const uint32 now = Time::getMillisecondCounter();
  51060. if (now > timeEnteredCurrentChildComp + 100
  51061. && reallyContains (x, y, true)
  51062. && currentChild->isValidComponent()
  51063. && (! disableMouseMoves)
  51064. && ! (activeSubMenu != 0 && activeSubMenu->isVisible()))
  51065. {
  51066. showSubMenuFor (currentChild);
  51067. }
  51068. if (mx != lastMouseX || my != lastMouseY || now > lastMouseMoveTime + 350)
  51069. {
  51070. highlightItemUnderMouse (mx, my, x, y);
  51071. }
  51072. bool overScrollArea = false;
  51073. if (isScrolling()
  51074. && (isOver || (isDown && ((unsigned int) x) < (unsigned int) getWidth()))
  51075. && ((isScrollZoneActive (false) && y < scrollZone)
  51076. || (isScrollZoneActive (true) && y > getHeight() - scrollZone)))
  51077. {
  51078. if (now > lastScroll + 20)
  51079. {
  51080. scrollAcceleration = jmin (4.0, scrollAcceleration * 1.04);
  51081. int amount = 0;
  51082. for (int i = 0; i < getNumChildComponents() && amount == 0; ++i)
  51083. amount = ((int) scrollAcceleration) * getChildComponent (i)->getHeight();
  51084. alterChildYPos (y < scrollZone ? -amount : amount);
  51085. lastScroll = now;
  51086. }
  51087. overScrollArea = true;
  51088. lastMouseX = -1; // trigger a mouse-move
  51089. }
  51090. else
  51091. {
  51092. scrollAcceleration = 1.0;
  51093. }
  51094. const bool wasDown = isDown;
  51095. bool isOverAny = isOverAnyMenu();
  51096. if (hideOnExit && hasBeenOver && (! isOverAny) && activeSubMenu != 0)
  51097. {
  51098. activeSubMenu->updateMouseOverStatus (mx, my);
  51099. isOverAny = isOverAnyMenu();
  51100. }
  51101. if (hideOnExit && hasBeenOver && ! isOverAny)
  51102. {
  51103. hide (0);
  51104. }
  51105. else
  51106. {
  51107. isDown = hasBeenOver
  51108. && (ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown()
  51109. || ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown());
  51110. bool anyFocused = Process::isForegroundProcess();
  51111. if (anyFocused && Component::getCurrentlyFocusedComponent() == 0)
  51112. {
  51113. // because no component at all may have focus, our test here will
  51114. // only be triggered when something has focus and then loses it.
  51115. anyFocused = ! hasAnyJuceCompHadFocus;
  51116. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  51117. {
  51118. if (ComponentPeer::getPeer (i)->isFocused())
  51119. {
  51120. anyFocused = true;
  51121. hasAnyJuceCompHadFocus = true;
  51122. break;
  51123. }
  51124. }
  51125. }
  51126. if (! anyFocused)
  51127. {
  51128. if (now > lastFocused + 10)
  51129. {
  51130. wasHiddenBecauseOfAppChange = true;
  51131. dismissMenu (0);
  51132. return; // may have been deleted by the previous call..
  51133. }
  51134. }
  51135. else if (wasDown && now > menuCreationTime + 250
  51136. && ! (isDown || overScrollArea))
  51137. {
  51138. isOver = reallyContains (x, y, true);
  51139. if (isOver)
  51140. {
  51141. triggerCurrentlyHighlightedItem();
  51142. }
  51143. else if ((hasBeenOver || ! dismissOnMouseUp) && ! isOverAny)
  51144. {
  51145. dismissMenu (0);
  51146. }
  51147. return; // may have been deleted by the previous calls..
  51148. }
  51149. else
  51150. {
  51151. lastFocused = now;
  51152. }
  51153. }
  51154. }
  51155. juce_UseDebuggingNewOperator
  51156. private:
  51157. PopupMenuWindow* owner;
  51158. MenuItemComponent* currentChild;
  51159. PopupMenuWindow* activeSubMenu;
  51160. Component* menuBarComponent;
  51161. ApplicationCommandManager** managerOfChosenCommand;
  51162. Component* componentAttachedTo;
  51163. ComponentDeletionWatcher* attachedCompWatcher;
  51164. Rectangle windowPos;
  51165. int lastMouseX, lastMouseY;
  51166. int minimumWidth, maximumNumColumns, standardItemHeight;
  51167. bool isOver, hasBeenOver, isDown, needsToScroll;
  51168. bool dismissOnMouseUp, hideOnExit, disableMouseMoves, hasAnyJuceCompHadFocus;
  51169. int numColumns, contentHeight, childYOffset;
  51170. Array <int> columnWidths;
  51171. uint32 menuCreationTime, lastFocused, lastScroll, lastMouseMoveTime, timeEnteredCurrentChildComp;
  51172. double scrollAcceleration;
  51173. bool overlaps (const Rectangle& r) const throw()
  51174. {
  51175. return r.intersects (getBounds())
  51176. || (owner != 0 && owner->overlaps (r));
  51177. }
  51178. bool isOverAnyMenu() const throw()
  51179. {
  51180. return (owner != 0) ? owner->isOverAnyMenu()
  51181. : isOverChildren();
  51182. }
  51183. bool isOverChildren() const throw()
  51184. {
  51185. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  51186. return isVisible()
  51187. && (isOver || (activeSubMenu != 0 && activeSubMenu->isOverChildren()));
  51188. }
  51189. void updateMouseOverStatus (const int mx, const int my) throw()
  51190. {
  51191. int rx = mx, ry = my;
  51192. globalPositionToRelative (rx, ry);
  51193. isOver = reallyContains (rx, ry, true);
  51194. if (activeSubMenu != 0)
  51195. activeSubMenu->updateMouseOverStatus (mx, my);
  51196. }
  51197. bool treeContains (const PopupMenuWindow* const window) const throw()
  51198. {
  51199. const PopupMenuWindow* mw = this;
  51200. while (mw->owner != 0)
  51201. mw = mw->owner;
  51202. while (mw != 0)
  51203. {
  51204. if (mw == window)
  51205. return true;
  51206. mw = mw->activeSubMenu;
  51207. }
  51208. return false;
  51209. }
  51210. void calculateWindowPos (const int minX, const int maxX,
  51211. const int minY, const int maxY,
  51212. const bool alignToRectangle)
  51213. {
  51214. const Rectangle mon (Desktop::getInstance()
  51215. .getMonitorAreaContaining ((minX + maxX) / 2,
  51216. (minY + maxY) / 2,
  51217. true));
  51218. int x, y, widthToUse, heightToUse;
  51219. layoutMenuItems (mon.getWidth() - 24, widthToUse, heightToUse);
  51220. if (alignToRectangle)
  51221. {
  51222. x = minX;
  51223. const int spaceUnder = mon.getHeight() - (maxY - mon.getY());
  51224. const int spaceOver = minY - mon.getY();
  51225. if (heightToUse < spaceUnder - 30 || spaceUnder >= spaceOver)
  51226. y = maxY;
  51227. else
  51228. y = minY - heightToUse;
  51229. }
  51230. else
  51231. {
  51232. bool tendTowardsRight = (minX + maxX) / 2 < mon.getCentreX();
  51233. if (owner != 0)
  51234. {
  51235. if (owner->owner != 0)
  51236. {
  51237. const bool ownerGoingRight = (owner->getX() + owner->getWidth() / 2
  51238. > owner->owner->getX() + owner->owner->getWidth() / 2);
  51239. if (ownerGoingRight && maxX + widthToUse < mon.getRight() - 4)
  51240. tendTowardsRight = true;
  51241. else if ((! ownerGoingRight) && minX > widthToUse + 4)
  51242. tendTowardsRight = false;
  51243. }
  51244. else if (maxX + widthToUse < mon.getRight() - 32)
  51245. {
  51246. tendTowardsRight = true;
  51247. }
  51248. }
  51249. const int biggestSpace = jmax (mon.getRight() - maxX,
  51250. minX - mon.getX()) - 32;
  51251. if (biggestSpace < widthToUse)
  51252. {
  51253. layoutMenuItems (biggestSpace + (maxX - minX) / 3, widthToUse, heightToUse);
  51254. if (numColumns > 1)
  51255. layoutMenuItems (biggestSpace - 4, widthToUse, heightToUse);
  51256. tendTowardsRight = (mon.getRight() - maxX) >= (minX - mon.getX());
  51257. }
  51258. if (tendTowardsRight)
  51259. x = jmin (mon.getRight() - widthToUse - 4, maxX);
  51260. else
  51261. x = jmax (mon.getX() + 4, minX - widthToUse);
  51262. y = minY;
  51263. if ((minY + maxY) / 2 > mon.getCentreY())
  51264. y = jmax (mon.getY(), maxY - heightToUse);
  51265. }
  51266. x = jlimit (mon.getX() + 1, mon.getRight() - (widthToUse + 6), x);
  51267. y = jlimit (mon.getY() + 1, mon.getBottom() - (heightToUse + 6), y);
  51268. windowPos.setBounds (x, y, widthToUse, heightToUse);
  51269. // sets this flag if it's big enough to obscure any of its parent menus
  51270. hideOnExit = (owner != 0)
  51271. && owner->windowPos.intersects (windowPos.expanded (-4, -4));
  51272. }
  51273. void layoutMenuItems (const int maxMenuW, int& width, int& height)
  51274. {
  51275. numColumns = 0;
  51276. contentHeight = 0;
  51277. const int maxMenuH = getParentHeight() - 24;
  51278. int totalW;
  51279. do
  51280. {
  51281. ++numColumns;
  51282. totalW = workOutBestSize (numColumns, maxMenuW);
  51283. if (totalW > maxMenuW)
  51284. {
  51285. numColumns = jmax (1, numColumns - 1);
  51286. totalW = workOutBestSize (numColumns, maxMenuW); // to update col widths
  51287. break;
  51288. }
  51289. else if (totalW > maxMenuW / 2 || contentHeight < maxMenuH)
  51290. {
  51291. break;
  51292. }
  51293. } while (numColumns < maximumNumColumns);
  51294. const int actualH = jmin (contentHeight, maxMenuH);
  51295. needsToScroll = contentHeight > actualH;
  51296. width = updateYPositions();
  51297. height = actualH + borderSize * 2;
  51298. }
  51299. int workOutBestSize (const int numColumns, const int maxMenuW)
  51300. {
  51301. int totalW = 0;
  51302. contentHeight = 0;
  51303. int childNum = 0;
  51304. for (int col = 0; col < numColumns; ++col)
  51305. {
  51306. int i, colW = 50, colH = 0;
  51307. const int numChildren = jmin (getNumChildComponents() - childNum,
  51308. (getNumChildComponents() + numColumns - 1) / numColumns);
  51309. for (i = numChildren; --i >= 0;)
  51310. {
  51311. colW = jmax (colW, getChildComponent (childNum + i)->getWidth());
  51312. colH += getChildComponent (childNum + i)->getHeight();
  51313. }
  51314. colW = jmin (maxMenuW / jmax (1, numColumns - 2), colW + borderSize * 2);
  51315. columnWidths.set (col, colW);
  51316. totalW += colW;
  51317. contentHeight = jmax (contentHeight, colH);
  51318. childNum += numChildren;
  51319. }
  51320. if (totalW < minimumWidth)
  51321. {
  51322. totalW = minimumWidth;
  51323. for (int col = 0; col < numColumns; ++col)
  51324. columnWidths.set (0, totalW / numColumns);
  51325. }
  51326. return totalW;
  51327. }
  51328. void ensureItemIsVisible (const int itemId, int wantedY)
  51329. {
  51330. jassert (itemId != 0)
  51331. for (int i = getNumChildComponents(); --i >= 0;)
  51332. {
  51333. MenuItemComponent* const m = (MenuItemComponent*) getChildComponent (i);
  51334. if (m != 0
  51335. && m->itemInfo.itemId == itemId
  51336. && windowPos.getHeight() > scrollZone * 4)
  51337. {
  51338. const int currentY = m->getY();
  51339. if (wantedY > 0 || currentY < 0 || m->getBottom() > windowPos.getHeight())
  51340. {
  51341. if (wantedY < 0)
  51342. wantedY = jlimit (scrollZone,
  51343. jmax (scrollZone, windowPos.getHeight() - (scrollZone + m->getHeight())),
  51344. currentY);
  51345. const Rectangle mon (Desktop::getInstance()
  51346. .getMonitorAreaContaining (windowPos.getX(),
  51347. windowPos.getY(),
  51348. true));
  51349. int deltaY = wantedY - currentY;
  51350. const int newY = jlimit (mon.getY(),
  51351. mon.getBottom() - windowPos.getHeight(),
  51352. windowPos.getY() + deltaY);
  51353. deltaY -= newY - windowPos.getY();
  51354. childYOffset -= deltaY;
  51355. windowPos.setPosition (windowPos.getX(), newY);
  51356. updateYPositions();
  51357. }
  51358. break;
  51359. }
  51360. }
  51361. }
  51362. void resizeToBestWindowPos()
  51363. {
  51364. Rectangle r (windowPos);
  51365. if (childYOffset < 0)
  51366. {
  51367. r.setBounds (r.getX(), r.getY() - childYOffset,
  51368. r.getWidth(), r.getHeight() + childYOffset);
  51369. }
  51370. else if (childYOffset > 0)
  51371. {
  51372. const int spaceAtBottom = r.getHeight() - (contentHeight - childYOffset);
  51373. if (spaceAtBottom > 0)
  51374. r.setSize (r.getWidth(), r.getHeight() - spaceAtBottom);
  51375. }
  51376. setBounds (r);
  51377. updateYPositions();
  51378. }
  51379. void alterChildYPos (const int delta)
  51380. {
  51381. if (isScrolling())
  51382. {
  51383. childYOffset += delta;
  51384. if (delta < 0)
  51385. {
  51386. childYOffset = jmax (childYOffset, 0);
  51387. }
  51388. else if (delta > 0)
  51389. {
  51390. childYOffset = jmin (childYOffset,
  51391. contentHeight - windowPos.getHeight() + borderSize);
  51392. }
  51393. updateYPositions();
  51394. }
  51395. else
  51396. {
  51397. childYOffset = 0;
  51398. }
  51399. resizeToBestWindowPos();
  51400. repaint();
  51401. }
  51402. int updateYPositions()
  51403. {
  51404. int x = 0;
  51405. int childNum = 0;
  51406. for (int col = 0; col < numColumns; ++col)
  51407. {
  51408. const int numChildren = jmin (getNumChildComponents() - childNum,
  51409. (getNumChildComponents() + numColumns - 1) / numColumns);
  51410. const int colW = columnWidths [col];
  51411. int y = borderSize - (childYOffset + (getY() - windowPos.getY()));
  51412. for (int i = 0; i < numChildren; ++i)
  51413. {
  51414. Component* const c = getChildComponent (childNum + i);
  51415. c->setBounds (x, y, colW, c->getHeight());
  51416. y += c->getHeight();
  51417. }
  51418. x += colW;
  51419. childNum += numChildren;
  51420. }
  51421. return x;
  51422. }
  51423. bool isScrolling() const throw()
  51424. {
  51425. return childYOffset != 0 || needsToScroll;
  51426. }
  51427. void setCurrentlyHighlightedChild (MenuItemComponent* const child) throw()
  51428. {
  51429. if (currentChild->isValidComponent())
  51430. currentChild->setHighlighted (false);
  51431. currentChild = child;
  51432. if (currentChild != 0)
  51433. {
  51434. currentChild->setHighlighted (true);
  51435. timeEnteredCurrentChildComp = Time::getApproximateMillisecondCounter();
  51436. }
  51437. }
  51438. bool showSubMenuFor (MenuItemComponent* const childComp)
  51439. {
  51440. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent());
  51441. deleteAndZero (activeSubMenu);
  51442. if (childComp->isValidComponent() && childComp->itemInfo.hasActiveSubMenu())
  51443. {
  51444. int left = 0, top = 0;
  51445. childComp->relativePositionToGlobal (left, top);
  51446. int right = childComp->getWidth(), bottom = childComp->getHeight();
  51447. childComp->relativePositionToGlobal (right, bottom);
  51448. activeSubMenu = PopupMenuWindow::create (*(childComp->itemInfo.subMenu),
  51449. dismissOnMouseUp,
  51450. this,
  51451. left, right, top, bottom,
  51452. 0, maximumNumColumns,
  51453. standardItemHeight,
  51454. false, 0, menuBarComponent,
  51455. managerOfChosenCommand,
  51456. componentAttachedTo);
  51457. if (activeSubMenu != 0)
  51458. {
  51459. activeSubMenu->setVisible (true);
  51460. activeSubMenu->enterModalState (false);
  51461. activeSubMenu->toFront (false);
  51462. return true;
  51463. }
  51464. }
  51465. return false;
  51466. }
  51467. void highlightItemUnderMouse (const int mx, const int my, const int x, const int y)
  51468. {
  51469. isOver = reallyContains (x, y, true);
  51470. if (isOver)
  51471. hasBeenOver = true;
  51472. if (abs (lastMouseX - mx) > 2 || abs (lastMouseY - my) > 2)
  51473. {
  51474. lastMouseMoveTime = Time::getApproximateMillisecondCounter();
  51475. if (disableMouseMoves && isOver)
  51476. disableMouseMoves = false;
  51477. }
  51478. if (disableMouseMoves)
  51479. return;
  51480. bool isMovingTowardsMenu = false;
  51481. jassert (activeSubMenu == 0 || activeSubMenu->isValidComponent())
  51482. if (isOver && (activeSubMenu != 0) && (mx != lastMouseX || my != lastMouseY))
  51483. {
  51484. // try to intelligently guess whether the user is moving the mouse towards a currently-open
  51485. // submenu. To do this, look at whether the mouse stays inside a triangular region that
  51486. // extends from the last mouse pos to the submenu's rectangle..
  51487. float subX = (float) activeSubMenu->getScreenX();
  51488. if (activeSubMenu->getX() > getX())
  51489. {
  51490. lastMouseX -= 2; // to enlarge the triangle a bit, in case the mouse only moves a couple of pixels
  51491. }
  51492. else
  51493. {
  51494. lastMouseX += 2;
  51495. subX += activeSubMenu->getWidth();
  51496. }
  51497. Path areaTowardsSubMenu;
  51498. areaTowardsSubMenu.addTriangle ((float) lastMouseX,
  51499. (float) lastMouseY,
  51500. subX,
  51501. (float) activeSubMenu->getScreenY(),
  51502. subX,
  51503. (float) (activeSubMenu->getScreenY() + activeSubMenu->getHeight()));
  51504. isMovingTowardsMenu = areaTowardsSubMenu.contains ((float) mx, (float) my);
  51505. }
  51506. lastMouseX = mx;
  51507. lastMouseY = my;
  51508. if (! isMovingTowardsMenu)
  51509. {
  51510. Component* c = getComponentAt (x, y);
  51511. if (c == this)
  51512. c = 0;
  51513. MenuItemComponent* mic = dynamic_cast <MenuItemComponent*> (c);
  51514. if (mic == 0 && c != 0)
  51515. mic = c->findParentComponentOfClass ((MenuItemComponent*) 0);
  51516. if (mic != currentChild
  51517. && (isOver || (activeSubMenu == 0) || ! activeSubMenu->isVisible()))
  51518. {
  51519. if (isOver && (c != 0) && (activeSubMenu != 0))
  51520. {
  51521. activeSubMenu->hide (0);
  51522. }
  51523. if (! isOver)
  51524. mic = 0;
  51525. setCurrentlyHighlightedChild (mic);
  51526. }
  51527. }
  51528. }
  51529. void triggerCurrentlyHighlightedItem()
  51530. {
  51531. if (currentChild->isValidComponent()
  51532. && currentChild->itemInfo.canBeTriggered()
  51533. && (currentChild->itemInfo.customComp == 0
  51534. || currentChild->itemInfo.customComp->isTriggeredAutomatically))
  51535. {
  51536. dismissMenu (&currentChild->itemInfo);
  51537. }
  51538. }
  51539. void selectNextItem (const int delta)
  51540. {
  51541. disableTimerUntilMouseMoves();
  51542. MenuItemComponent* mic = 0;
  51543. bool wasLastOne = (currentChild == 0);
  51544. const int numItems = getNumChildComponents();
  51545. for (int i = 0; i < numItems + 1; ++i)
  51546. {
  51547. int index = (delta > 0) ? i : (numItems - 1 - i);
  51548. index = (index + numItems) % numItems;
  51549. mic = dynamic_cast <MenuItemComponent*> (getChildComponent (index));
  51550. if (mic != 0 && (mic->itemInfo.canBeTriggered() || mic->itemInfo.hasActiveSubMenu())
  51551. && wasLastOne)
  51552. break;
  51553. if (mic == currentChild)
  51554. wasLastOne = true;
  51555. }
  51556. setCurrentlyHighlightedChild (mic);
  51557. }
  51558. void disableTimerUntilMouseMoves() throw()
  51559. {
  51560. disableMouseMoves = true;
  51561. if (owner != 0)
  51562. owner->disableTimerUntilMouseMoves();
  51563. }
  51564. PopupMenuWindow (const PopupMenuWindow&);
  51565. const PopupMenuWindow& operator= (const PopupMenuWindow&);
  51566. };
  51567. PopupMenu::PopupMenu() throw()
  51568. : items (8),
  51569. lookAndFeel (0),
  51570. separatorPending (false)
  51571. {
  51572. }
  51573. PopupMenu::PopupMenu (const PopupMenu& other) throw()
  51574. : items (8),
  51575. lookAndFeel (other.lookAndFeel),
  51576. separatorPending (false)
  51577. {
  51578. items.ensureStorageAllocated (other.items.size());
  51579. for (int i = 0; i < other.items.size(); ++i)
  51580. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  51581. }
  51582. const PopupMenu& PopupMenu::operator= (const PopupMenu& other) throw()
  51583. {
  51584. if (this != &other)
  51585. {
  51586. lookAndFeel = other.lookAndFeel;
  51587. clear();
  51588. items.ensureStorageAllocated (other.items.size());
  51589. for (int i = 0; i < other.items.size(); ++i)
  51590. items.add (new MenuItemInfo (*(const MenuItemInfo*) other.items.getUnchecked(i)));
  51591. }
  51592. return *this;
  51593. }
  51594. PopupMenu::~PopupMenu() throw()
  51595. {
  51596. clear();
  51597. }
  51598. void PopupMenu::clear() throw()
  51599. {
  51600. for (int i = items.size(); --i >= 0;)
  51601. {
  51602. MenuItemInfo* const mi = (MenuItemInfo*) items.getUnchecked(i);
  51603. delete mi;
  51604. }
  51605. items.clear();
  51606. separatorPending = false;
  51607. }
  51608. void PopupMenu::addSeparatorIfPending()
  51609. {
  51610. if (separatorPending)
  51611. {
  51612. separatorPending = false;
  51613. if (items.size() > 0)
  51614. items.add (new MenuItemInfo());
  51615. }
  51616. }
  51617. void PopupMenu::addItem (const int itemResultId,
  51618. const String& itemText,
  51619. const bool isActive,
  51620. const bool isTicked,
  51621. const Image* const iconToUse) throw()
  51622. {
  51623. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  51624. // didn't pick anything, so you shouldn't use it as the id
  51625. // for an item..
  51626. addSeparatorIfPending();
  51627. items.add (new MenuItemInfo (itemResultId,
  51628. itemText,
  51629. isActive,
  51630. isTicked,
  51631. iconToUse,
  51632. Colours::black,
  51633. false,
  51634. 0, 0, 0));
  51635. }
  51636. void PopupMenu::addCommandItem (ApplicationCommandManager* commandManager,
  51637. const int commandID,
  51638. const String& displayName) throw()
  51639. {
  51640. jassert (commandManager != 0 && commandID != 0);
  51641. const ApplicationCommandInfo* const registeredInfo = commandManager->getCommandForID (commandID);
  51642. if (registeredInfo != 0)
  51643. {
  51644. ApplicationCommandInfo info (*registeredInfo);
  51645. ApplicationCommandTarget* const target = commandManager->getTargetForCommand (commandID, info);
  51646. addSeparatorIfPending();
  51647. items.add (new MenuItemInfo (commandID,
  51648. displayName.isNotEmpty() ? displayName
  51649. : info.shortName,
  51650. target != 0 && (info.flags & ApplicationCommandInfo::isDisabled) == 0,
  51651. (info.flags & ApplicationCommandInfo::isTicked) != 0,
  51652. 0,
  51653. Colours::black,
  51654. false,
  51655. 0, 0,
  51656. commandManager));
  51657. }
  51658. }
  51659. void PopupMenu::addColouredItem (const int itemResultId,
  51660. const String& itemText,
  51661. const Colour& itemTextColour,
  51662. const bool isActive,
  51663. const bool isTicked,
  51664. const Image* const iconToUse) throw()
  51665. {
  51666. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  51667. // didn't pick anything, so you shouldn't use it as the id
  51668. // for an item..
  51669. addSeparatorIfPending();
  51670. items.add (new MenuItemInfo (itemResultId,
  51671. itemText,
  51672. isActive,
  51673. isTicked,
  51674. iconToUse,
  51675. itemTextColour,
  51676. true,
  51677. 0, 0, 0));
  51678. }
  51679. void PopupMenu::addCustomItem (const int itemResultId,
  51680. PopupMenuCustomComponent* const customComponent) throw()
  51681. {
  51682. jassert (itemResultId != 0); // 0 is used as a return value to indicate that the user
  51683. // didn't pick anything, so you shouldn't use it as the id
  51684. // for an item..
  51685. addSeparatorIfPending();
  51686. items.add (new MenuItemInfo (itemResultId,
  51687. String::empty,
  51688. true,
  51689. false,
  51690. 0,
  51691. Colours::black,
  51692. false,
  51693. customComponent,
  51694. 0, 0));
  51695. }
  51696. class NormalComponentWrapper : public PopupMenuCustomComponent
  51697. {
  51698. public:
  51699. NormalComponentWrapper (Component* const comp,
  51700. const int w, const int h,
  51701. const bool triggerMenuItemAutomaticallyWhenClicked)
  51702. : PopupMenuCustomComponent (triggerMenuItemAutomaticallyWhenClicked),
  51703. width (w),
  51704. height (h)
  51705. {
  51706. addAndMakeVisible (comp);
  51707. }
  51708. ~NormalComponentWrapper() {}
  51709. void getIdealSize (int& idealWidth, int& idealHeight)
  51710. {
  51711. idealWidth = width;
  51712. idealHeight = height;
  51713. }
  51714. void resized()
  51715. {
  51716. if (getChildComponent(0) != 0)
  51717. getChildComponent(0)->setBounds (0, 0, getWidth(), getHeight());
  51718. }
  51719. juce_UseDebuggingNewOperator
  51720. private:
  51721. const int width, height;
  51722. NormalComponentWrapper (const NormalComponentWrapper&);
  51723. const NormalComponentWrapper& operator= (const NormalComponentWrapper&);
  51724. };
  51725. void PopupMenu::addCustomItem (const int itemResultId,
  51726. Component* customComponent,
  51727. int idealWidth, int idealHeight,
  51728. const bool triggerMenuItemAutomaticallyWhenClicked) throw()
  51729. {
  51730. addCustomItem (itemResultId,
  51731. new NormalComponentWrapper (customComponent,
  51732. idealWidth, idealHeight,
  51733. triggerMenuItemAutomaticallyWhenClicked));
  51734. }
  51735. void PopupMenu::addSubMenu (const String& subMenuName,
  51736. const PopupMenu& subMenu,
  51737. const bool isActive,
  51738. Image* const iconToUse,
  51739. const bool isTicked) throw()
  51740. {
  51741. addSeparatorIfPending();
  51742. items.add (new MenuItemInfo (0,
  51743. subMenuName,
  51744. isActive && (subMenu.getNumItems() > 0),
  51745. isTicked,
  51746. iconToUse,
  51747. Colours::black,
  51748. false,
  51749. 0,
  51750. &subMenu,
  51751. 0));
  51752. }
  51753. void PopupMenu::addSeparator() throw()
  51754. {
  51755. separatorPending = true;
  51756. }
  51757. class HeaderItemComponent : public PopupMenuCustomComponent
  51758. {
  51759. public:
  51760. HeaderItemComponent (const String& name)
  51761. : PopupMenuCustomComponent (false)
  51762. {
  51763. setName (name);
  51764. }
  51765. ~HeaderItemComponent()
  51766. {
  51767. }
  51768. void paint (Graphics& g)
  51769. {
  51770. Font f (getLookAndFeel().getPopupMenuFont());
  51771. f.setBold (true);
  51772. g.setFont (f);
  51773. g.setColour (findColour (PopupMenu::headerTextColourId));
  51774. g.drawFittedText (getName(),
  51775. 12, 0, getWidth() - 16, proportionOfHeight (0.8f),
  51776. Justification::bottomLeft, 1);
  51777. }
  51778. void getIdealSize (int& idealWidth,
  51779. int& idealHeight)
  51780. {
  51781. getLookAndFeel().getIdealPopupMenuItemSize (getName(), false, -1, idealWidth, idealHeight);
  51782. idealHeight += idealHeight / 2;
  51783. idealWidth += idealWidth / 4;
  51784. }
  51785. juce_UseDebuggingNewOperator
  51786. };
  51787. void PopupMenu::addSectionHeader (const String& title) throw()
  51788. {
  51789. addCustomItem (0X4734a34f, new HeaderItemComponent (title));
  51790. }
  51791. Component* PopupMenu::createMenuComponent (const int x, const int y, const int w, const int h,
  51792. const int itemIdThatMustBeVisible,
  51793. const int minimumWidth,
  51794. const int maximumNumColumns,
  51795. const int standardItemHeight,
  51796. const bool alignToRectangle,
  51797. Component* menuBarComponent,
  51798. ApplicationCommandManager** managerOfChosenCommand,
  51799. Component* const componentAttachedTo) throw()
  51800. {
  51801. PopupMenuWindow* const pw
  51802. = PopupMenuWindow::create (*this,
  51803. ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown(),
  51804. 0,
  51805. x, x + w,
  51806. y, y + h,
  51807. minimumWidth,
  51808. maximumNumColumns,
  51809. standardItemHeight,
  51810. alignToRectangle,
  51811. itemIdThatMustBeVisible,
  51812. menuBarComponent,
  51813. managerOfChosenCommand,
  51814. componentAttachedTo);
  51815. if (pw != 0)
  51816. pw->setVisible (true);
  51817. return pw;
  51818. }
  51819. int PopupMenu::showMenu (const int x, const int y, const int w, const int h,
  51820. const int itemIdThatMustBeVisible,
  51821. const int minimumWidth,
  51822. const int maximumNumColumns,
  51823. const int standardItemHeight,
  51824. const bool alignToRectangle,
  51825. Component* const componentAttachedTo) throw()
  51826. {
  51827. Component* const prevFocused = Component::getCurrentlyFocusedComponent();
  51828. ComponentDeletionWatcher* deletionChecker1 = 0;
  51829. if (prevFocused != 0)
  51830. deletionChecker1 = new ComponentDeletionWatcher (prevFocused);
  51831. Component* const prevTopLevel = (prevFocused != 0) ? prevFocused->getTopLevelComponent() : 0;
  51832. ComponentDeletionWatcher* deletionChecker2 = 0;
  51833. if (prevTopLevel != 0)
  51834. deletionChecker2 = new ComponentDeletionWatcher (prevTopLevel);
  51835. wasHiddenBecauseOfAppChange = false;
  51836. int result = 0;
  51837. ApplicationCommandManager* managerOfChosenCommand = 0;
  51838. Component* const popupComp = createMenuComponent (x, y, w, h,
  51839. itemIdThatMustBeVisible,
  51840. minimumWidth,
  51841. maximumNumColumns > 0 ? maximumNumColumns : 7,
  51842. standardItemHeight,
  51843. alignToRectangle, 0,
  51844. &managerOfChosenCommand,
  51845. componentAttachedTo);
  51846. if (popupComp != 0)
  51847. {
  51848. popupComp->enterModalState (false);
  51849. popupComp->toFront (false); // need to do this after making it modal, or it could
  51850. // be stuck behind other comps that are already modal..
  51851. result = popupComp->runModalLoop();
  51852. delete popupComp;
  51853. if (! wasHiddenBecauseOfAppChange)
  51854. {
  51855. if (deletionChecker2 != 0 && ! deletionChecker2->hasBeenDeleted())
  51856. prevTopLevel->toFront (true);
  51857. if (deletionChecker1 != 0 && ! deletionChecker1->hasBeenDeleted())
  51858. prevFocused->grabKeyboardFocus();
  51859. }
  51860. }
  51861. delete deletionChecker1;
  51862. delete deletionChecker2;
  51863. if (managerOfChosenCommand != 0 && result != 0)
  51864. {
  51865. ApplicationCommandTarget::InvocationInfo info (result);
  51866. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  51867. managerOfChosenCommand->invoke (info, true);
  51868. }
  51869. return result;
  51870. }
  51871. int PopupMenu::show (const int itemIdThatMustBeVisible,
  51872. const int minimumWidth,
  51873. const int maximumNumColumns,
  51874. const int standardItemHeight)
  51875. {
  51876. int x, y;
  51877. Desktop::getMousePosition (x, y);
  51878. return showAt (x, y,
  51879. itemIdThatMustBeVisible,
  51880. minimumWidth,
  51881. maximumNumColumns,
  51882. standardItemHeight);
  51883. }
  51884. int PopupMenu::showAt (const int screenX,
  51885. const int screenY,
  51886. const int itemIdThatMustBeVisible,
  51887. const int minimumWidth,
  51888. const int maximumNumColumns,
  51889. const int standardItemHeight)
  51890. {
  51891. return showMenu (screenX, screenY, 1, 1,
  51892. itemIdThatMustBeVisible,
  51893. minimumWidth, maximumNumColumns,
  51894. standardItemHeight,
  51895. false, 0);
  51896. }
  51897. int PopupMenu::showAt (Component* componentToAttachTo,
  51898. const int itemIdThatMustBeVisible,
  51899. const int minimumWidth,
  51900. const int maximumNumColumns,
  51901. const int standardItemHeight)
  51902. {
  51903. if (componentToAttachTo != 0)
  51904. {
  51905. return showMenu (componentToAttachTo->getScreenX(),
  51906. componentToAttachTo->getScreenY(),
  51907. componentToAttachTo->getWidth(),
  51908. componentToAttachTo->getHeight(),
  51909. itemIdThatMustBeVisible,
  51910. minimumWidth,
  51911. maximumNumColumns,
  51912. standardItemHeight,
  51913. true, componentToAttachTo);
  51914. }
  51915. else
  51916. {
  51917. return show (itemIdThatMustBeVisible,
  51918. minimumWidth,
  51919. maximumNumColumns,
  51920. standardItemHeight);
  51921. }
  51922. }
  51923. void JUCE_CALLTYPE PopupMenu::dismissAllActiveMenus() throw()
  51924. {
  51925. for (int i = activeMenuWindows.size(); --i >= 0;)
  51926. {
  51927. PopupMenuWindow* const pmw = (PopupMenuWindow*) activeMenuWindows[i];
  51928. if (pmw != 0)
  51929. pmw->dismissMenu (0);
  51930. }
  51931. }
  51932. int PopupMenu::getNumItems() const throw()
  51933. {
  51934. int num = 0;
  51935. for (int i = items.size(); --i >= 0;)
  51936. if (! ((MenuItemInfo*) items.getUnchecked(i))->isSeparator)
  51937. ++num;
  51938. return num;
  51939. }
  51940. bool PopupMenu::containsCommandItem (const int commandID) const throw()
  51941. {
  51942. for (int i = items.size(); --i >= 0;)
  51943. {
  51944. const MenuItemInfo* mi = (const MenuItemInfo*) items.getUnchecked (i);
  51945. if ((mi->itemId == commandID && mi->commandManager != 0)
  51946. || (mi->subMenu != 0 && mi->subMenu->containsCommandItem (commandID)))
  51947. {
  51948. return true;
  51949. }
  51950. }
  51951. return false;
  51952. }
  51953. bool PopupMenu::containsAnyActiveItems() const throw()
  51954. {
  51955. for (int i = items.size(); --i >= 0;)
  51956. {
  51957. const MenuItemInfo* const mi = (const MenuItemInfo*) items.getUnchecked (i);
  51958. if (mi->subMenu != 0)
  51959. {
  51960. if (mi->subMenu->containsAnyActiveItems())
  51961. return true;
  51962. }
  51963. else if (mi->active)
  51964. {
  51965. return true;
  51966. }
  51967. }
  51968. return false;
  51969. }
  51970. void PopupMenu::setLookAndFeel (LookAndFeel* const newLookAndFeel) throw()
  51971. {
  51972. lookAndFeel = newLookAndFeel;
  51973. }
  51974. PopupMenuCustomComponent::PopupMenuCustomComponent (const bool isTriggeredAutomatically_)
  51975. : refCount_ (0),
  51976. isHighlighted (false),
  51977. isTriggeredAutomatically (isTriggeredAutomatically_)
  51978. {
  51979. }
  51980. PopupMenuCustomComponent::~PopupMenuCustomComponent()
  51981. {
  51982. jassert (refCount_ == 0); // should be deleted only by the menu component, as they keep a ref-count.
  51983. }
  51984. void PopupMenuCustomComponent::triggerMenuItem()
  51985. {
  51986. MenuItemComponent* const mic = dynamic_cast<MenuItemComponent*> (getParentComponent());
  51987. if (mic != 0)
  51988. {
  51989. PopupMenuWindow* const pmw = dynamic_cast<PopupMenuWindow*> (mic->getParentComponent());
  51990. if (pmw != 0)
  51991. {
  51992. pmw->dismissMenu (&mic->itemInfo);
  51993. }
  51994. else
  51995. {
  51996. // something must have gone wrong with the component hierarchy if this happens..
  51997. jassertfalse
  51998. }
  51999. }
  52000. else
  52001. {
  52002. // why isn't this component inside a menu? Not much point triggering the item if
  52003. // there's no menu.
  52004. jassertfalse
  52005. }
  52006. }
  52007. PopupMenu::MenuItemIterator::MenuItemIterator (const PopupMenu& menu_) throw()
  52008. : subMenu (0),
  52009. itemId (0),
  52010. isSeparator (false),
  52011. isTicked (false),
  52012. isEnabled (false),
  52013. isCustomComponent (false),
  52014. isSectionHeader (false),
  52015. customColour (0),
  52016. customImage (0),
  52017. menu (menu_),
  52018. index (0)
  52019. {
  52020. }
  52021. PopupMenu::MenuItemIterator::~MenuItemIterator() throw()
  52022. {
  52023. }
  52024. bool PopupMenu::MenuItemIterator::next() throw()
  52025. {
  52026. if (index >= menu.items.size())
  52027. return false;
  52028. const MenuItemInfo* const item = (const MenuItemInfo*) menu.items.getUnchecked (index);
  52029. ++index;
  52030. itemName = item->customComp != 0 ? item->customComp->getName() : item->text;
  52031. subMenu = item->subMenu;
  52032. itemId = item->itemId;
  52033. isSeparator = item->isSeparator;
  52034. isTicked = item->isTicked;
  52035. isEnabled = item->active;
  52036. isSectionHeader = dynamic_cast <HeaderItemComponent*> (item->customComp) != 0;
  52037. isCustomComponent = (! isSectionHeader) && item->customComp != 0;
  52038. customColour = item->usesColour ? &(item->textColour) : 0;
  52039. customImage = item->image;
  52040. commandManager = item->commandManager;
  52041. return true;
  52042. }
  52043. END_JUCE_NAMESPACE
  52044. /********* End of inlined file: juce_PopupMenu.cpp *********/
  52045. /********* Start of inlined file: juce_ComponentDragger.cpp *********/
  52046. BEGIN_JUCE_NAMESPACE
  52047. ComponentDragger::ComponentDragger()
  52048. : constrainer (0),
  52049. originalX (0),
  52050. originalY (0)
  52051. {
  52052. }
  52053. ComponentDragger::~ComponentDragger()
  52054. {
  52055. }
  52056. void ComponentDragger::startDraggingComponent (Component* const componentToDrag,
  52057. ComponentBoundsConstrainer* const constrainer_)
  52058. {
  52059. jassert (componentToDrag->isValidComponent());
  52060. if (componentToDrag->isValidComponent())
  52061. {
  52062. constrainer = constrainer_;
  52063. originalX = 0;
  52064. originalY = 0;
  52065. componentToDrag->relativePositionToGlobal (originalX, originalY);
  52066. }
  52067. }
  52068. void ComponentDragger::dragComponent (Component* const componentToDrag, const MouseEvent& e)
  52069. {
  52070. jassert (componentToDrag->isValidComponent());
  52071. jassert (e.mods.isAnyMouseButtonDown()); // (the event has to be a drag event..)
  52072. if (componentToDrag->isValidComponent())
  52073. {
  52074. int x = originalX + e.getDistanceFromDragStartX();
  52075. int y = originalY + e.getDistanceFromDragStartY();
  52076. int w = componentToDrag->getWidth();
  52077. int h = componentToDrag->getHeight();
  52078. const Component* const parentComp = componentToDrag->getParentComponent();
  52079. if (parentComp != 0)
  52080. parentComp->globalPositionToRelative (x, y);
  52081. if (constrainer != 0)
  52082. constrainer->setBoundsForComponent (componentToDrag, x, y, w, h,
  52083. false, false, false, false);
  52084. else
  52085. componentToDrag->setBounds (x, y, w, h);
  52086. }
  52087. }
  52088. END_JUCE_NAMESPACE
  52089. /********* End of inlined file: juce_ComponentDragger.cpp *********/
  52090. /********* Start of inlined file: juce_DragAndDropContainer.cpp *********/
  52091. BEGIN_JUCE_NAMESPACE
  52092. bool juce_performDragDropFiles (const StringArray& files, const bool copyFiles, bool& shouldStop);
  52093. bool juce_performDragDropText (const String& text, bool& shouldStop);
  52094. class DragImageComponent : public Component,
  52095. public Timer
  52096. {
  52097. private:
  52098. Image* image;
  52099. Component* const source;
  52100. DragAndDropContainer* const owner;
  52101. ComponentDeletionWatcher* sourceWatcher;
  52102. Component* mouseDragSource;
  52103. ComponentDeletionWatcher* mouseDragSourceWatcher;
  52104. DragAndDropTarget* currentlyOver;
  52105. String dragDesc;
  52106. int xOff, yOff;
  52107. bool hasCheckedForExternalDrag, drawImage;
  52108. DragImageComponent (const DragImageComponent&);
  52109. const DragImageComponent& operator= (const DragImageComponent&);
  52110. public:
  52111. DragImageComponent (Image* const im,
  52112. const String& desc,
  52113. Component* const s,
  52114. DragAndDropContainer* const o)
  52115. : image (im),
  52116. source (s),
  52117. owner (o),
  52118. currentlyOver (0),
  52119. dragDesc (desc),
  52120. hasCheckedForExternalDrag (false),
  52121. drawImage (true)
  52122. {
  52123. setSize (im->getWidth(), im->getHeight());
  52124. sourceWatcher = new ComponentDeletionWatcher (source);
  52125. mouseDragSource = Component::getComponentUnderMouse();
  52126. if (mouseDragSource == 0)
  52127. mouseDragSource = source;
  52128. mouseDragSourceWatcher = new ComponentDeletionWatcher (mouseDragSource);
  52129. mouseDragSource->addMouseListener (this, false);
  52130. int mx, my;
  52131. Desktop::getLastMouseDownPosition (mx, my);
  52132. source->globalPositionToRelative (mx, my);
  52133. xOff = jlimit (0, im->getWidth(), mx);
  52134. yOff = jlimit (0, im->getHeight(), my);
  52135. startTimer (200);
  52136. setInterceptsMouseClicks (false, false);
  52137. setAlwaysOnTop (true);
  52138. }
  52139. ~DragImageComponent()
  52140. {
  52141. if (owner->dragImageComponent == this)
  52142. owner->dragImageComponent = 0;
  52143. if (((Component*) currentlyOver)->isValidComponent())
  52144. {
  52145. Component* const over = dynamic_cast <Component*> (currentlyOver);
  52146. if (over != 0
  52147. && over->isValidComponent()
  52148. && source->isValidComponent()
  52149. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  52150. {
  52151. currentlyOver->itemDragExit (dragDesc, source);
  52152. }
  52153. }
  52154. if (! mouseDragSourceWatcher->hasBeenDeleted())
  52155. mouseDragSource->removeMouseListener (this);
  52156. delete mouseDragSourceWatcher;
  52157. delete sourceWatcher;
  52158. delete image;
  52159. }
  52160. void paint (Graphics& g)
  52161. {
  52162. if (isOpaque())
  52163. g.fillAll (Colours::white);
  52164. if (drawImage)
  52165. {
  52166. g.setOpacity (1.0f);
  52167. g.drawImageAt (image, 0, 0);
  52168. }
  52169. }
  52170. DragAndDropTarget* findTarget (const int screenX, const int screenY,
  52171. int& relX, int& relY) const throw()
  52172. {
  52173. Component* hit = getParentComponent();
  52174. if (hit == 0)
  52175. {
  52176. hit = Desktop::getInstance().findComponentAt (screenX, screenY);
  52177. }
  52178. else
  52179. {
  52180. int rx = screenX, ry = screenY;
  52181. hit->globalPositionToRelative (rx, ry);
  52182. hit = hit->getComponentAt (rx, ry);
  52183. }
  52184. while (hit != 0)
  52185. {
  52186. DragAndDropTarget* const ddt = dynamic_cast <DragAndDropTarget*> (hit);
  52187. if (ddt != 0 && ddt->isInterestedInDragSource (dragDesc, source))
  52188. {
  52189. relX = screenX;
  52190. relY = screenY;
  52191. hit->globalPositionToRelative (relX, relY);
  52192. return ddt;
  52193. }
  52194. hit = hit->getParentComponent();
  52195. }
  52196. return 0;
  52197. }
  52198. void mouseUp (const MouseEvent& e)
  52199. {
  52200. if (e.originalComponent != this)
  52201. {
  52202. if (! mouseDragSourceWatcher->hasBeenDeleted())
  52203. mouseDragSource->removeMouseListener (this);
  52204. bool dropAccepted = false;
  52205. DragAndDropTarget* ddt = 0;
  52206. int relX = 0, relY = 0;
  52207. if (isVisible())
  52208. {
  52209. setVisible (false);
  52210. ddt = findTarget (e.getScreenX(),
  52211. e.getScreenY(),
  52212. relX, relY);
  52213. // fade this component and remove it - it'll be deleted later by the timer callback
  52214. dropAccepted = ddt != 0;
  52215. setVisible (true);
  52216. if (dropAccepted || sourceWatcher->hasBeenDeleted())
  52217. {
  52218. fadeOutComponent (120);
  52219. }
  52220. else
  52221. {
  52222. int targetX = source->getWidth() / 2;
  52223. int targetY = source->getHeight() / 2;
  52224. source->relativePositionToGlobal (targetX, targetY);
  52225. int ourCentreX = getWidth() / 2;
  52226. int ourCentreY = getHeight() / 2;
  52227. relativePositionToGlobal (ourCentreX, ourCentreY);
  52228. fadeOutComponent (120,
  52229. targetX - ourCentreX,
  52230. targetY - ourCentreY);
  52231. }
  52232. }
  52233. if (getParentComponent() != 0)
  52234. getParentComponent()->removeChildComponent (this);
  52235. if (dropAccepted && ddt != 0)
  52236. ddt->itemDropped (dragDesc, source, relX, relY);
  52237. // careful - this object could now be deleted..
  52238. }
  52239. }
  52240. void updateLocation (const bool canDoExternalDrag, int x, int y)
  52241. {
  52242. int newX = x - xOff;
  52243. int newY = y - yOff;
  52244. if (getParentComponent() != 0)
  52245. getParentComponent()->globalPositionToRelative (newX, newY);
  52246. if (newX != getX() || newY != getY())
  52247. {
  52248. setTopLeftPosition (newX, newY);
  52249. int relX = 0, relY = 0;
  52250. DragAndDropTarget* const ddt = findTarget (x, y, relX, relY);
  52251. drawImage = (ddt == 0) || ddt->shouldDrawDragImageWhenOver();
  52252. if (ddt != currentlyOver)
  52253. {
  52254. Component* const over = dynamic_cast <Component*> (currentlyOver);
  52255. if (over != 0
  52256. && over->isValidComponent()
  52257. && ! (sourceWatcher->hasBeenDeleted())
  52258. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  52259. {
  52260. currentlyOver->itemDragExit (dragDesc, source);
  52261. }
  52262. currentlyOver = ddt;
  52263. if (currentlyOver != 0
  52264. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  52265. currentlyOver->itemDragEnter (dragDesc, source, relX, relY);
  52266. }
  52267. if (currentlyOver != 0
  52268. && currentlyOver->isInterestedInDragSource (dragDesc, source))
  52269. currentlyOver->itemDragMove (dragDesc, source, relX, relY);
  52270. if (currentlyOver == 0
  52271. && canDoExternalDrag
  52272. && ! hasCheckedForExternalDrag)
  52273. {
  52274. if (Desktop::getInstance().findComponentAt (x, y) == 0)
  52275. {
  52276. hasCheckedForExternalDrag = true;
  52277. StringArray files;
  52278. bool canMoveFiles = false;
  52279. if (owner->shouldDropFilesWhenDraggedExternally (dragDesc, source, files, canMoveFiles)
  52280. && files.size() > 0)
  52281. {
  52282. ComponentDeletionWatcher cdw (this);
  52283. setVisible (false);
  52284. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  52285. DragAndDropContainer::performExternalDragDropOfFiles (files, canMoveFiles);
  52286. if (! cdw.hasBeenDeleted())
  52287. delete this;
  52288. return;
  52289. }
  52290. }
  52291. }
  52292. }
  52293. }
  52294. void mouseDrag (const MouseEvent& e)
  52295. {
  52296. if (e.originalComponent != this)
  52297. updateLocation (true, e.getScreenX(), e.getScreenY());
  52298. }
  52299. void timerCallback()
  52300. {
  52301. if (sourceWatcher->hasBeenDeleted())
  52302. {
  52303. delete this;
  52304. }
  52305. else if (! isMouseButtonDownAnywhere())
  52306. {
  52307. if (! mouseDragSourceWatcher->hasBeenDeleted())
  52308. mouseDragSource->removeMouseListener (this);
  52309. delete this;
  52310. }
  52311. }
  52312. };
  52313. DragAndDropContainer::DragAndDropContainer()
  52314. : dragImageComponent (0)
  52315. {
  52316. }
  52317. DragAndDropContainer::~DragAndDropContainer()
  52318. {
  52319. if (dragImageComponent != 0)
  52320. delete dragImageComponent;
  52321. }
  52322. void DragAndDropContainer::startDragging (const String& sourceDescription,
  52323. Component* sourceComponent,
  52324. Image* im,
  52325. const bool allowDraggingToExternalWindows)
  52326. {
  52327. if (dragImageComponent != 0)
  52328. {
  52329. if (im != 0)
  52330. delete im;
  52331. }
  52332. else
  52333. {
  52334. Component* const thisComp = dynamic_cast <Component*> (this);
  52335. if (thisComp != 0)
  52336. {
  52337. int mx, my;
  52338. Desktop::getLastMouseDownPosition (mx, my);
  52339. if (im == 0)
  52340. {
  52341. im = sourceComponent->createComponentSnapshot (Rectangle (0, 0, sourceComponent->getWidth(), sourceComponent->getHeight()));
  52342. if (im->getFormat() != Image::ARGB)
  52343. {
  52344. Image* newIm = new Image (Image::ARGB, im->getWidth(), im->getHeight(), true);
  52345. Graphics g2 (*newIm);
  52346. g2.drawImageAt (im, 0, 0);
  52347. delete im;
  52348. im = newIm;
  52349. }
  52350. im->multiplyAllAlphas (0.6f);
  52351. const int lo = 150;
  52352. const int hi = 400;
  52353. int rx = mx, ry = my;
  52354. sourceComponent->globalPositionToRelative (rx, ry);
  52355. const int cx = jlimit (0, im->getWidth(), rx);
  52356. const int cy = jlimit (0, im->getHeight(), ry);
  52357. for (int y = im->getHeight(); --y >= 0;)
  52358. {
  52359. const double dy = (y - cy) * (y - cy);
  52360. for (int x = im->getWidth(); --x >= 0;)
  52361. {
  52362. const int dx = x - cx;
  52363. const int distance = roundDoubleToInt (sqrt (dx * dx + dy));
  52364. if (distance > lo)
  52365. {
  52366. const float alpha = (distance > hi) ? 0
  52367. : (hi - distance) / (float) (hi - lo)
  52368. + Random::getSystemRandom().nextFloat() * 0.008f;
  52369. im->multiplyAlphaAt (x, y, alpha);
  52370. }
  52371. }
  52372. }
  52373. }
  52374. DragImageComponent* const dic
  52375. = new DragImageComponent (im,
  52376. sourceDescription,
  52377. sourceComponent,
  52378. this);
  52379. dragImageComponent = dic;
  52380. currentDragDesc = sourceDescription;
  52381. if (allowDraggingToExternalWindows)
  52382. {
  52383. if (! Desktop::canUseSemiTransparentWindows())
  52384. dic->setOpaque (true);
  52385. dic->addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  52386. | ComponentPeer::windowIsTemporary);
  52387. }
  52388. else
  52389. thisComp->addChildComponent (dic);
  52390. dic->updateLocation (false, mx, my);
  52391. dic->setVisible (true);
  52392. }
  52393. else
  52394. {
  52395. // this class must only be implemented by an object that
  52396. // is also a Component.
  52397. jassertfalse
  52398. if (im != 0)
  52399. delete im;
  52400. }
  52401. }
  52402. }
  52403. bool DragAndDropContainer::isDragAndDropActive() const
  52404. {
  52405. return dragImageComponent != 0;
  52406. }
  52407. const String DragAndDropContainer::getCurrentDragDescription() const
  52408. {
  52409. return (dragImageComponent != 0) ? currentDragDesc
  52410. : String::empty;
  52411. }
  52412. DragAndDropContainer* DragAndDropContainer::findParentDragContainerFor (Component* c)
  52413. {
  52414. if (c == 0)
  52415. return 0;
  52416. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  52417. return c->findParentComponentOfClass ((DragAndDropContainer*) 0);
  52418. }
  52419. bool DragAndDropContainer::shouldDropFilesWhenDraggedExternally (const String&, Component*, StringArray&, bool&)
  52420. {
  52421. return false;
  52422. }
  52423. void DragAndDropTarget::itemDragEnter (const String&, Component*, int, int)
  52424. {
  52425. }
  52426. void DragAndDropTarget::itemDragMove (const String&, Component*, int, int)
  52427. {
  52428. }
  52429. void DragAndDropTarget::itemDragExit (const String&, Component*)
  52430. {
  52431. }
  52432. bool DragAndDropTarget::shouldDrawDragImageWhenOver()
  52433. {
  52434. return true;
  52435. }
  52436. void FileDragAndDropTarget::fileDragEnter (const StringArray&, int, int)
  52437. {
  52438. }
  52439. void FileDragAndDropTarget::fileDragMove (const StringArray&, int, int)
  52440. {
  52441. }
  52442. void FileDragAndDropTarget::fileDragExit (const StringArray&)
  52443. {
  52444. }
  52445. END_JUCE_NAMESPACE
  52446. /********* End of inlined file: juce_DragAndDropContainer.cpp *********/
  52447. /********* Start of inlined file: juce_MouseCursor.cpp *********/
  52448. BEGIN_JUCE_NAMESPACE
  52449. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw();
  52450. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw();
  52451. // isStandard set depending on which interface was used to create the cursor
  52452. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw();
  52453. static CriticalSection mouseCursorLock;
  52454. static VoidArray standardCursors (2);
  52455. class RefCountedMouseCursor
  52456. {
  52457. public:
  52458. RefCountedMouseCursor (const MouseCursor::StandardCursorType t) throw()
  52459. : refCount (1),
  52460. standardType (t),
  52461. isStandard (true)
  52462. {
  52463. handle = juce_createStandardMouseCursor (standardType);
  52464. standardCursors.add (this);
  52465. }
  52466. RefCountedMouseCursor (Image& image,
  52467. const int hotSpotX,
  52468. const int hotSpotY) throw()
  52469. : refCount (1),
  52470. standardType (MouseCursor::NormalCursor),
  52471. isStandard (false)
  52472. {
  52473. handle = juce_createMouseCursorFromImage (image, hotSpotX, hotSpotY);
  52474. }
  52475. ~RefCountedMouseCursor() throw()
  52476. {
  52477. juce_deleteMouseCursor (handle, isStandard);
  52478. standardCursors.removeValue (this);
  52479. }
  52480. void decRef() throw()
  52481. {
  52482. if (--refCount == 0)
  52483. delete this;
  52484. }
  52485. void incRef() throw()
  52486. {
  52487. ++refCount;
  52488. }
  52489. void* getHandle() const throw()
  52490. {
  52491. return handle;
  52492. }
  52493. static RefCountedMouseCursor* findInstance (MouseCursor::StandardCursorType type) throw()
  52494. {
  52495. const ScopedLock sl (mouseCursorLock);
  52496. for (int i = 0; i < standardCursors.size(); i++)
  52497. {
  52498. RefCountedMouseCursor* const r = (RefCountedMouseCursor*) standardCursors.getUnchecked(i);
  52499. if (r->standardType == type)
  52500. {
  52501. r->incRef();
  52502. return r;
  52503. }
  52504. }
  52505. return new RefCountedMouseCursor (type);
  52506. }
  52507. juce_UseDebuggingNewOperator
  52508. private:
  52509. void* handle;
  52510. int refCount;
  52511. const MouseCursor::StandardCursorType standardType;
  52512. const bool isStandard;
  52513. const RefCountedMouseCursor& operator= (const RefCountedMouseCursor&);
  52514. };
  52515. MouseCursor::MouseCursor() throw()
  52516. {
  52517. cursorHandle = RefCountedMouseCursor::findInstance (NormalCursor);
  52518. }
  52519. MouseCursor::MouseCursor (const StandardCursorType type) throw()
  52520. {
  52521. cursorHandle = RefCountedMouseCursor::findInstance (type);
  52522. }
  52523. MouseCursor::MouseCursor (Image& image,
  52524. const int hotSpotX,
  52525. const int hotSpotY) throw()
  52526. {
  52527. cursorHandle = new RefCountedMouseCursor (image, hotSpotX, hotSpotY);
  52528. }
  52529. MouseCursor::MouseCursor (const MouseCursor& other) throw()
  52530. : cursorHandle (other.cursorHandle)
  52531. {
  52532. const ScopedLock sl (mouseCursorLock);
  52533. cursorHandle->incRef();
  52534. }
  52535. MouseCursor::~MouseCursor() throw()
  52536. {
  52537. const ScopedLock sl (mouseCursorLock);
  52538. cursorHandle->decRef();
  52539. }
  52540. const MouseCursor& MouseCursor::operator= (const MouseCursor& other) throw()
  52541. {
  52542. if (this != &other)
  52543. {
  52544. const ScopedLock sl (mouseCursorLock);
  52545. cursorHandle->decRef();
  52546. cursorHandle = other.cursorHandle;
  52547. cursorHandle->incRef();
  52548. }
  52549. return *this;
  52550. }
  52551. bool MouseCursor::operator== (const MouseCursor& other) const throw()
  52552. {
  52553. return cursorHandle == other.cursorHandle;
  52554. }
  52555. bool MouseCursor::operator!= (const MouseCursor& other) const throw()
  52556. {
  52557. return cursorHandle != other.cursorHandle;
  52558. }
  52559. void* MouseCursor::getHandle() const throw()
  52560. {
  52561. return cursorHandle->getHandle();
  52562. }
  52563. void MouseCursor::showWaitCursor() throw()
  52564. {
  52565. const MouseCursor mc (MouseCursor::WaitCursor);
  52566. mc.showInAllWindows();
  52567. }
  52568. void MouseCursor::hideWaitCursor() throw()
  52569. {
  52570. if (Component::getComponentUnderMouse()->isValidComponent())
  52571. {
  52572. Component::getComponentUnderMouse()->getMouseCursor().showInAllWindows();
  52573. }
  52574. else
  52575. {
  52576. const MouseCursor mc (MouseCursor::NormalCursor);
  52577. mc.showInAllWindows();
  52578. }
  52579. }
  52580. END_JUCE_NAMESPACE
  52581. /********* End of inlined file: juce_MouseCursor.cpp *********/
  52582. /********* Start of inlined file: juce_MouseEvent.cpp *********/
  52583. BEGIN_JUCE_NAMESPACE
  52584. MouseEvent::MouseEvent (const int x_,
  52585. const int y_,
  52586. const ModifierKeys& mods_,
  52587. Component* const originator,
  52588. const Time& eventTime_,
  52589. const int mouseDownX_,
  52590. const int mouseDownY_,
  52591. const Time& mouseDownTime_,
  52592. const int numberOfClicks_,
  52593. const bool mouseWasDragged) throw()
  52594. : x (x_),
  52595. y (y_),
  52596. mods (mods_),
  52597. eventComponent (originator),
  52598. originalComponent (originator),
  52599. eventTime (eventTime_),
  52600. mouseDownX (mouseDownX_),
  52601. mouseDownY (mouseDownY_),
  52602. mouseDownTime (mouseDownTime_),
  52603. numberOfClicks (numberOfClicks_),
  52604. wasMovedSinceMouseDown (mouseWasDragged)
  52605. {
  52606. }
  52607. MouseEvent::~MouseEvent() throw()
  52608. {
  52609. }
  52610. bool MouseEvent::mouseWasClicked() const throw()
  52611. {
  52612. return ! wasMovedSinceMouseDown;
  52613. }
  52614. int MouseEvent::getMouseDownX() const throw()
  52615. {
  52616. return mouseDownX;
  52617. }
  52618. int MouseEvent::getMouseDownY() const throw()
  52619. {
  52620. return mouseDownY;
  52621. }
  52622. int MouseEvent::getDistanceFromDragStartX() const throw()
  52623. {
  52624. return x - mouseDownX;
  52625. }
  52626. int MouseEvent::getDistanceFromDragStartY() const throw()
  52627. {
  52628. return y - mouseDownY;
  52629. }
  52630. int MouseEvent::getDistanceFromDragStart() const throw()
  52631. {
  52632. return roundDoubleToInt (juce_hypot (getDistanceFromDragStartX(),
  52633. getDistanceFromDragStartY()));
  52634. }
  52635. int MouseEvent::getLengthOfMousePress() const throw()
  52636. {
  52637. if (mouseDownTime.toMilliseconds() > 0)
  52638. return jmax (0, (int) (eventTime - mouseDownTime).inMilliseconds());
  52639. return 0;
  52640. }
  52641. int MouseEvent::getScreenX() const throw()
  52642. {
  52643. int sx = x, sy = y;
  52644. eventComponent->relativePositionToGlobal (sx, sy);
  52645. return sx;
  52646. }
  52647. int MouseEvent::getScreenY() const throw()
  52648. {
  52649. int sx = x, sy = y;
  52650. eventComponent->relativePositionToGlobal (sx, sy);
  52651. return sy;
  52652. }
  52653. int MouseEvent::getMouseDownScreenX() const throw()
  52654. {
  52655. int sx = mouseDownX, sy = mouseDownY;
  52656. eventComponent->relativePositionToGlobal (sx, sy);
  52657. return sx;
  52658. }
  52659. int MouseEvent::getMouseDownScreenY() const throw()
  52660. {
  52661. int sx = mouseDownX, sy = mouseDownY;
  52662. eventComponent->relativePositionToGlobal (sx, sy);
  52663. return sy;
  52664. }
  52665. const MouseEvent MouseEvent::getEventRelativeTo (Component* const otherComponent) const throw()
  52666. {
  52667. if (otherComponent == 0)
  52668. {
  52669. jassertfalse
  52670. return *this;
  52671. }
  52672. MouseEvent me (*this);
  52673. eventComponent->relativePositionToOtherComponent (otherComponent, me.x, me.y);
  52674. eventComponent->relativePositionToOtherComponent (otherComponent, me.mouseDownX, me.mouseDownY);
  52675. me.eventComponent = otherComponent;
  52676. return me;
  52677. }
  52678. static int doubleClickTimeOutMs = 400;
  52679. void MouseEvent::setDoubleClickTimeout (const int newTime) throw()
  52680. {
  52681. doubleClickTimeOutMs = newTime;
  52682. }
  52683. int MouseEvent::getDoubleClickTimeout() throw()
  52684. {
  52685. return doubleClickTimeOutMs;
  52686. }
  52687. END_JUCE_NAMESPACE
  52688. /********* End of inlined file: juce_MouseEvent.cpp *********/
  52689. /********* Start of inlined file: juce_MouseHoverDetector.cpp *********/
  52690. BEGIN_JUCE_NAMESPACE
  52691. MouseHoverDetector::MouseHoverDetector (const int hoverTimeMillisecs_)
  52692. : source (0),
  52693. hoverTimeMillisecs (hoverTimeMillisecs_),
  52694. hasJustHovered (false)
  52695. {
  52696. internalTimer.owner = this;
  52697. }
  52698. MouseHoverDetector::~MouseHoverDetector()
  52699. {
  52700. setHoverComponent (0);
  52701. }
  52702. void MouseHoverDetector::setHoverTimeMillisecs (const int newTimeInMillisecs)
  52703. {
  52704. hoverTimeMillisecs = newTimeInMillisecs;
  52705. }
  52706. void MouseHoverDetector::setHoverComponent (Component* const newSourceComponent)
  52707. {
  52708. if (source != newSourceComponent)
  52709. {
  52710. internalTimer.stopTimer();
  52711. hasJustHovered = false;
  52712. if (source != 0)
  52713. {
  52714. // ! you need to delete the hover detector before deleting its component
  52715. jassert (source->isValidComponent());
  52716. source->removeMouseListener (&internalTimer);
  52717. }
  52718. source = newSourceComponent;
  52719. if (newSourceComponent != 0)
  52720. newSourceComponent->addMouseListener (&internalTimer, false);
  52721. }
  52722. }
  52723. void MouseHoverDetector::hoverTimerCallback()
  52724. {
  52725. internalTimer.stopTimer();
  52726. if (source != 0)
  52727. {
  52728. int mx, my;
  52729. source->getMouseXYRelative (mx, my);
  52730. if (source->reallyContains (mx, my, false))
  52731. {
  52732. hasJustHovered = true;
  52733. mouseHovered (mx, my);
  52734. }
  52735. }
  52736. }
  52737. void MouseHoverDetector::checkJustHoveredCallback()
  52738. {
  52739. if (hasJustHovered)
  52740. {
  52741. hasJustHovered = false;
  52742. mouseMovedAfterHover();
  52743. }
  52744. }
  52745. void MouseHoverDetector::HoverDetectorInternal::timerCallback()
  52746. {
  52747. owner->hoverTimerCallback();
  52748. }
  52749. void MouseHoverDetector::HoverDetectorInternal::mouseEnter (const MouseEvent&)
  52750. {
  52751. stopTimer();
  52752. owner->checkJustHoveredCallback();
  52753. }
  52754. void MouseHoverDetector::HoverDetectorInternal::mouseExit (const MouseEvent&)
  52755. {
  52756. stopTimer();
  52757. owner->checkJustHoveredCallback();
  52758. }
  52759. void MouseHoverDetector::HoverDetectorInternal::mouseDown (const MouseEvent&)
  52760. {
  52761. stopTimer();
  52762. owner->checkJustHoveredCallback();
  52763. }
  52764. void MouseHoverDetector::HoverDetectorInternal::mouseUp (const MouseEvent&)
  52765. {
  52766. stopTimer();
  52767. owner->checkJustHoveredCallback();
  52768. }
  52769. void MouseHoverDetector::HoverDetectorInternal::mouseMove (const MouseEvent& e)
  52770. {
  52771. if (lastX != e.x || lastY != e.y) // to avoid fake mouse-moves setting it off
  52772. {
  52773. lastX = e.x;
  52774. lastY = e.y;
  52775. if (owner->source != 0)
  52776. startTimer (owner->hoverTimeMillisecs);
  52777. owner->checkJustHoveredCallback();
  52778. }
  52779. }
  52780. void MouseHoverDetector::HoverDetectorInternal::mouseWheelMove (const MouseEvent&, float, float)
  52781. {
  52782. stopTimer();
  52783. owner->checkJustHoveredCallback();
  52784. }
  52785. END_JUCE_NAMESPACE
  52786. /********* End of inlined file: juce_MouseHoverDetector.cpp *********/
  52787. /********* Start of inlined file: juce_MouseListener.cpp *********/
  52788. BEGIN_JUCE_NAMESPACE
  52789. void MouseListener::mouseEnter (const MouseEvent&)
  52790. {
  52791. }
  52792. void MouseListener::mouseExit (const MouseEvent&)
  52793. {
  52794. }
  52795. void MouseListener::mouseDown (const MouseEvent&)
  52796. {
  52797. }
  52798. void MouseListener::mouseUp (const MouseEvent&)
  52799. {
  52800. }
  52801. void MouseListener::mouseDrag (const MouseEvent&)
  52802. {
  52803. }
  52804. void MouseListener::mouseMove (const MouseEvent&)
  52805. {
  52806. }
  52807. void MouseListener::mouseDoubleClick (const MouseEvent&)
  52808. {
  52809. }
  52810. void MouseListener::mouseWheelMove (const MouseEvent&, float, float)
  52811. {
  52812. }
  52813. END_JUCE_NAMESPACE
  52814. /********* End of inlined file: juce_MouseListener.cpp *********/
  52815. /********* Start of inlined file: juce_BooleanPropertyComponent.cpp *********/
  52816. BEGIN_JUCE_NAMESPACE
  52817. BooleanPropertyComponent::BooleanPropertyComponent (const String& name,
  52818. const String& buttonTextWhenTrue,
  52819. const String& buttonTextWhenFalse)
  52820. : PropertyComponent (name),
  52821. onText (buttonTextWhenTrue),
  52822. offText (buttonTextWhenFalse)
  52823. {
  52824. addAndMakeVisible (button = new ToggleButton (String::empty));
  52825. button->setClickingTogglesState (false);
  52826. button->addButtonListener (this);
  52827. }
  52828. BooleanPropertyComponent::~BooleanPropertyComponent()
  52829. {
  52830. deleteAllChildren();
  52831. }
  52832. void BooleanPropertyComponent::paint (Graphics& g)
  52833. {
  52834. PropertyComponent::paint (g);
  52835. const Rectangle r (button->getBounds());
  52836. g.setColour (Colours::white);
  52837. g.fillRect (r);
  52838. g.setColour (findColour (ComboBox::outlineColourId));
  52839. g.drawRect (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  52840. }
  52841. void BooleanPropertyComponent::refresh()
  52842. {
  52843. button->setToggleState (getState(), false);
  52844. button->setButtonText (button->getToggleState() ? onText : offText);
  52845. }
  52846. void BooleanPropertyComponent::buttonClicked (Button*)
  52847. {
  52848. setState (! getState());
  52849. }
  52850. END_JUCE_NAMESPACE
  52851. /********* End of inlined file: juce_BooleanPropertyComponent.cpp *********/
  52852. /********* Start of inlined file: juce_ButtonPropertyComponent.cpp *********/
  52853. BEGIN_JUCE_NAMESPACE
  52854. ButtonPropertyComponent::ButtonPropertyComponent (const String& name,
  52855. const bool triggerOnMouseDown)
  52856. : PropertyComponent (name)
  52857. {
  52858. addAndMakeVisible (button = new TextButton (String::empty));
  52859. button->setTriggeredOnMouseDown (triggerOnMouseDown);
  52860. button->addButtonListener (this);
  52861. }
  52862. ButtonPropertyComponent::~ButtonPropertyComponent()
  52863. {
  52864. deleteAllChildren();
  52865. }
  52866. void ButtonPropertyComponent::refresh()
  52867. {
  52868. button->setButtonText (getButtonText());
  52869. }
  52870. void ButtonPropertyComponent::buttonClicked (Button*)
  52871. {
  52872. buttonClicked();
  52873. }
  52874. END_JUCE_NAMESPACE
  52875. /********* End of inlined file: juce_ButtonPropertyComponent.cpp *********/
  52876. /********* Start of inlined file: juce_ChoicePropertyComponent.cpp *********/
  52877. BEGIN_JUCE_NAMESPACE
  52878. ChoicePropertyComponent::ChoicePropertyComponent (const String& name)
  52879. : PropertyComponent (name),
  52880. comboBox (0)
  52881. {
  52882. }
  52883. ChoicePropertyComponent::~ChoicePropertyComponent()
  52884. {
  52885. deleteAllChildren();
  52886. }
  52887. const StringArray& ChoicePropertyComponent::getChoices() const throw()
  52888. {
  52889. return choices;
  52890. }
  52891. void ChoicePropertyComponent::refresh()
  52892. {
  52893. if (comboBox == 0)
  52894. {
  52895. addAndMakeVisible (comboBox = new ComboBox (String::empty));
  52896. for (int i = 0; i < choices.size(); ++i)
  52897. {
  52898. if (choices[i].isNotEmpty())
  52899. comboBox->addItem (choices[i], i + 1);
  52900. else
  52901. comboBox->addSeparator();
  52902. }
  52903. comboBox->setEditableText (false);
  52904. comboBox->addListener (this);
  52905. }
  52906. comboBox->setSelectedId (getIndex() + 1, true);
  52907. }
  52908. void ChoicePropertyComponent::comboBoxChanged (ComboBox*)
  52909. {
  52910. const int newIndex = comboBox->getSelectedId() - 1;
  52911. if (newIndex != getIndex())
  52912. setIndex (newIndex);
  52913. }
  52914. END_JUCE_NAMESPACE
  52915. /********* End of inlined file: juce_ChoicePropertyComponent.cpp *********/
  52916. /********* Start of inlined file: juce_PropertyComponent.cpp *********/
  52917. BEGIN_JUCE_NAMESPACE
  52918. PropertyComponent::PropertyComponent (const String& name,
  52919. const int preferredHeight_)
  52920. : Component (name),
  52921. preferredHeight (preferredHeight_)
  52922. {
  52923. jassert (name.isNotEmpty());
  52924. }
  52925. PropertyComponent::~PropertyComponent()
  52926. {
  52927. }
  52928. void PropertyComponent::paint (Graphics& g)
  52929. {
  52930. getLookAndFeel().drawPropertyComponentBackground (g, getWidth(), getHeight(), *this);
  52931. getLookAndFeel().drawPropertyComponentLabel (g, getWidth(), getHeight(), *this);
  52932. }
  52933. void PropertyComponent::resized()
  52934. {
  52935. if (getNumChildComponents() > 0)
  52936. getChildComponent (0)->setBounds (getLookAndFeel().getPropertyComponentContentPosition (*this));
  52937. }
  52938. void PropertyComponent::enablementChanged()
  52939. {
  52940. repaint();
  52941. }
  52942. END_JUCE_NAMESPACE
  52943. /********* End of inlined file: juce_PropertyComponent.cpp *********/
  52944. /********* Start of inlined file: juce_PropertyPanel.cpp *********/
  52945. BEGIN_JUCE_NAMESPACE
  52946. class PropertyHolderComponent : public Component
  52947. {
  52948. public:
  52949. PropertyHolderComponent()
  52950. {
  52951. }
  52952. ~PropertyHolderComponent()
  52953. {
  52954. deleteAllChildren();
  52955. }
  52956. void paint (Graphics&)
  52957. {
  52958. }
  52959. void updateLayout (const int width);
  52960. void refreshAll() const;
  52961. };
  52962. class PropertySectionComponent : public Component
  52963. {
  52964. public:
  52965. PropertySectionComponent (const String& sectionTitle,
  52966. const Array <PropertyComponent*>& newProperties,
  52967. const bool open)
  52968. : Component (sectionTitle),
  52969. titleHeight (sectionTitle.isNotEmpty() ? 22 : 0),
  52970. isOpen_ (open)
  52971. {
  52972. for (int i = newProperties.size(); --i >= 0;)
  52973. {
  52974. addAndMakeVisible (newProperties.getUnchecked(i));
  52975. newProperties.getUnchecked(i)->refresh();
  52976. }
  52977. }
  52978. ~PropertySectionComponent()
  52979. {
  52980. deleteAllChildren();
  52981. }
  52982. void paint (Graphics& g)
  52983. {
  52984. if (titleHeight > 0)
  52985. getLookAndFeel().drawPropertyPanelSectionHeader (g, getName(), isOpen(), getWidth(), titleHeight);
  52986. }
  52987. void resized()
  52988. {
  52989. int y = titleHeight;
  52990. for (int i = getNumChildComponents(); --i >= 0;)
  52991. {
  52992. PropertyComponent* const pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  52993. if (pec != 0)
  52994. {
  52995. const int prefH = pec->getPreferredHeight();
  52996. pec->setBounds (1, y, getWidth() - 2, prefH);
  52997. y += prefH;
  52998. }
  52999. }
  53000. }
  53001. int getPreferredHeight() const
  53002. {
  53003. int y = titleHeight;
  53004. if (isOpen())
  53005. {
  53006. for (int i = 0; i < getNumChildComponents(); ++i)
  53007. {
  53008. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  53009. if (pec != 0)
  53010. y += pec->getPreferredHeight();
  53011. }
  53012. }
  53013. return y;
  53014. }
  53015. void setOpen (const bool open)
  53016. {
  53017. if (isOpen_ != open)
  53018. {
  53019. isOpen_ = open;
  53020. for (int i = 0; i < getNumChildComponents(); ++i)
  53021. {
  53022. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  53023. if (pec != 0)
  53024. pec->setVisible (open);
  53025. }
  53026. // (unable to use the syntax findParentComponentOfClass <DragAndDropContainer> () because of a VC6 compiler bug)
  53027. PropertyPanel* const pp = findParentComponentOfClass ((PropertyPanel*) 0);
  53028. if (pp != 0)
  53029. pp->resized();
  53030. }
  53031. }
  53032. bool isOpen() const throw()
  53033. {
  53034. return isOpen_;
  53035. }
  53036. void refreshAll() const
  53037. {
  53038. for (int i = 0; i < getNumChildComponents(); ++i)
  53039. {
  53040. PropertyComponent* pec = dynamic_cast <PropertyComponent*> (getChildComponent (i));
  53041. if (pec != 0)
  53042. pec->refresh();
  53043. }
  53044. }
  53045. void mouseDown (const MouseEvent&)
  53046. {
  53047. }
  53048. void mouseUp (const MouseEvent& e)
  53049. {
  53050. if (e.getMouseDownX() < titleHeight
  53051. && e.x < titleHeight
  53052. && e.y < titleHeight
  53053. && e.getNumberOfClicks() != 2)
  53054. {
  53055. setOpen (! isOpen());
  53056. }
  53057. }
  53058. void mouseDoubleClick (const MouseEvent& e)
  53059. {
  53060. if (e.y < titleHeight)
  53061. setOpen (! isOpen());
  53062. }
  53063. private:
  53064. int titleHeight;
  53065. bool isOpen_;
  53066. };
  53067. void PropertyHolderComponent::updateLayout (const int width)
  53068. {
  53069. int y = 0;
  53070. for (int i = getNumChildComponents(); --i >= 0;)
  53071. {
  53072. PropertySectionComponent* const section
  53073. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  53074. if (section != 0)
  53075. {
  53076. const int prefH = section->getPreferredHeight();
  53077. section->setBounds (0, y, width, prefH);
  53078. y += prefH;
  53079. }
  53080. }
  53081. setSize (width, y);
  53082. repaint();
  53083. }
  53084. void PropertyHolderComponent::refreshAll() const
  53085. {
  53086. for (int i = getNumChildComponents(); --i >= 0;)
  53087. {
  53088. PropertySectionComponent* const section
  53089. = dynamic_cast <PropertySectionComponent*> (getChildComponent (i));
  53090. if (section != 0)
  53091. section->refreshAll();
  53092. }
  53093. }
  53094. PropertyPanel::PropertyPanel()
  53095. {
  53096. messageWhenEmpty = TRANS("(nothing selected)");
  53097. addAndMakeVisible (viewport = new Viewport());
  53098. viewport->setViewedComponent (propertyHolderComponent = new PropertyHolderComponent());
  53099. viewport->setFocusContainer (true);
  53100. }
  53101. PropertyPanel::~PropertyPanel()
  53102. {
  53103. clear();
  53104. deleteAllChildren();
  53105. }
  53106. void PropertyPanel::paint (Graphics& g)
  53107. {
  53108. if (propertyHolderComponent->getNumChildComponents() == 0)
  53109. {
  53110. g.setColour (Colours::black.withAlpha (0.5f));
  53111. g.setFont (14.0f);
  53112. g.drawText (messageWhenEmpty, 0, 0, getWidth(), 30,
  53113. Justification::centred, true);
  53114. }
  53115. }
  53116. void PropertyPanel::resized()
  53117. {
  53118. viewport->setBounds (0, 0, getWidth(), getHeight());
  53119. updatePropHolderLayout();
  53120. }
  53121. void PropertyPanel::clear()
  53122. {
  53123. if (propertyHolderComponent->getNumChildComponents() > 0)
  53124. {
  53125. propertyHolderComponent->deleteAllChildren();
  53126. repaint();
  53127. }
  53128. }
  53129. void PropertyPanel::addProperties (const Array <PropertyComponent*>& newProperties)
  53130. {
  53131. if (propertyHolderComponent->getNumChildComponents() == 0)
  53132. repaint();
  53133. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (String::empty,
  53134. newProperties,
  53135. true), 0);
  53136. updatePropHolderLayout();
  53137. }
  53138. void PropertyPanel::addSection (const String& sectionTitle,
  53139. const Array <PropertyComponent*>& newProperties,
  53140. const bool shouldBeOpen)
  53141. {
  53142. jassert (sectionTitle.isNotEmpty());
  53143. if (propertyHolderComponent->getNumChildComponents() == 0)
  53144. repaint();
  53145. propertyHolderComponent->addAndMakeVisible (new PropertySectionComponent (sectionTitle,
  53146. newProperties,
  53147. shouldBeOpen), 0);
  53148. updatePropHolderLayout();
  53149. }
  53150. void PropertyPanel::updatePropHolderLayout() const
  53151. {
  53152. const int maxWidth = viewport->getMaximumVisibleWidth();
  53153. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (maxWidth);
  53154. const int newMaxWidth = viewport->getMaximumVisibleWidth();
  53155. if (maxWidth != newMaxWidth)
  53156. {
  53157. // need to do this twice because of scrollbars changing the size, etc.
  53158. ((PropertyHolderComponent*) propertyHolderComponent)->updateLayout (newMaxWidth);
  53159. }
  53160. }
  53161. void PropertyPanel::refreshAll() const
  53162. {
  53163. ((PropertyHolderComponent*) propertyHolderComponent)->refreshAll();
  53164. }
  53165. const StringArray PropertyPanel::getSectionNames() const
  53166. {
  53167. StringArray s;
  53168. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  53169. {
  53170. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  53171. if (section != 0 && section->getName().isNotEmpty())
  53172. s.add (section->getName());
  53173. }
  53174. return s;
  53175. }
  53176. bool PropertyPanel::isSectionOpen (const int sectionIndex) const
  53177. {
  53178. int index = 0;
  53179. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  53180. {
  53181. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  53182. if (section != 0 && section->getName().isNotEmpty())
  53183. {
  53184. if (index == sectionIndex)
  53185. return section->isOpen();
  53186. ++index;
  53187. }
  53188. }
  53189. return false;
  53190. }
  53191. void PropertyPanel::setSectionOpen (const int sectionIndex, const bool shouldBeOpen)
  53192. {
  53193. int index = 0;
  53194. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  53195. {
  53196. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  53197. if (section != 0 && section->getName().isNotEmpty())
  53198. {
  53199. if (index == sectionIndex)
  53200. {
  53201. section->setOpen (shouldBeOpen);
  53202. break;
  53203. }
  53204. ++index;
  53205. }
  53206. }
  53207. }
  53208. void PropertyPanel::setSectionEnabled (const int sectionIndex, const bool shouldBeEnabled)
  53209. {
  53210. int index = 0;
  53211. for (int i = 0; i < propertyHolderComponent->getNumChildComponents(); ++i)
  53212. {
  53213. PropertySectionComponent* const section = dynamic_cast <PropertySectionComponent*> (propertyHolderComponent->getChildComponent (i));
  53214. if (section != 0 && section->getName().isNotEmpty())
  53215. {
  53216. if (index == sectionIndex)
  53217. {
  53218. section->setEnabled (shouldBeEnabled);
  53219. break;
  53220. }
  53221. ++index;
  53222. }
  53223. }
  53224. }
  53225. XmlElement* PropertyPanel::getOpennessState() const
  53226. {
  53227. XmlElement* const xml = new XmlElement (T("PROPERTYPANELSTATE"));
  53228. const StringArray sections (getSectionNames());
  53229. for (int i = 0; i < sections.size(); ++i)
  53230. {
  53231. if (sections[i].isNotEmpty())
  53232. {
  53233. XmlElement* const e = new XmlElement (T("SECTION"));
  53234. e->setAttribute (T("name"), sections[i]);
  53235. e->setAttribute (T("open"), isSectionOpen (i) ? 1 : 0);
  53236. xml->addChildElement (e);
  53237. }
  53238. }
  53239. return xml;
  53240. }
  53241. void PropertyPanel::restoreOpennessState (const XmlElement& xml)
  53242. {
  53243. if (xml.hasTagName (T("PROPERTYPANELSTATE")))
  53244. {
  53245. const StringArray sections (getSectionNames());
  53246. forEachXmlChildElementWithTagName (xml, e, T("SECTION"))
  53247. {
  53248. setSectionOpen (sections.indexOf (e->getStringAttribute (T("name"))),
  53249. e->getBoolAttribute (T("open")));
  53250. }
  53251. }
  53252. }
  53253. void PropertyPanel::setMessageWhenEmpty (const String& newMessage)
  53254. {
  53255. if (messageWhenEmpty != newMessage)
  53256. {
  53257. messageWhenEmpty = newMessage;
  53258. repaint();
  53259. }
  53260. }
  53261. const String& PropertyPanel::getMessageWhenEmpty() const throw()
  53262. {
  53263. return messageWhenEmpty;
  53264. }
  53265. END_JUCE_NAMESPACE
  53266. /********* End of inlined file: juce_PropertyPanel.cpp *********/
  53267. /********* Start of inlined file: juce_SliderPropertyComponent.cpp *********/
  53268. BEGIN_JUCE_NAMESPACE
  53269. SliderPropertyComponent::SliderPropertyComponent (const String& name,
  53270. const double rangeMin,
  53271. const double rangeMax,
  53272. const double interval,
  53273. const double skewFactor)
  53274. : PropertyComponent (name)
  53275. {
  53276. addAndMakeVisible (slider = new Slider (name));
  53277. slider->setRange (rangeMin, rangeMax, interval);
  53278. slider->setSkewFactor (skewFactor);
  53279. slider->setSliderStyle (Slider::LinearBar);
  53280. slider->addListener (this);
  53281. }
  53282. SliderPropertyComponent::~SliderPropertyComponent()
  53283. {
  53284. deleteAllChildren();
  53285. }
  53286. void SliderPropertyComponent::refresh()
  53287. {
  53288. slider->setValue (getValue(), false);
  53289. }
  53290. void SliderPropertyComponent::sliderValueChanged (Slider*)
  53291. {
  53292. if (getValue() != slider->getValue())
  53293. setValue (slider->getValue());
  53294. }
  53295. END_JUCE_NAMESPACE
  53296. /********* End of inlined file: juce_SliderPropertyComponent.cpp *********/
  53297. /********* Start of inlined file: juce_TextPropertyComponent.cpp *********/
  53298. BEGIN_JUCE_NAMESPACE
  53299. class TextPropLabel : public Label
  53300. {
  53301. TextPropertyComponent& owner;
  53302. int maxChars;
  53303. bool isMultiline;
  53304. public:
  53305. TextPropLabel (TextPropertyComponent& owner_,
  53306. const int maxChars_, const bool isMultiline_)
  53307. : Label (String::empty, String::empty),
  53308. owner (owner_),
  53309. maxChars (maxChars_),
  53310. isMultiline (isMultiline_)
  53311. {
  53312. setEditable (true, true, false);
  53313. setColour (backgroundColourId, Colours::white);
  53314. setColour (outlineColourId, findColour (ComboBox::outlineColourId));
  53315. }
  53316. ~TextPropLabel()
  53317. {
  53318. }
  53319. TextEditor* createEditorComponent()
  53320. {
  53321. TextEditor* const textEditor = Label::createEditorComponent();
  53322. textEditor->setInputRestrictions (maxChars);
  53323. if (isMultiline)
  53324. {
  53325. textEditor->setMultiLine (true, true);
  53326. textEditor->setReturnKeyStartsNewLine (true);
  53327. }
  53328. return textEditor;
  53329. }
  53330. void textWasEdited()
  53331. {
  53332. owner.textWasEdited();
  53333. }
  53334. };
  53335. TextPropertyComponent::TextPropertyComponent (const String& name,
  53336. const int maxNumChars,
  53337. const bool isMultiLine)
  53338. : PropertyComponent (name)
  53339. {
  53340. addAndMakeVisible (textEditor = new TextPropLabel (*this, maxNumChars, isMultiLine));
  53341. if (isMultiLine)
  53342. {
  53343. textEditor->setJustificationType (Justification::topLeft);
  53344. preferredHeight = 120;
  53345. }
  53346. }
  53347. TextPropertyComponent::~TextPropertyComponent()
  53348. {
  53349. deleteAllChildren();
  53350. }
  53351. void TextPropertyComponent::refresh()
  53352. {
  53353. textEditor->setText (getText(), false);
  53354. }
  53355. void TextPropertyComponent::textWasEdited()
  53356. {
  53357. const String newText (textEditor->getText());
  53358. if (getText() != newText)
  53359. setText (newText);
  53360. }
  53361. END_JUCE_NAMESPACE
  53362. /********* End of inlined file: juce_TextPropertyComponent.cpp *********/
  53363. /********* Start of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  53364. BEGIN_JUCE_NAMESPACE
  53365. class SimpleDeviceManagerInputLevelMeter : public Component,
  53366. public Timer
  53367. {
  53368. public:
  53369. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager* const manager_)
  53370. : manager (manager_),
  53371. level (0)
  53372. {
  53373. startTimer (50);
  53374. manager->enableInputLevelMeasurement (true);
  53375. }
  53376. ~SimpleDeviceManagerInputLevelMeter()
  53377. {
  53378. manager->enableInputLevelMeasurement (false);
  53379. }
  53380. void timerCallback()
  53381. {
  53382. const float newLevel = (float) manager->getCurrentInputLevel();
  53383. if (fabsf (level - newLevel) > 0.005f)
  53384. {
  53385. level = newLevel;
  53386. repaint();
  53387. }
  53388. }
  53389. void paint (Graphics& g)
  53390. {
  53391. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(), level);
  53392. }
  53393. private:
  53394. AudioDeviceManager* const manager;
  53395. float level;
  53396. };
  53397. class MidiInputSelectorComponentListBox : public ListBox,
  53398. public ListBoxModel
  53399. {
  53400. public:
  53401. MidiInputSelectorComponentListBox (AudioDeviceManager& deviceManager_,
  53402. const String& noItemsMessage_,
  53403. const int minNumber_,
  53404. const int maxNumber_)
  53405. : ListBox (String::empty, 0),
  53406. deviceManager (deviceManager_),
  53407. noItemsMessage (noItemsMessage_),
  53408. minNumber (minNumber_),
  53409. maxNumber (maxNumber_)
  53410. {
  53411. items = MidiInput::getDevices();
  53412. setModel (this);
  53413. setOutlineThickness (1);
  53414. }
  53415. ~MidiInputSelectorComponentListBox()
  53416. {
  53417. }
  53418. int getNumRows()
  53419. {
  53420. return items.size();
  53421. }
  53422. void paintListBoxItem (int row,
  53423. Graphics& g,
  53424. int width, int height,
  53425. bool rowIsSelected)
  53426. {
  53427. if (((unsigned int) row) < (unsigned int) items.size())
  53428. {
  53429. if (rowIsSelected)
  53430. g.fillAll (findColour (TextEditor::highlightColourId)
  53431. .withMultipliedAlpha (0.3f));
  53432. const String item (items [row]);
  53433. bool enabled = deviceManager.isMidiInputEnabled (item);
  53434. const int x = getTickX();
  53435. const int tickW = height - height / 4;
  53436. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  53437. enabled, true, true, false);
  53438. g.setFont (height * 0.6f);
  53439. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  53440. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  53441. }
  53442. }
  53443. void listBoxItemClicked (int row, const MouseEvent& e)
  53444. {
  53445. selectRow (row);
  53446. if (e.x < getTickX())
  53447. flipEnablement (row);
  53448. }
  53449. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  53450. {
  53451. flipEnablement (row);
  53452. }
  53453. void returnKeyPressed (int row)
  53454. {
  53455. flipEnablement (row);
  53456. }
  53457. void paint (Graphics& g)
  53458. {
  53459. ListBox::paint (g);
  53460. if (items.size() == 0)
  53461. {
  53462. g.setColour (Colours::grey);
  53463. g.setFont (13.0f);
  53464. g.drawText (noItemsMessage,
  53465. 0, 0, getWidth(), getHeight() / 2,
  53466. Justification::centred, true);
  53467. }
  53468. }
  53469. int getBestHeight (const int preferredHeight)
  53470. {
  53471. const int extra = getOutlineThickness() * 2;
  53472. return jmax (getRowHeight() * 2 + extra,
  53473. jmin (getRowHeight() * getNumRows() + extra,
  53474. preferredHeight));
  53475. }
  53476. juce_UseDebuggingNewOperator
  53477. private:
  53478. AudioDeviceManager& deviceManager;
  53479. const String noItemsMessage;
  53480. StringArray items;
  53481. int minNumber, maxNumber;
  53482. void flipEnablement (const int row)
  53483. {
  53484. if (((unsigned int) row) < (unsigned int) items.size())
  53485. {
  53486. const String item (items [row]);
  53487. deviceManager.setMidiInputEnabled (item, ! deviceManager.isMidiInputEnabled (item));
  53488. }
  53489. }
  53490. int getTickX() const throw()
  53491. {
  53492. return getRowHeight() + 5;
  53493. }
  53494. MidiInputSelectorComponentListBox (const MidiInputSelectorComponentListBox&);
  53495. const MidiInputSelectorComponentListBox& operator= (const MidiInputSelectorComponentListBox&);
  53496. };
  53497. class AudioDeviceSettingsPanel : public Component,
  53498. public ComboBoxListener,
  53499. public ChangeListener,
  53500. public ButtonListener
  53501. {
  53502. public:
  53503. AudioDeviceSettingsPanel (AudioIODeviceType* type_,
  53504. AudioIODeviceType::DeviceSetupDetails& setup_,
  53505. const bool hideAdvancedOptionsWithButton)
  53506. : type (type_),
  53507. setup (setup_)
  53508. {
  53509. sampleRateDropDown = 0;
  53510. sampleRateLabel = 0;
  53511. bufferSizeDropDown = 0;
  53512. bufferSizeLabel = 0;
  53513. outputDeviceDropDown = 0;
  53514. outputDeviceLabel = 0;
  53515. inputDeviceDropDown = 0;
  53516. inputDeviceLabel = 0;
  53517. testButton = 0;
  53518. inputLevelMeter = 0;
  53519. showUIButton = 0;
  53520. inputChanList = 0;
  53521. outputChanList = 0;
  53522. inputChanLabel = 0;
  53523. outputChanLabel = 0;
  53524. showAdvancedSettingsButton = 0;
  53525. if (hideAdvancedOptionsWithButton)
  53526. {
  53527. addAndMakeVisible (showAdvancedSettingsButton = new TextButton (TRANS("Show advanced settings...")));
  53528. showAdvancedSettingsButton->addButtonListener (this);
  53529. }
  53530. type->scanForDevices();
  53531. setup.manager->addChangeListener (this);
  53532. changeListenerCallback (0);
  53533. }
  53534. ~AudioDeviceSettingsPanel()
  53535. {
  53536. setup.manager->removeChangeListener (this);
  53537. deleteAndZero (outputDeviceLabel);
  53538. deleteAndZero (inputDeviceLabel);
  53539. deleteAndZero (sampleRateLabel);
  53540. deleteAndZero (bufferSizeLabel);
  53541. deleteAndZero (showUIButton);
  53542. deleteAndZero (inputChanLabel);
  53543. deleteAndZero (outputChanLabel);
  53544. deleteAndZero (showAdvancedSettingsButton);
  53545. deleteAllChildren();
  53546. }
  53547. void resized()
  53548. {
  53549. const int lx = proportionOfWidth (0.35f);
  53550. const int w = proportionOfWidth (0.4f);
  53551. const int h = 24;
  53552. const int space = 6;
  53553. const int dh = h + space;
  53554. int y = 0;
  53555. if (outputDeviceDropDown != 0)
  53556. {
  53557. outputDeviceDropDown->setBounds (lx, y, w, h);
  53558. if (testButton != 0)
  53559. testButton->setBounds (proportionOfWidth (0.77f),
  53560. outputDeviceDropDown->getY(),
  53561. proportionOfWidth (0.18f),
  53562. h);
  53563. y += dh;
  53564. }
  53565. if (inputDeviceDropDown != 0)
  53566. {
  53567. inputDeviceDropDown->setBounds (lx, y, w, h);
  53568. inputLevelMeter->setBounds (proportionOfWidth (0.77f),
  53569. inputDeviceDropDown->getY(),
  53570. proportionOfWidth (0.18f),
  53571. h);
  53572. y += dh;
  53573. }
  53574. const int maxBoxHeight = 100;//(getHeight() - y - dh * 2) / numBoxes;
  53575. if (outputChanList != 0)
  53576. {
  53577. const int bh = outputChanList->getBestHeight (maxBoxHeight);
  53578. outputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  53579. y += bh + space;
  53580. }
  53581. if (inputChanList != 0)
  53582. {
  53583. const int bh = inputChanList->getBestHeight (maxBoxHeight);
  53584. inputChanList->setBounds (lx, y, proportionOfWidth (0.55f), bh);
  53585. y += bh + space;
  53586. }
  53587. y += space * 2;
  53588. if (showAdvancedSettingsButton != 0)
  53589. {
  53590. showAdvancedSettingsButton->changeWidthToFitText (h);
  53591. showAdvancedSettingsButton->setTopLeftPosition (lx, y);
  53592. }
  53593. if (sampleRateDropDown != 0)
  53594. {
  53595. sampleRateDropDown->setVisible (showAdvancedSettingsButton == 0
  53596. || ! showAdvancedSettingsButton->isVisible());
  53597. sampleRateDropDown->setBounds (lx, y, w, h);
  53598. y += dh;
  53599. }
  53600. if (bufferSizeDropDown != 0)
  53601. {
  53602. bufferSizeDropDown->setVisible (showAdvancedSettingsButton == 0
  53603. || ! showAdvancedSettingsButton->isVisible());
  53604. bufferSizeDropDown->setBounds (lx, y, w, h);
  53605. y += dh;
  53606. }
  53607. if (showUIButton != 0)
  53608. {
  53609. showUIButton->setVisible (showAdvancedSettingsButton == 0
  53610. || ! showAdvancedSettingsButton->isVisible());
  53611. showUIButton->changeWidthToFitText (h);
  53612. showUIButton->setTopLeftPosition (lx, y);
  53613. }
  53614. }
  53615. void comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  53616. {
  53617. if (comboBoxThatHasChanged == 0)
  53618. return;
  53619. AudioDeviceManager::AudioDeviceSetup config;
  53620. setup.manager->getAudioDeviceSetup (config);
  53621. String error;
  53622. if (comboBoxThatHasChanged == outputDeviceDropDown
  53623. || comboBoxThatHasChanged == inputDeviceDropDown)
  53624. {
  53625. if (outputDeviceDropDown != 0)
  53626. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String::empty
  53627. : outputDeviceDropDown->getText();
  53628. if (inputDeviceDropDown != 0)
  53629. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String::empty
  53630. : inputDeviceDropDown->getText();
  53631. if (! type->hasSeparateInputsAndOutputs())
  53632. config.inputDeviceName = config.outputDeviceName;
  53633. if (comboBoxThatHasChanged == inputDeviceDropDown)
  53634. config.useDefaultInputChannels = true;
  53635. else
  53636. config.useDefaultOutputChannels = true;
  53637. error = setup.manager->setAudioDeviceSetup (config, true);
  53638. showCorrectDeviceName (inputDeviceDropDown, true);
  53639. showCorrectDeviceName (outputDeviceDropDown, false);
  53640. updateControlPanelButton();
  53641. resized();
  53642. }
  53643. else if (comboBoxThatHasChanged == sampleRateDropDown)
  53644. {
  53645. if (sampleRateDropDown->getSelectedId() > 0)
  53646. {
  53647. config.sampleRate = sampleRateDropDown->getSelectedId();
  53648. error = setup.manager->setAudioDeviceSetup (config, true);
  53649. }
  53650. }
  53651. else if (comboBoxThatHasChanged == bufferSizeDropDown)
  53652. {
  53653. if (bufferSizeDropDown->getSelectedId() > 0)
  53654. {
  53655. config.bufferSize = bufferSizeDropDown->getSelectedId();
  53656. error = setup.manager->setAudioDeviceSetup (config, true);
  53657. }
  53658. }
  53659. if (error.isNotEmpty())
  53660. {
  53661. AlertWindow::showMessageBox (AlertWindow::WarningIcon,
  53662. T("Error when trying to open audio device!"),
  53663. error);
  53664. }
  53665. }
  53666. void buttonClicked (Button* button)
  53667. {
  53668. if (button == showAdvancedSettingsButton)
  53669. {
  53670. showAdvancedSettingsButton->setVisible (false);
  53671. resized();
  53672. }
  53673. else if (button == showUIButton)
  53674. {
  53675. AudioIODevice* const device = setup.manager->getCurrentAudioDevice();
  53676. if (device != 0 && device->showControlPanel())
  53677. {
  53678. setup.manager->closeAudioDevice();
  53679. setup.manager->restartLastAudioDevice();
  53680. getTopLevelComponent()->toFront (true);
  53681. }
  53682. }
  53683. else if (button == testButton && testButton != 0)
  53684. {
  53685. setup.manager->playTestSound();
  53686. }
  53687. }
  53688. void updateControlPanelButton()
  53689. {
  53690. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  53691. deleteAndZero (showUIButton);
  53692. if (currentDevice != 0 && currentDevice->hasControlPanel())
  53693. {
  53694. addAndMakeVisible (showUIButton = new TextButton (TRANS ("show this device's control panel"),
  53695. TRANS ("opens the device's own control panel")));
  53696. showUIButton->addButtonListener (this);
  53697. }
  53698. resized();
  53699. }
  53700. void changeListenerCallback (void*)
  53701. {
  53702. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  53703. if (setup.maxNumOutputChannels > 0 || ! type->hasSeparateInputsAndOutputs())
  53704. {
  53705. if (outputDeviceDropDown == 0)
  53706. {
  53707. outputDeviceDropDown = new ComboBox (String::empty);
  53708. outputDeviceDropDown->addListener (this);
  53709. addAndMakeVisible (outputDeviceDropDown);
  53710. outputDeviceLabel = new Label (String::empty,
  53711. type->hasSeparateInputsAndOutputs() ? TRANS ("output:")
  53712. : TRANS ("device:"));
  53713. outputDeviceLabel->attachToComponent (outputDeviceDropDown, true);
  53714. if (setup.maxNumOutputChannels > 0)
  53715. {
  53716. addAndMakeVisible (testButton = new TextButton (TRANS ("Test")));
  53717. testButton->addButtonListener (this);
  53718. }
  53719. }
  53720. addNamesToDeviceBox (*outputDeviceDropDown, false);
  53721. }
  53722. if (setup.maxNumInputChannels > 0 && type->hasSeparateInputsAndOutputs())
  53723. {
  53724. if (inputDeviceDropDown == 0)
  53725. {
  53726. inputDeviceDropDown = new ComboBox (String::empty);
  53727. inputDeviceDropDown->addListener (this);
  53728. addAndMakeVisible (inputDeviceDropDown);
  53729. inputDeviceLabel = new Label (String::empty, TRANS ("input:"));
  53730. inputDeviceLabel->attachToComponent (inputDeviceDropDown, true);
  53731. addAndMakeVisible (inputLevelMeter
  53732. = new SimpleDeviceManagerInputLevelMeter (setup.manager));
  53733. }
  53734. addNamesToDeviceBox (*inputDeviceDropDown, true);
  53735. }
  53736. updateControlPanelButton();
  53737. showCorrectDeviceName (inputDeviceDropDown, true);
  53738. showCorrectDeviceName (outputDeviceDropDown, false);
  53739. if (currentDevice != 0)
  53740. {
  53741. if (setup.maxNumOutputChannels > 0
  53742. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  53743. {
  53744. if (outputChanList == 0)
  53745. {
  53746. addAndMakeVisible (outputChanList
  53747. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  53748. TRANS ("(no audio output channels found)")));
  53749. outputChanLabel = new Label (String::empty, TRANS ("active output channels:"));
  53750. outputChanLabel->attachToComponent (outputChanList, true);
  53751. }
  53752. outputChanList->refresh();
  53753. }
  53754. else
  53755. {
  53756. deleteAndZero (outputChanLabel);
  53757. deleteAndZero (outputChanList);
  53758. }
  53759. if (setup.maxNumInputChannels > 0
  53760. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  53761. {
  53762. if (inputChanList == 0)
  53763. {
  53764. addAndMakeVisible (inputChanList
  53765. = new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  53766. TRANS ("(no audio input channels found)")));
  53767. inputChanLabel = new Label (String::empty, TRANS ("active input channels:"));
  53768. inputChanLabel->attachToComponent (inputChanList, true);
  53769. }
  53770. inputChanList->refresh();
  53771. }
  53772. else
  53773. {
  53774. deleteAndZero (inputChanLabel);
  53775. deleteAndZero (inputChanList);
  53776. }
  53777. // sample rate..
  53778. {
  53779. if (sampleRateDropDown == 0)
  53780. {
  53781. addAndMakeVisible (sampleRateDropDown = new ComboBox (String::empty));
  53782. sampleRateDropDown->addListener (this);
  53783. delete sampleRateLabel;
  53784. sampleRateLabel = new Label (String::empty, TRANS ("sample rate:"));
  53785. sampleRateLabel->attachToComponent (sampleRateDropDown, true);
  53786. }
  53787. else
  53788. {
  53789. sampleRateDropDown->clear();
  53790. sampleRateDropDown->removeListener (this);
  53791. }
  53792. const int numRates = currentDevice->getNumSampleRates();
  53793. for (int i = 0; i < numRates; ++i)
  53794. {
  53795. const int rate = roundDoubleToInt (currentDevice->getSampleRate (i));
  53796. sampleRateDropDown->addItem (String (rate) + T(" Hz"), rate);
  53797. }
  53798. sampleRateDropDown->setSelectedId (roundDoubleToInt (currentDevice->getCurrentSampleRate()), true);
  53799. sampleRateDropDown->addListener (this);
  53800. }
  53801. // buffer size
  53802. {
  53803. if (bufferSizeDropDown == 0)
  53804. {
  53805. addAndMakeVisible (bufferSizeDropDown = new ComboBox (String::empty));
  53806. bufferSizeDropDown->addListener (this);
  53807. delete bufferSizeLabel;
  53808. bufferSizeLabel = new Label (String::empty, TRANS ("audio buffer size:"));
  53809. bufferSizeLabel->attachToComponent (bufferSizeDropDown, true);
  53810. }
  53811. else
  53812. {
  53813. bufferSizeDropDown->clear();
  53814. }
  53815. const int numBufferSizes = currentDevice->getNumBufferSizesAvailable();
  53816. double currentRate = currentDevice->getCurrentSampleRate();
  53817. if (currentRate == 0)
  53818. currentRate = 48000.0;
  53819. for (int i = 0; i < numBufferSizes; ++i)
  53820. {
  53821. const int bs = currentDevice->getBufferSizeSamples (i);
  53822. bufferSizeDropDown->addItem (String (bs)
  53823. + T(" samples (")
  53824. + String (bs * 1000.0 / currentRate, 1)
  53825. + T(" ms)"),
  53826. bs);
  53827. }
  53828. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), true);
  53829. }
  53830. }
  53831. else
  53832. {
  53833. jassert (setup.manager->getCurrentAudioDevice() == 0); // not the correct device type!
  53834. deleteAndZero (sampleRateLabel);
  53835. deleteAndZero (bufferSizeLabel);
  53836. deleteAndZero (sampleRateDropDown);
  53837. deleteAndZero (bufferSizeDropDown);
  53838. if (outputDeviceDropDown != 0)
  53839. outputDeviceDropDown->setSelectedId (-1, true);
  53840. if (inputDeviceDropDown != 0)
  53841. inputDeviceDropDown->setSelectedId (-1, true);
  53842. }
  53843. resized();
  53844. setSize (getWidth(), getLowestY() + 4);
  53845. }
  53846. private:
  53847. AudioIODeviceType* const type;
  53848. const AudioIODeviceType::DeviceSetupDetails setup;
  53849. ComboBox* outputDeviceDropDown;
  53850. ComboBox* inputDeviceDropDown;
  53851. ComboBox* sampleRateDropDown;
  53852. ComboBox* bufferSizeDropDown;
  53853. Label* outputDeviceLabel;
  53854. Label* inputDeviceLabel;
  53855. Label* sampleRateLabel;
  53856. Label* bufferSizeLabel;
  53857. Label* inputChanLabel;
  53858. Label* outputChanLabel;
  53859. TextButton* testButton;
  53860. Component* inputLevelMeter;
  53861. TextButton* showUIButton;
  53862. TextButton* showAdvancedSettingsButton;
  53863. void showCorrectDeviceName (ComboBox* const box, const bool isInput)
  53864. {
  53865. if (box != 0)
  53866. {
  53867. AudioIODevice* const currentDevice = dynamic_cast <AudioIODevice*> (setup.manager->getCurrentAudioDevice());
  53868. const int index = type->getIndexOfDevice (currentDevice, isInput);
  53869. box->setSelectedId (index + 1, true);
  53870. if (testButton != 0 && ! isInput)
  53871. testButton->setEnabled (index >= 0);
  53872. }
  53873. }
  53874. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  53875. {
  53876. const StringArray devs (type->getDeviceNames (isInputs));
  53877. combo.clear (true);
  53878. for (int i = 0; i < devs.size(); ++i)
  53879. combo.addItem (devs[i], i + 1);
  53880. combo.addItem (TRANS("<< none >>"), -1);
  53881. combo.setSelectedId (-1, true);
  53882. }
  53883. int getLowestY() const
  53884. {
  53885. int y = 0;
  53886. for (int i = getNumChildComponents(); --i >= 0;)
  53887. y = jmax (y, getChildComponent (i)->getBottom());
  53888. return y;
  53889. }
  53890. class ChannelSelectorListBox : public ListBox,
  53891. public ListBoxModel
  53892. {
  53893. public:
  53894. enum BoxType
  53895. {
  53896. audioInputType,
  53897. audioOutputType
  53898. };
  53899. ChannelSelectorListBox (const AudioIODeviceType::DeviceSetupDetails& setup_,
  53900. const BoxType type_,
  53901. const String& noItemsMessage_)
  53902. : ListBox (String::empty, 0),
  53903. setup (setup_),
  53904. type (type_),
  53905. noItemsMessage (noItemsMessage_)
  53906. {
  53907. refresh();
  53908. setModel (this);
  53909. setOutlineThickness (1);
  53910. }
  53911. ~ChannelSelectorListBox()
  53912. {
  53913. }
  53914. void refresh()
  53915. {
  53916. items.clear();
  53917. AudioIODevice* const currentDevice = setup.manager->getCurrentAudioDevice();
  53918. if (currentDevice != 0)
  53919. {
  53920. if (type == audioInputType)
  53921. items = currentDevice->getInputChannelNames();
  53922. else if (type == audioOutputType)
  53923. items = currentDevice->getOutputChannelNames();
  53924. if (setup.useStereoPairs)
  53925. {
  53926. StringArray pairs;
  53927. for (int i = 0; i < items.size(); i += 2)
  53928. {
  53929. String name (items[i]);
  53930. String name2 (items[i + 1]);
  53931. String commonBit;
  53932. for (int j = 0; j < name.length(); ++j)
  53933. if (name.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  53934. commonBit = name.substring (0, j);
  53935. pairs.add (name.trim()
  53936. + " + "
  53937. + name2.substring (commonBit.length()).trim());
  53938. }
  53939. items = pairs;
  53940. }
  53941. }
  53942. updateContent();
  53943. repaint();
  53944. }
  53945. int getNumRows()
  53946. {
  53947. return items.size();
  53948. }
  53949. void paintListBoxItem (int row,
  53950. Graphics& g,
  53951. int width, int height,
  53952. bool rowIsSelected)
  53953. {
  53954. if (((unsigned int) row) < (unsigned int) items.size())
  53955. {
  53956. if (rowIsSelected)
  53957. g.fillAll (findColour (TextEditor::highlightColourId)
  53958. .withMultipliedAlpha (0.3f));
  53959. const String item (items [row]);
  53960. bool enabled = false;
  53961. AudioDeviceManager::AudioDeviceSetup config;
  53962. setup.manager->getAudioDeviceSetup (config);
  53963. if (setup.useStereoPairs)
  53964. {
  53965. if (type == audioInputType)
  53966. enabled = config.inputChannels [row * 2] || config.inputChannels [row * 2 + 1];
  53967. else if (type == audioOutputType)
  53968. enabled = config.outputChannels [row * 2] || config.outputChannels [row * 2 + 1];
  53969. }
  53970. else
  53971. {
  53972. if (type == audioInputType)
  53973. enabled = config.inputChannels [row];
  53974. else if (type == audioOutputType)
  53975. enabled = config.outputChannels [row];
  53976. }
  53977. const int x = getTickX();
  53978. const int tickW = height - height / 4;
  53979. getLookAndFeel().drawTickBox (g, *this, x - tickW, (height - tickW) / 2, tickW, tickW,
  53980. enabled, true, true, false);
  53981. g.setFont (height * 0.6f);
  53982. g.setColour (findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f));
  53983. g.drawText (item, x, 0, width - x - 2, height, Justification::centredLeft, true);
  53984. }
  53985. }
  53986. void listBoxItemClicked (int row, const MouseEvent& e)
  53987. {
  53988. selectRow (row);
  53989. if (e.x < getTickX())
  53990. flipEnablement (row);
  53991. }
  53992. void listBoxItemDoubleClicked (int row, const MouseEvent&)
  53993. {
  53994. flipEnablement (row);
  53995. }
  53996. void returnKeyPressed (int row)
  53997. {
  53998. flipEnablement (row);
  53999. }
  54000. void paint (Graphics& g)
  54001. {
  54002. ListBox::paint (g);
  54003. if (items.size() == 0)
  54004. {
  54005. g.setColour (Colours::grey);
  54006. g.setFont (13.0f);
  54007. g.drawText (noItemsMessage,
  54008. 0, 0, getWidth(), getHeight() / 2,
  54009. Justification::centred, true);
  54010. }
  54011. }
  54012. int getBestHeight (int maxHeight)
  54013. {
  54014. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  54015. getNumRows())
  54016. + getOutlineThickness() * 2;
  54017. }
  54018. juce_UseDebuggingNewOperator
  54019. private:
  54020. const AudioIODeviceType::DeviceSetupDetails setup;
  54021. const BoxType type;
  54022. const String noItemsMessage;
  54023. StringArray items;
  54024. void flipEnablement (const int row)
  54025. {
  54026. jassert (type == audioInputType || type == audioOutputType);
  54027. if (((unsigned int) row) < (unsigned int) items.size())
  54028. {
  54029. AudioDeviceManager::AudioDeviceSetup config;
  54030. setup.manager->getAudioDeviceSetup (config);
  54031. if (setup.useStereoPairs)
  54032. {
  54033. BitArray bits;
  54034. BitArray& original = (type == audioInputType ? config.inputChannels
  54035. : config.outputChannels);
  54036. int i;
  54037. for (i = 0; i < 256; i += 2)
  54038. bits.setBit (i / 2, original [i] || original [i + 1]);
  54039. if (type == audioInputType)
  54040. {
  54041. config.useDefaultInputChannels = false;
  54042. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  54043. }
  54044. else
  54045. {
  54046. config.useDefaultOutputChannels = false;
  54047. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  54048. }
  54049. for (i = 0; i < 256; ++i)
  54050. original.setBit (i, bits [i / 2]);
  54051. }
  54052. else
  54053. {
  54054. if (type == audioInputType)
  54055. {
  54056. config.useDefaultInputChannels = false;
  54057. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  54058. }
  54059. else
  54060. {
  54061. config.useDefaultOutputChannels = false;
  54062. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  54063. }
  54064. }
  54065. String error (setup.manager->setAudioDeviceSetup (config, true));
  54066. if (! error.isEmpty())
  54067. {
  54068. //xxx
  54069. }
  54070. }
  54071. }
  54072. static void flipBit (BitArray& chans, int index, int minNumber, int maxNumber)
  54073. {
  54074. const int numActive = chans.countNumberOfSetBits();
  54075. if (chans [index])
  54076. {
  54077. if (numActive > minNumber)
  54078. chans.setBit (index, false);
  54079. }
  54080. else
  54081. {
  54082. if (numActive >= maxNumber)
  54083. {
  54084. const int firstActiveChan = chans.findNextSetBit();
  54085. chans.setBit (index > firstActiveChan
  54086. ? firstActiveChan : chans.getHighestBit(),
  54087. false);
  54088. }
  54089. chans.setBit (index, true);
  54090. }
  54091. }
  54092. int getTickX() const throw()
  54093. {
  54094. return getRowHeight() + 5;
  54095. }
  54096. ChannelSelectorListBox (const ChannelSelectorListBox&);
  54097. const ChannelSelectorListBox& operator= (const ChannelSelectorListBox&);
  54098. };
  54099. ChannelSelectorListBox* inputChanList;
  54100. ChannelSelectorListBox* outputChanList;
  54101. AudioDeviceSettingsPanel (const AudioDeviceSettingsPanel&);
  54102. const AudioDeviceSettingsPanel& operator= (const AudioDeviceSettingsPanel&);
  54103. };
  54104. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& deviceManager_,
  54105. const int minInputChannels_,
  54106. const int maxInputChannels_,
  54107. const int minOutputChannels_,
  54108. const int maxOutputChannels_,
  54109. const bool showMidiInputOptions,
  54110. const bool showMidiOutputSelector,
  54111. const bool showChannelsAsStereoPairs_,
  54112. const bool hideAdvancedOptionsWithButton_)
  54113. : deviceManager (deviceManager_),
  54114. deviceTypeDropDown (0),
  54115. deviceTypeDropDownLabel (0),
  54116. audioDeviceSettingsComp (0),
  54117. minOutputChannels (minOutputChannels_),
  54118. maxOutputChannels (maxOutputChannels_),
  54119. minInputChannels (minInputChannels_),
  54120. maxInputChannels (maxInputChannels_),
  54121. showChannelsAsStereoPairs (showChannelsAsStereoPairs_),
  54122. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButton_)
  54123. {
  54124. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  54125. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  54126. if (deviceManager_.getAvailableDeviceTypes().size() > 1)
  54127. {
  54128. deviceTypeDropDown = new ComboBox (String::empty);
  54129. for (int i = 0; i < deviceManager_.getAvailableDeviceTypes().size(); ++i)
  54130. {
  54131. deviceTypeDropDown
  54132. ->addItem (deviceManager_.getAvailableDeviceTypes().getUnchecked(i)->getTypeName(),
  54133. i + 1);
  54134. }
  54135. addAndMakeVisible (deviceTypeDropDown);
  54136. deviceTypeDropDown->addListener (this);
  54137. deviceTypeDropDownLabel = new Label (String::empty, TRANS ("audio device type:"));
  54138. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  54139. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown, true);
  54140. }
  54141. if (showMidiInputOptions)
  54142. {
  54143. addAndMakeVisible (midiInputsList
  54144. = new MidiInputSelectorComponentListBox (deviceManager,
  54145. TRANS("(no midi inputs available)"),
  54146. 0, 0));
  54147. midiInputsLabel = new Label (String::empty, TRANS ("active midi inputs:"));
  54148. midiInputsLabel->setJustificationType (Justification::topRight);
  54149. midiInputsLabel->attachToComponent (midiInputsList, true);
  54150. }
  54151. else
  54152. {
  54153. midiInputsList = 0;
  54154. midiInputsLabel = 0;
  54155. }
  54156. if (showMidiOutputSelector)
  54157. {
  54158. addAndMakeVisible (midiOutputSelector = new ComboBox (String::empty));
  54159. midiOutputSelector->addListener (this);
  54160. midiOutputLabel = new Label ("lm", TRANS("Midi Output:"));
  54161. midiOutputLabel->attachToComponent (midiOutputSelector, true);
  54162. }
  54163. else
  54164. {
  54165. midiOutputSelector = 0;
  54166. midiOutputLabel = 0;
  54167. }
  54168. deviceManager_.addChangeListener (this);
  54169. changeListenerCallback (0);
  54170. }
  54171. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  54172. {
  54173. deviceManager.removeChangeListener (this);
  54174. deleteAllChildren();
  54175. }
  54176. void AudioDeviceSelectorComponent::resized()
  54177. {
  54178. const int lx = proportionOfWidth (0.35f);
  54179. const int w = proportionOfWidth (0.4f);
  54180. const int h = 24;
  54181. const int space = 6;
  54182. const int dh = h + space;
  54183. int y = 15;
  54184. if (deviceTypeDropDown != 0)
  54185. {
  54186. deviceTypeDropDown->setBounds (lx, y, proportionOfWidth (0.3f), h);
  54187. y += dh + space * 2;
  54188. }
  54189. if (audioDeviceSettingsComp != 0)
  54190. {
  54191. audioDeviceSettingsComp->setBounds (0, y, getWidth(), audioDeviceSettingsComp->getHeight());
  54192. y += audioDeviceSettingsComp->getHeight() + space;
  54193. }
  54194. if (midiInputsList != 0)
  54195. {
  54196. const int bh = midiInputsList->getBestHeight (jmin (h * 8, getHeight() - y - space - h));
  54197. midiInputsList->setBounds (lx, y, w, bh);
  54198. y += bh + space;
  54199. }
  54200. if (midiOutputSelector != 0)
  54201. midiOutputSelector->setBounds (lx, y, w, h);
  54202. }
  54203. void AudioDeviceSelectorComponent::buttonClicked (Button*)
  54204. {
  54205. AudioIODevice* const device = deviceManager.getCurrentAudioDevice();
  54206. if (device != 0 && device->hasControlPanel())
  54207. {
  54208. if (device->showControlPanel())
  54209. deviceManager.restartLastAudioDevice();
  54210. getTopLevelComponent()->toFront (true);
  54211. }
  54212. }
  54213. void AudioDeviceSelectorComponent::comboBoxChanged (ComboBox* comboBoxThatHasChanged)
  54214. {
  54215. if (comboBoxThatHasChanged == deviceTypeDropDown)
  54216. {
  54217. AudioIODeviceType* const type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1];
  54218. if (type != 0)
  54219. {
  54220. deleteAndZero (audioDeviceSettingsComp);
  54221. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  54222. changeListenerCallback (0); // needed in case the type hasn't actally changed
  54223. }
  54224. }
  54225. else if (comboBoxThatHasChanged == midiOutputSelector)
  54226. {
  54227. deviceManager.setDefaultMidiOutput (midiOutputSelector->getText());
  54228. }
  54229. }
  54230. void AudioDeviceSelectorComponent::changeListenerCallback (void*)
  54231. {
  54232. if (deviceTypeDropDown != 0)
  54233. {
  54234. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), false);
  54235. }
  54236. if (audioDeviceSettingsComp == 0
  54237. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  54238. {
  54239. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  54240. deleteAndZero (audioDeviceSettingsComp);
  54241. AudioIODeviceType* const type
  54242. = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == 0
  54243. ? 0 : deviceTypeDropDown->getSelectedId() - 1];
  54244. if (type != 0)
  54245. {
  54246. AudioIODeviceType::DeviceSetupDetails details;
  54247. details.manager = &deviceManager;
  54248. details.minNumInputChannels = minInputChannels;
  54249. details.maxNumInputChannels = maxInputChannels;
  54250. details.minNumOutputChannels = minOutputChannels;
  54251. details.maxNumOutputChannels = maxOutputChannels;
  54252. details.useStereoPairs = showChannelsAsStereoPairs;
  54253. audioDeviceSettingsComp = new AudioDeviceSettingsPanel (type, details, hideAdvancedOptionsWithButton);
  54254. if (audioDeviceSettingsComp != 0)
  54255. {
  54256. addAndMakeVisible (audioDeviceSettingsComp);
  54257. audioDeviceSettingsComp->resized();
  54258. }
  54259. }
  54260. }
  54261. if (midiInputsList != 0)
  54262. {
  54263. midiInputsList->updateContent();
  54264. midiInputsList->repaint();
  54265. }
  54266. if (midiOutputSelector != 0)
  54267. {
  54268. midiOutputSelector->clear();
  54269. const StringArray midiOuts (MidiOutput::getDevices());
  54270. midiOutputSelector->addItem (TRANS("<< none >>"), -1);
  54271. midiOutputSelector->addSeparator();
  54272. for (int i = 0; i < midiOuts.size(); ++i)
  54273. midiOutputSelector->addItem (midiOuts[i], i + 1);
  54274. int current = -1;
  54275. if (deviceManager.getDefaultMidiOutput() != 0)
  54276. current = 1 + midiOuts.indexOf (deviceManager.getDefaultMidiOutputName());
  54277. midiOutputSelector->setSelectedId (current, true);
  54278. }
  54279. resized();
  54280. }
  54281. END_JUCE_NAMESPACE
  54282. /********* End of inlined file: juce_AudioDeviceSelectorComponent.cpp *********/
  54283. /********* Start of inlined file: juce_BubbleComponent.cpp *********/
  54284. BEGIN_JUCE_NAMESPACE
  54285. BubbleComponent::BubbleComponent()
  54286. : side (0),
  54287. allowablePlacements (above | below | left | right),
  54288. arrowTipX (0.0f),
  54289. arrowTipY (0.0f)
  54290. {
  54291. setInterceptsMouseClicks (false, false);
  54292. shadow.setShadowProperties (5.0f, 0.35f, 0, 0);
  54293. setComponentEffect (&shadow);
  54294. }
  54295. BubbleComponent::~BubbleComponent()
  54296. {
  54297. }
  54298. void BubbleComponent::paint (Graphics& g)
  54299. {
  54300. int x = content.getX();
  54301. int y = content.getY();
  54302. int w = content.getWidth();
  54303. int h = content.getHeight();
  54304. int cw, ch;
  54305. getContentSize (cw, ch);
  54306. if (side == 3)
  54307. x += w - cw;
  54308. else if (side != 1)
  54309. x += (w - cw) / 2;
  54310. w = cw;
  54311. if (side == 2)
  54312. y += h - ch;
  54313. else if (side != 0)
  54314. y += (h - ch) / 2;
  54315. h = ch;
  54316. getLookAndFeel().drawBubble (g, arrowTipX, arrowTipY,
  54317. (float) x, (float) y,
  54318. (float) w, (float) h);
  54319. const int cx = x + (w - cw) / 2;
  54320. const int cy = y + (h - ch) / 2;
  54321. const int indent = 3;
  54322. g.setOrigin (cx + indent, cy + indent);
  54323. g.reduceClipRegion (0, 0, cw - indent * 2, ch - indent * 2);
  54324. paintContent (g, cw - indent * 2, ch - indent * 2);
  54325. }
  54326. void BubbleComponent::setAllowedPlacement (const int newPlacement)
  54327. {
  54328. allowablePlacements = newPlacement;
  54329. }
  54330. void BubbleComponent::setPosition (Component* componentToPointTo)
  54331. {
  54332. jassert (componentToPointTo->isValidComponent());
  54333. int tx = 0;
  54334. int ty = 0;
  54335. if (getParentComponent() != 0)
  54336. componentToPointTo->relativePositionToOtherComponent (getParentComponent(), tx, ty);
  54337. else
  54338. componentToPointTo->relativePositionToGlobal (tx, ty);
  54339. setPosition (Rectangle (tx, ty, componentToPointTo->getWidth(), componentToPointTo->getHeight()));
  54340. }
  54341. void BubbleComponent::setPosition (const int arrowTipX,
  54342. const int arrowTipY)
  54343. {
  54344. setPosition (Rectangle (arrowTipX, arrowTipY, 1, 1));
  54345. }
  54346. void BubbleComponent::setPosition (const Rectangle& rectangleToPointTo)
  54347. {
  54348. Rectangle availableSpace;
  54349. if (getParentComponent() != 0)
  54350. {
  54351. availableSpace.setSize (getParentComponent()->getWidth(),
  54352. getParentComponent()->getHeight());
  54353. }
  54354. else
  54355. {
  54356. availableSpace = getParentMonitorArea();
  54357. }
  54358. int x = 0;
  54359. int y = 0;
  54360. int w = 150;
  54361. int h = 30;
  54362. getContentSize (w, h);
  54363. w += 30;
  54364. h += 30;
  54365. const float edgeIndent = 2.0f;
  54366. const int arrowLength = jmin (10, h / 3, w / 3);
  54367. int spaceAbove = ((allowablePlacements & above) != 0) ? jmax (0, rectangleToPointTo.getY() - availableSpace.getY()) : -1;
  54368. int spaceBelow = ((allowablePlacements & below) != 0) ? jmax (0, availableSpace.getBottom() - rectangleToPointTo.getBottom()) : -1;
  54369. int spaceLeft = ((allowablePlacements & left) != 0) ? jmax (0, rectangleToPointTo.getX() - availableSpace.getX()) : -1;
  54370. int spaceRight = ((allowablePlacements & right) != 0) ? jmax (0, availableSpace.getRight() - rectangleToPointTo.getRight()) : -1;
  54371. // look at whether the component is elongated, and if so, try to position next to its longer dimension.
  54372. if (rectangleToPointTo.getWidth() > rectangleToPointTo.getHeight() * 2
  54373. && (spaceAbove > h + 20 || spaceBelow > h + 20))
  54374. {
  54375. spaceLeft = spaceRight = 0;
  54376. }
  54377. else if (rectangleToPointTo.getWidth() < rectangleToPointTo.getHeight() / 2
  54378. && (spaceLeft > w + 20 || spaceRight > w + 20))
  54379. {
  54380. spaceAbove = spaceBelow = 0;
  54381. }
  54382. if (jmax (spaceAbove, spaceBelow) >= jmax (spaceLeft, spaceRight))
  54383. {
  54384. x = rectangleToPointTo.getX() + (rectangleToPointTo.getWidth() - w) / 2;
  54385. arrowTipX = w * 0.5f;
  54386. content.setSize (w, h - arrowLength);
  54387. if (spaceAbove >= spaceBelow)
  54388. {
  54389. // above
  54390. y = rectangleToPointTo.getY() - h;
  54391. content.setPosition (0, 0);
  54392. arrowTipY = h - edgeIndent;
  54393. side = 2;
  54394. }
  54395. else
  54396. {
  54397. // below
  54398. y = rectangleToPointTo.getBottom();
  54399. content.setPosition (0, arrowLength);
  54400. arrowTipY = edgeIndent;
  54401. side = 0;
  54402. }
  54403. }
  54404. else
  54405. {
  54406. y = rectangleToPointTo.getY() + (rectangleToPointTo.getHeight() - h) / 2;
  54407. arrowTipY = h * 0.5f;
  54408. content.setSize (w - arrowLength, h);
  54409. if (spaceLeft > spaceRight)
  54410. {
  54411. // on the left
  54412. x = rectangleToPointTo.getX() - w;
  54413. content.setPosition (0, 0);
  54414. arrowTipX = w - edgeIndent;
  54415. side = 3;
  54416. }
  54417. else
  54418. {
  54419. // on the right
  54420. x = rectangleToPointTo.getRight();
  54421. content.setPosition (arrowLength, 0);
  54422. arrowTipX = edgeIndent;
  54423. side = 1;
  54424. }
  54425. }
  54426. setBounds (x, y, w, h);
  54427. }
  54428. END_JUCE_NAMESPACE
  54429. /********* End of inlined file: juce_BubbleComponent.cpp *********/
  54430. /********* Start of inlined file: juce_BubbleMessageComponent.cpp *********/
  54431. BEGIN_JUCE_NAMESPACE
  54432. BubbleMessageComponent::BubbleMessageComponent (int fadeOutLengthMs)
  54433. : fadeOutLength (fadeOutLengthMs),
  54434. deleteAfterUse (false)
  54435. {
  54436. }
  54437. BubbleMessageComponent::~BubbleMessageComponent()
  54438. {
  54439. fadeOutComponent (fadeOutLength);
  54440. }
  54441. void BubbleMessageComponent::showAt (int x, int y,
  54442. const String& text,
  54443. const int numMillisecondsBeforeRemoving,
  54444. const bool removeWhenMouseClicked,
  54445. const bool deleteSelfAfterUse)
  54446. {
  54447. textLayout.clear();
  54448. textLayout.setText (text, Font (14.0f));
  54449. textLayout.layout (256, Justification::centredLeft, true);
  54450. setPosition (x, y);
  54451. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  54452. }
  54453. void BubbleMessageComponent::showAt (Component* const component,
  54454. const String& text,
  54455. const int numMillisecondsBeforeRemoving,
  54456. const bool removeWhenMouseClicked,
  54457. const bool deleteSelfAfterUse)
  54458. {
  54459. textLayout.clear();
  54460. textLayout.setText (text, Font (14.0f));
  54461. textLayout.layout (256, Justification::centredLeft, true);
  54462. setPosition (component);
  54463. init (numMillisecondsBeforeRemoving, removeWhenMouseClicked, deleteSelfAfterUse);
  54464. }
  54465. void BubbleMessageComponent::init (const int numMillisecondsBeforeRemoving,
  54466. const bool removeWhenMouseClicked,
  54467. const bool deleteSelfAfterUse)
  54468. {
  54469. setVisible (true);
  54470. deleteAfterUse = deleteSelfAfterUse;
  54471. if (numMillisecondsBeforeRemoving > 0)
  54472. expiryTime = Time::getMillisecondCounter() + numMillisecondsBeforeRemoving;
  54473. else
  54474. expiryTime = 0;
  54475. startTimer (77);
  54476. mouseClickCounter = Desktop::getInstance().getMouseButtonClickCounter();
  54477. if (! (removeWhenMouseClicked && isShowing()))
  54478. mouseClickCounter += 0xfffff;
  54479. repaint();
  54480. }
  54481. void BubbleMessageComponent::getContentSize (int& w, int& h)
  54482. {
  54483. w = textLayout.getWidth() + 16;
  54484. h = textLayout.getHeight() + 16;
  54485. }
  54486. void BubbleMessageComponent::paintContent (Graphics& g, int w, int h)
  54487. {
  54488. g.setColour (findColour (TooltipWindow::textColourId));
  54489. textLayout.drawWithin (g, 0, 0, w, h, Justification::centred);
  54490. }
  54491. void BubbleMessageComponent::timerCallback()
  54492. {
  54493. if (Desktop::getInstance().getMouseButtonClickCounter() > mouseClickCounter)
  54494. {
  54495. stopTimer();
  54496. setVisible (false);
  54497. if (deleteAfterUse)
  54498. delete this;
  54499. }
  54500. else if (expiryTime != 0 && Time::getMillisecondCounter() > expiryTime)
  54501. {
  54502. stopTimer();
  54503. fadeOutComponent (fadeOutLength);
  54504. if (deleteAfterUse)
  54505. delete this;
  54506. }
  54507. }
  54508. END_JUCE_NAMESPACE
  54509. /********* End of inlined file: juce_BubbleMessageComponent.cpp *********/
  54510. /********* Start of inlined file: juce_ColourSelector.cpp *********/
  54511. BEGIN_JUCE_NAMESPACE
  54512. static const int swatchesPerRow = 8;
  54513. static const int swatchHeight = 22;
  54514. class ColourComponentSlider : public Slider
  54515. {
  54516. public:
  54517. ColourComponentSlider (const String& name)
  54518. : Slider (name)
  54519. {
  54520. setRange (0.0, 255.0, 1.0);
  54521. }
  54522. ~ColourComponentSlider()
  54523. {
  54524. }
  54525. const String getTextFromValue (double currentValue)
  54526. {
  54527. return String::formatted (T("%02X"), (int)currentValue);
  54528. }
  54529. double getValueFromText (const String& text)
  54530. {
  54531. return (double) text.getHexValue32();
  54532. }
  54533. private:
  54534. ColourComponentSlider (const ColourComponentSlider&);
  54535. const ColourComponentSlider& operator= (const ColourComponentSlider&);
  54536. };
  54537. class ColourSpaceMarker : public Component
  54538. {
  54539. public:
  54540. ColourSpaceMarker()
  54541. {
  54542. setInterceptsMouseClicks (false, false);
  54543. }
  54544. ~ColourSpaceMarker()
  54545. {
  54546. }
  54547. void paint (Graphics& g)
  54548. {
  54549. g.setColour (Colour::greyLevel (0.1f));
  54550. g.drawEllipse (1.0f, 1.0f, getWidth() - 2.0f, getHeight() - 2.0f, 1.0f);
  54551. g.setColour (Colour::greyLevel (0.9f));
  54552. g.drawEllipse (2.0f, 2.0f, getWidth() - 4.0f, getHeight() - 4.0f, 1.0f);
  54553. }
  54554. private:
  54555. ColourSpaceMarker (const ColourSpaceMarker&);
  54556. const ColourSpaceMarker& operator= (const ColourSpaceMarker&);
  54557. };
  54558. class ColourSpaceView : public Component
  54559. {
  54560. ColourSelector* const owner;
  54561. float& h;
  54562. float& s;
  54563. float& v;
  54564. float lastHue;
  54565. ColourSpaceMarker* marker;
  54566. const int edge;
  54567. public:
  54568. ColourSpaceView (ColourSelector* owner_,
  54569. float& h_, float& s_, float& v_,
  54570. const int edgeSize)
  54571. : owner (owner_),
  54572. h (h_), s (s_), v (v_),
  54573. lastHue (0.0f),
  54574. edge (edgeSize)
  54575. {
  54576. addAndMakeVisible (marker = new ColourSpaceMarker());
  54577. setMouseCursor (MouseCursor::CrosshairCursor);
  54578. }
  54579. ~ColourSpaceView()
  54580. {
  54581. deleteAllChildren();
  54582. }
  54583. void paint (Graphics& g)
  54584. {
  54585. const float hue = h;
  54586. const float xScale = 1.0f / (getWidth() - edge * 2);
  54587. const float yScale = 1.0f / (getHeight() - edge * 2);
  54588. const Rectangle clip (g.getClipBounds());
  54589. const int x1 = jmax (clip.getX(), edge) & ~1;
  54590. const int x2 = jmin (clip.getRight(), getWidth() - edge) | 1;
  54591. const int y1 = jmax (clip.getY(), edge) & ~1;
  54592. const int y2 = jmin (clip.getBottom(), getHeight() - edge) | 1;
  54593. for (int y = y1; y < y2; y += 2)
  54594. {
  54595. const float v = jlimit (0.0f, 1.0f, 1.0f - (y - edge) * yScale);
  54596. for (int x = x1; x < x2; x += 2)
  54597. {
  54598. const float s = jlimit (0.0f, 1.0f, (x - edge) * xScale);
  54599. g.setColour (Colour (hue, s, v, 1.0f));
  54600. g.fillRect (x, y, 2, 2);
  54601. }
  54602. }
  54603. }
  54604. void mouseDown (const MouseEvent& e)
  54605. {
  54606. mouseDrag (e);
  54607. }
  54608. void mouseDrag (const MouseEvent& e)
  54609. {
  54610. const float s = (e.x - edge) / (float) (getWidth() - edge * 2);
  54611. const float v = 1.0f - (e.y - edge) / (float) (getHeight() - edge * 2);
  54612. owner->setSV (s, v);
  54613. }
  54614. void updateIfNeeded()
  54615. {
  54616. if (lastHue != h)
  54617. {
  54618. lastHue = h;
  54619. repaint();
  54620. }
  54621. resized();
  54622. }
  54623. void resized()
  54624. {
  54625. marker->setBounds (roundFloatToInt ((getWidth() - edge * 2) * s),
  54626. roundFloatToInt ((getHeight() - edge * 2) * (1.0f - v)),
  54627. edge * 2, edge * 2);
  54628. }
  54629. private:
  54630. ColourSpaceView (const ColourSpaceView&);
  54631. const ColourSpaceView& operator= (const ColourSpaceView&);
  54632. };
  54633. class HueSelectorMarker : public Component
  54634. {
  54635. public:
  54636. HueSelectorMarker()
  54637. {
  54638. setInterceptsMouseClicks (false, false);
  54639. }
  54640. ~HueSelectorMarker()
  54641. {
  54642. }
  54643. void paint (Graphics& g)
  54644. {
  54645. Path p;
  54646. p.addTriangle (1.0f, 1.0f,
  54647. getWidth() * 0.3f, getHeight() * 0.5f,
  54648. 1.0f, getHeight() - 1.0f);
  54649. p.addTriangle (getWidth() - 1.0f, 1.0f,
  54650. getWidth() * 0.7f, getHeight() * 0.5f,
  54651. getWidth() - 1.0f, getHeight() - 1.0f);
  54652. g.setColour (Colours::white.withAlpha (0.75f));
  54653. g.fillPath (p);
  54654. g.setColour (Colours::black.withAlpha (0.75f));
  54655. g.strokePath (p, PathStrokeType (1.2f));
  54656. }
  54657. private:
  54658. HueSelectorMarker (const HueSelectorMarker&);
  54659. const HueSelectorMarker& operator= (const HueSelectorMarker&);
  54660. };
  54661. class HueSelectorComp : public Component
  54662. {
  54663. public:
  54664. HueSelectorComp (ColourSelector* owner_,
  54665. float& h_, float& s_, float& v_,
  54666. const int edgeSize)
  54667. : owner (owner_),
  54668. h (h_), s (s_), v (v_),
  54669. lastHue (0.0f),
  54670. edge (edgeSize)
  54671. {
  54672. addAndMakeVisible (marker = new HueSelectorMarker());
  54673. }
  54674. ~HueSelectorComp()
  54675. {
  54676. deleteAllChildren();
  54677. }
  54678. void paint (Graphics& g)
  54679. {
  54680. const float yScale = 1.0f / (getHeight() - edge * 2);
  54681. const Rectangle clip (g.getClipBounds());
  54682. for (int y = jmin (clip.getBottom(), getHeight() - edge); --y >= jmax (edge, clip.getY());)
  54683. {
  54684. g.setColour (Colour ((y - edge) * yScale, 1.0f, 1.0f, 1.0f));
  54685. g.fillRect (edge, y, getWidth() - edge * 2, 1);
  54686. }
  54687. }
  54688. void resized()
  54689. {
  54690. marker->setBounds (0, roundFloatToInt ((getHeight() - edge * 2) * h),
  54691. getWidth(), edge * 2);
  54692. }
  54693. void mouseDown (const MouseEvent& e)
  54694. {
  54695. mouseDrag (e);
  54696. }
  54697. void mouseDrag (const MouseEvent& e)
  54698. {
  54699. const float hue = (e.y - edge) / (float) (getHeight() - edge * 2);
  54700. owner->setHue (hue);
  54701. }
  54702. void updateIfNeeded()
  54703. {
  54704. resized();
  54705. }
  54706. private:
  54707. ColourSelector* const owner;
  54708. float& h;
  54709. float& s;
  54710. float& v;
  54711. float lastHue;
  54712. HueSelectorMarker* marker;
  54713. const int edge;
  54714. HueSelectorComp (const HueSelectorComp&);
  54715. const HueSelectorComp& operator= (const HueSelectorComp&);
  54716. };
  54717. class SwatchComponent : public Component
  54718. {
  54719. public:
  54720. SwatchComponent (ColourSelector* owner_, int index_)
  54721. : owner (owner_),
  54722. index (index_)
  54723. {
  54724. }
  54725. ~SwatchComponent()
  54726. {
  54727. }
  54728. void paint (Graphics& g)
  54729. {
  54730. const Colour colour (owner->getSwatchColour (index));
  54731. g.fillCheckerBoard (0, 0, getWidth(), getHeight(),
  54732. 6, 6,
  54733. Colour (0xffdddddd).overlaidWith (colour),
  54734. Colour (0xffffffff).overlaidWith (colour));
  54735. }
  54736. void mouseDown (const MouseEvent&)
  54737. {
  54738. PopupMenu m;
  54739. m.addItem (1, TRANS("Use this swatch as the current colour"));
  54740. m.addSeparator();
  54741. m.addItem (2, TRANS("Set this swatch to the current colour"));
  54742. const int r = m.showAt (this);
  54743. if (r == 1)
  54744. {
  54745. owner->setCurrentColour (owner->getSwatchColour (index));
  54746. }
  54747. else if (r == 2)
  54748. {
  54749. if (owner->getSwatchColour (index) != owner->getCurrentColour())
  54750. {
  54751. owner->setSwatchColour (index, owner->getCurrentColour());
  54752. repaint();
  54753. }
  54754. }
  54755. }
  54756. private:
  54757. ColourSelector* const owner;
  54758. const int index;
  54759. SwatchComponent (const SwatchComponent&);
  54760. const SwatchComponent& operator= (const SwatchComponent&);
  54761. };
  54762. ColourSelector::ColourSelector (const int flags_,
  54763. const int edgeGap_,
  54764. const int gapAroundColourSpaceComponent)
  54765. : colour (Colours::white),
  54766. flags (flags_),
  54767. topSpace (0),
  54768. edgeGap (edgeGap_)
  54769. {
  54770. // not much point having a selector with no components in it!
  54771. jassert ((flags_ & (showColourAtTop | showSliders | showColourspace)) != 0);
  54772. updateHSV();
  54773. if ((flags & showSliders) != 0)
  54774. {
  54775. addAndMakeVisible (sliders[0] = new ColourComponentSlider (TRANS ("red")));
  54776. addAndMakeVisible (sliders[1] = new ColourComponentSlider (TRANS ("green")));
  54777. addAndMakeVisible (sliders[2] = new ColourComponentSlider (TRANS ("blue")));
  54778. addChildComponent (sliders[3] = new ColourComponentSlider (TRANS ("alpha")));
  54779. sliders[3]->setVisible ((flags & showAlphaChannel) != 0);
  54780. for (int i = 4; --i >= 0;)
  54781. sliders[i]->addListener (this);
  54782. }
  54783. else
  54784. {
  54785. zeromem (sliders, sizeof (sliders));
  54786. }
  54787. if ((flags & showColourspace) != 0)
  54788. {
  54789. addAndMakeVisible (colourSpace = new ColourSpaceView (this, h, s, v, gapAroundColourSpaceComponent));
  54790. addAndMakeVisible (hueSelector = new HueSelectorComp (this, h, s, v, gapAroundColourSpaceComponent));
  54791. }
  54792. else
  54793. {
  54794. colourSpace = 0;
  54795. hueSelector = 0;
  54796. }
  54797. update();
  54798. }
  54799. ColourSelector::~ColourSelector()
  54800. {
  54801. dispatchPendingMessages();
  54802. deleteAllChildren();
  54803. }
  54804. const Colour ColourSelector::getCurrentColour() const
  54805. {
  54806. return ((flags & showAlphaChannel) != 0) ? colour
  54807. : colour.withAlpha ((uint8) 0xff);
  54808. }
  54809. void ColourSelector::setCurrentColour (const Colour& c)
  54810. {
  54811. if (c != colour)
  54812. {
  54813. colour = ((flags & showAlphaChannel) != 0) ? c : c.withAlpha ((uint8) 0xff);
  54814. updateHSV();
  54815. update();
  54816. }
  54817. }
  54818. void ColourSelector::setHue (float newH)
  54819. {
  54820. newH = jlimit (0.0f, 1.0f, newH);
  54821. if (h != newH)
  54822. {
  54823. h = newH;
  54824. colour = Colour (h, s, v, colour.getFloatAlpha());
  54825. update();
  54826. }
  54827. }
  54828. void ColourSelector::setSV (float newS, float newV)
  54829. {
  54830. newS = jlimit (0.0f, 1.0f, newS);
  54831. newV = jlimit (0.0f, 1.0f, newV);
  54832. if (s != newS || v != newV)
  54833. {
  54834. s = newS;
  54835. v = newV;
  54836. colour = Colour (h, s, v, colour.getFloatAlpha());
  54837. update();
  54838. }
  54839. }
  54840. void ColourSelector::updateHSV()
  54841. {
  54842. colour.getHSB (h, s, v);
  54843. }
  54844. void ColourSelector::update()
  54845. {
  54846. if (sliders[0] != 0)
  54847. {
  54848. sliders[0]->setValue ((int) colour.getRed());
  54849. sliders[1]->setValue ((int) colour.getGreen());
  54850. sliders[2]->setValue ((int) colour.getBlue());
  54851. sliders[3]->setValue ((int) colour.getAlpha());
  54852. }
  54853. if (colourSpace != 0)
  54854. {
  54855. ((ColourSpaceView*) colourSpace)->updateIfNeeded();
  54856. ((HueSelectorComp*) hueSelector)->updateIfNeeded();
  54857. }
  54858. if ((flags & showColourAtTop) != 0)
  54859. repaint (0, edgeGap, getWidth(), topSpace - edgeGap);
  54860. sendChangeMessage (this);
  54861. }
  54862. void ColourSelector::paint (Graphics& g)
  54863. {
  54864. g.fillAll (findColour (backgroundColourId));
  54865. if ((flags & showColourAtTop) != 0)
  54866. {
  54867. const Colour colour (getCurrentColour());
  54868. g.fillCheckerBoard (edgeGap, edgeGap, getWidth() - edgeGap - edgeGap, topSpace - edgeGap - edgeGap,
  54869. 10, 10,
  54870. Colour (0xffdddddd).overlaidWith (colour),
  54871. Colour (0xffffffff).overlaidWith (colour));
  54872. g.setColour (Colours::white.overlaidWith (colour).contrasting());
  54873. g.setFont (14.0f, true);
  54874. g.drawText (((flags & showAlphaChannel) != 0)
  54875. ? String::formatted (T("#%02X%02X%02X%02X"),
  54876. (int) colour.getAlpha(),
  54877. (int) colour.getRed(),
  54878. (int) colour.getGreen(),
  54879. (int) colour.getBlue())
  54880. : String::formatted (T("#%02X%02X%02X"),
  54881. (int) colour.getRed(),
  54882. (int) colour.getGreen(),
  54883. (int) colour.getBlue()),
  54884. 0, edgeGap, getWidth(), topSpace - edgeGap * 2,
  54885. Justification::centred, false);
  54886. }
  54887. if ((flags & showSliders) != 0)
  54888. {
  54889. g.setColour (findColour (labelTextColourId));
  54890. g.setFont (11.0f);
  54891. for (int i = 4; --i >= 0;)
  54892. {
  54893. if (sliders[i]->isVisible())
  54894. g.drawText (sliders[i]->getName() + T(":"),
  54895. 0, sliders[i]->getY(),
  54896. sliders[i]->getX() - 8, sliders[i]->getHeight(),
  54897. Justification::centredRight, false);
  54898. }
  54899. }
  54900. }
  54901. void ColourSelector::resized()
  54902. {
  54903. const int numSliders = ((flags & showAlphaChannel) != 0) ? 4 : 3;
  54904. const int numSwatches = getNumSwatches();
  54905. const int swatchSpace = numSwatches > 0 ? edgeGap + swatchHeight * ((numSwatches + 7) / swatchesPerRow) : 0;
  54906. const int sliderSpace = ((flags & showSliders) != 0) ? jmin (22 * numSliders + edgeGap, proportionOfHeight (0.3f)) : 0;
  54907. topSpace = ((flags & showColourAtTop) != 0) ? jmin (30 + edgeGap * 2, proportionOfHeight (0.2f)) : edgeGap;
  54908. int y = topSpace;
  54909. if ((flags & showColourspace) != 0)
  54910. {
  54911. const int hueWidth = jmin (50, proportionOfWidth (0.15f));
  54912. colourSpace->setBounds (edgeGap, y,
  54913. getWidth() - hueWidth - edgeGap - 4,
  54914. getHeight() - topSpace - sliderSpace - swatchSpace - edgeGap);
  54915. hueSelector->setBounds (colourSpace->getRight() + 4, y,
  54916. getWidth() - edgeGap - (colourSpace->getRight() + 4),
  54917. colourSpace->getHeight());
  54918. y = getHeight() - sliderSpace - swatchSpace - edgeGap;
  54919. }
  54920. if ((flags & showSliders) != 0)
  54921. {
  54922. const int sliderHeight = jmax (4, sliderSpace / numSliders);
  54923. for (int i = 0; i < numSliders; ++i)
  54924. {
  54925. sliders[i]->setBounds (proportionOfWidth (0.2f), y,
  54926. proportionOfWidth (0.72f), sliderHeight - 2);
  54927. y += sliderHeight;
  54928. }
  54929. }
  54930. if (numSwatches > 0)
  54931. {
  54932. const int startX = 8;
  54933. const int xGap = 4;
  54934. const int yGap = 4;
  54935. const int swatchWidth = (getWidth() - startX * 2) / swatchesPerRow;
  54936. y += edgeGap;
  54937. if (swatchComponents.size() != numSwatches)
  54938. {
  54939. int i;
  54940. for (i = swatchComponents.size(); --i >= 0;)
  54941. {
  54942. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  54943. delete sc;
  54944. }
  54945. for (i = 0; i < numSwatches; ++i)
  54946. {
  54947. SwatchComponent* const sc = new SwatchComponent (this, i);
  54948. swatchComponents.add (sc);
  54949. addAndMakeVisible (sc);
  54950. }
  54951. }
  54952. int x = startX;
  54953. for (int i = 0; i < swatchComponents.size(); ++i)
  54954. {
  54955. SwatchComponent* const sc = (SwatchComponent*) swatchComponents.getUnchecked(i);
  54956. sc->setBounds (x + xGap / 2,
  54957. y + yGap / 2,
  54958. swatchWidth - xGap,
  54959. swatchHeight - yGap);
  54960. if (((i + 1) % swatchesPerRow) == 0)
  54961. {
  54962. x = startX;
  54963. y += swatchHeight;
  54964. }
  54965. else
  54966. {
  54967. x += swatchWidth;
  54968. }
  54969. }
  54970. }
  54971. }
  54972. void ColourSelector::sliderValueChanged (Slider*)
  54973. {
  54974. if (sliders[0] != 0)
  54975. setCurrentColour (Colour ((uint8) sliders[0]->getValue(),
  54976. (uint8) sliders[1]->getValue(),
  54977. (uint8) sliders[2]->getValue(),
  54978. (uint8) sliders[3]->getValue()));
  54979. }
  54980. int ColourSelector::getNumSwatches() const
  54981. {
  54982. return 0;
  54983. }
  54984. const Colour ColourSelector::getSwatchColour (const int) const
  54985. {
  54986. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  54987. return Colours::black;
  54988. }
  54989. void ColourSelector::setSwatchColour (const int, const Colour&) const
  54990. {
  54991. jassertfalse // if you've overridden getNumSwatches(), you also need to implement this method
  54992. }
  54993. END_JUCE_NAMESPACE
  54994. /********* End of inlined file: juce_ColourSelector.cpp *********/
  54995. /********* Start of inlined file: juce_DropShadower.cpp *********/
  54996. BEGIN_JUCE_NAMESPACE
  54997. class ShadowWindow : public Component
  54998. {
  54999. Component* owner;
  55000. Image** shadowImageSections;
  55001. const int type; // 0 = left, 1 = right, 2 = top, 3 = bottom. left + right are full-height
  55002. public:
  55003. ShadowWindow (Component* const owner_,
  55004. const int type_,
  55005. Image** const shadowImageSections_)
  55006. : owner (owner_),
  55007. shadowImageSections (shadowImageSections_),
  55008. type (type_)
  55009. {
  55010. setInterceptsMouseClicks (false, false);
  55011. if (owner_->isOnDesktop())
  55012. {
  55013. setSize (1, 1); // to keep the OS happy by not having zero-size windows
  55014. addToDesktop (ComponentPeer::windowIgnoresMouseClicks
  55015. | ComponentPeer::windowIsTemporary);
  55016. }
  55017. else if (owner_->getParentComponent() != 0)
  55018. {
  55019. owner_->getParentComponent()->addChildComponent (this);
  55020. }
  55021. }
  55022. ~ShadowWindow()
  55023. {
  55024. }
  55025. void paint (Graphics& g)
  55026. {
  55027. Image* const topLeft = shadowImageSections [type * 3];
  55028. Image* const bottomRight = shadowImageSections [type * 3 + 1];
  55029. Image* const filler = shadowImageSections [type * 3 + 2];
  55030. ImageBrush fillBrush (filler, 0, 0, 1.0f);
  55031. g.setOpacity (1.0f);
  55032. if (type < 2)
  55033. {
  55034. int imH = jmin (topLeft->getHeight(), getHeight() / 2);
  55035. g.drawImage (topLeft,
  55036. 0, 0, topLeft->getWidth(), imH,
  55037. 0, 0, topLeft->getWidth(), imH);
  55038. imH = jmin (bottomRight->getHeight(), getHeight() - getHeight() / 2);
  55039. g.drawImage (bottomRight,
  55040. 0, getHeight() - imH, bottomRight->getWidth(), imH,
  55041. 0, bottomRight->getHeight() - imH, bottomRight->getWidth(), imH);
  55042. g.setBrush (&fillBrush);
  55043. g.fillRect (0, topLeft->getHeight(), getWidth(), getHeight() - (topLeft->getHeight() + bottomRight->getHeight()));
  55044. }
  55045. else
  55046. {
  55047. int imW = jmin (topLeft->getWidth(), getWidth() / 2);
  55048. g.drawImage (topLeft,
  55049. 0, 0, imW, topLeft->getHeight(),
  55050. 0, 0, imW, topLeft->getHeight());
  55051. imW = jmin (bottomRight->getWidth(), getWidth() - getWidth() / 2);
  55052. g.drawImage (bottomRight,
  55053. getWidth() - imW, 0, imW, bottomRight->getHeight(),
  55054. bottomRight->getWidth() - imW, 0, imW, bottomRight->getHeight());
  55055. g.setBrush (&fillBrush);
  55056. g.fillRect (topLeft->getWidth(), 0, getWidth() - (topLeft->getWidth() + bottomRight->getWidth()), getHeight());
  55057. }
  55058. }
  55059. void resized()
  55060. {
  55061. repaint(); // (needed for correct repainting)
  55062. }
  55063. private:
  55064. ShadowWindow (const ShadowWindow&);
  55065. const ShadowWindow& operator= (const ShadowWindow&);
  55066. };
  55067. DropShadower::DropShadower (const float alpha_,
  55068. const int xOffset_,
  55069. const int yOffset_,
  55070. const float blurRadius_)
  55071. : owner (0),
  55072. numShadows (0),
  55073. shadowEdge (jmax (xOffset_, yOffset_) + (int) blurRadius_),
  55074. xOffset (xOffset_),
  55075. yOffset (yOffset_),
  55076. alpha (alpha_),
  55077. blurRadius (blurRadius_),
  55078. inDestructor (false),
  55079. reentrant (false)
  55080. {
  55081. }
  55082. DropShadower::~DropShadower()
  55083. {
  55084. if (owner != 0)
  55085. owner->removeComponentListener (this);
  55086. inDestructor = true;
  55087. deleteShadowWindows();
  55088. }
  55089. void DropShadower::deleteShadowWindows()
  55090. {
  55091. if (numShadows > 0)
  55092. {
  55093. int i;
  55094. for (i = numShadows; --i >= 0;)
  55095. delete shadowWindows[i];
  55096. for (i = 12; --i >= 0;)
  55097. delete shadowImageSections[i];
  55098. numShadows = 0;
  55099. }
  55100. }
  55101. void DropShadower::setOwner (Component* componentToFollow)
  55102. {
  55103. if (componentToFollow != owner)
  55104. {
  55105. if (owner != 0)
  55106. owner->removeComponentListener (this);
  55107. // (the component can't be null)
  55108. jassert (componentToFollow != 0);
  55109. owner = componentToFollow;
  55110. jassert (owner != 0);
  55111. jassert (owner->isOpaque()); // doesn't work properly for semi-transparent comps!
  55112. owner->addComponentListener (this);
  55113. updateShadows();
  55114. }
  55115. }
  55116. void DropShadower::componentMovedOrResized (Component&, bool /*wasMoved*/, bool /*wasResized*/)
  55117. {
  55118. updateShadows();
  55119. }
  55120. void DropShadower::componentBroughtToFront (Component&)
  55121. {
  55122. bringShadowWindowsToFront();
  55123. }
  55124. void DropShadower::componentChildrenChanged (Component&)
  55125. {
  55126. }
  55127. void DropShadower::componentParentHierarchyChanged (Component&)
  55128. {
  55129. deleteShadowWindows();
  55130. updateShadows();
  55131. }
  55132. void DropShadower::componentVisibilityChanged (Component&)
  55133. {
  55134. updateShadows();
  55135. }
  55136. void DropShadower::updateShadows()
  55137. {
  55138. if (reentrant || inDestructor || (owner == 0))
  55139. return;
  55140. reentrant = true;
  55141. ComponentPeer* const nw = owner->getPeer();
  55142. const bool isOwnerVisible = owner->isVisible()
  55143. && (nw == 0 || ! nw->isMinimised());
  55144. const bool createShadowWindows = numShadows == 0
  55145. && owner->getWidth() > 0
  55146. && owner->getHeight() > 0
  55147. && isOwnerVisible
  55148. && (Desktop::canUseSemiTransparentWindows()
  55149. || owner->getParentComponent() != 0);
  55150. if (createShadowWindows)
  55151. {
  55152. // keep a cached version of the image to save doing the gaussian too often
  55153. String imageId;
  55154. imageId << shadowEdge << T(',')
  55155. << xOffset << T(',')
  55156. << yOffset << T(',')
  55157. << alpha;
  55158. const int hash = imageId.hashCode();
  55159. Image* bigIm = ImageCache::getFromHashCode (hash);
  55160. if (bigIm == 0)
  55161. {
  55162. bigIm = new Image (Image::ARGB, shadowEdge * 5, shadowEdge * 5, true);
  55163. Graphics bigG (*bigIm);
  55164. bigG.setColour (Colours::black.withAlpha (alpha));
  55165. bigG.fillRect (shadowEdge + xOffset,
  55166. shadowEdge + yOffset,
  55167. bigIm->getWidth() - (shadowEdge * 2),
  55168. bigIm->getHeight() - (shadowEdge * 2));
  55169. ImageConvolutionKernel blurKernel (roundFloatToInt (blurRadius * 2.0f));
  55170. blurKernel.createGaussianBlur (blurRadius);
  55171. blurKernel.applyToImage (*bigIm, 0,
  55172. xOffset,
  55173. yOffset,
  55174. bigIm->getWidth(),
  55175. bigIm->getHeight());
  55176. ImageCache::addImageToCache (bigIm, hash);
  55177. }
  55178. const int iw = bigIm->getWidth();
  55179. const int ih = bigIm->getHeight();
  55180. const int shadowEdge2 = shadowEdge * 2;
  55181. setShadowImage (bigIm, 0, shadowEdge, shadowEdge2, 0, 0);
  55182. setShadowImage (bigIm, 1, shadowEdge, shadowEdge2, 0, ih - shadowEdge2);
  55183. setShadowImage (bigIm, 2, shadowEdge, shadowEdge, 0, shadowEdge2);
  55184. setShadowImage (bigIm, 3, shadowEdge, shadowEdge2, iw - shadowEdge, 0);
  55185. setShadowImage (bigIm, 4, shadowEdge, shadowEdge2, iw - shadowEdge, ih - shadowEdge2);
  55186. setShadowImage (bigIm, 5, shadowEdge, shadowEdge, iw - shadowEdge, shadowEdge2);
  55187. setShadowImage (bigIm, 6, shadowEdge, shadowEdge, shadowEdge, 0);
  55188. setShadowImage (bigIm, 7, shadowEdge, shadowEdge, iw - shadowEdge2, 0);
  55189. setShadowImage (bigIm, 8, shadowEdge, shadowEdge, shadowEdge2, 0);
  55190. setShadowImage (bigIm, 9, shadowEdge, shadowEdge, shadowEdge, ih - shadowEdge);
  55191. setShadowImage (bigIm, 10, shadowEdge, shadowEdge, iw - shadowEdge2, ih - shadowEdge);
  55192. setShadowImage (bigIm, 11, shadowEdge, shadowEdge, shadowEdge2, ih - shadowEdge);
  55193. ImageCache::release (bigIm);
  55194. for (int i = 0; i < 4; ++i)
  55195. {
  55196. shadowWindows[numShadows] = new ShadowWindow (owner, i, shadowImageSections);
  55197. ++numShadows;
  55198. }
  55199. }
  55200. if (numShadows > 0)
  55201. {
  55202. for (int i = numShadows; --i >= 0;)
  55203. {
  55204. shadowWindows[i]->setAlwaysOnTop (owner->isAlwaysOnTop());
  55205. shadowWindows[i]->setVisible (isOwnerVisible);
  55206. }
  55207. const int x = owner->getX();
  55208. const int y = owner->getY() - shadowEdge;
  55209. const int w = owner->getWidth();
  55210. const int h = owner->getHeight() + shadowEdge + shadowEdge;
  55211. shadowWindows[0]->setBounds (x - shadowEdge,
  55212. y,
  55213. shadowEdge,
  55214. h);
  55215. shadowWindows[1]->setBounds (x + w,
  55216. y,
  55217. shadowEdge,
  55218. h);
  55219. shadowWindows[2]->setBounds (x,
  55220. y,
  55221. w,
  55222. shadowEdge);
  55223. shadowWindows[3]->setBounds (x,
  55224. owner->getBottom(),
  55225. w,
  55226. shadowEdge);
  55227. }
  55228. reentrant = false;
  55229. if (createShadowWindows)
  55230. bringShadowWindowsToFront();
  55231. }
  55232. void DropShadower::setShadowImage (Image* const src,
  55233. const int num,
  55234. const int w,
  55235. const int h,
  55236. const int sx,
  55237. const int sy) throw()
  55238. {
  55239. shadowImageSections[num] = new Image (Image::ARGB, w, h, true);
  55240. Graphics g (*shadowImageSections[num]);
  55241. g.drawImage (src, 0, 0, w, h, sx, sy, w, h);
  55242. }
  55243. void DropShadower::bringShadowWindowsToFront()
  55244. {
  55245. if (! (inDestructor || reentrant))
  55246. {
  55247. updateShadows();
  55248. reentrant = true;
  55249. for (int i = numShadows; --i >= 0;)
  55250. shadowWindows[i]->toBehind (owner);
  55251. reentrant = false;
  55252. }
  55253. }
  55254. END_JUCE_NAMESPACE
  55255. /********* End of inlined file: juce_DropShadower.cpp *********/
  55256. /********* Start of inlined file: juce_MagnifierComponent.cpp *********/
  55257. BEGIN_JUCE_NAMESPACE
  55258. class MagnifyingPeer : public ComponentPeer
  55259. {
  55260. public:
  55261. MagnifyingPeer (Component* const component,
  55262. MagnifierComponent* const magnifierComp_)
  55263. : ComponentPeer (component, 0),
  55264. magnifierComp (magnifierComp_)
  55265. {
  55266. }
  55267. ~MagnifyingPeer()
  55268. {
  55269. }
  55270. void* getNativeHandle() const { return 0; }
  55271. void setVisible (bool) {}
  55272. void setTitle (const String&) {}
  55273. void setPosition (int, int) {}
  55274. void setSize (int, int) {}
  55275. void setBounds (int, int, int, int, const bool) {}
  55276. void setMinimised (bool) {}
  55277. bool isMinimised() const { return false; }
  55278. void setFullScreen (bool) {}
  55279. bool isFullScreen() const { return false; }
  55280. const BorderSize getFrameSize() const { return BorderSize (0); }
  55281. bool setAlwaysOnTop (bool) { return true; }
  55282. void toFront (bool) {}
  55283. void toBehind (ComponentPeer*) {}
  55284. void setIcon (const Image&) {}
  55285. bool isFocused() const
  55286. {
  55287. return magnifierComp->hasKeyboardFocus (true);
  55288. }
  55289. void grabFocus()
  55290. {
  55291. ComponentPeer* peer = magnifierComp->getPeer();
  55292. if (peer != 0)
  55293. peer->grabFocus();
  55294. }
  55295. void textInputRequired (int x, int y)
  55296. {
  55297. ComponentPeer* peer = magnifierComp->getPeer();
  55298. if (peer != 0)
  55299. peer->textInputRequired (x, y);
  55300. }
  55301. void getBounds (int& x, int& y, int& w, int& h) const
  55302. {
  55303. x = magnifierComp->getScreenX();
  55304. y = magnifierComp->getScreenY();
  55305. w = component->getWidth();
  55306. h = component->getHeight();
  55307. }
  55308. int getScreenX() const { return magnifierComp->getScreenX(); }
  55309. int getScreenY() const { return magnifierComp->getScreenY(); }
  55310. void relativePositionToGlobal (int& x, int& y)
  55311. {
  55312. const double zoom = magnifierComp->getScaleFactor();
  55313. x = roundDoubleToInt (x * zoom);
  55314. y = roundDoubleToInt (y * zoom);
  55315. magnifierComp->relativePositionToGlobal (x, y);
  55316. }
  55317. void globalPositionToRelative (int& x, int& y)
  55318. {
  55319. magnifierComp->globalPositionToRelative (x, y);
  55320. const double zoom = magnifierComp->getScaleFactor();
  55321. x = roundDoubleToInt (x / zoom);
  55322. y = roundDoubleToInt (y / zoom);
  55323. }
  55324. bool contains (int x, int y, bool) const
  55325. {
  55326. return ((unsigned int) x) < (unsigned int) magnifierComp->getWidth()
  55327. && ((unsigned int) y) < (unsigned int) magnifierComp->getHeight();
  55328. }
  55329. void repaint (int x, int y, int w, int h)
  55330. {
  55331. const double zoom = magnifierComp->getScaleFactor();
  55332. magnifierComp->repaint ((int) (x * zoom),
  55333. (int) (y * zoom),
  55334. roundDoubleToInt (w * zoom) + 1,
  55335. roundDoubleToInt (h * zoom) + 1);
  55336. }
  55337. void performAnyPendingRepaintsNow()
  55338. {
  55339. }
  55340. juce_UseDebuggingNewOperator
  55341. private:
  55342. MagnifierComponent* const magnifierComp;
  55343. MagnifyingPeer (const MagnifyingPeer&);
  55344. const MagnifyingPeer& operator= (const MagnifyingPeer&);
  55345. };
  55346. class PeerHolderComp : public Component
  55347. {
  55348. public:
  55349. PeerHolderComp (MagnifierComponent* const magnifierComp_)
  55350. : magnifierComp (magnifierComp_)
  55351. {
  55352. setVisible (true);
  55353. }
  55354. ~PeerHolderComp()
  55355. {
  55356. }
  55357. ComponentPeer* createNewPeer (int, void*)
  55358. {
  55359. return new MagnifyingPeer (this, magnifierComp);
  55360. }
  55361. void childBoundsChanged (Component* c)
  55362. {
  55363. if (c != 0)
  55364. {
  55365. setSize (c->getWidth(), c->getHeight());
  55366. magnifierComp->childBoundsChanged (this);
  55367. }
  55368. }
  55369. void mouseWheelMove (const MouseEvent& e, float ix, float iy)
  55370. {
  55371. // unhandled mouse wheel moves can be referred upwards to the parent comp..
  55372. Component* const p = magnifierComp->getParentComponent();
  55373. if (p != 0)
  55374. p->mouseWheelMove (e.getEventRelativeTo (p), ix, iy);
  55375. }
  55376. private:
  55377. MagnifierComponent* const magnifierComp;
  55378. PeerHolderComp (const PeerHolderComp&);
  55379. const PeerHolderComp& operator= (const PeerHolderComp&);
  55380. };
  55381. MagnifierComponent::MagnifierComponent (Component* const content_,
  55382. const bool deleteContentCompWhenNoLongerNeeded)
  55383. : content (content_),
  55384. scaleFactor (0.0),
  55385. peer (0),
  55386. deleteContent (deleteContentCompWhenNoLongerNeeded)
  55387. {
  55388. holderComp = new PeerHolderComp (this);
  55389. setScaleFactor (1.0);
  55390. }
  55391. MagnifierComponent::~MagnifierComponent()
  55392. {
  55393. delete holderComp;
  55394. if (deleteContent)
  55395. delete content;
  55396. }
  55397. void MagnifierComponent::setScaleFactor (double newScaleFactor)
  55398. {
  55399. jassert (newScaleFactor > 0.0); // hmm - unlikely to work well with a negative scale factor
  55400. newScaleFactor = jlimit (1.0 / 8.0, 1000.0, newScaleFactor);
  55401. if (scaleFactor != newScaleFactor)
  55402. {
  55403. scaleFactor = newScaleFactor;
  55404. if (scaleFactor == 1.0)
  55405. {
  55406. holderComp->removeFromDesktop();
  55407. peer = 0;
  55408. addChildComponent (content);
  55409. childBoundsChanged (content);
  55410. }
  55411. else
  55412. {
  55413. holderComp->addAndMakeVisible (content);
  55414. holderComp->childBoundsChanged (content);
  55415. childBoundsChanged (holderComp);
  55416. holderComp->addToDesktop (0);
  55417. peer = holderComp->getPeer();
  55418. }
  55419. repaint();
  55420. }
  55421. }
  55422. void MagnifierComponent::paint (Graphics& g)
  55423. {
  55424. const int w = holderComp->getWidth();
  55425. const int h = holderComp->getHeight();
  55426. if (w == 0 || h == 0)
  55427. return;
  55428. const Rectangle r (g.getClipBounds());
  55429. const int srcX = (int) (r.getX() / scaleFactor);
  55430. const int srcY = (int) (r.getY() / scaleFactor);
  55431. int srcW = roundDoubleToInt (r.getRight() / scaleFactor) - srcX;
  55432. int srcH = roundDoubleToInt (r.getBottom() / scaleFactor) - srcY;
  55433. if (scaleFactor >= 1.0)
  55434. {
  55435. ++srcW;
  55436. ++srcH;
  55437. }
  55438. Image temp (Image::ARGB, jmax (w, srcX + srcW), jmax (h, srcY + srcH), false);
  55439. temp.clear (srcX, srcY, srcW, srcH);
  55440. Graphics g2 (temp);
  55441. g2.reduceClipRegion (srcX, srcY, srcW, srcH);
  55442. holderComp->paintEntireComponent (g2);
  55443. g.setImageResamplingQuality (Graphics::lowResamplingQuality);
  55444. g.drawImage (&temp,
  55445. 0, 0, (int) (w * scaleFactor), (int) (h * scaleFactor),
  55446. 0, 0, w, h,
  55447. false);
  55448. }
  55449. void MagnifierComponent::childBoundsChanged (Component* c)
  55450. {
  55451. if (c != 0)
  55452. setSize (roundDoubleToInt (c->getWidth() * scaleFactor),
  55453. roundDoubleToInt (c->getHeight() * scaleFactor));
  55454. }
  55455. void MagnifierComponent::mouseDown (const MouseEvent& e)
  55456. {
  55457. if (peer != 0)
  55458. peer->handleMouseDown (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  55459. }
  55460. void MagnifierComponent::mouseUp (const MouseEvent& e)
  55461. {
  55462. if (peer != 0)
  55463. peer->handleMouseUp (e.mods.getRawFlags(), scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  55464. }
  55465. void MagnifierComponent::mouseDrag (const MouseEvent& e)
  55466. {
  55467. if (peer != 0)
  55468. peer->handleMouseDrag (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  55469. }
  55470. void MagnifierComponent::mouseMove (const MouseEvent& e)
  55471. {
  55472. if (peer != 0)
  55473. peer->handleMouseMove (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  55474. }
  55475. void MagnifierComponent::mouseEnter (const MouseEvent& e)
  55476. {
  55477. if (peer != 0)
  55478. peer->handleMouseEnter (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  55479. }
  55480. void MagnifierComponent::mouseExit (const MouseEvent& e)
  55481. {
  55482. if (peer != 0)
  55483. peer->handleMouseExit (scaleInt (e.x), scaleInt (e.y), e.eventTime.toMilliseconds());
  55484. }
  55485. void MagnifierComponent::mouseWheelMove (const MouseEvent& e, float ix, float iy)
  55486. {
  55487. if (peer != 0)
  55488. peer->handleMouseWheel (roundFloatToInt (ix * 256.0f),
  55489. roundFloatToInt (iy * 256.0f),
  55490. e.eventTime.toMilliseconds());
  55491. else
  55492. Component::mouseWheelMove (e, ix, iy);
  55493. }
  55494. int MagnifierComponent::scaleInt (const int n) const throw()
  55495. {
  55496. return roundDoubleToInt (n / scaleFactor);
  55497. }
  55498. END_JUCE_NAMESPACE
  55499. /********* End of inlined file: juce_MagnifierComponent.cpp *********/
  55500. /********* Start of inlined file: juce_MidiKeyboardComponent.cpp *********/
  55501. BEGIN_JUCE_NAMESPACE
  55502. class MidiKeyboardUpDownButton : public Button
  55503. {
  55504. public:
  55505. MidiKeyboardUpDownButton (MidiKeyboardComponent* const owner_,
  55506. const int delta_)
  55507. : Button (String::empty),
  55508. owner (owner_),
  55509. delta (delta_)
  55510. {
  55511. setOpaque (true);
  55512. }
  55513. ~MidiKeyboardUpDownButton()
  55514. {
  55515. }
  55516. void clicked()
  55517. {
  55518. int note = owner->getLowestVisibleKey();
  55519. if (delta < 0)
  55520. note = (note - 1) / 12;
  55521. else
  55522. note = note / 12 + 1;
  55523. owner->setLowestVisibleKey (note * 12);
  55524. }
  55525. void paintButton (Graphics& g,
  55526. bool isMouseOverButton,
  55527. bool isButtonDown)
  55528. {
  55529. owner->drawUpDownButton (g, getWidth(), getHeight(),
  55530. isMouseOverButton, isButtonDown,
  55531. delta > 0);
  55532. }
  55533. private:
  55534. MidiKeyboardComponent* const owner;
  55535. const int delta;
  55536. MidiKeyboardUpDownButton (const MidiKeyboardUpDownButton&);
  55537. const MidiKeyboardUpDownButton& operator= (const MidiKeyboardUpDownButton&);
  55538. };
  55539. MidiKeyboardComponent::MidiKeyboardComponent (MidiKeyboardState& state_,
  55540. const Orientation orientation_)
  55541. : state (state_),
  55542. xOffset (0),
  55543. blackNoteLength (1),
  55544. keyWidth (16.0f),
  55545. orientation (orientation_),
  55546. midiChannel (1),
  55547. midiInChannelMask (0xffff),
  55548. velocity (1.0f),
  55549. noteUnderMouse (-1),
  55550. mouseDownNote (-1),
  55551. rangeStart (0),
  55552. rangeEnd (127),
  55553. firstKey (12 * 4),
  55554. canScroll (true),
  55555. mouseDragging (false),
  55556. keyPresses (4),
  55557. keyPressNotes (16),
  55558. keyMappingOctave (6),
  55559. octaveNumForMiddleC (3)
  55560. {
  55561. addChildComponent (scrollDown = new MidiKeyboardUpDownButton (this, -1));
  55562. addChildComponent (scrollUp = new MidiKeyboardUpDownButton (this, 1));
  55563. // initialise with a default set of querty key-mappings..
  55564. const char* const keymap = "awsedftgyhujkolp;";
  55565. for (int i = String (keymap).length(); --i >= 0;)
  55566. setKeyPressForNote (KeyPress (keymap[i], 0, 0), i);
  55567. setOpaque (true);
  55568. setWantsKeyboardFocus (true);
  55569. state.addListener (this);
  55570. }
  55571. MidiKeyboardComponent::~MidiKeyboardComponent()
  55572. {
  55573. state.removeListener (this);
  55574. jassert (mouseDownNote < 0 && keysPressed.countNumberOfSetBits() == 0); // leaving stuck notes!
  55575. deleteAllChildren();
  55576. }
  55577. void MidiKeyboardComponent::setKeyWidth (const float widthInPixels)
  55578. {
  55579. keyWidth = widthInPixels;
  55580. resized();
  55581. }
  55582. void MidiKeyboardComponent::setOrientation (const Orientation newOrientation)
  55583. {
  55584. if (orientation != newOrientation)
  55585. {
  55586. orientation = newOrientation;
  55587. resized();
  55588. }
  55589. }
  55590. void MidiKeyboardComponent::setAvailableRange (const int lowestNote,
  55591. const int highestNote)
  55592. {
  55593. jassert (lowestNote >= 0 && lowestNote <= 127);
  55594. jassert (highestNote >= 0 && highestNote <= 127);
  55595. jassert (lowestNote <= highestNote);
  55596. if (rangeStart != lowestNote || rangeEnd != highestNote)
  55597. {
  55598. rangeStart = jlimit (0, 127, lowestNote);
  55599. rangeEnd = jlimit (0, 127, highestNote);
  55600. firstKey = jlimit (rangeStart, rangeEnd, firstKey);
  55601. resized();
  55602. }
  55603. }
  55604. void MidiKeyboardComponent::setLowestVisibleKey (int noteNumber)
  55605. {
  55606. noteNumber = jlimit (rangeStart, rangeEnd, noteNumber);
  55607. if (noteNumber != firstKey)
  55608. {
  55609. firstKey = noteNumber;
  55610. sendChangeMessage (this);
  55611. resized();
  55612. }
  55613. }
  55614. void MidiKeyboardComponent::setScrollButtonsVisible (const bool canScroll_)
  55615. {
  55616. if (canScroll != canScroll_)
  55617. {
  55618. canScroll = canScroll_;
  55619. resized();
  55620. }
  55621. }
  55622. void MidiKeyboardComponent::colourChanged()
  55623. {
  55624. repaint();
  55625. }
  55626. void MidiKeyboardComponent::setMidiChannel (const int midiChannelNumber)
  55627. {
  55628. jassert (midiChannelNumber > 0 && midiChannelNumber <= 16);
  55629. if (midiChannel != midiChannelNumber)
  55630. {
  55631. resetAnyKeysInUse();
  55632. midiChannel = jlimit (1, 16, midiChannelNumber);
  55633. }
  55634. }
  55635. void MidiKeyboardComponent::setMidiChannelsToDisplay (const int midiChannelMask)
  55636. {
  55637. midiInChannelMask = midiChannelMask;
  55638. triggerAsyncUpdate();
  55639. }
  55640. void MidiKeyboardComponent::setVelocity (const float velocity_)
  55641. {
  55642. velocity = jlimit (0.0f, 1.0f, velocity_);
  55643. }
  55644. void MidiKeyboardComponent::getKeyPosition (int midiNoteNumber, const float keyWidth, int& x, int& w) const
  55645. {
  55646. jassert (midiNoteNumber >= 0 && midiNoteNumber < 128);
  55647. static const float blackNoteWidth = 0.7f;
  55648. static const float notePos[] = { 0.0f, 1 - blackNoteWidth * 0.6f,
  55649. 1.0f, 2 - blackNoteWidth * 0.4f,
  55650. 2.0f, 3.0f, 4 - blackNoteWidth * 0.7f,
  55651. 4.0f, 5 - blackNoteWidth * 0.5f,
  55652. 5.0f, 6 - blackNoteWidth * 0.3f,
  55653. 6.0f };
  55654. static const float widths[] = { 1.0f, blackNoteWidth,
  55655. 1.0f, blackNoteWidth,
  55656. 1.0f, 1.0f, blackNoteWidth,
  55657. 1.0f, blackNoteWidth,
  55658. 1.0f, blackNoteWidth,
  55659. 1.0f };
  55660. const int octave = midiNoteNumber / 12;
  55661. const int note = midiNoteNumber % 12;
  55662. x = roundFloatToInt (octave * 7.0f * keyWidth + notePos [note] * keyWidth);
  55663. w = roundFloatToInt (widths [note] * keyWidth);
  55664. }
  55665. void MidiKeyboardComponent::getKeyPos (int midiNoteNumber, int& x, int& w) const
  55666. {
  55667. getKeyPosition (midiNoteNumber, keyWidth, x, w);
  55668. int rx, rw;
  55669. getKeyPosition (rangeStart, keyWidth, rx, rw);
  55670. x -= xOffset + rx;
  55671. }
  55672. int MidiKeyboardComponent::getKeyStartPosition (const int midiNoteNumber) const
  55673. {
  55674. int x, y;
  55675. getKeyPos (midiNoteNumber, x, y);
  55676. return x;
  55677. }
  55678. static const uint8 whiteNotes[] = { 0, 2, 4, 5, 7, 9, 11 };
  55679. static const uint8 blackNotes[] = { 1, 3, 6, 8, 10 };
  55680. int MidiKeyboardComponent::xyToNote (int x, int y)
  55681. {
  55682. if (! reallyContains (x, y, false))
  55683. return -1;
  55684. if (orientation != horizontalKeyboard)
  55685. {
  55686. swapVariables (x, y);
  55687. if (orientation == verticalKeyboardFacingLeft)
  55688. y = getWidth() - y;
  55689. else
  55690. x = getHeight() - x;
  55691. }
  55692. return remappedXYToNote (x + xOffset, y);
  55693. }
  55694. int MidiKeyboardComponent::remappedXYToNote (int x, int y) const
  55695. {
  55696. if (y < blackNoteLength)
  55697. {
  55698. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  55699. {
  55700. for (int i = 0; i < 5; ++i)
  55701. {
  55702. const int note = octaveStart + blackNotes [i];
  55703. if (note >= rangeStart && note <= rangeEnd)
  55704. {
  55705. int kx, kw;
  55706. getKeyPos (note, kx, kw);
  55707. kx += xOffset;
  55708. if (x >= kx && x < kx + kw)
  55709. return note;
  55710. }
  55711. }
  55712. }
  55713. }
  55714. for (int octaveStart = 12 * (rangeStart / 12); octaveStart <= rangeEnd; octaveStart += 12)
  55715. {
  55716. for (int i = 0; i < 7; ++i)
  55717. {
  55718. const int note = octaveStart + whiteNotes [i];
  55719. if (note >= rangeStart && note <= rangeEnd)
  55720. {
  55721. int kx, kw;
  55722. getKeyPos (note, kx, kw);
  55723. kx += xOffset;
  55724. if (x >= kx && x < kx + kw)
  55725. return note;
  55726. }
  55727. }
  55728. }
  55729. return -1;
  55730. }
  55731. void MidiKeyboardComponent::repaintNote (const int noteNum)
  55732. {
  55733. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  55734. {
  55735. int x, w;
  55736. getKeyPos (noteNum, x, w);
  55737. if (orientation == horizontalKeyboard)
  55738. repaint (x, 0, w, getHeight());
  55739. else if (orientation == verticalKeyboardFacingLeft)
  55740. repaint (0, x, getWidth(), w);
  55741. else if (orientation == verticalKeyboardFacingRight)
  55742. repaint (0, getHeight() - x - w, getWidth(), w);
  55743. }
  55744. }
  55745. void MidiKeyboardComponent::paint (Graphics& g)
  55746. {
  55747. g.fillAll (Colours::white.overlaidWith (findColour (whiteNoteColourId)));
  55748. const Colour lineColour (findColour (keySeparatorLineColourId));
  55749. const Colour textColour (findColour (textLabelColourId));
  55750. int x, w, octave;
  55751. for (octave = 0; octave < 128; octave += 12)
  55752. {
  55753. for (int white = 0; white < 7; ++white)
  55754. {
  55755. const int noteNum = octave + whiteNotes [white];
  55756. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  55757. {
  55758. getKeyPos (noteNum, x, w);
  55759. if (orientation == horizontalKeyboard)
  55760. drawWhiteNote (noteNum, g, x, 0, w, getHeight(),
  55761. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  55762. noteUnderMouse == noteNum,
  55763. lineColour, textColour);
  55764. else if (orientation == verticalKeyboardFacingLeft)
  55765. drawWhiteNote (noteNum, g, 0, x, getWidth(), w,
  55766. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  55767. noteUnderMouse == noteNum,
  55768. lineColour, textColour);
  55769. else if (orientation == verticalKeyboardFacingRight)
  55770. drawWhiteNote (noteNum, g, 0, getHeight() - x - w, getWidth(), w,
  55771. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  55772. noteUnderMouse == noteNum,
  55773. lineColour, textColour);
  55774. }
  55775. }
  55776. }
  55777. float x1 = 0.0f, y1 = 0.0f, x2 = 0.0f, y2 = 0.0f;
  55778. if (orientation == verticalKeyboardFacingLeft)
  55779. {
  55780. x1 = getWidth() - 1.0f;
  55781. x2 = getWidth() - 5.0f;
  55782. }
  55783. else if (orientation == verticalKeyboardFacingRight)
  55784. x2 = 5.0f;
  55785. else
  55786. y2 = 5.0f;
  55787. GradientBrush gb (Colours::black.withAlpha (0.3f), x1, y1,
  55788. Colours::transparentBlack, x2, y2, false);
  55789. g.setBrush (&gb);
  55790. getKeyPos (rangeEnd, x, w);
  55791. x += w;
  55792. if (orientation == verticalKeyboardFacingLeft)
  55793. g.fillRect (getWidth() - 5, 0, 5, x);
  55794. else if (orientation == verticalKeyboardFacingRight)
  55795. g.fillRect (0, 0, 5, x);
  55796. else
  55797. g.fillRect (0, 0, x, 5);
  55798. g.setColour (lineColour);
  55799. if (orientation == verticalKeyboardFacingLeft)
  55800. g.fillRect (0, 0, 1, x);
  55801. else if (orientation == verticalKeyboardFacingRight)
  55802. g.fillRect (getWidth() - 1, 0, 1, x);
  55803. else
  55804. g.fillRect (0, getHeight() - 1, x, 1);
  55805. const Colour blackNoteColour (findColour (blackNoteColourId));
  55806. for (octave = 0; octave < 128; octave += 12)
  55807. {
  55808. for (int black = 0; black < 5; ++black)
  55809. {
  55810. const int noteNum = octave + blackNotes [black];
  55811. if (noteNum >= rangeStart && noteNum <= rangeEnd)
  55812. {
  55813. getKeyPos (noteNum, x, w);
  55814. if (orientation == horizontalKeyboard)
  55815. drawBlackNote (noteNum, g, x, 0, w, blackNoteLength,
  55816. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  55817. noteUnderMouse == noteNum,
  55818. blackNoteColour);
  55819. else if (orientation == verticalKeyboardFacingLeft)
  55820. drawBlackNote (noteNum, g, getWidth() - blackNoteLength, x, blackNoteLength, w,
  55821. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  55822. noteUnderMouse == noteNum,
  55823. blackNoteColour);
  55824. else if (orientation == verticalKeyboardFacingRight)
  55825. drawBlackNote (noteNum, g, 0, getHeight() - x - w, blackNoteLength, w,
  55826. state.isNoteOnForChannels (midiInChannelMask, noteNum),
  55827. noteUnderMouse == noteNum,
  55828. blackNoteColour);
  55829. }
  55830. }
  55831. }
  55832. }
  55833. void MidiKeyboardComponent::drawWhiteNote (int midiNoteNumber,
  55834. Graphics& g, int x, int y, int w, int h,
  55835. bool isDown, bool isOver,
  55836. const Colour& lineColour,
  55837. const Colour& textColour)
  55838. {
  55839. Colour c (Colours::transparentWhite);
  55840. if (isDown)
  55841. c = findColour (keyDownOverlayColourId);
  55842. if (isOver)
  55843. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  55844. g.setColour (c);
  55845. g.fillRect (x, y, w, h);
  55846. const String text (getWhiteNoteText (midiNoteNumber));
  55847. if (! text.isEmpty())
  55848. {
  55849. g.setColour (textColour);
  55850. Font f (jmin (12.0f, keyWidth * 0.9f));
  55851. f.setHorizontalScale (0.8f);
  55852. g.setFont (f);
  55853. Justification justification (Justification::centredBottom);
  55854. if (orientation == verticalKeyboardFacingLeft)
  55855. justification = Justification::centredLeft;
  55856. else if (orientation == verticalKeyboardFacingRight)
  55857. justification = Justification::centredRight;
  55858. g.drawFittedText (text, x + 2, y + 2, w - 4, h - 4, justification, 1);
  55859. }
  55860. g.setColour (lineColour);
  55861. if (orientation == horizontalKeyboard)
  55862. g.fillRect (x, y, 1, h);
  55863. else if (orientation == verticalKeyboardFacingLeft)
  55864. g.fillRect (x, y, w, 1);
  55865. else if (orientation == verticalKeyboardFacingRight)
  55866. g.fillRect (x, y + h - 1, w, 1);
  55867. if (midiNoteNumber == rangeEnd)
  55868. {
  55869. if (orientation == horizontalKeyboard)
  55870. g.fillRect (x + w, y, 1, h);
  55871. else if (orientation == verticalKeyboardFacingLeft)
  55872. g.fillRect (x, y + h, w, 1);
  55873. else if (orientation == verticalKeyboardFacingRight)
  55874. g.fillRect (x, y - 1, w, 1);
  55875. }
  55876. }
  55877. void MidiKeyboardComponent::drawBlackNote (int /*midiNoteNumber*/,
  55878. Graphics& g, int x, int y, int w, int h,
  55879. bool isDown, bool isOver,
  55880. const Colour& noteFillColour)
  55881. {
  55882. Colour c (noteFillColour);
  55883. if (isDown)
  55884. c = c.overlaidWith (findColour (keyDownOverlayColourId));
  55885. if (isOver)
  55886. c = c.overlaidWith (findColour (mouseOverKeyOverlayColourId));
  55887. g.setColour (c);
  55888. g.fillRect (x, y, w, h);
  55889. if (isDown)
  55890. {
  55891. g.setColour (noteFillColour);
  55892. g.drawRect (x, y, w, h);
  55893. }
  55894. else
  55895. {
  55896. const int xIndent = jmax (1, jmin (w, h) / 8);
  55897. g.setColour (c.brighter());
  55898. if (orientation == horizontalKeyboard)
  55899. g.fillRect (x + xIndent, y, w - xIndent * 2, 7 * h / 8);
  55900. else if (orientation == verticalKeyboardFacingLeft)
  55901. g.fillRect (x + w / 8, y + xIndent, w - w / 8, h - xIndent * 2);
  55902. else if (orientation == verticalKeyboardFacingRight)
  55903. g.fillRect (x, y + xIndent, 7 * w / 8, h - xIndent * 2);
  55904. }
  55905. }
  55906. void MidiKeyboardComponent::setOctaveForMiddleC (const int octaveNumForMiddleC_) throw()
  55907. {
  55908. octaveNumForMiddleC = octaveNumForMiddleC_;
  55909. repaint();
  55910. }
  55911. const String MidiKeyboardComponent::getWhiteNoteText (const int midiNoteNumber)
  55912. {
  55913. if (keyWidth > 14.0f && midiNoteNumber % 12 == 0)
  55914. return MidiMessage::getMidiNoteName (midiNoteNumber, true, true, octaveNumForMiddleC);
  55915. return String::empty;
  55916. }
  55917. void MidiKeyboardComponent::drawUpDownButton (Graphics& g, int w, int h,
  55918. const bool isMouseOver,
  55919. const bool isButtonDown,
  55920. const bool movesOctavesUp)
  55921. {
  55922. g.fillAll (findColour (upDownButtonBackgroundColourId));
  55923. float angle;
  55924. if (orientation == MidiKeyboardComponent::horizontalKeyboard)
  55925. angle = movesOctavesUp ? 0.0f : 0.5f;
  55926. else if (orientation == MidiKeyboardComponent::verticalKeyboardFacingLeft)
  55927. angle = movesOctavesUp ? 0.25f : 0.75f;
  55928. else
  55929. angle = movesOctavesUp ? 0.75f : 0.25f;
  55930. Path path;
  55931. path.lineTo (0.0f, 1.0f);
  55932. path.lineTo (1.0f, 0.5f);
  55933. path.closeSubPath();
  55934. path.applyTransform (AffineTransform::rotation (float_Pi * 2.0f * angle, 0.5f, 0.5f));
  55935. g.setColour (findColour (upDownButtonArrowColourId)
  55936. .withAlpha (isButtonDown ? 1.0f : (isMouseOver ? 0.6f : 0.4f)));
  55937. g.fillPath (path, path.getTransformToScaleToFit (1.0f, 1.0f,
  55938. w - 2.0f,
  55939. h - 2.0f,
  55940. true));
  55941. }
  55942. void MidiKeyboardComponent::resized()
  55943. {
  55944. int w = getWidth();
  55945. int h = getHeight();
  55946. if (w > 0 && h > 0)
  55947. {
  55948. if (orientation != horizontalKeyboard)
  55949. swapVariables (w, h);
  55950. blackNoteLength = roundFloatToInt (h * 0.7f);
  55951. int kx2, kw2;
  55952. getKeyPos (rangeEnd, kx2, kw2);
  55953. kx2 += kw2;
  55954. if (firstKey != rangeStart)
  55955. {
  55956. int kx1, kw1;
  55957. getKeyPos (rangeStart, kx1, kw1);
  55958. if (kx2 - kx1 <= w)
  55959. {
  55960. firstKey = rangeStart;
  55961. sendChangeMessage (this);
  55962. repaint();
  55963. }
  55964. }
  55965. const bool showScrollButtons = canScroll && (firstKey > rangeStart || kx2 > w + xOffset * 2);
  55966. scrollDown->setVisible (showScrollButtons);
  55967. scrollUp->setVisible (showScrollButtons);
  55968. xOffset = 0;
  55969. if (showScrollButtons)
  55970. {
  55971. const int scrollButtonW = jmin (12, w / 2);
  55972. if (orientation == horizontalKeyboard)
  55973. {
  55974. scrollDown->setBounds (0, 0, scrollButtonW, getHeight());
  55975. scrollUp->setBounds (getWidth() - scrollButtonW, 0, scrollButtonW, getHeight());
  55976. }
  55977. else if (orientation == verticalKeyboardFacingLeft)
  55978. {
  55979. scrollDown->setBounds (0, 0, getWidth(), scrollButtonW);
  55980. scrollUp->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  55981. }
  55982. else if (orientation == verticalKeyboardFacingRight)
  55983. {
  55984. scrollDown->setBounds (0, getHeight() - scrollButtonW, getWidth(), scrollButtonW);
  55985. scrollUp->setBounds (0, 0, getWidth(), scrollButtonW);
  55986. }
  55987. int endOfLastKey, kw;
  55988. getKeyPos (rangeEnd, endOfLastKey, kw);
  55989. endOfLastKey += kw;
  55990. const int spaceAvailable = w - scrollButtonW * 2;
  55991. const int lastStartKey = remappedXYToNote (endOfLastKey - spaceAvailable, 0) + 1;
  55992. if (lastStartKey >= 0 && firstKey > lastStartKey)
  55993. {
  55994. firstKey = jlimit (rangeStart, rangeEnd, lastStartKey);
  55995. sendChangeMessage (this);
  55996. }
  55997. int newOffset = 0;
  55998. getKeyPos (firstKey, newOffset, kw);
  55999. xOffset = newOffset - scrollButtonW;
  56000. }
  56001. else
  56002. {
  56003. firstKey = rangeStart;
  56004. }
  56005. timerCallback();
  56006. repaint();
  56007. }
  56008. }
  56009. void MidiKeyboardComponent::handleNoteOn (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/, float /*velocity*/)
  56010. {
  56011. triggerAsyncUpdate();
  56012. }
  56013. void MidiKeyboardComponent::handleNoteOff (MidiKeyboardState*, int /*midiChannel*/, int /*midiNoteNumber*/)
  56014. {
  56015. triggerAsyncUpdate();
  56016. }
  56017. void MidiKeyboardComponent::handleAsyncUpdate()
  56018. {
  56019. for (int i = rangeStart; i <= rangeEnd; ++i)
  56020. {
  56021. if (keysCurrentlyDrawnDown[i] != state.isNoteOnForChannels (midiInChannelMask, i))
  56022. {
  56023. keysCurrentlyDrawnDown.setBit (i, state.isNoteOnForChannels (midiInChannelMask, i));
  56024. repaintNote (i);
  56025. }
  56026. }
  56027. }
  56028. void MidiKeyboardComponent::resetAnyKeysInUse()
  56029. {
  56030. if (keysPressed.countNumberOfSetBits() > 0 || mouseDownNote > 0)
  56031. {
  56032. state.allNotesOff (midiChannel);
  56033. keysPressed.clear();
  56034. mouseDownNote = -1;
  56035. }
  56036. }
  56037. void MidiKeyboardComponent::updateNoteUnderMouse (int x, int y)
  56038. {
  56039. const int newNote = (mouseDragging || isMouseOver())
  56040. ? xyToNote (x, y) : -1;
  56041. if (noteUnderMouse != newNote)
  56042. {
  56043. if (mouseDownNote >= 0)
  56044. {
  56045. state.noteOff (midiChannel, mouseDownNote);
  56046. mouseDownNote = -1;
  56047. }
  56048. if (mouseDragging && newNote >= 0)
  56049. {
  56050. state.noteOn (midiChannel, newNote, velocity);
  56051. mouseDownNote = newNote;
  56052. }
  56053. repaintNote (noteUnderMouse);
  56054. noteUnderMouse = newNote;
  56055. repaintNote (noteUnderMouse);
  56056. }
  56057. else if (mouseDownNote >= 0 && ! mouseDragging)
  56058. {
  56059. state.noteOff (midiChannel, mouseDownNote);
  56060. mouseDownNote = -1;
  56061. }
  56062. }
  56063. void MidiKeyboardComponent::mouseMove (const MouseEvent& e)
  56064. {
  56065. updateNoteUnderMouse (e.x, e.y);
  56066. stopTimer();
  56067. }
  56068. void MidiKeyboardComponent::mouseDrag (const MouseEvent& e)
  56069. {
  56070. const int newNote = xyToNote (e.x, e.y);
  56071. if (newNote >= 0)
  56072. mouseDraggedToKey (newNote, e);
  56073. updateNoteUnderMouse (e.x, e.y);
  56074. }
  56075. bool MidiKeyboardComponent::mouseDownOnKey (int /*midiNoteNumber*/, const MouseEvent&)
  56076. {
  56077. return true;
  56078. }
  56079. void MidiKeyboardComponent::mouseDraggedToKey (int /*midiNoteNumber*/, const MouseEvent&)
  56080. {
  56081. }
  56082. void MidiKeyboardComponent::mouseDown (const MouseEvent& e)
  56083. {
  56084. const int newNote = xyToNote (e.x, e.y);
  56085. mouseDragging = false;
  56086. if (newNote >= 0 && mouseDownOnKey (newNote, e))
  56087. {
  56088. repaintNote (noteUnderMouse);
  56089. noteUnderMouse = -1;
  56090. mouseDragging = true;
  56091. updateNoteUnderMouse (e.x, e.y);
  56092. startTimer (500);
  56093. }
  56094. }
  56095. void MidiKeyboardComponent::mouseUp (const MouseEvent& e)
  56096. {
  56097. mouseDragging = false;
  56098. updateNoteUnderMouse (e.x, e.y);
  56099. stopTimer();
  56100. }
  56101. void MidiKeyboardComponent::mouseEnter (const MouseEvent& e)
  56102. {
  56103. updateNoteUnderMouse (e.x, e.y);
  56104. }
  56105. void MidiKeyboardComponent::mouseExit (const MouseEvent& e)
  56106. {
  56107. updateNoteUnderMouse (e.x, e.y);
  56108. }
  56109. void MidiKeyboardComponent::mouseWheelMove (const MouseEvent&, float ix, float iy)
  56110. {
  56111. setLowestVisibleKey (getLowestVisibleKey() + roundFloatToInt ((ix != 0 ? ix : iy) * 5.0f));
  56112. }
  56113. void MidiKeyboardComponent::timerCallback()
  56114. {
  56115. int mx, my;
  56116. getMouseXYRelative (mx, my);
  56117. updateNoteUnderMouse (mx, my);
  56118. }
  56119. void MidiKeyboardComponent::clearKeyMappings()
  56120. {
  56121. resetAnyKeysInUse();
  56122. keyPressNotes.clear();
  56123. keyPresses.clear();
  56124. }
  56125. void MidiKeyboardComponent::setKeyPressForNote (const KeyPress& key,
  56126. const int midiNoteOffsetFromC)
  56127. {
  56128. removeKeyPressForNote (midiNoteOffsetFromC);
  56129. keyPressNotes.add (midiNoteOffsetFromC);
  56130. keyPresses.add (key);
  56131. }
  56132. void MidiKeyboardComponent::removeKeyPressForNote (const int midiNoteOffsetFromC)
  56133. {
  56134. for (int i = keyPressNotes.size(); --i >= 0;)
  56135. {
  56136. if (keyPressNotes.getUnchecked (i) == midiNoteOffsetFromC)
  56137. {
  56138. keyPressNotes.remove (i);
  56139. keyPresses.remove (i);
  56140. }
  56141. }
  56142. }
  56143. void MidiKeyboardComponent::setKeyPressBaseOctave (const int newOctaveNumber)
  56144. {
  56145. jassert (newOctaveNumber >= 0 && newOctaveNumber <= 10);
  56146. keyMappingOctave = newOctaveNumber;
  56147. }
  56148. bool MidiKeyboardComponent::keyStateChanged()
  56149. {
  56150. bool keyPressUsed = false;
  56151. for (int i = keyPresses.size(); --i >= 0;)
  56152. {
  56153. const int note = 12 * keyMappingOctave + keyPressNotes.getUnchecked (i);
  56154. if (keyPresses.getReference(i).isCurrentlyDown())
  56155. {
  56156. if (! keysPressed [note])
  56157. {
  56158. keysPressed.setBit (note);
  56159. state.noteOn (midiChannel, note, velocity);
  56160. keyPressUsed = true;
  56161. }
  56162. }
  56163. else
  56164. {
  56165. if (keysPressed [note])
  56166. {
  56167. keysPressed.clearBit (note);
  56168. state.noteOff (midiChannel, note);
  56169. keyPressUsed = true;
  56170. }
  56171. }
  56172. }
  56173. return keyPressUsed;
  56174. }
  56175. void MidiKeyboardComponent::focusLost (FocusChangeType)
  56176. {
  56177. resetAnyKeysInUse();
  56178. }
  56179. END_JUCE_NAMESPACE
  56180. /********* End of inlined file: juce_MidiKeyboardComponent.cpp *********/
  56181. /********* Start of inlined file: juce_OpenGLComponent.cpp *********/
  56182. #if JUCE_OPENGL
  56183. BEGIN_JUCE_NAMESPACE
  56184. extern void juce_glViewport (const int w, const int h);
  56185. OpenGLPixelFormat::OpenGLPixelFormat (const int bitsPerRGBComponent,
  56186. const int alphaBits_,
  56187. const int depthBufferBits_,
  56188. const int stencilBufferBits_) throw()
  56189. : redBits (bitsPerRGBComponent),
  56190. greenBits (bitsPerRGBComponent),
  56191. blueBits (bitsPerRGBComponent),
  56192. alphaBits (alphaBits_),
  56193. depthBufferBits (depthBufferBits_),
  56194. stencilBufferBits (stencilBufferBits_),
  56195. accumulationBufferRedBits (0),
  56196. accumulationBufferGreenBits (0),
  56197. accumulationBufferBlueBits (0),
  56198. accumulationBufferAlphaBits (0),
  56199. fullSceneAntiAliasingNumSamples (0)
  56200. {
  56201. }
  56202. bool OpenGLPixelFormat::operator== (const OpenGLPixelFormat& other) const throw()
  56203. {
  56204. return memcmp (this, &other, sizeof (other)) == 0;
  56205. }
  56206. static VoidArray knownContexts;
  56207. OpenGLContext::OpenGLContext() throw()
  56208. {
  56209. knownContexts.add (this);
  56210. }
  56211. OpenGLContext::~OpenGLContext()
  56212. {
  56213. knownContexts.removeValue (this);
  56214. }
  56215. OpenGLContext* OpenGLContext::getCurrentContext()
  56216. {
  56217. for (int i = knownContexts.size(); --i >= 0;)
  56218. {
  56219. OpenGLContext* const oglc = (OpenGLContext*) knownContexts.getUnchecked(i);
  56220. if (oglc->isActive())
  56221. return oglc;
  56222. }
  56223. return 0;
  56224. }
  56225. class OpenGLComponentWatcher : public ComponentMovementWatcher
  56226. {
  56227. public:
  56228. OpenGLComponentWatcher (OpenGLComponent* const owner_)
  56229. : ComponentMovementWatcher (owner_),
  56230. owner (owner_),
  56231. wasShowing (false)
  56232. {
  56233. }
  56234. ~OpenGLComponentWatcher() {}
  56235. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  56236. {
  56237. owner->updateContextPosition();
  56238. }
  56239. void componentPeerChanged()
  56240. {
  56241. const ScopedLock sl (owner->getContextLock());
  56242. owner->deleteContext();
  56243. }
  56244. void componentVisibilityChanged (Component&)
  56245. {
  56246. const bool isShowingNow = owner->isShowing();
  56247. if (wasShowing != isShowingNow)
  56248. {
  56249. wasShowing = isShowingNow;
  56250. owner->updateContextPosition();
  56251. }
  56252. }
  56253. juce_UseDebuggingNewOperator
  56254. private:
  56255. OpenGLComponent* const owner;
  56256. bool wasShowing;
  56257. };
  56258. OpenGLComponent::OpenGLComponent()
  56259. : context (0),
  56260. contextToShareListsWith (0),
  56261. needToUpdateViewport (true)
  56262. {
  56263. setOpaque (true);
  56264. componentWatcher = new OpenGLComponentWatcher (this);
  56265. }
  56266. OpenGLComponent::~OpenGLComponent()
  56267. {
  56268. deleteContext();
  56269. delete componentWatcher;
  56270. }
  56271. void OpenGLComponent::deleteContext()
  56272. {
  56273. const ScopedLock sl (contextLock);
  56274. deleteAndZero (context);
  56275. }
  56276. void OpenGLComponent::updateContextPosition()
  56277. {
  56278. needToUpdateViewport = true;
  56279. if (getWidth() > 0 && getHeight() > 0)
  56280. {
  56281. Component* const topComp = getTopLevelComponent();
  56282. if (topComp->getPeer() != 0)
  56283. {
  56284. const ScopedLock sl (contextLock);
  56285. if (context != 0)
  56286. context->updateWindowPosition (getScreenX() - topComp->getScreenX(),
  56287. getScreenY() - topComp->getScreenY(),
  56288. getWidth(),
  56289. getHeight(),
  56290. topComp->getHeight());
  56291. }
  56292. }
  56293. }
  56294. const OpenGLPixelFormat OpenGLComponent::getPixelFormat() const
  56295. {
  56296. OpenGLPixelFormat pf;
  56297. const ScopedLock sl (contextLock);
  56298. if (context != 0)
  56299. pf = context->getPixelFormat();
  56300. return pf;
  56301. }
  56302. void OpenGLComponent::setPixelFormat (const OpenGLPixelFormat& formatToUse)
  56303. {
  56304. if (! (preferredPixelFormat == formatToUse))
  56305. {
  56306. const ScopedLock sl (contextLock);
  56307. deleteContext();
  56308. preferredPixelFormat = formatToUse;
  56309. }
  56310. }
  56311. void OpenGLComponent::shareWith (OpenGLContext* context)
  56312. {
  56313. if (contextToShareListsWith != context)
  56314. {
  56315. const ScopedLock sl (contextLock);
  56316. deleteContext();
  56317. contextToShareListsWith = context;
  56318. }
  56319. }
  56320. bool OpenGLComponent::makeCurrentContextActive()
  56321. {
  56322. if (context == 0)
  56323. {
  56324. const ScopedLock sl (contextLock);
  56325. if (isShowing() && getTopLevelComponent()->getPeer() != 0)
  56326. {
  56327. context = OpenGLContext::createContextForWindow (this,
  56328. preferredPixelFormat,
  56329. contextToShareListsWith);
  56330. if (context != 0)
  56331. {
  56332. updateContextPosition();
  56333. if (context->makeActive())
  56334. newOpenGLContextCreated();
  56335. }
  56336. }
  56337. }
  56338. return context != 0 && context->makeActive();
  56339. }
  56340. void OpenGLComponent::makeCurrentContextInactive()
  56341. {
  56342. if (context != 0)
  56343. context->makeInactive();
  56344. }
  56345. bool OpenGLComponent::isActiveContext() const throw()
  56346. {
  56347. return context != 0 && context->isActive();
  56348. }
  56349. void OpenGLComponent::swapBuffers()
  56350. {
  56351. if (context != 0)
  56352. context->swapBuffers();
  56353. }
  56354. void OpenGLComponent::paint (Graphics&)
  56355. {
  56356. if (renderAndSwapBuffers())
  56357. {
  56358. ComponentPeer* const peer = getPeer();
  56359. if (peer != 0)
  56360. {
  56361. peer->addMaskedRegion (getScreenX() - peer->getScreenX(),
  56362. getScreenY() - peer->getScreenY(),
  56363. getWidth(), getHeight());
  56364. }
  56365. }
  56366. }
  56367. bool OpenGLComponent::renderAndSwapBuffers()
  56368. {
  56369. const ScopedLock sl (contextLock);
  56370. if (! makeCurrentContextActive())
  56371. return false;
  56372. if (needToUpdateViewport)
  56373. {
  56374. needToUpdateViewport = false;
  56375. juce_glViewport (getWidth(), getHeight());
  56376. }
  56377. renderOpenGL();
  56378. swapBuffers();
  56379. return true;
  56380. }
  56381. void OpenGLComponent::internalRepaint (int x, int y, int w, int h)
  56382. {
  56383. Component::internalRepaint (x, y, w, h);
  56384. if (context != 0)
  56385. context->repaint();
  56386. }
  56387. END_JUCE_NAMESPACE
  56388. #endif
  56389. /********* End of inlined file: juce_OpenGLComponent.cpp *********/
  56390. /********* Start of inlined file: juce_PreferencesPanel.cpp *********/
  56391. BEGIN_JUCE_NAMESPACE
  56392. PreferencesPanel::PreferencesPanel()
  56393. : currentPage (0),
  56394. buttonSize (70)
  56395. {
  56396. }
  56397. PreferencesPanel::~PreferencesPanel()
  56398. {
  56399. deleteAllChildren();
  56400. }
  56401. void PreferencesPanel::addSettingsPage (const String& title,
  56402. const Drawable* icon,
  56403. const Drawable* overIcon,
  56404. const Drawable* downIcon)
  56405. {
  56406. DrawableButton* button = new DrawableButton (title, DrawableButton::ImageAboveTextLabel);
  56407. button->setImages (icon, overIcon, downIcon);
  56408. button->setRadioGroupId (1);
  56409. button->addButtonListener (this);
  56410. button->setClickingTogglesState (true);
  56411. button->setWantsKeyboardFocus (false);
  56412. addAndMakeVisible (button);
  56413. resized();
  56414. }
  56415. void PreferencesPanel::addSettingsPage (const String& title,
  56416. const char* imageData,
  56417. const int imageDataSize)
  56418. {
  56419. DrawableImage icon, iconOver, iconDown;
  56420. icon.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  56421. iconOver.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  56422. iconOver.setOverlayColour (Colours::black.withAlpha (0.12f));
  56423. iconDown.setImage (ImageCache::getFromMemory (imageData, imageDataSize), true);
  56424. iconDown.setOverlayColour (Colours::black.withAlpha (0.25f));
  56425. addSettingsPage (title, &icon, &iconOver, &iconDown);
  56426. if (currentPage == 0)
  56427. setCurrentPage (title);
  56428. }
  56429. class PrefsDialogWindow : public DialogWindow
  56430. {
  56431. public:
  56432. PrefsDialogWindow (const String& dialogtitle,
  56433. const Colour& backgroundColour)
  56434. : DialogWindow (dialogtitle, backgroundColour, true)
  56435. {
  56436. }
  56437. ~PrefsDialogWindow()
  56438. {
  56439. }
  56440. void closeButtonPressed()
  56441. {
  56442. exitModalState (0);
  56443. }
  56444. private:
  56445. PrefsDialogWindow (const PrefsDialogWindow&);
  56446. const PrefsDialogWindow& operator= (const PrefsDialogWindow&);
  56447. };
  56448. void PreferencesPanel::showInDialogBox (const String& dialogtitle,
  56449. int dialogWidth,
  56450. int dialogHeight,
  56451. const Colour& backgroundColour)
  56452. {
  56453. setSize (dialogWidth, dialogHeight);
  56454. PrefsDialogWindow dw (dialogtitle, backgroundColour);
  56455. dw.setContentComponent (this, true, true);
  56456. dw.centreAroundComponent (0, dw.getWidth(), dw.getHeight());
  56457. dw.runModalLoop();
  56458. }
  56459. void PreferencesPanel::resized()
  56460. {
  56461. int x = 0;
  56462. for (int i = 0; i < getNumChildComponents(); ++i)
  56463. {
  56464. Component* c = getChildComponent (i);
  56465. if (dynamic_cast <DrawableButton*> (c) == 0)
  56466. {
  56467. c->setBounds (0, buttonSize + 5, getWidth(), getHeight() - buttonSize - 5);
  56468. }
  56469. else
  56470. {
  56471. c->setBounds (x, 0, buttonSize, buttonSize);
  56472. x += buttonSize;
  56473. }
  56474. }
  56475. }
  56476. void PreferencesPanel::paint (Graphics& g)
  56477. {
  56478. g.setColour (Colours::grey);
  56479. g.fillRect (0, buttonSize + 2, getWidth(), 1);
  56480. }
  56481. void PreferencesPanel::setCurrentPage (const String& pageName)
  56482. {
  56483. if (currentPageName != pageName)
  56484. {
  56485. currentPageName = pageName;
  56486. deleteAndZero (currentPage);
  56487. currentPage = createComponentForPage (pageName);
  56488. if (currentPage != 0)
  56489. {
  56490. addAndMakeVisible (currentPage);
  56491. currentPage->toBack();
  56492. resized();
  56493. }
  56494. for (int i = 0; i < getNumChildComponents(); ++i)
  56495. {
  56496. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  56497. if (db != 0 && db->getName() == pageName)
  56498. {
  56499. db->setToggleState (true, false);
  56500. break;
  56501. }
  56502. }
  56503. }
  56504. }
  56505. void PreferencesPanel::buttonClicked (Button*)
  56506. {
  56507. for (int i = 0; i < getNumChildComponents(); ++i)
  56508. {
  56509. DrawableButton* db = dynamic_cast <DrawableButton*> (getChildComponent (i));
  56510. if (db != 0 && db->getToggleState())
  56511. {
  56512. setCurrentPage (db->getName());
  56513. break;
  56514. }
  56515. }
  56516. }
  56517. END_JUCE_NAMESPACE
  56518. /********* End of inlined file: juce_PreferencesPanel.cpp *********/
  56519. /********* Start of inlined file: juce_SystemTrayIconComponent.cpp *********/
  56520. #if JUCE_WIN32 || JUCE_LINUX
  56521. BEGIN_JUCE_NAMESPACE
  56522. SystemTrayIconComponent::SystemTrayIconComponent()
  56523. {
  56524. addToDesktop (0);
  56525. }
  56526. SystemTrayIconComponent::~SystemTrayIconComponent()
  56527. {
  56528. }
  56529. END_JUCE_NAMESPACE
  56530. #endif
  56531. /********* End of inlined file: juce_SystemTrayIconComponent.cpp *********/
  56532. /********* Start of inlined file: juce_AlertWindow.cpp *********/
  56533. BEGIN_JUCE_NAMESPACE
  56534. static const int titleH = 24;
  56535. static const int iconWidth = 80;
  56536. class AlertWindowTextEditor : public TextEditor
  56537. {
  56538. public:
  56539. #if JUCE_LINUX
  56540. #define PASSWORD_CHAR 0x2022
  56541. #else
  56542. #define PASSWORD_CHAR 0x25cf
  56543. #endif
  56544. AlertWindowTextEditor (const String& name,
  56545. const bool isPasswordBox)
  56546. : TextEditor (name,
  56547. isPasswordBox ? (const tchar) PASSWORD_CHAR
  56548. : (const tchar) 0)
  56549. {
  56550. setSelectAllWhenFocused (true);
  56551. }
  56552. ~AlertWindowTextEditor()
  56553. {
  56554. }
  56555. void returnPressed()
  56556. {
  56557. // pass these up the component hierarchy to be trigger the buttons
  56558. getParentComponent()->keyPressed (KeyPress (KeyPress::returnKey, 0, T('\n')));
  56559. }
  56560. void escapePressed()
  56561. {
  56562. // pass these up the component hierarchy to be trigger the buttons
  56563. getParentComponent()->keyPressed (KeyPress (KeyPress::escapeKey, 0, 0));
  56564. }
  56565. private:
  56566. AlertWindowTextEditor (const AlertWindowTextEditor&);
  56567. const AlertWindowTextEditor& operator= (const AlertWindowTextEditor&);
  56568. };
  56569. AlertWindow::AlertWindow (const String& title,
  56570. const String& message,
  56571. AlertIconType iconType)
  56572. : TopLevelWindow (title, true),
  56573. alertIconType (iconType)
  56574. {
  56575. if (message.isEmpty())
  56576. text = T(" "); // to force an update if the message is empty
  56577. setMessage (message);
  56578. #if JUCE_MAC
  56579. setAlwaysOnTop (true);
  56580. #else
  56581. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  56582. {
  56583. Component* const c = Desktop::getInstance().getComponent (i);
  56584. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  56585. {
  56586. setAlwaysOnTop (true);
  56587. break;
  56588. }
  56589. }
  56590. #endif
  56591. lookAndFeelChanged();
  56592. constrainer.setMinimumOnscreenAmounts (0x10000, 0x10000, 0x10000, 0x10000);
  56593. }
  56594. AlertWindow::~AlertWindow()
  56595. {
  56596. for (int i = customComps.size(); --i >= 0;)
  56597. removeChildComponent ((Component*) customComps[i]);
  56598. deleteAllChildren();
  56599. }
  56600. void AlertWindow::setMessage (const String& message)
  56601. {
  56602. const String newMessage (message.substring (0, 2048));
  56603. if (text != newMessage)
  56604. {
  56605. text = newMessage;
  56606. font.setHeight (15.0f);
  56607. Font titleFont (font.getHeight() * 1.1f, Font::bold);
  56608. textLayout.setText (getName() + T("\n\n"), titleFont);
  56609. textLayout.appendText (text, font);
  56610. updateLayout (true);
  56611. repaint();
  56612. }
  56613. }
  56614. void AlertWindow::buttonClicked (Button* button)
  56615. {
  56616. for (int i = 0; i < buttons.size(); i++)
  56617. {
  56618. TextButton* const c = (TextButton*) buttons[i];
  56619. if (button->getName() == c->getName())
  56620. {
  56621. if (c->getParentComponent() != 0)
  56622. c->getParentComponent()->exitModalState (c->getCommandID());
  56623. break;
  56624. }
  56625. }
  56626. }
  56627. void AlertWindow::addButton (const String& name,
  56628. const int returnValue,
  56629. const KeyPress& shortcutKey1,
  56630. const KeyPress& shortcutKey2)
  56631. {
  56632. TextButton* const b = new TextButton (name, String::empty);
  56633. b->setWantsKeyboardFocus (true);
  56634. b->setMouseClickGrabsKeyboardFocus (false);
  56635. b->setCommandToTrigger (0, returnValue, false);
  56636. b->addShortcut (shortcutKey1);
  56637. b->addShortcut (shortcutKey2);
  56638. b->addButtonListener (this);
  56639. b->changeWidthToFitText (getLookAndFeel().getAlertWindowButtonHeight());
  56640. addAndMakeVisible (b, 0);
  56641. buttons.add (b);
  56642. updateLayout (false);
  56643. }
  56644. int AlertWindow::getNumButtons() const
  56645. {
  56646. return buttons.size();
  56647. }
  56648. void AlertWindow::addTextEditor (const String& name,
  56649. const String& initialContents,
  56650. const String& onScreenLabel,
  56651. const bool isPasswordBox)
  56652. {
  56653. AlertWindowTextEditor* const tc = new AlertWindowTextEditor (name, isPasswordBox);
  56654. tc->setColour (TextEditor::outlineColourId, findColour (ComboBox::outlineColourId));
  56655. tc->setFont (font);
  56656. tc->setText (initialContents);
  56657. tc->setCaretPosition (initialContents.length());
  56658. addAndMakeVisible (tc);
  56659. textBoxes.add (tc);
  56660. allComps.add (tc);
  56661. textboxNames.add (onScreenLabel);
  56662. updateLayout (false);
  56663. }
  56664. const String AlertWindow::getTextEditorContents (const String& nameOfTextEditor) const
  56665. {
  56666. for (int i = textBoxes.size(); --i >= 0;)
  56667. if (((TextEditor*)textBoxes[i])->getName() == nameOfTextEditor)
  56668. return ((TextEditor*)textBoxes[i])->getText();
  56669. return String::empty;
  56670. }
  56671. void AlertWindow::addComboBox (const String& name,
  56672. const StringArray& items,
  56673. const String& onScreenLabel)
  56674. {
  56675. ComboBox* const cb = new ComboBox (name);
  56676. for (int i = 0; i < items.size(); ++i)
  56677. cb->addItem (items[i], i + 1);
  56678. addAndMakeVisible (cb);
  56679. cb->setSelectedItemIndex (0);
  56680. comboBoxes.add (cb);
  56681. allComps.add (cb);
  56682. comboBoxNames.add (onScreenLabel);
  56683. updateLayout (false);
  56684. }
  56685. ComboBox* AlertWindow::getComboBoxComponent (const String& nameOfList) const
  56686. {
  56687. for (int i = comboBoxes.size(); --i >= 0;)
  56688. if (((ComboBox*) comboBoxes[i])->getName() == nameOfList)
  56689. return (ComboBox*) comboBoxes[i];
  56690. return 0;
  56691. }
  56692. class AlertTextComp : public TextEditor
  56693. {
  56694. AlertTextComp (const AlertTextComp&);
  56695. const AlertTextComp& operator= (const AlertTextComp&);
  56696. int bestWidth;
  56697. public:
  56698. AlertTextComp (const String& message,
  56699. const Font& font)
  56700. {
  56701. setReadOnly (true);
  56702. setMultiLine (true, true);
  56703. setCaretVisible (false);
  56704. setScrollbarsShown (true);
  56705. lookAndFeelChanged();
  56706. setWantsKeyboardFocus (false);
  56707. setFont (font);
  56708. setText (message, false);
  56709. bestWidth = 2 * (int) sqrt (font.getHeight() * font.getStringWidth (message));
  56710. setColour (TextEditor::backgroundColourId, Colours::transparentBlack);
  56711. setColour (TextEditor::outlineColourId, Colours::transparentBlack);
  56712. setColour (TextEditor::shadowColourId, Colours::transparentBlack);
  56713. }
  56714. ~AlertTextComp()
  56715. {
  56716. }
  56717. int getPreferredWidth() const throw() { return bestWidth; }
  56718. void updateLayout (const int width)
  56719. {
  56720. TextLayout text;
  56721. text.appendText (getText(), getFont());
  56722. text.layout (width - 8, Justification::topLeft, true);
  56723. setSize (width, jmin (width, text.getHeight() + (int) getFont().getHeight()));
  56724. }
  56725. };
  56726. void AlertWindow::addTextBlock (const String& text)
  56727. {
  56728. AlertTextComp* const c = new AlertTextComp (text, font);
  56729. textBlocks.add (c);
  56730. allComps.add (c);
  56731. addAndMakeVisible (c);
  56732. updateLayout (false);
  56733. }
  56734. void AlertWindow::addProgressBarComponent (double& progressValue)
  56735. {
  56736. ProgressBar* const pb = new ProgressBar (progressValue);
  56737. progressBars.add (pb);
  56738. allComps.add (pb);
  56739. addAndMakeVisible (pb);
  56740. updateLayout (false);
  56741. }
  56742. void AlertWindow::addCustomComponent (Component* const component)
  56743. {
  56744. customComps.add (component);
  56745. allComps.add (component);
  56746. addAndMakeVisible (component);
  56747. updateLayout (false);
  56748. }
  56749. int AlertWindow::getNumCustomComponents() const
  56750. {
  56751. return customComps.size();
  56752. }
  56753. Component* AlertWindow::getCustomComponent (const int index) const
  56754. {
  56755. return (Component*) customComps [index];
  56756. }
  56757. Component* AlertWindow::removeCustomComponent (const int index)
  56758. {
  56759. Component* const c = getCustomComponent (index);
  56760. if (c != 0)
  56761. {
  56762. customComps.removeValue (c);
  56763. allComps.removeValue (c);
  56764. removeChildComponent (c);
  56765. updateLayout (false);
  56766. }
  56767. return c;
  56768. }
  56769. void AlertWindow::paint (Graphics& g)
  56770. {
  56771. getLookAndFeel().drawAlertBox (g, *this, textArea, textLayout);
  56772. g.setColour (findColour (textColourId));
  56773. g.setFont (getLookAndFeel().getAlertWindowFont());
  56774. int i;
  56775. for (i = textBoxes.size(); --i >= 0;)
  56776. {
  56777. if (textboxNames[i].isNotEmpty())
  56778. {
  56779. const TextEditor* const te = (TextEditor*) textBoxes[i];
  56780. g.drawFittedText (textboxNames[i],
  56781. te->getX(), te->getY() - 14,
  56782. te->getWidth(), 14,
  56783. Justification::centredLeft, 1);
  56784. }
  56785. }
  56786. for (i = comboBoxNames.size(); --i >= 0;)
  56787. {
  56788. if (comboBoxNames[i].isNotEmpty())
  56789. {
  56790. const ComboBox* const cb = (ComboBox*) comboBoxes[i];
  56791. g.drawFittedText (comboBoxNames[i],
  56792. cb->getX(), cb->getY() - 14,
  56793. cb->getWidth(), 14,
  56794. Justification::centredLeft, 1);
  56795. }
  56796. }
  56797. }
  56798. void AlertWindow::updateLayout (const bool onlyIncreaseSize)
  56799. {
  56800. const int wid = jmax (font.getStringWidth (text),
  56801. font.getStringWidth (getName()));
  56802. const int sw = (int) sqrt (font.getHeight() * wid);
  56803. int w = jmin (300 + sw * 2, (int) (getParentWidth() * 0.7f));
  56804. const int edgeGap = 10;
  56805. int iconSpace;
  56806. if (alertIconType == NoIcon)
  56807. {
  56808. textLayout.layout (w, Justification::horizontallyCentred, true);
  56809. iconSpace = 0;
  56810. }
  56811. else
  56812. {
  56813. textLayout.layout (w, Justification::left, true);
  56814. iconSpace = iconWidth;
  56815. }
  56816. w = jmax (350, textLayout.getWidth() + iconSpace + edgeGap * 4);
  56817. w = jmin (w, (int) (getParentWidth() * 0.7f));
  56818. const int textLayoutH = textLayout.getHeight();
  56819. const int textBottom = 16 + titleH + textLayoutH;
  56820. int h = textBottom;
  56821. int buttonW = 40;
  56822. int i;
  56823. for (i = 0; i < buttons.size(); ++i)
  56824. buttonW += 16 + ((const TextButton*) buttons[i])->getWidth();
  56825. w = jmax (buttonW, w);
  56826. h += (textBoxes.size() + comboBoxes.size() + progressBars.size()) * 50;
  56827. if (buttons.size() > 0)
  56828. h += 20 + ((TextButton*) buttons[0])->getHeight();
  56829. for (i = customComps.size(); --i >= 0;)
  56830. {
  56831. w = jmax (w, ((Component*) customComps[i])->getWidth() + 40);
  56832. h += 10 + ((Component*) customComps[i])->getHeight();
  56833. }
  56834. for (i = textBlocks.size(); --i >= 0;)
  56835. {
  56836. const AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  56837. w = jmax (w, ac->getPreferredWidth());
  56838. }
  56839. w = jmin (w, (int) (getParentWidth() * 0.7f));
  56840. for (i = textBlocks.size(); --i >= 0;)
  56841. {
  56842. AlertTextComp* const ac = (AlertTextComp*) textBlocks[i];
  56843. ac->updateLayout ((int) (w * 0.8f));
  56844. h += ac->getHeight() + 10;
  56845. }
  56846. h = jmin (getParentHeight() - 50, h);
  56847. if (onlyIncreaseSize)
  56848. {
  56849. w = jmax (w, getWidth());
  56850. h = jmax (h, getHeight());
  56851. }
  56852. if (! isVisible())
  56853. {
  56854. centreAroundComponent (0, w, h);
  56855. }
  56856. else
  56857. {
  56858. const int cx = getX() + getWidth() / 2;
  56859. const int cy = getY() + getHeight() / 2;
  56860. setBounds (cx - w / 2,
  56861. cy - h / 2,
  56862. w, h);
  56863. }
  56864. textArea.setBounds (edgeGap, edgeGap, w - (edgeGap * 2), h - edgeGap);
  56865. const int spacer = 16;
  56866. int totalWidth = -spacer;
  56867. for (i = buttons.size(); --i >= 0;)
  56868. totalWidth += ((TextButton*) buttons[i])->getWidth() + spacer;
  56869. int x = (w - totalWidth) / 2;
  56870. int y = (int) (getHeight() * 0.95f);
  56871. for (i = 0; i < buttons.size(); ++i)
  56872. {
  56873. TextButton* const c = (TextButton*) buttons[i];
  56874. int ny = proportionOfHeight (0.95f) - c->getHeight();
  56875. c->setTopLeftPosition (x, ny);
  56876. if (ny < y)
  56877. y = ny;
  56878. x += c->getWidth() + spacer;
  56879. c->toFront (false);
  56880. }
  56881. y = textBottom;
  56882. for (i = 0; i < allComps.size(); ++i)
  56883. {
  56884. Component* const c = (Component*) allComps[i];
  56885. const int h = 22;
  56886. const int comboIndex = comboBoxes.indexOf (c);
  56887. if (comboIndex >= 0 && comboBoxNames [comboIndex].isNotEmpty())
  56888. y += 18;
  56889. const int tbIndex = textBoxes.indexOf (c);
  56890. if (tbIndex >= 0 && textboxNames[tbIndex].isNotEmpty())
  56891. y += 18;
  56892. if (customComps.contains (c) || textBlocks.contains (c))
  56893. {
  56894. c->setTopLeftPosition ((getWidth() - c->getWidth()) / 2, y);
  56895. y += c->getHeight() + 10;
  56896. }
  56897. else
  56898. {
  56899. c->setBounds (proportionOfWidth (0.1f), y, proportionOfWidth (0.8f), h);
  56900. y += h + 10;
  56901. }
  56902. }
  56903. setWantsKeyboardFocus (getNumChildComponents() == 0);
  56904. }
  56905. bool AlertWindow::containsAnyExtraComponents() const
  56906. {
  56907. return textBoxes.size()
  56908. + comboBoxes.size()
  56909. + progressBars.size()
  56910. + customComps.size() > 0;
  56911. }
  56912. void AlertWindow::mouseDown (const MouseEvent&)
  56913. {
  56914. dragger.startDraggingComponent (this, &constrainer);
  56915. }
  56916. void AlertWindow::mouseDrag (const MouseEvent& e)
  56917. {
  56918. dragger.dragComponent (this, e);
  56919. }
  56920. bool AlertWindow::keyPressed (const KeyPress& key)
  56921. {
  56922. for (int i = buttons.size(); --i >= 0;)
  56923. {
  56924. TextButton* const b = (TextButton*) buttons[i];
  56925. if (b->isRegisteredForShortcut (key))
  56926. {
  56927. b->triggerClick();
  56928. return true;
  56929. }
  56930. }
  56931. if (key.isKeyCode (KeyPress::escapeKey) && buttons.size() == 0)
  56932. {
  56933. exitModalState (0);
  56934. return true;
  56935. }
  56936. else if (key.isKeyCode (KeyPress::returnKey) && buttons.size() == 1)
  56937. {
  56938. ((TextButton*) buttons.getFirst())->triggerClick();
  56939. return true;
  56940. }
  56941. return false;
  56942. }
  56943. void AlertWindow::lookAndFeelChanged()
  56944. {
  56945. const int flags = getLookAndFeel().getAlertBoxWindowFlags();
  56946. setUsingNativeTitleBar ((flags & ComponentPeer::windowHasTitleBar) != 0);
  56947. setDropShadowEnabled ((flags & ComponentPeer::windowHasDropShadow) != 0);
  56948. }
  56949. struct AlertWindowInfo
  56950. {
  56951. String title, message, button1, button2, button3;
  56952. AlertWindow::AlertIconType iconType;
  56953. int numButtons;
  56954. int run() const
  56955. {
  56956. return (int) (pointer_sized_int)
  56957. MessageManager::getInstance()->callFunctionOnMessageThread (showCallback, (void*) this);
  56958. }
  56959. private:
  56960. int show() const
  56961. {
  56962. AlertWindow aw (title, message, iconType);
  56963. if (numButtons == 1)
  56964. {
  56965. aw.addButton (button1, 0,
  56966. KeyPress (KeyPress::escapeKey, 0, 0),
  56967. KeyPress (KeyPress::returnKey, 0, 0));
  56968. }
  56969. else
  56970. {
  56971. const KeyPress button1ShortCut (CharacterFunctions::toLowerCase (button1[0]), 0, 0);
  56972. KeyPress button2ShortCut (CharacterFunctions::toLowerCase (button2[0]), 0, 0);
  56973. if (button1ShortCut == button2ShortCut)
  56974. button2ShortCut = KeyPress();
  56975. if (numButtons == 2)
  56976. {
  56977. aw.addButton (button1, 1, KeyPress (KeyPress::returnKey, 0, 0), button1ShortCut);
  56978. aw.addButton (button2, 0, KeyPress (KeyPress::escapeKey, 0, 0), button2ShortCut);
  56979. }
  56980. else
  56981. {
  56982. jassert (numButtons == 3);
  56983. aw.addButton (button1, 1, button1ShortCut);
  56984. aw.addButton (button2, 2, button2ShortCut);
  56985. aw.addButton (button3, 0, KeyPress (KeyPress::escapeKey, 0, 0));
  56986. }
  56987. }
  56988. return aw.runModalLoop();
  56989. }
  56990. static void* showCallback (void* userData)
  56991. {
  56992. return (void*) (pointer_sized_int) ((const AlertWindowInfo*) userData)->show();
  56993. }
  56994. };
  56995. void AlertWindow::showMessageBox (AlertIconType iconType,
  56996. const String& title,
  56997. const String& message,
  56998. const String& buttonText)
  56999. {
  57000. AlertWindowInfo info;
  57001. info.title = title;
  57002. info.message = message;
  57003. info.button1 = buttonText.isEmpty() ? TRANS("ok") : buttonText;
  57004. info.iconType = iconType;
  57005. info.numButtons = 1;
  57006. info.run();
  57007. }
  57008. bool AlertWindow::showOkCancelBox (AlertIconType iconType,
  57009. const String& title,
  57010. const String& message,
  57011. const String& button1Text,
  57012. const String& button2Text)
  57013. {
  57014. AlertWindowInfo info;
  57015. info.title = title;
  57016. info.message = message;
  57017. info.button1 = button1Text.isEmpty() ? TRANS("ok") : button1Text;
  57018. info.button2 = button2Text.isEmpty() ? TRANS("cancel") : button2Text;
  57019. info.iconType = iconType;
  57020. info.numButtons = 2;
  57021. return info.run() != 0;
  57022. }
  57023. int AlertWindow::showYesNoCancelBox (AlertIconType iconType,
  57024. const String& title,
  57025. const String& message,
  57026. const String& button1Text,
  57027. const String& button2Text,
  57028. const String& button3Text)
  57029. {
  57030. AlertWindowInfo info;
  57031. info.title = title;
  57032. info.message = message;
  57033. info.button1 = button1Text.isEmpty() ? TRANS("yes") : button1Text;
  57034. info.button2 = button2Text.isEmpty() ? TRANS("no") : button2Text;
  57035. info.button3 = button3Text.isEmpty() ? TRANS("cancel") : button3Text;
  57036. info.iconType = iconType;
  57037. info.numButtons = 3;
  57038. return info.run();
  57039. }
  57040. END_JUCE_NAMESPACE
  57041. /********* End of inlined file: juce_AlertWindow.cpp *********/
  57042. /********* Start of inlined file: juce_ComponentPeer.cpp *********/
  57043. BEGIN_JUCE_NAMESPACE
  57044. //#define JUCE_ENABLE_REPAINT_DEBUGGING 1
  57045. // these are over in juce_component.cpp
  57046. extern int64 juce_recentMouseDownTimes[4];
  57047. extern int juce_recentMouseDownX [4];
  57048. extern int juce_recentMouseDownY [4];
  57049. extern Component* juce_recentMouseDownComponent [4];
  57050. extern int juce_LastMousePosX;
  57051. extern int juce_LastMousePosY;
  57052. extern int juce_MouseClickCounter;
  57053. extern bool juce_MouseHasMovedSignificantlySincePressed;
  57054. static const int fakeMouseMoveMessage = 0x7fff00ff;
  57055. static VoidArray heavyweightPeers (4);
  57056. ComponentPeer::ComponentPeer (Component* const component_,
  57057. const int styleFlags_) throw()
  57058. : component (component_),
  57059. styleFlags (styleFlags_),
  57060. lastPaintTime (0),
  57061. constrainer (0),
  57062. lastFocusedComponent (0),
  57063. dragAndDropTargetComponent (0),
  57064. lastDragAndDropCompUnderMouse (0),
  57065. fakeMouseMessageSent (false),
  57066. isWindowMinimised (false)
  57067. {
  57068. heavyweightPeers.add (this);
  57069. }
  57070. ComponentPeer::~ComponentPeer()
  57071. {
  57072. heavyweightPeers.removeValue (this);
  57073. delete dragAndDropTargetComponent;
  57074. }
  57075. int ComponentPeer::getNumPeers() throw()
  57076. {
  57077. return heavyweightPeers.size();
  57078. }
  57079. ComponentPeer* ComponentPeer::getPeer (const int index) throw()
  57080. {
  57081. return (ComponentPeer*) heavyweightPeers [index];
  57082. }
  57083. ComponentPeer* ComponentPeer::getPeerFor (const Component* const component) throw()
  57084. {
  57085. for (int i = heavyweightPeers.size(); --i >= 0;)
  57086. {
  57087. ComponentPeer* const peer = (ComponentPeer*) heavyweightPeers.getUnchecked(i);
  57088. if (peer->getComponent() == component)
  57089. return peer;
  57090. }
  57091. return 0;
  57092. }
  57093. bool ComponentPeer::isValidPeer (const ComponentPeer* const peer) throw()
  57094. {
  57095. return heavyweightPeers.contains (const_cast <ComponentPeer*> (peer));
  57096. }
  57097. void ComponentPeer::updateCurrentModifiers() throw()
  57098. {
  57099. ModifierKeys::updateCurrentModifiers();
  57100. }
  57101. void ComponentPeer::handleMouseEnter (int x, int y, const int64 time)
  57102. {
  57103. jassert (component->isValidComponent());
  57104. updateCurrentModifiers();
  57105. Component* c = component->getComponentAt (x, y);
  57106. const ComponentDeletionWatcher deletionChecker (component);
  57107. if (c != Component::componentUnderMouse && Component::componentUnderMouse != 0)
  57108. {
  57109. jassert (Component::componentUnderMouse->isValidComponent());
  57110. const int oldX = x;
  57111. const int oldY = y;
  57112. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  57113. Component::componentUnderMouse->internalMouseExit (x, y, time);
  57114. Component::componentUnderMouse = 0;
  57115. if (deletionChecker.hasBeenDeleted())
  57116. return;
  57117. c = component->getComponentAt (oldX, oldY);
  57118. }
  57119. Component::componentUnderMouse = c;
  57120. if (Component::componentUnderMouse != 0)
  57121. {
  57122. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  57123. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  57124. }
  57125. }
  57126. void ComponentPeer::handleMouseMove (int x, int y, const int64 time)
  57127. {
  57128. jassert (component->isValidComponent());
  57129. updateCurrentModifiers();
  57130. fakeMouseMessageSent = false;
  57131. const ComponentDeletionWatcher deletionChecker (component);
  57132. Component* c = component->getComponentAt (x, y);
  57133. if (c != Component::componentUnderMouse)
  57134. {
  57135. const int oldX = x;
  57136. const int oldY = y;
  57137. if (Component::componentUnderMouse != 0)
  57138. {
  57139. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  57140. Component::componentUnderMouse->internalMouseExit (x, y, time);
  57141. x = oldX;
  57142. y = oldY;
  57143. Component::componentUnderMouse = 0;
  57144. if (deletionChecker.hasBeenDeleted())
  57145. return; // if this window has just been deleted..
  57146. c = component->getComponentAt (x, y);
  57147. }
  57148. Component::componentUnderMouse = c;
  57149. if (c != 0)
  57150. {
  57151. component->relativePositionToOtherComponent (c, x, y);
  57152. c->internalMouseEnter (x, y, time);
  57153. x = oldX;
  57154. y = oldY;
  57155. if (deletionChecker.hasBeenDeleted())
  57156. return; // if this window has just been deleted..
  57157. }
  57158. }
  57159. if (Component::componentUnderMouse != 0)
  57160. {
  57161. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  57162. Component::componentUnderMouse->internalMouseMove (x, y, time);
  57163. }
  57164. }
  57165. void ComponentPeer::handleMouseDown (int x, int y, const int64 time)
  57166. {
  57167. ++juce_MouseClickCounter;
  57168. updateCurrentModifiers();
  57169. int numMouseButtonsDown = 0;
  57170. if (ModifierKeys::getCurrentModifiers().isLeftButtonDown())
  57171. ++numMouseButtonsDown;
  57172. if (ModifierKeys::getCurrentModifiers().isRightButtonDown())
  57173. ++numMouseButtonsDown;
  57174. if (ModifierKeys::getCurrentModifiers().isMiddleButtonDown())
  57175. ++numMouseButtonsDown;
  57176. if (numMouseButtonsDown == 1)
  57177. {
  57178. Component::componentUnderMouse = component->getComponentAt (x, y);
  57179. if (Component::componentUnderMouse != 0)
  57180. {
  57181. // can't set these in the mouseDownInt() method, because it's re-entrant, so do it here..
  57182. for (int i = numElementsInArray (juce_recentMouseDownTimes); --i > 0;)
  57183. {
  57184. juce_recentMouseDownTimes [i] = juce_recentMouseDownTimes [i - 1];
  57185. juce_recentMouseDownX [i] = juce_recentMouseDownX [i - 1];
  57186. juce_recentMouseDownY [i] = juce_recentMouseDownY [i - 1];
  57187. juce_recentMouseDownComponent [i] = juce_recentMouseDownComponent [i - 1];
  57188. }
  57189. juce_recentMouseDownTimes[0] = time;
  57190. juce_recentMouseDownX[0] = x;
  57191. juce_recentMouseDownY[0] = y;
  57192. juce_recentMouseDownComponent[0] = Component::componentUnderMouse;
  57193. relativePositionToGlobal (juce_recentMouseDownX[0], juce_recentMouseDownY[0]);
  57194. juce_MouseHasMovedSignificantlySincePressed = false;
  57195. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  57196. Component::componentUnderMouse->internalMouseDown (x, y);
  57197. }
  57198. }
  57199. }
  57200. void ComponentPeer::handleMouseDrag (int x, int y, const int64 time)
  57201. {
  57202. updateCurrentModifiers();
  57203. if (Component::componentUnderMouse != 0)
  57204. {
  57205. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  57206. Component::componentUnderMouse->internalMouseDrag (x, y, time);
  57207. }
  57208. }
  57209. void ComponentPeer::handleMouseUp (const int oldModifiers, int x, int y, const int64 time)
  57210. {
  57211. updateCurrentModifiers();
  57212. int numMouseButtonsDown = 0;
  57213. if ((oldModifiers & ModifierKeys::leftButtonModifier) != 0)
  57214. ++numMouseButtonsDown;
  57215. if ((oldModifiers & ModifierKeys::rightButtonModifier) != 0)
  57216. ++numMouseButtonsDown;
  57217. if ((oldModifiers & ModifierKeys::middleButtonModifier) != 0)
  57218. ++numMouseButtonsDown;
  57219. if (numMouseButtonsDown == 1)
  57220. {
  57221. const ComponentDeletionWatcher deletionChecker (component);
  57222. Component* c = component->getComponentAt (x, y);
  57223. if (c != Component::componentUnderMouse)
  57224. {
  57225. const int oldX = x;
  57226. const int oldY = y;
  57227. if (Component::componentUnderMouse != 0)
  57228. {
  57229. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  57230. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  57231. x = oldX;
  57232. y = oldY;
  57233. if (Component::componentUnderMouse != 0)
  57234. Component::componentUnderMouse->internalMouseExit (x, y, time);
  57235. if (deletionChecker.hasBeenDeleted())
  57236. return;
  57237. c = component->getComponentAt (oldX, oldY);
  57238. }
  57239. Component::componentUnderMouse = c;
  57240. if (Component::componentUnderMouse != 0)
  57241. {
  57242. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  57243. Component::componentUnderMouse->internalMouseEnter (x, y, time);
  57244. }
  57245. }
  57246. else
  57247. {
  57248. if (Component::componentUnderMouse != 0)
  57249. {
  57250. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  57251. Component::componentUnderMouse->internalMouseUp (oldModifiers, x, y, time);
  57252. }
  57253. }
  57254. }
  57255. }
  57256. void ComponentPeer::handleMouseExit (int x, int y, const int64 time)
  57257. {
  57258. jassert (component->isValidComponent());
  57259. updateCurrentModifiers();
  57260. if (Component::componentUnderMouse != 0)
  57261. {
  57262. component->relativePositionToOtherComponent (Component::componentUnderMouse, x, y);
  57263. Component::componentUnderMouse->internalMouseExit (x, y, time);
  57264. Component::componentUnderMouse = 0;
  57265. }
  57266. }
  57267. void ComponentPeer::handleMouseWheel (const int amountX, const int amountY, const int64 time)
  57268. {
  57269. updateCurrentModifiers();
  57270. if (Component::componentUnderMouse != 0)
  57271. Component::componentUnderMouse->internalMouseWheel (amountX, amountY, time);
  57272. }
  57273. void ComponentPeer::sendFakeMouseMove() throw()
  57274. {
  57275. if ((! fakeMouseMessageSent)
  57276. && component->flags.hasHeavyweightPeerFlag
  57277. && ! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  57278. {
  57279. if (! isMinimised())
  57280. {
  57281. int realX, realY, realW, realH;
  57282. getBounds (realX, realY, realW, realH);
  57283. component->bounds_.setBounds (realX, realY, realW, realH);
  57284. }
  57285. int x, y;
  57286. component->getMouseXYRelative (x, y);
  57287. if (((unsigned int) x) < (unsigned int) component->getWidth()
  57288. && ((unsigned int) y) < (unsigned int) component->getHeight()
  57289. && contains (x, y, false))
  57290. {
  57291. postMessage (new Message (fakeMouseMoveMessage, x, y, 0));
  57292. }
  57293. fakeMouseMessageSent = true;
  57294. }
  57295. }
  57296. void ComponentPeer::handleMessage (const Message& message)
  57297. {
  57298. if (message.intParameter1 == fakeMouseMoveMessage)
  57299. {
  57300. if (! ModifierKeys::getCurrentModifiers().isAnyMouseButtonDown())
  57301. handleMouseMove (message.intParameter2,
  57302. message.intParameter3,
  57303. Time::currentTimeMillis());
  57304. }
  57305. }
  57306. void ComponentPeer::handlePaint (LowLevelGraphicsContext& contextToPaintTo)
  57307. {
  57308. Graphics g (&contextToPaintTo);
  57309. #if JUCE_ENABLE_REPAINT_DEBUGGING
  57310. g.saveState();
  57311. #endif
  57312. JUCE_TRY
  57313. {
  57314. component->paintEntireComponent (g);
  57315. }
  57316. JUCE_CATCH_EXCEPTION
  57317. #if JUCE_ENABLE_REPAINT_DEBUGGING
  57318. // enabling this code will fill all areas that get repainted with a colour overlay, to show
  57319. // clearly when things are being repainted.
  57320. {
  57321. g.restoreState();
  57322. g.fillAll (Colour ((uint8) Random::getSystemRandom().nextInt (255),
  57323. (uint8) Random::getSystemRandom().nextInt (255),
  57324. (uint8) Random::getSystemRandom().nextInt (255),
  57325. (uint8) 0x50));
  57326. }
  57327. #endif
  57328. }
  57329. bool ComponentPeer::handleKeyPress (const int keyCode,
  57330. const juce_wchar textCharacter)
  57331. {
  57332. updateCurrentModifiers();
  57333. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  57334. ? Component::currentlyFocusedComponent
  57335. : component;
  57336. if (target->isCurrentlyBlockedByAnotherModalComponent())
  57337. {
  57338. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  57339. if (currentModalComp != 0)
  57340. target = currentModalComp;
  57341. }
  57342. const KeyPress keyInfo (keyCode,
  57343. ModifierKeys::getCurrentModifiers().getRawFlags()
  57344. & ModifierKeys::allKeyboardModifiers,
  57345. textCharacter);
  57346. bool keyWasUsed = false;
  57347. while (target != 0)
  57348. {
  57349. const ComponentDeletionWatcher deletionChecker (target);
  57350. if (target->keyListeners_ != 0)
  57351. {
  57352. for (int i = target->keyListeners_->size(); --i >= 0;)
  57353. {
  57354. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyPressed (keyInfo, target);
  57355. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57356. return keyWasUsed;
  57357. i = jmin (i, target->keyListeners_->size());
  57358. }
  57359. }
  57360. keyWasUsed = target->keyPressed (keyInfo);
  57361. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57362. break;
  57363. if (keyInfo.isKeyCode (KeyPress::tabKey) && Component::getCurrentlyFocusedComponent() != 0)
  57364. {
  57365. Component::getCurrentlyFocusedComponent()
  57366. ->moveKeyboardFocusToSibling (! keyInfo.getModifiers().isShiftDown());
  57367. keyWasUsed = true;
  57368. break;
  57369. }
  57370. target = target->parentComponent_;
  57371. }
  57372. return keyWasUsed;
  57373. }
  57374. bool ComponentPeer::handleKeyUpOrDown()
  57375. {
  57376. updateCurrentModifiers();
  57377. Component* target = Component::currentlyFocusedComponent->isValidComponent()
  57378. ? Component::currentlyFocusedComponent
  57379. : component;
  57380. if (target->isCurrentlyBlockedByAnotherModalComponent())
  57381. {
  57382. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  57383. if (currentModalComp != 0)
  57384. target = currentModalComp;
  57385. }
  57386. bool keyWasUsed = false;
  57387. while (target != 0)
  57388. {
  57389. const ComponentDeletionWatcher deletionChecker (target);
  57390. keyWasUsed = target->keyStateChanged();
  57391. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57392. break;
  57393. if (target->keyListeners_ != 0)
  57394. {
  57395. for (int i = target->keyListeners_->size(); --i >= 0;)
  57396. {
  57397. keyWasUsed = ((KeyListener*) target->keyListeners_->getUnchecked(i))->keyStateChanged (target);
  57398. if (keyWasUsed || deletionChecker.hasBeenDeleted())
  57399. return keyWasUsed;
  57400. i = jmin (i, target->keyListeners_->size());
  57401. }
  57402. }
  57403. target = target->parentComponent_;
  57404. }
  57405. return keyWasUsed;
  57406. }
  57407. void ComponentPeer::handleModifierKeysChange()
  57408. {
  57409. updateCurrentModifiers();
  57410. Component* target = Component::getComponentUnderMouse();
  57411. if (target == 0)
  57412. target = Component::getCurrentlyFocusedComponent();
  57413. if (target == 0)
  57414. target = component;
  57415. if (target->isValidComponent())
  57416. target->internalModifierKeysChanged();
  57417. }
  57418. void ComponentPeer::handleBroughtToFront()
  57419. {
  57420. updateCurrentModifiers();
  57421. if (component != 0)
  57422. component->internalBroughtToFront();
  57423. }
  57424. void ComponentPeer::setConstrainer (ComponentBoundsConstrainer* const newConstrainer) throw()
  57425. {
  57426. constrainer = newConstrainer;
  57427. }
  57428. void ComponentPeer::handleMovedOrResized()
  57429. {
  57430. jassert (component->isValidComponent());
  57431. updateCurrentModifiers();
  57432. const bool nowMinimised = isMinimised();
  57433. if (component->flags.hasHeavyweightPeerFlag && ! nowMinimised)
  57434. {
  57435. const ComponentDeletionWatcher deletionChecker (component);
  57436. int realX, realY, realW, realH;
  57437. getBounds (realX, realY, realW, realH);
  57438. const bool wasMoved = (component->getX() != realX || component->getY() != realY);
  57439. const bool wasResized = (component->getWidth() != realW || component->getHeight() != realH);
  57440. if (wasMoved || wasResized)
  57441. {
  57442. component->bounds_.setBounds (realX, realY, realW, realH);
  57443. if (wasResized)
  57444. component->repaint();
  57445. component->sendMovedResizedMessages (wasMoved, wasResized);
  57446. if (deletionChecker.hasBeenDeleted())
  57447. return;
  57448. }
  57449. }
  57450. if (isWindowMinimised != nowMinimised)
  57451. {
  57452. isWindowMinimised = nowMinimised;
  57453. component->minimisationStateChanged (nowMinimised);
  57454. component->sendVisibilityChangeMessage();
  57455. }
  57456. if (! isFullScreen())
  57457. lastNonFullscreenBounds = component->getBounds();
  57458. }
  57459. void ComponentPeer::handleFocusGain()
  57460. {
  57461. updateCurrentModifiers();
  57462. if (component->isParentOf (lastFocusedComponent))
  57463. {
  57464. Component::currentlyFocusedComponent = lastFocusedComponent;
  57465. Desktop::getInstance().triggerFocusCallback();
  57466. lastFocusedComponent->internalFocusGain (Component::focusChangedDirectly);
  57467. }
  57468. else
  57469. {
  57470. if (! component->isCurrentlyBlockedByAnotherModalComponent())
  57471. {
  57472. component->grabKeyboardFocus();
  57473. }
  57474. else
  57475. {
  57476. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  57477. if (currentModalComp != 0)
  57478. currentModalComp->toFront (! currentModalComp->hasKeyboardFocus (true));
  57479. }
  57480. }
  57481. }
  57482. void ComponentPeer::handleFocusLoss()
  57483. {
  57484. updateCurrentModifiers();
  57485. if (component->hasKeyboardFocus (true))
  57486. {
  57487. lastFocusedComponent = Component::currentlyFocusedComponent;
  57488. if (lastFocusedComponent != 0)
  57489. {
  57490. Component::currentlyFocusedComponent = 0;
  57491. Desktop::getInstance().triggerFocusCallback();
  57492. lastFocusedComponent->internalFocusLoss (Component::focusChangedByMouseClick);
  57493. }
  57494. }
  57495. }
  57496. Component* ComponentPeer::getLastFocusedSubcomponent() const throw()
  57497. {
  57498. return (component->isParentOf (lastFocusedComponent) && lastFocusedComponent->isShowing())
  57499. ? lastFocusedComponent
  57500. : component;
  57501. }
  57502. void ComponentPeer::handleScreenSizeChange()
  57503. {
  57504. updateCurrentModifiers();
  57505. component->parentSizeChanged();
  57506. handleMovedOrResized();
  57507. }
  57508. void ComponentPeer::setNonFullScreenBounds (const Rectangle& newBounds) throw()
  57509. {
  57510. lastNonFullscreenBounds = newBounds;
  57511. }
  57512. const Rectangle& ComponentPeer::getNonFullScreenBounds() const throw()
  57513. {
  57514. return lastNonFullscreenBounds;
  57515. }
  57516. static FileDragAndDropTarget* findDragAndDropTarget (Component* c,
  57517. const StringArray& files,
  57518. FileDragAndDropTarget* const lastOne)
  57519. {
  57520. while (c != 0)
  57521. {
  57522. FileDragAndDropTarget* const t = dynamic_cast <FileDragAndDropTarget*> (c);
  57523. if (t != 0 && (t == lastOne || t->isInterestedInFileDrag (files)))
  57524. return t;
  57525. c = c->getParentComponent();
  57526. }
  57527. return 0;
  57528. }
  57529. void ComponentPeer::handleFileDragMove (const StringArray& files, int x, int y)
  57530. {
  57531. updateCurrentModifiers();
  57532. FileDragAndDropTarget* lastTarget = 0;
  57533. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  57534. lastTarget = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  57535. FileDragAndDropTarget* newTarget = 0;
  57536. Component* const compUnderMouse = component->getComponentAt (x, y);
  57537. if (compUnderMouse != lastDragAndDropCompUnderMouse)
  57538. {
  57539. lastDragAndDropCompUnderMouse = compUnderMouse;
  57540. newTarget = findDragAndDropTarget (compUnderMouse, files, lastTarget);
  57541. if (newTarget != lastTarget)
  57542. {
  57543. if (lastTarget != 0)
  57544. lastTarget->fileDragExit (files);
  57545. deleteAndZero (dragAndDropTargetComponent);
  57546. if (newTarget != 0)
  57547. {
  57548. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  57549. int mx = x, my = y;
  57550. component->relativePositionToOtherComponent (targetComp, mx, my);
  57551. dragAndDropTargetComponent = new ComponentDeletionWatcher (dynamic_cast <Component*> (newTarget));
  57552. newTarget->fileDragEnter (files, mx, my);
  57553. }
  57554. }
  57555. }
  57556. else
  57557. {
  57558. newTarget = lastTarget;
  57559. }
  57560. if (newTarget != 0)
  57561. {
  57562. Component* const targetComp = dynamic_cast <Component*> (newTarget);
  57563. component->relativePositionToOtherComponent (targetComp, x, y);
  57564. newTarget->fileDragMove (files, x, y);
  57565. }
  57566. }
  57567. void ComponentPeer::handleFileDragExit (const StringArray& files)
  57568. {
  57569. handleFileDragMove (files, -1, -1);
  57570. jassert (dragAndDropTargetComponent == 0);
  57571. lastDragAndDropCompUnderMouse = 0;
  57572. }
  57573. void ComponentPeer::handleFileDragDrop (const StringArray& files, int x, int y)
  57574. {
  57575. handleFileDragMove (files, x, y);
  57576. if (dragAndDropTargetComponent != 0 && ! dragAndDropTargetComponent->hasBeenDeleted())
  57577. {
  57578. FileDragAndDropTarget* const target = const_cast <FileDragAndDropTarget*> (dynamic_cast <const FileDragAndDropTarget*> (dragAndDropTargetComponent->getComponent()));
  57579. deleteAndZero (dragAndDropTargetComponent);
  57580. lastDragAndDropCompUnderMouse = 0;
  57581. if (target != 0)
  57582. {
  57583. Component* const targetComp = dynamic_cast <Component*> (target);
  57584. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  57585. {
  57586. targetComp->internalModalInputAttempt();
  57587. if (targetComp->isCurrentlyBlockedByAnotherModalComponent())
  57588. return;
  57589. }
  57590. component->relativePositionToOtherComponent (targetComp, x, y);
  57591. target->filesDropped (files, x, y);
  57592. }
  57593. }
  57594. }
  57595. void ComponentPeer::handleUserClosingWindow()
  57596. {
  57597. updateCurrentModifiers();
  57598. component->userTriedToCloseWindow();
  57599. }
  57600. void ComponentPeer::clearMaskedRegion() throw()
  57601. {
  57602. maskedRegion.clear();
  57603. }
  57604. void ComponentPeer::addMaskedRegion (int x, int y, int w, int h) throw()
  57605. {
  57606. maskedRegion.add (x, y, w, h);
  57607. }
  57608. END_JUCE_NAMESPACE
  57609. /********* End of inlined file: juce_ComponentPeer.cpp *********/
  57610. /********* Start of inlined file: juce_DialogWindow.cpp *********/
  57611. BEGIN_JUCE_NAMESPACE
  57612. DialogWindow::DialogWindow (const String& name,
  57613. const Colour& backgroundColour_,
  57614. const bool escapeKeyTriggersCloseButton_,
  57615. const bool addToDesktop_)
  57616. : DocumentWindow (name, backgroundColour_, DocumentWindow::closeButton, addToDesktop_),
  57617. escapeKeyTriggersCloseButton (escapeKeyTriggersCloseButton_)
  57618. {
  57619. }
  57620. DialogWindow::~DialogWindow()
  57621. {
  57622. }
  57623. void DialogWindow::resized()
  57624. {
  57625. DocumentWindow::resized();
  57626. const KeyPress esc (KeyPress::escapeKey, 0, 0);
  57627. if (escapeKeyTriggersCloseButton
  57628. && getCloseButton() != 0
  57629. && ! getCloseButton()->isRegisteredForShortcut (esc))
  57630. {
  57631. getCloseButton()->addShortcut (esc);
  57632. }
  57633. }
  57634. class TempDialogWindow : public DialogWindow
  57635. {
  57636. public:
  57637. TempDialogWindow (const String& title, const Colour& colour, const bool escapeCloses)
  57638. : DialogWindow (title, colour, escapeCloses, true)
  57639. {
  57640. }
  57641. ~TempDialogWindow()
  57642. {
  57643. }
  57644. void closeButtonPressed()
  57645. {
  57646. setVisible (false);
  57647. }
  57648. private:
  57649. TempDialogWindow (const TempDialogWindow&);
  57650. const TempDialogWindow& operator= (const TempDialogWindow&);
  57651. };
  57652. int DialogWindow::showModalDialog (const String& dialogTitle,
  57653. Component* contentComponent,
  57654. Component* componentToCentreAround,
  57655. const Colour& colour,
  57656. const bool escapeKeyTriggersCloseButton,
  57657. const bool shouldBeResizable,
  57658. const bool useBottomRightCornerResizer)
  57659. {
  57660. TempDialogWindow dw (dialogTitle, colour, escapeKeyTriggersCloseButton);
  57661. dw.setContentComponent (contentComponent, true, true);
  57662. dw.centreAroundComponent (componentToCentreAround, dw.getWidth(), dw.getHeight());
  57663. dw.setResizable (shouldBeResizable, useBottomRightCornerResizer);
  57664. const int result = dw.runModalLoop();
  57665. dw.setContentComponent (0, false);
  57666. return result;
  57667. }
  57668. END_JUCE_NAMESPACE
  57669. /********* End of inlined file: juce_DialogWindow.cpp *********/
  57670. /********* Start of inlined file: juce_DocumentWindow.cpp *********/
  57671. BEGIN_JUCE_NAMESPACE
  57672. DocumentWindow::DocumentWindow (const String& title,
  57673. const Colour& backgroundColour,
  57674. const int requiredButtons_,
  57675. const bool addToDesktop_)
  57676. : ResizableWindow (title, backgroundColour, addToDesktop_),
  57677. titleBarHeight (26),
  57678. menuBarHeight (24),
  57679. requiredButtons (requiredButtons_),
  57680. #if JUCE_MAC
  57681. positionTitleBarButtonsOnLeft (true),
  57682. #else
  57683. positionTitleBarButtonsOnLeft (false),
  57684. #endif
  57685. drawTitleTextCentred (true),
  57686. titleBarIcon (0),
  57687. menuBar (0),
  57688. menuBarModel (0)
  57689. {
  57690. zeromem (titleBarButtons, sizeof (titleBarButtons));
  57691. setResizeLimits (128, 128, 32768, 32768);
  57692. lookAndFeelChanged();
  57693. }
  57694. DocumentWindow::~DocumentWindow()
  57695. {
  57696. for (int i = 0; i < 3; ++i)
  57697. delete titleBarButtons[i];
  57698. delete titleBarIcon;
  57699. delete menuBar;
  57700. }
  57701. void DocumentWindow::repaintTitleBar()
  57702. {
  57703. const int border = getBorderSize();
  57704. repaint (border, border, getWidth() - border * 2, getTitleBarHeight());
  57705. }
  57706. void DocumentWindow::setName (const String& newName)
  57707. {
  57708. if (newName != getName())
  57709. {
  57710. Component::setName (newName);
  57711. repaintTitleBar();
  57712. }
  57713. }
  57714. void DocumentWindow::setIcon (const Image* imageToUse)
  57715. {
  57716. deleteAndZero (titleBarIcon);
  57717. if (imageToUse != 0)
  57718. titleBarIcon = imageToUse->createCopy();
  57719. repaintTitleBar();
  57720. }
  57721. void DocumentWindow::setTitleBarHeight (const int newHeight)
  57722. {
  57723. titleBarHeight = newHeight;
  57724. resized();
  57725. repaintTitleBar();
  57726. }
  57727. void DocumentWindow::setTitleBarButtonsRequired (const int requiredButtons_,
  57728. const bool positionTitleBarButtonsOnLeft_)
  57729. {
  57730. requiredButtons = requiredButtons_;
  57731. positionTitleBarButtonsOnLeft = positionTitleBarButtonsOnLeft_;
  57732. lookAndFeelChanged();
  57733. }
  57734. void DocumentWindow::setTitleBarTextCentred (const bool textShouldBeCentred)
  57735. {
  57736. drawTitleTextCentred = textShouldBeCentred;
  57737. repaintTitleBar();
  57738. }
  57739. void DocumentWindow::setMenuBar (MenuBarModel* menuBarModel_,
  57740. const int menuBarHeight_)
  57741. {
  57742. if (menuBarModel != menuBarModel_)
  57743. {
  57744. delete menuBar;
  57745. menuBar = 0;
  57746. menuBarModel = menuBarModel_;
  57747. menuBarHeight = (menuBarHeight_ > 0) ? menuBarHeight_
  57748. : getLookAndFeel().getDefaultMenuBarHeight();
  57749. if (menuBarModel != 0)
  57750. {
  57751. // (call the Component method directly to avoid the assertion in ResizableWindow)
  57752. Component::addAndMakeVisible (menuBar = new MenuBarComponent (menuBarModel));
  57753. menuBar->setEnabled (isActiveWindow());
  57754. }
  57755. resized();
  57756. }
  57757. }
  57758. void DocumentWindow::closeButtonPressed()
  57759. {
  57760. /* If you've got a close button, you have to override this method to get
  57761. rid of your window!
  57762. If the window is just a pop-up, you should override this method and make
  57763. it delete the window in whatever way is appropriate for your app. E.g. you
  57764. might just want to call "delete this".
  57765. If your app is centred around this window such that the whole app should quit when
  57766. the window is closed, then you will probably want to use this method as an opportunity
  57767. to call JUCEApplication::quit(), and leave the window to be deleted later by your
  57768. JUCEApplication::shutdown() method. (Doing it this way means that your window will
  57769. still get cleaned-up if the app is quit by some other means (e.g. a cmd-Q on the mac
  57770. or closing it via the taskbar icon on Windows).
  57771. */
  57772. jassertfalse
  57773. }
  57774. void DocumentWindow::minimiseButtonPressed()
  57775. {
  57776. setMinimised (true);
  57777. }
  57778. void DocumentWindow::maximiseButtonPressed()
  57779. {
  57780. setFullScreen (! isFullScreen());
  57781. }
  57782. void DocumentWindow::paint (Graphics& g)
  57783. {
  57784. ResizableWindow::paint (g);
  57785. if (resizableBorder == 0 && getBorderSize() == 1)
  57786. {
  57787. g.setColour (getBackgroundColour().overlaidWith (Colour (0x80000000)));
  57788. g.drawRect (0, 0, getWidth(), getHeight());
  57789. }
  57790. const int border = getBorderSize();
  57791. g.setOrigin (border, border);
  57792. g.reduceClipRegion (0, 0, getWidth() - border * 2, getTitleBarHeight());
  57793. int titleSpaceX1 = 6;
  57794. int titleSpaceX2 = getWidth() - 6;
  57795. for (int i = 0; i < 3; ++i)
  57796. {
  57797. if (titleBarButtons[i] != 0)
  57798. {
  57799. if (positionTitleBarButtonsOnLeft)
  57800. titleSpaceX1 = jmax (titleSpaceX1, titleBarButtons[i]->getRight() + (getWidth() - titleBarButtons[i]->getRight()) / 8);
  57801. else
  57802. titleSpaceX2 = jmin (titleSpaceX2, titleBarButtons[i]->getX() - (titleBarButtons[i]->getX() / 8));
  57803. }
  57804. }
  57805. getLookAndFeel()
  57806. .drawDocumentWindowTitleBar (*this, g,
  57807. getWidth() - border * 2,
  57808. getTitleBarHeight(),
  57809. titleSpaceX1, jmax (1, titleSpaceX2 - titleSpaceX1),
  57810. titleBarIcon, ! drawTitleTextCentred);
  57811. }
  57812. void DocumentWindow::resized()
  57813. {
  57814. ResizableWindow::resized();
  57815. if (titleBarButtons[1] != 0)
  57816. titleBarButtons[1]->setToggleState (isFullScreen(), false);
  57817. const int border = getBorderSize();
  57818. getLookAndFeel()
  57819. .positionDocumentWindowButtons (*this,
  57820. border, border,
  57821. getWidth() - border * 2, getTitleBarHeight(),
  57822. titleBarButtons[0],
  57823. titleBarButtons[1],
  57824. titleBarButtons[2],
  57825. positionTitleBarButtonsOnLeft);
  57826. if (menuBar != 0)
  57827. menuBar->setBounds (border, border + getTitleBarHeight(),
  57828. getWidth() - border * 2, menuBarHeight);
  57829. }
  57830. Button* DocumentWindow::getCloseButton() const throw()
  57831. {
  57832. return titleBarButtons[2];
  57833. }
  57834. Button* DocumentWindow::getMinimiseButton() const throw()
  57835. {
  57836. return titleBarButtons[0];
  57837. }
  57838. Button* DocumentWindow::getMaximiseButton() const throw()
  57839. {
  57840. return titleBarButtons[1];
  57841. }
  57842. int DocumentWindow::getDesktopWindowStyleFlags() const
  57843. {
  57844. int flags = ResizableWindow::getDesktopWindowStyleFlags();
  57845. if ((requiredButtons & minimiseButton) != 0)
  57846. flags |= ComponentPeer::windowHasMinimiseButton;
  57847. if ((requiredButtons & maximiseButton) != 0)
  57848. flags |= ComponentPeer::windowHasMaximiseButton;
  57849. if ((requiredButtons & closeButton) != 0)
  57850. flags |= ComponentPeer::windowHasCloseButton;
  57851. return flags;
  57852. }
  57853. void DocumentWindow::lookAndFeelChanged()
  57854. {
  57855. int i;
  57856. for (i = 0; i < 3; ++i)
  57857. deleteAndZero (titleBarButtons[i]);
  57858. if (! isUsingNativeTitleBar())
  57859. {
  57860. titleBarButtons[0] = ((requiredButtons & minimiseButton) != 0)
  57861. ? getLookAndFeel().createDocumentWindowButton (minimiseButton) : 0;
  57862. titleBarButtons[1] = ((requiredButtons & maximiseButton) != 0)
  57863. ? getLookAndFeel().createDocumentWindowButton (maximiseButton) : 0;
  57864. titleBarButtons[2] = ((requiredButtons & closeButton) != 0)
  57865. ? getLookAndFeel().createDocumentWindowButton (closeButton) : 0;
  57866. for (i = 0; i < 3; ++i)
  57867. {
  57868. if (titleBarButtons[i] != 0)
  57869. {
  57870. buttonListener.owner = this;
  57871. titleBarButtons[i]->addButtonListener (&buttonListener);
  57872. titleBarButtons[i]->setWantsKeyboardFocus (false);
  57873. // (call the Component method directly to avoid the assertion in ResizableWindow)
  57874. Component::addAndMakeVisible (titleBarButtons[i]);
  57875. }
  57876. }
  57877. if (getCloseButton() != 0)
  57878. {
  57879. #if JUCE_MAC
  57880. getCloseButton()->addShortcut (KeyPress (T('w'), ModifierKeys::commandModifier, 0));
  57881. #else
  57882. getCloseButton()->addShortcut (KeyPress (KeyPress::F4Key, ModifierKeys::altModifier, 0));
  57883. #endif
  57884. }
  57885. }
  57886. activeWindowStatusChanged();
  57887. ResizableWindow::lookAndFeelChanged();
  57888. }
  57889. void DocumentWindow::parentHierarchyChanged()
  57890. {
  57891. lookAndFeelChanged();
  57892. }
  57893. void DocumentWindow::activeWindowStatusChanged()
  57894. {
  57895. ResizableWindow::activeWindowStatusChanged();
  57896. for (int i = 0; i < 3; ++i)
  57897. if (titleBarButtons[i] != 0)
  57898. titleBarButtons[i]->setEnabled (isActiveWindow());
  57899. if (menuBar != 0)
  57900. menuBar->setEnabled (isActiveWindow());
  57901. }
  57902. const BorderSize DocumentWindow::getBorderThickness()
  57903. {
  57904. return BorderSize (getBorderSize());
  57905. }
  57906. const BorderSize DocumentWindow::getContentComponentBorder()
  57907. {
  57908. const int size = getBorderSize();
  57909. return BorderSize (size
  57910. + (isUsingNativeTitleBar() ? 0 : titleBarHeight)
  57911. + (menuBar != 0 ? menuBarHeight : 0),
  57912. size, size, size);
  57913. }
  57914. void DocumentWindow::mouseDoubleClick (const MouseEvent& e)
  57915. {
  57916. const int border = getBorderSize();
  57917. if (e.x >= border
  57918. && e.y >= border
  57919. && e.x < getWidth() - border
  57920. && e.y < border + getTitleBarHeight()
  57921. && getMaximiseButton() != 0)
  57922. {
  57923. getMaximiseButton()->triggerClick();
  57924. }
  57925. }
  57926. void DocumentWindow::userTriedToCloseWindow()
  57927. {
  57928. closeButtonPressed();
  57929. }
  57930. int DocumentWindow::getTitleBarHeight() const
  57931. {
  57932. return isUsingNativeTitleBar() ? 0 : jmin (titleBarHeight, getHeight() - 4);
  57933. }
  57934. int DocumentWindow::getBorderSize() const
  57935. {
  57936. return (isFullScreen() || isUsingNativeTitleBar()) ? 0 : (resizableBorder != 0 ? 4 : 1);
  57937. }
  57938. DocumentWindow::ButtonListenerProxy::ButtonListenerProxy()
  57939. {
  57940. }
  57941. void DocumentWindow::ButtonListenerProxy::buttonClicked (Button* button)
  57942. {
  57943. if (button == owner->getMinimiseButton())
  57944. {
  57945. owner->minimiseButtonPressed();
  57946. }
  57947. else if (button == owner->getMaximiseButton())
  57948. {
  57949. owner->maximiseButtonPressed();
  57950. }
  57951. else if (button == owner->getCloseButton())
  57952. {
  57953. owner->closeButtonPressed();
  57954. }
  57955. }
  57956. END_JUCE_NAMESPACE
  57957. /********* End of inlined file: juce_DocumentWindow.cpp *********/
  57958. /********* Start of inlined file: juce_ResizableWindow.cpp *********/
  57959. BEGIN_JUCE_NAMESPACE
  57960. ResizableWindow::ResizableWindow (const String& name,
  57961. const Colour& backgroundColour_,
  57962. const bool addToDesktop_)
  57963. : TopLevelWindow (name, addToDesktop_),
  57964. resizableCorner (0),
  57965. resizableBorder (0),
  57966. contentComponent (0),
  57967. resizeToFitContent (false),
  57968. fullscreen (false),
  57969. constrainer (0)
  57970. #ifdef JUCE_DEBUG
  57971. , hasBeenResized (false)
  57972. #endif
  57973. {
  57974. setBackgroundColour (backgroundColour_);
  57975. defaultConstrainer.setMinimumOnscreenAmounts (0x10000, 16, 24, 16);
  57976. lastNonFullScreenPos.setBounds (50, 50, 256, 256);
  57977. if (addToDesktop_)
  57978. Component::addToDesktop (getDesktopWindowStyleFlags());
  57979. }
  57980. ResizableWindow::~ResizableWindow()
  57981. {
  57982. deleteAndZero (resizableCorner);
  57983. deleteAndZero (resizableBorder);
  57984. deleteAndZero (contentComponent);
  57985. // have you been adding your own components directly to this window..? tut tut tut.
  57986. // Read the instructions for using a ResizableWindow!
  57987. jassert (getNumChildComponents() == 0);
  57988. }
  57989. int ResizableWindow::getDesktopWindowStyleFlags() const
  57990. {
  57991. int flags = TopLevelWindow::getDesktopWindowStyleFlags();
  57992. if (isResizable() && (flags & ComponentPeer::windowHasTitleBar) != 0)
  57993. flags |= ComponentPeer::windowIsResizable;
  57994. return flags;
  57995. }
  57996. void ResizableWindow::setContentComponent (Component* const newContentComponent,
  57997. const bool deleteOldOne,
  57998. const bool resizeToFit)
  57999. {
  58000. resizeToFitContent = resizeToFit;
  58001. if (contentComponent != newContentComponent)
  58002. {
  58003. if (deleteOldOne)
  58004. delete contentComponent;
  58005. else
  58006. removeChildComponent (contentComponent);
  58007. contentComponent = newContentComponent;
  58008. Component::addAndMakeVisible (contentComponent);
  58009. }
  58010. if (resizeToFit)
  58011. childBoundsChanged (contentComponent);
  58012. resized(); // must always be called to position the new content comp
  58013. }
  58014. void ResizableWindow::setContentComponentSize (int width, int height)
  58015. {
  58016. jassert (width > 0 && height > 0); // not a great idea to give it a zero size..
  58017. const BorderSize border (getContentComponentBorder());
  58018. setSize (width + border.getLeftAndRight(),
  58019. height + border.getTopAndBottom());
  58020. }
  58021. const BorderSize ResizableWindow::getBorderThickness()
  58022. {
  58023. return BorderSize (isUsingNativeTitleBar() ? 0 : ((resizableBorder != 0 && ! isFullScreen()) ? 5 : 3));
  58024. }
  58025. const BorderSize ResizableWindow::getContentComponentBorder()
  58026. {
  58027. return getBorderThickness();
  58028. }
  58029. void ResizableWindow::moved()
  58030. {
  58031. updateLastPos();
  58032. }
  58033. void ResizableWindow::visibilityChanged()
  58034. {
  58035. TopLevelWindow::visibilityChanged();
  58036. updateLastPos();
  58037. }
  58038. void ResizableWindow::resized()
  58039. {
  58040. if (resizableBorder != 0)
  58041. {
  58042. resizableBorder->setVisible (! isFullScreen());
  58043. resizableBorder->setBorderThickness (getBorderThickness());
  58044. resizableBorder->setSize (getWidth(), getHeight());
  58045. resizableBorder->toBack();
  58046. }
  58047. if (resizableCorner != 0)
  58048. {
  58049. resizableCorner->setVisible (! isFullScreen());
  58050. const int resizerSize = 18;
  58051. resizableCorner->setBounds (getWidth() - resizerSize,
  58052. getHeight() - resizerSize,
  58053. resizerSize, resizerSize);
  58054. }
  58055. if (contentComponent != 0)
  58056. contentComponent->setBoundsInset (getContentComponentBorder());
  58057. updateLastPos();
  58058. #ifdef JUCE_DEBUG
  58059. hasBeenResized = true;
  58060. #endif
  58061. }
  58062. void ResizableWindow::childBoundsChanged (Component* child)
  58063. {
  58064. if ((child == contentComponent) && (child != 0) && resizeToFitContent)
  58065. {
  58066. // not going to look very good if this component has a zero size..
  58067. jassert (child->getWidth() > 0);
  58068. jassert (child->getHeight() > 0);
  58069. const BorderSize borders (getContentComponentBorder());
  58070. setSize (child->getWidth() + borders.getLeftAndRight(),
  58071. child->getHeight() + borders.getTopAndBottom());
  58072. }
  58073. }
  58074. void ResizableWindow::activeWindowStatusChanged()
  58075. {
  58076. const BorderSize borders (getContentComponentBorder());
  58077. repaint (0, 0, getWidth(), borders.getTop());
  58078. repaint (0, borders.getTop(), borders.getLeft(), getHeight() - borders.getBottom() - borders.getTop());
  58079. repaint (0, getHeight() - borders.getBottom(), getWidth(), borders.getBottom());
  58080. repaint (getWidth() - borders.getRight(), borders.getTop(), borders.getRight(), getHeight() - borders.getBottom() - borders.getTop());
  58081. }
  58082. void ResizableWindow::setResizable (const bool shouldBeResizable,
  58083. const bool useBottomRightCornerResizer)
  58084. {
  58085. if (shouldBeResizable)
  58086. {
  58087. if (useBottomRightCornerResizer)
  58088. {
  58089. deleteAndZero (resizableBorder);
  58090. if (resizableCorner == 0)
  58091. {
  58092. Component::addChildComponent (resizableCorner = new ResizableCornerComponent (this, constrainer));
  58093. resizableCorner->setAlwaysOnTop (true);
  58094. }
  58095. }
  58096. else
  58097. {
  58098. deleteAndZero (resizableCorner);
  58099. if (resizableBorder == 0)
  58100. Component::addChildComponent (resizableBorder = new ResizableBorderComponent (this, constrainer));
  58101. }
  58102. }
  58103. else
  58104. {
  58105. deleteAndZero (resizableCorner);
  58106. deleteAndZero (resizableBorder);
  58107. }
  58108. if (isUsingNativeTitleBar())
  58109. recreateDesktopWindow();
  58110. childBoundsChanged (contentComponent);
  58111. resized();
  58112. }
  58113. bool ResizableWindow::isResizable() const throw()
  58114. {
  58115. return resizableCorner != 0
  58116. || resizableBorder != 0;
  58117. }
  58118. void ResizableWindow::setResizeLimits (const int newMinimumWidth,
  58119. const int newMinimumHeight,
  58120. const int newMaximumWidth,
  58121. const int newMaximumHeight) throw()
  58122. {
  58123. // if you've set up a custom constrainer then these settings won't have any effect..
  58124. jassert (constrainer == &defaultConstrainer || constrainer == 0);
  58125. if (constrainer == 0)
  58126. setConstrainer (&defaultConstrainer);
  58127. defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
  58128. newMaximumWidth, newMaximumHeight);
  58129. setBoundsConstrained (getX(), getY(), getWidth(), getHeight());
  58130. }
  58131. void ResizableWindow::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
  58132. {
  58133. if (constrainer != newConstrainer)
  58134. {
  58135. constrainer = newConstrainer;
  58136. const bool useBottomRightCornerResizer = resizableCorner != 0;
  58137. const bool shouldBeResizable = useBottomRightCornerResizer || resizableBorder != 0;
  58138. deleteAndZero (resizableCorner);
  58139. deleteAndZero (resizableBorder);
  58140. setResizable (shouldBeResizable, useBottomRightCornerResizer);
  58141. ComponentPeer* const peer = getPeer();
  58142. if (peer != 0)
  58143. peer->setConstrainer (newConstrainer);
  58144. }
  58145. }
  58146. void ResizableWindow::setBoundsConstrained (int x, int y, int w, int h)
  58147. {
  58148. if (constrainer != 0)
  58149. constrainer->setBoundsForComponent (this, x, y, w, h, false, false, false, false);
  58150. else
  58151. setBounds (x, y, w, h);
  58152. }
  58153. void ResizableWindow::paint (Graphics& g)
  58154. {
  58155. g.fillAll (backgroundColour);
  58156. if (! isFullScreen())
  58157. {
  58158. getLookAndFeel().drawResizableWindowBorder (g, getWidth(), getHeight(),
  58159. getBorderThickness(), *this);
  58160. }
  58161. #ifdef JUCE_DEBUG
  58162. /* If this fails, then you've probably written a subclass with a resized()
  58163. callback but forgotten to make it call its parent class's resized() method.
  58164. It's important when you override methods like resized(), moved(),
  58165. etc., that you make sure the base class methods also get called.
  58166. Of course you shouldn't really be overriding ResizableWindow::resized() anyway,
  58167. because your content should all be inside the content component - and it's the
  58168. content component's resized() method that you should be using to do your
  58169. layout.
  58170. */
  58171. jassert (hasBeenResized || (getWidth() == 0 && getHeight() == 0));
  58172. #endif
  58173. }
  58174. void ResizableWindow::lookAndFeelChanged()
  58175. {
  58176. resized();
  58177. if (isOnDesktop())
  58178. {
  58179. Component::addToDesktop (getDesktopWindowStyleFlags());
  58180. ComponentPeer* const peer = getPeer();
  58181. if (peer != 0)
  58182. peer->setConstrainer (constrainer);
  58183. }
  58184. }
  58185. void ResizableWindow::setBackgroundColour (const Colour& newColour)
  58186. {
  58187. if (Desktop::canUseSemiTransparentWindows())
  58188. backgroundColour = newColour;
  58189. else
  58190. backgroundColour = newColour.withAlpha (1.0f);
  58191. setOpaque (backgroundColour.isOpaque());
  58192. repaint();
  58193. }
  58194. bool ResizableWindow::isFullScreen() const
  58195. {
  58196. if (isOnDesktop())
  58197. {
  58198. ComponentPeer* const peer = getPeer();
  58199. return peer != 0 && peer->isFullScreen();
  58200. }
  58201. return fullscreen;
  58202. }
  58203. void ResizableWindow::setFullScreen (const bool shouldBeFullScreen)
  58204. {
  58205. if (shouldBeFullScreen != isFullScreen())
  58206. {
  58207. updateLastPos();
  58208. fullscreen = shouldBeFullScreen;
  58209. if (isOnDesktop())
  58210. {
  58211. ComponentPeer* const peer = getPeer();
  58212. if (peer != 0)
  58213. {
  58214. // keep a copy of this intact in case the real one gets messed-up while we're un-maximising
  58215. const Rectangle lastPos (lastNonFullScreenPos);
  58216. peer->setFullScreen (shouldBeFullScreen);
  58217. if (! shouldBeFullScreen)
  58218. setBounds (lastPos);
  58219. }
  58220. else
  58221. {
  58222. jassertfalse
  58223. }
  58224. }
  58225. else
  58226. {
  58227. if (shouldBeFullScreen)
  58228. setBounds (0, 0, getParentWidth(), getParentHeight());
  58229. else
  58230. setBounds (lastNonFullScreenPos);
  58231. }
  58232. resized();
  58233. }
  58234. }
  58235. bool ResizableWindow::isMinimised() const
  58236. {
  58237. ComponentPeer* const peer = getPeer();
  58238. return (peer != 0) && peer->isMinimised();
  58239. }
  58240. void ResizableWindow::setMinimised (const bool shouldMinimise)
  58241. {
  58242. if (shouldMinimise != isMinimised())
  58243. {
  58244. ComponentPeer* const peer = getPeer();
  58245. if (peer != 0)
  58246. {
  58247. updateLastPos();
  58248. peer->setMinimised (shouldMinimise);
  58249. }
  58250. else
  58251. {
  58252. jassertfalse
  58253. }
  58254. }
  58255. }
  58256. void ResizableWindow::updateLastPos()
  58257. {
  58258. if (isShowing() && ! (isFullScreen() || isMinimised()))
  58259. {
  58260. lastNonFullScreenPos = getBounds();
  58261. }
  58262. }
  58263. void ResizableWindow::parentSizeChanged()
  58264. {
  58265. if (isFullScreen() && getParentComponent() != 0)
  58266. {
  58267. setBounds (0, 0, getParentWidth(), getParentHeight());
  58268. }
  58269. }
  58270. const String ResizableWindow::getWindowStateAsString()
  58271. {
  58272. updateLastPos();
  58273. String s;
  58274. if (isFullScreen())
  58275. s << "fs ";
  58276. s << lastNonFullScreenPos.getX() << T(' ')
  58277. << lastNonFullScreenPos.getY() << T(' ')
  58278. << lastNonFullScreenPos.getWidth() << T(' ')
  58279. << lastNonFullScreenPos.getHeight();
  58280. return s;
  58281. }
  58282. bool ResizableWindow::restoreWindowStateFromString (const String& s)
  58283. {
  58284. StringArray tokens;
  58285. tokens.addTokens (s, false);
  58286. tokens.removeEmptyStrings();
  58287. tokens.trim();
  58288. const bool fs = tokens[0].startsWithIgnoreCase (T("fs"));
  58289. const int n = fs ? 1 : 0;
  58290. if (tokens.size() != 4 + n)
  58291. return false;
  58292. Rectangle r (tokens[n].getIntValue(),
  58293. tokens[n + 1].getIntValue(),
  58294. tokens[n + 2].getIntValue(),
  58295. tokens[n + 3].getIntValue());
  58296. if (r.isEmpty())
  58297. return false;
  58298. const Rectangle screen (Desktop::getInstance().getMonitorAreaContaining (r.getX(), r.getY()));
  58299. r = r.getIntersection (screen);
  58300. lastNonFullScreenPos = r;
  58301. if (isOnDesktop())
  58302. {
  58303. ComponentPeer* const peer = getPeer();
  58304. if (peer != 0)
  58305. peer->setNonFullScreenBounds (r);
  58306. }
  58307. setFullScreen (fs);
  58308. if (! fs)
  58309. setBoundsConstrained (r.getX(),
  58310. r.getY(),
  58311. r.getWidth(),
  58312. r.getHeight());
  58313. return true;
  58314. }
  58315. void ResizableWindow::mouseDown (const MouseEvent&)
  58316. {
  58317. if (! isFullScreen())
  58318. dragger.startDraggingComponent (this, constrainer);
  58319. }
  58320. void ResizableWindow::mouseDrag (const MouseEvent& e)
  58321. {
  58322. if (! isFullScreen())
  58323. dragger.dragComponent (this, e);
  58324. }
  58325. #ifdef JUCE_DEBUG
  58326. void ResizableWindow::addChildComponent (Component* const child, int zOrder)
  58327. {
  58328. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  58329. manages its child components automatically, and if you add your own it'll cause
  58330. trouble. Instead, use setContentComponent() to give it a component which
  58331. will be automatically resized and kept in the right place - then you can add
  58332. subcomponents to the content comp. See the notes for the ResizableWindow class
  58333. for more info.
  58334. If you really know what you're doing and want to avoid this assertion, just call
  58335. Component::addChildComponent directly.
  58336. */
  58337. jassertfalse
  58338. Component::addChildComponent (child, zOrder);
  58339. }
  58340. void ResizableWindow::addAndMakeVisible (Component* const child, int zOrder)
  58341. {
  58342. /* Agh! You shouldn't add components directly to a ResizableWindow - this class
  58343. manages its child components automatically, and if you add your own it'll cause
  58344. trouble. Instead, use setContentComponent() to give it a component which
  58345. will be automatically resized and kept in the right place - then you can add
  58346. subcomponents to the content comp. See the notes for the ResizableWindow class
  58347. for more info.
  58348. If you really know what you're doing and want to avoid this assertion, just call
  58349. Component::addAndMakeVisible directly.
  58350. */
  58351. jassertfalse
  58352. Component::addAndMakeVisible (child, zOrder);
  58353. }
  58354. #endif
  58355. END_JUCE_NAMESPACE
  58356. /********* End of inlined file: juce_ResizableWindow.cpp *********/
  58357. /********* Start of inlined file: juce_SplashScreen.cpp *********/
  58358. BEGIN_JUCE_NAMESPACE
  58359. SplashScreen::SplashScreen()
  58360. : backgroundImage (0),
  58361. isImageInCache (false)
  58362. {
  58363. setOpaque (true);
  58364. }
  58365. SplashScreen::~SplashScreen()
  58366. {
  58367. if (isImageInCache)
  58368. ImageCache::release (backgroundImage);
  58369. else
  58370. delete backgroundImage;
  58371. }
  58372. void SplashScreen::show (const String& title,
  58373. Image* const backgroundImage_,
  58374. const int minimumTimeToDisplayFor,
  58375. const bool useDropShadow,
  58376. const bool removeOnMouseClick)
  58377. {
  58378. backgroundImage = backgroundImage_;
  58379. jassert (backgroundImage_ != 0);
  58380. if (backgroundImage_ != 0)
  58381. {
  58382. isImageInCache = ImageCache::isImageInCache (backgroundImage_);
  58383. setOpaque (! backgroundImage_->hasAlphaChannel());
  58384. show (title,
  58385. backgroundImage_->getWidth(),
  58386. backgroundImage_->getHeight(),
  58387. minimumTimeToDisplayFor,
  58388. useDropShadow,
  58389. removeOnMouseClick);
  58390. }
  58391. }
  58392. void SplashScreen::show (const String& title,
  58393. const int width,
  58394. const int height,
  58395. const int minimumTimeToDisplayFor,
  58396. const bool useDropShadow,
  58397. const bool removeOnMouseClick)
  58398. {
  58399. setName (title);
  58400. setAlwaysOnTop (true);
  58401. setVisible (true);
  58402. centreWithSize (width, height);
  58403. addToDesktop (useDropShadow ? ComponentPeer::windowHasDropShadow : 0);
  58404. toFront (false);
  58405. MessageManager::getInstance()->runDispatchLoopUntil (300);
  58406. repaint();
  58407. originalClickCounter = removeOnMouseClick
  58408. ? Desktop::getMouseButtonClickCounter()
  58409. : INT_MAX;
  58410. earliestTimeToDelete = Time::getCurrentTime() + RelativeTime::milliseconds (minimumTimeToDisplayFor);
  58411. startTimer (50);
  58412. }
  58413. void SplashScreen::paint (Graphics& g)
  58414. {
  58415. if (backgroundImage != 0)
  58416. {
  58417. g.setOpacity (1.0f);
  58418. g.drawImage (backgroundImage,
  58419. 0, 0, getWidth(), getHeight(),
  58420. 0, 0, backgroundImage->getWidth(), backgroundImage->getHeight());
  58421. }
  58422. }
  58423. void SplashScreen::timerCallback()
  58424. {
  58425. if (Time::getCurrentTime() > earliestTimeToDelete
  58426. || Desktop::getMouseButtonClickCounter() > originalClickCounter)
  58427. {
  58428. delete this;
  58429. }
  58430. }
  58431. END_JUCE_NAMESPACE
  58432. /********* End of inlined file: juce_SplashScreen.cpp *********/
  58433. /********* Start of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  58434. BEGIN_JUCE_NAMESPACE
  58435. ThreadWithProgressWindow::ThreadWithProgressWindow (const String& title,
  58436. const bool hasProgressBar,
  58437. const bool hasCancelButton,
  58438. const int timeOutMsWhenCancelling_,
  58439. const String& cancelButtonText)
  58440. : Thread ("Juce Progress Window"),
  58441. progress (0.0),
  58442. alertWindow (title, String::empty, AlertWindow::NoIcon),
  58443. timeOutMsWhenCancelling (timeOutMsWhenCancelling_)
  58444. {
  58445. if (hasProgressBar)
  58446. alertWindow.addProgressBarComponent (progress);
  58447. if (hasCancelButton)
  58448. alertWindow.addButton (cancelButtonText, 1);
  58449. }
  58450. ThreadWithProgressWindow::~ThreadWithProgressWindow()
  58451. {
  58452. stopThread (timeOutMsWhenCancelling);
  58453. }
  58454. bool ThreadWithProgressWindow::runThread (const int priority)
  58455. {
  58456. startThread (priority);
  58457. startTimer (100);
  58458. {
  58459. const ScopedLock sl (messageLock);
  58460. alertWindow.setMessage (message);
  58461. }
  58462. const bool wasCancelled = alertWindow.runModalLoop() != 0;
  58463. stopThread (timeOutMsWhenCancelling);
  58464. alertWindow.setVisible (false);
  58465. return ! wasCancelled;
  58466. }
  58467. void ThreadWithProgressWindow::setProgress (const double newProgress)
  58468. {
  58469. progress = newProgress;
  58470. }
  58471. void ThreadWithProgressWindow::setStatusMessage (const String& newStatusMessage)
  58472. {
  58473. const ScopedLock sl (messageLock);
  58474. message = newStatusMessage;
  58475. }
  58476. void ThreadWithProgressWindow::timerCallback()
  58477. {
  58478. if (! isThreadRunning())
  58479. {
  58480. // thread has finished normally..
  58481. alertWindow.exitModalState (0);
  58482. alertWindow.setVisible (false);
  58483. }
  58484. else
  58485. {
  58486. const ScopedLock sl (messageLock);
  58487. alertWindow.setMessage (message);
  58488. }
  58489. }
  58490. END_JUCE_NAMESPACE
  58491. /********* End of inlined file: juce_ThreadWithProgressWindow.cpp *********/
  58492. /********* Start of inlined file: juce_TooltipWindow.cpp *********/
  58493. BEGIN_JUCE_NAMESPACE
  58494. TooltipWindow::TooltipWindow (Component* const parentComponent,
  58495. const int millisecondsBeforeTipAppears_)
  58496. : Component ("tooltip"),
  58497. millisecondsBeforeTipAppears (millisecondsBeforeTipAppears_),
  58498. mouseX (0),
  58499. mouseY (0),
  58500. lastMouseMoveTime (0),
  58501. lastHideTime (0),
  58502. lastComponentUnderMouse (0),
  58503. changedCompsSinceShown (true)
  58504. {
  58505. startTimer (123);
  58506. setAlwaysOnTop (true);
  58507. setOpaque (true);
  58508. if (parentComponent != 0)
  58509. parentComponent->addChildComponent (this);
  58510. }
  58511. TooltipWindow::~TooltipWindow()
  58512. {
  58513. hide();
  58514. }
  58515. void TooltipWindow::paint (Graphics& g)
  58516. {
  58517. getLookAndFeel().drawTooltip (g, tip, getWidth(), getHeight());
  58518. }
  58519. void TooltipWindow::mouseEnter (const MouseEvent&)
  58520. {
  58521. hide();
  58522. }
  58523. void TooltipWindow::showFor (Component* const c)
  58524. {
  58525. TooltipClient* const ttc = dynamic_cast <TooltipClient*> (c);
  58526. if (ttc != 0 && ! c->isCurrentlyBlockedByAnotherModalComponent())
  58527. tip = ttc->getTooltip();
  58528. else
  58529. tip = String::empty;
  58530. if (tip.isEmpty())
  58531. {
  58532. hide();
  58533. }
  58534. else
  58535. {
  58536. int mx, my;
  58537. Desktop::getMousePosition (mx, my);
  58538. if (getParentComponent() != 0)
  58539. getParentComponent()->globalPositionToRelative (mx, my);
  58540. int x, y, w, h;
  58541. getLookAndFeel().getTooltipSize (tip, w, h);
  58542. if (mx > getParentWidth() / 2)
  58543. x = mx - (w + 12);
  58544. else
  58545. x = mx + 24;
  58546. if (my > getParentHeight() / 2)
  58547. y = my - (h + 6);
  58548. else
  58549. y = my + 6;
  58550. setBounds (x, y, w, h);
  58551. setVisible (true);
  58552. if (getParentComponent() == 0)
  58553. {
  58554. addToDesktop (ComponentPeer::windowHasDropShadow
  58555. | ComponentPeer::windowIsTemporary);
  58556. }
  58557. toFront (false);
  58558. }
  58559. }
  58560. void TooltipWindow::hide()
  58561. {
  58562. removeFromDesktop();
  58563. setVisible (false);
  58564. }
  58565. void TooltipWindow::timerCallback()
  58566. {
  58567. int mx, my;
  58568. Desktop::getMousePosition (mx, my);
  58569. const unsigned int now = Time::getApproximateMillisecondCounter();
  58570. Component* const underMouse = Component::getComponentUnderMouse();
  58571. const bool changedComp = (underMouse != lastComponentUnderMouse);
  58572. lastComponentUnderMouse = underMouse;
  58573. if (changedComp
  58574. || abs (mx - mouseX) > 4
  58575. || abs (my - mouseY) > 4
  58576. || Desktop::getInstance().getMouseButtonClickCounter() > mouseClicks)
  58577. {
  58578. lastMouseMoveTime = now;
  58579. if (isVisible())
  58580. {
  58581. lastHideTime = now;
  58582. hide();
  58583. }
  58584. changedCompsSinceShown = changedCompsSinceShown || changedComp;
  58585. tip = String::empty;
  58586. mouseX = mx;
  58587. mouseY = my;
  58588. }
  58589. if (changedCompsSinceShown)
  58590. {
  58591. if ((now > lastMouseMoveTime + millisecondsBeforeTipAppears
  58592. || now < lastHideTime + 500)
  58593. && ! isVisible())
  58594. {
  58595. if (underMouse->isValidComponent())
  58596. showFor (underMouse);
  58597. changedCompsSinceShown = false;
  58598. }
  58599. }
  58600. mouseClicks = Desktop::getInstance().getMouseButtonClickCounter();
  58601. }
  58602. END_JUCE_NAMESPACE
  58603. /********* End of inlined file: juce_TooltipWindow.cpp *********/
  58604. /********* Start of inlined file: juce_TopLevelWindow.cpp *********/
  58605. BEGIN_JUCE_NAMESPACE
  58606. /** Keeps track of the active top level window.
  58607. */
  58608. class TopLevelWindowManager : public Timer,
  58609. public DeletedAtShutdown
  58610. {
  58611. public:
  58612. TopLevelWindowManager()
  58613. : windows (8),
  58614. currentActive (0)
  58615. {
  58616. }
  58617. ~TopLevelWindowManager()
  58618. {
  58619. clearSingletonInstance();
  58620. }
  58621. juce_DeclareSingleton_SingleThreaded_Minimal (TopLevelWindowManager)
  58622. void timerCallback()
  58623. {
  58624. startTimer (jmin (1731, getTimerInterval() * 2));
  58625. TopLevelWindow* active = 0;
  58626. if (Process::isForegroundProcess())
  58627. {
  58628. active = currentActive;
  58629. Component* const c = Component::getCurrentlyFocusedComponent();
  58630. TopLevelWindow* tlw = dynamic_cast <TopLevelWindow*> (c);
  58631. if (tlw == 0 && c != 0)
  58632. // (unable to use the syntax findParentComponentOfClass <TopLevelWindow> () because of a VC6 compiler bug)
  58633. tlw = c->findParentComponentOfClass ((TopLevelWindow*) 0);
  58634. if (tlw != 0)
  58635. active = tlw;
  58636. }
  58637. if (active != currentActive)
  58638. {
  58639. currentActive = active;
  58640. for (int i = windows.size(); --i >= 0;)
  58641. {
  58642. TopLevelWindow* const tlw = (TopLevelWindow*) windows.getUnchecked (i);
  58643. tlw->setWindowActive (isWindowActive (tlw));
  58644. i = jmin (i, windows.size() - 1);
  58645. }
  58646. Desktop::getInstance().triggerFocusCallback();
  58647. }
  58648. }
  58649. bool addWindow (TopLevelWindow* const w) throw()
  58650. {
  58651. windows.add (w);
  58652. startTimer (10);
  58653. return isWindowActive (w);
  58654. }
  58655. void removeWindow (TopLevelWindow* const w) throw()
  58656. {
  58657. startTimer (10);
  58658. if (currentActive == w)
  58659. currentActive = 0;
  58660. windows.removeValue (w);
  58661. if (windows.size() == 0)
  58662. deleteInstance();
  58663. }
  58664. VoidArray windows;
  58665. private:
  58666. TopLevelWindow* currentActive;
  58667. bool isWindowActive (TopLevelWindow* const tlw) const throw()
  58668. {
  58669. return (tlw == currentActive
  58670. || tlw->isParentOf (currentActive)
  58671. || tlw->hasKeyboardFocus (true))
  58672. && tlw->isShowing();
  58673. }
  58674. TopLevelWindowManager (const TopLevelWindowManager&);
  58675. const TopLevelWindowManager& operator= (const TopLevelWindowManager&);
  58676. };
  58677. juce_ImplementSingleton_SingleThreaded (TopLevelWindowManager)
  58678. void juce_CheckCurrentlyFocusedTopLevelWindow() throw()
  58679. {
  58680. if (TopLevelWindowManager::getInstanceWithoutCreating() != 0)
  58681. TopLevelWindowManager::getInstanceWithoutCreating()->startTimer (20);
  58682. }
  58683. TopLevelWindow::TopLevelWindow (const String& name,
  58684. const bool addToDesktop_)
  58685. : Component (name),
  58686. useDropShadow (true),
  58687. useNativeTitleBar (false),
  58688. windowIsActive_ (false),
  58689. shadower (0)
  58690. {
  58691. setOpaque (true);
  58692. if (addToDesktop_)
  58693. Component::addToDesktop (getDesktopWindowStyleFlags());
  58694. else
  58695. setDropShadowEnabled (true);
  58696. setWantsKeyboardFocus (true);
  58697. setBroughtToFrontOnMouseClick (true);
  58698. windowIsActive_ = TopLevelWindowManager::getInstance()->addWindow (this);
  58699. }
  58700. TopLevelWindow::~TopLevelWindow()
  58701. {
  58702. deleteAndZero (shadower);
  58703. TopLevelWindowManager::getInstance()->removeWindow (this);
  58704. }
  58705. void TopLevelWindow::focusOfChildComponentChanged (FocusChangeType)
  58706. {
  58707. if (hasKeyboardFocus (true))
  58708. TopLevelWindowManager::getInstance()->timerCallback();
  58709. else
  58710. TopLevelWindowManager::getInstance()->startTimer (10);
  58711. }
  58712. void TopLevelWindow::setWindowActive (const bool isNowActive) throw()
  58713. {
  58714. if (windowIsActive_ != isNowActive)
  58715. {
  58716. windowIsActive_ = isNowActive;
  58717. activeWindowStatusChanged();
  58718. }
  58719. }
  58720. void TopLevelWindow::activeWindowStatusChanged()
  58721. {
  58722. }
  58723. void TopLevelWindow::parentHierarchyChanged()
  58724. {
  58725. setDropShadowEnabled (useDropShadow);
  58726. }
  58727. void TopLevelWindow::visibilityChanged()
  58728. {
  58729. if (isShowing())
  58730. toFront (true);
  58731. }
  58732. int TopLevelWindow::getDesktopWindowStyleFlags() const
  58733. {
  58734. int flags = ComponentPeer::windowAppearsOnTaskbar;
  58735. if (useDropShadow)
  58736. flags |= ComponentPeer::windowHasDropShadow;
  58737. if (useNativeTitleBar)
  58738. flags |= ComponentPeer::windowHasTitleBar;
  58739. return flags;
  58740. }
  58741. void TopLevelWindow::setDropShadowEnabled (const bool useShadow)
  58742. {
  58743. useDropShadow = useShadow;
  58744. if (isOnDesktop())
  58745. {
  58746. deleteAndZero (shadower);
  58747. Component::addToDesktop (getDesktopWindowStyleFlags());
  58748. }
  58749. else
  58750. {
  58751. if (useShadow && isOpaque())
  58752. {
  58753. if (shadower == 0)
  58754. {
  58755. shadower = getLookAndFeel().createDropShadowerForComponent (this);
  58756. if (shadower != 0)
  58757. shadower->setOwner (this);
  58758. }
  58759. }
  58760. else
  58761. {
  58762. deleteAndZero (shadower);
  58763. }
  58764. }
  58765. }
  58766. void TopLevelWindow::setUsingNativeTitleBar (const bool useNativeTitleBar_)
  58767. {
  58768. if (useNativeTitleBar != useNativeTitleBar_)
  58769. {
  58770. useNativeTitleBar = useNativeTitleBar_;
  58771. recreateDesktopWindow();
  58772. sendLookAndFeelChange();
  58773. }
  58774. }
  58775. void TopLevelWindow::recreateDesktopWindow()
  58776. {
  58777. if (isOnDesktop())
  58778. {
  58779. Component::addToDesktop (getDesktopWindowStyleFlags());
  58780. toFront (true);
  58781. }
  58782. }
  58783. void TopLevelWindow::addToDesktop (int windowStyleFlags, void* nativeWindowToAttachTo)
  58784. {
  58785. /* It's not recommended to change the desktop window flags directly for a TopLevelWindow,
  58786. because this class needs to make sure its layout corresponds with settings like whether
  58787. it's got a native title bar or not.
  58788. If you need custom flags for your window, you can override the getDesktopWindowStyleFlags()
  58789. method. If you do this, it's best to call the base class's getDesktopWindowStyleFlags()
  58790. method, then add or remove whatever flags are necessary from this value before returning it.
  58791. */
  58792. jassert ((windowStyleFlags & ~ComponentPeer::windowIsSemiTransparent)
  58793. == (getDesktopWindowStyleFlags() & ~ComponentPeer::windowIsSemiTransparent));
  58794. Component::addToDesktop (windowStyleFlags, nativeWindowToAttachTo);
  58795. if (windowStyleFlags != getDesktopWindowStyleFlags())
  58796. sendLookAndFeelChange();
  58797. }
  58798. void TopLevelWindow::centreAroundComponent (Component* c, const int width, const int height)
  58799. {
  58800. if (c == 0)
  58801. c = TopLevelWindow::getActiveTopLevelWindow();
  58802. if (c == 0)
  58803. {
  58804. centreWithSize (width, height);
  58805. }
  58806. else
  58807. {
  58808. int x = (c->getWidth() - width) / 2;
  58809. int y = (c->getHeight() - height) / 2;
  58810. c->relativePositionToGlobal (x, y);
  58811. Rectangle parentArea (c->getParentMonitorArea());
  58812. if (getParentComponent() != 0)
  58813. {
  58814. getParentComponent()->globalPositionToRelative (x, y);
  58815. parentArea.setBounds (0, 0, getParentWidth(), getParentHeight());
  58816. }
  58817. parentArea.reduce (12, 12);
  58818. setBounds (jlimit (parentArea.getX(), jmax (parentArea.getX(), parentArea.getRight() - width), x),
  58819. jlimit (parentArea.getY(), jmax (parentArea.getY(), parentArea.getBottom() - height), y),
  58820. width, height);
  58821. }
  58822. }
  58823. int TopLevelWindow::getNumTopLevelWindows() throw()
  58824. {
  58825. return TopLevelWindowManager::getInstance()->windows.size();
  58826. }
  58827. TopLevelWindow* TopLevelWindow::getTopLevelWindow (const int index) throw()
  58828. {
  58829. return (TopLevelWindow*) TopLevelWindowManager::getInstance()->windows [index];
  58830. }
  58831. TopLevelWindow* TopLevelWindow::getActiveTopLevelWindow() throw()
  58832. {
  58833. TopLevelWindow* best = 0;
  58834. int bestNumTWLParents = -1;
  58835. for (int i = TopLevelWindow::getNumTopLevelWindows(); --i >= 0;)
  58836. {
  58837. TopLevelWindow* const tlw = TopLevelWindow::getTopLevelWindow (i);
  58838. if (tlw->isActiveWindow())
  58839. {
  58840. int numTWLParents = 0;
  58841. const Component* c = tlw->getParentComponent();
  58842. while (c != 0)
  58843. {
  58844. if (dynamic_cast <const TopLevelWindow*> (c) != 0)
  58845. ++numTWLParents;
  58846. c = c->getParentComponent();
  58847. }
  58848. if (bestNumTWLParents < numTWLParents)
  58849. {
  58850. best = tlw;
  58851. bestNumTWLParents = numTWLParents;
  58852. }
  58853. }
  58854. }
  58855. return best;
  58856. }
  58857. END_JUCE_NAMESPACE
  58858. /********* End of inlined file: juce_TopLevelWindow.cpp *********/
  58859. /********* Start of inlined file: juce_Brush.cpp *********/
  58860. BEGIN_JUCE_NAMESPACE
  58861. Brush::Brush() throw()
  58862. {
  58863. }
  58864. Brush::~Brush() throw()
  58865. {
  58866. }
  58867. void Brush::paintVerticalLine (LowLevelGraphicsContext& context,
  58868. int x, float y1, float y2) throw()
  58869. {
  58870. Path p;
  58871. p.addRectangle ((float) x, y1, 1.0f, y2 - y1);
  58872. paintPath (context, p, AffineTransform::identity);
  58873. }
  58874. void Brush::paintHorizontalLine (LowLevelGraphicsContext& context,
  58875. int y, float x1, float x2) throw()
  58876. {
  58877. Path p;
  58878. p.addRectangle (x1, (float) y, x2 - x1, 1.0f);
  58879. paintPath (context, p, AffineTransform::identity);
  58880. }
  58881. void Brush::paintLine (LowLevelGraphicsContext& context,
  58882. float x1, float y1, float x2, float y2) throw()
  58883. {
  58884. Path p;
  58885. p.addLineSegment (x1, y1, x2, y2, 1.0f);
  58886. paintPath (context, p, AffineTransform::identity);
  58887. }
  58888. END_JUCE_NAMESPACE
  58889. /********* End of inlined file: juce_Brush.cpp *********/
  58890. /********* Start of inlined file: juce_GradientBrush.cpp *********/
  58891. BEGIN_JUCE_NAMESPACE
  58892. GradientBrush::GradientBrush (const Colour& colour1,
  58893. const float x1,
  58894. const float y1,
  58895. const Colour& colour2,
  58896. const float x2,
  58897. const float y2,
  58898. const bool isRadial) throw()
  58899. : gradient (colour1, x1, y1,
  58900. colour2, x2, y2,
  58901. isRadial)
  58902. {
  58903. }
  58904. GradientBrush::GradientBrush (const ColourGradient& gradient_) throw()
  58905. : gradient (gradient_)
  58906. {
  58907. }
  58908. GradientBrush::~GradientBrush() throw()
  58909. {
  58910. }
  58911. Brush* GradientBrush::createCopy() const throw()
  58912. {
  58913. return new GradientBrush (gradient);
  58914. }
  58915. void GradientBrush::applyTransform (const AffineTransform& transform) throw()
  58916. {
  58917. gradient.transform = gradient.transform.followedBy (transform);
  58918. }
  58919. void GradientBrush::multiplyOpacity (const float multiple) throw()
  58920. {
  58921. gradient.multiplyOpacity (multiple);
  58922. }
  58923. bool GradientBrush::isInvisible() const throw()
  58924. {
  58925. return gradient.isInvisible();
  58926. }
  58927. void GradientBrush::paintPath (LowLevelGraphicsContext& context,
  58928. const Path& path, const AffineTransform& transform) throw()
  58929. {
  58930. context.fillPathWithGradient (path, transform, gradient, EdgeTable::Oversampling_4times);
  58931. }
  58932. void GradientBrush::paintRectangle (LowLevelGraphicsContext& context,
  58933. int x, int y, int w, int h) throw()
  58934. {
  58935. context.fillRectWithGradient (x, y, w, h, gradient);
  58936. }
  58937. void GradientBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  58938. const Image& alphaChannelImage, int imageX, int imageY,
  58939. int x, int y, int w, int h) throw()
  58940. {
  58941. context.saveState();
  58942. if (context.reduceClipRegion (x, y, w, h))
  58943. context.fillAlphaChannelWithGradient (alphaChannelImage, imageX, imageY, gradient);
  58944. context.restoreState();
  58945. }
  58946. END_JUCE_NAMESPACE
  58947. /********* End of inlined file: juce_GradientBrush.cpp *********/
  58948. /********* Start of inlined file: juce_ImageBrush.cpp *********/
  58949. BEGIN_JUCE_NAMESPACE
  58950. ImageBrush::ImageBrush (Image* const image_,
  58951. const int anchorX_,
  58952. const int anchorY_,
  58953. const float opacity_) throw()
  58954. : image (image_),
  58955. anchorX (anchorX_),
  58956. anchorY (anchorY_),
  58957. opacity (opacity_)
  58958. {
  58959. jassert (image != 0); // not much point creating a brush without an image, is there?
  58960. if (image != 0)
  58961. {
  58962. if (image->getWidth() == 0 || image->getHeight() == 0)
  58963. {
  58964. jassertfalse // you've passed in an empty image - not exactly brilliant for tiling.
  58965. image = 0;
  58966. }
  58967. }
  58968. }
  58969. ImageBrush::~ImageBrush() throw()
  58970. {
  58971. }
  58972. Brush* ImageBrush::createCopy() const throw()
  58973. {
  58974. return new ImageBrush (image, anchorX, anchorY, opacity);
  58975. }
  58976. void ImageBrush::multiplyOpacity (const float multiple) throw()
  58977. {
  58978. opacity *= multiple;
  58979. }
  58980. bool ImageBrush::isInvisible() const throw()
  58981. {
  58982. return opacity == 0.0f;
  58983. }
  58984. void ImageBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  58985. {
  58986. //xxx should probably be smarter and warp the image
  58987. }
  58988. void ImageBrush::getStartXY (int& x, int& y) const throw()
  58989. {
  58990. x -= anchorX;
  58991. y -= anchorY;
  58992. const int iw = image->getWidth();
  58993. const int ih = image->getHeight();
  58994. if (x < 0)
  58995. x = ((x / iw) - 1) * iw;
  58996. else
  58997. x = (x / iw) * iw;
  58998. if (y < 0)
  58999. y = ((y / ih) - 1) * ih;
  59000. else
  59001. y = (y / ih) * ih;
  59002. x += anchorX;
  59003. y += anchorY;
  59004. }
  59005. void ImageBrush::paintRectangle (LowLevelGraphicsContext& context,
  59006. int x, int y, int w, int h) throw()
  59007. {
  59008. context.saveState();
  59009. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  59010. {
  59011. const int right = x + w;
  59012. const int bottom = y + h;
  59013. const int iw = image->getWidth();
  59014. const int ih = image->getHeight();
  59015. int startX = x;
  59016. getStartXY (startX, y);
  59017. while (y < bottom)
  59018. {
  59019. x = startX;
  59020. while (x < right)
  59021. {
  59022. context.blendImage (*image, x, y, iw, ih, 0, 0, opacity);
  59023. x += iw;
  59024. }
  59025. y += ih;
  59026. }
  59027. }
  59028. context.restoreState();
  59029. }
  59030. void ImageBrush::paintPath (LowLevelGraphicsContext& context,
  59031. const Path& path, const AffineTransform& transform) throw()
  59032. {
  59033. if (image != 0)
  59034. {
  59035. Rectangle clip (context.getClipBounds());
  59036. {
  59037. float x, y, w, h;
  59038. path.getBoundsTransformed (transform, x, y, w, h);
  59039. clip = clip.getIntersection (Rectangle ((int) floorf (x),
  59040. (int) floorf (y),
  59041. 2 + (int) floorf (w),
  59042. 2 + (int) floorf (h)));
  59043. }
  59044. int x = clip.getX();
  59045. int y = clip.getY();
  59046. const int right = clip.getRight();
  59047. const int bottom = clip.getBottom();
  59048. const int iw = image->getWidth();
  59049. const int ih = image->getHeight();
  59050. int startX = x;
  59051. getStartXY (startX, y);
  59052. while (y < bottom)
  59053. {
  59054. x = startX;
  59055. while (x < right)
  59056. {
  59057. context.fillPathWithImage (path, transform, *image, x, y, opacity, EdgeTable::Oversampling_4times);
  59058. x += iw;
  59059. }
  59060. y += ih;
  59061. }
  59062. }
  59063. }
  59064. void ImageBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  59065. const Image& alphaChannelImage, int imageX, int imageY,
  59066. int x, int y, int w, int h) throw()
  59067. {
  59068. context.saveState();
  59069. if (image != 0 && context.reduceClipRegion (x, y, w, h))
  59070. {
  59071. const Rectangle clip (context.getClipBounds());
  59072. x = clip.getX();
  59073. y = clip.getY();
  59074. const int right = clip.getRight();
  59075. const int bottom = clip.getBottom();
  59076. const int iw = image->getWidth();
  59077. const int ih = image->getHeight();
  59078. int startX = x;
  59079. getStartXY (startX, y);
  59080. while (y < bottom)
  59081. {
  59082. x = startX;
  59083. while (x < right)
  59084. {
  59085. context.fillAlphaChannelWithImage (alphaChannelImage,
  59086. imageX, imageY, *image,
  59087. x, y, opacity);
  59088. x += iw;
  59089. }
  59090. y += ih;
  59091. }
  59092. }
  59093. context.restoreState();
  59094. }
  59095. END_JUCE_NAMESPACE
  59096. /********* End of inlined file: juce_ImageBrush.cpp *********/
  59097. /********* Start of inlined file: juce_SolidColourBrush.cpp *********/
  59098. BEGIN_JUCE_NAMESPACE
  59099. SolidColourBrush::SolidColourBrush() throw()
  59100. : colour (0xff000000)
  59101. {
  59102. }
  59103. SolidColourBrush::SolidColourBrush (const Colour& colour_) throw()
  59104. : colour (colour_)
  59105. {
  59106. }
  59107. SolidColourBrush::~SolidColourBrush() throw()
  59108. {
  59109. }
  59110. Brush* SolidColourBrush::createCopy() const throw()
  59111. {
  59112. return new SolidColourBrush (colour);
  59113. }
  59114. void SolidColourBrush::applyTransform (const AffineTransform& /*transform*/) throw()
  59115. {
  59116. }
  59117. void SolidColourBrush::multiplyOpacity (const float multiple) throw()
  59118. {
  59119. colour = colour.withMultipliedAlpha (multiple);
  59120. }
  59121. bool SolidColourBrush::isInvisible() const throw()
  59122. {
  59123. return colour.isTransparent();
  59124. }
  59125. void SolidColourBrush::paintPath (LowLevelGraphicsContext& context,
  59126. const Path& path, const AffineTransform& transform) throw()
  59127. {
  59128. if (! colour.isTransparent())
  59129. context.fillPathWithColour (path, transform, colour, EdgeTable::Oversampling_4times);
  59130. }
  59131. void SolidColourBrush::paintRectangle (LowLevelGraphicsContext& context,
  59132. int x, int y, int w, int h) throw()
  59133. {
  59134. if (! colour.isTransparent())
  59135. context.fillRectWithColour (x, y, w, h, colour, false);
  59136. }
  59137. void SolidColourBrush::paintAlphaChannel (LowLevelGraphicsContext& context,
  59138. const Image& alphaChannelImage, int imageX, int imageY,
  59139. int x, int y, int w, int h) throw()
  59140. {
  59141. if (! colour.isTransparent())
  59142. {
  59143. context.saveState();
  59144. if (context.reduceClipRegion (x, y, w, h))
  59145. context.fillAlphaChannelWithColour (alphaChannelImage, imageX, imageY, colour);
  59146. context.restoreState();
  59147. }
  59148. }
  59149. void SolidColourBrush::paintVerticalLine (LowLevelGraphicsContext& context,
  59150. int x, float y1, float y2) throw()
  59151. {
  59152. context.drawVerticalLine (x, y1, y2, colour);
  59153. }
  59154. void SolidColourBrush::paintHorizontalLine (LowLevelGraphicsContext& context,
  59155. int y, float x1, float x2) throw()
  59156. {
  59157. context.drawHorizontalLine (y, x1, x2, colour);
  59158. }
  59159. void SolidColourBrush::paintLine (LowLevelGraphicsContext& context,
  59160. float x1, float y1, float x2, float y2) throw()
  59161. {
  59162. context.drawLine (x1, y1, x2, y2, colour);
  59163. }
  59164. END_JUCE_NAMESPACE
  59165. /********* End of inlined file: juce_SolidColourBrush.cpp *********/
  59166. /********* Start of inlined file: juce_Colour.cpp *********/
  59167. BEGIN_JUCE_NAMESPACE
  59168. static forcedinline uint8 floatAlphaToInt (const float alpha)
  59169. {
  59170. return (uint8) jlimit (0, 0xff, roundFloatToInt (alpha * 255.0f));
  59171. }
  59172. static const float oneOver255 = 1.0f / 255.0f;
  59173. Colour::Colour() throw()
  59174. : argb (0)
  59175. {
  59176. }
  59177. Colour::Colour (const Colour& other) throw()
  59178. : argb (other.argb)
  59179. {
  59180. }
  59181. const Colour& Colour::operator= (const Colour& other) throw()
  59182. {
  59183. argb = other.argb;
  59184. return *this;
  59185. }
  59186. bool Colour::operator== (const Colour& other) const throw()
  59187. {
  59188. return argb.getARGB() == other.argb.getARGB();
  59189. }
  59190. bool Colour::operator!= (const Colour& other) const throw()
  59191. {
  59192. return argb.getARGB() != other.argb.getARGB();
  59193. }
  59194. Colour::Colour (const uint32 argb_) throw()
  59195. : argb (argb_)
  59196. {
  59197. }
  59198. Colour::Colour (const uint8 red,
  59199. const uint8 green,
  59200. const uint8 blue) throw()
  59201. {
  59202. argb.setARGB (0xff, red, green, blue);
  59203. }
  59204. const Colour Colour::fromRGB (const uint8 red,
  59205. const uint8 green,
  59206. const uint8 blue) throw()
  59207. {
  59208. return Colour (red, green, blue);
  59209. }
  59210. Colour::Colour (const uint8 red,
  59211. const uint8 green,
  59212. const uint8 blue,
  59213. const uint8 alpha) throw()
  59214. {
  59215. argb.setARGB (alpha, red, green, blue);
  59216. }
  59217. const Colour Colour::fromRGBA (const uint8 red,
  59218. const uint8 green,
  59219. const uint8 blue,
  59220. const uint8 alpha) throw()
  59221. {
  59222. return Colour (red, green, blue, alpha);
  59223. }
  59224. Colour::Colour (const uint8 red,
  59225. const uint8 green,
  59226. const uint8 blue,
  59227. const float alpha) throw()
  59228. {
  59229. argb.setARGB (floatAlphaToInt (alpha), red, green, blue);
  59230. }
  59231. const Colour Colour::fromRGBAFloat (const uint8 red,
  59232. const uint8 green,
  59233. const uint8 blue,
  59234. const float alpha) throw()
  59235. {
  59236. return Colour (red, green, blue, alpha);
  59237. }
  59238. static void convertHSBtoRGB (float h, const float s, float v,
  59239. uint8& r, uint8& g, uint8& b) throw()
  59240. {
  59241. v *= 255.0f;
  59242. const uint8 intV = (uint8) roundFloatToInt (v);
  59243. if (s == 0)
  59244. {
  59245. r = intV;
  59246. g = intV;
  59247. b = intV;
  59248. }
  59249. else
  59250. {
  59251. h = (h - floorf (h)) * 6.0f + 0.00001f; // need a small adjustment to compensate for rounding errors
  59252. const float f = h - floorf (h);
  59253. const uint8 x = (uint8) roundFloatToInt (v * (1.0f - s));
  59254. const float y = v * (1.0f - s * f);
  59255. const float z = v * (1.0f - (s * (1.0f - f)));
  59256. if (h < 1.0f)
  59257. {
  59258. r = intV;
  59259. g = (uint8) roundFloatToInt (z);
  59260. b = x;
  59261. }
  59262. else if (h < 2.0f)
  59263. {
  59264. r = (uint8) roundFloatToInt (y);
  59265. g = intV;
  59266. b = x;
  59267. }
  59268. else if (h < 3.0f)
  59269. {
  59270. r = x;
  59271. g = intV;
  59272. b = (uint8) roundFloatToInt (z);
  59273. }
  59274. else if (h < 4.0f)
  59275. {
  59276. r = x;
  59277. g = (uint8) roundFloatToInt (y);
  59278. b = intV;
  59279. }
  59280. else if (h < 5.0f)
  59281. {
  59282. r = (uint8) roundFloatToInt (z);
  59283. g = x;
  59284. b = intV;
  59285. }
  59286. else if (h < 6.0f)
  59287. {
  59288. r = intV;
  59289. g = x;
  59290. b = (uint8) roundFloatToInt (y);
  59291. }
  59292. else
  59293. {
  59294. r = 0;
  59295. g = 0;
  59296. b = 0;
  59297. }
  59298. }
  59299. }
  59300. Colour::Colour (const float hue,
  59301. const float saturation,
  59302. const float brightness,
  59303. const float alpha) throw()
  59304. {
  59305. uint8 r = getRed(), g = getGreen(), b = getBlue();
  59306. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  59307. argb.setARGB (floatAlphaToInt (alpha), r, g, b);
  59308. }
  59309. const Colour Colour::fromHSV (const float hue,
  59310. const float saturation,
  59311. const float brightness,
  59312. const float alpha) throw()
  59313. {
  59314. return Colour (hue, saturation, brightness, alpha);
  59315. }
  59316. Colour::Colour (const float hue,
  59317. const float saturation,
  59318. const float brightness,
  59319. const uint8 alpha) throw()
  59320. {
  59321. uint8 r = getRed(), g = getGreen(), b = getBlue();
  59322. convertHSBtoRGB (hue, saturation, brightness, r, g, b);
  59323. argb.setARGB (alpha, r, g, b);
  59324. }
  59325. Colour::~Colour() throw()
  59326. {
  59327. }
  59328. const PixelARGB Colour::getPixelARGB() const throw()
  59329. {
  59330. PixelARGB p (argb);
  59331. p.premultiply();
  59332. return p;
  59333. }
  59334. uint32 Colour::getARGB() const throw()
  59335. {
  59336. return argb.getARGB();
  59337. }
  59338. bool Colour::isTransparent() const throw()
  59339. {
  59340. return getAlpha() == 0;
  59341. }
  59342. bool Colour::isOpaque() const throw()
  59343. {
  59344. return getAlpha() == 0xff;
  59345. }
  59346. const Colour Colour::withAlpha (const uint8 newAlpha) const throw()
  59347. {
  59348. PixelARGB newCol (argb);
  59349. newCol.setAlpha (newAlpha);
  59350. return Colour (newCol.getARGB());
  59351. }
  59352. const Colour Colour::withAlpha (const float newAlpha) const throw()
  59353. {
  59354. jassert (newAlpha >= 0 && newAlpha <= 1.0f);
  59355. PixelARGB newCol (argb);
  59356. newCol.setAlpha (floatAlphaToInt (newAlpha));
  59357. return Colour (newCol.getARGB());
  59358. }
  59359. const Colour Colour::withMultipliedAlpha (const float alphaMultiplier) const throw()
  59360. {
  59361. jassert (alphaMultiplier >= 0);
  59362. PixelARGB newCol (argb);
  59363. newCol.setAlpha ((uint8) jmin (0xff, roundFloatToInt (alphaMultiplier * newCol.getAlpha())));
  59364. return Colour (newCol.getARGB());
  59365. }
  59366. const Colour Colour::overlaidWith (const Colour& src) const throw()
  59367. {
  59368. const int destAlpha = getAlpha();
  59369. if (destAlpha > 0)
  59370. {
  59371. const int invA = 0xff - (int) src.getAlpha();
  59372. const int resA = 0xff - (((0xff - destAlpha) * invA) >> 8);
  59373. if (resA > 0)
  59374. {
  59375. const int da = (invA * destAlpha) / resA;
  59376. return Colour ((uint8) (src.getRed() + ((((int) getRed() - src.getRed()) * da) >> 8)),
  59377. (uint8) (src.getGreen() + ((((int) getGreen() - src.getGreen()) * da) >> 8)),
  59378. (uint8) (src.getBlue() + ((((int) getBlue() - src.getBlue()) * da) >> 8)),
  59379. (uint8) resA);
  59380. }
  59381. return *this;
  59382. }
  59383. else
  59384. {
  59385. return src;
  59386. }
  59387. }
  59388. float Colour::getFloatRed() const throw()
  59389. {
  59390. return getRed() * oneOver255;
  59391. }
  59392. float Colour::getFloatGreen() const throw()
  59393. {
  59394. return getGreen() * oneOver255;
  59395. }
  59396. float Colour::getFloatBlue() const throw()
  59397. {
  59398. return getBlue() * oneOver255;
  59399. }
  59400. float Colour::getFloatAlpha() const throw()
  59401. {
  59402. return getAlpha() * oneOver255;
  59403. }
  59404. void Colour::getHSB (float& h, float& s, float& v) const throw()
  59405. {
  59406. const int r = getRed();
  59407. const int g = getGreen();
  59408. const int b = getBlue();
  59409. const int hi = jmax (r, g, b);
  59410. const int lo = jmin (r, g, b);
  59411. if (hi != 0)
  59412. {
  59413. s = (hi - lo) / (float) hi;
  59414. if (s != 0)
  59415. {
  59416. const float invDiff = 1.0f / (hi - lo);
  59417. const float red = (hi - r) * invDiff;
  59418. const float green = (hi - g) * invDiff;
  59419. const float blue = (hi - b) * invDiff;
  59420. if (r == hi)
  59421. h = blue - green;
  59422. else if (g == hi)
  59423. h = 2.0f + red - blue;
  59424. else
  59425. h = 4.0f + green - red;
  59426. h *= 1.0f / 6.0f;
  59427. if (h < 0)
  59428. ++h;
  59429. }
  59430. else
  59431. {
  59432. h = 0;
  59433. }
  59434. }
  59435. else
  59436. {
  59437. s = 0;
  59438. h = 0;
  59439. }
  59440. v = hi * oneOver255;
  59441. }
  59442. float Colour::getHue() const throw()
  59443. {
  59444. float h, s, b;
  59445. getHSB (h, s, b);
  59446. return h;
  59447. }
  59448. const Colour Colour::withHue (const float hue) const throw()
  59449. {
  59450. float h, s, b;
  59451. getHSB (h, s, b);
  59452. return Colour (hue, s, b, getAlpha());
  59453. }
  59454. const Colour Colour::withRotatedHue (const float amountToRotate) const throw()
  59455. {
  59456. float h, s, b;
  59457. getHSB (h, s, b);
  59458. h += amountToRotate;
  59459. h -= floorf (h);
  59460. return Colour (h, s, b, getAlpha());
  59461. }
  59462. float Colour::getSaturation() const throw()
  59463. {
  59464. float h, s, b;
  59465. getHSB (h, s, b);
  59466. return s;
  59467. }
  59468. const Colour Colour::withSaturation (const float saturation) const throw()
  59469. {
  59470. float h, s, b;
  59471. getHSB (h, s, b);
  59472. return Colour (h, saturation, b, getAlpha());
  59473. }
  59474. const Colour Colour::withMultipliedSaturation (const float amount) const throw()
  59475. {
  59476. float h, s, b;
  59477. getHSB (h, s, b);
  59478. return Colour (h, jmin (1.0f, s * amount), b, getAlpha());
  59479. }
  59480. float Colour::getBrightness() const throw()
  59481. {
  59482. float h, s, b;
  59483. getHSB (h, s, b);
  59484. return b;
  59485. }
  59486. const Colour Colour::withBrightness (const float brightness) const throw()
  59487. {
  59488. float h, s, b;
  59489. getHSB (h, s, b);
  59490. return Colour (h, s, brightness, getAlpha());
  59491. }
  59492. const Colour Colour::withMultipliedBrightness (const float amount) const throw()
  59493. {
  59494. float h, s, b;
  59495. getHSB (h, s, b);
  59496. b *= amount;
  59497. if (b > 1.0f)
  59498. b = 1.0f;
  59499. return Colour (h, s, b, getAlpha());
  59500. }
  59501. const Colour Colour::brighter (float amount) const throw()
  59502. {
  59503. amount = 1.0f / (1.0f + amount);
  59504. return Colour ((uint8) (255 - (amount * (255 - getRed()))),
  59505. (uint8) (255 - (amount * (255 - getGreen()))),
  59506. (uint8) (255 - (amount * (255 - getBlue()))),
  59507. getAlpha());
  59508. }
  59509. const Colour Colour::darker (float amount) const throw()
  59510. {
  59511. amount = 1.0f / (1.0f + amount);
  59512. return Colour ((uint8) (amount * getRed()),
  59513. (uint8) (amount * getGreen()),
  59514. (uint8) (amount * getBlue()),
  59515. getAlpha());
  59516. }
  59517. const Colour Colour::greyLevel (const float brightness) throw()
  59518. {
  59519. const uint8 level
  59520. = (uint8) jlimit (0x00, 0xff, roundFloatToInt (brightness * 255.0f));
  59521. return Colour (level, level, level);
  59522. }
  59523. const Colour Colour::contrasting (const float amount) const throw()
  59524. {
  59525. return overlaidWith ((((int) getRed() + (int) getGreen() + (int) getBlue() >= 3 * 128)
  59526. ? Colours::black
  59527. : Colours::white).withAlpha (amount));
  59528. }
  59529. const Colour Colour::contrasting (const Colour& colour1,
  59530. const Colour& colour2) throw()
  59531. {
  59532. const float b1 = colour1.getBrightness();
  59533. const float b2 = colour2.getBrightness();
  59534. float best = 0.0f;
  59535. float bestDist = 0.0f;
  59536. for (float i = 0.0f; i < 1.0f; i += 0.02f)
  59537. {
  59538. const float d1 = fabsf (i - b1);
  59539. const float d2 = fabsf (i - b2);
  59540. const float dist = jmin (d1, d2, 1.0f - d1, 1.0f - d2);
  59541. if (dist > bestDist)
  59542. {
  59543. best = i;
  59544. bestDist = dist;
  59545. }
  59546. }
  59547. return colour1.overlaidWith (colour2.withMultipliedAlpha (0.5f))
  59548. .withBrightness (best);
  59549. }
  59550. const String Colour::toString() const throw()
  59551. {
  59552. return String::toHexString ((int) argb.getARGB());
  59553. }
  59554. const Colour Colour::fromString (const String& encodedColourString)
  59555. {
  59556. return Colour ((uint32) encodedColourString.getHexValue32());
  59557. }
  59558. END_JUCE_NAMESPACE
  59559. /********* End of inlined file: juce_Colour.cpp *********/
  59560. /********* Start of inlined file: juce_ColourGradient.cpp *********/
  59561. BEGIN_JUCE_NAMESPACE
  59562. ColourGradient::ColourGradient() throw()
  59563. : colours (4)
  59564. {
  59565. #ifdef JUCE_DEBUG
  59566. x1 = 987654.0f;
  59567. #endif
  59568. }
  59569. ColourGradient::ColourGradient (const Colour& colour1,
  59570. const float x1_,
  59571. const float y1_,
  59572. const Colour& colour2,
  59573. const float x2_,
  59574. const float y2_,
  59575. const bool isRadial_) throw()
  59576. : x1 (x1_),
  59577. y1 (y1_),
  59578. x2 (x2_),
  59579. y2 (y2_),
  59580. isRadial (isRadial_),
  59581. colours (4)
  59582. {
  59583. colours.add (0);
  59584. colours.add (colour1.getPixelARGB().getARGB());
  59585. colours.add (1 << 16);
  59586. colours.add (colour2.getPixelARGB().getARGB());
  59587. }
  59588. ColourGradient::~ColourGradient() throw()
  59589. {
  59590. }
  59591. void ColourGradient::clearColours() throw()
  59592. {
  59593. colours.clear();
  59594. }
  59595. void ColourGradient::addColour (const double proportionAlongGradient,
  59596. const Colour& colour) throw()
  59597. {
  59598. // must be within the two end-points
  59599. jassert (proportionAlongGradient >= 0 && proportionAlongGradient <= 1.0);
  59600. const uint32 pos = jlimit (0, 65535, roundDoubleToInt (proportionAlongGradient * 65536.0));
  59601. int i;
  59602. for (i = 0; i < colours.size(); i += 2)
  59603. if (colours.getUnchecked(i) > pos)
  59604. break;
  59605. colours.insert (i, pos);
  59606. colours.insert (i + 1, colour.getPixelARGB().getARGB());
  59607. }
  59608. void ColourGradient::multiplyOpacity (const float multiplier) throw()
  59609. {
  59610. for (int i = 1; i < colours.size(); i += 2)
  59611. {
  59612. PixelARGB pix (colours.getUnchecked(i));
  59613. pix.multiplyAlpha (multiplier);
  59614. colours.set (i, pix.getARGB());
  59615. }
  59616. }
  59617. int ColourGradient::getNumColours() const throw()
  59618. {
  59619. return colours.size() >> 1;
  59620. }
  59621. double ColourGradient::getColourPosition (const int index) const throw()
  59622. {
  59623. return colours [index << 1];
  59624. }
  59625. const Colour ColourGradient::getColour (const int index) const throw()
  59626. {
  59627. PixelARGB pix (colours [(index << 1) + 1]);
  59628. pix.unpremultiply();
  59629. return Colour (pix.getARGB());
  59630. }
  59631. PixelARGB* ColourGradient::createLookupTable (int& numEntries) const throw()
  59632. {
  59633. #ifdef JUCE_DEBUG
  59634. // trying to use the object without setting its co-ordinates? Have a careful read of
  59635. // the comments for the constructors.
  59636. jassert (x1 != 987654.0f);
  59637. #endif
  59638. const int numColours = colours.size() >> 1;
  59639. float tx1 = x1, ty1 = y1, tx2 = x2, ty2 = y2;
  59640. transform.transformPoint (tx1, ty1);
  59641. transform.transformPoint (tx2, ty2);
  59642. const double distance = juce_hypot (tx1 - tx2, ty1 - ty2);
  59643. numEntries = jlimit (1, (numColours - 1) << 8, 3 * (int) distance);
  59644. PixelARGB* const lookupTable = (PixelARGB*) juce_calloc (numEntries * sizeof (PixelARGB));
  59645. if (numColours >= 2)
  59646. {
  59647. jassert (colours.getUnchecked (0) == 0); // the first colour specified has to go at position 0
  59648. PixelARGB pix1 (colours.getUnchecked (1));
  59649. int index = 0;
  59650. for (int j = 2; j < colours.size(); j += 2)
  59651. {
  59652. const int numToDo = ((colours.getUnchecked (j) * numEntries) >> 16) - index;
  59653. const PixelARGB pix2 (colours.getUnchecked (j + 1));
  59654. for (int i = 0; i < numToDo; ++i)
  59655. {
  59656. jassert (index >= 0 && index < numEntries);
  59657. lookupTable[index] = pix1;
  59658. lookupTable[index].tween (pix2, (i << 8) / numToDo);
  59659. ++index;
  59660. }
  59661. pix1 = pix2;
  59662. }
  59663. while (index < numEntries)
  59664. lookupTable [index++] = pix1;
  59665. }
  59666. else
  59667. {
  59668. jassertfalse // no colours specified!
  59669. }
  59670. return lookupTable;
  59671. }
  59672. bool ColourGradient::isOpaque() const throw()
  59673. {
  59674. for (int i = 1; i < colours.size(); i += 2)
  59675. if (PixelARGB (colours.getUnchecked(i)).getAlpha() < 0xff)
  59676. return false;
  59677. return true;
  59678. }
  59679. bool ColourGradient::isInvisible() const throw()
  59680. {
  59681. for (int i = 1; i < colours.size(); i += 2)
  59682. if (PixelARGB (colours.getUnchecked(i)).getAlpha() > 0)
  59683. return false;
  59684. return true;
  59685. }
  59686. END_JUCE_NAMESPACE
  59687. /********* End of inlined file: juce_ColourGradient.cpp *********/
  59688. /********* Start of inlined file: juce_Colours.cpp *********/
  59689. BEGIN_JUCE_NAMESPACE
  59690. const Colour Colours::transparentBlack (0);
  59691. const Colour Colours::transparentWhite (0x00ffffff);
  59692. const Colour Colours::aliceblue (0xfff0f8ff);
  59693. const Colour Colours::antiquewhite (0xfffaebd7);
  59694. const Colour Colours::aqua (0xff00ffff);
  59695. const Colour Colours::aquamarine (0xff7fffd4);
  59696. const Colour Colours::azure (0xfff0ffff);
  59697. const Colour Colours::beige (0xfff5f5dc);
  59698. const Colour Colours::bisque (0xffffe4c4);
  59699. const Colour Colours::black (0xff000000);
  59700. const Colour Colours::blanchedalmond (0xffffebcd);
  59701. const Colour Colours::blue (0xff0000ff);
  59702. const Colour Colours::blueviolet (0xff8a2be2);
  59703. const Colour Colours::brown (0xffa52a2a);
  59704. const Colour Colours::burlywood (0xffdeb887);
  59705. const Colour Colours::cadetblue (0xff5f9ea0);
  59706. const Colour Colours::chartreuse (0xff7fff00);
  59707. const Colour Colours::chocolate (0xffd2691e);
  59708. const Colour Colours::coral (0xffff7f50);
  59709. const Colour Colours::cornflowerblue (0xff6495ed);
  59710. const Colour Colours::cornsilk (0xfffff8dc);
  59711. const Colour Colours::crimson (0xffdc143c);
  59712. const Colour Colours::cyan (0xff00ffff);
  59713. const Colour Colours::darkblue (0xff00008b);
  59714. const Colour Colours::darkcyan (0xff008b8b);
  59715. const Colour Colours::darkgoldenrod (0xffb8860b);
  59716. const Colour Colours::darkgrey (0xff555555);
  59717. const Colour Colours::darkgreen (0xff006400);
  59718. const Colour Colours::darkkhaki (0xffbdb76b);
  59719. const Colour Colours::darkmagenta (0xff8b008b);
  59720. const Colour Colours::darkolivegreen (0xff556b2f);
  59721. const Colour Colours::darkorange (0xffff8c00);
  59722. const Colour Colours::darkorchid (0xff9932cc);
  59723. const Colour Colours::darkred (0xff8b0000);
  59724. const Colour Colours::darksalmon (0xffe9967a);
  59725. const Colour Colours::darkseagreen (0xff8fbc8f);
  59726. const Colour Colours::darkslateblue (0xff483d8b);
  59727. const Colour Colours::darkslategrey (0xff2f4f4f);
  59728. const Colour Colours::darkturquoise (0xff00ced1);
  59729. const Colour Colours::darkviolet (0xff9400d3);
  59730. const Colour Colours::deeppink (0xffff1493);
  59731. const Colour Colours::deepskyblue (0xff00bfff);
  59732. const Colour Colours::dimgrey (0xff696969);
  59733. const Colour Colours::dodgerblue (0xff1e90ff);
  59734. const Colour Colours::firebrick (0xffb22222);
  59735. const Colour Colours::floralwhite (0xfffffaf0);
  59736. const Colour Colours::forestgreen (0xff228b22);
  59737. const Colour Colours::fuchsia (0xffff00ff);
  59738. const Colour Colours::gainsboro (0xffdcdcdc);
  59739. const Colour Colours::gold (0xffffd700);
  59740. const Colour Colours::goldenrod (0xffdaa520);
  59741. const Colour Colours::grey (0xff808080);
  59742. const Colour Colours::green (0xff008000);
  59743. const Colour Colours::greenyellow (0xffadff2f);
  59744. const Colour Colours::honeydew (0xfff0fff0);
  59745. const Colour Colours::hotpink (0xffff69b4);
  59746. const Colour Colours::indianred (0xffcd5c5c);
  59747. const Colour Colours::indigo (0xff4b0082);
  59748. const Colour Colours::ivory (0xfffffff0);
  59749. const Colour Colours::khaki (0xfff0e68c);
  59750. const Colour Colours::lavender (0xffe6e6fa);
  59751. const Colour Colours::lavenderblush (0xfffff0f5);
  59752. const Colour Colours::lemonchiffon (0xfffffacd);
  59753. const Colour Colours::lightblue (0xffadd8e6);
  59754. const Colour Colours::lightcoral (0xfff08080);
  59755. const Colour Colours::lightcyan (0xffe0ffff);
  59756. const Colour Colours::lightgoldenrodyellow (0xfffafad2);
  59757. const Colour Colours::lightgreen (0xff90ee90);
  59758. const Colour Colours::lightgrey (0xffd3d3d3);
  59759. const Colour Colours::lightpink (0xffffb6c1);
  59760. const Colour Colours::lightsalmon (0xffffa07a);
  59761. const Colour Colours::lightseagreen (0xff20b2aa);
  59762. const Colour Colours::lightskyblue (0xff87cefa);
  59763. const Colour Colours::lightslategrey (0xff778899);
  59764. const Colour Colours::lightsteelblue (0xffb0c4de);
  59765. const Colour Colours::lightyellow (0xffffffe0);
  59766. const Colour Colours::lime (0xff00ff00);
  59767. const Colour Colours::limegreen (0xff32cd32);
  59768. const Colour Colours::linen (0xfffaf0e6);
  59769. const Colour Colours::magenta (0xffff00ff);
  59770. const Colour Colours::maroon (0xff800000);
  59771. const Colour Colours::mediumaquamarine (0xff66cdaa);
  59772. const Colour Colours::mediumblue (0xff0000cd);
  59773. const Colour Colours::mediumorchid (0xffba55d3);
  59774. const Colour Colours::mediumpurple (0xff9370db);
  59775. const Colour Colours::mediumseagreen (0xff3cb371);
  59776. const Colour Colours::mediumslateblue (0xff7b68ee);
  59777. const Colour Colours::mediumspringgreen (0xff00fa9a);
  59778. const Colour Colours::mediumturquoise (0xff48d1cc);
  59779. const Colour Colours::mediumvioletred (0xffc71585);
  59780. const Colour Colours::midnightblue (0xff191970);
  59781. const Colour Colours::mintcream (0xfff5fffa);
  59782. const Colour Colours::mistyrose (0xffffe4e1);
  59783. const Colour Colours::navajowhite (0xffffdead);
  59784. const Colour Colours::navy (0xff000080);
  59785. const Colour Colours::oldlace (0xfffdf5e6);
  59786. const Colour Colours::olive (0xff808000);
  59787. const Colour Colours::olivedrab (0xff6b8e23);
  59788. const Colour Colours::orange (0xffffa500);
  59789. const Colour Colours::orangered (0xffff4500);
  59790. const Colour Colours::orchid (0xffda70d6);
  59791. const Colour Colours::palegoldenrod (0xffeee8aa);
  59792. const Colour Colours::palegreen (0xff98fb98);
  59793. const Colour Colours::paleturquoise (0xffafeeee);
  59794. const Colour Colours::palevioletred (0xffdb7093);
  59795. const Colour Colours::papayawhip (0xffffefd5);
  59796. const Colour Colours::peachpuff (0xffffdab9);
  59797. const Colour Colours::peru (0xffcd853f);
  59798. const Colour Colours::pink (0xffffc0cb);
  59799. const Colour Colours::plum (0xffdda0dd);
  59800. const Colour Colours::powderblue (0xffb0e0e6);
  59801. const Colour Colours::purple (0xff800080);
  59802. const Colour Colours::red (0xffff0000);
  59803. const Colour Colours::rosybrown (0xffbc8f8f);
  59804. const Colour Colours::royalblue (0xff4169e1);
  59805. const Colour Colours::saddlebrown (0xff8b4513);
  59806. const Colour Colours::salmon (0xfffa8072);
  59807. const Colour Colours::sandybrown (0xfff4a460);
  59808. const Colour Colours::seagreen (0xff2e8b57);
  59809. const Colour Colours::seashell (0xfffff5ee);
  59810. const Colour Colours::sienna (0xffa0522d);
  59811. const Colour Colours::silver (0xffc0c0c0);
  59812. const Colour Colours::skyblue (0xff87ceeb);
  59813. const Colour Colours::slateblue (0xff6a5acd);
  59814. const Colour Colours::slategrey (0xff708090);
  59815. const Colour Colours::snow (0xfffffafa);
  59816. const Colour Colours::springgreen (0xff00ff7f);
  59817. const Colour Colours::steelblue (0xff4682b4);
  59818. const Colour Colours::tan (0xffd2b48c);
  59819. const Colour Colours::teal (0xff008080);
  59820. const Colour Colours::thistle (0xffd8bfd8);
  59821. const Colour Colours::tomato (0xffff6347);
  59822. const Colour Colours::turquoise (0xff40e0d0);
  59823. const Colour Colours::violet (0xffee82ee);
  59824. const Colour Colours::wheat (0xfff5deb3);
  59825. const Colour Colours::white (0xffffffff);
  59826. const Colour Colours::whitesmoke (0xfff5f5f5);
  59827. const Colour Colours::yellow (0xffffff00);
  59828. const Colour Colours::yellowgreen (0xff9acd32);
  59829. const Colour Colours::findColourForName (const String& colourName,
  59830. const Colour& defaultColour)
  59831. {
  59832. static const int presets[] =
  59833. {
  59834. // (first value is the string's hashcode, second is ARGB)
  59835. 0x05978fff, 0xff000000, /* black */
  59836. 0x06bdcc29, 0xffffffff, /* white */
  59837. 0x002e305a, 0xff0000ff, /* blue */
  59838. 0x00308adf, 0xff808080, /* grey */
  59839. 0x05e0cf03, 0xff008000, /* green */
  59840. 0x0001b891, 0xffff0000, /* red */
  59841. 0xd43c6474, 0xffffff00, /* yellow */
  59842. 0x620886da, 0xfff0f8ff, /* aliceblue */
  59843. 0x20a2676a, 0xfffaebd7, /* antiquewhite */
  59844. 0x002dcebc, 0xff00ffff, /* aqua */
  59845. 0x46bb5f7e, 0xff7fffd4, /* aquamarine */
  59846. 0x0590228f, 0xfff0ffff, /* azure */
  59847. 0x05947fe4, 0xfff5f5dc, /* beige */
  59848. 0xad388e35, 0xffffe4c4, /* bisque */
  59849. 0x00674f7e, 0xffffebcd, /* blanchedalmond */
  59850. 0x39129959, 0xff8a2be2, /* blueviolet */
  59851. 0x059a8136, 0xffa52a2a, /* brown */
  59852. 0x89cea8f9, 0xffdeb887, /* burlywood */
  59853. 0x0fa260cf, 0xff5f9ea0, /* cadetblue */
  59854. 0x6b748956, 0xff7fff00, /* chartreuse */
  59855. 0x2903623c, 0xffd2691e, /* chocolate */
  59856. 0x05a74431, 0xffff7f50, /* coral */
  59857. 0x618d42dd, 0xff6495ed, /* cornflowerblue */
  59858. 0xe4b479fd, 0xfffff8dc, /* cornsilk */
  59859. 0x3d8c4edf, 0xffdc143c, /* crimson */
  59860. 0x002ed323, 0xff00ffff, /* cyan */
  59861. 0x67cc74d0, 0xff00008b, /* darkblue */
  59862. 0x67cd1799, 0xff008b8b, /* darkcyan */
  59863. 0x31bbd168, 0xffb8860b, /* darkgoldenrod */
  59864. 0x67cecf55, 0xff555555, /* darkgrey */
  59865. 0x920b194d, 0xff006400, /* darkgreen */
  59866. 0x923edd4c, 0xffbdb76b, /* darkkhaki */
  59867. 0x5c293873, 0xff8b008b, /* darkmagenta */
  59868. 0x6b6671fe, 0xff556b2f, /* darkolivegreen */
  59869. 0xbcfd2524, 0xffff8c00, /* darkorange */
  59870. 0xbcfdf799, 0xff9932cc, /* darkorchid */
  59871. 0x55ee0d5b, 0xff8b0000, /* darkred */
  59872. 0xc2e5f564, 0xffe9967a, /* darksalmon */
  59873. 0x61be858a, 0xff8fbc8f, /* darkseagreen */
  59874. 0xc2b0f2bd, 0xff483d8b, /* darkslateblue */
  59875. 0xc2b34d42, 0xff2f4f4f, /* darkslategrey */
  59876. 0x7cf2b06b, 0xff00ced1, /* darkturquoise */
  59877. 0xc8769375, 0xff9400d3, /* darkviolet */
  59878. 0x25832862, 0xffff1493, /* deeppink */
  59879. 0xfcad568f, 0xff00bfff, /* deepskyblue */
  59880. 0x634c8b67, 0xff696969, /* dimgrey */
  59881. 0x45c1ce55, 0xff1e90ff, /* dodgerblue */
  59882. 0xef19e3cb, 0xffb22222, /* firebrick */
  59883. 0xb852b195, 0xfffffaf0, /* floralwhite */
  59884. 0xd086fd06, 0xff228b22, /* forestgreen */
  59885. 0xe106b6d7, 0xffff00ff, /* fuchsia */
  59886. 0x7880d61e, 0xffdcdcdc, /* gainsboro */
  59887. 0x00308060, 0xffffd700, /* gold */
  59888. 0xb3b3bc1e, 0xffdaa520, /* goldenrod */
  59889. 0xbab8a537, 0xffadff2f, /* greenyellow */
  59890. 0xe4cacafb, 0xfff0fff0, /* honeydew */
  59891. 0x41892743, 0xffff69b4, /* hotpink */
  59892. 0xd5796f1a, 0xffcd5c5c, /* indianred */
  59893. 0xb969fed2, 0xff4b0082, /* indigo */
  59894. 0x05fef6a9, 0xfffffff0, /* ivory */
  59895. 0x06149302, 0xfff0e68c, /* khaki */
  59896. 0xad5a05c7, 0xffe6e6fa, /* lavender */
  59897. 0x7c4d5b99, 0xfffff0f5, /* lavenderblush */
  59898. 0x195756f0, 0xfffffacd, /* lemonchiffon */
  59899. 0x28e4ea70, 0xffadd8e6, /* lightblue */
  59900. 0xf3c7ccdb, 0xfff08080, /* lightcoral */
  59901. 0x28e58d39, 0xffe0ffff, /* lightcyan */
  59902. 0x21234e3c, 0xfffafad2, /* lightgoldenrodyellow */
  59903. 0xf40157ad, 0xff90ee90, /* lightgreen */
  59904. 0x28e744f5, 0xffd3d3d3, /* lightgrey */
  59905. 0x28eb3b8c, 0xffffb6c1, /* lightpink */
  59906. 0x9fb78304, 0xffffa07a, /* lightsalmon */
  59907. 0x50632b2a, 0xff20b2aa, /* lightseagreen */
  59908. 0x68fb7b25, 0xff87cefa, /* lightskyblue */
  59909. 0xa8a35ba2, 0xff778899, /* lightslategrey */
  59910. 0xa20d484f, 0xffb0c4de, /* lightsteelblue */
  59911. 0xaa2cf10a, 0xffffffe0, /* lightyellow */
  59912. 0x0032afd5, 0xff00ff00, /* lime */
  59913. 0x607bbc4e, 0xff32cd32, /* limegreen */
  59914. 0x06234efa, 0xfffaf0e6, /* linen */
  59915. 0x316858a9, 0xffff00ff, /* magenta */
  59916. 0xbf8ca470, 0xff800000, /* maroon */
  59917. 0xbd58e0b3, 0xff66cdaa, /* mediumaquamarine */
  59918. 0x967dfd4f, 0xff0000cd, /* mediumblue */
  59919. 0x056f5c58, 0xffba55d3, /* mediumorchid */
  59920. 0x07556b71, 0xff9370db, /* mediumpurple */
  59921. 0x5369b689, 0xff3cb371, /* mediumseagreen */
  59922. 0x066be19e, 0xff7b68ee, /* mediumslateblue */
  59923. 0x3256b281, 0xff00fa9a, /* mediumspringgreen */
  59924. 0xc0ad9f4c, 0xff48d1cc, /* mediumturquoise */
  59925. 0x628e63dd, 0xffc71585, /* mediumvioletred */
  59926. 0x168eb32a, 0xff191970, /* midnightblue */
  59927. 0x4306b960, 0xfff5fffa, /* mintcream */
  59928. 0x4cbc0e6b, 0xffffe4e1, /* mistyrose */
  59929. 0xe97218a6, 0xffffdead, /* navajowhite */
  59930. 0x00337bb6, 0xff000080, /* navy */
  59931. 0xadd2d33e, 0xfffdf5e6, /* oldlace */
  59932. 0x064ee1db, 0xff808000, /* olive */
  59933. 0x9e33a98a, 0xff6b8e23, /* olivedrab */
  59934. 0xc3de262e, 0xffffa500, /* orange */
  59935. 0x58bebba3, 0xffff4500, /* orangered */
  59936. 0xc3def8a3, 0xffda70d6, /* orchid */
  59937. 0x28cb4834, 0xffeee8aa, /* palegoldenrod */
  59938. 0x3d9dd619, 0xff98fb98, /* palegreen */
  59939. 0x74022737, 0xffafeeee, /* paleturquoise */
  59940. 0x15e2ebc8, 0xffdb7093, /* palevioletred */
  59941. 0x5fd898e2, 0xffffefd5, /* papayawhip */
  59942. 0x93e1b776, 0xffffdab9, /* peachpuff */
  59943. 0x003472f8, 0xffcd853f, /* peru */
  59944. 0x00348176, 0xffffc0cb, /* pink */
  59945. 0x00348d94, 0xffdda0dd, /* plum */
  59946. 0xd036be93, 0xffb0e0e6, /* powderblue */
  59947. 0xc5c507bc, 0xff800080, /* purple */
  59948. 0xa89d65b3, 0xffbc8f8f, /* rosybrown */
  59949. 0xbd9413e1, 0xff4169e1, /* royalblue */
  59950. 0xf456044f, 0xff8b4513, /* saddlebrown */
  59951. 0xc9c6f66e, 0xfffa8072, /* salmon */
  59952. 0x0bb131e1, 0xfff4a460, /* sandybrown */
  59953. 0x34636c14, 0xff2e8b57, /* seagreen */
  59954. 0x3507fb41, 0xfffff5ee, /* seashell */
  59955. 0xca348772, 0xffa0522d, /* sienna */
  59956. 0xca37d30d, 0xffc0c0c0, /* silver */
  59957. 0x80da74fb, 0xff87ceeb, /* skyblue */
  59958. 0x44a8dd73, 0xff6a5acd, /* slateblue */
  59959. 0x44ab37f8, 0xff708090, /* slategrey */
  59960. 0x0035f183, 0xfffffafa, /* snow */
  59961. 0xd5440d16, 0xff00ff7f, /* springgreen */
  59962. 0x3e1524a5, 0xff4682b4, /* steelblue */
  59963. 0x0001bfa1, 0xffd2b48c, /* tan */
  59964. 0x0036425c, 0xff008080, /* teal */
  59965. 0xafc8858f, 0xffd8bfd8, /* thistle */
  59966. 0xcc41600a, 0xffff6347, /* tomato */
  59967. 0xfeea9b21, 0xff40e0d0, /* turquoise */
  59968. 0xcf57947f, 0xffee82ee, /* violet */
  59969. 0x06bdbae7, 0xfff5deb3, /* wheat */
  59970. 0x10802ee6, 0xfff5f5f5, /* whitesmoke */
  59971. 0xe1b5130f, 0xff9acd32 /* yellowgreen */
  59972. };
  59973. const int hash = colourName.trim().toLowerCase().hashCode();
  59974. for (int i = 0; i < numElementsInArray (presets); i += 2)
  59975. if (presets [i] == hash)
  59976. return Colour (presets [i + 1]);
  59977. return defaultColour;
  59978. }
  59979. END_JUCE_NAMESPACE
  59980. /********* End of inlined file: juce_Colours.cpp *********/
  59981. /********* Start of inlined file: juce_EdgeTable.cpp *********/
  59982. BEGIN_JUCE_NAMESPACE
  59983. EdgeTable::EdgeTable (const int top_,
  59984. const int height_,
  59985. const OversamplingLevel oversampling_,
  59986. const int expectedEdgesPerLine) throw()
  59987. : top (top_),
  59988. height (height_),
  59989. maxEdgesPerLine (expectedEdgesPerLine),
  59990. lineStrideElements ((expectedEdgesPerLine << 1) + 1),
  59991. oversampling (oversampling_)
  59992. {
  59993. table = (int*) juce_calloc ((height << (int)oversampling_)
  59994. * lineStrideElements * sizeof (int));
  59995. }
  59996. EdgeTable::EdgeTable (const EdgeTable& other) throw()
  59997. : table (0)
  59998. {
  59999. operator= (other);
  60000. }
  60001. const EdgeTable& EdgeTable::operator= (const EdgeTable& other) throw()
  60002. {
  60003. juce_free (table);
  60004. top = other.top;
  60005. height = other.height;
  60006. maxEdgesPerLine = other.maxEdgesPerLine;
  60007. lineStrideElements = other.lineStrideElements;
  60008. oversampling = other.oversampling;
  60009. const int tableSize = (height << (int)oversampling)
  60010. * lineStrideElements * sizeof (int);
  60011. table = (int*) juce_malloc (tableSize);
  60012. memcpy (table, other.table, tableSize);
  60013. return *this;
  60014. }
  60015. EdgeTable::~EdgeTable() throw()
  60016. {
  60017. juce_free (table);
  60018. }
  60019. void EdgeTable::remapTableForNumEdges (const int newNumEdgesPerLine) throw()
  60020. {
  60021. if (newNumEdgesPerLine != maxEdgesPerLine)
  60022. {
  60023. maxEdgesPerLine = newNumEdgesPerLine;
  60024. const int newLineStrideElements = maxEdgesPerLine * 2 + 1;
  60025. int* const newTable = (int*) juce_malloc ((height << (int) oversampling)
  60026. * newLineStrideElements * sizeof (int));
  60027. for (int i = 0; i < (height << (int) oversampling); ++i)
  60028. {
  60029. const int* srcLine = table + lineStrideElements * i;
  60030. int* dstLine = newTable + newLineStrideElements * i;
  60031. int num = *srcLine++;
  60032. *dstLine++ = num;
  60033. num <<= 1;
  60034. while (--num >= 0)
  60035. *dstLine++ = *srcLine++;
  60036. }
  60037. juce_free (table);
  60038. table = newTable;
  60039. lineStrideElements = newLineStrideElements;
  60040. }
  60041. }
  60042. void EdgeTable::optimiseTable() throw()
  60043. {
  60044. int maxLineElements = 0;
  60045. for (int i = height; --i >= 0;)
  60046. maxLineElements = jmax (maxLineElements,
  60047. table [i * lineStrideElements]);
  60048. remapTableForNumEdges (maxLineElements);
  60049. }
  60050. void EdgeTable::addEdgePoint (const int x, const int y, const int winding) throw()
  60051. {
  60052. jassert (y >= 0 && y < (height << oversampling))
  60053. int* lineStart = table + lineStrideElements * y;
  60054. int n = lineStart[0];
  60055. if (n >= maxEdgesPerLine)
  60056. {
  60057. remapTableForNumEdges (maxEdgesPerLine + juce_edgeTableDefaultEdgesPerLine);
  60058. lineStart = table + lineStrideElements * y;
  60059. }
  60060. n <<= 1;
  60061. int* const line = lineStart + 1;
  60062. while (n > 0)
  60063. {
  60064. const int cx = line [n - 2];
  60065. if (cx <= x)
  60066. break;
  60067. line [n] = cx;
  60068. line [n + 1] = line [n - 1];
  60069. n -= 2;
  60070. }
  60071. line [n] = x;
  60072. line [n + 1] = winding;
  60073. lineStart[0]++;
  60074. }
  60075. void EdgeTable::addPath (const Path& path,
  60076. const AffineTransform& transform) throw()
  60077. {
  60078. const int windingAmount = 256 / (1 << (int) oversampling);
  60079. const float timesOversampling = (float) (1 << (int) oversampling);
  60080. const int bottomLimit = (height << (int) oversampling);
  60081. PathFlatteningIterator iter (path, transform);
  60082. while (iter.next())
  60083. {
  60084. int y1 = roundFloatToInt (iter.y1 * timesOversampling) - (top << (int) oversampling);
  60085. int y2 = roundFloatToInt (iter.y2 * timesOversampling) - (top << (int) oversampling);
  60086. if (y1 != y2)
  60087. {
  60088. const double x1 = 256.0 * iter.x1;
  60089. const double x2 = 256.0 * iter.x2;
  60090. const double multiplier = (x2 - x1) / (y2 - y1);
  60091. const int oldY1 = y1;
  60092. int winding;
  60093. if (y1 > y2)
  60094. {
  60095. swapVariables (y1, y2);
  60096. winding = windingAmount;
  60097. }
  60098. else
  60099. {
  60100. winding = -windingAmount;
  60101. }
  60102. jassert (y1 < y2);
  60103. if (y1 < 0)
  60104. y1 = 0;
  60105. if (y2 > bottomLimit)
  60106. y2 = bottomLimit;
  60107. while (y1 < y2)
  60108. {
  60109. addEdgePoint (roundDoubleToInt (x1 + multiplier * (y1 - oldY1)),
  60110. y1,
  60111. winding);
  60112. ++y1;
  60113. }
  60114. }
  60115. }
  60116. if (! path.isUsingNonZeroWinding())
  60117. {
  60118. // if it's an alternate-winding path, we need to go through and
  60119. // make sure all the windings are alternating.
  60120. int* lineStart = table;
  60121. for (int i = height << (int) oversampling; --i >= 0;)
  60122. {
  60123. int* line = lineStart;
  60124. lineStart += lineStrideElements;
  60125. int num = *line;
  60126. while (--num >= 0)
  60127. {
  60128. line += 2;
  60129. *line = abs (*line);
  60130. if (--num >= 0)
  60131. {
  60132. line += 2;
  60133. *line = -abs (*line);
  60134. }
  60135. }
  60136. }
  60137. }
  60138. }
  60139. END_JUCE_NAMESPACE
  60140. /********* End of inlined file: juce_EdgeTable.cpp *********/
  60141. /********* Start of inlined file: juce_Graphics.cpp *********/
  60142. BEGIN_JUCE_NAMESPACE
  60143. static const Graphics::ResamplingQuality defaultQuality = Graphics::mediumResamplingQuality;
  60144. #define MINIMUM_COORD -0x3fffffff
  60145. #define MAXIMUM_COORD 0x3fffffff
  60146. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  60147. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  60148. jassert ((int) x >= MINIMUM_COORD \
  60149. && (int) x <= MAXIMUM_COORD \
  60150. && (int) y >= MINIMUM_COORD \
  60151. && (int) y <= MAXIMUM_COORD \
  60152. && (int) w >= MINIMUM_COORD \
  60153. && (int) w <= MAXIMUM_COORD \
  60154. && (int) h >= MINIMUM_COORD \
  60155. && (int) h <= MAXIMUM_COORD);
  60156. LowLevelGraphicsContext::LowLevelGraphicsContext()
  60157. {
  60158. }
  60159. LowLevelGraphicsContext::~LowLevelGraphicsContext()
  60160. {
  60161. }
  60162. Graphics::Graphics (Image& imageToDrawOnto) throw()
  60163. : context (imageToDrawOnto.createLowLevelContext()),
  60164. ownsContext (true),
  60165. state (new GraphicsState()),
  60166. saveStatePending (false)
  60167. {
  60168. }
  60169. Graphics::Graphics (LowLevelGraphicsContext* const internalContext) throw()
  60170. : context (internalContext),
  60171. ownsContext (false),
  60172. state (new GraphicsState()),
  60173. saveStatePending (false)
  60174. {
  60175. }
  60176. Graphics::~Graphics() throw()
  60177. {
  60178. delete state;
  60179. if (ownsContext)
  60180. delete context;
  60181. }
  60182. void Graphics::resetToDefaultState() throw()
  60183. {
  60184. setColour (Colours::black);
  60185. state->font.resetToDefaultState();
  60186. state->quality = defaultQuality;
  60187. }
  60188. bool Graphics::isVectorDevice() const throw()
  60189. {
  60190. return context->isVectorDevice();
  60191. }
  60192. bool Graphics::reduceClipRegion (const int x, const int y,
  60193. const int w, const int h) throw()
  60194. {
  60195. saveStateIfPending();
  60196. return context->reduceClipRegion (x, y, w, h);
  60197. }
  60198. bool Graphics::reduceClipRegion (const RectangleList& clipRegion) throw()
  60199. {
  60200. saveStateIfPending();
  60201. return context->reduceClipRegion (clipRegion);
  60202. }
  60203. void Graphics::excludeClipRegion (const int x, const int y,
  60204. const int w, const int h) throw()
  60205. {
  60206. saveStateIfPending();
  60207. context->excludeClipRegion (x, y, w, h);
  60208. }
  60209. bool Graphics::isClipEmpty() const throw()
  60210. {
  60211. return context->isClipEmpty();
  60212. }
  60213. const Rectangle Graphics::getClipBounds() const throw()
  60214. {
  60215. return context->getClipBounds();
  60216. }
  60217. void Graphics::saveState() throw()
  60218. {
  60219. saveStateIfPending();
  60220. saveStatePending = true;
  60221. }
  60222. void Graphics::restoreState() throw()
  60223. {
  60224. if (saveStatePending)
  60225. {
  60226. saveStatePending = false;
  60227. }
  60228. else
  60229. {
  60230. const int stackSize = stateStack.size();
  60231. if (stackSize > 0)
  60232. {
  60233. context->restoreState();
  60234. delete state;
  60235. state = stateStack.getUnchecked (stackSize - 1);
  60236. stateStack.removeLast (1, false);
  60237. }
  60238. else
  60239. {
  60240. // Trying to call restoreState() more times than you've called saveState() !
  60241. // Be careful to correctly match each saveState() with exactly one call to restoreState().
  60242. jassertfalse
  60243. }
  60244. }
  60245. }
  60246. void Graphics::saveStateIfPending() throw()
  60247. {
  60248. if (saveStatePending)
  60249. {
  60250. saveStatePending = false;
  60251. context->saveState();
  60252. stateStack.add (new GraphicsState (*state));
  60253. }
  60254. }
  60255. void Graphics::setOrigin (const int newOriginX,
  60256. const int newOriginY) throw()
  60257. {
  60258. saveStateIfPending();
  60259. context->setOrigin (newOriginX, newOriginY);
  60260. }
  60261. bool Graphics::clipRegionIntersects (const int x, const int y,
  60262. const int w, const int h) const throw()
  60263. {
  60264. return context->clipRegionIntersects (x, y, w, h);
  60265. }
  60266. void Graphics::setColour (const Colour& newColour) throw()
  60267. {
  60268. saveStateIfPending();
  60269. state->colour = newColour;
  60270. deleteAndZero (state->brush);
  60271. }
  60272. const Colour& Graphics::getCurrentColour() const throw()
  60273. {
  60274. return state->colour;
  60275. }
  60276. void Graphics::setOpacity (const float newOpacity) throw()
  60277. {
  60278. saveStateIfPending();
  60279. state->colour = state->colour.withAlpha (newOpacity);
  60280. }
  60281. void Graphics::setBrush (const Brush* const newBrush) throw()
  60282. {
  60283. saveStateIfPending();
  60284. delete state->brush;
  60285. if (newBrush != 0)
  60286. state->brush = newBrush->createCopy();
  60287. else
  60288. state->brush = 0;
  60289. }
  60290. Graphics::GraphicsState::GraphicsState() throw()
  60291. : colour (Colours::black),
  60292. brush (0),
  60293. quality (defaultQuality)
  60294. {
  60295. }
  60296. Graphics::GraphicsState::GraphicsState (const GraphicsState& other) throw()
  60297. : colour (other.colour),
  60298. brush (other.brush != 0 ? other.brush->createCopy() : 0),
  60299. font (other.font),
  60300. quality (other.quality)
  60301. {
  60302. }
  60303. Graphics::GraphicsState::~GraphicsState() throw()
  60304. {
  60305. delete brush;
  60306. }
  60307. void Graphics::setFont (const Font& newFont) throw()
  60308. {
  60309. saveStateIfPending();
  60310. state->font = newFont;
  60311. }
  60312. void Graphics::setFont (const float newFontHeight,
  60313. const int newFontStyleFlags) throw()
  60314. {
  60315. saveStateIfPending();
  60316. state->font.setSizeAndStyle (newFontHeight, newFontStyleFlags, 1.0f, 0.0f);
  60317. }
  60318. const Font& Graphics::getCurrentFont() const throw()
  60319. {
  60320. return state->font;
  60321. }
  60322. void Graphics::drawSingleLineText (const String& text,
  60323. const int startX,
  60324. const int baselineY) const throw()
  60325. {
  60326. if (text.isNotEmpty()
  60327. && startX < context->getClipBounds().getRight())
  60328. {
  60329. GlyphArrangement arr;
  60330. arr.addLineOfText (state->font, text, (float) startX, (float) baselineY);
  60331. arr.draw (*this);
  60332. }
  60333. }
  60334. void Graphics::drawTextAsPath (const String& text,
  60335. const AffineTransform& transform) const throw()
  60336. {
  60337. if (text.isNotEmpty())
  60338. {
  60339. GlyphArrangement arr;
  60340. arr.addLineOfText (state->font, text, 0.0f, 0.0f);
  60341. arr.draw (*this, transform);
  60342. }
  60343. }
  60344. void Graphics::drawMultiLineText (const String& text,
  60345. const int startX,
  60346. const int baselineY,
  60347. const int maximumLineWidth) const throw()
  60348. {
  60349. if (text.isNotEmpty()
  60350. && startX < context->getClipBounds().getRight())
  60351. {
  60352. GlyphArrangement arr;
  60353. arr.addJustifiedText (state->font, text,
  60354. (float) startX, (float) baselineY, (float) maximumLineWidth,
  60355. Justification::left);
  60356. arr.draw (*this);
  60357. }
  60358. }
  60359. void Graphics::drawText (const String& text,
  60360. const int x,
  60361. const int y,
  60362. const int width,
  60363. const int height,
  60364. const Justification& justificationType,
  60365. const bool useEllipsesIfTooBig) const throw()
  60366. {
  60367. if (text.isNotEmpty() && context->clipRegionIntersects (x, y, width, height))
  60368. {
  60369. GlyphArrangement arr;
  60370. arr.addCurtailedLineOfText (state->font, text,
  60371. 0.0f, 0.0f, (float)width,
  60372. useEllipsesIfTooBig);
  60373. arr.justifyGlyphs (0, arr.getNumGlyphs(),
  60374. (float) x, (float) y,
  60375. (float) width, (float) height,
  60376. justificationType);
  60377. arr.draw (*this);
  60378. }
  60379. }
  60380. void Graphics::drawFittedText (const String& text,
  60381. const int x,
  60382. const int y,
  60383. const int width,
  60384. const int height,
  60385. const Justification& justification,
  60386. const int maximumNumberOfLines,
  60387. const float minimumHorizontalScale) const throw()
  60388. {
  60389. if (text.isNotEmpty()
  60390. && width > 0 && height > 0
  60391. && context->clipRegionIntersects (x, y, width, height))
  60392. {
  60393. GlyphArrangement arr;
  60394. arr.addFittedText (state->font, text,
  60395. (float) x, (float) y,
  60396. (float) width, (float) height,
  60397. justification,
  60398. maximumNumberOfLines,
  60399. minimumHorizontalScale);
  60400. arr.draw (*this);
  60401. }
  60402. }
  60403. void Graphics::fillRect (int x,
  60404. int y,
  60405. int width,
  60406. int height) const throw()
  60407. {
  60408. // passing in a silly number can cause maths problems in rendering!
  60409. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60410. SolidColourBrush colourBrush (state->colour);
  60411. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, width, height);
  60412. }
  60413. void Graphics::fillRect (const Rectangle& r) const throw()
  60414. {
  60415. fillRect (r.getX(),
  60416. r.getY(),
  60417. r.getWidth(),
  60418. r.getHeight());
  60419. }
  60420. void Graphics::fillRect (const float x,
  60421. const float y,
  60422. const float width,
  60423. const float height) const throw()
  60424. {
  60425. // passing in a silly number can cause maths problems in rendering!
  60426. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60427. Path p;
  60428. p.addRectangle (x, y, width, height);
  60429. fillPath (p);
  60430. }
  60431. void Graphics::setPixel (int x, int y) const throw()
  60432. {
  60433. if (context->clipRegionIntersects (x, y, 1, 1))
  60434. {
  60435. SolidColourBrush colourBrush (state->colour);
  60436. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintRectangle (*context, x, y, 1, 1);
  60437. }
  60438. }
  60439. void Graphics::fillAll() const throw()
  60440. {
  60441. fillRect (context->getClipBounds());
  60442. }
  60443. void Graphics::fillAll (const Colour& colourToUse) const throw()
  60444. {
  60445. if (! colourToUse.isTransparent())
  60446. {
  60447. const Rectangle clip (context->getClipBounds());
  60448. context->fillRectWithColour (clip.getX(), clip.getY(), clip.getWidth(), clip.getHeight(),
  60449. colourToUse, false);
  60450. }
  60451. }
  60452. void Graphics::fillPath (const Path& path,
  60453. const AffineTransform& transform) const throw()
  60454. {
  60455. if ((! context->isClipEmpty()) && ! path.isEmpty())
  60456. {
  60457. SolidColourBrush colourBrush (state->colour);
  60458. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintPath (*context, path, transform);
  60459. }
  60460. }
  60461. void Graphics::strokePath (const Path& path,
  60462. const PathStrokeType& strokeType,
  60463. const AffineTransform& transform) const throw()
  60464. {
  60465. if (! state->colour.isTransparent())
  60466. {
  60467. Path stroke;
  60468. strokeType.createStrokedPath (stroke, path, transform);
  60469. fillPath (stroke);
  60470. }
  60471. }
  60472. void Graphics::drawRect (const int x,
  60473. const int y,
  60474. const int width,
  60475. const int height,
  60476. const int lineThickness) const throw()
  60477. {
  60478. // passing in a silly number can cause maths problems in rendering!
  60479. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60480. SolidColourBrush colourBrush (state->colour);
  60481. Brush& b = (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush);
  60482. b.paintRectangle (*context, x, y, width, lineThickness);
  60483. b.paintRectangle (*context, x, y + lineThickness, lineThickness, height - lineThickness * 2);
  60484. b.paintRectangle (*context, x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2);
  60485. b.paintRectangle (*context, x, y + height - lineThickness, width, lineThickness);
  60486. }
  60487. void Graphics::drawRect (const float x,
  60488. const float y,
  60489. const float width,
  60490. const float height,
  60491. const float lineThickness) const throw()
  60492. {
  60493. // passing in a silly number can cause maths problems in rendering!
  60494. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60495. Path p;
  60496. p.addRectangle (x, y, width, lineThickness);
  60497. p.addRectangle (x, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  60498. p.addRectangle (x + width - lineThickness, y + lineThickness, lineThickness, height - lineThickness * 2.0f);
  60499. p.addRectangle (x, y + height - lineThickness, width, lineThickness);
  60500. fillPath (p);
  60501. }
  60502. void Graphics::drawRect (const Rectangle& r,
  60503. const int lineThickness) const throw()
  60504. {
  60505. drawRect (r.getX(), r.getY(),
  60506. r.getWidth(), r.getHeight(),
  60507. lineThickness);
  60508. }
  60509. void Graphics::drawBevel (const int x,
  60510. const int y,
  60511. const int width,
  60512. const int height,
  60513. const int bevelThickness,
  60514. const Colour& topLeftColour,
  60515. const Colour& bottomRightColour,
  60516. const bool useGradient) const throw()
  60517. {
  60518. // passing in a silly number can cause maths problems in rendering!
  60519. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60520. if (clipRegionIntersects (x, y, width, height))
  60521. {
  60522. const float oldOpacity = state->colour.getFloatAlpha();
  60523. const float ramp = oldOpacity / bevelThickness;
  60524. for (int i = bevelThickness; --i >= 0;)
  60525. {
  60526. const float op = useGradient ? ramp * (bevelThickness - i)
  60527. : oldOpacity;
  60528. context->fillRectWithColour (x + i, y + i, width - i * 2, 1, topLeftColour.withMultipliedAlpha (op), false);
  60529. context->fillRectWithColour (x + i, y + i + 1, 1, height - i * 2 - 2, topLeftColour.withMultipliedAlpha (op * 0.75f), false);
  60530. context->fillRectWithColour (x + i, y + height - i - 1, width - i * 2, 1, bottomRightColour.withMultipliedAlpha (op), false);
  60531. context->fillRectWithColour (x + width - i - 1, y + i + 1, 1, height - i * 2 - 2, bottomRightColour.withMultipliedAlpha (op * 0.75f), false);
  60532. }
  60533. }
  60534. }
  60535. void Graphics::fillEllipse (const float x,
  60536. const float y,
  60537. const float width,
  60538. const float height) const throw()
  60539. {
  60540. // passing in a silly number can cause maths problems in rendering!
  60541. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60542. Path p;
  60543. p.addEllipse (x, y, width, height);
  60544. fillPath (p);
  60545. }
  60546. void Graphics::drawEllipse (const float x,
  60547. const float y,
  60548. const float width,
  60549. const float height,
  60550. const float lineThickness) const throw()
  60551. {
  60552. // passing in a silly number can cause maths problems in rendering!
  60553. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60554. Path p;
  60555. p.addEllipse (x, y, width, height);
  60556. strokePath (p, PathStrokeType (lineThickness));
  60557. }
  60558. void Graphics::fillRoundedRectangle (const float x,
  60559. const float y,
  60560. const float width,
  60561. const float height,
  60562. const float cornerSize) const throw()
  60563. {
  60564. // passing in a silly number can cause maths problems in rendering!
  60565. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60566. Path p;
  60567. p.addRoundedRectangle (x, y, width, height, cornerSize);
  60568. fillPath (p);
  60569. }
  60570. void Graphics::fillRoundedRectangle (const Rectangle& r,
  60571. const float cornerSize) const throw()
  60572. {
  60573. fillRoundedRectangle ((float) r.getX(),
  60574. (float) r.getY(),
  60575. (float) r.getWidth(),
  60576. (float) r.getHeight(),
  60577. cornerSize);
  60578. }
  60579. void Graphics::drawRoundedRectangle (const float x,
  60580. const float y,
  60581. const float width,
  60582. const float height,
  60583. const float cornerSize,
  60584. const float lineThickness) const throw()
  60585. {
  60586. // passing in a silly number can cause maths problems in rendering!
  60587. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, width, height);
  60588. Path p;
  60589. p.addRoundedRectangle (x, y, width, height, cornerSize);
  60590. strokePath (p, PathStrokeType (lineThickness));
  60591. }
  60592. void Graphics::drawRoundedRectangle (const Rectangle& r,
  60593. const float cornerSize,
  60594. const float lineThickness) const throw()
  60595. {
  60596. drawRoundedRectangle ((float) r.getX(),
  60597. (float) r.getY(),
  60598. (float) r.getWidth(),
  60599. (float) r.getHeight(),
  60600. cornerSize, lineThickness);
  60601. }
  60602. void Graphics::drawArrow (const float startX,
  60603. const float startY,
  60604. const float endX,
  60605. const float endY,
  60606. const float lineThickness,
  60607. const float arrowheadWidth,
  60608. const float arrowheadLength) const throw()
  60609. {
  60610. Path p;
  60611. p.addArrow (startX, startY, endX, endY,
  60612. lineThickness, arrowheadWidth, arrowheadLength);
  60613. fillPath (p);
  60614. }
  60615. void Graphics::fillCheckerBoard (int x, int y,
  60616. int width, int height,
  60617. const int checkWidth,
  60618. const int checkHeight,
  60619. const Colour& colour1,
  60620. const Colour& colour2) const throw()
  60621. {
  60622. jassert (checkWidth > 0 && checkHeight > 0); // can't be zero or less!
  60623. if (checkWidth > 0 && checkHeight > 0)
  60624. {
  60625. if (colour1 == colour2)
  60626. {
  60627. context->fillRectWithColour (x, y, width, height, colour1, false);
  60628. }
  60629. else
  60630. {
  60631. const Rectangle clip (context->getClipBounds());
  60632. const int right = jmin (x + width, clip.getRight());
  60633. const int bottom = jmin (y + height, clip.getBottom());
  60634. int cy = 0;
  60635. while (y < bottom)
  60636. {
  60637. int cx = cy;
  60638. for (int xx = x; xx < right; xx += checkWidth)
  60639. context->fillRectWithColour (xx, y,
  60640. jmin (checkWidth, right - xx),
  60641. jmin (checkHeight, bottom - y),
  60642. ((cx++ & 1) == 0) ? colour1 : colour2,
  60643. false);
  60644. ++cy;
  60645. y += checkHeight;
  60646. }
  60647. }
  60648. }
  60649. }
  60650. void Graphics::drawVerticalLine (const int x, float top, float bottom) const throw()
  60651. {
  60652. SolidColourBrush colourBrush (state->colour);
  60653. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintVerticalLine (*context, x, top, bottom);
  60654. }
  60655. void Graphics::drawHorizontalLine (const int y, float left, float right) const throw()
  60656. {
  60657. SolidColourBrush colourBrush (state->colour);
  60658. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintHorizontalLine (*context, y, left, right);
  60659. }
  60660. void Graphics::drawLine (float x1, float y1,
  60661. float x2, float y2) const throw()
  60662. {
  60663. if (! context->isClipEmpty())
  60664. {
  60665. SolidColourBrush colourBrush (state->colour);
  60666. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintLine (*context, x1, y1, x2, y2);
  60667. }
  60668. }
  60669. void Graphics::drawLine (const float startX,
  60670. const float startY,
  60671. const float endX,
  60672. const float endY,
  60673. const float lineThickness) const throw()
  60674. {
  60675. Path p;
  60676. p.addLineSegment (startX, startY, endX, endY, lineThickness);
  60677. fillPath (p);
  60678. }
  60679. void Graphics::drawLine (const Line& line) const throw()
  60680. {
  60681. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY());
  60682. }
  60683. void Graphics::drawLine (const Line& line,
  60684. const float lineThickness) const throw()
  60685. {
  60686. drawLine (line.getStartX(), line.getStartY(), line.getEndX(), line.getEndY(), lineThickness);
  60687. }
  60688. void Graphics::drawDashedLine (const float startX,
  60689. const float startY,
  60690. const float endX,
  60691. const float endY,
  60692. const float* const dashLengths,
  60693. const int numDashLengths,
  60694. const float lineThickness) const throw()
  60695. {
  60696. const double dx = endX - startX;
  60697. const double dy = endY - startY;
  60698. const double totalLen = juce_hypot (dx, dy);
  60699. if (totalLen >= 0.5)
  60700. {
  60701. const double onePixAlpha = 1.0 / totalLen;
  60702. double alpha = 0.0;
  60703. float x = startX;
  60704. float y = startY;
  60705. int n = 0;
  60706. while (alpha < 1.0f)
  60707. {
  60708. alpha = jmin (1.0, alpha + dashLengths[n++] * onePixAlpha);
  60709. n = n % numDashLengths;
  60710. const float oldX = x;
  60711. const float oldY = y;
  60712. x = (float) (startX + dx * alpha);
  60713. y = (float) (startY + dy * alpha);
  60714. if ((n & 1) != 0)
  60715. {
  60716. if (lineThickness != 1.0f)
  60717. drawLine (oldX, oldY, x, y, lineThickness);
  60718. else
  60719. drawLine (oldX, oldY, x, y);
  60720. }
  60721. }
  60722. }
  60723. }
  60724. void Graphics::setImageResamplingQuality (const Graphics::ResamplingQuality newQuality) throw()
  60725. {
  60726. saveStateIfPending();
  60727. state->quality = newQuality;
  60728. }
  60729. void Graphics::drawImageAt (const Image* const imageToDraw,
  60730. const int topLeftX,
  60731. const int topLeftY,
  60732. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60733. {
  60734. if (imageToDraw != 0)
  60735. {
  60736. const int imageW = imageToDraw->getWidth();
  60737. const int imageH = imageToDraw->getHeight();
  60738. drawImage (imageToDraw,
  60739. topLeftX, topLeftY, imageW, imageH,
  60740. 0, 0, imageW, imageH,
  60741. fillAlphaChannelWithCurrentBrush);
  60742. }
  60743. }
  60744. void Graphics::drawImageWithin (const Image* const imageToDraw,
  60745. const int destX,
  60746. const int destY,
  60747. const int destW,
  60748. const int destH,
  60749. const RectanglePlacement& placementWithinTarget,
  60750. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60751. {
  60752. // passing in a silly number can cause maths problems in rendering!
  60753. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (destX, destY, destW, destH);
  60754. if (imageToDraw != 0)
  60755. {
  60756. const int imageW = imageToDraw->getWidth();
  60757. const int imageH = imageToDraw->getHeight();
  60758. if (imageW > 0 && imageH > 0)
  60759. {
  60760. double newX = 0.0, newY = 0.0;
  60761. double newW = imageW;
  60762. double newH = imageH;
  60763. placementWithinTarget.applyTo (newX, newY, newW, newH,
  60764. destX, destY, destW, destH);
  60765. if (newW > 0 && newH > 0)
  60766. {
  60767. drawImage (imageToDraw,
  60768. roundDoubleToInt (newX), roundDoubleToInt (newY),
  60769. roundDoubleToInt (newW), roundDoubleToInt (newH),
  60770. 0, 0, imageW, imageH,
  60771. fillAlphaChannelWithCurrentBrush);
  60772. }
  60773. }
  60774. }
  60775. }
  60776. void Graphics::drawImage (const Image* const imageToDraw,
  60777. int dx, int dy, int dw, int dh,
  60778. int sx, int sy, int sw, int sh,
  60779. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60780. {
  60781. // passing in a silly number can cause maths problems in rendering!
  60782. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (dx, dy, dw, dh);
  60783. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (sx, sy, sw, sh);
  60784. if (imageToDraw == 0 || ! context->clipRegionIntersects (dx, dy, dw, dh))
  60785. return;
  60786. if (sw == dw && sh == dh)
  60787. {
  60788. if (sx < 0)
  60789. {
  60790. dx -= sx;
  60791. dw += sx;
  60792. sw += sx;
  60793. sx = 0;
  60794. }
  60795. if (sx + sw > imageToDraw->getWidth())
  60796. {
  60797. const int amount = sx + sw - imageToDraw->getWidth();
  60798. dw -= amount;
  60799. sw -= amount;
  60800. }
  60801. if (sy < 0)
  60802. {
  60803. dy -= sy;
  60804. dh += sy;
  60805. sh += sy;
  60806. sy = 0;
  60807. }
  60808. if (sy + sh > imageToDraw->getHeight())
  60809. {
  60810. const int amount = sy + sh - imageToDraw->getHeight();
  60811. dh -= amount;
  60812. sh -= amount;
  60813. }
  60814. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  60815. return;
  60816. if (fillAlphaChannelWithCurrentBrush)
  60817. {
  60818. SolidColourBrush colourBrush (state->colour);
  60819. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  60820. .paintAlphaChannel (*context, *imageToDraw,
  60821. dx - sx, dy - sy,
  60822. dx, dy,
  60823. dw, dh);
  60824. }
  60825. else
  60826. {
  60827. context->blendImage (*imageToDraw,
  60828. dx, dy, dw, dh, sx, sy,
  60829. state->colour.getFloatAlpha());
  60830. }
  60831. }
  60832. else
  60833. {
  60834. if (dw <= 0 || dh <= 0 || sw <= 0 || sh <= 0)
  60835. return;
  60836. if (fillAlphaChannelWithCurrentBrush)
  60837. {
  60838. if (imageToDraw->isRGB())
  60839. {
  60840. fillRect (dx, dy, dw, dh);
  60841. }
  60842. else
  60843. {
  60844. int tx = dx;
  60845. int ty = dy;
  60846. int tw = dw;
  60847. int th = dh;
  60848. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  60849. {
  60850. Image temp (imageToDraw->getFormat(), tw, th, true);
  60851. Graphics g (temp);
  60852. g.setImageResamplingQuality (state->quality);
  60853. g.setOrigin (dx - tx, dy - ty);
  60854. g.drawImage (imageToDraw,
  60855. 0, 0, dw, dh,
  60856. sx, sy, sw, sh,
  60857. false);
  60858. SolidColourBrush colourBrush (state->colour);
  60859. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush)
  60860. .paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  60861. }
  60862. }
  60863. }
  60864. else
  60865. {
  60866. context->blendImageRescaling (*imageToDraw,
  60867. dx, dy, dw, dh,
  60868. sx, sy, sw, sh,
  60869. state->colour.getFloatAlpha(),
  60870. state->quality);
  60871. }
  60872. }
  60873. }
  60874. void Graphics::drawImageTransformed (const Image* const imageToDraw,
  60875. int sourceClipX,
  60876. int sourceClipY,
  60877. int sourceClipWidth,
  60878. int sourceClipHeight,
  60879. const AffineTransform& transform,
  60880. const bool fillAlphaChannelWithCurrentBrush) const throw()
  60881. {
  60882. if (imageToDraw != 0
  60883. && (! context->isClipEmpty())
  60884. && ! transform.isSingularity())
  60885. {
  60886. if (fillAlphaChannelWithCurrentBrush)
  60887. {
  60888. Path p;
  60889. p.addRectangle ((float) sourceClipX, (float) sourceClipY,
  60890. (float) sourceClipWidth, (float) sourceClipHeight);
  60891. p.applyTransform (transform);
  60892. float dx, dy, dw, dh;
  60893. p.getBounds (dx, dy, dw, dh);
  60894. int tx = (int) dx;
  60895. int ty = (int) dy;
  60896. int tw = roundFloatToInt (dw) + 2;
  60897. int th = roundFloatToInt (dh) + 2;
  60898. if (context->getClipBounds().intersectRectangle (tx, ty, tw, th))
  60899. {
  60900. Image temp (imageToDraw->getFormat(), tw, th, true);
  60901. Graphics g (temp);
  60902. g.setImageResamplingQuality (state->quality);
  60903. g.drawImageTransformed (imageToDraw,
  60904. sourceClipX,
  60905. sourceClipY,
  60906. sourceClipWidth,
  60907. sourceClipHeight,
  60908. transform.translated ((float) -tx, (float) -ty),
  60909. false);
  60910. SolidColourBrush colourBrush (state->colour);
  60911. (state->brush != 0 ? *(state->brush) : (Brush&) colourBrush).paintAlphaChannel (*context, temp, tx, ty, tx, ty, tw, th);
  60912. }
  60913. }
  60914. else
  60915. {
  60916. context->blendImageWarping (*imageToDraw,
  60917. sourceClipX,
  60918. sourceClipY,
  60919. sourceClipWidth,
  60920. sourceClipHeight,
  60921. transform,
  60922. state->colour.getFloatAlpha(),
  60923. state->quality);
  60924. }
  60925. }
  60926. }
  60927. END_JUCE_NAMESPACE
  60928. /********* End of inlined file: juce_Graphics.cpp *********/
  60929. /********* Start of inlined file: juce_Justification.cpp *********/
  60930. BEGIN_JUCE_NAMESPACE
  60931. Justification::Justification (const Justification& other) throw()
  60932. : flags (other.flags)
  60933. {
  60934. }
  60935. const Justification& Justification::operator= (const Justification& other) throw()
  60936. {
  60937. flags = other.flags;
  60938. return *this;
  60939. }
  60940. int Justification::getOnlyVerticalFlags() const throw()
  60941. {
  60942. return flags & (top | bottom | verticallyCentred);
  60943. }
  60944. int Justification::getOnlyHorizontalFlags() const throw()
  60945. {
  60946. return flags & (left | right | horizontallyCentred | horizontallyJustified);
  60947. }
  60948. void Justification::applyToRectangle (int& x, int& y,
  60949. const int w, const int h,
  60950. const int spaceX, const int spaceY,
  60951. const int spaceW, const int spaceH) const throw()
  60952. {
  60953. if ((flags & horizontallyCentred) != 0)
  60954. {
  60955. x = spaceX + ((spaceW - w) >> 1);
  60956. }
  60957. else if ((flags & right) != 0)
  60958. {
  60959. x = spaceX + spaceW - w;
  60960. }
  60961. else
  60962. {
  60963. x = spaceX;
  60964. }
  60965. if ((flags & verticallyCentred) != 0)
  60966. {
  60967. y = spaceY + ((spaceH - h) >> 1);
  60968. }
  60969. else if ((flags & bottom) != 0)
  60970. {
  60971. y = spaceY + spaceH - h;
  60972. }
  60973. else
  60974. {
  60975. y = spaceY;
  60976. }
  60977. }
  60978. END_JUCE_NAMESPACE
  60979. /********* End of inlined file: juce_Justification.cpp *********/
  60980. /********* Start of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  60981. BEGIN_JUCE_NAMESPACE
  60982. #if JUCE_MSVC
  60983. #pragma warning (disable: 4996) // deprecated sprintf warning
  60984. #endif
  60985. // this will throw an assertion if you try to draw something that's not
  60986. // possible in postscript
  60987. #define WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS 0
  60988. #if defined (JUCE_DEBUG) && WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS
  60989. #define notPossibleInPostscriptAssert jassertfalse
  60990. #else
  60991. #define notPossibleInPostscriptAssert
  60992. #endif
  60993. LowLevelGraphicsPostScriptRenderer::LowLevelGraphicsPostScriptRenderer (OutputStream& resultingPostScript,
  60994. const String& documentTitle,
  60995. const int totalWidth_,
  60996. const int totalHeight_)
  60997. : out (resultingPostScript),
  60998. totalWidth (totalWidth_),
  60999. totalHeight (totalHeight_),
  61000. xOffset (0),
  61001. yOffset (0),
  61002. needToClip (true)
  61003. {
  61004. clip = new RectangleList (Rectangle (0, 0, totalWidth_, totalHeight_));
  61005. const float scale = jmin ((520.0f / totalWidth_), (750.0f / totalHeight));
  61006. out << "%!PS-Adobe-3.0 EPSF-3.0"
  61007. "\n%%BoundingBox: 0 0 600 824"
  61008. "\n%%Pages: 0"
  61009. "\n%%Creator: Raw Material Software JUCE"
  61010. "\n%%Title: " << documentTitle <<
  61011. "\n%%CreationDate: none"
  61012. "\n%%LanguageLevel: 2"
  61013. "\n%%EndComments"
  61014. "\n%%BeginProlog"
  61015. "\n%%BeginResource: JRes"
  61016. "\n/bd {bind def} bind def"
  61017. "\n/c {setrgbcolor} bd"
  61018. "\n/m {moveto} bd"
  61019. "\n/l {lineto} bd"
  61020. "\n/rl {rlineto} bd"
  61021. "\n/ct {curveto} bd"
  61022. "\n/cp {closepath} bd"
  61023. "\n/pr {3 index 3 index moveto 1 index 0 rlineto 0 1 index rlineto pop neg 0 rlineto pop pop closepath} bd"
  61024. "\n/doclip {initclip newpath} bd"
  61025. "\n/endclip {clip newpath} bd"
  61026. "\n%%EndResource"
  61027. "\n%%EndProlog"
  61028. "\n%%BeginSetup"
  61029. "\n%%EndSetup"
  61030. "\n%%Page: 1 1"
  61031. "\n%%BeginPageSetup"
  61032. "\n%%EndPageSetup\n\n"
  61033. << "40 800 translate\n"
  61034. << scale << ' ' << scale << " scale\n\n";
  61035. }
  61036. LowLevelGraphicsPostScriptRenderer::~LowLevelGraphicsPostScriptRenderer()
  61037. {
  61038. delete clip;
  61039. }
  61040. bool LowLevelGraphicsPostScriptRenderer::isVectorDevice() const
  61041. {
  61042. return true;
  61043. }
  61044. void LowLevelGraphicsPostScriptRenderer::setOrigin (int x, int y)
  61045. {
  61046. if (x != 0 || y != 0)
  61047. {
  61048. xOffset += x;
  61049. yOffset += y;
  61050. needToClip = true;
  61051. }
  61052. }
  61053. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (int x, int y, int w, int h)
  61054. {
  61055. needToClip = true;
  61056. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  61057. }
  61058. bool LowLevelGraphicsPostScriptRenderer::reduceClipRegion (const RectangleList& clipRegion)
  61059. {
  61060. needToClip = true;
  61061. return clip->clipTo (clipRegion);
  61062. }
  61063. void LowLevelGraphicsPostScriptRenderer::excludeClipRegion (int x, int y, int w, int h)
  61064. {
  61065. needToClip = true;
  61066. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  61067. }
  61068. bool LowLevelGraphicsPostScriptRenderer::clipRegionIntersects (int x, int y, int w, int h)
  61069. {
  61070. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  61071. }
  61072. const Rectangle LowLevelGraphicsPostScriptRenderer::getClipBounds() const
  61073. {
  61074. return clip->getBounds().translated (-xOffset, -yOffset);
  61075. }
  61076. bool LowLevelGraphicsPostScriptRenderer::isClipEmpty() const
  61077. {
  61078. return clip->isEmpty();
  61079. }
  61080. LowLevelGraphicsPostScriptRenderer::SavedState::SavedState (RectangleList* const clip_,
  61081. const int xOffset_, const int yOffset_)
  61082. : clip (clip_),
  61083. xOffset (xOffset_),
  61084. yOffset (yOffset_)
  61085. {
  61086. }
  61087. LowLevelGraphicsPostScriptRenderer::SavedState::~SavedState()
  61088. {
  61089. delete clip;
  61090. }
  61091. void LowLevelGraphicsPostScriptRenderer::saveState()
  61092. {
  61093. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  61094. }
  61095. void LowLevelGraphicsPostScriptRenderer::restoreState()
  61096. {
  61097. SavedState* const top = stateStack.getLast();
  61098. if (top != 0)
  61099. {
  61100. clip->swapWith (*top->clip);
  61101. xOffset = top->xOffset;
  61102. yOffset = top->yOffset;
  61103. stateStack.removeLast();
  61104. needToClip = true;
  61105. }
  61106. else
  61107. {
  61108. jassertfalse // trying to pop with an empty stack!
  61109. }
  61110. }
  61111. void LowLevelGraphicsPostScriptRenderer::writeClip()
  61112. {
  61113. if (needToClip)
  61114. {
  61115. needToClip = false;
  61116. out << "doclip ";
  61117. int itemsOnLine = 0;
  61118. for (RectangleList::Iterator i (*clip); i.next();)
  61119. {
  61120. if (++itemsOnLine == 6)
  61121. {
  61122. itemsOnLine = 0;
  61123. out << '\n';
  61124. }
  61125. const Rectangle& r = *i.getRectangle();
  61126. out << r.getX() << ' ' << -r.getY() << ' '
  61127. << r.getWidth() << ' ' << -r.getHeight() << " pr ";
  61128. }
  61129. out << "endclip\n";
  61130. }
  61131. }
  61132. void LowLevelGraphicsPostScriptRenderer::writeColour (const Colour& colour)
  61133. {
  61134. Colour c (Colours::white.overlaidWith (colour));
  61135. if (lastColour != c)
  61136. {
  61137. lastColour = c;
  61138. out << String (c.getFloatRed(), 3) << ' '
  61139. << String (c.getFloatGreen(), 3) << ' '
  61140. << String (c.getFloatBlue(), 3) << " c\n";
  61141. }
  61142. }
  61143. void LowLevelGraphicsPostScriptRenderer::writeXY (const float x, const float y) const
  61144. {
  61145. out << String (x, 2) << ' '
  61146. << String (-y, 2) << ' ';
  61147. }
  61148. void LowLevelGraphicsPostScriptRenderer::writePath (const Path& path) const
  61149. {
  61150. out << "newpath ";
  61151. float lastX = 0.0f;
  61152. float lastY = 0.0f;
  61153. int itemsOnLine = 0;
  61154. Path::Iterator i (path);
  61155. while (i.next())
  61156. {
  61157. if (++itemsOnLine == 4)
  61158. {
  61159. itemsOnLine = 0;
  61160. out << '\n';
  61161. }
  61162. switch (i.elementType)
  61163. {
  61164. case Path::Iterator::startNewSubPath:
  61165. writeXY (i.x1, i.y1);
  61166. lastX = i.x1;
  61167. lastY = i.y1;
  61168. out << "m ";
  61169. break;
  61170. case Path::Iterator::lineTo:
  61171. writeXY (i.x1, i.y1);
  61172. lastX = i.x1;
  61173. lastY = i.y1;
  61174. out << "l ";
  61175. break;
  61176. case Path::Iterator::quadraticTo:
  61177. {
  61178. const float cp1x = lastX + (i.x1 - lastX) * 2.0f / 3.0f;
  61179. const float cp1y = lastY + (i.y1 - lastY) * 2.0f / 3.0f;
  61180. const float cp2x = cp1x + (i.x2 - lastX) / 3.0f;
  61181. const float cp2y = cp1y + (i.y2 - lastY) / 3.0f;
  61182. writeXY (cp1x, cp1y);
  61183. writeXY (cp2x, cp2y);
  61184. writeXY (i.x2, i.y2);
  61185. out << "ct ";
  61186. lastX = i.x2;
  61187. lastY = i.y2;
  61188. }
  61189. break;
  61190. case Path::Iterator::cubicTo:
  61191. writeXY (i.x1, i.y1);
  61192. writeXY (i.x2, i.y2);
  61193. writeXY (i.x3, i.y3);
  61194. out << "ct ";
  61195. lastX = i.x3;
  61196. lastY = i.y3;
  61197. break;
  61198. case Path::Iterator::closePath:
  61199. out << "cp ";
  61200. break;
  61201. default:
  61202. jassertfalse
  61203. break;
  61204. }
  61205. }
  61206. out << '\n';
  61207. }
  61208. void LowLevelGraphicsPostScriptRenderer::writeTransform (const AffineTransform& trans) const
  61209. {
  61210. out << "[ "
  61211. << trans.mat00 << ' '
  61212. << trans.mat10 << ' '
  61213. << trans.mat01 << ' '
  61214. << trans.mat11 << ' '
  61215. << trans.mat02 << ' '
  61216. << trans.mat12 << " ] concat ";
  61217. }
  61218. void LowLevelGraphicsPostScriptRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool /*replaceExistingContents*/)
  61219. {
  61220. writeClip();
  61221. writeColour (colour);
  61222. x += xOffset;
  61223. y += yOffset;
  61224. out << x << ' ' << -(y + h) << ' ' << w << ' ' << h << " rectfill\n";
  61225. }
  61226. void LowLevelGraphicsPostScriptRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  61227. {
  61228. Path p;
  61229. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  61230. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_256times);
  61231. }
  61232. void LowLevelGraphicsPostScriptRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  61233. const Colour& colour, EdgeTable::OversamplingLevel /*quality*/)
  61234. {
  61235. writeClip();
  61236. Path p (path);
  61237. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  61238. writePath (p);
  61239. writeColour (colour);
  61240. out << "fill\n";
  61241. }
  61242. void LowLevelGraphicsPostScriptRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel /*quality*/)
  61243. {
  61244. // this doesn't work correctly yet - it could be improved to handle solid gradients, but
  61245. // postscript can't do semi-transparent ones.
  61246. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  61247. writeClip();
  61248. out << "gsave ";
  61249. {
  61250. Path p (path);
  61251. p.applyTransform (t.translated ((float) xOffset, (float) yOffset));
  61252. writePath (p);
  61253. out << "clip\n";
  61254. }
  61255. int numColours = 256;
  61256. PixelARGB* const colours = gradient.createLookupTable (numColours);
  61257. for (int i = numColours; --i >= 0;)
  61258. colours[i].unpremultiply();
  61259. const Rectangle bounds (clip->getBounds());
  61260. // ideally this would draw lots of lines or ellipses to approximate the gradient, but for the
  61261. // time-being, this just fills it with the average colour..
  61262. writeColour (Colour (colours [numColours / 2].getARGB()));
  61263. out << bounds.getX() << ' ' << -bounds.getBottom() << ' ' << bounds.getWidth() << ' ' << bounds.getHeight() << " rectfill\n";
  61264. juce_free (colours);
  61265. out << "grestore\n";
  61266. }
  61267. void LowLevelGraphicsPostScriptRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  61268. const Image& sourceImage,
  61269. int imageX, int imageY,
  61270. float opacity, EdgeTable::OversamplingLevel /*quality*/)
  61271. {
  61272. writeClip();
  61273. out << "gsave ";
  61274. Path p (path);
  61275. p.applyTransform (transform.translated ((float) xOffset, (float) yOffset));
  61276. writePath (p);
  61277. out << "clip\n";
  61278. blendImage (sourceImage, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight(), 0, 0, opacity);
  61279. out << "grestore\n";
  61280. }
  61281. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithColour (const Image& /*clipImage*/, int x, int y, const Colour& colour)
  61282. {
  61283. x += xOffset;
  61284. y += yOffset;
  61285. writeClip();
  61286. writeColour (colour);
  61287. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  61288. }
  61289. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithGradient (const Image& /*alphaChannelImage*/, int imageX, int imageY, const ColourGradient& /*gradient*/)
  61290. {
  61291. imageX += xOffset;
  61292. imageY += yOffset;
  61293. writeClip();
  61294. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  61295. }
  61296. void LowLevelGraphicsPostScriptRenderer::fillAlphaChannelWithImage (const Image& /*alphaImage*/, int alphaImageX, int alphaImageY,
  61297. const Image& /*fillerImage*/, int fillerImageX, int fillerImageY, float /*opacity*/)
  61298. {
  61299. alphaImageX += xOffset;
  61300. alphaImageY += yOffset;
  61301. fillerImageX += xOffset;
  61302. fillerImageY += yOffset;
  61303. writeClip();
  61304. notPossibleInPostscriptAssert // you can disable this warning by setting the WARN_ABOUT_NON_POSTSCRIPT_OPERATIONS flag at the top of this file
  61305. }
  61306. void LowLevelGraphicsPostScriptRenderer::blendImageRescaling (const Image& sourceImage,
  61307. int dx, int dy, int dw, int dh,
  61308. int sx, int sy, int sw, int sh,
  61309. float alpha,
  61310. const Graphics::ResamplingQuality quality)
  61311. {
  61312. if (sw > 0 && sh > 0)
  61313. {
  61314. jassert (sx >= 0 && sx + sw <= sourceImage.getWidth());
  61315. jassert (sy >= 0 && sy + sh <= sourceImage.getHeight());
  61316. if (sw == dw && sh == dh)
  61317. {
  61318. blendImage (sourceImage,
  61319. dx, dy, dw, dh,
  61320. sx, sy, alpha);
  61321. }
  61322. else
  61323. {
  61324. blendImageWarping (sourceImage,
  61325. sx, sy, sw, sh,
  61326. AffineTransform::scale (dw / (float) sw,
  61327. dh / (float) sh)
  61328. .translated ((float) (dx - sx),
  61329. (float) (dy - sy)),
  61330. alpha,
  61331. quality);
  61332. }
  61333. }
  61334. }
  61335. void LowLevelGraphicsPostScriptRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  61336. {
  61337. blendImageWarping (sourceImage,
  61338. sx, sy, dw, dh,
  61339. AffineTransform::translation ((float) dx, (float) dy),
  61340. opacity, Graphics::highResamplingQuality);
  61341. }
  61342. void LowLevelGraphicsPostScriptRenderer::writeImage (const Image& im,
  61343. const int sx, const int sy,
  61344. const int maxW, const int maxH) const
  61345. {
  61346. out << "{<\n";
  61347. const int w = jmin (maxW, im.getWidth());
  61348. const int h = jmin (maxH, im.getHeight());
  61349. int charsOnLine = 0;
  61350. int lineStride, pixelStride;
  61351. const uint8* data = im.lockPixelDataReadOnly (0, 0, w, h, lineStride, pixelStride);
  61352. Colour pixel;
  61353. for (int y = h; --y >= 0;)
  61354. {
  61355. for (int x = 0; x < w; ++x)
  61356. {
  61357. const uint8* pixelData = data + lineStride * y + pixelStride * x;
  61358. if (x >= sx && y >= sy)
  61359. {
  61360. if (im.isARGB())
  61361. {
  61362. PixelARGB p (*(const PixelARGB*) pixelData);
  61363. p.unpremultiply();
  61364. pixel = Colours::white.overlaidWith (Colour (p.getARGB()));
  61365. }
  61366. else if (im.isRGB())
  61367. {
  61368. pixel = Colour (((const PixelRGB*) pixelData)->getARGB());
  61369. }
  61370. else
  61371. {
  61372. pixel = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixelData);
  61373. }
  61374. }
  61375. else
  61376. {
  61377. pixel = Colours::transparentWhite;
  61378. }
  61379. char colourString [16];
  61380. sprintf (colourString, "%x%x%x", pixel.getRed(), pixel.getGreen(), pixel.getBlue());
  61381. out << (const char*) colourString;
  61382. charsOnLine += 3;
  61383. if (charsOnLine > 100)
  61384. {
  61385. out << '\n';
  61386. charsOnLine = 0;
  61387. }
  61388. }
  61389. }
  61390. im.releasePixelDataReadOnly (data);
  61391. out << "\n>}\n";
  61392. }
  61393. void LowLevelGraphicsPostScriptRenderer::blendImageWarping (const Image& sourceImage,
  61394. int srcClipX, int srcClipY,
  61395. int srcClipW, int srcClipH,
  61396. const AffineTransform& t,
  61397. float /*opacity*/,
  61398. const Graphics::ResamplingQuality /*quality*/)
  61399. {
  61400. const int w = jmin (sourceImage.getWidth(), srcClipX + srcClipW);
  61401. const int h = jmin (sourceImage.getHeight(), srcClipY + srcClipH);
  61402. writeClip();
  61403. out << "gsave ";
  61404. writeTransform (t.translated ((float) xOffset, (float) yOffset)
  61405. .scaled (1.0f, -1.0f));
  61406. RectangleList imageClip;
  61407. sourceImage.createSolidAreaMask (imageClip, 0.5f);
  61408. imageClip.clipTo (Rectangle (srcClipX, srcClipY, srcClipW, srcClipH));
  61409. out << "newpath ";
  61410. int itemsOnLine = 0;
  61411. for (RectangleList::Iterator i (imageClip); i.next();)
  61412. {
  61413. if (++itemsOnLine == 6)
  61414. {
  61415. out << '\n';
  61416. itemsOnLine = 0;
  61417. }
  61418. const Rectangle& r = *i.getRectangle();
  61419. out << r.getX() << ' ' << r.getY() << ' ' << r.getWidth() << ' ' << r.getHeight() << " pr ";
  61420. }
  61421. out << " clip newpath\n";
  61422. out << w << ' ' << h << " scale\n";
  61423. out << w << ' ' << h << " 8 [" << w << " 0 0 -" << h << ' ' << (int) 0 << ' ' << h << " ]\n";
  61424. writeImage (sourceImage, srcClipX, srcClipY, srcClipW, srcClipH);
  61425. out << "false 3 colorimage grestore\n";
  61426. needToClip = true;
  61427. }
  61428. void LowLevelGraphicsPostScriptRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  61429. {
  61430. Path p;
  61431. p.addLineSegment ((float) x1, (float) y1, (float) x2, (float) y2, 1.0f);
  61432. fillPathWithColour (p, AffineTransform::identity, colour, EdgeTable::Oversampling_256times);
  61433. }
  61434. void LowLevelGraphicsPostScriptRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  61435. {
  61436. drawLine (x, top, x, bottom, col);
  61437. }
  61438. void LowLevelGraphicsPostScriptRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  61439. {
  61440. drawLine (left, y, right, y, col);
  61441. }
  61442. END_JUCE_NAMESPACE
  61443. /********* End of inlined file: juce_LowLevelGraphicsPostScriptRenderer.cpp *********/
  61444. /********* Start of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  61445. BEGIN_JUCE_NAMESPACE
  61446. #if ! (defined (JUCE_MAC) || (defined (JUCE_WIN32) && defined (JUCE_64BIT)))
  61447. #define JUCE_USE_SSE_INSTRUCTIONS 1
  61448. #endif
  61449. #if defined (JUCE_DEBUG) && JUCE_MSVC
  61450. #pragma warning (disable: 4714)
  61451. #endif
  61452. #define MINIMUM_COORD -0x3fffffff
  61453. #define MAXIMUM_COORD 0x3fffffff
  61454. #undef ASSERT_COORDS_ARE_SENSIBLE_NUMBERS
  61455. #define ASSERT_COORDS_ARE_SENSIBLE_NUMBERS(x, y, w, h) \
  61456. jassert ((int) x >= MINIMUM_COORD \
  61457. && (int) x <= MAXIMUM_COORD \
  61458. && (int) y >= MINIMUM_COORD \
  61459. && (int) y <= MAXIMUM_COORD \
  61460. && (int) w >= 0 \
  61461. && (int) w < MAXIMUM_COORD \
  61462. && (int) h >= 0 \
  61463. && (int) h < MAXIMUM_COORD);
  61464. static void replaceRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61465. {
  61466. const PixelARGB blendColour (colour.getPixelARGB());
  61467. if (w < 32)
  61468. {
  61469. while (--h >= 0)
  61470. {
  61471. PixelRGB* dest = (PixelRGB*) pixels;
  61472. for (int i = w; --i >= 0;)
  61473. (dest++)->set (blendColour);
  61474. pixels += stride;
  61475. }
  61476. }
  61477. else
  61478. {
  61479. // for wider fills, it's worth using some optimisations..
  61480. const uint8 r = blendColour.getRed();
  61481. const uint8 g = blendColour.getGreen();
  61482. const uint8 b = blendColour.getBlue();
  61483. if (r == g && r == b) // if all the component values are the same, we can cheat..
  61484. {
  61485. while (--h >= 0)
  61486. {
  61487. memset (pixels, r, w * 3);
  61488. pixels += stride;
  61489. }
  61490. }
  61491. else
  61492. {
  61493. PixelRGB filler [4];
  61494. filler[0].set (blendColour);
  61495. filler[1].set (blendColour);
  61496. filler[2].set (blendColour);
  61497. filler[3].set (blendColour);
  61498. const int* const intFiller = (const int*) filler;
  61499. while (--h >= 0)
  61500. {
  61501. uint8* dest = (uint8*) pixels;
  61502. int i = w;
  61503. while ((i > 8) && (((pointer_sized_int) dest & 7) != 0))
  61504. {
  61505. ((PixelRGB*) dest)->set (blendColour);
  61506. dest += 3;
  61507. --i;
  61508. }
  61509. while (i >= 4)
  61510. {
  61511. ((int*) dest) [0] = intFiller[0];
  61512. ((int*) dest) [1] = intFiller[1];
  61513. ((int*) dest) [2] = intFiller[2];
  61514. dest += 12;
  61515. i -= 4;
  61516. }
  61517. while (--i >= 0)
  61518. {
  61519. ((PixelRGB*) dest)->set (blendColour);
  61520. dest += 3;
  61521. }
  61522. pixels += stride;
  61523. }
  61524. }
  61525. }
  61526. }
  61527. static void replaceRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61528. {
  61529. const PixelARGB blendColour (colour.getPixelARGB());
  61530. while (--h >= 0)
  61531. {
  61532. PixelARGB* const dest = (PixelARGB*) pixels;
  61533. for (int i = 0; i < w; ++i)
  61534. dest[i] = blendColour;
  61535. pixels += stride;
  61536. }
  61537. }
  61538. static void blendRectRGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61539. {
  61540. if (colour.isOpaque())
  61541. {
  61542. replaceRectRGB (pixels, w, h, stride, colour);
  61543. }
  61544. else
  61545. {
  61546. const PixelARGB blendColour (colour.getPixelARGB());
  61547. const int alpha = blendColour.getAlpha();
  61548. if (alpha <= 0)
  61549. return;
  61550. #if defined (JUCE_USE_SSE_INSTRUCTIONS) && ! JUCE_64BIT
  61551. if (SystemStats::hasSSE())
  61552. {
  61553. int64 rgb0 = (((int64) blendColour.getRed()) << 32)
  61554. | (int64) ((blendColour.getGreen() << 16)
  61555. | blendColour.getBlue());
  61556. const int invAlpha = 0xff - alpha;
  61557. int64 aaaa = (invAlpha << 16) | invAlpha;
  61558. aaaa = (aaaa << 16) | aaaa;
  61559. #ifndef JUCE_GCC
  61560. __asm
  61561. {
  61562. movq mm1, aaaa
  61563. movq mm2, rgb0
  61564. pxor mm7, mm7
  61565. }
  61566. while (--h >= 0)
  61567. {
  61568. __asm
  61569. {
  61570. mov edx, pixels
  61571. mov ebx, w
  61572. pixloop:
  61573. prefetchnta [edx]
  61574. mov ax, [edx + 1]
  61575. shl eax, 8
  61576. mov al, [edx]
  61577. movd mm0, eax
  61578. punpcklbw mm0, mm7
  61579. pmullw mm0, mm1
  61580. psrlw mm0, 8
  61581. paddw mm0, mm2
  61582. packuswb mm0, mm7
  61583. movd eax, mm0
  61584. mov [edx], al
  61585. inc edx
  61586. shr eax, 8
  61587. mov [edx], ax
  61588. add edx, 2
  61589. dec ebx
  61590. jg pixloop
  61591. }
  61592. pixels += stride;
  61593. }
  61594. __asm emms
  61595. #else
  61596. __asm__ __volatile__ (
  61597. "movq %[aaaa], %%mm1 \n"
  61598. "\tmovq %[rgb0], %%mm2 \n"
  61599. "\tpxor %%mm7, %%mm7 \n"
  61600. ".lineLoop2: \n"
  61601. "\tmovl %%esi,%%edx \n"
  61602. "\tmovl %[w], %%ebx \n"
  61603. ".pixLoop2: \n"
  61604. "\tprefetchnta (%%edx) \n"
  61605. "\tmov (%%edx), %%ax \n"
  61606. "\tshl $8, %%eax \n"
  61607. "\tmov 2(%%edx), %%al \n"
  61608. "\tmovd %%eax, %%mm0 \n"
  61609. "\tpunpcklbw %%mm7, %%mm0 \n"
  61610. "\tpmullw %%mm1, %%mm0 \n"
  61611. "\tpsrlw $8, %%mm0 \n"
  61612. "\tpaddw %%mm2, %%mm0 \n"
  61613. "\tpackuswb %%mm7, %%mm0 \n"
  61614. "\tmovd %%mm0, %%eax \n"
  61615. "\tmovb %%al, (%%edx) \n"
  61616. "\tinc %%edx \n"
  61617. "\tshr $8, %%eax \n"
  61618. "\tmovw %%ax, (%%edx) \n"
  61619. "\tadd $2, %%edx \n"
  61620. "\tdec %%ebx \n"
  61621. "\tjg .pixLoop2 \n"
  61622. "\tadd %%edi, %%esi \n"
  61623. "\tdec %%ecx \n"
  61624. "\tjg .lineLoop2 \n"
  61625. "\temms \n"
  61626. : /* No output registers */
  61627. : [aaaa] "m" (aaaa), /* Input registers */
  61628. [rgb0] "m" (rgb0),
  61629. [w] "m" (w),
  61630. "c" (h),
  61631. [stride] "D" (stride),
  61632. [pixels] "S" (pixels)
  61633. : "cc", "eax", "edx", "memory" /* Clobber list */
  61634. );
  61635. #endif
  61636. }
  61637. else
  61638. #endif
  61639. {
  61640. while (--h >= 0)
  61641. {
  61642. PixelRGB* dest = (PixelRGB*) pixels;
  61643. for (int i = w; --i >= 0;)
  61644. (dest++)->blend (blendColour);
  61645. pixels += stride;
  61646. }
  61647. }
  61648. }
  61649. }
  61650. static void blendRectARGB (uint8* pixels, const int w, int h, const int stride, const Colour& colour) throw()
  61651. {
  61652. if (colour.isOpaque())
  61653. {
  61654. replaceRectARGB (pixels, w, h, stride, colour);
  61655. }
  61656. else
  61657. {
  61658. const PixelARGB blendColour (colour.getPixelARGB());
  61659. const int alpha = blendColour.getAlpha();
  61660. if (alpha <= 0)
  61661. return;
  61662. while (--h >= 0)
  61663. {
  61664. PixelARGB* dest = (PixelARGB*) pixels;
  61665. for (int i = w; --i >= 0;)
  61666. (dest++)->blend (blendColour);
  61667. pixels += stride;
  61668. }
  61669. }
  61670. }
  61671. static void blendAlphaMapARGB (uint8* destPixel, const int imageStride,
  61672. const uint8* alphaValues, const int w, int h,
  61673. const int pixelStride, const int lineStride,
  61674. const Colour& colour) throw()
  61675. {
  61676. const PixelARGB srcPix (colour.getPixelARGB());
  61677. while (--h >= 0)
  61678. {
  61679. PixelARGB* dest = (PixelARGB*) destPixel;
  61680. const uint8* src = alphaValues;
  61681. int i = w;
  61682. while (--i >= 0)
  61683. {
  61684. unsigned int srcAlpha = *src;
  61685. src += pixelStride;
  61686. if (srcAlpha > 0)
  61687. dest->blend (srcPix, srcAlpha);
  61688. ++dest;
  61689. }
  61690. alphaValues += lineStride;
  61691. destPixel += imageStride;
  61692. }
  61693. }
  61694. static void blendAlphaMapRGB (uint8* destPixel, const int imageStride,
  61695. const uint8* alphaValues, int const width, int height,
  61696. const int pixelStride, const int lineStride,
  61697. const Colour& colour) throw()
  61698. {
  61699. const PixelARGB srcPix (colour.getPixelARGB());
  61700. while (--height >= 0)
  61701. {
  61702. PixelRGB* dest = (PixelRGB*) destPixel;
  61703. const uint8* src = alphaValues;
  61704. int i = width;
  61705. while (--i >= 0)
  61706. {
  61707. unsigned int srcAlpha = *src;
  61708. src += pixelStride;
  61709. if (srcAlpha > 0)
  61710. dest->blend (srcPix, srcAlpha);
  61711. ++dest;
  61712. }
  61713. alphaValues += lineStride;
  61714. destPixel += imageStride;
  61715. }
  61716. }
  61717. template <class PixelType>
  61718. class SolidColourEdgeTableRenderer
  61719. {
  61720. uint8* const data;
  61721. const int stride;
  61722. PixelType* linePixels;
  61723. PixelARGB sourceColour;
  61724. SolidColourEdgeTableRenderer (const SolidColourEdgeTableRenderer&);
  61725. const SolidColourEdgeTableRenderer& operator= (const SolidColourEdgeTableRenderer&);
  61726. public:
  61727. SolidColourEdgeTableRenderer (uint8* const data_,
  61728. const int stride_,
  61729. const Colour& colour) throw()
  61730. : data (data_),
  61731. stride (stride_),
  61732. sourceColour (colour.getPixelARGB())
  61733. {
  61734. }
  61735. forcedinline void setEdgeTableYPos (const int y) throw()
  61736. {
  61737. linePixels = (PixelType*) (data + stride * y);
  61738. }
  61739. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  61740. {
  61741. linePixels[x].blend (sourceColour, alphaLevel);
  61742. }
  61743. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  61744. {
  61745. PixelARGB p (sourceColour);
  61746. p.multiplyAlpha (alphaLevel);
  61747. PixelType* dest = linePixels + x;
  61748. if (p.getAlpha() < 0xff)
  61749. {
  61750. do
  61751. {
  61752. dest->blend (p);
  61753. ++dest;
  61754. } while (--width > 0);
  61755. }
  61756. else
  61757. {
  61758. do
  61759. {
  61760. dest->set (p);
  61761. ++dest;
  61762. } while (--width > 0);
  61763. }
  61764. }
  61765. };
  61766. class AlphaBitmapRenderer
  61767. {
  61768. uint8* data;
  61769. int stride;
  61770. uint8* lineStart;
  61771. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  61772. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  61773. public:
  61774. AlphaBitmapRenderer (uint8* const data_,
  61775. const int stride_) throw()
  61776. : data (data_),
  61777. stride (stride_)
  61778. {
  61779. }
  61780. forcedinline void setEdgeTableYPos (const int y) throw()
  61781. {
  61782. lineStart = data + (stride * y);
  61783. }
  61784. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  61785. {
  61786. lineStart [x] = (uint8) alphaLevel;
  61787. }
  61788. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  61789. {
  61790. uint8* d = lineStart + x;
  61791. while (--width >= 0)
  61792. *d++ = (uint8) alphaLevel;
  61793. }
  61794. };
  61795. static const int numScaleBits = 12;
  61796. class LinearGradientPixelGenerator
  61797. {
  61798. const PixelARGB* const lookupTable;
  61799. const int numEntries;
  61800. PixelARGB linePix;
  61801. int start, scale;
  61802. double grad, yTerm;
  61803. bool vertical, horizontal;
  61804. LinearGradientPixelGenerator (const LinearGradientPixelGenerator&);
  61805. const LinearGradientPixelGenerator& operator= (const LinearGradientPixelGenerator&);
  61806. public:
  61807. LinearGradientPixelGenerator (const ColourGradient& gradient,
  61808. const PixelARGB* const lookupTable_, const int numEntries_)
  61809. : lookupTable (lookupTable_),
  61810. numEntries (numEntries_)
  61811. {
  61812. jassert (numEntries_ >= 0);
  61813. float x1 = gradient.x1;
  61814. float y1 = gradient.y1;
  61815. float x2 = gradient.x2;
  61816. float y2 = gradient.y2;
  61817. if (! gradient.transform.isIdentity())
  61818. {
  61819. Line l (x2, y2, x1, y1);
  61820. const Point p3 = l.getPointAlongLine (0.0, 100.0f);
  61821. float x3 = p3.getX();
  61822. float y3 = p3.getY();
  61823. gradient.transform.transformPoint (x1, y1);
  61824. gradient.transform.transformPoint (x2, y2);
  61825. gradient.transform.transformPoint (x3, y3);
  61826. Line l2 (x2, y2, x3, y3);
  61827. float prop = l2.findNearestPointTo (x1, y1);
  61828. const Point newP2 (l2.getPointAlongLineProportionally (prop));
  61829. x2 = newP2.getX();
  61830. y2 = newP2.getY();
  61831. }
  61832. vertical = fabs (x1 - x2) < 0.001f;
  61833. horizontal = fabs (y1 - y2) < 0.001f;
  61834. if (vertical)
  61835. {
  61836. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (y2 - y1));
  61837. start = roundDoubleToInt (y1 * scale);
  61838. }
  61839. else if (horizontal)
  61840. {
  61841. scale = roundDoubleToInt ((numEntries << numScaleBits) / (double) (x2 - x1));
  61842. start = roundDoubleToInt (x1 * scale);
  61843. }
  61844. else
  61845. {
  61846. grad = (y2 - y1) / (double) (x1 - x2);
  61847. yTerm = y1 - x1 / grad;
  61848. scale = roundDoubleToInt ((numEntries << numScaleBits) / (yTerm * grad - (y2 * grad - x2)));
  61849. grad *= scale;
  61850. }
  61851. }
  61852. forcedinline void setY (const int y) throw()
  61853. {
  61854. if (vertical)
  61855. linePix = lookupTable [jlimit (0, numEntries, (y * scale - start) >> numScaleBits)];
  61856. else if (! horizontal)
  61857. start = roundDoubleToInt ((y - yTerm) * grad);
  61858. }
  61859. forcedinline const PixelARGB getPixel (const int x) const throw()
  61860. {
  61861. if (vertical)
  61862. return linePix;
  61863. return lookupTable [jlimit (0, numEntries, (x * scale - start) >> numScaleBits)];
  61864. }
  61865. };
  61866. class RadialGradientPixelGenerator
  61867. {
  61868. protected:
  61869. const PixelARGB* const lookupTable;
  61870. const int numEntries;
  61871. const double gx1, gy1;
  61872. double maxDist, invScale;
  61873. double dy;
  61874. RadialGradientPixelGenerator (const RadialGradientPixelGenerator&);
  61875. const RadialGradientPixelGenerator& operator= (const RadialGradientPixelGenerator&);
  61876. public:
  61877. RadialGradientPixelGenerator (const ColourGradient& gradient,
  61878. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  61879. : lookupTable (lookupTable_),
  61880. numEntries (numEntries_),
  61881. gx1 (gradient.x1),
  61882. gy1 (gradient.y1)
  61883. {
  61884. jassert (numEntries_ >= 0);
  61885. const float dx = gradient.x1 - gradient.x2;
  61886. const float dy = gradient.y1 - gradient.y2;
  61887. maxDist = dx * dx + dy * dy;
  61888. invScale = (numEntries + 1) / sqrt (maxDist);
  61889. }
  61890. forcedinline void setY (const int y) throw()
  61891. {
  61892. dy = y - gy1;
  61893. dy *= dy;
  61894. }
  61895. forcedinline const PixelARGB getPixel (const int px) const throw()
  61896. {
  61897. double x = px - gx1;
  61898. x *= x;
  61899. x += dy;
  61900. if (x >= maxDist)
  61901. return lookupTable [numEntries];
  61902. else
  61903. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  61904. }
  61905. };
  61906. class TransformedRadialGradientPixelGenerator : public RadialGradientPixelGenerator
  61907. {
  61908. double tM10, tM00, lineYM01, lineYM11;
  61909. AffineTransform inverseTransform;
  61910. TransformedRadialGradientPixelGenerator (const TransformedRadialGradientPixelGenerator&);
  61911. const TransformedRadialGradientPixelGenerator& operator= (const TransformedRadialGradientPixelGenerator&);
  61912. public:
  61913. TransformedRadialGradientPixelGenerator (const ColourGradient& gradient,
  61914. const PixelARGB* const lookupTable_, const int numEntries_) throw()
  61915. : RadialGradientPixelGenerator (gradient, lookupTable_, numEntries_),
  61916. inverseTransform (gradient.transform.inverted())
  61917. {
  61918. tM10 = inverseTransform.mat10;
  61919. tM00 = inverseTransform.mat00;
  61920. }
  61921. forcedinline void setY (const int y) throw()
  61922. {
  61923. lineYM01 = inverseTransform.mat01 * y + inverseTransform.mat02 - gx1;
  61924. lineYM11 = inverseTransform.mat11 * y + inverseTransform.mat12 - gy1;
  61925. }
  61926. forcedinline const PixelARGB getPixel (const int px) const throw()
  61927. {
  61928. double x = px;
  61929. const double y = tM10 * x + lineYM11;
  61930. x = tM00 * x + lineYM01;
  61931. x *= x;
  61932. x += y * y;
  61933. if (x >= maxDist)
  61934. return lookupTable [numEntries];
  61935. else
  61936. return lookupTable [jmin (numEntries, roundDoubleToInt (sqrt (x) * invScale))];
  61937. }
  61938. };
  61939. template <class PixelType, class GradientType>
  61940. class GradientEdgeTableRenderer : public GradientType
  61941. {
  61942. uint8* const data;
  61943. const int stride;
  61944. PixelType* linePixels;
  61945. GradientEdgeTableRenderer (const GradientEdgeTableRenderer&);
  61946. const GradientEdgeTableRenderer& operator= (const GradientEdgeTableRenderer&);
  61947. public:
  61948. GradientEdgeTableRenderer (uint8* const data_,
  61949. const int stride_,
  61950. const ColourGradient& gradient,
  61951. const PixelARGB* const lookupTable, const int numEntries) throw()
  61952. : GradientType (gradient, lookupTable, numEntries - 1),
  61953. data (data_),
  61954. stride (stride_)
  61955. {
  61956. }
  61957. forcedinline void setEdgeTableYPos (const int y) throw()
  61958. {
  61959. linePixels = (PixelType*) (data + stride * y);
  61960. GradientType::setY (y);
  61961. }
  61962. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  61963. {
  61964. linePixels[x].blend (GradientType::getPixel (x), alphaLevel);
  61965. }
  61966. forcedinline void handleEdgeTableLine (int x, int width, const int alphaLevel) const throw()
  61967. {
  61968. PixelType* dest = linePixels + x;
  61969. if (alphaLevel < 0xff)
  61970. {
  61971. do
  61972. {
  61973. (dest++)->blend (GradientType::getPixel (x++), alphaLevel);
  61974. } while (--width > 0);
  61975. }
  61976. else
  61977. {
  61978. do
  61979. {
  61980. (dest++)->blend (GradientType::getPixel (x++));
  61981. } while (--width > 0);
  61982. }
  61983. }
  61984. };
  61985. template <class DestPixelType, class SrcPixelType>
  61986. class ImageFillEdgeTableRenderer
  61987. {
  61988. uint8* const destImageData;
  61989. const uint8* srcImageData;
  61990. int stride, srcStride, extraAlpha;
  61991. DestPixelType* linePixels;
  61992. SrcPixelType* sourceLineStart;
  61993. ImageFillEdgeTableRenderer (const ImageFillEdgeTableRenderer&);
  61994. const ImageFillEdgeTableRenderer& operator= (const ImageFillEdgeTableRenderer&);
  61995. public:
  61996. ImageFillEdgeTableRenderer (uint8* const destImageData_,
  61997. const int stride_,
  61998. const uint8* srcImageData_,
  61999. const int srcStride_,
  62000. int extraAlpha_,
  62001. SrcPixelType*) throw() // dummy param to avoid compiler error
  62002. : destImageData (destImageData_),
  62003. srcImageData (srcImageData_),
  62004. stride (stride_),
  62005. srcStride (srcStride_),
  62006. extraAlpha (extraAlpha_)
  62007. {
  62008. }
  62009. forcedinline void setEdgeTableYPos (int y) throw()
  62010. {
  62011. linePixels = (DestPixelType*) (destImageData + stride * y);
  62012. sourceLineStart = (SrcPixelType*) (srcImageData + srcStride * y);
  62013. }
  62014. forcedinline void handleEdgeTablePixel (const int x, int alphaLevel) const throw()
  62015. {
  62016. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  62017. linePixels[x].blend (sourceLineStart [x], alphaLevel);
  62018. }
  62019. forcedinline void handleEdgeTableLine (int x, int width, int alphaLevel) const throw()
  62020. {
  62021. DestPixelType* dest = linePixels + x;
  62022. alphaLevel = (alphaLevel * extraAlpha) >> 8;
  62023. if (alphaLevel < 0xfe)
  62024. {
  62025. do
  62026. {
  62027. dest++ ->blend (sourceLineStart [x++], alphaLevel);
  62028. } while (--width > 0);
  62029. }
  62030. else
  62031. {
  62032. do
  62033. {
  62034. dest++ ->blend (sourceLineStart [x++]);
  62035. } while (--width > 0);
  62036. }
  62037. }
  62038. };
  62039. static void blendRowOfPixels (PixelARGB* dst,
  62040. const PixelRGB* src,
  62041. int width) throw()
  62042. {
  62043. while (--width >= 0)
  62044. (dst++)->set (*src++);
  62045. }
  62046. static void blendRowOfPixels (PixelRGB* dst,
  62047. const PixelRGB* src,
  62048. int width) throw()
  62049. {
  62050. memcpy (dst, src, 3 * width);
  62051. }
  62052. static void blendRowOfPixels (PixelRGB* dst,
  62053. const PixelARGB* src,
  62054. int width) throw()
  62055. {
  62056. while (--width >= 0)
  62057. (dst++)->blend (*src++);
  62058. }
  62059. static void blendRowOfPixels (PixelARGB* dst,
  62060. const PixelARGB* src,
  62061. int width) throw()
  62062. {
  62063. while (--width >= 0)
  62064. (dst++)->blend (*src++);
  62065. }
  62066. static void blendRowOfPixels (PixelARGB* dst,
  62067. const PixelRGB* src,
  62068. int width,
  62069. const uint8 alpha) throw()
  62070. {
  62071. while (--width >= 0)
  62072. (dst++)->blend (*src++, alpha);
  62073. }
  62074. static void blendRowOfPixels (PixelRGB* dst,
  62075. const PixelRGB* src,
  62076. int width,
  62077. const uint8 alpha) throw()
  62078. {
  62079. uint8* d = (uint8*) dst;
  62080. const uint8* s = (const uint8*) src;
  62081. const int inverseAlpha = 0xff - alpha;
  62082. while (--width >= 0)
  62083. {
  62084. d[0] = (uint8) (s[0] + (((d[0] - s[0]) * inverseAlpha) >> 8));
  62085. d[1] = (uint8) (s[1] + (((d[1] - s[1]) * inverseAlpha) >> 8));
  62086. d[2] = (uint8) (s[2] + (((d[2] - s[2]) * inverseAlpha) >> 8));
  62087. d += 3;
  62088. s += 3;
  62089. }
  62090. }
  62091. static void blendRowOfPixels (PixelRGB* dst,
  62092. const PixelARGB* src,
  62093. int width,
  62094. const uint8 alpha) throw()
  62095. {
  62096. while (--width >= 0)
  62097. (dst++)->blend (*src++, alpha);
  62098. }
  62099. static void blendRowOfPixels (PixelARGB* dst,
  62100. const PixelARGB* src,
  62101. int width,
  62102. const uint8 alpha) throw()
  62103. {
  62104. while (--width >= 0)
  62105. (dst++)->blend (*src++, alpha);
  62106. }
  62107. template <class DestPixelType, class SrcPixelType>
  62108. static void overlayImage (DestPixelType* dest,
  62109. const int destStride,
  62110. const SrcPixelType* src,
  62111. const int srcStride,
  62112. const int width,
  62113. int height,
  62114. const uint8 alpha) throw()
  62115. {
  62116. if (alpha < 0xff)
  62117. {
  62118. while (--height >= 0)
  62119. {
  62120. blendRowOfPixels (dest, src, width, alpha);
  62121. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  62122. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  62123. }
  62124. }
  62125. else
  62126. {
  62127. while (--height >= 0)
  62128. {
  62129. blendRowOfPixels (dest, src, width);
  62130. dest = (DestPixelType*) (((uint8*) dest) + destStride);
  62131. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  62132. }
  62133. }
  62134. }
  62135. template <class DestPixelType, class SrcPixelType>
  62136. static void transformedImageRender (Image& destImage,
  62137. const Image& sourceImage,
  62138. const int destClipX, const int destClipY,
  62139. const int destClipW, const int destClipH,
  62140. const int srcClipX, const int srcClipY,
  62141. const int srcClipWidth, const int srcClipHeight,
  62142. double srcX, double srcY,
  62143. const double lineDX, const double lineDY,
  62144. const double pixelDX, const double pixelDY,
  62145. const uint8 alpha,
  62146. const Graphics::ResamplingQuality quality,
  62147. DestPixelType*,
  62148. SrcPixelType*) throw() // forced by a compiler bug to include dummy
  62149. // parameters of the templated classes to
  62150. // make it use the correct instance of this function..
  62151. {
  62152. int destStride, destPixelStride;
  62153. uint8* const destPixels = destImage.lockPixelDataReadWrite (destClipX, destClipY, destClipW, destClipH, destStride, destPixelStride);
  62154. int srcStride, srcPixelStride;
  62155. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (srcClipX, srcClipY, srcClipWidth, srcClipHeight, srcStride, srcPixelStride);
  62156. if (quality == Graphics::lowResamplingQuality) // nearest-neighbour..
  62157. {
  62158. for (int y = 0; y < destClipH; ++y)
  62159. {
  62160. double sx = srcX;
  62161. double sy = srcY;
  62162. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  62163. for (int x = 0; x < destClipW; ++x)
  62164. {
  62165. const int ix = roundDoubleToInt (floor (sx)) - srcClipX;
  62166. if (((unsigned int) ix) < (unsigned int) srcClipWidth)
  62167. {
  62168. const int iy = roundDoubleToInt (floor (sy)) - srcClipY;
  62169. if (((unsigned int) iy) < (unsigned int) srcClipHeight)
  62170. {
  62171. const SrcPixelType* const src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  62172. dest->blend (*src, alpha);
  62173. }
  62174. }
  62175. ++dest;
  62176. sx += pixelDX;
  62177. sy += pixelDY;
  62178. }
  62179. srcX += lineDX;
  62180. srcY += lineDY;
  62181. }
  62182. }
  62183. else
  62184. {
  62185. jassert (quality == Graphics::mediumResamplingQuality); // (only bilinear is implemented, so that's what you'll get here..)
  62186. for (int y = 0; y < destClipH; ++y)
  62187. {
  62188. double sx = srcX - (srcClipWidth == destClipW ? 0.0 : 0.5);
  62189. double sy = srcY - (srcClipHeight == destClipH ? 0.0 : 0.5);
  62190. DestPixelType* dest = (DestPixelType*) (destPixels + destStride * y);
  62191. for (int x = 0; x < destClipW; ++x)
  62192. {
  62193. const double fx = floor (sx);
  62194. const double fy = floor (sy);
  62195. const int ix = roundDoubleToInt (fx) - srcClipX;
  62196. const int iy = roundDoubleToInt (fy) - srcClipY;
  62197. if (ix < srcClipWidth && iy < srcClipHeight)
  62198. {
  62199. PixelARGB p1 (0), p2 (0), p3 (0), p4 (0);
  62200. const SrcPixelType* src = (const SrcPixelType*) (srcPixels + srcStride * iy + srcPixelStride * ix);
  62201. if (iy >= 0)
  62202. {
  62203. if (ix >= 0)
  62204. p1.set (src[0]);
  62205. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  62206. p2.set (src[1]);
  62207. }
  62208. if (((unsigned int) (iy + 1)) < (unsigned int) srcClipHeight)
  62209. {
  62210. src = (const SrcPixelType*) (((const uint8*) src) + srcStride);
  62211. if (ix >= 0)
  62212. p3.set (src[0]);
  62213. if (((unsigned int) (ix + 1)) < (unsigned int) srcClipWidth)
  62214. p4.set (src[1]);
  62215. }
  62216. const int dx = roundDoubleToInt ((sx - fx) * 255.0);
  62217. p1.tween (p2, dx);
  62218. p3.tween (p4, dx);
  62219. p1.tween (p3, roundDoubleToInt ((sy - fy) * 255.0));
  62220. if (p1.getAlpha() > 0)
  62221. dest->blend (p1, alpha);
  62222. }
  62223. ++dest;
  62224. sx += pixelDX;
  62225. sy += pixelDY;
  62226. }
  62227. srcX += lineDX;
  62228. srcY += lineDY;
  62229. }
  62230. }
  62231. destImage.releasePixelDataReadWrite (destPixels);
  62232. sourceImage.releasePixelDataReadOnly (srcPixels);
  62233. }
  62234. template <class SrcPixelType, class DestPixelType>
  62235. static void renderAlphaMap (DestPixelType* destPixels,
  62236. int destStride,
  62237. SrcPixelType* srcPixels,
  62238. int srcStride,
  62239. const uint8* alphaValues,
  62240. const int lineStride, const int pixelStride,
  62241. int width, int height,
  62242. const int extraAlpha) throw()
  62243. {
  62244. while (--height >= 0)
  62245. {
  62246. SrcPixelType* srcPix = srcPixels;
  62247. srcPixels = (SrcPixelType*) (((const uint8*) srcPixels) + srcStride);
  62248. DestPixelType* destPix = destPixels;
  62249. destPixels = (DestPixelType*) (((uint8*) destPixels) + destStride);
  62250. const uint8* alpha = alphaValues;
  62251. alphaValues += lineStride;
  62252. if (extraAlpha < 0x100)
  62253. {
  62254. for (int i = width; --i >= 0;)
  62255. {
  62256. destPix++ ->blend (*srcPix++, (extraAlpha * *alpha) >> 8);
  62257. alpha += pixelStride;
  62258. }
  62259. }
  62260. else
  62261. {
  62262. for (int i = width; --i >= 0;)
  62263. {
  62264. destPix++ ->blend (*srcPix++, *alpha);
  62265. alpha += pixelStride;
  62266. }
  62267. }
  62268. }
  62269. }
  62270. LowLevelGraphicsSoftwareRenderer::LowLevelGraphicsSoftwareRenderer (Image& image_)
  62271. : image (image_),
  62272. xOffset (0),
  62273. yOffset (0),
  62274. stateStack (20)
  62275. {
  62276. clip = new RectangleList (Rectangle (0, 0, image_.getWidth(), image_.getHeight()));
  62277. }
  62278. LowLevelGraphicsSoftwareRenderer::~LowLevelGraphicsSoftwareRenderer()
  62279. {
  62280. delete clip;
  62281. }
  62282. bool LowLevelGraphicsSoftwareRenderer::isVectorDevice() const
  62283. {
  62284. return false;
  62285. }
  62286. void LowLevelGraphicsSoftwareRenderer::setOrigin (int x, int y)
  62287. {
  62288. xOffset += x;
  62289. yOffset += y;
  62290. }
  62291. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (int x, int y, int w, int h)
  62292. {
  62293. return clip->clipTo (Rectangle (x + xOffset, y + yOffset, w, h));
  62294. }
  62295. bool LowLevelGraphicsSoftwareRenderer::reduceClipRegion (const RectangleList& clipRegion)
  62296. {
  62297. RectangleList temp (clipRegion);
  62298. temp.offsetAll (xOffset, yOffset);
  62299. return clip->clipTo (temp);
  62300. }
  62301. void LowLevelGraphicsSoftwareRenderer::excludeClipRegion (int x, int y, int w, int h)
  62302. {
  62303. clip->subtract (Rectangle (x + xOffset, y + yOffset, w, h));
  62304. }
  62305. bool LowLevelGraphicsSoftwareRenderer::clipRegionIntersects (int x, int y, int w, int h)
  62306. {
  62307. return clip->intersectsRectangle (Rectangle (x + xOffset, y + yOffset, w, h));
  62308. }
  62309. const Rectangle LowLevelGraphicsSoftwareRenderer::getClipBounds() const
  62310. {
  62311. return clip->getBounds().translated (-xOffset, -yOffset);
  62312. }
  62313. bool LowLevelGraphicsSoftwareRenderer::isClipEmpty() const
  62314. {
  62315. return clip->isEmpty();
  62316. }
  62317. LowLevelGraphicsSoftwareRenderer::SavedState::SavedState (RectangleList* const clip_,
  62318. const int xOffset_, const int yOffset_)
  62319. : clip (clip_),
  62320. xOffset (xOffset_),
  62321. yOffset (yOffset_)
  62322. {
  62323. }
  62324. LowLevelGraphicsSoftwareRenderer::SavedState::~SavedState()
  62325. {
  62326. delete clip;
  62327. }
  62328. void LowLevelGraphicsSoftwareRenderer::saveState()
  62329. {
  62330. stateStack.add (new SavedState (new RectangleList (*clip), xOffset, yOffset));
  62331. }
  62332. void LowLevelGraphicsSoftwareRenderer::restoreState()
  62333. {
  62334. SavedState* const top = stateStack.getLast();
  62335. if (top != 0)
  62336. {
  62337. clip->swapWith (*top->clip);
  62338. xOffset = top->xOffset;
  62339. yOffset = top->yOffset;
  62340. stateStack.removeLast();
  62341. }
  62342. else
  62343. {
  62344. jassertfalse // trying to pop with an empty stack!
  62345. }
  62346. }
  62347. void LowLevelGraphicsSoftwareRenderer::fillRectWithColour (int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  62348. {
  62349. x += xOffset;
  62350. y += yOffset;
  62351. for (RectangleList::Iterator i (*clip); i.next();)
  62352. {
  62353. clippedFillRectWithColour (*i.getRectangle(), x, y, w, h, colour, replaceExistingContents);
  62354. }
  62355. }
  62356. void LowLevelGraphicsSoftwareRenderer::clippedFillRectWithColour (const Rectangle& clipRect,
  62357. int x, int y, int w, int h, const Colour& colour, const bool replaceExistingContents)
  62358. {
  62359. if (clipRect.intersectRectangle (x, y, w, h))
  62360. {
  62361. int stride, pixelStride;
  62362. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  62363. if (image.getFormat() == Image::RGB)
  62364. {
  62365. if (replaceExistingContents)
  62366. replaceRectRGB (pixels, w, h, stride, colour);
  62367. else
  62368. blendRectRGB (pixels, w, h, stride, colour);
  62369. }
  62370. else if (image.getFormat() == Image::ARGB)
  62371. {
  62372. if (replaceExistingContents)
  62373. replaceRectARGB (pixels, w, h, stride, colour);
  62374. else
  62375. blendRectARGB (pixels, w, h, stride, colour);
  62376. }
  62377. else
  62378. {
  62379. jassertfalse // not done!
  62380. }
  62381. image.releasePixelDataReadWrite (pixels);
  62382. }
  62383. }
  62384. void LowLevelGraphicsSoftwareRenderer::fillRectWithGradient (int x, int y, int w, int h, const ColourGradient& gradient)
  62385. {
  62386. Path p;
  62387. p.addRectangle ((float) x, (float) y, (float) w, (float) h);
  62388. fillPathWithGradient (p, AffineTransform::identity, gradient, EdgeTable::Oversampling_none);
  62389. }
  62390. bool LowLevelGraphicsSoftwareRenderer::getPathBounds (int clipX, int clipY, int clipW, int clipH,
  62391. const Path& path, const AffineTransform& transform,
  62392. int& x, int& y, int& w, int& h) const
  62393. {
  62394. float tx, ty, tw, th;
  62395. path.getBoundsTransformed (transform, tx, ty, tw, th);
  62396. x = roundDoubleToInt (tx) - 1;
  62397. y = roundDoubleToInt (ty) - 1;
  62398. w = roundDoubleToInt (tw) + 2;
  62399. h = roundDoubleToInt (th) + 2;
  62400. // seems like this operation is using some crazy out-of-range numbers..
  62401. ASSERT_COORDS_ARE_SENSIBLE_NUMBERS (x, y, w, h);
  62402. return Rectangle::intersectRectangles (x, y, w, h, clipX, clipY, clipW, clipH);
  62403. }
  62404. void LowLevelGraphicsSoftwareRenderer::fillPathWithColour (const Path& path, const AffineTransform& t,
  62405. const Colour& colour, EdgeTable::OversamplingLevel quality)
  62406. {
  62407. for (RectangleList::Iterator i (*clip); i.next();)
  62408. {
  62409. const Rectangle& r = *i.getRectangle();
  62410. clippedFillPathWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(), path, t, colour, quality);
  62411. }
  62412. }
  62413. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithColour (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  62414. const Colour& colour, EdgeTable::OversamplingLevel quality)
  62415. {
  62416. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  62417. int cx, cy, cw, ch;
  62418. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  62419. {
  62420. EdgeTable edgeTable (0, ch, quality);
  62421. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  62422. int stride, pixelStride;
  62423. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  62424. if (image.getFormat() == Image::RGB)
  62425. {
  62426. jassert (pixelStride == 3);
  62427. SolidColourEdgeTableRenderer <PixelRGB> renderer (pixels, stride, colour);
  62428. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62429. }
  62430. else if (image.getFormat() == Image::ARGB)
  62431. {
  62432. jassert (pixelStride == 4);
  62433. SolidColourEdgeTableRenderer <PixelARGB> renderer (pixels, stride, colour);
  62434. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62435. }
  62436. else if (image.getFormat() == Image::SingleChannel)
  62437. {
  62438. jassert (pixelStride == 1);
  62439. AlphaBitmapRenderer renderer (pixels, stride);
  62440. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62441. }
  62442. image.releasePixelDataReadWrite (pixels);
  62443. }
  62444. }
  62445. void LowLevelGraphicsSoftwareRenderer::fillPathWithGradient (const Path& path, const AffineTransform& t, const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  62446. {
  62447. for (RectangleList::Iterator i (*clip); i.next();)
  62448. {
  62449. const Rectangle& r = *i.getRectangle();
  62450. clippedFillPathWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62451. path, t, gradient, quality);
  62452. }
  62453. }
  62454. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithGradient (int clipX, int clipY, int clipW, int clipH, const Path& path, const AffineTransform& t,
  62455. const ColourGradient& gradient, EdgeTable::OversamplingLevel quality)
  62456. {
  62457. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  62458. int cx, cy, cw, ch;
  62459. if (getPathBounds (clipX, clipY, clipW, clipH, path, transform, cx, cy, cw, ch))
  62460. {
  62461. int stride, pixelStride;
  62462. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (cx, cy, cw, ch, stride, pixelStride);
  62463. ColourGradient g2 (gradient);
  62464. const bool isIdentity = g2.transform.isIdentity();
  62465. if (isIdentity)
  62466. {
  62467. g2.x1 += xOffset - cx;
  62468. g2.x2 += xOffset - cx;
  62469. g2.y1 += yOffset - cy;
  62470. g2.y2 += yOffset - cy;
  62471. }
  62472. else
  62473. {
  62474. g2.transform = g2.transform.translated ((float) (xOffset - cx),
  62475. (float) (yOffset - cy));
  62476. }
  62477. int numLookupEntries;
  62478. PixelARGB* const lookupTable = g2.createLookupTable (numLookupEntries);
  62479. jassert (numLookupEntries > 0);
  62480. EdgeTable edgeTable (0, ch, quality);
  62481. edgeTable.addPath (path, transform.translated ((float) -cx, (float) -cy));
  62482. if (image.getFormat() == Image::RGB)
  62483. {
  62484. jassert (pixelStride == 3);
  62485. if (g2.isRadial)
  62486. {
  62487. if (isIdentity)
  62488. {
  62489. GradientEdgeTableRenderer <PixelRGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62490. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62491. }
  62492. else
  62493. {
  62494. GradientEdgeTableRenderer <PixelRGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62495. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62496. }
  62497. }
  62498. else
  62499. {
  62500. GradientEdgeTableRenderer <PixelRGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62501. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62502. }
  62503. }
  62504. else if (image.getFormat() == Image::ARGB)
  62505. {
  62506. jassert (pixelStride == 4);
  62507. if (g2.isRadial)
  62508. {
  62509. if (isIdentity)
  62510. {
  62511. GradientEdgeTableRenderer <PixelARGB, RadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62512. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62513. }
  62514. else
  62515. {
  62516. GradientEdgeTableRenderer <PixelARGB, TransformedRadialGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62517. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62518. }
  62519. }
  62520. else
  62521. {
  62522. GradientEdgeTableRenderer <PixelARGB, LinearGradientPixelGenerator> renderer (pixels, stride, g2, lookupTable, numLookupEntries);
  62523. edgeTable.iterate (renderer, 0, 0, cw, ch, 0);
  62524. }
  62525. }
  62526. else if (image.getFormat() == Image::SingleChannel)
  62527. {
  62528. jassertfalse // not done!
  62529. }
  62530. juce_free (lookupTable);
  62531. image.releasePixelDataReadWrite (pixels);
  62532. }
  62533. }
  62534. void LowLevelGraphicsSoftwareRenderer::fillPathWithImage (const Path& path, const AffineTransform& transform,
  62535. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  62536. {
  62537. imageX += xOffset;
  62538. imageY += yOffset;
  62539. for (RectangleList::Iterator i (*clip); i.next();)
  62540. {
  62541. const Rectangle& r = *i.getRectangle();
  62542. clippedFillPathWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62543. path, transform, sourceImage, imageX, imageY, opacity, quality);
  62544. }
  62545. }
  62546. void LowLevelGraphicsSoftwareRenderer::clippedFillPathWithImage (int x, int y, int w, int h, const Path& path, const AffineTransform& transform,
  62547. const Image& sourceImage, int imageX, int imageY, float opacity, EdgeTable::OversamplingLevel quality)
  62548. {
  62549. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, sourceImage.getWidth(), sourceImage.getHeight()))
  62550. {
  62551. EdgeTable edgeTable (0, h, quality);
  62552. edgeTable.addPath (path, transform.translated ((float) (xOffset - x), (float) (yOffset - y)));
  62553. int stride, pixelStride;
  62554. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  62555. int srcStride, srcPixelStride;
  62556. const uint8* const srcPix = (const uint8*) sourceImage.lockPixelDataReadOnly (x - imageX, y - imageY, w, h, srcStride, srcPixelStride);
  62557. const int alpha = jlimit (0, 255, roundDoubleToInt (opacity * 255.0f));
  62558. if (image.getFormat() == Image::RGB)
  62559. {
  62560. if (sourceImage.getFormat() == Image::RGB)
  62561. {
  62562. ImageFillEdgeTableRenderer <PixelRGB, PixelRGB> renderer (pixels, stride,
  62563. srcPix, srcStride,
  62564. alpha, (PixelRGB*) 0);
  62565. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62566. }
  62567. else if (sourceImage.getFormat() == Image::ARGB)
  62568. {
  62569. ImageFillEdgeTableRenderer <PixelRGB, PixelARGB> renderer (pixels, stride,
  62570. srcPix, srcStride,
  62571. alpha, (PixelARGB*) 0);
  62572. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62573. }
  62574. else
  62575. {
  62576. jassertfalse // not done!
  62577. }
  62578. }
  62579. else if (image.getFormat() == Image::ARGB)
  62580. {
  62581. if (sourceImage.getFormat() == Image::RGB)
  62582. {
  62583. ImageFillEdgeTableRenderer <PixelARGB, PixelRGB> renderer (pixels, stride,
  62584. srcPix, srcStride,
  62585. alpha, (PixelRGB*) 0);
  62586. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62587. }
  62588. else if (sourceImage.getFormat() == Image::ARGB)
  62589. {
  62590. ImageFillEdgeTableRenderer <PixelARGB, PixelARGB> renderer (pixels, stride,
  62591. srcPix, srcStride,
  62592. alpha, (PixelARGB*) 0);
  62593. edgeTable.iterate (renderer, 0, 0, w, h, 0);
  62594. }
  62595. else
  62596. {
  62597. jassertfalse // not done!
  62598. }
  62599. }
  62600. else
  62601. {
  62602. jassertfalse // not done!
  62603. }
  62604. sourceImage.releasePixelDataReadOnly (srcPix);
  62605. image.releasePixelDataReadWrite (pixels);
  62606. }
  62607. }
  62608. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithColour (const Image& clipImage, int x, int y, const Colour& colour)
  62609. {
  62610. x += xOffset;
  62611. y += yOffset;
  62612. for (RectangleList::Iterator i (*clip); i.next();)
  62613. {
  62614. const Rectangle& r = *i.getRectangle();
  62615. clippedFillAlphaChannelWithColour (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62616. clipImage, x, y, colour);
  62617. }
  62618. }
  62619. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithColour (int clipX, int clipY, int clipW, int clipH, const Image& clipImage, int x, int y, const Colour& colour)
  62620. {
  62621. int w = clipImage.getWidth();
  62622. int h = clipImage.getHeight();
  62623. int sx = 0;
  62624. int sy = 0;
  62625. if (x < clipX)
  62626. {
  62627. sx = clipX - x;
  62628. w -= clipX - x;
  62629. x = clipX;
  62630. }
  62631. if (y < clipY)
  62632. {
  62633. sy = clipY - y;
  62634. h -= clipY - y;
  62635. y = clipY;
  62636. }
  62637. if (x + w > clipX + clipW)
  62638. w = clipX + clipW - x;
  62639. if (y + h > clipY + clipH)
  62640. h = clipY + clipH - y;
  62641. if (w > 0 && h > 0)
  62642. {
  62643. int stride, alphaStride, pixelStride;
  62644. uint8* const pixels = (uint8*) image.lockPixelDataReadWrite (x, y, w, h, stride, pixelStride);
  62645. const uint8* const alphaValues
  62646. = clipImage.lockPixelDataReadOnly (sx, sy, w, h, alphaStride, pixelStride);
  62647. #if JUCE_BIG_ENDIAN
  62648. const uint8* const alphas = alphaValues;
  62649. #else
  62650. const uint8* const alphas = alphaValues + (clipImage.getFormat() == Image::ARGB ? 3 : 0);
  62651. #endif
  62652. if (image.getFormat() == Image::RGB)
  62653. {
  62654. blendAlphaMapRGB (pixels, stride,
  62655. alphas, w, h,
  62656. pixelStride, alphaStride,
  62657. colour);
  62658. }
  62659. else if (image.getFormat() == Image::ARGB)
  62660. {
  62661. blendAlphaMapARGB (pixels, stride,
  62662. alphas, w, h,
  62663. pixelStride, alphaStride,
  62664. colour);
  62665. }
  62666. else
  62667. {
  62668. jassertfalse // not done!
  62669. }
  62670. clipImage.releasePixelDataReadOnly (alphaValues);
  62671. image.releasePixelDataReadWrite (pixels);
  62672. }
  62673. }
  62674. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithGradient (const Image& alphaChannelImage, int imageX, int imageY, const ColourGradient& gradient)
  62675. {
  62676. imageX += xOffset;
  62677. imageY += yOffset;
  62678. for (RectangleList::Iterator i (*clip); i.next();)
  62679. {
  62680. const Rectangle& r = *i.getRectangle();
  62681. clippedFillAlphaChannelWithGradient (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62682. alphaChannelImage, imageX, imageY, gradient);
  62683. }
  62684. }
  62685. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithGradient (int x, int y, int w, int h,
  62686. const Image& alphaChannelImage,
  62687. int imageX, int imageY, const ColourGradient& gradient)
  62688. {
  62689. if (Rectangle::intersectRectangles (x, y, w, h, imageX, imageY, alphaChannelImage.getWidth(), alphaChannelImage.getHeight()))
  62690. {
  62691. ColourGradient g2 (gradient);
  62692. g2.x1 += xOffset - x;
  62693. g2.x2 += xOffset - x;
  62694. g2.y1 += yOffset - y;
  62695. g2.y2 += yOffset - y;
  62696. Image temp (g2.isOpaque() ? Image::RGB : Image::ARGB, w, h, true);
  62697. LowLevelGraphicsSoftwareRenderer tempG (temp);
  62698. tempG.fillRectWithGradient (0, 0, w, h, g2);
  62699. clippedFillAlphaChannelWithImage (x, y, w, h,
  62700. alphaChannelImage, imageX, imageY,
  62701. temp, x, y, 1.0f);
  62702. }
  62703. }
  62704. void LowLevelGraphicsSoftwareRenderer::fillAlphaChannelWithImage (const Image& alphaImage, int alphaImageX, int alphaImageY,
  62705. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  62706. {
  62707. alphaImageX += xOffset;
  62708. alphaImageY += yOffset;
  62709. fillerImageX += xOffset;
  62710. fillerImageY += yOffset;
  62711. for (RectangleList::Iterator i (*clip); i.next();)
  62712. {
  62713. const Rectangle& r = *i.getRectangle();
  62714. clippedFillAlphaChannelWithImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62715. alphaImage, alphaImageX, alphaImageY,
  62716. fillerImage, fillerImageX, fillerImageY, opacity);
  62717. }
  62718. }
  62719. void LowLevelGraphicsSoftwareRenderer::clippedFillAlphaChannelWithImage (int x, int y, int w, int h, const Image& alphaImage, int alphaImageX, int alphaImageY,
  62720. const Image& fillerImage, int fillerImageX, int fillerImageY, float opacity)
  62721. {
  62722. if (Rectangle::intersectRectangles (x, y, w, h, alphaImageX, alphaImageY, alphaImage.getWidth(), alphaImage.getHeight())
  62723. && Rectangle::intersectRectangles (x, y, w, h, fillerImageX, fillerImageY, fillerImage.getWidth(), fillerImage.getHeight()))
  62724. {
  62725. int dstStride, dstPixStride;
  62726. uint8* const dstPix = image.lockPixelDataReadWrite (x, y, w, h, dstStride, dstPixStride);
  62727. int srcStride, srcPixStride;
  62728. const uint8* const srcPix = fillerImage.lockPixelDataReadOnly (x - fillerImageX, y - fillerImageY, w, h, srcStride, srcPixStride);
  62729. int maskStride, maskPixStride;
  62730. const uint8* const alpha
  62731. = alphaImage.lockPixelDataReadOnly (x - alphaImageX, y - alphaImageY, w, h, maskStride, maskPixStride);
  62732. #if JUCE_BIG_ENDIAN
  62733. const uint8* const alphaValues = alpha;
  62734. #else
  62735. const uint8* const alphaValues = alpha + (alphaImage.getFormat() == Image::ARGB ? 3 : 0);
  62736. #endif
  62737. const int extraAlpha = jlimit (0, 0x100, roundDoubleToInt (opacity * 256.0f));
  62738. if (image.getFormat() == Image::RGB)
  62739. {
  62740. if (fillerImage.getFormat() == Image::RGB)
  62741. {
  62742. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62743. }
  62744. else if (fillerImage.getFormat() == Image::ARGB)
  62745. {
  62746. renderAlphaMap ((PixelRGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62747. }
  62748. else
  62749. {
  62750. jassertfalse // not done!
  62751. }
  62752. }
  62753. else if (image.getFormat() == Image::ARGB)
  62754. {
  62755. if (fillerImage.getFormat() == Image::RGB)
  62756. {
  62757. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelRGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62758. }
  62759. else if (fillerImage.getFormat() == Image::ARGB)
  62760. {
  62761. renderAlphaMap ((PixelARGB*) dstPix, dstStride, (const PixelARGB*) srcPix, srcStride, alphaValues, maskStride, maskPixStride, w, h, extraAlpha);
  62762. }
  62763. else
  62764. {
  62765. jassertfalse // not done!
  62766. }
  62767. }
  62768. else
  62769. {
  62770. jassertfalse // not done!
  62771. }
  62772. alphaImage.releasePixelDataReadOnly (alphaValues);
  62773. fillerImage.releasePixelDataReadOnly (srcPix);
  62774. image.releasePixelDataReadWrite (dstPix);
  62775. }
  62776. }
  62777. void LowLevelGraphicsSoftwareRenderer::blendImage (const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  62778. {
  62779. dx += xOffset;
  62780. dy += yOffset;
  62781. for (RectangleList::Iterator i (*clip); i.next();)
  62782. {
  62783. const Rectangle& r = *i.getRectangle();
  62784. clippedBlendImage (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62785. sourceImage, dx, dy, dw, dh, sx, sy, opacity);
  62786. }
  62787. }
  62788. void LowLevelGraphicsSoftwareRenderer::clippedBlendImage (int clipX, int clipY, int clipW, int clipH,
  62789. const Image& sourceImage, int dx, int dy, int dw, int dh, int sx, int sy, float opacity)
  62790. {
  62791. if (dx < clipX)
  62792. {
  62793. sx += clipX - dx;
  62794. dw -= clipX - dx;
  62795. dx = clipX;
  62796. }
  62797. if (dy < clipY)
  62798. {
  62799. sy += clipY - dy;
  62800. dh -= clipY - dy;
  62801. dy = clipY;
  62802. }
  62803. if (dx + dw > clipX + clipW)
  62804. dw = clipX + clipW - dx;
  62805. if (dy + dh > clipY + clipH)
  62806. dh = clipY + clipH - dy;
  62807. if (dw <= 0 || dh <= 0)
  62808. return;
  62809. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  62810. if (alpha == 0)
  62811. return;
  62812. int dstStride, dstPixelStride;
  62813. uint8* const dstPixels = image.lockPixelDataReadWrite (dx, dy, dw, dh, dstStride, dstPixelStride);
  62814. int srcStride, srcPixelStride;
  62815. const uint8* const srcPixels = sourceImage.lockPixelDataReadOnly (sx, sy, dw, dh, srcStride, srcPixelStride);
  62816. if (image.getFormat() == Image::ARGB)
  62817. {
  62818. if (sourceImage.getFormat() == Image::ARGB)
  62819. {
  62820. overlayImage ((PixelARGB*) dstPixels, dstStride,
  62821. (PixelARGB*) srcPixels, srcStride,
  62822. dw, dh, alpha);
  62823. }
  62824. else if (sourceImage.getFormat() == Image::RGB)
  62825. {
  62826. overlayImage ((PixelARGB*) dstPixels, dstStride,
  62827. (PixelRGB*) srcPixels, srcStride,
  62828. dw, dh, alpha);
  62829. }
  62830. else
  62831. {
  62832. jassertfalse
  62833. }
  62834. }
  62835. else if (image.getFormat() == Image::RGB)
  62836. {
  62837. if (sourceImage.getFormat() == Image::ARGB)
  62838. {
  62839. overlayImage ((PixelRGB*) dstPixels, dstStride,
  62840. (PixelARGB*) srcPixels, srcStride,
  62841. dw, dh, alpha);
  62842. }
  62843. else if (sourceImage.getFormat() == Image::RGB)
  62844. {
  62845. overlayImage ((PixelRGB*) dstPixels, dstStride,
  62846. (PixelRGB*) srcPixels, srcStride,
  62847. dw, dh, alpha);
  62848. }
  62849. else
  62850. {
  62851. jassertfalse
  62852. }
  62853. }
  62854. else
  62855. {
  62856. jassertfalse
  62857. }
  62858. image.releasePixelDataReadWrite (dstPixels);
  62859. sourceImage.releasePixelDataReadOnly (srcPixels);
  62860. }
  62861. void LowLevelGraphicsSoftwareRenderer::blendImageRescaling (const Image& sourceImage,
  62862. int dx, int dy, int dw, int dh,
  62863. int sx, int sy, int sw, int sh,
  62864. float alpha,
  62865. const Graphics::ResamplingQuality quality)
  62866. {
  62867. if (sw > 0 && sh > 0)
  62868. {
  62869. if (sw == dw && sh == dh)
  62870. {
  62871. blendImage (sourceImage,
  62872. dx, dy, dw, dh,
  62873. sx, sy, alpha);
  62874. }
  62875. else
  62876. {
  62877. blendImageWarping (sourceImage,
  62878. sx, sy, sw, sh,
  62879. AffineTransform::translation ((float) -sx,
  62880. (float) -sy)
  62881. .scaled (dw / (float) sw,
  62882. dh / (float) sh)
  62883. .translated ((float) dx,
  62884. (float) dy),
  62885. alpha,
  62886. quality);
  62887. }
  62888. }
  62889. }
  62890. void LowLevelGraphicsSoftwareRenderer::blendImageWarping (const Image& sourceImage,
  62891. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  62892. const AffineTransform& t,
  62893. float opacity,
  62894. const Graphics::ResamplingQuality quality)
  62895. {
  62896. const AffineTransform transform (t.translated ((float) xOffset, (float) yOffset));
  62897. for (RectangleList::Iterator i (*clip); i.next();)
  62898. {
  62899. const Rectangle& r = *i.getRectangle();
  62900. clippedBlendImageWarping (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  62901. sourceImage, srcClipX, srcClipY, srcClipW, srcClipH,
  62902. transform, opacity, quality);
  62903. }
  62904. }
  62905. void LowLevelGraphicsSoftwareRenderer::clippedBlendImageWarping (int destClipX, int destClipY, int destClipW, int destClipH,
  62906. const Image& sourceImage,
  62907. int srcClipX, int srcClipY, int srcClipW, int srcClipH,
  62908. const AffineTransform& transform,
  62909. float opacity,
  62910. const Graphics::ResamplingQuality quality)
  62911. {
  62912. if (opacity > 0 && destClipW > 0 && destClipH > 0 && ! transform.isSingularity())
  62913. {
  62914. Rectangle::intersectRectangles (srcClipX, srcClipY, srcClipW, srcClipH,
  62915. 0, 0, sourceImage.getWidth(), sourceImage.getHeight());
  62916. if (srcClipW <= 0 || srcClipH <= 0)
  62917. return;
  62918. jassert (srcClipX >= 0 && srcClipY >= 0);
  62919. Path imageBounds;
  62920. imageBounds.addRectangle ((float) srcClipX, (float) srcClipY, (float) srcClipW, (float) srcClipH);
  62921. imageBounds.applyTransform (transform);
  62922. float imX, imY, imW, imH;
  62923. imageBounds.getBounds (imX, imY, imW, imH);
  62924. if (Rectangle::intersectRectangles (destClipX, destClipY, destClipW, destClipH,
  62925. (int) floorf (imX),
  62926. (int) floorf (imY),
  62927. 1 + roundDoubleToInt (imW),
  62928. 1 + roundDoubleToInt (imH)))
  62929. {
  62930. const uint8 alpha = (uint8) jlimit (0, 0xff, roundDoubleToInt (opacity * 256.0f));
  62931. float srcX1 = (float) destClipX;
  62932. float srcY1 = (float) destClipY;
  62933. float srcX2 = (float) (destClipX + destClipW);
  62934. float srcY2 = srcY1;
  62935. float srcX3 = srcX1;
  62936. float srcY3 = (float) (destClipY + destClipH);
  62937. AffineTransform inverse (transform.inverted());
  62938. inverse.transformPoint (srcX1, srcY1);
  62939. inverse.transformPoint (srcX2, srcY2);
  62940. inverse.transformPoint (srcX3, srcY3);
  62941. const double lineDX = (double) (srcX3 - srcX1) / destClipH;
  62942. const double lineDY = (double) (srcY3 - srcY1) / destClipH;
  62943. const double pixelDX = (double) (srcX2 - srcX1) / destClipW;
  62944. const double pixelDY = (double) (srcY2 - srcY1) / destClipW;
  62945. if (image.getFormat() == Image::ARGB)
  62946. {
  62947. if (sourceImage.getFormat() == Image::ARGB)
  62948. {
  62949. transformedImageRender (image, sourceImage,
  62950. destClipX, destClipY, destClipW, destClipH,
  62951. srcClipX, srcClipY, srcClipW, srcClipH,
  62952. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62953. alpha, quality, (PixelARGB*)0, (PixelARGB*)0);
  62954. }
  62955. else if (sourceImage.getFormat() == Image::RGB)
  62956. {
  62957. transformedImageRender (image, sourceImage,
  62958. destClipX, destClipY, destClipW, destClipH,
  62959. srcClipX, srcClipY, srcClipW, srcClipH,
  62960. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62961. alpha, quality, (PixelARGB*)0, (PixelRGB*)0);
  62962. }
  62963. else
  62964. {
  62965. jassertfalse
  62966. }
  62967. }
  62968. else if (image.getFormat() == Image::RGB)
  62969. {
  62970. if (sourceImage.getFormat() == Image::ARGB)
  62971. {
  62972. transformedImageRender (image, sourceImage,
  62973. destClipX, destClipY, destClipW, destClipH,
  62974. srcClipX, srcClipY, srcClipW, srcClipH,
  62975. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62976. alpha, quality, (PixelRGB*)0, (PixelARGB*)0);
  62977. }
  62978. else if (sourceImage.getFormat() == Image::RGB)
  62979. {
  62980. transformedImageRender (image, sourceImage,
  62981. destClipX, destClipY, destClipW, destClipH,
  62982. srcClipX, srcClipY, srcClipW, srcClipH,
  62983. srcX1, srcY1, lineDX, lineDY, pixelDX, pixelDY,
  62984. alpha, quality, (PixelRGB*)0, (PixelRGB*)0);
  62985. }
  62986. else
  62987. {
  62988. jassertfalse
  62989. }
  62990. }
  62991. else
  62992. {
  62993. jassertfalse
  62994. }
  62995. }
  62996. }
  62997. }
  62998. void LowLevelGraphicsSoftwareRenderer::drawLine (double x1, double y1, double x2, double y2, const Colour& colour)
  62999. {
  63000. x1 += xOffset;
  63001. y1 += yOffset;
  63002. x2 += xOffset;
  63003. y2 += yOffset;
  63004. for (RectangleList::Iterator i (*clip); i.next();)
  63005. {
  63006. const Rectangle& r = *i.getRectangle();
  63007. clippedDrawLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  63008. x1, y1, x2, y2, colour);
  63009. }
  63010. }
  63011. void LowLevelGraphicsSoftwareRenderer::clippedDrawLine (int clipX, int clipY, int clipW, int clipH, double x1, double y1, double x2, double y2, const Colour& colour)
  63012. {
  63013. if (clipW > 0 && clipH > 0)
  63014. {
  63015. if (x1 == x2)
  63016. {
  63017. if (y2 < y1)
  63018. swapVariables (y1, y2);
  63019. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (x1), y1, y2, colour);
  63020. }
  63021. else if (y1 == y2)
  63022. {
  63023. if (x2 < x1)
  63024. swapVariables (x1, x2);
  63025. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, roundDoubleToInt (y1), x1, x2, colour);
  63026. }
  63027. else
  63028. {
  63029. double gradient = (y2 - y1) / (x2 - x1);
  63030. if (fabs (gradient) > 1.0)
  63031. {
  63032. gradient = 1.0 / gradient;
  63033. int y = roundDoubleToInt (y1);
  63034. const int startY = y;
  63035. int endY = roundDoubleToInt (y2);
  63036. if (y > endY)
  63037. swapVariables (y, endY);
  63038. while (y < endY)
  63039. {
  63040. const double x = x1 + gradient * (y - startY);
  63041. clippedDrawHorizontalLine (clipX, clipY, clipW, clipH, y, x, x + 1.0, colour);
  63042. ++y;
  63043. }
  63044. }
  63045. else
  63046. {
  63047. int x = roundDoubleToInt (x1);
  63048. const int startX = x;
  63049. int endX = roundDoubleToInt (x2);
  63050. if (x > endX)
  63051. swapVariables (x, endX);
  63052. while (x < endX)
  63053. {
  63054. const double y = y1 + gradient * (x - startX);
  63055. clippedDrawVerticalLine (clipX, clipY, clipW, clipH, x, y, y + 1.0, colour);
  63056. ++x;
  63057. }
  63058. }
  63059. }
  63060. }
  63061. }
  63062. void LowLevelGraphicsSoftwareRenderer::drawVerticalLine (const int x, double top, double bottom, const Colour& col)
  63063. {
  63064. for (RectangleList::Iterator i (*clip); i.next();)
  63065. {
  63066. const Rectangle& r = *i.getRectangle();
  63067. clippedDrawVerticalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  63068. x + xOffset, top + yOffset, bottom + yOffset, col);
  63069. }
  63070. }
  63071. void LowLevelGraphicsSoftwareRenderer::clippedDrawVerticalLine (int clipX, int clipY, int clipW, int clipH,
  63072. const int x, double top, double bottom, const Colour& col)
  63073. {
  63074. jassert (top <= bottom);
  63075. if (((unsigned int) (x - clipX)) < (unsigned int) clipW
  63076. && top < clipY + clipH
  63077. && bottom > clipY
  63078. && clipW > 0)
  63079. {
  63080. if (top < clipY)
  63081. top = clipY;
  63082. if (bottom > clipY + clipH)
  63083. bottom = clipY + clipH;
  63084. if (bottom > top)
  63085. drawVertical (x, top, bottom, col);
  63086. }
  63087. }
  63088. void LowLevelGraphicsSoftwareRenderer::drawHorizontalLine (const int y, double left, double right, const Colour& col)
  63089. {
  63090. for (RectangleList::Iterator i (*clip); i.next();)
  63091. {
  63092. const Rectangle& r = *i.getRectangle();
  63093. clippedDrawHorizontalLine (r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  63094. y + yOffset, left + xOffset, right + xOffset, col);
  63095. }
  63096. }
  63097. void LowLevelGraphicsSoftwareRenderer::clippedDrawHorizontalLine (int clipX, int clipY, int clipW, int clipH,
  63098. const int y, double left, double right, const Colour& col)
  63099. {
  63100. jassert (left <= right);
  63101. if (((unsigned int) (y - clipY)) < (unsigned int) clipH
  63102. && left < clipX + clipW
  63103. && right > clipX
  63104. && clipW > 0)
  63105. {
  63106. if (left < clipX)
  63107. left = clipX;
  63108. if (right > clipX + clipW)
  63109. right = clipX + clipW;
  63110. if (right > left)
  63111. drawHorizontal (y, left, right, col);
  63112. }
  63113. }
  63114. void LowLevelGraphicsSoftwareRenderer::drawVertical (const int x,
  63115. const double top,
  63116. const double bottom,
  63117. const Colour& col)
  63118. {
  63119. int wholeStart = (int) top;
  63120. const int wholeEnd = (int) bottom;
  63121. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  63122. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  63123. if (totalPixels <= 0)
  63124. return;
  63125. int lineStride, dstPixelStride;
  63126. uint8* const dstPixels = image.lockPixelDataReadWrite (x, wholeStart, 1, totalPixels, lineStride, dstPixelStride);
  63127. uint8* dest = dstPixels;
  63128. PixelARGB colour (col.getPixelARGB());
  63129. if (wholeEnd == wholeStart)
  63130. {
  63131. if (image.getFormat() == Image::ARGB)
  63132. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  63133. else if (image.getFormat() == Image::RGB)
  63134. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  63135. else
  63136. {
  63137. jassertfalse
  63138. }
  63139. }
  63140. else
  63141. {
  63142. if (image.getFormat() == Image::ARGB)
  63143. {
  63144. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  63145. ++wholeStart;
  63146. dest += lineStride;
  63147. if (colour.getAlpha() == 0xff)
  63148. {
  63149. while (wholeEnd > wholeStart)
  63150. {
  63151. ((PixelARGB*) dest)->set (colour);
  63152. ++wholeStart;
  63153. dest += lineStride;
  63154. }
  63155. }
  63156. else
  63157. {
  63158. while (wholeEnd > wholeStart)
  63159. {
  63160. ((PixelARGB*) dest)->blend (colour);
  63161. ++wholeStart;
  63162. dest += lineStride;
  63163. }
  63164. }
  63165. if (lastAlpha > 0)
  63166. {
  63167. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  63168. }
  63169. }
  63170. else if (image.getFormat() == Image::RGB)
  63171. {
  63172. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  63173. ++wholeStart;
  63174. dest += lineStride;
  63175. if (colour.getAlpha() == 0xff)
  63176. {
  63177. while (wholeEnd > wholeStart)
  63178. {
  63179. ((PixelRGB*) dest)->set (colour);
  63180. ++wholeStart;
  63181. dest += lineStride;
  63182. }
  63183. }
  63184. else
  63185. {
  63186. while (wholeEnd > wholeStart)
  63187. {
  63188. ((PixelRGB*) dest)->blend (colour);
  63189. ++wholeStart;
  63190. dest += lineStride;
  63191. }
  63192. }
  63193. if (lastAlpha > 0)
  63194. {
  63195. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  63196. }
  63197. }
  63198. else
  63199. {
  63200. jassertfalse
  63201. }
  63202. }
  63203. image.releasePixelDataReadWrite (dstPixels);
  63204. }
  63205. void LowLevelGraphicsSoftwareRenderer::drawHorizontal (const int y,
  63206. const double top,
  63207. const double bottom,
  63208. const Colour& col)
  63209. {
  63210. int wholeStart = (int) top;
  63211. const int wholeEnd = (int) bottom;
  63212. const int lastAlpha = roundDoubleToInt (255.0 * (bottom - wholeEnd));
  63213. const int totalPixels = (wholeEnd - wholeStart) + (lastAlpha > 0 ? 1 : 0);
  63214. if (totalPixels <= 0)
  63215. return;
  63216. int lineStride, dstPixelStride;
  63217. uint8* const dstPixels = image.lockPixelDataReadWrite (wholeStart, y, totalPixels, 1, lineStride, dstPixelStride);
  63218. uint8* dest = dstPixels;
  63219. PixelARGB colour (col.getPixelARGB());
  63220. if (wholeEnd == wholeStart)
  63221. {
  63222. if (image.getFormat() == Image::ARGB)
  63223. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  63224. else if (image.getFormat() == Image::RGB)
  63225. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (bottom - top)));
  63226. else
  63227. {
  63228. jassertfalse
  63229. }
  63230. }
  63231. else
  63232. {
  63233. if (image.getFormat() == Image::ARGB)
  63234. {
  63235. ((PixelARGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  63236. dest += dstPixelStride;
  63237. ++wholeStart;
  63238. if (colour.getAlpha() == 0xff)
  63239. {
  63240. while (wholeEnd > wholeStart)
  63241. {
  63242. ((PixelARGB*) dest)->set (colour);
  63243. dest += dstPixelStride;
  63244. ++wholeStart;
  63245. }
  63246. }
  63247. else
  63248. {
  63249. while (wholeEnd > wholeStart)
  63250. {
  63251. ((PixelARGB*) dest)->blend (colour);
  63252. dest += dstPixelStride;
  63253. ++wholeStart;
  63254. }
  63255. }
  63256. if (lastAlpha > 0)
  63257. {
  63258. ((PixelARGB*) dest)->blend (colour, lastAlpha);
  63259. }
  63260. }
  63261. else if (image.getFormat() == Image::RGB)
  63262. {
  63263. ((PixelRGB*) dest)->blend (colour, roundDoubleToInt (255.0 * (1.0 - (top - wholeStart))));
  63264. dest += dstPixelStride;
  63265. ++wholeStart;
  63266. if (colour.getAlpha() == 0xff)
  63267. {
  63268. while (wholeEnd > wholeStart)
  63269. {
  63270. ((PixelRGB*) dest)->set (colour);
  63271. dest += dstPixelStride;
  63272. ++wholeStart;
  63273. }
  63274. }
  63275. else
  63276. {
  63277. while (wholeEnd > wholeStart)
  63278. {
  63279. ((PixelRGB*) dest)->blend (colour);
  63280. dest += dstPixelStride;
  63281. ++wholeStart;
  63282. }
  63283. }
  63284. if (lastAlpha > 0)
  63285. {
  63286. ((PixelRGB*) dest)->blend (colour, lastAlpha);
  63287. }
  63288. }
  63289. else
  63290. {
  63291. jassertfalse
  63292. }
  63293. }
  63294. image.releasePixelDataReadWrite (dstPixels);
  63295. }
  63296. END_JUCE_NAMESPACE
  63297. /********* End of inlined file: juce_LowLevelGraphicsSoftwareRenderer.cpp *********/
  63298. /********* Start of inlined file: juce_RectanglePlacement.cpp *********/
  63299. BEGIN_JUCE_NAMESPACE
  63300. RectanglePlacement::RectanglePlacement (const RectanglePlacement& other) throw()
  63301. : flags (other.flags)
  63302. {
  63303. }
  63304. const RectanglePlacement& RectanglePlacement::operator= (const RectanglePlacement& other) throw()
  63305. {
  63306. flags = other.flags;
  63307. return *this;
  63308. }
  63309. void RectanglePlacement::applyTo (double& x, double& y,
  63310. double& w, double& h,
  63311. const double dx, const double dy,
  63312. const double dw, const double dh) const throw()
  63313. {
  63314. if (w == 0 || h == 0)
  63315. return;
  63316. if ((flags & stretchToFit) != 0)
  63317. {
  63318. x = dx;
  63319. y = dy;
  63320. w = dw;
  63321. h = dh;
  63322. }
  63323. else
  63324. {
  63325. double scale = (flags & fillDestination) != 0 ? jmax (dw / w, dh / h)
  63326. : jmin (dw / w, dh / h);
  63327. if ((flags & onlyReduceInSize) != 0)
  63328. scale = jmin (scale, 1.0);
  63329. if ((flags & onlyIncreaseInSize) != 0)
  63330. scale = jmax (scale, 1.0);
  63331. w *= scale;
  63332. h *= scale;
  63333. if ((flags & xLeft) != 0)
  63334. x = dx;
  63335. else if ((flags & xRight) != 0)
  63336. x = dx + dw - w;
  63337. else
  63338. x = dx + (dw - w) * 0.5;
  63339. if ((flags & yTop) != 0)
  63340. y = dy;
  63341. else if ((flags & yBottom) != 0)
  63342. y = dy + dh - h;
  63343. else
  63344. y = dy + (dh - h) * 0.5;
  63345. }
  63346. }
  63347. const AffineTransform RectanglePlacement::getTransformToFit (float x, float y,
  63348. float w, float h,
  63349. const float dx, const float dy,
  63350. const float dw, const float dh) const throw()
  63351. {
  63352. if (w == 0 || h == 0)
  63353. return AffineTransform::identity;
  63354. const float scaleX = dw / w;
  63355. const float scaleY = dh / h;
  63356. if ((flags & stretchToFit) != 0)
  63357. {
  63358. return AffineTransform::translation (-x, -y)
  63359. .scaled (scaleX, scaleY)
  63360. .translated (dx - x, dy - y);
  63361. }
  63362. float scale = (flags & fillDestination) != 0 ? jmax (scaleX, scaleY)
  63363. : jmin (scaleX, scaleY);
  63364. if ((flags & onlyReduceInSize) != 0)
  63365. scale = jmin (scale, 1.0f);
  63366. if ((flags & onlyIncreaseInSize) != 0)
  63367. scale = jmax (scale, 1.0f);
  63368. w *= scale;
  63369. h *= scale;
  63370. float newX = dx;
  63371. if ((flags & xRight) != 0)
  63372. newX += dw - w; // right
  63373. else if ((flags & xLeft) == 0)
  63374. newX += (dw - w) / 2.0f; // centre
  63375. float newY = dy;
  63376. if ((flags & yBottom) != 0)
  63377. newY += dh - h; // bottom
  63378. else if ((flags & yTop) == 0)
  63379. newY += (dh - h) / 2.0f; // centre
  63380. return AffineTransform::translation (-x, -y)
  63381. .scaled (scale, scale)
  63382. .translated (newX, newY);
  63383. }
  63384. END_JUCE_NAMESPACE
  63385. /********* End of inlined file: juce_RectanglePlacement.cpp *********/
  63386. /********* Start of inlined file: juce_Drawable.cpp *********/
  63387. BEGIN_JUCE_NAMESPACE
  63388. Drawable::Drawable()
  63389. {
  63390. }
  63391. Drawable::~Drawable()
  63392. {
  63393. }
  63394. void Drawable::drawAt (Graphics& g, const float x, const float y) const
  63395. {
  63396. draw (g, AffineTransform::translation (x, y));
  63397. }
  63398. void Drawable::drawWithin (Graphics& g,
  63399. const int destX,
  63400. const int destY,
  63401. const int destW,
  63402. const int destH,
  63403. const RectanglePlacement& placement) const
  63404. {
  63405. if (destW > 0 && destH > 0)
  63406. {
  63407. float x, y, w, h;
  63408. getBounds (x, y, w, h);
  63409. draw (g, placement.getTransformToFit (x, y, w, h,
  63410. (float) destX, (float) destY,
  63411. (float) destW, (float) destH));
  63412. }
  63413. }
  63414. Drawable* Drawable::createFromImageData (const void* data, const int numBytes)
  63415. {
  63416. Drawable* result = 0;
  63417. Image* const image = ImageFileFormat::loadFrom (data, numBytes);
  63418. if (image != 0)
  63419. {
  63420. DrawableImage* const di = new DrawableImage();
  63421. di->setImage (image, true);
  63422. result = di;
  63423. }
  63424. else
  63425. {
  63426. const String asString (String::createStringFromData (data, numBytes));
  63427. XmlDocument doc (asString);
  63428. XmlElement* const outer = doc.getDocumentElement (true);
  63429. if (outer != 0 && outer->hasTagName (T("svg")))
  63430. {
  63431. XmlElement* const svg = doc.getDocumentElement();
  63432. if (svg != 0)
  63433. {
  63434. result = Drawable::createFromSVG (*svg);
  63435. delete svg;
  63436. }
  63437. }
  63438. delete outer;
  63439. }
  63440. return result;
  63441. }
  63442. Drawable* Drawable::createFromImageDataStream (InputStream& dataSource)
  63443. {
  63444. MemoryBlock mb;
  63445. dataSource.readIntoMemoryBlock (mb);
  63446. return createFromImageData (mb.getData(), mb.getSize());
  63447. }
  63448. Drawable* Drawable::createFromImageFile (const File& file)
  63449. {
  63450. FileInputStream* fin = file.createInputStream();
  63451. if (fin == 0)
  63452. return 0;
  63453. Drawable* d = createFromImageDataStream (*fin);
  63454. delete fin;
  63455. return d;
  63456. }
  63457. END_JUCE_NAMESPACE
  63458. /********* End of inlined file: juce_Drawable.cpp *********/
  63459. /********* Start of inlined file: juce_DrawableComposite.cpp *********/
  63460. BEGIN_JUCE_NAMESPACE
  63461. DrawableComposite::DrawableComposite()
  63462. {
  63463. }
  63464. DrawableComposite::~DrawableComposite()
  63465. {
  63466. }
  63467. void DrawableComposite::insertDrawable (Drawable* drawable,
  63468. const AffineTransform& transform,
  63469. const int index)
  63470. {
  63471. if (drawable != 0)
  63472. {
  63473. if (! drawables.contains (drawable))
  63474. {
  63475. drawables.insert (index, drawable);
  63476. if (transform.isIdentity())
  63477. transforms.insert (index, 0);
  63478. else
  63479. transforms.insert (index, new AffineTransform (transform));
  63480. }
  63481. else
  63482. {
  63483. jassertfalse // trying to add a drawable that's already in here!
  63484. }
  63485. }
  63486. }
  63487. void DrawableComposite::insertDrawable (const Drawable& drawable,
  63488. const AffineTransform& transform,
  63489. const int index)
  63490. {
  63491. insertDrawable (drawable.createCopy(), transform, index);
  63492. }
  63493. void DrawableComposite::removeDrawable (const int index)
  63494. {
  63495. drawables.remove (index);
  63496. transforms.remove (index);
  63497. }
  63498. void DrawableComposite::bringToFront (const int index)
  63499. {
  63500. if (index >= 0 && index < drawables.size() - 1)
  63501. {
  63502. drawables.move (index, -1);
  63503. transforms.move (index, -1);
  63504. }
  63505. }
  63506. void DrawableComposite::draw (Graphics& g, const AffineTransform& transform) const
  63507. {
  63508. for (int i = 0; i < drawables.size(); ++i)
  63509. {
  63510. const AffineTransform* const t = transforms.getUnchecked(i);
  63511. drawables.getUnchecked(i)->draw (g, t == 0 ? transform
  63512. : t->followedBy (transform));
  63513. }
  63514. }
  63515. void DrawableComposite::getBounds (float& x, float& y, float& width, float& height) const
  63516. {
  63517. Path totalPath;
  63518. for (int i = 0; i < drawables.size(); ++i)
  63519. {
  63520. drawables.getUnchecked(i)->getBounds (x, y, width, height);
  63521. if (width > 0.0f && height > 0.0f)
  63522. {
  63523. Path outline;
  63524. outline.addRectangle (x, y, width, height);
  63525. const AffineTransform* const t = transforms.getUnchecked(i);
  63526. if (t == 0)
  63527. totalPath.addPath (outline);
  63528. else
  63529. totalPath.addPath (outline, *t);
  63530. }
  63531. }
  63532. totalPath.getBounds (x, y, width, height);
  63533. }
  63534. bool DrawableComposite::hitTest (float x, float y) const
  63535. {
  63536. for (int i = 0; i < drawables.size(); ++i)
  63537. {
  63538. float tx = x;
  63539. float ty = y;
  63540. const AffineTransform* const t = transforms.getUnchecked(i);
  63541. if (t != 0)
  63542. t->inverted().transformPoint (tx, ty);
  63543. if (drawables.getUnchecked(i)->hitTest (tx, ty))
  63544. return true;
  63545. }
  63546. return false;
  63547. }
  63548. Drawable* DrawableComposite::createCopy() const
  63549. {
  63550. DrawableComposite* const dc = new DrawableComposite();
  63551. for (int i = 0; i < drawables.size(); ++i)
  63552. {
  63553. dc->drawables.add (drawables.getUnchecked(i)->createCopy());
  63554. const AffineTransform* const t = transforms.getUnchecked(i);
  63555. dc->transforms.add (t != 0 ? new AffineTransform (*t) : 0);
  63556. }
  63557. return dc;
  63558. }
  63559. END_JUCE_NAMESPACE
  63560. /********* End of inlined file: juce_DrawableComposite.cpp *********/
  63561. /********* Start of inlined file: juce_DrawableImage.cpp *********/
  63562. BEGIN_JUCE_NAMESPACE
  63563. DrawableImage::DrawableImage()
  63564. : image (0),
  63565. canDeleteImage (false),
  63566. opacity (1.0f),
  63567. overlayColour (0x00000000)
  63568. {
  63569. }
  63570. DrawableImage::~DrawableImage()
  63571. {
  63572. clearImage();
  63573. }
  63574. void DrawableImage::clearImage()
  63575. {
  63576. if (canDeleteImage && image != 0)
  63577. {
  63578. if (ImageCache::isImageInCache (image))
  63579. ImageCache::release (image);
  63580. else
  63581. delete image;
  63582. }
  63583. image = 0;
  63584. }
  63585. void DrawableImage::setImage (const Image& imageToCopy)
  63586. {
  63587. clearImage();
  63588. image = new Image (imageToCopy);
  63589. canDeleteImage = true;
  63590. }
  63591. void DrawableImage::setImage (Image* imageToUse,
  63592. const bool releaseWhenNotNeeded)
  63593. {
  63594. clearImage();
  63595. image = imageToUse;
  63596. canDeleteImage = releaseWhenNotNeeded;
  63597. }
  63598. void DrawableImage::setOpacity (const float newOpacity)
  63599. {
  63600. opacity = newOpacity;
  63601. }
  63602. void DrawableImage::setOverlayColour (const Colour& newOverlayColour)
  63603. {
  63604. overlayColour = newOverlayColour;
  63605. }
  63606. void DrawableImage::draw (Graphics& g, const AffineTransform& transform) const
  63607. {
  63608. if (image != 0)
  63609. {
  63610. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  63611. if (opacity > 0.0f && ! overlayColour.isOpaque())
  63612. {
  63613. g.setColour (oldColour.withMultipliedAlpha (opacity));
  63614. g.drawImageTransformed (image,
  63615. 0, 0, image->getWidth(), image->getHeight(),
  63616. transform, false);
  63617. }
  63618. if (! overlayColour.isTransparent())
  63619. {
  63620. g.setColour (overlayColour.withMultipliedAlpha (oldColour.getFloatAlpha()));
  63621. g.drawImageTransformed (image,
  63622. 0, 0, image->getWidth(), image->getHeight(),
  63623. transform, true);
  63624. }
  63625. g.setColour (oldColour);
  63626. }
  63627. }
  63628. void DrawableImage::getBounds (float& x, float& y, float& width, float& height) const
  63629. {
  63630. x = 0.0f;
  63631. y = 0.0f;
  63632. width = 0.0f;
  63633. height = 0.0f;
  63634. if (image != 0)
  63635. {
  63636. width = (float) image->getWidth();
  63637. height = (float) image->getHeight();
  63638. }
  63639. }
  63640. bool DrawableImage::hitTest (float x, float y) const
  63641. {
  63642. return image != 0
  63643. && x >= 0.0f
  63644. && y >= 0.0f
  63645. && x < image->getWidth()
  63646. && y < image->getHeight()
  63647. && image->getPixelAt (roundFloatToInt (x), roundFloatToInt (y)).getAlpha() >= 127;
  63648. }
  63649. Drawable* DrawableImage::createCopy() const
  63650. {
  63651. DrawableImage* const di = new DrawableImage();
  63652. di->opacity = opacity;
  63653. di->overlayColour = overlayColour;
  63654. if (image != 0)
  63655. {
  63656. if ((! canDeleteImage) || ! ImageCache::isImageInCache (image))
  63657. {
  63658. di->setImage (*image);
  63659. }
  63660. else
  63661. {
  63662. ImageCache::incReferenceCount (image);
  63663. di->setImage (image, true);
  63664. }
  63665. }
  63666. return di;
  63667. }
  63668. END_JUCE_NAMESPACE
  63669. /********* End of inlined file: juce_DrawableImage.cpp *********/
  63670. /********* Start of inlined file: juce_DrawablePath.cpp *********/
  63671. BEGIN_JUCE_NAMESPACE
  63672. DrawablePath::DrawablePath()
  63673. : fillBrush (new SolidColourBrush (Colours::black)),
  63674. strokeBrush (0),
  63675. strokeType (0.0f)
  63676. {
  63677. }
  63678. DrawablePath::~DrawablePath()
  63679. {
  63680. delete fillBrush;
  63681. delete strokeBrush;
  63682. }
  63683. void DrawablePath::setPath (const Path& newPath)
  63684. {
  63685. path = newPath;
  63686. updateOutline();
  63687. }
  63688. void DrawablePath::setSolidFill (const Colour& newColour)
  63689. {
  63690. delete fillBrush;
  63691. fillBrush = new SolidColourBrush (newColour);
  63692. }
  63693. void DrawablePath::setFillBrush (const Brush& newBrush)
  63694. {
  63695. delete fillBrush;
  63696. fillBrush = newBrush.createCopy();
  63697. }
  63698. void DrawablePath::setOutline (const float thickness, const Colour& colour)
  63699. {
  63700. strokeType = PathStrokeType (thickness);
  63701. delete strokeBrush;
  63702. strokeBrush = new SolidColourBrush (colour);
  63703. updateOutline();
  63704. }
  63705. void DrawablePath::setOutline (const PathStrokeType& strokeType_, const Brush& newStrokeBrush)
  63706. {
  63707. strokeType = strokeType_;
  63708. delete strokeBrush;
  63709. strokeBrush = newStrokeBrush.createCopy();
  63710. updateOutline();
  63711. }
  63712. void DrawablePath::draw (Graphics& g, const AffineTransform& transform) const
  63713. {
  63714. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  63715. const float currentOpacity = oldColour.getFloatAlpha();
  63716. {
  63717. Brush* const tempBrush = fillBrush->createCopy();
  63718. tempBrush->applyTransform (transform);
  63719. tempBrush->multiplyOpacity (currentOpacity);
  63720. g.setBrush (tempBrush);
  63721. g.fillPath (path, transform);
  63722. delete tempBrush;
  63723. }
  63724. if (strokeBrush != 0 && strokeType.getStrokeThickness() > 0.0f)
  63725. {
  63726. Brush* const tempBrush = strokeBrush->createCopy();
  63727. tempBrush->applyTransform (transform);
  63728. tempBrush->multiplyOpacity (currentOpacity);
  63729. g.setBrush (tempBrush);
  63730. g.fillPath (outline, transform);
  63731. delete tempBrush;
  63732. }
  63733. g.setColour (oldColour);
  63734. }
  63735. void DrawablePath::updateOutline()
  63736. {
  63737. outline.clear();
  63738. strokeType.createStrokedPath (outline, path, AffineTransform::identity, 4.0f);
  63739. }
  63740. void DrawablePath::getBounds (float& x, float& y, float& width, float& height) const
  63741. {
  63742. if (strokeType.getStrokeThickness() > 0.0f)
  63743. outline.getBounds (x, y, width, height);
  63744. else
  63745. path.getBounds (x, y, width, height);
  63746. }
  63747. bool DrawablePath::hitTest (float x, float y) const
  63748. {
  63749. return path.contains (x, y)
  63750. || outline.contains (x, y);
  63751. }
  63752. Drawable* DrawablePath::createCopy() const
  63753. {
  63754. DrawablePath* const dp = new DrawablePath();
  63755. dp->path = path;
  63756. dp->setFillBrush (*fillBrush);
  63757. if (strokeBrush != 0)
  63758. dp->setOutline (strokeType, *strokeBrush);
  63759. return dp;
  63760. }
  63761. END_JUCE_NAMESPACE
  63762. /********* End of inlined file: juce_DrawablePath.cpp *********/
  63763. /********* Start of inlined file: juce_DrawableText.cpp *********/
  63764. BEGIN_JUCE_NAMESPACE
  63765. DrawableText::DrawableText()
  63766. : colour (Colours::white)
  63767. {
  63768. }
  63769. DrawableText::~DrawableText()
  63770. {
  63771. }
  63772. void DrawableText::setText (const GlyphArrangement& newText)
  63773. {
  63774. text = newText;
  63775. }
  63776. void DrawableText::setText (const String& newText, const Font& fontToUse)
  63777. {
  63778. text.clear();
  63779. text.addLineOfText (fontToUse, newText, 0.0f, 0.0f);
  63780. }
  63781. void DrawableText::setColour (const Colour& newColour)
  63782. {
  63783. colour = newColour;
  63784. }
  63785. void DrawableText::draw (Graphics& g, const AffineTransform& transform) const
  63786. {
  63787. const Colour oldColour (g.getCurrentColour()); // save this so we can restore it later
  63788. g.setColour (colour.withMultipliedAlpha (oldColour.getFloatAlpha()));
  63789. text.draw (g, transform);
  63790. g.setColour (oldColour);
  63791. }
  63792. void DrawableText::getBounds (float& x, float& y, float& width, float& height) const
  63793. {
  63794. text.getBoundingBox (0, -1, x, y, width, height, false); // (really returns top, left, bottom, right)
  63795. width -= x;
  63796. height -= y;
  63797. }
  63798. bool DrawableText::hitTest (float x, float y) const
  63799. {
  63800. return text.findGlyphIndexAt (x, y) >= 0;
  63801. }
  63802. Drawable* DrawableText::createCopy() const
  63803. {
  63804. DrawableText* const dt = new DrawableText();
  63805. dt->text = text;
  63806. dt->colour = colour;
  63807. return dt;
  63808. }
  63809. END_JUCE_NAMESPACE
  63810. /********* End of inlined file: juce_DrawableText.cpp *********/
  63811. /********* Start of inlined file: juce_SVGParser.cpp *********/
  63812. BEGIN_JUCE_NAMESPACE
  63813. class SVGState
  63814. {
  63815. public:
  63816. SVGState (const XmlElement* const topLevel)
  63817. : topLevelXml (topLevel),
  63818. x (0), y (0),
  63819. width (512), height (512),
  63820. viewBoxW (0), viewBoxH (0)
  63821. {
  63822. }
  63823. ~SVGState()
  63824. {
  63825. }
  63826. Drawable* parseSVGElement (const XmlElement& xml)
  63827. {
  63828. if (! xml.hasTagName (T("svg")))
  63829. return 0;
  63830. DrawableComposite* const drawable = new DrawableComposite();
  63831. drawable->setName (xml.getStringAttribute (T("id")));
  63832. SVGState newState (*this);
  63833. if (xml.hasAttribute (T("transform")))
  63834. newState.addTransform (xml);
  63835. newState.x = getCoordLength (xml.getStringAttribute (T("x"), String (newState.x)), viewBoxW);
  63836. newState.y = getCoordLength (xml.getStringAttribute (T("y"), String (newState.y)), viewBoxH);
  63837. newState.width = getCoordLength (xml.getStringAttribute (T("width"), String (newState.width)), viewBoxW);
  63838. newState.height = getCoordLength (xml.getStringAttribute (T("height"), String (newState.height)), viewBoxH);
  63839. if (xml.hasAttribute (T("viewBox")))
  63840. {
  63841. const String viewParams (xml.getStringAttribute (T("viewBox")));
  63842. int i = 0;
  63843. float vx, vy, vw, vh;
  63844. if (parseCoords (viewParams, vx, vy, i, true)
  63845. && parseCoords (viewParams, vw, vh, i, true)
  63846. && vw > 0
  63847. && vh > 0)
  63848. {
  63849. newState.viewBoxW = vw;
  63850. newState.viewBoxH = vh;
  63851. int placementFlags = 0;
  63852. const String aspect (xml.getStringAttribute (T("preserveAspectRatio")));
  63853. if (aspect.containsIgnoreCase (T("none")))
  63854. {
  63855. placementFlags = RectanglePlacement::stretchToFit;
  63856. }
  63857. else
  63858. {
  63859. if (aspect.containsIgnoreCase (T("slice")))
  63860. placementFlags |= RectanglePlacement::fillDestination;
  63861. if (aspect.containsIgnoreCase (T("xMin")))
  63862. placementFlags |= RectanglePlacement::xLeft;
  63863. else if (aspect.containsIgnoreCase (T("xMax")))
  63864. placementFlags |= RectanglePlacement::xRight;
  63865. else
  63866. placementFlags |= RectanglePlacement::xMid;
  63867. if (aspect.containsIgnoreCase (T("yMin")))
  63868. placementFlags |= RectanglePlacement::yTop;
  63869. else if (aspect.containsIgnoreCase (T("yMax")))
  63870. placementFlags |= RectanglePlacement::yBottom;
  63871. else
  63872. placementFlags |= RectanglePlacement::yMid;
  63873. }
  63874. const RectanglePlacement placement (placementFlags);
  63875. newState.transform
  63876. = placement.getTransformToFit (vx, vy, vw, vh,
  63877. 0.0f, 0.0f, newState.width, newState.height)
  63878. .followedBy (newState.transform);
  63879. }
  63880. }
  63881. else
  63882. {
  63883. if (viewBoxW == 0)
  63884. newState.viewBoxW = newState.width;
  63885. if (viewBoxH == 0)
  63886. newState.viewBoxH = newState.height;
  63887. }
  63888. newState.parseSubElements (xml, drawable);
  63889. return drawable;
  63890. }
  63891. private:
  63892. const XmlElement* const topLevelXml;
  63893. float x, y, width, height, viewBoxW, viewBoxH;
  63894. AffineTransform transform;
  63895. String cssStyleText;
  63896. void parseSubElements (const XmlElement& xml, DrawableComposite* const parentDrawable)
  63897. {
  63898. forEachXmlChildElement (xml, e)
  63899. {
  63900. Drawable* d = 0;
  63901. if (e->hasTagName (T("g")))
  63902. d = parseGroupElement (*e);
  63903. else if (e->hasTagName (T("svg")))
  63904. d = parseSVGElement (*e);
  63905. else if (e->hasTagName (T("path")))
  63906. d = parsePath (*e);
  63907. else if (e->hasTagName (T("rect")))
  63908. d = parseRect (*e);
  63909. else if (e->hasTagName (T("circle")))
  63910. d = parseCircle (*e);
  63911. else if (e->hasTagName (T("ellipse")))
  63912. d = parseEllipse (*e);
  63913. else if (e->hasTagName (T("line")))
  63914. d = parseLine (*e);
  63915. else if (e->hasTagName (T("polyline")))
  63916. d = parsePolygon (*e, true);
  63917. else if (e->hasTagName (T("polygon")))
  63918. d = parsePolygon (*e, false);
  63919. else if (e->hasTagName (T("text")))
  63920. d = parseText (*e);
  63921. else if (e->hasTagName (T("switch")))
  63922. d = parseSwitch (*e);
  63923. else if (e->hasTagName (T("style")))
  63924. parseCSSStyle (*e);
  63925. parentDrawable->insertDrawable (d);
  63926. }
  63927. }
  63928. DrawableComposite* parseSwitch (const XmlElement& xml)
  63929. {
  63930. const XmlElement* const group = xml.getChildByName (T("g"));
  63931. if (group != 0)
  63932. return parseGroupElement (*group);
  63933. return 0;
  63934. }
  63935. DrawableComposite* parseGroupElement (const XmlElement& xml)
  63936. {
  63937. DrawableComposite* const drawable = new DrawableComposite();
  63938. drawable->setName (xml.getStringAttribute (T("id")));
  63939. if (xml.hasAttribute (T("transform")))
  63940. {
  63941. SVGState newState (*this);
  63942. newState.addTransform (xml);
  63943. newState.parseSubElements (xml, drawable);
  63944. }
  63945. else
  63946. {
  63947. parseSubElements (xml, drawable);
  63948. }
  63949. return drawable;
  63950. }
  63951. Drawable* parsePath (const XmlElement& xml) const
  63952. {
  63953. const String d (xml.getStringAttribute (T("d")).trimStart());
  63954. Path path;
  63955. if (getStyleAttribute (&xml, T("fill-rule")).trim().equalsIgnoreCase (T("evenodd")))
  63956. path.setUsingNonZeroWinding (false);
  63957. int index = 0;
  63958. float lastX = 0, lastY = 0;
  63959. float lastX2 = 0, lastY2 = 0;
  63960. tchar lastCommandChar = 0;
  63961. bool carryOn = true;
  63962. const String validCommandChars (T("MmLlHhVvCcSsQqTtAaZz"));
  63963. for (;;)
  63964. {
  63965. float x, y, x2, y2, x3, y3;
  63966. const bool isRelative = (d[index] >= 'a' && d[index] <= 'z');
  63967. if (validCommandChars.containsChar (d[index]))
  63968. lastCommandChar = d [index++];
  63969. switch (lastCommandChar)
  63970. {
  63971. case T('M'):
  63972. case T('m'):
  63973. case T('L'):
  63974. case T('l'):
  63975. if (parseCoords (d, x, y, index, false))
  63976. {
  63977. if (isRelative)
  63978. {
  63979. x += lastX;
  63980. y += lastY;
  63981. }
  63982. if (lastCommandChar == T('M') || lastCommandChar == T('m'))
  63983. path.startNewSubPath (x, y);
  63984. else
  63985. path.lineTo (x, y);
  63986. lastX2 = lastX;
  63987. lastY2 = lastY;
  63988. lastX = x;
  63989. lastY = y;
  63990. }
  63991. else
  63992. {
  63993. ++index;
  63994. }
  63995. break;
  63996. case T('H'):
  63997. case T('h'):
  63998. if (parseCoord (d, x, index, false, true))
  63999. {
  64000. if (isRelative)
  64001. x += lastX;
  64002. path.lineTo (x, lastY);
  64003. lastX2 = lastX;
  64004. lastX = x;
  64005. }
  64006. else
  64007. {
  64008. ++index;
  64009. }
  64010. break;
  64011. case T('V'):
  64012. case T('v'):
  64013. if (parseCoord (d, y, index, false, false))
  64014. {
  64015. if (isRelative)
  64016. y += lastY;
  64017. path.lineTo (lastX, y);
  64018. lastY2 = lastY;
  64019. lastY = y;
  64020. }
  64021. else
  64022. {
  64023. ++index;
  64024. }
  64025. break;
  64026. case T('C'):
  64027. case T('c'):
  64028. if (parseCoords (d, x, y, index, false)
  64029. && parseCoords (d, x2, y2, index, false)
  64030. && parseCoords (d, x3, y3, index, false))
  64031. {
  64032. if (isRelative)
  64033. {
  64034. x += lastX;
  64035. y += lastY;
  64036. x2 += lastX;
  64037. y2 += lastY;
  64038. x3 += lastX;
  64039. y3 += lastY;
  64040. }
  64041. path.cubicTo (x, y, x2, y2, x3, y3);
  64042. lastX2 = x2;
  64043. lastY2 = y2;
  64044. lastX = x3;
  64045. lastY = y3;
  64046. }
  64047. else
  64048. {
  64049. ++index;
  64050. }
  64051. break;
  64052. case T('S'):
  64053. case T('s'):
  64054. if (parseCoords (d, x, y, index, false)
  64055. && parseCoords (d, x3, y3, index, false))
  64056. {
  64057. if (isRelative)
  64058. {
  64059. x += lastX;
  64060. y += lastY;
  64061. x3 += lastX;
  64062. y3 += lastY;
  64063. }
  64064. x2 = lastX + (lastX - lastX2);
  64065. y2 = lastY + (lastY - lastY2);
  64066. path.cubicTo (x2, y2, x, y, x3, y3);
  64067. lastX2 = x2;
  64068. lastY2 = y2;
  64069. lastX = x3;
  64070. lastY = y3;
  64071. }
  64072. else
  64073. {
  64074. ++index;
  64075. }
  64076. break;
  64077. case T('Q'):
  64078. case T('q'):
  64079. if (parseCoords (d, x, y, index, false)
  64080. && parseCoords (d, x2, y2, index, false))
  64081. {
  64082. if (isRelative)
  64083. {
  64084. x += lastX;
  64085. y += lastY;
  64086. x2 += lastX;
  64087. y2 += lastY;
  64088. }
  64089. path.quadraticTo (x, y, x2, y2);
  64090. lastX2 = x;
  64091. lastY2 = y;
  64092. lastX = x2;
  64093. lastY = y2;
  64094. }
  64095. else
  64096. {
  64097. ++index;
  64098. }
  64099. break;
  64100. case T('T'):
  64101. case T('t'):
  64102. if (parseCoords (d, x, y, index, false))
  64103. {
  64104. if (isRelative)
  64105. {
  64106. x += lastX;
  64107. y += lastY;
  64108. }
  64109. x2 = lastX + (lastX - lastX2);
  64110. y2 = lastY + (lastY - lastY2);
  64111. path.quadraticTo (x2, y2, x, y);
  64112. lastX2 = x2;
  64113. lastY2 = y2;
  64114. lastX = x;
  64115. lastY = y;
  64116. }
  64117. else
  64118. {
  64119. ++index;
  64120. }
  64121. break;
  64122. case T('A'):
  64123. case T('a'):
  64124. if (parseCoords (d, x, y, index, false))
  64125. {
  64126. String num;
  64127. if (parseNextNumber (d, num, index, false))
  64128. {
  64129. const float angle = num.getFloatValue() * (180.0f / float_Pi);
  64130. if (parseNextNumber (d, num, index, false))
  64131. {
  64132. const bool largeArc = num.getIntValue() != 0;
  64133. if (parseNextNumber (d, num, index, false))
  64134. {
  64135. const bool sweep = num.getIntValue() != 0;
  64136. if (parseCoords (d, x2, y2, index, false))
  64137. {
  64138. if (isRelative)
  64139. {
  64140. x2 += lastX;
  64141. y2 += lastY;
  64142. }
  64143. if (lastX != x2 || lastY != y2)
  64144. {
  64145. double centreX, centreY, startAngle, deltaAngle;
  64146. double rx = x, ry = y;
  64147. endpointToCentreParameters (lastX, lastY, x2, y2,
  64148. angle, largeArc, sweep,
  64149. rx, ry, centreX, centreY,
  64150. startAngle, deltaAngle);
  64151. path.addCentredArc ((float) centreX, (float) centreY,
  64152. (float) rx, (float) ry,
  64153. angle, (float) startAngle, (float) (startAngle + deltaAngle),
  64154. false);
  64155. path.lineTo (x2, y2);
  64156. }
  64157. lastX2 = lastX;
  64158. lastY2 = lastY;
  64159. lastX = x2;
  64160. lastY = y2;
  64161. }
  64162. }
  64163. }
  64164. }
  64165. }
  64166. else
  64167. {
  64168. ++index;
  64169. }
  64170. break;
  64171. case T('Z'):
  64172. case T('z'):
  64173. path.closeSubPath();
  64174. while (CharacterFunctions::isWhitespace (d [index]))
  64175. ++index;
  64176. break;
  64177. default:
  64178. carryOn = false;
  64179. break;
  64180. }
  64181. if (! carryOn)
  64182. break;
  64183. }
  64184. return parseShape (xml, path);
  64185. }
  64186. Drawable* parseRect (const XmlElement& xml) const
  64187. {
  64188. Path rect;
  64189. const bool hasRX = xml.hasAttribute (T("rx"));
  64190. const bool hasRY = xml.hasAttribute (T("ry"));
  64191. if (hasRX || hasRY)
  64192. {
  64193. float rx = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  64194. float ry = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  64195. if (! hasRX)
  64196. rx = ry;
  64197. else if (! hasRY)
  64198. ry = rx;
  64199. rect.addRoundedRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  64200. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  64201. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  64202. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH),
  64203. rx, ry);
  64204. }
  64205. else
  64206. {
  64207. rect.addRectangle (getCoordLength (xml.getStringAttribute (T("x")), viewBoxW),
  64208. getCoordLength (xml.getStringAttribute (T("y")), viewBoxH),
  64209. getCoordLength (xml.getStringAttribute (T("width")), viewBoxW),
  64210. getCoordLength (xml.getStringAttribute (T("height")), viewBoxH));
  64211. }
  64212. return parseShape (xml, rect);
  64213. }
  64214. Drawable* parseCircle (const XmlElement& xml) const
  64215. {
  64216. Path circle;
  64217. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  64218. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  64219. const float radius = getCoordLength (xml.getStringAttribute (T("r")), viewBoxW);
  64220. circle.addEllipse (cx - radius, cy - radius, radius * 2.0f, radius * 2.0f);
  64221. return parseShape (xml, circle);
  64222. }
  64223. Drawable* parseEllipse (const XmlElement& xml) const
  64224. {
  64225. Path ellipse;
  64226. const float cx = getCoordLength (xml.getStringAttribute (T("cx")), viewBoxW);
  64227. const float cy = getCoordLength (xml.getStringAttribute (T("cy")), viewBoxH);
  64228. const float radiusX = getCoordLength (xml.getStringAttribute (T("rx")), viewBoxW);
  64229. const float radiusY = getCoordLength (xml.getStringAttribute (T("ry")), viewBoxH);
  64230. ellipse.addEllipse (cx - radiusX, cy - radiusY, radiusX * 2.0f, radiusY * 2.0f);
  64231. return parseShape (xml, ellipse);
  64232. }
  64233. Drawable* parseLine (const XmlElement& xml) const
  64234. {
  64235. Path line;
  64236. const float x1 = getCoordLength (xml.getStringAttribute (T("x1")), viewBoxW);
  64237. const float y1 = getCoordLength (xml.getStringAttribute (T("y1")), viewBoxH);
  64238. const float x2 = getCoordLength (xml.getStringAttribute (T("x2")), viewBoxW);
  64239. const float y2 = getCoordLength (xml.getStringAttribute (T("y2")), viewBoxH);
  64240. line.startNewSubPath (x1, y1);
  64241. line.lineTo (x2, y2);
  64242. return parseShape (xml, line);
  64243. }
  64244. Drawable* parsePolygon (const XmlElement& xml, const bool isPolyline) const
  64245. {
  64246. const String points (xml.getStringAttribute (T("points")));
  64247. Path path;
  64248. int index = 0;
  64249. float x, y;
  64250. if (parseCoords (points, x, y, index, true))
  64251. {
  64252. float firstX = x;
  64253. float firstY = y;
  64254. float lastX = 0, lastY = 0;
  64255. path.startNewSubPath (x, y);
  64256. while (parseCoords (points, x, y, index, true))
  64257. {
  64258. lastX = x;
  64259. lastY = y;
  64260. path.lineTo (x, y);
  64261. }
  64262. if ((! isPolyline) || (firstX == lastX && firstY == lastY))
  64263. path.closeSubPath();
  64264. }
  64265. return parseShape (xml, path);
  64266. }
  64267. Drawable* parseShape (const XmlElement& xml, Path& path,
  64268. const bool parseTransform = true) const
  64269. {
  64270. if (parseTransform && xml.hasAttribute (T("transform")))
  64271. {
  64272. SVGState newState (*this);
  64273. newState.addTransform (xml);
  64274. return newState.parseShape (xml, path, false);
  64275. }
  64276. DrawablePath* dp = new DrawablePath();
  64277. dp->setSolidFill (Colours::transparentBlack);
  64278. path.applyTransform (transform);
  64279. dp->setPath (path);
  64280. Path::Iterator iter (path);
  64281. bool containsClosedSubPath = false;
  64282. while (iter.next())
  64283. {
  64284. if (iter.elementType == Path::Iterator::closePath)
  64285. {
  64286. containsClosedSubPath = true;
  64287. break;
  64288. }
  64289. }
  64290. Brush* const fillBrush
  64291. = getBrushForFill (path,
  64292. getStyleAttribute (&xml, T("fill")),
  64293. getStyleAttribute (&xml, T("fill-opacity")),
  64294. getStyleAttribute (&xml, T("opacity")),
  64295. containsClosedSubPath ? Colours::black
  64296. : Colours::transparentBlack);
  64297. if (fillBrush != 0)
  64298. {
  64299. if (! fillBrush->isInvisible())
  64300. {
  64301. fillBrush->applyTransform (transform);
  64302. dp->setFillBrush (*fillBrush);
  64303. }
  64304. delete fillBrush;
  64305. }
  64306. const String strokeType (getStyleAttribute (&xml, T("stroke")));
  64307. if (strokeType.isNotEmpty() && ! strokeType.equalsIgnoreCase (T("none")))
  64308. {
  64309. Brush* const strokeBrush
  64310. = getBrushForFill (path, strokeType,
  64311. getStyleAttribute (&xml, T("stroke-opacity")),
  64312. getStyleAttribute (&xml, T("opacity")),
  64313. Colours::transparentBlack);
  64314. if (strokeBrush != 0)
  64315. {
  64316. const PathStrokeType stroke (getStrokeFor (&xml));
  64317. if (! strokeBrush->isInvisible())
  64318. {
  64319. strokeBrush->applyTransform (transform);
  64320. dp->setOutline (stroke, *strokeBrush);
  64321. }
  64322. delete strokeBrush;
  64323. }
  64324. }
  64325. return dp;
  64326. }
  64327. const XmlElement* findLinkedElement (const XmlElement* e) const
  64328. {
  64329. const String id (e->getStringAttribute (T("xlink:href")));
  64330. if (! id.startsWithChar (T('#')))
  64331. return 0;
  64332. return findElementForId (topLevelXml, id.substring (1));
  64333. }
  64334. void addGradientStopsIn (ColourGradient& cg, const XmlElement* const fillXml) const
  64335. {
  64336. if (fillXml == 0)
  64337. return;
  64338. forEachXmlChildElementWithTagName (*fillXml, e, T("stop"))
  64339. {
  64340. int index = 0;
  64341. Colour col (parseColour (getStyleAttribute (e, T("stop-color")), index, Colours::black));
  64342. const String opacity (getStyleAttribute (e, T("stop-opacity"), T("1")));
  64343. col = col.withMultipliedAlpha (jlimit (0.0f, 1.0f, opacity.getFloatValue()));
  64344. double offset = e->getDoubleAttribute (T("offset"));
  64345. if (e->getStringAttribute (T("offset")).containsChar (T('%')))
  64346. offset *= 0.01;
  64347. cg.addColour (jlimit (0.0, 1.0, offset), col);
  64348. }
  64349. }
  64350. Brush* getBrushForFill (const Path& path,
  64351. const String& fill,
  64352. const String& fillOpacity,
  64353. const String& overallOpacity,
  64354. const Colour& defaultColour) const
  64355. {
  64356. float opacity = 1.0f;
  64357. if (overallOpacity.isNotEmpty())
  64358. opacity = jlimit (0.0f, 1.0f, overallOpacity.getFloatValue());
  64359. if (fillOpacity.isNotEmpty())
  64360. opacity *= (jlimit (0.0f, 1.0f, fillOpacity.getFloatValue()));
  64361. if (fill.startsWithIgnoreCase (T("url")))
  64362. {
  64363. const String id (fill.fromFirstOccurrenceOf (T("#"), false, false)
  64364. .upToLastOccurrenceOf (T(")"), false, false).trim());
  64365. const XmlElement* const fillXml = findElementForId (topLevelXml, id);
  64366. if (fillXml != 0
  64367. && (fillXml->hasTagName (T("linearGradient"))
  64368. || fillXml->hasTagName (T("radialGradient"))))
  64369. {
  64370. const XmlElement* inheritedFrom = findLinkedElement (fillXml);
  64371. ColourGradient cg;
  64372. addGradientStopsIn (cg, inheritedFrom);
  64373. addGradientStopsIn (cg, fillXml);
  64374. if (cg.getNumColours() > 0)
  64375. {
  64376. cg.addColour (0.0, cg.getColour (0));
  64377. cg.addColour (1.0, cg.getColour (cg.getNumColours() - 1));
  64378. }
  64379. else
  64380. {
  64381. cg.addColour (0.0, Colours::black);
  64382. cg.addColour (1.0, Colours::black);
  64383. }
  64384. if (overallOpacity.isNotEmpty())
  64385. cg.multiplyOpacity (overallOpacity.getFloatValue());
  64386. jassert (cg.getNumColours() > 0);
  64387. cg.isRadial = fillXml->hasTagName (T("radialGradient"));
  64388. cg.transform = parseTransform (fillXml->getStringAttribute (T("gradientTransform")));
  64389. float width = viewBoxW;
  64390. float height = viewBoxH;
  64391. float dx = 0.0;
  64392. float dy = 0.0;
  64393. const bool userSpace = fillXml->getStringAttribute (T("gradientUnits")).equalsIgnoreCase (T("userSpaceOnUse"));
  64394. if (! userSpace)
  64395. path.getBounds (dx, dy, width, height);
  64396. if (cg.isRadial)
  64397. {
  64398. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("cx"), T("50%")), width);
  64399. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("cy"), T("50%")), height);
  64400. const float radius = getCoordLength (fillXml->getStringAttribute (T("r"), T("50%")), width);
  64401. cg.x2 = cg.x1 + radius;
  64402. cg.y2 = cg.y1;
  64403. //xxx (the fx, fy focal point isn't handled properly here..)
  64404. }
  64405. else
  64406. {
  64407. cg.x1 = dx + getCoordLength (fillXml->getStringAttribute (T("x1"), T("0%")), width);
  64408. cg.y1 = dy + getCoordLength (fillXml->getStringAttribute (T("y1"), T("0%")), height);
  64409. cg.x2 = dx + getCoordLength (fillXml->getStringAttribute (T("x2"), T("100%")), width);
  64410. cg.y2 = dy + getCoordLength (fillXml->getStringAttribute (T("y2"), T("0%")), height);
  64411. if (cg.x1 == cg.x2 && cg.y1 == cg.y2)
  64412. return new SolidColourBrush (cg.getColour (cg.getNumColours() - 1));
  64413. }
  64414. return new GradientBrush (cg);
  64415. }
  64416. }
  64417. if (fill.equalsIgnoreCase (T("none")))
  64418. return new SolidColourBrush (Colours::transparentBlack);
  64419. int i = 0;
  64420. Colour colour (parseColour (fill, i, defaultColour));
  64421. colour = colour.withMultipliedAlpha (opacity);
  64422. return new SolidColourBrush (colour);
  64423. }
  64424. const PathStrokeType getStrokeFor (const XmlElement* const xml) const
  64425. {
  64426. const String width (getStyleAttribute (xml, T("stroke-width")));
  64427. const String cap (getStyleAttribute (xml, T("stroke-linecap")));
  64428. const String join (getStyleAttribute (xml, T("stroke-linejoin")));
  64429. //const String mitreLimit (getStyleAttribute (xml, T("stroke-miterlimit")));
  64430. //const String dashArray (getStyleAttribute (xml, T("stroke-dasharray")));
  64431. //const String dashOffset (getStyleAttribute (xml, T("stroke-dashoffset")));
  64432. PathStrokeType::JointStyle joinStyle = PathStrokeType::mitered;
  64433. PathStrokeType::EndCapStyle capStyle = PathStrokeType::butt;
  64434. if (join.equalsIgnoreCase (T("round")))
  64435. joinStyle = PathStrokeType::curved;
  64436. else if (join.equalsIgnoreCase (T("bevel")))
  64437. joinStyle = PathStrokeType::beveled;
  64438. if (cap.equalsIgnoreCase (T("round")))
  64439. capStyle = PathStrokeType::rounded;
  64440. else if (cap.equalsIgnoreCase (T("square")))
  64441. capStyle = PathStrokeType::square;
  64442. float ox = 0.0f, oy = 0.0f;
  64443. transform.transformPoint (ox, oy);
  64444. float x = getCoordLength (width, viewBoxW), y = 0.0f;
  64445. transform.transformPoint (x, y);
  64446. return PathStrokeType (width.isNotEmpty() ? juce_hypotf (x - ox, y - oy) : 1.0f,
  64447. joinStyle, capStyle);
  64448. }
  64449. Drawable* parseText (const XmlElement& xml)
  64450. {
  64451. Array <float> xCoords, yCoords, dxCoords, dyCoords;
  64452. getCoordList (xCoords, getInheritedAttribute (&xml, T("x")), true, true);
  64453. getCoordList (yCoords, getInheritedAttribute (&xml, T("y")), true, false);
  64454. getCoordList (dxCoords, getInheritedAttribute (&xml, T("dx")), true, true);
  64455. getCoordList (dyCoords, getInheritedAttribute (&xml, T("dy")), true, false);
  64456. //xxx not done text yet!
  64457. forEachXmlChildElement (xml, e)
  64458. {
  64459. if (e->isTextElement())
  64460. {
  64461. const String text (e->getText());
  64462. Path path;
  64463. Drawable* s = parseShape (*e, path);
  64464. delete s;
  64465. }
  64466. else if (e->hasTagName (T("tspan")))
  64467. {
  64468. Drawable* s = parseText (*e);
  64469. delete s;
  64470. }
  64471. }
  64472. return 0;
  64473. }
  64474. void addTransform (const XmlElement& xml)
  64475. {
  64476. transform = parseTransform (xml.getStringAttribute (T("transform")))
  64477. .followedBy (transform);
  64478. }
  64479. bool parseCoord (const String& s, float& value, int& index,
  64480. const bool allowUnits, const bool isX) const
  64481. {
  64482. String number;
  64483. if (! parseNextNumber (s, number, index, allowUnits))
  64484. {
  64485. value = 0;
  64486. return false;
  64487. }
  64488. value = getCoordLength (number, isX ? viewBoxW : viewBoxH);
  64489. return true;
  64490. }
  64491. bool parseCoords (const String& s, float& x, float& y,
  64492. int& index, const bool allowUnits) const
  64493. {
  64494. return parseCoord (s, x, index, allowUnits, true)
  64495. && parseCoord (s, y, index, allowUnits, false);
  64496. }
  64497. float getCoordLength (const String& s, const float sizeForProportions) const
  64498. {
  64499. float n = s.getFloatValue();
  64500. const int len = s.length();
  64501. if (len > 2)
  64502. {
  64503. const float dpi = 96.0f;
  64504. const tchar n1 = s [len - 2];
  64505. const tchar n2 = s [len - 1];
  64506. if (n1 == T('i') && n2 == T('n'))
  64507. n *= dpi;
  64508. else if (n1 == T('m') && n2 == T('m'))
  64509. n *= dpi / 25.4f;
  64510. else if (n1 == T('c') && n2 == T('m'))
  64511. n *= dpi / 2.54f;
  64512. else if (n1 == T('p') && n2 == T('c'))
  64513. n *= 15.0f;
  64514. else if (n2 == T('%'))
  64515. n *= 0.01f * sizeForProportions;
  64516. }
  64517. return n;
  64518. }
  64519. void getCoordList (Array <float>& coords, const String& list,
  64520. const bool allowUnits, const bool isX) const
  64521. {
  64522. int index = 0;
  64523. float value;
  64524. while (parseCoord (list, value, index, allowUnits, isX))
  64525. coords.add (value);
  64526. }
  64527. void parseCSSStyle (const XmlElement& xml)
  64528. {
  64529. cssStyleText = xml.getAllSubText() + T("\n") + cssStyleText;
  64530. }
  64531. const String getStyleAttribute (const XmlElement* xml, const String& attributeName,
  64532. const String& defaultValue = String::empty) const
  64533. {
  64534. if (xml->hasAttribute (attributeName))
  64535. return xml->getStringAttribute (attributeName, defaultValue);
  64536. const String styleAtt (xml->getStringAttribute (T("style")));
  64537. if (styleAtt.isNotEmpty())
  64538. {
  64539. const String value (getAttributeFromStyleList (styleAtt, attributeName, String::empty));
  64540. if (value.isNotEmpty())
  64541. return value;
  64542. }
  64543. else if (xml->hasAttribute (T("class")))
  64544. {
  64545. const String className (T(".") + xml->getStringAttribute (T("class")));
  64546. int index = cssStyleText.indexOfIgnoreCase (className + T(" "));
  64547. if (index < 0)
  64548. index = cssStyleText.indexOfIgnoreCase (className + T("{"));
  64549. if (index >= 0)
  64550. {
  64551. const int openBracket = cssStyleText.indexOfChar (index, T('{'));
  64552. if (openBracket > index)
  64553. {
  64554. const int closeBracket = cssStyleText.indexOfChar (openBracket, T('}'));
  64555. if (closeBracket > openBracket)
  64556. {
  64557. const String value (getAttributeFromStyleList (cssStyleText.substring (openBracket + 1, closeBracket), attributeName, defaultValue));
  64558. if (value.isNotEmpty())
  64559. return value;
  64560. }
  64561. }
  64562. }
  64563. }
  64564. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  64565. if (xml != 0)
  64566. return getStyleAttribute (xml, attributeName, defaultValue);
  64567. return defaultValue;
  64568. }
  64569. const String getInheritedAttribute (const XmlElement* xml, const String& attributeName) const
  64570. {
  64571. if (xml->hasAttribute (attributeName))
  64572. return xml->getStringAttribute (attributeName);
  64573. xml = const_cast <XmlElement*> (topLevelXml)->findParentElementOf (xml);
  64574. if (xml != 0)
  64575. return getInheritedAttribute (xml, attributeName);
  64576. return String::empty;
  64577. }
  64578. static bool isIdentifierChar (const tchar c)
  64579. {
  64580. return CharacterFunctions::isLetter (c) || c == T('-');
  64581. }
  64582. static const String getAttributeFromStyleList (const String& list, const String& attributeName, const String& defaultValue)
  64583. {
  64584. int i = 0;
  64585. for (;;)
  64586. {
  64587. i = list.indexOf (i, attributeName);
  64588. if (i < 0)
  64589. break;
  64590. if ((i == 0 || (i > 0 && ! isIdentifierChar (list [i - 1])))
  64591. && ! isIdentifierChar (list [i + attributeName.length()]))
  64592. {
  64593. i = list.indexOfChar (i, T(':'));
  64594. if (i < 0)
  64595. break;
  64596. int end = list.indexOfChar (i, T(';'));
  64597. if (end < 0)
  64598. end = 0x7ffff;
  64599. return list.substring (i + 1, end).trim();
  64600. }
  64601. ++i;
  64602. }
  64603. return defaultValue;
  64604. }
  64605. static bool parseNextNumber (const String& source, String& value, int& index, const bool allowUnits)
  64606. {
  64607. const tchar* const s = (const tchar*) source;
  64608. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  64609. ++index;
  64610. int start = index;
  64611. if (CharacterFunctions::isDigit (s[index]) || s[index] == T('.') || s[index] == T('-'))
  64612. ++index;
  64613. while (CharacterFunctions::isDigit (s[index]) || s[index] == T('.'))
  64614. ++index;
  64615. if ((s[index] == T('e') || s[index] == T('E'))
  64616. && (CharacterFunctions::isDigit (s[index + 1])
  64617. || s[index + 1] == T('-')
  64618. || s[index + 1] == T('+')))
  64619. {
  64620. index += 2;
  64621. while (CharacterFunctions::isDigit (s[index]))
  64622. ++index;
  64623. }
  64624. if (allowUnits)
  64625. {
  64626. while (CharacterFunctions::isLetter (s[index]))
  64627. ++index;
  64628. }
  64629. if (index == start)
  64630. return false;
  64631. value = String (s + start, index - start);
  64632. while (CharacterFunctions::isWhitespace (s[index]) || s[index] == T(','))
  64633. ++index;
  64634. return true;
  64635. }
  64636. static const Colour parseColour (const String& s, int& index, const Colour& defaultColour)
  64637. {
  64638. if (s [index] == T('#'))
  64639. {
  64640. uint32 hex [6];
  64641. zeromem (hex, sizeof (hex));
  64642. int numChars = 0;
  64643. for (int i = 6; --i >= 0;)
  64644. {
  64645. const int hexValue = CharacterFunctions::getHexDigitValue (s [++index]);
  64646. if (hexValue >= 0)
  64647. hex [numChars++] = hexValue;
  64648. else
  64649. break;
  64650. }
  64651. if (numChars <= 3)
  64652. return Colour ((uint8) (hex [0] * 0x11),
  64653. (uint8) (hex [1] * 0x11),
  64654. (uint8) (hex [2] * 0x11));
  64655. else
  64656. return Colour ((uint8) ((hex [0] << 4) + hex [1]),
  64657. (uint8) ((hex [2] << 4) + hex [3]),
  64658. (uint8) ((hex [4] << 4) + hex [5]));
  64659. }
  64660. else if (s [index] == T('r')
  64661. && s [index + 1] == T('g')
  64662. && s [index + 2] == T('b'))
  64663. {
  64664. const int openBracket = s.indexOfChar (index, T('('));
  64665. const int closeBracket = s.indexOfChar (openBracket, T(')'));
  64666. if (openBracket >= 3 && closeBracket > openBracket)
  64667. {
  64668. index = closeBracket;
  64669. StringArray tokens;
  64670. tokens.addTokens (s.substring (openBracket + 1, closeBracket), T(","), T(""));
  64671. tokens.trim();
  64672. tokens.removeEmptyStrings();
  64673. if (tokens[0].containsChar (T('%')))
  64674. return Colour ((uint8) roundDoubleToInt (2.55 * tokens[0].getDoubleValue()),
  64675. (uint8) roundDoubleToInt (2.55 * tokens[1].getDoubleValue()),
  64676. (uint8) roundDoubleToInt (2.55 * tokens[2].getDoubleValue()));
  64677. else
  64678. return Colour ((uint8) tokens[0].getIntValue(),
  64679. (uint8) tokens[1].getIntValue(),
  64680. (uint8) tokens[2].getIntValue());
  64681. }
  64682. }
  64683. return Colours::findColourForName (s, defaultColour);
  64684. }
  64685. static const AffineTransform parseTransform (String t)
  64686. {
  64687. AffineTransform result;
  64688. while (t.isNotEmpty())
  64689. {
  64690. StringArray tokens;
  64691. tokens.addTokens (t.fromFirstOccurrenceOf (T("("), false, false)
  64692. .upToFirstOccurrenceOf (T(")"), false, false),
  64693. T(", "), 0);
  64694. tokens.removeEmptyStrings (true);
  64695. float numbers [6];
  64696. for (int i = 0; i < 6; ++i)
  64697. numbers[i] = tokens[i].getFloatValue();
  64698. AffineTransform trans;
  64699. if (t.startsWithIgnoreCase (T("matrix")))
  64700. {
  64701. trans = AffineTransform (numbers[0], numbers[2], numbers[4],
  64702. numbers[1], numbers[3], numbers[5]);
  64703. }
  64704. else if (t.startsWithIgnoreCase (T("translate")))
  64705. {
  64706. trans = trans.translated (numbers[0], numbers[1]);
  64707. }
  64708. else if (t.startsWithIgnoreCase (T("scale")))
  64709. {
  64710. if (tokens.size() == 1)
  64711. trans = trans.scaled (numbers[0], numbers[0]);
  64712. else
  64713. trans = trans.scaled (numbers[0], numbers[1]);
  64714. }
  64715. else if (t.startsWithIgnoreCase (T("rotate")))
  64716. {
  64717. if (tokens.size() != 3)
  64718. trans = trans.rotated (numbers[0] / (180.0f / float_Pi));
  64719. else
  64720. trans = trans.rotated (numbers[0] / (180.0f / float_Pi),
  64721. numbers[1], numbers[2]);
  64722. }
  64723. else if (t.startsWithIgnoreCase (T("skewX")))
  64724. {
  64725. trans = AffineTransform (1.0f, tanf (numbers[0] * (float_Pi / 180.0f)), 0.0f,
  64726. 0.0f, 1.0f, 0.0f);
  64727. }
  64728. else if (t.startsWithIgnoreCase (T("skewY")))
  64729. {
  64730. trans = AffineTransform (1.0f, 0.0f, 0.0f,
  64731. tanf (numbers[0] * (float_Pi / 180.0f)), 1.0f, 0.0f);
  64732. }
  64733. result = trans.followedBy (result);
  64734. t = t.fromFirstOccurrenceOf (T(")"), false, false).trimStart();
  64735. }
  64736. return result;
  64737. }
  64738. static void endpointToCentreParameters (const double x1, const double y1,
  64739. const double x2, const double y2,
  64740. const double angle,
  64741. const bool largeArc, const bool sweep,
  64742. double& rx, double& ry,
  64743. double& centreX, double& centreY,
  64744. double& startAngle, double& deltaAngle)
  64745. {
  64746. const double midX = (x1 - x2) * 0.5;
  64747. const double midY = (y1 - y2) * 0.5;
  64748. const double cosAngle = cos (angle);
  64749. const double sinAngle = sin (angle);
  64750. const double xp = cosAngle * midX + sinAngle * midY;
  64751. const double yp = cosAngle * midY - sinAngle * midX;
  64752. const double xp2 = xp * xp;
  64753. const double yp2 = yp * yp;
  64754. double rx2 = rx * rx;
  64755. double ry2 = ry * ry;
  64756. const double s = (xp2 / rx2) + (yp2 / ry2);
  64757. double c;
  64758. if (s <= 1.0)
  64759. {
  64760. c = sqrt (jmax (0.0, ((rx2 * ry2) - (rx2 * yp2) - (ry2 * xp2))
  64761. / (( rx2 * yp2) + (ry2 * xp2))));
  64762. if (largeArc == sweep)
  64763. c = -c;
  64764. }
  64765. else
  64766. {
  64767. const double s2 = sqrt (s);
  64768. rx *= s2;
  64769. ry *= s2;
  64770. rx2 = rx * rx;
  64771. ry2 = ry * ry;
  64772. c = 0;
  64773. }
  64774. const double cpx = ((rx * yp) / ry) * c;
  64775. const double cpy = ((-ry * xp) / rx) * c;
  64776. centreX = ((x1 + x2) * 0.5) + (cosAngle * cpx) - (sinAngle * cpy);
  64777. centreY = ((y1 + y2) * 0.5) + (sinAngle * cpx) + (cosAngle * cpy);
  64778. const double ux = (xp - cpx) / rx;
  64779. const double uy = (yp - cpy) / ry;
  64780. const double vx = (-xp - cpx) / rx;
  64781. const double vy = (-yp - cpy) / ry;
  64782. const double length = juce_hypot (ux, uy);
  64783. startAngle = acos (jlimit (-1.0, 1.0, ux / length));
  64784. if (uy < 0)
  64785. startAngle = -startAngle;
  64786. startAngle += double_Pi * 0.5;
  64787. deltaAngle = acos (jlimit (-1.0, 1.0, ((ux * vx) + (uy * vy))
  64788. / (length * juce_hypot (vx, vy))));
  64789. if ((ux * vy) - (uy * vx) < 0)
  64790. deltaAngle = -deltaAngle;
  64791. if (sweep)
  64792. {
  64793. if (deltaAngle < 0)
  64794. deltaAngle += double_Pi * 2.0;
  64795. }
  64796. else
  64797. {
  64798. if (deltaAngle > 0)
  64799. deltaAngle -= double_Pi * 2.0;
  64800. }
  64801. deltaAngle = fmod (deltaAngle, double_Pi * 2.0);
  64802. }
  64803. static const XmlElement* findElementForId (const XmlElement* const parent, const String& id)
  64804. {
  64805. forEachXmlChildElement (*parent, e)
  64806. {
  64807. if (e->compareAttribute (T("id"), id))
  64808. return e;
  64809. const XmlElement* const found = findElementForId (e, id);
  64810. if (found != 0)
  64811. return found;
  64812. }
  64813. return 0;
  64814. }
  64815. const SVGState& operator= (const SVGState&);
  64816. };
  64817. Drawable* Drawable::createFromSVG (const XmlElement& svgDocument)
  64818. {
  64819. SVGState state (&svgDocument);
  64820. return state.parseSVGElement (svgDocument);
  64821. }
  64822. END_JUCE_NAMESPACE
  64823. /********* End of inlined file: juce_SVGParser.cpp *********/
  64824. /********* Start of inlined file: juce_DropShadowEffect.cpp *********/
  64825. BEGIN_JUCE_NAMESPACE
  64826. #if JUCE_MSVC
  64827. #pragma optimize ("t", on) // try to avoid slowing everything down in debug builds
  64828. #endif
  64829. DropShadowEffect::DropShadowEffect()
  64830. : offsetX (0),
  64831. offsetY (0),
  64832. radius (4),
  64833. opacity (0.6f)
  64834. {
  64835. }
  64836. DropShadowEffect::~DropShadowEffect()
  64837. {
  64838. }
  64839. void DropShadowEffect::setShadowProperties (const float newRadius,
  64840. const float newOpacity,
  64841. const int newShadowOffsetX,
  64842. const int newShadowOffsetY)
  64843. {
  64844. radius = jmax (1.1f, newRadius);
  64845. offsetX = newShadowOffsetX;
  64846. offsetY = newShadowOffsetY;
  64847. opacity = newOpacity;
  64848. }
  64849. void DropShadowEffect::applyEffect (Image& image, Graphics& g)
  64850. {
  64851. const int w = image.getWidth();
  64852. const int h = image.getHeight();
  64853. int lineStride, pixelStride;
  64854. const PixelARGB* srcPixels = (const PixelARGB*) image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(), lineStride, pixelStride);
  64855. Image shadowImage (Image::SingleChannel, w, h, false);
  64856. int destStride, destPixelStride;
  64857. uint8* const shadowChannel = (uint8*) shadowImage.lockPixelDataReadWrite (0, 0, w, h, destStride, destPixelStride);
  64858. const int filter = roundFloatToInt (63.0f / radius);
  64859. const int radiusMinus1 = roundFloatToInt ((radius - 1.0f) * 63.0f);
  64860. for (int x = w; --x >= 0;)
  64861. {
  64862. int shadowAlpha = 0;
  64863. const PixelARGB* src = srcPixels + x;
  64864. uint8* shadowPix = shadowChannel + x;
  64865. for (int y = h; --y >= 0;)
  64866. {
  64867. shadowAlpha = ((shadowAlpha * radiusMinus1 + (src->getAlpha() << 6)) * filter) >> 12;
  64868. *shadowPix = (uint8) shadowAlpha;
  64869. src = (const PixelARGB*) (((const uint8*) src) + lineStride);
  64870. shadowPix += destStride;
  64871. }
  64872. }
  64873. for (int y = h; --y >= 0;)
  64874. {
  64875. int shadowAlpha = 0;
  64876. uint8* shadowPix = shadowChannel + y * destStride;
  64877. for (int x = w; --x >= 0;)
  64878. {
  64879. shadowAlpha = ((shadowAlpha * radiusMinus1 + (*shadowPix << 6)) * filter) >> 12;
  64880. *shadowPix++ = (uint8) shadowAlpha;
  64881. }
  64882. }
  64883. image.releasePixelDataReadOnly (srcPixels);
  64884. shadowImage.releasePixelDataReadWrite (shadowChannel);
  64885. g.setColour (Colours::black.withAlpha (opacity));
  64886. g.drawImageAt (&shadowImage, offsetX, offsetY, true);
  64887. g.setOpacity (1.0f);
  64888. g.drawImageAt (&image, 0, 0);
  64889. }
  64890. END_JUCE_NAMESPACE
  64891. /********* End of inlined file: juce_DropShadowEffect.cpp *********/
  64892. /********* Start of inlined file: juce_GlowEffect.cpp *********/
  64893. BEGIN_JUCE_NAMESPACE
  64894. GlowEffect::GlowEffect()
  64895. : radius (2.0f),
  64896. colour (Colours::white)
  64897. {
  64898. }
  64899. GlowEffect::~GlowEffect()
  64900. {
  64901. }
  64902. void GlowEffect::setGlowProperties (const float newRadius,
  64903. const Colour& newColour)
  64904. {
  64905. radius = newRadius;
  64906. colour = newColour;
  64907. }
  64908. void GlowEffect::applyEffect (Image& image, Graphics& g)
  64909. {
  64910. const int w = image.getWidth();
  64911. const int h = image.getHeight();
  64912. Image temp (image.getFormat(), w, h, true);
  64913. ImageConvolutionKernel blurKernel (roundFloatToInt (radius * 2.0f));
  64914. blurKernel.createGaussianBlur (radius);
  64915. blurKernel.rescaleAllValues (radius);
  64916. blurKernel.applyToImage (temp, &image, 0, 0, w, h);
  64917. g.setColour (colour);
  64918. g.drawImageAt (&temp, 0, 0, true);
  64919. g.setOpacity (1.0f);
  64920. g.drawImageAt (&image, 0, 0, false);
  64921. }
  64922. END_JUCE_NAMESPACE
  64923. /********* End of inlined file: juce_GlowEffect.cpp *********/
  64924. /********* Start of inlined file: juce_ReduceOpacityEffect.cpp *********/
  64925. BEGIN_JUCE_NAMESPACE
  64926. ReduceOpacityEffect::ReduceOpacityEffect (const float opacity_)
  64927. : opacity (opacity_)
  64928. {
  64929. }
  64930. ReduceOpacityEffect::~ReduceOpacityEffect()
  64931. {
  64932. }
  64933. void ReduceOpacityEffect::setOpacity (const float newOpacity)
  64934. {
  64935. opacity = jlimit (0.0f, 1.0f, newOpacity);
  64936. }
  64937. void ReduceOpacityEffect::applyEffect (Image& image, Graphics& g)
  64938. {
  64939. g.setOpacity (opacity);
  64940. g.drawImageAt (&image, 0, 0);
  64941. }
  64942. END_JUCE_NAMESPACE
  64943. /********* End of inlined file: juce_ReduceOpacityEffect.cpp *********/
  64944. /********* Start of inlined file: juce_Font.cpp *********/
  64945. BEGIN_JUCE_NAMESPACE
  64946. static const float minFontHeight = 0.1f;
  64947. static const float maxFontHeight = 10000.0f;
  64948. static const float defaultFontHeight = 14.0f;
  64949. static String defaultSans, defaultSerif, defaultFixed, fallbackFont;
  64950. Font::Font() throw()
  64951. : typefaceName (defaultSans),
  64952. height (defaultFontHeight),
  64953. horizontalScale (1.0f),
  64954. kerning (0),
  64955. ascent (0),
  64956. styleFlags (Font::plain)
  64957. {
  64958. }
  64959. void Font::resetToDefaultState() throw()
  64960. {
  64961. typefaceName = defaultSans;
  64962. height = defaultFontHeight;
  64963. horizontalScale = 1.0f;
  64964. kerning = 0;
  64965. ascent = 0;
  64966. styleFlags = Font::plain;
  64967. typeface = 0;
  64968. }
  64969. Font::Font (const float fontHeight,
  64970. const int styleFlags_) throw()
  64971. : typefaceName (defaultSans),
  64972. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  64973. horizontalScale (1.0f),
  64974. kerning (0),
  64975. ascent (0),
  64976. styleFlags (styleFlags_)
  64977. {
  64978. }
  64979. Font::Font (const String& typefaceName_,
  64980. const float fontHeight,
  64981. const int styleFlags_) throw()
  64982. : typefaceName (typefaceName_),
  64983. height (jlimit (minFontHeight, maxFontHeight, fontHeight)),
  64984. horizontalScale (1.0f),
  64985. kerning (0),
  64986. ascent (0),
  64987. styleFlags (styleFlags_)
  64988. {
  64989. }
  64990. Font::Font (const Font& other) throw()
  64991. : typefaceName (other.typefaceName),
  64992. height (other.height),
  64993. horizontalScale (other.horizontalScale),
  64994. kerning (other.kerning),
  64995. ascent (other.ascent),
  64996. styleFlags (other.styleFlags),
  64997. typeface (other.typeface)
  64998. {
  64999. }
  65000. const Font& Font::operator= (const Font& other) throw()
  65001. {
  65002. if (this != &other)
  65003. {
  65004. typefaceName = other.typefaceName;
  65005. height = other.height;
  65006. styleFlags = other.styleFlags;
  65007. horizontalScale = other.horizontalScale;
  65008. kerning = other.kerning;
  65009. ascent = other.ascent;
  65010. typeface = other.typeface;
  65011. }
  65012. return *this;
  65013. }
  65014. Font::~Font() throw()
  65015. {
  65016. }
  65017. Font::Font (const Typeface& face) throw()
  65018. : height (11.0f),
  65019. horizontalScale (1.0f),
  65020. kerning (0),
  65021. ascent (0),
  65022. styleFlags (plain)
  65023. {
  65024. typefaceName = face.getName();
  65025. setBold (face.isBold());
  65026. setItalic (face.isItalic());
  65027. typeface = new Typeface (face);
  65028. }
  65029. bool Font::operator== (const Font& other) const throw()
  65030. {
  65031. return height == other.height
  65032. && horizontalScale == other.horizontalScale
  65033. && kerning == other.kerning
  65034. && styleFlags == other.styleFlags
  65035. && typefaceName == other.typefaceName;
  65036. }
  65037. bool Font::operator!= (const Font& other) const throw()
  65038. {
  65039. return ! operator== (other);
  65040. }
  65041. void Font::setTypefaceName (const String& faceName) throw()
  65042. {
  65043. typefaceName = faceName;
  65044. typeface = 0;
  65045. ascent = 0;
  65046. }
  65047. void Font::initialiseDefaultFontNames() throw()
  65048. {
  65049. Font::getDefaultFontNames (defaultSans,
  65050. defaultSerif,
  65051. defaultFixed);
  65052. }
  65053. void clearUpDefaultFontNames() throw() // called at shutdown by code in Typface
  65054. {
  65055. defaultSans = String::empty;
  65056. defaultSerif = String::empty;
  65057. defaultFixed = String::empty;
  65058. fallbackFont = String::empty;
  65059. }
  65060. const String Font::getDefaultSansSerifFontName() throw()
  65061. {
  65062. return defaultSans;
  65063. }
  65064. const String Font::getDefaultSerifFontName() throw()
  65065. {
  65066. return defaultSerif;
  65067. }
  65068. const String Font::getDefaultMonospacedFontName() throw()
  65069. {
  65070. return defaultFixed;
  65071. }
  65072. void Font::setDefaultSansSerifFontName (const String& name) throw()
  65073. {
  65074. defaultSans = name;
  65075. }
  65076. const String Font::getFallbackFontName() throw()
  65077. {
  65078. return fallbackFont;
  65079. }
  65080. void Font::setFallbackFontName (const String& name) throw()
  65081. {
  65082. fallbackFont = name;
  65083. }
  65084. void Font::setHeight (float newHeight) throw()
  65085. {
  65086. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  65087. }
  65088. void Font::setHeightWithoutChangingWidth (float newHeight) throw()
  65089. {
  65090. newHeight = jlimit (minFontHeight, maxFontHeight, newHeight);
  65091. horizontalScale *= (height / newHeight);
  65092. height = newHeight;
  65093. }
  65094. void Font::setStyleFlags (const int newFlags) throw()
  65095. {
  65096. if (styleFlags != newFlags)
  65097. {
  65098. styleFlags = newFlags;
  65099. typeface = 0;
  65100. ascent = 0;
  65101. }
  65102. }
  65103. void Font::setSizeAndStyle (const float newHeight,
  65104. const int newStyleFlags,
  65105. const float newHorizontalScale,
  65106. const float newKerningAmount) throw()
  65107. {
  65108. height = jlimit (minFontHeight, maxFontHeight, newHeight);
  65109. horizontalScale = newHorizontalScale;
  65110. kerning = newKerningAmount;
  65111. setStyleFlags (newStyleFlags);
  65112. }
  65113. void Font::setHorizontalScale (const float scaleFactor) throw()
  65114. {
  65115. horizontalScale = scaleFactor;
  65116. }
  65117. void Font::setExtraKerningFactor (const float extraKerning) throw()
  65118. {
  65119. kerning = extraKerning;
  65120. }
  65121. void Font::setBold (const bool shouldBeBold) throw()
  65122. {
  65123. setStyleFlags (shouldBeBold ? (styleFlags | bold)
  65124. : (styleFlags & ~bold));
  65125. }
  65126. bool Font::isBold() const throw()
  65127. {
  65128. return (styleFlags & bold) != 0;
  65129. }
  65130. void Font::setItalic (const bool shouldBeItalic) throw()
  65131. {
  65132. setStyleFlags (shouldBeItalic ? (styleFlags | italic)
  65133. : (styleFlags & ~italic));
  65134. }
  65135. bool Font::isItalic() const throw()
  65136. {
  65137. return (styleFlags & italic) != 0;
  65138. }
  65139. void Font::setUnderline (const bool shouldBeUnderlined) throw()
  65140. {
  65141. setStyleFlags (shouldBeUnderlined ? (styleFlags | underlined)
  65142. : (styleFlags & ~underlined));
  65143. }
  65144. bool Font::isUnderlined() const throw()
  65145. {
  65146. return (styleFlags & underlined) != 0;
  65147. }
  65148. float Font::getAscent() const throw()
  65149. {
  65150. if (ascent == 0)
  65151. ascent = getTypeface()->getAscent();
  65152. return height * ascent;
  65153. }
  65154. float Font::getDescent() const throw()
  65155. {
  65156. return height - getAscent();
  65157. }
  65158. int Font::getStringWidth (const String& text) const throw()
  65159. {
  65160. return roundFloatToInt (getStringWidthFloat (text));
  65161. }
  65162. float Font::getStringWidthFloat (const String& text) const throw()
  65163. {
  65164. float x = 0.0f;
  65165. if (text.isNotEmpty())
  65166. {
  65167. Typeface* const typeface = getTypeface();
  65168. const juce_wchar* t = (const juce_wchar*) text;
  65169. do
  65170. {
  65171. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (*t++);
  65172. if (glyph != 0)
  65173. x += kerning + glyph->getHorizontalSpacing (*t);
  65174. }
  65175. while (*t != 0);
  65176. x *= height;
  65177. x *= horizontalScale;
  65178. }
  65179. return x;
  65180. }
  65181. Typeface* Font::getTypeface() const throw()
  65182. {
  65183. if (typeface == 0)
  65184. typeface = Typeface::getTypefaceFor (*this);
  65185. return typeface;
  65186. }
  65187. void Font::findFonts (OwnedArray<Font>& destArray) throw()
  65188. {
  65189. const StringArray names (findAllTypefaceNames());
  65190. for (int i = 0; i < names.size(); ++i)
  65191. destArray.add (new Font (names[i], defaultFontHeight, Font::plain));
  65192. }
  65193. END_JUCE_NAMESPACE
  65194. /********* End of inlined file: juce_Font.cpp *********/
  65195. /********* Start of inlined file: juce_GlyphArrangement.cpp *********/
  65196. BEGIN_JUCE_NAMESPACE
  65197. #define SHOULD_WRAP(x, wrapwidth) (((x) - 0.0001f) >= (wrapwidth))
  65198. class FontGlyphAlphaMap
  65199. {
  65200. public:
  65201. bool draw (const Graphics& g, float x, const float y) const throw()
  65202. {
  65203. if (bitmap1 == 0)
  65204. return false;
  65205. x += xOrigin;
  65206. const float xFloor = floorf (x);
  65207. const int intX = (int) xFloor;
  65208. g.drawImageAt (((x - xFloor) >= 0.5f && bitmap2 != 0) ? bitmap2 : bitmap1,
  65209. intX, (int) floorf (y + yOrigin), true);
  65210. return true;
  65211. }
  65212. juce_UseDebuggingNewOperator
  65213. private:
  65214. Image* bitmap1;
  65215. Image* bitmap2;
  65216. float xOrigin, yOrigin;
  65217. int lastAccessCount;
  65218. Typeface::Ptr typeface;
  65219. float height, horizontalScale;
  65220. juce_wchar character;
  65221. friend class GlyphCache;
  65222. FontGlyphAlphaMap() throw()
  65223. : bitmap1 (0),
  65224. bitmap2 (0),
  65225. lastAccessCount (0),
  65226. height (0),
  65227. horizontalScale (0),
  65228. character (0)
  65229. {
  65230. }
  65231. ~FontGlyphAlphaMap() throw()
  65232. {
  65233. delete bitmap1;
  65234. delete bitmap2;
  65235. }
  65236. class AlphaBitmapRenderer
  65237. {
  65238. uint8* const data;
  65239. const int stride;
  65240. uint8* lineStart;
  65241. AlphaBitmapRenderer (const AlphaBitmapRenderer&);
  65242. const AlphaBitmapRenderer& operator= (const AlphaBitmapRenderer&);
  65243. public:
  65244. AlphaBitmapRenderer (uint8* const data_,
  65245. const int stride_) throw()
  65246. : data (data_),
  65247. stride (stride_)
  65248. {
  65249. }
  65250. forcedinline void setEdgeTableYPos (const int y) throw()
  65251. {
  65252. lineStart = data + (stride * y);
  65253. }
  65254. forcedinline void handleEdgeTablePixel (const int x, const int alphaLevel) const throw()
  65255. {
  65256. lineStart [x] = (uint8) alphaLevel;
  65257. }
  65258. forcedinline void handleEdgeTableLine (const int x, int width, const int alphaLevel) const throw()
  65259. {
  65260. uint8* d = lineStart + x;
  65261. while (--width >= 0)
  65262. *d++ = (uint8) alphaLevel;
  65263. }
  65264. };
  65265. Image* createAlphaMapFromPath (const Path& path,
  65266. float& topLeftX, float& topLeftY,
  65267. float xScale, float yScale,
  65268. const float subPixelOffsetX) throw()
  65269. {
  65270. Image* im = 0;
  65271. float px, py, pw, ph;
  65272. path.getBounds (px, py, pw, ph);
  65273. topLeftX = floorf (px * xScale);
  65274. topLeftY = floorf (py * yScale);
  65275. int bitmapWidth = roundFloatToInt (pw * xScale) + 2;
  65276. int bitmapHeight = roundFloatToInt (ph * yScale) + 2;
  65277. im = new Image (Image::SingleChannel, bitmapWidth, bitmapHeight, true);
  65278. EdgeTable edgeTable (0, bitmapHeight, EdgeTable::Oversampling_16times);
  65279. edgeTable.addPath (path, AffineTransform::scale (xScale, yScale)
  65280. .translated (subPixelOffsetX - topLeftX, -topLeftY));
  65281. int stride, pixelStride;
  65282. uint8* const pixels = (uint8*) im->lockPixelDataReadWrite (0, 0, bitmapWidth, bitmapHeight, stride, pixelStride);
  65283. jassert (pixelStride == 1);
  65284. AlphaBitmapRenderer renderer (pixels, stride);
  65285. edgeTable.iterate (renderer, 0, 0, bitmapWidth, bitmapHeight, 0);
  65286. im->releasePixelDataReadWrite (pixels);
  65287. return im;
  65288. }
  65289. void generate (Typeface* const face,
  65290. const juce_wchar character_,
  65291. const float fontHeight,
  65292. const float fontHorizontalScale) throw()
  65293. {
  65294. character = character_;
  65295. typeface = face;
  65296. height = fontHeight;
  65297. horizontalScale = fontHorizontalScale;
  65298. const Path* const glyphPath = face->getOutlineForGlyph (character_);
  65299. deleteAndZero (bitmap1);
  65300. deleteAndZero (bitmap2);
  65301. const float fontHScale = fontHeight * fontHorizontalScale;
  65302. if (glyphPath != 0 && ! glyphPath->isEmpty())
  65303. {
  65304. bitmap1 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.0f);
  65305. if (fontHScale < 24.0f)
  65306. bitmap2 = createAlphaMapFromPath (*glyphPath, xOrigin, yOrigin, fontHScale, fontHeight, 0.5f);
  65307. }
  65308. else
  65309. {
  65310. xOrigin = yOrigin = 0;
  65311. }
  65312. }
  65313. };
  65314. static const int defaultNumGlyphsToCache = 120;
  65315. class GlyphCache;
  65316. static GlyphCache* cacheInstance = 0;
  65317. class GlyphCache : private DeletedAtShutdown
  65318. {
  65319. public:
  65320. static GlyphCache* getInstance() throw()
  65321. {
  65322. if (cacheInstance == 0)
  65323. cacheInstance = new GlyphCache();
  65324. return cacheInstance;
  65325. }
  65326. const FontGlyphAlphaMap& getGlyphFor (Typeface* const typeface,
  65327. const float fontHeight,
  65328. const float fontHorizontalScale,
  65329. const juce_wchar character) throw()
  65330. {
  65331. ++accessCounter;
  65332. int oldestCounter = INT_MAX;
  65333. int oldestIndex = 0;
  65334. for (int i = numGlyphs; --i >= 0;)
  65335. {
  65336. FontGlyphAlphaMap& g = glyphs[i];
  65337. if (g.character == character
  65338. && g.height == fontHeight
  65339. && g.typeface->hashCode() == typeface->hashCode()
  65340. && g.horizontalScale == fontHorizontalScale)
  65341. {
  65342. g.lastAccessCount = accessCounter;
  65343. ++hits;
  65344. return g;
  65345. }
  65346. if (oldestCounter > g.lastAccessCount)
  65347. {
  65348. oldestCounter = g.lastAccessCount;
  65349. oldestIndex = i;
  65350. }
  65351. }
  65352. ++misses;
  65353. if (hits + misses > (numGlyphs << 4))
  65354. {
  65355. if (misses * 2 > hits)
  65356. setCacheSize (numGlyphs + 32);
  65357. hits = 0;
  65358. misses = 0;
  65359. oldestIndex = 0;
  65360. }
  65361. FontGlyphAlphaMap& oldest = glyphs [oldestIndex];
  65362. oldest.lastAccessCount = accessCounter;
  65363. oldest.generate (typeface,
  65364. character,
  65365. fontHeight,
  65366. fontHorizontalScale);
  65367. return oldest;
  65368. }
  65369. void setCacheSize (const int num) throw()
  65370. {
  65371. if (numGlyphs != num)
  65372. {
  65373. numGlyphs = num;
  65374. if (glyphs != 0)
  65375. delete[] glyphs;
  65376. glyphs = new FontGlyphAlphaMap [numGlyphs];
  65377. hits = 0;
  65378. misses = 0;
  65379. }
  65380. }
  65381. juce_UseDebuggingNewOperator
  65382. private:
  65383. FontGlyphAlphaMap* glyphs;
  65384. int numGlyphs, accessCounter;
  65385. int hits, misses;
  65386. GlyphCache() throw()
  65387. : glyphs (0),
  65388. numGlyphs (0),
  65389. accessCounter (0)
  65390. {
  65391. setCacheSize (defaultNumGlyphsToCache);
  65392. }
  65393. ~GlyphCache() throw()
  65394. {
  65395. delete[] glyphs;
  65396. jassert (cacheInstance == this);
  65397. cacheInstance = 0;
  65398. }
  65399. GlyphCache (const GlyphCache&);
  65400. const GlyphCache& operator= (const GlyphCache&);
  65401. };
  65402. PositionedGlyph::PositionedGlyph() throw()
  65403. {
  65404. }
  65405. void PositionedGlyph::draw (const Graphics& g) const throw()
  65406. {
  65407. if (! glyphInfo->isWhitespace())
  65408. {
  65409. if (fontHeight < 100.0f && fontHeight > 0.1f && ! g.isVectorDevice())
  65410. {
  65411. const FontGlyphAlphaMap& alphaMap
  65412. = GlyphCache::getInstance()->getGlyphFor (glyphInfo->getTypeface(),
  65413. fontHeight,
  65414. fontHorizontalScale,
  65415. getCharacter());
  65416. alphaMap.draw (g, x, y);
  65417. }
  65418. else
  65419. {
  65420. // that's a bit of a dodgy size, isn't it??
  65421. jassert (fontHeight > 0.0f && fontHeight < 4000.0f);
  65422. draw (g, AffineTransform::identity);
  65423. }
  65424. }
  65425. }
  65426. void PositionedGlyph::draw (const Graphics& g,
  65427. const AffineTransform& transform) const throw()
  65428. {
  65429. if (! glyphInfo->isWhitespace())
  65430. {
  65431. g.fillPath (glyphInfo->getPath(),
  65432. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  65433. .translated (x, y)
  65434. .followedBy (transform));
  65435. }
  65436. }
  65437. void PositionedGlyph::createPath (Path& path) const throw()
  65438. {
  65439. if (! glyphInfo->isWhitespace())
  65440. {
  65441. path.addPath (glyphInfo->getPath(),
  65442. AffineTransform::scale (fontHeight * fontHorizontalScale, fontHeight)
  65443. .translated (x, y));
  65444. }
  65445. }
  65446. bool PositionedGlyph::hitTest (float px, float py) const throw()
  65447. {
  65448. if (px >= getLeft() && px < getRight()
  65449. && py >= getTop() && py < getBottom()
  65450. && fontHeight > 0.0f
  65451. && ! glyphInfo->isWhitespace())
  65452. {
  65453. AffineTransform::translation (-x, -y)
  65454. .scaled (1.0f / (fontHeight * fontHorizontalScale), 1.0f / fontHeight)
  65455. .transformPoint (px, py);
  65456. return glyphInfo->getPath().contains (px, py);
  65457. }
  65458. return false;
  65459. }
  65460. void PositionedGlyph::moveBy (const float deltaX,
  65461. const float deltaY) throw()
  65462. {
  65463. x += deltaX;
  65464. y += deltaY;
  65465. }
  65466. GlyphArrangement::GlyphArrangement() throw()
  65467. : numGlyphs (0),
  65468. numAllocated (0),
  65469. glyphs (0)
  65470. {
  65471. }
  65472. GlyphArrangement::GlyphArrangement (const GlyphArrangement& other) throw()
  65473. : numGlyphs (0),
  65474. numAllocated (0),
  65475. glyphs (0)
  65476. {
  65477. addGlyphArrangement (other);
  65478. }
  65479. const GlyphArrangement& GlyphArrangement::operator= (const GlyphArrangement& other) throw()
  65480. {
  65481. if (this != &other)
  65482. {
  65483. clear();
  65484. addGlyphArrangement (other);
  65485. }
  65486. return *this;
  65487. }
  65488. GlyphArrangement::~GlyphArrangement() throw()
  65489. {
  65490. clear();
  65491. juce_free (glyphs);
  65492. }
  65493. void GlyphArrangement::ensureNumGlyphsAllocated (const int minGlyphs) throw()
  65494. {
  65495. if (numAllocated <= minGlyphs)
  65496. {
  65497. numAllocated = minGlyphs + 2;
  65498. if (glyphs == 0)
  65499. glyphs = (PositionedGlyph*) juce_malloc (numAllocated * sizeof (PositionedGlyph));
  65500. else
  65501. glyphs = (PositionedGlyph*) juce_realloc (glyphs, numAllocated * sizeof (PositionedGlyph));
  65502. }
  65503. }
  65504. void GlyphArrangement::incGlyphRefCount (const int i) const throw()
  65505. {
  65506. jassert (((unsigned int) i) < (unsigned int) numGlyphs);
  65507. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  65508. glyphs[i].glyphInfo->getTypeface()->incReferenceCount();
  65509. }
  65510. void GlyphArrangement::decGlyphRefCount (const int i) const throw()
  65511. {
  65512. if (glyphs[i].glyphInfo != 0 && glyphs[i].glyphInfo->getTypeface() != 0)
  65513. glyphs[i].glyphInfo->getTypeface()->decReferenceCount();
  65514. }
  65515. void GlyphArrangement::clear() throw()
  65516. {
  65517. for (int i = numGlyphs; --i >= 0;)
  65518. decGlyphRefCount (i);
  65519. numGlyphs = 0;
  65520. }
  65521. PositionedGlyph& GlyphArrangement::getGlyph (const int index) const throw()
  65522. {
  65523. jassert (((unsigned int) index) < (unsigned int) numGlyphs);
  65524. return glyphs [index];
  65525. }
  65526. void GlyphArrangement::addGlyphArrangement (const GlyphArrangement& other) throw()
  65527. {
  65528. ensureNumGlyphsAllocated (numGlyphs + other.numGlyphs);
  65529. memcpy (glyphs + numGlyphs, other.glyphs,
  65530. other.numGlyphs * sizeof (PositionedGlyph));
  65531. for (int i = other.numGlyphs; --i >= 0;)
  65532. incGlyphRefCount (numGlyphs++);
  65533. }
  65534. void GlyphArrangement::removeLast() throw()
  65535. {
  65536. if (numGlyphs > 0)
  65537. decGlyphRefCount (--numGlyphs);
  65538. }
  65539. void GlyphArrangement::removeRangeOfGlyphs (int startIndex, const int num) throw()
  65540. {
  65541. jassert (startIndex >= 0);
  65542. if (startIndex < 0)
  65543. startIndex = 0;
  65544. if (num < 0 || startIndex + num >= numGlyphs)
  65545. {
  65546. while (numGlyphs > startIndex)
  65547. removeLast();
  65548. }
  65549. else if (num > 0)
  65550. {
  65551. int i;
  65552. for (i = startIndex; i < startIndex + num; ++i)
  65553. decGlyphRefCount (i);
  65554. for (i = numGlyphs - (startIndex + num); --i >= 0;)
  65555. {
  65556. glyphs [startIndex] = glyphs [startIndex + num];
  65557. ++startIndex;
  65558. }
  65559. numGlyphs -= num;
  65560. }
  65561. }
  65562. void GlyphArrangement::addLineOfText (const Font& font,
  65563. const String& text,
  65564. const float xOffset,
  65565. const float yOffset) throw()
  65566. {
  65567. addCurtailedLineOfText (font, text,
  65568. xOffset, yOffset,
  65569. 1.0e10f, false);
  65570. }
  65571. void GlyphArrangement::addCurtailedLineOfText (const Font& font,
  65572. const String& text,
  65573. float xOffset,
  65574. const float yOffset,
  65575. const float maxWidthPixels,
  65576. const bool useEllipsis) throw()
  65577. {
  65578. const int textLen = text.length();
  65579. if (textLen > 0)
  65580. {
  65581. ensureNumGlyphsAllocated (numGlyphs + textLen + 3); // extra chars for ellipsis
  65582. Typeface* const typeface = font.getTypeface();
  65583. const float fontHeight = font.getHeight();
  65584. const float ascent = font.getAscent();
  65585. const float fontHorizontalScale = font.getHorizontalScale();
  65586. const float heightTimesScale = fontHorizontalScale * fontHeight;
  65587. const float kerningFactor = font.getExtraKerningFactor();
  65588. const float startX = xOffset;
  65589. const juce_wchar* const unicodeText = (const juce_wchar*) text;
  65590. for (int i = 0; i < textLen; ++i)
  65591. {
  65592. const TypefaceGlyphInfo* const glyph = typeface->getGlyph (unicodeText[i]);
  65593. if (glyph != 0)
  65594. {
  65595. jassert (numAllocated > numGlyphs);
  65596. ensureNumGlyphsAllocated (numGlyphs);
  65597. PositionedGlyph& pg = glyphs [numGlyphs];
  65598. pg.glyphInfo = glyph;
  65599. pg.x = xOffset;
  65600. pg.y = yOffset;
  65601. pg.w = heightTimesScale * glyph->getHorizontalSpacing (0);
  65602. pg.fontHeight = fontHeight;
  65603. pg.fontAscent = ascent;
  65604. pg.fontHorizontalScale = fontHorizontalScale;
  65605. pg.isUnderlined = font.isUnderlined();
  65606. xOffset += heightTimesScale * (kerningFactor + glyph->getHorizontalSpacing (unicodeText [i + 1]));
  65607. if (xOffset - startX > maxWidthPixels + 1.0f)
  65608. {
  65609. // curtail the string if it's too wide..
  65610. if (useEllipsis && textLen > 3 && numGlyphs >= 3)
  65611. appendEllipsis (font, startX + maxWidthPixels);
  65612. break;
  65613. }
  65614. else
  65615. {
  65616. if (glyph->getTypeface() != 0)
  65617. glyph->getTypeface()->incReferenceCount();
  65618. ++numGlyphs;
  65619. }
  65620. }
  65621. }
  65622. }
  65623. }
  65624. void GlyphArrangement::appendEllipsis (const Font& font, const float maxXPixels) throw()
  65625. {
  65626. const TypefaceGlyphInfo* const dotGlyph = font.getTypeface()->getGlyph (T('.'));
  65627. if (dotGlyph != 0)
  65628. {
  65629. if (numGlyphs > 0)
  65630. {
  65631. PositionedGlyph& glyph = glyphs [numGlyphs - 1];
  65632. const float fontHeight = glyph.fontHeight;
  65633. const float fontHorizontalScale = glyph.fontHorizontalScale;
  65634. const float fontAscent = glyph.fontAscent;
  65635. const float dx = fontHeight * fontHorizontalScale
  65636. * (font.getExtraKerningFactor() + dotGlyph->getHorizontalSpacing (T('.')));
  65637. float xOffset = 0.0f, yOffset = 0.0f;
  65638. for (int dotPos = 3; --dotPos >= 0 && numGlyphs > 0;)
  65639. {
  65640. removeLast();
  65641. jassert (numAllocated > numGlyphs);
  65642. PositionedGlyph& pg = glyphs [numGlyphs];
  65643. xOffset = pg.x;
  65644. yOffset = pg.y;
  65645. if (numGlyphs == 0 || xOffset + dx * 3 <= maxXPixels)
  65646. break;
  65647. }
  65648. for (int i = 3; --i >= 0;)
  65649. {
  65650. jassert (numAllocated > numGlyphs);
  65651. ensureNumGlyphsAllocated (numGlyphs);
  65652. PositionedGlyph& pg = glyphs [numGlyphs];
  65653. pg.glyphInfo = dotGlyph;
  65654. pg.x = xOffset;
  65655. pg.y = yOffset;
  65656. pg.w = dx;
  65657. pg.fontHeight = fontHeight;
  65658. pg.fontAscent = fontAscent;
  65659. pg.fontHorizontalScale = fontHorizontalScale;
  65660. pg.isUnderlined = font.isUnderlined();
  65661. xOffset += dx;
  65662. if (dotGlyph->getTypeface() != 0)
  65663. dotGlyph->getTypeface()->incReferenceCount();
  65664. ++numGlyphs;
  65665. }
  65666. }
  65667. }
  65668. }
  65669. void GlyphArrangement::addJustifiedText (const Font& font,
  65670. const String& text,
  65671. float x, float y,
  65672. const float maxLineWidth,
  65673. const Justification& horizontalLayout) throw()
  65674. {
  65675. int lineStartIndex = numGlyphs;
  65676. addLineOfText (font, text, x, y);
  65677. const float originalY = y;
  65678. while (lineStartIndex < numGlyphs)
  65679. {
  65680. int i = lineStartIndex;
  65681. if (glyphs[i].getCharacter() != T('\n') && glyphs[i].getCharacter() != T('\r'))
  65682. ++i;
  65683. const float lineMaxX = glyphs [lineStartIndex].getLeft() + maxLineWidth;
  65684. int lastWordBreakIndex = -1;
  65685. while (i < numGlyphs)
  65686. {
  65687. PositionedGlyph& pg = glyphs[i];
  65688. const juce_wchar c = pg.getCharacter();
  65689. if (c == T('\r') || c == T('\n'))
  65690. {
  65691. ++i;
  65692. if (c == T('\r') && i < numGlyphs && glyphs [i].getCharacter() == T('\n'))
  65693. ++i;
  65694. break;
  65695. }
  65696. else if (pg.isWhitespace())
  65697. {
  65698. lastWordBreakIndex = i + 1;
  65699. }
  65700. else if (SHOULD_WRAP (pg.getRight(), lineMaxX))
  65701. {
  65702. if (lastWordBreakIndex >= 0)
  65703. i = lastWordBreakIndex;
  65704. break;
  65705. }
  65706. ++i;
  65707. }
  65708. const float currentLineStartX = glyphs [lineStartIndex].getLeft();
  65709. float currentLineEndX = currentLineStartX;
  65710. for (int j = i; --j >= lineStartIndex;)
  65711. {
  65712. if (! glyphs[j].isWhitespace())
  65713. {
  65714. currentLineEndX = glyphs[j].getRight();
  65715. break;
  65716. }
  65717. }
  65718. float deltaX = 0.0f;
  65719. if (horizontalLayout.testFlags (Justification::horizontallyJustified))
  65720. spreadOutLine (lineStartIndex, i - lineStartIndex, maxLineWidth);
  65721. else if (horizontalLayout.testFlags (Justification::horizontallyCentred))
  65722. deltaX = (maxLineWidth - (currentLineEndX - currentLineStartX)) * 0.5f;
  65723. else if (horizontalLayout.testFlags (Justification::right))
  65724. deltaX = maxLineWidth - (currentLineEndX - currentLineStartX);
  65725. moveRangeOfGlyphs (lineStartIndex, i - lineStartIndex,
  65726. x + deltaX - currentLineStartX, y - originalY);
  65727. lineStartIndex = i;
  65728. y += font.getHeight();
  65729. }
  65730. }
  65731. void GlyphArrangement::addFittedText (const Font& f,
  65732. const String& text,
  65733. float x, float y,
  65734. float width, float height,
  65735. const Justification& layout,
  65736. int maximumLines,
  65737. const float minimumHorizontalScale) throw()
  65738. {
  65739. // doesn't make much sense if this is outside a sensible range of 0.5 to 1.0
  65740. jassert (minimumHorizontalScale > 0 && minimumHorizontalScale <= 1.0f);
  65741. if (text.containsAnyOf (T("\r\n")))
  65742. {
  65743. GlyphArrangement ga;
  65744. ga.addJustifiedText (f, text, x, y, width, layout);
  65745. float l, t, r, b;
  65746. ga.getBoundingBox (0, -1, l, t, r, b, false);
  65747. float dy = y - t;
  65748. if (layout.testFlags (Justification::verticallyCentred))
  65749. dy += (height - (b - t)) * 0.5f;
  65750. else if (layout.testFlags (Justification::bottom))
  65751. dy += height - (b - t);
  65752. ga.moveRangeOfGlyphs (0, -1, 0.0f, dy);
  65753. addGlyphArrangement (ga);
  65754. return;
  65755. }
  65756. int startIndex = numGlyphs;
  65757. addLineOfText (f, text.trim(), x, y);
  65758. if (numGlyphs > startIndex)
  65759. {
  65760. float lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  65761. if (lineWidth <= 0)
  65762. return;
  65763. if (lineWidth * minimumHorizontalScale < width)
  65764. {
  65765. if (lineWidth > width)
  65766. {
  65767. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex,
  65768. width / lineWidth);
  65769. }
  65770. justifyGlyphs (startIndex, numGlyphs - startIndex,
  65771. x, y, width, height, layout);
  65772. }
  65773. else if (maximumLines <= 1)
  65774. {
  65775. const float ratio = jmax (minimumHorizontalScale, width / lineWidth);
  65776. stretchRangeOfGlyphs (startIndex, numGlyphs - startIndex, ratio);
  65777. while (numGlyphs > 0 && glyphs [numGlyphs - 1].x + glyphs [numGlyphs - 1].w >= x + width)
  65778. removeLast();
  65779. appendEllipsis (f, x + width);
  65780. justifyGlyphs (startIndex, numGlyphs - startIndex,
  65781. x, y, width, height, layout);
  65782. }
  65783. else
  65784. {
  65785. Font font (f);
  65786. String txt (text.trim());
  65787. const int length = txt.length();
  65788. int numLines = 1;
  65789. const int originalStartIndex = startIndex;
  65790. if (length <= 12 && ! txt.containsAnyOf (T(" -\t\r\n")))
  65791. maximumLines = 1;
  65792. maximumLines = jmin (maximumLines, length);
  65793. while (numLines < maximumLines)
  65794. {
  65795. ++numLines;
  65796. const float newFontHeight = height / (float)numLines;
  65797. if (newFontHeight < 8.0f)
  65798. break;
  65799. if (newFontHeight < font.getHeight())
  65800. {
  65801. font.setHeight (newFontHeight);
  65802. while (numGlyphs > startIndex)
  65803. removeLast();
  65804. addLineOfText (font, txt, x, y);
  65805. lineWidth = glyphs[numGlyphs - 1].getRight() - glyphs[startIndex].getLeft();
  65806. }
  65807. if (numLines > lineWidth / width)
  65808. break;
  65809. }
  65810. if (numLines < 1)
  65811. numLines = 1;
  65812. float lineY = y;
  65813. float widthPerLine = lineWidth / numLines;
  65814. int lastLineStartIndex = 0;
  65815. for (int line = 0; line < numLines; ++line)
  65816. {
  65817. int i = startIndex;
  65818. lastLineStartIndex = i;
  65819. float lineStartX = glyphs[startIndex].getLeft();
  65820. while (i < numGlyphs)
  65821. {
  65822. lineWidth = (glyphs[i].getRight() - lineStartX);
  65823. if (lineWidth > widthPerLine)
  65824. {
  65825. // got to a point where the line's too long, so skip forward to find a
  65826. // good place to break it..
  65827. const int searchStartIndex = i;
  65828. while (i < numGlyphs)
  65829. {
  65830. if ((glyphs[i].getRight() - lineStartX) * minimumHorizontalScale < width)
  65831. {
  65832. if (glyphs[i].isWhitespace()
  65833. || glyphs[i].getCharacter() == T('-'))
  65834. {
  65835. ++i;
  65836. break;
  65837. }
  65838. }
  65839. else
  65840. {
  65841. // can't find a suitable break, so try looking backwards..
  65842. i = searchStartIndex;
  65843. for (int back = 1; back < jmin (5, i - startIndex - 1); ++back)
  65844. {
  65845. if (glyphs[i - back].isWhitespace()
  65846. || glyphs[i - back].getCharacter() == T('-'))
  65847. {
  65848. i -= back - 1;
  65849. break;
  65850. }
  65851. }
  65852. break;
  65853. }
  65854. ++i;
  65855. }
  65856. break;
  65857. }
  65858. ++i;
  65859. }
  65860. int wsStart = i;
  65861. while (wsStart > 0 && glyphs[wsStart - 1].isWhitespace())
  65862. --wsStart;
  65863. int wsEnd = i;
  65864. while (wsEnd < numGlyphs && glyphs[wsEnd].isWhitespace())
  65865. ++wsEnd;
  65866. removeRangeOfGlyphs (wsStart, wsEnd - wsStart);
  65867. i = jmax (wsStart, startIndex + 1);
  65868. lineWidth = glyphs[i - 1].getRight() - lineStartX;
  65869. if (lineWidth > width)
  65870. {
  65871. stretchRangeOfGlyphs (startIndex, i - startIndex,
  65872. width / lineWidth);
  65873. }
  65874. justifyGlyphs (startIndex, i - startIndex,
  65875. x, lineY, width, font.getHeight(),
  65876. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  65877. startIndex = i;
  65878. lineY += font.getHeight();
  65879. if (startIndex >= numGlyphs)
  65880. break;
  65881. }
  65882. if (startIndex < numGlyphs)
  65883. {
  65884. while (numGlyphs > startIndex)
  65885. removeLast();
  65886. if (startIndex - originalStartIndex > 4)
  65887. {
  65888. const float lineStartX = glyphs[lastLineStartIndex].getLeft();
  65889. appendEllipsis (font, lineStartX + width);
  65890. lineWidth = glyphs[startIndex - 1].getRight() - lineStartX;
  65891. if (lineWidth > width)
  65892. {
  65893. stretchRangeOfGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  65894. width / lineWidth);
  65895. }
  65896. justifyGlyphs (lastLineStartIndex, startIndex - lastLineStartIndex,
  65897. x, lineY - font.getHeight(), width, font.getHeight(),
  65898. layout.getOnlyHorizontalFlags() | Justification::verticallyCentred);
  65899. }
  65900. startIndex = numGlyphs;
  65901. }
  65902. justifyGlyphs (originalStartIndex, startIndex - originalStartIndex,
  65903. x, y, width, height, layout.getFlags() & ~Justification::horizontallyJustified);
  65904. }
  65905. }
  65906. }
  65907. void GlyphArrangement::moveRangeOfGlyphs (int startIndex, int num,
  65908. const float dx, const float dy) throw()
  65909. {
  65910. jassert (startIndex >= 0);
  65911. if (dx != 0.0f || dy != 0.0f)
  65912. {
  65913. if (num < 0 || startIndex + num > numGlyphs)
  65914. num = numGlyphs - startIndex;
  65915. while (--num >= 0)
  65916. {
  65917. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  65918. glyphs [startIndex++].moveBy (dx, dy);
  65919. }
  65920. }
  65921. }
  65922. void GlyphArrangement::stretchRangeOfGlyphs (int startIndex, int num,
  65923. const float horizontalScaleFactor) throw()
  65924. {
  65925. jassert (startIndex >= 0);
  65926. if (num < 0 || startIndex + num > numGlyphs)
  65927. num = numGlyphs - startIndex;
  65928. if (num > 0)
  65929. {
  65930. const float xAnchor = glyphs[startIndex].getLeft();
  65931. while (--num >= 0)
  65932. {
  65933. jassert (((unsigned int) startIndex) <= (unsigned int) numGlyphs);
  65934. PositionedGlyph& pg = glyphs[startIndex++];
  65935. pg.x = xAnchor + (pg.x - xAnchor) * horizontalScaleFactor;
  65936. pg.fontHorizontalScale *= horizontalScaleFactor;
  65937. pg.w *= horizontalScaleFactor;
  65938. }
  65939. }
  65940. }
  65941. void GlyphArrangement::getBoundingBox (int startIndex, int num,
  65942. float& left,
  65943. float& top,
  65944. float& right,
  65945. float& bottom,
  65946. const bool includeWhitespace) const throw()
  65947. {
  65948. jassert (startIndex >= 0);
  65949. if (num < 0 || startIndex + num > numGlyphs)
  65950. num = numGlyphs - startIndex;
  65951. left = 0.0f;
  65952. top = 0.0f;
  65953. right = 0.0f;
  65954. bottom = 0.0f;
  65955. bool isFirst = true;
  65956. while (--num >= 0)
  65957. {
  65958. const PositionedGlyph& pg = glyphs [startIndex++];
  65959. if (includeWhitespace || ! pg.isWhitespace())
  65960. {
  65961. if (isFirst)
  65962. {
  65963. isFirst = false;
  65964. left = pg.getLeft();
  65965. top = pg.getTop();
  65966. right = pg.getRight();
  65967. bottom = pg.getBottom();
  65968. }
  65969. else
  65970. {
  65971. left = jmin (left, pg.getLeft());
  65972. top = jmin (top, pg.getTop());
  65973. right = jmax (right, pg.getRight());
  65974. bottom = jmax (bottom, pg.getBottom());
  65975. }
  65976. }
  65977. }
  65978. }
  65979. void GlyphArrangement::justifyGlyphs (const int startIndex,
  65980. const int num,
  65981. const float x, const float y,
  65982. const float width, const float height,
  65983. const Justification& justification) throw()
  65984. {
  65985. jassert (num >= 0 && startIndex >= 0);
  65986. if (numGlyphs > 0 && num > 0)
  65987. {
  65988. float left, top, right, bottom;
  65989. getBoundingBox (startIndex, num, left, top, right, bottom,
  65990. ! justification.testFlags (Justification::horizontallyJustified
  65991. | Justification::horizontallyCentred));
  65992. float deltaX = 0.0f;
  65993. if (justification.testFlags (Justification::horizontallyJustified))
  65994. deltaX = x - left;
  65995. else if (justification.testFlags (Justification::horizontallyCentred))
  65996. deltaX = x + (width - (right - left)) * 0.5f - left;
  65997. else if (justification.testFlags (Justification::right))
  65998. deltaX = (x + width) - right;
  65999. else
  66000. deltaX = x - left;
  66001. float deltaY = 0.0f;
  66002. if (justification.testFlags (Justification::top))
  66003. deltaY = y - top;
  66004. else if (justification.testFlags (Justification::bottom))
  66005. deltaY = (y + height) - bottom;
  66006. else
  66007. deltaY = y + (height - (bottom - top)) * 0.5f - top;
  66008. moveRangeOfGlyphs (startIndex, num, deltaX, deltaY);
  66009. if (justification.testFlags (Justification::horizontallyJustified))
  66010. {
  66011. int lineStart = 0;
  66012. float baseY = glyphs [startIndex].getBaselineY();
  66013. int i;
  66014. for (i = 0; i < num; ++i)
  66015. {
  66016. const float glyphY = glyphs [startIndex + i].getBaselineY();
  66017. if (glyphY != baseY)
  66018. {
  66019. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  66020. lineStart = i;
  66021. baseY = glyphY;
  66022. }
  66023. }
  66024. if (i > lineStart)
  66025. spreadOutLine (startIndex + lineStart, i - lineStart, width);
  66026. }
  66027. }
  66028. }
  66029. void GlyphArrangement::spreadOutLine (const int start, const int num, const float targetWidth) throw()
  66030. {
  66031. if (start + num < numGlyphs
  66032. && glyphs [start + num - 1].getCharacter() != T('\r')
  66033. && glyphs [start + num - 1].getCharacter() != T('\n'))
  66034. {
  66035. int numSpaces = 0;
  66036. int spacesAtEnd = 0;
  66037. for (int i = 0; i < num; ++i)
  66038. {
  66039. if (glyphs [start + i].isWhitespace())
  66040. {
  66041. ++spacesAtEnd;
  66042. ++numSpaces;
  66043. }
  66044. else
  66045. {
  66046. spacesAtEnd = 0;
  66047. }
  66048. }
  66049. numSpaces -= spacesAtEnd;
  66050. if (numSpaces > 0)
  66051. {
  66052. const float startX = glyphs [start].getLeft();
  66053. const float endX = glyphs [start + num - 1 - spacesAtEnd].getRight();
  66054. const float extraPaddingBetweenWords
  66055. = (targetWidth - (endX - startX)) / (float) numSpaces;
  66056. float deltaX = 0.0f;
  66057. for (int i = 0; i < num; ++i)
  66058. {
  66059. glyphs [start + i].moveBy (deltaX, 0.0);
  66060. if (glyphs [start + i].isWhitespace())
  66061. deltaX += extraPaddingBetweenWords;
  66062. }
  66063. }
  66064. }
  66065. }
  66066. void GlyphArrangement::draw (const Graphics& g) const throw()
  66067. {
  66068. for (int i = 0; i < numGlyphs; ++i)
  66069. {
  66070. glyphs[i].draw (g);
  66071. if (glyphs[i].isUnderlined)
  66072. {
  66073. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  66074. juce_wchar nextChar = 0;
  66075. if (i < numGlyphs - 1
  66076. && glyphs[i + 1].y == glyphs[i].y)
  66077. {
  66078. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  66079. }
  66080. g.fillRect (glyphs[i].x,
  66081. glyphs[i].y + lineThickness * 2.0f,
  66082. glyphs[i].fontHeight
  66083. * glyphs[i].fontHorizontalScale
  66084. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  66085. lineThickness);
  66086. }
  66087. }
  66088. }
  66089. void GlyphArrangement::draw (const Graphics& g, const AffineTransform& transform) const throw()
  66090. {
  66091. for (int i = 0; i < numGlyphs; ++i)
  66092. {
  66093. glyphs[i].draw (g, transform);
  66094. if (glyphs[i].isUnderlined)
  66095. {
  66096. const float lineThickness = (glyphs[i].fontHeight - glyphs[i].fontAscent) * 0.3f;
  66097. juce_wchar nextChar = 0;
  66098. if (i < numGlyphs - 1
  66099. && glyphs[i + 1].y == glyphs[i].y)
  66100. {
  66101. nextChar = glyphs[i + 1].glyphInfo->getCharacter();
  66102. }
  66103. Path p;
  66104. p.addLineSegment (glyphs[i].x,
  66105. glyphs[i].y + lineThickness * 2.5f,
  66106. glyphs[i].x + glyphs[i].fontHeight
  66107. * glyphs[i].fontHorizontalScale
  66108. * glyphs[i].glyphInfo->getHorizontalSpacing (nextChar),
  66109. glyphs[i].y + lineThickness * 2.5f,
  66110. lineThickness);
  66111. g.fillPath (p, transform);
  66112. }
  66113. }
  66114. }
  66115. void GlyphArrangement::createPath (Path& path) const throw()
  66116. {
  66117. for (int i = 0; i < numGlyphs; ++i)
  66118. glyphs[i].createPath (path);
  66119. }
  66120. int GlyphArrangement::findGlyphIndexAt (float x, float y) const throw()
  66121. {
  66122. for (int i = 0; i < numGlyphs; ++i)
  66123. if (glyphs[i].hitTest (x, y))
  66124. return i;
  66125. return -1;
  66126. }
  66127. END_JUCE_NAMESPACE
  66128. /********* End of inlined file: juce_GlyphArrangement.cpp *********/
  66129. /********* Start of inlined file: juce_TextLayout.cpp *********/
  66130. BEGIN_JUCE_NAMESPACE
  66131. class TextLayoutToken
  66132. {
  66133. public:
  66134. String text;
  66135. Font font;
  66136. int x, y, w, h;
  66137. int line, lineHeight;
  66138. bool isWhitespace, isNewLine;
  66139. TextLayoutToken (const String& t,
  66140. const Font& f,
  66141. const bool isWhitespace_) throw()
  66142. : text (t),
  66143. font (f),
  66144. x(0),
  66145. y(0),
  66146. isWhitespace (isWhitespace_)
  66147. {
  66148. w = font.getStringWidth (t);
  66149. h = roundFloatToInt (f.getHeight());
  66150. isNewLine = t.containsAnyOf (T("\r\n"));
  66151. }
  66152. TextLayoutToken (const TextLayoutToken& other) throw()
  66153. : text (other.text),
  66154. font (other.font),
  66155. x (other.x),
  66156. y (other.y),
  66157. w (other.w),
  66158. h (other.h),
  66159. line (other.line),
  66160. lineHeight (other.lineHeight),
  66161. isWhitespace (other.isWhitespace),
  66162. isNewLine (other.isNewLine)
  66163. {
  66164. }
  66165. ~TextLayoutToken() throw()
  66166. {
  66167. }
  66168. void draw (Graphics& g,
  66169. const int xOffset,
  66170. const int yOffset) throw()
  66171. {
  66172. if (! isWhitespace)
  66173. {
  66174. g.setFont (font);
  66175. g.drawSingleLineText (text.trimEnd(),
  66176. xOffset + x,
  66177. yOffset + y + (lineHeight - h)
  66178. + roundFloatToInt (font.getAscent()));
  66179. }
  66180. }
  66181. juce_UseDebuggingNewOperator
  66182. };
  66183. TextLayout::TextLayout() throw()
  66184. : tokens (64),
  66185. totalLines (0)
  66186. {
  66187. }
  66188. TextLayout::TextLayout (const String& text,
  66189. const Font& font) throw()
  66190. : tokens (64),
  66191. totalLines (0)
  66192. {
  66193. appendText (text, font);
  66194. }
  66195. TextLayout::TextLayout (const TextLayout& other) throw()
  66196. : tokens (64),
  66197. totalLines (0)
  66198. {
  66199. *this = other;
  66200. }
  66201. const TextLayout& TextLayout::operator= (const TextLayout& other) throw()
  66202. {
  66203. if (this != &other)
  66204. {
  66205. clear();
  66206. totalLines = other.totalLines;
  66207. for (int i = 0; i < other.tokens.size(); ++i)
  66208. tokens.add (new TextLayoutToken (*(const TextLayoutToken*)(other.tokens.getUnchecked(i))));
  66209. }
  66210. return *this;
  66211. }
  66212. TextLayout::~TextLayout() throw()
  66213. {
  66214. clear();
  66215. }
  66216. void TextLayout::clear() throw()
  66217. {
  66218. for (int i = tokens.size(); --i >= 0;)
  66219. {
  66220. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  66221. delete t;
  66222. }
  66223. tokens.clear();
  66224. totalLines = 0;
  66225. }
  66226. void TextLayout::appendText (const String& text,
  66227. const Font& font) throw()
  66228. {
  66229. const tchar* t = text;
  66230. String currentString;
  66231. int lastCharType = 0;
  66232. for (;;)
  66233. {
  66234. const tchar c = *t++;
  66235. if (c == 0)
  66236. break;
  66237. int charType;
  66238. if (c == T('\r') || c == T('\n'))
  66239. {
  66240. charType = 0;
  66241. }
  66242. else if (CharacterFunctions::isWhitespace (c))
  66243. {
  66244. charType = 2;
  66245. }
  66246. else
  66247. {
  66248. charType = 1;
  66249. }
  66250. if (charType == 0 || charType != lastCharType)
  66251. {
  66252. if (currentString.isNotEmpty())
  66253. {
  66254. tokens.add (new TextLayoutToken (currentString, font,
  66255. lastCharType == 2 || lastCharType == 0));
  66256. }
  66257. currentString = String::charToString (c);
  66258. if (c == T('\r') && *t == T('\n'))
  66259. currentString += *t++;
  66260. }
  66261. else
  66262. {
  66263. currentString += c;
  66264. }
  66265. lastCharType = charType;
  66266. }
  66267. if (currentString.isNotEmpty())
  66268. tokens.add (new TextLayoutToken (currentString,
  66269. font,
  66270. lastCharType == 2));
  66271. }
  66272. void TextLayout::setText (const String& text, const Font& font) throw()
  66273. {
  66274. clear();
  66275. appendText (text, font);
  66276. }
  66277. void TextLayout::layout (int maxWidth,
  66278. const Justification& justification,
  66279. const bool attemptToBalanceLineLengths) throw()
  66280. {
  66281. if (attemptToBalanceLineLengths)
  66282. {
  66283. const int originalW = maxWidth;
  66284. int bestWidth = maxWidth;
  66285. float bestLineProportion = 0.0f;
  66286. while (maxWidth > originalW / 2)
  66287. {
  66288. layout (maxWidth, justification, false);
  66289. if (getNumLines() <= 1)
  66290. return;
  66291. const int lastLineW = getLineWidth (getNumLines() - 1);
  66292. const int lastButOneLineW = getLineWidth (getNumLines() - 2);
  66293. const float prop = lastLineW / (float) lastButOneLineW;
  66294. if (prop > 0.9f)
  66295. return;
  66296. if (prop > bestLineProportion)
  66297. {
  66298. bestLineProportion = prop;
  66299. bestWidth = maxWidth;
  66300. }
  66301. maxWidth -= 10;
  66302. }
  66303. layout (bestWidth, justification, false);
  66304. }
  66305. else
  66306. {
  66307. int x = 0;
  66308. int y = 0;
  66309. int h = 0;
  66310. totalLines = 0;
  66311. int i;
  66312. for (i = 0; i < tokens.size(); ++i)
  66313. {
  66314. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(i);
  66315. t->x = x;
  66316. t->y = y;
  66317. t->line = totalLines;
  66318. x += t->w;
  66319. h = jmax (h, t->h);
  66320. const TextLayoutToken* nextTok = (TextLayoutToken*) tokens [i + 1];
  66321. if (nextTok == 0)
  66322. break;
  66323. if (t->isNewLine || ((! nextTok->isWhitespace) && x + nextTok->w > maxWidth))
  66324. {
  66325. // finished a line, so go back and update the heights of the things on it
  66326. for (int j = i; j >= 0; --j)
  66327. {
  66328. TextLayoutToken* const tok = (TextLayoutToken*)tokens.getUnchecked(j);
  66329. if (tok->line == totalLines)
  66330. tok->lineHeight = h;
  66331. else
  66332. break;
  66333. }
  66334. x = 0;
  66335. y += h;
  66336. h = 0;
  66337. ++totalLines;
  66338. }
  66339. }
  66340. // finished a line, so go back and update the heights of the things on it
  66341. for (int j = jmin (i, tokens.size() - 1); j >= 0; --j)
  66342. {
  66343. TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(j);
  66344. if (t->line == totalLines)
  66345. t->lineHeight = h;
  66346. else
  66347. break;
  66348. }
  66349. ++totalLines;
  66350. if (! justification.testFlags (Justification::left))
  66351. {
  66352. int totalW = getWidth();
  66353. for (i = totalLines; --i >= 0;)
  66354. {
  66355. const int lineW = getLineWidth (i);
  66356. int dx = 0;
  66357. if (justification.testFlags (Justification::horizontallyCentred))
  66358. dx = (totalW - lineW) / 2;
  66359. else if (justification.testFlags (Justification::right))
  66360. dx = totalW - lineW;
  66361. for (int j = tokens.size(); --j >= 0;)
  66362. {
  66363. TextLayoutToken* const t = (TextLayoutToken*)tokens.getUnchecked(j);
  66364. if (t->line == i)
  66365. t->x += dx;
  66366. }
  66367. }
  66368. }
  66369. }
  66370. }
  66371. int TextLayout::getLineWidth (const int lineNumber) const throw()
  66372. {
  66373. int maxW = 0;
  66374. for (int i = tokens.size(); --i >= 0;)
  66375. {
  66376. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  66377. if (t->line == lineNumber && ! t->isWhitespace)
  66378. maxW = jmax (maxW, t->x + t->w);
  66379. }
  66380. return maxW;
  66381. }
  66382. int TextLayout::getWidth() const throw()
  66383. {
  66384. int maxW = 0;
  66385. for (int i = tokens.size(); --i >= 0;)
  66386. {
  66387. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  66388. if (! t->isWhitespace)
  66389. maxW = jmax (maxW, t->x + t->w);
  66390. }
  66391. return maxW;
  66392. }
  66393. int TextLayout::getHeight() const throw()
  66394. {
  66395. int maxH = 0;
  66396. for (int i = tokens.size(); --i >= 0;)
  66397. {
  66398. const TextLayoutToken* const t = (TextLayoutToken*) tokens.getUnchecked(i);
  66399. if (! t->isWhitespace)
  66400. maxH = jmax (maxH, t->y + t->h);
  66401. }
  66402. return maxH;
  66403. }
  66404. void TextLayout::draw (Graphics& g,
  66405. const int xOffset,
  66406. const int yOffset) const throw()
  66407. {
  66408. for (int i = tokens.size(); --i >= 0;)
  66409. ((TextLayoutToken*) tokens.getUnchecked(i))->draw (g, xOffset, yOffset);
  66410. }
  66411. void TextLayout::drawWithin (Graphics& g,
  66412. int x, int y, int w, int h,
  66413. const Justification& justification) const throw()
  66414. {
  66415. justification.applyToRectangle (x, y, getWidth(), getHeight(),
  66416. x, y, w, h);
  66417. draw (g, x, y);
  66418. }
  66419. END_JUCE_NAMESPACE
  66420. /********* End of inlined file: juce_TextLayout.cpp *********/
  66421. /********* Start of inlined file: juce_Typeface.cpp *********/
  66422. BEGIN_JUCE_NAMESPACE
  66423. TypefaceGlyphInfo::TypefaceGlyphInfo (const juce_wchar character_,
  66424. const Path& shape,
  66425. const float horizontalSeparation,
  66426. Typeface* const typeface_) throw()
  66427. : character (character_),
  66428. path (shape),
  66429. width (horizontalSeparation),
  66430. typeface (typeface_)
  66431. {
  66432. }
  66433. TypefaceGlyphInfo::~TypefaceGlyphInfo() throw()
  66434. {
  66435. }
  66436. float TypefaceGlyphInfo::getHorizontalSpacing (const juce_wchar subsequentCharacter) const throw()
  66437. {
  66438. if (subsequentCharacter != 0)
  66439. {
  66440. const KerningPair* const pairs = (const KerningPair*) kerningPairs.getData();
  66441. const int numPairs = getNumKerningPairs();
  66442. for (int i = 0; i < numPairs; ++i)
  66443. if (pairs [i].character2 == subsequentCharacter)
  66444. return width + pairs [i].kerningAmount;
  66445. }
  66446. return width;
  66447. }
  66448. void TypefaceGlyphInfo::addKerningPair (const juce_wchar subsequentCharacter,
  66449. const float extraKerningAmount) throw()
  66450. {
  66451. const int numPairs = getNumKerningPairs();
  66452. kerningPairs.setSize ((numPairs + 1) * sizeof (KerningPair));
  66453. KerningPair& p = getKerningPair (numPairs);
  66454. p.character2 = subsequentCharacter;
  66455. p.kerningAmount = extraKerningAmount;
  66456. }
  66457. TypefaceGlyphInfo::KerningPair& TypefaceGlyphInfo::getKerningPair (const int index) const throw()
  66458. {
  66459. return ((KerningPair*) kerningPairs.getData()) [index];
  66460. }
  66461. int TypefaceGlyphInfo::getNumKerningPairs() const throw()
  66462. {
  66463. return kerningPairs.getSize() / sizeof (KerningPair);
  66464. }
  66465. Typeface::Typeface() throw()
  66466. : hash (0),
  66467. isFullyPopulated (false)
  66468. {
  66469. zeromem (lookupTable, sizeof (lookupTable));
  66470. }
  66471. Typeface::Typeface (const Typeface& other)
  66472. : typefaceName (other.typefaceName),
  66473. ascent (other.ascent),
  66474. bold (other.bold),
  66475. italic (other.italic),
  66476. isFullyPopulated (other.isFullyPopulated),
  66477. defaultCharacter (other.defaultCharacter)
  66478. {
  66479. zeromem (lookupTable, sizeof (lookupTable));
  66480. for (int i = 0; i < other.glyphs.size(); ++i)
  66481. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  66482. updateHashCode();
  66483. }
  66484. Typeface::Typeface (const String& faceName,
  66485. const bool bold,
  66486. const bool italic)
  66487. : isFullyPopulated (false)
  66488. {
  66489. zeromem (lookupTable, sizeof (lookupTable));
  66490. initialiseTypefaceCharacteristics (faceName, bold, italic, false);
  66491. updateHashCode();
  66492. }
  66493. Typeface::~Typeface()
  66494. {
  66495. clear();
  66496. }
  66497. const Typeface& Typeface::operator= (const Typeface& other) throw()
  66498. {
  66499. if (this != &other)
  66500. {
  66501. clear();
  66502. typefaceName = other.typefaceName;
  66503. ascent = other.ascent;
  66504. bold = other.bold;
  66505. italic = other.italic;
  66506. isFullyPopulated = other.isFullyPopulated;
  66507. defaultCharacter = other.defaultCharacter;
  66508. for (int i = 0; i < other.glyphs.size(); ++i)
  66509. addGlyphCopy ((const TypefaceGlyphInfo*) other.glyphs.getUnchecked(i));
  66510. updateHashCode();
  66511. }
  66512. return *this;
  66513. }
  66514. void Typeface::updateHashCode() throw()
  66515. {
  66516. hash = typefaceName.hashCode();
  66517. if (bold)
  66518. hash ^= 0xffff;
  66519. if (italic)
  66520. hash ^= 0xffff0000;
  66521. }
  66522. void Typeface::clear() throw()
  66523. {
  66524. zeromem (lookupTable, sizeof (lookupTable));
  66525. typefaceName = String::empty;
  66526. bold = false;
  66527. italic = false;
  66528. for (int i = glyphs.size(); --i >= 0;)
  66529. {
  66530. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) (glyphs.getUnchecked(i));
  66531. delete g;
  66532. }
  66533. glyphs.clear();
  66534. updateHashCode();
  66535. }
  66536. Typeface::Typeface (InputStream& serialisedTypefaceStream)
  66537. {
  66538. zeromem (lookupTable, sizeof (lookupTable));
  66539. isFullyPopulated = true;
  66540. GZIPDecompressorInputStream gzin (&serialisedTypefaceStream, false);
  66541. BufferedInputStream in (&gzin, 32768, false);
  66542. typefaceName = in.readString();
  66543. bold = in.readBool();
  66544. italic = in.readBool();
  66545. ascent = in.readFloat();
  66546. defaultCharacter = (juce_wchar) in.readShort();
  66547. int i, numChars = in.readInt();
  66548. for (i = 0; i < numChars; ++i)
  66549. {
  66550. const juce_wchar c = (juce_wchar) in.readShort();
  66551. const float width = in.readFloat();
  66552. Path p;
  66553. p.loadPathFromStream (in);
  66554. addGlyph (c, p, width);
  66555. }
  66556. const int numKerningPairs = in.readInt();
  66557. for (i = 0; i < numKerningPairs; ++i)
  66558. {
  66559. const juce_wchar char1 = (juce_wchar) in.readShort();
  66560. const juce_wchar char2 = (juce_wchar) in.readShort();
  66561. addKerningPair (char1, char2, in.readFloat());
  66562. }
  66563. updateHashCode();
  66564. }
  66565. void Typeface::serialise (OutputStream& outputStream)
  66566. {
  66567. GZIPCompressorOutputStream out (&outputStream);
  66568. out.writeString (typefaceName);
  66569. out.writeBool (bold);
  66570. out.writeBool (italic);
  66571. out.writeFloat (ascent);
  66572. out.writeShort ((short) (unsigned short) defaultCharacter);
  66573. out.writeInt (glyphs.size());
  66574. int i, numKerningPairs = 0;
  66575. for (i = 0; i < glyphs.size(); ++i)
  66576. {
  66577. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  66578. out.writeShort ((short) (unsigned short) g.character);
  66579. out.writeFloat (g.width);
  66580. g.path.writePathToStream (out);
  66581. numKerningPairs += g.getNumKerningPairs();
  66582. }
  66583. out.writeInt (numKerningPairs);
  66584. for (i = 0; i < glyphs.size(); ++i)
  66585. {
  66586. const TypefaceGlyphInfo& g = *(const TypefaceGlyphInfo*)(glyphs.getUnchecked (i));
  66587. for (int j = 0; j < g.getNumKerningPairs(); ++j)
  66588. {
  66589. const TypefaceGlyphInfo::KerningPair& p = g.getKerningPair (j);
  66590. out.writeShort ((short) (unsigned short) g.character);
  66591. out.writeShort ((short) (unsigned short) p.character2);
  66592. out.writeFloat (p.kerningAmount);
  66593. }
  66594. }
  66595. }
  66596. const Path* Typeface::getOutlineForGlyph (const juce_wchar character) throw()
  66597. {
  66598. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) getGlyph (character);
  66599. if (g != 0)
  66600. return &(g->path);
  66601. else
  66602. return 0;
  66603. }
  66604. const TypefaceGlyphInfo* Typeface::getGlyph (const juce_wchar character) throw()
  66605. {
  66606. if (((unsigned int) character) < 128 && lookupTable [character] > 0)
  66607. return (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  66608. for (int i = 0; i < glyphs.size(); ++i)
  66609. {
  66610. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  66611. if (g->character == character)
  66612. return g;
  66613. }
  66614. if ((! isFullyPopulated)
  66615. && findAndAddSystemGlyph (character))
  66616. {
  66617. for (int i = 0; i < glyphs.size(); ++i)
  66618. {
  66619. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  66620. if (g->character == character)
  66621. return g;
  66622. }
  66623. }
  66624. if (CharacterFunctions::isWhitespace (character) && character != L' ')
  66625. {
  66626. const TypefaceGlyphInfo* spaceGlyph = getGlyph (L' ');
  66627. if (spaceGlyph != 0)
  66628. {
  66629. // Add a copy of the empty glyph, mapped onto this character
  66630. addGlyph (character, spaceGlyph->getPath(), spaceGlyph->getHorizontalSpacing (0));
  66631. spaceGlyph = (const TypefaceGlyphInfo*) glyphs [(int) lookupTable [character]];
  66632. }
  66633. return spaceGlyph;
  66634. }
  66635. else if (character != defaultCharacter)
  66636. {
  66637. const Font fallbackFont (Font::getFallbackFontName(), 10, 0);
  66638. Typeface* const fallbackTypeface = fallbackFont.getTypeface();
  66639. if (fallbackTypeface != 0 && fallbackTypeface != this)
  66640. return fallbackTypeface->getGlyph (character);
  66641. return getGlyph (defaultCharacter);
  66642. }
  66643. return 0;
  66644. }
  66645. void Typeface::addGlyph (const juce_wchar character,
  66646. const Path& path,
  66647. const float horizontalSpacing) throw()
  66648. {
  66649. #ifdef JUCE_DEBUG
  66650. for (int i = 0; i < glyphs.size(); ++i)
  66651. {
  66652. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  66653. if (g->character == character)
  66654. jassertfalse;
  66655. }
  66656. #endif
  66657. if (((unsigned int) character) < 128)
  66658. lookupTable [character] = (short) glyphs.size();
  66659. glyphs.add (new TypefaceGlyphInfo (character,
  66660. path,
  66661. horizontalSpacing,
  66662. this));
  66663. }
  66664. void Typeface::addGlyphCopy (const TypefaceGlyphInfo* const glyphInfoToCopy) throw()
  66665. {
  66666. if (glyphInfoToCopy != 0)
  66667. {
  66668. if (glyphInfoToCopy->character > 0 && glyphInfoToCopy->character < 128)
  66669. lookupTable [glyphInfoToCopy->character] = (short) glyphs.size();
  66670. TypefaceGlyphInfo* const newOne
  66671. = new TypefaceGlyphInfo (glyphInfoToCopy->character,
  66672. glyphInfoToCopy->path,
  66673. glyphInfoToCopy->width,
  66674. this);
  66675. newOne->kerningPairs = glyphInfoToCopy->kerningPairs;
  66676. glyphs.add (newOne);
  66677. }
  66678. }
  66679. void Typeface::addKerningPair (const juce_wchar char1,
  66680. const juce_wchar char2,
  66681. const float extraAmount) throw()
  66682. {
  66683. TypefaceGlyphInfo* const g = (TypefaceGlyphInfo*) getGlyph (char1);
  66684. if (g != 0)
  66685. g->addKerningPair (char2, extraAmount);
  66686. }
  66687. void Typeface::setName (const String& name) throw()
  66688. {
  66689. typefaceName = name;
  66690. updateHashCode();
  66691. }
  66692. void Typeface::setAscent (const float newAscent) throw()
  66693. {
  66694. ascent = newAscent;
  66695. }
  66696. void Typeface::setDefaultCharacter (const juce_wchar newDefaultCharacter) throw()
  66697. {
  66698. defaultCharacter = newDefaultCharacter;
  66699. }
  66700. void Typeface::setBold (const bool shouldBeBold) throw()
  66701. {
  66702. bold = shouldBeBold;
  66703. updateHashCode();
  66704. }
  66705. void Typeface::setItalic (const bool shouldBeItalic) throw()
  66706. {
  66707. italic = shouldBeItalic;
  66708. updateHashCode();
  66709. }
  66710. class TypefaceCache;
  66711. static TypefaceCache* typefaceCacheInstance = 0;
  66712. void clearUpDefaultFontNames() throw(); // in juce_Font.cpp
  66713. class TypefaceCache : private DeletedAtShutdown
  66714. {
  66715. private:
  66716. struct CachedFace
  66717. {
  66718. CachedFace() throw()
  66719. : lastUsageCount (0),
  66720. flags (0)
  66721. {
  66722. }
  66723. String typefaceName;
  66724. int lastUsageCount;
  66725. int flags;
  66726. Typeface::Ptr typeFace;
  66727. };
  66728. int counter;
  66729. OwnedArray <CachedFace> faces;
  66730. TypefaceCache (const TypefaceCache&);
  66731. const TypefaceCache& operator= (const TypefaceCache&);
  66732. public:
  66733. TypefaceCache (int numToCache = 10)
  66734. : counter (1),
  66735. faces (2)
  66736. {
  66737. while (--numToCache >= 0)
  66738. {
  66739. CachedFace* const face = new CachedFace();
  66740. face->typeFace = new Typeface();
  66741. faces.add (face);
  66742. }
  66743. }
  66744. ~TypefaceCache()
  66745. {
  66746. faces.clear();
  66747. jassert (typefaceCacheInstance == this);
  66748. typefaceCacheInstance = 0;
  66749. // just a courtesy call to get avoid leaking these strings at shutdown
  66750. clearUpDefaultFontNames();
  66751. }
  66752. static TypefaceCache* getInstance() throw()
  66753. {
  66754. if (typefaceCacheInstance == 0)
  66755. typefaceCacheInstance = new TypefaceCache();
  66756. return typefaceCacheInstance;
  66757. }
  66758. const Typeface::Ptr findTypefaceFor (const Font& font) throw()
  66759. {
  66760. const int flags = font.getStyleFlags() & (Font::bold | Font::italic);
  66761. int i;
  66762. for (i = faces.size(); --i >= 0;)
  66763. {
  66764. CachedFace* const face = faces.getUnchecked(i);
  66765. if (face->flags == flags
  66766. && face->typefaceName == font.getTypefaceName())
  66767. {
  66768. face->lastUsageCount = ++counter;
  66769. return face->typeFace;
  66770. }
  66771. }
  66772. int replaceIndex = 0;
  66773. int bestLastUsageCount = INT_MAX;
  66774. for (i = faces.size(); --i >= 0;)
  66775. {
  66776. const int lu = faces.getUnchecked(i)->lastUsageCount;
  66777. if (bestLastUsageCount > lu)
  66778. {
  66779. bestLastUsageCount = lu;
  66780. replaceIndex = i;
  66781. }
  66782. }
  66783. CachedFace* const face = faces.getUnchecked (replaceIndex);
  66784. face->typefaceName = font.getTypefaceName();
  66785. face->flags = flags;
  66786. face->lastUsageCount = ++counter;
  66787. face->typeFace = new Typeface (font.getTypefaceName(),
  66788. font.isBold(),
  66789. font.isItalic());
  66790. return face->typeFace;
  66791. }
  66792. };
  66793. const Typeface::Ptr Typeface::getTypefaceFor (const Font& font) throw()
  66794. {
  66795. return TypefaceCache::getInstance()->findTypefaceFor (font);
  66796. }
  66797. END_JUCE_NAMESPACE
  66798. /********* End of inlined file: juce_Typeface.cpp *********/
  66799. /********* Start of inlined file: juce_AffineTransform.cpp *********/
  66800. BEGIN_JUCE_NAMESPACE
  66801. AffineTransform::AffineTransform() throw()
  66802. : mat00 (1.0f),
  66803. mat01 (0),
  66804. mat02 (0),
  66805. mat10 (0),
  66806. mat11 (1.0f),
  66807. mat12 (0)
  66808. {
  66809. }
  66810. AffineTransform::AffineTransform (const AffineTransform& other) throw()
  66811. : mat00 (other.mat00),
  66812. mat01 (other.mat01),
  66813. mat02 (other.mat02),
  66814. mat10 (other.mat10),
  66815. mat11 (other.mat11),
  66816. mat12 (other.mat12)
  66817. {
  66818. }
  66819. AffineTransform::AffineTransform (const float mat00_,
  66820. const float mat01_,
  66821. const float mat02_,
  66822. const float mat10_,
  66823. const float mat11_,
  66824. const float mat12_) throw()
  66825. : mat00 (mat00_),
  66826. mat01 (mat01_),
  66827. mat02 (mat02_),
  66828. mat10 (mat10_),
  66829. mat11 (mat11_),
  66830. mat12 (mat12_)
  66831. {
  66832. }
  66833. const AffineTransform& AffineTransform::operator= (const AffineTransform& other) throw()
  66834. {
  66835. mat00 = other.mat00;
  66836. mat01 = other.mat01;
  66837. mat02 = other.mat02;
  66838. mat10 = other.mat10;
  66839. mat11 = other.mat11;
  66840. mat12 = other.mat12;
  66841. return *this;
  66842. }
  66843. bool AffineTransform::operator== (const AffineTransform& other) const throw()
  66844. {
  66845. return mat00 == other.mat00
  66846. && mat01 == other.mat01
  66847. && mat02 == other.mat02
  66848. && mat10 == other.mat10
  66849. && mat11 == other.mat11
  66850. && mat12 == other.mat12;
  66851. }
  66852. bool AffineTransform::operator!= (const AffineTransform& other) const throw()
  66853. {
  66854. return ! operator== (other);
  66855. }
  66856. bool AffineTransform::isIdentity() const throw()
  66857. {
  66858. return (mat01 == 0)
  66859. && (mat02 == 0)
  66860. && (mat10 == 0)
  66861. && (mat12 == 0)
  66862. && (mat00 == 1.0f)
  66863. && (mat11 == 1.0f);
  66864. }
  66865. const AffineTransform AffineTransform::identity;
  66866. const AffineTransform AffineTransform::followedBy (const AffineTransform& other) const throw()
  66867. {
  66868. return AffineTransform (other.mat00 * mat00 + other.mat01 * mat10,
  66869. other.mat00 * mat01 + other.mat01 * mat11,
  66870. other.mat00 * mat02 + other.mat01 * mat12 + other.mat02,
  66871. other.mat10 * mat00 + other.mat11 * mat10,
  66872. other.mat10 * mat01 + other.mat11 * mat11,
  66873. other.mat10 * mat02 + other.mat11 * mat12 + other.mat12);
  66874. }
  66875. const AffineTransform AffineTransform::followedBy (const float omat00,
  66876. const float omat01,
  66877. const float omat02,
  66878. const float omat10,
  66879. const float omat11,
  66880. const float omat12) const throw()
  66881. {
  66882. return AffineTransform (omat00 * mat00 + omat01 * mat10,
  66883. omat00 * mat01 + omat01 * mat11,
  66884. omat00 * mat02 + omat01 * mat12 + omat02,
  66885. omat10 * mat00 + omat11 * mat10,
  66886. omat10 * mat01 + omat11 * mat11,
  66887. omat10 * mat02 + omat11 * mat12 + omat12);
  66888. }
  66889. const AffineTransform AffineTransform::translated (const float dx,
  66890. const float dy) const throw()
  66891. {
  66892. return followedBy (1.0f, 0, dx,
  66893. 0, 1.0f, dy);
  66894. }
  66895. const AffineTransform AffineTransform::translation (const float dx,
  66896. const float dy) throw()
  66897. {
  66898. return AffineTransform (1.0f, 0, dx,
  66899. 0, 1.0f, dy);
  66900. }
  66901. const AffineTransform AffineTransform::rotated (const float rad) const throw()
  66902. {
  66903. const float cosRad = cosf (rad);
  66904. const float sinRad = sinf (rad);
  66905. return followedBy (cosRad, -sinRad, 0,
  66906. sinRad, cosRad, 0);
  66907. }
  66908. const AffineTransform AffineTransform::rotation (const float rad) throw()
  66909. {
  66910. const float cosRad = cosf (rad);
  66911. const float sinRad = sinf (rad);
  66912. return AffineTransform (cosRad, -sinRad, 0,
  66913. sinRad, cosRad, 0);
  66914. }
  66915. const AffineTransform AffineTransform::rotated (const float angle,
  66916. const float pivotX,
  66917. const float pivotY) const throw()
  66918. {
  66919. return translated (-pivotX, -pivotY)
  66920. .rotated (angle)
  66921. .translated (pivotX, pivotY);
  66922. }
  66923. const AffineTransform AffineTransform::rotation (const float angle,
  66924. const float pivotX,
  66925. const float pivotY) throw()
  66926. {
  66927. return translation (-pivotX, -pivotY)
  66928. .rotated (angle)
  66929. .translated (pivotX, pivotY);
  66930. }
  66931. const AffineTransform AffineTransform::scaled (const float factorX,
  66932. const float factorY) const throw()
  66933. {
  66934. return followedBy (factorX, 0, 0,
  66935. 0, factorY, 0);
  66936. }
  66937. const AffineTransform AffineTransform::scale (const float factorX,
  66938. const float factorY) throw()
  66939. {
  66940. return AffineTransform (factorX, 0, 0,
  66941. 0, factorY, 0);
  66942. }
  66943. const AffineTransform AffineTransform::sheared (const float shearX,
  66944. const float shearY) const throw()
  66945. {
  66946. return followedBy (1.0f, shearX, 0,
  66947. shearY, 1.0f, 0);
  66948. }
  66949. const AffineTransform AffineTransform::inverted() const throw()
  66950. {
  66951. double determinant = (mat00 * mat11 - mat10 * mat01);
  66952. if (determinant != 0.0)
  66953. {
  66954. determinant = 1.0 / determinant;
  66955. const float dst00 = (float) (mat11 * determinant);
  66956. const float dst10 = (float) (-mat10 * determinant);
  66957. const float dst01 = (float) (-mat01 * determinant);
  66958. const float dst11 = (float) (mat00 * determinant);
  66959. return AffineTransform (dst00, dst01, -mat02 * dst00 - mat12 * dst01,
  66960. dst10, dst11, -mat02 * dst10 - mat12 * dst11);
  66961. }
  66962. else
  66963. {
  66964. // singularity..
  66965. return *this;
  66966. }
  66967. }
  66968. bool AffineTransform::isSingularity() const throw()
  66969. {
  66970. return (mat00 * mat11 - mat10 * mat01) == 0.0;
  66971. }
  66972. void AffineTransform::transformPoint (float& x,
  66973. float& y) const throw()
  66974. {
  66975. const float oldX = x;
  66976. x = mat00 * oldX + mat01 * y + mat02;
  66977. y = mat10 * oldX + mat11 * y + mat12;
  66978. }
  66979. void AffineTransform::transformPoint (double& x,
  66980. double& y) const throw()
  66981. {
  66982. const double oldX = x;
  66983. x = mat00 * oldX + mat01 * y + mat02;
  66984. y = mat10 * oldX + mat11 * y + mat12;
  66985. }
  66986. END_JUCE_NAMESPACE
  66987. /********* End of inlined file: juce_AffineTransform.cpp *********/
  66988. /********* Start of inlined file: juce_BorderSize.cpp *********/
  66989. BEGIN_JUCE_NAMESPACE
  66990. BorderSize::BorderSize() throw()
  66991. : top (0),
  66992. left (0),
  66993. bottom (0),
  66994. right (0)
  66995. {
  66996. }
  66997. BorderSize::BorderSize (const BorderSize& other) throw()
  66998. : top (other.top),
  66999. left (other.left),
  67000. bottom (other.bottom),
  67001. right (other.right)
  67002. {
  67003. }
  67004. BorderSize::BorderSize (const int topGap,
  67005. const int leftGap,
  67006. const int bottomGap,
  67007. const int rightGap) throw()
  67008. : top (topGap),
  67009. left (leftGap),
  67010. bottom (bottomGap),
  67011. right (rightGap)
  67012. {
  67013. }
  67014. BorderSize::BorderSize (const int allGaps) throw()
  67015. : top (allGaps),
  67016. left (allGaps),
  67017. bottom (allGaps),
  67018. right (allGaps)
  67019. {
  67020. }
  67021. BorderSize::~BorderSize() throw()
  67022. {
  67023. }
  67024. void BorderSize::setTop (const int newTopGap) throw()
  67025. {
  67026. top = newTopGap;
  67027. }
  67028. void BorderSize::setLeft (const int newLeftGap) throw()
  67029. {
  67030. left = newLeftGap;
  67031. }
  67032. void BorderSize::setBottom (const int newBottomGap) throw()
  67033. {
  67034. bottom = newBottomGap;
  67035. }
  67036. void BorderSize::setRight (const int newRightGap) throw()
  67037. {
  67038. right = newRightGap;
  67039. }
  67040. const Rectangle BorderSize::subtractedFrom (const Rectangle& r) const throw()
  67041. {
  67042. return Rectangle (r.getX() + left,
  67043. r.getY() + top,
  67044. r.getWidth() - (left + right),
  67045. r.getHeight() - (top + bottom));
  67046. }
  67047. void BorderSize::subtractFrom (Rectangle& r) const throw()
  67048. {
  67049. r.setBounds (r.getX() + left,
  67050. r.getY() + top,
  67051. r.getWidth() - (left + right),
  67052. r.getHeight() - (top + bottom));
  67053. }
  67054. const Rectangle BorderSize::addedTo (const Rectangle& r) const throw()
  67055. {
  67056. return Rectangle (r.getX() - left,
  67057. r.getY() - top,
  67058. r.getWidth() + (left + right),
  67059. r.getHeight() + (top + bottom));
  67060. }
  67061. void BorderSize::addTo (Rectangle& r) const throw()
  67062. {
  67063. r.setBounds (r.getX() - left,
  67064. r.getY() - top,
  67065. r.getWidth() + (left + right),
  67066. r.getHeight() + (top + bottom));
  67067. }
  67068. bool BorderSize::operator== (const BorderSize& other) const throw()
  67069. {
  67070. return top == other.top
  67071. && left == other.left
  67072. && bottom == other.bottom
  67073. && right == other.right;
  67074. }
  67075. bool BorderSize::operator!= (const BorderSize& other) const throw()
  67076. {
  67077. return ! operator== (other);
  67078. }
  67079. END_JUCE_NAMESPACE
  67080. /********* End of inlined file: juce_BorderSize.cpp *********/
  67081. /********* Start of inlined file: juce_Line.cpp *********/
  67082. BEGIN_JUCE_NAMESPACE
  67083. static bool juce_lineIntersection (const float x1, const float y1,
  67084. const float x2, const float y2,
  67085. const float x3, const float y3,
  67086. const float x4, const float y4,
  67087. float& intersectionX,
  67088. float& intersectionY) throw()
  67089. {
  67090. if (x2 != x3 || y2 != y3)
  67091. {
  67092. const float dx1 = x2 - x1;
  67093. const float dy1 = y2 - y1;
  67094. const float dx2 = x4 - x3;
  67095. const float dy2 = y4 - y3;
  67096. const float divisor = dx1 * dy2 - dx2 * dy1;
  67097. if (divisor == 0)
  67098. {
  67099. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  67100. {
  67101. if (dy1 == 0 && dy2 != 0)
  67102. {
  67103. const float along = (y1 - y3) / dy2;
  67104. intersectionX = x3 + along * dx2;
  67105. intersectionY = y1;
  67106. return along >= 0 && along <= 1.0f;
  67107. }
  67108. else if (dy2 == 0 && dy1 != 0)
  67109. {
  67110. const float along = (y3 - y1) / dy1;
  67111. intersectionX = x1 + along * dx1;
  67112. intersectionY = y3;
  67113. return along >= 0 && along <= 1.0f;
  67114. }
  67115. else if (dx1 == 0 && dx2 != 0)
  67116. {
  67117. const float along = (x1 - x3) / dx2;
  67118. intersectionX = x1;
  67119. intersectionY = y3 + along * dy2;
  67120. return along >= 0 && along <= 1.0f;
  67121. }
  67122. else if (dx2 == 0 && dx1 != 0)
  67123. {
  67124. const float along = (x3 - x1) / dx1;
  67125. intersectionX = x3;
  67126. intersectionY = y1 + along * dy1;
  67127. return along >= 0 && along <= 1.0f;
  67128. }
  67129. }
  67130. intersectionX = 0.5f * (x2 + x3);
  67131. intersectionY = 0.5f * (y2 + y3);
  67132. return false;
  67133. }
  67134. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  67135. intersectionX = x1 + along1 * dx1;
  67136. intersectionY = y1 + along1 * dy1;
  67137. if (along1 < 0 || along1 > 1.0f)
  67138. return false;
  67139. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1) / divisor;
  67140. return along2 >= 0 && along2 <= 1.0f;
  67141. }
  67142. intersectionX = x2;
  67143. intersectionY = y2;
  67144. return true;
  67145. }
  67146. Line::Line() throw()
  67147. : startX (0.0f),
  67148. startY (0.0f),
  67149. endX (0.0f),
  67150. endY (0.0f)
  67151. {
  67152. }
  67153. Line::Line (const Line& other) throw()
  67154. : startX (other.startX),
  67155. startY (other.startY),
  67156. endX (other.endX),
  67157. endY (other.endY)
  67158. {
  67159. }
  67160. Line::Line (const float startX_, const float startY_,
  67161. const float endX_, const float endY_) throw()
  67162. : startX (startX_),
  67163. startY (startY_),
  67164. endX (endX_),
  67165. endY (endY_)
  67166. {
  67167. }
  67168. Line::Line (const Point& start,
  67169. const Point& end) throw()
  67170. : startX (start.getX()),
  67171. startY (start.getY()),
  67172. endX (end.getX()),
  67173. endY (end.getY())
  67174. {
  67175. }
  67176. const Line& Line::operator= (const Line& other) throw()
  67177. {
  67178. startX = other.startX;
  67179. startY = other.startY;
  67180. endX = other.endX;
  67181. endY = other.endY;
  67182. return *this;
  67183. }
  67184. Line::~Line() throw()
  67185. {
  67186. }
  67187. const Point Line::getStart() const throw()
  67188. {
  67189. return Point (startX, startY);
  67190. }
  67191. const Point Line::getEnd() const throw()
  67192. {
  67193. return Point (endX, endY);
  67194. }
  67195. void Line::setStart (const float newStartX,
  67196. const float newStartY) throw()
  67197. {
  67198. startX = newStartX;
  67199. startY = newStartY;
  67200. }
  67201. void Line::setStart (const Point& newStart) throw()
  67202. {
  67203. startX = newStart.getX();
  67204. startY = newStart.getY();
  67205. }
  67206. void Line::setEnd (const float newEndX,
  67207. const float newEndY) throw()
  67208. {
  67209. endX = newEndX;
  67210. endY = newEndY;
  67211. }
  67212. void Line::setEnd (const Point& newEnd) throw()
  67213. {
  67214. endX = newEnd.getX();
  67215. endY = newEnd.getY();
  67216. }
  67217. bool Line::operator== (const Line& other) const throw()
  67218. {
  67219. return startX == other.startX
  67220. && startY == other.startY
  67221. && endX == other.endX
  67222. && endY == other.endY;
  67223. }
  67224. bool Line::operator!= (const Line& other) const throw()
  67225. {
  67226. return startX != other.startX
  67227. || startY != other.startY
  67228. || endX != other.endX
  67229. || endY != other.endY;
  67230. }
  67231. void Line::applyTransform (const AffineTransform& transform) throw()
  67232. {
  67233. transform.transformPoint (startX, startY);
  67234. transform.transformPoint (endX, endY);
  67235. }
  67236. float Line::getLength() const throw()
  67237. {
  67238. return (float) juce_hypot (startX - endX,
  67239. startY - endY);
  67240. }
  67241. float Line::getAngle() const throw()
  67242. {
  67243. return atan2f (endX - startX,
  67244. endY - startY);
  67245. }
  67246. const Point Line::getPointAlongLine (const float distanceFromStart) const throw()
  67247. {
  67248. const float alpha = distanceFromStart / getLength();
  67249. return Point (startX + (endX - startX) * alpha,
  67250. startY + (endY - startY) * alpha);
  67251. }
  67252. const Point Line::getPointAlongLine (const float offsetX,
  67253. const float offsetY) const throw()
  67254. {
  67255. const float dx = endX - startX;
  67256. const float dy = endY - startY;
  67257. const double length = juce_hypot (dx, dy);
  67258. if (length == 0)
  67259. return Point (startX, startY);
  67260. else
  67261. return Point (startX + (float) (((dx * offsetX) - (dy * offsetY)) / length),
  67262. startY + (float) (((dy * offsetX) + (dx * offsetY)) / length));
  67263. }
  67264. const Point Line::getPointAlongLineProportionally (const float alpha) const throw()
  67265. {
  67266. return Point (startX + (endX - startX) * alpha,
  67267. startY + (endY - startY) * alpha);
  67268. }
  67269. float Line::getDistanceFromLine (const float x,
  67270. const float y) const throw()
  67271. {
  67272. const double dx = endX - startX;
  67273. const double dy = endY - startY;
  67274. const double length = dx * dx + dy * dy;
  67275. if (length > 0)
  67276. {
  67277. const double prop = ((x - startX) * dx + (y - startY) * dy) / length;
  67278. if (prop >= 0.0f && prop < 1.0f)
  67279. {
  67280. return (float) juce_hypot (x - (startX + prop * dx),
  67281. y - (startY + prop * dy));
  67282. }
  67283. }
  67284. return (float) jmin (juce_hypot (x - startX, y - startY),
  67285. juce_hypot (x - endX, y - endY));
  67286. }
  67287. float Line::findNearestPointTo (const float x,
  67288. const float y) const throw()
  67289. {
  67290. const double dx = endX - startX;
  67291. const double dy = endY - startY;
  67292. const double length = dx * dx + dy * dy;
  67293. if (length <= 0.0)
  67294. return 0.0f;
  67295. return jlimit (0.0f, 1.0f,
  67296. (float) (((x - startX) * dx + (y - startY) * dy) / length));
  67297. }
  67298. const Line Line::withShortenedStart (const float distanceToShortenBy) const throw()
  67299. {
  67300. const float length = getLength();
  67301. return Line (getPointAlongLine (jmin (distanceToShortenBy, length)),
  67302. getEnd());
  67303. }
  67304. const Line Line::withShortenedEnd (const float distanceToShortenBy) const throw()
  67305. {
  67306. const float length = getLength();
  67307. return Line (getStart(),
  67308. getPointAlongLine (length - jmin (distanceToShortenBy, length)));
  67309. }
  67310. bool Line::clipToPath (const Path& path,
  67311. const bool keepSectionOutsidePath) throw()
  67312. {
  67313. const bool startInside = path.contains (startX, startY);
  67314. const bool endInside = path.contains (endX, endY);
  67315. if (startInside == endInside)
  67316. {
  67317. if (keepSectionOutsidePath != startInside)
  67318. {
  67319. // entirely outside the path
  67320. return false;
  67321. }
  67322. else
  67323. {
  67324. // entirely inside the path
  67325. startX = 0.0f;
  67326. startY = 0.0f;
  67327. endX = 0.0f;
  67328. endY = 0.0f;
  67329. return true;
  67330. }
  67331. }
  67332. else
  67333. {
  67334. bool changed = false;
  67335. PathFlatteningIterator iter (path, AffineTransform::identity);
  67336. while (iter.next())
  67337. {
  67338. float ix, iy;
  67339. if (intersects (Line (iter.x1, iter.y1,
  67340. iter.x2, iter.y2),
  67341. ix, iy))
  67342. {
  67343. if ((startInside && keepSectionOutsidePath)
  67344. || (endInside && ! keepSectionOutsidePath))
  67345. {
  67346. setStart (ix, iy);
  67347. }
  67348. else
  67349. {
  67350. setEnd (ix, iy);
  67351. }
  67352. changed = true;
  67353. }
  67354. }
  67355. return changed;
  67356. }
  67357. }
  67358. bool Line::intersects (const Line& line,
  67359. float& intersectionX,
  67360. float& intersectionY) const throw()
  67361. {
  67362. return juce_lineIntersection (startX, startY,
  67363. endX, endY,
  67364. line.startX, line.startY,
  67365. line.endX, line.endY,
  67366. intersectionX,
  67367. intersectionY);
  67368. }
  67369. bool Line::isVertical() const throw()
  67370. {
  67371. return startX == endX;
  67372. }
  67373. bool Line::isHorizontal() const throw()
  67374. {
  67375. return startY == endY;
  67376. }
  67377. bool Line::isPointAbove (const float x, const float y) const throw()
  67378. {
  67379. return startX != endX
  67380. && y < ((endY - startY) * (x - startX)) / (endX - startX) + startY;
  67381. }
  67382. END_JUCE_NAMESPACE
  67383. /********* End of inlined file: juce_Line.cpp *********/
  67384. /********* Start of inlined file: juce_Path.cpp *********/
  67385. BEGIN_JUCE_NAMESPACE
  67386. // tests that some co-ords aren't NaNs
  67387. #define CHECK_COORDS_ARE_VALID(x, y) \
  67388. jassert (x == x && y == y);
  67389. const float Path::lineMarker = 100001.0f;
  67390. const float Path::moveMarker = 100002.0f;
  67391. const float Path::quadMarker = 100003.0f;
  67392. const float Path::cubicMarker = 100004.0f;
  67393. const float Path::closeSubPathMarker = 100005.0f;
  67394. static const int defaultGranularity = 32;
  67395. Path::Path() throw()
  67396. : ArrayAllocationBase <float> (defaultGranularity),
  67397. numElements (0),
  67398. pathXMin (0),
  67399. pathXMax (0),
  67400. pathYMin (0),
  67401. pathYMax (0),
  67402. useNonZeroWinding (true)
  67403. {
  67404. }
  67405. Path::~Path() throw()
  67406. {
  67407. }
  67408. Path::Path (const Path& other) throw()
  67409. : ArrayAllocationBase <float> (defaultGranularity),
  67410. numElements (other.numElements),
  67411. pathXMin (other.pathXMin),
  67412. pathXMax (other.pathXMax),
  67413. pathYMin (other.pathYMin),
  67414. pathYMax (other.pathYMax),
  67415. useNonZeroWinding (other.useNonZeroWinding)
  67416. {
  67417. if (numElements > 0)
  67418. {
  67419. setAllocatedSize (numElements);
  67420. memcpy (elements, other.elements, numElements * sizeof (float));
  67421. }
  67422. }
  67423. const Path& Path::operator= (const Path& other) throw()
  67424. {
  67425. if (this != &other)
  67426. {
  67427. ensureAllocatedSize (other.numElements);
  67428. numElements = other.numElements;
  67429. pathXMin = other.pathXMin;
  67430. pathXMax = other.pathXMax;
  67431. pathYMin = other.pathYMin;
  67432. pathYMax = other.pathYMax;
  67433. useNonZeroWinding = other.useNonZeroWinding;
  67434. if (numElements > 0)
  67435. memcpy (elements, other.elements, numElements * sizeof (float));
  67436. }
  67437. return *this;
  67438. }
  67439. void Path::clear() throw()
  67440. {
  67441. numElements = 0;
  67442. pathXMin = 0;
  67443. pathYMin = 0;
  67444. pathYMax = 0;
  67445. pathXMax = 0;
  67446. }
  67447. void Path::swapWithPath (Path& other)
  67448. {
  67449. swapVariables <int> (this->numAllocated, other.numAllocated);
  67450. swapVariables <float*> (this->elements, other.elements);
  67451. swapVariables <int> (this->numElements, other.numElements);
  67452. swapVariables <float> (this->pathXMin, other.pathXMin);
  67453. swapVariables <float> (this->pathXMax, other.pathXMax);
  67454. swapVariables <float> (this->pathYMin, other.pathYMin);
  67455. swapVariables <float> (this->pathYMax, other.pathYMax);
  67456. swapVariables <bool> (this->useNonZeroWinding, other.useNonZeroWinding);
  67457. }
  67458. void Path::setUsingNonZeroWinding (const bool isNonZero) throw()
  67459. {
  67460. useNonZeroWinding = isNonZero;
  67461. }
  67462. void Path::scaleToFit (const float x, const float y, const float w, const float h,
  67463. const bool preserveProportions) throw()
  67464. {
  67465. applyTransform (getTransformToScaleToFit (x, y, w, h, preserveProportions));
  67466. }
  67467. bool Path::isEmpty() const throw()
  67468. {
  67469. int i = 0;
  67470. while (i < numElements)
  67471. {
  67472. const float type = elements [i++];
  67473. if (type == moveMarker)
  67474. {
  67475. i += 2;
  67476. }
  67477. else if (type == lineMarker
  67478. || type == quadMarker
  67479. || type == cubicMarker)
  67480. {
  67481. return false;
  67482. }
  67483. }
  67484. return true;
  67485. }
  67486. void Path::getBounds (float& x, float& y,
  67487. float& w, float& h) const throw()
  67488. {
  67489. x = pathXMin;
  67490. y = pathYMin;
  67491. w = pathXMax - pathXMin;
  67492. h = pathYMax - pathYMin;
  67493. }
  67494. void Path::getBoundsTransformed (const AffineTransform& transform,
  67495. float& x, float& y,
  67496. float& w, float& h) const throw()
  67497. {
  67498. float x1 = pathXMin;
  67499. float y1 = pathYMin;
  67500. transform.transformPoint (x1, y1);
  67501. float x2 = pathXMax;
  67502. float y2 = pathYMin;
  67503. transform.transformPoint (x2, y2);
  67504. float x3 = pathXMin;
  67505. float y3 = pathYMax;
  67506. transform.transformPoint (x3, y3);
  67507. float x4 = pathXMax;
  67508. float y4 = pathYMax;
  67509. transform.transformPoint (x4, y4);
  67510. x = jmin (x1, x2, x3, x4);
  67511. y = jmin (y1, y2, y3, y4);
  67512. w = jmax (x1, x2, x3, x4) - x;
  67513. h = jmax (y1, y2, y3, y4) - y;
  67514. }
  67515. void Path::startNewSubPath (const float x,
  67516. const float y) throw()
  67517. {
  67518. CHECK_COORDS_ARE_VALID (x, y);
  67519. if (numElements == 0)
  67520. {
  67521. pathXMin = pathXMax = x;
  67522. pathYMin = pathYMax = y;
  67523. }
  67524. else
  67525. {
  67526. pathXMin = jmin (pathXMin, x);
  67527. pathXMax = jmax (pathXMax, x);
  67528. pathYMin = jmin (pathYMin, y);
  67529. pathYMax = jmax (pathYMax, y);
  67530. }
  67531. ensureAllocatedSize (numElements + 3);
  67532. elements [numElements++] = moveMarker;
  67533. elements [numElements++] = x;
  67534. elements [numElements++] = y;
  67535. }
  67536. void Path::lineTo (const float x, const float y) throw()
  67537. {
  67538. CHECK_COORDS_ARE_VALID (x, y);
  67539. if (numElements == 0)
  67540. startNewSubPath (0, 0);
  67541. ensureAllocatedSize (numElements + 3);
  67542. elements [numElements++] = lineMarker;
  67543. elements [numElements++] = x;
  67544. elements [numElements++] = y;
  67545. pathXMin = jmin (pathXMin, x);
  67546. pathXMax = jmax (pathXMax, x);
  67547. pathYMin = jmin (pathYMin, y);
  67548. pathYMax = jmax (pathYMax, y);
  67549. }
  67550. void Path::quadraticTo (const float x1, const float y1,
  67551. const float x2, const float y2) throw()
  67552. {
  67553. CHECK_COORDS_ARE_VALID (x1, y1);
  67554. CHECK_COORDS_ARE_VALID (x2, y2);
  67555. if (numElements == 0)
  67556. startNewSubPath (0, 0);
  67557. ensureAllocatedSize (numElements + 5);
  67558. elements [numElements++] = quadMarker;
  67559. elements [numElements++] = x1;
  67560. elements [numElements++] = y1;
  67561. elements [numElements++] = x2;
  67562. elements [numElements++] = y2;
  67563. pathXMin = jmin (pathXMin, x1, x2);
  67564. pathXMax = jmax (pathXMax, x1, x2);
  67565. pathYMin = jmin (pathYMin, y1, y2);
  67566. pathYMax = jmax (pathYMax, y1, y2);
  67567. }
  67568. void Path::cubicTo (const float x1, const float y1,
  67569. const float x2, const float y2,
  67570. const float x3, const float y3) throw()
  67571. {
  67572. CHECK_COORDS_ARE_VALID (x1, y1);
  67573. CHECK_COORDS_ARE_VALID (x2, y2);
  67574. CHECK_COORDS_ARE_VALID (x3, y3);
  67575. if (numElements == 0)
  67576. startNewSubPath (0, 0);
  67577. ensureAllocatedSize (numElements + 7);
  67578. elements [numElements++] = cubicMarker;
  67579. elements [numElements++] = x1;
  67580. elements [numElements++] = y1;
  67581. elements [numElements++] = x2;
  67582. elements [numElements++] = y2;
  67583. elements [numElements++] = x3;
  67584. elements [numElements++] = y3;
  67585. pathXMin = jmin (pathXMin, x1, x2, x3);
  67586. pathXMax = jmax (pathXMax, x1, x2, x3);
  67587. pathYMin = jmin (pathYMin, y1, y2, y3);
  67588. pathYMax = jmax (pathYMax, y1, y2, y3);
  67589. }
  67590. void Path::closeSubPath() throw()
  67591. {
  67592. if (numElements > 0
  67593. && elements [numElements - 1] != closeSubPathMarker)
  67594. {
  67595. ensureAllocatedSize (numElements + 1);
  67596. elements [numElements++] = closeSubPathMarker;
  67597. }
  67598. }
  67599. const Point Path::getCurrentPosition() const
  67600. {
  67601. int i = numElements - 1;
  67602. if (i > 0 && elements[i] == closeSubPathMarker)
  67603. {
  67604. while (i >= 0)
  67605. {
  67606. if (elements[i] == moveMarker)
  67607. {
  67608. i += 2;
  67609. break;
  67610. }
  67611. --i;
  67612. }
  67613. }
  67614. if (i > 0)
  67615. return Point (elements [i - 1], elements [i]);
  67616. return Point (0.0f, 0.0f);
  67617. }
  67618. void Path::addRectangle (const float x, const float y,
  67619. const float w, const float h) throw()
  67620. {
  67621. startNewSubPath (x, y + h);
  67622. lineTo (x, y);
  67623. lineTo (x + w, y);
  67624. lineTo (x + w, y + h);
  67625. closeSubPath();
  67626. }
  67627. void Path::addRoundedRectangle (const float x, const float y,
  67628. const float w, const float h,
  67629. float csx,
  67630. float csy) throw()
  67631. {
  67632. csx = jmin (csx, w * 0.5f);
  67633. csy = jmin (csy, h * 0.5f);
  67634. const float cs45x = csx * 0.45f;
  67635. const float cs45y = csy * 0.45f;
  67636. const float x2 = x + w;
  67637. const float y2 = y + h;
  67638. startNewSubPath (x + csx, y);
  67639. lineTo (x2 - csx, y);
  67640. cubicTo (x2 - cs45x, y, x2, y + cs45y, x2, y + csy);
  67641. lineTo (x2, y2 - csy);
  67642. cubicTo (x2, y2 - cs45y, x2 - cs45x, y2, x2 - csx, y2);
  67643. lineTo (x + csx, y2);
  67644. cubicTo (x + cs45x, y2, x, y2 - cs45y, x, y2 - csy);
  67645. lineTo (x, y + csy);
  67646. cubicTo (x, y + cs45y, x + cs45x, y, x + csx, y);
  67647. closeSubPath();
  67648. }
  67649. void Path::addRoundedRectangle (const float x, const float y,
  67650. const float w, const float h,
  67651. float cs) throw()
  67652. {
  67653. addRoundedRectangle (x, y, w, h, cs, cs);
  67654. }
  67655. void Path::addTriangle (const float x1, const float y1,
  67656. const float x2, const float y2,
  67657. const float x3, const float y3) throw()
  67658. {
  67659. startNewSubPath (x1, y1);
  67660. lineTo (x2, y2);
  67661. lineTo (x3, y3);
  67662. closeSubPath();
  67663. }
  67664. void Path::addQuadrilateral (const float x1, const float y1,
  67665. const float x2, const float y2,
  67666. const float x3, const float y3,
  67667. const float x4, const float y4) throw()
  67668. {
  67669. startNewSubPath (x1, y1);
  67670. lineTo (x2, y2);
  67671. lineTo (x3, y3);
  67672. lineTo (x4, y4);
  67673. closeSubPath();
  67674. }
  67675. void Path::addEllipse (const float x, const float y,
  67676. const float w, const float h) throw()
  67677. {
  67678. const float hw = w * 0.5f;
  67679. const float hw55 = hw * 0.55f;
  67680. const float hh = h * 0.5f;
  67681. const float hh45 = hh * 0.55f;
  67682. const float cx = x + hw;
  67683. const float cy = y + hh;
  67684. startNewSubPath (cx, cy - hh);
  67685. cubicTo (cx + hw55, cy - hh, cx + hw, cy - hh45, cx + hw, cy);
  67686. cubicTo (cx + hw, cy + hh45, cx + hw55, cy + hh, cx, cy + hh);
  67687. cubicTo (cx - hw55, cy + hh, cx - hw, cy + hh45, cx - hw, cy);
  67688. cubicTo (cx - hw, cy - hh45, cx - hw55, cy - hh, cx, cy - hh);
  67689. closeSubPath();
  67690. }
  67691. void Path::addArc (const float x, const float y,
  67692. const float w, const float h,
  67693. const float fromRadians,
  67694. const float toRadians,
  67695. const bool startAsNewSubPath) throw()
  67696. {
  67697. const float radiusX = w / 2.0f;
  67698. const float radiusY = h / 2.0f;
  67699. addCentredArc (x + radiusX,
  67700. y + radiusY,
  67701. radiusX, radiusY,
  67702. 0.0f,
  67703. fromRadians, toRadians,
  67704. startAsNewSubPath);
  67705. }
  67706. static const float ellipseAngularIncrement = 0.05f;
  67707. void Path::addCentredArc (const float centreX, const float centreY,
  67708. const float radiusX, const float radiusY,
  67709. const float rotationOfEllipse,
  67710. const float fromRadians,
  67711. const float toRadians,
  67712. const bool startAsNewSubPath) throw()
  67713. {
  67714. if (radiusX > 0.0f && radiusY > 0.0f)
  67715. {
  67716. const AffineTransform rotation (AffineTransform::rotation (rotationOfEllipse, centreX, centreY));
  67717. float angle = fromRadians;
  67718. if (startAsNewSubPath)
  67719. {
  67720. float x = centreX + radiusX * sinf (angle);
  67721. float y = centreY - radiusY * cosf (angle);
  67722. if (rotationOfEllipse != 0)
  67723. rotation.transformPoint (x, y);
  67724. startNewSubPath (x, y);
  67725. }
  67726. if (fromRadians < toRadians)
  67727. {
  67728. if (startAsNewSubPath)
  67729. angle += ellipseAngularIncrement;
  67730. while (angle < toRadians)
  67731. {
  67732. float x = centreX + radiusX * sinf (angle);
  67733. float y = centreY - radiusY * cosf (angle);
  67734. if (rotationOfEllipse != 0)
  67735. rotation.transformPoint (x, y);
  67736. lineTo (x, y);
  67737. angle += ellipseAngularIncrement;
  67738. }
  67739. }
  67740. else
  67741. {
  67742. if (startAsNewSubPath)
  67743. angle -= ellipseAngularIncrement;
  67744. while (angle > toRadians)
  67745. {
  67746. float x = centreX + radiusX * sinf (angle);
  67747. float y = centreY - radiusY * cosf (angle);
  67748. if (rotationOfEllipse != 0)
  67749. rotation.transformPoint (x, y);
  67750. lineTo (x, y);
  67751. angle -= ellipseAngularIncrement;
  67752. }
  67753. }
  67754. float x = centreX + radiusX * sinf (toRadians);
  67755. float y = centreY - radiusY * cosf (toRadians);
  67756. if (rotationOfEllipse != 0)
  67757. rotation.transformPoint (x, y);
  67758. lineTo (x, y);
  67759. }
  67760. }
  67761. void Path::addPieSegment (const float x, const float y,
  67762. const float width, const float height,
  67763. const float fromRadians,
  67764. const float toRadians,
  67765. const float innerCircleProportionalSize)
  67766. {
  67767. float hw = width * 0.5f;
  67768. float hh = height * 0.5f;
  67769. const float centreX = x + hw;
  67770. const float centreY = y + hh;
  67771. startNewSubPath (centreX + hw * sinf (fromRadians),
  67772. centreY - hh * cosf (fromRadians));
  67773. addArc (x, y, width, height, fromRadians, toRadians);
  67774. if (fabs (fromRadians - toRadians) > float_Pi * 1.999f)
  67775. {
  67776. closeSubPath();
  67777. if (innerCircleProportionalSize > 0)
  67778. {
  67779. hw *= innerCircleProportionalSize;
  67780. hh *= innerCircleProportionalSize;
  67781. startNewSubPath (centreX + hw * sinf (toRadians),
  67782. centreY - hh * cosf (toRadians));
  67783. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  67784. toRadians, fromRadians);
  67785. }
  67786. }
  67787. else
  67788. {
  67789. if (innerCircleProportionalSize > 0)
  67790. {
  67791. hw *= innerCircleProportionalSize;
  67792. hh *= innerCircleProportionalSize;
  67793. addArc (centreX - hw, centreY - hh, hw * 2.0f, hh * 2.0f,
  67794. toRadians, fromRadians);
  67795. }
  67796. else
  67797. {
  67798. lineTo (centreX, centreY);
  67799. }
  67800. }
  67801. closeSubPath();
  67802. }
  67803. static void perpendicularOffset (const float x1, const float y1,
  67804. const float x2, const float y2,
  67805. const float offsetX, const float offsetY,
  67806. float& resultX, float& resultY) throw()
  67807. {
  67808. const float dx = x2 - x1;
  67809. const float dy = y2 - y1;
  67810. const float len = juce_hypotf (dx, dy);
  67811. if (len == 0)
  67812. {
  67813. resultX = x1;
  67814. resultY = y1;
  67815. }
  67816. else
  67817. {
  67818. resultX = x1 + ((dx * offsetX) - (dy * offsetY)) / len;
  67819. resultY = y1 + ((dy * offsetX) + (dx * offsetY)) / len;
  67820. }
  67821. }
  67822. void Path::addLineSegment (const float startX, const float startY,
  67823. const float endX, const float endY,
  67824. float lineThickness) throw()
  67825. {
  67826. lineThickness *= 0.5f;
  67827. float x, y;
  67828. perpendicularOffset (startX, startY, endX, endY,
  67829. 0, lineThickness, x, y);
  67830. startNewSubPath (x, y);
  67831. perpendicularOffset (startX, startY, endX, endY,
  67832. 0, -lineThickness, x, y);
  67833. lineTo (x, y);
  67834. perpendicularOffset (endX, endY, startX, startY,
  67835. 0, lineThickness, x, y);
  67836. lineTo (x, y);
  67837. perpendicularOffset (endX, endY, startX, startY,
  67838. 0, -lineThickness, x, y);
  67839. lineTo (x, y);
  67840. closeSubPath();
  67841. }
  67842. void Path::addArrow (const float startX, const float startY,
  67843. const float endX, const float endY,
  67844. float lineThickness,
  67845. float arrowheadWidth,
  67846. float arrowheadLength) throw()
  67847. {
  67848. lineThickness *= 0.5f;
  67849. arrowheadWidth *= 0.5f;
  67850. arrowheadLength = jmin (arrowheadLength, 0.8f * juce_hypotf (startX - endX,
  67851. startY - endY));
  67852. float x, y;
  67853. perpendicularOffset (startX, startY, endX, endY,
  67854. 0, lineThickness, x, y);
  67855. startNewSubPath (x, y);
  67856. perpendicularOffset (startX, startY, endX, endY,
  67857. 0, -lineThickness, x, y);
  67858. lineTo (x, y);
  67859. perpendicularOffset (endX, endY, startX, startY,
  67860. arrowheadLength, lineThickness, x, y);
  67861. lineTo (x, y);
  67862. perpendicularOffset (endX, endY, startX, startY,
  67863. arrowheadLength, arrowheadWidth, x, y);
  67864. lineTo (x, y);
  67865. perpendicularOffset (endX, endY, startX, startY,
  67866. 0, 0, x, y);
  67867. lineTo (x, y);
  67868. perpendicularOffset (endX, endY, startX, startY,
  67869. arrowheadLength, -arrowheadWidth, x, y);
  67870. lineTo (x, y);
  67871. perpendicularOffset (endX, endY, startX, startY,
  67872. arrowheadLength, -lineThickness, x, y);
  67873. lineTo (x, y);
  67874. closeSubPath();
  67875. }
  67876. void Path::addStar (const float centreX,
  67877. const float centreY,
  67878. const int numberOfPoints,
  67879. const float innerRadius,
  67880. const float outerRadius,
  67881. const float startAngle)
  67882. {
  67883. jassert (numberOfPoints > 1); // this would be silly.
  67884. if (numberOfPoints > 1)
  67885. {
  67886. const float angleBetweenPoints = float_Pi * 2.0f / numberOfPoints;
  67887. for (int i = 0; i < numberOfPoints; ++i)
  67888. {
  67889. float angle = startAngle + i * angleBetweenPoints;
  67890. const float x = centreX + outerRadius * sinf (angle);
  67891. const float y = centreY - outerRadius * cosf (angle);
  67892. if (i == 0)
  67893. startNewSubPath (x, y);
  67894. else
  67895. lineTo (x, y);
  67896. angle += angleBetweenPoints * 0.5f;
  67897. lineTo (centreX + innerRadius * sinf (angle),
  67898. centreY - innerRadius * cosf (angle));
  67899. }
  67900. closeSubPath();
  67901. }
  67902. }
  67903. void Path::addBubble (float x, float y,
  67904. float w, float h,
  67905. float cs,
  67906. float tipX,
  67907. float tipY,
  67908. int whichSide,
  67909. float arrowPos,
  67910. float arrowWidth)
  67911. {
  67912. if (w > 1.0f && h > 1.0f)
  67913. {
  67914. cs = jmin (cs, w * 0.5f, h * 0.5f);
  67915. const float cs2 = 2.0f * cs;
  67916. startNewSubPath (x + cs, y);
  67917. if (whichSide == 0)
  67918. {
  67919. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  67920. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  67921. lineTo (arrowX1, y);
  67922. lineTo (tipX, tipY);
  67923. lineTo (arrowX1 + halfArrowW * 2.0f, y);
  67924. }
  67925. lineTo (x + w - cs, y);
  67926. if (cs > 0.0f)
  67927. addArc (x + w - cs2, y, cs2, cs2, 0, float_Pi * 0.5f);
  67928. if (whichSide == 3)
  67929. {
  67930. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  67931. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  67932. lineTo (x + w, arrowY1);
  67933. lineTo (tipX, tipY);
  67934. lineTo (x + w, arrowY1 + halfArrowH * 2.0f);
  67935. }
  67936. lineTo (x + w, y + h - cs);
  67937. if (cs > 0.0f)
  67938. addArc (x + w - cs2, y + h - cs2, cs2, cs2, float_Pi * 0.5f, float_Pi);
  67939. if (whichSide == 2)
  67940. {
  67941. const float halfArrowW = jmin (arrowWidth, w - cs2) * 0.5f;
  67942. const float arrowX1 = x + cs + jmax (0.0f, (w - cs2) * arrowPos - halfArrowW);
  67943. lineTo (arrowX1 + halfArrowW * 2.0f, y + h);
  67944. lineTo (tipX, tipY);
  67945. lineTo (arrowX1, y + h);
  67946. }
  67947. lineTo (x + cs, y + h);
  67948. if (cs > 0.0f)
  67949. addArc (x, y + h - cs2, cs2, cs2, float_Pi, float_Pi * 1.5f);
  67950. if (whichSide == 1)
  67951. {
  67952. const float halfArrowH = jmin (arrowWidth, h - cs2) * 0.5f;
  67953. const float arrowY1 = y + cs + jmax (0.0f, (h - cs2) * arrowPos - halfArrowH);
  67954. lineTo (x, arrowY1 + halfArrowH * 2.0f);
  67955. lineTo (tipX, tipY);
  67956. lineTo (x, arrowY1);
  67957. }
  67958. lineTo (x, y + cs);
  67959. if (cs > 0.0f)
  67960. addArc (x, y, cs2, cs2, float_Pi * 1.5f, float_Pi * 2.0f - ellipseAngularIncrement);
  67961. closeSubPath();
  67962. }
  67963. }
  67964. void Path::addPath (const Path& other) throw()
  67965. {
  67966. int i = 0;
  67967. while (i < other.numElements)
  67968. {
  67969. const float type = other.elements [i++];
  67970. if (type == moveMarker)
  67971. {
  67972. startNewSubPath (other.elements [i],
  67973. other.elements [i + 1]);
  67974. i += 2;
  67975. }
  67976. else if (type == lineMarker)
  67977. {
  67978. lineTo (other.elements [i],
  67979. other.elements [i + 1]);
  67980. i += 2;
  67981. }
  67982. else if (type == quadMarker)
  67983. {
  67984. quadraticTo (other.elements [i],
  67985. other.elements [i + 1],
  67986. other.elements [i + 2],
  67987. other.elements [i + 3]);
  67988. i += 4;
  67989. }
  67990. else if (type == cubicMarker)
  67991. {
  67992. cubicTo (other.elements [i],
  67993. other.elements [i + 1],
  67994. other.elements [i + 2],
  67995. other.elements [i + 3],
  67996. other.elements [i + 4],
  67997. other.elements [i + 5]);
  67998. i += 6;
  67999. }
  68000. else if (type == closeSubPathMarker)
  68001. {
  68002. closeSubPath();
  68003. }
  68004. else
  68005. {
  68006. // something's gone wrong with the element list!
  68007. jassertfalse
  68008. }
  68009. }
  68010. }
  68011. void Path::addPath (const Path& other,
  68012. const AffineTransform& transformToApply) throw()
  68013. {
  68014. int i = 0;
  68015. while (i < other.numElements)
  68016. {
  68017. const float type = other.elements [i++];
  68018. if (type == closeSubPathMarker)
  68019. {
  68020. closeSubPath();
  68021. }
  68022. else
  68023. {
  68024. float x = other.elements [i++];
  68025. float y = other.elements [i++];
  68026. transformToApply.transformPoint (x, y);
  68027. if (type == moveMarker)
  68028. {
  68029. startNewSubPath (x, y);
  68030. }
  68031. else if (type == lineMarker)
  68032. {
  68033. lineTo (x, y);
  68034. }
  68035. else if (type == quadMarker)
  68036. {
  68037. float x2 = other.elements [i++];
  68038. float y2 = other.elements [i++];
  68039. transformToApply.transformPoint (x2, y2);
  68040. quadraticTo (x, y, x2, y2);
  68041. }
  68042. else if (type == cubicMarker)
  68043. {
  68044. float x2 = other.elements [i++];
  68045. float y2 = other.elements [i++];
  68046. float x3 = other.elements [i++];
  68047. float y3 = other.elements [i++];
  68048. transformToApply.transformPoint (x2, y2);
  68049. transformToApply.transformPoint (x3, y3);
  68050. cubicTo (x, y, x2, y2, x3, y3);
  68051. }
  68052. else
  68053. {
  68054. // something's gone wrong with the element list!
  68055. jassertfalse
  68056. }
  68057. }
  68058. }
  68059. }
  68060. void Path::applyTransform (const AffineTransform& transform) throw()
  68061. {
  68062. int i = 0;
  68063. pathYMin = pathXMin = 0;
  68064. pathYMax = pathXMax = 0;
  68065. bool setMaxMin = false;
  68066. while (i < numElements)
  68067. {
  68068. const float type = elements [i++];
  68069. if (type == moveMarker)
  68070. {
  68071. transform.transformPoint (elements [i],
  68072. elements [i + 1]);
  68073. if (setMaxMin)
  68074. {
  68075. pathXMin = jmin (pathXMin, elements [i]);
  68076. pathXMax = jmax (pathXMax, elements [i]);
  68077. pathYMin = jmin (pathYMin, elements [i + 1]);
  68078. pathYMax = jmax (pathYMax, elements [i + 1]);
  68079. }
  68080. else
  68081. {
  68082. pathXMin = pathXMax = elements [i];
  68083. pathYMin = pathYMax = elements [i + 1];
  68084. setMaxMin = true;
  68085. }
  68086. i += 2;
  68087. }
  68088. else if (type == lineMarker)
  68089. {
  68090. transform.transformPoint (elements [i],
  68091. elements [i + 1]);
  68092. pathXMin = jmin (pathXMin, elements [i]);
  68093. pathXMax = jmax (pathXMax, elements [i]);
  68094. pathYMin = jmin (pathYMin, elements [i + 1]);
  68095. pathYMax = jmax (pathYMax, elements [i + 1]);
  68096. i += 2;
  68097. }
  68098. else if (type == quadMarker)
  68099. {
  68100. transform.transformPoint (elements [i],
  68101. elements [i + 1]);
  68102. transform.transformPoint (elements [i + 2],
  68103. elements [i + 3]);
  68104. pathXMin = jmin (pathXMin, elements [i], elements [i + 2]);
  68105. pathXMax = jmax (pathXMax, elements [i], elements [i + 2]);
  68106. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3]);
  68107. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3]);
  68108. i += 4;
  68109. }
  68110. else if (type == cubicMarker)
  68111. {
  68112. transform.transformPoint (elements [i],
  68113. elements [i + 1]);
  68114. transform.transformPoint (elements [i + 2],
  68115. elements [i + 3]);
  68116. transform.transformPoint (elements [i + 4],
  68117. elements [i + 5]);
  68118. pathXMin = jmin (pathXMin, elements [i], elements [i + 2], elements [i + 4]);
  68119. pathXMax = jmax (pathXMax, elements [i], elements [i + 2], elements [i + 4]);
  68120. pathYMin = jmin (pathYMin, elements [i + 1], elements [i + 3], elements [i + 5]);
  68121. pathYMax = jmax (pathYMax, elements [i + 1], elements [i + 3], elements [i + 5]);
  68122. i += 6;
  68123. }
  68124. }
  68125. }
  68126. const AffineTransform Path::getTransformToScaleToFit (const float x, const float y,
  68127. const float w, const float h,
  68128. const bool preserveProportions,
  68129. const Justification& justification) const throw()
  68130. {
  68131. float sx, sy, sw, sh;
  68132. getBounds (sx, sy, sw, sh);
  68133. if (preserveProportions)
  68134. {
  68135. if (w <= 0 || h <= 0 || sw <= 0 || sh <= 0)
  68136. return AffineTransform::identity;
  68137. float newW, newH;
  68138. const float srcRatio = sh / sw;
  68139. if (srcRatio > h / w)
  68140. {
  68141. newW = h / srcRatio;
  68142. newH = h;
  68143. }
  68144. else
  68145. {
  68146. newW = w;
  68147. newH = w * srcRatio;
  68148. }
  68149. float newXCentre = x;
  68150. float newYCentre = y;
  68151. if (justification.testFlags (Justification::left))
  68152. newXCentre += newW * 0.5f;
  68153. else if (justification.testFlags (Justification::right))
  68154. newXCentre += w - newW * 0.5f;
  68155. else
  68156. newXCentre += w * 0.5f;
  68157. if (justification.testFlags (Justification::top))
  68158. newYCentre += newH * 0.5f;
  68159. else if (justification.testFlags (Justification::bottom))
  68160. newYCentre += h - newH * 0.5f;
  68161. else
  68162. newYCentre += h * 0.5f;
  68163. return AffineTransform::translation (sw * -0.5f - sx, sh * -0.5f - sy)
  68164. .scaled (newW / sw, newH / sh)
  68165. .translated (newXCentre, newYCentre);
  68166. }
  68167. else
  68168. {
  68169. return AffineTransform::translation (-sx, -sy)
  68170. .scaled (w / sw, h / sh)
  68171. .translated (x, y);
  68172. }
  68173. }
  68174. static const float collisionDetectionTolerence = 20.0f;
  68175. bool Path::contains (const float x, const float y) const throw()
  68176. {
  68177. if (x <= pathXMin || x >= pathXMax
  68178. || y <= pathYMin || y >= pathYMax)
  68179. return false;
  68180. PathFlatteningIterator i (*this, AffineTransform::identity, collisionDetectionTolerence);
  68181. int positiveCrossings = 0;
  68182. int negativeCrossings = 0;
  68183. while (i.next())
  68184. {
  68185. if ((i.y1 <= y && i.y2 > y)
  68186. || (i.y2 <= y && i.y1 > y))
  68187. {
  68188. const float intersectX = i.x1 + (i.x2 - i.x1) * (y - i.y1) / (i.y2 - i.y1);
  68189. if (intersectX <= x)
  68190. {
  68191. if (i.y1 < i.y2)
  68192. ++positiveCrossings;
  68193. else
  68194. ++negativeCrossings;
  68195. }
  68196. }
  68197. }
  68198. return (useNonZeroWinding) ? (negativeCrossings != positiveCrossings)
  68199. : ((negativeCrossings + positiveCrossings) & 1) != 0;
  68200. }
  68201. bool Path::intersectsLine (const float x1, const float y1,
  68202. const float x2, const float y2) throw()
  68203. {
  68204. PathFlatteningIterator i (*this, AffineTransform::identity, collisionDetectionTolerence);
  68205. const Line line1 (x1, y1, x2, y2);
  68206. while (i.next())
  68207. {
  68208. const Line line2 (i.x1, i.y1, i.x2, i.y2);
  68209. float ix, iy;
  68210. if (line1.intersects (line2, ix, iy))
  68211. return true;
  68212. }
  68213. return false;
  68214. }
  68215. const Path Path::createPathWithRoundedCorners (const float cornerRadius) const throw()
  68216. {
  68217. if (cornerRadius <= 0.01f)
  68218. return *this;
  68219. int indexOfPathStart = 0, indexOfPathStartThis = 0;
  68220. int n = 0;
  68221. bool lastWasLine = false, firstWasLine = false;
  68222. Path p;
  68223. while (n < numElements)
  68224. {
  68225. const float type = elements [n++];
  68226. if (type == moveMarker)
  68227. {
  68228. indexOfPathStart = p.numElements;
  68229. indexOfPathStartThis = n - 1;
  68230. const float x = elements [n++];
  68231. const float y = elements [n++];
  68232. p.startNewSubPath (x, y);
  68233. lastWasLine = false;
  68234. firstWasLine = (elements [n] == lineMarker);
  68235. }
  68236. else if (type == lineMarker || type == closeSubPathMarker)
  68237. {
  68238. float startX = 0, startY = 0, joinX = 0, joinY = 0, endX, endY;
  68239. if (type == lineMarker)
  68240. {
  68241. endX = elements [n++];
  68242. endY = elements [n++];
  68243. if (n > 8)
  68244. {
  68245. startX = elements [n - 8];
  68246. startY = elements [n - 7];
  68247. joinX = elements [n - 5];
  68248. joinY = elements [n - 4];
  68249. }
  68250. }
  68251. else
  68252. {
  68253. endX = elements [indexOfPathStartThis + 1];
  68254. endY = elements [indexOfPathStartThis + 2];
  68255. if (n > 6)
  68256. {
  68257. startX = elements [n - 6];
  68258. startY = elements [n - 5];
  68259. joinX = elements [n - 3];
  68260. joinY = elements [n - 2];
  68261. }
  68262. }
  68263. if (lastWasLine)
  68264. {
  68265. const double len1 = juce_hypot (startX - joinX,
  68266. startY - joinY);
  68267. if (len1 > 0)
  68268. {
  68269. const double propNeeded = jmin (0.5, cornerRadius / len1);
  68270. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  68271. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  68272. }
  68273. const double len2 = juce_hypot (endX - joinX,
  68274. endY - joinY);
  68275. if (len2 > 0)
  68276. {
  68277. const double propNeeded = jmin (0.5, cornerRadius / len2);
  68278. p.quadraticTo (joinX, joinY,
  68279. (float) (joinX + (endX - joinX) * propNeeded),
  68280. (float) (joinY + (endY - joinY) * propNeeded));
  68281. }
  68282. p.lineTo (endX, endY);
  68283. }
  68284. else if (type == lineMarker)
  68285. {
  68286. p.lineTo (endX, endY);
  68287. lastWasLine = true;
  68288. }
  68289. if (type == closeSubPathMarker)
  68290. {
  68291. if (firstWasLine)
  68292. {
  68293. startX = elements [n - 3];
  68294. startY = elements [n - 2];
  68295. joinX = endX;
  68296. joinY = endY;
  68297. endX = elements [indexOfPathStartThis + 4];
  68298. endY = elements [indexOfPathStartThis + 5];
  68299. const double len1 = juce_hypot (startX - joinX,
  68300. startY - joinY);
  68301. if (len1 > 0)
  68302. {
  68303. const double propNeeded = jmin (0.5, cornerRadius / len1);
  68304. p.elements [p.numElements - 2] = (float) (joinX - (joinX - startX) * propNeeded);
  68305. p.elements [p.numElements - 1] = (float) (joinY - (joinY - startY) * propNeeded);
  68306. }
  68307. const double len2 = juce_hypot (endX - joinX,
  68308. endY - joinY);
  68309. if (len2 > 0)
  68310. {
  68311. const double propNeeded = jmin (0.5, cornerRadius / len2);
  68312. endX = (float) (joinX + (endX - joinX) * propNeeded);
  68313. endY = (float) (joinY + (endY - joinY) * propNeeded);
  68314. p.quadraticTo (joinX, joinY, endX, endY);
  68315. p.elements [indexOfPathStart + 1] = endX;
  68316. p.elements [indexOfPathStart + 2] = endY;
  68317. }
  68318. }
  68319. p.closeSubPath();
  68320. }
  68321. }
  68322. else if (type == quadMarker)
  68323. {
  68324. lastWasLine = false;
  68325. const float x1 = elements [n++];
  68326. const float y1 = elements [n++];
  68327. const float x2 = elements [n++];
  68328. const float y2 = elements [n++];
  68329. p.quadraticTo (x1, y1, x2, y2);
  68330. }
  68331. else if (type == cubicMarker)
  68332. {
  68333. lastWasLine = false;
  68334. const float x1 = elements [n++];
  68335. const float y1 = elements [n++];
  68336. const float x2 = elements [n++];
  68337. const float y2 = elements [n++];
  68338. const float x3 = elements [n++];
  68339. const float y3 = elements [n++];
  68340. p.cubicTo (x1, y1, x2, y2, x3, y3);
  68341. }
  68342. }
  68343. return p;
  68344. }
  68345. void Path::loadPathFromStream (InputStream& source)
  68346. {
  68347. while (! source.isExhausted())
  68348. {
  68349. switch (source.readByte())
  68350. {
  68351. case 'm':
  68352. {
  68353. const float x = source.readFloat();
  68354. const float y = source.readFloat();
  68355. startNewSubPath (x, y);
  68356. break;
  68357. }
  68358. case 'l':
  68359. {
  68360. const float x = source.readFloat();
  68361. const float y = source.readFloat();
  68362. lineTo (x, y);
  68363. break;
  68364. }
  68365. case 'q':
  68366. {
  68367. const float x1 = source.readFloat();
  68368. const float y1 = source.readFloat();
  68369. const float x2 = source.readFloat();
  68370. const float y2 = source.readFloat();
  68371. quadraticTo (x1, y1, x2, y2);
  68372. break;
  68373. }
  68374. case 'b':
  68375. {
  68376. const float x1 = source.readFloat();
  68377. const float y1 = source.readFloat();
  68378. const float x2 = source.readFloat();
  68379. const float y2 = source.readFloat();
  68380. const float x3 = source.readFloat();
  68381. const float y3 = source.readFloat();
  68382. cubicTo (x1, y1, x2, y2, x3, y3);
  68383. break;
  68384. }
  68385. case 'c':
  68386. closeSubPath();
  68387. break;
  68388. case 'n':
  68389. useNonZeroWinding = true;
  68390. break;
  68391. case 'z':
  68392. useNonZeroWinding = false;
  68393. break;
  68394. case 'e':
  68395. return; // end of path marker
  68396. default:
  68397. jassertfalse // illegal char in the stream
  68398. break;
  68399. }
  68400. }
  68401. }
  68402. void Path::loadPathFromData (const unsigned char* const data,
  68403. const int numberOfBytes) throw()
  68404. {
  68405. MemoryInputStream in ((const char*) data, numberOfBytes, false);
  68406. loadPathFromStream (in);
  68407. }
  68408. void Path::writePathToStream (OutputStream& dest) const
  68409. {
  68410. dest.writeByte ((useNonZeroWinding) ? 'n' : 'z');
  68411. int i = 0;
  68412. while (i < numElements)
  68413. {
  68414. const float type = elements [i++];
  68415. if (type == moveMarker)
  68416. {
  68417. dest.writeByte ('m');
  68418. dest.writeFloat (elements [i++]);
  68419. dest.writeFloat (elements [i++]);
  68420. }
  68421. else if (type == lineMarker)
  68422. {
  68423. dest.writeByte ('l');
  68424. dest.writeFloat (elements [i++]);
  68425. dest.writeFloat (elements [i++]);
  68426. }
  68427. else if (type == quadMarker)
  68428. {
  68429. dest.writeByte ('q');
  68430. dest.writeFloat (elements [i++]);
  68431. dest.writeFloat (elements [i++]);
  68432. dest.writeFloat (elements [i++]);
  68433. dest.writeFloat (elements [i++]);
  68434. }
  68435. else if (type == cubicMarker)
  68436. {
  68437. dest.writeByte ('b');
  68438. dest.writeFloat (elements [i++]);
  68439. dest.writeFloat (elements [i++]);
  68440. dest.writeFloat (elements [i++]);
  68441. dest.writeFloat (elements [i++]);
  68442. dest.writeFloat (elements [i++]);
  68443. dest.writeFloat (elements [i++]);
  68444. }
  68445. else if (type == closeSubPathMarker)
  68446. {
  68447. dest.writeByte ('c');
  68448. }
  68449. }
  68450. dest.writeByte ('e'); // marks the end-of-path
  68451. }
  68452. const String Path::toString() const
  68453. {
  68454. String s;
  68455. s.preallocateStorage (numElements * 4);
  68456. if (! useNonZeroWinding)
  68457. s << T("a ");
  68458. int i = 0;
  68459. float lastMarker = 0.0f;
  68460. while (i < numElements)
  68461. {
  68462. const float marker = elements [i++];
  68463. tchar markerChar = 0;
  68464. int numCoords = 0;
  68465. if (marker == moveMarker)
  68466. {
  68467. markerChar = T('m');
  68468. numCoords = 2;
  68469. }
  68470. else if (marker == lineMarker)
  68471. {
  68472. markerChar = T('l');
  68473. numCoords = 2;
  68474. }
  68475. else if (marker == quadMarker)
  68476. {
  68477. markerChar = T('q');
  68478. numCoords = 4;
  68479. }
  68480. else if (marker == cubicMarker)
  68481. {
  68482. markerChar = T('c');
  68483. numCoords = 6;
  68484. }
  68485. else
  68486. {
  68487. jassert (marker == closeSubPathMarker);
  68488. markerChar = T('z');
  68489. }
  68490. if (marker != lastMarker)
  68491. {
  68492. s << markerChar << T(' ');
  68493. lastMarker = marker;
  68494. }
  68495. while (--numCoords >= 0 && i < numElements)
  68496. {
  68497. String n (elements [i++], 3);
  68498. while (n.endsWithChar (T('0')))
  68499. n = n.dropLastCharacters (1);
  68500. if (n.endsWithChar (T('.')))
  68501. n = n.dropLastCharacters (1);
  68502. s << n << T(' ');
  68503. }
  68504. }
  68505. return s.trimEnd();
  68506. }
  68507. static const String nextToken (const tchar*& t)
  68508. {
  68509. while (*t == T(' '))
  68510. ++t;
  68511. const tchar* const start = t;
  68512. while (*t != 0 && *t != T(' '))
  68513. ++t;
  68514. const int length = (int) (t - start);
  68515. while (*t == T(' '))
  68516. ++t;
  68517. return String (start, length);
  68518. }
  68519. void Path::restoreFromString (const String& stringVersion)
  68520. {
  68521. clear();
  68522. setUsingNonZeroWinding (true);
  68523. const tchar* t = stringVersion;
  68524. tchar marker = T('m');
  68525. int numValues = 2;
  68526. float values [6];
  68527. while (*t != 0)
  68528. {
  68529. const String token (nextToken (t));
  68530. const tchar firstChar = token[0];
  68531. int startNum = 0;
  68532. if (firstChar == T('m') || firstChar == T('l'))
  68533. {
  68534. marker = firstChar;
  68535. numValues = 2;
  68536. }
  68537. else if (firstChar == T('q'))
  68538. {
  68539. marker = firstChar;
  68540. numValues = 4;
  68541. }
  68542. else if (firstChar == T('c'))
  68543. {
  68544. marker = firstChar;
  68545. numValues = 6;
  68546. }
  68547. else if (firstChar == T('z'))
  68548. {
  68549. marker = firstChar;
  68550. numValues = 0;
  68551. }
  68552. else if (firstChar == T('a'))
  68553. {
  68554. setUsingNonZeroWinding (false);
  68555. continue;
  68556. }
  68557. else
  68558. {
  68559. ++startNum;
  68560. values [0] = token.getFloatValue();
  68561. }
  68562. for (int i = startNum; i < numValues; ++i)
  68563. values [i] = nextToken (t).getFloatValue();
  68564. switch (marker)
  68565. {
  68566. case T('m'):
  68567. startNewSubPath (values[0], values[1]);
  68568. break;
  68569. case T('l'):
  68570. lineTo (values[0], values[1]);
  68571. break;
  68572. case T('q'):
  68573. quadraticTo (values[0], values[1],
  68574. values[2], values[3]);
  68575. break;
  68576. case T('c'):
  68577. cubicTo (values[0], values[1],
  68578. values[2], values[3],
  68579. values[4], values[5]);
  68580. break;
  68581. case T('z'):
  68582. closeSubPath();
  68583. break;
  68584. default:
  68585. jassertfalse // illegal string format?
  68586. break;
  68587. }
  68588. }
  68589. }
  68590. Path::Iterator::Iterator (const Path& path_)
  68591. : path (path_),
  68592. index (0)
  68593. {
  68594. }
  68595. Path::Iterator::~Iterator()
  68596. {
  68597. }
  68598. bool Path::Iterator::next()
  68599. {
  68600. const float* const elements = path.elements;
  68601. if (index < path.numElements)
  68602. {
  68603. const float type = elements [index++];
  68604. if (type == moveMarker)
  68605. {
  68606. elementType = startNewSubPath;
  68607. x1 = elements [index++];
  68608. y1 = elements [index++];
  68609. }
  68610. else if (type == lineMarker)
  68611. {
  68612. elementType = lineTo;
  68613. x1 = elements [index++];
  68614. y1 = elements [index++];
  68615. }
  68616. else if (type == quadMarker)
  68617. {
  68618. elementType = quadraticTo;
  68619. x1 = elements [index++];
  68620. y1 = elements [index++];
  68621. x2 = elements [index++];
  68622. y2 = elements [index++];
  68623. }
  68624. else if (type == cubicMarker)
  68625. {
  68626. elementType = cubicTo;
  68627. x1 = elements [index++];
  68628. y1 = elements [index++];
  68629. x2 = elements [index++];
  68630. y2 = elements [index++];
  68631. x3 = elements [index++];
  68632. y3 = elements [index++];
  68633. }
  68634. else if (type == closeSubPathMarker)
  68635. {
  68636. elementType = closePath;
  68637. }
  68638. return true;
  68639. }
  68640. return false;
  68641. }
  68642. END_JUCE_NAMESPACE
  68643. /********* End of inlined file: juce_Path.cpp *********/
  68644. /********* Start of inlined file: juce_PathIterator.cpp *********/
  68645. BEGIN_JUCE_NAMESPACE
  68646. #if JUCE_MSVC
  68647. #pragma optimize ("t", on)
  68648. #endif
  68649. PathFlatteningIterator::PathFlatteningIterator (const Path& path_,
  68650. const AffineTransform& transform_,
  68651. float tolerence_) throw()
  68652. : x2 (0),
  68653. y2 (0),
  68654. closesSubPath (false),
  68655. subPathIndex (-1),
  68656. path (path_),
  68657. transform (transform_),
  68658. points (path_.elements),
  68659. tolerence (tolerence_ * tolerence_),
  68660. subPathCloseX (0),
  68661. subPathCloseY (0),
  68662. index (0),
  68663. stackSize (32)
  68664. {
  68665. stackBase = (float*) juce_malloc (stackSize * sizeof (float));
  68666. isIdentityTransform = transform.isIdentity();
  68667. stackPos = stackBase;
  68668. }
  68669. PathFlatteningIterator::~PathFlatteningIterator() throw()
  68670. {
  68671. juce_free (stackBase);
  68672. }
  68673. bool PathFlatteningIterator::next() throw()
  68674. {
  68675. x1 = x2;
  68676. y1 = y2;
  68677. float x3 = 0;
  68678. float y3 = 0;
  68679. float x4 = 0;
  68680. float y4 = 0;
  68681. float type;
  68682. for (;;)
  68683. {
  68684. if (stackPos == stackBase)
  68685. {
  68686. if (index >= path.numElements)
  68687. {
  68688. return false;
  68689. }
  68690. else
  68691. {
  68692. type = points [index++];
  68693. if (type != Path::closeSubPathMarker)
  68694. {
  68695. x2 = points [index++];
  68696. y2 = points [index++];
  68697. if (! isIdentityTransform)
  68698. transform.transformPoint (x2, y2);
  68699. if (type == Path::quadMarker)
  68700. {
  68701. x3 = points [index++];
  68702. y3 = points [index++];
  68703. if (! isIdentityTransform)
  68704. transform.transformPoint (x3, y3);
  68705. }
  68706. else if (type == Path::cubicMarker)
  68707. {
  68708. x3 = points [index++];
  68709. y3 = points [index++];
  68710. x4 = points [index++];
  68711. y4 = points [index++];
  68712. if (! isIdentityTransform)
  68713. {
  68714. transform.transformPoint (x3, y3);
  68715. transform.transformPoint (x4, y4);
  68716. }
  68717. }
  68718. }
  68719. }
  68720. }
  68721. else
  68722. {
  68723. type = *--stackPos;
  68724. if (type != Path::closeSubPathMarker)
  68725. {
  68726. x2 = *--stackPos;
  68727. y2 = *--stackPos;
  68728. if (type == Path::quadMarker)
  68729. {
  68730. x3 = *--stackPos;
  68731. y3 = *--stackPos;
  68732. }
  68733. else if (type == Path::cubicMarker)
  68734. {
  68735. x3 = *--stackPos;
  68736. y3 = *--stackPos;
  68737. x4 = *--stackPos;
  68738. y4 = *--stackPos;
  68739. }
  68740. }
  68741. }
  68742. if (type == Path::lineMarker)
  68743. {
  68744. ++subPathIndex;
  68745. closesSubPath = (stackPos == stackBase)
  68746. && (index < path.numElements)
  68747. && (points [index] == Path::closeSubPathMarker)
  68748. && x2 == subPathCloseX
  68749. && y2 == subPathCloseY;
  68750. return true;
  68751. }
  68752. else if (type == Path::quadMarker)
  68753. {
  68754. const int offset = (int) (stackPos - stackBase);
  68755. if (offset >= stackSize - 10)
  68756. {
  68757. stackSize <<= 1;
  68758. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  68759. stackPos = stackBase + offset;
  68760. }
  68761. const float dx1 = x1 - x2;
  68762. const float dy1 = y1 - y2;
  68763. const float dx2 = x2 - x3;
  68764. const float dy2 = y2 - y3;
  68765. const float m1x = (x1 + x2) * 0.5f;
  68766. const float m1y = (y1 + y2) * 0.5f;
  68767. const float m2x = (x2 + x3) * 0.5f;
  68768. const float m2y = (y2 + y3) * 0.5f;
  68769. const float m3x = (m1x + m2x) * 0.5f;
  68770. const float m3y = (m1y + m2y) * 0.5f;
  68771. if (dx1*dx1 + dy1*dy1 + dx2*dx2 + dy2*dy2 > tolerence)
  68772. {
  68773. *stackPos++ = y3;
  68774. *stackPos++ = x3;
  68775. *stackPos++ = m2y;
  68776. *stackPos++ = m2x;
  68777. *stackPos++ = Path::quadMarker;
  68778. *stackPos++ = m3y;
  68779. *stackPos++ = m3x;
  68780. *stackPos++ = m1y;
  68781. *stackPos++ = m1x;
  68782. *stackPos++ = Path::quadMarker;
  68783. }
  68784. else
  68785. {
  68786. *stackPos++ = y3;
  68787. *stackPos++ = x3;
  68788. *stackPos++ = Path::lineMarker;
  68789. *stackPos++ = m3y;
  68790. *stackPos++ = m3x;
  68791. *stackPos++ = Path::lineMarker;
  68792. }
  68793. jassert (stackPos < stackBase + stackSize);
  68794. }
  68795. else if (type == Path::cubicMarker)
  68796. {
  68797. const int offset = (int) (stackPos - stackBase);
  68798. if (offset >= stackSize - 16)
  68799. {
  68800. stackSize <<= 1;
  68801. stackBase = (float*) juce_realloc (stackBase, stackSize * sizeof (float));
  68802. stackPos = stackBase + offset;
  68803. }
  68804. const float dx1 = x1 - x2;
  68805. const float dy1 = y1 - y2;
  68806. const float dx2 = x2 - x3;
  68807. const float dy2 = y2 - y3;
  68808. const float dx3 = x3 - x4;
  68809. const float dy3 = y3 - y4;
  68810. const float m1x = (x1 + x2) * 0.5f;
  68811. const float m1y = (y1 + y2) * 0.5f;
  68812. const float m2x = (x3 + x2) * 0.5f;
  68813. const float m2y = (y3 + y2) * 0.5f;
  68814. const float m3x = (x3 + x4) * 0.5f;
  68815. const float m3y = (y3 + y4) * 0.5f;
  68816. const float m4x = (m1x + m2x) * 0.5f;
  68817. const float m4y = (m1y + m2y) * 0.5f;
  68818. const float m5x = (m3x + m2x) * 0.5f;
  68819. const float m5y = (m3y + m2y) * 0.5f;
  68820. if (dx1*dx1 + dy1*dy1 + dx2*dx2
  68821. + dy2*dy2 + dx3*dx3 + dy3*dy3 > tolerence)
  68822. {
  68823. *stackPos++ = y4;
  68824. *stackPos++ = x4;
  68825. *stackPos++ = m3y;
  68826. *stackPos++ = m3x;
  68827. *stackPos++ = m5y;
  68828. *stackPos++ = m5x;
  68829. *stackPos++ = Path::cubicMarker;
  68830. *stackPos++ = (m4y + m5y) * 0.5f;
  68831. *stackPos++ = (m4x + m5x) * 0.5f;
  68832. *stackPos++ = m4y;
  68833. *stackPos++ = m4x;
  68834. *stackPos++ = m1y;
  68835. *stackPos++ = m1x;
  68836. *stackPos++ = Path::cubicMarker;
  68837. }
  68838. else
  68839. {
  68840. *stackPos++ = y4;
  68841. *stackPos++ = x4;
  68842. *stackPos++ = Path::lineMarker;
  68843. *stackPos++ = m5y;
  68844. *stackPos++ = m5x;
  68845. *stackPos++ = Path::lineMarker;
  68846. *stackPos++ = m4y;
  68847. *stackPos++ = m4x;
  68848. *stackPos++ = Path::lineMarker;
  68849. }
  68850. }
  68851. else if (type == Path::closeSubPathMarker)
  68852. {
  68853. if (x2 != subPathCloseX || y2 != subPathCloseY)
  68854. {
  68855. x1 = x2;
  68856. y1 = y2;
  68857. x2 = subPathCloseX;
  68858. y2 = subPathCloseY;
  68859. closesSubPath = true;
  68860. return true;
  68861. }
  68862. }
  68863. else
  68864. {
  68865. subPathIndex = -1;
  68866. subPathCloseX = x1 = x2;
  68867. subPathCloseY = y1 = y2;
  68868. }
  68869. }
  68870. }
  68871. END_JUCE_NAMESPACE
  68872. /********* End of inlined file: juce_PathIterator.cpp *********/
  68873. /********* Start of inlined file: juce_PathStrokeType.cpp *********/
  68874. BEGIN_JUCE_NAMESPACE
  68875. PathStrokeType::PathStrokeType (const float strokeThickness,
  68876. const JointStyle jointStyle_,
  68877. const EndCapStyle endStyle_) throw()
  68878. : thickness (strokeThickness),
  68879. jointStyle (jointStyle_),
  68880. endStyle (endStyle_)
  68881. {
  68882. }
  68883. PathStrokeType::PathStrokeType (const PathStrokeType& other) throw()
  68884. : thickness (other.thickness),
  68885. jointStyle (other.jointStyle),
  68886. endStyle (other.endStyle)
  68887. {
  68888. }
  68889. const PathStrokeType& PathStrokeType::operator= (const PathStrokeType& other) throw()
  68890. {
  68891. thickness = other.thickness;
  68892. jointStyle = other.jointStyle;
  68893. endStyle = other.endStyle;
  68894. return *this;
  68895. }
  68896. PathStrokeType::~PathStrokeType() throw()
  68897. {
  68898. }
  68899. bool PathStrokeType::operator== (const PathStrokeType& other) const throw()
  68900. {
  68901. return thickness == other.thickness
  68902. && jointStyle == other.jointStyle
  68903. && endStyle == other.endStyle;
  68904. }
  68905. bool PathStrokeType::operator!= (const PathStrokeType& other) const throw()
  68906. {
  68907. return ! operator== (other);
  68908. }
  68909. static bool lineIntersection (const float x1, const float y1,
  68910. const float x2, const float y2,
  68911. const float x3, const float y3,
  68912. const float x4, const float y4,
  68913. float& intersectionX,
  68914. float& intersectionY,
  68915. float& distanceBeyondLine1EndSquared) throw()
  68916. {
  68917. if (x2 != x3 || y2 != y3)
  68918. {
  68919. const float dx1 = x2 - x1;
  68920. const float dy1 = y2 - y1;
  68921. const float dx2 = x4 - x3;
  68922. const float dy2 = y4 - y3;
  68923. const float divisor = dx1 * dy2 - dx2 * dy1;
  68924. if (divisor == 0)
  68925. {
  68926. if (! ((dx1 == 0 && dy1 == 0) || (dx2 == 0 && dy2 == 0)))
  68927. {
  68928. if (dy1 == 0 && dy2 != 0)
  68929. {
  68930. const float along = (y1 - y3) / dy2;
  68931. intersectionX = x3 + along * dx2;
  68932. intersectionY = y1;
  68933. distanceBeyondLine1EndSquared = intersectionX - x2;
  68934. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68935. if ((x2 > x1) == (intersectionX < x2))
  68936. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68937. return along >= 0 && along <= 1.0f;
  68938. }
  68939. else if (dy2 == 0 && dy1 != 0)
  68940. {
  68941. const float along = (y3 - y1) / dy1;
  68942. intersectionX = x1 + along * dx1;
  68943. intersectionY = y3;
  68944. distanceBeyondLine1EndSquared = (along - 1.0f) * dx1;
  68945. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68946. if (along < 1.0f)
  68947. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68948. return along >= 0 && along <= 1.0f;
  68949. }
  68950. else if (dx1 == 0 && dx2 != 0)
  68951. {
  68952. const float along = (x1 - x3) / dx2;
  68953. intersectionX = x1;
  68954. intersectionY = y3 + along * dy2;
  68955. distanceBeyondLine1EndSquared = intersectionY - y2;
  68956. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68957. if ((y2 > y1) == (intersectionY < y2))
  68958. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68959. return along >= 0 && along <= 1.0f;
  68960. }
  68961. else if (dx2 == 0 && dx1 != 0)
  68962. {
  68963. const float along = (x3 - x1) / dx1;
  68964. intersectionX = x3;
  68965. intersectionY = y1 + along * dy1;
  68966. distanceBeyondLine1EndSquared = (along - 1.0f) * dy1;
  68967. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68968. if (along < 1.0f)
  68969. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68970. return along >= 0 && along <= 1.0f;
  68971. }
  68972. }
  68973. intersectionX = 0.5f * (x2 + x3);
  68974. intersectionY = 0.5f * (y2 + y3);
  68975. distanceBeyondLine1EndSquared = 0.0f;
  68976. return false;
  68977. }
  68978. else
  68979. {
  68980. const float along1 = ((y1 - y3) * dx2 - (x1 - x3) * dy2) / divisor;
  68981. intersectionX = x1 + along1 * dx1;
  68982. intersectionY = y1 + along1 * dy1;
  68983. if (along1 >= 0 && along1 <= 1.0f)
  68984. {
  68985. const float along2 = ((y1 - y3) * dx1 - (x1 - x3) * dy1);
  68986. if (along2 >= 0 && along2 <= divisor)
  68987. {
  68988. distanceBeyondLine1EndSquared = 0.0f;
  68989. return true;
  68990. }
  68991. }
  68992. distanceBeyondLine1EndSquared = along1 - 1.0f;
  68993. distanceBeyondLine1EndSquared *= distanceBeyondLine1EndSquared;
  68994. distanceBeyondLine1EndSquared *= (dx1 * dx1 + dy1 * dy1);
  68995. if (along1 < 1.0f)
  68996. distanceBeyondLine1EndSquared = -distanceBeyondLine1EndSquared;
  68997. return false;
  68998. }
  68999. }
  69000. intersectionX = x2;
  69001. intersectionY = y2;
  69002. distanceBeyondLine1EndSquared = 0.0f;
  69003. return true;
  69004. }
  69005. // part of stroke drawing stuff
  69006. static void addEdgeAndJoint (Path& destPath,
  69007. const PathStrokeType::JointStyle style,
  69008. const float maxMiterExtensionSquared, const float width,
  69009. const float x1, const float y1,
  69010. const float x2, const float y2,
  69011. const float x3, const float y3,
  69012. const float x4, const float y4,
  69013. const float midX, const float midY) throw()
  69014. {
  69015. if (style == PathStrokeType::beveled
  69016. || (x3 == x4 && y3 == y4)
  69017. || (x1 == x2 && y1 == y2))
  69018. {
  69019. destPath.lineTo (x2, y2);
  69020. destPath.lineTo (x3, y3);
  69021. }
  69022. else
  69023. {
  69024. float jx, jy, distanceBeyondLine1EndSquared;
  69025. // if they intersect, use this point..
  69026. if (lineIntersection (x1, y1, x2, y2,
  69027. x3, y3, x4, y4,
  69028. jx, jy, distanceBeyondLine1EndSquared))
  69029. {
  69030. destPath.lineTo (jx, jy);
  69031. }
  69032. else
  69033. {
  69034. if (style == PathStrokeType::mitered)
  69035. {
  69036. if (distanceBeyondLine1EndSquared < maxMiterExtensionSquared
  69037. && distanceBeyondLine1EndSquared > 0.0f)
  69038. {
  69039. destPath.lineTo (jx, jy);
  69040. }
  69041. else
  69042. {
  69043. // the end sticks out too far, so just use a blunt joint
  69044. destPath.lineTo (x2, y2);
  69045. destPath.lineTo (x3, y3);
  69046. }
  69047. }
  69048. else
  69049. {
  69050. // curved joints
  69051. float angle = atan2f (x2 - midX, y2 - midY);
  69052. float angle2 = atan2f (x3 - midX, y3 - midY);
  69053. while (angle < angle2 - 0.01f)
  69054. angle2 -= float_Pi * 2.0f;
  69055. destPath.lineTo (x2, y2);
  69056. while (angle > angle2)
  69057. {
  69058. destPath.lineTo (midX + width * sinf (angle),
  69059. midY + width * cosf (angle));
  69060. angle -= 0.1f;
  69061. }
  69062. destPath.lineTo (x3, y3);
  69063. }
  69064. }
  69065. }
  69066. }
  69067. static inline void addLineEnd (Path& destPath,
  69068. const PathStrokeType::EndCapStyle style,
  69069. const float x1, const float y1,
  69070. const float x2, const float y2,
  69071. const float width) throw()
  69072. {
  69073. if (style == PathStrokeType::butt)
  69074. {
  69075. destPath.lineTo (x2, y2);
  69076. }
  69077. else
  69078. {
  69079. float offx1, offy1, offx2, offy2;
  69080. float dx = x2 - x1;
  69081. float dy = y2 - y1;
  69082. const float len = juce_hypotf (dx, dy);
  69083. if (len == 0)
  69084. {
  69085. offx1 = offx2 = x1;
  69086. offy1 = offy2 = y1;
  69087. }
  69088. else
  69089. {
  69090. const float offset = width / len;
  69091. dx *= offset;
  69092. dy *= offset;
  69093. offx1 = x1 + dy;
  69094. offy1 = y1 - dx;
  69095. offx2 = x2 + dy;
  69096. offy2 = y2 - dx;
  69097. }
  69098. if (style == PathStrokeType::square)
  69099. {
  69100. // sqaure ends
  69101. destPath.lineTo (offx1, offy1);
  69102. destPath.lineTo (offx2, offy2);
  69103. destPath.lineTo (x2, y2);
  69104. }
  69105. else
  69106. {
  69107. // rounded ends
  69108. const float midx = (offx1 + offx2) * 0.5f;
  69109. const float midy = (offy1 + offy2) * 0.5f;
  69110. destPath.cubicTo (x1 + (offx1 - x1) * 0.55f, y1 + (offy1 - y1) * 0.55f,
  69111. offx1 + (midx - offx1) * 0.45f, offy1 + (midy - offy1) * 0.45f,
  69112. midx, midy);
  69113. destPath.cubicTo (midx + (offx2 - midx) * 0.55f, midy + (offy2 - midy) * 0.55f,
  69114. offx2 + (x2 - offx2) * 0.45f, offy2 + (y2 - offy2) * 0.45f,
  69115. x2, y2);
  69116. }
  69117. }
  69118. }
  69119. struct LineSection
  69120. {
  69121. LineSection() throw() {}
  69122. LineSection (int) throw() {}
  69123. float x1, y1, x2, y2; // original line
  69124. float lx1, ly1, lx2, ly2; // the left-hand stroke
  69125. float rx1, ry1, rx2, ry2; // the right-hand stroke
  69126. };
  69127. static void addSubPath (Path& destPath, const Array <LineSection>& subPath,
  69128. const bool isClosed,
  69129. const float width, const float maxMiterExtensionSquared,
  69130. const PathStrokeType::JointStyle jointStyle, const PathStrokeType::EndCapStyle endStyle) throw()
  69131. {
  69132. jassert (subPath.size() > 0);
  69133. const LineSection& firstLine = subPath.getReference (0);
  69134. float lastX1 = firstLine.lx1;
  69135. float lastY1 = firstLine.ly1;
  69136. float lastX2 = firstLine.lx2;
  69137. float lastY2 = firstLine.ly2;
  69138. if (isClosed)
  69139. {
  69140. destPath.startNewSubPath (lastX1, lastY1);
  69141. }
  69142. else
  69143. {
  69144. destPath.startNewSubPath (firstLine.rx2, firstLine.ry2);
  69145. addLineEnd (destPath, endStyle,
  69146. firstLine.rx2, firstLine.ry2,
  69147. lastX1, lastY1,
  69148. width);
  69149. }
  69150. int i;
  69151. for (i = 1; i < subPath.size(); ++i)
  69152. {
  69153. const LineSection& l = subPath.getReference (i);
  69154. addEdgeAndJoint (destPath, jointStyle,
  69155. maxMiterExtensionSquared, width,
  69156. lastX1, lastY1, lastX2, lastY2,
  69157. l.lx1, l.ly1, l.lx2, l.ly2,
  69158. l.x1, l.y1);
  69159. lastX1 = l.lx1;
  69160. lastY1 = l.ly1;
  69161. lastX2 = l.lx2;
  69162. lastY2 = l.ly2;
  69163. }
  69164. const LineSection& lastLine = subPath.getReference (subPath.size() - 1);
  69165. if (isClosed)
  69166. {
  69167. const LineSection& l = subPath.getReference (0);
  69168. addEdgeAndJoint (destPath, jointStyle,
  69169. maxMiterExtensionSquared, width,
  69170. lastX1, lastY1, lastX2, lastY2,
  69171. l.lx1, l.ly1, l.lx2, l.ly2,
  69172. l.x1, l.y1);
  69173. destPath.closeSubPath();
  69174. destPath.startNewSubPath (lastLine.rx1, lastLine.ry1);
  69175. }
  69176. else
  69177. {
  69178. destPath.lineTo (lastX2, lastY2);
  69179. addLineEnd (destPath, endStyle,
  69180. lastX2, lastY2,
  69181. lastLine.rx1, lastLine.ry1,
  69182. width);
  69183. }
  69184. lastX1 = lastLine.rx1;
  69185. lastY1 = lastLine.ry1;
  69186. lastX2 = lastLine.rx2;
  69187. lastY2 = lastLine.ry2;
  69188. for (i = subPath.size() - 1; --i >= 0;)
  69189. {
  69190. const LineSection& l = subPath.getReference (i);
  69191. addEdgeAndJoint (destPath, jointStyle,
  69192. maxMiterExtensionSquared, width,
  69193. lastX1, lastY1, lastX2, lastY2,
  69194. l.rx1, l.ry1, l.rx2, l.ry2,
  69195. l.x2, l.y2);
  69196. lastX1 = l.rx1;
  69197. lastY1 = l.ry1;
  69198. lastX2 = l.rx2;
  69199. lastY2 = l.ry2;
  69200. }
  69201. if (isClosed)
  69202. {
  69203. addEdgeAndJoint (destPath, jointStyle,
  69204. maxMiterExtensionSquared, width,
  69205. lastX1, lastY1, lastX2, lastY2,
  69206. lastLine.rx1, lastLine.ry1, lastLine.rx2, lastLine.ry2,
  69207. lastLine.x2, lastLine.y2);
  69208. }
  69209. else
  69210. {
  69211. // do the last line
  69212. destPath.lineTo (lastX2, lastY2);
  69213. }
  69214. destPath.closeSubPath();
  69215. }
  69216. void PathStrokeType::createStrokedPath (Path& destPath,
  69217. const Path& source,
  69218. const AffineTransform& transform,
  69219. const float extraAccuracy) const throw()
  69220. {
  69221. if (thickness <= 0)
  69222. {
  69223. destPath.clear();
  69224. return;
  69225. }
  69226. const Path* sourcePath = &source;
  69227. Path temp;
  69228. if (sourcePath == &destPath)
  69229. {
  69230. destPath.swapWithPath (temp);
  69231. sourcePath = &temp;
  69232. }
  69233. else
  69234. {
  69235. destPath.clear();
  69236. }
  69237. destPath.setUsingNonZeroWinding (true);
  69238. const float maxMiterExtensionSquared = 9.0f * thickness * thickness;
  69239. const float width = 0.5f * thickness;
  69240. // Iterate the path, creating a list of the
  69241. // left/right-hand lines along either side of it...
  69242. PathFlatteningIterator it (*sourcePath, transform, 9.0f / extraAccuracy);
  69243. Array <LineSection> subPath;
  69244. LineSection l;
  69245. l.x1 = 0;
  69246. l.y1 = 0;
  69247. const float minSegmentLength = 2.0f / (extraAccuracy * extraAccuracy);
  69248. while (it.next())
  69249. {
  69250. if (it.subPathIndex == 0)
  69251. {
  69252. if (subPath.size() > 0)
  69253. {
  69254. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  69255. subPath.clearQuick();
  69256. }
  69257. l.x1 = it.x1;
  69258. l.y1 = it.y1;
  69259. }
  69260. l.x2 = it.x2;
  69261. l.y2 = it.y2;
  69262. float dx = l.x2 - l.x1;
  69263. float dy = l.y2 - l.y1;
  69264. const float hypotSquared = dx*dx + dy*dy;
  69265. if (it.closesSubPath || hypotSquared > minSegmentLength || it.isLastInSubpath())
  69266. {
  69267. const float len = sqrtf (hypotSquared);
  69268. if (len == 0)
  69269. {
  69270. l.rx1 = l.rx2 = l.lx1 = l.lx2 = l.x1;
  69271. l.ry1 = l.ry2 = l.ly1 = l.ly2 = l.y1;
  69272. }
  69273. else
  69274. {
  69275. const float offset = width / len;
  69276. dx *= offset;
  69277. dy *= offset;
  69278. l.rx2 = l.x1 - dy;
  69279. l.ry2 = l.y1 + dx;
  69280. l.lx1 = l.x1 + dy;
  69281. l.ly1 = l.y1 - dx;
  69282. l.lx2 = l.x2 + dy;
  69283. l.ly2 = l.y2 - dx;
  69284. l.rx1 = l.x2 - dy;
  69285. l.ry1 = l.y2 + dx;
  69286. }
  69287. subPath.add (l);
  69288. if (it.closesSubPath)
  69289. {
  69290. addSubPath (destPath, subPath, true, width, maxMiterExtensionSquared, jointStyle, endStyle);
  69291. subPath.clearQuick();
  69292. }
  69293. else
  69294. {
  69295. l.x1 = it.x2;
  69296. l.y1 = it.y2;
  69297. }
  69298. }
  69299. }
  69300. if (subPath.size() > 0)
  69301. addSubPath (destPath, subPath, false, width, maxMiterExtensionSquared, jointStyle, endStyle);
  69302. }
  69303. void PathStrokeType::createDashedStroke (Path& destPath,
  69304. const Path& sourcePath,
  69305. const float* dashLengths,
  69306. int numDashLengths,
  69307. const AffineTransform& transform,
  69308. const float extraAccuracy) const throw()
  69309. {
  69310. if (thickness <= 0)
  69311. return;
  69312. // this should really be an even number..
  69313. jassert ((numDashLengths & 1) == 0);
  69314. Path newDestPath;
  69315. PathFlatteningIterator it (sourcePath, transform, 9.0f / extraAccuracy);
  69316. bool first = true;
  69317. int dashNum = 0;
  69318. float pos = 0.0f, lineLen = 0.0f, lineEndPos = 0.0f;
  69319. float dx = 0.0f, dy = 0.0f;
  69320. for (;;)
  69321. {
  69322. const bool isSolid = ((dashNum & 1) == 0);
  69323. const float dashLen = dashLengths [dashNum++ % numDashLengths];
  69324. jassert (dashLen > 0); // must be a positive increment!
  69325. if (dashLen <= 0)
  69326. break;
  69327. pos += dashLen;
  69328. while (pos > lineEndPos)
  69329. {
  69330. if (! it.next())
  69331. {
  69332. if (isSolid && ! first)
  69333. newDestPath.lineTo (it.x2, it.y2);
  69334. createStrokedPath (destPath, newDestPath, AffineTransform::identity, extraAccuracy);
  69335. return;
  69336. }
  69337. if (isSolid && ! first)
  69338. {
  69339. newDestPath.lineTo (it.x1, it.y1);
  69340. }
  69341. else
  69342. {
  69343. newDestPath.startNewSubPath (it.x1, it.y1);
  69344. first = false;
  69345. }
  69346. dx = it.x2 - it.x1;
  69347. dy = it.y2 - it.y1;
  69348. lineLen = juce_hypotf (dx, dy);
  69349. lineEndPos += lineLen;
  69350. }
  69351. const float alpha = (pos - (lineEndPos - lineLen)) / lineLen;
  69352. if (isSolid)
  69353. newDestPath.lineTo (it.x1 + dx * alpha,
  69354. it.y1 + dy * alpha);
  69355. else
  69356. newDestPath.startNewSubPath (it.x1 + dx * alpha,
  69357. it.y1 + dy * alpha);
  69358. }
  69359. }
  69360. END_JUCE_NAMESPACE
  69361. /********* End of inlined file: juce_PathStrokeType.cpp *********/
  69362. /********* Start of inlined file: juce_Point.cpp *********/
  69363. BEGIN_JUCE_NAMESPACE
  69364. Point::Point() throw()
  69365. : x (0.0f),
  69366. y (0.0f)
  69367. {
  69368. }
  69369. Point::Point (const Point& other) throw()
  69370. : x (other.x),
  69371. y (other.y)
  69372. {
  69373. }
  69374. const Point& Point::operator= (const Point& other) throw()
  69375. {
  69376. x = other.x;
  69377. y = other.y;
  69378. return *this;
  69379. }
  69380. Point::Point (const float x_,
  69381. const float y_) throw()
  69382. : x (x_),
  69383. y (y_)
  69384. {
  69385. }
  69386. Point::~Point() throw()
  69387. {
  69388. }
  69389. void Point::setXY (const float x_,
  69390. const float y_) throw()
  69391. {
  69392. x = x_;
  69393. y = y_;
  69394. }
  69395. void Point::applyTransform (const AffineTransform& transform) throw()
  69396. {
  69397. transform.transformPoint (x, y);
  69398. }
  69399. END_JUCE_NAMESPACE
  69400. /********* End of inlined file: juce_Point.cpp *********/
  69401. /********* Start of inlined file: juce_PositionedRectangle.cpp *********/
  69402. BEGIN_JUCE_NAMESPACE
  69403. PositionedRectangle::PositionedRectangle() throw()
  69404. : x (0.0),
  69405. y (0.0),
  69406. w (0.0),
  69407. h (0.0),
  69408. xMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  69409. yMode (anchorAtLeftOrTop | absoluteFromParentTopLeft),
  69410. wMode (absoluteSize),
  69411. hMode (absoluteSize)
  69412. {
  69413. }
  69414. PositionedRectangle::PositionedRectangle (const PositionedRectangle& other) throw()
  69415. : x (other.x),
  69416. y (other.y),
  69417. w (other.w),
  69418. h (other.h),
  69419. xMode (other.xMode),
  69420. yMode (other.yMode),
  69421. wMode (other.wMode),
  69422. hMode (other.hMode)
  69423. {
  69424. }
  69425. const PositionedRectangle& PositionedRectangle::operator= (const PositionedRectangle& other) throw()
  69426. {
  69427. if (this != &other)
  69428. {
  69429. x = other.x;
  69430. y = other.y;
  69431. w = other.w;
  69432. h = other.h;
  69433. xMode = other.xMode;
  69434. yMode = other.yMode;
  69435. wMode = other.wMode;
  69436. hMode = other.hMode;
  69437. }
  69438. return *this;
  69439. }
  69440. PositionedRectangle::~PositionedRectangle() throw()
  69441. {
  69442. }
  69443. const bool PositionedRectangle::operator== (const PositionedRectangle& other) const throw()
  69444. {
  69445. return x == other.x
  69446. && y == other.y
  69447. && w == other.w
  69448. && h == other.h
  69449. && xMode == other.xMode
  69450. && yMode == other.yMode
  69451. && wMode == other.wMode
  69452. && hMode == other.hMode;
  69453. }
  69454. const bool PositionedRectangle::operator!= (const PositionedRectangle& other) const throw()
  69455. {
  69456. return ! operator== (other);
  69457. }
  69458. PositionedRectangle::PositionedRectangle (const String& stringVersion) throw()
  69459. {
  69460. StringArray tokens;
  69461. tokens.addTokens (stringVersion, false);
  69462. decodePosString (tokens [0], xMode, x);
  69463. decodePosString (tokens [1], yMode, y);
  69464. decodeSizeString (tokens [2], wMode, w);
  69465. decodeSizeString (tokens [3], hMode, h);
  69466. }
  69467. const String PositionedRectangle::toString() const throw()
  69468. {
  69469. String s;
  69470. s.preallocateStorage (12);
  69471. addPosDescription (s, xMode, x);
  69472. s << T(' ');
  69473. addPosDescription (s, yMode, y);
  69474. s << T(' ');
  69475. addSizeDescription (s, wMode, w);
  69476. s << T(' ');
  69477. addSizeDescription (s, hMode, h);
  69478. return s;
  69479. }
  69480. const Rectangle PositionedRectangle::getRectangle (const Rectangle& target) const throw()
  69481. {
  69482. jassert (! target.isEmpty());
  69483. double x_, y_, w_, h_;
  69484. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  69485. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  69486. return Rectangle (roundDoubleToInt (x_), roundDoubleToInt (y_),
  69487. roundDoubleToInt (w_), roundDoubleToInt (h_));
  69488. }
  69489. void PositionedRectangle::getRectangleDouble (const Rectangle& target,
  69490. double& x_, double& y_,
  69491. double& w_, double& h_) const throw()
  69492. {
  69493. jassert (! target.isEmpty());
  69494. applyPosAndSize (x_, w_, x, w, xMode, wMode, target.getX(), target.getWidth());
  69495. applyPosAndSize (y_, h_, y, h, yMode, hMode, target.getY(), target.getHeight());
  69496. }
  69497. void PositionedRectangle::applyToComponent (Component& comp) const throw()
  69498. {
  69499. comp.setBounds (getRectangle (Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight())));
  69500. }
  69501. void PositionedRectangle::updateFrom (const Rectangle& rectangle,
  69502. const Rectangle& target) throw()
  69503. {
  69504. updatePosAndSize (x, w, rectangle.getX(), rectangle.getWidth(), xMode, wMode, target.getX(), target.getWidth());
  69505. updatePosAndSize (y, h, rectangle.getY(), rectangle.getHeight(), yMode, hMode, target.getY(), target.getHeight());
  69506. }
  69507. void PositionedRectangle::updateFromDouble (const double newX, const double newY,
  69508. const double newW, const double newH,
  69509. const Rectangle& target) throw()
  69510. {
  69511. updatePosAndSize (x, w, newX, newW, xMode, wMode, target.getX(), target.getWidth());
  69512. updatePosAndSize (y, h, newY, newH, yMode, hMode, target.getY(), target.getHeight());
  69513. }
  69514. void PositionedRectangle::updateFromComponent (const Component& comp) throw()
  69515. {
  69516. if (comp.getParentComponent() == 0 && ! comp.isOnDesktop())
  69517. updateFrom (comp.getBounds(), Rectangle());
  69518. else
  69519. updateFrom (comp.getBounds(), Rectangle (0, 0, comp.getParentWidth(), comp.getParentHeight()));
  69520. }
  69521. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointX() const throw()
  69522. {
  69523. return (AnchorPoint) (xMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  69524. }
  69525. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeX() const throw()
  69526. {
  69527. return (PositionMode) (xMode & (absoluteFromParentTopLeft
  69528. | absoluteFromParentBottomRight
  69529. | absoluteFromParentCentre
  69530. | proportionOfParentSize));
  69531. }
  69532. PositionedRectangle::AnchorPoint PositionedRectangle::getAnchorPointY() const throw()
  69533. {
  69534. return (AnchorPoint) (yMode & (anchorAtLeftOrTop | anchorAtRightOrBottom | anchorAtCentre));
  69535. }
  69536. PositionedRectangle::PositionMode PositionedRectangle::getPositionModeY() const throw()
  69537. {
  69538. return (PositionMode) (yMode & (absoluteFromParentTopLeft
  69539. | absoluteFromParentBottomRight
  69540. | absoluteFromParentCentre
  69541. | proportionOfParentSize));
  69542. }
  69543. PositionedRectangle::SizeMode PositionedRectangle::getWidthMode() const throw()
  69544. {
  69545. return (SizeMode) wMode;
  69546. }
  69547. PositionedRectangle::SizeMode PositionedRectangle::getHeightMode() const throw()
  69548. {
  69549. return (SizeMode) hMode;
  69550. }
  69551. void PositionedRectangle::setModes (const AnchorPoint xAnchor,
  69552. const PositionMode xMode_,
  69553. const AnchorPoint yAnchor,
  69554. const PositionMode yMode_,
  69555. const SizeMode widthMode,
  69556. const SizeMode heightMode,
  69557. const Rectangle& target) throw()
  69558. {
  69559. if (xMode != (xAnchor | xMode_) || wMode != widthMode)
  69560. {
  69561. double tx, tw;
  69562. applyPosAndSize (tx, tw, x, w, xMode, wMode, target.getX(), target.getWidth());
  69563. xMode = (uint8) (xAnchor | xMode_);
  69564. wMode = (uint8) widthMode;
  69565. updatePosAndSize (x, w, tx, tw, xMode, wMode, target.getX(), target.getWidth());
  69566. }
  69567. if (yMode != (yAnchor | yMode_) || hMode != heightMode)
  69568. {
  69569. double ty, th;
  69570. applyPosAndSize (ty, th, y, h, yMode, hMode, target.getY(), target.getHeight());
  69571. yMode = (uint8) (yAnchor | yMode_);
  69572. hMode = (uint8) heightMode;
  69573. updatePosAndSize (y, h, ty, th, yMode, hMode, target.getY(), target.getHeight());
  69574. }
  69575. }
  69576. bool PositionedRectangle::isPositionAbsolute() const throw()
  69577. {
  69578. return xMode == absoluteFromParentTopLeft
  69579. && yMode == absoluteFromParentTopLeft
  69580. && wMode == absoluteSize
  69581. && hMode == absoluteSize;
  69582. }
  69583. void PositionedRectangle::addPosDescription (String& s, const uint8 mode, const double value) const throw()
  69584. {
  69585. if ((mode & proportionOfParentSize) != 0)
  69586. {
  69587. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  69588. }
  69589. else
  69590. {
  69591. s << (roundDoubleToInt (value * 100.0) / 100.0);
  69592. if ((mode & absoluteFromParentBottomRight) != 0)
  69593. s << T('R');
  69594. else if ((mode & absoluteFromParentCentre) != 0)
  69595. s << T('C');
  69596. }
  69597. if ((mode & anchorAtRightOrBottom) != 0)
  69598. s << T('r');
  69599. else if ((mode & anchorAtCentre) != 0)
  69600. s << T('c');
  69601. }
  69602. void PositionedRectangle::addSizeDescription (String& s, const uint8 mode, const double value) const throw()
  69603. {
  69604. if (mode == proportionalSize)
  69605. s << (roundDoubleToInt (value * 100000.0) / 1000.0) << T('%');
  69606. else if (mode == parentSizeMinusAbsolute)
  69607. s << (roundDoubleToInt (value * 100.0) / 100.0) << T('M');
  69608. else
  69609. s << (roundDoubleToInt (value * 100.0) / 100.0);
  69610. }
  69611. void PositionedRectangle::decodePosString (const String& s, uint8& mode, double& value) throw()
  69612. {
  69613. if (s.containsChar (T('r')))
  69614. mode = anchorAtRightOrBottom;
  69615. else if (s.containsChar (T('c')))
  69616. mode = anchorAtCentre;
  69617. else
  69618. mode = anchorAtLeftOrTop;
  69619. if (s.containsChar (T('%')))
  69620. {
  69621. mode |= proportionOfParentSize;
  69622. value = s.removeCharacters (T("%rcRC")).getDoubleValue() / 100.0;
  69623. }
  69624. else
  69625. {
  69626. if (s.containsChar (T('R')))
  69627. mode |= absoluteFromParentBottomRight;
  69628. else if (s.containsChar (T('C')))
  69629. mode |= absoluteFromParentCentre;
  69630. else
  69631. mode |= absoluteFromParentTopLeft;
  69632. value = s.removeCharacters (T("rcRC")).getDoubleValue();
  69633. }
  69634. }
  69635. void PositionedRectangle::decodeSizeString (const String& s, uint8& mode, double& value) throw()
  69636. {
  69637. if (s.containsChar (T('%')))
  69638. {
  69639. mode = proportionalSize;
  69640. value = s.upToFirstOccurrenceOf (T("%"), false, false).getDoubleValue() / 100.0;
  69641. }
  69642. else if (s.containsChar (T('M')))
  69643. {
  69644. mode = parentSizeMinusAbsolute;
  69645. value = s.getDoubleValue();
  69646. }
  69647. else
  69648. {
  69649. mode = absoluteSize;
  69650. value = s.getDoubleValue();
  69651. }
  69652. }
  69653. void PositionedRectangle::applyPosAndSize (double& xOut, double& wOut,
  69654. const double x, const double w,
  69655. const uint8 xMode, const uint8 wMode,
  69656. const int parentPos,
  69657. const int parentSize) const throw()
  69658. {
  69659. if (wMode == proportionalSize)
  69660. wOut = roundDoubleToInt (w * parentSize);
  69661. else if (wMode == parentSizeMinusAbsolute)
  69662. wOut = jmax (0, parentSize - roundDoubleToInt (w));
  69663. else
  69664. wOut = roundDoubleToInt (w);
  69665. if ((xMode & proportionOfParentSize) != 0)
  69666. xOut = parentPos + x * parentSize;
  69667. else if ((xMode & absoluteFromParentBottomRight) != 0)
  69668. xOut = (parentPos + parentSize) - x;
  69669. else if ((xMode & absoluteFromParentCentre) != 0)
  69670. xOut = x + (parentPos + parentSize / 2);
  69671. else
  69672. xOut = x + parentPos;
  69673. if ((xMode & anchorAtRightOrBottom) != 0)
  69674. xOut -= wOut;
  69675. else if ((xMode & anchorAtCentre) != 0)
  69676. xOut -= wOut / 2;
  69677. }
  69678. void PositionedRectangle::updatePosAndSize (double& xOut, double& wOut,
  69679. double x, const double w,
  69680. const uint8 xMode, const uint8 wMode,
  69681. const int parentPos,
  69682. const int parentSize) const throw()
  69683. {
  69684. if (wMode == proportionalSize)
  69685. {
  69686. if (parentSize > 0)
  69687. wOut = w / parentSize;
  69688. }
  69689. else if (wMode == parentSizeMinusAbsolute)
  69690. wOut = parentSize - w;
  69691. else
  69692. wOut = w;
  69693. if ((xMode & anchorAtRightOrBottom) != 0)
  69694. x += w;
  69695. else if ((xMode & anchorAtCentre) != 0)
  69696. x += w / 2;
  69697. if ((xMode & proportionOfParentSize) != 0)
  69698. {
  69699. if (parentSize > 0)
  69700. xOut = (x - parentPos) / parentSize;
  69701. }
  69702. else if ((xMode & absoluteFromParentBottomRight) != 0)
  69703. xOut = (parentPos + parentSize) - x;
  69704. else if ((xMode & absoluteFromParentCentre) != 0)
  69705. xOut = x - (parentPos + parentSize / 2);
  69706. else
  69707. xOut = x - parentPos;
  69708. }
  69709. END_JUCE_NAMESPACE
  69710. /********* End of inlined file: juce_PositionedRectangle.cpp *********/
  69711. /********* Start of inlined file: juce_Rectangle.cpp *********/
  69712. BEGIN_JUCE_NAMESPACE
  69713. Rectangle::Rectangle() throw()
  69714. : x (0),
  69715. y (0),
  69716. w (0),
  69717. h (0)
  69718. {
  69719. }
  69720. Rectangle::Rectangle (const int x_, const int y_,
  69721. const int w_, const int h_) throw()
  69722. : x (x_),
  69723. y (y_),
  69724. w (w_),
  69725. h (h_)
  69726. {
  69727. }
  69728. Rectangle::Rectangle (const int w_, const int h_) throw()
  69729. : x (0),
  69730. y (0),
  69731. w (w_),
  69732. h (h_)
  69733. {
  69734. }
  69735. Rectangle::Rectangle (const Rectangle& other) throw()
  69736. : x (other.x),
  69737. y (other.y),
  69738. w (other.w),
  69739. h (other.h)
  69740. {
  69741. }
  69742. Rectangle::~Rectangle() throw()
  69743. {
  69744. }
  69745. bool Rectangle::isEmpty() const throw()
  69746. {
  69747. return w <= 0 || h <= 0;
  69748. }
  69749. void Rectangle::setBounds (const int x_,
  69750. const int y_,
  69751. const int w_,
  69752. const int h_) throw()
  69753. {
  69754. x = x_;
  69755. y = y_;
  69756. w = w_;
  69757. h = h_;
  69758. }
  69759. void Rectangle::setPosition (const int x_,
  69760. const int y_) throw()
  69761. {
  69762. x = x_;
  69763. y = y_;
  69764. }
  69765. void Rectangle::setSize (const int w_,
  69766. const int h_) throw()
  69767. {
  69768. w = w_;
  69769. h = h_;
  69770. }
  69771. void Rectangle::translate (const int dx,
  69772. const int dy) throw()
  69773. {
  69774. x += dx;
  69775. y += dy;
  69776. }
  69777. const Rectangle Rectangle::translated (const int dx,
  69778. const int dy) const throw()
  69779. {
  69780. return Rectangle (x + dx, y + dy, w, h);
  69781. }
  69782. void Rectangle::expand (const int deltaX,
  69783. const int deltaY) throw()
  69784. {
  69785. const int nw = jmax (0, w + deltaX + deltaX);
  69786. const int nh = jmax (0, h + deltaY + deltaY);
  69787. setBounds (x - deltaX,
  69788. y - deltaY,
  69789. nw, nh);
  69790. }
  69791. const Rectangle Rectangle::expanded (const int deltaX,
  69792. const int deltaY) const throw()
  69793. {
  69794. const int nw = jmax (0, w + deltaX + deltaX);
  69795. const int nh = jmax (0, h + deltaY + deltaY);
  69796. return Rectangle (x - deltaX,
  69797. y - deltaY,
  69798. nw, nh);
  69799. }
  69800. void Rectangle::reduce (const int deltaX,
  69801. const int deltaY) throw()
  69802. {
  69803. expand (-deltaX, -deltaY);
  69804. }
  69805. const Rectangle Rectangle::reduced (const int deltaX,
  69806. const int deltaY) const throw()
  69807. {
  69808. return expanded (-deltaX, -deltaY);
  69809. }
  69810. bool Rectangle::operator== (const Rectangle& other) const throw()
  69811. {
  69812. return x == other.x
  69813. && y == other.y
  69814. && w == other.w
  69815. && h == other.h;
  69816. }
  69817. bool Rectangle::operator!= (const Rectangle& other) const throw()
  69818. {
  69819. return x != other.x
  69820. || y != other.y
  69821. || w != other.w
  69822. || h != other.h;
  69823. }
  69824. bool Rectangle::contains (const int px,
  69825. const int py) const throw()
  69826. {
  69827. return px >= x
  69828. && py >= y
  69829. && px < x + w
  69830. && py < y + h;
  69831. }
  69832. bool Rectangle::contains (const Rectangle& other) const throw()
  69833. {
  69834. return x <= other.x
  69835. && y <= other.y
  69836. && x + w >= other.x + other.w
  69837. && y + h >= other.y + other.h;
  69838. }
  69839. bool Rectangle::intersects (const Rectangle& other) const throw()
  69840. {
  69841. return x + w > other.x
  69842. && y + h > other.y
  69843. && x < other.x + other.w
  69844. && y < other.y + other.h
  69845. && w > 0
  69846. && h > 0;
  69847. }
  69848. const Rectangle Rectangle::getIntersection (const Rectangle& other) const throw()
  69849. {
  69850. const int nx = jmax (x, other.x);
  69851. const int ny = jmax (y, other.y);
  69852. const int nw = jmin (x + w, other.x + other.w) - nx;
  69853. const int nh = jmin (y + h, other.y + other.h) - ny;
  69854. if (nw >= 0 && nh >= 0)
  69855. return Rectangle (nx, ny, nw, nh);
  69856. else
  69857. return Rectangle();
  69858. }
  69859. bool Rectangle::intersectRectangle (int& x1, int& y1, int& w1, int& h1) const throw()
  69860. {
  69861. const int maxX = jmax (x1, x);
  69862. w1 = jmin (x1 + w1, x + w) - maxX;
  69863. if (w1 > 0)
  69864. {
  69865. const int maxY = jmax (y1, y);
  69866. h1 = jmin (y1 + h1, y + h) - maxY;
  69867. if (h1 > 0)
  69868. {
  69869. x1 = maxX;
  69870. y1 = maxY;
  69871. return true;
  69872. }
  69873. }
  69874. return false;
  69875. }
  69876. bool Rectangle::intersectRectangles (int& x1, int& y1, int& w1, int& h1,
  69877. int x2, int y2, int w2, int h2) throw()
  69878. {
  69879. const int x = jmax (x1, x2);
  69880. w1 = jmin (x1 + w1, x2 + w2) - x;
  69881. if (w1 > 0)
  69882. {
  69883. const int y = jmax (y1, y2);
  69884. h1 = jmin (y1 + h1, y2 + h2) - y;
  69885. if (h1 > 0)
  69886. {
  69887. x1 = x;
  69888. y1 = y;
  69889. return true;
  69890. }
  69891. }
  69892. return false;
  69893. }
  69894. const Rectangle Rectangle::getUnion (const Rectangle& other) const throw()
  69895. {
  69896. const int newX = jmin (x, other.x);
  69897. const int newY = jmin (y, other.y);
  69898. return Rectangle (newX, newY,
  69899. jmax (x + w, other.x + other.w) - newX,
  69900. jmax (y + h, other.y + other.h) - newY);
  69901. }
  69902. bool Rectangle::enlargeIfAdjacent (const Rectangle& other) throw()
  69903. {
  69904. if (x == other.x && getRight() == other.getRight()
  69905. && (other.getBottom() >= y && other.y <= getBottom()))
  69906. {
  69907. const int newY = jmin (y, other.y);
  69908. h = jmax (getBottom(), other.getBottom()) - newY;
  69909. y = newY;
  69910. return true;
  69911. }
  69912. else if (y == other.y && getBottom() == other.getBottom()
  69913. && (other.getRight() >= x && other.x <= getRight()))
  69914. {
  69915. const int newX = jmin (x, other.x);
  69916. w = jmax (getRight(), other.getRight()) - newX;
  69917. x = newX;
  69918. return true;
  69919. }
  69920. return false;
  69921. }
  69922. bool Rectangle::reduceIfPartlyContainedIn (const Rectangle& other) throw()
  69923. {
  69924. int inside = 0;
  69925. const int otherR = other.getRight();
  69926. if (x >= other.x && x < otherR)
  69927. inside = 1;
  69928. const int otherB = other.getBottom();
  69929. if (y >= other.y && y < otherB)
  69930. inside |= 2;
  69931. const int r = x + w;
  69932. if (r >= other.x && r < otherR)
  69933. inside |= 4;
  69934. const int b = y + h;
  69935. if (b >= other.y && b < otherB)
  69936. inside |= 8;
  69937. switch (inside)
  69938. {
  69939. case 1 + 2 + 8:
  69940. w = r - otherR;
  69941. x = otherR;
  69942. return true;
  69943. case 1 + 2 + 4:
  69944. h = b - otherB;
  69945. y = otherB;
  69946. return true;
  69947. case 2 + 4 + 8:
  69948. w = other.x - x;
  69949. return true;
  69950. case 1 + 4 + 8:
  69951. h = other.y - y;
  69952. return true;
  69953. }
  69954. return false;
  69955. }
  69956. const String Rectangle::toString() const throw()
  69957. {
  69958. String s;
  69959. s.preallocateStorage (16);
  69960. s << x << T(' ')
  69961. << y << T(' ')
  69962. << w << T(' ')
  69963. << h;
  69964. return s;
  69965. }
  69966. const Rectangle Rectangle::fromString (const String& stringVersion)
  69967. {
  69968. StringArray toks;
  69969. toks.addTokens (stringVersion.trim(), T(",; \t\r\n"), 0);
  69970. return Rectangle (toks[0].trim().getIntValue(),
  69971. toks[1].trim().getIntValue(),
  69972. toks[2].trim().getIntValue(),
  69973. toks[3].trim().getIntValue());
  69974. }
  69975. END_JUCE_NAMESPACE
  69976. /********* End of inlined file: juce_Rectangle.cpp *********/
  69977. /********* Start of inlined file: juce_RectangleList.cpp *********/
  69978. BEGIN_JUCE_NAMESPACE
  69979. RectangleList::RectangleList() throw()
  69980. {
  69981. }
  69982. RectangleList::RectangleList (const Rectangle& rect) throw()
  69983. {
  69984. if (! rect.isEmpty())
  69985. rects.add (rect);
  69986. }
  69987. RectangleList::RectangleList (const RectangleList& other) throw()
  69988. : rects (other.rects)
  69989. {
  69990. }
  69991. const RectangleList& RectangleList::operator= (const RectangleList& other) throw()
  69992. {
  69993. if (this != &other)
  69994. rects = other.rects;
  69995. return *this;
  69996. }
  69997. RectangleList::~RectangleList() throw()
  69998. {
  69999. }
  70000. void RectangleList::clear() throw()
  70001. {
  70002. rects.clearQuick();
  70003. }
  70004. const Rectangle RectangleList::getRectangle (const int index) const throw()
  70005. {
  70006. if (((unsigned int) index) < (unsigned int) rects.size())
  70007. return rects.getReference (index);
  70008. return Rectangle();
  70009. }
  70010. bool RectangleList::isEmpty() const throw()
  70011. {
  70012. return rects.size() == 0;
  70013. }
  70014. RectangleList::Iterator::Iterator (const RectangleList& list) throw()
  70015. : current (0),
  70016. owner (list),
  70017. index (list.rects.size())
  70018. {
  70019. }
  70020. RectangleList::Iterator::~Iterator() throw()
  70021. {
  70022. }
  70023. bool RectangleList::Iterator::next() throw()
  70024. {
  70025. if (--index >= 0)
  70026. {
  70027. current = & (owner.rects.getReference (index));
  70028. return true;
  70029. }
  70030. return false;
  70031. }
  70032. void RectangleList::add (const Rectangle& rect) throw()
  70033. {
  70034. if (! rect.isEmpty())
  70035. {
  70036. if (rects.size() == 0)
  70037. {
  70038. rects.add (rect);
  70039. }
  70040. else
  70041. {
  70042. bool anyOverlaps = false;
  70043. int i;
  70044. for (i = rects.size(); --i >= 0;)
  70045. {
  70046. Rectangle& ourRect = rects.getReference (i);
  70047. if (rect.intersects (ourRect))
  70048. {
  70049. if (rect.contains (ourRect))
  70050. rects.remove (i);
  70051. else if (! ourRect.reduceIfPartlyContainedIn (rect))
  70052. anyOverlaps = true;
  70053. }
  70054. }
  70055. if (anyOverlaps && rects.size() > 0)
  70056. {
  70057. RectangleList r (rect);
  70058. for (i = rects.size(); --i >= 0;)
  70059. {
  70060. const Rectangle& ourRect = rects.getReference (i);
  70061. if (rect.intersects (ourRect))
  70062. {
  70063. r.subtract (ourRect);
  70064. if (r.rects.size() == 0)
  70065. return;
  70066. }
  70067. }
  70068. for (i = r.getNumRectangles(); --i >= 0;)
  70069. rects.add (r.rects.getReference (i));
  70070. }
  70071. else
  70072. {
  70073. rects.add (rect);
  70074. }
  70075. }
  70076. }
  70077. }
  70078. void RectangleList::addWithoutMerging (const Rectangle& rect) throw()
  70079. {
  70080. rects.add (rect);
  70081. }
  70082. void RectangleList::add (const int x, const int y, const int w, const int h) throw()
  70083. {
  70084. if (rects.size() == 0)
  70085. {
  70086. if (w > 0 && h > 0)
  70087. rects.add (Rectangle (x, y, w, h));
  70088. }
  70089. else
  70090. {
  70091. add (Rectangle (x, y, w, h));
  70092. }
  70093. }
  70094. void RectangleList::add (const RectangleList& other) throw()
  70095. {
  70096. for (int i = 0; i < other.rects.size(); ++i)
  70097. add (other.rects.getReference (i));
  70098. }
  70099. void RectangleList::subtract (const Rectangle& rect) throw()
  70100. {
  70101. const int originalNumRects = rects.size();
  70102. if (originalNumRects > 0)
  70103. {
  70104. const int x1 = rect.x;
  70105. const int y1 = rect.y;
  70106. const int x2 = x1 + rect.w;
  70107. const int y2 = y1 + rect.h;
  70108. for (int i = getNumRectangles(); --i >= 0;)
  70109. {
  70110. Rectangle& r = rects.getReference (i);
  70111. const int rx1 = r.x;
  70112. const int ry1 = r.y;
  70113. const int rx2 = rx1 + r.w;
  70114. const int ry2 = ry1 + r.h;
  70115. if (! (x2 <= rx1 || x1 >= rx2 || y2 <= ry1 || y1 >= ry2))
  70116. {
  70117. if (x1 > rx1 && x1 < rx2)
  70118. {
  70119. if (y1 <= ry1 && y2 >= ry2 && x2 >= rx2)
  70120. {
  70121. r.w = x1 - rx1;
  70122. }
  70123. else
  70124. {
  70125. r.x = x1;
  70126. r.w = rx2 - x1;
  70127. rects.insert (i + 1, Rectangle (rx1, ry1, x1 - rx1, ry2 - ry1));
  70128. i += 2;
  70129. }
  70130. }
  70131. else if (x2 > rx1 && x2 < rx2)
  70132. {
  70133. r.x = x2;
  70134. r.w = rx2 - x2;
  70135. if (y1 > ry1 || y2 < ry2 || x1 > rx1)
  70136. {
  70137. rects.insert (i + 1, Rectangle (rx1, ry1, x2 - rx1, ry2 - ry1));
  70138. i += 2;
  70139. }
  70140. }
  70141. else if (y1 > ry1 && y1 < ry2)
  70142. {
  70143. if (x1 <= rx1 && x2 >= rx2 && y2 >= ry2)
  70144. {
  70145. r.h = y1 - ry1;
  70146. }
  70147. else
  70148. {
  70149. r.y = y1;
  70150. r.h = ry2 - y1;
  70151. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y1 - ry1));
  70152. i += 2;
  70153. }
  70154. }
  70155. else if (y2 > ry1 && y2 < ry2)
  70156. {
  70157. r.y = y2;
  70158. r.h = ry2 - y2;
  70159. if (x1 > rx1 || x2 < rx2 || y1 > ry1)
  70160. {
  70161. rects.insert (i + 1, Rectangle (rx1, ry1, rx2 - rx1, y2 - ry1));
  70162. i += 2;
  70163. }
  70164. }
  70165. else
  70166. {
  70167. rects.remove (i);
  70168. }
  70169. }
  70170. }
  70171. if (rects.size() > originalNumRects + 10)
  70172. consolidate();
  70173. }
  70174. }
  70175. void RectangleList::subtract (const RectangleList& otherList) throw()
  70176. {
  70177. for (int i = otherList.rects.size(); --i >= 0;)
  70178. subtract (otherList.rects.getReference (i));
  70179. }
  70180. bool RectangleList::clipTo (const Rectangle& rect) throw()
  70181. {
  70182. bool notEmpty = false;
  70183. if (rect.isEmpty())
  70184. {
  70185. clear();
  70186. }
  70187. else
  70188. {
  70189. for (int i = rects.size(); --i >= 0;)
  70190. {
  70191. Rectangle& r = rects.getReference (i);
  70192. if (! rect.intersectRectangle (r.x, r.y, r.w, r.h))
  70193. rects.remove (i);
  70194. else
  70195. notEmpty = true;
  70196. }
  70197. }
  70198. return notEmpty;
  70199. }
  70200. bool RectangleList::clipTo (const RectangleList& other) throw()
  70201. {
  70202. if (rects.size() == 0)
  70203. return false;
  70204. RectangleList result;
  70205. for (int j = 0; j < rects.size(); ++j)
  70206. {
  70207. const Rectangle& rect = rects.getReference (j);
  70208. for (int i = other.rects.size(); --i >= 0;)
  70209. {
  70210. Rectangle r (other.rects.getReference (i));
  70211. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  70212. result.rects.add (r);
  70213. }
  70214. }
  70215. swapWith (result);
  70216. return ! isEmpty();
  70217. }
  70218. bool RectangleList::getIntersectionWith (const Rectangle& rect, RectangleList& destRegion) const throw()
  70219. {
  70220. destRegion.clear();
  70221. if (! rect.isEmpty())
  70222. {
  70223. for (int i = rects.size(); --i >= 0;)
  70224. {
  70225. Rectangle r (rects.getReference (i));
  70226. if (rect.intersectRectangle (r.x, r.y, r.w, r.h))
  70227. destRegion.rects.add (r);
  70228. }
  70229. }
  70230. return destRegion.rects.size() > 0;
  70231. }
  70232. void RectangleList::swapWith (RectangleList& otherList) throw()
  70233. {
  70234. rects.swapWithArray (otherList.rects);
  70235. }
  70236. void RectangleList::consolidate() throw()
  70237. {
  70238. int i;
  70239. for (i = 0; i < getNumRectangles() - 1; ++i)
  70240. {
  70241. Rectangle& r = rects.getReference (i);
  70242. const int rx1 = r.x;
  70243. const int ry1 = r.y;
  70244. const int rx2 = rx1 + r.w;
  70245. const int ry2 = ry1 + r.h;
  70246. for (int j = rects.size(); --j > i;)
  70247. {
  70248. Rectangle& r2 = rects.getReference (j);
  70249. const int jrx1 = r2.x;
  70250. const int jry1 = r2.y;
  70251. const int jrx2 = jrx1 + r2.w;
  70252. const int jry2 = jry1 + r2.h;
  70253. // if the vertical edges of any blocks are touching and their horizontals don't
  70254. // line up, split them horizontally..
  70255. if (jrx1 == rx2 || jrx2 == rx1)
  70256. {
  70257. if (jry1 > ry1 && jry1 < ry2)
  70258. {
  70259. r.h = jry1 - ry1;
  70260. rects.add (Rectangle (rx1, jry1, rx2 - rx1, ry2 - jry1));
  70261. i = -1;
  70262. break;
  70263. }
  70264. if (jry2 > ry1 && jry2 < ry2)
  70265. {
  70266. r.h = jry2 - ry1;
  70267. rects.add (Rectangle (rx1, jry2, rx2 - rx1, ry2 - jry2));
  70268. i = -1;
  70269. break;
  70270. }
  70271. else if (ry1 > jry1 && ry1 < jry2)
  70272. {
  70273. r2.h = ry1 - jry1;
  70274. rects.add (Rectangle (jrx1, ry1, jrx2 - jrx1, jry2 - ry1));
  70275. i = -1;
  70276. break;
  70277. }
  70278. else if (ry2 > jry1 && ry2 < jry2)
  70279. {
  70280. r2.h = ry2 - jry1;
  70281. rects.add (Rectangle (jrx1, ry2, jrx2 - jrx1, jry2 - ry2));
  70282. i = -1;
  70283. break;
  70284. }
  70285. }
  70286. }
  70287. }
  70288. for (i = 0; i < rects.size() - 1; ++i)
  70289. {
  70290. Rectangle& r = rects.getReference (i);
  70291. for (int j = rects.size(); --j > i;)
  70292. {
  70293. if (r.enlargeIfAdjacent (rects.getReference (j)))
  70294. {
  70295. rects.remove (j);
  70296. i = -1;
  70297. break;
  70298. }
  70299. }
  70300. }
  70301. }
  70302. bool RectangleList::containsPoint (const int x, const int y) const throw()
  70303. {
  70304. for (int i = getNumRectangles(); --i >= 0;)
  70305. if (rects.getReference (i).contains (x, y))
  70306. return true;
  70307. return false;
  70308. }
  70309. bool RectangleList::containsRectangle (const Rectangle& rectangleToCheck) const throw()
  70310. {
  70311. if (rects.size() > 1)
  70312. {
  70313. RectangleList r (rectangleToCheck);
  70314. for (int i = rects.size(); --i >= 0;)
  70315. {
  70316. r.subtract (rects.getReference (i));
  70317. if (r.rects.size() == 0)
  70318. return true;
  70319. }
  70320. }
  70321. else if (rects.size() > 0)
  70322. {
  70323. return rects.getReference (0).contains (rectangleToCheck);
  70324. }
  70325. return false;
  70326. }
  70327. bool RectangleList::intersectsRectangle (const Rectangle& rectangleToCheck) const throw()
  70328. {
  70329. for (int i = rects.size(); --i >= 0;)
  70330. if (rects.getReference (i).intersects (rectangleToCheck))
  70331. return true;
  70332. return false;
  70333. }
  70334. bool RectangleList::intersects (const RectangleList& other) const throw()
  70335. {
  70336. for (int i = rects.size(); --i >= 0;)
  70337. if (other.intersectsRectangle (rects.getReference (i)))
  70338. return true;
  70339. return false;
  70340. }
  70341. const Rectangle RectangleList::getBounds() const throw()
  70342. {
  70343. if (rects.size() <= 1)
  70344. {
  70345. if (rects.size() == 0)
  70346. return Rectangle();
  70347. else
  70348. return rects.getReference (0);
  70349. }
  70350. else
  70351. {
  70352. const Rectangle& r = rects.getReference (0);
  70353. int minX = r.x;
  70354. int minY = r.y;
  70355. int maxX = minX + r.w;
  70356. int maxY = minY + r.h;
  70357. for (int i = rects.size(); --i > 0;)
  70358. {
  70359. const Rectangle& r2 = rects.getReference (i);
  70360. minX = jmin (minX, r2.x);
  70361. minY = jmin (minY, r2.y);
  70362. maxX = jmax (maxX, r2.getRight());
  70363. maxY = jmax (maxY, r2.getBottom());
  70364. }
  70365. return Rectangle (minX, minY, maxX - minX, maxY - minY);
  70366. }
  70367. }
  70368. void RectangleList::offsetAll (const int dx, const int dy) throw()
  70369. {
  70370. for (int i = rects.size(); --i >= 0;)
  70371. {
  70372. Rectangle& r = rects.getReference (i);
  70373. r.x += dx;
  70374. r.y += dy;
  70375. }
  70376. }
  70377. const Path RectangleList::toPath() const throw()
  70378. {
  70379. Path p;
  70380. for (int i = rects.size(); --i >= 0;)
  70381. {
  70382. const Rectangle& r = rects.getReference (i);
  70383. p.addRectangle ((float) r.x,
  70384. (float) r.y,
  70385. (float) r.w,
  70386. (float) r.h);
  70387. }
  70388. return p;
  70389. }
  70390. END_JUCE_NAMESPACE
  70391. /********* End of inlined file: juce_RectangleList.cpp *********/
  70392. /********* Start of inlined file: juce_Image.cpp *********/
  70393. BEGIN_JUCE_NAMESPACE
  70394. static const int fullAlphaThreshold = 253;
  70395. Image::Image (const PixelFormat format_,
  70396. const int imageWidth_,
  70397. const int imageHeight_)
  70398. : format (format_),
  70399. imageWidth (imageWidth_),
  70400. imageHeight (imageHeight_),
  70401. imageData (0)
  70402. {
  70403. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  70404. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  70405. // actual image will be at least 1x1.
  70406. }
  70407. Image::Image (const PixelFormat format_,
  70408. const int imageWidth_,
  70409. const int imageHeight_,
  70410. const bool clearImage)
  70411. : format (format_),
  70412. imageWidth (imageWidth_),
  70413. imageHeight (imageHeight_)
  70414. {
  70415. jassert (format_ == RGB || format_ == ARGB || format_ == SingleChannel);
  70416. jassert (imageWidth_ > 0 && imageHeight_ > 0); // it's illegal to create a zero-sized image - the
  70417. // actual image will be at least 1x1.
  70418. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  70419. lineStride = (pixelStride * jmax (1, imageWidth_) + 3) & ~3;
  70420. const int dataSize = lineStride * jmax (1, imageHeight_);
  70421. imageData = (uint8*) (clearImage ? juce_calloc (dataSize)
  70422. : juce_malloc (dataSize));
  70423. }
  70424. Image::Image (const Image& other)
  70425. : format (other.format),
  70426. imageWidth (other.imageWidth),
  70427. imageHeight (other.imageHeight)
  70428. {
  70429. pixelStride = (format == RGB) ? 3 : ((format == ARGB) ? 4 : 1);
  70430. lineStride = (pixelStride * jmax (1, imageWidth) + 3) & ~3;
  70431. const int dataSize = lineStride * jmax (1, imageHeight);
  70432. imageData = (uint8*) juce_malloc (dataSize);
  70433. int ls, ps;
  70434. const uint8* srcData = other.lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  70435. setPixelData (0, 0, imageWidth, imageHeight, srcData, ls);
  70436. other.releasePixelDataReadOnly (srcData);
  70437. }
  70438. Image::~Image()
  70439. {
  70440. juce_free (imageData);
  70441. }
  70442. LowLevelGraphicsContext* Image::createLowLevelContext()
  70443. {
  70444. return new LowLevelGraphicsSoftwareRenderer (*this);
  70445. }
  70446. uint8* Image::lockPixelDataReadWrite (int x, int y, int w, int h, int& ls, int& ps)
  70447. {
  70448. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  70449. w = w;
  70450. h = h;
  70451. ls = lineStride;
  70452. ps = pixelStride;
  70453. return imageData + x * pixelStride + y * lineStride;
  70454. }
  70455. void Image::releasePixelDataReadWrite (void*)
  70456. {
  70457. }
  70458. const uint8* Image::lockPixelDataReadOnly (int x, int y, int w, int h, int& ls, int& ps) const
  70459. {
  70460. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  70461. w = w;
  70462. h = h;
  70463. ls = lineStride;
  70464. ps = pixelStride;
  70465. return imageData + x * pixelStride + y * lineStride;
  70466. }
  70467. void Image::releasePixelDataReadOnly (const void*) const
  70468. {
  70469. }
  70470. void Image::setPixelData (int x, int y, int w, int h,
  70471. const uint8* sourcePixelData, int sourceLineStride)
  70472. {
  70473. jassert (x >= 0 && y >= 0 && w > 0 && h > 0 && x + w <= imageWidth && y + h <= imageHeight);
  70474. if (Rectangle::intersectRectangles (x, y, w, h, 0, 0, imageWidth, imageHeight))
  70475. {
  70476. int ls, ps;
  70477. uint8* dest = lockPixelDataReadWrite (x, y, w, h, ls, ps);
  70478. for (int i = 0; i < h; ++i)
  70479. {
  70480. memcpy (dest + ls * i,
  70481. sourcePixelData + sourceLineStride * i,
  70482. w * pixelStride);
  70483. }
  70484. releasePixelDataReadWrite (dest);
  70485. }
  70486. }
  70487. void Image::clear (int dx, int dy, int dw, int dh,
  70488. const Colour& colourToClearTo)
  70489. {
  70490. const PixelARGB col (colourToClearTo.getPixelARGB());
  70491. int ls, ps;
  70492. uint8* dstData = lockPixelDataReadWrite (dx, dy, dw, dh, ls, ps);
  70493. uint8* dest = dstData;
  70494. while (--dh >= 0)
  70495. {
  70496. uint8* line = dest;
  70497. dest += ls;
  70498. if (isARGB())
  70499. {
  70500. for (int x = dw; --x >= 0;)
  70501. {
  70502. ((PixelARGB*) line)->set (col);
  70503. line += ps;
  70504. }
  70505. }
  70506. else if (isRGB())
  70507. {
  70508. for (int x = dw; --x >= 0;)
  70509. {
  70510. ((PixelRGB*) line)->set (col);
  70511. line += ps;
  70512. }
  70513. }
  70514. else
  70515. {
  70516. for (int x = dw; --x >= 0;)
  70517. {
  70518. *line = col.getAlpha();
  70519. line += ps;
  70520. }
  70521. }
  70522. }
  70523. releasePixelDataReadWrite (dstData);
  70524. }
  70525. Image* Image::createCopy (int newWidth, int newHeight,
  70526. const Graphics::ResamplingQuality quality) const
  70527. {
  70528. if (newWidth < 0)
  70529. newWidth = imageWidth;
  70530. if (newHeight < 0)
  70531. newHeight = imageHeight;
  70532. Image* const newImage = new Image (format, newWidth, newHeight, true);
  70533. Graphics g (*newImage);
  70534. g.setImageResamplingQuality (quality);
  70535. g.drawImage (this,
  70536. 0, 0, newWidth, newHeight,
  70537. 0, 0, imageWidth, imageHeight,
  70538. false);
  70539. return newImage;
  70540. }
  70541. const Colour Image::getPixelAt (const int x, const int y) const
  70542. {
  70543. Colour c;
  70544. if (((unsigned int) x) < (unsigned int) imageWidth
  70545. && ((unsigned int) y) < (unsigned int) imageHeight)
  70546. {
  70547. int ls, ps;
  70548. const uint8* const pixels = lockPixelDataReadOnly (x, y, 1, 1, ls, ps);
  70549. if (isARGB())
  70550. {
  70551. PixelARGB p (*(const PixelARGB*) pixels);
  70552. p.unpremultiply();
  70553. c = Colour (p.getARGB());
  70554. }
  70555. else if (isRGB())
  70556. c = Colour (((const PixelRGB*) pixels)->getARGB());
  70557. else
  70558. c = Colour ((uint8) 0, (uint8) 0, (uint8) 0, *pixels);
  70559. releasePixelDataReadOnly (pixels);
  70560. }
  70561. return c;
  70562. }
  70563. void Image::setPixelAt (const int x, const int y,
  70564. const Colour& colour)
  70565. {
  70566. if (((unsigned int) x) < (unsigned int) imageWidth
  70567. && ((unsigned int) y) < (unsigned int) imageHeight)
  70568. {
  70569. int ls, ps;
  70570. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  70571. const PixelARGB col (colour.getPixelARGB());
  70572. if (isARGB())
  70573. ((PixelARGB*) pixels)->set (col);
  70574. else if (isRGB())
  70575. ((PixelRGB*) pixels)->set (col);
  70576. else
  70577. *pixels = col.getAlpha();
  70578. releasePixelDataReadWrite (pixels);
  70579. }
  70580. }
  70581. void Image::multiplyAlphaAt (const int x, const int y,
  70582. const float multiplier)
  70583. {
  70584. if (((unsigned int) x) < (unsigned int) imageWidth
  70585. && ((unsigned int) y) < (unsigned int) imageHeight
  70586. && hasAlphaChannel())
  70587. {
  70588. int ls, ps;
  70589. uint8* const pixels = lockPixelDataReadWrite (x, y, 1, 1, ls, ps);
  70590. if (isARGB())
  70591. ((PixelARGB*) pixels)->multiplyAlpha (multiplier);
  70592. else
  70593. *pixels = (uint8) (*pixels * multiplier);
  70594. releasePixelDataReadWrite (pixels);
  70595. }
  70596. }
  70597. void Image::multiplyAllAlphas (const float amountToMultiplyBy)
  70598. {
  70599. if (hasAlphaChannel())
  70600. {
  70601. int ls, ps;
  70602. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  70603. if (isARGB())
  70604. {
  70605. for (int y = 0; y < imageHeight; ++y)
  70606. {
  70607. uint8* p = pixels + y * ls;
  70608. for (int x = 0; x < imageWidth; ++x)
  70609. {
  70610. ((PixelARGB*) p)->multiplyAlpha (amountToMultiplyBy);
  70611. p += ps;
  70612. }
  70613. }
  70614. }
  70615. else
  70616. {
  70617. for (int y = 0; y < imageHeight; ++y)
  70618. {
  70619. uint8* p = pixels + y * ls;
  70620. for (int x = 0; x < imageWidth; ++x)
  70621. {
  70622. *p = (uint8) (*p * amountToMultiplyBy);
  70623. p += ps;
  70624. }
  70625. }
  70626. }
  70627. releasePixelDataReadWrite (pixels);
  70628. }
  70629. else
  70630. {
  70631. jassertfalse // can't do this without an alpha-channel!
  70632. }
  70633. }
  70634. void Image::desaturate()
  70635. {
  70636. if (isARGB() || isRGB())
  70637. {
  70638. int ls, ps;
  70639. uint8* const pixels = lockPixelDataReadWrite (0, 0, getWidth(), getHeight(), ls, ps);
  70640. if (isARGB())
  70641. {
  70642. for (int y = 0; y < imageHeight; ++y)
  70643. {
  70644. uint8* p = pixels + y * ls;
  70645. for (int x = 0; x < imageWidth; ++x)
  70646. {
  70647. ((PixelARGB*) p)->desaturate();
  70648. p += ps;
  70649. }
  70650. }
  70651. }
  70652. else
  70653. {
  70654. for (int y = 0; y < imageHeight; ++y)
  70655. {
  70656. uint8* p = pixels + y * ls;
  70657. for (int x = 0; x < imageWidth; ++x)
  70658. {
  70659. ((PixelRGB*) p)->desaturate();
  70660. p += ps;
  70661. }
  70662. }
  70663. }
  70664. releasePixelDataReadWrite (pixels);
  70665. }
  70666. }
  70667. void Image::createSolidAreaMask (RectangleList& result, const float alphaThreshold) const
  70668. {
  70669. if (hasAlphaChannel())
  70670. {
  70671. const uint8 threshold = (uint8) jlimit (0, 255, roundFloatToInt (alphaThreshold * 255.0f));
  70672. SparseSet <int> pixelsOnRow;
  70673. int ls, ps;
  70674. const uint8* const pixels = lockPixelDataReadOnly (0, 0, imageWidth, imageHeight, ls, ps);
  70675. for (int y = 0; y < imageHeight; ++y)
  70676. {
  70677. pixelsOnRow.clear();
  70678. const uint8* lineData = pixels + ls * y;
  70679. if (isARGB())
  70680. {
  70681. for (int x = 0; x < imageWidth; ++x)
  70682. {
  70683. if (((const PixelARGB*) lineData)->getAlpha() >= threshold)
  70684. pixelsOnRow.addRange (x, 1);
  70685. lineData += ps;
  70686. }
  70687. }
  70688. else
  70689. {
  70690. for (int x = 0; x < imageWidth; ++x)
  70691. {
  70692. if (*lineData >= threshold)
  70693. pixelsOnRow.addRange (x, 1);
  70694. lineData += ps;
  70695. }
  70696. }
  70697. for (int i = 0; i < pixelsOnRow.getNumRanges(); ++i)
  70698. {
  70699. int x, w;
  70700. if (pixelsOnRow.getRange (i, x, w))
  70701. result.add (Rectangle (x, y, w, 1));
  70702. }
  70703. result.consolidate();
  70704. }
  70705. releasePixelDataReadOnly (pixels);
  70706. }
  70707. else
  70708. {
  70709. result.add (0, 0, imageWidth, imageHeight);
  70710. }
  70711. }
  70712. void Image::moveImageSection (int dx, int dy,
  70713. int sx, int sy,
  70714. int w, int h)
  70715. {
  70716. if (dx < 0)
  70717. {
  70718. w += dx;
  70719. sx -= dx;
  70720. dx = 0;
  70721. }
  70722. if (dy < 0)
  70723. {
  70724. h += dy;
  70725. sy -= dy;
  70726. dy = 0;
  70727. }
  70728. if (sx < 0)
  70729. {
  70730. w += sx;
  70731. dx -= sx;
  70732. sx = 0;
  70733. }
  70734. if (sy < 0)
  70735. {
  70736. h += sy;
  70737. dy -= sy;
  70738. sy = 0;
  70739. }
  70740. const int minX = jmin (dx, sx);
  70741. const int minY = jmin (dy, sy);
  70742. w = jmin (w, getWidth() - jmax (sx, dx));
  70743. h = jmin (h, getHeight() - jmax (sy, dy));
  70744. if (w > 0 && h > 0)
  70745. {
  70746. const int maxX = jmax (dx, sx) + w;
  70747. const int maxY = jmax (dy, sy) + h;
  70748. int ls, ps;
  70749. uint8* const pixels = lockPixelDataReadWrite (minX, minY, maxX - minX, maxY - minY, ls, ps);
  70750. uint8* dst = pixels + ls * (dy - minY) + ps * (dx - minX);
  70751. const uint8* src = pixels + ls * (sy - minY) + ps * (sx - minX);
  70752. const int lineSize = ps * w;
  70753. if (dy > sy)
  70754. {
  70755. while (--h >= 0)
  70756. {
  70757. const int offset = h * ls;
  70758. memmove (dst + offset, src + offset, lineSize);
  70759. }
  70760. }
  70761. else if (dst != src)
  70762. {
  70763. while (--h >= 0)
  70764. {
  70765. memmove (dst, src, lineSize);
  70766. dst += ls;
  70767. src += ls;
  70768. }
  70769. }
  70770. releasePixelDataReadWrite (pixels);
  70771. }
  70772. }
  70773. END_JUCE_NAMESPACE
  70774. /********* End of inlined file: juce_Image.cpp *********/
  70775. /********* Start of inlined file: juce_ImageCache.cpp *********/
  70776. BEGIN_JUCE_NAMESPACE
  70777. struct CachedImageInfo
  70778. {
  70779. Image* image;
  70780. int64 hashCode;
  70781. int refCount;
  70782. unsigned int releaseTime;
  70783. juce_UseDebuggingNewOperator
  70784. };
  70785. static ImageCache* instance = 0;
  70786. static int cacheTimeout = 5000;
  70787. ImageCache::ImageCache() throw()
  70788. : images (4)
  70789. {
  70790. }
  70791. ImageCache::~ImageCache()
  70792. {
  70793. const ScopedLock sl (lock);
  70794. for (int i = images.size(); --i >= 0;)
  70795. {
  70796. CachedImageInfo* const ci = (CachedImageInfo*)(images.getUnchecked(i));
  70797. delete ci->image;
  70798. delete ci;
  70799. }
  70800. images.clear();
  70801. jassert (instance == this);
  70802. instance = 0;
  70803. }
  70804. Image* ImageCache::getFromHashCode (const int64 hashCode)
  70805. {
  70806. if (instance != 0)
  70807. {
  70808. const ScopedLock sl (instance->lock);
  70809. for (int i = instance->images.size(); --i >= 0;)
  70810. {
  70811. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  70812. if (ci->hashCode == hashCode)
  70813. {
  70814. atomicIncrement (ci->refCount);
  70815. return ci->image;
  70816. }
  70817. }
  70818. }
  70819. return 0;
  70820. }
  70821. void ImageCache::addImageToCache (Image* const image,
  70822. const int64 hashCode)
  70823. {
  70824. if (image != 0)
  70825. {
  70826. if (instance == 0)
  70827. instance = new ImageCache();
  70828. CachedImageInfo* const newC = new CachedImageInfo();
  70829. newC->hashCode = hashCode;
  70830. newC->image = image;
  70831. newC->refCount = 1;
  70832. newC->releaseTime = 0;
  70833. const ScopedLock sl (instance->lock);
  70834. instance->images.add (newC);
  70835. }
  70836. }
  70837. void ImageCache::release (Image* const imageToRelease)
  70838. {
  70839. if (imageToRelease != 0 && instance != 0)
  70840. {
  70841. const ScopedLock sl (instance->lock);
  70842. for (int i = instance->images.size(); --i >= 0;)
  70843. {
  70844. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  70845. if (ci->image == imageToRelease)
  70846. {
  70847. if (--(ci->refCount) == 0)
  70848. ci->releaseTime = Time::getApproximateMillisecondCounter();
  70849. if (! instance->isTimerRunning())
  70850. instance->startTimer (999);
  70851. break;
  70852. }
  70853. }
  70854. }
  70855. }
  70856. bool ImageCache::isImageInCache (Image* const imageToLookFor)
  70857. {
  70858. if (instance != 0)
  70859. {
  70860. const ScopedLock sl (instance->lock);
  70861. for (int i = instance->images.size(); --i >= 0;)
  70862. if (((const CachedImageInfo*) instance->images.getUnchecked(i))->image == imageToLookFor)
  70863. return true;
  70864. }
  70865. return false;
  70866. }
  70867. void ImageCache::incReferenceCount (Image* const image)
  70868. {
  70869. if (instance != 0)
  70870. {
  70871. const ScopedLock sl (instance->lock);
  70872. for (int i = instance->images.size(); --i >= 0;)
  70873. {
  70874. CachedImageInfo* const ci = (CachedImageInfo*) instance->images.getUnchecked(i);
  70875. if (ci->image == image)
  70876. {
  70877. ci->refCount++;
  70878. return;
  70879. }
  70880. }
  70881. }
  70882. jassertfalse // (trying to inc the ref count of an image that's not in the cache)
  70883. }
  70884. void ImageCache::timerCallback()
  70885. {
  70886. int numberStillNeedingReleasing = 0;
  70887. const unsigned int now = Time::getApproximateMillisecondCounter();
  70888. const ScopedLock sl (lock);
  70889. for (int i = images.size(); --i >= 0;)
  70890. {
  70891. CachedImageInfo* const ci = (CachedImageInfo*) images.getUnchecked(i);
  70892. if (ci->refCount <= 0)
  70893. {
  70894. if (now > ci->releaseTime + cacheTimeout
  70895. || now < ci->releaseTime - 1000)
  70896. {
  70897. images.remove (i);
  70898. delete ci->image;
  70899. delete ci;
  70900. }
  70901. else
  70902. {
  70903. ++numberStillNeedingReleasing;
  70904. }
  70905. }
  70906. }
  70907. if (numberStillNeedingReleasing == 0)
  70908. stopTimer();
  70909. }
  70910. Image* ImageCache::getFromFile (const File& file)
  70911. {
  70912. const int64 hashCode = file.getFullPathName().hashCode64();
  70913. Image* image = getFromHashCode (hashCode);
  70914. if (image == 0)
  70915. {
  70916. image = ImageFileFormat::loadFrom (file);
  70917. addImageToCache (image, hashCode);
  70918. }
  70919. return image;
  70920. }
  70921. Image* ImageCache::getFromMemory (const void* imageData,
  70922. const int dataSize)
  70923. {
  70924. const int64 hashCode = (int64) (pointer_sized_int) imageData;
  70925. Image* image = getFromHashCode (hashCode);
  70926. if (image == 0)
  70927. {
  70928. image = ImageFileFormat::loadFrom (imageData, dataSize);
  70929. addImageToCache (image, hashCode);
  70930. }
  70931. return image;
  70932. }
  70933. void ImageCache::setCacheTimeout (const int millisecs)
  70934. {
  70935. cacheTimeout = millisecs;
  70936. }
  70937. END_JUCE_NAMESPACE
  70938. /********* End of inlined file: juce_ImageCache.cpp *********/
  70939. /********* Start of inlined file: juce_ImageConvolutionKernel.cpp *********/
  70940. BEGIN_JUCE_NAMESPACE
  70941. ImageConvolutionKernel::ImageConvolutionKernel (const int size_) throw()
  70942. : size (size_)
  70943. {
  70944. values = new float* [size];
  70945. for (int i = size; --i >= 0;)
  70946. values[i] = new float [size];
  70947. clear();
  70948. }
  70949. ImageConvolutionKernel::~ImageConvolutionKernel() throw()
  70950. {
  70951. for (int i = size; --i >= 0;)
  70952. delete[] values[i];
  70953. delete[] values;
  70954. }
  70955. void ImageConvolutionKernel::setKernelValue (const int x,
  70956. const int y,
  70957. const float value) throw()
  70958. {
  70959. if (((unsigned int) x) < (unsigned int) size
  70960. && ((unsigned int) y) < (unsigned int) size)
  70961. {
  70962. values[x][y] = value;
  70963. }
  70964. else
  70965. {
  70966. jassertfalse
  70967. }
  70968. }
  70969. void ImageConvolutionKernel::clear() throw()
  70970. {
  70971. for (int y = size; --y >= 0;)
  70972. for (int x = size; --x >= 0;)
  70973. values[x][y] = 0;
  70974. }
  70975. void ImageConvolutionKernel::setOverallSum (const float desiredTotalSum) throw()
  70976. {
  70977. double currentTotal = 0.0;
  70978. for (int y = size; --y >= 0;)
  70979. for (int x = size; --x >= 0;)
  70980. currentTotal += values[x][y];
  70981. rescaleAllValues ((float) (desiredTotalSum / currentTotal));
  70982. }
  70983. void ImageConvolutionKernel::rescaleAllValues (const float multiplier) throw()
  70984. {
  70985. for (int y = size; --y >= 0;)
  70986. for (int x = size; --x >= 0;)
  70987. values[x][y] *= multiplier;
  70988. }
  70989. void ImageConvolutionKernel::createGaussianBlur (const float radius) throw()
  70990. {
  70991. const double radiusFactor = -1.0 / (radius * radius * 2);
  70992. const int centre = size >> 1;
  70993. for (int y = size; --y >= 0;)
  70994. {
  70995. for (int x = size; --x >= 0;)
  70996. {
  70997. const int cx = x - centre;
  70998. const int cy = y - centre;
  70999. values[x][y] = (float) exp (radiusFactor * (cx * cx + cy * cy));
  71000. }
  71001. }
  71002. setOverallSum (1.0f);
  71003. }
  71004. void ImageConvolutionKernel::applyToImage (Image& destImage,
  71005. const Image* sourceImage,
  71006. int dx,
  71007. int dy,
  71008. int dw,
  71009. int dh) const
  71010. {
  71011. Image* imageCreated = 0;
  71012. if (sourceImage == 0)
  71013. {
  71014. sourceImage = imageCreated = destImage.createCopy();
  71015. }
  71016. else
  71017. {
  71018. jassert (sourceImage->getWidth() == destImage.getWidth()
  71019. && sourceImage->getHeight() == destImage.getHeight()
  71020. && sourceImage->getFormat() == destImage.getFormat());
  71021. if (sourceImage->getWidth() != destImage.getWidth()
  71022. || sourceImage->getHeight() != destImage.getHeight()
  71023. || sourceImage->getFormat() != destImage.getFormat())
  71024. return;
  71025. }
  71026. const int imageWidth = destImage.getWidth();
  71027. const int imageHeight = destImage.getHeight();
  71028. if (dx >= imageWidth || dy >= imageHeight)
  71029. return;
  71030. if (dx + dw > imageWidth)
  71031. dw = imageWidth - dx;
  71032. if (dy + dh > imageHeight)
  71033. dh = imageHeight - dy;
  71034. const int dx2 = dx + dw;
  71035. const int dy2 = dy + dh;
  71036. int lineStride, pixelStride;
  71037. uint8* pixels = destImage.lockPixelDataReadWrite (dx, dy, dw, dh, lineStride, pixelStride);
  71038. uint8* line = pixels;
  71039. int srcLineStride, srcPixelStride;
  71040. const uint8* srcPixels = sourceImage->lockPixelDataReadOnly (0, 0, sourceImage->getWidth(), sourceImage->getHeight(), srcLineStride, srcPixelStride);
  71041. if (pixelStride == 4)
  71042. {
  71043. for (int y = dy; y < dy2; ++y)
  71044. {
  71045. uint8* dest = line;
  71046. line += lineStride;
  71047. for (int x = dx; x < dx2; ++x)
  71048. {
  71049. float c1 = 0;
  71050. float c2 = 0;
  71051. float c3 = 0;
  71052. float c4 = 0;
  71053. for (int yy = 0; yy < size; ++yy)
  71054. {
  71055. const int sy = y + yy - (size >> 1);
  71056. if (sy >= imageHeight)
  71057. break;
  71058. if (sy >= 0)
  71059. {
  71060. int sx = x - (size >> 1);
  71061. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  71062. for (int xx = 0; xx < size; ++xx)
  71063. {
  71064. if (sx >= imageWidth)
  71065. break;
  71066. if (sx >= 0)
  71067. {
  71068. const float kernelMult = values[xx][yy];
  71069. c1 += kernelMult * *src++;
  71070. c2 += kernelMult * *src++;
  71071. c3 += kernelMult * *src++;
  71072. c4 += kernelMult * *src++;
  71073. }
  71074. else
  71075. {
  71076. src += 4;
  71077. }
  71078. ++sx;
  71079. }
  71080. }
  71081. }
  71082. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c1));
  71083. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c2));
  71084. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c3));
  71085. *dest++ = (uint8) jmin (0xff, roundFloatToInt (c4));
  71086. }
  71087. }
  71088. }
  71089. else if (pixelStride == 3)
  71090. {
  71091. for (int y = dy; y < dy2; ++y)
  71092. {
  71093. uint8* dest = line;
  71094. line += lineStride;
  71095. for (int x = dx; x < dx2; ++x)
  71096. {
  71097. float c1 = 0;
  71098. float c2 = 0;
  71099. float c3 = 0;
  71100. for (int yy = 0; yy < size; ++yy)
  71101. {
  71102. const int sy = y + yy - (size >> 1);
  71103. if (sy >= imageHeight)
  71104. break;
  71105. if (sy >= 0)
  71106. {
  71107. int sx = x - (size >> 1);
  71108. const uint8* src = srcPixels + srcLineStride * sy + srcPixelStride * sx;
  71109. for (int xx = 0; xx < size; ++xx)
  71110. {
  71111. if (sx >= imageWidth)
  71112. break;
  71113. if (sx >= 0)
  71114. {
  71115. const float kernelMult = values[xx][yy];
  71116. c1 += kernelMult * *src++;
  71117. c2 += kernelMult * *src++;
  71118. c3 += kernelMult * *src++;
  71119. }
  71120. else
  71121. {
  71122. src += 3;
  71123. }
  71124. ++sx;
  71125. }
  71126. }
  71127. }
  71128. *dest++ = (uint8) roundFloatToInt (c1);
  71129. *dest++ = (uint8) roundFloatToInt (c2);
  71130. *dest++ = (uint8) roundFloatToInt (c3);
  71131. }
  71132. }
  71133. }
  71134. sourceImage->releasePixelDataReadOnly (srcPixels);
  71135. destImage.releasePixelDataReadWrite (pixels);
  71136. if (imageCreated != 0)
  71137. delete imageCreated;
  71138. }
  71139. END_JUCE_NAMESPACE
  71140. /********* End of inlined file: juce_ImageConvolutionKernel.cpp *********/
  71141. /********* Start of inlined file: juce_ImageFileFormat.cpp *********/
  71142. BEGIN_JUCE_NAMESPACE
  71143. /********* Start of inlined file: juce_GIFLoader.h *********/
  71144. #ifndef __JUCE_GIFLOADER_JUCEHEADER__
  71145. #define __JUCE_GIFLOADER_JUCEHEADER__
  71146. #ifndef DOXYGEN
  71147. static const int maxGifCode = 1 << 12;
  71148. /**
  71149. Used internally by ImageFileFormat - don't use this class directly in your
  71150. application.
  71151. @see ImageFileFormat
  71152. */
  71153. class GIFLoader
  71154. {
  71155. public:
  71156. GIFLoader (InputStream& in);
  71157. ~GIFLoader() throw();
  71158. Image* getImage() const throw() { return image; }
  71159. private:
  71160. Image* image;
  71161. InputStream& input;
  71162. uint8 buffer [300];
  71163. uint8 palette [256][4];
  71164. bool dataBlockIsZero, fresh, finished;
  71165. int currentBit, lastBit, lastByteIndex;
  71166. int codeSize, setCodeSize;
  71167. int maxCode, maxCodeSize;
  71168. int firstcode, oldcode;
  71169. int clearCode, end_code;
  71170. int table [2] [maxGifCode];
  71171. int stack [2 * maxGifCode];
  71172. int *sp;
  71173. bool getSizeFromHeader (int& width, int& height);
  71174. bool readPalette (const int numCols);
  71175. int readDataBlock (unsigned char* dest);
  71176. int processExtension (int type, int& transparent);
  71177. int readLZWByte (bool initialise, int input_code_size);
  71178. int getCode (int code_size, bool initialise);
  71179. bool readImage (int width, int height,
  71180. int interlace, int transparent);
  71181. GIFLoader (const GIFLoader&);
  71182. const GIFLoader& operator= (const GIFLoader&);
  71183. };
  71184. #endif // DOXYGEN
  71185. #endif // __JUCE_GIFLOADER_JUCEHEADER__
  71186. /********* End of inlined file: juce_GIFLoader.h *********/
  71187. Image* juce_loadPNGImageFromStream (InputStream& inputStream) throw();
  71188. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw();
  71189. PNGImageFormat::PNGImageFormat() throw() {}
  71190. PNGImageFormat::~PNGImageFormat() throw() {}
  71191. const String PNGImageFormat::getFormatName()
  71192. {
  71193. return T("PNG");
  71194. }
  71195. bool PNGImageFormat::canUnderstand (InputStream& in)
  71196. {
  71197. const int bytesNeeded = 4;
  71198. char header [bytesNeeded];
  71199. return in.read (header, bytesNeeded) == bytesNeeded
  71200. && header[1] == 'P'
  71201. && header[2] == 'N'
  71202. && header[3] == 'G';
  71203. }
  71204. Image* PNGImageFormat::decodeImage (InputStream& in)
  71205. {
  71206. return juce_loadPNGImageFromStream (in);
  71207. }
  71208. bool PNGImageFormat::writeImageToStream (const Image& sourceImage,
  71209. OutputStream& destStream)
  71210. {
  71211. return juce_writePNGImageToStream (sourceImage, destStream);
  71212. }
  71213. Image* juce_loadJPEGImageFromStream (InputStream& inputStream) throw();
  71214. bool juce_writeJPEGImageToStream (const Image& image, OutputStream& out, float quality) throw();
  71215. JPEGImageFormat::JPEGImageFormat() throw()
  71216. : quality (-1.0f)
  71217. {
  71218. }
  71219. JPEGImageFormat::~JPEGImageFormat() throw() {}
  71220. void JPEGImageFormat::setQuality (const float newQuality)
  71221. {
  71222. quality = newQuality;
  71223. }
  71224. const String JPEGImageFormat::getFormatName()
  71225. {
  71226. return T("JPEG");
  71227. }
  71228. bool JPEGImageFormat::canUnderstand (InputStream& in)
  71229. {
  71230. const int bytesNeeded = 10;
  71231. uint8 header [bytesNeeded];
  71232. if (in.read (header, bytesNeeded) == bytesNeeded)
  71233. {
  71234. return header[0] == 0xff
  71235. && header[1] == 0xd8
  71236. && header[2] == 0xff
  71237. && (header[3] == 0xe0 || header[3] == 0xe1);
  71238. }
  71239. return false;
  71240. }
  71241. Image* JPEGImageFormat::decodeImage (InputStream& in)
  71242. {
  71243. return juce_loadJPEGImageFromStream (in);
  71244. }
  71245. bool JPEGImageFormat::writeImageToStream (const Image& sourceImage,
  71246. OutputStream& destStream)
  71247. {
  71248. return juce_writeJPEGImageToStream (sourceImage, destStream, quality);
  71249. }
  71250. class GIFImageFormat : public ImageFileFormat
  71251. {
  71252. public:
  71253. GIFImageFormat() throw() {}
  71254. ~GIFImageFormat() throw() {}
  71255. const String getFormatName()
  71256. {
  71257. return T("GIF");
  71258. }
  71259. bool canUnderstand (InputStream& in)
  71260. {
  71261. const int bytesNeeded = 4;
  71262. char header [bytesNeeded];
  71263. return (in.read (header, bytesNeeded) == bytesNeeded)
  71264. && header[0] == 'G'
  71265. && header[1] == 'I'
  71266. && header[2] == 'F';
  71267. }
  71268. Image* decodeImage (InputStream& in)
  71269. {
  71270. GIFLoader* const loader = new GIFLoader (in);
  71271. Image* const im = loader->getImage();
  71272. delete loader;
  71273. return im;
  71274. }
  71275. bool writeImageToStream (const Image& /*sourceImage*/, OutputStream& /*destStream*/)
  71276. {
  71277. return false;
  71278. }
  71279. };
  71280. ImageFileFormat* ImageFileFormat::findImageFormatForStream (InputStream& input)
  71281. {
  71282. static PNGImageFormat png;
  71283. static JPEGImageFormat jpg;
  71284. static GIFImageFormat gif;
  71285. ImageFileFormat* formats[4];
  71286. int numFormats = 0;
  71287. formats [numFormats++] = &png;
  71288. formats [numFormats++] = &jpg;
  71289. formats [numFormats++] = &gif;
  71290. const int64 streamPos = input.getPosition();
  71291. for (int i = 0; i < numFormats; ++i)
  71292. {
  71293. const bool found = formats[i]->canUnderstand (input);
  71294. input.setPosition (streamPos);
  71295. if (found)
  71296. return formats[i];
  71297. }
  71298. return 0;
  71299. }
  71300. Image* ImageFileFormat::loadFrom (InputStream& input)
  71301. {
  71302. ImageFileFormat* const format = findImageFormatForStream (input);
  71303. if (format != 0)
  71304. return format->decodeImage (input);
  71305. return 0;
  71306. }
  71307. Image* ImageFileFormat::loadFrom (const File& file)
  71308. {
  71309. InputStream* const in = file.createInputStream();
  71310. if (in != 0)
  71311. {
  71312. BufferedInputStream b (in, 8192, true);
  71313. return loadFrom (b);
  71314. }
  71315. return 0;
  71316. }
  71317. Image* ImageFileFormat::loadFrom (const void* rawData, const int numBytes)
  71318. {
  71319. if (rawData != 0 && numBytes > 4)
  71320. {
  71321. MemoryInputStream stream (rawData, numBytes, false);
  71322. return loadFrom (stream);
  71323. }
  71324. return 0;
  71325. }
  71326. END_JUCE_NAMESPACE
  71327. /********* End of inlined file: juce_ImageFileFormat.cpp *********/
  71328. /********* Start of inlined file: juce_GIFLoader.cpp *********/
  71329. BEGIN_JUCE_NAMESPACE
  71330. static inline int makeWord (const unsigned char a, const unsigned char b) throw()
  71331. {
  71332. return (b << 8) | a;
  71333. }
  71334. GIFLoader::GIFLoader (InputStream& in)
  71335. : image (0),
  71336. input (in),
  71337. dataBlockIsZero (false),
  71338. fresh (false),
  71339. finished (false)
  71340. {
  71341. currentBit = lastBit = lastByteIndex = 0;
  71342. maxCode = maxCodeSize = codeSize = setCodeSize = 0;
  71343. firstcode = oldcode = 0;
  71344. clearCode = end_code = 0;
  71345. int imageWidth, imageHeight;
  71346. int transparent = -1;
  71347. if (! getSizeFromHeader (imageWidth, imageHeight))
  71348. return;
  71349. if ((imageWidth <= 0) || (imageHeight <= 0))
  71350. return;
  71351. unsigned char buf [16];
  71352. if (in.read (buf, 3) != 3)
  71353. return;
  71354. int numColours = 2 << (buf[0] & 7);
  71355. if ((buf[0] & 0x80) != 0)
  71356. readPalette (numColours);
  71357. for (;;)
  71358. {
  71359. if (input.read (buf, 1) != 1)
  71360. break;
  71361. if (buf[0] == ';')
  71362. break;
  71363. if (buf[0] == '!')
  71364. {
  71365. if (input.read (buf, 1) != 1)
  71366. break;
  71367. if (processExtension (buf[0], transparent) < 0)
  71368. break;
  71369. continue;
  71370. }
  71371. if (buf[0] != ',')
  71372. continue;
  71373. if (input.read (buf, 9) != 9)
  71374. break;
  71375. imageWidth = makeWord (buf[4], buf[5]);
  71376. imageHeight = makeWord (buf[6], buf[7]);
  71377. numColours = 2 << (buf[8] & 7);
  71378. if ((buf[8] & 0x80) != 0)
  71379. if (! readPalette (numColours))
  71380. break;
  71381. image = new Image ((transparent >= 0) ? Image::ARGB : Image::RGB,
  71382. imageWidth, imageHeight, (transparent >= 0));
  71383. readImage (imageWidth, imageHeight,
  71384. (buf[8] & 0x40) != 0,
  71385. transparent);
  71386. break;
  71387. }
  71388. }
  71389. GIFLoader::~GIFLoader() throw()
  71390. {
  71391. }
  71392. bool GIFLoader::getSizeFromHeader (int& w, int& h)
  71393. {
  71394. unsigned char b [8];
  71395. if (input.read (b, 6) == 6)
  71396. {
  71397. if ((strncmp ("GIF87a", (char*) b, 6) == 0)
  71398. || (strncmp ("GIF89a", (char*) b, 6) == 0))
  71399. {
  71400. if (input.read (b, 4) == 4)
  71401. {
  71402. w = makeWord (b[0], b[1]);
  71403. h = makeWord (b[2], b[3]);
  71404. return true;
  71405. }
  71406. }
  71407. }
  71408. return false;
  71409. }
  71410. bool GIFLoader::readPalette (const int numCols)
  71411. {
  71412. unsigned char rgb[4];
  71413. for (int i = 0; i < numCols; ++i)
  71414. {
  71415. input.read (rgb, 3);
  71416. palette [i][0] = rgb[0];
  71417. palette [i][1] = rgb[1];
  71418. palette [i][2] = rgb[2];
  71419. palette [i][3] = 0xff;
  71420. }
  71421. return true;
  71422. }
  71423. int GIFLoader::readDataBlock (unsigned char* const dest)
  71424. {
  71425. unsigned char n;
  71426. if (input.read (&n, 1) == 1)
  71427. {
  71428. dataBlockIsZero = (n == 0);
  71429. if (dataBlockIsZero || (input.read (dest, n) == n))
  71430. return n;
  71431. }
  71432. return -1;
  71433. }
  71434. int GIFLoader::processExtension (const int type, int& transparent)
  71435. {
  71436. unsigned char b [300];
  71437. int n = 0;
  71438. if (type == 0xf9)
  71439. {
  71440. n = readDataBlock (b);
  71441. if (n < 0)
  71442. return 1;
  71443. if ((b[0] & 0x1) != 0)
  71444. transparent = b[3];
  71445. }
  71446. do
  71447. {
  71448. n = readDataBlock (b);
  71449. }
  71450. while (n > 0);
  71451. return n;
  71452. }
  71453. int GIFLoader::getCode (const int codeSize, const bool initialise)
  71454. {
  71455. if (initialise)
  71456. {
  71457. currentBit = 0;
  71458. lastBit = 0;
  71459. finished = false;
  71460. return 0;
  71461. }
  71462. if ((currentBit + codeSize) >= lastBit)
  71463. {
  71464. if (finished)
  71465. return -1;
  71466. buffer[0] = buffer [lastByteIndex - 2];
  71467. buffer[1] = buffer [lastByteIndex - 1];
  71468. const int n = readDataBlock (&buffer[2]);
  71469. if (n == 0)
  71470. finished = true;
  71471. lastByteIndex = 2 + n;
  71472. currentBit = (currentBit - lastBit) + 16;
  71473. lastBit = (2 + n) * 8 ;
  71474. }
  71475. int result = 0;
  71476. int i = currentBit;
  71477. for (int j = 0; j < codeSize; ++j)
  71478. {
  71479. result |= ((buffer[i >> 3] & (1 << (i & 7))) != 0) << j;
  71480. ++i;
  71481. }
  71482. currentBit += codeSize;
  71483. return result;
  71484. }
  71485. int GIFLoader::readLZWByte (const bool initialise, const int inputCodeSize)
  71486. {
  71487. int code, incode, i;
  71488. if (initialise)
  71489. {
  71490. setCodeSize = inputCodeSize;
  71491. codeSize = setCodeSize + 1;
  71492. clearCode = 1 << setCodeSize;
  71493. end_code = clearCode + 1;
  71494. maxCodeSize = 2 * clearCode;
  71495. maxCode = clearCode + 2;
  71496. getCode (0, true);
  71497. fresh = true;
  71498. for (i = 0; i < clearCode; ++i)
  71499. {
  71500. table[0][i] = 0;
  71501. table[1][i] = i;
  71502. }
  71503. for (; i < maxGifCode; ++i)
  71504. {
  71505. table[0][i] = 0;
  71506. table[1][i] = 0;
  71507. }
  71508. sp = stack;
  71509. return 0;
  71510. }
  71511. else if (fresh)
  71512. {
  71513. fresh = false;
  71514. do
  71515. {
  71516. firstcode = oldcode
  71517. = getCode (codeSize, false);
  71518. }
  71519. while (firstcode == clearCode);
  71520. return firstcode;
  71521. }
  71522. if (sp > stack)
  71523. return *--sp;
  71524. while ((code = getCode (codeSize, false)) >= 0)
  71525. {
  71526. if (code == clearCode)
  71527. {
  71528. for (i = 0; i < clearCode; ++i)
  71529. {
  71530. table[0][i] = 0;
  71531. table[1][i] = i;
  71532. }
  71533. for (; i < maxGifCode; ++i)
  71534. {
  71535. table[0][i] = 0;
  71536. table[1][i] = 0;
  71537. }
  71538. codeSize = setCodeSize + 1;
  71539. maxCodeSize = 2 * clearCode;
  71540. maxCode = clearCode + 2;
  71541. sp = stack;
  71542. firstcode = oldcode = getCode (codeSize, false);
  71543. return firstcode;
  71544. }
  71545. else if (code == end_code)
  71546. {
  71547. if (dataBlockIsZero)
  71548. return -2;
  71549. unsigned char buf [260];
  71550. int n;
  71551. while ((n = readDataBlock (buf)) > 0)
  71552. {}
  71553. if (n != 0)
  71554. return -2;
  71555. }
  71556. incode = code;
  71557. if (code >= maxCode)
  71558. {
  71559. *sp++ = firstcode;
  71560. code = oldcode;
  71561. }
  71562. while (code >= clearCode)
  71563. {
  71564. *sp++ = table[1][code];
  71565. if (code == table[0][code])
  71566. return -2;
  71567. code = table[0][code];
  71568. }
  71569. *sp++ = firstcode = table[1][code];
  71570. if ((code = maxCode) < maxGifCode)
  71571. {
  71572. table[0][code] = oldcode;
  71573. table[1][code] = firstcode;
  71574. ++maxCode;
  71575. if ((maxCode >= maxCodeSize)
  71576. && (maxCodeSize < maxGifCode))
  71577. {
  71578. maxCodeSize <<= 1;
  71579. ++codeSize;
  71580. }
  71581. }
  71582. oldcode = incode;
  71583. if (sp > stack)
  71584. return *--sp;
  71585. }
  71586. return code;
  71587. }
  71588. bool GIFLoader::readImage (const int width, const int height,
  71589. const int interlace, const int transparent)
  71590. {
  71591. unsigned char c;
  71592. if (input.read (&c, 1) != 1
  71593. || readLZWByte (true, c) < 0)
  71594. return false;
  71595. if (transparent >= 0)
  71596. {
  71597. palette [transparent][0] = 0;
  71598. palette [transparent][1] = 0;
  71599. palette [transparent][2] = 0;
  71600. palette [transparent][3] = 0;
  71601. }
  71602. int index;
  71603. int xpos = 0, ypos = 0, pass = 0;
  71604. int stride, pixelStride;
  71605. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  71606. uint8* p = pixels;
  71607. const bool hasAlpha = image->hasAlphaChannel();
  71608. while ((index = readLZWByte (false, c)) >= 0)
  71609. {
  71610. const uint8* const paletteEntry = palette [index];
  71611. if (hasAlpha)
  71612. {
  71613. ((PixelARGB*) p)->setARGB (paletteEntry[3],
  71614. paletteEntry[0],
  71615. paletteEntry[1],
  71616. paletteEntry[2]);
  71617. ((PixelARGB*) p)->premultiply();
  71618. p += pixelStride;
  71619. }
  71620. else
  71621. {
  71622. ((PixelRGB*) p)->setARGB (0,
  71623. paletteEntry[0],
  71624. paletteEntry[1],
  71625. paletteEntry[2]);
  71626. p += pixelStride;
  71627. }
  71628. ++xpos;
  71629. if (xpos == width)
  71630. {
  71631. xpos = 0;
  71632. if (interlace)
  71633. {
  71634. switch (pass)
  71635. {
  71636. case 0:
  71637. case 1:
  71638. ypos += 8;
  71639. break;
  71640. case 2:
  71641. ypos += 4;
  71642. break;
  71643. case 3:
  71644. ypos += 2;
  71645. break;
  71646. }
  71647. while (ypos >= height)
  71648. {
  71649. ++pass;
  71650. switch (pass)
  71651. {
  71652. case 1:
  71653. ypos = 4;
  71654. break;
  71655. case 2:
  71656. ypos = 2;
  71657. break;
  71658. case 3:
  71659. ypos = 1;
  71660. break;
  71661. default:
  71662. return true;
  71663. }
  71664. }
  71665. }
  71666. else
  71667. {
  71668. ++ypos;
  71669. }
  71670. p = pixels + xpos * pixelStride + ypos * stride;
  71671. }
  71672. if (ypos >= height)
  71673. break;
  71674. }
  71675. image->releasePixelDataReadWrite (pixels);
  71676. return true;
  71677. }
  71678. END_JUCE_NAMESPACE
  71679. /********* End of inlined file: juce_GIFLoader.cpp *********/
  71680. #endif
  71681. //==============================================================================
  71682. // some files include lots of library code, so leave them to the end to avoid cluttering
  71683. // up the build for the clean files.
  71684. /********* Start of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  71685. namespace zlibNamespace
  71686. {
  71687. #if JUCE_INCLUDE_ZLIB_CODE
  71688. #undef OS_CODE
  71689. #undef fdopen
  71690. /********* Start of inlined file: zlib.h *********/
  71691. #ifndef ZLIB_H
  71692. #define ZLIB_H
  71693. /********* Start of inlined file: zconf.h *********/
  71694. /* @(#) $Id: zconf.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  71695. #ifndef ZCONF_H
  71696. #define ZCONF_H
  71697. // *** Just a few hacks here to make it compile nicely with Juce..
  71698. #define Z_PREFIX 1
  71699. #undef __MACTYPES__
  71700. #ifdef _MSC_VER
  71701. #pragma warning (disable : 4131 4127 4244 4267)
  71702. #endif
  71703. /*
  71704. * If you *really* need a unique prefix for all types and library functions,
  71705. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
  71706. */
  71707. #ifdef Z_PREFIX
  71708. # define deflateInit_ z_deflateInit_
  71709. # define deflate z_deflate
  71710. # define deflateEnd z_deflateEnd
  71711. # define inflateInit_ z_inflateInit_
  71712. # define inflate z_inflate
  71713. # define inflateEnd z_inflateEnd
  71714. # define deflateInit2_ z_deflateInit2_
  71715. # define deflateSetDictionary z_deflateSetDictionary
  71716. # define deflateCopy z_deflateCopy
  71717. # define deflateReset z_deflateReset
  71718. # define deflateParams z_deflateParams
  71719. # define deflateBound z_deflateBound
  71720. # define deflatePrime z_deflatePrime
  71721. # define inflateInit2_ z_inflateInit2_
  71722. # define inflateSetDictionary z_inflateSetDictionary
  71723. # define inflateSync z_inflateSync
  71724. # define inflateSyncPoint z_inflateSyncPoint
  71725. # define inflateCopy z_inflateCopy
  71726. # define inflateReset z_inflateReset
  71727. # define inflateBack z_inflateBack
  71728. # define inflateBackEnd z_inflateBackEnd
  71729. # define compress z_compress
  71730. # define compress2 z_compress2
  71731. # define compressBound z_compressBound
  71732. # define uncompress z_uncompress
  71733. # define adler32 z_adler32
  71734. # define crc32 z_crc32
  71735. # define get_crc_table z_get_crc_table
  71736. # define zError z_zError
  71737. # define alloc_func z_alloc_func
  71738. # define free_func z_free_func
  71739. # define in_func z_in_func
  71740. # define out_func z_out_func
  71741. # define Byte z_Byte
  71742. # define uInt z_uInt
  71743. # define uLong z_uLong
  71744. # define Bytef z_Bytef
  71745. # define charf z_charf
  71746. # define intf z_intf
  71747. # define uIntf z_uIntf
  71748. # define uLongf z_uLongf
  71749. # define voidpf z_voidpf
  71750. # define voidp z_voidp
  71751. #endif
  71752. #if defined(__MSDOS__) && !defined(MSDOS)
  71753. # define MSDOS
  71754. #endif
  71755. #if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
  71756. # define OS2
  71757. #endif
  71758. #if defined(_WINDOWS) && !defined(WINDOWS)
  71759. # define WINDOWS
  71760. #endif
  71761. #if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
  71762. # ifndef WIN32
  71763. # define WIN32
  71764. # endif
  71765. #endif
  71766. #if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
  71767. # if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
  71768. # ifndef SYS16BIT
  71769. # define SYS16BIT
  71770. # endif
  71771. # endif
  71772. #endif
  71773. /*
  71774. * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
  71775. * than 64k bytes at a time (needed on systems with 16-bit int).
  71776. */
  71777. #ifdef SYS16BIT
  71778. # define MAXSEG_64K
  71779. #endif
  71780. #ifdef MSDOS
  71781. # define UNALIGNED_OK
  71782. #endif
  71783. #ifdef __STDC_VERSION__
  71784. # ifndef STDC
  71785. # define STDC
  71786. # endif
  71787. # if __STDC_VERSION__ >= 199901L
  71788. # ifndef STDC99
  71789. # define STDC99
  71790. # endif
  71791. # endif
  71792. #endif
  71793. #if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
  71794. # define STDC
  71795. #endif
  71796. #if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
  71797. # define STDC
  71798. #endif
  71799. #if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
  71800. # define STDC
  71801. #endif
  71802. #if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
  71803. # define STDC
  71804. #endif
  71805. #if defined(__OS400__) && !defined(STDC) /* iSeries (formerly AS/400). */
  71806. # define STDC
  71807. #endif
  71808. #ifndef STDC
  71809. # ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
  71810. # define const /* note: need a more gentle solution here */
  71811. # endif
  71812. #endif
  71813. /* Some Mac compilers merge all .h files incorrectly: */
  71814. #if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
  71815. # define NO_DUMMY_DECL
  71816. #endif
  71817. /* Maximum value for memLevel in deflateInit2 */
  71818. #ifndef MAX_MEM_LEVEL
  71819. # ifdef MAXSEG_64K
  71820. # define MAX_MEM_LEVEL 8
  71821. # else
  71822. # define MAX_MEM_LEVEL 9
  71823. # endif
  71824. #endif
  71825. /* Maximum value for windowBits in deflateInit2 and inflateInit2.
  71826. * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
  71827. * created by gzip. (Files created by minigzip can still be extracted by
  71828. * gzip.)
  71829. */
  71830. #ifndef MAX_WBITS
  71831. # define MAX_WBITS 15 /* 32K LZ77 window */
  71832. #endif
  71833. /* The memory requirements for deflate are (in bytes):
  71834. (1 << (windowBits+2)) + (1 << (memLevel+9))
  71835. that is: 128K for windowBits=15 + 128K for memLevel = 8 (default values)
  71836. plus a few kilobytes for small objects. For example, if you want to reduce
  71837. the default memory requirements from 256K to 128K, compile with
  71838. make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
  71839. Of course this will generally degrade compression (there's no free lunch).
  71840. The memory requirements for inflate are (in bytes) 1 << windowBits
  71841. that is, 32K for windowBits=15 (default value) plus a few kilobytes
  71842. for small objects.
  71843. */
  71844. /* Type declarations */
  71845. #ifndef OF /* function prototypes */
  71846. # ifdef STDC
  71847. # define OF(args) args
  71848. # else
  71849. # define OF(args) ()
  71850. # endif
  71851. #endif
  71852. /* The following definitions for FAR are needed only for MSDOS mixed
  71853. * model programming (small or medium model with some far allocations).
  71854. * This was tested only with MSC; for other MSDOS compilers you may have
  71855. * to define NO_MEMCPY in zutil.h. If you don't need the mixed model,
  71856. * just define FAR to be empty.
  71857. */
  71858. #ifdef SYS16BIT
  71859. # if defined(M_I86SM) || defined(M_I86MM)
  71860. /* MSC small or medium model */
  71861. # define SMALL_MEDIUM
  71862. # ifdef _MSC_VER
  71863. # define FAR _far
  71864. # else
  71865. # define FAR far
  71866. # endif
  71867. # endif
  71868. # if (defined(__SMALL__) || defined(__MEDIUM__))
  71869. /* Turbo C small or medium model */
  71870. # define SMALL_MEDIUM
  71871. # ifdef __BORLANDC__
  71872. # define FAR _far
  71873. # else
  71874. # define FAR far
  71875. # endif
  71876. # endif
  71877. #endif
  71878. #if defined(WINDOWS) || defined(WIN32)
  71879. /* If building or using zlib as a DLL, define ZLIB_DLL.
  71880. * This is not mandatory, but it offers a little performance increase.
  71881. */
  71882. # ifdef ZLIB_DLL
  71883. # if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
  71884. # ifdef ZLIB_INTERNAL
  71885. # define ZEXTERN extern __declspec(dllexport)
  71886. # else
  71887. # define ZEXTERN extern __declspec(dllimport)
  71888. # endif
  71889. # endif
  71890. # endif /* ZLIB_DLL */
  71891. /* If building or using zlib with the WINAPI/WINAPIV calling convention,
  71892. * define ZLIB_WINAPI.
  71893. * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
  71894. */
  71895. # ifdef ZLIB_WINAPI
  71896. # ifdef FAR
  71897. # undef FAR
  71898. # endif
  71899. # include <windows.h>
  71900. /* No need for _export, use ZLIB.DEF instead. */
  71901. /* For complete Windows compatibility, use WINAPI, not __stdcall. */
  71902. # define ZEXPORT WINAPI
  71903. # ifdef WIN32
  71904. # define ZEXPORTVA WINAPIV
  71905. # else
  71906. # define ZEXPORTVA FAR CDECL
  71907. # endif
  71908. # endif
  71909. #endif
  71910. #if defined (__BEOS__)
  71911. # ifdef ZLIB_DLL
  71912. # ifdef ZLIB_INTERNAL
  71913. # define ZEXPORT __declspec(dllexport)
  71914. # define ZEXPORTVA __declspec(dllexport)
  71915. # else
  71916. # define ZEXPORT __declspec(dllimport)
  71917. # define ZEXPORTVA __declspec(dllimport)
  71918. # endif
  71919. # endif
  71920. #endif
  71921. #ifndef ZEXTERN
  71922. # define ZEXTERN extern
  71923. #endif
  71924. #ifndef ZEXPORT
  71925. # define ZEXPORT
  71926. #endif
  71927. #ifndef ZEXPORTVA
  71928. # define ZEXPORTVA
  71929. #endif
  71930. #ifndef FAR
  71931. # define FAR
  71932. #endif
  71933. #if !defined(__MACTYPES__)
  71934. typedef unsigned char Byte; /* 8 bits */
  71935. #endif
  71936. typedef unsigned int uInt; /* 16 bits or more */
  71937. typedef unsigned long uLong; /* 32 bits or more */
  71938. #ifdef SMALL_MEDIUM
  71939. /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
  71940. # define Bytef Byte FAR
  71941. #else
  71942. typedef Byte FAR Bytef;
  71943. #endif
  71944. typedef char FAR charf;
  71945. typedef int FAR intf;
  71946. typedef uInt FAR uIntf;
  71947. typedef uLong FAR uLongf;
  71948. #ifdef STDC
  71949. typedef void const *voidpc;
  71950. typedef void FAR *voidpf;
  71951. typedef void *voidp;
  71952. #else
  71953. typedef Byte const *voidpc;
  71954. typedef Byte FAR *voidpf;
  71955. typedef Byte *voidp;
  71956. #endif
  71957. #if 0 /* HAVE_UNISTD_H -- this line is updated by ./configure */
  71958. # include <sys/types.h> /* for off_t */
  71959. # include <unistd.h> /* for SEEK_* and off_t */
  71960. # ifdef VMS
  71961. # include <unixio.h> /* for off_t */
  71962. # endif
  71963. # define z_off_t off_t
  71964. #endif
  71965. #ifndef SEEK_SET
  71966. # define SEEK_SET 0 /* Seek from beginning of file. */
  71967. # define SEEK_CUR 1 /* Seek from current position. */
  71968. # define SEEK_END 2 /* Set file pointer to EOF plus "offset" */
  71969. #endif
  71970. #ifndef z_off_t
  71971. # define z_off_t long
  71972. #endif
  71973. #if defined(__OS400__)
  71974. # define NO_vsnprintf
  71975. #endif
  71976. #if defined(__MVS__)
  71977. # define NO_vsnprintf
  71978. # ifdef FAR
  71979. # undef FAR
  71980. # endif
  71981. #endif
  71982. /* MVS linker does not support external names larger than 8 bytes */
  71983. #if defined(__MVS__)
  71984. # pragma map(deflateInit_,"DEIN")
  71985. # pragma map(deflateInit2_,"DEIN2")
  71986. # pragma map(deflateEnd,"DEEND")
  71987. # pragma map(deflateBound,"DEBND")
  71988. # pragma map(inflateInit_,"ININ")
  71989. # pragma map(inflateInit2_,"ININ2")
  71990. # pragma map(inflateEnd,"INEND")
  71991. # pragma map(inflateSync,"INSY")
  71992. # pragma map(inflateSetDictionary,"INSEDI")
  71993. # pragma map(compressBound,"CMBND")
  71994. # pragma map(inflate_table,"INTABL")
  71995. # pragma map(inflate_fast,"INFA")
  71996. # pragma map(inflate_copyright,"INCOPY")
  71997. #endif
  71998. #endif /* ZCONF_H */
  71999. /********* End of inlined file: zconf.h *********/
  72000. #ifdef __cplusplus
  72001. extern "C" {
  72002. #endif
  72003. #define ZLIB_VERSION "1.2.3"
  72004. #define ZLIB_VERNUM 0x1230
  72005. /*
  72006. The 'zlib' compression library provides in-memory compression and
  72007. decompression functions, including integrity checks of the uncompressed
  72008. data. This version of the library supports only one compression method
  72009. (deflation) but other algorithms will be added later and will have the same
  72010. stream interface.
  72011. Compression can be done in a single step if the buffers are large
  72012. enough (for example if an input file is mmap'ed), or can be done by
  72013. repeated calls of the compression function. In the latter case, the
  72014. application must provide more input and/or consume the output
  72015. (providing more output space) before each call.
  72016. The compressed data format used by default by the in-memory functions is
  72017. the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
  72018. around a deflate stream, which is itself documented in RFC 1951.
  72019. The library also supports reading and writing files in gzip (.gz) format
  72020. with an interface similar to that of stdio using the functions that start
  72021. with "gz". The gzip format is different from the zlib format. gzip is a
  72022. gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
  72023. This library can optionally read and write gzip streams in memory as well.
  72024. The zlib format was designed to be compact and fast for use in memory
  72025. and on communications channels. The gzip format was designed for single-
  72026. file compression on file systems, has a larger header than zlib to maintain
  72027. directory information, and uses a different, slower check method than zlib.
  72028. The library does not install any signal handler. The decoder checks
  72029. the consistency of the compressed data, so the library should never
  72030. crash even in case of corrupted input.
  72031. */
  72032. typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
  72033. typedef void (*free_func) OF((voidpf opaque, voidpf address));
  72034. struct internal_state;
  72035. typedef struct z_stream_s {
  72036. Bytef *next_in; /* next input byte */
  72037. uInt avail_in; /* number of bytes available at next_in */
  72038. uLong total_in; /* total nb of input bytes read so far */
  72039. Bytef *next_out; /* next output byte should be put there */
  72040. uInt avail_out; /* remaining free space at next_out */
  72041. uLong total_out; /* total nb of bytes output so far */
  72042. char *msg; /* last error message, NULL if no error */
  72043. struct internal_state FAR *state; /* not visible by applications */
  72044. alloc_func zalloc; /* used to allocate the internal state */
  72045. free_func zfree; /* used to free the internal state */
  72046. voidpf opaque; /* private data object passed to zalloc and zfree */
  72047. int data_type; /* best guess about the data type: binary or text */
  72048. uLong adler; /* adler32 value of the uncompressed data */
  72049. uLong reserved; /* reserved for future use */
  72050. } z_stream;
  72051. typedef z_stream FAR *z_streamp;
  72052. /*
  72053. gzip header information passed to and from zlib routines. See RFC 1952
  72054. for more details on the meanings of these fields.
  72055. */
  72056. typedef struct gz_header_s {
  72057. int text; /* true if compressed data believed to be text */
  72058. uLong time; /* modification time */
  72059. int xflags; /* extra flags (not used when writing a gzip file) */
  72060. int os; /* operating system */
  72061. Bytef *extra; /* pointer to extra field or Z_NULL if none */
  72062. uInt extra_len; /* extra field length (valid if extra != Z_NULL) */
  72063. uInt extra_max; /* space at extra (only when reading header) */
  72064. Bytef *name; /* pointer to zero-terminated file name or Z_NULL */
  72065. uInt name_max; /* space at name (only when reading header) */
  72066. Bytef *comment; /* pointer to zero-terminated comment or Z_NULL */
  72067. uInt comm_max; /* space at comment (only when reading header) */
  72068. int hcrc; /* true if there was or will be a header crc */
  72069. int done; /* true when done reading gzip header (not used
  72070. when writing a gzip file) */
  72071. } gz_header;
  72072. typedef gz_header FAR *gz_headerp;
  72073. /*
  72074. The application must update next_in and avail_in when avail_in has
  72075. dropped to zero. It must update next_out and avail_out when avail_out
  72076. has dropped to zero. The application must initialize zalloc, zfree and
  72077. opaque before calling the init function. All other fields are set by the
  72078. compression library and must not be updated by the application.
  72079. The opaque value provided by the application will be passed as the first
  72080. parameter for calls of zalloc and zfree. This can be useful for custom
  72081. memory management. The compression library attaches no meaning to the
  72082. opaque value.
  72083. zalloc must return Z_NULL if there is not enough memory for the object.
  72084. If zlib is used in a multi-threaded application, zalloc and zfree must be
  72085. thread safe.
  72086. On 16-bit systems, the functions zalloc and zfree must be able to allocate
  72087. exactly 65536 bytes, but will not be required to allocate more than this
  72088. if the symbol MAXSEG_64K is defined (see zconf.h). WARNING: On MSDOS,
  72089. pointers returned by zalloc for objects of exactly 65536 bytes *must*
  72090. have their offset normalized to zero. The default allocation function
  72091. provided by this library ensures this (see zutil.c). To reduce memory
  72092. requirements and avoid any allocation of 64K objects, at the expense of
  72093. compression ratio, compile the library with -DMAX_WBITS=14 (see zconf.h).
  72094. The fields total_in and total_out can be used for statistics or
  72095. progress reports. After compression, total_in holds the total size of
  72096. the uncompressed data and may be saved for use in the decompressor
  72097. (particularly if the decompressor wants to decompress everything in
  72098. a single step).
  72099. */
  72100. /* constants */
  72101. #define Z_NO_FLUSH 0
  72102. #define Z_PARTIAL_FLUSH 1 /* will be removed, use Z_SYNC_FLUSH instead */
  72103. #define Z_SYNC_FLUSH 2
  72104. #define Z_FULL_FLUSH 3
  72105. #define Z_FINISH 4
  72106. #define Z_BLOCK 5
  72107. /* Allowed flush values; see deflate() and inflate() below for details */
  72108. #define Z_OK 0
  72109. #define Z_STREAM_END 1
  72110. #define Z_NEED_DICT 2
  72111. #define Z_ERRNO (-1)
  72112. #define Z_STREAM_ERROR (-2)
  72113. #define Z_DATA_ERROR (-3)
  72114. #define Z_MEM_ERROR (-4)
  72115. #define Z_BUF_ERROR (-5)
  72116. #define Z_VERSION_ERROR (-6)
  72117. /* Return codes for the compression/decompression functions. Negative
  72118. * values are errors, positive values are used for special but normal events.
  72119. */
  72120. #define Z_NO_COMPRESSION 0
  72121. #define Z_BEST_SPEED 1
  72122. #define Z_BEST_COMPRESSION 9
  72123. #define Z_DEFAULT_COMPRESSION (-1)
  72124. /* compression levels */
  72125. #define Z_FILTERED 1
  72126. #define Z_HUFFMAN_ONLY 2
  72127. #define Z_RLE 3
  72128. #define Z_FIXED 4
  72129. #define Z_DEFAULT_STRATEGY 0
  72130. /* compression strategy; see deflateInit2() below for details */
  72131. #define Z_BINARY 0
  72132. #define Z_TEXT 1
  72133. #define Z_ASCII Z_TEXT /* for compatibility with 1.2.2 and earlier */
  72134. #define Z_UNKNOWN 2
  72135. /* Possible values of the data_type field (though see inflate()) */
  72136. #define Z_DEFLATED 8
  72137. /* The deflate compression method (the only one supported in this version) */
  72138. #define Z_NULL 0 /* for initializing zalloc, zfree, opaque */
  72139. #define zlib_version zlibVersion()
  72140. /* for compatibility with versions < 1.0.2 */
  72141. /* basic functions */
  72142. //ZEXTERN const char * ZEXPORT zlibVersion OF((void));
  72143. /* The application can compare zlibVersion and ZLIB_VERSION for consistency.
  72144. If the first character differs, the library code actually used is
  72145. not compatible with the zlib.h header file used by the application.
  72146. This check is automatically made by deflateInit and inflateInit.
  72147. */
  72148. /*
  72149. ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
  72150. Initializes the internal stream state for compression. The fields
  72151. zalloc, zfree and opaque must be initialized before by the caller.
  72152. If zalloc and zfree are set to Z_NULL, deflateInit updates them to
  72153. use default allocation functions.
  72154. The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
  72155. 1 gives best speed, 9 gives best compression, 0 gives no compression at
  72156. all (the input data is simply copied a block at a time).
  72157. Z_DEFAULT_COMPRESSION requests a default compromise between speed and
  72158. compression (currently equivalent to level 6).
  72159. deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not
  72160. enough memory, Z_STREAM_ERROR if level is not a valid compression level,
  72161. Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
  72162. with the version assumed by the caller (ZLIB_VERSION).
  72163. msg is set to null if there is no error message. deflateInit does not
  72164. perform any compression: this will be done by deflate().
  72165. */
  72166. ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
  72167. /*
  72168. deflate compresses as much data as possible, and stops when the input
  72169. buffer becomes empty or the output buffer becomes full. It may introduce some
  72170. output latency (reading input without producing any output) except when
  72171. forced to flush.
  72172. The detailed semantics are as follows. deflate performs one or both of the
  72173. following actions:
  72174. - Compress more input starting at next_in and update next_in and avail_in
  72175. accordingly. If not all input can be processed (because there is not
  72176. enough room in the output buffer), next_in and avail_in are updated and
  72177. processing will resume at this point for the next call of deflate().
  72178. - Provide more output starting at next_out and update next_out and avail_out
  72179. accordingly. This action is forced if the parameter flush is non zero.
  72180. Forcing flush frequently degrades the compression ratio, so this parameter
  72181. should be set only when necessary (in interactive applications).
  72182. Some output may be provided even if flush is not set.
  72183. Before the call of deflate(), the application should ensure that at least
  72184. one of the actions is possible, by providing more input and/or consuming
  72185. more output, and updating avail_in or avail_out accordingly; avail_out
  72186. should never be zero before the call. The application can consume the
  72187. compressed output when it wants, for example when the output buffer is full
  72188. (avail_out == 0), or after each call of deflate(). If deflate returns Z_OK
  72189. and with zero avail_out, it must be called again after making room in the
  72190. output buffer because there might be more output pending.
  72191. Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
  72192. decide how much data to accumualte before producing output, in order to
  72193. maximize compression.
  72194. If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
  72195. flushed to the output buffer and the output is aligned on a byte boundary, so
  72196. that the decompressor can get all input data available so far. (In particular
  72197. avail_in is zero after the call if enough output space has been provided
  72198. before the call.) Flushing may degrade compression for some compression
  72199. algorithms and so it should be used only when necessary.
  72200. If flush is set to Z_FULL_FLUSH, all output is flushed as with
  72201. Z_SYNC_FLUSH, and the compression state is reset so that decompression can
  72202. restart from this point if previous compressed data has been damaged or if
  72203. random access is desired. Using Z_FULL_FLUSH too often can seriously degrade
  72204. compression.
  72205. If deflate returns with avail_out == 0, this function must be called again
  72206. with the same value of the flush parameter and more output space (updated
  72207. avail_out), until the flush is complete (deflate returns with non-zero
  72208. avail_out). In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
  72209. avail_out is greater than six to avoid repeated flush markers due to
  72210. avail_out == 0 on return.
  72211. If the parameter flush is set to Z_FINISH, pending input is processed,
  72212. pending output is flushed and deflate returns with Z_STREAM_END if there
  72213. was enough output space; if deflate returns with Z_OK, this function must be
  72214. called again with Z_FINISH and more output space (updated avail_out) but no
  72215. more input data, until it returns with Z_STREAM_END or an error. After
  72216. deflate has returned Z_STREAM_END, the only possible operations on the
  72217. stream are deflateReset or deflateEnd.
  72218. Z_FINISH can be used immediately after deflateInit if all the compression
  72219. is to be done in a single step. In this case, avail_out must be at least
  72220. the value returned by deflateBound (see below). If deflate does not return
  72221. Z_STREAM_END, then it must be called again as described above.
  72222. deflate() sets strm->adler to the adler32 checksum of all input read
  72223. so far (that is, total_in bytes).
  72224. deflate() may update strm->data_type if it can make a good guess about
  72225. the input data type (Z_BINARY or Z_TEXT). In doubt, the data is considered
  72226. binary. This field is only for information purposes and does not affect
  72227. the compression algorithm in any manner.
  72228. deflate() returns Z_OK if some progress has been made (more input
  72229. processed or more output produced), Z_STREAM_END if all input has been
  72230. consumed and all output has been produced (only when flush is set to
  72231. Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
  72232. if next_in or next_out was NULL), Z_BUF_ERROR if no progress is possible
  72233. (for example avail_in or avail_out was zero). Note that Z_BUF_ERROR is not
  72234. fatal, and deflate() can be called again with more input and more output
  72235. space to continue compressing.
  72236. */
  72237. ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
  72238. /*
  72239. All dynamically allocated data structures for this stream are freed.
  72240. This function discards any unprocessed input and does not flush any
  72241. pending output.
  72242. deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
  72243. stream state was inconsistent, Z_DATA_ERROR if the stream was freed
  72244. prematurely (some input or output was discarded). In the error case,
  72245. msg may be set but then points to a static string (which must not be
  72246. deallocated).
  72247. */
  72248. /*
  72249. ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
  72250. Initializes the internal stream state for decompression. The fields
  72251. next_in, avail_in, zalloc, zfree and opaque must be initialized before by
  72252. the caller. If next_in is not Z_NULL and avail_in is large enough (the exact
  72253. value depends on the compression method), inflateInit determines the
  72254. compression method from the zlib header and allocates all data structures
  72255. accordingly; otherwise the allocation will be deferred to the first call of
  72256. inflate. If zalloc and zfree are set to Z_NULL, inflateInit updates them to
  72257. use default allocation functions.
  72258. inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72259. memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
  72260. version assumed by the caller. msg is set to null if there is no error
  72261. message. inflateInit does not perform any decompression apart from reading
  72262. the zlib header if present: this will be done by inflate(). (So next_in and
  72263. avail_in may be modified, but next_out and avail_out are unchanged.)
  72264. */
  72265. ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
  72266. /*
  72267. inflate decompresses as much data as possible, and stops when the input
  72268. buffer becomes empty or the output buffer becomes full. It may introduce
  72269. some output latency (reading input without producing any output) except when
  72270. forced to flush.
  72271. The detailed semantics are as follows. inflate performs one or both of the
  72272. following actions:
  72273. - Decompress more input starting at next_in and update next_in and avail_in
  72274. accordingly. If not all input can be processed (because there is not
  72275. enough room in the output buffer), next_in is updated and processing
  72276. will resume at this point for the next call of inflate().
  72277. - Provide more output starting at next_out and update next_out and avail_out
  72278. accordingly. inflate() provides as much output as possible, until there
  72279. is no more input data or no more space in the output buffer (see below
  72280. about the flush parameter).
  72281. Before the call of inflate(), the application should ensure that at least
  72282. one of the actions is possible, by providing more input and/or consuming
  72283. more output, and updating the next_* and avail_* values accordingly.
  72284. The application can consume the uncompressed output when it wants, for
  72285. example when the output buffer is full (avail_out == 0), or after each
  72286. call of inflate(). If inflate returns Z_OK and with zero avail_out, it
  72287. must be called again after making room in the output buffer because there
  72288. might be more output pending.
  72289. The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH,
  72290. Z_FINISH, or Z_BLOCK. Z_SYNC_FLUSH requests that inflate() flush as much
  72291. output as possible to the output buffer. Z_BLOCK requests that inflate() stop
  72292. if and when it gets to the next deflate block boundary. When decoding the
  72293. zlib or gzip format, this will cause inflate() to return immediately after
  72294. the header and before the first block. When doing a raw inflate, inflate()
  72295. will go ahead and process the first block, and will return when it gets to
  72296. the end of that block, or when it runs out of data.
  72297. The Z_BLOCK option assists in appending to or combining deflate streams.
  72298. Also to assist in this, on return inflate() will set strm->data_type to the
  72299. number of unused bits in the last byte taken from strm->next_in, plus 64
  72300. if inflate() is currently decoding the last block in the deflate stream,
  72301. plus 128 if inflate() returned immediately after decoding an end-of-block
  72302. code or decoding the complete header up to just before the first byte of the
  72303. deflate stream. The end-of-block will not be indicated until all of the
  72304. uncompressed data from that block has been written to strm->next_out. The
  72305. number of unused bits may in general be greater than seven, except when
  72306. bit 7 of data_type is set, in which case the number of unused bits will be
  72307. less than eight.
  72308. inflate() should normally be called until it returns Z_STREAM_END or an
  72309. error. However if all decompression is to be performed in a single step
  72310. (a single call of inflate), the parameter flush should be set to
  72311. Z_FINISH. In this case all pending input is processed and all pending
  72312. output is flushed; avail_out must be large enough to hold all the
  72313. uncompressed data. (The size of the uncompressed data may have been saved
  72314. by the compressor for this purpose.) The next operation on this stream must
  72315. be inflateEnd to deallocate the decompression state. The use of Z_FINISH
  72316. is never required, but can be used to inform inflate that a faster approach
  72317. may be used for the single inflate() call.
  72318. In this implementation, inflate() always flushes as much output as
  72319. possible to the output buffer, and always uses the faster approach on the
  72320. first call. So the only effect of the flush parameter in this implementation
  72321. is on the return value of inflate(), as noted below, or when it returns early
  72322. because Z_BLOCK is used.
  72323. If a preset dictionary is needed after this call (see inflateSetDictionary
  72324. below), inflate sets strm->adler to the adler32 checksum of the dictionary
  72325. chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
  72326. strm->adler to the adler32 checksum of all output produced so far (that is,
  72327. total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
  72328. below. At the end of the stream, inflate() checks that its computed adler32
  72329. checksum is equal to that saved by the compressor and returns Z_STREAM_END
  72330. only if the checksum is correct.
  72331. inflate() will decompress and check either zlib-wrapped or gzip-wrapped
  72332. deflate data. The header type is detected automatically. Any information
  72333. contained in the gzip header is not retained, so applications that need that
  72334. information should instead use raw inflate, see inflateInit2() below, or
  72335. inflateBack() and perform their own processing of the gzip header and
  72336. trailer.
  72337. inflate() returns Z_OK if some progress has been made (more input processed
  72338. or more output produced), Z_STREAM_END if the end of the compressed data has
  72339. been reached and all uncompressed output has been produced, Z_NEED_DICT if a
  72340. preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
  72341. corrupted (input stream not conforming to the zlib format or incorrect check
  72342. value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
  72343. if next_in or next_out was NULL), Z_MEM_ERROR if there was not enough memory,
  72344. Z_BUF_ERROR if no progress is possible or if there was not enough room in the
  72345. output buffer when Z_FINISH is used. Note that Z_BUF_ERROR is not fatal, and
  72346. inflate() can be called again with more input and more output space to
  72347. continue decompressing. If Z_DATA_ERROR is returned, the application may then
  72348. call inflateSync() to look for a good compression block if a partial recovery
  72349. of the data is desired.
  72350. */
  72351. ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
  72352. /*
  72353. All dynamically allocated data structures for this stream are freed.
  72354. This function discards any unprocessed input and does not flush any
  72355. pending output.
  72356. inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
  72357. was inconsistent. In the error case, msg may be set but then points to a
  72358. static string (which must not be deallocated).
  72359. */
  72360. /* Advanced functions */
  72361. /*
  72362. The following functions are needed only in some special applications.
  72363. */
  72364. /*
  72365. ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
  72366. int level,
  72367. int method,
  72368. int windowBits,
  72369. int memLevel,
  72370. int strategy));
  72371. This is another version of deflateInit with more compression options. The
  72372. fields next_in, zalloc, zfree and opaque must be initialized before by
  72373. the caller.
  72374. The method parameter is the compression method. It must be Z_DEFLATED in
  72375. this version of the library.
  72376. The windowBits parameter is the base two logarithm of the window size
  72377. (the size of the history buffer). It should be in the range 8..15 for this
  72378. version of the library. Larger values of this parameter result in better
  72379. compression at the expense of memory usage. The default value is 15 if
  72380. deflateInit is used instead.
  72381. windowBits can also be -8..-15 for raw deflate. In this case, -windowBits
  72382. determines the window size. deflate() will then generate raw deflate data
  72383. with no zlib header or trailer, and will not compute an adler32 check value.
  72384. windowBits can also be greater than 15 for optional gzip encoding. Add
  72385. 16 to windowBits to write a simple gzip header and trailer around the
  72386. compressed data instead of a zlib wrapper. The gzip header will have no
  72387. file name, no extra data, no comment, no modification time (set to zero),
  72388. no header crc, and the operating system will be set to 255 (unknown). If a
  72389. gzip stream is being written, strm->adler is a crc32 instead of an adler32.
  72390. The memLevel parameter specifies how much memory should be allocated
  72391. for the internal compression state. memLevel=1 uses minimum memory but
  72392. is slow and reduces compression ratio; memLevel=9 uses maximum memory
  72393. for optimal speed. The default value is 8. See zconf.h for total memory
  72394. usage as a function of windowBits and memLevel.
  72395. The strategy parameter is used to tune the compression algorithm. Use the
  72396. value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
  72397. filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
  72398. string match), or Z_RLE to limit match distances to one (run-length
  72399. encoding). Filtered data consists mostly of small values with a somewhat
  72400. random distribution. In this case, the compression algorithm is tuned to
  72401. compress them better. The effect of Z_FILTERED is to force more Huffman
  72402. coding and less string matching; it is somewhat intermediate between
  72403. Z_DEFAULT and Z_HUFFMAN_ONLY. Z_RLE is designed to be almost as fast as
  72404. Z_HUFFMAN_ONLY, but give better compression for PNG image data. The strategy
  72405. parameter only affects the compression ratio but not the correctness of the
  72406. compressed output even if it is not set appropriately. Z_FIXED prevents the
  72407. use of dynamic Huffman codes, allowing for a simpler decoder for special
  72408. applications.
  72409. deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72410. memory, Z_STREAM_ERROR if a parameter is invalid (such as an invalid
  72411. method). msg is set to null if there is no error message. deflateInit2 does
  72412. not perform any compression: this will be done by deflate().
  72413. */
  72414. ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
  72415. const Bytef *dictionary,
  72416. uInt dictLength));
  72417. /*
  72418. Initializes the compression dictionary from the given byte sequence
  72419. without producing any compressed output. This function must be called
  72420. immediately after deflateInit, deflateInit2 or deflateReset, before any
  72421. call of deflate. The compressor and decompressor must use exactly the same
  72422. dictionary (see inflateSetDictionary).
  72423. The dictionary should consist of strings (byte sequences) that are likely
  72424. to be encountered later in the data to be compressed, with the most commonly
  72425. used strings preferably put towards the end of the dictionary. Using a
  72426. dictionary is most useful when the data to be compressed is short and can be
  72427. predicted with good accuracy; the data can then be compressed better than
  72428. with the default empty dictionary.
  72429. Depending on the size of the compression data structures selected by
  72430. deflateInit or deflateInit2, a part of the dictionary may in effect be
  72431. discarded, for example if the dictionary is larger than the window size in
  72432. deflate or deflate2. Thus the strings most likely to be useful should be
  72433. put at the end of the dictionary, not at the front. In addition, the
  72434. current implementation of deflate will use at most the window size minus
  72435. 262 bytes of the provided dictionary.
  72436. Upon return of this function, strm->adler is set to the adler32 value
  72437. of the dictionary; the decompressor may later use this value to determine
  72438. which dictionary has been used by the compressor. (The adler32 value
  72439. applies to the whole dictionary even if only a subset of the dictionary is
  72440. actually used by the compressor.) If a raw deflate was requested, then the
  72441. adler32 value is not computed and strm->adler is not set.
  72442. deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
  72443. parameter is invalid (such as NULL dictionary) or the stream state is
  72444. inconsistent (for example if deflate has already been called for this stream
  72445. or if the compression method is bsort). deflateSetDictionary does not
  72446. perform any compression: this will be done by deflate().
  72447. */
  72448. ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
  72449. z_streamp source));
  72450. /*
  72451. Sets the destination stream as a complete copy of the source stream.
  72452. This function can be useful when several compression strategies will be
  72453. tried, for example when there are several ways of pre-processing the input
  72454. data with a filter. The streams that will be discarded should then be freed
  72455. by calling deflateEnd. Note that deflateCopy duplicates the internal
  72456. compression state which can be quite large, so this strategy is slow and
  72457. can consume lots of memory.
  72458. deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  72459. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  72460. (such as zalloc being NULL). msg is left unchanged in both source and
  72461. destination.
  72462. */
  72463. ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
  72464. /*
  72465. This function is equivalent to deflateEnd followed by deflateInit,
  72466. but does not free and reallocate all the internal compression state.
  72467. The stream will keep the same compression level and any other attributes
  72468. that may have been set by deflateInit2.
  72469. deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  72470. stream state was inconsistent (such as zalloc or state being NULL).
  72471. */
  72472. ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
  72473. int level,
  72474. int strategy));
  72475. /*
  72476. Dynamically update the compression level and compression strategy. The
  72477. interpretation of level and strategy is as in deflateInit2. This can be
  72478. used to switch between compression and straight copy of the input data, or
  72479. to switch to a different kind of input data requiring a different
  72480. strategy. If the compression level is changed, the input available so far
  72481. is compressed with the old level (and may be flushed); the new level will
  72482. take effect only at the next call of deflate().
  72483. Before the call of deflateParams, the stream state must be set as for
  72484. a call of deflate(), since the currently available input may have to
  72485. be compressed and flushed. In particular, strm->avail_out must be non-zero.
  72486. deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
  72487. stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR
  72488. if strm->avail_out was zero.
  72489. */
  72490. ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
  72491. int good_length,
  72492. int max_lazy,
  72493. int nice_length,
  72494. int max_chain));
  72495. /*
  72496. Fine tune deflate's internal compression parameters. This should only be
  72497. used by someone who understands the algorithm used by zlib's deflate for
  72498. searching for the best matching string, and even then only by the most
  72499. fanatic optimizer trying to squeeze out the last compressed bit for their
  72500. specific input data. Read the deflate.c source code for the meaning of the
  72501. max_lazy, good_length, nice_length, and max_chain parameters.
  72502. deflateTune() can be called after deflateInit() or deflateInit2(), and
  72503. returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
  72504. */
  72505. ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
  72506. uLong sourceLen));
  72507. /*
  72508. deflateBound() returns an upper bound on the compressed size after
  72509. deflation of sourceLen bytes. It must be called after deflateInit()
  72510. or deflateInit2(). This would be used to allocate an output buffer
  72511. for deflation in a single pass, and so would be called before deflate().
  72512. */
  72513. ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
  72514. int bits,
  72515. int value));
  72516. /*
  72517. deflatePrime() inserts bits in the deflate output stream. The intent
  72518. is that this function is used to start off the deflate output with the
  72519. bits leftover from a previous deflate stream when appending to it. As such,
  72520. this function can only be used for raw deflate, and must be used before the
  72521. first deflate() call after a deflateInit2() or deflateReset(). bits must be
  72522. less than or equal to 16, and that many of the least significant bits of
  72523. value will be inserted in the output.
  72524. deflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  72525. stream state was inconsistent.
  72526. */
  72527. ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
  72528. gz_headerp head));
  72529. /*
  72530. deflateSetHeader() provides gzip header information for when a gzip
  72531. stream is requested by deflateInit2(). deflateSetHeader() may be called
  72532. after deflateInit2() or deflateReset() and before the first call of
  72533. deflate(). The text, time, os, extra field, name, and comment information
  72534. in the provided gz_header structure are written to the gzip header (xflag is
  72535. ignored -- the extra flags are set according to the compression level). The
  72536. caller must assure that, if not Z_NULL, name and comment are terminated with
  72537. a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
  72538. available there. If hcrc is true, a gzip header crc is included. Note that
  72539. the current versions of the command-line version of gzip (up through version
  72540. 1.3.x) do not support header crc's, and will report that it is a "multi-part
  72541. gzip file" and give up.
  72542. If deflateSetHeader is not used, the default gzip header has text false,
  72543. the time set to zero, and os set to 255, with no extra, name, or comment
  72544. fields. The gzip header is returned to the default state by deflateReset().
  72545. deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  72546. stream state was inconsistent.
  72547. */
  72548. /*
  72549. ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
  72550. int windowBits));
  72551. This is another version of inflateInit with an extra parameter. The
  72552. fields next_in, avail_in, zalloc, zfree and opaque must be initialized
  72553. before by the caller.
  72554. The windowBits parameter is the base two logarithm of the maximum window
  72555. size (the size of the history buffer). It should be in the range 8..15 for
  72556. this version of the library. The default value is 15 if inflateInit is used
  72557. instead. windowBits must be greater than or equal to the windowBits value
  72558. provided to deflateInit2() while compressing, or it must be equal to 15 if
  72559. deflateInit2() was not used. If a compressed stream with a larger window
  72560. size is given as input, inflate() will return with the error code
  72561. Z_DATA_ERROR instead of trying to allocate a larger window.
  72562. windowBits can also be -8..-15 for raw inflate. In this case, -windowBits
  72563. determines the window size. inflate() will then process raw deflate data,
  72564. not looking for a zlib or gzip header, not generating a check value, and not
  72565. looking for any check values for comparison at the end of the stream. This
  72566. is for use with other formats that use the deflate compressed data format
  72567. such as zip. Those formats provide their own check values. If a custom
  72568. format is developed using the raw deflate format for compressed data, it is
  72569. recommended that a check value such as an adler32 or a crc32 be applied to
  72570. the uncompressed data as is done in the zlib, gzip, and zip formats. For
  72571. most applications, the zlib format should be used as is. Note that comments
  72572. above on the use in deflateInit2() applies to the magnitude of windowBits.
  72573. windowBits can also be greater than 15 for optional gzip decoding. Add
  72574. 32 to windowBits to enable zlib and gzip decoding with automatic header
  72575. detection, or add 16 to decode only the gzip format (the zlib format will
  72576. return a Z_DATA_ERROR). If a gzip stream is being decoded, strm->adler is
  72577. a crc32 instead of an adler32.
  72578. inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72579. memory, Z_STREAM_ERROR if a parameter is invalid (such as a null strm). msg
  72580. is set to null if there is no error message. inflateInit2 does not perform
  72581. any decompression apart from reading the zlib header if present: this will
  72582. be done by inflate(). (So next_in and avail_in may be modified, but next_out
  72583. and avail_out are unchanged.)
  72584. */
  72585. ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
  72586. const Bytef *dictionary,
  72587. uInt dictLength));
  72588. /*
  72589. Initializes the decompression dictionary from the given uncompressed byte
  72590. sequence. This function must be called immediately after a call of inflate,
  72591. if that call returned Z_NEED_DICT. The dictionary chosen by the compressor
  72592. can be determined from the adler32 value returned by that call of inflate.
  72593. The compressor and decompressor must use exactly the same dictionary (see
  72594. deflateSetDictionary). For raw inflate, this function can be called
  72595. immediately after inflateInit2() or inflateReset() and before any call of
  72596. inflate() to set the dictionary. The application must insure that the
  72597. dictionary that was used for compression is provided.
  72598. inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
  72599. parameter is invalid (such as NULL dictionary) or the stream state is
  72600. inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
  72601. expected one (incorrect adler32 value). inflateSetDictionary does not
  72602. perform any decompression: this will be done by subsequent calls of
  72603. inflate().
  72604. */
  72605. ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
  72606. /*
  72607. Skips invalid compressed data until a full flush point (see above the
  72608. description of deflate with Z_FULL_FLUSH) can be found, or until all
  72609. available input is skipped. No output is provided.
  72610. inflateSync returns Z_OK if a full flush point has been found, Z_BUF_ERROR
  72611. if no more input was provided, Z_DATA_ERROR if no flush point has been found,
  72612. or Z_STREAM_ERROR if the stream structure was inconsistent. In the success
  72613. case, the application may save the current current value of total_in which
  72614. indicates where valid compressed data was found. In the error case, the
  72615. application may repeatedly call inflateSync, providing more input each time,
  72616. until success or end of the input data.
  72617. */
  72618. ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
  72619. z_streamp source));
  72620. /*
  72621. Sets the destination stream as a complete copy of the source stream.
  72622. This function can be useful when randomly accessing a large stream. The
  72623. first pass through the stream can periodically record the inflate state,
  72624. allowing restarting inflate at those points when randomly accessing the
  72625. stream.
  72626. inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
  72627. enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
  72628. (such as zalloc being NULL). msg is left unchanged in both source and
  72629. destination.
  72630. */
  72631. ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
  72632. /*
  72633. This function is equivalent to inflateEnd followed by inflateInit,
  72634. but does not free and reallocate all the internal decompression state.
  72635. The stream will keep attributes that may have been set by inflateInit2.
  72636. inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
  72637. stream state was inconsistent (such as zalloc or state being NULL).
  72638. */
  72639. ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
  72640. int bits,
  72641. int value));
  72642. /*
  72643. This function inserts bits in the inflate input stream. The intent is
  72644. that this function is used to start inflating at a bit position in the
  72645. middle of a byte. The provided bits will be used before any bytes are used
  72646. from next_in. This function should only be used with raw inflate, and
  72647. should be used before the first inflate() call after inflateInit2() or
  72648. inflateReset(). bits must be less than or equal to 16, and that many of the
  72649. least significant bits of value will be inserted in the input.
  72650. inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
  72651. stream state was inconsistent.
  72652. */
  72653. ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
  72654. gz_headerp head));
  72655. /*
  72656. inflateGetHeader() requests that gzip header information be stored in the
  72657. provided gz_header structure. inflateGetHeader() may be called after
  72658. inflateInit2() or inflateReset(), and before the first call of inflate().
  72659. As inflate() processes the gzip stream, head->done is zero until the header
  72660. is completed, at which time head->done is set to one. If a zlib stream is
  72661. being decoded, then head->done is set to -1 to indicate that there will be
  72662. no gzip header information forthcoming. Note that Z_BLOCK can be used to
  72663. force inflate() to return immediately after header processing is complete
  72664. and before any actual data is decompressed.
  72665. The text, time, xflags, and os fields are filled in with the gzip header
  72666. contents. hcrc is set to true if there is a header CRC. (The header CRC
  72667. was valid if done is set to one.) If extra is not Z_NULL, then extra_max
  72668. contains the maximum number of bytes to write to extra. Once done is true,
  72669. extra_len contains the actual extra field length, and extra contains the
  72670. extra field, or that field truncated if extra_max is less than extra_len.
  72671. If name is not Z_NULL, then up to name_max characters are written there,
  72672. terminated with a zero unless the length is greater than name_max. If
  72673. comment is not Z_NULL, then up to comm_max characters are written there,
  72674. terminated with a zero unless the length is greater than comm_max. When
  72675. any of extra, name, or comment are not Z_NULL and the respective field is
  72676. not present in the header, then that field is set to Z_NULL to signal its
  72677. absence. This allows the use of deflateSetHeader() with the returned
  72678. structure to duplicate the header. However if those fields are set to
  72679. allocated memory, then the application will need to save those pointers
  72680. elsewhere so that they can be eventually freed.
  72681. If inflateGetHeader is not used, then the header information is simply
  72682. discarded. The header is always checked for validity, including the header
  72683. CRC if present. inflateReset() will reset the process to discard the header
  72684. information. The application would need to call inflateGetHeader() again to
  72685. retrieve the header from the next gzip stream.
  72686. inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
  72687. stream state was inconsistent.
  72688. */
  72689. /*
  72690. ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
  72691. unsigned char FAR *window));
  72692. Initialize the internal stream state for decompression using inflateBack()
  72693. calls. The fields zalloc, zfree and opaque in strm must be initialized
  72694. before the call. If zalloc and zfree are Z_NULL, then the default library-
  72695. derived memory allocation routines are used. windowBits is the base two
  72696. logarithm of the window size, in the range 8..15. window is a caller
  72697. supplied buffer of that size. Except for special applications where it is
  72698. assured that deflate was used with small window sizes, windowBits must be 15
  72699. and a 32K byte window must be supplied to be able to decompress general
  72700. deflate streams.
  72701. See inflateBack() for the usage of these routines.
  72702. inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
  72703. the paramaters are invalid, Z_MEM_ERROR if the internal state could not
  72704. be allocated, or Z_VERSION_ERROR if the version of the library does not
  72705. match the version of the header file.
  72706. */
  72707. typedef unsigned (*in_func) OF((void FAR *, unsigned char FAR * FAR *));
  72708. typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
  72709. ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
  72710. in_func in, void FAR *in_desc,
  72711. out_func out, void FAR *out_desc));
  72712. /*
  72713. inflateBack() does a raw inflate with a single call using a call-back
  72714. interface for input and output. This is more efficient than inflate() for
  72715. file i/o applications in that it avoids copying between the output and the
  72716. sliding window by simply making the window itself the output buffer. This
  72717. function trusts the application to not change the output buffer passed by
  72718. the output function, at least until inflateBack() returns.
  72719. inflateBackInit() must be called first to allocate the internal state
  72720. and to initialize the state with the user-provided window buffer.
  72721. inflateBack() may then be used multiple times to inflate a complete, raw
  72722. deflate stream with each call. inflateBackEnd() is then called to free
  72723. the allocated state.
  72724. A raw deflate stream is one with no zlib or gzip header or trailer.
  72725. This routine would normally be used in a utility that reads zip or gzip
  72726. files and writes out uncompressed files. The utility would decode the
  72727. header and process the trailer on its own, hence this routine expects
  72728. only the raw deflate stream to decompress. This is different from the
  72729. normal behavior of inflate(), which expects either a zlib or gzip header and
  72730. trailer around the deflate stream.
  72731. inflateBack() uses two subroutines supplied by the caller that are then
  72732. called by inflateBack() for input and output. inflateBack() calls those
  72733. routines until it reads a complete deflate stream and writes out all of the
  72734. uncompressed data, or until it encounters an error. The function's
  72735. parameters and return types are defined above in the in_func and out_func
  72736. typedefs. inflateBack() will call in(in_desc, &buf) which should return the
  72737. number of bytes of provided input, and a pointer to that input in buf. If
  72738. there is no input available, in() must return zero--buf is ignored in that
  72739. case--and inflateBack() will return a buffer error. inflateBack() will call
  72740. out(out_desc, buf, len) to write the uncompressed data buf[0..len-1]. out()
  72741. should return zero on success, or non-zero on failure. If out() returns
  72742. non-zero, inflateBack() will return with an error. Neither in() nor out()
  72743. are permitted to change the contents of the window provided to
  72744. inflateBackInit(), which is also the buffer that out() uses to write from.
  72745. The length written by out() will be at most the window size. Any non-zero
  72746. amount of input may be provided by in().
  72747. For convenience, inflateBack() can be provided input on the first call by
  72748. setting strm->next_in and strm->avail_in. If that input is exhausted, then
  72749. in() will be called. Therefore strm->next_in must be initialized before
  72750. calling inflateBack(). If strm->next_in is Z_NULL, then in() will be called
  72751. immediately for input. If strm->next_in is not Z_NULL, then strm->avail_in
  72752. must also be initialized, and then if strm->avail_in is not zero, input will
  72753. initially be taken from strm->next_in[0 .. strm->avail_in - 1].
  72754. The in_desc and out_desc parameters of inflateBack() is passed as the
  72755. first parameter of in() and out() respectively when they are called. These
  72756. descriptors can be optionally used to pass any information that the caller-
  72757. supplied in() and out() functions need to do their job.
  72758. On return, inflateBack() will set strm->next_in and strm->avail_in to
  72759. pass back any unused input that was provided by the last in() call. The
  72760. return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
  72761. if in() or out() returned an error, Z_DATA_ERROR if there was a format
  72762. error in the deflate stream (in which case strm->msg is set to indicate the
  72763. nature of the error), or Z_STREAM_ERROR if the stream was not properly
  72764. initialized. In the case of Z_BUF_ERROR, an input or output error can be
  72765. distinguished using strm->next_in which will be Z_NULL only if in() returned
  72766. an error. If strm->next is not Z_NULL, then the Z_BUF_ERROR was due to
  72767. out() returning non-zero. (in() will always be called before out(), so
  72768. strm->next_in is assured to be defined if out() returns non-zero.) Note
  72769. that inflateBack() cannot return Z_OK.
  72770. */
  72771. ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
  72772. /*
  72773. All memory allocated by inflateBackInit() is freed.
  72774. inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
  72775. state was inconsistent.
  72776. */
  72777. //ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
  72778. /* Return flags indicating compile-time options.
  72779. Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
  72780. 1.0: size of uInt
  72781. 3.2: size of uLong
  72782. 5.4: size of voidpf (pointer)
  72783. 7.6: size of z_off_t
  72784. Compiler, assembler, and debug options:
  72785. 8: DEBUG
  72786. 9: ASMV or ASMINF -- use ASM code
  72787. 10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
  72788. 11: 0 (reserved)
  72789. One-time table building (smaller code, but not thread-safe if true):
  72790. 12: BUILDFIXED -- build static block decoding tables when needed
  72791. 13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
  72792. 14,15: 0 (reserved)
  72793. Library content (indicates missing functionality):
  72794. 16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
  72795. deflate code when not needed)
  72796. 17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
  72797. and decode gzip streams (to avoid linking crc code)
  72798. 18-19: 0 (reserved)
  72799. Operation variations (changes in library functionality):
  72800. 20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
  72801. 21: FASTEST -- deflate algorithm with only one, lowest compression level
  72802. 22,23: 0 (reserved)
  72803. The sprintf variant used by gzprintf (zero is best):
  72804. 24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
  72805. 25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
  72806. 26: 0 = returns value, 1 = void -- 1 means inferred string length returned
  72807. Remainder:
  72808. 27-31: 0 (reserved)
  72809. */
  72810. /* utility functions */
  72811. /*
  72812. The following utility functions are implemented on top of the
  72813. basic stream-oriented functions. To simplify the interface, some
  72814. default options are assumed (compression level and memory usage,
  72815. standard memory allocation functions). The source code of these
  72816. utility functions can easily be modified if you need special options.
  72817. */
  72818. ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
  72819. const Bytef *source, uLong sourceLen));
  72820. /*
  72821. Compresses the source buffer into the destination buffer. sourceLen is
  72822. the byte length of the source buffer. Upon entry, destLen is the total
  72823. size of the destination buffer, which must be at least the value returned
  72824. by compressBound(sourceLen). Upon exit, destLen is the actual size of the
  72825. compressed buffer.
  72826. This function can be used to compress a whole file at once if the
  72827. input file is mmap'ed.
  72828. compress returns Z_OK if success, Z_MEM_ERROR if there was not
  72829. enough memory, Z_BUF_ERROR if there was not enough room in the output
  72830. buffer.
  72831. */
  72832. ZEXTERN int ZEXPORT compress2 OF((Bytef *dest, uLongf *destLen,
  72833. const Bytef *source, uLong sourceLen,
  72834. int level));
  72835. /*
  72836. Compresses the source buffer into the destination buffer. The level
  72837. parameter has the same meaning as in deflateInit. sourceLen is the byte
  72838. length of the source buffer. Upon entry, destLen is the total size of the
  72839. destination buffer, which must be at least the value returned by
  72840. compressBound(sourceLen). Upon exit, destLen is the actual size of the
  72841. compressed buffer.
  72842. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  72843. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  72844. Z_STREAM_ERROR if the level parameter is invalid.
  72845. */
  72846. ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
  72847. /*
  72848. compressBound() returns an upper bound on the compressed size after
  72849. compress() or compress2() on sourceLen bytes. It would be used before
  72850. a compress() or compress2() call to allocate the destination buffer.
  72851. */
  72852. ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
  72853. const Bytef *source, uLong sourceLen));
  72854. /*
  72855. Decompresses the source buffer into the destination buffer. sourceLen is
  72856. the byte length of the source buffer. Upon entry, destLen is the total
  72857. size of the destination buffer, which must be large enough to hold the
  72858. entire uncompressed data. (The size of the uncompressed data must have
  72859. been saved previously by the compressor and transmitted to the decompressor
  72860. by some mechanism outside the scope of this compression library.)
  72861. Upon exit, destLen is the actual size of the compressed buffer.
  72862. This function can be used to decompress a whole file at once if the
  72863. input file is mmap'ed.
  72864. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  72865. enough memory, Z_BUF_ERROR if there was not enough room in the output
  72866. buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.
  72867. */
  72868. typedef voidp gzFile;
  72869. ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
  72870. /*
  72871. Opens a gzip (.gz) file for reading or writing. The mode parameter
  72872. is as in fopen ("rb" or "wb") but can also include a compression level
  72873. ("wb9") or a strategy: 'f' for filtered data as in "wb6f", 'h' for
  72874. Huffman only compression as in "wb1h", or 'R' for run-length encoding
  72875. as in "wb1R". (See the description of deflateInit2 for more information
  72876. about the strategy parameter.)
  72877. gzopen can be used to read a file which is not in gzip format; in this
  72878. case gzread will directly read from the file without decompression.
  72879. gzopen returns NULL if the file could not be opened or if there was
  72880. insufficient memory to allocate the (de)compression state; errno
  72881. can be checked to distinguish the two cases (if errno is zero, the
  72882. zlib error is Z_MEM_ERROR). */
  72883. ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
  72884. /*
  72885. gzdopen() associates a gzFile with the file descriptor fd. File
  72886. descriptors are obtained from calls like open, dup, creat, pipe or
  72887. fileno (in the file has been previously opened with fopen).
  72888. The mode parameter is as in gzopen.
  72889. The next call of gzclose on the returned gzFile will also close the
  72890. file descriptor fd, just like fclose(fdopen(fd), mode) closes the file
  72891. descriptor fd. If you want to keep fd open, use gzdopen(dup(fd), mode).
  72892. gzdopen returns NULL if there was insufficient memory to allocate
  72893. the (de)compression state.
  72894. */
  72895. ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
  72896. /*
  72897. Dynamically update the compression level or strategy. See the description
  72898. of deflateInit2 for the meaning of these parameters.
  72899. gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
  72900. opened for writing.
  72901. */
  72902. ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
  72903. /*
  72904. Reads the given number of uncompressed bytes from the compressed file.
  72905. If the input file was not in gzip format, gzread copies the given number
  72906. of bytes into the buffer.
  72907. gzread returns the number of uncompressed bytes actually read (0 for
  72908. end of file, -1 for error). */
  72909. ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
  72910. voidpc buf, unsigned len));
  72911. /*
  72912. Writes the given number of uncompressed bytes into the compressed file.
  72913. gzwrite returns the number of uncompressed bytes actually written
  72914. (0 in case of error).
  72915. */
  72916. ZEXTERN int ZEXPORTVA gzprintf OF((gzFile file, const char *format, ...));
  72917. /*
  72918. Converts, formats, and writes the args to the compressed file under
  72919. control of the format string, as in fprintf. gzprintf returns the number of
  72920. uncompressed bytes actually written (0 in case of error). The number of
  72921. uncompressed bytes written is limited to 4095. The caller should assure that
  72922. this limit is not exceeded. If it is exceeded, then gzprintf() will return
  72923. return an error (0) with nothing written. In this case, there may also be a
  72924. buffer overflow with unpredictable consequences, which is possible only if
  72925. zlib was compiled with the insecure functions sprintf() or vsprintf()
  72926. because the secure snprintf() or vsnprintf() functions were not available.
  72927. */
  72928. ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
  72929. /*
  72930. Writes the given null-terminated string to the compressed file, excluding
  72931. the terminating null character.
  72932. gzputs returns the number of characters written, or -1 in case of error.
  72933. */
  72934. ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
  72935. /*
  72936. Reads bytes from the compressed file until len-1 characters are read, or
  72937. a newline character is read and transferred to buf, or an end-of-file
  72938. condition is encountered. The string is then terminated with a null
  72939. character.
  72940. gzgets returns buf, or Z_NULL in case of error.
  72941. */
  72942. ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
  72943. /*
  72944. Writes c, converted to an unsigned char, into the compressed file.
  72945. gzputc returns the value that was written, or -1 in case of error.
  72946. */
  72947. ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
  72948. /*
  72949. Reads one byte from the compressed file. gzgetc returns this byte
  72950. or -1 in case of end of file or error.
  72951. */
  72952. ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
  72953. /*
  72954. Push one character back onto the stream to be read again later.
  72955. Only one character of push-back is allowed. gzungetc() returns the
  72956. character pushed, or -1 on failure. gzungetc() will fail if a
  72957. character has been pushed but not read yet, or if c is -1. The pushed
  72958. character will be discarded if the stream is repositioned with gzseek()
  72959. or gzrewind().
  72960. */
  72961. ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
  72962. /*
  72963. Flushes all pending output into the compressed file. The parameter
  72964. flush is as in the deflate() function. The return value is the zlib
  72965. error number (see function gzerror below). gzflush returns Z_OK if
  72966. the flush parameter is Z_FINISH and all output could be flushed.
  72967. gzflush should be called only when strictly necessary because it can
  72968. degrade compression.
  72969. */
  72970. ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
  72971. z_off_t offset, int whence));
  72972. /*
  72973. Sets the starting position for the next gzread or gzwrite on the
  72974. given compressed file. The offset represents a number of bytes in the
  72975. uncompressed data stream. The whence parameter is defined as in lseek(2);
  72976. the value SEEK_END is not supported.
  72977. If the file is opened for reading, this function is emulated but can be
  72978. extremely slow. If the file is opened for writing, only forward seeks are
  72979. supported; gzseek then compresses a sequence of zeroes up to the new
  72980. starting position.
  72981. gzseek returns the resulting offset location as measured in bytes from
  72982. the beginning of the uncompressed stream, or -1 in case of error, in
  72983. particular if the file is opened for writing and the new starting position
  72984. would be before the current position.
  72985. */
  72986. ZEXTERN int ZEXPORT gzrewind OF((gzFile file));
  72987. /*
  72988. Rewinds the given file. This function is supported only for reading.
  72989. gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
  72990. */
  72991. ZEXTERN z_off_t ZEXPORT gztell OF((gzFile file));
  72992. /*
  72993. Returns the starting position for the next gzread or gzwrite on the
  72994. given compressed file. This position represents a number of bytes in the
  72995. uncompressed data stream.
  72996. gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
  72997. */
  72998. ZEXTERN int ZEXPORT gzeof OF((gzFile file));
  72999. /*
  73000. Returns 1 when EOF has previously been detected reading the given
  73001. input stream, otherwise zero.
  73002. */
  73003. ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
  73004. /*
  73005. Returns 1 if file is being read directly without decompression, otherwise
  73006. zero.
  73007. */
  73008. ZEXTERN int ZEXPORT gzclose OF((gzFile file));
  73009. /*
  73010. Flushes all pending output if necessary, closes the compressed file
  73011. and deallocates all the (de)compression state. The return value is the zlib
  73012. error number (see function gzerror below).
  73013. */
  73014. ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
  73015. /*
  73016. Returns the error message for the last error which occurred on the
  73017. given compressed file. errnum is set to zlib error number. If an
  73018. error occurred in the file system and not in the compression library,
  73019. errnum is set to Z_ERRNO and the application may consult errno
  73020. to get the exact error code.
  73021. */
  73022. ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
  73023. /*
  73024. Clears the error and end-of-file flags for file. This is analogous to the
  73025. clearerr() function in stdio. This is useful for continuing to read a gzip
  73026. file that is being written concurrently.
  73027. */
  73028. /* checksum functions */
  73029. /*
  73030. These functions are not related to compression but are exported
  73031. anyway because they might be useful in applications using the
  73032. compression library.
  73033. */
  73034. ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
  73035. /*
  73036. Update a running Adler-32 checksum with the bytes buf[0..len-1] and
  73037. return the updated checksum. If buf is NULL, this function returns
  73038. the required initial value for the checksum.
  73039. An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
  73040. much faster. Usage example:
  73041. uLong adler = adler32(0L, Z_NULL, 0);
  73042. while (read_buffer(buffer, length) != EOF) {
  73043. adler = adler32(adler, buffer, length);
  73044. }
  73045. if (adler != original_adler) error();
  73046. */
  73047. ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
  73048. z_off_t len2));
  73049. /*
  73050. Combine two Adler-32 checksums into one. For two sequences of bytes, seq1
  73051. and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
  73052. each, adler1 and adler2. adler32_combine() returns the Adler-32 checksum of
  73053. seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.
  73054. */
  73055. ZEXTERN uLong ZEXPORT crc32 OF((uLong crc, const Bytef *buf, uInt len));
  73056. /*
  73057. Update a running CRC-32 with the bytes buf[0..len-1] and return the
  73058. updated CRC-32. If buf is NULL, this function returns the required initial
  73059. value for the for the crc. Pre- and post-conditioning (one's complement) is
  73060. performed within this function so it shouldn't be done by the application.
  73061. Usage example:
  73062. uLong crc = crc32(0L, Z_NULL, 0);
  73063. while (read_buffer(buffer, length) != EOF) {
  73064. crc = crc32(crc, buffer, length);
  73065. }
  73066. if (crc != original_crc) error();
  73067. */
  73068. ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
  73069. /*
  73070. Combine two CRC-32 check values into one. For two sequences of bytes,
  73071. seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
  73072. calculated for each, crc1 and crc2. crc32_combine() returns the CRC-32
  73073. check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
  73074. len2.
  73075. */
  73076. /* various hacks, don't look :) */
  73077. /* deflateInit and inflateInit are macros to allow checking the zlib version
  73078. * and the compiler's view of z_stream:
  73079. */
  73080. ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
  73081. const char *version, int stream_size));
  73082. ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
  73083. const char *version, int stream_size));
  73084. ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int level, int method,
  73085. int windowBits, int memLevel,
  73086. int strategy, const char *version,
  73087. int stream_size));
  73088. ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int windowBits,
  73089. const char *version, int stream_size));
  73090. ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
  73091. unsigned char FAR *window,
  73092. const char *version,
  73093. int stream_size));
  73094. #define deflateInit(strm, level) \
  73095. deflateInit_((strm), (level), ZLIB_VERSION, sizeof(z_stream))
  73096. #define inflateInit(strm) \
  73097. inflateInit_((strm), ZLIB_VERSION, sizeof(z_stream))
  73098. #define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
  73099. deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
  73100. (strategy), ZLIB_VERSION, sizeof(z_stream))
  73101. #define inflateInit2(strm, windowBits) \
  73102. inflateInit2_((strm), (windowBits), ZLIB_VERSION, sizeof(z_stream))
  73103. #define inflateBackInit(strm, windowBits, window) \
  73104. inflateBackInit_((strm), (windowBits), (window), \
  73105. ZLIB_VERSION, sizeof(z_stream))
  73106. #if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
  73107. struct internal_state {int dummy;}; /* hack for buggy compilers */
  73108. #endif
  73109. ZEXTERN const char * ZEXPORT zError OF((int));
  73110. ZEXTERN int ZEXPORT inflateSyncPoint OF((z_streamp z));
  73111. ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
  73112. #ifdef __cplusplus
  73113. }
  73114. #endif
  73115. #endif /* ZLIB_H */
  73116. /********* End of inlined file: zlib.h *********/
  73117. #undef OS_CODE
  73118. #else
  73119. #include <zlib.h>
  73120. #endif
  73121. }
  73122. BEGIN_JUCE_NAMESPACE
  73123. using namespace zlibNamespace;
  73124. // internal helper object that holds the zlib structures so they don't have to be
  73125. // included publicly.
  73126. class GZIPCompressorHelper
  73127. {
  73128. private:
  73129. z_stream* stream;
  73130. uint8* data;
  73131. int dataSize, compLevel, strategy;
  73132. bool setParams;
  73133. public:
  73134. bool finished, shouldFinish;
  73135. GZIPCompressorHelper (const int compressionLevel, const bool nowrap)
  73136. : data (0),
  73137. dataSize (0),
  73138. compLevel (compressionLevel),
  73139. strategy (0),
  73140. setParams (true),
  73141. finished (false),
  73142. shouldFinish (false)
  73143. {
  73144. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  73145. if (deflateInit2 (stream,
  73146. compLevel,
  73147. Z_DEFLATED,
  73148. nowrap ? -MAX_WBITS : MAX_WBITS,
  73149. 8,
  73150. strategy) != Z_OK)
  73151. {
  73152. juce_free (stream);
  73153. stream = 0;
  73154. }
  73155. }
  73156. ~GZIPCompressorHelper()
  73157. {
  73158. if (stream != 0)
  73159. {
  73160. deflateEnd (stream);
  73161. juce_free (stream);
  73162. }
  73163. }
  73164. bool needsInput() const throw()
  73165. {
  73166. return dataSize <= 0;
  73167. }
  73168. void setInput (uint8* const newData, const int size) throw()
  73169. {
  73170. data = newData;
  73171. dataSize = size;
  73172. }
  73173. int doNextBlock (uint8* const dest, const int destSize) throw()
  73174. {
  73175. if (stream != 0)
  73176. {
  73177. stream->next_in = data;
  73178. stream->next_out = dest;
  73179. stream->avail_in = dataSize;
  73180. stream->avail_out = destSize;
  73181. const int result = setParams ? deflateParams (stream, compLevel, strategy)
  73182. : deflate (stream, shouldFinish ? Z_FINISH : Z_NO_FLUSH);
  73183. setParams = false;
  73184. switch (result)
  73185. {
  73186. case Z_STREAM_END:
  73187. finished = true;
  73188. case Z_OK:
  73189. data += dataSize - stream->avail_in;
  73190. dataSize = stream->avail_in;
  73191. return destSize - stream->avail_out;
  73192. default:
  73193. break;
  73194. }
  73195. }
  73196. return 0;
  73197. }
  73198. };
  73199. const int gzipCompBufferSize = 32768;
  73200. GZIPCompressorOutputStream::GZIPCompressorOutputStream (OutputStream* const destStream_,
  73201. int compressionLevel,
  73202. const bool deleteDestStream_,
  73203. const bool noWrap)
  73204. : destStream (destStream_),
  73205. deleteDestStream (deleteDestStream_)
  73206. {
  73207. if (compressionLevel < 1 || compressionLevel > 9)
  73208. compressionLevel = -1;
  73209. helper = new GZIPCompressorHelper (compressionLevel, noWrap);
  73210. buffer = (uint8*) juce_malloc (gzipCompBufferSize);
  73211. }
  73212. GZIPCompressorOutputStream::~GZIPCompressorOutputStream()
  73213. {
  73214. flush();
  73215. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  73216. delete h;
  73217. juce_free (buffer);
  73218. if (deleteDestStream)
  73219. delete destStream;
  73220. }
  73221. void GZIPCompressorOutputStream::flush()
  73222. {
  73223. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  73224. if (! h->finished)
  73225. {
  73226. h->shouldFinish = true;
  73227. while (! h->finished)
  73228. doNextBlock();
  73229. }
  73230. destStream->flush();
  73231. }
  73232. bool GZIPCompressorOutputStream::write (const void* destBuffer, int howMany)
  73233. {
  73234. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  73235. if (! h->finished)
  73236. {
  73237. h->setInput ((uint8*) destBuffer, howMany);
  73238. while (! h->needsInput())
  73239. {
  73240. if (! doNextBlock())
  73241. return false;
  73242. }
  73243. }
  73244. return true;
  73245. }
  73246. bool GZIPCompressorOutputStream::doNextBlock()
  73247. {
  73248. GZIPCompressorHelper* const h = (GZIPCompressorHelper*) helper;
  73249. const int len = h->doNextBlock (buffer, gzipCompBufferSize);
  73250. if (len > 0)
  73251. return destStream->write (buffer, len);
  73252. else
  73253. return true;
  73254. }
  73255. int64 GZIPCompressorOutputStream::getPosition()
  73256. {
  73257. return destStream->getPosition();
  73258. }
  73259. bool GZIPCompressorOutputStream::setPosition (int64 /*newPosition*/)
  73260. {
  73261. jassertfalse // can't do it!
  73262. return false;
  73263. }
  73264. END_JUCE_NAMESPACE
  73265. /********* End of inlined file: juce_GZIPCompressorOutputStream.cpp *********/
  73266. /********* Start of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  73267. #if JUCE_MSVC
  73268. #pragma warning (push)
  73269. #pragma warning (disable: 4309 4305)
  73270. #endif
  73271. namespace zlibNamespace
  73272. {
  73273. #if JUCE_INCLUDE_ZLIB_CODE
  73274. extern "C"
  73275. {
  73276. #undef OS_CODE
  73277. #undef fdopen
  73278. #define ZLIB_INTERNAL
  73279. #define NO_DUMMY_DECL
  73280. /********* Start of inlined file: adler32.c *********/
  73281. /* @(#) $Id: adler32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73282. #define ZLIB_INTERNAL
  73283. #define BASE 65521UL /* largest prime smaller than 65536 */
  73284. #define NMAX 5552
  73285. /* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
  73286. #define DO1(buf,i) {adler += (buf)[i]; sum2 += adler;}
  73287. #define DO2(buf,i) DO1(buf,i); DO1(buf,i+1);
  73288. #define DO4(buf,i) DO2(buf,i); DO2(buf,i+2);
  73289. #define DO8(buf,i) DO4(buf,i); DO4(buf,i+4);
  73290. #define DO16(buf) DO8(buf,0); DO8(buf,8);
  73291. /* use NO_DIVIDE if your processor does not do division in hardware */
  73292. #ifdef NO_DIVIDE
  73293. # define MOD(a) \
  73294. do { \
  73295. if (a >= (BASE << 16)) a -= (BASE << 16); \
  73296. if (a >= (BASE << 15)) a -= (BASE << 15); \
  73297. if (a >= (BASE << 14)) a -= (BASE << 14); \
  73298. if (a >= (BASE << 13)) a -= (BASE << 13); \
  73299. if (a >= (BASE << 12)) a -= (BASE << 12); \
  73300. if (a >= (BASE << 11)) a -= (BASE << 11); \
  73301. if (a >= (BASE << 10)) a -= (BASE << 10); \
  73302. if (a >= (BASE << 9)) a -= (BASE << 9); \
  73303. if (a >= (BASE << 8)) a -= (BASE << 8); \
  73304. if (a >= (BASE << 7)) a -= (BASE << 7); \
  73305. if (a >= (BASE << 6)) a -= (BASE << 6); \
  73306. if (a >= (BASE << 5)) a -= (BASE << 5); \
  73307. if (a >= (BASE << 4)) a -= (BASE << 4); \
  73308. if (a >= (BASE << 3)) a -= (BASE << 3); \
  73309. if (a >= (BASE << 2)) a -= (BASE << 2); \
  73310. if (a >= (BASE << 1)) a -= (BASE << 1); \
  73311. if (a >= BASE) a -= BASE; \
  73312. } while (0)
  73313. # define MOD4(a) \
  73314. do { \
  73315. if (a >= (BASE << 4)) a -= (BASE << 4); \
  73316. if (a >= (BASE << 3)) a -= (BASE << 3); \
  73317. if (a >= (BASE << 2)) a -= (BASE << 2); \
  73318. if (a >= (BASE << 1)) a -= (BASE << 1); \
  73319. if (a >= BASE) a -= BASE; \
  73320. } while (0)
  73321. #else
  73322. # define MOD(a) a %= BASE
  73323. # define MOD4(a) a %= BASE
  73324. #endif
  73325. /* ========================================================================= */
  73326. uLong ZEXPORT adler32(uLong adler, const Bytef *buf, uInt len)
  73327. {
  73328. unsigned long sum2;
  73329. unsigned n;
  73330. /* split Adler-32 into component sums */
  73331. sum2 = (adler >> 16) & 0xffff;
  73332. adler &= 0xffff;
  73333. /* in case user likes doing a byte at a time, keep it fast */
  73334. if (len == 1) {
  73335. adler += buf[0];
  73336. if (adler >= BASE)
  73337. adler -= BASE;
  73338. sum2 += adler;
  73339. if (sum2 >= BASE)
  73340. sum2 -= BASE;
  73341. return adler | (sum2 << 16);
  73342. }
  73343. /* initial Adler-32 value (deferred check for len == 1 speed) */
  73344. if (buf == Z_NULL)
  73345. return 1L;
  73346. /* in case short lengths are provided, keep it somewhat fast */
  73347. if (len < 16) {
  73348. while (len--) {
  73349. adler += *buf++;
  73350. sum2 += adler;
  73351. }
  73352. if (adler >= BASE)
  73353. adler -= BASE;
  73354. MOD4(sum2); /* only added so many BASE's */
  73355. return adler | (sum2 << 16);
  73356. }
  73357. /* do length NMAX blocks -- requires just one modulo operation */
  73358. while (len >= NMAX) {
  73359. len -= NMAX;
  73360. n = NMAX / 16; /* NMAX is divisible by 16 */
  73361. do {
  73362. DO16(buf); /* 16 sums unrolled */
  73363. buf += 16;
  73364. } while (--n);
  73365. MOD(adler);
  73366. MOD(sum2);
  73367. }
  73368. /* do remaining bytes (less than NMAX, still just one modulo) */
  73369. if (len) { /* avoid modulos if none remaining */
  73370. while (len >= 16) {
  73371. len -= 16;
  73372. DO16(buf);
  73373. buf += 16;
  73374. }
  73375. while (len--) {
  73376. adler += *buf++;
  73377. sum2 += adler;
  73378. }
  73379. MOD(adler);
  73380. MOD(sum2);
  73381. }
  73382. /* return recombined sums */
  73383. return adler | (sum2 << 16);
  73384. }
  73385. /* ========================================================================= */
  73386. uLong ZEXPORT adler32_combine(uLong adler1, uLong adler2, z_off_t len2)
  73387. {
  73388. unsigned long sum1;
  73389. unsigned long sum2;
  73390. unsigned rem;
  73391. /* the derivation of this formula is left as an exercise for the reader */
  73392. rem = (unsigned)(len2 % BASE);
  73393. sum1 = adler1 & 0xffff;
  73394. sum2 = rem * sum1;
  73395. MOD(sum2);
  73396. sum1 += (adler2 & 0xffff) + BASE - 1;
  73397. sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
  73398. if (sum1 > BASE) sum1 -= BASE;
  73399. if (sum1 > BASE) sum1 -= BASE;
  73400. if (sum2 > (BASE << 1)) sum2 -= (BASE << 1);
  73401. if (sum2 > BASE) sum2 -= BASE;
  73402. return sum1 | (sum2 << 16);
  73403. }
  73404. /********* End of inlined file: adler32.c *********/
  73405. /********* Start of inlined file: compress.c *********/
  73406. /* @(#) $Id: compress.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73407. #define ZLIB_INTERNAL
  73408. /* ===========================================================================
  73409. Compresses the source buffer into the destination buffer. The level
  73410. parameter has the same meaning as in deflateInit. sourceLen is the byte
  73411. length of the source buffer. Upon entry, destLen is the total size of the
  73412. destination buffer, which must be at least 0.1% larger than sourceLen plus
  73413. 12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
  73414. compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
  73415. memory, Z_BUF_ERROR if there was not enough room in the output buffer,
  73416. Z_STREAM_ERROR if the level parameter is invalid.
  73417. */
  73418. int ZEXPORT compress2 (Bytef *dest, uLongf *destLen, const Bytef *source,
  73419. uLong sourceLen, int level)
  73420. {
  73421. z_stream stream;
  73422. int err;
  73423. stream.next_in = (Bytef*)source;
  73424. stream.avail_in = (uInt)sourceLen;
  73425. #ifdef MAXSEG_64K
  73426. /* Check for source > 64K on 16-bit machine: */
  73427. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  73428. #endif
  73429. stream.next_out = dest;
  73430. stream.avail_out = (uInt)*destLen;
  73431. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  73432. stream.zalloc = (alloc_func)0;
  73433. stream.zfree = (free_func)0;
  73434. stream.opaque = (voidpf)0;
  73435. err = deflateInit(&stream, level);
  73436. if (err != Z_OK) return err;
  73437. err = deflate(&stream, Z_FINISH);
  73438. if (err != Z_STREAM_END) {
  73439. deflateEnd(&stream);
  73440. return err == Z_OK ? Z_BUF_ERROR : err;
  73441. }
  73442. *destLen = stream.total_out;
  73443. err = deflateEnd(&stream);
  73444. return err;
  73445. }
  73446. /* ===========================================================================
  73447. */
  73448. int ZEXPORT compress (Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen)
  73449. {
  73450. return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
  73451. }
  73452. /* ===========================================================================
  73453. If the default memLevel or windowBits for deflateInit() is changed, then
  73454. this function needs to be updated.
  73455. */
  73456. uLong ZEXPORT compressBound (uLong sourceLen)
  73457. {
  73458. return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) + 11;
  73459. }
  73460. /********* End of inlined file: compress.c *********/
  73461. #undef DO1
  73462. #undef DO8
  73463. /********* Start of inlined file: crc32.c *********/
  73464. /* @(#) $Id: crc32.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73465. /*
  73466. Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
  73467. protection on the static variables used to control the first-use generation
  73468. of the crc tables. Therefore, if you #define DYNAMIC_CRC_TABLE, you should
  73469. first call get_crc_table() to initialize the tables before allowing more than
  73470. one thread to use crc32().
  73471. */
  73472. #ifdef MAKECRCH
  73473. # include <stdio.h>
  73474. # ifndef DYNAMIC_CRC_TABLE
  73475. # define DYNAMIC_CRC_TABLE
  73476. # endif /* !DYNAMIC_CRC_TABLE */
  73477. #endif /* MAKECRCH */
  73478. /********* Start of inlined file: zutil.h *********/
  73479. /* WARNING: this file should *not* be used by applications. It is
  73480. part of the implementation of the compression library and is
  73481. subject to change. Applications should only use zlib.h.
  73482. */
  73483. /* @(#) $Id: zutil.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  73484. #ifndef ZUTIL_H
  73485. #define ZUTIL_H
  73486. #define ZLIB_INTERNAL
  73487. #ifdef STDC
  73488. # ifndef _WIN32_WCE
  73489. # include <stddef.h>
  73490. # endif
  73491. # include <string.h>
  73492. # include <stdlib.h>
  73493. #endif
  73494. #ifdef NO_ERRNO_H
  73495. # ifdef _WIN32_WCE
  73496. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  73497. * errno. We define it as a global variable to simplify porting.
  73498. * Its value is always 0 and should not be used. We rename it to
  73499. * avoid conflict with other libraries that use the same workaround.
  73500. */
  73501. # define errno z_errno
  73502. # endif
  73503. extern int errno;
  73504. #else
  73505. # ifndef _WIN32_WCE
  73506. # include <errno.h>
  73507. # endif
  73508. #endif
  73509. #ifndef local
  73510. # define local static
  73511. #endif
  73512. /* compile with -Dlocal if your debugger can't find static symbols */
  73513. typedef unsigned char uch;
  73514. typedef uch FAR uchf;
  73515. typedef unsigned short ush;
  73516. typedef ush FAR ushf;
  73517. typedef unsigned long ulg;
  73518. extern const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
  73519. /* (size given to avoid silly warnings with Visual C++) */
  73520. #define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
  73521. #define ERR_RETURN(strm,err) \
  73522. return (strm->msg = (char*)ERR_MSG(err), (err))
  73523. /* To be used only when the state is known to be valid */
  73524. /* common constants */
  73525. #ifndef DEF_WBITS
  73526. # define DEF_WBITS MAX_WBITS
  73527. #endif
  73528. /* default windowBits for decompression. MAX_WBITS is for compression only */
  73529. #if MAX_MEM_LEVEL >= 8
  73530. # define DEF_MEM_LEVEL 8
  73531. #else
  73532. # define DEF_MEM_LEVEL MAX_MEM_LEVEL
  73533. #endif
  73534. /* default memLevel */
  73535. #define STORED_BLOCK 0
  73536. #define STATIC_TREES 1
  73537. #define DYN_TREES 2
  73538. /* The three kinds of block type */
  73539. #define MIN_MATCH 3
  73540. #define MAX_MATCH 258
  73541. /* The minimum and maximum match lengths */
  73542. #define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
  73543. /* target dependencies */
  73544. #if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
  73545. # define OS_CODE 0x00
  73546. # if defined(__TURBOC__) || defined(__BORLANDC__)
  73547. # if(__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
  73548. /* Allow compilation with ANSI keywords only enabled */
  73549. void _Cdecl farfree( void *block );
  73550. void *_Cdecl farmalloc( unsigned long nbytes );
  73551. # else
  73552. # include <alloc.h>
  73553. # endif
  73554. # else /* MSC or DJGPP */
  73555. # include <malloc.h>
  73556. # endif
  73557. #endif
  73558. #ifdef AMIGA
  73559. # define OS_CODE 0x01
  73560. #endif
  73561. #if defined(VAXC) || defined(VMS)
  73562. # define OS_CODE 0x02
  73563. # define F_OPEN(name, mode) \
  73564. fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
  73565. #endif
  73566. #if defined(ATARI) || defined(atarist)
  73567. # define OS_CODE 0x05
  73568. #endif
  73569. #ifdef OS2
  73570. # define OS_CODE 0x06
  73571. # ifdef M_I86
  73572. #include <malloc.h>
  73573. # endif
  73574. #endif
  73575. #if defined(MACOS) || TARGET_OS_MAC
  73576. # define OS_CODE 0x07
  73577. # if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
  73578. # include <unix.h> /* for fdopen */
  73579. # else
  73580. # ifndef fdopen
  73581. # define fdopen(fd,mode) NULL /* No fdopen() */
  73582. # endif
  73583. # endif
  73584. #endif
  73585. #ifdef TOPS20
  73586. # define OS_CODE 0x0a
  73587. #endif
  73588. #ifdef WIN32
  73589. # ifndef __CYGWIN__ /* Cygwin is Unix, not Win32 */
  73590. # define OS_CODE 0x0b
  73591. # endif
  73592. #endif
  73593. #ifdef __50SERIES /* Prime/PRIMOS */
  73594. # define OS_CODE 0x0f
  73595. #endif
  73596. #if defined(_BEOS_) || defined(RISCOS)
  73597. # define fdopen(fd,mode) NULL /* No fdopen() */
  73598. #endif
  73599. #if (defined(_MSC_VER) && (_MSC_VER > 600))
  73600. # if defined(_WIN32_WCE)
  73601. # define fdopen(fd,mode) NULL /* No fdopen() */
  73602. # ifndef _PTRDIFF_T_DEFINED
  73603. typedef int ptrdiff_t;
  73604. # define _PTRDIFF_T_DEFINED
  73605. # endif
  73606. # else
  73607. # define fdopen(fd,type) _fdopen(fd,type)
  73608. # endif
  73609. #endif
  73610. /* common defaults */
  73611. #ifndef OS_CODE
  73612. # define OS_CODE 0x03 /* assume Unix */
  73613. #endif
  73614. #ifndef F_OPEN
  73615. # define F_OPEN(name, mode) fopen((name), (mode))
  73616. #endif
  73617. /* functions */
  73618. #if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
  73619. # ifndef HAVE_VSNPRINTF
  73620. # define HAVE_VSNPRINTF
  73621. # endif
  73622. #endif
  73623. #if defined(__CYGWIN__)
  73624. # ifndef HAVE_VSNPRINTF
  73625. # define HAVE_VSNPRINTF
  73626. # endif
  73627. #endif
  73628. #ifndef HAVE_VSNPRINTF
  73629. # ifdef MSDOS
  73630. /* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
  73631. but for now we just assume it doesn't. */
  73632. # define NO_vsnprintf
  73633. # endif
  73634. # ifdef __TURBOC__
  73635. # define NO_vsnprintf
  73636. # endif
  73637. # ifdef WIN32
  73638. /* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
  73639. # if !defined(vsnprintf) && !defined(NO_vsnprintf)
  73640. # define vsnprintf _vsnprintf
  73641. # endif
  73642. # endif
  73643. # ifdef __SASC
  73644. # define NO_vsnprintf
  73645. # endif
  73646. #endif
  73647. #ifdef VMS
  73648. # define NO_vsnprintf
  73649. #endif
  73650. #if defined(pyr)
  73651. # define NO_MEMCPY
  73652. #endif
  73653. #if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
  73654. /* Use our own functions for small and medium model with MSC <= 5.0.
  73655. * You may have to use the same strategy for Borland C (untested).
  73656. * The __SC__ check is for Symantec.
  73657. */
  73658. # define NO_MEMCPY
  73659. #endif
  73660. #if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
  73661. # define HAVE_MEMCPY
  73662. #endif
  73663. #ifdef HAVE_MEMCPY
  73664. # ifdef SMALL_MEDIUM /* MSDOS small or medium model */
  73665. # define zmemcpy _fmemcpy
  73666. # define zmemcmp _fmemcmp
  73667. # define zmemzero(dest, len) _fmemset(dest, 0, len)
  73668. # else
  73669. # define zmemcpy memcpy
  73670. # define zmemcmp memcmp
  73671. # define zmemzero(dest, len) memset(dest, 0, len)
  73672. # endif
  73673. #else
  73674. extern void zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
  73675. extern int zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
  73676. extern void zmemzero OF((Bytef* dest, uInt len));
  73677. #endif
  73678. /* Diagnostic functions */
  73679. #ifdef DEBUG
  73680. # include <stdio.h>
  73681. extern int z_verbose;
  73682. extern void z_error OF((char *m));
  73683. # define Assert(cond,msg) {if(!(cond)) z_error(msg);}
  73684. # define Trace(x) {if (z_verbose>=0) fprintf x ;}
  73685. # define Tracev(x) {if (z_verbose>0) fprintf x ;}
  73686. # define Tracevv(x) {if (z_verbose>1) fprintf x ;}
  73687. # define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
  73688. # define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
  73689. #else
  73690. # define Assert(cond,msg)
  73691. # define Trace(x)
  73692. # define Tracev(x)
  73693. # define Tracevv(x)
  73694. # define Tracec(c,x)
  73695. # define Tracecv(c,x)
  73696. #endif
  73697. voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
  73698. void zcfree OF((voidpf opaque, voidpf ptr));
  73699. #define ZALLOC(strm, items, size) \
  73700. (*((strm)->zalloc))((strm)->opaque, (items), (size))
  73701. #define ZFREE(strm, addr) (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
  73702. #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
  73703. #endif /* ZUTIL_H */
  73704. /********* End of inlined file: zutil.h *********/
  73705. /* for STDC and FAR definitions */
  73706. #define local static
  73707. /* Find a four-byte integer type for crc32_little() and crc32_big(). */
  73708. #ifndef NOBYFOUR
  73709. # ifdef STDC /* need ANSI C limits.h to determine sizes */
  73710. # include <limits.h>
  73711. # define BYFOUR
  73712. # if (UINT_MAX == 0xffffffffUL)
  73713. typedef unsigned int u4;
  73714. # else
  73715. # if (ULONG_MAX == 0xffffffffUL)
  73716. typedef unsigned long u4;
  73717. # else
  73718. # if (USHRT_MAX == 0xffffffffUL)
  73719. typedef unsigned short u4;
  73720. # else
  73721. # undef BYFOUR /* can't find a four-byte integer type! */
  73722. # endif
  73723. # endif
  73724. # endif
  73725. # endif /* STDC */
  73726. #endif /* !NOBYFOUR */
  73727. /* Definitions for doing the crc four data bytes at a time. */
  73728. #ifdef BYFOUR
  73729. # define REV(w) (((w)>>24)+(((w)>>8)&0xff00)+ \
  73730. (((w)&0xff00)<<8)+(((w)&0xff)<<24))
  73731. local unsigned long crc32_little OF((unsigned long,
  73732. const unsigned char FAR *, unsigned));
  73733. local unsigned long crc32_big OF((unsigned long,
  73734. const unsigned char FAR *, unsigned));
  73735. # define TBLS 8
  73736. #else
  73737. # define TBLS 1
  73738. #endif /* BYFOUR */
  73739. /* Local functions for crc concatenation */
  73740. local unsigned long gf2_matrix_times OF((unsigned long *mat,
  73741. unsigned long vec));
  73742. local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
  73743. #ifdef DYNAMIC_CRC_TABLE
  73744. local volatile int crc_table_empty = 1;
  73745. local unsigned long FAR crc_table[TBLS][256];
  73746. local void make_crc_table OF((void));
  73747. #ifdef MAKECRCH
  73748. local void write_table OF((FILE *, const unsigned long FAR *));
  73749. #endif /* MAKECRCH */
  73750. /*
  73751. Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
  73752. 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.
  73753. Polynomials over GF(2) are represented in binary, one bit per coefficient,
  73754. with the lowest powers in the most significant bit. Then adding polynomials
  73755. is just exclusive-or, and multiplying a polynomial by x is a right shift by
  73756. one. If we call the above polynomial p, and represent a byte as the
  73757. polynomial q, also with the lowest power in the most significant bit (so the
  73758. byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
  73759. where a mod b means the remainder after dividing a by b.
  73760. This calculation is done using the shift-register method of multiplying and
  73761. taking the remainder. The register is initialized to zero, and for each
  73762. incoming bit, x^32 is added mod p to the register if the bit is a one (where
  73763. x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
  73764. x (which is shifting right by one and adding x^32 mod p if the bit shifted
  73765. out is a one). We start with the highest power (least significant bit) of
  73766. q and repeat for all eight bits of q.
  73767. The first table is simply the CRC of all possible eight bit values. This is
  73768. all the information needed to generate CRCs on data a byte at a time for all
  73769. combinations of CRC register values and incoming bytes. The remaining tables
  73770. allow for word-at-a-time CRC calculation for both big-endian and little-
  73771. endian machines, where a word is four bytes.
  73772. */
  73773. local void make_crc_table()
  73774. {
  73775. unsigned long c;
  73776. int n, k;
  73777. unsigned long poly; /* polynomial exclusive-or pattern */
  73778. /* terms of polynomial defining this crc (except x^32): */
  73779. static volatile int first = 1; /* flag to limit concurrent making */
  73780. static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
  73781. /* See if another task is already doing this (not thread-safe, but better
  73782. than nothing -- significantly reduces duration of vulnerability in
  73783. case the advice about DYNAMIC_CRC_TABLE is ignored) */
  73784. if (first) {
  73785. first = 0;
  73786. /* make exclusive-or pattern from polynomial (0xedb88320UL) */
  73787. poly = 0UL;
  73788. for (n = 0; n < sizeof(p)/sizeof(unsigned char); n++)
  73789. poly |= 1UL << (31 - p[n]);
  73790. /* generate a crc for every 8-bit value */
  73791. for (n = 0; n < 256; n++) {
  73792. c = (unsigned long)n;
  73793. for (k = 0; k < 8; k++)
  73794. c = c & 1 ? poly ^ (c >> 1) : c >> 1;
  73795. crc_table[0][n] = c;
  73796. }
  73797. #ifdef BYFOUR
  73798. /* generate crc for each value followed by one, two, and three zeros,
  73799. and then the byte reversal of those as well as the first table */
  73800. for (n = 0; n < 256; n++) {
  73801. c = crc_table[0][n];
  73802. crc_table[4][n] = REV(c);
  73803. for (k = 1; k < 4; k++) {
  73804. c = crc_table[0][c & 0xff] ^ (c >> 8);
  73805. crc_table[k][n] = c;
  73806. crc_table[k + 4][n] = REV(c);
  73807. }
  73808. }
  73809. #endif /* BYFOUR */
  73810. crc_table_empty = 0;
  73811. }
  73812. else { /* not first */
  73813. /* wait for the other guy to finish (not efficient, but rare) */
  73814. while (crc_table_empty)
  73815. ;
  73816. }
  73817. #ifdef MAKECRCH
  73818. /* write out CRC tables to crc32.h */
  73819. {
  73820. FILE *out;
  73821. out = fopen("crc32.h", "w");
  73822. if (out == NULL) return;
  73823. fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
  73824. fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
  73825. fprintf(out, "local const unsigned long FAR ");
  73826. fprintf(out, "crc_table[TBLS][256] =\n{\n {\n");
  73827. write_table(out, crc_table[0]);
  73828. # ifdef BYFOUR
  73829. fprintf(out, "#ifdef BYFOUR\n");
  73830. for (k = 1; k < 8; k++) {
  73831. fprintf(out, " },\n {\n");
  73832. write_table(out, crc_table[k]);
  73833. }
  73834. fprintf(out, "#endif\n");
  73835. # endif /* BYFOUR */
  73836. fprintf(out, " }\n};\n");
  73837. fclose(out);
  73838. }
  73839. #endif /* MAKECRCH */
  73840. }
  73841. #ifdef MAKECRCH
  73842. local void write_table(out, table)
  73843. FILE *out;
  73844. const unsigned long FAR *table;
  73845. {
  73846. int n;
  73847. for (n = 0; n < 256; n++)
  73848. fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : " ", table[n],
  73849. n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
  73850. }
  73851. #endif /* MAKECRCH */
  73852. #else /* !DYNAMIC_CRC_TABLE */
  73853. /* ========================================================================
  73854. * Tables of CRC-32s of all single-byte values, made by make_crc_table().
  73855. */
  73856. /********* Start of inlined file: crc32.h *********/
  73857. local const unsigned long FAR crc_table[TBLS][256] =
  73858. {
  73859. {
  73860. 0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
  73861. 0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
  73862. 0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
  73863. 0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
  73864. 0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
  73865. 0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
  73866. 0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
  73867. 0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
  73868. 0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
  73869. 0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
  73870. 0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
  73871. 0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
  73872. 0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
  73873. 0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
  73874. 0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
  73875. 0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
  73876. 0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
  73877. 0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
  73878. 0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
  73879. 0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
  73880. 0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
  73881. 0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
  73882. 0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
  73883. 0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
  73884. 0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
  73885. 0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
  73886. 0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
  73887. 0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
  73888. 0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
  73889. 0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
  73890. 0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
  73891. 0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
  73892. 0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
  73893. 0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
  73894. 0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
  73895. 0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
  73896. 0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
  73897. 0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
  73898. 0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
  73899. 0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
  73900. 0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
  73901. 0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
  73902. 0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
  73903. 0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
  73904. 0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
  73905. 0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
  73906. 0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
  73907. 0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
  73908. 0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
  73909. 0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
  73910. 0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
  73911. 0x2d02ef8dUL
  73912. #ifdef BYFOUR
  73913. },
  73914. {
  73915. 0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
  73916. 0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
  73917. 0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
  73918. 0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
  73919. 0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
  73920. 0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
  73921. 0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
  73922. 0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
  73923. 0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
  73924. 0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
  73925. 0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
  73926. 0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
  73927. 0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
  73928. 0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
  73929. 0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
  73930. 0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
  73931. 0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
  73932. 0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
  73933. 0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
  73934. 0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
  73935. 0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
  73936. 0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
  73937. 0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
  73938. 0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
  73939. 0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
  73940. 0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
  73941. 0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
  73942. 0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
  73943. 0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
  73944. 0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
  73945. 0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
  73946. 0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
  73947. 0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
  73948. 0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
  73949. 0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
  73950. 0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
  73951. 0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
  73952. 0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
  73953. 0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
  73954. 0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
  73955. 0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
  73956. 0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
  73957. 0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
  73958. 0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
  73959. 0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
  73960. 0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
  73961. 0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
  73962. 0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
  73963. 0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
  73964. 0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
  73965. 0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
  73966. 0x9324fd72UL
  73967. },
  73968. {
  73969. 0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
  73970. 0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
  73971. 0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
  73972. 0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
  73973. 0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
  73974. 0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
  73975. 0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
  73976. 0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
  73977. 0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
  73978. 0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
  73979. 0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
  73980. 0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
  73981. 0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
  73982. 0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
  73983. 0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
  73984. 0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
  73985. 0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
  73986. 0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
  73987. 0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
  73988. 0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
  73989. 0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
  73990. 0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
  73991. 0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
  73992. 0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
  73993. 0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
  73994. 0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
  73995. 0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
  73996. 0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
  73997. 0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
  73998. 0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
  73999. 0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
  74000. 0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
  74001. 0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
  74002. 0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
  74003. 0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
  74004. 0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
  74005. 0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
  74006. 0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
  74007. 0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
  74008. 0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
  74009. 0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
  74010. 0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
  74011. 0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
  74012. 0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
  74013. 0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
  74014. 0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
  74015. 0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
  74016. 0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
  74017. 0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
  74018. 0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
  74019. 0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
  74020. 0xbe9834edUL
  74021. },
  74022. {
  74023. 0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
  74024. 0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
  74025. 0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
  74026. 0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
  74027. 0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
  74028. 0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
  74029. 0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
  74030. 0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
  74031. 0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
  74032. 0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
  74033. 0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
  74034. 0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
  74035. 0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
  74036. 0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
  74037. 0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
  74038. 0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
  74039. 0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
  74040. 0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
  74041. 0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
  74042. 0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
  74043. 0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
  74044. 0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
  74045. 0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
  74046. 0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
  74047. 0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
  74048. 0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
  74049. 0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
  74050. 0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
  74051. 0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
  74052. 0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
  74053. 0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
  74054. 0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
  74055. 0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
  74056. 0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
  74057. 0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
  74058. 0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
  74059. 0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
  74060. 0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
  74061. 0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
  74062. 0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
  74063. 0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
  74064. 0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
  74065. 0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
  74066. 0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
  74067. 0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
  74068. 0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
  74069. 0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
  74070. 0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
  74071. 0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
  74072. 0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
  74073. 0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
  74074. 0xde0506f1UL
  74075. },
  74076. {
  74077. 0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
  74078. 0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
  74079. 0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
  74080. 0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
  74081. 0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
  74082. 0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
  74083. 0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
  74084. 0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
  74085. 0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
  74086. 0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
  74087. 0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
  74088. 0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
  74089. 0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
  74090. 0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
  74091. 0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
  74092. 0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
  74093. 0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
  74094. 0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
  74095. 0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
  74096. 0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
  74097. 0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
  74098. 0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
  74099. 0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
  74100. 0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
  74101. 0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
  74102. 0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
  74103. 0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
  74104. 0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
  74105. 0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
  74106. 0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
  74107. 0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
  74108. 0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
  74109. 0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
  74110. 0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
  74111. 0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
  74112. 0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
  74113. 0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
  74114. 0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
  74115. 0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
  74116. 0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
  74117. 0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
  74118. 0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
  74119. 0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
  74120. 0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
  74121. 0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
  74122. 0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
  74123. 0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
  74124. 0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
  74125. 0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
  74126. 0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
  74127. 0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
  74128. 0x8def022dUL
  74129. },
  74130. {
  74131. 0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
  74132. 0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
  74133. 0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
  74134. 0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
  74135. 0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
  74136. 0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
  74137. 0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
  74138. 0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
  74139. 0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
  74140. 0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
  74141. 0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
  74142. 0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
  74143. 0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
  74144. 0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
  74145. 0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
  74146. 0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
  74147. 0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
  74148. 0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
  74149. 0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
  74150. 0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
  74151. 0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
  74152. 0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
  74153. 0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
  74154. 0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
  74155. 0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
  74156. 0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
  74157. 0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
  74158. 0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
  74159. 0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
  74160. 0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
  74161. 0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
  74162. 0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
  74163. 0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
  74164. 0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
  74165. 0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
  74166. 0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
  74167. 0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
  74168. 0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
  74169. 0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
  74170. 0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
  74171. 0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
  74172. 0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
  74173. 0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
  74174. 0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
  74175. 0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
  74176. 0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
  74177. 0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
  74178. 0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
  74179. 0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
  74180. 0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
  74181. 0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
  74182. 0x72fd2493UL
  74183. },
  74184. {
  74185. 0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
  74186. 0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
  74187. 0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
  74188. 0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
  74189. 0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
  74190. 0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
  74191. 0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
  74192. 0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
  74193. 0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
  74194. 0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
  74195. 0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
  74196. 0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
  74197. 0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
  74198. 0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
  74199. 0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
  74200. 0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
  74201. 0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
  74202. 0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
  74203. 0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
  74204. 0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
  74205. 0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
  74206. 0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
  74207. 0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
  74208. 0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
  74209. 0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
  74210. 0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
  74211. 0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
  74212. 0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
  74213. 0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
  74214. 0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
  74215. 0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
  74216. 0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
  74217. 0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
  74218. 0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
  74219. 0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
  74220. 0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
  74221. 0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
  74222. 0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
  74223. 0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
  74224. 0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
  74225. 0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
  74226. 0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
  74227. 0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
  74228. 0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
  74229. 0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
  74230. 0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
  74231. 0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
  74232. 0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
  74233. 0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
  74234. 0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
  74235. 0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
  74236. 0xed3498beUL
  74237. },
  74238. {
  74239. 0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
  74240. 0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
  74241. 0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
  74242. 0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
  74243. 0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
  74244. 0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
  74245. 0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
  74246. 0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
  74247. 0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
  74248. 0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
  74249. 0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
  74250. 0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
  74251. 0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
  74252. 0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
  74253. 0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
  74254. 0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
  74255. 0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
  74256. 0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
  74257. 0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
  74258. 0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
  74259. 0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
  74260. 0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
  74261. 0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
  74262. 0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
  74263. 0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
  74264. 0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
  74265. 0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
  74266. 0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
  74267. 0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
  74268. 0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
  74269. 0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
  74270. 0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
  74271. 0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
  74272. 0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
  74273. 0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
  74274. 0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
  74275. 0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
  74276. 0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
  74277. 0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
  74278. 0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
  74279. 0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
  74280. 0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
  74281. 0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
  74282. 0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
  74283. 0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
  74284. 0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
  74285. 0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
  74286. 0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
  74287. 0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
  74288. 0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
  74289. 0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
  74290. 0xf10605deUL
  74291. #endif
  74292. }
  74293. };
  74294. /********* End of inlined file: crc32.h *********/
  74295. #endif /* DYNAMIC_CRC_TABLE */
  74296. /* =========================================================================
  74297. * This function can be used by asm versions of crc32()
  74298. */
  74299. const unsigned long FAR * ZEXPORT get_crc_table()
  74300. {
  74301. #ifdef DYNAMIC_CRC_TABLE
  74302. if (crc_table_empty)
  74303. make_crc_table();
  74304. #endif /* DYNAMIC_CRC_TABLE */
  74305. return (const unsigned long FAR *)crc_table;
  74306. }
  74307. /* ========================================================================= */
  74308. #define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
  74309. #define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
  74310. /* ========================================================================= */
  74311. unsigned long ZEXPORT crc32 (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  74312. {
  74313. if (buf == Z_NULL) return 0UL;
  74314. #ifdef DYNAMIC_CRC_TABLE
  74315. if (crc_table_empty)
  74316. make_crc_table();
  74317. #endif /* DYNAMIC_CRC_TABLE */
  74318. #ifdef BYFOUR
  74319. if (sizeof(void *) == sizeof(ptrdiff_t)) {
  74320. u4 endian;
  74321. endian = 1;
  74322. if (*((unsigned char *)(&endian)))
  74323. return crc32_little(crc, buf, len);
  74324. else
  74325. return crc32_big(crc, buf, len);
  74326. }
  74327. #endif /* BYFOUR */
  74328. crc = crc ^ 0xffffffffUL;
  74329. while (len >= 8) {
  74330. DO8;
  74331. len -= 8;
  74332. }
  74333. if (len) do {
  74334. DO1;
  74335. } while (--len);
  74336. return crc ^ 0xffffffffUL;
  74337. }
  74338. #ifdef BYFOUR
  74339. /* ========================================================================= */
  74340. #define DOLIT4 c ^= *buf4++; \
  74341. c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
  74342. crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
  74343. #define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
  74344. /* ========================================================================= */
  74345. local unsigned long crc32_little(unsigned long crc, const unsigned char FAR *buf, unsigned len)
  74346. {
  74347. register u4 c;
  74348. register const u4 FAR *buf4;
  74349. c = (u4)crc;
  74350. c = ~c;
  74351. while (len && ((ptrdiff_t)buf & 3)) {
  74352. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  74353. len--;
  74354. }
  74355. buf4 = (const u4 FAR *)(const void FAR *)buf;
  74356. while (len >= 32) {
  74357. DOLIT32;
  74358. len -= 32;
  74359. }
  74360. while (len >= 4) {
  74361. DOLIT4;
  74362. len -= 4;
  74363. }
  74364. buf = (const unsigned char FAR *)buf4;
  74365. if (len) do {
  74366. c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
  74367. } while (--len);
  74368. c = ~c;
  74369. return (unsigned long)c;
  74370. }
  74371. /* ========================================================================= */
  74372. #define DOBIG4 c ^= *++buf4; \
  74373. c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
  74374. crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
  74375. #define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
  74376. /* ========================================================================= */
  74377. local unsigned long crc32_big (unsigned long crc, const unsigned char FAR *buf, unsigned len)
  74378. {
  74379. register u4 c;
  74380. register const u4 FAR *buf4;
  74381. c = REV((u4)crc);
  74382. c = ~c;
  74383. while (len && ((ptrdiff_t)buf & 3)) {
  74384. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  74385. len--;
  74386. }
  74387. buf4 = (const u4 FAR *)(const void FAR *)buf;
  74388. buf4--;
  74389. while (len >= 32) {
  74390. DOBIG32;
  74391. len -= 32;
  74392. }
  74393. while (len >= 4) {
  74394. DOBIG4;
  74395. len -= 4;
  74396. }
  74397. buf4++;
  74398. buf = (const unsigned char FAR *)buf4;
  74399. if (len) do {
  74400. c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
  74401. } while (--len);
  74402. c = ~c;
  74403. return (unsigned long)(REV(c));
  74404. }
  74405. #endif /* BYFOUR */
  74406. #define GF2_DIM 32 /* dimension of GF(2) vectors (length of CRC) */
  74407. /* ========================================================================= */
  74408. local unsigned long gf2_matrix_times (unsigned long *mat, unsigned long vec)
  74409. {
  74410. unsigned long sum;
  74411. sum = 0;
  74412. while (vec) {
  74413. if (vec & 1)
  74414. sum ^= *mat;
  74415. vec >>= 1;
  74416. mat++;
  74417. }
  74418. return sum;
  74419. }
  74420. /* ========================================================================= */
  74421. local void gf2_matrix_square (unsigned long *square, unsigned long *mat)
  74422. {
  74423. int n;
  74424. for (n = 0; n < GF2_DIM; n++)
  74425. square[n] = gf2_matrix_times(mat, mat[n]);
  74426. }
  74427. /* ========================================================================= */
  74428. uLong ZEXPORT crc32_combine (uLong crc1, uLong crc2, z_off_t len2)
  74429. {
  74430. int n;
  74431. unsigned long row;
  74432. unsigned long even[GF2_DIM]; /* even-power-of-two zeros operator */
  74433. unsigned long odd[GF2_DIM]; /* odd-power-of-two zeros operator */
  74434. /* degenerate case */
  74435. if (len2 == 0)
  74436. return crc1;
  74437. /* put operator for one zero bit in odd */
  74438. odd[0] = 0xedb88320L; /* CRC-32 polynomial */
  74439. row = 1;
  74440. for (n = 1; n < GF2_DIM; n++) {
  74441. odd[n] = row;
  74442. row <<= 1;
  74443. }
  74444. /* put operator for two zero bits in even */
  74445. gf2_matrix_square(even, odd);
  74446. /* put operator for four zero bits in odd */
  74447. gf2_matrix_square(odd, even);
  74448. /* apply len2 zeros to crc1 (first square will put the operator for one
  74449. zero byte, eight zero bits, in even) */
  74450. do {
  74451. /* apply zeros operator for this bit of len2 */
  74452. gf2_matrix_square(even, odd);
  74453. if (len2 & 1)
  74454. crc1 = gf2_matrix_times(even, crc1);
  74455. len2 >>= 1;
  74456. /* if no more bits set, then done */
  74457. if (len2 == 0)
  74458. break;
  74459. /* another iteration of the loop with odd and even swapped */
  74460. gf2_matrix_square(odd, even);
  74461. if (len2 & 1)
  74462. crc1 = gf2_matrix_times(odd, crc1);
  74463. len2 >>= 1;
  74464. /* if no more bits set, then done */
  74465. } while (len2 != 0);
  74466. /* return combined crc */
  74467. crc1 ^= crc2;
  74468. return crc1;
  74469. }
  74470. /********* End of inlined file: crc32.c *********/
  74471. /********* Start of inlined file: deflate.c *********/
  74472. /*
  74473. * ALGORITHM
  74474. *
  74475. * The "deflation" process depends on being able to identify portions
  74476. * of the input text which are identical to earlier input (within a
  74477. * sliding window trailing behind the input currently being processed).
  74478. *
  74479. * The most straightforward technique turns out to be the fastest for
  74480. * most input files: try all possible matches and select the longest.
  74481. * The key feature of this algorithm is that insertions into the string
  74482. * dictionary are very simple and thus fast, and deletions are avoided
  74483. * completely. Insertions are performed at each input character, whereas
  74484. * string matches are performed only when the previous match ends. So it
  74485. * is preferable to spend more time in matches to allow very fast string
  74486. * insertions and avoid deletions. The matching algorithm for small
  74487. * strings is inspired from that of Rabin & Karp. A brute force approach
  74488. * is used to find longer strings when a small match has been found.
  74489. * A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
  74490. * (by Leonid Broukhis).
  74491. * A previous version of this file used a more sophisticated algorithm
  74492. * (by Fiala and Greene) which is guaranteed to run in linear amortized
  74493. * time, but has a larger average cost, uses more memory and is patented.
  74494. * However the F&G algorithm may be faster for some highly redundant
  74495. * files if the parameter max_chain_length (described below) is too large.
  74496. *
  74497. * ACKNOWLEDGEMENTS
  74498. *
  74499. * The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
  74500. * I found it in 'freeze' written by Leonid Broukhis.
  74501. * Thanks to many people for bug reports and testing.
  74502. *
  74503. * REFERENCES
  74504. *
  74505. * Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
  74506. * Available in http://www.ietf.org/rfc/rfc1951.txt
  74507. *
  74508. * A description of the Rabin and Karp algorithm is given in the book
  74509. * "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
  74510. *
  74511. * Fiala,E.R., and Greene,D.H.
  74512. * Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
  74513. *
  74514. */
  74515. /* @(#) $Id: deflate.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74516. /********* Start of inlined file: deflate.h *********/
  74517. /* WARNING: this file should *not* be used by applications. It is
  74518. part of the implementation of the compression library and is
  74519. subject to change. Applications should only use zlib.h.
  74520. */
  74521. /* @(#) $Id: deflate.h,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  74522. #ifndef DEFLATE_H
  74523. #define DEFLATE_H
  74524. /* define NO_GZIP when compiling if you want to disable gzip header and
  74525. trailer creation by deflate(). NO_GZIP would be used to avoid linking in
  74526. the crc code when it is not needed. For shared libraries, gzip encoding
  74527. should be left enabled. */
  74528. #ifndef NO_GZIP
  74529. # define GZIP
  74530. #endif
  74531. #define NO_DUMMY_DECL
  74532. /* ===========================================================================
  74533. * Internal compression state.
  74534. */
  74535. #define LENGTH_CODES 29
  74536. /* number of length codes, not counting the special END_BLOCK code */
  74537. #define LITERALS 256
  74538. /* number of literal bytes 0..255 */
  74539. #define L_CODES (LITERALS+1+LENGTH_CODES)
  74540. /* number of Literal or Length codes, including the END_BLOCK code */
  74541. #define D_CODES 30
  74542. /* number of distance codes */
  74543. #define BL_CODES 19
  74544. /* number of codes used to transfer the bit lengths */
  74545. #define HEAP_SIZE (2*L_CODES+1)
  74546. /* maximum heap size */
  74547. #define MAX_BITS 15
  74548. /* All codes must not exceed MAX_BITS bits */
  74549. #define INIT_STATE 42
  74550. #define EXTRA_STATE 69
  74551. #define NAME_STATE 73
  74552. #define COMMENT_STATE 91
  74553. #define HCRC_STATE 103
  74554. #define BUSY_STATE 113
  74555. #define FINISH_STATE 666
  74556. /* Stream status */
  74557. /* Data structure describing a single value and its code string. */
  74558. typedef struct ct_data_s {
  74559. union {
  74560. ush freq; /* frequency count */
  74561. ush code; /* bit string */
  74562. } fc;
  74563. union {
  74564. ush dad; /* father node in Huffman tree */
  74565. ush len; /* length of bit string */
  74566. } dl;
  74567. } FAR ct_data;
  74568. #define Freq fc.freq
  74569. #define Code fc.code
  74570. #define Dad dl.dad
  74571. #define Len dl.len
  74572. typedef struct static_tree_desc_s static_tree_desc;
  74573. typedef struct tree_desc_s {
  74574. ct_data *dyn_tree; /* the dynamic tree */
  74575. int max_code; /* largest code with non zero frequency */
  74576. static_tree_desc *stat_desc; /* the corresponding static tree */
  74577. } FAR tree_desc;
  74578. typedef ush Pos;
  74579. typedef Pos FAR Posf;
  74580. typedef unsigned IPos;
  74581. /* A Pos is an index in the character window. We use short instead of int to
  74582. * save space in the various tables. IPos is used only for parameter passing.
  74583. */
  74584. typedef struct internal_state {
  74585. z_streamp strm; /* pointer back to this zlib stream */
  74586. int status; /* as the name implies */
  74587. Bytef *pending_buf; /* output still pending */
  74588. ulg pending_buf_size; /* size of pending_buf */
  74589. Bytef *pending_out; /* next pending byte to output to the stream */
  74590. uInt pending; /* nb of bytes in the pending buffer */
  74591. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  74592. gz_headerp gzhead; /* gzip header information to write */
  74593. uInt gzindex; /* where in extra, name, or comment */
  74594. Byte method; /* STORED (for zip only) or DEFLATED */
  74595. int last_flush; /* value of flush param for previous deflate call */
  74596. /* used by deflate.c: */
  74597. uInt w_size; /* LZ77 window size (32K by default) */
  74598. uInt w_bits; /* log2(w_size) (8..16) */
  74599. uInt w_mask; /* w_size - 1 */
  74600. Bytef *window;
  74601. /* Sliding window. Input bytes are read into the second half of the window,
  74602. * and move to the first half later to keep a dictionary of at least wSize
  74603. * bytes. With this organization, matches are limited to a distance of
  74604. * wSize-MAX_MATCH bytes, but this ensures that IO is always
  74605. * performed with a length multiple of the block size. Also, it limits
  74606. * the window size to 64K, which is quite useful on MSDOS.
  74607. * To do: use the user input buffer as sliding window.
  74608. */
  74609. ulg window_size;
  74610. /* Actual size of window: 2*wSize, except when the user input buffer
  74611. * is directly used as sliding window.
  74612. */
  74613. Posf *prev;
  74614. /* Link to older string with same hash index. To limit the size of this
  74615. * array to 64K, this link is maintained only for the last 32K strings.
  74616. * An index in this array is thus a window index modulo 32K.
  74617. */
  74618. Posf *head; /* Heads of the hash chains or NIL. */
  74619. uInt ins_h; /* hash index of string to be inserted */
  74620. uInt hash_size; /* number of elements in hash table */
  74621. uInt hash_bits; /* log2(hash_size) */
  74622. uInt hash_mask; /* hash_size-1 */
  74623. uInt hash_shift;
  74624. /* Number of bits by which ins_h must be shifted at each input
  74625. * step. It must be such that after MIN_MATCH steps, the oldest
  74626. * byte no longer takes part in the hash key, that is:
  74627. * hash_shift * MIN_MATCH >= hash_bits
  74628. */
  74629. long block_start;
  74630. /* Window position at the beginning of the current output block. Gets
  74631. * negative when the window is moved backwards.
  74632. */
  74633. uInt match_length; /* length of best match */
  74634. IPos prev_match; /* previous match */
  74635. int match_available; /* set if previous match exists */
  74636. uInt strstart; /* start of string to insert */
  74637. uInt match_start; /* start of matching string */
  74638. uInt lookahead; /* number of valid bytes ahead in window */
  74639. uInt prev_length;
  74640. /* Length of the best match at previous step. Matches not greater than this
  74641. * are discarded. This is used in the lazy match evaluation.
  74642. */
  74643. uInt max_chain_length;
  74644. /* To speed up deflation, hash chains are never searched beyond this
  74645. * length. A higher limit improves compression ratio but degrades the
  74646. * speed.
  74647. */
  74648. uInt max_lazy_match;
  74649. /* Attempt to find a better match only when the current match is strictly
  74650. * smaller than this value. This mechanism is used only for compression
  74651. * levels >= 4.
  74652. */
  74653. # define max_insert_length max_lazy_match
  74654. /* Insert new strings in the hash table only if the match length is not
  74655. * greater than this length. This saves time but degrades compression.
  74656. * max_insert_length is used only for compression levels <= 3.
  74657. */
  74658. int level; /* compression level (1..9) */
  74659. int strategy; /* favor or force Huffman coding*/
  74660. uInt good_match;
  74661. /* Use a faster search when the previous match is longer than this */
  74662. int nice_match; /* Stop searching when current match exceeds this */
  74663. /* used by trees.c: */
  74664. /* Didn't use ct_data typedef below to supress compiler warning */
  74665. struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
  74666. struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
  74667. struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
  74668. struct tree_desc_s l_desc; /* desc. for literal tree */
  74669. struct tree_desc_s d_desc; /* desc. for distance tree */
  74670. struct tree_desc_s bl_desc; /* desc. for bit length tree */
  74671. ush bl_count[MAX_BITS+1];
  74672. /* number of codes at each bit length for an optimal tree */
  74673. int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
  74674. int heap_len; /* number of elements in the heap */
  74675. int heap_max; /* element of largest frequency */
  74676. /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
  74677. * The same heap array is used to build all trees.
  74678. */
  74679. uch depth[2*L_CODES+1];
  74680. /* Depth of each subtree used as tie breaker for trees of equal frequency
  74681. */
  74682. uchf *l_buf; /* buffer for literals or lengths */
  74683. uInt lit_bufsize;
  74684. /* Size of match buffer for literals/lengths. There are 4 reasons for
  74685. * limiting lit_bufsize to 64K:
  74686. * - frequencies can be kept in 16 bit counters
  74687. * - if compression is not successful for the first block, all input
  74688. * data is still in the window so we can still emit a stored block even
  74689. * when input comes from standard input. (This can also be done for
  74690. * all blocks if lit_bufsize is not greater than 32K.)
  74691. * - if compression is not successful for a file smaller than 64K, we can
  74692. * even emit a stored file instead of a stored block (saving 5 bytes).
  74693. * This is applicable only for zip (not gzip or zlib).
  74694. * - creating new Huffman trees less frequently may not provide fast
  74695. * adaptation to changes in the input data statistics. (Take for
  74696. * example a binary file with poorly compressible code followed by
  74697. * a highly compressible string table.) Smaller buffer sizes give
  74698. * fast adaptation but have of course the overhead of transmitting
  74699. * trees more frequently.
  74700. * - I can't count above 4
  74701. */
  74702. uInt last_lit; /* running index in l_buf */
  74703. ushf *d_buf;
  74704. /* Buffer for distances. To simplify the code, d_buf and l_buf have
  74705. * the same number of elements. To use different lengths, an extra flag
  74706. * array would be necessary.
  74707. */
  74708. ulg opt_len; /* bit length of current block with optimal trees */
  74709. ulg static_len; /* bit length of current block with static trees */
  74710. uInt matches; /* number of string matches in current block */
  74711. int last_eob_len; /* bit length of EOB code for last block */
  74712. #ifdef DEBUG
  74713. ulg compressed_len; /* total bit length of compressed file mod 2^32 */
  74714. ulg bits_sent; /* bit length of compressed data sent mod 2^32 */
  74715. #endif
  74716. ush bi_buf;
  74717. /* Output buffer. bits are inserted starting at the bottom (least
  74718. * significant bits).
  74719. */
  74720. int bi_valid;
  74721. /* Number of valid bits in bi_buf. All bits above the last valid bit
  74722. * are always zero.
  74723. */
  74724. } FAR deflate_state;
  74725. /* Output a byte on the stream.
  74726. * IN assertion: there is enough room in pending_buf.
  74727. */
  74728. #define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
  74729. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  74730. /* Minimum amount of lookahead, except at the end of the input file.
  74731. * See deflate.c for comments about the MIN_MATCH+1.
  74732. */
  74733. #define MAX_DIST(s) ((s)->w_size-MIN_LOOKAHEAD)
  74734. /* In order to simplify the code, particularly on 16 bit machines, match
  74735. * distances are limited to MAX_DIST instead of WSIZE.
  74736. */
  74737. /* in trees.c */
  74738. void _tr_init OF((deflate_state *s));
  74739. int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
  74740. void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
  74741. int eof));
  74742. void _tr_align OF((deflate_state *s));
  74743. void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
  74744. int eof));
  74745. #define d_code(dist) \
  74746. ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
  74747. /* Mapping from a distance to a distance code. dist is the distance - 1 and
  74748. * must not have side effects. _dist_code[256] and _dist_code[257] are never
  74749. * used.
  74750. */
  74751. #ifndef DEBUG
  74752. /* Inline versions of _tr_tally for speed: */
  74753. #if defined(GEN_TREES_H) || !defined(STDC)
  74754. extern uch _length_code[];
  74755. extern uch _dist_code[];
  74756. #else
  74757. extern const uch _length_code[];
  74758. extern const uch _dist_code[];
  74759. #endif
  74760. # define _tr_tally_lit(s, c, flush) \
  74761. { uch cc = (c); \
  74762. s->d_buf[s->last_lit] = 0; \
  74763. s->l_buf[s->last_lit++] = cc; \
  74764. s->dyn_ltree[cc].Freq++; \
  74765. flush = (s->last_lit == s->lit_bufsize-1); \
  74766. }
  74767. # define _tr_tally_dist(s, distance, length, flush) \
  74768. { uch len = (length); \
  74769. ush dist = (distance); \
  74770. s->d_buf[s->last_lit] = dist; \
  74771. s->l_buf[s->last_lit++] = len; \
  74772. dist--; \
  74773. s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
  74774. s->dyn_dtree[d_code(dist)].Freq++; \
  74775. flush = (s->last_lit == s->lit_bufsize-1); \
  74776. }
  74777. #else
  74778. # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
  74779. # define _tr_tally_dist(s, distance, length, flush) \
  74780. flush = _tr_tally(s, distance, length)
  74781. #endif
  74782. #endif /* DEFLATE_H */
  74783. /********* End of inlined file: deflate.h *********/
  74784. const char deflate_copyright[] =
  74785. " deflate 1.2.3 Copyright 1995-2005 Jean-loup Gailly ";
  74786. /*
  74787. If you use the zlib library in a product, an acknowledgment is welcome
  74788. in the documentation of your product. If for some reason you cannot
  74789. include such an acknowledgment, I would appreciate that you keep this
  74790. copyright string in the executable of your product.
  74791. */
  74792. /* ===========================================================================
  74793. * Function prototypes.
  74794. */
  74795. typedef enum {
  74796. need_more, /* block not completed, need more input or more output */
  74797. block_done, /* block flush performed */
  74798. finish_started, /* finish started, need only more output at next deflate */
  74799. finish_done /* finish done, accept no more input or output */
  74800. } block_state;
  74801. typedef block_state (*compress_func) OF((deflate_state *s, int flush));
  74802. /* Compression function. Returns the block state after the call. */
  74803. local void fill_window OF((deflate_state *s));
  74804. local block_state deflate_stored OF((deflate_state *s, int flush));
  74805. local block_state deflate_fast OF((deflate_state *s, int flush));
  74806. #ifndef FASTEST
  74807. local block_state deflate_slow OF((deflate_state *s, int flush));
  74808. #endif
  74809. local void lm_init OF((deflate_state *s));
  74810. local void putShortMSB OF((deflate_state *s, uInt b));
  74811. local void flush_pending OF((z_streamp strm));
  74812. local int read_buf OF((z_streamp strm, Bytef *buf, unsigned size));
  74813. #ifndef FASTEST
  74814. #ifdef ASMV
  74815. void match_init OF((void)); /* asm code initialization */
  74816. uInt longest_match OF((deflate_state *s, IPos cur_match));
  74817. #else
  74818. local uInt longest_match OF((deflate_state *s, IPos cur_match));
  74819. #endif
  74820. #endif
  74821. local uInt longest_match_fast OF((deflate_state *s, IPos cur_match));
  74822. #ifdef DEBUG
  74823. local void check_match OF((deflate_state *s, IPos start, IPos match,
  74824. int length));
  74825. #endif
  74826. /* ===========================================================================
  74827. * Local data
  74828. */
  74829. #define NIL 0
  74830. /* Tail of hash chains */
  74831. #ifndef TOO_FAR
  74832. # define TOO_FAR 4096
  74833. #endif
  74834. /* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
  74835. #define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
  74836. /* Minimum amount of lookahead, except at the end of the input file.
  74837. * See deflate.c for comments about the MIN_MATCH+1.
  74838. */
  74839. /* Values for max_lazy_match, good_match and max_chain_length, depending on
  74840. * the desired pack level (0..9). The values given below have been tuned to
  74841. * exclude worst case performance for pathological files. Better values may be
  74842. * found for specific files.
  74843. */
  74844. typedef struct config_s {
  74845. ush good_length; /* reduce lazy search above this match length */
  74846. ush max_lazy; /* do not perform lazy search above this match length */
  74847. ush nice_length; /* quit search above this match length */
  74848. ush max_chain;
  74849. compress_func func;
  74850. } config;
  74851. #ifdef FASTEST
  74852. local const config configuration_table[2] = {
  74853. /* good lazy nice chain */
  74854. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  74855. /* 1 */ {4, 4, 8, 4, deflate_fast}}; /* max speed, no lazy matches */
  74856. #else
  74857. local const config configuration_table[10] = {
  74858. /* good lazy nice chain */
  74859. /* 0 */ {0, 0, 0, 0, deflate_stored}, /* store only */
  74860. /* 1 */ {4, 4, 8, 4, deflate_fast}, /* max speed, no lazy matches */
  74861. /* 2 */ {4, 5, 16, 8, deflate_fast},
  74862. /* 3 */ {4, 6, 32, 32, deflate_fast},
  74863. /* 4 */ {4, 4, 16, 16, deflate_slow}, /* lazy matches */
  74864. /* 5 */ {8, 16, 32, 32, deflate_slow},
  74865. /* 6 */ {8, 16, 128, 128, deflate_slow},
  74866. /* 7 */ {8, 32, 128, 256, deflate_slow},
  74867. /* 8 */ {32, 128, 258, 1024, deflate_slow},
  74868. /* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
  74869. #endif
  74870. /* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
  74871. * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
  74872. * meaning.
  74873. */
  74874. #define EQUAL 0
  74875. /* result of memcmp for equal strings */
  74876. #ifndef NO_DUMMY_DECL
  74877. struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
  74878. #endif
  74879. /* ===========================================================================
  74880. * Update a hash value with the given input byte
  74881. * IN assertion: all calls to to UPDATE_HASH are made with consecutive
  74882. * input characters, so that a running hash key can be computed from the
  74883. * previous key instead of complete recalculation each time.
  74884. */
  74885. #define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
  74886. /* ===========================================================================
  74887. * Insert string str in the dictionary and set match_head to the previous head
  74888. * of the hash chain (the most recent string with same hash key). Return
  74889. * the previous length of the hash chain.
  74890. * If this file is compiled with -DFASTEST, the compression level is forced
  74891. * to 1, and no hash chains are maintained.
  74892. * IN assertion: all calls to to INSERT_STRING are made with consecutive
  74893. * input characters and the first MIN_MATCH bytes of str are valid
  74894. * (except for the last MIN_MATCH-1 bytes of the input file).
  74895. */
  74896. #ifdef FASTEST
  74897. #define INSERT_STRING(s, str, match_head) \
  74898. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  74899. match_head = s->head[s->ins_h], \
  74900. s->head[s->ins_h] = (Pos)(str))
  74901. #else
  74902. #define INSERT_STRING(s, str, match_head) \
  74903. (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
  74904. match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
  74905. s->head[s->ins_h] = (Pos)(str))
  74906. #endif
  74907. /* ===========================================================================
  74908. * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
  74909. * prev[] will be initialized on the fly.
  74910. */
  74911. #define CLEAR_HASH(s) \
  74912. s->head[s->hash_size-1] = NIL; \
  74913. zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
  74914. /* ========================================================================= */
  74915. int ZEXPORT deflateInit_(z_streamp strm, int level, const char *version, int stream_size)
  74916. {
  74917. return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
  74918. Z_DEFAULT_STRATEGY, version, stream_size);
  74919. /* To do: ignore strm->next_in if we use it as window */
  74920. }
  74921. /* ========================================================================= */
  74922. int ZEXPORT deflateInit2_ (z_streamp strm, int level, int method, int windowBits, int memLevel, int strategy, const char *version, int stream_size)
  74923. {
  74924. deflate_state *s;
  74925. int wrap = 1;
  74926. static const char my_version[] = ZLIB_VERSION;
  74927. ushf *overlay;
  74928. /* We overlay pending_buf and d_buf+l_buf. This works since the average
  74929. * output size for (length,distance) codes is <= 24 bits.
  74930. */
  74931. if (version == Z_NULL || version[0] != my_version[0] ||
  74932. stream_size != sizeof(z_stream)) {
  74933. return Z_VERSION_ERROR;
  74934. }
  74935. if (strm == Z_NULL) return Z_STREAM_ERROR;
  74936. strm->msg = Z_NULL;
  74937. if (strm->zalloc == (alloc_func)0) {
  74938. strm->zalloc = zcalloc;
  74939. strm->opaque = (voidpf)0;
  74940. }
  74941. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  74942. #ifdef FASTEST
  74943. if (level != 0) level = 1;
  74944. #else
  74945. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  74946. #endif
  74947. if (windowBits < 0) { /* suppress zlib wrapper */
  74948. wrap = 0;
  74949. windowBits = -windowBits;
  74950. }
  74951. #ifdef GZIP
  74952. else if (windowBits > 15) {
  74953. wrap = 2; /* write gzip wrapper instead */
  74954. windowBits -= 16;
  74955. }
  74956. #endif
  74957. if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
  74958. windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
  74959. strategy < 0 || strategy > Z_FIXED) {
  74960. return Z_STREAM_ERROR;
  74961. }
  74962. if (windowBits == 8) windowBits = 9; /* until 256-byte window bug fixed */
  74963. s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
  74964. if (s == Z_NULL) return Z_MEM_ERROR;
  74965. strm->state = (struct internal_state FAR *)s;
  74966. s->strm = strm;
  74967. s->wrap = wrap;
  74968. s->gzhead = Z_NULL;
  74969. s->w_bits = windowBits;
  74970. s->w_size = 1 << s->w_bits;
  74971. s->w_mask = s->w_size - 1;
  74972. s->hash_bits = memLevel + 7;
  74973. s->hash_size = 1 << s->hash_bits;
  74974. s->hash_mask = s->hash_size - 1;
  74975. s->hash_shift = ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
  74976. s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
  74977. s->prev = (Posf *) ZALLOC(strm, s->w_size, sizeof(Pos));
  74978. s->head = (Posf *) ZALLOC(strm, s->hash_size, sizeof(Pos));
  74979. s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
  74980. overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
  74981. s->pending_buf = (uchf *) overlay;
  74982. s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
  74983. if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
  74984. s->pending_buf == Z_NULL) {
  74985. s->status = FINISH_STATE;
  74986. strm->msg = (char*)ERR_MSG(Z_MEM_ERROR);
  74987. deflateEnd (strm);
  74988. return Z_MEM_ERROR;
  74989. }
  74990. s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
  74991. s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
  74992. s->level = level;
  74993. s->strategy = strategy;
  74994. s->method = (Byte)method;
  74995. return deflateReset(strm);
  74996. }
  74997. /* ========================================================================= */
  74998. int ZEXPORT deflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  74999. {
  75000. deflate_state *s;
  75001. uInt length = dictLength;
  75002. uInt n;
  75003. IPos hash_head = 0;
  75004. if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL ||
  75005. strm->state->wrap == 2 ||
  75006. (strm->state->wrap == 1 && strm->state->status != INIT_STATE))
  75007. return Z_STREAM_ERROR;
  75008. s = strm->state;
  75009. if (s->wrap)
  75010. strm->adler = adler32(strm->adler, dictionary, dictLength);
  75011. if (length < MIN_MATCH) return Z_OK;
  75012. if (length > MAX_DIST(s)) {
  75013. length = MAX_DIST(s);
  75014. dictionary += dictLength - length; /* use the tail of the dictionary */
  75015. }
  75016. zmemcpy(s->window, dictionary, length);
  75017. s->strstart = length;
  75018. s->block_start = (long)length;
  75019. /* Insert all strings in the hash table (except for the last two bytes).
  75020. * s->lookahead stays null, so s->ins_h will be recomputed at the next
  75021. * call of fill_window.
  75022. */
  75023. s->ins_h = s->window[0];
  75024. UPDATE_HASH(s, s->ins_h, s->window[1]);
  75025. for (n = 0; n <= length - MIN_MATCH; n++) {
  75026. INSERT_STRING(s, n, hash_head);
  75027. }
  75028. if (hash_head) hash_head = 0; /* to make compiler happy */
  75029. return Z_OK;
  75030. }
  75031. /* ========================================================================= */
  75032. int ZEXPORT deflateReset (z_streamp strm)
  75033. {
  75034. deflate_state *s;
  75035. if (strm == Z_NULL || strm->state == Z_NULL ||
  75036. strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
  75037. return Z_STREAM_ERROR;
  75038. }
  75039. strm->total_in = strm->total_out = 0;
  75040. strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
  75041. strm->data_type = Z_UNKNOWN;
  75042. s = (deflate_state *)strm->state;
  75043. s->pending = 0;
  75044. s->pending_out = s->pending_buf;
  75045. if (s->wrap < 0) {
  75046. s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
  75047. }
  75048. s->status = s->wrap ? INIT_STATE : BUSY_STATE;
  75049. strm->adler =
  75050. #ifdef GZIP
  75051. s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
  75052. #endif
  75053. adler32(0L, Z_NULL, 0);
  75054. s->last_flush = Z_NO_FLUSH;
  75055. _tr_init(s);
  75056. lm_init(s);
  75057. return Z_OK;
  75058. }
  75059. /* ========================================================================= */
  75060. int ZEXPORT deflateSetHeader (z_streamp strm, gz_headerp head)
  75061. {
  75062. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  75063. if (strm->state->wrap != 2) return Z_STREAM_ERROR;
  75064. strm->state->gzhead = head;
  75065. return Z_OK;
  75066. }
  75067. /* ========================================================================= */
  75068. int ZEXPORT deflatePrime (z_streamp strm, int bits, int value)
  75069. {
  75070. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  75071. strm->state->bi_valid = bits;
  75072. strm->state->bi_buf = (ush)(value & ((1 << bits) - 1));
  75073. return Z_OK;
  75074. }
  75075. /* ========================================================================= */
  75076. int ZEXPORT deflateParams (z_streamp strm, int level, int strategy)
  75077. {
  75078. deflate_state *s;
  75079. compress_func func;
  75080. int err = Z_OK;
  75081. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  75082. s = strm->state;
  75083. #ifdef FASTEST
  75084. if (level != 0) level = 1;
  75085. #else
  75086. if (level == Z_DEFAULT_COMPRESSION) level = 6;
  75087. #endif
  75088. if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
  75089. return Z_STREAM_ERROR;
  75090. }
  75091. func = configuration_table[s->level].func;
  75092. if (func != configuration_table[level].func && strm->total_in != 0) {
  75093. /* Flush the last buffer: */
  75094. err = deflate(strm, Z_PARTIAL_FLUSH);
  75095. }
  75096. if (s->level != level) {
  75097. s->level = level;
  75098. s->max_lazy_match = configuration_table[level].max_lazy;
  75099. s->good_match = configuration_table[level].good_length;
  75100. s->nice_match = configuration_table[level].nice_length;
  75101. s->max_chain_length = configuration_table[level].max_chain;
  75102. }
  75103. s->strategy = strategy;
  75104. return err;
  75105. }
  75106. /* ========================================================================= */
  75107. int ZEXPORT deflateTune (z_streamp strm, int good_length, int max_lazy, int nice_length, int max_chain)
  75108. {
  75109. deflate_state *s;
  75110. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  75111. s = strm->state;
  75112. s->good_match = good_length;
  75113. s->max_lazy_match = max_lazy;
  75114. s->nice_match = nice_length;
  75115. s->max_chain_length = max_chain;
  75116. return Z_OK;
  75117. }
  75118. /* =========================================================================
  75119. * For the default windowBits of 15 and memLevel of 8, this function returns
  75120. * a close to exact, as well as small, upper bound on the compressed size.
  75121. * They are coded as constants here for a reason--if the #define's are
  75122. * changed, then this function needs to be changed as well. The return
  75123. * value for 15 and 8 only works for those exact settings.
  75124. *
  75125. * For any setting other than those defaults for windowBits and memLevel,
  75126. * the value returned is a conservative worst case for the maximum expansion
  75127. * resulting from using fixed blocks instead of stored blocks, which deflate
  75128. * can emit on compressed data for some combinations of the parameters.
  75129. *
  75130. * This function could be more sophisticated to provide closer upper bounds
  75131. * for every combination of windowBits and memLevel, as well as wrap.
  75132. * But even the conservative upper bound of about 14% expansion does not
  75133. * seem onerous for output buffer allocation.
  75134. */
  75135. uLong ZEXPORT deflateBound (z_streamp strm, uLong sourceLen)
  75136. {
  75137. deflate_state *s;
  75138. uLong destLen;
  75139. /* conservative upper bound */
  75140. destLen = sourceLen +
  75141. ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 11;
  75142. /* if can't get parameters, return conservative bound */
  75143. if (strm == Z_NULL || strm->state == Z_NULL)
  75144. return destLen;
  75145. /* if not default parameters, return conservative bound */
  75146. s = strm->state;
  75147. if (s->w_bits != 15 || s->hash_bits != 8 + 7)
  75148. return destLen;
  75149. /* default settings: return tight bound for that case */
  75150. return compressBound(sourceLen);
  75151. }
  75152. /* =========================================================================
  75153. * Put a short in the pending buffer. The 16-bit value is put in MSB order.
  75154. * IN assertion: the stream state is correct and there is enough room in
  75155. * pending_buf.
  75156. */
  75157. local void putShortMSB (deflate_state *s, uInt b)
  75158. {
  75159. put_byte(s, (Byte)(b >> 8));
  75160. put_byte(s, (Byte)(b & 0xff));
  75161. }
  75162. /* =========================================================================
  75163. * Flush as much pending output as possible. All deflate() output goes
  75164. * through this function so some applications may wish to modify it
  75165. * to avoid allocating a large strm->next_out buffer and copying into it.
  75166. * (See also read_buf()).
  75167. */
  75168. local void flush_pending (z_streamp strm)
  75169. {
  75170. unsigned len = strm->state->pending;
  75171. if (len > strm->avail_out) len = strm->avail_out;
  75172. if (len == 0) return;
  75173. zmemcpy(strm->next_out, strm->state->pending_out, len);
  75174. strm->next_out += len;
  75175. strm->state->pending_out += len;
  75176. strm->total_out += len;
  75177. strm->avail_out -= len;
  75178. strm->state->pending -= len;
  75179. if (strm->state->pending == 0) {
  75180. strm->state->pending_out = strm->state->pending_buf;
  75181. }
  75182. }
  75183. /* ========================================================================= */
  75184. int ZEXPORT deflate (z_streamp strm, int flush)
  75185. {
  75186. int old_flush; /* value of flush param for previous deflate call */
  75187. deflate_state *s;
  75188. if (strm == Z_NULL || strm->state == Z_NULL ||
  75189. flush > Z_FINISH || flush < 0) {
  75190. return Z_STREAM_ERROR;
  75191. }
  75192. s = strm->state;
  75193. if (strm->next_out == Z_NULL ||
  75194. (strm->next_in == Z_NULL && strm->avail_in != 0) ||
  75195. (s->status == FINISH_STATE && flush != Z_FINISH)) {
  75196. ERR_RETURN(strm, Z_STREAM_ERROR);
  75197. }
  75198. if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
  75199. s->strm = strm; /* just in case */
  75200. old_flush = s->last_flush;
  75201. s->last_flush = flush;
  75202. /* Write the header */
  75203. if (s->status == INIT_STATE) {
  75204. #ifdef GZIP
  75205. if (s->wrap == 2) {
  75206. strm->adler = crc32(0L, Z_NULL, 0);
  75207. put_byte(s, 31);
  75208. put_byte(s, 139);
  75209. put_byte(s, 8);
  75210. if (s->gzhead == NULL) {
  75211. put_byte(s, 0);
  75212. put_byte(s, 0);
  75213. put_byte(s, 0);
  75214. put_byte(s, 0);
  75215. put_byte(s, 0);
  75216. put_byte(s, s->level == 9 ? 2 :
  75217. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  75218. 4 : 0));
  75219. put_byte(s, OS_CODE);
  75220. s->status = BUSY_STATE;
  75221. }
  75222. else {
  75223. put_byte(s, (s->gzhead->text ? 1 : 0) +
  75224. (s->gzhead->hcrc ? 2 : 0) +
  75225. (s->gzhead->extra == Z_NULL ? 0 : 4) +
  75226. (s->gzhead->name == Z_NULL ? 0 : 8) +
  75227. (s->gzhead->comment == Z_NULL ? 0 : 16)
  75228. );
  75229. put_byte(s, (Byte)(s->gzhead->time & 0xff));
  75230. put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
  75231. put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
  75232. put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
  75233. put_byte(s, s->level == 9 ? 2 :
  75234. (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
  75235. 4 : 0));
  75236. put_byte(s, s->gzhead->os & 0xff);
  75237. if (s->gzhead->extra != NULL) {
  75238. put_byte(s, s->gzhead->extra_len & 0xff);
  75239. put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
  75240. }
  75241. if (s->gzhead->hcrc)
  75242. strm->adler = crc32(strm->adler, s->pending_buf,
  75243. s->pending);
  75244. s->gzindex = 0;
  75245. s->status = EXTRA_STATE;
  75246. }
  75247. }
  75248. else
  75249. #endif
  75250. {
  75251. uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
  75252. uInt level_flags;
  75253. if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
  75254. level_flags = 0;
  75255. else if (s->level < 6)
  75256. level_flags = 1;
  75257. else if (s->level == 6)
  75258. level_flags = 2;
  75259. else
  75260. level_flags = 3;
  75261. header |= (level_flags << 6);
  75262. if (s->strstart != 0) header |= PRESET_DICT;
  75263. header += 31 - (header % 31);
  75264. s->status = BUSY_STATE;
  75265. putShortMSB(s, header);
  75266. /* Save the adler32 of the preset dictionary: */
  75267. if (s->strstart != 0) {
  75268. putShortMSB(s, (uInt)(strm->adler >> 16));
  75269. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  75270. }
  75271. strm->adler = adler32(0L, Z_NULL, 0);
  75272. }
  75273. }
  75274. #ifdef GZIP
  75275. if (s->status == EXTRA_STATE) {
  75276. if (s->gzhead->extra != NULL) {
  75277. uInt beg = s->pending; /* start of bytes to update crc */
  75278. while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
  75279. if (s->pending == s->pending_buf_size) {
  75280. if (s->gzhead->hcrc && s->pending > beg)
  75281. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75282. s->pending - beg);
  75283. flush_pending(strm);
  75284. beg = s->pending;
  75285. if (s->pending == s->pending_buf_size)
  75286. break;
  75287. }
  75288. put_byte(s, s->gzhead->extra[s->gzindex]);
  75289. s->gzindex++;
  75290. }
  75291. if (s->gzhead->hcrc && s->pending > beg)
  75292. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75293. s->pending - beg);
  75294. if (s->gzindex == s->gzhead->extra_len) {
  75295. s->gzindex = 0;
  75296. s->status = NAME_STATE;
  75297. }
  75298. }
  75299. else
  75300. s->status = NAME_STATE;
  75301. }
  75302. if (s->status == NAME_STATE) {
  75303. if (s->gzhead->name != NULL) {
  75304. uInt beg = s->pending; /* start of bytes to update crc */
  75305. int val;
  75306. do {
  75307. if (s->pending == s->pending_buf_size) {
  75308. if (s->gzhead->hcrc && s->pending > beg)
  75309. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75310. s->pending - beg);
  75311. flush_pending(strm);
  75312. beg = s->pending;
  75313. if (s->pending == s->pending_buf_size) {
  75314. val = 1;
  75315. break;
  75316. }
  75317. }
  75318. val = s->gzhead->name[s->gzindex++];
  75319. put_byte(s, val);
  75320. } while (val != 0);
  75321. if (s->gzhead->hcrc && s->pending > beg)
  75322. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75323. s->pending - beg);
  75324. if (val == 0) {
  75325. s->gzindex = 0;
  75326. s->status = COMMENT_STATE;
  75327. }
  75328. }
  75329. else
  75330. s->status = COMMENT_STATE;
  75331. }
  75332. if (s->status == COMMENT_STATE) {
  75333. if (s->gzhead->comment != NULL) {
  75334. uInt beg = s->pending; /* start of bytes to update crc */
  75335. int val;
  75336. do {
  75337. if (s->pending == s->pending_buf_size) {
  75338. if (s->gzhead->hcrc && s->pending > beg)
  75339. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75340. s->pending - beg);
  75341. flush_pending(strm);
  75342. beg = s->pending;
  75343. if (s->pending == s->pending_buf_size) {
  75344. val = 1;
  75345. break;
  75346. }
  75347. }
  75348. val = s->gzhead->comment[s->gzindex++];
  75349. put_byte(s, val);
  75350. } while (val != 0);
  75351. if (s->gzhead->hcrc && s->pending > beg)
  75352. strm->adler = crc32(strm->adler, s->pending_buf + beg,
  75353. s->pending - beg);
  75354. if (val == 0)
  75355. s->status = HCRC_STATE;
  75356. }
  75357. else
  75358. s->status = HCRC_STATE;
  75359. }
  75360. if (s->status == HCRC_STATE) {
  75361. if (s->gzhead->hcrc) {
  75362. if (s->pending + 2 > s->pending_buf_size)
  75363. flush_pending(strm);
  75364. if (s->pending + 2 <= s->pending_buf_size) {
  75365. put_byte(s, (Byte)(strm->adler & 0xff));
  75366. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  75367. strm->adler = crc32(0L, Z_NULL, 0);
  75368. s->status = BUSY_STATE;
  75369. }
  75370. }
  75371. else
  75372. s->status = BUSY_STATE;
  75373. }
  75374. #endif
  75375. /* Flush as much pending output as possible */
  75376. if (s->pending != 0) {
  75377. flush_pending(strm);
  75378. if (strm->avail_out == 0) {
  75379. /* Since avail_out is 0, deflate will be called again with
  75380. * more output space, but possibly with both pending and
  75381. * avail_in equal to zero. There won't be anything to do,
  75382. * but this is not an error situation so make sure we
  75383. * return OK instead of BUF_ERROR at next call of deflate:
  75384. */
  75385. s->last_flush = -1;
  75386. return Z_OK;
  75387. }
  75388. /* Make sure there is something to do and avoid duplicate consecutive
  75389. * flushes. For repeated and useless calls with Z_FINISH, we keep
  75390. * returning Z_STREAM_END instead of Z_BUF_ERROR.
  75391. */
  75392. } else if (strm->avail_in == 0 && flush <= old_flush &&
  75393. flush != Z_FINISH) {
  75394. ERR_RETURN(strm, Z_BUF_ERROR);
  75395. }
  75396. /* User must not provide more input after the first FINISH: */
  75397. if (s->status == FINISH_STATE && strm->avail_in != 0) {
  75398. ERR_RETURN(strm, Z_BUF_ERROR);
  75399. }
  75400. /* Start a new block or continue the current one.
  75401. */
  75402. if (strm->avail_in != 0 || s->lookahead != 0 ||
  75403. (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
  75404. block_state bstate;
  75405. bstate = (*(configuration_table[s->level].func))(s, flush);
  75406. if (bstate == finish_started || bstate == finish_done) {
  75407. s->status = FINISH_STATE;
  75408. }
  75409. if (bstate == need_more || bstate == finish_started) {
  75410. if (strm->avail_out == 0) {
  75411. s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
  75412. }
  75413. return Z_OK;
  75414. /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
  75415. * of deflate should use the same flush parameter to make sure
  75416. * that the flush is complete. So we don't have to output an
  75417. * empty block here, this will be done at next call. This also
  75418. * ensures that for a very small output buffer, we emit at most
  75419. * one empty block.
  75420. */
  75421. }
  75422. if (bstate == block_done) {
  75423. if (flush == Z_PARTIAL_FLUSH) {
  75424. _tr_align(s);
  75425. } else { /* FULL_FLUSH or SYNC_FLUSH */
  75426. _tr_stored_block(s, (char*)0, 0L, 0);
  75427. /* For a full flush, this empty block will be recognized
  75428. * as a special marker by inflate_sync().
  75429. */
  75430. if (flush == Z_FULL_FLUSH) {
  75431. CLEAR_HASH(s); /* forget history */
  75432. }
  75433. }
  75434. flush_pending(strm);
  75435. if (strm->avail_out == 0) {
  75436. s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
  75437. return Z_OK;
  75438. }
  75439. }
  75440. }
  75441. Assert(strm->avail_out > 0, "bug2");
  75442. if (flush != Z_FINISH) return Z_OK;
  75443. if (s->wrap <= 0) return Z_STREAM_END;
  75444. /* Write the trailer */
  75445. #ifdef GZIP
  75446. if (s->wrap == 2) {
  75447. put_byte(s, (Byte)(strm->adler & 0xff));
  75448. put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
  75449. put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
  75450. put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
  75451. put_byte(s, (Byte)(strm->total_in & 0xff));
  75452. put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
  75453. put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
  75454. put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
  75455. }
  75456. else
  75457. #endif
  75458. {
  75459. putShortMSB(s, (uInt)(strm->adler >> 16));
  75460. putShortMSB(s, (uInt)(strm->adler & 0xffff));
  75461. }
  75462. flush_pending(strm);
  75463. /* If avail_out is zero, the application will call deflate again
  75464. * to flush the rest.
  75465. */
  75466. if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
  75467. return s->pending != 0 ? Z_OK : Z_STREAM_END;
  75468. }
  75469. /* ========================================================================= */
  75470. int ZEXPORT deflateEnd (z_streamp strm)
  75471. {
  75472. int status;
  75473. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  75474. status = strm->state->status;
  75475. if (status != INIT_STATE &&
  75476. status != EXTRA_STATE &&
  75477. status != NAME_STATE &&
  75478. status != COMMENT_STATE &&
  75479. status != HCRC_STATE &&
  75480. status != BUSY_STATE &&
  75481. status != FINISH_STATE) {
  75482. return Z_STREAM_ERROR;
  75483. }
  75484. /* Deallocate in reverse order of allocations: */
  75485. TRY_FREE(strm, strm->state->pending_buf);
  75486. TRY_FREE(strm, strm->state->head);
  75487. TRY_FREE(strm, strm->state->prev);
  75488. TRY_FREE(strm, strm->state->window);
  75489. ZFREE(strm, strm->state);
  75490. strm->state = Z_NULL;
  75491. return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
  75492. }
  75493. /* =========================================================================
  75494. * Copy the source state to the destination state.
  75495. * To simplify the source, this is not supported for 16-bit MSDOS (which
  75496. * doesn't have enough memory anyway to duplicate compression states).
  75497. */
  75498. int ZEXPORT deflateCopy (z_streamp dest, z_streamp source)
  75499. {
  75500. #ifdef MAXSEG_64K
  75501. return Z_STREAM_ERROR;
  75502. #else
  75503. deflate_state *ds;
  75504. deflate_state *ss;
  75505. ushf *overlay;
  75506. if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
  75507. return Z_STREAM_ERROR;
  75508. }
  75509. ss = source->state;
  75510. zmemcpy(dest, source, sizeof(z_stream));
  75511. ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
  75512. if (ds == Z_NULL) return Z_MEM_ERROR;
  75513. dest->state = (struct internal_state FAR *) ds;
  75514. zmemcpy(ds, ss, sizeof(deflate_state));
  75515. ds->strm = dest;
  75516. ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
  75517. ds->prev = (Posf *) ZALLOC(dest, ds->w_size, sizeof(Pos));
  75518. ds->head = (Posf *) ZALLOC(dest, ds->hash_size, sizeof(Pos));
  75519. overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
  75520. ds->pending_buf = (uchf *) overlay;
  75521. if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
  75522. ds->pending_buf == Z_NULL) {
  75523. deflateEnd (dest);
  75524. return Z_MEM_ERROR;
  75525. }
  75526. /* following zmemcpy do not work for 16-bit MSDOS */
  75527. zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
  75528. zmemcpy(ds->prev, ss->prev, ds->w_size * sizeof(Pos));
  75529. zmemcpy(ds->head, ss->head, ds->hash_size * sizeof(Pos));
  75530. zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
  75531. ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
  75532. ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
  75533. ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
  75534. ds->l_desc.dyn_tree = ds->dyn_ltree;
  75535. ds->d_desc.dyn_tree = ds->dyn_dtree;
  75536. ds->bl_desc.dyn_tree = ds->bl_tree;
  75537. return Z_OK;
  75538. #endif /* MAXSEG_64K */
  75539. }
  75540. /* ===========================================================================
  75541. * Read a new buffer from the current input stream, update the adler32
  75542. * and total number of bytes read. All deflate() input goes through
  75543. * this function so some applications may wish to modify it to avoid
  75544. * allocating a large strm->next_in buffer and copying from it.
  75545. * (See also flush_pending()).
  75546. */
  75547. local int read_buf (z_streamp strm, Bytef *buf, unsigned size)
  75548. {
  75549. unsigned len = strm->avail_in;
  75550. if (len > size) len = size;
  75551. if (len == 0) return 0;
  75552. strm->avail_in -= len;
  75553. if (strm->state->wrap == 1) {
  75554. strm->adler = adler32(strm->adler, strm->next_in, len);
  75555. }
  75556. #ifdef GZIP
  75557. else if (strm->state->wrap == 2) {
  75558. strm->adler = crc32(strm->adler, strm->next_in, len);
  75559. }
  75560. #endif
  75561. zmemcpy(buf, strm->next_in, len);
  75562. strm->next_in += len;
  75563. strm->total_in += len;
  75564. return (int)len;
  75565. }
  75566. /* ===========================================================================
  75567. * Initialize the "longest match" routines for a new zlib stream
  75568. */
  75569. local void lm_init (deflate_state *s)
  75570. {
  75571. s->window_size = (ulg)2L*s->w_size;
  75572. CLEAR_HASH(s);
  75573. /* Set the default configuration parameters:
  75574. */
  75575. s->max_lazy_match = configuration_table[s->level].max_lazy;
  75576. s->good_match = configuration_table[s->level].good_length;
  75577. s->nice_match = configuration_table[s->level].nice_length;
  75578. s->max_chain_length = configuration_table[s->level].max_chain;
  75579. s->strstart = 0;
  75580. s->block_start = 0L;
  75581. s->lookahead = 0;
  75582. s->match_length = s->prev_length = MIN_MATCH-1;
  75583. s->match_available = 0;
  75584. s->ins_h = 0;
  75585. #ifndef FASTEST
  75586. #ifdef ASMV
  75587. match_init(); /* initialize the asm code */
  75588. #endif
  75589. #endif
  75590. }
  75591. #ifndef FASTEST
  75592. /* ===========================================================================
  75593. * Set match_start to the longest match starting at the given string and
  75594. * return its length. Matches shorter or equal to prev_length are discarded,
  75595. * in which case the result is equal to prev_length and match_start is
  75596. * garbage.
  75597. * IN assertions: cur_match is the head of the hash chain for the current
  75598. * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
  75599. * OUT assertion: the match length is not greater than s->lookahead.
  75600. */
  75601. #ifndef ASMV
  75602. /* For 80x86 and 680x0, an optimized version will be provided in match.asm or
  75603. * match.S. The code will be functionally equivalent.
  75604. */
  75605. local uInt longest_match(deflate_state *s, IPos cur_match)
  75606. {
  75607. unsigned chain_length = s->max_chain_length;/* max hash chain length */
  75608. register Bytef *scan = s->window + s->strstart; /* current string */
  75609. register Bytef *match; /* matched string */
  75610. register int len; /* length of current match */
  75611. int best_len = s->prev_length; /* best match length so far */
  75612. int nice_match = s->nice_match; /* stop if match long enough */
  75613. IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
  75614. s->strstart - (IPos)MAX_DIST(s) : NIL;
  75615. /* Stop when cur_match becomes <= limit. To simplify the code,
  75616. * we prevent matches with the string of window index 0.
  75617. */
  75618. Posf *prev = s->prev;
  75619. uInt wmask = s->w_mask;
  75620. #ifdef UNALIGNED_OK
  75621. /* Compare two bytes at a time. Note: this is not always beneficial.
  75622. * Try with and without -DUNALIGNED_OK to check.
  75623. */
  75624. register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
  75625. register ush scan_start = *(ushf*)scan;
  75626. register ush scan_end = *(ushf*)(scan+best_len-1);
  75627. #else
  75628. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  75629. register Byte scan_end1 = scan[best_len-1];
  75630. register Byte scan_end = scan[best_len];
  75631. #endif
  75632. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  75633. * It is easy to get rid of this optimization if necessary.
  75634. */
  75635. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  75636. /* Do not waste too much time if we already have a good match: */
  75637. if (s->prev_length >= s->good_match) {
  75638. chain_length >>= 2;
  75639. }
  75640. /* Do not look for matches beyond the end of the input. This is necessary
  75641. * to make deflate deterministic.
  75642. */
  75643. if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
  75644. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  75645. do {
  75646. Assert(cur_match < s->strstart, "no future");
  75647. match = s->window + cur_match;
  75648. /* Skip to next match if the match length cannot increase
  75649. * or if the match length is less than 2. Note that the checks below
  75650. * for insufficient lookahead only occur occasionally for performance
  75651. * reasons. Therefore uninitialized memory will be accessed, and
  75652. * conditional jumps will be made that depend on those values.
  75653. * However the length of the match is limited to the lookahead, so
  75654. * the output of deflate is not affected by the uninitialized values.
  75655. */
  75656. #if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
  75657. /* This code assumes sizeof(unsigned short) == 2. Do not use
  75658. * UNALIGNED_OK if your compiler uses a different size.
  75659. */
  75660. if (*(ushf*)(match+best_len-1) != scan_end ||
  75661. *(ushf*)match != scan_start) continue;
  75662. /* It is not necessary to compare scan[2] and match[2] since they are
  75663. * always equal when the other bytes match, given that the hash keys
  75664. * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
  75665. * strstart+3, +5, ... up to strstart+257. We check for insufficient
  75666. * lookahead only every 4th comparison; the 128th check will be made
  75667. * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
  75668. * necessary to put more guard bytes at the end of the window, or
  75669. * to check more often for insufficient lookahead.
  75670. */
  75671. Assert(scan[2] == match[2], "scan[2]?");
  75672. scan++, match++;
  75673. do {
  75674. } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75675. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75676. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75677. *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
  75678. scan < strend);
  75679. /* The funny "do {}" generates better code on most compilers */
  75680. /* Here, scan <= window+strstart+257 */
  75681. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  75682. if (*scan == *match) scan++;
  75683. len = (MAX_MATCH - 1) - (int)(strend-scan);
  75684. scan = strend - (MAX_MATCH-1);
  75685. #else /* UNALIGNED_OK */
  75686. if (match[best_len] != scan_end ||
  75687. match[best_len-1] != scan_end1 ||
  75688. *match != *scan ||
  75689. *++match != scan[1]) continue;
  75690. /* The check at best_len-1 can be removed because it will be made
  75691. * again later. (This heuristic is not always a win.)
  75692. * It is not necessary to compare scan[2] and match[2] since they
  75693. * are always equal when the other bytes match, given that
  75694. * the hash keys are equal and that HASH_BITS >= 8.
  75695. */
  75696. scan += 2, match++;
  75697. Assert(*scan == *match, "match[2]?");
  75698. /* We check for insufficient lookahead only every 8th comparison;
  75699. * the 256th check will be made at strstart+258.
  75700. */
  75701. do {
  75702. } while (*++scan == *++match && *++scan == *++match &&
  75703. *++scan == *++match && *++scan == *++match &&
  75704. *++scan == *++match && *++scan == *++match &&
  75705. *++scan == *++match && *++scan == *++match &&
  75706. scan < strend);
  75707. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  75708. len = MAX_MATCH - (int)(strend - scan);
  75709. scan = strend - MAX_MATCH;
  75710. #endif /* UNALIGNED_OK */
  75711. if (len > best_len) {
  75712. s->match_start = cur_match;
  75713. best_len = len;
  75714. if (len >= nice_match) break;
  75715. #ifdef UNALIGNED_OK
  75716. scan_end = *(ushf*)(scan+best_len-1);
  75717. #else
  75718. scan_end1 = scan[best_len-1];
  75719. scan_end = scan[best_len];
  75720. #endif
  75721. }
  75722. } while ((cur_match = prev[cur_match & wmask]) > limit
  75723. && --chain_length != 0);
  75724. if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
  75725. return s->lookahead;
  75726. }
  75727. #endif /* ASMV */
  75728. #endif /* FASTEST */
  75729. /* ---------------------------------------------------------------------------
  75730. * Optimized version for level == 1 or strategy == Z_RLE only
  75731. */
  75732. local uInt longest_match_fast (deflate_state *s, IPos cur_match)
  75733. {
  75734. register Bytef *scan = s->window + s->strstart; /* current string */
  75735. register Bytef *match; /* matched string */
  75736. register int len; /* length of current match */
  75737. register Bytef *strend = s->window + s->strstart + MAX_MATCH;
  75738. /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
  75739. * It is easy to get rid of this optimization if necessary.
  75740. */
  75741. Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
  75742. Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
  75743. Assert(cur_match < s->strstart, "no future");
  75744. match = s->window + cur_match;
  75745. /* Return failure if the match length is less than 2:
  75746. */
  75747. if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
  75748. /* The check at best_len-1 can be removed because it will be made
  75749. * again later. (This heuristic is not always a win.)
  75750. * It is not necessary to compare scan[2] and match[2] since they
  75751. * are always equal when the other bytes match, given that
  75752. * the hash keys are equal and that HASH_BITS >= 8.
  75753. */
  75754. scan += 2, match += 2;
  75755. Assert(*scan == *match, "match[2]?");
  75756. /* We check for insufficient lookahead only every 8th comparison;
  75757. * the 256th check will be made at strstart+258.
  75758. */
  75759. do {
  75760. } while (*++scan == *++match && *++scan == *++match &&
  75761. *++scan == *++match && *++scan == *++match &&
  75762. *++scan == *++match && *++scan == *++match &&
  75763. *++scan == *++match && *++scan == *++match &&
  75764. scan < strend);
  75765. Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
  75766. len = MAX_MATCH - (int)(strend - scan);
  75767. if (len < MIN_MATCH) return MIN_MATCH - 1;
  75768. s->match_start = cur_match;
  75769. return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
  75770. }
  75771. #ifdef DEBUG
  75772. /* ===========================================================================
  75773. * Check that the match at match_start is indeed a match.
  75774. */
  75775. local void check_match(deflate_state *s, IPos start, IPos match, int length)
  75776. {
  75777. /* check that the match is indeed a match */
  75778. if (zmemcmp(s->window + match,
  75779. s->window + start, length) != EQUAL) {
  75780. fprintf(stderr, " start %u, match %u, length %d\n",
  75781. start, match, length);
  75782. do {
  75783. fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
  75784. } while (--length != 0);
  75785. z_error("invalid match");
  75786. }
  75787. if (z_verbose > 1) {
  75788. fprintf(stderr,"\\[%d,%d]", start-match, length);
  75789. do { putc(s->window[start++], stderr); } while (--length != 0);
  75790. }
  75791. }
  75792. #else
  75793. # define check_match(s, start, match, length)
  75794. #endif /* DEBUG */
  75795. /* ===========================================================================
  75796. * Fill the window when the lookahead becomes insufficient.
  75797. * Updates strstart and lookahead.
  75798. *
  75799. * IN assertion: lookahead < MIN_LOOKAHEAD
  75800. * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
  75801. * At least one byte has been read, or avail_in == 0; reads are
  75802. * performed for at least two bytes (required for the zip translate_eol
  75803. * option -- not supported here).
  75804. */
  75805. local void fill_window (deflate_state *s)
  75806. {
  75807. register unsigned n, m;
  75808. register Posf *p;
  75809. unsigned more; /* Amount of free space at the end of the window. */
  75810. uInt wsize = s->w_size;
  75811. do {
  75812. more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
  75813. /* Deal with !@#$% 64K limit: */
  75814. if (sizeof(int) <= 2) {
  75815. if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
  75816. more = wsize;
  75817. } else if (more == (unsigned)(-1)) {
  75818. /* Very unlikely, but possible on 16 bit machine if
  75819. * strstart == 0 && lookahead == 1 (input done a byte at time)
  75820. */
  75821. more--;
  75822. }
  75823. }
  75824. /* If the window is almost full and there is insufficient lookahead,
  75825. * move the upper half to the lower one to make room in the upper half.
  75826. */
  75827. if (s->strstart >= wsize+MAX_DIST(s)) {
  75828. zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
  75829. s->match_start -= wsize;
  75830. s->strstart -= wsize; /* we now have strstart >= MAX_DIST */
  75831. s->block_start -= (long) wsize;
  75832. /* Slide the hash table (could be avoided with 32 bit values
  75833. at the expense of memory usage). We slide even when level == 0
  75834. to keep the hash table consistent if we switch back to level > 0
  75835. later. (Using level 0 permanently is not an optimal usage of
  75836. zlib, so we don't care about this pathological case.)
  75837. */
  75838. /* %%% avoid this when Z_RLE */
  75839. n = s->hash_size;
  75840. p = &s->head[n];
  75841. do {
  75842. m = *--p;
  75843. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  75844. } while (--n);
  75845. n = wsize;
  75846. #ifndef FASTEST
  75847. p = &s->prev[n];
  75848. do {
  75849. m = *--p;
  75850. *p = (Pos)(m >= wsize ? m-wsize : NIL);
  75851. /* If n is not on any hash chain, prev[n] is garbage but
  75852. * its value will never be used.
  75853. */
  75854. } while (--n);
  75855. #endif
  75856. more += wsize;
  75857. }
  75858. if (s->strm->avail_in == 0) return;
  75859. /* If there was no sliding:
  75860. * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
  75861. * more == window_size - lookahead - strstart
  75862. * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
  75863. * => more >= window_size - 2*WSIZE + 2
  75864. * In the BIG_MEM or MMAP case (not yet supported),
  75865. * window_size == input_size + MIN_LOOKAHEAD &&
  75866. * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
  75867. * Otherwise, window_size == 2*WSIZE so more >= 2.
  75868. * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
  75869. */
  75870. Assert(more >= 2, "more < 2");
  75871. n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
  75872. s->lookahead += n;
  75873. /* Initialize the hash value now that we have some input: */
  75874. if (s->lookahead >= MIN_MATCH) {
  75875. s->ins_h = s->window[s->strstart];
  75876. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  75877. #if MIN_MATCH != 3
  75878. Call UPDATE_HASH() MIN_MATCH-3 more times
  75879. #endif
  75880. }
  75881. /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
  75882. * but this is not important since only literal bytes will be emitted.
  75883. */
  75884. } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
  75885. }
  75886. /* ===========================================================================
  75887. * Flush the current block, with given end-of-file flag.
  75888. * IN assertion: strstart is set to the end of the current match.
  75889. */
  75890. #define FLUSH_BLOCK_ONLY(s, eof) { \
  75891. _tr_flush_block(s, (s->block_start >= 0L ? \
  75892. (charf *)&s->window[(unsigned)s->block_start] : \
  75893. (charf *)Z_NULL), \
  75894. (ulg)((long)s->strstart - s->block_start), \
  75895. (eof)); \
  75896. s->block_start = s->strstart; \
  75897. flush_pending(s->strm); \
  75898. Tracev((stderr,"[FLUSH]")); \
  75899. }
  75900. /* Same but force premature exit if necessary. */
  75901. #define FLUSH_BLOCK(s, eof) { \
  75902. FLUSH_BLOCK_ONLY(s, eof); \
  75903. if (s->strm->avail_out == 0) return (eof) ? finish_started : need_more; \
  75904. }
  75905. /* ===========================================================================
  75906. * Copy without compression as much as possible from the input stream, return
  75907. * the current block state.
  75908. * This function does not insert new strings in the dictionary since
  75909. * uncompressible data is probably not useful. This function is used
  75910. * only for the level=0 compression option.
  75911. * NOTE: this function should be optimized to avoid extra copying from
  75912. * window to pending_buf.
  75913. */
  75914. local block_state deflate_stored(deflate_state *s, int flush)
  75915. {
  75916. /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
  75917. * to pending_buf_size, and each stored block has a 5 byte header:
  75918. */
  75919. ulg max_block_size = 0xffff;
  75920. ulg max_start;
  75921. if (max_block_size > s->pending_buf_size - 5) {
  75922. max_block_size = s->pending_buf_size - 5;
  75923. }
  75924. /* Copy as much as possible from input to output: */
  75925. for (;;) {
  75926. /* Fill the window as much as possible: */
  75927. if (s->lookahead <= 1) {
  75928. Assert(s->strstart < s->w_size+MAX_DIST(s) ||
  75929. s->block_start >= (long)s->w_size, "slide too late");
  75930. fill_window(s);
  75931. if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
  75932. if (s->lookahead == 0) break; /* flush the current block */
  75933. }
  75934. Assert(s->block_start >= 0L, "block gone");
  75935. s->strstart += s->lookahead;
  75936. s->lookahead = 0;
  75937. /* Emit a stored block if pending_buf will be full: */
  75938. max_start = s->block_start + max_block_size;
  75939. if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
  75940. /* strstart == 0 is possible when wraparound on 16-bit machine */
  75941. s->lookahead = (uInt)(s->strstart - max_start);
  75942. s->strstart = (uInt)max_start;
  75943. FLUSH_BLOCK(s, 0);
  75944. }
  75945. /* Flush if we may have to slide, otherwise block_start may become
  75946. * negative and the data will be gone:
  75947. */
  75948. if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
  75949. FLUSH_BLOCK(s, 0);
  75950. }
  75951. }
  75952. FLUSH_BLOCK(s, flush == Z_FINISH);
  75953. return flush == Z_FINISH ? finish_done : block_done;
  75954. }
  75955. /* ===========================================================================
  75956. * Compress as much as possible from the input stream, return the current
  75957. * block state.
  75958. * This function does not perform lazy evaluation of matches and inserts
  75959. * new strings in the dictionary only for unmatched strings or for short
  75960. * matches. It is used only for the fast compression options.
  75961. */
  75962. local block_state deflate_fast(deflate_state *s, int flush)
  75963. {
  75964. IPos hash_head = NIL; /* head of the hash chain */
  75965. int bflush; /* set if current block must be flushed */
  75966. for (;;) {
  75967. /* Make sure that we always have enough lookahead, except
  75968. * at the end of the input file. We need MAX_MATCH bytes
  75969. * for the next match, plus MIN_MATCH bytes to insert the
  75970. * string following the next match.
  75971. */
  75972. if (s->lookahead < MIN_LOOKAHEAD) {
  75973. fill_window(s);
  75974. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  75975. return need_more;
  75976. }
  75977. if (s->lookahead == 0) break; /* flush the current block */
  75978. }
  75979. /* Insert the string window[strstart .. strstart+2] in the
  75980. * dictionary, and set hash_head to the head of the hash chain:
  75981. */
  75982. if (s->lookahead >= MIN_MATCH) {
  75983. INSERT_STRING(s, s->strstart, hash_head);
  75984. }
  75985. /* Find the longest match, discarding those <= prev_length.
  75986. * At this point we have always match_length < MIN_MATCH
  75987. */
  75988. if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
  75989. /* To simplify the code, we prevent matches with the string
  75990. * of window index 0 (in particular we have to avoid a match
  75991. * of the string with itself at the start of the input file).
  75992. */
  75993. #ifdef FASTEST
  75994. if ((s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) ||
  75995. (s->strategy == Z_RLE && s->strstart - hash_head == 1)) {
  75996. s->match_length = longest_match_fast (s, hash_head);
  75997. }
  75998. #else
  75999. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  76000. s->match_length = longest_match (s, hash_head);
  76001. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  76002. s->match_length = longest_match_fast (s, hash_head);
  76003. }
  76004. #endif
  76005. /* longest_match() or longest_match_fast() sets match_start */
  76006. }
  76007. if (s->match_length >= MIN_MATCH) {
  76008. check_match(s, s->strstart, s->match_start, s->match_length);
  76009. _tr_tally_dist(s, s->strstart - s->match_start,
  76010. s->match_length - MIN_MATCH, bflush);
  76011. s->lookahead -= s->match_length;
  76012. /* Insert new strings in the hash table only if the match length
  76013. * is not too large. This saves time but degrades compression.
  76014. */
  76015. #ifndef FASTEST
  76016. if (s->match_length <= s->max_insert_length &&
  76017. s->lookahead >= MIN_MATCH) {
  76018. s->match_length--; /* string at strstart already in table */
  76019. do {
  76020. s->strstart++;
  76021. INSERT_STRING(s, s->strstart, hash_head);
  76022. /* strstart never exceeds WSIZE-MAX_MATCH, so there are
  76023. * always MIN_MATCH bytes ahead.
  76024. */
  76025. } while (--s->match_length != 0);
  76026. s->strstart++;
  76027. } else
  76028. #endif
  76029. {
  76030. s->strstart += s->match_length;
  76031. s->match_length = 0;
  76032. s->ins_h = s->window[s->strstart];
  76033. UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
  76034. #if MIN_MATCH != 3
  76035. Call UPDATE_HASH() MIN_MATCH-3 more times
  76036. #endif
  76037. /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
  76038. * matter since it will be recomputed at next deflate call.
  76039. */
  76040. }
  76041. } else {
  76042. /* No match, output a literal byte */
  76043. Tracevv((stderr,"%c", s->window[s->strstart]));
  76044. _tr_tally_lit (s, s->window[s->strstart], bflush);
  76045. s->lookahead--;
  76046. s->strstart++;
  76047. }
  76048. if (bflush) FLUSH_BLOCK(s, 0);
  76049. }
  76050. FLUSH_BLOCK(s, flush == Z_FINISH);
  76051. return flush == Z_FINISH ? finish_done : block_done;
  76052. }
  76053. #ifndef FASTEST
  76054. /* ===========================================================================
  76055. * Same as above, but achieves better compression. We use a lazy
  76056. * evaluation for matches: a match is finally adopted only if there is
  76057. * no better match at the next window position.
  76058. */
  76059. local block_state deflate_slow(deflate_state *s, int flush)
  76060. {
  76061. IPos hash_head = NIL; /* head of hash chain */
  76062. int bflush; /* set if current block must be flushed */
  76063. /* Process the input block. */
  76064. for (;;) {
  76065. /* Make sure that we always have enough lookahead, except
  76066. * at the end of the input file. We need MAX_MATCH bytes
  76067. * for the next match, plus MIN_MATCH bytes to insert the
  76068. * string following the next match.
  76069. */
  76070. if (s->lookahead < MIN_LOOKAHEAD) {
  76071. fill_window(s);
  76072. if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
  76073. return need_more;
  76074. }
  76075. if (s->lookahead == 0) break; /* flush the current block */
  76076. }
  76077. /* Insert the string window[strstart .. strstart+2] in the
  76078. * dictionary, and set hash_head to the head of the hash chain:
  76079. */
  76080. if (s->lookahead >= MIN_MATCH) {
  76081. INSERT_STRING(s, s->strstart, hash_head);
  76082. }
  76083. /* Find the longest match, discarding those <= prev_length.
  76084. */
  76085. s->prev_length = s->match_length, s->prev_match = s->match_start;
  76086. s->match_length = MIN_MATCH-1;
  76087. if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
  76088. s->strstart - hash_head <= MAX_DIST(s)) {
  76089. /* To simplify the code, we prevent matches with the string
  76090. * of window index 0 (in particular we have to avoid a match
  76091. * of the string with itself at the start of the input file).
  76092. */
  76093. if (s->strategy != Z_HUFFMAN_ONLY && s->strategy != Z_RLE) {
  76094. s->match_length = longest_match (s, hash_head);
  76095. } else if (s->strategy == Z_RLE && s->strstart - hash_head == 1) {
  76096. s->match_length = longest_match_fast (s, hash_head);
  76097. }
  76098. /* longest_match() or longest_match_fast() sets match_start */
  76099. if (s->match_length <= 5 && (s->strategy == Z_FILTERED
  76100. #if TOO_FAR <= 32767
  76101. || (s->match_length == MIN_MATCH &&
  76102. s->strstart - s->match_start > TOO_FAR)
  76103. #endif
  76104. )) {
  76105. /* If prev_match is also MIN_MATCH, match_start is garbage
  76106. * but we will ignore the current match anyway.
  76107. */
  76108. s->match_length = MIN_MATCH-1;
  76109. }
  76110. }
  76111. /* If there was a match at the previous step and the current
  76112. * match is not better, output the previous match:
  76113. */
  76114. if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
  76115. uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
  76116. /* Do not insert strings in hash table beyond this. */
  76117. check_match(s, s->strstart-1, s->prev_match, s->prev_length);
  76118. _tr_tally_dist(s, s->strstart -1 - s->prev_match,
  76119. s->prev_length - MIN_MATCH, bflush);
  76120. /* Insert in hash table all strings up to the end of the match.
  76121. * strstart-1 and strstart are already inserted. If there is not
  76122. * enough lookahead, the last two strings are not inserted in
  76123. * the hash table.
  76124. */
  76125. s->lookahead -= s->prev_length-1;
  76126. s->prev_length -= 2;
  76127. do {
  76128. if (++s->strstart <= max_insert) {
  76129. INSERT_STRING(s, s->strstart, hash_head);
  76130. }
  76131. } while (--s->prev_length != 0);
  76132. s->match_available = 0;
  76133. s->match_length = MIN_MATCH-1;
  76134. s->strstart++;
  76135. if (bflush) FLUSH_BLOCK(s, 0);
  76136. } else if (s->match_available) {
  76137. /* If there was no match at the previous position, output a
  76138. * single literal. If there was a match but the current match
  76139. * is longer, truncate the previous match to a single literal.
  76140. */
  76141. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  76142. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  76143. if (bflush) {
  76144. FLUSH_BLOCK_ONLY(s, 0);
  76145. }
  76146. s->strstart++;
  76147. s->lookahead--;
  76148. if (s->strm->avail_out == 0) return need_more;
  76149. } else {
  76150. /* There is no previous match to compare with, wait for
  76151. * the next step to decide.
  76152. */
  76153. s->match_available = 1;
  76154. s->strstart++;
  76155. s->lookahead--;
  76156. }
  76157. }
  76158. Assert (flush != Z_NO_FLUSH, "no flush?");
  76159. if (s->match_available) {
  76160. Tracevv((stderr,"%c", s->window[s->strstart-1]));
  76161. _tr_tally_lit(s, s->window[s->strstart-1], bflush);
  76162. s->match_available = 0;
  76163. }
  76164. FLUSH_BLOCK(s, flush == Z_FINISH);
  76165. return flush == Z_FINISH ? finish_done : block_done;
  76166. }
  76167. #endif /* FASTEST */
  76168. #if 0
  76169. /* ===========================================================================
  76170. * For Z_RLE, simply look for runs of bytes, generate matches only of distance
  76171. * one. Do not maintain a hash table. (It will be regenerated if this run of
  76172. * deflate switches away from Z_RLE.)
  76173. */
  76174. local block_state deflate_rle(s, flush)
  76175. deflate_state *s;
  76176. int flush;
  76177. {
  76178. int bflush; /* set if current block must be flushed */
  76179. uInt run; /* length of run */
  76180. uInt max; /* maximum length of run */
  76181. uInt prev; /* byte at distance one to match */
  76182. Bytef *scan; /* scan for end of run */
  76183. for (;;) {
  76184. /* Make sure that we always have enough lookahead, except
  76185. * at the end of the input file. We need MAX_MATCH bytes
  76186. * for the longest encodable run.
  76187. */
  76188. if (s->lookahead < MAX_MATCH) {
  76189. fill_window(s);
  76190. if (s->lookahead < MAX_MATCH && flush == Z_NO_FLUSH) {
  76191. return need_more;
  76192. }
  76193. if (s->lookahead == 0) break; /* flush the current block */
  76194. }
  76195. /* See how many times the previous byte repeats */
  76196. run = 0;
  76197. if (s->strstart > 0) { /* if there is a previous byte, that is */
  76198. max = s->lookahead < MAX_MATCH ? s->lookahead : MAX_MATCH;
  76199. scan = s->window + s->strstart - 1;
  76200. prev = *scan++;
  76201. do {
  76202. if (*scan++ != prev)
  76203. break;
  76204. } while (++run < max);
  76205. }
  76206. /* Emit match if have run of MIN_MATCH or longer, else emit literal */
  76207. if (run >= MIN_MATCH) {
  76208. check_match(s, s->strstart, s->strstart - 1, run);
  76209. _tr_tally_dist(s, 1, run - MIN_MATCH, bflush);
  76210. s->lookahead -= run;
  76211. s->strstart += run;
  76212. } else {
  76213. /* No match, output a literal byte */
  76214. Tracevv((stderr,"%c", s->window[s->strstart]));
  76215. _tr_tally_lit (s, s->window[s->strstart], bflush);
  76216. s->lookahead--;
  76217. s->strstart++;
  76218. }
  76219. if (bflush) FLUSH_BLOCK(s, 0);
  76220. }
  76221. FLUSH_BLOCK(s, flush == Z_FINISH);
  76222. return flush == Z_FINISH ? finish_done : block_done;
  76223. }
  76224. #endif
  76225. /********* End of inlined file: deflate.c *********/
  76226. /********* Start of inlined file: infback.c *********/
  76227. /*
  76228. This code is largely copied from inflate.c. Normally either infback.o or
  76229. inflate.o would be linked into an application--not both. The interface
  76230. with inffast.c is retained so that optimized assembler-coded versions of
  76231. inflate_fast() can be used with either inflate.c or infback.c.
  76232. */
  76233. /********* Start of inlined file: inftrees.h *********/
  76234. /* WARNING: this file should *not* be used by applications. It is
  76235. part of the implementation of the compression library and is
  76236. subject to change. Applications should only use zlib.h.
  76237. */
  76238. #ifndef _INFTREES_H_
  76239. #define _INFTREES_H_
  76240. /* Structure for decoding tables. Each entry provides either the
  76241. information needed to do the operation requested by the code that
  76242. indexed that table entry, or it provides a pointer to another
  76243. table that indexes more bits of the code. op indicates whether
  76244. the entry is a pointer to another table, a literal, a length or
  76245. distance, an end-of-block, or an invalid code. For a table
  76246. pointer, the low four bits of op is the number of index bits of
  76247. that table. For a length or distance, the low four bits of op
  76248. is the number of extra bits to get after the code. bits is
  76249. the number of bits in this code or part of the code to drop off
  76250. of the bit buffer. val is the actual byte to output in the case
  76251. of a literal, the base length or distance, or the offset from
  76252. the current table to the next table. Each entry is four bytes. */
  76253. typedef struct {
  76254. unsigned char op; /* operation, extra bits, table bits */
  76255. unsigned char bits; /* bits in this part of the code */
  76256. unsigned short val; /* offset in table or code value */
  76257. } code;
  76258. /* op values as set by inflate_table():
  76259. 00000000 - literal
  76260. 0000tttt - table link, tttt != 0 is the number of table index bits
  76261. 0001eeee - length or distance, eeee is the number of extra bits
  76262. 01100000 - end of block
  76263. 01000000 - invalid code
  76264. */
  76265. /* Maximum size of dynamic tree. The maximum found in a long but non-
  76266. exhaustive search was 1444 code structures (852 for length/literals
  76267. and 592 for distances, the latter actually the result of an
  76268. exhaustive search). The true maximum is not known, but the value
  76269. below is more than safe. */
  76270. #define ENOUGH 2048
  76271. #define MAXD 592
  76272. /* Type of code to build for inftable() */
  76273. typedef enum {
  76274. CODES,
  76275. LENS,
  76276. DISTS
  76277. } codetype;
  76278. extern int inflate_table OF((codetype type, unsigned short FAR *lens,
  76279. unsigned codes, code FAR * FAR *table,
  76280. unsigned FAR *bits, unsigned short FAR *work));
  76281. #endif
  76282. /********* End of inlined file: inftrees.h *********/
  76283. /********* Start of inlined file: inflate.h *********/
  76284. /* WARNING: this file should *not* be used by applications. It is
  76285. part of the implementation of the compression library and is
  76286. subject to change. Applications should only use zlib.h.
  76287. */
  76288. #ifndef _INFLATE_H_
  76289. #define _INFLATE_H_
  76290. /* define NO_GZIP when compiling if you want to disable gzip header and
  76291. trailer decoding by inflate(). NO_GZIP would be used to avoid linking in
  76292. the crc code when it is not needed. For shared libraries, gzip decoding
  76293. should be left enabled. */
  76294. #ifndef NO_GZIP
  76295. # define GUNZIP
  76296. #endif
  76297. /* Possible inflate modes between inflate() calls */
  76298. typedef enum {
  76299. HEAD, /* i: waiting for magic header */
  76300. FLAGS, /* i: waiting for method and flags (gzip) */
  76301. TIME, /* i: waiting for modification time (gzip) */
  76302. OS, /* i: waiting for extra flags and operating system (gzip) */
  76303. EXLEN, /* i: waiting for extra length (gzip) */
  76304. EXTRA, /* i: waiting for extra bytes (gzip) */
  76305. NAME, /* i: waiting for end of file name (gzip) */
  76306. COMMENT, /* i: waiting for end of comment (gzip) */
  76307. HCRC, /* i: waiting for header crc (gzip) */
  76308. DICTID, /* i: waiting for dictionary check value */
  76309. DICT, /* waiting for inflateSetDictionary() call */
  76310. TYPE, /* i: waiting for type bits, including last-flag bit */
  76311. TYPEDO, /* i: same, but skip check to exit inflate on new block */
  76312. STORED, /* i: waiting for stored size (length and complement) */
  76313. COPY, /* i/o: waiting for input or output to copy stored block */
  76314. TABLE, /* i: waiting for dynamic block table lengths */
  76315. LENLENS, /* i: waiting for code length code lengths */
  76316. CODELENS, /* i: waiting for length/lit and distance code lengths */
  76317. LEN, /* i: waiting for length/lit code */
  76318. LENEXT, /* i: waiting for length extra bits */
  76319. DIST, /* i: waiting for distance code */
  76320. DISTEXT, /* i: waiting for distance extra bits */
  76321. MATCH, /* o: waiting for output space to copy string */
  76322. LIT, /* o: waiting for output space to write literal */
  76323. CHECK, /* i: waiting for 32-bit check value */
  76324. LENGTH, /* i: waiting for 32-bit length (gzip) */
  76325. DONE, /* finished check, done -- remain here until reset */
  76326. BAD, /* got a data error -- remain here until reset */
  76327. MEM, /* got an inflate() memory error -- remain here until reset */
  76328. SYNC /* looking for synchronization bytes to restart inflate() */
  76329. } inflate_mode;
  76330. /*
  76331. State transitions between above modes -
  76332. (most modes can go to the BAD or MEM mode -- not shown for clarity)
  76333. Process header:
  76334. HEAD -> (gzip) or (zlib)
  76335. (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME
  76336. NAME -> COMMENT -> HCRC -> TYPE
  76337. (zlib) -> DICTID or TYPE
  76338. DICTID -> DICT -> TYPE
  76339. Read deflate blocks:
  76340. TYPE -> STORED or TABLE or LEN or CHECK
  76341. STORED -> COPY -> TYPE
  76342. TABLE -> LENLENS -> CODELENS -> LEN
  76343. Read deflate codes:
  76344. LEN -> LENEXT or LIT or TYPE
  76345. LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
  76346. LIT -> LEN
  76347. Process trailer:
  76348. CHECK -> LENGTH -> DONE
  76349. */
  76350. /* state maintained between inflate() calls. Approximately 7K bytes. */
  76351. struct inflate_state {
  76352. inflate_mode mode; /* current inflate mode */
  76353. int last; /* true if processing last block */
  76354. int wrap; /* bit 0 true for zlib, bit 1 true for gzip */
  76355. int havedict; /* true if dictionary provided */
  76356. int flags; /* gzip header method and flags (0 if zlib) */
  76357. unsigned dmax; /* zlib header max distance (INFLATE_STRICT) */
  76358. unsigned long check; /* protected copy of check value */
  76359. unsigned long total; /* protected copy of output count */
  76360. gz_headerp head; /* where to save gzip header information */
  76361. /* sliding window */
  76362. unsigned wbits; /* log base 2 of requested window size */
  76363. unsigned wsize; /* window size or zero if not using window */
  76364. unsigned whave; /* valid bytes in the window */
  76365. unsigned write; /* window write index */
  76366. unsigned char FAR *window; /* allocated sliding window, if needed */
  76367. /* bit accumulator */
  76368. unsigned long hold; /* input bit accumulator */
  76369. unsigned bits; /* number of bits in "in" */
  76370. /* for string and stored block copying */
  76371. unsigned length; /* literal or length of data to copy */
  76372. unsigned offset; /* distance back to copy string from */
  76373. /* for table and code decoding */
  76374. unsigned extra; /* extra bits needed */
  76375. /* fixed and dynamic code tables */
  76376. code const FAR *lencode; /* starting table for length/literal codes */
  76377. code const FAR *distcode; /* starting table for distance codes */
  76378. unsigned lenbits; /* index bits for lencode */
  76379. unsigned distbits; /* index bits for distcode */
  76380. /* dynamic table building */
  76381. unsigned ncode; /* number of code length code lengths */
  76382. unsigned nlen; /* number of length code lengths */
  76383. unsigned ndist; /* number of distance code lengths */
  76384. unsigned have; /* number of code lengths in lens[] */
  76385. code FAR *next; /* next available space in codes[] */
  76386. unsigned short lens[320]; /* temporary storage for code lengths */
  76387. unsigned short work[288]; /* work area for code table building */
  76388. code codes[ENOUGH]; /* space for code tables */
  76389. };
  76390. #endif
  76391. /********* End of inlined file: inflate.h *********/
  76392. /********* Start of inlined file: inffast.h *********/
  76393. /* WARNING: this file should *not* be used by applications. It is
  76394. part of the implementation of the compression library and is
  76395. subject to change. Applications should only use zlib.h.
  76396. */
  76397. void inflate_fast OF((z_streamp strm, unsigned start));
  76398. /********* End of inlined file: inffast.h *********/
  76399. /* function prototypes */
  76400. local void fixedtables1 OF((struct inflate_state FAR *state));
  76401. /*
  76402. strm provides memory allocation functions in zalloc and zfree, or
  76403. Z_NULL to use the library memory allocation functions.
  76404. windowBits is in the range 8..15, and window is a user-supplied
  76405. window and output buffer that is 2**windowBits bytes.
  76406. */
  76407. int ZEXPORT inflateBackInit_(z_streamp strm, int windowBits, unsigned char FAR *window, const char *version, int stream_size)
  76408. {
  76409. struct inflate_state FAR *state;
  76410. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  76411. stream_size != (int)(sizeof(z_stream)))
  76412. return Z_VERSION_ERROR;
  76413. if (strm == Z_NULL || window == Z_NULL ||
  76414. windowBits < 8 || windowBits > 15)
  76415. return Z_STREAM_ERROR;
  76416. strm->msg = Z_NULL; /* in case we return an error */
  76417. if (strm->zalloc == (alloc_func)0) {
  76418. strm->zalloc = zcalloc;
  76419. strm->opaque = (voidpf)0;
  76420. }
  76421. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  76422. state = (struct inflate_state FAR *)ZALLOC(strm, 1,
  76423. sizeof(struct inflate_state));
  76424. if (state == Z_NULL) return Z_MEM_ERROR;
  76425. Tracev((stderr, "inflate: allocated\n"));
  76426. strm->state = (struct internal_state FAR *)state;
  76427. state->dmax = 32768U;
  76428. state->wbits = windowBits;
  76429. state->wsize = 1U << windowBits;
  76430. state->window = window;
  76431. state->write = 0;
  76432. state->whave = 0;
  76433. return Z_OK;
  76434. }
  76435. /*
  76436. Return state with length and distance decoding tables and index sizes set to
  76437. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  76438. If BUILDFIXED is defined, then instead this routine builds the tables the
  76439. first time it's called, and returns those tables the first time and
  76440. thereafter. This reduces the size of the code by about 2K bytes, in
  76441. exchange for a little execution time. However, BUILDFIXED should not be
  76442. used for threaded applications, since the rewriting of the tables and virgin
  76443. may not be thread-safe.
  76444. */
  76445. local void fixedtables1 (struct inflate_state FAR *state)
  76446. {
  76447. #ifdef BUILDFIXED
  76448. static int virgin = 1;
  76449. static code *lenfix, *distfix;
  76450. static code fixed[544];
  76451. /* build fixed huffman tables if first call (may not be thread safe) */
  76452. if (virgin) {
  76453. unsigned sym, bits;
  76454. static code *next;
  76455. /* literal/length table */
  76456. sym = 0;
  76457. while (sym < 144) state->lens[sym++] = 8;
  76458. while (sym < 256) state->lens[sym++] = 9;
  76459. while (sym < 280) state->lens[sym++] = 7;
  76460. while (sym < 288) state->lens[sym++] = 8;
  76461. next = fixed;
  76462. lenfix = next;
  76463. bits = 9;
  76464. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  76465. /* distance table */
  76466. sym = 0;
  76467. while (sym < 32) state->lens[sym++] = 5;
  76468. distfix = next;
  76469. bits = 5;
  76470. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  76471. /* do this just once */
  76472. virgin = 0;
  76473. }
  76474. #else /* !BUILDFIXED */
  76475. /********* Start of inlined file: inffixed.h *********/
  76476. /* inffixed.h -- table for decoding fixed codes
  76477. * Generated automatically by makefixed().
  76478. */
  76479. /* WARNING: this file should *not* be used by applications. It
  76480. is part of the implementation of the compression library and
  76481. is subject to change. Applications should only use zlib.h.
  76482. */
  76483. static const code lenfix[512] = {
  76484. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  76485. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  76486. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  76487. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  76488. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  76489. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  76490. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  76491. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  76492. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  76493. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  76494. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  76495. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  76496. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  76497. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  76498. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  76499. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  76500. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  76501. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  76502. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  76503. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  76504. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  76505. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  76506. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  76507. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  76508. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  76509. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  76510. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  76511. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  76512. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  76513. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  76514. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  76515. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  76516. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  76517. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  76518. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  76519. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  76520. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  76521. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  76522. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  76523. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  76524. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  76525. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  76526. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  76527. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  76528. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  76529. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  76530. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  76531. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  76532. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  76533. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  76534. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  76535. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  76536. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  76537. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  76538. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  76539. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  76540. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  76541. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  76542. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  76543. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  76544. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  76545. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  76546. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  76547. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  76548. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  76549. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  76550. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  76551. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  76552. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  76553. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  76554. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  76555. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  76556. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  76557. {0,9,255}
  76558. };
  76559. static const code distfix[32] = {
  76560. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  76561. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  76562. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  76563. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  76564. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  76565. {22,5,193},{64,5,0}
  76566. };
  76567. /********* End of inlined file: inffixed.h *********/
  76568. #endif /* BUILDFIXED */
  76569. state->lencode = lenfix;
  76570. state->lenbits = 9;
  76571. state->distcode = distfix;
  76572. state->distbits = 5;
  76573. }
  76574. /* Macros for inflateBack(): */
  76575. /* Load returned state from inflate_fast() */
  76576. #define LOAD() \
  76577. do { \
  76578. put = strm->next_out; \
  76579. left = strm->avail_out; \
  76580. next = strm->next_in; \
  76581. have = strm->avail_in; \
  76582. hold = state->hold; \
  76583. bits = state->bits; \
  76584. } while (0)
  76585. /* Set state from registers for inflate_fast() */
  76586. #define RESTORE() \
  76587. do { \
  76588. strm->next_out = put; \
  76589. strm->avail_out = left; \
  76590. strm->next_in = next; \
  76591. strm->avail_in = have; \
  76592. state->hold = hold; \
  76593. state->bits = bits; \
  76594. } while (0)
  76595. /* Clear the input bit accumulator */
  76596. #define INITBITS() \
  76597. do { \
  76598. hold = 0; \
  76599. bits = 0; \
  76600. } while (0)
  76601. /* Assure that some input is available. If input is requested, but denied,
  76602. then return a Z_BUF_ERROR from inflateBack(). */
  76603. #define PULL() \
  76604. do { \
  76605. if (have == 0) { \
  76606. have = in(in_desc, &next); \
  76607. if (have == 0) { \
  76608. next = Z_NULL; \
  76609. ret = Z_BUF_ERROR; \
  76610. goto inf_leave; \
  76611. } \
  76612. } \
  76613. } while (0)
  76614. /* Get a byte of input into the bit accumulator, or return from inflateBack()
  76615. with an error if there is no input available. */
  76616. #define PULLBYTE() \
  76617. do { \
  76618. PULL(); \
  76619. have--; \
  76620. hold += (unsigned long)(*next++) << bits; \
  76621. bits += 8; \
  76622. } while (0)
  76623. /* Assure that there are at least n bits in the bit accumulator. If there is
  76624. not enough available input to do that, then return from inflateBack() with
  76625. an error. */
  76626. #define NEEDBITS(n) \
  76627. do { \
  76628. while (bits < (unsigned)(n)) \
  76629. PULLBYTE(); \
  76630. } while (0)
  76631. /* Return the low n bits of the bit accumulator (n < 16) */
  76632. #define BITS(n) \
  76633. ((unsigned)hold & ((1U << (n)) - 1))
  76634. /* Remove n bits from the bit accumulator */
  76635. #define DROPBITS(n) \
  76636. do { \
  76637. hold >>= (n); \
  76638. bits -= (unsigned)(n); \
  76639. } while (0)
  76640. /* Remove zero to seven bits as needed to go to a byte boundary */
  76641. #define BYTEBITS() \
  76642. do { \
  76643. hold >>= bits & 7; \
  76644. bits -= bits & 7; \
  76645. } while (0)
  76646. /* Assure that some output space is available, by writing out the window
  76647. if it's full. If the write fails, return from inflateBack() with a
  76648. Z_BUF_ERROR. */
  76649. #define ROOM() \
  76650. do { \
  76651. if (left == 0) { \
  76652. put = state->window; \
  76653. left = state->wsize; \
  76654. state->whave = left; \
  76655. if (out(out_desc, put, left)) { \
  76656. ret = Z_BUF_ERROR; \
  76657. goto inf_leave; \
  76658. } \
  76659. } \
  76660. } while (0)
  76661. /*
  76662. strm provides the memory allocation functions and window buffer on input,
  76663. and provides information on the unused input on return. For Z_DATA_ERROR
  76664. returns, strm will also provide an error message.
  76665. in() and out() are the call-back input and output functions. When
  76666. inflateBack() needs more input, it calls in(). When inflateBack() has
  76667. filled the window with output, or when it completes with data in the
  76668. window, it calls out() to write out the data. The application must not
  76669. change the provided input until in() is called again or inflateBack()
  76670. returns. The application must not change the window/output buffer until
  76671. inflateBack() returns.
  76672. in() and out() are called with a descriptor parameter provided in the
  76673. inflateBack() call. This parameter can be a structure that provides the
  76674. information required to do the read or write, as well as accumulated
  76675. information on the input and output such as totals and check values.
  76676. in() should return zero on failure. out() should return non-zero on
  76677. failure. If either in() or out() fails, than inflateBack() returns a
  76678. Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it
  76679. was in() or out() that caused in the error. Otherwise, inflateBack()
  76680. returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
  76681. error, or Z_MEM_ERROR if it could not allocate memory for the state.
  76682. inflateBack() can also return Z_STREAM_ERROR if the input parameters
  76683. are not correct, i.e. strm is Z_NULL or the state was not initialized.
  76684. */
  76685. int ZEXPORT inflateBack(z_streamp strm, in_func in, void FAR *in_desc, out_func out, void FAR *out_desc)
  76686. {
  76687. struct inflate_state FAR *state;
  76688. unsigned char FAR *next; /* next input */
  76689. unsigned char FAR *put; /* next output */
  76690. unsigned have, left; /* available input and output */
  76691. unsigned long hold; /* bit buffer */
  76692. unsigned bits; /* bits in bit buffer */
  76693. unsigned copy; /* number of stored or match bytes to copy */
  76694. unsigned char FAR *from; /* where to copy match bytes from */
  76695. code thisx; /* current decoding table entry */
  76696. code last; /* parent table entry */
  76697. unsigned len; /* length to copy for repeats, bits to drop */
  76698. int ret; /* return code */
  76699. static const unsigned short order[19] = /* permutation of code lengths */
  76700. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  76701. /* Check that the strm exists and that the state was initialized */
  76702. if (strm == Z_NULL || strm->state == Z_NULL)
  76703. return Z_STREAM_ERROR;
  76704. state = (struct inflate_state FAR *)strm->state;
  76705. /* Reset the state */
  76706. strm->msg = Z_NULL;
  76707. state->mode = TYPE;
  76708. state->last = 0;
  76709. state->whave = 0;
  76710. next = strm->next_in;
  76711. have = next != Z_NULL ? strm->avail_in : 0;
  76712. hold = 0;
  76713. bits = 0;
  76714. put = state->window;
  76715. left = state->wsize;
  76716. /* Inflate until end of block marked as last */
  76717. for (;;)
  76718. switch (state->mode) {
  76719. case TYPE:
  76720. /* determine and dispatch block type */
  76721. if (state->last) {
  76722. BYTEBITS();
  76723. state->mode = DONE;
  76724. break;
  76725. }
  76726. NEEDBITS(3);
  76727. state->last = BITS(1);
  76728. DROPBITS(1);
  76729. switch (BITS(2)) {
  76730. case 0: /* stored block */
  76731. Tracev((stderr, "inflate: stored block%s\n",
  76732. state->last ? " (last)" : ""));
  76733. state->mode = STORED;
  76734. break;
  76735. case 1: /* fixed block */
  76736. fixedtables1(state);
  76737. Tracev((stderr, "inflate: fixed codes block%s\n",
  76738. state->last ? " (last)" : ""));
  76739. state->mode = LEN; /* decode codes */
  76740. break;
  76741. case 2: /* dynamic block */
  76742. Tracev((stderr, "inflate: dynamic codes block%s\n",
  76743. state->last ? " (last)" : ""));
  76744. state->mode = TABLE;
  76745. break;
  76746. case 3:
  76747. strm->msg = (char *)"invalid block type";
  76748. state->mode = BAD;
  76749. }
  76750. DROPBITS(2);
  76751. break;
  76752. case STORED:
  76753. /* get and verify stored block length */
  76754. BYTEBITS(); /* go to byte boundary */
  76755. NEEDBITS(32);
  76756. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  76757. strm->msg = (char *)"invalid stored block lengths";
  76758. state->mode = BAD;
  76759. break;
  76760. }
  76761. state->length = (unsigned)hold & 0xffff;
  76762. Tracev((stderr, "inflate: stored length %u\n",
  76763. state->length));
  76764. INITBITS();
  76765. /* copy stored block from input to output */
  76766. while (state->length != 0) {
  76767. copy = state->length;
  76768. PULL();
  76769. ROOM();
  76770. if (copy > have) copy = have;
  76771. if (copy > left) copy = left;
  76772. zmemcpy(put, next, copy);
  76773. have -= copy;
  76774. next += copy;
  76775. left -= copy;
  76776. put += copy;
  76777. state->length -= copy;
  76778. }
  76779. Tracev((stderr, "inflate: stored end\n"));
  76780. state->mode = TYPE;
  76781. break;
  76782. case TABLE:
  76783. /* get dynamic table entries descriptor */
  76784. NEEDBITS(14);
  76785. state->nlen = BITS(5) + 257;
  76786. DROPBITS(5);
  76787. state->ndist = BITS(5) + 1;
  76788. DROPBITS(5);
  76789. state->ncode = BITS(4) + 4;
  76790. DROPBITS(4);
  76791. #ifndef PKZIP_BUG_WORKAROUND
  76792. if (state->nlen > 286 || state->ndist > 30) {
  76793. strm->msg = (char *)"too many length or distance symbols";
  76794. state->mode = BAD;
  76795. break;
  76796. }
  76797. #endif
  76798. Tracev((stderr, "inflate: table sizes ok\n"));
  76799. /* get code length code lengths (not a typo) */
  76800. state->have = 0;
  76801. while (state->have < state->ncode) {
  76802. NEEDBITS(3);
  76803. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  76804. DROPBITS(3);
  76805. }
  76806. while (state->have < 19)
  76807. state->lens[order[state->have++]] = 0;
  76808. state->next = state->codes;
  76809. state->lencode = (code const FAR *)(state->next);
  76810. state->lenbits = 7;
  76811. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  76812. &(state->lenbits), state->work);
  76813. if (ret) {
  76814. strm->msg = (char *)"invalid code lengths set";
  76815. state->mode = BAD;
  76816. break;
  76817. }
  76818. Tracev((stderr, "inflate: code lengths ok\n"));
  76819. /* get length and distance code code lengths */
  76820. state->have = 0;
  76821. while (state->have < state->nlen + state->ndist) {
  76822. for (;;) {
  76823. thisx = state->lencode[BITS(state->lenbits)];
  76824. if ((unsigned)(thisx.bits) <= bits) break;
  76825. PULLBYTE();
  76826. }
  76827. if (thisx.val < 16) {
  76828. NEEDBITS(thisx.bits);
  76829. DROPBITS(thisx.bits);
  76830. state->lens[state->have++] = thisx.val;
  76831. }
  76832. else {
  76833. if (thisx.val == 16) {
  76834. NEEDBITS(thisx.bits + 2);
  76835. DROPBITS(thisx.bits);
  76836. if (state->have == 0) {
  76837. strm->msg = (char *)"invalid bit length repeat";
  76838. state->mode = BAD;
  76839. break;
  76840. }
  76841. len = (unsigned)(state->lens[state->have - 1]);
  76842. copy = 3 + BITS(2);
  76843. DROPBITS(2);
  76844. }
  76845. else if (thisx.val == 17) {
  76846. NEEDBITS(thisx.bits + 3);
  76847. DROPBITS(thisx.bits);
  76848. len = 0;
  76849. copy = 3 + BITS(3);
  76850. DROPBITS(3);
  76851. }
  76852. else {
  76853. NEEDBITS(thisx.bits + 7);
  76854. DROPBITS(thisx.bits);
  76855. len = 0;
  76856. copy = 11 + BITS(7);
  76857. DROPBITS(7);
  76858. }
  76859. if (state->have + copy > state->nlen + state->ndist) {
  76860. strm->msg = (char *)"invalid bit length repeat";
  76861. state->mode = BAD;
  76862. break;
  76863. }
  76864. while (copy--)
  76865. state->lens[state->have++] = (unsigned short)len;
  76866. }
  76867. }
  76868. /* handle error breaks in while */
  76869. if (state->mode == BAD) break;
  76870. /* build code tables */
  76871. state->next = state->codes;
  76872. state->lencode = (code const FAR *)(state->next);
  76873. state->lenbits = 9;
  76874. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  76875. &(state->lenbits), state->work);
  76876. if (ret) {
  76877. strm->msg = (char *)"invalid literal/lengths set";
  76878. state->mode = BAD;
  76879. break;
  76880. }
  76881. state->distcode = (code const FAR *)(state->next);
  76882. state->distbits = 6;
  76883. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  76884. &(state->next), &(state->distbits), state->work);
  76885. if (ret) {
  76886. strm->msg = (char *)"invalid distances set";
  76887. state->mode = BAD;
  76888. break;
  76889. }
  76890. Tracev((stderr, "inflate: codes ok\n"));
  76891. state->mode = LEN;
  76892. case LEN:
  76893. /* use inflate_fast() if we have enough input and output */
  76894. if (have >= 6 && left >= 258) {
  76895. RESTORE();
  76896. if (state->whave < state->wsize)
  76897. state->whave = state->wsize - left;
  76898. inflate_fast(strm, state->wsize);
  76899. LOAD();
  76900. break;
  76901. }
  76902. /* get a literal, length, or end-of-block code */
  76903. for (;;) {
  76904. thisx = state->lencode[BITS(state->lenbits)];
  76905. if ((unsigned)(thisx.bits) <= bits) break;
  76906. PULLBYTE();
  76907. }
  76908. if (thisx.op && (thisx.op & 0xf0) == 0) {
  76909. last = thisx;
  76910. for (;;) {
  76911. thisx = state->lencode[last.val +
  76912. (BITS(last.bits + last.op) >> last.bits)];
  76913. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  76914. PULLBYTE();
  76915. }
  76916. DROPBITS(last.bits);
  76917. }
  76918. DROPBITS(thisx.bits);
  76919. state->length = (unsigned)thisx.val;
  76920. /* process literal */
  76921. if (thisx.op == 0) {
  76922. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  76923. "inflate: literal '%c'\n" :
  76924. "inflate: literal 0x%02x\n", thisx.val));
  76925. ROOM();
  76926. *put++ = (unsigned char)(state->length);
  76927. left--;
  76928. state->mode = LEN;
  76929. break;
  76930. }
  76931. /* process end of block */
  76932. if (thisx.op & 32) {
  76933. Tracevv((stderr, "inflate: end of block\n"));
  76934. state->mode = TYPE;
  76935. break;
  76936. }
  76937. /* invalid code */
  76938. if (thisx.op & 64) {
  76939. strm->msg = (char *)"invalid literal/length code";
  76940. state->mode = BAD;
  76941. break;
  76942. }
  76943. /* length code -- get extra bits, if any */
  76944. state->extra = (unsigned)(thisx.op) & 15;
  76945. if (state->extra != 0) {
  76946. NEEDBITS(state->extra);
  76947. state->length += BITS(state->extra);
  76948. DROPBITS(state->extra);
  76949. }
  76950. Tracevv((stderr, "inflate: length %u\n", state->length));
  76951. /* get distance code */
  76952. for (;;) {
  76953. thisx = state->distcode[BITS(state->distbits)];
  76954. if ((unsigned)(thisx.bits) <= bits) break;
  76955. PULLBYTE();
  76956. }
  76957. if ((thisx.op & 0xf0) == 0) {
  76958. last = thisx;
  76959. for (;;) {
  76960. thisx = state->distcode[last.val +
  76961. (BITS(last.bits + last.op) >> last.bits)];
  76962. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  76963. PULLBYTE();
  76964. }
  76965. DROPBITS(last.bits);
  76966. }
  76967. DROPBITS(thisx.bits);
  76968. if (thisx.op & 64) {
  76969. strm->msg = (char *)"invalid distance code";
  76970. state->mode = BAD;
  76971. break;
  76972. }
  76973. state->offset = (unsigned)thisx.val;
  76974. /* get distance extra bits, if any */
  76975. state->extra = (unsigned)(thisx.op) & 15;
  76976. if (state->extra != 0) {
  76977. NEEDBITS(state->extra);
  76978. state->offset += BITS(state->extra);
  76979. DROPBITS(state->extra);
  76980. }
  76981. if (state->offset > state->wsize - (state->whave < state->wsize ?
  76982. left : 0)) {
  76983. strm->msg = (char *)"invalid distance too far back";
  76984. state->mode = BAD;
  76985. break;
  76986. }
  76987. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  76988. /* copy match from window to output */
  76989. do {
  76990. ROOM();
  76991. copy = state->wsize - state->offset;
  76992. if (copy < left) {
  76993. from = put + copy;
  76994. copy = left - copy;
  76995. }
  76996. else {
  76997. from = put - state->offset;
  76998. copy = left;
  76999. }
  77000. if (copy > state->length) copy = state->length;
  77001. state->length -= copy;
  77002. left -= copy;
  77003. do {
  77004. *put++ = *from++;
  77005. } while (--copy);
  77006. } while (state->length != 0);
  77007. break;
  77008. case DONE:
  77009. /* inflate stream terminated properly -- write leftover output */
  77010. ret = Z_STREAM_END;
  77011. if (left < state->wsize) {
  77012. if (out(out_desc, state->window, state->wsize - left))
  77013. ret = Z_BUF_ERROR;
  77014. }
  77015. goto inf_leave;
  77016. case BAD:
  77017. ret = Z_DATA_ERROR;
  77018. goto inf_leave;
  77019. default: /* can't happen, but makes compilers happy */
  77020. ret = Z_STREAM_ERROR;
  77021. goto inf_leave;
  77022. }
  77023. /* Return unused input */
  77024. inf_leave:
  77025. strm->next_in = next;
  77026. strm->avail_in = have;
  77027. return ret;
  77028. }
  77029. int ZEXPORT inflateBackEnd (z_streamp strm)
  77030. {
  77031. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  77032. return Z_STREAM_ERROR;
  77033. ZFREE(strm, strm->state);
  77034. strm->state = Z_NULL;
  77035. Tracev((stderr, "inflate: end\n"));
  77036. return Z_OK;
  77037. }
  77038. /********* End of inlined file: infback.c *********/
  77039. /********* Start of inlined file: inffast.c *********/
  77040. /********* Start of inlined file: inffast.h *********/
  77041. /* WARNING: this file should *not* be used by applications. It is
  77042. part of the implementation of the compression library and is
  77043. subject to change. Applications should only use zlib.h.
  77044. */
  77045. void inflate_fast OF((z_streamp strm, unsigned start));
  77046. /********* End of inlined file: inffast.h *********/
  77047. #ifndef ASMINF
  77048. /* Allow machine dependent optimization for post-increment or pre-increment.
  77049. Based on testing to date,
  77050. Pre-increment preferred for:
  77051. - PowerPC G3 (Adler)
  77052. - MIPS R5000 (Randers-Pehrson)
  77053. Post-increment preferred for:
  77054. - none
  77055. No measurable difference:
  77056. - Pentium III (Anderson)
  77057. - M68060 (Nikl)
  77058. */
  77059. #ifdef POSTINC
  77060. # define OFF 0
  77061. # define PUP(a) *(a)++
  77062. #else
  77063. # define OFF 1
  77064. # define PUP(a) *++(a)
  77065. #endif
  77066. /*
  77067. Decode literal, length, and distance codes and write out the resulting
  77068. literal and match bytes until either not enough input or output is
  77069. available, an end-of-block is encountered, or a data error is encountered.
  77070. When large enough input and output buffers are supplied to inflate(), for
  77071. example, a 16K input buffer and a 64K output buffer, more than 95% of the
  77072. inflate execution time is spent in this routine.
  77073. Entry assumptions:
  77074. state->mode == LEN
  77075. strm->avail_in >= 6
  77076. strm->avail_out >= 258
  77077. start >= strm->avail_out
  77078. state->bits < 8
  77079. On return, state->mode is one of:
  77080. LEN -- ran out of enough output space or enough available input
  77081. TYPE -- reached end of block code, inflate() to interpret next block
  77082. BAD -- error in block data
  77083. Notes:
  77084. - The maximum input bits used by a length/distance pair is 15 bits for the
  77085. length code, 5 bits for the length extra, 15 bits for the distance code,
  77086. and 13 bits for the distance extra. This totals 48 bits, or six bytes.
  77087. Therefore if strm->avail_in >= 6, then there is enough input to avoid
  77088. checking for available input while decoding.
  77089. - The maximum bytes that a single length/distance pair can output is 258
  77090. bytes, which is the maximum length that can be coded. inflate_fast()
  77091. requires strm->avail_out >= 258 for each loop to avoid checking for
  77092. output space.
  77093. */
  77094. void inflate_fast (z_streamp strm, unsigned start)
  77095. {
  77096. struct inflate_state FAR *state;
  77097. unsigned char FAR *in; /* local strm->next_in */
  77098. unsigned char FAR *last; /* while in < last, enough input available */
  77099. unsigned char FAR *out; /* local strm->next_out */
  77100. unsigned char FAR *beg; /* inflate()'s initial strm->next_out */
  77101. unsigned char FAR *end; /* while out < end, enough space available */
  77102. #ifdef INFLATE_STRICT
  77103. unsigned dmax; /* maximum distance from zlib header */
  77104. #endif
  77105. unsigned wsize; /* window size or zero if not using window */
  77106. unsigned whave; /* valid bytes in the window */
  77107. unsigned write; /* window write index */
  77108. unsigned char FAR *window; /* allocated sliding window, if wsize != 0 */
  77109. unsigned long hold; /* local strm->hold */
  77110. unsigned bits; /* local strm->bits */
  77111. code const FAR *lcode; /* local strm->lencode */
  77112. code const FAR *dcode; /* local strm->distcode */
  77113. unsigned lmask; /* mask for first level of length codes */
  77114. unsigned dmask; /* mask for first level of distance codes */
  77115. code thisx; /* retrieved table entry */
  77116. unsigned op; /* code bits, operation, extra bits, or */
  77117. /* window position, window bytes to copy */
  77118. unsigned len; /* match length, unused bytes */
  77119. unsigned dist; /* match distance */
  77120. unsigned char FAR *from; /* where to copy match from */
  77121. /* copy state to local variables */
  77122. state = (struct inflate_state FAR *)strm->state;
  77123. in = strm->next_in - OFF;
  77124. last = in + (strm->avail_in - 5);
  77125. out = strm->next_out - OFF;
  77126. beg = out - (start - strm->avail_out);
  77127. end = out + (strm->avail_out - 257);
  77128. #ifdef INFLATE_STRICT
  77129. dmax = state->dmax;
  77130. #endif
  77131. wsize = state->wsize;
  77132. whave = state->whave;
  77133. write = state->write;
  77134. window = state->window;
  77135. hold = state->hold;
  77136. bits = state->bits;
  77137. lcode = state->lencode;
  77138. dcode = state->distcode;
  77139. lmask = (1U << state->lenbits) - 1;
  77140. dmask = (1U << state->distbits) - 1;
  77141. /* decode literals and length/distances until end-of-block or not enough
  77142. input data or output space */
  77143. do {
  77144. if (bits < 15) {
  77145. hold += (unsigned long)(PUP(in)) << bits;
  77146. bits += 8;
  77147. hold += (unsigned long)(PUP(in)) << bits;
  77148. bits += 8;
  77149. }
  77150. thisx = lcode[hold & lmask];
  77151. dolen:
  77152. op = (unsigned)(thisx.bits);
  77153. hold >>= op;
  77154. bits -= op;
  77155. op = (unsigned)(thisx.op);
  77156. if (op == 0) { /* literal */
  77157. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  77158. "inflate: literal '%c'\n" :
  77159. "inflate: literal 0x%02x\n", thisx.val));
  77160. PUP(out) = (unsigned char)(thisx.val);
  77161. }
  77162. else if (op & 16) { /* length base */
  77163. len = (unsigned)(thisx.val);
  77164. op &= 15; /* number of extra bits */
  77165. if (op) {
  77166. if (bits < op) {
  77167. hold += (unsigned long)(PUP(in)) << bits;
  77168. bits += 8;
  77169. }
  77170. len += (unsigned)hold & ((1U << op) - 1);
  77171. hold >>= op;
  77172. bits -= op;
  77173. }
  77174. Tracevv((stderr, "inflate: length %u\n", len));
  77175. if (bits < 15) {
  77176. hold += (unsigned long)(PUP(in)) << bits;
  77177. bits += 8;
  77178. hold += (unsigned long)(PUP(in)) << bits;
  77179. bits += 8;
  77180. }
  77181. thisx = dcode[hold & dmask];
  77182. dodist:
  77183. op = (unsigned)(thisx.bits);
  77184. hold >>= op;
  77185. bits -= op;
  77186. op = (unsigned)(thisx.op);
  77187. if (op & 16) { /* distance base */
  77188. dist = (unsigned)(thisx.val);
  77189. op &= 15; /* number of extra bits */
  77190. if (bits < op) {
  77191. hold += (unsigned long)(PUP(in)) << bits;
  77192. bits += 8;
  77193. if (bits < op) {
  77194. hold += (unsigned long)(PUP(in)) << bits;
  77195. bits += 8;
  77196. }
  77197. }
  77198. dist += (unsigned)hold & ((1U << op) - 1);
  77199. #ifdef INFLATE_STRICT
  77200. if (dist > dmax) {
  77201. strm->msg = (char *)"invalid distance too far back";
  77202. state->mode = BAD;
  77203. break;
  77204. }
  77205. #endif
  77206. hold >>= op;
  77207. bits -= op;
  77208. Tracevv((stderr, "inflate: distance %u\n", dist));
  77209. op = (unsigned)(out - beg); /* max distance in output */
  77210. if (dist > op) { /* see if copy from window */
  77211. op = dist - op; /* distance back in window */
  77212. if (op > whave) {
  77213. strm->msg = (char *)"invalid distance too far back";
  77214. state->mode = BAD;
  77215. break;
  77216. }
  77217. from = window - OFF;
  77218. if (write == 0) { /* very common case */
  77219. from += wsize - op;
  77220. if (op < len) { /* some from window */
  77221. len -= op;
  77222. do {
  77223. PUP(out) = PUP(from);
  77224. } while (--op);
  77225. from = out - dist; /* rest from output */
  77226. }
  77227. }
  77228. else if (write < op) { /* wrap around window */
  77229. from += wsize + write - op;
  77230. op -= write;
  77231. if (op < len) { /* some from end of window */
  77232. len -= op;
  77233. do {
  77234. PUP(out) = PUP(from);
  77235. } while (--op);
  77236. from = window - OFF;
  77237. if (write < len) { /* some from start of window */
  77238. op = write;
  77239. len -= op;
  77240. do {
  77241. PUP(out) = PUP(from);
  77242. } while (--op);
  77243. from = out - dist; /* rest from output */
  77244. }
  77245. }
  77246. }
  77247. else { /* contiguous in window */
  77248. from += write - op;
  77249. if (op < len) { /* some from window */
  77250. len -= op;
  77251. do {
  77252. PUP(out) = PUP(from);
  77253. } while (--op);
  77254. from = out - dist; /* rest from output */
  77255. }
  77256. }
  77257. while (len > 2) {
  77258. PUP(out) = PUP(from);
  77259. PUP(out) = PUP(from);
  77260. PUP(out) = PUP(from);
  77261. len -= 3;
  77262. }
  77263. if (len) {
  77264. PUP(out) = PUP(from);
  77265. if (len > 1)
  77266. PUP(out) = PUP(from);
  77267. }
  77268. }
  77269. else {
  77270. from = out - dist; /* copy direct from output */
  77271. do { /* minimum length is three */
  77272. PUP(out) = PUP(from);
  77273. PUP(out) = PUP(from);
  77274. PUP(out) = PUP(from);
  77275. len -= 3;
  77276. } while (len > 2);
  77277. if (len) {
  77278. PUP(out) = PUP(from);
  77279. if (len > 1)
  77280. PUP(out) = PUP(from);
  77281. }
  77282. }
  77283. }
  77284. else if ((op & 64) == 0) { /* 2nd level distance code */
  77285. thisx = dcode[thisx.val + (hold & ((1U << op) - 1))];
  77286. goto dodist;
  77287. }
  77288. else {
  77289. strm->msg = (char *)"invalid distance code";
  77290. state->mode = BAD;
  77291. break;
  77292. }
  77293. }
  77294. else if ((op & 64) == 0) { /* 2nd level length code */
  77295. thisx = lcode[thisx.val + (hold & ((1U << op) - 1))];
  77296. goto dolen;
  77297. }
  77298. else if (op & 32) { /* end-of-block */
  77299. Tracevv((stderr, "inflate: end of block\n"));
  77300. state->mode = TYPE;
  77301. break;
  77302. }
  77303. else {
  77304. strm->msg = (char *)"invalid literal/length code";
  77305. state->mode = BAD;
  77306. break;
  77307. }
  77308. } while (in < last && out < end);
  77309. /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
  77310. len = bits >> 3;
  77311. in -= len;
  77312. bits -= len << 3;
  77313. hold &= (1U << bits) - 1;
  77314. /* update state and return */
  77315. strm->next_in = in + OFF;
  77316. strm->next_out = out + OFF;
  77317. strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
  77318. strm->avail_out = (unsigned)(out < end ?
  77319. 257 + (end - out) : 257 - (out - end));
  77320. state->hold = hold;
  77321. state->bits = bits;
  77322. return;
  77323. }
  77324. /*
  77325. inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
  77326. - Using bit fields for code structure
  77327. - Different op definition to avoid & for extra bits (do & for table bits)
  77328. - Three separate decoding do-loops for direct, window, and write == 0
  77329. - Special case for distance > 1 copies to do overlapped load and store copy
  77330. - Explicit branch predictions (based on measured branch probabilities)
  77331. - Deferring match copy and interspersed it with decoding subsequent codes
  77332. - Swapping literal/length else
  77333. - Swapping window/direct else
  77334. - Larger unrolled copy loops (three is about right)
  77335. - Moving len -= 3 statement into middle of loop
  77336. */
  77337. #endif /* !ASMINF */
  77338. /********* End of inlined file: inffast.c *********/
  77339. #undef PULLBYTE
  77340. #undef LOAD
  77341. #undef RESTORE
  77342. #undef INITBITS
  77343. #undef NEEDBITS
  77344. #undef DROPBITS
  77345. #undef BYTEBITS
  77346. /********* Start of inlined file: inflate.c *********/
  77347. /*
  77348. * Change history:
  77349. *
  77350. * 1.2.beta0 24 Nov 2002
  77351. * - First version -- complete rewrite of inflate to simplify code, avoid
  77352. * creation of window when not needed, minimize use of window when it is
  77353. * needed, make inffast.c even faster, implement gzip decoding, and to
  77354. * improve code readability and style over the previous zlib inflate code
  77355. *
  77356. * 1.2.beta1 25 Nov 2002
  77357. * - Use pointers for available input and output checking in inffast.c
  77358. * - Remove input and output counters in inffast.c
  77359. * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
  77360. * - Remove unnecessary second byte pull from length extra in inffast.c
  77361. * - Unroll direct copy to three copies per loop in inffast.c
  77362. *
  77363. * 1.2.beta2 4 Dec 2002
  77364. * - Change external routine names to reduce potential conflicts
  77365. * - Correct filename to inffixed.h for fixed tables in inflate.c
  77366. * - Make hbuf[] unsigned char to match parameter type in inflate.c
  77367. * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
  77368. * to avoid negation problem on Alphas (64 bit) in inflate.c
  77369. *
  77370. * 1.2.beta3 22 Dec 2002
  77371. * - Add comments on state->bits assertion in inffast.c
  77372. * - Add comments on op field in inftrees.h
  77373. * - Fix bug in reuse of allocated window after inflateReset()
  77374. * - Remove bit fields--back to byte structure for speed
  77375. * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
  77376. * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
  77377. * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
  77378. * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
  77379. * - Use local copies of stream next and avail values, as well as local bit
  77380. * buffer and bit count in inflate()--for speed when inflate_fast() not used
  77381. *
  77382. * 1.2.beta4 1 Jan 2003
  77383. * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
  77384. * - Move a comment on output buffer sizes from inffast.c to inflate.c
  77385. * - Add comments in inffast.c to introduce the inflate_fast() routine
  77386. * - Rearrange window copies in inflate_fast() for speed and simplification
  77387. * - Unroll last copy for window match in inflate_fast()
  77388. * - Use local copies of window variables in inflate_fast() for speed
  77389. * - Pull out common write == 0 case for speed in inflate_fast()
  77390. * - Make op and len in inflate_fast() unsigned for consistency
  77391. * - Add FAR to lcode and dcode declarations in inflate_fast()
  77392. * - Simplified bad distance check in inflate_fast()
  77393. * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
  77394. * source file infback.c to provide a call-back interface to inflate for
  77395. * programs like gzip and unzip -- uses window as output buffer to avoid
  77396. * window copying
  77397. *
  77398. * 1.2.beta5 1 Jan 2003
  77399. * - Improved inflateBack() interface to allow the caller to provide initial
  77400. * input in strm.
  77401. * - Fixed stored blocks bug in inflateBack()
  77402. *
  77403. * 1.2.beta6 4 Jan 2003
  77404. * - Added comments in inffast.c on effectiveness of POSTINC
  77405. * - Typecasting all around to reduce compiler warnings
  77406. * - Changed loops from while (1) or do {} while (1) to for (;;), again to
  77407. * make compilers happy
  77408. * - Changed type of window in inflateBackInit() to unsigned char *
  77409. *
  77410. * 1.2.beta7 27 Jan 2003
  77411. * - Changed many types to unsigned or unsigned short to avoid warnings
  77412. * - Added inflateCopy() function
  77413. *
  77414. * 1.2.0 9 Mar 2003
  77415. * - Changed inflateBack() interface to provide separate opaque descriptors
  77416. * for the in() and out() functions
  77417. * - Changed inflateBack() argument and in_func typedef to swap the length
  77418. * and buffer address return values for the input function
  77419. * - Check next_in and next_out for Z_NULL on entry to inflate()
  77420. *
  77421. * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
  77422. */
  77423. /********* Start of inlined file: inffast.h *********/
  77424. /* WARNING: this file should *not* be used by applications. It is
  77425. part of the implementation of the compression library and is
  77426. subject to change. Applications should only use zlib.h.
  77427. */
  77428. void inflate_fast OF((z_streamp strm, unsigned start));
  77429. /********* End of inlined file: inffast.h *********/
  77430. #ifdef MAKEFIXED
  77431. # ifndef BUILDFIXED
  77432. # define BUILDFIXED
  77433. # endif
  77434. #endif
  77435. /* function prototypes */
  77436. local void fixedtables OF((struct inflate_state FAR *state));
  77437. local int updatewindow OF((z_streamp strm, unsigned out));
  77438. #ifdef BUILDFIXED
  77439. void makefixed OF((void));
  77440. #endif
  77441. local unsigned syncsearch OF((unsigned FAR *have, unsigned char FAR *buf,
  77442. unsigned len));
  77443. int ZEXPORT inflateReset (z_streamp strm)
  77444. {
  77445. struct inflate_state FAR *state;
  77446. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77447. state = (struct inflate_state FAR *)strm->state;
  77448. strm->total_in = strm->total_out = state->total = 0;
  77449. strm->msg = Z_NULL;
  77450. strm->adler = 1; /* to support ill-conceived Java test suite */
  77451. state->mode = HEAD;
  77452. state->last = 0;
  77453. state->havedict = 0;
  77454. state->dmax = 32768U;
  77455. state->head = Z_NULL;
  77456. state->wsize = 0;
  77457. state->whave = 0;
  77458. state->write = 0;
  77459. state->hold = 0;
  77460. state->bits = 0;
  77461. state->lencode = state->distcode = state->next = state->codes;
  77462. Tracev((stderr, "inflate: reset\n"));
  77463. return Z_OK;
  77464. }
  77465. int ZEXPORT inflatePrime (z_streamp strm, int bits, int value)
  77466. {
  77467. struct inflate_state FAR *state;
  77468. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  77469. state = (struct inflate_state FAR *)strm->state;
  77470. if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
  77471. value &= (1L << bits) - 1;
  77472. state->hold += value << state->bits;
  77473. state->bits += bits;
  77474. return Z_OK;
  77475. }
  77476. int ZEXPORT inflateInit2_(z_streamp strm, int windowBits, const char *version, int stream_size)
  77477. {
  77478. struct inflate_state FAR *state;
  77479. if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
  77480. stream_size != (int)(sizeof(z_stream)))
  77481. return Z_VERSION_ERROR;
  77482. if (strm == Z_NULL) return Z_STREAM_ERROR;
  77483. strm->msg = Z_NULL; /* in case we return an error */
  77484. if (strm->zalloc == (alloc_func)0) {
  77485. strm->zalloc = zcalloc;
  77486. strm->opaque = (voidpf)0;
  77487. }
  77488. if (strm->zfree == (free_func)0) strm->zfree = zcfree;
  77489. state = (struct inflate_state FAR *)
  77490. ZALLOC(strm, 1, sizeof(struct inflate_state));
  77491. if (state == Z_NULL) return Z_MEM_ERROR;
  77492. Tracev((stderr, "inflate: allocated\n"));
  77493. strm->state = (struct internal_state FAR *)state;
  77494. if (windowBits < 0) {
  77495. state->wrap = 0;
  77496. windowBits = -windowBits;
  77497. }
  77498. else {
  77499. state->wrap = (windowBits >> 4) + 1;
  77500. #ifdef GUNZIP
  77501. if (windowBits < 48) windowBits &= 15;
  77502. #endif
  77503. }
  77504. if (windowBits < 8 || windowBits > 15) {
  77505. ZFREE(strm, state);
  77506. strm->state = Z_NULL;
  77507. return Z_STREAM_ERROR;
  77508. }
  77509. state->wbits = (unsigned)windowBits;
  77510. state->window = Z_NULL;
  77511. return inflateReset(strm);
  77512. }
  77513. int ZEXPORT inflateInit_ (z_streamp strm, const char *version, int stream_size)
  77514. {
  77515. return inflateInit2_(strm, DEF_WBITS, version, stream_size);
  77516. }
  77517. /*
  77518. Return state with length and distance decoding tables and index sizes set to
  77519. fixed code decoding. Normally this returns fixed tables from inffixed.h.
  77520. If BUILDFIXED is defined, then instead this routine builds the tables the
  77521. first time it's called, and returns those tables the first time and
  77522. thereafter. This reduces the size of the code by about 2K bytes, in
  77523. exchange for a little execution time. However, BUILDFIXED should not be
  77524. used for threaded applications, since the rewriting of the tables and virgin
  77525. may not be thread-safe.
  77526. */
  77527. local void fixedtables (struct inflate_state FAR *state)
  77528. {
  77529. #ifdef BUILDFIXED
  77530. static int virgin = 1;
  77531. static code *lenfix, *distfix;
  77532. static code fixed[544];
  77533. /* build fixed huffman tables if first call (may not be thread safe) */
  77534. if (virgin) {
  77535. unsigned sym, bits;
  77536. static code *next;
  77537. /* literal/length table */
  77538. sym = 0;
  77539. while (sym < 144) state->lens[sym++] = 8;
  77540. while (sym < 256) state->lens[sym++] = 9;
  77541. while (sym < 280) state->lens[sym++] = 7;
  77542. while (sym < 288) state->lens[sym++] = 8;
  77543. next = fixed;
  77544. lenfix = next;
  77545. bits = 9;
  77546. inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
  77547. /* distance table */
  77548. sym = 0;
  77549. while (sym < 32) state->lens[sym++] = 5;
  77550. distfix = next;
  77551. bits = 5;
  77552. inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
  77553. /* do this just once */
  77554. virgin = 0;
  77555. }
  77556. #else /* !BUILDFIXED */
  77557. /********* Start of inlined file: inffixed.h *********/
  77558. /* inffixed.h -- table for decoding fixed codes
  77559. * Generated automatically by makefixed().
  77560. */
  77561. /* WARNING: this file should *not* be used by applications. It
  77562. is part of the implementation of the compression library and
  77563. is subject to change. Applications should only use zlib.h.
  77564. */
  77565. static const code lenfix[512] = {
  77566. {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
  77567. {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
  77568. {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
  77569. {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
  77570. {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
  77571. {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
  77572. {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
  77573. {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
  77574. {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
  77575. {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
  77576. {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
  77577. {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
  77578. {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
  77579. {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
  77580. {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
  77581. {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
  77582. {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
  77583. {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
  77584. {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
  77585. {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
  77586. {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
  77587. {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
  77588. {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
  77589. {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
  77590. {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
  77591. {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
  77592. {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
  77593. {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
  77594. {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
  77595. {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
  77596. {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
  77597. {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
  77598. {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
  77599. {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
  77600. {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
  77601. {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
  77602. {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
  77603. {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
  77604. {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
  77605. {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
  77606. {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
  77607. {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
  77608. {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
  77609. {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
  77610. {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
  77611. {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
  77612. {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
  77613. {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
  77614. {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
  77615. {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
  77616. {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
  77617. {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
  77618. {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
  77619. {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
  77620. {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
  77621. {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
  77622. {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
  77623. {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
  77624. {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
  77625. {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
  77626. {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
  77627. {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
  77628. {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
  77629. {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
  77630. {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
  77631. {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
  77632. {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
  77633. {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
  77634. {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
  77635. {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
  77636. {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
  77637. {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
  77638. {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
  77639. {0,9,255}
  77640. };
  77641. static const code distfix[32] = {
  77642. {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
  77643. {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
  77644. {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
  77645. {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
  77646. {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
  77647. {22,5,193},{64,5,0}
  77648. };
  77649. /********* End of inlined file: inffixed.h *********/
  77650. #endif /* BUILDFIXED */
  77651. state->lencode = lenfix;
  77652. state->lenbits = 9;
  77653. state->distcode = distfix;
  77654. state->distbits = 5;
  77655. }
  77656. #ifdef MAKEFIXED
  77657. #include <stdio.h>
  77658. /*
  77659. Write out the inffixed.h that is #include'd above. Defining MAKEFIXED also
  77660. defines BUILDFIXED, so the tables are built on the fly. makefixed() writes
  77661. those tables to stdout, which would be piped to inffixed.h. A small program
  77662. can simply call makefixed to do this:
  77663. void makefixed(void);
  77664. int main(void)
  77665. {
  77666. makefixed();
  77667. return 0;
  77668. }
  77669. Then that can be linked with zlib built with MAKEFIXED defined and run:
  77670. a.out > inffixed.h
  77671. */
  77672. void makefixed()
  77673. {
  77674. unsigned low, size;
  77675. struct inflate_state state;
  77676. fixedtables(&state);
  77677. puts(" /* inffixed.h -- table for decoding fixed codes");
  77678. puts(" * Generated automatically by makefixed().");
  77679. puts(" */");
  77680. puts("");
  77681. puts(" /* WARNING: this file should *not* be used by applications.");
  77682. puts(" It is part of the implementation of this library and is");
  77683. puts(" subject to change. Applications should only use zlib.h.");
  77684. puts(" */");
  77685. puts("");
  77686. size = 1U << 9;
  77687. printf(" static const code lenfix[%u] = {", size);
  77688. low = 0;
  77689. for (;;) {
  77690. if ((low % 7) == 0) printf("\n ");
  77691. printf("{%u,%u,%d}", state.lencode[low].op, state.lencode[low].bits,
  77692. state.lencode[low].val);
  77693. if (++low == size) break;
  77694. putchar(',');
  77695. }
  77696. puts("\n };");
  77697. size = 1U << 5;
  77698. printf("\n static const code distfix[%u] = {", size);
  77699. low = 0;
  77700. for (;;) {
  77701. if ((low % 6) == 0) printf("\n ");
  77702. printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
  77703. state.distcode[low].val);
  77704. if (++low == size) break;
  77705. putchar(',');
  77706. }
  77707. puts("\n };");
  77708. }
  77709. #endif /* MAKEFIXED */
  77710. /*
  77711. Update the window with the last wsize (normally 32K) bytes written before
  77712. returning. If window does not exist yet, create it. This is only called
  77713. when a window is already in use, or when output has been written during this
  77714. inflate call, but the end of the deflate stream has not been reached yet.
  77715. It is also called to create a window for dictionary data when a dictionary
  77716. is loaded.
  77717. Providing output buffers larger than 32K to inflate() should provide a speed
  77718. advantage, since only the last 32K of output is copied to the sliding window
  77719. upon return from inflate(), and since all distances after the first 32K of
  77720. output will fall in the output data, making match copies simpler and faster.
  77721. The advantage may be dependent on the size of the processor's data caches.
  77722. */
  77723. local int updatewindow (z_streamp strm, unsigned out)
  77724. {
  77725. struct inflate_state FAR *state;
  77726. unsigned copy, dist;
  77727. state = (struct inflate_state FAR *)strm->state;
  77728. /* if it hasn't been done already, allocate space for the window */
  77729. if (state->window == Z_NULL) {
  77730. state->window = (unsigned char FAR *)
  77731. ZALLOC(strm, 1U << state->wbits,
  77732. sizeof(unsigned char));
  77733. if (state->window == Z_NULL) return 1;
  77734. }
  77735. /* if window not in use yet, initialize */
  77736. if (state->wsize == 0) {
  77737. state->wsize = 1U << state->wbits;
  77738. state->write = 0;
  77739. state->whave = 0;
  77740. }
  77741. /* copy state->wsize or less output bytes into the circular window */
  77742. copy = out - strm->avail_out;
  77743. if (copy >= state->wsize) {
  77744. zmemcpy(state->window, strm->next_out - state->wsize, state->wsize);
  77745. state->write = 0;
  77746. state->whave = state->wsize;
  77747. }
  77748. else {
  77749. dist = state->wsize - state->write;
  77750. if (dist > copy) dist = copy;
  77751. zmemcpy(state->window + state->write, strm->next_out - copy, dist);
  77752. copy -= dist;
  77753. if (copy) {
  77754. zmemcpy(state->window, strm->next_out - copy, copy);
  77755. state->write = copy;
  77756. state->whave = state->wsize;
  77757. }
  77758. else {
  77759. state->write += dist;
  77760. if (state->write == state->wsize) state->write = 0;
  77761. if (state->whave < state->wsize) state->whave += dist;
  77762. }
  77763. }
  77764. return 0;
  77765. }
  77766. /* Macros for inflate(): */
  77767. /* check function to use adler32() for zlib or crc32() for gzip */
  77768. #ifdef GUNZIP
  77769. # define UPDATE(check, buf, len) \
  77770. (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
  77771. #else
  77772. # define UPDATE(check, buf, len) adler32(check, buf, len)
  77773. #endif
  77774. /* check macros for header crc */
  77775. #ifdef GUNZIP
  77776. # define CRC2(check, word) \
  77777. do { \
  77778. hbuf[0] = (unsigned char)(word); \
  77779. hbuf[1] = (unsigned char)((word) >> 8); \
  77780. check = crc32(check, hbuf, 2); \
  77781. } while (0)
  77782. # define CRC4(check, word) \
  77783. do { \
  77784. hbuf[0] = (unsigned char)(word); \
  77785. hbuf[1] = (unsigned char)((word) >> 8); \
  77786. hbuf[2] = (unsigned char)((word) >> 16); \
  77787. hbuf[3] = (unsigned char)((word) >> 24); \
  77788. check = crc32(check, hbuf, 4); \
  77789. } while (0)
  77790. #endif
  77791. /* Load registers with state in inflate() for speed */
  77792. #define LOAD() \
  77793. do { \
  77794. put = strm->next_out; \
  77795. left = strm->avail_out; \
  77796. next = strm->next_in; \
  77797. have = strm->avail_in; \
  77798. hold = state->hold; \
  77799. bits = state->bits; \
  77800. } while (0)
  77801. /* Restore state from registers in inflate() */
  77802. #define RESTORE() \
  77803. do { \
  77804. strm->next_out = put; \
  77805. strm->avail_out = left; \
  77806. strm->next_in = next; \
  77807. strm->avail_in = have; \
  77808. state->hold = hold; \
  77809. state->bits = bits; \
  77810. } while (0)
  77811. /* Clear the input bit accumulator */
  77812. #define INITBITS() \
  77813. do { \
  77814. hold = 0; \
  77815. bits = 0; \
  77816. } while (0)
  77817. /* Get a byte of input into the bit accumulator, or return from inflate()
  77818. if there is no input available. */
  77819. #define PULLBYTE() \
  77820. do { \
  77821. if (have == 0) goto inf_leave; \
  77822. have--; \
  77823. hold += (unsigned long)(*next++) << bits; \
  77824. bits += 8; \
  77825. } while (0)
  77826. /* Assure that there are at least n bits in the bit accumulator. If there is
  77827. not enough available input to do that, then return from inflate(). */
  77828. #define NEEDBITS(n) \
  77829. do { \
  77830. while (bits < (unsigned)(n)) \
  77831. PULLBYTE(); \
  77832. } while (0)
  77833. /* Return the low n bits of the bit accumulator (n < 16) */
  77834. #define BITS(n) \
  77835. ((unsigned)hold & ((1U << (n)) - 1))
  77836. /* Remove n bits from the bit accumulator */
  77837. #define DROPBITS(n) \
  77838. do { \
  77839. hold >>= (n); \
  77840. bits -= (unsigned)(n); \
  77841. } while (0)
  77842. /* Remove zero to seven bits as needed to go to a byte boundary */
  77843. #define BYTEBITS() \
  77844. do { \
  77845. hold >>= bits & 7; \
  77846. bits -= bits & 7; \
  77847. } while (0)
  77848. /* Reverse the bytes in a 32-bit value */
  77849. #define REVERSE(q) \
  77850. ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
  77851. (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
  77852. /*
  77853. inflate() uses a state machine to process as much input data and generate as
  77854. much output data as possible before returning. The state machine is
  77855. structured roughly as follows:
  77856. for (;;) switch (state) {
  77857. ...
  77858. case STATEn:
  77859. if (not enough input data or output space to make progress)
  77860. return;
  77861. ... make progress ...
  77862. state = STATEm;
  77863. break;
  77864. ...
  77865. }
  77866. so when inflate() is called again, the same case is attempted again, and
  77867. if the appropriate resources are provided, the machine proceeds to the
  77868. next state. The NEEDBITS() macro is usually the way the state evaluates
  77869. whether it can proceed or should return. NEEDBITS() does the return if
  77870. the requested bits are not available. The typical use of the BITS macros
  77871. is:
  77872. NEEDBITS(n);
  77873. ... do something with BITS(n) ...
  77874. DROPBITS(n);
  77875. where NEEDBITS(n) either returns from inflate() if there isn't enough
  77876. input left to load n bits into the accumulator, or it continues. BITS(n)
  77877. gives the low n bits in the accumulator. When done, DROPBITS(n) drops
  77878. the low n bits off the accumulator. INITBITS() clears the accumulator
  77879. and sets the number of available bits to zero. BYTEBITS() discards just
  77880. enough bits to put the accumulator on a byte boundary. After BYTEBITS()
  77881. and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
  77882. NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
  77883. if there is no input available. The decoding of variable length codes uses
  77884. PULLBYTE() directly in order to pull just enough bytes to decode the next
  77885. code, and no more.
  77886. Some states loop until they get enough input, making sure that enough
  77887. state information is maintained to continue the loop where it left off
  77888. if NEEDBITS() returns in the loop. For example, want, need, and keep
  77889. would all have to actually be part of the saved state in case NEEDBITS()
  77890. returns:
  77891. case STATEw:
  77892. while (want < need) {
  77893. NEEDBITS(n);
  77894. keep[want++] = BITS(n);
  77895. DROPBITS(n);
  77896. }
  77897. state = STATEx;
  77898. case STATEx:
  77899. As shown above, if the next state is also the next case, then the break
  77900. is omitted.
  77901. A state may also return if there is not enough output space available to
  77902. complete that state. Those states are copying stored data, writing a
  77903. literal byte, and copying a matching string.
  77904. When returning, a "goto inf_leave" is used to update the total counters,
  77905. update the check value, and determine whether any progress has been made
  77906. during that inflate() call in order to return the proper return code.
  77907. Progress is defined as a change in either strm->avail_in or strm->avail_out.
  77908. When there is a window, goto inf_leave will update the window with the last
  77909. output written. If a goto inf_leave occurs in the middle of decompression
  77910. and there is no window currently, goto inf_leave will create one and copy
  77911. output to the window for the next call of inflate().
  77912. In this implementation, the flush parameter of inflate() only affects the
  77913. return code (per zlib.h). inflate() always writes as much as possible to
  77914. strm->next_out, given the space available and the provided input--the effect
  77915. documented in zlib.h of Z_SYNC_FLUSH. Furthermore, inflate() always defers
  77916. the allocation of and copying into a sliding window until necessary, which
  77917. provides the effect documented in zlib.h for Z_FINISH when the entire input
  77918. stream available. So the only thing the flush parameter actually does is:
  77919. when flush is set to Z_FINISH, inflate() cannot return Z_OK. Instead it
  77920. will return Z_BUF_ERROR if it has not reached the end of the stream.
  77921. */
  77922. int ZEXPORT inflate (z_streamp strm, int flush)
  77923. {
  77924. struct inflate_state FAR *state;
  77925. unsigned char FAR *next; /* next input */
  77926. unsigned char FAR *put; /* next output */
  77927. unsigned have, left; /* available input and output */
  77928. unsigned long hold; /* bit buffer */
  77929. unsigned bits; /* bits in bit buffer */
  77930. unsigned in, out; /* save starting available input and output */
  77931. unsigned copy; /* number of stored or match bytes to copy */
  77932. unsigned char FAR *from; /* where to copy match bytes from */
  77933. code thisx; /* current decoding table entry */
  77934. code last; /* parent table entry */
  77935. unsigned len; /* length to copy for repeats, bits to drop */
  77936. int ret; /* return code */
  77937. #ifdef GUNZIP
  77938. unsigned char hbuf[4]; /* buffer for gzip header crc calculation */
  77939. #endif
  77940. static const unsigned short order[19] = /* permutation of code lengths */
  77941. {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
  77942. if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
  77943. (strm->next_in == Z_NULL && strm->avail_in != 0))
  77944. return Z_STREAM_ERROR;
  77945. state = (struct inflate_state FAR *)strm->state;
  77946. if (state->mode == TYPE) state->mode = TYPEDO; /* skip check */
  77947. LOAD();
  77948. in = have;
  77949. out = left;
  77950. ret = Z_OK;
  77951. for (;;)
  77952. switch (state->mode) {
  77953. case HEAD:
  77954. if (state->wrap == 0) {
  77955. state->mode = TYPEDO;
  77956. break;
  77957. }
  77958. NEEDBITS(16);
  77959. #ifdef GUNZIP
  77960. if ((state->wrap & 2) && hold == 0x8b1f) { /* gzip header */
  77961. state->check = crc32(0L, Z_NULL, 0);
  77962. CRC2(state->check, hold);
  77963. INITBITS();
  77964. state->mode = FLAGS;
  77965. break;
  77966. }
  77967. state->flags = 0; /* expect zlib header */
  77968. if (state->head != Z_NULL)
  77969. state->head->done = -1;
  77970. if (!(state->wrap & 1) || /* check if zlib header allowed */
  77971. #else
  77972. if (
  77973. #endif
  77974. ((BITS(8) << 8) + (hold >> 8)) % 31) {
  77975. strm->msg = (char *)"incorrect header check";
  77976. state->mode = BAD;
  77977. break;
  77978. }
  77979. if (BITS(4) != Z_DEFLATED) {
  77980. strm->msg = (char *)"unknown compression method";
  77981. state->mode = BAD;
  77982. break;
  77983. }
  77984. DROPBITS(4);
  77985. len = BITS(4) + 8;
  77986. if (len > state->wbits) {
  77987. strm->msg = (char *)"invalid window size";
  77988. state->mode = BAD;
  77989. break;
  77990. }
  77991. state->dmax = 1U << len;
  77992. Tracev((stderr, "inflate: zlib header ok\n"));
  77993. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  77994. state->mode = hold & 0x200 ? DICTID : TYPE;
  77995. INITBITS();
  77996. break;
  77997. #ifdef GUNZIP
  77998. case FLAGS:
  77999. NEEDBITS(16);
  78000. state->flags = (int)(hold);
  78001. if ((state->flags & 0xff) != Z_DEFLATED) {
  78002. strm->msg = (char *)"unknown compression method";
  78003. state->mode = BAD;
  78004. break;
  78005. }
  78006. if (state->flags & 0xe000) {
  78007. strm->msg = (char *)"unknown header flags set";
  78008. state->mode = BAD;
  78009. break;
  78010. }
  78011. if (state->head != Z_NULL)
  78012. state->head->text = (int)((hold >> 8) & 1);
  78013. if (state->flags & 0x0200) CRC2(state->check, hold);
  78014. INITBITS();
  78015. state->mode = TIME;
  78016. case TIME:
  78017. NEEDBITS(32);
  78018. if (state->head != Z_NULL)
  78019. state->head->time = hold;
  78020. if (state->flags & 0x0200) CRC4(state->check, hold);
  78021. INITBITS();
  78022. state->mode = OS;
  78023. case OS:
  78024. NEEDBITS(16);
  78025. if (state->head != Z_NULL) {
  78026. state->head->xflags = (int)(hold & 0xff);
  78027. state->head->os = (int)(hold >> 8);
  78028. }
  78029. if (state->flags & 0x0200) CRC2(state->check, hold);
  78030. INITBITS();
  78031. state->mode = EXLEN;
  78032. case EXLEN:
  78033. if (state->flags & 0x0400) {
  78034. NEEDBITS(16);
  78035. state->length = (unsigned)(hold);
  78036. if (state->head != Z_NULL)
  78037. state->head->extra_len = (unsigned)hold;
  78038. if (state->flags & 0x0200) CRC2(state->check, hold);
  78039. INITBITS();
  78040. }
  78041. else if (state->head != Z_NULL)
  78042. state->head->extra = Z_NULL;
  78043. state->mode = EXTRA;
  78044. case EXTRA:
  78045. if (state->flags & 0x0400) {
  78046. copy = state->length;
  78047. if (copy > have) copy = have;
  78048. if (copy) {
  78049. if (state->head != Z_NULL &&
  78050. state->head->extra != Z_NULL) {
  78051. len = state->head->extra_len - state->length;
  78052. zmemcpy(state->head->extra + len, next,
  78053. len + copy > state->head->extra_max ?
  78054. state->head->extra_max - len : copy);
  78055. }
  78056. if (state->flags & 0x0200)
  78057. state->check = crc32(state->check, next, copy);
  78058. have -= copy;
  78059. next += copy;
  78060. state->length -= copy;
  78061. }
  78062. if (state->length) goto inf_leave;
  78063. }
  78064. state->length = 0;
  78065. state->mode = NAME;
  78066. case NAME:
  78067. if (state->flags & 0x0800) {
  78068. if (have == 0) goto inf_leave;
  78069. copy = 0;
  78070. do {
  78071. len = (unsigned)(next[copy++]);
  78072. if (state->head != Z_NULL &&
  78073. state->head->name != Z_NULL &&
  78074. state->length < state->head->name_max)
  78075. state->head->name[state->length++] = len;
  78076. } while (len && copy < have);
  78077. if (state->flags & 0x0200)
  78078. state->check = crc32(state->check, next, copy);
  78079. have -= copy;
  78080. next += copy;
  78081. if (len) goto inf_leave;
  78082. }
  78083. else if (state->head != Z_NULL)
  78084. state->head->name = Z_NULL;
  78085. state->length = 0;
  78086. state->mode = COMMENT;
  78087. case COMMENT:
  78088. if (state->flags & 0x1000) {
  78089. if (have == 0) goto inf_leave;
  78090. copy = 0;
  78091. do {
  78092. len = (unsigned)(next[copy++]);
  78093. if (state->head != Z_NULL &&
  78094. state->head->comment != Z_NULL &&
  78095. state->length < state->head->comm_max)
  78096. state->head->comment[state->length++] = len;
  78097. } while (len && copy < have);
  78098. if (state->flags & 0x0200)
  78099. state->check = crc32(state->check, next, copy);
  78100. have -= copy;
  78101. next += copy;
  78102. if (len) goto inf_leave;
  78103. }
  78104. else if (state->head != Z_NULL)
  78105. state->head->comment = Z_NULL;
  78106. state->mode = HCRC;
  78107. case HCRC:
  78108. if (state->flags & 0x0200) {
  78109. NEEDBITS(16);
  78110. if (hold != (state->check & 0xffff)) {
  78111. strm->msg = (char *)"header crc mismatch";
  78112. state->mode = BAD;
  78113. break;
  78114. }
  78115. INITBITS();
  78116. }
  78117. if (state->head != Z_NULL) {
  78118. state->head->hcrc = (int)((state->flags >> 9) & 1);
  78119. state->head->done = 1;
  78120. }
  78121. strm->adler = state->check = crc32(0L, Z_NULL, 0);
  78122. state->mode = TYPE;
  78123. break;
  78124. #endif
  78125. case DICTID:
  78126. NEEDBITS(32);
  78127. strm->adler = state->check = REVERSE(hold);
  78128. INITBITS();
  78129. state->mode = DICT;
  78130. case DICT:
  78131. if (state->havedict == 0) {
  78132. RESTORE();
  78133. return Z_NEED_DICT;
  78134. }
  78135. strm->adler = state->check = adler32(0L, Z_NULL, 0);
  78136. state->mode = TYPE;
  78137. case TYPE:
  78138. if (flush == Z_BLOCK) goto inf_leave;
  78139. case TYPEDO:
  78140. if (state->last) {
  78141. BYTEBITS();
  78142. state->mode = CHECK;
  78143. break;
  78144. }
  78145. NEEDBITS(3);
  78146. state->last = BITS(1);
  78147. DROPBITS(1);
  78148. switch (BITS(2)) {
  78149. case 0: /* stored block */
  78150. Tracev((stderr, "inflate: stored block%s\n",
  78151. state->last ? " (last)" : ""));
  78152. state->mode = STORED;
  78153. break;
  78154. case 1: /* fixed block */
  78155. fixedtables(state);
  78156. Tracev((stderr, "inflate: fixed codes block%s\n",
  78157. state->last ? " (last)" : ""));
  78158. state->mode = LEN; /* decode codes */
  78159. break;
  78160. case 2: /* dynamic block */
  78161. Tracev((stderr, "inflate: dynamic codes block%s\n",
  78162. state->last ? " (last)" : ""));
  78163. state->mode = TABLE;
  78164. break;
  78165. case 3:
  78166. strm->msg = (char *)"invalid block type";
  78167. state->mode = BAD;
  78168. }
  78169. DROPBITS(2);
  78170. break;
  78171. case STORED:
  78172. BYTEBITS(); /* go to byte boundary */
  78173. NEEDBITS(32);
  78174. if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
  78175. strm->msg = (char *)"invalid stored block lengths";
  78176. state->mode = BAD;
  78177. break;
  78178. }
  78179. state->length = (unsigned)hold & 0xffff;
  78180. Tracev((stderr, "inflate: stored length %u\n",
  78181. state->length));
  78182. INITBITS();
  78183. state->mode = COPY;
  78184. case COPY:
  78185. copy = state->length;
  78186. if (copy) {
  78187. if (copy > have) copy = have;
  78188. if (copy > left) copy = left;
  78189. if (copy == 0) goto inf_leave;
  78190. zmemcpy(put, next, copy);
  78191. have -= copy;
  78192. next += copy;
  78193. left -= copy;
  78194. put += copy;
  78195. state->length -= copy;
  78196. break;
  78197. }
  78198. Tracev((stderr, "inflate: stored end\n"));
  78199. state->mode = TYPE;
  78200. break;
  78201. case TABLE:
  78202. NEEDBITS(14);
  78203. state->nlen = BITS(5) + 257;
  78204. DROPBITS(5);
  78205. state->ndist = BITS(5) + 1;
  78206. DROPBITS(5);
  78207. state->ncode = BITS(4) + 4;
  78208. DROPBITS(4);
  78209. #ifndef PKZIP_BUG_WORKAROUND
  78210. if (state->nlen > 286 || state->ndist > 30) {
  78211. strm->msg = (char *)"too many length or distance symbols";
  78212. state->mode = BAD;
  78213. break;
  78214. }
  78215. #endif
  78216. Tracev((stderr, "inflate: table sizes ok\n"));
  78217. state->have = 0;
  78218. state->mode = LENLENS;
  78219. case LENLENS:
  78220. while (state->have < state->ncode) {
  78221. NEEDBITS(3);
  78222. state->lens[order[state->have++]] = (unsigned short)BITS(3);
  78223. DROPBITS(3);
  78224. }
  78225. while (state->have < 19)
  78226. state->lens[order[state->have++]] = 0;
  78227. state->next = state->codes;
  78228. state->lencode = (code const FAR *)(state->next);
  78229. state->lenbits = 7;
  78230. ret = inflate_table(CODES, state->lens, 19, &(state->next),
  78231. &(state->lenbits), state->work);
  78232. if (ret) {
  78233. strm->msg = (char *)"invalid code lengths set";
  78234. state->mode = BAD;
  78235. break;
  78236. }
  78237. Tracev((stderr, "inflate: code lengths ok\n"));
  78238. state->have = 0;
  78239. state->mode = CODELENS;
  78240. case CODELENS:
  78241. while (state->have < state->nlen + state->ndist) {
  78242. for (;;) {
  78243. thisx = state->lencode[BITS(state->lenbits)];
  78244. if ((unsigned)(thisx.bits) <= bits) break;
  78245. PULLBYTE();
  78246. }
  78247. if (thisx.val < 16) {
  78248. NEEDBITS(thisx.bits);
  78249. DROPBITS(thisx.bits);
  78250. state->lens[state->have++] = thisx.val;
  78251. }
  78252. else {
  78253. if (thisx.val == 16) {
  78254. NEEDBITS(thisx.bits + 2);
  78255. DROPBITS(thisx.bits);
  78256. if (state->have == 0) {
  78257. strm->msg = (char *)"invalid bit length repeat";
  78258. state->mode = BAD;
  78259. break;
  78260. }
  78261. len = state->lens[state->have - 1];
  78262. copy = 3 + BITS(2);
  78263. DROPBITS(2);
  78264. }
  78265. else if (thisx.val == 17) {
  78266. NEEDBITS(thisx.bits + 3);
  78267. DROPBITS(thisx.bits);
  78268. len = 0;
  78269. copy = 3 + BITS(3);
  78270. DROPBITS(3);
  78271. }
  78272. else {
  78273. NEEDBITS(thisx.bits + 7);
  78274. DROPBITS(thisx.bits);
  78275. len = 0;
  78276. copy = 11 + BITS(7);
  78277. DROPBITS(7);
  78278. }
  78279. if (state->have + copy > state->nlen + state->ndist) {
  78280. strm->msg = (char *)"invalid bit length repeat";
  78281. state->mode = BAD;
  78282. break;
  78283. }
  78284. while (copy--)
  78285. state->lens[state->have++] = (unsigned short)len;
  78286. }
  78287. }
  78288. /* handle error breaks in while */
  78289. if (state->mode == BAD) break;
  78290. /* build code tables */
  78291. state->next = state->codes;
  78292. state->lencode = (code const FAR *)(state->next);
  78293. state->lenbits = 9;
  78294. ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
  78295. &(state->lenbits), state->work);
  78296. if (ret) {
  78297. strm->msg = (char *)"invalid literal/lengths set";
  78298. state->mode = BAD;
  78299. break;
  78300. }
  78301. state->distcode = (code const FAR *)(state->next);
  78302. state->distbits = 6;
  78303. ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
  78304. &(state->next), &(state->distbits), state->work);
  78305. if (ret) {
  78306. strm->msg = (char *)"invalid distances set";
  78307. state->mode = BAD;
  78308. break;
  78309. }
  78310. Tracev((stderr, "inflate: codes ok\n"));
  78311. state->mode = LEN;
  78312. case LEN:
  78313. if (have >= 6 && left >= 258) {
  78314. RESTORE();
  78315. inflate_fast(strm, out);
  78316. LOAD();
  78317. break;
  78318. }
  78319. for (;;) {
  78320. thisx = state->lencode[BITS(state->lenbits)];
  78321. if ((unsigned)(thisx.bits) <= bits) break;
  78322. PULLBYTE();
  78323. }
  78324. if (thisx.op && (thisx.op & 0xf0) == 0) {
  78325. last = thisx;
  78326. for (;;) {
  78327. thisx = state->lencode[last.val +
  78328. (BITS(last.bits + last.op) >> last.bits)];
  78329. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  78330. PULLBYTE();
  78331. }
  78332. DROPBITS(last.bits);
  78333. }
  78334. DROPBITS(thisx.bits);
  78335. state->length = (unsigned)thisx.val;
  78336. if ((int)(thisx.op) == 0) {
  78337. Tracevv((stderr, thisx.val >= 0x20 && thisx.val < 0x7f ?
  78338. "inflate: literal '%c'\n" :
  78339. "inflate: literal 0x%02x\n", thisx.val));
  78340. state->mode = LIT;
  78341. break;
  78342. }
  78343. if (thisx.op & 32) {
  78344. Tracevv((stderr, "inflate: end of block\n"));
  78345. state->mode = TYPE;
  78346. break;
  78347. }
  78348. if (thisx.op & 64) {
  78349. strm->msg = (char *)"invalid literal/length code";
  78350. state->mode = BAD;
  78351. break;
  78352. }
  78353. state->extra = (unsigned)(thisx.op) & 15;
  78354. state->mode = LENEXT;
  78355. case LENEXT:
  78356. if (state->extra) {
  78357. NEEDBITS(state->extra);
  78358. state->length += BITS(state->extra);
  78359. DROPBITS(state->extra);
  78360. }
  78361. Tracevv((stderr, "inflate: length %u\n", state->length));
  78362. state->mode = DIST;
  78363. case DIST:
  78364. for (;;) {
  78365. thisx = state->distcode[BITS(state->distbits)];
  78366. if ((unsigned)(thisx.bits) <= bits) break;
  78367. PULLBYTE();
  78368. }
  78369. if ((thisx.op & 0xf0) == 0) {
  78370. last = thisx;
  78371. for (;;) {
  78372. thisx = state->distcode[last.val +
  78373. (BITS(last.bits + last.op) >> last.bits)];
  78374. if ((unsigned)(last.bits + thisx.bits) <= bits) break;
  78375. PULLBYTE();
  78376. }
  78377. DROPBITS(last.bits);
  78378. }
  78379. DROPBITS(thisx.bits);
  78380. if (thisx.op & 64) {
  78381. strm->msg = (char *)"invalid distance code";
  78382. state->mode = BAD;
  78383. break;
  78384. }
  78385. state->offset = (unsigned)thisx.val;
  78386. state->extra = (unsigned)(thisx.op) & 15;
  78387. state->mode = DISTEXT;
  78388. case DISTEXT:
  78389. if (state->extra) {
  78390. NEEDBITS(state->extra);
  78391. state->offset += BITS(state->extra);
  78392. DROPBITS(state->extra);
  78393. }
  78394. #ifdef INFLATE_STRICT
  78395. if (state->offset > state->dmax) {
  78396. strm->msg = (char *)"invalid distance too far back";
  78397. state->mode = BAD;
  78398. break;
  78399. }
  78400. #endif
  78401. if (state->offset > state->whave + out - left) {
  78402. strm->msg = (char *)"invalid distance too far back";
  78403. state->mode = BAD;
  78404. break;
  78405. }
  78406. Tracevv((stderr, "inflate: distance %u\n", state->offset));
  78407. state->mode = MATCH;
  78408. case MATCH:
  78409. if (left == 0) goto inf_leave;
  78410. copy = out - left;
  78411. if (state->offset > copy) { /* copy from window */
  78412. copy = state->offset - copy;
  78413. if (copy > state->write) {
  78414. copy -= state->write;
  78415. from = state->window + (state->wsize - copy);
  78416. }
  78417. else
  78418. from = state->window + (state->write - copy);
  78419. if (copy > state->length) copy = state->length;
  78420. }
  78421. else { /* copy from output */
  78422. from = put - state->offset;
  78423. copy = state->length;
  78424. }
  78425. if (copy > left) copy = left;
  78426. left -= copy;
  78427. state->length -= copy;
  78428. do {
  78429. *put++ = *from++;
  78430. } while (--copy);
  78431. if (state->length == 0) state->mode = LEN;
  78432. break;
  78433. case LIT:
  78434. if (left == 0) goto inf_leave;
  78435. *put++ = (unsigned char)(state->length);
  78436. left--;
  78437. state->mode = LEN;
  78438. break;
  78439. case CHECK:
  78440. if (state->wrap) {
  78441. NEEDBITS(32);
  78442. out -= left;
  78443. strm->total_out += out;
  78444. state->total += out;
  78445. if (out)
  78446. strm->adler = state->check =
  78447. UPDATE(state->check, put - out, out);
  78448. out = left;
  78449. if ((
  78450. #ifdef GUNZIP
  78451. state->flags ? hold :
  78452. #endif
  78453. REVERSE(hold)) != state->check) {
  78454. strm->msg = (char *)"incorrect data check";
  78455. state->mode = BAD;
  78456. break;
  78457. }
  78458. INITBITS();
  78459. Tracev((stderr, "inflate: check matches trailer\n"));
  78460. }
  78461. #ifdef GUNZIP
  78462. state->mode = LENGTH;
  78463. case LENGTH:
  78464. if (state->wrap && state->flags) {
  78465. NEEDBITS(32);
  78466. if (hold != (state->total & 0xffffffffUL)) {
  78467. strm->msg = (char *)"incorrect length check";
  78468. state->mode = BAD;
  78469. break;
  78470. }
  78471. INITBITS();
  78472. Tracev((stderr, "inflate: length matches trailer\n"));
  78473. }
  78474. #endif
  78475. state->mode = DONE;
  78476. case DONE:
  78477. ret = Z_STREAM_END;
  78478. goto inf_leave;
  78479. case BAD:
  78480. ret = Z_DATA_ERROR;
  78481. goto inf_leave;
  78482. case MEM:
  78483. return Z_MEM_ERROR;
  78484. case SYNC:
  78485. default:
  78486. return Z_STREAM_ERROR;
  78487. }
  78488. /*
  78489. Return from inflate(), updating the total counts and the check value.
  78490. If there was no progress during the inflate() call, return a buffer
  78491. error. Call updatewindow() to create and/or update the window state.
  78492. Note: a memory error from inflate() is non-recoverable.
  78493. */
  78494. inf_leave:
  78495. RESTORE();
  78496. if (state->wsize || (state->mode < CHECK && out != strm->avail_out))
  78497. if (updatewindow(strm, out)) {
  78498. state->mode = MEM;
  78499. return Z_MEM_ERROR;
  78500. }
  78501. in -= strm->avail_in;
  78502. out -= strm->avail_out;
  78503. strm->total_in += in;
  78504. strm->total_out += out;
  78505. state->total += out;
  78506. if (state->wrap && out)
  78507. strm->adler = state->check =
  78508. UPDATE(state->check, strm->next_out - out, out);
  78509. strm->data_type = state->bits + (state->last ? 64 : 0) +
  78510. (state->mode == TYPE ? 128 : 0);
  78511. if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
  78512. ret = Z_BUF_ERROR;
  78513. return ret;
  78514. }
  78515. int ZEXPORT inflateEnd (z_streamp strm)
  78516. {
  78517. struct inflate_state FAR *state;
  78518. if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
  78519. return Z_STREAM_ERROR;
  78520. state = (struct inflate_state FAR *)strm->state;
  78521. if (state->window != Z_NULL) ZFREE(strm, state->window);
  78522. ZFREE(strm, strm->state);
  78523. strm->state = Z_NULL;
  78524. Tracev((stderr, "inflate: end\n"));
  78525. return Z_OK;
  78526. }
  78527. int ZEXPORT inflateSetDictionary (z_streamp strm, const Bytef *dictionary, uInt dictLength)
  78528. {
  78529. struct inflate_state FAR *state;
  78530. unsigned long id_;
  78531. /* check state */
  78532. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78533. state = (struct inflate_state FAR *)strm->state;
  78534. if (state->wrap != 0 && state->mode != DICT)
  78535. return Z_STREAM_ERROR;
  78536. /* check for correct dictionary id */
  78537. if (state->mode == DICT) {
  78538. id_ = adler32(0L, Z_NULL, 0);
  78539. id_ = adler32(id_, dictionary, dictLength);
  78540. if (id_ != state->check)
  78541. return Z_DATA_ERROR;
  78542. }
  78543. /* copy dictionary to window */
  78544. if (updatewindow(strm, strm->avail_out)) {
  78545. state->mode = MEM;
  78546. return Z_MEM_ERROR;
  78547. }
  78548. if (dictLength > state->wsize) {
  78549. zmemcpy(state->window, dictionary + dictLength - state->wsize,
  78550. state->wsize);
  78551. state->whave = state->wsize;
  78552. }
  78553. else {
  78554. zmemcpy(state->window + state->wsize - dictLength, dictionary,
  78555. dictLength);
  78556. state->whave = dictLength;
  78557. }
  78558. state->havedict = 1;
  78559. Tracev((stderr, "inflate: dictionary set\n"));
  78560. return Z_OK;
  78561. }
  78562. int ZEXPORT inflateGetHeader (z_streamp strm, gz_headerp head)
  78563. {
  78564. struct inflate_state FAR *state;
  78565. /* check state */
  78566. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78567. state = (struct inflate_state FAR *)strm->state;
  78568. if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
  78569. /* save header structure */
  78570. state->head = head;
  78571. head->done = 0;
  78572. return Z_OK;
  78573. }
  78574. /*
  78575. Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff. Return when found
  78576. or when out of input. When called, *have is the number of pattern bytes
  78577. found in order so far, in 0..3. On return *have is updated to the new
  78578. state. If on return *have equals four, then the pattern was found and the
  78579. return value is how many bytes were read including the last byte of the
  78580. pattern. If *have is less than four, then the pattern has not been found
  78581. yet and the return value is len. In the latter case, syncsearch() can be
  78582. called again with more data and the *have state. *have is initialized to
  78583. zero for the first call.
  78584. */
  78585. local unsigned syncsearch (unsigned FAR *have, unsigned char FAR *buf, unsigned len)
  78586. {
  78587. unsigned got;
  78588. unsigned next;
  78589. got = *have;
  78590. next = 0;
  78591. while (next < len && got < 4) {
  78592. if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
  78593. got++;
  78594. else if (buf[next])
  78595. got = 0;
  78596. else
  78597. got = 4 - got;
  78598. next++;
  78599. }
  78600. *have = got;
  78601. return next;
  78602. }
  78603. int ZEXPORT inflateSync (z_streamp strm)
  78604. {
  78605. unsigned len; /* number of bytes to look at or looked at */
  78606. unsigned long in, out; /* temporary to save total_in and total_out */
  78607. unsigned char buf[4]; /* to restore bit buffer to byte string */
  78608. struct inflate_state FAR *state;
  78609. /* check parameters */
  78610. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78611. state = (struct inflate_state FAR *)strm->state;
  78612. if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
  78613. /* if first time, start search in bit buffer */
  78614. if (state->mode != SYNC) {
  78615. state->mode = SYNC;
  78616. state->hold <<= state->bits & 7;
  78617. state->bits -= state->bits & 7;
  78618. len = 0;
  78619. while (state->bits >= 8) {
  78620. buf[len++] = (unsigned char)(state->hold);
  78621. state->hold >>= 8;
  78622. state->bits -= 8;
  78623. }
  78624. state->have = 0;
  78625. syncsearch(&(state->have), buf, len);
  78626. }
  78627. /* search available input */
  78628. len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
  78629. strm->avail_in -= len;
  78630. strm->next_in += len;
  78631. strm->total_in += len;
  78632. /* return no joy or set up to restart inflate() on a new block */
  78633. if (state->have != 4) return Z_DATA_ERROR;
  78634. in = strm->total_in; out = strm->total_out;
  78635. inflateReset(strm);
  78636. strm->total_in = in; strm->total_out = out;
  78637. state->mode = TYPE;
  78638. return Z_OK;
  78639. }
  78640. /*
  78641. Returns true if inflate is currently at the end of a block generated by
  78642. Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
  78643. implementation to provide an additional safety check. PPP uses
  78644. Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
  78645. block. When decompressing, PPP checks that at the end of input packet,
  78646. inflate is waiting for these length bytes.
  78647. */
  78648. int ZEXPORT inflateSyncPoint (z_streamp strm)
  78649. {
  78650. struct inflate_state FAR *state;
  78651. if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
  78652. state = (struct inflate_state FAR *)strm->state;
  78653. return state->mode == STORED && state->bits == 0;
  78654. }
  78655. int ZEXPORT inflateCopy(z_streamp dest, z_streamp source)
  78656. {
  78657. struct inflate_state FAR *state;
  78658. struct inflate_state FAR *copy;
  78659. unsigned char FAR *window;
  78660. unsigned wsize;
  78661. /* check input */
  78662. if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
  78663. source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
  78664. return Z_STREAM_ERROR;
  78665. state = (struct inflate_state FAR *)source->state;
  78666. /* allocate space */
  78667. copy = (struct inflate_state FAR *)
  78668. ZALLOC(source, 1, sizeof(struct inflate_state));
  78669. if (copy == Z_NULL) return Z_MEM_ERROR;
  78670. window = Z_NULL;
  78671. if (state->window != Z_NULL) {
  78672. window = (unsigned char FAR *)
  78673. ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
  78674. if (window == Z_NULL) {
  78675. ZFREE(source, copy);
  78676. return Z_MEM_ERROR;
  78677. }
  78678. }
  78679. /* copy state */
  78680. zmemcpy(dest, source, sizeof(z_stream));
  78681. zmemcpy(copy, state, sizeof(struct inflate_state));
  78682. if (state->lencode >= state->codes &&
  78683. state->lencode <= state->codes + ENOUGH - 1) {
  78684. copy->lencode = copy->codes + (state->lencode - state->codes);
  78685. copy->distcode = copy->codes + (state->distcode - state->codes);
  78686. }
  78687. copy->next = copy->codes + (state->next - state->codes);
  78688. if (window != Z_NULL) {
  78689. wsize = 1U << state->wbits;
  78690. zmemcpy(window, state->window, wsize);
  78691. }
  78692. copy->window = window;
  78693. dest->state = (struct internal_state FAR *)copy;
  78694. return Z_OK;
  78695. }
  78696. /********* End of inlined file: inflate.c *********/
  78697. /********* Start of inlined file: inftrees.c *********/
  78698. #define MAXBITS 15
  78699. const char inflate_copyright[] =
  78700. " inflate 1.2.3 Copyright 1995-2005 Mark Adler ";
  78701. /*
  78702. If you use the zlib library in a product, an acknowledgment is welcome
  78703. in the documentation of your product. If for some reason you cannot
  78704. include such an acknowledgment, I would appreciate that you keep this
  78705. copyright string in the executable of your product.
  78706. */
  78707. /*
  78708. Build a set of tables to decode the provided canonical Huffman code.
  78709. The code lengths are lens[0..codes-1]. The result starts at *table,
  78710. whose indices are 0..2^bits-1. work is a writable array of at least
  78711. lens shorts, which is used as a work area. type is the type of code
  78712. to be generated, CODES, LENS, or DISTS. On return, zero is success,
  78713. -1 is an invalid code, and +1 means that ENOUGH isn't enough. table
  78714. on return points to the next available entry's address. bits is the
  78715. requested root table index bits, and on return it is the actual root
  78716. table index bits. It will differ if the request is greater than the
  78717. longest code or if it is less than the shortest code.
  78718. */
  78719. int inflate_table (codetype type,
  78720. unsigned short FAR *lens,
  78721. unsigned codes,
  78722. code FAR * FAR *table,
  78723. unsigned FAR *bits,
  78724. unsigned short FAR *work)
  78725. {
  78726. unsigned len; /* a code's length in bits */
  78727. unsigned sym; /* index of code symbols */
  78728. unsigned min, max; /* minimum and maximum code lengths */
  78729. unsigned root; /* number of index bits for root table */
  78730. unsigned curr; /* number of index bits for current table */
  78731. unsigned drop; /* code bits to drop for sub-table */
  78732. int left; /* number of prefix codes available */
  78733. unsigned used; /* code entries in table used */
  78734. unsigned huff; /* Huffman code */
  78735. unsigned incr; /* for incrementing code, index */
  78736. unsigned fill; /* index for replicating entries */
  78737. unsigned low; /* low bits for current root entry */
  78738. unsigned mask; /* mask for low root bits */
  78739. code thisx; /* table entry for duplication */
  78740. code FAR *next; /* next available space in table */
  78741. const unsigned short FAR *base; /* base value table to use */
  78742. const unsigned short FAR *extra; /* extra bits table to use */
  78743. int end; /* use base and extra for symbol > end */
  78744. unsigned short count[MAXBITS+1]; /* number of codes of each length */
  78745. unsigned short offs[MAXBITS+1]; /* offsets in table for each length */
  78746. static const unsigned short lbase[31] = { /* Length codes 257..285 base */
  78747. 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
  78748. 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
  78749. static const unsigned short lext[31] = { /* Length codes 257..285 extra */
  78750. 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
  78751. 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 201, 196};
  78752. static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
  78753. 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
  78754. 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
  78755. 8193, 12289, 16385, 24577, 0, 0};
  78756. static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
  78757. 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
  78758. 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
  78759. 28, 28, 29, 29, 64, 64};
  78760. /*
  78761. Process a set of code lengths to create a canonical Huffman code. The
  78762. code lengths are lens[0..codes-1]. Each length corresponds to the
  78763. symbols 0..codes-1. The Huffman code is generated by first sorting the
  78764. symbols by length from short to long, and retaining the symbol order
  78765. for codes with equal lengths. Then the code starts with all zero bits
  78766. for the first code of the shortest length, and the codes are integer
  78767. increments for the same length, and zeros are appended as the length
  78768. increases. For the deflate format, these bits are stored backwards
  78769. from their more natural integer increment ordering, and so when the
  78770. decoding tables are built in the large loop below, the integer codes
  78771. are incremented backwards.
  78772. This routine assumes, but does not check, that all of the entries in
  78773. lens[] are in the range 0..MAXBITS. The caller must assure this.
  78774. 1..MAXBITS is interpreted as that code length. zero means that that
  78775. symbol does not occur in this code.
  78776. The codes are sorted by computing a count of codes for each length,
  78777. creating from that a table of starting indices for each length in the
  78778. sorted table, and then entering the symbols in order in the sorted
  78779. table. The sorted table is work[], with that space being provided by
  78780. the caller.
  78781. The length counts are used for other purposes as well, i.e. finding
  78782. the minimum and maximum length codes, determining if there are any
  78783. codes at all, checking for a valid set of lengths, and looking ahead
  78784. at length counts to determine sub-table sizes when building the
  78785. decoding tables.
  78786. */
  78787. /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
  78788. for (len = 0; len <= MAXBITS; len++)
  78789. count[len] = 0;
  78790. for (sym = 0; sym < codes; sym++)
  78791. count[lens[sym]]++;
  78792. /* bound code lengths, force root to be within code lengths */
  78793. root = *bits;
  78794. for (max = MAXBITS; max >= 1; max--)
  78795. if (count[max] != 0) break;
  78796. if (root > max) root = max;
  78797. if (max == 0) { /* no symbols to code at all */
  78798. thisx.op = (unsigned char)64; /* invalid code marker */
  78799. thisx.bits = (unsigned char)1;
  78800. thisx.val = (unsigned short)0;
  78801. *(*table)++ = thisx; /* make a table to force an error */
  78802. *(*table)++ = thisx;
  78803. *bits = 1;
  78804. return 0; /* no symbols, but wait for decoding to report error */
  78805. }
  78806. for (min = 1; min <= MAXBITS; min++)
  78807. if (count[min] != 0) break;
  78808. if (root < min) root = min;
  78809. /* check for an over-subscribed or incomplete set of lengths */
  78810. left = 1;
  78811. for (len = 1; len <= MAXBITS; len++) {
  78812. left <<= 1;
  78813. left -= count[len];
  78814. if (left < 0) return -1; /* over-subscribed */
  78815. }
  78816. if (left > 0 && (type == CODES || max != 1))
  78817. return -1; /* incomplete set */
  78818. /* generate offsets into symbol table for each length for sorting */
  78819. offs[1] = 0;
  78820. for (len = 1; len < MAXBITS; len++)
  78821. offs[len + 1] = offs[len] + count[len];
  78822. /* sort symbols by length, by symbol order within each length */
  78823. for (sym = 0; sym < codes; sym++)
  78824. if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
  78825. /*
  78826. Create and fill in decoding tables. In this loop, the table being
  78827. filled is at next and has curr index bits. The code being used is huff
  78828. with length len. That code is converted to an index by dropping drop
  78829. bits off of the bottom. For codes where len is less than drop + curr,
  78830. those top drop + curr - len bits are incremented through all values to
  78831. fill the table with replicated entries.
  78832. root is the number of index bits for the root table. When len exceeds
  78833. root, sub-tables are created pointed to by the root entry with an index
  78834. of the low root bits of huff. This is saved in low to check for when a
  78835. new sub-table should be started. drop is zero when the root table is
  78836. being filled, and drop is root when sub-tables are being filled.
  78837. When a new sub-table is needed, it is necessary to look ahead in the
  78838. code lengths to determine what size sub-table is needed. The length
  78839. counts are used for this, and so count[] is decremented as codes are
  78840. entered in the tables.
  78841. used keeps track of how many table entries have been allocated from the
  78842. provided *table space. It is checked when a LENS table is being made
  78843. against the space in *table, ENOUGH, minus the maximum space needed by
  78844. the worst case distance code, MAXD. This should never happen, but the
  78845. sufficiency of ENOUGH has not been proven exhaustively, hence the check.
  78846. This assumes that when type == LENS, bits == 9.
  78847. sym increments through all symbols, and the loop terminates when
  78848. all codes of length max, i.e. all codes, have been processed. This
  78849. routine permits incomplete codes, so another loop after this one fills
  78850. in the rest of the decoding tables with invalid code markers.
  78851. */
  78852. /* set up for code type */
  78853. switch (type) {
  78854. case CODES:
  78855. base = extra = work; /* dummy value--not used */
  78856. end = 19;
  78857. break;
  78858. case LENS:
  78859. base = lbase;
  78860. base -= 257;
  78861. extra = lext;
  78862. extra -= 257;
  78863. end = 256;
  78864. break;
  78865. default: /* DISTS */
  78866. base = dbase;
  78867. extra = dext;
  78868. end = -1;
  78869. }
  78870. /* initialize state for loop */
  78871. huff = 0; /* starting code */
  78872. sym = 0; /* starting code symbol */
  78873. len = min; /* starting code length */
  78874. next = *table; /* current table to fill in */
  78875. curr = root; /* current table index bits */
  78876. drop = 0; /* current bits to drop from code for index */
  78877. low = (unsigned)(-1); /* trigger new sub-table when len > root */
  78878. used = 1U << root; /* use root table entries */
  78879. mask = used - 1; /* mask for comparing low */
  78880. /* check available table space */
  78881. if (type == LENS && used >= ENOUGH - MAXD)
  78882. return 1;
  78883. /* process all codes and make table entries */
  78884. for (;;) {
  78885. /* create table entry */
  78886. thisx.bits = (unsigned char)(len - drop);
  78887. if ((int)(work[sym]) < end) {
  78888. thisx.op = (unsigned char)0;
  78889. thisx.val = work[sym];
  78890. }
  78891. else if ((int)(work[sym]) > end) {
  78892. thisx.op = (unsigned char)(extra[work[sym]]);
  78893. thisx.val = base[work[sym]];
  78894. }
  78895. else {
  78896. thisx.op = (unsigned char)(32 + 64); /* end of block */
  78897. thisx.val = 0;
  78898. }
  78899. /* replicate for those indices with low len bits equal to huff */
  78900. incr = 1U << (len - drop);
  78901. fill = 1U << curr;
  78902. min = fill; /* save offset to next table */
  78903. do {
  78904. fill -= incr;
  78905. next[(huff >> drop) + fill] = thisx;
  78906. } while (fill != 0);
  78907. /* backwards increment the len-bit code huff */
  78908. incr = 1U << (len - 1);
  78909. while (huff & incr)
  78910. incr >>= 1;
  78911. if (incr != 0) {
  78912. huff &= incr - 1;
  78913. huff += incr;
  78914. }
  78915. else
  78916. huff = 0;
  78917. /* go to next symbol, update count, len */
  78918. sym++;
  78919. if (--(count[len]) == 0) {
  78920. if (len == max) break;
  78921. len = lens[work[sym]];
  78922. }
  78923. /* create new sub-table if needed */
  78924. if (len > root && (huff & mask) != low) {
  78925. /* if first time, transition to sub-tables */
  78926. if (drop == 0)
  78927. drop = root;
  78928. /* increment past last table */
  78929. next += min; /* here min is 1 << curr */
  78930. /* determine length of next table */
  78931. curr = len - drop;
  78932. left = (int)(1 << curr);
  78933. while (curr + drop < max) {
  78934. left -= count[curr + drop];
  78935. if (left <= 0) break;
  78936. curr++;
  78937. left <<= 1;
  78938. }
  78939. /* check for enough space */
  78940. used += 1U << curr;
  78941. if (type == LENS && used >= ENOUGH - MAXD)
  78942. return 1;
  78943. /* point entry in root table to sub-table */
  78944. low = huff & mask;
  78945. (*table)[low].op = (unsigned char)curr;
  78946. (*table)[low].bits = (unsigned char)root;
  78947. (*table)[low].val = (unsigned short)(next - *table);
  78948. }
  78949. }
  78950. /*
  78951. Fill in rest of table for incomplete codes. This loop is similar to the
  78952. loop above in incrementing huff for table indices. It is assumed that
  78953. len is equal to curr + drop, so there is no loop needed to increment
  78954. through high index bits. When the current sub-table is filled, the loop
  78955. drops back to the root table to fill in any remaining entries there.
  78956. */
  78957. thisx.op = (unsigned char)64; /* invalid code marker */
  78958. thisx.bits = (unsigned char)(len - drop);
  78959. thisx.val = (unsigned short)0;
  78960. while (huff != 0) {
  78961. /* when done with sub-table, drop back to root table */
  78962. if (drop != 0 && (huff & mask) != low) {
  78963. drop = 0;
  78964. len = root;
  78965. next = *table;
  78966. thisx.bits = (unsigned char)len;
  78967. }
  78968. /* put invalid code marker in table */
  78969. next[huff >> drop] = thisx;
  78970. /* backwards increment the len-bit code huff */
  78971. incr = 1U << (len - 1);
  78972. while (huff & incr)
  78973. incr >>= 1;
  78974. if (incr != 0) {
  78975. huff &= incr - 1;
  78976. huff += incr;
  78977. }
  78978. else
  78979. huff = 0;
  78980. }
  78981. /* set return parameters */
  78982. *table += used;
  78983. *bits = root;
  78984. return 0;
  78985. }
  78986. /********* End of inlined file: inftrees.c *********/
  78987. /********* Start of inlined file: trees.c *********/
  78988. /*
  78989. * ALGORITHM
  78990. *
  78991. * The "deflation" process uses several Huffman trees. The more
  78992. * common source values are represented by shorter bit sequences.
  78993. *
  78994. * Each code tree is stored in a compressed form which is itself
  78995. * a Huffman encoding of the lengths of all the code strings (in
  78996. * ascending order by source values). The actual code strings are
  78997. * reconstructed from the lengths in the inflate process, as described
  78998. * in the deflate specification.
  78999. *
  79000. * REFERENCES
  79001. *
  79002. * Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
  79003. * Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
  79004. *
  79005. * Storer, James A.
  79006. * Data Compression: Methods and Theory, pp. 49-50.
  79007. * Computer Science Press, 1988. ISBN 0-7167-8156-5.
  79008. *
  79009. * Sedgewick, R.
  79010. * Algorithms, p290.
  79011. * Addison-Wesley, 1983. ISBN 0-201-06672-6.
  79012. */
  79013. /* @(#) $Id: trees.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  79014. /* #define GEN_TREES_H */
  79015. #ifdef DEBUG
  79016. # include <ctype.h>
  79017. #endif
  79018. /* ===========================================================================
  79019. * Constants
  79020. */
  79021. #define MAX_BL_BITS 7
  79022. /* Bit length codes must not exceed MAX_BL_BITS bits */
  79023. #define END_BLOCK 256
  79024. /* end of block literal code */
  79025. #define REP_3_6 16
  79026. /* repeat previous bit length 3-6 times (2 bits of repeat count) */
  79027. #define REPZ_3_10 17
  79028. /* repeat a zero length 3-10 times (3 bits of repeat count) */
  79029. #define REPZ_11_138 18
  79030. /* repeat a zero length 11-138 times (7 bits of repeat count) */
  79031. local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
  79032. = {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};
  79033. local const int extra_dbits[D_CODES] /* extra bits for each distance code */
  79034. = {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};
  79035. local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
  79036. = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
  79037. local const uch bl_order[BL_CODES]
  79038. = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
  79039. /* The lengths of the bit length codes are sent in order of decreasing
  79040. * probability, to avoid transmitting the lengths for unused bit length codes.
  79041. */
  79042. #define Buf_size (8 * 2*sizeof(char))
  79043. /* Number of bits used within bi_buf. (bi_buf might be implemented on
  79044. * more than 16 bits on some systems.)
  79045. */
  79046. /* ===========================================================================
  79047. * Local data. These are initialized only once.
  79048. */
  79049. #define DIST_CODE_LEN 512 /* see definition of array dist_code below */
  79050. #if defined(GEN_TREES_H) || !defined(STDC)
  79051. /* non ANSI compilers may not accept trees.h */
  79052. local ct_data static_ltree[L_CODES+2];
  79053. /* The static literal tree. Since the bit lengths are imposed, there is no
  79054. * need for the L_CODES extra codes used during heap construction. However
  79055. * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
  79056. * below).
  79057. */
  79058. local ct_data static_dtree[D_CODES];
  79059. /* The static distance tree. (Actually a trivial tree since all codes use
  79060. * 5 bits.)
  79061. */
  79062. uch _dist_code[DIST_CODE_LEN];
  79063. /* Distance codes. The first 256 values correspond to the distances
  79064. * 3 .. 258, the last 256 values correspond to the top 8 bits of
  79065. * the 15 bit distances.
  79066. */
  79067. uch _length_code[MAX_MATCH-MIN_MATCH+1];
  79068. /* length code for each normalized match length (0 == MIN_MATCH) */
  79069. local int base_length[LENGTH_CODES];
  79070. /* First normalized length for each code (0 = MIN_MATCH) */
  79071. local int base_dist[D_CODES];
  79072. /* First normalized distance for each code (0 = distance of 1) */
  79073. #else
  79074. /********* Start of inlined file: trees.h *********/
  79075. local const ct_data static_ltree[L_CODES+2] = {
  79076. {{ 12},{ 8}}, {{140},{ 8}}, {{ 76},{ 8}}, {{204},{ 8}}, {{ 44},{ 8}},
  79077. {{172},{ 8}}, {{108},{ 8}}, {{236},{ 8}}, {{ 28},{ 8}}, {{156},{ 8}},
  79078. {{ 92},{ 8}}, {{220},{ 8}}, {{ 60},{ 8}}, {{188},{ 8}}, {{124},{ 8}},
  79079. {{252},{ 8}}, {{ 2},{ 8}}, {{130},{ 8}}, {{ 66},{ 8}}, {{194},{ 8}},
  79080. {{ 34},{ 8}}, {{162},{ 8}}, {{ 98},{ 8}}, {{226},{ 8}}, {{ 18},{ 8}},
  79081. {{146},{ 8}}, {{ 82},{ 8}}, {{210},{ 8}}, {{ 50},{ 8}}, {{178},{ 8}},
  79082. {{114},{ 8}}, {{242},{ 8}}, {{ 10},{ 8}}, {{138},{ 8}}, {{ 74},{ 8}},
  79083. {{202},{ 8}}, {{ 42},{ 8}}, {{170},{ 8}}, {{106},{ 8}}, {{234},{ 8}},
  79084. {{ 26},{ 8}}, {{154},{ 8}}, {{ 90},{ 8}}, {{218},{ 8}}, {{ 58},{ 8}},
  79085. {{186},{ 8}}, {{122},{ 8}}, {{250},{ 8}}, {{ 6},{ 8}}, {{134},{ 8}},
  79086. {{ 70},{ 8}}, {{198},{ 8}}, {{ 38},{ 8}}, {{166},{ 8}}, {{102},{ 8}},
  79087. {{230},{ 8}}, {{ 22},{ 8}}, {{150},{ 8}}, {{ 86},{ 8}}, {{214},{ 8}},
  79088. {{ 54},{ 8}}, {{182},{ 8}}, {{118},{ 8}}, {{246},{ 8}}, {{ 14},{ 8}},
  79089. {{142},{ 8}}, {{ 78},{ 8}}, {{206},{ 8}}, {{ 46},{ 8}}, {{174},{ 8}},
  79090. {{110},{ 8}}, {{238},{ 8}}, {{ 30},{ 8}}, {{158},{ 8}}, {{ 94},{ 8}},
  79091. {{222},{ 8}}, {{ 62},{ 8}}, {{190},{ 8}}, {{126},{ 8}}, {{254},{ 8}},
  79092. {{ 1},{ 8}}, {{129},{ 8}}, {{ 65},{ 8}}, {{193},{ 8}}, {{ 33},{ 8}},
  79093. {{161},{ 8}}, {{ 97},{ 8}}, {{225},{ 8}}, {{ 17},{ 8}}, {{145},{ 8}},
  79094. {{ 81},{ 8}}, {{209},{ 8}}, {{ 49},{ 8}}, {{177},{ 8}}, {{113},{ 8}},
  79095. {{241},{ 8}}, {{ 9},{ 8}}, {{137},{ 8}}, {{ 73},{ 8}}, {{201},{ 8}},
  79096. {{ 41},{ 8}}, {{169},{ 8}}, {{105},{ 8}}, {{233},{ 8}}, {{ 25},{ 8}},
  79097. {{153},{ 8}}, {{ 89},{ 8}}, {{217},{ 8}}, {{ 57},{ 8}}, {{185},{ 8}},
  79098. {{121},{ 8}}, {{249},{ 8}}, {{ 5},{ 8}}, {{133},{ 8}}, {{ 69},{ 8}},
  79099. {{197},{ 8}}, {{ 37},{ 8}}, {{165},{ 8}}, {{101},{ 8}}, {{229},{ 8}},
  79100. {{ 21},{ 8}}, {{149},{ 8}}, {{ 85},{ 8}}, {{213},{ 8}}, {{ 53},{ 8}},
  79101. {{181},{ 8}}, {{117},{ 8}}, {{245},{ 8}}, {{ 13},{ 8}}, {{141},{ 8}},
  79102. {{ 77},{ 8}}, {{205},{ 8}}, {{ 45},{ 8}}, {{173},{ 8}}, {{109},{ 8}},
  79103. {{237},{ 8}}, {{ 29},{ 8}}, {{157},{ 8}}, {{ 93},{ 8}}, {{221},{ 8}},
  79104. {{ 61},{ 8}}, {{189},{ 8}}, {{125},{ 8}}, {{253},{ 8}}, {{ 19},{ 9}},
  79105. {{275},{ 9}}, {{147},{ 9}}, {{403},{ 9}}, {{ 83},{ 9}}, {{339},{ 9}},
  79106. {{211},{ 9}}, {{467},{ 9}}, {{ 51},{ 9}}, {{307},{ 9}}, {{179},{ 9}},
  79107. {{435},{ 9}}, {{115},{ 9}}, {{371},{ 9}}, {{243},{ 9}}, {{499},{ 9}},
  79108. {{ 11},{ 9}}, {{267},{ 9}}, {{139},{ 9}}, {{395},{ 9}}, {{ 75},{ 9}},
  79109. {{331},{ 9}}, {{203},{ 9}}, {{459},{ 9}}, {{ 43},{ 9}}, {{299},{ 9}},
  79110. {{171},{ 9}}, {{427},{ 9}}, {{107},{ 9}}, {{363},{ 9}}, {{235},{ 9}},
  79111. {{491},{ 9}}, {{ 27},{ 9}}, {{283},{ 9}}, {{155},{ 9}}, {{411},{ 9}},
  79112. {{ 91},{ 9}}, {{347},{ 9}}, {{219},{ 9}}, {{475},{ 9}}, {{ 59},{ 9}},
  79113. {{315},{ 9}}, {{187},{ 9}}, {{443},{ 9}}, {{123},{ 9}}, {{379},{ 9}},
  79114. {{251},{ 9}}, {{507},{ 9}}, {{ 7},{ 9}}, {{263},{ 9}}, {{135},{ 9}},
  79115. {{391},{ 9}}, {{ 71},{ 9}}, {{327},{ 9}}, {{199},{ 9}}, {{455},{ 9}},
  79116. {{ 39},{ 9}}, {{295},{ 9}}, {{167},{ 9}}, {{423},{ 9}}, {{103},{ 9}},
  79117. {{359},{ 9}}, {{231},{ 9}}, {{487},{ 9}}, {{ 23},{ 9}}, {{279},{ 9}},
  79118. {{151},{ 9}}, {{407},{ 9}}, {{ 87},{ 9}}, {{343},{ 9}}, {{215},{ 9}},
  79119. {{471},{ 9}}, {{ 55},{ 9}}, {{311},{ 9}}, {{183},{ 9}}, {{439},{ 9}},
  79120. {{119},{ 9}}, {{375},{ 9}}, {{247},{ 9}}, {{503},{ 9}}, {{ 15},{ 9}},
  79121. {{271},{ 9}}, {{143},{ 9}}, {{399},{ 9}}, {{ 79},{ 9}}, {{335},{ 9}},
  79122. {{207},{ 9}}, {{463},{ 9}}, {{ 47},{ 9}}, {{303},{ 9}}, {{175},{ 9}},
  79123. {{431},{ 9}}, {{111},{ 9}}, {{367},{ 9}}, {{239},{ 9}}, {{495},{ 9}},
  79124. {{ 31},{ 9}}, {{287},{ 9}}, {{159},{ 9}}, {{415},{ 9}}, {{ 95},{ 9}},
  79125. {{351},{ 9}}, {{223},{ 9}}, {{479},{ 9}}, {{ 63},{ 9}}, {{319},{ 9}},
  79126. {{191},{ 9}}, {{447},{ 9}}, {{127},{ 9}}, {{383},{ 9}}, {{255},{ 9}},
  79127. {{511},{ 9}}, {{ 0},{ 7}}, {{ 64},{ 7}}, {{ 32},{ 7}}, {{ 96},{ 7}},
  79128. {{ 16},{ 7}}, {{ 80},{ 7}}, {{ 48},{ 7}}, {{112},{ 7}}, {{ 8},{ 7}},
  79129. {{ 72},{ 7}}, {{ 40},{ 7}}, {{104},{ 7}}, {{ 24},{ 7}}, {{ 88},{ 7}},
  79130. {{ 56},{ 7}}, {{120},{ 7}}, {{ 4},{ 7}}, {{ 68},{ 7}}, {{ 36},{ 7}},
  79131. {{100},{ 7}}, {{ 20},{ 7}}, {{ 84},{ 7}}, {{ 52},{ 7}}, {{116},{ 7}},
  79132. {{ 3},{ 8}}, {{131},{ 8}}, {{ 67},{ 8}}, {{195},{ 8}}, {{ 35},{ 8}},
  79133. {{163},{ 8}}, {{ 99},{ 8}}, {{227},{ 8}}
  79134. };
  79135. local const ct_data static_dtree[D_CODES] = {
  79136. {{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
  79137. {{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
  79138. {{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
  79139. {{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
  79140. {{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
  79141. {{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
  79142. };
  79143. const uch _dist_code[DIST_CODE_LEN] = {
  79144. 0, 1, 2, 3, 4, 4, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8,
  79145. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 10, 10, 10, 10, 10, 10, 10, 10,
  79146. 10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
  79147. 11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
  79148. 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
  79149. 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
  79150. 13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  79151. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  79152. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
  79153. 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
  79154. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  79155. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
  79156. 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 0, 0, 16, 17,
  79157. 18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
  79158. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  79159. 24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  79160. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  79161. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
  79162. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  79163. 27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  79164. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  79165. 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
  79166. 28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  79167. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  79168. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
  79169. 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
  79170. };
  79171. const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {
  79172. 0, 1, 2, 3, 4, 5, 6, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 12, 12,
  79173. 13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
  79174. 17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
  79175. 19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
  79176. 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
  79177. 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
  79178. 23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  79179. 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
  79180. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
  79181. 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
  79182. 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
  79183. 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
  79184. 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
  79185. };
  79186. local const int base_length[LENGTH_CODES] = {
  79187. 0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
  79188. 64, 80, 96, 112, 128, 160, 192, 224, 0
  79189. };
  79190. local const int base_dist[D_CODES] = {
  79191. 0, 1, 2, 3, 4, 6, 8, 12, 16, 24,
  79192. 32, 48, 64, 96, 128, 192, 256, 384, 512, 768,
  79193. 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
  79194. };
  79195. /********* End of inlined file: trees.h *********/
  79196. #endif /* GEN_TREES_H */
  79197. struct static_tree_desc_s {
  79198. const ct_data *static_tree; /* static tree or NULL */
  79199. const intf *extra_bits; /* extra bits for each code or NULL */
  79200. int extra_base; /* base index for extra_bits */
  79201. int elems; /* max number of elements in the tree */
  79202. int max_length; /* max bit length for the codes */
  79203. };
  79204. local static_tree_desc static_l_desc =
  79205. {static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
  79206. local static_tree_desc static_d_desc =
  79207. {static_dtree, extra_dbits, 0, D_CODES, MAX_BITS};
  79208. local static_tree_desc static_bl_desc =
  79209. {(const ct_data *)0, extra_blbits, 0, BL_CODES, MAX_BL_BITS};
  79210. /* ===========================================================================
  79211. * Local (static) routines in this file.
  79212. */
  79213. local void tr_static_init OF((void));
  79214. local void init_block OF((deflate_state *s));
  79215. local void pqdownheap OF((deflate_state *s, ct_data *tree, int k));
  79216. local void gen_bitlen OF((deflate_state *s, tree_desc *desc));
  79217. local void gen_codes OF((ct_data *tree, int max_code, ushf *bl_count));
  79218. local void build_tree OF((deflate_state *s, tree_desc *desc));
  79219. local void scan_tree OF((deflate_state *s, ct_data *tree, int max_code));
  79220. local void send_tree OF((deflate_state *s, ct_data *tree, int max_code));
  79221. local int build_bl_tree OF((deflate_state *s));
  79222. local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
  79223. int blcodes));
  79224. local void compress_block OF((deflate_state *s, ct_data *ltree,
  79225. ct_data *dtree));
  79226. local void set_data_type OF((deflate_state *s));
  79227. local unsigned bi_reverse OF((unsigned value, int length));
  79228. local void bi_windup OF((deflate_state *s));
  79229. local void bi_flush OF((deflate_state *s));
  79230. local void copy_block OF((deflate_state *s, charf *buf, unsigned len,
  79231. int header));
  79232. #ifdef GEN_TREES_H
  79233. local void gen_trees_header OF((void));
  79234. #endif
  79235. #ifndef DEBUG
  79236. # define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
  79237. /* Send a code of the given tree. c and tree must not have side effects */
  79238. #else /* DEBUG */
  79239. # define send_code(s, c, tree) \
  79240. { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
  79241. send_bits(s, tree[c].Code, tree[c].Len); }
  79242. #endif
  79243. /* ===========================================================================
  79244. * Output a short LSB first on the stream.
  79245. * IN assertion: there is enough room in pendingBuf.
  79246. */
  79247. #define put_short(s, w) { \
  79248. put_byte(s, (uch)((w) & 0xff)); \
  79249. put_byte(s, (uch)((ush)(w) >> 8)); \
  79250. }
  79251. /* ===========================================================================
  79252. * Send a value on a given number of bits.
  79253. * IN assertion: length <= 16 and value fits in length bits.
  79254. */
  79255. #ifdef DEBUG
  79256. local void send_bits OF((deflate_state *s, int value, int length));
  79257. local void send_bits (deflate_state *s, int value, int length)
  79258. {
  79259. Tracevv((stderr," l %2d v %4x ", length, value));
  79260. Assert(length > 0 && length <= 15, "invalid length");
  79261. s->bits_sent += (ulg)length;
  79262. /* If not enough room in bi_buf, use (valid) bits from bi_buf and
  79263. * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
  79264. * unused bits in value.
  79265. */
  79266. if (s->bi_valid > (int)Buf_size - length) {
  79267. s->bi_buf |= (value << s->bi_valid);
  79268. put_short(s, s->bi_buf);
  79269. s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
  79270. s->bi_valid += length - Buf_size;
  79271. } else {
  79272. s->bi_buf |= value << s->bi_valid;
  79273. s->bi_valid += length;
  79274. }
  79275. }
  79276. #else /* !DEBUG */
  79277. #define send_bits(s, value, length) \
  79278. { int len = length;\
  79279. if (s->bi_valid > (int)Buf_size - len) {\
  79280. int val = value;\
  79281. s->bi_buf |= (val << s->bi_valid);\
  79282. put_short(s, s->bi_buf);\
  79283. s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
  79284. s->bi_valid += len - Buf_size;\
  79285. } else {\
  79286. s->bi_buf |= (value) << s->bi_valid;\
  79287. s->bi_valid += len;\
  79288. }\
  79289. }
  79290. #endif /* DEBUG */
  79291. /* the arguments must not have side effects */
  79292. /* ===========================================================================
  79293. * Initialize the various 'constant' tables.
  79294. */
  79295. local void tr_static_init()
  79296. {
  79297. #if defined(GEN_TREES_H) || !defined(STDC)
  79298. static int static_init_done = 0;
  79299. int n; /* iterates over tree elements */
  79300. int bits; /* bit counter */
  79301. int length; /* length value */
  79302. int code; /* code value */
  79303. int dist; /* distance index */
  79304. ush bl_count[MAX_BITS+1];
  79305. /* number of codes at each bit length for an optimal tree */
  79306. if (static_init_done) return;
  79307. /* For some embedded targets, global variables are not initialized: */
  79308. static_l_desc.static_tree = static_ltree;
  79309. static_l_desc.extra_bits = extra_lbits;
  79310. static_d_desc.static_tree = static_dtree;
  79311. static_d_desc.extra_bits = extra_dbits;
  79312. static_bl_desc.extra_bits = extra_blbits;
  79313. /* Initialize the mapping length (0..255) -> length code (0..28) */
  79314. length = 0;
  79315. for (code = 0; code < LENGTH_CODES-1; code++) {
  79316. base_length[code] = length;
  79317. for (n = 0; n < (1<<extra_lbits[code]); n++) {
  79318. _length_code[length++] = (uch)code;
  79319. }
  79320. }
  79321. Assert (length == 256, "tr_static_init: length != 256");
  79322. /* Note that the length 255 (match length 258) can be represented
  79323. * in two different ways: code 284 + 5 bits or code 285, so we
  79324. * overwrite length_code[255] to use the best encoding:
  79325. */
  79326. _length_code[length-1] = (uch)code;
  79327. /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
  79328. dist = 0;
  79329. for (code = 0 ; code < 16; code++) {
  79330. base_dist[code] = dist;
  79331. for (n = 0; n < (1<<extra_dbits[code]); n++) {
  79332. _dist_code[dist++] = (uch)code;
  79333. }
  79334. }
  79335. Assert (dist == 256, "tr_static_init: dist != 256");
  79336. dist >>= 7; /* from now on, all distances are divided by 128 */
  79337. for ( ; code < D_CODES; code++) {
  79338. base_dist[code] = dist << 7;
  79339. for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
  79340. _dist_code[256 + dist++] = (uch)code;
  79341. }
  79342. }
  79343. Assert (dist == 256, "tr_static_init: 256+dist != 512");
  79344. /* Construct the codes of the static literal tree */
  79345. for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
  79346. n = 0;
  79347. while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
  79348. while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
  79349. while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
  79350. while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
  79351. /* Codes 286 and 287 do not exist, but we must include them in the
  79352. * tree construction to get a canonical Huffman tree (longest code
  79353. * all ones)
  79354. */
  79355. gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
  79356. /* The static distance tree is trivial: */
  79357. for (n = 0; n < D_CODES; n++) {
  79358. static_dtree[n].Len = 5;
  79359. static_dtree[n].Code = bi_reverse((unsigned)n, 5);
  79360. }
  79361. static_init_done = 1;
  79362. # ifdef GEN_TREES_H
  79363. gen_trees_header();
  79364. # endif
  79365. #endif /* defined(GEN_TREES_H) || !defined(STDC) */
  79366. }
  79367. /* ===========================================================================
  79368. * Genererate the file trees.h describing the static trees.
  79369. */
  79370. #ifdef GEN_TREES_H
  79371. # ifndef DEBUG
  79372. # include <stdio.h>
  79373. # endif
  79374. # define SEPARATOR(i, last, width) \
  79375. ((i) == (last)? "\n};\n\n" : \
  79376. ((i) % (width) == (width)-1 ? ",\n" : ", "))
  79377. void gen_trees_header()
  79378. {
  79379. FILE *header = fopen("trees.h", "w");
  79380. int i;
  79381. Assert (header != NULL, "Can't open trees.h");
  79382. fprintf(header,
  79383. "/* header created automatically with -DGEN_TREES_H */\n\n");
  79384. fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
  79385. for (i = 0; i < L_CODES+2; i++) {
  79386. fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
  79387. static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
  79388. }
  79389. fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
  79390. for (i = 0; i < D_CODES; i++) {
  79391. fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
  79392. static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
  79393. }
  79394. fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
  79395. for (i = 0; i < DIST_CODE_LEN; i++) {
  79396. fprintf(header, "%2u%s", _dist_code[i],
  79397. SEPARATOR(i, DIST_CODE_LEN-1, 20));
  79398. }
  79399. fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
  79400. for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
  79401. fprintf(header, "%2u%s", _length_code[i],
  79402. SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
  79403. }
  79404. fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
  79405. for (i = 0; i < LENGTH_CODES; i++) {
  79406. fprintf(header, "%1u%s", base_length[i],
  79407. SEPARATOR(i, LENGTH_CODES-1, 20));
  79408. }
  79409. fprintf(header, "local const int base_dist[D_CODES] = {\n");
  79410. for (i = 0; i < D_CODES; i++) {
  79411. fprintf(header, "%5u%s", base_dist[i],
  79412. SEPARATOR(i, D_CODES-1, 10));
  79413. }
  79414. fclose(header);
  79415. }
  79416. #endif /* GEN_TREES_H */
  79417. /* ===========================================================================
  79418. * Initialize the tree data structures for a new zlib stream.
  79419. */
  79420. void _tr_init(deflate_state *s)
  79421. {
  79422. tr_static_init();
  79423. s->l_desc.dyn_tree = s->dyn_ltree;
  79424. s->l_desc.stat_desc = &static_l_desc;
  79425. s->d_desc.dyn_tree = s->dyn_dtree;
  79426. s->d_desc.stat_desc = &static_d_desc;
  79427. s->bl_desc.dyn_tree = s->bl_tree;
  79428. s->bl_desc.stat_desc = &static_bl_desc;
  79429. s->bi_buf = 0;
  79430. s->bi_valid = 0;
  79431. s->last_eob_len = 8; /* enough lookahead for inflate */
  79432. #ifdef DEBUG
  79433. s->compressed_len = 0L;
  79434. s->bits_sent = 0L;
  79435. #endif
  79436. /* Initialize the first block of the first file: */
  79437. init_block(s);
  79438. }
  79439. /* ===========================================================================
  79440. * Initialize a new block.
  79441. */
  79442. local void init_block (deflate_state *s)
  79443. {
  79444. int n; /* iterates over tree elements */
  79445. /* Initialize the trees. */
  79446. for (n = 0; n < L_CODES; n++) s->dyn_ltree[n].Freq = 0;
  79447. for (n = 0; n < D_CODES; n++) s->dyn_dtree[n].Freq = 0;
  79448. for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
  79449. s->dyn_ltree[END_BLOCK].Freq = 1;
  79450. s->opt_len = s->static_len = 0L;
  79451. s->last_lit = s->matches = 0;
  79452. }
  79453. #define SMALLEST 1
  79454. /* Index within the heap array of least frequent node in the Huffman tree */
  79455. /* ===========================================================================
  79456. * Remove the smallest element from the heap and recreate the heap with
  79457. * one less element. Updates heap and heap_len.
  79458. */
  79459. #define pqremove(s, tree, top) \
  79460. {\
  79461. top = s->heap[SMALLEST]; \
  79462. s->heap[SMALLEST] = s->heap[s->heap_len--]; \
  79463. pqdownheap(s, tree, SMALLEST); \
  79464. }
  79465. /* ===========================================================================
  79466. * Compares to subtrees, using the tree depth as tie breaker when
  79467. * the subtrees have equal frequency. This minimizes the worst case length.
  79468. */
  79469. #define smaller(tree, n, m, depth) \
  79470. (tree[n].Freq < tree[m].Freq || \
  79471. (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
  79472. /* ===========================================================================
  79473. * Restore the heap property by moving down the tree starting at node k,
  79474. * exchanging a node with the smallest of its two sons if necessary, stopping
  79475. * when the heap property is re-established (each father smaller than its
  79476. * two sons).
  79477. */
  79478. local void pqdownheap (deflate_state *s,
  79479. ct_data *tree, /* the tree to restore */
  79480. int k) /* node to move down */
  79481. {
  79482. int v = s->heap[k];
  79483. int j = k << 1; /* left son of k */
  79484. while (j <= s->heap_len) {
  79485. /* Set j to the smallest of the two sons: */
  79486. if (j < s->heap_len &&
  79487. smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
  79488. j++;
  79489. }
  79490. /* Exit if v is smaller than both sons */
  79491. if (smaller(tree, v, s->heap[j], s->depth)) break;
  79492. /* Exchange v with the smallest son */
  79493. s->heap[k] = s->heap[j]; k = j;
  79494. /* And continue down the tree, setting j to the left son of k */
  79495. j <<= 1;
  79496. }
  79497. s->heap[k] = v;
  79498. }
  79499. /* ===========================================================================
  79500. * Compute the optimal bit lengths for a tree and update the total bit length
  79501. * for the current block.
  79502. * IN assertion: the fields freq and dad are set, heap[heap_max] and
  79503. * above are the tree nodes sorted by increasing frequency.
  79504. * OUT assertions: the field len is set to the optimal bit length, the
  79505. * array bl_count contains the frequencies for each bit length.
  79506. * The length opt_len is updated; static_len is also updated if stree is
  79507. * not null.
  79508. */
  79509. local void gen_bitlen (deflate_state *s, tree_desc *desc)
  79510. {
  79511. ct_data *tree = desc->dyn_tree;
  79512. int max_code = desc->max_code;
  79513. const ct_data *stree = desc->stat_desc->static_tree;
  79514. const intf *extra = desc->stat_desc->extra_bits;
  79515. int base = desc->stat_desc->extra_base;
  79516. int max_length = desc->stat_desc->max_length;
  79517. int h; /* heap index */
  79518. int n, m; /* iterate over the tree elements */
  79519. int bits; /* bit length */
  79520. int xbits; /* extra bits */
  79521. ush f; /* frequency */
  79522. int overflow = 0; /* number of elements with bit length too large */
  79523. for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
  79524. /* In a first pass, compute the optimal bit lengths (which may
  79525. * overflow in the case of the bit length tree).
  79526. */
  79527. tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
  79528. for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
  79529. n = s->heap[h];
  79530. bits = tree[tree[n].Dad].Len + 1;
  79531. if (bits > max_length) bits = max_length, overflow++;
  79532. tree[n].Len = (ush)bits;
  79533. /* We overwrite tree[n].Dad which is no longer needed */
  79534. if (n > max_code) continue; /* not a leaf node */
  79535. s->bl_count[bits]++;
  79536. xbits = 0;
  79537. if (n >= base) xbits = extra[n-base];
  79538. f = tree[n].Freq;
  79539. s->opt_len += (ulg)f * (bits + xbits);
  79540. if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
  79541. }
  79542. if (overflow == 0) return;
  79543. Trace((stderr,"\nbit length overflow\n"));
  79544. /* This happens for example on obj2 and pic of the Calgary corpus */
  79545. /* Find the first bit length which could increase: */
  79546. do {
  79547. bits = max_length-1;
  79548. while (s->bl_count[bits] == 0) bits--;
  79549. s->bl_count[bits]--; /* move one leaf down the tree */
  79550. s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
  79551. s->bl_count[max_length]--;
  79552. /* The brother of the overflow item also moves one step up,
  79553. * but this does not affect bl_count[max_length]
  79554. */
  79555. overflow -= 2;
  79556. } while (overflow > 0);
  79557. /* Now recompute all bit lengths, scanning in increasing frequency.
  79558. * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
  79559. * lengths instead of fixing only the wrong ones. This idea is taken
  79560. * from 'ar' written by Haruhiko Okumura.)
  79561. */
  79562. for (bits = max_length; bits != 0; bits--) {
  79563. n = s->bl_count[bits];
  79564. while (n != 0) {
  79565. m = s->heap[--h];
  79566. if (m > max_code) continue;
  79567. if ((unsigned) tree[m].Len != (unsigned) bits) {
  79568. Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
  79569. s->opt_len += ((long)bits - (long)tree[m].Len)
  79570. *(long)tree[m].Freq;
  79571. tree[m].Len = (ush)bits;
  79572. }
  79573. n--;
  79574. }
  79575. }
  79576. }
  79577. /* ===========================================================================
  79578. * Generate the codes for a given tree and bit counts (which need not be
  79579. * optimal).
  79580. * IN assertion: the array bl_count contains the bit length statistics for
  79581. * the given tree and the field len is set for all tree elements.
  79582. * OUT assertion: the field code is set for all tree elements of non
  79583. * zero code length.
  79584. */
  79585. local void gen_codes (ct_data *tree, /* the tree to decorate */
  79586. int max_code, /* largest code with non zero frequency */
  79587. ushf *bl_count) /* number of codes at each bit length */
  79588. {
  79589. ush next_code[MAX_BITS+1]; /* next code value for each bit length */
  79590. ush code = 0; /* running code value */
  79591. int bits; /* bit index */
  79592. int n; /* code index */
  79593. /* The distribution counts are first used to generate the code values
  79594. * without bit reversal.
  79595. */
  79596. for (bits = 1; bits <= MAX_BITS; bits++) {
  79597. next_code[bits] = code = (code + bl_count[bits-1]) << 1;
  79598. }
  79599. /* Check that the bit counts in bl_count are consistent. The last code
  79600. * must be all ones.
  79601. */
  79602. Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
  79603. "inconsistent bit counts");
  79604. Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
  79605. for (n = 0; n <= max_code; n++) {
  79606. int len = tree[n].Len;
  79607. if (len == 0) continue;
  79608. /* Now reverse the bits */
  79609. tree[n].Code = bi_reverse(next_code[len]++, len);
  79610. Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
  79611. n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
  79612. }
  79613. }
  79614. /* ===========================================================================
  79615. * Construct one Huffman tree and assigns the code bit strings and lengths.
  79616. * Update the total bit length for the current block.
  79617. * IN assertion: the field freq is set for all tree elements.
  79618. * OUT assertions: the fields len and code are set to the optimal bit length
  79619. * and corresponding code. The length opt_len is updated; static_len is
  79620. * also updated if stree is not null. The field max_code is set.
  79621. */
  79622. local void build_tree (deflate_state *s,
  79623. tree_desc *desc) /* the tree descriptor */
  79624. {
  79625. ct_data *tree = desc->dyn_tree;
  79626. const ct_data *stree = desc->stat_desc->static_tree;
  79627. int elems = desc->stat_desc->elems;
  79628. int n, m; /* iterate over heap elements */
  79629. int max_code = -1; /* largest code with non zero frequency */
  79630. int node; /* new node being created */
  79631. /* Construct the initial heap, with least frequent element in
  79632. * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
  79633. * heap[0] is not used.
  79634. */
  79635. s->heap_len = 0, s->heap_max = HEAP_SIZE;
  79636. for (n = 0; n < elems; n++) {
  79637. if (tree[n].Freq != 0) {
  79638. s->heap[++(s->heap_len)] = max_code = n;
  79639. s->depth[n] = 0;
  79640. } else {
  79641. tree[n].Len = 0;
  79642. }
  79643. }
  79644. /* The pkzip format requires that at least one distance code exists,
  79645. * and that at least one bit should be sent even if there is only one
  79646. * possible code. So to avoid special checks later on we force at least
  79647. * two codes of non zero frequency.
  79648. */
  79649. while (s->heap_len < 2) {
  79650. node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
  79651. tree[node].Freq = 1;
  79652. s->depth[node] = 0;
  79653. s->opt_len--; if (stree) s->static_len -= stree[node].Len;
  79654. /* node is 0 or 1 so it does not have extra bits */
  79655. }
  79656. desc->max_code = max_code;
  79657. /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
  79658. * establish sub-heaps of increasing lengths:
  79659. */
  79660. for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
  79661. /* Construct the Huffman tree by repeatedly combining the least two
  79662. * frequent nodes.
  79663. */
  79664. node = elems; /* next internal node of the tree */
  79665. do {
  79666. pqremove(s, tree, n); /* n = node of least frequency */
  79667. m = s->heap[SMALLEST]; /* m = node of next least frequency */
  79668. s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
  79669. s->heap[--(s->heap_max)] = m;
  79670. /* Create a new node father of n and m */
  79671. tree[node].Freq = tree[n].Freq + tree[m].Freq;
  79672. s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
  79673. s->depth[n] : s->depth[m]) + 1);
  79674. tree[n].Dad = tree[m].Dad = (ush)node;
  79675. #ifdef DUMP_BL_TREE
  79676. if (tree == s->bl_tree) {
  79677. fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
  79678. node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
  79679. }
  79680. #endif
  79681. /* and insert the new node in the heap */
  79682. s->heap[SMALLEST] = node++;
  79683. pqdownheap(s, tree, SMALLEST);
  79684. } while (s->heap_len >= 2);
  79685. s->heap[--(s->heap_max)] = s->heap[SMALLEST];
  79686. /* At this point, the fields freq and dad are set. We can now
  79687. * generate the bit lengths.
  79688. */
  79689. gen_bitlen(s, (tree_desc *)desc);
  79690. /* The field len is now set, we can generate the bit codes */
  79691. gen_codes ((ct_data *)tree, max_code, s->bl_count);
  79692. }
  79693. /* ===========================================================================
  79694. * Scan a literal or distance tree to determine the frequencies of the codes
  79695. * in the bit length tree.
  79696. */
  79697. local void scan_tree (deflate_state *s,
  79698. ct_data *tree, /* the tree to be scanned */
  79699. int max_code) /* and its largest code of non zero frequency */
  79700. {
  79701. int n; /* iterates over all tree elements */
  79702. int prevlen = -1; /* last emitted length */
  79703. int curlen; /* length of current code */
  79704. int nextlen = tree[0].Len; /* length of next code */
  79705. int count = 0; /* repeat count of the current code */
  79706. int max_count = 7; /* max repeat count */
  79707. int min_count = 4; /* min repeat count */
  79708. if (nextlen == 0) max_count = 138, min_count = 3;
  79709. tree[max_code+1].Len = (ush)0xffff; /* guard */
  79710. for (n = 0; n <= max_code; n++) {
  79711. curlen = nextlen; nextlen = tree[n+1].Len;
  79712. if (++count < max_count && curlen == nextlen) {
  79713. continue;
  79714. } else if (count < min_count) {
  79715. s->bl_tree[curlen].Freq += count;
  79716. } else if (curlen != 0) {
  79717. if (curlen != prevlen) s->bl_tree[curlen].Freq++;
  79718. s->bl_tree[REP_3_6].Freq++;
  79719. } else if (count <= 10) {
  79720. s->bl_tree[REPZ_3_10].Freq++;
  79721. } else {
  79722. s->bl_tree[REPZ_11_138].Freq++;
  79723. }
  79724. count = 0; prevlen = curlen;
  79725. if (nextlen == 0) {
  79726. max_count = 138, min_count = 3;
  79727. } else if (curlen == nextlen) {
  79728. max_count = 6, min_count = 3;
  79729. } else {
  79730. max_count = 7, min_count = 4;
  79731. }
  79732. }
  79733. }
  79734. /* ===========================================================================
  79735. * Send a literal or distance tree in compressed form, using the codes in
  79736. * bl_tree.
  79737. */
  79738. local void send_tree (deflate_state *s,
  79739. ct_data *tree, /* the tree to be scanned */
  79740. int max_code) /* and its largest code of non zero frequency */
  79741. {
  79742. int n; /* iterates over all tree elements */
  79743. int prevlen = -1; /* last emitted length */
  79744. int curlen; /* length of current code */
  79745. int nextlen = tree[0].Len; /* length of next code */
  79746. int count = 0; /* repeat count of the current code */
  79747. int max_count = 7; /* max repeat count */
  79748. int min_count = 4; /* min repeat count */
  79749. /* tree[max_code+1].Len = -1; */ /* guard already set */
  79750. if (nextlen == 0) max_count = 138, min_count = 3;
  79751. for (n = 0; n <= max_code; n++) {
  79752. curlen = nextlen; nextlen = tree[n+1].Len;
  79753. if (++count < max_count && curlen == nextlen) {
  79754. continue;
  79755. } else if (count < min_count) {
  79756. do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
  79757. } else if (curlen != 0) {
  79758. if (curlen != prevlen) {
  79759. send_code(s, curlen, s->bl_tree); count--;
  79760. }
  79761. Assert(count >= 3 && count <= 6, " 3_6?");
  79762. send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
  79763. } else if (count <= 10) {
  79764. send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
  79765. } else {
  79766. send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
  79767. }
  79768. count = 0; prevlen = curlen;
  79769. if (nextlen == 0) {
  79770. max_count = 138, min_count = 3;
  79771. } else if (curlen == nextlen) {
  79772. max_count = 6, min_count = 3;
  79773. } else {
  79774. max_count = 7, min_count = 4;
  79775. }
  79776. }
  79777. }
  79778. /* ===========================================================================
  79779. * Construct the Huffman tree for the bit lengths and return the index in
  79780. * bl_order of the last bit length code to send.
  79781. */
  79782. local int build_bl_tree (deflate_state *s)
  79783. {
  79784. int max_blindex; /* index of last bit length code of non zero freq */
  79785. /* Determine the bit length frequencies for literal and distance trees */
  79786. scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
  79787. scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
  79788. /* Build the bit length tree: */
  79789. build_tree(s, (tree_desc *)(&(s->bl_desc)));
  79790. /* opt_len now includes the length of the tree representations, except
  79791. * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
  79792. */
  79793. /* Determine the number of bit length codes to send. The pkzip format
  79794. * requires that at least 4 bit length codes be sent. (appnote.txt says
  79795. * 3 but the actual value used is 4.)
  79796. */
  79797. for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
  79798. if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
  79799. }
  79800. /* Update opt_len to include the bit length tree and counts */
  79801. s->opt_len += 3*(max_blindex+1) + 5+5+4;
  79802. Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
  79803. s->opt_len, s->static_len));
  79804. return max_blindex;
  79805. }
  79806. /* ===========================================================================
  79807. * Send the header for a block using dynamic Huffman trees: the counts, the
  79808. * lengths of the bit length codes, the literal tree and the distance tree.
  79809. * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
  79810. */
  79811. local void send_all_trees (deflate_state *s,
  79812. int lcodes, int dcodes, int blcodes) /* number of codes for each tree */
  79813. {
  79814. int rank; /* index in bl_order */
  79815. Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
  79816. Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
  79817. "too many codes");
  79818. Tracev((stderr, "\nbl counts: "));
  79819. send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
  79820. send_bits(s, dcodes-1, 5);
  79821. send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
  79822. for (rank = 0; rank < blcodes; rank++) {
  79823. Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
  79824. send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
  79825. }
  79826. Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
  79827. send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
  79828. Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
  79829. send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
  79830. Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
  79831. }
  79832. /* ===========================================================================
  79833. * Send a stored block
  79834. */
  79835. void _tr_stored_block (deflate_state *s, charf *buf, ulg stored_len, int eof)
  79836. {
  79837. send_bits(s, (STORED_BLOCK<<1)+eof, 3); /* send block type */
  79838. #ifdef DEBUG
  79839. s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
  79840. s->compressed_len += (stored_len + 4) << 3;
  79841. #endif
  79842. copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
  79843. }
  79844. /* ===========================================================================
  79845. * Send one empty static block to give enough lookahead for inflate.
  79846. * This takes 10 bits, of which 7 may remain in the bit buffer.
  79847. * The current inflate code requires 9 bits of lookahead. If the
  79848. * last two codes for the previous block (real code plus EOB) were coded
  79849. * on 5 bits or less, inflate may have only 5+3 bits of lookahead to decode
  79850. * the last real code. In this case we send two empty static blocks instead
  79851. * of one. (There are no problems if the previous block is stored or fixed.)
  79852. * To simplify the code, we assume the worst case of last real code encoded
  79853. * on one bit only.
  79854. */
  79855. void _tr_align (deflate_state *s)
  79856. {
  79857. send_bits(s, STATIC_TREES<<1, 3);
  79858. send_code(s, END_BLOCK, static_ltree);
  79859. #ifdef DEBUG
  79860. s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
  79861. #endif
  79862. bi_flush(s);
  79863. /* Of the 10 bits for the empty block, we have already sent
  79864. * (10 - bi_valid) bits. The lookahead for the last real code (before
  79865. * the EOB of the previous block) was thus at least one plus the length
  79866. * of the EOB plus what we have just sent of the empty static block.
  79867. */
  79868. if (1 + s->last_eob_len + 10 - s->bi_valid < 9) {
  79869. send_bits(s, STATIC_TREES<<1, 3);
  79870. send_code(s, END_BLOCK, static_ltree);
  79871. #ifdef DEBUG
  79872. s->compressed_len += 10L;
  79873. #endif
  79874. bi_flush(s);
  79875. }
  79876. s->last_eob_len = 7;
  79877. }
  79878. /* ===========================================================================
  79879. * Determine the best encoding for the current block: dynamic trees, static
  79880. * trees or store, and output the encoded block to the zip file.
  79881. */
  79882. void _tr_flush_block (deflate_state *s,
  79883. charf *buf, /* input block, or NULL if too old */
  79884. ulg stored_len, /* length of input block */
  79885. int eof) /* true if this is the last block for a file */
  79886. {
  79887. ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
  79888. int max_blindex = 0; /* index of last bit length code of non zero freq */
  79889. /* Build the Huffman trees unless a stored block is forced */
  79890. if (s->level > 0) {
  79891. /* Check if the file is binary or text */
  79892. if (stored_len > 0 && s->strm->data_type == Z_UNKNOWN)
  79893. set_data_type(s);
  79894. /* Construct the literal and distance trees */
  79895. build_tree(s, (tree_desc *)(&(s->l_desc)));
  79896. Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
  79897. s->static_len));
  79898. build_tree(s, (tree_desc *)(&(s->d_desc)));
  79899. Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
  79900. s->static_len));
  79901. /* At this point, opt_len and static_len are the total bit lengths of
  79902. * the compressed block data, excluding the tree representations.
  79903. */
  79904. /* Build the bit length tree for the above two trees, and get the index
  79905. * in bl_order of the last bit length code to send.
  79906. */
  79907. max_blindex = build_bl_tree(s);
  79908. /* Determine the best encoding. Compute the block lengths in bytes. */
  79909. opt_lenb = (s->opt_len+3+7)>>3;
  79910. static_lenb = (s->static_len+3+7)>>3;
  79911. Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
  79912. opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
  79913. s->last_lit));
  79914. if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
  79915. } else {
  79916. Assert(buf != (char*)0, "lost buf");
  79917. opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
  79918. }
  79919. #ifdef FORCE_STORED
  79920. if (buf != (char*)0) { /* force stored block */
  79921. #else
  79922. if (stored_len+4 <= opt_lenb && buf != (char*)0) {
  79923. /* 4: two words for the lengths */
  79924. #endif
  79925. /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
  79926. * Otherwise we can't have processed more than WSIZE input bytes since
  79927. * the last block flush, because compression would have been
  79928. * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
  79929. * transform a block into a stored block.
  79930. */
  79931. _tr_stored_block(s, buf, stored_len, eof);
  79932. #ifdef FORCE_STATIC
  79933. } else if (static_lenb >= 0) { /* force static trees */
  79934. #else
  79935. } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
  79936. #endif
  79937. send_bits(s, (STATIC_TREES<<1)+eof, 3);
  79938. compress_block(s, (ct_data *)static_ltree, (ct_data *)static_dtree);
  79939. #ifdef DEBUG
  79940. s->compressed_len += 3 + s->static_len;
  79941. #endif
  79942. } else {
  79943. send_bits(s, (DYN_TREES<<1)+eof, 3);
  79944. send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
  79945. max_blindex+1);
  79946. compress_block(s, (ct_data *)s->dyn_ltree, (ct_data *)s->dyn_dtree);
  79947. #ifdef DEBUG
  79948. s->compressed_len += 3 + s->opt_len;
  79949. #endif
  79950. }
  79951. Assert (s->compressed_len == s->bits_sent, "bad compressed size");
  79952. /* The above check is made mod 2^32, for files larger than 512 MB
  79953. * and uLong implemented on 32 bits.
  79954. */
  79955. init_block(s);
  79956. if (eof) {
  79957. bi_windup(s);
  79958. #ifdef DEBUG
  79959. s->compressed_len += 7; /* align on byte boundary */
  79960. #endif
  79961. }
  79962. Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
  79963. s->compressed_len-7*eof));
  79964. }
  79965. /* ===========================================================================
  79966. * Save the match info and tally the frequency counts. Return true if
  79967. * the current block must be flushed.
  79968. */
  79969. int _tr_tally (deflate_state *s,
  79970. unsigned dist, /* distance of matched string */
  79971. unsigned lc) /* match length-MIN_MATCH or unmatched char (if dist==0) */
  79972. {
  79973. s->d_buf[s->last_lit] = (ush)dist;
  79974. s->l_buf[s->last_lit++] = (uch)lc;
  79975. if (dist == 0) {
  79976. /* lc is the unmatched char */
  79977. s->dyn_ltree[lc].Freq++;
  79978. } else {
  79979. s->matches++;
  79980. /* Here, lc is the match length - MIN_MATCH */
  79981. dist--; /* dist = match distance - 1 */
  79982. Assert((ush)dist < (ush)MAX_DIST(s) &&
  79983. (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
  79984. (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
  79985. s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
  79986. s->dyn_dtree[d_code(dist)].Freq++;
  79987. }
  79988. #ifdef TRUNCATE_BLOCK
  79989. /* Try to guess if it is profitable to stop the current block here */
  79990. if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
  79991. /* Compute an upper bound for the compressed length */
  79992. ulg out_length = (ulg)s->last_lit*8L;
  79993. ulg in_length = (ulg)((long)s->strstart - s->block_start);
  79994. int dcode;
  79995. for (dcode = 0; dcode < D_CODES; dcode++) {
  79996. out_length += (ulg)s->dyn_dtree[dcode].Freq *
  79997. (5L+extra_dbits[dcode]);
  79998. }
  79999. out_length >>= 3;
  80000. Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
  80001. s->last_lit, in_length, out_length,
  80002. 100L - out_length*100L/in_length));
  80003. if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
  80004. }
  80005. #endif
  80006. return (s->last_lit == s->lit_bufsize-1);
  80007. /* We avoid equality with lit_bufsize because of wraparound at 64K
  80008. * on 16 bit machines and because stored blocks are restricted to
  80009. * 64K-1 bytes.
  80010. */
  80011. }
  80012. /* ===========================================================================
  80013. * Send the block data compressed using the given Huffman trees
  80014. */
  80015. local void compress_block (deflate_state *s,
  80016. ct_data *ltree, /* literal tree */
  80017. ct_data *dtree) /* distance tree */
  80018. {
  80019. unsigned dist; /* distance of matched string */
  80020. int lc; /* match length or unmatched char (if dist == 0) */
  80021. unsigned lx = 0; /* running index in l_buf */
  80022. unsigned code; /* the code to send */
  80023. int extra; /* number of extra bits to send */
  80024. if (s->last_lit != 0) do {
  80025. dist = s->d_buf[lx];
  80026. lc = s->l_buf[lx++];
  80027. if (dist == 0) {
  80028. send_code(s, lc, ltree); /* send a literal byte */
  80029. Tracecv(isgraph(lc), (stderr," '%c' ", lc));
  80030. } else {
  80031. /* Here, lc is the match length - MIN_MATCH */
  80032. code = _length_code[lc];
  80033. send_code(s, code+LITERALS+1, ltree); /* send the length code */
  80034. extra = extra_lbits[code];
  80035. if (extra != 0) {
  80036. lc -= base_length[code];
  80037. send_bits(s, lc, extra); /* send the extra length bits */
  80038. }
  80039. dist--; /* dist is now the match distance - 1 */
  80040. code = d_code(dist);
  80041. Assert (code < D_CODES, "bad d_code");
  80042. send_code(s, code, dtree); /* send the distance code */
  80043. extra = extra_dbits[code];
  80044. if (extra != 0) {
  80045. dist -= base_dist[code];
  80046. send_bits(s, dist, extra); /* send the extra distance bits */
  80047. }
  80048. } /* literal or match pair ? */
  80049. /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
  80050. Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
  80051. "pendingBuf overflow");
  80052. } while (lx < s->last_lit);
  80053. send_code(s, END_BLOCK, ltree);
  80054. s->last_eob_len = ltree[END_BLOCK].Len;
  80055. }
  80056. /* ===========================================================================
  80057. * Set the data type to BINARY or TEXT, using a crude approximation:
  80058. * set it to Z_TEXT if all symbols are either printable characters (33 to 255)
  80059. * or white spaces (9 to 13, or 32); or set it to Z_BINARY otherwise.
  80060. * IN assertion: the fields Freq of dyn_ltree are set.
  80061. */
  80062. local void set_data_type (deflate_state *s)
  80063. {
  80064. int n;
  80065. for (n = 0; n < 9; n++)
  80066. if (s->dyn_ltree[n].Freq != 0)
  80067. break;
  80068. if (n == 9)
  80069. for (n = 14; n < 32; n++)
  80070. if (s->dyn_ltree[n].Freq != 0)
  80071. break;
  80072. s->strm->data_type = (n == 32) ? Z_TEXT : Z_BINARY;
  80073. }
  80074. /* ===========================================================================
  80075. * Reverse the first len bits of a code, using straightforward code (a faster
  80076. * method would use a table)
  80077. * IN assertion: 1 <= len <= 15
  80078. */
  80079. local unsigned bi_reverse (unsigned code, int len)
  80080. {
  80081. register unsigned res = 0;
  80082. do {
  80083. res |= code & 1;
  80084. code >>= 1, res <<= 1;
  80085. } while (--len > 0);
  80086. return res >> 1;
  80087. }
  80088. /* ===========================================================================
  80089. * Flush the bit buffer, keeping at most 7 bits in it.
  80090. */
  80091. local void bi_flush (deflate_state *s)
  80092. {
  80093. if (s->bi_valid == 16) {
  80094. put_short(s, s->bi_buf);
  80095. s->bi_buf = 0;
  80096. s->bi_valid = 0;
  80097. } else if (s->bi_valid >= 8) {
  80098. put_byte(s, (Byte)s->bi_buf);
  80099. s->bi_buf >>= 8;
  80100. s->bi_valid -= 8;
  80101. }
  80102. }
  80103. /* ===========================================================================
  80104. * Flush the bit buffer and align the output on a byte boundary
  80105. */
  80106. local void bi_windup (deflate_state *s)
  80107. {
  80108. if (s->bi_valid > 8) {
  80109. put_short(s, s->bi_buf);
  80110. } else if (s->bi_valid > 0) {
  80111. put_byte(s, (Byte)s->bi_buf);
  80112. }
  80113. s->bi_buf = 0;
  80114. s->bi_valid = 0;
  80115. #ifdef DEBUG
  80116. s->bits_sent = (s->bits_sent+7) & ~7;
  80117. #endif
  80118. }
  80119. /* ===========================================================================
  80120. * Copy a stored block, storing first the length and its
  80121. * one's complement if requested.
  80122. */
  80123. local void copy_block(deflate_state *s,
  80124. charf *buf, /* the input data */
  80125. unsigned len, /* its length */
  80126. int header) /* true if block header must be written */
  80127. {
  80128. bi_windup(s); /* align on byte boundary */
  80129. s->last_eob_len = 8; /* enough lookahead for inflate */
  80130. if (header) {
  80131. put_short(s, (ush)len);
  80132. put_short(s, (ush)~len);
  80133. #ifdef DEBUG
  80134. s->bits_sent += 2*16;
  80135. #endif
  80136. }
  80137. #ifdef DEBUG
  80138. s->bits_sent += (ulg)len<<3;
  80139. #endif
  80140. while (len--) {
  80141. put_byte(s, *buf++);
  80142. }
  80143. }
  80144. /********* End of inlined file: trees.c *********/
  80145. /********* Start of inlined file: uncompr.c *********/
  80146. /* @(#) $Id: uncompr.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80147. #define ZLIB_INTERNAL
  80148. /* ===========================================================================
  80149. Decompresses the source buffer into the destination buffer. sourceLen is
  80150. the byte length of the source buffer. Upon entry, destLen is the total
  80151. size of the destination buffer, which must be large enough to hold the
  80152. entire uncompressed data. (The size of the uncompressed data must have
  80153. been saved previously by the compressor and transmitted to the decompressor
  80154. by some mechanism outside the scope of this compression library.)
  80155. Upon exit, destLen is the actual size of the compressed buffer.
  80156. This function can be used to decompress a whole file at once if the
  80157. input file is mmap'ed.
  80158. uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
  80159. enough memory, Z_BUF_ERROR if there was not enough room in the output
  80160. buffer, or Z_DATA_ERROR if the input data was corrupted.
  80161. */
  80162. int ZEXPORT uncompress (Bytef *dest,
  80163. uLongf *destLen,
  80164. const Bytef *source,
  80165. uLong sourceLen)
  80166. {
  80167. z_stream stream;
  80168. int err;
  80169. stream.next_in = (Bytef*)source;
  80170. stream.avail_in = (uInt)sourceLen;
  80171. /* Check for source > 64K on 16-bit machine: */
  80172. if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
  80173. stream.next_out = dest;
  80174. stream.avail_out = (uInt)*destLen;
  80175. if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
  80176. stream.zalloc = (alloc_func)0;
  80177. stream.zfree = (free_func)0;
  80178. err = inflateInit(&stream);
  80179. if (err != Z_OK) return err;
  80180. err = inflate(&stream, Z_FINISH);
  80181. if (err != Z_STREAM_END) {
  80182. inflateEnd(&stream);
  80183. if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
  80184. return Z_DATA_ERROR;
  80185. return err;
  80186. }
  80187. *destLen = stream.total_out;
  80188. err = inflateEnd(&stream);
  80189. return err;
  80190. }
  80191. /********* End of inlined file: uncompr.c *********/
  80192. /********* Start of inlined file: zutil.c *********/
  80193. /* @(#) $Id: zutil.c,v 1.1 2007/06/07 17:54:37 jules_rms Exp $ */
  80194. #ifndef NO_DUMMY_DECL
  80195. struct internal_state {int dummy;}; /* for buggy compilers */
  80196. #endif
  80197. const char * const z_errmsg[10] = {
  80198. "need dictionary", /* Z_NEED_DICT 2 */
  80199. "stream end", /* Z_STREAM_END 1 */
  80200. "", /* Z_OK 0 */
  80201. "file error", /* Z_ERRNO (-1) */
  80202. "stream error", /* Z_STREAM_ERROR (-2) */
  80203. "data error", /* Z_DATA_ERROR (-3) */
  80204. "insufficient memory", /* Z_MEM_ERROR (-4) */
  80205. "buffer error", /* Z_BUF_ERROR (-5) */
  80206. "incompatible version",/* Z_VERSION_ERROR (-6) */
  80207. ""};
  80208. /*const char * ZEXPORT zlibVersion()
  80209. {
  80210. return ZLIB_VERSION;
  80211. }
  80212. uLong ZEXPORT zlibCompileFlags()
  80213. {
  80214. uLong flags;
  80215. flags = 0;
  80216. switch (sizeof(uInt)) {
  80217. case 2: break;
  80218. case 4: flags += 1; break;
  80219. case 8: flags += 2; break;
  80220. default: flags += 3;
  80221. }
  80222. switch (sizeof(uLong)) {
  80223. case 2: break;
  80224. case 4: flags += 1 << 2; break;
  80225. case 8: flags += 2 << 2; break;
  80226. default: flags += 3 << 2;
  80227. }
  80228. switch (sizeof(voidpf)) {
  80229. case 2: break;
  80230. case 4: flags += 1 << 4; break;
  80231. case 8: flags += 2 << 4; break;
  80232. default: flags += 3 << 4;
  80233. }
  80234. switch (sizeof(z_off_t)) {
  80235. case 2: break;
  80236. case 4: flags += 1 << 6; break;
  80237. case 8: flags += 2 << 6; break;
  80238. default: flags += 3 << 6;
  80239. }
  80240. #ifdef DEBUG
  80241. flags += 1 << 8;
  80242. #endif
  80243. #if defined(ASMV) || defined(ASMINF)
  80244. flags += 1 << 9;
  80245. #endif
  80246. #ifdef ZLIB_WINAPI
  80247. flags += 1 << 10;
  80248. #endif
  80249. #ifdef BUILDFIXED
  80250. flags += 1 << 12;
  80251. #endif
  80252. #ifdef DYNAMIC_CRC_TABLE
  80253. flags += 1 << 13;
  80254. #endif
  80255. #ifdef NO_GZCOMPRESS
  80256. flags += 1L << 16;
  80257. #endif
  80258. #ifdef NO_GZIP
  80259. flags += 1L << 17;
  80260. #endif
  80261. #ifdef PKZIP_BUG_WORKAROUND
  80262. flags += 1L << 20;
  80263. #endif
  80264. #ifdef FASTEST
  80265. flags += 1L << 21;
  80266. #endif
  80267. #ifdef STDC
  80268. # ifdef NO_vsnprintf
  80269. flags += 1L << 25;
  80270. # ifdef HAS_vsprintf_void
  80271. flags += 1L << 26;
  80272. # endif
  80273. # else
  80274. # ifdef HAS_vsnprintf_void
  80275. flags += 1L << 26;
  80276. # endif
  80277. # endif
  80278. #else
  80279. flags += 1L << 24;
  80280. # ifdef NO_snprintf
  80281. flags += 1L << 25;
  80282. # ifdef HAS_sprintf_void
  80283. flags += 1L << 26;
  80284. # endif
  80285. # else
  80286. # ifdef HAS_snprintf_void
  80287. flags += 1L << 26;
  80288. # endif
  80289. # endif
  80290. #endif
  80291. return flags;
  80292. }*/
  80293. #ifdef DEBUG
  80294. # ifndef verbose
  80295. # define verbose 0
  80296. # endif
  80297. int z_verbose = verbose;
  80298. void z_error (char *m)
  80299. {
  80300. fprintf(stderr, "%s\n", m);
  80301. exit(1);
  80302. }
  80303. #endif
  80304. /* exported to allow conversion of error code to string for compress() and
  80305. * uncompress()
  80306. */
  80307. const char * ZEXPORT zError(int err)
  80308. {
  80309. return ERR_MSG(err);
  80310. }
  80311. #if defined(_WIN32_WCE)
  80312. /* The Microsoft C Run-Time Library for Windows CE doesn't have
  80313. * errno. We define it as a global variable to simplify porting.
  80314. * Its value is always 0 and should not be used.
  80315. */
  80316. int errno = 0;
  80317. #endif
  80318. #ifndef HAVE_MEMCPY
  80319. void zmemcpy(dest, source, len)
  80320. Bytef* dest;
  80321. const Bytef* source;
  80322. uInt len;
  80323. {
  80324. if (len == 0) return;
  80325. do {
  80326. *dest++ = *source++; /* ??? to be unrolled */
  80327. } while (--len != 0);
  80328. }
  80329. int zmemcmp(s1, s2, len)
  80330. const Bytef* s1;
  80331. const Bytef* s2;
  80332. uInt len;
  80333. {
  80334. uInt j;
  80335. for (j = 0; j < len; j++) {
  80336. if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
  80337. }
  80338. return 0;
  80339. }
  80340. void zmemzero(dest, len)
  80341. Bytef* dest;
  80342. uInt len;
  80343. {
  80344. if (len == 0) return;
  80345. do {
  80346. *dest++ = 0; /* ??? to be unrolled */
  80347. } while (--len != 0);
  80348. }
  80349. #endif
  80350. #ifdef SYS16BIT
  80351. #ifdef __TURBOC__
  80352. /* Turbo C in 16-bit mode */
  80353. # define MY_ZCALLOC
  80354. /* Turbo C malloc() does not allow dynamic allocation of 64K bytes
  80355. * and farmalloc(64K) returns a pointer with an offset of 8, so we
  80356. * must fix the pointer. Warning: the pointer must be put back to its
  80357. * original form in order to free it, use zcfree().
  80358. */
  80359. #define MAX_PTR 10
  80360. /* 10*64K = 640K */
  80361. local int next_ptr = 0;
  80362. typedef struct ptr_table_s {
  80363. voidpf org_ptr;
  80364. voidpf new_ptr;
  80365. } ptr_table;
  80366. local ptr_table table[MAX_PTR];
  80367. /* This table is used to remember the original form of pointers
  80368. * to large buffers (64K). Such pointers are normalized with a zero offset.
  80369. * Since MSDOS is not a preemptive multitasking OS, this table is not
  80370. * protected from concurrent access. This hack doesn't work anyway on
  80371. * a protected system like OS/2. Use Microsoft C instead.
  80372. */
  80373. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80374. {
  80375. voidpf buf = opaque; /* just to make some compilers happy */
  80376. ulg bsize = (ulg)items*size;
  80377. /* If we allocate less than 65520 bytes, we assume that farmalloc
  80378. * will return a usable pointer which doesn't have to be normalized.
  80379. */
  80380. if (bsize < 65520L) {
  80381. buf = farmalloc(bsize);
  80382. if (*(ush*)&buf != 0) return buf;
  80383. } else {
  80384. buf = farmalloc(bsize + 16L);
  80385. }
  80386. if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
  80387. table[next_ptr].org_ptr = buf;
  80388. /* Normalize the pointer to seg:0 */
  80389. *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
  80390. *(ush*)&buf = 0;
  80391. table[next_ptr++].new_ptr = buf;
  80392. return buf;
  80393. }
  80394. void zcfree (voidpf opaque, voidpf ptr)
  80395. {
  80396. int n;
  80397. if (*(ush*)&ptr != 0) { /* object < 64K */
  80398. farfree(ptr);
  80399. return;
  80400. }
  80401. /* Find the original pointer */
  80402. for (n = 0; n < next_ptr; n++) {
  80403. if (ptr != table[n].new_ptr) continue;
  80404. farfree(table[n].org_ptr);
  80405. while (++n < next_ptr) {
  80406. table[n-1] = table[n];
  80407. }
  80408. next_ptr--;
  80409. return;
  80410. }
  80411. ptr = opaque; /* just to make some compilers happy */
  80412. Assert(0, "zcfree: ptr not found");
  80413. }
  80414. #endif /* __TURBOC__ */
  80415. #ifdef M_I86
  80416. /* Microsoft C in 16-bit mode */
  80417. # define MY_ZCALLOC
  80418. #if (!defined(_MSC_VER) || (_MSC_VER <= 600))
  80419. # define _halloc halloc
  80420. # define _hfree hfree
  80421. #endif
  80422. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80423. {
  80424. if (opaque) opaque = 0; /* to make compiler happy */
  80425. return _halloc((long)items, size);
  80426. }
  80427. void zcfree (voidpf opaque, voidpf ptr)
  80428. {
  80429. if (opaque) opaque = 0; /* to make compiler happy */
  80430. _hfree(ptr);
  80431. }
  80432. #endif /* M_I86 */
  80433. #endif /* SYS16BIT */
  80434. #ifndef MY_ZCALLOC /* Any system without a special alloc function */
  80435. #ifndef STDC
  80436. extern voidp malloc OF((uInt size));
  80437. extern voidp calloc OF((uInt items, uInt size));
  80438. extern void free OF((voidpf ptr));
  80439. #endif
  80440. voidpf zcalloc (voidpf opaque, unsigned items, unsigned size)
  80441. {
  80442. if (opaque) items += size - size; /* make compiler happy */
  80443. return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
  80444. (voidpf)calloc(items, size);
  80445. }
  80446. void zcfree (voidpf opaque, voidpf ptr)
  80447. {
  80448. free(ptr);
  80449. if (opaque) return; /* make compiler happy */
  80450. }
  80451. #endif /* MY_ZCALLOC */
  80452. /********* End of inlined file: zutil.c *********/
  80453. #undef Byte
  80454. }
  80455. #else
  80456. #include <zlib.h>
  80457. #endif
  80458. }
  80459. #if JUCE_MSVC
  80460. #pragma warning (pop)
  80461. #endif
  80462. BEGIN_JUCE_NAMESPACE
  80463. using namespace zlibNamespace;
  80464. // internal helper object that holds the zlib structures so they don't have to be
  80465. // included publicly.
  80466. class GZIPDecompressHelper
  80467. {
  80468. private:
  80469. z_stream* stream;
  80470. uint8* data;
  80471. int dataSize;
  80472. public:
  80473. bool finished, needsDictionary, error;
  80474. GZIPDecompressHelper (const bool noWrap) throw()
  80475. : data (0),
  80476. dataSize (0),
  80477. finished (false),
  80478. needsDictionary (false),
  80479. error (false)
  80480. {
  80481. stream = (z_stream*) juce_calloc (sizeof (z_stream));
  80482. if (inflateInit2 (stream, (noWrap) ? -MAX_WBITS
  80483. : MAX_WBITS) != Z_OK)
  80484. {
  80485. juce_free (stream);
  80486. stream = 0;
  80487. error = true;
  80488. finished = true;
  80489. }
  80490. }
  80491. ~GZIPDecompressHelper() throw()
  80492. {
  80493. if (stream != 0)
  80494. {
  80495. inflateEnd (stream);
  80496. juce_free (stream);
  80497. }
  80498. }
  80499. bool needsInput() const throw() { return dataSize <= 0; }
  80500. void setInput (uint8* const data_, const int size) throw()
  80501. {
  80502. data = data_;
  80503. dataSize = size;
  80504. }
  80505. int doNextBlock (uint8* const dest, const int destSize) throw()
  80506. {
  80507. if (stream != 0 && data != 0 && ! finished)
  80508. {
  80509. stream->next_in = data;
  80510. stream->next_out = dest;
  80511. stream->avail_in = dataSize;
  80512. stream->avail_out = destSize;
  80513. switch (inflate (stream, Z_PARTIAL_FLUSH))
  80514. {
  80515. case Z_STREAM_END:
  80516. finished = true;
  80517. // deliberate fall-through
  80518. case Z_OK:
  80519. data += dataSize - stream->avail_in;
  80520. dataSize = stream->avail_in;
  80521. return destSize - stream->avail_out;
  80522. case Z_NEED_DICT:
  80523. needsDictionary = true;
  80524. data += dataSize - stream->avail_in;
  80525. dataSize = stream->avail_in;
  80526. break;
  80527. case Z_DATA_ERROR:
  80528. case Z_MEM_ERROR:
  80529. error = true;
  80530. default:
  80531. break;
  80532. }
  80533. }
  80534. return 0;
  80535. }
  80536. };
  80537. const int gzipDecompBufferSize = 32768;
  80538. GZIPDecompressorInputStream::GZIPDecompressorInputStream (InputStream* const sourceStream_,
  80539. const bool deleteSourceWhenDestroyed_,
  80540. const bool noWrap_,
  80541. const int64 uncompressedStreamLength_)
  80542. : sourceStream (sourceStream_),
  80543. uncompressedStreamLength (uncompressedStreamLength_),
  80544. deleteSourceWhenDestroyed (deleteSourceWhenDestroyed_),
  80545. noWrap (noWrap_),
  80546. isEof (false),
  80547. activeBufferSize (0),
  80548. originalSourcePos (sourceStream_->getPosition()),
  80549. currentPos (0)
  80550. {
  80551. buffer = (uint8*) juce_malloc (gzipDecompBufferSize);
  80552. helper = new GZIPDecompressHelper (noWrap_);
  80553. }
  80554. GZIPDecompressorInputStream::~GZIPDecompressorInputStream()
  80555. {
  80556. juce_free (buffer);
  80557. if (deleteSourceWhenDestroyed)
  80558. delete sourceStream;
  80559. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80560. delete h;
  80561. }
  80562. int64 GZIPDecompressorInputStream::getTotalLength()
  80563. {
  80564. return uncompressedStreamLength;
  80565. }
  80566. int GZIPDecompressorInputStream::read (void* destBuffer, int howMany)
  80567. {
  80568. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80569. if ((howMany > 0) && ! isEof)
  80570. {
  80571. jassert (destBuffer != 0);
  80572. if (destBuffer != 0)
  80573. {
  80574. int numRead = 0;
  80575. uint8* d = (uint8*) destBuffer;
  80576. while (! h->error)
  80577. {
  80578. const int n = h->doNextBlock (d, howMany);
  80579. currentPos += n;
  80580. if (n == 0)
  80581. {
  80582. if (h->finished || h->needsDictionary)
  80583. {
  80584. isEof = true;
  80585. return numRead;
  80586. }
  80587. if (h->needsInput())
  80588. {
  80589. activeBufferSize = sourceStream->read (buffer, gzipDecompBufferSize);
  80590. if (activeBufferSize > 0)
  80591. {
  80592. h->setInput ((uint8*) buffer, activeBufferSize);
  80593. }
  80594. else
  80595. {
  80596. isEof = true;
  80597. return numRead;
  80598. }
  80599. }
  80600. }
  80601. else
  80602. {
  80603. numRead += n;
  80604. howMany -= n;
  80605. d += n;
  80606. if (howMany <= 0)
  80607. return numRead;
  80608. }
  80609. }
  80610. }
  80611. }
  80612. return 0;
  80613. }
  80614. bool GZIPDecompressorInputStream::isExhausted()
  80615. {
  80616. const GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80617. return h->error || isEof;
  80618. }
  80619. int64 GZIPDecompressorInputStream::getPosition()
  80620. {
  80621. return currentPos;
  80622. }
  80623. bool GZIPDecompressorInputStream::setPosition (int64 newPos)
  80624. {
  80625. if (newPos != currentPos)
  80626. {
  80627. if (newPos > currentPos)
  80628. {
  80629. skipNextBytes (newPos - currentPos);
  80630. }
  80631. else
  80632. {
  80633. // reset the stream and start again..
  80634. GZIPDecompressHelper* const h = (GZIPDecompressHelper*) helper;
  80635. delete h;
  80636. isEof = false;
  80637. activeBufferSize = 0;
  80638. currentPos = 0;
  80639. helper = new GZIPDecompressHelper (noWrap);
  80640. sourceStream->setPosition (originalSourcePos);
  80641. skipNextBytes (newPos);
  80642. }
  80643. }
  80644. return true;
  80645. }
  80646. END_JUCE_NAMESPACE
  80647. /********* End of inlined file: juce_GZIPDecompressorInputStream.cpp *********/
  80648. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  80649. /********* Start of inlined file: juce_FlacAudioFormat.cpp *********/
  80650. /********* Start of inlined file: juce_Config.h *********/
  80651. #ifndef __JUCE_CONFIG_JUCEHEADER__
  80652. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  80653. /*
  80654. This file contains macros that enable/disable various JUCE features.
  80655. */
  80656. /** The name of the namespace that all Juce classes and functions will be
  80657. put inside. If this is not defined, no namespace will be used.
  80658. */
  80659. #ifndef JUCE_NAMESPACE
  80660. #define JUCE_NAMESPACE juce
  80661. #endif
  80662. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  80663. but if you define this value, you can override this can force it to be true or
  80664. false.
  80665. */
  80666. #ifndef JUCE_FORCE_DEBUG
  80667. //#define JUCE_FORCE_DEBUG 1
  80668. #endif
  80669. /** If this flag is enabled, the the jassert and jassertfalse macros will
  80670. always use Logger::writeToLog() to write a message when an assertion happens.
  80671. Enabling it will also leave this turned on in release builds. When it's disabled,
  80672. however, the jassert and jassertfalse macros will not be compiled in a
  80673. release build.
  80674. @see jassert, jassertfalse, Logger
  80675. */
  80676. #ifndef JUCE_LOG_ASSERTIONS
  80677. // #define JUCE_LOG_ASSERTIONS 1
  80678. #endif
  80679. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  80680. which the ASIOAudioIODevice class can't be built. See the comments in the
  80681. ASIOAudioIODevice class's header file for more info about this.
  80682. (This only affects a Win32 build)
  80683. */
  80684. #ifndef JUCE_ASIO
  80685. #define JUCE_ASIO 1
  80686. #endif
  80687. /** Comment out this macro to disable building of ALSA device support on Linux.
  80688. */
  80689. #ifndef JUCE_ALSA
  80690. #define JUCE_ALSA 1
  80691. #endif
  80692. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  80693. have the SDK installed.
  80694. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  80695. classes will be unavailable.
  80696. On Windows, if you enable this, you'll need to have the QuickTime SDK
  80697. installed, and its header files will need to be on your include path.
  80698. */
  80699. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  80700. #define JUCE_QUICKTIME 1
  80701. #endif
  80702. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  80703. have the appropriate headers and libraries available. If it's not enabled, the
  80704. OpenGLComponent class will be unavailable.
  80705. */
  80706. #ifndef JUCE_OPENGL
  80707. #define JUCE_OPENGL 1
  80708. #endif
  80709. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  80710. If you're not going to need either of these formats, turn off the flags to
  80711. avoid bloating your codebase with them.
  80712. */
  80713. #ifndef JUCE_USE_FLAC
  80714. #define JUCE_USE_FLAC 1
  80715. #endif
  80716. #ifndef JUCE_USE_OGGVORBIS
  80717. #define JUCE_USE_OGGVORBIS 1
  80718. #endif
  80719. /** This flag lets you enable support for CD-burning. You might want to disable
  80720. it to build without the MS SDK under windows.
  80721. */
  80722. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  80723. #define JUCE_USE_CDBURNER 1
  80724. #endif
  80725. /** Enabling this macro means that all regions that get repainted will have a coloured
  80726. line drawn around them.
  80727. This is handy if you're trying to optimise drawing, because it lets you easily see
  80728. when anything is being repainted unnecessarily.
  80729. */
  80730. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  80731. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  80732. #endif
  80733. /** Enable this under Linux to use Xinerama for multi-monitor support.
  80734. */
  80735. #ifndef JUCE_USE_XINERAMA
  80736. #define JUCE_USE_XINERAMA 1
  80737. #endif
  80738. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  80739. */
  80740. #ifndef JUCE_USE_XSHM
  80741. #define JUCE_USE_XSHM 1
  80742. #endif
  80743. /** Enabling this builds support for VST audio plugins.
  80744. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  80745. */
  80746. #ifndef JUCE_PLUGINHOST_VST
  80747. // #define JUCE_PLUGINHOST_VST 1
  80748. #endif
  80749. /** Enabling this builds support for AudioUnit audio plugins.
  80750. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  80751. */
  80752. #ifndef JUCE_PLUGINHOST_AU
  80753. // #define JUCE_PLUGINHOST_AU 1
  80754. #endif
  80755. /** Disabling this will avoid linking to any UI code. This is handy for
  80756. writing command-line utilities, e.g. on linux boxes which don't have some
  80757. of the UI libraries installed.
  80758. (On mac and windows, this won't generally make much difference to the build).
  80759. */
  80760. #ifndef JUCE_BUILD_GUI_CLASSES
  80761. #define JUCE_BUILD_GUI_CLASSES 1
  80762. #endif
  80763. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  80764. */
  80765. #ifndef JUCE_WEB_BROWSER
  80766. #define JUCE_WEB_BROWSER 1
  80767. #endif
  80768. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  80769. codebase - you might need to use this if you're linking to some of these libraries
  80770. yourself.
  80771. */
  80772. #ifndef JUCE_INCLUDE_ZLIB_CODE
  80773. #define JUCE_INCLUDE_ZLIB_CODE 1
  80774. #endif
  80775. #ifndef JUCE_INCLUDE_FLAC_CODE
  80776. #define JUCE_INCLUDE_FLAC_CODE 1
  80777. #endif
  80778. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  80779. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  80780. #endif
  80781. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  80782. #define JUCE_INCLUDE_PNGLIB_CODE 1
  80783. #endif
  80784. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  80785. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  80786. #endif
  80787. /** Enable this to add extra memory-leak info to the new and delete operators.
  80788. (Currently, this only affects Windows builds in debug mode).
  80789. */
  80790. #ifndef JUCE_CHECK_MEMORY_LEAKS
  80791. #define JUCE_CHECK_MEMORY_LEAKS 1
  80792. #endif
  80793. /** Enable this to turn on juce's internal catching of exceptions.
  80794. Turning it off will avoid any exception catching. With it on, all exceptions
  80795. are passed to the JUCEApplication::unhandledException() callback for logging.
  80796. */
  80797. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  80798. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  80799. #endif
  80800. /** If this macro is set, the Juce String class will use unicode as its
  80801. internal representation. If it isn't set, it'll use ANSI.
  80802. */
  80803. #ifndef JUCE_STRINGS_ARE_UNICODE
  80804. #define JUCE_STRINGS_ARE_UNICODE 1
  80805. #endif
  80806. #endif
  80807. /********* End of inlined file: juce_Config.h *********/
  80808. #ifdef _MSC_VER
  80809. #include <windows.h>
  80810. #endif
  80811. #if JUCE_USE_FLAC
  80812. #ifdef _MSC_VER
  80813. #pragma warning (disable : 4505)
  80814. #pragma warning (push)
  80815. #endif
  80816. namespace FlacNamespace
  80817. {
  80818. #if JUCE_INCLUDE_FLAC_CODE
  80819. #define FLAC__NO_DLL 1
  80820. #if ! defined (SIZE_MAX)
  80821. #define SIZE_MAX 0xffffffff
  80822. #endif
  80823. #define __STDC_LIMIT_MACROS 1
  80824. /********* Start of inlined file: all.h *********/
  80825. #ifndef FLAC__ALL_H
  80826. #define FLAC__ALL_H
  80827. /********* Start of inlined file: export.h *********/
  80828. #ifndef FLAC__EXPORT_H
  80829. #define FLAC__EXPORT_H
  80830. /** \file include/FLAC/export.h
  80831. *
  80832. * \brief
  80833. * This module contains #defines and symbols for exporting function
  80834. * calls, and providing version information and compiled-in features.
  80835. *
  80836. * See the \link flac_export export \endlink module.
  80837. */
  80838. /** \defgroup flac_export FLAC/export.h: export symbols
  80839. * \ingroup flac
  80840. *
  80841. * \brief
  80842. * This module contains #defines and symbols for exporting function
  80843. * calls, and providing version information and compiled-in features.
  80844. *
  80845. * If you are compiling with MSVC and will link to the static library
  80846. * (libFLAC.lib) you should define FLAC__NO_DLL in your project to
  80847. * make sure the symbols are exported properly.
  80848. *
  80849. * \{
  80850. */
  80851. #if defined(FLAC__NO_DLL) || !defined(_MSC_VER)
  80852. #define FLAC_API
  80853. #else
  80854. #ifdef FLAC_API_EXPORTS
  80855. #define FLAC_API _declspec(dllexport)
  80856. #else
  80857. #define FLAC_API _declspec(dllimport)
  80858. #endif
  80859. #endif
  80860. /** These #defines will mirror the libtool-based library version number, see
  80861. * http://www.gnu.org/software/libtool/manual.html#Libtool-versioning
  80862. */
  80863. #define FLAC_API_VERSION_CURRENT 10
  80864. #define FLAC_API_VERSION_REVISION 0 /**< see above */
  80865. #define FLAC_API_VERSION_AGE 2 /**< see above */
  80866. #ifdef __cplusplus
  80867. extern "C" {
  80868. #endif
  80869. /** \c 1 if the library has been compiled with support for Ogg FLAC, else \c 0. */
  80870. extern FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC;
  80871. #ifdef __cplusplus
  80872. }
  80873. #endif
  80874. /* \} */
  80875. #endif
  80876. /********* End of inlined file: export.h *********/
  80877. /********* Start of inlined file: assert.h *********/
  80878. #ifndef FLAC__ASSERT_H
  80879. #define FLAC__ASSERT_H
  80880. /* we need this since some compilers (like MSVC) leave assert()s on release code (and we don't want to use their ASSERT) */
  80881. #ifdef DEBUG
  80882. #include <assert.h>
  80883. #define FLAC__ASSERT(x) assert(x)
  80884. #define FLAC__ASSERT_DECLARATION(x) x
  80885. #else
  80886. #define FLAC__ASSERT(x)
  80887. #define FLAC__ASSERT_DECLARATION(x)
  80888. #endif
  80889. #endif
  80890. /********* End of inlined file: assert.h *********/
  80891. /********* Start of inlined file: callback.h *********/
  80892. #ifndef FLAC__CALLBACK_H
  80893. #define FLAC__CALLBACK_H
  80894. /********* Start of inlined file: ordinals.h *********/
  80895. #ifndef FLAC__ORDINALS_H
  80896. #define FLAC__ORDINALS_H
  80897. #if !(defined(_MSC_VER) || defined(__BORLANDC__) || defined(__EMX__))
  80898. #include <inttypes.h>
  80899. #endif
  80900. typedef signed char FLAC__int8;
  80901. typedef unsigned char FLAC__uint8;
  80902. #if defined(_MSC_VER) || defined(__BORLANDC__)
  80903. typedef __int16 FLAC__int16;
  80904. typedef __int32 FLAC__int32;
  80905. typedef __int64 FLAC__int64;
  80906. typedef unsigned __int16 FLAC__uint16;
  80907. typedef unsigned __int32 FLAC__uint32;
  80908. typedef unsigned __int64 FLAC__uint64;
  80909. #elif defined(__EMX__)
  80910. typedef short FLAC__int16;
  80911. typedef long FLAC__int32;
  80912. typedef long long FLAC__int64;
  80913. typedef unsigned short FLAC__uint16;
  80914. typedef unsigned long FLAC__uint32;
  80915. typedef unsigned long long FLAC__uint64;
  80916. #else
  80917. typedef int16_t FLAC__int16;
  80918. typedef int32_t FLAC__int32;
  80919. typedef int64_t FLAC__int64;
  80920. typedef uint16_t FLAC__uint16;
  80921. typedef uint32_t FLAC__uint32;
  80922. typedef uint64_t FLAC__uint64;
  80923. #endif
  80924. typedef int FLAC__bool;
  80925. typedef FLAC__uint8 FLAC__byte;
  80926. #ifdef true
  80927. #undef true
  80928. #endif
  80929. #ifdef false
  80930. #undef false
  80931. #endif
  80932. #ifndef __cplusplus
  80933. #define true 1
  80934. #define false 0
  80935. #endif
  80936. #endif
  80937. /********* End of inlined file: ordinals.h *********/
  80938. #include <stdlib.h> /* for size_t */
  80939. /** \file include/FLAC/callback.h
  80940. *
  80941. * \brief
  80942. * This module defines the structures for describing I/O callbacks
  80943. * to the other FLAC interfaces.
  80944. *
  80945. * See the detailed documentation for callbacks in the
  80946. * \link flac_callbacks callbacks \endlink module.
  80947. */
  80948. /** \defgroup flac_callbacks FLAC/callback.h: I/O callback structures
  80949. * \ingroup flac
  80950. *
  80951. * \brief
  80952. * This module defines the structures for describing I/O callbacks
  80953. * to the other FLAC interfaces.
  80954. *
  80955. * The purpose of the I/O callback functions is to create a common way
  80956. * for the metadata interfaces to handle I/O.
  80957. *
  80958. * Originally the metadata interfaces required filenames as the way of
  80959. * specifying FLAC files to operate on. This is problematic in some
  80960. * environments so there is an additional option to specify a set of
  80961. * callbacks for doing I/O on the FLAC file, instead of the filename.
  80962. *
  80963. * In addition to the callbacks, a FLAC__IOHandle type is defined as an
  80964. * opaque structure for a data source.
  80965. *
  80966. * The callback function prototypes are similar (but not identical) to the
  80967. * stdio functions fread, fwrite, fseek, ftell, feof, and fclose. If you use
  80968. * stdio streams to implement the callbacks, you can pass fread, fwrite, and
  80969. * fclose anywhere a FLAC__IOCallback_Read, FLAC__IOCallback_Write, or
  80970. * FLAC__IOCallback_Close is required, and a FILE* anywhere a FLAC__IOHandle
  80971. * is required. \warning You generally CANNOT directly use fseek or ftell
  80972. * for FLAC__IOCallback_Seek or FLAC__IOCallback_Tell since on most systems
  80973. * these use 32-bit offsets and FLAC requires 64-bit offsets to deal with
  80974. * large files. You will have to find an equivalent function (e.g. ftello),
  80975. * or write a wrapper. The same is true for feof() since this is usually
  80976. * implemented as a macro, not as a function whose address can be taken.
  80977. *
  80978. * \{
  80979. */
  80980. #ifdef __cplusplus
  80981. extern "C" {
  80982. #endif
  80983. /** This is the opaque handle type used by the callbacks. Typically
  80984. * this is a \c FILE* or address of a file descriptor.
  80985. */
  80986. typedef void* FLAC__IOHandle;
  80987. /** Signature for the read callback.
  80988. * The signature and semantics match POSIX fread() implementations
  80989. * and can generally be used interchangeably.
  80990. *
  80991. * \param ptr The address of the read buffer.
  80992. * \param size The size of the records to be read.
  80993. * \param nmemb The number of records to be read.
  80994. * \param handle The handle to the data source.
  80995. * \retval size_t
  80996. * The number of records read.
  80997. */
  80998. typedef size_t (*FLAC__IOCallback_Read) (void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  80999. /** Signature for the write callback.
  81000. * The signature and semantics match POSIX fwrite() implementations
  81001. * and can generally be used interchangeably.
  81002. *
  81003. * \param ptr The address of the write buffer.
  81004. * \param size The size of the records to be written.
  81005. * \param nmemb The number of records to be written.
  81006. * \param handle The handle to the data source.
  81007. * \retval size_t
  81008. * The number of records written.
  81009. */
  81010. typedef size_t (*FLAC__IOCallback_Write) (const void *ptr, size_t size, size_t nmemb, FLAC__IOHandle handle);
  81011. /** Signature for the seek callback.
  81012. * The signature and semantics mostly match POSIX fseek() WITH ONE IMPORTANT
  81013. * EXCEPTION: the offset is a 64-bit type whereas fseek() is generally 'long'
  81014. * and 32-bits wide.
  81015. *
  81016. * \param handle The handle to the data source.
  81017. * \param offset The new position, relative to \a whence
  81018. * \param whence \c SEEK_SET, \c SEEK_CUR, or \c SEEK_END
  81019. * \retval int
  81020. * \c 0 on success, \c -1 on error.
  81021. */
  81022. typedef int (*FLAC__IOCallback_Seek) (FLAC__IOHandle handle, FLAC__int64 offset, int whence);
  81023. /** Signature for the tell callback.
  81024. * The signature and semantics mostly match POSIX ftell() WITH ONE IMPORTANT
  81025. * EXCEPTION: the offset is a 64-bit type whereas ftell() is generally 'long'
  81026. * and 32-bits wide.
  81027. *
  81028. * \param handle The handle to the data source.
  81029. * \retval FLAC__int64
  81030. * The current position on success, \c -1 on error.
  81031. */
  81032. typedef FLAC__int64 (*FLAC__IOCallback_Tell) (FLAC__IOHandle handle);
  81033. /** Signature for the EOF callback.
  81034. * The signature and semantics mostly match POSIX feof() but WATCHOUT:
  81035. * on many systems, feof() is a macro, so in this case a wrapper function
  81036. * must be provided instead.
  81037. *
  81038. * \param handle The handle to the data source.
  81039. * \retval int
  81040. * \c 0 if not at end of file, nonzero if at end of file.
  81041. */
  81042. typedef int (*FLAC__IOCallback_Eof) (FLAC__IOHandle handle);
  81043. /** Signature for the close callback.
  81044. * The signature and semantics match POSIX fclose() implementations
  81045. * and can generally be used interchangeably.
  81046. *
  81047. * \param handle The handle to the data source.
  81048. * \retval int
  81049. * \c 0 on success, \c EOF on error.
  81050. */
  81051. typedef int (*FLAC__IOCallback_Close) (FLAC__IOHandle handle);
  81052. /** A structure for holding a set of callbacks.
  81053. * Each FLAC interface that requires a FLAC__IOCallbacks structure will
  81054. * describe which of the callbacks are required. The ones that are not
  81055. * required may be set to NULL.
  81056. *
  81057. * If the seek requirement for an interface is optional, you can signify that
  81058. * a data sorce is not seekable by setting the \a seek field to \c NULL.
  81059. */
  81060. typedef struct {
  81061. FLAC__IOCallback_Read read;
  81062. FLAC__IOCallback_Write write;
  81063. FLAC__IOCallback_Seek seek;
  81064. FLAC__IOCallback_Tell tell;
  81065. FLAC__IOCallback_Eof eof;
  81066. FLAC__IOCallback_Close close;
  81067. } FLAC__IOCallbacks;
  81068. /* \} */
  81069. #ifdef __cplusplus
  81070. }
  81071. #endif
  81072. #endif
  81073. /********* End of inlined file: callback.h *********/
  81074. /********* Start of inlined file: format.h *********/
  81075. #ifndef FLAC__FORMAT_H
  81076. #define FLAC__FORMAT_H
  81077. #ifdef __cplusplus
  81078. extern "C" {
  81079. #endif
  81080. /** \file include/FLAC/format.h
  81081. *
  81082. * \brief
  81083. * This module contains structure definitions for the representation
  81084. * of FLAC format components in memory. These are the basic
  81085. * structures used by the rest of the interfaces.
  81086. *
  81087. * See the detailed documentation in the
  81088. * \link flac_format format \endlink module.
  81089. */
  81090. /** \defgroup flac_format FLAC/format.h: format components
  81091. * \ingroup flac
  81092. *
  81093. * \brief
  81094. * This module contains structure definitions for the representation
  81095. * of FLAC format components in memory. These are the basic
  81096. * structures used by the rest of the interfaces.
  81097. *
  81098. * First, you should be familiar with the
  81099. * <A HREF="../format.html">FLAC format</A>. Many of the values here
  81100. * follow directly from the specification. As a user of libFLAC, the
  81101. * interesting parts really are the structures that describe the frame
  81102. * header and metadata blocks.
  81103. *
  81104. * The format structures here are very primitive, designed to store
  81105. * information in an efficient way. Reading information from the
  81106. * structures is easy but creating or modifying them directly is
  81107. * more complex. For the most part, as a user of a library, editing
  81108. * is not necessary; however, for metadata blocks it is, so there are
  81109. * convenience functions provided in the \link flac_metadata metadata
  81110. * module \endlink to simplify the manipulation of metadata blocks.
  81111. *
  81112. * \note
  81113. * It's not the best convention, but symbols ending in _LEN are in bits
  81114. * and _LENGTH are in bytes. _LENGTH symbols are \#defines instead of
  81115. * global variables because they are usually used when declaring byte
  81116. * arrays and some compilers require compile-time knowledge of array
  81117. * sizes when declared on the stack.
  81118. *
  81119. * \{
  81120. */
  81121. /*
  81122. Most of the values described in this file are defined by the FLAC
  81123. format specification. There is nothing to tune here.
  81124. */
  81125. /** The largest legal metadata type code. */
  81126. #define FLAC__MAX_METADATA_TYPE_CODE (126u)
  81127. /** The minimum block size, in samples, permitted by the format. */
  81128. #define FLAC__MIN_BLOCK_SIZE (16u)
  81129. /** The maximum block size, in samples, permitted by the format. */
  81130. #define FLAC__MAX_BLOCK_SIZE (65535u)
  81131. /** The maximum block size, in samples, permitted by the FLAC subset for
  81132. * sample rates up to 48kHz. */
  81133. #define FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ (4608u)
  81134. /** The maximum number of channels permitted by the format. */
  81135. #define FLAC__MAX_CHANNELS (8u)
  81136. /** The minimum sample resolution permitted by the format. */
  81137. #define FLAC__MIN_BITS_PER_SAMPLE (4u)
  81138. /** The maximum sample resolution permitted by the format. */
  81139. #define FLAC__MAX_BITS_PER_SAMPLE (32u)
  81140. /** The maximum sample resolution permitted by libFLAC.
  81141. *
  81142. * \warning
  81143. * FLAC__MAX_BITS_PER_SAMPLE is the limit of the FLAC format. However,
  81144. * the reference encoder/decoder is currently limited to 24 bits because
  81145. * of prevalent 32-bit math, so make sure and use this value when
  81146. * appropriate.
  81147. */
  81148. #define FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE (24u)
  81149. /** The maximum sample rate permitted by the format. The value is
  81150. * ((2 ^ 16) - 1) * 10; see <A HREF="../format.html">FLAC format</A>
  81151. * as to why.
  81152. */
  81153. #define FLAC__MAX_SAMPLE_RATE (655350u)
  81154. /** The maximum LPC order permitted by the format. */
  81155. #define FLAC__MAX_LPC_ORDER (32u)
  81156. /** The maximum LPC order permitted by the FLAC subset for sample rates
  81157. * up to 48kHz. */
  81158. #define FLAC__SUBSET_MAX_LPC_ORDER_48000HZ (12u)
  81159. /** The minimum quantized linear predictor coefficient precision
  81160. * permitted by the format.
  81161. */
  81162. #define FLAC__MIN_QLP_COEFF_PRECISION (5u)
  81163. /** The maximum quantized linear predictor coefficient precision
  81164. * permitted by the format.
  81165. */
  81166. #define FLAC__MAX_QLP_COEFF_PRECISION (15u)
  81167. /** The maximum order of the fixed predictors permitted by the format. */
  81168. #define FLAC__MAX_FIXED_ORDER (4u)
  81169. /** The maximum Rice partition order permitted by the format. */
  81170. #define FLAC__MAX_RICE_PARTITION_ORDER (15u)
  81171. /** The maximum Rice partition order permitted by the FLAC Subset. */
  81172. #define FLAC__SUBSET_MAX_RICE_PARTITION_ORDER (8u)
  81173. /** The version string of the release, stamped onto the libraries and binaries.
  81174. *
  81175. * \note
  81176. * This does not correspond to the shared library version number, which
  81177. * is used to determine binary compatibility.
  81178. */
  81179. extern FLAC_API const char *FLAC__VERSION_STRING;
  81180. /** The vendor string inserted by the encoder into the VORBIS_COMMENT block.
  81181. * This is a NUL-terminated ASCII string; when inserted into the
  81182. * VORBIS_COMMENT the trailing null is stripped.
  81183. */
  81184. extern FLAC_API const char *FLAC__VENDOR_STRING;
  81185. /** The byte string representation of the beginning of a FLAC stream. */
  81186. extern FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4]; /* = "fLaC" */
  81187. /** The 32-bit integer big-endian representation of the beginning of
  81188. * a FLAC stream.
  81189. */
  81190. extern FLAC_API const unsigned FLAC__STREAM_SYNC; /* = 0x664C6143 */
  81191. /** The length of the FLAC signature in bits. */
  81192. extern FLAC_API const unsigned FLAC__STREAM_SYNC_LEN; /* = 32 bits */
  81193. /** The length of the FLAC signature in bytes. */
  81194. #define FLAC__STREAM_SYNC_LENGTH (4u)
  81195. /*****************************************************************************
  81196. *
  81197. * Subframe structures
  81198. *
  81199. *****************************************************************************/
  81200. /*****************************************************************************/
  81201. /** An enumeration of the available entropy coding methods. */
  81202. typedef enum {
  81203. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE = 0,
  81204. /**< Residual is coded by partitioning into contexts, each with it's own
  81205. * 4-bit Rice parameter. */
  81206. FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 = 1
  81207. /**< Residual is coded by partitioning into contexts, each with it's own
  81208. * 5-bit Rice parameter. */
  81209. } FLAC__EntropyCodingMethodType;
  81210. /** Maps a FLAC__EntropyCodingMethodType to a C string.
  81211. *
  81212. * Using a FLAC__EntropyCodingMethodType as the index to this array will
  81213. * give the string equivalent. The contents should not be modified.
  81214. */
  81215. extern FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[];
  81216. /** Contents of a Rice partitioned residual
  81217. */
  81218. typedef struct {
  81219. unsigned *parameters;
  81220. /**< The Rice parameters for each context. */
  81221. unsigned *raw_bits;
  81222. /**< Widths for escape-coded partitions. Will be non-zero for escaped
  81223. * partitions and zero for unescaped partitions.
  81224. */
  81225. unsigned capacity_by_order;
  81226. /**< The capacity of the \a parameters and \a raw_bits arrays
  81227. * specified as an order, i.e. the number of array elements
  81228. * allocated is 2 ^ \a capacity_by_order.
  81229. */
  81230. } FLAC__EntropyCodingMethod_PartitionedRiceContents;
  81231. /** Header for a Rice partitioned residual. (c.f. <A HREF="../format.html#partitioned_rice">format specification</A>)
  81232. */
  81233. typedef struct {
  81234. unsigned order;
  81235. /**< The partition order, i.e. # of contexts = 2 ^ \a order. */
  81236. const FLAC__EntropyCodingMethod_PartitionedRiceContents *contents;
  81237. /**< The context's Rice parameters and/or raw bits. */
  81238. } FLAC__EntropyCodingMethod_PartitionedRice;
  81239. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN; /**< == 4 (bits) */
  81240. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN; /**< == 4 (bits) */
  81241. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN; /**< == 5 (bits) */
  81242. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN; /**< == 5 (bits) */
  81243. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  81244. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  81245. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER;
  81246. /**< == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  81247. /** Header for the entropy coding method. (c.f. <A HREF="../format.html#residual">format specification</A>)
  81248. */
  81249. typedef struct {
  81250. FLAC__EntropyCodingMethodType type;
  81251. union {
  81252. FLAC__EntropyCodingMethod_PartitionedRice partitioned_rice;
  81253. } data;
  81254. } FLAC__EntropyCodingMethod;
  81255. extern FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN; /**< == 2 (bits) */
  81256. /*****************************************************************************/
  81257. /** An enumeration of the available subframe types. */
  81258. typedef enum {
  81259. FLAC__SUBFRAME_TYPE_CONSTANT = 0, /**< constant signal */
  81260. FLAC__SUBFRAME_TYPE_VERBATIM = 1, /**< uncompressed signal */
  81261. FLAC__SUBFRAME_TYPE_FIXED = 2, /**< fixed polynomial prediction */
  81262. FLAC__SUBFRAME_TYPE_LPC = 3 /**< linear prediction */
  81263. } FLAC__SubframeType;
  81264. /** Maps a FLAC__SubframeType to a C string.
  81265. *
  81266. * Using a FLAC__SubframeType as the index to this array will
  81267. * give the string equivalent. The contents should not be modified.
  81268. */
  81269. extern FLAC_API const char * const FLAC__SubframeTypeString[];
  81270. /** CONSTANT subframe. (c.f. <A HREF="../format.html#subframe_constant">format specification</A>)
  81271. */
  81272. typedef struct {
  81273. FLAC__int32 value; /**< The constant signal value. */
  81274. } FLAC__Subframe_Constant;
  81275. /** VERBATIM subframe. (c.f. <A HREF="../format.html#subframe_verbatim">format specification</A>)
  81276. */
  81277. typedef struct {
  81278. const FLAC__int32 *data; /**< A pointer to verbatim signal. */
  81279. } FLAC__Subframe_Verbatim;
  81280. /** FIXED subframe. (c.f. <A HREF="../format.html#subframe_fixed">format specification</A>)
  81281. */
  81282. typedef struct {
  81283. FLAC__EntropyCodingMethod entropy_coding_method;
  81284. /**< The residual coding method. */
  81285. unsigned order;
  81286. /**< The polynomial order. */
  81287. FLAC__int32 warmup[FLAC__MAX_FIXED_ORDER];
  81288. /**< Warmup samples to prime the predictor, length == order. */
  81289. const FLAC__int32 *residual;
  81290. /**< The residual signal, length == (blocksize minus order) samples. */
  81291. } FLAC__Subframe_Fixed;
  81292. /** LPC subframe. (c.f. <A HREF="../format.html#subframe_lpc">format specification</A>)
  81293. */
  81294. typedef struct {
  81295. FLAC__EntropyCodingMethod entropy_coding_method;
  81296. /**< The residual coding method. */
  81297. unsigned order;
  81298. /**< The FIR order. */
  81299. unsigned qlp_coeff_precision;
  81300. /**< Quantized FIR filter coefficient precision in bits. */
  81301. int quantization_level;
  81302. /**< The qlp coeff shift needed. */
  81303. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  81304. /**< FIR filter coefficients. */
  81305. FLAC__int32 warmup[FLAC__MAX_LPC_ORDER];
  81306. /**< Warmup samples to prime the predictor, length == order. */
  81307. const FLAC__int32 *residual;
  81308. /**< The residual signal, length == (blocksize minus order) samples. */
  81309. } FLAC__Subframe_LPC;
  81310. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN; /**< == 4 (bits) */
  81311. extern FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN; /**< == 5 (bits) */
  81312. /** FLAC subframe structure. (c.f. <A HREF="../format.html#subframe">format specification</A>)
  81313. */
  81314. typedef struct {
  81315. FLAC__SubframeType type;
  81316. union {
  81317. FLAC__Subframe_Constant constant;
  81318. FLAC__Subframe_Fixed fixed;
  81319. FLAC__Subframe_LPC lpc;
  81320. FLAC__Subframe_Verbatim verbatim;
  81321. } data;
  81322. unsigned wasted_bits;
  81323. } FLAC__Subframe;
  81324. /** == 1 (bit)
  81325. *
  81326. * This used to be a zero-padding bit (hence the name
  81327. * FLAC__SUBFRAME_ZERO_PAD_LEN) but is now a reserved bit. It still has a
  81328. * mandatory value of \c 0 but in the future may take on the value \c 0 or \c 1
  81329. * to mean something else.
  81330. */
  81331. extern FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN;
  81332. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN; /**< == 6 (bits) */
  81333. extern FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN; /**< == 1 (bit) */
  81334. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK; /**< = 0x00 */
  81335. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK; /**< = 0x02 */
  81336. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK; /**< = 0x10 */
  81337. extern FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK; /**< = 0x40 */
  81338. /*****************************************************************************/
  81339. /*****************************************************************************
  81340. *
  81341. * Frame structures
  81342. *
  81343. *****************************************************************************/
  81344. /** An enumeration of the available channel assignments. */
  81345. typedef enum {
  81346. FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT = 0, /**< independent channels */
  81347. FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE = 1, /**< left+side stereo */
  81348. FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE = 2, /**< right+side stereo */
  81349. FLAC__CHANNEL_ASSIGNMENT_MID_SIDE = 3 /**< mid+side stereo */
  81350. } FLAC__ChannelAssignment;
  81351. /** Maps a FLAC__ChannelAssignment to a C string.
  81352. *
  81353. * Using a FLAC__ChannelAssignment as the index to this array will
  81354. * give the string equivalent. The contents should not be modified.
  81355. */
  81356. extern FLAC_API const char * const FLAC__ChannelAssignmentString[];
  81357. /** An enumeration of the possible frame numbering methods. */
  81358. typedef enum {
  81359. FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER, /**< number contains the frame number */
  81360. FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER /**< number contains the sample number of first sample in frame */
  81361. } FLAC__FrameNumberType;
  81362. /** Maps a FLAC__FrameNumberType to a C string.
  81363. *
  81364. * Using a FLAC__FrameNumberType as the index to this array will
  81365. * give the string equivalent. The contents should not be modified.
  81366. */
  81367. extern FLAC_API const char * const FLAC__FrameNumberTypeString[];
  81368. /** FLAC frame header structure. (c.f. <A HREF="../format.html#frame_header">format specification</A>)
  81369. */
  81370. typedef struct {
  81371. unsigned blocksize;
  81372. /**< The number of samples per subframe. */
  81373. unsigned sample_rate;
  81374. /**< The sample rate in Hz. */
  81375. unsigned channels;
  81376. /**< The number of channels (== number of subframes). */
  81377. FLAC__ChannelAssignment channel_assignment;
  81378. /**< The channel assignment for the frame. */
  81379. unsigned bits_per_sample;
  81380. /**< The sample resolution. */
  81381. FLAC__FrameNumberType number_type;
  81382. /**< The numbering scheme used for the frame. As a convenience, the
  81383. * decoder will always convert a frame number to a sample number because
  81384. * the rules are complex. */
  81385. union {
  81386. FLAC__uint32 frame_number;
  81387. FLAC__uint64 sample_number;
  81388. } number;
  81389. /**< The frame number or sample number of first sample in frame;
  81390. * use the \a number_type value to determine which to use. */
  81391. FLAC__uint8 crc;
  81392. /**< CRC-8 (polynomial = x^8 + x^2 + x^1 + x^0, initialized with 0)
  81393. * of the raw frame header bytes, meaning everything before the CRC byte
  81394. * including the sync code.
  81395. */
  81396. } FLAC__FrameHeader;
  81397. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC; /**< == 0x3ffe; the frame header sync code */
  81398. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN; /**< == 14 (bits) */
  81399. extern FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN; /**< == 1 (bits) */
  81400. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN; /**< == 1 (bits) */
  81401. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN; /**< == 4 (bits) */
  81402. extern FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN; /**< == 4 (bits) */
  81403. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN; /**< == 4 (bits) */
  81404. extern FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN; /**< == 3 (bits) */
  81405. extern FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN; /**< == 1 (bit) */
  81406. extern FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN; /**< == 8 (bits) */
  81407. /** FLAC frame footer structure. (c.f. <A HREF="../format.html#frame_footer">format specification</A>)
  81408. */
  81409. typedef struct {
  81410. FLAC__uint16 crc;
  81411. /**< CRC-16 (polynomial = x^16 + x^15 + x^2 + x^0, initialized with
  81412. * 0) of the bytes before the crc, back to and including the frame header
  81413. * sync code.
  81414. */
  81415. } FLAC__FrameFooter;
  81416. extern FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN; /**< == 16 (bits) */
  81417. /** FLAC frame structure. (c.f. <A HREF="../format.html#frame">format specification</A>)
  81418. */
  81419. typedef struct {
  81420. FLAC__FrameHeader header;
  81421. FLAC__Subframe subframes[FLAC__MAX_CHANNELS];
  81422. FLAC__FrameFooter footer;
  81423. } FLAC__Frame;
  81424. /*****************************************************************************/
  81425. /*****************************************************************************
  81426. *
  81427. * Meta-data structures
  81428. *
  81429. *****************************************************************************/
  81430. /** An enumeration of the available metadata block types. */
  81431. typedef enum {
  81432. FLAC__METADATA_TYPE_STREAMINFO = 0,
  81433. /**< <A HREF="../format.html#metadata_block_streaminfo">STREAMINFO</A> block */
  81434. FLAC__METADATA_TYPE_PADDING = 1,
  81435. /**< <A HREF="../format.html#metadata_block_padding">PADDING</A> block */
  81436. FLAC__METADATA_TYPE_APPLICATION = 2,
  81437. /**< <A HREF="../format.html#metadata_block_application">APPLICATION</A> block */
  81438. FLAC__METADATA_TYPE_SEEKTABLE = 3,
  81439. /**< <A HREF="../format.html#metadata_block_seektable">SEEKTABLE</A> block */
  81440. FLAC__METADATA_TYPE_VORBIS_COMMENT = 4,
  81441. /**< <A HREF="../format.html#metadata_block_vorbis_comment">VORBISCOMMENT</A> block (a.k.a. FLAC tags) */
  81442. FLAC__METADATA_TYPE_CUESHEET = 5,
  81443. /**< <A HREF="../format.html#metadata_block_cuesheet">CUESHEET</A> block */
  81444. FLAC__METADATA_TYPE_PICTURE = 6,
  81445. /**< <A HREF="../format.html#metadata_block_picture">PICTURE</A> block */
  81446. FLAC__METADATA_TYPE_UNDEFINED = 7
  81447. /**< marker to denote beginning of undefined type range; this number will increase as new metadata types are added */
  81448. } FLAC__MetadataType;
  81449. /** Maps a FLAC__MetadataType to a C string.
  81450. *
  81451. * Using a FLAC__MetadataType as the index to this array will
  81452. * give the string equivalent. The contents should not be modified.
  81453. */
  81454. extern FLAC_API const char * const FLAC__MetadataTypeString[];
  81455. /** FLAC STREAMINFO structure. (c.f. <A HREF="../format.html#metadata_block_streaminfo">format specification</A>)
  81456. */
  81457. typedef struct {
  81458. unsigned min_blocksize, max_blocksize;
  81459. unsigned min_framesize, max_framesize;
  81460. unsigned sample_rate;
  81461. unsigned channels;
  81462. unsigned bits_per_sample;
  81463. FLAC__uint64 total_samples;
  81464. FLAC__byte md5sum[16];
  81465. } FLAC__StreamMetadata_StreamInfo;
  81466. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  81467. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN; /**< == 16 (bits) */
  81468. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN; /**< == 24 (bits) */
  81469. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN; /**< == 24 (bits) */
  81470. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN; /**< == 20 (bits) */
  81471. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN; /**< == 3 (bits) */
  81472. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN; /**< == 5 (bits) */
  81473. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN; /**< == 36 (bits) */
  81474. extern FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN; /**< == 128 (bits) */
  81475. /** The total stream length of the STREAMINFO block in bytes. */
  81476. #define FLAC__STREAM_METADATA_STREAMINFO_LENGTH (34u)
  81477. /** FLAC PADDING structure. (c.f. <A HREF="../format.html#metadata_block_padding">format specification</A>)
  81478. */
  81479. typedef struct {
  81480. int dummy;
  81481. /**< Conceptually this is an empty struct since we don't store the
  81482. * padding bytes. Empty structs are not allowed by some C compilers,
  81483. * hence the dummy.
  81484. */
  81485. } FLAC__StreamMetadata_Padding;
  81486. /** FLAC APPLICATION structure. (c.f. <A HREF="../format.html#metadata_block_application">format specification</A>)
  81487. */
  81488. typedef struct {
  81489. FLAC__byte id[4];
  81490. FLAC__byte *data;
  81491. } FLAC__StreamMetadata_Application;
  81492. extern FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN; /**< == 32 (bits) */
  81493. /** SeekPoint structure used in SEEKTABLE blocks. (c.f. <A HREF="../format.html#seekpoint">format specification</A>)
  81494. */
  81495. typedef struct {
  81496. FLAC__uint64 sample_number;
  81497. /**< The sample number of the target frame. */
  81498. FLAC__uint64 stream_offset;
  81499. /**< The offset, in bytes, of the target frame with respect to
  81500. * beginning of the first frame. */
  81501. unsigned frame_samples;
  81502. /**< The number of samples in the target frame. */
  81503. } FLAC__StreamMetadata_SeekPoint;
  81504. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN; /**< == 64 (bits) */
  81505. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN; /**< == 64 (bits) */
  81506. extern FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN; /**< == 16 (bits) */
  81507. /** The total stream length of a seek point in bytes. */
  81508. #define FLAC__STREAM_METADATA_SEEKPOINT_LENGTH (18u)
  81509. /** The value used in the \a sample_number field of
  81510. * FLAC__StreamMetadataSeekPoint used to indicate a placeholder
  81511. * point (== 0xffffffffffffffff).
  81512. */
  81513. extern FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  81514. /** FLAC SEEKTABLE structure. (c.f. <A HREF="../format.html#metadata_block_seektable">format specification</A>)
  81515. *
  81516. * \note From the format specification:
  81517. * - The seek points must be sorted by ascending sample number.
  81518. * - Each seek point's sample number must be the first sample of the
  81519. * target frame.
  81520. * - Each seek point's sample number must be unique within the table.
  81521. * - Existence of a SEEKTABLE block implies a correct setting of
  81522. * total_samples in the stream_info block.
  81523. * - Behavior is undefined when more than one SEEKTABLE block is
  81524. * present in a stream.
  81525. */
  81526. typedef struct {
  81527. unsigned num_points;
  81528. FLAC__StreamMetadata_SeekPoint *points;
  81529. } FLAC__StreamMetadata_SeekTable;
  81530. /** Vorbis comment entry structure used in VORBIS_COMMENT blocks. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  81531. *
  81532. * For convenience, the APIs maintain a trailing NUL character at the end of
  81533. * \a entry which is not counted toward \a length, i.e.
  81534. * \code strlen(entry) == length \endcode
  81535. */
  81536. typedef struct {
  81537. FLAC__uint32 length;
  81538. FLAC__byte *entry;
  81539. } FLAC__StreamMetadata_VorbisComment_Entry;
  81540. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN; /**< == 32 (bits) */
  81541. /** FLAC VORBIS_COMMENT structure. (c.f. <A HREF="../format.html#metadata_block_vorbis_comment">format specification</A>)
  81542. */
  81543. typedef struct {
  81544. FLAC__StreamMetadata_VorbisComment_Entry vendor_string;
  81545. FLAC__uint32 num_comments;
  81546. FLAC__StreamMetadata_VorbisComment_Entry *comments;
  81547. } FLAC__StreamMetadata_VorbisComment;
  81548. extern FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN; /**< == 32 (bits) */
  81549. /** FLAC CUESHEET track index structure. (See the
  81550. * <A HREF="../format.html#cuesheet_track_index">format specification</A> for
  81551. * the full description of each field.)
  81552. */
  81553. typedef struct {
  81554. FLAC__uint64 offset;
  81555. /**< Offset in samples, relative to the track offset, of the index
  81556. * point.
  81557. */
  81558. FLAC__byte number;
  81559. /**< The index point number. */
  81560. } FLAC__StreamMetadata_CueSheet_Index;
  81561. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN; /**< == 64 (bits) */
  81562. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN; /**< == 8 (bits) */
  81563. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN; /**< == 3*8 (bits) */
  81564. /** FLAC CUESHEET track structure. (See the
  81565. * <A HREF="../format.html#cuesheet_track">format specification</A> for
  81566. * the full description of each field.)
  81567. */
  81568. typedef struct {
  81569. FLAC__uint64 offset;
  81570. /**< Track offset in samples, relative to the beginning of the FLAC audio stream. */
  81571. FLAC__byte number;
  81572. /**< The track number. */
  81573. char isrc[13];
  81574. /**< Track ISRC. This is a 12-digit alphanumeric code plus a trailing \c NUL byte */
  81575. unsigned type:1;
  81576. /**< The track type: 0 for audio, 1 for non-audio. */
  81577. unsigned pre_emphasis:1;
  81578. /**< The pre-emphasis flag: 0 for no pre-emphasis, 1 for pre-emphasis. */
  81579. FLAC__byte num_indices;
  81580. /**< The number of track index points. */
  81581. FLAC__StreamMetadata_CueSheet_Index *indices;
  81582. /**< NULL if num_indices == 0, else pointer to array of index points. */
  81583. } FLAC__StreamMetadata_CueSheet_Track;
  81584. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN; /**< == 64 (bits) */
  81585. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN; /**< == 8 (bits) */
  81586. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN; /**< == 12*8 (bits) */
  81587. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN; /**< == 1 (bit) */
  81588. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN; /**< == 1 (bit) */
  81589. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN; /**< == 6+13*8 (bits) */
  81590. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN; /**< == 8 (bits) */
  81591. /** FLAC CUESHEET structure. (See the
  81592. * <A HREF="../format.html#metadata_block_cuesheet">format specification</A>
  81593. * for the full description of each field.)
  81594. */
  81595. typedef struct {
  81596. char media_catalog_number[129];
  81597. /**< Media catalog number, in ASCII printable characters 0x20-0x7e. In
  81598. * general, the media catalog number may be 0 to 128 bytes long; any
  81599. * unused characters should be right-padded with NUL characters.
  81600. */
  81601. FLAC__uint64 lead_in;
  81602. /**< The number of lead-in samples. */
  81603. FLAC__bool is_cd;
  81604. /**< \c true if CUESHEET corresponds to a Compact Disc, else \c false. */
  81605. unsigned num_tracks;
  81606. /**< The number of tracks. */
  81607. FLAC__StreamMetadata_CueSheet_Track *tracks;
  81608. /**< NULL if num_tracks == 0, else pointer to array of tracks. */
  81609. } FLAC__StreamMetadata_CueSheet;
  81610. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN; /**< == 128*8 (bits) */
  81611. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN; /**< == 64 (bits) */
  81612. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN; /**< == 1 (bit) */
  81613. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN; /**< == 7+258*8 (bits) */
  81614. extern FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN; /**< == 8 (bits) */
  81615. /** An enumeration of the PICTURE types (see FLAC__StreamMetadataPicture and id3 v2.4 APIC tag). */
  81616. typedef enum {
  81617. FLAC__STREAM_METADATA_PICTURE_TYPE_OTHER = 0, /**< Other */
  81618. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD = 1, /**< 32x32 pixels 'file icon' (PNG only) */
  81619. FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON = 2, /**< Other file icon */
  81620. FLAC__STREAM_METADATA_PICTURE_TYPE_FRONT_COVER = 3, /**< Cover (front) */
  81621. FLAC__STREAM_METADATA_PICTURE_TYPE_BACK_COVER = 4, /**< Cover (back) */
  81622. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAFLET_PAGE = 5, /**< Leaflet page */
  81623. FLAC__STREAM_METADATA_PICTURE_TYPE_MEDIA = 6, /**< Media (e.g. label side of CD) */
  81624. FLAC__STREAM_METADATA_PICTURE_TYPE_LEAD_ARTIST = 7, /**< Lead artist/lead performer/soloist */
  81625. FLAC__STREAM_METADATA_PICTURE_TYPE_ARTIST = 8, /**< Artist/performer */
  81626. FLAC__STREAM_METADATA_PICTURE_TYPE_CONDUCTOR = 9, /**< Conductor */
  81627. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND = 10, /**< Band/Orchestra */
  81628. FLAC__STREAM_METADATA_PICTURE_TYPE_COMPOSER = 11, /**< Composer */
  81629. FLAC__STREAM_METADATA_PICTURE_TYPE_LYRICIST = 12, /**< Lyricist/text writer */
  81630. FLAC__STREAM_METADATA_PICTURE_TYPE_RECORDING_LOCATION = 13, /**< Recording Location */
  81631. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_RECORDING = 14, /**< During recording */
  81632. FLAC__STREAM_METADATA_PICTURE_TYPE_DURING_PERFORMANCE = 15, /**< During performance */
  81633. FLAC__STREAM_METADATA_PICTURE_TYPE_VIDEO_SCREEN_CAPTURE = 16, /**< Movie/video screen capture */
  81634. FLAC__STREAM_METADATA_PICTURE_TYPE_FISH = 17, /**< A bright coloured fish */
  81635. FLAC__STREAM_METADATA_PICTURE_TYPE_ILLUSTRATION = 18, /**< Illustration */
  81636. FLAC__STREAM_METADATA_PICTURE_TYPE_BAND_LOGOTYPE = 19, /**< Band/artist logotype */
  81637. FLAC__STREAM_METADATA_PICTURE_TYPE_PUBLISHER_LOGOTYPE = 20, /**< Publisher/Studio logotype */
  81638. FLAC__STREAM_METADATA_PICTURE_TYPE_UNDEFINED
  81639. } FLAC__StreamMetadata_Picture_Type;
  81640. /** Maps a FLAC__StreamMetadata_Picture_Type to a C string.
  81641. *
  81642. * Using a FLAC__StreamMetadata_Picture_Type as the index to this array
  81643. * will give the string equivalent. The contents should not be
  81644. * modified.
  81645. */
  81646. extern FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[];
  81647. /** FLAC PICTURE structure. (See the
  81648. * <A HREF="../format.html#metadata_block_picture">format specification</A>
  81649. * for the full description of each field.)
  81650. */
  81651. typedef struct {
  81652. FLAC__StreamMetadata_Picture_Type type;
  81653. /**< The kind of picture stored. */
  81654. char *mime_type;
  81655. /**< Picture data's MIME type, in ASCII printable characters
  81656. * 0x20-0x7e, NUL terminated. For best compatibility with players,
  81657. * use picture data of MIME type \c image/jpeg or \c image/png. A
  81658. * MIME type of '-->' is also allowed, in which case the picture
  81659. * data should be a complete URL. In file storage, the MIME type is
  81660. * stored as a 32-bit length followed by the ASCII string with no NUL
  81661. * terminator, but is converted to a plain C string in this structure
  81662. * for convenience.
  81663. */
  81664. FLAC__byte *description;
  81665. /**< Picture's description in UTF-8, NUL terminated. In file storage,
  81666. * the description is stored as a 32-bit length followed by the UTF-8
  81667. * string with no NUL terminator, but is converted to a plain C string
  81668. * in this structure for convenience.
  81669. */
  81670. FLAC__uint32 width;
  81671. /**< Picture's width in pixels. */
  81672. FLAC__uint32 height;
  81673. /**< Picture's height in pixels. */
  81674. FLAC__uint32 depth;
  81675. /**< Picture's color depth in bits-per-pixel. */
  81676. FLAC__uint32 colors;
  81677. /**< For indexed palettes (like GIF), picture's number of colors (the
  81678. * number of palette entries), or \c 0 for non-indexed (i.e. 2^depth).
  81679. */
  81680. FLAC__uint32 data_length;
  81681. /**< Length of binary picture data in bytes. */
  81682. FLAC__byte *data;
  81683. /**< Binary picture data. */
  81684. } FLAC__StreamMetadata_Picture;
  81685. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN; /**< == 32 (bits) */
  81686. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN; /**< == 32 (bits) */
  81687. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN; /**< == 32 (bits) */
  81688. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN; /**< == 32 (bits) */
  81689. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN; /**< == 32 (bits) */
  81690. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN; /**< == 32 (bits) */
  81691. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN; /**< == 32 (bits) */
  81692. extern FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN; /**< == 32 (bits) */
  81693. /** Structure that is used when a metadata block of unknown type is loaded.
  81694. * The contents are opaque. The structure is used only internally to
  81695. * correctly handle unknown metadata.
  81696. */
  81697. typedef struct {
  81698. FLAC__byte *data;
  81699. } FLAC__StreamMetadata_Unknown;
  81700. /** FLAC metadata block structure. (c.f. <A HREF="../format.html#metadata_block">format specification</A>)
  81701. */
  81702. typedef struct {
  81703. FLAC__MetadataType type;
  81704. /**< The type of the metadata block; used determine which member of the
  81705. * \a data union to dereference. If type >= FLAC__METADATA_TYPE_UNDEFINED
  81706. * then \a data.unknown must be used. */
  81707. FLAC__bool is_last;
  81708. /**< \c true if this metadata block is the last, else \a false */
  81709. unsigned length;
  81710. /**< Length, in bytes, of the block data as it appears in the stream. */
  81711. union {
  81712. FLAC__StreamMetadata_StreamInfo stream_info;
  81713. FLAC__StreamMetadata_Padding padding;
  81714. FLAC__StreamMetadata_Application application;
  81715. FLAC__StreamMetadata_SeekTable seek_table;
  81716. FLAC__StreamMetadata_VorbisComment vorbis_comment;
  81717. FLAC__StreamMetadata_CueSheet cue_sheet;
  81718. FLAC__StreamMetadata_Picture picture;
  81719. FLAC__StreamMetadata_Unknown unknown;
  81720. } data;
  81721. /**< Polymorphic block data; use the \a type value to determine which
  81722. * to use. */
  81723. } FLAC__StreamMetadata;
  81724. extern FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN; /**< == 1 (bit) */
  81725. extern FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN; /**< == 7 (bits) */
  81726. extern FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN; /**< == 24 (bits) */
  81727. /** The total stream length of a metadata block header in bytes. */
  81728. #define FLAC__STREAM_METADATA_HEADER_LENGTH (4u)
  81729. /*****************************************************************************/
  81730. /*****************************************************************************
  81731. *
  81732. * Utility functions
  81733. *
  81734. *****************************************************************************/
  81735. /** Tests that a sample rate is valid for FLAC.
  81736. *
  81737. * \param sample_rate The sample rate to test for compliance.
  81738. * \retval FLAC__bool
  81739. * \c true if the given sample rate conforms to the specification, else
  81740. * \c false.
  81741. */
  81742. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate);
  81743. /** Tests that a sample rate is valid for the FLAC subset. The subset rules
  81744. * for valid sample rates are slightly more complex since the rate has to
  81745. * be expressible completely in the frame header.
  81746. *
  81747. * \param sample_rate The sample rate to test for compliance.
  81748. * \retval FLAC__bool
  81749. * \c true if the given sample rate conforms to the specification for the
  81750. * subset, else \c false.
  81751. */
  81752. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate);
  81753. /** Check a Vorbis comment entry name to see if it conforms to the Vorbis
  81754. * comment specification.
  81755. *
  81756. * Vorbis comment names must be composed only of characters from
  81757. * [0x20-0x3C,0x3E-0x7D].
  81758. *
  81759. * \param name A NUL-terminated string to be checked.
  81760. * \assert
  81761. * \code name != NULL \endcode
  81762. * \retval FLAC__bool
  81763. * \c false if entry name is illegal, else \c true.
  81764. */
  81765. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name);
  81766. /** Check a Vorbis comment entry value to see if it conforms to the Vorbis
  81767. * comment specification.
  81768. *
  81769. * Vorbis comment values must be valid UTF-8 sequences.
  81770. *
  81771. * \param value A string to be checked.
  81772. * \param length A the length of \a value in bytes. May be
  81773. * \c (unsigned)(-1) to indicate that \a value is a plain
  81774. * UTF-8 NUL-terminated string.
  81775. * \assert
  81776. * \code value != NULL \endcode
  81777. * \retval FLAC__bool
  81778. * \c false if entry name is illegal, else \c true.
  81779. */
  81780. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length);
  81781. /** Check a Vorbis comment entry to see if it conforms to the Vorbis
  81782. * comment specification.
  81783. *
  81784. * Vorbis comment entries must be of the form 'name=value', and 'name' and
  81785. * 'value' must be legal according to
  81786. * FLAC__format_vorbiscomment_entry_name_is_legal() and
  81787. * FLAC__format_vorbiscomment_entry_value_is_legal() respectively.
  81788. *
  81789. * \param entry An entry to be checked.
  81790. * \param length The length of \a entry in bytes.
  81791. * \assert
  81792. * \code value != NULL \endcode
  81793. * \retval FLAC__bool
  81794. * \c false if entry name is illegal, else \c true.
  81795. */
  81796. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length);
  81797. /** Check a seek table to see if it conforms to the FLAC specification.
  81798. * See the format specification for limits on the contents of the
  81799. * seek table.
  81800. *
  81801. * \param seek_table A pointer to a seek table to be checked.
  81802. * \assert
  81803. * \code seek_table != NULL \endcode
  81804. * \retval FLAC__bool
  81805. * \c false if seek table is illegal, else \c true.
  81806. */
  81807. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table);
  81808. /** Sort a seek table's seek points according to the format specification.
  81809. * This includes a "unique-ification" step to remove duplicates, i.e.
  81810. * seek points with identical \a sample_number values. Duplicate seek
  81811. * points are converted into placeholder points and sorted to the end of
  81812. * the table.
  81813. *
  81814. * \param seek_table A pointer to a seek table to be sorted.
  81815. * \assert
  81816. * \code seek_table != NULL \endcode
  81817. * \retval unsigned
  81818. * The number of duplicate seek points converted into placeholders.
  81819. */
  81820. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table);
  81821. /** Check a cue sheet to see if it conforms to the FLAC specification.
  81822. * See the format specification for limits on the contents of the
  81823. * cue sheet.
  81824. *
  81825. * \param cue_sheet A pointer to an existing cue sheet to be checked.
  81826. * \param check_cd_da_subset If \c true, check CUESHEET against more
  81827. * stringent requirements for a CD-DA (audio) disc.
  81828. * \param violation Address of a pointer to a string. If there is a
  81829. * violation, a pointer to a string explanation of the
  81830. * violation will be returned here. \a violation may be
  81831. * \c NULL if you don't need the returned string. Do not
  81832. * free the returned string; it will always point to static
  81833. * data.
  81834. * \assert
  81835. * \code cue_sheet != NULL \endcode
  81836. * \retval FLAC__bool
  81837. * \c false if cue sheet is illegal, else \c true.
  81838. */
  81839. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation);
  81840. /** Check picture data to see if it conforms to the FLAC specification.
  81841. * See the format specification for limits on the contents of the
  81842. * PICTURE block.
  81843. *
  81844. * \param picture A pointer to existing picture data to be checked.
  81845. * \param violation Address of a pointer to a string. If there is a
  81846. * violation, a pointer to a string explanation of the
  81847. * violation will be returned here. \a violation may be
  81848. * \c NULL if you don't need the returned string. Do not
  81849. * free the returned string; it will always point to static
  81850. * data.
  81851. * \assert
  81852. * \code picture != NULL \endcode
  81853. * \retval FLAC__bool
  81854. * \c false if picture data is illegal, else \c true.
  81855. */
  81856. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation);
  81857. /* \} */
  81858. #ifdef __cplusplus
  81859. }
  81860. #endif
  81861. #endif
  81862. /********* End of inlined file: format.h *********/
  81863. /********* Start of inlined file: metadata.h *********/
  81864. #ifndef FLAC__METADATA_H
  81865. #define FLAC__METADATA_H
  81866. #include <sys/types.h> /* for off_t */
  81867. /* --------------------------------------------------------------------
  81868. (For an example of how all these routines are used, see the source
  81869. code for the unit tests in src/test_libFLAC/metadata_*.c, or
  81870. metaflac in src/metaflac/)
  81871. ------------------------------------------------------------------*/
  81872. /** \file include/FLAC/metadata.h
  81873. *
  81874. * \brief
  81875. * This module provides functions for creating and manipulating FLAC
  81876. * metadata blocks in memory, and three progressively more powerful
  81877. * interfaces for traversing and editing metadata in FLAC files.
  81878. *
  81879. * See the detailed documentation for each interface in the
  81880. * \link flac_metadata metadata \endlink module.
  81881. */
  81882. /** \defgroup flac_metadata FLAC/metadata.h: metadata interfaces
  81883. * \ingroup flac
  81884. *
  81885. * \brief
  81886. * This module provides functions for creating and manipulating FLAC
  81887. * metadata blocks in memory, and three progressively more powerful
  81888. * interfaces for traversing and editing metadata in native FLAC files.
  81889. * Note that currently only the Chain interface (level 2) supports Ogg
  81890. * FLAC files, and it is read-only i.e. no writing back changed
  81891. * metadata to file.
  81892. *
  81893. * There are three metadata interfaces of increasing complexity:
  81894. *
  81895. * Level 0:
  81896. * Read-only access to the STREAMINFO, VORBIS_COMMENT, CUESHEET, and
  81897. * PICTURE blocks.
  81898. *
  81899. * Level 1:
  81900. * Read-write access to all metadata blocks. This level is write-
  81901. * efficient in most cases (more on this below), and uses less memory
  81902. * than level 2.
  81903. *
  81904. * Level 2:
  81905. * Read-write access to all metadata blocks. This level is write-
  81906. * efficient in all cases, but uses more memory since all metadata for
  81907. * the whole file is read into memory and manipulated before writing
  81908. * out again.
  81909. *
  81910. * What do we mean by efficient? Since FLAC metadata appears at the
  81911. * beginning of the file, when writing metadata back to a FLAC file
  81912. * it is possible to grow or shrink the metadata such that the entire
  81913. * file must be rewritten. However, if the size remains the same during
  81914. * changes or PADDING blocks are utilized, only the metadata needs to be
  81915. * overwritten, which is much faster.
  81916. *
  81917. * Efficient means the whole file is rewritten at most one time, and only
  81918. * when necessary. Level 1 is not efficient only in the case that you
  81919. * cause more than one metadata block to grow or shrink beyond what can
  81920. * be accomodated by padding. In this case you should probably use level
  81921. * 2, which allows you to edit all the metadata for a file in memory and
  81922. * write it out all at once.
  81923. *
  81924. * All levels know how to skip over and not disturb an ID3v2 tag at the
  81925. * front of the file.
  81926. *
  81927. * All levels access files via their filenames. In addition, level 2
  81928. * has additional alternative read and write functions that take an I/O
  81929. * handle and callbacks, for situations where access by filename is not
  81930. * possible.
  81931. *
  81932. * In addition to the three interfaces, this module defines functions for
  81933. * creating and manipulating various metadata objects in memory. As we see
  81934. * from the Format module, FLAC metadata blocks in memory are very primitive
  81935. * structures for storing information in an efficient way. Reading
  81936. * information from the structures is easy but creating or modifying them
  81937. * directly is more complex. The metadata object routines here facilitate
  81938. * this by taking care of the consistency and memory management drudgery.
  81939. *
  81940. * Unless you will be using the level 1 or 2 interfaces to modify existing
  81941. * metadata however, you will not probably not need these.
  81942. *
  81943. * From a dependency standpoint, none of the encoders or decoders require
  81944. * the metadata module. This is so that embedded users can strip out the
  81945. * metadata module from libFLAC to reduce the size and complexity.
  81946. */
  81947. #ifdef __cplusplus
  81948. extern "C" {
  81949. #endif
  81950. /** \defgroup flac_metadata_level0 FLAC/metadata.h: metadata level 0 interface
  81951. * \ingroup flac_metadata
  81952. *
  81953. * \brief
  81954. * The level 0 interface consists of individual routines to read the
  81955. * STREAMINFO, VORBIS_COMMENT, CUESHEET, and PICTURE blocks, requiring
  81956. * only a filename.
  81957. *
  81958. * They try to skip any ID3v2 tag at the head of the file.
  81959. *
  81960. * \{
  81961. */
  81962. /** Read the STREAMINFO metadata block of the given FLAC file. This function
  81963. * will try to skip any ID3v2 tag at the head of the file.
  81964. *
  81965. * \param filename The path to the FLAC file to read.
  81966. * \param streaminfo A pointer to space for the STREAMINFO block. Since
  81967. * FLAC__StreamMetadata is a simple structure with no
  81968. * memory allocation involved, you pass the address of
  81969. * an existing structure. It need not be initialized.
  81970. * \assert
  81971. * \code filename != NULL \endcode
  81972. * \code streaminfo != NULL \endcode
  81973. * \retval FLAC__bool
  81974. * \c true if a valid STREAMINFO block was read from \a filename. Returns
  81975. * \c false if there was a memory allocation error, a file decoder error,
  81976. * or the file contained no STREAMINFO block. (A memory allocation error
  81977. * is possible because this function must set up a file decoder.)
  81978. */
  81979. FLAC_API FLAC__bool FLAC__metadata_get_streaminfo(const char *filename, FLAC__StreamMetadata *streaminfo);
  81980. /** Read the VORBIS_COMMENT metadata block of the given FLAC file. This
  81981. * function will try to skip any ID3v2 tag at the head of the file.
  81982. *
  81983. * \param filename The path to the FLAC file to read.
  81984. * \param tags The address where the returned pointer will be
  81985. * stored. The \a tags object must be deleted by
  81986. * the caller using FLAC__metadata_object_delete().
  81987. * \assert
  81988. * \code filename != NULL \endcode
  81989. * \code tags != NULL \endcode
  81990. * \retval FLAC__bool
  81991. * \c true if a valid VORBIS_COMMENT block was read from \a filename,
  81992. * and \a *tags will be set to the address of the metadata structure.
  81993. * Returns \c false if there was a memory allocation error, a file
  81994. * decoder error, or the file contained no VORBIS_COMMENT block, and
  81995. * \a *tags will be set to \c NULL.
  81996. */
  81997. FLAC_API FLAC__bool FLAC__metadata_get_tags(const char *filename, FLAC__StreamMetadata **tags);
  81998. /** Read the CUESHEET metadata block of the given FLAC file. This
  81999. * function will try to skip any ID3v2 tag at the head of the file.
  82000. *
  82001. * \param filename The path to the FLAC file to read.
  82002. * \param cuesheet The address where the returned pointer will be
  82003. * stored. The \a cuesheet object must be deleted by
  82004. * the caller using FLAC__metadata_object_delete().
  82005. * \assert
  82006. * \code filename != NULL \endcode
  82007. * \code cuesheet != NULL \endcode
  82008. * \retval FLAC__bool
  82009. * \c true if a valid CUESHEET block was read from \a filename,
  82010. * and \a *cuesheet will be set to the address of the metadata
  82011. * structure. Returns \c false if there was a memory allocation
  82012. * error, a file decoder error, or the file contained no CUESHEET
  82013. * block, and \a *cuesheet will be set to \c NULL.
  82014. */
  82015. FLAC_API FLAC__bool FLAC__metadata_get_cuesheet(const char *filename, FLAC__StreamMetadata **cuesheet);
  82016. /** Read a PICTURE metadata block of the given FLAC file. This
  82017. * function will try to skip any ID3v2 tag at the head of the file.
  82018. * Since there can be more than one PICTURE block in a file, this
  82019. * function takes a number of parameters that act as constraints to
  82020. * the search. The PICTURE block with the largest area matching all
  82021. * the constraints will be returned, or \a *picture will be set to
  82022. * \c NULL if there was no such block.
  82023. *
  82024. * \param filename The path to the FLAC file to read.
  82025. * \param picture The address where the returned pointer will be
  82026. * stored. The \a picture object must be deleted by
  82027. * the caller using FLAC__metadata_object_delete().
  82028. * \param type The desired picture type. Use \c -1 to mean
  82029. * "any type".
  82030. * \param mime_type The desired MIME type, e.g. "image/jpeg". The
  82031. * string will be matched exactly. Use \c NULL to
  82032. * mean "any MIME type".
  82033. * \param description The desired description. The string will be
  82034. * matched exactly. Use \c NULL to mean "any
  82035. * description".
  82036. * \param max_width The maximum width in pixels desired. Use
  82037. * \c (unsigned)(-1) to mean "any width".
  82038. * \param max_height The maximum height in pixels desired. Use
  82039. * \c (unsigned)(-1) to mean "any height".
  82040. * \param max_depth The maximum color depth in bits-per-pixel desired.
  82041. * Use \c (unsigned)(-1) to mean "any depth".
  82042. * \param max_colors The maximum number of colors desired. Use
  82043. * \c (unsigned)(-1) to mean "any number of colors".
  82044. * \assert
  82045. * \code filename != NULL \endcode
  82046. * \code picture != NULL \endcode
  82047. * \retval FLAC__bool
  82048. * \c true if a valid PICTURE block was read from \a filename,
  82049. * and \a *picture will be set to the address of the metadata
  82050. * structure. Returns \c false if there was a memory allocation
  82051. * error, a file decoder error, or the file contained no PICTURE
  82052. * block, and \a *picture will be set to \c NULL.
  82053. */
  82054. 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);
  82055. /* \} */
  82056. /** \defgroup flac_metadata_level1 FLAC/metadata.h: metadata level 1 interface
  82057. * \ingroup flac_metadata
  82058. *
  82059. * \brief
  82060. * The level 1 interface provides read-write access to FLAC file metadata and
  82061. * operates directly on the FLAC file.
  82062. *
  82063. * The general usage of this interface is:
  82064. *
  82065. * - Create an iterator using FLAC__metadata_simple_iterator_new()
  82066. * - Attach it to a file using FLAC__metadata_simple_iterator_init() and check
  82067. * the exit code. Call FLAC__metadata_simple_iterator_is_writable() to
  82068. * see if the file is writable, or only read access is allowed.
  82069. * - Use FLAC__metadata_simple_iterator_next() and
  82070. * FLAC__metadata_simple_iterator_prev() to traverse the blocks.
  82071. * This is does not read the actual blocks themselves.
  82072. * FLAC__metadata_simple_iterator_next() is relatively fast.
  82073. * FLAC__metadata_simple_iterator_prev() is slower since it needs to search
  82074. * forward from the front of the file.
  82075. * - Use FLAC__metadata_simple_iterator_get_block_type() or
  82076. * FLAC__metadata_simple_iterator_get_block() to access the actual data at
  82077. * the current iterator position. The returned object is yours to modify
  82078. * and free.
  82079. * - Use FLAC__metadata_simple_iterator_set_block() to write a modified block
  82080. * back. You must have write permission to the original file. Make sure to
  82081. * read the whole comment to FLAC__metadata_simple_iterator_set_block()
  82082. * below.
  82083. * - Use FLAC__metadata_simple_iterator_insert_block_after() to add new blocks.
  82084. * Use the object creation functions from
  82085. * \link flac_metadata_object here \endlink to generate new objects.
  82086. * - Use FLAC__metadata_simple_iterator_delete_block() to remove the block
  82087. * currently referred to by the iterator, or replace it with padding.
  82088. * - Destroy the iterator with FLAC__metadata_simple_iterator_delete() when
  82089. * finished.
  82090. *
  82091. * \note
  82092. * The FLAC file remains open the whole time between
  82093. * FLAC__metadata_simple_iterator_init() and
  82094. * FLAC__metadata_simple_iterator_delete(), so make sure you are not altering
  82095. * the file during this time.
  82096. *
  82097. * \note
  82098. * Do not modify the \a is_last, \a length, or \a type fields of returned
  82099. * FLAC__StreamMetadata objects. These are managed automatically.
  82100. *
  82101. * \note
  82102. * If any of the modification functions
  82103. * (FLAC__metadata_simple_iterator_set_block(),
  82104. * FLAC__metadata_simple_iterator_delete_block(),
  82105. * FLAC__metadata_simple_iterator_insert_block_after(), etc.) return \c false,
  82106. * you should delete the iterator as it may no longer be valid.
  82107. *
  82108. * \{
  82109. */
  82110. struct FLAC__Metadata_SimpleIterator;
  82111. /** The opaque structure definition for the level 1 iterator type.
  82112. * See the
  82113. * \link flac_metadata_level1 metadata level 1 module \endlink
  82114. * for a detailed description.
  82115. */
  82116. typedef struct FLAC__Metadata_SimpleIterator FLAC__Metadata_SimpleIterator;
  82117. /** Status type for FLAC__Metadata_SimpleIterator.
  82118. *
  82119. * The iterator's current status can be obtained by calling FLAC__metadata_simple_iterator_status().
  82120. */
  82121. typedef enum {
  82122. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK = 0,
  82123. /**< The iterator is in the normal OK state */
  82124. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT,
  82125. /**< The data passed into a function violated the function's usage criteria */
  82126. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ERROR_OPENING_FILE,
  82127. /**< The iterator could not open the target file */
  82128. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_A_FLAC_FILE,
  82129. /**< The iterator could not find the FLAC signature at the start of the file */
  82130. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_NOT_WRITABLE,
  82131. /**< The iterator tried to write to a file that was not writable */
  82132. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_BAD_METADATA,
  82133. /**< The iterator encountered input that does not conform to the FLAC metadata specification */
  82134. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR,
  82135. /**< The iterator encountered an error while reading the FLAC file */
  82136. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR,
  82137. /**< The iterator encountered an error while seeking in the FLAC file */
  82138. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_WRITE_ERROR,
  82139. /**< The iterator encountered an error while writing the FLAC file */
  82140. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_RENAME_ERROR,
  82141. /**< The iterator encountered an error renaming the FLAC file */
  82142. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_UNLINK_ERROR,
  82143. /**< The iterator encountered an error removing the temporary file */
  82144. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_MEMORY_ALLOCATION_ERROR,
  82145. /**< Memory allocation failed */
  82146. FLAC__METADATA_SIMPLE_ITERATOR_STATUS_INTERNAL_ERROR
  82147. /**< The caller violated an assertion or an unexpected error occurred */
  82148. } FLAC__Metadata_SimpleIteratorStatus;
  82149. /** Maps a FLAC__Metadata_SimpleIteratorStatus to a C string.
  82150. *
  82151. * Using a FLAC__Metadata_SimpleIteratorStatus as the index to this array
  82152. * will give the string equivalent. The contents should not be modified.
  82153. */
  82154. extern FLAC_API const char * const FLAC__Metadata_SimpleIteratorStatusString[];
  82155. /** Create a new iterator instance.
  82156. *
  82157. * \retval FLAC__Metadata_SimpleIterator*
  82158. * \c NULL if there was an error allocating memory, else the new instance.
  82159. */
  82160. FLAC_API FLAC__Metadata_SimpleIterator *FLAC__metadata_simple_iterator_new(void);
  82161. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  82162. *
  82163. * \param iterator A pointer to an existing iterator.
  82164. * \assert
  82165. * \code iterator != NULL \endcode
  82166. */
  82167. FLAC_API void FLAC__metadata_simple_iterator_delete(FLAC__Metadata_SimpleIterator *iterator);
  82168. /** Get the current status of the iterator. Call this after a function
  82169. * returns \c false to get the reason for the error. Also resets the status
  82170. * to FLAC__METADATA_SIMPLE_ITERATOR_STATUS_OK.
  82171. *
  82172. * \param iterator A pointer to an existing iterator.
  82173. * \assert
  82174. * \code iterator != NULL \endcode
  82175. * \retval FLAC__Metadata_SimpleIteratorStatus
  82176. * The current status of the iterator.
  82177. */
  82178. FLAC_API FLAC__Metadata_SimpleIteratorStatus FLAC__metadata_simple_iterator_status(FLAC__Metadata_SimpleIterator *iterator);
  82179. /** Initialize the iterator to point to the first metadata block in the
  82180. * given FLAC file.
  82181. *
  82182. * \param iterator A pointer to an existing iterator.
  82183. * \param filename The path to the FLAC file.
  82184. * \param read_only If \c true, the FLAC file will be opened
  82185. * in read-only mode; if \c false, the FLAC
  82186. * file will be opened for edit even if no
  82187. * edits are performed.
  82188. * \param preserve_file_stats If \c true, the owner and modification
  82189. * time will be preserved even if the FLAC
  82190. * file is written to.
  82191. * \assert
  82192. * \code iterator != NULL \endcode
  82193. * \code filename != NULL \endcode
  82194. * \retval FLAC__bool
  82195. * \c false if a memory allocation error occurs, the file can't be
  82196. * opened, or another error occurs, else \c true.
  82197. */
  82198. 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);
  82199. /** Returns \c true if the FLAC file is writable. If \c false, calls to
  82200. * FLAC__metadata_simple_iterator_set_block() and
  82201. * FLAC__metadata_simple_iterator_insert_block_after() will fail.
  82202. *
  82203. * \param iterator A pointer to an existing iterator.
  82204. * \assert
  82205. * \code iterator != NULL \endcode
  82206. * \retval FLAC__bool
  82207. * See above.
  82208. */
  82209. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_writable(const FLAC__Metadata_SimpleIterator *iterator);
  82210. /** Moves the iterator forward one metadata block, returning \c false if
  82211. * already at the end.
  82212. *
  82213. * \param iterator A pointer to an existing initialized iterator.
  82214. * \assert
  82215. * \code iterator != NULL \endcode
  82216. * \a iterator has been successfully initialized with
  82217. * FLAC__metadata_simple_iterator_init()
  82218. * \retval FLAC__bool
  82219. * \c false if already at the last metadata block of the chain, else
  82220. * \c true.
  82221. */
  82222. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_next(FLAC__Metadata_SimpleIterator *iterator);
  82223. /** Moves the iterator backward one metadata block, returning \c false if
  82224. * already at the beginning.
  82225. *
  82226. * \param iterator A pointer to an existing initialized iterator.
  82227. * \assert
  82228. * \code iterator != NULL \endcode
  82229. * \a iterator has been successfully initialized with
  82230. * FLAC__metadata_simple_iterator_init()
  82231. * \retval FLAC__bool
  82232. * \c false if already at the first metadata block of the chain, else
  82233. * \c true.
  82234. */
  82235. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_prev(FLAC__Metadata_SimpleIterator *iterator);
  82236. /** Returns a flag telling if the current metadata block is the last.
  82237. *
  82238. * \param iterator A pointer to an existing initialized iterator.
  82239. * \assert
  82240. * \code iterator != NULL \endcode
  82241. * \a iterator has been successfully initialized with
  82242. * FLAC__metadata_simple_iterator_init()
  82243. * \retval FLAC__bool
  82244. * \c true if the current metadata block is the last in the file,
  82245. * else \c false.
  82246. */
  82247. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_is_last(const FLAC__Metadata_SimpleIterator *iterator);
  82248. /** Get the offset of the metadata block at the current position. This
  82249. * avoids reading the actual block data which can save time for large
  82250. * blocks.
  82251. *
  82252. * \param iterator A pointer to an existing initialized iterator.
  82253. * \assert
  82254. * \code iterator != NULL \endcode
  82255. * \a iterator has been successfully initialized with
  82256. * FLAC__metadata_simple_iterator_init()
  82257. * \retval off_t
  82258. * The offset of the metadata block at the current iterator position.
  82259. * This is the byte offset relative to the beginning of the file of
  82260. * the current metadata block's header.
  82261. */
  82262. FLAC_API off_t FLAC__metadata_simple_iterator_get_block_offset(const FLAC__Metadata_SimpleIterator *iterator);
  82263. /** Get the type of the metadata block at the current position. This
  82264. * avoids reading the actual block data which can save time for large
  82265. * blocks.
  82266. *
  82267. * \param iterator A pointer to an existing initialized iterator.
  82268. * \assert
  82269. * \code iterator != NULL \endcode
  82270. * \a iterator has been successfully initialized with
  82271. * FLAC__metadata_simple_iterator_init()
  82272. * \retval FLAC__MetadataType
  82273. * The type of the metadata block at the current iterator position.
  82274. */
  82275. FLAC_API FLAC__MetadataType FLAC__metadata_simple_iterator_get_block_type(const FLAC__Metadata_SimpleIterator *iterator);
  82276. /** Get the length of the metadata block at the current position. This
  82277. * avoids reading the actual block data which can save time for large
  82278. * blocks.
  82279. *
  82280. * \param iterator A pointer to an existing initialized iterator.
  82281. * \assert
  82282. * \code iterator != NULL \endcode
  82283. * \a iterator has been successfully initialized with
  82284. * FLAC__metadata_simple_iterator_init()
  82285. * \retval unsigned
  82286. * The length of the metadata block at the current iterator position.
  82287. * The is same length as that in the
  82288. * <a href="http://flac.sourceforge.net/format.html#metadata_block_header">metadata block header</a>,
  82289. * i.e. the length of the metadata body that follows the header.
  82290. */
  82291. FLAC_API unsigned FLAC__metadata_simple_iterator_get_block_length(const FLAC__Metadata_SimpleIterator *iterator);
  82292. /** Get the application ID of the \c APPLICATION block at the current
  82293. * position. This avoids reading the actual block data which can save
  82294. * time for large blocks.
  82295. *
  82296. * \param iterator A pointer to an existing initialized iterator.
  82297. * \param id A pointer to a buffer of at least \c 4 bytes where
  82298. * the ID will be stored.
  82299. * \assert
  82300. * \code iterator != NULL \endcode
  82301. * \code id != NULL \endcode
  82302. * \a iterator has been successfully initialized with
  82303. * FLAC__metadata_simple_iterator_init()
  82304. * \retval FLAC__bool
  82305. * \c true if the ID was successfully read, else \c false, in which
  82306. * case you should check FLAC__metadata_simple_iterator_status() to
  82307. * find out why. If the status is
  82308. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_ILLEGAL_INPUT, then the
  82309. * current metadata block is not an \c APPLICATION block. Otherwise
  82310. * if the status is
  82311. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_READ_ERROR or
  82312. * \c FLAC__METADATA_SIMPLE_ITERATOR_STATUS_SEEK_ERROR, an I/O error
  82313. * occurred and the iterator can no longer be used.
  82314. */
  82315. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_get_application_id(FLAC__Metadata_SimpleIterator *iterator, FLAC__byte *id);
  82316. /** Get the metadata block at the current position. You can modify the
  82317. * block but must use FLAC__metadata_simple_iterator_set_block() to
  82318. * write it back to the FLAC file.
  82319. *
  82320. * You must call FLAC__metadata_object_delete() on the returned object
  82321. * when you are finished with it.
  82322. *
  82323. * \param iterator A pointer to an existing initialized iterator.
  82324. * \assert
  82325. * \code iterator != NULL \endcode
  82326. * \a iterator has been successfully initialized with
  82327. * FLAC__metadata_simple_iterator_init()
  82328. * \retval FLAC__StreamMetadata*
  82329. * The current metadata block, or \c NULL if there was a memory
  82330. * allocation error.
  82331. */
  82332. FLAC_API FLAC__StreamMetadata *FLAC__metadata_simple_iterator_get_block(FLAC__Metadata_SimpleIterator *iterator);
  82333. /** Write a block back to the FLAC file. This function tries to be
  82334. * as efficient as possible; how the block is actually written is
  82335. * shown by the following:
  82336. *
  82337. * Existing block is a STREAMINFO block and the new block is a
  82338. * STREAMINFO block: the new block is written in place. Make sure
  82339. * you know what you're doing when changing the values of a
  82340. * STREAMINFO block.
  82341. *
  82342. * Existing block is a STREAMINFO block and the new block is a
  82343. * not a STREAMINFO block: this is an error since the first block
  82344. * must be a STREAMINFO block. Returns \c false without altering the
  82345. * file.
  82346. *
  82347. * Existing block is not a STREAMINFO block and the new block is a
  82348. * STREAMINFO block: this is an error since there may be only one
  82349. * STREAMINFO block. Returns \c false without altering the file.
  82350. *
  82351. * Existing block and new block are the same length: the existing
  82352. * block will be replaced by the new block, written in place.
  82353. *
  82354. * Existing block is longer than new block: if use_padding is \c true,
  82355. * the existing block will be overwritten in place with the new
  82356. * block followed by a PADDING block, if possible, to make the total
  82357. * size the same as the existing block. Remember that a padding
  82358. * block requires at least four bytes so if the difference in size
  82359. * between the new block and existing block is less than that, the
  82360. * entire file will have to be rewritten, using the new block's
  82361. * exact size. If use_padding is \c false, the entire file will be
  82362. * rewritten, replacing the existing block by the new block.
  82363. *
  82364. * Existing block is shorter than new block: if use_padding is \c true,
  82365. * the function will try and expand the new block into the following
  82366. * PADDING block, if it exists and doing so won't shrink the PADDING
  82367. * block to less than 4 bytes. If there is no following PADDING
  82368. * block, or it will shrink to less than 4 bytes, or use_padding is
  82369. * \c false, the entire file is rewritten, replacing the existing block
  82370. * with the new block. Note that in this case any following PADDING
  82371. * block is preserved as is.
  82372. *
  82373. * After writing the block, the iterator will remain in the same
  82374. * place, i.e. pointing to the new block.
  82375. *
  82376. * \param iterator A pointer to an existing initialized iterator.
  82377. * \param block The block to set.
  82378. * \param use_padding See above.
  82379. * \assert
  82380. * \code iterator != NULL \endcode
  82381. * \a iterator has been successfully initialized with
  82382. * FLAC__metadata_simple_iterator_init()
  82383. * \code block != NULL \endcode
  82384. * \retval FLAC__bool
  82385. * \c true if successful, else \c false.
  82386. */
  82387. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_set_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  82388. /** This is similar to FLAC__metadata_simple_iterator_set_block()
  82389. * except that instead of writing over an existing block, it appends
  82390. * a block after the existing block. \a use_padding is again used to
  82391. * tell the function to try an expand into following padding in an
  82392. * attempt to avoid rewriting the entire file.
  82393. *
  82394. * This function will fail and return \c false if given a STREAMINFO
  82395. * block.
  82396. *
  82397. * After writing the block, the iterator will be pointing to the
  82398. * new block.
  82399. *
  82400. * \param iterator A pointer to an existing initialized iterator.
  82401. * \param block The block to set.
  82402. * \param use_padding See above.
  82403. * \assert
  82404. * \code iterator != NULL \endcode
  82405. * \a iterator has been successfully initialized with
  82406. * FLAC__metadata_simple_iterator_init()
  82407. * \code block != NULL \endcode
  82408. * \retval FLAC__bool
  82409. * \c true if successful, else \c false.
  82410. */
  82411. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_insert_block_after(FLAC__Metadata_SimpleIterator *iterator, FLAC__StreamMetadata *block, FLAC__bool use_padding);
  82412. /** Deletes the block at the current position. This will cause the
  82413. * entire FLAC file to be rewritten, unless \a use_padding is \c true,
  82414. * in which case the block will be replaced by an equal-sized PADDING
  82415. * block. The iterator will be left pointing to the block before the
  82416. * one just deleted.
  82417. *
  82418. * You may not delete the STREAMINFO block.
  82419. *
  82420. * \param iterator A pointer to an existing initialized iterator.
  82421. * \param use_padding See above.
  82422. * \assert
  82423. * \code iterator != NULL \endcode
  82424. * \a iterator has been successfully initialized with
  82425. * FLAC__metadata_simple_iterator_init()
  82426. * \retval FLAC__bool
  82427. * \c true if successful, else \c false.
  82428. */
  82429. FLAC_API FLAC__bool FLAC__metadata_simple_iterator_delete_block(FLAC__Metadata_SimpleIterator *iterator, FLAC__bool use_padding);
  82430. /* \} */
  82431. /** \defgroup flac_metadata_level2 FLAC/metadata.h: metadata level 2 interface
  82432. * \ingroup flac_metadata
  82433. *
  82434. * \brief
  82435. * The level 2 interface provides read-write access to FLAC file metadata;
  82436. * all metadata is read into memory, operated on in memory, and then written
  82437. * to file, which is more efficient than level 1 when editing multiple blocks.
  82438. *
  82439. * Currently Ogg FLAC is supported for read only, via
  82440. * FLAC__metadata_chain_read_ogg() but a subsequent
  82441. * FLAC__metadata_chain_write() will fail.
  82442. *
  82443. * The general usage of this interface is:
  82444. *
  82445. * - Create a new chain using FLAC__metadata_chain_new(). A chain is a
  82446. * linked list of FLAC metadata blocks.
  82447. * - Read all metadata into the the chain from a FLAC file using
  82448. * FLAC__metadata_chain_read() or FLAC__metadata_chain_read_ogg() and
  82449. * check the status.
  82450. * - Optionally, consolidate the padding using
  82451. * FLAC__metadata_chain_merge_padding() or
  82452. * FLAC__metadata_chain_sort_padding().
  82453. * - Create a new iterator using FLAC__metadata_iterator_new()
  82454. * - Initialize the iterator to point to the first element in the chain
  82455. * using FLAC__metadata_iterator_init()
  82456. * - Traverse the chain using FLAC__metadata_iterator_next and
  82457. * FLAC__metadata_iterator_prev().
  82458. * - Get a block for reading or modification using
  82459. * FLAC__metadata_iterator_get_block(). The pointer to the object
  82460. * inside the chain is returned, so the block is yours to modify.
  82461. * Changes will be reflected in the FLAC file when you write the
  82462. * chain. You can also add and delete blocks (see functions below).
  82463. * - When done, write out the chain using FLAC__metadata_chain_write().
  82464. * Make sure to read the whole comment to the function below.
  82465. * - Delete the chain using FLAC__metadata_chain_delete().
  82466. *
  82467. * \note
  82468. * Even though the FLAC file is not open while the chain is being
  82469. * manipulated, you must not alter the file externally during
  82470. * this time. The chain assumes the FLAC file will not change
  82471. * between the time of FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg()
  82472. * and FLAC__metadata_chain_write().
  82473. *
  82474. * \note
  82475. * Do not modify the is_last, length, or type fields of returned
  82476. * FLAC__StreamMetadata objects. These are managed automatically.
  82477. *
  82478. * \note
  82479. * The metadata objects returned by FLAC__metadata_iterator_get_block()
  82480. * are owned by the chain; do not FLAC__metadata_object_delete() them.
  82481. * In the same way, blocks passed to FLAC__metadata_iterator_set_block()
  82482. * become owned by the chain and they will be deleted when the chain is
  82483. * deleted.
  82484. *
  82485. * \{
  82486. */
  82487. struct FLAC__Metadata_Chain;
  82488. /** The opaque structure definition for the level 2 chain type.
  82489. */
  82490. typedef struct FLAC__Metadata_Chain FLAC__Metadata_Chain;
  82491. struct FLAC__Metadata_Iterator;
  82492. /** The opaque structure definition for the level 2 iterator type.
  82493. */
  82494. typedef struct FLAC__Metadata_Iterator FLAC__Metadata_Iterator;
  82495. typedef enum {
  82496. FLAC__METADATA_CHAIN_STATUS_OK = 0,
  82497. /**< The chain is in the normal OK state */
  82498. FLAC__METADATA_CHAIN_STATUS_ILLEGAL_INPUT,
  82499. /**< The data passed into a function violated the function's usage criteria */
  82500. FLAC__METADATA_CHAIN_STATUS_ERROR_OPENING_FILE,
  82501. /**< The chain could not open the target file */
  82502. FLAC__METADATA_CHAIN_STATUS_NOT_A_FLAC_FILE,
  82503. /**< The chain could not find the FLAC signature at the start of the file */
  82504. FLAC__METADATA_CHAIN_STATUS_NOT_WRITABLE,
  82505. /**< The chain tried to write to a file that was not writable */
  82506. FLAC__METADATA_CHAIN_STATUS_BAD_METADATA,
  82507. /**< The chain encountered input that does not conform to the FLAC metadata specification */
  82508. FLAC__METADATA_CHAIN_STATUS_READ_ERROR,
  82509. /**< The chain encountered an error while reading the FLAC file */
  82510. FLAC__METADATA_CHAIN_STATUS_SEEK_ERROR,
  82511. /**< The chain encountered an error while seeking in the FLAC file */
  82512. FLAC__METADATA_CHAIN_STATUS_WRITE_ERROR,
  82513. /**< The chain encountered an error while writing the FLAC file */
  82514. FLAC__METADATA_CHAIN_STATUS_RENAME_ERROR,
  82515. /**< The chain encountered an error renaming the FLAC file */
  82516. FLAC__METADATA_CHAIN_STATUS_UNLINK_ERROR,
  82517. /**< The chain encountered an error removing the temporary file */
  82518. FLAC__METADATA_CHAIN_STATUS_MEMORY_ALLOCATION_ERROR,
  82519. /**< Memory allocation failed */
  82520. FLAC__METADATA_CHAIN_STATUS_INTERNAL_ERROR,
  82521. /**< The caller violated an assertion or an unexpected error occurred */
  82522. FLAC__METADATA_CHAIN_STATUS_INVALID_CALLBACKS,
  82523. /**< One or more of the required callbacks was NULL */
  82524. FLAC__METADATA_CHAIN_STATUS_READ_WRITE_MISMATCH,
  82525. /**< FLAC__metadata_chain_write() was called on a chain read by
  82526. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  82527. * or
  82528. * FLAC__metadata_chain_write_with_callbacks()/FLAC__metadata_chain_write_with_callbacks_and_tempfile()
  82529. * was called on a chain read by
  82530. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  82531. * Matching read/write methods must always be used. */
  82532. FLAC__METADATA_CHAIN_STATUS_WRONG_WRITE_CALL
  82533. /**< FLAC__metadata_chain_write_with_callbacks() was called when the
  82534. * chain write requires a tempfile; use
  82535. * FLAC__metadata_chain_write_with_callbacks_and_tempfile() instead.
  82536. * Or, FLAC__metadata_chain_write_with_callbacks_and_tempfile() was
  82537. * called when the chain write does not require a tempfile; use
  82538. * FLAC__metadata_chain_write_with_callbacks() instead.
  82539. * Always check FLAC__metadata_chain_check_if_tempfile_needed()
  82540. * before writing via callbacks. */
  82541. } FLAC__Metadata_ChainStatus;
  82542. /** Maps a FLAC__Metadata_ChainStatus to a C string.
  82543. *
  82544. * Using a FLAC__Metadata_ChainStatus as the index to this array
  82545. * will give the string equivalent. The contents should not be modified.
  82546. */
  82547. extern FLAC_API const char * const FLAC__Metadata_ChainStatusString[];
  82548. /*********** FLAC__Metadata_Chain ***********/
  82549. /** Create a new chain instance.
  82550. *
  82551. * \retval FLAC__Metadata_Chain*
  82552. * \c NULL if there was an error allocating memory, else the new instance.
  82553. */
  82554. FLAC_API FLAC__Metadata_Chain *FLAC__metadata_chain_new(void);
  82555. /** Free a chain instance. Deletes the object pointed to by \a chain.
  82556. *
  82557. * \param chain A pointer to an existing chain.
  82558. * \assert
  82559. * \code chain != NULL \endcode
  82560. */
  82561. FLAC_API void FLAC__metadata_chain_delete(FLAC__Metadata_Chain *chain);
  82562. /** Get the current status of the chain. Call this after a function
  82563. * returns \c false to get the reason for the error. Also resets the
  82564. * status to FLAC__METADATA_CHAIN_STATUS_OK.
  82565. *
  82566. * \param chain A pointer to an existing chain.
  82567. * \assert
  82568. * \code chain != NULL \endcode
  82569. * \retval FLAC__Metadata_ChainStatus
  82570. * The current status of the chain.
  82571. */
  82572. FLAC_API FLAC__Metadata_ChainStatus FLAC__metadata_chain_status(FLAC__Metadata_Chain *chain);
  82573. /** Read all metadata from a FLAC file into the chain.
  82574. *
  82575. * \param chain A pointer to an existing chain.
  82576. * \param filename The path to the FLAC file to read.
  82577. * \assert
  82578. * \code chain != NULL \endcode
  82579. * \code filename != NULL \endcode
  82580. * \retval FLAC__bool
  82581. * \c true if a valid list of metadata blocks was read from
  82582. * \a filename, else \c false. On failure, check the status with
  82583. * FLAC__metadata_chain_status().
  82584. */
  82585. FLAC_API FLAC__bool FLAC__metadata_chain_read(FLAC__Metadata_Chain *chain, const char *filename);
  82586. /** Read all metadata from an Ogg FLAC file into the chain.
  82587. *
  82588. * \note Ogg FLAC metadata data writing is not supported yet and
  82589. * FLAC__metadata_chain_write() will fail.
  82590. *
  82591. * \param chain A pointer to an existing chain.
  82592. * \param filename The path to the Ogg FLAC file to read.
  82593. * \assert
  82594. * \code chain != NULL \endcode
  82595. * \code filename != NULL \endcode
  82596. * \retval FLAC__bool
  82597. * \c true if a valid list of metadata blocks was read from
  82598. * \a filename, else \c false. On failure, check the status with
  82599. * FLAC__metadata_chain_status().
  82600. */
  82601. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg(FLAC__Metadata_Chain *chain, const char *filename);
  82602. /** Read all metadata from a FLAC stream into the chain via I/O callbacks.
  82603. *
  82604. * The \a handle need only be open for reading, but must be seekable.
  82605. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  82606. * for Windows).
  82607. *
  82608. * \param chain A pointer to an existing chain.
  82609. * \param handle The I/O handle of the FLAC stream to read. The
  82610. * handle will NOT be closed after the metadata is read;
  82611. * that is the duty of the caller.
  82612. * \param callbacks
  82613. * A set of callbacks to use for I/O. The mandatory
  82614. * callbacks are \a read, \a seek, and \a tell.
  82615. * \assert
  82616. * \code chain != NULL \endcode
  82617. * \retval FLAC__bool
  82618. * \c true if a valid list of metadata blocks was read from
  82619. * \a handle, else \c false. On failure, check the status with
  82620. * FLAC__metadata_chain_status().
  82621. */
  82622. FLAC_API FLAC__bool FLAC__metadata_chain_read_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  82623. /** Read all metadata from an Ogg FLAC stream into the chain via I/O callbacks.
  82624. *
  82625. * The \a handle need only be open for reading, but must be seekable.
  82626. * The equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  82627. * for Windows).
  82628. *
  82629. * \note Ogg FLAC metadata data writing is not supported yet and
  82630. * FLAC__metadata_chain_write() will fail.
  82631. *
  82632. * \param chain A pointer to an existing chain.
  82633. * \param handle The I/O handle of the Ogg FLAC stream to read. The
  82634. * handle will NOT be closed after the metadata is read;
  82635. * that is the duty of the caller.
  82636. * \param callbacks
  82637. * A set of callbacks to use for I/O. The mandatory
  82638. * callbacks are \a read, \a seek, and \a tell.
  82639. * \assert
  82640. * \code chain != NULL \endcode
  82641. * \retval FLAC__bool
  82642. * \c true if a valid list of metadata blocks was read from
  82643. * \a handle, else \c false. On failure, check the status with
  82644. * FLAC__metadata_chain_status().
  82645. */
  82646. FLAC_API FLAC__bool FLAC__metadata_chain_read_ogg_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  82647. /** Checks if writing the given chain would require the use of a
  82648. * temporary file, or if it could be written in place.
  82649. *
  82650. * Under certain conditions, padding can be utilized so that writing
  82651. * edited metadata back to the FLAC file does not require rewriting the
  82652. * entire file. If rewriting is required, then a temporary workfile is
  82653. * required. When writing metadata using callbacks, you must check
  82654. * this function to know whether to call
  82655. * FLAC__metadata_chain_write_with_callbacks() or
  82656. * FLAC__metadata_chain_write_with_callbacks_and_tempfile(). When
  82657. * writing with FLAC__metadata_chain_write(), the temporary file is
  82658. * handled internally.
  82659. *
  82660. * \param chain A pointer to an existing chain.
  82661. * \param use_padding
  82662. * Whether or not padding will be allowed to be used
  82663. * during the write. The value of \a use_padding given
  82664. * here must match the value later passed to
  82665. * FLAC__metadata_chain_write_with_callbacks() or
  82666. * FLAC__metadata_chain_write_with_callbacks_with_tempfile().
  82667. * \assert
  82668. * \code chain != NULL \endcode
  82669. * \retval FLAC__bool
  82670. * \c true if writing the current chain would require a tempfile, or
  82671. * \c false if metadata can be written in place.
  82672. */
  82673. FLAC_API FLAC__bool FLAC__metadata_chain_check_if_tempfile_needed(FLAC__Metadata_Chain *chain, FLAC__bool use_padding);
  82674. /** Write all metadata out to the FLAC file. This function tries to be as
  82675. * efficient as possible; how the metadata is actually written is shown by
  82676. * the following:
  82677. *
  82678. * If the current chain is the same size as the existing metadata, the new
  82679. * data is written in place.
  82680. *
  82681. * If the current chain is longer than the existing metadata, and
  82682. * \a use_padding is \c true, and the last block is a PADDING block of
  82683. * sufficient length, the function will truncate the final padding block
  82684. * so that the overall size of the metadata is the same as the existing
  82685. * metadata, and then just rewrite the metadata. Otherwise, if not all of
  82686. * the above conditions are met, the entire FLAC file must be rewritten.
  82687. * If you want to use padding this way it is a good idea to call
  82688. * FLAC__metadata_chain_sort_padding() first so that you have the maximum
  82689. * amount of padding to work with, unless you need to preserve ordering
  82690. * of the PADDING blocks for some reason.
  82691. *
  82692. * If the current chain is shorter than the existing metadata, and
  82693. * \a use_padding is \c true, and the final block is a PADDING block, the padding
  82694. * is extended to make the overall size the same as the existing data. If
  82695. * \a use_padding is \c true and the last block is not a PADDING block, a new
  82696. * PADDING block is added to the end of the new data to make it the same
  82697. * size as the existing data (if possible, see the note to
  82698. * FLAC__metadata_simple_iterator_set_block() about the four byte limit)
  82699. * and the new data is written in place. If none of the above apply or
  82700. * \a use_padding is \c false, the entire FLAC file is rewritten.
  82701. *
  82702. * If \a preserve_file_stats is \c true, the owner and modification time will
  82703. * be preserved even if the FLAC file is written.
  82704. *
  82705. * For this write function to be used, the chain must have been read with
  82706. * FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg(), not
  82707. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks().
  82708. *
  82709. * \param chain A pointer to an existing chain.
  82710. * \param use_padding See above.
  82711. * \param preserve_file_stats See above.
  82712. * \assert
  82713. * \code chain != NULL \endcode
  82714. * \retval FLAC__bool
  82715. * \c true if the write succeeded, else \c false. On failure,
  82716. * check the status with FLAC__metadata_chain_status().
  82717. */
  82718. FLAC_API FLAC__bool FLAC__metadata_chain_write(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__bool preserve_file_stats);
  82719. /** Write all metadata out to a FLAC stream via callbacks.
  82720. *
  82721. * (See FLAC__metadata_chain_write() for the details on how padding is
  82722. * used to write metadata in place if possible.)
  82723. *
  82724. * The \a handle must be open for updating and be seekable. The
  82725. * equivalent minimum stdio fopen() file mode is \c "r+" (or \c "r+b"
  82726. * for Windows).
  82727. *
  82728. * For this write function to be used, the chain must have been read with
  82729. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  82730. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  82731. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  82732. * \c false.
  82733. *
  82734. * \param chain A pointer to an existing chain.
  82735. * \param use_padding See FLAC__metadata_chain_write()
  82736. * \param handle The I/O handle of the FLAC stream to write. The
  82737. * handle will NOT be closed after the metadata is
  82738. * written; that is the duty of the caller.
  82739. * \param callbacks A set of callbacks to use for I/O. The mandatory
  82740. * callbacks are \a write and \a seek.
  82741. * \assert
  82742. * \code chain != NULL \endcode
  82743. * \retval FLAC__bool
  82744. * \c true if the write succeeded, else \c false. On failure,
  82745. * check the status with FLAC__metadata_chain_status().
  82746. */
  82747. FLAC_API FLAC__bool FLAC__metadata_chain_write_with_callbacks(FLAC__Metadata_Chain *chain, FLAC__bool use_padding, FLAC__IOHandle handle, FLAC__IOCallbacks callbacks);
  82748. /** Write all metadata out to a FLAC stream via callbacks.
  82749. *
  82750. * (See FLAC__metadata_chain_write() for the details on how padding is
  82751. * used to write metadata in place if possible.)
  82752. *
  82753. * This version of the write-with-callbacks function must be used when
  82754. * FLAC__metadata_chain_check_if_tempfile_needed() returns true. In
  82755. * this function, you must supply an I/O handle corresponding to the
  82756. * FLAC file to edit, and a temporary handle to which the new FLAC
  82757. * file will be written. It is the caller's job to move this temporary
  82758. * FLAC file on top of the original FLAC file to complete the metadata
  82759. * edit.
  82760. *
  82761. * The \a handle must be open for reading and be seekable. The
  82762. * equivalent minimum stdio fopen() file mode is \c "r" (or \c "rb"
  82763. * for Windows).
  82764. *
  82765. * The \a temp_handle must be open for writing. The
  82766. * equivalent minimum stdio fopen() file mode is \c "w" (or \c "wb"
  82767. * for Windows). It should be an empty stream, or at least positioned
  82768. * at the start-of-file (in which case it is the caller's duty to
  82769. * truncate it on return).
  82770. *
  82771. * For this write function to be used, the chain must have been read with
  82772. * FLAC__metadata_chain_read_with_callbacks()/FLAC__metadata_chain_read_ogg_with_callbacks(),
  82773. * not FLAC__metadata_chain_read()/FLAC__metadata_chain_read_ogg().
  82774. * Also, FLAC__metadata_chain_check_if_tempfile_needed() must have returned
  82775. * \c true.
  82776. *
  82777. * \param chain A pointer to an existing chain.
  82778. * \param use_padding See FLAC__metadata_chain_write()
  82779. * \param handle The I/O handle of the original FLAC stream to read.
  82780. * The handle will NOT be closed after the metadata is
  82781. * written; that is the duty of the caller.
  82782. * \param callbacks A set of callbacks to use for I/O on \a handle.
  82783. * The mandatory callbacks are \a read, \a seek, and
  82784. * \a eof.
  82785. * \param temp_handle The I/O handle of the FLAC stream to write. The
  82786. * handle will NOT be closed after the metadata is
  82787. * written; that is the duty of the caller.
  82788. * \param temp_callbacks
  82789. * A set of callbacks to use for I/O on temp_handle.
  82790. * The only mandatory callback is \a write.
  82791. * \assert
  82792. * \code chain != NULL \endcode
  82793. * \retval FLAC__bool
  82794. * \c true if the write succeeded, else \c false. On failure,
  82795. * check the status with FLAC__metadata_chain_status().
  82796. */
  82797. 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);
  82798. /** Merge adjacent PADDING blocks into a single block.
  82799. *
  82800. * \note This function does not write to the FLAC file, it only
  82801. * modifies the chain.
  82802. *
  82803. * \warning Any iterator on the current chain will become invalid after this
  82804. * call. You should delete the iterator and get a new one.
  82805. *
  82806. * \param chain A pointer to an existing chain.
  82807. * \assert
  82808. * \code chain != NULL \endcode
  82809. */
  82810. FLAC_API void FLAC__metadata_chain_merge_padding(FLAC__Metadata_Chain *chain);
  82811. /** This function will move all PADDING blocks to the end on the metadata,
  82812. * then merge them into a single block.
  82813. *
  82814. * \note This function does not write to the FLAC file, it only
  82815. * modifies the chain.
  82816. *
  82817. * \warning Any iterator on the current chain will become invalid after this
  82818. * call. You should delete the iterator and get a new one.
  82819. *
  82820. * \param chain A pointer to an existing chain.
  82821. * \assert
  82822. * \code chain != NULL \endcode
  82823. */
  82824. FLAC_API void FLAC__metadata_chain_sort_padding(FLAC__Metadata_Chain *chain);
  82825. /*********** FLAC__Metadata_Iterator ***********/
  82826. /** Create a new iterator instance.
  82827. *
  82828. * \retval FLAC__Metadata_Iterator*
  82829. * \c NULL if there was an error allocating memory, else the new instance.
  82830. */
  82831. FLAC_API FLAC__Metadata_Iterator *FLAC__metadata_iterator_new(void);
  82832. /** Free an iterator instance. Deletes the object pointed to by \a iterator.
  82833. *
  82834. * \param iterator A pointer to an existing iterator.
  82835. * \assert
  82836. * \code iterator != NULL \endcode
  82837. */
  82838. FLAC_API void FLAC__metadata_iterator_delete(FLAC__Metadata_Iterator *iterator);
  82839. /** Initialize the iterator to point to the first metadata block in the
  82840. * given chain.
  82841. *
  82842. * \param iterator A pointer to an existing iterator.
  82843. * \param chain A pointer to an existing and initialized (read) chain.
  82844. * \assert
  82845. * \code iterator != NULL \endcode
  82846. * \code chain != NULL \endcode
  82847. */
  82848. FLAC_API void FLAC__metadata_iterator_init(FLAC__Metadata_Iterator *iterator, FLAC__Metadata_Chain *chain);
  82849. /** Moves the iterator forward one metadata block, returning \c false if
  82850. * already at the end.
  82851. *
  82852. * \param iterator A pointer to an existing initialized iterator.
  82853. * \assert
  82854. * \code iterator != NULL \endcode
  82855. * \a iterator has been successfully initialized with
  82856. * FLAC__metadata_iterator_init()
  82857. * \retval FLAC__bool
  82858. * \c false if already at the last metadata block of the chain, else
  82859. * \c true.
  82860. */
  82861. FLAC_API FLAC__bool FLAC__metadata_iterator_next(FLAC__Metadata_Iterator *iterator);
  82862. /** Moves the iterator backward one metadata block, returning \c false if
  82863. * already at the beginning.
  82864. *
  82865. * \param iterator A pointer to an existing initialized iterator.
  82866. * \assert
  82867. * \code iterator != NULL \endcode
  82868. * \a iterator has been successfully initialized with
  82869. * FLAC__metadata_iterator_init()
  82870. * \retval FLAC__bool
  82871. * \c false if already at the first metadata block of the chain, else
  82872. * \c true.
  82873. */
  82874. FLAC_API FLAC__bool FLAC__metadata_iterator_prev(FLAC__Metadata_Iterator *iterator);
  82875. /** Get the type of the metadata block at the current position.
  82876. *
  82877. * \param iterator A pointer to an existing initialized iterator.
  82878. * \assert
  82879. * \code iterator != NULL \endcode
  82880. * \a iterator has been successfully initialized with
  82881. * FLAC__metadata_iterator_init()
  82882. * \retval FLAC__MetadataType
  82883. * The type of the metadata block at the current iterator position.
  82884. */
  82885. FLAC_API FLAC__MetadataType FLAC__metadata_iterator_get_block_type(const FLAC__Metadata_Iterator *iterator);
  82886. /** Get the metadata block at the current position. You can modify
  82887. * the block in place but must write the chain before the changes
  82888. * are reflected to the FLAC file. You do not need to call
  82889. * FLAC__metadata_iterator_set_block() to reflect the changes;
  82890. * the pointer returned by FLAC__metadata_iterator_get_block()
  82891. * points directly into the chain.
  82892. *
  82893. * \warning
  82894. * Do not call FLAC__metadata_object_delete() on the returned object;
  82895. * to delete a block use FLAC__metadata_iterator_delete_block().
  82896. *
  82897. * \param iterator A pointer to an existing initialized iterator.
  82898. * \assert
  82899. * \code iterator != NULL \endcode
  82900. * \a iterator has been successfully initialized with
  82901. * FLAC__metadata_iterator_init()
  82902. * \retval FLAC__StreamMetadata*
  82903. * The current metadata block.
  82904. */
  82905. FLAC_API FLAC__StreamMetadata *FLAC__metadata_iterator_get_block(FLAC__Metadata_Iterator *iterator);
  82906. /** Set the metadata block at the current position, replacing the existing
  82907. * block. The new block passed in becomes owned by the chain and it will be
  82908. * deleted when the chain is deleted.
  82909. *
  82910. * \param iterator A pointer to an existing initialized iterator.
  82911. * \param block A pointer to a metadata block.
  82912. * \assert
  82913. * \code iterator != NULL \endcode
  82914. * \a iterator has been successfully initialized with
  82915. * FLAC__metadata_iterator_init()
  82916. * \code block != NULL \endcode
  82917. * \retval FLAC__bool
  82918. * \c false if the conditions in the above description are not met, or
  82919. * a memory allocation error occurs, otherwise \c true.
  82920. */
  82921. FLAC_API FLAC__bool FLAC__metadata_iterator_set_block(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  82922. /** Removes the current block from the chain. If \a replace_with_padding is
  82923. * \c true, the block will instead be replaced with a padding block of equal
  82924. * size. You can not delete the STREAMINFO block. The iterator will be
  82925. * left pointing to the block before the one just "deleted", even if
  82926. * \a replace_with_padding is \c true.
  82927. *
  82928. * \param iterator A pointer to an existing initialized iterator.
  82929. * \param replace_with_padding See above.
  82930. * \assert
  82931. * \code iterator != NULL \endcode
  82932. * \a iterator has been successfully initialized with
  82933. * FLAC__metadata_iterator_init()
  82934. * \retval FLAC__bool
  82935. * \c false if the conditions in the above description are not met,
  82936. * otherwise \c true.
  82937. */
  82938. FLAC_API FLAC__bool FLAC__metadata_iterator_delete_block(FLAC__Metadata_Iterator *iterator, FLAC__bool replace_with_padding);
  82939. /** Insert a new block before the current block. You cannot insert a block
  82940. * before the first STREAMINFO block. You cannot insert a STREAMINFO block
  82941. * as there can be only one, the one that already exists at the head when you
  82942. * read in a chain. The chain takes ownership of the new block and it will be
  82943. * deleted when the chain is deleted. The iterator will be left pointing to
  82944. * the new block.
  82945. *
  82946. * \param iterator A pointer to an existing initialized iterator.
  82947. * \param block A pointer to a metadata block to insert.
  82948. * \assert
  82949. * \code iterator != NULL \endcode
  82950. * \a iterator has been successfully initialized with
  82951. * FLAC__metadata_iterator_init()
  82952. * \retval FLAC__bool
  82953. * \c false if the conditions in the above description are not met, or
  82954. * a memory allocation error occurs, otherwise \c true.
  82955. */
  82956. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_before(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  82957. /** Insert a new block after the current block. You cannot insert a STREAMINFO
  82958. * block as there can be only one, the one that already exists at the head when
  82959. * you read in a chain. The chain takes ownership of the new block and it will
  82960. * be deleted when the chain is deleted. The iterator will be left pointing to
  82961. * the new block.
  82962. *
  82963. * \param iterator A pointer to an existing initialized iterator.
  82964. * \param block A pointer to a metadata block to insert.
  82965. * \assert
  82966. * \code iterator != NULL \endcode
  82967. * \a iterator has been successfully initialized with
  82968. * FLAC__metadata_iterator_init()
  82969. * \retval FLAC__bool
  82970. * \c false if the conditions in the above description are not met, or
  82971. * a memory allocation error occurs, otherwise \c true.
  82972. */
  82973. FLAC_API FLAC__bool FLAC__metadata_iterator_insert_block_after(FLAC__Metadata_Iterator *iterator, FLAC__StreamMetadata *block);
  82974. /* \} */
  82975. /** \defgroup flac_metadata_object FLAC/metadata.h: metadata object methods
  82976. * \ingroup flac_metadata
  82977. *
  82978. * \brief
  82979. * This module contains methods for manipulating FLAC metadata objects.
  82980. *
  82981. * Since many are variable length we have to be careful about the memory
  82982. * management. We decree that all pointers to data in the object are
  82983. * owned by the object and memory-managed by the object.
  82984. *
  82985. * Use the FLAC__metadata_object_new() and FLAC__metadata_object_delete()
  82986. * functions to create all instances. When using the
  82987. * FLAC__metadata_object_set_*() functions to set pointers to data, set
  82988. * \a copy to \c true to have the function make it's own copy of the data, or
  82989. * to \c false to give the object ownership of your data. In the latter case
  82990. * your pointer must be freeable by free() and will be free()d when the object
  82991. * is FLAC__metadata_object_delete()d. It is legal to pass a null pointer as
  82992. * the data pointer to a FLAC__metadata_object_set_*() function as long as
  82993. * the length argument is 0 and the \a copy argument is \c false.
  82994. *
  82995. * The FLAC__metadata_object_new() and FLAC__metadata_object_clone() function
  82996. * will return \c NULL in the case of a memory allocation error, otherwise a new
  82997. * object. The FLAC__metadata_object_set_*() functions return \c false in the
  82998. * case of a memory allocation error.
  82999. *
  83000. * We don't have the convenience of C++ here, so note that the library relies
  83001. * on you to keep the types straight. In other words, if you pass, for
  83002. * example, a FLAC__StreamMetadata* that represents a STREAMINFO block to
  83003. * FLAC__metadata_object_application_set_data(), you will get an assertion
  83004. * failure.
  83005. *
  83006. * For convenience the FLAC__metadata_object_vorbiscomment_*() functions
  83007. * maintain a trailing NUL on each Vorbis comment entry. This is not counted
  83008. * toward the length or stored in the stream, but it can make working with plain
  83009. * comments (those that don't contain embedded-NULs in the value) easier.
  83010. * Entries passed into these functions have trailing NULs added if missing, and
  83011. * returned entries are guaranteed to have a trailing NUL.
  83012. *
  83013. * The FLAC__metadata_object_vorbiscomment_*() functions that take a Vorbis
  83014. * comment entry/name/value will first validate that it complies with the Vorbis
  83015. * comment specification and return false if it does not.
  83016. *
  83017. * There is no need to recalculate the length field on metadata blocks you
  83018. * have modified. They will be calculated automatically before they are
  83019. * written back to a file.
  83020. *
  83021. * \{
  83022. */
  83023. /** Create a new metadata object instance of the given type.
  83024. *
  83025. * The object will be "empty"; i.e. values and data pointers will be \c 0,
  83026. * with the exception of FLAC__METADATA_TYPE_VORBIS_COMMENT, which will have
  83027. * the vendor string set (but zero comments).
  83028. *
  83029. * Do not pass in a value greater than or equal to
  83030. * \a FLAC__METADATA_TYPE_UNDEFINED unless you really know what you're
  83031. * doing.
  83032. *
  83033. * \param type Type of object to create
  83034. * \retval FLAC__StreamMetadata*
  83035. * \c NULL if there was an error allocating memory or the type code is
  83036. * greater than FLAC__MAX_METADATA_TYPE_CODE, else the new instance.
  83037. */
  83038. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_new(FLAC__MetadataType type);
  83039. /** Create a copy of an existing metadata object.
  83040. *
  83041. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  83042. * object is also copied. The caller takes ownership of the new block and
  83043. * is responsible for freeing it with FLAC__metadata_object_delete().
  83044. *
  83045. * \param object Pointer to object to copy.
  83046. * \assert
  83047. * \code object != NULL \endcode
  83048. * \retval FLAC__StreamMetadata*
  83049. * \c NULL if there was an error allocating memory, else the new instance.
  83050. */
  83051. FLAC_API FLAC__StreamMetadata *FLAC__metadata_object_clone(const FLAC__StreamMetadata *object);
  83052. /** Free a metadata object. Deletes the object pointed to by \a object.
  83053. *
  83054. * The delete is a "deep" delete, i.e. dynamically allocated data within the
  83055. * object is also deleted.
  83056. *
  83057. * \param object A pointer to an existing object.
  83058. * \assert
  83059. * \code object != NULL \endcode
  83060. */
  83061. FLAC_API void FLAC__metadata_object_delete(FLAC__StreamMetadata *object);
  83062. /** Compares two metadata objects.
  83063. *
  83064. * The compare is "deep", i.e. dynamically allocated data within the
  83065. * object is also compared.
  83066. *
  83067. * \param block1 A pointer to an existing object.
  83068. * \param block2 A pointer to an existing object.
  83069. * \assert
  83070. * \code block1 != NULL \endcode
  83071. * \code block2 != NULL \endcode
  83072. * \retval FLAC__bool
  83073. * \c true if objects are identical, else \c false.
  83074. */
  83075. FLAC_API FLAC__bool FLAC__metadata_object_is_equal(const FLAC__StreamMetadata *block1, const FLAC__StreamMetadata *block2);
  83076. /** Sets the application data of an APPLICATION block.
  83077. *
  83078. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  83079. * takes ownership of the pointer. The existing data will be freed if this
  83080. * function is successful, otherwise the original data will remain if \a copy
  83081. * is \c true and malloc() fails.
  83082. *
  83083. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  83084. *
  83085. * \param object A pointer to an existing APPLICATION object.
  83086. * \param data A pointer to the data to set.
  83087. * \param length The length of \a data in bytes.
  83088. * \param copy See above.
  83089. * \assert
  83090. * \code object != NULL \endcode
  83091. * \code object->type == FLAC__METADATA_TYPE_APPLICATION \endcode
  83092. * \code (data != NULL && length > 0) ||
  83093. * (data == NULL && length == 0 && copy == false) \endcode
  83094. * \retval FLAC__bool
  83095. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83096. */
  83097. FLAC_API FLAC__bool FLAC__metadata_object_application_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, unsigned length, FLAC__bool copy);
  83098. /** Resize the seekpoint array.
  83099. *
  83100. * If the size shrinks, elements will truncated; if it grows, new placeholder
  83101. * points will be added to the end.
  83102. *
  83103. * \param object A pointer to an existing SEEKTABLE object.
  83104. * \param new_num_points The desired length of the array; may be \c 0.
  83105. * \assert
  83106. * \code object != NULL \endcode
  83107. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83108. * \code (object->data.seek_table.points == NULL && object->data.seek_table.num_points == 0) ||
  83109. * (object->data.seek_table.points != NULL && object->data.seek_table.num_points > 0) \endcode
  83110. * \retval FLAC__bool
  83111. * \c false if memory allocation error, else \c true.
  83112. */
  83113. FLAC_API FLAC__bool FLAC__metadata_object_seektable_resize_points(FLAC__StreamMetadata *object, unsigned new_num_points);
  83114. /** Set a seekpoint in a seektable.
  83115. *
  83116. * \param object A pointer to an existing SEEKTABLE object.
  83117. * \param point_num Index into seekpoint array to set.
  83118. * \param point The point to set.
  83119. * \assert
  83120. * \code object != NULL \endcode
  83121. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83122. * \code object->data.seek_table.num_points > point_num \endcode
  83123. */
  83124. FLAC_API void FLAC__metadata_object_seektable_set_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  83125. /** Insert a seekpoint into a seektable.
  83126. *
  83127. * \param object A pointer to an existing SEEKTABLE object.
  83128. * \param point_num Index into seekpoint array to set.
  83129. * \param point The point to set.
  83130. * \assert
  83131. * \code object != NULL \endcode
  83132. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83133. * \code object->data.seek_table.num_points >= point_num \endcode
  83134. * \retval FLAC__bool
  83135. * \c false if memory allocation error, else \c true.
  83136. */
  83137. FLAC_API FLAC__bool FLAC__metadata_object_seektable_insert_point(FLAC__StreamMetadata *object, unsigned point_num, FLAC__StreamMetadata_SeekPoint point);
  83138. /** Delete a seekpoint from a seektable.
  83139. *
  83140. * \param object A pointer to an existing SEEKTABLE object.
  83141. * \param point_num Index into seekpoint array to set.
  83142. * \assert
  83143. * \code object != NULL \endcode
  83144. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83145. * \code object->data.seek_table.num_points > point_num \endcode
  83146. * \retval FLAC__bool
  83147. * \c false if memory allocation error, else \c true.
  83148. */
  83149. FLAC_API FLAC__bool FLAC__metadata_object_seektable_delete_point(FLAC__StreamMetadata *object, unsigned point_num);
  83150. /** Check a seektable to see if it conforms to the FLAC specification.
  83151. * See the format specification for limits on the contents of the
  83152. * seektable.
  83153. *
  83154. * \param object A pointer to an existing SEEKTABLE object.
  83155. * \assert
  83156. * \code object != NULL \endcode
  83157. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83158. * \retval FLAC__bool
  83159. * \c false if seek table is illegal, else \c true.
  83160. */
  83161. FLAC_API FLAC__bool FLAC__metadata_object_seektable_is_legal(const FLAC__StreamMetadata *object);
  83162. /** Append a number of placeholder points to the end of a seek table.
  83163. *
  83164. * \note
  83165. * As with the other ..._seektable_template_... functions, you should
  83166. * call FLAC__metadata_object_seektable_template_sort() when finished
  83167. * to make the seek table legal.
  83168. *
  83169. * \param object A pointer to an existing SEEKTABLE object.
  83170. * \param num The number of placeholder points to append.
  83171. * \assert
  83172. * \code object != NULL \endcode
  83173. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83174. * \retval FLAC__bool
  83175. * \c false if memory allocation fails, else \c true.
  83176. */
  83177. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_placeholders(FLAC__StreamMetadata *object, unsigned num);
  83178. /** Append a specific seek point template to the end of a seek table.
  83179. *
  83180. * \note
  83181. * As with the other ..._seektable_template_... functions, you should
  83182. * call FLAC__metadata_object_seektable_template_sort() when finished
  83183. * to make the seek table legal.
  83184. *
  83185. * \param object A pointer to an existing SEEKTABLE object.
  83186. * \param sample_number The sample number of the seek point template.
  83187. * \assert
  83188. * \code object != NULL \endcode
  83189. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83190. * \retval FLAC__bool
  83191. * \c false if memory allocation fails, else \c true.
  83192. */
  83193. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_point(FLAC__StreamMetadata *object, FLAC__uint64 sample_number);
  83194. /** Append specific seek point templates to the end of a seek table.
  83195. *
  83196. * \note
  83197. * As with the other ..._seektable_template_... functions, you should
  83198. * call FLAC__metadata_object_seektable_template_sort() when finished
  83199. * to make the seek table legal.
  83200. *
  83201. * \param object A pointer to an existing SEEKTABLE object.
  83202. * \param sample_numbers An array of sample numbers for the seek points.
  83203. * \param num The number of seek point templates to append.
  83204. * \assert
  83205. * \code object != NULL \endcode
  83206. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83207. * \retval FLAC__bool
  83208. * \c false if memory allocation fails, else \c true.
  83209. */
  83210. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_points(FLAC__StreamMetadata *object, FLAC__uint64 sample_numbers[], unsigned num);
  83211. /** Append a set of evenly-spaced seek point templates to the end of a
  83212. * seek table.
  83213. *
  83214. * \note
  83215. * As with the other ..._seektable_template_... functions, you should
  83216. * call FLAC__metadata_object_seektable_template_sort() when finished
  83217. * to make the seek table legal.
  83218. *
  83219. * \param object A pointer to an existing SEEKTABLE object.
  83220. * \param num The number of placeholder points to append.
  83221. * \param total_samples The total number of samples to be encoded;
  83222. * the seekpoints will be spaced approximately
  83223. * \a total_samples / \a num samples apart.
  83224. * \assert
  83225. * \code object != NULL \endcode
  83226. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83227. * \code total_samples > 0 \endcode
  83228. * \retval FLAC__bool
  83229. * \c false if memory allocation fails, else \c true.
  83230. */
  83231. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points(FLAC__StreamMetadata *object, unsigned num, FLAC__uint64 total_samples);
  83232. /** Append a set of evenly-spaced seek point templates to the end of a
  83233. * seek table.
  83234. *
  83235. * \note
  83236. * As with the other ..._seektable_template_... functions, you should
  83237. * call FLAC__metadata_object_seektable_template_sort() when finished
  83238. * to make the seek table legal.
  83239. *
  83240. * \param object A pointer to an existing SEEKTABLE object.
  83241. * \param samples The number of samples apart to space the placeholder
  83242. * points. The first point will be at sample \c 0, the
  83243. * second at sample \a samples, then 2*\a samples, and
  83244. * so on. As long as \a samples and \a total_samples
  83245. * are greater than \c 0, there will always be at least
  83246. * one seekpoint at sample \c 0.
  83247. * \param total_samples The total number of samples to be encoded;
  83248. * the seekpoints will be spaced
  83249. * \a samples samples apart.
  83250. * \assert
  83251. * \code object != NULL \endcode
  83252. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83253. * \code samples > 0 \endcode
  83254. * \code total_samples > 0 \endcode
  83255. * \retval FLAC__bool
  83256. * \c false if memory allocation fails, else \c true.
  83257. */
  83258. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_append_spaced_points_by_samples(FLAC__StreamMetadata *object, unsigned samples, FLAC__uint64 total_samples);
  83259. /** Sort a seek table's seek points according to the format specification,
  83260. * removing duplicates.
  83261. *
  83262. * \param object A pointer to a seek table to be sorted.
  83263. * \param compact If \c false, behaves like FLAC__format_seektable_sort().
  83264. * If \c true, duplicates are deleted and the seek table is
  83265. * shrunk appropriately; the number of placeholder points
  83266. * present in the seek table will be the same after the call
  83267. * as before.
  83268. * \assert
  83269. * \code object != NULL \endcode
  83270. * \code object->type == FLAC__METADATA_TYPE_SEEKTABLE \endcode
  83271. * \retval FLAC__bool
  83272. * \c false if realloc() fails, else \c true.
  83273. */
  83274. FLAC_API FLAC__bool FLAC__metadata_object_seektable_template_sort(FLAC__StreamMetadata *object, FLAC__bool compact);
  83275. /** Sets the vendor string in a VORBIS_COMMENT block.
  83276. *
  83277. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83278. * one already.
  83279. *
  83280. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83281. * takes ownership of the \c entry.entry pointer.
  83282. *
  83283. * \note If this function returns \c false, the caller still owns the
  83284. * pointer.
  83285. *
  83286. * \param object A pointer to an existing VORBIS_COMMENT object.
  83287. * \param entry The entry to set the vendor string to.
  83288. * \param copy See above.
  83289. * \assert
  83290. * \code object != NULL \endcode
  83291. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83292. * \code (entry.entry != NULL && entry.length > 0) ||
  83293. * (entry.entry == NULL && entry.length == 0) \endcode
  83294. * \retval FLAC__bool
  83295. * \c false if memory allocation fails or \a entry does not comply with the
  83296. * Vorbis comment specification, else \c true.
  83297. */
  83298. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_vendor_string(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  83299. /** Resize the comment array.
  83300. *
  83301. * If the size shrinks, elements will truncated; if it grows, new empty
  83302. * fields will be added to the end.
  83303. *
  83304. * \param object A pointer to an existing VORBIS_COMMENT object.
  83305. * \param new_num_comments The desired length of the array; may be \c 0.
  83306. * \assert
  83307. * \code object != NULL \endcode
  83308. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83309. * \code (object->data.vorbis_comment.comments == NULL && object->data.vorbis_comment.num_comments == 0) ||
  83310. * (object->data.vorbis_comment.comments != NULL && object->data.vorbis_comment.num_comments > 0) \endcode
  83311. * \retval FLAC__bool
  83312. * \c false if memory allocation fails, else \c true.
  83313. */
  83314. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_resize_comments(FLAC__StreamMetadata *object, unsigned new_num_comments);
  83315. /** Sets a comment in a VORBIS_COMMENT block.
  83316. *
  83317. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83318. * one already.
  83319. *
  83320. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83321. * takes ownership of the \c entry.entry pointer.
  83322. *
  83323. * \note If this function returns \c false, the caller still owns the
  83324. * pointer.
  83325. *
  83326. * \param object A pointer to an existing VORBIS_COMMENT object.
  83327. * \param comment_num Index into comment array to set.
  83328. * \param entry The entry to set the comment to.
  83329. * \param copy See above.
  83330. * \assert
  83331. * \code object != NULL \endcode
  83332. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83333. * \code comment_num < object->data.vorbis_comment.num_comments \endcode
  83334. * \code (entry.entry != NULL && entry.length > 0) ||
  83335. * (entry.entry == NULL && entry.length == 0) \endcode
  83336. * \retval FLAC__bool
  83337. * \c false if memory allocation fails or \a entry does not comply with the
  83338. * Vorbis comment specification, else \c true.
  83339. */
  83340. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_set_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  83341. /** Insert a comment in a VORBIS_COMMENT block at the given index.
  83342. *
  83343. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83344. * one already.
  83345. *
  83346. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83347. * takes ownership of the \c entry.entry pointer.
  83348. *
  83349. * \note If this function returns \c false, the caller still owns the
  83350. * pointer.
  83351. *
  83352. * \param object A pointer to an existing VORBIS_COMMENT object.
  83353. * \param comment_num The index at which to insert the comment. The comments
  83354. * at and after \a comment_num move right one position.
  83355. * To append a comment to the end, set \a comment_num to
  83356. * \c object->data.vorbis_comment.num_comments .
  83357. * \param entry The comment to insert.
  83358. * \param copy See above.
  83359. * \assert
  83360. * \code object != NULL \endcode
  83361. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83362. * \code object->data.vorbis_comment.num_comments >= comment_num \endcode
  83363. * \code (entry.entry != NULL && entry.length > 0) ||
  83364. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  83365. * \retval FLAC__bool
  83366. * \c false if memory allocation fails or \a entry does not comply with the
  83367. * Vorbis comment specification, else \c true.
  83368. */
  83369. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_insert_comment(FLAC__StreamMetadata *object, unsigned comment_num, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  83370. /** Appends a comment to a VORBIS_COMMENT block.
  83371. *
  83372. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83373. * one already.
  83374. *
  83375. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83376. * takes ownership of the \c entry.entry pointer.
  83377. *
  83378. * \note If this function returns \c false, the caller still owns the
  83379. * pointer.
  83380. *
  83381. * \param object A pointer to an existing VORBIS_COMMENT object.
  83382. * \param entry The comment to insert.
  83383. * \param copy See above.
  83384. * \assert
  83385. * \code object != NULL \endcode
  83386. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83387. * \code (entry.entry != NULL && entry.length > 0) ||
  83388. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  83389. * \retval FLAC__bool
  83390. * \c false if memory allocation fails or \a entry does not comply with the
  83391. * Vorbis comment specification, else \c true.
  83392. */
  83393. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_append_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool copy);
  83394. /** Replaces comments in a VORBIS_COMMENT block with a new one.
  83395. *
  83396. * For convenience, a trailing NUL is added to the entry if it doesn't have
  83397. * one already.
  83398. *
  83399. * Depending on the the value of \a all, either all or just the first comment
  83400. * whose field name(s) match the given entry's name will be replaced by the
  83401. * given entry. If no comments match, \a entry will simply be appended.
  83402. *
  83403. * If \a copy is \c true, a copy of the entry is stored; otherwise, the object
  83404. * takes ownership of the \c entry.entry pointer.
  83405. *
  83406. * \note If this function returns \c false, the caller still owns the
  83407. * pointer.
  83408. *
  83409. * \param object A pointer to an existing VORBIS_COMMENT object.
  83410. * \param entry The comment to insert.
  83411. * \param all If \c true, all comments whose field name matches
  83412. * \a entry's field name will be removed, and \a entry will
  83413. * be inserted at the position of the first matching
  83414. * comment. If \c false, only the first comment whose
  83415. * field name matches \a entry's field name will be
  83416. * replaced with \a entry.
  83417. * \param copy See above.
  83418. * \assert
  83419. * \code object != NULL \endcode
  83420. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83421. * \code (entry.entry != NULL && entry.length > 0) ||
  83422. * (entry.entry == NULL && entry.length == 0 && copy == false) \endcode
  83423. * \retval FLAC__bool
  83424. * \c false if memory allocation fails or \a entry does not comply with the
  83425. * Vorbis comment specification, else \c true.
  83426. */
  83427. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_replace_comment(FLAC__StreamMetadata *object, FLAC__StreamMetadata_VorbisComment_Entry entry, FLAC__bool all, FLAC__bool copy);
  83428. /** Delete a comment in a VORBIS_COMMENT block at the given index.
  83429. *
  83430. * \param object A pointer to an existing VORBIS_COMMENT object.
  83431. * \param comment_num The index of the comment to delete.
  83432. * \assert
  83433. * \code object != NULL \endcode
  83434. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83435. * \code object->data.vorbis_comment.num_comments > comment_num \endcode
  83436. * \retval FLAC__bool
  83437. * \c false if realloc() fails, else \c true.
  83438. */
  83439. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_delete_comment(FLAC__StreamMetadata *object, unsigned comment_num);
  83440. /** Creates a Vorbis comment entry from NUL-terminated name and value strings.
  83441. *
  83442. * On return, the filled-in \a entry->entry pointer will point to malloc()ed
  83443. * memory and shall be owned by the caller. For convenience the entry will
  83444. * have a terminating NUL.
  83445. *
  83446. * \param entry A pointer to a Vorbis comment entry. The entry's
  83447. * \c entry pointer should not point to allocated
  83448. * memory as it will be overwritten.
  83449. * \param field_name The field name in ASCII, \c NUL terminated.
  83450. * \param field_value The field value in UTF-8, \c NUL terminated.
  83451. * \assert
  83452. * \code entry != NULL \endcode
  83453. * \code field_name != NULL \endcode
  83454. * \code field_value != NULL \endcode
  83455. * \retval FLAC__bool
  83456. * \c false if malloc() fails, or if \a field_name or \a field_value does
  83457. * not comply with the Vorbis comment specification, else \c true.
  83458. */
  83459. 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);
  83460. /** Splits a Vorbis comment entry into NUL-terminated name and value strings.
  83461. *
  83462. * The returned pointers to name and value will be allocated by malloc()
  83463. * and shall be owned by the caller.
  83464. *
  83465. * \param entry An existing Vorbis comment entry.
  83466. * \param field_name The address of where the returned pointer to the
  83467. * field name will be stored.
  83468. * \param field_value The address of where the returned pointer to the
  83469. * field value will be stored.
  83470. * \assert
  83471. * \code (entry.entry != NULL && entry.length > 0) \endcode
  83472. * \code memchr(entry.entry, '=', entry.length) != NULL \endcode
  83473. * \code field_name != NULL \endcode
  83474. * \code field_value != NULL \endcode
  83475. * \retval FLAC__bool
  83476. * \c false if memory allocation fails or \a entry does not comply with the
  83477. * Vorbis comment specification, else \c true.
  83478. */
  83479. 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);
  83480. /** Check if the given Vorbis comment entry's field name matches the given
  83481. * field name.
  83482. *
  83483. * \param entry An existing Vorbis comment entry.
  83484. * \param field_name The field name to check.
  83485. * \param field_name_length The length of \a field_name, not including the
  83486. * terminating \c NUL.
  83487. * \assert
  83488. * \code (entry.entry != NULL && entry.length > 0) \endcode
  83489. * \retval FLAC__bool
  83490. * \c true if the field names match, else \c false
  83491. */
  83492. FLAC_API FLAC__bool FLAC__metadata_object_vorbiscomment_entry_matches(const FLAC__StreamMetadata_VorbisComment_Entry entry, const char *field_name, unsigned field_name_length);
  83493. /** Find a Vorbis comment with the given field name.
  83494. *
  83495. * The search begins at entry number \a offset; use an offset of 0 to
  83496. * search from the beginning of the comment array.
  83497. *
  83498. * \param object A pointer to an existing VORBIS_COMMENT object.
  83499. * \param offset The offset into the comment array from where to start
  83500. * the search.
  83501. * \param field_name The field name of the comment to find.
  83502. * \assert
  83503. * \code object != NULL \endcode
  83504. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83505. * \code field_name != NULL \endcode
  83506. * \retval int
  83507. * The offset in the comment array of the first comment whose field
  83508. * name matches \a field_name, or \c -1 if no match was found.
  83509. */
  83510. FLAC_API int FLAC__metadata_object_vorbiscomment_find_entry_from(const FLAC__StreamMetadata *object, unsigned offset, const char *field_name);
  83511. /** Remove first Vorbis comment matching the given field name.
  83512. *
  83513. * \param object A pointer to an existing VORBIS_COMMENT object.
  83514. * \param field_name The field name of comment to delete.
  83515. * \assert
  83516. * \code object != NULL \endcode
  83517. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83518. * \retval int
  83519. * \c -1 for memory allocation error, \c 0 for no matching entries,
  83520. * \c 1 for one matching entry deleted.
  83521. */
  83522. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entry_matching(FLAC__StreamMetadata *object, const char *field_name);
  83523. /** Remove all Vorbis comments matching the given field name.
  83524. *
  83525. * \param object A pointer to an existing VORBIS_COMMENT object.
  83526. * \param field_name The field name of comments to delete.
  83527. * \assert
  83528. * \code object != NULL \endcode
  83529. * \code object->type == FLAC__METADATA_TYPE_VORBIS_COMMENT \endcode
  83530. * \retval int
  83531. * \c -1 for memory allocation error, \c 0 for no matching entries,
  83532. * else the number of matching entries deleted.
  83533. */
  83534. FLAC_API int FLAC__metadata_object_vorbiscomment_remove_entries_matching(FLAC__StreamMetadata *object, const char *field_name);
  83535. /** Create a new CUESHEET track instance.
  83536. *
  83537. * The object will be "empty"; i.e. values and data pointers will be \c 0.
  83538. *
  83539. * \retval FLAC__StreamMetadata_CueSheet_Track*
  83540. * \c NULL if there was an error allocating memory, else the new instance.
  83541. */
  83542. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_new(void);
  83543. /** Create a copy of an existing CUESHEET track object.
  83544. *
  83545. * The copy is a "deep" copy, i.e. dynamically allocated data within the
  83546. * object is also copied. The caller takes ownership of the new object and
  83547. * is responsible for freeing it with
  83548. * FLAC__metadata_object_cuesheet_track_delete().
  83549. *
  83550. * \param object Pointer to object to copy.
  83551. * \assert
  83552. * \code object != NULL \endcode
  83553. * \retval FLAC__StreamMetadata_CueSheet_Track*
  83554. * \c NULL if there was an error allocating memory, else the new instance.
  83555. */
  83556. FLAC_API FLAC__StreamMetadata_CueSheet_Track *FLAC__metadata_object_cuesheet_track_clone(const FLAC__StreamMetadata_CueSheet_Track *object);
  83557. /** Delete a CUESHEET track object
  83558. *
  83559. * \param object A pointer to an existing CUESHEET track object.
  83560. * \assert
  83561. * \code object != NULL \endcode
  83562. */
  83563. FLAC_API void FLAC__metadata_object_cuesheet_track_delete(FLAC__StreamMetadata_CueSheet_Track *object);
  83564. /** Resize a track's index point array.
  83565. *
  83566. * If the size shrinks, elements will truncated; if it grows, new blank
  83567. * indices will be added to the end.
  83568. *
  83569. * \param object A pointer to an existing CUESHEET object.
  83570. * \param track_num The index of the track to modify. NOTE: this is not
  83571. * necessarily the same as the track's \a number field.
  83572. * \param new_num_indices The desired length of the array; may be \c 0.
  83573. * \assert
  83574. * \code object != NULL \endcode
  83575. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83576. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83577. * \code (object->data.cue_sheet.tracks[track_num].indices == NULL && object->data.cue_sheet.tracks[track_num].num_indices == 0) ||
  83578. * (object->data.cue_sheet.tracks[track_num].indices != NULL && object->data.cue_sheet.tracks[track_num].num_indices > 0) \endcode
  83579. * \retval FLAC__bool
  83580. * \c false if memory allocation error, else \c true.
  83581. */
  83582. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_resize_indices(FLAC__StreamMetadata *object, unsigned track_num, unsigned new_num_indices);
  83583. /** Insert an index point in a CUESHEET track at the given index.
  83584. *
  83585. * \param object A pointer to an existing CUESHEET object.
  83586. * \param track_num The index of the track to modify. NOTE: this is not
  83587. * necessarily the same as the track's \a number field.
  83588. * \param index_num The index into the track's index array at which to
  83589. * insert the index point. NOTE: this is not necessarily
  83590. * the same as the index point's \a number field. The
  83591. * indices at and after \a index_num move right one
  83592. * position. To append an index point to the end, set
  83593. * \a index_num to
  83594. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  83595. * \param index The index point to insert.
  83596. * \assert
  83597. * \code object != NULL \endcode
  83598. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83599. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83600. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  83601. * \retval FLAC__bool
  83602. * \c false if realloc() fails, else \c true.
  83603. */
  83604. 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);
  83605. /** Insert a blank index point in a CUESHEET track at the given index.
  83606. *
  83607. * A blank index point is one in which all field values are zero.
  83608. *
  83609. * \param object A pointer to an existing CUESHEET object.
  83610. * \param track_num The index of the track to modify. NOTE: this is not
  83611. * necessarily the same as the track's \a number field.
  83612. * \param index_num The index into the track's index array at which to
  83613. * insert the index point. NOTE: this is not necessarily
  83614. * the same as the index point's \a number field. The
  83615. * indices at and after \a index_num move right one
  83616. * position. To append an index point to the end, set
  83617. * \a index_num to
  83618. * \c object->data.cue_sheet.tracks[track_num].num_indices .
  83619. * \assert
  83620. * \code object != NULL \endcode
  83621. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83622. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83623. * \code object->data.cue_sheet.tracks[track_num].num_indices >= index_num \endcode
  83624. * \retval FLAC__bool
  83625. * \c false if realloc() fails, else \c true.
  83626. */
  83627. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_insert_blank_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  83628. /** Delete an index point in a CUESHEET track at the given index.
  83629. *
  83630. * \param object A pointer to an existing CUESHEET object.
  83631. * \param track_num The index into the track array of the track to
  83632. * modify. NOTE: this is not necessarily the same
  83633. * as the track's \a number field.
  83634. * \param index_num The index into the track's index array of the index
  83635. * to delete. NOTE: this is not necessarily the same
  83636. * as the index's \a number field.
  83637. * \assert
  83638. * \code object != NULL \endcode
  83639. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83640. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83641. * \code object->data.cue_sheet.tracks[track_num].num_indices > index_num \endcode
  83642. * \retval FLAC__bool
  83643. * \c false if realloc() fails, else \c true.
  83644. */
  83645. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_track_delete_index(FLAC__StreamMetadata *object, unsigned track_num, unsigned index_num);
  83646. /** Resize the track array.
  83647. *
  83648. * If the size shrinks, elements will truncated; if it grows, new blank
  83649. * tracks will be added to the end.
  83650. *
  83651. * \param object A pointer to an existing CUESHEET object.
  83652. * \param new_num_tracks The desired length of the array; may be \c 0.
  83653. * \assert
  83654. * \code object != NULL \endcode
  83655. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83656. * \code (object->data.cue_sheet.tracks == NULL && object->data.cue_sheet.num_tracks == 0) ||
  83657. * (object->data.cue_sheet.tracks != NULL && object->data.cue_sheet.num_tracks > 0) \endcode
  83658. * \retval FLAC__bool
  83659. * \c false if memory allocation error, else \c true.
  83660. */
  83661. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_resize_tracks(FLAC__StreamMetadata *object, unsigned new_num_tracks);
  83662. /** Sets a track in a CUESHEET block.
  83663. *
  83664. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  83665. * takes ownership of the \a track pointer.
  83666. *
  83667. * \param object A pointer to an existing CUESHEET object.
  83668. * \param track_num Index into track array to set. NOTE: this is not
  83669. * necessarily the same as the track's \a number field.
  83670. * \param track The track to set the track to. You may safely pass in
  83671. * a const pointer if \a copy is \c true.
  83672. * \param copy See above.
  83673. * \assert
  83674. * \code object != NULL \endcode
  83675. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83676. * \code track_num < object->data.cue_sheet.num_tracks \endcode
  83677. * \code (track->indices != NULL && track->num_indices > 0) ||
  83678. * (track->indices == NULL && track->num_indices == 0)
  83679. * \retval FLAC__bool
  83680. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83681. */
  83682. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_set_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  83683. /** Insert a track in a CUESHEET block at the given index.
  83684. *
  83685. * If \a copy is \c true, a copy of the track is stored; otherwise, the object
  83686. * takes ownership of the \a track pointer.
  83687. *
  83688. * \param object A pointer to an existing CUESHEET object.
  83689. * \param track_num The index at which to insert the track. NOTE: this
  83690. * is not necessarily the same as the track's \a number
  83691. * field. The tracks at and after \a track_num move right
  83692. * one position. To append a track to the end, set
  83693. * \a track_num to \c object->data.cue_sheet.num_tracks .
  83694. * \param track The track to insert. You may safely pass in a const
  83695. * pointer if \a copy is \c true.
  83696. * \param copy See above.
  83697. * \assert
  83698. * \code object != NULL \endcode
  83699. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83700. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  83701. * \retval FLAC__bool
  83702. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83703. */
  83704. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_track(FLAC__StreamMetadata *object, unsigned track_num, FLAC__StreamMetadata_CueSheet_Track *track, FLAC__bool copy);
  83705. /** Insert a blank track in a CUESHEET block at the given index.
  83706. *
  83707. * A blank track is one in which all field values are zero.
  83708. *
  83709. * \param object A pointer to an existing CUESHEET object.
  83710. * \param track_num The index at which to insert the track. NOTE: this
  83711. * is not necessarily the same as the track's \a number
  83712. * field. The tracks at and after \a track_num move right
  83713. * one position. To append a track to the end, set
  83714. * \a track_num to \c object->data.cue_sheet.num_tracks .
  83715. * \assert
  83716. * \code object != NULL \endcode
  83717. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83718. * \code object->data.cue_sheet.num_tracks >= track_num \endcode
  83719. * \retval FLAC__bool
  83720. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83721. */
  83722. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_insert_blank_track(FLAC__StreamMetadata *object, unsigned track_num);
  83723. /** Delete a track in a CUESHEET block at the given index.
  83724. *
  83725. * \param object A pointer to an existing CUESHEET object.
  83726. * \param track_num The index into the track array of the track to
  83727. * delete. NOTE: this is not necessarily the same
  83728. * as the track's \a number field.
  83729. * \assert
  83730. * \code object != NULL \endcode
  83731. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83732. * \code object->data.cue_sheet.num_tracks > track_num \endcode
  83733. * \retval FLAC__bool
  83734. * \c false if realloc() fails, else \c true.
  83735. */
  83736. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_delete_track(FLAC__StreamMetadata *object, unsigned track_num);
  83737. /** Check a cue sheet to see if it conforms to the FLAC specification.
  83738. * See the format specification for limits on the contents of the
  83739. * cue sheet.
  83740. *
  83741. * \param object A pointer to an existing CUESHEET object.
  83742. * \param check_cd_da_subset If \c true, check CUESHEET against more
  83743. * stringent requirements for a CD-DA (audio) disc.
  83744. * \param violation Address of a pointer to a string. If there is a
  83745. * violation, a pointer to a string explanation of the
  83746. * violation will be returned here. \a violation may be
  83747. * \c NULL if you don't need the returned string. Do not
  83748. * free the returned string; it will always point to static
  83749. * data.
  83750. * \assert
  83751. * \code object != NULL \endcode
  83752. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83753. * \retval FLAC__bool
  83754. * \c false if cue sheet is illegal, else \c true.
  83755. */
  83756. FLAC_API FLAC__bool FLAC__metadata_object_cuesheet_is_legal(const FLAC__StreamMetadata *object, FLAC__bool check_cd_da_subset, const char **violation);
  83757. /** Calculate and return the CDDB/freedb ID for a cue sheet. The function
  83758. * assumes the cue sheet corresponds to a CD; the result is undefined
  83759. * if the cuesheet's is_cd bit is not set.
  83760. *
  83761. * \param object A pointer to an existing CUESHEET object.
  83762. * \assert
  83763. * \code object != NULL \endcode
  83764. * \code object->type == FLAC__METADATA_TYPE_CUESHEET \endcode
  83765. * \retval FLAC__uint32
  83766. * The unsigned integer representation of the CDDB/freedb ID
  83767. */
  83768. FLAC_API FLAC__uint32 FLAC__metadata_object_cuesheet_calculate_cddb_id(const FLAC__StreamMetadata *object);
  83769. /** Sets the MIME type of a PICTURE block.
  83770. *
  83771. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  83772. * takes ownership of the pointer. The existing string will be freed if this
  83773. * function is successful, otherwise the original string will remain if \a copy
  83774. * is \c true and malloc() fails.
  83775. *
  83776. * \note It is safe to pass a const pointer to \a mime_type if \a copy is \c true.
  83777. *
  83778. * \param object A pointer to an existing PICTURE object.
  83779. * \param mime_type A pointer to the MIME type string. The string must be
  83780. * ASCII characters 0x20-0x7e, NUL-terminated. No validation
  83781. * is done.
  83782. * \param copy See above.
  83783. * \assert
  83784. * \code object != NULL \endcode
  83785. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83786. * \code (mime_type != NULL) \endcode
  83787. * \retval FLAC__bool
  83788. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83789. */
  83790. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_mime_type(FLAC__StreamMetadata *object, char *mime_type, FLAC__bool copy);
  83791. /** Sets the description of a PICTURE block.
  83792. *
  83793. * If \a copy is \c true, a copy of the string is stored; otherwise, the object
  83794. * takes ownership of the pointer. The existing string will be freed if this
  83795. * function is successful, otherwise the original string will remain if \a copy
  83796. * is \c true and malloc() fails.
  83797. *
  83798. * \note It is safe to pass a const pointer to \a description if \a copy is \c true.
  83799. *
  83800. * \param object A pointer to an existing PICTURE object.
  83801. * \param description A pointer to the description string. The string must be
  83802. * valid UTF-8, NUL-terminated. No validation is done.
  83803. * \param copy See above.
  83804. * \assert
  83805. * \code object != NULL \endcode
  83806. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83807. * \code (description != NULL) \endcode
  83808. * \retval FLAC__bool
  83809. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83810. */
  83811. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_description(FLAC__StreamMetadata *object, FLAC__byte *description, FLAC__bool copy);
  83812. /** Sets the picture data of a PICTURE block.
  83813. *
  83814. * If \a copy is \c true, a copy of the data is stored; otherwise, the object
  83815. * takes ownership of the pointer. Also sets the \a data_length field of the
  83816. * metadata object to what is passed in as the \a length parameter. The
  83817. * existing data will be freed if this function is successful, otherwise the
  83818. * original data and data_length will remain if \a copy is \c true and
  83819. * malloc() fails.
  83820. *
  83821. * \note It is safe to pass a const pointer to \a data if \a copy is \c true.
  83822. *
  83823. * \param object A pointer to an existing PICTURE object.
  83824. * \param data A pointer to the data to set.
  83825. * \param length The length of \a data in bytes.
  83826. * \param copy See above.
  83827. * \assert
  83828. * \code object != NULL \endcode
  83829. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83830. * \code (data != NULL && length > 0) ||
  83831. * (data == NULL && length == 0 && copy == false) \endcode
  83832. * \retval FLAC__bool
  83833. * \c false if \a copy is \c true and malloc() fails, else \c true.
  83834. */
  83835. FLAC_API FLAC__bool FLAC__metadata_object_picture_set_data(FLAC__StreamMetadata *object, FLAC__byte *data, FLAC__uint32 length, FLAC__bool copy);
  83836. /** Check a PICTURE block to see if it conforms to the FLAC specification.
  83837. * See the format specification for limits on the contents of the
  83838. * PICTURE block.
  83839. *
  83840. * \param object A pointer to existing PICTURE block to be checked.
  83841. * \param violation Address of a pointer to a string. If there is a
  83842. * violation, a pointer to a string explanation of the
  83843. * violation will be returned here. \a violation may be
  83844. * \c NULL if you don't need the returned string. Do not
  83845. * free the returned string; it will always point to static
  83846. * data.
  83847. * \assert
  83848. * \code object != NULL \endcode
  83849. * \code object->type == FLAC__METADATA_TYPE_PICTURE \endcode
  83850. * \retval FLAC__bool
  83851. * \c false if PICTURE block is illegal, else \c true.
  83852. */
  83853. FLAC_API FLAC__bool FLAC__metadata_object_picture_is_legal(const FLAC__StreamMetadata *object, const char **violation);
  83854. /* \} */
  83855. #ifdef __cplusplus
  83856. }
  83857. #endif
  83858. #endif
  83859. /********* End of inlined file: metadata.h *********/
  83860. /********* Start of inlined file: stream_decoder.h *********/
  83861. #ifndef FLAC__STREAM_DECODER_H
  83862. #define FLAC__STREAM_DECODER_H
  83863. #include <stdio.h> /* for FILE */
  83864. #ifdef __cplusplus
  83865. extern "C" {
  83866. #endif
  83867. /** \file include/FLAC/stream_decoder.h
  83868. *
  83869. * \brief
  83870. * This module contains the functions which implement the stream
  83871. * decoder.
  83872. *
  83873. * See the detailed documentation in the
  83874. * \link flac_stream_decoder stream decoder \endlink module.
  83875. */
  83876. /** \defgroup flac_decoder FLAC/ \*_decoder.h: decoder interfaces
  83877. * \ingroup flac
  83878. *
  83879. * \brief
  83880. * This module describes the decoder layers provided by libFLAC.
  83881. *
  83882. * The stream decoder can be used to decode complete streams either from
  83883. * the client via callbacks, or directly from a file, depending on how
  83884. * it is initialized. When decoding via callbacks, the client provides
  83885. * callbacks for reading FLAC data and writing decoded samples, and
  83886. * handling metadata and errors. If the client also supplies seek-related
  83887. * callback, the decoder function for sample-accurate seeking within the
  83888. * FLAC input is also available. When decoding from a file, the client
  83889. * needs only supply a filename or open \c FILE* and write/metadata/error
  83890. * callbacks; the rest of the callbacks are supplied internally. For more
  83891. * info see the \link flac_stream_decoder stream decoder \endlink module.
  83892. */
  83893. /** \defgroup flac_stream_decoder FLAC/stream_decoder.h: stream decoder interface
  83894. * \ingroup flac_decoder
  83895. *
  83896. * \brief
  83897. * This module contains the functions which implement the stream
  83898. * decoder.
  83899. *
  83900. * The stream decoder can decode native FLAC, and optionally Ogg FLAC
  83901. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  83902. *
  83903. * The basic usage of this decoder is as follows:
  83904. * - The program creates an instance of a decoder using
  83905. * FLAC__stream_decoder_new().
  83906. * - The program overrides the default settings using
  83907. * FLAC__stream_decoder_set_*() functions.
  83908. * - The program initializes the instance to validate the settings and
  83909. * prepare for decoding using
  83910. * - FLAC__stream_decoder_init_stream() or FLAC__stream_decoder_init_FILE()
  83911. * or FLAC__stream_decoder_init_file() for native FLAC,
  83912. * - FLAC__stream_decoder_init_ogg_stream() or FLAC__stream_decoder_init_ogg_FILE()
  83913. * or FLAC__stream_decoder_init_ogg_file() for Ogg FLAC
  83914. * - The program calls the FLAC__stream_decoder_process_*() functions
  83915. * to decode data, which subsequently calls the callbacks.
  83916. * - The program finishes the decoding with FLAC__stream_decoder_finish(),
  83917. * which flushes the input and output and resets the decoder to the
  83918. * uninitialized state.
  83919. * - The instance may be used again or deleted with
  83920. * FLAC__stream_decoder_delete().
  83921. *
  83922. * In more detail, the program will create a new instance by calling
  83923. * FLAC__stream_decoder_new(), then call FLAC__stream_decoder_set_*()
  83924. * functions to override the default decoder options, and call
  83925. * one of the FLAC__stream_decoder_init_*() functions.
  83926. *
  83927. * There are three initialization functions for native FLAC, one for
  83928. * setting up the decoder to decode FLAC data from the client via
  83929. * callbacks, and two for decoding directly from a FLAC file.
  83930. *
  83931. * For decoding via callbacks, use FLAC__stream_decoder_init_stream().
  83932. * You must also supply several callbacks for handling I/O. Some (like
  83933. * seeking) are optional, depending on the capabilities of the input.
  83934. *
  83935. * For decoding directly from a file, use FLAC__stream_decoder_init_FILE()
  83936. * or FLAC__stream_decoder_init_file(). Then you must only supply an open
  83937. * \c FILE* or filename and fewer callbacks; the decoder will handle
  83938. * the other callbacks internally.
  83939. *
  83940. * There are three similarly-named init functions for decoding from Ogg
  83941. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  83942. * library has been built with Ogg support.
  83943. *
  83944. * Once the decoder is initialized, your program will call one of several
  83945. * functions to start the decoding process:
  83946. *
  83947. * - FLAC__stream_decoder_process_single() - Tells the decoder to process at
  83948. * most one metadata block or audio frame and return, calling either the
  83949. * metadata callback or write callback, respectively, once. If the decoder
  83950. * loses sync it will return with only the error callback being called.
  83951. * - FLAC__stream_decoder_process_until_end_of_metadata() - Tells the decoder
  83952. * to process the stream from the current location and stop upon reaching
  83953. * the first audio frame. The client will get one metadata, write, or error
  83954. * callback per metadata block, audio frame, or sync error, respectively.
  83955. * - FLAC__stream_decoder_process_until_end_of_stream() - Tells the decoder
  83956. * to process the stream from the current location until the read callback
  83957. * returns FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM or
  83958. * FLAC__STREAM_DECODER_READ_STATUS_ABORT. The client will get one metadata,
  83959. * write, or error callback per metadata block, audio frame, or sync error,
  83960. * respectively.
  83961. *
  83962. * When the decoder has finished decoding (normally or through an abort),
  83963. * the instance is finished by calling FLAC__stream_decoder_finish(), which
  83964. * ensures the decoder is in the correct state and frees memory. Then the
  83965. * instance may be deleted with FLAC__stream_decoder_delete() or initialized
  83966. * again to decode another stream.
  83967. *
  83968. * Seeking is exposed through the FLAC__stream_decoder_seek_absolute() method.
  83969. * At any point after the stream decoder has been initialized, the client can
  83970. * call this function to seek to an exact sample within the stream.
  83971. * Subsequently, the first time the write callback is called it will be
  83972. * passed a (possibly partial) block starting at that sample.
  83973. *
  83974. * If the client cannot seek via the callback interface provided, but still
  83975. * has another way of seeking, it can flush the decoder using
  83976. * FLAC__stream_decoder_flush() and start feeding data from the new position
  83977. * through the read callback.
  83978. *
  83979. * The stream decoder also provides MD5 signature checking. If this is
  83980. * turned on before initialization, FLAC__stream_decoder_finish() will
  83981. * report when the decoded MD5 signature does not match the one stored
  83982. * in the STREAMINFO block. MD5 checking is automatically turned off
  83983. * (until the next FLAC__stream_decoder_reset()) if there is no signature
  83984. * in the STREAMINFO block or when a seek is attempted.
  83985. *
  83986. * The FLAC__stream_decoder_set_metadata_*() functions deserve special
  83987. * attention. By default, the decoder only calls the metadata_callback for
  83988. * the STREAMINFO block. These functions allow you to tell the decoder
  83989. * explicitly which blocks to parse and return via the metadata_callback
  83990. * and/or which to skip. Use a FLAC__stream_decoder_set_metadata_respond_all(),
  83991. * FLAC__stream_decoder_set_metadata_ignore() ... or FLAC__stream_decoder_set_metadata_ignore_all(),
  83992. * FLAC__stream_decoder_set_metadata_respond() ... sequence to exactly specify
  83993. * which blocks to return. Remember that metadata blocks can potentially
  83994. * be big (for example, cover art) so filtering out the ones you don't
  83995. * use can reduce the memory requirements of the decoder. Also note the
  83996. * special forms FLAC__stream_decoder_set_metadata_respond_application(id)
  83997. * and FLAC__stream_decoder_set_metadata_ignore_application(id) for
  83998. * filtering APPLICATION blocks based on the application ID.
  83999. *
  84000. * STREAMINFO and SEEKTABLE blocks are always parsed and used internally, but
  84001. * they still can legally be filtered from the metadata_callback.
  84002. *
  84003. * \note
  84004. * The "set" functions may only be called when the decoder is in the
  84005. * state FLAC__STREAM_DECODER_UNINITIALIZED, i.e. after
  84006. * FLAC__stream_decoder_new() or FLAC__stream_decoder_finish(), but
  84007. * before FLAC__stream_decoder_init_*(). If this is the case they will
  84008. * return \c true, otherwise \c false.
  84009. *
  84010. * \note
  84011. * FLAC__stream_decoder_finish() resets all settings to the constructor
  84012. * defaults, including the callbacks.
  84013. *
  84014. * \{
  84015. */
  84016. /** State values for a FLAC__StreamDecoder
  84017. *
  84018. * The decoder's state can be obtained by calling FLAC__stream_decoder_get_state().
  84019. */
  84020. typedef enum {
  84021. FLAC__STREAM_DECODER_SEARCH_FOR_METADATA = 0,
  84022. /**< The decoder is ready to search for metadata. */
  84023. FLAC__STREAM_DECODER_READ_METADATA,
  84024. /**< The decoder is ready to or is in the process of reading metadata. */
  84025. FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC,
  84026. /**< The decoder is ready to or is in the process of searching for the
  84027. * frame sync code.
  84028. */
  84029. FLAC__STREAM_DECODER_READ_FRAME,
  84030. /**< The decoder is ready to or is in the process of reading a frame. */
  84031. FLAC__STREAM_DECODER_END_OF_STREAM,
  84032. /**< The decoder has reached the end of the stream. */
  84033. FLAC__STREAM_DECODER_OGG_ERROR,
  84034. /**< An error occurred in the underlying Ogg layer. */
  84035. FLAC__STREAM_DECODER_SEEK_ERROR,
  84036. /**< An error occurred while seeking. The decoder must be flushed
  84037. * with FLAC__stream_decoder_flush() or reset with
  84038. * FLAC__stream_decoder_reset() before decoding can continue.
  84039. */
  84040. FLAC__STREAM_DECODER_ABORTED,
  84041. /**< The decoder was aborted by the read callback. */
  84042. FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR,
  84043. /**< An error occurred allocating memory. The decoder is in an invalid
  84044. * state and can no longer be used.
  84045. */
  84046. FLAC__STREAM_DECODER_UNINITIALIZED
  84047. /**< The decoder is in the uninitialized state; one of the
  84048. * FLAC__stream_decoder_init_*() functions must be called before samples
  84049. * can be processed.
  84050. */
  84051. } FLAC__StreamDecoderState;
  84052. /** Maps a FLAC__StreamDecoderState to a C string.
  84053. *
  84054. * Using a FLAC__StreamDecoderState as the index to this array
  84055. * will give the string equivalent. The contents should not be modified.
  84056. */
  84057. extern FLAC_API const char * const FLAC__StreamDecoderStateString[];
  84058. /** Possible return values for the FLAC__stream_decoder_init_*() functions.
  84059. */
  84060. typedef enum {
  84061. FLAC__STREAM_DECODER_INIT_STATUS_OK = 0,
  84062. /**< Initialization was successful. */
  84063. FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  84064. /**< The library was not compiled with support for the given container
  84065. * format.
  84066. */
  84067. FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS,
  84068. /**< A required callback was not supplied. */
  84069. FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR,
  84070. /**< An error occurred allocating memory. */
  84071. FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE,
  84072. /**< fopen() failed in FLAC__stream_decoder_init_file() or
  84073. * FLAC__stream_decoder_init_ogg_file(). */
  84074. FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED
  84075. /**< FLAC__stream_decoder_init_*() was called when the decoder was
  84076. * already initialized, usually because
  84077. * FLAC__stream_decoder_finish() was not called.
  84078. */
  84079. } FLAC__StreamDecoderInitStatus;
  84080. /** Maps a FLAC__StreamDecoderInitStatus to a C string.
  84081. *
  84082. * Using a FLAC__StreamDecoderInitStatus as the index to this array
  84083. * will give the string equivalent. The contents should not be modified.
  84084. */
  84085. extern FLAC_API const char * const FLAC__StreamDecoderInitStatusString[];
  84086. /** Return values for the FLAC__StreamDecoder read callback.
  84087. */
  84088. typedef enum {
  84089. FLAC__STREAM_DECODER_READ_STATUS_CONTINUE,
  84090. /**< The read was OK and decoding can continue. */
  84091. FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM,
  84092. /**< The read was attempted while at the end of the stream. Note that
  84093. * the client must only return this value when the read callback was
  84094. * called when already at the end of the stream. Otherwise, if the read
  84095. * itself moves to the end of the stream, the client should still return
  84096. * the data and \c FLAC__STREAM_DECODER_READ_STATUS_CONTINUE, and then on
  84097. * the next read callback it should return
  84098. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM with a byte count
  84099. * of \c 0.
  84100. */
  84101. FLAC__STREAM_DECODER_READ_STATUS_ABORT
  84102. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84103. } FLAC__StreamDecoderReadStatus;
  84104. /** Maps a FLAC__StreamDecoderReadStatus to a C string.
  84105. *
  84106. * Using a FLAC__StreamDecoderReadStatus as the index to this array
  84107. * will give the string equivalent. The contents should not be modified.
  84108. */
  84109. extern FLAC_API const char * const FLAC__StreamDecoderReadStatusString[];
  84110. /** Return values for the FLAC__StreamDecoder seek callback.
  84111. */
  84112. typedef enum {
  84113. FLAC__STREAM_DECODER_SEEK_STATUS_OK,
  84114. /**< The seek was OK and decoding can continue. */
  84115. FLAC__STREAM_DECODER_SEEK_STATUS_ERROR,
  84116. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84117. FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  84118. /**< Client does not support seeking. */
  84119. } FLAC__StreamDecoderSeekStatus;
  84120. /** Maps a FLAC__StreamDecoderSeekStatus to a C string.
  84121. *
  84122. * Using a FLAC__StreamDecoderSeekStatus as the index to this array
  84123. * will give the string equivalent. The contents should not be modified.
  84124. */
  84125. extern FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[];
  84126. /** Return values for the FLAC__StreamDecoder tell callback.
  84127. */
  84128. typedef enum {
  84129. FLAC__STREAM_DECODER_TELL_STATUS_OK,
  84130. /**< The tell was OK and decoding can continue. */
  84131. FLAC__STREAM_DECODER_TELL_STATUS_ERROR,
  84132. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84133. FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  84134. /**< Client does not support telling the position. */
  84135. } FLAC__StreamDecoderTellStatus;
  84136. /** Maps a FLAC__StreamDecoderTellStatus to a C string.
  84137. *
  84138. * Using a FLAC__StreamDecoderTellStatus as the index to this array
  84139. * will give the string equivalent. The contents should not be modified.
  84140. */
  84141. extern FLAC_API const char * const FLAC__StreamDecoderTellStatusString[];
  84142. /** Return values for the FLAC__StreamDecoder length callback.
  84143. */
  84144. typedef enum {
  84145. FLAC__STREAM_DECODER_LENGTH_STATUS_OK,
  84146. /**< The length call was OK and decoding can continue. */
  84147. FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR,
  84148. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84149. FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  84150. /**< Client does not support reporting the length. */
  84151. } FLAC__StreamDecoderLengthStatus;
  84152. /** Maps a FLAC__StreamDecoderLengthStatus to a C string.
  84153. *
  84154. * Using a FLAC__StreamDecoderLengthStatus as the index to this array
  84155. * will give the string equivalent. The contents should not be modified.
  84156. */
  84157. extern FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[];
  84158. /** Return values for the FLAC__StreamDecoder write callback.
  84159. */
  84160. typedef enum {
  84161. FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE,
  84162. /**< The write was OK and decoding can continue. */
  84163. FLAC__STREAM_DECODER_WRITE_STATUS_ABORT
  84164. /**< An unrecoverable error occurred. The decoder will return from the process call. */
  84165. } FLAC__StreamDecoderWriteStatus;
  84166. /** Maps a FLAC__StreamDecoderWriteStatus to a C string.
  84167. *
  84168. * Using a FLAC__StreamDecoderWriteStatus as the index to this array
  84169. * will give the string equivalent. The contents should not be modified.
  84170. */
  84171. extern FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[];
  84172. /** Possible values passed back to the FLAC__StreamDecoder error callback.
  84173. * \c FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC is the generic catch-
  84174. * all. The rest could be caused by bad sync (false synchronization on
  84175. * data that is not the start of a frame) or corrupted data. The error
  84176. * itself is the decoder's best guess at what happened assuming a correct
  84177. * sync. For example \c FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER
  84178. * could be caused by a correct sync on the start of a frame, but some
  84179. * data in the frame header was corrupted. Or it could be the result of
  84180. * syncing on a point the stream that looked like the starting of a frame
  84181. * but was not. \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  84182. * could be because the decoder encountered a valid frame made by a future
  84183. * version of the encoder which it cannot parse, or because of a false
  84184. * sync making it appear as though an encountered frame was generated by
  84185. * a future encoder.
  84186. */
  84187. typedef enum {
  84188. FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC,
  84189. /**< An error in the stream caused the decoder to lose synchronization. */
  84190. FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER,
  84191. /**< The decoder encountered a corrupted frame header. */
  84192. FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH,
  84193. /**< The frame's data did not match the CRC in the footer. */
  84194. FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM
  84195. /**< The decoder encountered reserved fields in use in the stream. */
  84196. } FLAC__StreamDecoderErrorStatus;
  84197. /** Maps a FLAC__StreamDecoderErrorStatus to a C string.
  84198. *
  84199. * Using a FLAC__StreamDecoderErrorStatus as the index to this array
  84200. * will give the string equivalent. The contents should not be modified.
  84201. */
  84202. extern FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[];
  84203. /***********************************************************************
  84204. *
  84205. * class FLAC__StreamDecoder
  84206. *
  84207. ***********************************************************************/
  84208. struct FLAC__StreamDecoderProtected;
  84209. struct FLAC__StreamDecoderPrivate;
  84210. /** The opaque structure definition for the stream decoder type.
  84211. * See the \link flac_stream_decoder stream decoder module \endlink
  84212. * for a detailed description.
  84213. */
  84214. typedef struct {
  84215. struct FLAC__StreamDecoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  84216. struct FLAC__StreamDecoderPrivate *private_; /* avoid the C++ keyword 'private' */
  84217. } FLAC__StreamDecoder;
  84218. /** Signature for the read callback.
  84219. *
  84220. * A function pointer matching this signature must be passed to
  84221. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84222. * called when the decoder needs more input data. The address of the
  84223. * buffer to be filled is supplied, along with the number of bytes the
  84224. * buffer can hold. The callback may choose to supply less data and
  84225. * modify the byte count but must be careful not to overflow the buffer.
  84226. * The callback then returns a status code chosen from
  84227. * FLAC__StreamDecoderReadStatus.
  84228. *
  84229. * Here is an example of a read callback for stdio streams:
  84230. * \code
  84231. * FLAC__StreamDecoderReadStatus read_cb(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  84232. * {
  84233. * FILE *file = ((MyClientData*)client_data)->file;
  84234. * if(*bytes > 0) {
  84235. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  84236. * if(ferror(file))
  84237. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  84238. * else if(*bytes == 0)
  84239. * return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  84240. * else
  84241. * return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  84242. * }
  84243. * else
  84244. * return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  84245. * }
  84246. * \endcode
  84247. *
  84248. * \note In general, FLAC__StreamDecoder functions which change the
  84249. * state should not be called on the \a decoder while in the callback.
  84250. *
  84251. * \param decoder The decoder instance calling the callback.
  84252. * \param buffer A pointer to a location for the callee to store
  84253. * data to be decoded.
  84254. * \param bytes A pointer to the size of the buffer. On entry
  84255. * to the callback, it contains the maximum number
  84256. * of bytes that may be stored in \a buffer. The
  84257. * callee must set it to the actual number of bytes
  84258. * stored (0 in case of error or end-of-stream) before
  84259. * returning.
  84260. * \param client_data The callee's client data set through
  84261. * FLAC__stream_decoder_init_*().
  84262. * \retval FLAC__StreamDecoderReadStatus
  84263. * The callee's return status. Note that the callback should return
  84264. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM if and only if
  84265. * zero bytes were read and there is no more data to be read.
  84266. */
  84267. typedef FLAC__StreamDecoderReadStatus (*FLAC__StreamDecoderReadCallback)(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  84268. /** Signature for the seek callback.
  84269. *
  84270. * A function pointer matching this signature may be passed to
  84271. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84272. * called when the decoder needs to seek the input stream. The decoder
  84273. * will pass the absolute byte offset to seek to, 0 meaning the
  84274. * beginning of the stream.
  84275. *
  84276. * Here is an example of a seek callback for stdio streams:
  84277. * \code
  84278. * FLAC__StreamDecoderSeekStatus seek_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  84279. * {
  84280. * FILE *file = ((MyClientData*)client_data)->file;
  84281. * if(file == stdin)
  84282. * return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  84283. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  84284. * return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  84285. * else
  84286. * return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  84287. * }
  84288. * \endcode
  84289. *
  84290. * \note In general, FLAC__StreamDecoder functions which change the
  84291. * state should not be called on the \a decoder while in the callback.
  84292. *
  84293. * \param decoder The decoder instance calling the callback.
  84294. * \param absolute_byte_offset The offset from the beginning of the stream
  84295. * to seek to.
  84296. * \param client_data The callee's client data set through
  84297. * FLAC__stream_decoder_init_*().
  84298. * \retval FLAC__StreamDecoderSeekStatus
  84299. * The callee's return status.
  84300. */
  84301. typedef FLAC__StreamDecoderSeekStatus (*FLAC__StreamDecoderSeekCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  84302. /** Signature for the tell callback.
  84303. *
  84304. * A function pointer matching this signature may be passed to
  84305. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84306. * called when the decoder wants to know the current position of the
  84307. * stream. The callback should return the byte offset from the
  84308. * beginning of the stream.
  84309. *
  84310. * Here is an example of a tell callback for stdio streams:
  84311. * \code
  84312. * FLAC__StreamDecoderTellStatus tell_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  84313. * {
  84314. * FILE *file = ((MyClientData*)client_data)->file;
  84315. * off_t pos;
  84316. * if(file == stdin)
  84317. * return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  84318. * else if((pos = ftello(file)) < 0)
  84319. * return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  84320. * else {
  84321. * *absolute_byte_offset = (FLAC__uint64)pos;
  84322. * return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  84323. * }
  84324. * }
  84325. * \endcode
  84326. *
  84327. * \note In general, FLAC__StreamDecoder functions which change the
  84328. * state should not be called on the \a decoder while in the callback.
  84329. *
  84330. * \param decoder The decoder instance calling the callback.
  84331. * \param absolute_byte_offset A pointer to storage for the current offset
  84332. * from the beginning of the stream.
  84333. * \param client_data The callee's client data set through
  84334. * FLAC__stream_decoder_init_*().
  84335. * \retval FLAC__StreamDecoderTellStatus
  84336. * The callee's return status.
  84337. */
  84338. typedef FLAC__StreamDecoderTellStatus (*FLAC__StreamDecoderTellCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  84339. /** Signature for the length callback.
  84340. *
  84341. * A function pointer matching this signature may be passed to
  84342. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84343. * called when the decoder wants to know the total length of the stream
  84344. * in bytes.
  84345. *
  84346. * Here is an example of a length callback for stdio streams:
  84347. * \code
  84348. * FLAC__StreamDecoderLengthStatus length_cb(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  84349. * {
  84350. * FILE *file = ((MyClientData*)client_data)->file;
  84351. * struct stat filestats;
  84352. *
  84353. * if(file == stdin)
  84354. * return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  84355. * else if(fstat(fileno(file), &filestats) != 0)
  84356. * return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  84357. * else {
  84358. * *stream_length = (FLAC__uint64)filestats.st_size;
  84359. * return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  84360. * }
  84361. * }
  84362. * \endcode
  84363. *
  84364. * \note In general, FLAC__StreamDecoder functions which change the
  84365. * state should not be called on the \a decoder while in the callback.
  84366. *
  84367. * \param decoder The decoder instance calling the callback.
  84368. * \param stream_length A pointer to storage for the length of the stream
  84369. * in bytes.
  84370. * \param client_data The callee's client data set through
  84371. * FLAC__stream_decoder_init_*().
  84372. * \retval FLAC__StreamDecoderLengthStatus
  84373. * The callee's return status.
  84374. */
  84375. typedef FLAC__StreamDecoderLengthStatus (*FLAC__StreamDecoderLengthCallback)(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  84376. /** Signature for the EOF callback.
  84377. *
  84378. * A function pointer matching this signature may be passed to
  84379. * FLAC__stream_decoder_init*_stream(). The supplied function will be
  84380. * called when the decoder needs to know if the end of the stream has
  84381. * been reached.
  84382. *
  84383. * Here is an example of a EOF callback for stdio streams:
  84384. * FLAC__bool eof_cb(const FLAC__StreamDecoder *decoder, void *client_data)
  84385. * \code
  84386. * {
  84387. * FILE *file = ((MyClientData*)client_data)->file;
  84388. * return feof(file)? true : false;
  84389. * }
  84390. * \endcode
  84391. *
  84392. * \note In general, FLAC__StreamDecoder functions which change the
  84393. * state should not be called on the \a decoder while in the callback.
  84394. *
  84395. * \param decoder The decoder instance calling the callback.
  84396. * \param client_data The callee's client data set through
  84397. * FLAC__stream_decoder_init_*().
  84398. * \retval FLAC__bool
  84399. * \c true if the currently at the end of the stream, else \c false.
  84400. */
  84401. typedef FLAC__bool (*FLAC__StreamDecoderEofCallback)(const FLAC__StreamDecoder *decoder, void *client_data);
  84402. /** Signature for the write callback.
  84403. *
  84404. * A function pointer matching this signature must be passed to one of
  84405. * the FLAC__stream_decoder_init_*() functions.
  84406. * The supplied function will be called when the decoder has decoded a
  84407. * single audio frame. The decoder will pass the frame metadata as well
  84408. * as an array of pointers (one for each channel) pointing to the
  84409. * decoded audio.
  84410. *
  84411. * \note In general, FLAC__StreamDecoder functions which change the
  84412. * state should not be called on the \a decoder while in the callback.
  84413. *
  84414. * \param decoder The decoder instance calling the callback.
  84415. * \param frame The description of the decoded frame. See
  84416. * FLAC__Frame.
  84417. * \param buffer An array of pointers to decoded channels of data.
  84418. * Each pointer will point to an array of signed
  84419. * samples of length \a frame->header.blocksize.
  84420. * Channels will be ordered according to the FLAC
  84421. * specification; see the documentation for the
  84422. * <A HREF="../format.html#frame_header">frame header</A>.
  84423. * \param client_data The callee's client data set through
  84424. * FLAC__stream_decoder_init_*().
  84425. * \retval FLAC__StreamDecoderWriteStatus
  84426. * The callee's return status.
  84427. */
  84428. typedef FLAC__StreamDecoderWriteStatus (*FLAC__StreamDecoderWriteCallback)(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  84429. /** Signature for the metadata callback.
  84430. *
  84431. * A function pointer matching this signature must be passed to one of
  84432. * the FLAC__stream_decoder_init_*() functions.
  84433. * The supplied function will be called when the decoder has decoded a
  84434. * metadata block. In a valid FLAC file there will always be one
  84435. * \c STREAMINFO block, followed by zero or more other metadata blocks.
  84436. * These will be supplied by the decoder in the same order as they
  84437. * appear in the stream and always before the first audio frame (i.e.
  84438. * write callback). The metadata block that is passed in must not be
  84439. * modified, and it doesn't live beyond the callback, so you should make
  84440. * a copy of it with FLAC__metadata_object_clone() if you will need it
  84441. * elsewhere. Since metadata blocks can potentially be large, by
  84442. * default the decoder only calls the metadata callback for the
  84443. * \c STREAMINFO block; you can instruct the decoder to pass or filter
  84444. * other blocks with FLAC__stream_decoder_set_metadata_*() calls.
  84445. *
  84446. * \note In general, FLAC__StreamDecoder functions which change the
  84447. * state should not be called on the \a decoder while in the callback.
  84448. *
  84449. * \param decoder The decoder instance calling the callback.
  84450. * \param metadata The decoded metadata block.
  84451. * \param client_data The callee's client data set through
  84452. * FLAC__stream_decoder_init_*().
  84453. */
  84454. typedef void (*FLAC__StreamDecoderMetadataCallback)(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  84455. /** Signature for the error callback.
  84456. *
  84457. * A function pointer matching this signature must be passed to one of
  84458. * the FLAC__stream_decoder_init_*() functions.
  84459. * The supplied function will be called whenever an error occurs during
  84460. * decoding.
  84461. *
  84462. * \note In general, FLAC__StreamDecoder functions which change the
  84463. * state should not be called on the \a decoder while in the callback.
  84464. *
  84465. * \param decoder The decoder instance calling the callback.
  84466. * \param status The error encountered by the decoder.
  84467. * \param client_data The callee's client data set through
  84468. * FLAC__stream_decoder_init_*().
  84469. */
  84470. typedef void (*FLAC__StreamDecoderErrorCallback)(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  84471. /***********************************************************************
  84472. *
  84473. * Class constructor/destructor
  84474. *
  84475. ***********************************************************************/
  84476. /** Create a new stream decoder instance. The instance is created with
  84477. * default settings; see the individual FLAC__stream_decoder_set_*()
  84478. * functions for each setting's default.
  84479. *
  84480. * \retval FLAC__StreamDecoder*
  84481. * \c NULL if there was an error allocating memory, else the new instance.
  84482. */
  84483. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void);
  84484. /** Free a decoder instance. Deletes the object pointed to by \a decoder.
  84485. *
  84486. * \param decoder A pointer to an existing decoder.
  84487. * \assert
  84488. * \code decoder != NULL \endcode
  84489. */
  84490. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder);
  84491. /***********************************************************************
  84492. *
  84493. * Public class method prototypes
  84494. *
  84495. ***********************************************************************/
  84496. /** Set the serial number for the FLAC stream within the Ogg container.
  84497. * The default behavior is to use the serial number of the first Ogg
  84498. * page. Setting a serial number here will explicitly specify which
  84499. * stream is to be decoded.
  84500. *
  84501. * \note
  84502. * This does not need to be set for native FLAC decoding.
  84503. *
  84504. * \default \c use serial number of first page
  84505. * \param decoder A decoder instance to set.
  84506. * \param serial_number See above.
  84507. * \assert
  84508. * \code decoder != NULL \endcode
  84509. * \retval FLAC__bool
  84510. * \c false if the decoder is already initialized, else \c true.
  84511. */
  84512. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long serial_number);
  84513. /** Set the "MD5 signature checking" flag. If \c true, the decoder will
  84514. * compute the MD5 signature of the unencoded audio data while decoding
  84515. * and compare it to the signature from the STREAMINFO block, if it
  84516. * exists, during FLAC__stream_decoder_finish().
  84517. *
  84518. * MD5 signature checking will be turned off (until the next
  84519. * FLAC__stream_decoder_reset()) if there is no signature in the
  84520. * STREAMINFO block or when a seek is attempted.
  84521. *
  84522. * Clients that do not use the MD5 check should leave this off to speed
  84523. * up decoding.
  84524. *
  84525. * \default \c false
  84526. * \param decoder A decoder instance to set.
  84527. * \param value Flag value (see above).
  84528. * \assert
  84529. * \code decoder != NULL \endcode
  84530. * \retval FLAC__bool
  84531. * \c false if the decoder is already initialized, else \c true.
  84532. */
  84533. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value);
  84534. /** Direct the decoder to pass on all metadata blocks of type \a type.
  84535. *
  84536. * \default By default, only the \c STREAMINFO block is returned via the
  84537. * metadata callback.
  84538. * \param decoder A decoder instance to set.
  84539. * \param type See above.
  84540. * \assert
  84541. * \code decoder != NULL \endcode
  84542. * \a type is valid
  84543. * \retval FLAC__bool
  84544. * \c false if the decoder is already initialized, else \c true.
  84545. */
  84546. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  84547. /** Direct the decoder to pass on all APPLICATION metadata blocks of the
  84548. * given \a id.
  84549. *
  84550. * \default By default, only the \c STREAMINFO block is returned via the
  84551. * metadata callback.
  84552. * \param decoder A decoder instance to set.
  84553. * \param id See above.
  84554. * \assert
  84555. * \code decoder != NULL \endcode
  84556. * \code id != NULL \endcode
  84557. * \retval FLAC__bool
  84558. * \c false if the decoder is already initialized, else \c true.
  84559. */
  84560. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  84561. /** Direct the decoder to pass on all metadata blocks of any type.
  84562. *
  84563. * \default By default, only the \c STREAMINFO block is returned via the
  84564. * metadata callback.
  84565. * \param decoder A decoder instance to set.
  84566. * \assert
  84567. * \code decoder != NULL \endcode
  84568. * \retval FLAC__bool
  84569. * \c false if the decoder is already initialized, else \c true.
  84570. */
  84571. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder);
  84572. /** Direct the decoder to filter out all metadata blocks of type \a type.
  84573. *
  84574. * \default By default, only the \c STREAMINFO block is returned via the
  84575. * metadata callback.
  84576. * \param decoder A decoder instance to set.
  84577. * \param type See above.
  84578. * \assert
  84579. * \code decoder != NULL \endcode
  84580. * \a type is valid
  84581. * \retval FLAC__bool
  84582. * \c false if the decoder is already initialized, else \c true.
  84583. */
  84584. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type);
  84585. /** Direct the decoder to filter out all APPLICATION metadata blocks of
  84586. * the given \a id.
  84587. *
  84588. * \default By default, only the \c STREAMINFO block is returned via the
  84589. * metadata callback.
  84590. * \param decoder A decoder instance to set.
  84591. * \param id See above.
  84592. * \assert
  84593. * \code decoder != NULL \endcode
  84594. * \code id != NULL \endcode
  84595. * \retval FLAC__bool
  84596. * \c false if the decoder is already initialized, else \c true.
  84597. */
  84598. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4]);
  84599. /** Direct the decoder to filter out all metadata blocks of any type.
  84600. *
  84601. * \default By default, only the \c STREAMINFO block is returned via the
  84602. * metadata callback.
  84603. * \param decoder A decoder instance to set.
  84604. * \assert
  84605. * \code decoder != NULL \endcode
  84606. * \retval FLAC__bool
  84607. * \c false if the decoder is already initialized, else \c true.
  84608. */
  84609. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder);
  84610. /** Get the current decoder state.
  84611. *
  84612. * \param decoder A decoder instance to query.
  84613. * \assert
  84614. * \code decoder != NULL \endcode
  84615. * \retval FLAC__StreamDecoderState
  84616. * The current decoder state.
  84617. */
  84618. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder);
  84619. /** Get the current decoder state as a C string.
  84620. *
  84621. * \param decoder A decoder instance to query.
  84622. * \assert
  84623. * \code decoder != NULL \endcode
  84624. * \retval const char *
  84625. * The decoder state as a C string. Do not modify the contents.
  84626. */
  84627. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder);
  84628. /** Get the "MD5 signature checking" flag.
  84629. * This is the value of the setting, not whether or not the decoder is
  84630. * currently checking the MD5 (remember, it can be turned off automatically
  84631. * by a seek). When the decoder is reset the flag will be restored to the
  84632. * value returned by this function.
  84633. *
  84634. * \param decoder A decoder instance to query.
  84635. * \assert
  84636. * \code decoder != NULL \endcode
  84637. * \retval FLAC__bool
  84638. * See above.
  84639. */
  84640. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder);
  84641. /** Get the total number of samples in the stream being decoded.
  84642. * Will only be valid after decoding has started and will contain the
  84643. * value from the \c STREAMINFO block. A value of \c 0 means "unknown".
  84644. *
  84645. * \param decoder A decoder instance to query.
  84646. * \assert
  84647. * \code decoder != NULL \endcode
  84648. * \retval unsigned
  84649. * See above.
  84650. */
  84651. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder);
  84652. /** Get the current number of channels in the stream being decoded.
  84653. * Will only be valid after decoding has started and will contain the
  84654. * value from the most recently decoded frame header.
  84655. *
  84656. * \param decoder A decoder instance to query.
  84657. * \assert
  84658. * \code decoder != NULL \endcode
  84659. * \retval unsigned
  84660. * See above.
  84661. */
  84662. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder);
  84663. /** Get the current channel assignment in the stream being decoded.
  84664. * Will only be valid after decoding has started and will contain the
  84665. * value from the most recently decoded frame header.
  84666. *
  84667. * \param decoder A decoder instance to query.
  84668. * \assert
  84669. * \code decoder != NULL \endcode
  84670. * \retval FLAC__ChannelAssignment
  84671. * See above.
  84672. */
  84673. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder);
  84674. /** Get the current sample resolution in the stream being decoded.
  84675. * Will only be valid after decoding has started and will contain the
  84676. * value from the most recently decoded frame header.
  84677. *
  84678. * \param decoder A decoder instance to query.
  84679. * \assert
  84680. * \code decoder != NULL \endcode
  84681. * \retval unsigned
  84682. * See above.
  84683. */
  84684. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder);
  84685. /** Get the current sample rate in Hz of the stream being decoded.
  84686. * Will only be valid after decoding has started and will contain the
  84687. * value from the most recently decoded frame header.
  84688. *
  84689. * \param decoder A decoder instance to query.
  84690. * \assert
  84691. * \code decoder != NULL \endcode
  84692. * \retval unsigned
  84693. * See above.
  84694. */
  84695. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder);
  84696. /** Get the current blocksize of the stream being decoded.
  84697. * Will only be valid after decoding has started and will contain the
  84698. * value from the most recently decoded frame header.
  84699. *
  84700. * \param decoder A decoder instance to query.
  84701. * \assert
  84702. * \code decoder != NULL \endcode
  84703. * \retval unsigned
  84704. * See above.
  84705. */
  84706. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder);
  84707. /** Returns the decoder's current read position within the stream.
  84708. * The position is the byte offset from the start of the stream.
  84709. * Bytes before this position have been fully decoded. Note that
  84710. * there may still be undecoded bytes in the decoder's read FIFO.
  84711. * The returned position is correct even after a seek.
  84712. *
  84713. * \warning This function currently only works for native FLAC,
  84714. * not Ogg FLAC streams.
  84715. *
  84716. * \param decoder A decoder instance to query.
  84717. * \param position Address at which to return the desired position.
  84718. * \assert
  84719. * \code decoder != NULL \endcode
  84720. * \code position != NULL \endcode
  84721. * \retval FLAC__bool
  84722. * \c true if successful, \c false if the stream is not native FLAC,
  84723. * or there was an error from the 'tell' callback or it returned
  84724. * \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED.
  84725. */
  84726. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position);
  84727. /** Initialize the decoder instance to decode native FLAC streams.
  84728. *
  84729. * This flavor of initialization sets up the decoder to decode from a
  84730. * native FLAC stream. I/O is performed via callbacks to the client.
  84731. * For decoding from a plain file via filename or open FILE*,
  84732. * FLAC__stream_decoder_init_file() and FLAC__stream_decoder_init_FILE()
  84733. * provide a simpler interface.
  84734. *
  84735. * This function should be called after FLAC__stream_decoder_new() and
  84736. * FLAC__stream_decoder_set_*() but before any of the
  84737. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84738. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84739. * if initialization succeeded.
  84740. *
  84741. * \param decoder An uninitialized decoder instance.
  84742. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  84743. * pointer must not be \c NULL.
  84744. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  84745. * pointer may be \c NULL if seeking is not
  84746. * supported. If \a seek_callback is not \c NULL then a
  84747. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  84748. * Alternatively, a dummy seek callback that just
  84749. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  84750. * may also be supplied, all though this is slightly
  84751. * less efficient for the decoder.
  84752. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  84753. * pointer may be \c NULL if not supported by the client. If
  84754. * \a seek_callback is not \c NULL then a
  84755. * \a tell_callback must also be supplied.
  84756. * Alternatively, a dummy tell callback that just
  84757. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  84758. * may also be supplied, all though this is slightly
  84759. * less efficient for the decoder.
  84760. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  84761. * pointer may be \c NULL if not supported by the client. If
  84762. * \a seek_callback is not \c NULL then a
  84763. * \a length_callback must also be supplied.
  84764. * Alternatively, a dummy length callback that just
  84765. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  84766. * may also be supplied, all though this is slightly
  84767. * less efficient for the decoder.
  84768. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  84769. * pointer may be \c NULL if not supported by the client. If
  84770. * \a seek_callback is not \c NULL then a
  84771. * \a eof_callback must also be supplied.
  84772. * Alternatively, a dummy length callback that just
  84773. * returns \c false
  84774. * may also be supplied, all though this is slightly
  84775. * less efficient for the decoder.
  84776. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84777. * pointer must not be \c NULL.
  84778. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84779. * pointer may be \c NULL if the callback is not
  84780. * desired.
  84781. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84782. * pointer must not be \c NULL.
  84783. * \param client_data This value will be supplied to callbacks in their
  84784. * \a client_data argument.
  84785. * \assert
  84786. * \code decoder != NULL \endcode
  84787. * \retval FLAC__StreamDecoderInitStatus
  84788. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84789. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84790. */
  84791. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  84792. FLAC__StreamDecoder *decoder,
  84793. FLAC__StreamDecoderReadCallback read_callback,
  84794. FLAC__StreamDecoderSeekCallback seek_callback,
  84795. FLAC__StreamDecoderTellCallback tell_callback,
  84796. FLAC__StreamDecoderLengthCallback length_callback,
  84797. FLAC__StreamDecoderEofCallback eof_callback,
  84798. FLAC__StreamDecoderWriteCallback write_callback,
  84799. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84800. FLAC__StreamDecoderErrorCallback error_callback,
  84801. void *client_data
  84802. );
  84803. /** Initialize the decoder instance to decode Ogg FLAC streams.
  84804. *
  84805. * This flavor of initialization sets up the decoder to decode from a
  84806. * FLAC stream in an Ogg container. I/O is performed via callbacks to the
  84807. * client. For decoding from a plain file via filename or open FILE*,
  84808. * FLAC__stream_decoder_init_ogg_file() and FLAC__stream_decoder_init_ogg_FILE()
  84809. * provide a simpler interface.
  84810. *
  84811. * This function should be called after FLAC__stream_decoder_new() and
  84812. * FLAC__stream_decoder_set_*() but before any of the
  84813. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84814. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84815. * if initialization succeeded.
  84816. *
  84817. * \note Support for Ogg FLAC in the library is optional. If this
  84818. * library has been built without support for Ogg FLAC, this function
  84819. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  84820. *
  84821. * \param decoder An uninitialized decoder instance.
  84822. * \param read_callback See FLAC__StreamDecoderReadCallback. This
  84823. * pointer must not be \c NULL.
  84824. * \param seek_callback See FLAC__StreamDecoderSeekCallback. This
  84825. * pointer may be \c NULL if seeking is not
  84826. * supported. If \a seek_callback is not \c NULL then a
  84827. * \a tell_callback, \a length_callback, and \a eof_callback must also be supplied.
  84828. * Alternatively, a dummy seek callback that just
  84829. * returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED
  84830. * may also be supplied, all though this is slightly
  84831. * less efficient for the decoder.
  84832. * \param tell_callback See FLAC__StreamDecoderTellCallback. This
  84833. * pointer may be \c NULL if not supported by the client. If
  84834. * \a seek_callback is not \c NULL then a
  84835. * \a tell_callback must also be supplied.
  84836. * Alternatively, a dummy tell callback that just
  84837. * returns \c FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED
  84838. * may also be supplied, all though this is slightly
  84839. * less efficient for the decoder.
  84840. * \param length_callback See FLAC__StreamDecoderLengthCallback. This
  84841. * pointer may be \c NULL if not supported by the client. If
  84842. * \a seek_callback is not \c NULL then a
  84843. * \a length_callback must also be supplied.
  84844. * Alternatively, a dummy length callback that just
  84845. * returns \c FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED
  84846. * may also be supplied, all though this is slightly
  84847. * less efficient for the decoder.
  84848. * \param eof_callback See FLAC__StreamDecoderEofCallback. This
  84849. * pointer may be \c NULL if not supported by the client. If
  84850. * \a seek_callback is not \c NULL then a
  84851. * \a eof_callback must also be supplied.
  84852. * Alternatively, a dummy length callback that just
  84853. * returns \c false
  84854. * may also be supplied, all though this is slightly
  84855. * less efficient for the decoder.
  84856. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84857. * pointer must not be \c NULL.
  84858. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84859. * pointer may be \c NULL if the callback is not
  84860. * desired.
  84861. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84862. * pointer must not be \c NULL.
  84863. * \param client_data This value will be supplied to callbacks in their
  84864. * \a client_data argument.
  84865. * \assert
  84866. * \code decoder != NULL \endcode
  84867. * \retval FLAC__StreamDecoderInitStatus
  84868. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84869. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84870. */
  84871. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  84872. FLAC__StreamDecoder *decoder,
  84873. FLAC__StreamDecoderReadCallback read_callback,
  84874. FLAC__StreamDecoderSeekCallback seek_callback,
  84875. FLAC__StreamDecoderTellCallback tell_callback,
  84876. FLAC__StreamDecoderLengthCallback length_callback,
  84877. FLAC__StreamDecoderEofCallback eof_callback,
  84878. FLAC__StreamDecoderWriteCallback write_callback,
  84879. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84880. FLAC__StreamDecoderErrorCallback error_callback,
  84881. void *client_data
  84882. );
  84883. /** Initialize the decoder instance to decode native FLAC files.
  84884. *
  84885. * This flavor of initialization sets up the decoder to decode from a
  84886. * plain native FLAC file. For non-stdio streams, you must use
  84887. * FLAC__stream_decoder_init_stream() and provide callbacks for the I/O.
  84888. *
  84889. * This function should be called after FLAC__stream_decoder_new() and
  84890. * FLAC__stream_decoder_set_*() but before any of the
  84891. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84892. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84893. * if initialization succeeded.
  84894. *
  84895. * \param decoder An uninitialized decoder instance.
  84896. * \param file An open FLAC file. The file should have been
  84897. * opened with mode \c "rb" and rewound. The file
  84898. * becomes owned by the decoder and should not be
  84899. * manipulated by the client while decoding.
  84900. * Unless \a file is \c stdin, it will be closed
  84901. * when FLAC__stream_decoder_finish() is called.
  84902. * Note however that seeking will not work when
  84903. * decoding from \c stdout since it is not seekable.
  84904. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84905. * pointer must not be \c NULL.
  84906. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84907. * pointer may be \c NULL if the callback is not
  84908. * desired.
  84909. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84910. * pointer must not be \c NULL.
  84911. * \param client_data This value will be supplied to callbacks in their
  84912. * \a client_data argument.
  84913. * \assert
  84914. * \code decoder != NULL \endcode
  84915. * \code file != NULL \endcode
  84916. * \retval FLAC__StreamDecoderInitStatus
  84917. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84918. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84919. */
  84920. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  84921. FLAC__StreamDecoder *decoder,
  84922. FILE *file,
  84923. FLAC__StreamDecoderWriteCallback write_callback,
  84924. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84925. FLAC__StreamDecoderErrorCallback error_callback,
  84926. void *client_data
  84927. );
  84928. /** Initialize the decoder instance to decode Ogg FLAC files.
  84929. *
  84930. * This flavor of initialization sets up the decoder to decode from a
  84931. * plain Ogg FLAC file. For non-stdio streams, you must use
  84932. * FLAC__stream_decoder_init_ogg_stream() and provide callbacks for the I/O.
  84933. *
  84934. * This function should be called after FLAC__stream_decoder_new() and
  84935. * FLAC__stream_decoder_set_*() but before any of the
  84936. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84937. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84938. * if initialization succeeded.
  84939. *
  84940. * \note Support for Ogg FLAC in the library is optional. If this
  84941. * library has been built without support for Ogg FLAC, this function
  84942. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  84943. *
  84944. * \param decoder An uninitialized decoder instance.
  84945. * \param file An open FLAC file. The file should have been
  84946. * opened with mode \c "rb" and rewound. The file
  84947. * becomes owned by the decoder and should not be
  84948. * manipulated by the client while decoding.
  84949. * Unless \a file is \c stdin, it will be closed
  84950. * when FLAC__stream_decoder_finish() is called.
  84951. * Note however that seeking will not work when
  84952. * decoding from \c stdout since it is not seekable.
  84953. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84954. * pointer must not be \c NULL.
  84955. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84956. * pointer may be \c NULL if the callback is not
  84957. * desired.
  84958. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  84959. * pointer must not be \c NULL.
  84960. * \param client_data This value will be supplied to callbacks in their
  84961. * \a client_data argument.
  84962. * \assert
  84963. * \code decoder != NULL \endcode
  84964. * \code file != NULL \endcode
  84965. * \retval FLAC__StreamDecoderInitStatus
  84966. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  84967. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  84968. */
  84969. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  84970. FLAC__StreamDecoder *decoder,
  84971. FILE *file,
  84972. FLAC__StreamDecoderWriteCallback write_callback,
  84973. FLAC__StreamDecoderMetadataCallback metadata_callback,
  84974. FLAC__StreamDecoderErrorCallback error_callback,
  84975. void *client_data
  84976. );
  84977. /** Initialize the decoder instance to decode native FLAC files.
  84978. *
  84979. * This flavor of initialization sets up the decoder to decode from a plain
  84980. * native FLAC file. If POSIX fopen() semantics are not sufficient, (for
  84981. * example, with Unicode filenames on Windows), you must use
  84982. * FLAC__stream_decoder_init_FILE(), or FLAC__stream_decoder_init_stream()
  84983. * and provide callbacks for the I/O.
  84984. *
  84985. * This function should be called after FLAC__stream_decoder_new() and
  84986. * FLAC__stream_decoder_set_*() but before any of the
  84987. * FLAC__stream_decoder_process_*() functions. Will set and return the
  84988. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  84989. * if initialization succeeded.
  84990. *
  84991. * \param decoder An uninitialized decoder instance.
  84992. * \param filename The name of the file to decode from. The file will
  84993. * be opened with fopen(). Use \c NULL to decode from
  84994. * \c stdin. Note that \c stdin is not seekable.
  84995. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  84996. * pointer must not be \c NULL.
  84997. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  84998. * pointer may be \c NULL if the callback is not
  84999. * desired.
  85000. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85001. * pointer must not be \c NULL.
  85002. * \param client_data This value will be supplied to callbacks in their
  85003. * \a client_data argument.
  85004. * \assert
  85005. * \code decoder != NULL \endcode
  85006. * \retval FLAC__StreamDecoderInitStatus
  85007. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85008. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85009. */
  85010. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  85011. FLAC__StreamDecoder *decoder,
  85012. const char *filename,
  85013. FLAC__StreamDecoderWriteCallback write_callback,
  85014. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85015. FLAC__StreamDecoderErrorCallback error_callback,
  85016. void *client_data
  85017. );
  85018. /** Initialize the decoder instance to decode Ogg FLAC files.
  85019. *
  85020. * This flavor of initialization sets up the decoder to decode from a plain
  85021. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient, (for
  85022. * example, with Unicode filenames on Windows), you must use
  85023. * FLAC__stream_decoder_init_ogg_FILE(), or FLAC__stream_decoder_init_ogg_stream()
  85024. * and provide callbacks for the I/O.
  85025. *
  85026. * This function should be called after FLAC__stream_decoder_new() and
  85027. * FLAC__stream_decoder_set_*() but before any of the
  85028. * FLAC__stream_decoder_process_*() functions. Will set and return the
  85029. * decoder state, which will be FLAC__STREAM_DECODER_SEARCH_FOR_METADATA
  85030. * if initialization succeeded.
  85031. *
  85032. * \note Support for Ogg FLAC in the library is optional. If this
  85033. * library has been built without support for Ogg FLAC, this function
  85034. * will return \c FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER.
  85035. *
  85036. * \param decoder An uninitialized decoder instance.
  85037. * \param filename The name of the file to decode from. The file will
  85038. * be opened with fopen(). Use \c NULL to decode from
  85039. * \c stdin. Note that \c stdin is not seekable.
  85040. * \param write_callback See FLAC__StreamDecoderWriteCallback. This
  85041. * pointer must not be \c NULL.
  85042. * \param metadata_callback See FLAC__StreamDecoderMetadataCallback. This
  85043. * pointer may be \c NULL if the callback is not
  85044. * desired.
  85045. * \param error_callback See FLAC__StreamDecoderErrorCallback. This
  85046. * pointer must not be \c NULL.
  85047. * \param client_data This value will be supplied to callbacks in their
  85048. * \a client_data argument.
  85049. * \assert
  85050. * \code decoder != NULL \endcode
  85051. * \retval FLAC__StreamDecoderInitStatus
  85052. * \c FLAC__STREAM_DECODER_INIT_STATUS_OK if initialization was successful;
  85053. * see FLAC__StreamDecoderInitStatus for the meanings of other return values.
  85054. */
  85055. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  85056. FLAC__StreamDecoder *decoder,
  85057. const char *filename,
  85058. FLAC__StreamDecoderWriteCallback write_callback,
  85059. FLAC__StreamDecoderMetadataCallback metadata_callback,
  85060. FLAC__StreamDecoderErrorCallback error_callback,
  85061. void *client_data
  85062. );
  85063. /** Finish the decoding process.
  85064. * Flushes the decoding buffer, releases resources, resets the decoder
  85065. * settings to their defaults, and returns the decoder state to
  85066. * FLAC__STREAM_DECODER_UNINITIALIZED.
  85067. *
  85068. * In the event of a prematurely-terminated decode, it is not strictly
  85069. * necessary to call this immediately before FLAC__stream_decoder_delete()
  85070. * but it is good practice to match every FLAC__stream_decoder_init_*()
  85071. * with a FLAC__stream_decoder_finish().
  85072. *
  85073. * \param decoder An uninitialized decoder instance.
  85074. * \assert
  85075. * \code decoder != NULL \endcode
  85076. * \retval FLAC__bool
  85077. * \c false if MD5 checking is on AND a STREAMINFO block was available
  85078. * AND the MD5 signature in the STREAMINFO block was non-zero AND the
  85079. * signature does not match the one computed by the decoder; else
  85080. * \c true.
  85081. */
  85082. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder);
  85083. /** Flush the stream input.
  85084. * The decoder's input buffer will be cleared and the state set to
  85085. * \c FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC. This will also turn
  85086. * off MD5 checking.
  85087. *
  85088. * \param decoder A decoder instance.
  85089. * \assert
  85090. * \code decoder != NULL \endcode
  85091. * \retval FLAC__bool
  85092. * \c true if successful, else \c false if a memory allocation
  85093. * error occurs (in which case the state will be set to
  85094. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR).
  85095. */
  85096. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder);
  85097. /** Reset the decoding process.
  85098. * The decoder's input buffer will be cleared and the state set to
  85099. * \c FLAC__STREAM_DECODER_SEARCH_FOR_METADATA. This is similar to
  85100. * FLAC__stream_decoder_finish() except that the settings are
  85101. * preserved; there is no need to call FLAC__stream_decoder_init_*()
  85102. * before decoding again. MD5 checking will be restored to its original
  85103. * setting.
  85104. *
  85105. * If the decoder is seekable, or was initialized with
  85106. * FLAC__stream_decoder_init*_FILE() or FLAC__stream_decoder_init*_file(),
  85107. * the decoder will also attempt to seek to the beginning of the file.
  85108. * If this rewind fails, this function will return \c false. It follows
  85109. * that FLAC__stream_decoder_reset() cannot be used when decoding from
  85110. * \c stdin.
  85111. *
  85112. * If the decoder was initialized with FLAC__stream_encoder_init*_stream()
  85113. * and is not seekable (i.e. no seek callback was provided or the seek
  85114. * callback returns \c FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED), it
  85115. * is the duty of the client to start feeding data from the beginning of
  85116. * the stream on the next FLAC__stream_decoder_process() or
  85117. * FLAC__stream_decoder_process_interleaved() call.
  85118. *
  85119. * \param decoder A decoder instance.
  85120. * \assert
  85121. * \code decoder != NULL \endcode
  85122. * \retval FLAC__bool
  85123. * \c true if successful, else \c false if a memory allocation occurs
  85124. * (in which case the state will be set to
  85125. * \c FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR) or a seek error
  85126. * occurs (the state will be unchanged).
  85127. */
  85128. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder);
  85129. /** Decode one metadata block or audio frame.
  85130. * This version instructs the decoder to decode a either a single metadata
  85131. * block or a single frame and stop, unless the callbacks return a fatal
  85132. * error or the read callback returns
  85133. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  85134. *
  85135. * As the decoder needs more input it will call the read callback.
  85136. * Depending on what was decoded, the metadata or write callback will be
  85137. * called with the decoded metadata block or audio frame.
  85138. *
  85139. * Unless there is a fatal read error or end of stream, this function
  85140. * will return once one whole frame is decoded. In other words, if the
  85141. * stream is not synchronized or points to a corrupt frame header, the
  85142. * decoder will continue to try and resync until it gets to a valid
  85143. * frame, then decode one frame, then return. If the decoder points to
  85144. * a frame whose frame CRC in the frame footer does not match the
  85145. * computed frame CRC, this function will issue a
  85146. * FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH error to the
  85147. * error callback, and return, having decoded one complete, although
  85148. * corrupt, frame. (Such corrupted frames are sent as silence of the
  85149. * correct length to the write callback.)
  85150. *
  85151. * \param decoder An initialized decoder instance.
  85152. * \assert
  85153. * \code decoder != NULL \endcode
  85154. * \retval FLAC__bool
  85155. * \c false if any fatal read, write, or memory allocation error
  85156. * occurred (meaning decoding must stop), else \c true; for more
  85157. * information about the decoder, check the decoder state with
  85158. * FLAC__stream_decoder_get_state().
  85159. */
  85160. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder);
  85161. /** Decode until the end of the metadata.
  85162. * This version instructs the decoder to decode from the current position
  85163. * and continue until all the metadata has been read, or until the
  85164. * callbacks return a fatal error or the read callback returns
  85165. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  85166. *
  85167. * As the decoder needs more input it will call the read callback.
  85168. * As each metadata block is decoded, the metadata callback will be called
  85169. * with the decoded metadata.
  85170. *
  85171. * \param decoder An initialized decoder instance.
  85172. * \assert
  85173. * \code decoder != NULL \endcode
  85174. * \retval FLAC__bool
  85175. * \c false if any fatal read, write, or memory allocation error
  85176. * occurred (meaning decoding must stop), else \c true; for more
  85177. * information about the decoder, check the decoder state with
  85178. * FLAC__stream_decoder_get_state().
  85179. */
  85180. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder);
  85181. /** Decode until the end of the stream.
  85182. * This version instructs the decoder to decode from the current position
  85183. * and continue until the end of stream (the read callback returns
  85184. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM), or until the
  85185. * callbacks return a fatal error.
  85186. *
  85187. * As the decoder needs more input it will call the read callback.
  85188. * As each metadata block and frame is decoded, the metadata or write
  85189. * callback will be called with the decoded metadata or frame.
  85190. *
  85191. * \param decoder An initialized decoder instance.
  85192. * \assert
  85193. * \code decoder != NULL \endcode
  85194. * \retval FLAC__bool
  85195. * \c false if any fatal read, write, or memory allocation error
  85196. * occurred (meaning decoding must stop), else \c true; for more
  85197. * information about the decoder, check the decoder state with
  85198. * FLAC__stream_decoder_get_state().
  85199. */
  85200. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder);
  85201. /** Skip one audio frame.
  85202. * This version instructs the decoder to 'skip' a single frame and stop,
  85203. * unless the callbacks return a fatal error or the read callback returns
  85204. * \c FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM.
  85205. *
  85206. * The decoding flow is the same as what occurs when
  85207. * FLAC__stream_decoder_process_single() is called to process an audio
  85208. * frame, except that this function does not decode the parsed data into
  85209. * PCM or call the write callback. The integrity of the frame is still
  85210. * checked the same way as in the other process functions.
  85211. *
  85212. * This function will return once one whole frame is skipped, in the
  85213. * same way that FLAC__stream_decoder_process_single() will return once
  85214. * one whole frame is decoded.
  85215. *
  85216. * This function can be used in more quickly determining FLAC frame
  85217. * boundaries when decoding of the actual data is not needed, for
  85218. * example when an application is separating a FLAC stream into frames
  85219. * for editing or storing in a container. To do this, the application
  85220. * can use FLAC__stream_decoder_skip_single_frame() to quickly advance
  85221. * to the next frame, then use
  85222. * FLAC__stream_decoder_get_decode_position() to find the new frame
  85223. * boundary.
  85224. *
  85225. * This function should only be called when the stream has advanced
  85226. * past all the metadata, otherwise it will return \c false.
  85227. *
  85228. * \param decoder An initialized decoder instance not in a metadata
  85229. * state.
  85230. * \assert
  85231. * \code decoder != NULL \endcode
  85232. * \retval FLAC__bool
  85233. * \c false if any fatal read, write, or memory allocation error
  85234. * occurred (meaning decoding must stop), or if the decoder
  85235. * is in the FLAC__STREAM_DECODER_SEARCH_FOR_METADATA or
  85236. * FLAC__STREAM_DECODER_READ_METADATA state, else \c true; for more
  85237. * information about the decoder, check the decoder state with
  85238. * FLAC__stream_decoder_get_state().
  85239. */
  85240. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder);
  85241. /** Flush the input and seek to an absolute sample.
  85242. * Decoding will resume at the given sample. Note that because of
  85243. * this, the next write callback may contain a partial block. The
  85244. * client must support seeking the input or this function will fail
  85245. * and return \c false. Furthermore, if the decoder state is
  85246. * \c FLAC__STREAM_DECODER_SEEK_ERROR, then the decoder must be flushed
  85247. * with FLAC__stream_decoder_flush() or reset with
  85248. * FLAC__stream_decoder_reset() before decoding can continue.
  85249. *
  85250. * \param decoder A decoder instance.
  85251. * \param sample The target sample number to seek to.
  85252. * \assert
  85253. * \code decoder != NULL \endcode
  85254. * \retval FLAC__bool
  85255. * \c true if successful, else \c false.
  85256. */
  85257. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample);
  85258. /* \} */
  85259. #ifdef __cplusplus
  85260. }
  85261. #endif
  85262. #endif
  85263. /********* End of inlined file: stream_decoder.h *********/
  85264. /********* Start of inlined file: stream_encoder.h *********/
  85265. #ifndef FLAC__STREAM_ENCODER_H
  85266. #define FLAC__STREAM_ENCODER_H
  85267. #include <stdio.h> /* for FILE */
  85268. #ifdef __cplusplus
  85269. extern "C" {
  85270. #endif
  85271. /** \file include/FLAC/stream_encoder.h
  85272. *
  85273. * \brief
  85274. * This module contains the functions which implement the stream
  85275. * encoder.
  85276. *
  85277. * See the detailed documentation in the
  85278. * \link flac_stream_encoder stream encoder \endlink module.
  85279. */
  85280. /** \defgroup flac_encoder FLAC/ \*_encoder.h: encoder interfaces
  85281. * \ingroup flac
  85282. *
  85283. * \brief
  85284. * This module describes the encoder layers provided by libFLAC.
  85285. *
  85286. * The stream encoder can be used to encode complete streams either to the
  85287. * client via callbacks, or directly to a file, depending on how it is
  85288. * initialized. When encoding via callbacks, the client provides a write
  85289. * callback which will be called whenever FLAC data is ready to be written.
  85290. * If the client also supplies a seek callback, the encoder will also
  85291. * automatically handle the writing back of metadata discovered while
  85292. * encoding, like stream info, seek points offsets, etc. When encoding to
  85293. * a file, the client needs only supply a filename or open \c FILE* and an
  85294. * optional progress callback for periodic notification of progress; the
  85295. * write and seek callbacks are supplied internally. For more info see the
  85296. * \link flac_stream_encoder stream encoder \endlink module.
  85297. */
  85298. /** \defgroup flac_stream_encoder FLAC/stream_encoder.h: stream encoder interface
  85299. * \ingroup flac_encoder
  85300. *
  85301. * \brief
  85302. * This module contains the functions which implement the stream
  85303. * encoder.
  85304. *
  85305. * The stream encoder can encode to native FLAC, and optionally Ogg FLAC
  85306. * (check FLAC_API_SUPPORTS_OGG_FLAC) streams and files.
  85307. *
  85308. * The basic usage of this encoder is as follows:
  85309. * - The program creates an instance of an encoder using
  85310. * FLAC__stream_encoder_new().
  85311. * - The program overrides the default settings using
  85312. * FLAC__stream_encoder_set_*() functions. At a minimum, the following
  85313. * functions should be called:
  85314. * - FLAC__stream_encoder_set_channels()
  85315. * - FLAC__stream_encoder_set_bits_per_sample()
  85316. * - FLAC__stream_encoder_set_sample_rate()
  85317. * - FLAC__stream_encoder_set_ogg_serial_number() (if encoding to Ogg FLAC)
  85318. * - FLAC__stream_encoder_set_total_samples_estimate() (if known)
  85319. * - If the application wants to control the compression level or set its own
  85320. * metadata, then the following should also be called:
  85321. * - FLAC__stream_encoder_set_compression_level()
  85322. * - FLAC__stream_encoder_set_verify()
  85323. * - FLAC__stream_encoder_set_metadata()
  85324. * - The rest of the set functions should only be called if the client needs
  85325. * exact control over how the audio is compressed; thorough understanding
  85326. * of the FLAC format is necessary to achieve good results.
  85327. * - The program initializes the instance to validate the settings and
  85328. * prepare for encoding using
  85329. * - FLAC__stream_encoder_init_stream() or FLAC__stream_encoder_init_FILE()
  85330. * or FLAC__stream_encoder_init_file() for native FLAC
  85331. * - FLAC__stream_encoder_init_ogg_stream() or FLAC__stream_encoder_init_ogg_FILE()
  85332. * or FLAC__stream_encoder_init_ogg_file() for Ogg FLAC
  85333. * - The program calls FLAC__stream_encoder_process() or
  85334. * FLAC__stream_encoder_process_interleaved() to encode data, which
  85335. * subsequently calls the callbacks when there is encoder data ready
  85336. * to be written.
  85337. * - The program finishes the encoding with FLAC__stream_encoder_finish(),
  85338. * which causes the encoder to encode any data still in its input pipe,
  85339. * update the metadata with the final encoding statistics if output
  85340. * seeking is possible, and finally reset the encoder to the
  85341. * uninitialized state.
  85342. * - The instance may be used again or deleted with
  85343. * FLAC__stream_encoder_delete().
  85344. *
  85345. * In more detail, the stream encoder functions similarly to the
  85346. * \link flac_stream_decoder stream decoder \endlink, but has fewer
  85347. * callbacks and more options. Typically the client will create a new
  85348. * instance by calling FLAC__stream_encoder_new(), then set the necessary
  85349. * parameters with FLAC__stream_encoder_set_*(), and initialize it by
  85350. * calling one of the FLAC__stream_encoder_init_*() functions.
  85351. *
  85352. * Unlike the decoders, the stream encoder has many options that can
  85353. * affect the speed and compression ratio. When setting these parameters
  85354. * you should have some basic knowledge of the format (see the
  85355. * <A HREF="../documentation.html#format">user-level documentation</A>
  85356. * or the <A HREF="../format.html">formal description</A>). The
  85357. * FLAC__stream_encoder_set_*() functions themselves do not validate the
  85358. * values as many are interdependent. The FLAC__stream_encoder_init_*()
  85359. * functions will do this, so make sure to pay attention to the state
  85360. * returned by FLAC__stream_encoder_init_*() to make sure that it is
  85361. * FLAC__STREAM_ENCODER_INIT_STATUS_OK. Any parameters that are not set
  85362. * before FLAC__stream_encoder_init_*() will take on the defaults from
  85363. * the constructor.
  85364. *
  85365. * There are three initialization functions for native FLAC, one for
  85366. * setting up the encoder to encode FLAC data to the client via
  85367. * callbacks, and two for encoding directly to a file.
  85368. *
  85369. * For encoding via callbacks, use FLAC__stream_encoder_init_stream().
  85370. * You must also supply a write callback which will be called anytime
  85371. * there is raw encoded data to write. If the client can seek the output
  85372. * it is best to also supply seek and tell callbacks, as this allows the
  85373. * encoder to go back after encoding is finished to write back
  85374. * information that was collected while encoding, like seek point offsets,
  85375. * frame sizes, etc.
  85376. *
  85377. * For encoding directly to a file, use FLAC__stream_encoder_init_FILE()
  85378. * or FLAC__stream_encoder_init_file(). Then you must only supply a
  85379. * filename or open \c FILE*; the encoder will handle all the callbacks
  85380. * internally. You may also supply a progress callback for periodic
  85381. * notification of the encoding progress.
  85382. *
  85383. * There are three similarly-named init functions for encoding to Ogg
  85384. * FLAC streams. Check \c FLAC_API_SUPPORTS_OGG_FLAC to find out if the
  85385. * library has been built with Ogg support.
  85386. *
  85387. * The call to FLAC__stream_encoder_init_*() currently will also immediately
  85388. * call the write callback several times, once with the \c fLaC signature,
  85389. * and once for each encoded metadata block. Note that for Ogg FLAC
  85390. * encoding you will usually get at least twice the number of callbacks than
  85391. * with native FLAC, one for the Ogg page header and one for the page body.
  85392. *
  85393. * After initializing the instance, the client may feed audio data to the
  85394. * encoder in one of two ways:
  85395. *
  85396. * - Channel separate, through FLAC__stream_encoder_process() - The client
  85397. * will pass an array of pointers to buffers, one for each channel, to
  85398. * the encoder, each of the same length. The samples need not be
  85399. * block-aligned, but each channel should have the same number of samples.
  85400. * - Channel interleaved, through
  85401. * FLAC__stream_encoder_process_interleaved() - The client will pass a single
  85402. * pointer to data that is channel-interleaved (i.e. channel0_sample0,
  85403. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  85404. * Again, the samples need not be block-aligned but they must be
  85405. * sample-aligned, i.e. the first value should be channel0_sample0 and
  85406. * the last value channelN_sampleM.
  85407. *
  85408. * Note that for either process call, each sample in the buffers should be a
  85409. * signed integer, right-justified to the resolution set by
  85410. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the resolution
  85411. * is 16 bits per sample, the samples should all be in the range [-32768,32767].
  85412. *
  85413. * When the client is finished encoding data, it calls
  85414. * FLAC__stream_encoder_finish(), which causes the encoder to encode any
  85415. * data still in its input pipe, and call the metadata callback with the
  85416. * final encoding statistics. Then the instance may be deleted with
  85417. * FLAC__stream_encoder_delete() or initialized again to encode another
  85418. * stream.
  85419. *
  85420. * For programs that write their own metadata, but that do not know the
  85421. * actual metadata until after encoding, it is advantageous to instruct
  85422. * the encoder to write a PADDING block of the correct size, so that
  85423. * instead of rewriting the whole stream after encoding, the program can
  85424. * just overwrite the PADDING block. If only the maximum size of the
  85425. * metadata is known, the program can write a slightly larger padding
  85426. * block, then split it after encoding.
  85427. *
  85428. * Make sure you understand how lengths are calculated. All FLAC metadata
  85429. * blocks have a 4 byte header which contains the type and length. This
  85430. * length does not include the 4 bytes of the header. See the format page
  85431. * for the specification of metadata blocks and their lengths.
  85432. *
  85433. * \note
  85434. * If you are writing the FLAC data to a file via callbacks, make sure it
  85435. * is open for update (e.g. mode "w+" for stdio streams). This is because
  85436. * after the first encoding pass, the encoder will try to seek back to the
  85437. * beginning of the stream, to the STREAMINFO block, to write some data
  85438. * there. (If using FLAC__stream_encoder_init*_file() or
  85439. * FLAC__stream_encoder_init*_FILE(), the file is managed internally.)
  85440. *
  85441. * \note
  85442. * The "set" functions may only be called when the encoder is in the
  85443. * state FLAC__STREAM_ENCODER_UNINITIALIZED, i.e. after
  85444. * FLAC__stream_encoder_new() or FLAC__stream_encoder_finish(), but
  85445. * before FLAC__stream_encoder_init_*(). If this is the case they will
  85446. * return \c true, otherwise \c false.
  85447. *
  85448. * \note
  85449. * FLAC__stream_encoder_finish() resets all settings to the constructor
  85450. * defaults.
  85451. *
  85452. * \{
  85453. */
  85454. /** State values for a FLAC__StreamEncoder.
  85455. *
  85456. * The encoder's state can be obtained by calling FLAC__stream_encoder_get_state().
  85457. *
  85458. * If the encoder gets into any other state besides \c FLAC__STREAM_ENCODER_OK
  85459. * or \c FLAC__STREAM_ENCODER_UNINITIALIZED, it becomes invalid for encoding and
  85460. * must be deleted with FLAC__stream_encoder_delete().
  85461. */
  85462. typedef enum {
  85463. FLAC__STREAM_ENCODER_OK = 0,
  85464. /**< The encoder is in the normal OK state and samples can be processed. */
  85465. FLAC__STREAM_ENCODER_UNINITIALIZED,
  85466. /**< The encoder is in the uninitialized state; one of the
  85467. * FLAC__stream_encoder_init_*() functions must be called before samples
  85468. * can be processed.
  85469. */
  85470. FLAC__STREAM_ENCODER_OGG_ERROR,
  85471. /**< An error occurred in the underlying Ogg layer. */
  85472. FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR,
  85473. /**< An error occurred in the underlying verify stream decoder;
  85474. * check FLAC__stream_encoder_get_verify_decoder_state().
  85475. */
  85476. FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA,
  85477. /**< The verify decoder detected a mismatch between the original
  85478. * audio signal and the decoded audio signal.
  85479. */
  85480. FLAC__STREAM_ENCODER_CLIENT_ERROR,
  85481. /**< One of the callbacks returned a fatal error. */
  85482. FLAC__STREAM_ENCODER_IO_ERROR,
  85483. /**< An I/O error occurred while opening/reading/writing a file.
  85484. * Check \c errno.
  85485. */
  85486. FLAC__STREAM_ENCODER_FRAMING_ERROR,
  85487. /**< An error occurred while writing the stream; usually, the
  85488. * write_callback returned an error.
  85489. */
  85490. FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR
  85491. /**< Memory allocation failed. */
  85492. } FLAC__StreamEncoderState;
  85493. /** Maps a FLAC__StreamEncoderState to a C string.
  85494. *
  85495. * Using a FLAC__StreamEncoderState as the index to this array
  85496. * will give the string equivalent. The contents should not be modified.
  85497. */
  85498. extern FLAC_API const char * const FLAC__StreamEncoderStateString[];
  85499. /** Possible return values for the FLAC__stream_encoder_init_*() functions.
  85500. */
  85501. typedef enum {
  85502. FLAC__STREAM_ENCODER_INIT_STATUS_OK = 0,
  85503. /**< Initialization was successful. */
  85504. FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR,
  85505. /**< General failure to set up encoder; call FLAC__stream_encoder_get_state() for cause. */
  85506. FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER,
  85507. /**< The library was not compiled with support for the given container
  85508. * format.
  85509. */
  85510. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS,
  85511. /**< A required callback was not supplied. */
  85512. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS,
  85513. /**< The encoder has an invalid setting for number of channels. */
  85514. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE,
  85515. /**< The encoder has an invalid setting for bits-per-sample.
  85516. * FLAC supports 4-32 bps but the reference encoder currently supports
  85517. * only up to 24 bps.
  85518. */
  85519. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE,
  85520. /**< The encoder has an invalid setting for the input sample rate. */
  85521. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE,
  85522. /**< The encoder has an invalid setting for the block size. */
  85523. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER,
  85524. /**< The encoder has an invalid setting for the maximum LPC order. */
  85525. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION,
  85526. /**< The encoder has an invalid setting for the precision of the quantized linear predictor coefficients. */
  85527. FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER,
  85528. /**< The specified block size is less than the maximum LPC order. */
  85529. FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE,
  85530. /**< The encoder is bound to the <A HREF="../format.html#subset">Subset</A> but other settings violate it. */
  85531. FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA,
  85532. /**< The metadata input to the encoder is invalid, in one of the following ways:
  85533. * - FLAC__stream_encoder_set_metadata() was called with a null pointer but a block count > 0
  85534. * - One of the metadata blocks contains an undefined type
  85535. * - It contains an illegal CUESHEET as checked by FLAC__format_cuesheet_is_legal()
  85536. * - It contains an illegal SEEKTABLE as checked by FLAC__format_seektable_is_legal()
  85537. * - It contains more than one SEEKTABLE block or more than one VORBIS_COMMENT block
  85538. */
  85539. FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED
  85540. /**< FLAC__stream_encoder_init_*() was called when the encoder was
  85541. * already initialized, usually because
  85542. * FLAC__stream_encoder_finish() was not called.
  85543. */
  85544. } FLAC__StreamEncoderInitStatus;
  85545. /** Maps a FLAC__StreamEncoderInitStatus to a C string.
  85546. *
  85547. * Using a FLAC__StreamEncoderInitStatus as the index to this array
  85548. * will give the string equivalent. The contents should not be modified.
  85549. */
  85550. extern FLAC_API const char * const FLAC__StreamEncoderInitStatusString[];
  85551. /** Return values for the FLAC__StreamEncoder read callback.
  85552. */
  85553. typedef enum {
  85554. FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE,
  85555. /**< The read was OK and decoding can continue. */
  85556. FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM,
  85557. /**< The read was attempted at the end of the stream. */
  85558. FLAC__STREAM_ENCODER_READ_STATUS_ABORT,
  85559. /**< An unrecoverable error occurred. */
  85560. FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED
  85561. /**< Client does not support reading back from the output. */
  85562. } FLAC__StreamEncoderReadStatus;
  85563. /** Maps a FLAC__StreamEncoderReadStatus to a C string.
  85564. *
  85565. * Using a FLAC__StreamEncoderReadStatus as the index to this array
  85566. * will give the string equivalent. The contents should not be modified.
  85567. */
  85568. extern FLAC_API const char * const FLAC__StreamEncoderReadStatusString[];
  85569. /** Return values for the FLAC__StreamEncoder write callback.
  85570. */
  85571. typedef enum {
  85572. FLAC__STREAM_ENCODER_WRITE_STATUS_OK = 0,
  85573. /**< The write was OK and encoding can continue. */
  85574. FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR
  85575. /**< An unrecoverable error occurred. The encoder will return from the process call. */
  85576. } FLAC__StreamEncoderWriteStatus;
  85577. /** Maps a FLAC__StreamEncoderWriteStatus to a C string.
  85578. *
  85579. * Using a FLAC__StreamEncoderWriteStatus as the index to this array
  85580. * will give the string equivalent. The contents should not be modified.
  85581. */
  85582. extern FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[];
  85583. /** Return values for the FLAC__StreamEncoder seek callback.
  85584. */
  85585. typedef enum {
  85586. FLAC__STREAM_ENCODER_SEEK_STATUS_OK,
  85587. /**< The seek was OK and encoding can continue. */
  85588. FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR,
  85589. /**< An unrecoverable error occurred. */
  85590. FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  85591. /**< Client does not support seeking. */
  85592. } FLAC__StreamEncoderSeekStatus;
  85593. /** Maps a FLAC__StreamEncoderSeekStatus to a C string.
  85594. *
  85595. * Using a FLAC__StreamEncoderSeekStatus as the index to this array
  85596. * will give the string equivalent. The contents should not be modified.
  85597. */
  85598. extern FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[];
  85599. /** Return values for the FLAC__StreamEncoder tell callback.
  85600. */
  85601. typedef enum {
  85602. FLAC__STREAM_ENCODER_TELL_STATUS_OK,
  85603. /**< The tell was OK and encoding can continue. */
  85604. FLAC__STREAM_ENCODER_TELL_STATUS_ERROR,
  85605. /**< An unrecoverable error occurred. */
  85606. FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  85607. /**< Client does not support seeking. */
  85608. } FLAC__StreamEncoderTellStatus;
  85609. /** Maps a FLAC__StreamEncoderTellStatus to a C string.
  85610. *
  85611. * Using a FLAC__StreamEncoderTellStatus as the index to this array
  85612. * will give the string equivalent. The contents should not be modified.
  85613. */
  85614. extern FLAC_API const char * const FLAC__StreamEncoderTellStatusString[];
  85615. /***********************************************************************
  85616. *
  85617. * class FLAC__StreamEncoder
  85618. *
  85619. ***********************************************************************/
  85620. struct FLAC__StreamEncoderProtected;
  85621. struct FLAC__StreamEncoderPrivate;
  85622. /** The opaque structure definition for the stream encoder type.
  85623. * See the \link flac_stream_encoder stream encoder module \endlink
  85624. * for a detailed description.
  85625. */
  85626. typedef struct {
  85627. struct FLAC__StreamEncoderProtected *protected_; /* avoid the C++ keyword 'protected' */
  85628. struct FLAC__StreamEncoderPrivate *private_; /* avoid the C++ keyword 'private' */
  85629. } FLAC__StreamEncoder;
  85630. /** Signature for the read callback.
  85631. *
  85632. * A function pointer matching this signature must be passed to
  85633. * FLAC__stream_encoder_init_ogg_stream() if seeking is supported.
  85634. * The supplied function will be called when the encoder needs to read back
  85635. * encoded data. This happens during the metadata callback, when the encoder
  85636. * has to read, modify, and rewrite the metadata (e.g. seekpoints) gathered
  85637. * while encoding. The address of the buffer to be filled is supplied, along
  85638. * with the number of bytes the buffer can hold. The callback may choose to
  85639. * supply less data and modify the byte count but must be careful not to
  85640. * overflow the buffer. The callback then returns a status code chosen from
  85641. * FLAC__StreamEncoderReadStatus.
  85642. *
  85643. * Here is an example of a read callback for stdio streams:
  85644. * \code
  85645. * FLAC__StreamEncoderReadStatus read_cb(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  85646. * {
  85647. * FILE *file = ((MyClientData*)client_data)->file;
  85648. * if(*bytes > 0) {
  85649. * *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, file);
  85650. * if(ferror(file))
  85651. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  85652. * else if(*bytes == 0)
  85653. * return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  85654. * else
  85655. * return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  85656. * }
  85657. * else
  85658. * return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  85659. * }
  85660. * \endcode
  85661. *
  85662. * \note In general, FLAC__StreamEncoder functions which change the
  85663. * state should not be called on the \a encoder while in the callback.
  85664. *
  85665. * \param encoder The encoder instance calling the callback.
  85666. * \param buffer A pointer to a location for the callee to store
  85667. * data to be encoded.
  85668. * \param bytes A pointer to the size of the buffer. On entry
  85669. * to the callback, it contains the maximum number
  85670. * of bytes that may be stored in \a buffer. The
  85671. * callee must set it to the actual number of bytes
  85672. * stored (0 in case of error or end-of-stream) before
  85673. * returning.
  85674. * \param client_data The callee's client data set through
  85675. * FLAC__stream_encoder_set_client_data().
  85676. * \retval FLAC__StreamEncoderReadStatus
  85677. * The callee's return status.
  85678. */
  85679. typedef FLAC__StreamEncoderReadStatus (*FLAC__StreamEncoderReadCallback)(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  85680. /** Signature for the write callback.
  85681. *
  85682. * A function pointer matching this signature must be passed to
  85683. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85684. * by the encoder anytime there is raw encoded data ready to write. It may
  85685. * include metadata mixed with encoded audio frames and the data is not
  85686. * guaranteed to be aligned on frame or metadata block boundaries.
  85687. *
  85688. * The only duty of the callback is to write out the \a bytes worth of data
  85689. * in \a buffer to the current position in the output stream. The arguments
  85690. * \a samples and \a current_frame are purely informational. If \a samples
  85691. * is greater than \c 0, then \a current_frame will hold the current frame
  85692. * number that is being written; otherwise it indicates that the write
  85693. * callback is being called to write metadata.
  85694. *
  85695. * \note
  85696. * Unlike when writing to native FLAC, when writing to Ogg FLAC the
  85697. * write callback will be called twice when writing each audio
  85698. * frame; once for the page header, and once for the page body.
  85699. * When writing the page header, the \a samples argument to the
  85700. * write callback will be \c 0.
  85701. *
  85702. * \note In general, FLAC__StreamEncoder functions which change the
  85703. * state should not be called on the \a encoder while in the callback.
  85704. *
  85705. * \param encoder The encoder instance calling the callback.
  85706. * \param buffer An array of encoded data of length \a bytes.
  85707. * \param bytes The byte length of \a buffer.
  85708. * \param samples The number of samples encoded by \a buffer.
  85709. * \c 0 has a special meaning; see above.
  85710. * \param current_frame The number of the current frame being encoded.
  85711. * \param client_data The callee's client data set through
  85712. * FLAC__stream_encoder_init_*().
  85713. * \retval FLAC__StreamEncoderWriteStatus
  85714. * The callee's return status.
  85715. */
  85716. typedef FLAC__StreamEncoderWriteStatus (*FLAC__StreamEncoderWriteCallback)(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data);
  85717. /** Signature for the seek callback.
  85718. *
  85719. * A function pointer matching this signature may be passed to
  85720. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85721. * when the encoder needs to seek the output stream. The encoder will pass
  85722. * the absolute byte offset to seek to, 0 meaning the beginning of the stream.
  85723. *
  85724. * Here is an example of a seek callback for stdio streams:
  85725. * \code
  85726. * FLAC__StreamEncoderSeekStatus seek_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  85727. * {
  85728. * FILE *file = ((MyClientData*)client_data)->file;
  85729. * if(file == stdin)
  85730. * return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  85731. * else if(fseeko(file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  85732. * return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  85733. * else
  85734. * return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  85735. * }
  85736. * \endcode
  85737. *
  85738. * \note In general, FLAC__StreamEncoder functions which change the
  85739. * state should not be called on the \a encoder while in the callback.
  85740. *
  85741. * \param encoder The encoder instance calling the callback.
  85742. * \param absolute_byte_offset The offset from the beginning of the stream
  85743. * to seek to.
  85744. * \param client_data The callee's client data set through
  85745. * FLAC__stream_encoder_init_*().
  85746. * \retval FLAC__StreamEncoderSeekStatus
  85747. * The callee's return status.
  85748. */
  85749. typedef FLAC__StreamEncoderSeekStatus (*FLAC__StreamEncoderSeekCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  85750. /** Signature for the tell callback.
  85751. *
  85752. * A function pointer matching this signature may be passed to
  85753. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85754. * when the encoder needs to know the current position of the output stream.
  85755. *
  85756. * \warning
  85757. * The callback must return the true current byte offset of the output to
  85758. * which the encoder is writing. If you are buffering the output, make
  85759. * sure and take this into account. If you are writing directly to a
  85760. * FILE* from your write callback, ftell() is sufficient. If you are
  85761. * writing directly to a file descriptor from your write callback, you
  85762. * can use lseek(fd, SEEK_CUR, 0). The encoder may later seek back to
  85763. * these points to rewrite metadata after encoding.
  85764. *
  85765. * Here is an example of a tell callback for stdio streams:
  85766. * \code
  85767. * FLAC__StreamEncoderTellStatus tell_cb(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  85768. * {
  85769. * FILE *file = ((MyClientData*)client_data)->file;
  85770. * off_t pos;
  85771. * if(file == stdin)
  85772. * return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  85773. * else if((pos = ftello(file)) < 0)
  85774. * return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  85775. * else {
  85776. * *absolute_byte_offset = (FLAC__uint64)pos;
  85777. * return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  85778. * }
  85779. * }
  85780. * \endcode
  85781. *
  85782. * \note In general, FLAC__StreamEncoder functions which change the
  85783. * state should not be called on the \a encoder while in the callback.
  85784. *
  85785. * \param encoder The encoder instance calling the callback.
  85786. * \param absolute_byte_offset The address at which to store the current
  85787. * position of the output.
  85788. * \param client_data The callee's client data set through
  85789. * FLAC__stream_encoder_init_*().
  85790. * \retval FLAC__StreamEncoderTellStatus
  85791. * The callee's return status.
  85792. */
  85793. typedef FLAC__StreamEncoderTellStatus (*FLAC__StreamEncoderTellCallback)(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  85794. /** Signature for the metadata callback.
  85795. *
  85796. * A function pointer matching this signature may be passed to
  85797. * FLAC__stream_encoder_init*_stream(). The supplied function will be called
  85798. * once at the end of encoding with the populated STREAMINFO structure. This
  85799. * is so the client can seek back to the beginning of the file and write the
  85800. * STREAMINFO block with the correct statistics after encoding (like
  85801. * minimum/maximum frame size and total samples).
  85802. *
  85803. * \note In general, FLAC__StreamEncoder functions which change the
  85804. * state should not be called on the \a encoder while in the callback.
  85805. *
  85806. * \param encoder The encoder instance calling the callback.
  85807. * \param metadata The final populated STREAMINFO block.
  85808. * \param client_data The callee's client data set through
  85809. * FLAC__stream_encoder_init_*().
  85810. */
  85811. typedef void (*FLAC__StreamEncoderMetadataCallback)(const FLAC__StreamEncoder *encoder, const FLAC__StreamMetadata *metadata, void *client_data);
  85812. /** Signature for the progress callback.
  85813. *
  85814. * A function pointer matching this signature may be passed to
  85815. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE().
  85816. * The supplied function will be called when the encoder has finished
  85817. * writing a frame. The \c total_frames_estimate argument to the
  85818. * callback will be based on the value from
  85819. * FLAC__stream_encoder_set_total_samples_estimate().
  85820. *
  85821. * \note In general, FLAC__StreamEncoder functions which change the
  85822. * state should not be called on the \a encoder while in the callback.
  85823. *
  85824. * \param encoder The encoder instance calling the callback.
  85825. * \param bytes_written Bytes written so far.
  85826. * \param samples_written Samples written so far.
  85827. * \param frames_written Frames written so far.
  85828. * \param total_frames_estimate The estimate of the total number of
  85829. * frames to be written.
  85830. * \param client_data The callee's client data set through
  85831. * FLAC__stream_encoder_init_*().
  85832. */
  85833. 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);
  85834. /***********************************************************************
  85835. *
  85836. * Class constructor/destructor
  85837. *
  85838. ***********************************************************************/
  85839. /** Create a new stream encoder instance. The instance is created with
  85840. * default settings; see the individual FLAC__stream_encoder_set_*()
  85841. * functions for each setting's default.
  85842. *
  85843. * \retval FLAC__StreamEncoder*
  85844. * \c NULL if there was an error allocating memory, else the new instance.
  85845. */
  85846. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void);
  85847. /** Free an encoder instance. Deletes the object pointed to by \a encoder.
  85848. *
  85849. * \param encoder A pointer to an existing encoder.
  85850. * \assert
  85851. * \code encoder != NULL \endcode
  85852. */
  85853. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder);
  85854. /***********************************************************************
  85855. *
  85856. * Public class method prototypes
  85857. *
  85858. ***********************************************************************/
  85859. /** Set the serial number for the FLAC stream to use in the Ogg container.
  85860. *
  85861. * \note
  85862. * This does not need to be set for native FLAC encoding.
  85863. *
  85864. * \note
  85865. * It is recommended to set a serial number explicitly as the default of '0'
  85866. * may collide with other streams.
  85867. *
  85868. * \default \c 0
  85869. * \param encoder An encoder instance to set.
  85870. * \param serial_number See above.
  85871. * \assert
  85872. * \code encoder != NULL \endcode
  85873. * \retval FLAC__bool
  85874. * \c false if the encoder is already initialized, else \c true.
  85875. */
  85876. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long serial_number);
  85877. /** Set the "verify" flag. If \c true, the encoder will verify it's own
  85878. * encoded output by feeding it through an internal decoder and comparing
  85879. * the original signal against the decoded signal. If a mismatch occurs,
  85880. * the process call will return \c false. Note that this will slow the
  85881. * encoding process by the extra time required for decoding and comparison.
  85882. *
  85883. * \default \c false
  85884. * \param encoder An encoder instance to set.
  85885. * \param value Flag value (see above).
  85886. * \assert
  85887. * \code encoder != NULL \endcode
  85888. * \retval FLAC__bool
  85889. * \c false if the encoder is already initialized, else \c true.
  85890. */
  85891. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85892. /** Set the <A HREF="../format.html#subset">Subset</A> flag. If \c true,
  85893. * the encoder will comply with the Subset and will check the
  85894. * settings during FLAC__stream_encoder_init_*() to see if all settings
  85895. * comply. If \c false, the settings may take advantage of the full
  85896. * range that the format allows.
  85897. *
  85898. * Make sure you know what it entails before setting this to \c false.
  85899. *
  85900. * \default \c true
  85901. * \param encoder An encoder instance to set.
  85902. * \param value Flag value (see above).
  85903. * \assert
  85904. * \code encoder != NULL \endcode
  85905. * \retval FLAC__bool
  85906. * \c false if the encoder is already initialized, else \c true.
  85907. */
  85908. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value);
  85909. /** Set the number of channels to be encoded.
  85910. *
  85911. * \default \c 2
  85912. * \param encoder An encoder instance to set.
  85913. * \param value See above.
  85914. * \assert
  85915. * \code encoder != NULL \endcode
  85916. * \retval FLAC__bool
  85917. * \c false if the encoder is already initialized, else \c true.
  85918. */
  85919. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value);
  85920. /** Set the sample resolution of the input to be encoded.
  85921. *
  85922. * \warning
  85923. * Do not feed the encoder data that is wider than the value you
  85924. * set here or you will generate an invalid stream.
  85925. *
  85926. * \default \c 16
  85927. * \param encoder An encoder instance to set.
  85928. * \param value See above.
  85929. * \assert
  85930. * \code encoder != NULL \endcode
  85931. * \retval FLAC__bool
  85932. * \c false if the encoder is already initialized, else \c true.
  85933. */
  85934. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value);
  85935. /** Set the sample rate (in Hz) of the input to be encoded.
  85936. *
  85937. * \default \c 44100
  85938. * \param encoder An encoder instance to set.
  85939. * \param value See above.
  85940. * \assert
  85941. * \code encoder != NULL \endcode
  85942. * \retval FLAC__bool
  85943. * \c false if the encoder is already initialized, else \c true.
  85944. */
  85945. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value);
  85946. /** Set the compression level
  85947. *
  85948. * The compression level is roughly proportional to the amount of effort
  85949. * the encoder expends to compress the file. A higher level usually
  85950. * means more computation but higher compression. The default level is
  85951. * suitable for most applications.
  85952. *
  85953. * Currently the levels range from \c 0 (fastest, least compression) to
  85954. * \c 8 (slowest, most compression). A value larger than \c 8 will be
  85955. * treated as \c 8.
  85956. *
  85957. * This function automatically calls the following other \c _set_
  85958. * functions with appropriate values, so the client does not need to
  85959. * unless it specifically wants to override them:
  85960. * - FLAC__stream_encoder_set_do_mid_side_stereo()
  85961. * - FLAC__stream_encoder_set_loose_mid_side_stereo()
  85962. * - FLAC__stream_encoder_set_apodization()
  85963. * - FLAC__stream_encoder_set_max_lpc_order()
  85964. * - FLAC__stream_encoder_set_qlp_coeff_precision()
  85965. * - FLAC__stream_encoder_set_do_qlp_coeff_prec_search()
  85966. * - FLAC__stream_encoder_set_do_escape_coding()
  85967. * - FLAC__stream_encoder_set_do_exhaustive_model_search()
  85968. * - FLAC__stream_encoder_set_min_residual_partition_order()
  85969. * - FLAC__stream_encoder_set_max_residual_partition_order()
  85970. * - FLAC__stream_encoder_set_rice_parameter_search_dist()
  85971. *
  85972. * The actual values set for each level are:
  85973. * <table>
  85974. * <tr>
  85975. * <td><b>level</b><td>
  85976. * <td>do mid-side stereo<td>
  85977. * <td>loose mid-side stereo<td>
  85978. * <td>apodization<td>
  85979. * <td>max lpc order<td>
  85980. * <td>qlp coeff precision<td>
  85981. * <td>qlp coeff prec search<td>
  85982. * <td>escape coding<td>
  85983. * <td>exhaustive model search<td>
  85984. * <td>min residual partition order<td>
  85985. * <td>max residual partition order<td>
  85986. * <td>rice parameter search dist<td>
  85987. * </tr>
  85988. * <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>
  85989. * <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>
  85990. * <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>
  85991. * <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>
  85992. * <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>
  85993. * <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>
  85994. * <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>
  85995. * <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>
  85996. * <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>
  85997. * </table>
  85998. *
  85999. * \default \c 5
  86000. * \param encoder An encoder instance to set.
  86001. * \param value See above.
  86002. * \assert
  86003. * \code encoder != NULL \endcode
  86004. * \retval FLAC__bool
  86005. * \c false if the encoder is already initialized, else \c true.
  86006. */
  86007. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value);
  86008. /** Set the blocksize to use while encoding.
  86009. *
  86010. * The number of samples to use per frame. Use \c 0 to let the encoder
  86011. * estimate a blocksize; this is usually best.
  86012. *
  86013. * \default \c 0
  86014. * \param encoder An encoder instance to set.
  86015. * \param value See above.
  86016. * \assert
  86017. * \code encoder != NULL \endcode
  86018. * \retval FLAC__bool
  86019. * \c false if the encoder is already initialized, else \c true.
  86020. */
  86021. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value);
  86022. /** Set to \c true to enable mid-side encoding on stereo input. The
  86023. * number of channels must be 2 for this to have any effect. Set to
  86024. * \c false to use only independent channel coding.
  86025. *
  86026. * \default \c false
  86027. * \param encoder An encoder instance to set.
  86028. * \param value Flag value (see above).
  86029. * \assert
  86030. * \code encoder != NULL \endcode
  86031. * \retval FLAC__bool
  86032. * \c false if the encoder is already initialized, else \c true.
  86033. */
  86034. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86035. /** Set to \c true to enable adaptive switching between mid-side and
  86036. * left-right encoding on stereo input. Set to \c false to use
  86037. * exhaustive searching. Setting this to \c true requires
  86038. * FLAC__stream_encoder_set_do_mid_side_stereo() to also be set to
  86039. * \c true in order to have any effect.
  86040. *
  86041. * \default \c false
  86042. * \param encoder An encoder instance to set.
  86043. * \param value Flag value (see above).
  86044. * \assert
  86045. * \code encoder != NULL \endcode
  86046. * \retval FLAC__bool
  86047. * \c false if the encoder is already initialized, else \c true.
  86048. */
  86049. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86050. /** Sets the apodization function(s) the encoder will use when windowing
  86051. * audio data for LPC analysis.
  86052. *
  86053. * The \a specification is a plain ASCII string which specifies exactly
  86054. * which functions to use. There may be more than one (up to 32),
  86055. * separated by \c ';' characters. Some functions take one or more
  86056. * comma-separated arguments in parentheses.
  86057. *
  86058. * The available functions are \c bartlett, \c bartlett_hann,
  86059. * \c blackman, \c blackman_harris_4term_92db, \c connes, \c flattop,
  86060. * \c gauss(STDDEV), \c hamming, \c hann, \c kaiser_bessel, \c nuttall,
  86061. * \c rectangle, \c triangle, \c tukey(P), \c welch.
  86062. *
  86063. * For \c gauss(STDDEV), STDDEV specifies the standard deviation
  86064. * (0<STDDEV<=0.5).
  86065. *
  86066. * For \c tukey(P), P specifies the fraction of the window that is
  86067. * tapered (0<=P<=1). P=0 corresponds to \c rectangle and P=1
  86068. * corresponds to \c hann.
  86069. *
  86070. * Example specifications are \c "blackman" or
  86071. * \c "hann;triangle;tukey(0.5);tukey(0.25);tukey(0.125)"
  86072. *
  86073. * Any function that is specified erroneously is silently dropped. Up
  86074. * to 32 functions are kept, the rest are dropped. If the specification
  86075. * is empty the encoder defaults to \c "tukey(0.5)".
  86076. *
  86077. * When more than one function is specified, then for every subframe the
  86078. * encoder will try each of them separately and choose the window that
  86079. * results in the smallest compressed subframe.
  86080. *
  86081. * Note that each function specified causes the encoder to occupy a
  86082. * floating point array in which to store the window.
  86083. *
  86084. * \default \c "tukey(0.5)"
  86085. * \param encoder An encoder instance to set.
  86086. * \param specification See above.
  86087. * \assert
  86088. * \code encoder != NULL \endcode
  86089. * \code specification != NULL \endcode
  86090. * \retval FLAC__bool
  86091. * \c false if the encoder is already initialized, else \c true.
  86092. */
  86093. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification);
  86094. /** Set the maximum LPC order, or \c 0 to use only the fixed predictors.
  86095. *
  86096. * \default \c 0
  86097. * \param encoder An encoder instance to set.
  86098. * \param value See above.
  86099. * \assert
  86100. * \code encoder != NULL \endcode
  86101. * \retval FLAC__bool
  86102. * \c false if the encoder is already initialized, else \c true.
  86103. */
  86104. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value);
  86105. /** Set the precision, in bits, of the quantized linear predictor
  86106. * coefficients, or \c 0 to let the encoder select it based on the
  86107. * blocksize.
  86108. *
  86109. * \note
  86110. * In the current implementation, qlp_coeff_precision + bits_per_sample must
  86111. * be less than 32.
  86112. *
  86113. * \default \c 0
  86114. * \param encoder An encoder instance to set.
  86115. * \param value See above.
  86116. * \assert
  86117. * \code encoder != NULL \endcode
  86118. * \retval FLAC__bool
  86119. * \c false if the encoder is already initialized, else \c true.
  86120. */
  86121. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value);
  86122. /** Set to \c false to use only the specified quantized linear predictor
  86123. * coefficient precision, or \c true to search neighboring precision
  86124. * values and use the best one.
  86125. *
  86126. * \default \c false
  86127. * \param encoder An encoder instance to set.
  86128. * \param value See above.
  86129. * \assert
  86130. * \code encoder != NULL \endcode
  86131. * \retval FLAC__bool
  86132. * \c false if the encoder is already initialized, else \c true.
  86133. */
  86134. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86135. /** Deprecated. Setting this value has no effect.
  86136. *
  86137. * \default \c false
  86138. * \param encoder An encoder instance to set.
  86139. * \param value See above.
  86140. * \assert
  86141. * \code encoder != NULL \endcode
  86142. * \retval FLAC__bool
  86143. * \c false if the encoder is already initialized, else \c true.
  86144. */
  86145. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86146. /** Set to \c false to let the encoder estimate the best model order
  86147. * based on the residual signal energy, or \c true to force the
  86148. * encoder to evaluate all order models and select the best.
  86149. *
  86150. * \default \c false
  86151. * \param encoder An encoder instance to set.
  86152. * \param value See above.
  86153. * \assert
  86154. * \code encoder != NULL \endcode
  86155. * \retval FLAC__bool
  86156. * \c false if the encoder is already initialized, else \c true.
  86157. */
  86158. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value);
  86159. /** Set the minimum partition order to search when coding the residual.
  86160. * This is used in tandem with
  86161. * FLAC__stream_encoder_set_max_residual_partition_order().
  86162. *
  86163. * The partition order determines the context size in the residual.
  86164. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  86165. *
  86166. * Set both min and max values to \c 0 to force a single context,
  86167. * whose Rice parameter is based on the residual signal variance.
  86168. * Otherwise, set a min and max order, and the encoder will search
  86169. * all orders, using the mean of each context for its Rice parameter,
  86170. * and use the best.
  86171. *
  86172. * \default \c 0
  86173. * \param encoder An encoder instance to set.
  86174. * \param value See above.
  86175. * \assert
  86176. * \code encoder != NULL \endcode
  86177. * \retval FLAC__bool
  86178. * \c false if the encoder is already initialized, else \c true.
  86179. */
  86180. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  86181. /** Set the maximum partition order to search when coding the residual.
  86182. * This is used in tandem with
  86183. * FLAC__stream_encoder_set_min_residual_partition_order().
  86184. *
  86185. * The partition order determines the context size in the residual.
  86186. * The context size will be approximately <tt>blocksize / (2 ^ order)</tt>.
  86187. *
  86188. * Set both min and max values to \c 0 to force a single context,
  86189. * whose Rice parameter is based on the residual signal variance.
  86190. * Otherwise, set a min and max order, and the encoder will search
  86191. * all orders, using the mean of each context for its Rice parameter,
  86192. * and use the best.
  86193. *
  86194. * \default \c 0
  86195. * \param encoder An encoder instance to set.
  86196. * \param value See above.
  86197. * \assert
  86198. * \code encoder != NULL \endcode
  86199. * \retval FLAC__bool
  86200. * \c false if the encoder is already initialized, else \c true.
  86201. */
  86202. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value);
  86203. /** Deprecated. Setting this value has no effect.
  86204. *
  86205. * \default \c 0
  86206. * \param encoder An encoder instance to set.
  86207. * \param value See above.
  86208. * \assert
  86209. * \code encoder != NULL \endcode
  86210. * \retval FLAC__bool
  86211. * \c false if the encoder is already initialized, else \c true.
  86212. */
  86213. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value);
  86214. /** Set an estimate of the total samples that will be encoded.
  86215. * This is merely an estimate and may be set to \c 0 if unknown.
  86216. * This value will be written to the STREAMINFO block before encoding,
  86217. * and can remove the need for the caller to rewrite the value later
  86218. * if the value is known before encoding.
  86219. *
  86220. * \default \c 0
  86221. * \param encoder An encoder instance to set.
  86222. * \param value See above.
  86223. * \assert
  86224. * \code encoder != NULL \endcode
  86225. * \retval FLAC__bool
  86226. * \c false if the encoder is already initialized, else \c true.
  86227. */
  86228. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value);
  86229. /** Set the metadata blocks to be emitted to the stream before encoding.
  86230. * A value of \c NULL, \c 0 implies no metadata; otherwise, supply an
  86231. * array of pointers to metadata blocks. The array is non-const since
  86232. * the encoder may need to change the \a is_last flag inside them, and
  86233. * in some cases update seek point offsets. Otherwise, the encoder will
  86234. * not modify or free the blocks. It is up to the caller to free the
  86235. * metadata blocks after encoding finishes.
  86236. *
  86237. * \note
  86238. * The encoder stores only copies of the pointers in the \a metadata array;
  86239. * the metadata blocks themselves must survive at least until after
  86240. * FLAC__stream_encoder_finish() returns. Do not free the blocks until then.
  86241. *
  86242. * \note
  86243. * The STREAMINFO block is always written and no STREAMINFO block may
  86244. * occur in the supplied array.
  86245. *
  86246. * \note
  86247. * By default the encoder does not create a SEEKTABLE. If one is supplied
  86248. * in the \a metadata array, but the client has specified that it does not
  86249. * support seeking, then the SEEKTABLE will be written verbatim. However
  86250. * by itself this is not very useful as the client will not know the stream
  86251. * offsets for the seekpoints ahead of time. In order to get a proper
  86252. * seektable the client must support seeking. See next note.
  86253. *
  86254. * \note
  86255. * SEEKTABLE blocks are handled specially. Since you will not know
  86256. * the values for the seek point stream offsets, you should pass in
  86257. * a SEEKTABLE 'template', that is, a SEEKTABLE object with the
  86258. * required sample numbers (or placeholder points), with \c 0 for the
  86259. * \a frame_samples and \a stream_offset fields for each point. If the
  86260. * client has specified that it supports seeking by providing a seek
  86261. * callback to FLAC__stream_encoder_init_stream() or both seek AND read
  86262. * callback to FLAC__stream_encoder_init_ogg_stream() (or by using
  86263. * FLAC__stream_encoder_init*_file() or FLAC__stream_encoder_init*_FILE()),
  86264. * then while it is encoding the encoder will fill the stream offsets in
  86265. * for you and when encoding is finished, it will seek back and write the
  86266. * real values into the SEEKTABLE block in the stream. There are helper
  86267. * routines for manipulating seektable template blocks; see metadata.h:
  86268. * FLAC__metadata_object_seektable_template_*(). If the client does
  86269. * not support seeking, the SEEKTABLE will have inaccurate offsets which
  86270. * will slow down or remove the ability to seek in the FLAC stream.
  86271. *
  86272. * \note
  86273. * The encoder instance \b will modify the first \c SEEKTABLE block
  86274. * as it transforms the template to a valid seektable while encoding,
  86275. * but it is still up to the caller to free all metadata blocks after
  86276. * encoding.
  86277. *
  86278. * \note
  86279. * A VORBIS_COMMENT block may be supplied. The vendor string in it
  86280. * will be ignored. libFLAC will use it's own vendor string. libFLAC
  86281. * will not modify the passed-in VORBIS_COMMENT's vendor string, it
  86282. * will simply write it's own into the stream. If no VORBIS_COMMENT
  86283. * block is present in the \a metadata array, libFLAC will write an
  86284. * empty one, containing only the vendor string.
  86285. *
  86286. * \note The Ogg FLAC mapping requires that the VORBIS_COMMENT block be
  86287. * the second metadata block of the stream. The encoder already supplies
  86288. * the STREAMINFO block automatically. If \a metadata does not contain a
  86289. * VORBIS_COMMENT block, the encoder will supply that too. Otherwise, if
  86290. * \a metadata does contain a VORBIS_COMMENT block and it is not the
  86291. * first, the init function will reorder \a metadata by moving the
  86292. * VORBIS_COMMENT block to the front; the relative ordering of the other
  86293. * blocks will remain as they were.
  86294. *
  86295. * \note The Ogg FLAC mapping limits the number of metadata blocks per
  86296. * stream to \c 65535. If \a num_blocks exceeds this the function will
  86297. * return \c false.
  86298. *
  86299. * \default \c NULL, 0
  86300. * \param encoder An encoder instance to set.
  86301. * \param metadata See above.
  86302. * \param num_blocks See above.
  86303. * \assert
  86304. * \code encoder != NULL \endcode
  86305. * \retval FLAC__bool
  86306. * \c false if the encoder is already initialized, else \c true.
  86307. * \c false if the encoder is already initialized, or if
  86308. * \a num_blocks > 65535 if encoding to Ogg FLAC, else \c true.
  86309. */
  86310. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks);
  86311. /** Get the current encoder state.
  86312. *
  86313. * \param encoder An encoder instance to query.
  86314. * \assert
  86315. * \code encoder != NULL \endcode
  86316. * \retval FLAC__StreamEncoderState
  86317. * The current encoder state.
  86318. */
  86319. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder);
  86320. /** Get the state of the verify stream decoder.
  86321. * Useful when the stream encoder state is
  86322. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR.
  86323. *
  86324. * \param encoder An encoder instance to query.
  86325. * \assert
  86326. * \code encoder != NULL \endcode
  86327. * \retval FLAC__StreamDecoderState
  86328. * The verify stream decoder state.
  86329. */
  86330. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder);
  86331. /** Get the current encoder state as a C string.
  86332. * This version automatically resolves
  86333. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR by getting the
  86334. * verify decoder's state.
  86335. *
  86336. * \param encoder A encoder instance to query.
  86337. * \assert
  86338. * \code encoder != NULL \endcode
  86339. * \retval const char *
  86340. * The encoder state as a C string. Do not modify the contents.
  86341. */
  86342. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder);
  86343. /** Get relevant values about the nature of a verify decoder error.
  86344. * Useful when the stream encoder state is
  86345. * \c FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR. The arguments should
  86346. * be addresses in which the stats will be returned, or NULL if value
  86347. * is not desired.
  86348. *
  86349. * \param encoder An encoder instance to query.
  86350. * \param absolute_sample The absolute sample number of the mismatch.
  86351. * \param frame_number The number of the frame in which the mismatch occurred.
  86352. * \param channel The channel in which the mismatch occurred.
  86353. * \param sample The number of the sample (relative to the frame) in
  86354. * which the mismatch occurred.
  86355. * \param expected The expected value for the sample in question.
  86356. * \param got The actual value returned by the decoder.
  86357. * \assert
  86358. * \code encoder != NULL \endcode
  86359. */
  86360. 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);
  86361. /** Get the "verify" flag.
  86362. *
  86363. * \param encoder An encoder instance to query.
  86364. * \assert
  86365. * \code encoder != NULL \endcode
  86366. * \retval FLAC__bool
  86367. * See FLAC__stream_encoder_set_verify().
  86368. */
  86369. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder);
  86370. /** Get the <A HREF="../format.html#subset>Subset</A> flag.
  86371. *
  86372. * \param encoder An encoder instance to query.
  86373. * \assert
  86374. * \code encoder != NULL \endcode
  86375. * \retval FLAC__bool
  86376. * See FLAC__stream_encoder_set_streamable_subset().
  86377. */
  86378. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder);
  86379. /** Get the number of input channels being processed.
  86380. *
  86381. * \param encoder An encoder instance to query.
  86382. * \assert
  86383. * \code encoder != NULL \endcode
  86384. * \retval unsigned
  86385. * See FLAC__stream_encoder_set_channels().
  86386. */
  86387. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder);
  86388. /** Get the input sample resolution setting.
  86389. *
  86390. * \param encoder An encoder instance to query.
  86391. * \assert
  86392. * \code encoder != NULL \endcode
  86393. * \retval unsigned
  86394. * See FLAC__stream_encoder_set_bits_per_sample().
  86395. */
  86396. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder);
  86397. /** Get the input sample rate setting.
  86398. *
  86399. * \param encoder An encoder instance to query.
  86400. * \assert
  86401. * \code encoder != NULL \endcode
  86402. * \retval unsigned
  86403. * See FLAC__stream_encoder_set_sample_rate().
  86404. */
  86405. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder);
  86406. /** Get the blocksize setting.
  86407. *
  86408. * \param encoder An encoder instance to query.
  86409. * \assert
  86410. * \code encoder != NULL \endcode
  86411. * \retval unsigned
  86412. * See FLAC__stream_encoder_set_blocksize().
  86413. */
  86414. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder);
  86415. /** Get the "mid/side stereo coding" flag.
  86416. *
  86417. * \param encoder An encoder instance to query.
  86418. * \assert
  86419. * \code encoder != NULL \endcode
  86420. * \retval FLAC__bool
  86421. * See FLAC__stream_encoder_get_do_mid_side_stereo().
  86422. */
  86423. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  86424. /** Get the "adaptive mid/side switching" flag.
  86425. *
  86426. * \param encoder An encoder instance to query.
  86427. * \assert
  86428. * \code encoder != NULL \endcode
  86429. * \retval FLAC__bool
  86430. * See FLAC__stream_encoder_set_loose_mid_side_stereo().
  86431. */
  86432. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder);
  86433. /** Get the maximum LPC order setting.
  86434. *
  86435. * \param encoder An encoder instance to query.
  86436. * \assert
  86437. * \code encoder != NULL \endcode
  86438. * \retval unsigned
  86439. * See FLAC__stream_encoder_set_max_lpc_order().
  86440. */
  86441. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder);
  86442. /** Get the quantized linear predictor coefficient precision setting.
  86443. *
  86444. * \param encoder An encoder instance to query.
  86445. * \assert
  86446. * \code encoder != NULL \endcode
  86447. * \retval unsigned
  86448. * See FLAC__stream_encoder_set_qlp_coeff_precision().
  86449. */
  86450. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder);
  86451. /** Get the qlp coefficient precision search flag.
  86452. *
  86453. * \param encoder An encoder instance to query.
  86454. * \assert
  86455. * \code encoder != NULL \endcode
  86456. * \retval FLAC__bool
  86457. * See FLAC__stream_encoder_set_do_qlp_coeff_prec_search().
  86458. */
  86459. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder);
  86460. /** Get the "escape coding" flag.
  86461. *
  86462. * \param encoder An encoder instance to query.
  86463. * \assert
  86464. * \code encoder != NULL \endcode
  86465. * \retval FLAC__bool
  86466. * See FLAC__stream_encoder_set_do_escape_coding().
  86467. */
  86468. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder);
  86469. /** Get the exhaustive model search flag.
  86470. *
  86471. * \param encoder An encoder instance to query.
  86472. * \assert
  86473. * \code encoder != NULL \endcode
  86474. * \retval FLAC__bool
  86475. * See FLAC__stream_encoder_set_do_exhaustive_model_search().
  86476. */
  86477. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder);
  86478. /** Get the minimum residual partition order setting.
  86479. *
  86480. * \param encoder An encoder instance to query.
  86481. * \assert
  86482. * \code encoder != NULL \endcode
  86483. * \retval unsigned
  86484. * See FLAC__stream_encoder_set_min_residual_partition_order().
  86485. */
  86486. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder);
  86487. /** Get maximum residual partition order setting.
  86488. *
  86489. * \param encoder An encoder instance to query.
  86490. * \assert
  86491. * \code encoder != NULL \endcode
  86492. * \retval unsigned
  86493. * See FLAC__stream_encoder_set_max_residual_partition_order().
  86494. */
  86495. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder);
  86496. /** Get the Rice parameter search distance setting.
  86497. *
  86498. * \param encoder An encoder instance to query.
  86499. * \assert
  86500. * \code encoder != NULL \endcode
  86501. * \retval unsigned
  86502. * See FLAC__stream_encoder_set_rice_parameter_search_dist().
  86503. */
  86504. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder);
  86505. /** Get the previously set estimate of the total samples to be encoded.
  86506. * The encoder merely mimics back the value given to
  86507. * FLAC__stream_encoder_set_total_samples_estimate() since it has no
  86508. * other way of knowing how many samples the client will encode.
  86509. *
  86510. * \param encoder An encoder instance to set.
  86511. * \assert
  86512. * \code encoder != NULL \endcode
  86513. * \retval FLAC__uint64
  86514. * See FLAC__stream_encoder_get_total_samples_estimate().
  86515. */
  86516. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder);
  86517. /** Initialize the encoder instance to encode native FLAC streams.
  86518. *
  86519. * This flavor of initialization sets up the encoder to encode to a
  86520. * native FLAC stream. I/O is performed via callbacks to the client.
  86521. * For encoding to a plain file via filename or open \c FILE*,
  86522. * FLAC__stream_encoder_init_file() and FLAC__stream_encoder_init_FILE()
  86523. * provide a simpler interface.
  86524. *
  86525. * This function should be called after FLAC__stream_encoder_new() and
  86526. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86527. * or FLAC__stream_encoder_process_interleaved().
  86528. * initialization succeeded.
  86529. *
  86530. * The call to FLAC__stream_encoder_init_stream() currently will also
  86531. * immediately call the write callback several times, once with the \c fLaC
  86532. * signature, and once for each encoded metadata block.
  86533. *
  86534. * \param encoder An uninitialized encoder instance.
  86535. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  86536. * pointer must not be \c NULL.
  86537. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  86538. * pointer may be \c NULL if seeking is not
  86539. * supported. The encoder uses seeking to go back
  86540. * and write some some stream statistics to the
  86541. * STREAMINFO block; this is recommended but not
  86542. * necessary to create a valid FLAC stream. If
  86543. * \a seek_callback is not \c NULL then a
  86544. * \a tell_callback must also be supplied.
  86545. * Alternatively, a dummy seek callback that just
  86546. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86547. * may also be supplied, all though this is slightly
  86548. * less efficient for the encoder.
  86549. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  86550. * pointer may be \c NULL if seeking is not
  86551. * supported. If \a seek_callback is \c NULL then
  86552. * this argument will be ignored. If
  86553. * \a seek_callback is not \c NULL then a
  86554. * \a tell_callback must also be supplied.
  86555. * Alternatively, a dummy tell callback that just
  86556. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  86557. * may also be supplied, all though this is slightly
  86558. * less efficient for the encoder.
  86559. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  86560. * pointer may be \c NULL if the callback is not
  86561. * desired. If the client provides a seek callback,
  86562. * this function is not necessary as the encoder
  86563. * will automatically seek back and update the
  86564. * STREAMINFO block. It may also be \c NULL if the
  86565. * client does not support seeking, since it will
  86566. * have no way of going back to update the
  86567. * STREAMINFO. However the client can still supply
  86568. * a callback if it would like to know the details
  86569. * from the STREAMINFO.
  86570. * \param client_data This value will be supplied to callbacks in their
  86571. * \a client_data argument.
  86572. * \assert
  86573. * \code encoder != NULL \endcode
  86574. * \retval FLAC__StreamEncoderInitStatus
  86575. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86576. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86577. */
  86578. 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);
  86579. /** Initialize the encoder instance to encode Ogg FLAC streams.
  86580. *
  86581. * This flavor of initialization sets up the encoder to encode to a FLAC
  86582. * stream in an Ogg container. I/O is performed via callbacks to the
  86583. * client. For encoding to a plain file via filename or open \c FILE*,
  86584. * FLAC__stream_encoder_init_ogg_file() and FLAC__stream_encoder_init_ogg_FILE()
  86585. * provide a simpler interface.
  86586. *
  86587. * This function should be called after FLAC__stream_encoder_new() and
  86588. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86589. * or FLAC__stream_encoder_process_interleaved().
  86590. * initialization succeeded.
  86591. *
  86592. * The call to FLAC__stream_encoder_init_ogg_stream() currently will also
  86593. * immediately call the write callback several times to write the metadata
  86594. * packets.
  86595. *
  86596. * \param encoder An uninitialized encoder instance.
  86597. * \param read_callback See FLAC__StreamEncoderReadCallback. This
  86598. * pointer must not be \c NULL if \a seek_callback
  86599. * is non-NULL since they are both needed to be
  86600. * able to write data back to the Ogg FLAC stream
  86601. * in the post-encode phase.
  86602. * \param write_callback See FLAC__StreamEncoderWriteCallback. This
  86603. * pointer must not be \c NULL.
  86604. * \param seek_callback See FLAC__StreamEncoderSeekCallback. This
  86605. * pointer may be \c NULL if seeking is not
  86606. * supported. The encoder uses seeking to go back
  86607. * and write some some stream statistics to the
  86608. * STREAMINFO block; this is recommended but not
  86609. * necessary to create a valid FLAC stream. If
  86610. * \a seek_callback is not \c NULL then a
  86611. * \a tell_callback must also be supplied.
  86612. * Alternatively, a dummy seek callback that just
  86613. * returns \c FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED
  86614. * may also be supplied, all though this is slightly
  86615. * less efficient for the encoder.
  86616. * \param tell_callback See FLAC__StreamEncoderTellCallback. This
  86617. * pointer may be \c NULL if seeking is not
  86618. * supported. If \a seek_callback is \c NULL then
  86619. * this argument will be ignored. If
  86620. * \a seek_callback is not \c NULL then a
  86621. * \a tell_callback must also be supplied.
  86622. * Alternatively, a dummy tell callback that just
  86623. * returns \c FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED
  86624. * may also be supplied, all though this is slightly
  86625. * less efficient for the encoder.
  86626. * \param metadata_callback See FLAC__StreamEncoderMetadataCallback. This
  86627. * pointer may be \c NULL if the callback is not
  86628. * desired. If the client provides a seek callback,
  86629. * this function is not necessary as the encoder
  86630. * will automatically seek back and update the
  86631. * STREAMINFO block. It may also be \c NULL if the
  86632. * client does not support seeking, since it will
  86633. * have no way of going back to update the
  86634. * STREAMINFO. However the client can still supply
  86635. * a callback if it would like to know the details
  86636. * from the STREAMINFO.
  86637. * \param client_data This value will be supplied to callbacks in their
  86638. * \a client_data argument.
  86639. * \assert
  86640. * \code encoder != NULL \endcode
  86641. * \retval FLAC__StreamEncoderInitStatus
  86642. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86643. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86644. */
  86645. 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);
  86646. /** Initialize the encoder instance to encode native FLAC files.
  86647. *
  86648. * This flavor of initialization sets up the encoder to encode to a
  86649. * plain native FLAC file. For non-stdio streams, you must use
  86650. * FLAC__stream_encoder_init_stream() and provide callbacks for the I/O.
  86651. *
  86652. * This function should be called after FLAC__stream_encoder_new() and
  86653. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86654. * or FLAC__stream_encoder_process_interleaved().
  86655. * initialization succeeded.
  86656. *
  86657. * \param encoder An uninitialized encoder instance.
  86658. * \param file An open file. The file should have been opened
  86659. * with mode \c "w+b" and rewound. The file
  86660. * becomes owned by the encoder and should not be
  86661. * manipulated by the client while encoding.
  86662. * Unless \a file is \c stdout, it will be closed
  86663. * when FLAC__stream_encoder_finish() is called.
  86664. * Note however that a proper SEEKTABLE cannot be
  86665. * created when encoding to \c stdout since it is
  86666. * not seekable.
  86667. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86668. * pointer may be \c NULL if the callback is not
  86669. * desired.
  86670. * \param client_data This value will be supplied to callbacks in their
  86671. * \a client_data argument.
  86672. * \assert
  86673. * \code encoder != NULL \endcode
  86674. * \code file != NULL \endcode
  86675. * \retval FLAC__StreamEncoderInitStatus
  86676. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86677. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86678. */
  86679. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86680. /** Initialize the encoder instance to encode Ogg FLAC files.
  86681. *
  86682. * This flavor of initialization sets up the encoder to encode to a
  86683. * plain Ogg FLAC file. For non-stdio streams, you must use
  86684. * FLAC__stream_encoder_init_ogg_stream() and provide callbacks for the I/O.
  86685. *
  86686. * This function should be called after FLAC__stream_encoder_new() and
  86687. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86688. * or FLAC__stream_encoder_process_interleaved().
  86689. * initialization succeeded.
  86690. *
  86691. * \param encoder An uninitialized encoder instance.
  86692. * \param file An open file. The file should have been opened
  86693. * with mode \c "w+b" and rewound. The file
  86694. * becomes owned by the encoder and should not be
  86695. * manipulated by the client while encoding.
  86696. * Unless \a file is \c stdout, it will be closed
  86697. * when FLAC__stream_encoder_finish() is called.
  86698. * Note however that a proper SEEKTABLE cannot be
  86699. * created when encoding to \c stdout since it is
  86700. * not seekable.
  86701. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86702. * pointer may be \c NULL if the callback is not
  86703. * desired.
  86704. * \param client_data This value will be supplied to callbacks in their
  86705. * \a client_data argument.
  86706. * \assert
  86707. * \code encoder != NULL \endcode
  86708. * \code file != NULL \endcode
  86709. * \retval FLAC__StreamEncoderInitStatus
  86710. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86711. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86712. */
  86713. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(FLAC__StreamEncoder *encoder, FILE *file, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86714. /** Initialize the encoder instance to encode native FLAC files.
  86715. *
  86716. * This flavor of initialization sets up the encoder to encode to a plain
  86717. * FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  86718. * with Unicode filenames on Windows), you must use
  86719. * FLAC__stream_encoder_init_FILE(), or FLAC__stream_encoder_init_stream()
  86720. * and provide callbacks for the I/O.
  86721. *
  86722. * This function should be called after FLAC__stream_encoder_new() and
  86723. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86724. * or FLAC__stream_encoder_process_interleaved().
  86725. * initialization succeeded.
  86726. *
  86727. * \param encoder An uninitialized encoder instance.
  86728. * \param filename The name of the file to encode to. The file will
  86729. * be opened with fopen(). Use \c NULL to encode to
  86730. * \c stdout. Note however that a proper SEEKTABLE
  86731. * cannot be created when encoding to \c stdout since
  86732. * it is not seekable.
  86733. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86734. * pointer may be \c NULL if the callback is not
  86735. * desired.
  86736. * \param client_data This value will be supplied to callbacks in their
  86737. * \a client_data argument.
  86738. * \assert
  86739. * \code encoder != NULL \endcode
  86740. * \retval FLAC__StreamEncoderInitStatus
  86741. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86742. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86743. */
  86744. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86745. /** Initialize the encoder instance to encode Ogg FLAC files.
  86746. *
  86747. * This flavor of initialization sets up the encoder to encode to a plain
  86748. * Ogg FLAC file. If POSIX fopen() semantics are not sufficient (for example,
  86749. * with Unicode filenames on Windows), you must use
  86750. * FLAC__stream_encoder_init_ogg_FILE(), or FLAC__stream_encoder_init_ogg_stream()
  86751. * and provide callbacks for the I/O.
  86752. *
  86753. * This function should be called after FLAC__stream_encoder_new() and
  86754. * FLAC__stream_encoder_set_*() but before FLAC__stream_encoder_process()
  86755. * or FLAC__stream_encoder_process_interleaved().
  86756. * initialization succeeded.
  86757. *
  86758. * \param encoder An uninitialized encoder instance.
  86759. * \param filename The name of the file to encode to. The file will
  86760. * be opened with fopen(). Use \c NULL to encode to
  86761. * \c stdout. Note however that a proper SEEKTABLE
  86762. * cannot be created when encoding to \c stdout since
  86763. * it is not seekable.
  86764. * \param progress_callback See FLAC__StreamEncoderProgressCallback. This
  86765. * pointer may be \c NULL if the callback is not
  86766. * desired.
  86767. * \param client_data This value will be supplied to callbacks in their
  86768. * \a client_data argument.
  86769. * \assert
  86770. * \code encoder != NULL \endcode
  86771. * \retval FLAC__StreamEncoderInitStatus
  86772. * \c FLAC__STREAM_ENCODER_INIT_STATUS_OK if initialization was successful;
  86773. * see FLAC__StreamEncoderInitStatus for the meanings of other return values.
  86774. */
  86775. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(FLAC__StreamEncoder *encoder, const char *filename, FLAC__StreamEncoderProgressCallback progress_callback, void *client_data);
  86776. /** Finish the encoding process.
  86777. * Flushes the encoding buffer, releases resources, resets the encoder
  86778. * settings to their defaults, and returns the encoder state to
  86779. * FLAC__STREAM_ENCODER_UNINITIALIZED. Note that this can generate
  86780. * one or more write callbacks before returning, and will generate
  86781. * a metadata callback.
  86782. *
  86783. * Note that in the course of processing the last frame, errors can
  86784. * occur, so the caller should be sure to check the return value to
  86785. * ensure the file was encoded properly.
  86786. *
  86787. * In the event of a prematurely-terminated encode, it is not strictly
  86788. * necessary to call this immediately before FLAC__stream_encoder_delete()
  86789. * but it is good practice to match every FLAC__stream_encoder_init_*()
  86790. * with a FLAC__stream_encoder_finish().
  86791. *
  86792. * \param encoder An uninitialized encoder instance.
  86793. * \assert
  86794. * \code encoder != NULL \endcode
  86795. * \retval FLAC__bool
  86796. * \c false if an error occurred processing the last frame; or if verify
  86797. * mode is set (see FLAC__stream_encoder_set_verify()), there was a
  86798. * verify mismatch; else \c true. If \c false, caller should check the
  86799. * state with FLAC__stream_encoder_get_state() for more information
  86800. * about the error.
  86801. */
  86802. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder);
  86803. /** Submit data for encoding.
  86804. * This version allows you to supply the input data via an array of
  86805. * pointers, each pointer pointing to an array of \a samples samples
  86806. * representing one channel. The samples need not be block-aligned,
  86807. * but each channel should have the same number of samples. Each sample
  86808. * should be a signed integer, right-justified to the resolution set by
  86809. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  86810. * resolution is 16 bits per sample, the samples should all be in the
  86811. * range [-32768,32767].
  86812. *
  86813. * For applications where channel order is important, channels must
  86814. * follow the order as described in the
  86815. * <A HREF="../format.html#frame_header">frame header</A>.
  86816. *
  86817. * \param encoder An initialized encoder instance in the OK state.
  86818. * \param buffer An array of pointers to each channel's signal.
  86819. * \param samples The number of samples in one channel.
  86820. * \assert
  86821. * \code encoder != NULL \endcode
  86822. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  86823. * \retval FLAC__bool
  86824. * \c true if successful, else \c false; in this case, check the
  86825. * encoder state with FLAC__stream_encoder_get_state() to see what
  86826. * went wrong.
  86827. */
  86828. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples);
  86829. /** Submit data for encoding.
  86830. * This version allows you to supply the input data where the channels
  86831. * are interleaved into a single array (i.e. channel0_sample0,
  86832. * channel1_sample0, ... , channelN_sample0, channel0_sample1, ...).
  86833. * The samples need not be block-aligned but they must be
  86834. * sample-aligned, i.e. the first value should be channel0_sample0
  86835. * and the last value channelN_sampleM. Each sample should be a signed
  86836. * integer, right-justified to the resolution set by
  86837. * FLAC__stream_encoder_set_bits_per_sample(). For example, if the
  86838. * resolution is 16 bits per sample, the samples should all be in the
  86839. * range [-32768,32767].
  86840. *
  86841. * For applications where channel order is important, channels must
  86842. * follow the order as described in the
  86843. * <A HREF="../format.html#frame_header">frame header</A>.
  86844. *
  86845. * \param encoder An initialized encoder instance in the OK state.
  86846. * \param buffer An array of channel-interleaved data (see above).
  86847. * \param samples The number of samples in one channel, the same as for
  86848. * FLAC__stream_encoder_process(). For example, if
  86849. * encoding two channels, \c 1000 \a samples corresponds
  86850. * to a \a buffer of 2000 values.
  86851. * \assert
  86852. * \code encoder != NULL \endcode
  86853. * \code FLAC__stream_encoder_get_state(encoder) == FLAC__STREAM_ENCODER_OK \endcode
  86854. * \retval FLAC__bool
  86855. * \c true if successful, else \c false; in this case, check the
  86856. * encoder state with FLAC__stream_encoder_get_state() to see what
  86857. * went wrong.
  86858. */
  86859. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples);
  86860. /* \} */
  86861. #ifdef __cplusplus
  86862. }
  86863. #endif
  86864. #endif
  86865. /********* End of inlined file: stream_encoder.h *********/
  86866. #ifdef _MSC_VER
  86867. /* OPT: an MSVC built-in would be better */
  86868. static _inline FLAC__uint32 local_swap32_(FLAC__uint32 x)
  86869. {
  86870. x = ((x<<8)&0xFF00FF00) | ((x>>8)&0x00FF00FF);
  86871. return (x>>16) | (x<<16);
  86872. }
  86873. #endif
  86874. #if defined(_MSC_VER) && defined(_X86_)
  86875. /* OPT: an MSVC built-in would be better */
  86876. static void local_swap32_block_(FLAC__uint32 *start, FLAC__uint32 len)
  86877. {
  86878. __asm {
  86879. mov edx, start
  86880. mov ecx, len
  86881. test ecx, ecx
  86882. loop1:
  86883. jz done1
  86884. mov eax, [edx]
  86885. bswap eax
  86886. mov [edx], eax
  86887. add edx, 4
  86888. dec ecx
  86889. jmp short loop1
  86890. done1:
  86891. }
  86892. }
  86893. #endif
  86894. /** \mainpage
  86895. *
  86896. * \section intro Introduction
  86897. *
  86898. * This is the documentation for the FLAC C and C++ APIs. It is
  86899. * highly interconnected; this introduction should give you a top
  86900. * level idea of the structure and how to find the information you
  86901. * need. As a prerequisite you should have at least a basic
  86902. * knowledge of the FLAC format, documented
  86903. * <A HREF="../format.html">here</A>.
  86904. *
  86905. * \section c_api FLAC C API
  86906. *
  86907. * The FLAC C API is the interface to libFLAC, a set of structures
  86908. * describing the components of FLAC streams, and functions for
  86909. * encoding and decoding streams, as well as manipulating FLAC
  86910. * metadata in files. The public include files will be installed
  86911. * in your include area (for example /usr/include/FLAC/...).
  86912. *
  86913. * By writing a little code and linking against libFLAC, it is
  86914. * relatively easy to add FLAC support to another program. The
  86915. * library is licensed under <A HREF="../license.html">Xiph's BSD license</A>.
  86916. * Complete source code of libFLAC as well as the command-line
  86917. * encoder and plugins is available and is a useful source of
  86918. * examples.
  86919. *
  86920. * Aside from encoders and decoders, libFLAC provides a powerful
  86921. * metadata interface for manipulating metadata in FLAC files. It
  86922. * allows the user to add, delete, and modify FLAC metadata blocks
  86923. * and it can automatically take advantage of PADDING blocks to avoid
  86924. * rewriting the entire FLAC file when changing the size of the
  86925. * metadata.
  86926. *
  86927. * libFLAC usually only requires the standard C library and C math
  86928. * library. In particular, threading is not used so there is no
  86929. * dependency on a thread library. However, libFLAC does not use
  86930. * global variables and should be thread-safe.
  86931. *
  86932. * libFLAC also supports encoding to and decoding from Ogg FLAC.
  86933. * However the metadata editing interfaces currently have limited
  86934. * read-only support for Ogg FLAC files.
  86935. *
  86936. * \section cpp_api FLAC C++ API
  86937. *
  86938. * The FLAC C++ API is a set of classes that encapsulate the
  86939. * structures and functions in libFLAC. They provide slightly more
  86940. * functionality with respect to metadata but are otherwise
  86941. * equivalent. For the most part, they share the same usage as
  86942. * their counterparts in libFLAC, and the FLAC C API documentation
  86943. * can be used as a supplement. The public include files
  86944. * for the C++ API will be installed in your include area (for
  86945. * example /usr/include/FLAC++/...).
  86946. *
  86947. * libFLAC++ is also licensed under
  86948. * <A HREF="../license.html">Xiph's BSD license</A>.
  86949. *
  86950. * \section getting_started Getting Started
  86951. *
  86952. * A good starting point for learning the API is to browse through
  86953. * the <A HREF="modules.html">modules</A>. Modules are logical
  86954. * groupings of related functions or classes, which correspond roughly
  86955. * to header files or sections of header files. Each module includes a
  86956. * detailed description of the general usage of its functions or
  86957. * classes.
  86958. *
  86959. * From there you can go on to look at the documentation of
  86960. * individual functions. You can see different views of the individual
  86961. * functions through the links in top bar across this page.
  86962. *
  86963. * If you prefer a more hands-on approach, you can jump right to some
  86964. * <A HREF="../documentation_example_code.html">example code</A>.
  86965. *
  86966. * \section porting_guide Porting Guide
  86967. *
  86968. * Starting with FLAC 1.1.3 a \link porting Porting Guide \endlink
  86969. * has been introduced which gives detailed instructions on how to
  86970. * port your code to newer versions of FLAC.
  86971. *
  86972. * \section embedded_developers Embedded Developers
  86973. *
  86974. * libFLAC has grown larger over time as more functionality has been
  86975. * included, but much of it may be unnecessary for a particular embedded
  86976. * implementation. Unused parts may be pruned by some simple editing of
  86977. * src/libFLAC/Makefile.am. In general, the decoders, encoders, and
  86978. * metadata interface are all independent from each other.
  86979. *
  86980. * It is easiest to just describe the dependencies:
  86981. *
  86982. * - All modules depend on the \link flac_format Format \endlink module.
  86983. * - The decoders and encoders depend on the bitbuffer.
  86984. * - The decoder is independent of the encoder. The encoder uses the
  86985. * decoder because of the verify feature, but this can be removed if
  86986. * not needed.
  86987. * - Parts of the metadata interface require the stream decoder (but not
  86988. * the encoder).
  86989. * - Ogg support is selectable through the compile time macro
  86990. * \c FLAC__HAS_OGG.
  86991. *
  86992. * For example, if your application only requires the stream decoder, no
  86993. * encoder, and no metadata interface, you can remove the stream encoder
  86994. * and the metadata interface, which will greatly reduce the size of the
  86995. * library.
  86996. *
  86997. * Also, there are several places in the libFLAC code with comments marked
  86998. * with "OPT:" where a #define can be changed to enable code that might be
  86999. * faster on a specific platform. Experimenting with these can yield faster
  87000. * binaries.
  87001. */
  87002. /** \defgroup porting Porting Guide for New Versions
  87003. *
  87004. * This module describes differences in the library interfaces from
  87005. * version to version. It assists in the porting of code that uses
  87006. * the libraries to newer versions of FLAC.
  87007. *
  87008. * One simple facility for making porting easier that has been added
  87009. * in FLAC 1.1.3 is a set of \c #defines in \c export.h of each
  87010. * library's includes (e.g. \c include/FLAC/export.h). The
  87011. * \c #defines mirror the libraries'
  87012. * <A HREF="http://www.gnu.org/software/libtool/manual.html#Libtool-versioning">libtool version numbers</A>,
  87013. * e.g. in libFLAC there are \c FLAC_API_VERSION_CURRENT,
  87014. * \c FLAC_API_VERSION_REVISION, and \c FLAC_API_VERSION_AGE.
  87015. * These can be used to support multiple versions of an API during the
  87016. * transition phase, e.g.
  87017. *
  87018. * \code
  87019. * #if !defined(FLAC_API_VERSION_CURRENT) || FLAC_API_VERSION_CURRENT <= 7
  87020. * legacy code
  87021. * #else
  87022. * new code
  87023. * #endif
  87024. * \endcode
  87025. *
  87026. * The the source will work for multiple versions and the legacy code can
  87027. * easily be removed when the transition is complete.
  87028. *
  87029. * Another available symbol is FLAC_API_SUPPORTS_OGG_FLAC (defined in
  87030. * include/FLAC/export.h), which can be used to determine whether or not
  87031. * the library has been compiled with support for Ogg FLAC. This is
  87032. * simpler than trying to call an Ogg init function and catching the
  87033. * error.
  87034. */
  87035. /** \defgroup porting_1_1_2_to_1_1_3 Porting from FLAC 1.1.2 to 1.1.3
  87036. * \ingroup porting
  87037. *
  87038. * \brief
  87039. * This module describes porting from FLAC 1.1.2 to FLAC 1.1.3.
  87040. *
  87041. * The main change between the APIs in 1.1.2 and 1.1.3 is that they have
  87042. * been simplified. First, libOggFLAC has been merged into libFLAC and
  87043. * libOggFLAC++ has been merged into libFLAC++. Second, both the three
  87044. * decoding layers and three encoding layers have been merged into a
  87045. * single stream decoder and stream encoder. That is, the functionality
  87046. * of FLAC__SeekableStreamDecoder and FLAC__FileDecoder has been merged
  87047. * into FLAC__StreamDecoder, and FLAC__SeekableStreamEncoder and
  87048. * FLAC__FileEncoder into FLAC__StreamEncoder. Only the
  87049. * FLAC__StreamDecoder and FLAC__StreamEncoder remain. What this means
  87050. * is there is now a single API that can be used to encode or decode
  87051. * streams to/from native FLAC or Ogg FLAC and the single API can work
  87052. * on both seekable and non-seekable streams.
  87053. *
  87054. * Instead of creating an encoder or decoder of a certain layer, now the
  87055. * client will always create a FLAC__StreamEncoder or
  87056. * FLAC__StreamDecoder. The old layers are now differentiated by the
  87057. * initialization function. For example, for the decoder,
  87058. * FLAC__stream_decoder_init() has been replaced by
  87059. * FLAC__stream_decoder_init_stream(). This init function takes
  87060. * callbacks for the I/O, and the seeking callbacks are optional. This
  87061. * allows the client to use the same object for seekable and
  87062. * non-seekable streams. For decoding a FLAC file directly, the client
  87063. * can use FLAC__stream_decoder_init_file() and pass just a filename
  87064. * and fewer callbacks; most of the other callbacks are supplied
  87065. * internally. For situations where fopen()ing by filename is not
  87066. * possible (e.g. Unicode filenames on Windows) the client can instead
  87067. * open the file itself and supply the FILE* to
  87068. * FLAC__stream_decoder_init_FILE(). The init functions now returns a
  87069. * FLAC__StreamDecoderInitStatus instead of FLAC__StreamDecoderState.
  87070. * Since the callbacks and client data are now passed to the init
  87071. * function, the FLAC__stream_decoder_set_*_callback() functions and
  87072. * FLAC__stream_decoder_set_client_data() are no longer needed. The
  87073. * rest of the calls to the decoder are the same as before.
  87074. *
  87075. * There are counterpart init functions for Ogg FLAC, e.g.
  87076. * FLAC__stream_decoder_init_ogg_stream(). All the rest of the calls
  87077. * and callbacks are the same as for native FLAC.
  87078. *
  87079. * As an example, in FLAC 1.1.2 a seekable stream decoder would have
  87080. * been set up like so:
  87081. *
  87082. * \code
  87083. * FLAC__SeekableStreamDecoder *decoder = FLAC__seekable_stream_decoder_new();
  87084. * if(decoder == NULL) do_something;
  87085. * FLAC__seekable_stream_decoder_set_md5_checking(decoder, true);
  87086. * [... other settings ...]
  87087. * FLAC__seekable_stream_decoder_set_read_callback(decoder, my_read_callback);
  87088. * FLAC__seekable_stream_decoder_set_seek_callback(decoder, my_seek_callback);
  87089. * FLAC__seekable_stream_decoder_set_tell_callback(decoder, my_tell_callback);
  87090. * FLAC__seekable_stream_decoder_set_length_callback(decoder, my_length_callback);
  87091. * FLAC__seekable_stream_decoder_set_eof_callback(decoder, my_eof_callback);
  87092. * FLAC__seekable_stream_decoder_set_write_callback(decoder, my_write_callback);
  87093. * FLAC__seekable_stream_decoder_set_metadata_callback(decoder, my_metadata_callback);
  87094. * FLAC__seekable_stream_decoder_set_error_callback(decoder, my_error_callback);
  87095. * FLAC__seekable_stream_decoder_set_client_data(decoder, my_client_data);
  87096. * if(FLAC__seekable_stream_decoder_init(decoder) != FLAC__SEEKABLE_STREAM_DECODER_OK) do_something;
  87097. * \endcode
  87098. *
  87099. * In FLAC 1.1.3 it is like this:
  87100. *
  87101. * \code
  87102. * FLAC__StreamDecoder *decoder = FLAC__stream_decoder_new();
  87103. * if(decoder == NULL) do_something;
  87104. * FLAC__stream_decoder_set_md5_checking(decoder, true);
  87105. * [... other settings ...]
  87106. * if(FLAC__stream_decoder_init_stream(
  87107. * decoder,
  87108. * my_read_callback,
  87109. * my_seek_callback, // or NULL
  87110. * my_tell_callback, // or NULL
  87111. * my_length_callback, // or NULL
  87112. * my_eof_callback, // or NULL
  87113. * my_write_callback,
  87114. * my_metadata_callback, // or NULL
  87115. * my_error_callback,
  87116. * my_client_data
  87117. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  87118. * \endcode
  87119. *
  87120. * or you could do;
  87121. *
  87122. * \code
  87123. * [...]
  87124. * FILE *file = fopen("somefile.flac","rb");
  87125. * if(file == NULL) do_somthing;
  87126. * if(FLAC__stream_decoder_init_FILE(
  87127. * decoder,
  87128. * file,
  87129. * my_write_callback,
  87130. * my_metadata_callback, // or NULL
  87131. * my_error_callback,
  87132. * my_client_data
  87133. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  87134. * \endcode
  87135. *
  87136. * or just:
  87137. *
  87138. * \code
  87139. * [...]
  87140. * if(FLAC__stream_decoder_init_file(
  87141. * decoder,
  87142. * "somefile.flac",
  87143. * my_write_callback,
  87144. * my_metadata_callback, // or NULL
  87145. * my_error_callback,
  87146. * my_client_data
  87147. * ) != FLAC__STREAM_DECODER_INIT_STATUS_OK) do_something;
  87148. * \endcode
  87149. *
  87150. * Another small change to the decoder is in how it handles unparseable
  87151. * streams. Before, when the decoder found an unparseable stream
  87152. * (reserved for when the decoder encounters a stream from a future
  87153. * encoder that it can't parse), it changed the state to
  87154. * \c FLAC__STREAM_DECODER_UNPARSEABLE_STREAM. Now the decoder instead
  87155. * drops sync and calls the error callback with a new error code
  87156. * \c FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM. This is
  87157. * more robust. If your error callback does not discriminate on the the
  87158. * error state, your code does not need to be changed.
  87159. *
  87160. * The encoder now has a new setting:
  87161. * FLAC__stream_encoder_set_apodization(). This is for setting the
  87162. * method used to window the data before LPC analysis. You only need to
  87163. * add a call to this function if the default is not suitable. There
  87164. * are also two new convenience functions that may be useful:
  87165. * FLAC__metadata_object_cuesheet_calculate_cddb_id() and
  87166. * FLAC__metadata_get_cuesheet().
  87167. *
  87168. * The \a bytes parameter to FLAC__StreamDecoderReadCallback,
  87169. * FLAC__StreamEncoderReadCallback, and FLAC__StreamEncoderWriteCallback
  87170. * is now \c size_t instead of \c unsigned.
  87171. */
  87172. /** \defgroup porting_1_1_3_to_1_1_4 Porting from FLAC 1.1.3 to 1.1.4
  87173. * \ingroup porting
  87174. *
  87175. * \brief
  87176. * This module describes porting from FLAC 1.1.3 to FLAC 1.1.4.
  87177. *
  87178. * There were no changes to any of the interfaces from 1.1.3 to 1.1.4.
  87179. * There was a slight change in the implementation of
  87180. * FLAC__stream_encoder_set_metadata(); the function now makes a copy
  87181. * of the \a metadata array of pointers so the client no longer needs
  87182. * to maintain it after the call. The objects themselves that are
  87183. * pointed to by the array are still not copied though and must be
  87184. * maintained until the call to FLAC__stream_encoder_finish().
  87185. */
  87186. /** \defgroup porting_1_1_4_to_1_2_0 Porting from FLAC 1.1.4 to 1.2.0
  87187. * \ingroup porting
  87188. *
  87189. * \brief
  87190. * This module describes porting from FLAC 1.1.4 to FLAC 1.2.0.
  87191. *
  87192. * There were only very minor changes to the interfaces from 1.1.4 to 1.2.0.
  87193. * In libFLAC, \c FLAC__format_sample_rate_is_subset() was added.
  87194. * In libFLAC++, \c FLAC::Decoder::Stream::get_decode_position() was added.
  87195. *
  87196. * Finally, value of the constant \c FLAC__FRAME_HEADER_RESERVED_LEN
  87197. * has changed to reflect the conversion of one of the reserved bits
  87198. * into active use. It used to be \c 2 and now is \c 1. However the
  87199. * FLAC frame header length has not changed, so to skip the proper
  87200. * number of bits, use \c FLAC__FRAME_HEADER_RESERVED_LEN +
  87201. * \c FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN
  87202. */
  87203. /** \defgroup flac FLAC C API
  87204. *
  87205. * The FLAC C API is the interface to libFLAC, a set of structures
  87206. * describing the components of FLAC streams, and functions for
  87207. * encoding and decoding streams, as well as manipulating FLAC
  87208. * metadata in files.
  87209. *
  87210. * You should start with the format components as all other modules
  87211. * are dependent on it.
  87212. */
  87213. #endif
  87214. /********* End of inlined file: all.h *********/
  87215. /********* Start of inlined file: bitmath.c *********/
  87216. /********* Start of inlined file: juce_FlacHeader.h *********/
  87217. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  87218. // tasks..
  87219. /********* Start of inlined file: juce_Config.h *********/
  87220. #ifndef __JUCE_CONFIG_JUCEHEADER__
  87221. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  87222. /*
  87223. This file contains macros that enable/disable various JUCE features.
  87224. */
  87225. /** The name of the namespace that all Juce classes and functions will be
  87226. put inside. If this is not defined, no namespace will be used.
  87227. */
  87228. #ifndef JUCE_NAMESPACE
  87229. #define JUCE_NAMESPACE juce
  87230. #endif
  87231. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  87232. but if you define this value, you can override this can force it to be true or
  87233. false.
  87234. */
  87235. #ifndef JUCE_FORCE_DEBUG
  87236. //#define JUCE_FORCE_DEBUG 1
  87237. #endif
  87238. /** If this flag is enabled, the the jassert and jassertfalse macros will
  87239. always use Logger::writeToLog() to write a message when an assertion happens.
  87240. Enabling it will also leave this turned on in release builds. When it's disabled,
  87241. however, the jassert and jassertfalse macros will not be compiled in a
  87242. release build.
  87243. @see jassert, jassertfalse, Logger
  87244. */
  87245. #ifndef JUCE_LOG_ASSERTIONS
  87246. // #define JUCE_LOG_ASSERTIONS 1
  87247. #endif
  87248. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  87249. which the ASIOAudioIODevice class can't be built. See the comments in the
  87250. ASIOAudioIODevice class's header file for more info about this.
  87251. (This only affects a Win32 build)
  87252. */
  87253. #ifndef JUCE_ASIO
  87254. #define JUCE_ASIO 1
  87255. #endif
  87256. /** Comment out this macro to disable building of ALSA device support on Linux.
  87257. */
  87258. #ifndef JUCE_ALSA
  87259. #define JUCE_ALSA 1
  87260. #endif
  87261. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  87262. have the SDK installed.
  87263. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  87264. classes will be unavailable.
  87265. On Windows, if you enable this, you'll need to have the QuickTime SDK
  87266. installed, and its header files will need to be on your include path.
  87267. */
  87268. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  87269. #define JUCE_QUICKTIME 1
  87270. #endif
  87271. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  87272. have the appropriate headers and libraries available. If it's not enabled, the
  87273. OpenGLComponent class will be unavailable.
  87274. */
  87275. #ifndef JUCE_OPENGL
  87276. #define JUCE_OPENGL 1
  87277. #endif
  87278. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  87279. If you're not going to need either of these formats, turn off the flags to
  87280. avoid bloating your codebase with them.
  87281. */
  87282. #ifndef JUCE_USE_FLAC
  87283. #define JUCE_USE_FLAC 1
  87284. #endif
  87285. #ifndef JUCE_USE_OGGVORBIS
  87286. #define JUCE_USE_OGGVORBIS 1
  87287. #endif
  87288. /** This flag lets you enable support for CD-burning. You might want to disable
  87289. it to build without the MS SDK under windows.
  87290. */
  87291. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  87292. #define JUCE_USE_CDBURNER 1
  87293. #endif
  87294. /** Enabling this macro means that all regions that get repainted will have a coloured
  87295. line drawn around them.
  87296. This is handy if you're trying to optimise drawing, because it lets you easily see
  87297. when anything is being repainted unnecessarily.
  87298. */
  87299. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  87300. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  87301. #endif
  87302. /** Enable this under Linux to use Xinerama for multi-monitor support.
  87303. */
  87304. #ifndef JUCE_USE_XINERAMA
  87305. #define JUCE_USE_XINERAMA 1
  87306. #endif
  87307. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  87308. */
  87309. #ifndef JUCE_USE_XSHM
  87310. #define JUCE_USE_XSHM 1
  87311. #endif
  87312. /** Enabling this builds support for VST audio plugins.
  87313. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  87314. */
  87315. #ifndef JUCE_PLUGINHOST_VST
  87316. // #define JUCE_PLUGINHOST_VST 1
  87317. #endif
  87318. /** Enabling this builds support for AudioUnit audio plugins.
  87319. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  87320. */
  87321. #ifndef JUCE_PLUGINHOST_AU
  87322. // #define JUCE_PLUGINHOST_AU 1
  87323. #endif
  87324. /** Disabling this will avoid linking to any UI code. This is handy for
  87325. writing command-line utilities, e.g. on linux boxes which don't have some
  87326. of the UI libraries installed.
  87327. (On mac and windows, this won't generally make much difference to the build).
  87328. */
  87329. #ifndef JUCE_BUILD_GUI_CLASSES
  87330. #define JUCE_BUILD_GUI_CLASSES 1
  87331. #endif
  87332. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  87333. */
  87334. #ifndef JUCE_WEB_BROWSER
  87335. #define JUCE_WEB_BROWSER 1
  87336. #endif
  87337. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  87338. codebase - you might need to use this if you're linking to some of these libraries
  87339. yourself.
  87340. */
  87341. #ifndef JUCE_INCLUDE_ZLIB_CODE
  87342. #define JUCE_INCLUDE_ZLIB_CODE 1
  87343. #endif
  87344. #ifndef JUCE_INCLUDE_FLAC_CODE
  87345. #define JUCE_INCLUDE_FLAC_CODE 1
  87346. #endif
  87347. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  87348. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  87349. #endif
  87350. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  87351. #define JUCE_INCLUDE_PNGLIB_CODE 1
  87352. #endif
  87353. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  87354. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  87355. #endif
  87356. /** Enable this to add extra memory-leak info to the new and delete operators.
  87357. (Currently, this only affects Windows builds in debug mode).
  87358. */
  87359. #ifndef JUCE_CHECK_MEMORY_LEAKS
  87360. #define JUCE_CHECK_MEMORY_LEAKS 1
  87361. #endif
  87362. /** Enable this to turn on juce's internal catching of exceptions.
  87363. Turning it off will avoid any exception catching. With it on, all exceptions
  87364. are passed to the JUCEApplication::unhandledException() callback for logging.
  87365. */
  87366. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  87367. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  87368. #endif
  87369. /** If this macro is set, the Juce String class will use unicode as its
  87370. internal representation. If it isn't set, it'll use ANSI.
  87371. */
  87372. #ifndef JUCE_STRINGS_ARE_UNICODE
  87373. #define JUCE_STRINGS_ARE_UNICODE 1
  87374. #endif
  87375. #endif
  87376. /********* End of inlined file: juce_Config.h *********/
  87377. #define VERSION "1.2.1"
  87378. #define FLAC__NO_DLL 1
  87379. #ifdef _MSC_VER
  87380. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  87381. #endif
  87382. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  87383. #define FLAC__SYS_DARWIN 1
  87384. #endif
  87385. /********* End of inlined file: juce_FlacHeader.h *********/
  87386. #if JUCE_USE_FLAC
  87387. #if HAVE_CONFIG_H
  87388. # include <config.h>
  87389. #endif
  87390. /********* Start of inlined file: bitmath.h *********/
  87391. #ifndef FLAC__PRIVATE__BITMATH_H
  87392. #define FLAC__PRIVATE__BITMATH_H
  87393. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v);
  87394. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v);
  87395. unsigned FLAC__bitmath_silog2(int v);
  87396. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v);
  87397. #endif
  87398. /********* End of inlined file: bitmath.h *********/
  87399. /* An example of what FLAC__bitmath_ilog2() computes:
  87400. *
  87401. * ilog2( 0) = assertion failure
  87402. * ilog2( 1) = 0
  87403. * ilog2( 2) = 1
  87404. * ilog2( 3) = 1
  87405. * ilog2( 4) = 2
  87406. * ilog2( 5) = 2
  87407. * ilog2( 6) = 2
  87408. * ilog2( 7) = 2
  87409. * ilog2( 8) = 3
  87410. * ilog2( 9) = 3
  87411. * ilog2(10) = 3
  87412. * ilog2(11) = 3
  87413. * ilog2(12) = 3
  87414. * ilog2(13) = 3
  87415. * ilog2(14) = 3
  87416. * ilog2(15) = 3
  87417. * ilog2(16) = 4
  87418. * ilog2(17) = 4
  87419. * ilog2(18) = 4
  87420. */
  87421. unsigned FLAC__bitmath_ilog2(FLAC__uint32 v)
  87422. {
  87423. unsigned l = 0;
  87424. FLAC__ASSERT(v > 0);
  87425. while(v >>= 1)
  87426. l++;
  87427. return l;
  87428. }
  87429. unsigned FLAC__bitmath_ilog2_wide(FLAC__uint64 v)
  87430. {
  87431. unsigned l = 0;
  87432. FLAC__ASSERT(v > 0);
  87433. while(v >>= 1)
  87434. l++;
  87435. return l;
  87436. }
  87437. /* An example of what FLAC__bitmath_silog2() computes:
  87438. *
  87439. * silog2(-10) = 5
  87440. * silog2(- 9) = 5
  87441. * silog2(- 8) = 4
  87442. * silog2(- 7) = 4
  87443. * silog2(- 6) = 4
  87444. * silog2(- 5) = 4
  87445. * silog2(- 4) = 3
  87446. * silog2(- 3) = 3
  87447. * silog2(- 2) = 2
  87448. * silog2(- 1) = 2
  87449. * silog2( 0) = 0
  87450. * silog2( 1) = 2
  87451. * silog2( 2) = 3
  87452. * silog2( 3) = 3
  87453. * silog2( 4) = 4
  87454. * silog2( 5) = 4
  87455. * silog2( 6) = 4
  87456. * silog2( 7) = 4
  87457. * silog2( 8) = 5
  87458. * silog2( 9) = 5
  87459. * silog2( 10) = 5
  87460. */
  87461. unsigned FLAC__bitmath_silog2(int v)
  87462. {
  87463. while(1) {
  87464. if(v == 0) {
  87465. return 0;
  87466. }
  87467. else if(v > 0) {
  87468. unsigned l = 0;
  87469. while(v) {
  87470. l++;
  87471. v >>= 1;
  87472. }
  87473. return l+1;
  87474. }
  87475. else if(v == -1) {
  87476. return 2;
  87477. }
  87478. else {
  87479. v++;
  87480. v = -v;
  87481. }
  87482. }
  87483. }
  87484. unsigned FLAC__bitmath_silog2_wide(FLAC__int64 v)
  87485. {
  87486. while(1) {
  87487. if(v == 0) {
  87488. return 0;
  87489. }
  87490. else if(v > 0) {
  87491. unsigned l = 0;
  87492. while(v) {
  87493. l++;
  87494. v >>= 1;
  87495. }
  87496. return l+1;
  87497. }
  87498. else if(v == -1) {
  87499. return 2;
  87500. }
  87501. else {
  87502. v++;
  87503. v = -v;
  87504. }
  87505. }
  87506. }
  87507. #endif
  87508. /********* End of inlined file: bitmath.c *********/
  87509. /********* Start of inlined file: bitreader.c *********/
  87510. /********* Start of inlined file: juce_FlacHeader.h *********/
  87511. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  87512. // tasks..
  87513. /********* Start of inlined file: juce_Config.h *********/
  87514. #ifndef __JUCE_CONFIG_JUCEHEADER__
  87515. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  87516. /*
  87517. This file contains macros that enable/disable various JUCE features.
  87518. */
  87519. /** The name of the namespace that all Juce classes and functions will be
  87520. put inside. If this is not defined, no namespace will be used.
  87521. */
  87522. #ifndef JUCE_NAMESPACE
  87523. #define JUCE_NAMESPACE juce
  87524. #endif
  87525. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  87526. but if you define this value, you can override this can force it to be true or
  87527. false.
  87528. */
  87529. #ifndef JUCE_FORCE_DEBUG
  87530. //#define JUCE_FORCE_DEBUG 1
  87531. #endif
  87532. /** If this flag is enabled, the the jassert and jassertfalse macros will
  87533. always use Logger::writeToLog() to write a message when an assertion happens.
  87534. Enabling it will also leave this turned on in release builds. When it's disabled,
  87535. however, the jassert and jassertfalse macros will not be compiled in a
  87536. release build.
  87537. @see jassert, jassertfalse, Logger
  87538. */
  87539. #ifndef JUCE_LOG_ASSERTIONS
  87540. // #define JUCE_LOG_ASSERTIONS 1
  87541. #endif
  87542. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  87543. which the ASIOAudioIODevice class can't be built. See the comments in the
  87544. ASIOAudioIODevice class's header file for more info about this.
  87545. (This only affects a Win32 build)
  87546. */
  87547. #ifndef JUCE_ASIO
  87548. #define JUCE_ASIO 1
  87549. #endif
  87550. /** Comment out this macro to disable building of ALSA device support on Linux.
  87551. */
  87552. #ifndef JUCE_ALSA
  87553. #define JUCE_ALSA 1
  87554. #endif
  87555. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  87556. have the SDK installed.
  87557. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  87558. classes will be unavailable.
  87559. On Windows, if you enable this, you'll need to have the QuickTime SDK
  87560. installed, and its header files will need to be on your include path.
  87561. */
  87562. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  87563. #define JUCE_QUICKTIME 1
  87564. #endif
  87565. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  87566. have the appropriate headers and libraries available. If it's not enabled, the
  87567. OpenGLComponent class will be unavailable.
  87568. */
  87569. #ifndef JUCE_OPENGL
  87570. #define JUCE_OPENGL 1
  87571. #endif
  87572. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  87573. If you're not going to need either of these formats, turn off the flags to
  87574. avoid bloating your codebase with them.
  87575. */
  87576. #ifndef JUCE_USE_FLAC
  87577. #define JUCE_USE_FLAC 1
  87578. #endif
  87579. #ifndef JUCE_USE_OGGVORBIS
  87580. #define JUCE_USE_OGGVORBIS 1
  87581. #endif
  87582. /** This flag lets you enable support for CD-burning. You might want to disable
  87583. it to build without the MS SDK under windows.
  87584. */
  87585. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  87586. #define JUCE_USE_CDBURNER 1
  87587. #endif
  87588. /** Enabling this macro means that all regions that get repainted will have a coloured
  87589. line drawn around them.
  87590. This is handy if you're trying to optimise drawing, because it lets you easily see
  87591. when anything is being repainted unnecessarily.
  87592. */
  87593. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  87594. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  87595. #endif
  87596. /** Enable this under Linux to use Xinerama for multi-monitor support.
  87597. */
  87598. #ifndef JUCE_USE_XINERAMA
  87599. #define JUCE_USE_XINERAMA 1
  87600. #endif
  87601. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  87602. */
  87603. #ifndef JUCE_USE_XSHM
  87604. #define JUCE_USE_XSHM 1
  87605. #endif
  87606. /** Enabling this builds support for VST audio plugins.
  87607. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  87608. */
  87609. #ifndef JUCE_PLUGINHOST_VST
  87610. // #define JUCE_PLUGINHOST_VST 1
  87611. #endif
  87612. /** Enabling this builds support for AudioUnit audio plugins.
  87613. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  87614. */
  87615. #ifndef JUCE_PLUGINHOST_AU
  87616. // #define JUCE_PLUGINHOST_AU 1
  87617. #endif
  87618. /** Disabling this will avoid linking to any UI code. This is handy for
  87619. writing command-line utilities, e.g. on linux boxes which don't have some
  87620. of the UI libraries installed.
  87621. (On mac and windows, this won't generally make much difference to the build).
  87622. */
  87623. #ifndef JUCE_BUILD_GUI_CLASSES
  87624. #define JUCE_BUILD_GUI_CLASSES 1
  87625. #endif
  87626. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  87627. */
  87628. #ifndef JUCE_WEB_BROWSER
  87629. #define JUCE_WEB_BROWSER 1
  87630. #endif
  87631. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  87632. codebase - you might need to use this if you're linking to some of these libraries
  87633. yourself.
  87634. */
  87635. #ifndef JUCE_INCLUDE_ZLIB_CODE
  87636. #define JUCE_INCLUDE_ZLIB_CODE 1
  87637. #endif
  87638. #ifndef JUCE_INCLUDE_FLAC_CODE
  87639. #define JUCE_INCLUDE_FLAC_CODE 1
  87640. #endif
  87641. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  87642. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  87643. #endif
  87644. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  87645. #define JUCE_INCLUDE_PNGLIB_CODE 1
  87646. #endif
  87647. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  87648. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  87649. #endif
  87650. /** Enable this to add extra memory-leak info to the new and delete operators.
  87651. (Currently, this only affects Windows builds in debug mode).
  87652. */
  87653. #ifndef JUCE_CHECK_MEMORY_LEAKS
  87654. #define JUCE_CHECK_MEMORY_LEAKS 1
  87655. #endif
  87656. /** Enable this to turn on juce's internal catching of exceptions.
  87657. Turning it off will avoid any exception catching. With it on, all exceptions
  87658. are passed to the JUCEApplication::unhandledException() callback for logging.
  87659. */
  87660. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  87661. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  87662. #endif
  87663. /** If this macro is set, the Juce String class will use unicode as its
  87664. internal representation. If it isn't set, it'll use ANSI.
  87665. */
  87666. #ifndef JUCE_STRINGS_ARE_UNICODE
  87667. #define JUCE_STRINGS_ARE_UNICODE 1
  87668. #endif
  87669. #endif
  87670. /********* End of inlined file: juce_Config.h *********/
  87671. #define VERSION "1.2.1"
  87672. #define FLAC__NO_DLL 1
  87673. #ifdef _MSC_VER
  87674. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  87675. #endif
  87676. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  87677. #define FLAC__SYS_DARWIN 1
  87678. #endif
  87679. /********* End of inlined file: juce_FlacHeader.h *********/
  87680. #if JUCE_USE_FLAC
  87681. #if HAVE_CONFIG_H
  87682. # include <config.h>
  87683. #endif
  87684. #include <stdlib.h> /* for malloc() */
  87685. #include <string.h> /* for memcpy(), memset() */
  87686. #ifdef _MSC_VER
  87687. #include <winsock.h> /* for ntohl() */
  87688. #elif defined FLAC__SYS_DARWIN
  87689. #include <machine/endian.h> /* for ntohl() */
  87690. #elif defined __MINGW32__
  87691. #include <winsock.h> /* for ntohl() */
  87692. #else
  87693. #include <netinet/in.h> /* for ntohl() */
  87694. #endif
  87695. /********* Start of inlined file: bitreader.h *********/
  87696. #ifndef FLAC__PRIVATE__BITREADER_H
  87697. #define FLAC__PRIVATE__BITREADER_H
  87698. #include <stdio.h> /* for FILE */
  87699. /********* Start of inlined file: cpu.h *********/
  87700. #ifndef FLAC__PRIVATE__CPU_H
  87701. #define FLAC__PRIVATE__CPU_H
  87702. #ifdef HAVE_CONFIG_H
  87703. #include <config.h>
  87704. #endif
  87705. typedef enum {
  87706. FLAC__CPUINFO_TYPE_IA32,
  87707. FLAC__CPUINFO_TYPE_PPC,
  87708. FLAC__CPUINFO_TYPE_UNKNOWN
  87709. } FLAC__CPUInfo_Type;
  87710. typedef struct {
  87711. FLAC__bool cpuid;
  87712. FLAC__bool bswap;
  87713. FLAC__bool cmov;
  87714. FLAC__bool mmx;
  87715. FLAC__bool fxsr;
  87716. FLAC__bool sse;
  87717. FLAC__bool sse2;
  87718. FLAC__bool sse3;
  87719. FLAC__bool ssse3;
  87720. FLAC__bool _3dnow;
  87721. FLAC__bool ext3dnow;
  87722. FLAC__bool extmmx;
  87723. } FLAC__CPUInfo_IA32;
  87724. typedef struct {
  87725. FLAC__bool altivec;
  87726. FLAC__bool ppc64;
  87727. } FLAC__CPUInfo_PPC;
  87728. typedef struct {
  87729. FLAC__bool use_asm;
  87730. FLAC__CPUInfo_Type type;
  87731. union {
  87732. FLAC__CPUInfo_IA32 ia32;
  87733. FLAC__CPUInfo_PPC ppc;
  87734. } data;
  87735. } FLAC__CPUInfo;
  87736. void FLAC__cpu_info(FLAC__CPUInfo *info);
  87737. #ifndef FLAC__NO_ASM
  87738. #ifdef FLAC__CPU_IA32
  87739. #ifdef FLAC__HAS_NASM
  87740. FLAC__uint32 FLAC__cpu_have_cpuid_asm_ia32(void);
  87741. void FLAC__cpu_info_asm_ia32(FLAC__uint32 *flags_edx, FLAC__uint32 *flags_ecx);
  87742. FLAC__uint32 FLAC__cpu_info_extended_amd_asm_ia32(void);
  87743. #endif
  87744. #endif
  87745. #endif
  87746. #endif
  87747. /********* End of inlined file: cpu.h *********/
  87748. /*
  87749. * opaque structure definition
  87750. */
  87751. struct FLAC__BitReader;
  87752. typedef struct FLAC__BitReader FLAC__BitReader;
  87753. typedef FLAC__bool (*FLAC__BitReaderReadCallback)(FLAC__byte buffer[], size_t *bytes, void *client_data);
  87754. /*
  87755. * construction, deletion, initialization, etc functions
  87756. */
  87757. FLAC__BitReader *FLAC__bitreader_new(void);
  87758. void FLAC__bitreader_delete(FLAC__BitReader *br);
  87759. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd);
  87760. void FLAC__bitreader_free(FLAC__BitReader *br); /* does not 'free(br)' */
  87761. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br);
  87762. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out);
  87763. /*
  87764. * CRC functions
  87765. */
  87766. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed);
  87767. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br);
  87768. /*
  87769. * info functions
  87770. */
  87771. FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br);
  87772. unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br);
  87773. unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br);
  87774. /*
  87775. * read functions
  87776. */
  87777. FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits);
  87778. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits);
  87779. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits);
  87780. FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val); /*only for bits=32*/
  87781. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits); /* WATCHOUT: does not CRC the skipped data! */ /*@@@@ add to unit tests */
  87782. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals); /* WATCHOUT: does not CRC the read data! */
  87783. 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! */
  87784. FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val);
  87785. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  87786. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  87787. #ifndef FLAC__NO_ASM
  87788. # ifdef FLAC__CPU_IA32
  87789. # ifdef FLAC__HAS_NASM
  87790. FLAC__bool FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter);
  87791. # endif
  87792. # endif
  87793. #endif
  87794. #if 0 /* UNUSED */
  87795. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter);
  87796. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter);
  87797. #endif
  87798. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen);
  87799. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen);
  87800. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br);
  87801. #endif
  87802. /********* End of inlined file: bitreader.h *********/
  87803. /********* Start of inlined file: crc.h *********/
  87804. #ifndef FLAC__PRIVATE__CRC_H
  87805. #define FLAC__PRIVATE__CRC_H
  87806. /* 8 bit CRC generator, MSB shifted first
  87807. ** polynomial = x^8 + x^2 + x^1 + x^0
  87808. ** init = 0
  87809. */
  87810. extern FLAC__byte const FLAC__crc8_table[256];
  87811. #define FLAC__CRC8_UPDATE(data, crc) (crc) = FLAC__crc8_table[(crc) ^ (data)];
  87812. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc);
  87813. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc);
  87814. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len);
  87815. /* 16 bit CRC generator, MSB shifted first
  87816. ** polynomial = x^16 + x^15 + x^2 + x^0
  87817. ** init = 0
  87818. */
  87819. extern unsigned FLAC__crc16_table[256];
  87820. #define FLAC__CRC16_UPDATE(data, crc) (((((crc)<<8) & 0xffff) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]))
  87821. /* this alternate may be faster on some systems/compilers */
  87822. #if 0
  87823. #define FLAC__CRC16_UPDATE(data, crc) ((((crc)<<8) ^ FLAC__crc16_table[((crc)>>8) ^ (data)]) & 0xffff)
  87824. #endif
  87825. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len);
  87826. #endif
  87827. /********* End of inlined file: crc.h *********/
  87828. /* Things should be fastest when this matches the machine word size */
  87829. /* WATCHOUT: if you change this you must also change the following #defines down to COUNT_ZERO_MSBS below to match */
  87830. /* WATCHOUT: there are a few places where the code will not work unless brword is >= 32 bits wide */
  87831. /* also, some sections currently only have fast versions for 4 or 8 bytes per word */
  87832. typedef FLAC__uint32 brword;
  87833. #define FLAC__BYTES_PER_WORD 4
  87834. #define FLAC__BITS_PER_WORD 32
  87835. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  87836. /* SWAP_BE_WORD_TO_HOST swaps bytes in a brword (which is always big-endian) if necessary to match host byte order */
  87837. #if WORDS_BIGENDIAN
  87838. #define SWAP_BE_WORD_TO_HOST(x) (x)
  87839. #else
  87840. #if defined (_MSC_VER) && defined (_X86_)
  87841. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  87842. #else
  87843. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  87844. #endif
  87845. #endif
  87846. /* counts the # of zero MSBs in a word */
  87847. #define COUNT_ZERO_MSBS(word) ( \
  87848. (word) <= 0xffff ? \
  87849. ( (word) <= 0xff? byte_to_unary_table[word] + 24 : byte_to_unary_table[(word) >> 8] + 16 ) : \
  87850. ( (word) <= 0xffffff? byte_to_unary_table[word >> 16] + 8 : byte_to_unary_table[(word) >> 24] ) \
  87851. )
  87852. /* this alternate might be slightly faster on some systems/compilers: */
  87853. #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])) )
  87854. /*
  87855. * This should be at least twice as large as the largest number of words
  87856. * required to represent any 'number' (in any encoding) you are going to
  87857. * read. With FLAC this is on the order of maybe a few hundred bits.
  87858. * If the buffer is smaller than that, the decoder won't be able to read
  87859. * in a whole number that is in a variable length encoding (e.g. Rice).
  87860. * But to be practical it should be at least 1K bytes.
  87861. *
  87862. * Increase this number to decrease the number of read callbacks, at the
  87863. * expense of using more memory. Or decrease for the reverse effect,
  87864. * keeping in mind the limit from the first paragraph. The optimal size
  87865. * also depends on the CPU cache size and other factors; some twiddling
  87866. * may be necessary to squeeze out the best performance.
  87867. */
  87868. static const unsigned FLAC__BITREADER_DEFAULT_CAPACITY = 65536u / FLAC__BITS_PER_WORD; /* in words */
  87869. static const unsigned char byte_to_unary_table[] = {
  87870. 8, 7, 6, 6, 5, 5, 5, 5, 4, 4, 4, 4, 4, 4, 4, 4,
  87871. 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3,
  87872. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  87873. 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2,
  87874. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87875. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87876. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87877. 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
  87878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  87885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
  87886. };
  87887. #ifdef min
  87888. #undef min
  87889. #endif
  87890. #define min(x,y) ((x)<(y)?(x):(y))
  87891. #ifdef max
  87892. #undef max
  87893. #endif
  87894. #define max(x,y) ((x)>(y)?(x):(y))
  87895. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  87896. #ifdef _MSC_VER
  87897. #define FLAC__U64L(x) x
  87898. #else
  87899. #define FLAC__U64L(x) x##LLU
  87900. #endif
  87901. #ifndef FLaC__INLINE
  87902. #define FLaC__INLINE
  87903. #endif
  87904. /* WATCHOUT: assembly routines rely on the order in which these fields are declared */
  87905. struct FLAC__BitReader {
  87906. /* any partially-consumed word at the head will stay right-justified as bits are consumed from the left */
  87907. /* any incomplete word at the tail will be left-justified, and bytes from the read callback are added on the right */
  87908. brword *buffer;
  87909. unsigned capacity; /* in words */
  87910. unsigned words; /* # of completed words in buffer */
  87911. unsigned bytes; /* # of bytes in incomplete word at buffer[words] */
  87912. unsigned consumed_words; /* #words ... */
  87913. unsigned consumed_bits; /* ... + (#bits of head word) already consumed from the front of buffer */
  87914. unsigned read_crc16; /* the running frame CRC */
  87915. unsigned crc16_align; /* the number of bits in the current consumed word that should not be CRC'd */
  87916. FLAC__BitReaderReadCallback read_callback;
  87917. void *client_data;
  87918. FLAC__CPUInfo cpu_info;
  87919. };
  87920. static FLaC__INLINE void crc16_update_word_(FLAC__BitReader *br, brword word)
  87921. {
  87922. register unsigned crc = br->read_crc16;
  87923. #if FLAC__BYTES_PER_WORD == 4
  87924. switch(br->crc16_align) {
  87925. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 24), crc);
  87926. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  87927. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  87928. case 24: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  87929. }
  87930. #elif FLAC__BYTES_PER_WORD == 8
  87931. switch(br->crc16_align) {
  87932. case 0: crc = FLAC__CRC16_UPDATE((unsigned)(word >> 56), crc);
  87933. case 8: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 48) & 0xff), crc);
  87934. case 16: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 40) & 0xff), crc);
  87935. case 24: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 32) & 0xff), crc);
  87936. case 32: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 24) & 0xff), crc);
  87937. case 40: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 16) & 0xff), crc);
  87938. case 48: crc = FLAC__CRC16_UPDATE((unsigned)((word >> 8) & 0xff), crc);
  87939. case 56: br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)(word & 0xff), crc);
  87940. }
  87941. #else
  87942. for( ; br->crc16_align < FLAC__BITS_PER_WORD; br->crc16_align += 8)
  87943. crc = FLAC__CRC16_UPDATE((unsigned)((word >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), crc);
  87944. br->read_crc16 = crc;
  87945. #endif
  87946. br->crc16_align = 0;
  87947. }
  87948. /* would be static except it needs to be called by asm routines */
  87949. FLAC__bool bitreader_read_from_client_(FLAC__BitReader *br)
  87950. {
  87951. unsigned start, end;
  87952. size_t bytes;
  87953. FLAC__byte *target;
  87954. /* first shift the unconsumed buffer data toward the front as much as possible */
  87955. if(br->consumed_words > 0) {
  87956. start = br->consumed_words;
  87957. end = br->words + (br->bytes? 1:0);
  87958. memmove(br->buffer, br->buffer+start, FLAC__BYTES_PER_WORD * (end - start));
  87959. br->words -= start;
  87960. br->consumed_words = 0;
  87961. }
  87962. /*
  87963. * set the target for reading, taking into account word alignment and endianness
  87964. */
  87965. bytes = (br->capacity - br->words) * FLAC__BYTES_PER_WORD - br->bytes;
  87966. if(bytes == 0)
  87967. return false; /* no space left, buffer is too small; see note for FLAC__BITREADER_DEFAULT_CAPACITY */
  87968. target = ((FLAC__byte*)(br->buffer+br->words)) + br->bytes;
  87969. /* before reading, if the existing reader looks like this (say brword is 32 bits wide)
  87970. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1 (partial tail word is left-justified)
  87971. * buffer[BE]: 11 22 33 44 55 ?? ?? ?? (shown layed out as bytes sequentially in memory)
  87972. * buffer[LE]: 44 33 22 11 ?? ?? ?? 55 (?? being don't-care)
  87973. * ^^-------target, bytes=3
  87974. * on LE machines, have to byteswap the odd tail word so nothing is
  87975. * overwritten:
  87976. */
  87977. #if WORDS_BIGENDIAN
  87978. #else
  87979. if(br->bytes)
  87980. br->buffer[br->words] = SWAP_BE_WORD_TO_HOST(br->buffer[br->words]);
  87981. #endif
  87982. /* now it looks like:
  87983. * bitstream : 11 22 33 44 55 br->words=1 br->bytes=1
  87984. * buffer[BE]: 11 22 33 44 55 ?? ?? ??
  87985. * buffer[LE]: 44 33 22 11 55 ?? ?? ??
  87986. * ^^-------target, bytes=3
  87987. */
  87988. /* read in the data; note that the callback may return a smaller number of bytes */
  87989. if(!br->read_callback(target, &bytes, br->client_data))
  87990. return false;
  87991. /* after reading bytes 66 77 88 99 AA BB CC DD EE FF from the client:
  87992. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  87993. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  87994. * buffer[LE]: 44 33 22 11 55 66 77 88 99 AA BB CC DD EE FF ??
  87995. * now have to byteswap on LE machines:
  87996. */
  87997. #if WORDS_BIGENDIAN
  87998. #else
  87999. end = (br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes + (FLAC__BYTES_PER_WORD-1)) / FLAC__BYTES_PER_WORD;
  88000. # if defined(_MSC_VER) && defined (_X86_) && (FLAC__BYTES_PER_WORD == 4)
  88001. if(br->cpu_info.type == FLAC__CPUINFO_TYPE_IA32 && br->cpu_info.data.ia32.bswap) {
  88002. start = br->words;
  88003. local_swap32_block_(br->buffer + start, end - start);
  88004. }
  88005. else
  88006. # endif
  88007. for(start = br->words; start < end; start++)
  88008. br->buffer[start] = SWAP_BE_WORD_TO_HOST(br->buffer[start]);
  88009. #endif
  88010. /* now it looks like:
  88011. * bitstream : 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF
  88012. * buffer[BE]: 11 22 33 44 55 66 77 88 99 AA BB CC DD EE FF ??
  88013. * buffer[LE]: 44 33 22 11 88 77 66 55 CC BB AA 99 ?? FF EE DD
  88014. * finally we'll update the reader values:
  88015. */
  88016. end = br->words*FLAC__BYTES_PER_WORD + br->bytes + bytes;
  88017. br->words = end / FLAC__BYTES_PER_WORD;
  88018. br->bytes = end % FLAC__BYTES_PER_WORD;
  88019. return true;
  88020. }
  88021. /***********************************************************************
  88022. *
  88023. * Class constructor/destructor
  88024. *
  88025. ***********************************************************************/
  88026. FLAC__BitReader *FLAC__bitreader_new(void)
  88027. {
  88028. FLAC__BitReader *br = (FLAC__BitReader*)calloc(1, sizeof(FLAC__BitReader));
  88029. /* calloc() implies:
  88030. memset(br, 0, sizeof(FLAC__BitReader));
  88031. br->buffer = 0;
  88032. br->capacity = 0;
  88033. br->words = br->bytes = 0;
  88034. br->consumed_words = br->consumed_bits = 0;
  88035. br->read_callback = 0;
  88036. br->client_data = 0;
  88037. */
  88038. return br;
  88039. }
  88040. void FLAC__bitreader_delete(FLAC__BitReader *br)
  88041. {
  88042. FLAC__ASSERT(0 != br);
  88043. FLAC__bitreader_free(br);
  88044. free(br);
  88045. }
  88046. /***********************************************************************
  88047. *
  88048. * Public class methods
  88049. *
  88050. ***********************************************************************/
  88051. FLAC__bool FLAC__bitreader_init(FLAC__BitReader *br, FLAC__CPUInfo cpu, FLAC__BitReaderReadCallback rcb, void *cd)
  88052. {
  88053. FLAC__ASSERT(0 != br);
  88054. br->words = br->bytes = 0;
  88055. br->consumed_words = br->consumed_bits = 0;
  88056. br->capacity = FLAC__BITREADER_DEFAULT_CAPACITY;
  88057. br->buffer = (brword*)malloc(sizeof(brword) * br->capacity);
  88058. if(br->buffer == 0)
  88059. return false;
  88060. br->read_callback = rcb;
  88061. br->client_data = cd;
  88062. br->cpu_info = cpu;
  88063. return true;
  88064. }
  88065. void FLAC__bitreader_free(FLAC__BitReader *br)
  88066. {
  88067. FLAC__ASSERT(0 != br);
  88068. if(0 != br->buffer)
  88069. free(br->buffer);
  88070. br->buffer = 0;
  88071. br->capacity = 0;
  88072. br->words = br->bytes = 0;
  88073. br->consumed_words = br->consumed_bits = 0;
  88074. br->read_callback = 0;
  88075. br->client_data = 0;
  88076. }
  88077. FLAC__bool FLAC__bitreader_clear(FLAC__BitReader *br)
  88078. {
  88079. br->words = br->bytes = 0;
  88080. br->consumed_words = br->consumed_bits = 0;
  88081. return true;
  88082. }
  88083. void FLAC__bitreader_dump(const FLAC__BitReader *br, FILE *out)
  88084. {
  88085. unsigned i, j;
  88086. if(br == 0) {
  88087. fprintf(out, "bitreader is NULL\n");
  88088. }
  88089. else {
  88090. 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);
  88091. for(i = 0; i < br->words; i++) {
  88092. fprintf(out, "%08X: ", i);
  88093. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  88094. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  88095. fprintf(out, ".");
  88096. else
  88097. fprintf(out, "%01u", br->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  88098. fprintf(out, "\n");
  88099. }
  88100. if(br->bytes > 0) {
  88101. fprintf(out, "%08X: ", i);
  88102. for(j = 0; j < br->bytes*8; j++)
  88103. if(i < br->consumed_words || (i == br->consumed_words && j < br->consumed_bits))
  88104. fprintf(out, ".");
  88105. else
  88106. fprintf(out, "%01u", br->buffer[i] & (1 << (br->bytes*8-j-1)) ? 1:0);
  88107. fprintf(out, "\n");
  88108. }
  88109. }
  88110. }
  88111. void FLAC__bitreader_reset_read_crc16(FLAC__BitReader *br, FLAC__uint16 seed)
  88112. {
  88113. FLAC__ASSERT(0 != br);
  88114. FLAC__ASSERT(0 != br->buffer);
  88115. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  88116. br->read_crc16 = (unsigned)seed;
  88117. br->crc16_align = br->consumed_bits;
  88118. }
  88119. FLAC__uint16 FLAC__bitreader_get_read_crc16(FLAC__BitReader *br)
  88120. {
  88121. FLAC__ASSERT(0 != br);
  88122. FLAC__ASSERT(0 != br->buffer);
  88123. FLAC__ASSERT((br->consumed_bits & 7) == 0);
  88124. FLAC__ASSERT(br->crc16_align <= br->consumed_bits);
  88125. /* CRC any tail bytes in a partially-consumed word */
  88126. if(br->consumed_bits) {
  88127. const brword tail = br->buffer[br->consumed_words];
  88128. for( ; br->crc16_align < br->consumed_bits; br->crc16_align += 8)
  88129. br->read_crc16 = FLAC__CRC16_UPDATE((unsigned)((tail >> (FLAC__BITS_PER_WORD-8-br->crc16_align)) & 0xff), br->read_crc16);
  88130. }
  88131. return br->read_crc16;
  88132. }
  88133. FLaC__INLINE FLAC__bool FLAC__bitreader_is_consumed_byte_aligned(const FLAC__BitReader *br)
  88134. {
  88135. return ((br->consumed_bits & 7) == 0);
  88136. }
  88137. FLaC__INLINE unsigned FLAC__bitreader_bits_left_for_byte_alignment(const FLAC__BitReader *br)
  88138. {
  88139. return 8 - (br->consumed_bits & 7);
  88140. }
  88141. FLaC__INLINE unsigned FLAC__bitreader_get_input_bits_unconsumed(const FLAC__BitReader *br)
  88142. {
  88143. return (br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits;
  88144. }
  88145. FLaC__INLINE FLAC__bool FLAC__bitreader_read_raw_uint32(FLAC__BitReader *br, FLAC__uint32 *val, unsigned bits)
  88146. {
  88147. FLAC__ASSERT(0 != br);
  88148. FLAC__ASSERT(0 != br->buffer);
  88149. FLAC__ASSERT(bits <= 32);
  88150. FLAC__ASSERT((br->capacity*FLAC__BITS_PER_WORD) * 2 >= bits);
  88151. FLAC__ASSERT(br->consumed_words <= br->words);
  88152. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88153. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88154. if(bits == 0) { /* OPT: investigate if this can ever happen, maybe change to assertion */
  88155. *val = 0;
  88156. return true;
  88157. }
  88158. while((br->words-br->consumed_words)*FLAC__BITS_PER_WORD + br->bytes*8 - br->consumed_bits < bits) {
  88159. if(!bitreader_read_from_client_(br))
  88160. return false;
  88161. }
  88162. if(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  88163. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  88164. if(br->consumed_bits) {
  88165. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88166. const unsigned n = FLAC__BITS_PER_WORD - br->consumed_bits;
  88167. const brword word = br->buffer[br->consumed_words];
  88168. if(bits < n) {
  88169. *val = (word & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (n-bits);
  88170. br->consumed_bits += bits;
  88171. return true;
  88172. }
  88173. *val = word & (FLAC__WORD_ALL_ONES >> br->consumed_bits);
  88174. bits -= n;
  88175. crc16_update_word_(br, word);
  88176. br->consumed_words++;
  88177. br->consumed_bits = 0;
  88178. 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 */
  88179. *val <<= bits;
  88180. *val |= (br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits));
  88181. br->consumed_bits = bits;
  88182. }
  88183. return true;
  88184. }
  88185. else {
  88186. const brword word = br->buffer[br->consumed_words];
  88187. if(bits < FLAC__BITS_PER_WORD) {
  88188. *val = word >> (FLAC__BITS_PER_WORD-bits);
  88189. br->consumed_bits = bits;
  88190. return true;
  88191. }
  88192. /* at this point 'bits' must be == FLAC__BITS_PER_WORD; because of previous assertions, it can't be larger */
  88193. *val = word;
  88194. crc16_update_word_(br, word);
  88195. br->consumed_words++;
  88196. return true;
  88197. }
  88198. }
  88199. else {
  88200. /* in this case we're starting our read at a partial tail word;
  88201. * the reader has guaranteed that we have at least 'bits' bits
  88202. * available to read, which makes this case simpler.
  88203. */
  88204. /* OPT: taking out the consumed_bits==0 "else" case below might make things faster if less code allows the compiler to inline this function */
  88205. if(br->consumed_bits) {
  88206. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88207. FLAC__ASSERT(br->consumed_bits + bits <= br->bytes*8);
  88208. *val = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES >> br->consumed_bits)) >> (FLAC__BITS_PER_WORD-br->consumed_bits-bits);
  88209. br->consumed_bits += bits;
  88210. return true;
  88211. }
  88212. else {
  88213. *val = br->buffer[br->consumed_words] >> (FLAC__BITS_PER_WORD-bits);
  88214. br->consumed_bits += bits;
  88215. return true;
  88216. }
  88217. }
  88218. }
  88219. FLAC__bool FLAC__bitreader_read_raw_int32(FLAC__BitReader *br, FLAC__int32 *val, unsigned bits)
  88220. {
  88221. /* OPT: inline raw uint32 code here, or make into a macro if possible in the .h file */
  88222. if(!FLAC__bitreader_read_raw_uint32(br, (FLAC__uint32*)val, bits))
  88223. return false;
  88224. /* sign-extend: */
  88225. *val <<= (32-bits);
  88226. *val >>= (32-bits);
  88227. return true;
  88228. }
  88229. FLAC__bool FLAC__bitreader_read_raw_uint64(FLAC__BitReader *br, FLAC__uint64 *val, unsigned bits)
  88230. {
  88231. FLAC__uint32 hi, lo;
  88232. if(bits > 32) {
  88233. if(!FLAC__bitreader_read_raw_uint32(br, &hi, bits-32))
  88234. return false;
  88235. if(!FLAC__bitreader_read_raw_uint32(br, &lo, 32))
  88236. return false;
  88237. *val = hi;
  88238. *val <<= 32;
  88239. *val |= lo;
  88240. }
  88241. else {
  88242. if(!FLAC__bitreader_read_raw_uint32(br, &lo, bits))
  88243. return false;
  88244. *val = lo;
  88245. }
  88246. return true;
  88247. }
  88248. FLaC__INLINE FLAC__bool FLAC__bitreader_read_uint32_little_endian(FLAC__BitReader *br, FLAC__uint32 *val)
  88249. {
  88250. FLAC__uint32 x8, x32 = 0;
  88251. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  88252. if(!FLAC__bitreader_read_raw_uint32(br, &x32, 8))
  88253. return false;
  88254. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  88255. return false;
  88256. x32 |= (x8 << 8);
  88257. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  88258. return false;
  88259. x32 |= (x8 << 16);
  88260. if(!FLAC__bitreader_read_raw_uint32(br, &x8, 8))
  88261. return false;
  88262. x32 |= (x8 << 24);
  88263. *val = x32;
  88264. return true;
  88265. }
  88266. FLAC__bool FLAC__bitreader_skip_bits_no_crc(FLAC__BitReader *br, unsigned bits)
  88267. {
  88268. /*
  88269. * OPT: a faster implementation is possible but probably not that useful
  88270. * since this is only called a couple of times in the metadata readers.
  88271. */
  88272. FLAC__ASSERT(0 != br);
  88273. FLAC__ASSERT(0 != br->buffer);
  88274. if(bits > 0) {
  88275. const unsigned n = br->consumed_bits & 7;
  88276. unsigned m;
  88277. FLAC__uint32 x;
  88278. if(n != 0) {
  88279. m = min(8-n, bits);
  88280. if(!FLAC__bitreader_read_raw_uint32(br, &x, m))
  88281. return false;
  88282. bits -= m;
  88283. }
  88284. m = bits / 8;
  88285. if(m > 0) {
  88286. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(br, m))
  88287. return false;
  88288. bits %= 8;
  88289. }
  88290. if(bits > 0) {
  88291. if(!FLAC__bitreader_read_raw_uint32(br, &x, bits))
  88292. return false;
  88293. }
  88294. }
  88295. return true;
  88296. }
  88297. FLAC__bool FLAC__bitreader_skip_byte_block_aligned_no_crc(FLAC__BitReader *br, unsigned nvals)
  88298. {
  88299. FLAC__uint32 x;
  88300. FLAC__ASSERT(0 != br);
  88301. FLAC__ASSERT(0 != br->buffer);
  88302. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  88303. /* step 1: skip over partial head word to get word aligned */
  88304. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  88305. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88306. return false;
  88307. nvals--;
  88308. }
  88309. if(0 == nvals)
  88310. return true;
  88311. /* step 2: skip whole words in chunks */
  88312. while(nvals >= FLAC__BYTES_PER_WORD) {
  88313. if(br->consumed_words < br->words) {
  88314. br->consumed_words++;
  88315. nvals -= FLAC__BYTES_PER_WORD;
  88316. }
  88317. else if(!bitreader_read_from_client_(br))
  88318. return false;
  88319. }
  88320. /* step 3: skip any remainder from partial tail bytes */
  88321. while(nvals) {
  88322. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88323. return false;
  88324. nvals--;
  88325. }
  88326. return true;
  88327. }
  88328. FLAC__bool FLAC__bitreader_read_byte_block_aligned_no_crc(FLAC__BitReader *br, FLAC__byte *val, unsigned nvals)
  88329. {
  88330. FLAC__uint32 x;
  88331. FLAC__ASSERT(0 != br);
  88332. FLAC__ASSERT(0 != br->buffer);
  88333. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(br));
  88334. /* step 1: read from partial head word to get word aligned */
  88335. while(nvals && br->consumed_bits) { /* i.e. run until we read 'nvals' bytes or we hit the end of the head word */
  88336. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88337. return false;
  88338. *val++ = (FLAC__byte)x;
  88339. nvals--;
  88340. }
  88341. if(0 == nvals)
  88342. return true;
  88343. /* step 2: read whole words in chunks */
  88344. while(nvals >= FLAC__BYTES_PER_WORD) {
  88345. if(br->consumed_words < br->words) {
  88346. const brword word = br->buffer[br->consumed_words++];
  88347. #if FLAC__BYTES_PER_WORD == 4
  88348. val[0] = (FLAC__byte)(word >> 24);
  88349. val[1] = (FLAC__byte)(word >> 16);
  88350. val[2] = (FLAC__byte)(word >> 8);
  88351. val[3] = (FLAC__byte)word;
  88352. #elif FLAC__BYTES_PER_WORD == 8
  88353. val[0] = (FLAC__byte)(word >> 56);
  88354. val[1] = (FLAC__byte)(word >> 48);
  88355. val[2] = (FLAC__byte)(word >> 40);
  88356. val[3] = (FLAC__byte)(word >> 32);
  88357. val[4] = (FLAC__byte)(word >> 24);
  88358. val[5] = (FLAC__byte)(word >> 16);
  88359. val[6] = (FLAC__byte)(word >> 8);
  88360. val[7] = (FLAC__byte)word;
  88361. #else
  88362. for(x = 0; x < FLAC__BYTES_PER_WORD; x++)
  88363. val[x] = (FLAC__byte)(word >> (8*(FLAC__BYTES_PER_WORD-x-1)));
  88364. #endif
  88365. val += FLAC__BYTES_PER_WORD;
  88366. nvals -= FLAC__BYTES_PER_WORD;
  88367. }
  88368. else if(!bitreader_read_from_client_(br))
  88369. return false;
  88370. }
  88371. /* step 3: read any remainder from partial tail bytes */
  88372. while(nvals) {
  88373. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88374. return false;
  88375. *val++ = (FLAC__byte)x;
  88376. nvals--;
  88377. }
  88378. return true;
  88379. }
  88380. FLaC__INLINE FLAC__bool FLAC__bitreader_read_unary_unsigned(FLAC__BitReader *br, unsigned *val)
  88381. #if 0 /* slow but readable version */
  88382. {
  88383. unsigned bit;
  88384. FLAC__ASSERT(0 != br);
  88385. FLAC__ASSERT(0 != br->buffer);
  88386. *val = 0;
  88387. while(1) {
  88388. if(!FLAC__bitreader_read_bit(br, &bit))
  88389. return false;
  88390. if(bit)
  88391. break;
  88392. else
  88393. *val++;
  88394. }
  88395. return true;
  88396. }
  88397. #else
  88398. {
  88399. unsigned i;
  88400. FLAC__ASSERT(0 != br);
  88401. FLAC__ASSERT(0 != br->buffer);
  88402. *val = 0;
  88403. while(1) {
  88404. while(br->consumed_words < br->words) { /* if we've not consumed up to a partial tail word... */
  88405. brword b = br->buffer[br->consumed_words] << br->consumed_bits;
  88406. if(b) {
  88407. i = COUNT_ZERO_MSBS(b);
  88408. *val += i;
  88409. i++;
  88410. br->consumed_bits += i;
  88411. if(br->consumed_bits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(br->consumed_bits == FLAC__BITS_PER_WORD) */
  88412. crc16_update_word_(br, br->buffer[br->consumed_words]);
  88413. br->consumed_words++;
  88414. br->consumed_bits = 0;
  88415. }
  88416. return true;
  88417. }
  88418. else {
  88419. *val += FLAC__BITS_PER_WORD - br->consumed_bits;
  88420. crc16_update_word_(br, br->buffer[br->consumed_words]);
  88421. br->consumed_words++;
  88422. br->consumed_bits = 0;
  88423. /* didn't find stop bit yet, have to keep going... */
  88424. }
  88425. }
  88426. /* at this point we've eaten up all the whole words; have to try
  88427. * reading through any tail bytes before calling the read callback.
  88428. * this is a repeat of the above logic adjusted for the fact we
  88429. * don't have a whole word. note though if the client is feeding
  88430. * us data a byte at a time (unlikely), br->consumed_bits may not
  88431. * be zero.
  88432. */
  88433. if(br->bytes) {
  88434. const unsigned end = br->bytes * 8;
  88435. brword b = (br->buffer[br->consumed_words] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << br->consumed_bits;
  88436. if(b) {
  88437. i = COUNT_ZERO_MSBS(b);
  88438. *val += i;
  88439. i++;
  88440. br->consumed_bits += i;
  88441. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  88442. return true;
  88443. }
  88444. else {
  88445. *val += end - br->consumed_bits;
  88446. br->consumed_bits += end;
  88447. FLAC__ASSERT(br->consumed_bits < FLAC__BITS_PER_WORD);
  88448. /* didn't find stop bit yet, have to keep going... */
  88449. }
  88450. }
  88451. if(!bitreader_read_from_client_(br))
  88452. return false;
  88453. }
  88454. }
  88455. #endif
  88456. FLAC__bool FLAC__bitreader_read_rice_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  88457. {
  88458. FLAC__uint32 lsbs = 0, msbs = 0;
  88459. unsigned uval;
  88460. FLAC__ASSERT(0 != br);
  88461. FLAC__ASSERT(0 != br->buffer);
  88462. FLAC__ASSERT(parameter <= 31);
  88463. /* read the unary MSBs and end bit */
  88464. if(!FLAC__bitreader_read_unary_unsigned(br, (unsigned int*) &msbs))
  88465. return false;
  88466. /* read the binary LSBs */
  88467. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, parameter))
  88468. return false;
  88469. /* compose the value */
  88470. uval = (msbs << parameter) | lsbs;
  88471. if(uval & 1)
  88472. *val = -((int)(uval >> 1)) - 1;
  88473. else
  88474. *val = (int)(uval >> 1);
  88475. return true;
  88476. }
  88477. /* this is by far the most heavily used reader call. it ain't pretty but it's fast */
  88478. /* a lot of the logic is copied, then adapted, from FLAC__bitreader_read_unary_unsigned() and FLAC__bitreader_read_raw_uint32() */
  88479. FLAC__bool FLAC__bitreader_read_rice_signed_block(FLAC__BitReader *br, int vals[], unsigned nvals, unsigned parameter)
  88480. /* OPT: possibly faster version for use with MSVC */
  88481. #ifdef _MSC_VER
  88482. {
  88483. unsigned i;
  88484. unsigned uval = 0;
  88485. unsigned bits; /* the # of binary LSBs left to read to finish a rice codeword */
  88486. /* try and get br->consumed_words and br->consumed_bits into register;
  88487. * must remember to flush them back to *br before calling other
  88488. * bitwriter functions that use them, and before returning */
  88489. register unsigned cwords;
  88490. register unsigned cbits;
  88491. FLAC__ASSERT(0 != br);
  88492. FLAC__ASSERT(0 != br->buffer);
  88493. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88494. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88495. FLAC__ASSERT(parameter < 32);
  88496. /* 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 */
  88497. if(nvals == 0)
  88498. return true;
  88499. cbits = br->consumed_bits;
  88500. cwords = br->consumed_words;
  88501. while(1) {
  88502. /* read unary part */
  88503. while(1) {
  88504. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  88505. brword b = br->buffer[cwords] << cbits;
  88506. if(b) {
  88507. #if 0 /* slower, probably due to bad register allocation... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32
  88508. __asm {
  88509. bsr eax, b
  88510. not eax
  88511. and eax, 31
  88512. mov i, eax
  88513. }
  88514. #else
  88515. i = COUNT_ZERO_MSBS(b);
  88516. #endif
  88517. uval += i;
  88518. bits = parameter;
  88519. i++;
  88520. cbits += i;
  88521. if(cbits == FLAC__BITS_PER_WORD) {
  88522. crc16_update_word_(br, br->buffer[cwords]);
  88523. cwords++;
  88524. cbits = 0;
  88525. }
  88526. goto break1;
  88527. }
  88528. else {
  88529. uval += FLAC__BITS_PER_WORD - cbits;
  88530. crc16_update_word_(br, br->buffer[cwords]);
  88531. cwords++;
  88532. cbits = 0;
  88533. /* didn't find stop bit yet, have to keep going... */
  88534. }
  88535. }
  88536. /* at this point we've eaten up all the whole words; have to try
  88537. * reading through any tail bytes before calling the read callback.
  88538. * this is a repeat of the above logic adjusted for the fact we
  88539. * don't have a whole word. note though if the client is feeding
  88540. * us data a byte at a time (unlikely), br->consumed_bits may not
  88541. * be zero.
  88542. */
  88543. if(br->bytes) {
  88544. const unsigned end = br->bytes * 8;
  88545. brword b = (br->buffer[cwords] & (FLAC__WORD_ALL_ONES << (FLAC__BITS_PER_WORD-end))) << cbits;
  88546. if(b) {
  88547. i = COUNT_ZERO_MSBS(b);
  88548. uval += i;
  88549. bits = parameter;
  88550. i++;
  88551. cbits += i;
  88552. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  88553. goto break1;
  88554. }
  88555. else {
  88556. uval += end - cbits;
  88557. cbits += end;
  88558. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  88559. /* didn't find stop bit yet, have to keep going... */
  88560. }
  88561. }
  88562. /* flush registers and read; bitreader_read_from_client_() does
  88563. * not touch br->consumed_bits at all but we still need to set
  88564. * it in case it fails and we have to return false.
  88565. */
  88566. br->consumed_bits = cbits;
  88567. br->consumed_words = cwords;
  88568. if(!bitreader_read_from_client_(br))
  88569. return false;
  88570. cwords = br->consumed_words;
  88571. }
  88572. break1:
  88573. /* read binary part */
  88574. FLAC__ASSERT(cwords <= br->words);
  88575. if(bits) {
  88576. while((br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits < bits) {
  88577. /* flush registers and read; bitreader_read_from_client_() does
  88578. * not touch br->consumed_bits at all but we still need to set
  88579. * it in case it fails and we have to return false.
  88580. */
  88581. br->consumed_bits = cbits;
  88582. br->consumed_words = cwords;
  88583. if(!bitreader_read_from_client_(br))
  88584. return false;
  88585. cwords = br->consumed_words;
  88586. }
  88587. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  88588. if(cbits) {
  88589. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88590. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  88591. const brword word = br->buffer[cwords];
  88592. if(bits < n) {
  88593. uval <<= bits;
  88594. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-bits);
  88595. cbits += bits;
  88596. goto break2;
  88597. }
  88598. uval <<= n;
  88599. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  88600. bits -= n;
  88601. crc16_update_word_(br, word);
  88602. cwords++;
  88603. cbits = 0;
  88604. 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 */
  88605. uval <<= bits;
  88606. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits));
  88607. cbits = bits;
  88608. }
  88609. goto break2;
  88610. }
  88611. else {
  88612. FLAC__ASSERT(bits < FLAC__BITS_PER_WORD);
  88613. uval <<= bits;
  88614. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  88615. cbits = bits;
  88616. goto break2;
  88617. }
  88618. }
  88619. else {
  88620. /* in this case we're starting our read at a partial tail word;
  88621. * the reader has guaranteed that we have at least 'bits' bits
  88622. * available to read, which makes this case simpler.
  88623. */
  88624. uval <<= bits;
  88625. if(cbits) {
  88626. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88627. FLAC__ASSERT(cbits + bits <= br->bytes*8);
  88628. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-bits);
  88629. cbits += bits;
  88630. goto break2;
  88631. }
  88632. else {
  88633. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-bits);
  88634. cbits += bits;
  88635. goto break2;
  88636. }
  88637. }
  88638. }
  88639. break2:
  88640. /* compose the value */
  88641. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  88642. /* are we done? */
  88643. --nvals;
  88644. if(nvals == 0) {
  88645. br->consumed_bits = cbits;
  88646. br->consumed_words = cwords;
  88647. return true;
  88648. }
  88649. uval = 0;
  88650. ++vals;
  88651. }
  88652. }
  88653. #else
  88654. {
  88655. unsigned i;
  88656. unsigned uval = 0;
  88657. /* try and get br->consumed_words and br->consumed_bits into register;
  88658. * must remember to flush them back to *br before calling other
  88659. * bitwriter functions that use them, and before returning */
  88660. register unsigned cwords;
  88661. register unsigned cbits;
  88662. unsigned ucbits; /* keep track of the number of unconsumed bits in the buffer */
  88663. FLAC__ASSERT(0 != br);
  88664. FLAC__ASSERT(0 != br->buffer);
  88665. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  88666. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  88667. FLAC__ASSERT(parameter < 32);
  88668. /* 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 */
  88669. if(nvals == 0)
  88670. return true;
  88671. cbits = br->consumed_bits;
  88672. cwords = br->consumed_words;
  88673. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  88674. while(1) {
  88675. /* read unary part */
  88676. while(1) {
  88677. while(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  88678. brword b = br->buffer[cwords] << cbits;
  88679. if(b) {
  88680. #if 0 /* is not discernably faster... */ && defined FLAC__CPU_IA32 && !defined FLAC__NO_ASM && FLAC__BITS_PER_WORD == 32 && defined __GNUC__
  88681. asm volatile (
  88682. "bsrl %1, %0;"
  88683. "notl %0;"
  88684. "andl $31, %0;"
  88685. : "=r"(i)
  88686. : "r"(b)
  88687. );
  88688. #else
  88689. i = COUNT_ZERO_MSBS(b);
  88690. #endif
  88691. uval += i;
  88692. cbits += i;
  88693. cbits++; /* skip over stop bit */
  88694. if(cbits >= FLAC__BITS_PER_WORD) { /* faster way of testing if(cbits == FLAC__BITS_PER_WORD) */
  88695. crc16_update_word_(br, br->buffer[cwords]);
  88696. cwords++;
  88697. cbits = 0;
  88698. }
  88699. goto break1;
  88700. }
  88701. else {
  88702. uval += FLAC__BITS_PER_WORD - cbits;
  88703. crc16_update_word_(br, br->buffer[cwords]);
  88704. cwords++;
  88705. cbits = 0;
  88706. /* didn't find stop bit yet, have to keep going... */
  88707. }
  88708. }
  88709. /* at this point we've eaten up all the whole words; have to try
  88710. * reading through any tail bytes before calling the read callback.
  88711. * this is a repeat of the above logic adjusted for the fact we
  88712. * don't have a whole word. note though if the client is feeding
  88713. * us data a byte at a time (unlikely), br->consumed_bits may not
  88714. * be zero.
  88715. */
  88716. if(br->bytes) {
  88717. const unsigned end = br->bytes * 8;
  88718. brword b = (br->buffer[cwords] & ~(FLAC__WORD_ALL_ONES >> end)) << cbits;
  88719. if(b) {
  88720. i = COUNT_ZERO_MSBS(b);
  88721. uval += i;
  88722. cbits += i;
  88723. cbits++; /* skip over stop bit */
  88724. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  88725. goto break1;
  88726. }
  88727. else {
  88728. uval += end - cbits;
  88729. cbits += end;
  88730. FLAC__ASSERT(cbits < FLAC__BITS_PER_WORD);
  88731. /* didn't find stop bit yet, have to keep going... */
  88732. }
  88733. }
  88734. /* flush registers and read; bitreader_read_from_client_() does
  88735. * not touch br->consumed_bits at all but we still need to set
  88736. * it in case it fails and we have to return false.
  88737. */
  88738. br->consumed_bits = cbits;
  88739. br->consumed_words = cwords;
  88740. if(!bitreader_read_from_client_(br))
  88741. return false;
  88742. cwords = br->consumed_words;
  88743. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits + uval;
  88744. /* + uval to offset our count by the # of unary bits already
  88745. * consumed before the read, because we will add these back
  88746. * in all at once at break1
  88747. */
  88748. }
  88749. break1:
  88750. ucbits -= uval;
  88751. ucbits--; /* account for stop bit */
  88752. /* read binary part */
  88753. FLAC__ASSERT(cwords <= br->words);
  88754. if(parameter) {
  88755. while(ucbits < parameter) {
  88756. /* flush registers and read; bitreader_read_from_client_() does
  88757. * not touch br->consumed_bits at all but we still need to set
  88758. * it in case it fails and we have to return false.
  88759. */
  88760. br->consumed_bits = cbits;
  88761. br->consumed_words = cwords;
  88762. if(!bitreader_read_from_client_(br))
  88763. return false;
  88764. cwords = br->consumed_words;
  88765. ucbits = (br->words-cwords)*FLAC__BITS_PER_WORD + br->bytes*8 - cbits;
  88766. }
  88767. if(cwords < br->words) { /* if we've not consumed up to a partial tail word... */
  88768. if(cbits) {
  88769. /* this also works when consumed_bits==0, it's just slower than necessary for that case */
  88770. const unsigned n = FLAC__BITS_PER_WORD - cbits;
  88771. const brword word = br->buffer[cwords];
  88772. if(parameter < n) {
  88773. uval <<= parameter;
  88774. uval |= (word & (FLAC__WORD_ALL_ONES >> cbits)) >> (n-parameter);
  88775. cbits += parameter;
  88776. }
  88777. else {
  88778. uval <<= n;
  88779. uval |= word & (FLAC__WORD_ALL_ONES >> cbits);
  88780. crc16_update_word_(br, word);
  88781. cwords++;
  88782. cbits = parameter - n;
  88783. 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 */
  88784. uval <<= cbits;
  88785. uval |= (br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits));
  88786. }
  88787. }
  88788. }
  88789. else {
  88790. cbits = parameter;
  88791. uval <<= parameter;
  88792. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  88793. }
  88794. }
  88795. else {
  88796. /* in this case we're starting our read at a partial tail word;
  88797. * the reader has guaranteed that we have at least 'parameter'
  88798. * bits available to read, which makes this case simpler.
  88799. */
  88800. uval <<= parameter;
  88801. if(cbits) {
  88802. /* this also works when consumed_bits==0, it's just a little slower than necessary for that case */
  88803. FLAC__ASSERT(cbits + parameter <= br->bytes*8);
  88804. uval |= (br->buffer[cwords] & (FLAC__WORD_ALL_ONES >> cbits)) >> (FLAC__BITS_PER_WORD-cbits-parameter);
  88805. cbits += parameter;
  88806. }
  88807. else {
  88808. cbits = parameter;
  88809. uval |= br->buffer[cwords] >> (FLAC__BITS_PER_WORD-cbits);
  88810. }
  88811. }
  88812. }
  88813. ucbits -= parameter;
  88814. /* compose the value */
  88815. *vals = (int)(uval >> 1 ^ -(int)(uval & 1));
  88816. /* are we done? */
  88817. --nvals;
  88818. if(nvals == 0) {
  88819. br->consumed_bits = cbits;
  88820. br->consumed_words = cwords;
  88821. return true;
  88822. }
  88823. uval = 0;
  88824. ++vals;
  88825. }
  88826. }
  88827. #endif
  88828. #if 0 /* UNUSED */
  88829. FLAC__bool FLAC__bitreader_read_golomb_signed(FLAC__BitReader *br, int *val, unsigned parameter)
  88830. {
  88831. FLAC__uint32 lsbs = 0, msbs = 0;
  88832. unsigned bit, uval, k;
  88833. FLAC__ASSERT(0 != br);
  88834. FLAC__ASSERT(0 != br->buffer);
  88835. k = FLAC__bitmath_ilog2(parameter);
  88836. /* read the unary MSBs and end bit */
  88837. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  88838. return false;
  88839. /* read the binary LSBs */
  88840. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  88841. return false;
  88842. if(parameter == 1u<<k) {
  88843. /* compose the value */
  88844. uval = (msbs << k) | lsbs;
  88845. }
  88846. else {
  88847. unsigned d = (1 << (k+1)) - parameter;
  88848. if(lsbs >= d) {
  88849. if(!FLAC__bitreader_read_bit(br, &bit))
  88850. return false;
  88851. lsbs <<= 1;
  88852. lsbs |= bit;
  88853. lsbs -= d;
  88854. }
  88855. /* compose the value */
  88856. uval = msbs * parameter + lsbs;
  88857. }
  88858. /* unfold unsigned to signed */
  88859. if(uval & 1)
  88860. *val = -((int)(uval >> 1)) - 1;
  88861. else
  88862. *val = (int)(uval >> 1);
  88863. return true;
  88864. }
  88865. FLAC__bool FLAC__bitreader_read_golomb_unsigned(FLAC__BitReader *br, unsigned *val, unsigned parameter)
  88866. {
  88867. FLAC__uint32 lsbs, msbs = 0;
  88868. unsigned bit, k;
  88869. FLAC__ASSERT(0 != br);
  88870. FLAC__ASSERT(0 != br->buffer);
  88871. k = FLAC__bitmath_ilog2(parameter);
  88872. /* read the unary MSBs and end bit */
  88873. if(!FLAC__bitreader_read_unary_unsigned(br, &msbs))
  88874. return false;
  88875. /* read the binary LSBs */
  88876. if(!FLAC__bitreader_read_raw_uint32(br, &lsbs, k))
  88877. return false;
  88878. if(parameter == 1u<<k) {
  88879. /* compose the value */
  88880. *val = (msbs << k) | lsbs;
  88881. }
  88882. else {
  88883. unsigned d = (1 << (k+1)) - parameter;
  88884. if(lsbs >= d) {
  88885. if(!FLAC__bitreader_read_bit(br, &bit))
  88886. return false;
  88887. lsbs <<= 1;
  88888. lsbs |= bit;
  88889. lsbs -= d;
  88890. }
  88891. /* compose the value */
  88892. *val = msbs * parameter + lsbs;
  88893. }
  88894. return true;
  88895. }
  88896. #endif /* UNUSED */
  88897. /* on return, if *val == 0xffffffff then the utf-8 sequence was invalid, but the return value will be true */
  88898. FLAC__bool FLAC__bitreader_read_utf8_uint32(FLAC__BitReader *br, FLAC__uint32 *val, FLAC__byte *raw, unsigned *rawlen)
  88899. {
  88900. FLAC__uint32 v = 0;
  88901. FLAC__uint32 x;
  88902. unsigned i;
  88903. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88904. return false;
  88905. if(raw)
  88906. raw[(*rawlen)++] = (FLAC__byte)x;
  88907. if(!(x & 0x80)) { /* 0xxxxxxx */
  88908. v = x;
  88909. i = 0;
  88910. }
  88911. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  88912. v = x & 0x1F;
  88913. i = 1;
  88914. }
  88915. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  88916. v = x & 0x0F;
  88917. i = 2;
  88918. }
  88919. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  88920. v = x & 0x07;
  88921. i = 3;
  88922. }
  88923. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  88924. v = x & 0x03;
  88925. i = 4;
  88926. }
  88927. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  88928. v = x & 0x01;
  88929. i = 5;
  88930. }
  88931. else {
  88932. *val = 0xffffffff;
  88933. return true;
  88934. }
  88935. for( ; i; i--) {
  88936. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88937. return false;
  88938. if(raw)
  88939. raw[(*rawlen)++] = (FLAC__byte)x;
  88940. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  88941. *val = 0xffffffff;
  88942. return true;
  88943. }
  88944. v <<= 6;
  88945. v |= (x & 0x3F);
  88946. }
  88947. *val = v;
  88948. return true;
  88949. }
  88950. /* on return, if *val == 0xffffffffffffffff then the utf-8 sequence was invalid, but the return value will be true */
  88951. FLAC__bool FLAC__bitreader_read_utf8_uint64(FLAC__BitReader *br, FLAC__uint64 *val, FLAC__byte *raw, unsigned *rawlen)
  88952. {
  88953. FLAC__uint64 v = 0;
  88954. FLAC__uint32 x;
  88955. unsigned i;
  88956. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88957. return false;
  88958. if(raw)
  88959. raw[(*rawlen)++] = (FLAC__byte)x;
  88960. if(!(x & 0x80)) { /* 0xxxxxxx */
  88961. v = x;
  88962. i = 0;
  88963. }
  88964. else if(x & 0xC0 && !(x & 0x20)) { /* 110xxxxx */
  88965. v = x & 0x1F;
  88966. i = 1;
  88967. }
  88968. else if(x & 0xE0 && !(x & 0x10)) { /* 1110xxxx */
  88969. v = x & 0x0F;
  88970. i = 2;
  88971. }
  88972. else if(x & 0xF0 && !(x & 0x08)) { /* 11110xxx */
  88973. v = x & 0x07;
  88974. i = 3;
  88975. }
  88976. else if(x & 0xF8 && !(x & 0x04)) { /* 111110xx */
  88977. v = x & 0x03;
  88978. i = 4;
  88979. }
  88980. else if(x & 0xFC && !(x & 0x02)) { /* 1111110x */
  88981. v = x & 0x01;
  88982. i = 5;
  88983. }
  88984. else if(x & 0xFE && !(x & 0x01)) { /* 11111110 */
  88985. v = 0;
  88986. i = 6;
  88987. }
  88988. else {
  88989. *val = FLAC__U64L(0xffffffffffffffff);
  88990. return true;
  88991. }
  88992. for( ; i; i--) {
  88993. if(!FLAC__bitreader_read_raw_uint32(br, &x, 8))
  88994. return false;
  88995. if(raw)
  88996. raw[(*rawlen)++] = (FLAC__byte)x;
  88997. if(!(x & 0x80) || (x & 0x40)) { /* 10xxxxxx */
  88998. *val = FLAC__U64L(0xffffffffffffffff);
  88999. return true;
  89000. }
  89001. v <<= 6;
  89002. v |= (x & 0x3F);
  89003. }
  89004. *val = v;
  89005. return true;
  89006. }
  89007. #endif
  89008. /********* End of inlined file: bitreader.c *********/
  89009. /********* Start of inlined file: bitwriter.c *********/
  89010. /********* Start of inlined file: juce_FlacHeader.h *********/
  89011. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  89012. // tasks..
  89013. /********* Start of inlined file: juce_Config.h *********/
  89014. #ifndef __JUCE_CONFIG_JUCEHEADER__
  89015. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  89016. /*
  89017. This file contains macros that enable/disable various JUCE features.
  89018. */
  89019. /** The name of the namespace that all Juce classes and functions will be
  89020. put inside. If this is not defined, no namespace will be used.
  89021. */
  89022. #ifndef JUCE_NAMESPACE
  89023. #define JUCE_NAMESPACE juce
  89024. #endif
  89025. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  89026. but if you define this value, you can override this can force it to be true or
  89027. false.
  89028. */
  89029. #ifndef JUCE_FORCE_DEBUG
  89030. //#define JUCE_FORCE_DEBUG 1
  89031. #endif
  89032. /** If this flag is enabled, the the jassert and jassertfalse macros will
  89033. always use Logger::writeToLog() to write a message when an assertion happens.
  89034. Enabling it will also leave this turned on in release builds. When it's disabled,
  89035. however, the jassert and jassertfalse macros will not be compiled in a
  89036. release build.
  89037. @see jassert, jassertfalse, Logger
  89038. */
  89039. #ifndef JUCE_LOG_ASSERTIONS
  89040. // #define JUCE_LOG_ASSERTIONS 1
  89041. #endif
  89042. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  89043. which the ASIOAudioIODevice class can't be built. See the comments in the
  89044. ASIOAudioIODevice class's header file for more info about this.
  89045. (This only affects a Win32 build)
  89046. */
  89047. #ifndef JUCE_ASIO
  89048. #define JUCE_ASIO 1
  89049. #endif
  89050. /** Comment out this macro to disable building of ALSA device support on Linux.
  89051. */
  89052. #ifndef JUCE_ALSA
  89053. #define JUCE_ALSA 1
  89054. #endif
  89055. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  89056. have the SDK installed.
  89057. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  89058. classes will be unavailable.
  89059. On Windows, if you enable this, you'll need to have the QuickTime SDK
  89060. installed, and its header files will need to be on your include path.
  89061. */
  89062. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  89063. #define JUCE_QUICKTIME 1
  89064. #endif
  89065. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  89066. have the appropriate headers and libraries available. If it's not enabled, the
  89067. OpenGLComponent class will be unavailable.
  89068. */
  89069. #ifndef JUCE_OPENGL
  89070. #define JUCE_OPENGL 1
  89071. #endif
  89072. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  89073. If you're not going to need either of these formats, turn off the flags to
  89074. avoid bloating your codebase with them.
  89075. */
  89076. #ifndef JUCE_USE_FLAC
  89077. #define JUCE_USE_FLAC 1
  89078. #endif
  89079. #ifndef JUCE_USE_OGGVORBIS
  89080. #define JUCE_USE_OGGVORBIS 1
  89081. #endif
  89082. /** This flag lets you enable support for CD-burning. You might want to disable
  89083. it to build without the MS SDK under windows.
  89084. */
  89085. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  89086. #define JUCE_USE_CDBURNER 1
  89087. #endif
  89088. /** Enabling this macro means that all regions that get repainted will have a coloured
  89089. line drawn around them.
  89090. This is handy if you're trying to optimise drawing, because it lets you easily see
  89091. when anything is being repainted unnecessarily.
  89092. */
  89093. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  89094. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  89095. #endif
  89096. /** Enable this under Linux to use Xinerama for multi-monitor support.
  89097. */
  89098. #ifndef JUCE_USE_XINERAMA
  89099. #define JUCE_USE_XINERAMA 1
  89100. #endif
  89101. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  89102. */
  89103. #ifndef JUCE_USE_XSHM
  89104. #define JUCE_USE_XSHM 1
  89105. #endif
  89106. /** Enabling this builds support for VST audio plugins.
  89107. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  89108. */
  89109. #ifndef JUCE_PLUGINHOST_VST
  89110. // #define JUCE_PLUGINHOST_VST 1
  89111. #endif
  89112. /** Enabling this builds support for AudioUnit audio plugins.
  89113. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  89114. */
  89115. #ifndef JUCE_PLUGINHOST_AU
  89116. // #define JUCE_PLUGINHOST_AU 1
  89117. #endif
  89118. /** Disabling this will avoid linking to any UI code. This is handy for
  89119. writing command-line utilities, e.g. on linux boxes which don't have some
  89120. of the UI libraries installed.
  89121. (On mac and windows, this won't generally make much difference to the build).
  89122. */
  89123. #ifndef JUCE_BUILD_GUI_CLASSES
  89124. #define JUCE_BUILD_GUI_CLASSES 1
  89125. #endif
  89126. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  89127. */
  89128. #ifndef JUCE_WEB_BROWSER
  89129. #define JUCE_WEB_BROWSER 1
  89130. #endif
  89131. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  89132. codebase - you might need to use this if you're linking to some of these libraries
  89133. yourself.
  89134. */
  89135. #ifndef JUCE_INCLUDE_ZLIB_CODE
  89136. #define JUCE_INCLUDE_ZLIB_CODE 1
  89137. #endif
  89138. #ifndef JUCE_INCLUDE_FLAC_CODE
  89139. #define JUCE_INCLUDE_FLAC_CODE 1
  89140. #endif
  89141. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  89142. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  89143. #endif
  89144. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  89145. #define JUCE_INCLUDE_PNGLIB_CODE 1
  89146. #endif
  89147. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  89148. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  89149. #endif
  89150. /** Enable this to add extra memory-leak info to the new and delete operators.
  89151. (Currently, this only affects Windows builds in debug mode).
  89152. */
  89153. #ifndef JUCE_CHECK_MEMORY_LEAKS
  89154. #define JUCE_CHECK_MEMORY_LEAKS 1
  89155. #endif
  89156. /** Enable this to turn on juce's internal catching of exceptions.
  89157. Turning it off will avoid any exception catching. With it on, all exceptions
  89158. are passed to the JUCEApplication::unhandledException() callback for logging.
  89159. */
  89160. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  89161. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  89162. #endif
  89163. /** If this macro is set, the Juce String class will use unicode as its
  89164. internal representation. If it isn't set, it'll use ANSI.
  89165. */
  89166. #ifndef JUCE_STRINGS_ARE_UNICODE
  89167. #define JUCE_STRINGS_ARE_UNICODE 1
  89168. #endif
  89169. #endif
  89170. /********* End of inlined file: juce_Config.h *********/
  89171. #define VERSION "1.2.1"
  89172. #define FLAC__NO_DLL 1
  89173. #ifdef _MSC_VER
  89174. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  89175. #endif
  89176. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  89177. #define FLAC__SYS_DARWIN 1
  89178. #endif
  89179. /********* End of inlined file: juce_FlacHeader.h *********/
  89180. #if JUCE_USE_FLAC
  89181. #if HAVE_CONFIG_H
  89182. # include <config.h>
  89183. #endif
  89184. #include <stdlib.h> /* for malloc() */
  89185. #include <string.h> /* for memcpy(), memset() */
  89186. #ifdef _MSC_VER
  89187. #include <winsock.h> /* for ntohl() */
  89188. #elif defined FLAC__SYS_DARWIN
  89189. #include <machine/endian.h> /* for ntohl() */
  89190. #elif defined __MINGW32__
  89191. #include <winsock.h> /* for ntohl() */
  89192. #else
  89193. #include <netinet/in.h> /* for ntohl() */
  89194. #endif
  89195. #if 0 /* UNUSED */
  89196. #endif
  89197. /********* Start of inlined file: bitwriter.h *********/
  89198. #ifndef FLAC__PRIVATE__BITWRITER_H
  89199. #define FLAC__PRIVATE__BITWRITER_H
  89200. #include <stdio.h> /* for FILE */
  89201. /*
  89202. * opaque structure definition
  89203. */
  89204. struct FLAC__BitWriter;
  89205. typedef struct FLAC__BitWriter FLAC__BitWriter;
  89206. /*
  89207. * construction, deletion, initialization, etc functions
  89208. */
  89209. FLAC__BitWriter *FLAC__bitwriter_new(void);
  89210. void FLAC__bitwriter_delete(FLAC__BitWriter *bw);
  89211. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw);
  89212. void FLAC__bitwriter_free(FLAC__BitWriter *bw); /* does not 'free(buffer)' */
  89213. void FLAC__bitwriter_clear(FLAC__BitWriter *bw);
  89214. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out);
  89215. /*
  89216. * CRC functions
  89217. *
  89218. * non-const *bw because they have to cal FLAC__bitwriter_get_buffer()
  89219. */
  89220. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc);
  89221. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc);
  89222. /*
  89223. * info functions
  89224. */
  89225. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw);
  89226. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw); /* can be called anytime, returns total # of bits unconsumed */
  89227. /*
  89228. * direct buffer access
  89229. *
  89230. * there may be no calls on the bitwriter between get and release.
  89231. * the bitwriter continues to own the returned buffer.
  89232. * before get, bitwriter MUST be byte aligned: check with FLAC__bitwriter_is_byte_aligned()
  89233. */
  89234. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes);
  89235. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw);
  89236. /*
  89237. * write functions
  89238. */
  89239. FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits);
  89240. FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits);
  89241. FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits);
  89242. FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits);
  89243. FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val); /*only for bits=32*/
  89244. FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals);
  89245. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val);
  89246. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter);
  89247. #if 0 /* UNUSED */
  89248. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter);
  89249. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned val, unsigned parameter);
  89250. #endif
  89251. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter);
  89252. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter);
  89253. #if 0 /* UNUSED */
  89254. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter);
  89255. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned val, unsigned parameter);
  89256. #endif
  89257. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val);
  89258. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val);
  89259. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw);
  89260. #endif
  89261. /********* End of inlined file: bitwriter.h *********/
  89262. /********* Start of inlined file: alloc.h *********/
  89263. #ifndef FLAC__SHARE__ALLOC_H
  89264. #define FLAC__SHARE__ALLOC_H
  89265. #if HAVE_CONFIG_H
  89266. # include <config.h>
  89267. #endif
  89268. /* WATCHOUT: for c++ you may have to #define __STDC_LIMIT_MACROS 1 real early
  89269. * before #including this file, otherwise SIZE_MAX might not be defined
  89270. */
  89271. #include <limits.h> /* for SIZE_MAX */
  89272. #if !defined _MSC_VER && !defined __MINGW32__ && !defined __EMX__
  89273. #include <stdint.h> /* for SIZE_MAX in case limits.h didn't get it */
  89274. #endif
  89275. #include <stdlib.h> /* for size_t, malloc(), etc */
  89276. #ifndef SIZE_MAX
  89277. # ifndef SIZE_T_MAX
  89278. # ifdef _MSC_VER
  89279. # define SIZE_T_MAX UINT_MAX
  89280. # else
  89281. # error
  89282. # endif
  89283. # endif
  89284. # define SIZE_MAX SIZE_T_MAX
  89285. #endif
  89286. #ifndef FLaC__INLINE
  89287. #define FLaC__INLINE
  89288. #endif
  89289. /* avoid malloc()ing 0 bytes, see:
  89290. * https://www.securecoding.cert.org/confluence/display/seccode/MEM04-A.+Do+not+make+assumptions+about+the+result+of+allocating+0+bytes?focusedCommentId=5407003
  89291. */
  89292. static FLaC__INLINE void *safe_malloc_(size_t size)
  89293. {
  89294. /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89295. if(!size)
  89296. size++;
  89297. return malloc(size);
  89298. }
  89299. static FLaC__INLINE void *safe_calloc_(size_t nmemb, size_t size)
  89300. {
  89301. if(!nmemb || !size)
  89302. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89303. return calloc(nmemb, size);
  89304. }
  89305. /*@@@@ there's probably a better way to prevent overflows when allocating untrusted sums but this works for now */
  89306. static FLaC__INLINE void *safe_malloc_add_2op_(size_t size1, size_t size2)
  89307. {
  89308. size2 += size1;
  89309. if(size2 < size1)
  89310. return 0;
  89311. return safe_malloc_(size2);
  89312. }
  89313. static FLaC__INLINE void *safe_malloc_add_3op_(size_t size1, size_t size2, size_t size3)
  89314. {
  89315. size2 += size1;
  89316. if(size2 < size1)
  89317. return 0;
  89318. size3 += size2;
  89319. if(size3 < size2)
  89320. return 0;
  89321. return safe_malloc_(size3);
  89322. }
  89323. static FLaC__INLINE void *safe_malloc_add_4op_(size_t size1, size_t size2, size_t size3, size_t size4)
  89324. {
  89325. size2 += size1;
  89326. if(size2 < size1)
  89327. return 0;
  89328. size3 += size2;
  89329. if(size3 < size2)
  89330. return 0;
  89331. size4 += size3;
  89332. if(size4 < size3)
  89333. return 0;
  89334. return safe_malloc_(size4);
  89335. }
  89336. static FLaC__INLINE void *safe_malloc_mul_2op_(size_t size1, size_t size2)
  89337. #if 0
  89338. needs support for cases where sizeof(size_t) != 4
  89339. {
  89340. /* could be faster #ifdef'ing off SIZEOF_SIZE_T */
  89341. if(sizeof(size_t) == 4) {
  89342. if ((double)size1 * (double)size2 < 4294967296.0)
  89343. return malloc(size1*size2);
  89344. }
  89345. return 0;
  89346. }
  89347. #else
  89348. /* better? */
  89349. {
  89350. if(!size1 || !size2)
  89351. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89352. if(size1 > SIZE_MAX / size2)
  89353. return 0;
  89354. return malloc(size1*size2);
  89355. }
  89356. #endif
  89357. static FLaC__INLINE void *safe_malloc_mul_3op_(size_t size1, size_t size2, size_t size3)
  89358. {
  89359. if(!size1 || !size2 || !size3)
  89360. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89361. if(size1 > SIZE_MAX / size2)
  89362. return 0;
  89363. size1 *= size2;
  89364. if(size1 > SIZE_MAX / size3)
  89365. return 0;
  89366. return malloc(size1*size3);
  89367. }
  89368. /* size1*size2 + size3 */
  89369. static FLaC__INLINE void *safe_malloc_mul2add_(size_t size1, size_t size2, size_t size3)
  89370. {
  89371. if(!size1 || !size2)
  89372. return safe_malloc_(size3);
  89373. if(size1 > SIZE_MAX / size2)
  89374. return 0;
  89375. return safe_malloc_add_2op_(size1*size2, size3);
  89376. }
  89377. /* size1 * (size2 + size3) */
  89378. static FLaC__INLINE void *safe_malloc_muladd2_(size_t size1, size_t size2, size_t size3)
  89379. {
  89380. if(!size1 || (!size2 && !size3))
  89381. return malloc(1); /* malloc(0) is undefined; FLAC src convention is to always allocate */
  89382. size2 += size3;
  89383. if(size2 < size3)
  89384. return 0;
  89385. return safe_malloc_mul_2op_(size1, size2);
  89386. }
  89387. static FLaC__INLINE void *safe_realloc_add_2op_(void *ptr, size_t size1, size_t size2)
  89388. {
  89389. size2 += size1;
  89390. if(size2 < size1)
  89391. return 0;
  89392. return realloc(ptr, size2);
  89393. }
  89394. static FLaC__INLINE void *safe_realloc_add_3op_(void *ptr, size_t size1, size_t size2, size_t size3)
  89395. {
  89396. size2 += size1;
  89397. if(size2 < size1)
  89398. return 0;
  89399. size3 += size2;
  89400. if(size3 < size2)
  89401. return 0;
  89402. return realloc(ptr, size3);
  89403. }
  89404. static FLaC__INLINE void *safe_realloc_add_4op_(void *ptr, size_t size1, size_t size2, size_t size3, size_t size4)
  89405. {
  89406. size2 += size1;
  89407. if(size2 < size1)
  89408. return 0;
  89409. size3 += size2;
  89410. if(size3 < size2)
  89411. return 0;
  89412. size4 += size3;
  89413. if(size4 < size3)
  89414. return 0;
  89415. return realloc(ptr, size4);
  89416. }
  89417. static FLaC__INLINE void *safe_realloc_mul_2op_(void *ptr, size_t size1, size_t size2)
  89418. {
  89419. if(!size1 || !size2)
  89420. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  89421. if(size1 > SIZE_MAX / size2)
  89422. return 0;
  89423. return realloc(ptr, size1*size2);
  89424. }
  89425. /* size1 * (size2 + size3) */
  89426. static FLaC__INLINE void *safe_realloc_muladd2_(void *ptr, size_t size1, size_t size2, size_t size3)
  89427. {
  89428. if(!size1 || (!size2 && !size3))
  89429. return realloc(ptr, 0); /* preserve POSIX realloc(ptr, 0) semantics */
  89430. size2 += size3;
  89431. if(size2 < size3)
  89432. return 0;
  89433. return safe_realloc_mul_2op_(ptr, size1, size2);
  89434. }
  89435. #endif
  89436. /********* End of inlined file: alloc.h *********/
  89437. /* Things should be fastest when this matches the machine word size */
  89438. /* WATCHOUT: if you change this you must also change the following #defines down to SWAP_BE_WORD_TO_HOST below to match */
  89439. /* WATCHOUT: there are a few places where the code will not work unless bwword is >= 32 bits wide */
  89440. typedef FLAC__uint32 bwword;
  89441. #define FLAC__BYTES_PER_WORD 4
  89442. #define FLAC__BITS_PER_WORD 32
  89443. #define FLAC__WORD_ALL_ONES ((FLAC__uint32)0xffffffff)
  89444. /* SWAP_BE_WORD_TO_HOST swaps bytes in a bwword (which is always big-endian) if necessary to match host byte order */
  89445. #if WORDS_BIGENDIAN
  89446. #define SWAP_BE_WORD_TO_HOST(x) (x)
  89447. #else
  89448. #ifdef _MSC_VER
  89449. #define SWAP_BE_WORD_TO_HOST(x) local_swap32_(x)
  89450. #else
  89451. #define SWAP_BE_WORD_TO_HOST(x) ntohl(x)
  89452. #endif
  89453. #endif
  89454. /*
  89455. * The default capacity here doesn't matter too much. The buffer always grows
  89456. * to hold whatever is written to it. Usually the encoder will stop adding at
  89457. * a frame or metadata block, then write that out and clear the buffer for the
  89458. * next one.
  89459. */
  89460. static const unsigned FLAC__BITWRITER_DEFAULT_CAPACITY = 32768u / sizeof(bwword); /* size in words */
  89461. /* When growing, increment 4K at a time */
  89462. static const unsigned FLAC__BITWRITER_DEFAULT_INCREMENT = 4096u / sizeof(bwword); /* size in words */
  89463. #define FLAC__WORDS_TO_BITS(words) ((words) * FLAC__BITS_PER_WORD)
  89464. #define FLAC__TOTAL_BITS(bw) (FLAC__WORDS_TO_BITS((bw)->words) + (bw)->bits)
  89465. #ifdef min
  89466. #undef min
  89467. #endif
  89468. #define min(x,y) ((x)<(y)?(x):(y))
  89469. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  89470. #ifdef _MSC_VER
  89471. #define FLAC__U64L(x) x
  89472. #else
  89473. #define FLAC__U64L(x) x##LLU
  89474. #endif
  89475. #ifndef FLaC__INLINE
  89476. #define FLaC__INLINE
  89477. #endif
  89478. struct FLAC__BitWriter {
  89479. bwword *buffer;
  89480. bwword accum; /* accumulator; bits are right-justified; when full, accum is appended to buffer */
  89481. unsigned capacity; /* capacity of buffer in words */
  89482. unsigned words; /* # of complete words in buffer */
  89483. unsigned bits; /* # of used bits in accum */
  89484. };
  89485. /* * WATCHOUT: The current implementation only grows the buffer. */
  89486. static FLAC__bool bitwriter_grow_(FLAC__BitWriter *bw, unsigned bits_to_add)
  89487. {
  89488. unsigned new_capacity;
  89489. bwword *new_buffer;
  89490. FLAC__ASSERT(0 != bw);
  89491. FLAC__ASSERT(0 != bw->buffer);
  89492. /* calculate total words needed to store 'bits_to_add' additional bits */
  89493. new_capacity = bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD);
  89494. /* it's possible (due to pessimism in the growth estimation that
  89495. * leads to this call) that we don't actually need to grow
  89496. */
  89497. if(bw->capacity >= new_capacity)
  89498. return true;
  89499. /* round up capacity increase to the nearest FLAC__BITWRITER_DEFAULT_INCREMENT */
  89500. if((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT)
  89501. new_capacity += FLAC__BITWRITER_DEFAULT_INCREMENT - ((new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  89502. /* make sure we got everything right */
  89503. FLAC__ASSERT(0 == (new_capacity - bw->capacity) % FLAC__BITWRITER_DEFAULT_INCREMENT);
  89504. FLAC__ASSERT(new_capacity > bw->capacity);
  89505. FLAC__ASSERT(new_capacity >= bw->words + ((bw->bits + bits_to_add + FLAC__BITS_PER_WORD - 1) / FLAC__BITS_PER_WORD));
  89506. new_buffer = (bwword*)safe_realloc_mul_2op_(bw->buffer, sizeof(bwword), /*times*/new_capacity);
  89507. if(new_buffer == 0)
  89508. return false;
  89509. bw->buffer = new_buffer;
  89510. bw->capacity = new_capacity;
  89511. return true;
  89512. }
  89513. /***********************************************************************
  89514. *
  89515. * Class constructor/destructor
  89516. *
  89517. ***********************************************************************/
  89518. FLAC__BitWriter *FLAC__bitwriter_new(void)
  89519. {
  89520. FLAC__BitWriter *bw = (FLAC__BitWriter*)calloc(1, sizeof(FLAC__BitWriter));
  89521. /* note that calloc() sets all members to 0 for us */
  89522. return bw;
  89523. }
  89524. void FLAC__bitwriter_delete(FLAC__BitWriter *bw)
  89525. {
  89526. FLAC__ASSERT(0 != bw);
  89527. FLAC__bitwriter_free(bw);
  89528. free(bw);
  89529. }
  89530. /***********************************************************************
  89531. *
  89532. * Public class methods
  89533. *
  89534. ***********************************************************************/
  89535. FLAC__bool FLAC__bitwriter_init(FLAC__BitWriter *bw)
  89536. {
  89537. FLAC__ASSERT(0 != bw);
  89538. bw->words = bw->bits = 0;
  89539. bw->capacity = FLAC__BITWRITER_DEFAULT_CAPACITY;
  89540. bw->buffer = (bwword*)malloc(sizeof(bwword) * bw->capacity);
  89541. if(bw->buffer == 0)
  89542. return false;
  89543. return true;
  89544. }
  89545. void FLAC__bitwriter_free(FLAC__BitWriter *bw)
  89546. {
  89547. FLAC__ASSERT(0 != bw);
  89548. if(0 != bw->buffer)
  89549. free(bw->buffer);
  89550. bw->buffer = 0;
  89551. bw->capacity = 0;
  89552. bw->words = bw->bits = 0;
  89553. }
  89554. void FLAC__bitwriter_clear(FLAC__BitWriter *bw)
  89555. {
  89556. bw->words = bw->bits = 0;
  89557. }
  89558. void FLAC__bitwriter_dump(const FLAC__BitWriter *bw, FILE *out)
  89559. {
  89560. unsigned i, j;
  89561. if(bw == 0) {
  89562. fprintf(out, "bitwriter is NULL\n");
  89563. }
  89564. else {
  89565. fprintf(out, "bitwriter: capacity=%u words=%u bits=%u total_bits=%u\n", bw->capacity, bw->words, bw->bits, FLAC__TOTAL_BITS(bw));
  89566. for(i = 0; i < bw->words; i++) {
  89567. fprintf(out, "%08X: ", i);
  89568. for(j = 0; j < FLAC__BITS_PER_WORD; j++)
  89569. fprintf(out, "%01u", bw->buffer[i] & (1 << (FLAC__BITS_PER_WORD-j-1)) ? 1:0);
  89570. fprintf(out, "\n");
  89571. }
  89572. if(bw->bits > 0) {
  89573. fprintf(out, "%08X: ", i);
  89574. for(j = 0; j < bw->bits; j++)
  89575. fprintf(out, "%01u", bw->accum & (1 << (bw->bits-j-1)) ? 1:0);
  89576. fprintf(out, "\n");
  89577. }
  89578. }
  89579. }
  89580. FLAC__bool FLAC__bitwriter_get_write_crc16(FLAC__BitWriter *bw, FLAC__uint16 *crc)
  89581. {
  89582. const FLAC__byte *buffer;
  89583. size_t bytes;
  89584. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  89585. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  89586. return false;
  89587. *crc = (FLAC__uint16)FLAC__crc16(buffer, bytes);
  89588. FLAC__bitwriter_release_buffer(bw);
  89589. return true;
  89590. }
  89591. FLAC__bool FLAC__bitwriter_get_write_crc8(FLAC__BitWriter *bw, FLAC__byte *crc)
  89592. {
  89593. const FLAC__byte *buffer;
  89594. size_t bytes;
  89595. FLAC__ASSERT((bw->bits & 7) == 0); /* assert that we're byte-aligned */
  89596. if(!FLAC__bitwriter_get_buffer(bw, &buffer, &bytes))
  89597. return false;
  89598. *crc = FLAC__crc8(buffer, bytes);
  89599. FLAC__bitwriter_release_buffer(bw);
  89600. return true;
  89601. }
  89602. FLAC__bool FLAC__bitwriter_is_byte_aligned(const FLAC__BitWriter *bw)
  89603. {
  89604. return ((bw->bits & 7) == 0);
  89605. }
  89606. unsigned FLAC__bitwriter_get_input_bits_unconsumed(const FLAC__BitWriter *bw)
  89607. {
  89608. return FLAC__TOTAL_BITS(bw);
  89609. }
  89610. FLAC__bool FLAC__bitwriter_get_buffer(FLAC__BitWriter *bw, const FLAC__byte **buffer, size_t *bytes)
  89611. {
  89612. FLAC__ASSERT((bw->bits & 7) == 0);
  89613. /* double protection */
  89614. if(bw->bits & 7)
  89615. return false;
  89616. /* if we have bits in the accumulator we have to flush those to the buffer first */
  89617. if(bw->bits) {
  89618. FLAC__ASSERT(bw->words <= bw->capacity);
  89619. if(bw->words == bw->capacity && !bitwriter_grow_(bw, FLAC__BITS_PER_WORD))
  89620. return false;
  89621. /* append bits as complete word to buffer, but don't change bw->accum or bw->bits */
  89622. bw->buffer[bw->words] = SWAP_BE_WORD_TO_HOST(bw->accum << (FLAC__BITS_PER_WORD-bw->bits));
  89623. }
  89624. /* now we can just return what we have */
  89625. *buffer = (FLAC__byte*)bw->buffer;
  89626. *bytes = (FLAC__BYTES_PER_WORD * bw->words) + (bw->bits >> 3);
  89627. return true;
  89628. }
  89629. void FLAC__bitwriter_release_buffer(FLAC__BitWriter *bw)
  89630. {
  89631. /* nothing to do. in the future, strict checking of a 'writer-is-in-
  89632. * get-mode' flag could be added everywhere and then cleared here
  89633. */
  89634. (void)bw;
  89635. }
  89636. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_zeroes(FLAC__BitWriter *bw, unsigned bits)
  89637. {
  89638. unsigned n;
  89639. FLAC__ASSERT(0 != bw);
  89640. FLAC__ASSERT(0 != bw->buffer);
  89641. if(bits == 0)
  89642. return true;
  89643. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  89644. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  89645. return false;
  89646. /* first part gets to word alignment */
  89647. if(bw->bits) {
  89648. n = min(FLAC__BITS_PER_WORD - bw->bits, bits);
  89649. bw->accum <<= n;
  89650. bits -= n;
  89651. bw->bits += n;
  89652. if(bw->bits == FLAC__BITS_PER_WORD) {
  89653. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89654. bw->bits = 0;
  89655. }
  89656. else
  89657. return true;
  89658. }
  89659. /* do whole words */
  89660. while(bits >= FLAC__BITS_PER_WORD) {
  89661. bw->buffer[bw->words++] = 0;
  89662. bits -= FLAC__BITS_PER_WORD;
  89663. }
  89664. /* do any leftovers */
  89665. if(bits > 0) {
  89666. bw->accum = 0;
  89667. bw->bits = bits;
  89668. }
  89669. return true;
  89670. }
  89671. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32(FLAC__BitWriter *bw, FLAC__uint32 val, unsigned bits)
  89672. {
  89673. register unsigned left;
  89674. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89675. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89676. FLAC__ASSERT(0 != bw);
  89677. FLAC__ASSERT(0 != bw->buffer);
  89678. FLAC__ASSERT(bits <= 32);
  89679. if(bits == 0)
  89680. return true;
  89681. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+bits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  89682. if(bw->capacity <= bw->words + bits && !bitwriter_grow_(bw, bits))
  89683. return false;
  89684. left = FLAC__BITS_PER_WORD - bw->bits;
  89685. if(bits < left) {
  89686. bw->accum <<= bits;
  89687. bw->accum |= val;
  89688. bw->bits += bits;
  89689. }
  89690. 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 */
  89691. bw->accum <<= left;
  89692. bw->accum |= val >> (bw->bits = bits - left);
  89693. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89694. bw->accum = val;
  89695. }
  89696. else {
  89697. bw->accum = val;
  89698. bw->bits = 0;
  89699. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(val);
  89700. }
  89701. return true;
  89702. }
  89703. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_int32(FLAC__BitWriter *bw, FLAC__int32 val, unsigned bits)
  89704. {
  89705. /* zero-out unused bits */
  89706. if(bits < 32)
  89707. val &= (~(0xffffffff << bits));
  89708. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  89709. }
  89710. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint64(FLAC__BitWriter *bw, FLAC__uint64 val, unsigned bits)
  89711. {
  89712. /* this could be a little faster but it's not used for much */
  89713. if(bits > 32) {
  89714. return
  89715. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(val>>32), bits-32) &&
  89716. FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 32);
  89717. }
  89718. else
  89719. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, bits);
  89720. }
  89721. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_raw_uint32_little_endian(FLAC__BitWriter *bw, FLAC__uint32 val)
  89722. {
  89723. /* this doesn't need to be that fast as currently it is only used for vorbis comments */
  89724. if(!FLAC__bitwriter_write_raw_uint32(bw, val & 0xff, 8))
  89725. return false;
  89726. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>8) & 0xff, 8))
  89727. return false;
  89728. if(!FLAC__bitwriter_write_raw_uint32(bw, (val>>16) & 0xff, 8))
  89729. return false;
  89730. if(!FLAC__bitwriter_write_raw_uint32(bw, val>>24, 8))
  89731. return false;
  89732. return true;
  89733. }
  89734. FLaC__INLINE FLAC__bool FLAC__bitwriter_write_byte_block(FLAC__BitWriter *bw, const FLAC__byte vals[], unsigned nvals)
  89735. {
  89736. unsigned i;
  89737. /* this could be faster but currently we don't need it to be since it's only used for writing metadata */
  89738. for(i = 0; i < nvals; i++) {
  89739. if(!FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)(vals[i]), 8))
  89740. return false;
  89741. }
  89742. return true;
  89743. }
  89744. FLAC__bool FLAC__bitwriter_write_unary_unsigned(FLAC__BitWriter *bw, unsigned val)
  89745. {
  89746. if(val < 32)
  89747. return FLAC__bitwriter_write_raw_uint32(bw, 1, ++val);
  89748. else
  89749. return
  89750. FLAC__bitwriter_write_zeroes(bw, val) &&
  89751. FLAC__bitwriter_write_raw_uint32(bw, 1, 1);
  89752. }
  89753. unsigned FLAC__bitwriter_rice_bits(FLAC__int32 val, unsigned parameter)
  89754. {
  89755. FLAC__uint32 uval;
  89756. FLAC__ASSERT(parameter < sizeof(unsigned)*8);
  89757. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  89758. uval = (val<<1) ^ (val>>31);
  89759. return 1 + parameter + (uval >> parameter);
  89760. }
  89761. #if 0 /* UNUSED */
  89762. unsigned FLAC__bitwriter_golomb_bits_signed(int val, unsigned parameter)
  89763. {
  89764. unsigned bits, msbs, uval;
  89765. unsigned k;
  89766. FLAC__ASSERT(parameter > 0);
  89767. /* fold signed to unsigned */
  89768. if(val < 0)
  89769. uval = (unsigned)(((-(++val)) << 1) + 1);
  89770. else
  89771. uval = (unsigned)(val << 1);
  89772. k = FLAC__bitmath_ilog2(parameter);
  89773. if(parameter == 1u<<k) {
  89774. FLAC__ASSERT(k <= 30);
  89775. msbs = uval >> k;
  89776. bits = 1 + k + msbs;
  89777. }
  89778. else {
  89779. unsigned q, r, d;
  89780. d = (1 << (k+1)) - parameter;
  89781. q = uval / parameter;
  89782. r = uval - (q * parameter);
  89783. bits = 1 + q + k;
  89784. if(r >= d)
  89785. bits++;
  89786. }
  89787. return bits;
  89788. }
  89789. unsigned FLAC__bitwriter_golomb_bits_unsigned(unsigned uval, unsigned parameter)
  89790. {
  89791. unsigned bits, msbs;
  89792. unsigned k;
  89793. FLAC__ASSERT(parameter > 0);
  89794. k = FLAC__bitmath_ilog2(parameter);
  89795. if(parameter == 1u<<k) {
  89796. FLAC__ASSERT(k <= 30);
  89797. msbs = uval >> k;
  89798. bits = 1 + k + msbs;
  89799. }
  89800. else {
  89801. unsigned q, r, d;
  89802. d = (1 << (k+1)) - parameter;
  89803. q = uval / parameter;
  89804. r = uval - (q * parameter);
  89805. bits = 1 + q + k;
  89806. if(r >= d)
  89807. bits++;
  89808. }
  89809. return bits;
  89810. }
  89811. #endif /* UNUSED */
  89812. FLAC__bool FLAC__bitwriter_write_rice_signed(FLAC__BitWriter *bw, FLAC__int32 val, unsigned parameter)
  89813. {
  89814. unsigned total_bits, interesting_bits, msbs;
  89815. FLAC__uint32 uval, pattern;
  89816. FLAC__ASSERT(0 != bw);
  89817. FLAC__ASSERT(0 != bw->buffer);
  89818. FLAC__ASSERT(parameter < 8*sizeof(uval));
  89819. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  89820. uval = (val<<1) ^ (val>>31);
  89821. msbs = uval >> parameter;
  89822. interesting_bits = 1 + parameter;
  89823. total_bits = interesting_bits + msbs;
  89824. pattern = 1 << parameter; /* the unary end bit */
  89825. pattern |= (uval & ((1<<parameter)-1)); /* the binary LSBs */
  89826. if(total_bits <= 32)
  89827. return FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits);
  89828. else
  89829. return
  89830. FLAC__bitwriter_write_zeroes(bw, msbs) && /* write the unary MSBs */
  89831. FLAC__bitwriter_write_raw_uint32(bw, pattern, interesting_bits); /* write the unary end bit and binary LSBs */
  89832. }
  89833. FLAC__bool FLAC__bitwriter_write_rice_signed_block(FLAC__BitWriter *bw, const FLAC__int32 *vals, unsigned nvals, unsigned parameter)
  89834. {
  89835. const FLAC__uint32 mask1 = FLAC__WORD_ALL_ONES << parameter; /* we val|=mask1 to set the stop bit above it... */
  89836. const FLAC__uint32 mask2 = FLAC__WORD_ALL_ONES >> (31-parameter); /* ...then mask off the bits above the stop bit with val&=mask2*/
  89837. FLAC__uint32 uval;
  89838. unsigned left;
  89839. const unsigned lsbits = 1 + parameter;
  89840. unsigned msbits;
  89841. FLAC__ASSERT(0 != bw);
  89842. FLAC__ASSERT(0 != bw->buffer);
  89843. FLAC__ASSERT(parameter < 8*sizeof(bwword)-1);
  89844. /* WATCHOUT: code does not work with <32bit words; we can make things much faster with this assertion */
  89845. FLAC__ASSERT(FLAC__BITS_PER_WORD >= 32);
  89846. while(nvals) {
  89847. /* fold signed to unsigned; actual formula is: negative(v)? -2v-1 : 2v */
  89848. uval = (*vals<<1) ^ (*vals>>31);
  89849. msbits = uval >> parameter;
  89850. #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) */
  89851. if(bw->bits && bw->bits + msbits + lsbits <= FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  89852. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  89853. bw->bits = bw->bits + msbits + lsbits;
  89854. uval |= mask1; /* set stop bit */
  89855. uval &= mask2; /* mask off unused top bits */
  89856. /* NOT: bw->accum <<= msbits + lsbits because msbits+lsbits could be 32, then the shift would be a NOP */
  89857. bw->accum <<= msbits;
  89858. bw->accum <<= lsbits;
  89859. bw->accum |= uval;
  89860. if(bw->bits == FLAC__BITS_PER_WORD) {
  89861. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89862. bw->bits = 0;
  89863. /* burying the capacity check down here means we have to grow the buffer a little if there are more vals to do */
  89864. if(bw->capacity <= bw->words && nvals > 1 && !bitwriter_grow_(bw, 1)) {
  89865. FLAC__ASSERT(bw->capacity == bw->words);
  89866. return false;
  89867. }
  89868. }
  89869. }
  89870. else {
  89871. #elif 1 /*@@@@@@ OPT: try this version with MSVC6 to see if better, not much difference for gcc-4 */
  89872. if(bw->bits && bw->bits + msbits + lsbits < FLAC__BITS_PER_WORD) { /* i.e. if the whole thing fits in the current bwword */
  89873. /* ^^^ if bw->bits is 0 then we may have filled the buffer and have no free bwword to work in */
  89874. bw->bits = bw->bits + msbits + lsbits;
  89875. uval |= mask1; /* set stop bit */
  89876. uval &= mask2; /* mask off unused top bits */
  89877. bw->accum <<= msbits + lsbits;
  89878. bw->accum |= uval;
  89879. }
  89880. else {
  89881. #endif
  89882. /* slightly pessimistic size check but faster than "<= bw->words + (bw->bits+msbits+lsbits+FLAC__BITS_PER_WORD-1)/FLAC__BITS_PER_WORD" */
  89883. /* OPT: pessimism may cause flurry of false calls to grow_ which eat up all savings before it */
  89884. if(bw->capacity <= bw->words + bw->bits + msbits + 1/*lsbits always fit in 1 bwword*/ && !bitwriter_grow_(bw, msbits+lsbits))
  89885. return false;
  89886. if(msbits) {
  89887. /* first part gets to word alignment */
  89888. if(bw->bits) {
  89889. left = FLAC__BITS_PER_WORD - bw->bits;
  89890. if(msbits < left) {
  89891. bw->accum <<= msbits;
  89892. bw->bits += msbits;
  89893. goto break1;
  89894. }
  89895. else {
  89896. bw->accum <<= left;
  89897. msbits -= left;
  89898. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89899. bw->bits = 0;
  89900. }
  89901. }
  89902. /* do whole words */
  89903. while(msbits >= FLAC__BITS_PER_WORD) {
  89904. bw->buffer[bw->words++] = 0;
  89905. msbits -= FLAC__BITS_PER_WORD;
  89906. }
  89907. /* do any leftovers */
  89908. if(msbits > 0) {
  89909. bw->accum = 0;
  89910. bw->bits = msbits;
  89911. }
  89912. }
  89913. break1:
  89914. uval |= mask1; /* set stop bit */
  89915. uval &= mask2; /* mask off unused top bits */
  89916. left = FLAC__BITS_PER_WORD - bw->bits;
  89917. if(lsbits < left) {
  89918. bw->accum <<= lsbits;
  89919. bw->accum |= uval;
  89920. bw->bits += lsbits;
  89921. }
  89922. else {
  89923. /* if bw->bits == 0, left==FLAC__BITS_PER_WORD which will always
  89924. * be > lsbits (because of previous assertions) so it would have
  89925. * triggered the (lsbits<left) case above.
  89926. */
  89927. FLAC__ASSERT(bw->bits);
  89928. FLAC__ASSERT(left < FLAC__BITS_PER_WORD);
  89929. bw->accum <<= left;
  89930. bw->accum |= uval >> (bw->bits = lsbits - left);
  89931. bw->buffer[bw->words++] = SWAP_BE_WORD_TO_HOST(bw->accum);
  89932. bw->accum = uval;
  89933. }
  89934. #if 1
  89935. }
  89936. #endif
  89937. vals++;
  89938. nvals--;
  89939. }
  89940. return true;
  89941. }
  89942. #if 0 /* UNUSED */
  89943. FLAC__bool FLAC__bitwriter_write_golomb_signed(FLAC__BitWriter *bw, int val, unsigned parameter)
  89944. {
  89945. unsigned total_bits, msbs, uval;
  89946. unsigned k;
  89947. FLAC__ASSERT(0 != bw);
  89948. FLAC__ASSERT(0 != bw->buffer);
  89949. FLAC__ASSERT(parameter > 0);
  89950. /* fold signed to unsigned */
  89951. if(val < 0)
  89952. uval = (unsigned)(((-(++val)) << 1) + 1);
  89953. else
  89954. uval = (unsigned)(val << 1);
  89955. k = FLAC__bitmath_ilog2(parameter);
  89956. if(parameter == 1u<<k) {
  89957. unsigned pattern;
  89958. FLAC__ASSERT(k <= 30);
  89959. msbs = uval >> k;
  89960. total_bits = 1 + k + msbs;
  89961. pattern = 1 << k; /* the unary end bit */
  89962. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  89963. if(total_bits <= 32) {
  89964. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  89965. return false;
  89966. }
  89967. else {
  89968. /* write the unary MSBs */
  89969. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  89970. return false;
  89971. /* write the unary end bit and binary LSBs */
  89972. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  89973. return false;
  89974. }
  89975. }
  89976. else {
  89977. unsigned q, r, d;
  89978. d = (1 << (k+1)) - parameter;
  89979. q = uval / parameter;
  89980. r = uval - (q * parameter);
  89981. /* write the unary MSBs */
  89982. if(!FLAC__bitwriter_write_zeroes(bw, q))
  89983. return false;
  89984. /* write the unary end bit */
  89985. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  89986. return false;
  89987. /* write the binary LSBs */
  89988. if(r >= d) {
  89989. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  89990. return false;
  89991. }
  89992. else {
  89993. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  89994. return false;
  89995. }
  89996. }
  89997. return true;
  89998. }
  89999. FLAC__bool FLAC__bitwriter_write_golomb_unsigned(FLAC__BitWriter *bw, unsigned uval, unsigned parameter)
  90000. {
  90001. unsigned total_bits, msbs;
  90002. unsigned k;
  90003. FLAC__ASSERT(0 != bw);
  90004. FLAC__ASSERT(0 != bw->buffer);
  90005. FLAC__ASSERT(parameter > 0);
  90006. k = FLAC__bitmath_ilog2(parameter);
  90007. if(parameter == 1u<<k) {
  90008. unsigned pattern;
  90009. FLAC__ASSERT(k <= 30);
  90010. msbs = uval >> k;
  90011. total_bits = 1 + k + msbs;
  90012. pattern = 1 << k; /* the unary end bit */
  90013. pattern |= (uval & ((1u<<k)-1)); /* the binary LSBs */
  90014. if(total_bits <= 32) {
  90015. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, total_bits))
  90016. return false;
  90017. }
  90018. else {
  90019. /* write the unary MSBs */
  90020. if(!FLAC__bitwriter_write_zeroes(bw, msbs))
  90021. return false;
  90022. /* write the unary end bit and binary LSBs */
  90023. if(!FLAC__bitwriter_write_raw_uint32(bw, pattern, k+1))
  90024. return false;
  90025. }
  90026. }
  90027. else {
  90028. unsigned q, r, d;
  90029. d = (1 << (k+1)) - parameter;
  90030. q = uval / parameter;
  90031. r = uval - (q * parameter);
  90032. /* write the unary MSBs */
  90033. if(!FLAC__bitwriter_write_zeroes(bw, q))
  90034. return false;
  90035. /* write the unary end bit */
  90036. if(!FLAC__bitwriter_write_raw_uint32(bw, 1, 1))
  90037. return false;
  90038. /* write the binary LSBs */
  90039. if(r >= d) {
  90040. if(!FLAC__bitwriter_write_raw_uint32(bw, r+d, k+1))
  90041. return false;
  90042. }
  90043. else {
  90044. if(!FLAC__bitwriter_write_raw_uint32(bw, r, k))
  90045. return false;
  90046. }
  90047. }
  90048. return true;
  90049. }
  90050. #endif /* UNUSED */
  90051. FLAC__bool FLAC__bitwriter_write_utf8_uint32(FLAC__BitWriter *bw, FLAC__uint32 val)
  90052. {
  90053. FLAC__bool ok = 1;
  90054. FLAC__ASSERT(0 != bw);
  90055. FLAC__ASSERT(0 != bw->buffer);
  90056. FLAC__ASSERT(!(val & 0x80000000)); /* this version only handles 31 bits */
  90057. if(val < 0x80) {
  90058. return FLAC__bitwriter_write_raw_uint32(bw, val, 8);
  90059. }
  90060. else if(val < 0x800) {
  90061. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (val>>6), 8);
  90062. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90063. }
  90064. else if(val < 0x10000) {
  90065. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (val>>12), 8);
  90066. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90067. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90068. }
  90069. else if(val < 0x200000) {
  90070. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (val>>18), 8);
  90071. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90072. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90073. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90074. }
  90075. else if(val < 0x4000000) {
  90076. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (val>>24), 8);
  90077. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  90078. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90079. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90080. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90081. }
  90082. else {
  90083. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (val>>30), 8);
  90084. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>24)&0x3F), 8);
  90085. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>18)&0x3F), 8);
  90086. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>12)&0x3F), 8);
  90087. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | ((val>>6)&0x3F), 8);
  90088. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (val&0x3F), 8);
  90089. }
  90090. return ok;
  90091. }
  90092. FLAC__bool FLAC__bitwriter_write_utf8_uint64(FLAC__BitWriter *bw, FLAC__uint64 val)
  90093. {
  90094. FLAC__bool ok = 1;
  90095. FLAC__ASSERT(0 != bw);
  90096. FLAC__ASSERT(0 != bw->buffer);
  90097. FLAC__ASSERT(!(val & FLAC__U64L(0xFFFFFFF000000000))); /* this version only handles 36 bits */
  90098. if(val < 0x80) {
  90099. return FLAC__bitwriter_write_raw_uint32(bw, (FLAC__uint32)val, 8);
  90100. }
  90101. else if(val < 0x800) {
  90102. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xC0 | (FLAC__uint32)(val>>6), 8);
  90103. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90104. }
  90105. else if(val < 0x10000) {
  90106. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xE0 | (FLAC__uint32)(val>>12), 8);
  90107. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90108. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90109. }
  90110. else if(val < 0x200000) {
  90111. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF0 | (FLAC__uint32)(val>>18), 8);
  90112. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90113. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90114. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90115. }
  90116. else if(val < 0x4000000) {
  90117. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xF8 | (FLAC__uint32)(val>>24), 8);
  90118. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90119. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90120. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90121. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90122. }
  90123. else if(val < 0x80000000) {
  90124. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFC | (FLAC__uint32)(val>>30), 8);
  90125. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  90126. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90127. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90128. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90129. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90130. }
  90131. else {
  90132. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0xFE, 8);
  90133. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>30)&0x3F), 8);
  90134. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>24)&0x3F), 8);
  90135. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>18)&0x3F), 8);
  90136. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>12)&0x3F), 8);
  90137. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)((val>>6)&0x3F), 8);
  90138. ok &= FLAC__bitwriter_write_raw_uint32(bw, 0x80 | (FLAC__uint32)(val&0x3F), 8);
  90139. }
  90140. return ok;
  90141. }
  90142. FLAC__bool FLAC__bitwriter_zero_pad_to_byte_boundary(FLAC__BitWriter *bw)
  90143. {
  90144. /* 0-pad to byte boundary */
  90145. if(bw->bits & 7u)
  90146. return FLAC__bitwriter_write_zeroes(bw, 8 - (bw->bits & 7u));
  90147. else
  90148. return true;
  90149. }
  90150. #endif
  90151. /********* End of inlined file: bitwriter.c *********/
  90152. /********* Start of inlined file: cpu.c *********/
  90153. /********* Start of inlined file: juce_FlacHeader.h *********/
  90154. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90155. // tasks..
  90156. /********* Start of inlined file: juce_Config.h *********/
  90157. #ifndef __JUCE_CONFIG_JUCEHEADER__
  90158. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  90159. /*
  90160. This file contains macros that enable/disable various JUCE features.
  90161. */
  90162. /** The name of the namespace that all Juce classes and functions will be
  90163. put inside. If this is not defined, no namespace will be used.
  90164. */
  90165. #ifndef JUCE_NAMESPACE
  90166. #define JUCE_NAMESPACE juce
  90167. #endif
  90168. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  90169. but if you define this value, you can override this can force it to be true or
  90170. false.
  90171. */
  90172. #ifndef JUCE_FORCE_DEBUG
  90173. //#define JUCE_FORCE_DEBUG 1
  90174. #endif
  90175. /** If this flag is enabled, the the jassert and jassertfalse macros will
  90176. always use Logger::writeToLog() to write a message when an assertion happens.
  90177. Enabling it will also leave this turned on in release builds. When it's disabled,
  90178. however, the jassert and jassertfalse macros will not be compiled in a
  90179. release build.
  90180. @see jassert, jassertfalse, Logger
  90181. */
  90182. #ifndef JUCE_LOG_ASSERTIONS
  90183. // #define JUCE_LOG_ASSERTIONS 1
  90184. #endif
  90185. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  90186. which the ASIOAudioIODevice class can't be built. See the comments in the
  90187. ASIOAudioIODevice class's header file for more info about this.
  90188. (This only affects a Win32 build)
  90189. */
  90190. #ifndef JUCE_ASIO
  90191. #define JUCE_ASIO 1
  90192. #endif
  90193. /** Comment out this macro to disable building of ALSA device support on Linux.
  90194. */
  90195. #ifndef JUCE_ALSA
  90196. #define JUCE_ALSA 1
  90197. #endif
  90198. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  90199. have the SDK installed.
  90200. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  90201. classes will be unavailable.
  90202. On Windows, if you enable this, you'll need to have the QuickTime SDK
  90203. installed, and its header files will need to be on your include path.
  90204. */
  90205. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  90206. #define JUCE_QUICKTIME 1
  90207. #endif
  90208. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  90209. have the appropriate headers and libraries available. If it's not enabled, the
  90210. OpenGLComponent class will be unavailable.
  90211. */
  90212. #ifndef JUCE_OPENGL
  90213. #define JUCE_OPENGL 1
  90214. #endif
  90215. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  90216. If you're not going to need either of these formats, turn off the flags to
  90217. avoid bloating your codebase with them.
  90218. */
  90219. #ifndef JUCE_USE_FLAC
  90220. #define JUCE_USE_FLAC 1
  90221. #endif
  90222. #ifndef JUCE_USE_OGGVORBIS
  90223. #define JUCE_USE_OGGVORBIS 1
  90224. #endif
  90225. /** This flag lets you enable support for CD-burning. You might want to disable
  90226. it to build without the MS SDK under windows.
  90227. */
  90228. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  90229. #define JUCE_USE_CDBURNER 1
  90230. #endif
  90231. /** Enabling this macro means that all regions that get repainted will have a coloured
  90232. line drawn around them.
  90233. This is handy if you're trying to optimise drawing, because it lets you easily see
  90234. when anything is being repainted unnecessarily.
  90235. */
  90236. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  90237. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  90238. #endif
  90239. /** Enable this under Linux to use Xinerama for multi-monitor support.
  90240. */
  90241. #ifndef JUCE_USE_XINERAMA
  90242. #define JUCE_USE_XINERAMA 1
  90243. #endif
  90244. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  90245. */
  90246. #ifndef JUCE_USE_XSHM
  90247. #define JUCE_USE_XSHM 1
  90248. #endif
  90249. /** Enabling this builds support for VST audio plugins.
  90250. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  90251. */
  90252. #ifndef JUCE_PLUGINHOST_VST
  90253. // #define JUCE_PLUGINHOST_VST 1
  90254. #endif
  90255. /** Enabling this builds support for AudioUnit audio plugins.
  90256. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  90257. */
  90258. #ifndef JUCE_PLUGINHOST_AU
  90259. // #define JUCE_PLUGINHOST_AU 1
  90260. #endif
  90261. /** Disabling this will avoid linking to any UI code. This is handy for
  90262. writing command-line utilities, e.g. on linux boxes which don't have some
  90263. of the UI libraries installed.
  90264. (On mac and windows, this won't generally make much difference to the build).
  90265. */
  90266. #ifndef JUCE_BUILD_GUI_CLASSES
  90267. #define JUCE_BUILD_GUI_CLASSES 1
  90268. #endif
  90269. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  90270. */
  90271. #ifndef JUCE_WEB_BROWSER
  90272. #define JUCE_WEB_BROWSER 1
  90273. #endif
  90274. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  90275. codebase - you might need to use this if you're linking to some of these libraries
  90276. yourself.
  90277. */
  90278. #ifndef JUCE_INCLUDE_ZLIB_CODE
  90279. #define JUCE_INCLUDE_ZLIB_CODE 1
  90280. #endif
  90281. #ifndef JUCE_INCLUDE_FLAC_CODE
  90282. #define JUCE_INCLUDE_FLAC_CODE 1
  90283. #endif
  90284. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  90285. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  90286. #endif
  90287. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  90288. #define JUCE_INCLUDE_PNGLIB_CODE 1
  90289. #endif
  90290. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  90291. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  90292. #endif
  90293. /** Enable this to add extra memory-leak info to the new and delete operators.
  90294. (Currently, this only affects Windows builds in debug mode).
  90295. */
  90296. #ifndef JUCE_CHECK_MEMORY_LEAKS
  90297. #define JUCE_CHECK_MEMORY_LEAKS 1
  90298. #endif
  90299. /** Enable this to turn on juce's internal catching of exceptions.
  90300. Turning it off will avoid any exception catching. With it on, all exceptions
  90301. are passed to the JUCEApplication::unhandledException() callback for logging.
  90302. */
  90303. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  90304. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  90305. #endif
  90306. /** If this macro is set, the Juce String class will use unicode as its
  90307. internal representation. If it isn't set, it'll use ANSI.
  90308. */
  90309. #ifndef JUCE_STRINGS_ARE_UNICODE
  90310. #define JUCE_STRINGS_ARE_UNICODE 1
  90311. #endif
  90312. #endif
  90313. /********* End of inlined file: juce_Config.h *********/
  90314. #define VERSION "1.2.1"
  90315. #define FLAC__NO_DLL 1
  90316. #ifdef _MSC_VER
  90317. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90318. #endif
  90319. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90320. #define FLAC__SYS_DARWIN 1
  90321. #endif
  90322. /********* End of inlined file: juce_FlacHeader.h *********/
  90323. #if JUCE_USE_FLAC
  90324. #if HAVE_CONFIG_H
  90325. # include <config.h>
  90326. #endif
  90327. #include <stdlib.h>
  90328. #include <stdio.h>
  90329. #if defined FLAC__CPU_IA32
  90330. # include <signal.h>
  90331. #elif defined FLAC__CPU_PPC
  90332. # if !defined FLAC__NO_ASM
  90333. # if defined FLAC__SYS_DARWIN
  90334. # include <sys/sysctl.h>
  90335. # include <mach/mach.h>
  90336. # include <mach/mach_host.h>
  90337. # include <mach/host_info.h>
  90338. # include <mach/machine.h>
  90339. # ifndef CPU_SUBTYPE_POWERPC_970
  90340. # define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
  90341. # endif
  90342. # else /* FLAC__SYS_DARWIN */
  90343. # include <signal.h>
  90344. # include <setjmp.h>
  90345. static sigjmp_buf jmpbuf;
  90346. static volatile sig_atomic_t canjump = 0;
  90347. static void sigill_handler (int sig)
  90348. {
  90349. if (!canjump) {
  90350. signal (sig, SIG_DFL);
  90351. raise (sig);
  90352. }
  90353. canjump = 0;
  90354. siglongjmp (jmpbuf, 1);
  90355. }
  90356. # endif /* FLAC__SYS_DARWIN */
  90357. # endif /* FLAC__NO_ASM */
  90358. #endif /* FLAC__CPU_PPC */
  90359. #if defined (__NetBSD__) || defined(__OpenBSD__)
  90360. #include <sys/param.h>
  90361. #include <sys/sysctl.h>
  90362. #include <machine/cpu.h>
  90363. #endif
  90364. #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
  90365. #include <sys/types.h>
  90366. #include <sys/sysctl.h>
  90367. #endif
  90368. #if defined(__APPLE__)
  90369. /* how to get sysctlbyname()? */
  90370. #endif
  90371. /* these are flags in EDX of CPUID AX=00000001 */
  90372. static const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
  90373. static const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
  90374. static const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
  90375. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
  90376. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
  90377. /* these are flags in ECX of CPUID AX=00000001 */
  90378. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSE3 = 0x00000001;
  90379. static const unsigned FLAC__CPUINFO_IA32_CPUID_SSSE3 = 0x00000200;
  90380. /* these are flags in EDX of CPUID AX=80000001 */
  90381. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
  90382. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
  90383. static const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
  90384. /*
  90385. * Extra stuff needed for detection of OS support for SSE on IA-32
  90386. */
  90387. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
  90388. # if defined(__linux__)
  90389. /*
  90390. * If the OS doesn't support SSE, we will get here with a SIGILL. We
  90391. * modify the return address to jump over the offending SSE instruction
  90392. * and also the operation following it that indicates the instruction
  90393. * executed successfully. In this way we use no global variables and
  90394. * stay thread-safe.
  90395. *
  90396. * 3 + 3 + 6:
  90397. * 3 bytes for "xorps xmm0,xmm0"
  90398. * 3 bytes for estimate of how long the follwing "inc var" instruction is
  90399. * 6 bytes extra in case our estimate is wrong
  90400. * 12 bytes puts us in the NOP "landing zone"
  90401. */
  90402. # undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
  90403. # ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  90404. static void sigill_handler_sse_os(int signal, struct sigcontext sc)
  90405. {
  90406. (void)signal;
  90407. sc.eip += 3 + 3 + 6;
  90408. }
  90409. # else
  90410. # include <sys/ucontext.h>
  90411. static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
  90412. {
  90413. (void)signal, (void)si;
  90414. ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
  90415. }
  90416. # endif
  90417. # elif defined(_MSC_VER)
  90418. # include <windows.h>
  90419. # undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
  90420. # ifdef USE_TRY_CATCH_FLAVOR
  90421. # else
  90422. LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
  90423. {
  90424. if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
  90425. ep->ContextRecord->Eip += 3 + 3 + 6;
  90426. return EXCEPTION_CONTINUE_EXECUTION;
  90427. }
  90428. return EXCEPTION_CONTINUE_SEARCH;
  90429. }
  90430. # endif
  90431. # endif
  90432. #endif
  90433. void FLAC__cpu_info(FLAC__CPUInfo *info)
  90434. {
  90435. /*
  90436. * IA32-specific
  90437. */
  90438. #ifdef FLAC__CPU_IA32
  90439. info->type = FLAC__CPUINFO_TYPE_IA32;
  90440. #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  90441. info->use_asm = true; /* we assume a minimum of 80386 with FLAC__CPU_IA32 */
  90442. info->data.ia32.cpuid = FLAC__cpu_have_cpuid_asm_ia32()? true : false;
  90443. info->data.ia32.bswap = info->data.ia32.cpuid; /* CPUID => BSWAP since it came after */
  90444. info->data.ia32.cmov = false;
  90445. info->data.ia32.mmx = false;
  90446. info->data.ia32.fxsr = false;
  90447. info->data.ia32.sse = false;
  90448. info->data.ia32.sse2 = false;
  90449. info->data.ia32.sse3 = false;
  90450. info->data.ia32.ssse3 = false;
  90451. info->data.ia32._3dnow = false;
  90452. info->data.ia32.ext3dnow = false;
  90453. info->data.ia32.extmmx = false;
  90454. if(info->data.ia32.cpuid) {
  90455. /* http://www.sandpile.org/ia32/cpuid.htm */
  90456. FLAC__uint32 flags_edx, flags_ecx;
  90457. FLAC__cpu_info_asm_ia32(&flags_edx, &flags_ecx);
  90458. info->data.ia32.cmov = (flags_edx & FLAC__CPUINFO_IA32_CPUID_CMOV )? true : false;
  90459. info->data.ia32.mmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
  90460. info->data.ia32.fxsr = (flags_edx & FLAC__CPUINFO_IA32_CPUID_FXSR )? true : false;
  90461. info->data.ia32.sse = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
  90462. info->data.ia32.sse2 = (flags_edx & FLAC__CPUINFO_IA32_CPUID_SSE2 )? true : false;
  90463. info->data.ia32.sse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSE3 )? true : false;
  90464. info->data.ia32.ssse3 = (flags_ecx & FLAC__CPUINFO_IA32_CPUID_SSSE3)? true : false;
  90465. #ifdef FLAC__USE_3DNOW
  90466. flags_edx = FLAC__cpu_info_extended_amd_asm_ia32();
  90467. info->data.ia32._3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW )? true : false;
  90468. info->data.ia32.ext3dnow = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
  90469. info->data.ia32.extmmx = (flags_edx & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX )? true : false;
  90470. #else
  90471. info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
  90472. #endif
  90473. #ifdef DEBUG
  90474. fprintf(stderr, "CPU info (IA-32):\n");
  90475. fprintf(stderr, " CPUID ...... %c\n", info->data.ia32.cpuid ? 'Y' : 'n');
  90476. fprintf(stderr, " BSWAP ...... %c\n", info->data.ia32.bswap ? 'Y' : 'n');
  90477. fprintf(stderr, " CMOV ....... %c\n", info->data.ia32.cmov ? 'Y' : 'n');
  90478. fprintf(stderr, " MMX ........ %c\n", info->data.ia32.mmx ? 'Y' : 'n');
  90479. fprintf(stderr, " FXSR ....... %c\n", info->data.ia32.fxsr ? 'Y' : 'n');
  90480. fprintf(stderr, " SSE ........ %c\n", info->data.ia32.sse ? 'Y' : 'n');
  90481. fprintf(stderr, " SSE2 ....... %c\n", info->data.ia32.sse2 ? 'Y' : 'n');
  90482. fprintf(stderr, " SSE3 ....... %c\n", info->data.ia32.sse3 ? 'Y' : 'n');
  90483. fprintf(stderr, " SSSE3 ...... %c\n", info->data.ia32.ssse3 ? 'Y' : 'n');
  90484. fprintf(stderr, " 3DNow! ..... %c\n", info->data.ia32._3dnow ? 'Y' : 'n');
  90485. fprintf(stderr, " 3DNow!-ext . %c\n", info->data.ia32.ext3dnow? 'Y' : 'n');
  90486. fprintf(stderr, " 3DNow!-MMX . %c\n", info->data.ia32.extmmx ? 'Y' : 'n');
  90487. #endif
  90488. /*
  90489. * now have to check for OS support of SSE/SSE2
  90490. */
  90491. if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
  90492. #if defined FLAC__NO_SSE_OS
  90493. /* assume user knows better than us; turn it off */
  90494. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90495. #elif defined FLAC__SSE_OS
  90496. /* assume user knows better than us; leave as detected above */
  90497. #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
  90498. int sse = 0;
  90499. size_t len;
  90500. /* at least one of these must work: */
  90501. len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
  90502. len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse" , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
  90503. if(!sse)
  90504. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90505. #elif defined(__NetBSD__) || defined (__OpenBSD__)
  90506. # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
  90507. int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
  90508. size_t len = sizeof(val);
  90509. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  90510. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90511. else { /* double-check SSE2 */
  90512. mib[1] = CPU_SSE2;
  90513. len = sizeof(val);
  90514. if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
  90515. info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90516. }
  90517. # else
  90518. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90519. # endif
  90520. #elif defined(__linux__)
  90521. int sse = 0;
  90522. struct sigaction sigill_save;
  90523. #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
  90524. if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
  90525. #else
  90526. struct sigaction sigill_sse;
  90527. sigill_sse.sa_sigaction = sigill_handler_sse_os;
  90528. __sigemptyset(&sigill_sse.sa_mask);
  90529. 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 */
  90530. if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
  90531. #endif
  90532. {
  90533. /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
  90534. /* see sigill_handler_sse_os() for an explanation of the following: */
  90535. asm volatile (
  90536. "xorl %0,%0\n\t" /* for some reason, still need to do this to clear 'sse' var */
  90537. "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
  90538. "incl %0\n\t" /* SIGILL handler will jump over this */
  90539. /* landing zone */
  90540. "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
  90541. "nop\n\t"
  90542. "nop\n\t"
  90543. "nop\n\t"
  90544. "nop\n\t"
  90545. "nop\n\t"
  90546. "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
  90547. "nop\n\t"
  90548. "nop" /* SIGILL jump lands here if "inc" is 1 byte */
  90549. : "=r"(sse)
  90550. : "r"(sse)
  90551. );
  90552. sigaction(SIGILL, &sigill_save, NULL);
  90553. }
  90554. if(!sse)
  90555. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90556. #elif defined(_MSC_VER)
  90557. # ifdef USE_TRY_CATCH_FLAVOR
  90558. _try {
  90559. __asm {
  90560. # if _MSC_VER <= 1200
  90561. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  90562. _emit 0x0F
  90563. _emit 0x57
  90564. _emit 0xC0
  90565. # else
  90566. xorps xmm0,xmm0
  90567. # endif
  90568. }
  90569. }
  90570. _except(EXCEPTION_EXECUTE_HANDLER) {
  90571. if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
  90572. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90573. }
  90574. # else
  90575. int sse = 0;
  90576. LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
  90577. /* see GCC version above for explanation */
  90578. /* http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx */
  90579. /* http://www.codeproject.com/cpp/gccasm.asp */
  90580. /* http://www.hick.org/~mmiller/msvc_inline_asm.html */
  90581. __asm {
  90582. # if _MSC_VER <= 1200
  90583. /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
  90584. _emit 0x0F
  90585. _emit 0x57
  90586. _emit 0xC0
  90587. # else
  90588. xorps xmm0,xmm0
  90589. # endif
  90590. inc sse
  90591. nop
  90592. nop
  90593. nop
  90594. nop
  90595. nop
  90596. nop
  90597. nop
  90598. nop
  90599. nop
  90600. }
  90601. SetUnhandledExceptionFilter(save);
  90602. if(!sse)
  90603. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90604. # endif
  90605. #else
  90606. /* no way to test, disable to be safe */
  90607. info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = info->data.ia32.sse3 = info->data.ia32.ssse3 = false;
  90608. #endif
  90609. #ifdef DEBUG
  90610. fprintf(stderr, " SSE OS sup . %c\n", info->data.ia32.sse ? 'Y' : 'n');
  90611. #endif
  90612. }
  90613. }
  90614. #else
  90615. info->use_asm = false;
  90616. #endif
  90617. /*
  90618. * PPC-specific
  90619. */
  90620. #elif defined FLAC__CPU_PPC
  90621. info->type = FLAC__CPUINFO_TYPE_PPC;
  90622. # if !defined FLAC__NO_ASM
  90623. info->use_asm = true;
  90624. # ifdef FLAC__USE_ALTIVEC
  90625. # if defined FLAC__SYS_DARWIN
  90626. {
  90627. int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
  90628. size_t len = sizeof(val);
  90629. info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
  90630. }
  90631. {
  90632. host_basic_info_data_t hostInfo;
  90633. mach_msg_type_number_t infoCount;
  90634. infoCount = HOST_BASIC_INFO_COUNT;
  90635. host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
  90636. info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
  90637. }
  90638. # else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
  90639. {
  90640. /* no Darwin, do it the brute-force way */
  90641. /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
  90642. info->data.ppc.altivec = 0;
  90643. info->data.ppc.ppc64 = 0;
  90644. signal (SIGILL, sigill_handler);
  90645. canjump = 0;
  90646. if (!sigsetjmp (jmpbuf, 1)) {
  90647. canjump = 1;
  90648. asm volatile (
  90649. "mtspr 256, %0\n\t"
  90650. "vand %%v0, %%v0, %%v0"
  90651. :
  90652. : "r" (-1)
  90653. );
  90654. info->data.ppc.altivec = 1;
  90655. }
  90656. canjump = 0;
  90657. if (!sigsetjmp (jmpbuf, 1)) {
  90658. int x = 0;
  90659. canjump = 1;
  90660. /* PPC64 hardware implements the cntlzd instruction */
  90661. asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
  90662. info->data.ppc.ppc64 = 1;
  90663. }
  90664. signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
  90665. }
  90666. # endif
  90667. # else /* !FLAC__USE_ALTIVEC */
  90668. info->data.ppc.altivec = 0;
  90669. info->data.ppc.ppc64 = 0;
  90670. # endif
  90671. # else
  90672. info->use_asm = false;
  90673. # endif
  90674. /*
  90675. * unknown CPI
  90676. */
  90677. #else
  90678. info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
  90679. info->use_asm = false;
  90680. #endif
  90681. }
  90682. #endif
  90683. /********* End of inlined file: cpu.c *********/
  90684. /********* Start of inlined file: crc.c *********/
  90685. /********* Start of inlined file: juce_FlacHeader.h *********/
  90686. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90687. // tasks..
  90688. /********* Start of inlined file: juce_Config.h *********/
  90689. #ifndef __JUCE_CONFIG_JUCEHEADER__
  90690. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  90691. /*
  90692. This file contains macros that enable/disable various JUCE features.
  90693. */
  90694. /** The name of the namespace that all Juce classes and functions will be
  90695. put inside. If this is not defined, no namespace will be used.
  90696. */
  90697. #ifndef JUCE_NAMESPACE
  90698. #define JUCE_NAMESPACE juce
  90699. #endif
  90700. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  90701. but if you define this value, you can override this can force it to be true or
  90702. false.
  90703. */
  90704. #ifndef JUCE_FORCE_DEBUG
  90705. //#define JUCE_FORCE_DEBUG 1
  90706. #endif
  90707. /** If this flag is enabled, the the jassert and jassertfalse macros will
  90708. always use Logger::writeToLog() to write a message when an assertion happens.
  90709. Enabling it will also leave this turned on in release builds. When it's disabled,
  90710. however, the jassert and jassertfalse macros will not be compiled in a
  90711. release build.
  90712. @see jassert, jassertfalse, Logger
  90713. */
  90714. #ifndef JUCE_LOG_ASSERTIONS
  90715. // #define JUCE_LOG_ASSERTIONS 1
  90716. #endif
  90717. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  90718. which the ASIOAudioIODevice class can't be built. See the comments in the
  90719. ASIOAudioIODevice class's header file for more info about this.
  90720. (This only affects a Win32 build)
  90721. */
  90722. #ifndef JUCE_ASIO
  90723. #define JUCE_ASIO 1
  90724. #endif
  90725. /** Comment out this macro to disable building of ALSA device support on Linux.
  90726. */
  90727. #ifndef JUCE_ALSA
  90728. #define JUCE_ALSA 1
  90729. #endif
  90730. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  90731. have the SDK installed.
  90732. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  90733. classes will be unavailable.
  90734. On Windows, if you enable this, you'll need to have the QuickTime SDK
  90735. installed, and its header files will need to be on your include path.
  90736. */
  90737. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  90738. #define JUCE_QUICKTIME 1
  90739. #endif
  90740. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  90741. have the appropriate headers and libraries available. If it's not enabled, the
  90742. OpenGLComponent class will be unavailable.
  90743. */
  90744. #ifndef JUCE_OPENGL
  90745. #define JUCE_OPENGL 1
  90746. #endif
  90747. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  90748. If you're not going to need either of these formats, turn off the flags to
  90749. avoid bloating your codebase with them.
  90750. */
  90751. #ifndef JUCE_USE_FLAC
  90752. #define JUCE_USE_FLAC 1
  90753. #endif
  90754. #ifndef JUCE_USE_OGGVORBIS
  90755. #define JUCE_USE_OGGVORBIS 1
  90756. #endif
  90757. /** This flag lets you enable support for CD-burning. You might want to disable
  90758. it to build without the MS SDK under windows.
  90759. */
  90760. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  90761. #define JUCE_USE_CDBURNER 1
  90762. #endif
  90763. /** Enabling this macro means that all regions that get repainted will have a coloured
  90764. line drawn around them.
  90765. This is handy if you're trying to optimise drawing, because it lets you easily see
  90766. when anything is being repainted unnecessarily.
  90767. */
  90768. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  90769. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  90770. #endif
  90771. /** Enable this under Linux to use Xinerama for multi-monitor support.
  90772. */
  90773. #ifndef JUCE_USE_XINERAMA
  90774. #define JUCE_USE_XINERAMA 1
  90775. #endif
  90776. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  90777. */
  90778. #ifndef JUCE_USE_XSHM
  90779. #define JUCE_USE_XSHM 1
  90780. #endif
  90781. /** Enabling this builds support for VST audio plugins.
  90782. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  90783. */
  90784. #ifndef JUCE_PLUGINHOST_VST
  90785. // #define JUCE_PLUGINHOST_VST 1
  90786. #endif
  90787. /** Enabling this builds support for AudioUnit audio plugins.
  90788. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  90789. */
  90790. #ifndef JUCE_PLUGINHOST_AU
  90791. // #define JUCE_PLUGINHOST_AU 1
  90792. #endif
  90793. /** Disabling this will avoid linking to any UI code. This is handy for
  90794. writing command-line utilities, e.g. on linux boxes which don't have some
  90795. of the UI libraries installed.
  90796. (On mac and windows, this won't generally make much difference to the build).
  90797. */
  90798. #ifndef JUCE_BUILD_GUI_CLASSES
  90799. #define JUCE_BUILD_GUI_CLASSES 1
  90800. #endif
  90801. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  90802. */
  90803. #ifndef JUCE_WEB_BROWSER
  90804. #define JUCE_WEB_BROWSER 1
  90805. #endif
  90806. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  90807. codebase - you might need to use this if you're linking to some of these libraries
  90808. yourself.
  90809. */
  90810. #ifndef JUCE_INCLUDE_ZLIB_CODE
  90811. #define JUCE_INCLUDE_ZLIB_CODE 1
  90812. #endif
  90813. #ifndef JUCE_INCLUDE_FLAC_CODE
  90814. #define JUCE_INCLUDE_FLAC_CODE 1
  90815. #endif
  90816. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  90817. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  90818. #endif
  90819. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  90820. #define JUCE_INCLUDE_PNGLIB_CODE 1
  90821. #endif
  90822. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  90823. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  90824. #endif
  90825. /** Enable this to add extra memory-leak info to the new and delete operators.
  90826. (Currently, this only affects Windows builds in debug mode).
  90827. */
  90828. #ifndef JUCE_CHECK_MEMORY_LEAKS
  90829. #define JUCE_CHECK_MEMORY_LEAKS 1
  90830. #endif
  90831. /** Enable this to turn on juce's internal catching of exceptions.
  90832. Turning it off will avoid any exception catching. With it on, all exceptions
  90833. are passed to the JUCEApplication::unhandledException() callback for logging.
  90834. */
  90835. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  90836. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  90837. #endif
  90838. /** If this macro is set, the Juce String class will use unicode as its
  90839. internal representation. If it isn't set, it'll use ANSI.
  90840. */
  90841. #ifndef JUCE_STRINGS_ARE_UNICODE
  90842. #define JUCE_STRINGS_ARE_UNICODE 1
  90843. #endif
  90844. #endif
  90845. /********* End of inlined file: juce_Config.h *********/
  90846. #define VERSION "1.2.1"
  90847. #define FLAC__NO_DLL 1
  90848. #ifdef _MSC_VER
  90849. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  90850. #endif
  90851. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  90852. #define FLAC__SYS_DARWIN 1
  90853. #endif
  90854. /********* End of inlined file: juce_FlacHeader.h *********/
  90855. #if JUCE_USE_FLAC
  90856. #if HAVE_CONFIG_H
  90857. # include <config.h>
  90858. #endif
  90859. /* CRC-8, poly = x^8 + x^2 + x^1 + x^0, init = 0 */
  90860. FLAC__byte const FLAC__crc8_table[256] = {
  90861. 0x00, 0x07, 0x0E, 0x09, 0x1C, 0x1B, 0x12, 0x15,
  90862. 0x38, 0x3F, 0x36, 0x31, 0x24, 0x23, 0x2A, 0x2D,
  90863. 0x70, 0x77, 0x7E, 0x79, 0x6C, 0x6B, 0x62, 0x65,
  90864. 0x48, 0x4F, 0x46, 0x41, 0x54, 0x53, 0x5A, 0x5D,
  90865. 0xE0, 0xE7, 0xEE, 0xE9, 0xFC, 0xFB, 0xF2, 0xF5,
  90866. 0xD8, 0xDF, 0xD6, 0xD1, 0xC4, 0xC3, 0xCA, 0xCD,
  90867. 0x90, 0x97, 0x9E, 0x99, 0x8C, 0x8B, 0x82, 0x85,
  90868. 0xA8, 0xAF, 0xA6, 0xA1, 0xB4, 0xB3, 0xBA, 0xBD,
  90869. 0xC7, 0xC0, 0xC9, 0xCE, 0xDB, 0xDC, 0xD5, 0xD2,
  90870. 0xFF, 0xF8, 0xF1, 0xF6, 0xE3, 0xE4, 0xED, 0xEA,
  90871. 0xB7, 0xB0, 0xB9, 0xBE, 0xAB, 0xAC, 0xA5, 0xA2,
  90872. 0x8F, 0x88, 0x81, 0x86, 0x93, 0x94, 0x9D, 0x9A,
  90873. 0x27, 0x20, 0x29, 0x2E, 0x3B, 0x3C, 0x35, 0x32,
  90874. 0x1F, 0x18, 0x11, 0x16, 0x03, 0x04, 0x0D, 0x0A,
  90875. 0x57, 0x50, 0x59, 0x5E, 0x4B, 0x4C, 0x45, 0x42,
  90876. 0x6F, 0x68, 0x61, 0x66, 0x73, 0x74, 0x7D, 0x7A,
  90877. 0x89, 0x8E, 0x87, 0x80, 0x95, 0x92, 0x9B, 0x9C,
  90878. 0xB1, 0xB6, 0xBF, 0xB8, 0xAD, 0xAA, 0xA3, 0xA4,
  90879. 0xF9, 0xFE, 0xF7, 0xF0, 0xE5, 0xE2, 0xEB, 0xEC,
  90880. 0xC1, 0xC6, 0xCF, 0xC8, 0xDD, 0xDA, 0xD3, 0xD4,
  90881. 0x69, 0x6E, 0x67, 0x60, 0x75, 0x72, 0x7B, 0x7C,
  90882. 0x51, 0x56, 0x5F, 0x58, 0x4D, 0x4A, 0x43, 0x44,
  90883. 0x19, 0x1E, 0x17, 0x10, 0x05, 0x02, 0x0B, 0x0C,
  90884. 0x21, 0x26, 0x2F, 0x28, 0x3D, 0x3A, 0x33, 0x34,
  90885. 0x4E, 0x49, 0x40, 0x47, 0x52, 0x55, 0x5C, 0x5B,
  90886. 0x76, 0x71, 0x78, 0x7F, 0x6A, 0x6D, 0x64, 0x63,
  90887. 0x3E, 0x39, 0x30, 0x37, 0x22, 0x25, 0x2C, 0x2B,
  90888. 0x06, 0x01, 0x08, 0x0F, 0x1A, 0x1D, 0x14, 0x13,
  90889. 0xAE, 0xA9, 0xA0, 0xA7, 0xB2, 0xB5, 0xBC, 0xBB,
  90890. 0x96, 0x91, 0x98, 0x9F, 0x8A, 0x8D, 0x84, 0x83,
  90891. 0xDE, 0xD9, 0xD0, 0xD7, 0xC2, 0xC5, 0xCC, 0xCB,
  90892. 0xE6, 0xE1, 0xE8, 0xEF, 0xFA, 0xFD, 0xF4, 0xF3
  90893. };
  90894. /* CRC-16, poly = x^16 + x^15 + x^2 + x^0, init = 0 */
  90895. unsigned FLAC__crc16_table[256] = {
  90896. 0x0000, 0x8005, 0x800f, 0x000a, 0x801b, 0x001e, 0x0014, 0x8011,
  90897. 0x8033, 0x0036, 0x003c, 0x8039, 0x0028, 0x802d, 0x8027, 0x0022,
  90898. 0x8063, 0x0066, 0x006c, 0x8069, 0x0078, 0x807d, 0x8077, 0x0072,
  90899. 0x0050, 0x8055, 0x805f, 0x005a, 0x804b, 0x004e, 0x0044, 0x8041,
  90900. 0x80c3, 0x00c6, 0x00cc, 0x80c9, 0x00d8, 0x80dd, 0x80d7, 0x00d2,
  90901. 0x00f0, 0x80f5, 0x80ff, 0x00fa, 0x80eb, 0x00ee, 0x00e4, 0x80e1,
  90902. 0x00a0, 0x80a5, 0x80af, 0x00aa, 0x80bb, 0x00be, 0x00b4, 0x80b1,
  90903. 0x8093, 0x0096, 0x009c, 0x8099, 0x0088, 0x808d, 0x8087, 0x0082,
  90904. 0x8183, 0x0186, 0x018c, 0x8189, 0x0198, 0x819d, 0x8197, 0x0192,
  90905. 0x01b0, 0x81b5, 0x81bf, 0x01ba, 0x81ab, 0x01ae, 0x01a4, 0x81a1,
  90906. 0x01e0, 0x81e5, 0x81ef, 0x01ea, 0x81fb, 0x01fe, 0x01f4, 0x81f1,
  90907. 0x81d3, 0x01d6, 0x01dc, 0x81d9, 0x01c8, 0x81cd, 0x81c7, 0x01c2,
  90908. 0x0140, 0x8145, 0x814f, 0x014a, 0x815b, 0x015e, 0x0154, 0x8151,
  90909. 0x8173, 0x0176, 0x017c, 0x8179, 0x0168, 0x816d, 0x8167, 0x0162,
  90910. 0x8123, 0x0126, 0x012c, 0x8129, 0x0138, 0x813d, 0x8137, 0x0132,
  90911. 0x0110, 0x8115, 0x811f, 0x011a, 0x810b, 0x010e, 0x0104, 0x8101,
  90912. 0x8303, 0x0306, 0x030c, 0x8309, 0x0318, 0x831d, 0x8317, 0x0312,
  90913. 0x0330, 0x8335, 0x833f, 0x033a, 0x832b, 0x032e, 0x0324, 0x8321,
  90914. 0x0360, 0x8365, 0x836f, 0x036a, 0x837b, 0x037e, 0x0374, 0x8371,
  90915. 0x8353, 0x0356, 0x035c, 0x8359, 0x0348, 0x834d, 0x8347, 0x0342,
  90916. 0x03c0, 0x83c5, 0x83cf, 0x03ca, 0x83db, 0x03de, 0x03d4, 0x83d1,
  90917. 0x83f3, 0x03f6, 0x03fc, 0x83f9, 0x03e8, 0x83ed, 0x83e7, 0x03e2,
  90918. 0x83a3, 0x03a6, 0x03ac, 0x83a9, 0x03b8, 0x83bd, 0x83b7, 0x03b2,
  90919. 0x0390, 0x8395, 0x839f, 0x039a, 0x838b, 0x038e, 0x0384, 0x8381,
  90920. 0x0280, 0x8285, 0x828f, 0x028a, 0x829b, 0x029e, 0x0294, 0x8291,
  90921. 0x82b3, 0x02b6, 0x02bc, 0x82b9, 0x02a8, 0x82ad, 0x82a7, 0x02a2,
  90922. 0x82e3, 0x02e6, 0x02ec, 0x82e9, 0x02f8, 0x82fd, 0x82f7, 0x02f2,
  90923. 0x02d0, 0x82d5, 0x82df, 0x02da, 0x82cb, 0x02ce, 0x02c4, 0x82c1,
  90924. 0x8243, 0x0246, 0x024c, 0x8249, 0x0258, 0x825d, 0x8257, 0x0252,
  90925. 0x0270, 0x8275, 0x827f, 0x027a, 0x826b, 0x026e, 0x0264, 0x8261,
  90926. 0x0220, 0x8225, 0x822f, 0x022a, 0x823b, 0x023e, 0x0234, 0x8231,
  90927. 0x8213, 0x0216, 0x021c, 0x8219, 0x0208, 0x820d, 0x8207, 0x0202
  90928. };
  90929. void FLAC__crc8_update(const FLAC__byte data, FLAC__uint8 *crc)
  90930. {
  90931. *crc = FLAC__crc8_table[*crc ^ data];
  90932. }
  90933. void FLAC__crc8_update_block(const FLAC__byte *data, unsigned len, FLAC__uint8 *crc)
  90934. {
  90935. while(len--)
  90936. *crc = FLAC__crc8_table[*crc ^ *data++];
  90937. }
  90938. FLAC__uint8 FLAC__crc8(const FLAC__byte *data, unsigned len)
  90939. {
  90940. FLAC__uint8 crc = 0;
  90941. while(len--)
  90942. crc = FLAC__crc8_table[crc ^ *data++];
  90943. return crc;
  90944. }
  90945. unsigned FLAC__crc16(const FLAC__byte *data, unsigned len)
  90946. {
  90947. unsigned crc = 0;
  90948. while(len--)
  90949. crc = ((crc<<8) ^ FLAC__crc16_table[(crc>>8) ^ *data++]) & 0xffff;
  90950. return crc;
  90951. }
  90952. #endif
  90953. /********* End of inlined file: crc.c *********/
  90954. /********* Start of inlined file: fixed.c *********/
  90955. /********* Start of inlined file: juce_FlacHeader.h *********/
  90956. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  90957. // tasks..
  90958. /********* Start of inlined file: juce_Config.h *********/
  90959. #ifndef __JUCE_CONFIG_JUCEHEADER__
  90960. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  90961. /*
  90962. This file contains macros that enable/disable various JUCE features.
  90963. */
  90964. /** The name of the namespace that all Juce classes and functions will be
  90965. put inside. If this is not defined, no namespace will be used.
  90966. */
  90967. #ifndef JUCE_NAMESPACE
  90968. #define JUCE_NAMESPACE juce
  90969. #endif
  90970. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  90971. but if you define this value, you can override this can force it to be true or
  90972. false.
  90973. */
  90974. #ifndef JUCE_FORCE_DEBUG
  90975. //#define JUCE_FORCE_DEBUG 1
  90976. #endif
  90977. /** If this flag is enabled, the the jassert and jassertfalse macros will
  90978. always use Logger::writeToLog() to write a message when an assertion happens.
  90979. Enabling it will also leave this turned on in release builds. When it's disabled,
  90980. however, the jassert and jassertfalse macros will not be compiled in a
  90981. release build.
  90982. @see jassert, jassertfalse, Logger
  90983. */
  90984. #ifndef JUCE_LOG_ASSERTIONS
  90985. // #define JUCE_LOG_ASSERTIONS 1
  90986. #endif
  90987. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  90988. which the ASIOAudioIODevice class can't be built. See the comments in the
  90989. ASIOAudioIODevice class's header file for more info about this.
  90990. (This only affects a Win32 build)
  90991. */
  90992. #ifndef JUCE_ASIO
  90993. #define JUCE_ASIO 1
  90994. #endif
  90995. /** Comment out this macro to disable building of ALSA device support on Linux.
  90996. */
  90997. #ifndef JUCE_ALSA
  90998. #define JUCE_ALSA 1
  90999. #endif
  91000. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  91001. have the SDK installed.
  91002. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  91003. classes will be unavailable.
  91004. On Windows, if you enable this, you'll need to have the QuickTime SDK
  91005. installed, and its header files will need to be on your include path.
  91006. */
  91007. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  91008. #define JUCE_QUICKTIME 1
  91009. #endif
  91010. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  91011. have the appropriate headers and libraries available. If it's not enabled, the
  91012. OpenGLComponent class will be unavailable.
  91013. */
  91014. #ifndef JUCE_OPENGL
  91015. #define JUCE_OPENGL 1
  91016. #endif
  91017. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  91018. If you're not going to need either of these formats, turn off the flags to
  91019. avoid bloating your codebase with them.
  91020. */
  91021. #ifndef JUCE_USE_FLAC
  91022. #define JUCE_USE_FLAC 1
  91023. #endif
  91024. #ifndef JUCE_USE_OGGVORBIS
  91025. #define JUCE_USE_OGGVORBIS 1
  91026. #endif
  91027. /** This flag lets you enable support for CD-burning. You might want to disable
  91028. it to build without the MS SDK under windows.
  91029. */
  91030. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  91031. #define JUCE_USE_CDBURNER 1
  91032. #endif
  91033. /** Enabling this macro means that all regions that get repainted will have a coloured
  91034. line drawn around them.
  91035. This is handy if you're trying to optimise drawing, because it lets you easily see
  91036. when anything is being repainted unnecessarily.
  91037. */
  91038. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  91039. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  91040. #endif
  91041. /** Enable this under Linux to use Xinerama for multi-monitor support.
  91042. */
  91043. #ifndef JUCE_USE_XINERAMA
  91044. #define JUCE_USE_XINERAMA 1
  91045. #endif
  91046. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  91047. */
  91048. #ifndef JUCE_USE_XSHM
  91049. #define JUCE_USE_XSHM 1
  91050. #endif
  91051. /** Enabling this builds support for VST audio plugins.
  91052. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  91053. */
  91054. #ifndef JUCE_PLUGINHOST_VST
  91055. // #define JUCE_PLUGINHOST_VST 1
  91056. #endif
  91057. /** Enabling this builds support for AudioUnit audio plugins.
  91058. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  91059. */
  91060. #ifndef JUCE_PLUGINHOST_AU
  91061. // #define JUCE_PLUGINHOST_AU 1
  91062. #endif
  91063. /** Disabling this will avoid linking to any UI code. This is handy for
  91064. writing command-line utilities, e.g. on linux boxes which don't have some
  91065. of the UI libraries installed.
  91066. (On mac and windows, this won't generally make much difference to the build).
  91067. */
  91068. #ifndef JUCE_BUILD_GUI_CLASSES
  91069. #define JUCE_BUILD_GUI_CLASSES 1
  91070. #endif
  91071. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  91072. */
  91073. #ifndef JUCE_WEB_BROWSER
  91074. #define JUCE_WEB_BROWSER 1
  91075. #endif
  91076. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  91077. codebase - you might need to use this if you're linking to some of these libraries
  91078. yourself.
  91079. */
  91080. #ifndef JUCE_INCLUDE_ZLIB_CODE
  91081. #define JUCE_INCLUDE_ZLIB_CODE 1
  91082. #endif
  91083. #ifndef JUCE_INCLUDE_FLAC_CODE
  91084. #define JUCE_INCLUDE_FLAC_CODE 1
  91085. #endif
  91086. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  91087. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  91088. #endif
  91089. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  91090. #define JUCE_INCLUDE_PNGLIB_CODE 1
  91091. #endif
  91092. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  91093. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  91094. #endif
  91095. /** Enable this to add extra memory-leak info to the new and delete operators.
  91096. (Currently, this only affects Windows builds in debug mode).
  91097. */
  91098. #ifndef JUCE_CHECK_MEMORY_LEAKS
  91099. #define JUCE_CHECK_MEMORY_LEAKS 1
  91100. #endif
  91101. /** Enable this to turn on juce's internal catching of exceptions.
  91102. Turning it off will avoid any exception catching. With it on, all exceptions
  91103. are passed to the JUCEApplication::unhandledException() callback for logging.
  91104. */
  91105. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  91106. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  91107. #endif
  91108. /** If this macro is set, the Juce String class will use unicode as its
  91109. internal representation. If it isn't set, it'll use ANSI.
  91110. */
  91111. #ifndef JUCE_STRINGS_ARE_UNICODE
  91112. #define JUCE_STRINGS_ARE_UNICODE 1
  91113. #endif
  91114. #endif
  91115. /********* End of inlined file: juce_Config.h *********/
  91116. #define VERSION "1.2.1"
  91117. #define FLAC__NO_DLL 1
  91118. #ifdef _MSC_VER
  91119. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91120. #endif
  91121. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91122. #define FLAC__SYS_DARWIN 1
  91123. #endif
  91124. /********* End of inlined file: juce_FlacHeader.h *********/
  91125. #if JUCE_USE_FLAC
  91126. #if HAVE_CONFIG_H
  91127. # include <config.h>
  91128. #endif
  91129. #include <math.h>
  91130. #include <string.h>
  91131. /********* Start of inlined file: fixed.h *********/
  91132. #ifndef FLAC__PRIVATE__FIXED_H
  91133. #define FLAC__PRIVATE__FIXED_H
  91134. #ifdef HAVE_CONFIG_H
  91135. #include <config.h>
  91136. #endif
  91137. /********* Start of inlined file: float.h *********/
  91138. #ifndef FLAC__PRIVATE__FLOAT_H
  91139. #define FLAC__PRIVATE__FLOAT_H
  91140. #ifdef HAVE_CONFIG_H
  91141. #include <config.h>
  91142. #endif
  91143. /*
  91144. * These typedefs make it easier to ensure that integer versions of
  91145. * the library really only contain integer operations. All the code
  91146. * in libFLAC should use FLAC__float and FLAC__double in place of
  91147. * float and double, and be protected by checks of the macro
  91148. * FLAC__INTEGER_ONLY_LIBRARY.
  91149. *
  91150. * FLAC__real is the basic floating point type used in LPC analysis.
  91151. */
  91152. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91153. typedef double FLAC__double;
  91154. typedef float FLAC__float;
  91155. /*
  91156. * WATCHOUT: changing FLAC__real will change the signatures of many
  91157. * functions that have assembly language equivalents and break them.
  91158. */
  91159. typedef float FLAC__real;
  91160. #else
  91161. /*
  91162. * The convention for FLAC__fixedpoint is to use the upper 16 bits
  91163. * for the integer part and lower 16 bits for the fractional part.
  91164. */
  91165. typedef FLAC__int32 FLAC__fixedpoint;
  91166. extern const FLAC__fixedpoint FLAC__FP_ZERO;
  91167. extern const FLAC__fixedpoint FLAC__FP_ONE_HALF;
  91168. extern const FLAC__fixedpoint FLAC__FP_ONE;
  91169. extern const FLAC__fixedpoint FLAC__FP_LN2;
  91170. extern const FLAC__fixedpoint FLAC__FP_E;
  91171. #define FLAC__fixedpoint_trunc(x) ((x)>>16)
  91172. #define FLAC__fixedpoint_mul(x, y) ( (FLAC__fixedpoint) ( ((FLAC__int64)(x)*(FLAC__int64)(y)) >> 16 ) )
  91173. #define FLAC__fixedpoint_div(x, y) ( (FLAC__fixedpoint) ( ( ((FLAC__int64)(x)<<32) / (FLAC__int64)(y) ) >> 16 ) )
  91174. /*
  91175. * FLAC__fixedpoint_log2()
  91176. * --------------------------------------------------------------------
  91177. * Returns the base-2 logarithm of the fixed-point number 'x' using an
  91178. * algorithm by Knuth for x >= 1.0
  91179. *
  91180. * 'fracbits' is the number of fractional bits of 'x'. 'fracbits' must
  91181. * be < 32 and evenly divisible by 4 (0 is OK but not very precise).
  91182. *
  91183. * 'precision' roughly limits the number of iterations that are done;
  91184. * use (unsigned)(-1) for maximum precision.
  91185. *
  91186. * If 'x' is less than one -- that is, x < (1<<fracbits) -- then this
  91187. * function will punt and return 0.
  91188. *
  91189. * The return value will also have 'fracbits' fractional bits.
  91190. */
  91191. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision);
  91192. #endif
  91193. #endif
  91194. /********* End of inlined file: float.h *********/
  91195. /********* Start of inlined file: format.h *********/
  91196. #ifndef FLAC__PRIVATE__FORMAT_H
  91197. #define FLAC__PRIVATE__FORMAT_H
  91198. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order);
  91199. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize);
  91200. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order);
  91201. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  91202. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object);
  91203. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order);
  91204. #endif
  91205. /********* End of inlined file: format.h *********/
  91206. /*
  91207. * FLAC__fixed_compute_best_predictor()
  91208. * --------------------------------------------------------------------
  91209. * Compute the best fixed predictor and the expected bits-per-sample
  91210. * of the residual signal for each order. The _wide() version uses
  91211. * 64-bit integers which is statistically necessary when bits-per-
  91212. * sample + log2(blocksize) > 30
  91213. *
  91214. * IN data[0,data_len-1]
  91215. * IN data_len
  91216. * OUT residual_bits_per_sample[0,FLAC__MAX_FIXED_ORDER]
  91217. */
  91218. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91219. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91220. # ifndef FLAC__NO_ASM
  91221. # ifdef FLAC__CPU_IA32
  91222. # ifdef FLAC__HAS_NASM
  91223. 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]);
  91224. # endif
  91225. # endif
  91226. # endif
  91227. 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]);
  91228. #else
  91229. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  91230. 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]);
  91231. #endif
  91232. /*
  91233. * FLAC__fixed_compute_residual()
  91234. * --------------------------------------------------------------------
  91235. * Compute the residual signal obtained from sutracting the predicted
  91236. * signal from the original.
  91237. *
  91238. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  91239. * IN data_len length of original signal
  91240. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  91241. * OUT residual[0,data_len-1] residual signal
  91242. */
  91243. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[]);
  91244. /*
  91245. * FLAC__fixed_restore_signal()
  91246. * --------------------------------------------------------------------
  91247. * Restore the original signal by summing the residual and the
  91248. * predictor.
  91249. *
  91250. * IN residual[0,data_len-1] residual signal
  91251. * IN data_len length of original signal
  91252. * IN order <= FLAC__MAX_FIXED_ORDER fixed-predictor order
  91253. * *** IMPORTANT: the caller must pass in the historical samples:
  91254. * IN data[-order,-1] previously-reconstructed historical samples
  91255. * OUT data[0,data_len-1] original signal
  91256. */
  91257. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[]);
  91258. #endif
  91259. /********* End of inlined file: fixed.h *********/
  91260. #ifndef M_LN2
  91261. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  91262. #define M_LN2 0.69314718055994530942
  91263. #endif
  91264. #ifdef min
  91265. #undef min
  91266. #endif
  91267. #define min(x,y) ((x) < (y)? (x) : (y))
  91268. #ifdef local_abs
  91269. #undef local_abs
  91270. #endif
  91271. #define local_abs(x) ((unsigned)((x)<0? -(x) : (x)))
  91272. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  91273. /* rbps stands for residual bits per sample
  91274. *
  91275. * (ln(2) * err)
  91276. * rbps = log (-----------)
  91277. * 2 ( n )
  91278. */
  91279. static FLAC__fixedpoint local__compute_rbps_integerized(FLAC__uint32 err, FLAC__uint32 n)
  91280. {
  91281. FLAC__uint32 rbps;
  91282. unsigned bits; /* the number of bits required to represent a number */
  91283. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  91284. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  91285. FLAC__ASSERT(err > 0);
  91286. FLAC__ASSERT(n > 0);
  91287. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  91288. if(err <= n)
  91289. return 0;
  91290. /*
  91291. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  91292. * These allow us later to know we won't lose too much precision in the
  91293. * fixed-point division (err<<fracbits)/n.
  91294. */
  91295. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2(err)+1);
  91296. err <<= fracbits;
  91297. err /= n;
  91298. /* err now holds err/n with fracbits fractional bits */
  91299. /*
  91300. * Whittle err down to 16 bits max. 16 significant bits is enough for
  91301. * our purposes.
  91302. */
  91303. FLAC__ASSERT(err > 0);
  91304. bits = FLAC__bitmath_ilog2(err)+1;
  91305. if(bits > 16) {
  91306. err >>= (bits-16);
  91307. fracbits -= (bits-16);
  91308. }
  91309. rbps = (FLAC__uint32)err;
  91310. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  91311. rbps *= FLAC__FP_LN2;
  91312. fracbits += 16;
  91313. FLAC__ASSERT(fracbits >= 0);
  91314. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  91315. {
  91316. const int f = fracbits & 3;
  91317. if(f) {
  91318. rbps >>= f;
  91319. fracbits -= f;
  91320. }
  91321. }
  91322. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  91323. if(rbps == 0)
  91324. return 0;
  91325. /*
  91326. * The return value must have 16 fractional bits. Since the whole part
  91327. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  91328. * must be >= -3, these assertion allows us to be able to shift rbps
  91329. * left if necessary to get 16 fracbits without losing any bits of the
  91330. * whole part of rbps.
  91331. *
  91332. * There is a slight chance due to accumulated error that the whole part
  91333. * will require 6 bits, so we use 6 in the assertion. Really though as
  91334. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  91335. */
  91336. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  91337. FLAC__ASSERT(fracbits >= -3);
  91338. /* now shift the decimal point into place */
  91339. if(fracbits < 16)
  91340. return rbps << (16-fracbits);
  91341. else if(fracbits > 16)
  91342. return rbps >> (fracbits-16);
  91343. else
  91344. return rbps;
  91345. }
  91346. static FLAC__fixedpoint local__compute_rbps_wide_integerized(FLAC__uint64 err, FLAC__uint32 n)
  91347. {
  91348. FLAC__uint32 rbps;
  91349. unsigned bits; /* the number of bits required to represent a number */
  91350. int fracbits; /* the number of bits of rbps that comprise the fractional part */
  91351. FLAC__ASSERT(sizeof(rbps) == sizeof(FLAC__fixedpoint));
  91352. FLAC__ASSERT(err > 0);
  91353. FLAC__ASSERT(n > 0);
  91354. FLAC__ASSERT(n <= FLAC__MAX_BLOCK_SIZE);
  91355. if(err <= n)
  91356. return 0;
  91357. /*
  91358. * The above two things tell us 1) n fits in 16 bits; 2) err/n > 1.
  91359. * These allow us later to know we won't lose too much precision in the
  91360. * fixed-point division (err<<fracbits)/n.
  91361. */
  91362. fracbits = (8*sizeof(err)) - (FLAC__bitmath_ilog2_wide(err)+1);
  91363. err <<= fracbits;
  91364. err /= n;
  91365. /* err now holds err/n with fracbits fractional bits */
  91366. /*
  91367. * Whittle err down to 16 bits max. 16 significant bits is enough for
  91368. * our purposes.
  91369. */
  91370. FLAC__ASSERT(err > 0);
  91371. bits = FLAC__bitmath_ilog2_wide(err)+1;
  91372. if(bits > 16) {
  91373. err >>= (bits-16);
  91374. fracbits -= (bits-16);
  91375. }
  91376. rbps = (FLAC__uint32)err;
  91377. /* Multiply by fixed-point version of ln(2), with 16 fractional bits */
  91378. rbps *= FLAC__FP_LN2;
  91379. fracbits += 16;
  91380. FLAC__ASSERT(fracbits >= 0);
  91381. /* FLAC__fixedpoint_log2 requires fracbits%4 to be 0 */
  91382. {
  91383. const int f = fracbits & 3;
  91384. if(f) {
  91385. rbps >>= f;
  91386. fracbits -= f;
  91387. }
  91388. }
  91389. rbps = FLAC__fixedpoint_log2(rbps, fracbits, (unsigned)(-1));
  91390. if(rbps == 0)
  91391. return 0;
  91392. /*
  91393. * The return value must have 16 fractional bits. Since the whole part
  91394. * of the base-2 log of a 32 bit number must fit in 5 bits, and fracbits
  91395. * must be >= -3, these assertion allows us to be able to shift rbps
  91396. * left if necessary to get 16 fracbits without losing any bits of the
  91397. * whole part of rbps.
  91398. *
  91399. * There is a slight chance due to accumulated error that the whole part
  91400. * will require 6 bits, so we use 6 in the assertion. Really though as
  91401. * long as it fits in 13 bits (32 - (16 - (-3))) we are fine.
  91402. */
  91403. FLAC__ASSERT((int)FLAC__bitmath_ilog2(rbps)+1 <= fracbits + 6);
  91404. FLAC__ASSERT(fracbits >= -3);
  91405. /* now shift the decimal point into place */
  91406. if(fracbits < 16)
  91407. return rbps << (16-fracbits);
  91408. else if(fracbits > 16)
  91409. return rbps >> (fracbits-16);
  91410. else
  91411. return rbps;
  91412. }
  91413. #endif
  91414. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91415. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91416. #else
  91417. unsigned FLAC__fixed_compute_best_predictor(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1])
  91418. #endif
  91419. {
  91420. FLAC__int32 last_error_0 = data[-1];
  91421. FLAC__int32 last_error_1 = data[-1] - data[-2];
  91422. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  91423. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  91424. FLAC__int32 error, save;
  91425. FLAC__uint32 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  91426. unsigned i, order;
  91427. for(i = 0; i < data_len; i++) {
  91428. error = data[i] ; total_error_0 += local_abs(error); save = error;
  91429. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  91430. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  91431. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  91432. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  91433. }
  91434. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  91435. order = 0;
  91436. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  91437. order = 1;
  91438. else if(total_error_2 < min(total_error_3, total_error_4))
  91439. order = 2;
  91440. else if(total_error_3 < total_error_4)
  91441. order = 3;
  91442. else
  91443. order = 4;
  91444. /* Estimate the expected number of bits per residual signal sample. */
  91445. /* 'total_error*' is linearly related to the variance of the residual */
  91446. /* signal, so we use it directly to compute E(|x|) */
  91447. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  91448. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  91449. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  91450. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  91451. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  91452. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91453. 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);
  91454. 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);
  91455. 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);
  91456. 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);
  91457. 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);
  91458. #else
  91459. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_integerized(total_error_0, data_len) : 0;
  91460. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_integerized(total_error_1, data_len) : 0;
  91461. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_integerized(total_error_2, data_len) : 0;
  91462. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_integerized(total_error_3, data_len) : 0;
  91463. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_integerized(total_error_4, data_len) : 0;
  91464. #endif
  91465. return order;
  91466. }
  91467. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91468. 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])
  91469. #else
  91470. 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])
  91471. #endif
  91472. {
  91473. FLAC__int32 last_error_0 = data[-1];
  91474. FLAC__int32 last_error_1 = data[-1] - data[-2];
  91475. FLAC__int32 last_error_2 = last_error_1 - (data[-2] - data[-3]);
  91476. FLAC__int32 last_error_3 = last_error_2 - (data[-2] - 2*data[-3] + data[-4]);
  91477. FLAC__int32 error, save;
  91478. /* total_error_* are 64-bits to avoid overflow when encoding
  91479. * erratic signals when the bits-per-sample and blocksize are
  91480. * large.
  91481. */
  91482. FLAC__uint64 total_error_0 = 0, total_error_1 = 0, total_error_2 = 0, total_error_3 = 0, total_error_4 = 0;
  91483. unsigned i, order;
  91484. for(i = 0; i < data_len; i++) {
  91485. error = data[i] ; total_error_0 += local_abs(error); save = error;
  91486. error -= last_error_0; total_error_1 += local_abs(error); last_error_0 = save; save = error;
  91487. error -= last_error_1; total_error_2 += local_abs(error); last_error_1 = save; save = error;
  91488. error -= last_error_2; total_error_3 += local_abs(error); last_error_2 = save; save = error;
  91489. error -= last_error_3; total_error_4 += local_abs(error); last_error_3 = save;
  91490. }
  91491. if(total_error_0 < min(min(min(total_error_1, total_error_2), total_error_3), total_error_4))
  91492. order = 0;
  91493. else if(total_error_1 < min(min(total_error_2, total_error_3), total_error_4))
  91494. order = 1;
  91495. else if(total_error_2 < min(total_error_3, total_error_4))
  91496. order = 2;
  91497. else if(total_error_3 < total_error_4)
  91498. order = 3;
  91499. else
  91500. order = 4;
  91501. /* Estimate the expected number of bits per residual signal sample. */
  91502. /* 'total_error*' is linearly related to the variance of the residual */
  91503. /* signal, so we use it directly to compute E(|x|) */
  91504. FLAC__ASSERT(data_len > 0 || total_error_0 == 0);
  91505. FLAC__ASSERT(data_len > 0 || total_error_1 == 0);
  91506. FLAC__ASSERT(data_len > 0 || total_error_2 == 0);
  91507. FLAC__ASSERT(data_len > 0 || total_error_3 == 0);
  91508. FLAC__ASSERT(data_len > 0 || total_error_4 == 0);
  91509. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  91510. #if defined _MSC_VER || defined __MINGW32__
  91511. /* with MSVC you have to spoon feed it the casting */
  91512. 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);
  91513. 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);
  91514. 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);
  91515. 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);
  91516. 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);
  91517. #else
  91518. 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);
  91519. 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);
  91520. 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);
  91521. 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);
  91522. 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);
  91523. #endif
  91524. #else
  91525. residual_bits_per_sample[0] = (total_error_0 > 0) ? local__compute_rbps_wide_integerized(total_error_0, data_len) : 0;
  91526. residual_bits_per_sample[1] = (total_error_1 > 0) ? local__compute_rbps_wide_integerized(total_error_1, data_len) : 0;
  91527. residual_bits_per_sample[2] = (total_error_2 > 0) ? local__compute_rbps_wide_integerized(total_error_2, data_len) : 0;
  91528. residual_bits_per_sample[3] = (total_error_3 > 0) ? local__compute_rbps_wide_integerized(total_error_3, data_len) : 0;
  91529. residual_bits_per_sample[4] = (total_error_4 > 0) ? local__compute_rbps_wide_integerized(total_error_4, data_len) : 0;
  91530. #endif
  91531. return order;
  91532. }
  91533. void FLAC__fixed_compute_residual(const FLAC__int32 data[], unsigned data_len, unsigned order, FLAC__int32 residual[])
  91534. {
  91535. const int idata_len = (int)data_len;
  91536. int i;
  91537. switch(order) {
  91538. case 0:
  91539. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  91540. memcpy(residual, data, sizeof(residual[0])*data_len);
  91541. break;
  91542. case 1:
  91543. for(i = 0; i < idata_len; i++)
  91544. residual[i] = data[i] - data[i-1];
  91545. break;
  91546. case 2:
  91547. for(i = 0; i < idata_len; i++)
  91548. #if 1 /* OPT: may be faster with some compilers on some systems */
  91549. residual[i] = data[i] - (data[i-1] << 1) + data[i-2];
  91550. #else
  91551. residual[i] = data[i] - 2*data[i-1] + data[i-2];
  91552. #endif
  91553. break;
  91554. case 3:
  91555. for(i = 0; i < idata_len; i++)
  91556. #if 1 /* OPT: may be faster with some compilers on some systems */
  91557. residual[i] = data[i] - (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) - data[i-3];
  91558. #else
  91559. residual[i] = data[i] - 3*data[i-1] + 3*data[i-2] - data[i-3];
  91560. #endif
  91561. break;
  91562. case 4:
  91563. for(i = 0; i < idata_len; i++)
  91564. #if 1 /* OPT: may be faster with some compilers on some systems */
  91565. residual[i] = data[i] - ((data[i-1]+data[i-3])<<2) + ((data[i-2]<<2) + (data[i-2]<<1)) + data[i-4];
  91566. #else
  91567. residual[i] = data[i] - 4*data[i-1] + 6*data[i-2] - 4*data[i-3] + data[i-4];
  91568. #endif
  91569. break;
  91570. default:
  91571. FLAC__ASSERT(0);
  91572. }
  91573. }
  91574. void FLAC__fixed_restore_signal(const FLAC__int32 residual[], unsigned data_len, unsigned order, FLAC__int32 data[])
  91575. {
  91576. int i, idata_len = (int)data_len;
  91577. switch(order) {
  91578. case 0:
  91579. FLAC__ASSERT(sizeof(residual[0]) == sizeof(data[0]));
  91580. memcpy(data, residual, sizeof(residual[0])*data_len);
  91581. break;
  91582. case 1:
  91583. for(i = 0; i < idata_len; i++)
  91584. data[i] = residual[i] + data[i-1];
  91585. break;
  91586. case 2:
  91587. for(i = 0; i < idata_len; i++)
  91588. #if 1 /* OPT: may be faster with some compilers on some systems */
  91589. data[i] = residual[i] + (data[i-1]<<1) - data[i-2];
  91590. #else
  91591. data[i] = residual[i] + 2*data[i-1] - data[i-2];
  91592. #endif
  91593. break;
  91594. case 3:
  91595. for(i = 0; i < idata_len; i++)
  91596. #if 1 /* OPT: may be faster with some compilers on some systems */
  91597. data[i] = residual[i] + (((data[i-1]-data[i-2])<<1) + (data[i-1]-data[i-2])) + data[i-3];
  91598. #else
  91599. data[i] = residual[i] + 3*data[i-1] - 3*data[i-2] + data[i-3];
  91600. #endif
  91601. break;
  91602. case 4:
  91603. for(i = 0; i < idata_len; i++)
  91604. #if 1 /* OPT: may be faster with some compilers on some systems */
  91605. data[i] = residual[i] + ((data[i-1]+data[i-3])<<2) - ((data[i-2]<<2) + (data[i-2]<<1)) - data[i-4];
  91606. #else
  91607. data[i] = residual[i] + 4*data[i-1] - 6*data[i-2] + 4*data[i-3] - data[i-4];
  91608. #endif
  91609. break;
  91610. default:
  91611. FLAC__ASSERT(0);
  91612. }
  91613. }
  91614. #endif
  91615. /********* End of inlined file: fixed.c *********/
  91616. /********* Start of inlined file: float.c *********/
  91617. /********* Start of inlined file: juce_FlacHeader.h *********/
  91618. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  91619. // tasks..
  91620. /********* Start of inlined file: juce_Config.h *********/
  91621. #ifndef __JUCE_CONFIG_JUCEHEADER__
  91622. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  91623. /*
  91624. This file contains macros that enable/disable various JUCE features.
  91625. */
  91626. /** The name of the namespace that all Juce classes and functions will be
  91627. put inside. If this is not defined, no namespace will be used.
  91628. */
  91629. #ifndef JUCE_NAMESPACE
  91630. #define JUCE_NAMESPACE juce
  91631. #endif
  91632. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  91633. but if you define this value, you can override this can force it to be true or
  91634. false.
  91635. */
  91636. #ifndef JUCE_FORCE_DEBUG
  91637. //#define JUCE_FORCE_DEBUG 1
  91638. #endif
  91639. /** If this flag is enabled, the the jassert and jassertfalse macros will
  91640. always use Logger::writeToLog() to write a message when an assertion happens.
  91641. Enabling it will also leave this turned on in release builds. When it's disabled,
  91642. however, the jassert and jassertfalse macros will not be compiled in a
  91643. release build.
  91644. @see jassert, jassertfalse, Logger
  91645. */
  91646. #ifndef JUCE_LOG_ASSERTIONS
  91647. // #define JUCE_LOG_ASSERTIONS 1
  91648. #endif
  91649. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  91650. which the ASIOAudioIODevice class can't be built. See the comments in the
  91651. ASIOAudioIODevice class's header file for more info about this.
  91652. (This only affects a Win32 build)
  91653. */
  91654. #ifndef JUCE_ASIO
  91655. #define JUCE_ASIO 1
  91656. #endif
  91657. /** Comment out this macro to disable building of ALSA device support on Linux.
  91658. */
  91659. #ifndef JUCE_ALSA
  91660. #define JUCE_ALSA 1
  91661. #endif
  91662. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  91663. have the SDK installed.
  91664. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  91665. classes will be unavailable.
  91666. On Windows, if you enable this, you'll need to have the QuickTime SDK
  91667. installed, and its header files will need to be on your include path.
  91668. */
  91669. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  91670. #define JUCE_QUICKTIME 1
  91671. #endif
  91672. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  91673. have the appropriate headers and libraries available. If it's not enabled, the
  91674. OpenGLComponent class will be unavailable.
  91675. */
  91676. #ifndef JUCE_OPENGL
  91677. #define JUCE_OPENGL 1
  91678. #endif
  91679. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  91680. If you're not going to need either of these formats, turn off the flags to
  91681. avoid bloating your codebase with them.
  91682. */
  91683. #ifndef JUCE_USE_FLAC
  91684. #define JUCE_USE_FLAC 1
  91685. #endif
  91686. #ifndef JUCE_USE_OGGVORBIS
  91687. #define JUCE_USE_OGGVORBIS 1
  91688. #endif
  91689. /** This flag lets you enable support for CD-burning. You might want to disable
  91690. it to build without the MS SDK under windows.
  91691. */
  91692. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  91693. #define JUCE_USE_CDBURNER 1
  91694. #endif
  91695. /** Enabling this macro means that all regions that get repainted will have a coloured
  91696. line drawn around them.
  91697. This is handy if you're trying to optimise drawing, because it lets you easily see
  91698. when anything is being repainted unnecessarily.
  91699. */
  91700. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  91701. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  91702. #endif
  91703. /** Enable this under Linux to use Xinerama for multi-monitor support.
  91704. */
  91705. #ifndef JUCE_USE_XINERAMA
  91706. #define JUCE_USE_XINERAMA 1
  91707. #endif
  91708. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  91709. */
  91710. #ifndef JUCE_USE_XSHM
  91711. #define JUCE_USE_XSHM 1
  91712. #endif
  91713. /** Enabling this builds support for VST audio plugins.
  91714. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  91715. */
  91716. #ifndef JUCE_PLUGINHOST_VST
  91717. // #define JUCE_PLUGINHOST_VST 1
  91718. #endif
  91719. /** Enabling this builds support for AudioUnit audio plugins.
  91720. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  91721. */
  91722. #ifndef JUCE_PLUGINHOST_AU
  91723. // #define JUCE_PLUGINHOST_AU 1
  91724. #endif
  91725. /** Disabling this will avoid linking to any UI code. This is handy for
  91726. writing command-line utilities, e.g. on linux boxes which don't have some
  91727. of the UI libraries installed.
  91728. (On mac and windows, this won't generally make much difference to the build).
  91729. */
  91730. #ifndef JUCE_BUILD_GUI_CLASSES
  91731. #define JUCE_BUILD_GUI_CLASSES 1
  91732. #endif
  91733. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  91734. */
  91735. #ifndef JUCE_WEB_BROWSER
  91736. #define JUCE_WEB_BROWSER 1
  91737. #endif
  91738. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  91739. codebase - you might need to use this if you're linking to some of these libraries
  91740. yourself.
  91741. */
  91742. #ifndef JUCE_INCLUDE_ZLIB_CODE
  91743. #define JUCE_INCLUDE_ZLIB_CODE 1
  91744. #endif
  91745. #ifndef JUCE_INCLUDE_FLAC_CODE
  91746. #define JUCE_INCLUDE_FLAC_CODE 1
  91747. #endif
  91748. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  91749. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  91750. #endif
  91751. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  91752. #define JUCE_INCLUDE_PNGLIB_CODE 1
  91753. #endif
  91754. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  91755. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  91756. #endif
  91757. /** Enable this to add extra memory-leak info to the new and delete operators.
  91758. (Currently, this only affects Windows builds in debug mode).
  91759. */
  91760. #ifndef JUCE_CHECK_MEMORY_LEAKS
  91761. #define JUCE_CHECK_MEMORY_LEAKS 1
  91762. #endif
  91763. /** Enable this to turn on juce's internal catching of exceptions.
  91764. Turning it off will avoid any exception catching. With it on, all exceptions
  91765. are passed to the JUCEApplication::unhandledException() callback for logging.
  91766. */
  91767. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  91768. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  91769. #endif
  91770. /** If this macro is set, the Juce String class will use unicode as its
  91771. internal representation. If it isn't set, it'll use ANSI.
  91772. */
  91773. #ifndef JUCE_STRINGS_ARE_UNICODE
  91774. #define JUCE_STRINGS_ARE_UNICODE 1
  91775. #endif
  91776. #endif
  91777. /********* End of inlined file: juce_Config.h *********/
  91778. #define VERSION "1.2.1"
  91779. #define FLAC__NO_DLL 1
  91780. #ifdef _MSC_VER
  91781. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  91782. #endif
  91783. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  91784. #define FLAC__SYS_DARWIN 1
  91785. #endif
  91786. /********* End of inlined file: juce_FlacHeader.h *********/
  91787. #if JUCE_USE_FLAC
  91788. #if HAVE_CONFIG_H
  91789. # include <config.h>
  91790. #endif
  91791. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  91792. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  91793. #ifdef _MSC_VER
  91794. #define FLAC__U64L(x) x
  91795. #else
  91796. #define FLAC__U64L(x) x##LLU
  91797. #endif
  91798. const FLAC__fixedpoint FLAC__FP_ZERO = 0;
  91799. const FLAC__fixedpoint FLAC__FP_ONE_HALF = 0x00008000;
  91800. const FLAC__fixedpoint FLAC__FP_ONE = 0x00010000;
  91801. const FLAC__fixedpoint FLAC__FP_LN2 = 45426;
  91802. const FLAC__fixedpoint FLAC__FP_E = 178145;
  91803. /* Lookup tables for Knuth's logarithm algorithm */
  91804. #define LOG2_LOOKUP_PRECISION 16
  91805. static const FLAC__uint32 log2_lookup[][LOG2_LOOKUP_PRECISION] = {
  91806. {
  91807. /*
  91808. * 0 fraction bits
  91809. */
  91810. /* undefined */ 0x00000000,
  91811. /* lg(2/1) = */ 0x00000001,
  91812. /* lg(4/3) = */ 0x00000000,
  91813. /* lg(8/7) = */ 0x00000000,
  91814. /* lg(16/15) = */ 0x00000000,
  91815. /* lg(32/31) = */ 0x00000000,
  91816. /* lg(64/63) = */ 0x00000000,
  91817. /* lg(128/127) = */ 0x00000000,
  91818. /* lg(256/255) = */ 0x00000000,
  91819. /* lg(512/511) = */ 0x00000000,
  91820. /* lg(1024/1023) = */ 0x00000000,
  91821. /* lg(2048/2047) = */ 0x00000000,
  91822. /* lg(4096/4095) = */ 0x00000000,
  91823. /* lg(8192/8191) = */ 0x00000000,
  91824. /* lg(16384/16383) = */ 0x00000000,
  91825. /* lg(32768/32767) = */ 0x00000000
  91826. },
  91827. {
  91828. /*
  91829. * 4 fraction bits
  91830. */
  91831. /* undefined */ 0x00000000,
  91832. /* lg(2/1) = */ 0x00000010,
  91833. /* lg(4/3) = */ 0x00000007,
  91834. /* lg(8/7) = */ 0x00000003,
  91835. /* lg(16/15) = */ 0x00000001,
  91836. /* lg(32/31) = */ 0x00000001,
  91837. /* lg(64/63) = */ 0x00000000,
  91838. /* lg(128/127) = */ 0x00000000,
  91839. /* lg(256/255) = */ 0x00000000,
  91840. /* lg(512/511) = */ 0x00000000,
  91841. /* lg(1024/1023) = */ 0x00000000,
  91842. /* lg(2048/2047) = */ 0x00000000,
  91843. /* lg(4096/4095) = */ 0x00000000,
  91844. /* lg(8192/8191) = */ 0x00000000,
  91845. /* lg(16384/16383) = */ 0x00000000,
  91846. /* lg(32768/32767) = */ 0x00000000
  91847. },
  91848. {
  91849. /*
  91850. * 8 fraction bits
  91851. */
  91852. /* undefined */ 0x00000000,
  91853. /* lg(2/1) = */ 0x00000100,
  91854. /* lg(4/3) = */ 0x0000006a,
  91855. /* lg(8/7) = */ 0x00000031,
  91856. /* lg(16/15) = */ 0x00000018,
  91857. /* lg(32/31) = */ 0x0000000c,
  91858. /* lg(64/63) = */ 0x00000006,
  91859. /* lg(128/127) = */ 0x00000003,
  91860. /* lg(256/255) = */ 0x00000001,
  91861. /* lg(512/511) = */ 0x00000001,
  91862. /* lg(1024/1023) = */ 0x00000000,
  91863. /* lg(2048/2047) = */ 0x00000000,
  91864. /* lg(4096/4095) = */ 0x00000000,
  91865. /* lg(8192/8191) = */ 0x00000000,
  91866. /* lg(16384/16383) = */ 0x00000000,
  91867. /* lg(32768/32767) = */ 0x00000000
  91868. },
  91869. {
  91870. /*
  91871. * 12 fraction bits
  91872. */
  91873. /* undefined */ 0x00000000,
  91874. /* lg(2/1) = */ 0x00001000,
  91875. /* lg(4/3) = */ 0x000006a4,
  91876. /* lg(8/7) = */ 0x00000315,
  91877. /* lg(16/15) = */ 0x0000017d,
  91878. /* lg(32/31) = */ 0x000000bc,
  91879. /* lg(64/63) = */ 0x0000005d,
  91880. /* lg(128/127) = */ 0x0000002e,
  91881. /* lg(256/255) = */ 0x00000017,
  91882. /* lg(512/511) = */ 0x0000000c,
  91883. /* lg(1024/1023) = */ 0x00000006,
  91884. /* lg(2048/2047) = */ 0x00000003,
  91885. /* lg(4096/4095) = */ 0x00000001,
  91886. /* lg(8192/8191) = */ 0x00000001,
  91887. /* lg(16384/16383) = */ 0x00000000,
  91888. /* lg(32768/32767) = */ 0x00000000
  91889. },
  91890. {
  91891. /*
  91892. * 16 fraction bits
  91893. */
  91894. /* undefined */ 0x00000000,
  91895. /* lg(2/1) = */ 0x00010000,
  91896. /* lg(4/3) = */ 0x00006a40,
  91897. /* lg(8/7) = */ 0x00003151,
  91898. /* lg(16/15) = */ 0x000017d6,
  91899. /* lg(32/31) = */ 0x00000bba,
  91900. /* lg(64/63) = */ 0x000005d1,
  91901. /* lg(128/127) = */ 0x000002e6,
  91902. /* lg(256/255) = */ 0x00000172,
  91903. /* lg(512/511) = */ 0x000000b9,
  91904. /* lg(1024/1023) = */ 0x0000005c,
  91905. /* lg(2048/2047) = */ 0x0000002e,
  91906. /* lg(4096/4095) = */ 0x00000017,
  91907. /* lg(8192/8191) = */ 0x0000000c,
  91908. /* lg(16384/16383) = */ 0x00000006,
  91909. /* lg(32768/32767) = */ 0x00000003
  91910. },
  91911. {
  91912. /*
  91913. * 20 fraction bits
  91914. */
  91915. /* undefined */ 0x00000000,
  91916. /* lg(2/1) = */ 0x00100000,
  91917. /* lg(4/3) = */ 0x0006a3fe,
  91918. /* lg(8/7) = */ 0x00031513,
  91919. /* lg(16/15) = */ 0x00017d60,
  91920. /* lg(32/31) = */ 0x0000bb9d,
  91921. /* lg(64/63) = */ 0x00005d10,
  91922. /* lg(128/127) = */ 0x00002e59,
  91923. /* lg(256/255) = */ 0x00001721,
  91924. /* lg(512/511) = */ 0x00000b8e,
  91925. /* lg(1024/1023) = */ 0x000005c6,
  91926. /* lg(2048/2047) = */ 0x000002e3,
  91927. /* lg(4096/4095) = */ 0x00000171,
  91928. /* lg(8192/8191) = */ 0x000000b9,
  91929. /* lg(16384/16383) = */ 0x0000005c,
  91930. /* lg(32768/32767) = */ 0x0000002e
  91931. },
  91932. {
  91933. /*
  91934. * 24 fraction bits
  91935. */
  91936. /* undefined */ 0x00000000,
  91937. /* lg(2/1) = */ 0x01000000,
  91938. /* lg(4/3) = */ 0x006a3fe6,
  91939. /* lg(8/7) = */ 0x00315130,
  91940. /* lg(16/15) = */ 0x0017d605,
  91941. /* lg(32/31) = */ 0x000bb9ca,
  91942. /* lg(64/63) = */ 0x0005d0fc,
  91943. /* lg(128/127) = */ 0x0002e58f,
  91944. /* lg(256/255) = */ 0x0001720e,
  91945. /* lg(512/511) = */ 0x0000b8d8,
  91946. /* lg(1024/1023) = */ 0x00005c61,
  91947. /* lg(2048/2047) = */ 0x00002e2d,
  91948. /* lg(4096/4095) = */ 0x00001716,
  91949. /* lg(8192/8191) = */ 0x00000b8b,
  91950. /* lg(16384/16383) = */ 0x000005c5,
  91951. /* lg(32768/32767) = */ 0x000002e3
  91952. },
  91953. {
  91954. /*
  91955. * 28 fraction bits
  91956. */
  91957. /* undefined */ 0x00000000,
  91958. /* lg(2/1) = */ 0x10000000,
  91959. /* lg(4/3) = */ 0x06a3fe5c,
  91960. /* lg(8/7) = */ 0x03151301,
  91961. /* lg(16/15) = */ 0x017d6049,
  91962. /* lg(32/31) = */ 0x00bb9ca6,
  91963. /* lg(64/63) = */ 0x005d0fba,
  91964. /* lg(128/127) = */ 0x002e58f7,
  91965. /* lg(256/255) = */ 0x001720da,
  91966. /* lg(512/511) = */ 0x000b8d87,
  91967. /* lg(1024/1023) = */ 0x0005c60b,
  91968. /* lg(2048/2047) = */ 0x0002e2d7,
  91969. /* lg(4096/4095) = */ 0x00017160,
  91970. /* lg(8192/8191) = */ 0x0000b8ad,
  91971. /* lg(16384/16383) = */ 0x00005c56,
  91972. /* lg(32768/32767) = */ 0x00002e2b
  91973. }
  91974. };
  91975. #if 0
  91976. static const FLAC__uint64 log2_lookup_wide[] = {
  91977. {
  91978. /*
  91979. * 32 fraction bits
  91980. */
  91981. /* undefined */ 0x00000000,
  91982. /* lg(2/1) = */ FLAC__U64L(0x100000000),
  91983. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c6),
  91984. /* lg(8/7) = */ FLAC__U64L(0x31513015),
  91985. /* lg(16/15) = */ FLAC__U64L(0x17d60497),
  91986. /* lg(32/31) = */ FLAC__U64L(0x0bb9ca65),
  91987. /* lg(64/63) = */ FLAC__U64L(0x05d0fba2),
  91988. /* lg(128/127) = */ FLAC__U64L(0x02e58f74),
  91989. /* lg(256/255) = */ FLAC__U64L(0x01720d9c),
  91990. /* lg(512/511) = */ FLAC__U64L(0x00b8d875),
  91991. /* lg(1024/1023) = */ FLAC__U64L(0x005c60aa),
  91992. /* lg(2048/2047) = */ FLAC__U64L(0x002e2d72),
  91993. /* lg(4096/4095) = */ FLAC__U64L(0x00171600),
  91994. /* lg(8192/8191) = */ FLAC__U64L(0x000b8ad2),
  91995. /* lg(16384/16383) = */ FLAC__U64L(0x0005c55d),
  91996. /* lg(32768/32767) = */ FLAC__U64L(0x0002e2ac)
  91997. },
  91998. {
  91999. /*
  92000. * 48 fraction bits
  92001. */
  92002. /* undefined */ 0x00000000,
  92003. /* lg(2/1) = */ FLAC__U64L(0x1000000000000),
  92004. /* lg(4/3) = */ FLAC__U64L(0x6a3fe5c60429),
  92005. /* lg(8/7) = */ FLAC__U64L(0x315130157f7a),
  92006. /* lg(16/15) = */ FLAC__U64L(0x17d60496cfbb),
  92007. /* lg(32/31) = */ FLAC__U64L(0xbb9ca64ecac),
  92008. /* lg(64/63) = */ FLAC__U64L(0x5d0fba187cd),
  92009. /* lg(128/127) = */ FLAC__U64L(0x2e58f7441ee),
  92010. /* lg(256/255) = */ FLAC__U64L(0x1720d9c06a8),
  92011. /* lg(512/511) = */ FLAC__U64L(0xb8d8752173),
  92012. /* lg(1024/1023) = */ FLAC__U64L(0x5c60aa252e),
  92013. /* lg(2048/2047) = */ FLAC__U64L(0x2e2d71b0d8),
  92014. /* lg(4096/4095) = */ FLAC__U64L(0x1716001719),
  92015. /* lg(8192/8191) = */ FLAC__U64L(0xb8ad1de1b),
  92016. /* lg(16384/16383) = */ FLAC__U64L(0x5c55d640d),
  92017. /* lg(32768/32767) = */ FLAC__U64L(0x2e2abcf52)
  92018. }
  92019. };
  92020. #endif
  92021. FLAC__uint32 FLAC__fixedpoint_log2(FLAC__uint32 x, unsigned fracbits, unsigned precision)
  92022. {
  92023. const FLAC__uint32 ONE = (1u << fracbits);
  92024. const FLAC__uint32 *table = log2_lookup[fracbits >> 2];
  92025. FLAC__ASSERT(fracbits < 32);
  92026. FLAC__ASSERT((fracbits & 0x3) == 0);
  92027. if(x < ONE)
  92028. return 0;
  92029. if(precision > LOG2_LOOKUP_PRECISION)
  92030. precision = LOG2_LOOKUP_PRECISION;
  92031. /* Knuth's algorithm for computing logarithms, optimized for base-2 with lookup tables */
  92032. {
  92033. FLAC__uint32 y = 0;
  92034. FLAC__uint32 z = x >> 1, k = 1;
  92035. while (x > ONE && k < precision) {
  92036. if (x - z >= ONE) {
  92037. x -= z;
  92038. z = x >> k;
  92039. y += table[k];
  92040. }
  92041. else {
  92042. z >>= 1;
  92043. k++;
  92044. }
  92045. }
  92046. return y;
  92047. }
  92048. }
  92049. #endif /* defined FLAC__INTEGER_ONLY_LIBRARY */
  92050. #endif
  92051. /********* End of inlined file: float.c *********/
  92052. /********* Start of inlined file: format.c *********/
  92053. /********* Start of inlined file: juce_FlacHeader.h *********/
  92054. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92055. // tasks..
  92056. /********* Start of inlined file: juce_Config.h *********/
  92057. #ifndef __JUCE_CONFIG_JUCEHEADER__
  92058. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  92059. /*
  92060. This file contains macros that enable/disable various JUCE features.
  92061. */
  92062. /** The name of the namespace that all Juce classes and functions will be
  92063. put inside. If this is not defined, no namespace will be used.
  92064. */
  92065. #ifndef JUCE_NAMESPACE
  92066. #define JUCE_NAMESPACE juce
  92067. #endif
  92068. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  92069. but if you define this value, you can override this can force it to be true or
  92070. false.
  92071. */
  92072. #ifndef JUCE_FORCE_DEBUG
  92073. //#define JUCE_FORCE_DEBUG 1
  92074. #endif
  92075. /** If this flag is enabled, the the jassert and jassertfalse macros will
  92076. always use Logger::writeToLog() to write a message when an assertion happens.
  92077. Enabling it will also leave this turned on in release builds. When it's disabled,
  92078. however, the jassert and jassertfalse macros will not be compiled in a
  92079. release build.
  92080. @see jassert, jassertfalse, Logger
  92081. */
  92082. #ifndef JUCE_LOG_ASSERTIONS
  92083. // #define JUCE_LOG_ASSERTIONS 1
  92084. #endif
  92085. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  92086. which the ASIOAudioIODevice class can't be built. See the comments in the
  92087. ASIOAudioIODevice class's header file for more info about this.
  92088. (This only affects a Win32 build)
  92089. */
  92090. #ifndef JUCE_ASIO
  92091. #define JUCE_ASIO 1
  92092. #endif
  92093. /** Comment out this macro to disable building of ALSA device support on Linux.
  92094. */
  92095. #ifndef JUCE_ALSA
  92096. #define JUCE_ALSA 1
  92097. #endif
  92098. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  92099. have the SDK installed.
  92100. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  92101. classes will be unavailable.
  92102. On Windows, if you enable this, you'll need to have the QuickTime SDK
  92103. installed, and its header files will need to be on your include path.
  92104. */
  92105. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  92106. #define JUCE_QUICKTIME 1
  92107. #endif
  92108. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  92109. have the appropriate headers and libraries available. If it's not enabled, the
  92110. OpenGLComponent class will be unavailable.
  92111. */
  92112. #ifndef JUCE_OPENGL
  92113. #define JUCE_OPENGL 1
  92114. #endif
  92115. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  92116. If you're not going to need either of these formats, turn off the flags to
  92117. avoid bloating your codebase with them.
  92118. */
  92119. #ifndef JUCE_USE_FLAC
  92120. #define JUCE_USE_FLAC 1
  92121. #endif
  92122. #ifndef JUCE_USE_OGGVORBIS
  92123. #define JUCE_USE_OGGVORBIS 1
  92124. #endif
  92125. /** This flag lets you enable support for CD-burning. You might want to disable
  92126. it to build without the MS SDK under windows.
  92127. */
  92128. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  92129. #define JUCE_USE_CDBURNER 1
  92130. #endif
  92131. /** Enabling this macro means that all regions that get repainted will have a coloured
  92132. line drawn around them.
  92133. This is handy if you're trying to optimise drawing, because it lets you easily see
  92134. when anything is being repainted unnecessarily.
  92135. */
  92136. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  92137. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  92138. #endif
  92139. /** Enable this under Linux to use Xinerama for multi-monitor support.
  92140. */
  92141. #ifndef JUCE_USE_XINERAMA
  92142. #define JUCE_USE_XINERAMA 1
  92143. #endif
  92144. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  92145. */
  92146. #ifndef JUCE_USE_XSHM
  92147. #define JUCE_USE_XSHM 1
  92148. #endif
  92149. /** Enabling this builds support for VST audio plugins.
  92150. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  92151. */
  92152. #ifndef JUCE_PLUGINHOST_VST
  92153. // #define JUCE_PLUGINHOST_VST 1
  92154. #endif
  92155. /** Enabling this builds support for AudioUnit audio plugins.
  92156. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  92157. */
  92158. #ifndef JUCE_PLUGINHOST_AU
  92159. // #define JUCE_PLUGINHOST_AU 1
  92160. #endif
  92161. /** Disabling this will avoid linking to any UI code. This is handy for
  92162. writing command-line utilities, e.g. on linux boxes which don't have some
  92163. of the UI libraries installed.
  92164. (On mac and windows, this won't generally make much difference to the build).
  92165. */
  92166. #ifndef JUCE_BUILD_GUI_CLASSES
  92167. #define JUCE_BUILD_GUI_CLASSES 1
  92168. #endif
  92169. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  92170. */
  92171. #ifndef JUCE_WEB_BROWSER
  92172. #define JUCE_WEB_BROWSER 1
  92173. #endif
  92174. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  92175. codebase - you might need to use this if you're linking to some of these libraries
  92176. yourself.
  92177. */
  92178. #ifndef JUCE_INCLUDE_ZLIB_CODE
  92179. #define JUCE_INCLUDE_ZLIB_CODE 1
  92180. #endif
  92181. #ifndef JUCE_INCLUDE_FLAC_CODE
  92182. #define JUCE_INCLUDE_FLAC_CODE 1
  92183. #endif
  92184. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  92185. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  92186. #endif
  92187. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  92188. #define JUCE_INCLUDE_PNGLIB_CODE 1
  92189. #endif
  92190. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  92191. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  92192. #endif
  92193. /** Enable this to add extra memory-leak info to the new and delete operators.
  92194. (Currently, this only affects Windows builds in debug mode).
  92195. */
  92196. #ifndef JUCE_CHECK_MEMORY_LEAKS
  92197. #define JUCE_CHECK_MEMORY_LEAKS 1
  92198. #endif
  92199. /** Enable this to turn on juce's internal catching of exceptions.
  92200. Turning it off will avoid any exception catching. With it on, all exceptions
  92201. are passed to the JUCEApplication::unhandledException() callback for logging.
  92202. */
  92203. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  92204. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  92205. #endif
  92206. /** If this macro is set, the Juce String class will use unicode as its
  92207. internal representation. If it isn't set, it'll use ANSI.
  92208. */
  92209. #ifndef JUCE_STRINGS_ARE_UNICODE
  92210. #define JUCE_STRINGS_ARE_UNICODE 1
  92211. #endif
  92212. #endif
  92213. /********* End of inlined file: juce_Config.h *********/
  92214. #define VERSION "1.2.1"
  92215. #define FLAC__NO_DLL 1
  92216. #ifdef _MSC_VER
  92217. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92218. #endif
  92219. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92220. #define FLAC__SYS_DARWIN 1
  92221. #endif
  92222. /********* End of inlined file: juce_FlacHeader.h *********/
  92223. #if JUCE_USE_FLAC
  92224. #if HAVE_CONFIG_H
  92225. # include <config.h>
  92226. #endif
  92227. #include <stdio.h>
  92228. #include <stdlib.h> /* for qsort() */
  92229. #include <string.h> /* for memset() */
  92230. #ifndef FLaC__INLINE
  92231. #define FLaC__INLINE
  92232. #endif
  92233. #ifdef min
  92234. #undef min
  92235. #endif
  92236. #define min(a,b) ((a)<(b)?(a):(b))
  92237. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  92238. #ifdef _MSC_VER
  92239. #define FLAC__U64L(x) x
  92240. #else
  92241. #define FLAC__U64L(x) x##LLU
  92242. #endif
  92243. /* VERSION should come from configure */
  92244. FLAC_API const char *FLAC__VERSION_STRING = VERSION
  92245. ;
  92246. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINW32__
  92247. /* yet one more hack because of MSVC6: */
  92248. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC 1.2.1 20070917";
  92249. #else
  92250. FLAC_API const char *FLAC__VENDOR_STRING = "reference libFLAC " VERSION " 20070917";
  92251. #endif
  92252. FLAC_API const FLAC__byte FLAC__STREAM_SYNC_STRING[4] = { 'f','L','a','C' };
  92253. FLAC_API const unsigned FLAC__STREAM_SYNC = 0x664C6143;
  92254. FLAC_API const unsigned FLAC__STREAM_SYNC_LEN = 32; /* bits */
  92255. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN = 16; /* bits */
  92256. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN = 16; /* bits */
  92257. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN = 24; /* bits */
  92258. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN = 24; /* bits */
  92259. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN = 20; /* bits */
  92260. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN = 3; /* bits */
  92261. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN = 5; /* bits */
  92262. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN = 36; /* bits */
  92263. FLAC_API const unsigned FLAC__STREAM_METADATA_STREAMINFO_MD5SUM_LEN = 128; /* bits */
  92264. FLAC_API const unsigned FLAC__STREAM_METADATA_APPLICATION_ID_LEN = 32; /* bits */
  92265. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN = 64; /* bits */
  92266. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN = 64; /* bits */
  92267. FLAC_API const unsigned FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN = 16; /* bits */
  92268. FLAC_API const FLAC__uint64 FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER = FLAC__U64L(0xffffffffffffffff);
  92269. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN = 32; /* bits */
  92270. FLAC_API const unsigned FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN = 32; /* bits */
  92271. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN = 64; /* bits */
  92272. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN = 8; /* bits */
  92273. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN = 3*8; /* bits */
  92274. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN = 64; /* bits */
  92275. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN = 8; /* bits */
  92276. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN = 12*8; /* bits */
  92277. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN = 1; /* bit */
  92278. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN = 1; /* bit */
  92279. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN = 6+13*8; /* bits */
  92280. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN = 8; /* bits */
  92281. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN = 128*8; /* bits */
  92282. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN = 64; /* bits */
  92283. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN = 1; /* bit */
  92284. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN = 7+258*8; /* bits */
  92285. FLAC_API const unsigned FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN = 8; /* bits */
  92286. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_TYPE_LEN = 32; /* bits */
  92287. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN = 32; /* bits */
  92288. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN = 32; /* bits */
  92289. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN = 32; /* bits */
  92290. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN = 32; /* bits */
  92291. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN = 32; /* bits */
  92292. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_COLORS_LEN = 32; /* bits */
  92293. FLAC_API const unsigned FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN = 32; /* bits */
  92294. FLAC_API const unsigned FLAC__STREAM_METADATA_IS_LAST_LEN = 1; /* bits */
  92295. FLAC_API const unsigned FLAC__STREAM_METADATA_TYPE_LEN = 7; /* bits */
  92296. FLAC_API const unsigned FLAC__STREAM_METADATA_LENGTH_LEN = 24; /* bits */
  92297. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC = 0x3ffe;
  92298. FLAC_API const unsigned FLAC__FRAME_HEADER_SYNC_LEN = 14; /* bits */
  92299. FLAC_API const unsigned FLAC__FRAME_HEADER_RESERVED_LEN = 1; /* bits */
  92300. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN = 1; /* bits */
  92301. FLAC_API const unsigned FLAC__FRAME_HEADER_BLOCK_SIZE_LEN = 4; /* bits */
  92302. FLAC_API const unsigned FLAC__FRAME_HEADER_SAMPLE_RATE_LEN = 4; /* bits */
  92303. FLAC_API const unsigned FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN = 4; /* bits */
  92304. FLAC_API const unsigned FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN = 3; /* bits */
  92305. FLAC_API const unsigned FLAC__FRAME_HEADER_ZERO_PAD_LEN = 1; /* bits */
  92306. FLAC_API const unsigned FLAC__FRAME_HEADER_CRC_LEN = 8; /* bits */
  92307. FLAC_API const unsigned FLAC__FRAME_FOOTER_CRC_LEN = 16; /* bits */
  92308. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_TYPE_LEN = 2; /* bits */
  92309. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN = 4; /* bits */
  92310. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN = 4; /* bits */
  92311. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN = 5; /* bits */
  92312. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN = 5; /* bits */
  92313. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER = 15; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN)-1 */
  92314. FLAC_API const unsigned FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER = 31; /* == (1<<FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN)-1 */
  92315. FLAC_API const char * const FLAC__EntropyCodingMethodTypeString[] = {
  92316. "PARTITIONED_RICE",
  92317. "PARTITIONED_RICE2"
  92318. };
  92319. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN = 4; /* bits */
  92320. FLAC_API const unsigned FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN = 5; /* bits */
  92321. FLAC_API const unsigned FLAC__SUBFRAME_ZERO_PAD_LEN = 1; /* bits */
  92322. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LEN = 6; /* bits */
  92323. FLAC_API const unsigned FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN = 1; /* bits */
  92324. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_CONSTANT_BYTE_ALIGNED_MASK = 0x00;
  92325. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_VERBATIM_BYTE_ALIGNED_MASK = 0x02;
  92326. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_FIXED_BYTE_ALIGNED_MASK = 0x10;
  92327. FLAC_API const unsigned FLAC__SUBFRAME_TYPE_LPC_BYTE_ALIGNED_MASK = 0x40;
  92328. FLAC_API const char * const FLAC__SubframeTypeString[] = {
  92329. "CONSTANT",
  92330. "VERBATIM",
  92331. "FIXED",
  92332. "LPC"
  92333. };
  92334. FLAC_API const char * const FLAC__ChannelAssignmentString[] = {
  92335. "INDEPENDENT",
  92336. "LEFT_SIDE",
  92337. "RIGHT_SIDE",
  92338. "MID_SIDE"
  92339. };
  92340. FLAC_API const char * const FLAC__FrameNumberTypeString[] = {
  92341. "FRAME_NUMBER_TYPE_FRAME_NUMBER",
  92342. "FRAME_NUMBER_TYPE_SAMPLE_NUMBER"
  92343. };
  92344. FLAC_API const char * const FLAC__MetadataTypeString[] = {
  92345. "STREAMINFO",
  92346. "PADDING",
  92347. "APPLICATION",
  92348. "SEEKTABLE",
  92349. "VORBIS_COMMENT",
  92350. "CUESHEET",
  92351. "PICTURE"
  92352. };
  92353. FLAC_API const char * const FLAC__StreamMetadata_Picture_TypeString[] = {
  92354. "Other",
  92355. "32x32 pixels 'file icon' (PNG only)",
  92356. "Other file icon",
  92357. "Cover (front)",
  92358. "Cover (back)",
  92359. "Leaflet page",
  92360. "Media (e.g. label side of CD)",
  92361. "Lead artist/lead performer/soloist",
  92362. "Artist/performer",
  92363. "Conductor",
  92364. "Band/Orchestra",
  92365. "Composer",
  92366. "Lyricist/text writer",
  92367. "Recording Location",
  92368. "During recording",
  92369. "During performance",
  92370. "Movie/video screen capture",
  92371. "A bright coloured fish",
  92372. "Illustration",
  92373. "Band/artist logotype",
  92374. "Publisher/Studio logotype"
  92375. };
  92376. FLAC_API FLAC__bool FLAC__format_sample_rate_is_valid(unsigned sample_rate)
  92377. {
  92378. if(sample_rate == 0 || sample_rate > FLAC__MAX_SAMPLE_RATE) {
  92379. return false;
  92380. }
  92381. else
  92382. return true;
  92383. }
  92384. FLAC_API FLAC__bool FLAC__format_sample_rate_is_subset(unsigned sample_rate)
  92385. {
  92386. if(
  92387. !FLAC__format_sample_rate_is_valid(sample_rate) ||
  92388. (
  92389. sample_rate >= (1u << 16) &&
  92390. !(sample_rate % 1000 == 0 || sample_rate % 10 == 0)
  92391. )
  92392. ) {
  92393. return false;
  92394. }
  92395. else
  92396. return true;
  92397. }
  92398. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92399. FLAC_API FLAC__bool FLAC__format_seektable_is_legal(const FLAC__StreamMetadata_SeekTable *seek_table)
  92400. {
  92401. unsigned i;
  92402. FLAC__uint64 prev_sample_number = 0;
  92403. FLAC__bool got_prev = false;
  92404. FLAC__ASSERT(0 != seek_table);
  92405. for(i = 0; i < seek_table->num_points; i++) {
  92406. if(got_prev) {
  92407. if(
  92408. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  92409. seek_table->points[i].sample_number <= prev_sample_number
  92410. )
  92411. return false;
  92412. }
  92413. prev_sample_number = seek_table->points[i].sample_number;
  92414. got_prev = true;
  92415. }
  92416. return true;
  92417. }
  92418. /* used as the sort predicate for qsort() */
  92419. static int seekpoint_compare_(const FLAC__StreamMetadata_SeekPoint *l, const FLAC__StreamMetadata_SeekPoint *r)
  92420. {
  92421. /* we don't just 'return l->sample_number - r->sample_number' since the result (FLAC__int64) might overflow an 'int' */
  92422. if(l->sample_number == r->sample_number)
  92423. return 0;
  92424. else if(l->sample_number < r->sample_number)
  92425. return -1;
  92426. else
  92427. return 1;
  92428. }
  92429. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92430. FLAC_API unsigned FLAC__format_seektable_sort(FLAC__StreamMetadata_SeekTable *seek_table)
  92431. {
  92432. unsigned i, j;
  92433. FLAC__bool first;
  92434. FLAC__ASSERT(0 != seek_table);
  92435. /* sort the seekpoints */
  92436. qsort(seek_table->points, seek_table->num_points, sizeof(FLAC__StreamMetadata_SeekPoint), (int (*)(const void *, const void *))seekpoint_compare_);
  92437. /* uniquify the seekpoints */
  92438. first = true;
  92439. for(i = j = 0; i < seek_table->num_points; i++) {
  92440. if(seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER) {
  92441. if(!first) {
  92442. if(seek_table->points[i].sample_number == seek_table->points[j-1].sample_number)
  92443. continue;
  92444. }
  92445. }
  92446. first = false;
  92447. seek_table->points[j++] = seek_table->points[i];
  92448. }
  92449. for(i = j; i < seek_table->num_points; i++) {
  92450. seek_table->points[i].sample_number = FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER;
  92451. seek_table->points[i].stream_offset = 0;
  92452. seek_table->points[i].frame_samples = 0;
  92453. }
  92454. return j;
  92455. }
  92456. /*
  92457. * also disallows non-shortest-form encodings, c.f.
  92458. * http://www.unicode.org/versions/corrigendum1.html
  92459. * and a more clear explanation at the end of this section:
  92460. * http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
  92461. */
  92462. static FLaC__INLINE unsigned utf8len_(const FLAC__byte *utf8)
  92463. {
  92464. FLAC__ASSERT(0 != utf8);
  92465. if ((utf8[0] & 0x80) == 0) {
  92466. return 1;
  92467. }
  92468. else if ((utf8[0] & 0xE0) == 0xC0 && (utf8[1] & 0xC0) == 0x80) {
  92469. if ((utf8[0] & 0xFE) == 0xC0) /* overlong sequence check */
  92470. return 0;
  92471. return 2;
  92472. }
  92473. else if ((utf8[0] & 0xF0) == 0xE0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80) {
  92474. if (utf8[0] == 0xE0 && (utf8[1] & 0xE0) == 0x80) /* overlong sequence check */
  92475. return 0;
  92476. /* illegal surrogates check (U+D800...U+DFFF and U+FFFE...U+FFFF) */
  92477. if (utf8[0] == 0xED && (utf8[1] & 0xE0) == 0xA0) /* D800-DFFF */
  92478. return 0;
  92479. if (utf8[0] == 0xEF && utf8[1] == 0xBF && (utf8[2] & 0xFE) == 0xBE) /* FFFE-FFFF */
  92480. return 0;
  92481. return 3;
  92482. }
  92483. else if ((utf8[0] & 0xF8) == 0xF0 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80) {
  92484. if (utf8[0] == 0xF0 && (utf8[1] & 0xF0) == 0x80) /* overlong sequence check */
  92485. return 0;
  92486. return 4;
  92487. }
  92488. else if ((utf8[0] & 0xFC) == 0xF8 && (utf8[1] & 0xC0) == 0x80 && (utf8[2] & 0xC0) == 0x80 && (utf8[3] & 0xC0) == 0x80 && (utf8[4] & 0xC0) == 0x80) {
  92489. if (utf8[0] == 0xF8 && (utf8[1] & 0xF8) == 0x80) /* overlong sequence check */
  92490. return 0;
  92491. return 5;
  92492. }
  92493. 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) {
  92494. if (utf8[0] == 0xFC && (utf8[1] & 0xFC) == 0x80) /* overlong sequence check */
  92495. return 0;
  92496. return 6;
  92497. }
  92498. else {
  92499. return 0;
  92500. }
  92501. }
  92502. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_name_is_legal(const char *name)
  92503. {
  92504. char c;
  92505. for(c = *name; c; c = *(++name))
  92506. if(c < 0x20 || c == 0x3d || c > 0x7d)
  92507. return false;
  92508. return true;
  92509. }
  92510. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_value_is_legal(const FLAC__byte *value, unsigned length)
  92511. {
  92512. if(length == (unsigned)(-1)) {
  92513. while(*value) {
  92514. unsigned n = utf8len_(value);
  92515. if(n == 0)
  92516. return false;
  92517. value += n;
  92518. }
  92519. }
  92520. else {
  92521. const FLAC__byte *end = value + length;
  92522. while(value < end) {
  92523. unsigned n = utf8len_(value);
  92524. if(n == 0)
  92525. return false;
  92526. value += n;
  92527. }
  92528. if(value != end)
  92529. return false;
  92530. }
  92531. return true;
  92532. }
  92533. FLAC_API FLAC__bool FLAC__format_vorbiscomment_entry_is_legal(const FLAC__byte *entry, unsigned length)
  92534. {
  92535. const FLAC__byte *s, *end;
  92536. for(s = entry, end = s + length; s < end && *s != '='; s++) {
  92537. if(*s < 0x20 || *s > 0x7D)
  92538. return false;
  92539. }
  92540. if(s == end)
  92541. return false;
  92542. s++; /* skip '=' */
  92543. while(s < end) {
  92544. unsigned n = utf8len_(s);
  92545. if(n == 0)
  92546. return false;
  92547. s += n;
  92548. }
  92549. if(s != end)
  92550. return false;
  92551. return true;
  92552. }
  92553. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92554. FLAC_API FLAC__bool FLAC__format_cuesheet_is_legal(const FLAC__StreamMetadata_CueSheet *cue_sheet, FLAC__bool check_cd_da_subset, const char **violation)
  92555. {
  92556. unsigned i, j;
  92557. if(check_cd_da_subset) {
  92558. if(cue_sheet->lead_in < 2 * 44100) {
  92559. if(violation) *violation = "CD-DA cue sheet must have a lead-in length of at least 2 seconds";
  92560. return false;
  92561. }
  92562. if(cue_sheet->lead_in % 588 != 0) {
  92563. if(violation) *violation = "CD-DA cue sheet lead-in length must be evenly divisible by 588 samples";
  92564. return false;
  92565. }
  92566. }
  92567. if(cue_sheet->num_tracks == 0) {
  92568. if(violation) *violation = "cue sheet must have at least one track (the lead-out)";
  92569. return false;
  92570. }
  92571. if(check_cd_da_subset && cue_sheet->tracks[cue_sheet->num_tracks-1].number != 170) {
  92572. if(violation) *violation = "CD-DA cue sheet must have a lead-out track number 170 (0xAA)";
  92573. return false;
  92574. }
  92575. for(i = 0; i < cue_sheet->num_tracks; i++) {
  92576. if(cue_sheet->tracks[i].number == 0) {
  92577. if(violation) *violation = "cue sheet may not have a track number 0";
  92578. return false;
  92579. }
  92580. if(check_cd_da_subset) {
  92581. if(!((cue_sheet->tracks[i].number >= 1 && cue_sheet->tracks[i].number <= 99) || cue_sheet->tracks[i].number == 170)) {
  92582. if(violation) *violation = "CD-DA cue sheet track number must be 1-99 or 170";
  92583. return false;
  92584. }
  92585. }
  92586. if(check_cd_da_subset && cue_sheet->tracks[i].offset % 588 != 0) {
  92587. if(violation) {
  92588. if(i == cue_sheet->num_tracks-1) /* the lead-out track... */
  92589. *violation = "CD-DA cue sheet lead-out offset must be evenly divisible by 588 samples";
  92590. else
  92591. *violation = "CD-DA cue sheet track offset must be evenly divisible by 588 samples";
  92592. }
  92593. return false;
  92594. }
  92595. if(i < cue_sheet->num_tracks - 1) {
  92596. if(cue_sheet->tracks[i].num_indices == 0) {
  92597. if(violation) *violation = "cue sheet track must have at least one index point";
  92598. return false;
  92599. }
  92600. if(cue_sheet->tracks[i].indices[0].number > 1) {
  92601. if(violation) *violation = "cue sheet track's first index number must be 0 or 1";
  92602. return false;
  92603. }
  92604. }
  92605. for(j = 0; j < cue_sheet->tracks[i].num_indices; j++) {
  92606. if(check_cd_da_subset && cue_sheet->tracks[i].indices[j].offset % 588 != 0) {
  92607. if(violation) *violation = "CD-DA cue sheet track index offset must be evenly divisible by 588 samples";
  92608. return false;
  92609. }
  92610. if(j > 0) {
  92611. if(cue_sheet->tracks[i].indices[j].number != cue_sheet->tracks[i].indices[j-1].number + 1) {
  92612. if(violation) *violation = "cue sheet track index numbers must increase by 1";
  92613. return false;
  92614. }
  92615. }
  92616. }
  92617. }
  92618. return true;
  92619. }
  92620. /* @@@@ add to unit tests; it is already indirectly tested by the metadata_object tests */
  92621. FLAC_API FLAC__bool FLAC__format_picture_is_legal(const FLAC__StreamMetadata_Picture *picture, const char **violation)
  92622. {
  92623. char *p;
  92624. FLAC__byte *b;
  92625. for(p = picture->mime_type; *p; p++) {
  92626. if(*p < 0x20 || *p > 0x7e) {
  92627. if(violation) *violation = "MIME type string must contain only printable ASCII characters (0x20-0x7e)";
  92628. return false;
  92629. }
  92630. }
  92631. for(b = picture->description; *b; ) {
  92632. unsigned n = utf8len_(b);
  92633. if(n == 0) {
  92634. if(violation) *violation = "description string must be valid UTF-8";
  92635. return false;
  92636. }
  92637. b += n;
  92638. }
  92639. return true;
  92640. }
  92641. /*
  92642. * These routines are private to libFLAC
  92643. */
  92644. unsigned FLAC__format_get_max_rice_partition_order(unsigned blocksize, unsigned predictor_order)
  92645. {
  92646. return
  92647. FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(
  92648. FLAC__format_get_max_rice_partition_order_from_blocksize(blocksize),
  92649. blocksize,
  92650. predictor_order
  92651. );
  92652. }
  92653. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize(unsigned blocksize)
  92654. {
  92655. unsigned max_rice_partition_order = 0;
  92656. while(!(blocksize & 1)) {
  92657. max_rice_partition_order++;
  92658. blocksize >>= 1;
  92659. }
  92660. return min(FLAC__MAX_RICE_PARTITION_ORDER, max_rice_partition_order);
  92661. }
  92662. unsigned FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(unsigned limit, unsigned blocksize, unsigned predictor_order)
  92663. {
  92664. unsigned max_rice_partition_order = limit;
  92665. while(max_rice_partition_order > 0 && (blocksize >> max_rice_partition_order) <= predictor_order)
  92666. max_rice_partition_order--;
  92667. FLAC__ASSERT(
  92668. (max_rice_partition_order == 0 && blocksize >= predictor_order) ||
  92669. (max_rice_partition_order > 0 && blocksize >> max_rice_partition_order > predictor_order)
  92670. );
  92671. return max_rice_partition_order;
  92672. }
  92673. void FLAC__format_entropy_coding_method_partitioned_rice_contents_init(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  92674. {
  92675. FLAC__ASSERT(0 != object);
  92676. object->parameters = 0;
  92677. object->raw_bits = 0;
  92678. object->capacity_by_order = 0;
  92679. }
  92680. void FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(FLAC__EntropyCodingMethod_PartitionedRiceContents *object)
  92681. {
  92682. FLAC__ASSERT(0 != object);
  92683. if(0 != object->parameters)
  92684. free(object->parameters);
  92685. if(0 != object->raw_bits)
  92686. free(object->raw_bits);
  92687. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(object);
  92688. }
  92689. FLAC__bool FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(FLAC__EntropyCodingMethod_PartitionedRiceContents *object, unsigned max_partition_order)
  92690. {
  92691. FLAC__ASSERT(0 != object);
  92692. FLAC__ASSERT(object->capacity_by_order > 0 || (0 == object->parameters && 0 == object->raw_bits));
  92693. if(object->capacity_by_order < max_partition_order) {
  92694. if(0 == (object->parameters = (unsigned*)realloc(object->parameters, sizeof(unsigned)*(1 << max_partition_order))))
  92695. return false;
  92696. if(0 == (object->raw_bits = (unsigned*)realloc(object->raw_bits, sizeof(unsigned)*(1 << max_partition_order))))
  92697. return false;
  92698. memset(object->raw_bits, 0, sizeof(unsigned)*(1 << max_partition_order));
  92699. object->capacity_by_order = max_partition_order;
  92700. }
  92701. return true;
  92702. }
  92703. #endif
  92704. /********* End of inlined file: format.c *********/
  92705. /********* Start of inlined file: lpc_flac.c *********/
  92706. /********* Start of inlined file: juce_FlacHeader.h *********/
  92707. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  92708. // tasks..
  92709. /********* Start of inlined file: juce_Config.h *********/
  92710. #ifndef __JUCE_CONFIG_JUCEHEADER__
  92711. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  92712. /*
  92713. This file contains macros that enable/disable various JUCE features.
  92714. */
  92715. /** The name of the namespace that all Juce classes and functions will be
  92716. put inside. If this is not defined, no namespace will be used.
  92717. */
  92718. #ifndef JUCE_NAMESPACE
  92719. #define JUCE_NAMESPACE juce
  92720. #endif
  92721. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  92722. but if you define this value, you can override this can force it to be true or
  92723. false.
  92724. */
  92725. #ifndef JUCE_FORCE_DEBUG
  92726. //#define JUCE_FORCE_DEBUG 1
  92727. #endif
  92728. /** If this flag is enabled, the the jassert and jassertfalse macros will
  92729. always use Logger::writeToLog() to write a message when an assertion happens.
  92730. Enabling it will also leave this turned on in release builds. When it's disabled,
  92731. however, the jassert and jassertfalse macros will not be compiled in a
  92732. release build.
  92733. @see jassert, jassertfalse, Logger
  92734. */
  92735. #ifndef JUCE_LOG_ASSERTIONS
  92736. // #define JUCE_LOG_ASSERTIONS 1
  92737. #endif
  92738. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  92739. which the ASIOAudioIODevice class can't be built. See the comments in the
  92740. ASIOAudioIODevice class's header file for more info about this.
  92741. (This only affects a Win32 build)
  92742. */
  92743. #ifndef JUCE_ASIO
  92744. #define JUCE_ASIO 1
  92745. #endif
  92746. /** Comment out this macro to disable building of ALSA device support on Linux.
  92747. */
  92748. #ifndef JUCE_ALSA
  92749. #define JUCE_ALSA 1
  92750. #endif
  92751. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  92752. have the SDK installed.
  92753. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  92754. classes will be unavailable.
  92755. On Windows, if you enable this, you'll need to have the QuickTime SDK
  92756. installed, and its header files will need to be on your include path.
  92757. */
  92758. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  92759. #define JUCE_QUICKTIME 1
  92760. #endif
  92761. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  92762. have the appropriate headers and libraries available. If it's not enabled, the
  92763. OpenGLComponent class will be unavailable.
  92764. */
  92765. #ifndef JUCE_OPENGL
  92766. #define JUCE_OPENGL 1
  92767. #endif
  92768. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  92769. If you're not going to need either of these formats, turn off the flags to
  92770. avoid bloating your codebase with them.
  92771. */
  92772. #ifndef JUCE_USE_FLAC
  92773. #define JUCE_USE_FLAC 1
  92774. #endif
  92775. #ifndef JUCE_USE_OGGVORBIS
  92776. #define JUCE_USE_OGGVORBIS 1
  92777. #endif
  92778. /** This flag lets you enable support for CD-burning. You might want to disable
  92779. it to build without the MS SDK under windows.
  92780. */
  92781. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  92782. #define JUCE_USE_CDBURNER 1
  92783. #endif
  92784. /** Enabling this macro means that all regions that get repainted will have a coloured
  92785. line drawn around them.
  92786. This is handy if you're trying to optimise drawing, because it lets you easily see
  92787. when anything is being repainted unnecessarily.
  92788. */
  92789. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  92790. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  92791. #endif
  92792. /** Enable this under Linux to use Xinerama for multi-monitor support.
  92793. */
  92794. #ifndef JUCE_USE_XINERAMA
  92795. #define JUCE_USE_XINERAMA 1
  92796. #endif
  92797. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  92798. */
  92799. #ifndef JUCE_USE_XSHM
  92800. #define JUCE_USE_XSHM 1
  92801. #endif
  92802. /** Enabling this builds support for VST audio plugins.
  92803. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  92804. */
  92805. #ifndef JUCE_PLUGINHOST_VST
  92806. // #define JUCE_PLUGINHOST_VST 1
  92807. #endif
  92808. /** Enabling this builds support for AudioUnit audio plugins.
  92809. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  92810. */
  92811. #ifndef JUCE_PLUGINHOST_AU
  92812. // #define JUCE_PLUGINHOST_AU 1
  92813. #endif
  92814. /** Disabling this will avoid linking to any UI code. This is handy for
  92815. writing command-line utilities, e.g. on linux boxes which don't have some
  92816. of the UI libraries installed.
  92817. (On mac and windows, this won't generally make much difference to the build).
  92818. */
  92819. #ifndef JUCE_BUILD_GUI_CLASSES
  92820. #define JUCE_BUILD_GUI_CLASSES 1
  92821. #endif
  92822. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  92823. */
  92824. #ifndef JUCE_WEB_BROWSER
  92825. #define JUCE_WEB_BROWSER 1
  92826. #endif
  92827. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  92828. codebase - you might need to use this if you're linking to some of these libraries
  92829. yourself.
  92830. */
  92831. #ifndef JUCE_INCLUDE_ZLIB_CODE
  92832. #define JUCE_INCLUDE_ZLIB_CODE 1
  92833. #endif
  92834. #ifndef JUCE_INCLUDE_FLAC_CODE
  92835. #define JUCE_INCLUDE_FLAC_CODE 1
  92836. #endif
  92837. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  92838. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  92839. #endif
  92840. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  92841. #define JUCE_INCLUDE_PNGLIB_CODE 1
  92842. #endif
  92843. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  92844. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  92845. #endif
  92846. /** Enable this to add extra memory-leak info to the new and delete operators.
  92847. (Currently, this only affects Windows builds in debug mode).
  92848. */
  92849. #ifndef JUCE_CHECK_MEMORY_LEAKS
  92850. #define JUCE_CHECK_MEMORY_LEAKS 1
  92851. #endif
  92852. /** Enable this to turn on juce's internal catching of exceptions.
  92853. Turning it off will avoid any exception catching. With it on, all exceptions
  92854. are passed to the JUCEApplication::unhandledException() callback for logging.
  92855. */
  92856. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  92857. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  92858. #endif
  92859. /** If this macro is set, the Juce String class will use unicode as its
  92860. internal representation. If it isn't set, it'll use ANSI.
  92861. */
  92862. #ifndef JUCE_STRINGS_ARE_UNICODE
  92863. #define JUCE_STRINGS_ARE_UNICODE 1
  92864. #endif
  92865. #endif
  92866. /********* End of inlined file: juce_Config.h *********/
  92867. #define VERSION "1.2.1"
  92868. #define FLAC__NO_DLL 1
  92869. #ifdef _MSC_VER
  92870. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  92871. #endif
  92872. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  92873. #define FLAC__SYS_DARWIN 1
  92874. #endif
  92875. /********* End of inlined file: juce_FlacHeader.h *********/
  92876. #if JUCE_USE_FLAC
  92877. #if HAVE_CONFIG_H
  92878. # include <config.h>
  92879. #endif
  92880. #include <math.h>
  92881. /********* Start of inlined file: lpc.h *********/
  92882. #ifndef FLAC__PRIVATE__LPC_H
  92883. #define FLAC__PRIVATE__LPC_H
  92884. #ifdef HAVE_CONFIG_H
  92885. #include <config.h>
  92886. #endif
  92887. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  92888. /*
  92889. * FLAC__lpc_window_data()
  92890. * --------------------------------------------------------------------
  92891. * Applies the given window to the data.
  92892. * OPT: asm implementation
  92893. *
  92894. * IN in[0,data_len-1]
  92895. * IN window[0,data_len-1]
  92896. * OUT out[0,lag-1]
  92897. * IN data_len
  92898. */
  92899. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len);
  92900. /*
  92901. * FLAC__lpc_compute_autocorrelation()
  92902. * --------------------------------------------------------------------
  92903. * Compute the autocorrelation for lags between 0 and lag-1.
  92904. * Assumes data[] outside of [0,data_len-1] == 0.
  92905. * Asserts that lag > 0.
  92906. *
  92907. * IN data[0,data_len-1]
  92908. * IN data_len
  92909. * IN 0 < lag <= data_len
  92910. * OUT autoc[0,lag-1]
  92911. */
  92912. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92913. #ifndef FLAC__NO_ASM
  92914. # ifdef FLAC__CPU_IA32
  92915. # ifdef FLAC__HAS_NASM
  92916. void FLAC__lpc_compute_autocorrelation_asm_ia32(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92917. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92918. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92919. void FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92920. void FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  92921. # endif
  92922. # endif
  92923. #endif
  92924. /*
  92925. * FLAC__lpc_compute_lp_coefficients()
  92926. * --------------------------------------------------------------------
  92927. * Computes LP coefficients for orders 1..max_order.
  92928. * Do not call if autoc[0] == 0.0. This means the signal is zero
  92929. * and there is no point in calculating a predictor.
  92930. *
  92931. * IN autoc[0,max_order] autocorrelation values
  92932. * IN 0 < max_order <= FLAC__MAX_LPC_ORDER max LP order to compute
  92933. * OUT lp_coeff[0,max_order-1][0,max_order-1] LP coefficients for each order
  92934. * *** IMPORTANT:
  92935. * *** lp_coeff[0,max_order-1][max_order,FLAC__MAX_LPC_ORDER-1] are untouched
  92936. * OUT error[0,max_order-1] error for each order (more
  92937. * specifically, the variance of
  92938. * the error signal times # of
  92939. * samples in the signal)
  92940. *
  92941. * Example: if max_order is 9, the LP coefficients for order 9 will be
  92942. * in lp_coeff[8][0,8], the LP coefficients for order 8 will be
  92943. * in lp_coeff[7][0,7], etc.
  92944. */
  92945. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[]);
  92946. /*
  92947. * FLAC__lpc_quantize_coefficients()
  92948. * --------------------------------------------------------------------
  92949. * Quantizes the LP coefficients. NOTE: precision + bits_per_sample
  92950. * must be less than 32 (sizeof(FLAC__int32)*8).
  92951. *
  92952. * IN lp_coeff[0,order-1] LP coefficients
  92953. * IN order LP order
  92954. * IN FLAC__MIN_QLP_COEFF_PRECISION < precision
  92955. * desired precision (in bits, including sign
  92956. * bit) of largest coefficient
  92957. * OUT qlp_coeff[0,order-1] quantized coefficients
  92958. * OUT shift # of bits to shift right to get approximated
  92959. * LP coefficients. NOTE: could be negative.
  92960. * RETURN 0 => quantization OK
  92961. * 1 => coefficients require too much shifting for *shift to
  92962. * fit in the LPC subframe header. 'shift' is unset.
  92963. * 2 => coefficients are all zero, which is bad. 'shift' is
  92964. * unset.
  92965. */
  92966. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift);
  92967. /*
  92968. * FLAC__lpc_compute_residual_from_qlp_coefficients()
  92969. * --------------------------------------------------------------------
  92970. * Compute the residual signal obtained from sutracting the predicted
  92971. * signal from the original.
  92972. *
  92973. * IN data[-order,data_len-1] original signal (NOTE THE INDICES!)
  92974. * IN data_len length of original signal
  92975. * IN qlp_coeff[0,order-1] quantized LP coefficients
  92976. * IN order > 0 LP order
  92977. * IN lp_quantization quantization of LP coefficients in bits
  92978. * OUT residual[0,data_len-1] residual signal
  92979. */
  92980. 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[]);
  92981. 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[]);
  92982. #ifndef FLAC__NO_ASM
  92983. # ifdef FLAC__CPU_IA32
  92984. # ifdef FLAC__HAS_NASM
  92985. 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[]);
  92986. 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[]);
  92987. # endif
  92988. # endif
  92989. #endif
  92990. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  92991. /*
  92992. * FLAC__lpc_restore_signal()
  92993. * --------------------------------------------------------------------
  92994. * Restore the original signal by summing the residual and the
  92995. * predictor.
  92996. *
  92997. * IN residual[0,data_len-1] residual signal
  92998. * IN data_len length of original signal
  92999. * IN qlp_coeff[0,order-1] quantized LP coefficients
  93000. * IN order > 0 LP order
  93001. * IN lp_quantization quantization of LP coefficients in bits
  93002. * *** IMPORTANT: the caller must pass in the historical samples:
  93003. * IN data[-order,-1] previously-reconstructed historical samples
  93004. * OUT data[0,data_len-1] original signal
  93005. */
  93006. 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[]);
  93007. 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[]);
  93008. #ifndef FLAC__NO_ASM
  93009. # ifdef FLAC__CPU_IA32
  93010. # ifdef FLAC__HAS_NASM
  93011. 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[]);
  93012. 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[]);
  93013. # endif /* FLAC__HAS_NASM */
  93014. # elif defined FLAC__CPU_PPC
  93015. 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[]);
  93016. 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[]);
  93017. # endif/* FLAC__CPU_IA32 || FLAC__CPU_PPC */
  93018. #endif /* FLAC__NO_ASM */
  93019. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93020. /*
  93021. * FLAC__lpc_compute_expected_bits_per_residual_sample()
  93022. * --------------------------------------------------------------------
  93023. * Compute the expected number of bits per residual signal sample
  93024. * based on the LP error (which is related to the residual variance).
  93025. *
  93026. * IN lpc_error >= 0.0 error returned from calculating LP coefficients
  93027. * IN total_samples > 0 # of samples in residual signal
  93028. * RETURN expected bits per sample
  93029. */
  93030. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples);
  93031. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale);
  93032. /*
  93033. * FLAC__lpc_compute_best_order()
  93034. * --------------------------------------------------------------------
  93035. * Compute the best order from the array of signal errors returned
  93036. * during coefficient computation.
  93037. *
  93038. * IN lpc_error[0,max_order-1] >= 0.0 error returned from calculating LP coefficients
  93039. * IN max_order > 0 max LP order
  93040. * IN total_samples > 0 # of samples in residual signal
  93041. * IN overhead_bits_per_order # of bits overhead for each increased LP order
  93042. * (includes warmup sample size and quantized LP coefficient)
  93043. * RETURN [1,max_order] best order
  93044. */
  93045. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order);
  93046. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  93047. #endif
  93048. /********* End of inlined file: lpc.h *********/
  93049. #if defined DEBUG || defined FLAC__OVERFLOW_DETECT || defined FLAC__OVERFLOW_DETECT_VERBOSE
  93050. #include <stdio.h>
  93051. #endif
  93052. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  93053. #ifndef M_LN2
  93054. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  93055. #define M_LN2 0.69314718055994530942
  93056. #endif
  93057. /* OPT: #undef'ing this may improve the speed on some architectures */
  93058. #define FLAC__LPC_UNROLLED_FILTER_LOOPS
  93059. void FLAC__lpc_window_data(const FLAC__int32 in[], const FLAC__real window[], FLAC__real out[], unsigned data_len)
  93060. {
  93061. unsigned i;
  93062. for(i = 0; i < data_len; i++)
  93063. out[i] = in[i] * window[i];
  93064. }
  93065. void FLAC__lpc_compute_autocorrelation(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[])
  93066. {
  93067. /* a readable, but slower, version */
  93068. #if 0
  93069. FLAC__real d;
  93070. unsigned i;
  93071. FLAC__ASSERT(lag > 0);
  93072. FLAC__ASSERT(lag <= data_len);
  93073. /*
  93074. * Technically we should subtract the mean first like so:
  93075. * for(i = 0; i < data_len; i++)
  93076. * data[i] -= mean;
  93077. * but it appears not to make enough of a difference to matter, and
  93078. * most signals are already closely centered around zero
  93079. */
  93080. while(lag--) {
  93081. for(i = lag, d = 0.0; i < data_len; i++)
  93082. d += data[i] * data[i - lag];
  93083. autoc[lag] = d;
  93084. }
  93085. #endif
  93086. /*
  93087. * this version tends to run faster because of better data locality
  93088. * ('data_len' is usually much larger than 'lag')
  93089. */
  93090. FLAC__real d;
  93091. unsigned sample, coeff;
  93092. const unsigned limit = data_len - lag;
  93093. FLAC__ASSERT(lag > 0);
  93094. FLAC__ASSERT(lag <= data_len);
  93095. for(coeff = 0; coeff < lag; coeff++)
  93096. autoc[coeff] = 0.0;
  93097. for(sample = 0; sample <= limit; sample++) {
  93098. d = data[sample];
  93099. for(coeff = 0; coeff < lag; coeff++)
  93100. autoc[coeff] += d * data[sample+coeff];
  93101. }
  93102. for(; sample < data_len; sample++) {
  93103. d = data[sample];
  93104. for(coeff = 0; coeff < data_len - sample; coeff++)
  93105. autoc[coeff] += d * data[sample+coeff];
  93106. }
  93107. }
  93108. void FLAC__lpc_compute_lp_coefficients(const FLAC__real autoc[], unsigned *max_order, FLAC__real lp_coeff[][FLAC__MAX_LPC_ORDER], FLAC__double error[])
  93109. {
  93110. unsigned i, j;
  93111. FLAC__double r, err, ref[FLAC__MAX_LPC_ORDER], lpc[FLAC__MAX_LPC_ORDER];
  93112. FLAC__ASSERT(0 != max_order);
  93113. FLAC__ASSERT(0 < *max_order);
  93114. FLAC__ASSERT(*max_order <= FLAC__MAX_LPC_ORDER);
  93115. FLAC__ASSERT(autoc[0] != 0.0);
  93116. err = autoc[0];
  93117. for(i = 0; i < *max_order; i++) {
  93118. /* Sum up this iteration's reflection coefficient. */
  93119. r = -autoc[i+1];
  93120. for(j = 0; j < i; j++)
  93121. r -= lpc[j] * autoc[i-j];
  93122. ref[i] = (r/=err);
  93123. /* Update LPC coefficients and total error. */
  93124. lpc[i]=r;
  93125. for(j = 0; j < (i>>1); j++) {
  93126. FLAC__double tmp = lpc[j];
  93127. lpc[j] += r * lpc[i-1-j];
  93128. lpc[i-1-j] += r * tmp;
  93129. }
  93130. if(i & 1)
  93131. lpc[j] += lpc[j] * r;
  93132. err *= (1.0 - r * r);
  93133. /* save this order */
  93134. for(j = 0; j <= i; j++)
  93135. lp_coeff[i][j] = (FLAC__real)(-lpc[j]); /* negate FIR filter coeff to get predictor coeff */
  93136. error[i] = err;
  93137. /* see SF bug #1601812 http://sourceforge.net/tracker/index.php?func=detail&aid=1601812&group_id=13478&atid=113478 */
  93138. if(err == 0.0) {
  93139. *max_order = i+1;
  93140. return;
  93141. }
  93142. }
  93143. }
  93144. int FLAC__lpc_quantize_coefficients(const FLAC__real lp_coeff[], unsigned order, unsigned precision, FLAC__int32 qlp_coeff[], int *shift)
  93145. {
  93146. unsigned i;
  93147. FLAC__double cmax;
  93148. FLAC__int32 qmax, qmin;
  93149. FLAC__ASSERT(precision > 0);
  93150. FLAC__ASSERT(precision >= FLAC__MIN_QLP_COEFF_PRECISION);
  93151. /* drop one bit for the sign; from here on out we consider only |lp_coeff[i]| */
  93152. precision--;
  93153. qmax = 1 << precision;
  93154. qmin = -qmax;
  93155. qmax--;
  93156. /* calc cmax = max( |lp_coeff[i]| ) */
  93157. cmax = 0.0;
  93158. for(i = 0; i < order; i++) {
  93159. const FLAC__double d = fabs(lp_coeff[i]);
  93160. if(d > cmax)
  93161. cmax = d;
  93162. }
  93163. if(cmax <= 0.0) {
  93164. /* => coefficients are all 0, which means our constant-detect didn't work */
  93165. return 2;
  93166. }
  93167. else {
  93168. const int max_shiftlimit = (1 << (FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN-1)) - 1;
  93169. const int min_shiftlimit = -max_shiftlimit - 1;
  93170. int log2cmax;
  93171. (void)frexp(cmax, &log2cmax);
  93172. log2cmax--;
  93173. *shift = (int)precision - log2cmax - 1;
  93174. if(*shift > max_shiftlimit)
  93175. *shift = max_shiftlimit;
  93176. else if(*shift < min_shiftlimit)
  93177. return 1;
  93178. }
  93179. if(*shift >= 0) {
  93180. FLAC__double error = 0.0;
  93181. FLAC__int32 q;
  93182. for(i = 0; i < order; i++) {
  93183. error += lp_coeff[i] * (1 << *shift);
  93184. #if 1 /* unfortunately lround() is C99 */
  93185. if(error >= 0.0)
  93186. q = (FLAC__int32)(error + 0.5);
  93187. else
  93188. q = (FLAC__int32)(error - 0.5);
  93189. #else
  93190. q = lround(error);
  93191. #endif
  93192. #ifdef FLAC__OVERFLOW_DETECT
  93193. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  93194. 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]);
  93195. else if(q < qmin)
  93196. 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]);
  93197. #endif
  93198. if(q > qmax)
  93199. q = qmax;
  93200. else if(q < qmin)
  93201. q = qmin;
  93202. error -= q;
  93203. qlp_coeff[i] = q;
  93204. }
  93205. }
  93206. /* negative shift is very rare but due to design flaw, negative shift is
  93207. * a NOP in the decoder, so it must be handled specially by scaling down
  93208. * coeffs
  93209. */
  93210. else {
  93211. const int nshift = -(*shift);
  93212. FLAC__double error = 0.0;
  93213. FLAC__int32 q;
  93214. #ifdef DEBUG
  93215. fprintf(stderr,"FLAC__lpc_quantize_coefficients: negative shift=%d order=%u cmax=%f\n", *shift, order, cmax);
  93216. #endif
  93217. for(i = 0; i < order; i++) {
  93218. error += lp_coeff[i] / (1 << nshift);
  93219. #if 1 /* unfortunately lround() is C99 */
  93220. if(error >= 0.0)
  93221. q = (FLAC__int32)(error + 0.5);
  93222. else
  93223. q = (FLAC__int32)(error - 0.5);
  93224. #else
  93225. q = lround(error);
  93226. #endif
  93227. #ifdef FLAC__OVERFLOW_DETECT
  93228. if(q > qmax+1) /* we expect q==qmax+1 occasionally due to rounding */
  93229. 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]);
  93230. else if(q < qmin)
  93231. 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]);
  93232. #endif
  93233. if(q > qmax)
  93234. q = qmax;
  93235. else if(q < qmin)
  93236. q = qmin;
  93237. error -= q;
  93238. qlp_coeff[i] = q;
  93239. }
  93240. *shift = 0;
  93241. }
  93242. return 0;
  93243. }
  93244. 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[])
  93245. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93246. {
  93247. FLAC__int64 sumo;
  93248. unsigned i, j;
  93249. FLAC__int32 sum;
  93250. const FLAC__int32 *history;
  93251. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93252. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93253. for(i=0;i<order;i++)
  93254. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93255. fprintf(stderr,"\n");
  93256. #endif
  93257. FLAC__ASSERT(order > 0);
  93258. for(i = 0; i < data_len; i++) {
  93259. sumo = 0;
  93260. sum = 0;
  93261. history = data;
  93262. for(j = 0; j < order; j++) {
  93263. sum += qlp_coeff[j] * (*(--history));
  93264. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  93265. #if defined _MSC_VER
  93266. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  93267. 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);
  93268. #else
  93269. if(sumo > 2147483647ll || sumo < -2147483648ll)
  93270. 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);
  93271. #endif
  93272. }
  93273. *(residual++) = *(data++) - (sum >> lp_quantization);
  93274. }
  93275. /* Here's a slower but clearer version:
  93276. for(i = 0; i < data_len; i++) {
  93277. sum = 0;
  93278. for(j = 0; j < order; j++)
  93279. sum += qlp_coeff[j] * data[i-j-1];
  93280. residual[i] = data[i] - (sum >> lp_quantization);
  93281. }
  93282. */
  93283. }
  93284. #else /* fully unrolled version for normal use */
  93285. {
  93286. int i;
  93287. FLAC__int32 sum;
  93288. FLAC__ASSERT(order > 0);
  93289. FLAC__ASSERT(order <= 32);
  93290. /*
  93291. * We do unique versions up to 12th order since that's the subset limit.
  93292. * Also they are roughly ordered to match frequency of occurrence to
  93293. * minimize branching.
  93294. */
  93295. if(order <= 12) {
  93296. if(order > 8) {
  93297. if(order > 10) {
  93298. if(order == 12) {
  93299. for(i = 0; i < (int)data_len; i++) {
  93300. sum = 0;
  93301. sum += qlp_coeff[11] * data[i-12];
  93302. sum += qlp_coeff[10] * data[i-11];
  93303. sum += qlp_coeff[9] * data[i-10];
  93304. sum += qlp_coeff[8] * data[i-9];
  93305. sum += qlp_coeff[7] * data[i-8];
  93306. sum += qlp_coeff[6] * data[i-7];
  93307. sum += qlp_coeff[5] * data[i-6];
  93308. sum += qlp_coeff[4] * data[i-5];
  93309. sum += qlp_coeff[3] * data[i-4];
  93310. sum += qlp_coeff[2] * data[i-3];
  93311. sum += qlp_coeff[1] * data[i-2];
  93312. sum += qlp_coeff[0] * data[i-1];
  93313. residual[i] = data[i] - (sum >> lp_quantization);
  93314. }
  93315. }
  93316. else { /* order == 11 */
  93317. for(i = 0; i < (int)data_len; i++) {
  93318. sum = 0;
  93319. sum += qlp_coeff[10] * data[i-11];
  93320. sum += qlp_coeff[9] * data[i-10];
  93321. sum += qlp_coeff[8] * data[i-9];
  93322. sum += qlp_coeff[7] * data[i-8];
  93323. sum += qlp_coeff[6] * data[i-7];
  93324. sum += qlp_coeff[5] * data[i-6];
  93325. sum += qlp_coeff[4] * data[i-5];
  93326. sum += qlp_coeff[3] * data[i-4];
  93327. sum += qlp_coeff[2] * data[i-3];
  93328. sum += qlp_coeff[1] * data[i-2];
  93329. sum += qlp_coeff[0] * data[i-1];
  93330. residual[i] = data[i] - (sum >> lp_quantization);
  93331. }
  93332. }
  93333. }
  93334. else {
  93335. if(order == 10) {
  93336. for(i = 0; i < (int)data_len; i++) {
  93337. sum = 0;
  93338. sum += qlp_coeff[9] * data[i-10];
  93339. sum += qlp_coeff[8] * data[i-9];
  93340. sum += qlp_coeff[7] * data[i-8];
  93341. sum += qlp_coeff[6] * data[i-7];
  93342. sum += qlp_coeff[5] * data[i-6];
  93343. sum += qlp_coeff[4] * data[i-5];
  93344. sum += qlp_coeff[3] * data[i-4];
  93345. sum += qlp_coeff[2] * data[i-3];
  93346. sum += qlp_coeff[1] * data[i-2];
  93347. sum += qlp_coeff[0] * data[i-1];
  93348. residual[i] = data[i] - (sum >> lp_quantization);
  93349. }
  93350. }
  93351. else { /* order == 9 */
  93352. for(i = 0; i < (int)data_len; i++) {
  93353. sum = 0;
  93354. sum += qlp_coeff[8] * data[i-9];
  93355. sum += qlp_coeff[7] * data[i-8];
  93356. sum += qlp_coeff[6] * data[i-7];
  93357. sum += qlp_coeff[5] * data[i-6];
  93358. sum += qlp_coeff[4] * data[i-5];
  93359. sum += qlp_coeff[3] * data[i-4];
  93360. sum += qlp_coeff[2] * data[i-3];
  93361. sum += qlp_coeff[1] * data[i-2];
  93362. sum += qlp_coeff[0] * data[i-1];
  93363. residual[i] = data[i] - (sum >> lp_quantization);
  93364. }
  93365. }
  93366. }
  93367. }
  93368. else if(order > 4) {
  93369. if(order > 6) {
  93370. if(order == 8) {
  93371. for(i = 0; i < (int)data_len; i++) {
  93372. sum = 0;
  93373. sum += qlp_coeff[7] * data[i-8];
  93374. sum += qlp_coeff[6] * data[i-7];
  93375. sum += qlp_coeff[5] * data[i-6];
  93376. sum += qlp_coeff[4] * data[i-5];
  93377. sum += qlp_coeff[3] * data[i-4];
  93378. sum += qlp_coeff[2] * data[i-3];
  93379. sum += qlp_coeff[1] * data[i-2];
  93380. sum += qlp_coeff[0] * data[i-1];
  93381. residual[i] = data[i] - (sum >> lp_quantization);
  93382. }
  93383. }
  93384. else { /* order == 7 */
  93385. for(i = 0; i < (int)data_len; i++) {
  93386. sum = 0;
  93387. sum += qlp_coeff[6] * data[i-7];
  93388. sum += qlp_coeff[5] * data[i-6];
  93389. sum += qlp_coeff[4] * data[i-5];
  93390. sum += qlp_coeff[3] * data[i-4];
  93391. sum += qlp_coeff[2] * data[i-3];
  93392. sum += qlp_coeff[1] * data[i-2];
  93393. sum += qlp_coeff[0] * data[i-1];
  93394. residual[i] = data[i] - (sum >> lp_quantization);
  93395. }
  93396. }
  93397. }
  93398. else {
  93399. if(order == 6) {
  93400. for(i = 0; i < (int)data_len; i++) {
  93401. sum = 0;
  93402. sum += qlp_coeff[5] * data[i-6];
  93403. sum += qlp_coeff[4] * data[i-5];
  93404. sum += qlp_coeff[3] * data[i-4];
  93405. sum += qlp_coeff[2] * data[i-3];
  93406. sum += qlp_coeff[1] * data[i-2];
  93407. sum += qlp_coeff[0] * data[i-1];
  93408. residual[i] = data[i] - (sum >> lp_quantization);
  93409. }
  93410. }
  93411. else { /* order == 5 */
  93412. for(i = 0; i < (int)data_len; i++) {
  93413. sum = 0;
  93414. sum += qlp_coeff[4] * data[i-5];
  93415. sum += qlp_coeff[3] * data[i-4];
  93416. sum += qlp_coeff[2] * data[i-3];
  93417. sum += qlp_coeff[1] * data[i-2];
  93418. sum += qlp_coeff[0] * data[i-1];
  93419. residual[i] = data[i] - (sum >> lp_quantization);
  93420. }
  93421. }
  93422. }
  93423. }
  93424. else {
  93425. if(order > 2) {
  93426. if(order == 4) {
  93427. for(i = 0; i < (int)data_len; i++) {
  93428. sum = 0;
  93429. sum += qlp_coeff[3] * data[i-4];
  93430. sum += qlp_coeff[2] * data[i-3];
  93431. sum += qlp_coeff[1] * data[i-2];
  93432. sum += qlp_coeff[0] * data[i-1];
  93433. residual[i] = data[i] - (sum >> lp_quantization);
  93434. }
  93435. }
  93436. else { /* order == 3 */
  93437. for(i = 0; i < (int)data_len; i++) {
  93438. sum = 0;
  93439. sum += qlp_coeff[2] * data[i-3];
  93440. sum += qlp_coeff[1] * data[i-2];
  93441. sum += qlp_coeff[0] * data[i-1];
  93442. residual[i] = data[i] - (sum >> lp_quantization);
  93443. }
  93444. }
  93445. }
  93446. else {
  93447. if(order == 2) {
  93448. for(i = 0; i < (int)data_len; i++) {
  93449. sum = 0;
  93450. sum += qlp_coeff[1] * data[i-2];
  93451. sum += qlp_coeff[0] * data[i-1];
  93452. residual[i] = data[i] - (sum >> lp_quantization);
  93453. }
  93454. }
  93455. else { /* order == 1 */
  93456. for(i = 0; i < (int)data_len; i++)
  93457. residual[i] = data[i] - ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  93458. }
  93459. }
  93460. }
  93461. }
  93462. else { /* order > 12 */
  93463. for(i = 0; i < (int)data_len; i++) {
  93464. sum = 0;
  93465. switch(order) {
  93466. case 32: sum += qlp_coeff[31] * data[i-32];
  93467. case 31: sum += qlp_coeff[30] * data[i-31];
  93468. case 30: sum += qlp_coeff[29] * data[i-30];
  93469. case 29: sum += qlp_coeff[28] * data[i-29];
  93470. case 28: sum += qlp_coeff[27] * data[i-28];
  93471. case 27: sum += qlp_coeff[26] * data[i-27];
  93472. case 26: sum += qlp_coeff[25] * data[i-26];
  93473. case 25: sum += qlp_coeff[24] * data[i-25];
  93474. case 24: sum += qlp_coeff[23] * data[i-24];
  93475. case 23: sum += qlp_coeff[22] * data[i-23];
  93476. case 22: sum += qlp_coeff[21] * data[i-22];
  93477. case 21: sum += qlp_coeff[20] * data[i-21];
  93478. case 20: sum += qlp_coeff[19] * data[i-20];
  93479. case 19: sum += qlp_coeff[18] * data[i-19];
  93480. case 18: sum += qlp_coeff[17] * data[i-18];
  93481. case 17: sum += qlp_coeff[16] * data[i-17];
  93482. case 16: sum += qlp_coeff[15] * data[i-16];
  93483. case 15: sum += qlp_coeff[14] * data[i-15];
  93484. case 14: sum += qlp_coeff[13] * data[i-14];
  93485. case 13: sum += qlp_coeff[12] * data[i-13];
  93486. sum += qlp_coeff[11] * data[i-12];
  93487. sum += qlp_coeff[10] * data[i-11];
  93488. sum += qlp_coeff[ 9] * data[i-10];
  93489. sum += qlp_coeff[ 8] * data[i- 9];
  93490. sum += qlp_coeff[ 7] * data[i- 8];
  93491. sum += qlp_coeff[ 6] * data[i- 7];
  93492. sum += qlp_coeff[ 5] * data[i- 6];
  93493. sum += qlp_coeff[ 4] * data[i- 5];
  93494. sum += qlp_coeff[ 3] * data[i- 4];
  93495. sum += qlp_coeff[ 2] * data[i- 3];
  93496. sum += qlp_coeff[ 1] * data[i- 2];
  93497. sum += qlp_coeff[ 0] * data[i- 1];
  93498. }
  93499. residual[i] = data[i] - (sum >> lp_quantization);
  93500. }
  93501. }
  93502. }
  93503. #endif
  93504. 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[])
  93505. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93506. {
  93507. unsigned i, j;
  93508. FLAC__int64 sum;
  93509. const FLAC__int32 *history;
  93510. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93511. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93512. for(i=0;i<order;i++)
  93513. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93514. fprintf(stderr,"\n");
  93515. #endif
  93516. FLAC__ASSERT(order > 0);
  93517. for(i = 0; i < data_len; i++) {
  93518. sum = 0;
  93519. history = data;
  93520. for(j = 0; j < order; j++)
  93521. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  93522. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  93523. #if defined _MSC_VER
  93524. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  93525. #else
  93526. fprintf(stderr,"FLAC__lpc_compute_residual_from_qlp_coefficients_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  93527. #endif
  93528. break;
  93529. }
  93530. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*data) - (sum >> lp_quantization)) > 32) {
  93531. #if defined _MSC_VER
  93532. 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));
  93533. #else
  93534. 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)));
  93535. #endif
  93536. break;
  93537. }
  93538. *(residual++) = *(data++) - (FLAC__int32)(sum >> lp_quantization);
  93539. }
  93540. }
  93541. #else /* fully unrolled version for normal use */
  93542. {
  93543. int i;
  93544. FLAC__int64 sum;
  93545. FLAC__ASSERT(order > 0);
  93546. FLAC__ASSERT(order <= 32);
  93547. /*
  93548. * We do unique versions up to 12th order since that's the subset limit.
  93549. * Also they are roughly ordered to match frequency of occurrence to
  93550. * minimize branching.
  93551. */
  93552. if(order <= 12) {
  93553. if(order > 8) {
  93554. if(order > 10) {
  93555. if(order == 12) {
  93556. for(i = 0; i < (int)data_len; i++) {
  93557. sum = 0;
  93558. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93559. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93560. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93561. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93562. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93563. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93564. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93565. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93566. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93567. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93568. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93569. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93570. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93571. }
  93572. }
  93573. else { /* order == 11 */
  93574. for(i = 0; i < (int)data_len; i++) {
  93575. sum = 0;
  93576. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93577. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93578. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93579. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93580. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93581. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93582. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93583. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93584. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93585. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93586. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93587. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93588. }
  93589. }
  93590. }
  93591. else {
  93592. if(order == 10) {
  93593. for(i = 0; i < (int)data_len; i++) {
  93594. sum = 0;
  93595. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  93596. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93597. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93598. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93599. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93600. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93601. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93602. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93603. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93604. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93605. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93606. }
  93607. }
  93608. else { /* order == 9 */
  93609. for(i = 0; i < (int)data_len; i++) {
  93610. sum = 0;
  93611. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  93612. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93613. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93614. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93615. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93616. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93617. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93618. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93619. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93620. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93621. }
  93622. }
  93623. }
  93624. }
  93625. else if(order > 4) {
  93626. if(order > 6) {
  93627. if(order == 8) {
  93628. for(i = 0; i < (int)data_len; i++) {
  93629. sum = 0;
  93630. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  93631. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93632. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93633. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93634. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93635. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93636. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93637. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93638. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93639. }
  93640. }
  93641. else { /* order == 7 */
  93642. for(i = 0; i < (int)data_len; i++) {
  93643. sum = 0;
  93644. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  93645. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93646. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93647. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93648. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93649. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93650. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93651. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93652. }
  93653. }
  93654. }
  93655. else {
  93656. if(order == 6) {
  93657. for(i = 0; i < (int)data_len; i++) {
  93658. sum = 0;
  93659. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  93660. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93661. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93662. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93663. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93664. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93665. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93666. }
  93667. }
  93668. else { /* order == 5 */
  93669. for(i = 0; i < (int)data_len; i++) {
  93670. sum = 0;
  93671. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  93672. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93673. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93674. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93675. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93676. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93677. }
  93678. }
  93679. }
  93680. }
  93681. else {
  93682. if(order > 2) {
  93683. if(order == 4) {
  93684. for(i = 0; i < (int)data_len; i++) {
  93685. sum = 0;
  93686. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  93687. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93688. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93689. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93690. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93691. }
  93692. }
  93693. else { /* order == 3 */
  93694. for(i = 0; i < (int)data_len; i++) {
  93695. sum = 0;
  93696. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  93697. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93698. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93699. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93700. }
  93701. }
  93702. }
  93703. else {
  93704. if(order == 2) {
  93705. for(i = 0; i < (int)data_len; i++) {
  93706. sum = 0;
  93707. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  93708. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  93709. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93710. }
  93711. }
  93712. else { /* order == 1 */
  93713. for(i = 0; i < (int)data_len; i++)
  93714. residual[i] = data[i] - (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  93715. }
  93716. }
  93717. }
  93718. }
  93719. else { /* order > 12 */
  93720. for(i = 0; i < (int)data_len; i++) {
  93721. sum = 0;
  93722. switch(order) {
  93723. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  93724. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  93725. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  93726. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  93727. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  93728. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  93729. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  93730. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  93731. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  93732. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  93733. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  93734. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  93735. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  93736. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  93737. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  93738. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  93739. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  93740. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  93741. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  93742. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  93743. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  93744. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  93745. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  93746. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  93747. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  93748. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  93749. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  93750. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  93751. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  93752. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  93753. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  93754. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  93755. }
  93756. residual[i] = data[i] - (FLAC__int32)(sum >> lp_quantization);
  93757. }
  93758. }
  93759. }
  93760. #endif
  93761. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  93762. 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[])
  93763. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  93764. {
  93765. FLAC__int64 sumo;
  93766. unsigned i, j;
  93767. FLAC__int32 sum;
  93768. const FLAC__int32 *r = residual, *history;
  93769. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  93770. fprintf(stderr,"FLAC__lpc_restore_signal: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  93771. for(i=0;i<order;i++)
  93772. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  93773. fprintf(stderr,"\n");
  93774. #endif
  93775. FLAC__ASSERT(order > 0);
  93776. for(i = 0; i < data_len; i++) {
  93777. sumo = 0;
  93778. sum = 0;
  93779. history = data;
  93780. for(j = 0; j < order; j++) {
  93781. sum += qlp_coeff[j] * (*(--history));
  93782. sumo += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*history);
  93783. #if defined _MSC_VER
  93784. if(sumo > 2147483647I64 || sumo < -2147483648I64)
  93785. 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);
  93786. #else
  93787. if(sumo > 2147483647ll || sumo < -2147483648ll)
  93788. 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);
  93789. #endif
  93790. }
  93791. *(data++) = *(r++) + (sum >> lp_quantization);
  93792. }
  93793. /* Here's a slower but clearer version:
  93794. for(i = 0; i < data_len; i++) {
  93795. sum = 0;
  93796. for(j = 0; j < order; j++)
  93797. sum += qlp_coeff[j] * data[i-j-1];
  93798. data[i] = residual[i] + (sum >> lp_quantization);
  93799. }
  93800. */
  93801. }
  93802. #else /* fully unrolled version for normal use */
  93803. {
  93804. int i;
  93805. FLAC__int32 sum;
  93806. FLAC__ASSERT(order > 0);
  93807. FLAC__ASSERT(order <= 32);
  93808. /*
  93809. * We do unique versions up to 12th order since that's the subset limit.
  93810. * Also they are roughly ordered to match frequency of occurrence to
  93811. * minimize branching.
  93812. */
  93813. if(order <= 12) {
  93814. if(order > 8) {
  93815. if(order > 10) {
  93816. if(order == 12) {
  93817. for(i = 0; i < (int)data_len; i++) {
  93818. sum = 0;
  93819. sum += qlp_coeff[11] * data[i-12];
  93820. sum += qlp_coeff[10] * data[i-11];
  93821. sum += qlp_coeff[9] * data[i-10];
  93822. sum += qlp_coeff[8] * data[i-9];
  93823. sum += qlp_coeff[7] * data[i-8];
  93824. sum += qlp_coeff[6] * data[i-7];
  93825. sum += qlp_coeff[5] * data[i-6];
  93826. sum += qlp_coeff[4] * data[i-5];
  93827. sum += qlp_coeff[3] * data[i-4];
  93828. sum += qlp_coeff[2] * data[i-3];
  93829. sum += qlp_coeff[1] * data[i-2];
  93830. sum += qlp_coeff[0] * data[i-1];
  93831. data[i] = residual[i] + (sum >> lp_quantization);
  93832. }
  93833. }
  93834. else { /* order == 11 */
  93835. for(i = 0; i < (int)data_len; i++) {
  93836. sum = 0;
  93837. sum += qlp_coeff[10] * data[i-11];
  93838. sum += qlp_coeff[9] * data[i-10];
  93839. sum += qlp_coeff[8] * data[i-9];
  93840. sum += qlp_coeff[7] * data[i-8];
  93841. sum += qlp_coeff[6] * data[i-7];
  93842. sum += qlp_coeff[5] * data[i-6];
  93843. sum += qlp_coeff[4] * data[i-5];
  93844. sum += qlp_coeff[3] * data[i-4];
  93845. sum += qlp_coeff[2] * data[i-3];
  93846. sum += qlp_coeff[1] * data[i-2];
  93847. sum += qlp_coeff[0] * data[i-1];
  93848. data[i] = residual[i] + (sum >> lp_quantization);
  93849. }
  93850. }
  93851. }
  93852. else {
  93853. if(order == 10) {
  93854. for(i = 0; i < (int)data_len; i++) {
  93855. sum = 0;
  93856. sum += qlp_coeff[9] * data[i-10];
  93857. sum += qlp_coeff[8] * data[i-9];
  93858. sum += qlp_coeff[7] * data[i-8];
  93859. sum += qlp_coeff[6] * data[i-7];
  93860. sum += qlp_coeff[5] * data[i-6];
  93861. sum += qlp_coeff[4] * data[i-5];
  93862. sum += qlp_coeff[3] * data[i-4];
  93863. sum += qlp_coeff[2] * data[i-3];
  93864. sum += qlp_coeff[1] * data[i-2];
  93865. sum += qlp_coeff[0] * data[i-1];
  93866. data[i] = residual[i] + (sum >> lp_quantization);
  93867. }
  93868. }
  93869. else { /* order == 9 */
  93870. for(i = 0; i < (int)data_len; i++) {
  93871. sum = 0;
  93872. sum += qlp_coeff[8] * data[i-9];
  93873. sum += qlp_coeff[7] * data[i-8];
  93874. sum += qlp_coeff[6] * data[i-7];
  93875. sum += qlp_coeff[5] * data[i-6];
  93876. sum += qlp_coeff[4] * data[i-5];
  93877. sum += qlp_coeff[3] * data[i-4];
  93878. sum += qlp_coeff[2] * data[i-3];
  93879. sum += qlp_coeff[1] * data[i-2];
  93880. sum += qlp_coeff[0] * data[i-1];
  93881. data[i] = residual[i] + (sum >> lp_quantization);
  93882. }
  93883. }
  93884. }
  93885. }
  93886. else if(order > 4) {
  93887. if(order > 6) {
  93888. if(order == 8) {
  93889. for(i = 0; i < (int)data_len; i++) {
  93890. sum = 0;
  93891. sum += qlp_coeff[7] * data[i-8];
  93892. sum += qlp_coeff[6] * data[i-7];
  93893. sum += qlp_coeff[5] * data[i-6];
  93894. sum += qlp_coeff[4] * data[i-5];
  93895. sum += qlp_coeff[3] * data[i-4];
  93896. sum += qlp_coeff[2] * data[i-3];
  93897. sum += qlp_coeff[1] * data[i-2];
  93898. sum += qlp_coeff[0] * data[i-1];
  93899. data[i] = residual[i] + (sum >> lp_quantization);
  93900. }
  93901. }
  93902. else { /* order == 7 */
  93903. for(i = 0; i < (int)data_len; i++) {
  93904. sum = 0;
  93905. sum += qlp_coeff[6] * data[i-7];
  93906. sum += qlp_coeff[5] * data[i-6];
  93907. sum += qlp_coeff[4] * data[i-5];
  93908. sum += qlp_coeff[3] * data[i-4];
  93909. sum += qlp_coeff[2] * data[i-3];
  93910. sum += qlp_coeff[1] * data[i-2];
  93911. sum += qlp_coeff[0] * data[i-1];
  93912. data[i] = residual[i] + (sum >> lp_quantization);
  93913. }
  93914. }
  93915. }
  93916. else {
  93917. if(order == 6) {
  93918. for(i = 0; i < (int)data_len; i++) {
  93919. sum = 0;
  93920. sum += qlp_coeff[5] * data[i-6];
  93921. sum += qlp_coeff[4] * data[i-5];
  93922. sum += qlp_coeff[3] * data[i-4];
  93923. sum += qlp_coeff[2] * data[i-3];
  93924. sum += qlp_coeff[1] * data[i-2];
  93925. sum += qlp_coeff[0] * data[i-1];
  93926. data[i] = residual[i] + (sum >> lp_quantization);
  93927. }
  93928. }
  93929. else { /* order == 5 */
  93930. for(i = 0; i < (int)data_len; i++) {
  93931. sum = 0;
  93932. sum += qlp_coeff[4] * data[i-5];
  93933. sum += qlp_coeff[3] * data[i-4];
  93934. sum += qlp_coeff[2] * data[i-3];
  93935. sum += qlp_coeff[1] * data[i-2];
  93936. sum += qlp_coeff[0] * data[i-1];
  93937. data[i] = residual[i] + (sum >> lp_quantization);
  93938. }
  93939. }
  93940. }
  93941. }
  93942. else {
  93943. if(order > 2) {
  93944. if(order == 4) {
  93945. for(i = 0; i < (int)data_len; i++) {
  93946. sum = 0;
  93947. sum += qlp_coeff[3] * data[i-4];
  93948. sum += qlp_coeff[2] * data[i-3];
  93949. sum += qlp_coeff[1] * data[i-2];
  93950. sum += qlp_coeff[0] * data[i-1];
  93951. data[i] = residual[i] + (sum >> lp_quantization);
  93952. }
  93953. }
  93954. else { /* order == 3 */
  93955. for(i = 0; i < (int)data_len; i++) {
  93956. sum = 0;
  93957. sum += qlp_coeff[2] * data[i-3];
  93958. sum += qlp_coeff[1] * data[i-2];
  93959. sum += qlp_coeff[0] * data[i-1];
  93960. data[i] = residual[i] + (sum >> lp_quantization);
  93961. }
  93962. }
  93963. }
  93964. else {
  93965. if(order == 2) {
  93966. for(i = 0; i < (int)data_len; i++) {
  93967. sum = 0;
  93968. sum += qlp_coeff[1] * data[i-2];
  93969. sum += qlp_coeff[0] * data[i-1];
  93970. data[i] = residual[i] + (sum >> lp_quantization);
  93971. }
  93972. }
  93973. else { /* order == 1 */
  93974. for(i = 0; i < (int)data_len; i++)
  93975. data[i] = residual[i] + ((qlp_coeff[0] * data[i-1]) >> lp_quantization);
  93976. }
  93977. }
  93978. }
  93979. }
  93980. else { /* order > 12 */
  93981. for(i = 0; i < (int)data_len; i++) {
  93982. sum = 0;
  93983. switch(order) {
  93984. case 32: sum += qlp_coeff[31] * data[i-32];
  93985. case 31: sum += qlp_coeff[30] * data[i-31];
  93986. case 30: sum += qlp_coeff[29] * data[i-30];
  93987. case 29: sum += qlp_coeff[28] * data[i-29];
  93988. case 28: sum += qlp_coeff[27] * data[i-28];
  93989. case 27: sum += qlp_coeff[26] * data[i-27];
  93990. case 26: sum += qlp_coeff[25] * data[i-26];
  93991. case 25: sum += qlp_coeff[24] * data[i-25];
  93992. case 24: sum += qlp_coeff[23] * data[i-24];
  93993. case 23: sum += qlp_coeff[22] * data[i-23];
  93994. case 22: sum += qlp_coeff[21] * data[i-22];
  93995. case 21: sum += qlp_coeff[20] * data[i-21];
  93996. case 20: sum += qlp_coeff[19] * data[i-20];
  93997. case 19: sum += qlp_coeff[18] * data[i-19];
  93998. case 18: sum += qlp_coeff[17] * data[i-18];
  93999. case 17: sum += qlp_coeff[16] * data[i-17];
  94000. case 16: sum += qlp_coeff[15] * data[i-16];
  94001. case 15: sum += qlp_coeff[14] * data[i-15];
  94002. case 14: sum += qlp_coeff[13] * data[i-14];
  94003. case 13: sum += qlp_coeff[12] * data[i-13];
  94004. sum += qlp_coeff[11] * data[i-12];
  94005. sum += qlp_coeff[10] * data[i-11];
  94006. sum += qlp_coeff[ 9] * data[i-10];
  94007. sum += qlp_coeff[ 8] * data[i- 9];
  94008. sum += qlp_coeff[ 7] * data[i- 8];
  94009. sum += qlp_coeff[ 6] * data[i- 7];
  94010. sum += qlp_coeff[ 5] * data[i- 6];
  94011. sum += qlp_coeff[ 4] * data[i- 5];
  94012. sum += qlp_coeff[ 3] * data[i- 4];
  94013. sum += qlp_coeff[ 2] * data[i- 3];
  94014. sum += qlp_coeff[ 1] * data[i- 2];
  94015. sum += qlp_coeff[ 0] * data[i- 1];
  94016. }
  94017. data[i] = residual[i] + (sum >> lp_quantization);
  94018. }
  94019. }
  94020. }
  94021. #endif
  94022. 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[])
  94023. #if defined(FLAC__OVERFLOW_DETECT) || !defined(FLAC__LPC_UNROLLED_FILTER_LOOPS)
  94024. {
  94025. unsigned i, j;
  94026. FLAC__int64 sum;
  94027. const FLAC__int32 *r = residual, *history;
  94028. #ifdef FLAC__OVERFLOW_DETECT_VERBOSE
  94029. fprintf(stderr,"FLAC__lpc_restore_signal_wide: data_len=%d, order=%u, lpq=%d",data_len,order,lp_quantization);
  94030. for(i=0;i<order;i++)
  94031. fprintf(stderr,", q[%u]=%d",i,qlp_coeff[i]);
  94032. fprintf(stderr,"\n");
  94033. #endif
  94034. FLAC__ASSERT(order > 0);
  94035. for(i = 0; i < data_len; i++) {
  94036. sum = 0;
  94037. history = data;
  94038. for(j = 0; j < order; j++)
  94039. sum += (FLAC__int64)qlp_coeff[j] * (FLAC__int64)(*(--history));
  94040. if(FLAC__bitmath_silog2_wide(sum >> lp_quantization) > 32) {
  94041. #ifdef _MSC_VER
  94042. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%I64d\n", i, sum >> lp_quantization);
  94043. #else
  94044. fprintf(stderr,"FLAC__lpc_restore_signal_wide: OVERFLOW, i=%u, sum=%lld\n", i, (long long)(sum >> lp_quantization));
  94045. #endif
  94046. break;
  94047. }
  94048. if(FLAC__bitmath_silog2_wide((FLAC__int64)(*r) + (sum >> lp_quantization)) > 32) {
  94049. #ifdef _MSC_VER
  94050. 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));
  94051. #else
  94052. 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)));
  94053. #endif
  94054. break;
  94055. }
  94056. *(data++) = *(r++) + (FLAC__int32)(sum >> lp_quantization);
  94057. }
  94058. }
  94059. #else /* fully unrolled version for normal use */
  94060. {
  94061. int i;
  94062. FLAC__int64 sum;
  94063. FLAC__ASSERT(order > 0);
  94064. FLAC__ASSERT(order <= 32);
  94065. /*
  94066. * We do unique versions up to 12th order since that's the subset limit.
  94067. * Also they are roughly ordered to match frequency of occurrence to
  94068. * minimize branching.
  94069. */
  94070. if(order <= 12) {
  94071. if(order > 8) {
  94072. if(order > 10) {
  94073. if(order == 12) {
  94074. for(i = 0; i < (int)data_len; i++) {
  94075. sum = 0;
  94076. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94077. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94078. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94079. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94080. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94081. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94082. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94083. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94084. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94085. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94086. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94087. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94088. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94089. }
  94090. }
  94091. else { /* order == 11 */
  94092. for(i = 0; i < (int)data_len; i++) {
  94093. sum = 0;
  94094. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94095. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94096. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94097. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94098. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94099. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94100. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94101. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94102. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94103. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94104. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94105. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94106. }
  94107. }
  94108. }
  94109. else {
  94110. if(order == 10) {
  94111. for(i = 0; i < (int)data_len; i++) {
  94112. sum = 0;
  94113. sum += qlp_coeff[9] * (FLAC__int64)data[i-10];
  94114. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94115. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94116. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94117. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94118. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94119. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94120. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94121. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94122. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94123. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94124. }
  94125. }
  94126. else { /* order == 9 */
  94127. for(i = 0; i < (int)data_len; i++) {
  94128. sum = 0;
  94129. sum += qlp_coeff[8] * (FLAC__int64)data[i-9];
  94130. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94131. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94132. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94133. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94134. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94135. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94136. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94137. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94138. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94139. }
  94140. }
  94141. }
  94142. }
  94143. else if(order > 4) {
  94144. if(order > 6) {
  94145. if(order == 8) {
  94146. for(i = 0; i < (int)data_len; i++) {
  94147. sum = 0;
  94148. sum += qlp_coeff[7] * (FLAC__int64)data[i-8];
  94149. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94150. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94151. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94152. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94153. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94154. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94155. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94156. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94157. }
  94158. }
  94159. else { /* order == 7 */
  94160. for(i = 0; i < (int)data_len; i++) {
  94161. sum = 0;
  94162. sum += qlp_coeff[6] * (FLAC__int64)data[i-7];
  94163. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94164. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94165. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94166. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94167. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94168. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94169. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94170. }
  94171. }
  94172. }
  94173. else {
  94174. if(order == 6) {
  94175. for(i = 0; i < (int)data_len; i++) {
  94176. sum = 0;
  94177. sum += qlp_coeff[5] * (FLAC__int64)data[i-6];
  94178. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94179. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94180. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94181. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94182. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94183. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94184. }
  94185. }
  94186. else { /* order == 5 */
  94187. for(i = 0; i < (int)data_len; i++) {
  94188. sum = 0;
  94189. sum += qlp_coeff[4] * (FLAC__int64)data[i-5];
  94190. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94191. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94192. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94193. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94194. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94195. }
  94196. }
  94197. }
  94198. }
  94199. else {
  94200. if(order > 2) {
  94201. if(order == 4) {
  94202. for(i = 0; i < (int)data_len; i++) {
  94203. sum = 0;
  94204. sum += qlp_coeff[3] * (FLAC__int64)data[i-4];
  94205. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94206. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94207. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94208. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94209. }
  94210. }
  94211. else { /* order == 3 */
  94212. for(i = 0; i < (int)data_len; i++) {
  94213. sum = 0;
  94214. sum += qlp_coeff[2] * (FLAC__int64)data[i-3];
  94215. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94216. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94217. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94218. }
  94219. }
  94220. }
  94221. else {
  94222. if(order == 2) {
  94223. for(i = 0; i < (int)data_len; i++) {
  94224. sum = 0;
  94225. sum += qlp_coeff[1] * (FLAC__int64)data[i-2];
  94226. sum += qlp_coeff[0] * (FLAC__int64)data[i-1];
  94227. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94228. }
  94229. }
  94230. else { /* order == 1 */
  94231. for(i = 0; i < (int)data_len; i++)
  94232. data[i] = residual[i] + (FLAC__int32)((qlp_coeff[0] * (FLAC__int64)data[i-1]) >> lp_quantization);
  94233. }
  94234. }
  94235. }
  94236. }
  94237. else { /* order > 12 */
  94238. for(i = 0; i < (int)data_len; i++) {
  94239. sum = 0;
  94240. switch(order) {
  94241. case 32: sum += qlp_coeff[31] * (FLAC__int64)data[i-32];
  94242. case 31: sum += qlp_coeff[30] * (FLAC__int64)data[i-31];
  94243. case 30: sum += qlp_coeff[29] * (FLAC__int64)data[i-30];
  94244. case 29: sum += qlp_coeff[28] * (FLAC__int64)data[i-29];
  94245. case 28: sum += qlp_coeff[27] * (FLAC__int64)data[i-28];
  94246. case 27: sum += qlp_coeff[26] * (FLAC__int64)data[i-27];
  94247. case 26: sum += qlp_coeff[25] * (FLAC__int64)data[i-26];
  94248. case 25: sum += qlp_coeff[24] * (FLAC__int64)data[i-25];
  94249. case 24: sum += qlp_coeff[23] * (FLAC__int64)data[i-24];
  94250. case 23: sum += qlp_coeff[22] * (FLAC__int64)data[i-23];
  94251. case 22: sum += qlp_coeff[21] * (FLAC__int64)data[i-22];
  94252. case 21: sum += qlp_coeff[20] * (FLAC__int64)data[i-21];
  94253. case 20: sum += qlp_coeff[19] * (FLAC__int64)data[i-20];
  94254. case 19: sum += qlp_coeff[18] * (FLAC__int64)data[i-19];
  94255. case 18: sum += qlp_coeff[17] * (FLAC__int64)data[i-18];
  94256. case 17: sum += qlp_coeff[16] * (FLAC__int64)data[i-17];
  94257. case 16: sum += qlp_coeff[15] * (FLAC__int64)data[i-16];
  94258. case 15: sum += qlp_coeff[14] * (FLAC__int64)data[i-15];
  94259. case 14: sum += qlp_coeff[13] * (FLAC__int64)data[i-14];
  94260. case 13: sum += qlp_coeff[12] * (FLAC__int64)data[i-13];
  94261. sum += qlp_coeff[11] * (FLAC__int64)data[i-12];
  94262. sum += qlp_coeff[10] * (FLAC__int64)data[i-11];
  94263. sum += qlp_coeff[ 9] * (FLAC__int64)data[i-10];
  94264. sum += qlp_coeff[ 8] * (FLAC__int64)data[i- 9];
  94265. sum += qlp_coeff[ 7] * (FLAC__int64)data[i- 8];
  94266. sum += qlp_coeff[ 6] * (FLAC__int64)data[i- 7];
  94267. sum += qlp_coeff[ 5] * (FLAC__int64)data[i- 6];
  94268. sum += qlp_coeff[ 4] * (FLAC__int64)data[i- 5];
  94269. sum += qlp_coeff[ 3] * (FLAC__int64)data[i- 4];
  94270. sum += qlp_coeff[ 2] * (FLAC__int64)data[i- 3];
  94271. sum += qlp_coeff[ 1] * (FLAC__int64)data[i- 2];
  94272. sum += qlp_coeff[ 0] * (FLAC__int64)data[i- 1];
  94273. }
  94274. data[i] = residual[i] + (FLAC__int32)(sum >> lp_quantization);
  94275. }
  94276. }
  94277. }
  94278. #endif
  94279. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  94280. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample(FLAC__double lpc_error, unsigned total_samples)
  94281. {
  94282. FLAC__double error_scale;
  94283. FLAC__ASSERT(total_samples > 0);
  94284. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  94285. return FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(lpc_error, error_scale);
  94286. }
  94287. FLAC__double FLAC__lpc_compute_expected_bits_per_residual_sample_with_error_scale(FLAC__double lpc_error, FLAC__double error_scale)
  94288. {
  94289. if(lpc_error > 0.0) {
  94290. FLAC__double bps = (FLAC__double)0.5 * log(error_scale * lpc_error) / M_LN2;
  94291. if(bps >= 0.0)
  94292. return bps;
  94293. else
  94294. return 0.0;
  94295. }
  94296. else if(lpc_error < 0.0) { /* error should not be negative but can happen due to inadequate floating-point resolution */
  94297. return 1e32;
  94298. }
  94299. else {
  94300. return 0.0;
  94301. }
  94302. }
  94303. unsigned FLAC__lpc_compute_best_order(const FLAC__double lpc_error[], unsigned max_order, unsigned total_samples, unsigned overhead_bits_per_order)
  94304. {
  94305. 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 */
  94306. FLAC__double bits, best_bits, error_scale;
  94307. FLAC__ASSERT(max_order > 0);
  94308. FLAC__ASSERT(total_samples > 0);
  94309. error_scale = 0.5 * M_LN2 * M_LN2 / (FLAC__double)total_samples;
  94310. best_index = 0;
  94311. best_bits = (unsigned)(-1);
  94312. for(index = 0, order = 1; index < max_order; index++, order++) {
  94313. 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);
  94314. if(bits < best_bits) {
  94315. best_index = index;
  94316. best_bits = bits;
  94317. }
  94318. }
  94319. return best_index+1; /* +1 since index of lpc_error[] is order-1 */
  94320. }
  94321. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  94322. #endif
  94323. /********* End of inlined file: lpc_flac.c *********/
  94324. /********* Start of inlined file: md5.c *********/
  94325. /********* Start of inlined file: juce_FlacHeader.h *********/
  94326. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94327. // tasks..
  94328. /********* Start of inlined file: juce_Config.h *********/
  94329. #ifndef __JUCE_CONFIG_JUCEHEADER__
  94330. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  94331. /*
  94332. This file contains macros that enable/disable various JUCE features.
  94333. */
  94334. /** The name of the namespace that all Juce classes and functions will be
  94335. put inside. If this is not defined, no namespace will be used.
  94336. */
  94337. #ifndef JUCE_NAMESPACE
  94338. #define JUCE_NAMESPACE juce
  94339. #endif
  94340. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  94341. but if you define this value, you can override this can force it to be true or
  94342. false.
  94343. */
  94344. #ifndef JUCE_FORCE_DEBUG
  94345. //#define JUCE_FORCE_DEBUG 1
  94346. #endif
  94347. /** If this flag is enabled, the the jassert and jassertfalse macros will
  94348. always use Logger::writeToLog() to write a message when an assertion happens.
  94349. Enabling it will also leave this turned on in release builds. When it's disabled,
  94350. however, the jassert and jassertfalse macros will not be compiled in a
  94351. release build.
  94352. @see jassert, jassertfalse, Logger
  94353. */
  94354. #ifndef JUCE_LOG_ASSERTIONS
  94355. // #define JUCE_LOG_ASSERTIONS 1
  94356. #endif
  94357. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  94358. which the ASIOAudioIODevice class can't be built. See the comments in the
  94359. ASIOAudioIODevice class's header file for more info about this.
  94360. (This only affects a Win32 build)
  94361. */
  94362. #ifndef JUCE_ASIO
  94363. #define JUCE_ASIO 1
  94364. #endif
  94365. /** Comment out this macro to disable building of ALSA device support on Linux.
  94366. */
  94367. #ifndef JUCE_ALSA
  94368. #define JUCE_ALSA 1
  94369. #endif
  94370. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  94371. have the SDK installed.
  94372. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  94373. classes will be unavailable.
  94374. On Windows, if you enable this, you'll need to have the QuickTime SDK
  94375. installed, and its header files will need to be on your include path.
  94376. */
  94377. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  94378. #define JUCE_QUICKTIME 1
  94379. #endif
  94380. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  94381. have the appropriate headers and libraries available. If it's not enabled, the
  94382. OpenGLComponent class will be unavailable.
  94383. */
  94384. #ifndef JUCE_OPENGL
  94385. #define JUCE_OPENGL 1
  94386. #endif
  94387. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  94388. If you're not going to need either of these formats, turn off the flags to
  94389. avoid bloating your codebase with them.
  94390. */
  94391. #ifndef JUCE_USE_FLAC
  94392. #define JUCE_USE_FLAC 1
  94393. #endif
  94394. #ifndef JUCE_USE_OGGVORBIS
  94395. #define JUCE_USE_OGGVORBIS 1
  94396. #endif
  94397. /** This flag lets you enable support for CD-burning. You might want to disable
  94398. it to build without the MS SDK under windows.
  94399. */
  94400. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  94401. #define JUCE_USE_CDBURNER 1
  94402. #endif
  94403. /** Enabling this macro means that all regions that get repainted will have a coloured
  94404. line drawn around them.
  94405. This is handy if you're trying to optimise drawing, because it lets you easily see
  94406. when anything is being repainted unnecessarily.
  94407. */
  94408. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  94409. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  94410. #endif
  94411. /** Enable this under Linux to use Xinerama for multi-monitor support.
  94412. */
  94413. #ifndef JUCE_USE_XINERAMA
  94414. #define JUCE_USE_XINERAMA 1
  94415. #endif
  94416. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  94417. */
  94418. #ifndef JUCE_USE_XSHM
  94419. #define JUCE_USE_XSHM 1
  94420. #endif
  94421. /** Enabling this builds support for VST audio plugins.
  94422. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  94423. */
  94424. #ifndef JUCE_PLUGINHOST_VST
  94425. // #define JUCE_PLUGINHOST_VST 1
  94426. #endif
  94427. /** Enabling this builds support for AudioUnit audio plugins.
  94428. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  94429. */
  94430. #ifndef JUCE_PLUGINHOST_AU
  94431. // #define JUCE_PLUGINHOST_AU 1
  94432. #endif
  94433. /** Disabling this will avoid linking to any UI code. This is handy for
  94434. writing command-line utilities, e.g. on linux boxes which don't have some
  94435. of the UI libraries installed.
  94436. (On mac and windows, this won't generally make much difference to the build).
  94437. */
  94438. #ifndef JUCE_BUILD_GUI_CLASSES
  94439. #define JUCE_BUILD_GUI_CLASSES 1
  94440. #endif
  94441. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  94442. */
  94443. #ifndef JUCE_WEB_BROWSER
  94444. #define JUCE_WEB_BROWSER 1
  94445. #endif
  94446. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  94447. codebase - you might need to use this if you're linking to some of these libraries
  94448. yourself.
  94449. */
  94450. #ifndef JUCE_INCLUDE_ZLIB_CODE
  94451. #define JUCE_INCLUDE_ZLIB_CODE 1
  94452. #endif
  94453. #ifndef JUCE_INCLUDE_FLAC_CODE
  94454. #define JUCE_INCLUDE_FLAC_CODE 1
  94455. #endif
  94456. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  94457. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  94458. #endif
  94459. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  94460. #define JUCE_INCLUDE_PNGLIB_CODE 1
  94461. #endif
  94462. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  94463. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  94464. #endif
  94465. /** Enable this to add extra memory-leak info to the new and delete operators.
  94466. (Currently, this only affects Windows builds in debug mode).
  94467. */
  94468. #ifndef JUCE_CHECK_MEMORY_LEAKS
  94469. #define JUCE_CHECK_MEMORY_LEAKS 1
  94470. #endif
  94471. /** Enable this to turn on juce's internal catching of exceptions.
  94472. Turning it off will avoid any exception catching. With it on, all exceptions
  94473. are passed to the JUCEApplication::unhandledException() callback for logging.
  94474. */
  94475. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  94476. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  94477. #endif
  94478. /** If this macro is set, the Juce String class will use unicode as its
  94479. internal representation. If it isn't set, it'll use ANSI.
  94480. */
  94481. #ifndef JUCE_STRINGS_ARE_UNICODE
  94482. #define JUCE_STRINGS_ARE_UNICODE 1
  94483. #endif
  94484. #endif
  94485. /********* End of inlined file: juce_Config.h *********/
  94486. #define VERSION "1.2.1"
  94487. #define FLAC__NO_DLL 1
  94488. #ifdef _MSC_VER
  94489. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  94490. #endif
  94491. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  94492. #define FLAC__SYS_DARWIN 1
  94493. #endif
  94494. /********* End of inlined file: juce_FlacHeader.h *********/
  94495. #if JUCE_USE_FLAC
  94496. #if HAVE_CONFIG_H
  94497. # include <config.h>
  94498. #endif
  94499. #include <stdlib.h> /* for malloc() */
  94500. #include <string.h> /* for memcpy() */
  94501. /********* Start of inlined file: md5.h *********/
  94502. #ifndef FLAC__PRIVATE__MD5_H
  94503. #define FLAC__PRIVATE__MD5_H
  94504. /*
  94505. * This is the header file for the MD5 message-digest algorithm.
  94506. * The algorithm is due to Ron Rivest. This code was
  94507. * written by Colin Plumb in 1993, no copyright is claimed.
  94508. * This code is in the public domain; do with it what you wish.
  94509. *
  94510. * Equivalent code is available from RSA Data Security, Inc.
  94511. * This code has been tested against that, and is equivalent,
  94512. * except that you don't need to include two pages of legalese
  94513. * with every copy.
  94514. *
  94515. * To compute the message digest of a chunk of bytes, declare an
  94516. * MD5Context structure, pass it to MD5Init, call MD5Update as
  94517. * needed on buffers full of bytes, and then call MD5Final, which
  94518. * will fill a supplied 16-byte array with the digest.
  94519. *
  94520. * Changed so as no longer to depend on Colin Plumb's `usual.h'
  94521. * header definitions; now uses stuff from dpkg's config.h
  94522. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  94523. * Still in the public domain.
  94524. *
  94525. * Josh Coalson: made some changes to integrate with libFLAC.
  94526. * Still in the public domain, with no warranty.
  94527. */
  94528. typedef struct {
  94529. FLAC__uint32 in[16];
  94530. FLAC__uint32 buf[4];
  94531. FLAC__uint32 bytes[2];
  94532. FLAC__byte *internal_buf;
  94533. size_t capacity;
  94534. } FLAC__MD5Context;
  94535. void FLAC__MD5Init(FLAC__MD5Context *context);
  94536. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *context);
  94537. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample);
  94538. #endif
  94539. /********* End of inlined file: md5.h *********/
  94540. #ifndef FLaC__INLINE
  94541. #define FLaC__INLINE
  94542. #endif
  94543. /*
  94544. * This code implements the MD5 message-digest algorithm.
  94545. * The algorithm is due to Ron Rivest. This code was
  94546. * written by Colin Plumb in 1993, no copyright is claimed.
  94547. * This code is in the public domain; do with it what you wish.
  94548. *
  94549. * Equivalent code is available from RSA Data Security, Inc.
  94550. * This code has been tested against that, and is equivalent,
  94551. * except that you don't need to include two pages of legalese
  94552. * with every copy.
  94553. *
  94554. * To compute the message digest of a chunk of bytes, declare an
  94555. * MD5Context structure, pass it to MD5Init, call MD5Update as
  94556. * needed on buffers full of bytes, and then call MD5Final, which
  94557. * will fill a supplied 16-byte array with the digest.
  94558. *
  94559. * Changed so as no longer to depend on Colin Plumb's `usual.h' header
  94560. * definitions; now uses stuff from dpkg's config.h.
  94561. * - Ian Jackson <ijackson@nyx.cs.du.edu>.
  94562. * Still in the public domain.
  94563. *
  94564. * Josh Coalson: made some changes to integrate with libFLAC.
  94565. * Still in the public domain.
  94566. */
  94567. /* The four core functions - F1 is optimized somewhat */
  94568. /* #define F1(x, y, z) (x & y | ~x & z) */
  94569. #define F1(x, y, z) (z ^ (x & (y ^ z)))
  94570. #define F2(x, y, z) F1(z, x, y)
  94571. #define F3(x, y, z) (x ^ y ^ z)
  94572. #define F4(x, y, z) (y ^ (x | ~z))
  94573. /* This is the central step in the MD5 algorithm. */
  94574. #define MD5STEP(f,w,x,y,z,in,s) \
  94575. (w += f(x,y,z) + in, w = (w<<s | w>>(32-s)) + x)
  94576. /*
  94577. * The core of the MD5 algorithm, this alters an existing MD5 hash to
  94578. * reflect the addition of 16 longwords of new data. MD5Update blocks
  94579. * the data and converts bytes into longwords for this routine.
  94580. */
  94581. static void FLAC__MD5Transform(FLAC__uint32 buf[4], FLAC__uint32 const in[16])
  94582. {
  94583. register FLAC__uint32 a, b, c, d;
  94584. a = buf[0];
  94585. b = buf[1];
  94586. c = buf[2];
  94587. d = buf[3];
  94588. MD5STEP(F1, a, b, c, d, in[0] + 0xd76aa478, 7);
  94589. MD5STEP(F1, d, a, b, c, in[1] + 0xe8c7b756, 12);
  94590. MD5STEP(F1, c, d, a, b, in[2] + 0x242070db, 17);
  94591. MD5STEP(F1, b, c, d, a, in[3] + 0xc1bdceee, 22);
  94592. MD5STEP(F1, a, b, c, d, in[4] + 0xf57c0faf, 7);
  94593. MD5STEP(F1, d, a, b, c, in[5] + 0x4787c62a, 12);
  94594. MD5STEP(F1, c, d, a, b, in[6] + 0xa8304613, 17);
  94595. MD5STEP(F1, b, c, d, a, in[7] + 0xfd469501, 22);
  94596. MD5STEP(F1, a, b, c, d, in[8] + 0x698098d8, 7);
  94597. MD5STEP(F1, d, a, b, c, in[9] + 0x8b44f7af, 12);
  94598. MD5STEP(F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
  94599. MD5STEP(F1, b, c, d, a, in[11] + 0x895cd7be, 22);
  94600. MD5STEP(F1, a, b, c, d, in[12] + 0x6b901122, 7);
  94601. MD5STEP(F1, d, a, b, c, in[13] + 0xfd987193, 12);
  94602. MD5STEP(F1, c, d, a, b, in[14] + 0xa679438e, 17);
  94603. MD5STEP(F1, b, c, d, a, in[15] + 0x49b40821, 22);
  94604. MD5STEP(F2, a, b, c, d, in[1] + 0xf61e2562, 5);
  94605. MD5STEP(F2, d, a, b, c, in[6] + 0xc040b340, 9);
  94606. MD5STEP(F2, c, d, a, b, in[11] + 0x265e5a51, 14);
  94607. MD5STEP(F2, b, c, d, a, in[0] + 0xe9b6c7aa, 20);
  94608. MD5STEP(F2, a, b, c, d, in[5] + 0xd62f105d, 5);
  94609. MD5STEP(F2, d, a, b, c, in[10] + 0x02441453, 9);
  94610. MD5STEP(F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
  94611. MD5STEP(F2, b, c, d, a, in[4] + 0xe7d3fbc8, 20);
  94612. MD5STEP(F2, a, b, c, d, in[9] + 0x21e1cde6, 5);
  94613. MD5STEP(F2, d, a, b, c, in[14] + 0xc33707d6, 9);
  94614. MD5STEP(F2, c, d, a, b, in[3] + 0xf4d50d87, 14);
  94615. MD5STEP(F2, b, c, d, a, in[8] + 0x455a14ed, 20);
  94616. MD5STEP(F2, a, b, c, d, in[13] + 0xa9e3e905, 5);
  94617. MD5STEP(F2, d, a, b, c, in[2] + 0xfcefa3f8, 9);
  94618. MD5STEP(F2, c, d, a, b, in[7] + 0x676f02d9, 14);
  94619. MD5STEP(F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
  94620. MD5STEP(F3, a, b, c, d, in[5] + 0xfffa3942, 4);
  94621. MD5STEP(F3, d, a, b, c, in[8] + 0x8771f681, 11);
  94622. MD5STEP(F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
  94623. MD5STEP(F3, b, c, d, a, in[14] + 0xfde5380c, 23);
  94624. MD5STEP(F3, a, b, c, d, in[1] + 0xa4beea44, 4);
  94625. MD5STEP(F3, d, a, b, c, in[4] + 0x4bdecfa9, 11);
  94626. MD5STEP(F3, c, d, a, b, in[7] + 0xf6bb4b60, 16);
  94627. MD5STEP(F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
  94628. MD5STEP(F3, a, b, c, d, in[13] + 0x289b7ec6, 4);
  94629. MD5STEP(F3, d, a, b, c, in[0] + 0xeaa127fa, 11);
  94630. MD5STEP(F3, c, d, a, b, in[3] + 0xd4ef3085, 16);
  94631. MD5STEP(F3, b, c, d, a, in[6] + 0x04881d05, 23);
  94632. MD5STEP(F3, a, b, c, d, in[9] + 0xd9d4d039, 4);
  94633. MD5STEP(F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
  94634. MD5STEP(F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
  94635. MD5STEP(F3, b, c, d, a, in[2] + 0xc4ac5665, 23);
  94636. MD5STEP(F4, a, b, c, d, in[0] + 0xf4292244, 6);
  94637. MD5STEP(F4, d, a, b, c, in[7] + 0x432aff97, 10);
  94638. MD5STEP(F4, c, d, a, b, in[14] + 0xab9423a7, 15);
  94639. MD5STEP(F4, b, c, d, a, in[5] + 0xfc93a039, 21);
  94640. MD5STEP(F4, a, b, c, d, in[12] + 0x655b59c3, 6);
  94641. MD5STEP(F4, d, a, b, c, in[3] + 0x8f0ccc92, 10);
  94642. MD5STEP(F4, c, d, a, b, in[10] + 0xffeff47d, 15);
  94643. MD5STEP(F4, b, c, d, a, in[1] + 0x85845dd1, 21);
  94644. MD5STEP(F4, a, b, c, d, in[8] + 0x6fa87e4f, 6);
  94645. MD5STEP(F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
  94646. MD5STEP(F4, c, d, a, b, in[6] + 0xa3014314, 15);
  94647. MD5STEP(F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
  94648. MD5STEP(F4, a, b, c, d, in[4] + 0xf7537e82, 6);
  94649. MD5STEP(F4, d, a, b, c, in[11] + 0xbd3af235, 10);
  94650. MD5STEP(F4, c, d, a, b, in[2] + 0x2ad7d2bb, 15);
  94651. MD5STEP(F4, b, c, d, a, in[9] + 0xeb86d391, 21);
  94652. buf[0] += a;
  94653. buf[1] += b;
  94654. buf[2] += c;
  94655. buf[3] += d;
  94656. }
  94657. #if WORDS_BIGENDIAN
  94658. //@@@@@@ OPT: use bswap/intrinsics
  94659. static void byteSwap(FLAC__uint32 *buf, unsigned words)
  94660. {
  94661. register FLAC__uint32 x;
  94662. do {
  94663. x = *buf;
  94664. x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff);
  94665. *buf++ = (x >> 16) | (x << 16);
  94666. } while (--words);
  94667. }
  94668. static void byteSwapX16(FLAC__uint32 *buf)
  94669. {
  94670. register FLAC__uint32 x;
  94671. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94672. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94673. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94674. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94675. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94676. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94677. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94678. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94679. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94680. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94681. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94682. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94683. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94684. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94685. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf++ = (x >> 16) | (x << 16);
  94686. x = *buf; x = ((x << 8) & 0xff00ff00) | ((x >> 8) & 0x00ff00ff); *buf = (x >> 16) | (x << 16);
  94687. }
  94688. #else
  94689. #define byteSwap(buf, words)
  94690. #define byteSwapX16(buf)
  94691. #endif
  94692. /*
  94693. * Update context to reflect the concatenation of another buffer full
  94694. * of bytes.
  94695. */
  94696. static void FLAC__MD5Update(FLAC__MD5Context *ctx, FLAC__byte const *buf, unsigned len)
  94697. {
  94698. FLAC__uint32 t;
  94699. /* Update byte count */
  94700. t = ctx->bytes[0];
  94701. if ((ctx->bytes[0] = t + len) < t)
  94702. ctx->bytes[1]++; /* Carry from low to high */
  94703. t = 64 - (t & 0x3f); /* Space available in ctx->in (at least 1) */
  94704. if (t > len) {
  94705. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, len);
  94706. return;
  94707. }
  94708. /* First chunk is an odd size */
  94709. memcpy((FLAC__byte *)ctx->in + 64 - t, buf, t);
  94710. byteSwapX16(ctx->in);
  94711. FLAC__MD5Transform(ctx->buf, ctx->in);
  94712. buf += t;
  94713. len -= t;
  94714. /* Process data in 64-byte chunks */
  94715. while (len >= 64) {
  94716. memcpy(ctx->in, buf, 64);
  94717. byteSwapX16(ctx->in);
  94718. FLAC__MD5Transform(ctx->buf, ctx->in);
  94719. buf += 64;
  94720. len -= 64;
  94721. }
  94722. /* Handle any remaining bytes of data. */
  94723. memcpy(ctx->in, buf, len);
  94724. }
  94725. /*
  94726. * Start MD5 accumulation. Set bit count to 0 and buffer to mysterious
  94727. * initialization constants.
  94728. */
  94729. void FLAC__MD5Init(FLAC__MD5Context *ctx)
  94730. {
  94731. ctx->buf[0] = 0x67452301;
  94732. ctx->buf[1] = 0xefcdab89;
  94733. ctx->buf[2] = 0x98badcfe;
  94734. ctx->buf[3] = 0x10325476;
  94735. ctx->bytes[0] = 0;
  94736. ctx->bytes[1] = 0;
  94737. ctx->internal_buf = 0;
  94738. ctx->capacity = 0;
  94739. }
  94740. /*
  94741. * Final wrapup - pad to 64-byte boundary with the bit pattern
  94742. * 1 0* (64-bit count of bits processed, MSB-first)
  94743. */
  94744. void FLAC__MD5Final(FLAC__byte digest[16], FLAC__MD5Context *ctx)
  94745. {
  94746. int count = ctx->bytes[0] & 0x3f; /* Number of bytes in ctx->in */
  94747. FLAC__byte *p = (FLAC__byte *)ctx->in + count;
  94748. /* Set the first char of padding to 0x80. There is always room. */
  94749. *p++ = 0x80;
  94750. /* Bytes of padding needed to make 56 bytes (-8..55) */
  94751. count = 56 - 1 - count;
  94752. if (count < 0) { /* Padding forces an extra block */
  94753. memset(p, 0, count + 8);
  94754. byteSwapX16(ctx->in);
  94755. FLAC__MD5Transform(ctx->buf, ctx->in);
  94756. p = (FLAC__byte *)ctx->in;
  94757. count = 56;
  94758. }
  94759. memset(p, 0, count);
  94760. byteSwap(ctx->in, 14);
  94761. /* Append length in bits and transform */
  94762. ctx->in[14] = ctx->bytes[0] << 3;
  94763. ctx->in[15] = ctx->bytes[1] << 3 | ctx->bytes[0] >> 29;
  94764. FLAC__MD5Transform(ctx->buf, ctx->in);
  94765. byteSwap(ctx->buf, 4);
  94766. memcpy(digest, ctx->buf, 16);
  94767. memset(ctx, 0, sizeof(ctx)); /* In case it's sensitive */
  94768. if(0 != ctx->internal_buf) {
  94769. free(ctx->internal_buf);
  94770. ctx->internal_buf = 0;
  94771. ctx->capacity = 0;
  94772. }
  94773. }
  94774. /*
  94775. * Convert the incoming audio signal to a byte stream
  94776. */
  94777. static void format_input_(FLAC__byte *buf, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  94778. {
  94779. unsigned channel, sample;
  94780. register FLAC__int32 a_word;
  94781. register FLAC__byte *buf_ = buf;
  94782. #if WORDS_BIGENDIAN
  94783. #else
  94784. if(channels == 2 && bytes_per_sample == 2) {
  94785. FLAC__int16 *buf1_ = ((FLAC__int16*)buf_) + 1;
  94786. memcpy(buf_, signal[0], sizeof(FLAC__int32) * samples);
  94787. for(sample = 0; sample < samples; sample++, buf1_+=2)
  94788. *buf1_ = (FLAC__int16)signal[1][sample];
  94789. }
  94790. else if(channels == 1 && bytes_per_sample == 2) {
  94791. FLAC__int16 *buf1_ = (FLAC__int16*)buf_;
  94792. for(sample = 0; sample < samples; sample++)
  94793. *buf1_++ = (FLAC__int16)signal[0][sample];
  94794. }
  94795. else
  94796. #endif
  94797. if(bytes_per_sample == 2) {
  94798. if(channels == 2) {
  94799. for(sample = 0; sample < samples; sample++) {
  94800. a_word = signal[0][sample];
  94801. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94802. *buf_++ = (FLAC__byte)a_word;
  94803. a_word = signal[1][sample];
  94804. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94805. *buf_++ = (FLAC__byte)a_word;
  94806. }
  94807. }
  94808. else if(channels == 1) {
  94809. for(sample = 0; sample < samples; sample++) {
  94810. a_word = signal[0][sample];
  94811. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94812. *buf_++ = (FLAC__byte)a_word;
  94813. }
  94814. }
  94815. else {
  94816. for(sample = 0; sample < samples; sample++) {
  94817. for(channel = 0; channel < channels; channel++) {
  94818. a_word = signal[channel][sample];
  94819. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94820. *buf_++ = (FLAC__byte)a_word;
  94821. }
  94822. }
  94823. }
  94824. }
  94825. else if(bytes_per_sample == 3) {
  94826. if(channels == 2) {
  94827. for(sample = 0; sample < samples; sample++) {
  94828. a_word = signal[0][sample];
  94829. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94830. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94831. *buf_++ = (FLAC__byte)a_word;
  94832. a_word = signal[1][sample];
  94833. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94834. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94835. *buf_++ = (FLAC__byte)a_word;
  94836. }
  94837. }
  94838. else if(channels == 1) {
  94839. for(sample = 0; sample < samples; sample++) {
  94840. a_word = signal[0][sample];
  94841. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94842. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94843. *buf_++ = (FLAC__byte)a_word;
  94844. }
  94845. }
  94846. else {
  94847. for(sample = 0; sample < samples; sample++) {
  94848. for(channel = 0; channel < channels; channel++) {
  94849. a_word = signal[channel][sample];
  94850. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94851. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94852. *buf_++ = (FLAC__byte)a_word;
  94853. }
  94854. }
  94855. }
  94856. }
  94857. else if(bytes_per_sample == 1) {
  94858. if(channels == 2) {
  94859. for(sample = 0; sample < samples; sample++) {
  94860. a_word = signal[0][sample];
  94861. *buf_++ = (FLAC__byte)a_word;
  94862. a_word = signal[1][sample];
  94863. *buf_++ = (FLAC__byte)a_word;
  94864. }
  94865. }
  94866. else if(channels == 1) {
  94867. for(sample = 0; sample < samples; sample++) {
  94868. a_word = signal[0][sample];
  94869. *buf_++ = (FLAC__byte)a_word;
  94870. }
  94871. }
  94872. else {
  94873. for(sample = 0; sample < samples; sample++) {
  94874. for(channel = 0; channel < channels; channel++) {
  94875. a_word = signal[channel][sample];
  94876. *buf_++ = (FLAC__byte)a_word;
  94877. }
  94878. }
  94879. }
  94880. }
  94881. else { /* bytes_per_sample == 4, maybe optimize more later */
  94882. for(sample = 0; sample < samples; sample++) {
  94883. for(channel = 0; channel < channels; channel++) {
  94884. a_word = signal[channel][sample];
  94885. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94886. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94887. *buf_++ = (FLAC__byte)a_word; a_word >>= 8;
  94888. *buf_++ = (FLAC__byte)a_word;
  94889. }
  94890. }
  94891. }
  94892. }
  94893. /*
  94894. * Convert the incoming audio signal to a byte stream and FLAC__MD5Update it.
  94895. */
  94896. FLAC__bool FLAC__MD5Accumulate(FLAC__MD5Context *ctx, const FLAC__int32 * const signal[], unsigned channels, unsigned samples, unsigned bytes_per_sample)
  94897. {
  94898. const size_t bytes_needed = (size_t)channels * (size_t)samples * (size_t)bytes_per_sample;
  94899. /* overflow check */
  94900. if((size_t)channels > SIZE_MAX / (size_t)bytes_per_sample)
  94901. return false;
  94902. if((size_t)channels * (size_t)bytes_per_sample > SIZE_MAX / (size_t)samples)
  94903. return false;
  94904. if(ctx->capacity < bytes_needed) {
  94905. FLAC__byte *tmp = (FLAC__byte*)realloc(ctx->internal_buf, bytes_needed);
  94906. if(0 == tmp) {
  94907. free(ctx->internal_buf);
  94908. if(0 == (ctx->internal_buf = (FLAC__byte*)safe_malloc_(bytes_needed)))
  94909. return false;
  94910. }
  94911. ctx->internal_buf = tmp;
  94912. ctx->capacity = bytes_needed;
  94913. }
  94914. format_input_(ctx->internal_buf, signal, channels, samples, bytes_per_sample);
  94915. FLAC__MD5Update(ctx, ctx->internal_buf, bytes_needed);
  94916. return true;
  94917. }
  94918. #endif
  94919. /********* End of inlined file: md5.c *********/
  94920. /********* Start of inlined file: memory.c *********/
  94921. /********* Start of inlined file: juce_FlacHeader.h *********/
  94922. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  94923. // tasks..
  94924. /********* Start of inlined file: juce_Config.h *********/
  94925. #ifndef __JUCE_CONFIG_JUCEHEADER__
  94926. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  94927. /*
  94928. This file contains macros that enable/disable various JUCE features.
  94929. */
  94930. /** The name of the namespace that all Juce classes and functions will be
  94931. put inside. If this is not defined, no namespace will be used.
  94932. */
  94933. #ifndef JUCE_NAMESPACE
  94934. #define JUCE_NAMESPACE juce
  94935. #endif
  94936. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  94937. but if you define this value, you can override this can force it to be true or
  94938. false.
  94939. */
  94940. #ifndef JUCE_FORCE_DEBUG
  94941. //#define JUCE_FORCE_DEBUG 1
  94942. #endif
  94943. /** If this flag is enabled, the the jassert and jassertfalse macros will
  94944. always use Logger::writeToLog() to write a message when an assertion happens.
  94945. Enabling it will also leave this turned on in release builds. When it's disabled,
  94946. however, the jassert and jassertfalse macros will not be compiled in a
  94947. release build.
  94948. @see jassert, jassertfalse, Logger
  94949. */
  94950. #ifndef JUCE_LOG_ASSERTIONS
  94951. // #define JUCE_LOG_ASSERTIONS 1
  94952. #endif
  94953. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  94954. which the ASIOAudioIODevice class can't be built. See the comments in the
  94955. ASIOAudioIODevice class's header file for more info about this.
  94956. (This only affects a Win32 build)
  94957. */
  94958. #ifndef JUCE_ASIO
  94959. #define JUCE_ASIO 1
  94960. #endif
  94961. /** Comment out this macro to disable building of ALSA device support on Linux.
  94962. */
  94963. #ifndef JUCE_ALSA
  94964. #define JUCE_ALSA 1
  94965. #endif
  94966. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  94967. have the SDK installed.
  94968. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  94969. classes will be unavailable.
  94970. On Windows, if you enable this, you'll need to have the QuickTime SDK
  94971. installed, and its header files will need to be on your include path.
  94972. */
  94973. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  94974. #define JUCE_QUICKTIME 1
  94975. #endif
  94976. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  94977. have the appropriate headers and libraries available. If it's not enabled, the
  94978. OpenGLComponent class will be unavailable.
  94979. */
  94980. #ifndef JUCE_OPENGL
  94981. #define JUCE_OPENGL 1
  94982. #endif
  94983. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  94984. If you're not going to need either of these formats, turn off the flags to
  94985. avoid bloating your codebase with them.
  94986. */
  94987. #ifndef JUCE_USE_FLAC
  94988. #define JUCE_USE_FLAC 1
  94989. #endif
  94990. #ifndef JUCE_USE_OGGVORBIS
  94991. #define JUCE_USE_OGGVORBIS 1
  94992. #endif
  94993. /** This flag lets you enable support for CD-burning. You might want to disable
  94994. it to build without the MS SDK under windows.
  94995. */
  94996. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  94997. #define JUCE_USE_CDBURNER 1
  94998. #endif
  94999. /** Enabling this macro means that all regions that get repainted will have a coloured
  95000. line drawn around them.
  95001. This is handy if you're trying to optimise drawing, because it lets you easily see
  95002. when anything is being repainted unnecessarily.
  95003. */
  95004. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  95005. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  95006. #endif
  95007. /** Enable this under Linux to use Xinerama for multi-monitor support.
  95008. */
  95009. #ifndef JUCE_USE_XINERAMA
  95010. #define JUCE_USE_XINERAMA 1
  95011. #endif
  95012. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  95013. */
  95014. #ifndef JUCE_USE_XSHM
  95015. #define JUCE_USE_XSHM 1
  95016. #endif
  95017. /** Enabling this builds support for VST audio plugins.
  95018. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  95019. */
  95020. #ifndef JUCE_PLUGINHOST_VST
  95021. // #define JUCE_PLUGINHOST_VST 1
  95022. #endif
  95023. /** Enabling this builds support for AudioUnit audio plugins.
  95024. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  95025. */
  95026. #ifndef JUCE_PLUGINHOST_AU
  95027. // #define JUCE_PLUGINHOST_AU 1
  95028. #endif
  95029. /** Disabling this will avoid linking to any UI code. This is handy for
  95030. writing command-line utilities, e.g. on linux boxes which don't have some
  95031. of the UI libraries installed.
  95032. (On mac and windows, this won't generally make much difference to the build).
  95033. */
  95034. #ifndef JUCE_BUILD_GUI_CLASSES
  95035. #define JUCE_BUILD_GUI_CLASSES 1
  95036. #endif
  95037. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  95038. */
  95039. #ifndef JUCE_WEB_BROWSER
  95040. #define JUCE_WEB_BROWSER 1
  95041. #endif
  95042. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  95043. codebase - you might need to use this if you're linking to some of these libraries
  95044. yourself.
  95045. */
  95046. #ifndef JUCE_INCLUDE_ZLIB_CODE
  95047. #define JUCE_INCLUDE_ZLIB_CODE 1
  95048. #endif
  95049. #ifndef JUCE_INCLUDE_FLAC_CODE
  95050. #define JUCE_INCLUDE_FLAC_CODE 1
  95051. #endif
  95052. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  95053. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  95054. #endif
  95055. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  95056. #define JUCE_INCLUDE_PNGLIB_CODE 1
  95057. #endif
  95058. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  95059. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  95060. #endif
  95061. /** Enable this to add extra memory-leak info to the new and delete operators.
  95062. (Currently, this only affects Windows builds in debug mode).
  95063. */
  95064. #ifndef JUCE_CHECK_MEMORY_LEAKS
  95065. #define JUCE_CHECK_MEMORY_LEAKS 1
  95066. #endif
  95067. /** Enable this to turn on juce's internal catching of exceptions.
  95068. Turning it off will avoid any exception catching. With it on, all exceptions
  95069. are passed to the JUCEApplication::unhandledException() callback for logging.
  95070. */
  95071. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  95072. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  95073. #endif
  95074. /** If this macro is set, the Juce String class will use unicode as its
  95075. internal representation. If it isn't set, it'll use ANSI.
  95076. */
  95077. #ifndef JUCE_STRINGS_ARE_UNICODE
  95078. #define JUCE_STRINGS_ARE_UNICODE 1
  95079. #endif
  95080. #endif
  95081. /********* End of inlined file: juce_Config.h *********/
  95082. #define VERSION "1.2.1"
  95083. #define FLAC__NO_DLL 1
  95084. #ifdef _MSC_VER
  95085. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95086. #endif
  95087. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  95088. #define FLAC__SYS_DARWIN 1
  95089. #endif
  95090. /********* End of inlined file: juce_FlacHeader.h *********/
  95091. #if JUCE_USE_FLAC
  95092. #if HAVE_CONFIG_H
  95093. # include <config.h>
  95094. #endif
  95095. /********* Start of inlined file: memory.h *********/
  95096. #ifndef FLAC__PRIVATE__MEMORY_H
  95097. #define FLAC__PRIVATE__MEMORY_H
  95098. #ifdef HAVE_CONFIG_H
  95099. #include <config.h>
  95100. #endif
  95101. #include <stdlib.h> /* for size_t */
  95102. /* Returns the unaligned address returned by malloc.
  95103. * Use free() on this address to deallocate.
  95104. */
  95105. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address);
  95106. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer);
  95107. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer);
  95108. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer);
  95109. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer);
  95110. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95111. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer);
  95112. #endif
  95113. #endif
  95114. /********* End of inlined file: memory.h *********/
  95115. void *FLAC__memory_alloc_aligned(size_t bytes, void **aligned_address)
  95116. {
  95117. void *x;
  95118. FLAC__ASSERT(0 != aligned_address);
  95119. #ifdef FLAC__ALIGN_MALLOC_DATA
  95120. /* align on 32-byte (256-bit) boundary */
  95121. x = safe_malloc_add_2op_(bytes, /*+*/31);
  95122. #ifdef SIZEOF_VOIDP
  95123. #if SIZEOF_VOIDP == 4
  95124. /* could do *aligned_address = x + ((unsigned) (32 - (((unsigned)x) & 31))) & 31; */
  95125. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  95126. #elif SIZEOF_VOIDP == 8
  95127. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  95128. #else
  95129. # error Unsupported sizeof(void*)
  95130. #endif
  95131. #else
  95132. /* there's got to be a better way to do this right for all archs */
  95133. if(sizeof(void*) == sizeof(unsigned))
  95134. *aligned_address = (void*)(((unsigned)x + 31) & -32);
  95135. else if(sizeof(void*) == sizeof(FLAC__uint64))
  95136. *aligned_address = (void*)(((FLAC__uint64)x + 31) & (FLAC__uint64)(-((FLAC__int64)32)));
  95137. else
  95138. return 0;
  95139. #endif
  95140. #else
  95141. x = safe_malloc_(bytes);
  95142. *aligned_address = x;
  95143. #endif
  95144. return x;
  95145. }
  95146. FLAC__bool FLAC__memory_alloc_aligned_int32_array(unsigned elements, FLAC__int32 **unaligned_pointer, FLAC__int32 **aligned_pointer)
  95147. {
  95148. FLAC__int32 *pu; /* unaligned pointer */
  95149. union { /* union needed to comply with C99 pointer aliasing rules */
  95150. FLAC__int32 *pa; /* aligned pointer */
  95151. void *pv; /* aligned pointer alias */
  95152. } u;
  95153. FLAC__ASSERT(elements > 0);
  95154. FLAC__ASSERT(0 != unaligned_pointer);
  95155. FLAC__ASSERT(0 != aligned_pointer);
  95156. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95157. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  95158. return false;
  95159. pu = (FLAC__int32*)FLAC__memory_alloc_aligned(sizeof(*pu) * (size_t)elements, &u.pv);
  95160. if(0 == pu) {
  95161. return false;
  95162. }
  95163. else {
  95164. if(*unaligned_pointer != 0)
  95165. free(*unaligned_pointer);
  95166. *unaligned_pointer = pu;
  95167. *aligned_pointer = u.pa;
  95168. return true;
  95169. }
  95170. }
  95171. FLAC__bool FLAC__memory_alloc_aligned_uint32_array(unsigned elements, FLAC__uint32 **unaligned_pointer, FLAC__uint32 **aligned_pointer)
  95172. {
  95173. FLAC__uint32 *pu; /* unaligned pointer */
  95174. union { /* union needed to comply with C99 pointer aliasing rules */
  95175. FLAC__uint32 *pa; /* aligned pointer */
  95176. void *pv; /* aligned pointer alias */
  95177. } u;
  95178. FLAC__ASSERT(elements > 0);
  95179. FLAC__ASSERT(0 != unaligned_pointer);
  95180. FLAC__ASSERT(0 != aligned_pointer);
  95181. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95182. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  95183. return false;
  95184. pu = (FLAC__uint32*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95185. if(0 == pu) {
  95186. return false;
  95187. }
  95188. else {
  95189. if(*unaligned_pointer != 0)
  95190. free(*unaligned_pointer);
  95191. *unaligned_pointer = pu;
  95192. *aligned_pointer = u.pa;
  95193. return true;
  95194. }
  95195. }
  95196. FLAC__bool FLAC__memory_alloc_aligned_uint64_array(unsigned elements, FLAC__uint64 **unaligned_pointer, FLAC__uint64 **aligned_pointer)
  95197. {
  95198. FLAC__uint64 *pu; /* unaligned pointer */
  95199. union { /* union needed to comply with C99 pointer aliasing rules */
  95200. FLAC__uint64 *pa; /* aligned pointer */
  95201. void *pv; /* aligned pointer alias */
  95202. } u;
  95203. FLAC__ASSERT(elements > 0);
  95204. FLAC__ASSERT(0 != unaligned_pointer);
  95205. FLAC__ASSERT(0 != aligned_pointer);
  95206. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95207. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  95208. return false;
  95209. pu = (FLAC__uint64*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95210. if(0 == pu) {
  95211. return false;
  95212. }
  95213. else {
  95214. if(*unaligned_pointer != 0)
  95215. free(*unaligned_pointer);
  95216. *unaligned_pointer = pu;
  95217. *aligned_pointer = u.pa;
  95218. return true;
  95219. }
  95220. }
  95221. FLAC__bool FLAC__memory_alloc_aligned_unsigned_array(unsigned elements, unsigned **unaligned_pointer, unsigned **aligned_pointer)
  95222. {
  95223. unsigned *pu; /* unaligned pointer */
  95224. union { /* union needed to comply with C99 pointer aliasing rules */
  95225. unsigned *pa; /* aligned pointer */
  95226. void *pv; /* aligned pointer alias */
  95227. } u;
  95228. FLAC__ASSERT(elements > 0);
  95229. FLAC__ASSERT(0 != unaligned_pointer);
  95230. FLAC__ASSERT(0 != aligned_pointer);
  95231. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95232. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  95233. return false;
  95234. pu = (unsigned*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95235. if(0 == pu) {
  95236. return false;
  95237. }
  95238. else {
  95239. if(*unaligned_pointer != 0)
  95240. free(*unaligned_pointer);
  95241. *unaligned_pointer = pu;
  95242. *aligned_pointer = u.pa;
  95243. return true;
  95244. }
  95245. }
  95246. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  95247. FLAC__bool FLAC__memory_alloc_aligned_real_array(unsigned elements, FLAC__real **unaligned_pointer, FLAC__real **aligned_pointer)
  95248. {
  95249. FLAC__real *pu; /* unaligned pointer */
  95250. union { /* union needed to comply with C99 pointer aliasing rules */
  95251. FLAC__real *pa; /* aligned pointer */
  95252. void *pv; /* aligned pointer alias */
  95253. } u;
  95254. FLAC__ASSERT(elements > 0);
  95255. FLAC__ASSERT(0 != unaligned_pointer);
  95256. FLAC__ASSERT(0 != aligned_pointer);
  95257. FLAC__ASSERT(unaligned_pointer != aligned_pointer);
  95258. if((size_t)elements > SIZE_MAX / sizeof(*pu)) /* overflow check */
  95259. return false;
  95260. pu = (FLAC__real*)FLAC__memory_alloc_aligned(sizeof(*pu) * elements, &u.pv);
  95261. if(0 == pu) {
  95262. return false;
  95263. }
  95264. else {
  95265. if(*unaligned_pointer != 0)
  95266. free(*unaligned_pointer);
  95267. *unaligned_pointer = pu;
  95268. *aligned_pointer = u.pa;
  95269. return true;
  95270. }
  95271. }
  95272. #endif
  95273. #endif
  95274. /********* End of inlined file: memory.c *********/
  95275. /********* Start of inlined file: stream_decoder.c *********/
  95276. /********* Start of inlined file: juce_FlacHeader.h *********/
  95277. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  95278. // tasks..
  95279. /********* Start of inlined file: juce_Config.h *********/
  95280. #ifndef __JUCE_CONFIG_JUCEHEADER__
  95281. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  95282. /*
  95283. This file contains macros that enable/disable various JUCE features.
  95284. */
  95285. /** The name of the namespace that all Juce classes and functions will be
  95286. put inside. If this is not defined, no namespace will be used.
  95287. */
  95288. #ifndef JUCE_NAMESPACE
  95289. #define JUCE_NAMESPACE juce
  95290. #endif
  95291. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  95292. but if you define this value, you can override this can force it to be true or
  95293. false.
  95294. */
  95295. #ifndef JUCE_FORCE_DEBUG
  95296. //#define JUCE_FORCE_DEBUG 1
  95297. #endif
  95298. /** If this flag is enabled, the the jassert and jassertfalse macros will
  95299. always use Logger::writeToLog() to write a message when an assertion happens.
  95300. Enabling it will also leave this turned on in release builds. When it's disabled,
  95301. however, the jassert and jassertfalse macros will not be compiled in a
  95302. release build.
  95303. @see jassert, jassertfalse, Logger
  95304. */
  95305. #ifndef JUCE_LOG_ASSERTIONS
  95306. // #define JUCE_LOG_ASSERTIONS 1
  95307. #endif
  95308. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  95309. which the ASIOAudioIODevice class can't be built. See the comments in the
  95310. ASIOAudioIODevice class's header file for more info about this.
  95311. (This only affects a Win32 build)
  95312. */
  95313. #ifndef JUCE_ASIO
  95314. #define JUCE_ASIO 1
  95315. #endif
  95316. /** Comment out this macro to disable building of ALSA device support on Linux.
  95317. */
  95318. #ifndef JUCE_ALSA
  95319. #define JUCE_ALSA 1
  95320. #endif
  95321. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  95322. have the SDK installed.
  95323. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  95324. classes will be unavailable.
  95325. On Windows, if you enable this, you'll need to have the QuickTime SDK
  95326. installed, and its header files will need to be on your include path.
  95327. */
  95328. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  95329. #define JUCE_QUICKTIME 1
  95330. #endif
  95331. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  95332. have the appropriate headers and libraries available. If it's not enabled, the
  95333. OpenGLComponent class will be unavailable.
  95334. */
  95335. #ifndef JUCE_OPENGL
  95336. #define JUCE_OPENGL 1
  95337. #endif
  95338. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  95339. If you're not going to need either of these formats, turn off the flags to
  95340. avoid bloating your codebase with them.
  95341. */
  95342. #ifndef JUCE_USE_FLAC
  95343. #define JUCE_USE_FLAC 1
  95344. #endif
  95345. #ifndef JUCE_USE_OGGVORBIS
  95346. #define JUCE_USE_OGGVORBIS 1
  95347. #endif
  95348. /** This flag lets you enable support for CD-burning. You might want to disable
  95349. it to build without the MS SDK under windows.
  95350. */
  95351. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  95352. #define JUCE_USE_CDBURNER 1
  95353. #endif
  95354. /** Enabling this macro means that all regions that get repainted will have a coloured
  95355. line drawn around them.
  95356. This is handy if you're trying to optimise drawing, because it lets you easily see
  95357. when anything is being repainted unnecessarily.
  95358. */
  95359. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  95360. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  95361. #endif
  95362. /** Enable this under Linux to use Xinerama for multi-monitor support.
  95363. */
  95364. #ifndef JUCE_USE_XINERAMA
  95365. #define JUCE_USE_XINERAMA 1
  95366. #endif
  95367. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  95368. */
  95369. #ifndef JUCE_USE_XSHM
  95370. #define JUCE_USE_XSHM 1
  95371. #endif
  95372. /** Enabling this builds support for VST audio plugins.
  95373. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  95374. */
  95375. #ifndef JUCE_PLUGINHOST_VST
  95376. // #define JUCE_PLUGINHOST_VST 1
  95377. #endif
  95378. /** Enabling this builds support for AudioUnit audio plugins.
  95379. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  95380. */
  95381. #ifndef JUCE_PLUGINHOST_AU
  95382. // #define JUCE_PLUGINHOST_AU 1
  95383. #endif
  95384. /** Disabling this will avoid linking to any UI code. This is handy for
  95385. writing command-line utilities, e.g. on linux boxes which don't have some
  95386. of the UI libraries installed.
  95387. (On mac and windows, this won't generally make much difference to the build).
  95388. */
  95389. #ifndef JUCE_BUILD_GUI_CLASSES
  95390. #define JUCE_BUILD_GUI_CLASSES 1
  95391. #endif
  95392. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  95393. */
  95394. #ifndef JUCE_WEB_BROWSER
  95395. #define JUCE_WEB_BROWSER 1
  95396. #endif
  95397. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  95398. codebase - you might need to use this if you're linking to some of these libraries
  95399. yourself.
  95400. */
  95401. #ifndef JUCE_INCLUDE_ZLIB_CODE
  95402. #define JUCE_INCLUDE_ZLIB_CODE 1
  95403. #endif
  95404. #ifndef JUCE_INCLUDE_FLAC_CODE
  95405. #define JUCE_INCLUDE_FLAC_CODE 1
  95406. #endif
  95407. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  95408. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  95409. #endif
  95410. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  95411. #define JUCE_INCLUDE_PNGLIB_CODE 1
  95412. #endif
  95413. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  95414. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  95415. #endif
  95416. /** Enable this to add extra memory-leak info to the new and delete operators.
  95417. (Currently, this only affects Windows builds in debug mode).
  95418. */
  95419. #ifndef JUCE_CHECK_MEMORY_LEAKS
  95420. #define JUCE_CHECK_MEMORY_LEAKS 1
  95421. #endif
  95422. /** Enable this to turn on juce's internal catching of exceptions.
  95423. Turning it off will avoid any exception catching. With it on, all exceptions
  95424. are passed to the JUCEApplication::unhandledException() callback for logging.
  95425. */
  95426. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  95427. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  95428. #endif
  95429. /** If this macro is set, the Juce String class will use unicode as its
  95430. internal representation. If it isn't set, it'll use ANSI.
  95431. */
  95432. #ifndef JUCE_STRINGS_ARE_UNICODE
  95433. #define JUCE_STRINGS_ARE_UNICODE 1
  95434. #endif
  95435. #endif
  95436. /********* End of inlined file: juce_Config.h *********/
  95437. #define VERSION "1.2.1"
  95438. #define FLAC__NO_DLL 1
  95439. #ifdef _MSC_VER
  95440. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  95441. #endif
  95442. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  95443. #define FLAC__SYS_DARWIN 1
  95444. #endif
  95445. /********* End of inlined file: juce_FlacHeader.h *********/
  95446. #if JUCE_USE_FLAC
  95447. #if HAVE_CONFIG_H
  95448. # include <config.h>
  95449. #endif
  95450. #if defined _MSC_VER || defined __MINGW32__
  95451. #include <io.h> /* for _setmode() */
  95452. #include <fcntl.h> /* for _O_BINARY */
  95453. #endif
  95454. #if defined __CYGWIN__ || defined __EMX__
  95455. #include <io.h> /* for setmode(), O_BINARY */
  95456. #include <fcntl.h> /* for _O_BINARY */
  95457. #endif
  95458. #include <stdio.h>
  95459. #include <stdlib.h> /* for malloc() */
  95460. #include <string.h> /* for memset/memcpy() */
  95461. #include <sys/stat.h> /* for stat() */
  95462. #include <sys/types.h> /* for off_t */
  95463. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  95464. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  95465. #define fseeko fseek
  95466. #define ftello ftell
  95467. #endif
  95468. #endif
  95469. /********* Start of inlined file: stream_decoder.h *********/
  95470. #ifndef FLAC__PROTECTED__STREAM_DECODER_H
  95471. #define FLAC__PROTECTED__STREAM_DECODER_H
  95472. #if FLAC__HAS_OGG
  95473. #include "include/private/ogg_decoder_aspect.h"
  95474. #endif
  95475. typedef struct FLAC__StreamDecoderProtected {
  95476. FLAC__StreamDecoderState state;
  95477. unsigned channels;
  95478. FLAC__ChannelAssignment channel_assignment;
  95479. unsigned bits_per_sample;
  95480. unsigned sample_rate; /* in Hz */
  95481. unsigned blocksize; /* in samples (per channel) */
  95482. FLAC__bool md5_checking; /* if true, generate MD5 signature of decoded data and compare against signature in the STREAMINFO metadata block */
  95483. #if FLAC__HAS_OGG
  95484. FLAC__OggDecoderAspect ogg_decoder_aspect;
  95485. #endif
  95486. } FLAC__StreamDecoderProtected;
  95487. /*
  95488. * return the number of input bytes consumed
  95489. */
  95490. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder);
  95491. #endif
  95492. /********* End of inlined file: stream_decoder.h *********/
  95493. #ifdef max
  95494. #undef max
  95495. #endif
  95496. #define max(a,b) ((a)>(b)?(a):(b))
  95497. /* adjust for compilers that can't understand using LLU suffix for uint64_t literals */
  95498. #ifdef _MSC_VER
  95499. #define FLAC__U64L(x) x
  95500. #else
  95501. #define FLAC__U64L(x) x##LLU
  95502. #endif
  95503. /* technically this should be in an "export.c" but this is convenient enough */
  95504. FLAC_API int FLAC_API_SUPPORTS_OGG_FLAC =
  95505. #if FLAC__HAS_OGG
  95506. 1
  95507. #else
  95508. 0
  95509. #endif
  95510. ;
  95511. /***********************************************************************
  95512. *
  95513. * Private static data
  95514. *
  95515. ***********************************************************************/
  95516. static FLAC__byte ID3V2_TAG_[3] = { 'I', 'D', '3' };
  95517. /***********************************************************************
  95518. *
  95519. * Private class method prototypes
  95520. *
  95521. ***********************************************************************/
  95522. static void set_defaults_dec(FLAC__StreamDecoder *decoder);
  95523. static FILE *get_binary_stdin_(void);
  95524. static FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels);
  95525. static FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id);
  95526. static FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder);
  95527. static FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder);
  95528. static FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  95529. static FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length);
  95530. static FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj);
  95531. static FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj);
  95532. static FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj);
  95533. static FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder);
  95534. static FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder);
  95535. static FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode);
  95536. static FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder);
  95537. static FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  95538. static FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  95539. static FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  95540. static FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode);
  95541. static FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode);
  95542. 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);
  95543. static FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder);
  95544. static FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data);
  95545. #if FLAC__HAS_OGG
  95546. static FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes);
  95547. static FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  95548. #endif
  95549. static FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[]);
  95550. static void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status);
  95551. static FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  95552. #if FLAC__HAS_OGG
  95553. static FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample);
  95554. #endif
  95555. static FLAC__StreamDecoderReadStatus file_read_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  95556. static FLAC__StreamDecoderSeekStatus file_seek_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  95557. static FLAC__StreamDecoderTellStatus file_tell_callback_dec (const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  95558. static FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data);
  95559. static FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data);
  95560. /***********************************************************************
  95561. *
  95562. * Private class data
  95563. *
  95564. ***********************************************************************/
  95565. typedef struct FLAC__StreamDecoderPrivate {
  95566. #if FLAC__HAS_OGG
  95567. FLAC__bool is_ogg;
  95568. #endif
  95569. FLAC__StreamDecoderReadCallback read_callback;
  95570. FLAC__StreamDecoderSeekCallback seek_callback;
  95571. FLAC__StreamDecoderTellCallback tell_callback;
  95572. FLAC__StreamDecoderLengthCallback length_callback;
  95573. FLAC__StreamDecoderEofCallback eof_callback;
  95574. FLAC__StreamDecoderWriteCallback write_callback;
  95575. FLAC__StreamDecoderMetadataCallback metadata_callback;
  95576. FLAC__StreamDecoderErrorCallback error_callback;
  95577. /* generic 32-bit datapath: */
  95578. 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[]);
  95579. /* generic 64-bit datapath: */
  95580. 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[]);
  95581. /* for use when the signal is <= 16 bits-per-sample, or <= 15 bits-per-sample on a side channel (which requires 1 extra bit): */
  95582. 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[]);
  95583. /* 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: */
  95584. 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[]);
  95585. FLAC__bool (*local_bitreader_read_rice_signed_block)(FLAC__BitReader *br, int* vals, unsigned nvals, unsigned parameter);
  95586. void *client_data;
  95587. FILE *file; /* only used if FLAC__stream_decoder_init_file()/FLAC__stream_decoder_init_file() called, else NULL */
  95588. FLAC__BitReader *input;
  95589. FLAC__int32 *output[FLAC__MAX_CHANNELS];
  95590. FLAC__int32 *residual[FLAC__MAX_CHANNELS]; /* WATCHOUT: these are the aligned pointers; the real pointers that should be free()'d are residual_unaligned[] below */
  95591. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents[FLAC__MAX_CHANNELS];
  95592. unsigned output_capacity, output_channels;
  95593. FLAC__uint32 fixed_block_size, next_fixed_block_size;
  95594. FLAC__uint64 samples_decoded;
  95595. FLAC__bool has_stream_info, has_seek_table;
  95596. FLAC__StreamMetadata stream_info;
  95597. FLAC__StreamMetadata seek_table;
  95598. FLAC__bool metadata_filter[128]; /* MAGIC number 128 == total number of metadata block types == 1 << 7 */
  95599. FLAC__byte *metadata_filter_ids;
  95600. size_t metadata_filter_ids_count, metadata_filter_ids_capacity; /* units for both are IDs, not bytes */
  95601. FLAC__Frame frame;
  95602. FLAC__bool cached; /* true if there is a byte in lookahead */
  95603. FLAC__CPUInfo cpuinfo;
  95604. FLAC__byte header_warmup[2]; /* contains the sync code and reserved bits */
  95605. FLAC__byte lookahead; /* temp storage when we need to look ahead one byte in the stream */
  95606. /* unaligned (original) pointers to allocated data */
  95607. FLAC__int32 *residual_unaligned[FLAC__MAX_CHANNELS];
  95608. 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 */
  95609. FLAC__bool internal_reset_hack; /* used only during init() so we can call reset to set up the decoder without rewinding the input */
  95610. FLAC__bool is_seeking;
  95611. FLAC__MD5Context md5context;
  95612. FLAC__byte computed_md5sum[16]; /* this is the sum we computed from the decoded data */
  95613. /* (the rest of these are only used for seeking) */
  95614. FLAC__Frame last_frame; /* holds the info of the last frame we seeked to */
  95615. FLAC__uint64 first_frame_offset; /* hint to the seek routine of where in the stream the first audio frame starts */
  95616. FLAC__uint64 target_sample;
  95617. unsigned unparseable_frame_count; /* used to tell whether we're decoding a future version of FLAC or just got a bad sync */
  95618. #if FLAC__HAS_OGG
  95619. FLAC__bool got_a_frame; /* hack needed in Ogg FLAC seek routine to check when process_single() actually writes a frame */
  95620. #endif
  95621. } FLAC__StreamDecoderPrivate;
  95622. /***********************************************************************
  95623. *
  95624. * Public static class data
  95625. *
  95626. ***********************************************************************/
  95627. FLAC_API const char * const FLAC__StreamDecoderStateString[] = {
  95628. "FLAC__STREAM_DECODER_SEARCH_FOR_METADATA",
  95629. "FLAC__STREAM_DECODER_READ_METADATA",
  95630. "FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC",
  95631. "FLAC__STREAM_DECODER_READ_FRAME",
  95632. "FLAC__STREAM_DECODER_END_OF_STREAM",
  95633. "FLAC__STREAM_DECODER_OGG_ERROR",
  95634. "FLAC__STREAM_DECODER_SEEK_ERROR",
  95635. "FLAC__STREAM_DECODER_ABORTED",
  95636. "FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR",
  95637. "FLAC__STREAM_DECODER_UNINITIALIZED"
  95638. };
  95639. FLAC_API const char * const FLAC__StreamDecoderInitStatusString[] = {
  95640. "FLAC__STREAM_DECODER_INIT_STATUS_OK",
  95641. "FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  95642. "FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS",
  95643. "FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR",
  95644. "FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE",
  95645. "FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED"
  95646. };
  95647. FLAC_API const char * const FLAC__StreamDecoderReadStatusString[] = {
  95648. "FLAC__STREAM_DECODER_READ_STATUS_CONTINUE",
  95649. "FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM",
  95650. "FLAC__STREAM_DECODER_READ_STATUS_ABORT"
  95651. };
  95652. FLAC_API const char * const FLAC__StreamDecoderSeekStatusString[] = {
  95653. "FLAC__STREAM_DECODER_SEEK_STATUS_OK",
  95654. "FLAC__STREAM_DECODER_SEEK_STATUS_ERROR",
  95655. "FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED"
  95656. };
  95657. FLAC_API const char * const FLAC__StreamDecoderTellStatusString[] = {
  95658. "FLAC__STREAM_DECODER_TELL_STATUS_OK",
  95659. "FLAC__STREAM_DECODER_TELL_STATUS_ERROR",
  95660. "FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED"
  95661. };
  95662. FLAC_API const char * const FLAC__StreamDecoderLengthStatusString[] = {
  95663. "FLAC__STREAM_DECODER_LENGTH_STATUS_OK",
  95664. "FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR",
  95665. "FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED"
  95666. };
  95667. FLAC_API const char * const FLAC__StreamDecoderWriteStatusString[] = {
  95668. "FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE",
  95669. "FLAC__STREAM_DECODER_WRITE_STATUS_ABORT"
  95670. };
  95671. FLAC_API const char * const FLAC__StreamDecoderErrorStatusString[] = {
  95672. "FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC",
  95673. "FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER",
  95674. "FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH",
  95675. "FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM"
  95676. };
  95677. /***********************************************************************
  95678. *
  95679. * Class constructor/destructor
  95680. *
  95681. ***********************************************************************/
  95682. FLAC_API FLAC__StreamDecoder *FLAC__stream_decoder_new(void)
  95683. {
  95684. FLAC__StreamDecoder *decoder;
  95685. unsigned i;
  95686. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  95687. decoder = (FLAC__StreamDecoder*)calloc(1, sizeof(FLAC__StreamDecoder));
  95688. if(decoder == 0) {
  95689. return 0;
  95690. }
  95691. decoder->protected_ = (FLAC__StreamDecoderProtected*)calloc(1, sizeof(FLAC__StreamDecoderProtected));
  95692. if(decoder->protected_ == 0) {
  95693. free(decoder);
  95694. return 0;
  95695. }
  95696. decoder->private_ = (FLAC__StreamDecoderPrivate*)calloc(1, sizeof(FLAC__StreamDecoderPrivate));
  95697. if(decoder->private_ == 0) {
  95698. free(decoder->protected_);
  95699. free(decoder);
  95700. return 0;
  95701. }
  95702. decoder->private_->input = FLAC__bitreader_new();
  95703. if(decoder->private_->input == 0) {
  95704. free(decoder->private_);
  95705. free(decoder->protected_);
  95706. free(decoder);
  95707. return 0;
  95708. }
  95709. decoder->private_->metadata_filter_ids_capacity = 16;
  95710. if(0 == (decoder->private_->metadata_filter_ids = (FLAC__byte*)malloc((FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) * decoder->private_->metadata_filter_ids_capacity))) {
  95711. FLAC__bitreader_delete(decoder->private_->input);
  95712. free(decoder->private_);
  95713. free(decoder->protected_);
  95714. free(decoder);
  95715. return 0;
  95716. }
  95717. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  95718. decoder->private_->output[i] = 0;
  95719. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  95720. }
  95721. decoder->private_->output_capacity = 0;
  95722. decoder->private_->output_channels = 0;
  95723. decoder->private_->has_seek_table = false;
  95724. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  95725. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&decoder->private_->partitioned_rice_contents[i]);
  95726. decoder->private_->file = 0;
  95727. set_defaults_dec(decoder);
  95728. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  95729. return decoder;
  95730. }
  95731. FLAC_API void FLAC__stream_decoder_delete(FLAC__StreamDecoder *decoder)
  95732. {
  95733. unsigned i;
  95734. FLAC__ASSERT(0 != decoder);
  95735. FLAC__ASSERT(0 != decoder->protected_);
  95736. FLAC__ASSERT(0 != decoder->private_);
  95737. FLAC__ASSERT(0 != decoder->private_->input);
  95738. (void)FLAC__stream_decoder_finish(decoder);
  95739. if(0 != decoder->private_->metadata_filter_ids)
  95740. free(decoder->private_->metadata_filter_ids);
  95741. FLAC__bitreader_delete(decoder->private_->input);
  95742. for(i = 0; i < FLAC__MAX_CHANNELS; i++)
  95743. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&decoder->private_->partitioned_rice_contents[i]);
  95744. free(decoder->private_);
  95745. free(decoder->protected_);
  95746. free(decoder);
  95747. }
  95748. /***********************************************************************
  95749. *
  95750. * Public class methods
  95751. *
  95752. ***********************************************************************/
  95753. static FLAC__StreamDecoderInitStatus init_stream_internal_dec(
  95754. FLAC__StreamDecoder *decoder,
  95755. FLAC__StreamDecoderReadCallback read_callback,
  95756. FLAC__StreamDecoderSeekCallback seek_callback,
  95757. FLAC__StreamDecoderTellCallback tell_callback,
  95758. FLAC__StreamDecoderLengthCallback length_callback,
  95759. FLAC__StreamDecoderEofCallback eof_callback,
  95760. FLAC__StreamDecoderWriteCallback write_callback,
  95761. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95762. FLAC__StreamDecoderErrorCallback error_callback,
  95763. void *client_data,
  95764. FLAC__bool is_ogg
  95765. )
  95766. {
  95767. FLAC__ASSERT(0 != decoder);
  95768. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95769. return FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED;
  95770. #if !FLAC__HAS_OGG
  95771. if(is_ogg)
  95772. return FLAC__STREAM_DECODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  95773. #endif
  95774. if(
  95775. 0 == read_callback ||
  95776. 0 == write_callback ||
  95777. 0 == error_callback ||
  95778. (seek_callback && (0 == tell_callback || 0 == length_callback || 0 == eof_callback))
  95779. )
  95780. return FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS;
  95781. #if FLAC__HAS_OGG
  95782. decoder->private_->is_ogg = is_ogg;
  95783. if(is_ogg && !FLAC__ogg_decoder_aspect_init(&decoder->protected_->ogg_decoder_aspect))
  95784. return decoder->protected_->state = FLAC__STREAM_DECODER_OGG_ERROR;
  95785. #endif
  95786. /*
  95787. * get the CPU info and set the function pointers
  95788. */
  95789. FLAC__cpu_info(&decoder->private_->cpuinfo);
  95790. /* first default to the non-asm routines */
  95791. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal;
  95792. decoder->private_->local_lpc_restore_signal_64bit = FLAC__lpc_restore_signal_wide;
  95793. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal;
  95794. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal;
  95795. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block;
  95796. /* now override with asm where appropriate */
  95797. #ifndef FLAC__NO_ASM
  95798. if(decoder->private_->cpuinfo.use_asm) {
  95799. #ifdef FLAC__CPU_IA32
  95800. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  95801. #ifdef FLAC__HAS_NASM
  95802. #if 1 /*@@@@@@ OPT: not clearly faster, needs more testing */
  95803. if(decoder->private_->cpuinfo.data.ia32.bswap)
  95804. decoder->private_->local_bitreader_read_rice_signed_block = FLAC__bitreader_read_rice_signed_block_asm_ia32_bswap;
  95805. #endif
  95806. if(decoder->private_->cpuinfo.data.ia32.mmx) {
  95807. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  95808. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32_mmx;
  95809. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32_mmx;
  95810. }
  95811. else {
  95812. decoder->private_->local_lpc_restore_signal = FLAC__lpc_restore_signal_asm_ia32;
  95813. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ia32;
  95814. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ia32;
  95815. }
  95816. #endif
  95817. #elif defined FLAC__CPU_PPC
  95818. FLAC__ASSERT(decoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_PPC);
  95819. if(decoder->private_->cpuinfo.data.ppc.altivec) {
  95820. decoder->private_->local_lpc_restore_signal_16bit = FLAC__lpc_restore_signal_asm_ppc_altivec_16;
  95821. decoder->private_->local_lpc_restore_signal_16bit_order8 = FLAC__lpc_restore_signal_asm_ppc_altivec_16_order8;
  95822. }
  95823. #endif
  95824. }
  95825. #endif
  95826. /* from here on, errors are fatal */
  95827. if(!FLAC__bitreader_init(decoder->private_->input, decoder->private_->cpuinfo, read_callback_, decoder)) {
  95828. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  95829. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  95830. }
  95831. decoder->private_->read_callback = read_callback;
  95832. decoder->private_->seek_callback = seek_callback;
  95833. decoder->private_->tell_callback = tell_callback;
  95834. decoder->private_->length_callback = length_callback;
  95835. decoder->private_->eof_callback = eof_callback;
  95836. decoder->private_->write_callback = write_callback;
  95837. decoder->private_->metadata_callback = metadata_callback;
  95838. decoder->private_->error_callback = error_callback;
  95839. decoder->private_->client_data = client_data;
  95840. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  95841. decoder->private_->samples_decoded = 0;
  95842. decoder->private_->has_stream_info = false;
  95843. decoder->private_->cached = false;
  95844. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  95845. decoder->private_->is_seeking = false;
  95846. decoder->private_->internal_reset_hack = true; /* so the following reset does not try to rewind the input */
  95847. if(!FLAC__stream_decoder_reset(decoder)) {
  95848. /* above call sets the state for us */
  95849. return FLAC__STREAM_DECODER_INIT_STATUS_MEMORY_ALLOCATION_ERROR;
  95850. }
  95851. return FLAC__STREAM_DECODER_INIT_STATUS_OK;
  95852. }
  95853. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_stream(
  95854. FLAC__StreamDecoder *decoder,
  95855. FLAC__StreamDecoderReadCallback read_callback,
  95856. FLAC__StreamDecoderSeekCallback seek_callback,
  95857. FLAC__StreamDecoderTellCallback tell_callback,
  95858. FLAC__StreamDecoderLengthCallback length_callback,
  95859. FLAC__StreamDecoderEofCallback eof_callback,
  95860. FLAC__StreamDecoderWriteCallback write_callback,
  95861. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95862. FLAC__StreamDecoderErrorCallback error_callback,
  95863. void *client_data
  95864. )
  95865. {
  95866. return init_stream_internal_dec(
  95867. decoder,
  95868. read_callback,
  95869. seek_callback,
  95870. tell_callback,
  95871. length_callback,
  95872. eof_callback,
  95873. write_callback,
  95874. metadata_callback,
  95875. error_callback,
  95876. client_data,
  95877. /*is_ogg=*/false
  95878. );
  95879. }
  95880. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_stream(
  95881. FLAC__StreamDecoder *decoder,
  95882. FLAC__StreamDecoderReadCallback read_callback,
  95883. FLAC__StreamDecoderSeekCallback seek_callback,
  95884. FLAC__StreamDecoderTellCallback tell_callback,
  95885. FLAC__StreamDecoderLengthCallback length_callback,
  95886. FLAC__StreamDecoderEofCallback eof_callback,
  95887. FLAC__StreamDecoderWriteCallback write_callback,
  95888. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95889. FLAC__StreamDecoderErrorCallback error_callback,
  95890. void *client_data
  95891. )
  95892. {
  95893. return init_stream_internal_dec(
  95894. decoder,
  95895. read_callback,
  95896. seek_callback,
  95897. tell_callback,
  95898. length_callback,
  95899. eof_callback,
  95900. write_callback,
  95901. metadata_callback,
  95902. error_callback,
  95903. client_data,
  95904. /*is_ogg=*/true
  95905. );
  95906. }
  95907. static FLAC__StreamDecoderInitStatus init_FILE_internal_(
  95908. FLAC__StreamDecoder *decoder,
  95909. FILE *file,
  95910. FLAC__StreamDecoderWriteCallback write_callback,
  95911. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95912. FLAC__StreamDecoderErrorCallback error_callback,
  95913. void *client_data,
  95914. FLAC__bool is_ogg
  95915. )
  95916. {
  95917. FLAC__ASSERT(0 != decoder);
  95918. FLAC__ASSERT(0 != file);
  95919. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95920. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  95921. if(0 == write_callback || 0 == error_callback)
  95922. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  95923. /*
  95924. * To make sure that our file does not go unclosed after an error, we
  95925. * must assign the FILE pointer before any further error can occur in
  95926. * this routine.
  95927. */
  95928. if(file == stdin)
  95929. file = get_binary_stdin_(); /* just to be safe */
  95930. decoder->private_->file = file;
  95931. return init_stream_internal_dec(
  95932. decoder,
  95933. file_read_callback_dec,
  95934. decoder->private_->file == stdin? 0: file_seek_callback_dec,
  95935. decoder->private_->file == stdin? 0: file_tell_callback_dec,
  95936. decoder->private_->file == stdin? 0: file_length_callback_,
  95937. file_eof_callback_,
  95938. write_callback,
  95939. metadata_callback,
  95940. error_callback,
  95941. client_data,
  95942. is_ogg
  95943. );
  95944. }
  95945. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_FILE(
  95946. FLAC__StreamDecoder *decoder,
  95947. FILE *file,
  95948. FLAC__StreamDecoderWriteCallback write_callback,
  95949. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95950. FLAC__StreamDecoderErrorCallback error_callback,
  95951. void *client_data
  95952. )
  95953. {
  95954. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  95955. }
  95956. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_FILE(
  95957. FLAC__StreamDecoder *decoder,
  95958. FILE *file,
  95959. FLAC__StreamDecoderWriteCallback write_callback,
  95960. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95961. FLAC__StreamDecoderErrorCallback error_callback,
  95962. void *client_data
  95963. )
  95964. {
  95965. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  95966. }
  95967. static FLAC__StreamDecoderInitStatus init_file_internal_(
  95968. FLAC__StreamDecoder *decoder,
  95969. const char *filename,
  95970. FLAC__StreamDecoderWriteCallback write_callback,
  95971. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95972. FLAC__StreamDecoderErrorCallback error_callback,
  95973. void *client_data,
  95974. FLAC__bool is_ogg
  95975. )
  95976. {
  95977. FILE *file;
  95978. FLAC__ASSERT(0 != decoder);
  95979. /*
  95980. * To make sure that our file does not go unclosed after an error, we
  95981. * have to do the same entrance checks here that are later performed
  95982. * in FLAC__stream_decoder_init_FILE() before the FILE* is assigned.
  95983. */
  95984. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  95985. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_ALREADY_INITIALIZED);
  95986. if(0 == write_callback || 0 == error_callback)
  95987. return (FLAC__StreamDecoderInitStatus) (decoder->protected_->state = (FLAC__StreamDecoderState) FLAC__STREAM_DECODER_INIT_STATUS_INVALID_CALLBACKS);
  95988. file = filename? fopen(filename, "rb") : stdin;
  95989. if(0 == file)
  95990. return FLAC__STREAM_DECODER_INIT_STATUS_ERROR_OPENING_FILE;
  95991. return init_FILE_internal_(decoder, file, write_callback, metadata_callback, error_callback, client_data, is_ogg);
  95992. }
  95993. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_file(
  95994. FLAC__StreamDecoder *decoder,
  95995. const char *filename,
  95996. FLAC__StreamDecoderWriteCallback write_callback,
  95997. FLAC__StreamDecoderMetadataCallback metadata_callback,
  95998. FLAC__StreamDecoderErrorCallback error_callback,
  95999. void *client_data
  96000. )
  96001. {
  96002. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/false);
  96003. }
  96004. FLAC_API FLAC__StreamDecoderInitStatus FLAC__stream_decoder_init_ogg_file(
  96005. FLAC__StreamDecoder *decoder,
  96006. const char *filename,
  96007. FLAC__StreamDecoderWriteCallback write_callback,
  96008. FLAC__StreamDecoderMetadataCallback metadata_callback,
  96009. FLAC__StreamDecoderErrorCallback error_callback,
  96010. void *client_data
  96011. )
  96012. {
  96013. return init_file_internal_(decoder, filename, write_callback, metadata_callback, error_callback, client_data, /*is_ogg=*/true);
  96014. }
  96015. FLAC_API FLAC__bool FLAC__stream_decoder_finish(FLAC__StreamDecoder *decoder)
  96016. {
  96017. FLAC__bool md5_failed = false;
  96018. unsigned i;
  96019. FLAC__ASSERT(0 != decoder);
  96020. FLAC__ASSERT(0 != decoder->private_);
  96021. FLAC__ASSERT(0 != decoder->protected_);
  96022. if(decoder->protected_->state == FLAC__STREAM_DECODER_UNINITIALIZED)
  96023. return true;
  96024. /* see the comment in FLAC__seekable_stream_decoder_reset() as to why we
  96025. * always call FLAC__MD5Final()
  96026. */
  96027. FLAC__MD5Final(decoder->private_->computed_md5sum, &decoder->private_->md5context);
  96028. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  96029. free(decoder->private_->seek_table.data.seek_table.points);
  96030. decoder->private_->seek_table.data.seek_table.points = 0;
  96031. decoder->private_->has_seek_table = false;
  96032. }
  96033. FLAC__bitreader_free(decoder->private_->input);
  96034. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96035. /* WATCHOUT:
  96036. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  96037. * output arrays have a buffer of up to 3 zeroes in front
  96038. * (at negative indices) for alignment purposes; we use 4
  96039. * to keep the data well-aligned.
  96040. */
  96041. if(0 != decoder->private_->output[i]) {
  96042. free(decoder->private_->output[i]-4);
  96043. decoder->private_->output[i] = 0;
  96044. }
  96045. if(0 != decoder->private_->residual_unaligned[i]) {
  96046. free(decoder->private_->residual_unaligned[i]);
  96047. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  96048. }
  96049. }
  96050. decoder->private_->output_capacity = 0;
  96051. decoder->private_->output_channels = 0;
  96052. #if FLAC__HAS_OGG
  96053. if(decoder->private_->is_ogg)
  96054. FLAC__ogg_decoder_aspect_finish(&decoder->protected_->ogg_decoder_aspect);
  96055. #endif
  96056. if(0 != decoder->private_->file) {
  96057. if(decoder->private_->file != stdin)
  96058. fclose(decoder->private_->file);
  96059. decoder->private_->file = 0;
  96060. }
  96061. if(decoder->private_->do_md5_checking) {
  96062. if(memcmp(decoder->private_->stream_info.data.stream_info.md5sum, decoder->private_->computed_md5sum, 16))
  96063. md5_failed = true;
  96064. }
  96065. decoder->private_->is_seeking = false;
  96066. set_defaults_dec(decoder);
  96067. decoder->protected_->state = FLAC__STREAM_DECODER_UNINITIALIZED;
  96068. return !md5_failed;
  96069. }
  96070. FLAC_API FLAC__bool FLAC__stream_decoder_set_ogg_serial_number(FLAC__StreamDecoder *decoder, long value)
  96071. {
  96072. FLAC__ASSERT(0 != decoder);
  96073. FLAC__ASSERT(0 != decoder->private_);
  96074. FLAC__ASSERT(0 != decoder->protected_);
  96075. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96076. return false;
  96077. #if FLAC__HAS_OGG
  96078. /* can't check decoder->private_->is_ogg since that's not set until init time */
  96079. FLAC__ogg_decoder_aspect_set_serial_number(&decoder->protected_->ogg_decoder_aspect, value);
  96080. return true;
  96081. #else
  96082. (void)value;
  96083. return false;
  96084. #endif
  96085. }
  96086. FLAC_API FLAC__bool FLAC__stream_decoder_set_md5_checking(FLAC__StreamDecoder *decoder, FLAC__bool value)
  96087. {
  96088. FLAC__ASSERT(0 != decoder);
  96089. FLAC__ASSERT(0 != decoder->protected_);
  96090. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96091. return false;
  96092. decoder->protected_->md5_checking = value;
  96093. return true;
  96094. }
  96095. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  96096. {
  96097. FLAC__ASSERT(0 != decoder);
  96098. FLAC__ASSERT(0 != decoder->private_);
  96099. FLAC__ASSERT(0 != decoder->protected_);
  96100. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  96101. /* double protection */
  96102. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  96103. return false;
  96104. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96105. return false;
  96106. decoder->private_->metadata_filter[type] = true;
  96107. if(type == FLAC__METADATA_TYPE_APPLICATION)
  96108. decoder->private_->metadata_filter_ids_count = 0;
  96109. return true;
  96110. }
  96111. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  96112. {
  96113. FLAC__ASSERT(0 != decoder);
  96114. FLAC__ASSERT(0 != decoder->private_);
  96115. FLAC__ASSERT(0 != decoder->protected_);
  96116. FLAC__ASSERT(0 != id);
  96117. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96118. return false;
  96119. if(decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  96120. return true;
  96121. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  96122. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  96123. 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))) {
  96124. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96125. return false;
  96126. }
  96127. decoder->private_->metadata_filter_ids_capacity *= 2;
  96128. }
  96129. 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));
  96130. decoder->private_->metadata_filter_ids_count++;
  96131. return true;
  96132. }
  96133. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_respond_all(FLAC__StreamDecoder *decoder)
  96134. {
  96135. unsigned i;
  96136. FLAC__ASSERT(0 != decoder);
  96137. FLAC__ASSERT(0 != decoder->private_);
  96138. FLAC__ASSERT(0 != decoder->protected_);
  96139. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96140. return false;
  96141. for(i = 0; i < sizeof(decoder->private_->metadata_filter) / sizeof(decoder->private_->metadata_filter[0]); i++)
  96142. decoder->private_->metadata_filter[i] = true;
  96143. decoder->private_->metadata_filter_ids_count = 0;
  96144. return true;
  96145. }
  96146. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore(FLAC__StreamDecoder *decoder, FLAC__MetadataType type)
  96147. {
  96148. FLAC__ASSERT(0 != decoder);
  96149. FLAC__ASSERT(0 != decoder->private_);
  96150. FLAC__ASSERT(0 != decoder->protected_);
  96151. FLAC__ASSERT((unsigned)type <= FLAC__MAX_METADATA_TYPE_CODE);
  96152. /* double protection */
  96153. if((unsigned)type > FLAC__MAX_METADATA_TYPE_CODE)
  96154. return false;
  96155. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96156. return false;
  96157. decoder->private_->metadata_filter[type] = false;
  96158. if(type == FLAC__METADATA_TYPE_APPLICATION)
  96159. decoder->private_->metadata_filter_ids_count = 0;
  96160. return true;
  96161. }
  96162. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_application(FLAC__StreamDecoder *decoder, const FLAC__byte id[4])
  96163. {
  96164. FLAC__ASSERT(0 != decoder);
  96165. FLAC__ASSERT(0 != decoder->private_);
  96166. FLAC__ASSERT(0 != decoder->protected_);
  96167. FLAC__ASSERT(0 != id);
  96168. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96169. return false;
  96170. if(!decoder->private_->metadata_filter[FLAC__METADATA_TYPE_APPLICATION])
  96171. return true;
  96172. FLAC__ASSERT(0 != decoder->private_->metadata_filter_ids);
  96173. if(decoder->private_->metadata_filter_ids_count == decoder->private_->metadata_filter_ids_capacity) {
  96174. 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))) {
  96175. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96176. return false;
  96177. }
  96178. decoder->private_->metadata_filter_ids_capacity *= 2;
  96179. }
  96180. 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));
  96181. decoder->private_->metadata_filter_ids_count++;
  96182. return true;
  96183. }
  96184. FLAC_API FLAC__bool FLAC__stream_decoder_set_metadata_ignore_all(FLAC__StreamDecoder *decoder)
  96185. {
  96186. FLAC__ASSERT(0 != decoder);
  96187. FLAC__ASSERT(0 != decoder->private_);
  96188. FLAC__ASSERT(0 != decoder->protected_);
  96189. if(decoder->protected_->state != FLAC__STREAM_DECODER_UNINITIALIZED)
  96190. return false;
  96191. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  96192. decoder->private_->metadata_filter_ids_count = 0;
  96193. return true;
  96194. }
  96195. FLAC_API FLAC__StreamDecoderState FLAC__stream_decoder_get_state(const FLAC__StreamDecoder *decoder)
  96196. {
  96197. FLAC__ASSERT(0 != decoder);
  96198. FLAC__ASSERT(0 != decoder->protected_);
  96199. return decoder->protected_->state;
  96200. }
  96201. FLAC_API const char *FLAC__stream_decoder_get_resolved_state_string(const FLAC__StreamDecoder *decoder)
  96202. {
  96203. return FLAC__StreamDecoderStateString[decoder->protected_->state];
  96204. }
  96205. FLAC_API FLAC__bool FLAC__stream_decoder_get_md5_checking(const FLAC__StreamDecoder *decoder)
  96206. {
  96207. FLAC__ASSERT(0 != decoder);
  96208. FLAC__ASSERT(0 != decoder->protected_);
  96209. return decoder->protected_->md5_checking;
  96210. }
  96211. FLAC_API FLAC__uint64 FLAC__stream_decoder_get_total_samples(const FLAC__StreamDecoder *decoder)
  96212. {
  96213. FLAC__ASSERT(0 != decoder);
  96214. FLAC__ASSERT(0 != decoder->protected_);
  96215. return decoder->private_->has_stream_info? decoder->private_->stream_info.data.stream_info.total_samples : 0;
  96216. }
  96217. FLAC_API unsigned FLAC__stream_decoder_get_channels(const FLAC__StreamDecoder *decoder)
  96218. {
  96219. FLAC__ASSERT(0 != decoder);
  96220. FLAC__ASSERT(0 != decoder->protected_);
  96221. return decoder->protected_->channels;
  96222. }
  96223. FLAC_API FLAC__ChannelAssignment FLAC__stream_decoder_get_channel_assignment(const FLAC__StreamDecoder *decoder)
  96224. {
  96225. FLAC__ASSERT(0 != decoder);
  96226. FLAC__ASSERT(0 != decoder->protected_);
  96227. return decoder->protected_->channel_assignment;
  96228. }
  96229. FLAC_API unsigned FLAC__stream_decoder_get_bits_per_sample(const FLAC__StreamDecoder *decoder)
  96230. {
  96231. FLAC__ASSERT(0 != decoder);
  96232. FLAC__ASSERT(0 != decoder->protected_);
  96233. return decoder->protected_->bits_per_sample;
  96234. }
  96235. FLAC_API unsigned FLAC__stream_decoder_get_sample_rate(const FLAC__StreamDecoder *decoder)
  96236. {
  96237. FLAC__ASSERT(0 != decoder);
  96238. FLAC__ASSERT(0 != decoder->protected_);
  96239. return decoder->protected_->sample_rate;
  96240. }
  96241. FLAC_API unsigned FLAC__stream_decoder_get_blocksize(const FLAC__StreamDecoder *decoder)
  96242. {
  96243. FLAC__ASSERT(0 != decoder);
  96244. FLAC__ASSERT(0 != decoder->protected_);
  96245. return decoder->protected_->blocksize;
  96246. }
  96247. FLAC_API FLAC__bool FLAC__stream_decoder_get_decode_position(const FLAC__StreamDecoder *decoder, FLAC__uint64 *position)
  96248. {
  96249. FLAC__ASSERT(0 != decoder);
  96250. FLAC__ASSERT(0 != decoder->private_);
  96251. FLAC__ASSERT(0 != position);
  96252. #if FLAC__HAS_OGG
  96253. if(decoder->private_->is_ogg)
  96254. return false;
  96255. #endif
  96256. if(0 == decoder->private_->tell_callback)
  96257. return false;
  96258. if(decoder->private_->tell_callback(decoder, position, decoder->private_->client_data) != FLAC__STREAM_DECODER_TELL_STATUS_OK)
  96259. return false;
  96260. /* should never happen since all FLAC frames and metadata blocks are byte aligned, but check just in case */
  96261. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input))
  96262. return false;
  96263. FLAC__ASSERT(*position >= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder));
  96264. *position -= FLAC__stream_decoder_get_input_bytes_unconsumed(decoder);
  96265. return true;
  96266. }
  96267. FLAC_API FLAC__bool FLAC__stream_decoder_flush(FLAC__StreamDecoder *decoder)
  96268. {
  96269. FLAC__ASSERT(0 != decoder);
  96270. FLAC__ASSERT(0 != decoder->private_);
  96271. FLAC__ASSERT(0 != decoder->protected_);
  96272. decoder->private_->samples_decoded = 0;
  96273. decoder->private_->do_md5_checking = false;
  96274. #if FLAC__HAS_OGG
  96275. if(decoder->private_->is_ogg)
  96276. FLAC__ogg_decoder_aspect_flush(&decoder->protected_->ogg_decoder_aspect);
  96277. #endif
  96278. if(!FLAC__bitreader_clear(decoder->private_->input)) {
  96279. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96280. return false;
  96281. }
  96282. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96283. return true;
  96284. }
  96285. FLAC_API FLAC__bool FLAC__stream_decoder_reset(FLAC__StreamDecoder *decoder)
  96286. {
  96287. FLAC__ASSERT(0 != decoder);
  96288. FLAC__ASSERT(0 != decoder->private_);
  96289. FLAC__ASSERT(0 != decoder->protected_);
  96290. if(!FLAC__stream_decoder_flush(decoder)) {
  96291. /* above call sets the state for us */
  96292. return false;
  96293. }
  96294. #if FLAC__HAS_OGG
  96295. /*@@@ could go in !internal_reset_hack block below */
  96296. if(decoder->private_->is_ogg)
  96297. FLAC__ogg_decoder_aspect_reset(&decoder->protected_->ogg_decoder_aspect);
  96298. #endif
  96299. /* Rewind if necessary. If FLAC__stream_decoder_init() is calling us,
  96300. * (internal_reset_hack) don't try to rewind since we are already at
  96301. * the beginning of the stream and don't want to fail if the input is
  96302. * not seekable.
  96303. */
  96304. if(!decoder->private_->internal_reset_hack) {
  96305. if(decoder->private_->file == stdin)
  96306. return false; /* can't rewind stdin, reset fails */
  96307. if(decoder->private_->seek_callback && decoder->private_->seek_callback(decoder, 0, decoder->private_->client_data) == FLAC__STREAM_DECODER_SEEK_STATUS_ERROR)
  96308. return false; /* seekable and seek fails, reset fails */
  96309. }
  96310. else
  96311. decoder->private_->internal_reset_hack = false;
  96312. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_METADATA;
  96313. decoder->private_->has_stream_info = false;
  96314. if(decoder->private_->has_seek_table && 0 != decoder->private_->seek_table.data.seek_table.points) {
  96315. free(decoder->private_->seek_table.data.seek_table.points);
  96316. decoder->private_->seek_table.data.seek_table.points = 0;
  96317. decoder->private_->has_seek_table = false;
  96318. }
  96319. decoder->private_->do_md5_checking = decoder->protected_->md5_checking;
  96320. /*
  96321. * This goes in reset() and not flush() because according to the spec, a
  96322. * fixed-blocksize stream must stay that way through the whole stream.
  96323. */
  96324. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size = 0;
  96325. /* We initialize the FLAC__MD5Context even though we may never use it. This
  96326. * is because md5 checking may be turned on to start and then turned off if
  96327. * a seek occurs. So we init the context here and finalize it in
  96328. * FLAC__stream_decoder_finish() to make sure things are always cleaned up
  96329. * properly.
  96330. */
  96331. FLAC__MD5Init(&decoder->private_->md5context);
  96332. decoder->private_->first_frame_offset = 0;
  96333. decoder->private_->unparseable_frame_count = 0;
  96334. return true;
  96335. }
  96336. FLAC_API FLAC__bool FLAC__stream_decoder_process_single(FLAC__StreamDecoder *decoder)
  96337. {
  96338. FLAC__bool got_a_frame;
  96339. FLAC__ASSERT(0 != decoder);
  96340. FLAC__ASSERT(0 != decoder->protected_);
  96341. while(1) {
  96342. switch(decoder->protected_->state) {
  96343. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96344. if(!find_metadata_(decoder))
  96345. return false; /* above function sets the status for us */
  96346. break;
  96347. case FLAC__STREAM_DECODER_READ_METADATA:
  96348. if(!read_metadata_(decoder))
  96349. return false; /* above function sets the status for us */
  96350. else
  96351. return true;
  96352. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96353. if(!frame_sync_(decoder))
  96354. return true; /* above function sets the status for us */
  96355. break;
  96356. case FLAC__STREAM_DECODER_READ_FRAME:
  96357. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/true))
  96358. return false; /* above function sets the status for us */
  96359. if(got_a_frame)
  96360. return true; /* above function sets the status for us */
  96361. break;
  96362. case FLAC__STREAM_DECODER_END_OF_STREAM:
  96363. case FLAC__STREAM_DECODER_ABORTED:
  96364. return true;
  96365. default:
  96366. FLAC__ASSERT(0);
  96367. return false;
  96368. }
  96369. }
  96370. }
  96371. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_metadata(FLAC__StreamDecoder *decoder)
  96372. {
  96373. FLAC__ASSERT(0 != decoder);
  96374. FLAC__ASSERT(0 != decoder->protected_);
  96375. while(1) {
  96376. switch(decoder->protected_->state) {
  96377. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96378. if(!find_metadata_(decoder))
  96379. return false; /* above function sets the status for us */
  96380. break;
  96381. case FLAC__STREAM_DECODER_READ_METADATA:
  96382. if(!read_metadata_(decoder))
  96383. return false; /* above function sets the status for us */
  96384. break;
  96385. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96386. case FLAC__STREAM_DECODER_READ_FRAME:
  96387. case FLAC__STREAM_DECODER_END_OF_STREAM:
  96388. case FLAC__STREAM_DECODER_ABORTED:
  96389. return true;
  96390. default:
  96391. FLAC__ASSERT(0);
  96392. return false;
  96393. }
  96394. }
  96395. }
  96396. FLAC_API FLAC__bool FLAC__stream_decoder_process_until_end_of_stream(FLAC__StreamDecoder *decoder)
  96397. {
  96398. FLAC__bool dummy;
  96399. FLAC__ASSERT(0 != decoder);
  96400. FLAC__ASSERT(0 != decoder->protected_);
  96401. while(1) {
  96402. switch(decoder->protected_->state) {
  96403. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96404. if(!find_metadata_(decoder))
  96405. return false; /* above function sets the status for us */
  96406. break;
  96407. case FLAC__STREAM_DECODER_READ_METADATA:
  96408. if(!read_metadata_(decoder))
  96409. return false; /* above function sets the status for us */
  96410. break;
  96411. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96412. if(!frame_sync_(decoder))
  96413. return true; /* above function sets the status for us */
  96414. break;
  96415. case FLAC__STREAM_DECODER_READ_FRAME:
  96416. if(!read_frame_(decoder, &dummy, /*do_full_decode=*/true))
  96417. return false; /* above function sets the status for us */
  96418. break;
  96419. case FLAC__STREAM_DECODER_END_OF_STREAM:
  96420. case FLAC__STREAM_DECODER_ABORTED:
  96421. return true;
  96422. default:
  96423. FLAC__ASSERT(0);
  96424. return false;
  96425. }
  96426. }
  96427. }
  96428. FLAC_API FLAC__bool FLAC__stream_decoder_skip_single_frame(FLAC__StreamDecoder *decoder)
  96429. {
  96430. FLAC__bool got_a_frame;
  96431. FLAC__ASSERT(0 != decoder);
  96432. FLAC__ASSERT(0 != decoder->protected_);
  96433. while(1) {
  96434. switch(decoder->protected_->state) {
  96435. case FLAC__STREAM_DECODER_SEARCH_FOR_METADATA:
  96436. case FLAC__STREAM_DECODER_READ_METADATA:
  96437. return false; /* above function sets the status for us */
  96438. case FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC:
  96439. if(!frame_sync_(decoder))
  96440. return true; /* above function sets the status for us */
  96441. break;
  96442. case FLAC__STREAM_DECODER_READ_FRAME:
  96443. if(!read_frame_(decoder, &got_a_frame, /*do_full_decode=*/false))
  96444. return false; /* above function sets the status for us */
  96445. if(got_a_frame)
  96446. return true; /* above function sets the status for us */
  96447. break;
  96448. case FLAC__STREAM_DECODER_END_OF_STREAM:
  96449. case FLAC__STREAM_DECODER_ABORTED:
  96450. return true;
  96451. default:
  96452. FLAC__ASSERT(0);
  96453. return false;
  96454. }
  96455. }
  96456. }
  96457. FLAC_API FLAC__bool FLAC__stream_decoder_seek_absolute(FLAC__StreamDecoder *decoder, FLAC__uint64 sample)
  96458. {
  96459. FLAC__uint64 length;
  96460. FLAC__ASSERT(0 != decoder);
  96461. if(
  96462. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_METADATA &&
  96463. decoder->protected_->state != FLAC__STREAM_DECODER_READ_METADATA &&
  96464. decoder->protected_->state != FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC &&
  96465. decoder->protected_->state != FLAC__STREAM_DECODER_READ_FRAME &&
  96466. decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM
  96467. )
  96468. return false;
  96469. if(0 == decoder->private_->seek_callback)
  96470. return false;
  96471. FLAC__ASSERT(decoder->private_->seek_callback);
  96472. FLAC__ASSERT(decoder->private_->tell_callback);
  96473. FLAC__ASSERT(decoder->private_->length_callback);
  96474. FLAC__ASSERT(decoder->private_->eof_callback);
  96475. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder))
  96476. return false;
  96477. decoder->private_->is_seeking = true;
  96478. /* turn off md5 checking if a seek is attempted */
  96479. decoder->private_->do_md5_checking = false;
  96480. /* 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) */
  96481. if(decoder->private_->length_callback(decoder, &length, decoder->private_->client_data) != FLAC__STREAM_DECODER_LENGTH_STATUS_OK) {
  96482. decoder->private_->is_seeking = false;
  96483. return false;
  96484. }
  96485. /* if we haven't finished processing the metadata yet, do that so we have the STREAMINFO, SEEK_TABLE, and first_frame_offset */
  96486. if(
  96487. decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_METADATA ||
  96488. decoder->protected_->state == FLAC__STREAM_DECODER_READ_METADATA
  96489. ) {
  96490. if(!FLAC__stream_decoder_process_until_end_of_metadata(decoder)) {
  96491. /* above call sets the state for us */
  96492. decoder->private_->is_seeking = false;
  96493. return false;
  96494. }
  96495. /* check this again in case we didn't know total_samples the first time */
  96496. if(FLAC__stream_decoder_get_total_samples(decoder) > 0 && sample >= FLAC__stream_decoder_get_total_samples(decoder)) {
  96497. decoder->private_->is_seeking = false;
  96498. return false;
  96499. }
  96500. }
  96501. {
  96502. const FLAC__bool ok =
  96503. #if FLAC__HAS_OGG
  96504. decoder->private_->is_ogg?
  96505. seek_to_absolute_sample_ogg_(decoder, length, sample) :
  96506. #endif
  96507. seek_to_absolute_sample_(decoder, length, sample)
  96508. ;
  96509. decoder->private_->is_seeking = false;
  96510. return ok;
  96511. }
  96512. }
  96513. /***********************************************************************
  96514. *
  96515. * Protected class methods
  96516. *
  96517. ***********************************************************************/
  96518. unsigned FLAC__stream_decoder_get_input_bytes_unconsumed(const FLAC__StreamDecoder *decoder)
  96519. {
  96520. FLAC__ASSERT(0 != decoder);
  96521. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96522. FLAC__ASSERT(!(FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) & 7));
  96523. return FLAC__bitreader_get_input_bits_unconsumed(decoder->private_->input) / 8;
  96524. }
  96525. /***********************************************************************
  96526. *
  96527. * Private class methods
  96528. *
  96529. ***********************************************************************/
  96530. void set_defaults_dec(FLAC__StreamDecoder *decoder)
  96531. {
  96532. #if FLAC__HAS_OGG
  96533. decoder->private_->is_ogg = false;
  96534. #endif
  96535. decoder->private_->read_callback = 0;
  96536. decoder->private_->seek_callback = 0;
  96537. decoder->private_->tell_callback = 0;
  96538. decoder->private_->length_callback = 0;
  96539. decoder->private_->eof_callback = 0;
  96540. decoder->private_->write_callback = 0;
  96541. decoder->private_->metadata_callback = 0;
  96542. decoder->private_->error_callback = 0;
  96543. decoder->private_->client_data = 0;
  96544. memset(decoder->private_->metadata_filter, 0, sizeof(decoder->private_->metadata_filter));
  96545. decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] = true;
  96546. decoder->private_->metadata_filter_ids_count = 0;
  96547. decoder->protected_->md5_checking = false;
  96548. #if FLAC__HAS_OGG
  96549. FLAC__ogg_decoder_aspect_set_defaults(&decoder->protected_->ogg_decoder_aspect);
  96550. #endif
  96551. }
  96552. /*
  96553. * This will forcibly set stdin to binary mode (for OSes that require it)
  96554. */
  96555. FILE *get_binary_stdin_(void)
  96556. {
  96557. /* if something breaks here it is probably due to the presence or
  96558. * absence of an underscore before the identifiers 'setmode',
  96559. * 'fileno', and/or 'O_BINARY'; check your system header files.
  96560. */
  96561. #if defined _MSC_VER || defined __MINGW32__
  96562. _setmode(_fileno(stdin), _O_BINARY);
  96563. #elif defined __CYGWIN__
  96564. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  96565. setmode(_fileno(stdin), _O_BINARY);
  96566. #elif defined __EMX__
  96567. setmode(fileno(stdin), O_BINARY);
  96568. #endif
  96569. return stdin;
  96570. }
  96571. FLAC__bool allocate_output_(FLAC__StreamDecoder *decoder, unsigned size, unsigned channels)
  96572. {
  96573. unsigned i;
  96574. FLAC__int32 *tmp;
  96575. if(size <= decoder->private_->output_capacity && channels <= decoder->private_->output_channels)
  96576. return true;
  96577. /* simply using realloc() is not practical because the number of channels may change mid-stream */
  96578. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  96579. if(0 != decoder->private_->output[i]) {
  96580. free(decoder->private_->output[i]-4);
  96581. decoder->private_->output[i] = 0;
  96582. }
  96583. if(0 != decoder->private_->residual_unaligned[i]) {
  96584. free(decoder->private_->residual_unaligned[i]);
  96585. decoder->private_->residual_unaligned[i] = decoder->private_->residual[i] = 0;
  96586. }
  96587. }
  96588. for(i = 0; i < channels; i++) {
  96589. /* WATCHOUT:
  96590. * FLAC__lpc_restore_signal_asm_ia32_mmx() requires that the
  96591. * output arrays have a buffer of up to 3 zeroes in front
  96592. * (at negative indices) for alignment purposes; we use 4
  96593. * to keep the data well-aligned.
  96594. */
  96595. tmp = (FLAC__int32*)safe_malloc_muladd2_(sizeof(FLAC__int32), /*times (*/size, /*+*/4/*)*/);
  96596. if(tmp == 0) {
  96597. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96598. return false;
  96599. }
  96600. memset(tmp, 0, sizeof(FLAC__int32)*4);
  96601. decoder->private_->output[i] = tmp + 4;
  96602. /* WATCHOUT:
  96603. * minimum of quadword alignment for PPC vector optimizations is REQUIRED:
  96604. */
  96605. if(!FLAC__memory_alloc_aligned_int32_array(size, &decoder->private_->residual_unaligned[i], &decoder->private_->residual[i])) {
  96606. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96607. return false;
  96608. }
  96609. }
  96610. decoder->private_->output_capacity = size;
  96611. decoder->private_->output_channels = channels;
  96612. return true;
  96613. }
  96614. FLAC__bool has_id_filtered_(FLAC__StreamDecoder *decoder, FLAC__byte *id)
  96615. {
  96616. size_t i;
  96617. FLAC__ASSERT(0 != decoder);
  96618. FLAC__ASSERT(0 != decoder->private_);
  96619. for(i = 0; i < decoder->private_->metadata_filter_ids_count; i++)
  96620. if(0 == memcmp(decoder->private_->metadata_filter_ids + i * (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8), id, (FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8)))
  96621. return true;
  96622. return false;
  96623. }
  96624. FLAC__bool find_metadata_(FLAC__StreamDecoder *decoder)
  96625. {
  96626. FLAC__uint32 x;
  96627. unsigned i, id_;
  96628. FLAC__bool first = true;
  96629. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96630. for(i = id_ = 0; i < 4; ) {
  96631. if(decoder->private_->cached) {
  96632. x = (FLAC__uint32)decoder->private_->lookahead;
  96633. decoder->private_->cached = false;
  96634. }
  96635. else {
  96636. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96637. return false; /* read_callback_ sets the state for us */
  96638. }
  96639. if(x == FLAC__STREAM_SYNC_STRING[i]) {
  96640. first = true;
  96641. i++;
  96642. id_ = 0;
  96643. continue;
  96644. }
  96645. if(x == ID3V2_TAG_[id_]) {
  96646. id_++;
  96647. i = 0;
  96648. if(id_ == 3) {
  96649. if(!skip_id3v2_tag_(decoder))
  96650. return false; /* skip_id3v2_tag_ sets the state for us */
  96651. }
  96652. continue;
  96653. }
  96654. id_ = 0;
  96655. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96656. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  96657. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  96658. return false; /* read_callback_ sets the state for us */
  96659. /* 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 */
  96660. /* else we have to check if the second byte is the end of a sync code */
  96661. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  96662. decoder->private_->lookahead = (FLAC__byte)x;
  96663. decoder->private_->cached = true;
  96664. }
  96665. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  96666. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  96667. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  96668. return true;
  96669. }
  96670. }
  96671. i = 0;
  96672. if(first) {
  96673. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  96674. first = false;
  96675. }
  96676. }
  96677. decoder->protected_->state = FLAC__STREAM_DECODER_READ_METADATA;
  96678. return true;
  96679. }
  96680. FLAC__bool read_metadata_(FLAC__StreamDecoder *decoder)
  96681. {
  96682. FLAC__bool is_last;
  96683. FLAC__uint32 i, x, type, length;
  96684. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96685. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_IS_LAST_LEN))
  96686. return false; /* read_callback_ sets the state for us */
  96687. is_last = x? true : false;
  96688. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &type, FLAC__STREAM_METADATA_TYPE_LEN))
  96689. return false; /* read_callback_ sets the state for us */
  96690. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &length, FLAC__STREAM_METADATA_LENGTH_LEN))
  96691. return false; /* read_callback_ sets the state for us */
  96692. if(type == FLAC__METADATA_TYPE_STREAMINFO) {
  96693. if(!read_metadata_streaminfo_(decoder, is_last, length))
  96694. return false;
  96695. decoder->private_->has_stream_info = true;
  96696. 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))
  96697. decoder->private_->do_md5_checking = false;
  96698. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_STREAMINFO] && decoder->private_->metadata_callback)
  96699. decoder->private_->metadata_callback(decoder, &decoder->private_->stream_info, decoder->private_->client_data);
  96700. }
  96701. else if(type == FLAC__METADATA_TYPE_SEEKTABLE) {
  96702. if(!read_metadata_seektable_(decoder, is_last, length))
  96703. return false;
  96704. decoder->private_->has_seek_table = true;
  96705. if(!decoder->private_->is_seeking && decoder->private_->metadata_filter[FLAC__METADATA_TYPE_SEEKTABLE] && decoder->private_->metadata_callback)
  96706. decoder->private_->metadata_callback(decoder, &decoder->private_->seek_table, decoder->private_->client_data);
  96707. }
  96708. else {
  96709. FLAC__bool skip_it = !decoder->private_->metadata_filter[type];
  96710. unsigned real_length = length;
  96711. FLAC__StreamMetadata block;
  96712. block.is_last = is_last;
  96713. block.type = (FLAC__MetadataType)type;
  96714. block.length = length;
  96715. if(type == FLAC__METADATA_TYPE_APPLICATION) {
  96716. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8))
  96717. return false; /* read_callback_ sets the state for us */
  96718. if(real_length < FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8) { /* underflow check */
  96719. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;/*@@@@@@ maybe wrong error? need to resync?*/
  96720. return false;
  96721. }
  96722. real_length -= FLAC__STREAM_METADATA_APPLICATION_ID_LEN/8;
  96723. if(decoder->private_->metadata_filter_ids_count > 0 && has_id_filtered_(decoder, block.data.application.id))
  96724. skip_it = !skip_it;
  96725. }
  96726. if(skip_it) {
  96727. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  96728. return false; /* read_callback_ sets the state for us */
  96729. }
  96730. else {
  96731. switch(type) {
  96732. case FLAC__METADATA_TYPE_PADDING:
  96733. /* skip the padding bytes */
  96734. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, real_length))
  96735. return false; /* read_callback_ sets the state for us */
  96736. break;
  96737. case FLAC__METADATA_TYPE_APPLICATION:
  96738. /* remember, we read the ID already */
  96739. if(real_length > 0) {
  96740. if(0 == (block.data.application.data = (FLAC__byte*)malloc(real_length))) {
  96741. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96742. return false;
  96743. }
  96744. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.application.data, real_length))
  96745. return false; /* read_callback_ sets the state for us */
  96746. }
  96747. else
  96748. block.data.application.data = 0;
  96749. break;
  96750. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  96751. if(!read_metadata_vorbiscomment_(decoder, &block.data.vorbis_comment))
  96752. return false;
  96753. break;
  96754. case FLAC__METADATA_TYPE_CUESHEET:
  96755. if(!read_metadata_cuesheet_(decoder, &block.data.cue_sheet))
  96756. return false;
  96757. break;
  96758. case FLAC__METADATA_TYPE_PICTURE:
  96759. if(!read_metadata_picture_(decoder, &block.data.picture))
  96760. return false;
  96761. break;
  96762. case FLAC__METADATA_TYPE_STREAMINFO:
  96763. case FLAC__METADATA_TYPE_SEEKTABLE:
  96764. FLAC__ASSERT(0);
  96765. break;
  96766. default:
  96767. if(real_length > 0) {
  96768. if(0 == (block.data.unknown.data = (FLAC__byte*)malloc(real_length))) {
  96769. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96770. return false;
  96771. }
  96772. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, block.data.unknown.data, real_length))
  96773. return false; /* read_callback_ sets the state for us */
  96774. }
  96775. else
  96776. block.data.unknown.data = 0;
  96777. break;
  96778. }
  96779. if(!decoder->private_->is_seeking && decoder->private_->metadata_callback)
  96780. decoder->private_->metadata_callback(decoder, &block, decoder->private_->client_data);
  96781. /* now we have to free any malloc()ed data in the block */
  96782. switch(type) {
  96783. case FLAC__METADATA_TYPE_PADDING:
  96784. break;
  96785. case FLAC__METADATA_TYPE_APPLICATION:
  96786. if(0 != block.data.application.data)
  96787. free(block.data.application.data);
  96788. break;
  96789. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  96790. if(0 != block.data.vorbis_comment.vendor_string.entry)
  96791. free(block.data.vorbis_comment.vendor_string.entry);
  96792. if(block.data.vorbis_comment.num_comments > 0)
  96793. for(i = 0; i < block.data.vorbis_comment.num_comments; i++)
  96794. if(0 != block.data.vorbis_comment.comments[i].entry)
  96795. free(block.data.vorbis_comment.comments[i].entry);
  96796. if(0 != block.data.vorbis_comment.comments)
  96797. free(block.data.vorbis_comment.comments);
  96798. break;
  96799. case FLAC__METADATA_TYPE_CUESHEET:
  96800. if(block.data.cue_sheet.num_tracks > 0)
  96801. for(i = 0; i < block.data.cue_sheet.num_tracks; i++)
  96802. if(0 != block.data.cue_sheet.tracks[i].indices)
  96803. free(block.data.cue_sheet.tracks[i].indices);
  96804. if(0 != block.data.cue_sheet.tracks)
  96805. free(block.data.cue_sheet.tracks);
  96806. break;
  96807. case FLAC__METADATA_TYPE_PICTURE:
  96808. if(0 != block.data.picture.mime_type)
  96809. free(block.data.picture.mime_type);
  96810. if(0 != block.data.picture.description)
  96811. free(block.data.picture.description);
  96812. if(0 != block.data.picture.data)
  96813. free(block.data.picture.data);
  96814. break;
  96815. case FLAC__METADATA_TYPE_STREAMINFO:
  96816. case FLAC__METADATA_TYPE_SEEKTABLE:
  96817. FLAC__ASSERT(0);
  96818. default:
  96819. if(0 != block.data.unknown.data)
  96820. free(block.data.unknown.data);
  96821. break;
  96822. }
  96823. }
  96824. }
  96825. if(is_last) {
  96826. /* if this fails, it's OK, it's just a hint for the seek routine */
  96827. if(!FLAC__stream_decoder_get_decode_position(decoder, &decoder->private_->first_frame_offset))
  96828. decoder->private_->first_frame_offset = 0;
  96829. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  96830. }
  96831. return true;
  96832. }
  96833. FLAC__bool read_metadata_streaminfo_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  96834. {
  96835. FLAC__uint32 x;
  96836. unsigned bits, used_bits = 0;
  96837. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96838. decoder->private_->stream_info.type = FLAC__METADATA_TYPE_STREAMINFO;
  96839. decoder->private_->stream_info.is_last = is_last;
  96840. decoder->private_->stream_info.length = length;
  96841. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN;
  96842. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, bits))
  96843. return false; /* read_callback_ sets the state for us */
  96844. decoder->private_->stream_info.data.stream_info.min_blocksize = x;
  96845. used_bits += bits;
  96846. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN;
  96847. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  96848. return false; /* read_callback_ sets the state for us */
  96849. decoder->private_->stream_info.data.stream_info.max_blocksize = x;
  96850. used_bits += bits;
  96851. bits = FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN;
  96852. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  96853. return false; /* read_callback_ sets the state for us */
  96854. decoder->private_->stream_info.data.stream_info.min_framesize = x;
  96855. used_bits += bits;
  96856. bits = FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN;
  96857. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  96858. return false; /* read_callback_ sets the state for us */
  96859. decoder->private_->stream_info.data.stream_info.max_framesize = x;
  96860. used_bits += bits;
  96861. bits = FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN;
  96862. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  96863. return false; /* read_callback_ sets the state for us */
  96864. decoder->private_->stream_info.data.stream_info.sample_rate = x;
  96865. used_bits += bits;
  96866. bits = FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN;
  96867. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  96868. return false; /* read_callback_ sets the state for us */
  96869. decoder->private_->stream_info.data.stream_info.channels = x+1;
  96870. used_bits += bits;
  96871. bits = FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN;
  96872. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  96873. return false; /* read_callback_ sets the state for us */
  96874. decoder->private_->stream_info.data.stream_info.bits_per_sample = x+1;
  96875. used_bits += bits;
  96876. bits = FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN;
  96877. 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))
  96878. return false; /* read_callback_ sets the state for us */
  96879. used_bits += bits;
  96880. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, decoder->private_->stream_info.data.stream_info.md5sum, 16))
  96881. return false; /* read_callback_ sets the state for us */
  96882. used_bits += 16*8;
  96883. /* skip the rest of the block */
  96884. FLAC__ASSERT(used_bits % 8 == 0);
  96885. length -= (used_bits / 8);
  96886. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  96887. return false; /* read_callback_ sets the state for us */
  96888. return true;
  96889. }
  96890. FLAC__bool read_metadata_seektable_(FLAC__StreamDecoder *decoder, FLAC__bool is_last, unsigned length)
  96891. {
  96892. FLAC__uint32 i, x;
  96893. FLAC__uint64 xx;
  96894. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96895. decoder->private_->seek_table.type = FLAC__METADATA_TYPE_SEEKTABLE;
  96896. decoder->private_->seek_table.is_last = is_last;
  96897. decoder->private_->seek_table.length = length;
  96898. decoder->private_->seek_table.data.seek_table.num_points = length / FLAC__STREAM_METADATA_SEEKPOINT_LENGTH;
  96899. /* use realloc since we may pass through here several times (e.g. after seeking) */
  96900. 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)))) {
  96901. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96902. return false;
  96903. }
  96904. for(i = 0; i < decoder->private_->seek_table.data.seek_table.num_points; i++) {
  96905. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  96906. return false; /* read_callback_ sets the state for us */
  96907. decoder->private_->seek_table.data.seek_table.points[i].sample_number = xx;
  96908. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &xx, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  96909. return false; /* read_callback_ sets the state for us */
  96910. decoder->private_->seek_table.data.seek_table.points[i].stream_offset = xx;
  96911. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  96912. return false; /* read_callback_ sets the state for us */
  96913. decoder->private_->seek_table.data.seek_table.points[i].frame_samples = x;
  96914. }
  96915. length -= (decoder->private_->seek_table.data.seek_table.num_points * FLAC__STREAM_METADATA_SEEKPOINT_LENGTH);
  96916. /* if there is a partial point left, skip over it */
  96917. if(length > 0) {
  96918. /*@@@ do a send_error_to_client_() here? there's an argument for either way */
  96919. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, length))
  96920. return false; /* read_callback_ sets the state for us */
  96921. }
  96922. return true;
  96923. }
  96924. FLAC__bool read_metadata_vorbiscomment_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_VorbisComment *obj)
  96925. {
  96926. FLAC__uint32 i;
  96927. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96928. /* read vendor string */
  96929. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  96930. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->vendor_string.length))
  96931. return false; /* read_callback_ sets the state for us */
  96932. if(obj->vendor_string.length > 0) {
  96933. if(0 == (obj->vendor_string.entry = (FLAC__byte*)safe_malloc_add_2op_(obj->vendor_string.length, /*+*/1))) {
  96934. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96935. return false;
  96936. }
  96937. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->vendor_string.entry, obj->vendor_string.length))
  96938. return false; /* read_callback_ sets the state for us */
  96939. obj->vendor_string.entry[obj->vendor_string.length] = '\0';
  96940. }
  96941. else
  96942. obj->vendor_string.entry = 0;
  96943. /* read num comments */
  96944. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_NUM_COMMENTS_LEN == 32);
  96945. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->num_comments))
  96946. return false; /* read_callback_ sets the state for us */
  96947. /* read comments */
  96948. if(obj->num_comments > 0) {
  96949. if(0 == (obj->comments = (FLAC__StreamMetadata_VorbisComment_Entry*)safe_malloc_mul_2op_(obj->num_comments, /*times*/sizeof(FLAC__StreamMetadata_VorbisComment_Entry)))) {
  96950. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96951. return false;
  96952. }
  96953. for(i = 0; i < obj->num_comments; i++) {
  96954. FLAC__ASSERT(FLAC__STREAM_METADATA_VORBIS_COMMENT_ENTRY_LENGTH_LEN == 32);
  96955. if(!FLAC__bitreader_read_uint32_little_endian(decoder->private_->input, &obj->comments[i].length))
  96956. return false; /* read_callback_ sets the state for us */
  96957. if(obj->comments[i].length > 0) {
  96958. if(0 == (obj->comments[i].entry = (FLAC__byte*)safe_malloc_add_2op_(obj->comments[i].length, /*+*/1))) {
  96959. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96960. return false;
  96961. }
  96962. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->comments[i].entry, obj->comments[i].length))
  96963. return false; /* read_callback_ sets the state for us */
  96964. obj->comments[i].entry[obj->comments[i].length] = '\0';
  96965. }
  96966. else
  96967. obj->comments[i].entry = 0;
  96968. }
  96969. }
  96970. else {
  96971. obj->comments = 0;
  96972. }
  96973. return true;
  96974. }
  96975. FLAC__bool read_metadata_cuesheet_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_CueSheet *obj)
  96976. {
  96977. FLAC__uint32 i, j, x;
  96978. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  96979. memset(obj, 0, sizeof(FLAC__StreamMetadata_CueSheet));
  96980. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  96981. 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))
  96982. return false; /* read_callback_ sets the state for us */
  96983. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &obj->lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  96984. return false; /* read_callback_ sets the state for us */
  96985. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  96986. return false; /* read_callback_ sets the state for us */
  96987. obj->is_cd = x? true : false;
  96988. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  96989. return false; /* read_callback_ sets the state for us */
  96990. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  96991. return false; /* read_callback_ sets the state for us */
  96992. obj->num_tracks = x;
  96993. if(obj->num_tracks > 0) {
  96994. if(0 == (obj->tracks = (FLAC__StreamMetadata_CueSheet_Track*)safe_calloc_(obj->num_tracks, sizeof(FLAC__StreamMetadata_CueSheet_Track)))) {
  96995. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  96996. return false;
  96997. }
  96998. for(i = 0; i < obj->num_tracks; i++) {
  96999. FLAC__StreamMetadata_CueSheet_Track *track = &obj->tracks[i];
  97000. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  97001. return false; /* read_callback_ sets the state for us */
  97002. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  97003. return false; /* read_callback_ sets the state for us */
  97004. track->number = (FLAC__byte)x;
  97005. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  97006. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  97007. return false; /* read_callback_ sets the state for us */
  97008. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  97009. return false; /* read_callback_ sets the state for us */
  97010. track->type = x;
  97011. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  97012. return false; /* read_callback_ sets the state for us */
  97013. track->pre_emphasis = x;
  97014. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  97015. return false; /* read_callback_ sets the state for us */
  97016. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  97017. return false; /* read_callback_ sets the state for us */
  97018. track->num_indices = (FLAC__byte)x;
  97019. if(track->num_indices > 0) {
  97020. if(0 == (track->indices = (FLAC__StreamMetadata_CueSheet_Index*)safe_calloc_(track->num_indices, sizeof(FLAC__StreamMetadata_CueSheet_Index)))) {
  97021. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97022. return false;
  97023. }
  97024. for(j = 0; j < track->num_indices; j++) {
  97025. FLAC__StreamMetadata_CueSheet_Index *index = &track->indices[j];
  97026. if(!FLAC__bitreader_read_raw_uint64(decoder->private_->input, &index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  97027. return false; /* read_callback_ sets the state for us */
  97028. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  97029. return false; /* read_callback_ sets the state for us */
  97030. index->number = (FLAC__byte)x;
  97031. if(!FLAC__bitreader_skip_bits_no_crc(decoder->private_->input, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  97032. return false; /* read_callback_ sets the state for us */
  97033. }
  97034. }
  97035. }
  97036. }
  97037. return true;
  97038. }
  97039. FLAC__bool read_metadata_picture_(FLAC__StreamDecoder *decoder, FLAC__StreamMetadata_Picture *obj)
  97040. {
  97041. FLAC__uint32 x;
  97042. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97043. /* read type */
  97044. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  97045. return false; /* read_callback_ sets the state for us */
  97046. obj->type = (FLAC__StreamMetadata_Picture_Type) x;
  97047. /* read MIME type */
  97048. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  97049. return false; /* read_callback_ sets the state for us */
  97050. if(0 == (obj->mime_type = (char*)safe_malloc_add_2op_(x, /*+*/1))) {
  97051. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97052. return false;
  97053. }
  97054. if(x > 0) {
  97055. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, (FLAC__byte*)obj->mime_type, x))
  97056. return false; /* read_callback_ sets the state for us */
  97057. }
  97058. obj->mime_type[x] = '\0';
  97059. /* read description */
  97060. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  97061. return false; /* read_callback_ sets the state for us */
  97062. if(0 == (obj->description = (FLAC__byte*)safe_malloc_add_2op_(x, /*+*/1))) {
  97063. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97064. return false;
  97065. }
  97066. if(x > 0) {
  97067. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->description, x))
  97068. return false; /* read_callback_ sets the state for us */
  97069. }
  97070. obj->description[x] = '\0';
  97071. /* read width */
  97072. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  97073. return false; /* read_callback_ sets the state for us */
  97074. /* read height */
  97075. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  97076. return false; /* read_callback_ sets the state for us */
  97077. /* read depth */
  97078. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  97079. return false; /* read_callback_ sets the state for us */
  97080. /* read colors */
  97081. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &obj->colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  97082. return false; /* read_callback_ sets the state for us */
  97083. /* read data */
  97084. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &(obj->data_length), FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  97085. return false; /* read_callback_ sets the state for us */
  97086. if(0 == (obj->data = (FLAC__byte*)safe_malloc_(obj->data_length))) {
  97087. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97088. return false;
  97089. }
  97090. if(obj->data_length > 0) {
  97091. if(!FLAC__bitreader_read_byte_block_aligned_no_crc(decoder->private_->input, obj->data, obj->data_length))
  97092. return false; /* read_callback_ sets the state for us */
  97093. }
  97094. return true;
  97095. }
  97096. FLAC__bool skip_id3v2_tag_(FLAC__StreamDecoder *decoder)
  97097. {
  97098. FLAC__uint32 x;
  97099. unsigned i, skip;
  97100. /* skip the version and flags bytes */
  97101. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 24))
  97102. return false; /* read_callback_ sets the state for us */
  97103. /* get the size (in bytes) to skip */
  97104. skip = 0;
  97105. for(i = 0; i < 4; i++) {
  97106. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97107. return false; /* read_callback_ sets the state for us */
  97108. skip <<= 7;
  97109. skip |= (x & 0x7f);
  97110. }
  97111. /* skip the rest of the tag */
  97112. if(!FLAC__bitreader_skip_byte_block_aligned_no_crc(decoder->private_->input, skip))
  97113. return false; /* read_callback_ sets the state for us */
  97114. return true;
  97115. }
  97116. FLAC__bool frame_sync_(FLAC__StreamDecoder *decoder)
  97117. {
  97118. FLAC__uint32 x;
  97119. FLAC__bool first = true;
  97120. /* If we know the total number of samples in the stream, stop if we've read that many. */
  97121. /* This will stop us, for example, from wasting time trying to sync on an ID3V1 tag. */
  97122. if(FLAC__stream_decoder_get_total_samples(decoder) > 0) {
  97123. if(decoder->private_->samples_decoded >= FLAC__stream_decoder_get_total_samples(decoder)) {
  97124. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97125. return true;
  97126. }
  97127. }
  97128. /* make sure we're byte aligned */
  97129. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  97130. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  97131. return false; /* read_callback_ sets the state for us */
  97132. }
  97133. while(1) {
  97134. if(decoder->private_->cached) {
  97135. x = (FLAC__uint32)decoder->private_->lookahead;
  97136. decoder->private_->cached = false;
  97137. }
  97138. else {
  97139. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97140. return false; /* read_callback_ sets the state for us */
  97141. }
  97142. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97143. decoder->private_->header_warmup[0] = (FLAC__byte)x;
  97144. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97145. return false; /* read_callback_ sets the state for us */
  97146. /* 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 */
  97147. /* else we have to check if the second byte is the end of a sync code */
  97148. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97149. decoder->private_->lookahead = (FLAC__byte)x;
  97150. decoder->private_->cached = true;
  97151. }
  97152. else if(x >> 2 == 0x3e) { /* MAGIC NUMBER for the last 6 sync bits */
  97153. decoder->private_->header_warmup[1] = (FLAC__byte)x;
  97154. decoder->protected_->state = FLAC__STREAM_DECODER_READ_FRAME;
  97155. return true;
  97156. }
  97157. }
  97158. if(first) {
  97159. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97160. first = false;
  97161. }
  97162. }
  97163. return true;
  97164. }
  97165. FLAC__bool read_frame_(FLAC__StreamDecoder *decoder, FLAC__bool *got_a_frame, FLAC__bool do_full_decode)
  97166. {
  97167. unsigned channel;
  97168. unsigned i;
  97169. FLAC__int32 mid, side;
  97170. unsigned frame_crc; /* the one we calculate from the input stream */
  97171. FLAC__uint32 x;
  97172. *got_a_frame = false;
  97173. /* init the CRC */
  97174. frame_crc = 0;
  97175. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[0], frame_crc);
  97176. frame_crc = FLAC__CRC16_UPDATE(decoder->private_->header_warmup[1], frame_crc);
  97177. FLAC__bitreader_reset_read_crc16(decoder->private_->input, (FLAC__uint16)frame_crc);
  97178. if(!read_frame_header_(decoder))
  97179. return false;
  97180. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means we didn't sync on a valid header */
  97181. return true;
  97182. if(!allocate_output_(decoder, decoder->private_->frame.header.blocksize, decoder->private_->frame.header.channels))
  97183. return false;
  97184. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  97185. /*
  97186. * first figure the correct bits-per-sample of the subframe
  97187. */
  97188. unsigned bps = decoder->private_->frame.header.bits_per_sample;
  97189. switch(decoder->private_->frame.header.channel_assignment) {
  97190. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  97191. /* no adjustment needed */
  97192. break;
  97193. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  97194. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97195. if(channel == 1)
  97196. bps++;
  97197. break;
  97198. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  97199. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97200. if(channel == 0)
  97201. bps++;
  97202. break;
  97203. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  97204. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97205. if(channel == 1)
  97206. bps++;
  97207. break;
  97208. default:
  97209. FLAC__ASSERT(0);
  97210. }
  97211. /*
  97212. * now read it
  97213. */
  97214. if(!read_subframe_(decoder, channel, bps, do_full_decode))
  97215. return false;
  97216. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  97217. return true;
  97218. }
  97219. if(!read_zero_padding_(decoder))
  97220. return false;
  97221. 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) */
  97222. return true;
  97223. /*
  97224. * Read the frame CRC-16 from the footer and check
  97225. */
  97226. frame_crc = FLAC__bitreader_get_read_crc16(decoder->private_->input);
  97227. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, FLAC__FRAME_FOOTER_CRC_LEN))
  97228. return false; /* read_callback_ sets the state for us */
  97229. if(frame_crc == x) {
  97230. if(do_full_decode) {
  97231. /* Undo any special channel coding */
  97232. switch(decoder->private_->frame.header.channel_assignment) {
  97233. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  97234. /* do nothing */
  97235. break;
  97236. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  97237. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97238. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97239. decoder->private_->output[1][i] = decoder->private_->output[0][i] - decoder->private_->output[1][i];
  97240. break;
  97241. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  97242. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97243. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97244. decoder->private_->output[0][i] += decoder->private_->output[1][i];
  97245. break;
  97246. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  97247. FLAC__ASSERT(decoder->private_->frame.header.channels == 2);
  97248. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  97249. #if 1
  97250. mid = decoder->private_->output[0][i];
  97251. side = decoder->private_->output[1][i];
  97252. mid <<= 1;
  97253. mid |= (side & 1); /* i.e. if 'side' is odd... */
  97254. decoder->private_->output[0][i] = (mid + side) >> 1;
  97255. decoder->private_->output[1][i] = (mid - side) >> 1;
  97256. #else
  97257. /* OPT: without 'side' temp variable */
  97258. mid = (decoder->private_->output[0][i] << 1) | (decoder->private_->output[1][i] & 1); /* i.e. if 'side' is odd... */
  97259. decoder->private_->output[0][i] = (mid + decoder->private_->output[1][i]) >> 1;
  97260. decoder->private_->output[1][i] = (mid - decoder->private_->output[1][i]) >> 1;
  97261. #endif
  97262. }
  97263. break;
  97264. default:
  97265. FLAC__ASSERT(0);
  97266. break;
  97267. }
  97268. }
  97269. }
  97270. else {
  97271. /* Bad frame, emit error and zero the output signal */
  97272. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_FRAME_CRC_MISMATCH);
  97273. if(do_full_decode) {
  97274. for(channel = 0; channel < decoder->private_->frame.header.channels; channel++) {
  97275. memset(decoder->private_->output[channel], 0, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  97276. }
  97277. }
  97278. }
  97279. *got_a_frame = true;
  97280. /* we wait to update fixed_block_size until here, when we're sure we've got a proper frame and hence a correct blocksize */
  97281. if(decoder->private_->next_fixed_block_size)
  97282. decoder->private_->fixed_block_size = decoder->private_->next_fixed_block_size;
  97283. /* put the latest values into the public section of the decoder instance */
  97284. decoder->protected_->channels = decoder->private_->frame.header.channels;
  97285. decoder->protected_->channel_assignment = decoder->private_->frame.header.channel_assignment;
  97286. decoder->protected_->bits_per_sample = decoder->private_->frame.header.bits_per_sample;
  97287. decoder->protected_->sample_rate = decoder->private_->frame.header.sample_rate;
  97288. decoder->protected_->blocksize = decoder->private_->frame.header.blocksize;
  97289. FLAC__ASSERT(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  97290. decoder->private_->samples_decoded = decoder->private_->frame.header.number.sample_number + decoder->private_->frame.header.blocksize;
  97291. /* write it */
  97292. if(do_full_decode) {
  97293. if(write_audio_frame_to_client_(decoder, &decoder->private_->frame, (const FLAC__int32 * const *)decoder->private_->output) != FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE)
  97294. return false;
  97295. }
  97296. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97297. return true;
  97298. }
  97299. FLAC__bool read_frame_header_(FLAC__StreamDecoder *decoder)
  97300. {
  97301. FLAC__uint32 x;
  97302. FLAC__uint64 xx;
  97303. unsigned i, blocksize_hint = 0, sample_rate_hint = 0;
  97304. FLAC__byte crc8, raw_header[16]; /* MAGIC NUMBER based on the maximum frame header size, including CRC */
  97305. unsigned raw_header_len;
  97306. FLAC__bool is_unparseable = false;
  97307. FLAC__ASSERT(FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input));
  97308. /* init the raw header with the saved bits from synchronization */
  97309. raw_header[0] = decoder->private_->header_warmup[0];
  97310. raw_header[1] = decoder->private_->header_warmup[1];
  97311. raw_header_len = 2;
  97312. /* check to make sure that reserved bit is 0 */
  97313. if(raw_header[1] & 0x02) /* MAGIC NUMBER */
  97314. is_unparseable = true;
  97315. /*
  97316. * Note that along the way as we read the header, we look for a sync
  97317. * code inside. If we find one it would indicate that our original
  97318. * sync was bad since there cannot be a sync code in a valid header.
  97319. *
  97320. * Three kinds of things can go wrong when reading the frame header:
  97321. * 1) We may have sync'ed incorrectly and not landed on a frame header.
  97322. * If we don't find a sync code, it can end up looking like we read
  97323. * a valid but unparseable header, until getting to the frame header
  97324. * CRC. Even then we could get a false positive on the CRC.
  97325. * 2) We may have sync'ed correctly but on an unparseable frame (from a
  97326. * future encoder).
  97327. * 3) We may be on a damaged frame which appears valid but unparseable.
  97328. *
  97329. * For all these reasons, we try and read a complete frame header as
  97330. * long as it seems valid, even if unparseable, up until the frame
  97331. * header CRC.
  97332. */
  97333. /*
  97334. * read in the raw header as bytes so we can CRC it, and parse it on the way
  97335. */
  97336. for(i = 0; i < 2; i++) {
  97337. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97338. return false; /* read_callback_ sets the state for us */
  97339. if(x == 0xff) { /* MAGIC NUMBER for the first 8 frame sync bits */
  97340. /* if we get here it means our original sync was erroneous since the sync code cannot appear in the header */
  97341. decoder->private_->lookahead = (FLAC__byte)x;
  97342. decoder->private_->cached = true;
  97343. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97344. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97345. return true;
  97346. }
  97347. raw_header[raw_header_len++] = (FLAC__byte)x;
  97348. }
  97349. switch(x = raw_header[2] >> 4) {
  97350. case 0:
  97351. is_unparseable = true;
  97352. break;
  97353. case 1:
  97354. decoder->private_->frame.header.blocksize = 192;
  97355. break;
  97356. case 2:
  97357. case 3:
  97358. case 4:
  97359. case 5:
  97360. decoder->private_->frame.header.blocksize = 576 << (x-2);
  97361. break;
  97362. case 6:
  97363. case 7:
  97364. blocksize_hint = x;
  97365. break;
  97366. case 8:
  97367. case 9:
  97368. case 10:
  97369. case 11:
  97370. case 12:
  97371. case 13:
  97372. case 14:
  97373. case 15:
  97374. decoder->private_->frame.header.blocksize = 256 << (x-8);
  97375. break;
  97376. default:
  97377. FLAC__ASSERT(0);
  97378. break;
  97379. }
  97380. switch(x = raw_header[2] & 0x0f) {
  97381. case 0:
  97382. if(decoder->private_->has_stream_info)
  97383. decoder->private_->frame.header.sample_rate = decoder->private_->stream_info.data.stream_info.sample_rate;
  97384. else
  97385. is_unparseable = true;
  97386. break;
  97387. case 1:
  97388. decoder->private_->frame.header.sample_rate = 88200;
  97389. break;
  97390. case 2:
  97391. decoder->private_->frame.header.sample_rate = 176400;
  97392. break;
  97393. case 3:
  97394. decoder->private_->frame.header.sample_rate = 192000;
  97395. break;
  97396. case 4:
  97397. decoder->private_->frame.header.sample_rate = 8000;
  97398. break;
  97399. case 5:
  97400. decoder->private_->frame.header.sample_rate = 16000;
  97401. break;
  97402. case 6:
  97403. decoder->private_->frame.header.sample_rate = 22050;
  97404. break;
  97405. case 7:
  97406. decoder->private_->frame.header.sample_rate = 24000;
  97407. break;
  97408. case 8:
  97409. decoder->private_->frame.header.sample_rate = 32000;
  97410. break;
  97411. case 9:
  97412. decoder->private_->frame.header.sample_rate = 44100;
  97413. break;
  97414. case 10:
  97415. decoder->private_->frame.header.sample_rate = 48000;
  97416. break;
  97417. case 11:
  97418. decoder->private_->frame.header.sample_rate = 96000;
  97419. break;
  97420. case 12:
  97421. case 13:
  97422. case 14:
  97423. sample_rate_hint = x;
  97424. break;
  97425. case 15:
  97426. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97427. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97428. return true;
  97429. default:
  97430. FLAC__ASSERT(0);
  97431. }
  97432. x = (unsigned)(raw_header[3] >> 4);
  97433. if(x & 8) {
  97434. decoder->private_->frame.header.channels = 2;
  97435. switch(x & 7) {
  97436. case 0:
  97437. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE;
  97438. break;
  97439. case 1:
  97440. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE;
  97441. break;
  97442. case 2:
  97443. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_MID_SIDE;
  97444. break;
  97445. default:
  97446. is_unparseable = true;
  97447. break;
  97448. }
  97449. }
  97450. else {
  97451. decoder->private_->frame.header.channels = (unsigned)x + 1;
  97452. decoder->private_->frame.header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  97453. }
  97454. switch(x = (unsigned)(raw_header[3] & 0x0e) >> 1) {
  97455. case 0:
  97456. if(decoder->private_->has_stream_info)
  97457. decoder->private_->frame.header.bits_per_sample = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  97458. else
  97459. is_unparseable = true;
  97460. break;
  97461. case 1:
  97462. decoder->private_->frame.header.bits_per_sample = 8;
  97463. break;
  97464. case 2:
  97465. decoder->private_->frame.header.bits_per_sample = 12;
  97466. break;
  97467. case 4:
  97468. decoder->private_->frame.header.bits_per_sample = 16;
  97469. break;
  97470. case 5:
  97471. decoder->private_->frame.header.bits_per_sample = 20;
  97472. break;
  97473. case 6:
  97474. decoder->private_->frame.header.bits_per_sample = 24;
  97475. break;
  97476. case 3:
  97477. case 7:
  97478. is_unparseable = true;
  97479. break;
  97480. default:
  97481. FLAC__ASSERT(0);
  97482. break;
  97483. }
  97484. /* check to make sure that reserved bit is 0 */
  97485. if(raw_header[3] & 0x01) /* MAGIC NUMBER */
  97486. is_unparseable = true;
  97487. /* read the frame's starting sample number (or frame number as the case may be) */
  97488. if(
  97489. raw_header[1] & 0x01 ||
  97490. /*@@@ 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 */
  97491. (decoder->private_->has_stream_info && decoder->private_->stream_info.data.stream_info.min_blocksize != decoder->private_->stream_info.data.stream_info.max_blocksize)
  97492. ) { /* variable blocksize */
  97493. if(!FLAC__bitreader_read_utf8_uint64(decoder->private_->input, &xx, raw_header, &raw_header_len))
  97494. return false; /* read_callback_ sets the state for us */
  97495. if(xx == FLAC__U64L(0xffffffffffffffff)) { /* i.e. non-UTF8 code... */
  97496. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  97497. decoder->private_->cached = true;
  97498. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97499. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97500. return true;
  97501. }
  97502. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  97503. decoder->private_->frame.header.number.sample_number = xx;
  97504. }
  97505. else { /* fixed blocksize */
  97506. if(!FLAC__bitreader_read_utf8_uint32(decoder->private_->input, &x, raw_header, &raw_header_len))
  97507. return false; /* read_callback_ sets the state for us */
  97508. if(x == 0xffffffff) { /* i.e. non-UTF8 code... */
  97509. decoder->private_->lookahead = raw_header[raw_header_len-1]; /* back up as much as we can */
  97510. decoder->private_->cached = true;
  97511. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97512. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97513. return true;
  97514. }
  97515. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  97516. decoder->private_->frame.header.number.frame_number = x;
  97517. }
  97518. if(blocksize_hint) {
  97519. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97520. return false; /* read_callback_ sets the state for us */
  97521. raw_header[raw_header_len++] = (FLAC__byte)x;
  97522. if(blocksize_hint == 7) {
  97523. FLAC__uint32 _x;
  97524. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  97525. return false; /* read_callback_ sets the state for us */
  97526. raw_header[raw_header_len++] = (FLAC__byte)_x;
  97527. x = (x << 8) | _x;
  97528. }
  97529. decoder->private_->frame.header.blocksize = x+1;
  97530. }
  97531. if(sample_rate_hint) {
  97532. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97533. return false; /* read_callback_ sets the state for us */
  97534. raw_header[raw_header_len++] = (FLAC__byte)x;
  97535. if(sample_rate_hint != 12) {
  97536. FLAC__uint32 _x;
  97537. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &_x, 8))
  97538. return false; /* read_callback_ sets the state for us */
  97539. raw_header[raw_header_len++] = (FLAC__byte)_x;
  97540. x = (x << 8) | _x;
  97541. }
  97542. if(sample_rate_hint == 12)
  97543. decoder->private_->frame.header.sample_rate = x*1000;
  97544. else if(sample_rate_hint == 13)
  97545. decoder->private_->frame.header.sample_rate = x;
  97546. else
  97547. decoder->private_->frame.header.sample_rate = x*10;
  97548. }
  97549. /* read the CRC-8 byte */
  97550. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8))
  97551. return false; /* read_callback_ sets the state for us */
  97552. crc8 = (FLAC__byte)x;
  97553. if(FLAC__crc8(raw_header, raw_header_len) != crc8) {
  97554. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_BAD_HEADER);
  97555. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97556. return true;
  97557. }
  97558. /* calculate the sample number from the frame number if needed */
  97559. decoder->private_->next_fixed_block_size = 0;
  97560. if(decoder->private_->frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  97561. x = decoder->private_->frame.header.number.frame_number;
  97562. decoder->private_->frame.header.number_type = FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER;
  97563. if(decoder->private_->fixed_block_size)
  97564. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->fixed_block_size * (FLAC__uint64)x;
  97565. else if(decoder->private_->has_stream_info) {
  97566. if(decoder->private_->stream_info.data.stream_info.min_blocksize == decoder->private_->stream_info.data.stream_info.max_blocksize) {
  97567. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->stream_info.data.stream_info.min_blocksize * (FLAC__uint64)x;
  97568. decoder->private_->next_fixed_block_size = decoder->private_->stream_info.data.stream_info.max_blocksize;
  97569. }
  97570. else
  97571. is_unparseable = true;
  97572. }
  97573. else if(x == 0) {
  97574. decoder->private_->frame.header.number.sample_number = 0;
  97575. decoder->private_->next_fixed_block_size = decoder->private_->frame.header.blocksize;
  97576. }
  97577. else {
  97578. /* can only get here if the stream has invalid frame numbering and no STREAMINFO, so assume it's not the last (possibly short) frame */
  97579. decoder->private_->frame.header.number.sample_number = (FLAC__uint64)decoder->private_->frame.header.blocksize * (FLAC__uint64)x;
  97580. }
  97581. }
  97582. if(is_unparseable) {
  97583. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97584. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97585. return true;
  97586. }
  97587. return true;
  97588. }
  97589. FLAC__bool read_subframe_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  97590. {
  97591. FLAC__uint32 x;
  97592. FLAC__bool wasted_bits;
  97593. unsigned i;
  97594. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &x, 8)) /* MAGIC NUMBER */
  97595. return false; /* read_callback_ sets the state for us */
  97596. wasted_bits = (x & 1);
  97597. x &= 0xfe;
  97598. if(wasted_bits) {
  97599. unsigned u;
  97600. if(!FLAC__bitreader_read_unary_unsigned(decoder->private_->input, &u))
  97601. return false; /* read_callback_ sets the state for us */
  97602. decoder->private_->frame.subframes[channel].wasted_bits = u+1;
  97603. bps -= decoder->private_->frame.subframes[channel].wasted_bits;
  97604. }
  97605. else
  97606. decoder->private_->frame.subframes[channel].wasted_bits = 0;
  97607. /*
  97608. * Lots of magic numbers here
  97609. */
  97610. if(x & 0x80) {
  97611. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97612. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97613. return true;
  97614. }
  97615. else if(x == 0) {
  97616. if(!read_subframe_constant_(decoder, channel, bps, do_full_decode))
  97617. return false;
  97618. }
  97619. else if(x == 2) {
  97620. if(!read_subframe_verbatim_(decoder, channel, bps, do_full_decode))
  97621. return false;
  97622. }
  97623. else if(x < 16) {
  97624. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97625. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97626. return true;
  97627. }
  97628. else if(x <= 24) {
  97629. if(!read_subframe_fixed_(decoder, channel, bps, (x>>1)&7, do_full_decode))
  97630. return false;
  97631. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  97632. return true;
  97633. }
  97634. else if(x < 64) {
  97635. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97636. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97637. return true;
  97638. }
  97639. else {
  97640. if(!read_subframe_lpc_(decoder, channel, bps, ((x>>1)&31)+1, do_full_decode))
  97641. return false;
  97642. if(decoder->protected_->state == FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC) /* means bad sync or got corruption */
  97643. return true;
  97644. }
  97645. if(wasted_bits && do_full_decode) {
  97646. x = decoder->private_->frame.subframes[channel].wasted_bits;
  97647. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97648. decoder->private_->output[channel][i] <<= x;
  97649. }
  97650. return true;
  97651. }
  97652. FLAC__bool read_subframe_constant_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  97653. {
  97654. FLAC__Subframe_Constant *subframe = &decoder->private_->frame.subframes[channel].data.constant;
  97655. FLAC__int32 x;
  97656. unsigned i;
  97657. FLAC__int32 *output = decoder->private_->output[channel];
  97658. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_CONSTANT;
  97659. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  97660. return false; /* read_callback_ sets the state for us */
  97661. subframe->value = x;
  97662. /* decode the subframe */
  97663. if(do_full_decode) {
  97664. for(i = 0; i < decoder->private_->frame.header.blocksize; i++)
  97665. output[i] = x;
  97666. }
  97667. return true;
  97668. }
  97669. FLAC__bool read_subframe_fixed_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  97670. {
  97671. FLAC__Subframe_Fixed *subframe = &decoder->private_->frame.subframes[channel].data.fixed;
  97672. FLAC__int32 i32;
  97673. FLAC__uint32 u32;
  97674. unsigned u;
  97675. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_FIXED;
  97676. subframe->residual = decoder->private_->residual[channel];
  97677. subframe->order = order;
  97678. /* read warm-up samples */
  97679. for(u = 0; u < order; u++) {
  97680. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  97681. return false; /* read_callback_ sets the state for us */
  97682. subframe->warmup[u] = i32;
  97683. }
  97684. /* read entropy coding method info */
  97685. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  97686. return false; /* read_callback_ sets the state for us */
  97687. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  97688. switch(subframe->entropy_coding_method.type) {
  97689. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97690. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97691. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  97692. return false; /* read_callback_ sets the state for us */
  97693. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  97694. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  97695. break;
  97696. default:
  97697. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97698. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97699. return true;
  97700. }
  97701. /* read residual */
  97702. switch(subframe->entropy_coding_method.type) {
  97703. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97704. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97705. 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))
  97706. return false;
  97707. break;
  97708. default:
  97709. FLAC__ASSERT(0);
  97710. }
  97711. /* decode the subframe */
  97712. if(do_full_decode) {
  97713. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  97714. FLAC__fixed_restore_signal(decoder->private_->residual[channel], decoder->private_->frame.header.blocksize-order, order, decoder->private_->output[channel]+order);
  97715. }
  97716. return true;
  97717. }
  97718. FLAC__bool read_subframe_lpc_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, const unsigned order, FLAC__bool do_full_decode)
  97719. {
  97720. FLAC__Subframe_LPC *subframe = &decoder->private_->frame.subframes[channel].data.lpc;
  97721. FLAC__int32 i32;
  97722. FLAC__uint32 u32;
  97723. unsigned u;
  97724. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_LPC;
  97725. subframe->residual = decoder->private_->residual[channel];
  97726. subframe->order = order;
  97727. /* read warm-up samples */
  97728. for(u = 0; u < order; u++) {
  97729. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, bps))
  97730. return false; /* read_callback_ sets the state for us */
  97731. subframe->warmup[u] = i32;
  97732. }
  97733. /* read qlp coeff precision */
  97734. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  97735. return false; /* read_callback_ sets the state for us */
  97736. if(u32 == (1u << FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN) - 1) {
  97737. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97738. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97739. return true;
  97740. }
  97741. subframe->qlp_coeff_precision = u32+1;
  97742. /* read qlp shift */
  97743. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  97744. return false; /* read_callback_ sets the state for us */
  97745. subframe->quantization_level = i32;
  97746. /* read quantized lp coefficiencts */
  97747. for(u = 0; u < order; u++) {
  97748. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &i32, subframe->qlp_coeff_precision))
  97749. return false; /* read_callback_ sets the state for us */
  97750. subframe->qlp_coeff[u] = i32;
  97751. }
  97752. /* read entropy coding method info */
  97753. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  97754. return false; /* read_callback_ sets the state for us */
  97755. subframe->entropy_coding_method.type = (FLAC__EntropyCodingMethodType)u32;
  97756. switch(subframe->entropy_coding_method.type) {
  97757. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97758. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97759. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &u32, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  97760. return false; /* read_callback_ sets the state for us */
  97761. subframe->entropy_coding_method.data.partitioned_rice.order = u32;
  97762. subframe->entropy_coding_method.data.partitioned_rice.contents = &decoder->private_->partitioned_rice_contents[channel];
  97763. break;
  97764. default:
  97765. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM);
  97766. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97767. return true;
  97768. }
  97769. /* read residual */
  97770. switch(subframe->entropy_coding_method.type) {
  97771. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  97772. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  97773. 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))
  97774. return false;
  97775. break;
  97776. default:
  97777. FLAC__ASSERT(0);
  97778. }
  97779. /* decode the subframe */
  97780. if(do_full_decode) {
  97781. memcpy(decoder->private_->output[channel], subframe->warmup, sizeof(FLAC__int32) * order);
  97782. /*@@@@@@ technically not pessimistic enough, should be more like
  97783. if( (FLAC__uint64)order * ((((FLAC__uint64)1)<<bps)-1) * ((1<<subframe->qlp_coeff_precision)-1) < (((FLAC__uint64)-1) << 32) )
  97784. */
  97785. if(bps + subframe->qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  97786. if(bps <= 16 && subframe->qlp_coeff_precision <= 16) {
  97787. if(order <= 8)
  97788. 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);
  97789. else
  97790. 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);
  97791. }
  97792. else
  97793. 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);
  97794. else
  97795. 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);
  97796. }
  97797. return true;
  97798. }
  97799. FLAC__bool read_subframe_verbatim_(FLAC__StreamDecoder *decoder, unsigned channel, unsigned bps, FLAC__bool do_full_decode)
  97800. {
  97801. FLAC__Subframe_Verbatim *subframe = &decoder->private_->frame.subframes[channel].data.verbatim;
  97802. FLAC__int32 x, *residual = decoder->private_->residual[channel];
  97803. unsigned i;
  97804. decoder->private_->frame.subframes[channel].type = FLAC__SUBFRAME_TYPE_VERBATIM;
  97805. subframe->data = residual;
  97806. for(i = 0; i < decoder->private_->frame.header.blocksize; i++) {
  97807. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, &x, bps))
  97808. return false; /* read_callback_ sets the state for us */
  97809. residual[i] = x;
  97810. }
  97811. /* decode the subframe */
  97812. if(do_full_decode)
  97813. memcpy(decoder->private_->output[channel], subframe->data, sizeof(FLAC__int32) * decoder->private_->frame.header.blocksize);
  97814. return true;
  97815. }
  97816. 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)
  97817. {
  97818. FLAC__uint32 rice_parameter;
  97819. int i;
  97820. unsigned partition, sample, u;
  97821. const unsigned partitions = 1u << partition_order;
  97822. const unsigned partition_samples = partition_order > 0? decoder->private_->frame.header.blocksize >> partition_order : decoder->private_->frame.header.blocksize - predictor_order;
  97823. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  97824. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  97825. /* sanity checks */
  97826. if(partition_order == 0) {
  97827. if(decoder->private_->frame.header.blocksize < predictor_order) {
  97828. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97829. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97830. return true;
  97831. }
  97832. }
  97833. else {
  97834. if(partition_samples < predictor_order) {
  97835. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97836. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97837. return true;
  97838. }
  97839. }
  97840. if(!FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order))) {
  97841. decoder->protected_->state = FLAC__STREAM_DECODER_MEMORY_ALLOCATION_ERROR;
  97842. return false;
  97843. }
  97844. sample = 0;
  97845. for(partition = 0; partition < partitions; partition++) {
  97846. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, plen))
  97847. return false; /* read_callback_ sets the state for us */
  97848. partitioned_rice_contents->parameters[partition] = rice_parameter;
  97849. if(rice_parameter < pesc) {
  97850. partitioned_rice_contents->raw_bits[partition] = 0;
  97851. u = (partition_order == 0 || partition > 0)? partition_samples : partition_samples - predictor_order;
  97852. if(!decoder->private_->local_bitreader_read_rice_signed_block(decoder->private_->input, (int*) residual + sample, u, rice_parameter))
  97853. return false; /* read_callback_ sets the state for us */
  97854. sample += u;
  97855. }
  97856. else {
  97857. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &rice_parameter, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  97858. return false; /* read_callback_ sets the state for us */
  97859. partitioned_rice_contents->raw_bits[partition] = rice_parameter;
  97860. for(u = (partition_order == 0 || partition > 0)? 0 : predictor_order; u < partition_samples; u++, sample++) {
  97861. if(!FLAC__bitreader_read_raw_int32(decoder->private_->input, (FLAC__int32*) &i, rice_parameter))
  97862. return false; /* read_callback_ sets the state for us */
  97863. residual[sample] = i;
  97864. }
  97865. }
  97866. }
  97867. return true;
  97868. }
  97869. FLAC__bool read_zero_padding_(FLAC__StreamDecoder *decoder)
  97870. {
  97871. if(!FLAC__bitreader_is_consumed_byte_aligned(decoder->private_->input)) {
  97872. FLAC__uint32 zero = 0;
  97873. if(!FLAC__bitreader_read_raw_uint32(decoder->private_->input, &zero, FLAC__bitreader_bits_left_for_byte_alignment(decoder->private_->input)))
  97874. return false; /* read_callback_ sets the state for us */
  97875. if(zero != 0) {
  97876. send_error_to_client_(decoder, FLAC__STREAM_DECODER_ERROR_STATUS_LOST_SYNC);
  97877. decoder->protected_->state = FLAC__STREAM_DECODER_SEARCH_FOR_FRAME_SYNC;
  97878. }
  97879. }
  97880. return true;
  97881. }
  97882. FLAC__bool read_callback_(FLAC__byte buffer[], size_t *bytes, void *client_data)
  97883. {
  97884. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder *)client_data;
  97885. if(
  97886. #if FLAC__HAS_OGG
  97887. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  97888. !decoder->private_->is_ogg &&
  97889. #endif
  97890. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  97891. ) {
  97892. *bytes = 0;
  97893. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97894. return false;
  97895. }
  97896. else if(*bytes > 0) {
  97897. /* While seeking, it is possible for our seek to land in the
  97898. * middle of audio data that looks exactly like a frame header
  97899. * from a future version of an encoder. When that happens, our
  97900. * error callback will get an
  97901. * FLAC__STREAM_DECODER_UNPARSEABLE_STREAM and increment its
  97902. * unparseable_frame_count. But there is a remote possibility
  97903. * that it is properly synced at such a "future-codec frame",
  97904. * so to make sure, we wait to see many "unparseable" errors in
  97905. * a row before bailing out.
  97906. */
  97907. if(decoder->private_->is_seeking && decoder->private_->unparseable_frame_count > 20) {
  97908. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97909. return false;
  97910. }
  97911. else {
  97912. const FLAC__StreamDecoderReadStatus status =
  97913. #if FLAC__HAS_OGG
  97914. decoder->private_->is_ogg?
  97915. read_callback_ogg_aspect_(decoder, buffer, bytes) :
  97916. #endif
  97917. decoder->private_->read_callback(decoder, buffer, bytes, decoder->private_->client_data)
  97918. ;
  97919. if(status == FLAC__STREAM_DECODER_READ_STATUS_ABORT) {
  97920. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97921. return false;
  97922. }
  97923. else if(*bytes == 0) {
  97924. if(
  97925. status == FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM ||
  97926. (
  97927. #if FLAC__HAS_OGG
  97928. /* see [1] HACK NOTE below for why we don't call the eof_callback when decoding Ogg FLAC */
  97929. !decoder->private_->is_ogg &&
  97930. #endif
  97931. decoder->private_->eof_callback && decoder->private_->eof_callback(decoder, decoder->private_->client_data)
  97932. )
  97933. ) {
  97934. decoder->protected_->state = FLAC__STREAM_DECODER_END_OF_STREAM;
  97935. return false;
  97936. }
  97937. else
  97938. return true;
  97939. }
  97940. else
  97941. return true;
  97942. }
  97943. }
  97944. else {
  97945. /* abort to avoid a deadlock */
  97946. decoder->protected_->state = FLAC__STREAM_DECODER_ABORTED;
  97947. return false;
  97948. }
  97949. /* [1] @@@ HACK NOTE: The end-of-stream checking has to be hacked around
  97950. * for Ogg FLAC. This is because the ogg decoder aspect can lose sync
  97951. * and at the same time hit the end of the stream (for example, seeking
  97952. * to a point that is after the beginning of the last Ogg page). There
  97953. * is no way to report an Ogg sync loss through the callbacks (see note
  97954. * in read_callback_ogg_aspect_()) so it returns CONTINUE with *bytes==0.
  97955. * So to keep the decoder from stopping at this point we gate the call
  97956. * to the eof_callback and let the Ogg decoder aspect set the
  97957. * end-of-stream state when it is needed.
  97958. */
  97959. }
  97960. #if FLAC__HAS_OGG
  97961. FLAC__StreamDecoderReadStatus read_callback_ogg_aspect_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes)
  97962. {
  97963. switch(FLAC__ogg_decoder_aspect_read_callback_wrapper(&decoder->protected_->ogg_decoder_aspect, buffer, bytes, read_callback_proxy_, decoder, decoder->private_->client_data)) {
  97964. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK:
  97965. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97966. /* we don't really have a way to handle lost sync via read
  97967. * callback so we'll let it pass and let the underlying
  97968. * FLAC decoder catch the error
  97969. */
  97970. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_LOST_SYNC:
  97971. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  97972. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM:
  97973. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  97974. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_NOT_FLAC:
  97975. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_UNSUPPORTED_MAPPING_VERSION:
  97976. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT:
  97977. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_ERROR:
  97978. case FLAC__OGG_DECODER_ASPECT_READ_STATUS_MEMORY_ALLOCATION_ERROR:
  97979. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97980. default:
  97981. FLAC__ASSERT(0);
  97982. /* double protection */
  97983. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  97984. }
  97985. }
  97986. FLAC__OggDecoderAspectReadStatus read_callback_proxy_(const void *void_decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  97987. {
  97988. FLAC__StreamDecoder *decoder = (FLAC__StreamDecoder*)void_decoder;
  97989. switch(decoder->private_->read_callback(decoder, buffer, bytes, client_data)) {
  97990. case FLAC__STREAM_DECODER_READ_STATUS_CONTINUE:
  97991. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_OK;
  97992. case FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM:
  97993. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_END_OF_STREAM;
  97994. case FLAC__STREAM_DECODER_READ_STATUS_ABORT:
  97995. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  97996. default:
  97997. /* double protection: */
  97998. FLAC__ASSERT(0);
  97999. return FLAC__OGG_DECODER_ASPECT_READ_STATUS_ABORT;
  98000. }
  98001. }
  98002. #endif
  98003. FLAC__StreamDecoderWriteStatus write_audio_frame_to_client_(FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[])
  98004. {
  98005. if(decoder->private_->is_seeking) {
  98006. FLAC__uint64 this_frame_sample = frame->header.number.sample_number;
  98007. FLAC__uint64 next_frame_sample = this_frame_sample + (FLAC__uint64)frame->header.blocksize;
  98008. FLAC__uint64 target_sample = decoder->private_->target_sample;
  98009. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98010. #if FLAC__HAS_OGG
  98011. decoder->private_->got_a_frame = true;
  98012. #endif
  98013. decoder->private_->last_frame = *frame; /* save the frame */
  98014. if(this_frame_sample <= target_sample && target_sample < next_frame_sample) { /* we hit our target frame */
  98015. unsigned delta = (unsigned)(target_sample - this_frame_sample);
  98016. /* kick out of seek mode */
  98017. decoder->private_->is_seeking = false;
  98018. /* shift out the samples before target_sample */
  98019. if(delta > 0) {
  98020. unsigned channel;
  98021. const FLAC__int32 *newbuffer[FLAC__MAX_CHANNELS];
  98022. for(channel = 0; channel < frame->header.channels; channel++)
  98023. newbuffer[channel] = buffer[channel] + delta;
  98024. decoder->private_->last_frame.header.blocksize -= delta;
  98025. decoder->private_->last_frame.header.number.sample_number += (FLAC__uint64)delta;
  98026. /* write the relevant samples */
  98027. return decoder->private_->write_callback(decoder, &decoder->private_->last_frame, newbuffer, decoder->private_->client_data);
  98028. }
  98029. else {
  98030. /* write the relevant samples */
  98031. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  98032. }
  98033. }
  98034. else {
  98035. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  98036. }
  98037. }
  98038. else {
  98039. /*
  98040. * If we never got STREAMINFO, turn off MD5 checking to save
  98041. * cycles since we don't have a sum to compare to anyway
  98042. */
  98043. if(!decoder->private_->has_stream_info)
  98044. decoder->private_->do_md5_checking = false;
  98045. if(decoder->private_->do_md5_checking) {
  98046. if(!FLAC__MD5Accumulate(&decoder->private_->md5context, buffer, frame->header.channels, frame->header.blocksize, (frame->header.bits_per_sample+7) / 8))
  98047. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  98048. }
  98049. return decoder->private_->write_callback(decoder, frame, buffer, decoder->private_->client_data);
  98050. }
  98051. }
  98052. void send_error_to_client_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status)
  98053. {
  98054. if(!decoder->private_->is_seeking)
  98055. decoder->private_->error_callback(decoder, status, decoder->private_->client_data);
  98056. else if(status == FLAC__STREAM_DECODER_ERROR_STATUS_UNPARSEABLE_STREAM)
  98057. decoder->private_->unparseable_frame_count++;
  98058. }
  98059. FLAC__bool seek_to_absolute_sample_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  98060. {
  98061. FLAC__uint64 first_frame_offset = decoder->private_->first_frame_offset, lower_bound, upper_bound, lower_bound_sample, upper_bound_sample, this_frame_sample;
  98062. FLAC__int64 pos = -1;
  98063. int i;
  98064. unsigned approx_bytes_per_frame;
  98065. FLAC__bool first_seek = true;
  98066. const FLAC__uint64 total_samples = FLAC__stream_decoder_get_total_samples(decoder);
  98067. const unsigned min_blocksize = decoder->private_->stream_info.data.stream_info.min_blocksize;
  98068. const unsigned max_blocksize = decoder->private_->stream_info.data.stream_info.max_blocksize;
  98069. const unsigned max_framesize = decoder->private_->stream_info.data.stream_info.max_framesize;
  98070. const unsigned min_framesize = decoder->private_->stream_info.data.stream_info.min_framesize;
  98071. /* take these from the current frame in case they've changed mid-stream */
  98072. unsigned channels = FLAC__stream_decoder_get_channels(decoder);
  98073. unsigned bps = FLAC__stream_decoder_get_bits_per_sample(decoder);
  98074. const FLAC__StreamMetadata_SeekTable *seek_table = decoder->private_->has_seek_table? &decoder->private_->seek_table.data.seek_table : 0;
  98075. /* use values from stream info if we didn't decode a frame */
  98076. if(channels == 0)
  98077. channels = decoder->private_->stream_info.data.stream_info.channels;
  98078. if(bps == 0)
  98079. bps = decoder->private_->stream_info.data.stream_info.bits_per_sample;
  98080. /* we are just guessing here */
  98081. if(max_framesize > 0)
  98082. approx_bytes_per_frame = (max_framesize + min_framesize) / 2 + 1;
  98083. /*
  98084. * Check if it's a known fixed-blocksize stream. Note that though
  98085. * the spec doesn't allow zeroes in the STREAMINFO block, we may
  98086. * never get a STREAMINFO block when decoding so the value of
  98087. * min_blocksize might be zero.
  98088. */
  98089. else if(min_blocksize == max_blocksize && min_blocksize > 0) {
  98090. /* note there are no () around 'bps/8' to keep precision up since it's an integer calulation */
  98091. approx_bytes_per_frame = min_blocksize * channels * bps/8 + 64;
  98092. }
  98093. else
  98094. approx_bytes_per_frame = 4096 * channels * bps/8 + 64;
  98095. /*
  98096. * First, we set an upper and lower bound on where in the
  98097. * stream we will search. For now we assume the worst case
  98098. * scenario, which is our best guess at the beginning of
  98099. * the first frame and end of the stream.
  98100. */
  98101. lower_bound = first_frame_offset;
  98102. lower_bound_sample = 0;
  98103. upper_bound = stream_length;
  98104. upper_bound_sample = total_samples > 0 ? total_samples : target_sample /*estimate it*/;
  98105. /*
  98106. * Now we refine the bounds if we have a seektable with
  98107. * suitable points. Note that according to the spec they
  98108. * must be ordered by ascending sample number.
  98109. *
  98110. * Note: to protect against invalid seek tables we will ignore points
  98111. * that have frame_samples==0 or sample_number>=total_samples
  98112. */
  98113. if(seek_table) {
  98114. FLAC__uint64 new_lower_bound = lower_bound;
  98115. FLAC__uint64 new_upper_bound = upper_bound;
  98116. FLAC__uint64 new_lower_bound_sample = lower_bound_sample;
  98117. FLAC__uint64 new_upper_bound_sample = upper_bound_sample;
  98118. /* find the closest seek point <= target_sample, if it exists */
  98119. for(i = (int)seek_table->num_points - 1; i >= 0; i--) {
  98120. if(
  98121. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  98122. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  98123. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  98124. seek_table->points[i].sample_number <= target_sample
  98125. )
  98126. break;
  98127. }
  98128. if(i >= 0) { /* i.e. we found a suitable seek point... */
  98129. new_lower_bound = first_frame_offset + seek_table->points[i].stream_offset;
  98130. new_lower_bound_sample = seek_table->points[i].sample_number;
  98131. }
  98132. /* find the closest seek point > target_sample, if it exists */
  98133. for(i = 0; i < (int)seek_table->num_points; i++) {
  98134. if(
  98135. seek_table->points[i].sample_number != FLAC__STREAM_METADATA_SEEKPOINT_PLACEHOLDER &&
  98136. seek_table->points[i].frame_samples > 0 && /* defense against bad seekpoints */
  98137. (total_samples <= 0 || seek_table->points[i].sample_number < total_samples) && /* defense against bad seekpoints */
  98138. seek_table->points[i].sample_number > target_sample
  98139. )
  98140. break;
  98141. }
  98142. if(i < (int)seek_table->num_points) { /* i.e. we found a suitable seek point... */
  98143. new_upper_bound = first_frame_offset + seek_table->points[i].stream_offset;
  98144. new_upper_bound_sample = seek_table->points[i].sample_number;
  98145. }
  98146. /* final protection against unsorted seek tables; keep original values if bogus */
  98147. if(new_upper_bound >= new_lower_bound) {
  98148. lower_bound = new_lower_bound;
  98149. upper_bound = new_upper_bound;
  98150. lower_bound_sample = new_lower_bound_sample;
  98151. upper_bound_sample = new_upper_bound_sample;
  98152. }
  98153. }
  98154. FLAC__ASSERT(upper_bound_sample >= lower_bound_sample);
  98155. /* there are 2 insidious ways that the following equality occurs, which
  98156. * we need to fix:
  98157. * 1) total_samples is 0 (unknown) and target_sample is 0
  98158. * 2) total_samples is 0 (unknown) and target_sample happens to be
  98159. * exactly equal to the last seek point in the seek table; this
  98160. * means there is no seek point above it, and upper_bound_samples
  98161. * remains equal to the estimate (of target_samples) we made above
  98162. * in either case it does not hurt to move upper_bound_sample up by 1
  98163. */
  98164. if(upper_bound_sample == lower_bound_sample)
  98165. upper_bound_sample++;
  98166. decoder->private_->target_sample = target_sample;
  98167. while(1) {
  98168. /* check if the bounds are still ok */
  98169. if (lower_bound_sample >= upper_bound_sample || lower_bound > upper_bound) {
  98170. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98171. return false;
  98172. }
  98173. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98174. #if defined _MSC_VER || defined __MINGW32__
  98175. /* with VC++ you have to spoon feed it the casting */
  98176. 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;
  98177. #else
  98178. 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;
  98179. #endif
  98180. #else
  98181. /* a little less accurate: */
  98182. if(upper_bound - lower_bound < 0xffffffff)
  98183. 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;
  98184. else /* @@@ WATCHOUT, ~2TB limit */
  98185. 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;
  98186. #endif
  98187. if(pos >= (FLAC__int64)upper_bound)
  98188. pos = (FLAC__int64)upper_bound - 1;
  98189. if(pos < (FLAC__int64)lower_bound)
  98190. pos = (FLAC__int64)lower_bound;
  98191. if(decoder->private_->seek_callback(decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  98192. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98193. return false;
  98194. }
  98195. if(!FLAC__stream_decoder_flush(decoder)) {
  98196. /* above call sets the state for us */
  98197. return false;
  98198. }
  98199. /* Now we need to get a frame. First we need to reset our
  98200. * unparseable_frame_count; if we get too many unparseable
  98201. * frames in a row, the read callback will return
  98202. * FLAC__STREAM_DECODER_READ_STATUS_ABORT, causing
  98203. * FLAC__stream_decoder_process_single() to return false.
  98204. */
  98205. decoder->private_->unparseable_frame_count = 0;
  98206. if(!FLAC__stream_decoder_process_single(decoder)) {
  98207. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98208. return false;
  98209. }
  98210. /* our write callback will change the state when it gets to the target frame */
  98211. /* 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 */
  98212. #if 0
  98213. /*@@@@@@ used to be the following; not clear if the check for end of stream is needed anymore */
  98214. if(decoder->protected_->state != FLAC__SEEKABLE_STREAM_DECODER_SEEKING && decoder->protected_->state != FLAC__STREAM_DECODER_END_OF_STREAM)
  98215. break;
  98216. #endif
  98217. if(!decoder->private_->is_seeking)
  98218. break;
  98219. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98220. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  98221. if (0 == decoder->private_->samples_decoded || (this_frame_sample + decoder->private_->last_frame.header.blocksize >= upper_bound_sample && !first_seek)) {
  98222. if (pos == (FLAC__int64)lower_bound) {
  98223. /* can't move back any more than the first frame, something is fatally wrong */
  98224. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98225. return false;
  98226. }
  98227. /* our last move backwards wasn't big enough, try again */
  98228. approx_bytes_per_frame = approx_bytes_per_frame? approx_bytes_per_frame * 2 : 16;
  98229. continue;
  98230. }
  98231. /* allow one seek over upper bound, so we can get a correct upper_bound_sample for streams with unknown total_samples */
  98232. first_seek = false;
  98233. /* make sure we are not seeking in corrupted stream */
  98234. if (this_frame_sample < lower_bound_sample) {
  98235. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98236. return false;
  98237. }
  98238. /* we need to narrow the search */
  98239. if(target_sample < this_frame_sample) {
  98240. upper_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  98241. /*@@@@@@ what will decode position be if at end of stream? */
  98242. if(!FLAC__stream_decoder_get_decode_position(decoder, &upper_bound)) {
  98243. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98244. return false;
  98245. }
  98246. approx_bytes_per_frame = (unsigned)(2 * (upper_bound - pos) / 3 + 16);
  98247. }
  98248. else { /* target_sample >= this_frame_sample + this frame's blocksize */
  98249. lower_bound_sample = this_frame_sample + decoder->private_->last_frame.header.blocksize;
  98250. if(!FLAC__stream_decoder_get_decode_position(decoder, &lower_bound)) {
  98251. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98252. return false;
  98253. }
  98254. approx_bytes_per_frame = (unsigned)(2 * (lower_bound - pos) / 3 + 16);
  98255. }
  98256. }
  98257. return true;
  98258. }
  98259. #if FLAC__HAS_OGG
  98260. FLAC__bool seek_to_absolute_sample_ogg_(FLAC__StreamDecoder *decoder, FLAC__uint64 stream_length, FLAC__uint64 target_sample)
  98261. {
  98262. FLAC__uint64 left_pos = 0, right_pos = stream_length;
  98263. FLAC__uint64 left_sample = 0, right_sample = FLAC__stream_decoder_get_total_samples(decoder);
  98264. FLAC__uint64 this_frame_sample = (FLAC__uint64)0 - 1;
  98265. FLAC__uint64 pos = 0; /* only initialized to avoid compiler warning */
  98266. FLAC__bool did_a_seek;
  98267. unsigned iteration = 0;
  98268. /* In the first iterations, we will calculate the target byte position
  98269. * by the distance from the target sample to left_sample and
  98270. * right_sample (let's call it "proportional search"). After that, we
  98271. * will switch to binary search.
  98272. */
  98273. unsigned BINARY_SEARCH_AFTER_ITERATION = 2;
  98274. /* We will switch to a linear search once our current sample is less
  98275. * than this number of samples ahead of the target sample
  98276. */
  98277. static const FLAC__uint64 LINEAR_SEARCH_WITHIN_SAMPLES = FLAC__MAX_BLOCK_SIZE * 2;
  98278. /* If the total number of samples is unknown, use a large value, and
  98279. * force binary search immediately.
  98280. */
  98281. if(right_sample == 0) {
  98282. right_sample = (FLAC__uint64)(-1);
  98283. BINARY_SEARCH_AFTER_ITERATION = 0;
  98284. }
  98285. decoder->private_->target_sample = target_sample;
  98286. for( ; ; iteration++) {
  98287. if (iteration == 0 || this_frame_sample > target_sample || target_sample - this_frame_sample > LINEAR_SEARCH_WITHIN_SAMPLES) {
  98288. if (iteration >= BINARY_SEARCH_AFTER_ITERATION) {
  98289. pos = (right_pos + left_pos) / 2;
  98290. }
  98291. else {
  98292. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98293. #if defined _MSC_VER || defined __MINGW32__
  98294. /* with MSVC you have to spoon feed it the casting */
  98295. 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));
  98296. #else
  98297. pos = (FLAC__uint64)((FLAC__double)(target_sample - left_sample) / (FLAC__double)(right_sample - left_sample) * (FLAC__double)(right_pos - left_pos));
  98298. #endif
  98299. #else
  98300. /* a little less accurate: */
  98301. if ((target_sample-left_sample <= 0xffffffff) && (right_pos-left_pos <= 0xffffffff))
  98302. pos = (FLAC__int64)(((target_sample-left_sample) * (right_pos-left_pos)) / (right_sample-left_sample));
  98303. else /* @@@ WATCHOUT, ~2TB limit */
  98304. pos = (FLAC__int64)((((target_sample-left_sample)>>8) * ((right_pos-left_pos)>>8)) / ((right_sample-left_sample)>>16));
  98305. #endif
  98306. /* @@@ TODO: might want to limit pos to some distance
  98307. * before EOF, to make sure we land before the last frame,
  98308. * thereby getting a this_frame_sample and so having a better
  98309. * estimate.
  98310. */
  98311. }
  98312. /* physical seek */
  98313. if(decoder->private_->seek_callback((FLAC__StreamDecoder*)decoder, (FLAC__uint64)pos, decoder->private_->client_data) != FLAC__STREAM_DECODER_SEEK_STATUS_OK) {
  98314. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98315. return false;
  98316. }
  98317. if(!FLAC__stream_decoder_flush(decoder)) {
  98318. /* above call sets the state for us */
  98319. return false;
  98320. }
  98321. did_a_seek = true;
  98322. }
  98323. else
  98324. did_a_seek = false;
  98325. decoder->private_->got_a_frame = false;
  98326. if(!FLAC__stream_decoder_process_single(decoder)) {
  98327. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98328. return false;
  98329. }
  98330. if(!decoder->private_->got_a_frame) {
  98331. if(did_a_seek) {
  98332. /* this can happen if we seek to a point after the last frame; we drop
  98333. * to binary search right away in this case to avoid any wasted
  98334. * iterations of proportional search.
  98335. */
  98336. right_pos = pos;
  98337. BINARY_SEARCH_AFTER_ITERATION = 0;
  98338. }
  98339. else {
  98340. /* this can probably only happen if total_samples is unknown and the
  98341. * target_sample is past the end of the stream
  98342. */
  98343. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98344. return false;
  98345. }
  98346. }
  98347. /* our write callback will change the state when it gets to the target frame */
  98348. else if(!decoder->private_->is_seeking) {
  98349. break;
  98350. }
  98351. else {
  98352. this_frame_sample = decoder->private_->last_frame.header.number.sample_number;
  98353. FLAC__ASSERT(decoder->private_->last_frame.header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  98354. if (did_a_seek) {
  98355. if (this_frame_sample <= target_sample) {
  98356. /* The 'equal' case should not happen, since
  98357. * FLAC__stream_decoder_process_single()
  98358. * should recognize that it has hit the
  98359. * target sample and we would exit through
  98360. * the 'break' above.
  98361. */
  98362. FLAC__ASSERT(this_frame_sample != target_sample);
  98363. left_sample = this_frame_sample;
  98364. /* sanity check to avoid infinite loop */
  98365. if (left_pos == pos) {
  98366. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98367. return false;
  98368. }
  98369. left_pos = pos;
  98370. }
  98371. else if(this_frame_sample > target_sample) {
  98372. right_sample = this_frame_sample;
  98373. /* sanity check to avoid infinite loop */
  98374. if (right_pos == pos) {
  98375. decoder->protected_->state = FLAC__STREAM_DECODER_SEEK_ERROR;
  98376. return false;
  98377. }
  98378. right_pos = pos;
  98379. }
  98380. }
  98381. }
  98382. }
  98383. return true;
  98384. }
  98385. #endif
  98386. FLAC__StreamDecoderReadStatus file_read_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  98387. {
  98388. (void)client_data;
  98389. if(*bytes > 0) {
  98390. *bytes = fread(buffer, sizeof(FLAC__byte), *bytes, decoder->private_->file);
  98391. if(ferror(decoder->private_->file))
  98392. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  98393. else if(*bytes == 0)
  98394. return FLAC__STREAM_DECODER_READ_STATUS_END_OF_STREAM;
  98395. else
  98396. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  98397. }
  98398. else
  98399. return FLAC__STREAM_DECODER_READ_STATUS_ABORT; /* abort to avoid a deadlock */
  98400. }
  98401. FLAC__StreamDecoderSeekStatus file_seek_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  98402. {
  98403. (void)client_data;
  98404. if(decoder->private_->file == stdin)
  98405. return FLAC__STREAM_DECODER_SEEK_STATUS_UNSUPPORTED;
  98406. else if(fseeko(decoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  98407. return FLAC__STREAM_DECODER_SEEK_STATUS_ERROR;
  98408. else
  98409. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  98410. }
  98411. FLAC__StreamDecoderTellStatus file_tell_callback_dec(const FLAC__StreamDecoder *decoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  98412. {
  98413. off_t pos;
  98414. (void)client_data;
  98415. if(decoder->private_->file == stdin)
  98416. return FLAC__STREAM_DECODER_TELL_STATUS_UNSUPPORTED;
  98417. else if((pos = ftello(decoder->private_->file)) < 0)
  98418. return FLAC__STREAM_DECODER_TELL_STATUS_ERROR;
  98419. else {
  98420. *absolute_byte_offset = (FLAC__uint64)pos;
  98421. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  98422. }
  98423. }
  98424. FLAC__StreamDecoderLengthStatus file_length_callback_(const FLAC__StreamDecoder *decoder, FLAC__uint64 *stream_length, void *client_data)
  98425. {
  98426. struct stat filestats;
  98427. (void)client_data;
  98428. if(decoder->private_->file == stdin)
  98429. return FLAC__STREAM_DECODER_LENGTH_STATUS_UNSUPPORTED;
  98430. else if(fstat(fileno(decoder->private_->file), &filestats) != 0)
  98431. return FLAC__STREAM_DECODER_LENGTH_STATUS_ERROR;
  98432. else {
  98433. *stream_length = (FLAC__uint64)filestats.st_size;
  98434. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  98435. }
  98436. }
  98437. FLAC__bool file_eof_callback_(const FLAC__StreamDecoder *decoder, void *client_data)
  98438. {
  98439. (void)client_data;
  98440. return feof(decoder->private_->file)? true : false;
  98441. }
  98442. #endif
  98443. /********* End of inlined file: stream_decoder.c *********/
  98444. /********* Start of inlined file: stream_encoder.c *********/
  98445. /********* Start of inlined file: juce_FlacHeader.h *********/
  98446. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  98447. // tasks..
  98448. /********* Start of inlined file: juce_Config.h *********/
  98449. #ifndef __JUCE_CONFIG_JUCEHEADER__
  98450. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  98451. /*
  98452. This file contains macros that enable/disable various JUCE features.
  98453. */
  98454. /** The name of the namespace that all Juce classes and functions will be
  98455. put inside. If this is not defined, no namespace will be used.
  98456. */
  98457. #ifndef JUCE_NAMESPACE
  98458. #define JUCE_NAMESPACE juce
  98459. #endif
  98460. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  98461. but if you define this value, you can override this can force it to be true or
  98462. false.
  98463. */
  98464. #ifndef JUCE_FORCE_DEBUG
  98465. //#define JUCE_FORCE_DEBUG 1
  98466. #endif
  98467. /** If this flag is enabled, the the jassert and jassertfalse macros will
  98468. always use Logger::writeToLog() to write a message when an assertion happens.
  98469. Enabling it will also leave this turned on in release builds. When it's disabled,
  98470. however, the jassert and jassertfalse macros will not be compiled in a
  98471. release build.
  98472. @see jassert, jassertfalse, Logger
  98473. */
  98474. #ifndef JUCE_LOG_ASSERTIONS
  98475. // #define JUCE_LOG_ASSERTIONS 1
  98476. #endif
  98477. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  98478. which the ASIOAudioIODevice class can't be built. See the comments in the
  98479. ASIOAudioIODevice class's header file for more info about this.
  98480. (This only affects a Win32 build)
  98481. */
  98482. #ifndef JUCE_ASIO
  98483. #define JUCE_ASIO 1
  98484. #endif
  98485. /** Comment out this macro to disable building of ALSA device support on Linux.
  98486. */
  98487. #ifndef JUCE_ALSA
  98488. #define JUCE_ALSA 1
  98489. #endif
  98490. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  98491. have the SDK installed.
  98492. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  98493. classes will be unavailable.
  98494. On Windows, if you enable this, you'll need to have the QuickTime SDK
  98495. installed, and its header files will need to be on your include path.
  98496. */
  98497. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  98498. #define JUCE_QUICKTIME 1
  98499. #endif
  98500. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  98501. have the appropriate headers and libraries available. If it's not enabled, the
  98502. OpenGLComponent class will be unavailable.
  98503. */
  98504. #ifndef JUCE_OPENGL
  98505. #define JUCE_OPENGL 1
  98506. #endif
  98507. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  98508. If you're not going to need either of these formats, turn off the flags to
  98509. avoid bloating your codebase with them.
  98510. */
  98511. #ifndef JUCE_USE_FLAC
  98512. #define JUCE_USE_FLAC 1
  98513. #endif
  98514. #ifndef JUCE_USE_OGGVORBIS
  98515. #define JUCE_USE_OGGVORBIS 1
  98516. #endif
  98517. /** This flag lets you enable support for CD-burning. You might want to disable
  98518. it to build without the MS SDK under windows.
  98519. */
  98520. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  98521. #define JUCE_USE_CDBURNER 1
  98522. #endif
  98523. /** Enabling this macro means that all regions that get repainted will have a coloured
  98524. line drawn around them.
  98525. This is handy if you're trying to optimise drawing, because it lets you easily see
  98526. when anything is being repainted unnecessarily.
  98527. */
  98528. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  98529. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  98530. #endif
  98531. /** Enable this under Linux to use Xinerama for multi-monitor support.
  98532. */
  98533. #ifndef JUCE_USE_XINERAMA
  98534. #define JUCE_USE_XINERAMA 1
  98535. #endif
  98536. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  98537. */
  98538. #ifndef JUCE_USE_XSHM
  98539. #define JUCE_USE_XSHM 1
  98540. #endif
  98541. /** Enabling this builds support for VST audio plugins.
  98542. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  98543. */
  98544. #ifndef JUCE_PLUGINHOST_VST
  98545. // #define JUCE_PLUGINHOST_VST 1
  98546. #endif
  98547. /** Enabling this builds support for AudioUnit audio plugins.
  98548. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  98549. */
  98550. #ifndef JUCE_PLUGINHOST_AU
  98551. // #define JUCE_PLUGINHOST_AU 1
  98552. #endif
  98553. /** Disabling this will avoid linking to any UI code. This is handy for
  98554. writing command-line utilities, e.g. on linux boxes which don't have some
  98555. of the UI libraries installed.
  98556. (On mac and windows, this won't generally make much difference to the build).
  98557. */
  98558. #ifndef JUCE_BUILD_GUI_CLASSES
  98559. #define JUCE_BUILD_GUI_CLASSES 1
  98560. #endif
  98561. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  98562. */
  98563. #ifndef JUCE_WEB_BROWSER
  98564. #define JUCE_WEB_BROWSER 1
  98565. #endif
  98566. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  98567. codebase - you might need to use this if you're linking to some of these libraries
  98568. yourself.
  98569. */
  98570. #ifndef JUCE_INCLUDE_ZLIB_CODE
  98571. #define JUCE_INCLUDE_ZLIB_CODE 1
  98572. #endif
  98573. #ifndef JUCE_INCLUDE_FLAC_CODE
  98574. #define JUCE_INCLUDE_FLAC_CODE 1
  98575. #endif
  98576. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  98577. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  98578. #endif
  98579. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  98580. #define JUCE_INCLUDE_PNGLIB_CODE 1
  98581. #endif
  98582. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  98583. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  98584. #endif
  98585. /** Enable this to add extra memory-leak info to the new and delete operators.
  98586. (Currently, this only affects Windows builds in debug mode).
  98587. */
  98588. #ifndef JUCE_CHECK_MEMORY_LEAKS
  98589. #define JUCE_CHECK_MEMORY_LEAKS 1
  98590. #endif
  98591. /** Enable this to turn on juce's internal catching of exceptions.
  98592. Turning it off will avoid any exception catching. With it on, all exceptions
  98593. are passed to the JUCEApplication::unhandledException() callback for logging.
  98594. */
  98595. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  98596. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  98597. #endif
  98598. /** If this macro is set, the Juce String class will use unicode as its
  98599. internal representation. If it isn't set, it'll use ANSI.
  98600. */
  98601. #ifndef JUCE_STRINGS_ARE_UNICODE
  98602. #define JUCE_STRINGS_ARE_UNICODE 1
  98603. #endif
  98604. #endif
  98605. /********* End of inlined file: juce_Config.h *********/
  98606. #define VERSION "1.2.1"
  98607. #define FLAC__NO_DLL 1
  98608. #ifdef _MSC_VER
  98609. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  98610. #endif
  98611. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  98612. #define FLAC__SYS_DARWIN 1
  98613. #endif
  98614. /********* End of inlined file: juce_FlacHeader.h *********/
  98615. #if JUCE_USE_FLAC
  98616. #if HAVE_CONFIG_H
  98617. # include <config.h>
  98618. #endif
  98619. #if defined _MSC_VER || defined __MINGW32__
  98620. #include <io.h> /* for _setmode() */
  98621. #include <fcntl.h> /* for _O_BINARY */
  98622. #endif
  98623. #if defined __CYGWIN__ || defined __EMX__
  98624. #include <io.h> /* for setmode(), O_BINARY */
  98625. #include <fcntl.h> /* for _O_BINARY */
  98626. #endif
  98627. #include <limits.h>
  98628. #include <stdio.h>
  98629. #include <stdlib.h> /* for malloc() */
  98630. #include <string.h> /* for memcpy() */
  98631. #include <sys/types.h> /* for off_t */
  98632. #if defined _MSC_VER || defined __BORLANDC__ || defined __MINGW32__
  98633. #if _MSC_VER <= 1600 || defined __BORLANDC__ /* @@@ [2G limit] */
  98634. #define fseeko fseek
  98635. #define ftello ftell
  98636. #endif
  98637. #endif
  98638. /********* Start of inlined file: stream_encoder.h *********/
  98639. #ifndef FLAC__PROTECTED__STREAM_ENCODER_H
  98640. #define FLAC__PROTECTED__STREAM_ENCODER_H
  98641. #if FLAC__HAS_OGG
  98642. #include "private/ogg_encoder_aspect.h"
  98643. #endif
  98644. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98645. #define FLAC__MAX_APODIZATION_FUNCTIONS 32
  98646. typedef enum {
  98647. FLAC__APODIZATION_BARTLETT,
  98648. FLAC__APODIZATION_BARTLETT_HANN,
  98649. FLAC__APODIZATION_BLACKMAN,
  98650. FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE,
  98651. FLAC__APODIZATION_CONNES,
  98652. FLAC__APODIZATION_FLATTOP,
  98653. FLAC__APODIZATION_GAUSS,
  98654. FLAC__APODIZATION_HAMMING,
  98655. FLAC__APODIZATION_HANN,
  98656. FLAC__APODIZATION_KAISER_BESSEL,
  98657. FLAC__APODIZATION_NUTTALL,
  98658. FLAC__APODIZATION_RECTANGLE,
  98659. FLAC__APODIZATION_TRIANGLE,
  98660. FLAC__APODIZATION_TUKEY,
  98661. FLAC__APODIZATION_WELCH
  98662. } FLAC__ApodizationFunction;
  98663. typedef struct {
  98664. FLAC__ApodizationFunction type;
  98665. union {
  98666. struct {
  98667. FLAC__real stddev;
  98668. } gauss;
  98669. struct {
  98670. FLAC__real p;
  98671. } tukey;
  98672. } parameters;
  98673. } FLAC__ApodizationSpecification;
  98674. #endif // #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98675. typedef struct FLAC__StreamEncoderProtected {
  98676. FLAC__StreamEncoderState state;
  98677. FLAC__bool verify;
  98678. FLAC__bool streamable_subset;
  98679. FLAC__bool do_md5;
  98680. FLAC__bool do_mid_side_stereo;
  98681. FLAC__bool loose_mid_side_stereo;
  98682. unsigned channels;
  98683. unsigned bits_per_sample;
  98684. unsigned sample_rate;
  98685. unsigned blocksize;
  98686. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98687. unsigned num_apodizations;
  98688. FLAC__ApodizationSpecification apodizations[FLAC__MAX_APODIZATION_FUNCTIONS];
  98689. #endif
  98690. unsigned max_lpc_order;
  98691. unsigned qlp_coeff_precision;
  98692. FLAC__bool do_qlp_coeff_prec_search;
  98693. FLAC__bool do_exhaustive_model_search;
  98694. FLAC__bool do_escape_coding;
  98695. unsigned min_residual_partition_order;
  98696. unsigned max_residual_partition_order;
  98697. unsigned rice_parameter_search_dist;
  98698. FLAC__uint64 total_samples_estimate;
  98699. FLAC__StreamMetadata **metadata;
  98700. unsigned num_metadata_blocks;
  98701. FLAC__uint64 streaminfo_offset, seektable_offset, audio_offset;
  98702. #if FLAC__HAS_OGG
  98703. FLAC__OggEncoderAspect ogg_encoder_aspect;
  98704. #endif
  98705. } FLAC__StreamEncoderProtected;
  98706. #endif
  98707. /********* End of inlined file: stream_encoder.h *********/
  98708. #if FLAC__HAS_OGG
  98709. #include "include/private/ogg_helper.h"
  98710. #include "include/private/ogg_mapping.h"
  98711. #endif
  98712. /********* Start of inlined file: stream_encoder_framing.h *********/
  98713. #ifndef FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  98714. #define FLAC__PRIVATE__STREAM_ENCODER_FRAMING_H
  98715. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw);
  98716. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw);
  98717. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  98718. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  98719. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  98720. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw);
  98721. #endif
  98722. /********* End of inlined file: stream_encoder_framing.h *********/
  98723. /********* Start of inlined file: window.h *********/
  98724. #ifndef FLAC__PRIVATE__WINDOW_H
  98725. #define FLAC__PRIVATE__WINDOW_H
  98726. #ifdef HAVE_CONFIG_H
  98727. #include <config.h>
  98728. #endif
  98729. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98730. /*
  98731. * FLAC__window_*()
  98732. * --------------------------------------------------------------------
  98733. * Calculates window coefficients according to different apodization
  98734. * functions.
  98735. *
  98736. * OUT window[0,L-1]
  98737. * IN L (number of points in window)
  98738. */
  98739. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L);
  98740. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L);
  98741. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L);
  98742. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L);
  98743. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L);
  98744. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L);
  98745. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev); /* 0.0 < stddev <= 0.5 */
  98746. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L);
  98747. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L);
  98748. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L);
  98749. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L);
  98750. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L);
  98751. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L);
  98752. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p);
  98753. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L);
  98754. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  98755. #endif
  98756. /********* End of inlined file: window.h *********/
  98757. #ifndef FLaC__INLINE
  98758. #define FLaC__INLINE
  98759. #endif
  98760. #ifdef min
  98761. #undef min
  98762. #endif
  98763. #define min(x,y) ((x)<(y)?(x):(y))
  98764. #ifdef max
  98765. #undef max
  98766. #endif
  98767. #define max(x,y) ((x)>(y)?(x):(y))
  98768. /* Exact Rice codeword length calculation is off by default. The simple
  98769. * (and fast) estimation (of how many bits a residual value will be
  98770. * encoded with) in this encoder is very good, almost always yielding
  98771. * compression within 0.1% of exact calculation.
  98772. */
  98773. #undef EXACT_RICE_BITS_CALCULATION
  98774. /* Rice parameter searching is off by default. The simple (and fast)
  98775. * parameter estimation in this encoder is very good, almost always
  98776. * yielding compression within 0.1% of the optimal parameters.
  98777. */
  98778. #undef ENABLE_RICE_PARAMETER_SEARCH
  98779. typedef struct {
  98780. FLAC__int32 *data[FLAC__MAX_CHANNELS];
  98781. unsigned size; /* of each data[] in samples */
  98782. unsigned tail;
  98783. } verify_input_fifo;
  98784. typedef struct {
  98785. const FLAC__byte *data;
  98786. unsigned capacity;
  98787. unsigned bytes;
  98788. } verify_output;
  98789. typedef enum {
  98790. ENCODER_IN_MAGIC = 0,
  98791. ENCODER_IN_METADATA = 1,
  98792. ENCODER_IN_AUDIO = 2
  98793. } EncoderStateHint;
  98794. static struct CompressionLevels {
  98795. FLAC__bool do_mid_side_stereo;
  98796. FLAC__bool loose_mid_side_stereo;
  98797. unsigned max_lpc_order;
  98798. unsigned qlp_coeff_precision;
  98799. FLAC__bool do_qlp_coeff_prec_search;
  98800. FLAC__bool do_escape_coding;
  98801. FLAC__bool do_exhaustive_model_search;
  98802. unsigned min_residual_partition_order;
  98803. unsigned max_residual_partition_order;
  98804. unsigned rice_parameter_search_dist;
  98805. } compression_levels_[] = {
  98806. { false, false, 0, 0, false, false, false, 0, 3, 0 },
  98807. { true , true , 0, 0, false, false, false, 0, 3, 0 },
  98808. { true , false, 0, 0, false, false, false, 0, 3, 0 },
  98809. { false, false, 6, 0, false, false, false, 0, 4, 0 },
  98810. { true , true , 8, 0, false, false, false, 0, 4, 0 },
  98811. { true , false, 8, 0, false, false, false, 0, 5, 0 },
  98812. { true , false, 8, 0, false, false, false, 0, 6, 0 },
  98813. { true , false, 8, 0, false, false, true , 0, 6, 0 },
  98814. { true , false, 12, 0, false, false, true , 0, 6, 0 }
  98815. };
  98816. /***********************************************************************
  98817. *
  98818. * Private class method prototypes
  98819. *
  98820. ***********************************************************************/
  98821. static void set_defaults_enc(FLAC__StreamEncoder *encoder);
  98822. static void free_(FLAC__StreamEncoder *encoder);
  98823. static FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize);
  98824. static FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block);
  98825. static FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block);
  98826. static void update_metadata_(const FLAC__StreamEncoder *encoder);
  98827. #if FLAC__HAS_OGG
  98828. static void update_ogg_metadata_(FLAC__StreamEncoder *encoder);
  98829. #endif
  98830. static FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block);
  98831. static FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block);
  98832. static FLAC__bool process_subframe_(
  98833. FLAC__StreamEncoder *encoder,
  98834. unsigned min_partition_order,
  98835. unsigned max_partition_order,
  98836. const FLAC__FrameHeader *frame_header,
  98837. unsigned subframe_bps,
  98838. const FLAC__int32 integer_signal[],
  98839. FLAC__Subframe *subframe[2],
  98840. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  98841. FLAC__int32 *residual[2],
  98842. unsigned *best_subframe,
  98843. unsigned *best_bits
  98844. );
  98845. static FLAC__bool add_subframe_(
  98846. FLAC__StreamEncoder *encoder,
  98847. unsigned blocksize,
  98848. unsigned subframe_bps,
  98849. const FLAC__Subframe *subframe,
  98850. FLAC__BitWriter *frame
  98851. );
  98852. static unsigned evaluate_constant_subframe_(
  98853. FLAC__StreamEncoder *encoder,
  98854. const FLAC__int32 signal,
  98855. unsigned blocksize,
  98856. unsigned subframe_bps,
  98857. FLAC__Subframe *subframe
  98858. );
  98859. static unsigned evaluate_fixed_subframe_(
  98860. FLAC__StreamEncoder *encoder,
  98861. const FLAC__int32 signal[],
  98862. FLAC__int32 residual[],
  98863. FLAC__uint64 abs_residual_partition_sums[],
  98864. unsigned raw_bits_per_partition[],
  98865. unsigned blocksize,
  98866. unsigned subframe_bps,
  98867. unsigned order,
  98868. unsigned rice_parameter,
  98869. unsigned rice_parameter_limit,
  98870. unsigned min_partition_order,
  98871. unsigned max_partition_order,
  98872. FLAC__bool do_escape_coding,
  98873. unsigned rice_parameter_search_dist,
  98874. FLAC__Subframe *subframe,
  98875. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  98876. );
  98877. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98878. static unsigned evaluate_lpc_subframe_(
  98879. FLAC__StreamEncoder *encoder,
  98880. const FLAC__int32 signal[],
  98881. FLAC__int32 residual[],
  98882. FLAC__uint64 abs_residual_partition_sums[],
  98883. unsigned raw_bits_per_partition[],
  98884. const FLAC__real lp_coeff[],
  98885. unsigned blocksize,
  98886. unsigned subframe_bps,
  98887. unsigned order,
  98888. unsigned qlp_coeff_precision,
  98889. unsigned rice_parameter,
  98890. unsigned rice_parameter_limit,
  98891. unsigned min_partition_order,
  98892. unsigned max_partition_order,
  98893. FLAC__bool do_escape_coding,
  98894. unsigned rice_parameter_search_dist,
  98895. FLAC__Subframe *subframe,
  98896. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  98897. );
  98898. #endif
  98899. static unsigned evaluate_verbatim_subframe_(
  98900. FLAC__StreamEncoder *encoder,
  98901. const FLAC__int32 signal[],
  98902. unsigned blocksize,
  98903. unsigned subframe_bps,
  98904. FLAC__Subframe *subframe
  98905. );
  98906. static unsigned find_best_partition_order_(
  98907. struct FLAC__StreamEncoderPrivate *private_,
  98908. const FLAC__int32 residual[],
  98909. FLAC__uint64 abs_residual_partition_sums[],
  98910. unsigned raw_bits_per_partition[],
  98911. unsigned residual_samples,
  98912. unsigned predictor_order,
  98913. unsigned rice_parameter,
  98914. unsigned rice_parameter_limit,
  98915. unsigned min_partition_order,
  98916. unsigned max_partition_order,
  98917. unsigned bps,
  98918. FLAC__bool do_escape_coding,
  98919. unsigned rice_parameter_search_dist,
  98920. FLAC__EntropyCodingMethod *best_ecm
  98921. );
  98922. static void precompute_partition_info_sums_(
  98923. const FLAC__int32 residual[],
  98924. FLAC__uint64 abs_residual_partition_sums[],
  98925. unsigned residual_samples,
  98926. unsigned predictor_order,
  98927. unsigned min_partition_order,
  98928. unsigned max_partition_order,
  98929. unsigned bps
  98930. );
  98931. static void precompute_partition_info_escapes_(
  98932. const FLAC__int32 residual[],
  98933. unsigned raw_bits_per_partition[],
  98934. unsigned residual_samples,
  98935. unsigned predictor_order,
  98936. unsigned min_partition_order,
  98937. unsigned max_partition_order
  98938. );
  98939. static FLAC__bool set_partitioned_rice_(
  98940. #ifdef EXACT_RICE_BITS_CALCULATION
  98941. const FLAC__int32 residual[],
  98942. #endif
  98943. const FLAC__uint64 abs_residual_partition_sums[],
  98944. const unsigned raw_bits_per_partition[],
  98945. const unsigned residual_samples,
  98946. const unsigned predictor_order,
  98947. const unsigned suggested_rice_parameter,
  98948. const unsigned rice_parameter_limit,
  98949. const unsigned rice_parameter_search_dist,
  98950. const unsigned partition_order,
  98951. const FLAC__bool search_for_escapes,
  98952. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  98953. unsigned *bits
  98954. );
  98955. static unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples);
  98956. /* verify-related routines: */
  98957. static void append_to_verify_fifo_(
  98958. verify_input_fifo *fifo,
  98959. const FLAC__int32 * const input[],
  98960. unsigned input_offset,
  98961. unsigned channels,
  98962. unsigned wide_samples
  98963. );
  98964. static void append_to_verify_fifo_interleaved_(
  98965. verify_input_fifo *fifo,
  98966. const FLAC__int32 input[],
  98967. unsigned input_offset,
  98968. unsigned channels,
  98969. unsigned wide_samples
  98970. );
  98971. static FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98972. static FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data);
  98973. static void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data);
  98974. static void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data);
  98975. static FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data);
  98976. static FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data);
  98977. static FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data);
  98978. 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);
  98979. static FILE *get_binary_stdout_(void);
  98980. /***********************************************************************
  98981. *
  98982. * Private class data
  98983. *
  98984. ***********************************************************************/
  98985. typedef struct FLAC__StreamEncoderPrivate {
  98986. unsigned input_capacity; /* current size (in samples) of the signal and residual buffers */
  98987. FLAC__int32 *integer_signal[FLAC__MAX_CHANNELS]; /* the integer version of the input signal */
  98988. FLAC__int32 *integer_signal_mid_side[2]; /* the integer version of the mid-side input signal (stereo only) */
  98989. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  98990. FLAC__real *real_signal[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) the floating-point version of the input signal */
  98991. FLAC__real *real_signal_mid_side[2]; /* (@@@ currently unused) the floating-point version of the mid-side input signal (stereo only) */
  98992. FLAC__real *window[FLAC__MAX_APODIZATION_FUNCTIONS]; /* the pre-computed floating-point window for each apodization function */
  98993. FLAC__real *windowed_signal; /* the integer_signal[] * current window[] */
  98994. #endif
  98995. unsigned subframe_bps[FLAC__MAX_CHANNELS]; /* the effective bits per sample of the input signal (stream bps - wasted bits) */
  98996. unsigned subframe_bps_mid_side[2]; /* the effective bits per sample of the mid-side input signal (stream bps - wasted bits + 0/1) */
  98997. FLAC__int32 *residual_workspace[FLAC__MAX_CHANNELS][2]; /* each channel has a candidate and best workspace where the subframe residual signals will be stored */
  98998. FLAC__int32 *residual_workspace_mid_side[2][2];
  98999. FLAC__Subframe subframe_workspace[FLAC__MAX_CHANNELS][2];
  99000. FLAC__Subframe subframe_workspace_mid_side[2][2];
  99001. FLAC__Subframe *subframe_workspace_ptr[FLAC__MAX_CHANNELS][2];
  99002. FLAC__Subframe *subframe_workspace_ptr_mid_side[2][2];
  99003. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace[FLAC__MAX_CHANNELS][2];
  99004. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_workspace_mid_side[FLAC__MAX_CHANNELS][2];
  99005. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr[FLAC__MAX_CHANNELS][2];
  99006. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents_workspace_ptr_mid_side[FLAC__MAX_CHANNELS][2];
  99007. unsigned best_subframe[FLAC__MAX_CHANNELS]; /* index (0 or 1) into 2nd dimension of the above workspaces */
  99008. unsigned best_subframe_mid_side[2];
  99009. unsigned best_subframe_bits[FLAC__MAX_CHANNELS]; /* size in bits of the best subframe for each channel */
  99010. unsigned best_subframe_bits_mid_side[2];
  99011. FLAC__uint64 *abs_residual_partition_sums; /* workspace where the sum of abs(candidate residual) for each partition is stored */
  99012. unsigned *raw_bits_per_partition; /* workspace where the sum of silog2(candidate residual) for each partition is stored */
  99013. FLAC__BitWriter *frame; /* the current frame being worked on */
  99014. unsigned loose_mid_side_stereo_frames; /* rounded number of frames the encoder will use before trying both independent and mid/side frames again */
  99015. unsigned loose_mid_side_stereo_frame_count; /* number of frames using the current channel assignment */
  99016. FLAC__ChannelAssignment last_channel_assignment;
  99017. FLAC__StreamMetadata streaminfo; /* scratchpad for STREAMINFO as it is built */
  99018. FLAC__StreamMetadata_SeekTable *seek_table; /* pointer into encoder->protected_->metadata_ where the seek table is */
  99019. unsigned current_sample_number;
  99020. unsigned current_frame_number;
  99021. FLAC__MD5Context md5context;
  99022. FLAC__CPUInfo cpuinfo;
  99023. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99024. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__float residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  99025. #else
  99026. unsigned (*local_fixed_compute_best_predictor)(const FLAC__int32 data[], unsigned data_len, FLAC__fixedpoint residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1]);
  99027. #endif
  99028. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99029. void (*local_lpc_compute_autocorrelation)(const FLAC__real data[], unsigned data_len, unsigned lag, FLAC__real autoc[]);
  99030. 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[]);
  99031. 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[]);
  99032. 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[]);
  99033. #endif
  99034. FLAC__bool use_wide_by_block; /* use slow 64-bit versions of some functions because of the block size */
  99035. FLAC__bool use_wide_by_partition; /* use slow 64-bit versions of some functions because of the min partition order and blocksize */
  99036. FLAC__bool use_wide_by_order; /* use slow 64-bit versions of some functions because of the lpc order */
  99037. FLAC__bool disable_constant_subframes;
  99038. FLAC__bool disable_fixed_subframes;
  99039. FLAC__bool disable_verbatim_subframes;
  99040. #if FLAC__HAS_OGG
  99041. FLAC__bool is_ogg;
  99042. #endif
  99043. FLAC__StreamEncoderReadCallback read_callback; /* currently only needed for Ogg FLAC */
  99044. FLAC__StreamEncoderSeekCallback seek_callback;
  99045. FLAC__StreamEncoderTellCallback tell_callback;
  99046. FLAC__StreamEncoderWriteCallback write_callback;
  99047. FLAC__StreamEncoderMetadataCallback metadata_callback;
  99048. FLAC__StreamEncoderProgressCallback progress_callback;
  99049. void *client_data;
  99050. unsigned first_seekpoint_to_check;
  99051. FILE *file; /* only used when encoding to a file */
  99052. FLAC__uint64 bytes_written;
  99053. FLAC__uint64 samples_written;
  99054. unsigned frames_written;
  99055. unsigned total_frames_estimate;
  99056. /* unaligned (original) pointers to allocated data */
  99057. FLAC__int32 *integer_signal_unaligned[FLAC__MAX_CHANNELS];
  99058. FLAC__int32 *integer_signal_mid_side_unaligned[2];
  99059. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99060. FLAC__real *real_signal_unaligned[FLAC__MAX_CHANNELS]; /* (@@@ currently unused) */
  99061. FLAC__real *real_signal_mid_side_unaligned[2]; /* (@@@ currently unused) */
  99062. FLAC__real *window_unaligned[FLAC__MAX_APODIZATION_FUNCTIONS];
  99063. FLAC__real *windowed_signal_unaligned;
  99064. #endif
  99065. FLAC__int32 *residual_workspace_unaligned[FLAC__MAX_CHANNELS][2];
  99066. FLAC__int32 *residual_workspace_mid_side_unaligned[2][2];
  99067. FLAC__uint64 *abs_residual_partition_sums_unaligned;
  99068. unsigned *raw_bits_per_partition_unaligned;
  99069. /*
  99070. * These fields have been moved here from private function local
  99071. * declarations merely to save stack space during encoding.
  99072. */
  99073. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99074. FLAC__real lp_coeff[FLAC__MAX_LPC_ORDER][FLAC__MAX_LPC_ORDER]; /* from process_subframe_() */
  99075. #endif
  99076. FLAC__EntropyCodingMethod_PartitionedRiceContents partitioned_rice_contents_extra[2]; /* from find_best_partition_order_() */
  99077. /*
  99078. * The data for the verify section
  99079. */
  99080. struct {
  99081. FLAC__StreamDecoder *decoder;
  99082. EncoderStateHint state_hint;
  99083. FLAC__bool needs_magic_hack;
  99084. verify_input_fifo input_fifo;
  99085. verify_output output;
  99086. struct {
  99087. FLAC__uint64 absolute_sample;
  99088. unsigned frame_number;
  99089. unsigned channel;
  99090. unsigned sample;
  99091. FLAC__int32 expected;
  99092. FLAC__int32 got;
  99093. } error_stats;
  99094. } verify;
  99095. FLAC__bool is_being_deleted; /* if true, call to ..._finish() from ..._delete() will not call the callbacks */
  99096. } FLAC__StreamEncoderPrivate;
  99097. /***********************************************************************
  99098. *
  99099. * Public static class data
  99100. *
  99101. ***********************************************************************/
  99102. FLAC_API const char * const FLAC__StreamEncoderStateString[] = {
  99103. "FLAC__STREAM_ENCODER_OK",
  99104. "FLAC__STREAM_ENCODER_UNINITIALIZED",
  99105. "FLAC__STREAM_ENCODER_OGG_ERROR",
  99106. "FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR",
  99107. "FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA",
  99108. "FLAC__STREAM_ENCODER_CLIENT_ERROR",
  99109. "FLAC__STREAM_ENCODER_IO_ERROR",
  99110. "FLAC__STREAM_ENCODER_FRAMING_ERROR",
  99111. "FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR"
  99112. };
  99113. FLAC_API const char * const FLAC__StreamEncoderInitStatusString[] = {
  99114. "FLAC__STREAM_ENCODER_INIT_STATUS_OK",
  99115. "FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR",
  99116. "FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER",
  99117. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS",
  99118. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS",
  99119. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE",
  99120. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE",
  99121. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE",
  99122. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER",
  99123. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION",
  99124. "FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER",
  99125. "FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE",
  99126. "FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA",
  99127. "FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED"
  99128. };
  99129. FLAC_API const char * const FLAC__treamEncoderReadStatusString[] = {
  99130. "FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE",
  99131. "FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM",
  99132. "FLAC__STREAM_ENCODER_READ_STATUS_ABORT",
  99133. "FLAC__STREAM_ENCODER_READ_STATUS_UNSUPPORTED"
  99134. };
  99135. FLAC_API const char * const FLAC__StreamEncoderWriteStatusString[] = {
  99136. "FLAC__STREAM_ENCODER_WRITE_STATUS_OK",
  99137. "FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR"
  99138. };
  99139. FLAC_API const char * const FLAC__StreamEncoderSeekStatusString[] = {
  99140. "FLAC__STREAM_ENCODER_SEEK_STATUS_OK",
  99141. "FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR",
  99142. "FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED"
  99143. };
  99144. FLAC_API const char * const FLAC__StreamEncoderTellStatusString[] = {
  99145. "FLAC__STREAM_ENCODER_TELL_STATUS_OK",
  99146. "FLAC__STREAM_ENCODER_TELL_STATUS_ERROR",
  99147. "FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED"
  99148. };
  99149. /* Number of samples that will be overread to watch for end of stream. By
  99150. * 'overread', we mean that the FLAC__stream_encoder_process*() calls will
  99151. * always try to read blocksize+1 samples before encoding a block, so that
  99152. * even if the stream has a total sample count that is an integral multiple
  99153. * of the blocksize, we will still notice when we are encoding the last
  99154. * block. This is needed, for example, to correctly set the end-of-stream
  99155. * marker in Ogg FLAC.
  99156. *
  99157. * WATCHOUT: some parts of the code assert that OVERREAD_ == 1 and there's
  99158. * not really any reason to change it.
  99159. */
  99160. static const unsigned OVERREAD_ = 1;
  99161. /***********************************************************************
  99162. *
  99163. * Class constructor/destructor
  99164. *
  99165. */
  99166. FLAC_API FLAC__StreamEncoder *FLAC__stream_encoder_new(void)
  99167. {
  99168. FLAC__StreamEncoder *encoder;
  99169. unsigned i;
  99170. FLAC__ASSERT(sizeof(int) >= 4); /* we want to die right away if this is not true */
  99171. encoder = (FLAC__StreamEncoder*)calloc(1, sizeof(FLAC__StreamEncoder));
  99172. if(encoder == 0) {
  99173. return 0;
  99174. }
  99175. encoder->protected_ = (FLAC__StreamEncoderProtected*)calloc(1, sizeof(FLAC__StreamEncoderProtected));
  99176. if(encoder->protected_ == 0) {
  99177. free(encoder);
  99178. return 0;
  99179. }
  99180. encoder->private_ = (FLAC__StreamEncoderPrivate*)calloc(1, sizeof(FLAC__StreamEncoderPrivate));
  99181. if(encoder->private_ == 0) {
  99182. free(encoder->protected_);
  99183. free(encoder);
  99184. return 0;
  99185. }
  99186. encoder->private_->frame = FLAC__bitwriter_new();
  99187. if(encoder->private_->frame == 0) {
  99188. free(encoder->private_);
  99189. free(encoder->protected_);
  99190. free(encoder);
  99191. return 0;
  99192. }
  99193. encoder->private_->file = 0;
  99194. set_defaults_enc(encoder);
  99195. encoder->private_->is_being_deleted = false;
  99196. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99197. encoder->private_->subframe_workspace_ptr[i][0] = &encoder->private_->subframe_workspace[i][0];
  99198. encoder->private_->subframe_workspace_ptr[i][1] = &encoder->private_->subframe_workspace[i][1];
  99199. }
  99200. for(i = 0; i < 2; i++) {
  99201. encoder->private_->subframe_workspace_ptr_mid_side[i][0] = &encoder->private_->subframe_workspace_mid_side[i][0];
  99202. encoder->private_->subframe_workspace_ptr_mid_side[i][1] = &encoder->private_->subframe_workspace_mid_side[i][1];
  99203. }
  99204. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99205. encoder->private_->partitioned_rice_contents_workspace_ptr[i][0] = &encoder->private_->partitioned_rice_contents_workspace[i][0];
  99206. encoder->private_->partitioned_rice_contents_workspace_ptr[i][1] = &encoder->private_->partitioned_rice_contents_workspace[i][1];
  99207. }
  99208. for(i = 0; i < 2; i++) {
  99209. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][0] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0];
  99210. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[i][1] = &encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1];
  99211. }
  99212. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99213. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  99214. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  99215. }
  99216. for(i = 0; i < 2; i++) {
  99217. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  99218. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  99219. }
  99220. for(i = 0; i < 2; i++)
  99221. FLAC__format_entropy_coding_method_partitioned_rice_contents_init(&encoder->private_->partitioned_rice_contents_extra[i]);
  99222. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  99223. return encoder;
  99224. }
  99225. FLAC_API void FLAC__stream_encoder_delete(FLAC__StreamEncoder *encoder)
  99226. {
  99227. unsigned i;
  99228. FLAC__ASSERT(0 != encoder);
  99229. FLAC__ASSERT(0 != encoder->protected_);
  99230. FLAC__ASSERT(0 != encoder->private_);
  99231. FLAC__ASSERT(0 != encoder->private_->frame);
  99232. encoder->private_->is_being_deleted = true;
  99233. (void)FLAC__stream_encoder_finish(encoder);
  99234. if(0 != encoder->private_->verify.decoder)
  99235. FLAC__stream_decoder_delete(encoder->private_->verify.decoder);
  99236. for(i = 0; i < FLAC__MAX_CHANNELS; i++) {
  99237. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][0]);
  99238. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace[i][1]);
  99239. }
  99240. for(i = 0; i < 2; i++) {
  99241. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][0]);
  99242. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_workspace_mid_side[i][1]);
  99243. }
  99244. for(i = 0; i < 2; i++)
  99245. FLAC__format_entropy_coding_method_partitioned_rice_contents_clear(&encoder->private_->partitioned_rice_contents_extra[i]);
  99246. FLAC__bitwriter_delete(encoder->private_->frame);
  99247. free(encoder->private_);
  99248. free(encoder->protected_);
  99249. free(encoder);
  99250. }
  99251. /***********************************************************************
  99252. *
  99253. * Public class methods
  99254. *
  99255. ***********************************************************************/
  99256. static FLAC__StreamEncoderInitStatus init_stream_internal_enc(
  99257. FLAC__StreamEncoder *encoder,
  99258. FLAC__StreamEncoderReadCallback read_callback,
  99259. FLAC__StreamEncoderWriteCallback write_callback,
  99260. FLAC__StreamEncoderSeekCallback seek_callback,
  99261. FLAC__StreamEncoderTellCallback tell_callback,
  99262. FLAC__StreamEncoderMetadataCallback metadata_callback,
  99263. void *client_data,
  99264. FLAC__bool is_ogg
  99265. )
  99266. {
  99267. unsigned i;
  99268. FLAC__bool metadata_has_seektable, metadata_has_vorbis_comment, metadata_picture_has_type1, metadata_picture_has_type2;
  99269. FLAC__ASSERT(0 != encoder);
  99270. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99271. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  99272. #if !FLAC__HAS_OGG
  99273. if(is_ogg)
  99274. return FLAC__STREAM_ENCODER_INIT_STATUS_UNSUPPORTED_CONTAINER;
  99275. #endif
  99276. if(0 == write_callback || (seek_callback && 0 == tell_callback))
  99277. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_CALLBACKS;
  99278. if(encoder->protected_->channels == 0 || encoder->protected_->channels > FLAC__MAX_CHANNELS)
  99279. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_NUMBER_OF_CHANNELS;
  99280. if(encoder->protected_->channels != 2) {
  99281. encoder->protected_->do_mid_side_stereo = false;
  99282. encoder->protected_->loose_mid_side_stereo = false;
  99283. }
  99284. else if(!encoder->protected_->do_mid_side_stereo)
  99285. encoder->protected_->loose_mid_side_stereo = false;
  99286. if(encoder->protected_->bits_per_sample >= 32)
  99287. encoder->protected_->do_mid_side_stereo = false; /* since we currenty do 32-bit math, the side channel would have 33 bps and overflow */
  99288. if(encoder->protected_->bits_per_sample < FLAC__MIN_BITS_PER_SAMPLE || encoder->protected_->bits_per_sample > FLAC__REFERENCE_CODEC_MAX_BITS_PER_SAMPLE)
  99289. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BITS_PER_SAMPLE;
  99290. if(!FLAC__format_sample_rate_is_valid(encoder->protected_->sample_rate))
  99291. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_SAMPLE_RATE;
  99292. if(encoder->protected_->blocksize == 0) {
  99293. if(encoder->protected_->max_lpc_order == 0)
  99294. encoder->protected_->blocksize = 1152;
  99295. else
  99296. encoder->protected_->blocksize = 4096;
  99297. }
  99298. if(encoder->protected_->blocksize < FLAC__MIN_BLOCK_SIZE || encoder->protected_->blocksize > FLAC__MAX_BLOCK_SIZE)
  99299. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_BLOCK_SIZE;
  99300. if(encoder->protected_->max_lpc_order > FLAC__MAX_LPC_ORDER)
  99301. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_MAX_LPC_ORDER;
  99302. if(encoder->protected_->blocksize < encoder->protected_->max_lpc_order)
  99303. return FLAC__STREAM_ENCODER_INIT_STATUS_BLOCK_SIZE_TOO_SMALL_FOR_LPC_ORDER;
  99304. if(encoder->protected_->qlp_coeff_precision == 0) {
  99305. if(encoder->protected_->bits_per_sample < 16) {
  99306. /* @@@ need some data about how to set this here w.r.t. blocksize and sample rate */
  99307. /* @@@ until then we'll make a guess */
  99308. encoder->protected_->qlp_coeff_precision = max(FLAC__MIN_QLP_COEFF_PRECISION, 2 + encoder->protected_->bits_per_sample / 2);
  99309. }
  99310. else if(encoder->protected_->bits_per_sample == 16) {
  99311. if(encoder->protected_->blocksize <= 192)
  99312. encoder->protected_->qlp_coeff_precision = 7;
  99313. else if(encoder->protected_->blocksize <= 384)
  99314. encoder->protected_->qlp_coeff_precision = 8;
  99315. else if(encoder->protected_->blocksize <= 576)
  99316. encoder->protected_->qlp_coeff_precision = 9;
  99317. else if(encoder->protected_->blocksize <= 1152)
  99318. encoder->protected_->qlp_coeff_precision = 10;
  99319. else if(encoder->protected_->blocksize <= 2304)
  99320. encoder->protected_->qlp_coeff_precision = 11;
  99321. else if(encoder->protected_->blocksize <= 4608)
  99322. encoder->protected_->qlp_coeff_precision = 12;
  99323. else
  99324. encoder->protected_->qlp_coeff_precision = 13;
  99325. }
  99326. else {
  99327. if(encoder->protected_->blocksize <= 384)
  99328. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-2;
  99329. else if(encoder->protected_->blocksize <= 1152)
  99330. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION-1;
  99331. else
  99332. encoder->protected_->qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  99333. }
  99334. FLAC__ASSERT(encoder->protected_->qlp_coeff_precision <= FLAC__MAX_QLP_COEFF_PRECISION);
  99335. }
  99336. else if(encoder->protected_->qlp_coeff_precision < FLAC__MIN_QLP_COEFF_PRECISION || encoder->protected_->qlp_coeff_precision > FLAC__MAX_QLP_COEFF_PRECISION)
  99337. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_QLP_COEFF_PRECISION;
  99338. if(encoder->protected_->streamable_subset) {
  99339. if(
  99340. encoder->protected_->blocksize != 192 &&
  99341. encoder->protected_->blocksize != 576 &&
  99342. encoder->protected_->blocksize != 1152 &&
  99343. encoder->protected_->blocksize != 2304 &&
  99344. encoder->protected_->blocksize != 4608 &&
  99345. encoder->protected_->blocksize != 256 &&
  99346. encoder->protected_->blocksize != 512 &&
  99347. encoder->protected_->blocksize != 1024 &&
  99348. encoder->protected_->blocksize != 2048 &&
  99349. encoder->protected_->blocksize != 4096 &&
  99350. encoder->protected_->blocksize != 8192 &&
  99351. encoder->protected_->blocksize != 16384
  99352. )
  99353. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99354. if(!FLAC__format_sample_rate_is_subset(encoder->protected_->sample_rate))
  99355. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99356. if(
  99357. encoder->protected_->bits_per_sample != 8 &&
  99358. encoder->protected_->bits_per_sample != 12 &&
  99359. encoder->protected_->bits_per_sample != 16 &&
  99360. encoder->protected_->bits_per_sample != 20 &&
  99361. encoder->protected_->bits_per_sample != 24
  99362. )
  99363. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99364. if(encoder->protected_->max_residual_partition_order > FLAC__SUBSET_MAX_RICE_PARTITION_ORDER)
  99365. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99366. if(
  99367. encoder->protected_->sample_rate <= 48000 &&
  99368. (
  99369. encoder->protected_->blocksize > FLAC__SUBSET_MAX_BLOCK_SIZE_48000HZ ||
  99370. encoder->protected_->max_lpc_order > FLAC__SUBSET_MAX_LPC_ORDER_48000HZ
  99371. )
  99372. ) {
  99373. return FLAC__STREAM_ENCODER_INIT_STATUS_NOT_STREAMABLE;
  99374. }
  99375. }
  99376. if(encoder->protected_->max_residual_partition_order >= (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  99377. encoder->protected_->max_residual_partition_order = (1u << FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN) - 1;
  99378. if(encoder->protected_->min_residual_partition_order >= encoder->protected_->max_residual_partition_order)
  99379. encoder->protected_->min_residual_partition_order = encoder->protected_->max_residual_partition_order;
  99380. #if FLAC__HAS_OGG
  99381. /* reorder metadata if necessary to ensure that any VORBIS_COMMENT is the first, according to the mapping spec */
  99382. if(is_ogg && 0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 1) {
  99383. unsigned i;
  99384. for(i = 1; i < encoder->protected_->num_metadata_blocks; i++) {
  99385. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  99386. FLAC__StreamMetadata *vc = encoder->protected_->metadata[i];
  99387. for( ; i > 0; i--)
  99388. encoder->protected_->metadata[i] = encoder->protected_->metadata[i-1];
  99389. encoder->protected_->metadata[0] = vc;
  99390. break;
  99391. }
  99392. }
  99393. }
  99394. #endif
  99395. /* keep track of any SEEKTABLE block */
  99396. if(0 != encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0) {
  99397. unsigned i;
  99398. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  99399. if(0 != encoder->protected_->metadata[i] && encoder->protected_->metadata[i]->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99400. encoder->private_->seek_table = &encoder->protected_->metadata[i]->data.seek_table;
  99401. break; /* take only the first one */
  99402. }
  99403. }
  99404. }
  99405. /* validate metadata */
  99406. if(0 == encoder->protected_->metadata && encoder->protected_->num_metadata_blocks > 0)
  99407. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99408. metadata_has_seektable = false;
  99409. metadata_has_vorbis_comment = false;
  99410. metadata_picture_has_type1 = false;
  99411. metadata_picture_has_type2 = false;
  99412. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  99413. const FLAC__StreamMetadata *m = encoder->protected_->metadata[i];
  99414. if(m->type == FLAC__METADATA_TYPE_STREAMINFO)
  99415. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99416. else if(m->type == FLAC__METADATA_TYPE_SEEKTABLE) {
  99417. if(metadata_has_seektable) /* only one is allowed */
  99418. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99419. metadata_has_seektable = true;
  99420. if(!FLAC__format_seektable_is_legal(&m->data.seek_table))
  99421. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99422. }
  99423. else if(m->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  99424. if(metadata_has_vorbis_comment) /* only one is allowed */
  99425. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99426. metadata_has_vorbis_comment = true;
  99427. }
  99428. else if(m->type == FLAC__METADATA_TYPE_CUESHEET) {
  99429. if(!FLAC__format_cuesheet_is_legal(&m->data.cue_sheet, m->data.cue_sheet.is_cd, /*violation=*/0))
  99430. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99431. }
  99432. else if(m->type == FLAC__METADATA_TYPE_PICTURE) {
  99433. if(!FLAC__format_picture_is_legal(&m->data.picture, /*violation=*/0))
  99434. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99435. if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD) {
  99436. if(metadata_picture_has_type1) /* there should only be 1 per stream */
  99437. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99438. metadata_picture_has_type1 = true;
  99439. /* standard icon must be 32x32 pixel PNG */
  99440. if(
  99441. m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON_STANDARD &&
  99442. (
  99443. (strcmp(m->data.picture.mime_type, "image/png") && strcmp(m->data.picture.mime_type, "-->")) ||
  99444. m->data.picture.width != 32 ||
  99445. m->data.picture.height != 32
  99446. )
  99447. )
  99448. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99449. }
  99450. else if(m->data.picture.type == FLAC__STREAM_METADATA_PICTURE_TYPE_FILE_ICON) {
  99451. if(metadata_picture_has_type2) /* there should only be 1 per stream */
  99452. return FLAC__STREAM_ENCODER_INIT_STATUS_INVALID_METADATA;
  99453. metadata_picture_has_type2 = true;
  99454. }
  99455. }
  99456. }
  99457. encoder->private_->input_capacity = 0;
  99458. for(i = 0; i < encoder->protected_->channels; i++) {
  99459. encoder->private_->integer_signal_unaligned[i] = encoder->private_->integer_signal[i] = 0;
  99460. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99461. encoder->private_->real_signal_unaligned[i] = encoder->private_->real_signal[i] = 0;
  99462. #endif
  99463. }
  99464. for(i = 0; i < 2; i++) {
  99465. encoder->private_->integer_signal_mid_side_unaligned[i] = encoder->private_->integer_signal_mid_side[i] = 0;
  99466. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99467. encoder->private_->real_signal_mid_side_unaligned[i] = encoder->private_->real_signal_mid_side[i] = 0;
  99468. #endif
  99469. }
  99470. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99471. for(i = 0; i < encoder->protected_->num_apodizations; i++)
  99472. encoder->private_->window_unaligned[i] = encoder->private_->window[i] = 0;
  99473. encoder->private_->windowed_signal_unaligned = encoder->private_->windowed_signal = 0;
  99474. #endif
  99475. for(i = 0; i < encoder->protected_->channels; i++) {
  99476. encoder->private_->residual_workspace_unaligned[i][0] = encoder->private_->residual_workspace[i][0] = 0;
  99477. encoder->private_->residual_workspace_unaligned[i][1] = encoder->private_->residual_workspace[i][1] = 0;
  99478. encoder->private_->best_subframe[i] = 0;
  99479. }
  99480. for(i = 0; i < 2; i++) {
  99481. encoder->private_->residual_workspace_mid_side_unaligned[i][0] = encoder->private_->residual_workspace_mid_side[i][0] = 0;
  99482. encoder->private_->residual_workspace_mid_side_unaligned[i][1] = encoder->private_->residual_workspace_mid_side[i][1] = 0;
  99483. encoder->private_->best_subframe_mid_side[i] = 0;
  99484. }
  99485. encoder->private_->abs_residual_partition_sums_unaligned = encoder->private_->abs_residual_partition_sums = 0;
  99486. encoder->private_->raw_bits_per_partition_unaligned = encoder->private_->raw_bits_per_partition = 0;
  99487. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99488. encoder->private_->loose_mid_side_stereo_frames = (unsigned)((FLAC__double)encoder->protected_->sample_rate * 0.4 / (FLAC__double)encoder->protected_->blocksize + 0.5);
  99489. #else
  99490. /* 26214 is the approximate fixed-point equivalent to 0.4 (0.4 * 2^16) */
  99491. /* sample rate can be up to 655350 Hz, and thus use 20 bits, so we do the multiply&divide by hand */
  99492. FLAC__ASSERT(FLAC__MAX_SAMPLE_RATE <= 655350);
  99493. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535);
  99494. FLAC__ASSERT(encoder->protected_->sample_rate <= 655350);
  99495. FLAC__ASSERT(encoder->protected_->blocksize <= 65535);
  99496. 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);
  99497. #endif
  99498. if(encoder->private_->loose_mid_side_stereo_frames == 0)
  99499. encoder->private_->loose_mid_side_stereo_frames = 1;
  99500. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  99501. encoder->private_->current_sample_number = 0;
  99502. encoder->private_->current_frame_number = 0;
  99503. encoder->private_->use_wide_by_block = (encoder->protected_->bits_per_sample + FLAC__bitmath_ilog2(encoder->protected_->blocksize)+1 > 30);
  99504. 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? */
  99505. encoder->private_->use_wide_by_partition = (false); /*@@@ need to set this */
  99506. /*
  99507. * get the CPU info and set the function pointers
  99508. */
  99509. FLAC__cpu_info(&encoder->private_->cpuinfo);
  99510. /* first default to the non-asm routines */
  99511. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99512. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation;
  99513. #endif
  99514. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor;
  99515. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99516. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients;
  99517. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit = FLAC__lpc_compute_residual_from_qlp_coefficients_wide;
  99518. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients;
  99519. #endif
  99520. /* now override with asm where appropriate */
  99521. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  99522. # ifndef FLAC__NO_ASM
  99523. if(encoder->private_->cpuinfo.use_asm) {
  99524. # ifdef FLAC__CPU_IA32
  99525. FLAC__ASSERT(encoder->private_->cpuinfo.type == FLAC__CPUINFO_TYPE_IA32);
  99526. # ifdef FLAC__HAS_NASM
  99527. if(encoder->private_->cpuinfo.data.ia32.sse) {
  99528. if(encoder->protected_->max_lpc_order < 4)
  99529. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_4;
  99530. else if(encoder->protected_->max_lpc_order < 8)
  99531. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_8;
  99532. else if(encoder->protected_->max_lpc_order < 12)
  99533. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_sse_lag_12;
  99534. else
  99535. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  99536. }
  99537. else if(encoder->private_->cpuinfo.data.ia32._3dnow)
  99538. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32_3dnow;
  99539. else
  99540. encoder->private_->local_lpc_compute_autocorrelation = FLAC__lpc_compute_autocorrelation_asm_ia32;
  99541. if(encoder->private_->cpuinfo.data.ia32.mmx) {
  99542. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  99543. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx;
  99544. }
  99545. else {
  99546. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  99547. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit = FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32;
  99548. }
  99549. if(encoder->private_->cpuinfo.data.ia32.mmx && encoder->private_->cpuinfo.data.ia32.cmov)
  99550. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_asm_ia32_mmx_cmov;
  99551. # endif /* FLAC__HAS_NASM */
  99552. # endif /* FLAC__CPU_IA32 */
  99553. }
  99554. # endif /* !FLAC__NO_ASM */
  99555. #endif /* !FLAC__INTEGER_ONLY_LIBRARY */
  99556. /* finally override based on wide-ness if necessary */
  99557. if(encoder->private_->use_wide_by_block) {
  99558. encoder->private_->local_fixed_compute_best_predictor = FLAC__fixed_compute_best_predictor_wide;
  99559. }
  99560. /* set state to OK; from here on, errors are fatal and we'll override the state then */
  99561. encoder->protected_->state = FLAC__STREAM_ENCODER_OK;
  99562. #if FLAC__HAS_OGG
  99563. encoder->private_->is_ogg = is_ogg;
  99564. if(is_ogg && !FLAC__ogg_encoder_aspect_init(&encoder->protected_->ogg_encoder_aspect)) {
  99565. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  99566. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99567. }
  99568. #endif
  99569. encoder->private_->read_callback = read_callback;
  99570. encoder->private_->write_callback = write_callback;
  99571. encoder->private_->seek_callback = seek_callback;
  99572. encoder->private_->tell_callback = tell_callback;
  99573. encoder->private_->metadata_callback = metadata_callback;
  99574. encoder->private_->client_data = client_data;
  99575. if(!resize_buffers_(encoder, encoder->protected_->blocksize)) {
  99576. /* the above function sets the state for us in case of an error */
  99577. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99578. }
  99579. if(!FLAC__bitwriter_init(encoder->private_->frame)) {
  99580. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99581. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99582. }
  99583. /*
  99584. * Set up the verify stuff if necessary
  99585. */
  99586. if(encoder->protected_->verify) {
  99587. /*
  99588. * First, set up the fifo which will hold the
  99589. * original signal to compare against
  99590. */
  99591. encoder->private_->verify.input_fifo.size = encoder->protected_->blocksize+OVERREAD_;
  99592. for(i = 0; i < encoder->protected_->channels; i++) {
  99593. 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))) {
  99594. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  99595. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99596. }
  99597. }
  99598. encoder->private_->verify.input_fifo.tail = 0;
  99599. /*
  99600. * Now set up a stream decoder for verification
  99601. */
  99602. encoder->private_->verify.decoder = FLAC__stream_decoder_new();
  99603. if(0 == encoder->private_->verify.decoder) {
  99604. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  99605. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99606. }
  99607. 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) {
  99608. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  99609. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99610. }
  99611. }
  99612. encoder->private_->verify.error_stats.absolute_sample = 0;
  99613. encoder->private_->verify.error_stats.frame_number = 0;
  99614. encoder->private_->verify.error_stats.channel = 0;
  99615. encoder->private_->verify.error_stats.sample = 0;
  99616. encoder->private_->verify.error_stats.expected = 0;
  99617. encoder->private_->verify.error_stats.got = 0;
  99618. /*
  99619. * These must be done before we write any metadata, because that
  99620. * calls the write_callback, which uses these values.
  99621. */
  99622. encoder->private_->first_seekpoint_to_check = 0;
  99623. encoder->private_->samples_written = 0;
  99624. encoder->protected_->streaminfo_offset = 0;
  99625. encoder->protected_->seektable_offset = 0;
  99626. encoder->protected_->audio_offset = 0;
  99627. /*
  99628. * write the stream header
  99629. */
  99630. if(encoder->protected_->verify)
  99631. encoder->private_->verify.state_hint = ENCODER_IN_MAGIC;
  99632. if(!FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, FLAC__STREAM_SYNC, FLAC__STREAM_SYNC_LEN)) {
  99633. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99634. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99635. }
  99636. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  99637. /* the above function sets the state for us in case of an error */
  99638. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99639. }
  99640. /*
  99641. * write the STREAMINFO metadata block
  99642. */
  99643. if(encoder->protected_->verify)
  99644. encoder->private_->verify.state_hint = ENCODER_IN_METADATA;
  99645. encoder->private_->streaminfo.type = FLAC__METADATA_TYPE_STREAMINFO;
  99646. encoder->private_->streaminfo.is_last = false; /* we will have at a minimum a VORBIS_COMMENT afterwards */
  99647. encoder->private_->streaminfo.length = FLAC__STREAM_METADATA_STREAMINFO_LENGTH;
  99648. encoder->private_->streaminfo.data.stream_info.min_blocksize = encoder->protected_->blocksize; /* this encoder uses the same blocksize for the whole stream */
  99649. encoder->private_->streaminfo.data.stream_info.max_blocksize = encoder->protected_->blocksize;
  99650. encoder->private_->streaminfo.data.stream_info.min_framesize = 0; /* we don't know this yet; have to fill it in later */
  99651. encoder->private_->streaminfo.data.stream_info.max_framesize = 0; /* we don't know this yet; have to fill it in later */
  99652. encoder->private_->streaminfo.data.stream_info.sample_rate = encoder->protected_->sample_rate;
  99653. encoder->private_->streaminfo.data.stream_info.channels = encoder->protected_->channels;
  99654. encoder->private_->streaminfo.data.stream_info.bits_per_sample = encoder->protected_->bits_per_sample;
  99655. encoder->private_->streaminfo.data.stream_info.total_samples = encoder->protected_->total_samples_estimate; /* we will replace this later with the real total */
  99656. memset(encoder->private_->streaminfo.data.stream_info.md5sum, 0, 16); /* we don't know this yet; have to fill it in later */
  99657. if(encoder->protected_->do_md5)
  99658. FLAC__MD5Init(&encoder->private_->md5context);
  99659. if(!FLAC__add_metadata_block(&encoder->private_->streaminfo, encoder->private_->frame)) {
  99660. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99661. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99662. }
  99663. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  99664. /* the above function sets the state for us in case of an error */
  99665. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99666. }
  99667. /*
  99668. * Now that the STREAMINFO block is written, we can init this to an
  99669. * absurdly-high value...
  99670. */
  99671. encoder->private_->streaminfo.data.stream_info.min_framesize = (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN) - 1;
  99672. /* ... and clear this to 0 */
  99673. encoder->private_->streaminfo.data.stream_info.total_samples = 0;
  99674. /*
  99675. * Check to see if the supplied metadata contains a VORBIS_COMMENT;
  99676. * if not, we will write an empty one (FLAC__add_metadata_block()
  99677. * automatically supplies the vendor string).
  99678. *
  99679. * WATCHOUT: the Ogg FLAC mapping requires us to write this block after
  99680. * the STREAMINFO. (In the case that metadata_has_vorbis_comment is
  99681. * true it will have already insured that the metadata list is properly
  99682. * ordered.)
  99683. */
  99684. if(!metadata_has_vorbis_comment) {
  99685. FLAC__StreamMetadata vorbis_comment;
  99686. vorbis_comment.type = FLAC__METADATA_TYPE_VORBIS_COMMENT;
  99687. vorbis_comment.is_last = (encoder->protected_->num_metadata_blocks == 0);
  99688. vorbis_comment.length = 4 + 4; /* MAGIC NUMBER */
  99689. vorbis_comment.data.vorbis_comment.vendor_string.length = 0;
  99690. vorbis_comment.data.vorbis_comment.vendor_string.entry = 0;
  99691. vorbis_comment.data.vorbis_comment.num_comments = 0;
  99692. vorbis_comment.data.vorbis_comment.comments = 0;
  99693. if(!FLAC__add_metadata_block(&vorbis_comment, encoder->private_->frame)) {
  99694. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99695. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99696. }
  99697. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  99698. /* the above function sets the state for us in case of an error */
  99699. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99700. }
  99701. }
  99702. /*
  99703. * write the user's metadata blocks
  99704. */
  99705. for(i = 0; i < encoder->protected_->num_metadata_blocks; i++) {
  99706. encoder->protected_->metadata[i]->is_last = (i == encoder->protected_->num_metadata_blocks - 1);
  99707. if(!FLAC__add_metadata_block(encoder->protected_->metadata[i], encoder->private_->frame)) {
  99708. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  99709. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99710. }
  99711. if(!write_bitbuffer_(encoder, 0, /*is_last_block=*/false)) {
  99712. /* the above function sets the state for us in case of an error */
  99713. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99714. }
  99715. }
  99716. /* now that all the metadata is written, we save the stream offset */
  99717. 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 */
  99718. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  99719. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99720. }
  99721. if(encoder->protected_->verify)
  99722. encoder->private_->verify.state_hint = ENCODER_IN_AUDIO;
  99723. return FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  99724. }
  99725. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_stream(
  99726. FLAC__StreamEncoder *encoder,
  99727. FLAC__StreamEncoderWriteCallback write_callback,
  99728. FLAC__StreamEncoderSeekCallback seek_callback,
  99729. FLAC__StreamEncoderTellCallback tell_callback,
  99730. FLAC__StreamEncoderMetadataCallback metadata_callback,
  99731. void *client_data
  99732. )
  99733. {
  99734. return init_stream_internal_enc(
  99735. encoder,
  99736. /*read_callback=*/0,
  99737. write_callback,
  99738. seek_callback,
  99739. tell_callback,
  99740. metadata_callback,
  99741. client_data,
  99742. /*is_ogg=*/false
  99743. );
  99744. }
  99745. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_stream(
  99746. FLAC__StreamEncoder *encoder,
  99747. FLAC__StreamEncoderReadCallback read_callback,
  99748. FLAC__StreamEncoderWriteCallback write_callback,
  99749. FLAC__StreamEncoderSeekCallback seek_callback,
  99750. FLAC__StreamEncoderTellCallback tell_callback,
  99751. FLAC__StreamEncoderMetadataCallback metadata_callback,
  99752. void *client_data
  99753. )
  99754. {
  99755. return init_stream_internal_enc(
  99756. encoder,
  99757. read_callback,
  99758. write_callback,
  99759. seek_callback,
  99760. tell_callback,
  99761. metadata_callback,
  99762. client_data,
  99763. /*is_ogg=*/true
  99764. );
  99765. }
  99766. static FLAC__StreamEncoderInitStatus init_FILE_internal_enc(
  99767. FLAC__StreamEncoder *encoder,
  99768. FILE *file,
  99769. FLAC__StreamEncoderProgressCallback progress_callback,
  99770. void *client_data,
  99771. FLAC__bool is_ogg
  99772. )
  99773. {
  99774. FLAC__StreamEncoderInitStatus init_status;
  99775. FLAC__ASSERT(0 != encoder);
  99776. FLAC__ASSERT(0 != file);
  99777. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99778. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  99779. /* double protection */
  99780. if(file == 0) {
  99781. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  99782. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99783. }
  99784. /*
  99785. * To make sure that our file does not go unclosed after an error, we
  99786. * must assign the FILE pointer before any further error can occur in
  99787. * this routine.
  99788. */
  99789. if(file == stdout)
  99790. file = get_binary_stdout_(); /* just to be safe */
  99791. encoder->private_->file = file;
  99792. encoder->private_->progress_callback = progress_callback;
  99793. encoder->private_->bytes_written = 0;
  99794. encoder->private_->samples_written = 0;
  99795. encoder->private_->frames_written = 0;
  99796. init_status = init_stream_internal_enc(
  99797. encoder,
  99798. encoder->private_->file == stdout? 0 : is_ogg? file_read_callback_enc : 0,
  99799. file_write_callback_,
  99800. encoder->private_->file == stdout? 0 : file_seek_callback_enc,
  99801. encoder->private_->file == stdout? 0 : file_tell_callback_enc,
  99802. /*metadata_callback=*/0,
  99803. client_data,
  99804. is_ogg
  99805. );
  99806. if(init_status != FLAC__STREAM_ENCODER_INIT_STATUS_OK) {
  99807. /* the above function sets the state for us in case of an error */
  99808. return init_status;
  99809. }
  99810. {
  99811. unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  99812. FLAC__ASSERT(blocksize != 0);
  99813. encoder->private_->total_frames_estimate = (unsigned)((FLAC__stream_encoder_get_total_samples_estimate(encoder) + blocksize - 1) / blocksize);
  99814. }
  99815. return init_status;
  99816. }
  99817. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_FILE(
  99818. FLAC__StreamEncoder *encoder,
  99819. FILE *file,
  99820. FLAC__StreamEncoderProgressCallback progress_callback,
  99821. void *client_data
  99822. )
  99823. {
  99824. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/false);
  99825. }
  99826. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_FILE(
  99827. FLAC__StreamEncoder *encoder,
  99828. FILE *file,
  99829. FLAC__StreamEncoderProgressCallback progress_callback,
  99830. void *client_data
  99831. )
  99832. {
  99833. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, /*is_ogg=*/true);
  99834. }
  99835. static FLAC__StreamEncoderInitStatus init_file_internal_enc(
  99836. FLAC__StreamEncoder *encoder,
  99837. const char *filename,
  99838. FLAC__StreamEncoderProgressCallback progress_callback,
  99839. void *client_data,
  99840. FLAC__bool is_ogg
  99841. )
  99842. {
  99843. FILE *file;
  99844. FLAC__ASSERT(0 != encoder);
  99845. /*
  99846. * To make sure that our file does not go unclosed after an error, we
  99847. * have to do the same entrance checks here that are later performed
  99848. * in FLAC__stream_encoder_init_FILE() before the FILE* is assigned.
  99849. */
  99850. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99851. return FLAC__STREAM_ENCODER_INIT_STATUS_ALREADY_INITIALIZED;
  99852. file = filename? fopen(filename, "w+b") : stdout;
  99853. if(file == 0) {
  99854. encoder->protected_->state = FLAC__STREAM_ENCODER_IO_ERROR;
  99855. return FLAC__STREAM_ENCODER_INIT_STATUS_ENCODER_ERROR;
  99856. }
  99857. return init_FILE_internal_enc(encoder, file, progress_callback, client_data, is_ogg);
  99858. }
  99859. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_file(
  99860. FLAC__StreamEncoder *encoder,
  99861. const char *filename,
  99862. FLAC__StreamEncoderProgressCallback progress_callback,
  99863. void *client_data
  99864. )
  99865. {
  99866. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/false);
  99867. }
  99868. FLAC_API FLAC__StreamEncoderInitStatus FLAC__stream_encoder_init_ogg_file(
  99869. FLAC__StreamEncoder *encoder,
  99870. const char *filename,
  99871. FLAC__StreamEncoderProgressCallback progress_callback,
  99872. void *client_data
  99873. )
  99874. {
  99875. return init_file_internal_enc(encoder, filename, progress_callback, client_data, /*is_ogg=*/true);
  99876. }
  99877. FLAC_API FLAC__bool FLAC__stream_encoder_finish(FLAC__StreamEncoder *encoder)
  99878. {
  99879. FLAC__bool error = false;
  99880. FLAC__ASSERT(0 != encoder);
  99881. FLAC__ASSERT(0 != encoder->private_);
  99882. FLAC__ASSERT(0 != encoder->protected_);
  99883. if(encoder->protected_->state == FLAC__STREAM_ENCODER_UNINITIALIZED)
  99884. return true;
  99885. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK && !encoder->private_->is_being_deleted) {
  99886. if(encoder->private_->current_sample_number != 0) {
  99887. const FLAC__bool is_fractional_block = encoder->protected_->blocksize != encoder->private_->current_sample_number;
  99888. encoder->protected_->blocksize = encoder->private_->current_sample_number;
  99889. if(!process_frame_(encoder, is_fractional_block, /*is_last_block=*/true))
  99890. error = true;
  99891. }
  99892. }
  99893. if(encoder->protected_->do_md5)
  99894. FLAC__MD5Final(encoder->private_->streaminfo.data.stream_info.md5sum, &encoder->private_->md5context);
  99895. if(!encoder->private_->is_being_deleted) {
  99896. if(encoder->protected_->state == FLAC__STREAM_ENCODER_OK) {
  99897. if(encoder->private_->seek_callback) {
  99898. #if FLAC__HAS_OGG
  99899. if(encoder->private_->is_ogg)
  99900. update_ogg_metadata_(encoder);
  99901. else
  99902. #endif
  99903. update_metadata_(encoder);
  99904. /* check if an error occurred while updating metadata */
  99905. if(encoder->protected_->state != FLAC__STREAM_ENCODER_OK)
  99906. error = true;
  99907. }
  99908. if(encoder->private_->metadata_callback)
  99909. encoder->private_->metadata_callback(encoder, &encoder->private_->streaminfo, encoder->private_->client_data);
  99910. }
  99911. if(encoder->protected_->verify && 0 != encoder->private_->verify.decoder && !FLAC__stream_decoder_finish(encoder->private_->verify.decoder)) {
  99912. if(!error)
  99913. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  99914. error = true;
  99915. }
  99916. }
  99917. if(0 != encoder->private_->file) {
  99918. if(encoder->private_->file != stdout)
  99919. fclose(encoder->private_->file);
  99920. encoder->private_->file = 0;
  99921. }
  99922. #if FLAC__HAS_OGG
  99923. if(encoder->private_->is_ogg)
  99924. FLAC__ogg_encoder_aspect_finish(&encoder->protected_->ogg_encoder_aspect);
  99925. #endif
  99926. free_(encoder);
  99927. set_defaults_enc(encoder);
  99928. if(!error)
  99929. encoder->protected_->state = FLAC__STREAM_ENCODER_UNINITIALIZED;
  99930. return !error;
  99931. }
  99932. FLAC_API FLAC__bool FLAC__stream_encoder_set_ogg_serial_number(FLAC__StreamEncoder *encoder, long value)
  99933. {
  99934. FLAC__ASSERT(0 != encoder);
  99935. FLAC__ASSERT(0 != encoder->private_);
  99936. FLAC__ASSERT(0 != encoder->protected_);
  99937. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99938. return false;
  99939. #if FLAC__HAS_OGG
  99940. /* can't check encoder->private_->is_ogg since that's not set until init time */
  99941. FLAC__ogg_encoder_aspect_set_serial_number(&encoder->protected_->ogg_encoder_aspect, value);
  99942. return true;
  99943. #else
  99944. (void)value;
  99945. return false;
  99946. #endif
  99947. }
  99948. FLAC_API FLAC__bool FLAC__stream_encoder_set_verify(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99949. {
  99950. FLAC__ASSERT(0 != encoder);
  99951. FLAC__ASSERT(0 != encoder->private_);
  99952. FLAC__ASSERT(0 != encoder->protected_);
  99953. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99954. return false;
  99955. #ifndef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  99956. encoder->protected_->verify = value;
  99957. #endif
  99958. return true;
  99959. }
  99960. FLAC_API FLAC__bool FLAC__stream_encoder_set_streamable_subset(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99961. {
  99962. FLAC__ASSERT(0 != encoder);
  99963. FLAC__ASSERT(0 != encoder->private_);
  99964. FLAC__ASSERT(0 != encoder->protected_);
  99965. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99966. return false;
  99967. encoder->protected_->streamable_subset = value;
  99968. return true;
  99969. }
  99970. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_md5(FLAC__StreamEncoder *encoder, FLAC__bool value)
  99971. {
  99972. FLAC__ASSERT(0 != encoder);
  99973. FLAC__ASSERT(0 != encoder->private_);
  99974. FLAC__ASSERT(0 != encoder->protected_);
  99975. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99976. return false;
  99977. encoder->protected_->do_md5 = value;
  99978. return true;
  99979. }
  99980. FLAC_API FLAC__bool FLAC__stream_encoder_set_channels(FLAC__StreamEncoder *encoder, unsigned value)
  99981. {
  99982. FLAC__ASSERT(0 != encoder);
  99983. FLAC__ASSERT(0 != encoder->private_);
  99984. FLAC__ASSERT(0 != encoder->protected_);
  99985. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99986. return false;
  99987. encoder->protected_->channels = value;
  99988. return true;
  99989. }
  99990. FLAC_API FLAC__bool FLAC__stream_encoder_set_bits_per_sample(FLAC__StreamEncoder *encoder, unsigned value)
  99991. {
  99992. FLAC__ASSERT(0 != encoder);
  99993. FLAC__ASSERT(0 != encoder->private_);
  99994. FLAC__ASSERT(0 != encoder->protected_);
  99995. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  99996. return false;
  99997. encoder->protected_->bits_per_sample = value;
  99998. return true;
  99999. }
  100000. FLAC_API FLAC__bool FLAC__stream_encoder_set_sample_rate(FLAC__StreamEncoder *encoder, unsigned value)
  100001. {
  100002. FLAC__ASSERT(0 != encoder);
  100003. FLAC__ASSERT(0 != encoder->private_);
  100004. FLAC__ASSERT(0 != encoder->protected_);
  100005. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100006. return false;
  100007. encoder->protected_->sample_rate = value;
  100008. return true;
  100009. }
  100010. FLAC_API FLAC__bool FLAC__stream_encoder_set_compression_level(FLAC__StreamEncoder *encoder, unsigned value)
  100011. {
  100012. FLAC__bool ok = true;
  100013. FLAC__ASSERT(0 != encoder);
  100014. FLAC__ASSERT(0 != encoder->private_);
  100015. FLAC__ASSERT(0 != encoder->protected_);
  100016. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100017. return false;
  100018. if(value >= sizeof(compression_levels_)/sizeof(compression_levels_[0]))
  100019. value = sizeof(compression_levels_)/sizeof(compression_levels_[0]) - 1;
  100020. ok &= FLAC__stream_encoder_set_do_mid_side_stereo (encoder, compression_levels_[value].do_mid_side_stereo);
  100021. ok &= FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, compression_levels_[value].loose_mid_side_stereo);
  100022. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100023. #if 0
  100024. /* was: */
  100025. ok &= FLAC__stream_encoder_set_apodization (encoder, compression_levels_[value].apodization);
  100026. /* but it's too hard to specify the string in a locale-specific way */
  100027. #else
  100028. encoder->protected_->num_apodizations = 1;
  100029. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  100030. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  100031. #endif
  100032. #endif
  100033. ok &= FLAC__stream_encoder_set_max_lpc_order (encoder, compression_levels_[value].max_lpc_order);
  100034. ok &= FLAC__stream_encoder_set_qlp_coeff_precision (encoder, compression_levels_[value].qlp_coeff_precision);
  100035. ok &= FLAC__stream_encoder_set_do_qlp_coeff_prec_search (encoder, compression_levels_[value].do_qlp_coeff_prec_search);
  100036. ok &= FLAC__stream_encoder_set_do_escape_coding (encoder, compression_levels_[value].do_escape_coding);
  100037. ok &= FLAC__stream_encoder_set_do_exhaustive_model_search (encoder, compression_levels_[value].do_exhaustive_model_search);
  100038. ok &= FLAC__stream_encoder_set_min_residual_partition_order(encoder, compression_levels_[value].min_residual_partition_order);
  100039. ok &= FLAC__stream_encoder_set_max_residual_partition_order(encoder, compression_levels_[value].max_residual_partition_order);
  100040. ok &= FLAC__stream_encoder_set_rice_parameter_search_dist (encoder, compression_levels_[value].rice_parameter_search_dist);
  100041. return ok;
  100042. }
  100043. FLAC_API FLAC__bool FLAC__stream_encoder_set_blocksize(FLAC__StreamEncoder *encoder, unsigned value)
  100044. {
  100045. FLAC__ASSERT(0 != encoder);
  100046. FLAC__ASSERT(0 != encoder->private_);
  100047. FLAC__ASSERT(0 != encoder->protected_);
  100048. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100049. return false;
  100050. encoder->protected_->blocksize = value;
  100051. return true;
  100052. }
  100053. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100054. {
  100055. FLAC__ASSERT(0 != encoder);
  100056. FLAC__ASSERT(0 != encoder->private_);
  100057. FLAC__ASSERT(0 != encoder->protected_);
  100058. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100059. return false;
  100060. encoder->protected_->do_mid_side_stereo = value;
  100061. return true;
  100062. }
  100063. FLAC_API FLAC__bool FLAC__stream_encoder_set_loose_mid_side_stereo(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100064. {
  100065. FLAC__ASSERT(0 != encoder);
  100066. FLAC__ASSERT(0 != encoder->private_);
  100067. FLAC__ASSERT(0 != encoder->protected_);
  100068. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100069. return false;
  100070. encoder->protected_->loose_mid_side_stereo = value;
  100071. return true;
  100072. }
  100073. /*@@@@add to tests*/
  100074. FLAC_API FLAC__bool FLAC__stream_encoder_set_apodization(FLAC__StreamEncoder *encoder, const char *specification)
  100075. {
  100076. FLAC__ASSERT(0 != encoder);
  100077. FLAC__ASSERT(0 != encoder->private_);
  100078. FLAC__ASSERT(0 != encoder->protected_);
  100079. FLAC__ASSERT(0 != specification);
  100080. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100081. return false;
  100082. #ifdef FLAC__INTEGER_ONLY_LIBRARY
  100083. (void)specification; /* silently ignore since we haven't integerized; will always use a rectangular window */
  100084. #else
  100085. encoder->protected_->num_apodizations = 0;
  100086. while(1) {
  100087. const char *s = strchr(specification, ';');
  100088. const size_t n = s? (size_t)(s - specification) : strlen(specification);
  100089. if (n==8 && 0 == strncmp("bartlett" , specification, n))
  100090. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT;
  100091. else if(n==13 && 0 == strncmp("bartlett_hann", specification, n))
  100092. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BARTLETT_HANN;
  100093. else if(n==8 && 0 == strncmp("blackman" , specification, n))
  100094. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN;
  100095. else if(n==26 && 0 == strncmp("blackman_harris_4term_92db", specification, n))
  100096. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE;
  100097. else if(n==6 && 0 == strncmp("connes" , specification, n))
  100098. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_CONNES;
  100099. else if(n==7 && 0 == strncmp("flattop" , specification, n))
  100100. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_FLATTOP;
  100101. else if(n>7 && 0 == strncmp("gauss(" , specification, 6)) {
  100102. FLAC__real stddev = (FLAC__real)strtod(specification+6, 0);
  100103. if (stddev > 0.0 && stddev <= 0.5) {
  100104. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.gauss.stddev = stddev;
  100105. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_GAUSS;
  100106. }
  100107. }
  100108. else if(n==7 && 0 == strncmp("hamming" , specification, n))
  100109. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HAMMING;
  100110. else if(n==4 && 0 == strncmp("hann" , specification, n))
  100111. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_HANN;
  100112. else if(n==13 && 0 == strncmp("kaiser_bessel", specification, n))
  100113. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_KAISER_BESSEL;
  100114. else if(n==7 && 0 == strncmp("nuttall" , specification, n))
  100115. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_NUTTALL;
  100116. else if(n==9 && 0 == strncmp("rectangle" , specification, n))
  100117. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_RECTANGLE;
  100118. else if(n==8 && 0 == strncmp("triangle" , specification, n))
  100119. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TRIANGLE;
  100120. else if(n>7 && 0 == strncmp("tukey(" , specification, 6)) {
  100121. FLAC__real p = (FLAC__real)strtod(specification+6, 0);
  100122. if (p >= 0.0 && p <= 1.0) {
  100123. encoder->protected_->apodizations[encoder->protected_->num_apodizations].parameters.tukey.p = p;
  100124. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_TUKEY;
  100125. }
  100126. }
  100127. else if(n==5 && 0 == strncmp("welch" , specification, n))
  100128. encoder->protected_->apodizations[encoder->protected_->num_apodizations++].type = FLAC__APODIZATION_WELCH;
  100129. if (encoder->protected_->num_apodizations == 32)
  100130. break;
  100131. if (s)
  100132. specification = s+1;
  100133. else
  100134. break;
  100135. }
  100136. if(encoder->protected_->num_apodizations == 0) {
  100137. encoder->protected_->num_apodizations = 1;
  100138. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  100139. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  100140. }
  100141. #endif
  100142. return true;
  100143. }
  100144. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_lpc_order(FLAC__StreamEncoder *encoder, unsigned value)
  100145. {
  100146. FLAC__ASSERT(0 != encoder);
  100147. FLAC__ASSERT(0 != encoder->private_);
  100148. FLAC__ASSERT(0 != encoder->protected_);
  100149. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100150. return false;
  100151. encoder->protected_->max_lpc_order = value;
  100152. return true;
  100153. }
  100154. FLAC_API FLAC__bool FLAC__stream_encoder_set_qlp_coeff_precision(FLAC__StreamEncoder *encoder, unsigned value)
  100155. {
  100156. FLAC__ASSERT(0 != encoder);
  100157. FLAC__ASSERT(0 != encoder->private_);
  100158. FLAC__ASSERT(0 != encoder->protected_);
  100159. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100160. return false;
  100161. encoder->protected_->qlp_coeff_precision = value;
  100162. return true;
  100163. }
  100164. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_qlp_coeff_prec_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100165. {
  100166. FLAC__ASSERT(0 != encoder);
  100167. FLAC__ASSERT(0 != encoder->private_);
  100168. FLAC__ASSERT(0 != encoder->protected_);
  100169. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100170. return false;
  100171. encoder->protected_->do_qlp_coeff_prec_search = value;
  100172. return true;
  100173. }
  100174. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_escape_coding(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100175. {
  100176. FLAC__ASSERT(0 != encoder);
  100177. FLAC__ASSERT(0 != encoder->private_);
  100178. FLAC__ASSERT(0 != encoder->protected_);
  100179. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100180. return false;
  100181. #if 0
  100182. /*@@@ deprecated: */
  100183. encoder->protected_->do_escape_coding = value;
  100184. #else
  100185. (void)value;
  100186. #endif
  100187. return true;
  100188. }
  100189. FLAC_API FLAC__bool FLAC__stream_encoder_set_do_exhaustive_model_search(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100190. {
  100191. FLAC__ASSERT(0 != encoder);
  100192. FLAC__ASSERT(0 != encoder->private_);
  100193. FLAC__ASSERT(0 != encoder->protected_);
  100194. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100195. return false;
  100196. encoder->protected_->do_exhaustive_model_search = value;
  100197. return true;
  100198. }
  100199. FLAC_API FLAC__bool FLAC__stream_encoder_set_min_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  100200. {
  100201. FLAC__ASSERT(0 != encoder);
  100202. FLAC__ASSERT(0 != encoder->private_);
  100203. FLAC__ASSERT(0 != encoder->protected_);
  100204. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100205. return false;
  100206. encoder->protected_->min_residual_partition_order = value;
  100207. return true;
  100208. }
  100209. FLAC_API FLAC__bool FLAC__stream_encoder_set_max_residual_partition_order(FLAC__StreamEncoder *encoder, unsigned value)
  100210. {
  100211. FLAC__ASSERT(0 != encoder);
  100212. FLAC__ASSERT(0 != encoder->private_);
  100213. FLAC__ASSERT(0 != encoder->protected_);
  100214. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100215. return false;
  100216. encoder->protected_->max_residual_partition_order = value;
  100217. return true;
  100218. }
  100219. FLAC_API FLAC__bool FLAC__stream_encoder_set_rice_parameter_search_dist(FLAC__StreamEncoder *encoder, unsigned value)
  100220. {
  100221. FLAC__ASSERT(0 != encoder);
  100222. FLAC__ASSERT(0 != encoder->private_);
  100223. FLAC__ASSERT(0 != encoder->protected_);
  100224. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100225. return false;
  100226. #if 0
  100227. /*@@@ deprecated: */
  100228. encoder->protected_->rice_parameter_search_dist = value;
  100229. #else
  100230. (void)value;
  100231. #endif
  100232. return true;
  100233. }
  100234. FLAC_API FLAC__bool FLAC__stream_encoder_set_total_samples_estimate(FLAC__StreamEncoder *encoder, FLAC__uint64 value)
  100235. {
  100236. FLAC__ASSERT(0 != encoder);
  100237. FLAC__ASSERT(0 != encoder->private_);
  100238. FLAC__ASSERT(0 != encoder->protected_);
  100239. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100240. return false;
  100241. encoder->protected_->total_samples_estimate = value;
  100242. return true;
  100243. }
  100244. FLAC_API FLAC__bool FLAC__stream_encoder_set_metadata(FLAC__StreamEncoder *encoder, FLAC__StreamMetadata **metadata, unsigned num_blocks)
  100245. {
  100246. FLAC__ASSERT(0 != encoder);
  100247. FLAC__ASSERT(0 != encoder->private_);
  100248. FLAC__ASSERT(0 != encoder->protected_);
  100249. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100250. return false;
  100251. if(0 == metadata)
  100252. num_blocks = 0;
  100253. if(0 == num_blocks)
  100254. metadata = 0;
  100255. /* realloc() does not do exactly what we want so... */
  100256. if(encoder->protected_->metadata) {
  100257. free(encoder->protected_->metadata);
  100258. encoder->protected_->metadata = 0;
  100259. encoder->protected_->num_metadata_blocks = 0;
  100260. }
  100261. if(num_blocks) {
  100262. FLAC__StreamMetadata **m;
  100263. if(0 == (m = (FLAC__StreamMetadata**)safe_malloc_mul_2op_(sizeof(m[0]), /*times*/num_blocks)))
  100264. return false;
  100265. memcpy(m, metadata, sizeof(m[0]) * num_blocks);
  100266. encoder->protected_->metadata = m;
  100267. encoder->protected_->num_metadata_blocks = num_blocks;
  100268. }
  100269. #if FLAC__HAS_OGG
  100270. if(!FLAC__ogg_encoder_aspect_set_num_metadata(&encoder->protected_->ogg_encoder_aspect, num_blocks))
  100271. return false;
  100272. #endif
  100273. return true;
  100274. }
  100275. /*
  100276. * These three functions are not static, but not publically exposed in
  100277. * include/FLAC/ either. They are used by the test suite.
  100278. */
  100279. FLAC_API FLAC__bool FLAC__stream_encoder_disable_constant_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100280. {
  100281. FLAC__ASSERT(0 != encoder);
  100282. FLAC__ASSERT(0 != encoder->private_);
  100283. FLAC__ASSERT(0 != encoder->protected_);
  100284. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100285. return false;
  100286. encoder->private_->disable_constant_subframes = value;
  100287. return true;
  100288. }
  100289. FLAC_API FLAC__bool FLAC__stream_encoder_disable_fixed_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100290. {
  100291. FLAC__ASSERT(0 != encoder);
  100292. FLAC__ASSERT(0 != encoder->private_);
  100293. FLAC__ASSERT(0 != encoder->protected_);
  100294. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100295. return false;
  100296. encoder->private_->disable_fixed_subframes = value;
  100297. return true;
  100298. }
  100299. FLAC_API FLAC__bool FLAC__stream_encoder_disable_verbatim_subframes(FLAC__StreamEncoder *encoder, FLAC__bool value)
  100300. {
  100301. FLAC__ASSERT(0 != encoder);
  100302. FLAC__ASSERT(0 != encoder->private_);
  100303. FLAC__ASSERT(0 != encoder->protected_);
  100304. if(encoder->protected_->state != FLAC__STREAM_ENCODER_UNINITIALIZED)
  100305. return false;
  100306. encoder->private_->disable_verbatim_subframes = value;
  100307. return true;
  100308. }
  100309. FLAC_API FLAC__StreamEncoderState FLAC__stream_encoder_get_state(const FLAC__StreamEncoder *encoder)
  100310. {
  100311. FLAC__ASSERT(0 != encoder);
  100312. FLAC__ASSERT(0 != encoder->private_);
  100313. FLAC__ASSERT(0 != encoder->protected_);
  100314. return encoder->protected_->state;
  100315. }
  100316. FLAC_API FLAC__StreamDecoderState FLAC__stream_encoder_get_verify_decoder_state(const FLAC__StreamEncoder *encoder)
  100317. {
  100318. FLAC__ASSERT(0 != encoder);
  100319. FLAC__ASSERT(0 != encoder->private_);
  100320. FLAC__ASSERT(0 != encoder->protected_);
  100321. if(encoder->protected_->verify)
  100322. return FLAC__stream_decoder_get_state(encoder->private_->verify.decoder);
  100323. else
  100324. return FLAC__STREAM_DECODER_UNINITIALIZED;
  100325. }
  100326. FLAC_API const char *FLAC__stream_encoder_get_resolved_state_string(const FLAC__StreamEncoder *encoder)
  100327. {
  100328. FLAC__ASSERT(0 != encoder);
  100329. FLAC__ASSERT(0 != encoder->private_);
  100330. FLAC__ASSERT(0 != encoder->protected_);
  100331. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR)
  100332. return FLAC__StreamEncoderStateString[encoder->protected_->state];
  100333. else
  100334. return FLAC__stream_decoder_get_resolved_state_string(encoder->private_->verify.decoder);
  100335. }
  100336. 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)
  100337. {
  100338. FLAC__ASSERT(0 != encoder);
  100339. FLAC__ASSERT(0 != encoder->private_);
  100340. FLAC__ASSERT(0 != encoder->protected_);
  100341. if(0 != absolute_sample)
  100342. *absolute_sample = encoder->private_->verify.error_stats.absolute_sample;
  100343. if(0 != frame_number)
  100344. *frame_number = encoder->private_->verify.error_stats.frame_number;
  100345. if(0 != channel)
  100346. *channel = encoder->private_->verify.error_stats.channel;
  100347. if(0 != sample)
  100348. *sample = encoder->private_->verify.error_stats.sample;
  100349. if(0 != expected)
  100350. *expected = encoder->private_->verify.error_stats.expected;
  100351. if(0 != got)
  100352. *got = encoder->private_->verify.error_stats.got;
  100353. }
  100354. FLAC_API FLAC__bool FLAC__stream_encoder_get_verify(const FLAC__StreamEncoder *encoder)
  100355. {
  100356. FLAC__ASSERT(0 != encoder);
  100357. FLAC__ASSERT(0 != encoder->private_);
  100358. FLAC__ASSERT(0 != encoder->protected_);
  100359. return encoder->protected_->verify;
  100360. }
  100361. FLAC_API FLAC__bool FLAC__stream_encoder_get_streamable_subset(const FLAC__StreamEncoder *encoder)
  100362. {
  100363. FLAC__ASSERT(0 != encoder);
  100364. FLAC__ASSERT(0 != encoder->private_);
  100365. FLAC__ASSERT(0 != encoder->protected_);
  100366. return encoder->protected_->streamable_subset;
  100367. }
  100368. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_md5(const FLAC__StreamEncoder *encoder)
  100369. {
  100370. FLAC__ASSERT(0 != encoder);
  100371. FLAC__ASSERT(0 != encoder->private_);
  100372. FLAC__ASSERT(0 != encoder->protected_);
  100373. return encoder->protected_->do_md5;
  100374. }
  100375. FLAC_API unsigned FLAC__stream_encoder_get_channels(const FLAC__StreamEncoder *encoder)
  100376. {
  100377. FLAC__ASSERT(0 != encoder);
  100378. FLAC__ASSERT(0 != encoder->private_);
  100379. FLAC__ASSERT(0 != encoder->protected_);
  100380. return encoder->protected_->channels;
  100381. }
  100382. FLAC_API unsigned FLAC__stream_encoder_get_bits_per_sample(const FLAC__StreamEncoder *encoder)
  100383. {
  100384. FLAC__ASSERT(0 != encoder);
  100385. FLAC__ASSERT(0 != encoder->private_);
  100386. FLAC__ASSERT(0 != encoder->protected_);
  100387. return encoder->protected_->bits_per_sample;
  100388. }
  100389. FLAC_API unsigned FLAC__stream_encoder_get_sample_rate(const FLAC__StreamEncoder *encoder)
  100390. {
  100391. FLAC__ASSERT(0 != encoder);
  100392. FLAC__ASSERT(0 != encoder->private_);
  100393. FLAC__ASSERT(0 != encoder->protected_);
  100394. return encoder->protected_->sample_rate;
  100395. }
  100396. FLAC_API unsigned FLAC__stream_encoder_get_blocksize(const FLAC__StreamEncoder *encoder)
  100397. {
  100398. FLAC__ASSERT(0 != encoder);
  100399. FLAC__ASSERT(0 != encoder->private_);
  100400. FLAC__ASSERT(0 != encoder->protected_);
  100401. return encoder->protected_->blocksize;
  100402. }
  100403. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  100404. {
  100405. FLAC__ASSERT(0 != encoder);
  100406. FLAC__ASSERT(0 != encoder->private_);
  100407. FLAC__ASSERT(0 != encoder->protected_);
  100408. return encoder->protected_->do_mid_side_stereo;
  100409. }
  100410. FLAC_API FLAC__bool FLAC__stream_encoder_get_loose_mid_side_stereo(const FLAC__StreamEncoder *encoder)
  100411. {
  100412. FLAC__ASSERT(0 != encoder);
  100413. FLAC__ASSERT(0 != encoder->private_);
  100414. FLAC__ASSERT(0 != encoder->protected_);
  100415. return encoder->protected_->loose_mid_side_stereo;
  100416. }
  100417. FLAC_API unsigned FLAC__stream_encoder_get_max_lpc_order(const FLAC__StreamEncoder *encoder)
  100418. {
  100419. FLAC__ASSERT(0 != encoder);
  100420. FLAC__ASSERT(0 != encoder->private_);
  100421. FLAC__ASSERT(0 != encoder->protected_);
  100422. return encoder->protected_->max_lpc_order;
  100423. }
  100424. FLAC_API unsigned FLAC__stream_encoder_get_qlp_coeff_precision(const FLAC__StreamEncoder *encoder)
  100425. {
  100426. FLAC__ASSERT(0 != encoder);
  100427. FLAC__ASSERT(0 != encoder->private_);
  100428. FLAC__ASSERT(0 != encoder->protected_);
  100429. return encoder->protected_->qlp_coeff_precision;
  100430. }
  100431. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_qlp_coeff_prec_search(const FLAC__StreamEncoder *encoder)
  100432. {
  100433. FLAC__ASSERT(0 != encoder);
  100434. FLAC__ASSERT(0 != encoder->private_);
  100435. FLAC__ASSERT(0 != encoder->protected_);
  100436. return encoder->protected_->do_qlp_coeff_prec_search;
  100437. }
  100438. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_escape_coding(const FLAC__StreamEncoder *encoder)
  100439. {
  100440. FLAC__ASSERT(0 != encoder);
  100441. FLAC__ASSERT(0 != encoder->private_);
  100442. FLAC__ASSERT(0 != encoder->protected_);
  100443. return encoder->protected_->do_escape_coding;
  100444. }
  100445. FLAC_API FLAC__bool FLAC__stream_encoder_get_do_exhaustive_model_search(const FLAC__StreamEncoder *encoder)
  100446. {
  100447. FLAC__ASSERT(0 != encoder);
  100448. FLAC__ASSERT(0 != encoder->private_);
  100449. FLAC__ASSERT(0 != encoder->protected_);
  100450. return encoder->protected_->do_exhaustive_model_search;
  100451. }
  100452. FLAC_API unsigned FLAC__stream_encoder_get_min_residual_partition_order(const FLAC__StreamEncoder *encoder)
  100453. {
  100454. FLAC__ASSERT(0 != encoder);
  100455. FLAC__ASSERT(0 != encoder->private_);
  100456. FLAC__ASSERT(0 != encoder->protected_);
  100457. return encoder->protected_->min_residual_partition_order;
  100458. }
  100459. FLAC_API unsigned FLAC__stream_encoder_get_max_residual_partition_order(const FLAC__StreamEncoder *encoder)
  100460. {
  100461. FLAC__ASSERT(0 != encoder);
  100462. FLAC__ASSERT(0 != encoder->private_);
  100463. FLAC__ASSERT(0 != encoder->protected_);
  100464. return encoder->protected_->max_residual_partition_order;
  100465. }
  100466. FLAC_API unsigned FLAC__stream_encoder_get_rice_parameter_search_dist(const FLAC__StreamEncoder *encoder)
  100467. {
  100468. FLAC__ASSERT(0 != encoder);
  100469. FLAC__ASSERT(0 != encoder->private_);
  100470. FLAC__ASSERT(0 != encoder->protected_);
  100471. return encoder->protected_->rice_parameter_search_dist;
  100472. }
  100473. FLAC_API FLAC__uint64 FLAC__stream_encoder_get_total_samples_estimate(const FLAC__StreamEncoder *encoder)
  100474. {
  100475. FLAC__ASSERT(0 != encoder);
  100476. FLAC__ASSERT(0 != encoder->private_);
  100477. FLAC__ASSERT(0 != encoder->protected_);
  100478. return encoder->protected_->total_samples_estimate;
  100479. }
  100480. FLAC_API FLAC__bool FLAC__stream_encoder_process(FLAC__StreamEncoder *encoder, const FLAC__int32 * const buffer[], unsigned samples)
  100481. {
  100482. unsigned i, j = 0, channel;
  100483. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  100484. FLAC__ASSERT(0 != encoder);
  100485. FLAC__ASSERT(0 != encoder->private_);
  100486. FLAC__ASSERT(0 != encoder->protected_);
  100487. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100488. do {
  100489. const unsigned n = min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j);
  100490. if(encoder->protected_->verify)
  100491. append_to_verify_fifo_(&encoder->private_->verify.input_fifo, buffer, j, channels, n);
  100492. for(channel = 0; channel < channels; channel++)
  100493. memcpy(&encoder->private_->integer_signal[channel][encoder->private_->current_sample_number], &buffer[channel][j], sizeof(buffer[channel][0]) * n);
  100494. if(encoder->protected_->do_mid_side_stereo) {
  100495. FLAC__ASSERT(channels == 2);
  100496. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  100497. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  100498. encoder->private_->integer_signal_mid_side[1][i] = buffer[0][j] - buffer[1][j];
  100499. 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' ! */
  100500. }
  100501. }
  100502. else
  100503. j += n;
  100504. encoder->private_->current_sample_number += n;
  100505. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  100506. if(encoder->private_->current_sample_number > blocksize) {
  100507. FLAC__ASSERT(encoder->private_->current_sample_number == blocksize+OVERREAD_);
  100508. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  100509. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  100510. return false;
  100511. /* move unprocessed overread samples to beginnings of arrays */
  100512. for(channel = 0; channel < channels; channel++)
  100513. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  100514. if(encoder->protected_->do_mid_side_stereo) {
  100515. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  100516. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  100517. }
  100518. encoder->private_->current_sample_number = 1;
  100519. }
  100520. } while(j < samples);
  100521. return true;
  100522. }
  100523. FLAC_API FLAC__bool FLAC__stream_encoder_process_interleaved(FLAC__StreamEncoder *encoder, const FLAC__int32 buffer[], unsigned samples)
  100524. {
  100525. unsigned i, j, k, channel;
  100526. FLAC__int32 x, mid, side;
  100527. const unsigned channels = encoder->protected_->channels, blocksize = encoder->protected_->blocksize;
  100528. FLAC__ASSERT(0 != encoder);
  100529. FLAC__ASSERT(0 != encoder->private_);
  100530. FLAC__ASSERT(0 != encoder->protected_);
  100531. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100532. j = k = 0;
  100533. /*
  100534. * we have several flavors of the same basic loop, optimized for
  100535. * different conditions:
  100536. */
  100537. if(encoder->protected_->do_mid_side_stereo && channels == 2) {
  100538. /*
  100539. * stereo coding: unroll channel loop
  100540. */
  100541. do {
  100542. if(encoder->protected_->verify)
  100543. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  100544. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  100545. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  100546. encoder->private_->integer_signal[0][i] = mid = side = buffer[k++];
  100547. x = buffer[k++];
  100548. encoder->private_->integer_signal[1][i] = x;
  100549. mid += x;
  100550. side -= x;
  100551. mid >>= 1; /* NOTE: not the same as 'mid = (left + right) / 2' ! */
  100552. encoder->private_->integer_signal_mid_side[1][i] = side;
  100553. encoder->private_->integer_signal_mid_side[0][i] = mid;
  100554. }
  100555. encoder->private_->current_sample_number = i;
  100556. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  100557. if(i > blocksize) {
  100558. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  100559. return false;
  100560. /* move unprocessed overread samples to beginnings of arrays */
  100561. FLAC__ASSERT(i == blocksize+OVERREAD_);
  100562. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  100563. encoder->private_->integer_signal[0][0] = encoder->private_->integer_signal[0][blocksize];
  100564. encoder->private_->integer_signal[1][0] = encoder->private_->integer_signal[1][blocksize];
  100565. encoder->private_->integer_signal_mid_side[0][0] = encoder->private_->integer_signal_mid_side[0][blocksize];
  100566. encoder->private_->integer_signal_mid_side[1][0] = encoder->private_->integer_signal_mid_side[1][blocksize];
  100567. encoder->private_->current_sample_number = 1;
  100568. }
  100569. } while(j < samples);
  100570. }
  100571. else {
  100572. /*
  100573. * independent channel coding: buffer each channel in inner loop
  100574. */
  100575. do {
  100576. if(encoder->protected_->verify)
  100577. append_to_verify_fifo_interleaved_(&encoder->private_->verify.input_fifo, buffer, j, channels, min(blocksize+OVERREAD_-encoder->private_->current_sample_number, samples-j));
  100578. /* "i <= blocksize" to overread 1 sample; see comment in OVERREAD_ decl */
  100579. for(i = encoder->private_->current_sample_number; i <= blocksize && j < samples; i++, j++) {
  100580. for(channel = 0; channel < channels; channel++)
  100581. encoder->private_->integer_signal[channel][i] = buffer[k++];
  100582. }
  100583. encoder->private_->current_sample_number = i;
  100584. /* we only process if we have a full block + 1 extra sample; final block is always handled by FLAC__stream_encoder_finish() */
  100585. if(i > blocksize) {
  100586. if(!process_frame_(encoder, /*is_fractional_block=*/false, /*is_last_block=*/false))
  100587. return false;
  100588. /* move unprocessed overread samples to beginnings of arrays */
  100589. FLAC__ASSERT(i == blocksize+OVERREAD_);
  100590. FLAC__ASSERT(OVERREAD_ == 1); /* assert we only overread 1 sample which simplifies the rest of the code below */
  100591. for(channel = 0; channel < channels; channel++)
  100592. encoder->private_->integer_signal[channel][0] = encoder->private_->integer_signal[channel][blocksize];
  100593. encoder->private_->current_sample_number = 1;
  100594. }
  100595. } while(j < samples);
  100596. }
  100597. return true;
  100598. }
  100599. /***********************************************************************
  100600. *
  100601. * Private class methods
  100602. *
  100603. ***********************************************************************/
  100604. void set_defaults_enc(FLAC__StreamEncoder *encoder)
  100605. {
  100606. FLAC__ASSERT(0 != encoder);
  100607. #ifdef FLAC__MANDATORY_VERIFY_WHILE_ENCODING
  100608. encoder->protected_->verify = true;
  100609. #else
  100610. encoder->protected_->verify = false;
  100611. #endif
  100612. encoder->protected_->streamable_subset = true;
  100613. encoder->protected_->do_md5 = true;
  100614. encoder->protected_->do_mid_side_stereo = false;
  100615. encoder->protected_->loose_mid_side_stereo = false;
  100616. encoder->protected_->channels = 2;
  100617. encoder->protected_->bits_per_sample = 16;
  100618. encoder->protected_->sample_rate = 44100;
  100619. encoder->protected_->blocksize = 0;
  100620. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100621. encoder->protected_->num_apodizations = 1;
  100622. encoder->protected_->apodizations[0].type = FLAC__APODIZATION_TUKEY;
  100623. encoder->protected_->apodizations[0].parameters.tukey.p = 0.5;
  100624. #endif
  100625. encoder->protected_->max_lpc_order = 0;
  100626. encoder->protected_->qlp_coeff_precision = 0;
  100627. encoder->protected_->do_qlp_coeff_prec_search = false;
  100628. encoder->protected_->do_exhaustive_model_search = false;
  100629. encoder->protected_->do_escape_coding = false;
  100630. encoder->protected_->min_residual_partition_order = 0;
  100631. encoder->protected_->max_residual_partition_order = 0;
  100632. encoder->protected_->rice_parameter_search_dist = 0;
  100633. encoder->protected_->total_samples_estimate = 0;
  100634. encoder->protected_->metadata = 0;
  100635. encoder->protected_->num_metadata_blocks = 0;
  100636. encoder->private_->seek_table = 0;
  100637. encoder->private_->disable_constant_subframes = false;
  100638. encoder->private_->disable_fixed_subframes = false;
  100639. encoder->private_->disable_verbatim_subframes = false;
  100640. #if FLAC__HAS_OGG
  100641. encoder->private_->is_ogg = false;
  100642. #endif
  100643. encoder->private_->read_callback = 0;
  100644. encoder->private_->write_callback = 0;
  100645. encoder->private_->seek_callback = 0;
  100646. encoder->private_->tell_callback = 0;
  100647. encoder->private_->metadata_callback = 0;
  100648. encoder->private_->progress_callback = 0;
  100649. encoder->private_->client_data = 0;
  100650. #if FLAC__HAS_OGG
  100651. FLAC__ogg_encoder_aspect_set_defaults(&encoder->protected_->ogg_encoder_aspect);
  100652. #endif
  100653. }
  100654. void free_(FLAC__StreamEncoder *encoder)
  100655. {
  100656. unsigned i, channel;
  100657. FLAC__ASSERT(0 != encoder);
  100658. if(encoder->protected_->metadata) {
  100659. free(encoder->protected_->metadata);
  100660. encoder->protected_->metadata = 0;
  100661. encoder->protected_->num_metadata_blocks = 0;
  100662. }
  100663. for(i = 0; i < encoder->protected_->channels; i++) {
  100664. if(0 != encoder->private_->integer_signal_unaligned[i]) {
  100665. free(encoder->private_->integer_signal_unaligned[i]);
  100666. encoder->private_->integer_signal_unaligned[i] = 0;
  100667. }
  100668. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100669. if(0 != encoder->private_->real_signal_unaligned[i]) {
  100670. free(encoder->private_->real_signal_unaligned[i]);
  100671. encoder->private_->real_signal_unaligned[i] = 0;
  100672. }
  100673. #endif
  100674. }
  100675. for(i = 0; i < 2; i++) {
  100676. if(0 != encoder->private_->integer_signal_mid_side_unaligned[i]) {
  100677. free(encoder->private_->integer_signal_mid_side_unaligned[i]);
  100678. encoder->private_->integer_signal_mid_side_unaligned[i] = 0;
  100679. }
  100680. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100681. if(0 != encoder->private_->real_signal_mid_side_unaligned[i]) {
  100682. free(encoder->private_->real_signal_mid_side_unaligned[i]);
  100683. encoder->private_->real_signal_mid_side_unaligned[i] = 0;
  100684. }
  100685. #endif
  100686. }
  100687. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100688. for(i = 0; i < encoder->protected_->num_apodizations; i++) {
  100689. if(0 != encoder->private_->window_unaligned[i]) {
  100690. free(encoder->private_->window_unaligned[i]);
  100691. encoder->private_->window_unaligned[i] = 0;
  100692. }
  100693. }
  100694. if(0 != encoder->private_->windowed_signal_unaligned) {
  100695. free(encoder->private_->windowed_signal_unaligned);
  100696. encoder->private_->windowed_signal_unaligned = 0;
  100697. }
  100698. #endif
  100699. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  100700. for(i = 0; i < 2; i++) {
  100701. if(0 != encoder->private_->residual_workspace_unaligned[channel][i]) {
  100702. free(encoder->private_->residual_workspace_unaligned[channel][i]);
  100703. encoder->private_->residual_workspace_unaligned[channel][i] = 0;
  100704. }
  100705. }
  100706. }
  100707. for(channel = 0; channel < 2; channel++) {
  100708. for(i = 0; i < 2; i++) {
  100709. if(0 != encoder->private_->residual_workspace_mid_side_unaligned[channel][i]) {
  100710. free(encoder->private_->residual_workspace_mid_side_unaligned[channel][i]);
  100711. encoder->private_->residual_workspace_mid_side_unaligned[channel][i] = 0;
  100712. }
  100713. }
  100714. }
  100715. if(0 != encoder->private_->abs_residual_partition_sums_unaligned) {
  100716. free(encoder->private_->abs_residual_partition_sums_unaligned);
  100717. encoder->private_->abs_residual_partition_sums_unaligned = 0;
  100718. }
  100719. if(0 != encoder->private_->raw_bits_per_partition_unaligned) {
  100720. free(encoder->private_->raw_bits_per_partition_unaligned);
  100721. encoder->private_->raw_bits_per_partition_unaligned = 0;
  100722. }
  100723. if(encoder->protected_->verify) {
  100724. for(i = 0; i < encoder->protected_->channels; i++) {
  100725. if(0 != encoder->private_->verify.input_fifo.data[i]) {
  100726. free(encoder->private_->verify.input_fifo.data[i]);
  100727. encoder->private_->verify.input_fifo.data[i] = 0;
  100728. }
  100729. }
  100730. }
  100731. FLAC__bitwriter_free(encoder->private_->frame);
  100732. }
  100733. FLAC__bool resize_buffers_(FLAC__StreamEncoder *encoder, unsigned new_blocksize)
  100734. {
  100735. FLAC__bool ok;
  100736. unsigned i, channel;
  100737. FLAC__ASSERT(new_blocksize > 0);
  100738. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  100739. FLAC__ASSERT(encoder->private_->current_sample_number == 0);
  100740. /* To avoid excessive malloc'ing, we only grow the buffer; no shrinking. */
  100741. if(new_blocksize <= encoder->private_->input_capacity)
  100742. return true;
  100743. ok = true;
  100744. /* WATCHOUT: FLAC__lpc_compute_residual_from_qlp_coefficients_asm_ia32_mmx()
  100745. * requires that the input arrays (in our case the integer signals)
  100746. * have a buffer of up to 3 zeroes in front (at negative indices) for
  100747. * alignment purposes; we use 4 in front to keep the data well-aligned.
  100748. */
  100749. for(i = 0; ok && i < encoder->protected_->channels; i++) {
  100750. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize+4+OVERREAD_, &encoder->private_->integer_signal_unaligned[i], &encoder->private_->integer_signal[i]);
  100751. memset(encoder->private_->integer_signal[i], 0, sizeof(FLAC__int32)*4);
  100752. encoder->private_->integer_signal[i] += 4;
  100753. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100754. #if 0 /* @@@ currently unused */
  100755. if(encoder->protected_->max_lpc_order > 0)
  100756. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize+OVERREAD_, &encoder->private_->real_signal_unaligned[i], &encoder->private_->real_signal[i]);
  100757. #endif
  100758. #endif
  100759. }
  100760. for(i = 0; ok && i < 2; i++) {
  100761. 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]);
  100762. memset(encoder->private_->integer_signal_mid_side[i], 0, sizeof(FLAC__int32)*4);
  100763. encoder->private_->integer_signal_mid_side[i] += 4;
  100764. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100765. #if 0 /* @@@ currently unused */
  100766. if(encoder->protected_->max_lpc_order > 0)
  100767. 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]);
  100768. #endif
  100769. #endif
  100770. }
  100771. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100772. if(ok && encoder->protected_->max_lpc_order > 0) {
  100773. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++)
  100774. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->window_unaligned[i], &encoder->private_->window[i]);
  100775. ok = ok && FLAC__memory_alloc_aligned_real_array(new_blocksize, &encoder->private_->windowed_signal_unaligned, &encoder->private_->windowed_signal);
  100776. }
  100777. #endif
  100778. for(channel = 0; ok && channel < encoder->protected_->channels; channel++) {
  100779. for(i = 0; ok && i < 2; i++) {
  100780. ok = ok && FLAC__memory_alloc_aligned_int32_array(new_blocksize, &encoder->private_->residual_workspace_unaligned[channel][i], &encoder->private_->residual_workspace[channel][i]);
  100781. }
  100782. }
  100783. for(channel = 0; ok && channel < 2; channel++) {
  100784. for(i = 0; ok && i < 2; i++) {
  100785. 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]);
  100786. }
  100787. }
  100788. /* the *2 is an approximation to the series 1 + 1/2 + 1/4 + ... that sums tree occupies in a flat array */
  100789. /*@@@ 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) */
  100790. ok = ok && FLAC__memory_alloc_aligned_uint64_array(new_blocksize * 2, &encoder->private_->abs_residual_partition_sums_unaligned, &encoder->private_->abs_residual_partition_sums);
  100791. if(encoder->protected_->do_escape_coding)
  100792. ok = ok && FLAC__memory_alloc_aligned_unsigned_array(new_blocksize * 2, &encoder->private_->raw_bits_per_partition_unaligned, &encoder->private_->raw_bits_per_partition);
  100793. /* now adjust the windows if the blocksize has changed */
  100794. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  100795. if(ok && new_blocksize != encoder->private_->input_capacity && encoder->protected_->max_lpc_order > 0) {
  100796. for(i = 0; ok && i < encoder->protected_->num_apodizations; i++) {
  100797. switch(encoder->protected_->apodizations[i].type) {
  100798. case FLAC__APODIZATION_BARTLETT:
  100799. FLAC__window_bartlett(encoder->private_->window[i], new_blocksize);
  100800. break;
  100801. case FLAC__APODIZATION_BARTLETT_HANN:
  100802. FLAC__window_bartlett_hann(encoder->private_->window[i], new_blocksize);
  100803. break;
  100804. case FLAC__APODIZATION_BLACKMAN:
  100805. FLAC__window_blackman(encoder->private_->window[i], new_blocksize);
  100806. break;
  100807. case FLAC__APODIZATION_BLACKMAN_HARRIS_4TERM_92DB_SIDELOBE:
  100808. FLAC__window_blackman_harris_4term_92db_sidelobe(encoder->private_->window[i], new_blocksize);
  100809. break;
  100810. case FLAC__APODIZATION_CONNES:
  100811. FLAC__window_connes(encoder->private_->window[i], new_blocksize);
  100812. break;
  100813. case FLAC__APODIZATION_FLATTOP:
  100814. FLAC__window_flattop(encoder->private_->window[i], new_blocksize);
  100815. break;
  100816. case FLAC__APODIZATION_GAUSS:
  100817. FLAC__window_gauss(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.gauss.stddev);
  100818. break;
  100819. case FLAC__APODIZATION_HAMMING:
  100820. FLAC__window_hamming(encoder->private_->window[i], new_blocksize);
  100821. break;
  100822. case FLAC__APODIZATION_HANN:
  100823. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  100824. break;
  100825. case FLAC__APODIZATION_KAISER_BESSEL:
  100826. FLAC__window_kaiser_bessel(encoder->private_->window[i], new_blocksize);
  100827. break;
  100828. case FLAC__APODIZATION_NUTTALL:
  100829. FLAC__window_nuttall(encoder->private_->window[i], new_blocksize);
  100830. break;
  100831. case FLAC__APODIZATION_RECTANGLE:
  100832. FLAC__window_rectangle(encoder->private_->window[i], new_blocksize);
  100833. break;
  100834. case FLAC__APODIZATION_TRIANGLE:
  100835. FLAC__window_triangle(encoder->private_->window[i], new_blocksize);
  100836. break;
  100837. case FLAC__APODIZATION_TUKEY:
  100838. FLAC__window_tukey(encoder->private_->window[i], new_blocksize, encoder->protected_->apodizations[i].parameters.tukey.p);
  100839. break;
  100840. case FLAC__APODIZATION_WELCH:
  100841. FLAC__window_welch(encoder->private_->window[i], new_blocksize);
  100842. break;
  100843. default:
  100844. FLAC__ASSERT(0);
  100845. /* double protection */
  100846. FLAC__window_hann(encoder->private_->window[i], new_blocksize);
  100847. break;
  100848. }
  100849. }
  100850. }
  100851. #endif
  100852. if(ok)
  100853. encoder->private_->input_capacity = new_blocksize;
  100854. else
  100855. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100856. return ok;
  100857. }
  100858. FLAC__bool write_bitbuffer_(FLAC__StreamEncoder *encoder, unsigned samples, FLAC__bool is_last_block)
  100859. {
  100860. const FLAC__byte *buffer;
  100861. size_t bytes;
  100862. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  100863. if(!FLAC__bitwriter_get_buffer(encoder->private_->frame, &buffer, &bytes)) {
  100864. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  100865. return false;
  100866. }
  100867. if(encoder->protected_->verify) {
  100868. encoder->private_->verify.output.data = buffer;
  100869. encoder->private_->verify.output.bytes = bytes;
  100870. if(encoder->private_->verify.state_hint == ENCODER_IN_MAGIC) {
  100871. encoder->private_->verify.needs_magic_hack = true;
  100872. }
  100873. else {
  100874. if(!FLAC__stream_decoder_process_single(encoder->private_->verify.decoder)) {
  100875. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100876. FLAC__bitwriter_clear(encoder->private_->frame);
  100877. if(encoder->protected_->state != FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA)
  100878. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  100879. return false;
  100880. }
  100881. }
  100882. }
  100883. if(write_frame_(encoder, buffer, bytes, samples, is_last_block) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100884. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100885. FLAC__bitwriter_clear(encoder->private_->frame);
  100886. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100887. return false;
  100888. }
  100889. FLAC__bitwriter_release_buffer(encoder->private_->frame);
  100890. FLAC__bitwriter_clear(encoder->private_->frame);
  100891. if(samples > 0) {
  100892. encoder->private_->streaminfo.data.stream_info.min_framesize = min(bytes, encoder->private_->streaminfo.data.stream_info.min_framesize);
  100893. encoder->private_->streaminfo.data.stream_info.max_framesize = max(bytes, encoder->private_->streaminfo.data.stream_info.max_framesize);
  100894. }
  100895. return true;
  100896. }
  100897. FLAC__StreamEncoderWriteStatus write_frame_(FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, FLAC__bool is_last_block)
  100898. {
  100899. FLAC__StreamEncoderWriteStatus status;
  100900. FLAC__uint64 output_position = 0;
  100901. /* FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED just means we didn't get the offset; no error */
  100902. if(encoder->private_->tell_callback && encoder->private_->tell_callback(encoder, &output_position, encoder->private_->client_data) == FLAC__STREAM_ENCODER_TELL_STATUS_ERROR) {
  100903. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100904. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  100905. }
  100906. /*
  100907. * Watch for the STREAMINFO block and first SEEKTABLE block to go by and store their offsets.
  100908. */
  100909. if(samples == 0) {
  100910. FLAC__MetadataType type = (FLAC__MetadataType) (buffer[0] & 0x7f);
  100911. if(type == FLAC__METADATA_TYPE_STREAMINFO)
  100912. encoder->protected_->streaminfo_offset = output_position;
  100913. else if(type == FLAC__METADATA_TYPE_SEEKTABLE && encoder->protected_->seektable_offset == 0)
  100914. encoder->protected_->seektable_offset = output_position;
  100915. }
  100916. /*
  100917. * Mark the current seek point if hit (if audio_offset == 0 that
  100918. * means we're still writing metadata and haven't hit the first
  100919. * frame yet)
  100920. */
  100921. if(0 != encoder->private_->seek_table && encoder->protected_->audio_offset > 0 && encoder->private_->seek_table->num_points > 0) {
  100922. const unsigned blocksize = FLAC__stream_encoder_get_blocksize(encoder);
  100923. const FLAC__uint64 frame_first_sample = encoder->private_->samples_written;
  100924. const FLAC__uint64 frame_last_sample = frame_first_sample + (FLAC__uint64)blocksize - 1;
  100925. FLAC__uint64 test_sample;
  100926. unsigned i;
  100927. for(i = encoder->private_->first_seekpoint_to_check; i < encoder->private_->seek_table->num_points; i++) {
  100928. test_sample = encoder->private_->seek_table->points[i].sample_number;
  100929. if(test_sample > frame_last_sample) {
  100930. break;
  100931. }
  100932. else if(test_sample >= frame_first_sample) {
  100933. encoder->private_->seek_table->points[i].sample_number = frame_first_sample;
  100934. encoder->private_->seek_table->points[i].stream_offset = output_position - encoder->protected_->audio_offset;
  100935. encoder->private_->seek_table->points[i].frame_samples = blocksize;
  100936. encoder->private_->first_seekpoint_to_check++;
  100937. /* DO NOT: "break;" and here's why:
  100938. * The seektable template may contain more than one target
  100939. * sample for any given frame; we will keep looping, generating
  100940. * duplicate seekpoints for them, and we'll clean it up later,
  100941. * just before writing the seektable back to the metadata.
  100942. */
  100943. }
  100944. else {
  100945. encoder->private_->first_seekpoint_to_check++;
  100946. }
  100947. }
  100948. }
  100949. #if FLAC__HAS_OGG
  100950. if(encoder->private_->is_ogg) {
  100951. status = FLAC__ogg_encoder_aspect_write_callback_wrapper(
  100952. &encoder->protected_->ogg_encoder_aspect,
  100953. buffer,
  100954. bytes,
  100955. samples,
  100956. encoder->private_->current_frame_number,
  100957. is_last_block,
  100958. (FLAC__OggEncoderAspectWriteCallbackProxy)encoder->private_->write_callback,
  100959. encoder,
  100960. encoder->private_->client_data
  100961. );
  100962. }
  100963. else
  100964. #endif
  100965. status = encoder->private_->write_callback(encoder, buffer, bytes, samples, encoder->private_->current_frame_number, encoder->private_->client_data);
  100966. if(status == FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  100967. encoder->private_->bytes_written += bytes;
  100968. encoder->private_->samples_written += samples;
  100969. /* we keep a high watermark on the number of frames written because
  100970. * when the encoder goes back to write metadata, 'current_frame'
  100971. * will drop back to 0.
  100972. */
  100973. encoder->private_->frames_written = max(encoder->private_->frames_written, encoder->private_->current_frame_number+1);
  100974. }
  100975. else
  100976. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  100977. return status;
  100978. }
  100979. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  100980. void update_metadata_(const FLAC__StreamEncoder *encoder)
  100981. {
  100982. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  100983. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  100984. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  100985. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  100986. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  100987. const unsigned bps = metadata->data.stream_info.bits_per_sample;
  100988. FLAC__StreamEncoderSeekStatus seek_status;
  100989. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  100990. /* All this is based on intimate knowledge of the stream header
  100991. * layout, but a change to the header format that would break this
  100992. * would also break all streams encoded in the previous format.
  100993. */
  100994. /*
  100995. * Write MD5 signature
  100996. */
  100997. {
  100998. const unsigned md5_offset =
  100999. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101000. (
  101001. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101002. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101003. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101004. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101005. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101006. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101007. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  101008. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  101009. ) / 8;
  101010. if((seek_status = encoder->private_->seek_callback(encoder, encoder->protected_->streaminfo_offset + md5_offset, encoder->private_->client_data)) != FLAC__STREAM_ENCODER_SEEK_STATUS_OK) {
  101011. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  101012. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101013. return;
  101014. }
  101015. if(encoder->private_->write_callback(encoder, metadata->data.stream_info.md5sum, 16, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101016. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101017. return;
  101018. }
  101019. }
  101020. /*
  101021. * Write total samples
  101022. */
  101023. {
  101024. const unsigned total_samples_byte_offset =
  101025. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101026. (
  101027. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101028. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101029. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101030. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101031. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101032. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101033. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  101034. - 4
  101035. ) / 8;
  101036. b[0] = ((FLAC__byte)(bps-1) << 4) | (FLAC__byte)((samples >> 32) & 0x0F);
  101037. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  101038. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  101039. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  101040. b[4] = (FLAC__byte)(samples & 0xFF);
  101041. 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) {
  101042. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  101043. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101044. return;
  101045. }
  101046. if(encoder->private_->write_callback(encoder, b, 5, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101047. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101048. return;
  101049. }
  101050. }
  101051. /*
  101052. * Write min/max framesize
  101053. */
  101054. {
  101055. const unsigned min_framesize_offset =
  101056. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101057. (
  101058. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101059. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  101060. ) / 8;
  101061. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  101062. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  101063. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  101064. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  101065. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  101066. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  101067. 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) {
  101068. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  101069. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101070. return;
  101071. }
  101072. if(encoder->private_->write_callback(encoder, b, 6, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101073. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101074. return;
  101075. }
  101076. }
  101077. /*
  101078. * Write seektable
  101079. */
  101080. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  101081. unsigned i;
  101082. FLAC__format_seektable_sort(encoder->private_->seek_table);
  101083. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  101084. 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) {
  101085. if(seek_status == FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR)
  101086. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101087. return;
  101088. }
  101089. for(i = 0; i < encoder->private_->seek_table->num_points; i++) {
  101090. FLAC__uint64 xx;
  101091. unsigned x;
  101092. xx = encoder->private_->seek_table->points[i].sample_number;
  101093. b[7] = (FLAC__byte)xx; xx >>= 8;
  101094. b[6] = (FLAC__byte)xx; xx >>= 8;
  101095. b[5] = (FLAC__byte)xx; xx >>= 8;
  101096. b[4] = (FLAC__byte)xx; xx >>= 8;
  101097. b[3] = (FLAC__byte)xx; xx >>= 8;
  101098. b[2] = (FLAC__byte)xx; xx >>= 8;
  101099. b[1] = (FLAC__byte)xx; xx >>= 8;
  101100. b[0] = (FLAC__byte)xx; xx >>= 8;
  101101. xx = encoder->private_->seek_table->points[i].stream_offset;
  101102. b[15] = (FLAC__byte)xx; xx >>= 8;
  101103. b[14] = (FLAC__byte)xx; xx >>= 8;
  101104. b[13] = (FLAC__byte)xx; xx >>= 8;
  101105. b[12] = (FLAC__byte)xx; xx >>= 8;
  101106. b[11] = (FLAC__byte)xx; xx >>= 8;
  101107. b[10] = (FLAC__byte)xx; xx >>= 8;
  101108. b[9] = (FLAC__byte)xx; xx >>= 8;
  101109. b[8] = (FLAC__byte)xx; xx >>= 8;
  101110. x = encoder->private_->seek_table->points[i].frame_samples;
  101111. b[17] = (FLAC__byte)x; x >>= 8;
  101112. b[16] = (FLAC__byte)x; x >>= 8;
  101113. if(encoder->private_->write_callback(encoder, b, 18, 0, 0, encoder->private_->client_data) != FLAC__STREAM_ENCODER_WRITE_STATUS_OK) {
  101114. encoder->protected_->state = FLAC__STREAM_ENCODER_CLIENT_ERROR;
  101115. return;
  101116. }
  101117. }
  101118. }
  101119. }
  101120. #if FLAC__HAS_OGG
  101121. /* Gets called when the encoding process has finished so that we can update the STREAMINFO and SEEKTABLE blocks. */
  101122. void update_ogg_metadata_(FLAC__StreamEncoder *encoder)
  101123. {
  101124. /* the # of bytes in the 1st packet that precede the STREAMINFO */
  101125. static const unsigned FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH =
  101126. FLAC__OGG_MAPPING_PACKET_TYPE_LENGTH +
  101127. FLAC__OGG_MAPPING_MAGIC_LENGTH +
  101128. FLAC__OGG_MAPPING_VERSION_MAJOR_LENGTH +
  101129. FLAC__OGG_MAPPING_VERSION_MINOR_LENGTH +
  101130. FLAC__OGG_MAPPING_NUM_HEADERS_LENGTH +
  101131. FLAC__STREAM_SYNC_LENGTH
  101132. ;
  101133. FLAC__byte b[max(6, FLAC__STREAM_METADATA_SEEKPOINT_LENGTH)];
  101134. const FLAC__StreamMetadata *metadata = &encoder->private_->streaminfo;
  101135. const FLAC__uint64 samples = metadata->data.stream_info.total_samples;
  101136. const unsigned min_framesize = metadata->data.stream_info.min_framesize;
  101137. const unsigned max_framesize = metadata->data.stream_info.max_framesize;
  101138. ogg_page page;
  101139. FLAC__ASSERT(metadata->type == FLAC__METADATA_TYPE_STREAMINFO);
  101140. FLAC__ASSERT(0 != encoder->private_->seek_callback);
  101141. /* Pre-check that client supports seeking, since we don't want the
  101142. * ogg_helper code to ever have to deal with this condition.
  101143. */
  101144. if(encoder->private_->seek_callback(encoder, 0, encoder->private_->client_data) == FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED)
  101145. return;
  101146. /* All this is based on intimate knowledge of the stream header
  101147. * layout, but a change to the header format that would break this
  101148. * would also break all streams encoded in the previous format.
  101149. */
  101150. /**
  101151. ** Write STREAMINFO stats
  101152. **/
  101153. simple_ogg_page__init(&page);
  101154. if(!simple_ogg_page__get_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  101155. simple_ogg_page__clear(&page);
  101156. return; /* state already set */
  101157. }
  101158. /*
  101159. * Write MD5 signature
  101160. */
  101161. {
  101162. const unsigned md5_offset =
  101163. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101164. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101165. (
  101166. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101167. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101168. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101169. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101170. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101171. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101172. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN +
  101173. FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN
  101174. ) / 8;
  101175. if(md5_offset + 16 > (unsigned)page.body_len) {
  101176. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101177. simple_ogg_page__clear(&page);
  101178. return;
  101179. }
  101180. memcpy(page.body + md5_offset, metadata->data.stream_info.md5sum, 16);
  101181. }
  101182. /*
  101183. * Write total samples
  101184. */
  101185. {
  101186. const unsigned total_samples_byte_offset =
  101187. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101188. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101189. (
  101190. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101191. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN +
  101192. FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN +
  101193. FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN +
  101194. FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN +
  101195. FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN +
  101196. FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN
  101197. - 4
  101198. ) / 8;
  101199. if(total_samples_byte_offset + 5 > (unsigned)page.body_len) {
  101200. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101201. simple_ogg_page__clear(&page);
  101202. return;
  101203. }
  101204. b[0] = (FLAC__byte)page.body[total_samples_byte_offset] & 0xF0;
  101205. b[0] |= (FLAC__byte)((samples >> 32) & 0x0F);
  101206. b[1] = (FLAC__byte)((samples >> 24) & 0xFF);
  101207. b[2] = (FLAC__byte)((samples >> 16) & 0xFF);
  101208. b[3] = (FLAC__byte)((samples >> 8) & 0xFF);
  101209. b[4] = (FLAC__byte)(samples & 0xFF);
  101210. memcpy(page.body + total_samples_byte_offset, b, 5);
  101211. }
  101212. /*
  101213. * Write min/max framesize
  101214. */
  101215. {
  101216. const unsigned min_framesize_offset =
  101217. FIRST_OGG_PACKET_STREAMINFO_PREFIX_LENGTH +
  101218. FLAC__STREAM_METADATA_HEADER_LENGTH +
  101219. (
  101220. FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN +
  101221. FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN
  101222. ) / 8;
  101223. if(min_framesize_offset + 6 > (unsigned)page.body_len) {
  101224. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101225. simple_ogg_page__clear(&page);
  101226. return;
  101227. }
  101228. b[0] = (FLAC__byte)((min_framesize >> 16) & 0xFF);
  101229. b[1] = (FLAC__byte)((min_framesize >> 8) & 0xFF);
  101230. b[2] = (FLAC__byte)(min_framesize & 0xFF);
  101231. b[3] = (FLAC__byte)((max_framesize >> 16) & 0xFF);
  101232. b[4] = (FLAC__byte)((max_framesize >> 8) & 0xFF);
  101233. b[5] = (FLAC__byte)(max_framesize & 0xFF);
  101234. memcpy(page.body + min_framesize_offset, b, 6);
  101235. }
  101236. if(!simple_ogg_page__set_at(encoder, encoder->protected_->streaminfo_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  101237. simple_ogg_page__clear(&page);
  101238. return; /* state already set */
  101239. }
  101240. simple_ogg_page__clear(&page);
  101241. /*
  101242. * Write seektable
  101243. */
  101244. if(0 != encoder->private_->seek_table && encoder->private_->seek_table->num_points > 0 && encoder->protected_->seektable_offset > 0) {
  101245. unsigned i;
  101246. FLAC__byte *p;
  101247. FLAC__format_seektable_sort(encoder->private_->seek_table);
  101248. FLAC__ASSERT(FLAC__format_seektable_is_legal(encoder->private_->seek_table));
  101249. simple_ogg_page__init(&page);
  101250. if(!simple_ogg_page__get_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->read_callback, encoder->private_->client_data)) {
  101251. simple_ogg_page__clear(&page);
  101252. return; /* state already set */
  101253. }
  101254. if((FLAC__STREAM_METADATA_HEADER_LENGTH + 18*encoder->private_->seek_table->num_points) != (unsigned)page.body_len) {
  101255. encoder->protected_->state = FLAC__STREAM_ENCODER_OGG_ERROR;
  101256. simple_ogg_page__clear(&page);
  101257. return;
  101258. }
  101259. for(i = 0, p = page.body + FLAC__STREAM_METADATA_HEADER_LENGTH; i < encoder->private_->seek_table->num_points; i++, p += 18) {
  101260. FLAC__uint64 xx;
  101261. unsigned x;
  101262. xx = encoder->private_->seek_table->points[i].sample_number;
  101263. b[7] = (FLAC__byte)xx; xx >>= 8;
  101264. b[6] = (FLAC__byte)xx; xx >>= 8;
  101265. b[5] = (FLAC__byte)xx; xx >>= 8;
  101266. b[4] = (FLAC__byte)xx; xx >>= 8;
  101267. b[3] = (FLAC__byte)xx; xx >>= 8;
  101268. b[2] = (FLAC__byte)xx; xx >>= 8;
  101269. b[1] = (FLAC__byte)xx; xx >>= 8;
  101270. b[0] = (FLAC__byte)xx; xx >>= 8;
  101271. xx = encoder->private_->seek_table->points[i].stream_offset;
  101272. b[15] = (FLAC__byte)xx; xx >>= 8;
  101273. b[14] = (FLAC__byte)xx; xx >>= 8;
  101274. b[13] = (FLAC__byte)xx; xx >>= 8;
  101275. b[12] = (FLAC__byte)xx; xx >>= 8;
  101276. b[11] = (FLAC__byte)xx; xx >>= 8;
  101277. b[10] = (FLAC__byte)xx; xx >>= 8;
  101278. b[9] = (FLAC__byte)xx; xx >>= 8;
  101279. b[8] = (FLAC__byte)xx; xx >>= 8;
  101280. x = encoder->private_->seek_table->points[i].frame_samples;
  101281. b[17] = (FLAC__byte)x; x >>= 8;
  101282. b[16] = (FLAC__byte)x; x >>= 8;
  101283. memcpy(p, b, 18);
  101284. }
  101285. if(!simple_ogg_page__set_at(encoder, encoder->protected_->seektable_offset, &page, encoder->private_->seek_callback, encoder->private_->write_callback, encoder->private_->client_data)) {
  101286. simple_ogg_page__clear(&page);
  101287. return; /* state already set */
  101288. }
  101289. simple_ogg_page__clear(&page);
  101290. }
  101291. }
  101292. #endif
  101293. FLAC__bool process_frame_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block, FLAC__bool is_last_block)
  101294. {
  101295. FLAC__uint16 crc;
  101296. FLAC__ASSERT(encoder->protected_->state == FLAC__STREAM_ENCODER_OK);
  101297. /*
  101298. * Accumulate raw signal to the MD5 signature
  101299. */
  101300. 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)) {
  101301. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101302. return false;
  101303. }
  101304. /*
  101305. * Process the frame header and subframes into the frame bitbuffer
  101306. */
  101307. if(!process_subframes_(encoder, is_fractional_block)) {
  101308. /* the above function sets the state for us in case of an error */
  101309. return false;
  101310. }
  101311. /*
  101312. * Zero-pad the frame to a byte_boundary
  101313. */
  101314. if(!FLAC__bitwriter_zero_pad_to_byte_boundary(encoder->private_->frame)) {
  101315. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101316. return false;
  101317. }
  101318. /*
  101319. * CRC-16 the whole thing
  101320. */
  101321. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(encoder->private_->frame));
  101322. if(
  101323. !FLAC__bitwriter_get_write_crc16(encoder->private_->frame, &crc) ||
  101324. !FLAC__bitwriter_write_raw_uint32(encoder->private_->frame, crc, FLAC__FRAME_FOOTER_CRC_LEN)
  101325. ) {
  101326. encoder->protected_->state = FLAC__STREAM_ENCODER_MEMORY_ALLOCATION_ERROR;
  101327. return false;
  101328. }
  101329. /*
  101330. * Write it
  101331. */
  101332. if(!write_bitbuffer_(encoder, encoder->protected_->blocksize, is_last_block)) {
  101333. /* the above function sets the state for us in case of an error */
  101334. return false;
  101335. }
  101336. /*
  101337. * Get ready for the next frame
  101338. */
  101339. encoder->private_->current_sample_number = 0;
  101340. encoder->private_->current_frame_number++;
  101341. encoder->private_->streaminfo.data.stream_info.total_samples += (FLAC__uint64)encoder->protected_->blocksize;
  101342. return true;
  101343. }
  101344. FLAC__bool process_subframes_(FLAC__StreamEncoder *encoder, FLAC__bool is_fractional_block)
  101345. {
  101346. FLAC__FrameHeader frame_header;
  101347. unsigned channel, min_partition_order = encoder->protected_->min_residual_partition_order, max_partition_order;
  101348. FLAC__bool do_independent, do_mid_side;
  101349. /*
  101350. * Calculate the min,max Rice partition orders
  101351. */
  101352. if(is_fractional_block) {
  101353. max_partition_order = 0;
  101354. }
  101355. else {
  101356. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize(encoder->protected_->blocksize);
  101357. max_partition_order = min(max_partition_order, encoder->protected_->max_residual_partition_order);
  101358. }
  101359. min_partition_order = min(min_partition_order, max_partition_order);
  101360. /*
  101361. * Setup the frame
  101362. */
  101363. frame_header.blocksize = encoder->protected_->blocksize;
  101364. frame_header.sample_rate = encoder->protected_->sample_rate;
  101365. frame_header.channels = encoder->protected_->channels;
  101366. frame_header.channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT; /* the default unless the encoder determines otherwise */
  101367. frame_header.bits_per_sample = encoder->protected_->bits_per_sample;
  101368. frame_header.number_type = FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER;
  101369. frame_header.number.frame_number = encoder->private_->current_frame_number;
  101370. /*
  101371. * Figure out what channel assignments to try
  101372. */
  101373. if(encoder->protected_->do_mid_side_stereo) {
  101374. if(encoder->protected_->loose_mid_side_stereo) {
  101375. if(encoder->private_->loose_mid_side_stereo_frame_count == 0) {
  101376. do_independent = true;
  101377. do_mid_side = true;
  101378. }
  101379. else {
  101380. do_independent = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT);
  101381. do_mid_side = !do_independent;
  101382. }
  101383. }
  101384. else {
  101385. do_independent = true;
  101386. do_mid_side = true;
  101387. }
  101388. }
  101389. else {
  101390. do_independent = true;
  101391. do_mid_side = false;
  101392. }
  101393. FLAC__ASSERT(do_independent || do_mid_side);
  101394. /*
  101395. * Check for wasted bits; set effective bps for each subframe
  101396. */
  101397. if(do_independent) {
  101398. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101399. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal[channel], encoder->protected_->blocksize);
  101400. encoder->private_->subframe_workspace[channel][0].wasted_bits = encoder->private_->subframe_workspace[channel][1].wasted_bits = w;
  101401. encoder->private_->subframe_bps[channel] = encoder->protected_->bits_per_sample - w;
  101402. }
  101403. }
  101404. if(do_mid_side) {
  101405. FLAC__ASSERT(encoder->protected_->channels == 2);
  101406. for(channel = 0; channel < 2; channel++) {
  101407. const unsigned w = get_wasted_bits_(encoder->private_->integer_signal_mid_side[channel], encoder->protected_->blocksize);
  101408. encoder->private_->subframe_workspace_mid_side[channel][0].wasted_bits = encoder->private_->subframe_workspace_mid_side[channel][1].wasted_bits = w;
  101409. encoder->private_->subframe_bps_mid_side[channel] = encoder->protected_->bits_per_sample - w + (channel==0? 0:1);
  101410. }
  101411. }
  101412. /*
  101413. * First do a normal encoding pass of each independent channel
  101414. */
  101415. if(do_independent) {
  101416. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101417. if(!
  101418. process_subframe_(
  101419. encoder,
  101420. min_partition_order,
  101421. max_partition_order,
  101422. &frame_header,
  101423. encoder->private_->subframe_bps[channel],
  101424. encoder->private_->integer_signal[channel],
  101425. encoder->private_->subframe_workspace_ptr[channel],
  101426. encoder->private_->partitioned_rice_contents_workspace_ptr[channel],
  101427. encoder->private_->residual_workspace[channel],
  101428. encoder->private_->best_subframe+channel,
  101429. encoder->private_->best_subframe_bits+channel
  101430. )
  101431. )
  101432. return false;
  101433. }
  101434. }
  101435. /*
  101436. * Now do mid and side channels if requested
  101437. */
  101438. if(do_mid_side) {
  101439. FLAC__ASSERT(encoder->protected_->channels == 2);
  101440. for(channel = 0; channel < 2; channel++) {
  101441. if(!
  101442. process_subframe_(
  101443. encoder,
  101444. min_partition_order,
  101445. max_partition_order,
  101446. &frame_header,
  101447. encoder->private_->subframe_bps_mid_side[channel],
  101448. encoder->private_->integer_signal_mid_side[channel],
  101449. encoder->private_->subframe_workspace_ptr_mid_side[channel],
  101450. encoder->private_->partitioned_rice_contents_workspace_ptr_mid_side[channel],
  101451. encoder->private_->residual_workspace_mid_side[channel],
  101452. encoder->private_->best_subframe_mid_side+channel,
  101453. encoder->private_->best_subframe_bits_mid_side+channel
  101454. )
  101455. )
  101456. return false;
  101457. }
  101458. }
  101459. /*
  101460. * Compose the frame bitbuffer
  101461. */
  101462. if(do_mid_side) {
  101463. unsigned left_bps = 0, right_bps = 0; /* initialized only to prevent superfluous compiler warning */
  101464. FLAC__Subframe *left_subframe = 0, *right_subframe = 0; /* initialized only to prevent superfluous compiler warning */
  101465. FLAC__ChannelAssignment channel_assignment;
  101466. FLAC__ASSERT(encoder->protected_->channels == 2);
  101467. if(encoder->protected_->loose_mid_side_stereo && encoder->private_->loose_mid_side_stereo_frame_count > 0) {
  101468. channel_assignment = (encoder->private_->last_channel_assignment == FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT? FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT : FLAC__CHANNEL_ASSIGNMENT_MID_SIDE);
  101469. }
  101470. else {
  101471. unsigned bits[4]; /* WATCHOUT - indexed by FLAC__ChannelAssignment */
  101472. unsigned min_bits;
  101473. int ca;
  101474. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT == 0);
  101475. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE == 1);
  101476. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE == 2);
  101477. FLAC__ASSERT(FLAC__CHANNEL_ASSIGNMENT_MID_SIDE == 3);
  101478. FLAC__ASSERT(do_independent && do_mid_side);
  101479. /* We have to figure out which channel assignent results in the smallest frame */
  101480. bits[FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits [1];
  101481. bits[FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE ] = encoder->private_->best_subframe_bits [0] + encoder->private_->best_subframe_bits_mid_side[1];
  101482. bits[FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE ] = encoder->private_->best_subframe_bits [1] + encoder->private_->best_subframe_bits_mid_side[1];
  101483. bits[FLAC__CHANNEL_ASSIGNMENT_MID_SIDE ] = encoder->private_->best_subframe_bits_mid_side[0] + encoder->private_->best_subframe_bits_mid_side[1];
  101484. channel_assignment = FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT;
  101485. min_bits = bits[channel_assignment];
  101486. for(ca = 1; ca <= 3; ca++) {
  101487. if(bits[ca] < min_bits) {
  101488. min_bits = bits[ca];
  101489. channel_assignment = (FLAC__ChannelAssignment)ca;
  101490. }
  101491. }
  101492. }
  101493. frame_header.channel_assignment = channel_assignment;
  101494. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  101495. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101496. return false;
  101497. }
  101498. switch(channel_assignment) {
  101499. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101500. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  101501. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  101502. break;
  101503. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101504. left_subframe = &encoder->private_->subframe_workspace [0][encoder->private_->best_subframe [0]];
  101505. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  101506. break;
  101507. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101508. left_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  101509. right_subframe = &encoder->private_->subframe_workspace [1][encoder->private_->best_subframe [1]];
  101510. break;
  101511. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101512. left_subframe = &encoder->private_->subframe_workspace_mid_side[0][encoder->private_->best_subframe_mid_side[0]];
  101513. right_subframe = &encoder->private_->subframe_workspace_mid_side[1][encoder->private_->best_subframe_mid_side[1]];
  101514. break;
  101515. default:
  101516. FLAC__ASSERT(0);
  101517. }
  101518. switch(channel_assignment) {
  101519. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  101520. left_bps = encoder->private_->subframe_bps [0];
  101521. right_bps = encoder->private_->subframe_bps [1];
  101522. break;
  101523. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  101524. left_bps = encoder->private_->subframe_bps [0];
  101525. right_bps = encoder->private_->subframe_bps_mid_side[1];
  101526. break;
  101527. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  101528. left_bps = encoder->private_->subframe_bps_mid_side[1];
  101529. right_bps = encoder->private_->subframe_bps [1];
  101530. break;
  101531. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  101532. left_bps = encoder->private_->subframe_bps_mid_side[0];
  101533. right_bps = encoder->private_->subframe_bps_mid_side[1];
  101534. break;
  101535. default:
  101536. FLAC__ASSERT(0);
  101537. }
  101538. /* note that encoder_add_subframe_ sets the state for us in case of an error */
  101539. if(!add_subframe_(encoder, frame_header.blocksize, left_bps , left_subframe , encoder->private_->frame))
  101540. return false;
  101541. if(!add_subframe_(encoder, frame_header.blocksize, right_bps, right_subframe, encoder->private_->frame))
  101542. return false;
  101543. }
  101544. else {
  101545. if(!FLAC__frame_add_header(&frame_header, encoder->private_->frame)) {
  101546. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101547. return false;
  101548. }
  101549. for(channel = 0; channel < encoder->protected_->channels; channel++) {
  101550. 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)) {
  101551. /* the above function sets the state for us in case of an error */
  101552. return false;
  101553. }
  101554. }
  101555. }
  101556. if(encoder->protected_->loose_mid_side_stereo) {
  101557. encoder->private_->loose_mid_side_stereo_frame_count++;
  101558. if(encoder->private_->loose_mid_side_stereo_frame_count >= encoder->private_->loose_mid_side_stereo_frames)
  101559. encoder->private_->loose_mid_side_stereo_frame_count = 0;
  101560. }
  101561. encoder->private_->last_channel_assignment = frame_header.channel_assignment;
  101562. return true;
  101563. }
  101564. FLAC__bool process_subframe_(
  101565. FLAC__StreamEncoder *encoder,
  101566. unsigned min_partition_order,
  101567. unsigned max_partition_order,
  101568. const FLAC__FrameHeader *frame_header,
  101569. unsigned subframe_bps,
  101570. const FLAC__int32 integer_signal[],
  101571. FLAC__Subframe *subframe[2],
  101572. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents[2],
  101573. FLAC__int32 *residual[2],
  101574. unsigned *best_subframe,
  101575. unsigned *best_bits
  101576. )
  101577. {
  101578. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101579. FLAC__float fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  101580. #else
  101581. FLAC__fixedpoint fixed_residual_bits_per_sample[FLAC__MAX_FIXED_ORDER+1];
  101582. #endif
  101583. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101584. FLAC__double lpc_residual_bits_per_sample;
  101585. 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 */
  101586. FLAC__double lpc_error[FLAC__MAX_LPC_ORDER];
  101587. unsigned min_lpc_order, max_lpc_order, lpc_order;
  101588. unsigned min_qlp_coeff_precision, max_qlp_coeff_precision, qlp_coeff_precision;
  101589. #endif
  101590. unsigned min_fixed_order, max_fixed_order, guess_fixed_order, fixed_order;
  101591. unsigned rice_parameter;
  101592. unsigned _candidate_bits, _best_bits;
  101593. unsigned _best_subframe;
  101594. /* only use RICE2 partitions if stream bps > 16 */
  101595. 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;
  101596. FLAC__ASSERT(frame_header->blocksize > 0);
  101597. /* verbatim subframe is the baseline against which we measure other compressed subframes */
  101598. _best_subframe = 0;
  101599. if(encoder->private_->disable_verbatim_subframes && frame_header->blocksize >= FLAC__MAX_FIXED_ORDER)
  101600. _best_bits = UINT_MAX;
  101601. else
  101602. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  101603. if(frame_header->blocksize >= FLAC__MAX_FIXED_ORDER) {
  101604. unsigned signal_is_constant = false;
  101605. 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);
  101606. /* check for constant subframe */
  101607. if(
  101608. !encoder->private_->disable_constant_subframes &&
  101609. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101610. fixed_residual_bits_per_sample[1] == 0.0
  101611. #else
  101612. fixed_residual_bits_per_sample[1] == FLAC__FP_ZERO
  101613. #endif
  101614. ) {
  101615. /* the above means it's possible all samples are the same value; now double-check it: */
  101616. unsigned i;
  101617. signal_is_constant = true;
  101618. for(i = 1; i < frame_header->blocksize; i++) {
  101619. if(integer_signal[0] != integer_signal[i]) {
  101620. signal_is_constant = false;
  101621. break;
  101622. }
  101623. }
  101624. }
  101625. if(signal_is_constant) {
  101626. _candidate_bits = evaluate_constant_subframe_(encoder, integer_signal[0], frame_header->blocksize, subframe_bps, subframe[!_best_subframe]);
  101627. if(_candidate_bits < _best_bits) {
  101628. _best_subframe = !_best_subframe;
  101629. _best_bits = _candidate_bits;
  101630. }
  101631. }
  101632. else {
  101633. if(!encoder->private_->disable_fixed_subframes || (encoder->protected_->max_lpc_order == 0 && _best_bits == UINT_MAX)) {
  101634. /* encode fixed */
  101635. if(encoder->protected_->do_exhaustive_model_search) {
  101636. min_fixed_order = 0;
  101637. max_fixed_order = FLAC__MAX_FIXED_ORDER;
  101638. }
  101639. else {
  101640. min_fixed_order = max_fixed_order = guess_fixed_order;
  101641. }
  101642. if(max_fixed_order >= frame_header->blocksize)
  101643. max_fixed_order = frame_header->blocksize - 1;
  101644. for(fixed_order = min_fixed_order; fixed_order <= max_fixed_order; fixed_order++) {
  101645. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101646. if(fixed_residual_bits_per_sample[fixed_order] >= (FLAC__float)subframe_bps)
  101647. continue; /* don't even try */
  101648. 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 */
  101649. #else
  101650. if(FLAC__fixedpoint_trunc(fixed_residual_bits_per_sample[fixed_order]) >= (int)subframe_bps)
  101651. continue; /* don't even try */
  101652. 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 */
  101653. #endif
  101654. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  101655. if(rice_parameter >= rice_parameter_limit) {
  101656. #ifdef DEBUG_VERBOSE
  101657. fprintf(stderr, "clipping rice_parameter (%u -> %u) @0\n", rice_parameter, rice_parameter_limit - 1);
  101658. #endif
  101659. rice_parameter = rice_parameter_limit - 1;
  101660. }
  101661. _candidate_bits =
  101662. evaluate_fixed_subframe_(
  101663. encoder,
  101664. integer_signal,
  101665. residual[!_best_subframe],
  101666. encoder->private_->abs_residual_partition_sums,
  101667. encoder->private_->raw_bits_per_partition,
  101668. frame_header->blocksize,
  101669. subframe_bps,
  101670. fixed_order,
  101671. rice_parameter,
  101672. rice_parameter_limit,
  101673. min_partition_order,
  101674. max_partition_order,
  101675. encoder->protected_->do_escape_coding,
  101676. encoder->protected_->rice_parameter_search_dist,
  101677. subframe[!_best_subframe],
  101678. partitioned_rice_contents[!_best_subframe]
  101679. );
  101680. if(_candidate_bits < _best_bits) {
  101681. _best_subframe = !_best_subframe;
  101682. _best_bits = _candidate_bits;
  101683. }
  101684. }
  101685. }
  101686. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101687. /* encode lpc */
  101688. if(encoder->protected_->max_lpc_order > 0) {
  101689. if(encoder->protected_->max_lpc_order >= frame_header->blocksize)
  101690. max_lpc_order = frame_header->blocksize-1;
  101691. else
  101692. max_lpc_order = encoder->protected_->max_lpc_order;
  101693. if(max_lpc_order > 0) {
  101694. unsigned a;
  101695. for (a = 0; a < encoder->protected_->num_apodizations; a++) {
  101696. FLAC__lpc_window_data(integer_signal, encoder->private_->window[a], encoder->private_->windowed_signal, frame_header->blocksize);
  101697. encoder->private_->local_lpc_compute_autocorrelation(encoder->private_->windowed_signal, frame_header->blocksize, max_lpc_order+1, autoc);
  101698. /* if autoc[0] == 0.0, the signal is constant and we usually won't get here, but it can happen */
  101699. if(autoc[0] != 0.0) {
  101700. FLAC__lpc_compute_lp_coefficients(autoc, &max_lpc_order, encoder->private_->lp_coeff, lpc_error);
  101701. if(encoder->protected_->do_exhaustive_model_search) {
  101702. min_lpc_order = 1;
  101703. }
  101704. else {
  101705. const unsigned guess_lpc_order =
  101706. FLAC__lpc_compute_best_order(
  101707. lpc_error,
  101708. max_lpc_order,
  101709. frame_header->blocksize,
  101710. subframe_bps + (
  101711. encoder->protected_->do_qlp_coeff_prec_search?
  101712. FLAC__MIN_QLP_COEFF_PRECISION : /* have to guess; use the min possible size to avoid accidentally favoring lower orders */
  101713. encoder->protected_->qlp_coeff_precision
  101714. )
  101715. );
  101716. min_lpc_order = max_lpc_order = guess_lpc_order;
  101717. }
  101718. if(max_lpc_order >= frame_header->blocksize)
  101719. max_lpc_order = frame_header->blocksize - 1;
  101720. for(lpc_order = min_lpc_order; lpc_order <= max_lpc_order; lpc_order++) {
  101721. lpc_residual_bits_per_sample = FLAC__lpc_compute_expected_bits_per_residual_sample(lpc_error[lpc_order-1], frame_header->blocksize-lpc_order);
  101722. if(lpc_residual_bits_per_sample >= (FLAC__double)subframe_bps)
  101723. continue; /* don't even try */
  101724. rice_parameter = (lpc_residual_bits_per_sample > 0.0)? (unsigned)(lpc_residual_bits_per_sample+0.5) : 0; /* 0.5 is for rounding */
  101725. rice_parameter++; /* to account for the signed->unsigned conversion during rice coding */
  101726. if(rice_parameter >= rice_parameter_limit) {
  101727. #ifdef DEBUG_VERBOSE
  101728. fprintf(stderr, "clipping rice_parameter (%u -> %u) @1\n", rice_parameter, rice_parameter_limit - 1);
  101729. #endif
  101730. rice_parameter = rice_parameter_limit - 1;
  101731. }
  101732. if(encoder->protected_->do_qlp_coeff_prec_search) {
  101733. min_qlp_coeff_precision = FLAC__MIN_QLP_COEFF_PRECISION;
  101734. /* try to ensure a 32-bit datapath throughout for 16bps(+1bps for side channel) or less */
  101735. if(subframe_bps <= 17) {
  101736. max_qlp_coeff_precision = min(32 - subframe_bps - lpc_order, FLAC__MAX_QLP_COEFF_PRECISION);
  101737. max_qlp_coeff_precision = max(max_qlp_coeff_precision, min_qlp_coeff_precision);
  101738. }
  101739. else
  101740. max_qlp_coeff_precision = FLAC__MAX_QLP_COEFF_PRECISION;
  101741. }
  101742. else {
  101743. min_qlp_coeff_precision = max_qlp_coeff_precision = encoder->protected_->qlp_coeff_precision;
  101744. }
  101745. for(qlp_coeff_precision = min_qlp_coeff_precision; qlp_coeff_precision <= max_qlp_coeff_precision; qlp_coeff_precision++) {
  101746. _candidate_bits =
  101747. evaluate_lpc_subframe_(
  101748. encoder,
  101749. integer_signal,
  101750. residual[!_best_subframe],
  101751. encoder->private_->abs_residual_partition_sums,
  101752. encoder->private_->raw_bits_per_partition,
  101753. encoder->private_->lp_coeff[lpc_order-1],
  101754. frame_header->blocksize,
  101755. subframe_bps,
  101756. lpc_order,
  101757. qlp_coeff_precision,
  101758. rice_parameter,
  101759. rice_parameter_limit,
  101760. min_partition_order,
  101761. max_partition_order,
  101762. encoder->protected_->do_escape_coding,
  101763. encoder->protected_->rice_parameter_search_dist,
  101764. subframe[!_best_subframe],
  101765. partitioned_rice_contents[!_best_subframe]
  101766. );
  101767. if(_candidate_bits > 0) { /* if == 0, there was a problem quantizing the lpcoeffs */
  101768. if(_candidate_bits < _best_bits) {
  101769. _best_subframe = !_best_subframe;
  101770. _best_bits = _candidate_bits;
  101771. }
  101772. }
  101773. }
  101774. }
  101775. }
  101776. }
  101777. }
  101778. }
  101779. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  101780. }
  101781. }
  101782. /* under rare circumstances this can happen when all but lpc subframe types are disabled: */
  101783. if(_best_bits == UINT_MAX) {
  101784. FLAC__ASSERT(_best_subframe == 0);
  101785. _best_bits = evaluate_verbatim_subframe_(encoder, integer_signal, frame_header->blocksize, subframe_bps, subframe[_best_subframe]);
  101786. }
  101787. *best_subframe = _best_subframe;
  101788. *best_bits = _best_bits;
  101789. return true;
  101790. }
  101791. FLAC__bool add_subframe_(
  101792. FLAC__StreamEncoder *encoder,
  101793. unsigned blocksize,
  101794. unsigned subframe_bps,
  101795. const FLAC__Subframe *subframe,
  101796. FLAC__BitWriter *frame
  101797. )
  101798. {
  101799. switch(subframe->type) {
  101800. case FLAC__SUBFRAME_TYPE_CONSTANT:
  101801. if(!FLAC__subframe_add_constant(&(subframe->data.constant), subframe_bps, subframe->wasted_bits, frame)) {
  101802. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101803. return false;
  101804. }
  101805. break;
  101806. case FLAC__SUBFRAME_TYPE_FIXED:
  101807. if(!FLAC__subframe_add_fixed(&(subframe->data.fixed), blocksize - subframe->data.fixed.order, subframe_bps, subframe->wasted_bits, frame)) {
  101808. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101809. return false;
  101810. }
  101811. break;
  101812. case FLAC__SUBFRAME_TYPE_LPC:
  101813. if(!FLAC__subframe_add_lpc(&(subframe->data.lpc), blocksize - subframe->data.lpc.order, subframe_bps, subframe->wasted_bits, frame)) {
  101814. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101815. return false;
  101816. }
  101817. break;
  101818. case FLAC__SUBFRAME_TYPE_VERBATIM:
  101819. if(!FLAC__subframe_add_verbatim(&(subframe->data.verbatim), blocksize, subframe_bps, subframe->wasted_bits, frame)) {
  101820. encoder->protected_->state = FLAC__STREAM_ENCODER_FRAMING_ERROR;
  101821. return false;
  101822. }
  101823. break;
  101824. default:
  101825. FLAC__ASSERT(0);
  101826. }
  101827. return true;
  101828. }
  101829. #define SPOTCHECK_ESTIMATE 0
  101830. #if SPOTCHECK_ESTIMATE
  101831. static void spotcheck_subframe_estimate_(
  101832. FLAC__StreamEncoder *encoder,
  101833. unsigned blocksize,
  101834. unsigned subframe_bps,
  101835. const FLAC__Subframe *subframe,
  101836. unsigned estimate
  101837. )
  101838. {
  101839. FLAC__bool ret;
  101840. FLAC__BitWriter *frame = FLAC__bitwriter_new();
  101841. if(frame == 0) {
  101842. fprintf(stderr, "EST: can't allocate frame\n");
  101843. return;
  101844. }
  101845. if(!FLAC__bitwriter_init(frame)) {
  101846. fprintf(stderr, "EST: can't init frame\n");
  101847. return;
  101848. }
  101849. ret = add_subframe_(encoder, blocksize, subframe_bps, subframe, frame);
  101850. FLAC__ASSERT(ret);
  101851. {
  101852. const unsigned actual = FLAC__bitwriter_get_input_bits_unconsumed(frame);
  101853. if(estimate != actual)
  101854. 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);
  101855. }
  101856. FLAC__bitwriter_delete(frame);
  101857. }
  101858. #endif
  101859. unsigned evaluate_constant_subframe_(
  101860. FLAC__StreamEncoder *encoder,
  101861. const FLAC__int32 signal,
  101862. unsigned blocksize,
  101863. unsigned subframe_bps,
  101864. FLAC__Subframe *subframe
  101865. )
  101866. {
  101867. unsigned estimate;
  101868. subframe->type = FLAC__SUBFRAME_TYPE_CONSTANT;
  101869. subframe->data.constant.value = signal;
  101870. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + subframe_bps;
  101871. #if SPOTCHECK_ESTIMATE
  101872. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101873. #else
  101874. (void)encoder, (void)blocksize;
  101875. #endif
  101876. return estimate;
  101877. }
  101878. unsigned evaluate_fixed_subframe_(
  101879. FLAC__StreamEncoder *encoder,
  101880. const FLAC__int32 signal[],
  101881. FLAC__int32 residual[],
  101882. FLAC__uint64 abs_residual_partition_sums[],
  101883. unsigned raw_bits_per_partition[],
  101884. unsigned blocksize,
  101885. unsigned subframe_bps,
  101886. unsigned order,
  101887. unsigned rice_parameter,
  101888. unsigned rice_parameter_limit,
  101889. unsigned min_partition_order,
  101890. unsigned max_partition_order,
  101891. FLAC__bool do_escape_coding,
  101892. unsigned rice_parameter_search_dist,
  101893. FLAC__Subframe *subframe,
  101894. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101895. )
  101896. {
  101897. unsigned i, residual_bits, estimate;
  101898. const unsigned residual_samples = blocksize - order;
  101899. FLAC__fixed_compute_residual(signal+order, residual_samples, order, residual);
  101900. subframe->type = FLAC__SUBFRAME_TYPE_FIXED;
  101901. subframe->data.fixed.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  101902. subframe->data.fixed.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  101903. subframe->data.fixed.residual = residual;
  101904. residual_bits =
  101905. find_best_partition_order_(
  101906. encoder->private_,
  101907. residual,
  101908. abs_residual_partition_sums,
  101909. raw_bits_per_partition,
  101910. residual_samples,
  101911. order,
  101912. rice_parameter,
  101913. rice_parameter_limit,
  101914. min_partition_order,
  101915. max_partition_order,
  101916. subframe_bps,
  101917. do_escape_coding,
  101918. rice_parameter_search_dist,
  101919. &subframe->data.fixed.entropy_coding_method
  101920. );
  101921. subframe->data.fixed.order = order;
  101922. for(i = 0; i < order; i++)
  101923. subframe->data.fixed.warmup[i] = signal[i];
  101924. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (order * subframe_bps) + residual_bits;
  101925. #if SPOTCHECK_ESTIMATE
  101926. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  101927. #endif
  101928. return estimate;
  101929. }
  101930. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  101931. unsigned evaluate_lpc_subframe_(
  101932. FLAC__StreamEncoder *encoder,
  101933. const FLAC__int32 signal[],
  101934. FLAC__int32 residual[],
  101935. FLAC__uint64 abs_residual_partition_sums[],
  101936. unsigned raw_bits_per_partition[],
  101937. const FLAC__real lp_coeff[],
  101938. unsigned blocksize,
  101939. unsigned subframe_bps,
  101940. unsigned order,
  101941. unsigned qlp_coeff_precision,
  101942. unsigned rice_parameter,
  101943. unsigned rice_parameter_limit,
  101944. unsigned min_partition_order,
  101945. unsigned max_partition_order,
  101946. FLAC__bool do_escape_coding,
  101947. unsigned rice_parameter_search_dist,
  101948. FLAC__Subframe *subframe,
  101949. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents
  101950. )
  101951. {
  101952. FLAC__int32 qlp_coeff[FLAC__MAX_LPC_ORDER];
  101953. unsigned i, residual_bits, estimate;
  101954. int quantization, ret;
  101955. const unsigned residual_samples = blocksize - order;
  101956. /* try to keep qlp coeff precision such that only 32-bit math is required for decode of <=16bps streams */
  101957. if(subframe_bps <= 16) {
  101958. FLAC__ASSERT(order > 0);
  101959. FLAC__ASSERT(order <= FLAC__MAX_LPC_ORDER);
  101960. qlp_coeff_precision = min(qlp_coeff_precision, 32 - subframe_bps - FLAC__bitmath_ilog2(order));
  101961. }
  101962. ret = FLAC__lpc_quantize_coefficients(lp_coeff, order, qlp_coeff_precision, qlp_coeff, &quantization);
  101963. if(ret != 0)
  101964. return 0; /* this is a hack to indicate to the caller that we can't do lp at this order on this subframe */
  101965. if(subframe_bps + qlp_coeff_precision + FLAC__bitmath_ilog2(order) <= 32)
  101966. if(subframe_bps <= 16 && qlp_coeff_precision <= 16)
  101967. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_16bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101968. else
  101969. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101970. else
  101971. encoder->private_->local_lpc_compute_residual_from_qlp_coefficients_64bit(signal+order, residual_samples, qlp_coeff, order, quantization, residual);
  101972. subframe->type = FLAC__SUBFRAME_TYPE_LPC;
  101973. subframe->data.lpc.entropy_coding_method.type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE;
  101974. subframe->data.lpc.entropy_coding_method.data.partitioned_rice.contents = partitioned_rice_contents;
  101975. subframe->data.lpc.residual = residual;
  101976. residual_bits =
  101977. find_best_partition_order_(
  101978. encoder->private_,
  101979. residual,
  101980. abs_residual_partition_sums,
  101981. raw_bits_per_partition,
  101982. residual_samples,
  101983. order,
  101984. rice_parameter,
  101985. rice_parameter_limit,
  101986. min_partition_order,
  101987. max_partition_order,
  101988. subframe_bps,
  101989. do_escape_coding,
  101990. rice_parameter_search_dist,
  101991. &subframe->data.lpc.entropy_coding_method
  101992. );
  101993. subframe->data.lpc.order = order;
  101994. subframe->data.lpc.qlp_coeff_precision = qlp_coeff_precision;
  101995. subframe->data.lpc.quantization_level = quantization;
  101996. memcpy(subframe->data.lpc.qlp_coeff, qlp_coeff, sizeof(FLAC__int32)*FLAC__MAX_LPC_ORDER);
  101997. for(i = 0; i < order; i++)
  101998. subframe->data.lpc.warmup[i] = signal[i];
  101999. 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;
  102000. #if SPOTCHECK_ESTIMATE
  102001. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  102002. #endif
  102003. return estimate;
  102004. }
  102005. #endif
  102006. unsigned evaluate_verbatim_subframe_(
  102007. FLAC__StreamEncoder *encoder,
  102008. const FLAC__int32 signal[],
  102009. unsigned blocksize,
  102010. unsigned subframe_bps,
  102011. FLAC__Subframe *subframe
  102012. )
  102013. {
  102014. unsigned estimate;
  102015. subframe->type = FLAC__SUBFRAME_TYPE_VERBATIM;
  102016. subframe->data.verbatim.data = signal;
  102017. estimate = FLAC__SUBFRAME_ZERO_PAD_LEN + FLAC__SUBFRAME_TYPE_LEN + FLAC__SUBFRAME_WASTED_BITS_FLAG_LEN + subframe->wasted_bits + (blocksize * subframe_bps);
  102018. #if SPOTCHECK_ESTIMATE
  102019. spotcheck_subframe_estimate_(encoder, blocksize, subframe_bps, subframe, estimate);
  102020. #else
  102021. (void)encoder;
  102022. #endif
  102023. return estimate;
  102024. }
  102025. unsigned find_best_partition_order_(
  102026. FLAC__StreamEncoderPrivate *private_,
  102027. const FLAC__int32 residual[],
  102028. FLAC__uint64 abs_residual_partition_sums[],
  102029. unsigned raw_bits_per_partition[],
  102030. unsigned residual_samples,
  102031. unsigned predictor_order,
  102032. unsigned rice_parameter,
  102033. unsigned rice_parameter_limit,
  102034. unsigned min_partition_order,
  102035. unsigned max_partition_order,
  102036. unsigned bps,
  102037. FLAC__bool do_escape_coding,
  102038. unsigned rice_parameter_search_dist,
  102039. FLAC__EntropyCodingMethod *best_ecm
  102040. )
  102041. {
  102042. unsigned residual_bits, best_residual_bits = 0;
  102043. unsigned best_parameters_index = 0;
  102044. unsigned best_partition_order = 0;
  102045. const unsigned blocksize = residual_samples + predictor_order;
  102046. max_partition_order = FLAC__format_get_max_rice_partition_order_from_blocksize_limited_max_and_predictor_order(max_partition_order, blocksize, predictor_order);
  102047. min_partition_order = min(min_partition_order, max_partition_order);
  102048. precompute_partition_info_sums_(residual, abs_residual_partition_sums, residual_samples, predictor_order, min_partition_order, max_partition_order, bps);
  102049. if(do_escape_coding)
  102050. precompute_partition_info_escapes_(residual, raw_bits_per_partition, residual_samples, predictor_order, min_partition_order, max_partition_order);
  102051. {
  102052. int partition_order;
  102053. unsigned sum;
  102054. for(partition_order = (int)max_partition_order, sum = 0; partition_order >= (int)min_partition_order; partition_order--) {
  102055. if(!
  102056. set_partitioned_rice_(
  102057. #ifdef EXACT_RICE_BITS_CALCULATION
  102058. residual,
  102059. #endif
  102060. abs_residual_partition_sums+sum,
  102061. raw_bits_per_partition+sum,
  102062. residual_samples,
  102063. predictor_order,
  102064. rice_parameter,
  102065. rice_parameter_limit,
  102066. rice_parameter_search_dist,
  102067. (unsigned)partition_order,
  102068. do_escape_coding,
  102069. &private_->partitioned_rice_contents_extra[!best_parameters_index],
  102070. &residual_bits
  102071. )
  102072. )
  102073. {
  102074. FLAC__ASSERT(best_residual_bits != 0);
  102075. break;
  102076. }
  102077. sum += 1u << partition_order;
  102078. if(best_residual_bits == 0 || residual_bits < best_residual_bits) {
  102079. best_residual_bits = residual_bits;
  102080. best_parameters_index = !best_parameters_index;
  102081. best_partition_order = partition_order;
  102082. }
  102083. }
  102084. }
  102085. best_ecm->data.partitioned_rice.order = best_partition_order;
  102086. {
  102087. /*
  102088. * We are allowed to de-const the pointer based on our special
  102089. * knowledge; it is const to the outside world.
  102090. */
  102091. FLAC__EntropyCodingMethod_PartitionedRiceContents* prc = (FLAC__EntropyCodingMethod_PartitionedRiceContents*)best_ecm->data.partitioned_rice.contents;
  102092. unsigned partition;
  102093. /* save best parameters and raw_bits */
  102094. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(prc, max(6, best_partition_order));
  102095. memcpy(prc->parameters, private_->partitioned_rice_contents_extra[best_parameters_index].parameters, sizeof(unsigned)*(1<<(best_partition_order)));
  102096. if(do_escape_coding)
  102097. memcpy(prc->raw_bits, private_->partitioned_rice_contents_extra[best_parameters_index].raw_bits, sizeof(unsigned)*(1<<(best_partition_order)));
  102098. /*
  102099. * Now need to check if the type should be changed to
  102100. * FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2 based on the
  102101. * size of the rice parameters.
  102102. */
  102103. for(partition = 0; partition < (1u<<best_partition_order); partition++) {
  102104. if(prc->parameters[partition] >= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER) {
  102105. best_ecm->type = FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2;
  102106. break;
  102107. }
  102108. }
  102109. }
  102110. return best_residual_bits;
  102111. }
  102112. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  102113. extern void precompute_partition_info_sums_32bit_asm_ia32_(
  102114. const FLAC__int32 residual[],
  102115. FLAC__uint64 abs_residual_partition_sums[],
  102116. unsigned blocksize,
  102117. unsigned predictor_order,
  102118. unsigned min_partition_order,
  102119. unsigned max_partition_order
  102120. );
  102121. #endif
  102122. void precompute_partition_info_sums_(
  102123. const FLAC__int32 residual[],
  102124. FLAC__uint64 abs_residual_partition_sums[],
  102125. unsigned residual_samples,
  102126. unsigned predictor_order,
  102127. unsigned min_partition_order,
  102128. unsigned max_partition_order,
  102129. unsigned bps
  102130. )
  102131. {
  102132. const unsigned default_partition_samples = (residual_samples + predictor_order) >> max_partition_order;
  102133. unsigned partitions = 1u << max_partition_order;
  102134. FLAC__ASSERT(default_partition_samples > predictor_order);
  102135. #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
  102136. /* slightly pessimistic but still catches all common cases */
  102137. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  102138. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  102139. precompute_partition_info_sums_32bit_asm_ia32_(residual, abs_residual_partition_sums, residual_samples + predictor_order, predictor_order, min_partition_order, max_partition_order);
  102140. return;
  102141. }
  102142. #endif
  102143. /* first do max_partition_order */
  102144. {
  102145. unsigned partition, residual_sample, end = (unsigned)(-(int)predictor_order);
  102146. /* slightly pessimistic but still catches all common cases */
  102147. /* WATCHOUT: "+ bps" is an assumption that the average residual magnitude will not be more than "bps" bits */
  102148. if(FLAC__bitmath_ilog2(default_partition_samples) + bps < 32) {
  102149. FLAC__uint32 abs_residual_partition_sum;
  102150. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102151. end += default_partition_samples;
  102152. abs_residual_partition_sum = 0;
  102153. for( ; residual_sample < end; residual_sample++)
  102154. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  102155. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  102156. }
  102157. }
  102158. else { /* have to pessimistically use 64 bits for accumulator */
  102159. FLAC__uint64 abs_residual_partition_sum;
  102160. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102161. end += default_partition_samples;
  102162. abs_residual_partition_sum = 0;
  102163. for( ; residual_sample < end; residual_sample++)
  102164. abs_residual_partition_sum += abs(residual[residual_sample]); /* abs(INT_MIN) is undefined, but if the residual is INT_MIN we have bigger problems */
  102165. abs_residual_partition_sums[partition] = abs_residual_partition_sum;
  102166. }
  102167. }
  102168. }
  102169. /* now merge partitions for lower orders */
  102170. {
  102171. unsigned from_partition = 0, to_partition = partitions;
  102172. int partition_order;
  102173. for(partition_order = (int)max_partition_order - 1; partition_order >= (int)min_partition_order; partition_order--) {
  102174. unsigned i;
  102175. partitions >>= 1;
  102176. for(i = 0; i < partitions; i++) {
  102177. abs_residual_partition_sums[to_partition++] =
  102178. abs_residual_partition_sums[from_partition ] +
  102179. abs_residual_partition_sums[from_partition+1];
  102180. from_partition += 2;
  102181. }
  102182. }
  102183. }
  102184. }
  102185. void precompute_partition_info_escapes_(
  102186. const FLAC__int32 residual[],
  102187. unsigned raw_bits_per_partition[],
  102188. unsigned residual_samples,
  102189. unsigned predictor_order,
  102190. unsigned min_partition_order,
  102191. unsigned max_partition_order
  102192. )
  102193. {
  102194. int partition_order;
  102195. unsigned from_partition, to_partition = 0;
  102196. const unsigned blocksize = residual_samples + predictor_order;
  102197. /* first do max_partition_order */
  102198. for(partition_order = (int)max_partition_order; partition_order >= 0; partition_order--) {
  102199. FLAC__int32 r;
  102200. FLAC__uint32 rmax;
  102201. unsigned partition, partition_sample, partition_samples, residual_sample;
  102202. const unsigned partitions = 1u << partition_order;
  102203. const unsigned default_partition_samples = blocksize >> partition_order;
  102204. FLAC__ASSERT(default_partition_samples > predictor_order);
  102205. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102206. partition_samples = default_partition_samples;
  102207. if(partition == 0)
  102208. partition_samples -= predictor_order;
  102209. rmax = 0;
  102210. for(partition_sample = 0; partition_sample < partition_samples; partition_sample++) {
  102211. r = residual[residual_sample++];
  102212. /* OPT: maybe faster: rmax |= r ^ (r>>31) */
  102213. if(r < 0)
  102214. rmax |= ~r;
  102215. else
  102216. rmax |= r;
  102217. }
  102218. /* now we know all residual values are in the range [-rmax-1,rmax] */
  102219. raw_bits_per_partition[partition] = rmax? FLAC__bitmath_ilog2(rmax) + 2 : 1;
  102220. }
  102221. to_partition = partitions;
  102222. break; /*@@@ yuck, should remove the 'for' loop instead */
  102223. }
  102224. /* now merge partitions for lower orders */
  102225. for(from_partition = 0, --partition_order; partition_order >= (int)min_partition_order; partition_order--) {
  102226. unsigned m;
  102227. unsigned i;
  102228. const unsigned partitions = 1u << partition_order;
  102229. for(i = 0; i < partitions; i++) {
  102230. m = raw_bits_per_partition[from_partition];
  102231. from_partition++;
  102232. raw_bits_per_partition[to_partition] = max(m, raw_bits_per_partition[from_partition]);
  102233. from_partition++;
  102234. to_partition++;
  102235. }
  102236. }
  102237. }
  102238. #ifdef EXACT_RICE_BITS_CALCULATION
  102239. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  102240. const unsigned rice_parameter,
  102241. const unsigned partition_samples,
  102242. const FLAC__int32 *residual
  102243. )
  102244. {
  102245. unsigned i, partition_bits =
  102246. 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 */
  102247. (1+rice_parameter) * partition_samples /* 1 for unary stop bit + rice_parameter for the binary portion */
  102248. ;
  102249. for(i = 0; i < partition_samples; i++)
  102250. partition_bits += ( (FLAC__uint32)((residual[i]<<1)^(residual[i]>>31)) >> rice_parameter );
  102251. return partition_bits;
  102252. }
  102253. #else
  102254. static FLaC__INLINE unsigned count_rice_bits_in_partition_(
  102255. const unsigned rice_parameter,
  102256. const unsigned partition_samples,
  102257. const FLAC__uint64 abs_residual_partition_sum
  102258. )
  102259. {
  102260. return
  102261. 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 */
  102262. (1+rice_parameter) * partition_samples + /* 1 for unary stop bit + rice_parameter for the binary portion */
  102263. (
  102264. rice_parameter?
  102265. (unsigned)(abs_residual_partition_sum >> (rice_parameter-1)) /* rice_parameter-1 because the real coder sign-folds instead of using a sign bit */
  102266. : (unsigned)(abs_residual_partition_sum << 1) /* can't shift by negative number, so reverse */
  102267. )
  102268. - (partition_samples >> 1)
  102269. /* -(partition_samples>>1) to subtract out extra contributions to the abs_residual_partition_sum.
  102270. * The actual number of bits used is closer to the sum(for all i in the partition) of abs(residual[i])>>(rice_parameter-1)
  102271. * By using the abs_residual_partition sum, we also add in bits in the LSBs that would normally be shifted out.
  102272. * So the subtraction term tries to guess how many extra bits were contributed.
  102273. * If the LSBs are randomly distributed, this should average to 0.5 extra bits per sample.
  102274. */
  102275. ;
  102276. }
  102277. #endif
  102278. FLAC__bool set_partitioned_rice_(
  102279. #ifdef EXACT_RICE_BITS_CALCULATION
  102280. const FLAC__int32 residual[],
  102281. #endif
  102282. const FLAC__uint64 abs_residual_partition_sums[],
  102283. const unsigned raw_bits_per_partition[],
  102284. const unsigned residual_samples,
  102285. const unsigned predictor_order,
  102286. const unsigned suggested_rice_parameter,
  102287. const unsigned rice_parameter_limit,
  102288. const unsigned rice_parameter_search_dist,
  102289. const unsigned partition_order,
  102290. const FLAC__bool search_for_escapes,
  102291. FLAC__EntropyCodingMethod_PartitionedRiceContents *partitioned_rice_contents,
  102292. unsigned *bits
  102293. )
  102294. {
  102295. unsigned rice_parameter, partition_bits;
  102296. unsigned best_partition_bits, best_rice_parameter = 0;
  102297. unsigned bits_ = FLAC__ENTROPY_CODING_METHOD_TYPE_LEN + FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN;
  102298. unsigned *parameters, *raw_bits;
  102299. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102300. unsigned min_rice_parameter, max_rice_parameter;
  102301. #else
  102302. (void)rice_parameter_search_dist;
  102303. #endif
  102304. FLAC__ASSERT(suggested_rice_parameter < FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  102305. FLAC__ASSERT(rice_parameter_limit <= FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER);
  102306. FLAC__format_entropy_coding_method_partitioned_rice_contents_ensure_size(partitioned_rice_contents, max(6, partition_order));
  102307. parameters = partitioned_rice_contents->parameters;
  102308. raw_bits = partitioned_rice_contents->raw_bits;
  102309. if(partition_order == 0) {
  102310. best_partition_bits = (unsigned)(-1);
  102311. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102312. if(rice_parameter_search_dist) {
  102313. if(suggested_rice_parameter < rice_parameter_search_dist)
  102314. min_rice_parameter = 0;
  102315. else
  102316. min_rice_parameter = suggested_rice_parameter - rice_parameter_search_dist;
  102317. max_rice_parameter = suggested_rice_parameter + rice_parameter_search_dist;
  102318. if(max_rice_parameter >= rice_parameter_limit) {
  102319. #ifdef DEBUG_VERBOSE
  102320. fprintf(stderr, "clipping rice_parameter (%u -> %u) @5\n", max_rice_parameter, rice_parameter_limit - 1);
  102321. #endif
  102322. max_rice_parameter = rice_parameter_limit - 1;
  102323. }
  102324. }
  102325. else
  102326. min_rice_parameter = max_rice_parameter = suggested_rice_parameter;
  102327. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  102328. #else
  102329. rice_parameter = suggested_rice_parameter;
  102330. #endif
  102331. #ifdef EXACT_RICE_BITS_CALCULATION
  102332. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, residual);
  102333. #else
  102334. partition_bits = count_rice_bits_in_partition_(rice_parameter, residual_samples, abs_residual_partition_sums[0]);
  102335. #endif
  102336. if(partition_bits < best_partition_bits) {
  102337. best_rice_parameter = rice_parameter;
  102338. best_partition_bits = partition_bits;
  102339. }
  102340. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102341. }
  102342. #endif
  102343. if(search_for_escapes) {
  102344. 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;
  102345. if(partition_bits <= best_partition_bits) {
  102346. raw_bits[0] = raw_bits_per_partition[0];
  102347. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  102348. best_partition_bits = partition_bits;
  102349. }
  102350. else
  102351. raw_bits[0] = 0;
  102352. }
  102353. parameters[0] = best_rice_parameter;
  102354. bits_ += best_partition_bits;
  102355. }
  102356. else {
  102357. unsigned partition, residual_sample;
  102358. unsigned partition_samples;
  102359. FLAC__uint64 mean, k;
  102360. const unsigned partitions = 1u << partition_order;
  102361. for(partition = residual_sample = 0; partition < partitions; partition++) {
  102362. partition_samples = (residual_samples+predictor_order) >> partition_order;
  102363. if(partition == 0) {
  102364. if(partition_samples <= predictor_order)
  102365. return false;
  102366. else
  102367. partition_samples -= predictor_order;
  102368. }
  102369. mean = abs_residual_partition_sums[partition];
  102370. /* we are basically calculating the size in bits of the
  102371. * average residual magnitude in the partition:
  102372. * rice_parameter = floor(log2(mean/partition_samples))
  102373. * 'mean' is not a good name for the variable, it is
  102374. * actually the sum of magnitudes of all residual values
  102375. * in the partition, so the actual mean is
  102376. * mean/partition_samples
  102377. */
  102378. for(rice_parameter = 0, k = partition_samples; k < mean; rice_parameter++, k <<= 1)
  102379. ;
  102380. if(rice_parameter >= rice_parameter_limit) {
  102381. #ifdef DEBUG_VERBOSE
  102382. fprintf(stderr, "clipping rice_parameter (%u -> %u) @6\n", rice_parameter, rice_parameter_limit - 1);
  102383. #endif
  102384. rice_parameter = rice_parameter_limit - 1;
  102385. }
  102386. best_partition_bits = (unsigned)(-1);
  102387. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102388. if(rice_parameter_search_dist) {
  102389. if(rice_parameter < rice_parameter_search_dist)
  102390. min_rice_parameter = 0;
  102391. else
  102392. min_rice_parameter = rice_parameter - rice_parameter_search_dist;
  102393. max_rice_parameter = rice_parameter + rice_parameter_search_dist;
  102394. if(max_rice_parameter >= rice_parameter_limit) {
  102395. #ifdef DEBUG_VERBOSE
  102396. fprintf(stderr, "clipping rice_parameter (%u -> %u) @7\n", max_rice_parameter, rice_parameter_limit - 1);
  102397. #endif
  102398. max_rice_parameter = rice_parameter_limit - 1;
  102399. }
  102400. }
  102401. else
  102402. min_rice_parameter = max_rice_parameter = rice_parameter;
  102403. for(rice_parameter = min_rice_parameter; rice_parameter <= max_rice_parameter; rice_parameter++) {
  102404. #endif
  102405. #ifdef EXACT_RICE_BITS_CALCULATION
  102406. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, residual+residual_sample);
  102407. #else
  102408. partition_bits = count_rice_bits_in_partition_(rice_parameter, partition_samples, abs_residual_partition_sums[partition]);
  102409. #endif
  102410. if(partition_bits < best_partition_bits) {
  102411. best_rice_parameter = rice_parameter;
  102412. best_partition_bits = partition_bits;
  102413. }
  102414. #ifdef ENABLE_RICE_PARAMETER_SEARCH
  102415. }
  102416. #endif
  102417. if(search_for_escapes) {
  102418. 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;
  102419. if(partition_bits <= best_partition_bits) {
  102420. raw_bits[partition] = raw_bits_per_partition[partition];
  102421. best_rice_parameter = 0; /* will be converted to appropriate escape parameter later */
  102422. best_partition_bits = partition_bits;
  102423. }
  102424. else
  102425. raw_bits[partition] = 0;
  102426. }
  102427. parameters[partition] = best_rice_parameter;
  102428. bits_ += best_partition_bits;
  102429. residual_sample += partition_samples;
  102430. }
  102431. }
  102432. *bits = bits_;
  102433. return true;
  102434. }
  102435. unsigned get_wasted_bits_(FLAC__int32 signal[], unsigned samples)
  102436. {
  102437. unsigned i, shift;
  102438. FLAC__int32 x = 0;
  102439. for(i = 0; i < samples && !(x&1); i++)
  102440. x |= signal[i];
  102441. if(x == 0) {
  102442. shift = 0;
  102443. }
  102444. else {
  102445. for(shift = 0; !(x&1); shift++)
  102446. x >>= 1;
  102447. }
  102448. if(shift > 0) {
  102449. for(i = 0; i < samples; i++)
  102450. signal[i] >>= shift;
  102451. }
  102452. return shift;
  102453. }
  102454. void append_to_verify_fifo_(verify_input_fifo *fifo, const FLAC__int32 * const input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  102455. {
  102456. unsigned channel;
  102457. for(channel = 0; channel < channels; channel++)
  102458. memcpy(&fifo->data[channel][fifo->tail], &input[channel][input_offset], sizeof(FLAC__int32) * wide_samples);
  102459. fifo->tail += wide_samples;
  102460. FLAC__ASSERT(fifo->tail <= fifo->size);
  102461. }
  102462. void append_to_verify_fifo_interleaved_(verify_input_fifo *fifo, const FLAC__int32 input[], unsigned input_offset, unsigned channels, unsigned wide_samples)
  102463. {
  102464. unsigned channel;
  102465. unsigned sample, wide_sample;
  102466. unsigned tail = fifo->tail;
  102467. sample = input_offset * channels;
  102468. for(wide_sample = 0; wide_sample < wide_samples; wide_sample++) {
  102469. for(channel = 0; channel < channels; channel++)
  102470. fifo->data[channel][tail] = input[sample++];
  102471. tail++;
  102472. }
  102473. fifo->tail = tail;
  102474. FLAC__ASSERT(fifo->tail <= fifo->size);
  102475. }
  102476. FLAC__StreamDecoderReadStatus verify_read_callback_(const FLAC__StreamDecoder *decoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102477. {
  102478. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  102479. const size_t encoded_bytes = encoder->private_->verify.output.bytes;
  102480. (void)decoder;
  102481. if(encoder->private_->verify.needs_magic_hack) {
  102482. FLAC__ASSERT(*bytes >= FLAC__STREAM_SYNC_LENGTH);
  102483. *bytes = FLAC__STREAM_SYNC_LENGTH;
  102484. memcpy(buffer, FLAC__STREAM_SYNC_STRING, *bytes);
  102485. encoder->private_->verify.needs_magic_hack = false;
  102486. }
  102487. else {
  102488. if(encoded_bytes == 0) {
  102489. /*
  102490. * If we get here, a FIFO underflow has occurred,
  102491. * which means there is a bug somewhere.
  102492. */
  102493. FLAC__ASSERT(0);
  102494. return FLAC__STREAM_DECODER_READ_STATUS_ABORT;
  102495. }
  102496. else if(encoded_bytes < *bytes)
  102497. *bytes = encoded_bytes;
  102498. memcpy(buffer, encoder->private_->verify.output.data, *bytes);
  102499. encoder->private_->verify.output.data += *bytes;
  102500. encoder->private_->verify.output.bytes -= *bytes;
  102501. }
  102502. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  102503. }
  102504. FLAC__StreamDecoderWriteStatus verify_write_callback_(const FLAC__StreamDecoder *decoder, const FLAC__Frame *frame, const FLAC__int32 * const buffer[], void *client_data)
  102505. {
  102506. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder *)client_data;
  102507. unsigned channel;
  102508. const unsigned channels = frame->header.channels;
  102509. const unsigned blocksize = frame->header.blocksize;
  102510. const unsigned bytes_per_block = sizeof(FLAC__int32) * blocksize;
  102511. (void)decoder;
  102512. for(channel = 0; channel < channels; channel++) {
  102513. if(0 != memcmp(buffer[channel], encoder->private_->verify.input_fifo.data[channel], bytes_per_block)) {
  102514. unsigned i, sample = 0;
  102515. FLAC__int32 expect = 0, got = 0;
  102516. for(i = 0; i < blocksize; i++) {
  102517. if(buffer[channel][i] != encoder->private_->verify.input_fifo.data[channel][i]) {
  102518. sample = i;
  102519. expect = (FLAC__int32)encoder->private_->verify.input_fifo.data[channel][i];
  102520. got = (FLAC__int32)buffer[channel][i];
  102521. break;
  102522. }
  102523. }
  102524. FLAC__ASSERT(i < blocksize);
  102525. FLAC__ASSERT(frame->header.number_type == FLAC__FRAME_NUMBER_TYPE_SAMPLE_NUMBER);
  102526. encoder->private_->verify.error_stats.absolute_sample = frame->header.number.sample_number + sample;
  102527. encoder->private_->verify.error_stats.frame_number = (unsigned)(frame->header.number.sample_number / blocksize);
  102528. encoder->private_->verify.error_stats.channel = channel;
  102529. encoder->private_->verify.error_stats.sample = sample;
  102530. encoder->private_->verify.error_stats.expected = expect;
  102531. encoder->private_->verify.error_stats.got = got;
  102532. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_MISMATCH_IN_AUDIO_DATA;
  102533. return FLAC__STREAM_DECODER_WRITE_STATUS_ABORT;
  102534. }
  102535. }
  102536. /* dequeue the frame from the fifo */
  102537. encoder->private_->verify.input_fifo.tail -= blocksize;
  102538. FLAC__ASSERT(encoder->private_->verify.input_fifo.tail <= OVERREAD_);
  102539. for(channel = 0; channel < channels; channel++)
  102540. 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]));
  102541. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  102542. }
  102543. void verify_metadata_callback_(const FLAC__StreamDecoder *decoder, const FLAC__StreamMetadata *metadata, void *client_data)
  102544. {
  102545. (void)decoder, (void)metadata, (void)client_data;
  102546. }
  102547. void verify_error_callback_(const FLAC__StreamDecoder *decoder, FLAC__StreamDecoderErrorStatus status, void *client_data)
  102548. {
  102549. FLAC__StreamEncoder *encoder = (FLAC__StreamEncoder*)client_data;
  102550. (void)decoder, (void)status;
  102551. encoder->protected_->state = FLAC__STREAM_ENCODER_VERIFY_DECODER_ERROR;
  102552. }
  102553. FLAC__StreamEncoderReadStatus file_read_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__byte buffer[], size_t *bytes, void *client_data)
  102554. {
  102555. (void)client_data;
  102556. *bytes = fread(buffer, 1, *bytes, encoder->private_->file);
  102557. if (*bytes == 0) {
  102558. if (feof(encoder->private_->file))
  102559. return FLAC__STREAM_ENCODER_READ_STATUS_END_OF_STREAM;
  102560. else if (ferror(encoder->private_->file))
  102561. return FLAC__STREAM_ENCODER_READ_STATUS_ABORT;
  102562. }
  102563. return FLAC__STREAM_ENCODER_READ_STATUS_CONTINUE;
  102564. }
  102565. FLAC__StreamEncoderSeekStatus file_seek_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 absolute_byte_offset, void *client_data)
  102566. {
  102567. (void)client_data;
  102568. if(fseeko(encoder->private_->file, (off_t)absolute_byte_offset, SEEK_SET) < 0)
  102569. return FLAC__STREAM_ENCODER_SEEK_STATUS_ERROR;
  102570. else
  102571. return FLAC__STREAM_ENCODER_SEEK_STATUS_OK;
  102572. }
  102573. FLAC__StreamEncoderTellStatus file_tell_callback_enc(const FLAC__StreamEncoder *encoder, FLAC__uint64 *absolute_byte_offset, void *client_data)
  102574. {
  102575. off_t offset;
  102576. (void)client_data;
  102577. offset = ftello(encoder->private_->file);
  102578. if(offset < 0) {
  102579. return FLAC__STREAM_ENCODER_TELL_STATUS_ERROR;
  102580. }
  102581. else {
  102582. *absolute_byte_offset = (FLAC__uint64)offset;
  102583. return FLAC__STREAM_ENCODER_TELL_STATUS_OK;
  102584. }
  102585. }
  102586. #ifdef FLAC__VALGRIND_TESTING
  102587. static size_t local__fwrite(const void *ptr, size_t size, size_t nmemb, FILE *stream)
  102588. {
  102589. size_t ret = fwrite(ptr, size, nmemb, stream);
  102590. if(!ferror(stream))
  102591. fflush(stream);
  102592. return ret;
  102593. }
  102594. #else
  102595. #define local__fwrite fwrite
  102596. #endif
  102597. FLAC__StreamEncoderWriteStatus file_write_callback_(const FLAC__StreamEncoder *encoder, const FLAC__byte buffer[], size_t bytes, unsigned samples, unsigned current_frame, void *client_data)
  102598. {
  102599. (void)client_data, (void)current_frame;
  102600. if(local__fwrite(buffer, sizeof(FLAC__byte), bytes, encoder->private_->file) == bytes) {
  102601. FLAC__bool call_it = 0 != encoder->private_->progress_callback && (
  102602. #if FLAC__HAS_OGG
  102603. /* We would like to be able to use 'samples > 0' in the
  102604. * clause here but currently because of the nature of our
  102605. * Ogg writing implementation, 'samples' is always 0 (see
  102606. * ogg_encoder_aspect.c). The downside is extra progress
  102607. * callbacks.
  102608. */
  102609. encoder->private_->is_ogg? true :
  102610. #endif
  102611. samples > 0
  102612. );
  102613. if(call_it) {
  102614. /* NOTE: We have to add +bytes, +samples, and +1 to the stats
  102615. * because at this point in the callback chain, the stats
  102616. * have not been updated. Only after we return and control
  102617. * gets back to write_frame_() are the stats updated
  102618. */
  102619. 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);
  102620. }
  102621. return FLAC__STREAM_ENCODER_WRITE_STATUS_OK;
  102622. }
  102623. else
  102624. return FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  102625. }
  102626. /*
  102627. * This will forcibly set stdout to binary mode (for OSes that require it)
  102628. */
  102629. FILE *get_binary_stdout_(void)
  102630. {
  102631. /* if something breaks here it is probably due to the presence or
  102632. * absence of an underscore before the identifiers 'setmode',
  102633. * 'fileno', and/or 'O_BINARY'; check your system header files.
  102634. */
  102635. #if defined _MSC_VER || defined __MINGW32__
  102636. _setmode(_fileno(stdout), _O_BINARY);
  102637. #elif defined __CYGWIN__
  102638. /* almost certainly not needed for any modern Cygwin, but let's be safe... */
  102639. setmode(_fileno(stdout), _O_BINARY);
  102640. #elif defined __EMX__
  102641. setmode(fileno(stdout), O_BINARY);
  102642. #endif
  102643. return stdout;
  102644. }
  102645. #endif
  102646. /********* End of inlined file: stream_encoder.c *********/
  102647. /********* Start of inlined file: stream_encoder_framing.c *********/
  102648. /********* Start of inlined file: juce_FlacHeader.h *********/
  102649. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  102650. // tasks..
  102651. /********* Start of inlined file: juce_Config.h *********/
  102652. #ifndef __JUCE_CONFIG_JUCEHEADER__
  102653. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  102654. /*
  102655. This file contains macros that enable/disable various JUCE features.
  102656. */
  102657. /** The name of the namespace that all Juce classes and functions will be
  102658. put inside. If this is not defined, no namespace will be used.
  102659. */
  102660. #ifndef JUCE_NAMESPACE
  102661. #define JUCE_NAMESPACE juce
  102662. #endif
  102663. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  102664. but if you define this value, you can override this can force it to be true or
  102665. false.
  102666. */
  102667. #ifndef JUCE_FORCE_DEBUG
  102668. //#define JUCE_FORCE_DEBUG 1
  102669. #endif
  102670. /** If this flag is enabled, the the jassert and jassertfalse macros will
  102671. always use Logger::writeToLog() to write a message when an assertion happens.
  102672. Enabling it will also leave this turned on in release builds. When it's disabled,
  102673. however, the jassert and jassertfalse macros will not be compiled in a
  102674. release build.
  102675. @see jassert, jassertfalse, Logger
  102676. */
  102677. #ifndef JUCE_LOG_ASSERTIONS
  102678. // #define JUCE_LOG_ASSERTIONS 1
  102679. #endif
  102680. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  102681. which the ASIOAudioIODevice class can't be built. See the comments in the
  102682. ASIOAudioIODevice class's header file for more info about this.
  102683. (This only affects a Win32 build)
  102684. */
  102685. #ifndef JUCE_ASIO
  102686. #define JUCE_ASIO 1
  102687. #endif
  102688. /** Comment out this macro to disable building of ALSA device support on Linux.
  102689. */
  102690. #ifndef JUCE_ALSA
  102691. #define JUCE_ALSA 1
  102692. #endif
  102693. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  102694. have the SDK installed.
  102695. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  102696. classes will be unavailable.
  102697. On Windows, if you enable this, you'll need to have the QuickTime SDK
  102698. installed, and its header files will need to be on your include path.
  102699. */
  102700. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  102701. #define JUCE_QUICKTIME 1
  102702. #endif
  102703. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  102704. have the appropriate headers and libraries available. If it's not enabled, the
  102705. OpenGLComponent class will be unavailable.
  102706. */
  102707. #ifndef JUCE_OPENGL
  102708. #define JUCE_OPENGL 1
  102709. #endif
  102710. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  102711. If you're not going to need either of these formats, turn off the flags to
  102712. avoid bloating your codebase with them.
  102713. */
  102714. #ifndef JUCE_USE_FLAC
  102715. #define JUCE_USE_FLAC 1
  102716. #endif
  102717. #ifndef JUCE_USE_OGGVORBIS
  102718. #define JUCE_USE_OGGVORBIS 1
  102719. #endif
  102720. /** This flag lets you enable support for CD-burning. You might want to disable
  102721. it to build without the MS SDK under windows.
  102722. */
  102723. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  102724. #define JUCE_USE_CDBURNER 1
  102725. #endif
  102726. /** Enabling this macro means that all regions that get repainted will have a coloured
  102727. line drawn around them.
  102728. This is handy if you're trying to optimise drawing, because it lets you easily see
  102729. when anything is being repainted unnecessarily.
  102730. */
  102731. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  102732. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  102733. #endif
  102734. /** Enable this under Linux to use Xinerama for multi-monitor support.
  102735. */
  102736. #ifndef JUCE_USE_XINERAMA
  102737. #define JUCE_USE_XINERAMA 1
  102738. #endif
  102739. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  102740. */
  102741. #ifndef JUCE_USE_XSHM
  102742. #define JUCE_USE_XSHM 1
  102743. #endif
  102744. /** Enabling this builds support for VST audio plugins.
  102745. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  102746. */
  102747. #ifndef JUCE_PLUGINHOST_VST
  102748. // #define JUCE_PLUGINHOST_VST 1
  102749. #endif
  102750. /** Enabling this builds support for AudioUnit audio plugins.
  102751. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  102752. */
  102753. #ifndef JUCE_PLUGINHOST_AU
  102754. // #define JUCE_PLUGINHOST_AU 1
  102755. #endif
  102756. /** Disabling this will avoid linking to any UI code. This is handy for
  102757. writing command-line utilities, e.g. on linux boxes which don't have some
  102758. of the UI libraries installed.
  102759. (On mac and windows, this won't generally make much difference to the build).
  102760. */
  102761. #ifndef JUCE_BUILD_GUI_CLASSES
  102762. #define JUCE_BUILD_GUI_CLASSES 1
  102763. #endif
  102764. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  102765. */
  102766. #ifndef JUCE_WEB_BROWSER
  102767. #define JUCE_WEB_BROWSER 1
  102768. #endif
  102769. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  102770. codebase - you might need to use this if you're linking to some of these libraries
  102771. yourself.
  102772. */
  102773. #ifndef JUCE_INCLUDE_ZLIB_CODE
  102774. #define JUCE_INCLUDE_ZLIB_CODE 1
  102775. #endif
  102776. #ifndef JUCE_INCLUDE_FLAC_CODE
  102777. #define JUCE_INCLUDE_FLAC_CODE 1
  102778. #endif
  102779. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  102780. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  102781. #endif
  102782. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  102783. #define JUCE_INCLUDE_PNGLIB_CODE 1
  102784. #endif
  102785. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  102786. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  102787. #endif
  102788. /** Enable this to add extra memory-leak info to the new and delete operators.
  102789. (Currently, this only affects Windows builds in debug mode).
  102790. */
  102791. #ifndef JUCE_CHECK_MEMORY_LEAKS
  102792. #define JUCE_CHECK_MEMORY_LEAKS 1
  102793. #endif
  102794. /** Enable this to turn on juce's internal catching of exceptions.
  102795. Turning it off will avoid any exception catching. With it on, all exceptions
  102796. are passed to the JUCEApplication::unhandledException() callback for logging.
  102797. */
  102798. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  102799. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  102800. #endif
  102801. /** If this macro is set, the Juce String class will use unicode as its
  102802. internal representation. If it isn't set, it'll use ANSI.
  102803. */
  102804. #ifndef JUCE_STRINGS_ARE_UNICODE
  102805. #define JUCE_STRINGS_ARE_UNICODE 1
  102806. #endif
  102807. #endif
  102808. /********* End of inlined file: juce_Config.h *********/
  102809. #define VERSION "1.2.1"
  102810. #define FLAC__NO_DLL 1
  102811. #ifdef _MSC_VER
  102812. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  102813. #endif
  102814. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  102815. #define FLAC__SYS_DARWIN 1
  102816. #endif
  102817. /********* End of inlined file: juce_FlacHeader.h *********/
  102818. #if JUCE_USE_FLAC
  102819. #if HAVE_CONFIG_H
  102820. # include <config.h>
  102821. #endif
  102822. #include <stdio.h>
  102823. #include <string.h> /* for strlen() */
  102824. #ifdef max
  102825. #undef max
  102826. #endif
  102827. #define max(x,y) ((x)>(y)?(x):(y))
  102828. static FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method);
  102829. 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);
  102830. FLAC__bool FLAC__add_metadata_block(const FLAC__StreamMetadata *metadata, FLAC__BitWriter *bw)
  102831. {
  102832. unsigned i, j;
  102833. const unsigned vendor_string_length = (unsigned)strlen(FLAC__VENDOR_STRING);
  102834. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->is_last, FLAC__STREAM_METADATA_IS_LAST_LEN))
  102835. return false;
  102836. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->type, FLAC__STREAM_METADATA_TYPE_LEN))
  102837. return false;
  102838. /*
  102839. * First, for VORBIS_COMMENTs, adjust the length to reflect our vendor string
  102840. */
  102841. i = metadata->length;
  102842. if(metadata->type == FLAC__METADATA_TYPE_VORBIS_COMMENT) {
  102843. FLAC__ASSERT(metadata->data.vorbis_comment.vendor_string.length == 0 || 0 != metadata->data.vorbis_comment.vendor_string.entry);
  102844. i -= metadata->data.vorbis_comment.vendor_string.length;
  102845. i += vendor_string_length;
  102846. }
  102847. FLAC__ASSERT(i < (1u << FLAC__STREAM_METADATA_LENGTH_LEN));
  102848. if(!FLAC__bitwriter_write_raw_uint32(bw, i, FLAC__STREAM_METADATA_LENGTH_LEN))
  102849. return false;
  102850. switch(metadata->type) {
  102851. case FLAC__METADATA_TYPE_STREAMINFO:
  102852. FLAC__ASSERT(metadata->data.stream_info.min_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN));
  102853. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MIN_BLOCK_SIZE_LEN))
  102854. return false;
  102855. FLAC__ASSERT(metadata->data.stream_info.max_blocksize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN));
  102856. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_blocksize, FLAC__STREAM_METADATA_STREAMINFO_MAX_BLOCK_SIZE_LEN))
  102857. return false;
  102858. FLAC__ASSERT(metadata->data.stream_info.min_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN));
  102859. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.min_framesize, FLAC__STREAM_METADATA_STREAMINFO_MIN_FRAME_SIZE_LEN))
  102860. return false;
  102861. FLAC__ASSERT(metadata->data.stream_info.max_framesize < (1u << FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN));
  102862. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.max_framesize, FLAC__STREAM_METADATA_STREAMINFO_MAX_FRAME_SIZE_LEN))
  102863. return false;
  102864. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(metadata->data.stream_info.sample_rate));
  102865. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.sample_rate, FLAC__STREAM_METADATA_STREAMINFO_SAMPLE_RATE_LEN))
  102866. return false;
  102867. FLAC__ASSERT(metadata->data.stream_info.channels > 0);
  102868. FLAC__ASSERT(metadata->data.stream_info.channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN));
  102869. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.channels-1, FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN))
  102870. return false;
  102871. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample > 0);
  102872. FLAC__ASSERT(metadata->data.stream_info.bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  102873. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.stream_info.bits_per_sample-1, FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN))
  102874. return false;
  102875. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.stream_info.total_samples, FLAC__STREAM_METADATA_STREAMINFO_TOTAL_SAMPLES_LEN))
  102876. return false;
  102877. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.stream_info.md5sum, 16))
  102878. return false;
  102879. break;
  102880. case FLAC__METADATA_TYPE_PADDING:
  102881. if(!FLAC__bitwriter_write_zeroes(bw, metadata->length * 8))
  102882. return false;
  102883. break;
  102884. case FLAC__METADATA_TYPE_APPLICATION:
  102885. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.id, FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8))
  102886. return false;
  102887. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.application.data, metadata->length - (FLAC__STREAM_METADATA_APPLICATION_ID_LEN / 8)))
  102888. return false;
  102889. break;
  102890. case FLAC__METADATA_TYPE_SEEKTABLE:
  102891. for(i = 0; i < metadata->data.seek_table.num_points; i++) {
  102892. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].sample_number, FLAC__STREAM_METADATA_SEEKPOINT_SAMPLE_NUMBER_LEN))
  102893. return false;
  102894. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.seek_table.points[i].stream_offset, FLAC__STREAM_METADATA_SEEKPOINT_STREAM_OFFSET_LEN))
  102895. return false;
  102896. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.seek_table.points[i].frame_samples, FLAC__STREAM_METADATA_SEEKPOINT_FRAME_SAMPLES_LEN))
  102897. return false;
  102898. }
  102899. break;
  102900. case FLAC__METADATA_TYPE_VORBIS_COMMENT:
  102901. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, vendor_string_length))
  102902. return false;
  102903. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)FLAC__VENDOR_STRING, vendor_string_length))
  102904. return false;
  102905. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.num_comments))
  102906. return false;
  102907. for(i = 0; i < metadata->data.vorbis_comment.num_comments; i++) {
  102908. if(!FLAC__bitwriter_write_raw_uint32_little_endian(bw, metadata->data.vorbis_comment.comments[i].length))
  102909. return false;
  102910. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.vorbis_comment.comments[i].entry, metadata->data.vorbis_comment.comments[i].length))
  102911. return false;
  102912. }
  102913. break;
  102914. case FLAC__METADATA_TYPE_CUESHEET:
  102915. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_MEDIA_CATALOG_NUMBER_LEN % 8 == 0);
  102916. 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))
  102917. return false;
  102918. if(!FLAC__bitwriter_write_raw_uint64(bw, metadata->data.cue_sheet.lead_in, FLAC__STREAM_METADATA_CUESHEET_LEAD_IN_LEN))
  102919. return false;
  102920. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.is_cd? 1 : 0, FLAC__STREAM_METADATA_CUESHEET_IS_CD_LEN))
  102921. return false;
  102922. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_RESERVED_LEN))
  102923. return false;
  102924. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.cue_sheet.num_tracks, FLAC__STREAM_METADATA_CUESHEET_NUM_TRACKS_LEN))
  102925. return false;
  102926. for(i = 0; i < metadata->data.cue_sheet.num_tracks; i++) {
  102927. const FLAC__StreamMetadata_CueSheet_Track *track = metadata->data.cue_sheet.tracks + i;
  102928. if(!FLAC__bitwriter_write_raw_uint64(bw, track->offset, FLAC__STREAM_METADATA_CUESHEET_TRACK_OFFSET_LEN))
  102929. return false;
  102930. if(!FLAC__bitwriter_write_raw_uint32(bw, track->number, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUMBER_LEN))
  102931. return false;
  102932. FLAC__ASSERT(FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN % 8 == 0);
  102933. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)track->isrc, FLAC__STREAM_METADATA_CUESHEET_TRACK_ISRC_LEN/8))
  102934. return false;
  102935. if(!FLAC__bitwriter_write_raw_uint32(bw, track->type, FLAC__STREAM_METADATA_CUESHEET_TRACK_TYPE_LEN))
  102936. return false;
  102937. if(!FLAC__bitwriter_write_raw_uint32(bw, track->pre_emphasis, FLAC__STREAM_METADATA_CUESHEET_TRACK_PRE_EMPHASIS_LEN))
  102938. return false;
  102939. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_TRACK_RESERVED_LEN))
  102940. return false;
  102941. if(!FLAC__bitwriter_write_raw_uint32(bw, track->num_indices, FLAC__STREAM_METADATA_CUESHEET_TRACK_NUM_INDICES_LEN))
  102942. return false;
  102943. for(j = 0; j < track->num_indices; j++) {
  102944. const FLAC__StreamMetadata_CueSheet_Index *index = track->indices + j;
  102945. if(!FLAC__bitwriter_write_raw_uint64(bw, index->offset, FLAC__STREAM_METADATA_CUESHEET_INDEX_OFFSET_LEN))
  102946. return false;
  102947. if(!FLAC__bitwriter_write_raw_uint32(bw, index->number, FLAC__STREAM_METADATA_CUESHEET_INDEX_NUMBER_LEN))
  102948. return false;
  102949. if(!FLAC__bitwriter_write_zeroes(bw, FLAC__STREAM_METADATA_CUESHEET_INDEX_RESERVED_LEN))
  102950. return false;
  102951. }
  102952. }
  102953. break;
  102954. case FLAC__METADATA_TYPE_PICTURE:
  102955. {
  102956. size_t len;
  102957. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.type, FLAC__STREAM_METADATA_PICTURE_TYPE_LEN))
  102958. return false;
  102959. len = strlen(metadata->data.picture.mime_type);
  102960. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_MIME_TYPE_LENGTH_LEN))
  102961. return false;
  102962. if(!FLAC__bitwriter_write_byte_block(bw, (const FLAC__byte*)metadata->data.picture.mime_type, len))
  102963. return false;
  102964. len = strlen((const char *)metadata->data.picture.description);
  102965. if(!FLAC__bitwriter_write_raw_uint32(bw, len, FLAC__STREAM_METADATA_PICTURE_DESCRIPTION_LENGTH_LEN))
  102966. return false;
  102967. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.description, len))
  102968. return false;
  102969. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.width, FLAC__STREAM_METADATA_PICTURE_WIDTH_LEN))
  102970. return false;
  102971. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.height, FLAC__STREAM_METADATA_PICTURE_HEIGHT_LEN))
  102972. return false;
  102973. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.depth, FLAC__STREAM_METADATA_PICTURE_DEPTH_LEN))
  102974. return false;
  102975. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.colors, FLAC__STREAM_METADATA_PICTURE_COLORS_LEN))
  102976. return false;
  102977. if(!FLAC__bitwriter_write_raw_uint32(bw, metadata->data.picture.data_length, FLAC__STREAM_METADATA_PICTURE_DATA_LENGTH_LEN))
  102978. return false;
  102979. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.picture.data, metadata->data.picture.data_length))
  102980. return false;
  102981. }
  102982. break;
  102983. default:
  102984. if(!FLAC__bitwriter_write_byte_block(bw, metadata->data.unknown.data, metadata->length))
  102985. return false;
  102986. break;
  102987. }
  102988. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  102989. return true;
  102990. }
  102991. FLAC__bool FLAC__frame_add_header(const FLAC__FrameHeader *header, FLAC__BitWriter *bw)
  102992. {
  102993. unsigned u, blocksize_hint, sample_rate_hint;
  102994. FLAC__byte crc;
  102995. FLAC__ASSERT(FLAC__bitwriter_is_byte_aligned(bw));
  102996. if(!FLAC__bitwriter_write_raw_uint32(bw, FLAC__FRAME_HEADER_SYNC, FLAC__FRAME_HEADER_SYNC_LEN))
  102997. return false;
  102998. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_RESERVED_LEN))
  102999. return false;
  103000. if(!FLAC__bitwriter_write_raw_uint32(bw, (header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER)? 0 : 1, FLAC__FRAME_HEADER_BLOCKING_STRATEGY_LEN))
  103001. return false;
  103002. FLAC__ASSERT(header->blocksize > 0 && header->blocksize <= FLAC__MAX_BLOCK_SIZE);
  103003. /* when this assertion holds true, any legal blocksize can be expressed in the frame header */
  103004. FLAC__ASSERT(FLAC__MAX_BLOCK_SIZE <= 65535u);
  103005. blocksize_hint = 0;
  103006. switch(header->blocksize) {
  103007. case 192: u = 1; break;
  103008. case 576: u = 2; break;
  103009. case 1152: u = 3; break;
  103010. case 2304: u = 4; break;
  103011. case 4608: u = 5; break;
  103012. case 256: u = 8; break;
  103013. case 512: u = 9; break;
  103014. case 1024: u = 10; break;
  103015. case 2048: u = 11; break;
  103016. case 4096: u = 12; break;
  103017. case 8192: u = 13; break;
  103018. case 16384: u = 14; break;
  103019. case 32768: u = 15; break;
  103020. default:
  103021. if(header->blocksize <= 0x100)
  103022. blocksize_hint = u = 6;
  103023. else
  103024. blocksize_hint = u = 7;
  103025. break;
  103026. }
  103027. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BLOCK_SIZE_LEN))
  103028. return false;
  103029. FLAC__ASSERT(FLAC__format_sample_rate_is_valid(header->sample_rate));
  103030. sample_rate_hint = 0;
  103031. switch(header->sample_rate) {
  103032. case 88200: u = 1; break;
  103033. case 176400: u = 2; break;
  103034. case 192000: u = 3; break;
  103035. case 8000: u = 4; break;
  103036. case 16000: u = 5; break;
  103037. case 22050: u = 6; break;
  103038. case 24000: u = 7; break;
  103039. case 32000: u = 8; break;
  103040. case 44100: u = 9; break;
  103041. case 48000: u = 10; break;
  103042. case 96000: u = 11; break;
  103043. default:
  103044. if(header->sample_rate <= 255000 && header->sample_rate % 1000 == 0)
  103045. sample_rate_hint = u = 12;
  103046. else if(header->sample_rate % 10 == 0)
  103047. sample_rate_hint = u = 14;
  103048. else if(header->sample_rate <= 0xffff)
  103049. sample_rate_hint = u = 13;
  103050. else
  103051. u = 0;
  103052. break;
  103053. }
  103054. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_SAMPLE_RATE_LEN))
  103055. return false;
  103056. FLAC__ASSERT(header->channels > 0 && header->channels <= (1u << FLAC__STREAM_METADATA_STREAMINFO_CHANNELS_LEN) && header->channels <= FLAC__MAX_CHANNELS);
  103057. switch(header->channel_assignment) {
  103058. case FLAC__CHANNEL_ASSIGNMENT_INDEPENDENT:
  103059. u = header->channels - 1;
  103060. break;
  103061. case FLAC__CHANNEL_ASSIGNMENT_LEFT_SIDE:
  103062. FLAC__ASSERT(header->channels == 2);
  103063. u = 8;
  103064. break;
  103065. case FLAC__CHANNEL_ASSIGNMENT_RIGHT_SIDE:
  103066. FLAC__ASSERT(header->channels == 2);
  103067. u = 9;
  103068. break;
  103069. case FLAC__CHANNEL_ASSIGNMENT_MID_SIDE:
  103070. FLAC__ASSERT(header->channels == 2);
  103071. u = 10;
  103072. break;
  103073. default:
  103074. FLAC__ASSERT(0);
  103075. }
  103076. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_CHANNEL_ASSIGNMENT_LEN))
  103077. return false;
  103078. FLAC__ASSERT(header->bits_per_sample > 0 && header->bits_per_sample <= (1u << FLAC__STREAM_METADATA_STREAMINFO_BITS_PER_SAMPLE_LEN));
  103079. switch(header->bits_per_sample) {
  103080. case 8 : u = 1; break;
  103081. case 12: u = 2; break;
  103082. case 16: u = 4; break;
  103083. case 20: u = 5; break;
  103084. case 24: u = 6; break;
  103085. default: u = 0; break;
  103086. }
  103087. if(!FLAC__bitwriter_write_raw_uint32(bw, u, FLAC__FRAME_HEADER_BITS_PER_SAMPLE_LEN))
  103088. return false;
  103089. if(!FLAC__bitwriter_write_raw_uint32(bw, 0, FLAC__FRAME_HEADER_ZERO_PAD_LEN))
  103090. return false;
  103091. if(header->number_type == FLAC__FRAME_NUMBER_TYPE_FRAME_NUMBER) {
  103092. if(!FLAC__bitwriter_write_utf8_uint32(bw, header->number.frame_number))
  103093. return false;
  103094. }
  103095. else {
  103096. if(!FLAC__bitwriter_write_utf8_uint64(bw, header->number.sample_number))
  103097. return false;
  103098. }
  103099. if(blocksize_hint)
  103100. if(!FLAC__bitwriter_write_raw_uint32(bw, header->blocksize-1, (blocksize_hint==6)? 8:16))
  103101. return false;
  103102. switch(sample_rate_hint) {
  103103. case 12:
  103104. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 1000, 8))
  103105. return false;
  103106. break;
  103107. case 13:
  103108. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate, 16))
  103109. return false;
  103110. break;
  103111. case 14:
  103112. if(!FLAC__bitwriter_write_raw_uint32(bw, header->sample_rate / 10, 16))
  103113. return false;
  103114. break;
  103115. }
  103116. /* write the CRC */
  103117. if(!FLAC__bitwriter_get_write_crc8(bw, &crc))
  103118. return false;
  103119. if(!FLAC__bitwriter_write_raw_uint32(bw, crc, FLAC__FRAME_HEADER_CRC_LEN))
  103120. return false;
  103121. return true;
  103122. }
  103123. FLAC__bool FLAC__subframe_add_constant(const FLAC__Subframe_Constant *subframe, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  103124. {
  103125. FLAC__bool ok;
  103126. ok =
  103127. 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) &&
  103128. (wasted_bits? FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1) : true) &&
  103129. FLAC__bitwriter_write_raw_int32(bw, subframe->value, subframe_bps)
  103130. ;
  103131. return ok;
  103132. }
  103133. FLAC__bool FLAC__subframe_add_fixed(const FLAC__Subframe_Fixed *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  103134. {
  103135. unsigned i;
  103136. 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))
  103137. return false;
  103138. if(wasted_bits)
  103139. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  103140. return false;
  103141. for(i = 0; i < subframe->order; i++)
  103142. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  103143. return false;
  103144. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  103145. return false;
  103146. switch(subframe->entropy_coding_method.type) {
  103147. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  103148. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  103149. if(!add_residual_partitioned_rice_(
  103150. bw,
  103151. subframe->residual,
  103152. residual_samples,
  103153. subframe->order,
  103154. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  103155. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  103156. subframe->entropy_coding_method.data.partitioned_rice.order,
  103157. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  103158. ))
  103159. return false;
  103160. break;
  103161. default:
  103162. FLAC__ASSERT(0);
  103163. }
  103164. return true;
  103165. }
  103166. FLAC__bool FLAC__subframe_add_lpc(const FLAC__Subframe_LPC *subframe, unsigned residual_samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  103167. {
  103168. unsigned i;
  103169. 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))
  103170. return false;
  103171. if(wasted_bits)
  103172. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  103173. return false;
  103174. for(i = 0; i < subframe->order; i++)
  103175. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->warmup[i], subframe_bps))
  103176. return false;
  103177. if(!FLAC__bitwriter_write_raw_uint32(bw, subframe->qlp_coeff_precision-1, FLAC__SUBFRAME_LPC_QLP_COEFF_PRECISION_LEN))
  103178. return false;
  103179. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->quantization_level, FLAC__SUBFRAME_LPC_QLP_SHIFT_LEN))
  103180. return false;
  103181. for(i = 0; i < subframe->order; i++)
  103182. if(!FLAC__bitwriter_write_raw_int32(bw, subframe->qlp_coeff[i], subframe->qlp_coeff_precision))
  103183. return false;
  103184. if(!add_entropy_coding_method_(bw, &subframe->entropy_coding_method))
  103185. return false;
  103186. switch(subframe->entropy_coding_method.type) {
  103187. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  103188. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  103189. if(!add_residual_partitioned_rice_(
  103190. bw,
  103191. subframe->residual,
  103192. residual_samples,
  103193. subframe->order,
  103194. subframe->entropy_coding_method.data.partitioned_rice.contents->parameters,
  103195. subframe->entropy_coding_method.data.partitioned_rice.contents->raw_bits,
  103196. subframe->entropy_coding_method.data.partitioned_rice.order,
  103197. /*is_extended=*/subframe->entropy_coding_method.type == FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2
  103198. ))
  103199. return false;
  103200. break;
  103201. default:
  103202. FLAC__ASSERT(0);
  103203. }
  103204. return true;
  103205. }
  103206. FLAC__bool FLAC__subframe_add_verbatim(const FLAC__Subframe_Verbatim *subframe, unsigned samples, unsigned subframe_bps, unsigned wasted_bits, FLAC__BitWriter *bw)
  103207. {
  103208. unsigned i;
  103209. const FLAC__int32 *signal = subframe->data;
  103210. 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))
  103211. return false;
  103212. if(wasted_bits)
  103213. if(!FLAC__bitwriter_write_unary_unsigned(bw, wasted_bits-1))
  103214. return false;
  103215. for(i = 0; i < samples; i++)
  103216. if(!FLAC__bitwriter_write_raw_int32(bw, signal[i], subframe_bps))
  103217. return false;
  103218. return true;
  103219. }
  103220. FLAC__bool add_entropy_coding_method_(FLAC__BitWriter *bw, const FLAC__EntropyCodingMethod *method)
  103221. {
  103222. if(!FLAC__bitwriter_write_raw_uint32(bw, method->type, FLAC__ENTROPY_CODING_METHOD_TYPE_LEN))
  103223. return false;
  103224. switch(method->type) {
  103225. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE:
  103226. case FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2:
  103227. if(!FLAC__bitwriter_write_raw_uint32(bw, method->data.partitioned_rice.order, FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ORDER_LEN))
  103228. return false;
  103229. break;
  103230. default:
  103231. FLAC__ASSERT(0);
  103232. }
  103233. return true;
  103234. }
  103235. 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)
  103236. {
  103237. const unsigned plen = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_PARAMETER_LEN : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_PARAMETER_LEN;
  103238. const unsigned pesc = is_extended? FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE2_ESCAPE_PARAMETER : FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_ESCAPE_PARAMETER;
  103239. if(partition_order == 0) {
  103240. unsigned i;
  103241. if(raw_bits[0] == 0) {
  103242. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[0], plen))
  103243. return false;
  103244. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual, residual_samples, rice_parameters[0]))
  103245. return false;
  103246. }
  103247. else {
  103248. FLAC__ASSERT(rice_parameters[0] == 0);
  103249. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  103250. return false;
  103251. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[0], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  103252. return false;
  103253. for(i = 0; i < residual_samples; i++) {
  103254. if(!FLAC__bitwriter_write_raw_int32(bw, residual[i], raw_bits[0]))
  103255. return false;
  103256. }
  103257. }
  103258. return true;
  103259. }
  103260. else {
  103261. unsigned i, j, k = 0, k_last = 0;
  103262. unsigned partition_samples;
  103263. const unsigned default_partition_samples = (residual_samples+predictor_order) >> partition_order;
  103264. for(i = 0; i < (1u<<partition_order); i++) {
  103265. partition_samples = default_partition_samples;
  103266. if(i == 0)
  103267. partition_samples -= predictor_order;
  103268. k += partition_samples;
  103269. if(raw_bits[i] == 0) {
  103270. if(!FLAC__bitwriter_write_raw_uint32(bw, rice_parameters[i], plen))
  103271. return false;
  103272. if(!FLAC__bitwriter_write_rice_signed_block(bw, residual+k_last, k-k_last, rice_parameters[i]))
  103273. return false;
  103274. }
  103275. else {
  103276. if(!FLAC__bitwriter_write_raw_uint32(bw, pesc, plen))
  103277. return false;
  103278. if(!FLAC__bitwriter_write_raw_uint32(bw, raw_bits[i], FLAC__ENTROPY_CODING_METHOD_PARTITIONED_RICE_RAW_LEN))
  103279. return false;
  103280. for(j = k_last; j < k; j++) {
  103281. if(!FLAC__bitwriter_write_raw_int32(bw, residual[j], raw_bits[i]))
  103282. return false;
  103283. }
  103284. }
  103285. k_last = k;
  103286. }
  103287. return true;
  103288. }
  103289. }
  103290. #endif
  103291. /********* End of inlined file: stream_encoder_framing.c *********/
  103292. /********* Start of inlined file: window_flac.c *********/
  103293. /********* Start of inlined file: juce_FlacHeader.h *********/
  103294. // This file is included at the start of each FLAC .c file, just to do a few housekeeping
  103295. // tasks..
  103296. /********* Start of inlined file: juce_Config.h *********/
  103297. #ifndef __JUCE_CONFIG_JUCEHEADER__
  103298. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  103299. /*
  103300. This file contains macros that enable/disable various JUCE features.
  103301. */
  103302. /** The name of the namespace that all Juce classes and functions will be
  103303. put inside. If this is not defined, no namespace will be used.
  103304. */
  103305. #ifndef JUCE_NAMESPACE
  103306. #define JUCE_NAMESPACE juce
  103307. #endif
  103308. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  103309. but if you define this value, you can override this can force it to be true or
  103310. false.
  103311. */
  103312. #ifndef JUCE_FORCE_DEBUG
  103313. //#define JUCE_FORCE_DEBUG 1
  103314. #endif
  103315. /** If this flag is enabled, the the jassert and jassertfalse macros will
  103316. always use Logger::writeToLog() to write a message when an assertion happens.
  103317. Enabling it will also leave this turned on in release builds. When it's disabled,
  103318. however, the jassert and jassertfalse macros will not be compiled in a
  103319. release build.
  103320. @see jassert, jassertfalse, Logger
  103321. */
  103322. #ifndef JUCE_LOG_ASSERTIONS
  103323. // #define JUCE_LOG_ASSERTIONS 1
  103324. #endif
  103325. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  103326. which the ASIOAudioIODevice class can't be built. See the comments in the
  103327. ASIOAudioIODevice class's header file for more info about this.
  103328. (This only affects a Win32 build)
  103329. */
  103330. #ifndef JUCE_ASIO
  103331. #define JUCE_ASIO 1
  103332. #endif
  103333. /** Comment out this macro to disable building of ALSA device support on Linux.
  103334. */
  103335. #ifndef JUCE_ALSA
  103336. #define JUCE_ALSA 1
  103337. #endif
  103338. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  103339. have the SDK installed.
  103340. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  103341. classes will be unavailable.
  103342. On Windows, if you enable this, you'll need to have the QuickTime SDK
  103343. installed, and its header files will need to be on your include path.
  103344. */
  103345. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  103346. #define JUCE_QUICKTIME 1
  103347. #endif
  103348. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  103349. have the appropriate headers and libraries available. If it's not enabled, the
  103350. OpenGLComponent class will be unavailable.
  103351. */
  103352. #ifndef JUCE_OPENGL
  103353. #define JUCE_OPENGL 1
  103354. #endif
  103355. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  103356. If you're not going to need either of these formats, turn off the flags to
  103357. avoid bloating your codebase with them.
  103358. */
  103359. #ifndef JUCE_USE_FLAC
  103360. #define JUCE_USE_FLAC 1
  103361. #endif
  103362. #ifndef JUCE_USE_OGGVORBIS
  103363. #define JUCE_USE_OGGVORBIS 1
  103364. #endif
  103365. /** This flag lets you enable support for CD-burning. You might want to disable
  103366. it to build without the MS SDK under windows.
  103367. */
  103368. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  103369. #define JUCE_USE_CDBURNER 1
  103370. #endif
  103371. /** Enabling this macro means that all regions that get repainted will have a coloured
  103372. line drawn around them.
  103373. This is handy if you're trying to optimise drawing, because it lets you easily see
  103374. when anything is being repainted unnecessarily.
  103375. */
  103376. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  103377. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  103378. #endif
  103379. /** Enable this under Linux to use Xinerama for multi-monitor support.
  103380. */
  103381. #ifndef JUCE_USE_XINERAMA
  103382. #define JUCE_USE_XINERAMA 1
  103383. #endif
  103384. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  103385. */
  103386. #ifndef JUCE_USE_XSHM
  103387. #define JUCE_USE_XSHM 1
  103388. #endif
  103389. /** Enabling this builds support for VST audio plugins.
  103390. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  103391. */
  103392. #ifndef JUCE_PLUGINHOST_VST
  103393. // #define JUCE_PLUGINHOST_VST 1
  103394. #endif
  103395. /** Enabling this builds support for AudioUnit audio plugins.
  103396. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  103397. */
  103398. #ifndef JUCE_PLUGINHOST_AU
  103399. // #define JUCE_PLUGINHOST_AU 1
  103400. #endif
  103401. /** Disabling this will avoid linking to any UI code. This is handy for
  103402. writing command-line utilities, e.g. on linux boxes which don't have some
  103403. of the UI libraries installed.
  103404. (On mac and windows, this won't generally make much difference to the build).
  103405. */
  103406. #ifndef JUCE_BUILD_GUI_CLASSES
  103407. #define JUCE_BUILD_GUI_CLASSES 1
  103408. #endif
  103409. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  103410. */
  103411. #ifndef JUCE_WEB_BROWSER
  103412. #define JUCE_WEB_BROWSER 1
  103413. #endif
  103414. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  103415. codebase - you might need to use this if you're linking to some of these libraries
  103416. yourself.
  103417. */
  103418. #ifndef JUCE_INCLUDE_ZLIB_CODE
  103419. #define JUCE_INCLUDE_ZLIB_CODE 1
  103420. #endif
  103421. #ifndef JUCE_INCLUDE_FLAC_CODE
  103422. #define JUCE_INCLUDE_FLAC_CODE 1
  103423. #endif
  103424. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  103425. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  103426. #endif
  103427. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  103428. #define JUCE_INCLUDE_PNGLIB_CODE 1
  103429. #endif
  103430. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  103431. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  103432. #endif
  103433. /** Enable this to add extra memory-leak info to the new and delete operators.
  103434. (Currently, this only affects Windows builds in debug mode).
  103435. */
  103436. #ifndef JUCE_CHECK_MEMORY_LEAKS
  103437. #define JUCE_CHECK_MEMORY_LEAKS 1
  103438. #endif
  103439. /** Enable this to turn on juce's internal catching of exceptions.
  103440. Turning it off will avoid any exception catching. With it on, all exceptions
  103441. are passed to the JUCEApplication::unhandledException() callback for logging.
  103442. */
  103443. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  103444. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  103445. #endif
  103446. /** If this macro is set, the Juce String class will use unicode as its
  103447. internal representation. If it isn't set, it'll use ANSI.
  103448. */
  103449. #ifndef JUCE_STRINGS_ARE_UNICODE
  103450. #define JUCE_STRINGS_ARE_UNICODE 1
  103451. #endif
  103452. #endif
  103453. /********* End of inlined file: juce_Config.h *********/
  103454. #define VERSION "1.2.1"
  103455. #define FLAC__NO_DLL 1
  103456. #ifdef _MSC_VER
  103457. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4312)
  103458. #endif
  103459. #if ! (defined (_WIN32) || defined (_WIN64) || defined (LINUX))
  103460. #define FLAC__SYS_DARWIN 1
  103461. #endif
  103462. /********* End of inlined file: juce_FlacHeader.h *********/
  103463. #if JUCE_USE_FLAC
  103464. #if HAVE_CONFIG_H
  103465. # include <config.h>
  103466. #endif
  103467. #include <math.h>
  103468. #ifndef FLAC__INTEGER_ONLY_LIBRARY
  103469. #ifndef M_PI
  103470. /* math.h in VC++ doesn't seem to have this (how Microsoft is that?) */
  103471. #define M_PI 3.14159265358979323846
  103472. #endif
  103473. void FLAC__window_bartlett(FLAC__real *window, const FLAC__int32 L)
  103474. {
  103475. const FLAC__int32 N = L - 1;
  103476. FLAC__int32 n;
  103477. if (L & 1) {
  103478. for (n = 0; n <= N/2; n++)
  103479. window[n] = 2.0f * n / (float)N;
  103480. for (; n <= N; n++)
  103481. window[n] = 2.0f - 2.0f * n / (float)N;
  103482. }
  103483. else {
  103484. for (n = 0; n <= L/2-1; n++)
  103485. window[n] = 2.0f * n / (float)N;
  103486. for (; n <= N; n++)
  103487. window[n] = 2.0f - 2.0f * (N-n) / (float)N;
  103488. }
  103489. }
  103490. void FLAC__window_bartlett_hann(FLAC__real *window, const FLAC__int32 L)
  103491. {
  103492. const FLAC__int32 N = L - 1;
  103493. FLAC__int32 n;
  103494. for (n = 0; n < L; n++)
  103495. 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)));
  103496. }
  103497. void FLAC__window_blackman(FLAC__real *window, const FLAC__int32 L)
  103498. {
  103499. const FLAC__int32 N = L - 1;
  103500. FLAC__int32 n;
  103501. for (n = 0; n < L; n++)
  103502. window[n] = (FLAC__real)(0.42f - 0.5f * cos(2.0f * M_PI * n / N) + 0.08f * cos(4.0f * M_PI * n / N));
  103503. }
  103504. /* 4-term -92dB side-lobe */
  103505. void FLAC__window_blackman_harris_4term_92db_sidelobe(FLAC__real *window, const FLAC__int32 L)
  103506. {
  103507. const FLAC__int32 N = L - 1;
  103508. FLAC__int32 n;
  103509. for (n = 0; n <= N; n++)
  103510. 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));
  103511. }
  103512. void FLAC__window_connes(FLAC__real *window, const FLAC__int32 L)
  103513. {
  103514. const FLAC__int32 N = L - 1;
  103515. const double N2 = (double)N / 2.;
  103516. FLAC__int32 n;
  103517. for (n = 0; n <= N; n++) {
  103518. double k = ((double)n - N2) / N2;
  103519. k = 1.0f - k * k;
  103520. window[n] = (FLAC__real)(k * k);
  103521. }
  103522. }
  103523. void FLAC__window_flattop(FLAC__real *window, const FLAC__int32 L)
  103524. {
  103525. const FLAC__int32 N = L - 1;
  103526. FLAC__int32 n;
  103527. for (n = 0; n < L; n++)
  103528. 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));
  103529. }
  103530. void FLAC__window_gauss(FLAC__real *window, const FLAC__int32 L, const FLAC__real stddev)
  103531. {
  103532. const FLAC__int32 N = L - 1;
  103533. const double N2 = (double)N / 2.;
  103534. FLAC__int32 n;
  103535. for (n = 0; n <= N; n++) {
  103536. const double k = ((double)n - N2) / (stddev * N2);
  103537. window[n] = (FLAC__real)exp(-0.5f * k * k);
  103538. }
  103539. }
  103540. void FLAC__window_hamming(FLAC__real *window, const FLAC__int32 L)
  103541. {
  103542. const FLAC__int32 N = L - 1;
  103543. FLAC__int32 n;
  103544. for (n = 0; n < L; n++)
  103545. window[n] = (FLAC__real)(0.54f - 0.46f * cos(2.0f * M_PI * n / N));
  103546. }
  103547. void FLAC__window_hann(FLAC__real *window, const FLAC__int32 L)
  103548. {
  103549. const FLAC__int32 N = L - 1;
  103550. FLAC__int32 n;
  103551. for (n = 0; n < L; n++)
  103552. window[n] = (FLAC__real)(0.5f - 0.5f * cos(2.0f * M_PI * n / N));
  103553. }
  103554. void FLAC__window_kaiser_bessel(FLAC__real *window, const FLAC__int32 L)
  103555. {
  103556. const FLAC__int32 N = L - 1;
  103557. FLAC__int32 n;
  103558. for (n = 0; n < L; n++)
  103559. 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));
  103560. }
  103561. void FLAC__window_nuttall(FLAC__real *window, const FLAC__int32 L)
  103562. {
  103563. const FLAC__int32 N = L - 1;
  103564. FLAC__int32 n;
  103565. for (n = 0; n < L; n++)
  103566. 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));
  103567. }
  103568. void FLAC__window_rectangle(FLAC__real *window, const FLAC__int32 L)
  103569. {
  103570. FLAC__int32 n;
  103571. for (n = 0; n < L; n++)
  103572. window[n] = 1.0f;
  103573. }
  103574. void FLAC__window_triangle(FLAC__real *window, const FLAC__int32 L)
  103575. {
  103576. FLAC__int32 n;
  103577. if (L & 1) {
  103578. for (n = 1; n <= L+1/2; n++)
  103579. window[n-1] = 2.0f * n / ((float)L + 1.0f);
  103580. for (; n <= L; n++)
  103581. window[n-1] = - (float)(2 * (L - n + 1)) / ((float)L + 1.0f);
  103582. }
  103583. else {
  103584. for (n = 1; n <= L/2; n++)
  103585. window[n-1] = 2.0f * n / (float)L;
  103586. for (; n <= L; n++)
  103587. window[n-1] = ((float)(2 * (L - n)) + 1.0f) / (float)L;
  103588. }
  103589. }
  103590. void FLAC__window_tukey(FLAC__real *window, const FLAC__int32 L, const FLAC__real p)
  103591. {
  103592. if (p <= 0.0)
  103593. FLAC__window_rectangle(window, L);
  103594. else if (p >= 1.0)
  103595. FLAC__window_hann(window, L);
  103596. else {
  103597. const FLAC__int32 Np = (FLAC__int32)(p / 2.0f * L) - 1;
  103598. FLAC__int32 n;
  103599. /* start with rectangle... */
  103600. FLAC__window_rectangle(window, L);
  103601. /* ...replace ends with hann */
  103602. if (Np > 0) {
  103603. for (n = 0; n <= Np; n++) {
  103604. window[n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * n / Np));
  103605. window[L-Np-1+n] = (FLAC__real)(0.5f - 0.5f * cos(M_PI * (n+Np) / Np));
  103606. }
  103607. }
  103608. }
  103609. }
  103610. void FLAC__window_welch(FLAC__real *window, const FLAC__int32 L)
  103611. {
  103612. const FLAC__int32 N = L - 1;
  103613. const double N2 = (double)N / 2.;
  103614. FLAC__int32 n;
  103615. for (n = 0; n <= N; n++) {
  103616. const double k = ((double)n - N2) / N2;
  103617. window[n] = (FLAC__real)(1.0f - k * k);
  103618. }
  103619. }
  103620. #endif /* !defined FLAC__INTEGER_ONLY_LIBRARY */
  103621. #endif
  103622. /********* End of inlined file: window_flac.c *********/
  103623. #else
  103624. #include <FLAC/all.h>
  103625. #endif
  103626. }
  103627. #ifdef _MSC_VER
  103628. #pragma warning (pop)
  103629. #endif
  103630. BEGIN_JUCE_NAMESPACE
  103631. using namespace FlacNamespace;
  103632. #define flacFormatName TRANS("FLAC file")
  103633. static const tchar* const flacExtensions[] = { T(".flac"), 0 };
  103634. class FlacReader : public AudioFormatReader
  103635. {
  103636. FLAC__StreamDecoder* decoder;
  103637. AudioSampleBuffer reservoir;
  103638. int reservoirStart, samplesInReservoir;
  103639. bool ok, scanningForLength;
  103640. public:
  103641. FlacReader (InputStream* const in)
  103642. : AudioFormatReader (in, flacFormatName),
  103643. reservoir (2, 0),
  103644. reservoirStart (0),
  103645. samplesInReservoir (0),
  103646. scanningForLength (false)
  103647. {
  103648. using namespace FlacNamespace;
  103649. lengthInSamples = 0;
  103650. decoder = FLAC__stream_decoder_new();
  103651. ok = FLAC__stream_decoder_init_stream (decoder,
  103652. readCallback_, seekCallback_, tellCallback_, lengthCallback_,
  103653. eofCallback_, writeCallback_, metadataCallback_, errorCallback_,
  103654. (void*) this) == FLAC__STREAM_DECODER_INIT_STATUS_OK;
  103655. if (ok)
  103656. {
  103657. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  103658. if (lengthInSamples == 0 && sampleRate > 0)
  103659. {
  103660. // the length hasn't been stored in the metadata, so we'll need to
  103661. // work it out the length the hard way, by scanning the whole file..
  103662. scanningForLength = true;
  103663. FLAC__stream_decoder_process_until_end_of_stream (decoder);
  103664. scanningForLength = false;
  103665. const int64 tempLength = lengthInSamples;
  103666. FLAC__stream_decoder_reset (decoder);
  103667. FLAC__stream_decoder_process_until_end_of_metadata (decoder);
  103668. lengthInSamples = tempLength;
  103669. }
  103670. }
  103671. }
  103672. ~FlacReader()
  103673. {
  103674. FLAC__stream_decoder_delete (decoder);
  103675. }
  103676. void useMetadata (const FLAC__StreamMetadata_StreamInfo& info)
  103677. {
  103678. sampleRate = info.sample_rate;
  103679. bitsPerSample = info.bits_per_sample;
  103680. lengthInSamples = (unsigned int) info.total_samples;
  103681. numChannels = info.channels;
  103682. reservoir.setSize (numChannels, 2 * info.max_blocksize, false, false, true);
  103683. }
  103684. // returns the number of samples read
  103685. bool read (int** destSamples,
  103686. int64 startSampleInFile,
  103687. int numSamples)
  103688. {
  103689. using namespace FlacNamespace;
  103690. if (! ok)
  103691. return false;
  103692. int offset = 0;
  103693. if (startSampleInFile < 0)
  103694. {
  103695. const int num = (int) jmin ((int64) numSamples, -startSampleInFile);
  103696. int n = 0;
  103697. while (destSamples[n] != 0)
  103698. {
  103699. zeromem (destSamples[n], sizeof (int) * num);
  103700. ++n;
  103701. }
  103702. offset += num;
  103703. startSampleInFile += num;
  103704. numSamples -= num;
  103705. }
  103706. while (numSamples > 0)
  103707. {
  103708. if (startSampleInFile >= reservoirStart
  103709. && startSampleInFile < reservoirStart + samplesInReservoir)
  103710. {
  103711. const int num = (int) jmin ((int64) numSamples,
  103712. reservoirStart + samplesInReservoir - startSampleInFile);
  103713. jassert (num > 0);
  103714. int n = 0;
  103715. while (destSamples[n] != 0)
  103716. {
  103717. memcpy (destSamples[n] + offset,
  103718. reservoir.getSampleData (n, (int) (startSampleInFile - reservoirStart)),
  103719. sizeof (int) * num);
  103720. ++n;
  103721. }
  103722. offset += num;
  103723. startSampleInFile += num;
  103724. numSamples -= num;
  103725. }
  103726. else
  103727. {
  103728. if (startSampleInFile < reservoirStart
  103729. || startSampleInFile > reservoirStart + jmax (samplesInReservoir, 511))
  103730. {
  103731. if (startSampleInFile >= (int) lengthInSamples)
  103732. {
  103733. samplesInReservoir = 0;
  103734. break;
  103735. }
  103736. // had some problems with flac crashing if the read pos is aligned more
  103737. // accurately than this. Probably fixed in newer versions of the library, though.
  103738. reservoirStart = (int) (startSampleInFile & ~511);
  103739. FLAC__stream_decoder_seek_absolute (decoder, (FLAC__uint64) reservoirStart);
  103740. }
  103741. else
  103742. {
  103743. reservoirStart += samplesInReservoir;
  103744. }
  103745. samplesInReservoir = 0;
  103746. FLAC__stream_decoder_process_single (decoder);
  103747. if (samplesInReservoir == 0)
  103748. break;
  103749. }
  103750. }
  103751. if (numSamples > 0)
  103752. {
  103753. int n = 0;
  103754. while (destSamples[n] != 0)
  103755. {
  103756. zeromem (destSamples[n] + offset, sizeof (int) * numSamples);
  103757. ++n;
  103758. }
  103759. }
  103760. return true;
  103761. }
  103762. void useSamples (const FLAC__int32* const buffer[], int numSamples)
  103763. {
  103764. if (scanningForLength)
  103765. {
  103766. lengthInSamples += numSamples;
  103767. }
  103768. else
  103769. {
  103770. if (numSamples > reservoir.getNumSamples())
  103771. reservoir.setSize (numChannels, numSamples, false, false, true);
  103772. const int bitsToShift = 32 - bitsPerSample;
  103773. for (int i = 0; i < (int) numChannels; ++i)
  103774. {
  103775. const FLAC__int32* src = buffer[i];
  103776. int n = i;
  103777. while (src == 0 && n > 0)
  103778. src = buffer [--n];
  103779. if (src != 0)
  103780. {
  103781. int* dest = (int*) reservoir.getSampleData(i);
  103782. for (int j = 0; j < numSamples; ++j)
  103783. dest[j] = src[j] << bitsToShift;
  103784. }
  103785. }
  103786. samplesInReservoir = numSamples;
  103787. }
  103788. }
  103789. static FLAC__StreamDecoderReadStatus readCallback_ (const FLAC__StreamDecoder*, FLAC__byte buffer[], size_t* bytes, void* client_data)
  103790. {
  103791. *bytes = (unsigned int) ((const FlacReader*) client_data)->input->read (buffer, (int) *bytes);
  103792. return FLAC__STREAM_DECODER_READ_STATUS_CONTINUE;
  103793. }
  103794. static FLAC__StreamDecoderSeekStatus seekCallback_ (const FLAC__StreamDecoder*, FLAC__uint64 absolute_byte_offset, void* client_data)
  103795. {
  103796. ((const FlacReader*) client_data)->input->setPosition ((int) absolute_byte_offset);
  103797. return FLAC__STREAM_DECODER_SEEK_STATUS_OK;
  103798. }
  103799. static FLAC__StreamDecoderTellStatus tellCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* absolute_byte_offset, void* client_data)
  103800. {
  103801. *absolute_byte_offset = ((const FlacReader*) client_data)->input->getPosition();
  103802. return FLAC__STREAM_DECODER_TELL_STATUS_OK;
  103803. }
  103804. static FLAC__StreamDecoderLengthStatus lengthCallback_ (const FLAC__StreamDecoder*, FLAC__uint64* stream_length, void* client_data)
  103805. {
  103806. *stream_length = ((const FlacReader*) client_data)->input->getTotalLength();
  103807. return FLAC__STREAM_DECODER_LENGTH_STATUS_OK;
  103808. }
  103809. static FLAC__bool eofCallback_ (const FLAC__StreamDecoder*, void* client_data)
  103810. {
  103811. return ((const FlacReader*) client_data)->input->isExhausted();
  103812. }
  103813. static FLAC__StreamDecoderWriteStatus writeCallback_ (const FLAC__StreamDecoder*,
  103814. const FLAC__Frame* frame,
  103815. const FLAC__int32* const buffer[],
  103816. void* client_data)
  103817. {
  103818. ((FlacReader*) client_data)->useSamples (buffer, frame->header.blocksize);
  103819. return FLAC__STREAM_DECODER_WRITE_STATUS_CONTINUE;
  103820. }
  103821. static void metadataCallback_ (const FLAC__StreamDecoder*,
  103822. const FLAC__StreamMetadata* metadata,
  103823. void* client_data)
  103824. {
  103825. ((FlacReader*) client_data)->useMetadata (metadata->data.stream_info);
  103826. }
  103827. static void errorCallback_ (const FLAC__StreamDecoder*, FLAC__StreamDecoderErrorStatus, void*)
  103828. {
  103829. }
  103830. juce_UseDebuggingNewOperator
  103831. };
  103832. class FlacWriter : public AudioFormatWriter
  103833. {
  103834. FLAC__StreamEncoder* encoder;
  103835. MemoryBlock temp;
  103836. public:
  103837. bool ok;
  103838. FlacWriter (OutputStream* const out,
  103839. const double sampleRate,
  103840. const int numChannels,
  103841. const int bitsPerSample_)
  103842. : AudioFormatWriter (out, flacFormatName,
  103843. sampleRate,
  103844. numChannels,
  103845. bitsPerSample_)
  103846. {
  103847. using namespace FlacNamespace;
  103848. encoder = FLAC__stream_encoder_new();
  103849. FLAC__stream_encoder_set_do_mid_side_stereo (encoder, numChannels == 2);
  103850. FLAC__stream_encoder_set_loose_mid_side_stereo (encoder, numChannels == 2);
  103851. FLAC__stream_encoder_set_channels (encoder, numChannels);
  103852. FLAC__stream_encoder_set_bits_per_sample (encoder, jmin (24, bitsPerSample));
  103853. FLAC__stream_encoder_set_sample_rate (encoder, (unsigned int) sampleRate);
  103854. FLAC__stream_encoder_set_blocksize (encoder, 2048);
  103855. FLAC__stream_encoder_set_do_escape_coding (encoder, true);
  103856. ok = FLAC__stream_encoder_init_stream (encoder,
  103857. encodeWriteCallback, encodeSeekCallback,
  103858. encodeTellCallback, encodeMetadataCallback,
  103859. (void*) this) == FLAC__STREAM_ENCODER_INIT_STATUS_OK;
  103860. }
  103861. ~FlacWriter()
  103862. {
  103863. if (ok)
  103864. {
  103865. FLAC__stream_encoder_finish (encoder);
  103866. output->flush();
  103867. }
  103868. else
  103869. {
  103870. output = 0; // to stop the base class deleting this, as it needs to be returned
  103871. // to the caller of createWriter()
  103872. }
  103873. FLAC__stream_encoder_delete (encoder);
  103874. }
  103875. bool write (const int** samplesToWrite, int numSamples)
  103876. {
  103877. if (! ok)
  103878. return false;
  103879. int* buf[3];
  103880. const int bitsToShift = 32 - bitsPerSample;
  103881. if (bitsToShift > 0)
  103882. {
  103883. const int numChannels = (samplesToWrite[1] == 0) ? 1 : 2;
  103884. temp.setSize (sizeof (int) * numSamples * numChannels);
  103885. buf[0] = (int*) temp.getData();
  103886. buf[1] = buf[0] + numSamples;
  103887. buf[2] = 0;
  103888. for (int i = numChannels; --i >= 0;)
  103889. {
  103890. if (samplesToWrite[i] != 0)
  103891. {
  103892. for (int j = 0; j < numSamples; ++j)
  103893. buf [i][j] = (samplesToWrite [i][j] >> bitsToShift);
  103894. }
  103895. }
  103896. samplesToWrite = (const int**) buf;
  103897. }
  103898. return FLAC__stream_encoder_process (encoder,
  103899. (const FLAC__int32**) samplesToWrite,
  103900. numSamples) != 0;
  103901. }
  103902. bool writeData (const void* const data, const int size) const
  103903. {
  103904. return output->write (data, size);
  103905. }
  103906. static void packUint32 (FLAC__uint32 val, FLAC__byte* b, const int bytes)
  103907. {
  103908. b += bytes;
  103909. for (int i = 0; i < bytes; ++i)
  103910. {
  103911. *(--b) = (FLAC__byte) (val & 0xff);
  103912. val >>= 8;
  103913. }
  103914. }
  103915. void writeMetaData (const FLAC__StreamMetadata* metadata)
  103916. {
  103917. using namespace FlacNamespace;
  103918. const FLAC__StreamMetadata_StreamInfo& info = metadata->data.stream_info;
  103919. unsigned char buffer [FLAC__STREAM_METADATA_STREAMINFO_LENGTH];
  103920. const unsigned int channelsMinus1 = info.channels - 1;
  103921. const unsigned int bitsMinus1 = info.bits_per_sample - 1;
  103922. packUint32 (info.min_blocksize, buffer, 2);
  103923. packUint32 (info.max_blocksize, buffer + 2, 2);
  103924. packUint32 (info.min_framesize, buffer + 4, 3);
  103925. packUint32 (info.max_framesize, buffer + 7, 3);
  103926. buffer[10] = (uint8) ((info.sample_rate >> 12) & 0xff);
  103927. buffer[11] = (uint8) ((info.sample_rate >> 4) & 0xff);
  103928. buffer[12] = (uint8) (((info.sample_rate & 0x0f) << 4) | (channelsMinus1 << 1) | (bitsMinus1 >> 4));
  103929. buffer[13] = (FLAC__byte) (((bitsMinus1 & 0x0f) << 4) | (unsigned int) ((info.total_samples >> 32) & 0x0f));
  103930. packUint32 ((FLAC__uint32) info.total_samples, buffer + 14, 4);
  103931. memcpy (buffer + 18, info.md5sum, 16);
  103932. const bool ok = output->setPosition (4);
  103933. (void) ok;
  103934. // if this fails, you've given it an output stream that can't seek! It needs
  103935. // to be able to seek back to write the header
  103936. jassert (ok);
  103937. output->writeIntBigEndian (FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  103938. output->write (buffer, FLAC__STREAM_METADATA_STREAMINFO_LENGTH);
  103939. }
  103940. static FLAC__StreamEncoderWriteStatus encodeWriteCallback (const FLAC__StreamEncoder*,
  103941. const FLAC__byte buffer[],
  103942. size_t bytes,
  103943. unsigned int /*samples*/,
  103944. unsigned int /*current_frame*/,
  103945. void* client_data)
  103946. {
  103947. using namespace FlacNamespace;
  103948. return ((FlacWriter*) client_data)->writeData (buffer, (int) bytes)
  103949. ? FLAC__STREAM_ENCODER_WRITE_STATUS_OK
  103950. : FLAC__STREAM_ENCODER_WRITE_STATUS_FATAL_ERROR;
  103951. }
  103952. static FLAC__StreamEncoderSeekStatus encodeSeekCallback (const FLAC__StreamEncoder*, FLAC__uint64, void*)
  103953. {
  103954. return FLAC__STREAM_ENCODER_SEEK_STATUS_UNSUPPORTED;
  103955. }
  103956. static FLAC__StreamEncoderTellStatus encodeTellCallback (const FLAC__StreamEncoder*, FLAC__uint64*, void*)
  103957. {
  103958. return FLAC__STREAM_ENCODER_TELL_STATUS_UNSUPPORTED;
  103959. }
  103960. static void encodeMetadataCallback (const FLAC__StreamEncoder*,
  103961. const FLAC__StreamMetadata* metadata,
  103962. void* client_data)
  103963. {
  103964. ((FlacWriter*) client_data)->writeMetaData (metadata);
  103965. }
  103966. juce_UseDebuggingNewOperator
  103967. };
  103968. FlacAudioFormat::FlacAudioFormat()
  103969. : AudioFormat (flacFormatName, (const tchar**) flacExtensions)
  103970. {
  103971. }
  103972. FlacAudioFormat::~FlacAudioFormat()
  103973. {
  103974. }
  103975. const Array <int> FlacAudioFormat::getPossibleSampleRates()
  103976. {
  103977. const int rates[] = { 22050, 32000, 44100, 48000, 88200, 96000, 0 };
  103978. return Array <int> (rates);
  103979. }
  103980. const Array <int> FlacAudioFormat::getPossibleBitDepths()
  103981. {
  103982. const int depths[] = { 16, 24, 0 };
  103983. return Array <int> (depths);
  103984. }
  103985. bool FlacAudioFormat::canDoStereo()
  103986. {
  103987. return true;
  103988. }
  103989. bool FlacAudioFormat::canDoMono()
  103990. {
  103991. return true;
  103992. }
  103993. bool FlacAudioFormat::isCompressed()
  103994. {
  103995. return true;
  103996. }
  103997. AudioFormatReader* FlacAudioFormat::createReaderFor (InputStream* in,
  103998. const bool deleteStreamIfOpeningFails)
  103999. {
  104000. FlacReader* r = new FlacReader (in);
  104001. if (r->sampleRate == 0)
  104002. {
  104003. if (! deleteStreamIfOpeningFails)
  104004. r->input = 0;
  104005. deleteAndZero (r);
  104006. }
  104007. return r;
  104008. }
  104009. AudioFormatWriter* FlacAudioFormat::createWriterFor (OutputStream* out,
  104010. double sampleRate,
  104011. unsigned int numberOfChannels,
  104012. int bitsPerSample,
  104013. const StringPairArray& /*metadataValues*/,
  104014. int /*qualityOptionIndex*/)
  104015. {
  104016. if (getPossibleBitDepths().contains (bitsPerSample))
  104017. {
  104018. FlacWriter* w = new FlacWriter (out,
  104019. sampleRate,
  104020. numberOfChannels,
  104021. bitsPerSample);
  104022. if (! w->ok)
  104023. deleteAndZero (w);
  104024. return w;
  104025. }
  104026. return 0;
  104027. }
  104028. END_JUCE_NAMESPACE
  104029. #endif
  104030. /********* End of inlined file: juce_FlacAudioFormat.cpp *********/
  104031. /********* Start of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  104032. /********* Start of inlined file: juce_Config.h *********/
  104033. #ifndef __JUCE_CONFIG_JUCEHEADER__
  104034. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  104035. /*
  104036. This file contains macros that enable/disable various JUCE features.
  104037. */
  104038. /** The name of the namespace that all Juce classes and functions will be
  104039. put inside. If this is not defined, no namespace will be used.
  104040. */
  104041. #ifndef JUCE_NAMESPACE
  104042. #define JUCE_NAMESPACE juce
  104043. #endif
  104044. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  104045. but if you define this value, you can override this can force it to be true or
  104046. false.
  104047. */
  104048. #ifndef JUCE_FORCE_DEBUG
  104049. //#define JUCE_FORCE_DEBUG 1
  104050. #endif
  104051. /** If this flag is enabled, the the jassert and jassertfalse macros will
  104052. always use Logger::writeToLog() to write a message when an assertion happens.
  104053. Enabling it will also leave this turned on in release builds. When it's disabled,
  104054. however, the jassert and jassertfalse macros will not be compiled in a
  104055. release build.
  104056. @see jassert, jassertfalse, Logger
  104057. */
  104058. #ifndef JUCE_LOG_ASSERTIONS
  104059. // #define JUCE_LOG_ASSERTIONS 1
  104060. #endif
  104061. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  104062. which the ASIOAudioIODevice class can't be built. See the comments in the
  104063. ASIOAudioIODevice class's header file for more info about this.
  104064. (This only affects a Win32 build)
  104065. */
  104066. #ifndef JUCE_ASIO
  104067. #define JUCE_ASIO 1
  104068. #endif
  104069. /** Comment out this macro to disable building of ALSA device support on Linux.
  104070. */
  104071. #ifndef JUCE_ALSA
  104072. #define JUCE_ALSA 1
  104073. #endif
  104074. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  104075. have the SDK installed.
  104076. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  104077. classes will be unavailable.
  104078. On Windows, if you enable this, you'll need to have the QuickTime SDK
  104079. installed, and its header files will need to be on your include path.
  104080. */
  104081. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  104082. #define JUCE_QUICKTIME 1
  104083. #endif
  104084. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  104085. have the appropriate headers and libraries available. If it's not enabled, the
  104086. OpenGLComponent class will be unavailable.
  104087. */
  104088. #ifndef JUCE_OPENGL
  104089. #define JUCE_OPENGL 1
  104090. #endif
  104091. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  104092. If you're not going to need either of these formats, turn off the flags to
  104093. avoid bloating your codebase with them.
  104094. */
  104095. #ifndef JUCE_USE_FLAC
  104096. #define JUCE_USE_FLAC 1
  104097. #endif
  104098. #ifndef JUCE_USE_OGGVORBIS
  104099. #define JUCE_USE_OGGVORBIS 1
  104100. #endif
  104101. /** This flag lets you enable support for CD-burning. You might want to disable
  104102. it to build without the MS SDK under windows.
  104103. */
  104104. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  104105. #define JUCE_USE_CDBURNER 1
  104106. #endif
  104107. /** Enabling this macro means that all regions that get repainted will have a coloured
  104108. line drawn around them.
  104109. This is handy if you're trying to optimise drawing, because it lets you easily see
  104110. when anything is being repainted unnecessarily.
  104111. */
  104112. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  104113. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  104114. #endif
  104115. /** Enable this under Linux to use Xinerama for multi-monitor support.
  104116. */
  104117. #ifndef JUCE_USE_XINERAMA
  104118. #define JUCE_USE_XINERAMA 1
  104119. #endif
  104120. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  104121. */
  104122. #ifndef JUCE_USE_XSHM
  104123. #define JUCE_USE_XSHM 1
  104124. #endif
  104125. /** Enabling this builds support for VST audio plugins.
  104126. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  104127. */
  104128. #ifndef JUCE_PLUGINHOST_VST
  104129. // #define JUCE_PLUGINHOST_VST 1
  104130. #endif
  104131. /** Enabling this builds support for AudioUnit audio plugins.
  104132. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  104133. */
  104134. #ifndef JUCE_PLUGINHOST_AU
  104135. // #define JUCE_PLUGINHOST_AU 1
  104136. #endif
  104137. /** Disabling this will avoid linking to any UI code. This is handy for
  104138. writing command-line utilities, e.g. on linux boxes which don't have some
  104139. of the UI libraries installed.
  104140. (On mac and windows, this won't generally make much difference to the build).
  104141. */
  104142. #ifndef JUCE_BUILD_GUI_CLASSES
  104143. #define JUCE_BUILD_GUI_CLASSES 1
  104144. #endif
  104145. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  104146. */
  104147. #ifndef JUCE_WEB_BROWSER
  104148. #define JUCE_WEB_BROWSER 1
  104149. #endif
  104150. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  104151. codebase - you might need to use this if you're linking to some of these libraries
  104152. yourself.
  104153. */
  104154. #ifndef JUCE_INCLUDE_ZLIB_CODE
  104155. #define JUCE_INCLUDE_ZLIB_CODE 1
  104156. #endif
  104157. #ifndef JUCE_INCLUDE_FLAC_CODE
  104158. #define JUCE_INCLUDE_FLAC_CODE 1
  104159. #endif
  104160. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  104161. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  104162. #endif
  104163. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  104164. #define JUCE_INCLUDE_PNGLIB_CODE 1
  104165. #endif
  104166. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  104167. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  104168. #endif
  104169. /** Enable this to add extra memory-leak info to the new and delete operators.
  104170. (Currently, this only affects Windows builds in debug mode).
  104171. */
  104172. #ifndef JUCE_CHECK_MEMORY_LEAKS
  104173. #define JUCE_CHECK_MEMORY_LEAKS 1
  104174. #endif
  104175. /** Enable this to turn on juce's internal catching of exceptions.
  104176. Turning it off will avoid any exception catching. With it on, all exceptions
  104177. are passed to the JUCEApplication::unhandledException() callback for logging.
  104178. */
  104179. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  104180. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  104181. #endif
  104182. /** If this macro is set, the Juce String class will use unicode as its
  104183. internal representation. If it isn't set, it'll use ANSI.
  104184. */
  104185. #ifndef JUCE_STRINGS_ARE_UNICODE
  104186. #define JUCE_STRINGS_ARE_UNICODE 1
  104187. #endif
  104188. #endif
  104189. /********* End of inlined file: juce_Config.h *********/
  104190. #if JUCE_USE_OGGVORBIS
  104191. #if JUCE_MAC
  104192. #define __MACOSX__ 1
  104193. #endif
  104194. namespace OggVorbisNamespace
  104195. {
  104196. #if JUCE_INCLUDE_OGGVORBIS_CODE
  104197. /********* Start of inlined file: vorbisenc.h *********/
  104198. #ifndef _OV_ENC_H_
  104199. #define _OV_ENC_H_
  104200. #ifdef __cplusplus
  104201. extern "C"
  104202. {
  104203. #endif /* __cplusplus */
  104204. /********* Start of inlined file: codec.h *********/
  104205. #ifndef _vorbis_codec_h_
  104206. #define _vorbis_codec_h_
  104207. #ifdef __cplusplus
  104208. extern "C"
  104209. {
  104210. #endif /* __cplusplus */
  104211. /********* Start of inlined file: ogg.h *********/
  104212. #ifndef _OGG_H
  104213. #define _OGG_H
  104214. #ifdef __cplusplus
  104215. extern "C" {
  104216. #endif
  104217. /********* Start of inlined file: os_types.h *********/
  104218. #ifndef _OS_TYPES_H
  104219. #define _OS_TYPES_H
  104220. /* make it easy on the folks that want to compile the libs with a
  104221. different malloc than stdlib */
  104222. #define _ogg_malloc malloc
  104223. #define _ogg_calloc calloc
  104224. #define _ogg_realloc realloc
  104225. #define _ogg_free free
  104226. #if defined(_WIN32)
  104227. # if defined(__CYGWIN__)
  104228. # include <_G_config.h>
  104229. typedef _G_int64_t ogg_int64_t;
  104230. typedef _G_int32_t ogg_int32_t;
  104231. typedef _G_uint32_t ogg_uint32_t;
  104232. typedef _G_int16_t ogg_int16_t;
  104233. typedef _G_uint16_t ogg_uint16_t;
  104234. # elif defined(__MINGW32__)
  104235. typedef short ogg_int16_t;
  104236. typedef unsigned short ogg_uint16_t;
  104237. typedef int ogg_int32_t;
  104238. typedef unsigned int ogg_uint32_t;
  104239. typedef long long ogg_int64_t;
  104240. typedef unsigned long long ogg_uint64_t;
  104241. # elif defined(__MWERKS__)
  104242. typedef long long ogg_int64_t;
  104243. typedef int ogg_int32_t;
  104244. typedef unsigned int ogg_uint32_t;
  104245. typedef short ogg_int16_t;
  104246. typedef unsigned short ogg_uint16_t;
  104247. # else
  104248. /* MSVC/Borland */
  104249. typedef __int64 ogg_int64_t;
  104250. typedef __int32 ogg_int32_t;
  104251. typedef unsigned __int32 ogg_uint32_t;
  104252. typedef __int16 ogg_int16_t;
  104253. typedef unsigned __int16 ogg_uint16_t;
  104254. # endif
  104255. #elif defined(__MACOS__)
  104256. # include <sys/types.h>
  104257. typedef SInt16 ogg_int16_t;
  104258. typedef UInt16 ogg_uint16_t;
  104259. typedef SInt32 ogg_int32_t;
  104260. typedef UInt32 ogg_uint32_t;
  104261. typedef SInt64 ogg_int64_t;
  104262. #elif defined(__MACOSX__) /* MacOS X Framework build */
  104263. # include <sys/types.h>
  104264. typedef int16_t ogg_int16_t;
  104265. typedef u_int16_t ogg_uint16_t;
  104266. typedef int32_t ogg_int32_t;
  104267. typedef u_int32_t ogg_uint32_t;
  104268. typedef int64_t ogg_int64_t;
  104269. #elif defined(__BEOS__)
  104270. /* Be */
  104271. # include <inttypes.h>
  104272. typedef int16_t ogg_int16_t;
  104273. typedef u_int16_t ogg_uint16_t;
  104274. typedef int32_t ogg_int32_t;
  104275. typedef u_int32_t ogg_uint32_t;
  104276. typedef int64_t ogg_int64_t;
  104277. #elif defined (__EMX__)
  104278. /* OS/2 GCC */
  104279. typedef short ogg_int16_t;
  104280. typedef unsigned short ogg_uint16_t;
  104281. typedef int ogg_int32_t;
  104282. typedef unsigned int ogg_uint32_t;
  104283. typedef long long ogg_int64_t;
  104284. #elif defined (DJGPP)
  104285. /* DJGPP */
  104286. typedef short ogg_int16_t;
  104287. typedef int ogg_int32_t;
  104288. typedef unsigned int ogg_uint32_t;
  104289. typedef long long ogg_int64_t;
  104290. #elif defined(R5900)
  104291. /* PS2 EE */
  104292. typedef long ogg_int64_t;
  104293. typedef int ogg_int32_t;
  104294. typedef unsigned ogg_uint32_t;
  104295. typedef short ogg_int16_t;
  104296. #elif defined(__SYMBIAN32__)
  104297. /* Symbian GCC */
  104298. typedef signed short ogg_int16_t;
  104299. typedef unsigned short ogg_uint16_t;
  104300. typedef signed int ogg_int32_t;
  104301. typedef unsigned int ogg_uint32_t;
  104302. typedef long long int ogg_int64_t;
  104303. #else
  104304. # include <sys/types.h>
  104305. /********* Start of inlined file: config_types.h *********/
  104306. #ifndef __CONFIG_TYPES_H__
  104307. #define __CONFIG_TYPES_H__
  104308. typedef int16_t ogg_int16_t;
  104309. typedef unsigned short ogg_uint16_t;
  104310. typedef int32_t ogg_int32_t;
  104311. typedef unsigned int ogg_uint32_t;
  104312. typedef int64_t ogg_int64_t;
  104313. #endif
  104314. /********* End of inlined file: config_types.h *********/
  104315. #endif
  104316. #endif /* _OS_TYPES_H */
  104317. /********* End of inlined file: os_types.h *********/
  104318. typedef struct {
  104319. long endbyte;
  104320. int endbit;
  104321. unsigned char *buffer;
  104322. unsigned char *ptr;
  104323. long storage;
  104324. } oggpack_buffer;
  104325. /* ogg_page is used to encapsulate the data in one Ogg bitstream page *****/
  104326. typedef struct {
  104327. unsigned char *header;
  104328. long header_len;
  104329. unsigned char *body;
  104330. long body_len;
  104331. } ogg_page;
  104332. ogg_uint32_t ogg_bitreverse(ogg_uint32_t x){
  104333. x= ((x>>16)&0x0000ffffUL) | ((x<<16)&0xffff0000UL);
  104334. x= ((x>> 8)&0x00ff00ffUL) | ((x<< 8)&0xff00ff00UL);
  104335. x= ((x>> 4)&0x0f0f0f0fUL) | ((x<< 4)&0xf0f0f0f0UL);
  104336. x= ((x>> 2)&0x33333333UL) | ((x<< 2)&0xccccccccUL);
  104337. return((x>> 1)&0x55555555UL) | ((x<< 1)&0xaaaaaaaaUL);
  104338. }
  104339. /* ogg_stream_state contains the current encode/decode state of a logical
  104340. Ogg bitstream **********************************************************/
  104341. typedef struct {
  104342. unsigned char *body_data; /* bytes from packet bodies */
  104343. long body_storage; /* storage elements allocated */
  104344. long body_fill; /* elements stored; fill mark */
  104345. long body_returned; /* elements of fill returned */
  104346. int *lacing_vals; /* The values that will go to the segment table */
  104347. ogg_int64_t *granule_vals; /* granulepos values for headers. Not compact
  104348. this way, but it is simple coupled to the
  104349. lacing fifo */
  104350. long lacing_storage;
  104351. long lacing_fill;
  104352. long lacing_packet;
  104353. long lacing_returned;
  104354. unsigned char header[282]; /* working space for header encode */
  104355. int header_fill;
  104356. int e_o_s; /* set when we have buffered the last packet in the
  104357. logical bitstream */
  104358. int b_o_s; /* set after we've written the initial page
  104359. of a logical bitstream */
  104360. long serialno;
  104361. long pageno;
  104362. ogg_int64_t packetno; /* sequence number for decode; the framing
  104363. knows where there's a hole in the data,
  104364. but we need coupling so that the codec
  104365. (which is in a seperate abstraction
  104366. layer) also knows about the gap */
  104367. ogg_int64_t granulepos;
  104368. } ogg_stream_state;
  104369. /* ogg_packet is used to encapsulate the data and metadata belonging
  104370. to a single raw Ogg/Vorbis packet *************************************/
  104371. typedef struct {
  104372. unsigned char *packet;
  104373. long bytes;
  104374. long b_o_s;
  104375. long e_o_s;
  104376. ogg_int64_t granulepos;
  104377. ogg_int64_t packetno; /* sequence number for decode; the framing
  104378. knows where there's a hole in the data,
  104379. but we need coupling so that the codec
  104380. (which is in a seperate abstraction
  104381. layer) also knows about the gap */
  104382. } ogg_packet;
  104383. typedef struct {
  104384. unsigned char *data;
  104385. int storage;
  104386. int fill;
  104387. int returned;
  104388. int unsynced;
  104389. int headerbytes;
  104390. int bodybytes;
  104391. } ogg_sync_state;
  104392. /* Ogg BITSTREAM PRIMITIVES: bitstream ************************/
  104393. extern void oggpack_writeinit(oggpack_buffer *b);
  104394. extern void oggpack_writetrunc(oggpack_buffer *b,long bits);
  104395. extern void oggpack_writealign(oggpack_buffer *b);
  104396. extern void oggpack_writecopy(oggpack_buffer *b,void *source,long bits);
  104397. extern void oggpack_reset(oggpack_buffer *b);
  104398. extern void oggpack_writeclear(oggpack_buffer *b);
  104399. extern void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  104400. extern void oggpack_write(oggpack_buffer *b,unsigned long value,int bits);
  104401. extern long oggpack_look(oggpack_buffer *b,int bits);
  104402. extern long oggpack_look1(oggpack_buffer *b);
  104403. extern void oggpack_adv(oggpack_buffer *b,int bits);
  104404. extern void oggpack_adv1(oggpack_buffer *b);
  104405. extern long oggpack_read(oggpack_buffer *b,int bits);
  104406. extern long oggpack_read1(oggpack_buffer *b);
  104407. extern long oggpack_bytes(oggpack_buffer *b);
  104408. extern long oggpack_bits(oggpack_buffer *b);
  104409. extern unsigned char *oggpack_get_buffer(oggpack_buffer *b);
  104410. extern void oggpackB_writeinit(oggpack_buffer *b);
  104411. extern void oggpackB_writetrunc(oggpack_buffer *b,long bits);
  104412. extern void oggpackB_writealign(oggpack_buffer *b);
  104413. extern void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits);
  104414. extern void oggpackB_reset(oggpack_buffer *b);
  104415. extern void oggpackB_writeclear(oggpack_buffer *b);
  104416. extern void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes);
  104417. extern void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits);
  104418. extern long oggpackB_look(oggpack_buffer *b,int bits);
  104419. extern long oggpackB_look1(oggpack_buffer *b);
  104420. extern void oggpackB_adv(oggpack_buffer *b,int bits);
  104421. extern void oggpackB_adv1(oggpack_buffer *b);
  104422. extern long oggpackB_read(oggpack_buffer *b,int bits);
  104423. extern long oggpackB_read1(oggpack_buffer *b);
  104424. extern long oggpackB_bytes(oggpack_buffer *b);
  104425. extern long oggpackB_bits(oggpack_buffer *b);
  104426. extern unsigned char *oggpackB_get_buffer(oggpack_buffer *b);
  104427. /* Ogg BITSTREAM PRIMITIVES: encoding **************************/
  104428. extern int ogg_stream_packetin(ogg_stream_state *os, ogg_packet *op);
  104429. extern int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og);
  104430. extern int ogg_stream_flush(ogg_stream_state *os, ogg_page *og);
  104431. /* Ogg BITSTREAM PRIMITIVES: decoding **************************/
  104432. extern int ogg_sync_init(ogg_sync_state *oy);
  104433. extern int ogg_sync_clear(ogg_sync_state *oy);
  104434. extern int ogg_sync_reset(ogg_sync_state *oy);
  104435. extern int ogg_sync_destroy(ogg_sync_state *oy);
  104436. extern char *ogg_sync_buffer(ogg_sync_state *oy, long size);
  104437. extern int ogg_sync_wrote(ogg_sync_state *oy, long bytes);
  104438. extern long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og);
  104439. extern int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og);
  104440. extern int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og);
  104441. extern int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op);
  104442. extern int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op);
  104443. /* Ogg BITSTREAM PRIMITIVES: general ***************************/
  104444. extern int ogg_stream_init(ogg_stream_state *os,int serialno);
  104445. extern int ogg_stream_clear(ogg_stream_state *os);
  104446. extern int ogg_stream_reset(ogg_stream_state *os);
  104447. extern int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno);
  104448. extern int ogg_stream_destroy(ogg_stream_state *os);
  104449. extern int ogg_stream_eos(ogg_stream_state *os);
  104450. extern void ogg_page_checksum_set(ogg_page *og);
  104451. extern int ogg_page_version(ogg_page *og);
  104452. extern int ogg_page_continued(ogg_page *og);
  104453. extern int ogg_page_bos(ogg_page *og);
  104454. extern int ogg_page_eos(ogg_page *og);
  104455. extern ogg_int64_t ogg_page_granulepos(ogg_page *og);
  104456. extern int ogg_page_serialno(ogg_page *og);
  104457. extern long ogg_page_pageno(ogg_page *og);
  104458. extern int ogg_page_packets(ogg_page *og);
  104459. extern void ogg_packet_clear(ogg_packet *op);
  104460. #ifdef __cplusplus
  104461. }
  104462. #endif
  104463. #endif /* _OGG_H */
  104464. /********* End of inlined file: ogg.h *********/
  104465. typedef struct vorbis_info{
  104466. int version;
  104467. int channels;
  104468. long rate;
  104469. /* The below bitrate declarations are *hints*.
  104470. Combinations of the three values carry the following implications:
  104471. all three set to the same value:
  104472. implies a fixed rate bitstream
  104473. only nominal set:
  104474. implies a VBR stream that averages the nominal bitrate. No hard
  104475. upper/lower limit
  104476. upper and or lower set:
  104477. implies a VBR bitstream that obeys the bitrate limits. nominal
  104478. may also be set to give a nominal rate.
  104479. none set:
  104480. the coder does not care to speculate.
  104481. */
  104482. long bitrate_upper;
  104483. long bitrate_nominal;
  104484. long bitrate_lower;
  104485. long bitrate_window;
  104486. void *codec_setup;
  104487. } vorbis_info;
  104488. /* vorbis_dsp_state buffers the current vorbis audio
  104489. analysis/synthesis state. The DSP state belongs to a specific
  104490. logical bitstream ****************************************************/
  104491. typedef struct vorbis_dsp_state{
  104492. int analysisp;
  104493. vorbis_info *vi;
  104494. float **pcm;
  104495. float **pcmret;
  104496. int pcm_storage;
  104497. int pcm_current;
  104498. int pcm_returned;
  104499. int preextrapolate;
  104500. int eofflag;
  104501. long lW;
  104502. long W;
  104503. long nW;
  104504. long centerW;
  104505. ogg_int64_t granulepos;
  104506. ogg_int64_t sequence;
  104507. ogg_int64_t glue_bits;
  104508. ogg_int64_t time_bits;
  104509. ogg_int64_t floor_bits;
  104510. ogg_int64_t res_bits;
  104511. void *backend_state;
  104512. } vorbis_dsp_state;
  104513. typedef struct vorbis_block{
  104514. /* necessary stream state for linking to the framing abstraction */
  104515. float **pcm; /* this is a pointer into local storage */
  104516. oggpack_buffer opb;
  104517. long lW;
  104518. long W;
  104519. long nW;
  104520. int pcmend;
  104521. int mode;
  104522. int eofflag;
  104523. ogg_int64_t granulepos;
  104524. ogg_int64_t sequence;
  104525. vorbis_dsp_state *vd; /* For read-only access of configuration */
  104526. /* local storage to avoid remallocing; it's up to the mapping to
  104527. structure it */
  104528. void *localstore;
  104529. long localtop;
  104530. long localalloc;
  104531. long totaluse;
  104532. struct alloc_chain *reap;
  104533. /* bitmetrics for the frame */
  104534. long glue_bits;
  104535. long time_bits;
  104536. long floor_bits;
  104537. long res_bits;
  104538. void *internal;
  104539. } vorbis_block;
  104540. /* vorbis_block is a single block of data to be processed as part of
  104541. the analysis/synthesis stream; it belongs to a specific logical
  104542. bitstream, but is independant from other vorbis_blocks belonging to
  104543. that logical bitstream. *************************************************/
  104544. struct alloc_chain{
  104545. void *ptr;
  104546. struct alloc_chain *next;
  104547. };
  104548. /* vorbis_info contains all the setup information specific to the
  104549. specific compression/decompression mode in progress (eg,
  104550. psychoacoustic settings, channel setup, options, codebook
  104551. etc). vorbis_info and substructures are in backends.h.
  104552. *********************************************************************/
  104553. /* the comments are not part of vorbis_info so that vorbis_info can be
  104554. static storage */
  104555. typedef struct vorbis_comment{
  104556. /* unlimited user comment fields. libvorbis writes 'libvorbis'
  104557. whatever vendor is set to in encode */
  104558. char **user_comments;
  104559. int *comment_lengths;
  104560. int comments;
  104561. char *vendor;
  104562. } vorbis_comment;
  104563. /* libvorbis encodes in two abstraction layers; first we perform DSP
  104564. and produce a packet (see docs/analysis.txt). The packet is then
  104565. coded into a framed OggSquish bitstream by the second layer (see
  104566. docs/framing.txt). Decode is the reverse process; we sync/frame
  104567. the bitstream and extract individual packets, then decode the
  104568. packet back into PCM audio.
  104569. The extra framing/packetizing is used in streaming formats, such as
  104570. files. Over the net (such as with UDP), the framing and
  104571. packetization aren't necessary as they're provided by the transport
  104572. and the streaming layer is not used */
  104573. /* Vorbis PRIMITIVES: general ***************************************/
  104574. extern void vorbis_info_init(vorbis_info *vi);
  104575. extern void vorbis_info_clear(vorbis_info *vi);
  104576. extern int vorbis_info_blocksize(vorbis_info *vi,int zo);
  104577. extern void vorbis_comment_init(vorbis_comment *vc);
  104578. extern void vorbis_comment_add(vorbis_comment *vc, char *comment);
  104579. extern void vorbis_comment_add_tag(vorbis_comment *vc,
  104580. char *tag, char *contents);
  104581. extern char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count);
  104582. extern int vorbis_comment_query_count(vorbis_comment *vc, char *tag);
  104583. extern void vorbis_comment_clear(vorbis_comment *vc);
  104584. extern int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb);
  104585. extern int vorbis_block_clear(vorbis_block *vb);
  104586. extern void vorbis_dsp_clear(vorbis_dsp_state *v);
  104587. extern double vorbis_granule_time(vorbis_dsp_state *v,
  104588. ogg_int64_t granulepos);
  104589. /* Vorbis PRIMITIVES: analysis/DSP layer ****************************/
  104590. extern int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi);
  104591. extern int vorbis_commentheader_out(vorbis_comment *vc, ogg_packet *op);
  104592. extern int vorbis_analysis_headerout(vorbis_dsp_state *v,
  104593. vorbis_comment *vc,
  104594. ogg_packet *op,
  104595. ogg_packet *op_comm,
  104596. ogg_packet *op_code);
  104597. extern float **vorbis_analysis_buffer(vorbis_dsp_state *v,int vals);
  104598. extern int vorbis_analysis_wrote(vorbis_dsp_state *v,int vals);
  104599. extern int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb);
  104600. extern int vorbis_analysis(vorbis_block *vb,ogg_packet *op);
  104601. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  104602. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,
  104603. ogg_packet *op);
  104604. /* Vorbis PRIMITIVES: synthesis layer *******************************/
  104605. extern int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,
  104606. ogg_packet *op);
  104607. extern int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi);
  104608. extern int vorbis_synthesis_restart(vorbis_dsp_state *v);
  104609. extern int vorbis_synthesis(vorbis_block *vb,ogg_packet *op);
  104610. extern int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op);
  104611. extern int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb);
  104612. extern int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm);
  104613. extern int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm);
  104614. extern int vorbis_synthesis_read(vorbis_dsp_state *v,int samples);
  104615. extern long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op);
  104616. extern int vorbis_synthesis_halfrate(vorbis_info *v,int flag);
  104617. extern int vorbis_synthesis_halfrate_p(vorbis_info *v);
  104618. /* Vorbis ERRORS and return codes ***********************************/
  104619. #define OV_FALSE -1
  104620. #define OV_EOF -2
  104621. #define OV_HOLE -3
  104622. #define OV_EREAD -128
  104623. #define OV_EFAULT -129
  104624. #define OV_EIMPL -130
  104625. #define OV_EINVAL -131
  104626. #define OV_ENOTVORBIS -132
  104627. #define OV_EBADHEADER -133
  104628. #define OV_EVERSION -134
  104629. #define OV_ENOTAUDIO -135
  104630. #define OV_EBADPACKET -136
  104631. #define OV_EBADLINK -137
  104632. #define OV_ENOSEEK -138
  104633. #ifdef __cplusplus
  104634. }
  104635. #endif /* __cplusplus */
  104636. #endif
  104637. /********* End of inlined file: codec.h *********/
  104638. extern int vorbis_encode_init(vorbis_info *vi,
  104639. long channels,
  104640. long rate,
  104641. long max_bitrate,
  104642. long nominal_bitrate,
  104643. long min_bitrate);
  104644. extern int vorbis_encode_setup_managed(vorbis_info *vi,
  104645. long channels,
  104646. long rate,
  104647. long max_bitrate,
  104648. long nominal_bitrate,
  104649. long min_bitrate);
  104650. extern int vorbis_encode_setup_vbr(vorbis_info *vi,
  104651. long channels,
  104652. long rate,
  104653. float quality /* quality level from 0. (lo) to 1. (hi) */
  104654. );
  104655. extern int vorbis_encode_init_vbr(vorbis_info *vi,
  104656. long channels,
  104657. long rate,
  104658. float base_quality /* quality level from 0. (lo) to 1. (hi) */
  104659. );
  104660. extern int vorbis_encode_setup_init(vorbis_info *vi);
  104661. extern int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg);
  104662. /* deprecated rate management supported only for compatability */
  104663. #define OV_ECTL_RATEMANAGE_GET 0x10
  104664. #define OV_ECTL_RATEMANAGE_SET 0x11
  104665. #define OV_ECTL_RATEMANAGE_AVG 0x12
  104666. #define OV_ECTL_RATEMANAGE_HARD 0x13
  104667. struct ovectl_ratemanage_arg {
  104668. int management_active;
  104669. long bitrate_hard_min;
  104670. long bitrate_hard_max;
  104671. double bitrate_hard_window;
  104672. long bitrate_av_lo;
  104673. long bitrate_av_hi;
  104674. double bitrate_av_window;
  104675. double bitrate_av_window_center;
  104676. };
  104677. /* new rate setup */
  104678. #define OV_ECTL_RATEMANAGE2_GET 0x14
  104679. #define OV_ECTL_RATEMANAGE2_SET 0x15
  104680. struct ovectl_ratemanage2_arg {
  104681. int management_active;
  104682. long bitrate_limit_min_kbps;
  104683. long bitrate_limit_max_kbps;
  104684. long bitrate_limit_reservoir_bits;
  104685. double bitrate_limit_reservoir_bias;
  104686. long bitrate_average_kbps;
  104687. double bitrate_average_damping;
  104688. };
  104689. #define OV_ECTL_LOWPASS_GET 0x20
  104690. #define OV_ECTL_LOWPASS_SET 0x21
  104691. #define OV_ECTL_IBLOCK_GET 0x30
  104692. #define OV_ECTL_IBLOCK_SET 0x31
  104693. #ifdef __cplusplus
  104694. }
  104695. #endif /* __cplusplus */
  104696. #endif
  104697. /********* End of inlined file: vorbisenc.h *********/
  104698. /********* Start of inlined file: vorbisfile.h *********/
  104699. #ifndef _OV_FILE_H_
  104700. #define _OV_FILE_H_
  104701. #ifdef __cplusplus
  104702. extern "C"
  104703. {
  104704. #endif /* __cplusplus */
  104705. #include <stdio.h>
  104706. /* The function prototypes for the callbacks are basically the same as for
  104707. * the stdio functions fread, fseek, fclose, ftell.
  104708. * The one difference is that the FILE * arguments have been replaced with
  104709. * a void * - this is to be used as a pointer to whatever internal data these
  104710. * functions might need. In the stdio case, it's just a FILE * cast to a void *
  104711. *
  104712. * If you use other functions, check the docs for these functions and return
  104713. * the right values. For seek_func(), you *MUST* return -1 if the stream is
  104714. * unseekable
  104715. */
  104716. typedef struct {
  104717. size_t (*read_func) (void *ptr, size_t size, size_t nmemb, void *datasource);
  104718. int (*seek_func) (void *datasource, ogg_int64_t offset, int whence);
  104719. int (*close_func) (void *datasource);
  104720. long (*tell_func) (void *datasource);
  104721. } ov_callbacks;
  104722. #define NOTOPEN 0
  104723. #define PARTOPEN 1
  104724. #define OPENED 2
  104725. #define STREAMSET 3
  104726. #define INITSET 4
  104727. typedef struct OggVorbis_File {
  104728. void *datasource; /* Pointer to a FILE *, etc. */
  104729. int seekable;
  104730. ogg_int64_t offset;
  104731. ogg_int64_t end;
  104732. ogg_sync_state oy;
  104733. /* If the FILE handle isn't seekable (eg, a pipe), only the current
  104734. stream appears */
  104735. int links;
  104736. ogg_int64_t *offsets;
  104737. ogg_int64_t *dataoffsets;
  104738. long *serialnos;
  104739. ogg_int64_t *pcmlengths; /* overloaded to maintain binary
  104740. compatability; x2 size, stores both
  104741. beginning and end values */
  104742. vorbis_info *vi;
  104743. vorbis_comment *vc;
  104744. /* Decoding working state local storage */
  104745. ogg_int64_t pcm_offset;
  104746. int ready_state;
  104747. long current_serialno;
  104748. int current_link;
  104749. double bittrack;
  104750. double samptrack;
  104751. ogg_stream_state os; /* take physical pages, weld into a logical
  104752. stream of packets */
  104753. vorbis_dsp_state vd; /* central working state for the packet->PCM decoder */
  104754. vorbis_block vb; /* local working space for packet->PCM decode */
  104755. ov_callbacks callbacks;
  104756. } OggVorbis_File;
  104757. extern int ov_clear(OggVorbis_File *vf);
  104758. extern int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  104759. extern int ov_open_callbacks(void *datasource, OggVorbis_File *vf,
  104760. char *initial, long ibytes, ov_callbacks callbacks);
  104761. extern int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes);
  104762. extern int ov_test_callbacks(void *datasource, OggVorbis_File *vf,
  104763. char *initial, long ibytes, ov_callbacks callbacks);
  104764. extern int ov_test_open(OggVorbis_File *vf);
  104765. extern long ov_bitrate(OggVorbis_File *vf,int i);
  104766. extern long ov_bitrate_instant(OggVorbis_File *vf);
  104767. extern long ov_streams(OggVorbis_File *vf);
  104768. extern long ov_seekable(OggVorbis_File *vf);
  104769. extern long ov_serialnumber(OggVorbis_File *vf,int i);
  104770. extern ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i);
  104771. extern ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i);
  104772. extern double ov_time_total(OggVorbis_File *vf,int i);
  104773. extern int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos);
  104774. extern int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos);
  104775. extern int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos);
  104776. extern int ov_time_seek(OggVorbis_File *vf,double pos);
  104777. extern int ov_time_seek_page(OggVorbis_File *vf,double pos);
  104778. extern int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104779. extern int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104780. extern int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos);
  104781. extern int ov_time_seek_lap(OggVorbis_File *vf,double pos);
  104782. extern int ov_time_seek_page_lap(OggVorbis_File *vf,double pos);
  104783. extern ogg_int64_t ov_raw_tell(OggVorbis_File *vf);
  104784. extern ogg_int64_t ov_pcm_tell(OggVorbis_File *vf);
  104785. extern double ov_time_tell(OggVorbis_File *vf);
  104786. extern vorbis_info *ov_info(OggVorbis_File *vf,int link);
  104787. extern vorbis_comment *ov_comment(OggVorbis_File *vf,int link);
  104788. extern long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int samples,
  104789. int *bitstream);
  104790. extern long ov_read(OggVorbis_File *vf,char *buffer,int length,
  104791. int bigendianp,int word,int sgned,int *bitstream);
  104792. extern int ov_crosslap(OggVorbis_File *vf1,OggVorbis_File *vf2);
  104793. extern int ov_halfrate(OggVorbis_File *vf,int flag);
  104794. extern int ov_halfrate_p(OggVorbis_File *vf);
  104795. #ifdef __cplusplus
  104796. }
  104797. #endif /* __cplusplus */
  104798. #endif
  104799. /********* End of inlined file: vorbisfile.h *********/
  104800. /********* Start of inlined file: bitwise.c *********/
  104801. /* We're 'LSb' endian; if we write a word but read individual bits,
  104802. then we'll read the lsb first */
  104803. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  104804. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  104805. // tasks..
  104806. /********* Start of inlined file: juce_Config.h *********/
  104807. #ifndef __JUCE_CONFIG_JUCEHEADER__
  104808. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  104809. /*
  104810. This file contains macros that enable/disable various JUCE features.
  104811. */
  104812. /** The name of the namespace that all Juce classes and functions will be
  104813. put inside. If this is not defined, no namespace will be used.
  104814. */
  104815. #ifndef JUCE_NAMESPACE
  104816. #define JUCE_NAMESPACE juce
  104817. #endif
  104818. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  104819. but if you define this value, you can override this can force it to be true or
  104820. false.
  104821. */
  104822. #ifndef JUCE_FORCE_DEBUG
  104823. //#define JUCE_FORCE_DEBUG 1
  104824. #endif
  104825. /** If this flag is enabled, the the jassert and jassertfalse macros will
  104826. always use Logger::writeToLog() to write a message when an assertion happens.
  104827. Enabling it will also leave this turned on in release builds. When it's disabled,
  104828. however, the jassert and jassertfalse macros will not be compiled in a
  104829. release build.
  104830. @see jassert, jassertfalse, Logger
  104831. */
  104832. #ifndef JUCE_LOG_ASSERTIONS
  104833. // #define JUCE_LOG_ASSERTIONS 1
  104834. #endif
  104835. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  104836. which the ASIOAudioIODevice class can't be built. See the comments in the
  104837. ASIOAudioIODevice class's header file for more info about this.
  104838. (This only affects a Win32 build)
  104839. */
  104840. #ifndef JUCE_ASIO
  104841. #define JUCE_ASIO 1
  104842. #endif
  104843. /** Comment out this macro to disable building of ALSA device support on Linux.
  104844. */
  104845. #ifndef JUCE_ALSA
  104846. #define JUCE_ALSA 1
  104847. #endif
  104848. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  104849. have the SDK installed.
  104850. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  104851. classes will be unavailable.
  104852. On Windows, if you enable this, you'll need to have the QuickTime SDK
  104853. installed, and its header files will need to be on your include path.
  104854. */
  104855. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  104856. #define JUCE_QUICKTIME 1
  104857. #endif
  104858. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  104859. have the appropriate headers and libraries available. If it's not enabled, the
  104860. OpenGLComponent class will be unavailable.
  104861. */
  104862. #ifndef JUCE_OPENGL
  104863. #define JUCE_OPENGL 1
  104864. #endif
  104865. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  104866. If you're not going to need either of these formats, turn off the flags to
  104867. avoid bloating your codebase with them.
  104868. */
  104869. #ifndef JUCE_USE_FLAC
  104870. #define JUCE_USE_FLAC 1
  104871. #endif
  104872. #ifndef JUCE_USE_OGGVORBIS
  104873. #define JUCE_USE_OGGVORBIS 1
  104874. #endif
  104875. /** This flag lets you enable support for CD-burning. You might want to disable
  104876. it to build without the MS SDK under windows.
  104877. */
  104878. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  104879. #define JUCE_USE_CDBURNER 1
  104880. #endif
  104881. /** Enabling this macro means that all regions that get repainted will have a coloured
  104882. line drawn around them.
  104883. This is handy if you're trying to optimise drawing, because it lets you easily see
  104884. when anything is being repainted unnecessarily.
  104885. */
  104886. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  104887. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  104888. #endif
  104889. /** Enable this under Linux to use Xinerama for multi-monitor support.
  104890. */
  104891. #ifndef JUCE_USE_XINERAMA
  104892. #define JUCE_USE_XINERAMA 1
  104893. #endif
  104894. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  104895. */
  104896. #ifndef JUCE_USE_XSHM
  104897. #define JUCE_USE_XSHM 1
  104898. #endif
  104899. /** Enabling this builds support for VST audio plugins.
  104900. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  104901. */
  104902. #ifndef JUCE_PLUGINHOST_VST
  104903. // #define JUCE_PLUGINHOST_VST 1
  104904. #endif
  104905. /** Enabling this builds support for AudioUnit audio plugins.
  104906. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  104907. */
  104908. #ifndef JUCE_PLUGINHOST_AU
  104909. // #define JUCE_PLUGINHOST_AU 1
  104910. #endif
  104911. /** Disabling this will avoid linking to any UI code. This is handy for
  104912. writing command-line utilities, e.g. on linux boxes which don't have some
  104913. of the UI libraries installed.
  104914. (On mac and windows, this won't generally make much difference to the build).
  104915. */
  104916. #ifndef JUCE_BUILD_GUI_CLASSES
  104917. #define JUCE_BUILD_GUI_CLASSES 1
  104918. #endif
  104919. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  104920. */
  104921. #ifndef JUCE_WEB_BROWSER
  104922. #define JUCE_WEB_BROWSER 1
  104923. #endif
  104924. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  104925. codebase - you might need to use this if you're linking to some of these libraries
  104926. yourself.
  104927. */
  104928. #ifndef JUCE_INCLUDE_ZLIB_CODE
  104929. #define JUCE_INCLUDE_ZLIB_CODE 1
  104930. #endif
  104931. #ifndef JUCE_INCLUDE_FLAC_CODE
  104932. #define JUCE_INCLUDE_FLAC_CODE 1
  104933. #endif
  104934. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  104935. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  104936. #endif
  104937. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  104938. #define JUCE_INCLUDE_PNGLIB_CODE 1
  104939. #endif
  104940. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  104941. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  104942. #endif
  104943. /** Enable this to add extra memory-leak info to the new and delete operators.
  104944. (Currently, this only affects Windows builds in debug mode).
  104945. */
  104946. #ifndef JUCE_CHECK_MEMORY_LEAKS
  104947. #define JUCE_CHECK_MEMORY_LEAKS 1
  104948. #endif
  104949. /** Enable this to turn on juce's internal catching of exceptions.
  104950. Turning it off will avoid any exception catching. With it on, all exceptions
  104951. are passed to the JUCEApplication::unhandledException() callback for logging.
  104952. */
  104953. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  104954. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  104955. #endif
  104956. /** If this macro is set, the Juce String class will use unicode as its
  104957. internal representation. If it isn't set, it'll use ANSI.
  104958. */
  104959. #ifndef JUCE_STRINGS_ARE_UNICODE
  104960. #define JUCE_STRINGS_ARE_UNICODE 1
  104961. #endif
  104962. #endif
  104963. /********* End of inlined file: juce_Config.h *********/
  104964. #ifdef _MSC_VER
  104965. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  104966. #endif
  104967. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  104968. #if JUCE_USE_OGGVORBIS
  104969. #include <string.h>
  104970. #include <stdlib.h>
  104971. #define BUFFER_INCREMENT 256
  104972. static const unsigned long mask[]=
  104973. {0x00000000,0x00000001,0x00000003,0x00000007,0x0000000f,
  104974. 0x0000001f,0x0000003f,0x0000007f,0x000000ff,0x000001ff,
  104975. 0x000003ff,0x000007ff,0x00000fff,0x00001fff,0x00003fff,
  104976. 0x00007fff,0x0000ffff,0x0001ffff,0x0003ffff,0x0007ffff,
  104977. 0x000fffff,0x001fffff,0x003fffff,0x007fffff,0x00ffffff,
  104978. 0x01ffffff,0x03ffffff,0x07ffffff,0x0fffffff,0x1fffffff,
  104979. 0x3fffffff,0x7fffffff,0xffffffff };
  104980. static const unsigned int mask8B[]=
  104981. {0x00,0x80,0xc0,0xe0,0xf0,0xf8,0xfc,0xfe,0xff};
  104982. void oggpack_writeinit(oggpack_buffer *b){
  104983. memset(b,0,sizeof(*b));
  104984. b->ptr=b->buffer=(unsigned char*) _ogg_malloc(BUFFER_INCREMENT);
  104985. b->buffer[0]='\0';
  104986. b->storage=BUFFER_INCREMENT;
  104987. }
  104988. void oggpackB_writeinit(oggpack_buffer *b){
  104989. oggpack_writeinit(b);
  104990. }
  104991. void oggpack_writetrunc(oggpack_buffer *b,long bits){
  104992. long bytes=bits>>3;
  104993. bits-=bytes*8;
  104994. b->ptr=b->buffer+bytes;
  104995. b->endbit=bits;
  104996. b->endbyte=bytes;
  104997. *b->ptr&=mask[bits];
  104998. }
  104999. void oggpackB_writetrunc(oggpack_buffer *b,long bits){
  105000. long bytes=bits>>3;
  105001. bits-=bytes*8;
  105002. b->ptr=b->buffer+bytes;
  105003. b->endbit=bits;
  105004. b->endbyte=bytes;
  105005. *b->ptr&=mask8B[bits];
  105006. }
  105007. /* Takes only up to 32 bits. */
  105008. void oggpack_write(oggpack_buffer *b,unsigned long value,int bits){
  105009. if(b->endbyte+4>=b->storage){
  105010. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  105011. b->storage+=BUFFER_INCREMENT;
  105012. b->ptr=b->buffer+b->endbyte;
  105013. }
  105014. value&=mask[bits];
  105015. bits+=b->endbit;
  105016. b->ptr[0]|=value<<b->endbit;
  105017. if(bits>=8){
  105018. b->ptr[1]=(unsigned char)(value>>(8-b->endbit));
  105019. if(bits>=16){
  105020. b->ptr[2]=(unsigned char)(value>>(16-b->endbit));
  105021. if(bits>=24){
  105022. b->ptr[3]=(unsigned char)(value>>(24-b->endbit));
  105023. if(bits>=32){
  105024. if(b->endbit)
  105025. b->ptr[4]=(unsigned char)(value>>(32-b->endbit));
  105026. else
  105027. b->ptr[4]=0;
  105028. }
  105029. }
  105030. }
  105031. }
  105032. b->endbyte+=bits/8;
  105033. b->ptr+=bits/8;
  105034. b->endbit=bits&7;
  105035. }
  105036. /* Takes only up to 32 bits. */
  105037. void oggpackB_write(oggpack_buffer *b,unsigned long value,int bits){
  105038. if(b->endbyte+4>=b->storage){
  105039. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage+BUFFER_INCREMENT);
  105040. b->storage+=BUFFER_INCREMENT;
  105041. b->ptr=b->buffer+b->endbyte;
  105042. }
  105043. value=(value&mask[bits])<<(32-bits);
  105044. bits+=b->endbit;
  105045. b->ptr[0]|=value>>(24+b->endbit);
  105046. if(bits>=8){
  105047. b->ptr[1]=(unsigned char)(value>>(16+b->endbit));
  105048. if(bits>=16){
  105049. b->ptr[2]=(unsigned char)(value>>(8+b->endbit));
  105050. if(bits>=24){
  105051. b->ptr[3]=(unsigned char)(value>>(b->endbit));
  105052. if(bits>=32){
  105053. if(b->endbit)
  105054. b->ptr[4]=(unsigned char)(value<<(8-b->endbit));
  105055. else
  105056. b->ptr[4]=0;
  105057. }
  105058. }
  105059. }
  105060. }
  105061. b->endbyte+=bits/8;
  105062. b->ptr+=bits/8;
  105063. b->endbit=bits&7;
  105064. }
  105065. void oggpack_writealign(oggpack_buffer *b){
  105066. int bits=8-b->endbit;
  105067. if(bits<8)
  105068. oggpack_write(b,0,bits);
  105069. }
  105070. void oggpackB_writealign(oggpack_buffer *b){
  105071. int bits=8-b->endbit;
  105072. if(bits<8)
  105073. oggpackB_write(b,0,bits);
  105074. }
  105075. static void oggpack_writecopy_helper(oggpack_buffer *b,
  105076. void *source,
  105077. long bits,
  105078. void (*w)(oggpack_buffer *,
  105079. unsigned long,
  105080. int),
  105081. int msb){
  105082. unsigned char *ptr=(unsigned char *)source;
  105083. long bytes=bits/8;
  105084. bits-=bytes*8;
  105085. if(b->endbit){
  105086. int i;
  105087. /* unaligned copy. Do it the hard way. */
  105088. for(i=0;i<bytes;i++)
  105089. w(b,(unsigned long)(ptr[i]),8);
  105090. }else{
  105091. /* aligned block copy */
  105092. if(b->endbyte+bytes+1>=b->storage){
  105093. b->storage=b->endbyte+bytes+BUFFER_INCREMENT;
  105094. b->buffer=(unsigned char*) _ogg_realloc(b->buffer,b->storage);
  105095. b->ptr=b->buffer+b->endbyte;
  105096. }
  105097. memmove(b->ptr,source,bytes);
  105098. b->ptr+=bytes;
  105099. b->endbyte+=bytes;
  105100. *b->ptr=0;
  105101. }
  105102. if(bits){
  105103. if(msb)
  105104. w(b,(unsigned long)(ptr[bytes]>>(8-bits)),bits);
  105105. else
  105106. w(b,(unsigned long)(ptr[bytes]),bits);
  105107. }
  105108. }
  105109. void oggpack_writecopy(oggpack_buffer *b,void *source,long bits){
  105110. oggpack_writecopy_helper(b,source,bits,oggpack_write,0);
  105111. }
  105112. void oggpackB_writecopy(oggpack_buffer *b,void *source,long bits){
  105113. oggpack_writecopy_helper(b,source,bits,oggpackB_write,1);
  105114. }
  105115. void oggpack_reset(oggpack_buffer *b){
  105116. b->ptr=b->buffer;
  105117. b->buffer[0]=0;
  105118. b->endbit=b->endbyte=0;
  105119. }
  105120. void oggpackB_reset(oggpack_buffer *b){
  105121. oggpack_reset(b);
  105122. }
  105123. void oggpack_writeclear(oggpack_buffer *b){
  105124. _ogg_free(b->buffer);
  105125. memset(b,0,sizeof(*b));
  105126. }
  105127. void oggpackB_writeclear(oggpack_buffer *b){
  105128. oggpack_writeclear(b);
  105129. }
  105130. void oggpack_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  105131. memset(b,0,sizeof(*b));
  105132. b->buffer=b->ptr=buf;
  105133. b->storage=bytes;
  105134. }
  105135. void oggpackB_readinit(oggpack_buffer *b,unsigned char *buf,int bytes){
  105136. oggpack_readinit(b,buf,bytes);
  105137. }
  105138. /* Read in bits without advancing the bitptr; bits <= 32 */
  105139. long oggpack_look(oggpack_buffer *b,int bits){
  105140. unsigned long ret;
  105141. unsigned long m=mask[bits];
  105142. bits+=b->endbit;
  105143. if(b->endbyte+4>=b->storage){
  105144. /* not the main path */
  105145. if(b->endbyte*8+bits>b->storage*8)return(-1);
  105146. }
  105147. ret=b->ptr[0]>>b->endbit;
  105148. if(bits>8){
  105149. ret|=b->ptr[1]<<(8-b->endbit);
  105150. if(bits>16){
  105151. ret|=b->ptr[2]<<(16-b->endbit);
  105152. if(bits>24){
  105153. ret|=b->ptr[3]<<(24-b->endbit);
  105154. if(bits>32 && b->endbit)
  105155. ret|=b->ptr[4]<<(32-b->endbit);
  105156. }
  105157. }
  105158. }
  105159. return(m&ret);
  105160. }
  105161. /* Read in bits without advancing the bitptr; bits <= 32 */
  105162. long oggpackB_look(oggpack_buffer *b,int bits){
  105163. unsigned long ret;
  105164. int m=32-bits;
  105165. bits+=b->endbit;
  105166. if(b->endbyte+4>=b->storage){
  105167. /* not the main path */
  105168. if(b->endbyte*8+bits>b->storage*8)return(-1);
  105169. }
  105170. ret=b->ptr[0]<<(24+b->endbit);
  105171. if(bits>8){
  105172. ret|=b->ptr[1]<<(16+b->endbit);
  105173. if(bits>16){
  105174. ret|=b->ptr[2]<<(8+b->endbit);
  105175. if(bits>24){
  105176. ret|=b->ptr[3]<<(b->endbit);
  105177. if(bits>32 && b->endbit)
  105178. ret|=b->ptr[4]>>(8-b->endbit);
  105179. }
  105180. }
  105181. }
  105182. return ((ret&0xffffffff)>>(m>>1))>>((m+1)>>1);
  105183. }
  105184. long oggpack_look1(oggpack_buffer *b){
  105185. if(b->endbyte>=b->storage)return(-1);
  105186. return((b->ptr[0]>>b->endbit)&1);
  105187. }
  105188. long oggpackB_look1(oggpack_buffer *b){
  105189. if(b->endbyte>=b->storage)return(-1);
  105190. return((b->ptr[0]>>(7-b->endbit))&1);
  105191. }
  105192. void oggpack_adv(oggpack_buffer *b,int bits){
  105193. bits+=b->endbit;
  105194. b->ptr+=bits/8;
  105195. b->endbyte+=bits/8;
  105196. b->endbit=bits&7;
  105197. }
  105198. void oggpackB_adv(oggpack_buffer *b,int bits){
  105199. oggpack_adv(b,bits);
  105200. }
  105201. void oggpack_adv1(oggpack_buffer *b){
  105202. if(++(b->endbit)>7){
  105203. b->endbit=0;
  105204. b->ptr++;
  105205. b->endbyte++;
  105206. }
  105207. }
  105208. void oggpackB_adv1(oggpack_buffer *b){
  105209. oggpack_adv1(b);
  105210. }
  105211. /* bits <= 32 */
  105212. long oggpack_read(oggpack_buffer *b,int bits){
  105213. long ret;
  105214. unsigned long m=mask[bits];
  105215. bits+=b->endbit;
  105216. if(b->endbyte+4>=b->storage){
  105217. /* not the main path */
  105218. ret=-1L;
  105219. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  105220. }
  105221. ret=b->ptr[0]>>b->endbit;
  105222. if(bits>8){
  105223. ret|=b->ptr[1]<<(8-b->endbit);
  105224. if(bits>16){
  105225. ret|=b->ptr[2]<<(16-b->endbit);
  105226. if(bits>24){
  105227. ret|=b->ptr[3]<<(24-b->endbit);
  105228. if(bits>32 && b->endbit){
  105229. ret|=b->ptr[4]<<(32-b->endbit);
  105230. }
  105231. }
  105232. }
  105233. }
  105234. ret&=m;
  105235. overflow:
  105236. b->ptr+=bits/8;
  105237. b->endbyte+=bits/8;
  105238. b->endbit=bits&7;
  105239. return(ret);
  105240. }
  105241. /* bits <= 32 */
  105242. long oggpackB_read(oggpack_buffer *b,int bits){
  105243. long ret;
  105244. long m=32-bits;
  105245. bits+=b->endbit;
  105246. if(b->endbyte+4>=b->storage){
  105247. /* not the main path */
  105248. ret=-1L;
  105249. if(b->endbyte*8+bits>b->storage*8)goto overflow;
  105250. }
  105251. ret=b->ptr[0]<<(24+b->endbit);
  105252. if(bits>8){
  105253. ret|=b->ptr[1]<<(16+b->endbit);
  105254. if(bits>16){
  105255. ret|=b->ptr[2]<<(8+b->endbit);
  105256. if(bits>24){
  105257. ret|=b->ptr[3]<<(b->endbit);
  105258. if(bits>32 && b->endbit)
  105259. ret|=b->ptr[4]>>(8-b->endbit);
  105260. }
  105261. }
  105262. }
  105263. ret=((ret&0xffffffffUL)>>(m>>1))>>((m+1)>>1);
  105264. overflow:
  105265. b->ptr+=bits/8;
  105266. b->endbyte+=bits/8;
  105267. b->endbit=bits&7;
  105268. return(ret);
  105269. }
  105270. long oggpack_read1(oggpack_buffer *b){
  105271. long ret;
  105272. if(b->endbyte>=b->storage){
  105273. /* not the main path */
  105274. ret=-1L;
  105275. goto overflow;
  105276. }
  105277. ret=(b->ptr[0]>>b->endbit)&1;
  105278. overflow:
  105279. b->endbit++;
  105280. if(b->endbit>7){
  105281. b->endbit=0;
  105282. b->ptr++;
  105283. b->endbyte++;
  105284. }
  105285. return(ret);
  105286. }
  105287. long oggpackB_read1(oggpack_buffer *b){
  105288. long ret;
  105289. if(b->endbyte>=b->storage){
  105290. /* not the main path */
  105291. ret=-1L;
  105292. goto overflow;
  105293. }
  105294. ret=(b->ptr[0]>>(7-b->endbit))&1;
  105295. overflow:
  105296. b->endbit++;
  105297. if(b->endbit>7){
  105298. b->endbit=0;
  105299. b->ptr++;
  105300. b->endbyte++;
  105301. }
  105302. return(ret);
  105303. }
  105304. long oggpack_bytes(oggpack_buffer *b){
  105305. return(b->endbyte+(b->endbit+7)/8);
  105306. }
  105307. long oggpack_bits(oggpack_buffer *b){
  105308. return(b->endbyte*8+b->endbit);
  105309. }
  105310. long oggpackB_bytes(oggpack_buffer *b){
  105311. return oggpack_bytes(b);
  105312. }
  105313. long oggpackB_bits(oggpack_buffer *b){
  105314. return oggpack_bits(b);
  105315. }
  105316. unsigned char *oggpack_get_buffer(oggpack_buffer *b){
  105317. return(b->buffer);
  105318. }
  105319. unsigned char *oggpackB_get_buffer(oggpack_buffer *b){
  105320. return oggpack_get_buffer(b);
  105321. }
  105322. /* Self test of the bitwise routines; everything else is based on
  105323. them, so they damned well better be solid. */
  105324. #ifdef _V_SELFTEST
  105325. #include <stdio.h>
  105326. static int ilog(unsigned int v){
  105327. int ret=0;
  105328. while(v){
  105329. ret++;
  105330. v>>=1;
  105331. }
  105332. return(ret);
  105333. }
  105334. oggpack_buffer o;
  105335. oggpack_buffer r;
  105336. void report(char *in){
  105337. fprintf(stderr,"%s",in);
  105338. exit(1);
  105339. }
  105340. void cliptest(unsigned long *b,int vals,int bits,int *comp,int compsize){
  105341. long bytes,i;
  105342. unsigned char *buffer;
  105343. oggpack_reset(&o);
  105344. for(i=0;i<vals;i++)
  105345. oggpack_write(&o,b[i],bits?bits:ilog(b[i]));
  105346. buffer=oggpack_get_buffer(&o);
  105347. bytes=oggpack_bytes(&o);
  105348. if(bytes!=compsize)report("wrong number of bytes!\n");
  105349. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  105350. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  105351. report("wrote incorrect value!\n");
  105352. }
  105353. oggpack_readinit(&r,buffer,bytes);
  105354. for(i=0;i<vals;i++){
  105355. int tbit=bits?bits:ilog(b[i]);
  105356. if(oggpack_look(&r,tbit)==-1)
  105357. report("out of data!\n");
  105358. if(oggpack_look(&r,tbit)!=(b[i]&mask[tbit]))
  105359. report("looked at incorrect value!\n");
  105360. if(tbit==1)
  105361. if(oggpack_look1(&r)!=(b[i]&mask[tbit]))
  105362. report("looked at single bit incorrect value!\n");
  105363. if(tbit==1){
  105364. if(oggpack_read1(&r)!=(b[i]&mask[tbit]))
  105365. report("read incorrect single bit value!\n");
  105366. }else{
  105367. if(oggpack_read(&r,tbit)!=(b[i]&mask[tbit]))
  105368. report("read incorrect value!\n");
  105369. }
  105370. }
  105371. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  105372. }
  105373. void cliptestB(unsigned long *b,int vals,int bits,int *comp,int compsize){
  105374. long bytes,i;
  105375. unsigned char *buffer;
  105376. oggpackB_reset(&o);
  105377. for(i=0;i<vals;i++)
  105378. oggpackB_write(&o,b[i],bits?bits:ilog(b[i]));
  105379. buffer=oggpackB_get_buffer(&o);
  105380. bytes=oggpackB_bytes(&o);
  105381. if(bytes!=compsize)report("wrong number of bytes!\n");
  105382. for(i=0;i<bytes;i++)if(buffer[i]!=comp[i]){
  105383. for(i=0;i<bytes;i++)fprintf(stderr,"%x %x\n",(int)buffer[i],(int)comp[i]);
  105384. report("wrote incorrect value!\n");
  105385. }
  105386. oggpackB_readinit(&r,buffer,bytes);
  105387. for(i=0;i<vals;i++){
  105388. int tbit=bits?bits:ilog(b[i]);
  105389. if(oggpackB_look(&r,tbit)==-1)
  105390. report("out of data!\n");
  105391. if(oggpackB_look(&r,tbit)!=(b[i]&mask[tbit]))
  105392. report("looked at incorrect value!\n");
  105393. if(tbit==1)
  105394. if(oggpackB_look1(&r)!=(b[i]&mask[tbit]))
  105395. report("looked at single bit incorrect value!\n");
  105396. if(tbit==1){
  105397. if(oggpackB_read1(&r)!=(b[i]&mask[tbit]))
  105398. report("read incorrect single bit value!\n");
  105399. }else{
  105400. if(oggpackB_read(&r,tbit)!=(b[i]&mask[tbit]))
  105401. report("read incorrect value!\n");
  105402. }
  105403. }
  105404. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  105405. }
  105406. int main(void){
  105407. unsigned char *buffer;
  105408. long bytes,i;
  105409. static unsigned long testbuffer1[]=
  105410. {18,12,103948,4325,543,76,432,52,3,65,4,56,32,42,34,21,1,23,32,546,456,7,
  105411. 567,56,8,8,55,3,52,342,341,4,265,7,67,86,2199,21,7,1,5,1,4};
  105412. int test1size=43;
  105413. static unsigned long testbuffer2[]=
  105414. {216531625L,1237861823,56732452,131,3212421,12325343,34547562,12313212,
  105415. 1233432,534,5,346435231,14436467,7869299,76326614,167548585,
  105416. 85525151,0,12321,1,349528352};
  105417. int test2size=21;
  105418. static unsigned long testbuffer3[]=
  105419. {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,
  105420. 0,1,30,1,1,1,0,0,1,0,0,0,12,0,11,0,1,0,0,1};
  105421. int test3size=56;
  105422. static unsigned long large[]=
  105423. {2136531625L,2137861823,56732452,131,3212421,12325343,34547562,12313212,
  105424. 1233432,534,5,2146435231,14436467,7869299,76326614,167548585,
  105425. 85525151,0,12321,1,2146528352};
  105426. int onesize=33;
  105427. static int one[33]={146,25,44,151,195,15,153,176,233,131,196,65,85,172,47,40,
  105428. 34,242,223,136,35,222,211,86,171,50,225,135,214,75,172,
  105429. 223,4};
  105430. static int oneB[33]={150,101,131,33,203,15,204,216,105,193,156,65,84,85,222,
  105431. 8,139,145,227,126,34,55,244,171,85,100,39,195,173,18,
  105432. 245,251,128};
  105433. int twosize=6;
  105434. static int two[6]={61,255,255,251,231,29};
  105435. static int twoB[6]={247,63,255,253,249,120};
  105436. int threesize=54;
  105437. static int three[54]={169,2,232,252,91,132,156,36,89,13,123,176,144,32,254,
  105438. 142,224,85,59,121,144,79,124,23,67,90,90,216,79,23,83,
  105439. 58,135,196,61,55,129,183,54,101,100,170,37,127,126,10,
  105440. 100,52,4,14,18,86,77,1};
  105441. static int threeB[54]={206,128,42,153,57,8,183,251,13,89,36,30,32,144,183,
  105442. 130,59,240,121,59,85,223,19,228,180,134,33,107,74,98,
  105443. 233,253,196,135,63,2,110,114,50,155,90,127,37,170,104,
  105444. 200,20,254,4,58,106,176,144,0};
  105445. int foursize=38;
  105446. static int four[38]={18,6,163,252,97,194,104,131,32,1,7,82,137,42,129,11,72,
  105447. 132,60,220,112,8,196,109,64,179,86,9,137,195,208,122,169,
  105448. 28,2,133,0,1};
  105449. static int fourB[38]={36,48,102,83,243,24,52,7,4,35,132,10,145,21,2,93,2,41,
  105450. 1,219,184,16,33,184,54,149,170,132,18,30,29,98,229,67,
  105451. 129,10,4,32};
  105452. int fivesize=45;
  105453. static int five[45]={169,2,126,139,144,172,30,4,80,72,240,59,130,218,73,62,
  105454. 241,24,210,44,4,20,0,248,116,49,135,100,110,130,181,169,
  105455. 84,75,159,2,1,0,132,192,8,0,0,18,22};
  105456. static int fiveB[45]={1,84,145,111,245,100,128,8,56,36,40,71,126,78,213,226,
  105457. 124,105,12,0,133,128,0,162,233,242,67,152,77,205,77,
  105458. 172,150,169,129,79,128,0,6,4,32,0,27,9,0};
  105459. int sixsize=7;
  105460. static int six[7]={17,177,170,242,169,19,148};
  105461. static int sixB[7]={136,141,85,79,149,200,41};
  105462. /* Test read/write together */
  105463. /* Later we test against pregenerated bitstreams */
  105464. oggpack_writeinit(&o);
  105465. fprintf(stderr,"\nSmall preclipped packing (LSb): ");
  105466. cliptest(testbuffer1,test1size,0,one,onesize);
  105467. fprintf(stderr,"ok.");
  105468. fprintf(stderr,"\nNull bit call (LSb): ");
  105469. cliptest(testbuffer3,test3size,0,two,twosize);
  105470. fprintf(stderr,"ok.");
  105471. fprintf(stderr,"\nLarge preclipped packing (LSb): ");
  105472. cliptest(testbuffer2,test2size,0,three,threesize);
  105473. fprintf(stderr,"ok.");
  105474. fprintf(stderr,"\n32 bit preclipped packing (LSb): ");
  105475. oggpack_reset(&o);
  105476. for(i=0;i<test2size;i++)
  105477. oggpack_write(&o,large[i],32);
  105478. buffer=oggpack_get_buffer(&o);
  105479. bytes=oggpack_bytes(&o);
  105480. oggpack_readinit(&r,buffer,bytes);
  105481. for(i=0;i<test2size;i++){
  105482. if(oggpack_look(&r,32)==-1)report("out of data. failed!");
  105483. if(oggpack_look(&r,32)!=large[i]){
  105484. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpack_look(&r,32),large[i],
  105485. oggpack_look(&r,32),large[i]);
  105486. report("read incorrect value!\n");
  105487. }
  105488. oggpack_adv(&r,32);
  105489. }
  105490. if(oggpack_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  105491. fprintf(stderr,"ok.");
  105492. fprintf(stderr,"\nSmall unclipped packing (LSb): ");
  105493. cliptest(testbuffer1,test1size,7,four,foursize);
  105494. fprintf(stderr,"ok.");
  105495. fprintf(stderr,"\nLarge unclipped packing (LSb): ");
  105496. cliptest(testbuffer2,test2size,17,five,fivesize);
  105497. fprintf(stderr,"ok.");
  105498. fprintf(stderr,"\nSingle bit unclipped packing (LSb): ");
  105499. cliptest(testbuffer3,test3size,1,six,sixsize);
  105500. fprintf(stderr,"ok.");
  105501. fprintf(stderr,"\nTesting read past end (LSb): ");
  105502. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  105503. for(i=0;i<64;i++){
  105504. if(oggpack_read(&r,1)!=0){
  105505. fprintf(stderr,"failed; got -1 prematurely.\n");
  105506. exit(1);
  105507. }
  105508. }
  105509. if(oggpack_look(&r,1)!=-1 ||
  105510. oggpack_read(&r,1)!=-1){
  105511. fprintf(stderr,"failed; read past end without -1.\n");
  105512. exit(1);
  105513. }
  105514. oggpack_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  105515. if(oggpack_read(&r,30)!=0 || oggpack_read(&r,16)!=0){
  105516. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  105517. exit(1);
  105518. }
  105519. if(oggpack_look(&r,18)!=0 ||
  105520. oggpack_look(&r,18)!=0){
  105521. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  105522. exit(1);
  105523. }
  105524. if(oggpack_look(&r,19)!=-1 ||
  105525. oggpack_look(&r,19)!=-1){
  105526. fprintf(stderr,"failed; read past end without -1.\n");
  105527. exit(1);
  105528. }
  105529. if(oggpack_look(&r,32)!=-1 ||
  105530. oggpack_look(&r,32)!=-1){
  105531. fprintf(stderr,"failed; read past end without -1.\n");
  105532. exit(1);
  105533. }
  105534. oggpack_writeclear(&o);
  105535. fprintf(stderr,"ok.\n");
  105536. /********** lazy, cut-n-paste retest with MSb packing ***********/
  105537. /* Test read/write together */
  105538. /* Later we test against pregenerated bitstreams */
  105539. oggpackB_writeinit(&o);
  105540. fprintf(stderr,"\nSmall preclipped packing (MSb): ");
  105541. cliptestB(testbuffer1,test1size,0,oneB,onesize);
  105542. fprintf(stderr,"ok.");
  105543. fprintf(stderr,"\nNull bit call (MSb): ");
  105544. cliptestB(testbuffer3,test3size,0,twoB,twosize);
  105545. fprintf(stderr,"ok.");
  105546. fprintf(stderr,"\nLarge preclipped packing (MSb): ");
  105547. cliptestB(testbuffer2,test2size,0,threeB,threesize);
  105548. fprintf(stderr,"ok.");
  105549. fprintf(stderr,"\n32 bit preclipped packing (MSb): ");
  105550. oggpackB_reset(&o);
  105551. for(i=0;i<test2size;i++)
  105552. oggpackB_write(&o,large[i],32);
  105553. buffer=oggpackB_get_buffer(&o);
  105554. bytes=oggpackB_bytes(&o);
  105555. oggpackB_readinit(&r,buffer,bytes);
  105556. for(i=0;i<test2size;i++){
  105557. if(oggpackB_look(&r,32)==-1)report("out of data. failed!");
  105558. if(oggpackB_look(&r,32)!=large[i]){
  105559. fprintf(stderr,"%ld != %ld (%lx!=%lx):",oggpackB_look(&r,32),large[i],
  105560. oggpackB_look(&r,32),large[i]);
  105561. report("read incorrect value!\n");
  105562. }
  105563. oggpackB_adv(&r,32);
  105564. }
  105565. if(oggpackB_bytes(&r)!=bytes)report("leftover bytes after read!\n");
  105566. fprintf(stderr,"ok.");
  105567. fprintf(stderr,"\nSmall unclipped packing (MSb): ");
  105568. cliptestB(testbuffer1,test1size,7,fourB,foursize);
  105569. fprintf(stderr,"ok.");
  105570. fprintf(stderr,"\nLarge unclipped packing (MSb): ");
  105571. cliptestB(testbuffer2,test2size,17,fiveB,fivesize);
  105572. fprintf(stderr,"ok.");
  105573. fprintf(stderr,"\nSingle bit unclipped packing (MSb): ");
  105574. cliptestB(testbuffer3,test3size,1,sixB,sixsize);
  105575. fprintf(stderr,"ok.");
  105576. fprintf(stderr,"\nTesting read past end (MSb): ");
  105577. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  105578. for(i=0;i<64;i++){
  105579. if(oggpackB_read(&r,1)!=0){
  105580. fprintf(stderr,"failed; got -1 prematurely.\n");
  105581. exit(1);
  105582. }
  105583. }
  105584. if(oggpackB_look(&r,1)!=-1 ||
  105585. oggpackB_read(&r,1)!=-1){
  105586. fprintf(stderr,"failed; read past end without -1.\n");
  105587. exit(1);
  105588. }
  105589. oggpackB_readinit(&r,"\0\0\0\0\0\0\0\0",8);
  105590. if(oggpackB_read(&r,30)!=0 || oggpackB_read(&r,16)!=0){
  105591. fprintf(stderr,"failed 2; got -1 prematurely.\n");
  105592. exit(1);
  105593. }
  105594. if(oggpackB_look(&r,18)!=0 ||
  105595. oggpackB_look(&r,18)!=0){
  105596. fprintf(stderr,"failed 3; got -1 prematurely.\n");
  105597. exit(1);
  105598. }
  105599. if(oggpackB_look(&r,19)!=-1 ||
  105600. oggpackB_look(&r,19)!=-1){
  105601. fprintf(stderr,"failed; read past end without -1.\n");
  105602. exit(1);
  105603. }
  105604. if(oggpackB_look(&r,32)!=-1 ||
  105605. oggpackB_look(&r,32)!=-1){
  105606. fprintf(stderr,"failed; read past end without -1.\n");
  105607. exit(1);
  105608. }
  105609. oggpackB_writeclear(&o);
  105610. fprintf(stderr,"ok.\n\n");
  105611. return(0);
  105612. }
  105613. #endif /* _V_SELFTEST */
  105614. #undef BUFFER_INCREMENT
  105615. #endif
  105616. /********* End of inlined file: bitwise.c *********/
  105617. /********* Start of inlined file: framing.c *********/
  105618. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  105619. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  105620. // tasks..
  105621. /********* Start of inlined file: juce_Config.h *********/
  105622. #ifndef __JUCE_CONFIG_JUCEHEADER__
  105623. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  105624. /*
  105625. This file contains macros that enable/disable various JUCE features.
  105626. */
  105627. /** The name of the namespace that all Juce classes and functions will be
  105628. put inside. If this is not defined, no namespace will be used.
  105629. */
  105630. #ifndef JUCE_NAMESPACE
  105631. #define JUCE_NAMESPACE juce
  105632. #endif
  105633. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  105634. but if you define this value, you can override this can force it to be true or
  105635. false.
  105636. */
  105637. #ifndef JUCE_FORCE_DEBUG
  105638. //#define JUCE_FORCE_DEBUG 1
  105639. #endif
  105640. /** If this flag is enabled, the the jassert and jassertfalse macros will
  105641. always use Logger::writeToLog() to write a message when an assertion happens.
  105642. Enabling it will also leave this turned on in release builds. When it's disabled,
  105643. however, the jassert and jassertfalse macros will not be compiled in a
  105644. release build.
  105645. @see jassert, jassertfalse, Logger
  105646. */
  105647. #ifndef JUCE_LOG_ASSERTIONS
  105648. // #define JUCE_LOG_ASSERTIONS 1
  105649. #endif
  105650. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  105651. which the ASIOAudioIODevice class can't be built. See the comments in the
  105652. ASIOAudioIODevice class's header file for more info about this.
  105653. (This only affects a Win32 build)
  105654. */
  105655. #ifndef JUCE_ASIO
  105656. #define JUCE_ASIO 1
  105657. #endif
  105658. /** Comment out this macro to disable building of ALSA device support on Linux.
  105659. */
  105660. #ifndef JUCE_ALSA
  105661. #define JUCE_ALSA 1
  105662. #endif
  105663. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  105664. have the SDK installed.
  105665. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  105666. classes will be unavailable.
  105667. On Windows, if you enable this, you'll need to have the QuickTime SDK
  105668. installed, and its header files will need to be on your include path.
  105669. */
  105670. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  105671. #define JUCE_QUICKTIME 1
  105672. #endif
  105673. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  105674. have the appropriate headers and libraries available. If it's not enabled, the
  105675. OpenGLComponent class will be unavailable.
  105676. */
  105677. #ifndef JUCE_OPENGL
  105678. #define JUCE_OPENGL 1
  105679. #endif
  105680. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  105681. If you're not going to need either of these formats, turn off the flags to
  105682. avoid bloating your codebase with them.
  105683. */
  105684. #ifndef JUCE_USE_FLAC
  105685. #define JUCE_USE_FLAC 1
  105686. #endif
  105687. #ifndef JUCE_USE_OGGVORBIS
  105688. #define JUCE_USE_OGGVORBIS 1
  105689. #endif
  105690. /** This flag lets you enable support for CD-burning. You might want to disable
  105691. it to build without the MS SDK under windows.
  105692. */
  105693. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  105694. #define JUCE_USE_CDBURNER 1
  105695. #endif
  105696. /** Enabling this macro means that all regions that get repainted will have a coloured
  105697. line drawn around them.
  105698. This is handy if you're trying to optimise drawing, because it lets you easily see
  105699. when anything is being repainted unnecessarily.
  105700. */
  105701. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  105702. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  105703. #endif
  105704. /** Enable this under Linux to use Xinerama for multi-monitor support.
  105705. */
  105706. #ifndef JUCE_USE_XINERAMA
  105707. #define JUCE_USE_XINERAMA 1
  105708. #endif
  105709. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  105710. */
  105711. #ifndef JUCE_USE_XSHM
  105712. #define JUCE_USE_XSHM 1
  105713. #endif
  105714. /** Enabling this builds support for VST audio plugins.
  105715. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  105716. */
  105717. #ifndef JUCE_PLUGINHOST_VST
  105718. // #define JUCE_PLUGINHOST_VST 1
  105719. #endif
  105720. /** Enabling this builds support for AudioUnit audio plugins.
  105721. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  105722. */
  105723. #ifndef JUCE_PLUGINHOST_AU
  105724. // #define JUCE_PLUGINHOST_AU 1
  105725. #endif
  105726. /** Disabling this will avoid linking to any UI code. This is handy for
  105727. writing command-line utilities, e.g. on linux boxes which don't have some
  105728. of the UI libraries installed.
  105729. (On mac and windows, this won't generally make much difference to the build).
  105730. */
  105731. #ifndef JUCE_BUILD_GUI_CLASSES
  105732. #define JUCE_BUILD_GUI_CLASSES 1
  105733. #endif
  105734. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  105735. */
  105736. #ifndef JUCE_WEB_BROWSER
  105737. #define JUCE_WEB_BROWSER 1
  105738. #endif
  105739. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  105740. codebase - you might need to use this if you're linking to some of these libraries
  105741. yourself.
  105742. */
  105743. #ifndef JUCE_INCLUDE_ZLIB_CODE
  105744. #define JUCE_INCLUDE_ZLIB_CODE 1
  105745. #endif
  105746. #ifndef JUCE_INCLUDE_FLAC_CODE
  105747. #define JUCE_INCLUDE_FLAC_CODE 1
  105748. #endif
  105749. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  105750. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  105751. #endif
  105752. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  105753. #define JUCE_INCLUDE_PNGLIB_CODE 1
  105754. #endif
  105755. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  105756. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  105757. #endif
  105758. /** Enable this to add extra memory-leak info to the new and delete operators.
  105759. (Currently, this only affects Windows builds in debug mode).
  105760. */
  105761. #ifndef JUCE_CHECK_MEMORY_LEAKS
  105762. #define JUCE_CHECK_MEMORY_LEAKS 1
  105763. #endif
  105764. /** Enable this to turn on juce's internal catching of exceptions.
  105765. Turning it off will avoid any exception catching. With it on, all exceptions
  105766. are passed to the JUCEApplication::unhandledException() callback for logging.
  105767. */
  105768. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  105769. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  105770. #endif
  105771. /** If this macro is set, the Juce String class will use unicode as its
  105772. internal representation. If it isn't set, it'll use ANSI.
  105773. */
  105774. #ifndef JUCE_STRINGS_ARE_UNICODE
  105775. #define JUCE_STRINGS_ARE_UNICODE 1
  105776. #endif
  105777. #endif
  105778. /********* End of inlined file: juce_Config.h *********/
  105779. #ifdef _MSC_VER
  105780. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  105781. #endif
  105782. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  105783. #if JUCE_USE_OGGVORBIS
  105784. #include <stdlib.h>
  105785. #include <string.h>
  105786. /* A complete description of Ogg framing exists in docs/framing.html */
  105787. int ogg_page_version(ogg_page *og){
  105788. return((int)(og->header[4]));
  105789. }
  105790. int ogg_page_continued(ogg_page *og){
  105791. return((int)(og->header[5]&0x01));
  105792. }
  105793. int ogg_page_bos(ogg_page *og){
  105794. return((int)(og->header[5]&0x02));
  105795. }
  105796. int ogg_page_eos(ogg_page *og){
  105797. return((int)(og->header[5]&0x04));
  105798. }
  105799. ogg_int64_t ogg_page_granulepos(ogg_page *og){
  105800. unsigned char *page=og->header;
  105801. ogg_int64_t granulepos=page[13]&(0xff);
  105802. granulepos= (granulepos<<8)|(page[12]&0xff);
  105803. granulepos= (granulepos<<8)|(page[11]&0xff);
  105804. granulepos= (granulepos<<8)|(page[10]&0xff);
  105805. granulepos= (granulepos<<8)|(page[9]&0xff);
  105806. granulepos= (granulepos<<8)|(page[8]&0xff);
  105807. granulepos= (granulepos<<8)|(page[7]&0xff);
  105808. granulepos= (granulepos<<8)|(page[6]&0xff);
  105809. return(granulepos);
  105810. }
  105811. int ogg_page_serialno(ogg_page *og){
  105812. return(og->header[14] |
  105813. (og->header[15]<<8) |
  105814. (og->header[16]<<16) |
  105815. (og->header[17]<<24));
  105816. }
  105817. long ogg_page_pageno(ogg_page *og){
  105818. return(og->header[18] |
  105819. (og->header[19]<<8) |
  105820. (og->header[20]<<16) |
  105821. (og->header[21]<<24));
  105822. }
  105823. /* returns the number of packets that are completed on this page (if
  105824. the leading packet is begun on a previous page, but ends on this
  105825. page, it's counted */
  105826. /* NOTE:
  105827. If a page consists of a packet begun on a previous page, and a new
  105828. packet begun (but not completed) on this page, the return will be:
  105829. ogg_page_packets(page) ==1,
  105830. ogg_page_continued(page) !=0
  105831. If a page happens to be a single packet that was begun on a
  105832. previous page, and spans to the next page (in the case of a three or
  105833. more page packet), the return will be:
  105834. ogg_page_packets(page) ==0,
  105835. ogg_page_continued(page) !=0
  105836. */
  105837. int ogg_page_packets(ogg_page *og){
  105838. int i,n=og->header[26],count=0;
  105839. for(i=0;i<n;i++)
  105840. if(og->header[27+i]<255)count++;
  105841. return(count);
  105842. }
  105843. #if 0
  105844. /* helper to initialize lookup for direct-table CRC (illustrative; we
  105845. use the static init below) */
  105846. static ogg_uint32_t _ogg_crc_entry(unsigned long index){
  105847. int i;
  105848. unsigned long r;
  105849. r = index << 24;
  105850. for (i=0; i<8; i++)
  105851. if (r & 0x80000000UL)
  105852. r = (r << 1) ^ 0x04c11db7; /* The same as the ethernet generator
  105853. polynomial, although we use an
  105854. unreflected alg and an init/final
  105855. of 0, not 0xffffffff */
  105856. else
  105857. r<<=1;
  105858. return (r & 0xffffffffUL);
  105859. }
  105860. #endif
  105861. static const ogg_uint32_t crc_lookup[256]={
  105862. 0x00000000,0x04c11db7,0x09823b6e,0x0d4326d9,
  105863. 0x130476dc,0x17c56b6b,0x1a864db2,0x1e475005,
  105864. 0x2608edb8,0x22c9f00f,0x2f8ad6d6,0x2b4bcb61,
  105865. 0x350c9b64,0x31cd86d3,0x3c8ea00a,0x384fbdbd,
  105866. 0x4c11db70,0x48d0c6c7,0x4593e01e,0x4152fda9,
  105867. 0x5f15adac,0x5bd4b01b,0x569796c2,0x52568b75,
  105868. 0x6a1936c8,0x6ed82b7f,0x639b0da6,0x675a1011,
  105869. 0x791d4014,0x7ddc5da3,0x709f7b7a,0x745e66cd,
  105870. 0x9823b6e0,0x9ce2ab57,0x91a18d8e,0x95609039,
  105871. 0x8b27c03c,0x8fe6dd8b,0x82a5fb52,0x8664e6e5,
  105872. 0xbe2b5b58,0xbaea46ef,0xb7a96036,0xb3687d81,
  105873. 0xad2f2d84,0xa9ee3033,0xa4ad16ea,0xa06c0b5d,
  105874. 0xd4326d90,0xd0f37027,0xddb056fe,0xd9714b49,
  105875. 0xc7361b4c,0xc3f706fb,0xceb42022,0xca753d95,
  105876. 0xf23a8028,0xf6fb9d9f,0xfbb8bb46,0xff79a6f1,
  105877. 0xe13ef6f4,0xe5ffeb43,0xe8bccd9a,0xec7dd02d,
  105878. 0x34867077,0x30476dc0,0x3d044b19,0x39c556ae,
  105879. 0x278206ab,0x23431b1c,0x2e003dc5,0x2ac12072,
  105880. 0x128e9dcf,0x164f8078,0x1b0ca6a1,0x1fcdbb16,
  105881. 0x018aeb13,0x054bf6a4,0x0808d07d,0x0cc9cdca,
  105882. 0x7897ab07,0x7c56b6b0,0x71159069,0x75d48dde,
  105883. 0x6b93dddb,0x6f52c06c,0x6211e6b5,0x66d0fb02,
  105884. 0x5e9f46bf,0x5a5e5b08,0x571d7dd1,0x53dc6066,
  105885. 0x4d9b3063,0x495a2dd4,0x44190b0d,0x40d816ba,
  105886. 0xaca5c697,0xa864db20,0xa527fdf9,0xa1e6e04e,
  105887. 0xbfa1b04b,0xbb60adfc,0xb6238b25,0xb2e29692,
  105888. 0x8aad2b2f,0x8e6c3698,0x832f1041,0x87ee0df6,
  105889. 0x99a95df3,0x9d684044,0x902b669d,0x94ea7b2a,
  105890. 0xe0b41de7,0xe4750050,0xe9362689,0xedf73b3e,
  105891. 0xf3b06b3b,0xf771768c,0xfa325055,0xfef34de2,
  105892. 0xc6bcf05f,0xc27dede8,0xcf3ecb31,0xcbffd686,
  105893. 0xd5b88683,0xd1799b34,0xdc3abded,0xd8fba05a,
  105894. 0x690ce0ee,0x6dcdfd59,0x608edb80,0x644fc637,
  105895. 0x7a089632,0x7ec98b85,0x738aad5c,0x774bb0eb,
  105896. 0x4f040d56,0x4bc510e1,0x46863638,0x42472b8f,
  105897. 0x5c007b8a,0x58c1663d,0x558240e4,0x51435d53,
  105898. 0x251d3b9e,0x21dc2629,0x2c9f00f0,0x285e1d47,
  105899. 0x36194d42,0x32d850f5,0x3f9b762c,0x3b5a6b9b,
  105900. 0x0315d626,0x07d4cb91,0x0a97ed48,0x0e56f0ff,
  105901. 0x1011a0fa,0x14d0bd4d,0x19939b94,0x1d528623,
  105902. 0xf12f560e,0xf5ee4bb9,0xf8ad6d60,0xfc6c70d7,
  105903. 0xe22b20d2,0xe6ea3d65,0xeba91bbc,0xef68060b,
  105904. 0xd727bbb6,0xd3e6a601,0xdea580d8,0xda649d6f,
  105905. 0xc423cd6a,0xc0e2d0dd,0xcda1f604,0xc960ebb3,
  105906. 0xbd3e8d7e,0xb9ff90c9,0xb4bcb610,0xb07daba7,
  105907. 0xae3afba2,0xaafbe615,0xa7b8c0cc,0xa379dd7b,
  105908. 0x9b3660c6,0x9ff77d71,0x92b45ba8,0x9675461f,
  105909. 0x8832161a,0x8cf30bad,0x81b02d74,0x857130c3,
  105910. 0x5d8a9099,0x594b8d2e,0x5408abf7,0x50c9b640,
  105911. 0x4e8ee645,0x4a4ffbf2,0x470cdd2b,0x43cdc09c,
  105912. 0x7b827d21,0x7f436096,0x7200464f,0x76c15bf8,
  105913. 0x68860bfd,0x6c47164a,0x61043093,0x65c52d24,
  105914. 0x119b4be9,0x155a565e,0x18197087,0x1cd86d30,
  105915. 0x029f3d35,0x065e2082,0x0b1d065b,0x0fdc1bec,
  105916. 0x3793a651,0x3352bbe6,0x3e119d3f,0x3ad08088,
  105917. 0x2497d08d,0x2056cd3a,0x2d15ebe3,0x29d4f654,
  105918. 0xc5a92679,0xc1683bce,0xcc2b1d17,0xc8ea00a0,
  105919. 0xd6ad50a5,0xd26c4d12,0xdf2f6bcb,0xdbee767c,
  105920. 0xe3a1cbc1,0xe760d676,0xea23f0af,0xeee2ed18,
  105921. 0xf0a5bd1d,0xf464a0aa,0xf9278673,0xfde69bc4,
  105922. 0x89b8fd09,0x8d79e0be,0x803ac667,0x84fbdbd0,
  105923. 0x9abc8bd5,0x9e7d9662,0x933eb0bb,0x97ffad0c,
  105924. 0xafb010b1,0xab710d06,0xa6322bdf,0xa2f33668,
  105925. 0xbcb4666d,0xb8757bda,0xb5365d03,0xb1f740b4};
  105926. /* init the encode/decode logical stream state */
  105927. int ogg_stream_init(ogg_stream_state *os,int serialno){
  105928. if(os){
  105929. memset(os,0,sizeof(*os));
  105930. os->body_storage=16*1024;
  105931. os->body_data=(unsigned char*) _ogg_malloc(os->body_storage*sizeof(*os->body_data));
  105932. os->lacing_storage=1024;
  105933. os->lacing_vals=(int*) _ogg_malloc(os->lacing_storage*sizeof(*os->lacing_vals));
  105934. os->granule_vals=(ogg_int64_t*) _ogg_malloc(os->lacing_storage*sizeof(*os->granule_vals));
  105935. os->serialno=serialno;
  105936. return(0);
  105937. }
  105938. return(-1);
  105939. }
  105940. /* _clear does not free os, only the non-flat storage within */
  105941. int ogg_stream_clear(ogg_stream_state *os){
  105942. if(os){
  105943. if(os->body_data)_ogg_free(os->body_data);
  105944. if(os->lacing_vals)_ogg_free(os->lacing_vals);
  105945. if(os->granule_vals)_ogg_free(os->granule_vals);
  105946. memset(os,0,sizeof(*os));
  105947. }
  105948. return(0);
  105949. }
  105950. int ogg_stream_destroy(ogg_stream_state *os){
  105951. if(os){
  105952. ogg_stream_clear(os);
  105953. _ogg_free(os);
  105954. }
  105955. return(0);
  105956. }
  105957. /* Helpers for ogg_stream_encode; this keeps the structure and
  105958. what's happening fairly clear */
  105959. static void _os_body_expand(ogg_stream_state *os,int needed){
  105960. if(os->body_storage<=os->body_fill+needed){
  105961. os->body_storage+=(needed+1024);
  105962. os->body_data=(unsigned char*) _ogg_realloc(os->body_data,os->body_storage*sizeof(*os->body_data));
  105963. }
  105964. }
  105965. static void _os_lacing_expand(ogg_stream_state *os,int needed){
  105966. if(os->lacing_storage<=os->lacing_fill+needed){
  105967. os->lacing_storage+=(needed+32);
  105968. os->lacing_vals=(int*)_ogg_realloc(os->lacing_vals,os->lacing_storage*sizeof(*os->lacing_vals));
  105969. os->granule_vals=(ogg_int64_t*)_ogg_realloc(os->granule_vals,os->lacing_storage*sizeof(*os->granule_vals));
  105970. }
  105971. }
  105972. /* checksum the page */
  105973. /* Direct table CRC; note that this will be faster in the future if we
  105974. perform the checksum silmultaneously with other copies */
  105975. void ogg_page_checksum_set(ogg_page *og){
  105976. if(og){
  105977. ogg_uint32_t crc_reg=0;
  105978. int i;
  105979. /* safety; needed for API behavior, but not framing code */
  105980. og->header[22]=0;
  105981. og->header[23]=0;
  105982. og->header[24]=0;
  105983. og->header[25]=0;
  105984. for(i=0;i<og->header_len;i++)
  105985. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->header[i]];
  105986. for(i=0;i<og->body_len;i++)
  105987. crc_reg=(crc_reg<<8)^crc_lookup[((crc_reg >> 24)&0xff)^og->body[i]];
  105988. og->header[22]=(unsigned char)(crc_reg&0xff);
  105989. og->header[23]=(unsigned char)((crc_reg>>8)&0xff);
  105990. og->header[24]=(unsigned char)((crc_reg>>16)&0xff);
  105991. og->header[25]=(unsigned char)((crc_reg>>24)&0xff);
  105992. }
  105993. }
  105994. /* submit data to the internal buffer of the framing engine */
  105995. int ogg_stream_packetin(ogg_stream_state *os,ogg_packet *op){
  105996. int lacing_vals=op->bytes/255+1,i;
  105997. if(os->body_returned){
  105998. /* advance packet data according to the body_returned pointer. We
  105999. had to keep it around to return a pointer into the buffer last
  106000. call */
  106001. os->body_fill-=os->body_returned;
  106002. if(os->body_fill)
  106003. memmove(os->body_data,os->body_data+os->body_returned,
  106004. os->body_fill);
  106005. os->body_returned=0;
  106006. }
  106007. /* make sure we have the buffer storage */
  106008. _os_body_expand(os,op->bytes);
  106009. _os_lacing_expand(os,lacing_vals);
  106010. /* Copy in the submitted packet. Yes, the copy is a waste; this is
  106011. the liability of overly clean abstraction for the time being. It
  106012. will actually be fairly easy to eliminate the extra copy in the
  106013. future */
  106014. memcpy(os->body_data+os->body_fill,op->packet,op->bytes);
  106015. os->body_fill+=op->bytes;
  106016. /* Store lacing vals for this packet */
  106017. for(i=0;i<lacing_vals-1;i++){
  106018. os->lacing_vals[os->lacing_fill+i]=255;
  106019. os->granule_vals[os->lacing_fill+i]=os->granulepos;
  106020. }
  106021. os->lacing_vals[os->lacing_fill+i]=(op->bytes)%255;
  106022. os->granulepos=os->granule_vals[os->lacing_fill+i]=op->granulepos;
  106023. /* flag the first segment as the beginning of the packet */
  106024. os->lacing_vals[os->lacing_fill]|= 0x100;
  106025. os->lacing_fill+=lacing_vals;
  106026. /* for the sake of completeness */
  106027. os->packetno++;
  106028. if(op->e_o_s)os->e_o_s=1;
  106029. return(0);
  106030. }
  106031. /* This will flush remaining packets into a page (returning nonzero),
  106032. even if there is not enough data to trigger a flush normally
  106033. (undersized page). If there are no packets or partial packets to
  106034. flush, ogg_stream_flush returns 0. Note that ogg_stream_flush will
  106035. try to flush a normal sized page like ogg_stream_pageout; a call to
  106036. ogg_stream_flush does not guarantee that all packets have flushed.
  106037. Only a return value of 0 from ogg_stream_flush indicates all packet
  106038. data is flushed into pages.
  106039. since ogg_stream_flush will flush the last page in a stream even if
  106040. it's undersized, you almost certainly want to use ogg_stream_pageout
  106041. (and *not* ogg_stream_flush) unless you specifically need to flush
  106042. an page regardless of size in the middle of a stream. */
  106043. int ogg_stream_flush(ogg_stream_state *os,ogg_page *og){
  106044. int i;
  106045. int vals=0;
  106046. int maxvals=(os->lacing_fill>255?255:os->lacing_fill);
  106047. int bytes=0;
  106048. long acc=0;
  106049. ogg_int64_t granule_pos=-1;
  106050. if(maxvals==0)return(0);
  106051. /* construct a page */
  106052. /* decide how many segments to include */
  106053. /* If this is the initial header case, the first page must only include
  106054. the initial header packet */
  106055. if(os->b_o_s==0){ /* 'initial header page' case */
  106056. granule_pos=0;
  106057. for(vals=0;vals<maxvals;vals++){
  106058. if((os->lacing_vals[vals]&0x0ff)<255){
  106059. vals++;
  106060. break;
  106061. }
  106062. }
  106063. }else{
  106064. for(vals=0;vals<maxvals;vals++){
  106065. if(acc>4096)break;
  106066. acc+=os->lacing_vals[vals]&0x0ff;
  106067. if((os->lacing_vals[vals]&0xff)<255)
  106068. granule_pos=os->granule_vals[vals];
  106069. }
  106070. }
  106071. /* construct the header in temp storage */
  106072. memcpy(os->header,"OggS",4);
  106073. /* stream structure version */
  106074. os->header[4]=0x00;
  106075. /* continued packet flag? */
  106076. os->header[5]=0x00;
  106077. if((os->lacing_vals[0]&0x100)==0)os->header[5]|=0x01;
  106078. /* first page flag? */
  106079. if(os->b_o_s==0)os->header[5]|=0x02;
  106080. /* last page flag? */
  106081. if(os->e_o_s && os->lacing_fill==vals)os->header[5]|=0x04;
  106082. os->b_o_s=1;
  106083. /* 64 bits of PCM position */
  106084. for(i=6;i<14;i++){
  106085. os->header[i]=(unsigned char)(granule_pos&0xff);
  106086. granule_pos>>=8;
  106087. }
  106088. /* 32 bits of stream serial number */
  106089. {
  106090. long serialno=os->serialno;
  106091. for(i=14;i<18;i++){
  106092. os->header[i]=(unsigned char)(serialno&0xff);
  106093. serialno>>=8;
  106094. }
  106095. }
  106096. /* 32 bits of page counter (we have both counter and page header
  106097. because this val can roll over) */
  106098. if(os->pageno==-1)os->pageno=0; /* because someone called
  106099. stream_reset; this would be a
  106100. strange thing to do in an
  106101. encode stream, but it has
  106102. plausible uses */
  106103. {
  106104. long pageno=os->pageno++;
  106105. for(i=18;i<22;i++){
  106106. os->header[i]=(unsigned char)(pageno&0xff);
  106107. pageno>>=8;
  106108. }
  106109. }
  106110. /* zero for computation; filled in later */
  106111. os->header[22]=0;
  106112. os->header[23]=0;
  106113. os->header[24]=0;
  106114. os->header[25]=0;
  106115. /* segment table */
  106116. os->header[26]=(unsigned char)(vals&0xff);
  106117. for(i=0;i<vals;i++)
  106118. bytes+=os->header[i+27]=(unsigned char)(os->lacing_vals[i]&0xff);
  106119. /* set pointers in the ogg_page struct */
  106120. og->header=os->header;
  106121. og->header_len=os->header_fill=vals+27;
  106122. og->body=os->body_data+os->body_returned;
  106123. og->body_len=bytes;
  106124. /* advance the lacing data and set the body_returned pointer */
  106125. os->lacing_fill-=vals;
  106126. memmove(os->lacing_vals,os->lacing_vals+vals,os->lacing_fill*sizeof(*os->lacing_vals));
  106127. memmove(os->granule_vals,os->granule_vals+vals,os->lacing_fill*sizeof(*os->granule_vals));
  106128. os->body_returned+=bytes;
  106129. /* calculate the checksum */
  106130. ogg_page_checksum_set(og);
  106131. /* done */
  106132. return(1);
  106133. }
  106134. /* This constructs pages from buffered packet segments. The pointers
  106135. returned are to static buffers; do not free. The returned buffers are
  106136. good only until the next call (using the same ogg_stream_state) */
  106137. int ogg_stream_pageout(ogg_stream_state *os, ogg_page *og){
  106138. if((os->e_o_s&&os->lacing_fill) || /* 'were done, now flush' case */
  106139. os->body_fill-os->body_returned > 4096 ||/* 'page nominal size' case */
  106140. os->lacing_fill>=255 || /* 'segment table full' case */
  106141. (os->lacing_fill&&!os->b_o_s)){ /* 'initial header page' case */
  106142. return(ogg_stream_flush(os,og));
  106143. }
  106144. /* not enough data to construct a page and not end of stream */
  106145. return(0);
  106146. }
  106147. int ogg_stream_eos(ogg_stream_state *os){
  106148. return os->e_o_s;
  106149. }
  106150. /* DECODING PRIMITIVES: packet streaming layer **********************/
  106151. /* This has two layers to place more of the multi-serialno and paging
  106152. control in the application's hands. First, we expose a data buffer
  106153. using ogg_sync_buffer(). The app either copies into the
  106154. buffer, or passes it directly to read(), etc. We then call
  106155. ogg_sync_wrote() to tell how many bytes we just added.
  106156. Pages are returned (pointers into the buffer in ogg_sync_state)
  106157. by ogg_sync_pageout(). The page is then submitted to
  106158. ogg_stream_pagein() along with the appropriate
  106159. ogg_stream_state* (ie, matching serialno). We then get raw
  106160. packets out calling ogg_stream_packetout() with a
  106161. ogg_stream_state. */
  106162. /* initialize the struct to a known state */
  106163. int ogg_sync_init(ogg_sync_state *oy){
  106164. if(oy){
  106165. memset(oy,0,sizeof(*oy));
  106166. }
  106167. return(0);
  106168. }
  106169. /* clear non-flat storage within */
  106170. int ogg_sync_clear(ogg_sync_state *oy){
  106171. if(oy){
  106172. if(oy->data)_ogg_free(oy->data);
  106173. ogg_sync_init(oy);
  106174. }
  106175. return(0);
  106176. }
  106177. int ogg_sync_destroy(ogg_sync_state *oy){
  106178. if(oy){
  106179. ogg_sync_clear(oy);
  106180. _ogg_free(oy);
  106181. }
  106182. return(0);
  106183. }
  106184. char *ogg_sync_buffer(ogg_sync_state *oy, long size){
  106185. /* first, clear out any space that has been previously returned */
  106186. if(oy->returned){
  106187. oy->fill-=oy->returned;
  106188. if(oy->fill>0)
  106189. memmove(oy->data,oy->data+oy->returned,oy->fill);
  106190. oy->returned=0;
  106191. }
  106192. if(size>oy->storage-oy->fill){
  106193. /* We need to extend the internal buffer */
  106194. long newsize=size+oy->fill+4096; /* an extra page to be nice */
  106195. if(oy->data)
  106196. oy->data=(unsigned char*) _ogg_realloc(oy->data,newsize);
  106197. else
  106198. oy->data=(unsigned char*) _ogg_malloc(newsize);
  106199. oy->storage=newsize;
  106200. }
  106201. /* expose a segment at least as large as requested at the fill mark */
  106202. return((char *)oy->data+oy->fill);
  106203. }
  106204. int ogg_sync_wrote(ogg_sync_state *oy, long bytes){
  106205. if(oy->fill+bytes>oy->storage)return(-1);
  106206. oy->fill+=bytes;
  106207. return(0);
  106208. }
  106209. /* sync the stream. This is meant to be useful for finding page
  106210. boundaries.
  106211. return values for this:
  106212. -n) skipped n bytes
  106213. 0) page not ready; more data (no bytes skipped)
  106214. n) page synced at current location; page length n bytes
  106215. */
  106216. long ogg_sync_pageseek(ogg_sync_state *oy,ogg_page *og){
  106217. unsigned char *page=oy->data+oy->returned;
  106218. unsigned char *next;
  106219. long bytes=oy->fill-oy->returned;
  106220. if(oy->headerbytes==0){
  106221. int headerbytes,i;
  106222. if(bytes<27)return(0); /* not enough for a header */
  106223. /* verify capture pattern */
  106224. if(memcmp(page,"OggS",4))goto sync_fail;
  106225. headerbytes=page[26]+27;
  106226. if(bytes<headerbytes)return(0); /* not enough for header + seg table */
  106227. /* count up body length in the segment table */
  106228. for(i=0;i<page[26];i++)
  106229. oy->bodybytes+=page[27+i];
  106230. oy->headerbytes=headerbytes;
  106231. }
  106232. if(oy->bodybytes+oy->headerbytes>bytes)return(0);
  106233. /* The whole test page is buffered. Verify the checksum */
  106234. {
  106235. /* Grab the checksum bytes, set the header field to zero */
  106236. char chksum[4];
  106237. ogg_page log;
  106238. memcpy(chksum,page+22,4);
  106239. memset(page+22,0,4);
  106240. /* set up a temp page struct and recompute the checksum */
  106241. log.header=page;
  106242. log.header_len=oy->headerbytes;
  106243. log.body=page+oy->headerbytes;
  106244. log.body_len=oy->bodybytes;
  106245. ogg_page_checksum_set(&log);
  106246. /* Compare */
  106247. if(memcmp(chksum,page+22,4)){
  106248. /* D'oh. Mismatch! Corrupt page (or miscapture and not a page
  106249. at all) */
  106250. /* replace the computed checksum with the one actually read in */
  106251. memcpy(page+22,chksum,4);
  106252. /* Bad checksum. Lose sync */
  106253. goto sync_fail;
  106254. }
  106255. }
  106256. /* yes, have a whole page all ready to go */
  106257. {
  106258. unsigned char *page=oy->data+oy->returned;
  106259. long bytes;
  106260. if(og){
  106261. og->header=page;
  106262. og->header_len=oy->headerbytes;
  106263. og->body=page+oy->headerbytes;
  106264. og->body_len=oy->bodybytes;
  106265. }
  106266. oy->unsynced=0;
  106267. oy->returned+=(bytes=oy->headerbytes+oy->bodybytes);
  106268. oy->headerbytes=0;
  106269. oy->bodybytes=0;
  106270. return(bytes);
  106271. }
  106272. sync_fail:
  106273. oy->headerbytes=0;
  106274. oy->bodybytes=0;
  106275. /* search for possible capture */
  106276. next=(unsigned char*)memchr(page+1,'O',bytes-1);
  106277. if(!next)
  106278. next=oy->data+oy->fill;
  106279. oy->returned=next-oy->data;
  106280. return(-(next-page));
  106281. }
  106282. /* sync the stream and get a page. Keep trying until we find a page.
  106283. Supress 'sync errors' after reporting the first.
  106284. return values:
  106285. -1) recapture (hole in data)
  106286. 0) need more data
  106287. 1) page returned
  106288. Returns pointers into buffered data; invalidated by next call to
  106289. _stream, _clear, _init, or _buffer */
  106290. int ogg_sync_pageout(ogg_sync_state *oy, ogg_page *og){
  106291. /* all we need to do is verify a page at the head of the stream
  106292. buffer. If it doesn't verify, we look for the next potential
  106293. frame */
  106294. for(;;){
  106295. long ret=ogg_sync_pageseek(oy,og);
  106296. if(ret>0){
  106297. /* have a page */
  106298. return(1);
  106299. }
  106300. if(ret==0){
  106301. /* need more data */
  106302. return(0);
  106303. }
  106304. /* head did not start a synced page... skipped some bytes */
  106305. if(!oy->unsynced){
  106306. oy->unsynced=1;
  106307. return(-1);
  106308. }
  106309. /* loop. keep looking */
  106310. }
  106311. }
  106312. /* add the incoming page to the stream state; we decompose the page
  106313. into packet segments here as well. */
  106314. int ogg_stream_pagein(ogg_stream_state *os, ogg_page *og){
  106315. unsigned char *header=og->header;
  106316. unsigned char *body=og->body;
  106317. long bodysize=og->body_len;
  106318. int segptr=0;
  106319. int version=ogg_page_version(og);
  106320. int continued=ogg_page_continued(og);
  106321. int bos=ogg_page_bos(og);
  106322. int eos=ogg_page_eos(og);
  106323. ogg_int64_t granulepos=ogg_page_granulepos(og);
  106324. int serialno=ogg_page_serialno(og);
  106325. long pageno=ogg_page_pageno(og);
  106326. int segments=header[26];
  106327. /* clean up 'returned data' */
  106328. {
  106329. long lr=os->lacing_returned;
  106330. long br=os->body_returned;
  106331. /* body data */
  106332. if(br){
  106333. os->body_fill-=br;
  106334. if(os->body_fill)
  106335. memmove(os->body_data,os->body_data+br,os->body_fill);
  106336. os->body_returned=0;
  106337. }
  106338. if(lr){
  106339. /* segment table */
  106340. if(os->lacing_fill-lr){
  106341. memmove(os->lacing_vals,os->lacing_vals+lr,
  106342. (os->lacing_fill-lr)*sizeof(*os->lacing_vals));
  106343. memmove(os->granule_vals,os->granule_vals+lr,
  106344. (os->lacing_fill-lr)*sizeof(*os->granule_vals));
  106345. }
  106346. os->lacing_fill-=lr;
  106347. os->lacing_packet-=lr;
  106348. os->lacing_returned=0;
  106349. }
  106350. }
  106351. /* check the serial number */
  106352. if(serialno!=os->serialno)return(-1);
  106353. if(version>0)return(-1);
  106354. _os_lacing_expand(os,segments+1);
  106355. /* are we in sequence? */
  106356. if(pageno!=os->pageno){
  106357. int i;
  106358. /* unroll previous partial packet (if any) */
  106359. for(i=os->lacing_packet;i<os->lacing_fill;i++)
  106360. os->body_fill-=os->lacing_vals[i]&0xff;
  106361. os->lacing_fill=os->lacing_packet;
  106362. /* make a note of dropped data in segment table */
  106363. if(os->pageno!=-1){
  106364. os->lacing_vals[os->lacing_fill++]=0x400;
  106365. os->lacing_packet++;
  106366. }
  106367. }
  106368. /* are we a 'continued packet' page? If so, we may need to skip
  106369. some segments */
  106370. if(continued){
  106371. if(os->lacing_fill<1 ||
  106372. os->lacing_vals[os->lacing_fill-1]==0x400){
  106373. bos=0;
  106374. for(;segptr<segments;segptr++){
  106375. int val=header[27+segptr];
  106376. body+=val;
  106377. bodysize-=val;
  106378. if(val<255){
  106379. segptr++;
  106380. break;
  106381. }
  106382. }
  106383. }
  106384. }
  106385. if(bodysize){
  106386. _os_body_expand(os,bodysize);
  106387. memcpy(os->body_data+os->body_fill,body,bodysize);
  106388. os->body_fill+=bodysize;
  106389. }
  106390. {
  106391. int saved=-1;
  106392. while(segptr<segments){
  106393. int val=header[27+segptr];
  106394. os->lacing_vals[os->lacing_fill]=val;
  106395. os->granule_vals[os->lacing_fill]=-1;
  106396. if(bos){
  106397. os->lacing_vals[os->lacing_fill]|=0x100;
  106398. bos=0;
  106399. }
  106400. if(val<255)saved=os->lacing_fill;
  106401. os->lacing_fill++;
  106402. segptr++;
  106403. if(val<255)os->lacing_packet=os->lacing_fill;
  106404. }
  106405. /* set the granulepos on the last granuleval of the last full packet */
  106406. if(saved!=-1){
  106407. os->granule_vals[saved]=granulepos;
  106408. }
  106409. }
  106410. if(eos){
  106411. os->e_o_s=1;
  106412. if(os->lacing_fill>0)
  106413. os->lacing_vals[os->lacing_fill-1]|=0x200;
  106414. }
  106415. os->pageno=pageno+1;
  106416. return(0);
  106417. }
  106418. /* clear things to an initial state. Good to call, eg, before seeking */
  106419. int ogg_sync_reset(ogg_sync_state *oy){
  106420. oy->fill=0;
  106421. oy->returned=0;
  106422. oy->unsynced=0;
  106423. oy->headerbytes=0;
  106424. oy->bodybytes=0;
  106425. return(0);
  106426. }
  106427. int ogg_stream_reset(ogg_stream_state *os){
  106428. os->body_fill=0;
  106429. os->body_returned=0;
  106430. os->lacing_fill=0;
  106431. os->lacing_packet=0;
  106432. os->lacing_returned=0;
  106433. os->header_fill=0;
  106434. os->e_o_s=0;
  106435. os->b_o_s=0;
  106436. os->pageno=-1;
  106437. os->packetno=0;
  106438. os->granulepos=0;
  106439. return(0);
  106440. }
  106441. int ogg_stream_reset_serialno(ogg_stream_state *os,int serialno){
  106442. ogg_stream_reset(os);
  106443. os->serialno=serialno;
  106444. return(0);
  106445. }
  106446. static int _packetout(ogg_stream_state *os,ogg_packet *op,int adv){
  106447. /* The last part of decode. We have the stream broken into packet
  106448. segments. Now we need to group them into packets (or return the
  106449. out of sync markers) */
  106450. int ptr=os->lacing_returned;
  106451. if(os->lacing_packet<=ptr)return(0);
  106452. if(os->lacing_vals[ptr]&0x400){
  106453. /* we need to tell the codec there's a gap; it might need to
  106454. handle previous packet dependencies. */
  106455. os->lacing_returned++;
  106456. os->packetno++;
  106457. return(-1);
  106458. }
  106459. if(!op && !adv)return(1); /* just using peek as an inexpensive way
  106460. to ask if there's a whole packet
  106461. waiting */
  106462. /* Gather the whole packet. We'll have no holes or a partial packet */
  106463. {
  106464. int size=os->lacing_vals[ptr]&0xff;
  106465. int bytes=size;
  106466. int eos=os->lacing_vals[ptr]&0x200; /* last packet of the stream? */
  106467. int bos=os->lacing_vals[ptr]&0x100; /* first packet of the stream? */
  106468. while(size==255){
  106469. int val=os->lacing_vals[++ptr];
  106470. size=val&0xff;
  106471. if(val&0x200)eos=0x200;
  106472. bytes+=size;
  106473. }
  106474. if(op){
  106475. op->e_o_s=eos;
  106476. op->b_o_s=bos;
  106477. op->packet=os->body_data+os->body_returned;
  106478. op->packetno=os->packetno;
  106479. op->granulepos=os->granule_vals[ptr];
  106480. op->bytes=bytes;
  106481. }
  106482. if(adv){
  106483. os->body_returned+=bytes;
  106484. os->lacing_returned=ptr+1;
  106485. os->packetno++;
  106486. }
  106487. }
  106488. return(1);
  106489. }
  106490. int ogg_stream_packetout(ogg_stream_state *os,ogg_packet *op){
  106491. return _packetout(os,op,1);
  106492. }
  106493. int ogg_stream_packetpeek(ogg_stream_state *os,ogg_packet *op){
  106494. return _packetout(os,op,0);
  106495. }
  106496. void ogg_packet_clear(ogg_packet *op) {
  106497. _ogg_free(op->packet);
  106498. memset(op, 0, sizeof(*op));
  106499. }
  106500. #ifdef _V_SELFTEST
  106501. #include <stdio.h>
  106502. ogg_stream_state os_en, os_de;
  106503. ogg_sync_state oy;
  106504. void checkpacket(ogg_packet *op,int len, int no, int pos){
  106505. long j;
  106506. static int sequence=0;
  106507. static int lastno=0;
  106508. if(op->bytes!=len){
  106509. fprintf(stderr,"incorrect packet length!\n");
  106510. exit(1);
  106511. }
  106512. if(op->granulepos!=pos){
  106513. fprintf(stderr,"incorrect packet position!\n");
  106514. exit(1);
  106515. }
  106516. /* packet number just follows sequence/gap; adjust the input number
  106517. for that */
  106518. if(no==0){
  106519. sequence=0;
  106520. }else{
  106521. sequence++;
  106522. if(no>lastno+1)
  106523. sequence++;
  106524. }
  106525. lastno=no;
  106526. if(op->packetno!=sequence){
  106527. fprintf(stderr,"incorrect packet sequence %ld != %d\n",
  106528. (long)(op->packetno),sequence);
  106529. exit(1);
  106530. }
  106531. /* Test data */
  106532. for(j=0;j<op->bytes;j++)
  106533. if(op->packet[j]!=((j+no)&0xff)){
  106534. fprintf(stderr,"body data mismatch (1) at pos %ld: %x!=%lx!\n\n",
  106535. j,op->packet[j],(j+no)&0xff);
  106536. exit(1);
  106537. }
  106538. }
  106539. void check_page(unsigned char *data,const int *header,ogg_page *og){
  106540. long j;
  106541. /* Test data */
  106542. for(j=0;j<og->body_len;j++)
  106543. if(og->body[j]!=data[j]){
  106544. fprintf(stderr,"body data mismatch (2) at pos %ld: %x!=%x!\n\n",
  106545. j,data[j],og->body[j]);
  106546. exit(1);
  106547. }
  106548. /* Test header */
  106549. for(j=0;j<og->header_len;j++){
  106550. if(og->header[j]!=header[j]){
  106551. fprintf(stderr,"header content mismatch at pos %ld:\n",j);
  106552. for(j=0;j<header[26]+27;j++)
  106553. fprintf(stderr," (%ld)%02x:%02x",j,header[j],og->header[j]);
  106554. fprintf(stderr,"\n");
  106555. exit(1);
  106556. }
  106557. }
  106558. if(og->header_len!=header[26]+27){
  106559. fprintf(stderr,"header length incorrect! (%ld!=%d)\n",
  106560. og->header_len,header[26]+27);
  106561. exit(1);
  106562. }
  106563. }
  106564. void print_header(ogg_page *og){
  106565. int j;
  106566. fprintf(stderr,"\nHEADER:\n");
  106567. fprintf(stderr," capture: %c %c %c %c version: %d flags: %x\n",
  106568. og->header[0],og->header[1],og->header[2],og->header[3],
  106569. (int)og->header[4],(int)og->header[5]);
  106570. fprintf(stderr," granulepos: %d serialno: %d pageno: %ld\n",
  106571. (og->header[9]<<24)|(og->header[8]<<16)|
  106572. (og->header[7]<<8)|og->header[6],
  106573. (og->header[17]<<24)|(og->header[16]<<16)|
  106574. (og->header[15]<<8)|og->header[14],
  106575. ((long)(og->header[21])<<24)|(og->header[20]<<16)|
  106576. (og->header[19]<<8)|og->header[18]);
  106577. fprintf(stderr," checksum: %02x:%02x:%02x:%02x\n segments: %d (",
  106578. (int)og->header[22],(int)og->header[23],
  106579. (int)og->header[24],(int)og->header[25],
  106580. (int)og->header[26]);
  106581. for(j=27;j<og->header_len;j++)
  106582. fprintf(stderr,"%d ",(int)og->header[j]);
  106583. fprintf(stderr,")\n\n");
  106584. }
  106585. void copy_page(ogg_page *og){
  106586. unsigned char *temp=_ogg_malloc(og->header_len);
  106587. memcpy(temp,og->header,og->header_len);
  106588. og->header=temp;
  106589. temp=_ogg_malloc(og->body_len);
  106590. memcpy(temp,og->body,og->body_len);
  106591. og->body=temp;
  106592. }
  106593. void free_page(ogg_page *og){
  106594. _ogg_free (og->header);
  106595. _ogg_free (og->body);
  106596. }
  106597. void error(void){
  106598. fprintf(stderr,"error!\n");
  106599. exit(1);
  106600. }
  106601. /* 17 only */
  106602. const int head1_0[] = {0x4f,0x67,0x67,0x53,0,0x06,
  106603. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106604. 0x01,0x02,0x03,0x04,0,0,0,0,
  106605. 0x15,0xed,0xec,0x91,
  106606. 1,
  106607. 17};
  106608. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  106609. const int head1_1[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106610. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106611. 0x01,0x02,0x03,0x04,0,0,0,0,
  106612. 0x59,0x10,0x6c,0x2c,
  106613. 1,
  106614. 17};
  106615. const int head2_1[] = {0x4f,0x67,0x67,0x53,0,0x04,
  106616. 0x07,0x18,0x00,0x00,0x00,0x00,0x00,0x00,
  106617. 0x01,0x02,0x03,0x04,1,0,0,0,
  106618. 0x89,0x33,0x85,0xce,
  106619. 13,
  106620. 254,255,0,255,1,255,245,255,255,0,
  106621. 255,255,90};
  106622. /* nil packets; beginning,middle,end */
  106623. const int head1_2[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106624. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106625. 0x01,0x02,0x03,0x04,0,0,0,0,
  106626. 0xff,0x7b,0x23,0x17,
  106627. 1,
  106628. 0};
  106629. const int head2_2[] = {0x4f,0x67,0x67,0x53,0,0x04,
  106630. 0x07,0x28,0x00,0x00,0x00,0x00,0x00,0x00,
  106631. 0x01,0x02,0x03,0x04,1,0,0,0,
  106632. 0x5c,0x3f,0x66,0xcb,
  106633. 17,
  106634. 17,254,255,0,0,255,1,0,255,245,255,255,0,
  106635. 255,255,90,0};
  106636. /* large initial packet */
  106637. const int head1_3[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106638. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106639. 0x01,0x02,0x03,0x04,0,0,0,0,
  106640. 0x01,0x27,0x31,0xaa,
  106641. 18,
  106642. 255,255,255,255,255,255,255,255,
  106643. 255,255,255,255,255,255,255,255,255,10};
  106644. const int head2_3[] = {0x4f,0x67,0x67,0x53,0,0x04,
  106645. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  106646. 0x01,0x02,0x03,0x04,1,0,0,0,
  106647. 0x7f,0x4e,0x8a,0xd2,
  106648. 4,
  106649. 255,4,255,0};
  106650. /* continuing packet test */
  106651. const int head1_4[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106652. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106653. 0x01,0x02,0x03,0x04,0,0,0,0,
  106654. 0xff,0x7b,0x23,0x17,
  106655. 1,
  106656. 0};
  106657. const int head2_4[] = {0x4f,0x67,0x67,0x53,0,0x00,
  106658. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  106659. 0x01,0x02,0x03,0x04,1,0,0,0,
  106660. 0x54,0x05,0x51,0xc8,
  106661. 17,
  106662. 255,255,255,255,255,255,255,255,
  106663. 255,255,255,255,255,255,255,255,255};
  106664. const int head3_4[] = {0x4f,0x67,0x67,0x53,0,0x05,
  106665. 0x07,0x0c,0x00,0x00,0x00,0x00,0x00,0x00,
  106666. 0x01,0x02,0x03,0x04,2,0,0,0,
  106667. 0xc8,0xc3,0xcb,0xed,
  106668. 5,
  106669. 10,255,4,255,0};
  106670. /* page with the 255 segment limit */
  106671. const int head1_5[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106672. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106673. 0x01,0x02,0x03,0x04,0,0,0,0,
  106674. 0xff,0x7b,0x23,0x17,
  106675. 1,
  106676. 0};
  106677. const int head2_5[] = {0x4f,0x67,0x67,0x53,0,0x00,
  106678. 0x07,0xfc,0x03,0x00,0x00,0x00,0x00,0x00,
  106679. 0x01,0x02,0x03,0x04,1,0,0,0,
  106680. 0xed,0x2a,0x2e,0xa7,
  106681. 255,
  106682. 10,10,10,10,10,10,10,10,
  106683. 10,10,10,10,10,10,10,10,
  106684. 10,10,10,10,10,10,10,10,
  106685. 10,10,10,10,10,10,10,10,
  106686. 10,10,10,10,10,10,10,10,
  106687. 10,10,10,10,10,10,10,10,
  106688. 10,10,10,10,10,10,10,10,
  106689. 10,10,10,10,10,10,10,10,
  106690. 10,10,10,10,10,10,10,10,
  106691. 10,10,10,10,10,10,10,10,
  106692. 10,10,10,10,10,10,10,10,
  106693. 10,10,10,10,10,10,10,10,
  106694. 10,10,10,10,10,10,10,10,
  106695. 10,10,10,10,10,10,10,10,
  106696. 10,10,10,10,10,10,10,10,
  106697. 10,10,10,10,10,10,10,10,
  106698. 10,10,10,10,10,10,10,10,
  106699. 10,10,10,10,10,10,10,10,
  106700. 10,10,10,10,10,10,10,10,
  106701. 10,10,10,10,10,10,10,10,
  106702. 10,10,10,10,10,10,10,10,
  106703. 10,10,10,10,10,10,10,10,
  106704. 10,10,10,10,10,10,10,10,
  106705. 10,10,10,10,10,10,10,10,
  106706. 10,10,10,10,10,10,10,10,
  106707. 10,10,10,10,10,10,10,10,
  106708. 10,10,10,10,10,10,10,10,
  106709. 10,10,10,10,10,10,10,10,
  106710. 10,10,10,10,10,10,10,10,
  106711. 10,10,10,10,10,10,10,10,
  106712. 10,10,10,10,10,10,10,10,
  106713. 10,10,10,10,10,10,10};
  106714. const int head3_5[] = {0x4f,0x67,0x67,0x53,0,0x04,
  106715. 0x07,0x00,0x04,0x00,0x00,0x00,0x00,0x00,
  106716. 0x01,0x02,0x03,0x04,2,0,0,0,
  106717. 0x6c,0x3b,0x82,0x3d,
  106718. 1,
  106719. 50};
  106720. /* packet that overspans over an entire page */
  106721. const int head1_6[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106722. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106723. 0x01,0x02,0x03,0x04,0,0,0,0,
  106724. 0xff,0x7b,0x23,0x17,
  106725. 1,
  106726. 0};
  106727. const int head2_6[] = {0x4f,0x67,0x67,0x53,0,0x00,
  106728. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  106729. 0x01,0x02,0x03,0x04,1,0,0,0,
  106730. 0x3c,0xd9,0x4d,0x3f,
  106731. 17,
  106732. 100,255,255,255,255,255,255,255,255,
  106733. 255,255,255,255,255,255,255,255};
  106734. const int head3_6[] = {0x4f,0x67,0x67,0x53,0,0x01,
  106735. 0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,
  106736. 0x01,0x02,0x03,0x04,2,0,0,0,
  106737. 0x01,0xd2,0xe5,0xe5,
  106738. 17,
  106739. 255,255,255,255,255,255,255,255,
  106740. 255,255,255,255,255,255,255,255,255};
  106741. const int head4_6[] = {0x4f,0x67,0x67,0x53,0,0x05,
  106742. 0x07,0x10,0x00,0x00,0x00,0x00,0x00,0x00,
  106743. 0x01,0x02,0x03,0x04,3,0,0,0,
  106744. 0xef,0xdd,0x88,0xde,
  106745. 7,
  106746. 255,255,75,255,4,255,0};
  106747. /* packet that overspans over an entire page */
  106748. const int head1_7[] = {0x4f,0x67,0x67,0x53,0,0x02,
  106749. 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
  106750. 0x01,0x02,0x03,0x04,0,0,0,0,
  106751. 0xff,0x7b,0x23,0x17,
  106752. 1,
  106753. 0};
  106754. const int head2_7[] = {0x4f,0x67,0x67,0x53,0,0x00,
  106755. 0x07,0x04,0x00,0x00,0x00,0x00,0x00,0x00,
  106756. 0x01,0x02,0x03,0x04,1,0,0,0,
  106757. 0x3c,0xd9,0x4d,0x3f,
  106758. 17,
  106759. 100,255,255,255,255,255,255,255,255,
  106760. 255,255,255,255,255,255,255,255};
  106761. const int head3_7[] = {0x4f,0x67,0x67,0x53,0,0x05,
  106762. 0x07,0x08,0x00,0x00,0x00,0x00,0x00,0x00,
  106763. 0x01,0x02,0x03,0x04,2,0,0,0,
  106764. 0xd4,0xe0,0x60,0xe5,
  106765. 1,0};
  106766. void test_pack(const int *pl, const int **headers, int byteskip,
  106767. int pageskip, int packetskip){
  106768. unsigned char *data=_ogg_malloc(1024*1024); /* for scripted test cases only */
  106769. long inptr=0;
  106770. long outptr=0;
  106771. long deptr=0;
  106772. long depacket=0;
  106773. long granule_pos=7,pageno=0;
  106774. int i,j,packets,pageout=pageskip;
  106775. int eosflag=0;
  106776. int bosflag=0;
  106777. int byteskipcount=0;
  106778. ogg_stream_reset(&os_en);
  106779. ogg_stream_reset(&os_de);
  106780. ogg_sync_reset(&oy);
  106781. for(packets=0;packets<packetskip;packets++)
  106782. depacket+=pl[packets];
  106783. for(packets=0;;packets++)if(pl[packets]==-1)break;
  106784. for(i=0;i<packets;i++){
  106785. /* construct a test packet */
  106786. ogg_packet op;
  106787. int len=pl[i];
  106788. op.packet=data+inptr;
  106789. op.bytes=len;
  106790. op.e_o_s=(pl[i+1]<0?1:0);
  106791. op.granulepos=granule_pos;
  106792. granule_pos+=1024;
  106793. for(j=0;j<len;j++)data[inptr++]=i+j;
  106794. /* submit the test packet */
  106795. ogg_stream_packetin(&os_en,&op);
  106796. /* retrieve any finished pages */
  106797. {
  106798. ogg_page og;
  106799. while(ogg_stream_pageout(&os_en,&og)){
  106800. /* We have a page. Check it carefully */
  106801. fprintf(stderr,"%ld, ",pageno);
  106802. if(headers[pageno]==NULL){
  106803. fprintf(stderr,"coded too many pages!\n");
  106804. exit(1);
  106805. }
  106806. check_page(data+outptr,headers[pageno],&og);
  106807. outptr+=og.body_len;
  106808. pageno++;
  106809. if(pageskip){
  106810. bosflag=1;
  106811. pageskip--;
  106812. deptr+=og.body_len;
  106813. }
  106814. /* have a complete page; submit it to sync/decode */
  106815. {
  106816. ogg_page og_de;
  106817. ogg_packet op_de,op_de2;
  106818. char *buf=ogg_sync_buffer(&oy,og.header_len+og.body_len);
  106819. char *next=buf;
  106820. byteskipcount+=og.header_len;
  106821. if(byteskipcount>byteskip){
  106822. memcpy(next,og.header,byteskipcount-byteskip);
  106823. next+=byteskipcount-byteskip;
  106824. byteskipcount=byteskip;
  106825. }
  106826. byteskipcount+=og.body_len;
  106827. if(byteskipcount>byteskip){
  106828. memcpy(next,og.body,byteskipcount-byteskip);
  106829. next+=byteskipcount-byteskip;
  106830. byteskipcount=byteskip;
  106831. }
  106832. ogg_sync_wrote(&oy,next-buf);
  106833. while(1){
  106834. int ret=ogg_sync_pageout(&oy,&og_de);
  106835. if(ret==0)break;
  106836. if(ret<0)continue;
  106837. /* got a page. Happy happy. Verify that it's good. */
  106838. fprintf(stderr,"(%ld), ",pageout);
  106839. check_page(data+deptr,headers[pageout],&og_de);
  106840. deptr+=og_de.body_len;
  106841. pageout++;
  106842. /* submit it to deconstitution */
  106843. ogg_stream_pagein(&os_de,&og_de);
  106844. /* packets out? */
  106845. while(ogg_stream_packetpeek(&os_de,&op_de2)>0){
  106846. ogg_stream_packetpeek(&os_de,NULL);
  106847. ogg_stream_packetout(&os_de,&op_de); /* just catching them all */
  106848. /* verify peek and out match */
  106849. if(memcmp(&op_de,&op_de2,sizeof(op_de))){
  106850. fprintf(stderr,"packetout != packetpeek! pos=%ld\n",
  106851. depacket);
  106852. exit(1);
  106853. }
  106854. /* verify the packet! */
  106855. /* check data */
  106856. if(memcmp(data+depacket,op_de.packet,op_de.bytes)){
  106857. fprintf(stderr,"packet data mismatch in decode! pos=%ld\n",
  106858. depacket);
  106859. exit(1);
  106860. }
  106861. /* check bos flag */
  106862. if(bosflag==0 && op_de.b_o_s==0){
  106863. fprintf(stderr,"b_o_s flag not set on packet!\n");
  106864. exit(1);
  106865. }
  106866. if(bosflag && op_de.b_o_s){
  106867. fprintf(stderr,"b_o_s flag incorrectly set on packet!\n");
  106868. exit(1);
  106869. }
  106870. bosflag=1;
  106871. depacket+=op_de.bytes;
  106872. /* check eos flag */
  106873. if(eosflag){
  106874. fprintf(stderr,"Multiple decoded packets with eos flag!\n");
  106875. exit(1);
  106876. }
  106877. if(op_de.e_o_s)eosflag=1;
  106878. /* check granulepos flag */
  106879. if(op_de.granulepos!=-1){
  106880. fprintf(stderr," granule:%ld ",(long)op_de.granulepos);
  106881. }
  106882. }
  106883. }
  106884. }
  106885. }
  106886. }
  106887. }
  106888. _ogg_free(data);
  106889. if(headers[pageno]!=NULL){
  106890. fprintf(stderr,"did not write last page!\n");
  106891. exit(1);
  106892. }
  106893. if(headers[pageout]!=NULL){
  106894. fprintf(stderr,"did not decode last page!\n");
  106895. exit(1);
  106896. }
  106897. if(inptr!=outptr){
  106898. fprintf(stderr,"encoded page data incomplete!\n");
  106899. exit(1);
  106900. }
  106901. if(inptr!=deptr){
  106902. fprintf(stderr,"decoded page data incomplete!\n");
  106903. exit(1);
  106904. }
  106905. if(inptr!=depacket){
  106906. fprintf(stderr,"decoded packet data incomplete!\n");
  106907. exit(1);
  106908. }
  106909. if(!eosflag){
  106910. fprintf(stderr,"Never got a packet with EOS set!\n");
  106911. exit(1);
  106912. }
  106913. fprintf(stderr,"ok.\n");
  106914. }
  106915. int main(void){
  106916. ogg_stream_init(&os_en,0x04030201);
  106917. ogg_stream_init(&os_de,0x04030201);
  106918. ogg_sync_init(&oy);
  106919. /* Exercise each code path in the framing code. Also verify that
  106920. the checksums are working. */
  106921. {
  106922. /* 17 only */
  106923. const int packets[]={17, -1};
  106924. const int *headret[]={head1_0,NULL};
  106925. fprintf(stderr,"testing single page encoding... ");
  106926. test_pack(packets,headret,0,0,0);
  106927. }
  106928. {
  106929. /* 17, 254, 255, 256, 500, 510, 600 byte, pad */
  106930. const int packets[]={17, 254, 255, 256, 500, 510, 600, -1};
  106931. const int *headret[]={head1_1,head2_1,NULL};
  106932. fprintf(stderr,"testing basic page encoding... ");
  106933. test_pack(packets,headret,0,0,0);
  106934. }
  106935. {
  106936. /* nil packets; beginning,middle,end */
  106937. const int packets[]={0,17, 254, 255, 0, 256, 0, 500, 510, 600, 0, -1};
  106938. const int *headret[]={head1_2,head2_2,NULL};
  106939. fprintf(stderr,"testing basic nil packets... ");
  106940. test_pack(packets,headret,0,0,0);
  106941. }
  106942. {
  106943. /* large initial packet */
  106944. const int packets[]={4345,259,255,-1};
  106945. const int *headret[]={head1_3,head2_3,NULL};
  106946. fprintf(stderr,"testing initial-packet lacing > 4k... ");
  106947. test_pack(packets,headret,0,0,0);
  106948. }
  106949. {
  106950. /* continuing packet test */
  106951. const int packets[]={0,4345,259,255,-1};
  106952. const int *headret[]={head1_4,head2_4,head3_4,NULL};
  106953. fprintf(stderr,"testing single packet page span... ");
  106954. test_pack(packets,headret,0,0,0);
  106955. }
  106956. /* page with the 255 segment limit */
  106957. {
  106958. const int packets[]={0,10,10,10,10,10,10,10,10,
  106959. 10,10,10,10,10,10,10,10,
  106960. 10,10,10,10,10,10,10,10,
  106961. 10,10,10,10,10,10,10,10,
  106962. 10,10,10,10,10,10,10,10,
  106963. 10,10,10,10,10,10,10,10,
  106964. 10,10,10,10,10,10,10,10,
  106965. 10,10,10,10,10,10,10,10,
  106966. 10,10,10,10,10,10,10,10,
  106967. 10,10,10,10,10,10,10,10,
  106968. 10,10,10,10,10,10,10,10,
  106969. 10,10,10,10,10,10,10,10,
  106970. 10,10,10,10,10,10,10,10,
  106971. 10,10,10,10,10,10,10,10,
  106972. 10,10,10,10,10,10,10,10,
  106973. 10,10,10,10,10,10,10,10,
  106974. 10,10,10,10,10,10,10,10,
  106975. 10,10,10,10,10,10,10,10,
  106976. 10,10,10,10,10,10,10,10,
  106977. 10,10,10,10,10,10,10,10,
  106978. 10,10,10,10,10,10,10,10,
  106979. 10,10,10,10,10,10,10,10,
  106980. 10,10,10,10,10,10,10,10,
  106981. 10,10,10,10,10,10,10,10,
  106982. 10,10,10,10,10,10,10,10,
  106983. 10,10,10,10,10,10,10,10,
  106984. 10,10,10,10,10,10,10,10,
  106985. 10,10,10,10,10,10,10,10,
  106986. 10,10,10,10,10,10,10,10,
  106987. 10,10,10,10,10,10,10,10,
  106988. 10,10,10,10,10,10,10,10,
  106989. 10,10,10,10,10,10,10,50,-1};
  106990. const int *headret[]={head1_5,head2_5,head3_5,NULL};
  106991. fprintf(stderr,"testing max packet segments... ");
  106992. test_pack(packets,headret,0,0,0);
  106993. }
  106994. {
  106995. /* packet that overspans over an entire page */
  106996. const int packets[]={0,100,9000,259,255,-1};
  106997. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  106998. fprintf(stderr,"testing very large packets... ");
  106999. test_pack(packets,headret,0,0,0);
  107000. }
  107001. {
  107002. /* test for the libogg 1.1.1 resync in large continuation bug
  107003. found by Josh Coalson) */
  107004. const int packets[]={0,100,9000,259,255,-1};
  107005. const int *headret[]={head1_6,head2_6,head3_6,head4_6,NULL};
  107006. fprintf(stderr,"testing continuation resync in very large packets... ");
  107007. test_pack(packets,headret,100,2,3);
  107008. }
  107009. {
  107010. /* term only page. why not? */
  107011. const int packets[]={0,100,4080,-1};
  107012. const int *headret[]={head1_7,head2_7,head3_7,NULL};
  107013. fprintf(stderr,"testing zero data page (1 nil packet)... ");
  107014. test_pack(packets,headret,0,0,0);
  107015. }
  107016. {
  107017. /* build a bunch of pages for testing */
  107018. unsigned char *data=_ogg_malloc(1024*1024);
  107019. int pl[]={0,100,4079,2956,2057,76,34,912,0,234,1000,1000,1000,300,-1};
  107020. int inptr=0,i,j;
  107021. ogg_page og[5];
  107022. ogg_stream_reset(&os_en);
  107023. for(i=0;pl[i]!=-1;i++){
  107024. ogg_packet op;
  107025. int len=pl[i];
  107026. op.packet=data+inptr;
  107027. op.bytes=len;
  107028. op.e_o_s=(pl[i+1]<0?1:0);
  107029. op.granulepos=(i+1)*1000;
  107030. for(j=0;j<len;j++)data[inptr++]=i+j;
  107031. ogg_stream_packetin(&os_en,&op);
  107032. }
  107033. _ogg_free(data);
  107034. /* retrieve finished pages */
  107035. for(i=0;i<5;i++){
  107036. if(ogg_stream_pageout(&os_en,&og[i])==0){
  107037. fprintf(stderr,"Too few pages output building sync tests!\n");
  107038. exit(1);
  107039. }
  107040. copy_page(&og[i]);
  107041. }
  107042. /* Test lost pages on pagein/packetout: no rollback */
  107043. {
  107044. ogg_page temp;
  107045. ogg_packet test;
  107046. fprintf(stderr,"Testing loss of pages... ");
  107047. ogg_sync_reset(&oy);
  107048. ogg_stream_reset(&os_de);
  107049. for(i=0;i<5;i++){
  107050. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  107051. og[i].header_len);
  107052. ogg_sync_wrote(&oy,og[i].header_len);
  107053. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  107054. ogg_sync_wrote(&oy,og[i].body_len);
  107055. }
  107056. ogg_sync_pageout(&oy,&temp);
  107057. ogg_stream_pagein(&os_de,&temp);
  107058. ogg_sync_pageout(&oy,&temp);
  107059. ogg_stream_pagein(&os_de,&temp);
  107060. ogg_sync_pageout(&oy,&temp);
  107061. /* skip */
  107062. ogg_sync_pageout(&oy,&temp);
  107063. ogg_stream_pagein(&os_de,&temp);
  107064. /* do we get the expected results/packets? */
  107065. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  107066. checkpacket(&test,0,0,0);
  107067. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  107068. checkpacket(&test,100,1,-1);
  107069. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  107070. checkpacket(&test,4079,2,3000);
  107071. if(ogg_stream_packetout(&os_de,&test)!=-1){
  107072. fprintf(stderr,"Error: loss of page did not return error\n");
  107073. exit(1);
  107074. }
  107075. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  107076. checkpacket(&test,76,5,-1);
  107077. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  107078. checkpacket(&test,34,6,-1);
  107079. fprintf(stderr,"ok.\n");
  107080. }
  107081. /* Test lost pages on pagein/packetout: rollback with continuation */
  107082. {
  107083. ogg_page temp;
  107084. ogg_packet test;
  107085. fprintf(stderr,"Testing loss of pages (rollback required)... ");
  107086. ogg_sync_reset(&oy);
  107087. ogg_stream_reset(&os_de);
  107088. for(i=0;i<5;i++){
  107089. memcpy(ogg_sync_buffer(&oy,og[i].header_len),og[i].header,
  107090. og[i].header_len);
  107091. ogg_sync_wrote(&oy,og[i].header_len);
  107092. memcpy(ogg_sync_buffer(&oy,og[i].body_len),og[i].body,og[i].body_len);
  107093. ogg_sync_wrote(&oy,og[i].body_len);
  107094. }
  107095. ogg_sync_pageout(&oy,&temp);
  107096. ogg_stream_pagein(&os_de,&temp);
  107097. ogg_sync_pageout(&oy,&temp);
  107098. ogg_stream_pagein(&os_de,&temp);
  107099. ogg_sync_pageout(&oy,&temp);
  107100. ogg_stream_pagein(&os_de,&temp);
  107101. ogg_sync_pageout(&oy,&temp);
  107102. /* skip */
  107103. ogg_sync_pageout(&oy,&temp);
  107104. ogg_stream_pagein(&os_de,&temp);
  107105. /* do we get the expected results/packets? */
  107106. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  107107. checkpacket(&test,0,0,0);
  107108. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  107109. checkpacket(&test,100,1,-1);
  107110. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  107111. checkpacket(&test,4079,2,3000);
  107112. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  107113. checkpacket(&test,2956,3,4000);
  107114. if(ogg_stream_packetout(&os_de,&test)!=-1){
  107115. fprintf(stderr,"Error: loss of page did not return error\n");
  107116. exit(1);
  107117. }
  107118. if(ogg_stream_packetout(&os_de,&test)!=1)error();
  107119. checkpacket(&test,300,13,14000);
  107120. fprintf(stderr,"ok.\n");
  107121. }
  107122. /* the rest only test sync */
  107123. {
  107124. ogg_page og_de;
  107125. /* Test fractional page inputs: incomplete capture */
  107126. fprintf(stderr,"Testing sync on partial inputs... ");
  107127. ogg_sync_reset(&oy);
  107128. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  107129. 3);
  107130. ogg_sync_wrote(&oy,3);
  107131. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  107132. /* Test fractional page inputs: incomplete fixed header */
  107133. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+3,
  107134. 20);
  107135. ogg_sync_wrote(&oy,20);
  107136. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  107137. /* Test fractional page inputs: incomplete header */
  107138. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+23,
  107139. 5);
  107140. ogg_sync_wrote(&oy,5);
  107141. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  107142. /* Test fractional page inputs: incomplete body */
  107143. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+28,
  107144. og[1].header_len-28);
  107145. ogg_sync_wrote(&oy,og[1].header_len-28);
  107146. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  107147. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,1000);
  107148. ogg_sync_wrote(&oy,1000);
  107149. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  107150. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body+1000,
  107151. og[1].body_len-1000);
  107152. ogg_sync_wrote(&oy,og[1].body_len-1000);
  107153. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  107154. fprintf(stderr,"ok.\n");
  107155. }
  107156. /* Test fractional page inputs: page + incomplete capture */
  107157. {
  107158. ogg_page og_de;
  107159. fprintf(stderr,"Testing sync on 1+partial inputs... ");
  107160. ogg_sync_reset(&oy);
  107161. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  107162. og[1].header_len);
  107163. ogg_sync_wrote(&oy,og[1].header_len);
  107164. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  107165. og[1].body_len);
  107166. ogg_sync_wrote(&oy,og[1].body_len);
  107167. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  107168. 20);
  107169. ogg_sync_wrote(&oy,20);
  107170. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  107171. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  107172. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header+20,
  107173. og[1].header_len-20);
  107174. ogg_sync_wrote(&oy,og[1].header_len-20);
  107175. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  107176. og[1].body_len);
  107177. ogg_sync_wrote(&oy,og[1].body_len);
  107178. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  107179. fprintf(stderr,"ok.\n");
  107180. }
  107181. /* Test recapture: garbage + page */
  107182. {
  107183. ogg_page og_de;
  107184. fprintf(stderr,"Testing search for capture... ");
  107185. ogg_sync_reset(&oy);
  107186. /* 'garbage' */
  107187. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  107188. og[1].body_len);
  107189. ogg_sync_wrote(&oy,og[1].body_len);
  107190. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  107191. og[1].header_len);
  107192. ogg_sync_wrote(&oy,og[1].header_len);
  107193. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  107194. og[1].body_len);
  107195. ogg_sync_wrote(&oy,og[1].body_len);
  107196. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  107197. 20);
  107198. ogg_sync_wrote(&oy,20);
  107199. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  107200. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  107201. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  107202. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header+20,
  107203. og[2].header_len-20);
  107204. ogg_sync_wrote(&oy,og[2].header_len-20);
  107205. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  107206. og[2].body_len);
  107207. ogg_sync_wrote(&oy,og[2].body_len);
  107208. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  107209. fprintf(stderr,"ok.\n");
  107210. }
  107211. /* Test recapture: page + garbage + page */
  107212. {
  107213. ogg_page og_de;
  107214. fprintf(stderr,"Testing recapture... ");
  107215. ogg_sync_reset(&oy);
  107216. memcpy(ogg_sync_buffer(&oy,og[1].header_len),og[1].header,
  107217. og[1].header_len);
  107218. ogg_sync_wrote(&oy,og[1].header_len);
  107219. memcpy(ogg_sync_buffer(&oy,og[1].body_len),og[1].body,
  107220. og[1].body_len);
  107221. ogg_sync_wrote(&oy,og[1].body_len);
  107222. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  107223. og[2].header_len);
  107224. ogg_sync_wrote(&oy,og[2].header_len);
  107225. memcpy(ogg_sync_buffer(&oy,og[2].header_len),og[2].header,
  107226. og[2].header_len);
  107227. ogg_sync_wrote(&oy,og[2].header_len);
  107228. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  107229. memcpy(ogg_sync_buffer(&oy,og[2].body_len),og[2].body,
  107230. og[2].body_len-5);
  107231. ogg_sync_wrote(&oy,og[2].body_len-5);
  107232. memcpy(ogg_sync_buffer(&oy,og[3].header_len),og[3].header,
  107233. og[3].header_len);
  107234. ogg_sync_wrote(&oy,og[3].header_len);
  107235. memcpy(ogg_sync_buffer(&oy,og[3].body_len),og[3].body,
  107236. og[3].body_len);
  107237. ogg_sync_wrote(&oy,og[3].body_len);
  107238. if(ogg_sync_pageout(&oy,&og_de)>0)error();
  107239. if(ogg_sync_pageout(&oy,&og_de)<=0)error();
  107240. fprintf(stderr,"ok.\n");
  107241. }
  107242. /* Free page data that was previously copied */
  107243. {
  107244. for(i=0;i<5;i++){
  107245. free_page(&og[i]);
  107246. }
  107247. }
  107248. }
  107249. return(0);
  107250. }
  107251. #endif
  107252. #endif
  107253. /********* End of inlined file: framing.c *********/
  107254. /********* Start of inlined file: analysis.c *********/
  107255. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  107256. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  107257. // tasks..
  107258. /********* Start of inlined file: juce_Config.h *********/
  107259. #ifndef __JUCE_CONFIG_JUCEHEADER__
  107260. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  107261. /*
  107262. This file contains macros that enable/disable various JUCE features.
  107263. */
  107264. /** The name of the namespace that all Juce classes and functions will be
  107265. put inside. If this is not defined, no namespace will be used.
  107266. */
  107267. #ifndef JUCE_NAMESPACE
  107268. #define JUCE_NAMESPACE juce
  107269. #endif
  107270. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  107271. but if you define this value, you can override this can force it to be true or
  107272. false.
  107273. */
  107274. #ifndef JUCE_FORCE_DEBUG
  107275. //#define JUCE_FORCE_DEBUG 1
  107276. #endif
  107277. /** If this flag is enabled, the the jassert and jassertfalse macros will
  107278. always use Logger::writeToLog() to write a message when an assertion happens.
  107279. Enabling it will also leave this turned on in release builds. When it's disabled,
  107280. however, the jassert and jassertfalse macros will not be compiled in a
  107281. release build.
  107282. @see jassert, jassertfalse, Logger
  107283. */
  107284. #ifndef JUCE_LOG_ASSERTIONS
  107285. // #define JUCE_LOG_ASSERTIONS 1
  107286. #endif
  107287. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  107288. which the ASIOAudioIODevice class can't be built. See the comments in the
  107289. ASIOAudioIODevice class's header file for more info about this.
  107290. (This only affects a Win32 build)
  107291. */
  107292. #ifndef JUCE_ASIO
  107293. #define JUCE_ASIO 1
  107294. #endif
  107295. /** Comment out this macro to disable building of ALSA device support on Linux.
  107296. */
  107297. #ifndef JUCE_ALSA
  107298. #define JUCE_ALSA 1
  107299. #endif
  107300. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  107301. have the SDK installed.
  107302. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  107303. classes will be unavailable.
  107304. On Windows, if you enable this, you'll need to have the QuickTime SDK
  107305. installed, and its header files will need to be on your include path.
  107306. */
  107307. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  107308. #define JUCE_QUICKTIME 1
  107309. #endif
  107310. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  107311. have the appropriate headers and libraries available. If it's not enabled, the
  107312. OpenGLComponent class will be unavailable.
  107313. */
  107314. #ifndef JUCE_OPENGL
  107315. #define JUCE_OPENGL 1
  107316. #endif
  107317. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  107318. If you're not going to need either of these formats, turn off the flags to
  107319. avoid bloating your codebase with them.
  107320. */
  107321. #ifndef JUCE_USE_FLAC
  107322. #define JUCE_USE_FLAC 1
  107323. #endif
  107324. #ifndef JUCE_USE_OGGVORBIS
  107325. #define JUCE_USE_OGGVORBIS 1
  107326. #endif
  107327. /** This flag lets you enable support for CD-burning. You might want to disable
  107328. it to build without the MS SDK under windows.
  107329. */
  107330. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  107331. #define JUCE_USE_CDBURNER 1
  107332. #endif
  107333. /** Enabling this macro means that all regions that get repainted will have a coloured
  107334. line drawn around them.
  107335. This is handy if you're trying to optimise drawing, because it lets you easily see
  107336. when anything is being repainted unnecessarily.
  107337. */
  107338. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  107339. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  107340. #endif
  107341. /** Enable this under Linux to use Xinerama for multi-monitor support.
  107342. */
  107343. #ifndef JUCE_USE_XINERAMA
  107344. #define JUCE_USE_XINERAMA 1
  107345. #endif
  107346. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  107347. */
  107348. #ifndef JUCE_USE_XSHM
  107349. #define JUCE_USE_XSHM 1
  107350. #endif
  107351. /** Enabling this builds support for VST audio plugins.
  107352. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  107353. */
  107354. #ifndef JUCE_PLUGINHOST_VST
  107355. // #define JUCE_PLUGINHOST_VST 1
  107356. #endif
  107357. /** Enabling this builds support for AudioUnit audio plugins.
  107358. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  107359. */
  107360. #ifndef JUCE_PLUGINHOST_AU
  107361. // #define JUCE_PLUGINHOST_AU 1
  107362. #endif
  107363. /** Disabling this will avoid linking to any UI code. This is handy for
  107364. writing command-line utilities, e.g. on linux boxes which don't have some
  107365. of the UI libraries installed.
  107366. (On mac and windows, this won't generally make much difference to the build).
  107367. */
  107368. #ifndef JUCE_BUILD_GUI_CLASSES
  107369. #define JUCE_BUILD_GUI_CLASSES 1
  107370. #endif
  107371. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  107372. */
  107373. #ifndef JUCE_WEB_BROWSER
  107374. #define JUCE_WEB_BROWSER 1
  107375. #endif
  107376. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  107377. codebase - you might need to use this if you're linking to some of these libraries
  107378. yourself.
  107379. */
  107380. #ifndef JUCE_INCLUDE_ZLIB_CODE
  107381. #define JUCE_INCLUDE_ZLIB_CODE 1
  107382. #endif
  107383. #ifndef JUCE_INCLUDE_FLAC_CODE
  107384. #define JUCE_INCLUDE_FLAC_CODE 1
  107385. #endif
  107386. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  107387. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  107388. #endif
  107389. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  107390. #define JUCE_INCLUDE_PNGLIB_CODE 1
  107391. #endif
  107392. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  107393. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  107394. #endif
  107395. /** Enable this to add extra memory-leak info to the new and delete operators.
  107396. (Currently, this only affects Windows builds in debug mode).
  107397. */
  107398. #ifndef JUCE_CHECK_MEMORY_LEAKS
  107399. #define JUCE_CHECK_MEMORY_LEAKS 1
  107400. #endif
  107401. /** Enable this to turn on juce's internal catching of exceptions.
  107402. Turning it off will avoid any exception catching. With it on, all exceptions
  107403. are passed to the JUCEApplication::unhandledException() callback for logging.
  107404. */
  107405. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  107406. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  107407. #endif
  107408. /** If this macro is set, the Juce String class will use unicode as its
  107409. internal representation. If it isn't set, it'll use ANSI.
  107410. */
  107411. #ifndef JUCE_STRINGS_ARE_UNICODE
  107412. #define JUCE_STRINGS_ARE_UNICODE 1
  107413. #endif
  107414. #endif
  107415. /********* End of inlined file: juce_Config.h *********/
  107416. #ifdef _MSC_VER
  107417. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  107418. #endif
  107419. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  107420. #if JUCE_USE_OGGVORBIS
  107421. #include <stdio.h>
  107422. #include <string.h>
  107423. #include <math.h>
  107424. /********* Start of inlined file: codec_internal.h *********/
  107425. #ifndef _V_CODECI_H_
  107426. #define _V_CODECI_H_
  107427. /********* Start of inlined file: envelope.h *********/
  107428. #ifndef _V_ENVELOPE_
  107429. #define _V_ENVELOPE_
  107430. /********* Start of inlined file: mdct.h *********/
  107431. #ifndef _OGG_mdct_H_
  107432. #define _OGG_mdct_H_
  107433. /*#define MDCT_INTEGERIZED <- be warned there could be some hurt left here*/
  107434. #ifdef MDCT_INTEGERIZED
  107435. #define DATA_TYPE int
  107436. #define REG_TYPE register int
  107437. #define TRIGBITS 14
  107438. #define cPI3_8 6270
  107439. #define cPI2_8 11585
  107440. #define cPI1_8 15137
  107441. #define FLOAT_CONV(x) ((int)((x)*(1<<TRIGBITS)+.5))
  107442. #define MULT_NORM(x) ((x)>>TRIGBITS)
  107443. #define HALVE(x) ((x)>>1)
  107444. #else
  107445. #define DATA_TYPE float
  107446. #define REG_TYPE float
  107447. #define cPI3_8 .38268343236508977175F
  107448. #define cPI2_8 .70710678118654752441F
  107449. #define cPI1_8 .92387953251128675613F
  107450. #define FLOAT_CONV(x) (x)
  107451. #define MULT_NORM(x) (x)
  107452. #define HALVE(x) ((x)*.5f)
  107453. #endif
  107454. typedef struct {
  107455. int n;
  107456. int log2n;
  107457. DATA_TYPE *trig;
  107458. int *bitrev;
  107459. DATA_TYPE scale;
  107460. } mdct_lookup;
  107461. extern void mdct_init(mdct_lookup *lookup,int n);
  107462. extern void mdct_clear(mdct_lookup *l);
  107463. extern void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  107464. extern void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out);
  107465. #endif
  107466. /********* End of inlined file: mdct.h *********/
  107467. #define VE_PRE 16
  107468. #define VE_WIN 4
  107469. #define VE_POST 2
  107470. #define VE_AMP (VE_PRE+VE_POST-1)
  107471. #define VE_BANDS 7
  107472. #define VE_NEARDC 15
  107473. #define VE_MINSTRETCH 2 /* a bit less than short block */
  107474. #define VE_MAXSTRETCH 12 /* one-third full block */
  107475. typedef struct {
  107476. float ampbuf[VE_AMP];
  107477. int ampptr;
  107478. float nearDC[VE_NEARDC];
  107479. float nearDC_acc;
  107480. float nearDC_partialacc;
  107481. int nearptr;
  107482. } envelope_filter_state;
  107483. typedef struct {
  107484. int begin;
  107485. int end;
  107486. float *window;
  107487. float total;
  107488. } envelope_band;
  107489. typedef struct {
  107490. int ch;
  107491. int winlength;
  107492. int searchstep;
  107493. float minenergy;
  107494. mdct_lookup mdct;
  107495. float *mdct_win;
  107496. envelope_band band[VE_BANDS];
  107497. envelope_filter_state *filter;
  107498. int stretch;
  107499. int *mark;
  107500. long storage;
  107501. long current;
  107502. long curmark;
  107503. long cursor;
  107504. } envelope_lookup;
  107505. extern void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi);
  107506. extern void _ve_envelope_clear(envelope_lookup *e);
  107507. extern long _ve_envelope_search(vorbis_dsp_state *v);
  107508. extern void _ve_envelope_shift(envelope_lookup *e,long shift);
  107509. extern int _ve_envelope_mark(vorbis_dsp_state *v);
  107510. #endif
  107511. /********* End of inlined file: envelope.h *********/
  107512. /********* Start of inlined file: codebook.h *********/
  107513. #ifndef _V_CODEBOOK_H_
  107514. #define _V_CODEBOOK_H_
  107515. /* This structure encapsulates huffman and VQ style encoding books; it
  107516. doesn't do anything specific to either.
  107517. valuelist/quantlist are nonNULL (and q_* significant) only if
  107518. there's entry->value mapping to be done.
  107519. If encode-side mapping must be done (and thus the entry needs to be
  107520. hunted), the auxiliary encode pointer will point to a decision
  107521. tree. This is true of both VQ and huffman, but is mostly useful
  107522. with VQ.
  107523. */
  107524. typedef struct static_codebook{
  107525. long dim; /* codebook dimensions (elements per vector) */
  107526. long entries; /* codebook entries */
  107527. long *lengthlist; /* codeword lengths in bits */
  107528. /* mapping ***************************************************************/
  107529. int maptype; /* 0=none
  107530. 1=implicitly populated values from map column
  107531. 2=listed arbitrary values */
  107532. /* The below does a linear, single monotonic sequence mapping. */
  107533. long q_min; /* packed 32 bit float; quant value 0 maps to minval */
  107534. long q_delta; /* packed 32 bit float; val 1 - val 0 == delta */
  107535. int q_quant; /* bits: 0 < quant <= 16 */
  107536. int q_sequencep; /* bitflag */
  107537. long *quantlist; /* map == 1: (int)(entries^(1/dim)) element column map
  107538. map == 2: list of dim*entries quantized entry vals
  107539. */
  107540. /* encode helpers ********************************************************/
  107541. struct encode_aux_nearestmatch *nearest_tree;
  107542. struct encode_aux_threshmatch *thresh_tree;
  107543. struct encode_aux_pigeonhole *pigeon_tree;
  107544. int allocedp;
  107545. } static_codebook;
  107546. /* this structures an arbitrary trained book to quickly find the
  107547. nearest cell match */
  107548. typedef struct encode_aux_nearestmatch{
  107549. /* pre-calculated partitioning tree */
  107550. long *ptr0;
  107551. long *ptr1;
  107552. long *p; /* decision points (each is an entry) */
  107553. long *q; /* decision points (each is an entry) */
  107554. long aux; /* number of tree entries */
  107555. long alloc;
  107556. } encode_aux_nearestmatch;
  107557. /* assumes a maptype of 1; encode side only, so that's OK */
  107558. typedef struct encode_aux_threshmatch{
  107559. float *quantthresh;
  107560. long *quantmap;
  107561. int quantvals;
  107562. int threshvals;
  107563. } encode_aux_threshmatch;
  107564. typedef struct encode_aux_pigeonhole{
  107565. float min;
  107566. float del;
  107567. int mapentries;
  107568. int quantvals;
  107569. long *pigeonmap;
  107570. long fittotal;
  107571. long *fitlist;
  107572. long *fitmap;
  107573. long *fitlength;
  107574. } encode_aux_pigeonhole;
  107575. typedef struct codebook{
  107576. long dim; /* codebook dimensions (elements per vector) */
  107577. long entries; /* codebook entries */
  107578. long used_entries; /* populated codebook entries */
  107579. const static_codebook *c;
  107580. /* for encode, the below are entry-ordered, fully populated */
  107581. /* for decode, the below are ordered by bitreversed codeword and only
  107582. used entries are populated */
  107583. float *valuelist; /* list of dim*entries actual entry values */
  107584. ogg_uint32_t *codelist; /* list of bitstream codewords for each entry */
  107585. int *dec_index; /* only used if sparseness collapsed */
  107586. char *dec_codelengths;
  107587. ogg_uint32_t *dec_firsttable;
  107588. int dec_firsttablen;
  107589. int dec_maxlength;
  107590. } codebook;
  107591. extern void vorbis_staticbook_clear(static_codebook *b);
  107592. extern void vorbis_staticbook_destroy(static_codebook *b);
  107593. extern int vorbis_book_init_encode(codebook *dest,const static_codebook *source);
  107594. extern int vorbis_book_init_decode(codebook *dest,const static_codebook *source);
  107595. extern void vorbis_book_clear(codebook *b);
  107596. extern float *_book_unquantize(const static_codebook *b,int n,int *map);
  107597. extern float *_book_logdist(const static_codebook *b,float *vals);
  107598. extern float _float32_unpack(long val);
  107599. extern long _float32_pack(float val);
  107600. extern int _best(codebook *book, float *a, int step);
  107601. extern int _ilog(unsigned int v);
  107602. extern long _book_maptype1_quantvals(const static_codebook *b);
  107603. extern int vorbis_book_besterror(codebook *book,float *a,int step,int addmul);
  107604. extern long vorbis_book_codeword(codebook *book,int entry);
  107605. extern long vorbis_book_codelen(codebook *book,int entry);
  107606. extern int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *b);
  107607. extern int vorbis_staticbook_unpack(oggpack_buffer *b,static_codebook *c);
  107608. extern int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b);
  107609. extern int vorbis_book_errorv(codebook *book, float *a);
  107610. extern int vorbis_book_encodev(codebook *book, int best,float *a,
  107611. oggpack_buffer *b);
  107612. extern long vorbis_book_decode(codebook *book, oggpack_buffer *b);
  107613. extern long vorbis_book_decodevs_add(codebook *book, float *a,
  107614. oggpack_buffer *b,int n);
  107615. extern long vorbis_book_decodev_set(codebook *book, float *a,
  107616. oggpack_buffer *b,int n);
  107617. extern long vorbis_book_decodev_add(codebook *book, float *a,
  107618. oggpack_buffer *b,int n);
  107619. extern long vorbis_book_decodevv_add(codebook *book, float **a,
  107620. long off,int ch,
  107621. oggpack_buffer *b,int n);
  107622. #endif
  107623. /********* End of inlined file: codebook.h *********/
  107624. #define BLOCKTYPE_IMPULSE 0
  107625. #define BLOCKTYPE_PADDING 1
  107626. #define BLOCKTYPE_TRANSITION 0
  107627. #define BLOCKTYPE_LONG 1
  107628. #define PACKETBLOBS 15
  107629. typedef struct vorbis_block_internal{
  107630. float **pcmdelay; /* this is a pointer into local storage */
  107631. float ampmax;
  107632. int blocktype;
  107633. oggpack_buffer *packetblob[PACKETBLOBS]; /* initialized, must be freed;
  107634. blob [PACKETBLOBS/2] points to
  107635. the oggpack_buffer in the
  107636. main vorbis_block */
  107637. } vorbis_block_internal;
  107638. typedef void vorbis_look_floor;
  107639. typedef void vorbis_look_residue;
  107640. typedef void vorbis_look_transform;
  107641. /* mode ************************************************************/
  107642. typedef struct {
  107643. int blockflag;
  107644. int windowtype;
  107645. int transformtype;
  107646. int mapping;
  107647. } vorbis_info_mode;
  107648. typedef void vorbis_info_floor;
  107649. typedef void vorbis_info_residue;
  107650. typedef void vorbis_info_mapping;
  107651. /********* Start of inlined file: psy.h *********/
  107652. #ifndef _V_PSY_H_
  107653. #define _V_PSY_H_
  107654. /********* Start of inlined file: smallft.h *********/
  107655. #ifndef _V_SMFT_H_
  107656. #define _V_SMFT_H_
  107657. typedef struct {
  107658. int n;
  107659. float *trigcache;
  107660. int *splitcache;
  107661. } drft_lookup;
  107662. extern void drft_forward(drft_lookup *l,float *data);
  107663. extern void drft_backward(drft_lookup *l,float *data);
  107664. extern void drft_init(drft_lookup *l,int n);
  107665. extern void drft_clear(drft_lookup *l);
  107666. #endif
  107667. /********* End of inlined file: smallft.h *********/
  107668. /********* Start of inlined file: backends.h *********/
  107669. /* this is exposed up here because we need it for static modes.
  107670. Lookups for each backend aren't exposed because there's no reason
  107671. to do so */
  107672. #ifndef _vorbis_backend_h_
  107673. #define _vorbis_backend_h_
  107674. /* this would all be simpler/shorter with templates, but.... */
  107675. /* Floor backend generic *****************************************/
  107676. typedef struct{
  107677. void (*pack) (vorbis_info_floor *,oggpack_buffer *);
  107678. vorbis_info_floor *(*unpack)(vorbis_info *,oggpack_buffer *);
  107679. vorbis_look_floor *(*look) (vorbis_dsp_state *,vorbis_info_floor *);
  107680. void (*free_info) (vorbis_info_floor *);
  107681. void (*free_look) (vorbis_look_floor *);
  107682. void *(*inverse1) (struct vorbis_block *,vorbis_look_floor *);
  107683. int (*inverse2) (struct vorbis_block *,vorbis_look_floor *,
  107684. void *buffer,float *);
  107685. } vorbis_func_floor;
  107686. typedef struct{
  107687. int order;
  107688. long rate;
  107689. long barkmap;
  107690. int ampbits;
  107691. int ampdB;
  107692. int numbooks; /* <= 16 */
  107693. int books[16];
  107694. float lessthan; /* encode-only config setting hacks for libvorbis */
  107695. float greaterthan; /* encode-only config setting hacks for libvorbis */
  107696. } vorbis_info_floor0;
  107697. #define VIF_POSIT 63
  107698. #define VIF_CLASS 16
  107699. #define VIF_PARTS 31
  107700. typedef struct{
  107701. int partitions; /* 0 to 31 */
  107702. int partitionclass[VIF_PARTS]; /* 0 to 15 */
  107703. int class_dim[VIF_CLASS]; /* 1 to 8 */
  107704. int class_subs[VIF_CLASS]; /* 0,1,2,3 (bits: 1<<n poss) */
  107705. int class_book[VIF_CLASS]; /* subs ^ dim entries */
  107706. int class_subbook[VIF_CLASS][8]; /* [VIF_CLASS][subs] */
  107707. int mult; /* 1 2 3 or 4 */
  107708. int postlist[VIF_POSIT+2]; /* first two implicit */
  107709. /* encode side analysis parameters */
  107710. float maxover;
  107711. float maxunder;
  107712. float maxerr;
  107713. float twofitweight;
  107714. float twofitatten;
  107715. int n;
  107716. } vorbis_info_floor1;
  107717. /* Residue backend generic *****************************************/
  107718. typedef struct{
  107719. void (*pack) (vorbis_info_residue *,oggpack_buffer *);
  107720. vorbis_info_residue *(*unpack)(vorbis_info *,oggpack_buffer *);
  107721. vorbis_look_residue *(*look) (vorbis_dsp_state *,
  107722. vorbis_info_residue *);
  107723. void (*free_info) (vorbis_info_residue *);
  107724. void (*free_look) (vorbis_look_residue *);
  107725. long **(*classx) (struct vorbis_block *,vorbis_look_residue *,
  107726. float **,int *,int);
  107727. int (*forward) (oggpack_buffer *,struct vorbis_block *,
  107728. vorbis_look_residue *,
  107729. float **,float **,int *,int,long **);
  107730. int (*inverse) (struct vorbis_block *,vorbis_look_residue *,
  107731. float **,int *,int);
  107732. } vorbis_func_residue;
  107733. typedef struct vorbis_info_residue0{
  107734. /* block-partitioned VQ coded straight residue */
  107735. long begin;
  107736. long end;
  107737. /* first stage (lossless partitioning) */
  107738. int grouping; /* group n vectors per partition */
  107739. int partitions; /* possible codebooks for a partition */
  107740. int groupbook; /* huffbook for partitioning */
  107741. int secondstages[64]; /* expanded out to pointers in lookup */
  107742. int booklist[256]; /* list of second stage books */
  107743. float classmetric1[64];
  107744. float classmetric2[64];
  107745. } vorbis_info_residue0;
  107746. /* Mapping backend generic *****************************************/
  107747. typedef struct{
  107748. void (*pack) (vorbis_info *,vorbis_info_mapping *,
  107749. oggpack_buffer *);
  107750. vorbis_info_mapping *(*unpack)(vorbis_info *,oggpack_buffer *);
  107751. void (*free_info) (vorbis_info_mapping *);
  107752. int (*forward) (struct vorbis_block *vb);
  107753. int (*inverse) (struct vorbis_block *vb,vorbis_info_mapping *);
  107754. } vorbis_func_mapping;
  107755. typedef struct vorbis_info_mapping0{
  107756. int submaps; /* <= 16 */
  107757. int chmuxlist[256]; /* up to 256 channels in a Vorbis stream */
  107758. int floorsubmap[16]; /* [mux] submap to floors */
  107759. int residuesubmap[16]; /* [mux] submap to residue */
  107760. int coupling_steps;
  107761. int coupling_mag[256];
  107762. int coupling_ang[256];
  107763. } vorbis_info_mapping0;
  107764. #endif
  107765. /********* End of inlined file: backends.h *********/
  107766. #ifndef EHMER_MAX
  107767. #define EHMER_MAX 56
  107768. #endif
  107769. /* psychoacoustic setup ********************************************/
  107770. #define P_BANDS 17 /* 62Hz to 16kHz */
  107771. #define P_LEVELS 8 /* 30dB to 100dB */
  107772. #define P_LEVEL_0 30. /* 30 dB */
  107773. #define P_NOISECURVES 3
  107774. #define NOISE_COMPAND_LEVELS 40
  107775. typedef struct vorbis_info_psy{
  107776. int blockflag;
  107777. float ath_adjatt;
  107778. float ath_maxatt;
  107779. float tone_masteratt[P_NOISECURVES];
  107780. float tone_centerboost;
  107781. float tone_decay;
  107782. float tone_abs_limit;
  107783. float toneatt[P_BANDS];
  107784. int noisemaskp;
  107785. float noisemaxsupp;
  107786. float noisewindowlo;
  107787. float noisewindowhi;
  107788. int noisewindowlomin;
  107789. int noisewindowhimin;
  107790. int noisewindowfixed;
  107791. float noiseoff[P_NOISECURVES][P_BANDS];
  107792. float noisecompand[NOISE_COMPAND_LEVELS];
  107793. float max_curve_dB;
  107794. int normal_channel_p;
  107795. int normal_point_p;
  107796. int normal_start;
  107797. int normal_partition;
  107798. double normal_thresh;
  107799. } vorbis_info_psy;
  107800. typedef struct{
  107801. int eighth_octave_lines;
  107802. /* for block long/short tuning; encode only */
  107803. float preecho_thresh[VE_BANDS];
  107804. float postecho_thresh[VE_BANDS];
  107805. float stretch_penalty;
  107806. float preecho_minenergy;
  107807. float ampmax_att_per_sec;
  107808. /* channel coupling config */
  107809. int coupling_pkHz[PACKETBLOBS];
  107810. int coupling_pointlimit[2][PACKETBLOBS];
  107811. int coupling_prepointamp[PACKETBLOBS];
  107812. int coupling_postpointamp[PACKETBLOBS];
  107813. int sliding_lowpass[2][PACKETBLOBS];
  107814. } vorbis_info_psy_global;
  107815. typedef struct {
  107816. float ampmax;
  107817. int channels;
  107818. vorbis_info_psy_global *gi;
  107819. int coupling_pointlimit[2][P_NOISECURVES];
  107820. } vorbis_look_psy_global;
  107821. typedef struct {
  107822. int n;
  107823. struct vorbis_info_psy *vi;
  107824. float ***tonecurves;
  107825. float **noiseoffset;
  107826. float *ath;
  107827. long *octave; /* in n.ocshift format */
  107828. long *bark;
  107829. long firstoc;
  107830. long shiftoc;
  107831. int eighth_octave_lines; /* power of two, please */
  107832. int total_octave_lines;
  107833. long rate; /* cache it */
  107834. float m_val; /* Masking compensation value */
  107835. } vorbis_look_psy;
  107836. extern void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  107837. vorbis_info_psy_global *gi,int n,long rate);
  107838. extern void _vp_psy_clear(vorbis_look_psy *p);
  107839. extern void *_vi_psy_dup(void *source);
  107840. extern void _vi_psy_free(vorbis_info_psy *i);
  107841. extern vorbis_info_psy *_vi_psy_copy(vorbis_info_psy *i);
  107842. extern void _vp_remove_floor(vorbis_look_psy *p,
  107843. float *mdct,
  107844. int *icodedflr,
  107845. float *residue,
  107846. int sliding_lowpass);
  107847. extern void _vp_noisemask(vorbis_look_psy *p,
  107848. float *logmdct,
  107849. float *logmask);
  107850. extern void _vp_tonemask(vorbis_look_psy *p,
  107851. float *logfft,
  107852. float *logmask,
  107853. float global_specmax,
  107854. float local_specmax);
  107855. extern void _vp_offset_and_mix(vorbis_look_psy *p,
  107856. float *noise,
  107857. float *tone,
  107858. int offset_select,
  107859. float *logmask,
  107860. float *mdct,
  107861. float *logmdct);
  107862. extern float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd);
  107863. extern float **_vp_quantize_couple_memo(vorbis_block *vb,
  107864. vorbis_info_psy_global *g,
  107865. vorbis_look_psy *p,
  107866. vorbis_info_mapping0 *vi,
  107867. float **mdct);
  107868. extern void _vp_couple(int blobno,
  107869. vorbis_info_psy_global *g,
  107870. vorbis_look_psy *p,
  107871. vorbis_info_mapping0 *vi,
  107872. float **res,
  107873. float **mag_memo,
  107874. int **mag_sort,
  107875. int **ifloor,
  107876. int *nonzero,
  107877. int sliding_lowpass);
  107878. extern void _vp_noise_normalize(vorbis_look_psy *p,
  107879. float *in,float *out,int *sortedindex);
  107880. extern void _vp_noise_normalize_sort(vorbis_look_psy *p,
  107881. float *magnitudes,int *sortedindex);
  107882. extern int **_vp_quantize_couple_sort(vorbis_block *vb,
  107883. vorbis_look_psy *p,
  107884. vorbis_info_mapping0 *vi,
  107885. float **mags);
  107886. extern void hf_reduction(vorbis_info_psy_global *g,
  107887. vorbis_look_psy *p,
  107888. vorbis_info_mapping0 *vi,
  107889. float **mdct);
  107890. #endif
  107891. /********* End of inlined file: psy.h *********/
  107892. /********* Start of inlined file: bitrate.h *********/
  107893. #ifndef _V_BITRATE_H_
  107894. #define _V_BITRATE_H_
  107895. /********* Start of inlined file: os.h *********/
  107896. #ifndef _OS_H
  107897. #define _OS_H
  107898. /********************************************************************
  107899. * *
  107900. * THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
  107901. * USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
  107902. * GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
  107903. * IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
  107904. * *
  107905. * THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2002 *
  107906. * by the XIPHOPHORUS Company http://www.xiph.org/ *
  107907. * *
  107908. ********************************************************************
  107909. function: #ifdef jail to whip a few platforms into the UNIX ideal.
  107910. last mod: $Id: os.h,v 1.1 2007/06/07 17:49:18 jules_rms Exp $
  107911. ********************************************************************/
  107912. #ifdef HAVE_CONFIG_H
  107913. #include "config.h"
  107914. #endif
  107915. #include <math.h>
  107916. /********* Start of inlined file: misc.h *********/
  107917. #ifndef _V_RANDOM_H_
  107918. #define _V_RANDOM_H_
  107919. extern int analysis_noisy;
  107920. extern void *_vorbis_block_alloc(vorbis_block *vb,long bytes);
  107921. extern void _vorbis_block_ripcord(vorbis_block *vb);
  107922. extern void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  107923. ogg_int64_t off);
  107924. #ifdef DEBUG_MALLOC
  107925. #define _VDBG_GRAPHFILE "malloc.m"
  107926. extern void *_VDBG_malloc(void *ptr,long bytes,char *file,long line);
  107927. extern void _VDBG_free(void *ptr,char *file,long line);
  107928. #ifndef MISC_C
  107929. #undef _ogg_malloc
  107930. #undef _ogg_calloc
  107931. #undef _ogg_realloc
  107932. #undef _ogg_free
  107933. #define _ogg_malloc(x) _VDBG_malloc(NULL,(x),__FILE__,__LINE__)
  107934. #define _ogg_calloc(x,y) _VDBG_malloc(NULL,(x)*(y),__FILE__,__LINE__)
  107935. #define _ogg_realloc(x,y) _VDBG_malloc((x),(y),__FILE__,__LINE__)
  107936. #define _ogg_free(x) _VDBG_free((x),__FILE__,__LINE__)
  107937. #endif
  107938. #endif
  107939. #endif
  107940. /********* End of inlined file: misc.h *********/
  107941. #ifndef _V_IFDEFJAIL_H_
  107942. # define _V_IFDEFJAIL_H_
  107943. # ifdef __GNUC__
  107944. # define STIN static __inline__
  107945. # elif _WIN32
  107946. # define STIN static __inline
  107947. # else
  107948. # define STIN static
  107949. # endif
  107950. #ifdef DJGPP
  107951. # define rint(x) (floor((x)+0.5f))
  107952. #endif
  107953. #ifndef M_PI
  107954. # define M_PI (3.1415926536f)
  107955. #endif
  107956. #if defined(_WIN32) && !defined(__SYMBIAN32__)
  107957. # include <malloc.h>
  107958. # define rint(x) (floor((x)+0.5f))
  107959. # define NO_FLOAT_MATH_LIB
  107960. # define FAST_HYPOT(a, b) sqrt((a)*(a) + (b)*(b))
  107961. #endif
  107962. #if defined(__SYMBIAN32__) && defined(__WINS__)
  107963. void *_alloca(size_t size);
  107964. # define alloca _alloca
  107965. #endif
  107966. #ifndef FAST_HYPOT
  107967. # define FAST_HYPOT hypot
  107968. #endif
  107969. #endif
  107970. #ifdef HAVE_ALLOCA_H
  107971. # include <alloca.h>
  107972. #endif
  107973. #ifdef USE_MEMORY_H
  107974. # include <memory.h>
  107975. #endif
  107976. #ifndef min
  107977. # define min(x,y) ((x)>(y)?(y):(x))
  107978. #endif
  107979. #ifndef max
  107980. # define max(x,y) ((x)<(y)?(y):(x))
  107981. #endif
  107982. #if defined(__i386__) && defined(__GNUC__) && !defined(__BEOS__)
  107983. # define VORBIS_FPU_CONTROL
  107984. /* both GCC and MSVC are kinda stupid about rounding/casting to int.
  107985. Because of encapsulation constraints (GCC can't see inside the asm
  107986. block and so we end up doing stupid things like a store/load that
  107987. is collectively a noop), we do it this way */
  107988. /* we must set up the fpu before this works!! */
  107989. typedef ogg_int16_t vorbis_fpu_control;
  107990. static inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  107991. ogg_int16_t ret;
  107992. ogg_int16_t temp;
  107993. __asm__ __volatile__("fnstcw %0\n\t"
  107994. "movw %0,%%dx\n\t"
  107995. "orw $62463,%%dx\n\t"
  107996. "movw %%dx,%1\n\t"
  107997. "fldcw %1\n\t":"=m"(ret):"m"(temp): "dx");
  107998. *fpu=ret;
  107999. }
  108000. static inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  108001. __asm__ __volatile__("fldcw %0":: "m"(fpu));
  108002. }
  108003. /* assumes the FPU is in round mode! */
  108004. static inline int vorbis_ftoi(double f){ /* yes, double! Otherwise,
  108005. we get extra fst/fld to
  108006. truncate precision */
  108007. int i;
  108008. __asm__("fistl %0": "=m"(i) : "t"(f));
  108009. return(i);
  108010. }
  108011. #endif
  108012. #if defined(_WIN32) && defined(_X86_) && !defined(__GNUC__) && !defined(__BORLANDC__)
  108013. # define VORBIS_FPU_CONTROL
  108014. typedef ogg_int16_t vorbis_fpu_control;
  108015. static __inline int vorbis_ftoi(double f){
  108016. int i;
  108017. __asm{
  108018. fld f
  108019. fistp i
  108020. }
  108021. return i;
  108022. }
  108023. static __inline void vorbis_fpu_setround(vorbis_fpu_control *fpu){
  108024. }
  108025. static __inline void vorbis_fpu_restore(vorbis_fpu_control fpu){
  108026. }
  108027. #endif
  108028. #ifndef VORBIS_FPU_CONTROL
  108029. typedef int vorbis_fpu_control;
  108030. static int vorbis_ftoi(double f){
  108031. return (int)(f+.5);
  108032. }
  108033. /* We don't have special code for this compiler/arch, so do it the slow way */
  108034. # define vorbis_fpu_setround(vorbis_fpu_control) {}
  108035. # define vorbis_fpu_restore(vorbis_fpu_control) {}
  108036. #endif
  108037. #endif /* _OS_H */
  108038. /********* End of inlined file: os.h *********/
  108039. /* encode side bitrate tracking */
  108040. typedef struct bitrate_manager_state {
  108041. int managed;
  108042. long avg_reservoir;
  108043. long minmax_reservoir;
  108044. long avg_bitsper;
  108045. long min_bitsper;
  108046. long max_bitsper;
  108047. long short_per_long;
  108048. double avgfloat;
  108049. vorbis_block *vb;
  108050. int choice;
  108051. } bitrate_manager_state;
  108052. typedef struct bitrate_manager_info{
  108053. long avg_rate;
  108054. long min_rate;
  108055. long max_rate;
  108056. long reservoir_bits;
  108057. double reservoir_bias;
  108058. double slew_damp;
  108059. } bitrate_manager_info;
  108060. extern void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bs);
  108061. extern void vorbis_bitrate_clear(bitrate_manager_state *bs);
  108062. extern int vorbis_bitrate_managed(vorbis_block *vb);
  108063. extern int vorbis_bitrate_addblock(vorbis_block *vb);
  108064. extern int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd, ogg_packet *op);
  108065. #endif
  108066. /********* End of inlined file: bitrate.h *********/
  108067. static int ilog(unsigned int v){
  108068. int ret=0;
  108069. while(v){
  108070. ret++;
  108071. v>>=1;
  108072. }
  108073. return(ret);
  108074. }
  108075. static int ilog2(unsigned int v){
  108076. int ret=0;
  108077. if(v)--v;
  108078. while(v){
  108079. ret++;
  108080. v>>=1;
  108081. }
  108082. return(ret);
  108083. }
  108084. typedef struct private_state {
  108085. /* local lookup storage */
  108086. envelope_lookup *ve; /* envelope lookup */
  108087. int window[2];
  108088. vorbis_look_transform **transform[2]; /* block, type */
  108089. drft_lookup fft_look[2];
  108090. int modebits;
  108091. vorbis_look_floor **flr;
  108092. vorbis_look_residue **residue;
  108093. vorbis_look_psy *psy;
  108094. vorbis_look_psy_global *psy_g_look;
  108095. /* local storage, only used on the encoding side. This way the
  108096. application does not need to worry about freeing some packets'
  108097. memory and not others'; packet storage is always tracked.
  108098. Cleared next call to a _dsp_ function */
  108099. unsigned char *header;
  108100. unsigned char *header1;
  108101. unsigned char *header2;
  108102. bitrate_manager_state bms;
  108103. ogg_int64_t sample_count;
  108104. } private_state;
  108105. /* codec_setup_info contains all the setup information specific to the
  108106. specific compression/decompression mode in progress (eg,
  108107. psychoacoustic settings, channel setup, options, codebook
  108108. etc).
  108109. *********************************************************************/
  108110. /********* Start of inlined file: highlevel.h *********/
  108111. typedef struct highlevel_byblocktype {
  108112. double tone_mask_setting;
  108113. double tone_peaklimit_setting;
  108114. double noise_bias_setting;
  108115. double noise_compand_setting;
  108116. } highlevel_byblocktype;
  108117. typedef struct highlevel_encode_setup {
  108118. void *setup;
  108119. int set_in_stone;
  108120. double base_setting;
  108121. double long_setting;
  108122. double short_setting;
  108123. double impulse_noisetune;
  108124. int managed;
  108125. long bitrate_min;
  108126. long bitrate_av;
  108127. double bitrate_av_damp;
  108128. long bitrate_max;
  108129. long bitrate_reservoir;
  108130. double bitrate_reservoir_bias;
  108131. int impulse_block_p;
  108132. int noise_normalize_p;
  108133. double stereo_point_setting;
  108134. double lowpass_kHz;
  108135. double ath_floating_dB;
  108136. double ath_absolute_dB;
  108137. double amplitude_track_dBpersec;
  108138. double trigger_setting;
  108139. highlevel_byblocktype block[4]; /* padding, impulse, transition, long */
  108140. } highlevel_encode_setup;
  108141. /********* End of inlined file: highlevel.h *********/
  108142. typedef struct codec_setup_info {
  108143. /* Vorbis supports only short and long blocks, but allows the
  108144. encoder to choose the sizes */
  108145. long blocksizes[2];
  108146. /* modes are the primary means of supporting on-the-fly different
  108147. blocksizes, different channel mappings (LR or M/A),
  108148. different residue backends, etc. Each mode consists of a
  108149. blocksize flag and a mapping (along with the mapping setup */
  108150. int modes;
  108151. int maps;
  108152. int floors;
  108153. int residues;
  108154. int books;
  108155. int psys; /* encode only */
  108156. vorbis_info_mode *mode_param[64];
  108157. int map_type[64];
  108158. vorbis_info_mapping *map_param[64];
  108159. int floor_type[64];
  108160. vorbis_info_floor *floor_param[64];
  108161. int residue_type[64];
  108162. vorbis_info_residue *residue_param[64];
  108163. static_codebook *book_param[256];
  108164. codebook *fullbooks;
  108165. vorbis_info_psy *psy_param[4]; /* encode only */
  108166. vorbis_info_psy_global psy_g_param;
  108167. bitrate_manager_info bi;
  108168. highlevel_encode_setup hi; /* used only by vorbisenc.c. It's a
  108169. highly redundant structure, but
  108170. improves clarity of program flow. */
  108171. int halfrate_flag; /* painless downsample for decode */
  108172. } codec_setup_info;
  108173. extern vorbis_look_psy_global *_vp_global_look(vorbis_info *vi);
  108174. extern void _vp_global_free(vorbis_look_psy_global *look);
  108175. #endif
  108176. /********* End of inlined file: codec_internal.h *********/
  108177. /********* Start of inlined file: registry.h *********/
  108178. #ifndef _V_REG_H_
  108179. #define _V_REG_H_
  108180. #define VI_TRANSFORMB 1
  108181. #define VI_WINDOWB 1
  108182. #define VI_TIMEB 1
  108183. #define VI_FLOORB 2
  108184. #define VI_RESB 3
  108185. #define VI_MAPB 1
  108186. extern vorbis_func_floor *_floor_P[];
  108187. extern vorbis_func_residue *_residue_P[];
  108188. extern vorbis_func_mapping *_mapping_P[];
  108189. #endif
  108190. /********* End of inlined file: registry.h *********/
  108191. /********* Start of inlined file: scales.h *********/
  108192. #ifndef _V_SCALES_H_
  108193. #define _V_SCALES_H_
  108194. #include <math.h>
  108195. /* 20log10(x) */
  108196. #define VORBIS_IEEE_FLOAT32 1
  108197. #ifdef VORBIS_IEEE_FLOAT32
  108198. static float unitnorm(float x){
  108199. union {
  108200. ogg_uint32_t i;
  108201. float f;
  108202. } ix;
  108203. ix.f = x;
  108204. ix.i = (ix.i & 0x80000000U) | (0x3f800000U);
  108205. return ix.f;
  108206. }
  108207. /* Segher was off (too high) by ~ .3 decibel. Center the conversion correctly. */
  108208. static float todB(const float *x){
  108209. union {
  108210. ogg_uint32_t i;
  108211. float f;
  108212. } ix;
  108213. ix.f = *x;
  108214. ix.i = ix.i&0x7fffffff;
  108215. return (float)(ix.i * 7.17711438e-7f -764.6161886f);
  108216. }
  108217. #define todB_nn(x) todB(x)
  108218. #else
  108219. static float unitnorm(float x){
  108220. if(x<0)return(-1.f);
  108221. return(1.f);
  108222. }
  108223. #define todB(x) (*(x)==0?-400.f:log(*(x)**(x))*4.34294480f)
  108224. #define todB_nn(x) (*(x)==0.f?-400.f:log(*(x))*8.6858896f)
  108225. #endif
  108226. #define fromdB(x) (exp((x)*.11512925f))
  108227. /* The bark scale equations are approximations, since the original
  108228. table was somewhat hand rolled. The below are chosen to have the
  108229. best possible fit to the rolled tables, thus their somewhat odd
  108230. appearance (these are more accurate and over a longer range than
  108231. the oft-quoted bark equations found in the texts I have). The
  108232. approximations are valid from 0 - 30kHz (nyquist) or so.
  108233. all f in Hz, z in Bark */
  108234. #define toBARK(n) (13.1f*atan(.00074f*(n))+2.24f*atan((n)*(n)*1.85e-8f)+1e-4f*(n))
  108235. #define fromBARK(z) (102.f*(z)-2.f*pow(z,2.f)+.4f*pow(z,3.f)+pow(1.46f,z)-1.f)
  108236. #define toMEL(n) (log(1.f+(n)*.001f)*1442.695f)
  108237. #define fromMEL(m) (1000.f*exp((m)/1442.695f)-1000.f)
  108238. /* Frequency to octave. We arbitrarily declare 63.5 Hz to be octave
  108239. 0.0 */
  108240. #define toOC(n) (log(n)*1.442695f-5.965784f)
  108241. #define fromOC(o) (exp(((o)+5.965784f)*.693147f))
  108242. #endif
  108243. /********* End of inlined file: scales.h *********/
  108244. int analysis_noisy=1;
  108245. /* decides between modes, dispatches to the appropriate mapping. */
  108246. int vorbis_analysis(vorbis_block *vb, ogg_packet *op){
  108247. int ret,i;
  108248. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  108249. vb->glue_bits=0;
  108250. vb->time_bits=0;
  108251. vb->floor_bits=0;
  108252. vb->res_bits=0;
  108253. /* first things first. Make sure encode is ready */
  108254. for(i=0;i<PACKETBLOBS;i++)
  108255. oggpack_reset(vbi->packetblob[i]);
  108256. /* we only have one mapping type (0), and we let the mapping code
  108257. itself figure out what soft mode to use. This allows easier
  108258. bitrate management */
  108259. if((ret=_mapping_P[0]->forward(vb)))
  108260. return(ret);
  108261. if(op){
  108262. if(vorbis_bitrate_managed(vb))
  108263. /* The app is using a bitmanaged mode... but not using the
  108264. bitrate management interface. */
  108265. return(OV_EINVAL);
  108266. op->packet=oggpack_get_buffer(&vb->opb);
  108267. op->bytes=oggpack_bytes(&vb->opb);
  108268. op->b_o_s=0;
  108269. op->e_o_s=vb->eofflag;
  108270. op->granulepos=vb->granulepos;
  108271. op->packetno=vb->sequence; /* for sake of completeness */
  108272. }
  108273. return(0);
  108274. }
  108275. /* there was no great place to put this.... */
  108276. void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,ogg_int64_t off){
  108277. int j;
  108278. FILE *of;
  108279. char buffer[80];
  108280. /* if(i==5870){*/
  108281. sprintf(buffer,"%s_%d.m",base,i);
  108282. of=fopen(buffer,"w");
  108283. if(!of)perror("failed to open data dump file");
  108284. for(j=0;j<n;j++){
  108285. if(bark){
  108286. float b=toBARK((4000.f*j/n)+.25);
  108287. fprintf(of,"%f ",b);
  108288. }else
  108289. if(off!=0)
  108290. fprintf(of,"%f ",(double)(j+off)/8000.);
  108291. else
  108292. fprintf(of,"%f ",(double)j);
  108293. if(dB){
  108294. float val;
  108295. if(v[j]==0.)
  108296. val=-140.;
  108297. else
  108298. val=todB(v+j);
  108299. fprintf(of,"%f\n",val);
  108300. }else{
  108301. fprintf(of,"%f\n",v[j]);
  108302. }
  108303. }
  108304. fclose(of);
  108305. /* } */
  108306. }
  108307. void _analysis_output(char *base,int i,float *v,int n,int bark,int dB,
  108308. ogg_int64_t off){
  108309. if(analysis_noisy)_analysis_output_always(base,i,v,n,bark,dB,off);
  108310. }
  108311. #endif
  108312. /********* End of inlined file: analysis.c *********/
  108313. /********* Start of inlined file: bitrate.c *********/
  108314. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108315. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108316. // tasks..
  108317. /********* Start of inlined file: juce_Config.h *********/
  108318. #ifndef __JUCE_CONFIG_JUCEHEADER__
  108319. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  108320. /*
  108321. This file contains macros that enable/disable various JUCE features.
  108322. */
  108323. /** The name of the namespace that all Juce classes and functions will be
  108324. put inside. If this is not defined, no namespace will be used.
  108325. */
  108326. #ifndef JUCE_NAMESPACE
  108327. #define JUCE_NAMESPACE juce
  108328. #endif
  108329. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  108330. but if you define this value, you can override this can force it to be true or
  108331. false.
  108332. */
  108333. #ifndef JUCE_FORCE_DEBUG
  108334. //#define JUCE_FORCE_DEBUG 1
  108335. #endif
  108336. /** If this flag is enabled, the the jassert and jassertfalse macros will
  108337. always use Logger::writeToLog() to write a message when an assertion happens.
  108338. Enabling it will also leave this turned on in release builds. When it's disabled,
  108339. however, the jassert and jassertfalse macros will not be compiled in a
  108340. release build.
  108341. @see jassert, jassertfalse, Logger
  108342. */
  108343. #ifndef JUCE_LOG_ASSERTIONS
  108344. // #define JUCE_LOG_ASSERTIONS 1
  108345. #endif
  108346. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  108347. which the ASIOAudioIODevice class can't be built. See the comments in the
  108348. ASIOAudioIODevice class's header file for more info about this.
  108349. (This only affects a Win32 build)
  108350. */
  108351. #ifndef JUCE_ASIO
  108352. #define JUCE_ASIO 1
  108353. #endif
  108354. /** Comment out this macro to disable building of ALSA device support on Linux.
  108355. */
  108356. #ifndef JUCE_ALSA
  108357. #define JUCE_ALSA 1
  108358. #endif
  108359. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  108360. have the SDK installed.
  108361. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  108362. classes will be unavailable.
  108363. On Windows, if you enable this, you'll need to have the QuickTime SDK
  108364. installed, and its header files will need to be on your include path.
  108365. */
  108366. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  108367. #define JUCE_QUICKTIME 1
  108368. #endif
  108369. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  108370. have the appropriate headers and libraries available. If it's not enabled, the
  108371. OpenGLComponent class will be unavailable.
  108372. */
  108373. #ifndef JUCE_OPENGL
  108374. #define JUCE_OPENGL 1
  108375. #endif
  108376. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  108377. If you're not going to need either of these formats, turn off the flags to
  108378. avoid bloating your codebase with them.
  108379. */
  108380. #ifndef JUCE_USE_FLAC
  108381. #define JUCE_USE_FLAC 1
  108382. #endif
  108383. #ifndef JUCE_USE_OGGVORBIS
  108384. #define JUCE_USE_OGGVORBIS 1
  108385. #endif
  108386. /** This flag lets you enable support for CD-burning. You might want to disable
  108387. it to build without the MS SDK under windows.
  108388. */
  108389. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  108390. #define JUCE_USE_CDBURNER 1
  108391. #endif
  108392. /** Enabling this macro means that all regions that get repainted will have a coloured
  108393. line drawn around them.
  108394. This is handy if you're trying to optimise drawing, because it lets you easily see
  108395. when anything is being repainted unnecessarily.
  108396. */
  108397. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  108398. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  108399. #endif
  108400. /** Enable this under Linux to use Xinerama for multi-monitor support.
  108401. */
  108402. #ifndef JUCE_USE_XINERAMA
  108403. #define JUCE_USE_XINERAMA 1
  108404. #endif
  108405. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  108406. */
  108407. #ifndef JUCE_USE_XSHM
  108408. #define JUCE_USE_XSHM 1
  108409. #endif
  108410. /** Enabling this builds support for VST audio plugins.
  108411. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  108412. */
  108413. #ifndef JUCE_PLUGINHOST_VST
  108414. // #define JUCE_PLUGINHOST_VST 1
  108415. #endif
  108416. /** Enabling this builds support for AudioUnit audio plugins.
  108417. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  108418. */
  108419. #ifndef JUCE_PLUGINHOST_AU
  108420. // #define JUCE_PLUGINHOST_AU 1
  108421. #endif
  108422. /** Disabling this will avoid linking to any UI code. This is handy for
  108423. writing command-line utilities, e.g. on linux boxes which don't have some
  108424. of the UI libraries installed.
  108425. (On mac and windows, this won't generally make much difference to the build).
  108426. */
  108427. #ifndef JUCE_BUILD_GUI_CLASSES
  108428. #define JUCE_BUILD_GUI_CLASSES 1
  108429. #endif
  108430. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  108431. */
  108432. #ifndef JUCE_WEB_BROWSER
  108433. #define JUCE_WEB_BROWSER 1
  108434. #endif
  108435. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  108436. codebase - you might need to use this if you're linking to some of these libraries
  108437. yourself.
  108438. */
  108439. #ifndef JUCE_INCLUDE_ZLIB_CODE
  108440. #define JUCE_INCLUDE_ZLIB_CODE 1
  108441. #endif
  108442. #ifndef JUCE_INCLUDE_FLAC_CODE
  108443. #define JUCE_INCLUDE_FLAC_CODE 1
  108444. #endif
  108445. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  108446. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  108447. #endif
  108448. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  108449. #define JUCE_INCLUDE_PNGLIB_CODE 1
  108450. #endif
  108451. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  108452. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  108453. #endif
  108454. /** Enable this to add extra memory-leak info to the new and delete operators.
  108455. (Currently, this only affects Windows builds in debug mode).
  108456. */
  108457. #ifndef JUCE_CHECK_MEMORY_LEAKS
  108458. #define JUCE_CHECK_MEMORY_LEAKS 1
  108459. #endif
  108460. /** Enable this to turn on juce's internal catching of exceptions.
  108461. Turning it off will avoid any exception catching. With it on, all exceptions
  108462. are passed to the JUCEApplication::unhandledException() callback for logging.
  108463. */
  108464. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  108465. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  108466. #endif
  108467. /** If this macro is set, the Juce String class will use unicode as its
  108468. internal representation. If it isn't set, it'll use ANSI.
  108469. */
  108470. #ifndef JUCE_STRINGS_ARE_UNICODE
  108471. #define JUCE_STRINGS_ARE_UNICODE 1
  108472. #endif
  108473. #endif
  108474. /********* End of inlined file: juce_Config.h *********/
  108475. #ifdef _MSC_VER
  108476. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108477. #endif
  108478. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108479. #if JUCE_USE_OGGVORBIS
  108480. #include <stdlib.h>
  108481. #include <string.h>
  108482. #include <math.h>
  108483. /* compute bitrate tracking setup */
  108484. void vorbis_bitrate_init(vorbis_info *vi,bitrate_manager_state *bm){
  108485. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  108486. bitrate_manager_info *bi=&ci->bi;
  108487. memset(bm,0,sizeof(*bm));
  108488. if(bi && (bi->reservoir_bits>0)){
  108489. long ratesamples=vi->rate;
  108490. int halfsamples=ci->blocksizes[0]>>1;
  108491. bm->short_per_long=ci->blocksizes[1]/ci->blocksizes[0];
  108492. bm->managed=1;
  108493. bm->avg_bitsper= rint(1.*bi->avg_rate*halfsamples/ratesamples);
  108494. bm->min_bitsper= rint(1.*bi->min_rate*halfsamples/ratesamples);
  108495. bm->max_bitsper= rint(1.*bi->max_rate*halfsamples/ratesamples);
  108496. bm->avgfloat=PACKETBLOBS/2;
  108497. /* not a necessary fix, but one that leads to a more balanced
  108498. typical initialization */
  108499. {
  108500. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  108501. bm->minmax_reservoir=desired_fill;
  108502. bm->avg_reservoir=desired_fill;
  108503. }
  108504. }
  108505. }
  108506. void vorbis_bitrate_clear(bitrate_manager_state *bm){
  108507. memset(bm,0,sizeof(*bm));
  108508. return;
  108509. }
  108510. int vorbis_bitrate_managed(vorbis_block *vb){
  108511. vorbis_dsp_state *vd=vb->vd;
  108512. private_state *b=(private_state*)vd->backend_state;
  108513. bitrate_manager_state *bm=&b->bms;
  108514. if(bm && bm->managed)return(1);
  108515. return(0);
  108516. }
  108517. /* finish taking in the block we just processed */
  108518. int vorbis_bitrate_addblock(vorbis_block *vb){
  108519. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  108520. vorbis_dsp_state *vd=vb->vd;
  108521. private_state *b=(private_state*)vd->backend_state;
  108522. bitrate_manager_state *bm=&b->bms;
  108523. vorbis_info *vi=vd->vi;
  108524. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108525. bitrate_manager_info *bi=&ci->bi;
  108526. int choice=rint(bm->avgfloat);
  108527. long this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108528. long min_target_bits=(vb->W?bm->min_bitsper*bm->short_per_long:bm->min_bitsper);
  108529. long max_target_bits=(vb->W?bm->max_bitsper*bm->short_per_long:bm->max_bitsper);
  108530. int samples=ci->blocksizes[vb->W]>>1;
  108531. long desired_fill=bi->reservoir_bits*bi->reservoir_bias;
  108532. if(!bm->managed){
  108533. /* not a bitrate managed stream, but for API simplicity, we'll
  108534. buffer the packet to keep the code path clean */
  108535. if(bm->vb)return(-1); /* one has been submitted without
  108536. being claimed */
  108537. bm->vb=vb;
  108538. return(0);
  108539. }
  108540. bm->vb=vb;
  108541. /* look ahead for avg floater */
  108542. if(bm->avg_bitsper>0){
  108543. double slew=0.;
  108544. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  108545. double slewlimit= 15./bi->slew_damp;
  108546. /* choosing a new floater:
  108547. if we're over target, we slew down
  108548. if we're under target, we slew up
  108549. choose slew as follows: look through packetblobs of this frame
  108550. and set slew as the first in the appropriate direction that
  108551. gives us the slew we want. This may mean no slew if delta is
  108552. already favorable.
  108553. Then limit slew to slew max */
  108554. if(bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  108555. while(choice>0 && this_bits>avg_target_bits &&
  108556. bm->avg_reservoir+(this_bits-avg_target_bits)>desired_fill){
  108557. choice--;
  108558. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108559. }
  108560. }else if(bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  108561. while(choice+1<PACKETBLOBS && this_bits<avg_target_bits &&
  108562. bm->avg_reservoir+(this_bits-avg_target_bits)<desired_fill){
  108563. choice++;
  108564. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108565. }
  108566. }
  108567. slew=rint(choice-bm->avgfloat)/samples*vi->rate;
  108568. if(slew<-slewlimit)slew=-slewlimit;
  108569. if(slew>slewlimit)slew=slewlimit;
  108570. choice=rint(bm->avgfloat+= slew/vi->rate*samples);
  108571. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108572. }
  108573. /* enforce min(if used) on the current floater (if used) */
  108574. if(bm->min_bitsper>0){
  108575. /* do we need to force the bitrate up? */
  108576. if(this_bits<min_target_bits){
  108577. while(bm->minmax_reservoir-(min_target_bits-this_bits)<0){
  108578. choice++;
  108579. if(choice>=PACKETBLOBS)break;
  108580. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108581. }
  108582. }
  108583. }
  108584. /* enforce max (if used) on the current floater (if used) */
  108585. if(bm->max_bitsper>0){
  108586. /* do we need to force the bitrate down? */
  108587. if(this_bits>max_target_bits){
  108588. while(bm->minmax_reservoir+(this_bits-max_target_bits)>bi->reservoir_bits){
  108589. choice--;
  108590. if(choice<0)break;
  108591. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108592. }
  108593. }
  108594. }
  108595. /* Choice of packetblobs now made based on floater, and min/max
  108596. requirements. Now boundary check extreme choices */
  108597. if(choice<0){
  108598. /* choosing a smaller packetblob is insufficient to trim bitrate.
  108599. frame will need to be truncated */
  108600. long maxsize=(max_target_bits+(bi->reservoir_bits-bm->minmax_reservoir))/8;
  108601. bm->choice=choice=0;
  108602. if(oggpack_bytes(vbi->packetblob[choice])>maxsize){
  108603. oggpack_writetrunc(vbi->packetblob[choice],maxsize*8);
  108604. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108605. }
  108606. }else{
  108607. long minsize=(min_target_bits-bm->minmax_reservoir+7)/8;
  108608. if(choice>=PACKETBLOBS)
  108609. choice=PACKETBLOBS-1;
  108610. bm->choice=choice;
  108611. /* prop up bitrate according to demand. pad this frame out with zeroes */
  108612. minsize-=oggpack_bytes(vbi->packetblob[choice]);
  108613. while(minsize-->0)oggpack_write(vbi->packetblob[choice],0,8);
  108614. this_bits=oggpack_bytes(vbi->packetblob[choice])*8;
  108615. }
  108616. /* now we have the final packet and the final packet size. Update statistics */
  108617. /* min and max reservoir */
  108618. if(bm->min_bitsper>0 || bm->max_bitsper>0){
  108619. if(max_target_bits>0 && this_bits>max_target_bits){
  108620. bm->minmax_reservoir+=(this_bits-max_target_bits);
  108621. }else if(min_target_bits>0 && this_bits<min_target_bits){
  108622. bm->minmax_reservoir+=(this_bits-min_target_bits);
  108623. }else{
  108624. /* inbetween; we want to take reservoir toward but not past desired_fill */
  108625. if(bm->minmax_reservoir>desired_fill){
  108626. if(max_target_bits>0){ /* logical bulletproofing against initialization state */
  108627. bm->minmax_reservoir+=(this_bits-max_target_bits);
  108628. if(bm->minmax_reservoir<desired_fill)bm->minmax_reservoir=desired_fill;
  108629. }else{
  108630. bm->minmax_reservoir=desired_fill;
  108631. }
  108632. }else{
  108633. if(min_target_bits>0){ /* logical bulletproofing against initialization state */
  108634. bm->minmax_reservoir+=(this_bits-min_target_bits);
  108635. if(bm->minmax_reservoir>desired_fill)bm->minmax_reservoir=desired_fill;
  108636. }else{
  108637. bm->minmax_reservoir=desired_fill;
  108638. }
  108639. }
  108640. }
  108641. }
  108642. /* avg reservoir */
  108643. if(bm->avg_bitsper>0){
  108644. long avg_target_bits=(vb->W?bm->avg_bitsper*bm->short_per_long:bm->avg_bitsper);
  108645. bm->avg_reservoir+=this_bits-avg_target_bits;
  108646. }
  108647. return(0);
  108648. }
  108649. int vorbis_bitrate_flushpacket(vorbis_dsp_state *vd,ogg_packet *op){
  108650. private_state *b=(private_state*)vd->backend_state;
  108651. bitrate_manager_state *bm=&b->bms;
  108652. vorbis_block *vb=bm->vb;
  108653. int choice=PACKETBLOBS/2;
  108654. if(!vb)return 0;
  108655. if(op){
  108656. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  108657. if(vorbis_bitrate_managed(vb))
  108658. choice=bm->choice;
  108659. op->packet=oggpack_get_buffer(vbi->packetblob[choice]);
  108660. op->bytes=oggpack_bytes(vbi->packetblob[choice]);
  108661. op->b_o_s=0;
  108662. op->e_o_s=vb->eofflag;
  108663. op->granulepos=vb->granulepos;
  108664. op->packetno=vb->sequence; /* for sake of completeness */
  108665. }
  108666. bm->vb=0;
  108667. return(1);
  108668. }
  108669. #endif
  108670. /********* End of inlined file: bitrate.c *********/
  108671. /********* Start of inlined file: block.c *********/
  108672. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  108673. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  108674. // tasks..
  108675. /********* Start of inlined file: juce_Config.h *********/
  108676. #ifndef __JUCE_CONFIG_JUCEHEADER__
  108677. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  108678. /*
  108679. This file contains macros that enable/disable various JUCE features.
  108680. */
  108681. /** The name of the namespace that all Juce classes and functions will be
  108682. put inside. If this is not defined, no namespace will be used.
  108683. */
  108684. #ifndef JUCE_NAMESPACE
  108685. #define JUCE_NAMESPACE juce
  108686. #endif
  108687. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  108688. but if you define this value, you can override this can force it to be true or
  108689. false.
  108690. */
  108691. #ifndef JUCE_FORCE_DEBUG
  108692. //#define JUCE_FORCE_DEBUG 1
  108693. #endif
  108694. /** If this flag is enabled, the the jassert and jassertfalse macros will
  108695. always use Logger::writeToLog() to write a message when an assertion happens.
  108696. Enabling it will also leave this turned on in release builds. When it's disabled,
  108697. however, the jassert and jassertfalse macros will not be compiled in a
  108698. release build.
  108699. @see jassert, jassertfalse, Logger
  108700. */
  108701. #ifndef JUCE_LOG_ASSERTIONS
  108702. // #define JUCE_LOG_ASSERTIONS 1
  108703. #endif
  108704. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  108705. which the ASIOAudioIODevice class can't be built. See the comments in the
  108706. ASIOAudioIODevice class's header file for more info about this.
  108707. (This only affects a Win32 build)
  108708. */
  108709. #ifndef JUCE_ASIO
  108710. #define JUCE_ASIO 1
  108711. #endif
  108712. /** Comment out this macro to disable building of ALSA device support on Linux.
  108713. */
  108714. #ifndef JUCE_ALSA
  108715. #define JUCE_ALSA 1
  108716. #endif
  108717. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  108718. have the SDK installed.
  108719. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  108720. classes will be unavailable.
  108721. On Windows, if you enable this, you'll need to have the QuickTime SDK
  108722. installed, and its header files will need to be on your include path.
  108723. */
  108724. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  108725. #define JUCE_QUICKTIME 1
  108726. #endif
  108727. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  108728. have the appropriate headers and libraries available. If it's not enabled, the
  108729. OpenGLComponent class will be unavailable.
  108730. */
  108731. #ifndef JUCE_OPENGL
  108732. #define JUCE_OPENGL 1
  108733. #endif
  108734. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  108735. If you're not going to need either of these formats, turn off the flags to
  108736. avoid bloating your codebase with them.
  108737. */
  108738. #ifndef JUCE_USE_FLAC
  108739. #define JUCE_USE_FLAC 1
  108740. #endif
  108741. #ifndef JUCE_USE_OGGVORBIS
  108742. #define JUCE_USE_OGGVORBIS 1
  108743. #endif
  108744. /** This flag lets you enable support for CD-burning. You might want to disable
  108745. it to build without the MS SDK under windows.
  108746. */
  108747. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  108748. #define JUCE_USE_CDBURNER 1
  108749. #endif
  108750. /** Enabling this macro means that all regions that get repainted will have a coloured
  108751. line drawn around them.
  108752. This is handy if you're trying to optimise drawing, because it lets you easily see
  108753. when anything is being repainted unnecessarily.
  108754. */
  108755. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  108756. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  108757. #endif
  108758. /** Enable this under Linux to use Xinerama for multi-monitor support.
  108759. */
  108760. #ifndef JUCE_USE_XINERAMA
  108761. #define JUCE_USE_XINERAMA 1
  108762. #endif
  108763. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  108764. */
  108765. #ifndef JUCE_USE_XSHM
  108766. #define JUCE_USE_XSHM 1
  108767. #endif
  108768. /** Enabling this builds support for VST audio plugins.
  108769. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  108770. */
  108771. #ifndef JUCE_PLUGINHOST_VST
  108772. // #define JUCE_PLUGINHOST_VST 1
  108773. #endif
  108774. /** Enabling this builds support for AudioUnit audio plugins.
  108775. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  108776. */
  108777. #ifndef JUCE_PLUGINHOST_AU
  108778. // #define JUCE_PLUGINHOST_AU 1
  108779. #endif
  108780. /** Disabling this will avoid linking to any UI code. This is handy for
  108781. writing command-line utilities, e.g. on linux boxes which don't have some
  108782. of the UI libraries installed.
  108783. (On mac and windows, this won't generally make much difference to the build).
  108784. */
  108785. #ifndef JUCE_BUILD_GUI_CLASSES
  108786. #define JUCE_BUILD_GUI_CLASSES 1
  108787. #endif
  108788. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  108789. */
  108790. #ifndef JUCE_WEB_BROWSER
  108791. #define JUCE_WEB_BROWSER 1
  108792. #endif
  108793. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  108794. codebase - you might need to use this if you're linking to some of these libraries
  108795. yourself.
  108796. */
  108797. #ifndef JUCE_INCLUDE_ZLIB_CODE
  108798. #define JUCE_INCLUDE_ZLIB_CODE 1
  108799. #endif
  108800. #ifndef JUCE_INCLUDE_FLAC_CODE
  108801. #define JUCE_INCLUDE_FLAC_CODE 1
  108802. #endif
  108803. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  108804. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  108805. #endif
  108806. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  108807. #define JUCE_INCLUDE_PNGLIB_CODE 1
  108808. #endif
  108809. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  108810. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  108811. #endif
  108812. /** Enable this to add extra memory-leak info to the new and delete operators.
  108813. (Currently, this only affects Windows builds in debug mode).
  108814. */
  108815. #ifndef JUCE_CHECK_MEMORY_LEAKS
  108816. #define JUCE_CHECK_MEMORY_LEAKS 1
  108817. #endif
  108818. /** Enable this to turn on juce's internal catching of exceptions.
  108819. Turning it off will avoid any exception catching. With it on, all exceptions
  108820. are passed to the JUCEApplication::unhandledException() callback for logging.
  108821. */
  108822. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  108823. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  108824. #endif
  108825. /** If this macro is set, the Juce String class will use unicode as its
  108826. internal representation. If it isn't set, it'll use ANSI.
  108827. */
  108828. #ifndef JUCE_STRINGS_ARE_UNICODE
  108829. #define JUCE_STRINGS_ARE_UNICODE 1
  108830. #endif
  108831. #endif
  108832. /********* End of inlined file: juce_Config.h *********/
  108833. #ifdef _MSC_VER
  108834. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  108835. #endif
  108836. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  108837. #if JUCE_USE_OGGVORBIS
  108838. #include <stdio.h>
  108839. #include <stdlib.h>
  108840. #include <string.h>
  108841. /********* Start of inlined file: window.h *********/
  108842. #ifndef _V_WINDOW_
  108843. #define _V_WINDOW_
  108844. extern float *_vorbis_window_get(int n);
  108845. extern void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  108846. int lW,int W,int nW);
  108847. #endif
  108848. /********* End of inlined file: window.h *********/
  108849. /********* Start of inlined file: lpc.h *********/
  108850. #ifndef _V_LPC_H_
  108851. #define _V_LPC_H_
  108852. /* simple linear scale LPC code */
  108853. extern float vorbis_lpc_from_data(float *data,float *lpc,int n,int m);
  108854. extern void vorbis_lpc_predict(float *coeff,float *prime,int m,
  108855. float *data,long n);
  108856. #endif
  108857. /********* End of inlined file: lpc.h *********/
  108858. /* pcm accumulator examples (not exhaustive):
  108859. <-------------- lW ---------------->
  108860. <--------------- W ---------------->
  108861. : .....|..... _______________ |
  108862. : .''' | '''_--- | |\ |
  108863. :.....''' |_____--- '''......| | \_______|
  108864. :.................|__________________|_______|__|______|
  108865. |<------ Sl ------>| > Sr < |endW
  108866. |beginSl |endSl | |endSr
  108867. |beginW |endlW |beginSr
  108868. |< lW >|
  108869. <--------------- W ---------------->
  108870. | | .. ______________ |
  108871. | | ' `/ | ---_ |
  108872. |___.'___/`. | ---_____|
  108873. |_______|__|_______|_________________|
  108874. | >|Sl|< |<------ Sr ----->|endW
  108875. | | |endSl |beginSr |endSr
  108876. |beginW | |endlW
  108877. mult[0] |beginSl mult[n]
  108878. <-------------- lW ----------------->
  108879. |<--W-->|
  108880. : .............. ___ | |
  108881. : .''' |`/ \ | |
  108882. :.....''' |/`....\|...|
  108883. :.........................|___|___|___|
  108884. |Sl |Sr |endW
  108885. | | |endSr
  108886. | |beginSr
  108887. | |endSl
  108888. |beginSl
  108889. |beginW
  108890. */
  108891. /* block abstraction setup *********************************************/
  108892. #ifndef WORD_ALIGN
  108893. #define WORD_ALIGN 8
  108894. #endif
  108895. int vorbis_block_init(vorbis_dsp_state *v, vorbis_block *vb){
  108896. int i;
  108897. memset(vb,0,sizeof(*vb));
  108898. vb->vd=v;
  108899. vb->localalloc=0;
  108900. vb->localstore=NULL;
  108901. if(v->analysisp){
  108902. vorbis_block_internal *vbi=(vorbis_block_internal*)
  108903. (vb->internal=(vorbis_block_internal*)_ogg_calloc(1,sizeof(vorbis_block_internal)));
  108904. vbi->ampmax=-9999;
  108905. for(i=0;i<PACKETBLOBS;i++){
  108906. if(i==PACKETBLOBS/2){
  108907. vbi->packetblob[i]=&vb->opb;
  108908. }else{
  108909. vbi->packetblob[i]=
  108910. (oggpack_buffer*) _ogg_calloc(1,sizeof(oggpack_buffer));
  108911. }
  108912. oggpack_writeinit(vbi->packetblob[i]);
  108913. }
  108914. }
  108915. return(0);
  108916. }
  108917. void *_vorbis_block_alloc(vorbis_block *vb,long bytes){
  108918. bytes=(bytes+(WORD_ALIGN-1)) & ~(WORD_ALIGN-1);
  108919. if(bytes+vb->localtop>vb->localalloc){
  108920. /* can't just _ogg_realloc... there are outstanding pointers */
  108921. if(vb->localstore){
  108922. struct alloc_chain *link=(struct alloc_chain*)_ogg_malloc(sizeof(*link));
  108923. vb->totaluse+=vb->localtop;
  108924. link->next=vb->reap;
  108925. link->ptr=vb->localstore;
  108926. vb->reap=link;
  108927. }
  108928. /* highly conservative */
  108929. vb->localalloc=bytes;
  108930. vb->localstore=_ogg_malloc(vb->localalloc);
  108931. vb->localtop=0;
  108932. }
  108933. {
  108934. void *ret=(void *)(((char *)vb->localstore)+vb->localtop);
  108935. vb->localtop+=bytes;
  108936. return ret;
  108937. }
  108938. }
  108939. /* reap the chain, pull the ripcord */
  108940. void _vorbis_block_ripcord(vorbis_block *vb){
  108941. /* reap the chain */
  108942. struct alloc_chain *reap=vb->reap;
  108943. while(reap){
  108944. struct alloc_chain *next=reap->next;
  108945. _ogg_free(reap->ptr);
  108946. memset(reap,0,sizeof(*reap));
  108947. _ogg_free(reap);
  108948. reap=next;
  108949. }
  108950. /* consolidate storage */
  108951. if(vb->totaluse){
  108952. vb->localstore=_ogg_realloc(vb->localstore,vb->totaluse+vb->localalloc);
  108953. vb->localalloc+=vb->totaluse;
  108954. vb->totaluse=0;
  108955. }
  108956. /* pull the ripcord */
  108957. vb->localtop=0;
  108958. vb->reap=NULL;
  108959. }
  108960. int vorbis_block_clear(vorbis_block *vb){
  108961. int i;
  108962. vorbis_block_internal *vbi=(vorbis_block_internal*)vb->internal;
  108963. _vorbis_block_ripcord(vb);
  108964. if(vb->localstore)_ogg_free(vb->localstore);
  108965. if(vbi){
  108966. for(i=0;i<PACKETBLOBS;i++){
  108967. oggpack_writeclear(vbi->packetblob[i]);
  108968. if(i!=PACKETBLOBS/2)_ogg_free(vbi->packetblob[i]);
  108969. }
  108970. _ogg_free(vbi);
  108971. }
  108972. memset(vb,0,sizeof(*vb));
  108973. return(0);
  108974. }
  108975. /* Analysis side code, but directly related to blocking. Thus it's
  108976. here and not in analysis.c (which is for analysis transforms only).
  108977. The init is here because some of it is shared */
  108978. static int _vds_shared_init(vorbis_dsp_state *v,vorbis_info *vi,int encp){
  108979. int i;
  108980. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  108981. private_state *b=NULL;
  108982. int hs;
  108983. if(ci==NULL) return 1;
  108984. hs=ci->halfrate_flag;
  108985. memset(v,0,sizeof(*v));
  108986. b=(private_state*) (v->backend_state=(private_state*)_ogg_calloc(1,sizeof(*b)));
  108987. v->vi=vi;
  108988. b->modebits=ilog2(ci->modes);
  108989. b->transform[0]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[0]));
  108990. b->transform[1]=(vorbis_look_transform**)_ogg_calloc(VI_TRANSFORMB,sizeof(*b->transform[1]));
  108991. /* MDCT is tranform 0 */
  108992. b->transform[0][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  108993. b->transform[1][0]=_ogg_calloc(1,sizeof(mdct_lookup));
  108994. mdct_init((mdct_lookup*)b->transform[0][0],ci->blocksizes[0]>>hs);
  108995. mdct_init((mdct_lookup*)b->transform[1][0],ci->blocksizes[1]>>hs);
  108996. /* Vorbis I uses only window type 0 */
  108997. b->window[0]=ilog2(ci->blocksizes[0])-6;
  108998. b->window[1]=ilog2(ci->blocksizes[1])-6;
  108999. if(encp){ /* encode/decode differ here */
  109000. /* analysis always needs an fft */
  109001. drft_init(&b->fft_look[0],ci->blocksizes[0]);
  109002. drft_init(&b->fft_look[1],ci->blocksizes[1]);
  109003. /* finish the codebooks */
  109004. if(!ci->fullbooks){
  109005. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  109006. for(i=0;i<ci->books;i++)
  109007. vorbis_book_init_encode(ci->fullbooks+i,ci->book_param[i]);
  109008. }
  109009. b->psy=(vorbis_look_psy*)_ogg_calloc(ci->psys,sizeof(*b->psy));
  109010. for(i=0;i<ci->psys;i++){
  109011. _vp_psy_init(b->psy+i,
  109012. ci->psy_param[i],
  109013. &ci->psy_g_param,
  109014. ci->blocksizes[ci->psy_param[i]->blockflag]/2,
  109015. vi->rate);
  109016. }
  109017. v->analysisp=1;
  109018. }else{
  109019. /* finish the codebooks */
  109020. if(!ci->fullbooks){
  109021. ci->fullbooks=(codebook*) _ogg_calloc(ci->books,sizeof(*ci->fullbooks));
  109022. for(i=0;i<ci->books;i++){
  109023. vorbis_book_init_decode(ci->fullbooks+i,ci->book_param[i]);
  109024. /* decode codebooks are now standalone after init */
  109025. vorbis_staticbook_destroy(ci->book_param[i]);
  109026. ci->book_param[i]=NULL;
  109027. }
  109028. }
  109029. }
  109030. /* initialize the storage vectors. blocksize[1] is small for encode,
  109031. but the correct size for decode */
  109032. v->pcm_storage=ci->blocksizes[1];
  109033. v->pcm=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcm));
  109034. v->pcmret=(float**)_ogg_malloc(vi->channels*sizeof(*v->pcmret));
  109035. {
  109036. int i;
  109037. for(i=0;i<vi->channels;i++)
  109038. v->pcm[i]=(float*)_ogg_calloc(v->pcm_storage,sizeof(*v->pcm[i]));
  109039. }
  109040. /* all 1 (large block) or 0 (small block) */
  109041. /* explicitly set for the sake of clarity */
  109042. v->lW=0; /* previous window size */
  109043. v->W=0; /* current window size */
  109044. /* all vector indexes */
  109045. v->centerW=ci->blocksizes[1]/2;
  109046. v->pcm_current=v->centerW;
  109047. /* initialize all the backend lookups */
  109048. b->flr=(vorbis_look_floor**)_ogg_calloc(ci->floors,sizeof(*b->flr));
  109049. b->residue=(vorbis_look_residue**)_ogg_calloc(ci->residues,sizeof(*b->residue));
  109050. for(i=0;i<ci->floors;i++)
  109051. b->flr[i]=_floor_P[ci->floor_type[i]]->
  109052. look(v,ci->floor_param[i]);
  109053. for(i=0;i<ci->residues;i++)
  109054. b->residue[i]=_residue_P[ci->residue_type[i]]->
  109055. look(v,ci->residue_param[i]);
  109056. return 0;
  109057. }
  109058. /* arbitrary settings and spec-mandated numbers get filled in here */
  109059. int vorbis_analysis_init(vorbis_dsp_state *v,vorbis_info *vi){
  109060. private_state *b=NULL;
  109061. if(_vds_shared_init(v,vi,1))return 1;
  109062. b=(private_state*)v->backend_state;
  109063. b->psy_g_look=_vp_global_look(vi);
  109064. /* Initialize the envelope state storage */
  109065. b->ve=(envelope_lookup*)_ogg_calloc(1,sizeof(*b->ve));
  109066. _ve_envelope_init(b->ve,vi);
  109067. vorbis_bitrate_init(vi,&b->bms);
  109068. /* compressed audio packets start after the headers
  109069. with sequence number 3 */
  109070. v->sequence=3;
  109071. return(0);
  109072. }
  109073. void vorbis_dsp_clear(vorbis_dsp_state *v){
  109074. int i;
  109075. if(v){
  109076. vorbis_info *vi=v->vi;
  109077. codec_setup_info *ci=(codec_setup_info*)(vi?vi->codec_setup:NULL);
  109078. private_state *b=(private_state*)v->backend_state;
  109079. if(b){
  109080. if(b->ve){
  109081. _ve_envelope_clear(b->ve);
  109082. _ogg_free(b->ve);
  109083. }
  109084. if(b->transform[0]){
  109085. mdct_clear((mdct_lookup*) b->transform[0][0]);
  109086. _ogg_free(b->transform[0][0]);
  109087. _ogg_free(b->transform[0]);
  109088. }
  109089. if(b->transform[1]){
  109090. mdct_clear((mdct_lookup*) b->transform[1][0]);
  109091. _ogg_free(b->transform[1][0]);
  109092. _ogg_free(b->transform[1]);
  109093. }
  109094. if(b->flr){
  109095. for(i=0;i<ci->floors;i++)
  109096. _floor_P[ci->floor_type[i]]->
  109097. free_look(b->flr[i]);
  109098. _ogg_free(b->flr);
  109099. }
  109100. if(b->residue){
  109101. for(i=0;i<ci->residues;i++)
  109102. _residue_P[ci->residue_type[i]]->
  109103. free_look(b->residue[i]);
  109104. _ogg_free(b->residue);
  109105. }
  109106. if(b->psy){
  109107. for(i=0;i<ci->psys;i++)
  109108. _vp_psy_clear(b->psy+i);
  109109. _ogg_free(b->psy);
  109110. }
  109111. if(b->psy_g_look)_vp_global_free(b->psy_g_look);
  109112. vorbis_bitrate_clear(&b->bms);
  109113. drft_clear(&b->fft_look[0]);
  109114. drft_clear(&b->fft_look[1]);
  109115. }
  109116. if(v->pcm){
  109117. for(i=0;i<vi->channels;i++)
  109118. if(v->pcm[i])_ogg_free(v->pcm[i]);
  109119. _ogg_free(v->pcm);
  109120. if(v->pcmret)_ogg_free(v->pcmret);
  109121. }
  109122. if(b){
  109123. /* free header, header1, header2 */
  109124. if(b->header)_ogg_free(b->header);
  109125. if(b->header1)_ogg_free(b->header1);
  109126. if(b->header2)_ogg_free(b->header2);
  109127. _ogg_free(b);
  109128. }
  109129. memset(v,0,sizeof(*v));
  109130. }
  109131. }
  109132. float **vorbis_analysis_buffer(vorbis_dsp_state *v, int vals){
  109133. int i;
  109134. vorbis_info *vi=v->vi;
  109135. private_state *b=(private_state*)v->backend_state;
  109136. /* free header, header1, header2 */
  109137. if(b->header)_ogg_free(b->header);b->header=NULL;
  109138. if(b->header1)_ogg_free(b->header1);b->header1=NULL;
  109139. if(b->header2)_ogg_free(b->header2);b->header2=NULL;
  109140. /* Do we have enough storage space for the requested buffer? If not,
  109141. expand the PCM (and envelope) storage */
  109142. if(v->pcm_current+vals>=v->pcm_storage){
  109143. v->pcm_storage=v->pcm_current+vals*2;
  109144. for(i=0;i<vi->channels;i++){
  109145. v->pcm[i]=(float*)_ogg_realloc(v->pcm[i],v->pcm_storage*sizeof(*v->pcm[i]));
  109146. }
  109147. }
  109148. for(i=0;i<vi->channels;i++)
  109149. v->pcmret[i]=v->pcm[i]+v->pcm_current;
  109150. return(v->pcmret);
  109151. }
  109152. static void _preextrapolate_helper(vorbis_dsp_state *v){
  109153. int i;
  109154. int order=32;
  109155. float *lpc=(float*)alloca(order*sizeof(*lpc));
  109156. float *work=(float*)alloca(v->pcm_current*sizeof(*work));
  109157. long j;
  109158. v->preextrapolate=1;
  109159. if(v->pcm_current-v->centerW>order*2){ /* safety */
  109160. for(i=0;i<v->vi->channels;i++){
  109161. /* need to run the extrapolation in reverse! */
  109162. for(j=0;j<v->pcm_current;j++)
  109163. work[j]=v->pcm[i][v->pcm_current-j-1];
  109164. /* prime as above */
  109165. vorbis_lpc_from_data(work,lpc,v->pcm_current-v->centerW,order);
  109166. /* run the predictor filter */
  109167. vorbis_lpc_predict(lpc,work+v->pcm_current-v->centerW-order,
  109168. order,
  109169. work+v->pcm_current-v->centerW,
  109170. v->centerW);
  109171. for(j=0;j<v->pcm_current;j++)
  109172. v->pcm[i][v->pcm_current-j-1]=work[j];
  109173. }
  109174. }
  109175. }
  109176. /* call with val<=0 to set eof */
  109177. int vorbis_analysis_wrote(vorbis_dsp_state *v, int vals){
  109178. vorbis_info *vi=v->vi;
  109179. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109180. if(vals<=0){
  109181. int order=32;
  109182. int i;
  109183. float *lpc=(float*) alloca(order*sizeof(*lpc));
  109184. /* if it wasn't done earlier (very short sample) */
  109185. if(!v->preextrapolate)
  109186. _preextrapolate_helper(v);
  109187. /* We're encoding the end of the stream. Just make sure we have
  109188. [at least] a few full blocks of zeroes at the end. */
  109189. /* actually, we don't want zeroes; that could drop a large
  109190. amplitude off a cliff, creating spread spectrum noise that will
  109191. suck to encode. Extrapolate for the sake of cleanliness. */
  109192. vorbis_analysis_buffer(v,ci->blocksizes[1]*3);
  109193. v->eofflag=v->pcm_current;
  109194. v->pcm_current+=ci->blocksizes[1]*3;
  109195. for(i=0;i<vi->channels;i++){
  109196. if(v->eofflag>order*2){
  109197. /* extrapolate with LPC to fill in */
  109198. long n;
  109199. /* make a predictor filter */
  109200. n=v->eofflag;
  109201. if(n>ci->blocksizes[1])n=ci->blocksizes[1];
  109202. vorbis_lpc_from_data(v->pcm[i]+v->eofflag-n,lpc,n,order);
  109203. /* run the predictor filter */
  109204. vorbis_lpc_predict(lpc,v->pcm[i]+v->eofflag-order,order,
  109205. v->pcm[i]+v->eofflag,v->pcm_current-v->eofflag);
  109206. }else{
  109207. /* not enough data to extrapolate (unlikely to happen due to
  109208. guarding the overlap, but bulletproof in case that
  109209. assumtion goes away). zeroes will do. */
  109210. memset(v->pcm[i]+v->eofflag,0,
  109211. (v->pcm_current-v->eofflag)*sizeof(*v->pcm[i]));
  109212. }
  109213. }
  109214. }else{
  109215. if(v->pcm_current+vals>v->pcm_storage)
  109216. return(OV_EINVAL);
  109217. v->pcm_current+=vals;
  109218. /* we may want to reverse extrapolate the beginning of a stream
  109219. too... in case we're beginning on a cliff! */
  109220. /* clumsy, but simple. It only runs once, so simple is good. */
  109221. if(!v->preextrapolate && v->pcm_current-v->centerW>ci->blocksizes[1])
  109222. _preextrapolate_helper(v);
  109223. }
  109224. return(0);
  109225. }
  109226. /* do the deltas, envelope shaping, pre-echo and determine the size of
  109227. the next block on which to continue analysis */
  109228. int vorbis_analysis_blockout(vorbis_dsp_state *v,vorbis_block *vb){
  109229. int i;
  109230. vorbis_info *vi=v->vi;
  109231. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109232. private_state *b=(private_state*)v->backend_state;
  109233. vorbis_look_psy_global *g=b->psy_g_look;
  109234. long beginW=v->centerW-ci->blocksizes[v->W]/2,centerNext;
  109235. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  109236. /* check to see if we're started... */
  109237. if(!v->preextrapolate)return(0);
  109238. /* check to see if we're done... */
  109239. if(v->eofflag==-1)return(0);
  109240. /* By our invariant, we have lW, W and centerW set. Search for
  109241. the next boundary so we can determine nW (the next window size)
  109242. which lets us compute the shape of the current block's window */
  109243. /* we do an envelope search even on a single blocksize; we may still
  109244. be throwing more bits at impulses, and envelope search handles
  109245. marking impulses too. */
  109246. {
  109247. long bp=_ve_envelope_search(v);
  109248. if(bp==-1){
  109249. if(v->eofflag==0)return(0); /* not enough data currently to search for a
  109250. full long block */
  109251. v->nW=0;
  109252. }else{
  109253. if(ci->blocksizes[0]==ci->blocksizes[1])
  109254. v->nW=0;
  109255. else
  109256. v->nW=bp;
  109257. }
  109258. }
  109259. centerNext=v->centerW+ci->blocksizes[v->W]/4+ci->blocksizes[v->nW]/4;
  109260. {
  109261. /* center of next block + next block maximum right side. */
  109262. long blockbound=centerNext+ci->blocksizes[v->nW]/2;
  109263. if(v->pcm_current<blockbound)return(0); /* not enough data yet;
  109264. although this check is
  109265. less strict that the
  109266. _ve_envelope_search,
  109267. the search is not run
  109268. if we only use one
  109269. block size */
  109270. }
  109271. /* fill in the block. Note that for a short window, lW and nW are *short*
  109272. regardless of actual settings in the stream */
  109273. _vorbis_block_ripcord(vb);
  109274. vb->lW=v->lW;
  109275. vb->W=v->W;
  109276. vb->nW=v->nW;
  109277. if(v->W){
  109278. if(!v->lW || !v->nW){
  109279. vbi->blocktype=BLOCKTYPE_TRANSITION;
  109280. /*fprintf(stderr,"-");*/
  109281. }else{
  109282. vbi->blocktype=BLOCKTYPE_LONG;
  109283. /*fprintf(stderr,"_");*/
  109284. }
  109285. }else{
  109286. if(_ve_envelope_mark(v)){
  109287. vbi->blocktype=BLOCKTYPE_IMPULSE;
  109288. /*fprintf(stderr,"|");*/
  109289. }else{
  109290. vbi->blocktype=BLOCKTYPE_PADDING;
  109291. /*fprintf(stderr,".");*/
  109292. }
  109293. }
  109294. vb->vd=v;
  109295. vb->sequence=v->sequence++;
  109296. vb->granulepos=v->granulepos;
  109297. vb->pcmend=ci->blocksizes[v->W];
  109298. /* copy the vectors; this uses the local storage in vb */
  109299. /* this tracks 'strongest peak' for later psychoacoustics */
  109300. /* moved to the global psy state; clean this mess up */
  109301. if(vbi->ampmax>g->ampmax)g->ampmax=vbi->ampmax;
  109302. g->ampmax=_vp_ampmax_decay(g->ampmax,v);
  109303. vbi->ampmax=g->ampmax;
  109304. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  109305. vbi->pcmdelay=(float**)_vorbis_block_alloc(vb,sizeof(*vbi->pcmdelay)*vi->channels);
  109306. for(i=0;i<vi->channels;i++){
  109307. vbi->pcmdelay[i]=
  109308. (float*) _vorbis_block_alloc(vb,(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  109309. memcpy(vbi->pcmdelay[i],v->pcm[i],(vb->pcmend+beginW)*sizeof(*vbi->pcmdelay[i]));
  109310. vb->pcm[i]=vbi->pcmdelay[i]+beginW;
  109311. /* before we added the delay
  109312. vb->pcm[i]=_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  109313. memcpy(vb->pcm[i],v->pcm[i]+beginW,ci->blocksizes[v->W]*sizeof(*vb->pcm[i]));
  109314. */
  109315. }
  109316. /* handle eof detection: eof==0 means that we've not yet received EOF
  109317. eof>0 marks the last 'real' sample in pcm[]
  109318. eof<0 'no more to do'; doesn't get here */
  109319. if(v->eofflag){
  109320. if(v->centerW>=v->eofflag){
  109321. v->eofflag=-1;
  109322. vb->eofflag=1;
  109323. return(1);
  109324. }
  109325. }
  109326. /* advance storage vectors and clean up */
  109327. {
  109328. int new_centerNext=ci->blocksizes[1]/2;
  109329. int movementW=centerNext-new_centerNext;
  109330. if(movementW>0){
  109331. _ve_envelope_shift(b->ve,movementW);
  109332. v->pcm_current-=movementW;
  109333. for(i=0;i<vi->channels;i++)
  109334. memmove(v->pcm[i],v->pcm[i]+movementW,
  109335. v->pcm_current*sizeof(*v->pcm[i]));
  109336. v->lW=v->W;
  109337. v->W=v->nW;
  109338. v->centerW=new_centerNext;
  109339. if(v->eofflag){
  109340. v->eofflag-=movementW;
  109341. if(v->eofflag<=0)v->eofflag=-1;
  109342. /* do not add padding to end of stream! */
  109343. if(v->centerW>=v->eofflag){
  109344. v->granulepos+=movementW-(v->centerW-v->eofflag);
  109345. }else{
  109346. v->granulepos+=movementW;
  109347. }
  109348. }else{
  109349. v->granulepos+=movementW;
  109350. }
  109351. }
  109352. }
  109353. /* done */
  109354. return(1);
  109355. }
  109356. int vorbis_synthesis_restart(vorbis_dsp_state *v){
  109357. vorbis_info *vi=v->vi;
  109358. codec_setup_info *ci;
  109359. int hs;
  109360. if(!v->backend_state)return -1;
  109361. if(!vi)return -1;
  109362. ci=(codec_setup_info*) vi->codec_setup;
  109363. if(!ci)return -1;
  109364. hs=ci->halfrate_flag;
  109365. v->centerW=ci->blocksizes[1]>>(hs+1);
  109366. v->pcm_current=v->centerW>>hs;
  109367. v->pcm_returned=-1;
  109368. v->granulepos=-1;
  109369. v->sequence=-1;
  109370. v->eofflag=0;
  109371. ((private_state *)(v->backend_state))->sample_count=-1;
  109372. return(0);
  109373. }
  109374. int vorbis_synthesis_init(vorbis_dsp_state *v,vorbis_info *vi){
  109375. if(_vds_shared_init(v,vi,0)) return 1;
  109376. vorbis_synthesis_restart(v);
  109377. return 0;
  109378. }
  109379. /* Unlike in analysis, the window is only partially applied for each
  109380. block. The time domain envelope is not yet handled at the point of
  109381. calling (as it relies on the previous block). */
  109382. int vorbis_synthesis_blockin(vorbis_dsp_state *v,vorbis_block *vb){
  109383. vorbis_info *vi=v->vi;
  109384. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  109385. private_state *b=(private_state*)v->backend_state;
  109386. int hs=ci->halfrate_flag;
  109387. int i,j;
  109388. if(!vb)return(OV_EINVAL);
  109389. if(v->pcm_current>v->pcm_returned && v->pcm_returned!=-1)return(OV_EINVAL);
  109390. v->lW=v->W;
  109391. v->W=vb->W;
  109392. v->nW=-1;
  109393. if((v->sequence==-1)||
  109394. (v->sequence+1 != vb->sequence)){
  109395. v->granulepos=-1; /* out of sequence; lose count */
  109396. b->sample_count=-1;
  109397. }
  109398. v->sequence=vb->sequence;
  109399. if(vb->pcm){ /* no pcm to process if vorbis_synthesis_trackonly
  109400. was called on block */
  109401. int n=ci->blocksizes[v->W]>>(hs+1);
  109402. int n0=ci->blocksizes[0]>>(hs+1);
  109403. int n1=ci->blocksizes[1]>>(hs+1);
  109404. int thisCenter;
  109405. int prevCenter;
  109406. v->glue_bits+=vb->glue_bits;
  109407. v->time_bits+=vb->time_bits;
  109408. v->floor_bits+=vb->floor_bits;
  109409. v->res_bits+=vb->res_bits;
  109410. if(v->centerW){
  109411. thisCenter=n1;
  109412. prevCenter=0;
  109413. }else{
  109414. thisCenter=0;
  109415. prevCenter=n1;
  109416. }
  109417. /* v->pcm is now used like a two-stage double buffer. We don't want
  109418. to have to constantly shift *or* adjust memory usage. Don't
  109419. accept a new block until the old is shifted out */
  109420. for(j=0;j<vi->channels;j++){
  109421. /* the overlap/add section */
  109422. if(v->lW){
  109423. if(v->W){
  109424. /* large/large */
  109425. float *w=_vorbis_window_get(b->window[1]-hs);
  109426. float *pcm=v->pcm[j]+prevCenter;
  109427. float *p=vb->pcm[j];
  109428. for(i=0;i<n1;i++)
  109429. pcm[i]=pcm[i]*w[n1-i-1] + p[i]*w[i];
  109430. }else{
  109431. /* large/small */
  109432. float *w=_vorbis_window_get(b->window[0]-hs);
  109433. float *pcm=v->pcm[j]+prevCenter+n1/2-n0/2;
  109434. float *p=vb->pcm[j];
  109435. for(i=0;i<n0;i++)
  109436. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  109437. }
  109438. }else{
  109439. if(v->W){
  109440. /* small/large */
  109441. float *w=_vorbis_window_get(b->window[0]-hs);
  109442. float *pcm=v->pcm[j]+prevCenter;
  109443. float *p=vb->pcm[j]+n1/2-n0/2;
  109444. for(i=0;i<n0;i++)
  109445. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  109446. for(;i<n1/2+n0/2;i++)
  109447. pcm[i]=p[i];
  109448. }else{
  109449. /* small/small */
  109450. float *w=_vorbis_window_get(b->window[0]-hs);
  109451. float *pcm=v->pcm[j]+prevCenter;
  109452. float *p=vb->pcm[j];
  109453. for(i=0;i<n0;i++)
  109454. pcm[i]=pcm[i]*w[n0-i-1] +p[i]*w[i];
  109455. }
  109456. }
  109457. /* the copy section */
  109458. {
  109459. float *pcm=v->pcm[j]+thisCenter;
  109460. float *p=vb->pcm[j]+n;
  109461. for(i=0;i<n;i++)
  109462. pcm[i]=p[i];
  109463. }
  109464. }
  109465. if(v->centerW)
  109466. v->centerW=0;
  109467. else
  109468. v->centerW=n1;
  109469. /* deal with initial packet state; we do this using the explicit
  109470. pcm_returned==-1 flag otherwise we're sensitive to first block
  109471. being short or long */
  109472. if(v->pcm_returned==-1){
  109473. v->pcm_returned=thisCenter;
  109474. v->pcm_current=thisCenter;
  109475. }else{
  109476. v->pcm_returned=prevCenter;
  109477. v->pcm_current=prevCenter+
  109478. ((ci->blocksizes[v->lW]/4+
  109479. ci->blocksizes[v->W]/4)>>hs);
  109480. }
  109481. }
  109482. /* track the frame number... This is for convenience, but also
  109483. making sure our last packet doesn't end with added padding. If
  109484. the last packet is partial, the number of samples we'll have to
  109485. return will be past the vb->granulepos.
  109486. This is not foolproof! It will be confused if we begin
  109487. decoding at the last page after a seek or hole. In that case,
  109488. we don't have a starting point to judge where the last frame
  109489. is. For this reason, vorbisfile will always try to make sure
  109490. it reads the last two marked pages in proper sequence */
  109491. if(b->sample_count==-1){
  109492. b->sample_count=0;
  109493. }else{
  109494. b->sample_count+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  109495. }
  109496. if(v->granulepos==-1){
  109497. if(vb->granulepos!=-1){ /* only set if we have a position to set to */
  109498. v->granulepos=vb->granulepos;
  109499. /* is this a short page? */
  109500. if(b->sample_count>v->granulepos){
  109501. /* corner case; if this is both the first and last audio page,
  109502. then spec says the end is cut, not beginning */
  109503. if(vb->eofflag){
  109504. /* trim the end */
  109505. /* no preceeding granulepos; assume we started at zero (we'd
  109506. have to in a short single-page stream) */
  109507. /* granulepos could be -1 due to a seek, but that would result
  109508. in a long count, not short count */
  109509. v->pcm_current-=(b->sample_count-v->granulepos)>>hs;
  109510. }else{
  109511. /* trim the beginning */
  109512. v->pcm_returned+=(b->sample_count-v->granulepos)>>hs;
  109513. if(v->pcm_returned>v->pcm_current)
  109514. v->pcm_returned=v->pcm_current;
  109515. }
  109516. }
  109517. }
  109518. }else{
  109519. v->granulepos+=ci->blocksizes[v->lW]/4+ci->blocksizes[v->W]/4;
  109520. if(vb->granulepos!=-1 && v->granulepos!=vb->granulepos){
  109521. if(v->granulepos>vb->granulepos){
  109522. long extra=v->granulepos-vb->granulepos;
  109523. if(extra)
  109524. if(vb->eofflag){
  109525. /* partial last frame. Strip the extra samples off */
  109526. v->pcm_current-=extra>>hs;
  109527. } /* else {Shouldn't happen *unless* the bitstream is out of
  109528. spec. Either way, believe the bitstream } */
  109529. } /* else {Shouldn't happen *unless* the bitstream is out of
  109530. spec. Either way, believe the bitstream } */
  109531. v->granulepos=vb->granulepos;
  109532. }
  109533. }
  109534. /* Update, cleanup */
  109535. if(vb->eofflag)v->eofflag=1;
  109536. return(0);
  109537. }
  109538. /* pcm==NULL indicates we just want the pending samples, no more */
  109539. int vorbis_synthesis_pcmout(vorbis_dsp_state *v,float ***pcm){
  109540. vorbis_info *vi=v->vi;
  109541. if(v->pcm_returned>-1 && v->pcm_returned<v->pcm_current){
  109542. if(pcm){
  109543. int i;
  109544. for(i=0;i<vi->channels;i++)
  109545. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  109546. *pcm=v->pcmret;
  109547. }
  109548. return(v->pcm_current-v->pcm_returned);
  109549. }
  109550. return(0);
  109551. }
  109552. int vorbis_synthesis_read(vorbis_dsp_state *v,int n){
  109553. if(n && v->pcm_returned+n>v->pcm_current)return(OV_EINVAL);
  109554. v->pcm_returned+=n;
  109555. return(0);
  109556. }
  109557. /* intended for use with a specific vorbisfile feature; we want access
  109558. to the [usually synthetic/postextrapolated] buffer and lapping at
  109559. the end of a decode cycle, specifically, a half-short-block worth.
  109560. This funtion works like pcmout above, except it will also expose
  109561. this implicit buffer data not normally decoded. */
  109562. int vorbis_synthesis_lapout(vorbis_dsp_state *v,float ***pcm){
  109563. vorbis_info *vi=v->vi;
  109564. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  109565. int hs=ci->halfrate_flag;
  109566. int n=ci->blocksizes[v->W]>>(hs+1);
  109567. int n0=ci->blocksizes[0]>>(hs+1);
  109568. int n1=ci->blocksizes[1]>>(hs+1);
  109569. int i,j;
  109570. if(v->pcm_returned<0)return 0;
  109571. /* our returned data ends at pcm_returned; because the synthesis pcm
  109572. buffer is a two-fragment ring, that means our data block may be
  109573. fragmented by buffering, wrapping or a short block not filling
  109574. out a buffer. To simplify things, we unfragment if it's at all
  109575. possibly needed. Otherwise, we'd need to call lapout more than
  109576. once as well as hold additional dsp state. Opt for
  109577. simplicity. */
  109578. /* centerW was advanced by blockin; it would be the center of the
  109579. *next* block */
  109580. if(v->centerW==n1){
  109581. /* the data buffer wraps; swap the halves */
  109582. /* slow, sure, small */
  109583. for(j=0;j<vi->channels;j++){
  109584. float *p=v->pcm[j];
  109585. for(i=0;i<n1;i++){
  109586. float temp=p[i];
  109587. p[i]=p[i+n1];
  109588. p[i+n1]=temp;
  109589. }
  109590. }
  109591. v->pcm_current-=n1;
  109592. v->pcm_returned-=n1;
  109593. v->centerW=0;
  109594. }
  109595. /* solidify buffer into contiguous space */
  109596. if((v->lW^v->W)==1){
  109597. /* long/short or short/long */
  109598. for(j=0;j<vi->channels;j++){
  109599. float *s=v->pcm[j];
  109600. float *d=v->pcm[j]+(n1-n0)/2;
  109601. for(i=(n1+n0)/2-1;i>=0;--i)
  109602. d[i]=s[i];
  109603. }
  109604. v->pcm_returned+=(n1-n0)/2;
  109605. v->pcm_current+=(n1-n0)/2;
  109606. }else{
  109607. if(v->lW==0){
  109608. /* short/short */
  109609. for(j=0;j<vi->channels;j++){
  109610. float *s=v->pcm[j];
  109611. float *d=v->pcm[j]+n1-n0;
  109612. for(i=n0-1;i>=0;--i)
  109613. d[i]=s[i];
  109614. }
  109615. v->pcm_returned+=n1-n0;
  109616. v->pcm_current+=n1-n0;
  109617. }
  109618. }
  109619. if(pcm){
  109620. int i;
  109621. for(i=0;i<vi->channels;i++)
  109622. v->pcmret[i]=v->pcm[i]+v->pcm_returned;
  109623. *pcm=v->pcmret;
  109624. }
  109625. return(n1+n-v->pcm_returned);
  109626. }
  109627. float *vorbis_window(vorbis_dsp_state *v,int W){
  109628. vorbis_info *vi=v->vi;
  109629. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  109630. int hs=ci->halfrate_flag;
  109631. private_state *b=(private_state*)v->backend_state;
  109632. if(b->window[W]-1<0)return NULL;
  109633. return _vorbis_window_get(b->window[W]-hs);
  109634. }
  109635. #endif
  109636. /********* End of inlined file: block.c *********/
  109637. /********* Start of inlined file: codebook.c *********/
  109638. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  109639. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  109640. // tasks..
  109641. /********* Start of inlined file: juce_Config.h *********/
  109642. #ifndef __JUCE_CONFIG_JUCEHEADER__
  109643. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  109644. /*
  109645. This file contains macros that enable/disable various JUCE features.
  109646. */
  109647. /** The name of the namespace that all Juce classes and functions will be
  109648. put inside. If this is not defined, no namespace will be used.
  109649. */
  109650. #ifndef JUCE_NAMESPACE
  109651. #define JUCE_NAMESPACE juce
  109652. #endif
  109653. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  109654. but if you define this value, you can override this can force it to be true or
  109655. false.
  109656. */
  109657. #ifndef JUCE_FORCE_DEBUG
  109658. //#define JUCE_FORCE_DEBUG 1
  109659. #endif
  109660. /** If this flag is enabled, the the jassert and jassertfalse macros will
  109661. always use Logger::writeToLog() to write a message when an assertion happens.
  109662. Enabling it will also leave this turned on in release builds. When it's disabled,
  109663. however, the jassert and jassertfalse macros will not be compiled in a
  109664. release build.
  109665. @see jassert, jassertfalse, Logger
  109666. */
  109667. #ifndef JUCE_LOG_ASSERTIONS
  109668. // #define JUCE_LOG_ASSERTIONS 1
  109669. #endif
  109670. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  109671. which the ASIOAudioIODevice class can't be built. See the comments in the
  109672. ASIOAudioIODevice class's header file for more info about this.
  109673. (This only affects a Win32 build)
  109674. */
  109675. #ifndef JUCE_ASIO
  109676. #define JUCE_ASIO 1
  109677. #endif
  109678. /** Comment out this macro to disable building of ALSA device support on Linux.
  109679. */
  109680. #ifndef JUCE_ALSA
  109681. #define JUCE_ALSA 1
  109682. #endif
  109683. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  109684. have the SDK installed.
  109685. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  109686. classes will be unavailable.
  109687. On Windows, if you enable this, you'll need to have the QuickTime SDK
  109688. installed, and its header files will need to be on your include path.
  109689. */
  109690. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  109691. #define JUCE_QUICKTIME 1
  109692. #endif
  109693. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  109694. have the appropriate headers and libraries available. If it's not enabled, the
  109695. OpenGLComponent class will be unavailable.
  109696. */
  109697. #ifndef JUCE_OPENGL
  109698. #define JUCE_OPENGL 1
  109699. #endif
  109700. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  109701. If you're not going to need either of these formats, turn off the flags to
  109702. avoid bloating your codebase with them.
  109703. */
  109704. #ifndef JUCE_USE_FLAC
  109705. #define JUCE_USE_FLAC 1
  109706. #endif
  109707. #ifndef JUCE_USE_OGGVORBIS
  109708. #define JUCE_USE_OGGVORBIS 1
  109709. #endif
  109710. /** This flag lets you enable support for CD-burning. You might want to disable
  109711. it to build without the MS SDK under windows.
  109712. */
  109713. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  109714. #define JUCE_USE_CDBURNER 1
  109715. #endif
  109716. /** Enabling this macro means that all regions that get repainted will have a coloured
  109717. line drawn around them.
  109718. This is handy if you're trying to optimise drawing, because it lets you easily see
  109719. when anything is being repainted unnecessarily.
  109720. */
  109721. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  109722. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  109723. #endif
  109724. /** Enable this under Linux to use Xinerama for multi-monitor support.
  109725. */
  109726. #ifndef JUCE_USE_XINERAMA
  109727. #define JUCE_USE_XINERAMA 1
  109728. #endif
  109729. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  109730. */
  109731. #ifndef JUCE_USE_XSHM
  109732. #define JUCE_USE_XSHM 1
  109733. #endif
  109734. /** Enabling this builds support for VST audio plugins.
  109735. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  109736. */
  109737. #ifndef JUCE_PLUGINHOST_VST
  109738. // #define JUCE_PLUGINHOST_VST 1
  109739. #endif
  109740. /** Enabling this builds support for AudioUnit audio plugins.
  109741. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  109742. */
  109743. #ifndef JUCE_PLUGINHOST_AU
  109744. // #define JUCE_PLUGINHOST_AU 1
  109745. #endif
  109746. /** Disabling this will avoid linking to any UI code. This is handy for
  109747. writing command-line utilities, e.g. on linux boxes which don't have some
  109748. of the UI libraries installed.
  109749. (On mac and windows, this won't generally make much difference to the build).
  109750. */
  109751. #ifndef JUCE_BUILD_GUI_CLASSES
  109752. #define JUCE_BUILD_GUI_CLASSES 1
  109753. #endif
  109754. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  109755. */
  109756. #ifndef JUCE_WEB_BROWSER
  109757. #define JUCE_WEB_BROWSER 1
  109758. #endif
  109759. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  109760. codebase - you might need to use this if you're linking to some of these libraries
  109761. yourself.
  109762. */
  109763. #ifndef JUCE_INCLUDE_ZLIB_CODE
  109764. #define JUCE_INCLUDE_ZLIB_CODE 1
  109765. #endif
  109766. #ifndef JUCE_INCLUDE_FLAC_CODE
  109767. #define JUCE_INCLUDE_FLAC_CODE 1
  109768. #endif
  109769. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  109770. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  109771. #endif
  109772. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  109773. #define JUCE_INCLUDE_PNGLIB_CODE 1
  109774. #endif
  109775. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  109776. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  109777. #endif
  109778. /** Enable this to add extra memory-leak info to the new and delete operators.
  109779. (Currently, this only affects Windows builds in debug mode).
  109780. */
  109781. #ifndef JUCE_CHECK_MEMORY_LEAKS
  109782. #define JUCE_CHECK_MEMORY_LEAKS 1
  109783. #endif
  109784. /** Enable this to turn on juce's internal catching of exceptions.
  109785. Turning it off will avoid any exception catching. With it on, all exceptions
  109786. are passed to the JUCEApplication::unhandledException() callback for logging.
  109787. */
  109788. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  109789. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  109790. #endif
  109791. /** If this macro is set, the Juce String class will use unicode as its
  109792. internal representation. If it isn't set, it'll use ANSI.
  109793. */
  109794. #ifndef JUCE_STRINGS_ARE_UNICODE
  109795. #define JUCE_STRINGS_ARE_UNICODE 1
  109796. #endif
  109797. #endif
  109798. /********* End of inlined file: juce_Config.h *********/
  109799. #ifdef _MSC_VER
  109800. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  109801. #endif
  109802. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  109803. #if JUCE_USE_OGGVORBIS
  109804. #include <stdlib.h>
  109805. #include <string.h>
  109806. #include <math.h>
  109807. /* packs the given codebook into the bitstream **************************/
  109808. int vorbis_staticbook_pack(const static_codebook *c,oggpack_buffer *opb){
  109809. long i,j;
  109810. int ordered=0;
  109811. /* first the basic parameters */
  109812. oggpack_write(opb,0x564342,24);
  109813. oggpack_write(opb,c->dim,16);
  109814. oggpack_write(opb,c->entries,24);
  109815. /* pack the codewords. There are two packings; length ordered and
  109816. length random. Decide between the two now. */
  109817. for(i=1;i<c->entries;i++)
  109818. if(c->lengthlist[i-1]==0 || c->lengthlist[i]<c->lengthlist[i-1])break;
  109819. if(i==c->entries)ordered=1;
  109820. if(ordered){
  109821. /* length ordered. We only need to say how many codewords of
  109822. each length. The actual codewords are generated
  109823. deterministically */
  109824. long count=0;
  109825. oggpack_write(opb,1,1); /* ordered */
  109826. oggpack_write(opb,c->lengthlist[0]-1,5); /* 1 to 32 */
  109827. for(i=1;i<c->entries;i++){
  109828. long thisx=c->lengthlist[i];
  109829. long last=c->lengthlist[i-1];
  109830. if(thisx>last){
  109831. for(j=last;j<thisx;j++){
  109832. oggpack_write(opb,i-count,_ilog(c->entries-count));
  109833. count=i;
  109834. }
  109835. }
  109836. }
  109837. oggpack_write(opb,i-count,_ilog(c->entries-count));
  109838. }else{
  109839. /* length random. Again, we don't code the codeword itself, just
  109840. the length. This time, though, we have to encode each length */
  109841. oggpack_write(opb,0,1); /* unordered */
  109842. /* algortihmic mapping has use for 'unused entries', which we tag
  109843. here. The algorithmic mapping happens as usual, but the unused
  109844. entry has no codeword. */
  109845. for(i=0;i<c->entries;i++)
  109846. if(c->lengthlist[i]==0)break;
  109847. if(i==c->entries){
  109848. oggpack_write(opb,0,1); /* no unused entries */
  109849. for(i=0;i<c->entries;i++)
  109850. oggpack_write(opb,c->lengthlist[i]-1,5);
  109851. }else{
  109852. oggpack_write(opb,1,1); /* we have unused entries; thus we tag */
  109853. for(i=0;i<c->entries;i++){
  109854. if(c->lengthlist[i]==0){
  109855. oggpack_write(opb,0,1);
  109856. }else{
  109857. oggpack_write(opb,1,1);
  109858. oggpack_write(opb,c->lengthlist[i]-1,5);
  109859. }
  109860. }
  109861. }
  109862. }
  109863. /* is the entry number the desired return value, or do we have a
  109864. mapping? If we have a mapping, what type? */
  109865. oggpack_write(opb,c->maptype,4);
  109866. switch(c->maptype){
  109867. case 0:
  109868. /* no mapping */
  109869. break;
  109870. case 1:case 2:
  109871. /* implicitly populated value mapping */
  109872. /* explicitly populated value mapping */
  109873. if(!c->quantlist){
  109874. /* no quantlist? error */
  109875. return(-1);
  109876. }
  109877. /* values that define the dequantization */
  109878. oggpack_write(opb,c->q_min,32);
  109879. oggpack_write(opb,c->q_delta,32);
  109880. oggpack_write(opb,c->q_quant-1,4);
  109881. oggpack_write(opb,c->q_sequencep,1);
  109882. {
  109883. int quantvals;
  109884. switch(c->maptype){
  109885. case 1:
  109886. /* a single column of (c->entries/c->dim) quantized values for
  109887. building a full value list algorithmically (square lattice) */
  109888. quantvals=_book_maptype1_quantvals(c);
  109889. break;
  109890. case 2:
  109891. /* every value (c->entries*c->dim total) specified explicitly */
  109892. quantvals=c->entries*c->dim;
  109893. break;
  109894. default: /* NOT_REACHABLE */
  109895. quantvals=-1;
  109896. }
  109897. /* quantized values */
  109898. for(i=0;i<quantvals;i++)
  109899. oggpack_write(opb,labs(c->quantlist[i]),c->q_quant);
  109900. }
  109901. break;
  109902. default:
  109903. /* error case; we don't have any other map types now */
  109904. return(-1);
  109905. }
  109906. return(0);
  109907. }
  109908. /* unpacks a codebook from the packet buffer into the codebook struct,
  109909. readies the codebook auxiliary structures for decode *************/
  109910. int vorbis_staticbook_unpack(oggpack_buffer *opb,static_codebook *s){
  109911. long i,j;
  109912. memset(s,0,sizeof(*s));
  109913. s->allocedp=1;
  109914. /* make sure alignment is correct */
  109915. if(oggpack_read(opb,24)!=0x564342)goto _eofout;
  109916. /* first the basic parameters */
  109917. s->dim=oggpack_read(opb,16);
  109918. s->entries=oggpack_read(opb,24);
  109919. if(s->entries==-1)goto _eofout;
  109920. /* codeword ordering.... length ordered or unordered? */
  109921. switch((int)oggpack_read(opb,1)){
  109922. case 0:
  109923. /* unordered */
  109924. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  109925. /* allocated but unused entries? */
  109926. if(oggpack_read(opb,1)){
  109927. /* yes, unused entries */
  109928. for(i=0;i<s->entries;i++){
  109929. if(oggpack_read(opb,1)){
  109930. long num=oggpack_read(opb,5);
  109931. if(num==-1)goto _eofout;
  109932. s->lengthlist[i]=num+1;
  109933. }else
  109934. s->lengthlist[i]=0;
  109935. }
  109936. }else{
  109937. /* all entries used; no tagging */
  109938. for(i=0;i<s->entries;i++){
  109939. long num=oggpack_read(opb,5);
  109940. if(num==-1)goto _eofout;
  109941. s->lengthlist[i]=num+1;
  109942. }
  109943. }
  109944. break;
  109945. case 1:
  109946. /* ordered */
  109947. {
  109948. long length=oggpack_read(opb,5)+1;
  109949. s->lengthlist=(long*)_ogg_malloc(sizeof(*s->lengthlist)*s->entries);
  109950. for(i=0;i<s->entries;){
  109951. long num=oggpack_read(opb,_ilog(s->entries-i));
  109952. if(num==-1)goto _eofout;
  109953. for(j=0;j<num && i<s->entries;j++,i++)
  109954. s->lengthlist[i]=length;
  109955. length++;
  109956. }
  109957. }
  109958. break;
  109959. default:
  109960. /* EOF */
  109961. return(-1);
  109962. }
  109963. /* Do we have a mapping to unpack? */
  109964. switch((s->maptype=oggpack_read(opb,4))){
  109965. case 0:
  109966. /* no mapping */
  109967. break;
  109968. case 1: case 2:
  109969. /* implicitly populated value mapping */
  109970. /* explicitly populated value mapping */
  109971. s->q_min=oggpack_read(opb,32);
  109972. s->q_delta=oggpack_read(opb,32);
  109973. s->q_quant=oggpack_read(opb,4)+1;
  109974. s->q_sequencep=oggpack_read(opb,1);
  109975. {
  109976. int quantvals=0;
  109977. switch(s->maptype){
  109978. case 1:
  109979. quantvals=_book_maptype1_quantvals(s);
  109980. break;
  109981. case 2:
  109982. quantvals=s->entries*s->dim;
  109983. break;
  109984. }
  109985. /* quantized values */
  109986. s->quantlist=(long*)_ogg_malloc(sizeof(*s->quantlist)*quantvals);
  109987. for(i=0;i<quantvals;i++)
  109988. s->quantlist[i]=oggpack_read(opb,s->q_quant);
  109989. if(quantvals&&s->quantlist[quantvals-1]==-1)goto _eofout;
  109990. }
  109991. break;
  109992. default:
  109993. goto _errout;
  109994. }
  109995. /* all set */
  109996. return(0);
  109997. _errout:
  109998. _eofout:
  109999. vorbis_staticbook_clear(s);
  110000. return(-1);
  110001. }
  110002. /* returns the number of bits ************************************************/
  110003. int vorbis_book_encode(codebook *book, int a, oggpack_buffer *b){
  110004. oggpack_write(b,book->codelist[a],book->c->lengthlist[a]);
  110005. return(book->c->lengthlist[a]);
  110006. }
  110007. /* One the encode side, our vector writers are each designed for a
  110008. specific purpose, and the encoder is not flexible without modification:
  110009. The LSP vector coder uses a single stage nearest-match with no
  110010. interleave, so no step and no error return. This is specced by floor0
  110011. and doesn't change.
  110012. Residue0 encoding interleaves, uses multiple stages, and each stage
  110013. peels of a specific amount of resolution from a lattice (thus we want
  110014. to match by threshold, not nearest match). Residue doesn't *have* to
  110015. be encoded that way, but to change it, one will need to add more
  110016. infrastructure on the encode side (decode side is specced and simpler) */
  110017. /* floor0 LSP (single stage, non interleaved, nearest match) */
  110018. /* returns entry number and *modifies a* to the quantization value *****/
  110019. int vorbis_book_errorv(codebook *book,float *a){
  110020. int dim=book->dim,k;
  110021. int best=_best(book,a,1);
  110022. for(k=0;k<dim;k++)
  110023. a[k]=(book->valuelist+best*dim)[k];
  110024. return(best);
  110025. }
  110026. /* returns the number of bits and *modifies a* to the quantization value *****/
  110027. int vorbis_book_encodev(codebook *book,int best,float *a,oggpack_buffer *b){
  110028. int k,dim=book->dim;
  110029. for(k=0;k<dim;k++)
  110030. a[k]=(book->valuelist+best*dim)[k];
  110031. return(vorbis_book_encode(book,best,b));
  110032. }
  110033. /* the 'eliminate the decode tree' optimization actually requires the
  110034. codewords to be MSb first, not LSb. This is an annoying inelegancy
  110035. (and one of the first places where carefully thought out design
  110036. turned out to be wrong; Vorbis II and future Ogg codecs should go
  110037. to an MSb bitpacker), but not actually the huge hit it appears to
  110038. be. The first-stage decode table catches most words so that
  110039. bitreverse is not in the main execution path. */
  110040. STIN long decode_packed_entry_number(codebook *book, oggpack_buffer *b){
  110041. int read=book->dec_maxlength;
  110042. long lo,hi;
  110043. long lok = oggpack_look(b,book->dec_firsttablen);
  110044. if (lok >= 0) {
  110045. long entry = book->dec_firsttable[lok];
  110046. if(entry&0x80000000UL){
  110047. lo=(entry>>15)&0x7fff;
  110048. hi=book->used_entries-(entry&0x7fff);
  110049. }else{
  110050. oggpack_adv(b, book->dec_codelengths[entry-1]);
  110051. return(entry-1);
  110052. }
  110053. }else{
  110054. lo=0;
  110055. hi=book->used_entries;
  110056. }
  110057. lok = oggpack_look(b, read);
  110058. while(lok<0 && read>1)
  110059. lok = oggpack_look(b, --read);
  110060. if(lok<0)return -1;
  110061. /* bisect search for the codeword in the ordered list */
  110062. {
  110063. ogg_uint32_t testword=ogg_bitreverse((ogg_uint32_t)lok);
  110064. while(hi-lo>1){
  110065. long p=(hi-lo)>>1;
  110066. long test=book->codelist[lo+p]>testword;
  110067. lo+=p&(test-1);
  110068. hi-=p&(-test);
  110069. }
  110070. if(book->dec_codelengths[lo]<=read){
  110071. oggpack_adv(b, book->dec_codelengths[lo]);
  110072. return(lo);
  110073. }
  110074. }
  110075. oggpack_adv(b, read);
  110076. return(-1);
  110077. }
  110078. /* Decode side is specced and easier, because we don't need to find
  110079. matches using different criteria; we simply read and map. There are
  110080. two things we need to do 'depending':
  110081. We may need to support interleave. We don't really, but it's
  110082. convenient to do it here rather than rebuild the vector later.
  110083. Cascades may be additive or multiplicitive; this is not inherent in
  110084. the codebook, but set in the code using the codebook. Like
  110085. interleaving, it's easiest to do it here.
  110086. addmul==0 -> declarative (set the value)
  110087. addmul==1 -> additive
  110088. addmul==2 -> multiplicitive */
  110089. /* returns the [original, not compacted] entry number or -1 on eof *********/
  110090. long vorbis_book_decode(codebook *book, oggpack_buffer *b){
  110091. long packed_entry=decode_packed_entry_number(book,b);
  110092. if(packed_entry>=0)
  110093. return(book->dec_index[packed_entry]);
  110094. /* if there's no dec_index, the codebook unpacking isn't collapsed */
  110095. return(packed_entry);
  110096. }
  110097. /* returns 0 on OK or -1 on eof *************************************/
  110098. long vorbis_book_decodevs_add(codebook *book,float *a,oggpack_buffer *b,int n){
  110099. int step=n/book->dim;
  110100. long *entry = (long*)alloca(sizeof(*entry)*step);
  110101. float **t = (float**)alloca(sizeof(*t)*step);
  110102. int i,j,o;
  110103. for (i = 0; i < step; i++) {
  110104. entry[i]=decode_packed_entry_number(book,b);
  110105. if(entry[i]==-1)return(-1);
  110106. t[i] = book->valuelist+entry[i]*book->dim;
  110107. }
  110108. for(i=0,o=0;i<book->dim;i++,o+=step)
  110109. for (j=0;j<step;j++)
  110110. a[o+j]+=t[j][i];
  110111. return(0);
  110112. }
  110113. long vorbis_book_decodev_add(codebook *book,float *a,oggpack_buffer *b,int n){
  110114. int i,j,entry;
  110115. float *t;
  110116. if(book->dim>8){
  110117. for(i=0;i<n;){
  110118. entry = decode_packed_entry_number(book,b);
  110119. if(entry==-1)return(-1);
  110120. t = book->valuelist+entry*book->dim;
  110121. for (j=0;j<book->dim;)
  110122. a[i++]+=t[j++];
  110123. }
  110124. }else{
  110125. for(i=0;i<n;){
  110126. entry = decode_packed_entry_number(book,b);
  110127. if(entry==-1)return(-1);
  110128. t = book->valuelist+entry*book->dim;
  110129. j=0;
  110130. switch((int)book->dim){
  110131. case 8:
  110132. a[i++]+=t[j++];
  110133. case 7:
  110134. a[i++]+=t[j++];
  110135. case 6:
  110136. a[i++]+=t[j++];
  110137. case 5:
  110138. a[i++]+=t[j++];
  110139. case 4:
  110140. a[i++]+=t[j++];
  110141. case 3:
  110142. a[i++]+=t[j++];
  110143. case 2:
  110144. a[i++]+=t[j++];
  110145. case 1:
  110146. a[i++]+=t[j++];
  110147. case 0:
  110148. break;
  110149. }
  110150. }
  110151. }
  110152. return(0);
  110153. }
  110154. long vorbis_book_decodev_set(codebook *book,float *a,oggpack_buffer *b,int n){
  110155. int i,j,entry;
  110156. float *t;
  110157. for(i=0;i<n;){
  110158. entry = decode_packed_entry_number(book,b);
  110159. if(entry==-1)return(-1);
  110160. t = book->valuelist+entry*book->dim;
  110161. for (j=0;j<book->dim;)
  110162. a[i++]=t[j++];
  110163. }
  110164. return(0);
  110165. }
  110166. long vorbis_book_decodevv_add(codebook *book,float **a,long offset,int ch,
  110167. oggpack_buffer *b,int n){
  110168. long i,j,entry;
  110169. int chptr=0;
  110170. for(i=offset/ch;i<(offset+n)/ch;){
  110171. entry = decode_packed_entry_number(book,b);
  110172. if(entry==-1)return(-1);
  110173. {
  110174. const float *t = book->valuelist+entry*book->dim;
  110175. for (j=0;j<book->dim;j++){
  110176. a[chptr++][i]+=t[j];
  110177. if(chptr==ch){
  110178. chptr=0;
  110179. i++;
  110180. }
  110181. }
  110182. }
  110183. }
  110184. return(0);
  110185. }
  110186. #ifdef _V_SELFTEST
  110187. /* Simple enough; pack a few candidate codebooks, unpack them. Code a
  110188. number of vectors through (keeping track of the quantized values),
  110189. and decode using the unpacked book. quantized version of in should
  110190. exactly equal out */
  110191. #include <stdio.h>
  110192. #include "vorbis/book/lsp20_0.vqh"
  110193. #include "vorbis/book/res0a_13.vqh"
  110194. #define TESTSIZE 40
  110195. float test1[TESTSIZE]={
  110196. 0.105939f,
  110197. 0.215373f,
  110198. 0.429117f,
  110199. 0.587974f,
  110200. 0.181173f,
  110201. 0.296583f,
  110202. 0.515707f,
  110203. 0.715261f,
  110204. 0.162327f,
  110205. 0.263834f,
  110206. 0.342876f,
  110207. 0.406025f,
  110208. 0.103571f,
  110209. 0.223561f,
  110210. 0.368513f,
  110211. 0.540313f,
  110212. 0.136672f,
  110213. 0.395882f,
  110214. 0.587183f,
  110215. 0.652476f,
  110216. 0.114338f,
  110217. 0.417300f,
  110218. 0.525486f,
  110219. 0.698679f,
  110220. 0.147492f,
  110221. 0.324481f,
  110222. 0.643089f,
  110223. 0.757582f,
  110224. 0.139556f,
  110225. 0.215795f,
  110226. 0.324559f,
  110227. 0.399387f,
  110228. 0.120236f,
  110229. 0.267420f,
  110230. 0.446940f,
  110231. 0.608760f,
  110232. 0.115587f,
  110233. 0.287234f,
  110234. 0.571081f,
  110235. 0.708603f,
  110236. };
  110237. float test3[TESTSIZE]={
  110238. 0,1,-2,3,4,-5,6,7,8,9,
  110239. 8,-2,7,-1,4,6,8,3,1,-9,
  110240. 10,11,12,13,14,15,26,17,18,19,
  110241. 30,-25,-30,-1,-5,-32,4,3,-2,0};
  110242. static_codebook *testlist[]={&_vq_book_lsp20_0,
  110243. &_vq_book_res0a_13,NULL};
  110244. float *testvec[]={test1,test3};
  110245. int main(){
  110246. oggpack_buffer write;
  110247. oggpack_buffer read;
  110248. long ptr=0,i;
  110249. oggpack_writeinit(&write);
  110250. fprintf(stderr,"Testing codebook abstraction...:\n");
  110251. while(testlist[ptr]){
  110252. codebook c;
  110253. static_codebook s;
  110254. float *qv=alloca(sizeof(*qv)*TESTSIZE);
  110255. float *iv=alloca(sizeof(*iv)*TESTSIZE);
  110256. memcpy(qv,testvec[ptr],sizeof(*qv)*TESTSIZE);
  110257. memset(iv,0,sizeof(*iv)*TESTSIZE);
  110258. fprintf(stderr,"\tpacking/coding %ld... ",ptr);
  110259. /* pack the codebook, write the testvector */
  110260. oggpack_reset(&write);
  110261. vorbis_book_init_encode(&c,testlist[ptr]); /* get it into memory
  110262. we can write */
  110263. vorbis_staticbook_pack(testlist[ptr],&write);
  110264. fprintf(stderr,"Codebook size %ld bytes... ",oggpack_bytes(&write));
  110265. for(i=0;i<TESTSIZE;i+=c.dim){
  110266. int best=_best(&c,qv+i,1);
  110267. vorbis_book_encodev(&c,best,qv+i,&write);
  110268. }
  110269. vorbis_book_clear(&c);
  110270. fprintf(stderr,"OK.\n");
  110271. fprintf(stderr,"\tunpacking/decoding %ld... ",ptr);
  110272. /* transfer the write data to a read buffer and unpack/read */
  110273. oggpack_readinit(&read,oggpack_get_buffer(&write),oggpack_bytes(&write));
  110274. if(vorbis_staticbook_unpack(&read,&s)){
  110275. fprintf(stderr,"Error unpacking codebook.\n");
  110276. exit(1);
  110277. }
  110278. if(vorbis_book_init_decode(&c,&s)){
  110279. fprintf(stderr,"Error initializing codebook.\n");
  110280. exit(1);
  110281. }
  110282. for(i=0;i<TESTSIZE;i+=c.dim)
  110283. if(vorbis_book_decodev_set(&c,iv+i,&read,c.dim)==-1){
  110284. fprintf(stderr,"Error reading codebook test data (EOP).\n");
  110285. exit(1);
  110286. }
  110287. for(i=0;i<TESTSIZE;i++)
  110288. if(fabs(qv[i]-iv[i])>.000001){
  110289. fprintf(stderr,"read (%g) != written (%g) at position (%ld)\n",
  110290. iv[i],qv[i],i);
  110291. exit(1);
  110292. }
  110293. fprintf(stderr,"OK\n");
  110294. ptr++;
  110295. }
  110296. /* The above is the trivial stuff; now try unquantizing a log scale codebook */
  110297. exit(0);
  110298. }
  110299. #endif
  110300. #endif
  110301. /********* End of inlined file: codebook.c *********/
  110302. /********* Start of inlined file: envelope.c *********/
  110303. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110304. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110305. // tasks..
  110306. /********* Start of inlined file: juce_Config.h *********/
  110307. #ifndef __JUCE_CONFIG_JUCEHEADER__
  110308. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  110309. /*
  110310. This file contains macros that enable/disable various JUCE features.
  110311. */
  110312. /** The name of the namespace that all Juce classes and functions will be
  110313. put inside. If this is not defined, no namespace will be used.
  110314. */
  110315. #ifndef JUCE_NAMESPACE
  110316. #define JUCE_NAMESPACE juce
  110317. #endif
  110318. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  110319. but if you define this value, you can override this can force it to be true or
  110320. false.
  110321. */
  110322. #ifndef JUCE_FORCE_DEBUG
  110323. //#define JUCE_FORCE_DEBUG 1
  110324. #endif
  110325. /** If this flag is enabled, the the jassert and jassertfalse macros will
  110326. always use Logger::writeToLog() to write a message when an assertion happens.
  110327. Enabling it will also leave this turned on in release builds. When it's disabled,
  110328. however, the jassert and jassertfalse macros will not be compiled in a
  110329. release build.
  110330. @see jassert, jassertfalse, Logger
  110331. */
  110332. #ifndef JUCE_LOG_ASSERTIONS
  110333. // #define JUCE_LOG_ASSERTIONS 1
  110334. #endif
  110335. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  110336. which the ASIOAudioIODevice class can't be built. See the comments in the
  110337. ASIOAudioIODevice class's header file for more info about this.
  110338. (This only affects a Win32 build)
  110339. */
  110340. #ifndef JUCE_ASIO
  110341. #define JUCE_ASIO 1
  110342. #endif
  110343. /** Comment out this macro to disable building of ALSA device support on Linux.
  110344. */
  110345. #ifndef JUCE_ALSA
  110346. #define JUCE_ALSA 1
  110347. #endif
  110348. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  110349. have the SDK installed.
  110350. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  110351. classes will be unavailable.
  110352. On Windows, if you enable this, you'll need to have the QuickTime SDK
  110353. installed, and its header files will need to be on your include path.
  110354. */
  110355. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  110356. #define JUCE_QUICKTIME 1
  110357. #endif
  110358. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  110359. have the appropriate headers and libraries available. If it's not enabled, the
  110360. OpenGLComponent class will be unavailable.
  110361. */
  110362. #ifndef JUCE_OPENGL
  110363. #define JUCE_OPENGL 1
  110364. #endif
  110365. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  110366. If you're not going to need either of these formats, turn off the flags to
  110367. avoid bloating your codebase with them.
  110368. */
  110369. #ifndef JUCE_USE_FLAC
  110370. #define JUCE_USE_FLAC 1
  110371. #endif
  110372. #ifndef JUCE_USE_OGGVORBIS
  110373. #define JUCE_USE_OGGVORBIS 1
  110374. #endif
  110375. /** This flag lets you enable support for CD-burning. You might want to disable
  110376. it to build without the MS SDK under windows.
  110377. */
  110378. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  110379. #define JUCE_USE_CDBURNER 1
  110380. #endif
  110381. /** Enabling this macro means that all regions that get repainted will have a coloured
  110382. line drawn around them.
  110383. This is handy if you're trying to optimise drawing, because it lets you easily see
  110384. when anything is being repainted unnecessarily.
  110385. */
  110386. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  110387. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  110388. #endif
  110389. /** Enable this under Linux to use Xinerama for multi-monitor support.
  110390. */
  110391. #ifndef JUCE_USE_XINERAMA
  110392. #define JUCE_USE_XINERAMA 1
  110393. #endif
  110394. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  110395. */
  110396. #ifndef JUCE_USE_XSHM
  110397. #define JUCE_USE_XSHM 1
  110398. #endif
  110399. /** Enabling this builds support for VST audio plugins.
  110400. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  110401. */
  110402. #ifndef JUCE_PLUGINHOST_VST
  110403. // #define JUCE_PLUGINHOST_VST 1
  110404. #endif
  110405. /** Enabling this builds support for AudioUnit audio plugins.
  110406. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  110407. */
  110408. #ifndef JUCE_PLUGINHOST_AU
  110409. // #define JUCE_PLUGINHOST_AU 1
  110410. #endif
  110411. /** Disabling this will avoid linking to any UI code. This is handy for
  110412. writing command-line utilities, e.g. on linux boxes which don't have some
  110413. of the UI libraries installed.
  110414. (On mac and windows, this won't generally make much difference to the build).
  110415. */
  110416. #ifndef JUCE_BUILD_GUI_CLASSES
  110417. #define JUCE_BUILD_GUI_CLASSES 1
  110418. #endif
  110419. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  110420. */
  110421. #ifndef JUCE_WEB_BROWSER
  110422. #define JUCE_WEB_BROWSER 1
  110423. #endif
  110424. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  110425. codebase - you might need to use this if you're linking to some of these libraries
  110426. yourself.
  110427. */
  110428. #ifndef JUCE_INCLUDE_ZLIB_CODE
  110429. #define JUCE_INCLUDE_ZLIB_CODE 1
  110430. #endif
  110431. #ifndef JUCE_INCLUDE_FLAC_CODE
  110432. #define JUCE_INCLUDE_FLAC_CODE 1
  110433. #endif
  110434. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  110435. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  110436. #endif
  110437. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  110438. #define JUCE_INCLUDE_PNGLIB_CODE 1
  110439. #endif
  110440. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  110441. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  110442. #endif
  110443. /** Enable this to add extra memory-leak info to the new and delete operators.
  110444. (Currently, this only affects Windows builds in debug mode).
  110445. */
  110446. #ifndef JUCE_CHECK_MEMORY_LEAKS
  110447. #define JUCE_CHECK_MEMORY_LEAKS 1
  110448. #endif
  110449. /** Enable this to turn on juce's internal catching of exceptions.
  110450. Turning it off will avoid any exception catching. With it on, all exceptions
  110451. are passed to the JUCEApplication::unhandledException() callback for logging.
  110452. */
  110453. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  110454. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  110455. #endif
  110456. /** If this macro is set, the Juce String class will use unicode as its
  110457. internal representation. If it isn't set, it'll use ANSI.
  110458. */
  110459. #ifndef JUCE_STRINGS_ARE_UNICODE
  110460. #define JUCE_STRINGS_ARE_UNICODE 1
  110461. #endif
  110462. #endif
  110463. /********* End of inlined file: juce_Config.h *********/
  110464. #ifdef _MSC_VER
  110465. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110466. #endif
  110467. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110468. #if JUCE_USE_OGGVORBIS
  110469. #include <stdlib.h>
  110470. #include <string.h>
  110471. #include <stdio.h>
  110472. #include <math.h>
  110473. void _ve_envelope_init(envelope_lookup *e,vorbis_info *vi){
  110474. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110475. vorbis_info_psy_global *gi=&ci->psy_g_param;
  110476. int ch=vi->channels;
  110477. int i,j;
  110478. int n=e->winlength=128;
  110479. e->searchstep=64; /* not random */
  110480. e->minenergy=gi->preecho_minenergy;
  110481. e->ch=ch;
  110482. e->storage=128;
  110483. e->cursor=ci->blocksizes[1]/2;
  110484. e->mdct_win=(float*)_ogg_calloc(n,sizeof(*e->mdct_win));
  110485. mdct_init(&e->mdct,n);
  110486. for(i=0;i<n;i++){
  110487. e->mdct_win[i]=sin(i/(n-1.)*M_PI);
  110488. e->mdct_win[i]*=e->mdct_win[i];
  110489. }
  110490. /* magic follows */
  110491. e->band[0].begin=2; e->band[0].end=4;
  110492. e->band[1].begin=4; e->band[1].end=5;
  110493. e->band[2].begin=6; e->band[2].end=6;
  110494. e->band[3].begin=9; e->band[3].end=8;
  110495. e->band[4].begin=13; e->band[4].end=8;
  110496. e->band[5].begin=17; e->band[5].end=8;
  110497. e->band[6].begin=22; e->band[6].end=8;
  110498. for(j=0;j<VE_BANDS;j++){
  110499. n=e->band[j].end;
  110500. e->band[j].window=(float*)_ogg_malloc(n*sizeof(*e->band[0].window));
  110501. for(i=0;i<n;i++){
  110502. e->band[j].window[i]=sin((i+.5)/n*M_PI);
  110503. e->band[j].total+=e->band[j].window[i];
  110504. }
  110505. e->band[j].total=1./e->band[j].total;
  110506. }
  110507. e->filter=(envelope_filter_state*)_ogg_calloc(VE_BANDS*ch,sizeof(*e->filter));
  110508. e->mark=(int*)_ogg_calloc(e->storage,sizeof(*e->mark));
  110509. }
  110510. void _ve_envelope_clear(envelope_lookup *e){
  110511. int i;
  110512. mdct_clear(&e->mdct);
  110513. for(i=0;i<VE_BANDS;i++)
  110514. _ogg_free(e->band[i].window);
  110515. _ogg_free(e->mdct_win);
  110516. _ogg_free(e->filter);
  110517. _ogg_free(e->mark);
  110518. memset(e,0,sizeof(*e));
  110519. }
  110520. /* fairly straight threshhold-by-band based until we find something
  110521. that works better and isn't patented. */
  110522. static int _ve_amp(envelope_lookup *ve,
  110523. vorbis_info_psy_global *gi,
  110524. float *data,
  110525. envelope_band *bands,
  110526. envelope_filter_state *filters,
  110527. long pos){
  110528. long n=ve->winlength;
  110529. int ret=0;
  110530. long i,j;
  110531. float decay;
  110532. /* we want to have a 'minimum bar' for energy, else we're just
  110533. basing blocks on quantization noise that outweighs the signal
  110534. itself (for low power signals) */
  110535. float minV=ve->minenergy;
  110536. float *vec=(float*) alloca(n*sizeof(*vec));
  110537. /* stretch is used to gradually lengthen the number of windows
  110538. considered prevoius-to-potential-trigger */
  110539. int stretch=max(VE_MINSTRETCH,ve->stretch/2);
  110540. float penalty=gi->stretch_penalty-(ve->stretch/2-VE_MINSTRETCH);
  110541. if(penalty<0.f)penalty=0.f;
  110542. if(penalty>gi->stretch_penalty)penalty=gi->stretch_penalty;
  110543. /*_analysis_output_always("lpcm",seq2,data,n,0,0,
  110544. totalshift+pos*ve->searchstep);*/
  110545. /* window and transform */
  110546. for(i=0;i<n;i++)
  110547. vec[i]=data[i]*ve->mdct_win[i];
  110548. mdct_forward(&ve->mdct,vec,vec);
  110549. /*_analysis_output_always("mdct",seq2,vec,n/2,0,1,0); */
  110550. /* near-DC spreading function; this has nothing to do with
  110551. psychoacoustics, just sidelobe leakage and window size */
  110552. {
  110553. float temp=vec[0]*vec[0]+.7*vec[1]*vec[1]+.2*vec[2]*vec[2];
  110554. int ptr=filters->nearptr;
  110555. /* the accumulation is regularly refreshed from scratch to avoid
  110556. floating point creep */
  110557. if(ptr==0){
  110558. decay=filters->nearDC_acc=filters->nearDC_partialacc+temp;
  110559. filters->nearDC_partialacc=temp;
  110560. }else{
  110561. decay=filters->nearDC_acc+=temp;
  110562. filters->nearDC_partialacc+=temp;
  110563. }
  110564. filters->nearDC_acc-=filters->nearDC[ptr];
  110565. filters->nearDC[ptr]=temp;
  110566. decay*=(1./(VE_NEARDC+1));
  110567. filters->nearptr++;
  110568. if(filters->nearptr>=VE_NEARDC)filters->nearptr=0;
  110569. decay=todB(&decay)*.5-15.f;
  110570. }
  110571. /* perform spreading and limiting, also smooth the spectrum. yes,
  110572. the MDCT results in all real coefficients, but it still *behaves*
  110573. like real/imaginary pairs */
  110574. for(i=0;i<n/2;i+=2){
  110575. float val=vec[i]*vec[i]+vec[i+1]*vec[i+1];
  110576. val=todB(&val)*.5f;
  110577. if(val<decay)val=decay;
  110578. if(val<minV)val=minV;
  110579. vec[i>>1]=val;
  110580. decay-=8.;
  110581. }
  110582. /*_analysis_output_always("spread",seq2++,vec,n/4,0,0,0);*/
  110583. /* perform preecho/postecho triggering by band */
  110584. for(j=0;j<VE_BANDS;j++){
  110585. float acc=0.;
  110586. float valmax,valmin;
  110587. /* accumulate amplitude */
  110588. for(i=0;i<bands[j].end;i++)
  110589. acc+=vec[i+bands[j].begin]*bands[j].window[i];
  110590. acc*=bands[j].total;
  110591. /* convert amplitude to delta */
  110592. {
  110593. int p,thisx=filters[j].ampptr;
  110594. float postmax,postmin,premax=-99999.f,premin=99999.f;
  110595. p=thisx;
  110596. p--;
  110597. if(p<0)p+=VE_AMP;
  110598. postmax=max(acc,filters[j].ampbuf[p]);
  110599. postmin=min(acc,filters[j].ampbuf[p]);
  110600. for(i=0;i<stretch;i++){
  110601. p--;
  110602. if(p<0)p+=VE_AMP;
  110603. premax=max(premax,filters[j].ampbuf[p]);
  110604. premin=min(premin,filters[j].ampbuf[p]);
  110605. }
  110606. valmin=postmin-premin;
  110607. valmax=postmax-premax;
  110608. /*filters[j].markers[pos]=valmax;*/
  110609. filters[j].ampbuf[thisx]=acc;
  110610. filters[j].ampptr++;
  110611. if(filters[j].ampptr>=VE_AMP)filters[j].ampptr=0;
  110612. }
  110613. /* look at min/max, decide trigger */
  110614. if(valmax>gi->preecho_thresh[j]+penalty){
  110615. ret|=1;
  110616. ret|=4;
  110617. }
  110618. if(valmin<gi->postecho_thresh[j]-penalty)ret|=2;
  110619. }
  110620. return(ret);
  110621. }
  110622. #if 0
  110623. static int seq=0;
  110624. static ogg_int64_t totalshift=-1024;
  110625. #endif
  110626. long _ve_envelope_search(vorbis_dsp_state *v){
  110627. vorbis_info *vi=v->vi;
  110628. codec_setup_info *ci=(codec_setup_info *)vi->codec_setup;
  110629. vorbis_info_psy_global *gi=&ci->psy_g_param;
  110630. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  110631. long i,j;
  110632. int first=ve->current/ve->searchstep;
  110633. int last=v->pcm_current/ve->searchstep-VE_WIN;
  110634. if(first<0)first=0;
  110635. /* make sure we have enough storage to match the PCM */
  110636. if(last+VE_WIN+VE_POST>ve->storage){
  110637. ve->storage=last+VE_WIN+VE_POST; /* be sure */
  110638. ve->mark=(int*)_ogg_realloc(ve->mark,ve->storage*sizeof(*ve->mark));
  110639. }
  110640. for(j=first;j<last;j++){
  110641. int ret=0;
  110642. ve->stretch++;
  110643. if(ve->stretch>VE_MAXSTRETCH*2)
  110644. ve->stretch=VE_MAXSTRETCH*2;
  110645. for(i=0;i<ve->ch;i++){
  110646. float *pcm=v->pcm[i]+ve->searchstep*(j);
  110647. ret|=_ve_amp(ve,gi,pcm,ve->band,ve->filter+i*VE_BANDS,j);
  110648. }
  110649. ve->mark[j+VE_POST]=0;
  110650. if(ret&1){
  110651. ve->mark[j]=1;
  110652. ve->mark[j+1]=1;
  110653. }
  110654. if(ret&2){
  110655. ve->mark[j]=1;
  110656. if(j>0)ve->mark[j-1]=1;
  110657. }
  110658. if(ret&4)ve->stretch=-1;
  110659. }
  110660. ve->current=last*ve->searchstep;
  110661. {
  110662. long centerW=v->centerW;
  110663. long testW=
  110664. centerW+
  110665. ci->blocksizes[v->W]/4+
  110666. ci->blocksizes[1]/2+
  110667. ci->blocksizes[0]/4;
  110668. j=ve->cursor;
  110669. while(j<ve->current-(ve->searchstep)){/* account for postecho
  110670. working back one window */
  110671. if(j>=testW)return(1);
  110672. ve->cursor=j;
  110673. if(ve->mark[j/ve->searchstep]){
  110674. if(j>centerW){
  110675. #if 0
  110676. if(j>ve->curmark){
  110677. float *marker=alloca(v->pcm_current*sizeof(*marker));
  110678. int l,m;
  110679. memset(marker,0,sizeof(*marker)*v->pcm_current);
  110680. fprintf(stderr,"mark! seq=%d, cursor:%fs time:%fs\n",
  110681. seq,
  110682. (totalshift+ve->cursor)/44100.,
  110683. (totalshift+j)/44100.);
  110684. _analysis_output_always("pcmL",seq,v->pcm[0],v->pcm_current,0,0,totalshift);
  110685. _analysis_output_always("pcmR",seq,v->pcm[1],v->pcm_current,0,0,totalshift);
  110686. _analysis_output_always("markL",seq,v->pcm[0],j,0,0,totalshift);
  110687. _analysis_output_always("markR",seq,v->pcm[1],j,0,0,totalshift);
  110688. for(m=0;m<VE_BANDS;m++){
  110689. char buf[80];
  110690. sprintf(buf,"delL%d",m);
  110691. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m].markers[l]*.1;
  110692. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  110693. }
  110694. for(m=0;m<VE_BANDS;m++){
  110695. char buf[80];
  110696. sprintf(buf,"delR%d",m);
  110697. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->filter[m+VE_BANDS].markers[l]*.1;
  110698. _analysis_output_always(buf,seq,marker,v->pcm_current,0,0,totalshift);
  110699. }
  110700. for(l=0;l<last;l++)marker[l*ve->searchstep]=ve->mark[l]*.4;
  110701. _analysis_output_always("mark",seq,marker,v->pcm_current,0,0,totalshift);
  110702. seq++;
  110703. }
  110704. #endif
  110705. ve->curmark=j;
  110706. if(j>=testW)return(1);
  110707. return(0);
  110708. }
  110709. }
  110710. j+=ve->searchstep;
  110711. }
  110712. }
  110713. return(-1);
  110714. }
  110715. int _ve_envelope_mark(vorbis_dsp_state *v){
  110716. envelope_lookup *ve=((private_state *)(v->backend_state))->ve;
  110717. vorbis_info *vi=v->vi;
  110718. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110719. long centerW=v->centerW;
  110720. long beginW=centerW-ci->blocksizes[v->W]/4;
  110721. long endW=centerW+ci->blocksizes[v->W]/4;
  110722. if(v->W){
  110723. beginW-=ci->blocksizes[v->lW]/4;
  110724. endW+=ci->blocksizes[v->nW]/4;
  110725. }else{
  110726. beginW-=ci->blocksizes[0]/4;
  110727. endW+=ci->blocksizes[0]/4;
  110728. }
  110729. if(ve->curmark>=beginW && ve->curmark<endW)return(1);
  110730. {
  110731. long first=beginW/ve->searchstep;
  110732. long last=endW/ve->searchstep;
  110733. long i;
  110734. for(i=first;i<last;i++)
  110735. if(ve->mark[i])return(1);
  110736. }
  110737. return(0);
  110738. }
  110739. void _ve_envelope_shift(envelope_lookup *e,long shift){
  110740. int smallsize=e->current/e->searchstep+VE_POST; /* adjust for placing marks
  110741. ahead of ve->current */
  110742. int smallshift=shift/e->searchstep;
  110743. memmove(e->mark,e->mark+smallshift,(smallsize-smallshift)*sizeof(*e->mark));
  110744. #if 0
  110745. for(i=0;i<VE_BANDS*e->ch;i++)
  110746. memmove(e->filter[i].markers,
  110747. e->filter[i].markers+smallshift,
  110748. (1024-smallshift)*sizeof(*(*e->filter).markers));
  110749. totalshift+=shift;
  110750. #endif
  110751. e->current-=shift;
  110752. if(e->curmark>=0)
  110753. e->curmark-=shift;
  110754. e->cursor-=shift;
  110755. }
  110756. #endif
  110757. /********* End of inlined file: envelope.c *********/
  110758. /********* Start of inlined file: floor0.c *********/
  110759. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  110760. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  110761. // tasks..
  110762. /********* Start of inlined file: juce_Config.h *********/
  110763. #ifndef __JUCE_CONFIG_JUCEHEADER__
  110764. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  110765. /*
  110766. This file contains macros that enable/disable various JUCE features.
  110767. */
  110768. /** The name of the namespace that all Juce classes and functions will be
  110769. put inside. If this is not defined, no namespace will be used.
  110770. */
  110771. #ifndef JUCE_NAMESPACE
  110772. #define JUCE_NAMESPACE juce
  110773. #endif
  110774. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  110775. but if you define this value, you can override this can force it to be true or
  110776. false.
  110777. */
  110778. #ifndef JUCE_FORCE_DEBUG
  110779. //#define JUCE_FORCE_DEBUG 1
  110780. #endif
  110781. /** If this flag is enabled, the the jassert and jassertfalse macros will
  110782. always use Logger::writeToLog() to write a message when an assertion happens.
  110783. Enabling it will also leave this turned on in release builds. When it's disabled,
  110784. however, the jassert and jassertfalse macros will not be compiled in a
  110785. release build.
  110786. @see jassert, jassertfalse, Logger
  110787. */
  110788. #ifndef JUCE_LOG_ASSERTIONS
  110789. // #define JUCE_LOG_ASSERTIONS 1
  110790. #endif
  110791. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  110792. which the ASIOAudioIODevice class can't be built. See the comments in the
  110793. ASIOAudioIODevice class's header file for more info about this.
  110794. (This only affects a Win32 build)
  110795. */
  110796. #ifndef JUCE_ASIO
  110797. #define JUCE_ASIO 1
  110798. #endif
  110799. /** Comment out this macro to disable building of ALSA device support on Linux.
  110800. */
  110801. #ifndef JUCE_ALSA
  110802. #define JUCE_ALSA 1
  110803. #endif
  110804. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  110805. have the SDK installed.
  110806. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  110807. classes will be unavailable.
  110808. On Windows, if you enable this, you'll need to have the QuickTime SDK
  110809. installed, and its header files will need to be on your include path.
  110810. */
  110811. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  110812. #define JUCE_QUICKTIME 1
  110813. #endif
  110814. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  110815. have the appropriate headers and libraries available. If it's not enabled, the
  110816. OpenGLComponent class will be unavailable.
  110817. */
  110818. #ifndef JUCE_OPENGL
  110819. #define JUCE_OPENGL 1
  110820. #endif
  110821. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  110822. If you're not going to need either of these formats, turn off the flags to
  110823. avoid bloating your codebase with them.
  110824. */
  110825. #ifndef JUCE_USE_FLAC
  110826. #define JUCE_USE_FLAC 1
  110827. #endif
  110828. #ifndef JUCE_USE_OGGVORBIS
  110829. #define JUCE_USE_OGGVORBIS 1
  110830. #endif
  110831. /** This flag lets you enable support for CD-burning. You might want to disable
  110832. it to build without the MS SDK under windows.
  110833. */
  110834. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  110835. #define JUCE_USE_CDBURNER 1
  110836. #endif
  110837. /** Enabling this macro means that all regions that get repainted will have a coloured
  110838. line drawn around them.
  110839. This is handy if you're trying to optimise drawing, because it lets you easily see
  110840. when anything is being repainted unnecessarily.
  110841. */
  110842. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  110843. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  110844. #endif
  110845. /** Enable this under Linux to use Xinerama for multi-monitor support.
  110846. */
  110847. #ifndef JUCE_USE_XINERAMA
  110848. #define JUCE_USE_XINERAMA 1
  110849. #endif
  110850. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  110851. */
  110852. #ifndef JUCE_USE_XSHM
  110853. #define JUCE_USE_XSHM 1
  110854. #endif
  110855. /** Enabling this builds support for VST audio plugins.
  110856. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  110857. */
  110858. #ifndef JUCE_PLUGINHOST_VST
  110859. // #define JUCE_PLUGINHOST_VST 1
  110860. #endif
  110861. /** Enabling this builds support for AudioUnit audio plugins.
  110862. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  110863. */
  110864. #ifndef JUCE_PLUGINHOST_AU
  110865. // #define JUCE_PLUGINHOST_AU 1
  110866. #endif
  110867. /** Disabling this will avoid linking to any UI code. This is handy for
  110868. writing command-line utilities, e.g. on linux boxes which don't have some
  110869. of the UI libraries installed.
  110870. (On mac and windows, this won't generally make much difference to the build).
  110871. */
  110872. #ifndef JUCE_BUILD_GUI_CLASSES
  110873. #define JUCE_BUILD_GUI_CLASSES 1
  110874. #endif
  110875. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  110876. */
  110877. #ifndef JUCE_WEB_BROWSER
  110878. #define JUCE_WEB_BROWSER 1
  110879. #endif
  110880. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  110881. codebase - you might need to use this if you're linking to some of these libraries
  110882. yourself.
  110883. */
  110884. #ifndef JUCE_INCLUDE_ZLIB_CODE
  110885. #define JUCE_INCLUDE_ZLIB_CODE 1
  110886. #endif
  110887. #ifndef JUCE_INCLUDE_FLAC_CODE
  110888. #define JUCE_INCLUDE_FLAC_CODE 1
  110889. #endif
  110890. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  110891. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  110892. #endif
  110893. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  110894. #define JUCE_INCLUDE_PNGLIB_CODE 1
  110895. #endif
  110896. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  110897. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  110898. #endif
  110899. /** Enable this to add extra memory-leak info to the new and delete operators.
  110900. (Currently, this only affects Windows builds in debug mode).
  110901. */
  110902. #ifndef JUCE_CHECK_MEMORY_LEAKS
  110903. #define JUCE_CHECK_MEMORY_LEAKS 1
  110904. #endif
  110905. /** Enable this to turn on juce's internal catching of exceptions.
  110906. Turning it off will avoid any exception catching. With it on, all exceptions
  110907. are passed to the JUCEApplication::unhandledException() callback for logging.
  110908. */
  110909. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  110910. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  110911. #endif
  110912. /** If this macro is set, the Juce String class will use unicode as its
  110913. internal representation. If it isn't set, it'll use ANSI.
  110914. */
  110915. #ifndef JUCE_STRINGS_ARE_UNICODE
  110916. #define JUCE_STRINGS_ARE_UNICODE 1
  110917. #endif
  110918. #endif
  110919. /********* End of inlined file: juce_Config.h *********/
  110920. #ifdef _MSC_VER
  110921. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  110922. #endif
  110923. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  110924. #if JUCE_USE_OGGVORBIS
  110925. #include <stdlib.h>
  110926. #include <string.h>
  110927. #include <math.h>
  110928. /********* Start of inlined file: lsp.h *********/
  110929. #ifndef _V_LSP_H_
  110930. #define _V_LSP_H_
  110931. extern int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m);
  110932. extern void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,
  110933. float *lsp,int m,
  110934. float amp,float ampoffset);
  110935. #endif
  110936. /********* End of inlined file: lsp.h *********/
  110937. #include <stdio.h>
  110938. typedef struct {
  110939. int ln;
  110940. int m;
  110941. int **linearmap;
  110942. int n[2];
  110943. vorbis_info_floor0 *vi;
  110944. long bits;
  110945. long frames;
  110946. } vorbis_look_floor0;
  110947. /***********************************************/
  110948. static void floor0_free_info(vorbis_info_floor *i){
  110949. vorbis_info_floor0 *info=(vorbis_info_floor0 *)i;
  110950. if(info){
  110951. memset(info,0,sizeof(*info));
  110952. _ogg_free(info);
  110953. }
  110954. }
  110955. static void floor0_free_look(vorbis_look_floor *i){
  110956. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  110957. if(look){
  110958. if(look->linearmap){
  110959. if(look->linearmap[0])_ogg_free(look->linearmap[0]);
  110960. if(look->linearmap[1])_ogg_free(look->linearmap[1]);
  110961. _ogg_free(look->linearmap);
  110962. }
  110963. memset(look,0,sizeof(*look));
  110964. _ogg_free(look);
  110965. }
  110966. }
  110967. static vorbis_info_floor *floor0_unpack (vorbis_info *vi,oggpack_buffer *opb){
  110968. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  110969. int j;
  110970. vorbis_info_floor0 *info=(vorbis_info_floor0*)_ogg_malloc(sizeof(*info));
  110971. info->order=oggpack_read(opb,8);
  110972. info->rate=oggpack_read(opb,16);
  110973. info->barkmap=oggpack_read(opb,16);
  110974. info->ampbits=oggpack_read(opb,6);
  110975. info->ampdB=oggpack_read(opb,8);
  110976. info->numbooks=oggpack_read(opb,4)+1;
  110977. if(info->order<1)goto err_out;
  110978. if(info->rate<1)goto err_out;
  110979. if(info->barkmap<1)goto err_out;
  110980. if(info->numbooks<1)goto err_out;
  110981. for(j=0;j<info->numbooks;j++){
  110982. info->books[j]=oggpack_read(opb,8);
  110983. if(info->books[j]<0 || info->books[j]>=ci->books)goto err_out;
  110984. }
  110985. return(info);
  110986. err_out:
  110987. floor0_free_info(info);
  110988. return(NULL);
  110989. }
  110990. /* initialize Bark scale and normalization lookups. We could do this
  110991. with static tables, but Vorbis allows a number of possible
  110992. combinations, so it's best to do it computationally.
  110993. The below is authoritative in terms of defining scale mapping.
  110994. Note that the scale depends on the sampling rate as well as the
  110995. linear block and mapping sizes */
  110996. static void floor0_map_lazy_init(vorbis_block *vb,
  110997. vorbis_info_floor *infoX,
  110998. vorbis_look_floor0 *look){
  110999. if(!look->linearmap[vb->W]){
  111000. vorbis_dsp_state *vd=vb->vd;
  111001. vorbis_info *vi=vd->vi;
  111002. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111003. vorbis_info_floor0 *info=(vorbis_info_floor0 *)infoX;
  111004. int W=vb->W;
  111005. int n=ci->blocksizes[W]/2,j;
  111006. /* we choose a scaling constant so that:
  111007. floor(bark(rate/2-1)*C)=mapped-1
  111008. floor(bark(rate/2)*C)=mapped */
  111009. float scale=look->ln/toBARK(info->rate/2.f);
  111010. /* the mapping from a linear scale to a smaller bark scale is
  111011. straightforward. We do *not* make sure that the linear mapping
  111012. does not skip bark-scale bins; the decoder simply skips them and
  111013. the encoder may do what it wishes in filling them. They're
  111014. necessary in some mapping combinations to keep the scale spacing
  111015. accurate */
  111016. look->linearmap[W]=(int*)_ogg_malloc((n+1)*sizeof(**look->linearmap));
  111017. for(j=0;j<n;j++){
  111018. int val=floor( toBARK((info->rate/2.f)/n*j)
  111019. *scale); /* bark numbers represent band edges */
  111020. if(val>=look->ln)val=look->ln-1; /* guard against the approximation */
  111021. look->linearmap[W][j]=val;
  111022. }
  111023. look->linearmap[W][j]=-1;
  111024. look->n[W]=n;
  111025. }
  111026. }
  111027. static vorbis_look_floor *floor0_look(vorbis_dsp_state *vd,
  111028. vorbis_info_floor *i){
  111029. vorbis_info_floor0 *info=(vorbis_info_floor0*)i;
  111030. vorbis_look_floor0 *look=(vorbis_look_floor0*)_ogg_calloc(1,sizeof(*look));
  111031. look->m=info->order;
  111032. look->ln=info->barkmap;
  111033. look->vi=info;
  111034. look->linearmap=(int**)_ogg_calloc(2,sizeof(*look->linearmap));
  111035. return look;
  111036. }
  111037. static void *floor0_inverse1(vorbis_block *vb,vorbis_look_floor *i){
  111038. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111039. vorbis_info_floor0 *info=look->vi;
  111040. int j,k;
  111041. int ampraw=oggpack_read(&vb->opb,info->ampbits);
  111042. if(ampraw>0){ /* also handles the -1 out of data case */
  111043. long maxval=(1<<info->ampbits)-1;
  111044. float amp=(float)ampraw/maxval*info->ampdB;
  111045. int booknum=oggpack_read(&vb->opb,_ilog(info->numbooks));
  111046. if(booknum!=-1 && booknum<info->numbooks){ /* be paranoid */
  111047. codec_setup_info *ci=(codec_setup_info *)vb->vd->vi->codec_setup;
  111048. codebook *b=ci->fullbooks+info->books[booknum];
  111049. float last=0.f;
  111050. /* the additional b->dim is a guard against any possible stack
  111051. smash; b->dim is provably more than we can overflow the
  111052. vector */
  111053. float *lsp=(float*)_vorbis_block_alloc(vb,sizeof(*lsp)*(look->m+b->dim+1));
  111054. for(j=0;j<look->m;j+=b->dim)
  111055. if(vorbis_book_decodev_set(b,lsp+j,&vb->opb,b->dim)==-1)goto eop;
  111056. for(j=0;j<look->m;){
  111057. for(k=0;k<b->dim;k++,j++)lsp[j]+=last;
  111058. last=lsp[j-1];
  111059. }
  111060. lsp[look->m]=amp;
  111061. return(lsp);
  111062. }
  111063. }
  111064. eop:
  111065. return(NULL);
  111066. }
  111067. static int floor0_inverse2(vorbis_block *vb,vorbis_look_floor *i,
  111068. void *memo,float *out){
  111069. vorbis_look_floor0 *look=(vorbis_look_floor0 *)i;
  111070. vorbis_info_floor0 *info=look->vi;
  111071. floor0_map_lazy_init(vb,info,look);
  111072. if(memo){
  111073. float *lsp=(float *)memo;
  111074. float amp=lsp[look->m];
  111075. /* take the coefficients back to a spectral envelope curve */
  111076. vorbis_lsp_to_curve(out,
  111077. look->linearmap[vb->W],
  111078. look->n[vb->W],
  111079. look->ln,
  111080. lsp,look->m,amp,(float)info->ampdB);
  111081. return(1);
  111082. }
  111083. memset(out,0,sizeof(*out)*look->n[vb->W]);
  111084. return(0);
  111085. }
  111086. /* export hooks */
  111087. vorbis_func_floor floor0_exportbundle={
  111088. NULL,&floor0_unpack,&floor0_look,&floor0_free_info,
  111089. &floor0_free_look,&floor0_inverse1,&floor0_inverse2
  111090. };
  111091. #endif
  111092. /********* End of inlined file: floor0.c *********/
  111093. /********* Start of inlined file: floor1.c *********/
  111094. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  111095. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  111096. // tasks..
  111097. /********* Start of inlined file: juce_Config.h *********/
  111098. #ifndef __JUCE_CONFIG_JUCEHEADER__
  111099. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  111100. /*
  111101. This file contains macros that enable/disable various JUCE features.
  111102. */
  111103. /** The name of the namespace that all Juce classes and functions will be
  111104. put inside. If this is not defined, no namespace will be used.
  111105. */
  111106. #ifndef JUCE_NAMESPACE
  111107. #define JUCE_NAMESPACE juce
  111108. #endif
  111109. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  111110. but if you define this value, you can override this can force it to be true or
  111111. false.
  111112. */
  111113. #ifndef JUCE_FORCE_DEBUG
  111114. //#define JUCE_FORCE_DEBUG 1
  111115. #endif
  111116. /** If this flag is enabled, the the jassert and jassertfalse macros will
  111117. always use Logger::writeToLog() to write a message when an assertion happens.
  111118. Enabling it will also leave this turned on in release builds. When it's disabled,
  111119. however, the jassert and jassertfalse macros will not be compiled in a
  111120. release build.
  111121. @see jassert, jassertfalse, Logger
  111122. */
  111123. #ifndef JUCE_LOG_ASSERTIONS
  111124. // #define JUCE_LOG_ASSERTIONS 1
  111125. #endif
  111126. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  111127. which the ASIOAudioIODevice class can't be built. See the comments in the
  111128. ASIOAudioIODevice class's header file for more info about this.
  111129. (This only affects a Win32 build)
  111130. */
  111131. #ifndef JUCE_ASIO
  111132. #define JUCE_ASIO 1
  111133. #endif
  111134. /** Comment out this macro to disable building of ALSA device support on Linux.
  111135. */
  111136. #ifndef JUCE_ALSA
  111137. #define JUCE_ALSA 1
  111138. #endif
  111139. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  111140. have the SDK installed.
  111141. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  111142. classes will be unavailable.
  111143. On Windows, if you enable this, you'll need to have the QuickTime SDK
  111144. installed, and its header files will need to be on your include path.
  111145. */
  111146. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  111147. #define JUCE_QUICKTIME 1
  111148. #endif
  111149. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  111150. have the appropriate headers and libraries available. If it's not enabled, the
  111151. OpenGLComponent class will be unavailable.
  111152. */
  111153. #ifndef JUCE_OPENGL
  111154. #define JUCE_OPENGL 1
  111155. #endif
  111156. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  111157. If you're not going to need either of these formats, turn off the flags to
  111158. avoid bloating your codebase with them.
  111159. */
  111160. #ifndef JUCE_USE_FLAC
  111161. #define JUCE_USE_FLAC 1
  111162. #endif
  111163. #ifndef JUCE_USE_OGGVORBIS
  111164. #define JUCE_USE_OGGVORBIS 1
  111165. #endif
  111166. /** This flag lets you enable support for CD-burning. You might want to disable
  111167. it to build without the MS SDK under windows.
  111168. */
  111169. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  111170. #define JUCE_USE_CDBURNER 1
  111171. #endif
  111172. /** Enabling this macro means that all regions that get repainted will have a coloured
  111173. line drawn around them.
  111174. This is handy if you're trying to optimise drawing, because it lets you easily see
  111175. when anything is being repainted unnecessarily.
  111176. */
  111177. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  111178. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  111179. #endif
  111180. /** Enable this under Linux to use Xinerama for multi-monitor support.
  111181. */
  111182. #ifndef JUCE_USE_XINERAMA
  111183. #define JUCE_USE_XINERAMA 1
  111184. #endif
  111185. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  111186. */
  111187. #ifndef JUCE_USE_XSHM
  111188. #define JUCE_USE_XSHM 1
  111189. #endif
  111190. /** Enabling this builds support for VST audio plugins.
  111191. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  111192. */
  111193. #ifndef JUCE_PLUGINHOST_VST
  111194. // #define JUCE_PLUGINHOST_VST 1
  111195. #endif
  111196. /** Enabling this builds support for AudioUnit audio plugins.
  111197. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  111198. */
  111199. #ifndef JUCE_PLUGINHOST_AU
  111200. // #define JUCE_PLUGINHOST_AU 1
  111201. #endif
  111202. /** Disabling this will avoid linking to any UI code. This is handy for
  111203. writing command-line utilities, e.g. on linux boxes which don't have some
  111204. of the UI libraries installed.
  111205. (On mac and windows, this won't generally make much difference to the build).
  111206. */
  111207. #ifndef JUCE_BUILD_GUI_CLASSES
  111208. #define JUCE_BUILD_GUI_CLASSES 1
  111209. #endif
  111210. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  111211. */
  111212. #ifndef JUCE_WEB_BROWSER
  111213. #define JUCE_WEB_BROWSER 1
  111214. #endif
  111215. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  111216. codebase - you might need to use this if you're linking to some of these libraries
  111217. yourself.
  111218. */
  111219. #ifndef JUCE_INCLUDE_ZLIB_CODE
  111220. #define JUCE_INCLUDE_ZLIB_CODE 1
  111221. #endif
  111222. #ifndef JUCE_INCLUDE_FLAC_CODE
  111223. #define JUCE_INCLUDE_FLAC_CODE 1
  111224. #endif
  111225. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  111226. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  111227. #endif
  111228. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  111229. #define JUCE_INCLUDE_PNGLIB_CODE 1
  111230. #endif
  111231. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  111232. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  111233. #endif
  111234. /** Enable this to add extra memory-leak info to the new and delete operators.
  111235. (Currently, this only affects Windows builds in debug mode).
  111236. */
  111237. #ifndef JUCE_CHECK_MEMORY_LEAKS
  111238. #define JUCE_CHECK_MEMORY_LEAKS 1
  111239. #endif
  111240. /** Enable this to turn on juce's internal catching of exceptions.
  111241. Turning it off will avoid any exception catching. With it on, all exceptions
  111242. are passed to the JUCEApplication::unhandledException() callback for logging.
  111243. */
  111244. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  111245. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  111246. #endif
  111247. /** If this macro is set, the Juce String class will use unicode as its
  111248. internal representation. If it isn't set, it'll use ANSI.
  111249. */
  111250. #ifndef JUCE_STRINGS_ARE_UNICODE
  111251. #define JUCE_STRINGS_ARE_UNICODE 1
  111252. #endif
  111253. #endif
  111254. /********* End of inlined file: juce_Config.h *********/
  111255. #ifdef _MSC_VER
  111256. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  111257. #endif
  111258. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  111259. #if JUCE_USE_OGGVORBIS
  111260. #include <stdlib.h>
  111261. #include <string.h>
  111262. #include <math.h>
  111263. #include <stdio.h>
  111264. #define floor1_rangedB 140 /* floor 1 fixed at -140dB to 0dB range */
  111265. typedef struct {
  111266. int sorted_index[VIF_POSIT+2];
  111267. int forward_index[VIF_POSIT+2];
  111268. int reverse_index[VIF_POSIT+2];
  111269. int hineighbor[VIF_POSIT];
  111270. int loneighbor[VIF_POSIT];
  111271. int posts;
  111272. int n;
  111273. int quant_q;
  111274. vorbis_info_floor1 *vi;
  111275. long phrasebits;
  111276. long postbits;
  111277. long frames;
  111278. } vorbis_look_floor1;
  111279. typedef struct lsfit_acc{
  111280. long x0;
  111281. long x1;
  111282. long xa;
  111283. long ya;
  111284. long x2a;
  111285. long y2a;
  111286. long xya;
  111287. long an;
  111288. } lsfit_acc;
  111289. /***********************************************/
  111290. static void floor1_free_info(vorbis_info_floor *i){
  111291. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  111292. if(info){
  111293. memset(info,0,sizeof(*info));
  111294. _ogg_free(info);
  111295. }
  111296. }
  111297. static void floor1_free_look(vorbis_look_floor *i){
  111298. vorbis_look_floor1 *look=(vorbis_look_floor1 *)i;
  111299. if(look){
  111300. /*fprintf(stderr,"floor 1 bit usage %f:%f (%f total)\n",
  111301. (float)look->phrasebits/look->frames,
  111302. (float)look->postbits/look->frames,
  111303. (float)(look->postbits+look->phrasebits)/look->frames);*/
  111304. memset(look,0,sizeof(*look));
  111305. _ogg_free(look);
  111306. }
  111307. }
  111308. static void floor1_pack (vorbis_info_floor *i,oggpack_buffer *opb){
  111309. vorbis_info_floor1 *info=(vorbis_info_floor1 *)i;
  111310. int j,k;
  111311. int count=0;
  111312. int rangebits;
  111313. int maxposit=info->postlist[1];
  111314. int maxclass=-1;
  111315. /* save out partitions */
  111316. oggpack_write(opb,info->partitions,5); /* only 0 to 31 legal */
  111317. for(j=0;j<info->partitions;j++){
  111318. oggpack_write(opb,info->partitionclass[j],4); /* only 0 to 15 legal */
  111319. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  111320. }
  111321. /* save out partition classes */
  111322. for(j=0;j<maxclass+1;j++){
  111323. oggpack_write(opb,info->class_dim[j]-1,3); /* 1 to 8 */
  111324. oggpack_write(opb,info->class_subs[j],2); /* 0 to 3 */
  111325. if(info->class_subs[j])oggpack_write(opb,info->class_book[j],8);
  111326. for(k=0;k<(1<<info->class_subs[j]);k++)
  111327. oggpack_write(opb,info->class_subbook[j][k]+1,8);
  111328. }
  111329. /* save out the post list */
  111330. oggpack_write(opb,info->mult-1,2); /* only 1,2,3,4 legal now */
  111331. oggpack_write(opb,ilog2(maxposit),4);
  111332. rangebits=ilog2(maxposit);
  111333. for(j=0,k=0;j<info->partitions;j++){
  111334. count+=info->class_dim[info->partitionclass[j]];
  111335. for(;k<count;k++)
  111336. oggpack_write(opb,info->postlist[k+2],rangebits);
  111337. }
  111338. }
  111339. static vorbis_info_floor *floor1_unpack (vorbis_info *vi,oggpack_buffer *opb){
  111340. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  111341. int j,k,count=0,maxclass=-1,rangebits;
  111342. vorbis_info_floor1 *info=(vorbis_info_floor1*)_ogg_calloc(1,sizeof(*info));
  111343. /* read partitions */
  111344. info->partitions=oggpack_read(opb,5); /* only 0 to 31 legal */
  111345. for(j=0;j<info->partitions;j++){
  111346. info->partitionclass[j]=oggpack_read(opb,4); /* only 0 to 15 legal */
  111347. if(maxclass<info->partitionclass[j])maxclass=info->partitionclass[j];
  111348. }
  111349. /* read partition classes */
  111350. for(j=0;j<maxclass+1;j++){
  111351. info->class_dim[j]=oggpack_read(opb,3)+1; /* 1 to 8 */
  111352. info->class_subs[j]=oggpack_read(opb,2); /* 0,1,2,3 bits */
  111353. if(info->class_subs[j]<0)
  111354. goto err_out;
  111355. if(info->class_subs[j])info->class_book[j]=oggpack_read(opb,8);
  111356. if(info->class_book[j]<0 || info->class_book[j]>=ci->books)
  111357. goto err_out;
  111358. for(k=0;k<(1<<info->class_subs[j]);k++){
  111359. info->class_subbook[j][k]=oggpack_read(opb,8)-1;
  111360. if(info->class_subbook[j][k]<-1 || info->class_subbook[j][k]>=ci->books)
  111361. goto err_out;
  111362. }
  111363. }
  111364. /* read the post list */
  111365. info->mult=oggpack_read(opb,2)+1; /* only 1,2,3,4 legal now */
  111366. rangebits=oggpack_read(opb,4);
  111367. for(j=0,k=0;j<info->partitions;j++){
  111368. count+=info->class_dim[info->partitionclass[j]];
  111369. for(;k<count;k++){
  111370. int t=info->postlist[k+2]=oggpack_read(opb,rangebits);
  111371. if(t<0 || t>=(1<<rangebits))
  111372. goto err_out;
  111373. }
  111374. }
  111375. info->postlist[0]=0;
  111376. info->postlist[1]=1<<rangebits;
  111377. return(info);
  111378. err_out:
  111379. floor1_free_info(info);
  111380. return(NULL);
  111381. }
  111382. static int icomp(const void *a,const void *b){
  111383. return(**(int **)a-**(int **)b);
  111384. }
  111385. static vorbis_look_floor *floor1_look(vorbis_dsp_state *vd,
  111386. vorbis_info_floor *in){
  111387. int *sortpointer[VIF_POSIT+2];
  111388. vorbis_info_floor1 *info=(vorbis_info_floor1*)in;
  111389. vorbis_look_floor1 *look=(vorbis_look_floor1*)_ogg_calloc(1,sizeof(*look));
  111390. int i,j,n=0;
  111391. look->vi=info;
  111392. look->n=info->postlist[1];
  111393. /* we drop each position value in-between already decoded values,
  111394. and use linear interpolation to predict each new value past the
  111395. edges. The positions are read in the order of the position
  111396. list... we precompute the bounding positions in the lookup. Of
  111397. course, the neighbors can change (if a position is declined), but
  111398. this is an initial mapping */
  111399. for(i=0;i<info->partitions;i++)n+=info->class_dim[info->partitionclass[i]];
  111400. n+=2;
  111401. look->posts=n;
  111402. /* also store a sorted position index */
  111403. for(i=0;i<n;i++)sortpointer[i]=info->postlist+i;
  111404. qsort(sortpointer,n,sizeof(*sortpointer),icomp);
  111405. /* points from sort order back to range number */
  111406. for(i=0;i<n;i++)look->forward_index[i]=sortpointer[i]-info->postlist;
  111407. /* points from range order to sorted position */
  111408. for(i=0;i<n;i++)look->reverse_index[look->forward_index[i]]=i;
  111409. /* we actually need the post values too */
  111410. for(i=0;i<n;i++)look->sorted_index[i]=info->postlist[look->forward_index[i]];
  111411. /* quantize values to multiplier spec */
  111412. switch(info->mult){
  111413. case 1: /* 1024 -> 256 */
  111414. look->quant_q=256;
  111415. break;
  111416. case 2: /* 1024 -> 128 */
  111417. look->quant_q=128;
  111418. break;
  111419. case 3: /* 1024 -> 86 */
  111420. look->quant_q=86;
  111421. break;
  111422. case 4: /* 1024 -> 64 */
  111423. look->quant_q=64;
  111424. break;
  111425. }
  111426. /* discover our neighbors for decode where we don't use fit flags
  111427. (that would push the neighbors outward) */
  111428. for(i=0;i<n-2;i++){
  111429. int lo=0;
  111430. int hi=1;
  111431. int lx=0;
  111432. int hx=look->n;
  111433. int currentx=info->postlist[i+2];
  111434. for(j=0;j<i+2;j++){
  111435. int x=info->postlist[j];
  111436. if(x>lx && x<currentx){
  111437. lo=j;
  111438. lx=x;
  111439. }
  111440. if(x<hx && x>currentx){
  111441. hi=j;
  111442. hx=x;
  111443. }
  111444. }
  111445. look->loneighbor[i]=lo;
  111446. look->hineighbor[i]=hi;
  111447. }
  111448. return(look);
  111449. }
  111450. static int render_point(int x0,int x1,int y0,int y1,int x){
  111451. y0&=0x7fff; /* mask off flag */
  111452. y1&=0x7fff;
  111453. {
  111454. int dy=y1-y0;
  111455. int adx=x1-x0;
  111456. int ady=abs(dy);
  111457. int err=ady*(x-x0);
  111458. int off=err/adx;
  111459. if(dy<0)return(y0-off);
  111460. return(y0+off);
  111461. }
  111462. }
  111463. static int vorbis_dBquant(const float *x){
  111464. int i= *x*7.3142857f+1023.5f;
  111465. if(i>1023)return(1023);
  111466. if(i<0)return(0);
  111467. return i;
  111468. }
  111469. static float FLOOR1_fromdB_LOOKUP[256]={
  111470. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  111471. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  111472. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  111473. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  111474. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  111475. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  111476. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  111477. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  111478. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  111479. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  111480. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  111481. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  111482. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  111483. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  111484. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  111485. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  111486. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  111487. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  111488. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  111489. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  111490. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  111491. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  111492. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  111493. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  111494. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  111495. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  111496. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  111497. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  111498. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  111499. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  111500. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  111501. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  111502. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  111503. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  111504. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  111505. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  111506. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  111507. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  111508. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  111509. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  111510. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  111511. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  111512. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  111513. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  111514. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  111515. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  111516. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  111517. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  111518. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  111519. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  111520. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  111521. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  111522. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  111523. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  111524. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  111525. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  111526. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  111527. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  111528. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  111529. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  111530. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  111531. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  111532. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  111533. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  111534. };
  111535. static void render_line(int x0,int x1,int y0,int y1,float *d){
  111536. int dy=y1-y0;
  111537. int adx=x1-x0;
  111538. int ady=abs(dy);
  111539. int base=dy/adx;
  111540. int sy=(dy<0?base-1:base+1);
  111541. int x=x0;
  111542. int y=y0;
  111543. int err=0;
  111544. ady-=abs(base*adx);
  111545. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  111546. while(++x<x1){
  111547. err=err+ady;
  111548. if(err>=adx){
  111549. err-=adx;
  111550. y+=sy;
  111551. }else{
  111552. y+=base;
  111553. }
  111554. d[x]*=FLOOR1_fromdB_LOOKUP[y];
  111555. }
  111556. }
  111557. static void render_line0(int x0,int x1,int y0,int y1,int *d){
  111558. int dy=y1-y0;
  111559. int adx=x1-x0;
  111560. int ady=abs(dy);
  111561. int base=dy/adx;
  111562. int sy=(dy<0?base-1:base+1);
  111563. int x=x0;
  111564. int y=y0;
  111565. int err=0;
  111566. ady-=abs(base*adx);
  111567. d[x]=y;
  111568. while(++x<x1){
  111569. err=err+ady;
  111570. if(err>=adx){
  111571. err-=adx;
  111572. y+=sy;
  111573. }else{
  111574. y+=base;
  111575. }
  111576. d[x]=y;
  111577. }
  111578. }
  111579. /* the floor has already been filtered to only include relevant sections */
  111580. static int accumulate_fit(const float *flr,const float *mdct,
  111581. int x0, int x1,lsfit_acc *a,
  111582. int n,vorbis_info_floor1 *info){
  111583. long i;
  111584. 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;
  111585. memset(a,0,sizeof(*a));
  111586. a->x0=x0;
  111587. a->x1=x1;
  111588. if(x1>=n)x1=n-1;
  111589. for(i=x0;i<=x1;i++){
  111590. int quantized=vorbis_dBquant(flr+i);
  111591. if(quantized){
  111592. if(mdct[i]+info->twofitatten>=flr[i]){
  111593. xa += i;
  111594. ya += quantized;
  111595. x2a += i*i;
  111596. y2a += quantized*quantized;
  111597. xya += i*quantized;
  111598. na++;
  111599. }else{
  111600. xb += i;
  111601. yb += quantized;
  111602. x2b += i*i;
  111603. y2b += quantized*quantized;
  111604. xyb += i*quantized;
  111605. nb++;
  111606. }
  111607. }
  111608. }
  111609. xb+=xa;
  111610. yb+=ya;
  111611. x2b+=x2a;
  111612. y2b+=y2a;
  111613. xyb+=xya;
  111614. nb+=na;
  111615. /* weight toward the actually used frequencies if we meet the threshhold */
  111616. {
  111617. int weight=nb*info->twofitweight/(na+1);
  111618. a->xa=xa*weight+xb;
  111619. a->ya=ya*weight+yb;
  111620. a->x2a=x2a*weight+x2b;
  111621. a->y2a=y2a*weight+y2b;
  111622. a->xya=xya*weight+xyb;
  111623. a->an=na*weight+nb;
  111624. }
  111625. return(na);
  111626. }
  111627. static void fit_line(lsfit_acc *a,int fits,int *y0,int *y1){
  111628. long x=0,y=0,x2=0,y2=0,xy=0,an=0,i;
  111629. long x0=a[0].x0;
  111630. long x1=a[fits-1].x1;
  111631. for(i=0;i<fits;i++){
  111632. x+=a[i].xa;
  111633. y+=a[i].ya;
  111634. x2+=a[i].x2a;
  111635. y2+=a[i].y2a;
  111636. xy+=a[i].xya;
  111637. an+=a[i].an;
  111638. }
  111639. if(*y0>=0){
  111640. x+= x0;
  111641. y+= *y0;
  111642. x2+= x0 * x0;
  111643. y2+= *y0 * *y0;
  111644. xy+= *y0 * x0;
  111645. an++;
  111646. }
  111647. if(*y1>=0){
  111648. x+= x1;
  111649. y+= *y1;
  111650. x2+= x1 * x1;
  111651. y2+= *y1 * *y1;
  111652. xy+= *y1 * x1;
  111653. an++;
  111654. }
  111655. if(an){
  111656. /* need 64 bit multiplies, which C doesn't give portably as int */
  111657. double fx=x;
  111658. double fy=y;
  111659. double fx2=x2;
  111660. double fxy=xy;
  111661. double denom=1./(an*fx2-fx*fx);
  111662. double a=(fy*fx2-fxy*fx)*denom;
  111663. double b=(an*fxy-fx*fy)*denom;
  111664. *y0=rint(a+b*x0);
  111665. *y1=rint(a+b*x1);
  111666. /* limit to our range! */
  111667. if(*y0>1023)*y0=1023;
  111668. if(*y1>1023)*y1=1023;
  111669. if(*y0<0)*y0=0;
  111670. if(*y1<0)*y1=0;
  111671. }else{
  111672. *y0=0;
  111673. *y1=0;
  111674. }
  111675. }
  111676. /*static void fit_line_point(lsfit_acc *a,int fits,int *y0,int *y1){
  111677. long y=0;
  111678. int i;
  111679. for(i=0;i<fits && y==0;i++)
  111680. y+=a[i].ya;
  111681. *y0=*y1=y;
  111682. }*/
  111683. static int inspect_error(int x0,int x1,int y0,int y1,const float *mask,
  111684. const float *mdct,
  111685. vorbis_info_floor1 *info){
  111686. int dy=y1-y0;
  111687. int adx=x1-x0;
  111688. int ady=abs(dy);
  111689. int base=dy/adx;
  111690. int sy=(dy<0?base-1:base+1);
  111691. int x=x0;
  111692. int y=y0;
  111693. int err=0;
  111694. int val=vorbis_dBquant(mask+x);
  111695. int mse=0;
  111696. int n=0;
  111697. ady-=abs(base*adx);
  111698. mse=(y-val);
  111699. mse*=mse;
  111700. n++;
  111701. if(mdct[x]+info->twofitatten>=mask[x]){
  111702. if(y+info->maxover<val)return(1);
  111703. if(y-info->maxunder>val)return(1);
  111704. }
  111705. while(++x<x1){
  111706. err=err+ady;
  111707. if(err>=adx){
  111708. err-=adx;
  111709. y+=sy;
  111710. }else{
  111711. y+=base;
  111712. }
  111713. val=vorbis_dBquant(mask+x);
  111714. mse+=((y-val)*(y-val));
  111715. n++;
  111716. if(mdct[x]+info->twofitatten>=mask[x]){
  111717. if(val){
  111718. if(y+info->maxover<val)return(1);
  111719. if(y-info->maxunder>val)return(1);
  111720. }
  111721. }
  111722. }
  111723. if(info->maxover*info->maxover/n>info->maxerr)return(0);
  111724. if(info->maxunder*info->maxunder/n>info->maxerr)return(0);
  111725. if(mse/n>info->maxerr)return(1);
  111726. return(0);
  111727. }
  111728. static int post_Y(int *A,int *B,int pos){
  111729. if(A[pos]<0)
  111730. return B[pos];
  111731. if(B[pos]<0)
  111732. return A[pos];
  111733. return (A[pos]+B[pos])>>1;
  111734. }
  111735. int *floor1_fit(vorbis_block *vb,void *look_,
  111736. const float *logmdct, /* in */
  111737. const float *logmask){
  111738. long i,j;
  111739. vorbis_look_floor1 *look = (vorbis_look_floor1*) look_;
  111740. vorbis_info_floor1 *info=look->vi;
  111741. long n=look->n;
  111742. long posts=look->posts;
  111743. long nonzero=0;
  111744. lsfit_acc fits[VIF_POSIT+1];
  111745. int fit_valueA[VIF_POSIT+2]; /* index by range list position */
  111746. int fit_valueB[VIF_POSIT+2]; /* index by range list position */
  111747. int loneighbor[VIF_POSIT+2]; /* sorted index of range list position (+2) */
  111748. int hineighbor[VIF_POSIT+2];
  111749. int *output=NULL;
  111750. int memo[VIF_POSIT+2];
  111751. for(i=0;i<posts;i++)fit_valueA[i]=-200; /* mark all unused */
  111752. for(i=0;i<posts;i++)fit_valueB[i]=-200; /* mark all unused */
  111753. for(i=0;i<posts;i++)loneighbor[i]=0; /* 0 for the implicit 0 post */
  111754. for(i=0;i<posts;i++)hineighbor[i]=1; /* 1 for the implicit post at n */
  111755. for(i=0;i<posts;i++)memo[i]=-1; /* no neighbor yet */
  111756. /* quantize the relevant floor points and collect them into line fit
  111757. structures (one per minimal division) at the same time */
  111758. if(posts==0){
  111759. nonzero+=accumulate_fit(logmask,logmdct,0,n,fits,n,info);
  111760. }else{
  111761. for(i=0;i<posts-1;i++)
  111762. nonzero+=accumulate_fit(logmask,logmdct,look->sorted_index[i],
  111763. look->sorted_index[i+1],fits+i,
  111764. n,info);
  111765. }
  111766. if(nonzero){
  111767. /* start by fitting the implicit base case.... */
  111768. int y0=-200;
  111769. int y1=-200;
  111770. fit_line(fits,posts-1,&y0,&y1);
  111771. fit_valueA[0]=y0;
  111772. fit_valueB[0]=y0;
  111773. fit_valueB[1]=y1;
  111774. fit_valueA[1]=y1;
  111775. /* Non degenerate case */
  111776. /* start progressive splitting. This is a greedy, non-optimal
  111777. algorithm, but simple and close enough to the best
  111778. answer. */
  111779. for(i=2;i<posts;i++){
  111780. int sortpos=look->reverse_index[i];
  111781. int ln=loneighbor[sortpos];
  111782. int hn=hineighbor[sortpos];
  111783. /* eliminate repeat searches of a particular range with a memo */
  111784. if(memo[ln]!=hn){
  111785. /* haven't performed this error search yet */
  111786. int lsortpos=look->reverse_index[ln];
  111787. int hsortpos=look->reverse_index[hn];
  111788. memo[ln]=hn;
  111789. {
  111790. /* A note: we want to bound/minimize *local*, not global, error */
  111791. int lx=info->postlist[ln];
  111792. int hx=info->postlist[hn];
  111793. int ly=post_Y(fit_valueA,fit_valueB,ln);
  111794. int hy=post_Y(fit_valueA,fit_valueB,hn);
  111795. if(ly==-1 || hy==-1){
  111796. exit(1);
  111797. }
  111798. if(inspect_error(lx,hx,ly,hy,logmask,logmdct,info)){
  111799. /* outside error bounds/begin search area. Split it. */
  111800. int ly0=-200;
  111801. int ly1=-200;
  111802. int hy0=-200;
  111803. int hy1=-200;
  111804. fit_line(fits+lsortpos,sortpos-lsortpos,&ly0,&ly1);
  111805. fit_line(fits+sortpos,hsortpos-sortpos,&hy0,&hy1);
  111806. /* store new edge values */
  111807. fit_valueB[ln]=ly0;
  111808. if(ln==0)fit_valueA[ln]=ly0;
  111809. fit_valueA[i]=ly1;
  111810. fit_valueB[i]=hy0;
  111811. fit_valueA[hn]=hy1;
  111812. if(hn==1)fit_valueB[hn]=hy1;
  111813. if(ly1>=0 || hy0>=0){
  111814. /* store new neighbor values */
  111815. for(j=sortpos-1;j>=0;j--)
  111816. if(hineighbor[j]==hn)
  111817. hineighbor[j]=i;
  111818. else
  111819. break;
  111820. for(j=sortpos+1;j<posts;j++)
  111821. if(loneighbor[j]==ln)
  111822. loneighbor[j]=i;
  111823. else
  111824. break;
  111825. }
  111826. }else{
  111827. fit_valueA[i]=-200;
  111828. fit_valueB[i]=-200;
  111829. }
  111830. }
  111831. }
  111832. }
  111833. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  111834. output[0]=post_Y(fit_valueA,fit_valueB,0);
  111835. output[1]=post_Y(fit_valueA,fit_valueB,1);
  111836. /* fill in posts marked as not using a fit; we will zero
  111837. back out to 'unused' when encoding them so long as curve
  111838. interpolation doesn't force them into use */
  111839. for(i=2;i<posts;i++){
  111840. int ln=look->loneighbor[i-2];
  111841. int hn=look->hineighbor[i-2];
  111842. int x0=info->postlist[ln];
  111843. int x1=info->postlist[hn];
  111844. int y0=output[ln];
  111845. int y1=output[hn];
  111846. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  111847. int vx=post_Y(fit_valueA,fit_valueB,i);
  111848. if(vx>=0 && predicted!=vx){
  111849. output[i]=vx;
  111850. }else{
  111851. output[i]= predicted|0x8000;
  111852. }
  111853. }
  111854. }
  111855. return(output);
  111856. }
  111857. int *floor1_interpolate_fit(vorbis_block *vb,void *look_,
  111858. int *A,int *B,
  111859. int del){
  111860. long i;
  111861. vorbis_look_floor1* look = (vorbis_look_floor1*) look_;
  111862. long posts=look->posts;
  111863. int *output=NULL;
  111864. if(A && B){
  111865. output=(int*)_vorbis_block_alloc(vb,sizeof(*output)*posts);
  111866. for(i=0;i<posts;i++){
  111867. output[i]=((65536-del)*(A[i]&0x7fff)+del*(B[i]&0x7fff)+32768)>>16;
  111868. if(A[i]&0x8000 && B[i]&0x8000)output[i]|=0x8000;
  111869. }
  111870. }
  111871. return(output);
  111872. }
  111873. int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  111874. void*look_,
  111875. int *post,int *ilogmask){
  111876. long i,j;
  111877. vorbis_look_floor1 *look = (vorbis_look_floor1 *) look_;
  111878. vorbis_info_floor1 *info=look->vi;
  111879. long posts=look->posts;
  111880. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  111881. int out[VIF_POSIT+2];
  111882. static_codebook **sbooks=ci->book_param;
  111883. codebook *books=ci->fullbooks;
  111884. static long seq=0;
  111885. /* quantize values to multiplier spec */
  111886. if(post){
  111887. for(i=0;i<posts;i++){
  111888. int val=post[i]&0x7fff;
  111889. switch(info->mult){
  111890. case 1: /* 1024 -> 256 */
  111891. val>>=2;
  111892. break;
  111893. case 2: /* 1024 -> 128 */
  111894. val>>=3;
  111895. break;
  111896. case 3: /* 1024 -> 86 */
  111897. val/=12;
  111898. break;
  111899. case 4: /* 1024 -> 64 */
  111900. val>>=4;
  111901. break;
  111902. }
  111903. post[i]=val | (post[i]&0x8000);
  111904. }
  111905. out[0]=post[0];
  111906. out[1]=post[1];
  111907. /* find prediction values for each post and subtract them */
  111908. for(i=2;i<posts;i++){
  111909. int ln=look->loneighbor[i-2];
  111910. int hn=look->hineighbor[i-2];
  111911. int x0=info->postlist[ln];
  111912. int x1=info->postlist[hn];
  111913. int y0=post[ln];
  111914. int y1=post[hn];
  111915. int predicted=render_point(x0,x1,y0,y1,info->postlist[i]);
  111916. if((post[i]&0x8000) || (predicted==post[i])){
  111917. post[i]=predicted|0x8000; /* in case there was roundoff jitter
  111918. in interpolation */
  111919. out[i]=0;
  111920. }else{
  111921. int headroom=(look->quant_q-predicted<predicted?
  111922. look->quant_q-predicted:predicted);
  111923. int val=post[i]-predicted;
  111924. /* at this point the 'deviation' value is in the range +/- max
  111925. range, but the real, unique range can always be mapped to
  111926. only [0-maxrange). So we want to wrap the deviation into
  111927. this limited range, but do it in the way that least screws
  111928. an essentially gaussian probability distribution. */
  111929. if(val<0)
  111930. if(val<-headroom)
  111931. val=headroom-val-1;
  111932. else
  111933. val=-1-(val<<1);
  111934. else
  111935. if(val>=headroom)
  111936. val= val+headroom;
  111937. else
  111938. val<<=1;
  111939. out[i]=val;
  111940. post[ln]&=0x7fff;
  111941. post[hn]&=0x7fff;
  111942. }
  111943. }
  111944. /* we have everything we need. pack it out */
  111945. /* mark nontrivial floor */
  111946. oggpack_write(opb,1,1);
  111947. /* beginning/end post */
  111948. look->frames++;
  111949. look->postbits+=ilog(look->quant_q-1)*2;
  111950. oggpack_write(opb,out[0],ilog(look->quant_q-1));
  111951. oggpack_write(opb,out[1],ilog(look->quant_q-1));
  111952. /* partition by partition */
  111953. for(i=0,j=2;i<info->partitions;i++){
  111954. int classx=info->partitionclass[i];
  111955. int cdim=info->class_dim[classx];
  111956. int csubbits=info->class_subs[classx];
  111957. int csub=1<<csubbits;
  111958. int bookas[8]={0,0,0,0,0,0,0,0};
  111959. int cval=0;
  111960. int cshift=0;
  111961. int k,l;
  111962. /* generate the partition's first stage cascade value */
  111963. if(csubbits){
  111964. int maxval[8];
  111965. for(k=0;k<csub;k++){
  111966. int booknum=info->class_subbook[classx][k];
  111967. if(booknum<0){
  111968. maxval[k]=1;
  111969. }else{
  111970. maxval[k]=sbooks[info->class_subbook[classx][k]]->entries;
  111971. }
  111972. }
  111973. for(k=0;k<cdim;k++){
  111974. for(l=0;l<csub;l++){
  111975. int val=out[j+k];
  111976. if(val<maxval[l]){
  111977. bookas[k]=l;
  111978. break;
  111979. }
  111980. }
  111981. cval|= bookas[k]<<cshift;
  111982. cshift+=csubbits;
  111983. }
  111984. /* write it */
  111985. look->phrasebits+=
  111986. vorbis_book_encode(books+info->class_book[classx],cval,opb);
  111987. #ifdef TRAIN_FLOOR1
  111988. {
  111989. FILE *of;
  111990. char buffer[80];
  111991. sprintf(buffer,"line_%dx%ld_class%d.vqd",
  111992. vb->pcmend/2,posts-2,class);
  111993. of=fopen(buffer,"a");
  111994. fprintf(of,"%d\n",cval);
  111995. fclose(of);
  111996. }
  111997. #endif
  111998. }
  111999. /* write post values */
  112000. for(k=0;k<cdim;k++){
  112001. int book=info->class_subbook[classx][bookas[k]];
  112002. if(book>=0){
  112003. /* hack to allow training with 'bad' books */
  112004. if(out[j+k]<(books+book)->entries)
  112005. look->postbits+=vorbis_book_encode(books+book,
  112006. out[j+k],opb);
  112007. /*else
  112008. fprintf(stderr,"+!");*/
  112009. #ifdef TRAIN_FLOOR1
  112010. {
  112011. FILE *of;
  112012. char buffer[80];
  112013. sprintf(buffer,"line_%dx%ld_%dsub%d.vqd",
  112014. vb->pcmend/2,posts-2,class,bookas[k]);
  112015. of=fopen(buffer,"a");
  112016. fprintf(of,"%d\n",out[j+k]);
  112017. fclose(of);
  112018. }
  112019. #endif
  112020. }
  112021. }
  112022. j+=cdim;
  112023. }
  112024. {
  112025. /* generate quantized floor equivalent to what we'd unpack in decode */
  112026. /* render the lines */
  112027. int hx=0;
  112028. int lx=0;
  112029. int ly=post[0]*info->mult;
  112030. for(j=1;j<look->posts;j++){
  112031. int current=look->forward_index[j];
  112032. int hy=post[current]&0x7fff;
  112033. if(hy==post[current]){
  112034. hy*=info->mult;
  112035. hx=info->postlist[current];
  112036. render_line0(lx,hx,ly,hy,ilogmask);
  112037. lx=hx;
  112038. ly=hy;
  112039. }
  112040. }
  112041. for(j=hx;j<vb->pcmend/2;j++)ilogmask[j]=ly; /* be certain */
  112042. seq++;
  112043. return(1);
  112044. }
  112045. }else{
  112046. oggpack_write(opb,0,1);
  112047. memset(ilogmask,0,vb->pcmend/2*sizeof(*ilogmask));
  112048. seq++;
  112049. return(0);
  112050. }
  112051. }
  112052. static void *floor1_inverse1(vorbis_block *vb,vorbis_look_floor *in){
  112053. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  112054. vorbis_info_floor1 *info=look->vi;
  112055. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112056. int i,j,k;
  112057. codebook *books=ci->fullbooks;
  112058. /* unpack wrapped/predicted values from stream */
  112059. if(oggpack_read(&vb->opb,1)==1){
  112060. int *fit_value=(int*)_vorbis_block_alloc(vb,(look->posts)*sizeof(*fit_value));
  112061. fit_value[0]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  112062. fit_value[1]=oggpack_read(&vb->opb,ilog(look->quant_q-1));
  112063. /* partition by partition */
  112064. for(i=0,j=2;i<info->partitions;i++){
  112065. int classx=info->partitionclass[i];
  112066. int cdim=info->class_dim[classx];
  112067. int csubbits=info->class_subs[classx];
  112068. int csub=1<<csubbits;
  112069. int cval=0;
  112070. /* decode the partition's first stage cascade value */
  112071. if(csubbits){
  112072. cval=vorbis_book_decode(books+info->class_book[classx],&vb->opb);
  112073. if(cval==-1)goto eop;
  112074. }
  112075. for(k=0;k<cdim;k++){
  112076. int book=info->class_subbook[classx][cval&(csub-1)];
  112077. cval>>=csubbits;
  112078. if(book>=0){
  112079. if((fit_value[j+k]=vorbis_book_decode(books+book,&vb->opb))==-1)
  112080. goto eop;
  112081. }else{
  112082. fit_value[j+k]=0;
  112083. }
  112084. }
  112085. j+=cdim;
  112086. }
  112087. /* unwrap positive values and reconsitute via linear interpolation */
  112088. for(i=2;i<look->posts;i++){
  112089. int predicted=render_point(info->postlist[look->loneighbor[i-2]],
  112090. info->postlist[look->hineighbor[i-2]],
  112091. fit_value[look->loneighbor[i-2]],
  112092. fit_value[look->hineighbor[i-2]],
  112093. info->postlist[i]);
  112094. int hiroom=look->quant_q-predicted;
  112095. int loroom=predicted;
  112096. int room=(hiroom<loroom?hiroom:loroom)<<1;
  112097. int val=fit_value[i];
  112098. if(val){
  112099. if(val>=room){
  112100. if(hiroom>loroom){
  112101. val = val-loroom;
  112102. }else{
  112103. val = -1-(val-hiroom);
  112104. }
  112105. }else{
  112106. if(val&1){
  112107. val= -((val+1)>>1);
  112108. }else{
  112109. val>>=1;
  112110. }
  112111. }
  112112. fit_value[i]=val+predicted;
  112113. fit_value[look->loneighbor[i-2]]&=0x7fff;
  112114. fit_value[look->hineighbor[i-2]]&=0x7fff;
  112115. }else{
  112116. fit_value[i]=predicted|0x8000;
  112117. }
  112118. }
  112119. return(fit_value);
  112120. }
  112121. eop:
  112122. return(NULL);
  112123. }
  112124. static int floor1_inverse2(vorbis_block *vb,vorbis_look_floor *in,void *memo,
  112125. float *out){
  112126. vorbis_look_floor1 *look=(vorbis_look_floor1 *)in;
  112127. vorbis_info_floor1 *info=look->vi;
  112128. codec_setup_info *ci=(codec_setup_info*)vb->vd->vi->codec_setup;
  112129. int n=ci->blocksizes[vb->W]/2;
  112130. int j;
  112131. if(memo){
  112132. /* render the lines */
  112133. int *fit_value=(int *)memo;
  112134. int hx=0;
  112135. int lx=0;
  112136. int ly=fit_value[0]*info->mult;
  112137. for(j=1;j<look->posts;j++){
  112138. int current=look->forward_index[j];
  112139. int hy=fit_value[current]&0x7fff;
  112140. if(hy==fit_value[current]){
  112141. hy*=info->mult;
  112142. hx=info->postlist[current];
  112143. render_line(lx,hx,ly,hy,out);
  112144. lx=hx;
  112145. ly=hy;
  112146. }
  112147. }
  112148. for(j=hx;j<n;j++)out[j]*=FLOOR1_fromdB_LOOKUP[ly]; /* be certain */
  112149. return(1);
  112150. }
  112151. memset(out,0,sizeof(*out)*n);
  112152. return(0);
  112153. }
  112154. /* export hooks */
  112155. vorbis_func_floor floor1_exportbundle={
  112156. &floor1_pack,&floor1_unpack,&floor1_look,&floor1_free_info,
  112157. &floor1_free_look,&floor1_inverse1,&floor1_inverse2
  112158. };
  112159. #endif
  112160. /********* End of inlined file: floor1.c *********/
  112161. /********* Start of inlined file: info.c *********/
  112162. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112163. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112164. // tasks..
  112165. /********* Start of inlined file: juce_Config.h *********/
  112166. #ifndef __JUCE_CONFIG_JUCEHEADER__
  112167. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  112168. /*
  112169. This file contains macros that enable/disable various JUCE features.
  112170. */
  112171. /** The name of the namespace that all Juce classes and functions will be
  112172. put inside. If this is not defined, no namespace will be used.
  112173. */
  112174. #ifndef JUCE_NAMESPACE
  112175. #define JUCE_NAMESPACE juce
  112176. #endif
  112177. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  112178. but if you define this value, you can override this can force it to be true or
  112179. false.
  112180. */
  112181. #ifndef JUCE_FORCE_DEBUG
  112182. //#define JUCE_FORCE_DEBUG 1
  112183. #endif
  112184. /** If this flag is enabled, the the jassert and jassertfalse macros will
  112185. always use Logger::writeToLog() to write a message when an assertion happens.
  112186. Enabling it will also leave this turned on in release builds. When it's disabled,
  112187. however, the jassert and jassertfalse macros will not be compiled in a
  112188. release build.
  112189. @see jassert, jassertfalse, Logger
  112190. */
  112191. #ifndef JUCE_LOG_ASSERTIONS
  112192. // #define JUCE_LOG_ASSERTIONS 1
  112193. #endif
  112194. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  112195. which the ASIOAudioIODevice class can't be built. See the comments in the
  112196. ASIOAudioIODevice class's header file for more info about this.
  112197. (This only affects a Win32 build)
  112198. */
  112199. #ifndef JUCE_ASIO
  112200. #define JUCE_ASIO 1
  112201. #endif
  112202. /** Comment out this macro to disable building of ALSA device support on Linux.
  112203. */
  112204. #ifndef JUCE_ALSA
  112205. #define JUCE_ALSA 1
  112206. #endif
  112207. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  112208. have the SDK installed.
  112209. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  112210. classes will be unavailable.
  112211. On Windows, if you enable this, you'll need to have the QuickTime SDK
  112212. installed, and its header files will need to be on your include path.
  112213. */
  112214. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  112215. #define JUCE_QUICKTIME 1
  112216. #endif
  112217. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  112218. have the appropriate headers and libraries available. If it's not enabled, the
  112219. OpenGLComponent class will be unavailable.
  112220. */
  112221. #ifndef JUCE_OPENGL
  112222. #define JUCE_OPENGL 1
  112223. #endif
  112224. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  112225. If you're not going to need either of these formats, turn off the flags to
  112226. avoid bloating your codebase with them.
  112227. */
  112228. #ifndef JUCE_USE_FLAC
  112229. #define JUCE_USE_FLAC 1
  112230. #endif
  112231. #ifndef JUCE_USE_OGGVORBIS
  112232. #define JUCE_USE_OGGVORBIS 1
  112233. #endif
  112234. /** This flag lets you enable support for CD-burning. You might want to disable
  112235. it to build without the MS SDK under windows.
  112236. */
  112237. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  112238. #define JUCE_USE_CDBURNER 1
  112239. #endif
  112240. /** Enabling this macro means that all regions that get repainted will have a coloured
  112241. line drawn around them.
  112242. This is handy if you're trying to optimise drawing, because it lets you easily see
  112243. when anything is being repainted unnecessarily.
  112244. */
  112245. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  112246. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  112247. #endif
  112248. /** Enable this under Linux to use Xinerama for multi-monitor support.
  112249. */
  112250. #ifndef JUCE_USE_XINERAMA
  112251. #define JUCE_USE_XINERAMA 1
  112252. #endif
  112253. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  112254. */
  112255. #ifndef JUCE_USE_XSHM
  112256. #define JUCE_USE_XSHM 1
  112257. #endif
  112258. /** Enabling this builds support for VST audio plugins.
  112259. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  112260. */
  112261. #ifndef JUCE_PLUGINHOST_VST
  112262. // #define JUCE_PLUGINHOST_VST 1
  112263. #endif
  112264. /** Enabling this builds support for AudioUnit audio plugins.
  112265. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  112266. */
  112267. #ifndef JUCE_PLUGINHOST_AU
  112268. // #define JUCE_PLUGINHOST_AU 1
  112269. #endif
  112270. /** Disabling this will avoid linking to any UI code. This is handy for
  112271. writing command-line utilities, e.g. on linux boxes which don't have some
  112272. of the UI libraries installed.
  112273. (On mac and windows, this won't generally make much difference to the build).
  112274. */
  112275. #ifndef JUCE_BUILD_GUI_CLASSES
  112276. #define JUCE_BUILD_GUI_CLASSES 1
  112277. #endif
  112278. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  112279. */
  112280. #ifndef JUCE_WEB_BROWSER
  112281. #define JUCE_WEB_BROWSER 1
  112282. #endif
  112283. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  112284. codebase - you might need to use this if you're linking to some of these libraries
  112285. yourself.
  112286. */
  112287. #ifndef JUCE_INCLUDE_ZLIB_CODE
  112288. #define JUCE_INCLUDE_ZLIB_CODE 1
  112289. #endif
  112290. #ifndef JUCE_INCLUDE_FLAC_CODE
  112291. #define JUCE_INCLUDE_FLAC_CODE 1
  112292. #endif
  112293. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  112294. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  112295. #endif
  112296. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  112297. #define JUCE_INCLUDE_PNGLIB_CODE 1
  112298. #endif
  112299. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  112300. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  112301. #endif
  112302. /** Enable this to add extra memory-leak info to the new and delete operators.
  112303. (Currently, this only affects Windows builds in debug mode).
  112304. */
  112305. #ifndef JUCE_CHECK_MEMORY_LEAKS
  112306. #define JUCE_CHECK_MEMORY_LEAKS 1
  112307. #endif
  112308. /** Enable this to turn on juce's internal catching of exceptions.
  112309. Turning it off will avoid any exception catching. With it on, all exceptions
  112310. are passed to the JUCEApplication::unhandledException() callback for logging.
  112311. */
  112312. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  112313. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  112314. #endif
  112315. /** If this macro is set, the Juce String class will use unicode as its
  112316. internal representation. If it isn't set, it'll use ANSI.
  112317. */
  112318. #ifndef JUCE_STRINGS_ARE_UNICODE
  112319. #define JUCE_STRINGS_ARE_UNICODE 1
  112320. #endif
  112321. #endif
  112322. /********* End of inlined file: juce_Config.h *********/
  112323. #ifdef _MSC_VER
  112324. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112325. #endif
  112326. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112327. #if JUCE_USE_OGGVORBIS
  112328. /* general handling of the header and the vorbis_info structure (and
  112329. substructures) */
  112330. #include <stdlib.h>
  112331. #include <string.h>
  112332. #include <ctype.h>
  112333. static void _v_writestring(oggpack_buffer *o,char *s, int bytes){
  112334. while(bytes--){
  112335. oggpack_write(o,*s++,8);
  112336. }
  112337. }
  112338. static void _v_readstring(oggpack_buffer *o,char *buf,int bytes){
  112339. while(bytes--){
  112340. *buf++=oggpack_read(o,8);
  112341. }
  112342. }
  112343. void vorbis_comment_init(vorbis_comment *vc){
  112344. memset(vc,0,sizeof(*vc));
  112345. }
  112346. void vorbis_comment_add(vorbis_comment *vc,char *comment){
  112347. vc->user_comments=(char**)_ogg_realloc(vc->user_comments,
  112348. (vc->comments+2)*sizeof(*vc->user_comments));
  112349. vc->comment_lengths=(int*)_ogg_realloc(vc->comment_lengths,
  112350. (vc->comments+2)*sizeof(*vc->comment_lengths));
  112351. vc->comment_lengths[vc->comments]=strlen(comment);
  112352. vc->user_comments[vc->comments]=(char*)_ogg_malloc(vc->comment_lengths[vc->comments]+1);
  112353. strcpy(vc->user_comments[vc->comments], comment);
  112354. vc->comments++;
  112355. vc->user_comments[vc->comments]=NULL;
  112356. }
  112357. void vorbis_comment_add_tag(vorbis_comment *vc, char *tag, char *contents){
  112358. char *comment=(char*)alloca(strlen(tag)+strlen(contents)+2); /* +2 for = and \0 */
  112359. strcpy(comment, tag);
  112360. strcat(comment, "=");
  112361. strcat(comment, contents);
  112362. vorbis_comment_add(vc, comment);
  112363. }
  112364. /* This is more or less the same as strncasecmp - but that doesn't exist
  112365. * everywhere, and this is a fairly trivial function, so we include it */
  112366. static int tagcompare(const char *s1, const char *s2, int n){
  112367. int c=0;
  112368. while(c < n){
  112369. if(toupper(s1[c]) != toupper(s2[c]))
  112370. return !0;
  112371. c++;
  112372. }
  112373. return 0;
  112374. }
  112375. char *vorbis_comment_query(vorbis_comment *vc, char *tag, int count){
  112376. long i;
  112377. int found = 0;
  112378. int taglen = strlen(tag)+1; /* +1 for the = we append */
  112379. char *fulltag = (char*)alloca(taglen+ 1);
  112380. strcpy(fulltag, tag);
  112381. strcat(fulltag, "=");
  112382. for(i=0;i<vc->comments;i++){
  112383. if(!tagcompare(vc->user_comments[i], fulltag, taglen)){
  112384. if(count == found)
  112385. /* We return a pointer to the data, not a copy */
  112386. return vc->user_comments[i] + taglen;
  112387. else
  112388. found++;
  112389. }
  112390. }
  112391. return NULL; /* didn't find anything */
  112392. }
  112393. int vorbis_comment_query_count(vorbis_comment *vc, char *tag){
  112394. int i,count=0;
  112395. int taglen = strlen(tag)+1; /* +1 for the = we append */
  112396. char *fulltag = (char*)alloca(taglen+1);
  112397. strcpy(fulltag,tag);
  112398. strcat(fulltag, "=");
  112399. for(i=0;i<vc->comments;i++){
  112400. if(!tagcompare(vc->user_comments[i], fulltag, taglen))
  112401. count++;
  112402. }
  112403. return count;
  112404. }
  112405. void vorbis_comment_clear(vorbis_comment *vc){
  112406. if(vc){
  112407. long i;
  112408. for(i=0;i<vc->comments;i++)
  112409. if(vc->user_comments[i])_ogg_free(vc->user_comments[i]);
  112410. if(vc->user_comments)_ogg_free(vc->user_comments);
  112411. if(vc->comment_lengths)_ogg_free(vc->comment_lengths);
  112412. if(vc->vendor)_ogg_free(vc->vendor);
  112413. }
  112414. memset(vc,0,sizeof(*vc));
  112415. }
  112416. /* blocksize 0 is guaranteed to be short, 1 is guarantted to be long.
  112417. They may be equal, but short will never ge greater than long */
  112418. int vorbis_info_blocksize(vorbis_info *vi,int zo){
  112419. codec_setup_info *ci = (codec_setup_info*)vi->codec_setup;
  112420. return ci ? ci->blocksizes[zo] : -1;
  112421. }
  112422. /* used by synthesis, which has a full, alloced vi */
  112423. void vorbis_info_init(vorbis_info *vi){
  112424. memset(vi,0,sizeof(*vi));
  112425. vi->codec_setup=_ogg_calloc(1,sizeof(codec_setup_info));
  112426. }
  112427. void vorbis_info_clear(vorbis_info *vi){
  112428. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112429. int i;
  112430. if(ci){
  112431. for(i=0;i<ci->modes;i++)
  112432. if(ci->mode_param[i])_ogg_free(ci->mode_param[i]);
  112433. for(i=0;i<ci->maps;i++) /* unpack does the range checking */
  112434. _mapping_P[ci->map_type[i]]->free_info(ci->map_param[i]);
  112435. for(i=0;i<ci->floors;i++) /* unpack does the range checking */
  112436. _floor_P[ci->floor_type[i]]->free_info(ci->floor_param[i]);
  112437. for(i=0;i<ci->residues;i++) /* unpack does the range checking */
  112438. _residue_P[ci->residue_type[i]]->free_info(ci->residue_param[i]);
  112439. for(i=0;i<ci->books;i++){
  112440. if(ci->book_param[i]){
  112441. /* knows if the book was not alloced */
  112442. vorbis_staticbook_destroy(ci->book_param[i]);
  112443. }
  112444. if(ci->fullbooks)
  112445. vorbis_book_clear(ci->fullbooks+i);
  112446. }
  112447. if(ci->fullbooks)
  112448. _ogg_free(ci->fullbooks);
  112449. for(i=0;i<ci->psys;i++)
  112450. _vi_psy_free(ci->psy_param[i]);
  112451. _ogg_free(ci);
  112452. }
  112453. memset(vi,0,sizeof(*vi));
  112454. }
  112455. /* Header packing/unpacking ********************************************/
  112456. static int _vorbis_unpack_info(vorbis_info *vi,oggpack_buffer *opb){
  112457. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112458. if(!ci)return(OV_EFAULT);
  112459. vi->version=oggpack_read(opb,32);
  112460. if(vi->version!=0)return(OV_EVERSION);
  112461. vi->channels=oggpack_read(opb,8);
  112462. vi->rate=oggpack_read(opb,32);
  112463. vi->bitrate_upper=oggpack_read(opb,32);
  112464. vi->bitrate_nominal=oggpack_read(opb,32);
  112465. vi->bitrate_lower=oggpack_read(opb,32);
  112466. ci->blocksizes[0]=1<<oggpack_read(opb,4);
  112467. ci->blocksizes[1]=1<<oggpack_read(opb,4);
  112468. if(vi->rate<1)goto err_out;
  112469. if(vi->channels<1)goto err_out;
  112470. if(ci->blocksizes[0]<8)goto err_out;
  112471. if(ci->blocksizes[1]<ci->blocksizes[0])goto err_out;
  112472. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  112473. return(0);
  112474. err_out:
  112475. vorbis_info_clear(vi);
  112476. return(OV_EBADHEADER);
  112477. }
  112478. static int _vorbis_unpack_comment(vorbis_comment *vc,oggpack_buffer *opb){
  112479. int i;
  112480. int vendorlen=oggpack_read(opb,32);
  112481. if(vendorlen<0)goto err_out;
  112482. vc->vendor=(char*)_ogg_calloc(vendorlen+1,1);
  112483. _v_readstring(opb,vc->vendor,vendorlen);
  112484. vc->comments=oggpack_read(opb,32);
  112485. if(vc->comments<0)goto err_out;
  112486. vc->user_comments=(char**)_ogg_calloc(vc->comments+1,sizeof(*vc->user_comments));
  112487. vc->comment_lengths=(int*)_ogg_calloc(vc->comments+1, sizeof(*vc->comment_lengths));
  112488. for(i=0;i<vc->comments;i++){
  112489. int len=oggpack_read(opb,32);
  112490. if(len<0)goto err_out;
  112491. vc->comment_lengths[i]=len;
  112492. vc->user_comments[i]=(char*)_ogg_calloc(len+1,1);
  112493. _v_readstring(opb,vc->user_comments[i],len);
  112494. }
  112495. if(oggpack_read(opb,1)!=1)goto err_out; /* EOP check */
  112496. return(0);
  112497. err_out:
  112498. vorbis_comment_clear(vc);
  112499. return(OV_EBADHEADER);
  112500. }
  112501. /* all of the real encoding details are here. The modes, books,
  112502. everything */
  112503. static int _vorbis_unpack_books(vorbis_info *vi,oggpack_buffer *opb){
  112504. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112505. int i;
  112506. if(!ci)return(OV_EFAULT);
  112507. /* codebooks */
  112508. ci->books=oggpack_read(opb,8)+1;
  112509. /*ci->book_param=_ogg_calloc(ci->books,sizeof(*ci->book_param));*/
  112510. for(i=0;i<ci->books;i++){
  112511. ci->book_param[i]=(static_codebook*)_ogg_calloc(1,sizeof(*ci->book_param[i]));
  112512. if(vorbis_staticbook_unpack(opb,ci->book_param[i]))goto err_out;
  112513. }
  112514. /* time backend settings; hooks are unused */
  112515. {
  112516. int times=oggpack_read(opb,6)+1;
  112517. for(i=0;i<times;i++){
  112518. int test=oggpack_read(opb,16);
  112519. if(test<0 || test>=VI_TIMEB)goto err_out;
  112520. }
  112521. }
  112522. /* floor backend settings */
  112523. ci->floors=oggpack_read(opb,6)+1;
  112524. /*ci->floor_type=_ogg_malloc(ci->floors*sizeof(*ci->floor_type));*/
  112525. /*ci->floor_param=_ogg_calloc(ci->floors,sizeof(void *));*/
  112526. for(i=0;i<ci->floors;i++){
  112527. ci->floor_type[i]=oggpack_read(opb,16);
  112528. if(ci->floor_type[i]<0 || ci->floor_type[i]>=VI_FLOORB)goto err_out;
  112529. ci->floor_param[i]=_floor_P[ci->floor_type[i]]->unpack(vi,opb);
  112530. if(!ci->floor_param[i])goto err_out;
  112531. }
  112532. /* residue backend settings */
  112533. ci->residues=oggpack_read(opb,6)+1;
  112534. /*ci->residue_type=_ogg_malloc(ci->residues*sizeof(*ci->residue_type));*/
  112535. /*ci->residue_param=_ogg_calloc(ci->residues,sizeof(void *));*/
  112536. for(i=0;i<ci->residues;i++){
  112537. ci->residue_type[i]=oggpack_read(opb,16);
  112538. if(ci->residue_type[i]<0 || ci->residue_type[i]>=VI_RESB)goto err_out;
  112539. ci->residue_param[i]=_residue_P[ci->residue_type[i]]->unpack(vi,opb);
  112540. if(!ci->residue_param[i])goto err_out;
  112541. }
  112542. /* map backend settings */
  112543. ci->maps=oggpack_read(opb,6)+1;
  112544. /*ci->map_type=_ogg_malloc(ci->maps*sizeof(*ci->map_type));*/
  112545. /*ci->map_param=_ogg_calloc(ci->maps,sizeof(void *));*/
  112546. for(i=0;i<ci->maps;i++){
  112547. ci->map_type[i]=oggpack_read(opb,16);
  112548. if(ci->map_type[i]<0 || ci->map_type[i]>=VI_MAPB)goto err_out;
  112549. ci->map_param[i]=_mapping_P[ci->map_type[i]]->unpack(vi,opb);
  112550. if(!ci->map_param[i])goto err_out;
  112551. }
  112552. /* mode settings */
  112553. ci->modes=oggpack_read(opb,6)+1;
  112554. /*vi->mode_param=_ogg_calloc(vi->modes,sizeof(void *));*/
  112555. for(i=0;i<ci->modes;i++){
  112556. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*ci->mode_param[i]));
  112557. ci->mode_param[i]->blockflag=oggpack_read(opb,1);
  112558. ci->mode_param[i]->windowtype=oggpack_read(opb,16);
  112559. ci->mode_param[i]->transformtype=oggpack_read(opb,16);
  112560. ci->mode_param[i]->mapping=oggpack_read(opb,8);
  112561. if(ci->mode_param[i]->windowtype>=VI_WINDOWB)goto err_out;
  112562. if(ci->mode_param[i]->transformtype>=VI_WINDOWB)goto err_out;
  112563. if(ci->mode_param[i]->mapping>=ci->maps)goto err_out;
  112564. }
  112565. if(oggpack_read(opb,1)!=1)goto err_out; /* top level EOP check */
  112566. return(0);
  112567. err_out:
  112568. vorbis_info_clear(vi);
  112569. return(OV_EBADHEADER);
  112570. }
  112571. /* The Vorbis header is in three packets; the initial small packet in
  112572. the first page that identifies basic parameters, a second packet
  112573. with bitstream comments and a third packet that holds the
  112574. codebook. */
  112575. int vorbis_synthesis_headerin(vorbis_info *vi,vorbis_comment *vc,ogg_packet *op){
  112576. oggpack_buffer opb;
  112577. if(op){
  112578. oggpack_readinit(&opb,op->packet,op->bytes);
  112579. /* Which of the three types of header is this? */
  112580. /* Also verify header-ness, vorbis */
  112581. {
  112582. char buffer[6];
  112583. int packtype=oggpack_read(&opb,8);
  112584. memset(buffer,0,6);
  112585. _v_readstring(&opb,buffer,6);
  112586. if(memcmp(buffer,"vorbis",6)){
  112587. /* not a vorbis header */
  112588. return(OV_ENOTVORBIS);
  112589. }
  112590. switch(packtype){
  112591. case 0x01: /* least significant *bit* is read first */
  112592. if(!op->b_o_s){
  112593. /* Not the initial packet */
  112594. return(OV_EBADHEADER);
  112595. }
  112596. if(vi->rate!=0){
  112597. /* previously initialized info header */
  112598. return(OV_EBADHEADER);
  112599. }
  112600. return(_vorbis_unpack_info(vi,&opb));
  112601. case 0x03: /* least significant *bit* is read first */
  112602. if(vi->rate==0){
  112603. /* um... we didn't get the initial header */
  112604. return(OV_EBADHEADER);
  112605. }
  112606. return(_vorbis_unpack_comment(vc,&opb));
  112607. case 0x05: /* least significant *bit* is read first */
  112608. if(vi->rate==0 || vc->vendor==NULL){
  112609. /* um... we didn;t get the initial header or comments yet */
  112610. return(OV_EBADHEADER);
  112611. }
  112612. return(_vorbis_unpack_books(vi,&opb));
  112613. default:
  112614. /* Not a valid vorbis header type */
  112615. return(OV_EBADHEADER);
  112616. break;
  112617. }
  112618. }
  112619. }
  112620. return(OV_EBADHEADER);
  112621. }
  112622. /* pack side **********************************************************/
  112623. static int _vorbis_pack_info(oggpack_buffer *opb,vorbis_info *vi){
  112624. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112625. if(!ci)return(OV_EFAULT);
  112626. /* preamble */
  112627. oggpack_write(opb,0x01,8);
  112628. _v_writestring(opb,"vorbis", 6);
  112629. /* basic information about the stream */
  112630. oggpack_write(opb,0x00,32);
  112631. oggpack_write(opb,vi->channels,8);
  112632. oggpack_write(opb,vi->rate,32);
  112633. oggpack_write(opb,vi->bitrate_upper,32);
  112634. oggpack_write(opb,vi->bitrate_nominal,32);
  112635. oggpack_write(opb,vi->bitrate_lower,32);
  112636. oggpack_write(opb,ilog2(ci->blocksizes[0]),4);
  112637. oggpack_write(opb,ilog2(ci->blocksizes[1]),4);
  112638. oggpack_write(opb,1,1);
  112639. return(0);
  112640. }
  112641. static int _vorbis_pack_comment(oggpack_buffer *opb,vorbis_comment *vc){
  112642. char temp[]="Xiph.Org libVorbis I 20050304";
  112643. int bytes = strlen(temp);
  112644. /* preamble */
  112645. oggpack_write(opb,0x03,8);
  112646. _v_writestring(opb,"vorbis", 6);
  112647. /* vendor */
  112648. oggpack_write(opb,bytes,32);
  112649. _v_writestring(opb,temp, bytes);
  112650. /* comments */
  112651. oggpack_write(opb,vc->comments,32);
  112652. if(vc->comments){
  112653. int i;
  112654. for(i=0;i<vc->comments;i++){
  112655. if(vc->user_comments[i]){
  112656. oggpack_write(opb,vc->comment_lengths[i],32);
  112657. _v_writestring(opb,vc->user_comments[i], vc->comment_lengths[i]);
  112658. }else{
  112659. oggpack_write(opb,0,32);
  112660. }
  112661. }
  112662. }
  112663. oggpack_write(opb,1,1);
  112664. return(0);
  112665. }
  112666. static int _vorbis_pack_books(oggpack_buffer *opb,vorbis_info *vi){
  112667. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  112668. int i;
  112669. if(!ci)return(OV_EFAULT);
  112670. oggpack_write(opb,0x05,8);
  112671. _v_writestring(opb,"vorbis", 6);
  112672. /* books */
  112673. oggpack_write(opb,ci->books-1,8);
  112674. for(i=0;i<ci->books;i++)
  112675. if(vorbis_staticbook_pack(ci->book_param[i],opb))goto err_out;
  112676. /* times; hook placeholders */
  112677. oggpack_write(opb,0,6);
  112678. oggpack_write(opb,0,16);
  112679. /* floors */
  112680. oggpack_write(opb,ci->floors-1,6);
  112681. for(i=0;i<ci->floors;i++){
  112682. oggpack_write(opb,ci->floor_type[i],16);
  112683. if(_floor_P[ci->floor_type[i]]->pack)
  112684. _floor_P[ci->floor_type[i]]->pack(ci->floor_param[i],opb);
  112685. else
  112686. goto err_out;
  112687. }
  112688. /* residues */
  112689. oggpack_write(opb,ci->residues-1,6);
  112690. for(i=0;i<ci->residues;i++){
  112691. oggpack_write(opb,ci->residue_type[i],16);
  112692. _residue_P[ci->residue_type[i]]->pack(ci->residue_param[i],opb);
  112693. }
  112694. /* maps */
  112695. oggpack_write(opb,ci->maps-1,6);
  112696. for(i=0;i<ci->maps;i++){
  112697. oggpack_write(opb,ci->map_type[i],16);
  112698. _mapping_P[ci->map_type[i]]->pack(vi,ci->map_param[i],opb);
  112699. }
  112700. /* modes */
  112701. oggpack_write(opb,ci->modes-1,6);
  112702. for(i=0;i<ci->modes;i++){
  112703. oggpack_write(opb,ci->mode_param[i]->blockflag,1);
  112704. oggpack_write(opb,ci->mode_param[i]->windowtype,16);
  112705. oggpack_write(opb,ci->mode_param[i]->transformtype,16);
  112706. oggpack_write(opb,ci->mode_param[i]->mapping,8);
  112707. }
  112708. oggpack_write(opb,1,1);
  112709. return(0);
  112710. err_out:
  112711. return(-1);
  112712. }
  112713. int vorbis_commentheader_out(vorbis_comment *vc,
  112714. ogg_packet *op){
  112715. oggpack_buffer opb;
  112716. oggpack_writeinit(&opb);
  112717. if(_vorbis_pack_comment(&opb,vc)) return OV_EIMPL;
  112718. op->packet = (unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  112719. memcpy(op->packet, opb.buffer, oggpack_bytes(&opb));
  112720. op->bytes=oggpack_bytes(&opb);
  112721. op->b_o_s=0;
  112722. op->e_o_s=0;
  112723. op->granulepos=0;
  112724. op->packetno=1;
  112725. return 0;
  112726. }
  112727. int vorbis_analysis_headerout(vorbis_dsp_state *v,
  112728. vorbis_comment *vc,
  112729. ogg_packet *op,
  112730. ogg_packet *op_comm,
  112731. ogg_packet *op_code){
  112732. int ret=OV_EIMPL;
  112733. vorbis_info *vi=v->vi;
  112734. oggpack_buffer opb;
  112735. private_state *b=(private_state*)v->backend_state;
  112736. if(!b){
  112737. ret=OV_EFAULT;
  112738. goto err_out;
  112739. }
  112740. /* first header packet **********************************************/
  112741. oggpack_writeinit(&opb);
  112742. if(_vorbis_pack_info(&opb,vi))goto err_out;
  112743. /* build the packet */
  112744. if(b->header)_ogg_free(b->header);
  112745. b->header=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  112746. memcpy(b->header,opb.buffer,oggpack_bytes(&opb));
  112747. op->packet=b->header;
  112748. op->bytes=oggpack_bytes(&opb);
  112749. op->b_o_s=1;
  112750. op->e_o_s=0;
  112751. op->granulepos=0;
  112752. op->packetno=0;
  112753. /* second header packet (comments) **********************************/
  112754. oggpack_reset(&opb);
  112755. if(_vorbis_pack_comment(&opb,vc))goto err_out;
  112756. if(b->header1)_ogg_free(b->header1);
  112757. b->header1=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  112758. memcpy(b->header1,opb.buffer,oggpack_bytes(&opb));
  112759. op_comm->packet=b->header1;
  112760. op_comm->bytes=oggpack_bytes(&opb);
  112761. op_comm->b_o_s=0;
  112762. op_comm->e_o_s=0;
  112763. op_comm->granulepos=0;
  112764. op_comm->packetno=1;
  112765. /* third header packet (modes/codebooks) ****************************/
  112766. oggpack_reset(&opb);
  112767. if(_vorbis_pack_books(&opb,vi))goto err_out;
  112768. if(b->header2)_ogg_free(b->header2);
  112769. b->header2=(unsigned char*) _ogg_malloc(oggpack_bytes(&opb));
  112770. memcpy(b->header2,opb.buffer,oggpack_bytes(&opb));
  112771. op_code->packet=b->header2;
  112772. op_code->bytes=oggpack_bytes(&opb);
  112773. op_code->b_o_s=0;
  112774. op_code->e_o_s=0;
  112775. op_code->granulepos=0;
  112776. op_code->packetno=2;
  112777. oggpack_writeclear(&opb);
  112778. return(0);
  112779. err_out:
  112780. oggpack_writeclear(&opb);
  112781. memset(op,0,sizeof(*op));
  112782. memset(op_comm,0,sizeof(*op_comm));
  112783. memset(op_code,0,sizeof(*op_code));
  112784. if(b->header)_ogg_free(b->header);
  112785. if(b->header1)_ogg_free(b->header1);
  112786. if(b->header2)_ogg_free(b->header2);
  112787. b->header=NULL;
  112788. b->header1=NULL;
  112789. b->header2=NULL;
  112790. return(ret);
  112791. }
  112792. double vorbis_granule_time(vorbis_dsp_state *v,ogg_int64_t granulepos){
  112793. if(granulepos>=0)
  112794. return((double)granulepos/v->vi->rate);
  112795. return(-1);
  112796. }
  112797. #endif
  112798. /********* End of inlined file: info.c *********/
  112799. /********* Start of inlined file: lpc.c *********/
  112800. /* Some of these routines (autocorrelator, LPC coefficient estimator)
  112801. are derived from code written by Jutta Degener and Carsten Bormann;
  112802. thus we include their copyright below. The entirety of this file
  112803. is freely redistributable on the condition that both of these
  112804. copyright notices are preserved without modification. */
  112805. /* Preserved Copyright: *********************************************/
  112806. /* Copyright 1992, 1993, 1994 by Jutta Degener and Carsten Bormann,
  112807. Technische Universita"t Berlin
  112808. Any use of this software is permitted provided that this notice is not
  112809. removed and that neither the authors nor the Technische Universita"t
  112810. Berlin are deemed to have made any representations as to the
  112811. suitability of this software for any purpose nor are held responsible
  112812. for any defects of this software. THERE IS ABSOLUTELY NO WARRANTY FOR
  112813. THIS SOFTWARE.
  112814. As a matter of courtesy, the authors request to be informed about uses
  112815. this software has found, about bugs in this software, and about any
  112816. improvements that may be of general interest.
  112817. Berlin, 28.11.1994
  112818. Jutta Degener
  112819. Carsten Bormann
  112820. *********************************************************************/
  112821. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  112822. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  112823. // tasks..
  112824. /********* Start of inlined file: juce_Config.h *********/
  112825. #ifndef __JUCE_CONFIG_JUCEHEADER__
  112826. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  112827. /*
  112828. This file contains macros that enable/disable various JUCE features.
  112829. */
  112830. /** The name of the namespace that all Juce classes and functions will be
  112831. put inside. If this is not defined, no namespace will be used.
  112832. */
  112833. #ifndef JUCE_NAMESPACE
  112834. #define JUCE_NAMESPACE juce
  112835. #endif
  112836. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  112837. but if you define this value, you can override this can force it to be true or
  112838. false.
  112839. */
  112840. #ifndef JUCE_FORCE_DEBUG
  112841. //#define JUCE_FORCE_DEBUG 1
  112842. #endif
  112843. /** If this flag is enabled, the the jassert and jassertfalse macros will
  112844. always use Logger::writeToLog() to write a message when an assertion happens.
  112845. Enabling it will also leave this turned on in release builds. When it's disabled,
  112846. however, the jassert and jassertfalse macros will not be compiled in a
  112847. release build.
  112848. @see jassert, jassertfalse, Logger
  112849. */
  112850. #ifndef JUCE_LOG_ASSERTIONS
  112851. // #define JUCE_LOG_ASSERTIONS 1
  112852. #endif
  112853. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  112854. which the ASIOAudioIODevice class can't be built. See the comments in the
  112855. ASIOAudioIODevice class's header file for more info about this.
  112856. (This only affects a Win32 build)
  112857. */
  112858. #ifndef JUCE_ASIO
  112859. #define JUCE_ASIO 1
  112860. #endif
  112861. /** Comment out this macro to disable building of ALSA device support on Linux.
  112862. */
  112863. #ifndef JUCE_ALSA
  112864. #define JUCE_ALSA 1
  112865. #endif
  112866. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  112867. have the SDK installed.
  112868. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  112869. classes will be unavailable.
  112870. On Windows, if you enable this, you'll need to have the QuickTime SDK
  112871. installed, and its header files will need to be on your include path.
  112872. */
  112873. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  112874. #define JUCE_QUICKTIME 1
  112875. #endif
  112876. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  112877. have the appropriate headers and libraries available. If it's not enabled, the
  112878. OpenGLComponent class will be unavailable.
  112879. */
  112880. #ifndef JUCE_OPENGL
  112881. #define JUCE_OPENGL 1
  112882. #endif
  112883. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  112884. If you're not going to need either of these formats, turn off the flags to
  112885. avoid bloating your codebase with them.
  112886. */
  112887. #ifndef JUCE_USE_FLAC
  112888. #define JUCE_USE_FLAC 1
  112889. #endif
  112890. #ifndef JUCE_USE_OGGVORBIS
  112891. #define JUCE_USE_OGGVORBIS 1
  112892. #endif
  112893. /** This flag lets you enable support for CD-burning. You might want to disable
  112894. it to build without the MS SDK under windows.
  112895. */
  112896. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  112897. #define JUCE_USE_CDBURNER 1
  112898. #endif
  112899. /** Enabling this macro means that all regions that get repainted will have a coloured
  112900. line drawn around them.
  112901. This is handy if you're trying to optimise drawing, because it lets you easily see
  112902. when anything is being repainted unnecessarily.
  112903. */
  112904. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  112905. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  112906. #endif
  112907. /** Enable this under Linux to use Xinerama for multi-monitor support.
  112908. */
  112909. #ifndef JUCE_USE_XINERAMA
  112910. #define JUCE_USE_XINERAMA 1
  112911. #endif
  112912. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  112913. */
  112914. #ifndef JUCE_USE_XSHM
  112915. #define JUCE_USE_XSHM 1
  112916. #endif
  112917. /** Enabling this builds support for VST audio plugins.
  112918. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  112919. */
  112920. #ifndef JUCE_PLUGINHOST_VST
  112921. // #define JUCE_PLUGINHOST_VST 1
  112922. #endif
  112923. /** Enabling this builds support for AudioUnit audio plugins.
  112924. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  112925. */
  112926. #ifndef JUCE_PLUGINHOST_AU
  112927. // #define JUCE_PLUGINHOST_AU 1
  112928. #endif
  112929. /** Disabling this will avoid linking to any UI code. This is handy for
  112930. writing command-line utilities, e.g. on linux boxes which don't have some
  112931. of the UI libraries installed.
  112932. (On mac and windows, this won't generally make much difference to the build).
  112933. */
  112934. #ifndef JUCE_BUILD_GUI_CLASSES
  112935. #define JUCE_BUILD_GUI_CLASSES 1
  112936. #endif
  112937. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  112938. */
  112939. #ifndef JUCE_WEB_BROWSER
  112940. #define JUCE_WEB_BROWSER 1
  112941. #endif
  112942. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  112943. codebase - you might need to use this if you're linking to some of these libraries
  112944. yourself.
  112945. */
  112946. #ifndef JUCE_INCLUDE_ZLIB_CODE
  112947. #define JUCE_INCLUDE_ZLIB_CODE 1
  112948. #endif
  112949. #ifndef JUCE_INCLUDE_FLAC_CODE
  112950. #define JUCE_INCLUDE_FLAC_CODE 1
  112951. #endif
  112952. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  112953. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  112954. #endif
  112955. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  112956. #define JUCE_INCLUDE_PNGLIB_CODE 1
  112957. #endif
  112958. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  112959. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  112960. #endif
  112961. /** Enable this to add extra memory-leak info to the new and delete operators.
  112962. (Currently, this only affects Windows builds in debug mode).
  112963. */
  112964. #ifndef JUCE_CHECK_MEMORY_LEAKS
  112965. #define JUCE_CHECK_MEMORY_LEAKS 1
  112966. #endif
  112967. /** Enable this to turn on juce's internal catching of exceptions.
  112968. Turning it off will avoid any exception catching. With it on, all exceptions
  112969. are passed to the JUCEApplication::unhandledException() callback for logging.
  112970. */
  112971. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  112972. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  112973. #endif
  112974. /** If this macro is set, the Juce String class will use unicode as its
  112975. internal representation. If it isn't set, it'll use ANSI.
  112976. */
  112977. #ifndef JUCE_STRINGS_ARE_UNICODE
  112978. #define JUCE_STRINGS_ARE_UNICODE 1
  112979. #endif
  112980. #endif
  112981. /********* End of inlined file: juce_Config.h *********/
  112982. #ifdef _MSC_VER
  112983. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  112984. #endif
  112985. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  112986. #if JUCE_USE_OGGVORBIS
  112987. #include <stdlib.h>
  112988. #include <string.h>
  112989. #include <math.h>
  112990. /* Autocorrelation LPC coeff generation algorithm invented by
  112991. N. Levinson in 1947, modified by J. Durbin in 1959. */
  112992. /* Input : n elements of time doamin data
  112993. Output: m lpc coefficients, excitation energy */
  112994. float vorbis_lpc_from_data(float *data,float *lpci,int n,int m){
  112995. double *aut=(double*)alloca(sizeof(*aut)*(m+1));
  112996. double *lpc=(double*)alloca(sizeof(*lpc)*(m));
  112997. double error;
  112998. int i,j;
  112999. /* autocorrelation, p+1 lag coefficients */
  113000. j=m+1;
  113001. while(j--){
  113002. double d=0; /* double needed for accumulator depth */
  113003. for(i=j;i<n;i++)d+=(double)data[i]*data[i-j];
  113004. aut[j]=d;
  113005. }
  113006. /* Generate lpc coefficients from autocorr values */
  113007. error=aut[0];
  113008. for(i=0;i<m;i++){
  113009. double r= -aut[i+1];
  113010. if(error==0){
  113011. memset(lpci,0,m*sizeof(*lpci));
  113012. return 0;
  113013. }
  113014. /* Sum up this iteration's reflection coefficient; note that in
  113015. Vorbis we don't save it. If anyone wants to recycle this code
  113016. and needs reflection coefficients, save the results of 'r' from
  113017. each iteration. */
  113018. for(j=0;j<i;j++)r-=lpc[j]*aut[i-j];
  113019. r/=error;
  113020. /* Update LPC coefficients and total error */
  113021. lpc[i]=r;
  113022. for(j=0;j<i/2;j++){
  113023. double tmp=lpc[j];
  113024. lpc[j]+=r*lpc[i-1-j];
  113025. lpc[i-1-j]+=r*tmp;
  113026. }
  113027. if(i%2)lpc[j]+=lpc[j]*r;
  113028. error*=1.f-r*r;
  113029. }
  113030. for(j=0;j<m;j++)lpci[j]=(float)lpc[j];
  113031. /* we need the error value to know how big an impulse to hit the
  113032. filter with later */
  113033. return error;
  113034. }
  113035. void vorbis_lpc_predict(float *coeff,float *prime,int m,
  113036. float *data,long n){
  113037. /* in: coeff[0...m-1] LPC coefficients
  113038. prime[0...m-1] initial values (allocated size of n+m-1)
  113039. out: data[0...n-1] data samples */
  113040. long i,j,o,p;
  113041. float y;
  113042. float *work=(float*)alloca(sizeof(*work)*(m+n));
  113043. if(!prime)
  113044. for(i=0;i<m;i++)
  113045. work[i]=0.f;
  113046. else
  113047. for(i=0;i<m;i++)
  113048. work[i]=prime[i];
  113049. for(i=0;i<n;i++){
  113050. y=0;
  113051. o=i;
  113052. p=m;
  113053. for(j=0;j<m;j++)
  113054. y-=work[o++]*coeff[--p];
  113055. data[i]=work[o]=y;
  113056. }
  113057. }
  113058. #endif
  113059. /********* End of inlined file: lpc.c *********/
  113060. /********* Start of inlined file: lsp.c *********/
  113061. /* Note that the lpc-lsp conversion finds the roots of polynomial with
  113062. an iterative root polisher (CACM algorithm 283). It *is* possible
  113063. to confuse this algorithm into not converging; that should only
  113064. happen with absurdly closely spaced roots (very sharp peaks in the
  113065. LPC f response) which in turn should be impossible in our use of
  113066. the code. If this *does* happen anyway, it's a bug in the floor
  113067. finder; find the cause of the confusion (probably a single bin
  113068. spike or accidental near-float-limit resolution problems) and
  113069. correct it. */
  113070. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113071. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113072. // tasks..
  113073. /********* Start of inlined file: juce_Config.h *********/
  113074. #ifndef __JUCE_CONFIG_JUCEHEADER__
  113075. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  113076. /*
  113077. This file contains macros that enable/disable various JUCE features.
  113078. */
  113079. /** The name of the namespace that all Juce classes and functions will be
  113080. put inside. If this is not defined, no namespace will be used.
  113081. */
  113082. #ifndef JUCE_NAMESPACE
  113083. #define JUCE_NAMESPACE juce
  113084. #endif
  113085. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  113086. but if you define this value, you can override this can force it to be true or
  113087. false.
  113088. */
  113089. #ifndef JUCE_FORCE_DEBUG
  113090. //#define JUCE_FORCE_DEBUG 1
  113091. #endif
  113092. /** If this flag is enabled, the the jassert and jassertfalse macros will
  113093. always use Logger::writeToLog() to write a message when an assertion happens.
  113094. Enabling it will also leave this turned on in release builds. When it's disabled,
  113095. however, the jassert and jassertfalse macros will not be compiled in a
  113096. release build.
  113097. @see jassert, jassertfalse, Logger
  113098. */
  113099. #ifndef JUCE_LOG_ASSERTIONS
  113100. // #define JUCE_LOG_ASSERTIONS 1
  113101. #endif
  113102. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  113103. which the ASIOAudioIODevice class can't be built. See the comments in the
  113104. ASIOAudioIODevice class's header file for more info about this.
  113105. (This only affects a Win32 build)
  113106. */
  113107. #ifndef JUCE_ASIO
  113108. #define JUCE_ASIO 1
  113109. #endif
  113110. /** Comment out this macro to disable building of ALSA device support on Linux.
  113111. */
  113112. #ifndef JUCE_ALSA
  113113. #define JUCE_ALSA 1
  113114. #endif
  113115. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  113116. have the SDK installed.
  113117. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  113118. classes will be unavailable.
  113119. On Windows, if you enable this, you'll need to have the QuickTime SDK
  113120. installed, and its header files will need to be on your include path.
  113121. */
  113122. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  113123. #define JUCE_QUICKTIME 1
  113124. #endif
  113125. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  113126. have the appropriate headers and libraries available. If it's not enabled, the
  113127. OpenGLComponent class will be unavailable.
  113128. */
  113129. #ifndef JUCE_OPENGL
  113130. #define JUCE_OPENGL 1
  113131. #endif
  113132. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  113133. If you're not going to need either of these formats, turn off the flags to
  113134. avoid bloating your codebase with them.
  113135. */
  113136. #ifndef JUCE_USE_FLAC
  113137. #define JUCE_USE_FLAC 1
  113138. #endif
  113139. #ifndef JUCE_USE_OGGVORBIS
  113140. #define JUCE_USE_OGGVORBIS 1
  113141. #endif
  113142. /** This flag lets you enable support for CD-burning. You might want to disable
  113143. it to build without the MS SDK under windows.
  113144. */
  113145. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  113146. #define JUCE_USE_CDBURNER 1
  113147. #endif
  113148. /** Enabling this macro means that all regions that get repainted will have a coloured
  113149. line drawn around them.
  113150. This is handy if you're trying to optimise drawing, because it lets you easily see
  113151. when anything is being repainted unnecessarily.
  113152. */
  113153. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  113154. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  113155. #endif
  113156. /** Enable this under Linux to use Xinerama for multi-monitor support.
  113157. */
  113158. #ifndef JUCE_USE_XINERAMA
  113159. #define JUCE_USE_XINERAMA 1
  113160. #endif
  113161. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  113162. */
  113163. #ifndef JUCE_USE_XSHM
  113164. #define JUCE_USE_XSHM 1
  113165. #endif
  113166. /** Enabling this builds support for VST audio plugins.
  113167. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  113168. */
  113169. #ifndef JUCE_PLUGINHOST_VST
  113170. // #define JUCE_PLUGINHOST_VST 1
  113171. #endif
  113172. /** Enabling this builds support for AudioUnit audio plugins.
  113173. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  113174. */
  113175. #ifndef JUCE_PLUGINHOST_AU
  113176. // #define JUCE_PLUGINHOST_AU 1
  113177. #endif
  113178. /** Disabling this will avoid linking to any UI code. This is handy for
  113179. writing command-line utilities, e.g. on linux boxes which don't have some
  113180. of the UI libraries installed.
  113181. (On mac and windows, this won't generally make much difference to the build).
  113182. */
  113183. #ifndef JUCE_BUILD_GUI_CLASSES
  113184. #define JUCE_BUILD_GUI_CLASSES 1
  113185. #endif
  113186. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  113187. */
  113188. #ifndef JUCE_WEB_BROWSER
  113189. #define JUCE_WEB_BROWSER 1
  113190. #endif
  113191. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  113192. codebase - you might need to use this if you're linking to some of these libraries
  113193. yourself.
  113194. */
  113195. #ifndef JUCE_INCLUDE_ZLIB_CODE
  113196. #define JUCE_INCLUDE_ZLIB_CODE 1
  113197. #endif
  113198. #ifndef JUCE_INCLUDE_FLAC_CODE
  113199. #define JUCE_INCLUDE_FLAC_CODE 1
  113200. #endif
  113201. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  113202. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  113203. #endif
  113204. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  113205. #define JUCE_INCLUDE_PNGLIB_CODE 1
  113206. #endif
  113207. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  113208. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  113209. #endif
  113210. /** Enable this to add extra memory-leak info to the new and delete operators.
  113211. (Currently, this only affects Windows builds in debug mode).
  113212. */
  113213. #ifndef JUCE_CHECK_MEMORY_LEAKS
  113214. #define JUCE_CHECK_MEMORY_LEAKS 1
  113215. #endif
  113216. /** Enable this to turn on juce's internal catching of exceptions.
  113217. Turning it off will avoid any exception catching. With it on, all exceptions
  113218. are passed to the JUCEApplication::unhandledException() callback for logging.
  113219. */
  113220. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  113221. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  113222. #endif
  113223. /** If this macro is set, the Juce String class will use unicode as its
  113224. internal representation. If it isn't set, it'll use ANSI.
  113225. */
  113226. #ifndef JUCE_STRINGS_ARE_UNICODE
  113227. #define JUCE_STRINGS_ARE_UNICODE 1
  113228. #endif
  113229. #endif
  113230. /********* End of inlined file: juce_Config.h *********/
  113231. #ifdef _MSC_VER
  113232. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113233. #endif
  113234. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113235. #if JUCE_USE_OGGVORBIS
  113236. #include <math.h>
  113237. #include <string.h>
  113238. #include <stdlib.h>
  113239. /********* Start of inlined file: lookup.h *********/
  113240. #ifndef _V_LOOKUP_H_
  113241. #ifdef FLOAT_LOOKUP
  113242. extern float vorbis_coslook(float a);
  113243. extern float vorbis_invsqlook(float a);
  113244. extern float vorbis_invsq2explook(int a);
  113245. extern float vorbis_fromdBlook(float a);
  113246. #endif
  113247. #ifdef INT_LOOKUP
  113248. extern long vorbis_invsqlook_i(long a,long e);
  113249. extern long vorbis_coslook_i(long a);
  113250. extern float vorbis_fromdBlook_i(long a);
  113251. #endif
  113252. #endif
  113253. /********* End of inlined file: lookup.h *********/
  113254. /* three possible LSP to f curve functions; the exact computation
  113255. (float), a lookup based float implementation, and an integer
  113256. implementation. The float lookup is likely the optimal choice on
  113257. any machine with an FPU. The integer implementation is *not* fixed
  113258. point (due to the need for a large dynamic range and thus a
  113259. seperately tracked exponent) and thus much more complex than the
  113260. relatively simple float implementations. It's mostly for future
  113261. work on a fully fixed point implementation for processors like the
  113262. ARM family. */
  113263. /* undefine both for the 'old' but more precise implementation */
  113264. #define FLOAT_LOOKUP
  113265. #undef INT_LOOKUP
  113266. #ifdef FLOAT_LOOKUP
  113267. /********* Start of inlined file: lookup.c *********/
  113268. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113269. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113270. // tasks..
  113271. /********* Start of inlined file: juce_Config.h *********/
  113272. #ifndef __JUCE_CONFIG_JUCEHEADER__
  113273. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  113274. /*
  113275. This file contains macros that enable/disable various JUCE features.
  113276. */
  113277. /** The name of the namespace that all Juce classes and functions will be
  113278. put inside. If this is not defined, no namespace will be used.
  113279. */
  113280. #ifndef JUCE_NAMESPACE
  113281. #define JUCE_NAMESPACE juce
  113282. #endif
  113283. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  113284. but if you define this value, you can override this can force it to be true or
  113285. false.
  113286. */
  113287. #ifndef JUCE_FORCE_DEBUG
  113288. //#define JUCE_FORCE_DEBUG 1
  113289. #endif
  113290. /** If this flag is enabled, the the jassert and jassertfalse macros will
  113291. always use Logger::writeToLog() to write a message when an assertion happens.
  113292. Enabling it will also leave this turned on in release builds. When it's disabled,
  113293. however, the jassert and jassertfalse macros will not be compiled in a
  113294. release build.
  113295. @see jassert, jassertfalse, Logger
  113296. */
  113297. #ifndef JUCE_LOG_ASSERTIONS
  113298. // #define JUCE_LOG_ASSERTIONS 1
  113299. #endif
  113300. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  113301. which the ASIOAudioIODevice class can't be built. See the comments in the
  113302. ASIOAudioIODevice class's header file for more info about this.
  113303. (This only affects a Win32 build)
  113304. */
  113305. #ifndef JUCE_ASIO
  113306. #define JUCE_ASIO 1
  113307. #endif
  113308. /** Comment out this macro to disable building of ALSA device support on Linux.
  113309. */
  113310. #ifndef JUCE_ALSA
  113311. #define JUCE_ALSA 1
  113312. #endif
  113313. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  113314. have the SDK installed.
  113315. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  113316. classes will be unavailable.
  113317. On Windows, if you enable this, you'll need to have the QuickTime SDK
  113318. installed, and its header files will need to be on your include path.
  113319. */
  113320. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  113321. #define JUCE_QUICKTIME 1
  113322. #endif
  113323. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  113324. have the appropriate headers and libraries available. If it's not enabled, the
  113325. OpenGLComponent class will be unavailable.
  113326. */
  113327. #ifndef JUCE_OPENGL
  113328. #define JUCE_OPENGL 1
  113329. #endif
  113330. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  113331. If you're not going to need either of these formats, turn off the flags to
  113332. avoid bloating your codebase with them.
  113333. */
  113334. #ifndef JUCE_USE_FLAC
  113335. #define JUCE_USE_FLAC 1
  113336. #endif
  113337. #ifndef JUCE_USE_OGGVORBIS
  113338. #define JUCE_USE_OGGVORBIS 1
  113339. #endif
  113340. /** This flag lets you enable support for CD-burning. You might want to disable
  113341. it to build without the MS SDK under windows.
  113342. */
  113343. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  113344. #define JUCE_USE_CDBURNER 1
  113345. #endif
  113346. /** Enabling this macro means that all regions that get repainted will have a coloured
  113347. line drawn around them.
  113348. This is handy if you're trying to optimise drawing, because it lets you easily see
  113349. when anything is being repainted unnecessarily.
  113350. */
  113351. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  113352. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  113353. #endif
  113354. /** Enable this under Linux to use Xinerama for multi-monitor support.
  113355. */
  113356. #ifndef JUCE_USE_XINERAMA
  113357. #define JUCE_USE_XINERAMA 1
  113358. #endif
  113359. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  113360. */
  113361. #ifndef JUCE_USE_XSHM
  113362. #define JUCE_USE_XSHM 1
  113363. #endif
  113364. /** Enabling this builds support for VST audio plugins.
  113365. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  113366. */
  113367. #ifndef JUCE_PLUGINHOST_VST
  113368. // #define JUCE_PLUGINHOST_VST 1
  113369. #endif
  113370. /** Enabling this builds support for AudioUnit audio plugins.
  113371. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  113372. */
  113373. #ifndef JUCE_PLUGINHOST_AU
  113374. // #define JUCE_PLUGINHOST_AU 1
  113375. #endif
  113376. /** Disabling this will avoid linking to any UI code. This is handy for
  113377. writing command-line utilities, e.g. on linux boxes which don't have some
  113378. of the UI libraries installed.
  113379. (On mac and windows, this won't generally make much difference to the build).
  113380. */
  113381. #ifndef JUCE_BUILD_GUI_CLASSES
  113382. #define JUCE_BUILD_GUI_CLASSES 1
  113383. #endif
  113384. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  113385. */
  113386. #ifndef JUCE_WEB_BROWSER
  113387. #define JUCE_WEB_BROWSER 1
  113388. #endif
  113389. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  113390. codebase - you might need to use this if you're linking to some of these libraries
  113391. yourself.
  113392. */
  113393. #ifndef JUCE_INCLUDE_ZLIB_CODE
  113394. #define JUCE_INCLUDE_ZLIB_CODE 1
  113395. #endif
  113396. #ifndef JUCE_INCLUDE_FLAC_CODE
  113397. #define JUCE_INCLUDE_FLAC_CODE 1
  113398. #endif
  113399. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  113400. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  113401. #endif
  113402. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  113403. #define JUCE_INCLUDE_PNGLIB_CODE 1
  113404. #endif
  113405. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  113406. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  113407. #endif
  113408. /** Enable this to add extra memory-leak info to the new and delete operators.
  113409. (Currently, this only affects Windows builds in debug mode).
  113410. */
  113411. #ifndef JUCE_CHECK_MEMORY_LEAKS
  113412. #define JUCE_CHECK_MEMORY_LEAKS 1
  113413. #endif
  113414. /** Enable this to turn on juce's internal catching of exceptions.
  113415. Turning it off will avoid any exception catching. With it on, all exceptions
  113416. are passed to the JUCEApplication::unhandledException() callback for logging.
  113417. */
  113418. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  113419. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  113420. #endif
  113421. /** If this macro is set, the Juce String class will use unicode as its
  113422. internal representation. If it isn't set, it'll use ANSI.
  113423. */
  113424. #ifndef JUCE_STRINGS_ARE_UNICODE
  113425. #define JUCE_STRINGS_ARE_UNICODE 1
  113426. #endif
  113427. #endif
  113428. /********* End of inlined file: juce_Config.h *********/
  113429. #ifdef _MSC_VER
  113430. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113431. #endif
  113432. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113433. #if JUCE_USE_OGGVORBIS
  113434. #include <math.h>
  113435. /********* Start of inlined file: lookup.h *********/
  113436. #ifndef _V_LOOKUP_H_
  113437. #ifdef FLOAT_LOOKUP
  113438. extern float vorbis_coslook(float a);
  113439. extern float vorbis_invsqlook(float a);
  113440. extern float vorbis_invsq2explook(int a);
  113441. extern float vorbis_fromdBlook(float a);
  113442. #endif
  113443. #ifdef INT_LOOKUP
  113444. extern long vorbis_invsqlook_i(long a,long e);
  113445. extern long vorbis_coslook_i(long a);
  113446. extern float vorbis_fromdBlook_i(long a);
  113447. #endif
  113448. #endif
  113449. /********* End of inlined file: lookup.h *********/
  113450. /********* Start of inlined file: lookup_data.h *********/
  113451. #ifndef _V_LOOKUP_DATA_H_
  113452. #ifdef FLOAT_LOOKUP
  113453. #define COS_LOOKUP_SZ 128
  113454. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113455. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113456. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113457. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113458. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113459. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113460. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113461. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113462. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113463. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113464. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113465. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113466. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113467. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113468. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113469. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113470. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113471. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113472. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113473. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113474. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113475. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113476. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113477. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113478. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113479. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113480. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113481. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113482. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113483. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113484. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113485. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113486. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113487. -1.0000000000000f,
  113488. };
  113489. #define INVSQ_LOOKUP_SZ 32
  113490. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113491. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113492. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113493. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113494. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113495. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113496. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113497. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113498. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113499. 1.000000000000f,
  113500. };
  113501. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113502. #define INVSQ2EXP_LOOKUP_MAX 32
  113503. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113504. INVSQ2EXP_LOOKUP_MIN+1]={
  113505. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113506. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113507. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113508. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113509. 256.f, 181.019336f, 128.f, 90.50966799f,
  113510. 64.f, 45.254834f, 32.f, 22.627417f,
  113511. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113512. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113513. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113514. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113515. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113516. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113517. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113518. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113519. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113520. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113521. 1.525878906e-05f,
  113522. };
  113523. #endif
  113524. #define FROMdB_LOOKUP_SZ 35
  113525. #define FROMdB2_LOOKUP_SZ 32
  113526. #define FROMdB_SHIFT 5
  113527. #define FROMdB2_SHIFT 3
  113528. #define FROMdB2_MASK 31
  113529. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113530. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113531. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113532. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113533. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113534. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113535. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113536. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113537. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113538. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113539. };
  113540. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113541. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113542. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113543. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  113544. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  113545. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  113546. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  113547. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  113548. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  113549. };
  113550. #ifdef INT_LOOKUP
  113551. #define INVSQ_LOOKUP_I_SHIFT 10
  113552. #define INVSQ_LOOKUP_I_MASK 1023
  113553. static long INVSQ_LOOKUP_I[64+1]={
  113554. 92682l, 91966l, 91267l, 90583l,
  113555. 89915l, 89261l, 88621l, 87995l,
  113556. 87381l, 86781l, 86192l, 85616l,
  113557. 85051l, 84497l, 83953l, 83420l,
  113558. 82897l, 82384l, 81880l, 81385l,
  113559. 80899l, 80422l, 79953l, 79492l,
  113560. 79039l, 78594l, 78156l, 77726l,
  113561. 77302l, 76885l, 76475l, 76072l,
  113562. 75674l, 75283l, 74898l, 74519l,
  113563. 74146l, 73778l, 73415l, 73058l,
  113564. 72706l, 72359l, 72016l, 71679l,
  113565. 71347l, 71019l, 70695l, 70376l,
  113566. 70061l, 69750l, 69444l, 69141l,
  113567. 68842l, 68548l, 68256l, 67969l,
  113568. 67685l, 67405l, 67128l, 66855l,
  113569. 66585l, 66318l, 66054l, 65794l,
  113570. 65536l,
  113571. };
  113572. #define COS_LOOKUP_I_SHIFT 9
  113573. #define COS_LOOKUP_I_MASK 511
  113574. #define COS_LOOKUP_I_SZ 128
  113575. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  113576. 16384l, 16379l, 16364l, 16340l,
  113577. 16305l, 16261l, 16207l, 16143l,
  113578. 16069l, 15986l, 15893l, 15791l,
  113579. 15679l, 15557l, 15426l, 15286l,
  113580. 15137l, 14978l, 14811l, 14635l,
  113581. 14449l, 14256l, 14053l, 13842l,
  113582. 13623l, 13395l, 13160l, 12916l,
  113583. 12665l, 12406l, 12140l, 11866l,
  113584. 11585l, 11297l, 11003l, 10702l,
  113585. 10394l, 10080l, 9760l, 9434l,
  113586. 9102l, 8765l, 8423l, 8076l,
  113587. 7723l, 7366l, 7005l, 6639l,
  113588. 6270l, 5897l, 5520l, 5139l,
  113589. 4756l, 4370l, 3981l, 3590l,
  113590. 3196l, 2801l, 2404l, 2006l,
  113591. 1606l, 1205l, 804l, 402l,
  113592. 0l, -401l, -803l, -1204l,
  113593. -1605l, -2005l, -2403l, -2800l,
  113594. -3195l, -3589l, -3980l, -4369l,
  113595. -4755l, -5138l, -5519l, -5896l,
  113596. -6269l, -6638l, -7004l, -7365l,
  113597. -7722l, -8075l, -8422l, -8764l,
  113598. -9101l, -9433l, -9759l, -10079l,
  113599. -10393l, -10701l, -11002l, -11296l,
  113600. -11584l, -11865l, -12139l, -12405l,
  113601. -12664l, -12915l, -13159l, -13394l,
  113602. -13622l, -13841l, -14052l, -14255l,
  113603. -14448l, -14634l, -14810l, -14977l,
  113604. -15136l, -15285l, -15425l, -15556l,
  113605. -15678l, -15790l, -15892l, -15985l,
  113606. -16068l, -16142l, -16206l, -16260l,
  113607. -16304l, -16339l, -16363l, -16378l,
  113608. -16383l,
  113609. };
  113610. #endif
  113611. #endif
  113612. /********* End of inlined file: lookup_data.h *********/
  113613. #ifdef FLOAT_LOOKUP
  113614. /* interpolated lookup based cos function, domain 0 to PI only */
  113615. float vorbis_coslook(float a){
  113616. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  113617. int i=vorbis_ftoi(d-.5);
  113618. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  113619. }
  113620. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113621. float vorbis_invsqlook(float a){
  113622. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  113623. int i=vorbis_ftoi(d-.5f);
  113624. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  113625. }
  113626. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  113627. float vorbis_invsq2explook(int a){
  113628. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  113629. }
  113630. #include <stdio.h>
  113631. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113632. float vorbis_fromdBlook(float a){
  113633. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  113634. return (i<0)?1.f:
  113635. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113636. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113637. }
  113638. #endif
  113639. #ifdef INT_LOOKUP
  113640. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  113641. 16.16 format
  113642. returns in m.8 format */
  113643. long vorbis_invsqlook_i(long a,long e){
  113644. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  113645. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  113646. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  113647. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  113648. d)>>16); /* result 1.16 */
  113649. e+=32;
  113650. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  113651. e=(e>>1)-8;
  113652. return(val>>e);
  113653. }
  113654. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  113655. /* a is in n.12 format */
  113656. float vorbis_fromdBlook_i(long a){
  113657. int i=(-a)>>(12-FROMdB2_SHIFT);
  113658. return (i<0)?1.f:
  113659. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  113660. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  113661. }
  113662. /* interpolated lookup based cos function, domain 0 to PI only */
  113663. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  113664. long vorbis_coslook_i(long a){
  113665. int i=a>>COS_LOOKUP_I_SHIFT;
  113666. int d=a&COS_LOOKUP_I_MASK;
  113667. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  113668. COS_LOOKUP_I_SHIFT);
  113669. }
  113670. #endif
  113671. #endif
  113672. /********* End of inlined file: lookup.c *********/
  113673. /* catch this in the build system; we #include for
  113674. compilers (like gcc) that can't inline across
  113675. modules */
  113676. /* side effect: changes *lsp to cosines of lsp */
  113677. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  113678. float amp,float ampoffset){
  113679. int i;
  113680. float wdel=M_PI/ln;
  113681. vorbis_fpu_control fpu;
  113682. (void) fpu; // to avoid an unused variable warning
  113683. vorbis_fpu_setround(&fpu);
  113684. for(i=0;i<m;i++)lsp[i]=vorbis_coslook(lsp[i]);
  113685. i=0;
  113686. while(i<n){
  113687. int k=map[i];
  113688. int qexp;
  113689. float p=.7071067812f;
  113690. float q=.7071067812f;
  113691. float w=vorbis_coslook(wdel*k);
  113692. float *ftmp=lsp;
  113693. int c=m>>1;
  113694. do{
  113695. q*=ftmp[0]-w;
  113696. p*=ftmp[1]-w;
  113697. ftmp+=2;
  113698. }while(--c);
  113699. if(m&1){
  113700. /* odd order filter; slightly assymetric */
  113701. /* the last coefficient */
  113702. q*=ftmp[0]-w;
  113703. q*=q;
  113704. p*=p*(1.f-w*w);
  113705. }else{
  113706. /* even order filter; still symmetric */
  113707. q*=q*(1.f+w);
  113708. p*=p*(1.f-w);
  113709. }
  113710. q=frexp(p+q,&qexp);
  113711. q=vorbis_fromdBlook(amp*
  113712. vorbis_invsqlook(q)*
  113713. vorbis_invsq2explook(qexp+m)-
  113714. ampoffset);
  113715. do{
  113716. curve[i++]*=q;
  113717. }while(map[i]==k);
  113718. }
  113719. vorbis_fpu_restore(fpu);
  113720. }
  113721. #else
  113722. #ifdef INT_LOOKUP
  113723. /********* Start of inlined file: lookup.c *********/
  113724. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  113725. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  113726. // tasks..
  113727. /********* Start of inlined file: juce_Config.h *********/
  113728. #ifndef __JUCE_CONFIG_JUCEHEADER__
  113729. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  113730. /*
  113731. This file contains macros that enable/disable various JUCE features.
  113732. */
  113733. /** The name of the namespace that all Juce classes and functions will be
  113734. put inside. If this is not defined, no namespace will be used.
  113735. */
  113736. #ifndef JUCE_NAMESPACE
  113737. #define JUCE_NAMESPACE juce
  113738. #endif
  113739. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  113740. but if you define this value, you can override this can force it to be true or
  113741. false.
  113742. */
  113743. #ifndef JUCE_FORCE_DEBUG
  113744. //#define JUCE_FORCE_DEBUG 1
  113745. #endif
  113746. /** If this flag is enabled, the the jassert and jassertfalse macros will
  113747. always use Logger::writeToLog() to write a message when an assertion happens.
  113748. Enabling it will also leave this turned on in release builds. When it's disabled,
  113749. however, the jassert and jassertfalse macros will not be compiled in a
  113750. release build.
  113751. @see jassert, jassertfalse, Logger
  113752. */
  113753. #ifndef JUCE_LOG_ASSERTIONS
  113754. // #define JUCE_LOG_ASSERTIONS 1
  113755. #endif
  113756. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  113757. which the ASIOAudioIODevice class can't be built. See the comments in the
  113758. ASIOAudioIODevice class's header file for more info about this.
  113759. (This only affects a Win32 build)
  113760. */
  113761. #ifndef JUCE_ASIO
  113762. #define JUCE_ASIO 1
  113763. #endif
  113764. /** Comment out this macro to disable building of ALSA device support on Linux.
  113765. */
  113766. #ifndef JUCE_ALSA
  113767. #define JUCE_ALSA 1
  113768. #endif
  113769. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  113770. have the SDK installed.
  113771. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  113772. classes will be unavailable.
  113773. On Windows, if you enable this, you'll need to have the QuickTime SDK
  113774. installed, and its header files will need to be on your include path.
  113775. */
  113776. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  113777. #define JUCE_QUICKTIME 1
  113778. #endif
  113779. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  113780. have the appropriate headers and libraries available. If it's not enabled, the
  113781. OpenGLComponent class will be unavailable.
  113782. */
  113783. #ifndef JUCE_OPENGL
  113784. #define JUCE_OPENGL 1
  113785. #endif
  113786. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  113787. If you're not going to need either of these formats, turn off the flags to
  113788. avoid bloating your codebase with them.
  113789. */
  113790. #ifndef JUCE_USE_FLAC
  113791. #define JUCE_USE_FLAC 1
  113792. #endif
  113793. #ifndef JUCE_USE_OGGVORBIS
  113794. #define JUCE_USE_OGGVORBIS 1
  113795. #endif
  113796. /** This flag lets you enable support for CD-burning. You might want to disable
  113797. it to build without the MS SDK under windows.
  113798. */
  113799. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  113800. #define JUCE_USE_CDBURNER 1
  113801. #endif
  113802. /** Enabling this macro means that all regions that get repainted will have a coloured
  113803. line drawn around them.
  113804. This is handy if you're trying to optimise drawing, because it lets you easily see
  113805. when anything is being repainted unnecessarily.
  113806. */
  113807. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  113808. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  113809. #endif
  113810. /** Enable this under Linux to use Xinerama for multi-monitor support.
  113811. */
  113812. #ifndef JUCE_USE_XINERAMA
  113813. #define JUCE_USE_XINERAMA 1
  113814. #endif
  113815. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  113816. */
  113817. #ifndef JUCE_USE_XSHM
  113818. #define JUCE_USE_XSHM 1
  113819. #endif
  113820. /** Enabling this builds support for VST audio plugins.
  113821. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  113822. */
  113823. #ifndef JUCE_PLUGINHOST_VST
  113824. // #define JUCE_PLUGINHOST_VST 1
  113825. #endif
  113826. /** Enabling this builds support for AudioUnit audio plugins.
  113827. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  113828. */
  113829. #ifndef JUCE_PLUGINHOST_AU
  113830. // #define JUCE_PLUGINHOST_AU 1
  113831. #endif
  113832. /** Disabling this will avoid linking to any UI code. This is handy for
  113833. writing command-line utilities, e.g. on linux boxes which don't have some
  113834. of the UI libraries installed.
  113835. (On mac and windows, this won't generally make much difference to the build).
  113836. */
  113837. #ifndef JUCE_BUILD_GUI_CLASSES
  113838. #define JUCE_BUILD_GUI_CLASSES 1
  113839. #endif
  113840. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  113841. */
  113842. #ifndef JUCE_WEB_BROWSER
  113843. #define JUCE_WEB_BROWSER 1
  113844. #endif
  113845. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  113846. codebase - you might need to use this if you're linking to some of these libraries
  113847. yourself.
  113848. */
  113849. #ifndef JUCE_INCLUDE_ZLIB_CODE
  113850. #define JUCE_INCLUDE_ZLIB_CODE 1
  113851. #endif
  113852. #ifndef JUCE_INCLUDE_FLAC_CODE
  113853. #define JUCE_INCLUDE_FLAC_CODE 1
  113854. #endif
  113855. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  113856. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  113857. #endif
  113858. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  113859. #define JUCE_INCLUDE_PNGLIB_CODE 1
  113860. #endif
  113861. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  113862. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  113863. #endif
  113864. /** Enable this to add extra memory-leak info to the new and delete operators.
  113865. (Currently, this only affects Windows builds in debug mode).
  113866. */
  113867. #ifndef JUCE_CHECK_MEMORY_LEAKS
  113868. #define JUCE_CHECK_MEMORY_LEAKS 1
  113869. #endif
  113870. /** Enable this to turn on juce's internal catching of exceptions.
  113871. Turning it off will avoid any exception catching. With it on, all exceptions
  113872. are passed to the JUCEApplication::unhandledException() callback for logging.
  113873. */
  113874. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  113875. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  113876. #endif
  113877. /** If this macro is set, the Juce String class will use unicode as its
  113878. internal representation. If it isn't set, it'll use ANSI.
  113879. */
  113880. #ifndef JUCE_STRINGS_ARE_UNICODE
  113881. #define JUCE_STRINGS_ARE_UNICODE 1
  113882. #endif
  113883. #endif
  113884. /********* End of inlined file: juce_Config.h *********/
  113885. #ifdef _MSC_VER
  113886. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  113887. #endif
  113888. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  113889. #if JUCE_USE_OGGVORBIS
  113890. #include <math.h>
  113891. /********* Start of inlined file: lookup.h *********/
  113892. #ifndef _V_LOOKUP_H_
  113893. #ifdef FLOAT_LOOKUP
  113894. extern float vorbis_coslook(float a);
  113895. extern float vorbis_invsqlook(float a);
  113896. extern float vorbis_invsq2explook(int a);
  113897. extern float vorbis_fromdBlook(float a);
  113898. #endif
  113899. #ifdef INT_LOOKUP
  113900. extern long vorbis_invsqlook_i(long a,long e);
  113901. extern long vorbis_coslook_i(long a);
  113902. extern float vorbis_fromdBlook_i(long a);
  113903. #endif
  113904. #endif
  113905. /********* End of inlined file: lookup.h *********/
  113906. /********* Start of inlined file: lookup_data.h *********/
  113907. #ifndef _V_LOOKUP_DATA_H_
  113908. #ifdef FLOAT_LOOKUP
  113909. #define COS_LOOKUP_SZ 128
  113910. static float COS_LOOKUP[COS_LOOKUP_SZ+1]={
  113911. +1.0000000000000f,+0.9996988186962f,+0.9987954562052f,+0.9972904566787f,
  113912. +0.9951847266722f,+0.9924795345987f,+0.9891765099648f,+0.9852776423889f,
  113913. +0.9807852804032f,+0.9757021300385f,+0.9700312531945f,+0.9637760657954f,
  113914. +0.9569403357322f,+0.9495281805930f,+0.9415440651830f,+0.9329927988347f,
  113915. +0.9238795325113f,+0.9142097557035f,+0.9039892931234f,+0.8932243011955f,
  113916. +0.8819212643484f,+0.8700869911087f,+0.8577286100003f,+0.8448535652497f,
  113917. +0.8314696123025f,+0.8175848131516f,+0.8032075314806f,+0.7883464276266f,
  113918. +0.7730104533627f,+0.7572088465065f,+0.7409511253550f,+0.7242470829515f,
  113919. +0.7071067811865f,+0.6895405447371f,+0.6715589548470f,+0.6531728429538f,
  113920. +0.6343932841636f,+0.6152315905806f,+0.5956993044924f,+0.5758081914178f,
  113921. +0.5555702330196f,+0.5349976198871f,+0.5141027441932f,+0.4928981922298f,
  113922. +0.4713967368260f,+0.4496113296546f,+0.4275550934303f,+0.4052413140050f,
  113923. +0.3826834323651f,+0.3598950365350f,+0.3368898533922f,+0.3136817403989f,
  113924. +0.2902846772545f,+0.2667127574749f,+0.2429801799033f,+0.2191012401569f,
  113925. +0.1950903220161f,+0.1709618887603f,+0.1467304744554f,+0.1224106751992f,
  113926. +0.0980171403296f,+0.0735645635997f,+0.0490676743274f,+0.0245412285229f,
  113927. +0.0000000000000f,-0.0245412285229f,-0.0490676743274f,-0.0735645635997f,
  113928. -0.0980171403296f,-0.1224106751992f,-0.1467304744554f,-0.1709618887603f,
  113929. -0.1950903220161f,-0.2191012401569f,-0.2429801799033f,-0.2667127574749f,
  113930. -0.2902846772545f,-0.3136817403989f,-0.3368898533922f,-0.3598950365350f,
  113931. -0.3826834323651f,-0.4052413140050f,-0.4275550934303f,-0.4496113296546f,
  113932. -0.4713967368260f,-0.4928981922298f,-0.5141027441932f,-0.5349976198871f,
  113933. -0.5555702330196f,-0.5758081914178f,-0.5956993044924f,-0.6152315905806f,
  113934. -0.6343932841636f,-0.6531728429538f,-0.6715589548470f,-0.6895405447371f,
  113935. -0.7071067811865f,-0.7242470829515f,-0.7409511253550f,-0.7572088465065f,
  113936. -0.7730104533627f,-0.7883464276266f,-0.8032075314806f,-0.8175848131516f,
  113937. -0.8314696123025f,-0.8448535652497f,-0.8577286100003f,-0.8700869911087f,
  113938. -0.8819212643484f,-0.8932243011955f,-0.9039892931234f,-0.9142097557035f,
  113939. -0.9238795325113f,-0.9329927988347f,-0.9415440651830f,-0.9495281805930f,
  113940. -0.9569403357322f,-0.9637760657954f,-0.9700312531945f,-0.9757021300385f,
  113941. -0.9807852804032f,-0.9852776423889f,-0.9891765099648f,-0.9924795345987f,
  113942. -0.9951847266722f,-0.9972904566787f,-0.9987954562052f,-0.9996988186962f,
  113943. -1.0000000000000f,
  113944. };
  113945. #define INVSQ_LOOKUP_SZ 32
  113946. static float INVSQ_LOOKUP[INVSQ_LOOKUP_SZ+1]={
  113947. 1.414213562373f,1.392621247646f,1.371988681140f,1.352246807566f,
  113948. 1.333333333333f,1.315191898443f,1.297771369046f,1.281025230441f,
  113949. 1.264911064067f,1.249390095109f,1.234426799697f,1.219988562661f,
  113950. 1.206045378311f,1.192569588000f,1.179535649239f,1.166919931983f,
  113951. 1.154700538379f,1.142857142857f,1.131370849898f,1.120224067222f,
  113952. 1.109400392450f,1.098884511590f,1.088662107904f,1.078719779941f,
  113953. 1.069044967650f,1.059625885652f,1.050451462878f,1.041511287847f,
  113954. 1.032795558989f,1.024295039463f,1.016001016002f,1.007905261358f,
  113955. 1.000000000000f,
  113956. };
  113957. #define INVSQ2EXP_LOOKUP_MIN (-32)
  113958. #define INVSQ2EXP_LOOKUP_MAX 32
  113959. static float INVSQ2EXP_LOOKUP[INVSQ2EXP_LOOKUP_MAX-\
  113960. INVSQ2EXP_LOOKUP_MIN+1]={
  113961. 65536.f, 46340.95001f, 32768.f, 23170.47501f,
  113962. 16384.f, 11585.2375f, 8192.f, 5792.618751f,
  113963. 4096.f, 2896.309376f, 2048.f, 1448.154688f,
  113964. 1024.f, 724.0773439f, 512.f, 362.038672f,
  113965. 256.f, 181.019336f, 128.f, 90.50966799f,
  113966. 64.f, 45.254834f, 32.f, 22.627417f,
  113967. 16.f, 11.3137085f, 8.f, 5.656854249f,
  113968. 4.f, 2.828427125f, 2.f, 1.414213562f,
  113969. 1.f, 0.7071067812f, 0.5f, 0.3535533906f,
  113970. 0.25f, 0.1767766953f, 0.125f, 0.08838834765f,
  113971. 0.0625f, 0.04419417382f, 0.03125f, 0.02209708691f,
  113972. 0.015625f, 0.01104854346f, 0.0078125f, 0.005524271728f,
  113973. 0.00390625f, 0.002762135864f, 0.001953125f, 0.001381067932f,
  113974. 0.0009765625f, 0.000690533966f, 0.00048828125f, 0.000345266983f,
  113975. 0.000244140625f,0.0001726334915f,0.0001220703125f,8.631674575e-05f,
  113976. 6.103515625e-05f,4.315837288e-05f,3.051757812e-05f,2.157918644e-05f,
  113977. 1.525878906e-05f,
  113978. };
  113979. #endif
  113980. #define FROMdB_LOOKUP_SZ 35
  113981. #define FROMdB2_LOOKUP_SZ 32
  113982. #define FROMdB_SHIFT 5
  113983. #define FROMdB2_SHIFT 3
  113984. #define FROMdB2_MASK 31
  113985. static float FROMdB_LOOKUP[FROMdB_LOOKUP_SZ]={
  113986. 1.f, 0.6309573445f, 0.3981071706f, 0.2511886432f,
  113987. 0.1584893192f, 0.1f, 0.06309573445f, 0.03981071706f,
  113988. 0.02511886432f, 0.01584893192f, 0.01f, 0.006309573445f,
  113989. 0.003981071706f, 0.002511886432f, 0.001584893192f, 0.001f,
  113990. 0.0006309573445f,0.0003981071706f,0.0002511886432f,0.0001584893192f,
  113991. 0.0001f,6.309573445e-05f,3.981071706e-05f,2.511886432e-05f,
  113992. 1.584893192e-05f, 1e-05f,6.309573445e-06f,3.981071706e-06f,
  113993. 2.511886432e-06f,1.584893192e-06f, 1e-06f,6.309573445e-07f,
  113994. 3.981071706e-07f,2.511886432e-07f,1.584893192e-07f,
  113995. };
  113996. static float FROMdB2_LOOKUP[FROMdB2_LOOKUP_SZ]={
  113997. 0.9928302478f, 0.9786445908f, 0.9646616199f, 0.9508784391f,
  113998. 0.9372921937f, 0.92390007f, 0.9106992942f, 0.8976871324f,
  113999. 0.8848608897f, 0.8722179097f, 0.8597555737f, 0.8474713009f,
  114000. 0.835362547f, 0.8234268041f, 0.8116616003f, 0.8000644989f,
  114001. 0.7886330981f, 0.7773650302f, 0.7662579617f, 0.755309592f,
  114002. 0.7445176537f, 0.7338799116f, 0.7233941627f, 0.7130582353f,
  114003. 0.7028699885f, 0.6928273125f, 0.6829281272f, 0.6731703824f,
  114004. 0.6635520573f, 0.6540711597f, 0.6447257262f, 0.6355138211f,
  114005. };
  114006. #ifdef INT_LOOKUP
  114007. #define INVSQ_LOOKUP_I_SHIFT 10
  114008. #define INVSQ_LOOKUP_I_MASK 1023
  114009. static long INVSQ_LOOKUP_I[64+1]={
  114010. 92682l, 91966l, 91267l, 90583l,
  114011. 89915l, 89261l, 88621l, 87995l,
  114012. 87381l, 86781l, 86192l, 85616l,
  114013. 85051l, 84497l, 83953l, 83420l,
  114014. 82897l, 82384l, 81880l, 81385l,
  114015. 80899l, 80422l, 79953l, 79492l,
  114016. 79039l, 78594l, 78156l, 77726l,
  114017. 77302l, 76885l, 76475l, 76072l,
  114018. 75674l, 75283l, 74898l, 74519l,
  114019. 74146l, 73778l, 73415l, 73058l,
  114020. 72706l, 72359l, 72016l, 71679l,
  114021. 71347l, 71019l, 70695l, 70376l,
  114022. 70061l, 69750l, 69444l, 69141l,
  114023. 68842l, 68548l, 68256l, 67969l,
  114024. 67685l, 67405l, 67128l, 66855l,
  114025. 66585l, 66318l, 66054l, 65794l,
  114026. 65536l,
  114027. };
  114028. #define COS_LOOKUP_I_SHIFT 9
  114029. #define COS_LOOKUP_I_MASK 511
  114030. #define COS_LOOKUP_I_SZ 128
  114031. static long COS_LOOKUP_I[COS_LOOKUP_I_SZ+1]={
  114032. 16384l, 16379l, 16364l, 16340l,
  114033. 16305l, 16261l, 16207l, 16143l,
  114034. 16069l, 15986l, 15893l, 15791l,
  114035. 15679l, 15557l, 15426l, 15286l,
  114036. 15137l, 14978l, 14811l, 14635l,
  114037. 14449l, 14256l, 14053l, 13842l,
  114038. 13623l, 13395l, 13160l, 12916l,
  114039. 12665l, 12406l, 12140l, 11866l,
  114040. 11585l, 11297l, 11003l, 10702l,
  114041. 10394l, 10080l, 9760l, 9434l,
  114042. 9102l, 8765l, 8423l, 8076l,
  114043. 7723l, 7366l, 7005l, 6639l,
  114044. 6270l, 5897l, 5520l, 5139l,
  114045. 4756l, 4370l, 3981l, 3590l,
  114046. 3196l, 2801l, 2404l, 2006l,
  114047. 1606l, 1205l, 804l, 402l,
  114048. 0l, -401l, -803l, -1204l,
  114049. -1605l, -2005l, -2403l, -2800l,
  114050. -3195l, -3589l, -3980l, -4369l,
  114051. -4755l, -5138l, -5519l, -5896l,
  114052. -6269l, -6638l, -7004l, -7365l,
  114053. -7722l, -8075l, -8422l, -8764l,
  114054. -9101l, -9433l, -9759l, -10079l,
  114055. -10393l, -10701l, -11002l, -11296l,
  114056. -11584l, -11865l, -12139l, -12405l,
  114057. -12664l, -12915l, -13159l, -13394l,
  114058. -13622l, -13841l, -14052l, -14255l,
  114059. -14448l, -14634l, -14810l, -14977l,
  114060. -15136l, -15285l, -15425l, -15556l,
  114061. -15678l, -15790l, -15892l, -15985l,
  114062. -16068l, -16142l, -16206l, -16260l,
  114063. -16304l, -16339l, -16363l, -16378l,
  114064. -16383l,
  114065. };
  114066. #endif
  114067. #endif
  114068. /********* End of inlined file: lookup_data.h *********/
  114069. #ifdef FLOAT_LOOKUP
  114070. /* interpolated lookup based cos function, domain 0 to PI only */
  114071. float vorbis_coslook(float a){
  114072. double d=a*(.31830989*(float)COS_LOOKUP_SZ);
  114073. int i=vorbis_ftoi(d-.5);
  114074. return COS_LOOKUP[i]+ (d-i)*(COS_LOOKUP[i+1]-COS_LOOKUP[i]);
  114075. }
  114076. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114077. float vorbis_invsqlook(float a){
  114078. double d=a*(2.f*(float)INVSQ_LOOKUP_SZ)-(float)INVSQ_LOOKUP_SZ;
  114079. int i=vorbis_ftoi(d-.5f);
  114080. return INVSQ_LOOKUP[i]+ (d-i)*(INVSQ_LOOKUP[i+1]-INVSQ_LOOKUP[i]);
  114081. }
  114082. /* interpolated 1./sqrt(p) where .5 <= p < 1. */
  114083. float vorbis_invsq2explook(int a){
  114084. return INVSQ2EXP_LOOKUP[a-INVSQ2EXP_LOOKUP_MIN];
  114085. }
  114086. #include <stdio.h>
  114087. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114088. float vorbis_fromdBlook(float a){
  114089. int i=vorbis_ftoi(a*((float)(-(1<<FROMdB2_SHIFT)))-.5f);
  114090. return (i<0)?1.f:
  114091. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114092. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114093. }
  114094. #endif
  114095. #ifdef INT_LOOKUP
  114096. /* interpolated 1./sqrt(p) where .5 <= a < 1. (.100000... to .111111...) in
  114097. 16.16 format
  114098. returns in m.8 format */
  114099. long vorbis_invsqlook_i(long a,long e){
  114100. long i=(a&0x7fff)>>(INVSQ_LOOKUP_I_SHIFT-1);
  114101. long d=(a&INVSQ_LOOKUP_I_MASK)<<(16-INVSQ_LOOKUP_I_SHIFT); /* 0.16 */
  114102. long val=INVSQ_LOOKUP_I[i]- /* 1.16 */
  114103. (((INVSQ_LOOKUP_I[i]-INVSQ_LOOKUP_I[i+1])* /* 0.16 */
  114104. d)>>16); /* result 1.16 */
  114105. e+=32;
  114106. if(e&1)val=(val*5792)>>13; /* multiply val by 1/sqrt(2) */
  114107. e=(e>>1)-8;
  114108. return(val>>e);
  114109. }
  114110. /* interpolated lookup based fromdB function, domain -140dB to 0dB only */
  114111. /* a is in n.12 format */
  114112. float vorbis_fromdBlook_i(long a){
  114113. int i=(-a)>>(12-FROMdB2_SHIFT);
  114114. return (i<0)?1.f:
  114115. ((i>=(FROMdB_LOOKUP_SZ<<FROMdB_SHIFT))?0.f:
  114116. FROMdB_LOOKUP[i>>FROMdB_SHIFT]*FROMdB2_LOOKUP[i&FROMdB2_MASK]);
  114117. }
  114118. /* interpolated lookup based cos function, domain 0 to PI only */
  114119. /* a is in 0.16 format, where 0==0, 2^^16-1==PI, return 0.14 */
  114120. long vorbis_coslook_i(long a){
  114121. int i=a>>COS_LOOKUP_I_SHIFT;
  114122. int d=a&COS_LOOKUP_I_MASK;
  114123. return COS_LOOKUP_I[i]- ((d*(COS_LOOKUP_I[i]-COS_LOOKUP_I[i+1]))>>
  114124. COS_LOOKUP_I_SHIFT);
  114125. }
  114126. #endif
  114127. #endif
  114128. /********* End of inlined file: lookup.c *********/
  114129. /* catch this in the build system; we #include for
  114130. compilers (like gcc) that can't inline across
  114131. modules */
  114132. static int MLOOP_1[64]={
  114133. 0,10,11,11, 12,12,12,12, 13,13,13,13, 13,13,13,13,
  114134. 14,14,14,14, 14,14,14,14, 14,14,14,14, 14,14,14,14,
  114135. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114136. 15,15,15,15, 15,15,15,15, 15,15,15,15, 15,15,15,15,
  114137. };
  114138. static int MLOOP_2[64]={
  114139. 0,4,5,5, 6,6,6,6, 7,7,7,7, 7,7,7,7,
  114140. 8,8,8,8, 8,8,8,8, 8,8,8,8, 8,8,8,8,
  114141. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114142. 9,9,9,9, 9,9,9,9, 9,9,9,9, 9,9,9,9,
  114143. };
  114144. static int MLOOP_3[8]={0,1,2,2,3,3,3,3};
  114145. /* side effect: changes *lsp to cosines of lsp */
  114146. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114147. float amp,float ampoffset){
  114148. /* 0 <= m < 256 */
  114149. /* set up for using all int later */
  114150. int i;
  114151. int ampoffseti=rint(ampoffset*4096.f);
  114152. int ampi=rint(amp*16.f);
  114153. long *ilsp=alloca(m*sizeof(*ilsp));
  114154. for(i=0;i<m;i++)ilsp[i]=vorbis_coslook_i(lsp[i]/M_PI*65536.f+.5f);
  114155. i=0;
  114156. while(i<n){
  114157. int j,k=map[i];
  114158. unsigned long pi=46341; /* 2**-.5 in 0.16 */
  114159. unsigned long qi=46341;
  114160. int qexp=0,shift;
  114161. long wi=vorbis_coslook_i(k*65536/ln);
  114162. qi*=labs(ilsp[0]-wi);
  114163. pi*=labs(ilsp[1]-wi);
  114164. for(j=3;j<m;j+=2){
  114165. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114166. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114167. shift=MLOOP_3[(pi|qi)>>16];
  114168. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114169. pi=(pi>>shift)*labs(ilsp[j]-wi);
  114170. qexp+=shift;
  114171. }
  114172. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114173. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114174. shift=MLOOP_3[(pi|qi)>>16];
  114175. /* pi,qi normalized collectively, both tracked using qexp */
  114176. if(m&1){
  114177. /* odd order filter; slightly assymetric */
  114178. /* the last coefficient */
  114179. qi=(qi>>shift)*labs(ilsp[j-1]-wi);
  114180. pi=(pi>>shift)<<14;
  114181. qexp+=shift;
  114182. if(!(shift=MLOOP_1[(pi|qi)>>25]))
  114183. if(!(shift=MLOOP_2[(pi|qi)>>19]))
  114184. shift=MLOOP_3[(pi|qi)>>16];
  114185. pi>>=shift;
  114186. qi>>=shift;
  114187. qexp+=shift-14*((m+1)>>1);
  114188. pi=((pi*pi)>>16);
  114189. qi=((qi*qi)>>16);
  114190. qexp=qexp*2+m;
  114191. pi*=(1<<14)-((wi*wi)>>14);
  114192. qi+=pi>>14;
  114193. }else{
  114194. /* even order filter; still symmetric */
  114195. /* p*=p(1-w), q*=q(1+w), let normalization drift because it isn't
  114196. worth tracking step by step */
  114197. pi>>=shift;
  114198. qi>>=shift;
  114199. qexp+=shift-7*m;
  114200. pi=((pi*pi)>>16);
  114201. qi=((qi*qi)>>16);
  114202. qexp=qexp*2+m;
  114203. pi*=(1<<14)-wi;
  114204. qi*=(1<<14)+wi;
  114205. qi=(qi+pi)>>14;
  114206. }
  114207. /* we've let the normalization drift because it wasn't important;
  114208. however, for the lookup, things must be normalized again. We
  114209. need at most one right shift or a number of left shifts */
  114210. if(qi&0xffff0000){ /* checks for 1.xxxxxxxxxxxxxxxx */
  114211. qi>>=1; qexp++;
  114212. }else
  114213. while(qi && !(qi&0x8000)){ /* checks for 0.0xxxxxxxxxxxxxxx or less*/
  114214. qi<<=1; qexp--;
  114215. }
  114216. amp=vorbis_fromdBlook_i(ampi* /* n.4 */
  114217. vorbis_invsqlook_i(qi,qexp)-
  114218. /* m.8, m+n<=8 */
  114219. ampoffseti); /* 8.12[0] */
  114220. curve[i]*=amp;
  114221. while(map[++i]==k)curve[i]*=amp;
  114222. }
  114223. }
  114224. #else
  114225. /* old, nonoptimized but simple version for any poor sap who needs to
  114226. figure out what the hell this code does, or wants the other
  114227. fraction of a dB precision */
  114228. /* side effect: changes *lsp to cosines of lsp */
  114229. void vorbis_lsp_to_curve(float *curve,int *map,int n,int ln,float *lsp,int m,
  114230. float amp,float ampoffset){
  114231. int i;
  114232. float wdel=M_PI/ln;
  114233. for(i=0;i<m;i++)lsp[i]=2.f*cos(lsp[i]);
  114234. i=0;
  114235. while(i<n){
  114236. int j,k=map[i];
  114237. float p=.5f;
  114238. float q=.5f;
  114239. float w=2.f*cos(wdel*k);
  114240. for(j=1;j<m;j+=2){
  114241. q *= w-lsp[j-1];
  114242. p *= w-lsp[j];
  114243. }
  114244. if(j==m){
  114245. /* odd order filter; slightly assymetric */
  114246. /* the last coefficient */
  114247. q*=w-lsp[j-1];
  114248. p*=p*(4.f-w*w);
  114249. q*=q;
  114250. }else{
  114251. /* even order filter; still symmetric */
  114252. p*=p*(2.f-w);
  114253. q*=q*(2.f+w);
  114254. }
  114255. q=fromdB(amp/sqrt(p+q)-ampoffset);
  114256. curve[i]*=q;
  114257. while(map[++i]==k)curve[i]*=q;
  114258. }
  114259. }
  114260. #endif
  114261. #endif
  114262. static void cheby(float *g, int ord) {
  114263. int i, j;
  114264. g[0] *= .5f;
  114265. for(i=2; i<= ord; i++) {
  114266. for(j=ord; j >= i; j--) {
  114267. g[j-2] -= g[j];
  114268. g[j] += g[j];
  114269. }
  114270. }
  114271. }
  114272. static int comp(const void *a,const void *b){
  114273. return (*(float *)a<*(float *)b)-(*(float *)a>*(float *)b);
  114274. }
  114275. /* Newton-Raphson-Maehly actually functioned as a decent root finder,
  114276. but there are root sets for which it gets into limit cycles
  114277. (exacerbated by zero suppression) and fails. We can't afford to
  114278. fail, even if the failure is 1 in 100,000,000, so we now use
  114279. Laguerre and later polish with Newton-Raphson (which can then
  114280. afford to fail) */
  114281. #define EPSILON 10e-7
  114282. static int Laguerre_With_Deflation(float *a,int ord,float *r){
  114283. int i,m;
  114284. double lastdelta=0.f;
  114285. double *defl=(double*)alloca(sizeof(*defl)*(ord+1));
  114286. for(i=0;i<=ord;i++)defl[i]=a[i];
  114287. for(m=ord;m>0;m--){
  114288. double newx=0.f,delta;
  114289. /* iterate a root */
  114290. while(1){
  114291. double p=defl[m],pp=0.f,ppp=0.f,denom;
  114292. /* eval the polynomial and its first two derivatives */
  114293. for(i=m;i>0;i--){
  114294. ppp = newx*ppp + pp;
  114295. pp = newx*pp + p;
  114296. p = newx*p + defl[i-1];
  114297. }
  114298. /* Laguerre's method */
  114299. denom=(m-1) * ((m-1)*pp*pp - m*p*ppp);
  114300. if(denom<0)
  114301. return(-1); /* complex root! The LPC generator handed us a bad filter */
  114302. if(pp>0){
  114303. denom = pp + sqrt(denom);
  114304. if(denom<EPSILON)denom=EPSILON;
  114305. }else{
  114306. denom = pp - sqrt(denom);
  114307. if(denom>-(EPSILON))denom=-(EPSILON);
  114308. }
  114309. delta = m*p/denom;
  114310. newx -= delta;
  114311. if(delta<0.f)delta*=-1;
  114312. if(fabs(delta/newx)<10e-12)break;
  114313. lastdelta=delta;
  114314. }
  114315. r[m-1]=newx;
  114316. /* forward deflation */
  114317. for(i=m;i>0;i--)
  114318. defl[i-1]+=newx*defl[i];
  114319. defl++;
  114320. }
  114321. return(0);
  114322. }
  114323. /* for spit-and-polish only */
  114324. static int Newton_Raphson(float *a,int ord,float *r){
  114325. int i, k, count=0;
  114326. double error=1.f;
  114327. double *root=(double*)alloca(ord*sizeof(*root));
  114328. for(i=0; i<ord;i++) root[i] = r[i];
  114329. while(error>1e-20){
  114330. error=0;
  114331. for(i=0; i<ord; i++) { /* Update each point. */
  114332. double pp=0.,delta;
  114333. double rooti=root[i];
  114334. double p=a[ord];
  114335. for(k=ord-1; k>= 0; k--) {
  114336. pp= pp* rooti + p;
  114337. p = p * rooti + a[k];
  114338. }
  114339. delta = p/pp;
  114340. root[i] -= delta;
  114341. error+= delta*delta;
  114342. }
  114343. if(count>40)return(-1);
  114344. count++;
  114345. }
  114346. /* Replaced the original bubble sort with a real sort. With your
  114347. help, we can eliminate the bubble sort in our lifetime. --Monty */
  114348. for(i=0; i<ord;i++) r[i] = root[i];
  114349. return(0);
  114350. }
  114351. /* Convert lpc coefficients to lsp coefficients */
  114352. int vorbis_lpc_to_lsp(float *lpc,float *lsp,int m){
  114353. int order2=(m+1)>>1;
  114354. int g1_order,g2_order;
  114355. float *g1=(float*)alloca(sizeof(*g1)*(order2+1));
  114356. float *g2=(float*)alloca(sizeof(*g2)*(order2+1));
  114357. float *g1r=(float*)alloca(sizeof(*g1r)*(order2+1));
  114358. float *g2r=(float*)alloca(sizeof(*g2r)*(order2+1));
  114359. int i;
  114360. /* even and odd are slightly different base cases */
  114361. g1_order=(m+1)>>1;
  114362. g2_order=(m) >>1;
  114363. /* Compute the lengths of the x polynomials. */
  114364. /* Compute the first half of K & R F1 & F2 polynomials. */
  114365. /* Compute half of the symmetric and antisymmetric polynomials. */
  114366. /* Remove the roots at +1 and -1. */
  114367. g1[g1_order] = 1.f;
  114368. for(i=1;i<=g1_order;i++) g1[g1_order-i] = lpc[i-1]+lpc[m-i];
  114369. g2[g2_order] = 1.f;
  114370. for(i=1;i<=g2_order;i++) g2[g2_order-i] = lpc[i-1]-lpc[m-i];
  114371. if(g1_order>g2_order){
  114372. for(i=2; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+2];
  114373. }else{
  114374. for(i=1; i<=g1_order;i++) g1[g1_order-i] -= g1[g1_order-i+1];
  114375. for(i=1; i<=g2_order;i++) g2[g2_order-i] += g2[g2_order-i+1];
  114376. }
  114377. /* Convert into polynomials in cos(alpha) */
  114378. cheby(g1,g1_order);
  114379. cheby(g2,g2_order);
  114380. /* Find the roots of the 2 even polynomials.*/
  114381. if(Laguerre_With_Deflation(g1,g1_order,g1r) ||
  114382. Laguerre_With_Deflation(g2,g2_order,g2r))
  114383. return(-1);
  114384. Newton_Raphson(g1,g1_order,g1r); /* if it fails, it leaves g1r alone */
  114385. Newton_Raphson(g2,g2_order,g2r); /* if it fails, it leaves g2r alone */
  114386. qsort(g1r,g1_order,sizeof(*g1r),comp);
  114387. qsort(g2r,g2_order,sizeof(*g2r),comp);
  114388. for(i=0;i<g1_order;i++)
  114389. lsp[i*2] = acos(g1r[i]);
  114390. for(i=0;i<g2_order;i++)
  114391. lsp[i*2+1] = acos(g2r[i]);
  114392. return(0);
  114393. }
  114394. #endif
  114395. /********* End of inlined file: lsp.c *********/
  114396. /********* Start of inlined file: mapping0.c *********/
  114397. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  114398. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  114399. // tasks..
  114400. /********* Start of inlined file: juce_Config.h *********/
  114401. #ifndef __JUCE_CONFIG_JUCEHEADER__
  114402. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  114403. /*
  114404. This file contains macros that enable/disable various JUCE features.
  114405. */
  114406. /** The name of the namespace that all Juce classes and functions will be
  114407. put inside. If this is not defined, no namespace will be used.
  114408. */
  114409. #ifndef JUCE_NAMESPACE
  114410. #define JUCE_NAMESPACE juce
  114411. #endif
  114412. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  114413. but if you define this value, you can override this can force it to be true or
  114414. false.
  114415. */
  114416. #ifndef JUCE_FORCE_DEBUG
  114417. //#define JUCE_FORCE_DEBUG 1
  114418. #endif
  114419. /** If this flag is enabled, the the jassert and jassertfalse macros will
  114420. always use Logger::writeToLog() to write a message when an assertion happens.
  114421. Enabling it will also leave this turned on in release builds. When it's disabled,
  114422. however, the jassert and jassertfalse macros will not be compiled in a
  114423. release build.
  114424. @see jassert, jassertfalse, Logger
  114425. */
  114426. #ifndef JUCE_LOG_ASSERTIONS
  114427. // #define JUCE_LOG_ASSERTIONS 1
  114428. #endif
  114429. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  114430. which the ASIOAudioIODevice class can't be built. See the comments in the
  114431. ASIOAudioIODevice class's header file for more info about this.
  114432. (This only affects a Win32 build)
  114433. */
  114434. #ifndef JUCE_ASIO
  114435. #define JUCE_ASIO 1
  114436. #endif
  114437. /** Comment out this macro to disable building of ALSA device support on Linux.
  114438. */
  114439. #ifndef JUCE_ALSA
  114440. #define JUCE_ALSA 1
  114441. #endif
  114442. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  114443. have the SDK installed.
  114444. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  114445. classes will be unavailable.
  114446. On Windows, if you enable this, you'll need to have the QuickTime SDK
  114447. installed, and its header files will need to be on your include path.
  114448. */
  114449. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  114450. #define JUCE_QUICKTIME 1
  114451. #endif
  114452. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  114453. have the appropriate headers and libraries available. If it's not enabled, the
  114454. OpenGLComponent class will be unavailable.
  114455. */
  114456. #ifndef JUCE_OPENGL
  114457. #define JUCE_OPENGL 1
  114458. #endif
  114459. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  114460. If you're not going to need either of these formats, turn off the flags to
  114461. avoid bloating your codebase with them.
  114462. */
  114463. #ifndef JUCE_USE_FLAC
  114464. #define JUCE_USE_FLAC 1
  114465. #endif
  114466. #ifndef JUCE_USE_OGGVORBIS
  114467. #define JUCE_USE_OGGVORBIS 1
  114468. #endif
  114469. /** This flag lets you enable support for CD-burning. You might want to disable
  114470. it to build without the MS SDK under windows.
  114471. */
  114472. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  114473. #define JUCE_USE_CDBURNER 1
  114474. #endif
  114475. /** Enabling this macro means that all regions that get repainted will have a coloured
  114476. line drawn around them.
  114477. This is handy if you're trying to optimise drawing, because it lets you easily see
  114478. when anything is being repainted unnecessarily.
  114479. */
  114480. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  114481. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  114482. #endif
  114483. /** Enable this under Linux to use Xinerama for multi-monitor support.
  114484. */
  114485. #ifndef JUCE_USE_XINERAMA
  114486. #define JUCE_USE_XINERAMA 1
  114487. #endif
  114488. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  114489. */
  114490. #ifndef JUCE_USE_XSHM
  114491. #define JUCE_USE_XSHM 1
  114492. #endif
  114493. /** Enabling this builds support for VST audio plugins.
  114494. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  114495. */
  114496. #ifndef JUCE_PLUGINHOST_VST
  114497. // #define JUCE_PLUGINHOST_VST 1
  114498. #endif
  114499. /** Enabling this builds support for AudioUnit audio plugins.
  114500. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  114501. */
  114502. #ifndef JUCE_PLUGINHOST_AU
  114503. // #define JUCE_PLUGINHOST_AU 1
  114504. #endif
  114505. /** Disabling this will avoid linking to any UI code. This is handy for
  114506. writing command-line utilities, e.g. on linux boxes which don't have some
  114507. of the UI libraries installed.
  114508. (On mac and windows, this won't generally make much difference to the build).
  114509. */
  114510. #ifndef JUCE_BUILD_GUI_CLASSES
  114511. #define JUCE_BUILD_GUI_CLASSES 1
  114512. #endif
  114513. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  114514. */
  114515. #ifndef JUCE_WEB_BROWSER
  114516. #define JUCE_WEB_BROWSER 1
  114517. #endif
  114518. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  114519. codebase - you might need to use this if you're linking to some of these libraries
  114520. yourself.
  114521. */
  114522. #ifndef JUCE_INCLUDE_ZLIB_CODE
  114523. #define JUCE_INCLUDE_ZLIB_CODE 1
  114524. #endif
  114525. #ifndef JUCE_INCLUDE_FLAC_CODE
  114526. #define JUCE_INCLUDE_FLAC_CODE 1
  114527. #endif
  114528. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  114529. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  114530. #endif
  114531. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  114532. #define JUCE_INCLUDE_PNGLIB_CODE 1
  114533. #endif
  114534. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  114535. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  114536. #endif
  114537. /** Enable this to add extra memory-leak info to the new and delete operators.
  114538. (Currently, this only affects Windows builds in debug mode).
  114539. */
  114540. #ifndef JUCE_CHECK_MEMORY_LEAKS
  114541. #define JUCE_CHECK_MEMORY_LEAKS 1
  114542. #endif
  114543. /** Enable this to turn on juce's internal catching of exceptions.
  114544. Turning it off will avoid any exception catching. With it on, all exceptions
  114545. are passed to the JUCEApplication::unhandledException() callback for logging.
  114546. */
  114547. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  114548. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  114549. #endif
  114550. /** If this macro is set, the Juce String class will use unicode as its
  114551. internal representation. If it isn't set, it'll use ANSI.
  114552. */
  114553. #ifndef JUCE_STRINGS_ARE_UNICODE
  114554. #define JUCE_STRINGS_ARE_UNICODE 1
  114555. #endif
  114556. #endif
  114557. /********* End of inlined file: juce_Config.h *********/
  114558. #ifdef _MSC_VER
  114559. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  114560. #endif
  114561. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  114562. #if JUCE_USE_OGGVORBIS
  114563. #include <stdlib.h>
  114564. #include <stdio.h>
  114565. #include <string.h>
  114566. #include <math.h>
  114567. /* simplistic, wasteful way of doing this (unique lookup for each
  114568. mode/submapping); there should be a central repository for
  114569. identical lookups. That will require minor work, so I'm putting it
  114570. off as low priority.
  114571. Why a lookup for each backend in a given mode? Because the
  114572. blocksize is set by the mode, and low backend lookups may require
  114573. parameters from other areas of the mode/mapping */
  114574. static void mapping0_free_info(vorbis_info_mapping *i){
  114575. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)i;
  114576. if(info){
  114577. memset(info,0,sizeof(*info));
  114578. _ogg_free(info);
  114579. }
  114580. }
  114581. static int ilog3(unsigned int v){
  114582. int ret=0;
  114583. if(v)--v;
  114584. while(v){
  114585. ret++;
  114586. v>>=1;
  114587. }
  114588. return(ret);
  114589. }
  114590. static void mapping0_pack(vorbis_info *vi,vorbis_info_mapping *vm,
  114591. oggpack_buffer *opb){
  114592. int i;
  114593. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)vm;
  114594. /* another 'we meant to do it this way' hack... up to beta 4, we
  114595. packed 4 binary zeros here to signify one submapping in use. We
  114596. now redefine that to mean four bitflags that indicate use of
  114597. deeper features; bit0:submappings, bit1:coupling,
  114598. bit2,3:reserved. This is backward compatable with all actual uses
  114599. of the beta code. */
  114600. if(info->submaps>1){
  114601. oggpack_write(opb,1,1);
  114602. oggpack_write(opb,info->submaps-1,4);
  114603. }else
  114604. oggpack_write(opb,0,1);
  114605. if(info->coupling_steps>0){
  114606. oggpack_write(opb,1,1);
  114607. oggpack_write(opb,info->coupling_steps-1,8);
  114608. for(i=0;i<info->coupling_steps;i++){
  114609. oggpack_write(opb,info->coupling_mag[i],ilog3(vi->channels));
  114610. oggpack_write(opb,info->coupling_ang[i],ilog3(vi->channels));
  114611. }
  114612. }else
  114613. oggpack_write(opb,0,1);
  114614. oggpack_write(opb,0,2); /* 2,3:reserved */
  114615. /* we don't write the channel submappings if we only have one... */
  114616. if(info->submaps>1){
  114617. for(i=0;i<vi->channels;i++)
  114618. oggpack_write(opb,info->chmuxlist[i],4);
  114619. }
  114620. for(i=0;i<info->submaps;i++){
  114621. oggpack_write(opb,0,8); /* time submap unused */
  114622. oggpack_write(opb,info->floorsubmap[i],8);
  114623. oggpack_write(opb,info->residuesubmap[i],8);
  114624. }
  114625. }
  114626. /* also responsible for range checking */
  114627. static vorbis_info_mapping *mapping0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  114628. int i;
  114629. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)_ogg_calloc(1,sizeof(*info));
  114630. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114631. memset(info,0,sizeof(*info));
  114632. if(oggpack_read(opb,1))
  114633. info->submaps=oggpack_read(opb,4)+1;
  114634. else
  114635. info->submaps=1;
  114636. if(oggpack_read(opb,1)){
  114637. info->coupling_steps=oggpack_read(opb,8)+1;
  114638. for(i=0;i<info->coupling_steps;i++){
  114639. int testM=info->coupling_mag[i]=oggpack_read(opb,ilog3(vi->channels));
  114640. int testA=info->coupling_ang[i]=oggpack_read(opb,ilog3(vi->channels));
  114641. if(testM<0 ||
  114642. testA<0 ||
  114643. testM==testA ||
  114644. testM>=vi->channels ||
  114645. testA>=vi->channels) goto err_out;
  114646. }
  114647. }
  114648. if(oggpack_read(opb,2)>0)goto err_out; /* 2,3:reserved */
  114649. if(info->submaps>1){
  114650. for(i=0;i<vi->channels;i++){
  114651. info->chmuxlist[i]=oggpack_read(opb,4);
  114652. if(info->chmuxlist[i]>=info->submaps)goto err_out;
  114653. }
  114654. }
  114655. for(i=0;i<info->submaps;i++){
  114656. oggpack_read(opb,8); /* time submap unused */
  114657. info->floorsubmap[i]=oggpack_read(opb,8);
  114658. if(info->floorsubmap[i]>=ci->floors)goto err_out;
  114659. info->residuesubmap[i]=oggpack_read(opb,8);
  114660. if(info->residuesubmap[i]>=ci->residues)goto err_out;
  114661. }
  114662. return info;
  114663. err_out:
  114664. mapping0_free_info(info);
  114665. return(NULL);
  114666. }
  114667. #if 0
  114668. static long seq=0;
  114669. static ogg_int64_t total=0;
  114670. static float FLOOR1_fromdB_LOOKUP[256]={
  114671. 1.0649863e-07F, 1.1341951e-07F, 1.2079015e-07F, 1.2863978e-07F,
  114672. 1.3699951e-07F, 1.4590251e-07F, 1.5538408e-07F, 1.6548181e-07F,
  114673. 1.7623575e-07F, 1.8768855e-07F, 1.9988561e-07F, 2.128753e-07F,
  114674. 2.2670913e-07F, 2.4144197e-07F, 2.5713223e-07F, 2.7384213e-07F,
  114675. 2.9163793e-07F, 3.1059021e-07F, 3.3077411e-07F, 3.5226968e-07F,
  114676. 3.7516214e-07F, 3.9954229e-07F, 4.2550680e-07F, 4.5315863e-07F,
  114677. 4.8260743e-07F, 5.1396998e-07F, 5.4737065e-07F, 5.8294187e-07F,
  114678. 6.2082472e-07F, 6.6116941e-07F, 7.0413592e-07F, 7.4989464e-07F,
  114679. 7.9862701e-07F, 8.5052630e-07F, 9.0579828e-07F, 9.6466216e-07F,
  114680. 1.0273513e-06F, 1.0941144e-06F, 1.1652161e-06F, 1.2409384e-06F,
  114681. 1.3215816e-06F, 1.4074654e-06F, 1.4989305e-06F, 1.5963394e-06F,
  114682. 1.7000785e-06F, 1.8105592e-06F, 1.9282195e-06F, 2.0535261e-06F,
  114683. 2.1869758e-06F, 2.3290978e-06F, 2.4804557e-06F, 2.6416497e-06F,
  114684. 2.8133190e-06F, 2.9961443e-06F, 3.1908506e-06F, 3.3982101e-06F,
  114685. 3.6190449e-06F, 3.8542308e-06F, 4.1047004e-06F, 4.3714470e-06F,
  114686. 4.6555282e-06F, 4.9580707e-06F, 5.2802740e-06F, 5.6234160e-06F,
  114687. 5.9888572e-06F, 6.3780469e-06F, 6.7925283e-06F, 7.2339451e-06F,
  114688. 7.7040476e-06F, 8.2047000e-06F, 8.7378876e-06F, 9.3057248e-06F,
  114689. 9.9104632e-06F, 1.0554501e-05F, 1.1240392e-05F, 1.1970856e-05F,
  114690. 1.2748789e-05F, 1.3577278e-05F, 1.4459606e-05F, 1.5399272e-05F,
  114691. 1.6400004e-05F, 1.7465768e-05F, 1.8600792e-05F, 1.9809576e-05F,
  114692. 2.1096914e-05F, 2.2467911e-05F, 2.3928002e-05F, 2.5482978e-05F,
  114693. 2.7139006e-05F, 2.8902651e-05F, 3.0780908e-05F, 3.2781225e-05F,
  114694. 3.4911534e-05F, 3.7180282e-05F, 3.9596466e-05F, 4.2169667e-05F,
  114695. 4.4910090e-05F, 4.7828601e-05F, 5.0936773e-05F, 5.4246931e-05F,
  114696. 5.7772202e-05F, 6.1526565e-05F, 6.5524908e-05F, 6.9783085e-05F,
  114697. 7.4317983e-05F, 7.9147585e-05F, 8.4291040e-05F, 8.9768747e-05F,
  114698. 9.5602426e-05F, 0.00010181521F, 0.00010843174F, 0.00011547824F,
  114699. 0.00012298267F, 0.00013097477F, 0.00013948625F, 0.00014855085F,
  114700. 0.00015820453F, 0.00016848555F, 0.00017943469F, 0.00019109536F,
  114701. 0.00020351382F, 0.00021673929F, 0.00023082423F, 0.00024582449F,
  114702. 0.00026179955F, 0.00027881276F, 0.00029693158F, 0.00031622787F,
  114703. 0.00033677814F, 0.00035866388F, 0.00038197188F, 0.00040679456F,
  114704. 0.00043323036F, 0.00046138411F, 0.00049136745F, 0.00052329927F,
  114705. 0.00055730621F, 0.00059352311F, 0.00063209358F, 0.00067317058F,
  114706. 0.00071691700F, 0.00076350630F, 0.00081312324F, 0.00086596457F,
  114707. 0.00092223983F, 0.00098217216F, 0.0010459992F, 0.0011139742F,
  114708. 0.0011863665F, 0.0012634633F, 0.0013455702F, 0.0014330129F,
  114709. 0.0015261382F, 0.0016253153F, 0.0017309374F, 0.0018434235F,
  114710. 0.0019632195F, 0.0020908006F, 0.0022266726F, 0.0023713743F,
  114711. 0.0025254795F, 0.0026895994F, 0.0028643847F, 0.0030505286F,
  114712. 0.0032487691F, 0.0034598925F, 0.0036847358F, 0.0039241906F,
  114713. 0.0041792066F, 0.0044507950F, 0.0047400328F, 0.0050480668F,
  114714. 0.0053761186F, 0.0057254891F, 0.0060975636F, 0.0064938176F,
  114715. 0.0069158225F, 0.0073652516F, 0.0078438871F, 0.0083536271F,
  114716. 0.0088964928F, 0.009474637F, 0.010090352F, 0.010746080F,
  114717. 0.011444421F, 0.012188144F, 0.012980198F, 0.013823725F,
  114718. 0.014722068F, 0.015678791F, 0.016697687F, 0.017782797F,
  114719. 0.018938423F, 0.020169149F, 0.021479854F, 0.022875735F,
  114720. 0.024362330F, 0.025945531F, 0.027631618F, 0.029427276F,
  114721. 0.031339626F, 0.033376252F, 0.035545228F, 0.037855157F,
  114722. 0.040315199F, 0.042935108F, 0.045725273F, 0.048696758F,
  114723. 0.051861348F, 0.055231591F, 0.058820850F, 0.062643361F,
  114724. 0.066714279F, 0.071049749F, 0.075666962F, 0.080584227F,
  114725. 0.085821044F, 0.091398179F, 0.097337747F, 0.10366330F,
  114726. 0.11039993F, 0.11757434F, 0.12521498F, 0.13335215F,
  114727. 0.14201813F, 0.15124727F, 0.16107617F, 0.17154380F,
  114728. 0.18269168F, 0.19456402F, 0.20720788F, 0.22067342F,
  114729. 0.23501402F, 0.25028656F, 0.26655159F, 0.28387361F,
  114730. 0.30232132F, 0.32196786F, 0.34289114F, 0.36517414F,
  114731. 0.38890521F, 0.41417847F, 0.44109412F, 0.46975890F,
  114732. 0.50028648F, 0.53279791F, 0.56742212F, 0.60429640F,
  114733. 0.64356699F, 0.68538959F, 0.72993007F, 0.77736504F,
  114734. 0.82788260F, 0.88168307F, 0.9389798F, 1.F,
  114735. };
  114736. #endif
  114737. extern int *floor1_fit(vorbis_block *vb,void *look,
  114738. const float *logmdct, /* in */
  114739. const float *logmask);
  114740. extern int *floor1_interpolate_fit(vorbis_block *vb,void *look,
  114741. int *A,int *B,
  114742. int del);
  114743. extern int floor1_encode(oggpack_buffer *opb,vorbis_block *vb,
  114744. void*look,
  114745. int *post,int *ilogmask);
  114746. static int mapping0_forward(vorbis_block *vb){
  114747. vorbis_dsp_state *vd=vb->vd;
  114748. vorbis_info *vi=vd->vi;
  114749. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  114750. private_state *b=(private_state*)vb->vd->backend_state;
  114751. vorbis_block_internal *vbi=(vorbis_block_internal *)vb->internal;
  114752. int n=vb->pcmend;
  114753. int i,j,k;
  114754. int *nonzero = (int*) alloca(sizeof(*nonzero)*vi->channels);
  114755. float **gmdct = (float**) _vorbis_block_alloc(vb,vi->channels*sizeof(*gmdct));
  114756. int **ilogmaskch= (int**) _vorbis_block_alloc(vb,vi->channels*sizeof(*ilogmaskch));
  114757. int ***floor_posts = (int***) _vorbis_block_alloc(vb,vi->channels*sizeof(*floor_posts));
  114758. float global_ampmax=vbi->ampmax;
  114759. float *local_ampmax=(float*)alloca(sizeof(*local_ampmax)*vi->channels);
  114760. int blocktype=vbi->blocktype;
  114761. int modenumber=vb->W;
  114762. vorbis_info_mapping0 *info=(vorbis_info_mapping0*)ci->map_param[modenumber];
  114763. vorbis_look_psy *psy_look=
  114764. b->psy+blocktype+(vb->W?2:0);
  114765. vb->mode=modenumber;
  114766. for(i=0;i<vi->channels;i++){
  114767. float scale=4.f/n;
  114768. float scale_dB;
  114769. float *pcm =vb->pcm[i];
  114770. float *logfft =pcm;
  114771. gmdct[i]=(float*)_vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  114772. scale_dB=todB(&scale) + .345; /* + .345 is a hack; the original
  114773. todB estimation used on IEEE 754
  114774. compliant machines had a bug that
  114775. returned dB values about a third
  114776. of a decibel too high. The bug
  114777. was harmless because tunings
  114778. implicitly took that into
  114779. account. However, fixing the bug
  114780. in the estimator requires
  114781. changing all the tunings as well.
  114782. For now, it's easier to sync
  114783. things back up here, and
  114784. recalibrate the tunings in the
  114785. next major model upgrade. */
  114786. #if 0
  114787. if(vi->channels==2)
  114788. if(i==0)
  114789. _analysis_output("pcmL",seq,pcm,n,0,0,total-n/2);
  114790. else
  114791. _analysis_output("pcmR",seq,pcm,n,0,0,total-n/2);
  114792. #endif
  114793. /* window the PCM data */
  114794. _vorbis_apply_window(pcm,b->window,ci->blocksizes,vb->lW,vb->W,vb->nW);
  114795. #if 0
  114796. if(vi->channels==2)
  114797. if(i==0)
  114798. _analysis_output("windowedL",seq,pcm,n,0,0,total-n/2);
  114799. else
  114800. _analysis_output("windowedR",seq,pcm,n,0,0,total-n/2);
  114801. #endif
  114802. /* transform the PCM data */
  114803. /* only MDCT right now.... */
  114804. mdct_forward((mdct_lookup*) b->transform[vb->W][0],pcm,gmdct[i]);
  114805. /* FFT yields more accurate tonal estimation (not phase sensitive) */
  114806. drft_forward(&b->fft_look[vb->W],pcm);
  114807. logfft[0]=scale_dB+todB(pcm) + .345; /* + .345 is a hack; the
  114808. original todB estimation used on
  114809. IEEE 754 compliant machines had a
  114810. bug that returned dB values about
  114811. a third of a decibel too high.
  114812. The bug was harmless because
  114813. tunings implicitly took that into
  114814. account. However, fixing the bug
  114815. in the estimator requires
  114816. changing all the tunings as well.
  114817. For now, it's easier to sync
  114818. things back up here, and
  114819. recalibrate the tunings in the
  114820. next major model upgrade. */
  114821. local_ampmax[i]=logfft[0];
  114822. for(j=1;j<n-1;j+=2){
  114823. float temp=pcm[j]*pcm[j]+pcm[j+1]*pcm[j+1];
  114824. temp=logfft[(j+1)>>1]=scale_dB+.5f*todB(&temp) + .345; /* +
  114825. .345 is a hack; the original todB
  114826. estimation used on IEEE 754
  114827. compliant machines had a bug that
  114828. returned dB values about a third
  114829. of a decibel too high. The bug
  114830. was harmless because tunings
  114831. implicitly took that into
  114832. account. However, fixing the bug
  114833. in the estimator requires
  114834. changing all the tunings as well.
  114835. For now, it's easier to sync
  114836. things back up here, and
  114837. recalibrate the tunings in the
  114838. next major model upgrade. */
  114839. if(temp>local_ampmax[i])local_ampmax[i]=temp;
  114840. }
  114841. if(local_ampmax[i]>0.f)local_ampmax[i]=0.f;
  114842. if(local_ampmax[i]>global_ampmax)global_ampmax=local_ampmax[i];
  114843. #if 0
  114844. if(vi->channels==2){
  114845. if(i==0){
  114846. _analysis_output("fftL",seq,logfft,n/2,1,0,0);
  114847. }else{
  114848. _analysis_output("fftR",seq,logfft,n/2,1,0,0);
  114849. }
  114850. }
  114851. #endif
  114852. }
  114853. {
  114854. float *noise = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*noise));
  114855. float *tone = (float*) _vorbis_block_alloc(vb,n/2*sizeof(*tone));
  114856. for(i=0;i<vi->channels;i++){
  114857. /* the encoder setup assumes that all the modes used by any
  114858. specific bitrate tweaking use the same floor */
  114859. int submap=info->chmuxlist[i];
  114860. /* the following makes things clearer to *me* anyway */
  114861. float *mdct =gmdct[i];
  114862. float *logfft =vb->pcm[i];
  114863. float *logmdct =logfft+n/2;
  114864. float *logmask =logfft;
  114865. vb->mode=modenumber;
  114866. floor_posts[i]=(int**) _vorbis_block_alloc(vb,PACKETBLOBS*sizeof(**floor_posts));
  114867. memset(floor_posts[i],0,sizeof(**floor_posts)*PACKETBLOBS);
  114868. for(j=0;j<n/2;j++)
  114869. logmdct[j]=todB(mdct+j) + .345; /* + .345 is a hack; the original
  114870. todB estimation used on IEEE 754
  114871. compliant machines had a bug that
  114872. returned dB values about a third
  114873. of a decibel too high. The bug
  114874. was harmless because tunings
  114875. implicitly took that into
  114876. account. However, fixing the bug
  114877. in the estimator requires
  114878. changing all the tunings as well.
  114879. For now, it's easier to sync
  114880. things back up here, and
  114881. recalibrate the tunings in the
  114882. next major model upgrade. */
  114883. #if 0
  114884. if(vi->channels==2){
  114885. if(i==0)
  114886. _analysis_output("mdctL",seq,logmdct,n/2,1,0,0);
  114887. else
  114888. _analysis_output("mdctR",seq,logmdct,n/2,1,0,0);
  114889. }else{
  114890. _analysis_output("mdct",seq,logmdct,n/2,1,0,0);
  114891. }
  114892. #endif
  114893. /* first step; noise masking. Not only does 'noise masking'
  114894. give us curves from which we can decide how much resolution
  114895. to give noise parts of the spectrum, it also implicitly hands
  114896. us a tonality estimate (the larger the value in the
  114897. 'noise_depth' vector, the more tonal that area is) */
  114898. _vp_noisemask(psy_look,
  114899. logmdct,
  114900. noise); /* noise does not have by-frequency offset
  114901. bias applied yet */
  114902. #if 0
  114903. if(vi->channels==2){
  114904. if(i==0)
  114905. _analysis_output("noiseL",seq,noise,n/2,1,0,0);
  114906. else
  114907. _analysis_output("noiseR",seq,noise,n/2,1,0,0);
  114908. }
  114909. #endif
  114910. /* second step: 'all the other crap'; all the stuff that isn't
  114911. computed/fit for bitrate management goes in the second psy
  114912. vector. This includes tone masking, peak limiting and ATH */
  114913. _vp_tonemask(psy_look,
  114914. logfft,
  114915. tone,
  114916. global_ampmax,
  114917. local_ampmax[i]);
  114918. #if 0
  114919. if(vi->channels==2){
  114920. if(i==0)
  114921. _analysis_output("toneL",seq,tone,n/2,1,0,0);
  114922. else
  114923. _analysis_output("toneR",seq,tone,n/2,1,0,0);
  114924. }
  114925. #endif
  114926. /* third step; we offset the noise vectors, overlay tone
  114927. masking. We then do a floor1-specific line fit. If we're
  114928. performing bitrate management, the line fit is performed
  114929. multiple times for up/down tweakage on demand. */
  114930. #if 0
  114931. {
  114932. float aotuv[psy_look->n];
  114933. #endif
  114934. _vp_offset_and_mix(psy_look,
  114935. noise,
  114936. tone,
  114937. 1,
  114938. logmask,
  114939. mdct,
  114940. logmdct);
  114941. #if 0
  114942. if(vi->channels==2){
  114943. if(i==0)
  114944. _analysis_output("aotuvM1_L",seq,aotuv,psy_look->n,1,1,0);
  114945. else
  114946. _analysis_output("aotuvM1_R",seq,aotuv,psy_look->n,1,1,0);
  114947. }
  114948. }
  114949. #endif
  114950. #if 0
  114951. if(vi->channels==2){
  114952. if(i==0)
  114953. _analysis_output("mask1L",seq,logmask,n/2,1,0,0);
  114954. else
  114955. _analysis_output("mask1R",seq,logmask,n/2,1,0,0);
  114956. }
  114957. #endif
  114958. /* this algorithm is hardwired to floor 1 for now; abort out if
  114959. we're *not* floor1. This won't happen unless someone has
  114960. broken the encode setup lib. Guard it anyway. */
  114961. if(ci->floor_type[info->floorsubmap[submap]]!=1)return(-1);
  114962. floor_posts[i][PACKETBLOBS/2]=
  114963. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114964. logmdct,
  114965. logmask);
  114966. /* are we managing bitrate? If so, perform two more fits for
  114967. later rate tweaking (fits represent hi/lo) */
  114968. if(vorbis_bitrate_managed(vb) && floor_posts[i][PACKETBLOBS/2]){
  114969. /* higher rate by way of lower noise curve */
  114970. _vp_offset_and_mix(psy_look,
  114971. noise,
  114972. tone,
  114973. 2,
  114974. logmask,
  114975. mdct,
  114976. logmdct);
  114977. #if 0
  114978. if(vi->channels==2){
  114979. if(i==0)
  114980. _analysis_output("mask2L",seq,logmask,n/2,1,0,0);
  114981. else
  114982. _analysis_output("mask2R",seq,logmask,n/2,1,0,0);
  114983. }
  114984. #endif
  114985. floor_posts[i][PACKETBLOBS-1]=
  114986. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  114987. logmdct,
  114988. logmask);
  114989. /* lower rate by way of higher noise curve */
  114990. _vp_offset_and_mix(psy_look,
  114991. noise,
  114992. tone,
  114993. 0,
  114994. logmask,
  114995. mdct,
  114996. logmdct);
  114997. #if 0
  114998. if(vi->channels==2)
  114999. if(i==0)
  115000. _analysis_output("mask0L",seq,logmask,n/2,1,0,0);
  115001. else
  115002. _analysis_output("mask0R",seq,logmask,n/2,1,0,0);
  115003. #endif
  115004. floor_posts[i][0]=
  115005. floor1_fit(vb,b->flr[info->floorsubmap[submap]],
  115006. logmdct,
  115007. logmask);
  115008. /* we also interpolate a range of intermediate curves for
  115009. intermediate rates */
  115010. for(k=1;k<PACKETBLOBS/2;k++)
  115011. floor_posts[i][k]=
  115012. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115013. floor_posts[i][0],
  115014. floor_posts[i][PACKETBLOBS/2],
  115015. k*65536/(PACKETBLOBS/2));
  115016. for(k=PACKETBLOBS/2+1;k<PACKETBLOBS-1;k++)
  115017. floor_posts[i][k]=
  115018. floor1_interpolate_fit(vb,b->flr[info->floorsubmap[submap]],
  115019. floor_posts[i][PACKETBLOBS/2],
  115020. floor_posts[i][PACKETBLOBS-1],
  115021. (k-PACKETBLOBS/2)*65536/(PACKETBLOBS/2));
  115022. }
  115023. }
  115024. }
  115025. vbi->ampmax=global_ampmax;
  115026. /*
  115027. the next phases are performed once for vbr-only and PACKETBLOB
  115028. times for bitrate managed modes.
  115029. 1) encode actual mode being used
  115030. 2) encode the floor for each channel, compute coded mask curve/res
  115031. 3) normalize and couple.
  115032. 4) encode residue
  115033. 5) save packet bytes to the packetblob vector
  115034. */
  115035. /* iterate over the many masking curve fits we've created */
  115036. {
  115037. float **res_bundle=(float**) alloca(sizeof(*res_bundle)*vi->channels);
  115038. float **couple_bundle=(float**) alloca(sizeof(*couple_bundle)*vi->channels);
  115039. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115040. int **sortindex=(int**) alloca(sizeof(*sortindex)*vi->channels);
  115041. float **mag_memo;
  115042. int **mag_sort;
  115043. if(info->coupling_steps){
  115044. mag_memo=_vp_quantize_couple_memo(vb,
  115045. &ci->psy_g_param,
  115046. psy_look,
  115047. info,
  115048. gmdct);
  115049. mag_sort=_vp_quantize_couple_sort(vb,
  115050. psy_look,
  115051. info,
  115052. mag_memo);
  115053. hf_reduction(&ci->psy_g_param,
  115054. psy_look,
  115055. info,
  115056. mag_memo);
  115057. }
  115058. memset(sortindex,0,sizeof(*sortindex)*vi->channels);
  115059. if(psy_look->vi->normal_channel_p){
  115060. for(i=0;i<vi->channels;i++){
  115061. float *mdct =gmdct[i];
  115062. sortindex[i]=(int*) alloca(sizeof(**sortindex)*n/2);
  115063. _vp_noise_normalize_sort(psy_look,mdct,sortindex[i]);
  115064. }
  115065. }
  115066. for(k=(vorbis_bitrate_managed(vb)?0:PACKETBLOBS/2);
  115067. k<=(vorbis_bitrate_managed(vb)?PACKETBLOBS-1:PACKETBLOBS/2);
  115068. k++){
  115069. oggpack_buffer *opb=vbi->packetblob[k];
  115070. /* start out our new packet blob with packet type and mode */
  115071. /* Encode the packet type */
  115072. oggpack_write(opb,0,1);
  115073. /* Encode the modenumber */
  115074. /* Encode frame mode, pre,post windowsize, then dispatch */
  115075. oggpack_write(opb,modenumber,b->modebits);
  115076. if(vb->W){
  115077. oggpack_write(opb,vb->lW,1);
  115078. oggpack_write(opb,vb->nW,1);
  115079. }
  115080. /* encode floor, compute masking curve, sep out residue */
  115081. for(i=0;i<vi->channels;i++){
  115082. int submap=info->chmuxlist[i];
  115083. float *mdct =gmdct[i];
  115084. float *res =vb->pcm[i];
  115085. int *ilogmask=ilogmaskch[i]=
  115086. (int*) _vorbis_block_alloc(vb,n/2*sizeof(**gmdct));
  115087. nonzero[i]=floor1_encode(opb,vb,b->flr[info->floorsubmap[submap]],
  115088. floor_posts[i][k],
  115089. ilogmask);
  115090. #if 0
  115091. {
  115092. char buf[80];
  115093. sprintf(buf,"maskI%c%d",i?'R':'L',k);
  115094. float work[n/2];
  115095. for(j=0;j<n/2;j++)
  115096. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]];
  115097. _analysis_output(buf,seq,work,n/2,1,1,0);
  115098. }
  115099. #endif
  115100. _vp_remove_floor(psy_look,
  115101. mdct,
  115102. ilogmask,
  115103. res,
  115104. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115105. _vp_noise_normalize(psy_look,res,res+n/2,sortindex[i]);
  115106. #if 0
  115107. {
  115108. char buf[80];
  115109. float work[n/2];
  115110. for(j=0;j<n/2;j++)
  115111. work[j]=FLOOR1_fromdB_LOOKUP[ilogmask[j]]*(res+n/2)[j];
  115112. sprintf(buf,"resI%c%d",i?'R':'L',k);
  115113. _analysis_output(buf,seq,work,n/2,1,1,0);
  115114. }
  115115. #endif
  115116. }
  115117. /* our iteration is now based on masking curve, not prequant and
  115118. coupling. Only one prequant/coupling step */
  115119. /* quantize/couple */
  115120. /* incomplete implementation that assumes the tree is all depth
  115121. one, or no tree at all */
  115122. if(info->coupling_steps){
  115123. _vp_couple(k,
  115124. &ci->psy_g_param,
  115125. psy_look,
  115126. info,
  115127. vb->pcm,
  115128. mag_memo,
  115129. mag_sort,
  115130. ilogmaskch,
  115131. nonzero,
  115132. ci->psy_g_param.sliding_lowpass[vb->W][k]);
  115133. }
  115134. /* classify and encode by submap */
  115135. for(i=0;i<info->submaps;i++){
  115136. int ch_in_bundle=0;
  115137. long **classifications;
  115138. int resnum=info->residuesubmap[i];
  115139. for(j=0;j<vi->channels;j++){
  115140. if(info->chmuxlist[j]==i){
  115141. zerobundle[ch_in_bundle]=0;
  115142. if(nonzero[j])zerobundle[ch_in_bundle]=1;
  115143. res_bundle[ch_in_bundle]=vb->pcm[j];
  115144. couple_bundle[ch_in_bundle++]=vb->pcm[j]+n/2;
  115145. }
  115146. }
  115147. classifications=_residue_P[ci->residue_type[resnum]]->
  115148. classx(vb,b->residue[resnum],couple_bundle,zerobundle,ch_in_bundle);
  115149. _residue_P[ci->residue_type[resnum]]->
  115150. forward(opb,vb,b->residue[resnum],
  115151. couple_bundle,NULL,zerobundle,ch_in_bundle,classifications);
  115152. }
  115153. /* ok, done encoding. Next protopacket. */
  115154. }
  115155. }
  115156. #if 0
  115157. seq++;
  115158. total+=ci->blocksizes[vb->W]/4+ci->blocksizes[vb->nW]/4;
  115159. #endif
  115160. return(0);
  115161. }
  115162. static int mapping0_inverse(vorbis_block *vb,vorbis_info_mapping *l){
  115163. vorbis_dsp_state *vd=vb->vd;
  115164. vorbis_info *vi=vd->vi;
  115165. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  115166. private_state *b=(private_state*)vd->backend_state;
  115167. vorbis_info_mapping0 *info=(vorbis_info_mapping0 *)l;
  115168. int i,j;
  115169. long n=vb->pcmend=ci->blocksizes[vb->W];
  115170. float **pcmbundle=(float**) alloca(sizeof(*pcmbundle)*vi->channels);
  115171. int *zerobundle=(int*) alloca(sizeof(*zerobundle)*vi->channels);
  115172. int *nonzero =(int*) alloca(sizeof(*nonzero)*vi->channels);
  115173. void **floormemo=(void**) alloca(sizeof(*floormemo)*vi->channels);
  115174. /* recover the spectral envelope; store it in the PCM vector for now */
  115175. for(i=0;i<vi->channels;i++){
  115176. int submap=info->chmuxlist[i];
  115177. floormemo[i]=_floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115178. inverse1(vb,b->flr[info->floorsubmap[submap]]);
  115179. if(floormemo[i])
  115180. nonzero[i]=1;
  115181. else
  115182. nonzero[i]=0;
  115183. memset(vb->pcm[i],0,sizeof(*vb->pcm[i])*n/2);
  115184. }
  115185. /* channel coupling can 'dirty' the nonzero listing */
  115186. for(i=0;i<info->coupling_steps;i++){
  115187. if(nonzero[info->coupling_mag[i]] ||
  115188. nonzero[info->coupling_ang[i]]){
  115189. nonzero[info->coupling_mag[i]]=1;
  115190. nonzero[info->coupling_ang[i]]=1;
  115191. }
  115192. }
  115193. /* recover the residue into our working vectors */
  115194. for(i=0;i<info->submaps;i++){
  115195. int ch_in_bundle=0;
  115196. for(j=0;j<vi->channels;j++){
  115197. if(info->chmuxlist[j]==i){
  115198. if(nonzero[j])
  115199. zerobundle[ch_in_bundle]=1;
  115200. else
  115201. zerobundle[ch_in_bundle]=0;
  115202. pcmbundle[ch_in_bundle++]=vb->pcm[j];
  115203. }
  115204. }
  115205. _residue_P[ci->residue_type[info->residuesubmap[i]]]->
  115206. inverse(vb,b->residue[info->residuesubmap[i]],
  115207. pcmbundle,zerobundle,ch_in_bundle);
  115208. }
  115209. /* channel coupling */
  115210. for(i=info->coupling_steps-1;i>=0;i--){
  115211. float *pcmM=vb->pcm[info->coupling_mag[i]];
  115212. float *pcmA=vb->pcm[info->coupling_ang[i]];
  115213. for(j=0;j<n/2;j++){
  115214. float mag=pcmM[j];
  115215. float ang=pcmA[j];
  115216. if(mag>0)
  115217. if(ang>0){
  115218. pcmM[j]=mag;
  115219. pcmA[j]=mag-ang;
  115220. }else{
  115221. pcmA[j]=mag;
  115222. pcmM[j]=mag+ang;
  115223. }
  115224. else
  115225. if(ang>0){
  115226. pcmM[j]=mag;
  115227. pcmA[j]=mag+ang;
  115228. }else{
  115229. pcmA[j]=mag;
  115230. pcmM[j]=mag-ang;
  115231. }
  115232. }
  115233. }
  115234. /* compute and apply spectral envelope */
  115235. for(i=0;i<vi->channels;i++){
  115236. float *pcm=vb->pcm[i];
  115237. int submap=info->chmuxlist[i];
  115238. _floor_P[ci->floor_type[info->floorsubmap[submap]]]->
  115239. inverse2(vb,b->flr[info->floorsubmap[submap]],
  115240. floormemo[i],pcm);
  115241. }
  115242. /* transform the PCM data; takes PCM vector, vb; modifies PCM vector */
  115243. /* only MDCT right now.... */
  115244. for(i=0;i<vi->channels;i++){
  115245. float *pcm=vb->pcm[i];
  115246. mdct_backward((mdct_lookup*) b->transform[vb->W][0],pcm,pcm);
  115247. }
  115248. /* all done! */
  115249. return(0);
  115250. }
  115251. /* export hooks */
  115252. vorbis_func_mapping mapping0_exportbundle={
  115253. &mapping0_pack,
  115254. &mapping0_unpack,
  115255. &mapping0_free_info,
  115256. &mapping0_forward,
  115257. &mapping0_inverse
  115258. };
  115259. #endif
  115260. /********* End of inlined file: mapping0.c *********/
  115261. /********* Start of inlined file: mdct.c *********/
  115262. /* this can also be run as an integer transform by uncommenting a
  115263. define in mdct.h; the integerization is a first pass and although
  115264. it's likely stable for Vorbis, the dynamic range is constrained and
  115265. roundoff isn't done (so it's noisy). Consider it functional, but
  115266. only a starting point. There's no point on a machine with an FPU */
  115267. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  115268. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115269. // tasks..
  115270. /********* Start of inlined file: juce_Config.h *********/
  115271. #ifndef __JUCE_CONFIG_JUCEHEADER__
  115272. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  115273. /*
  115274. This file contains macros that enable/disable various JUCE features.
  115275. */
  115276. /** The name of the namespace that all Juce classes and functions will be
  115277. put inside. If this is not defined, no namespace will be used.
  115278. */
  115279. #ifndef JUCE_NAMESPACE
  115280. #define JUCE_NAMESPACE juce
  115281. #endif
  115282. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  115283. but if you define this value, you can override this can force it to be true or
  115284. false.
  115285. */
  115286. #ifndef JUCE_FORCE_DEBUG
  115287. //#define JUCE_FORCE_DEBUG 1
  115288. #endif
  115289. /** If this flag is enabled, the the jassert and jassertfalse macros will
  115290. always use Logger::writeToLog() to write a message when an assertion happens.
  115291. Enabling it will also leave this turned on in release builds. When it's disabled,
  115292. however, the jassert and jassertfalse macros will not be compiled in a
  115293. release build.
  115294. @see jassert, jassertfalse, Logger
  115295. */
  115296. #ifndef JUCE_LOG_ASSERTIONS
  115297. // #define JUCE_LOG_ASSERTIONS 1
  115298. #endif
  115299. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  115300. which the ASIOAudioIODevice class can't be built. See the comments in the
  115301. ASIOAudioIODevice class's header file for more info about this.
  115302. (This only affects a Win32 build)
  115303. */
  115304. #ifndef JUCE_ASIO
  115305. #define JUCE_ASIO 1
  115306. #endif
  115307. /** Comment out this macro to disable building of ALSA device support on Linux.
  115308. */
  115309. #ifndef JUCE_ALSA
  115310. #define JUCE_ALSA 1
  115311. #endif
  115312. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  115313. have the SDK installed.
  115314. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  115315. classes will be unavailable.
  115316. On Windows, if you enable this, you'll need to have the QuickTime SDK
  115317. installed, and its header files will need to be on your include path.
  115318. */
  115319. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  115320. #define JUCE_QUICKTIME 1
  115321. #endif
  115322. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  115323. have the appropriate headers and libraries available. If it's not enabled, the
  115324. OpenGLComponent class will be unavailable.
  115325. */
  115326. #ifndef JUCE_OPENGL
  115327. #define JUCE_OPENGL 1
  115328. #endif
  115329. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  115330. If you're not going to need either of these formats, turn off the flags to
  115331. avoid bloating your codebase with them.
  115332. */
  115333. #ifndef JUCE_USE_FLAC
  115334. #define JUCE_USE_FLAC 1
  115335. #endif
  115336. #ifndef JUCE_USE_OGGVORBIS
  115337. #define JUCE_USE_OGGVORBIS 1
  115338. #endif
  115339. /** This flag lets you enable support for CD-burning. You might want to disable
  115340. it to build without the MS SDK under windows.
  115341. */
  115342. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  115343. #define JUCE_USE_CDBURNER 1
  115344. #endif
  115345. /** Enabling this macro means that all regions that get repainted will have a coloured
  115346. line drawn around them.
  115347. This is handy if you're trying to optimise drawing, because it lets you easily see
  115348. when anything is being repainted unnecessarily.
  115349. */
  115350. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  115351. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  115352. #endif
  115353. /** Enable this under Linux to use Xinerama for multi-monitor support.
  115354. */
  115355. #ifndef JUCE_USE_XINERAMA
  115356. #define JUCE_USE_XINERAMA 1
  115357. #endif
  115358. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  115359. */
  115360. #ifndef JUCE_USE_XSHM
  115361. #define JUCE_USE_XSHM 1
  115362. #endif
  115363. /** Enabling this builds support for VST audio plugins.
  115364. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  115365. */
  115366. #ifndef JUCE_PLUGINHOST_VST
  115367. // #define JUCE_PLUGINHOST_VST 1
  115368. #endif
  115369. /** Enabling this builds support for AudioUnit audio plugins.
  115370. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  115371. */
  115372. #ifndef JUCE_PLUGINHOST_AU
  115373. // #define JUCE_PLUGINHOST_AU 1
  115374. #endif
  115375. /** Disabling this will avoid linking to any UI code. This is handy for
  115376. writing command-line utilities, e.g. on linux boxes which don't have some
  115377. of the UI libraries installed.
  115378. (On mac and windows, this won't generally make much difference to the build).
  115379. */
  115380. #ifndef JUCE_BUILD_GUI_CLASSES
  115381. #define JUCE_BUILD_GUI_CLASSES 1
  115382. #endif
  115383. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  115384. */
  115385. #ifndef JUCE_WEB_BROWSER
  115386. #define JUCE_WEB_BROWSER 1
  115387. #endif
  115388. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  115389. codebase - you might need to use this if you're linking to some of these libraries
  115390. yourself.
  115391. */
  115392. #ifndef JUCE_INCLUDE_ZLIB_CODE
  115393. #define JUCE_INCLUDE_ZLIB_CODE 1
  115394. #endif
  115395. #ifndef JUCE_INCLUDE_FLAC_CODE
  115396. #define JUCE_INCLUDE_FLAC_CODE 1
  115397. #endif
  115398. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  115399. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  115400. #endif
  115401. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  115402. #define JUCE_INCLUDE_PNGLIB_CODE 1
  115403. #endif
  115404. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  115405. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  115406. #endif
  115407. /** Enable this to add extra memory-leak info to the new and delete operators.
  115408. (Currently, this only affects Windows builds in debug mode).
  115409. */
  115410. #ifndef JUCE_CHECK_MEMORY_LEAKS
  115411. #define JUCE_CHECK_MEMORY_LEAKS 1
  115412. #endif
  115413. /** Enable this to turn on juce's internal catching of exceptions.
  115414. Turning it off will avoid any exception catching. With it on, all exceptions
  115415. are passed to the JUCEApplication::unhandledException() callback for logging.
  115416. */
  115417. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  115418. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  115419. #endif
  115420. /** If this macro is set, the Juce String class will use unicode as its
  115421. internal representation. If it isn't set, it'll use ANSI.
  115422. */
  115423. #ifndef JUCE_STRINGS_ARE_UNICODE
  115424. #define JUCE_STRINGS_ARE_UNICODE 1
  115425. #endif
  115426. #endif
  115427. /********* End of inlined file: juce_Config.h *********/
  115428. #ifdef _MSC_VER
  115429. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  115430. #endif
  115431. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  115432. #if JUCE_USE_OGGVORBIS
  115433. #include <stdio.h>
  115434. #include <stdlib.h>
  115435. #include <string.h>
  115436. #include <math.h>
  115437. /* build lookups for trig functions; also pre-figure scaling and
  115438. some window function algebra. */
  115439. void mdct_init(mdct_lookup *lookup,int n){
  115440. int *bitrev=(int*) _ogg_malloc(sizeof(*bitrev)*(n/4));
  115441. DATA_TYPE *T=(DATA_TYPE*) _ogg_malloc(sizeof(*T)*(n+n/4));
  115442. int i;
  115443. int n2=n>>1;
  115444. int log2n=lookup->log2n=rint(log((float)n)/log(2.f));
  115445. lookup->n=n;
  115446. lookup->trig=T;
  115447. lookup->bitrev=bitrev;
  115448. /* trig lookups... */
  115449. for(i=0;i<n/4;i++){
  115450. T[i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i)));
  115451. T[i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i)));
  115452. T[n2+i*2]=FLOAT_CONV(cos((M_PI/(2*n))*(2*i+1)));
  115453. T[n2+i*2+1]=FLOAT_CONV(sin((M_PI/(2*n))*(2*i+1)));
  115454. }
  115455. for(i=0;i<n/8;i++){
  115456. T[n+i*2]=FLOAT_CONV(cos((M_PI/n)*(4*i+2))*.5);
  115457. T[n+i*2+1]=FLOAT_CONV(-sin((M_PI/n)*(4*i+2))*.5);
  115458. }
  115459. /* bitreverse lookup... */
  115460. {
  115461. int mask=(1<<(log2n-1))-1,i,j;
  115462. int msb=1<<(log2n-2);
  115463. for(i=0;i<n/8;i++){
  115464. int acc=0;
  115465. for(j=0;msb>>j;j++)
  115466. if((msb>>j)&i)acc|=1<<j;
  115467. bitrev[i*2]=((~acc)&mask)-1;
  115468. bitrev[i*2+1]=acc;
  115469. }
  115470. }
  115471. lookup->scale=FLOAT_CONV(4.f/n);
  115472. }
  115473. /* 8 point butterfly (in place, 4 register) */
  115474. STIN void mdct_butterfly_8(DATA_TYPE *x){
  115475. REG_TYPE r0 = x[6] + x[2];
  115476. REG_TYPE r1 = x[6] - x[2];
  115477. REG_TYPE r2 = x[4] + x[0];
  115478. REG_TYPE r3 = x[4] - x[0];
  115479. x[6] = r0 + r2;
  115480. x[4] = r0 - r2;
  115481. r0 = x[5] - x[1];
  115482. r2 = x[7] - x[3];
  115483. x[0] = r1 + r0;
  115484. x[2] = r1 - r0;
  115485. r0 = x[5] + x[1];
  115486. r1 = x[7] + x[3];
  115487. x[3] = r2 + r3;
  115488. x[1] = r2 - r3;
  115489. x[7] = r1 + r0;
  115490. x[5] = r1 - r0;
  115491. }
  115492. /* 16 point butterfly (in place, 4 register) */
  115493. STIN void mdct_butterfly_16(DATA_TYPE *x){
  115494. REG_TYPE r0 = x[1] - x[9];
  115495. REG_TYPE r1 = x[0] - x[8];
  115496. x[8] += x[0];
  115497. x[9] += x[1];
  115498. x[0] = MULT_NORM((r0 + r1) * cPI2_8);
  115499. x[1] = MULT_NORM((r0 - r1) * cPI2_8);
  115500. r0 = x[3] - x[11];
  115501. r1 = x[10] - x[2];
  115502. x[10] += x[2];
  115503. x[11] += x[3];
  115504. x[2] = r0;
  115505. x[3] = r1;
  115506. r0 = x[12] - x[4];
  115507. r1 = x[13] - x[5];
  115508. x[12] += x[4];
  115509. x[13] += x[5];
  115510. x[4] = MULT_NORM((r0 - r1) * cPI2_8);
  115511. x[5] = MULT_NORM((r0 + r1) * cPI2_8);
  115512. r0 = x[14] - x[6];
  115513. r1 = x[15] - x[7];
  115514. x[14] += x[6];
  115515. x[15] += x[7];
  115516. x[6] = r0;
  115517. x[7] = r1;
  115518. mdct_butterfly_8(x);
  115519. mdct_butterfly_8(x+8);
  115520. }
  115521. /* 32 point butterfly (in place, 4 register) */
  115522. STIN void mdct_butterfly_32(DATA_TYPE *x){
  115523. REG_TYPE r0 = x[30] - x[14];
  115524. REG_TYPE r1 = x[31] - x[15];
  115525. x[30] += x[14];
  115526. x[31] += x[15];
  115527. x[14] = r0;
  115528. x[15] = r1;
  115529. r0 = x[28] - x[12];
  115530. r1 = x[29] - x[13];
  115531. x[28] += x[12];
  115532. x[29] += x[13];
  115533. x[12] = MULT_NORM( r0 * cPI1_8 - r1 * cPI3_8 );
  115534. x[13] = MULT_NORM( r0 * cPI3_8 + r1 * cPI1_8 );
  115535. r0 = x[26] - x[10];
  115536. r1 = x[27] - x[11];
  115537. x[26] += x[10];
  115538. x[27] += x[11];
  115539. x[10] = MULT_NORM(( r0 - r1 ) * cPI2_8);
  115540. x[11] = MULT_NORM(( r0 + r1 ) * cPI2_8);
  115541. r0 = x[24] - x[8];
  115542. r1 = x[25] - x[9];
  115543. x[24] += x[8];
  115544. x[25] += x[9];
  115545. x[8] = MULT_NORM( r0 * cPI3_8 - r1 * cPI1_8 );
  115546. x[9] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115547. r0 = x[22] - x[6];
  115548. r1 = x[7] - x[23];
  115549. x[22] += x[6];
  115550. x[23] += x[7];
  115551. x[6] = r1;
  115552. x[7] = r0;
  115553. r0 = x[4] - x[20];
  115554. r1 = x[5] - x[21];
  115555. x[20] += x[4];
  115556. x[21] += x[5];
  115557. x[4] = MULT_NORM( r1 * cPI1_8 + r0 * cPI3_8 );
  115558. x[5] = MULT_NORM( r1 * cPI3_8 - r0 * cPI1_8 );
  115559. r0 = x[2] - x[18];
  115560. r1 = x[3] - x[19];
  115561. x[18] += x[2];
  115562. x[19] += x[3];
  115563. x[2] = MULT_NORM(( r1 + r0 ) * cPI2_8);
  115564. x[3] = MULT_NORM(( r1 - r0 ) * cPI2_8);
  115565. r0 = x[0] - x[16];
  115566. r1 = x[1] - x[17];
  115567. x[16] += x[0];
  115568. x[17] += x[1];
  115569. x[0] = MULT_NORM( r1 * cPI3_8 + r0 * cPI1_8 );
  115570. x[1] = MULT_NORM( r1 * cPI1_8 - r0 * cPI3_8 );
  115571. mdct_butterfly_16(x);
  115572. mdct_butterfly_16(x+16);
  115573. }
  115574. /* N point first stage butterfly (in place, 2 register) */
  115575. STIN void mdct_butterfly_first(DATA_TYPE *T,
  115576. DATA_TYPE *x,
  115577. int points){
  115578. DATA_TYPE *x1 = x + points - 8;
  115579. DATA_TYPE *x2 = x + (points>>1) - 8;
  115580. REG_TYPE r0;
  115581. REG_TYPE r1;
  115582. do{
  115583. r0 = x1[6] - x2[6];
  115584. r1 = x1[7] - x2[7];
  115585. x1[6] += x2[6];
  115586. x1[7] += x2[7];
  115587. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115588. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115589. r0 = x1[4] - x2[4];
  115590. r1 = x1[5] - x2[5];
  115591. x1[4] += x2[4];
  115592. x1[5] += x2[5];
  115593. x2[4] = MULT_NORM(r1 * T[5] + r0 * T[4]);
  115594. x2[5] = MULT_NORM(r1 * T[4] - r0 * T[5]);
  115595. r0 = x1[2] - x2[2];
  115596. r1 = x1[3] - x2[3];
  115597. x1[2] += x2[2];
  115598. x1[3] += x2[3];
  115599. x2[2] = MULT_NORM(r1 * T[9] + r0 * T[8]);
  115600. x2[3] = MULT_NORM(r1 * T[8] - r0 * T[9]);
  115601. r0 = x1[0] - x2[0];
  115602. r1 = x1[1] - x2[1];
  115603. x1[0] += x2[0];
  115604. x1[1] += x2[1];
  115605. x2[0] = MULT_NORM(r1 * T[13] + r0 * T[12]);
  115606. x2[1] = MULT_NORM(r1 * T[12] - r0 * T[13]);
  115607. x1-=8;
  115608. x2-=8;
  115609. T+=16;
  115610. }while(x2>=x);
  115611. }
  115612. /* N/stage point generic N stage butterfly (in place, 2 register) */
  115613. STIN void mdct_butterfly_generic(DATA_TYPE *T,
  115614. DATA_TYPE *x,
  115615. int points,
  115616. int trigint){
  115617. DATA_TYPE *x1 = x + points - 8;
  115618. DATA_TYPE *x2 = x + (points>>1) - 8;
  115619. REG_TYPE r0;
  115620. REG_TYPE r1;
  115621. do{
  115622. r0 = x1[6] - x2[6];
  115623. r1 = x1[7] - x2[7];
  115624. x1[6] += x2[6];
  115625. x1[7] += x2[7];
  115626. x2[6] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115627. x2[7] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115628. T+=trigint;
  115629. r0 = x1[4] - x2[4];
  115630. r1 = x1[5] - x2[5];
  115631. x1[4] += x2[4];
  115632. x1[5] += x2[5];
  115633. x2[4] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115634. x2[5] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115635. T+=trigint;
  115636. r0 = x1[2] - x2[2];
  115637. r1 = x1[3] - x2[3];
  115638. x1[2] += x2[2];
  115639. x1[3] += x2[3];
  115640. x2[2] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115641. x2[3] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115642. T+=trigint;
  115643. r0 = x1[0] - x2[0];
  115644. r1 = x1[1] - x2[1];
  115645. x1[0] += x2[0];
  115646. x1[1] += x2[1];
  115647. x2[0] = MULT_NORM(r1 * T[1] + r0 * T[0]);
  115648. x2[1] = MULT_NORM(r1 * T[0] - r0 * T[1]);
  115649. T+=trigint;
  115650. x1-=8;
  115651. x2-=8;
  115652. }while(x2>=x);
  115653. }
  115654. STIN void mdct_butterflies(mdct_lookup *init,
  115655. DATA_TYPE *x,
  115656. int points){
  115657. DATA_TYPE *T=init->trig;
  115658. int stages=init->log2n-5;
  115659. int i,j;
  115660. if(--stages>0){
  115661. mdct_butterfly_first(T,x,points);
  115662. }
  115663. for(i=1;--stages>0;i++){
  115664. for(j=0;j<(1<<i);j++)
  115665. mdct_butterfly_generic(T,x+(points>>i)*j,points>>i,4<<i);
  115666. }
  115667. for(j=0;j<points;j+=32)
  115668. mdct_butterfly_32(x+j);
  115669. }
  115670. void mdct_clear(mdct_lookup *l){
  115671. if(l){
  115672. if(l->trig)_ogg_free(l->trig);
  115673. if(l->bitrev)_ogg_free(l->bitrev);
  115674. memset(l,0,sizeof(*l));
  115675. }
  115676. }
  115677. STIN void mdct_bitreverse(mdct_lookup *init,
  115678. DATA_TYPE *x){
  115679. int n = init->n;
  115680. int *bit = init->bitrev;
  115681. DATA_TYPE *w0 = x;
  115682. DATA_TYPE *w1 = x = w0+(n>>1);
  115683. DATA_TYPE *T = init->trig+n;
  115684. do{
  115685. DATA_TYPE *x0 = x+bit[0];
  115686. DATA_TYPE *x1 = x+bit[1];
  115687. REG_TYPE r0 = x0[1] - x1[1];
  115688. REG_TYPE r1 = x0[0] + x1[0];
  115689. REG_TYPE r2 = MULT_NORM(r1 * T[0] + r0 * T[1]);
  115690. REG_TYPE r3 = MULT_NORM(r1 * T[1] - r0 * T[0]);
  115691. w1 -= 4;
  115692. r0 = HALVE(x0[1] + x1[1]);
  115693. r1 = HALVE(x0[0] - x1[0]);
  115694. w0[0] = r0 + r2;
  115695. w1[2] = r0 - r2;
  115696. w0[1] = r1 + r3;
  115697. w1[3] = r3 - r1;
  115698. x0 = x+bit[2];
  115699. x1 = x+bit[3];
  115700. r0 = x0[1] - x1[1];
  115701. r1 = x0[0] + x1[0];
  115702. r2 = MULT_NORM(r1 * T[2] + r0 * T[3]);
  115703. r3 = MULT_NORM(r1 * T[3] - r0 * T[2]);
  115704. r0 = HALVE(x0[1] + x1[1]);
  115705. r1 = HALVE(x0[0] - x1[0]);
  115706. w0[2] = r0 + r2;
  115707. w1[0] = r0 - r2;
  115708. w0[3] = r1 + r3;
  115709. w1[1] = r3 - r1;
  115710. T += 4;
  115711. bit += 4;
  115712. w0 += 4;
  115713. }while(w0<w1);
  115714. }
  115715. void mdct_backward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115716. int n=init->n;
  115717. int n2=n>>1;
  115718. int n4=n>>2;
  115719. /* rotate */
  115720. DATA_TYPE *iX = in+n2-7;
  115721. DATA_TYPE *oX = out+n2+n4;
  115722. DATA_TYPE *T = init->trig+n4;
  115723. do{
  115724. oX -= 4;
  115725. oX[0] = MULT_NORM(-iX[2] * T[3] - iX[0] * T[2]);
  115726. oX[1] = MULT_NORM (iX[0] * T[3] - iX[2] * T[2]);
  115727. oX[2] = MULT_NORM(-iX[6] * T[1] - iX[4] * T[0]);
  115728. oX[3] = MULT_NORM (iX[4] * T[1] - iX[6] * T[0]);
  115729. iX -= 8;
  115730. T += 4;
  115731. }while(iX>=in);
  115732. iX = in+n2-8;
  115733. oX = out+n2+n4;
  115734. T = init->trig+n4;
  115735. do{
  115736. T -= 4;
  115737. oX[0] = MULT_NORM (iX[4] * T[3] + iX[6] * T[2]);
  115738. oX[1] = MULT_NORM (iX[4] * T[2] - iX[6] * T[3]);
  115739. oX[2] = MULT_NORM (iX[0] * T[1] + iX[2] * T[0]);
  115740. oX[3] = MULT_NORM (iX[0] * T[0] - iX[2] * T[1]);
  115741. iX -= 8;
  115742. oX += 4;
  115743. }while(iX>=in);
  115744. mdct_butterflies(init,out+n2,n2);
  115745. mdct_bitreverse(init,out);
  115746. /* roatate + window */
  115747. {
  115748. DATA_TYPE *oX1=out+n2+n4;
  115749. DATA_TYPE *oX2=out+n2+n4;
  115750. DATA_TYPE *iX =out;
  115751. T =init->trig+n2;
  115752. do{
  115753. oX1-=4;
  115754. oX1[3] = MULT_NORM (iX[0] * T[1] - iX[1] * T[0]);
  115755. oX2[0] = -MULT_NORM (iX[0] * T[0] + iX[1] * T[1]);
  115756. oX1[2] = MULT_NORM (iX[2] * T[3] - iX[3] * T[2]);
  115757. oX2[1] = -MULT_NORM (iX[2] * T[2] + iX[3] * T[3]);
  115758. oX1[1] = MULT_NORM (iX[4] * T[5] - iX[5] * T[4]);
  115759. oX2[2] = -MULT_NORM (iX[4] * T[4] + iX[5] * T[5]);
  115760. oX1[0] = MULT_NORM (iX[6] * T[7] - iX[7] * T[6]);
  115761. oX2[3] = -MULT_NORM (iX[6] * T[6] + iX[7] * T[7]);
  115762. oX2+=4;
  115763. iX += 8;
  115764. T += 8;
  115765. }while(iX<oX1);
  115766. iX=out+n2+n4;
  115767. oX1=out+n4;
  115768. oX2=oX1;
  115769. do{
  115770. oX1-=4;
  115771. iX-=4;
  115772. oX2[0] = -(oX1[3] = iX[3]);
  115773. oX2[1] = -(oX1[2] = iX[2]);
  115774. oX2[2] = -(oX1[1] = iX[1]);
  115775. oX2[3] = -(oX1[0] = iX[0]);
  115776. oX2+=4;
  115777. }while(oX2<iX);
  115778. iX=out+n2+n4;
  115779. oX1=out+n2+n4;
  115780. oX2=out+n2;
  115781. do{
  115782. oX1-=4;
  115783. oX1[0]= iX[3];
  115784. oX1[1]= iX[2];
  115785. oX1[2]= iX[1];
  115786. oX1[3]= iX[0];
  115787. iX+=4;
  115788. }while(oX1>oX2);
  115789. }
  115790. }
  115791. void mdct_forward(mdct_lookup *init, DATA_TYPE *in, DATA_TYPE *out){
  115792. int n=init->n;
  115793. int n2=n>>1;
  115794. int n4=n>>2;
  115795. int n8=n>>3;
  115796. DATA_TYPE *w=(DATA_TYPE*) alloca(n*sizeof(*w)); /* forward needs working space */
  115797. DATA_TYPE *w2=w+n2;
  115798. /* rotate */
  115799. /* window + rotate + step 1 */
  115800. REG_TYPE r0;
  115801. REG_TYPE r1;
  115802. DATA_TYPE *x0=in+n2+n4;
  115803. DATA_TYPE *x1=x0+1;
  115804. DATA_TYPE *T=init->trig+n2;
  115805. int i=0;
  115806. for(i=0;i<n8;i+=2){
  115807. x0 -=4;
  115808. T-=2;
  115809. r0= x0[2] + x1[0];
  115810. r1= x0[0] + x1[2];
  115811. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115812. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115813. x1 +=4;
  115814. }
  115815. x1=in+1;
  115816. for(;i<n2-n8;i+=2){
  115817. T-=2;
  115818. x0 -=4;
  115819. r0= x0[2] - x1[0];
  115820. r1= x0[0] - x1[2];
  115821. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115822. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115823. x1 +=4;
  115824. }
  115825. x0=in+n;
  115826. for(;i<n2;i+=2){
  115827. T-=2;
  115828. x0 -=4;
  115829. r0= -x0[2] - x1[0];
  115830. r1= -x0[0] - x1[2];
  115831. w2[i]= MULT_NORM(r1*T[1] + r0*T[0]);
  115832. w2[i+1]= MULT_NORM(r1*T[0] - r0*T[1]);
  115833. x1 +=4;
  115834. }
  115835. mdct_butterflies(init,w+n2,n2);
  115836. mdct_bitreverse(init,w);
  115837. /* roatate + window */
  115838. T=init->trig+n2;
  115839. x0=out+n2;
  115840. for(i=0;i<n4;i++){
  115841. x0--;
  115842. out[i] =MULT_NORM((w[0]*T[0]+w[1]*T[1])*init->scale);
  115843. x0[0] =MULT_NORM((w[0]*T[1]-w[1]*T[0])*init->scale);
  115844. w+=2;
  115845. T+=2;
  115846. }
  115847. }
  115848. #endif
  115849. /********* End of inlined file: mdct.c *********/
  115850. /********* Start of inlined file: psy.c *********/
  115851. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  115852. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  115853. // tasks..
  115854. /********* Start of inlined file: juce_Config.h *********/
  115855. #ifndef __JUCE_CONFIG_JUCEHEADER__
  115856. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  115857. /*
  115858. This file contains macros that enable/disable various JUCE features.
  115859. */
  115860. /** The name of the namespace that all Juce classes and functions will be
  115861. put inside. If this is not defined, no namespace will be used.
  115862. */
  115863. #ifndef JUCE_NAMESPACE
  115864. #define JUCE_NAMESPACE juce
  115865. #endif
  115866. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  115867. but if you define this value, you can override this can force it to be true or
  115868. false.
  115869. */
  115870. #ifndef JUCE_FORCE_DEBUG
  115871. //#define JUCE_FORCE_DEBUG 1
  115872. #endif
  115873. /** If this flag is enabled, the the jassert and jassertfalse macros will
  115874. always use Logger::writeToLog() to write a message when an assertion happens.
  115875. Enabling it will also leave this turned on in release builds. When it's disabled,
  115876. however, the jassert and jassertfalse macros will not be compiled in a
  115877. release build.
  115878. @see jassert, jassertfalse, Logger
  115879. */
  115880. #ifndef JUCE_LOG_ASSERTIONS
  115881. // #define JUCE_LOG_ASSERTIONS 1
  115882. #endif
  115883. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  115884. which the ASIOAudioIODevice class can't be built. See the comments in the
  115885. ASIOAudioIODevice class's header file for more info about this.
  115886. (This only affects a Win32 build)
  115887. */
  115888. #ifndef JUCE_ASIO
  115889. #define JUCE_ASIO 1
  115890. #endif
  115891. /** Comment out this macro to disable building of ALSA device support on Linux.
  115892. */
  115893. #ifndef JUCE_ALSA
  115894. #define JUCE_ALSA 1
  115895. #endif
  115896. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  115897. have the SDK installed.
  115898. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  115899. classes will be unavailable.
  115900. On Windows, if you enable this, you'll need to have the QuickTime SDK
  115901. installed, and its header files will need to be on your include path.
  115902. */
  115903. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  115904. #define JUCE_QUICKTIME 1
  115905. #endif
  115906. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  115907. have the appropriate headers and libraries available. If it's not enabled, the
  115908. OpenGLComponent class will be unavailable.
  115909. */
  115910. #ifndef JUCE_OPENGL
  115911. #define JUCE_OPENGL 1
  115912. #endif
  115913. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  115914. If you're not going to need either of these formats, turn off the flags to
  115915. avoid bloating your codebase with them.
  115916. */
  115917. #ifndef JUCE_USE_FLAC
  115918. #define JUCE_USE_FLAC 1
  115919. #endif
  115920. #ifndef JUCE_USE_OGGVORBIS
  115921. #define JUCE_USE_OGGVORBIS 1
  115922. #endif
  115923. /** This flag lets you enable support for CD-burning. You might want to disable
  115924. it to build without the MS SDK under windows.
  115925. */
  115926. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  115927. #define JUCE_USE_CDBURNER 1
  115928. #endif
  115929. /** Enabling this macro means that all regions that get repainted will have a coloured
  115930. line drawn around them.
  115931. This is handy if you're trying to optimise drawing, because it lets you easily see
  115932. when anything is being repainted unnecessarily.
  115933. */
  115934. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  115935. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  115936. #endif
  115937. /** Enable this under Linux to use Xinerama for multi-monitor support.
  115938. */
  115939. #ifndef JUCE_USE_XINERAMA
  115940. #define JUCE_USE_XINERAMA 1
  115941. #endif
  115942. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  115943. */
  115944. #ifndef JUCE_USE_XSHM
  115945. #define JUCE_USE_XSHM 1
  115946. #endif
  115947. /** Enabling this builds support for VST audio plugins.
  115948. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  115949. */
  115950. #ifndef JUCE_PLUGINHOST_VST
  115951. // #define JUCE_PLUGINHOST_VST 1
  115952. #endif
  115953. /** Enabling this builds support for AudioUnit audio plugins.
  115954. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  115955. */
  115956. #ifndef JUCE_PLUGINHOST_AU
  115957. // #define JUCE_PLUGINHOST_AU 1
  115958. #endif
  115959. /** Disabling this will avoid linking to any UI code. This is handy for
  115960. writing command-line utilities, e.g. on linux boxes which don't have some
  115961. of the UI libraries installed.
  115962. (On mac and windows, this won't generally make much difference to the build).
  115963. */
  115964. #ifndef JUCE_BUILD_GUI_CLASSES
  115965. #define JUCE_BUILD_GUI_CLASSES 1
  115966. #endif
  115967. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  115968. */
  115969. #ifndef JUCE_WEB_BROWSER
  115970. #define JUCE_WEB_BROWSER 1
  115971. #endif
  115972. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  115973. codebase - you might need to use this if you're linking to some of these libraries
  115974. yourself.
  115975. */
  115976. #ifndef JUCE_INCLUDE_ZLIB_CODE
  115977. #define JUCE_INCLUDE_ZLIB_CODE 1
  115978. #endif
  115979. #ifndef JUCE_INCLUDE_FLAC_CODE
  115980. #define JUCE_INCLUDE_FLAC_CODE 1
  115981. #endif
  115982. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  115983. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  115984. #endif
  115985. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  115986. #define JUCE_INCLUDE_PNGLIB_CODE 1
  115987. #endif
  115988. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  115989. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  115990. #endif
  115991. /** Enable this to add extra memory-leak info to the new and delete operators.
  115992. (Currently, this only affects Windows builds in debug mode).
  115993. */
  115994. #ifndef JUCE_CHECK_MEMORY_LEAKS
  115995. #define JUCE_CHECK_MEMORY_LEAKS 1
  115996. #endif
  115997. /** Enable this to turn on juce's internal catching of exceptions.
  115998. Turning it off will avoid any exception catching. With it on, all exceptions
  115999. are passed to the JUCEApplication::unhandledException() callback for logging.
  116000. */
  116001. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  116002. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  116003. #endif
  116004. /** If this macro is set, the Juce String class will use unicode as its
  116005. internal representation. If it isn't set, it'll use ANSI.
  116006. */
  116007. #ifndef JUCE_STRINGS_ARE_UNICODE
  116008. #define JUCE_STRINGS_ARE_UNICODE 1
  116009. #endif
  116010. #endif
  116011. /********* End of inlined file: juce_Config.h *********/
  116012. #ifdef _MSC_VER
  116013. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  116014. #endif
  116015. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  116016. #if JUCE_USE_OGGVORBIS
  116017. #include <stdlib.h>
  116018. #include <math.h>
  116019. #include <string.h>
  116020. /********* Start of inlined file: masking.h *********/
  116021. #ifndef _V_MASKING_H_
  116022. #define _V_MASKING_H_
  116023. /* more detailed ATH; the bass if flat to save stressing the floor
  116024. overly for only a bin or two of savings. */
  116025. #define MAX_ATH 88
  116026. static float ATH[]={
  116027. /*15*/ -51, -52, -53, -54, -55, -56, -57, -58,
  116028. /*31*/ -59, -60, -61, -62, -63, -64, -65, -66,
  116029. /*63*/ -67, -68, -69, -70, -71, -72, -73, -74,
  116030. /*125*/ -75, -76, -77, -78, -80, -81, -82, -83,
  116031. /*250*/ -84, -85, -86, -87, -88, -88, -89, -89,
  116032. /*500*/ -90, -91, -91, -92, -93, -94, -95, -96,
  116033. /*1k*/ -96, -97, -98, -98, -99, -99,-100,-100,
  116034. /*2k*/ -101,-102,-103,-104,-106,-107,-107,-107,
  116035. /*4k*/ -107,-105,-103,-102,-101, -99, -98, -96,
  116036. /*8k*/ -95, -95, -96, -97, -96, -95, -93, -90,
  116037. /*16k*/ -80, -70, -50, -40, -30, -30, -30, -30
  116038. };
  116039. /* The tone masking curves from Ehmer's and Fielder's papers have been
  116040. replaced by an empirically collected data set. The previously
  116041. published values were, far too often, simply on crack. */
  116042. #define EHMER_OFFSET 16
  116043. #define EHMER_MAX 56
  116044. /* masking tones from -50 to 0dB, 62.5 through 16kHz at half octaves
  116045. test tones from -2 octaves to +5 octaves sampled at eighth octaves */
  116046. /* (Vorbis 0dB, the loudest possible tone, is assumed to be ~100dB SPL
  116047. for collection of these curves) */
  116048. static float tonemasks[P_BANDS][6][EHMER_MAX]={
  116049. /* 62.5 Hz */
  116050. {{ -60, -60, -60, -60, -60, -60, -60, -60,
  116051. -60, -60, -60, -60, -62, -62, -65, -73,
  116052. -69, -68, -68, -67, -70, -70, -72, -74,
  116053. -75, -79, -79, -80, -83, -88, -93, -100,
  116054. -110, -999, -999, -999, -999, -999, -999, -999,
  116055. -999, -999, -999, -999, -999, -999, -999, -999,
  116056. -999, -999, -999, -999, -999, -999, -999, -999},
  116057. { -48, -48, -48, -48, -48, -48, -48, -48,
  116058. -48, -48, -48, -48, -48, -53, -61, -66,
  116059. -66, -68, -67, -70, -76, -76, -72, -73,
  116060. -75, -76, -78, -79, -83, -88, -93, -100,
  116061. -110, -999, -999, -999, -999, -999, -999, -999,
  116062. -999, -999, -999, -999, -999, -999, -999, -999,
  116063. -999, -999, -999, -999, -999, -999, -999, -999},
  116064. { -37, -37, -37, -37, -37, -37, -37, -37,
  116065. -38, -40, -42, -46, -48, -53, -55, -62,
  116066. -65, -58, -56, -56, -61, -60, -65, -67,
  116067. -69, -71, -77, -77, -78, -80, -82, -84,
  116068. -88, -93, -98, -106, -112, -999, -999, -999,
  116069. -999, -999, -999, -999, -999, -999, -999, -999,
  116070. -999, -999, -999, -999, -999, -999, -999, -999},
  116071. { -25, -25, -25, -25, -25, -25, -25, -25,
  116072. -25, -26, -27, -29, -32, -38, -48, -52,
  116073. -52, -50, -48, -48, -51, -52, -54, -60,
  116074. -67, -67, -66, -68, -69, -73, -73, -76,
  116075. -80, -81, -81, -85, -85, -86, -88, -93,
  116076. -100, -110, -999, -999, -999, -999, -999, -999,
  116077. -999, -999, -999, -999, -999, -999, -999, -999},
  116078. { -16, -16, -16, -16, -16, -16, -16, -16,
  116079. -17, -19, -20, -22, -26, -28, -31, -40,
  116080. -47, -39, -39, -40, -42, -43, -47, -51,
  116081. -57, -52, -55, -55, -60, -58, -62, -63,
  116082. -70, -67, -69, -72, -73, -77, -80, -82,
  116083. -83, -87, -90, -94, -98, -104, -115, -999,
  116084. -999, -999, -999, -999, -999, -999, -999, -999},
  116085. { -8, -8, -8, -8, -8, -8, -8, -8,
  116086. -8, -8, -10, -11, -15, -19, -25, -30,
  116087. -34, -31, -30, -31, -29, -32, -35, -42,
  116088. -48, -42, -44, -46, -50, -50, -51, -52,
  116089. -59, -54, -55, -55, -58, -62, -63, -66,
  116090. -72, -73, -76, -75, -78, -80, -80, -81,
  116091. -84, -88, -90, -94, -98, -101, -106, -110}},
  116092. /* 88Hz */
  116093. {{ -66, -66, -66, -66, -66, -66, -66, -66,
  116094. -66, -66, -66, -66, -66, -67, -67, -67,
  116095. -76, -72, -71, -74, -76, -76, -75, -78,
  116096. -79, -79, -81, -83, -86, -89, -93, -97,
  116097. -100, -105, -110, -999, -999, -999, -999, -999,
  116098. -999, -999, -999, -999, -999, -999, -999, -999,
  116099. -999, -999, -999, -999, -999, -999, -999, -999},
  116100. { -47, -47, -47, -47, -47, -47, -47, -47,
  116101. -47, -47, -47, -48, -51, -55, -59, -66,
  116102. -66, -66, -67, -66, -68, -69, -70, -74,
  116103. -79, -77, -77, -78, -80, -81, -82, -84,
  116104. -86, -88, -91, -95, -100, -108, -116, -999,
  116105. -999, -999, -999, -999, -999, -999, -999, -999,
  116106. -999, -999, -999, -999, -999, -999, -999, -999},
  116107. { -36, -36, -36, -36, -36, -36, -36, -36,
  116108. -36, -37, -37, -41, -44, -48, -51, -58,
  116109. -62, -60, -57, -59, -59, -60, -63, -65,
  116110. -72, -71, -70, -72, -74, -77, -76, -78,
  116111. -81, -81, -80, -83, -86, -91, -96, -100,
  116112. -105, -110, -999, -999, -999, -999, -999, -999,
  116113. -999, -999, -999, -999, -999, -999, -999, -999},
  116114. { -28, -28, -28, -28, -28, -28, -28, -28,
  116115. -28, -30, -32, -32, -33, -35, -41, -49,
  116116. -50, -49, -47, -48, -48, -52, -51, -57,
  116117. -65, -61, -59, -61, -64, -69, -70, -74,
  116118. -77, -77, -78, -81, -84, -85, -87, -90,
  116119. -92, -96, -100, -107, -112, -999, -999, -999,
  116120. -999, -999, -999, -999, -999, -999, -999, -999},
  116121. { -19, -19, -19, -19, -19, -19, -19, -19,
  116122. -20, -21, -23, -27, -30, -35, -36, -41,
  116123. -46, -44, -42, -40, -41, -41, -43, -48,
  116124. -55, -53, -52, -53, -56, -59, -58, -60,
  116125. -67, -66, -69, -71, -72, -75, -79, -81,
  116126. -84, -87, -90, -93, -97, -101, -107, -114,
  116127. -999, -999, -999, -999, -999, -999, -999, -999},
  116128. { -9, -9, -9, -9, -9, -9, -9, -9,
  116129. -11, -12, -12, -15, -16, -20, -23, -30,
  116130. -37, -34, -33, -34, -31, -32, -32, -38,
  116131. -47, -44, -41, -40, -47, -49, -46, -46,
  116132. -58, -50, -50, -54, -58, -62, -64, -67,
  116133. -67, -70, -72, -76, -79, -83, -87, -91,
  116134. -96, -100, -104, -110, -999, -999, -999, -999}},
  116135. /* 125 Hz */
  116136. {{ -62, -62, -62, -62, -62, -62, -62, -62,
  116137. -62, -62, -63, -64, -66, -67, -66, -68,
  116138. -75, -72, -76, -75, -76, -78, -79, -82,
  116139. -84, -85, -90, -94, -101, -110, -999, -999,
  116140. -999, -999, -999, -999, -999, -999, -999, -999,
  116141. -999, -999, -999, -999, -999, -999, -999, -999,
  116142. -999, -999, -999, -999, -999, -999, -999, -999},
  116143. { -59, -59, -59, -59, -59, -59, -59, -59,
  116144. -59, -59, -59, -60, -60, -61, -63, -66,
  116145. -71, -68, -70, -70, -71, -72, -72, -75,
  116146. -81, -78, -79, -82, -83, -86, -90, -97,
  116147. -103, -113, -999, -999, -999, -999, -999, -999,
  116148. -999, -999, -999, -999, -999, -999, -999, -999,
  116149. -999, -999, -999, -999, -999, -999, -999, -999},
  116150. { -53, -53, -53, -53, -53, -53, -53, -53,
  116151. -53, -54, -55, -57, -56, -57, -55, -61,
  116152. -65, -60, -60, -62, -63, -63, -66, -68,
  116153. -74, -73, -75, -75, -78, -80, -80, -82,
  116154. -85, -90, -96, -101, -108, -999, -999, -999,
  116155. -999, -999, -999, -999, -999, -999, -999, -999,
  116156. -999, -999, -999, -999, -999, -999, -999, -999},
  116157. { -46, -46, -46, -46, -46, -46, -46, -46,
  116158. -46, -46, -47, -47, -47, -47, -48, -51,
  116159. -57, -51, -49, -50, -51, -53, -54, -59,
  116160. -66, -60, -62, -67, -67, -70, -72, -75,
  116161. -76, -78, -81, -85, -88, -94, -97, -104,
  116162. -112, -999, -999, -999, -999, -999, -999, -999,
  116163. -999, -999, -999, -999, -999, -999, -999, -999},
  116164. { -36, -36, -36, -36, -36, -36, -36, -36,
  116165. -39, -41, -42, -42, -39, -38, -41, -43,
  116166. -52, -44, -40, -39, -37, -37, -40, -47,
  116167. -54, -50, -48, -50, -55, -61, -59, -62,
  116168. -66, -66, -66, -69, -69, -73, -74, -74,
  116169. -75, -77, -79, -82, -87, -91, -95, -100,
  116170. -108, -115, -999, -999, -999, -999, -999, -999},
  116171. { -28, -26, -24, -22, -20, -20, -23, -29,
  116172. -30, -31, -28, -27, -28, -28, -28, -35,
  116173. -40, -33, -32, -29, -30, -30, -30, -37,
  116174. -45, -41, -37, -38, -45, -47, -47, -48,
  116175. -53, -49, -48, -50, -49, -49, -51, -52,
  116176. -58, -56, -57, -56, -60, -61, -62, -70,
  116177. -72, -74, -78, -83, -88, -93, -100, -106}},
  116178. /* 177 Hz */
  116179. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116180. -999, -110, -105, -100, -95, -91, -87, -83,
  116181. -80, -78, -76, -78, -78, -81, -83, -85,
  116182. -86, -85, -86, -87, -90, -97, -107, -999,
  116183. -999, -999, -999, -999, -999, -999, -999, -999,
  116184. -999, -999, -999, -999, -999, -999, -999, -999,
  116185. -999, -999, -999, -999, -999, -999, -999, -999},
  116186. {-999, -999, -999, -110, -105, -100, -95, -90,
  116187. -85, -81, -77, -73, -70, -67, -67, -68,
  116188. -75, -73, -70, -69, -70, -72, -75, -79,
  116189. -84, -83, -84, -86, -88, -89, -89, -93,
  116190. -98, -105, -112, -999, -999, -999, -999, -999,
  116191. -999, -999, -999, -999, -999, -999, -999, -999,
  116192. -999, -999, -999, -999, -999, -999, -999, -999},
  116193. {-105, -100, -95, -90, -85, -80, -76, -71,
  116194. -68, -68, -65, -63, -63, -62, -62, -64,
  116195. -65, -64, -61, -62, -63, -64, -66, -68,
  116196. -73, -73, -74, -75, -76, -81, -83, -85,
  116197. -88, -89, -92, -95, -100, -108, -999, -999,
  116198. -999, -999, -999, -999, -999, -999, -999, -999,
  116199. -999, -999, -999, -999, -999, -999, -999, -999},
  116200. { -80, -75, -71, -68, -65, -63, -62, -61,
  116201. -61, -61, -61, -59, -56, -57, -53, -50,
  116202. -58, -52, -50, -50, -52, -53, -54, -58,
  116203. -67, -63, -67, -68, -72, -75, -78, -80,
  116204. -81, -81, -82, -85, -89, -90, -93, -97,
  116205. -101, -107, -114, -999, -999, -999, -999, -999,
  116206. -999, -999, -999, -999, -999, -999, -999, -999},
  116207. { -65, -61, -59, -57, -56, -55, -55, -56,
  116208. -56, -57, -55, -53, -52, -47, -44, -44,
  116209. -50, -44, -41, -39, -39, -42, -40, -46,
  116210. -51, -49, -50, -53, -54, -63, -60, -61,
  116211. -62, -66, -66, -66, -70, -73, -74, -75,
  116212. -76, -75, -79, -85, -89, -91, -96, -102,
  116213. -110, -999, -999, -999, -999, -999, -999, -999},
  116214. { -52, -50, -49, -49, -48, -48, -48, -49,
  116215. -50, -50, -49, -46, -43, -39, -35, -33,
  116216. -38, -36, -32, -29, -32, -32, -32, -35,
  116217. -44, -39, -38, -38, -46, -50, -45, -46,
  116218. -53, -50, -50, -50, -54, -54, -53, -53,
  116219. -56, -57, -59, -66, -70, -72, -74, -79,
  116220. -83, -85, -90, -97, -114, -999, -999, -999}},
  116221. /* 250 Hz */
  116222. {{-999, -999, -999, -999, -999, -999, -110, -105,
  116223. -100, -95, -90, -86, -80, -75, -75, -79,
  116224. -80, -79, -80, -81, -82, -88, -95, -103,
  116225. -110, -999, -999, -999, -999, -999, -999, -999,
  116226. -999, -999, -999, -999, -999, -999, -999, -999,
  116227. -999, -999, -999, -999, -999, -999, -999, -999,
  116228. -999, -999, -999, -999, -999, -999, -999, -999},
  116229. {-999, -999, -999, -999, -108, -103, -98, -93,
  116230. -88, -83, -79, -78, -75, -71, -67, -68,
  116231. -73, -73, -72, -73, -75, -77, -80, -82,
  116232. -88, -93, -100, -107, -114, -999, -999, -999,
  116233. -999, -999, -999, -999, -999, -999, -999, -999,
  116234. -999, -999, -999, -999, -999, -999, -999, -999,
  116235. -999, -999, -999, -999, -999, -999, -999, -999},
  116236. {-999, -999, -999, -110, -105, -101, -96, -90,
  116237. -86, -81, -77, -73, -69, -66, -61, -62,
  116238. -66, -64, -62, -65, -66, -70, -72, -76,
  116239. -81, -80, -84, -90, -95, -102, -110, -999,
  116240. -999, -999, -999, -999, -999, -999, -999, -999,
  116241. -999, -999, -999, -999, -999, -999, -999, -999,
  116242. -999, -999, -999, -999, -999, -999, -999, -999},
  116243. {-999, -999, -999, -107, -103, -97, -92, -88,
  116244. -83, -79, -74, -70, -66, -59, -53, -58,
  116245. -62, -55, -54, -54, -54, -58, -61, -62,
  116246. -72, -70, -72, -75, -78, -80, -81, -80,
  116247. -83, -83, -88, -93, -100, -107, -115, -999,
  116248. -999, -999, -999, -999, -999, -999, -999, -999,
  116249. -999, -999, -999, -999, -999, -999, -999, -999},
  116250. {-999, -999, -999, -105, -100, -95, -90, -85,
  116251. -80, -75, -70, -66, -62, -56, -48, -44,
  116252. -48, -46, -46, -43, -46, -48, -48, -51,
  116253. -58, -58, -59, -60, -62, -62, -61, -61,
  116254. -65, -64, -65, -68, -70, -74, -75, -78,
  116255. -81, -86, -95, -110, -999, -999, -999, -999,
  116256. -999, -999, -999, -999, -999, -999, -999, -999},
  116257. {-999, -999, -105, -100, -95, -90, -85, -80,
  116258. -75, -70, -65, -61, -55, -49, -39, -33,
  116259. -40, -35, -32, -38, -40, -33, -35, -37,
  116260. -46, -41, -45, -44, -46, -42, -45, -46,
  116261. -52, -50, -50, -50, -54, -54, -55, -57,
  116262. -62, -64, -66, -68, -70, -76, -81, -90,
  116263. -100, -110, -999, -999, -999, -999, -999, -999}},
  116264. /* 354 hz */
  116265. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116266. -105, -98, -90, -85, -82, -83, -80, -78,
  116267. -84, -79, -80, -83, -87, -89, -91, -93,
  116268. -99, -106, -117, -999, -999, -999, -999, -999,
  116269. -999, -999, -999, -999, -999, -999, -999, -999,
  116270. -999, -999, -999, -999, -999, -999, -999, -999,
  116271. -999, -999, -999, -999, -999, -999, -999, -999},
  116272. {-999, -999, -999, -999, -999, -999, -999, -999,
  116273. -105, -98, -90, -85, -80, -75, -70, -68,
  116274. -74, -72, -74, -77, -80, -82, -85, -87,
  116275. -92, -89, -91, -95, -100, -106, -112, -999,
  116276. -999, -999, -999, -999, -999, -999, -999, -999,
  116277. -999, -999, -999, -999, -999, -999, -999, -999,
  116278. -999, -999, -999, -999, -999, -999, -999, -999},
  116279. {-999, -999, -999, -999, -999, -999, -999, -999,
  116280. -105, -98, -90, -83, -75, -71, -63, -64,
  116281. -67, -62, -64, -67, -70, -73, -77, -81,
  116282. -84, -83, -85, -89, -90, -93, -98, -104,
  116283. -109, -114, -999, -999, -999, -999, -999, -999,
  116284. -999, -999, -999, -999, -999, -999, -999, -999,
  116285. -999, -999, -999, -999, -999, -999, -999, -999},
  116286. {-999, -999, -999, -999, -999, -999, -999, -999,
  116287. -103, -96, -88, -81, -75, -68, -58, -54,
  116288. -56, -54, -56, -56, -58, -60, -63, -66,
  116289. -74, -69, -72, -72, -75, -74, -77, -81,
  116290. -81, -82, -84, -87, -93, -96, -99, -104,
  116291. -110, -999, -999, -999, -999, -999, -999, -999,
  116292. -999, -999, -999, -999, -999, -999, -999, -999},
  116293. {-999, -999, -999, -999, -999, -108, -102, -96,
  116294. -91, -85, -80, -74, -68, -60, -51, -46,
  116295. -48, -46, -43, -45, -47, -47, -49, -48,
  116296. -56, -53, -55, -58, -57, -63, -58, -60,
  116297. -66, -64, -67, -70, -70, -74, -77, -84,
  116298. -86, -89, -91, -93, -94, -101, -109, -118,
  116299. -999, -999, -999, -999, -999, -999, -999, -999},
  116300. {-999, -999, -999, -108, -103, -98, -93, -88,
  116301. -83, -78, -73, -68, -60, -53, -44, -35,
  116302. -38, -38, -34, -34, -36, -40, -41, -44,
  116303. -51, -45, -46, -47, -46, -54, -50, -49,
  116304. -50, -50, -50, -51, -54, -57, -58, -60,
  116305. -66, -66, -66, -64, -65, -68, -77, -82,
  116306. -87, -95, -110, -999, -999, -999, -999, -999}},
  116307. /* 500 Hz */
  116308. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116309. -107, -102, -97, -92, -87, -83, -78, -75,
  116310. -82, -79, -83, -85, -89, -92, -95, -98,
  116311. -101, -105, -109, -113, -999, -999, -999, -999,
  116312. -999, -999, -999, -999, -999, -999, -999, -999,
  116313. -999, -999, -999, -999, -999, -999, -999, -999,
  116314. -999, -999, -999, -999, -999, -999, -999, -999},
  116315. {-999, -999, -999, -999, -999, -999, -999, -106,
  116316. -100, -95, -90, -86, -81, -78, -74, -69,
  116317. -74, -74, -76, -79, -83, -84, -86, -89,
  116318. -92, -97, -93, -100, -103, -107, -110, -999,
  116319. -999, -999, -999, -999, -999, -999, -999, -999,
  116320. -999, -999, -999, -999, -999, -999, -999, -999,
  116321. -999, -999, -999, -999, -999, -999, -999, -999},
  116322. {-999, -999, -999, -999, -999, -999, -106, -100,
  116323. -95, -90, -87, -83, -80, -75, -69, -60,
  116324. -66, -66, -68, -70, -74, -78, -79, -81,
  116325. -81, -83, -84, -87, -93, -96, -99, -103,
  116326. -107, -110, -999, -999, -999, -999, -999, -999,
  116327. -999, -999, -999, -999, -999, -999, -999, -999,
  116328. -999, -999, -999, -999, -999, -999, -999, -999},
  116329. {-999, -999, -999, -999, -999, -108, -103, -98,
  116330. -93, -89, -85, -82, -78, -71, -62, -55,
  116331. -58, -58, -54, -54, -55, -59, -61, -62,
  116332. -70, -66, -66, -67, -70, -72, -75, -78,
  116333. -84, -84, -84, -88, -91, -90, -95, -98,
  116334. -102, -103, -106, -110, -999, -999, -999, -999,
  116335. -999, -999, -999, -999, -999, -999, -999, -999},
  116336. {-999, -999, -999, -999, -108, -103, -98, -94,
  116337. -90, -87, -82, -79, -73, -67, -58, -47,
  116338. -50, -45, -41, -45, -48, -44, -44, -49,
  116339. -54, -51, -48, -47, -49, -50, -51, -57,
  116340. -58, -60, -63, -69, -70, -69, -71, -74,
  116341. -78, -82, -90, -95, -101, -105, -110, -999,
  116342. -999, -999, -999, -999, -999, -999, -999, -999},
  116343. {-999, -999, -999, -105, -101, -97, -93, -90,
  116344. -85, -80, -77, -72, -65, -56, -48, -37,
  116345. -40, -36, -34, -40, -50, -47, -38, -41,
  116346. -47, -38, -35, -39, -38, -43, -40, -45,
  116347. -50, -45, -44, -47, -50, -55, -48, -48,
  116348. -52, -66, -70, -76, -82, -90, -97, -105,
  116349. -110, -999, -999, -999, -999, -999, -999, -999}},
  116350. /* 707 Hz */
  116351. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116352. -999, -108, -103, -98, -93, -86, -79, -76,
  116353. -83, -81, -85, -87, -89, -93, -98, -102,
  116354. -107, -112, -999, -999, -999, -999, -999, -999,
  116355. -999, -999, -999, -999, -999, -999, -999, -999,
  116356. -999, -999, -999, -999, -999, -999, -999, -999,
  116357. -999, -999, -999, -999, -999, -999, -999, -999},
  116358. {-999, -999, -999, -999, -999, -999, -999, -999,
  116359. -999, -108, -103, -98, -93, -86, -79, -71,
  116360. -77, -74, -77, -79, -81, -84, -85, -90,
  116361. -92, -93, -92, -98, -101, -108, -112, -999,
  116362. -999, -999, -999, -999, -999, -999, -999, -999,
  116363. -999, -999, -999, -999, -999, -999, -999, -999,
  116364. -999, -999, -999, -999, -999, -999, -999, -999},
  116365. {-999, -999, -999, -999, -999, -999, -999, -999,
  116366. -108, -103, -98, -93, -87, -78, -68, -65,
  116367. -66, -62, -65, -67, -70, -73, -75, -78,
  116368. -82, -82, -83, -84, -91, -93, -98, -102,
  116369. -106, -110, -999, -999, -999, -999, -999, -999,
  116370. -999, -999, -999, -999, -999, -999, -999, -999,
  116371. -999, -999, -999, -999, -999, -999, -999, -999},
  116372. {-999, -999, -999, -999, -999, -999, -999, -999,
  116373. -105, -100, -95, -90, -82, -74, -62, -57,
  116374. -58, -56, -51, -52, -52, -54, -54, -58,
  116375. -66, -59, -60, -63, -66, -69, -73, -79,
  116376. -83, -84, -80, -81, -81, -82, -88, -92,
  116377. -98, -105, -113, -999, -999, -999, -999, -999,
  116378. -999, -999, -999, -999, -999, -999, -999, -999},
  116379. {-999, -999, -999, -999, -999, -999, -999, -107,
  116380. -102, -97, -92, -84, -79, -69, -57, -47,
  116381. -52, -47, -44, -45, -50, -52, -42, -42,
  116382. -53, -43, -43, -48, -51, -56, -55, -52,
  116383. -57, -59, -61, -62, -67, -71, -78, -83,
  116384. -86, -94, -98, -103, -110, -999, -999, -999,
  116385. -999, -999, -999, -999, -999, -999, -999, -999},
  116386. {-999, -999, -999, -999, -999, -999, -105, -100,
  116387. -95, -90, -84, -78, -70, -61, -51, -41,
  116388. -40, -38, -40, -46, -52, -51, -41, -40,
  116389. -46, -40, -38, -38, -41, -46, -41, -46,
  116390. -47, -43, -43, -45, -41, -45, -56, -67,
  116391. -68, -83, -87, -90, -95, -102, -107, -113,
  116392. -999, -999, -999, -999, -999, -999, -999, -999}},
  116393. /* 1000 Hz */
  116394. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116395. -999, -109, -105, -101, -96, -91, -84, -77,
  116396. -82, -82, -85, -89, -94, -100, -106, -110,
  116397. -999, -999, -999, -999, -999, -999, -999, -999,
  116398. -999, -999, -999, -999, -999, -999, -999, -999,
  116399. -999, -999, -999, -999, -999, -999, -999, -999,
  116400. -999, -999, -999, -999, -999, -999, -999, -999},
  116401. {-999, -999, -999, -999, -999, -999, -999, -999,
  116402. -999, -106, -103, -98, -92, -85, -80, -71,
  116403. -75, -72, -76, -80, -84, -86, -89, -93,
  116404. -100, -107, -113, -999, -999, -999, -999, -999,
  116405. -999, -999, -999, -999, -999, -999, -999, -999,
  116406. -999, -999, -999, -999, -999, -999, -999, -999,
  116407. -999, -999, -999, -999, -999, -999, -999, -999},
  116408. {-999, -999, -999, -999, -999, -999, -999, -107,
  116409. -104, -101, -97, -92, -88, -84, -80, -64,
  116410. -66, -63, -64, -66, -69, -73, -77, -83,
  116411. -83, -86, -91, -98, -104, -111, -999, -999,
  116412. -999, -999, -999, -999, -999, -999, -999, -999,
  116413. -999, -999, -999, -999, -999, -999, -999, -999,
  116414. -999, -999, -999, -999, -999, -999, -999, -999},
  116415. {-999, -999, -999, -999, -999, -999, -999, -107,
  116416. -104, -101, -97, -92, -90, -84, -74, -57,
  116417. -58, -52, -55, -54, -50, -52, -50, -52,
  116418. -63, -62, -69, -76, -77, -78, -78, -79,
  116419. -82, -88, -94, -100, -106, -111, -999, -999,
  116420. -999, -999, -999, -999, -999, -999, -999, -999,
  116421. -999, -999, -999, -999, -999, -999, -999, -999},
  116422. {-999, -999, -999, -999, -999, -999, -106, -102,
  116423. -98, -95, -90, -85, -83, -78, -70, -50,
  116424. -50, -41, -44, -49, -47, -50, -50, -44,
  116425. -55, -46, -47, -48, -48, -54, -49, -49,
  116426. -58, -62, -71, -81, -87, -92, -97, -102,
  116427. -108, -114, -999, -999, -999, -999, -999, -999,
  116428. -999, -999, -999, -999, -999, -999, -999, -999},
  116429. {-999, -999, -999, -999, -999, -999, -106, -102,
  116430. -98, -95, -90, -85, -83, -78, -70, -45,
  116431. -43, -41, -47, -50, -51, -50, -49, -45,
  116432. -47, -41, -44, -41, -39, -43, -38, -37,
  116433. -40, -41, -44, -50, -58, -65, -73, -79,
  116434. -85, -92, -97, -101, -105, -109, -113, -999,
  116435. -999, -999, -999, -999, -999, -999, -999, -999}},
  116436. /* 1414 Hz */
  116437. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116438. -999, -999, -999, -107, -100, -95, -87, -81,
  116439. -85, -83, -88, -93, -100, -107, -114, -999,
  116440. -999, -999, -999, -999, -999, -999, -999, -999,
  116441. -999, -999, -999, -999, -999, -999, -999, -999,
  116442. -999, -999, -999, -999, -999, -999, -999, -999,
  116443. -999, -999, -999, -999, -999, -999, -999, -999},
  116444. {-999, -999, -999, -999, -999, -999, -999, -999,
  116445. -999, -999, -107, -101, -95, -88, -83, -76,
  116446. -73, -72, -79, -84, -90, -95, -100, -105,
  116447. -110, -115, -999, -999, -999, -999, -999, -999,
  116448. -999, -999, -999, -999, -999, -999, -999, -999,
  116449. -999, -999, -999, -999, -999, -999, -999, -999,
  116450. -999, -999, -999, -999, -999, -999, -999, -999},
  116451. {-999, -999, -999, -999, -999, -999, -999, -999,
  116452. -999, -999, -104, -98, -92, -87, -81, -70,
  116453. -65, -62, -67, -71, -74, -80, -85, -91,
  116454. -95, -99, -103, -108, -111, -114, -999, -999,
  116455. -999, -999, -999, -999, -999, -999, -999, -999,
  116456. -999, -999, -999, -999, -999, -999, -999, -999,
  116457. -999, -999, -999, -999, -999, -999, -999, -999},
  116458. {-999, -999, -999, -999, -999, -999, -999, -999,
  116459. -999, -999, -103, -97, -90, -85, -76, -60,
  116460. -56, -54, -60, -62, -61, -56, -63, -65,
  116461. -73, -74, -77, -75, -78, -81, -86, -87,
  116462. -88, -91, -94, -98, -103, -110, -999, -999,
  116463. -999, -999, -999, -999, -999, -999, -999, -999,
  116464. -999, -999, -999, -999, -999, -999, -999, -999},
  116465. {-999, -999, -999, -999, -999, -999, -999, -105,
  116466. -100, -97, -92, -86, -81, -79, -70, -57,
  116467. -51, -47, -51, -58, -60, -56, -53, -50,
  116468. -58, -52, -50, -50, -53, -55, -64, -69,
  116469. -71, -85, -82, -78, -81, -85, -95, -102,
  116470. -112, -999, -999, -999, -999, -999, -999, -999,
  116471. -999, -999, -999, -999, -999, -999, -999, -999},
  116472. {-999, -999, -999, -999, -999, -999, -999, -105,
  116473. -100, -97, -92, -85, -83, -79, -72, -49,
  116474. -40, -43, -43, -54, -56, -51, -50, -40,
  116475. -43, -38, -36, -35, -37, -38, -37, -44,
  116476. -54, -60, -57, -60, -70, -75, -84, -92,
  116477. -103, -112, -999, -999, -999, -999, -999, -999,
  116478. -999, -999, -999, -999, -999, -999, -999, -999}},
  116479. /* 2000 Hz */
  116480. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116481. -999, -999, -999, -110, -102, -95, -89, -82,
  116482. -83, -84, -90, -92, -99, -107, -113, -999,
  116483. -999, -999, -999, -999, -999, -999, -999, -999,
  116484. -999, -999, -999, -999, -999, -999, -999, -999,
  116485. -999, -999, -999, -999, -999, -999, -999, -999,
  116486. -999, -999, -999, -999, -999, -999, -999, -999},
  116487. {-999, -999, -999, -999, -999, -999, -999, -999,
  116488. -999, -999, -107, -101, -95, -89, -83, -72,
  116489. -74, -78, -85, -88, -88, -90, -92, -98,
  116490. -105, -111, -999, -999, -999, -999, -999, -999,
  116491. -999, -999, -999, -999, -999, -999, -999, -999,
  116492. -999, -999, -999, -999, -999, -999, -999, -999,
  116493. -999, -999, -999, -999, -999, -999, -999, -999},
  116494. {-999, -999, -999, -999, -999, -999, -999, -999,
  116495. -999, -109, -103, -97, -93, -87, -81, -70,
  116496. -70, -67, -75, -73, -76, -79, -81, -83,
  116497. -88, -89, -97, -103, -110, -999, -999, -999,
  116498. -999, -999, -999, -999, -999, -999, -999, -999,
  116499. -999, -999, -999, -999, -999, -999, -999, -999,
  116500. -999, -999, -999, -999, -999, -999, -999, -999},
  116501. {-999, -999, -999, -999, -999, -999, -999, -999,
  116502. -999, -107, -100, -94, -88, -83, -75, -63,
  116503. -59, -59, -63, -66, -60, -62, -67, -67,
  116504. -77, -76, -81, -88, -86, -92, -96, -102,
  116505. -109, -116, -999, -999, -999, -999, -999, -999,
  116506. -999, -999, -999, -999, -999, -999, -999, -999,
  116507. -999, -999, -999, -999, -999, -999, -999, -999},
  116508. {-999, -999, -999, -999, -999, -999, -999, -999,
  116509. -999, -105, -98, -92, -86, -81, -73, -56,
  116510. -52, -47, -55, -60, -58, -52, -51, -45,
  116511. -49, -50, -53, -54, -61, -71, -70, -69,
  116512. -78, -79, -87, -90, -96, -104, -112, -999,
  116513. -999, -999, -999, -999, -999, -999, -999, -999,
  116514. -999, -999, -999, -999, -999, -999, -999, -999},
  116515. {-999, -999, -999, -999, -999, -999, -999, -999,
  116516. -999, -103, -96, -90, -86, -78, -70, -51,
  116517. -42, -47, -48, -55, -54, -54, -53, -42,
  116518. -35, -28, -33, -38, -37, -44, -47, -49,
  116519. -54, -63, -68, -78, -82, -89, -94, -99,
  116520. -104, -109, -114, -999, -999, -999, -999, -999,
  116521. -999, -999, -999, -999, -999, -999, -999, -999}},
  116522. /* 2828 Hz */
  116523. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116524. -999, -999, -999, -999, -110, -100, -90, -79,
  116525. -85, -81, -82, -82, -89, -94, -99, -103,
  116526. -109, -115, -999, -999, -999, -999, -999, -999,
  116527. -999, -999, -999, -999, -999, -999, -999, -999,
  116528. -999, -999, -999, -999, -999, -999, -999, -999,
  116529. -999, -999, -999, -999, -999, -999, -999, -999},
  116530. {-999, -999, -999, -999, -999, -999, -999, -999,
  116531. -999, -999, -999, -999, -105, -97, -85, -72,
  116532. -74, -70, -70, -70, -76, -85, -91, -93,
  116533. -97, -103, -109, -115, -999, -999, -999, -999,
  116534. -999, -999, -999, -999, -999, -999, -999, -999,
  116535. -999, -999, -999, -999, -999, -999, -999, -999,
  116536. -999, -999, -999, -999, -999, -999, -999, -999},
  116537. {-999, -999, -999, -999, -999, -999, -999, -999,
  116538. -999, -999, -999, -999, -112, -93, -81, -68,
  116539. -62, -60, -60, -57, -63, -70, -77, -82,
  116540. -90, -93, -98, -104, -109, -113, -999, -999,
  116541. -999, -999, -999, -999, -999, -999, -999, -999,
  116542. -999, -999, -999, -999, -999, -999, -999, -999,
  116543. -999, -999, -999, -999, -999, -999, -999, -999},
  116544. {-999, -999, -999, -999, -999, -999, -999, -999,
  116545. -999, -999, -999, -113, -100, -93, -84, -63,
  116546. -58, -48, -53, -54, -52, -52, -57, -64,
  116547. -66, -76, -83, -81, -85, -85, -90, -95,
  116548. -98, -101, -103, -106, -108, -111, -999, -999,
  116549. -999, -999, -999, -999, -999, -999, -999, -999,
  116550. -999, -999, -999, -999, -999, -999, -999, -999},
  116551. {-999, -999, -999, -999, -999, -999, -999, -999,
  116552. -999, -999, -999, -105, -95, -86, -74, -53,
  116553. -50, -38, -43, -49, -43, -42, -39, -39,
  116554. -46, -52, -57, -56, -72, -69, -74, -81,
  116555. -87, -92, -94, -97, -99, -102, -105, -108,
  116556. -999, -999, -999, -999, -999, -999, -999, -999,
  116557. -999, -999, -999, -999, -999, -999, -999, -999},
  116558. {-999, -999, -999, -999, -999, -999, -999, -999,
  116559. -999, -999, -108, -99, -90, -76, -66, -45,
  116560. -43, -41, -44, -47, -43, -47, -40, -30,
  116561. -31, -31, -39, -33, -40, -41, -43, -53,
  116562. -59, -70, -73, -77, -79, -82, -84, -87,
  116563. -999, -999, -999, -999, -999, -999, -999, -999,
  116564. -999, -999, -999, -999, -999, -999, -999, -999}},
  116565. /* 4000 Hz */
  116566. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116567. -999, -999, -999, -999, -999, -110, -91, -76,
  116568. -75, -85, -93, -98, -104, -110, -999, -999,
  116569. -999, -999, -999, -999, -999, -999, -999, -999,
  116570. -999, -999, -999, -999, -999, -999, -999, -999,
  116571. -999, -999, -999, -999, -999, -999, -999, -999,
  116572. -999, -999, -999, -999, -999, -999, -999, -999},
  116573. {-999, -999, -999, -999, -999, -999, -999, -999,
  116574. -999, -999, -999, -999, -999, -110, -91, -70,
  116575. -70, -75, -86, -89, -94, -98, -101, -106,
  116576. -110, -999, -999, -999, -999, -999, -999, -999,
  116577. -999, -999, -999, -999, -999, -999, -999, -999,
  116578. -999, -999, -999, -999, -999, -999, -999, -999,
  116579. -999, -999, -999, -999, -999, -999, -999, -999},
  116580. {-999, -999, -999, -999, -999, -999, -999, -999,
  116581. -999, -999, -999, -999, -110, -95, -80, -60,
  116582. -65, -64, -74, -83, -88, -91, -95, -99,
  116583. -103, -107, -110, -999, -999, -999, -999, -999,
  116584. -999, -999, -999, -999, -999, -999, -999, -999,
  116585. -999, -999, -999, -999, -999, -999, -999, -999,
  116586. -999, -999, -999, -999, -999, -999, -999, -999},
  116587. {-999, -999, -999, -999, -999, -999, -999, -999,
  116588. -999, -999, -999, -999, -110, -95, -80, -58,
  116589. -55, -49, -66, -68, -71, -78, -78, -80,
  116590. -88, -85, -89, -97, -100, -105, -110, -999,
  116591. -999, -999, -999, -999, -999, -999, -999, -999,
  116592. -999, -999, -999, -999, -999, -999, -999, -999,
  116593. -999, -999, -999, -999, -999, -999, -999, -999},
  116594. {-999, -999, -999, -999, -999, -999, -999, -999,
  116595. -999, -999, -999, -999, -110, -95, -80, -53,
  116596. -52, -41, -59, -59, -49, -58, -56, -63,
  116597. -86, -79, -90, -93, -98, -103, -107, -112,
  116598. -999, -999, -999, -999, -999, -999, -999, -999,
  116599. -999, -999, -999, -999, -999, -999, -999, -999,
  116600. -999, -999, -999, -999, -999, -999, -999, -999},
  116601. {-999, -999, -999, -999, -999, -999, -999, -999,
  116602. -999, -999, -999, -110, -97, -91, -73, -45,
  116603. -40, -33, -53, -61, -49, -54, -50, -50,
  116604. -60, -52, -67, -74, -81, -92, -96, -100,
  116605. -105, -110, -999, -999, -999, -999, -999, -999,
  116606. -999, -999, -999, -999, -999, -999, -999, -999,
  116607. -999, -999, -999, -999, -999, -999, -999, -999}},
  116608. /* 5657 Hz */
  116609. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116610. -999, -999, -999, -113, -106, -99, -92, -77,
  116611. -80, -88, -97, -106, -115, -999, -999, -999,
  116612. -999, -999, -999, -999, -999, -999, -999, -999,
  116613. -999, -999, -999, -999, -999, -999, -999, -999,
  116614. -999, -999, -999, -999, -999, -999, -999, -999,
  116615. -999, -999, -999, -999, -999, -999, -999, -999},
  116616. {-999, -999, -999, -999, -999, -999, -999, -999,
  116617. -999, -999, -116, -109, -102, -95, -89, -74,
  116618. -72, -88, -87, -95, -102, -109, -116, -999,
  116619. -999, -999, -999, -999, -999, -999, -999, -999,
  116620. -999, -999, -999, -999, -999, -999, -999, -999,
  116621. -999, -999, -999, -999, -999, -999, -999, -999,
  116622. -999, -999, -999, -999, -999, -999, -999, -999},
  116623. {-999, -999, -999, -999, -999, -999, -999, -999,
  116624. -999, -999, -116, -109, -102, -95, -89, -75,
  116625. -66, -74, -77, -78, -86, -87, -90, -96,
  116626. -105, -115, -999, -999, -999, -999, -999, -999,
  116627. -999, -999, -999, -999, -999, -999, -999, -999,
  116628. -999, -999, -999, -999, -999, -999, -999, -999,
  116629. -999, -999, -999, -999, -999, -999, -999, -999},
  116630. {-999, -999, -999, -999, -999, -999, -999, -999,
  116631. -999, -999, -115, -108, -101, -94, -88, -66,
  116632. -56, -61, -70, -65, -78, -72, -83, -84,
  116633. -93, -98, -105, -110, -999, -999, -999, -999,
  116634. -999, -999, -999, -999, -999, -999, -999, -999,
  116635. -999, -999, -999, -999, -999, -999, -999, -999,
  116636. -999, -999, -999, -999, -999, -999, -999, -999},
  116637. {-999, -999, -999, -999, -999, -999, -999, -999,
  116638. -999, -999, -110, -105, -95, -89, -82, -57,
  116639. -52, -52, -59, -56, -59, -58, -69, -67,
  116640. -88, -82, -82, -89, -94, -100, -108, -999,
  116641. -999, -999, -999, -999, -999, -999, -999, -999,
  116642. -999, -999, -999, -999, -999, -999, -999, -999,
  116643. -999, -999, -999, -999, -999, -999, -999, -999},
  116644. {-999, -999, -999, -999, -999, -999, -999, -999,
  116645. -999, -110, -101, -96, -90, -83, -77, -54,
  116646. -43, -38, -50, -48, -52, -48, -42, -42,
  116647. -51, -52, -53, -59, -65, -71, -78, -85,
  116648. -95, -999, -999, -999, -999, -999, -999, -999,
  116649. -999, -999, -999, -999, -999, -999, -999, -999,
  116650. -999, -999, -999, -999, -999, -999, -999, -999}},
  116651. /* 8000 Hz */
  116652. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116653. -999, -999, -999, -999, -120, -105, -86, -68,
  116654. -78, -79, -90, -100, -110, -999, -999, -999,
  116655. -999, -999, -999, -999, -999, -999, -999, -999,
  116656. -999, -999, -999, -999, -999, -999, -999, -999,
  116657. -999, -999, -999, -999, -999, -999, -999, -999,
  116658. -999, -999, -999, -999, -999, -999, -999, -999},
  116659. {-999, -999, -999, -999, -999, -999, -999, -999,
  116660. -999, -999, -999, -999, -120, -105, -86, -66,
  116661. -73, -77, -88, -96, -105, -115, -999, -999,
  116662. -999, -999, -999, -999, -999, -999, -999, -999,
  116663. -999, -999, -999, -999, -999, -999, -999, -999,
  116664. -999, -999, -999, -999, -999, -999, -999, -999,
  116665. -999, -999, -999, -999, -999, -999, -999, -999},
  116666. {-999, -999, -999, -999, -999, -999, -999, -999,
  116667. -999, -999, -999, -120, -105, -92, -80, -61,
  116668. -64, -68, -80, -87, -92, -100, -110, -999,
  116669. -999, -999, -999, -999, -999, -999, -999, -999,
  116670. -999, -999, -999, -999, -999, -999, -999, -999,
  116671. -999, -999, -999, -999, -999, -999, -999, -999,
  116672. -999, -999, -999, -999, -999, -999, -999, -999},
  116673. {-999, -999, -999, -999, -999, -999, -999, -999,
  116674. -999, -999, -999, -120, -104, -91, -79, -52,
  116675. -60, -54, -64, -69, -77, -80, -82, -84,
  116676. -85, -87, -88, -90, -999, -999, -999, -999,
  116677. -999, -999, -999, -999, -999, -999, -999, -999,
  116678. -999, -999, -999, -999, -999, -999, -999, -999,
  116679. -999, -999, -999, -999, -999, -999, -999, -999},
  116680. {-999, -999, -999, -999, -999, -999, -999, -999,
  116681. -999, -999, -999, -118, -100, -87, -77, -49,
  116682. -50, -44, -58, -61, -61, -67, -65, -62,
  116683. -62, -62, -65, -68, -999, -999, -999, -999,
  116684. -999, -999, -999, -999, -999, -999, -999, -999,
  116685. -999, -999, -999, -999, -999, -999, -999, -999,
  116686. -999, -999, -999, -999, -999, -999, -999, -999},
  116687. {-999, -999, -999, -999, -999, -999, -999, -999,
  116688. -999, -999, -999, -115, -98, -84, -62, -49,
  116689. -44, -38, -46, -49, -49, -46, -39, -37,
  116690. -39, -40, -42, -43, -999, -999, -999, -999,
  116691. -999, -999, -999, -999, -999, -999, -999, -999,
  116692. -999, -999, -999, -999, -999, -999, -999, -999,
  116693. -999, -999, -999, -999, -999, -999, -999, -999}},
  116694. /* 11314 Hz */
  116695. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116696. -999, -999, -999, -999, -999, -110, -88, -74,
  116697. -77, -82, -82, -85, -90, -94, -99, -104,
  116698. -999, -999, -999, -999, -999, -999, -999, -999,
  116699. -999, -999, -999, -999, -999, -999, -999, -999,
  116700. -999, -999, -999, -999, -999, -999, -999, -999,
  116701. -999, -999, -999, -999, -999, -999, -999, -999},
  116702. {-999, -999, -999, -999, -999, -999, -999, -999,
  116703. -999, -999, -999, -999, -999, -110, -88, -66,
  116704. -70, -81, -80, -81, -84, -88, -91, -93,
  116705. -999, -999, -999, -999, -999, -999, -999, -999,
  116706. -999, -999, -999, -999, -999, -999, -999, -999,
  116707. -999, -999, -999, -999, -999, -999, -999, -999,
  116708. -999, -999, -999, -999, -999, -999, -999, -999},
  116709. {-999, -999, -999, -999, -999, -999, -999, -999,
  116710. -999, -999, -999, -999, -999, -110, -88, -61,
  116711. -63, -70, -71, -74, -77, -80, -83, -85,
  116712. -999, -999, -999, -999, -999, -999, -999, -999,
  116713. -999, -999, -999, -999, -999, -999, -999, -999,
  116714. -999, -999, -999, -999, -999, -999, -999, -999,
  116715. -999, -999, -999, -999, -999, -999, -999, -999},
  116716. {-999, -999, -999, -999, -999, -999, -999, -999,
  116717. -999, -999, -999, -999, -999, -110, -86, -62,
  116718. -63, -62, -62, -58, -52, -50, -50, -52,
  116719. -54, -999, -999, -999, -999, -999, -999, -999,
  116720. -999, -999, -999, -999, -999, -999, -999, -999,
  116721. -999, -999, -999, -999, -999, -999, -999, -999,
  116722. -999, -999, -999, -999, -999, -999, -999, -999},
  116723. {-999, -999, -999, -999, -999, -999, -999, -999,
  116724. -999, -999, -999, -999, -118, -108, -84, -53,
  116725. -50, -50, -50, -55, -47, -45, -40, -40,
  116726. -40, -999, -999, -999, -999, -999, -999, -999,
  116727. -999, -999, -999, -999, -999, -999, -999, -999,
  116728. -999, -999, -999, -999, -999, -999, -999, -999,
  116729. -999, -999, -999, -999, -999, -999, -999, -999},
  116730. {-999, -999, -999, -999, -999, -999, -999, -999,
  116731. -999, -999, -999, -999, -118, -100, -73, -43,
  116732. -37, -42, -43, -53, -38, -37, -35, -35,
  116733. -38, -999, -999, -999, -999, -999, -999, -999,
  116734. -999, -999, -999, -999, -999, -999, -999, -999,
  116735. -999, -999, -999, -999, -999, -999, -999, -999,
  116736. -999, -999, -999, -999, -999, -999, -999, -999}},
  116737. /* 16000 Hz */
  116738. {{-999, -999, -999, -999, -999, -999, -999, -999,
  116739. -999, -999, -999, -110, -100, -91, -84, -74,
  116740. -80, -80, -80, -80, -80, -999, -999, -999,
  116741. -999, -999, -999, -999, -999, -999, -999, -999,
  116742. -999, -999, -999, -999, -999, -999, -999, -999,
  116743. -999, -999, -999, -999, -999, -999, -999, -999,
  116744. -999, -999, -999, -999, -999, -999, -999, -999},
  116745. {-999, -999, -999, -999, -999, -999, -999, -999,
  116746. -999, -999, -999, -110, -100, -91, -84, -74,
  116747. -68, -68, -68, -68, -68, -999, -999, -999,
  116748. -999, -999, -999, -999, -999, -999, -999, -999,
  116749. -999, -999, -999, -999, -999, -999, -999, -999,
  116750. -999, -999, -999, -999, -999, -999, -999, -999,
  116751. -999, -999, -999, -999, -999, -999, -999, -999},
  116752. {-999, -999, -999, -999, -999, -999, -999, -999,
  116753. -999, -999, -999, -110, -100, -86, -78, -70,
  116754. -60, -45, -30, -21, -999, -999, -999, -999,
  116755. -999, -999, -999, -999, -999, -999, -999, -999,
  116756. -999, -999, -999, -999, -999, -999, -999, -999,
  116757. -999, -999, -999, -999, -999, -999, -999, -999,
  116758. -999, -999, -999, -999, -999, -999, -999, -999},
  116759. {-999, -999, -999, -999, -999, -999, -999, -999,
  116760. -999, -999, -999, -110, -100, -87, -78, -67,
  116761. -48, -38, -29, -21, -999, -999, -999, -999,
  116762. -999, -999, -999, -999, -999, -999, -999, -999,
  116763. -999, -999, -999, -999, -999, -999, -999, -999,
  116764. -999, -999, -999, -999, -999, -999, -999, -999,
  116765. -999, -999, -999, -999, -999, -999, -999, -999},
  116766. {-999, -999, -999, -999, -999, -999, -999, -999,
  116767. -999, -999, -999, -110, -100, -86, -69, -56,
  116768. -45, -35, -33, -29, -999, -999, -999, -999,
  116769. -999, -999, -999, -999, -999, -999, -999, -999,
  116770. -999, -999, -999, -999, -999, -999, -999, -999,
  116771. -999, -999, -999, -999, -999, -999, -999, -999,
  116772. -999, -999, -999, -999, -999, -999, -999, -999},
  116773. {-999, -999, -999, -999, -999, -999, -999, -999,
  116774. -999, -999, -999, -110, -100, -83, -71, -48,
  116775. -27, -38, -37, -34, -999, -999, -999, -999,
  116776. -999, -999, -999, -999, -999, -999, -999, -999,
  116777. -999, -999, -999, -999, -999, -999, -999, -999,
  116778. -999, -999, -999, -999, -999, -999, -999, -999,
  116779. -999, -999, -999, -999, -999, -999, -999, -999}}
  116780. };
  116781. #endif
  116782. /********* End of inlined file: masking.h *********/
  116783. #define NEGINF -9999.f
  116784. static double stereo_threshholds[]={0.0, .5, 1.0, 1.5, 2.5, 4.5, 8.5, 16.5, 9e10};
  116785. static double stereo_threshholds_limited[]={0.0, .5, 1.0, 1.5, 2.0, 2.5, 4.5, 8.5, 9e10};
  116786. vorbis_look_psy_global *_vp_global_look(vorbis_info *vi){
  116787. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  116788. vorbis_info_psy_global *gi=&ci->psy_g_param;
  116789. vorbis_look_psy_global *look=(vorbis_look_psy_global*)_ogg_calloc(1,sizeof(*look));
  116790. look->channels=vi->channels;
  116791. look->ampmax=-9999.;
  116792. look->gi=gi;
  116793. return(look);
  116794. }
  116795. void _vp_global_free(vorbis_look_psy_global *look){
  116796. if(look){
  116797. memset(look,0,sizeof(*look));
  116798. _ogg_free(look);
  116799. }
  116800. }
  116801. void _vi_gpsy_free(vorbis_info_psy_global *i){
  116802. if(i){
  116803. memset(i,0,sizeof(*i));
  116804. _ogg_free(i);
  116805. }
  116806. }
  116807. void _vi_psy_free(vorbis_info_psy *i){
  116808. if(i){
  116809. memset(i,0,sizeof(*i));
  116810. _ogg_free(i);
  116811. }
  116812. }
  116813. static void min_curve(float *c,
  116814. float *c2){
  116815. int i;
  116816. for(i=0;i<EHMER_MAX;i++)if(c2[i]<c[i])c[i]=c2[i];
  116817. }
  116818. static void max_curve(float *c,
  116819. float *c2){
  116820. int i;
  116821. for(i=0;i<EHMER_MAX;i++)if(c2[i]>c[i])c[i]=c2[i];
  116822. }
  116823. static void attenuate_curve(float *c,float att){
  116824. int i;
  116825. for(i=0;i<EHMER_MAX;i++)
  116826. c[i]+=att;
  116827. }
  116828. static float ***setup_tone_curves(float curveatt_dB[P_BANDS],float binHz,int n,
  116829. float center_boost, float center_decay_rate){
  116830. int i,j,k,m;
  116831. float ath[EHMER_MAX];
  116832. float workc[P_BANDS][P_LEVELS][EHMER_MAX];
  116833. float athc[P_LEVELS][EHMER_MAX];
  116834. float *brute_buffer=(float*) alloca(n*sizeof(*brute_buffer));
  116835. float ***ret=(float***) _ogg_malloc(sizeof(*ret)*P_BANDS);
  116836. memset(workc,0,sizeof(workc));
  116837. for(i=0;i<P_BANDS;i++){
  116838. /* we add back in the ATH to avoid low level curves falling off to
  116839. -infinity and unnecessarily cutting off high level curves in the
  116840. curve limiting (last step). */
  116841. /* A half-band's settings must be valid over the whole band, and
  116842. it's better to mask too little than too much */
  116843. int ath_offset=i*4;
  116844. for(j=0;j<EHMER_MAX;j++){
  116845. float min=999.;
  116846. for(k=0;k<4;k++)
  116847. if(j+k+ath_offset<MAX_ATH){
  116848. if(min>ATH[j+k+ath_offset])min=ATH[j+k+ath_offset];
  116849. }else{
  116850. if(min>ATH[MAX_ATH-1])min=ATH[MAX_ATH-1];
  116851. }
  116852. ath[j]=min;
  116853. }
  116854. /* copy curves into working space, replicate the 50dB curve to 30
  116855. and 40, replicate the 100dB curve to 110 */
  116856. for(j=0;j<6;j++)
  116857. memcpy(workc[i][j+2],tonemasks[i][j],EHMER_MAX*sizeof(*tonemasks[i][j]));
  116858. memcpy(workc[i][0],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116859. memcpy(workc[i][1],tonemasks[i][0],EHMER_MAX*sizeof(*tonemasks[i][0]));
  116860. /* apply centered curve boost/decay */
  116861. for(j=0;j<P_LEVELS;j++){
  116862. for(k=0;k<EHMER_MAX;k++){
  116863. float adj=center_boost+abs(EHMER_OFFSET-k)*center_decay_rate;
  116864. if(adj<0. && center_boost>0)adj=0.;
  116865. if(adj>0. && center_boost<0)adj=0.;
  116866. workc[i][j][k]+=adj;
  116867. }
  116868. }
  116869. /* normalize curves so the driving amplitude is 0dB */
  116870. /* make temp curves with the ATH overlayed */
  116871. for(j=0;j<P_LEVELS;j++){
  116872. attenuate_curve(workc[i][j],curveatt_dB[i]+100.-(j<2?2:j)*10.-P_LEVEL_0);
  116873. memcpy(athc[j],ath,EHMER_MAX*sizeof(**athc));
  116874. attenuate_curve(athc[j],+100.-j*10.f-P_LEVEL_0);
  116875. max_curve(athc[j],workc[i][j]);
  116876. }
  116877. /* Now limit the louder curves.
  116878. the idea is this: We don't know what the playback attenuation
  116879. will be; 0dB SL moves every time the user twiddles the volume
  116880. knob. So that means we have to use a single 'most pessimal' curve
  116881. for all masking amplitudes, right? Wrong. The *loudest* sound
  116882. can be in (we assume) a range of ...+100dB] SL. However, sounds
  116883. 20dB down will be in a range ...+80], 40dB down is from ...+60],
  116884. etc... */
  116885. for(j=1;j<P_LEVELS;j++){
  116886. min_curve(athc[j],athc[j-1]);
  116887. min_curve(workc[i][j],athc[j]);
  116888. }
  116889. }
  116890. for(i=0;i<P_BANDS;i++){
  116891. int hi_curve,lo_curve,bin;
  116892. ret[i]=(float**)_ogg_malloc(sizeof(**ret)*P_LEVELS);
  116893. /* low frequency curves are measured with greater resolution than
  116894. the MDCT/FFT will actually give us; we want the curve applied
  116895. to the tone data to be pessimistic and thus apply the minimum
  116896. masking possible for a given bin. That means that a single bin
  116897. could span more than one octave and that the curve will be a
  116898. composite of multiple octaves. It also may mean that a single
  116899. bin may span > an eighth of an octave and that the eighth
  116900. octave values may also be composited. */
  116901. /* which octave curves will we be compositing? */
  116902. bin=floor(fromOC(i*.5)/binHz);
  116903. lo_curve= ceil(toOC(bin*binHz+1)*2);
  116904. hi_curve= floor(toOC((bin+1)*binHz)*2);
  116905. if(lo_curve>i)lo_curve=i;
  116906. if(lo_curve<0)lo_curve=0;
  116907. if(hi_curve>=P_BANDS)hi_curve=P_BANDS-1;
  116908. for(m=0;m<P_LEVELS;m++){
  116909. ret[i][m]=(float*)_ogg_malloc(sizeof(***ret)*(EHMER_MAX+2));
  116910. for(j=0;j<n;j++)brute_buffer[j]=999.;
  116911. /* render the curve into bins, then pull values back into curve.
  116912. The point is that any inherent subsampling aliasing results in
  116913. a safe minimum */
  116914. for(k=lo_curve;k<=hi_curve;k++){
  116915. int l=0;
  116916. for(j=0;j<EHMER_MAX;j++){
  116917. int lo_bin= fromOC(j*.125+k*.5-2.0625)/binHz;
  116918. int hi_bin= fromOC(j*.125+k*.5-1.9375)/binHz+1;
  116919. if(lo_bin<0)lo_bin=0;
  116920. if(lo_bin>n)lo_bin=n;
  116921. if(lo_bin<l)l=lo_bin;
  116922. if(hi_bin<0)hi_bin=0;
  116923. if(hi_bin>n)hi_bin=n;
  116924. for(;l<hi_bin && l<n;l++)
  116925. if(brute_buffer[l]>workc[k][m][j])
  116926. brute_buffer[l]=workc[k][m][j];
  116927. }
  116928. for(;l<n;l++)
  116929. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116930. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116931. }
  116932. /* be equally paranoid about being valid up to next half ocatve */
  116933. if(i+1<P_BANDS){
  116934. int l=0;
  116935. k=i+1;
  116936. for(j=0;j<EHMER_MAX;j++){
  116937. int lo_bin= fromOC(j*.125+i*.5-2.0625)/binHz;
  116938. int hi_bin= fromOC(j*.125+i*.5-1.9375)/binHz+1;
  116939. if(lo_bin<0)lo_bin=0;
  116940. if(lo_bin>n)lo_bin=n;
  116941. if(lo_bin<l)l=lo_bin;
  116942. if(hi_bin<0)hi_bin=0;
  116943. if(hi_bin>n)hi_bin=n;
  116944. for(;l<hi_bin && l<n;l++)
  116945. if(brute_buffer[l]>workc[k][m][j])
  116946. brute_buffer[l]=workc[k][m][j];
  116947. }
  116948. for(;l<n;l++)
  116949. if(brute_buffer[l]>workc[k][m][EHMER_MAX-1])
  116950. brute_buffer[l]=workc[k][m][EHMER_MAX-1];
  116951. }
  116952. for(j=0;j<EHMER_MAX;j++){
  116953. int bin=fromOC(j*.125+i*.5-2.)/binHz;
  116954. if(bin<0){
  116955. ret[i][m][j+2]=-999.;
  116956. }else{
  116957. if(bin>=n){
  116958. ret[i][m][j+2]=-999.;
  116959. }else{
  116960. ret[i][m][j+2]=brute_buffer[bin];
  116961. }
  116962. }
  116963. }
  116964. /* add fenceposts */
  116965. for(j=0;j<EHMER_OFFSET;j++)
  116966. if(ret[i][m][j+2]>-200.f)break;
  116967. ret[i][m][0]=j;
  116968. for(j=EHMER_MAX-1;j>EHMER_OFFSET+1;j--)
  116969. if(ret[i][m][j+2]>-200.f)
  116970. break;
  116971. ret[i][m][1]=j;
  116972. }
  116973. }
  116974. return(ret);
  116975. }
  116976. void _vp_psy_init(vorbis_look_psy *p,vorbis_info_psy *vi,
  116977. vorbis_info_psy_global *gi,int n,long rate){
  116978. long i,j,lo=-99,hi=1;
  116979. long maxoc;
  116980. memset(p,0,sizeof(*p));
  116981. p->eighth_octave_lines=gi->eighth_octave_lines;
  116982. p->shiftoc=rint(log(gi->eighth_octave_lines*8.f)/log(2.f))-1;
  116983. p->firstoc=toOC(.25f*rate*.5/n)*(1<<(p->shiftoc+1))-gi->eighth_octave_lines;
  116984. maxoc=toOC((n+.25f)*rate*.5/n)*(1<<(p->shiftoc+1))+.5f;
  116985. p->total_octave_lines=maxoc-p->firstoc+1;
  116986. p->ath=(float*)_ogg_malloc(n*sizeof(*p->ath));
  116987. p->octave=(long*)_ogg_malloc(n*sizeof(*p->octave));
  116988. p->bark=(long*)_ogg_malloc(n*sizeof(*p->bark));
  116989. p->vi=vi;
  116990. p->n=n;
  116991. p->rate=rate;
  116992. /* AoTuV HF weighting */
  116993. p->m_val = 1.;
  116994. if(rate < 26000) p->m_val = 0;
  116995. else if(rate < 38000) p->m_val = .94; /* 32kHz */
  116996. else if(rate > 46000) p->m_val = 1.275; /* 48kHz */
  116997. /* set up the lookups for a given blocksize and sample rate */
  116998. for(i=0,j=0;i<MAX_ATH-1;i++){
  116999. int endpos=rint(fromOC((i+1)*.125-2.)*2*n/rate);
  117000. float base=ATH[i];
  117001. if(j<endpos){
  117002. float delta=(ATH[i+1]-base)/(endpos-j);
  117003. for(;j<endpos && j<n;j++){
  117004. p->ath[j]=base+100.;
  117005. base+=delta;
  117006. }
  117007. }
  117008. }
  117009. for(i=0;i<n;i++){
  117010. float bark=toBARK(rate/(2*n)*i);
  117011. for(;lo+vi->noisewindowlomin<i &&
  117012. toBARK(rate/(2*n)*lo)<(bark-vi->noisewindowlo);lo++);
  117013. for(;hi<=n && (hi<i+vi->noisewindowhimin ||
  117014. toBARK(rate/(2*n)*hi)<(bark+vi->noisewindowhi));hi++);
  117015. p->bark[i]=((lo-1)<<16)+(hi-1);
  117016. }
  117017. for(i=0;i<n;i++)
  117018. p->octave[i]=toOC((i+.25f)*.5*rate/n)*(1<<(p->shiftoc+1))+.5f;
  117019. p->tonecurves=setup_tone_curves(vi->toneatt,rate*.5/n,n,
  117020. vi->tone_centerboost,vi->tone_decay);
  117021. /* set up rolling noise median */
  117022. p->noiseoffset=(float**)_ogg_malloc(P_NOISECURVES*sizeof(*p->noiseoffset));
  117023. for(i=0;i<P_NOISECURVES;i++)
  117024. p->noiseoffset[i]=(float*)_ogg_malloc(n*sizeof(**p->noiseoffset));
  117025. for(i=0;i<n;i++){
  117026. float halfoc=toOC((i+.5)*rate/(2.*n))*2.;
  117027. int inthalfoc;
  117028. float del;
  117029. if(halfoc<0)halfoc=0;
  117030. if(halfoc>=P_BANDS-1)halfoc=P_BANDS-1;
  117031. inthalfoc=(int)halfoc;
  117032. del=halfoc-inthalfoc;
  117033. for(j=0;j<P_NOISECURVES;j++)
  117034. p->noiseoffset[j][i]=
  117035. p->vi->noiseoff[j][inthalfoc]*(1.-del) +
  117036. p->vi->noiseoff[j][inthalfoc+1]*del;
  117037. }
  117038. #if 0
  117039. {
  117040. static int ls=0;
  117041. _analysis_output_always("noiseoff0",ls,p->noiseoffset[0],n,1,0,0);
  117042. _analysis_output_always("noiseoff1",ls,p->noiseoffset[1],n,1,0,0);
  117043. _analysis_output_always("noiseoff2",ls++,p->noiseoffset[2],n,1,0,0);
  117044. }
  117045. #endif
  117046. }
  117047. void _vp_psy_clear(vorbis_look_psy *p){
  117048. int i,j;
  117049. if(p){
  117050. if(p->ath)_ogg_free(p->ath);
  117051. if(p->octave)_ogg_free(p->octave);
  117052. if(p->bark)_ogg_free(p->bark);
  117053. if(p->tonecurves){
  117054. for(i=0;i<P_BANDS;i++){
  117055. for(j=0;j<P_LEVELS;j++){
  117056. _ogg_free(p->tonecurves[i][j]);
  117057. }
  117058. _ogg_free(p->tonecurves[i]);
  117059. }
  117060. _ogg_free(p->tonecurves);
  117061. }
  117062. if(p->noiseoffset){
  117063. for(i=0;i<P_NOISECURVES;i++){
  117064. _ogg_free(p->noiseoffset[i]);
  117065. }
  117066. _ogg_free(p->noiseoffset);
  117067. }
  117068. memset(p,0,sizeof(*p));
  117069. }
  117070. }
  117071. /* octave/(8*eighth_octave_lines) x scale and dB y scale */
  117072. static void seed_curve(float *seed,
  117073. const float **curves,
  117074. float amp,
  117075. int oc, int n,
  117076. int linesper,float dBoffset){
  117077. int i,post1;
  117078. int seedptr;
  117079. const float *posts,*curve;
  117080. int choice=(int)((amp+dBoffset-P_LEVEL_0)*.1f);
  117081. choice=max(choice,0);
  117082. choice=min(choice,P_LEVELS-1);
  117083. posts=curves[choice];
  117084. curve=posts+2;
  117085. post1=(int)posts[1];
  117086. seedptr=oc+(posts[0]-EHMER_OFFSET)*linesper-(linesper>>1);
  117087. for(i=posts[0];i<post1;i++){
  117088. if(seedptr>0){
  117089. float lin=amp+curve[i];
  117090. if(seed[seedptr]<lin)seed[seedptr]=lin;
  117091. }
  117092. seedptr+=linesper;
  117093. if(seedptr>=n)break;
  117094. }
  117095. }
  117096. static void seed_loop(vorbis_look_psy *p,
  117097. const float ***curves,
  117098. const float *f,
  117099. const float *flr,
  117100. float *seed,
  117101. float specmax){
  117102. vorbis_info_psy *vi=p->vi;
  117103. long n=p->n,i;
  117104. float dBoffset=vi->max_curve_dB-specmax;
  117105. /* prime the working vector with peak values */
  117106. for(i=0;i<n;i++){
  117107. float max=f[i];
  117108. long oc=p->octave[i];
  117109. while(i+1<n && p->octave[i+1]==oc){
  117110. i++;
  117111. if(f[i]>max)max=f[i];
  117112. }
  117113. if(max+6.f>flr[i]){
  117114. oc=oc>>p->shiftoc;
  117115. if(oc>=P_BANDS)oc=P_BANDS-1;
  117116. if(oc<0)oc=0;
  117117. seed_curve(seed,
  117118. curves[oc],
  117119. max,
  117120. p->octave[i]-p->firstoc,
  117121. p->total_octave_lines,
  117122. p->eighth_octave_lines,
  117123. dBoffset);
  117124. }
  117125. }
  117126. }
  117127. static void seed_chase(float *seeds, int linesper, long n){
  117128. long *posstack=(long*)alloca(n*sizeof(*posstack));
  117129. float *ampstack=(float*)alloca(n*sizeof(*ampstack));
  117130. long stack=0;
  117131. long pos=0;
  117132. long i;
  117133. for(i=0;i<n;i++){
  117134. if(stack<2){
  117135. posstack[stack]=i;
  117136. ampstack[stack++]=seeds[i];
  117137. }else{
  117138. while(1){
  117139. if(seeds[i]<ampstack[stack-1]){
  117140. posstack[stack]=i;
  117141. ampstack[stack++]=seeds[i];
  117142. break;
  117143. }else{
  117144. if(i<posstack[stack-1]+linesper){
  117145. if(stack>1 && ampstack[stack-1]<=ampstack[stack-2] &&
  117146. i<posstack[stack-2]+linesper){
  117147. /* we completely overlap, making stack-1 irrelevant. pop it */
  117148. stack--;
  117149. continue;
  117150. }
  117151. }
  117152. posstack[stack]=i;
  117153. ampstack[stack++]=seeds[i];
  117154. break;
  117155. }
  117156. }
  117157. }
  117158. }
  117159. /* the stack now contains only the positions that are relevant. Scan
  117160. 'em straight through */
  117161. for(i=0;i<stack;i++){
  117162. long endpos;
  117163. if(i<stack-1 && ampstack[i+1]>ampstack[i]){
  117164. endpos=posstack[i+1];
  117165. }else{
  117166. endpos=posstack[i]+linesper+1; /* +1 is important, else bin 0 is
  117167. discarded in short frames */
  117168. }
  117169. if(endpos>n)endpos=n;
  117170. for(;pos<endpos;pos++)
  117171. seeds[pos]=ampstack[i];
  117172. }
  117173. /* there. Linear time. I now remember this was on a problem set I
  117174. had in Grad Skool... I didn't solve it at the time ;-) */
  117175. }
  117176. /* bleaugh, this is more complicated than it needs to be */
  117177. #include<stdio.h>
  117178. static void max_seeds(vorbis_look_psy *p,
  117179. float *seed,
  117180. float *flr){
  117181. long n=p->total_octave_lines;
  117182. int linesper=p->eighth_octave_lines;
  117183. long linpos=0;
  117184. long pos;
  117185. seed_chase(seed,linesper,n); /* for masking */
  117186. pos=p->octave[0]-p->firstoc-(linesper>>1);
  117187. while(linpos+1<p->n){
  117188. float minV=seed[pos];
  117189. long end=((p->octave[linpos]+p->octave[linpos+1])>>1)-p->firstoc;
  117190. if(minV>p->vi->tone_abs_limit)minV=p->vi->tone_abs_limit;
  117191. while(pos+1<=end){
  117192. pos++;
  117193. if((seed[pos]>NEGINF && seed[pos]<minV) || minV==NEGINF)
  117194. minV=seed[pos];
  117195. }
  117196. end=pos+p->firstoc;
  117197. for(;linpos<p->n && p->octave[linpos]<=end;linpos++)
  117198. if(flr[linpos]<minV)flr[linpos]=minV;
  117199. }
  117200. {
  117201. float minV=seed[p->total_octave_lines-1];
  117202. for(;linpos<p->n;linpos++)
  117203. if(flr[linpos]<minV)flr[linpos]=minV;
  117204. }
  117205. }
  117206. static void bark_noise_hybridmp(int n,const long *b,
  117207. const float *f,
  117208. float *noise,
  117209. const float offset,
  117210. const int fixed){
  117211. float *N=(float*) alloca(n*sizeof(*N));
  117212. float *X=(float*) alloca(n*sizeof(*N));
  117213. float *XX=(float*) alloca(n*sizeof(*N));
  117214. float *Y=(float*) alloca(n*sizeof(*N));
  117215. float *XY=(float*) alloca(n*sizeof(*N));
  117216. float tN, tX, tXX, tY, tXY;
  117217. int i;
  117218. int lo, hi;
  117219. float R, A, B, D;
  117220. float w, x, y;
  117221. tN = tX = tXX = tY = tXY = 0.f;
  117222. y = f[0] + offset;
  117223. if (y < 1.f) y = 1.f;
  117224. w = y * y * .5;
  117225. tN += w;
  117226. tX += w;
  117227. tY += w * y;
  117228. N[0] = tN;
  117229. X[0] = tX;
  117230. XX[0] = tXX;
  117231. Y[0] = tY;
  117232. XY[0] = tXY;
  117233. for (i = 1, x = 1.f; i < n; i++, x += 1.f) {
  117234. y = f[i] + offset;
  117235. if (y < 1.f) y = 1.f;
  117236. w = y * y;
  117237. tN += w;
  117238. tX += w * x;
  117239. tXX += w * x * x;
  117240. tY += w * y;
  117241. tXY += w * x * y;
  117242. N[i] = tN;
  117243. X[i] = tX;
  117244. XX[i] = tXX;
  117245. Y[i] = tY;
  117246. XY[i] = tXY;
  117247. }
  117248. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117249. lo = b[i] >> 16;
  117250. if( lo>=0 ) break;
  117251. hi = b[i] & 0xffff;
  117252. tN = N[hi] + N[-lo];
  117253. tX = X[hi] - X[-lo];
  117254. tXX = XX[hi] + XX[-lo];
  117255. tY = Y[hi] + Y[-lo];
  117256. tXY = XY[hi] - XY[-lo];
  117257. A = tY * tXX - tX * tXY;
  117258. B = tN * tXY - tX * tY;
  117259. D = tN * tXX - tX * tX;
  117260. R = (A + x * B) / D;
  117261. if (R < 0.f)
  117262. R = 0.f;
  117263. noise[i] = R - offset;
  117264. }
  117265. for ( ;; i++, x += 1.f) {
  117266. lo = b[i] >> 16;
  117267. hi = b[i] & 0xffff;
  117268. if(hi>=n)break;
  117269. tN = N[hi] - N[lo];
  117270. tX = X[hi] - X[lo];
  117271. tXX = XX[hi] - XX[lo];
  117272. tY = Y[hi] - Y[lo];
  117273. tXY = XY[hi] - XY[lo];
  117274. A = tY * tXX - tX * tXY;
  117275. B = tN * tXY - tX * tY;
  117276. D = tN * tXX - tX * tX;
  117277. R = (A + x * B) / D;
  117278. if (R < 0.f) R = 0.f;
  117279. noise[i] = R - offset;
  117280. }
  117281. for ( ; i < n; i++, x += 1.f) {
  117282. R = (A + x * B) / D;
  117283. if (R < 0.f) R = 0.f;
  117284. noise[i] = R - offset;
  117285. }
  117286. if (fixed <= 0) return;
  117287. for (i = 0, x = 0.f;; i++, x += 1.f) {
  117288. hi = i + fixed / 2;
  117289. lo = hi - fixed;
  117290. if(lo>=0)break;
  117291. tN = N[hi] + N[-lo];
  117292. tX = X[hi] - X[-lo];
  117293. tXX = XX[hi] + XX[-lo];
  117294. tY = Y[hi] + Y[-lo];
  117295. tXY = XY[hi] - XY[-lo];
  117296. A = tY * tXX - tX * tXY;
  117297. B = tN * tXY - tX * tY;
  117298. D = tN * tXX - tX * tX;
  117299. R = (A + x * B) / D;
  117300. if (R - offset < noise[i]) noise[i] = R - offset;
  117301. }
  117302. for ( ;; i++, x += 1.f) {
  117303. hi = i + fixed / 2;
  117304. lo = hi - fixed;
  117305. if(hi>=n)break;
  117306. tN = N[hi] - N[lo];
  117307. tX = X[hi] - X[lo];
  117308. tXX = XX[hi] - XX[lo];
  117309. tY = Y[hi] - Y[lo];
  117310. tXY = XY[hi] - XY[lo];
  117311. A = tY * tXX - tX * tXY;
  117312. B = tN * tXY - tX * tY;
  117313. D = tN * tXX - tX * tX;
  117314. R = (A + x * B) / D;
  117315. if (R - offset < noise[i]) noise[i] = R - offset;
  117316. }
  117317. for ( ; i < n; i++, x += 1.f) {
  117318. R = (A + x * B) / D;
  117319. if (R - offset < noise[i]) noise[i] = R - offset;
  117320. }
  117321. }
  117322. static float FLOOR1_fromdB_INV_LOOKUP[256]={
  117323. 0.F, 8.81683e+06F, 8.27882e+06F, 7.77365e+06F,
  117324. 7.29930e+06F, 6.85389e+06F, 6.43567e+06F, 6.04296e+06F,
  117325. 5.67422e+06F, 5.32798e+06F, 5.00286e+06F, 4.69759e+06F,
  117326. 4.41094e+06F, 4.14178e+06F, 3.88905e+06F, 3.65174e+06F,
  117327. 3.42891e+06F, 3.21968e+06F, 3.02321e+06F, 2.83873e+06F,
  117328. 2.66551e+06F, 2.50286e+06F, 2.35014e+06F, 2.20673e+06F,
  117329. 2.07208e+06F, 1.94564e+06F, 1.82692e+06F, 1.71544e+06F,
  117330. 1.61076e+06F, 1.51247e+06F, 1.42018e+06F, 1.33352e+06F,
  117331. 1.25215e+06F, 1.17574e+06F, 1.10400e+06F, 1.03663e+06F,
  117332. 973377.F, 913981.F, 858210.F, 805842.F,
  117333. 756669.F, 710497.F, 667142.F, 626433.F,
  117334. 588208.F, 552316.F, 518613.F, 486967.F,
  117335. 457252.F, 429351.F, 403152.F, 378551.F,
  117336. 355452.F, 333762.F, 313396.F, 294273.F,
  117337. 276316.F, 259455.F, 243623.F, 228757.F,
  117338. 214798.F, 201691.F, 189384.F, 177828.F,
  117339. 166977.F, 156788.F, 147221.F, 138237.F,
  117340. 129802.F, 121881.F, 114444.F, 107461.F,
  117341. 100903.F, 94746.3F, 88964.9F, 83536.2F,
  117342. 78438.8F, 73652.5F, 69158.2F, 64938.1F,
  117343. 60975.6F, 57254.9F, 53761.2F, 50480.6F,
  117344. 47400.3F, 44507.9F, 41792.0F, 39241.9F,
  117345. 36847.3F, 34598.9F, 32487.7F, 30505.3F,
  117346. 28643.8F, 26896.0F, 25254.8F, 23713.7F,
  117347. 22266.7F, 20908.0F, 19632.2F, 18434.2F,
  117348. 17309.4F, 16253.1F, 15261.4F, 14330.1F,
  117349. 13455.7F, 12634.6F, 11863.7F, 11139.7F,
  117350. 10460.0F, 9821.72F, 9222.39F, 8659.64F,
  117351. 8131.23F, 7635.06F, 7169.17F, 6731.70F,
  117352. 6320.93F, 5935.23F, 5573.06F, 5232.99F,
  117353. 4913.67F, 4613.84F, 4332.30F, 4067.94F,
  117354. 3819.72F, 3586.64F, 3367.78F, 3162.28F,
  117355. 2969.31F, 2788.13F, 2617.99F, 2458.24F,
  117356. 2308.24F, 2167.39F, 2035.14F, 1910.95F,
  117357. 1794.35F, 1684.85F, 1582.04F, 1485.51F,
  117358. 1394.86F, 1309.75F, 1229.83F, 1154.78F,
  117359. 1084.32F, 1018.15F, 956.024F, 897.687F,
  117360. 842.910F, 791.475F, 743.179F, 697.830F,
  117361. 655.249F, 615.265F, 577.722F, 542.469F,
  117362. 509.367F, 478.286F, 449.101F, 421.696F,
  117363. 395.964F, 371.803F, 349.115F, 327.812F,
  117364. 307.809F, 289.026F, 271.390F, 254.830F,
  117365. 239.280F, 224.679F, 210.969F, 198.096F,
  117366. 186.008F, 174.658F, 164.000F, 153.993F,
  117367. 144.596F, 135.773F, 127.488F, 119.708F,
  117368. 112.404F, 105.545F, 99.1046F, 93.0572F,
  117369. 87.3788F, 82.0469F, 77.0404F, 72.3394F,
  117370. 67.9252F, 63.7804F, 59.8885F, 56.2341F,
  117371. 52.8027F, 49.5807F, 46.5553F, 43.7144F,
  117372. 41.0470F, 38.5423F, 36.1904F, 33.9821F,
  117373. 31.9085F, 29.9614F, 28.1332F, 26.4165F,
  117374. 24.8045F, 23.2910F, 21.8697F, 20.5352F,
  117375. 19.2822F, 18.1056F, 17.0008F, 15.9634F,
  117376. 14.9893F, 14.0746F, 13.2158F, 12.4094F,
  117377. 11.6522F, 10.9411F, 10.2735F, 9.64662F,
  117378. 9.05798F, 8.50526F, 7.98626F, 7.49894F,
  117379. 7.04135F, 6.61169F, 6.20824F, 5.82941F,
  117380. 5.47370F, 5.13970F, 4.82607F, 4.53158F,
  117381. 4.25507F, 3.99542F, 3.75162F, 3.52269F,
  117382. 3.30774F, 3.10590F, 2.91638F, 2.73842F,
  117383. 2.57132F, 2.41442F, 2.26709F, 2.12875F,
  117384. 1.99885F, 1.87688F, 1.76236F, 1.65482F,
  117385. 1.55384F, 1.45902F, 1.36999F, 1.28640F,
  117386. 1.20790F, 1.13419F, 1.06499F, 1.F
  117387. };
  117388. void _vp_remove_floor(vorbis_look_psy *p,
  117389. float *mdct,
  117390. int *codedflr,
  117391. float *residue,
  117392. int sliding_lowpass){
  117393. int i,n=p->n;
  117394. if(sliding_lowpass>n)sliding_lowpass=n;
  117395. for(i=0;i<sliding_lowpass;i++){
  117396. residue[i]=
  117397. mdct[i]*FLOOR1_fromdB_INV_LOOKUP[codedflr[i]];
  117398. }
  117399. for(;i<n;i++)
  117400. residue[i]=0.;
  117401. }
  117402. void _vp_noisemask(vorbis_look_psy *p,
  117403. float *logmdct,
  117404. float *logmask){
  117405. int i,n=p->n;
  117406. float *work=(float*) alloca(n*sizeof(*work));
  117407. bark_noise_hybridmp(n,p->bark,logmdct,logmask,
  117408. 140.,-1);
  117409. for(i=0;i<n;i++)work[i]=logmdct[i]-logmask[i];
  117410. bark_noise_hybridmp(n,p->bark,work,logmask,0.,
  117411. p->vi->noisewindowfixed);
  117412. for(i=0;i<n;i++)work[i]=logmdct[i]-work[i];
  117413. #if 0
  117414. {
  117415. static int seq=0;
  117416. float work2[n];
  117417. for(i=0;i<n;i++){
  117418. work2[i]=logmask[i]+work[i];
  117419. }
  117420. if(seq&1)
  117421. _analysis_output("median2R",seq/2,work,n,1,0,0);
  117422. else
  117423. _analysis_output("median2L",seq/2,work,n,1,0,0);
  117424. if(seq&1)
  117425. _analysis_output("envelope2R",seq/2,work2,n,1,0,0);
  117426. else
  117427. _analysis_output("envelope2L",seq/2,work2,n,1,0,0);
  117428. seq++;
  117429. }
  117430. #endif
  117431. for(i=0;i<n;i++){
  117432. int dB=logmask[i]+.5;
  117433. if(dB>=NOISE_COMPAND_LEVELS)dB=NOISE_COMPAND_LEVELS-1;
  117434. if(dB<0)dB=0;
  117435. logmask[i]= work[i]+p->vi->noisecompand[dB];
  117436. }
  117437. }
  117438. void _vp_tonemask(vorbis_look_psy *p,
  117439. float *logfft,
  117440. float *logmask,
  117441. float global_specmax,
  117442. float local_specmax){
  117443. int i,n=p->n;
  117444. float *seed=(float*) alloca(sizeof(*seed)*p->total_octave_lines);
  117445. float att=local_specmax+p->vi->ath_adjatt;
  117446. for(i=0;i<p->total_octave_lines;i++)seed[i]=NEGINF;
  117447. /* set the ATH (floating below localmax, not global max by a
  117448. specified att) */
  117449. if(att<p->vi->ath_maxatt)att=p->vi->ath_maxatt;
  117450. for(i=0;i<n;i++)
  117451. logmask[i]=p->ath[i]+att;
  117452. /* tone masking */
  117453. seed_loop(p,(const float ***)p->tonecurves,logfft,logmask,seed,global_specmax);
  117454. max_seeds(p,seed,logmask);
  117455. }
  117456. void _vp_offset_and_mix(vorbis_look_psy *p,
  117457. float *noise,
  117458. float *tone,
  117459. int offset_select,
  117460. float *logmask,
  117461. float *mdct,
  117462. float *logmdct){
  117463. int i,n=p->n;
  117464. float de, coeffi, cx;/* AoTuV */
  117465. float toneatt=p->vi->tone_masteratt[offset_select];
  117466. cx = p->m_val;
  117467. for(i=0;i<n;i++){
  117468. float val= noise[i]+p->noiseoffset[offset_select][i];
  117469. if(val>p->vi->noisemaxsupp)val=p->vi->noisemaxsupp;
  117470. logmask[i]=max(val,tone[i]+toneatt);
  117471. /* AoTuV */
  117472. /** @ M1 **
  117473. The following codes improve a noise problem.
  117474. A fundamental idea uses the value of masking and carries out
  117475. the relative compensation of the MDCT.
  117476. However, this code is not perfect and all noise problems cannot be solved.
  117477. by Aoyumi @ 2004/04/18
  117478. */
  117479. if(offset_select == 1) {
  117480. coeffi = -17.2; /* coeffi is a -17.2dB threshold */
  117481. val = val - logmdct[i]; /* val == mdct line value relative to floor in dB */
  117482. if(val > coeffi){
  117483. /* mdct value is > -17.2 dB below floor */
  117484. de = 1.0-((val-coeffi)*0.005*cx);
  117485. /* pro-rated attenuation:
  117486. -0.00 dB boost if mdct value is -17.2dB (relative to floor)
  117487. -0.77 dB boost if mdct value is 0dB (relative to floor)
  117488. -1.64 dB boost if mdct value is +17.2dB (relative to floor)
  117489. etc... */
  117490. if(de < 0) de = 0.0001;
  117491. }else
  117492. /* mdct value is <= -17.2 dB below floor */
  117493. de = 1.0-((val-coeffi)*0.0003*cx);
  117494. /* pro-rated attenuation:
  117495. +0.00 dB atten if mdct value is -17.2dB (relative to floor)
  117496. +0.45 dB atten if mdct value is -34.4dB (relative to floor)
  117497. etc... */
  117498. mdct[i] *= de;
  117499. }
  117500. }
  117501. }
  117502. float _vp_ampmax_decay(float amp,vorbis_dsp_state *vd){
  117503. vorbis_info *vi=vd->vi;
  117504. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  117505. vorbis_info_psy_global *gi=&ci->psy_g_param;
  117506. int n=ci->blocksizes[vd->W]/2;
  117507. float secs=(float)n/vi->rate;
  117508. amp+=secs*gi->ampmax_att_per_sec;
  117509. if(amp<-9999)amp=-9999;
  117510. return(amp);
  117511. }
  117512. static void couple_lossless(float A, float B,
  117513. float *qA, float *qB){
  117514. int test1=fabs(*qA)>fabs(*qB);
  117515. test1-= fabs(*qA)<fabs(*qB);
  117516. if(!test1)test1=((fabs(A)>fabs(B))<<1)-1;
  117517. if(test1==1){
  117518. *qB=(*qA>0.f?*qA-*qB:*qB-*qA);
  117519. }else{
  117520. float temp=*qB;
  117521. *qB=(*qB>0.f?*qA-*qB:*qB-*qA);
  117522. *qA=temp;
  117523. }
  117524. if(*qB>fabs(*qA)*1.9999f){
  117525. *qB= -fabs(*qA)*2.f;
  117526. *qA= -*qA;
  117527. }
  117528. }
  117529. static float hypot_lookup[32]={
  117530. -0.009935, -0.011245, -0.012726, -0.014397,
  117531. -0.016282, -0.018407, -0.020800, -0.023494,
  117532. -0.026522, -0.029923, -0.033737, -0.038010,
  117533. -0.042787, -0.048121, -0.054064, -0.060671,
  117534. -0.068000, -0.076109, -0.085054, -0.094892,
  117535. -0.105675, -0.117451, -0.130260, -0.144134,
  117536. -0.159093, -0.175146, -0.192286, -0.210490,
  117537. -0.229718, -0.249913, -0.271001, -0.292893};
  117538. static void precomputed_couple_point(float premag,
  117539. int floorA,int floorB,
  117540. float *mag, float *ang){
  117541. int test=(floorA>floorB)-1;
  117542. int offset=31-abs(floorA-floorB);
  117543. float floormag=hypot_lookup[((offset<0)-1)&offset]+1.f;
  117544. floormag*=FLOOR1_fromdB_INV_LOOKUP[(floorB&test)|(floorA&(~test))];
  117545. *mag=premag*floormag;
  117546. *ang=0.f;
  117547. }
  117548. /* just like below, this is currently set up to only do
  117549. single-step-depth coupling. Otherwise, we'd have to do more
  117550. copying (which will be inevitable later) */
  117551. /* doing the real circular magnitude calculation is audibly superior
  117552. to (A+B)/sqrt(2) */
  117553. static float dipole_hypot(float a, float b){
  117554. if(a>0.){
  117555. if(b>0.)return sqrt(a*a+b*b);
  117556. if(a>-b)return sqrt(a*a-b*b);
  117557. return -sqrt(b*b-a*a);
  117558. }
  117559. if(b<0.)return -sqrt(a*a+b*b);
  117560. if(-a>b)return -sqrt(a*a-b*b);
  117561. return sqrt(b*b-a*a);
  117562. }
  117563. static float round_hypot(float a, float b){
  117564. if(a>0.){
  117565. if(b>0.)return sqrt(a*a+b*b);
  117566. if(a>-b)return sqrt(a*a+b*b);
  117567. return -sqrt(b*b+a*a);
  117568. }
  117569. if(b<0.)return -sqrt(a*a+b*b);
  117570. if(-a>b)return -sqrt(a*a+b*b);
  117571. return sqrt(b*b+a*a);
  117572. }
  117573. /* revert to round hypot for now */
  117574. float **_vp_quantize_couple_memo(vorbis_block *vb,
  117575. vorbis_info_psy_global *g,
  117576. vorbis_look_psy *p,
  117577. vorbis_info_mapping0 *vi,
  117578. float **mdct){
  117579. int i,j,n=p->n;
  117580. float **ret=(float**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117581. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117582. for(i=0;i<vi->coupling_steps;i++){
  117583. float *mdctM=mdct[vi->coupling_mag[i]];
  117584. float *mdctA=mdct[vi->coupling_ang[i]];
  117585. ret[i]=(float*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117586. for(j=0;j<limit;j++)
  117587. ret[i][j]=dipole_hypot(mdctM[j],mdctA[j]);
  117588. for(;j<n;j++)
  117589. ret[i][j]=round_hypot(mdctM[j],mdctA[j]);
  117590. }
  117591. return(ret);
  117592. }
  117593. /* this is for per-channel noise normalization */
  117594. static int apsort(const void *a, const void *b){
  117595. float f1=fabs(**(float**)a);
  117596. float f2=fabs(**(float**)b);
  117597. return (f1<f2)-(f1>f2);
  117598. }
  117599. int **_vp_quantize_couple_sort(vorbis_block *vb,
  117600. vorbis_look_psy *p,
  117601. vorbis_info_mapping0 *vi,
  117602. float **mags){
  117603. if(p->vi->normal_point_p){
  117604. int i,j,k,n=p->n;
  117605. int **ret=(int**) _vorbis_block_alloc(vb,vi->coupling_steps*sizeof(*ret));
  117606. int partition=p->vi->normal_partition;
  117607. float **work=(float**) alloca(sizeof(*work)*partition);
  117608. for(i=0;i<vi->coupling_steps;i++){
  117609. ret[i]=(int*) _vorbis_block_alloc(vb,n*sizeof(**ret));
  117610. for(j=0;j<n;j+=partition){
  117611. for(k=0;k<partition;k++)work[k]=mags[i]+k+j;
  117612. qsort(work,partition,sizeof(*work),apsort);
  117613. for(k=0;k<partition;k++)ret[i][k+j]=work[k]-mags[i];
  117614. }
  117615. }
  117616. return(ret);
  117617. }
  117618. return(NULL);
  117619. }
  117620. void _vp_noise_normalize_sort(vorbis_look_psy *p,
  117621. float *magnitudes,int *sortedindex){
  117622. int i,j,n=p->n;
  117623. vorbis_info_psy *vi=p->vi;
  117624. int partition=vi->normal_partition;
  117625. float **work=(float**) alloca(sizeof(*work)*partition);
  117626. int start=vi->normal_start;
  117627. for(j=start;j<n;j+=partition){
  117628. if(j+partition>n)partition=n-j;
  117629. for(i=0;i<partition;i++)work[i]=magnitudes+i+j;
  117630. qsort(work,partition,sizeof(*work),apsort);
  117631. for(i=0;i<partition;i++){
  117632. sortedindex[i+j-start]=work[i]-magnitudes;
  117633. }
  117634. }
  117635. }
  117636. void _vp_noise_normalize(vorbis_look_psy *p,
  117637. float *in,float *out,int *sortedindex){
  117638. int flag=0,i,j=0,n=p->n;
  117639. vorbis_info_psy *vi=p->vi;
  117640. int partition=vi->normal_partition;
  117641. int start=vi->normal_start;
  117642. if(start>n)start=n;
  117643. if(vi->normal_channel_p){
  117644. for(;j<start;j++)
  117645. out[j]=rint(in[j]);
  117646. for(;j+partition<=n;j+=partition){
  117647. float acc=0.;
  117648. int k;
  117649. for(i=j;i<j+partition;i++)
  117650. acc+=in[i]*in[i];
  117651. for(i=0;i<partition;i++){
  117652. k=sortedindex[i+j-start];
  117653. if(in[k]*in[k]>=.25f){
  117654. out[k]=rint(in[k]);
  117655. acc-=in[k]*in[k];
  117656. flag=1;
  117657. }else{
  117658. if(acc<vi->normal_thresh)break;
  117659. out[k]=unitnorm(in[k]);
  117660. acc-=1.;
  117661. }
  117662. }
  117663. for(;i<partition;i++){
  117664. k=sortedindex[i+j-start];
  117665. out[k]=0.;
  117666. }
  117667. }
  117668. }
  117669. for(;j<n;j++)
  117670. out[j]=rint(in[j]);
  117671. }
  117672. void _vp_couple(int blobno,
  117673. vorbis_info_psy_global *g,
  117674. vorbis_look_psy *p,
  117675. vorbis_info_mapping0 *vi,
  117676. float **res,
  117677. float **mag_memo,
  117678. int **mag_sort,
  117679. int **ifloor,
  117680. int *nonzero,
  117681. int sliding_lowpass){
  117682. int i,j,k,n=p->n;
  117683. /* perform any requested channel coupling */
  117684. /* point stereo can only be used in a first stage (in this encoder)
  117685. because of the dependency on floor lookups */
  117686. for(i=0;i<vi->coupling_steps;i++){
  117687. /* once we're doing multistage coupling in which a channel goes
  117688. through more than one coupling step, the floor vector
  117689. magnitudes will also have to be recalculated an propogated
  117690. along with PCM. Right now, we're not (that will wait until 5.1
  117691. most likely), so the code isn't here yet. The memory management
  117692. here is all assuming single depth couplings anyway. */
  117693. /* make sure coupling a zero and a nonzero channel results in two
  117694. nonzero channels. */
  117695. if(nonzero[vi->coupling_mag[i]] ||
  117696. nonzero[vi->coupling_ang[i]]){
  117697. float *rM=res[vi->coupling_mag[i]];
  117698. float *rA=res[vi->coupling_ang[i]];
  117699. float *qM=rM+n;
  117700. float *qA=rA+n;
  117701. int *floorM=ifloor[vi->coupling_mag[i]];
  117702. int *floorA=ifloor[vi->coupling_ang[i]];
  117703. float prepoint=stereo_threshholds[g->coupling_prepointamp[blobno]];
  117704. float postpoint=stereo_threshholds[g->coupling_postpointamp[blobno]];
  117705. int partition=(p->vi->normal_point_p?p->vi->normal_partition:p->n);
  117706. int limit=g->coupling_pointlimit[p->vi->blockflag][blobno];
  117707. int pointlimit=limit;
  117708. nonzero[vi->coupling_mag[i]]=1;
  117709. nonzero[vi->coupling_ang[i]]=1;
  117710. /* The threshold of a stereo is changed with the size of n */
  117711. if(n > 1000)
  117712. postpoint=stereo_threshholds_limited[g->coupling_postpointamp[blobno]];
  117713. for(j=0;j<p->n;j+=partition){
  117714. float acc=0.f;
  117715. for(k=0;k<partition;k++){
  117716. int l=k+j;
  117717. if(l<sliding_lowpass){
  117718. if((l>=limit && fabs(rM[l])<postpoint && fabs(rA[l])<postpoint) ||
  117719. (fabs(rM[l])<prepoint && fabs(rA[l])<prepoint)){
  117720. precomputed_couple_point(mag_memo[i][l],
  117721. floorM[l],floorA[l],
  117722. qM+l,qA+l);
  117723. if(rint(qM[l])==0.f)acc+=qM[l]*qM[l];
  117724. }else{
  117725. couple_lossless(rM[l],rA[l],qM+l,qA+l);
  117726. }
  117727. }else{
  117728. qM[l]=0.;
  117729. qA[l]=0.;
  117730. }
  117731. }
  117732. if(p->vi->normal_point_p){
  117733. for(k=0;k<partition && acc>=p->vi->normal_thresh;k++){
  117734. int l=mag_sort[i][j+k];
  117735. if(l<sliding_lowpass && l>=pointlimit && rint(qM[l])==0.f){
  117736. qM[l]=unitnorm(qM[l]);
  117737. acc-=1.f;
  117738. }
  117739. }
  117740. }
  117741. }
  117742. }
  117743. }
  117744. }
  117745. /* AoTuV */
  117746. /** @ M2 **
  117747. The boost problem by the combination of noise normalization and point stereo is eased.
  117748. However, this is a temporary patch.
  117749. by Aoyumi @ 2004/04/18
  117750. */
  117751. void hf_reduction(vorbis_info_psy_global *g,
  117752. vorbis_look_psy *p,
  117753. vorbis_info_mapping0 *vi,
  117754. float **mdct){
  117755. int i,j,n=p->n, de=0.3*p->m_val;
  117756. int limit=g->coupling_pointlimit[p->vi->blockflag][PACKETBLOBS/2];
  117757. for(i=0; i<vi->coupling_steps; i++){
  117758. /* for(j=start; j<limit; j++){} // ???*/
  117759. for(j=limit; j<n; j++)
  117760. mdct[i][j] *= (1.0 - de*((float)(j-limit) / (float)(n-limit)));
  117761. }
  117762. }
  117763. #endif
  117764. /********* End of inlined file: psy.c *********/
  117765. /********* Start of inlined file: registry.c *********/
  117766. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  117767. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117768. // tasks..
  117769. /********* Start of inlined file: juce_Config.h *********/
  117770. #ifndef __JUCE_CONFIG_JUCEHEADER__
  117771. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  117772. /*
  117773. This file contains macros that enable/disable various JUCE features.
  117774. */
  117775. /** The name of the namespace that all Juce classes and functions will be
  117776. put inside. If this is not defined, no namespace will be used.
  117777. */
  117778. #ifndef JUCE_NAMESPACE
  117779. #define JUCE_NAMESPACE juce
  117780. #endif
  117781. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  117782. but if you define this value, you can override this can force it to be true or
  117783. false.
  117784. */
  117785. #ifndef JUCE_FORCE_DEBUG
  117786. //#define JUCE_FORCE_DEBUG 1
  117787. #endif
  117788. /** If this flag is enabled, the the jassert and jassertfalse macros will
  117789. always use Logger::writeToLog() to write a message when an assertion happens.
  117790. Enabling it will also leave this turned on in release builds. When it's disabled,
  117791. however, the jassert and jassertfalse macros will not be compiled in a
  117792. release build.
  117793. @see jassert, jassertfalse, Logger
  117794. */
  117795. #ifndef JUCE_LOG_ASSERTIONS
  117796. // #define JUCE_LOG_ASSERTIONS 1
  117797. #endif
  117798. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  117799. which the ASIOAudioIODevice class can't be built. See the comments in the
  117800. ASIOAudioIODevice class's header file for more info about this.
  117801. (This only affects a Win32 build)
  117802. */
  117803. #ifndef JUCE_ASIO
  117804. #define JUCE_ASIO 1
  117805. #endif
  117806. /** Comment out this macro to disable building of ALSA device support on Linux.
  117807. */
  117808. #ifndef JUCE_ALSA
  117809. #define JUCE_ALSA 1
  117810. #endif
  117811. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  117812. have the SDK installed.
  117813. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  117814. classes will be unavailable.
  117815. On Windows, if you enable this, you'll need to have the QuickTime SDK
  117816. installed, and its header files will need to be on your include path.
  117817. */
  117818. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  117819. #define JUCE_QUICKTIME 1
  117820. #endif
  117821. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  117822. have the appropriate headers and libraries available. If it's not enabled, the
  117823. OpenGLComponent class will be unavailable.
  117824. */
  117825. #ifndef JUCE_OPENGL
  117826. #define JUCE_OPENGL 1
  117827. #endif
  117828. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  117829. If you're not going to need either of these formats, turn off the flags to
  117830. avoid bloating your codebase with them.
  117831. */
  117832. #ifndef JUCE_USE_FLAC
  117833. #define JUCE_USE_FLAC 1
  117834. #endif
  117835. #ifndef JUCE_USE_OGGVORBIS
  117836. #define JUCE_USE_OGGVORBIS 1
  117837. #endif
  117838. /** This flag lets you enable support for CD-burning. You might want to disable
  117839. it to build without the MS SDK under windows.
  117840. */
  117841. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  117842. #define JUCE_USE_CDBURNER 1
  117843. #endif
  117844. /** Enabling this macro means that all regions that get repainted will have a coloured
  117845. line drawn around them.
  117846. This is handy if you're trying to optimise drawing, because it lets you easily see
  117847. when anything is being repainted unnecessarily.
  117848. */
  117849. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  117850. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  117851. #endif
  117852. /** Enable this under Linux to use Xinerama for multi-monitor support.
  117853. */
  117854. #ifndef JUCE_USE_XINERAMA
  117855. #define JUCE_USE_XINERAMA 1
  117856. #endif
  117857. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  117858. */
  117859. #ifndef JUCE_USE_XSHM
  117860. #define JUCE_USE_XSHM 1
  117861. #endif
  117862. /** Enabling this builds support for VST audio plugins.
  117863. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  117864. */
  117865. #ifndef JUCE_PLUGINHOST_VST
  117866. // #define JUCE_PLUGINHOST_VST 1
  117867. #endif
  117868. /** Enabling this builds support for AudioUnit audio plugins.
  117869. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  117870. */
  117871. #ifndef JUCE_PLUGINHOST_AU
  117872. // #define JUCE_PLUGINHOST_AU 1
  117873. #endif
  117874. /** Disabling this will avoid linking to any UI code. This is handy for
  117875. writing command-line utilities, e.g. on linux boxes which don't have some
  117876. of the UI libraries installed.
  117877. (On mac and windows, this won't generally make much difference to the build).
  117878. */
  117879. #ifndef JUCE_BUILD_GUI_CLASSES
  117880. #define JUCE_BUILD_GUI_CLASSES 1
  117881. #endif
  117882. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  117883. */
  117884. #ifndef JUCE_WEB_BROWSER
  117885. #define JUCE_WEB_BROWSER 1
  117886. #endif
  117887. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  117888. codebase - you might need to use this if you're linking to some of these libraries
  117889. yourself.
  117890. */
  117891. #ifndef JUCE_INCLUDE_ZLIB_CODE
  117892. #define JUCE_INCLUDE_ZLIB_CODE 1
  117893. #endif
  117894. #ifndef JUCE_INCLUDE_FLAC_CODE
  117895. #define JUCE_INCLUDE_FLAC_CODE 1
  117896. #endif
  117897. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  117898. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  117899. #endif
  117900. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  117901. #define JUCE_INCLUDE_PNGLIB_CODE 1
  117902. #endif
  117903. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  117904. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  117905. #endif
  117906. /** Enable this to add extra memory-leak info to the new and delete operators.
  117907. (Currently, this only affects Windows builds in debug mode).
  117908. */
  117909. #ifndef JUCE_CHECK_MEMORY_LEAKS
  117910. #define JUCE_CHECK_MEMORY_LEAKS 1
  117911. #endif
  117912. /** Enable this to turn on juce's internal catching of exceptions.
  117913. Turning it off will avoid any exception catching. With it on, all exceptions
  117914. are passed to the JUCEApplication::unhandledException() callback for logging.
  117915. */
  117916. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  117917. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  117918. #endif
  117919. /** If this macro is set, the Juce String class will use unicode as its
  117920. internal representation. If it isn't set, it'll use ANSI.
  117921. */
  117922. #ifndef JUCE_STRINGS_ARE_UNICODE
  117923. #define JUCE_STRINGS_ARE_UNICODE 1
  117924. #endif
  117925. #endif
  117926. /********* End of inlined file: juce_Config.h *********/
  117927. #ifdef _MSC_VER
  117928. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  117929. #endif
  117930. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  117931. #if JUCE_USE_OGGVORBIS
  117932. /* seems like major overkill now; the backend numbers will grow into
  117933. the infrastructure soon enough */
  117934. extern vorbis_func_floor floor0_exportbundle;
  117935. extern vorbis_func_floor floor1_exportbundle;
  117936. extern vorbis_func_residue residue0_exportbundle;
  117937. extern vorbis_func_residue residue1_exportbundle;
  117938. extern vorbis_func_residue residue2_exportbundle;
  117939. extern vorbis_func_mapping mapping0_exportbundle;
  117940. vorbis_func_floor *_floor_P[]={
  117941. &floor0_exportbundle,
  117942. &floor1_exportbundle,
  117943. };
  117944. vorbis_func_residue *_residue_P[]={
  117945. &residue0_exportbundle,
  117946. &residue1_exportbundle,
  117947. &residue2_exportbundle,
  117948. };
  117949. vorbis_func_mapping *_mapping_P[]={
  117950. &mapping0_exportbundle,
  117951. };
  117952. #endif
  117953. /********* End of inlined file: registry.c *********/
  117954. /********* Start of inlined file: res0.c *********/
  117955. /* Slow, slow, slow, simpleminded and did I mention it was slow? The
  117956. encode/decode loops are coded for clarity and performance is not
  117957. yet even a nagging little idea lurking in the shadows. Oh and BTW,
  117958. it's slow. */
  117959. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  117960. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  117961. // tasks..
  117962. /********* Start of inlined file: juce_Config.h *********/
  117963. #ifndef __JUCE_CONFIG_JUCEHEADER__
  117964. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  117965. /*
  117966. This file contains macros that enable/disable various JUCE features.
  117967. */
  117968. /** The name of the namespace that all Juce classes and functions will be
  117969. put inside. If this is not defined, no namespace will be used.
  117970. */
  117971. #ifndef JUCE_NAMESPACE
  117972. #define JUCE_NAMESPACE juce
  117973. #endif
  117974. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  117975. but if you define this value, you can override this can force it to be true or
  117976. false.
  117977. */
  117978. #ifndef JUCE_FORCE_DEBUG
  117979. //#define JUCE_FORCE_DEBUG 1
  117980. #endif
  117981. /** If this flag is enabled, the the jassert and jassertfalse macros will
  117982. always use Logger::writeToLog() to write a message when an assertion happens.
  117983. Enabling it will also leave this turned on in release builds. When it's disabled,
  117984. however, the jassert and jassertfalse macros will not be compiled in a
  117985. release build.
  117986. @see jassert, jassertfalse, Logger
  117987. */
  117988. #ifndef JUCE_LOG_ASSERTIONS
  117989. // #define JUCE_LOG_ASSERTIONS 1
  117990. #endif
  117991. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  117992. which the ASIOAudioIODevice class can't be built. See the comments in the
  117993. ASIOAudioIODevice class's header file for more info about this.
  117994. (This only affects a Win32 build)
  117995. */
  117996. #ifndef JUCE_ASIO
  117997. #define JUCE_ASIO 1
  117998. #endif
  117999. /** Comment out this macro to disable building of ALSA device support on Linux.
  118000. */
  118001. #ifndef JUCE_ALSA
  118002. #define JUCE_ALSA 1
  118003. #endif
  118004. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  118005. have the SDK installed.
  118006. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  118007. classes will be unavailable.
  118008. On Windows, if you enable this, you'll need to have the QuickTime SDK
  118009. installed, and its header files will need to be on your include path.
  118010. */
  118011. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  118012. #define JUCE_QUICKTIME 1
  118013. #endif
  118014. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  118015. have the appropriate headers and libraries available. If it's not enabled, the
  118016. OpenGLComponent class will be unavailable.
  118017. */
  118018. #ifndef JUCE_OPENGL
  118019. #define JUCE_OPENGL 1
  118020. #endif
  118021. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  118022. If you're not going to need either of these formats, turn off the flags to
  118023. avoid bloating your codebase with them.
  118024. */
  118025. #ifndef JUCE_USE_FLAC
  118026. #define JUCE_USE_FLAC 1
  118027. #endif
  118028. #ifndef JUCE_USE_OGGVORBIS
  118029. #define JUCE_USE_OGGVORBIS 1
  118030. #endif
  118031. /** This flag lets you enable support for CD-burning. You might want to disable
  118032. it to build without the MS SDK under windows.
  118033. */
  118034. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  118035. #define JUCE_USE_CDBURNER 1
  118036. #endif
  118037. /** Enabling this macro means that all regions that get repainted will have a coloured
  118038. line drawn around them.
  118039. This is handy if you're trying to optimise drawing, because it lets you easily see
  118040. when anything is being repainted unnecessarily.
  118041. */
  118042. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  118043. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  118044. #endif
  118045. /** Enable this under Linux to use Xinerama for multi-monitor support.
  118046. */
  118047. #ifndef JUCE_USE_XINERAMA
  118048. #define JUCE_USE_XINERAMA 1
  118049. #endif
  118050. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  118051. */
  118052. #ifndef JUCE_USE_XSHM
  118053. #define JUCE_USE_XSHM 1
  118054. #endif
  118055. /** Enabling this builds support for VST audio plugins.
  118056. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  118057. */
  118058. #ifndef JUCE_PLUGINHOST_VST
  118059. // #define JUCE_PLUGINHOST_VST 1
  118060. #endif
  118061. /** Enabling this builds support for AudioUnit audio plugins.
  118062. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  118063. */
  118064. #ifndef JUCE_PLUGINHOST_AU
  118065. // #define JUCE_PLUGINHOST_AU 1
  118066. #endif
  118067. /** Disabling this will avoid linking to any UI code. This is handy for
  118068. writing command-line utilities, e.g. on linux boxes which don't have some
  118069. of the UI libraries installed.
  118070. (On mac and windows, this won't generally make much difference to the build).
  118071. */
  118072. #ifndef JUCE_BUILD_GUI_CLASSES
  118073. #define JUCE_BUILD_GUI_CLASSES 1
  118074. #endif
  118075. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  118076. */
  118077. #ifndef JUCE_WEB_BROWSER
  118078. #define JUCE_WEB_BROWSER 1
  118079. #endif
  118080. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  118081. codebase - you might need to use this if you're linking to some of these libraries
  118082. yourself.
  118083. */
  118084. #ifndef JUCE_INCLUDE_ZLIB_CODE
  118085. #define JUCE_INCLUDE_ZLIB_CODE 1
  118086. #endif
  118087. #ifndef JUCE_INCLUDE_FLAC_CODE
  118088. #define JUCE_INCLUDE_FLAC_CODE 1
  118089. #endif
  118090. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  118091. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  118092. #endif
  118093. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  118094. #define JUCE_INCLUDE_PNGLIB_CODE 1
  118095. #endif
  118096. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  118097. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  118098. #endif
  118099. /** Enable this to add extra memory-leak info to the new and delete operators.
  118100. (Currently, this only affects Windows builds in debug mode).
  118101. */
  118102. #ifndef JUCE_CHECK_MEMORY_LEAKS
  118103. #define JUCE_CHECK_MEMORY_LEAKS 1
  118104. #endif
  118105. /** Enable this to turn on juce's internal catching of exceptions.
  118106. Turning it off will avoid any exception catching. With it on, all exceptions
  118107. are passed to the JUCEApplication::unhandledException() callback for logging.
  118108. */
  118109. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  118110. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  118111. #endif
  118112. /** If this macro is set, the Juce String class will use unicode as its
  118113. internal representation. If it isn't set, it'll use ANSI.
  118114. */
  118115. #ifndef JUCE_STRINGS_ARE_UNICODE
  118116. #define JUCE_STRINGS_ARE_UNICODE 1
  118117. #endif
  118118. #endif
  118119. /********* End of inlined file: juce_Config.h *********/
  118120. #ifdef _MSC_VER
  118121. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  118122. #endif
  118123. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  118124. #if JUCE_USE_OGGVORBIS
  118125. #include <stdlib.h>
  118126. #include <string.h>
  118127. #include <math.h>
  118128. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118129. #include <stdio.h>
  118130. #endif
  118131. typedef struct {
  118132. vorbis_info_residue0 *info;
  118133. int parts;
  118134. int stages;
  118135. codebook *fullbooks;
  118136. codebook *phrasebook;
  118137. codebook ***partbooks;
  118138. int partvals;
  118139. int **decodemap;
  118140. long postbits;
  118141. long phrasebits;
  118142. long frames;
  118143. #if defined(TRAIN_RES) || defined(TRAIN_RESAUX)
  118144. int train_seq;
  118145. long *training_data[8][64];
  118146. float training_max[8][64];
  118147. float training_min[8][64];
  118148. float tmin;
  118149. float tmax;
  118150. #endif
  118151. } vorbis_look_residue0;
  118152. void res0_free_info(vorbis_info_residue *i){
  118153. vorbis_info_residue0 *info=(vorbis_info_residue0 *)i;
  118154. if(info){
  118155. memset(info,0,sizeof(*info));
  118156. _ogg_free(info);
  118157. }
  118158. }
  118159. void res0_free_look(vorbis_look_residue *i){
  118160. int j;
  118161. if(i){
  118162. vorbis_look_residue0 *look=(vorbis_look_residue0 *)i;
  118163. #ifdef TRAIN_RES
  118164. {
  118165. int j,k,l;
  118166. for(j=0;j<look->parts;j++){
  118167. /*fprintf(stderr,"partition %d: ",j);*/
  118168. for(k=0;k<8;k++)
  118169. if(look->training_data[k][j]){
  118170. char buffer[80];
  118171. FILE *of;
  118172. codebook *statebook=look->partbooks[j][k];
  118173. /* long and short into the same bucket by current convention */
  118174. sprintf(buffer,"res_part%d_pass%d.vqd",j,k);
  118175. of=fopen(buffer,"a");
  118176. for(l=0;l<statebook->entries;l++)
  118177. fprintf(of,"%d:%ld\n",l,look->training_data[k][j][l]);
  118178. fclose(of);
  118179. /*fprintf(stderr,"%d(%.2f|%.2f) ",k,
  118180. look->training_min[k][j],look->training_max[k][j]);*/
  118181. _ogg_free(look->training_data[k][j]);
  118182. look->training_data[k][j]=NULL;
  118183. }
  118184. /*fprintf(stderr,"\n");*/
  118185. }
  118186. }
  118187. fprintf(stderr,"min/max residue: %g::%g\n",look->tmin,look->tmax);
  118188. /*fprintf(stderr,"residue bit usage %f:%f (%f total)\n",
  118189. (float)look->phrasebits/look->frames,
  118190. (float)look->postbits/look->frames,
  118191. (float)(look->postbits+look->phrasebits)/look->frames);*/
  118192. #endif
  118193. /*vorbis_info_residue0 *info=look->info;
  118194. fprintf(stderr,
  118195. "%ld frames encoded in %ld phrasebits and %ld residue bits "
  118196. "(%g/frame) \n",look->frames,look->phrasebits,
  118197. look->resbitsflat,
  118198. (look->phrasebits+look->resbitsflat)/(float)look->frames);
  118199. for(j=0;j<look->parts;j++){
  118200. long acc=0;
  118201. fprintf(stderr,"\t[%d] == ",j);
  118202. for(k=0;k<look->stages;k++)
  118203. if((info->secondstages[j]>>k)&1){
  118204. fprintf(stderr,"%ld,",look->resbits[j][k]);
  118205. acc+=look->resbits[j][k];
  118206. }
  118207. fprintf(stderr,":: (%ld vals) %1.2fbits/sample\n",look->resvals[j],
  118208. acc?(float)acc/(look->resvals[j]*info->grouping):0);
  118209. }
  118210. fprintf(stderr,"\n");*/
  118211. for(j=0;j<look->parts;j++)
  118212. if(look->partbooks[j])_ogg_free(look->partbooks[j]);
  118213. _ogg_free(look->partbooks);
  118214. for(j=0;j<look->partvals;j++)
  118215. _ogg_free(look->decodemap[j]);
  118216. _ogg_free(look->decodemap);
  118217. memset(look,0,sizeof(*look));
  118218. _ogg_free(look);
  118219. }
  118220. }
  118221. static int icount(unsigned int v){
  118222. int ret=0;
  118223. while(v){
  118224. ret+=v&1;
  118225. v>>=1;
  118226. }
  118227. return(ret);
  118228. }
  118229. void res0_pack(vorbis_info_residue *vr,oggpack_buffer *opb){
  118230. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118231. int j,acc=0;
  118232. oggpack_write(opb,info->begin,24);
  118233. oggpack_write(opb,info->end,24);
  118234. oggpack_write(opb,info->grouping-1,24); /* residue vectors to group and
  118235. code with a partitioned book */
  118236. oggpack_write(opb,info->partitions-1,6); /* possible partition choices */
  118237. oggpack_write(opb,info->groupbook,8); /* group huffman book */
  118238. /* secondstages is a bitmask; as encoding progresses pass by pass, a
  118239. bitmask of one indicates this partition class has bits to write
  118240. this pass */
  118241. for(j=0;j<info->partitions;j++){
  118242. if(ilog(info->secondstages[j])>3){
  118243. /* yes, this is a minor hack due to not thinking ahead */
  118244. oggpack_write(opb,info->secondstages[j],3);
  118245. oggpack_write(opb,1,1);
  118246. oggpack_write(opb,info->secondstages[j]>>3,5);
  118247. }else
  118248. oggpack_write(opb,info->secondstages[j],4); /* trailing zero */
  118249. acc+=icount(info->secondstages[j]);
  118250. }
  118251. for(j=0;j<acc;j++)
  118252. oggpack_write(opb,info->booklist[j],8);
  118253. }
  118254. /* vorbis_info is for range checking */
  118255. vorbis_info_residue *res0_unpack(vorbis_info *vi,oggpack_buffer *opb){
  118256. int j,acc=0;
  118257. vorbis_info_residue0 *info=(vorbis_info_residue0*) _ogg_calloc(1,sizeof(*info));
  118258. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  118259. info->begin=oggpack_read(opb,24);
  118260. info->end=oggpack_read(opb,24);
  118261. info->grouping=oggpack_read(opb,24)+1;
  118262. info->partitions=oggpack_read(opb,6)+1;
  118263. info->groupbook=oggpack_read(opb,8);
  118264. for(j=0;j<info->partitions;j++){
  118265. int cascade=oggpack_read(opb,3);
  118266. if(oggpack_read(opb,1))
  118267. cascade|=(oggpack_read(opb,5)<<3);
  118268. info->secondstages[j]=cascade;
  118269. acc+=icount(cascade);
  118270. }
  118271. for(j=0;j<acc;j++)
  118272. info->booklist[j]=oggpack_read(opb,8);
  118273. if(info->groupbook>=ci->books)goto errout;
  118274. for(j=0;j<acc;j++)
  118275. if(info->booklist[j]>=ci->books)goto errout;
  118276. return(info);
  118277. errout:
  118278. res0_free_info(info);
  118279. return(NULL);
  118280. }
  118281. vorbis_look_residue *res0_look(vorbis_dsp_state *vd,
  118282. vorbis_info_residue *vr){
  118283. vorbis_info_residue0 *info=(vorbis_info_residue0 *)vr;
  118284. vorbis_look_residue0 *look=(vorbis_look_residue0 *)_ogg_calloc(1,sizeof(*look));
  118285. codec_setup_info *ci=(codec_setup_info*)vd->vi->codec_setup;
  118286. int j,k,acc=0;
  118287. int dim;
  118288. int maxstage=0;
  118289. look->info=info;
  118290. look->parts=info->partitions;
  118291. look->fullbooks=ci->fullbooks;
  118292. look->phrasebook=ci->fullbooks+info->groupbook;
  118293. dim=look->phrasebook->dim;
  118294. look->partbooks=(codebook***)_ogg_calloc(look->parts,sizeof(*look->partbooks));
  118295. for(j=0;j<look->parts;j++){
  118296. int stages=ilog(info->secondstages[j]);
  118297. if(stages){
  118298. if(stages>maxstage)maxstage=stages;
  118299. look->partbooks[j]=(codebook**) _ogg_calloc(stages,sizeof(*look->partbooks[j]));
  118300. for(k=0;k<stages;k++)
  118301. if(info->secondstages[j]&(1<<k)){
  118302. look->partbooks[j][k]=ci->fullbooks+info->booklist[acc++];
  118303. #ifdef TRAIN_RES
  118304. look->training_data[k][j]=_ogg_calloc(look->partbooks[j][k]->entries,
  118305. sizeof(***look->training_data));
  118306. #endif
  118307. }
  118308. }
  118309. }
  118310. look->partvals=rint(pow((float)look->parts,(float)dim));
  118311. look->stages=maxstage;
  118312. look->decodemap=(int**)_ogg_malloc(look->partvals*sizeof(*look->decodemap));
  118313. for(j=0;j<look->partvals;j++){
  118314. long val=j;
  118315. long mult=look->partvals/look->parts;
  118316. look->decodemap[j]=(int*)_ogg_malloc(dim*sizeof(*look->decodemap[j]));
  118317. for(k=0;k<dim;k++){
  118318. long deco=val/mult;
  118319. val-=deco*mult;
  118320. mult/=look->parts;
  118321. look->decodemap[j][k]=deco;
  118322. }
  118323. }
  118324. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118325. {
  118326. static int train_seq=0;
  118327. look->train_seq=train_seq++;
  118328. }
  118329. #endif
  118330. return(look);
  118331. }
  118332. /* break an abstraction and copy some code for performance purposes */
  118333. static int local_book_besterror(codebook *book,float *a){
  118334. int dim=book->dim,i,k,o;
  118335. int best=0;
  118336. encode_aux_threshmatch *tt=book->c->thresh_tree;
  118337. /* find the quant val of each scalar */
  118338. for(k=0,o=dim;k<dim;++k){
  118339. float val=a[--o];
  118340. i=tt->threshvals>>1;
  118341. if(val<tt->quantthresh[i]){
  118342. if(val<tt->quantthresh[i-1]){
  118343. for(--i;i>0;--i)
  118344. if(val>=tt->quantthresh[i-1])
  118345. break;
  118346. }
  118347. }else{
  118348. for(++i;i<tt->threshvals-1;++i)
  118349. if(val<tt->quantthresh[i])break;
  118350. }
  118351. best=(best*tt->quantvals)+tt->quantmap[i];
  118352. }
  118353. /* regular lattices are easy :-) */
  118354. if(book->c->lengthlist[best]<=0){
  118355. const static_codebook *c=book->c;
  118356. int i,j;
  118357. float bestf=0.f;
  118358. float *e=book->valuelist;
  118359. best=-1;
  118360. for(i=0;i<book->entries;i++){
  118361. if(c->lengthlist[i]>0){
  118362. float thisx=0.f;
  118363. for(j=0;j<dim;j++){
  118364. float val=(e[j]-a[j]);
  118365. thisx+=val*val;
  118366. }
  118367. if(best==-1 || thisx<bestf){
  118368. bestf=thisx;
  118369. best=i;
  118370. }
  118371. }
  118372. e+=dim;
  118373. }
  118374. }
  118375. {
  118376. float *ptr=book->valuelist+best*dim;
  118377. for(i=0;i<dim;i++)
  118378. *a++ -= *ptr++;
  118379. }
  118380. return(best);
  118381. }
  118382. static int _encodepart(oggpack_buffer *opb,float *vec, int n,
  118383. codebook *book,long *acc){
  118384. int i,bits=0;
  118385. int dim=book->dim;
  118386. int step=n/dim;
  118387. for(i=0;i<step;i++){
  118388. int entry=local_book_besterror(book,vec+i*dim);
  118389. #ifdef TRAIN_RES
  118390. acc[entry]++;
  118391. #endif
  118392. bits+=vorbis_book_encode(book,entry,opb);
  118393. }
  118394. return(bits);
  118395. }
  118396. static long **_01class(vorbis_block *vb,vorbis_look_residue *vl,
  118397. float **in,int ch){
  118398. long i,j,k;
  118399. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118400. vorbis_info_residue0 *info=look->info;
  118401. /* move all this setup out later */
  118402. int samples_per_partition=info->grouping;
  118403. int possible_partitions=info->partitions;
  118404. int n=info->end-info->begin;
  118405. int partvals=n/samples_per_partition;
  118406. long **partword=(long**)_vorbis_block_alloc(vb,ch*sizeof(*partword));
  118407. float scale=100./samples_per_partition;
  118408. /* we find the partition type for each partition of each
  118409. channel. We'll go back and do the interleaved encoding in a
  118410. bit. For now, clarity */
  118411. for(i=0;i<ch;i++){
  118412. partword[i]=(long*)_vorbis_block_alloc(vb,n/samples_per_partition*sizeof(*partword[i]));
  118413. memset(partword[i],0,n/samples_per_partition*sizeof(*partword[i]));
  118414. }
  118415. for(i=0;i<partvals;i++){
  118416. int offset=i*samples_per_partition+info->begin;
  118417. for(j=0;j<ch;j++){
  118418. float max=0.;
  118419. float ent=0.;
  118420. for(k=0;k<samples_per_partition;k++){
  118421. if(fabs(in[j][offset+k])>max)max=fabs(in[j][offset+k]);
  118422. ent+=fabs(rint(in[j][offset+k]));
  118423. }
  118424. ent*=scale;
  118425. for(k=0;k<possible_partitions-1;k++)
  118426. if(max<=info->classmetric1[k] &&
  118427. (info->classmetric2[k]<0 || (int)ent<info->classmetric2[k]))
  118428. break;
  118429. partword[j][i]=k;
  118430. }
  118431. }
  118432. #ifdef TRAIN_RESAUX
  118433. {
  118434. FILE *of;
  118435. char buffer[80];
  118436. for(i=0;i<ch;i++){
  118437. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118438. of=fopen(buffer,"a");
  118439. for(j=0;j<partvals;j++)
  118440. fprintf(of,"%ld, ",partword[i][j]);
  118441. fprintf(of,"\n");
  118442. fclose(of);
  118443. }
  118444. }
  118445. #endif
  118446. look->frames++;
  118447. return(partword);
  118448. }
  118449. /* designed for stereo or other modes where the partition size is an
  118450. integer multiple of the number of channels encoded in the current
  118451. submap */
  118452. static long **_2class(vorbis_block *vb,vorbis_look_residue *vl,float **in,
  118453. int ch){
  118454. long i,j,k,l;
  118455. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118456. vorbis_info_residue0 *info=look->info;
  118457. /* move all this setup out later */
  118458. int samples_per_partition=info->grouping;
  118459. int possible_partitions=info->partitions;
  118460. int n=info->end-info->begin;
  118461. int partvals=n/samples_per_partition;
  118462. long **partword=(long**)_vorbis_block_alloc(vb,sizeof(*partword));
  118463. #if defined(TRAIN_RES) || defined (TRAIN_RESAUX)
  118464. FILE *of;
  118465. char buffer[80];
  118466. #endif
  118467. partword[0]=(long*)_vorbis_block_alloc(vb,n*ch/samples_per_partition*sizeof(*partword[0]));
  118468. memset(partword[0],0,n*ch/samples_per_partition*sizeof(*partword[0]));
  118469. for(i=0,l=info->begin/ch;i<partvals;i++){
  118470. float magmax=0.f;
  118471. float angmax=0.f;
  118472. for(j=0;j<samples_per_partition;j+=ch){
  118473. if(fabs(in[0][l])>magmax)magmax=fabs(in[0][l]);
  118474. for(k=1;k<ch;k++)
  118475. if(fabs(in[k][l])>angmax)angmax=fabs(in[k][l]);
  118476. l++;
  118477. }
  118478. for(j=0;j<possible_partitions-1;j++)
  118479. if(magmax<=info->classmetric1[j] &&
  118480. angmax<=info->classmetric2[j])
  118481. break;
  118482. partword[0][i]=j;
  118483. }
  118484. #ifdef TRAIN_RESAUX
  118485. sprintf(buffer,"resaux_%d.vqd",look->train_seq);
  118486. of=fopen(buffer,"a");
  118487. for(i=0;i<partvals;i++)
  118488. fprintf(of,"%ld, ",partword[0][i]);
  118489. fprintf(of,"\n");
  118490. fclose(of);
  118491. #endif
  118492. look->frames++;
  118493. return(partword);
  118494. }
  118495. static int _01forward(oggpack_buffer *opb,
  118496. vorbis_block *vb,vorbis_look_residue *vl,
  118497. float **in,int ch,
  118498. long **partword,
  118499. int (*encode)(oggpack_buffer *,float *,int,
  118500. codebook *,long *)){
  118501. long i,j,k,s;
  118502. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118503. vorbis_info_residue0 *info=look->info;
  118504. /* move all this setup out later */
  118505. int samples_per_partition=info->grouping;
  118506. int possible_partitions=info->partitions;
  118507. int partitions_per_word=look->phrasebook->dim;
  118508. int n=info->end-info->begin;
  118509. int partvals=n/samples_per_partition;
  118510. long resbits[128];
  118511. long resvals[128];
  118512. #ifdef TRAIN_RES
  118513. for(i=0;i<ch;i++)
  118514. for(j=info->begin;j<info->end;j++){
  118515. if(in[i][j]>look->tmax)look->tmax=in[i][j];
  118516. if(in[i][j]<look->tmin)look->tmin=in[i][j];
  118517. }
  118518. #endif
  118519. memset(resbits,0,sizeof(resbits));
  118520. memset(resvals,0,sizeof(resvals));
  118521. /* we code the partition words for each channel, then the residual
  118522. words for a partition per channel until we've written all the
  118523. residual words for that partition word. Then write the next
  118524. partition channel words... */
  118525. for(s=0;s<look->stages;s++){
  118526. for(i=0;i<partvals;){
  118527. /* first we encode a partition codeword for each channel */
  118528. if(s==0){
  118529. for(j=0;j<ch;j++){
  118530. long val=partword[j][i];
  118531. for(k=1;k<partitions_per_word;k++){
  118532. val*=possible_partitions;
  118533. if(i+k<partvals)
  118534. val+=partword[j][i+k];
  118535. }
  118536. /* training hack */
  118537. if(val<look->phrasebook->entries)
  118538. look->phrasebits+=vorbis_book_encode(look->phrasebook,val,opb);
  118539. #if 0 /*def TRAIN_RES*/
  118540. else
  118541. fprintf(stderr,"!");
  118542. #endif
  118543. }
  118544. }
  118545. /* now we encode interleaved residual values for the partitions */
  118546. for(k=0;k<partitions_per_word && i<partvals;k++,i++){
  118547. long offset=i*samples_per_partition+info->begin;
  118548. for(j=0;j<ch;j++){
  118549. if(s==0)resvals[partword[j][i]]+=samples_per_partition;
  118550. if(info->secondstages[partword[j][i]]&(1<<s)){
  118551. codebook *statebook=look->partbooks[partword[j][i]][s];
  118552. if(statebook){
  118553. int ret;
  118554. long *accumulator=NULL;
  118555. #ifdef TRAIN_RES
  118556. accumulator=look->training_data[s][partword[j][i]];
  118557. {
  118558. int l;
  118559. float *samples=in[j]+offset;
  118560. for(l=0;l<samples_per_partition;l++){
  118561. if(samples[l]<look->training_min[s][partword[j][i]])
  118562. look->training_min[s][partword[j][i]]=samples[l];
  118563. if(samples[l]>look->training_max[s][partword[j][i]])
  118564. look->training_max[s][partword[j][i]]=samples[l];
  118565. }
  118566. }
  118567. #endif
  118568. ret=encode(opb,in[j]+offset,samples_per_partition,
  118569. statebook,accumulator);
  118570. look->postbits+=ret;
  118571. resbits[partword[j][i]]+=ret;
  118572. }
  118573. }
  118574. }
  118575. }
  118576. }
  118577. }
  118578. /*{
  118579. long total=0;
  118580. long totalbits=0;
  118581. fprintf(stderr,"%d :: ",vb->mode);
  118582. for(k=0;k<possible_partitions;k++){
  118583. fprintf(stderr,"%ld/%1.2g, ",resvals[k],(float)resbits[k]/resvals[k]);
  118584. total+=resvals[k];
  118585. totalbits+=resbits[k];
  118586. }
  118587. fprintf(stderr,":: %ld:%1.2g\n",total,(double)totalbits/total);
  118588. }*/
  118589. return(0);
  118590. }
  118591. /* a truncated packet here just means 'stop working'; it's not an error */
  118592. static int _01inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118593. float **in,int ch,
  118594. long (*decodepart)(codebook *, float *,
  118595. oggpack_buffer *,int)){
  118596. long i,j,k,l,s;
  118597. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118598. vorbis_info_residue0 *info=look->info;
  118599. /* move all this setup out later */
  118600. int samples_per_partition=info->grouping;
  118601. int partitions_per_word=look->phrasebook->dim;
  118602. int n=info->end-info->begin;
  118603. int partvals=n/samples_per_partition;
  118604. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118605. int ***partword=(int***)alloca(ch*sizeof(*partword));
  118606. for(j=0;j<ch;j++)
  118607. partword[j]=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword[j]));
  118608. for(s=0;s<look->stages;s++){
  118609. /* each loop decodes on partition codeword containing
  118610. partitions_pre_word partitions */
  118611. for(i=0,l=0;i<partvals;l++){
  118612. if(s==0){
  118613. /* fetch the partition word for each channel */
  118614. for(j=0;j<ch;j++){
  118615. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118616. if(temp==-1)goto eopbreak;
  118617. partword[j][l]=look->decodemap[temp];
  118618. if(partword[j][l]==NULL)goto errout;
  118619. }
  118620. }
  118621. /* now we decode residual values for the partitions */
  118622. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118623. for(j=0;j<ch;j++){
  118624. long offset=info->begin+i*samples_per_partition;
  118625. if(info->secondstages[partword[j][l][k]]&(1<<s)){
  118626. codebook *stagebook=look->partbooks[partword[j][l][k]][s];
  118627. if(stagebook){
  118628. if(decodepart(stagebook,in[j]+offset,&vb->opb,
  118629. samples_per_partition)==-1)goto eopbreak;
  118630. }
  118631. }
  118632. }
  118633. }
  118634. }
  118635. errout:
  118636. eopbreak:
  118637. return(0);
  118638. }
  118639. #if 0
  118640. /* residue 0 and 1 are just slight variants of one another. 0 is
  118641. interleaved, 1 is not */
  118642. long **res0_class(vorbis_block *vb,vorbis_look_residue *vl,
  118643. float **in,int *nonzero,int ch){
  118644. /* we encode only the nonzero parts of a bundle */
  118645. int i,used=0;
  118646. for(i=0;i<ch;i++)
  118647. if(nonzero[i])
  118648. in[used++]=in[i];
  118649. if(used)
  118650. /*return(_01class(vb,vl,in,used,_interleaved_testhack));*/
  118651. return(_01class(vb,vl,in,used));
  118652. else
  118653. return(0);
  118654. }
  118655. int res0_forward(vorbis_block *vb,vorbis_look_residue *vl,
  118656. float **in,float **out,int *nonzero,int ch,
  118657. long **partword){
  118658. /* we encode only the nonzero parts of a bundle */
  118659. int i,j,used=0,n=vb->pcmend/2;
  118660. for(i=0;i<ch;i++)
  118661. if(nonzero[i]){
  118662. if(out)
  118663. for(j=0;j<n;j++)
  118664. out[i][j]+=in[i][j];
  118665. in[used++]=in[i];
  118666. }
  118667. if(used){
  118668. int ret=_01forward(vb,vl,in,used,partword,
  118669. _interleaved_encodepart);
  118670. if(out){
  118671. used=0;
  118672. for(i=0;i<ch;i++)
  118673. if(nonzero[i]){
  118674. for(j=0;j<n;j++)
  118675. out[i][j]-=in[used][j];
  118676. used++;
  118677. }
  118678. }
  118679. return(ret);
  118680. }else{
  118681. return(0);
  118682. }
  118683. }
  118684. #endif
  118685. int res0_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118686. float **in,int *nonzero,int ch){
  118687. int i,used=0;
  118688. for(i=0;i<ch;i++)
  118689. if(nonzero[i])
  118690. in[used++]=in[i];
  118691. if(used)
  118692. return(_01inverse(vb,vl,in,used,vorbis_book_decodevs_add));
  118693. else
  118694. return(0);
  118695. }
  118696. int res1_forward(oggpack_buffer *opb,vorbis_block *vb,vorbis_look_residue *vl,
  118697. float **in,float **out,int *nonzero,int ch,
  118698. long **partword){
  118699. int i,j,used=0,n=vb->pcmend/2;
  118700. for(i=0;i<ch;i++)
  118701. if(nonzero[i]){
  118702. if(out)
  118703. for(j=0;j<n;j++)
  118704. out[i][j]+=in[i][j];
  118705. in[used++]=in[i];
  118706. }
  118707. if(used){
  118708. int ret=_01forward(opb,vb,vl,in,used,partword,_encodepart);
  118709. if(out){
  118710. used=0;
  118711. for(i=0;i<ch;i++)
  118712. if(nonzero[i]){
  118713. for(j=0;j<n;j++)
  118714. out[i][j]-=in[used][j];
  118715. used++;
  118716. }
  118717. }
  118718. return(ret);
  118719. }else{
  118720. return(0);
  118721. }
  118722. }
  118723. long **res1_class(vorbis_block *vb,vorbis_look_residue *vl,
  118724. float **in,int *nonzero,int ch){
  118725. int i,used=0;
  118726. for(i=0;i<ch;i++)
  118727. if(nonzero[i])
  118728. in[used++]=in[i];
  118729. if(used)
  118730. return(_01class(vb,vl,in,used));
  118731. else
  118732. return(0);
  118733. }
  118734. int res1_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118735. float **in,int *nonzero,int ch){
  118736. int i,used=0;
  118737. for(i=0;i<ch;i++)
  118738. if(nonzero[i])
  118739. in[used++]=in[i];
  118740. if(used)
  118741. return(_01inverse(vb,vl,in,used,vorbis_book_decodev_add));
  118742. else
  118743. return(0);
  118744. }
  118745. long **res2_class(vorbis_block *vb,vorbis_look_residue *vl,
  118746. float **in,int *nonzero,int ch){
  118747. int i,used=0;
  118748. for(i=0;i<ch;i++)
  118749. if(nonzero[i])used++;
  118750. if(used)
  118751. return(_2class(vb,vl,in,ch));
  118752. else
  118753. return(0);
  118754. }
  118755. /* res2 is slightly more different; all the channels are interleaved
  118756. into a single vector and encoded. */
  118757. int res2_forward(oggpack_buffer *opb,
  118758. vorbis_block *vb,vorbis_look_residue *vl,
  118759. float **in,float **out,int *nonzero,int ch,
  118760. long **partword){
  118761. long i,j,k,n=vb->pcmend/2,used=0;
  118762. /* don't duplicate the code; use a working vector hack for now and
  118763. reshape ourselves into a single channel res1 */
  118764. /* ugly; reallocs for each coupling pass :-( */
  118765. float *work=(float*)_vorbis_block_alloc(vb,ch*n*sizeof(*work));
  118766. for(i=0;i<ch;i++){
  118767. float *pcm=in[i];
  118768. if(nonzero[i])used++;
  118769. for(j=0,k=i;j<n;j++,k+=ch)
  118770. work[k]=pcm[j];
  118771. }
  118772. if(used){
  118773. int ret=_01forward(opb,vb,vl,&work,1,partword,_encodepart);
  118774. /* update the sofar vector */
  118775. if(out){
  118776. for(i=0;i<ch;i++){
  118777. float *pcm=in[i];
  118778. float *sofar=out[i];
  118779. for(j=0,k=i;j<n;j++,k+=ch)
  118780. sofar[j]+=pcm[j]-work[k];
  118781. }
  118782. }
  118783. return(ret);
  118784. }else{
  118785. return(0);
  118786. }
  118787. }
  118788. /* duplicate code here as speed is somewhat more important */
  118789. int res2_inverse(vorbis_block *vb,vorbis_look_residue *vl,
  118790. float **in,int *nonzero,int ch){
  118791. long i,k,l,s;
  118792. vorbis_look_residue0 *look=(vorbis_look_residue0 *)vl;
  118793. vorbis_info_residue0 *info=look->info;
  118794. /* move all this setup out later */
  118795. int samples_per_partition=info->grouping;
  118796. int partitions_per_word=look->phrasebook->dim;
  118797. int n=info->end-info->begin;
  118798. int partvals=n/samples_per_partition;
  118799. int partwords=(partvals+partitions_per_word-1)/partitions_per_word;
  118800. int **partword=(int**)_vorbis_block_alloc(vb,partwords*sizeof(*partword));
  118801. for(i=0;i<ch;i++)if(nonzero[i])break;
  118802. if(i==ch)return(0); /* no nonzero vectors */
  118803. for(s=0;s<look->stages;s++){
  118804. for(i=0,l=0;i<partvals;l++){
  118805. if(s==0){
  118806. /* fetch the partition word */
  118807. int temp=vorbis_book_decode(look->phrasebook,&vb->opb);
  118808. if(temp==-1)goto eopbreak;
  118809. partword[l]=look->decodemap[temp];
  118810. if(partword[l]==NULL)goto errout;
  118811. }
  118812. /* now we decode residual values for the partitions */
  118813. for(k=0;k<partitions_per_word && i<partvals;k++,i++)
  118814. if(info->secondstages[partword[l][k]]&(1<<s)){
  118815. codebook *stagebook=look->partbooks[partword[l][k]][s];
  118816. if(stagebook){
  118817. if(vorbis_book_decodevv_add(stagebook,in,
  118818. i*samples_per_partition+info->begin,ch,
  118819. &vb->opb,samples_per_partition)==-1)
  118820. goto eopbreak;
  118821. }
  118822. }
  118823. }
  118824. }
  118825. errout:
  118826. eopbreak:
  118827. return(0);
  118828. }
  118829. vorbis_func_residue residue0_exportbundle={
  118830. NULL,
  118831. &res0_unpack,
  118832. &res0_look,
  118833. &res0_free_info,
  118834. &res0_free_look,
  118835. NULL,
  118836. NULL,
  118837. &res0_inverse
  118838. };
  118839. vorbis_func_residue residue1_exportbundle={
  118840. &res0_pack,
  118841. &res0_unpack,
  118842. &res0_look,
  118843. &res0_free_info,
  118844. &res0_free_look,
  118845. &res1_class,
  118846. &res1_forward,
  118847. &res1_inverse
  118848. };
  118849. vorbis_func_residue residue2_exportbundle={
  118850. &res0_pack,
  118851. &res0_unpack,
  118852. &res0_look,
  118853. &res0_free_info,
  118854. &res0_free_look,
  118855. &res2_class,
  118856. &res2_forward,
  118857. &res2_inverse
  118858. };
  118859. #endif
  118860. /********* End of inlined file: res0.c *********/
  118861. /********* Start of inlined file: sharedbook.c *********/
  118862. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  118863. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  118864. // tasks..
  118865. /********* Start of inlined file: juce_Config.h *********/
  118866. #ifndef __JUCE_CONFIG_JUCEHEADER__
  118867. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  118868. /*
  118869. This file contains macros that enable/disable various JUCE features.
  118870. */
  118871. /** The name of the namespace that all Juce classes and functions will be
  118872. put inside. If this is not defined, no namespace will be used.
  118873. */
  118874. #ifndef JUCE_NAMESPACE
  118875. #define JUCE_NAMESPACE juce
  118876. #endif
  118877. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  118878. but if you define this value, you can override this can force it to be true or
  118879. false.
  118880. */
  118881. #ifndef JUCE_FORCE_DEBUG
  118882. //#define JUCE_FORCE_DEBUG 1
  118883. #endif
  118884. /** If this flag is enabled, the the jassert and jassertfalse macros will
  118885. always use Logger::writeToLog() to write a message when an assertion happens.
  118886. Enabling it will also leave this turned on in release builds. When it's disabled,
  118887. however, the jassert and jassertfalse macros will not be compiled in a
  118888. release build.
  118889. @see jassert, jassertfalse, Logger
  118890. */
  118891. #ifndef JUCE_LOG_ASSERTIONS
  118892. // #define JUCE_LOG_ASSERTIONS 1
  118893. #endif
  118894. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  118895. which the ASIOAudioIODevice class can't be built. See the comments in the
  118896. ASIOAudioIODevice class's header file for more info about this.
  118897. (This only affects a Win32 build)
  118898. */
  118899. #ifndef JUCE_ASIO
  118900. #define JUCE_ASIO 1
  118901. #endif
  118902. /** Comment out this macro to disable building of ALSA device support on Linux.
  118903. */
  118904. #ifndef JUCE_ALSA
  118905. #define JUCE_ALSA 1
  118906. #endif
  118907. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  118908. have the SDK installed.
  118909. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  118910. classes will be unavailable.
  118911. On Windows, if you enable this, you'll need to have the QuickTime SDK
  118912. installed, and its header files will need to be on your include path.
  118913. */
  118914. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  118915. #define JUCE_QUICKTIME 1
  118916. #endif
  118917. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  118918. have the appropriate headers and libraries available. If it's not enabled, the
  118919. OpenGLComponent class will be unavailable.
  118920. */
  118921. #ifndef JUCE_OPENGL
  118922. #define JUCE_OPENGL 1
  118923. #endif
  118924. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  118925. If you're not going to need either of these formats, turn off the flags to
  118926. avoid bloating your codebase with them.
  118927. */
  118928. #ifndef JUCE_USE_FLAC
  118929. #define JUCE_USE_FLAC 1
  118930. #endif
  118931. #ifndef JUCE_USE_OGGVORBIS
  118932. #define JUCE_USE_OGGVORBIS 1
  118933. #endif
  118934. /** This flag lets you enable support for CD-burning. You might want to disable
  118935. it to build without the MS SDK under windows.
  118936. */
  118937. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  118938. #define JUCE_USE_CDBURNER 1
  118939. #endif
  118940. /** Enabling this macro means that all regions that get repainted will have a coloured
  118941. line drawn around them.
  118942. This is handy if you're trying to optimise drawing, because it lets you easily see
  118943. when anything is being repainted unnecessarily.
  118944. */
  118945. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  118946. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  118947. #endif
  118948. /** Enable this under Linux to use Xinerama for multi-monitor support.
  118949. */
  118950. #ifndef JUCE_USE_XINERAMA
  118951. #define JUCE_USE_XINERAMA 1
  118952. #endif
  118953. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  118954. */
  118955. #ifndef JUCE_USE_XSHM
  118956. #define JUCE_USE_XSHM 1
  118957. #endif
  118958. /** Enabling this builds support for VST audio plugins.
  118959. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  118960. */
  118961. #ifndef JUCE_PLUGINHOST_VST
  118962. // #define JUCE_PLUGINHOST_VST 1
  118963. #endif
  118964. /** Enabling this builds support for AudioUnit audio plugins.
  118965. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  118966. */
  118967. #ifndef JUCE_PLUGINHOST_AU
  118968. // #define JUCE_PLUGINHOST_AU 1
  118969. #endif
  118970. /** Disabling this will avoid linking to any UI code. This is handy for
  118971. writing command-line utilities, e.g. on linux boxes which don't have some
  118972. of the UI libraries installed.
  118973. (On mac and windows, this won't generally make much difference to the build).
  118974. */
  118975. #ifndef JUCE_BUILD_GUI_CLASSES
  118976. #define JUCE_BUILD_GUI_CLASSES 1
  118977. #endif
  118978. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  118979. */
  118980. #ifndef JUCE_WEB_BROWSER
  118981. #define JUCE_WEB_BROWSER 1
  118982. #endif
  118983. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  118984. codebase - you might need to use this if you're linking to some of these libraries
  118985. yourself.
  118986. */
  118987. #ifndef JUCE_INCLUDE_ZLIB_CODE
  118988. #define JUCE_INCLUDE_ZLIB_CODE 1
  118989. #endif
  118990. #ifndef JUCE_INCLUDE_FLAC_CODE
  118991. #define JUCE_INCLUDE_FLAC_CODE 1
  118992. #endif
  118993. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  118994. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  118995. #endif
  118996. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  118997. #define JUCE_INCLUDE_PNGLIB_CODE 1
  118998. #endif
  118999. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  119000. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  119001. #endif
  119002. /** Enable this to add extra memory-leak info to the new and delete operators.
  119003. (Currently, this only affects Windows builds in debug mode).
  119004. */
  119005. #ifndef JUCE_CHECK_MEMORY_LEAKS
  119006. #define JUCE_CHECK_MEMORY_LEAKS 1
  119007. #endif
  119008. /** Enable this to turn on juce's internal catching of exceptions.
  119009. Turning it off will avoid any exception catching. With it on, all exceptions
  119010. are passed to the JUCEApplication::unhandledException() callback for logging.
  119011. */
  119012. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  119013. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  119014. #endif
  119015. /** If this macro is set, the Juce String class will use unicode as its
  119016. internal representation. If it isn't set, it'll use ANSI.
  119017. */
  119018. #ifndef JUCE_STRINGS_ARE_UNICODE
  119019. #define JUCE_STRINGS_ARE_UNICODE 1
  119020. #endif
  119021. #endif
  119022. /********* End of inlined file: juce_Config.h *********/
  119023. #ifdef _MSC_VER
  119024. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119025. #endif
  119026. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  119027. #if JUCE_USE_OGGVORBIS
  119028. #include <stdlib.h>
  119029. #include <math.h>
  119030. #include <string.h>
  119031. /**** pack/unpack helpers ******************************************/
  119032. int _ilog(unsigned int v){
  119033. int ret=0;
  119034. while(v){
  119035. ret++;
  119036. v>>=1;
  119037. }
  119038. return(ret);
  119039. }
  119040. /* 32 bit float (not IEEE; nonnormalized mantissa +
  119041. biased exponent) : neeeeeee eeemmmmm mmmmmmmm mmmmmmmm
  119042. Why not IEEE? It's just not that important here. */
  119043. #define VQ_FEXP 10
  119044. #define VQ_FMAN 21
  119045. #define VQ_FEXP_BIAS 768 /* bias toward values smaller than 1. */
  119046. /* doesn't currently guard under/overflow */
  119047. long _float32_pack(float val){
  119048. int sign=0;
  119049. long exp;
  119050. long mant;
  119051. if(val<0){
  119052. sign=0x80000000;
  119053. val= -val;
  119054. }
  119055. exp= floor(log(val)/log(2.f));
  119056. mant=rint(ldexp(val,(VQ_FMAN-1)-exp));
  119057. exp=(exp+VQ_FEXP_BIAS)<<VQ_FMAN;
  119058. return(sign|exp|mant);
  119059. }
  119060. float _float32_unpack(long val){
  119061. double mant=val&0x1fffff;
  119062. int sign=val&0x80000000;
  119063. long exp =(val&0x7fe00000L)>>VQ_FMAN;
  119064. if(sign)mant= -mant;
  119065. return(ldexp(mant,exp-(VQ_FMAN-1)-VQ_FEXP_BIAS));
  119066. }
  119067. /* given a list of word lengths, generate a list of codewords. Works
  119068. for length ordered or unordered, always assigns the lowest valued
  119069. codewords first. Extended to handle unused entries (length 0) */
  119070. ogg_uint32_t *_make_words(long *l,long n,long sparsecount){
  119071. long i,j,count=0;
  119072. ogg_uint32_t marker[33];
  119073. ogg_uint32_t *r=(ogg_uint32_t*)_ogg_malloc((sparsecount?sparsecount:n)*sizeof(*r));
  119074. memset(marker,0,sizeof(marker));
  119075. for(i=0;i<n;i++){
  119076. long length=l[i];
  119077. if(length>0){
  119078. ogg_uint32_t entry=marker[length];
  119079. /* when we claim a node for an entry, we also claim the nodes
  119080. below it (pruning off the imagined tree that may have dangled
  119081. from it) as well as blocking the use of any nodes directly
  119082. above for leaves */
  119083. /* update ourself */
  119084. if(length<32 && (entry>>length)){
  119085. /* error condition; the lengths must specify an overpopulated tree */
  119086. _ogg_free(r);
  119087. return(NULL);
  119088. }
  119089. r[count++]=entry;
  119090. /* Look to see if the next shorter marker points to the node
  119091. above. if so, update it and repeat. */
  119092. {
  119093. for(j=length;j>0;j--){
  119094. if(marker[j]&1){
  119095. /* have to jump branches */
  119096. if(j==1)
  119097. marker[1]++;
  119098. else
  119099. marker[j]=marker[j-1]<<1;
  119100. break; /* invariant says next upper marker would already
  119101. have been moved if it was on the same path */
  119102. }
  119103. marker[j]++;
  119104. }
  119105. }
  119106. /* prune the tree; the implicit invariant says all the longer
  119107. markers were dangling from our just-taken node. Dangle them
  119108. from our *new* node. */
  119109. for(j=length+1;j<33;j++)
  119110. if((marker[j]>>1) == entry){
  119111. entry=marker[j];
  119112. marker[j]=marker[j-1]<<1;
  119113. }else
  119114. break;
  119115. }else
  119116. if(sparsecount==0)count++;
  119117. }
  119118. /* bitreverse the words because our bitwise packer/unpacker is LSb
  119119. endian */
  119120. for(i=0,count=0;i<n;i++){
  119121. ogg_uint32_t temp=0;
  119122. for(j=0;j<l[i];j++){
  119123. temp<<=1;
  119124. temp|=(r[count]>>j)&1;
  119125. }
  119126. if(sparsecount){
  119127. if(l[i])
  119128. r[count++]=temp;
  119129. }else
  119130. r[count++]=temp;
  119131. }
  119132. return(r);
  119133. }
  119134. /* there might be a straightforward one-line way to do the below
  119135. that's portable and totally safe against roundoff, but I haven't
  119136. thought of it. Therefore, we opt on the side of caution */
  119137. long _book_maptype1_quantvals(const static_codebook *b){
  119138. long vals=floor(pow((float)b->entries,1.f/b->dim));
  119139. /* the above *should* be reliable, but we'll not assume that FP is
  119140. ever reliable when bitstream sync is at stake; verify via integer
  119141. means that vals really is the greatest value of dim for which
  119142. vals^b->bim <= b->entries */
  119143. /* treat the above as an initial guess */
  119144. while(1){
  119145. long acc=1;
  119146. long acc1=1;
  119147. int i;
  119148. for(i=0;i<b->dim;i++){
  119149. acc*=vals;
  119150. acc1*=vals+1;
  119151. }
  119152. if(acc<=b->entries && acc1>b->entries){
  119153. return(vals);
  119154. }else{
  119155. if(acc>b->entries){
  119156. vals--;
  119157. }else{
  119158. vals++;
  119159. }
  119160. }
  119161. }
  119162. }
  119163. /* unpack the quantized list of values for encode/decode ***********/
  119164. /* we need to deal with two map types: in map type 1, the values are
  119165. generated algorithmically (each column of the vector counts through
  119166. the values in the quant vector). in map type 2, all the values came
  119167. in in an explicit list. Both value lists must be unpacked */
  119168. float *_book_unquantize(const static_codebook *b,int n,int *sparsemap){
  119169. long j,k,count=0;
  119170. if(b->maptype==1 || b->maptype==2){
  119171. int quantvals;
  119172. float mindel=_float32_unpack(b->q_min);
  119173. float delta=_float32_unpack(b->q_delta);
  119174. float *r=(float*)_ogg_calloc(n*b->dim,sizeof(*r));
  119175. /* maptype 1 and 2 both use a quantized value vector, but
  119176. different sizes */
  119177. switch(b->maptype){
  119178. case 1:
  119179. /* most of the time, entries%dimensions == 0, but we need to be
  119180. well defined. We define that the possible vales at each
  119181. scalar is values == entries/dim. If entries%dim != 0, we'll
  119182. have 'too few' values (values*dim<entries), which means that
  119183. we'll have 'left over' entries; left over entries use zeroed
  119184. values (and are wasted). So don't generate codebooks like
  119185. that */
  119186. quantvals=_book_maptype1_quantvals(b);
  119187. for(j=0;j<b->entries;j++){
  119188. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119189. float last=0.f;
  119190. int indexdiv=1;
  119191. for(k=0;k<b->dim;k++){
  119192. int index= (j/indexdiv)%quantvals;
  119193. float val=b->quantlist[index];
  119194. val=fabs(val)*delta+mindel+last;
  119195. if(b->q_sequencep)last=val;
  119196. if(sparsemap)
  119197. r[sparsemap[count]*b->dim+k]=val;
  119198. else
  119199. r[count*b->dim+k]=val;
  119200. indexdiv*=quantvals;
  119201. }
  119202. count++;
  119203. }
  119204. }
  119205. break;
  119206. case 2:
  119207. for(j=0;j<b->entries;j++){
  119208. if((sparsemap && b->lengthlist[j]) || !sparsemap){
  119209. float last=0.f;
  119210. for(k=0;k<b->dim;k++){
  119211. float val=b->quantlist[j*b->dim+k];
  119212. val=fabs(val)*delta+mindel+last;
  119213. if(b->q_sequencep)last=val;
  119214. if(sparsemap)
  119215. r[sparsemap[count]*b->dim+k]=val;
  119216. else
  119217. r[count*b->dim+k]=val;
  119218. }
  119219. count++;
  119220. }
  119221. }
  119222. break;
  119223. }
  119224. return(r);
  119225. }
  119226. return(NULL);
  119227. }
  119228. void vorbis_staticbook_clear(static_codebook *b){
  119229. if(b->allocedp){
  119230. if(b->quantlist)_ogg_free(b->quantlist);
  119231. if(b->lengthlist)_ogg_free(b->lengthlist);
  119232. if(b->nearest_tree){
  119233. _ogg_free(b->nearest_tree->ptr0);
  119234. _ogg_free(b->nearest_tree->ptr1);
  119235. _ogg_free(b->nearest_tree->p);
  119236. _ogg_free(b->nearest_tree->q);
  119237. memset(b->nearest_tree,0,sizeof(*b->nearest_tree));
  119238. _ogg_free(b->nearest_tree);
  119239. }
  119240. if(b->thresh_tree){
  119241. _ogg_free(b->thresh_tree->quantthresh);
  119242. _ogg_free(b->thresh_tree->quantmap);
  119243. memset(b->thresh_tree,0,sizeof(*b->thresh_tree));
  119244. _ogg_free(b->thresh_tree);
  119245. }
  119246. memset(b,0,sizeof(*b));
  119247. }
  119248. }
  119249. void vorbis_staticbook_destroy(static_codebook *b){
  119250. if(b->allocedp){
  119251. vorbis_staticbook_clear(b);
  119252. _ogg_free(b);
  119253. }
  119254. }
  119255. void vorbis_book_clear(codebook *b){
  119256. /* static book is not cleared; we're likely called on the lookup and
  119257. the static codebook belongs to the info struct */
  119258. if(b->valuelist)_ogg_free(b->valuelist);
  119259. if(b->codelist)_ogg_free(b->codelist);
  119260. if(b->dec_index)_ogg_free(b->dec_index);
  119261. if(b->dec_codelengths)_ogg_free(b->dec_codelengths);
  119262. if(b->dec_firsttable)_ogg_free(b->dec_firsttable);
  119263. memset(b,0,sizeof(*b));
  119264. }
  119265. int vorbis_book_init_encode(codebook *c,const static_codebook *s){
  119266. memset(c,0,sizeof(*c));
  119267. c->c=s;
  119268. c->entries=s->entries;
  119269. c->used_entries=s->entries;
  119270. c->dim=s->dim;
  119271. c->codelist=_make_words(s->lengthlist,s->entries,0);
  119272. c->valuelist=_book_unquantize(s,s->entries,NULL);
  119273. return(0);
  119274. }
  119275. static int sort32a(const void *a,const void *b){
  119276. return ( **(ogg_uint32_t **)a>**(ogg_uint32_t **)b)-
  119277. ( **(ogg_uint32_t **)a<**(ogg_uint32_t **)b);
  119278. }
  119279. /* decode codebook arrangement is more heavily optimized than encode */
  119280. int vorbis_book_init_decode(codebook *c,const static_codebook *s){
  119281. int i,j,n=0,tabn;
  119282. int *sortindex;
  119283. memset(c,0,sizeof(*c));
  119284. /* count actually used entries */
  119285. for(i=0;i<s->entries;i++)
  119286. if(s->lengthlist[i]>0)
  119287. n++;
  119288. c->entries=s->entries;
  119289. c->used_entries=n;
  119290. c->dim=s->dim;
  119291. /* two different remappings go on here.
  119292. First, we collapse the likely sparse codebook down only to
  119293. actually represented values/words. This collapsing needs to be
  119294. indexed as map-valueless books are used to encode original entry
  119295. positions as integers.
  119296. Second, we reorder all vectors, including the entry index above,
  119297. by sorted bitreversed codeword to allow treeless decode. */
  119298. {
  119299. /* perform sort */
  119300. ogg_uint32_t *codes=_make_words(s->lengthlist,s->entries,c->used_entries);
  119301. ogg_uint32_t **codep=(ogg_uint32_t**)alloca(sizeof(*codep)*n);
  119302. if(codes==NULL)goto err_out;
  119303. for(i=0;i<n;i++){
  119304. codes[i]=ogg_bitreverse(codes[i]);
  119305. codep[i]=codes+i;
  119306. }
  119307. qsort(codep,n,sizeof(*codep),sort32a);
  119308. sortindex=(int*)alloca(n*sizeof(*sortindex));
  119309. c->codelist=(ogg_uint32_t*)_ogg_malloc(n*sizeof(*c->codelist));
  119310. /* the index is a reverse index */
  119311. for(i=0;i<n;i++){
  119312. int position=codep[i]-codes;
  119313. sortindex[position]=i;
  119314. }
  119315. for(i=0;i<n;i++)
  119316. c->codelist[sortindex[i]]=codes[i];
  119317. _ogg_free(codes);
  119318. }
  119319. c->valuelist=_book_unquantize(s,n,sortindex);
  119320. c->dec_index=(int*)_ogg_malloc(n*sizeof(*c->dec_index));
  119321. for(n=0,i=0;i<s->entries;i++)
  119322. if(s->lengthlist[i]>0)
  119323. c->dec_index[sortindex[n++]]=i;
  119324. c->dec_codelengths=(char*)_ogg_malloc(n*sizeof(*c->dec_codelengths));
  119325. for(n=0,i=0;i<s->entries;i++)
  119326. if(s->lengthlist[i]>0)
  119327. c->dec_codelengths[sortindex[n++]]=s->lengthlist[i];
  119328. c->dec_firsttablen=_ilog(c->used_entries)-4; /* this is magic */
  119329. if(c->dec_firsttablen<5)c->dec_firsttablen=5;
  119330. if(c->dec_firsttablen>8)c->dec_firsttablen=8;
  119331. tabn=1<<c->dec_firsttablen;
  119332. c->dec_firsttable=(ogg_uint32_t*)_ogg_calloc(tabn,sizeof(*c->dec_firsttable));
  119333. c->dec_maxlength=0;
  119334. for(i=0;i<n;i++){
  119335. if(c->dec_maxlength<c->dec_codelengths[i])
  119336. c->dec_maxlength=c->dec_codelengths[i];
  119337. if(c->dec_codelengths[i]<=c->dec_firsttablen){
  119338. ogg_uint32_t orig=ogg_bitreverse(c->codelist[i]);
  119339. for(j=0;j<(1<<(c->dec_firsttablen-c->dec_codelengths[i]));j++)
  119340. c->dec_firsttable[orig|(j<<c->dec_codelengths[i])]=i+1;
  119341. }
  119342. }
  119343. /* now fill in 'unused' entries in the firsttable with hi/lo search
  119344. hints for the non-direct-hits */
  119345. {
  119346. ogg_uint32_t mask=0xfffffffeUL<<(31-c->dec_firsttablen);
  119347. long lo=0,hi=0;
  119348. for(i=0;i<tabn;i++){
  119349. ogg_uint32_t word=i<<(32-c->dec_firsttablen);
  119350. if(c->dec_firsttable[ogg_bitreverse(word)]==0){
  119351. while((lo+1)<n && c->codelist[lo+1]<=word)lo++;
  119352. while( hi<n && word>=(c->codelist[hi]&mask))hi++;
  119353. /* we only actually have 15 bits per hint to play with here.
  119354. In order to overflow gracefully (nothing breaks, efficiency
  119355. just drops), encode as the difference from the extremes. */
  119356. {
  119357. unsigned long loval=lo;
  119358. unsigned long hival=n-hi;
  119359. if(loval>0x7fff)loval=0x7fff;
  119360. if(hival>0x7fff)hival=0x7fff;
  119361. c->dec_firsttable[ogg_bitreverse(word)]=
  119362. 0x80000000UL | (loval<<15) | hival;
  119363. }
  119364. }
  119365. }
  119366. }
  119367. return(0);
  119368. err_out:
  119369. vorbis_book_clear(c);
  119370. return(-1);
  119371. }
  119372. static float _dist(int el,float *ref, float *b,int step){
  119373. int i;
  119374. float acc=0.f;
  119375. for(i=0;i<el;i++){
  119376. float val=(ref[i]-b[i*step]);
  119377. acc+=val*val;
  119378. }
  119379. return(acc);
  119380. }
  119381. int _best(codebook *book, float *a, int step){
  119382. encode_aux_threshmatch *tt=book->c->thresh_tree;
  119383. #if 0
  119384. encode_aux_nearestmatch *nt=book->c->nearest_tree;
  119385. encode_aux_pigeonhole *pt=book->c->pigeon_tree;
  119386. #endif
  119387. int dim=book->dim;
  119388. int k,o;
  119389. /*int savebest=-1;
  119390. float saverr;*/
  119391. /* do we have a threshhold encode hint? */
  119392. if(tt){
  119393. int index=0,i;
  119394. /* find the quant val of each scalar */
  119395. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119396. i=tt->threshvals>>1;
  119397. if(a[o]<tt->quantthresh[i]){
  119398. for(;i>0;i--)
  119399. if(a[o]>=tt->quantthresh[i-1])
  119400. break;
  119401. }else{
  119402. for(i++;i<tt->threshvals-1;i++)
  119403. if(a[o]<tt->quantthresh[i])break;
  119404. }
  119405. index=(index*tt->quantvals)+tt->quantmap[i];
  119406. }
  119407. /* regular lattices are easy :-) */
  119408. if(book->c->lengthlist[index]>0) /* is this unused? If so, we'll
  119409. use a decision tree after all
  119410. and fall through*/
  119411. return(index);
  119412. }
  119413. #if 0
  119414. /* do we have a pigeonhole encode hint? */
  119415. if(pt){
  119416. const static_codebook *c=book->c;
  119417. int i,besti=-1;
  119418. float best=0.f;
  119419. int entry=0;
  119420. /* dealing with sequentialness is a pain in the ass */
  119421. if(c->q_sequencep){
  119422. int pv;
  119423. long mul=1;
  119424. float qlast=0;
  119425. for(k=0,o=0;k<dim;k++,o+=step){
  119426. pv=(int)((a[o]-qlast-pt->min)/pt->del);
  119427. if(pv<0 || pv>=pt->mapentries)break;
  119428. entry+=pt->pigeonmap[pv]*mul;
  119429. mul*=pt->quantvals;
  119430. qlast+=pv*pt->del+pt->min;
  119431. }
  119432. }else{
  119433. for(k=0,o=step*(dim-1);k<dim;k++,o-=step){
  119434. int pv=(int)((a[o]-pt->min)/pt->del);
  119435. if(pv<0 || pv>=pt->mapentries)break;
  119436. entry=entry*pt->quantvals+pt->pigeonmap[pv];
  119437. }
  119438. }
  119439. /* must be within the pigeonholable range; if we quant outside (or
  119440. in an entry that we define no list for), brute force it */
  119441. if(k==dim && pt->fitlength[entry]){
  119442. /* search the abbreviated list */
  119443. long *list=pt->fitlist+pt->fitmap[entry];
  119444. for(i=0;i<pt->fitlength[entry];i++){
  119445. float this=_dist(dim,book->valuelist+list[i]*dim,a,step);
  119446. if(besti==-1 || this<best){
  119447. best=this;
  119448. besti=list[i];
  119449. }
  119450. }
  119451. return(besti);
  119452. }
  119453. }
  119454. if(nt){
  119455. /* optimized using the decision tree */
  119456. while(1){
  119457. float c=0.f;
  119458. float *p=book->valuelist+nt->p[ptr];
  119459. float *q=book->valuelist+nt->q[ptr];
  119460. for(k=0,o=0;k<dim;k++,o+=step)
  119461. c+=(p[k]-q[k])*(a[o]-(p[k]+q[k])*.5);
  119462. if(c>0.f) /* in A */
  119463. ptr= -nt->ptr0[ptr];
  119464. else /* in B */
  119465. ptr= -nt->ptr1[ptr];
  119466. if(ptr<=0)break;
  119467. }
  119468. return(-ptr);
  119469. }
  119470. #endif
  119471. /* brute force it! */
  119472. {
  119473. const static_codebook *c=book->c;
  119474. int i,besti=-1;
  119475. float best=0.f;
  119476. float *e=book->valuelist;
  119477. for(i=0;i<book->entries;i++){
  119478. if(c->lengthlist[i]>0){
  119479. float thisx=_dist(dim,e,a,step);
  119480. if(besti==-1 || thisx<best){
  119481. best=thisx;
  119482. besti=i;
  119483. }
  119484. }
  119485. e+=dim;
  119486. }
  119487. /*if(savebest!=-1 && savebest!=besti){
  119488. fprintf(stderr,"brute force/pigeonhole disagreement:\n"
  119489. "original:");
  119490. for(i=0;i<dim*step;i+=step)fprintf(stderr,"%g,",a[i]);
  119491. fprintf(stderr,"\n"
  119492. "pigeonhole (entry %d, err %g):",savebest,saverr);
  119493. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119494. (book->valuelist+savebest*dim)[i]);
  119495. fprintf(stderr,"\n"
  119496. "bruteforce (entry %d, err %g):",besti,best);
  119497. for(i=0;i<dim;i++)fprintf(stderr,"%g,",
  119498. (book->valuelist+besti*dim)[i]);
  119499. fprintf(stderr,"\n");
  119500. }*/
  119501. return(besti);
  119502. }
  119503. }
  119504. long vorbis_book_codeword(codebook *book,int entry){
  119505. if(book->c) /* only use with encode; decode optimizations are
  119506. allowed to break this */
  119507. return book->codelist[entry];
  119508. return -1;
  119509. }
  119510. long vorbis_book_codelen(codebook *book,int entry){
  119511. if(book->c) /* only use with encode; decode optimizations are
  119512. allowed to break this */
  119513. return book->c->lengthlist[entry];
  119514. return -1;
  119515. }
  119516. #ifdef _V_SELFTEST
  119517. /* Unit tests of the dequantizer; this stuff will be OK
  119518. cross-platform, I simply want to be sure that special mapping cases
  119519. actually work properly; a bug could go unnoticed for a while */
  119520. #include <stdio.h>
  119521. /* cases:
  119522. no mapping
  119523. full, explicit mapping
  119524. algorithmic mapping
  119525. nonsequential
  119526. sequential
  119527. */
  119528. static long full_quantlist1[]={0,1,2,3, 4,5,6,7, 8,3,6,1};
  119529. static long partial_quantlist1[]={0,7,2};
  119530. /* no mapping */
  119531. static_codebook test1={
  119532. 4,16,
  119533. NULL,
  119534. 0,
  119535. 0,0,0,0,
  119536. NULL,
  119537. NULL,NULL
  119538. };
  119539. static float *test1_result=NULL;
  119540. /* linear, full mapping, nonsequential */
  119541. static_codebook test2={
  119542. 4,3,
  119543. NULL,
  119544. 2,
  119545. -533200896,1611661312,4,0,
  119546. full_quantlist1,
  119547. NULL,NULL
  119548. };
  119549. static float test2_result[]={-3,-2,-1,0, 1,2,3,4, 5,0,3,-2};
  119550. /* linear, full mapping, sequential */
  119551. static_codebook test3={
  119552. 4,3,
  119553. NULL,
  119554. 2,
  119555. -533200896,1611661312,4,1,
  119556. full_quantlist1,
  119557. NULL,NULL
  119558. };
  119559. static float test3_result[]={-3,-5,-6,-6, 1,3,6,10, 5,5,8,6};
  119560. /* linear, algorithmic mapping, nonsequential */
  119561. static_codebook test4={
  119562. 3,27,
  119563. NULL,
  119564. 1,
  119565. -533200896,1611661312,4,0,
  119566. partial_quantlist1,
  119567. NULL,NULL
  119568. };
  119569. static float test4_result[]={-3,-3,-3, 4,-3,-3, -1,-3,-3,
  119570. -3, 4,-3, 4, 4,-3, -1, 4,-3,
  119571. -3,-1,-3, 4,-1,-3, -1,-1,-3,
  119572. -3,-3, 4, 4,-3, 4, -1,-3, 4,
  119573. -3, 4, 4, 4, 4, 4, -1, 4, 4,
  119574. -3,-1, 4, 4,-1, 4, -1,-1, 4,
  119575. -3,-3,-1, 4,-3,-1, -1,-3,-1,
  119576. -3, 4,-1, 4, 4,-1, -1, 4,-1,
  119577. -3,-1,-1, 4,-1,-1, -1,-1,-1};
  119578. /* linear, algorithmic mapping, sequential */
  119579. static_codebook test5={
  119580. 3,27,
  119581. NULL,
  119582. 1,
  119583. -533200896,1611661312,4,1,
  119584. partial_quantlist1,
  119585. NULL,NULL
  119586. };
  119587. static float test5_result[]={-3,-6,-9, 4, 1,-2, -1,-4,-7,
  119588. -3, 1,-2, 4, 8, 5, -1, 3, 0,
  119589. -3,-4,-7, 4, 3, 0, -1,-2,-5,
  119590. -3,-6,-2, 4, 1, 5, -1,-4, 0,
  119591. -3, 1, 5, 4, 8,12, -1, 3, 7,
  119592. -3,-4, 0, 4, 3, 7, -1,-2, 2,
  119593. -3,-6,-7, 4, 1, 0, -1,-4,-5,
  119594. -3, 1, 0, 4, 8, 7, -1, 3, 2,
  119595. -3,-4,-5, 4, 3, 2, -1,-2,-3};
  119596. void run_test(static_codebook *b,float *comp){
  119597. float *out=_book_unquantize(b,b->entries,NULL);
  119598. int i;
  119599. if(comp){
  119600. if(!out){
  119601. fprintf(stderr,"_book_unquantize incorrectly returned NULL\n");
  119602. exit(1);
  119603. }
  119604. for(i=0;i<b->entries*b->dim;i++)
  119605. if(fabs(out[i]-comp[i])>.0001){
  119606. fprintf(stderr,"disagreement in unquantized and reference data:\n"
  119607. "position %d, %g != %g\n",i,out[i],comp[i]);
  119608. exit(1);
  119609. }
  119610. }else{
  119611. if(out){
  119612. fprintf(stderr,"_book_unquantize returned a value array: \n"
  119613. " correct result should have been NULL\n");
  119614. exit(1);
  119615. }
  119616. }
  119617. }
  119618. int main(){
  119619. /* run the nine dequant tests, and compare to the hand-rolled results */
  119620. fprintf(stderr,"Dequant test 1... ");
  119621. run_test(&test1,test1_result);
  119622. fprintf(stderr,"OK\nDequant test 2... ");
  119623. run_test(&test2,test2_result);
  119624. fprintf(stderr,"OK\nDequant test 3... ");
  119625. run_test(&test3,test3_result);
  119626. fprintf(stderr,"OK\nDequant test 4... ");
  119627. run_test(&test4,test4_result);
  119628. fprintf(stderr,"OK\nDequant test 5... ");
  119629. run_test(&test5,test5_result);
  119630. fprintf(stderr,"OK\n\n");
  119631. return(0);
  119632. }
  119633. #endif
  119634. #endif
  119635. /********* End of inlined file: sharedbook.c *********/
  119636. /********* Start of inlined file: smallft.c *********/
  119637. /* FFT implementation from OggSquish, minus cosine transforms,
  119638. * minus all but radix 2/4 case. In Vorbis we only need this
  119639. * cut-down version.
  119640. *
  119641. * To do more than just power-of-two sized vectors, see the full
  119642. * version I wrote for NetLib.
  119643. *
  119644. * Note that the packing is a little strange; rather than the FFT r/i
  119645. * packing following R_0, I_n, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1,
  119646. * it follows R_0, R_1, I_1, R_2, I_2 ... R_n-1, I_n-1, I_n like the
  119647. * FORTRAN version
  119648. */
  119649. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  119650. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  119651. // tasks..
  119652. /********* Start of inlined file: juce_Config.h *********/
  119653. #ifndef __JUCE_CONFIG_JUCEHEADER__
  119654. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  119655. /*
  119656. This file contains macros that enable/disable various JUCE features.
  119657. */
  119658. /** The name of the namespace that all Juce classes and functions will be
  119659. put inside. If this is not defined, no namespace will be used.
  119660. */
  119661. #ifndef JUCE_NAMESPACE
  119662. #define JUCE_NAMESPACE juce
  119663. #endif
  119664. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  119665. but if you define this value, you can override this can force it to be true or
  119666. false.
  119667. */
  119668. #ifndef JUCE_FORCE_DEBUG
  119669. //#define JUCE_FORCE_DEBUG 1
  119670. #endif
  119671. /** If this flag is enabled, the the jassert and jassertfalse macros will
  119672. always use Logger::writeToLog() to write a message when an assertion happens.
  119673. Enabling it will also leave this turned on in release builds. When it's disabled,
  119674. however, the jassert and jassertfalse macros will not be compiled in a
  119675. release build.
  119676. @see jassert, jassertfalse, Logger
  119677. */
  119678. #ifndef JUCE_LOG_ASSERTIONS
  119679. // #define JUCE_LOG_ASSERTIONS 1
  119680. #endif
  119681. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  119682. which the ASIOAudioIODevice class can't be built. See the comments in the
  119683. ASIOAudioIODevice class's header file for more info about this.
  119684. (This only affects a Win32 build)
  119685. */
  119686. #ifndef JUCE_ASIO
  119687. #define JUCE_ASIO 1
  119688. #endif
  119689. /** Comment out this macro to disable building of ALSA device support on Linux.
  119690. */
  119691. #ifndef JUCE_ALSA
  119692. #define JUCE_ALSA 1
  119693. #endif
  119694. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  119695. have the SDK installed.
  119696. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  119697. classes will be unavailable.
  119698. On Windows, if you enable this, you'll need to have the QuickTime SDK
  119699. installed, and its header files will need to be on your include path.
  119700. */
  119701. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  119702. #define JUCE_QUICKTIME 1
  119703. #endif
  119704. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  119705. have the appropriate headers and libraries available. If it's not enabled, the
  119706. OpenGLComponent class will be unavailable.
  119707. */
  119708. #ifndef JUCE_OPENGL
  119709. #define JUCE_OPENGL 1
  119710. #endif
  119711. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  119712. If you're not going to need either of these formats, turn off the flags to
  119713. avoid bloating your codebase with them.
  119714. */
  119715. #ifndef JUCE_USE_FLAC
  119716. #define JUCE_USE_FLAC 1
  119717. #endif
  119718. #ifndef JUCE_USE_OGGVORBIS
  119719. #define JUCE_USE_OGGVORBIS 1
  119720. #endif
  119721. /** This flag lets you enable support for CD-burning. You might want to disable
  119722. it to build without the MS SDK under windows.
  119723. */
  119724. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  119725. #define JUCE_USE_CDBURNER 1
  119726. #endif
  119727. /** Enabling this macro means that all regions that get repainted will have a coloured
  119728. line drawn around them.
  119729. This is handy if you're trying to optimise drawing, because it lets you easily see
  119730. when anything is being repainted unnecessarily.
  119731. */
  119732. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  119733. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  119734. #endif
  119735. /** Enable this under Linux to use Xinerama for multi-monitor support.
  119736. */
  119737. #ifndef JUCE_USE_XINERAMA
  119738. #define JUCE_USE_XINERAMA 1
  119739. #endif
  119740. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  119741. */
  119742. #ifndef JUCE_USE_XSHM
  119743. #define JUCE_USE_XSHM 1
  119744. #endif
  119745. /** Enabling this builds support for VST audio plugins.
  119746. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  119747. */
  119748. #ifndef JUCE_PLUGINHOST_VST
  119749. // #define JUCE_PLUGINHOST_VST 1
  119750. #endif
  119751. /** Enabling this builds support for AudioUnit audio plugins.
  119752. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  119753. */
  119754. #ifndef JUCE_PLUGINHOST_AU
  119755. // #define JUCE_PLUGINHOST_AU 1
  119756. #endif
  119757. /** Disabling this will avoid linking to any UI code. This is handy for
  119758. writing command-line utilities, e.g. on linux boxes which don't have some
  119759. of the UI libraries installed.
  119760. (On mac and windows, this won't generally make much difference to the build).
  119761. */
  119762. #ifndef JUCE_BUILD_GUI_CLASSES
  119763. #define JUCE_BUILD_GUI_CLASSES 1
  119764. #endif
  119765. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  119766. */
  119767. #ifndef JUCE_WEB_BROWSER
  119768. #define JUCE_WEB_BROWSER 1
  119769. #endif
  119770. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  119771. codebase - you might need to use this if you're linking to some of these libraries
  119772. yourself.
  119773. */
  119774. #ifndef JUCE_INCLUDE_ZLIB_CODE
  119775. #define JUCE_INCLUDE_ZLIB_CODE 1
  119776. #endif
  119777. #ifndef JUCE_INCLUDE_FLAC_CODE
  119778. #define JUCE_INCLUDE_FLAC_CODE 1
  119779. #endif
  119780. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  119781. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  119782. #endif
  119783. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  119784. #define JUCE_INCLUDE_PNGLIB_CODE 1
  119785. #endif
  119786. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  119787. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  119788. #endif
  119789. /** Enable this to add extra memory-leak info to the new and delete operators.
  119790. (Currently, this only affects Windows builds in debug mode).
  119791. */
  119792. #ifndef JUCE_CHECK_MEMORY_LEAKS
  119793. #define JUCE_CHECK_MEMORY_LEAKS 1
  119794. #endif
  119795. /** Enable this to turn on juce's internal catching of exceptions.
  119796. Turning it off will avoid any exception catching. With it on, all exceptions
  119797. are passed to the JUCEApplication::unhandledException() callback for logging.
  119798. */
  119799. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  119800. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  119801. #endif
  119802. /** If this macro is set, the Juce String class will use unicode as its
  119803. internal representation. If it isn't set, it'll use ANSI.
  119804. */
  119805. #ifndef JUCE_STRINGS_ARE_UNICODE
  119806. #define JUCE_STRINGS_ARE_UNICODE 1
  119807. #endif
  119808. #endif
  119809. /********* End of inlined file: juce_Config.h *********/
  119810. #ifdef _MSC_VER
  119811. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  119812. #endif
  119813. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  119814. #if JUCE_USE_OGGVORBIS
  119815. #include <stdlib.h>
  119816. #include <string.h>
  119817. #include <math.h>
  119818. static void drfti1(int n, float *wa, int *ifac){
  119819. static int ntryh[4] = { 4,2,3,5 };
  119820. static float tpi = 6.28318530717958648f;
  119821. float arg,argh,argld,fi;
  119822. int ntry=0,i,j=-1;
  119823. int k1, l1, l2, ib;
  119824. int ld, ii, ip, is, nq, nr;
  119825. int ido, ipm, nfm1;
  119826. int nl=n;
  119827. int nf=0;
  119828. L101:
  119829. j++;
  119830. if (j < 4)
  119831. ntry=ntryh[j];
  119832. else
  119833. ntry+=2;
  119834. L104:
  119835. nq=nl/ntry;
  119836. nr=nl-ntry*nq;
  119837. if (nr!=0) goto L101;
  119838. nf++;
  119839. ifac[nf+1]=ntry;
  119840. nl=nq;
  119841. if(ntry!=2)goto L107;
  119842. if(nf==1)goto L107;
  119843. for (i=1;i<nf;i++){
  119844. ib=nf-i+1;
  119845. ifac[ib+1]=ifac[ib];
  119846. }
  119847. ifac[2] = 2;
  119848. L107:
  119849. if(nl!=1)goto L104;
  119850. ifac[0]=n;
  119851. ifac[1]=nf;
  119852. argh=tpi/n;
  119853. is=0;
  119854. nfm1=nf-1;
  119855. l1=1;
  119856. if(nfm1==0)return;
  119857. for (k1=0;k1<nfm1;k1++){
  119858. ip=ifac[k1+2];
  119859. ld=0;
  119860. l2=l1*ip;
  119861. ido=n/l2;
  119862. ipm=ip-1;
  119863. for (j=0;j<ipm;j++){
  119864. ld+=l1;
  119865. i=is;
  119866. argld=(float)ld*argh;
  119867. fi=0.f;
  119868. for (ii=2;ii<ido;ii+=2){
  119869. fi+=1.f;
  119870. arg=fi*argld;
  119871. wa[i++]=cos(arg);
  119872. wa[i++]=sin(arg);
  119873. }
  119874. is+=ido;
  119875. }
  119876. l1=l2;
  119877. }
  119878. }
  119879. static void fdrffti(int n, float *wsave, int *ifac){
  119880. if (n == 1) return;
  119881. drfti1(n, wsave+n, ifac);
  119882. }
  119883. static void dradf2(int ido,int l1,float *cc,float *ch,float *wa1){
  119884. int i,k;
  119885. float ti2,tr2;
  119886. int t0,t1,t2,t3,t4,t5,t6;
  119887. t1=0;
  119888. t0=(t2=l1*ido);
  119889. t3=ido<<1;
  119890. for(k=0;k<l1;k++){
  119891. ch[t1<<1]=cc[t1]+cc[t2];
  119892. ch[(t1<<1)+t3-1]=cc[t1]-cc[t2];
  119893. t1+=ido;
  119894. t2+=ido;
  119895. }
  119896. if(ido<2)return;
  119897. if(ido==2)goto L105;
  119898. t1=0;
  119899. t2=t0;
  119900. for(k=0;k<l1;k++){
  119901. t3=t2;
  119902. t4=(t1<<1)+(ido<<1);
  119903. t5=t1;
  119904. t6=t1+t1;
  119905. for(i=2;i<ido;i+=2){
  119906. t3+=2;
  119907. t4-=2;
  119908. t5+=2;
  119909. t6+=2;
  119910. tr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119911. ti2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119912. ch[t6]=cc[t5]+ti2;
  119913. ch[t4]=ti2-cc[t5];
  119914. ch[t6-1]=cc[t5-1]+tr2;
  119915. ch[t4-1]=cc[t5-1]-tr2;
  119916. }
  119917. t1+=ido;
  119918. t2+=ido;
  119919. }
  119920. if(ido%2==1)return;
  119921. L105:
  119922. t3=(t2=(t1=ido)-1);
  119923. t2+=t0;
  119924. for(k=0;k<l1;k++){
  119925. ch[t1]=-cc[t2];
  119926. ch[t1-1]=cc[t3];
  119927. t1+=ido<<1;
  119928. t2+=ido;
  119929. t3+=ido;
  119930. }
  119931. }
  119932. static void dradf4(int ido,int l1,float *cc,float *ch,float *wa1,
  119933. float *wa2,float *wa3){
  119934. static float hsqt2 = .70710678118654752f;
  119935. int i,k,t0,t1,t2,t3,t4,t5,t6;
  119936. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  119937. t0=l1*ido;
  119938. t1=t0;
  119939. t4=t1<<1;
  119940. t2=t1+(t1<<1);
  119941. t3=0;
  119942. for(k=0;k<l1;k++){
  119943. tr1=cc[t1]+cc[t2];
  119944. tr2=cc[t3]+cc[t4];
  119945. ch[t5=t3<<2]=tr1+tr2;
  119946. ch[(ido<<2)+t5-1]=tr2-tr1;
  119947. ch[(t5+=(ido<<1))-1]=cc[t3]-cc[t4];
  119948. ch[t5]=cc[t2]-cc[t1];
  119949. t1+=ido;
  119950. t2+=ido;
  119951. t3+=ido;
  119952. t4+=ido;
  119953. }
  119954. if(ido<2)return;
  119955. if(ido==2)goto L105;
  119956. t1=0;
  119957. for(k=0;k<l1;k++){
  119958. t2=t1;
  119959. t4=t1<<2;
  119960. t5=(t6=ido<<1)+t4;
  119961. for(i=2;i<ido;i+=2){
  119962. t3=(t2+=2);
  119963. t4+=2;
  119964. t5-=2;
  119965. t3+=t0;
  119966. cr2=wa1[i-2]*cc[t3-1]+wa1[i-1]*cc[t3];
  119967. ci2=wa1[i-2]*cc[t3]-wa1[i-1]*cc[t3-1];
  119968. t3+=t0;
  119969. cr3=wa2[i-2]*cc[t3-1]+wa2[i-1]*cc[t3];
  119970. ci3=wa2[i-2]*cc[t3]-wa2[i-1]*cc[t3-1];
  119971. t3+=t0;
  119972. cr4=wa3[i-2]*cc[t3-1]+wa3[i-1]*cc[t3];
  119973. ci4=wa3[i-2]*cc[t3]-wa3[i-1]*cc[t3-1];
  119974. tr1=cr2+cr4;
  119975. tr4=cr4-cr2;
  119976. ti1=ci2+ci4;
  119977. ti4=ci2-ci4;
  119978. ti2=cc[t2]+ci3;
  119979. ti3=cc[t2]-ci3;
  119980. tr2=cc[t2-1]+cr3;
  119981. tr3=cc[t2-1]-cr3;
  119982. ch[t4-1]=tr1+tr2;
  119983. ch[t4]=ti1+ti2;
  119984. ch[t5-1]=tr3-ti4;
  119985. ch[t5]=tr4-ti3;
  119986. ch[t4+t6-1]=ti4+tr3;
  119987. ch[t4+t6]=tr4+ti3;
  119988. ch[t5+t6-1]=tr2-tr1;
  119989. ch[t5+t6]=ti1-ti2;
  119990. }
  119991. t1+=ido;
  119992. }
  119993. if(ido&1)return;
  119994. L105:
  119995. t2=(t1=t0+ido-1)+(t0<<1);
  119996. t3=ido<<2;
  119997. t4=ido;
  119998. t5=ido<<1;
  119999. t6=ido;
  120000. for(k=0;k<l1;k++){
  120001. ti1=-hsqt2*(cc[t1]+cc[t2]);
  120002. tr1=hsqt2*(cc[t1]-cc[t2]);
  120003. ch[t4-1]=tr1+cc[t6-1];
  120004. ch[t4+t5-1]=cc[t6-1]-tr1;
  120005. ch[t4]=ti1-cc[t1+t0];
  120006. ch[t4+t5]=ti1+cc[t1+t0];
  120007. t1+=ido;
  120008. t2+=ido;
  120009. t4+=t3;
  120010. t6+=ido;
  120011. }
  120012. }
  120013. static void dradfg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120014. float *c2,float *ch,float *ch2,float *wa){
  120015. static float tpi=6.283185307179586f;
  120016. int idij,ipph,i,j,k,l,ic,ik,is;
  120017. int t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120018. float dc2,ai1,ai2,ar1,ar2,ds2;
  120019. int nbd;
  120020. float dcp,arg,dsp,ar1h,ar2h;
  120021. int idp2,ipp2;
  120022. arg=tpi/(float)ip;
  120023. dcp=cos(arg);
  120024. dsp=sin(arg);
  120025. ipph=(ip+1)>>1;
  120026. ipp2=ip;
  120027. idp2=ido;
  120028. nbd=(ido-1)>>1;
  120029. t0=l1*ido;
  120030. t10=ip*ido;
  120031. if(ido==1)goto L119;
  120032. for(ik=0;ik<idl1;ik++)ch2[ik]=c2[ik];
  120033. t1=0;
  120034. for(j=1;j<ip;j++){
  120035. t1+=t0;
  120036. t2=t1;
  120037. for(k=0;k<l1;k++){
  120038. ch[t2]=c1[t2];
  120039. t2+=ido;
  120040. }
  120041. }
  120042. is=-ido;
  120043. t1=0;
  120044. if(nbd>l1){
  120045. for(j=1;j<ip;j++){
  120046. t1+=t0;
  120047. is+=ido;
  120048. t2= -ido+t1;
  120049. for(k=0;k<l1;k++){
  120050. idij=is-1;
  120051. t2+=ido;
  120052. t3=t2;
  120053. for(i=2;i<ido;i+=2){
  120054. idij+=2;
  120055. t3+=2;
  120056. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  120057. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  120058. }
  120059. }
  120060. }
  120061. }else{
  120062. for(j=1;j<ip;j++){
  120063. is+=ido;
  120064. idij=is-1;
  120065. t1+=t0;
  120066. t2=t1;
  120067. for(i=2;i<ido;i+=2){
  120068. idij+=2;
  120069. t2+=2;
  120070. t3=t2;
  120071. for(k=0;k<l1;k++){
  120072. ch[t3-1]=wa[idij-1]*c1[t3-1]+wa[idij]*c1[t3];
  120073. ch[t3]=wa[idij-1]*c1[t3]-wa[idij]*c1[t3-1];
  120074. t3+=ido;
  120075. }
  120076. }
  120077. }
  120078. }
  120079. t1=0;
  120080. t2=ipp2*t0;
  120081. if(nbd<l1){
  120082. for(j=1;j<ipph;j++){
  120083. t1+=t0;
  120084. t2-=t0;
  120085. t3=t1;
  120086. t4=t2;
  120087. for(i=2;i<ido;i+=2){
  120088. t3+=2;
  120089. t4+=2;
  120090. t5=t3-ido;
  120091. t6=t4-ido;
  120092. for(k=0;k<l1;k++){
  120093. t5+=ido;
  120094. t6+=ido;
  120095. c1[t5-1]=ch[t5-1]+ch[t6-1];
  120096. c1[t6-1]=ch[t5]-ch[t6];
  120097. c1[t5]=ch[t5]+ch[t6];
  120098. c1[t6]=ch[t6-1]-ch[t5-1];
  120099. }
  120100. }
  120101. }
  120102. }else{
  120103. for(j=1;j<ipph;j++){
  120104. t1+=t0;
  120105. t2-=t0;
  120106. t3=t1;
  120107. t4=t2;
  120108. for(k=0;k<l1;k++){
  120109. t5=t3;
  120110. t6=t4;
  120111. for(i=2;i<ido;i+=2){
  120112. t5+=2;
  120113. t6+=2;
  120114. c1[t5-1]=ch[t5-1]+ch[t6-1];
  120115. c1[t6-1]=ch[t5]-ch[t6];
  120116. c1[t5]=ch[t5]+ch[t6];
  120117. c1[t6]=ch[t6-1]-ch[t5-1];
  120118. }
  120119. t3+=ido;
  120120. t4+=ido;
  120121. }
  120122. }
  120123. }
  120124. L119:
  120125. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120126. t1=0;
  120127. t2=ipp2*idl1;
  120128. for(j=1;j<ipph;j++){
  120129. t1+=t0;
  120130. t2-=t0;
  120131. t3=t1-ido;
  120132. t4=t2-ido;
  120133. for(k=0;k<l1;k++){
  120134. t3+=ido;
  120135. t4+=ido;
  120136. c1[t3]=ch[t3]+ch[t4];
  120137. c1[t4]=ch[t4]-ch[t3];
  120138. }
  120139. }
  120140. ar1=1.f;
  120141. ai1=0.f;
  120142. t1=0;
  120143. t2=ipp2*idl1;
  120144. t3=(ip-1)*idl1;
  120145. for(l=1;l<ipph;l++){
  120146. t1+=idl1;
  120147. t2-=idl1;
  120148. ar1h=dcp*ar1-dsp*ai1;
  120149. ai1=dcp*ai1+dsp*ar1;
  120150. ar1=ar1h;
  120151. t4=t1;
  120152. t5=t2;
  120153. t6=t3;
  120154. t7=idl1;
  120155. for(ik=0;ik<idl1;ik++){
  120156. ch2[t4++]=c2[ik]+ar1*c2[t7++];
  120157. ch2[t5++]=ai1*c2[t6++];
  120158. }
  120159. dc2=ar1;
  120160. ds2=ai1;
  120161. ar2=ar1;
  120162. ai2=ai1;
  120163. t4=idl1;
  120164. t5=(ipp2-1)*idl1;
  120165. for(j=2;j<ipph;j++){
  120166. t4+=idl1;
  120167. t5-=idl1;
  120168. ar2h=dc2*ar2-ds2*ai2;
  120169. ai2=dc2*ai2+ds2*ar2;
  120170. ar2=ar2h;
  120171. t6=t1;
  120172. t7=t2;
  120173. t8=t4;
  120174. t9=t5;
  120175. for(ik=0;ik<idl1;ik++){
  120176. ch2[t6++]+=ar2*c2[t8++];
  120177. ch2[t7++]+=ai2*c2[t9++];
  120178. }
  120179. }
  120180. }
  120181. t1=0;
  120182. for(j=1;j<ipph;j++){
  120183. t1+=idl1;
  120184. t2=t1;
  120185. for(ik=0;ik<idl1;ik++)ch2[ik]+=c2[t2++];
  120186. }
  120187. if(ido<l1)goto L132;
  120188. t1=0;
  120189. t2=0;
  120190. for(k=0;k<l1;k++){
  120191. t3=t1;
  120192. t4=t2;
  120193. for(i=0;i<ido;i++)cc[t4++]=ch[t3++];
  120194. t1+=ido;
  120195. t2+=t10;
  120196. }
  120197. goto L135;
  120198. L132:
  120199. for(i=0;i<ido;i++){
  120200. t1=i;
  120201. t2=i;
  120202. for(k=0;k<l1;k++){
  120203. cc[t2]=ch[t1];
  120204. t1+=ido;
  120205. t2+=t10;
  120206. }
  120207. }
  120208. L135:
  120209. t1=0;
  120210. t2=ido<<1;
  120211. t3=0;
  120212. t4=ipp2*t0;
  120213. for(j=1;j<ipph;j++){
  120214. t1+=t2;
  120215. t3+=t0;
  120216. t4-=t0;
  120217. t5=t1;
  120218. t6=t3;
  120219. t7=t4;
  120220. for(k=0;k<l1;k++){
  120221. cc[t5-1]=ch[t6];
  120222. cc[t5]=ch[t7];
  120223. t5+=t10;
  120224. t6+=ido;
  120225. t7+=ido;
  120226. }
  120227. }
  120228. if(ido==1)return;
  120229. if(nbd<l1)goto L141;
  120230. t1=-ido;
  120231. t3=0;
  120232. t4=0;
  120233. t5=ipp2*t0;
  120234. for(j=1;j<ipph;j++){
  120235. t1+=t2;
  120236. t3+=t2;
  120237. t4+=t0;
  120238. t5-=t0;
  120239. t6=t1;
  120240. t7=t3;
  120241. t8=t4;
  120242. t9=t5;
  120243. for(k=0;k<l1;k++){
  120244. for(i=2;i<ido;i+=2){
  120245. ic=idp2-i;
  120246. cc[i+t7-1]=ch[i+t8-1]+ch[i+t9-1];
  120247. cc[ic+t6-1]=ch[i+t8-1]-ch[i+t9-1];
  120248. cc[i+t7]=ch[i+t8]+ch[i+t9];
  120249. cc[ic+t6]=ch[i+t9]-ch[i+t8];
  120250. }
  120251. t6+=t10;
  120252. t7+=t10;
  120253. t8+=ido;
  120254. t9+=ido;
  120255. }
  120256. }
  120257. return;
  120258. L141:
  120259. t1=-ido;
  120260. t3=0;
  120261. t4=0;
  120262. t5=ipp2*t0;
  120263. for(j=1;j<ipph;j++){
  120264. t1+=t2;
  120265. t3+=t2;
  120266. t4+=t0;
  120267. t5-=t0;
  120268. for(i=2;i<ido;i+=2){
  120269. t6=idp2+t1-i;
  120270. t7=i+t3;
  120271. t8=i+t4;
  120272. t9=i+t5;
  120273. for(k=0;k<l1;k++){
  120274. cc[t7-1]=ch[t8-1]+ch[t9-1];
  120275. cc[t6-1]=ch[t8-1]-ch[t9-1];
  120276. cc[t7]=ch[t8]+ch[t9];
  120277. cc[t6]=ch[t9]-ch[t8];
  120278. t6+=t10;
  120279. t7+=t10;
  120280. t8+=ido;
  120281. t9+=ido;
  120282. }
  120283. }
  120284. }
  120285. }
  120286. static void drftf1(int n,float *c,float *ch,float *wa,int *ifac){
  120287. int i,k1,l1,l2;
  120288. int na,kh,nf;
  120289. int ip,iw,ido,idl1,ix2,ix3;
  120290. nf=ifac[1];
  120291. na=1;
  120292. l2=n;
  120293. iw=n;
  120294. for(k1=0;k1<nf;k1++){
  120295. kh=nf-k1;
  120296. ip=ifac[kh+1];
  120297. l1=l2/ip;
  120298. ido=n/l2;
  120299. idl1=ido*l1;
  120300. iw-=(ip-1)*ido;
  120301. na=1-na;
  120302. if(ip!=4)goto L102;
  120303. ix2=iw+ido;
  120304. ix3=ix2+ido;
  120305. if(na!=0)
  120306. dradf4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120307. else
  120308. dradf4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120309. goto L110;
  120310. L102:
  120311. if(ip!=2)goto L104;
  120312. if(na!=0)goto L103;
  120313. dradf2(ido,l1,c,ch,wa+iw-1);
  120314. goto L110;
  120315. L103:
  120316. dradf2(ido,l1,ch,c,wa+iw-1);
  120317. goto L110;
  120318. L104:
  120319. if(ido==1)na=1-na;
  120320. if(na!=0)goto L109;
  120321. dradfg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120322. na=1;
  120323. goto L110;
  120324. L109:
  120325. dradfg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120326. na=0;
  120327. L110:
  120328. l2=l1;
  120329. }
  120330. if(na==1)return;
  120331. for(i=0;i<n;i++)c[i]=ch[i];
  120332. }
  120333. static void dradb2(int ido,int l1,float *cc,float *ch,float *wa1){
  120334. int i,k,t0,t1,t2,t3,t4,t5,t6;
  120335. float ti2,tr2;
  120336. t0=l1*ido;
  120337. t1=0;
  120338. t2=0;
  120339. t3=(ido<<1)-1;
  120340. for(k=0;k<l1;k++){
  120341. ch[t1]=cc[t2]+cc[t3+t2];
  120342. ch[t1+t0]=cc[t2]-cc[t3+t2];
  120343. t2=(t1+=ido)<<1;
  120344. }
  120345. if(ido<2)return;
  120346. if(ido==2)goto L105;
  120347. t1=0;
  120348. t2=0;
  120349. for(k=0;k<l1;k++){
  120350. t3=t1;
  120351. t5=(t4=t2)+(ido<<1);
  120352. t6=t0+t1;
  120353. for(i=2;i<ido;i+=2){
  120354. t3+=2;
  120355. t4+=2;
  120356. t5-=2;
  120357. t6+=2;
  120358. ch[t3-1]=cc[t4-1]+cc[t5-1];
  120359. tr2=cc[t4-1]-cc[t5-1];
  120360. ch[t3]=cc[t4]-cc[t5];
  120361. ti2=cc[t4]+cc[t5];
  120362. ch[t6-1]=wa1[i-2]*tr2-wa1[i-1]*ti2;
  120363. ch[t6]=wa1[i-2]*ti2+wa1[i-1]*tr2;
  120364. }
  120365. t2=(t1+=ido)<<1;
  120366. }
  120367. if(ido%2==1)return;
  120368. L105:
  120369. t1=ido-1;
  120370. t2=ido-1;
  120371. for(k=0;k<l1;k++){
  120372. ch[t1]=cc[t2]+cc[t2];
  120373. ch[t1+t0]=-(cc[t2+1]+cc[t2+1]);
  120374. t1+=ido;
  120375. t2+=ido<<1;
  120376. }
  120377. }
  120378. static void dradb3(int ido,int l1,float *cc,float *ch,float *wa1,
  120379. float *wa2){
  120380. static float taur = -.5f;
  120381. static float taui = .8660254037844386f;
  120382. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10;
  120383. float ci2,ci3,di2,di3,cr2,cr3,dr2,dr3,ti2,tr2;
  120384. t0=l1*ido;
  120385. t1=0;
  120386. t2=t0<<1;
  120387. t3=ido<<1;
  120388. t4=ido+(ido<<1);
  120389. t5=0;
  120390. for(k=0;k<l1;k++){
  120391. tr2=cc[t3-1]+cc[t3-1];
  120392. cr2=cc[t5]+(taur*tr2);
  120393. ch[t1]=cc[t5]+tr2;
  120394. ci3=taui*(cc[t3]+cc[t3]);
  120395. ch[t1+t0]=cr2-ci3;
  120396. ch[t1+t2]=cr2+ci3;
  120397. t1+=ido;
  120398. t3+=t4;
  120399. t5+=t4;
  120400. }
  120401. if(ido==1)return;
  120402. t1=0;
  120403. t3=ido<<1;
  120404. for(k=0;k<l1;k++){
  120405. t7=t1+(t1<<1);
  120406. t6=(t5=t7+t3);
  120407. t8=t1;
  120408. t10=(t9=t1+t0)+t0;
  120409. for(i=2;i<ido;i+=2){
  120410. t5+=2;
  120411. t6-=2;
  120412. t7+=2;
  120413. t8+=2;
  120414. t9+=2;
  120415. t10+=2;
  120416. tr2=cc[t5-1]+cc[t6-1];
  120417. cr2=cc[t7-1]+(taur*tr2);
  120418. ch[t8-1]=cc[t7-1]+tr2;
  120419. ti2=cc[t5]-cc[t6];
  120420. ci2=cc[t7]+(taur*ti2);
  120421. ch[t8]=cc[t7]+ti2;
  120422. cr3=taui*(cc[t5-1]-cc[t6-1]);
  120423. ci3=taui*(cc[t5]+cc[t6]);
  120424. dr2=cr2-ci3;
  120425. dr3=cr2+ci3;
  120426. di2=ci2+cr3;
  120427. di3=ci2-cr3;
  120428. ch[t9-1]=wa1[i-2]*dr2-wa1[i-1]*di2;
  120429. ch[t9]=wa1[i-2]*di2+wa1[i-1]*dr2;
  120430. ch[t10-1]=wa2[i-2]*dr3-wa2[i-1]*di3;
  120431. ch[t10]=wa2[i-2]*di3+wa2[i-1]*dr3;
  120432. }
  120433. t1+=ido;
  120434. }
  120435. }
  120436. static void dradb4(int ido,int l1,float *cc,float *ch,float *wa1,
  120437. float *wa2,float *wa3){
  120438. static float sqrt2=1.414213562373095f;
  120439. int i,k,t0,t1,t2,t3,t4,t5,t6,t7,t8;
  120440. float ci2,ci3,ci4,cr2,cr3,cr4,ti1,ti2,ti3,ti4,tr1,tr2,tr3,tr4;
  120441. t0=l1*ido;
  120442. t1=0;
  120443. t2=ido<<2;
  120444. t3=0;
  120445. t6=ido<<1;
  120446. for(k=0;k<l1;k++){
  120447. t4=t3+t6;
  120448. t5=t1;
  120449. tr3=cc[t4-1]+cc[t4-1];
  120450. tr4=cc[t4]+cc[t4];
  120451. tr1=cc[t3]-cc[(t4+=t6)-1];
  120452. tr2=cc[t3]+cc[t4-1];
  120453. ch[t5]=tr2+tr3;
  120454. ch[t5+=t0]=tr1-tr4;
  120455. ch[t5+=t0]=tr2-tr3;
  120456. ch[t5+=t0]=tr1+tr4;
  120457. t1+=ido;
  120458. t3+=t2;
  120459. }
  120460. if(ido<2)return;
  120461. if(ido==2)goto L105;
  120462. t1=0;
  120463. for(k=0;k<l1;k++){
  120464. t5=(t4=(t3=(t2=t1<<2)+t6))+t6;
  120465. t7=t1;
  120466. for(i=2;i<ido;i+=2){
  120467. t2+=2;
  120468. t3+=2;
  120469. t4-=2;
  120470. t5-=2;
  120471. t7+=2;
  120472. ti1=cc[t2]+cc[t5];
  120473. ti2=cc[t2]-cc[t5];
  120474. ti3=cc[t3]-cc[t4];
  120475. tr4=cc[t3]+cc[t4];
  120476. tr1=cc[t2-1]-cc[t5-1];
  120477. tr2=cc[t2-1]+cc[t5-1];
  120478. ti4=cc[t3-1]-cc[t4-1];
  120479. tr3=cc[t3-1]+cc[t4-1];
  120480. ch[t7-1]=tr2+tr3;
  120481. cr3=tr2-tr3;
  120482. ch[t7]=ti2+ti3;
  120483. ci3=ti2-ti3;
  120484. cr2=tr1-tr4;
  120485. cr4=tr1+tr4;
  120486. ci2=ti1+ti4;
  120487. ci4=ti1-ti4;
  120488. ch[(t8=t7+t0)-1]=wa1[i-2]*cr2-wa1[i-1]*ci2;
  120489. ch[t8]=wa1[i-2]*ci2+wa1[i-1]*cr2;
  120490. ch[(t8+=t0)-1]=wa2[i-2]*cr3-wa2[i-1]*ci3;
  120491. ch[t8]=wa2[i-2]*ci3+wa2[i-1]*cr3;
  120492. ch[(t8+=t0)-1]=wa3[i-2]*cr4-wa3[i-1]*ci4;
  120493. ch[t8]=wa3[i-2]*ci4+wa3[i-1]*cr4;
  120494. }
  120495. t1+=ido;
  120496. }
  120497. if(ido%2 == 1)return;
  120498. L105:
  120499. t1=ido;
  120500. t2=ido<<2;
  120501. t3=ido-1;
  120502. t4=ido+(ido<<1);
  120503. for(k=0;k<l1;k++){
  120504. t5=t3;
  120505. ti1=cc[t1]+cc[t4];
  120506. ti2=cc[t4]-cc[t1];
  120507. tr1=cc[t1-1]-cc[t4-1];
  120508. tr2=cc[t1-1]+cc[t4-1];
  120509. ch[t5]=tr2+tr2;
  120510. ch[t5+=t0]=sqrt2*(tr1-ti1);
  120511. ch[t5+=t0]=ti2+ti2;
  120512. ch[t5+=t0]=-sqrt2*(tr1+ti1);
  120513. t3+=ido;
  120514. t1+=t2;
  120515. t4+=t2;
  120516. }
  120517. }
  120518. static void dradbg(int ido,int ip,int l1,int idl1,float *cc,float *c1,
  120519. float *c2,float *ch,float *ch2,float *wa){
  120520. static float tpi=6.283185307179586f;
  120521. int idij,ipph,i,j,k,l,ik,is,t0,t1,t2,t3,t4,t5,t6,t7,t8,t9,t10,
  120522. t11,t12;
  120523. float dc2,ai1,ai2,ar1,ar2,ds2;
  120524. int nbd;
  120525. float dcp,arg,dsp,ar1h,ar2h;
  120526. int ipp2;
  120527. t10=ip*ido;
  120528. t0=l1*ido;
  120529. arg=tpi/(float)ip;
  120530. dcp=cos(arg);
  120531. dsp=sin(arg);
  120532. nbd=(ido-1)>>1;
  120533. ipp2=ip;
  120534. ipph=(ip+1)>>1;
  120535. if(ido<l1)goto L103;
  120536. t1=0;
  120537. t2=0;
  120538. for(k=0;k<l1;k++){
  120539. t3=t1;
  120540. t4=t2;
  120541. for(i=0;i<ido;i++){
  120542. ch[t3]=cc[t4];
  120543. t3++;
  120544. t4++;
  120545. }
  120546. t1+=ido;
  120547. t2+=t10;
  120548. }
  120549. goto L106;
  120550. L103:
  120551. t1=0;
  120552. for(i=0;i<ido;i++){
  120553. t2=t1;
  120554. t3=t1;
  120555. for(k=0;k<l1;k++){
  120556. ch[t2]=cc[t3];
  120557. t2+=ido;
  120558. t3+=t10;
  120559. }
  120560. t1++;
  120561. }
  120562. L106:
  120563. t1=0;
  120564. t2=ipp2*t0;
  120565. t7=(t5=ido<<1);
  120566. for(j=1;j<ipph;j++){
  120567. t1+=t0;
  120568. t2-=t0;
  120569. t3=t1;
  120570. t4=t2;
  120571. t6=t5;
  120572. for(k=0;k<l1;k++){
  120573. ch[t3]=cc[t6-1]+cc[t6-1];
  120574. ch[t4]=cc[t6]+cc[t6];
  120575. t3+=ido;
  120576. t4+=ido;
  120577. t6+=t10;
  120578. }
  120579. t5+=t7;
  120580. }
  120581. if (ido == 1)goto L116;
  120582. if(nbd<l1)goto L112;
  120583. t1=0;
  120584. t2=ipp2*t0;
  120585. t7=0;
  120586. for(j=1;j<ipph;j++){
  120587. t1+=t0;
  120588. t2-=t0;
  120589. t3=t1;
  120590. t4=t2;
  120591. t7+=(ido<<1);
  120592. t8=t7;
  120593. for(k=0;k<l1;k++){
  120594. t5=t3;
  120595. t6=t4;
  120596. t9=t8;
  120597. t11=t8;
  120598. for(i=2;i<ido;i+=2){
  120599. t5+=2;
  120600. t6+=2;
  120601. t9+=2;
  120602. t11-=2;
  120603. ch[t5-1]=cc[t9-1]+cc[t11-1];
  120604. ch[t6-1]=cc[t9-1]-cc[t11-1];
  120605. ch[t5]=cc[t9]-cc[t11];
  120606. ch[t6]=cc[t9]+cc[t11];
  120607. }
  120608. t3+=ido;
  120609. t4+=ido;
  120610. t8+=t10;
  120611. }
  120612. }
  120613. goto L116;
  120614. L112:
  120615. t1=0;
  120616. t2=ipp2*t0;
  120617. t7=0;
  120618. for(j=1;j<ipph;j++){
  120619. t1+=t0;
  120620. t2-=t0;
  120621. t3=t1;
  120622. t4=t2;
  120623. t7+=(ido<<1);
  120624. t8=t7;
  120625. t9=t7;
  120626. for(i=2;i<ido;i+=2){
  120627. t3+=2;
  120628. t4+=2;
  120629. t8+=2;
  120630. t9-=2;
  120631. t5=t3;
  120632. t6=t4;
  120633. t11=t8;
  120634. t12=t9;
  120635. for(k=0;k<l1;k++){
  120636. ch[t5-1]=cc[t11-1]+cc[t12-1];
  120637. ch[t6-1]=cc[t11-1]-cc[t12-1];
  120638. ch[t5]=cc[t11]-cc[t12];
  120639. ch[t6]=cc[t11]+cc[t12];
  120640. t5+=ido;
  120641. t6+=ido;
  120642. t11+=t10;
  120643. t12+=t10;
  120644. }
  120645. }
  120646. }
  120647. L116:
  120648. ar1=1.f;
  120649. ai1=0.f;
  120650. t1=0;
  120651. t9=(t2=ipp2*idl1);
  120652. t3=(ip-1)*idl1;
  120653. for(l=1;l<ipph;l++){
  120654. t1+=idl1;
  120655. t2-=idl1;
  120656. ar1h=dcp*ar1-dsp*ai1;
  120657. ai1=dcp*ai1+dsp*ar1;
  120658. ar1=ar1h;
  120659. t4=t1;
  120660. t5=t2;
  120661. t6=0;
  120662. t7=idl1;
  120663. t8=t3;
  120664. for(ik=0;ik<idl1;ik++){
  120665. c2[t4++]=ch2[t6++]+ar1*ch2[t7++];
  120666. c2[t5++]=ai1*ch2[t8++];
  120667. }
  120668. dc2=ar1;
  120669. ds2=ai1;
  120670. ar2=ar1;
  120671. ai2=ai1;
  120672. t6=idl1;
  120673. t7=t9-idl1;
  120674. for(j=2;j<ipph;j++){
  120675. t6+=idl1;
  120676. t7-=idl1;
  120677. ar2h=dc2*ar2-ds2*ai2;
  120678. ai2=dc2*ai2+ds2*ar2;
  120679. ar2=ar2h;
  120680. t4=t1;
  120681. t5=t2;
  120682. t11=t6;
  120683. t12=t7;
  120684. for(ik=0;ik<idl1;ik++){
  120685. c2[t4++]+=ar2*ch2[t11++];
  120686. c2[t5++]+=ai2*ch2[t12++];
  120687. }
  120688. }
  120689. }
  120690. t1=0;
  120691. for(j=1;j<ipph;j++){
  120692. t1+=idl1;
  120693. t2=t1;
  120694. for(ik=0;ik<idl1;ik++)ch2[ik]+=ch2[t2++];
  120695. }
  120696. t1=0;
  120697. t2=ipp2*t0;
  120698. for(j=1;j<ipph;j++){
  120699. t1+=t0;
  120700. t2-=t0;
  120701. t3=t1;
  120702. t4=t2;
  120703. for(k=0;k<l1;k++){
  120704. ch[t3]=c1[t3]-c1[t4];
  120705. ch[t4]=c1[t3]+c1[t4];
  120706. t3+=ido;
  120707. t4+=ido;
  120708. }
  120709. }
  120710. if(ido==1)goto L132;
  120711. if(nbd<l1)goto L128;
  120712. t1=0;
  120713. t2=ipp2*t0;
  120714. for(j=1;j<ipph;j++){
  120715. t1+=t0;
  120716. t2-=t0;
  120717. t3=t1;
  120718. t4=t2;
  120719. for(k=0;k<l1;k++){
  120720. t5=t3;
  120721. t6=t4;
  120722. for(i=2;i<ido;i+=2){
  120723. t5+=2;
  120724. t6+=2;
  120725. ch[t5-1]=c1[t5-1]-c1[t6];
  120726. ch[t6-1]=c1[t5-1]+c1[t6];
  120727. ch[t5]=c1[t5]+c1[t6-1];
  120728. ch[t6]=c1[t5]-c1[t6-1];
  120729. }
  120730. t3+=ido;
  120731. t4+=ido;
  120732. }
  120733. }
  120734. goto L132;
  120735. L128:
  120736. t1=0;
  120737. t2=ipp2*t0;
  120738. for(j=1;j<ipph;j++){
  120739. t1+=t0;
  120740. t2-=t0;
  120741. t3=t1;
  120742. t4=t2;
  120743. for(i=2;i<ido;i+=2){
  120744. t3+=2;
  120745. t4+=2;
  120746. t5=t3;
  120747. t6=t4;
  120748. for(k=0;k<l1;k++){
  120749. ch[t5-1]=c1[t5-1]-c1[t6];
  120750. ch[t6-1]=c1[t5-1]+c1[t6];
  120751. ch[t5]=c1[t5]+c1[t6-1];
  120752. ch[t6]=c1[t5]-c1[t6-1];
  120753. t5+=ido;
  120754. t6+=ido;
  120755. }
  120756. }
  120757. }
  120758. L132:
  120759. if(ido==1)return;
  120760. for(ik=0;ik<idl1;ik++)c2[ik]=ch2[ik];
  120761. t1=0;
  120762. for(j=1;j<ip;j++){
  120763. t2=(t1+=t0);
  120764. for(k=0;k<l1;k++){
  120765. c1[t2]=ch[t2];
  120766. t2+=ido;
  120767. }
  120768. }
  120769. if(nbd>l1)goto L139;
  120770. is= -ido-1;
  120771. t1=0;
  120772. for(j=1;j<ip;j++){
  120773. is+=ido;
  120774. t1+=t0;
  120775. idij=is;
  120776. t2=t1;
  120777. for(i=2;i<ido;i+=2){
  120778. t2+=2;
  120779. idij+=2;
  120780. t3=t2;
  120781. for(k=0;k<l1;k++){
  120782. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120783. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120784. t3+=ido;
  120785. }
  120786. }
  120787. }
  120788. return;
  120789. L139:
  120790. is= -ido-1;
  120791. t1=0;
  120792. for(j=1;j<ip;j++){
  120793. is+=ido;
  120794. t1+=t0;
  120795. t2=t1;
  120796. for(k=0;k<l1;k++){
  120797. idij=is;
  120798. t3=t2;
  120799. for(i=2;i<ido;i+=2){
  120800. idij+=2;
  120801. t3+=2;
  120802. c1[t3-1]=wa[idij-1]*ch[t3-1]-wa[idij]*ch[t3];
  120803. c1[t3]=wa[idij-1]*ch[t3]+wa[idij]*ch[t3-1];
  120804. }
  120805. t2+=ido;
  120806. }
  120807. }
  120808. }
  120809. static void drftb1(int n, float *c, float *ch, float *wa, int *ifac){
  120810. int i,k1,l1,l2;
  120811. int na;
  120812. int nf,ip,iw,ix2,ix3,ido,idl1;
  120813. nf=ifac[1];
  120814. na=0;
  120815. l1=1;
  120816. iw=1;
  120817. for(k1=0;k1<nf;k1++){
  120818. ip=ifac[k1 + 2];
  120819. l2=ip*l1;
  120820. ido=n/l2;
  120821. idl1=ido*l1;
  120822. if(ip!=4)goto L103;
  120823. ix2=iw+ido;
  120824. ix3=ix2+ido;
  120825. if(na!=0)
  120826. dradb4(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120827. else
  120828. dradb4(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1);
  120829. na=1-na;
  120830. goto L115;
  120831. L103:
  120832. if(ip!=2)goto L106;
  120833. if(na!=0)
  120834. dradb2(ido,l1,ch,c,wa+iw-1);
  120835. else
  120836. dradb2(ido,l1,c,ch,wa+iw-1);
  120837. na=1-na;
  120838. goto L115;
  120839. L106:
  120840. if(ip!=3)goto L109;
  120841. ix2=iw+ido;
  120842. if(na!=0)
  120843. dradb3(ido,l1,ch,c,wa+iw-1,wa+ix2-1);
  120844. else
  120845. dradb3(ido,l1,c,ch,wa+iw-1,wa+ix2-1);
  120846. na=1-na;
  120847. goto L115;
  120848. L109:
  120849. /* The radix five case can be translated later..... */
  120850. /* if(ip!=5)goto L112;
  120851. ix2=iw+ido;
  120852. ix3=ix2+ido;
  120853. ix4=ix3+ido;
  120854. if(na!=0)
  120855. dradb5(ido,l1,ch,c,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120856. else
  120857. dradb5(ido,l1,c,ch,wa+iw-1,wa+ix2-1,wa+ix3-1,wa+ix4-1);
  120858. na=1-na;
  120859. goto L115;
  120860. L112:*/
  120861. if(na!=0)
  120862. dradbg(ido,ip,l1,idl1,ch,ch,ch,c,c,wa+iw-1);
  120863. else
  120864. dradbg(ido,ip,l1,idl1,c,c,c,ch,ch,wa+iw-1);
  120865. if(ido==1)na=1-na;
  120866. L115:
  120867. l1=l2;
  120868. iw+=(ip-1)*ido;
  120869. }
  120870. if(na==0)return;
  120871. for(i=0;i<n;i++)c[i]=ch[i];
  120872. }
  120873. void drft_forward(drft_lookup *l,float *data){
  120874. if(l->n==1)return;
  120875. drftf1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120876. }
  120877. void drft_backward(drft_lookup *l,float *data){
  120878. if (l->n==1)return;
  120879. drftb1(l->n,data,l->trigcache,l->trigcache+l->n,l->splitcache);
  120880. }
  120881. void drft_init(drft_lookup *l,int n){
  120882. l->n=n;
  120883. l->trigcache=(float*)_ogg_calloc(3*n,sizeof(*l->trigcache));
  120884. l->splitcache=(int*)_ogg_calloc(32,sizeof(*l->splitcache));
  120885. fdrffti(n, l->trigcache, l->splitcache);
  120886. }
  120887. void drft_clear(drft_lookup *l){
  120888. if(l){
  120889. if(l->trigcache)_ogg_free(l->trigcache);
  120890. if(l->splitcache)_ogg_free(l->splitcache);
  120891. memset(l,0,sizeof(*l));
  120892. }
  120893. }
  120894. #endif
  120895. /********* End of inlined file: smallft.c *********/
  120896. /********* Start of inlined file: synthesis.c *********/
  120897. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  120898. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  120899. // tasks..
  120900. /********* Start of inlined file: juce_Config.h *********/
  120901. #ifndef __JUCE_CONFIG_JUCEHEADER__
  120902. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  120903. /*
  120904. This file contains macros that enable/disable various JUCE features.
  120905. */
  120906. /** The name of the namespace that all Juce classes and functions will be
  120907. put inside. If this is not defined, no namespace will be used.
  120908. */
  120909. #ifndef JUCE_NAMESPACE
  120910. #define JUCE_NAMESPACE juce
  120911. #endif
  120912. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  120913. but if you define this value, you can override this can force it to be true or
  120914. false.
  120915. */
  120916. #ifndef JUCE_FORCE_DEBUG
  120917. //#define JUCE_FORCE_DEBUG 1
  120918. #endif
  120919. /** If this flag is enabled, the the jassert and jassertfalse macros will
  120920. always use Logger::writeToLog() to write a message when an assertion happens.
  120921. Enabling it will also leave this turned on in release builds. When it's disabled,
  120922. however, the jassert and jassertfalse macros will not be compiled in a
  120923. release build.
  120924. @see jassert, jassertfalse, Logger
  120925. */
  120926. #ifndef JUCE_LOG_ASSERTIONS
  120927. // #define JUCE_LOG_ASSERTIONS 1
  120928. #endif
  120929. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  120930. which the ASIOAudioIODevice class can't be built. See the comments in the
  120931. ASIOAudioIODevice class's header file for more info about this.
  120932. (This only affects a Win32 build)
  120933. */
  120934. #ifndef JUCE_ASIO
  120935. #define JUCE_ASIO 1
  120936. #endif
  120937. /** Comment out this macro to disable building of ALSA device support on Linux.
  120938. */
  120939. #ifndef JUCE_ALSA
  120940. #define JUCE_ALSA 1
  120941. #endif
  120942. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  120943. have the SDK installed.
  120944. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  120945. classes will be unavailable.
  120946. On Windows, if you enable this, you'll need to have the QuickTime SDK
  120947. installed, and its header files will need to be on your include path.
  120948. */
  120949. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  120950. #define JUCE_QUICKTIME 1
  120951. #endif
  120952. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  120953. have the appropriate headers and libraries available. If it's not enabled, the
  120954. OpenGLComponent class will be unavailable.
  120955. */
  120956. #ifndef JUCE_OPENGL
  120957. #define JUCE_OPENGL 1
  120958. #endif
  120959. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  120960. If you're not going to need either of these formats, turn off the flags to
  120961. avoid bloating your codebase with them.
  120962. */
  120963. #ifndef JUCE_USE_FLAC
  120964. #define JUCE_USE_FLAC 1
  120965. #endif
  120966. #ifndef JUCE_USE_OGGVORBIS
  120967. #define JUCE_USE_OGGVORBIS 1
  120968. #endif
  120969. /** This flag lets you enable support for CD-burning. You might want to disable
  120970. it to build without the MS SDK under windows.
  120971. */
  120972. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  120973. #define JUCE_USE_CDBURNER 1
  120974. #endif
  120975. /** Enabling this macro means that all regions that get repainted will have a coloured
  120976. line drawn around them.
  120977. This is handy if you're trying to optimise drawing, because it lets you easily see
  120978. when anything is being repainted unnecessarily.
  120979. */
  120980. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  120981. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  120982. #endif
  120983. /** Enable this under Linux to use Xinerama for multi-monitor support.
  120984. */
  120985. #ifndef JUCE_USE_XINERAMA
  120986. #define JUCE_USE_XINERAMA 1
  120987. #endif
  120988. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  120989. */
  120990. #ifndef JUCE_USE_XSHM
  120991. #define JUCE_USE_XSHM 1
  120992. #endif
  120993. /** Enabling this builds support for VST audio plugins.
  120994. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  120995. */
  120996. #ifndef JUCE_PLUGINHOST_VST
  120997. // #define JUCE_PLUGINHOST_VST 1
  120998. #endif
  120999. /** Enabling this builds support for AudioUnit audio plugins.
  121000. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  121001. */
  121002. #ifndef JUCE_PLUGINHOST_AU
  121003. // #define JUCE_PLUGINHOST_AU 1
  121004. #endif
  121005. /** Disabling this will avoid linking to any UI code. This is handy for
  121006. writing command-line utilities, e.g. on linux boxes which don't have some
  121007. of the UI libraries installed.
  121008. (On mac and windows, this won't generally make much difference to the build).
  121009. */
  121010. #ifndef JUCE_BUILD_GUI_CLASSES
  121011. #define JUCE_BUILD_GUI_CLASSES 1
  121012. #endif
  121013. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  121014. */
  121015. #ifndef JUCE_WEB_BROWSER
  121016. #define JUCE_WEB_BROWSER 1
  121017. #endif
  121018. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  121019. codebase - you might need to use this if you're linking to some of these libraries
  121020. yourself.
  121021. */
  121022. #ifndef JUCE_INCLUDE_ZLIB_CODE
  121023. #define JUCE_INCLUDE_ZLIB_CODE 1
  121024. #endif
  121025. #ifndef JUCE_INCLUDE_FLAC_CODE
  121026. #define JUCE_INCLUDE_FLAC_CODE 1
  121027. #endif
  121028. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  121029. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  121030. #endif
  121031. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  121032. #define JUCE_INCLUDE_PNGLIB_CODE 1
  121033. #endif
  121034. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  121035. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  121036. #endif
  121037. /** Enable this to add extra memory-leak info to the new and delete operators.
  121038. (Currently, this only affects Windows builds in debug mode).
  121039. */
  121040. #ifndef JUCE_CHECK_MEMORY_LEAKS
  121041. #define JUCE_CHECK_MEMORY_LEAKS 1
  121042. #endif
  121043. /** Enable this to turn on juce's internal catching of exceptions.
  121044. Turning it off will avoid any exception catching. With it on, all exceptions
  121045. are passed to the JUCEApplication::unhandledException() callback for logging.
  121046. */
  121047. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  121048. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  121049. #endif
  121050. /** If this macro is set, the Juce String class will use unicode as its
  121051. internal representation. If it isn't set, it'll use ANSI.
  121052. */
  121053. #ifndef JUCE_STRINGS_ARE_UNICODE
  121054. #define JUCE_STRINGS_ARE_UNICODE 1
  121055. #endif
  121056. #endif
  121057. /********* End of inlined file: juce_Config.h *********/
  121058. #ifdef _MSC_VER
  121059. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  121060. #endif
  121061. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  121062. #if JUCE_USE_OGGVORBIS
  121063. #include <stdio.h>
  121064. int vorbis_synthesis(vorbis_block *vb,ogg_packet *op){
  121065. vorbis_dsp_state *vd=vb->vd;
  121066. private_state *b=(private_state*)vd->backend_state;
  121067. vorbis_info *vi=vd->vi;
  121068. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  121069. oggpack_buffer *opb=&vb->opb;
  121070. int type,mode,i;
  121071. /* first things first. Make sure decode is ready */
  121072. _vorbis_block_ripcord(vb);
  121073. oggpack_readinit(opb,op->packet,op->bytes);
  121074. /* Check the packet type */
  121075. if(oggpack_read(opb,1)!=0){
  121076. /* Oops. This is not an audio data packet */
  121077. return(OV_ENOTAUDIO);
  121078. }
  121079. /* read our mode and pre/post windowsize */
  121080. mode=oggpack_read(opb,b->modebits);
  121081. if(mode==-1)return(OV_EBADPACKET);
  121082. vb->mode=mode;
  121083. vb->W=ci->mode_param[mode]->blockflag;
  121084. if(vb->W){
  121085. /* this doesn;t get mapped through mode selection as it's used
  121086. only for window selection */
  121087. vb->lW=oggpack_read(opb,1);
  121088. vb->nW=oggpack_read(opb,1);
  121089. if(vb->nW==-1) return(OV_EBADPACKET);
  121090. }else{
  121091. vb->lW=0;
  121092. vb->nW=0;
  121093. }
  121094. /* more setup */
  121095. vb->granulepos=op->granulepos;
  121096. vb->sequence=op->packetno;
  121097. vb->eofflag=op->e_o_s;
  121098. /* alloc pcm passback storage */
  121099. vb->pcmend=ci->blocksizes[vb->W];
  121100. vb->pcm=(float**)_vorbis_block_alloc(vb,sizeof(*vb->pcm)*vi->channels);
  121101. for(i=0;i<vi->channels;i++)
  121102. vb->pcm[i]=(float*)_vorbis_block_alloc(vb,vb->pcmend*sizeof(*vb->pcm[i]));
  121103. /* unpack_header enforces range checking */
  121104. type=ci->map_type[ci->mode_param[mode]->mapping];
  121105. return(_mapping_P[type]->inverse(vb,ci->map_param[ci->mode_param[mode]->
  121106. mapping]));
  121107. }
  121108. /* used to track pcm position without actually performing decode.
  121109. Useful for sequential 'fast forward' */
  121110. int vorbis_synthesis_trackonly(vorbis_block *vb,ogg_packet *op){
  121111. vorbis_dsp_state *vd=vb->vd;
  121112. private_state *b=(private_state*)vd->backend_state;
  121113. vorbis_info *vi=vd->vi;
  121114. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  121115. oggpack_buffer *opb=&vb->opb;
  121116. int mode;
  121117. /* first things first. Make sure decode is ready */
  121118. _vorbis_block_ripcord(vb);
  121119. oggpack_readinit(opb,op->packet,op->bytes);
  121120. /* Check the packet type */
  121121. if(oggpack_read(opb,1)!=0){
  121122. /* Oops. This is not an audio data packet */
  121123. return(OV_ENOTAUDIO);
  121124. }
  121125. /* read our mode and pre/post windowsize */
  121126. mode=oggpack_read(opb,b->modebits);
  121127. if(mode==-1)return(OV_EBADPACKET);
  121128. vb->mode=mode;
  121129. vb->W=ci->mode_param[mode]->blockflag;
  121130. if(vb->W){
  121131. vb->lW=oggpack_read(opb,1);
  121132. vb->nW=oggpack_read(opb,1);
  121133. if(vb->nW==-1) return(OV_EBADPACKET);
  121134. }else{
  121135. vb->lW=0;
  121136. vb->nW=0;
  121137. }
  121138. /* more setup */
  121139. vb->granulepos=op->granulepos;
  121140. vb->sequence=op->packetno;
  121141. vb->eofflag=op->e_o_s;
  121142. /* no pcm */
  121143. vb->pcmend=0;
  121144. vb->pcm=NULL;
  121145. return(0);
  121146. }
  121147. long vorbis_packet_blocksize(vorbis_info *vi,ogg_packet *op){
  121148. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  121149. oggpack_buffer opb;
  121150. int mode;
  121151. oggpack_readinit(&opb,op->packet,op->bytes);
  121152. /* Check the packet type */
  121153. if(oggpack_read(&opb,1)!=0){
  121154. /* Oops. This is not an audio data packet */
  121155. return(OV_ENOTAUDIO);
  121156. }
  121157. {
  121158. int modebits=0;
  121159. int v=ci->modes;
  121160. while(v>1){
  121161. modebits++;
  121162. v>>=1;
  121163. }
  121164. /* read our mode and pre/post windowsize */
  121165. mode=oggpack_read(&opb,modebits);
  121166. }
  121167. if(mode==-1)return(OV_EBADPACKET);
  121168. return(ci->blocksizes[ci->mode_param[mode]->blockflag]);
  121169. }
  121170. int vorbis_synthesis_halfrate(vorbis_info *vi,int flag){
  121171. /* set / clear half-sample-rate mode */
  121172. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  121173. /* right now, our MDCT can't handle < 64 sample windows. */
  121174. if(ci->blocksizes[0]<=64 && flag)return -1;
  121175. ci->halfrate_flag=(flag?1:0);
  121176. return 0;
  121177. }
  121178. int vorbis_synthesis_halfrate_p(vorbis_info *vi){
  121179. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  121180. return ci->halfrate_flag;
  121181. }
  121182. #endif
  121183. /********* End of inlined file: synthesis.c *********/
  121184. /********* Start of inlined file: vorbisenc.c *********/
  121185. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  121186. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  121187. // tasks..
  121188. /********* Start of inlined file: juce_Config.h *********/
  121189. #ifndef __JUCE_CONFIG_JUCEHEADER__
  121190. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  121191. /*
  121192. This file contains macros that enable/disable various JUCE features.
  121193. */
  121194. /** The name of the namespace that all Juce classes and functions will be
  121195. put inside. If this is not defined, no namespace will be used.
  121196. */
  121197. #ifndef JUCE_NAMESPACE
  121198. #define JUCE_NAMESPACE juce
  121199. #endif
  121200. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  121201. but if you define this value, you can override this can force it to be true or
  121202. false.
  121203. */
  121204. #ifndef JUCE_FORCE_DEBUG
  121205. //#define JUCE_FORCE_DEBUG 1
  121206. #endif
  121207. /** If this flag is enabled, the the jassert and jassertfalse macros will
  121208. always use Logger::writeToLog() to write a message when an assertion happens.
  121209. Enabling it will also leave this turned on in release builds. When it's disabled,
  121210. however, the jassert and jassertfalse macros will not be compiled in a
  121211. release build.
  121212. @see jassert, jassertfalse, Logger
  121213. */
  121214. #ifndef JUCE_LOG_ASSERTIONS
  121215. // #define JUCE_LOG_ASSERTIONS 1
  121216. #endif
  121217. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  121218. which the ASIOAudioIODevice class can't be built. See the comments in the
  121219. ASIOAudioIODevice class's header file for more info about this.
  121220. (This only affects a Win32 build)
  121221. */
  121222. #ifndef JUCE_ASIO
  121223. #define JUCE_ASIO 1
  121224. #endif
  121225. /** Comment out this macro to disable building of ALSA device support on Linux.
  121226. */
  121227. #ifndef JUCE_ALSA
  121228. #define JUCE_ALSA 1
  121229. #endif
  121230. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  121231. have the SDK installed.
  121232. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  121233. classes will be unavailable.
  121234. On Windows, if you enable this, you'll need to have the QuickTime SDK
  121235. installed, and its header files will need to be on your include path.
  121236. */
  121237. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  121238. #define JUCE_QUICKTIME 1
  121239. #endif
  121240. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  121241. have the appropriate headers and libraries available. If it's not enabled, the
  121242. OpenGLComponent class will be unavailable.
  121243. */
  121244. #ifndef JUCE_OPENGL
  121245. #define JUCE_OPENGL 1
  121246. #endif
  121247. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  121248. If you're not going to need either of these formats, turn off the flags to
  121249. avoid bloating your codebase with them.
  121250. */
  121251. #ifndef JUCE_USE_FLAC
  121252. #define JUCE_USE_FLAC 1
  121253. #endif
  121254. #ifndef JUCE_USE_OGGVORBIS
  121255. #define JUCE_USE_OGGVORBIS 1
  121256. #endif
  121257. /** This flag lets you enable support for CD-burning. You might want to disable
  121258. it to build without the MS SDK under windows.
  121259. */
  121260. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  121261. #define JUCE_USE_CDBURNER 1
  121262. #endif
  121263. /** Enabling this macro means that all regions that get repainted will have a coloured
  121264. line drawn around them.
  121265. This is handy if you're trying to optimise drawing, because it lets you easily see
  121266. when anything is being repainted unnecessarily.
  121267. */
  121268. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  121269. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  121270. #endif
  121271. /** Enable this under Linux to use Xinerama for multi-monitor support.
  121272. */
  121273. #ifndef JUCE_USE_XINERAMA
  121274. #define JUCE_USE_XINERAMA 1
  121275. #endif
  121276. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  121277. */
  121278. #ifndef JUCE_USE_XSHM
  121279. #define JUCE_USE_XSHM 1
  121280. #endif
  121281. /** Enabling this builds support for VST audio plugins.
  121282. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  121283. */
  121284. #ifndef JUCE_PLUGINHOST_VST
  121285. // #define JUCE_PLUGINHOST_VST 1
  121286. #endif
  121287. /** Enabling this builds support for AudioUnit audio plugins.
  121288. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  121289. */
  121290. #ifndef JUCE_PLUGINHOST_AU
  121291. // #define JUCE_PLUGINHOST_AU 1
  121292. #endif
  121293. /** Disabling this will avoid linking to any UI code. This is handy for
  121294. writing command-line utilities, e.g. on linux boxes which don't have some
  121295. of the UI libraries installed.
  121296. (On mac and windows, this won't generally make much difference to the build).
  121297. */
  121298. #ifndef JUCE_BUILD_GUI_CLASSES
  121299. #define JUCE_BUILD_GUI_CLASSES 1
  121300. #endif
  121301. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  121302. */
  121303. #ifndef JUCE_WEB_BROWSER
  121304. #define JUCE_WEB_BROWSER 1
  121305. #endif
  121306. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  121307. codebase - you might need to use this if you're linking to some of these libraries
  121308. yourself.
  121309. */
  121310. #ifndef JUCE_INCLUDE_ZLIB_CODE
  121311. #define JUCE_INCLUDE_ZLIB_CODE 1
  121312. #endif
  121313. #ifndef JUCE_INCLUDE_FLAC_CODE
  121314. #define JUCE_INCLUDE_FLAC_CODE 1
  121315. #endif
  121316. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  121317. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  121318. #endif
  121319. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  121320. #define JUCE_INCLUDE_PNGLIB_CODE 1
  121321. #endif
  121322. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  121323. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  121324. #endif
  121325. /** Enable this to add extra memory-leak info to the new and delete operators.
  121326. (Currently, this only affects Windows builds in debug mode).
  121327. */
  121328. #ifndef JUCE_CHECK_MEMORY_LEAKS
  121329. #define JUCE_CHECK_MEMORY_LEAKS 1
  121330. #endif
  121331. /** Enable this to turn on juce's internal catching of exceptions.
  121332. Turning it off will avoid any exception catching. With it on, all exceptions
  121333. are passed to the JUCEApplication::unhandledException() callback for logging.
  121334. */
  121335. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  121336. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  121337. #endif
  121338. /** If this macro is set, the Juce String class will use unicode as its
  121339. internal representation. If it isn't set, it'll use ANSI.
  121340. */
  121341. #ifndef JUCE_STRINGS_ARE_UNICODE
  121342. #define JUCE_STRINGS_ARE_UNICODE 1
  121343. #endif
  121344. #endif
  121345. /********* End of inlined file: juce_Config.h *********/
  121346. #ifdef _MSC_VER
  121347. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  121348. #endif
  121349. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  121350. #if JUCE_USE_OGGVORBIS
  121351. #include <stdlib.h>
  121352. #include <string.h>
  121353. #include <math.h>
  121354. /* careful with this; it's using static array sizing to make managing
  121355. all the modes a little less annoying. If we use a residue backend
  121356. with > 12 partition types, or a different division of iteration,
  121357. this needs to be updated. */
  121358. typedef struct {
  121359. static_codebook *books[12][3];
  121360. } static_bookblock;
  121361. typedef struct {
  121362. int res_type;
  121363. int limit_type; /* 0 lowpass limited, 1 point stereo limited */
  121364. vorbis_info_residue0 *res;
  121365. static_codebook *book_aux;
  121366. static_codebook *book_aux_managed;
  121367. static_bookblock *books_base;
  121368. static_bookblock *books_base_managed;
  121369. } vorbis_residue_template;
  121370. typedef struct {
  121371. vorbis_info_mapping0 *map;
  121372. vorbis_residue_template *res;
  121373. } vorbis_mapping_template;
  121374. typedef struct vp_adjblock{
  121375. int block[P_BANDS];
  121376. } vp_adjblock;
  121377. typedef struct {
  121378. int data[NOISE_COMPAND_LEVELS];
  121379. } compandblock;
  121380. /* high level configuration information for setting things up
  121381. step-by-step with the detailed vorbis_encode_ctl interface.
  121382. There's a fair amount of redundancy such that interactive setup
  121383. does not directly deal with any vorbis_info or codec_setup_info
  121384. initialization; it's all stored (until full init) in this highlevel
  121385. setup, then flushed out to the real codec setup structs later. */
  121386. typedef struct {
  121387. int att[P_NOISECURVES];
  121388. float boost;
  121389. float decay;
  121390. } att3;
  121391. typedef struct { int data[P_NOISECURVES]; } adj3;
  121392. typedef struct {
  121393. int pre[PACKETBLOBS];
  121394. int post[PACKETBLOBS];
  121395. float kHz[PACKETBLOBS];
  121396. float lowpasskHz[PACKETBLOBS];
  121397. } adj_stereo;
  121398. typedef struct {
  121399. int lo;
  121400. int hi;
  121401. int fixed;
  121402. } noiseguard;
  121403. typedef struct {
  121404. int data[P_NOISECURVES][17];
  121405. } noise3;
  121406. typedef struct {
  121407. int mappings;
  121408. double *rate_mapping;
  121409. double *quality_mapping;
  121410. int coupling_restriction;
  121411. long samplerate_min_restriction;
  121412. long samplerate_max_restriction;
  121413. int *blocksize_short;
  121414. int *blocksize_long;
  121415. att3 *psy_tone_masteratt;
  121416. int *psy_tone_0dB;
  121417. int *psy_tone_dBsuppress;
  121418. vp_adjblock *psy_tone_adj_impulse;
  121419. vp_adjblock *psy_tone_adj_long;
  121420. vp_adjblock *psy_tone_adj_other;
  121421. noiseguard *psy_noiseguards;
  121422. noise3 *psy_noise_bias_impulse;
  121423. noise3 *psy_noise_bias_padding;
  121424. noise3 *psy_noise_bias_trans;
  121425. noise3 *psy_noise_bias_long;
  121426. int *psy_noise_dBsuppress;
  121427. compandblock *psy_noise_compand;
  121428. double *psy_noise_compand_short_mapping;
  121429. double *psy_noise_compand_long_mapping;
  121430. int *psy_noise_normal_start[2];
  121431. int *psy_noise_normal_partition[2];
  121432. double *psy_noise_normal_thresh;
  121433. int *psy_ath_float;
  121434. int *psy_ath_abs;
  121435. double *psy_lowpass;
  121436. vorbis_info_psy_global *global_params;
  121437. double *global_mapping;
  121438. adj_stereo *stereo_modes;
  121439. static_codebook ***floor_books;
  121440. vorbis_info_floor1 *floor_params;
  121441. int *floor_short_mapping;
  121442. int *floor_long_mapping;
  121443. vorbis_mapping_template *maps;
  121444. } ve_setup_data_template;
  121445. /* a few static coder conventions */
  121446. static vorbis_info_mode _mode_template[2]={
  121447. {0,0,0,0},
  121448. {1,0,0,1}
  121449. };
  121450. static vorbis_info_mapping0 _map_nominal[2]={
  121451. {1, {0,0}, {0}, {0}, 1,{0},{1}},
  121452. {1, {0,0}, {1}, {1}, 1,{0},{1}}
  121453. };
  121454. /********* Start of inlined file: setup_44.h *********/
  121455. /********* Start of inlined file: floor_all.h *********/
  121456. /********* Start of inlined file: floor_books.h *********/
  121457. static long _huff_lengthlist_line_256x7_0sub1[] = {
  121458. 0, 2, 3, 3, 3, 3, 4, 3, 4,
  121459. };
  121460. static static_codebook _huff_book_line_256x7_0sub1 = {
  121461. 1, 9,
  121462. _huff_lengthlist_line_256x7_0sub1,
  121463. 0, 0, 0, 0, 0,
  121464. NULL,
  121465. NULL,
  121466. NULL,
  121467. NULL,
  121468. 0
  121469. };
  121470. static long _huff_lengthlist_line_256x7_0sub2[] = {
  121471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 4, 3, 5, 3,
  121472. 6, 3, 6, 4, 6, 4, 7, 5, 7,
  121473. };
  121474. static static_codebook _huff_book_line_256x7_0sub2 = {
  121475. 1, 25,
  121476. _huff_lengthlist_line_256x7_0sub2,
  121477. 0, 0, 0, 0, 0,
  121478. NULL,
  121479. NULL,
  121480. NULL,
  121481. NULL,
  121482. 0
  121483. };
  121484. static long _huff_lengthlist_line_256x7_0sub3[] = {
  121485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 5, 2, 5, 3, 5, 3,
  121487. 6, 3, 6, 4, 7, 6, 7, 8, 7, 9, 8, 9, 9, 9,10, 9,
  121488. 11,13,11,13,10,10,13,13,13,13,13,13,12,12,12,12,
  121489. };
  121490. static static_codebook _huff_book_line_256x7_0sub3 = {
  121491. 1, 64,
  121492. _huff_lengthlist_line_256x7_0sub3,
  121493. 0, 0, 0, 0, 0,
  121494. NULL,
  121495. NULL,
  121496. NULL,
  121497. NULL,
  121498. 0
  121499. };
  121500. static long _huff_lengthlist_line_256x7_1sub1[] = {
  121501. 0, 3, 3, 3, 3, 2, 4, 3, 4,
  121502. };
  121503. static static_codebook _huff_book_line_256x7_1sub1 = {
  121504. 1, 9,
  121505. _huff_lengthlist_line_256x7_1sub1,
  121506. 0, 0, 0, 0, 0,
  121507. NULL,
  121508. NULL,
  121509. NULL,
  121510. NULL,
  121511. 0
  121512. };
  121513. static long _huff_lengthlist_line_256x7_1sub2[] = {
  121514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 3, 4, 3, 4, 4,
  121515. 5, 4, 6, 5, 6, 7, 6, 8, 8,
  121516. };
  121517. static static_codebook _huff_book_line_256x7_1sub2 = {
  121518. 1, 25,
  121519. _huff_lengthlist_line_256x7_1sub2,
  121520. 0, 0, 0, 0, 0,
  121521. NULL,
  121522. NULL,
  121523. NULL,
  121524. NULL,
  121525. 0
  121526. };
  121527. static long _huff_lengthlist_line_256x7_1sub3[] = {
  121528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 2, 4, 3, 6, 3, 7,
  121530. 3, 8, 5, 8, 6, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  121531. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7,
  121532. };
  121533. static static_codebook _huff_book_line_256x7_1sub3 = {
  121534. 1, 64,
  121535. _huff_lengthlist_line_256x7_1sub3,
  121536. 0, 0, 0, 0, 0,
  121537. NULL,
  121538. NULL,
  121539. NULL,
  121540. NULL,
  121541. 0
  121542. };
  121543. static long _huff_lengthlist_line_256x7_class0[] = {
  121544. 7, 5, 5, 9, 9, 6, 6, 9,12, 8, 7, 8,11, 8, 9,15,
  121545. 6, 3, 3, 7, 7, 4, 3, 6, 9, 6, 5, 6, 8, 6, 8,15,
  121546. 8, 5, 5, 9, 8, 5, 4, 6,10, 7, 5, 5,11, 8, 7,15,
  121547. 14,15,13,13,13,13, 8,11,15,10, 7, 6,11, 9,10,15,
  121548. };
  121549. static static_codebook _huff_book_line_256x7_class0 = {
  121550. 1, 64,
  121551. _huff_lengthlist_line_256x7_class0,
  121552. 0, 0, 0, 0, 0,
  121553. NULL,
  121554. NULL,
  121555. NULL,
  121556. NULL,
  121557. 0
  121558. };
  121559. static long _huff_lengthlist_line_256x7_class1[] = {
  121560. 5, 6, 8,15, 6, 9,10,15,10,11,12,15,15,15,15,15,
  121561. 4, 6, 7,15, 6, 7, 8,15, 9, 8, 9,15,15,15,15,15,
  121562. 6, 8, 9,15, 7, 7, 8,15,10, 9,10,15,15,15,15,15,
  121563. 15,13,15,15,15,10,11,15,15,13,13,15,15,15,15,15,
  121564. 4, 6, 7,15, 6, 8, 9,15,10,10,12,15,15,15,15,15,
  121565. 2, 5, 6,15, 5, 6, 7,15, 8, 6, 7,15,15,15,15,15,
  121566. 5, 6, 8,15, 5, 6, 7,15, 9, 6, 7,15,15,15,15,15,
  121567. 14,12,13,15,12,10,11,15,15,15,15,15,15,15,15,15,
  121568. 7, 8, 9,15, 9,10,10,15,15,14,14,15,15,15,15,15,
  121569. 5, 6, 7,15, 7, 8, 9,15,12, 9,10,15,15,15,15,15,
  121570. 7, 7, 9,15, 7, 7, 8,15,12, 8, 9,15,15,15,15,15,
  121571. 13,13,14,15,12,11,12,15,15,15,15,15,15,15,15,15,
  121572. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121573. 13,13,13,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121574. 15,12,13,15,15,12,13,15,15,14,15,15,15,15,15,15,
  121575. 15,15,15,15,15,15,13,15,15,15,15,15,15,15,15,15,
  121576. };
  121577. static static_codebook _huff_book_line_256x7_class1 = {
  121578. 1, 256,
  121579. _huff_lengthlist_line_256x7_class1,
  121580. 0, 0, 0, 0, 0,
  121581. NULL,
  121582. NULL,
  121583. NULL,
  121584. NULL,
  121585. 0
  121586. };
  121587. static long _huff_lengthlist_line_512x17_0sub0[] = {
  121588. 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  121589. 5, 6, 5, 6, 6, 6, 6, 5, 6, 6, 7, 6, 7, 6, 7, 6,
  121590. 7, 6, 8, 7, 8, 7, 8, 7, 8, 7, 8, 7, 9, 7, 9, 7,
  121591. 9, 7, 9, 8, 9, 8,10, 8,10, 8,10, 7,10, 6,10, 8,
  121592. 10, 8,11, 7,10, 7,11, 8,11,11,12,12,11,11,12,11,
  121593. 13,11,13,11,13,12,15,12,13,13,14,14,14,14,14,15,
  121594. 15,15,16,14,17,19,19,18,18,18,18,18,18,18,18,18,
  121595. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  121596. };
  121597. static static_codebook _huff_book_line_512x17_0sub0 = {
  121598. 1, 128,
  121599. _huff_lengthlist_line_512x17_0sub0,
  121600. 0, 0, 0, 0, 0,
  121601. NULL,
  121602. NULL,
  121603. NULL,
  121604. NULL,
  121605. 0
  121606. };
  121607. static long _huff_lengthlist_line_512x17_1sub0[] = {
  121608. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  121609. 6, 5, 6, 6, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 8, 7,
  121610. };
  121611. static static_codebook _huff_book_line_512x17_1sub0 = {
  121612. 1, 32,
  121613. _huff_lengthlist_line_512x17_1sub0,
  121614. 0, 0, 0, 0, 0,
  121615. NULL,
  121616. NULL,
  121617. NULL,
  121618. NULL,
  121619. 0
  121620. };
  121621. static long _huff_lengthlist_line_512x17_1sub1[] = {
  121622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121624. 4, 3, 5, 3, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 6, 5,
  121625. 6, 5, 7, 5, 8, 6, 8, 6, 8, 6, 8, 6, 8, 7, 9, 7,
  121626. 9, 7,11, 9,11,11,12,11,14,12,14,16,14,16,13,16,
  121627. 14,16,12,15,13,16,14,16,13,14,12,15,13,15,13,13,
  121628. 13,15,12,14,14,15,13,15,12,15,15,15,15,15,15,15,
  121629. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,
  121630. };
  121631. static static_codebook _huff_book_line_512x17_1sub1 = {
  121632. 1, 128,
  121633. _huff_lengthlist_line_512x17_1sub1,
  121634. 0, 0, 0, 0, 0,
  121635. NULL,
  121636. NULL,
  121637. NULL,
  121638. NULL,
  121639. 0
  121640. };
  121641. static long _huff_lengthlist_line_512x17_2sub1[] = {
  121642. 0, 4, 5, 4, 4, 4, 5, 4, 4, 4, 5, 4, 5, 4, 5, 3,
  121643. 5, 3,
  121644. };
  121645. static static_codebook _huff_book_line_512x17_2sub1 = {
  121646. 1, 18,
  121647. _huff_lengthlist_line_512x17_2sub1,
  121648. 0, 0, 0, 0, 0,
  121649. NULL,
  121650. NULL,
  121651. NULL,
  121652. NULL,
  121653. 0
  121654. };
  121655. static long _huff_lengthlist_line_512x17_2sub2[] = {
  121656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121657. 0, 0, 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 6, 4, 6, 5,
  121658. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 7, 8, 7, 9, 7,
  121659. 9, 8,
  121660. };
  121661. static static_codebook _huff_book_line_512x17_2sub2 = {
  121662. 1, 50,
  121663. _huff_lengthlist_line_512x17_2sub2,
  121664. 0, 0, 0, 0, 0,
  121665. NULL,
  121666. NULL,
  121667. NULL,
  121668. NULL,
  121669. 0
  121670. };
  121671. static long _huff_lengthlist_line_512x17_2sub3[] = {
  121672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121675. 0, 0, 3, 3, 3, 3, 4, 3, 4, 4, 5, 5, 6, 6, 7, 7,
  121676. 7, 8, 8,11, 8, 9, 9, 9,10,11,11,11, 9,10,10,11,
  121677. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121678. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121679. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  121680. };
  121681. static static_codebook _huff_book_line_512x17_2sub3 = {
  121682. 1, 128,
  121683. _huff_lengthlist_line_512x17_2sub3,
  121684. 0, 0, 0, 0, 0,
  121685. NULL,
  121686. NULL,
  121687. NULL,
  121688. NULL,
  121689. 0
  121690. };
  121691. static long _huff_lengthlist_line_512x17_3sub1[] = {
  121692. 0, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 5, 4, 5,
  121693. 5, 5,
  121694. };
  121695. static static_codebook _huff_book_line_512x17_3sub1 = {
  121696. 1, 18,
  121697. _huff_lengthlist_line_512x17_3sub1,
  121698. 0, 0, 0, 0, 0,
  121699. NULL,
  121700. NULL,
  121701. NULL,
  121702. NULL,
  121703. 0
  121704. };
  121705. static long _huff_lengthlist_line_512x17_3sub2[] = {
  121706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121707. 0, 0, 2, 3, 3, 4, 3, 5, 4, 6, 4, 6, 5, 7, 6, 7,
  121708. 6, 8, 6, 8, 7, 9, 8,10, 8,12, 9,13,10,15,10,15,
  121709. 11,14,
  121710. };
  121711. static static_codebook _huff_book_line_512x17_3sub2 = {
  121712. 1, 50,
  121713. _huff_lengthlist_line_512x17_3sub2,
  121714. 0, 0, 0, 0, 0,
  121715. NULL,
  121716. NULL,
  121717. NULL,
  121718. NULL,
  121719. 0
  121720. };
  121721. static long _huff_lengthlist_line_512x17_3sub3[] = {
  121722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121725. 0, 0, 4, 8, 4, 8, 4, 8, 4, 8, 5, 8, 5, 8, 6, 8,
  121726. 4, 8, 4, 8, 5, 8, 5, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121727. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121728. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121729. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  121730. };
  121731. static static_codebook _huff_book_line_512x17_3sub3 = {
  121732. 1, 128,
  121733. _huff_lengthlist_line_512x17_3sub3,
  121734. 0, 0, 0, 0, 0,
  121735. NULL,
  121736. NULL,
  121737. NULL,
  121738. NULL,
  121739. 0
  121740. };
  121741. static long _huff_lengthlist_line_512x17_class1[] = {
  121742. 1, 2, 3, 6, 5, 4, 7, 7,
  121743. };
  121744. static static_codebook _huff_book_line_512x17_class1 = {
  121745. 1, 8,
  121746. _huff_lengthlist_line_512x17_class1,
  121747. 0, 0, 0, 0, 0,
  121748. NULL,
  121749. NULL,
  121750. NULL,
  121751. NULL,
  121752. 0
  121753. };
  121754. static long _huff_lengthlist_line_512x17_class2[] = {
  121755. 3, 3, 3,14, 5, 4, 4,11, 8, 6, 6,10,17,12,11,17,
  121756. 6, 5, 5,15, 5, 3, 4,11, 8, 5, 5, 8,16, 9,10,14,
  121757. 10, 8, 9,17, 8, 6, 6,13,10, 7, 7,10,16,11,13,14,
  121758. 17,17,17,17,17,16,16,16,16,15,16,16,16,16,16,16,
  121759. };
  121760. static static_codebook _huff_book_line_512x17_class2 = {
  121761. 1, 64,
  121762. _huff_lengthlist_line_512x17_class2,
  121763. 0, 0, 0, 0, 0,
  121764. NULL,
  121765. NULL,
  121766. NULL,
  121767. NULL,
  121768. 0
  121769. };
  121770. static long _huff_lengthlist_line_512x17_class3[] = {
  121771. 2, 4, 6,17, 4, 5, 7,17, 8, 7,10,17,17,17,17,17,
  121772. 3, 4, 6,15, 3, 3, 6,15, 7, 6, 9,17,17,17,17,17,
  121773. 6, 8,10,17, 6, 6, 8,16, 9, 8,10,17,17,15,16,17,
  121774. 17,17,17,17,12,15,15,16,12,15,15,16,16,16,16,16,
  121775. };
  121776. static static_codebook _huff_book_line_512x17_class3 = {
  121777. 1, 64,
  121778. _huff_lengthlist_line_512x17_class3,
  121779. 0, 0, 0, 0, 0,
  121780. NULL,
  121781. NULL,
  121782. NULL,
  121783. NULL,
  121784. 0
  121785. };
  121786. static long _huff_lengthlist_line_128x4_class0[] = {
  121787. 7, 7, 7,11, 6, 6, 7,11, 7, 6, 6,10,12,10,10,13,
  121788. 7, 7, 8,11, 7, 7, 7,11, 7, 6, 7,10,11,10,10,13,
  121789. 10,10, 9,12, 9, 9, 9,11, 8, 8, 8,11,13,11,10,14,
  121790. 15,15,14,15,15,14,13,14,15,12,12,17,17,17,17,17,
  121791. 7, 7, 6, 9, 6, 6, 6, 9, 7, 6, 6, 8,11,11,10,12,
  121792. 7, 7, 7, 9, 7, 6, 6, 9, 7, 6, 6, 9,13,10,10,11,
  121793. 10, 9, 8,10, 9, 8, 8,10, 8, 8, 7, 9,13,12,10,11,
  121794. 17,14,14,13,15,14,12,13,17,13,12,15,17,17,14,17,
  121795. 7, 6, 6, 7, 6, 6, 5, 7, 6, 6, 6, 6,11, 9, 9, 9,
  121796. 7, 7, 6, 7, 7, 6, 6, 7, 6, 6, 6, 6,10, 9, 8, 9,
  121797. 10, 9, 8, 8, 9, 8, 7, 8, 8, 7, 6, 8,11,10, 9,10,
  121798. 17,17,12,15,15,15,12,14,14,14,10,12,15,13,12,13,
  121799. 11,10, 8,10,11,10, 8, 8,10, 9, 7, 7,10, 9, 9,11,
  121800. 11,11, 9,10,11,10, 8, 9,10, 8, 6, 8,10, 9, 9,11,
  121801. 14,13,10,12,12,11,10,10, 8, 7, 8,10,10,11,11,12,
  121802. 17,17,15,17,17,17,17,17,17,13,12,17,17,17,14,17,
  121803. };
  121804. static static_codebook _huff_book_line_128x4_class0 = {
  121805. 1, 256,
  121806. _huff_lengthlist_line_128x4_class0,
  121807. 0, 0, 0, 0, 0,
  121808. NULL,
  121809. NULL,
  121810. NULL,
  121811. NULL,
  121812. 0
  121813. };
  121814. static long _huff_lengthlist_line_128x4_0sub0[] = {
  121815. 2, 2, 2, 2,
  121816. };
  121817. static static_codebook _huff_book_line_128x4_0sub0 = {
  121818. 1, 4,
  121819. _huff_lengthlist_line_128x4_0sub0,
  121820. 0, 0, 0, 0, 0,
  121821. NULL,
  121822. NULL,
  121823. NULL,
  121824. NULL,
  121825. 0
  121826. };
  121827. static long _huff_lengthlist_line_128x4_0sub1[] = {
  121828. 0, 0, 0, 0, 3, 2, 3, 2, 3, 3,
  121829. };
  121830. static static_codebook _huff_book_line_128x4_0sub1 = {
  121831. 1, 10,
  121832. _huff_lengthlist_line_128x4_0sub1,
  121833. 0, 0, 0, 0, 0,
  121834. NULL,
  121835. NULL,
  121836. NULL,
  121837. NULL,
  121838. 0
  121839. };
  121840. static long _huff_lengthlist_line_128x4_0sub2[] = {
  121841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 4, 3, 4, 3,
  121842. 4, 4, 5, 4, 5, 4, 6, 5, 6,
  121843. };
  121844. static static_codebook _huff_book_line_128x4_0sub2 = {
  121845. 1, 25,
  121846. _huff_lengthlist_line_128x4_0sub2,
  121847. 0, 0, 0, 0, 0,
  121848. NULL,
  121849. NULL,
  121850. NULL,
  121851. NULL,
  121852. 0
  121853. };
  121854. static long _huff_lengthlist_line_128x4_0sub3[] = {
  121855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121857. 5, 4, 6, 5, 6, 5, 7, 6, 6, 7, 7, 9, 9,11,11,16,
  121858. 11,14,10,11,11,13,16,15,15,15,15,15,15,15,15,15,
  121859. };
  121860. static static_codebook _huff_book_line_128x4_0sub3 = {
  121861. 1, 64,
  121862. _huff_lengthlist_line_128x4_0sub3,
  121863. 0, 0, 0, 0, 0,
  121864. NULL,
  121865. NULL,
  121866. NULL,
  121867. NULL,
  121868. 0
  121869. };
  121870. static long _huff_lengthlist_line_256x4_class0[] = {
  121871. 6, 7, 7,12, 6, 6, 7,12, 7, 6, 6,10,15,12,11,13,
  121872. 7, 7, 8,13, 7, 7, 8,12, 7, 7, 7,11,12,12,11,13,
  121873. 10, 9, 9,11, 9, 9, 9,10,10, 8, 8,12,14,12,12,14,
  121874. 11,11,12,14,11,12,11,15,15,12,13,15,15,15,15,15,
  121875. 6, 6, 7,10, 6, 6, 6,11, 7, 6, 6, 9,14,12,11,13,
  121876. 7, 7, 7,10, 6, 6, 7, 9, 7, 7, 6,10,13,12,10,12,
  121877. 9, 9, 9,11, 9, 9, 8, 9, 9, 8, 8,10,13,12,10,12,
  121878. 12,12,11,13,12,12,11,12,15,13,12,15,15,15,14,14,
  121879. 6, 6, 6, 8, 6, 6, 5, 6, 7, 7, 6, 5,11,10, 9, 8,
  121880. 7, 6, 6, 7, 6, 6, 5, 6, 7, 7, 6, 6,11,10, 9, 8,
  121881. 8, 8, 8, 9, 8, 8, 7, 8, 8, 8, 6, 7,11,10, 9, 9,
  121882. 14,11,10,14,14,11,10,15,13,11, 9,11,15,12,12,11,
  121883. 11, 9, 8, 8,10, 9, 8, 9,11,10, 9, 8,12,11,12,11,
  121884. 13,10, 8, 9,11,10, 8, 9,10, 9, 8, 9,10, 8,12,12,
  121885. 15,11,10,10,13,11,10,10, 8, 8, 7,12,10, 9,11,12,
  121886. 15,12,11,15,13,11,11,15,12,14,11,13,15,15,13,13,
  121887. };
  121888. static static_codebook _huff_book_line_256x4_class0 = {
  121889. 1, 256,
  121890. _huff_lengthlist_line_256x4_class0,
  121891. 0, 0, 0, 0, 0,
  121892. NULL,
  121893. NULL,
  121894. NULL,
  121895. NULL,
  121896. 0
  121897. };
  121898. static long _huff_lengthlist_line_256x4_0sub0[] = {
  121899. 2, 2, 2, 2,
  121900. };
  121901. static static_codebook _huff_book_line_256x4_0sub0 = {
  121902. 1, 4,
  121903. _huff_lengthlist_line_256x4_0sub0,
  121904. 0, 0, 0, 0, 0,
  121905. NULL,
  121906. NULL,
  121907. NULL,
  121908. NULL,
  121909. 0
  121910. };
  121911. static long _huff_lengthlist_line_256x4_0sub1[] = {
  121912. 0, 0, 0, 0, 2, 2, 3, 3, 3, 3,
  121913. };
  121914. static static_codebook _huff_book_line_256x4_0sub1 = {
  121915. 1, 10,
  121916. _huff_lengthlist_line_256x4_0sub1,
  121917. 0, 0, 0, 0, 0,
  121918. NULL,
  121919. NULL,
  121920. NULL,
  121921. NULL,
  121922. 0
  121923. };
  121924. static long _huff_lengthlist_line_256x4_0sub2[] = {
  121925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 3, 4, 3, 4, 3,
  121926. 5, 3, 5, 4, 5, 4, 6, 4, 6,
  121927. };
  121928. static static_codebook _huff_book_line_256x4_0sub2 = {
  121929. 1, 25,
  121930. _huff_lengthlist_line_256x4_0sub2,
  121931. 0, 0, 0, 0, 0,
  121932. NULL,
  121933. NULL,
  121934. NULL,
  121935. NULL,
  121936. 0
  121937. };
  121938. static long _huff_lengthlist_line_256x4_0sub3[] = {
  121939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  121940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 4, 3, 5, 3, 5, 3,
  121941. 6, 4, 7, 4, 7, 5, 7, 6, 7, 6, 7, 8,10,13,13,13,
  121942. 13,13,13,13,13,13,13,13,13,13,13,12,12,12,12,12,
  121943. };
  121944. static static_codebook _huff_book_line_256x4_0sub3 = {
  121945. 1, 64,
  121946. _huff_lengthlist_line_256x4_0sub3,
  121947. 0, 0, 0, 0, 0,
  121948. NULL,
  121949. NULL,
  121950. NULL,
  121951. NULL,
  121952. 0
  121953. };
  121954. static long _huff_lengthlist_line_128x7_class0[] = {
  121955. 10, 7, 8,13, 9, 6, 7,11,10, 8, 8,12,17,17,17,17,
  121956. 7, 5, 5, 9, 6, 4, 4, 8, 8, 5, 5, 8,16,14,13,16,
  121957. 7, 5, 5, 7, 6, 3, 3, 5, 8, 5, 4, 7,14,12,12,15,
  121958. 10, 7, 8, 9, 7, 5, 5, 6, 9, 6, 5, 5,15,12, 9,10,
  121959. };
  121960. static static_codebook _huff_book_line_128x7_class0 = {
  121961. 1, 64,
  121962. _huff_lengthlist_line_128x7_class0,
  121963. 0, 0, 0, 0, 0,
  121964. NULL,
  121965. NULL,
  121966. NULL,
  121967. NULL,
  121968. 0
  121969. };
  121970. static long _huff_lengthlist_line_128x7_class1[] = {
  121971. 8,13,17,17, 8,11,17,17,11,13,17,17,17,17,17,17,
  121972. 6,10,16,17, 6,10,15,17, 8,10,16,17,17,17,17,17,
  121973. 9,13,15,17, 8,11,17,17,10,12,17,17,17,17,17,17,
  121974. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  121975. 6,11,15,17, 7,10,15,17, 8,10,17,17,17,15,17,17,
  121976. 4, 8,13,17, 4, 7,13,17, 6, 8,15,17,16,15,17,17,
  121977. 6,11,15,17, 6, 9,13,17, 8,10,17,17,15,17,17,17,
  121978. 16,17,17,17,12,14,15,17,13,14,15,17,17,17,17,17,
  121979. 5,10,14,17, 5, 9,14,17, 7, 9,15,17,15,15,17,17,
  121980. 3, 7,12,17, 3, 6,11,17, 5, 7,13,17,12,12,17,17,
  121981. 5, 9,14,17, 3, 7,11,17, 5, 8,13,17,13,11,16,17,
  121982. 12,17,17,17, 9,14,15,17,10,11,14,17,16,14,17,17,
  121983. 8,12,17,17, 8,12,17,17,10,12,17,17,17,17,17,17,
  121984. 5,10,17,17, 5, 9,15,17, 7, 9,17,17,13,13,17,17,
  121985. 7,11,17,17, 6,10,15,17, 7, 9,15,17,12,11,17,17,
  121986. 12,15,17,17,11,14,17,17,11,10,15,17,17,16,17,17,
  121987. };
  121988. static static_codebook _huff_book_line_128x7_class1 = {
  121989. 1, 256,
  121990. _huff_lengthlist_line_128x7_class1,
  121991. 0, 0, 0, 0, 0,
  121992. NULL,
  121993. NULL,
  121994. NULL,
  121995. NULL,
  121996. 0
  121997. };
  121998. static long _huff_lengthlist_line_128x7_0sub1[] = {
  121999. 0, 3, 3, 3, 3, 3, 3, 3, 3,
  122000. };
  122001. static static_codebook _huff_book_line_128x7_0sub1 = {
  122002. 1, 9,
  122003. _huff_lengthlist_line_128x7_0sub1,
  122004. 0, 0, 0, 0, 0,
  122005. NULL,
  122006. NULL,
  122007. NULL,
  122008. NULL,
  122009. 0
  122010. };
  122011. static long _huff_lengthlist_line_128x7_0sub2[] = {
  122012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 4, 4, 4,
  122013. 5, 4, 5, 4, 5, 4, 6, 4, 6,
  122014. };
  122015. static static_codebook _huff_book_line_128x7_0sub2 = {
  122016. 1, 25,
  122017. _huff_lengthlist_line_128x7_0sub2,
  122018. 0, 0, 0, 0, 0,
  122019. NULL,
  122020. NULL,
  122021. NULL,
  122022. NULL,
  122023. 0
  122024. };
  122025. static long _huff_lengthlist_line_128x7_0sub3[] = {
  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, 3, 5, 3, 5, 3, 5, 4,
  122028. 5, 4, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122029. 7, 8, 9,11,13,13,13,13,13,13,13,13,13,13,13,13,
  122030. };
  122031. static static_codebook _huff_book_line_128x7_0sub3 = {
  122032. 1, 64,
  122033. _huff_lengthlist_line_128x7_0sub3,
  122034. 0, 0, 0, 0, 0,
  122035. NULL,
  122036. NULL,
  122037. NULL,
  122038. NULL,
  122039. 0
  122040. };
  122041. static long _huff_lengthlist_line_128x7_1sub1[] = {
  122042. 0, 3, 3, 2, 3, 3, 4, 3, 4,
  122043. };
  122044. static static_codebook _huff_book_line_128x7_1sub1 = {
  122045. 1, 9,
  122046. _huff_lengthlist_line_128x7_1sub1,
  122047. 0, 0, 0, 0, 0,
  122048. NULL,
  122049. NULL,
  122050. NULL,
  122051. NULL,
  122052. 0
  122053. };
  122054. static long _huff_lengthlist_line_128x7_1sub2[] = {
  122055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 3, 6, 3, 6, 3,
  122056. 6, 3, 7, 3, 8, 4, 9, 4, 9,
  122057. };
  122058. static static_codebook _huff_book_line_128x7_1sub2 = {
  122059. 1, 25,
  122060. _huff_lengthlist_line_128x7_1sub2,
  122061. 0, 0, 0, 0, 0,
  122062. NULL,
  122063. NULL,
  122064. NULL,
  122065. NULL,
  122066. 0
  122067. };
  122068. static long _huff_lengthlist_line_128x7_1sub3[] = {
  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, 1, 7, 2, 7, 3, 8, 4,
  122071. 9, 5, 9, 8,10,11,11,12,14,14,14,14,14,14,14,14,
  122072. 14,14,14,14,14,14,14,14,14,14,14,14,13,13,13,13,
  122073. };
  122074. static static_codebook _huff_book_line_128x7_1sub3 = {
  122075. 1, 64,
  122076. _huff_lengthlist_line_128x7_1sub3,
  122077. 0, 0, 0, 0, 0,
  122078. NULL,
  122079. NULL,
  122080. NULL,
  122081. NULL,
  122082. 0
  122083. };
  122084. static long _huff_lengthlist_line_128x11_class1[] = {
  122085. 1, 6, 3, 7, 2, 4, 5, 7,
  122086. };
  122087. static static_codebook _huff_book_line_128x11_class1 = {
  122088. 1, 8,
  122089. _huff_lengthlist_line_128x11_class1,
  122090. 0, 0, 0, 0, 0,
  122091. NULL,
  122092. NULL,
  122093. NULL,
  122094. NULL,
  122095. 0
  122096. };
  122097. static long _huff_lengthlist_line_128x11_class2[] = {
  122098. 1, 6,12,16, 4,12,15,16, 9,15,16,16,16,16,16,16,
  122099. 2, 5,11,16, 5,11,13,16, 9,13,16,16,16,16,16,16,
  122100. 4, 8,12,16, 5, 9,12,16, 9,13,15,16,16,16,16,16,
  122101. 15,16,16,16,11,14,13,16,12,15,16,16,16,16,16,15,
  122102. };
  122103. static static_codebook _huff_book_line_128x11_class2 = {
  122104. 1, 64,
  122105. _huff_lengthlist_line_128x11_class2,
  122106. 0, 0, 0, 0, 0,
  122107. NULL,
  122108. NULL,
  122109. NULL,
  122110. NULL,
  122111. 0
  122112. };
  122113. static long _huff_lengthlist_line_128x11_class3[] = {
  122114. 7, 6, 9,17, 7, 6, 8,17,12, 9,11,16,16,16,16,16,
  122115. 5, 4, 7,16, 5, 3, 6,14, 9, 6, 8,15,16,16,16,16,
  122116. 5, 4, 6,13, 3, 2, 4,11, 7, 4, 6,13,16,11,10,14,
  122117. 12,12,12,16, 9, 7,10,15,12, 9,11,16,16,15,15,16,
  122118. };
  122119. static static_codebook _huff_book_line_128x11_class3 = {
  122120. 1, 64,
  122121. _huff_lengthlist_line_128x11_class3,
  122122. 0, 0, 0, 0, 0,
  122123. NULL,
  122124. NULL,
  122125. NULL,
  122126. NULL,
  122127. 0
  122128. };
  122129. static long _huff_lengthlist_line_128x11_0sub0[] = {
  122130. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122131. 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 6, 6, 6, 7, 6,
  122132. 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6, 8, 7,
  122133. 8, 7, 8, 7, 8, 7, 9, 7, 9, 8, 9, 8, 9, 8,10, 8,
  122134. 10, 9,10, 9,10, 9,11, 9,11, 9,10,10,11,10,11,10,
  122135. 11,11,11,11,11,11,12,13,14,14,14,15,15,16,16,16,
  122136. 17,15,16,15,16,16,17,17,16,17,17,17,17,17,17,17,
  122137. 17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,17,
  122138. };
  122139. static static_codebook _huff_book_line_128x11_0sub0 = {
  122140. 1, 128,
  122141. _huff_lengthlist_line_128x11_0sub0,
  122142. 0, 0, 0, 0, 0,
  122143. NULL,
  122144. NULL,
  122145. NULL,
  122146. NULL,
  122147. 0
  122148. };
  122149. static long _huff_lengthlist_line_128x11_1sub0[] = {
  122150. 2, 5, 5, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122151. 6, 5, 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 8, 6,
  122152. };
  122153. static static_codebook _huff_book_line_128x11_1sub0 = {
  122154. 1, 32,
  122155. _huff_lengthlist_line_128x11_1sub0,
  122156. 0, 0, 0, 0, 0,
  122157. NULL,
  122158. NULL,
  122159. NULL,
  122160. NULL,
  122161. 0
  122162. };
  122163. static long _huff_lengthlist_line_128x11_1sub1[] = {
  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. 5, 3, 5, 3, 6, 4, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  122167. 8, 4, 9, 5, 9, 5, 9, 5, 9, 6,10, 6,10, 6,11, 7,
  122168. 10, 7,10, 8,11, 9,11, 9,11,10,11,11,12,11,11,12,
  122169. 15,15,12,14,11,14,12,14,11,14,13,14,12,14,11,14,
  122170. 11,14,12,14,11,14,11,14,13,13,14,14,14,14,14,14,
  122171. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  122172. };
  122173. static static_codebook _huff_book_line_128x11_1sub1 = {
  122174. 1, 128,
  122175. _huff_lengthlist_line_128x11_1sub1,
  122176. 0, 0, 0, 0, 0,
  122177. NULL,
  122178. NULL,
  122179. NULL,
  122180. NULL,
  122181. 0
  122182. };
  122183. static long _huff_lengthlist_line_128x11_2sub1[] = {
  122184. 0, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4,
  122185. 5, 5,
  122186. };
  122187. static static_codebook _huff_book_line_128x11_2sub1 = {
  122188. 1, 18,
  122189. _huff_lengthlist_line_128x11_2sub1,
  122190. 0, 0, 0, 0, 0,
  122191. NULL,
  122192. NULL,
  122193. NULL,
  122194. NULL,
  122195. 0
  122196. };
  122197. static long _huff_lengthlist_line_128x11_2sub2[] = {
  122198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122199. 0, 0, 3, 3, 3, 4, 4, 4, 4, 5, 4, 5, 4, 6, 5, 7,
  122200. 5, 7, 6, 8, 6, 8, 6, 9, 7, 9, 7,10, 7, 9, 8,11,
  122201. 8,11,
  122202. };
  122203. static static_codebook _huff_book_line_128x11_2sub2 = {
  122204. 1, 50,
  122205. _huff_lengthlist_line_128x11_2sub2,
  122206. 0, 0, 0, 0, 0,
  122207. NULL,
  122208. NULL,
  122209. NULL,
  122210. NULL,
  122211. 0
  122212. };
  122213. static long _huff_lengthlist_line_128x11_2sub3[] = {
  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, 4, 8, 3, 8, 4, 8, 4, 8, 6, 8, 5, 8, 4, 8,
  122218. 4, 8, 6, 8, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122219. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122220. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122221. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122222. };
  122223. static static_codebook _huff_book_line_128x11_2sub3 = {
  122224. 1, 128,
  122225. _huff_lengthlist_line_128x11_2sub3,
  122226. 0, 0, 0, 0, 0,
  122227. NULL,
  122228. NULL,
  122229. NULL,
  122230. NULL,
  122231. 0
  122232. };
  122233. static long _huff_lengthlist_line_128x11_3sub1[] = {
  122234. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4,
  122235. 5, 4,
  122236. };
  122237. static static_codebook _huff_book_line_128x11_3sub1 = {
  122238. 1, 18,
  122239. _huff_lengthlist_line_128x11_3sub1,
  122240. 0, 0, 0, 0, 0,
  122241. NULL,
  122242. NULL,
  122243. NULL,
  122244. NULL,
  122245. 0
  122246. };
  122247. static long _huff_lengthlist_line_128x11_3sub2[] = {
  122248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122249. 0, 0, 5, 3, 5, 4, 6, 4, 6, 4, 7, 4, 7, 4, 8, 4,
  122250. 8, 4, 9, 4, 9, 4,10, 4,10, 5,10, 5,11, 5,12, 6,
  122251. 12, 6,
  122252. };
  122253. static static_codebook _huff_book_line_128x11_3sub2 = {
  122254. 1, 50,
  122255. _huff_lengthlist_line_128x11_3sub2,
  122256. 0, 0, 0, 0, 0,
  122257. NULL,
  122258. NULL,
  122259. NULL,
  122260. NULL,
  122261. 0
  122262. };
  122263. static long _huff_lengthlist_line_128x11_3sub3[] = {
  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, 7, 1, 6, 3, 7, 3, 8, 4, 8, 5, 8, 8, 8, 9,
  122268. 7, 8, 8, 7, 7, 7, 8, 9,10, 9, 9,10,10,10,10,10,
  122269. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122270. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  122271. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  122272. };
  122273. static static_codebook _huff_book_line_128x11_3sub3 = {
  122274. 1, 128,
  122275. _huff_lengthlist_line_128x11_3sub3,
  122276. 0, 0, 0, 0, 0,
  122277. NULL,
  122278. NULL,
  122279. NULL,
  122280. NULL,
  122281. 0
  122282. };
  122283. static long _huff_lengthlist_line_128x17_class1[] = {
  122284. 1, 3, 4, 7, 2, 5, 6, 7,
  122285. };
  122286. static static_codebook _huff_book_line_128x17_class1 = {
  122287. 1, 8,
  122288. _huff_lengthlist_line_128x17_class1,
  122289. 0, 0, 0, 0, 0,
  122290. NULL,
  122291. NULL,
  122292. NULL,
  122293. NULL,
  122294. 0
  122295. };
  122296. static long _huff_lengthlist_line_128x17_class2[] = {
  122297. 1, 4,10,19, 3, 8,13,19, 7,12,19,19,19,19,19,19,
  122298. 2, 6,11,19, 8,13,19,19, 9,11,19,19,19,19,19,19,
  122299. 6, 7,13,19, 9,13,19,19,10,13,18,18,18,18,18,18,
  122300. 18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,18,
  122301. };
  122302. static static_codebook _huff_book_line_128x17_class2 = {
  122303. 1, 64,
  122304. _huff_lengthlist_line_128x17_class2,
  122305. 0, 0, 0, 0, 0,
  122306. NULL,
  122307. NULL,
  122308. NULL,
  122309. NULL,
  122310. 0
  122311. };
  122312. static long _huff_lengthlist_line_128x17_class3[] = {
  122313. 3, 6,10,17, 4, 8,11,20, 8,10,11,20,20,20,20,20,
  122314. 2, 4, 8,18, 4, 6, 8,17, 7, 8,10,20,20,17,20,20,
  122315. 3, 5, 8,17, 3, 4, 6,17, 8, 8,10,17,17,12,16,20,
  122316. 13,13,15,20,10,10,12,20,15,14,15,20,20,20,19,19,
  122317. };
  122318. static static_codebook _huff_book_line_128x17_class3 = {
  122319. 1, 64,
  122320. _huff_lengthlist_line_128x17_class3,
  122321. 0, 0, 0, 0, 0,
  122322. NULL,
  122323. NULL,
  122324. NULL,
  122325. NULL,
  122326. 0
  122327. };
  122328. static long _huff_lengthlist_line_128x17_0sub0[] = {
  122329. 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122330. 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5,
  122331. 8, 5, 8, 5, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6, 9, 6,
  122332. 9, 6, 9, 7, 9, 7, 9, 7, 9, 7,10, 7,10, 8,10, 8,
  122333. 10, 8,10, 8,10, 8,11, 8,11, 8,11, 8,11, 8,11, 9,
  122334. 12, 9,12, 9,12, 9,12, 9,12,10,12,10,13,11,13,11,
  122335. 14,12,14,13,15,14,16,14,17,15,18,16,20,20,20,20,
  122336. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122337. };
  122338. static static_codebook _huff_book_line_128x17_0sub0 = {
  122339. 1, 128,
  122340. _huff_lengthlist_line_128x17_0sub0,
  122341. 0, 0, 0, 0, 0,
  122342. NULL,
  122343. NULL,
  122344. NULL,
  122345. NULL,
  122346. 0
  122347. };
  122348. static long _huff_lengthlist_line_128x17_1sub0[] = {
  122349. 2, 5, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122350. 6, 5, 6, 5, 7, 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7,
  122351. };
  122352. static static_codebook _huff_book_line_128x17_1sub0 = {
  122353. 1, 32,
  122354. _huff_lengthlist_line_128x17_1sub0,
  122355. 0, 0, 0, 0, 0,
  122356. NULL,
  122357. NULL,
  122358. NULL,
  122359. NULL,
  122360. 0
  122361. };
  122362. static long _huff_lengthlist_line_128x17_1sub1[] = {
  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. 4, 3, 5, 3, 5, 3, 6, 3, 6, 4, 6, 4, 7, 4, 7, 5,
  122366. 8, 5, 8, 6, 9, 7, 9, 7, 9, 8,10, 9,10, 9,11,10,
  122367. 11,11,11,11,11,11,12,12,12,13,12,13,12,14,12,15,
  122368. 12,14,12,16,13,17,13,17,14,17,14,16,13,17,14,17,
  122369. 14,17,15,17,15,15,16,17,17,17,17,17,17,17,17,17,
  122370. 17,17,17,17,17,17,16,16,16,16,16,16,16,16,16,16,
  122371. };
  122372. static static_codebook _huff_book_line_128x17_1sub1 = {
  122373. 1, 128,
  122374. _huff_lengthlist_line_128x17_1sub1,
  122375. 0, 0, 0, 0, 0,
  122376. NULL,
  122377. NULL,
  122378. NULL,
  122379. NULL,
  122380. 0
  122381. };
  122382. static long _huff_lengthlist_line_128x17_2sub1[] = {
  122383. 0, 4, 5, 4, 6, 4, 8, 3, 9, 3, 9, 2, 9, 3, 8, 4,
  122384. 9, 4,
  122385. };
  122386. static static_codebook _huff_book_line_128x17_2sub1 = {
  122387. 1, 18,
  122388. _huff_lengthlist_line_128x17_2sub1,
  122389. 0, 0, 0, 0, 0,
  122390. NULL,
  122391. NULL,
  122392. NULL,
  122393. NULL,
  122394. 0
  122395. };
  122396. static long _huff_lengthlist_line_128x17_2sub2[] = {
  122397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122398. 0, 0, 5, 1, 5, 3, 5, 3, 5, 4, 7, 5,10, 7,10, 7,
  122399. 12,10,14,10,14, 9,14,11,14,14,14,13,13,13,13,13,
  122400. 13,13,
  122401. };
  122402. static static_codebook _huff_book_line_128x17_2sub2 = {
  122403. 1, 50,
  122404. _huff_lengthlist_line_128x17_2sub2,
  122405. 0, 0, 0, 0, 0,
  122406. NULL,
  122407. NULL,
  122408. NULL,
  122409. NULL,
  122410. 0
  122411. };
  122412. static long _huff_lengthlist_line_128x17_2sub3[] = {
  122413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122416. 0, 0, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122417. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6,
  122418. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122419. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122420. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122421. };
  122422. static static_codebook _huff_book_line_128x17_2sub3 = {
  122423. 1, 128,
  122424. _huff_lengthlist_line_128x17_2sub3,
  122425. 0, 0, 0, 0, 0,
  122426. NULL,
  122427. NULL,
  122428. NULL,
  122429. NULL,
  122430. 0
  122431. };
  122432. static long _huff_lengthlist_line_128x17_3sub1[] = {
  122433. 0, 4, 4, 4, 4, 4, 4, 4, 5, 3, 5, 3, 5, 4, 6, 4,
  122434. 6, 4,
  122435. };
  122436. static static_codebook _huff_book_line_128x17_3sub1 = {
  122437. 1, 18,
  122438. _huff_lengthlist_line_128x17_3sub1,
  122439. 0, 0, 0, 0, 0,
  122440. NULL,
  122441. NULL,
  122442. NULL,
  122443. NULL,
  122444. 0
  122445. };
  122446. static long _huff_lengthlist_line_128x17_3sub2[] = {
  122447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122448. 0, 0, 5, 3, 6, 3, 6, 4, 7, 4, 7, 4, 7, 4, 8, 4,
  122449. 8, 4, 8, 4, 8, 4, 9, 4, 9, 5,10, 5,10, 7,10, 8,
  122450. 10, 8,
  122451. };
  122452. static static_codebook _huff_book_line_128x17_3sub2 = {
  122453. 1, 50,
  122454. _huff_lengthlist_line_128x17_3sub2,
  122455. 0, 0, 0, 0, 0,
  122456. NULL,
  122457. NULL,
  122458. NULL,
  122459. NULL,
  122460. 0
  122461. };
  122462. static long _huff_lengthlist_line_128x17_3sub3[] = {
  122463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122466. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 4, 7, 5, 8, 5,11,
  122467. 6,10, 6,12, 7,12, 7,12, 8,12, 8,12,10,12,12,12,
  122468. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122469. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122470. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122471. };
  122472. static static_codebook _huff_book_line_128x17_3sub3 = {
  122473. 1, 128,
  122474. _huff_lengthlist_line_128x17_3sub3,
  122475. 0, 0, 0, 0, 0,
  122476. NULL,
  122477. NULL,
  122478. NULL,
  122479. NULL,
  122480. 0
  122481. };
  122482. static long _huff_lengthlist_line_1024x27_class1[] = {
  122483. 2,10, 8,14, 7,12,11,14, 1, 5, 3, 7, 4, 9, 7,13,
  122484. };
  122485. static static_codebook _huff_book_line_1024x27_class1 = {
  122486. 1, 16,
  122487. _huff_lengthlist_line_1024x27_class1,
  122488. 0, 0, 0, 0, 0,
  122489. NULL,
  122490. NULL,
  122491. NULL,
  122492. NULL,
  122493. 0
  122494. };
  122495. static long _huff_lengthlist_line_1024x27_class2[] = {
  122496. 1, 4, 2, 6, 3, 7, 5, 7,
  122497. };
  122498. static static_codebook _huff_book_line_1024x27_class2 = {
  122499. 1, 8,
  122500. _huff_lengthlist_line_1024x27_class2,
  122501. 0, 0, 0, 0, 0,
  122502. NULL,
  122503. NULL,
  122504. NULL,
  122505. NULL,
  122506. 0
  122507. };
  122508. static long _huff_lengthlist_line_1024x27_class3[] = {
  122509. 1, 5, 7,21, 5, 8, 9,21,10, 9,12,20,20,16,20,20,
  122510. 4, 8, 9,20, 6, 8, 9,20,11,11,13,20,20,15,17,20,
  122511. 9,11,14,20, 8,10,15,20,11,13,15,20,20,20,20,20,
  122512. 20,20,20,20,13,20,20,20,18,18,20,20,20,20,20,20,
  122513. 3, 6, 8,20, 6, 7, 9,20,10, 9,12,20,20,20,20,20,
  122514. 5, 7, 9,20, 6, 6, 9,20,10, 9,12,20,20,20,20,20,
  122515. 8,10,13,20, 8, 9,12,20,11,10,12,20,20,20,20,20,
  122516. 18,20,20,20,15,17,18,20,18,17,18,20,20,20,20,20,
  122517. 7,10,12,20, 8, 9,11,20,14,13,14,20,20,20,20,20,
  122518. 6, 9,12,20, 7, 8,11,20,12,11,13,20,20,20,20,20,
  122519. 9,11,15,20, 8,10,14,20,12,11,14,20,20,20,20,20,
  122520. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122521. 11,16,18,20,15,15,17,20,20,17,20,20,20,20,20,20,
  122522. 9,14,16,20,12,12,15,20,17,15,18,20,20,20,20,20,
  122523. 16,19,18,20,15,16,20,20,17,17,20,20,20,20,20,20,
  122524. 20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,
  122525. };
  122526. static static_codebook _huff_book_line_1024x27_class3 = {
  122527. 1, 256,
  122528. _huff_lengthlist_line_1024x27_class3,
  122529. 0, 0, 0, 0, 0,
  122530. NULL,
  122531. NULL,
  122532. NULL,
  122533. NULL,
  122534. 0
  122535. };
  122536. static long _huff_lengthlist_line_1024x27_class4[] = {
  122537. 2, 3, 7,13, 4, 4, 7,15, 8, 6, 9,17,21,16,15,21,
  122538. 2, 5, 7,11, 5, 5, 7,14, 9, 7,10,16,17,15,16,21,
  122539. 4, 7,10,17, 7, 7, 9,15,11, 9,11,16,21,18,15,21,
  122540. 18,21,21,21,15,17,17,19,21,19,18,20,21,21,21,20,
  122541. };
  122542. static static_codebook _huff_book_line_1024x27_class4 = {
  122543. 1, 64,
  122544. _huff_lengthlist_line_1024x27_class4,
  122545. 0, 0, 0, 0, 0,
  122546. NULL,
  122547. NULL,
  122548. NULL,
  122549. NULL,
  122550. 0
  122551. };
  122552. static long _huff_lengthlist_line_1024x27_0sub0[] = {
  122553. 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122554. 6, 5, 6, 5, 6, 5, 6, 5, 7, 5, 7, 5, 7, 5, 7, 5,
  122555. 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,10, 6,10, 6,11, 6,
  122556. 11, 7,11, 7,12, 7,12, 7,12, 7,12, 7,12, 7,12, 7,
  122557. 12, 7,12, 8,13, 8,12, 8,12, 8,13, 8,13, 9,13, 9,
  122558. 13, 9,13, 9,12,10,12,10,13,10,14,11,14,12,14,13,
  122559. 14,13,14,14,15,16,15,15,15,14,15,17,21,22,22,21,
  122560. 22,22,22,22,22,22,21,21,21,21,21,21,21,21,21,21,
  122561. };
  122562. static static_codebook _huff_book_line_1024x27_0sub0 = {
  122563. 1, 128,
  122564. _huff_lengthlist_line_1024x27_0sub0,
  122565. 0, 0, 0, 0, 0,
  122566. NULL,
  122567. NULL,
  122568. NULL,
  122569. NULL,
  122570. 0
  122571. };
  122572. static long _huff_lengthlist_line_1024x27_1sub0[] = {
  122573. 2, 5, 5, 4, 5, 4, 5, 4, 5, 4, 6, 5, 6, 5, 6, 5,
  122574. 6, 5, 7, 5, 7, 6, 8, 6, 8, 6, 8, 6, 9, 6, 9, 6,
  122575. };
  122576. static static_codebook _huff_book_line_1024x27_1sub0 = {
  122577. 1, 32,
  122578. _huff_lengthlist_line_1024x27_1sub0,
  122579. 0, 0, 0, 0, 0,
  122580. NULL,
  122581. NULL,
  122582. NULL,
  122583. NULL,
  122584. 0
  122585. };
  122586. static long _huff_lengthlist_line_1024x27_1sub1[] = {
  122587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122589. 8, 5, 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 4,
  122590. 9, 4, 9, 4, 9, 4, 8, 4, 8, 4, 9, 5, 9, 5, 9, 5,
  122591. 9, 5, 9, 6,10, 6,10, 7,10, 8,11, 9,11,11,12,13,
  122592. 12,14,13,15,13,15,14,16,14,17,15,17,15,15,16,16,
  122593. 15,16,16,16,15,18,16,15,17,17,19,19,19,19,19,19,
  122594. 19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,19,
  122595. };
  122596. static static_codebook _huff_book_line_1024x27_1sub1 = {
  122597. 1, 128,
  122598. _huff_lengthlist_line_1024x27_1sub1,
  122599. 0, 0, 0, 0, 0,
  122600. NULL,
  122601. NULL,
  122602. NULL,
  122603. NULL,
  122604. 0
  122605. };
  122606. static long _huff_lengthlist_line_1024x27_2sub0[] = {
  122607. 1, 5, 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122608. 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 9, 8,10, 9,10, 9,
  122609. };
  122610. static static_codebook _huff_book_line_1024x27_2sub0 = {
  122611. 1, 32,
  122612. _huff_lengthlist_line_1024x27_2sub0,
  122613. 0, 0, 0, 0, 0,
  122614. NULL,
  122615. NULL,
  122616. NULL,
  122617. NULL,
  122618. 0
  122619. };
  122620. static long _huff_lengthlist_line_1024x27_2sub1[] = {
  122621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122623. 4, 3, 4, 3, 4, 4, 5, 4, 5, 4, 5, 5, 6, 5, 6, 5,
  122624. 7, 5, 7, 6, 7, 6, 8, 7, 8, 7, 8, 7, 9, 8, 9, 9,
  122625. 9, 9,10,10,10,11, 9,12, 9,12, 9,15,10,14, 9,13,
  122626. 10,13,10,12,10,12,10,13,10,12,11,13,11,14,12,13,
  122627. 13,14,14,13,14,15,14,16,13,13,14,16,16,16,16,16,
  122628. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,15,15,
  122629. };
  122630. static static_codebook _huff_book_line_1024x27_2sub1 = {
  122631. 1, 128,
  122632. _huff_lengthlist_line_1024x27_2sub1,
  122633. 0, 0, 0, 0, 0,
  122634. NULL,
  122635. NULL,
  122636. NULL,
  122637. NULL,
  122638. 0
  122639. };
  122640. static long _huff_lengthlist_line_1024x27_3sub1[] = {
  122641. 0, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4, 4, 4, 4, 5,
  122642. 5, 5,
  122643. };
  122644. static static_codebook _huff_book_line_1024x27_3sub1 = {
  122645. 1, 18,
  122646. _huff_lengthlist_line_1024x27_3sub1,
  122647. 0, 0, 0, 0, 0,
  122648. NULL,
  122649. NULL,
  122650. NULL,
  122651. NULL,
  122652. 0
  122653. };
  122654. static long _huff_lengthlist_line_1024x27_3sub2[] = {
  122655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122656. 0, 0, 3, 3, 4, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5, 6,
  122657. 5, 7, 5, 8, 6, 8, 6, 9, 7,10, 7,10, 8,10, 8,11,
  122658. 9,11,
  122659. };
  122660. static static_codebook _huff_book_line_1024x27_3sub2 = {
  122661. 1, 50,
  122662. _huff_lengthlist_line_1024x27_3sub2,
  122663. 0, 0, 0, 0, 0,
  122664. NULL,
  122665. NULL,
  122666. NULL,
  122667. NULL,
  122668. 0
  122669. };
  122670. static long _huff_lengthlist_line_1024x27_3sub3[] = {
  122671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122674. 0, 0, 3, 7, 3, 8, 3,10, 3, 8, 3, 9, 3, 8, 4, 9,
  122675. 4, 9, 5, 9, 6,10, 6, 9, 7,11, 7,12, 9,13,10,13,
  122676. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122677. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122678. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122679. };
  122680. static static_codebook _huff_book_line_1024x27_3sub3 = {
  122681. 1, 128,
  122682. _huff_lengthlist_line_1024x27_3sub3,
  122683. 0, 0, 0, 0, 0,
  122684. NULL,
  122685. NULL,
  122686. NULL,
  122687. NULL,
  122688. 0
  122689. };
  122690. static long _huff_lengthlist_line_1024x27_4sub1[] = {
  122691. 0, 4, 5, 4, 5, 4, 5, 4, 5, 3, 5, 3, 5, 3, 5, 4,
  122692. 5, 4,
  122693. };
  122694. static static_codebook _huff_book_line_1024x27_4sub1 = {
  122695. 1, 18,
  122696. _huff_lengthlist_line_1024x27_4sub1,
  122697. 0, 0, 0, 0, 0,
  122698. NULL,
  122699. NULL,
  122700. NULL,
  122701. NULL,
  122702. 0
  122703. };
  122704. static long _huff_lengthlist_line_1024x27_4sub2[] = {
  122705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122706. 0, 0, 4, 2, 4, 2, 5, 3, 5, 4, 6, 6, 6, 7, 7, 8,
  122707. 7, 8, 7, 8, 7, 9, 8, 9, 8, 9, 8,10, 8,11, 9,12,
  122708. 9,12,
  122709. };
  122710. static static_codebook _huff_book_line_1024x27_4sub2 = {
  122711. 1, 50,
  122712. _huff_lengthlist_line_1024x27_4sub2,
  122713. 0, 0, 0, 0, 0,
  122714. NULL,
  122715. NULL,
  122716. NULL,
  122717. NULL,
  122718. 0
  122719. };
  122720. static long _huff_lengthlist_line_1024x27_4sub3[] = {
  122721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122724. 0, 0, 2, 5, 2, 6, 3, 6, 4, 7, 4, 7, 5, 9, 5,11,
  122725. 6,11, 6,11, 7,11, 6,11, 6,11, 9,11, 8,11,11,11,
  122726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  122728. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  122729. };
  122730. static static_codebook _huff_book_line_1024x27_4sub3 = {
  122731. 1, 128,
  122732. _huff_lengthlist_line_1024x27_4sub3,
  122733. 0, 0, 0, 0, 0,
  122734. NULL,
  122735. NULL,
  122736. NULL,
  122737. NULL,
  122738. 0
  122739. };
  122740. static long _huff_lengthlist_line_2048x27_class1[] = {
  122741. 2, 6, 8, 9, 7,11,13,13, 1, 3, 5, 5, 6, 6,12,10,
  122742. };
  122743. static static_codebook _huff_book_line_2048x27_class1 = {
  122744. 1, 16,
  122745. _huff_lengthlist_line_2048x27_class1,
  122746. 0, 0, 0, 0, 0,
  122747. NULL,
  122748. NULL,
  122749. NULL,
  122750. NULL,
  122751. 0
  122752. };
  122753. static long _huff_lengthlist_line_2048x27_class2[] = {
  122754. 1, 2, 3, 6, 4, 7, 5, 7,
  122755. };
  122756. static static_codebook _huff_book_line_2048x27_class2 = {
  122757. 1, 8,
  122758. _huff_lengthlist_line_2048x27_class2,
  122759. 0, 0, 0, 0, 0,
  122760. NULL,
  122761. NULL,
  122762. NULL,
  122763. NULL,
  122764. 0
  122765. };
  122766. static long _huff_lengthlist_line_2048x27_class3[] = {
  122767. 3, 3, 6,16, 5, 5, 7,16, 9, 8,11,16,16,16,16,16,
  122768. 5, 5, 8,16, 5, 5, 7,16, 8, 7, 9,16,16,16,16,16,
  122769. 9, 9,12,16, 6, 8,11,16, 9,10,11,16,16,16,16,16,
  122770. 16,16,16,16,13,16,16,16,15,16,16,16,16,16,16,16,
  122771. 5, 4, 7,16, 6, 5, 8,16, 9, 8,10,16,16,16,16,16,
  122772. 5, 5, 7,15, 5, 4, 6,15, 7, 6, 8,16,16,16,16,16,
  122773. 9, 9,11,15, 7, 7, 9,16, 8, 8, 9,16,16,16,16,16,
  122774. 16,16,16,16,15,15,15,16,15,15,14,16,16,16,16,16,
  122775. 8, 8,11,16, 8, 9,10,16,11,10,14,16,16,16,16,16,
  122776. 6, 8,10,16, 6, 7,10,16, 8, 8,11,16,14,16,16,16,
  122777. 10,11,14,16, 9, 9,11,16,10,10,11,16,16,16,16,16,
  122778. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122779. 16,16,16,16,15,16,16,16,16,16,16,16,16,16,16,16,
  122780. 12,16,15,16,12,14,16,16,16,16,16,16,16,16,16,16,
  122781. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122782. 16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,16,
  122783. };
  122784. static static_codebook _huff_book_line_2048x27_class3 = {
  122785. 1, 256,
  122786. _huff_lengthlist_line_2048x27_class3,
  122787. 0, 0, 0, 0, 0,
  122788. NULL,
  122789. NULL,
  122790. NULL,
  122791. NULL,
  122792. 0
  122793. };
  122794. static long _huff_lengthlist_line_2048x27_class4[] = {
  122795. 2, 4, 7,13, 4, 5, 7,15, 8, 7,10,16,16,14,16,16,
  122796. 2, 4, 7,16, 3, 4, 7,14, 8, 8,10,16,16,16,15,16,
  122797. 6, 8,11,16, 7, 7, 9,16,11, 9,13,16,16,16,15,16,
  122798. 16,16,16,16,14,16,16,16,16,16,16,16,16,16,16,16,
  122799. };
  122800. static static_codebook _huff_book_line_2048x27_class4 = {
  122801. 1, 64,
  122802. _huff_lengthlist_line_2048x27_class4,
  122803. 0, 0, 0, 0, 0,
  122804. NULL,
  122805. NULL,
  122806. NULL,
  122807. NULL,
  122808. 0
  122809. };
  122810. static long _huff_lengthlist_line_2048x27_0sub0[] = {
  122811. 5, 5, 5, 5, 5, 5, 6, 5, 6, 5, 6, 5, 6, 5, 6, 5,
  122812. 6, 5, 7, 5, 7, 5, 7, 5, 8, 5, 8, 5, 8, 5, 9, 5,
  122813. 9, 6,10, 6,10, 6,11, 6,11, 6,11, 6,11, 6,11, 6,
  122814. 11, 6,11, 6,12, 7,11, 7,11, 7,11, 7,11, 7,10, 7,
  122815. 11, 7,11, 7,12, 7,11, 8,11, 8,11, 8,11, 8,13, 8,
  122816. 12, 9,11, 9,11, 9,11,10,12,10,12, 9,12,10,12,11,
  122817. 14,12,16,12,12,11,14,16,17,17,17,17,17,17,17,17,
  122818. 17,17,17,17,17,17,17,17,17,17,17,17,16,16,16,16,
  122819. };
  122820. static static_codebook _huff_book_line_2048x27_0sub0 = {
  122821. 1, 128,
  122822. _huff_lengthlist_line_2048x27_0sub0,
  122823. 0, 0, 0, 0, 0,
  122824. NULL,
  122825. NULL,
  122826. NULL,
  122827. NULL,
  122828. 0
  122829. };
  122830. static long _huff_lengthlist_line_2048x27_1sub0[] = {
  122831. 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5,
  122832. 5, 5, 6, 6, 6, 6, 6, 6, 7, 6, 7, 6, 7, 6, 7, 6,
  122833. };
  122834. static static_codebook _huff_book_line_2048x27_1sub0 = {
  122835. 1, 32,
  122836. _huff_lengthlist_line_2048x27_1sub0,
  122837. 0, 0, 0, 0, 0,
  122838. NULL,
  122839. NULL,
  122840. NULL,
  122841. NULL,
  122842. 0
  122843. };
  122844. static long _huff_lengthlist_line_2048x27_1sub1[] = {
  122845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122847. 6, 5, 7, 5, 7, 4, 7, 4, 8, 4, 8, 4, 8, 4, 8, 3,
  122848. 8, 4, 9, 4, 9, 4, 9, 4, 9, 4, 9, 5, 9, 5, 9, 6,
  122849. 9, 7, 9, 8, 9, 9, 9,10, 9,11, 9,14, 9,15,10,15,
  122850. 10,15,10,15,10,15,11,15,10,14,12,14,11,14,13,14,
  122851. 13,15,15,15,12,15,15,15,13,15,13,15,13,15,15,15,
  122852. 15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,14,
  122853. };
  122854. static static_codebook _huff_book_line_2048x27_1sub1 = {
  122855. 1, 128,
  122856. _huff_lengthlist_line_2048x27_1sub1,
  122857. 0, 0, 0, 0, 0,
  122858. NULL,
  122859. NULL,
  122860. NULL,
  122861. NULL,
  122862. 0
  122863. };
  122864. static long _huff_lengthlist_line_2048x27_2sub0[] = {
  122865. 2, 4, 5, 4, 5, 4, 5, 4, 5, 5, 5, 5, 5, 5, 6, 5,
  122866. 6, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  122867. };
  122868. static static_codebook _huff_book_line_2048x27_2sub0 = {
  122869. 1, 32,
  122870. _huff_lengthlist_line_2048x27_2sub0,
  122871. 0, 0, 0, 0, 0,
  122872. NULL,
  122873. NULL,
  122874. NULL,
  122875. NULL,
  122876. 0
  122877. };
  122878. static long _huff_lengthlist_line_2048x27_2sub1[] = {
  122879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122881. 3, 4, 3, 4, 3, 4, 4, 5, 4, 5, 5, 5, 6, 6, 6, 7,
  122882. 6, 8, 6, 8, 6, 9, 7,10, 7,10, 7,10, 7,12, 7,12,
  122883. 7,12, 9,12,11,12,10,12,10,12,11,12,12,12,10,12,
  122884. 10,12,10,12, 9,12,11,12,12,12,12,12,11,12,11,12,
  122885. 12,12,12,12,12,12,12,12,10,10,12,12,12,12,12,10,
  122886. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  122887. };
  122888. static static_codebook _huff_book_line_2048x27_2sub1 = {
  122889. 1, 128,
  122890. _huff_lengthlist_line_2048x27_2sub1,
  122891. 0, 0, 0, 0, 0,
  122892. NULL,
  122893. NULL,
  122894. NULL,
  122895. NULL,
  122896. 0
  122897. };
  122898. static long _huff_lengthlist_line_2048x27_3sub1[] = {
  122899. 0, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4,
  122900. 5, 5,
  122901. };
  122902. static static_codebook _huff_book_line_2048x27_3sub1 = {
  122903. 1, 18,
  122904. _huff_lengthlist_line_2048x27_3sub1,
  122905. 0, 0, 0, 0, 0,
  122906. NULL,
  122907. NULL,
  122908. NULL,
  122909. NULL,
  122910. 0
  122911. };
  122912. static long _huff_lengthlist_line_2048x27_3sub2[] = {
  122913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122914. 0, 0, 3, 3, 3, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 6,
  122915. 6, 7, 6, 7, 6, 8, 6, 9, 7, 9, 7, 9, 9,11, 9,12,
  122916. 10,12,
  122917. };
  122918. static static_codebook _huff_book_line_2048x27_3sub2 = {
  122919. 1, 50,
  122920. _huff_lengthlist_line_2048x27_3sub2,
  122921. 0, 0, 0, 0, 0,
  122922. NULL,
  122923. NULL,
  122924. NULL,
  122925. NULL,
  122926. 0
  122927. };
  122928. static long _huff_lengthlist_line_2048x27_3sub3[] = {
  122929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122932. 0, 0, 3, 6, 3, 7, 3, 7, 5, 7, 7, 7, 7, 7, 6, 7,
  122933. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122934. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122935. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122936. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122937. };
  122938. static static_codebook _huff_book_line_2048x27_3sub3 = {
  122939. 1, 128,
  122940. _huff_lengthlist_line_2048x27_3sub3,
  122941. 0, 0, 0, 0, 0,
  122942. NULL,
  122943. NULL,
  122944. NULL,
  122945. NULL,
  122946. 0
  122947. };
  122948. static long _huff_lengthlist_line_2048x27_4sub1[] = {
  122949. 0, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 4, 5, 4, 5, 4,
  122950. 4, 5,
  122951. };
  122952. static static_codebook _huff_book_line_2048x27_4sub1 = {
  122953. 1, 18,
  122954. _huff_lengthlist_line_2048x27_4sub1,
  122955. 0, 0, 0, 0, 0,
  122956. NULL,
  122957. NULL,
  122958. NULL,
  122959. NULL,
  122960. 0
  122961. };
  122962. static long _huff_lengthlist_line_2048x27_4sub2[] = {
  122963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122964. 0, 0, 3, 2, 4, 3, 4, 4, 4, 5, 5, 6, 5, 6, 5, 7,
  122965. 6, 6, 6, 7, 7, 7, 8, 9, 9, 9,12,10,11,10,10,12,
  122966. 10,10,
  122967. };
  122968. static static_codebook _huff_book_line_2048x27_4sub2 = {
  122969. 1, 50,
  122970. _huff_lengthlist_line_2048x27_4sub2,
  122971. 0, 0, 0, 0, 0,
  122972. NULL,
  122973. NULL,
  122974. NULL,
  122975. NULL,
  122976. 0
  122977. };
  122978. static long _huff_lengthlist_line_2048x27_4sub3[] = {
  122979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  122982. 0, 0, 3, 6, 5, 7, 5, 7, 7, 7, 7, 7, 5, 7, 5, 7,
  122983. 5, 7, 5, 7, 7, 7, 7, 7, 4, 7, 7, 7, 7, 7, 7, 7,
  122984. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122985. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  122986. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  122987. };
  122988. static static_codebook _huff_book_line_2048x27_4sub3 = {
  122989. 1, 128,
  122990. _huff_lengthlist_line_2048x27_4sub3,
  122991. 0, 0, 0, 0, 0,
  122992. NULL,
  122993. NULL,
  122994. NULL,
  122995. NULL,
  122996. 0
  122997. };
  122998. static long _huff_lengthlist_line_256x4low_class0[] = {
  122999. 4, 5, 6,11, 5, 5, 6,10, 7, 7, 6, 6,14,13, 9, 9,
  123000. 6, 6, 6,10, 6, 6, 6, 9, 8, 7, 7, 9,14,12, 8,11,
  123001. 8, 7, 7,11, 8, 8, 7,11, 9, 9, 7, 9,13,11, 9,13,
  123002. 19,19,18,19,15,16,16,19,11,11,10,13,10,10, 9,15,
  123003. 5, 5, 6,13, 6, 6, 6,11, 8, 7, 6, 7,14,11,10,11,
  123004. 6, 6, 6,12, 7, 6, 6,11, 8, 7, 7,11,13,11, 9,11,
  123005. 9, 7, 6,12, 8, 7, 6,12, 9, 8, 8,11,13,10, 7,13,
  123006. 19,19,17,19,17,14,14,19,12,10, 8,12,13,10, 9,16,
  123007. 7, 8, 7,12, 7, 7, 7,11, 8, 7, 7, 8,12,12,11,11,
  123008. 8, 8, 7,12, 8, 7, 6,11, 8, 7, 7,10,10,11,10,11,
  123009. 9, 8, 8,13, 9, 8, 7,12,10, 9, 7,11, 9, 8, 7,11,
  123010. 18,18,15,18,18,16,17,18,15,11,10,18,11, 9, 9,18,
  123011. 16,16,13,16,12,11,10,16,12,11, 9, 6,15,12,11,13,
  123012. 16,16,14,14,13,11,12,16,12, 9, 9,13,13,10,10,12,
  123013. 17,18,17,17,14,15,14,16,14,12,14,15,12,10,11,12,
  123014. 18,18,18,18,18,18,18,18,18,12,13,18,16,11, 9,18,
  123015. };
  123016. static static_codebook _huff_book_line_256x4low_class0 = {
  123017. 1, 256,
  123018. _huff_lengthlist_line_256x4low_class0,
  123019. 0, 0, 0, 0, 0,
  123020. NULL,
  123021. NULL,
  123022. NULL,
  123023. NULL,
  123024. 0
  123025. };
  123026. static long _huff_lengthlist_line_256x4low_0sub0[] = {
  123027. 1, 3, 2, 3,
  123028. };
  123029. static static_codebook _huff_book_line_256x4low_0sub0 = {
  123030. 1, 4,
  123031. _huff_lengthlist_line_256x4low_0sub0,
  123032. 0, 0, 0, 0, 0,
  123033. NULL,
  123034. NULL,
  123035. NULL,
  123036. NULL,
  123037. 0
  123038. };
  123039. static long _huff_lengthlist_line_256x4low_0sub1[] = {
  123040. 0, 0, 0, 0, 2, 3, 2, 3, 3, 3,
  123041. };
  123042. static static_codebook _huff_book_line_256x4low_0sub1 = {
  123043. 1, 10,
  123044. _huff_lengthlist_line_256x4low_0sub1,
  123045. 0, 0, 0, 0, 0,
  123046. NULL,
  123047. NULL,
  123048. NULL,
  123049. NULL,
  123050. 0
  123051. };
  123052. static long _huff_lengthlist_line_256x4low_0sub2[] = {
  123053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 3, 4,
  123054. 4, 4, 4, 4, 5, 5, 5, 6, 6,
  123055. };
  123056. static static_codebook _huff_book_line_256x4low_0sub2 = {
  123057. 1, 25,
  123058. _huff_lengthlist_line_256x4low_0sub2,
  123059. 0, 0, 0, 0, 0,
  123060. NULL,
  123061. NULL,
  123062. NULL,
  123063. NULL,
  123064. 0
  123065. };
  123066. static long _huff_lengthlist_line_256x4low_0sub3[] = {
  123067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 4, 2, 4, 3, 5, 4,
  123069. 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 7, 7, 8, 6, 9,
  123070. 7,12,11,16,13,16,12,15,13,15,12,14,12,15,15,15,
  123071. };
  123072. static static_codebook _huff_book_line_256x4low_0sub3 = {
  123073. 1, 64,
  123074. _huff_lengthlist_line_256x4low_0sub3,
  123075. 0, 0, 0, 0, 0,
  123076. NULL,
  123077. NULL,
  123078. NULL,
  123079. NULL,
  123080. 0
  123081. };
  123082. /********* End of inlined file: floor_books.h *********/
  123083. static static_codebook *_floor_128x4_books[]={
  123084. &_huff_book_line_128x4_class0,
  123085. &_huff_book_line_128x4_0sub0,
  123086. &_huff_book_line_128x4_0sub1,
  123087. &_huff_book_line_128x4_0sub2,
  123088. &_huff_book_line_128x4_0sub3,
  123089. };
  123090. static static_codebook *_floor_256x4_books[]={
  123091. &_huff_book_line_256x4_class0,
  123092. &_huff_book_line_256x4_0sub0,
  123093. &_huff_book_line_256x4_0sub1,
  123094. &_huff_book_line_256x4_0sub2,
  123095. &_huff_book_line_256x4_0sub3,
  123096. };
  123097. static static_codebook *_floor_128x7_books[]={
  123098. &_huff_book_line_128x7_class0,
  123099. &_huff_book_line_128x7_class1,
  123100. &_huff_book_line_128x7_0sub1,
  123101. &_huff_book_line_128x7_0sub2,
  123102. &_huff_book_line_128x7_0sub3,
  123103. &_huff_book_line_128x7_1sub1,
  123104. &_huff_book_line_128x7_1sub2,
  123105. &_huff_book_line_128x7_1sub3,
  123106. };
  123107. static static_codebook *_floor_256x7_books[]={
  123108. &_huff_book_line_256x7_class0,
  123109. &_huff_book_line_256x7_class1,
  123110. &_huff_book_line_256x7_0sub1,
  123111. &_huff_book_line_256x7_0sub2,
  123112. &_huff_book_line_256x7_0sub3,
  123113. &_huff_book_line_256x7_1sub1,
  123114. &_huff_book_line_256x7_1sub2,
  123115. &_huff_book_line_256x7_1sub3,
  123116. };
  123117. static static_codebook *_floor_128x11_books[]={
  123118. &_huff_book_line_128x11_class1,
  123119. &_huff_book_line_128x11_class2,
  123120. &_huff_book_line_128x11_class3,
  123121. &_huff_book_line_128x11_0sub0,
  123122. &_huff_book_line_128x11_1sub0,
  123123. &_huff_book_line_128x11_1sub1,
  123124. &_huff_book_line_128x11_2sub1,
  123125. &_huff_book_line_128x11_2sub2,
  123126. &_huff_book_line_128x11_2sub3,
  123127. &_huff_book_line_128x11_3sub1,
  123128. &_huff_book_line_128x11_3sub2,
  123129. &_huff_book_line_128x11_3sub3,
  123130. };
  123131. static static_codebook *_floor_128x17_books[]={
  123132. &_huff_book_line_128x17_class1,
  123133. &_huff_book_line_128x17_class2,
  123134. &_huff_book_line_128x17_class3,
  123135. &_huff_book_line_128x17_0sub0,
  123136. &_huff_book_line_128x17_1sub0,
  123137. &_huff_book_line_128x17_1sub1,
  123138. &_huff_book_line_128x17_2sub1,
  123139. &_huff_book_line_128x17_2sub2,
  123140. &_huff_book_line_128x17_2sub3,
  123141. &_huff_book_line_128x17_3sub1,
  123142. &_huff_book_line_128x17_3sub2,
  123143. &_huff_book_line_128x17_3sub3,
  123144. };
  123145. static static_codebook *_floor_256x4low_books[]={
  123146. &_huff_book_line_256x4low_class0,
  123147. &_huff_book_line_256x4low_0sub0,
  123148. &_huff_book_line_256x4low_0sub1,
  123149. &_huff_book_line_256x4low_0sub2,
  123150. &_huff_book_line_256x4low_0sub3,
  123151. };
  123152. static static_codebook *_floor_1024x27_books[]={
  123153. &_huff_book_line_1024x27_class1,
  123154. &_huff_book_line_1024x27_class2,
  123155. &_huff_book_line_1024x27_class3,
  123156. &_huff_book_line_1024x27_class4,
  123157. &_huff_book_line_1024x27_0sub0,
  123158. &_huff_book_line_1024x27_1sub0,
  123159. &_huff_book_line_1024x27_1sub1,
  123160. &_huff_book_line_1024x27_2sub0,
  123161. &_huff_book_line_1024x27_2sub1,
  123162. &_huff_book_line_1024x27_3sub1,
  123163. &_huff_book_line_1024x27_3sub2,
  123164. &_huff_book_line_1024x27_3sub3,
  123165. &_huff_book_line_1024x27_4sub1,
  123166. &_huff_book_line_1024x27_4sub2,
  123167. &_huff_book_line_1024x27_4sub3,
  123168. };
  123169. static static_codebook *_floor_2048x27_books[]={
  123170. &_huff_book_line_2048x27_class1,
  123171. &_huff_book_line_2048x27_class2,
  123172. &_huff_book_line_2048x27_class3,
  123173. &_huff_book_line_2048x27_class4,
  123174. &_huff_book_line_2048x27_0sub0,
  123175. &_huff_book_line_2048x27_1sub0,
  123176. &_huff_book_line_2048x27_1sub1,
  123177. &_huff_book_line_2048x27_2sub0,
  123178. &_huff_book_line_2048x27_2sub1,
  123179. &_huff_book_line_2048x27_3sub1,
  123180. &_huff_book_line_2048x27_3sub2,
  123181. &_huff_book_line_2048x27_3sub3,
  123182. &_huff_book_line_2048x27_4sub1,
  123183. &_huff_book_line_2048x27_4sub2,
  123184. &_huff_book_line_2048x27_4sub3,
  123185. };
  123186. static static_codebook *_floor_512x17_books[]={
  123187. &_huff_book_line_512x17_class1,
  123188. &_huff_book_line_512x17_class2,
  123189. &_huff_book_line_512x17_class3,
  123190. &_huff_book_line_512x17_0sub0,
  123191. &_huff_book_line_512x17_1sub0,
  123192. &_huff_book_line_512x17_1sub1,
  123193. &_huff_book_line_512x17_2sub1,
  123194. &_huff_book_line_512x17_2sub2,
  123195. &_huff_book_line_512x17_2sub3,
  123196. &_huff_book_line_512x17_3sub1,
  123197. &_huff_book_line_512x17_3sub2,
  123198. &_huff_book_line_512x17_3sub3,
  123199. };
  123200. static static_codebook **_floor_books[10]={
  123201. _floor_128x4_books,
  123202. _floor_256x4_books,
  123203. _floor_128x7_books,
  123204. _floor_256x7_books,
  123205. _floor_128x11_books,
  123206. _floor_128x17_books,
  123207. _floor_256x4low_books,
  123208. _floor_1024x27_books,
  123209. _floor_2048x27_books,
  123210. _floor_512x17_books,
  123211. };
  123212. static vorbis_info_floor1 _floor[10]={
  123213. /* 128 x 4 */
  123214. {
  123215. 1,{0},{4},{2},{0},
  123216. {{1,2,3,4}},
  123217. 4,{0,128, 33,8,16,70},
  123218. 60,30,500, 1.,18., -1
  123219. },
  123220. /* 256 x 4 */
  123221. {
  123222. 1,{0},{4},{2},{0},
  123223. {{1,2,3,4}},
  123224. 4,{0,256, 66,16,32,140},
  123225. 60,30,500, 1.,18., -1
  123226. },
  123227. /* 128 x 7 */
  123228. {
  123229. 2,{0,1},{3,4},{2,2},{0,1},
  123230. {{-1,2,3,4},{-1,5,6,7}},
  123231. 4,{0,128, 14,4,58, 2,8,28,90},
  123232. 60,30,500, 1.,18., -1
  123233. },
  123234. /* 256 x 7 */
  123235. {
  123236. 2,{0,1},{3,4},{2,2},{0,1},
  123237. {{-1,2,3,4},{-1,5,6,7}},
  123238. 4,{0,256, 28,8,116, 4,16,56,180},
  123239. 60,30,500, 1.,18., -1
  123240. },
  123241. /* 128 x 11 */
  123242. {
  123243. 4,{0,1,2,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  123244. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  123245. 2,{0,128, 8,33, 4,16,70, 2,6,12, 23,46,90},
  123246. 60,30,500, 1,18., -1
  123247. },
  123248. /* 128 x 17 */
  123249. {
  123250. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  123251. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  123252. 2,{0,128, 12,46, 4,8,16, 23,33,70, 2,6,10, 14,19,28, 39,58,90},
  123253. 60,30,500, 1,18., -1
  123254. },
  123255. /* 256 x 4 (low bitrate version) */
  123256. {
  123257. 1,{0},{4},{2},{0},
  123258. {{1,2,3,4}},
  123259. 4,{0,256, 66,16,32,140},
  123260. 60,30,500, 1.,18., -1
  123261. },
  123262. /* 1024 x 27 */
  123263. {
  123264. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  123265. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  123266. 2,{0,1024, 93,23,372, 6,46,186,750, 14,33,65, 130,260,556,
  123267. 3,10,18,28, 39,55,79,111, 158,220,312, 464,650,850},
  123268. 60,30,500, 3,18., -1 /* lowpass */
  123269. },
  123270. /* 2048 x 27 */
  123271. {
  123272. 8,{0,1,2,2,3,3,4,4},{3,4,3,4,3},{0,1,1,2,2},{-1,0,1,2,3},
  123273. {{4},{5,6},{7,8},{-1,9,10,11},{-1,12,13,14}},
  123274. 2,{0,2048, 186,46,744, 12,92,372,1500, 28,66,130, 260,520,1112,
  123275. 6,20,36,56, 78,110,158,222, 316,440,624, 928,1300,1700},
  123276. 60,30,500, 3,18., -1 /* lowpass */
  123277. },
  123278. /* 512 x 17 */
  123279. {
  123280. 6,{0,1,1,2,3,3},{2,3,3,3},{0,1,2,2},{-1,0,1,2},
  123281. {{3},{4,5},{-1,6,7,8},{-1,9,10,11}},
  123282. 2,{0,512, 46,186, 16,33,65, 93,130,278,
  123283. 7,23,39, 55,79,110, 156,232,360},
  123284. 60,30,500, 1,18., -1 /* lowpass! */
  123285. },
  123286. };
  123287. /********* End of inlined file: floor_all.h *********/
  123288. /********* Start of inlined file: residue_44.h *********/
  123289. /********* Start of inlined file: res_books_stereo.h *********/
  123290. static long _vq_quantlist__16c0_s_p1_0[] = {
  123291. 1,
  123292. 0,
  123293. 2,
  123294. };
  123295. static long _vq_lengthlist__16c0_s_p1_0[] = {
  123296. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  123297. 0, 0, 5, 7, 7, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0,
  123302. 0, 0, 0, 7, 9,10, 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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  123307. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 8, 0, 0, 0, 0,
  123342. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0,
  123347. 0, 0, 0, 9, 9,12, 0, 0, 0, 0, 0, 0,10,12,11, 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, 7,10,10, 0, 0,
  123352. 0, 0, 0, 0, 9,12,10, 0, 0, 0, 0, 0, 0,10,11,12,
  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, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  123388. 0, 0, 0, 0, 8,10,10, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,12,11, 0,
  123393. 0, 0, 0, 0, 0, 9,10,12, 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, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,12,
  123398. 0, 0, 0, 0, 0, 0, 9,12, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123706. 0,
  123707. };
  123708. static float _vq_quantthresh__16c0_s_p1_0[] = {
  123709. -0.5, 0.5,
  123710. };
  123711. static long _vq_quantmap__16c0_s_p1_0[] = {
  123712. 1, 0, 2,
  123713. };
  123714. static encode_aux_threshmatch _vq_auxt__16c0_s_p1_0 = {
  123715. _vq_quantthresh__16c0_s_p1_0,
  123716. _vq_quantmap__16c0_s_p1_0,
  123717. 3,
  123718. 3
  123719. };
  123720. static static_codebook _16c0_s_p1_0 = {
  123721. 8, 6561,
  123722. _vq_lengthlist__16c0_s_p1_0,
  123723. 1, -535822336, 1611661312, 2, 0,
  123724. _vq_quantlist__16c0_s_p1_0,
  123725. NULL,
  123726. &_vq_auxt__16c0_s_p1_0,
  123727. NULL,
  123728. 0
  123729. };
  123730. static long _vq_quantlist__16c0_s_p2_0[] = {
  123731. 2,
  123732. 1,
  123733. 3,
  123734. 0,
  123735. 4,
  123736. };
  123737. static long _vq_lengthlist__16c0_s_p2_0[] = {
  123738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123777. 0,
  123778. };
  123779. static float _vq_quantthresh__16c0_s_p2_0[] = {
  123780. -1.5, -0.5, 0.5, 1.5,
  123781. };
  123782. static long _vq_quantmap__16c0_s_p2_0[] = {
  123783. 3, 1, 0, 2, 4,
  123784. };
  123785. static encode_aux_threshmatch _vq_auxt__16c0_s_p2_0 = {
  123786. _vq_quantthresh__16c0_s_p2_0,
  123787. _vq_quantmap__16c0_s_p2_0,
  123788. 5,
  123789. 5
  123790. };
  123791. static static_codebook _16c0_s_p2_0 = {
  123792. 4, 625,
  123793. _vq_lengthlist__16c0_s_p2_0,
  123794. 1, -533725184, 1611661312, 3, 0,
  123795. _vq_quantlist__16c0_s_p2_0,
  123796. NULL,
  123797. &_vq_auxt__16c0_s_p2_0,
  123798. NULL,
  123799. 0
  123800. };
  123801. static long _vq_quantlist__16c0_s_p3_0[] = {
  123802. 2,
  123803. 1,
  123804. 3,
  123805. 0,
  123806. 4,
  123807. };
  123808. static long _vq_lengthlist__16c0_s_p3_0[] = {
  123809. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 7, 6, 0, 0,
  123811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123812. 0, 0, 4, 6, 6, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  123814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123815. 0, 0, 0, 0, 6, 6, 6, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  123816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123848. 0,
  123849. };
  123850. static float _vq_quantthresh__16c0_s_p3_0[] = {
  123851. -1.5, -0.5, 0.5, 1.5,
  123852. };
  123853. static long _vq_quantmap__16c0_s_p3_0[] = {
  123854. 3, 1, 0, 2, 4,
  123855. };
  123856. static encode_aux_threshmatch _vq_auxt__16c0_s_p3_0 = {
  123857. _vq_quantthresh__16c0_s_p3_0,
  123858. _vq_quantmap__16c0_s_p3_0,
  123859. 5,
  123860. 5
  123861. };
  123862. static static_codebook _16c0_s_p3_0 = {
  123863. 4, 625,
  123864. _vq_lengthlist__16c0_s_p3_0,
  123865. 1, -533725184, 1611661312, 3, 0,
  123866. _vq_quantlist__16c0_s_p3_0,
  123867. NULL,
  123868. &_vq_auxt__16c0_s_p3_0,
  123869. NULL,
  123870. 0
  123871. };
  123872. static long _vq_quantlist__16c0_s_p4_0[] = {
  123873. 4,
  123874. 3,
  123875. 5,
  123876. 2,
  123877. 6,
  123878. 1,
  123879. 7,
  123880. 0,
  123881. 8,
  123882. };
  123883. static long _vq_lengthlist__16c0_s_p4_0[] = {
  123884. 1, 3, 2, 7, 8, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  123885. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  123886. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  123887. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  123888. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  123889. 0,
  123890. };
  123891. static float _vq_quantthresh__16c0_s_p4_0[] = {
  123892. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123893. };
  123894. static long _vq_quantmap__16c0_s_p4_0[] = {
  123895. 7, 5, 3, 1, 0, 2, 4, 6,
  123896. 8,
  123897. };
  123898. static encode_aux_threshmatch _vq_auxt__16c0_s_p4_0 = {
  123899. _vq_quantthresh__16c0_s_p4_0,
  123900. _vq_quantmap__16c0_s_p4_0,
  123901. 9,
  123902. 9
  123903. };
  123904. static static_codebook _16c0_s_p4_0 = {
  123905. 2, 81,
  123906. _vq_lengthlist__16c0_s_p4_0,
  123907. 1, -531628032, 1611661312, 4, 0,
  123908. _vq_quantlist__16c0_s_p4_0,
  123909. NULL,
  123910. &_vq_auxt__16c0_s_p4_0,
  123911. NULL,
  123912. 0
  123913. };
  123914. static long _vq_quantlist__16c0_s_p5_0[] = {
  123915. 4,
  123916. 3,
  123917. 5,
  123918. 2,
  123919. 6,
  123920. 1,
  123921. 7,
  123922. 0,
  123923. 8,
  123924. };
  123925. static long _vq_lengthlist__16c0_s_p5_0[] = {
  123926. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  123927. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 8, 0, 0, 0, 7, 7,
  123928. 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0, 0, 0,
  123929. 8, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  123930. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  123931. 10,
  123932. };
  123933. static float _vq_quantthresh__16c0_s_p5_0[] = {
  123934. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  123935. };
  123936. static long _vq_quantmap__16c0_s_p5_0[] = {
  123937. 7, 5, 3, 1, 0, 2, 4, 6,
  123938. 8,
  123939. };
  123940. static encode_aux_threshmatch _vq_auxt__16c0_s_p5_0 = {
  123941. _vq_quantthresh__16c0_s_p5_0,
  123942. _vq_quantmap__16c0_s_p5_0,
  123943. 9,
  123944. 9
  123945. };
  123946. static static_codebook _16c0_s_p5_0 = {
  123947. 2, 81,
  123948. _vq_lengthlist__16c0_s_p5_0,
  123949. 1, -531628032, 1611661312, 4, 0,
  123950. _vq_quantlist__16c0_s_p5_0,
  123951. NULL,
  123952. &_vq_auxt__16c0_s_p5_0,
  123953. NULL,
  123954. 0
  123955. };
  123956. static long _vq_quantlist__16c0_s_p6_0[] = {
  123957. 8,
  123958. 7,
  123959. 9,
  123960. 6,
  123961. 10,
  123962. 5,
  123963. 11,
  123964. 4,
  123965. 12,
  123966. 3,
  123967. 13,
  123968. 2,
  123969. 14,
  123970. 1,
  123971. 15,
  123972. 0,
  123973. 16,
  123974. };
  123975. static long _vq_lengthlist__16c0_s_p6_0[] = {
  123976. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  123977. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  123978. 11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  123979. 11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  123980. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  123981. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  123982. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  123983. 10,11,11,12,12,12,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  123984. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10,10,10,
  123985. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  123986. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  123987. 9,10,10,11,11,12,12,13,13,13,14, 0, 0, 0, 0, 0,
  123988. 10,10,10,11,11,11,12,12,13,13,13,14, 0, 0, 0, 0,
  123989. 0, 0, 0,10,10,11,11,12,12,13,13,14,14, 0, 0, 0,
  123990. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  123991. 0, 0, 0, 0, 0,11,11,12,12,12,13,13,14,15,14, 0,
  123992. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,14,14,15,
  123993. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,13,14,
  123994. 14,
  123995. };
  123996. static float _vq_quantthresh__16c0_s_p6_0[] = {
  123997. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  123998. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  123999. };
  124000. static long _vq_quantmap__16c0_s_p6_0[] = {
  124001. 15, 13, 11, 9, 7, 5, 3, 1,
  124002. 0, 2, 4, 6, 8, 10, 12, 14,
  124003. 16,
  124004. };
  124005. static encode_aux_threshmatch _vq_auxt__16c0_s_p6_0 = {
  124006. _vq_quantthresh__16c0_s_p6_0,
  124007. _vq_quantmap__16c0_s_p6_0,
  124008. 17,
  124009. 17
  124010. };
  124011. static static_codebook _16c0_s_p6_0 = {
  124012. 2, 289,
  124013. _vq_lengthlist__16c0_s_p6_0,
  124014. 1, -529530880, 1611661312, 5, 0,
  124015. _vq_quantlist__16c0_s_p6_0,
  124016. NULL,
  124017. &_vq_auxt__16c0_s_p6_0,
  124018. NULL,
  124019. 0
  124020. };
  124021. static long _vq_quantlist__16c0_s_p7_0[] = {
  124022. 1,
  124023. 0,
  124024. 2,
  124025. };
  124026. static long _vq_lengthlist__16c0_s_p7_0[] = {
  124027. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,11,10,10,11,
  124028. 11,10, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  124029. 11,11,11,10, 6, 9, 9,11,12,12,11, 9, 9, 6, 9,10,
  124030. 11,12,12,11, 9,10, 7,11,11,11,11,11,12,13,12, 6,
  124031. 9,10,11,10,10,12,13,13, 6,10, 9,11,10,10,11,12,
  124032. 13,
  124033. };
  124034. static float _vq_quantthresh__16c0_s_p7_0[] = {
  124035. -5.5, 5.5,
  124036. };
  124037. static long _vq_quantmap__16c0_s_p7_0[] = {
  124038. 1, 0, 2,
  124039. };
  124040. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_0 = {
  124041. _vq_quantthresh__16c0_s_p7_0,
  124042. _vq_quantmap__16c0_s_p7_0,
  124043. 3,
  124044. 3
  124045. };
  124046. static static_codebook _16c0_s_p7_0 = {
  124047. 4, 81,
  124048. _vq_lengthlist__16c0_s_p7_0,
  124049. 1, -529137664, 1618345984, 2, 0,
  124050. _vq_quantlist__16c0_s_p7_0,
  124051. NULL,
  124052. &_vq_auxt__16c0_s_p7_0,
  124053. NULL,
  124054. 0
  124055. };
  124056. static long _vq_quantlist__16c0_s_p7_1[] = {
  124057. 5,
  124058. 4,
  124059. 6,
  124060. 3,
  124061. 7,
  124062. 2,
  124063. 8,
  124064. 1,
  124065. 9,
  124066. 0,
  124067. 10,
  124068. };
  124069. static long _vq_lengthlist__16c0_s_p7_1[] = {
  124070. 1, 3, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7,
  124071. 8, 8, 8, 9, 9, 9,10,10,10, 6, 7, 8, 8, 8, 8, 9,
  124072. 8,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10, 7,
  124073. 7, 8, 8, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9, 9,
  124074. 9, 9,11,11,11, 8, 8, 9, 9, 9, 9, 9,10,10,11,11,
  124075. 9, 9, 9, 9, 9, 9, 9,10,11,11,11,10,11, 9, 9, 9,
  124076. 9,10, 9,11,11,11,10,11,10,10, 9, 9,10,10,11,11,
  124077. 11,11,11, 9, 9, 9, 9,10,10,
  124078. };
  124079. static float _vq_quantthresh__16c0_s_p7_1[] = {
  124080. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  124081. 3.5, 4.5,
  124082. };
  124083. static long _vq_quantmap__16c0_s_p7_1[] = {
  124084. 9, 7, 5, 3, 1, 0, 2, 4,
  124085. 6, 8, 10,
  124086. };
  124087. static encode_aux_threshmatch _vq_auxt__16c0_s_p7_1 = {
  124088. _vq_quantthresh__16c0_s_p7_1,
  124089. _vq_quantmap__16c0_s_p7_1,
  124090. 11,
  124091. 11
  124092. };
  124093. static static_codebook _16c0_s_p7_1 = {
  124094. 2, 121,
  124095. _vq_lengthlist__16c0_s_p7_1,
  124096. 1, -531365888, 1611661312, 4, 0,
  124097. _vq_quantlist__16c0_s_p7_1,
  124098. NULL,
  124099. &_vq_auxt__16c0_s_p7_1,
  124100. NULL,
  124101. 0
  124102. };
  124103. static long _vq_quantlist__16c0_s_p8_0[] = {
  124104. 6,
  124105. 5,
  124106. 7,
  124107. 4,
  124108. 8,
  124109. 3,
  124110. 9,
  124111. 2,
  124112. 10,
  124113. 1,
  124114. 11,
  124115. 0,
  124116. 12,
  124117. };
  124118. static long _vq_lengthlist__16c0_s_p8_0[] = {
  124119. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8,10,10, 6, 5, 6,
  124120. 8, 8, 8, 8, 8, 8, 8, 9,10,10, 7, 6, 6, 8, 8, 8,
  124121. 8, 8, 8, 8, 8,10,10, 0, 8, 8, 8, 8, 9, 8, 9, 9,
  124122. 9,10,10,10, 0, 9, 8, 8, 8, 9, 9, 8, 8, 9, 9,10,
  124123. 10, 0,12,11, 8, 8, 9, 9, 9, 9,10,10,11,10, 0,12,
  124124. 13, 8, 8, 9,10, 9, 9,11,11,11,12, 0, 0, 0, 8, 8,
  124125. 8, 8,10, 9,12,13,12,14, 0, 0, 0, 8, 8, 8, 9,10,
  124126. 10,12,12,13,14, 0, 0, 0,13,13, 9, 9,11,11, 0, 0,
  124127. 14, 0, 0, 0, 0,14,14,10,10,12,11,12,14,14,14, 0,
  124128. 0, 0, 0, 0,11,11,13,13,14,13,14,14, 0, 0, 0, 0,
  124129. 0,12,13,13,12,13,14,14,14,
  124130. };
  124131. static float _vq_quantthresh__16c0_s_p8_0[] = {
  124132. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  124133. 12.5, 17.5, 22.5, 27.5,
  124134. };
  124135. static long _vq_quantmap__16c0_s_p8_0[] = {
  124136. 11, 9, 7, 5, 3, 1, 0, 2,
  124137. 4, 6, 8, 10, 12,
  124138. };
  124139. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_0 = {
  124140. _vq_quantthresh__16c0_s_p8_0,
  124141. _vq_quantmap__16c0_s_p8_0,
  124142. 13,
  124143. 13
  124144. };
  124145. static static_codebook _16c0_s_p8_0 = {
  124146. 2, 169,
  124147. _vq_lengthlist__16c0_s_p8_0,
  124148. 1, -526516224, 1616117760, 4, 0,
  124149. _vq_quantlist__16c0_s_p8_0,
  124150. NULL,
  124151. &_vq_auxt__16c0_s_p8_0,
  124152. NULL,
  124153. 0
  124154. };
  124155. static long _vq_quantlist__16c0_s_p8_1[] = {
  124156. 2,
  124157. 1,
  124158. 3,
  124159. 0,
  124160. 4,
  124161. };
  124162. static long _vq_lengthlist__16c0_s_p8_1[] = {
  124163. 1, 4, 3, 5, 5, 7, 7, 7, 6, 6, 7, 7, 7, 5, 5, 7,
  124164. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  124165. };
  124166. static float _vq_quantthresh__16c0_s_p8_1[] = {
  124167. -1.5, -0.5, 0.5, 1.5,
  124168. };
  124169. static long _vq_quantmap__16c0_s_p8_1[] = {
  124170. 3, 1, 0, 2, 4,
  124171. };
  124172. static encode_aux_threshmatch _vq_auxt__16c0_s_p8_1 = {
  124173. _vq_quantthresh__16c0_s_p8_1,
  124174. _vq_quantmap__16c0_s_p8_1,
  124175. 5,
  124176. 5
  124177. };
  124178. static static_codebook _16c0_s_p8_1 = {
  124179. 2, 25,
  124180. _vq_lengthlist__16c0_s_p8_1,
  124181. 1, -533725184, 1611661312, 3, 0,
  124182. _vq_quantlist__16c0_s_p8_1,
  124183. NULL,
  124184. &_vq_auxt__16c0_s_p8_1,
  124185. NULL,
  124186. 0
  124187. };
  124188. static long _vq_quantlist__16c0_s_p9_0[] = {
  124189. 1,
  124190. 0,
  124191. 2,
  124192. };
  124193. static long _vq_lengthlist__16c0_s_p9_0[] = {
  124194. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124195. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  124196. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  124197. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  124198. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  124199. 7,
  124200. };
  124201. static float _vq_quantthresh__16c0_s_p9_0[] = {
  124202. -157.5, 157.5,
  124203. };
  124204. static long _vq_quantmap__16c0_s_p9_0[] = {
  124205. 1, 0, 2,
  124206. };
  124207. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_0 = {
  124208. _vq_quantthresh__16c0_s_p9_0,
  124209. _vq_quantmap__16c0_s_p9_0,
  124210. 3,
  124211. 3
  124212. };
  124213. static static_codebook _16c0_s_p9_0 = {
  124214. 4, 81,
  124215. _vq_lengthlist__16c0_s_p9_0,
  124216. 1, -518803456, 1628680192, 2, 0,
  124217. _vq_quantlist__16c0_s_p9_0,
  124218. NULL,
  124219. &_vq_auxt__16c0_s_p9_0,
  124220. NULL,
  124221. 0
  124222. };
  124223. static long _vq_quantlist__16c0_s_p9_1[] = {
  124224. 7,
  124225. 6,
  124226. 8,
  124227. 5,
  124228. 9,
  124229. 4,
  124230. 10,
  124231. 3,
  124232. 11,
  124233. 2,
  124234. 12,
  124235. 1,
  124236. 13,
  124237. 0,
  124238. 14,
  124239. };
  124240. static long _vq_lengthlist__16c0_s_p9_1[] = {
  124241. 1, 5, 5, 5, 5, 9,11,11,10,10,10,10,10,10,10, 7,
  124242. 6, 6, 6, 6,10,10,10,10,10,10,10,10,10,10, 7, 6,
  124243. 6, 6, 6,10, 9,10,10,10,10,10,10,10,10,10, 7, 7,
  124244. 8, 9,10,10,10,10,10,10,10,10,10,10,10, 8, 7,10,
  124245. 10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124246. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124247. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124248. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124249. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124250. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124251. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124252. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124253. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124254. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  124255. 10,
  124256. };
  124257. static float _vq_quantthresh__16c0_s_p9_1[] = {
  124258. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  124259. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  124260. };
  124261. static long _vq_quantmap__16c0_s_p9_1[] = {
  124262. 13, 11, 9, 7, 5, 3, 1, 0,
  124263. 2, 4, 6, 8, 10, 12, 14,
  124264. };
  124265. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_1 = {
  124266. _vq_quantthresh__16c0_s_p9_1,
  124267. _vq_quantmap__16c0_s_p9_1,
  124268. 15,
  124269. 15
  124270. };
  124271. static static_codebook _16c0_s_p9_1 = {
  124272. 2, 225,
  124273. _vq_lengthlist__16c0_s_p9_1,
  124274. 1, -520986624, 1620377600, 4, 0,
  124275. _vq_quantlist__16c0_s_p9_1,
  124276. NULL,
  124277. &_vq_auxt__16c0_s_p9_1,
  124278. NULL,
  124279. 0
  124280. };
  124281. static long _vq_quantlist__16c0_s_p9_2[] = {
  124282. 10,
  124283. 9,
  124284. 11,
  124285. 8,
  124286. 12,
  124287. 7,
  124288. 13,
  124289. 6,
  124290. 14,
  124291. 5,
  124292. 15,
  124293. 4,
  124294. 16,
  124295. 3,
  124296. 17,
  124297. 2,
  124298. 18,
  124299. 1,
  124300. 19,
  124301. 0,
  124302. 20,
  124303. };
  124304. static long _vq_lengthlist__16c0_s_p9_2[] = {
  124305. 1, 5, 5, 7, 8, 8, 7, 9, 9, 9,12,12,11,12,12,10,
  124306. 10,11,12,12,12,11,12,12, 8, 9, 8, 7, 9,10,10,11,
  124307. 11,10,11,12,10,12,10,12,12,12,11,12,11, 9, 8, 8,
  124308. 9,10, 9, 8, 9,10,12,12,11,11,12,11,10,11,12,11,
  124309. 12,12, 8, 9, 9, 9,10,11,12,11,12,11,11,11,11,12,
  124310. 12,11,11,12,12,11,11, 9, 9, 8, 9, 9,11, 9, 9,10,
  124311. 9,11,11,11,11,12,11,11,10,12,12,12, 9,12,11,10,
  124312. 11,11,11,11,12,12,12,11,11,11,12,10,12,12,12,10,
  124313. 10, 9,10, 9,10,10, 9, 9, 9,10,10,12,10,11,11, 9,
  124314. 11,11,10,11,11,11,10,10,10, 9, 9,10,10, 9, 9,10,
  124315. 11,11,10,11,10,11,10,11,11,10,11,11,11,10, 9,10,
  124316. 10, 9,10, 9, 9,11, 9, 9,11,10,10,11,11,10,10,11,
  124317. 10,11, 8, 9,11,11,10, 9,10,11,11,10,11,11,10,10,
  124318. 10,11,10, 9,10,10,11, 9,10,10, 9,11,10,10,10,10,
  124319. 11,10,11,11, 9,11,10,11,10,10,11,11,10,10,10, 9,
  124320. 10,10,11,11,11, 9,10,10,10,10,10,11,10,10,10, 9,
  124321. 10,10,11,10,10,10,10,10, 9,10,11,10,10,10,10,11,
  124322. 11,11,10,10,10,10,10,11,10,11,10,11,10,10,10, 9,
  124323. 11,11,10,10,10,11,11,10,10,10,10,10,10,10,10,11,
  124324. 11, 9,10,10,10,11,10,11,10,10,10,11, 9,10,11,10,
  124325. 11,10,10, 9,10,10,10,11,10,11,10,10,10,10,10,11,
  124326. 11,10,11,11,10,10,11,11,10, 9, 9,10,10,10,10,10,
  124327. 9,11, 9,10,10,10,11,11,10,10,10,10,11,11,11,10,
  124328. 9, 9,10,10,11,10,10,10,10,10,11,11,11,10,10,10,
  124329. 11,11,11, 9,10,10,10,10, 9,10, 9,10,11,10,11,10,
  124330. 10,11,11,10,11,11,11,11,11,10,11,10,10,10, 9,11,
  124331. 11,10,11,11,11,11,11,11,11,11,11,10,11,10,10,10,
  124332. 10,11,10,10,11, 9,10,10,10,
  124333. };
  124334. static float _vq_quantthresh__16c0_s_p9_2[] = {
  124335. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  124336. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  124337. 6.5, 7.5, 8.5, 9.5,
  124338. };
  124339. static long _vq_quantmap__16c0_s_p9_2[] = {
  124340. 19, 17, 15, 13, 11, 9, 7, 5,
  124341. 3, 1, 0, 2, 4, 6, 8, 10,
  124342. 12, 14, 16, 18, 20,
  124343. };
  124344. static encode_aux_threshmatch _vq_auxt__16c0_s_p9_2 = {
  124345. _vq_quantthresh__16c0_s_p9_2,
  124346. _vq_quantmap__16c0_s_p9_2,
  124347. 21,
  124348. 21
  124349. };
  124350. static static_codebook _16c0_s_p9_2 = {
  124351. 2, 441,
  124352. _vq_lengthlist__16c0_s_p9_2,
  124353. 1, -529268736, 1611661312, 5, 0,
  124354. _vq_quantlist__16c0_s_p9_2,
  124355. NULL,
  124356. &_vq_auxt__16c0_s_p9_2,
  124357. NULL,
  124358. 0
  124359. };
  124360. static long _huff_lengthlist__16c0_s_single[] = {
  124361. 3, 4,19, 7, 9, 7, 8,11, 9,12, 4, 1,19, 6, 7, 7,
  124362. 8,10,11,13,18,18,18,18,18,18,18,18,18,18, 8, 6,
  124363. 18, 8, 9, 9,11,12,14,18, 9, 6,18, 9, 7, 8, 9,11,
  124364. 12,18, 7, 6,18, 8, 7, 7, 7, 9,11,17, 8, 8,18, 9,
  124365. 7, 6, 6, 8,11,17,10,10,18,12, 9, 8, 7, 9,12,18,
  124366. 13,15,18,15,13,11,10,11,15,18,14,18,18,18,18,18,
  124367. 16,16,18,18,
  124368. };
  124369. static static_codebook _huff_book__16c0_s_single = {
  124370. 2, 100,
  124371. _huff_lengthlist__16c0_s_single,
  124372. 0, 0, 0, 0, 0,
  124373. NULL,
  124374. NULL,
  124375. NULL,
  124376. NULL,
  124377. 0
  124378. };
  124379. static long _huff_lengthlist__16c1_s_long[] = {
  124380. 2, 5,20, 7,10, 7, 8,10,11,11, 4, 2,20, 5, 8, 6,
  124381. 7, 9,10,10,20,20,20,20,19,19,19,19,19,19, 7, 5,
  124382. 19, 6,10, 7, 9,11,13,17,11, 8,19,10, 7, 7, 8,10,
  124383. 11,15, 7, 5,19, 7, 7, 5, 6, 9,11,16, 7, 6,19, 8,
  124384. 7, 6, 6, 7, 9,13, 9, 9,19,11, 9, 8, 6, 7, 8,13,
  124385. 12,14,19,16,13,10, 9, 8, 9,13,14,17,19,18,18,17,
  124386. 12,11,11,13,
  124387. };
  124388. static static_codebook _huff_book__16c1_s_long = {
  124389. 2, 100,
  124390. _huff_lengthlist__16c1_s_long,
  124391. 0, 0, 0, 0, 0,
  124392. NULL,
  124393. NULL,
  124394. NULL,
  124395. NULL,
  124396. 0
  124397. };
  124398. static long _vq_quantlist__16c1_s_p1_0[] = {
  124399. 1,
  124400. 0,
  124401. 2,
  124402. };
  124403. static long _vq_lengthlist__16c1_s_p1_0[] = {
  124404. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  124405. 0, 0, 5, 7, 7, 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, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  124410. 0, 0, 0, 7, 8, 9, 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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  124415. 0, 0, 0, 0, 7, 9, 9, 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, 5, 8, 7, 0, 0, 0, 0,
  124450. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 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, 7, 9, 9, 0, 0, 0,
  124455. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 9,11,10, 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, 7, 9, 9, 0, 0,
  124460. 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  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, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  124496. 0, 0, 0, 0, 8, 9, 9, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  124501. 0, 0, 0, 0, 0, 8, 9,11, 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, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  124506. 0, 0, 0, 0, 0, 0, 9,11, 9, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124814. 0,
  124815. };
  124816. static float _vq_quantthresh__16c1_s_p1_0[] = {
  124817. -0.5, 0.5,
  124818. };
  124819. static long _vq_quantmap__16c1_s_p1_0[] = {
  124820. 1, 0, 2,
  124821. };
  124822. static encode_aux_threshmatch _vq_auxt__16c1_s_p1_0 = {
  124823. _vq_quantthresh__16c1_s_p1_0,
  124824. _vq_quantmap__16c1_s_p1_0,
  124825. 3,
  124826. 3
  124827. };
  124828. static static_codebook _16c1_s_p1_0 = {
  124829. 8, 6561,
  124830. _vq_lengthlist__16c1_s_p1_0,
  124831. 1, -535822336, 1611661312, 2, 0,
  124832. _vq_quantlist__16c1_s_p1_0,
  124833. NULL,
  124834. &_vq_auxt__16c1_s_p1_0,
  124835. NULL,
  124836. 0
  124837. };
  124838. static long _vq_quantlist__16c1_s_p2_0[] = {
  124839. 2,
  124840. 1,
  124841. 3,
  124842. 0,
  124843. 4,
  124844. };
  124845. static long _vq_lengthlist__16c1_s_p2_0[] = {
  124846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124885. 0,
  124886. };
  124887. static float _vq_quantthresh__16c1_s_p2_0[] = {
  124888. -1.5, -0.5, 0.5, 1.5,
  124889. };
  124890. static long _vq_quantmap__16c1_s_p2_0[] = {
  124891. 3, 1, 0, 2, 4,
  124892. };
  124893. static encode_aux_threshmatch _vq_auxt__16c1_s_p2_0 = {
  124894. _vq_quantthresh__16c1_s_p2_0,
  124895. _vq_quantmap__16c1_s_p2_0,
  124896. 5,
  124897. 5
  124898. };
  124899. static static_codebook _16c1_s_p2_0 = {
  124900. 4, 625,
  124901. _vq_lengthlist__16c1_s_p2_0,
  124902. 1, -533725184, 1611661312, 3, 0,
  124903. _vq_quantlist__16c1_s_p2_0,
  124904. NULL,
  124905. &_vq_auxt__16c1_s_p2_0,
  124906. NULL,
  124907. 0
  124908. };
  124909. static long _vq_quantlist__16c1_s_p3_0[] = {
  124910. 2,
  124911. 1,
  124912. 3,
  124913. 0,
  124914. 4,
  124915. };
  124916. static long _vq_lengthlist__16c1_s_p3_0[] = {
  124917. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  124919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124920. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 7, 7, 9, 9,
  124922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124923. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  124924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124956. 0,
  124957. };
  124958. static float _vq_quantthresh__16c1_s_p3_0[] = {
  124959. -1.5, -0.5, 0.5, 1.5,
  124960. };
  124961. static long _vq_quantmap__16c1_s_p3_0[] = {
  124962. 3, 1, 0, 2, 4,
  124963. };
  124964. static encode_aux_threshmatch _vq_auxt__16c1_s_p3_0 = {
  124965. _vq_quantthresh__16c1_s_p3_0,
  124966. _vq_quantmap__16c1_s_p3_0,
  124967. 5,
  124968. 5
  124969. };
  124970. static static_codebook _16c1_s_p3_0 = {
  124971. 4, 625,
  124972. _vq_lengthlist__16c1_s_p3_0,
  124973. 1, -533725184, 1611661312, 3, 0,
  124974. _vq_quantlist__16c1_s_p3_0,
  124975. NULL,
  124976. &_vq_auxt__16c1_s_p3_0,
  124977. NULL,
  124978. 0
  124979. };
  124980. static long _vq_quantlist__16c1_s_p4_0[] = {
  124981. 4,
  124982. 3,
  124983. 5,
  124984. 2,
  124985. 6,
  124986. 1,
  124987. 7,
  124988. 0,
  124989. 8,
  124990. };
  124991. static long _vq_lengthlist__16c1_s_p4_0[] = {
  124992. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  124993. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  124994. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  124995. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 9, 0, 0, 0, 0, 0,
  124996. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  124997. 0,
  124998. };
  124999. static float _vq_quantthresh__16c1_s_p4_0[] = {
  125000. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125001. };
  125002. static long _vq_quantmap__16c1_s_p4_0[] = {
  125003. 7, 5, 3, 1, 0, 2, 4, 6,
  125004. 8,
  125005. };
  125006. static encode_aux_threshmatch _vq_auxt__16c1_s_p4_0 = {
  125007. _vq_quantthresh__16c1_s_p4_0,
  125008. _vq_quantmap__16c1_s_p4_0,
  125009. 9,
  125010. 9
  125011. };
  125012. static static_codebook _16c1_s_p4_0 = {
  125013. 2, 81,
  125014. _vq_lengthlist__16c1_s_p4_0,
  125015. 1, -531628032, 1611661312, 4, 0,
  125016. _vq_quantlist__16c1_s_p4_0,
  125017. NULL,
  125018. &_vq_auxt__16c1_s_p4_0,
  125019. NULL,
  125020. 0
  125021. };
  125022. static long _vq_quantlist__16c1_s_p5_0[] = {
  125023. 4,
  125024. 3,
  125025. 5,
  125026. 2,
  125027. 6,
  125028. 1,
  125029. 7,
  125030. 0,
  125031. 8,
  125032. };
  125033. static long _vq_lengthlist__16c1_s_p5_0[] = {
  125034. 1, 3, 3, 5, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  125035. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 8, 8,
  125036. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  125037. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  125038. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  125039. 10,
  125040. };
  125041. static float _vq_quantthresh__16c1_s_p5_0[] = {
  125042. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125043. };
  125044. static long _vq_quantmap__16c1_s_p5_0[] = {
  125045. 7, 5, 3, 1, 0, 2, 4, 6,
  125046. 8,
  125047. };
  125048. static encode_aux_threshmatch _vq_auxt__16c1_s_p5_0 = {
  125049. _vq_quantthresh__16c1_s_p5_0,
  125050. _vq_quantmap__16c1_s_p5_0,
  125051. 9,
  125052. 9
  125053. };
  125054. static static_codebook _16c1_s_p5_0 = {
  125055. 2, 81,
  125056. _vq_lengthlist__16c1_s_p5_0,
  125057. 1, -531628032, 1611661312, 4, 0,
  125058. _vq_quantlist__16c1_s_p5_0,
  125059. NULL,
  125060. &_vq_auxt__16c1_s_p5_0,
  125061. NULL,
  125062. 0
  125063. };
  125064. static long _vq_quantlist__16c1_s_p6_0[] = {
  125065. 8,
  125066. 7,
  125067. 9,
  125068. 6,
  125069. 10,
  125070. 5,
  125071. 11,
  125072. 4,
  125073. 12,
  125074. 3,
  125075. 13,
  125076. 2,
  125077. 14,
  125078. 1,
  125079. 15,
  125080. 0,
  125081. 16,
  125082. };
  125083. static long _vq_lengthlist__16c1_s_p6_0[] = {
  125084. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,12,
  125085. 12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  125086. 12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  125087. 11,12,12, 0, 0, 0, 8, 8, 8, 9,10, 9,10,10,10,10,
  125088. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,11,
  125089. 11,11,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  125090. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  125091. 10,11,11,12,12,13,13, 0, 0, 0, 9, 9, 9, 9,10,10,
  125092. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  125093. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  125094. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  125095. 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0,
  125096. 10,10,11,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0,
  125097. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  125098. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  125099. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0,
  125100. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  125101. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  125102. 14,
  125103. };
  125104. static float _vq_quantthresh__16c1_s_p6_0[] = {
  125105. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125106. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125107. };
  125108. static long _vq_quantmap__16c1_s_p6_0[] = {
  125109. 15, 13, 11, 9, 7, 5, 3, 1,
  125110. 0, 2, 4, 6, 8, 10, 12, 14,
  125111. 16,
  125112. };
  125113. static encode_aux_threshmatch _vq_auxt__16c1_s_p6_0 = {
  125114. _vq_quantthresh__16c1_s_p6_0,
  125115. _vq_quantmap__16c1_s_p6_0,
  125116. 17,
  125117. 17
  125118. };
  125119. static static_codebook _16c1_s_p6_0 = {
  125120. 2, 289,
  125121. _vq_lengthlist__16c1_s_p6_0,
  125122. 1, -529530880, 1611661312, 5, 0,
  125123. _vq_quantlist__16c1_s_p6_0,
  125124. NULL,
  125125. &_vq_auxt__16c1_s_p6_0,
  125126. NULL,
  125127. 0
  125128. };
  125129. static long _vq_quantlist__16c1_s_p7_0[] = {
  125130. 1,
  125131. 0,
  125132. 2,
  125133. };
  125134. static long _vq_lengthlist__16c1_s_p7_0[] = {
  125135. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9,10,10,
  125136. 10, 9, 4, 7, 7,10,10,10,11,10,10, 6,10,10,11,11,
  125137. 11,11,10,10, 6,10, 9,11,11,11,11,10,10, 6,10,10,
  125138. 11,11,11,11,10,10, 7,11,11,11,11,11,12,12,11, 6,
  125139. 10,10,11,10,10,11,11,11, 6,10,10,10,11,10,11,11,
  125140. 11,
  125141. };
  125142. static float _vq_quantthresh__16c1_s_p7_0[] = {
  125143. -5.5, 5.5,
  125144. };
  125145. static long _vq_quantmap__16c1_s_p7_0[] = {
  125146. 1, 0, 2,
  125147. };
  125148. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_0 = {
  125149. _vq_quantthresh__16c1_s_p7_0,
  125150. _vq_quantmap__16c1_s_p7_0,
  125151. 3,
  125152. 3
  125153. };
  125154. static static_codebook _16c1_s_p7_0 = {
  125155. 4, 81,
  125156. _vq_lengthlist__16c1_s_p7_0,
  125157. 1, -529137664, 1618345984, 2, 0,
  125158. _vq_quantlist__16c1_s_p7_0,
  125159. NULL,
  125160. &_vq_auxt__16c1_s_p7_0,
  125161. NULL,
  125162. 0
  125163. };
  125164. static long _vq_quantlist__16c1_s_p7_1[] = {
  125165. 5,
  125166. 4,
  125167. 6,
  125168. 3,
  125169. 7,
  125170. 2,
  125171. 8,
  125172. 1,
  125173. 9,
  125174. 0,
  125175. 10,
  125176. };
  125177. static long _vq_lengthlist__16c1_s_p7_1[] = {
  125178. 2, 3, 3, 5, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  125179. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  125180. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  125181. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  125182. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  125183. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  125184. 8, 9, 9,10,10,10,10,10, 9, 9, 8, 8, 9, 9,10,10,
  125185. 10,10,10, 8, 8, 8, 8, 9, 9,
  125186. };
  125187. static float _vq_quantthresh__16c1_s_p7_1[] = {
  125188. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125189. 3.5, 4.5,
  125190. };
  125191. static long _vq_quantmap__16c1_s_p7_1[] = {
  125192. 9, 7, 5, 3, 1, 0, 2, 4,
  125193. 6, 8, 10,
  125194. };
  125195. static encode_aux_threshmatch _vq_auxt__16c1_s_p7_1 = {
  125196. _vq_quantthresh__16c1_s_p7_1,
  125197. _vq_quantmap__16c1_s_p7_1,
  125198. 11,
  125199. 11
  125200. };
  125201. static static_codebook _16c1_s_p7_1 = {
  125202. 2, 121,
  125203. _vq_lengthlist__16c1_s_p7_1,
  125204. 1, -531365888, 1611661312, 4, 0,
  125205. _vq_quantlist__16c1_s_p7_1,
  125206. NULL,
  125207. &_vq_auxt__16c1_s_p7_1,
  125208. NULL,
  125209. 0
  125210. };
  125211. static long _vq_quantlist__16c1_s_p8_0[] = {
  125212. 6,
  125213. 5,
  125214. 7,
  125215. 4,
  125216. 8,
  125217. 3,
  125218. 9,
  125219. 2,
  125220. 10,
  125221. 1,
  125222. 11,
  125223. 0,
  125224. 12,
  125225. };
  125226. static long _vq_lengthlist__16c1_s_p8_0[] = {
  125227. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  125228. 7, 8, 8, 9, 8, 8, 9, 9,10,11, 6, 5, 5, 8, 8, 9,
  125229. 9, 8, 8, 9,10,10,11, 0, 8, 8, 8, 9, 9, 9, 9, 9,
  125230. 10,10,11,11, 0, 9, 9, 9, 8, 9, 9, 9, 9,10,10,11,
  125231. 11, 0,13,13, 9, 9,10,10,10,10,11,11,12,12, 0,14,
  125232. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  125233. 9, 9,11,11,12,12,13,12, 0, 0, 0,10,10, 9, 9,10,
  125234. 10,12,12,13,13, 0, 0, 0,13,14,11,10,11,11,12,12,
  125235. 13,14, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  125236. 0, 0, 0, 0,12,12,12,12,13,13,14,15, 0, 0, 0, 0,
  125237. 0,12,12,12,12,13,13,14,15,
  125238. };
  125239. static float _vq_quantthresh__16c1_s_p8_0[] = {
  125240. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125241. 12.5, 17.5, 22.5, 27.5,
  125242. };
  125243. static long _vq_quantmap__16c1_s_p8_0[] = {
  125244. 11, 9, 7, 5, 3, 1, 0, 2,
  125245. 4, 6, 8, 10, 12,
  125246. };
  125247. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_0 = {
  125248. _vq_quantthresh__16c1_s_p8_0,
  125249. _vq_quantmap__16c1_s_p8_0,
  125250. 13,
  125251. 13
  125252. };
  125253. static static_codebook _16c1_s_p8_0 = {
  125254. 2, 169,
  125255. _vq_lengthlist__16c1_s_p8_0,
  125256. 1, -526516224, 1616117760, 4, 0,
  125257. _vq_quantlist__16c1_s_p8_0,
  125258. NULL,
  125259. &_vq_auxt__16c1_s_p8_0,
  125260. NULL,
  125261. 0
  125262. };
  125263. static long _vq_quantlist__16c1_s_p8_1[] = {
  125264. 2,
  125265. 1,
  125266. 3,
  125267. 0,
  125268. 4,
  125269. };
  125270. static long _vq_lengthlist__16c1_s_p8_1[] = {
  125271. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125272. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125273. };
  125274. static float _vq_quantthresh__16c1_s_p8_1[] = {
  125275. -1.5, -0.5, 0.5, 1.5,
  125276. };
  125277. static long _vq_quantmap__16c1_s_p8_1[] = {
  125278. 3, 1, 0, 2, 4,
  125279. };
  125280. static encode_aux_threshmatch _vq_auxt__16c1_s_p8_1 = {
  125281. _vq_quantthresh__16c1_s_p8_1,
  125282. _vq_quantmap__16c1_s_p8_1,
  125283. 5,
  125284. 5
  125285. };
  125286. static static_codebook _16c1_s_p8_1 = {
  125287. 2, 25,
  125288. _vq_lengthlist__16c1_s_p8_1,
  125289. 1, -533725184, 1611661312, 3, 0,
  125290. _vq_quantlist__16c1_s_p8_1,
  125291. NULL,
  125292. &_vq_auxt__16c1_s_p8_1,
  125293. NULL,
  125294. 0
  125295. };
  125296. static long _vq_quantlist__16c1_s_p9_0[] = {
  125297. 6,
  125298. 5,
  125299. 7,
  125300. 4,
  125301. 8,
  125302. 3,
  125303. 9,
  125304. 2,
  125305. 10,
  125306. 1,
  125307. 11,
  125308. 0,
  125309. 12,
  125310. };
  125311. static long _vq_lengthlist__16c1_s_p9_0[] = {
  125312. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125313. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125314. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125315. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125316. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  125317. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125318. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125319. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125320. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125321. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125322. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  125323. };
  125324. static float _vq_quantthresh__16c1_s_p9_0[] = {
  125325. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  125326. 787.5, 1102.5, 1417.5, 1732.5,
  125327. };
  125328. static long _vq_quantmap__16c1_s_p9_0[] = {
  125329. 11, 9, 7, 5, 3, 1, 0, 2,
  125330. 4, 6, 8, 10, 12,
  125331. };
  125332. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_0 = {
  125333. _vq_quantthresh__16c1_s_p9_0,
  125334. _vq_quantmap__16c1_s_p9_0,
  125335. 13,
  125336. 13
  125337. };
  125338. static static_codebook _16c1_s_p9_0 = {
  125339. 2, 169,
  125340. _vq_lengthlist__16c1_s_p9_0,
  125341. 1, -513964032, 1628680192, 4, 0,
  125342. _vq_quantlist__16c1_s_p9_0,
  125343. NULL,
  125344. &_vq_auxt__16c1_s_p9_0,
  125345. NULL,
  125346. 0
  125347. };
  125348. static long _vq_quantlist__16c1_s_p9_1[] = {
  125349. 7,
  125350. 6,
  125351. 8,
  125352. 5,
  125353. 9,
  125354. 4,
  125355. 10,
  125356. 3,
  125357. 11,
  125358. 2,
  125359. 12,
  125360. 1,
  125361. 13,
  125362. 0,
  125363. 14,
  125364. };
  125365. static long _vq_lengthlist__16c1_s_p9_1[] = {
  125366. 1, 4, 4, 4, 4, 8, 8,12,13,14,14,14,14,14,14, 6,
  125367. 6, 6, 6, 6,10, 9,14,14,14,14,14,14,14,14, 7, 6,
  125368. 5, 6, 6,10, 9,12,13,13,13,13,13,13,13,13, 7, 7,
  125369. 9, 9,11,11,12,13,13,13,13,13,13,13,13, 7, 7, 8,
  125370. 8,11,12,13,13,13,13,13,13,13,13,13,12,12,10,10,
  125371. 13,12,13,13,13,13,13,13,13,13,13,12,12,10,10,13,
  125372. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,13,12,
  125373. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  125374. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125375. 13,13,13,13,13,13,13,13,13,13,13,13,12,13,13,13,
  125376. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125377. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125378. 13,13,13,13,13,13,13,13,13,12,13,13,13,13,13,13,
  125379. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  125380. 13,
  125381. };
  125382. static float _vq_quantthresh__16c1_s_p9_1[] = {
  125383. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  125384. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  125385. };
  125386. static long _vq_quantmap__16c1_s_p9_1[] = {
  125387. 13, 11, 9, 7, 5, 3, 1, 0,
  125388. 2, 4, 6, 8, 10, 12, 14,
  125389. };
  125390. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_1 = {
  125391. _vq_quantthresh__16c1_s_p9_1,
  125392. _vq_quantmap__16c1_s_p9_1,
  125393. 15,
  125394. 15
  125395. };
  125396. static static_codebook _16c1_s_p9_1 = {
  125397. 2, 225,
  125398. _vq_lengthlist__16c1_s_p9_1,
  125399. 1, -520986624, 1620377600, 4, 0,
  125400. _vq_quantlist__16c1_s_p9_1,
  125401. NULL,
  125402. &_vq_auxt__16c1_s_p9_1,
  125403. NULL,
  125404. 0
  125405. };
  125406. static long _vq_quantlist__16c1_s_p9_2[] = {
  125407. 10,
  125408. 9,
  125409. 11,
  125410. 8,
  125411. 12,
  125412. 7,
  125413. 13,
  125414. 6,
  125415. 14,
  125416. 5,
  125417. 15,
  125418. 4,
  125419. 16,
  125420. 3,
  125421. 17,
  125422. 2,
  125423. 18,
  125424. 1,
  125425. 19,
  125426. 0,
  125427. 20,
  125428. };
  125429. static long _vq_lengthlist__16c1_s_p9_2[] = {
  125430. 1, 4, 4, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9,10,
  125431. 10,10, 9,10,10,11,12,12, 8, 8, 8, 8, 9, 9, 9, 9,
  125432. 10,10,10,10,10,11,11,10,12,11,11,13,11, 7, 7, 8,
  125433. 8, 8, 8, 9, 9, 9,10,10,10,10, 9,10,10,11,11,12,
  125434. 11,11, 8, 8, 8, 8, 9, 9,10,10,10,10,11,11,11,11,
  125435. 11,11,11,12,11,12,12, 8, 8, 9, 9, 9, 9, 9,10,10,
  125436. 10,10,10,10,11,11,11,11,11,11,12,11, 9, 9, 9, 9,
  125437. 10,10,10,10,11,10,11,11,11,11,11,11,12,12,12,12,
  125438. 11, 9, 9, 9, 9,10,10,10,10,11,11,11,11,11,11,11,
  125439. 11,11,12,12,12,13, 9,10,10, 9,11,10,10,10,10,11,
  125440. 11,11,11,11,10,11,12,11,12,12,11,12,11,10, 9,10,
  125441. 10,11,10,11,11,11,11,11,11,11,11,11,12,12,11,12,
  125442. 12,12,10,10,10,11,10,11,11,11,11,11,11,11,11,11,
  125443. 11,11,12,13,12,12,11, 9,10,10,11,11,10,11,11,11,
  125444. 12,11,11,11,11,11,12,12,13,13,12,13,10,10,12,10,
  125445. 11,11,11,11,11,11,11,11,11,12,12,11,13,12,12,12,
  125446. 12,13,12,11,11,11,11,11,11,12,11,12,11,11,11,11,
  125447. 12,12,13,12,11,12,12,11,11,11,11,11,12,11,11,11,
  125448. 11,12,11,11,12,11,12,13,13,12,12,12,12,11,11,11,
  125449. 11,11,12,11,11,12,11,12,11,11,11,11,13,12,12,12,
  125450. 12,13,11,11,11,12,12,11,11,11,12,11,12,12,12,11,
  125451. 12,13,12,11,11,12,12,11,12,11,11,11,12,12,11,12,
  125452. 11,11,11,12,12,12,12,13,12,13,12,12,12,12,11,11,
  125453. 12,11,11,11,11,11,11,12,12,12,13,12,11,13,13,12,
  125454. 12,11,12,10,11,11,11,11,12,11,12,12,11,12,12,13,
  125455. 12,12,13,12,12,12,12,12,11,12,12,12,11,12,11,11,
  125456. 11,12,13,12,13,13,13,13,13,12,13,13,12,12,13,11,
  125457. 11,11,11,11,12,11,11,12,11,
  125458. };
  125459. static float _vq_quantthresh__16c1_s_p9_2[] = {
  125460. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  125461. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  125462. 6.5, 7.5, 8.5, 9.5,
  125463. };
  125464. static long _vq_quantmap__16c1_s_p9_2[] = {
  125465. 19, 17, 15, 13, 11, 9, 7, 5,
  125466. 3, 1, 0, 2, 4, 6, 8, 10,
  125467. 12, 14, 16, 18, 20,
  125468. };
  125469. static encode_aux_threshmatch _vq_auxt__16c1_s_p9_2 = {
  125470. _vq_quantthresh__16c1_s_p9_2,
  125471. _vq_quantmap__16c1_s_p9_2,
  125472. 21,
  125473. 21
  125474. };
  125475. static static_codebook _16c1_s_p9_2 = {
  125476. 2, 441,
  125477. _vq_lengthlist__16c1_s_p9_2,
  125478. 1, -529268736, 1611661312, 5, 0,
  125479. _vq_quantlist__16c1_s_p9_2,
  125480. NULL,
  125481. &_vq_auxt__16c1_s_p9_2,
  125482. NULL,
  125483. 0
  125484. };
  125485. static long _huff_lengthlist__16c1_s_short[] = {
  125486. 5, 6,17, 8,12, 9,10,10,12,13, 5, 2,17, 4, 9, 5,
  125487. 7, 8,11,13,16,16,16,16,16,16,16,16,16,16, 6, 4,
  125488. 16, 5,10, 5, 7,10,14,16,13, 9,16,11, 8, 7, 8, 9,
  125489. 13,16, 7, 4,16, 5, 7, 4, 6, 8,11,13, 8, 6,16, 7,
  125490. 8, 5, 5, 7, 9,13, 9, 8,16, 9, 8, 6, 6, 7, 9,13,
  125491. 11,11,16,10,10, 7, 7, 7, 9,13,13,13,16,13,13, 9,
  125492. 9, 9,10,13,
  125493. };
  125494. static static_codebook _huff_book__16c1_s_short = {
  125495. 2, 100,
  125496. _huff_lengthlist__16c1_s_short,
  125497. 0, 0, 0, 0, 0,
  125498. NULL,
  125499. NULL,
  125500. NULL,
  125501. NULL,
  125502. 0
  125503. };
  125504. static long _huff_lengthlist__16c2_s_long[] = {
  125505. 4, 7, 9, 9, 9, 8, 9,10,15,19, 5, 4, 5, 6, 7, 7,
  125506. 8, 9,14,16, 6, 5, 4, 5, 6, 7, 8,10,12,19, 7, 6,
  125507. 5, 4, 5, 6, 7, 9,11,18, 8, 7, 6, 5, 5, 5, 7, 9,
  125508. 10,17, 8, 7, 7, 5, 5, 5, 6, 7,12,18, 8, 8, 8, 7,
  125509. 7, 5, 5, 7,12,18, 8, 9,10, 9, 9, 7, 6, 7,12,17,
  125510. 14,18,16,16,15,12,11,10,12,18,15,17,18,18,18,15,
  125511. 14,14,16,18,
  125512. };
  125513. static static_codebook _huff_book__16c2_s_long = {
  125514. 2, 100,
  125515. _huff_lengthlist__16c2_s_long,
  125516. 0, 0, 0, 0, 0,
  125517. NULL,
  125518. NULL,
  125519. NULL,
  125520. NULL,
  125521. 0
  125522. };
  125523. static long _vq_quantlist__16c2_s_p1_0[] = {
  125524. 1,
  125525. 0,
  125526. 2,
  125527. };
  125528. static long _vq_lengthlist__16c2_s_p1_0[] = {
  125529. 1, 3, 3, 0, 0, 0, 0, 0, 0, 4, 5, 5, 0, 0, 0, 0,
  125530. 0, 0, 4, 5, 5, 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,
  125535. };
  125536. static float _vq_quantthresh__16c2_s_p1_0[] = {
  125537. -0.5, 0.5,
  125538. };
  125539. static long _vq_quantmap__16c2_s_p1_0[] = {
  125540. 1, 0, 2,
  125541. };
  125542. static encode_aux_threshmatch _vq_auxt__16c2_s_p1_0 = {
  125543. _vq_quantthresh__16c2_s_p1_0,
  125544. _vq_quantmap__16c2_s_p1_0,
  125545. 3,
  125546. 3
  125547. };
  125548. static static_codebook _16c2_s_p1_0 = {
  125549. 4, 81,
  125550. _vq_lengthlist__16c2_s_p1_0,
  125551. 1, -535822336, 1611661312, 2, 0,
  125552. _vq_quantlist__16c2_s_p1_0,
  125553. NULL,
  125554. &_vq_auxt__16c2_s_p1_0,
  125555. NULL,
  125556. 0
  125557. };
  125558. static long _vq_quantlist__16c2_s_p2_0[] = {
  125559. 2,
  125560. 1,
  125561. 3,
  125562. 0,
  125563. 4,
  125564. };
  125565. static long _vq_lengthlist__16c2_s_p2_0[] = {
  125566. 2, 4, 3, 7, 7, 0, 0, 0, 7, 8, 0, 0, 0, 8, 8, 0,
  125567. 0, 0, 8, 8, 0, 0, 0, 8, 8, 4, 5, 4, 8, 8, 0, 0,
  125568. 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0,
  125569. 9, 9, 4, 4, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8,
  125570. 8, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 7, 8, 8,10,10,
  125571. 0, 0, 0,12,11, 0, 0, 0,11,11, 0, 0, 0,14,13, 0,
  125572. 0, 0,14,13, 7, 8, 8, 9,10, 0, 0, 0,11,12, 0, 0,
  125573. 0,11,11, 0, 0, 0,14,14, 0, 0, 0,13,14, 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, 8, 8, 8,11,11, 0, 0, 0,
  125579. 11,11, 0, 0, 0,12,11, 0, 0, 0,12,12, 0, 0, 0,13,
  125580. 13, 8, 8, 8,11,11, 0, 0, 0,11,11, 0, 0, 0,11,12,
  125581. 0, 0, 0,12,13, 0, 0, 0,13,13, 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, 8, 8, 8,12,11, 0, 0, 0,12,11, 0,
  125587. 0, 0,11,11, 0, 0, 0,13,13, 0, 0, 0,13,12, 8, 8,
  125588. 8,11,12, 0, 0, 0,11,12, 0, 0, 0,11,11, 0, 0, 0,
  125589. 13,13, 0, 0, 0,12,13, 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, 8, 9, 9,14,13, 0, 0, 0,13,12, 0, 0, 0,13,
  125595. 13, 0, 0, 0,13,12, 0, 0, 0,13,13, 8, 9, 9,13,14,
  125596. 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,13, 0,
  125597. 0, 0,13,13, 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, 8,
  125602. 9, 9,14,13, 0, 0, 0,13,13, 0, 0, 0,13,12, 0, 0,
  125603. 0,13,13, 0, 0, 0,13,12, 8, 9, 9,14,14, 0, 0, 0,
  125604. 13,13, 0, 0, 0,12,13, 0, 0, 0,13,13, 0, 0, 0,12,
  125605. 13,
  125606. };
  125607. static float _vq_quantthresh__16c2_s_p2_0[] = {
  125608. -1.5, -0.5, 0.5, 1.5,
  125609. };
  125610. static long _vq_quantmap__16c2_s_p2_0[] = {
  125611. 3, 1, 0, 2, 4,
  125612. };
  125613. static encode_aux_threshmatch _vq_auxt__16c2_s_p2_0 = {
  125614. _vq_quantthresh__16c2_s_p2_0,
  125615. _vq_quantmap__16c2_s_p2_0,
  125616. 5,
  125617. 5
  125618. };
  125619. static static_codebook _16c2_s_p2_0 = {
  125620. 4, 625,
  125621. _vq_lengthlist__16c2_s_p2_0,
  125622. 1, -533725184, 1611661312, 3, 0,
  125623. _vq_quantlist__16c2_s_p2_0,
  125624. NULL,
  125625. &_vq_auxt__16c2_s_p2_0,
  125626. NULL,
  125627. 0
  125628. };
  125629. static long _vq_quantlist__16c2_s_p3_0[] = {
  125630. 4,
  125631. 3,
  125632. 5,
  125633. 2,
  125634. 6,
  125635. 1,
  125636. 7,
  125637. 0,
  125638. 8,
  125639. };
  125640. static long _vq_lengthlist__16c2_s_p3_0[] = {
  125641. 1, 3, 3, 6, 6, 7, 7, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  125642. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  125643. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  125644. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 9, 9,10,10, 0,
  125645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125646. 0,
  125647. };
  125648. static float _vq_quantthresh__16c2_s_p3_0[] = {
  125649. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  125650. };
  125651. static long _vq_quantmap__16c2_s_p3_0[] = {
  125652. 7, 5, 3, 1, 0, 2, 4, 6,
  125653. 8,
  125654. };
  125655. static encode_aux_threshmatch _vq_auxt__16c2_s_p3_0 = {
  125656. _vq_quantthresh__16c2_s_p3_0,
  125657. _vq_quantmap__16c2_s_p3_0,
  125658. 9,
  125659. 9
  125660. };
  125661. static static_codebook _16c2_s_p3_0 = {
  125662. 2, 81,
  125663. _vq_lengthlist__16c2_s_p3_0,
  125664. 1, -531628032, 1611661312, 4, 0,
  125665. _vq_quantlist__16c2_s_p3_0,
  125666. NULL,
  125667. &_vq_auxt__16c2_s_p3_0,
  125668. NULL,
  125669. 0
  125670. };
  125671. static long _vq_quantlist__16c2_s_p4_0[] = {
  125672. 8,
  125673. 7,
  125674. 9,
  125675. 6,
  125676. 10,
  125677. 5,
  125678. 11,
  125679. 4,
  125680. 12,
  125681. 3,
  125682. 13,
  125683. 2,
  125684. 14,
  125685. 1,
  125686. 15,
  125687. 0,
  125688. 16,
  125689. };
  125690. static long _vq_lengthlist__16c2_s_p4_0[] = {
  125691. 2, 3, 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,
  125692. 10, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  125693. 11,11, 0, 0, 0, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  125694. 10,10,11, 0, 0, 0, 6, 6, 8, 8, 8, 8, 9, 9,10,10,
  125695. 10,11,11,11, 0, 0, 0, 6, 6, 8, 8, 9, 9, 9, 9,10,
  125696. 10,11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,
  125697. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9,
  125698. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  125699. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  125700. 9,10,10,11,11,12,12,12,12, 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,
  125710. };
  125711. static float _vq_quantthresh__16c2_s_p4_0[] = {
  125712. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  125713. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  125714. };
  125715. static long _vq_quantmap__16c2_s_p4_0[] = {
  125716. 15, 13, 11, 9, 7, 5, 3, 1,
  125717. 0, 2, 4, 6, 8, 10, 12, 14,
  125718. 16,
  125719. };
  125720. static encode_aux_threshmatch _vq_auxt__16c2_s_p4_0 = {
  125721. _vq_quantthresh__16c2_s_p4_0,
  125722. _vq_quantmap__16c2_s_p4_0,
  125723. 17,
  125724. 17
  125725. };
  125726. static static_codebook _16c2_s_p4_0 = {
  125727. 2, 289,
  125728. _vq_lengthlist__16c2_s_p4_0,
  125729. 1, -529530880, 1611661312, 5, 0,
  125730. _vq_quantlist__16c2_s_p4_0,
  125731. NULL,
  125732. &_vq_auxt__16c2_s_p4_0,
  125733. NULL,
  125734. 0
  125735. };
  125736. static long _vq_quantlist__16c2_s_p5_0[] = {
  125737. 1,
  125738. 0,
  125739. 2,
  125740. };
  125741. static long _vq_lengthlist__16c2_s_p5_0[] = {
  125742. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6,10,10,10,10,
  125743. 10,10, 4, 7, 6,10,10,10,10,10,10, 5, 9, 9, 9,12,
  125744. 11,10,11,12, 7,10,10,12,12,12,12,12,12, 7,10,10,
  125745. 11,12,12,12,12,13, 6,10,10,10,12,12,10,12,12, 7,
  125746. 10,10,11,13,12,12,12,12, 7,10,10,11,12,12,12,12,
  125747. 12,
  125748. };
  125749. static float _vq_quantthresh__16c2_s_p5_0[] = {
  125750. -5.5, 5.5,
  125751. };
  125752. static long _vq_quantmap__16c2_s_p5_0[] = {
  125753. 1, 0, 2,
  125754. };
  125755. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_0 = {
  125756. _vq_quantthresh__16c2_s_p5_0,
  125757. _vq_quantmap__16c2_s_p5_0,
  125758. 3,
  125759. 3
  125760. };
  125761. static static_codebook _16c2_s_p5_0 = {
  125762. 4, 81,
  125763. _vq_lengthlist__16c2_s_p5_0,
  125764. 1, -529137664, 1618345984, 2, 0,
  125765. _vq_quantlist__16c2_s_p5_0,
  125766. NULL,
  125767. &_vq_auxt__16c2_s_p5_0,
  125768. NULL,
  125769. 0
  125770. };
  125771. static long _vq_quantlist__16c2_s_p5_1[] = {
  125772. 5,
  125773. 4,
  125774. 6,
  125775. 3,
  125776. 7,
  125777. 2,
  125778. 8,
  125779. 1,
  125780. 9,
  125781. 0,
  125782. 10,
  125783. };
  125784. static long _vq_lengthlist__16c2_s_p5_1[] = {
  125785. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11, 6, 6,
  125786. 7, 7, 8, 8, 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8,
  125787. 8,11,11,11, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  125788. 6, 8, 8, 8, 8, 9, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  125789. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 9,11,11,11,
  125790. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,11,11, 8, 8, 8,
  125791. 8, 8, 8,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  125792. 11,11,11, 7, 7, 8, 8, 8, 8,
  125793. };
  125794. static float _vq_quantthresh__16c2_s_p5_1[] = {
  125795. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125796. 3.5, 4.5,
  125797. };
  125798. static long _vq_quantmap__16c2_s_p5_1[] = {
  125799. 9, 7, 5, 3, 1, 0, 2, 4,
  125800. 6, 8, 10,
  125801. };
  125802. static encode_aux_threshmatch _vq_auxt__16c2_s_p5_1 = {
  125803. _vq_quantthresh__16c2_s_p5_1,
  125804. _vq_quantmap__16c2_s_p5_1,
  125805. 11,
  125806. 11
  125807. };
  125808. static static_codebook _16c2_s_p5_1 = {
  125809. 2, 121,
  125810. _vq_lengthlist__16c2_s_p5_1,
  125811. 1, -531365888, 1611661312, 4, 0,
  125812. _vq_quantlist__16c2_s_p5_1,
  125813. NULL,
  125814. &_vq_auxt__16c2_s_p5_1,
  125815. NULL,
  125816. 0
  125817. };
  125818. static long _vq_quantlist__16c2_s_p6_0[] = {
  125819. 6,
  125820. 5,
  125821. 7,
  125822. 4,
  125823. 8,
  125824. 3,
  125825. 9,
  125826. 2,
  125827. 10,
  125828. 1,
  125829. 11,
  125830. 0,
  125831. 12,
  125832. };
  125833. static long _vq_lengthlist__16c2_s_p6_0[] = {
  125834. 1, 4, 4, 7, 6, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125835. 7, 7, 9, 9, 9, 9,11,11,12,12, 6, 5, 5, 7, 7, 9,
  125836. 9,10,10,11,11,12,12, 0, 6, 6, 7, 7, 9, 9,10,10,
  125837. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,12,12,
  125838. 12, 0,11,11, 8, 8,10,10,11,11,12,12,13,13, 0,11,
  125839. 12, 8, 8,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  125840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125844. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  125845. };
  125846. static float _vq_quantthresh__16c2_s_p6_0[] = {
  125847. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  125848. 12.5, 17.5, 22.5, 27.5,
  125849. };
  125850. static long _vq_quantmap__16c2_s_p6_0[] = {
  125851. 11, 9, 7, 5, 3, 1, 0, 2,
  125852. 4, 6, 8, 10, 12,
  125853. };
  125854. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_0 = {
  125855. _vq_quantthresh__16c2_s_p6_0,
  125856. _vq_quantmap__16c2_s_p6_0,
  125857. 13,
  125858. 13
  125859. };
  125860. static static_codebook _16c2_s_p6_0 = {
  125861. 2, 169,
  125862. _vq_lengthlist__16c2_s_p6_0,
  125863. 1, -526516224, 1616117760, 4, 0,
  125864. _vq_quantlist__16c2_s_p6_0,
  125865. NULL,
  125866. &_vq_auxt__16c2_s_p6_0,
  125867. NULL,
  125868. 0
  125869. };
  125870. static long _vq_quantlist__16c2_s_p6_1[] = {
  125871. 2,
  125872. 1,
  125873. 3,
  125874. 0,
  125875. 4,
  125876. };
  125877. static long _vq_lengthlist__16c2_s_p6_1[] = {
  125878. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  125879. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  125880. };
  125881. static float _vq_quantthresh__16c2_s_p6_1[] = {
  125882. -1.5, -0.5, 0.5, 1.5,
  125883. };
  125884. static long _vq_quantmap__16c2_s_p6_1[] = {
  125885. 3, 1, 0, 2, 4,
  125886. };
  125887. static encode_aux_threshmatch _vq_auxt__16c2_s_p6_1 = {
  125888. _vq_quantthresh__16c2_s_p6_1,
  125889. _vq_quantmap__16c2_s_p6_1,
  125890. 5,
  125891. 5
  125892. };
  125893. static static_codebook _16c2_s_p6_1 = {
  125894. 2, 25,
  125895. _vq_lengthlist__16c2_s_p6_1,
  125896. 1, -533725184, 1611661312, 3, 0,
  125897. _vq_quantlist__16c2_s_p6_1,
  125898. NULL,
  125899. &_vq_auxt__16c2_s_p6_1,
  125900. NULL,
  125901. 0
  125902. };
  125903. static long _vq_quantlist__16c2_s_p7_0[] = {
  125904. 6,
  125905. 5,
  125906. 7,
  125907. 4,
  125908. 8,
  125909. 3,
  125910. 9,
  125911. 2,
  125912. 10,
  125913. 1,
  125914. 11,
  125915. 0,
  125916. 12,
  125917. };
  125918. static long _vq_lengthlist__16c2_s_p7_0[] = {
  125919. 1, 4, 4, 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 5, 5,
  125920. 8, 8, 9, 9,10,10,11,11,12,12, 6, 5, 5, 8, 8, 9,
  125921. 9,10,10,11,11,12,13,18, 6, 6, 7, 7, 9, 9,10,10,
  125922. 12,12,13,13,18, 6, 6, 7, 7, 9, 9,10,10,12,12,13,
  125923. 13,18,11,10, 8, 8,10,10,11,11,12,12,13,13,18,11,
  125924. 11, 8, 8,10,10,11,11,12,13,13,13,18,18,18,10,11,
  125925. 11,11,12,12,13,13,14,14,18,18,18,11,11,11,11,12,
  125926. 12,13,13,14,14,18,18,18,14,14,12,12,12,12,14,14,
  125927. 15,14,18,18,18,15,15,11,12,12,12,13,13,15,15,18,
  125928. 18,18,18,18,13,13,13,13,13,14,17,16,18,18,18,18,
  125929. 18,13,14,13,13,14,13,15,14,
  125930. };
  125931. static float _vq_quantthresh__16c2_s_p7_0[] = {
  125932. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  125933. 27.5, 38.5, 49.5, 60.5,
  125934. };
  125935. static long _vq_quantmap__16c2_s_p7_0[] = {
  125936. 11, 9, 7, 5, 3, 1, 0, 2,
  125937. 4, 6, 8, 10, 12,
  125938. };
  125939. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_0 = {
  125940. _vq_quantthresh__16c2_s_p7_0,
  125941. _vq_quantmap__16c2_s_p7_0,
  125942. 13,
  125943. 13
  125944. };
  125945. static static_codebook _16c2_s_p7_0 = {
  125946. 2, 169,
  125947. _vq_lengthlist__16c2_s_p7_0,
  125948. 1, -523206656, 1618345984, 4, 0,
  125949. _vq_quantlist__16c2_s_p7_0,
  125950. NULL,
  125951. &_vq_auxt__16c2_s_p7_0,
  125952. NULL,
  125953. 0
  125954. };
  125955. static long _vq_quantlist__16c2_s_p7_1[] = {
  125956. 5,
  125957. 4,
  125958. 6,
  125959. 3,
  125960. 7,
  125961. 2,
  125962. 8,
  125963. 1,
  125964. 9,
  125965. 0,
  125966. 10,
  125967. };
  125968. static long _vq_lengthlist__16c2_s_p7_1[] = {
  125969. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 9, 9, 6, 6,
  125970. 7, 7, 8, 8, 8, 8, 9, 9, 9, 6, 6, 7, 7, 8, 8, 8,
  125971. 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7,
  125972. 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125973. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  125974. 7, 7, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 9, 7, 7, 7,
  125975. 7, 8, 8, 9, 9, 9, 9, 9, 8, 8, 7, 7, 8, 8, 9, 9,
  125976. 9, 9, 9, 7, 7, 7, 7, 8, 8,
  125977. };
  125978. static float _vq_quantthresh__16c2_s_p7_1[] = {
  125979. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  125980. 3.5, 4.5,
  125981. };
  125982. static long _vq_quantmap__16c2_s_p7_1[] = {
  125983. 9, 7, 5, 3, 1, 0, 2, 4,
  125984. 6, 8, 10,
  125985. };
  125986. static encode_aux_threshmatch _vq_auxt__16c2_s_p7_1 = {
  125987. _vq_quantthresh__16c2_s_p7_1,
  125988. _vq_quantmap__16c2_s_p7_1,
  125989. 11,
  125990. 11
  125991. };
  125992. static static_codebook _16c2_s_p7_1 = {
  125993. 2, 121,
  125994. _vq_lengthlist__16c2_s_p7_1,
  125995. 1, -531365888, 1611661312, 4, 0,
  125996. _vq_quantlist__16c2_s_p7_1,
  125997. NULL,
  125998. &_vq_auxt__16c2_s_p7_1,
  125999. NULL,
  126000. 0
  126001. };
  126002. static long _vq_quantlist__16c2_s_p8_0[] = {
  126003. 7,
  126004. 6,
  126005. 8,
  126006. 5,
  126007. 9,
  126008. 4,
  126009. 10,
  126010. 3,
  126011. 11,
  126012. 2,
  126013. 12,
  126014. 1,
  126015. 13,
  126016. 0,
  126017. 14,
  126018. };
  126019. static long _vq_lengthlist__16c2_s_p8_0[] = {
  126020. 1, 4, 4, 7, 6, 7, 7, 6, 6, 8, 8, 9, 9,10,10, 6,
  126021. 6, 6, 8, 8, 9, 8, 8, 8, 9, 9,11,10,11,11, 7, 6,
  126022. 6, 8, 8, 9, 8, 7, 7, 9, 9,10,10,12,11,14, 8, 8,
  126023. 8, 9, 9, 9, 9, 9,10, 9,10,10,11,13,14, 8, 8, 8,
  126024. 8, 9, 9, 8, 8, 9, 9,10,10,11,12,14,13,11, 9, 9,
  126025. 9, 9, 9, 9, 9,10,11,10,13,12,14,11,13, 8, 9, 9,
  126026. 9, 9, 9,10,10,11,10,13,12,14,14,14, 8, 9, 9, 9,
  126027. 11,11,11,11,11,12,13,13,14,14,14, 9, 8, 9, 9,10,
  126028. 10,12,10,11,12,12,14,14,14,14,11,12,10,10,12,12,
  126029. 12,12,13,14,12,12,14,14,14,12,12, 9,10,11,11,12,
  126030. 14,12,14,14,14,14,14,14,14,14,11,11,12,11,12,14,
  126031. 14,14,14,14,14,14,14,14,14,12,11,11,11,11,14,14,
  126032. 14,14,14,14,14,14,14,14,14,14,13,12,14,14,14,14,
  126033. 14,14,14,14,14,14,14,14,14,12,12,12,13,14,14,13,
  126034. 13,
  126035. };
  126036. static float _vq_quantthresh__16c2_s_p8_0[] = {
  126037. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  126038. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  126039. };
  126040. static long _vq_quantmap__16c2_s_p8_0[] = {
  126041. 13, 11, 9, 7, 5, 3, 1, 0,
  126042. 2, 4, 6, 8, 10, 12, 14,
  126043. };
  126044. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_0 = {
  126045. _vq_quantthresh__16c2_s_p8_0,
  126046. _vq_quantmap__16c2_s_p8_0,
  126047. 15,
  126048. 15
  126049. };
  126050. static static_codebook _16c2_s_p8_0 = {
  126051. 2, 225,
  126052. _vq_lengthlist__16c2_s_p8_0,
  126053. 1, -520986624, 1620377600, 4, 0,
  126054. _vq_quantlist__16c2_s_p8_0,
  126055. NULL,
  126056. &_vq_auxt__16c2_s_p8_0,
  126057. NULL,
  126058. 0
  126059. };
  126060. static long _vq_quantlist__16c2_s_p8_1[] = {
  126061. 10,
  126062. 9,
  126063. 11,
  126064. 8,
  126065. 12,
  126066. 7,
  126067. 13,
  126068. 6,
  126069. 14,
  126070. 5,
  126071. 15,
  126072. 4,
  126073. 16,
  126074. 3,
  126075. 17,
  126076. 2,
  126077. 18,
  126078. 1,
  126079. 19,
  126080. 0,
  126081. 20,
  126082. };
  126083. static long _vq_lengthlist__16c2_s_p8_1[] = {
  126084. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  126085. 8, 8, 8, 8, 8,11,12,11, 7, 7, 8, 8, 8, 8, 9, 9,
  126086. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,11,11,10, 7, 7, 8,
  126087. 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  126088. 11,11, 8, 7, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 9,10,
  126089. 10, 9,10,10,11,11,12, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  126090. 9, 9, 9,10, 9,10,10,10,10,11,11,11, 8, 8, 9, 9,
  126091. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  126092. 11, 8, 8, 9, 8, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,
  126093. 10, 9,10,11,11,11, 9, 9, 9, 9,10, 9, 9, 9,10,10,
  126094. 9,10, 9,10,10,10,10,10,11,12,11,11,11, 9, 9, 9,
  126095. 9, 9,10,10, 9,10,10,10,10,10,10,10,10,12,11,13,
  126096. 13,11, 9, 9, 9, 9,10,10, 9,10,10,10,10,11,10,10,
  126097. 10,10,11,12,11,12,11, 9, 9, 9,10,10, 9,10,10,10,
  126098. 10,10,10,10,10,10,10,11,11,11,12,11, 9,10,10,10,
  126099. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,12,12,
  126100. 11,11,11,10, 9,10,10,10,10,10,10,10,10,11,10,10,
  126101. 10,11,11,11,11,11,11,11,10,10,10,11,10,10,10,10,
  126102. 10,10,10,10,10,10,11,11,11,11,12,12,11,10,10,10,
  126103. 10,10,10,10,10,11,10,10,10,11,10,12,11,11,12,11,
  126104. 11,11,10,10,10,10,10,11,10,10,10,10,10,11,10,10,
  126105. 11,11,11,12,11,12,11,11,12,10,10,10,10,10,10,10,
  126106. 11,10,10,11,10,12,11,11,11,12,11,11,11,11,10,10,
  126107. 10,10,10,10,10,11,11,11,10,11,12,11,11,11,12,11,
  126108. 12,11,12,10,11,10,10,10,10,11,10,10,10,10,10,10,
  126109. 12,11,11,11,11,11,12,12,10,10,10,10,10,11,10,10,
  126110. 11,10,11,11,11,11,11,11,11,11,11,11,11,11,12,11,
  126111. 10,11,10,10,10,10,10,10,10,
  126112. };
  126113. static float _vq_quantthresh__16c2_s_p8_1[] = {
  126114. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  126115. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  126116. 6.5, 7.5, 8.5, 9.5,
  126117. };
  126118. static long _vq_quantmap__16c2_s_p8_1[] = {
  126119. 19, 17, 15, 13, 11, 9, 7, 5,
  126120. 3, 1, 0, 2, 4, 6, 8, 10,
  126121. 12, 14, 16, 18, 20,
  126122. };
  126123. static encode_aux_threshmatch _vq_auxt__16c2_s_p8_1 = {
  126124. _vq_quantthresh__16c2_s_p8_1,
  126125. _vq_quantmap__16c2_s_p8_1,
  126126. 21,
  126127. 21
  126128. };
  126129. static static_codebook _16c2_s_p8_1 = {
  126130. 2, 441,
  126131. _vq_lengthlist__16c2_s_p8_1,
  126132. 1, -529268736, 1611661312, 5, 0,
  126133. _vq_quantlist__16c2_s_p8_1,
  126134. NULL,
  126135. &_vq_auxt__16c2_s_p8_1,
  126136. NULL,
  126137. 0
  126138. };
  126139. static long _vq_quantlist__16c2_s_p9_0[] = {
  126140. 6,
  126141. 5,
  126142. 7,
  126143. 4,
  126144. 8,
  126145. 3,
  126146. 9,
  126147. 2,
  126148. 10,
  126149. 1,
  126150. 11,
  126151. 0,
  126152. 12,
  126153. };
  126154. static long _vq_lengthlist__16c2_s_p9_0[] = {
  126155. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126156. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126157. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126158. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126159. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  126160. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126161. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126162. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126163. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126164. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126165. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  126166. };
  126167. static float _vq_quantthresh__16c2_s_p9_0[] = {
  126168. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5,
  126169. 2327.5, 3258.5, 4189.5, 5120.5,
  126170. };
  126171. static long _vq_quantmap__16c2_s_p9_0[] = {
  126172. 11, 9, 7, 5, 3, 1, 0, 2,
  126173. 4, 6, 8, 10, 12,
  126174. };
  126175. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_0 = {
  126176. _vq_quantthresh__16c2_s_p9_0,
  126177. _vq_quantmap__16c2_s_p9_0,
  126178. 13,
  126179. 13
  126180. };
  126181. static static_codebook _16c2_s_p9_0 = {
  126182. 2, 169,
  126183. _vq_lengthlist__16c2_s_p9_0,
  126184. 1, -510275072, 1631393792, 4, 0,
  126185. _vq_quantlist__16c2_s_p9_0,
  126186. NULL,
  126187. &_vq_auxt__16c2_s_p9_0,
  126188. NULL,
  126189. 0
  126190. };
  126191. static long _vq_quantlist__16c2_s_p9_1[] = {
  126192. 8,
  126193. 7,
  126194. 9,
  126195. 6,
  126196. 10,
  126197. 5,
  126198. 11,
  126199. 4,
  126200. 12,
  126201. 3,
  126202. 13,
  126203. 2,
  126204. 14,
  126205. 1,
  126206. 15,
  126207. 0,
  126208. 16,
  126209. };
  126210. static long _vq_lengthlist__16c2_s_p9_1[] = {
  126211. 1, 5, 5, 9, 8, 7, 7, 7, 6,10,11,11,11,11,11,11,
  126212. 11, 8, 7, 6, 8, 8,10, 9,10,10,10, 9,11,10,10,10,
  126213. 10,10, 8, 6, 6, 8, 8, 9, 8, 9, 8, 9,10,10,10,10,
  126214. 10,10,10,10, 8,10, 9, 9, 9, 9,10,10,10,10,10,10,
  126215. 10,10,10,10,10, 8, 9, 9, 9,10,10, 9,10,10,10,10,
  126216. 10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,10,10,10,
  126217. 10,10,10,10,10,10,10,10, 9, 8, 8, 9, 9,10,10,10,
  126218. 10,10,10,10,10,10,10,10,10,10, 9,10, 9, 9,10,10,
  126219. 10,10,10,10,10,10,10,10,10,10,10, 9, 8, 9, 9,10,
  126220. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  126221. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126222. 8,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126223. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126224. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126225. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126226. 10,10,10,10, 9,10, 9,10,10,10,10,10,10,10,10,10,
  126227. 10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,
  126228. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  126229. 10,
  126230. };
  126231. static float _vq_quantthresh__16c2_s_p9_1[] = {
  126232. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -24.5,
  126233. 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5, 367.5,
  126234. };
  126235. static long _vq_quantmap__16c2_s_p9_1[] = {
  126236. 15, 13, 11, 9, 7, 5, 3, 1,
  126237. 0, 2, 4, 6, 8, 10, 12, 14,
  126238. 16,
  126239. };
  126240. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_1 = {
  126241. _vq_quantthresh__16c2_s_p9_1,
  126242. _vq_quantmap__16c2_s_p9_1,
  126243. 17,
  126244. 17
  126245. };
  126246. static static_codebook _16c2_s_p9_1 = {
  126247. 2, 289,
  126248. _vq_lengthlist__16c2_s_p9_1,
  126249. 1, -518488064, 1622704128, 5, 0,
  126250. _vq_quantlist__16c2_s_p9_1,
  126251. NULL,
  126252. &_vq_auxt__16c2_s_p9_1,
  126253. NULL,
  126254. 0
  126255. };
  126256. static long _vq_quantlist__16c2_s_p9_2[] = {
  126257. 13,
  126258. 12,
  126259. 14,
  126260. 11,
  126261. 15,
  126262. 10,
  126263. 16,
  126264. 9,
  126265. 17,
  126266. 8,
  126267. 18,
  126268. 7,
  126269. 19,
  126270. 6,
  126271. 20,
  126272. 5,
  126273. 21,
  126274. 4,
  126275. 22,
  126276. 3,
  126277. 23,
  126278. 2,
  126279. 24,
  126280. 1,
  126281. 25,
  126282. 0,
  126283. 26,
  126284. };
  126285. static long _vq_lengthlist__16c2_s_p9_2[] = {
  126286. 1, 4, 4, 5, 5, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  126287. 7, 7, 7, 7, 8, 7, 8, 7, 7, 4, 4,
  126288. };
  126289. static float _vq_quantthresh__16c2_s_p9_2[] = {
  126290. -12.5, -11.5, -10.5, -9.5, -8.5, -7.5, -6.5, -5.5,
  126291. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  126292. 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5, 10.5,
  126293. 11.5, 12.5,
  126294. };
  126295. static long _vq_quantmap__16c2_s_p9_2[] = {
  126296. 25, 23, 21, 19, 17, 15, 13, 11,
  126297. 9, 7, 5, 3, 1, 0, 2, 4,
  126298. 6, 8, 10, 12, 14, 16, 18, 20,
  126299. 22, 24, 26,
  126300. };
  126301. static encode_aux_threshmatch _vq_auxt__16c2_s_p9_2 = {
  126302. _vq_quantthresh__16c2_s_p9_2,
  126303. _vq_quantmap__16c2_s_p9_2,
  126304. 27,
  126305. 27
  126306. };
  126307. static static_codebook _16c2_s_p9_2 = {
  126308. 1, 27,
  126309. _vq_lengthlist__16c2_s_p9_2,
  126310. 1, -528875520, 1611661312, 5, 0,
  126311. _vq_quantlist__16c2_s_p9_2,
  126312. NULL,
  126313. &_vq_auxt__16c2_s_p9_2,
  126314. NULL,
  126315. 0
  126316. };
  126317. static long _huff_lengthlist__16c2_s_short[] = {
  126318. 7,10,11,11,11,14,15,15,17,14, 8, 6, 7, 7, 8, 9,
  126319. 11,11,14,17, 9, 6, 6, 6, 7, 7,10,11,15,16, 9, 6,
  126320. 6, 4, 4, 5, 8, 9,12,16,10, 6, 6, 4, 4, 4, 6, 9,
  126321. 13,16,10, 7, 6, 5, 4, 3, 5, 7,13,16,11, 9, 8, 7,
  126322. 6, 5, 5, 6,12,15,10,10,10, 9, 7, 6, 6, 7,11,15,
  126323. 13,13,13,13,11,10,10, 9,12,16,16,16,16,14,16,15,
  126324. 15,12,14,14,
  126325. };
  126326. static static_codebook _huff_book__16c2_s_short = {
  126327. 2, 100,
  126328. _huff_lengthlist__16c2_s_short,
  126329. 0, 0, 0, 0, 0,
  126330. NULL,
  126331. NULL,
  126332. NULL,
  126333. NULL,
  126334. 0
  126335. };
  126336. static long _vq_quantlist__8c0_s_p1_0[] = {
  126337. 1,
  126338. 0,
  126339. 2,
  126340. };
  126341. static long _vq_lengthlist__8c0_s_p1_0[] = {
  126342. 1, 5, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  126343. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126344. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126345. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126346. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126347. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  126348. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126349. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126350. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126351. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126352. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  126353. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126354. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126355. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126356. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126357. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126358. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126359. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126360. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126361. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126362. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126363. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126364. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126365. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126366. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126367. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126368. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126369. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126370. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126371. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126372. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126373. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126374. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126375. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126376. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126377. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126378. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126379. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126380. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126381. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126382. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126383. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126384. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126385. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126386. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126387. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  126388. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126389. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126390. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126391. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126392. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  126393. 0, 0, 0, 8, 9,11, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  126394. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126395. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126396. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126397. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9,10, 0, 0,
  126398. 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  126399. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126400. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126401. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126402. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126403. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126404. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126405. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126406. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126407. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126408. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126409. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126410. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126413. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126416. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126417. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126418. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126419. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126420. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126421. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126422. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126423. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126424. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126433. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  126434. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126438. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,11, 0,
  126439. 0, 0, 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 0, 0,
  126440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126443. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,11,11,
  126444. 0, 0, 0, 0, 0, 0, 8,11, 9, 0, 0, 0, 0, 0, 0, 0,
  126445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126477. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126482. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126487. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126497. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126498. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126499. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126500. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126504. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126505. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126537. 0, 0, 0, 0, 0, 0, 0, 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. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126545. 0, 0, 0, 0, 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, 0,
  126550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126752. 0,
  126753. };
  126754. static float _vq_quantthresh__8c0_s_p1_0[] = {
  126755. -0.5, 0.5,
  126756. };
  126757. static long _vq_quantmap__8c0_s_p1_0[] = {
  126758. 1, 0, 2,
  126759. };
  126760. static encode_aux_threshmatch _vq_auxt__8c0_s_p1_0 = {
  126761. _vq_quantthresh__8c0_s_p1_0,
  126762. _vq_quantmap__8c0_s_p1_0,
  126763. 3,
  126764. 3
  126765. };
  126766. static static_codebook _8c0_s_p1_0 = {
  126767. 8, 6561,
  126768. _vq_lengthlist__8c0_s_p1_0,
  126769. 1, -535822336, 1611661312, 2, 0,
  126770. _vq_quantlist__8c0_s_p1_0,
  126771. NULL,
  126772. &_vq_auxt__8c0_s_p1_0,
  126773. NULL,
  126774. 0
  126775. };
  126776. static long _vq_quantlist__8c0_s_p2_0[] = {
  126777. 2,
  126778. 1,
  126779. 3,
  126780. 0,
  126781. 4,
  126782. };
  126783. static long _vq_lengthlist__8c0_s_p2_0[] = {
  126784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  126793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126823. 0,
  126824. };
  126825. static float _vq_quantthresh__8c0_s_p2_0[] = {
  126826. -1.5, -0.5, 0.5, 1.5,
  126827. };
  126828. static long _vq_quantmap__8c0_s_p2_0[] = {
  126829. 3, 1, 0, 2, 4,
  126830. };
  126831. static encode_aux_threshmatch _vq_auxt__8c0_s_p2_0 = {
  126832. _vq_quantthresh__8c0_s_p2_0,
  126833. _vq_quantmap__8c0_s_p2_0,
  126834. 5,
  126835. 5
  126836. };
  126837. static static_codebook _8c0_s_p2_0 = {
  126838. 4, 625,
  126839. _vq_lengthlist__8c0_s_p2_0,
  126840. 1, -533725184, 1611661312, 3, 0,
  126841. _vq_quantlist__8c0_s_p2_0,
  126842. NULL,
  126843. &_vq_auxt__8c0_s_p2_0,
  126844. NULL,
  126845. 0
  126846. };
  126847. static long _vq_quantlist__8c0_s_p3_0[] = {
  126848. 2,
  126849. 1,
  126850. 3,
  126851. 0,
  126852. 4,
  126853. };
  126854. static long _vq_lengthlist__8c0_s_p3_0[] = {
  126855. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 6, 7, 7, 0, 0,
  126857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126858. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 8, 8,
  126860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126861. 0, 0, 0, 0, 6, 7, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  126862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126894. 0,
  126895. };
  126896. static float _vq_quantthresh__8c0_s_p3_0[] = {
  126897. -1.5, -0.5, 0.5, 1.5,
  126898. };
  126899. static long _vq_quantmap__8c0_s_p3_0[] = {
  126900. 3, 1, 0, 2, 4,
  126901. };
  126902. static encode_aux_threshmatch _vq_auxt__8c0_s_p3_0 = {
  126903. _vq_quantthresh__8c0_s_p3_0,
  126904. _vq_quantmap__8c0_s_p3_0,
  126905. 5,
  126906. 5
  126907. };
  126908. static static_codebook _8c0_s_p3_0 = {
  126909. 4, 625,
  126910. _vq_lengthlist__8c0_s_p3_0,
  126911. 1, -533725184, 1611661312, 3, 0,
  126912. _vq_quantlist__8c0_s_p3_0,
  126913. NULL,
  126914. &_vq_auxt__8c0_s_p3_0,
  126915. NULL,
  126916. 0
  126917. };
  126918. static long _vq_quantlist__8c0_s_p4_0[] = {
  126919. 4,
  126920. 3,
  126921. 5,
  126922. 2,
  126923. 6,
  126924. 1,
  126925. 7,
  126926. 0,
  126927. 8,
  126928. };
  126929. static long _vq_lengthlist__8c0_s_p4_0[] = {
  126930. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  126931. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  126932. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  126933. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  126934. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  126935. 0,
  126936. };
  126937. static float _vq_quantthresh__8c0_s_p4_0[] = {
  126938. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126939. };
  126940. static long _vq_quantmap__8c0_s_p4_0[] = {
  126941. 7, 5, 3, 1, 0, 2, 4, 6,
  126942. 8,
  126943. };
  126944. static encode_aux_threshmatch _vq_auxt__8c0_s_p4_0 = {
  126945. _vq_quantthresh__8c0_s_p4_0,
  126946. _vq_quantmap__8c0_s_p4_0,
  126947. 9,
  126948. 9
  126949. };
  126950. static static_codebook _8c0_s_p4_0 = {
  126951. 2, 81,
  126952. _vq_lengthlist__8c0_s_p4_0,
  126953. 1, -531628032, 1611661312, 4, 0,
  126954. _vq_quantlist__8c0_s_p4_0,
  126955. NULL,
  126956. &_vq_auxt__8c0_s_p4_0,
  126957. NULL,
  126958. 0
  126959. };
  126960. static long _vq_quantlist__8c0_s_p5_0[] = {
  126961. 4,
  126962. 3,
  126963. 5,
  126964. 2,
  126965. 6,
  126966. 1,
  126967. 7,
  126968. 0,
  126969. 8,
  126970. };
  126971. static long _vq_lengthlist__8c0_s_p5_0[] = {
  126972. 1, 3, 3, 5, 5, 7, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  126973. 8, 8, 0, 0, 0, 7, 7, 7, 7, 8, 9, 0, 0, 0, 8, 8,
  126974. 8, 8, 9, 9, 0, 0, 0, 8, 8, 8, 8, 9, 9, 0, 0, 0,
  126975. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  126976. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  126977. 10,
  126978. };
  126979. static float _vq_quantthresh__8c0_s_p5_0[] = {
  126980. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  126981. };
  126982. static long _vq_quantmap__8c0_s_p5_0[] = {
  126983. 7, 5, 3, 1, 0, 2, 4, 6,
  126984. 8,
  126985. };
  126986. static encode_aux_threshmatch _vq_auxt__8c0_s_p5_0 = {
  126987. _vq_quantthresh__8c0_s_p5_0,
  126988. _vq_quantmap__8c0_s_p5_0,
  126989. 9,
  126990. 9
  126991. };
  126992. static static_codebook _8c0_s_p5_0 = {
  126993. 2, 81,
  126994. _vq_lengthlist__8c0_s_p5_0,
  126995. 1, -531628032, 1611661312, 4, 0,
  126996. _vq_quantlist__8c0_s_p5_0,
  126997. NULL,
  126998. &_vq_auxt__8c0_s_p5_0,
  126999. NULL,
  127000. 0
  127001. };
  127002. static long _vq_quantlist__8c0_s_p6_0[] = {
  127003. 8,
  127004. 7,
  127005. 9,
  127006. 6,
  127007. 10,
  127008. 5,
  127009. 11,
  127010. 4,
  127011. 12,
  127012. 3,
  127013. 13,
  127014. 2,
  127015. 14,
  127016. 1,
  127017. 15,
  127018. 0,
  127019. 16,
  127020. };
  127021. static long _vq_lengthlist__8c0_s_p6_0[] = {
  127022. 1, 3, 3, 6, 6, 8, 8, 9, 9, 8, 8,10, 9,10,10,11,
  127023. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  127024. 11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  127025. 11,12,11, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,10,10,
  127026. 11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10, 9, 9,11,
  127027. 10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,10,
  127028. 11,11,11,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,10,
  127029. 10,11,11,12,12,13,13, 0, 0, 0,10,10,10,10,11,11,
  127030. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,10, 9,10,
  127031. 11,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  127032. 10, 9,10,11,12,12,13,13,14,13, 0, 0, 0, 0, 0, 9,
  127033. 9, 9,10,10,10,11,11,13,12,13,13, 0, 0, 0, 0, 0,
  127034. 10,10,10,10,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  127035. 0, 0, 0,10,10,11,11,12,12,13,13,13,14, 0, 0, 0,
  127036. 0, 0, 0, 0,11,11,11,11,12,12,13,14,14,14, 0, 0,
  127037. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,14,13, 0,
  127038. 0, 0, 0, 0, 0, 0,11,11,12,12,13,13,14,14,14,14,
  127039. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  127040. 14,
  127041. };
  127042. static float _vq_quantthresh__8c0_s_p6_0[] = {
  127043. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  127044. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  127045. };
  127046. static long _vq_quantmap__8c0_s_p6_0[] = {
  127047. 15, 13, 11, 9, 7, 5, 3, 1,
  127048. 0, 2, 4, 6, 8, 10, 12, 14,
  127049. 16,
  127050. };
  127051. static encode_aux_threshmatch _vq_auxt__8c0_s_p6_0 = {
  127052. _vq_quantthresh__8c0_s_p6_0,
  127053. _vq_quantmap__8c0_s_p6_0,
  127054. 17,
  127055. 17
  127056. };
  127057. static static_codebook _8c0_s_p6_0 = {
  127058. 2, 289,
  127059. _vq_lengthlist__8c0_s_p6_0,
  127060. 1, -529530880, 1611661312, 5, 0,
  127061. _vq_quantlist__8c0_s_p6_0,
  127062. NULL,
  127063. &_vq_auxt__8c0_s_p6_0,
  127064. NULL,
  127065. 0
  127066. };
  127067. static long _vq_quantlist__8c0_s_p7_0[] = {
  127068. 1,
  127069. 0,
  127070. 2,
  127071. };
  127072. static long _vq_lengthlist__8c0_s_p7_0[] = {
  127073. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,11, 9,10,12,
  127074. 9,10, 4, 7, 7,10,10,10,11, 9, 9, 6,11,10,11,11,
  127075. 12,11,11,11, 6,10,10,11,11,12,11,10,10, 6, 9,10,
  127076. 11,11,11,11,10,10, 7,10,11,12,11,11,12,11,12, 6,
  127077. 9, 9,10, 9, 9,11,10,10, 6, 9, 9,10,10,10,11,10,
  127078. 10,
  127079. };
  127080. static float _vq_quantthresh__8c0_s_p7_0[] = {
  127081. -5.5, 5.5,
  127082. };
  127083. static long _vq_quantmap__8c0_s_p7_0[] = {
  127084. 1, 0, 2,
  127085. };
  127086. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_0 = {
  127087. _vq_quantthresh__8c0_s_p7_0,
  127088. _vq_quantmap__8c0_s_p7_0,
  127089. 3,
  127090. 3
  127091. };
  127092. static static_codebook _8c0_s_p7_0 = {
  127093. 4, 81,
  127094. _vq_lengthlist__8c0_s_p7_0,
  127095. 1, -529137664, 1618345984, 2, 0,
  127096. _vq_quantlist__8c0_s_p7_0,
  127097. NULL,
  127098. &_vq_auxt__8c0_s_p7_0,
  127099. NULL,
  127100. 0
  127101. };
  127102. static long _vq_quantlist__8c0_s_p7_1[] = {
  127103. 5,
  127104. 4,
  127105. 6,
  127106. 3,
  127107. 7,
  127108. 2,
  127109. 8,
  127110. 1,
  127111. 9,
  127112. 0,
  127113. 10,
  127114. };
  127115. static long _vq_lengthlist__8c0_s_p7_1[] = {
  127116. 1, 3, 3, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10, 7, 7,
  127117. 8, 8, 9, 9, 9, 9,10,10, 9, 7, 7, 8, 8, 9, 9, 9,
  127118. 9,10,10,10, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10, 8,
  127119. 8, 9, 9, 9, 9, 8, 9,10,10,10, 8, 8, 9, 9, 9,10,
  127120. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,11,10,11,
  127121. 9, 9, 9, 9,10,10,10,10,11,11,11,10,10, 9, 9,10,
  127122. 10,10, 9,11,10,10,10,10,10,10, 9, 9,10,10,11,11,
  127123. 10,10,10, 9, 9, 9,10,10,10,
  127124. };
  127125. static float _vq_quantthresh__8c0_s_p7_1[] = {
  127126. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  127127. 3.5, 4.5,
  127128. };
  127129. static long _vq_quantmap__8c0_s_p7_1[] = {
  127130. 9, 7, 5, 3, 1, 0, 2, 4,
  127131. 6, 8, 10,
  127132. };
  127133. static encode_aux_threshmatch _vq_auxt__8c0_s_p7_1 = {
  127134. _vq_quantthresh__8c0_s_p7_1,
  127135. _vq_quantmap__8c0_s_p7_1,
  127136. 11,
  127137. 11
  127138. };
  127139. static static_codebook _8c0_s_p7_1 = {
  127140. 2, 121,
  127141. _vq_lengthlist__8c0_s_p7_1,
  127142. 1, -531365888, 1611661312, 4, 0,
  127143. _vq_quantlist__8c0_s_p7_1,
  127144. NULL,
  127145. &_vq_auxt__8c0_s_p7_1,
  127146. NULL,
  127147. 0
  127148. };
  127149. static long _vq_quantlist__8c0_s_p8_0[] = {
  127150. 6,
  127151. 5,
  127152. 7,
  127153. 4,
  127154. 8,
  127155. 3,
  127156. 9,
  127157. 2,
  127158. 10,
  127159. 1,
  127160. 11,
  127161. 0,
  127162. 12,
  127163. };
  127164. static long _vq_lengthlist__8c0_s_p8_0[] = {
  127165. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 6, 6,
  127166. 7, 7, 8, 8, 7, 7, 8, 9,10,10, 7, 6, 6, 7, 7, 8,
  127167. 7, 7, 7, 9, 9,10,12, 0, 8, 8, 8, 8, 8, 9, 8, 8,
  127168. 9, 9,10,10, 0, 8, 8, 8, 8, 8, 9, 8, 9, 9, 9,11,
  127169. 10, 0, 0,13, 9, 8, 9, 9, 9, 9,10,10,11,11, 0,13,
  127170. 0, 9, 9, 9, 9, 9, 9,11,10,11,11, 0, 0, 0, 8, 9,
  127171. 10, 9,10,10,13,11,12,12, 0, 0, 0, 8, 9, 9, 9,10,
  127172. 10,13,12,12,13, 0, 0, 0,12, 0,10,10,12,11,10,11,
  127173. 12,12, 0, 0, 0,13,13,10,10,10,11,12, 0,13, 0, 0,
  127174. 0, 0, 0, 0,13,11, 0,12,12,12,13,12, 0, 0, 0, 0,
  127175. 0, 0,13,13,11,13,13,11,12,
  127176. };
  127177. static float _vq_quantthresh__8c0_s_p8_0[] = {
  127178. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  127179. 12.5, 17.5, 22.5, 27.5,
  127180. };
  127181. static long _vq_quantmap__8c0_s_p8_0[] = {
  127182. 11, 9, 7, 5, 3, 1, 0, 2,
  127183. 4, 6, 8, 10, 12,
  127184. };
  127185. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_0 = {
  127186. _vq_quantthresh__8c0_s_p8_0,
  127187. _vq_quantmap__8c0_s_p8_0,
  127188. 13,
  127189. 13
  127190. };
  127191. static static_codebook _8c0_s_p8_0 = {
  127192. 2, 169,
  127193. _vq_lengthlist__8c0_s_p8_0,
  127194. 1, -526516224, 1616117760, 4, 0,
  127195. _vq_quantlist__8c0_s_p8_0,
  127196. NULL,
  127197. &_vq_auxt__8c0_s_p8_0,
  127198. NULL,
  127199. 0
  127200. };
  127201. static long _vq_quantlist__8c0_s_p8_1[] = {
  127202. 2,
  127203. 1,
  127204. 3,
  127205. 0,
  127206. 4,
  127207. };
  127208. static long _vq_lengthlist__8c0_s_p8_1[] = {
  127209. 1, 3, 4, 5, 5, 7, 6, 6, 6, 5, 7, 7, 7, 6, 6, 7,
  127210. 7, 7, 6, 6, 7, 7, 7, 6, 6,
  127211. };
  127212. static float _vq_quantthresh__8c0_s_p8_1[] = {
  127213. -1.5, -0.5, 0.5, 1.5,
  127214. };
  127215. static long _vq_quantmap__8c0_s_p8_1[] = {
  127216. 3, 1, 0, 2, 4,
  127217. };
  127218. static encode_aux_threshmatch _vq_auxt__8c0_s_p8_1 = {
  127219. _vq_quantthresh__8c0_s_p8_1,
  127220. _vq_quantmap__8c0_s_p8_1,
  127221. 5,
  127222. 5
  127223. };
  127224. static static_codebook _8c0_s_p8_1 = {
  127225. 2, 25,
  127226. _vq_lengthlist__8c0_s_p8_1,
  127227. 1, -533725184, 1611661312, 3, 0,
  127228. _vq_quantlist__8c0_s_p8_1,
  127229. NULL,
  127230. &_vq_auxt__8c0_s_p8_1,
  127231. NULL,
  127232. 0
  127233. };
  127234. static long _vq_quantlist__8c0_s_p9_0[] = {
  127235. 1,
  127236. 0,
  127237. 2,
  127238. };
  127239. static long _vq_lengthlist__8c0_s_p9_0[] = {
  127240. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  127241. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  127242. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  127243. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  127244. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  127245. 7,
  127246. };
  127247. static float _vq_quantthresh__8c0_s_p9_0[] = {
  127248. -157.5, 157.5,
  127249. };
  127250. static long _vq_quantmap__8c0_s_p9_0[] = {
  127251. 1, 0, 2,
  127252. };
  127253. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_0 = {
  127254. _vq_quantthresh__8c0_s_p9_0,
  127255. _vq_quantmap__8c0_s_p9_0,
  127256. 3,
  127257. 3
  127258. };
  127259. static static_codebook _8c0_s_p9_0 = {
  127260. 4, 81,
  127261. _vq_lengthlist__8c0_s_p9_0,
  127262. 1, -518803456, 1628680192, 2, 0,
  127263. _vq_quantlist__8c0_s_p9_0,
  127264. NULL,
  127265. &_vq_auxt__8c0_s_p9_0,
  127266. NULL,
  127267. 0
  127268. };
  127269. static long _vq_quantlist__8c0_s_p9_1[] = {
  127270. 7,
  127271. 6,
  127272. 8,
  127273. 5,
  127274. 9,
  127275. 4,
  127276. 10,
  127277. 3,
  127278. 11,
  127279. 2,
  127280. 12,
  127281. 1,
  127282. 13,
  127283. 0,
  127284. 14,
  127285. };
  127286. static long _vq_lengthlist__8c0_s_p9_1[] = {
  127287. 1, 4, 4, 5, 5,10, 8,11,11,11,11,11,11,11,11, 6,
  127288. 6, 6, 7, 6,11,10,11,11,11,11,11,11,11,11, 7, 5,
  127289. 6, 6, 6, 8, 7,11,11,11,11,11,11,11,11,11, 7, 8,
  127290. 8, 8, 9, 9,11,11,11,11,11,11,11,11,11, 9, 8, 7,
  127291. 8, 9,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  127292. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  127293. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127294. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127295. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127296. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127297. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127298. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127299. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127300. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  127301. 11,
  127302. };
  127303. static float _vq_quantthresh__8c0_s_p9_1[] = {
  127304. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  127305. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  127306. };
  127307. static long _vq_quantmap__8c0_s_p9_1[] = {
  127308. 13, 11, 9, 7, 5, 3, 1, 0,
  127309. 2, 4, 6, 8, 10, 12, 14,
  127310. };
  127311. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_1 = {
  127312. _vq_quantthresh__8c0_s_p9_1,
  127313. _vq_quantmap__8c0_s_p9_1,
  127314. 15,
  127315. 15
  127316. };
  127317. static static_codebook _8c0_s_p9_1 = {
  127318. 2, 225,
  127319. _vq_lengthlist__8c0_s_p9_1,
  127320. 1, -520986624, 1620377600, 4, 0,
  127321. _vq_quantlist__8c0_s_p9_1,
  127322. NULL,
  127323. &_vq_auxt__8c0_s_p9_1,
  127324. NULL,
  127325. 0
  127326. };
  127327. static long _vq_quantlist__8c0_s_p9_2[] = {
  127328. 10,
  127329. 9,
  127330. 11,
  127331. 8,
  127332. 12,
  127333. 7,
  127334. 13,
  127335. 6,
  127336. 14,
  127337. 5,
  127338. 15,
  127339. 4,
  127340. 16,
  127341. 3,
  127342. 17,
  127343. 2,
  127344. 18,
  127345. 1,
  127346. 19,
  127347. 0,
  127348. 20,
  127349. };
  127350. static long _vq_lengthlist__8c0_s_p9_2[] = {
  127351. 1, 5, 5, 7, 7, 8, 7, 8, 8,10,10, 9, 9,10,10,10,
  127352. 11,11,10,12,11,12,12,12, 9, 8, 8, 8, 8, 8, 9,10,
  127353. 10,10,10,11,11,11,10,11,11,12,12,11,12, 8, 8, 7,
  127354. 7, 8, 9,10,10,10, 9,10,10, 9,10,10,11,11,11,11,
  127355. 11,11, 9, 9, 9, 9, 8, 9,10,10,11,10,10,11,11,12,
  127356. 10,10,12,12,11,11,10, 9, 9,10, 8, 9,10,10,10, 9,
  127357. 10,10,11,11,10,11,10,10,10,12,12,12, 9,10, 9,10,
  127358. 9, 9,10,10,11,11,11,11,10,10,10,11,12,11,12,11,
  127359. 12,10,11,10,11, 9,10, 9,10, 9,10,10, 9,10,10,11,
  127360. 10,11,11,11,11,12,11, 9,10,10,10,10,11,11,11,11,
  127361. 11,10,11,11,11,11,10,12,10,12,12,11,12,10,10,11,
  127362. 10, 9,11,10,11, 9,10,11,10,10,10,11,11,11,11,12,
  127363. 12,10, 9, 9,11,10, 9,12,11,10,12,12,11,11,11,11,
  127364. 10,11,11,12,11,10,12, 9,11,10,11,10,10,11,10,11,
  127365. 9,10,10,10,11,12,11,11,12,11,10,10,11,11, 9,10,
  127366. 10,12,10,11,10,10,10, 9,10,10,10,10, 9,10,10,11,
  127367. 11,11,11,12,11,10,10,10,10,11,11,10,11,11, 9,11,
  127368. 10,12,10,12,11,10,11,10,10,10,11,10,10,11,11,10,
  127369. 11,10,10,10,10,11,11,12,10,10,10,11,10,11,12,11,
  127370. 10,11,10,10,11,11,10,12,10, 9,10,10,11,11,11,10,
  127371. 12,10,10,11,11,11,10,10,11,10,10,10,11,10,11,10,
  127372. 12,11,11,10,10,10,12,10,10,11, 9,10,11,11,11,10,
  127373. 10,11,10,10, 9,11,11,12,12,11,12,11,11,11,11,11,
  127374. 11, 9,10,11,10,12,10,10,10,10,11,10,10,11,10,10,
  127375. 12,10,10,10,10,10, 9,12,10,10,10,10,12, 9,11,10,
  127376. 10,11,10,12,12,10,12,12,12,10,10,10,10, 9,10,11,
  127377. 10,10,12,10,10,12,11,10,11,10,10,12,11,10,12,10,
  127378. 10,11, 9,11,10, 9,10, 9,10,
  127379. };
  127380. static float _vq_quantthresh__8c0_s_p9_2[] = {
  127381. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  127382. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  127383. 6.5, 7.5, 8.5, 9.5,
  127384. };
  127385. static long _vq_quantmap__8c0_s_p9_2[] = {
  127386. 19, 17, 15, 13, 11, 9, 7, 5,
  127387. 3, 1, 0, 2, 4, 6, 8, 10,
  127388. 12, 14, 16, 18, 20,
  127389. };
  127390. static encode_aux_threshmatch _vq_auxt__8c0_s_p9_2 = {
  127391. _vq_quantthresh__8c0_s_p9_2,
  127392. _vq_quantmap__8c0_s_p9_2,
  127393. 21,
  127394. 21
  127395. };
  127396. static static_codebook _8c0_s_p9_2 = {
  127397. 2, 441,
  127398. _vq_lengthlist__8c0_s_p9_2,
  127399. 1, -529268736, 1611661312, 5, 0,
  127400. _vq_quantlist__8c0_s_p9_2,
  127401. NULL,
  127402. &_vq_auxt__8c0_s_p9_2,
  127403. NULL,
  127404. 0
  127405. };
  127406. static long _huff_lengthlist__8c0_s_single[] = {
  127407. 4, 5,18, 7,10, 6, 7, 8, 9,10, 5, 2,18, 5, 7, 5,
  127408. 6, 7, 8,11,17,17,17,17,17,17,17,17,17,17, 7, 4,
  127409. 17, 6, 9, 6, 8,10,12,15,11, 7,17, 9, 6, 6, 7, 9,
  127410. 11,15, 6, 4,17, 6, 6, 4, 5, 8,11,16, 6, 6,17, 8,
  127411. 6, 5, 6, 9,13,16, 8, 9,17,11, 9, 8, 8,11,13,17,
  127412. 9,12,17,15,14,13,12,13,14,17,12,15,17,17,17,17,
  127413. 17,16,17,17,
  127414. };
  127415. static static_codebook _huff_book__8c0_s_single = {
  127416. 2, 100,
  127417. _huff_lengthlist__8c0_s_single,
  127418. 0, 0, 0, 0, 0,
  127419. NULL,
  127420. NULL,
  127421. NULL,
  127422. NULL,
  127423. 0
  127424. };
  127425. static long _vq_quantlist__8c1_s_p1_0[] = {
  127426. 1,
  127427. 0,
  127428. 2,
  127429. };
  127430. static long _vq_lengthlist__8c1_s_p1_0[] = {
  127431. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  127432. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127436. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0,
  127437. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127441. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  127442. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127449. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127450. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127451. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127452. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127453. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127454. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127455. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127456. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127457. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127458. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127459. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127460. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127461. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127462. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127463. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127464. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127465. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127466. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127467. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127468. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127469. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127470. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127471. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127472. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127473. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127474. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127475. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127476. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  127477. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  127478. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127479. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127480. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127481. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  127482. 0, 0, 0, 8, 8,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  127483. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127484. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127485. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127486. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  127487. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127488. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127489. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127490. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127491. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127492. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127493. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127494. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127495. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127496. 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127509. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127510. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127522. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  127523. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127527. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  127528. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  127529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127532. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  127533. 0, 0, 0, 0, 0, 0, 8,10, 8, 0, 0, 0, 0, 0, 0, 0,
  127534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127545. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127550. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127555. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  127641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127841. 0,
  127842. };
  127843. static float _vq_quantthresh__8c1_s_p1_0[] = {
  127844. -0.5, 0.5,
  127845. };
  127846. static long _vq_quantmap__8c1_s_p1_0[] = {
  127847. 1, 0, 2,
  127848. };
  127849. static encode_aux_threshmatch _vq_auxt__8c1_s_p1_0 = {
  127850. _vq_quantthresh__8c1_s_p1_0,
  127851. _vq_quantmap__8c1_s_p1_0,
  127852. 3,
  127853. 3
  127854. };
  127855. static static_codebook _8c1_s_p1_0 = {
  127856. 8, 6561,
  127857. _vq_lengthlist__8c1_s_p1_0,
  127858. 1, -535822336, 1611661312, 2, 0,
  127859. _vq_quantlist__8c1_s_p1_0,
  127860. NULL,
  127861. &_vq_auxt__8c1_s_p1_0,
  127862. NULL,
  127863. 0
  127864. };
  127865. static long _vq_quantlist__8c1_s_p2_0[] = {
  127866. 2,
  127867. 1,
  127868. 3,
  127869. 0,
  127870. 4,
  127871. };
  127872. static long _vq_lengthlist__8c1_s_p2_0[] = {
  127873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127912. 0,
  127913. };
  127914. static float _vq_quantthresh__8c1_s_p2_0[] = {
  127915. -1.5, -0.5, 0.5, 1.5,
  127916. };
  127917. static long _vq_quantmap__8c1_s_p2_0[] = {
  127918. 3, 1, 0, 2, 4,
  127919. };
  127920. static encode_aux_threshmatch _vq_auxt__8c1_s_p2_0 = {
  127921. _vq_quantthresh__8c1_s_p2_0,
  127922. _vq_quantmap__8c1_s_p2_0,
  127923. 5,
  127924. 5
  127925. };
  127926. static static_codebook _8c1_s_p2_0 = {
  127927. 4, 625,
  127928. _vq_lengthlist__8c1_s_p2_0,
  127929. 1, -533725184, 1611661312, 3, 0,
  127930. _vq_quantlist__8c1_s_p2_0,
  127931. NULL,
  127932. &_vq_auxt__8c1_s_p2_0,
  127933. NULL,
  127934. 0
  127935. };
  127936. static long _vq_quantlist__8c1_s_p3_0[] = {
  127937. 2,
  127938. 1,
  127939. 3,
  127940. 0,
  127941. 4,
  127942. };
  127943. static long _vq_lengthlist__8c1_s_p3_0[] = {
  127944. 2, 4, 4, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  127946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127947. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 7, 7,
  127949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127950. 0, 0, 0, 0, 6, 6, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  127951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  127983. 0,
  127984. };
  127985. static float _vq_quantthresh__8c1_s_p3_0[] = {
  127986. -1.5, -0.5, 0.5, 1.5,
  127987. };
  127988. static long _vq_quantmap__8c1_s_p3_0[] = {
  127989. 3, 1, 0, 2, 4,
  127990. };
  127991. static encode_aux_threshmatch _vq_auxt__8c1_s_p3_0 = {
  127992. _vq_quantthresh__8c1_s_p3_0,
  127993. _vq_quantmap__8c1_s_p3_0,
  127994. 5,
  127995. 5
  127996. };
  127997. static static_codebook _8c1_s_p3_0 = {
  127998. 4, 625,
  127999. _vq_lengthlist__8c1_s_p3_0,
  128000. 1, -533725184, 1611661312, 3, 0,
  128001. _vq_quantlist__8c1_s_p3_0,
  128002. NULL,
  128003. &_vq_auxt__8c1_s_p3_0,
  128004. NULL,
  128005. 0
  128006. };
  128007. static long _vq_quantlist__8c1_s_p4_0[] = {
  128008. 4,
  128009. 3,
  128010. 5,
  128011. 2,
  128012. 6,
  128013. 1,
  128014. 7,
  128015. 0,
  128016. 8,
  128017. };
  128018. static long _vq_lengthlist__8c1_s_p4_0[] = {
  128019. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  128020. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  128021. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  128022. 8, 8, 0, 0, 0, 0, 0, 0, 0, 9, 8, 0, 0, 0, 0, 0,
  128023. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128024. 0,
  128025. };
  128026. static float _vq_quantthresh__8c1_s_p4_0[] = {
  128027. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128028. };
  128029. static long _vq_quantmap__8c1_s_p4_0[] = {
  128030. 7, 5, 3, 1, 0, 2, 4, 6,
  128031. 8,
  128032. };
  128033. static encode_aux_threshmatch _vq_auxt__8c1_s_p4_0 = {
  128034. _vq_quantthresh__8c1_s_p4_0,
  128035. _vq_quantmap__8c1_s_p4_0,
  128036. 9,
  128037. 9
  128038. };
  128039. static static_codebook _8c1_s_p4_0 = {
  128040. 2, 81,
  128041. _vq_lengthlist__8c1_s_p4_0,
  128042. 1, -531628032, 1611661312, 4, 0,
  128043. _vq_quantlist__8c1_s_p4_0,
  128044. NULL,
  128045. &_vq_auxt__8c1_s_p4_0,
  128046. NULL,
  128047. 0
  128048. };
  128049. static long _vq_quantlist__8c1_s_p5_0[] = {
  128050. 4,
  128051. 3,
  128052. 5,
  128053. 2,
  128054. 6,
  128055. 1,
  128056. 7,
  128057. 0,
  128058. 8,
  128059. };
  128060. static long _vq_lengthlist__8c1_s_p5_0[] = {
  128061. 1, 3, 3, 4, 5, 6, 6, 8, 8, 0, 0, 0, 8, 8, 7, 7,
  128062. 9, 9, 0, 0, 0, 8, 8, 7, 7, 9, 9, 0, 0, 0, 9,10,
  128063. 8, 8, 9, 9, 0, 0, 0,10,10, 8, 8, 9, 9, 0, 0, 0,
  128064. 11,10, 8, 8,10,10, 0, 0, 0,11,11, 8, 8,10,10, 0,
  128065. 0, 0,12,12, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  128066. 10,
  128067. };
  128068. static float _vq_quantthresh__8c1_s_p5_0[] = {
  128069. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  128070. };
  128071. static long _vq_quantmap__8c1_s_p5_0[] = {
  128072. 7, 5, 3, 1, 0, 2, 4, 6,
  128073. 8,
  128074. };
  128075. static encode_aux_threshmatch _vq_auxt__8c1_s_p5_0 = {
  128076. _vq_quantthresh__8c1_s_p5_0,
  128077. _vq_quantmap__8c1_s_p5_0,
  128078. 9,
  128079. 9
  128080. };
  128081. static static_codebook _8c1_s_p5_0 = {
  128082. 2, 81,
  128083. _vq_lengthlist__8c1_s_p5_0,
  128084. 1, -531628032, 1611661312, 4, 0,
  128085. _vq_quantlist__8c1_s_p5_0,
  128086. NULL,
  128087. &_vq_auxt__8c1_s_p5_0,
  128088. NULL,
  128089. 0
  128090. };
  128091. static long _vq_quantlist__8c1_s_p6_0[] = {
  128092. 8,
  128093. 7,
  128094. 9,
  128095. 6,
  128096. 10,
  128097. 5,
  128098. 11,
  128099. 4,
  128100. 12,
  128101. 3,
  128102. 13,
  128103. 2,
  128104. 14,
  128105. 1,
  128106. 15,
  128107. 0,
  128108. 16,
  128109. };
  128110. static long _vq_lengthlist__8c1_s_p6_0[] = {
  128111. 1, 3, 3, 5, 5, 8, 8, 8, 8, 9, 9,10,10,11,11,11,
  128112. 11, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11,
  128113. 12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128114. 11,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,11,
  128115. 12,12,12,12, 0, 0, 0, 9, 9, 8, 8,10,10,10,10,11,
  128116. 11,12,12,12,12, 0, 0, 0,10,10, 9, 9,10,10,10,10,
  128117. 11,11,12,12,13,13, 0, 0, 0,10,10, 9, 9,10,10,10,
  128118. 10,11,11,12,12,13,13, 0, 0, 0,11,11, 9, 9,10,10,
  128119. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  128120. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  128121. 10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0, 0, 9,
  128122. 9,10,10,11,11,12,11,12,12,13,13, 0, 0, 0, 0, 0,
  128123. 10,10,11,11,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  128124. 0, 0, 0,11,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  128125. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  128126. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,13, 0,
  128127. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  128128. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  128129. 14,
  128130. };
  128131. static float _vq_quantthresh__8c1_s_p6_0[] = {
  128132. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  128133. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  128134. };
  128135. static long _vq_quantmap__8c1_s_p6_0[] = {
  128136. 15, 13, 11, 9, 7, 5, 3, 1,
  128137. 0, 2, 4, 6, 8, 10, 12, 14,
  128138. 16,
  128139. };
  128140. static encode_aux_threshmatch _vq_auxt__8c1_s_p6_0 = {
  128141. _vq_quantthresh__8c1_s_p6_0,
  128142. _vq_quantmap__8c1_s_p6_0,
  128143. 17,
  128144. 17
  128145. };
  128146. static static_codebook _8c1_s_p6_0 = {
  128147. 2, 289,
  128148. _vq_lengthlist__8c1_s_p6_0,
  128149. 1, -529530880, 1611661312, 5, 0,
  128150. _vq_quantlist__8c1_s_p6_0,
  128151. NULL,
  128152. &_vq_auxt__8c1_s_p6_0,
  128153. NULL,
  128154. 0
  128155. };
  128156. static long _vq_quantlist__8c1_s_p7_0[] = {
  128157. 1,
  128158. 0,
  128159. 2,
  128160. };
  128161. static long _vq_lengthlist__8c1_s_p7_0[] = {
  128162. 1, 4, 4, 6, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  128163. 9, 9, 5, 7, 7,10, 9, 9,10, 9, 9, 6,10,10,10,10,
  128164. 10,11,10,10, 6, 9, 9,10, 9,10,11,10,10, 6, 9, 9,
  128165. 10, 9, 9,11, 9,10, 7,10,10,11,11,11,11,10,10, 6,
  128166. 9, 9,10,10,10,11, 9, 9, 6, 9, 9,10,10,10,10, 9,
  128167. 9,
  128168. };
  128169. static float _vq_quantthresh__8c1_s_p7_0[] = {
  128170. -5.5, 5.5,
  128171. };
  128172. static long _vq_quantmap__8c1_s_p7_0[] = {
  128173. 1, 0, 2,
  128174. };
  128175. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_0 = {
  128176. _vq_quantthresh__8c1_s_p7_0,
  128177. _vq_quantmap__8c1_s_p7_0,
  128178. 3,
  128179. 3
  128180. };
  128181. static static_codebook _8c1_s_p7_0 = {
  128182. 4, 81,
  128183. _vq_lengthlist__8c1_s_p7_0,
  128184. 1, -529137664, 1618345984, 2, 0,
  128185. _vq_quantlist__8c1_s_p7_0,
  128186. NULL,
  128187. &_vq_auxt__8c1_s_p7_0,
  128188. NULL,
  128189. 0
  128190. };
  128191. static long _vq_quantlist__8c1_s_p7_1[] = {
  128192. 5,
  128193. 4,
  128194. 6,
  128195. 3,
  128196. 7,
  128197. 2,
  128198. 8,
  128199. 1,
  128200. 9,
  128201. 0,
  128202. 10,
  128203. };
  128204. static long _vq_lengthlist__8c1_s_p7_1[] = {
  128205. 2, 3, 3, 5, 5, 7, 7, 7, 7, 7, 7,10,10, 9, 7, 7,
  128206. 7, 7, 8, 8, 8, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8, 8,
  128207. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  128208. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  128209. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  128210. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  128211. 8, 8, 8,10,10,10,10,10, 8, 8, 8, 8, 8, 8,10,10,
  128212. 10,10,10, 8, 8, 8, 8, 8, 8,
  128213. };
  128214. static float _vq_quantthresh__8c1_s_p7_1[] = {
  128215. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  128216. 3.5, 4.5,
  128217. };
  128218. static long _vq_quantmap__8c1_s_p7_1[] = {
  128219. 9, 7, 5, 3, 1, 0, 2, 4,
  128220. 6, 8, 10,
  128221. };
  128222. static encode_aux_threshmatch _vq_auxt__8c1_s_p7_1 = {
  128223. _vq_quantthresh__8c1_s_p7_1,
  128224. _vq_quantmap__8c1_s_p7_1,
  128225. 11,
  128226. 11
  128227. };
  128228. static static_codebook _8c1_s_p7_1 = {
  128229. 2, 121,
  128230. _vq_lengthlist__8c1_s_p7_1,
  128231. 1, -531365888, 1611661312, 4, 0,
  128232. _vq_quantlist__8c1_s_p7_1,
  128233. NULL,
  128234. &_vq_auxt__8c1_s_p7_1,
  128235. NULL,
  128236. 0
  128237. };
  128238. static long _vq_quantlist__8c1_s_p8_0[] = {
  128239. 6,
  128240. 5,
  128241. 7,
  128242. 4,
  128243. 8,
  128244. 3,
  128245. 9,
  128246. 2,
  128247. 10,
  128248. 1,
  128249. 11,
  128250. 0,
  128251. 12,
  128252. };
  128253. static long _vq_lengthlist__8c1_s_p8_0[] = {
  128254. 1, 4, 4, 6, 6, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5,
  128255. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  128256. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  128257. 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  128258. 11, 0,12,12, 9, 9, 9, 9,10, 9,10,11,11,11, 0,13,
  128259. 12, 9, 8, 9, 9,10,10,11,11,12,11, 0, 0, 0, 9, 9,
  128260. 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10, 9, 9,10,
  128261. 10,11,11,12,12, 0, 0, 0,13,13,10,10,11,11,12,11,
  128262. 13,12, 0, 0, 0,14,14,10,10,11,10,11,11,12,12, 0,
  128263. 0, 0, 0, 0,12,12,11,11,12,12,13,13, 0, 0, 0, 0,
  128264. 0,12,12,11,10,12,11,13,12,
  128265. };
  128266. static float _vq_quantthresh__8c1_s_p8_0[] = {
  128267. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  128268. 12.5, 17.5, 22.5, 27.5,
  128269. };
  128270. static long _vq_quantmap__8c1_s_p8_0[] = {
  128271. 11, 9, 7, 5, 3, 1, 0, 2,
  128272. 4, 6, 8, 10, 12,
  128273. };
  128274. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_0 = {
  128275. _vq_quantthresh__8c1_s_p8_0,
  128276. _vq_quantmap__8c1_s_p8_0,
  128277. 13,
  128278. 13
  128279. };
  128280. static static_codebook _8c1_s_p8_0 = {
  128281. 2, 169,
  128282. _vq_lengthlist__8c1_s_p8_0,
  128283. 1, -526516224, 1616117760, 4, 0,
  128284. _vq_quantlist__8c1_s_p8_0,
  128285. NULL,
  128286. &_vq_auxt__8c1_s_p8_0,
  128287. NULL,
  128288. 0
  128289. };
  128290. static long _vq_quantlist__8c1_s_p8_1[] = {
  128291. 2,
  128292. 1,
  128293. 3,
  128294. 0,
  128295. 4,
  128296. };
  128297. static long _vq_lengthlist__8c1_s_p8_1[] = {
  128298. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  128299. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  128300. };
  128301. static float _vq_quantthresh__8c1_s_p8_1[] = {
  128302. -1.5, -0.5, 0.5, 1.5,
  128303. };
  128304. static long _vq_quantmap__8c1_s_p8_1[] = {
  128305. 3, 1, 0, 2, 4,
  128306. };
  128307. static encode_aux_threshmatch _vq_auxt__8c1_s_p8_1 = {
  128308. _vq_quantthresh__8c1_s_p8_1,
  128309. _vq_quantmap__8c1_s_p8_1,
  128310. 5,
  128311. 5
  128312. };
  128313. static static_codebook _8c1_s_p8_1 = {
  128314. 2, 25,
  128315. _vq_lengthlist__8c1_s_p8_1,
  128316. 1, -533725184, 1611661312, 3, 0,
  128317. _vq_quantlist__8c1_s_p8_1,
  128318. NULL,
  128319. &_vq_auxt__8c1_s_p8_1,
  128320. NULL,
  128321. 0
  128322. };
  128323. static long _vq_quantlist__8c1_s_p9_0[] = {
  128324. 6,
  128325. 5,
  128326. 7,
  128327. 4,
  128328. 8,
  128329. 3,
  128330. 9,
  128331. 2,
  128332. 10,
  128333. 1,
  128334. 11,
  128335. 0,
  128336. 12,
  128337. };
  128338. static long _vq_lengthlist__8c1_s_p9_0[] = {
  128339. 1, 3, 3,10,10,10,10,10,10,10,10,10,10, 5, 6, 6,
  128340. 10,10,10,10,10,10,10,10,10,10, 6, 7, 8,10,10,10,
  128341. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128342. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128343. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128344. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128345. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128346. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128347. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128348. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128349. 10,10,10,10,10, 9, 9, 9, 9,
  128350. };
  128351. static float _vq_quantthresh__8c1_s_p9_0[] = {
  128352. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  128353. 787.5, 1102.5, 1417.5, 1732.5,
  128354. };
  128355. static long _vq_quantmap__8c1_s_p9_0[] = {
  128356. 11, 9, 7, 5, 3, 1, 0, 2,
  128357. 4, 6, 8, 10, 12,
  128358. };
  128359. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_0 = {
  128360. _vq_quantthresh__8c1_s_p9_0,
  128361. _vq_quantmap__8c1_s_p9_0,
  128362. 13,
  128363. 13
  128364. };
  128365. static static_codebook _8c1_s_p9_0 = {
  128366. 2, 169,
  128367. _vq_lengthlist__8c1_s_p9_0,
  128368. 1, -513964032, 1628680192, 4, 0,
  128369. _vq_quantlist__8c1_s_p9_0,
  128370. NULL,
  128371. &_vq_auxt__8c1_s_p9_0,
  128372. NULL,
  128373. 0
  128374. };
  128375. static long _vq_quantlist__8c1_s_p9_1[] = {
  128376. 7,
  128377. 6,
  128378. 8,
  128379. 5,
  128380. 9,
  128381. 4,
  128382. 10,
  128383. 3,
  128384. 11,
  128385. 2,
  128386. 12,
  128387. 1,
  128388. 13,
  128389. 0,
  128390. 14,
  128391. };
  128392. static long _vq_lengthlist__8c1_s_p9_1[] = {
  128393. 1, 4, 4, 5, 5, 7, 7, 9, 9,11,11,12,12,13,13, 6,
  128394. 5, 5, 6, 6, 9, 9,10,10,12,12,12,13,15,14, 6, 5,
  128395. 5, 7, 7, 9, 9,10,10,12,12,12,13,14,13,17, 7, 7,
  128396. 8, 8,10,10,11,11,12,13,13,13,13,13,17, 7, 7, 8,
  128397. 8,10,10,11,11,13,13,13,13,14,14,17,11,11, 9, 9,
  128398. 11,11,12,12,12,13,13,14,15,13,17,12,12, 9, 9,11,
  128399. 11,12,12,13,13,13,13,14,16,17,17,17,11,12,12,12,
  128400. 13,13,13,14,15,14,15,15,17,17,17,12,12,11,11,13,
  128401. 13,14,14,15,14,15,15,17,17,17,15,15,13,13,14,14,
  128402. 15,14,15,15,16,15,17,17,17,15,15,13,13,13,14,14,
  128403. 15,15,15,15,16,17,17,17,17,16,14,15,14,14,15,14,
  128404. 14,15,15,15,17,17,17,17,17,14,14,16,14,15,15,15,
  128405. 15,15,15,17,17,17,17,17,17,16,16,15,17,15,15,14,
  128406. 17,15,17,16,17,17,17,17,16,15,14,15,15,15,15,15,
  128407. 15,
  128408. };
  128409. static float _vq_quantthresh__8c1_s_p9_1[] = {
  128410. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  128411. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  128412. };
  128413. static long _vq_quantmap__8c1_s_p9_1[] = {
  128414. 13, 11, 9, 7, 5, 3, 1, 0,
  128415. 2, 4, 6, 8, 10, 12, 14,
  128416. };
  128417. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_1 = {
  128418. _vq_quantthresh__8c1_s_p9_1,
  128419. _vq_quantmap__8c1_s_p9_1,
  128420. 15,
  128421. 15
  128422. };
  128423. static static_codebook _8c1_s_p9_1 = {
  128424. 2, 225,
  128425. _vq_lengthlist__8c1_s_p9_1,
  128426. 1, -520986624, 1620377600, 4, 0,
  128427. _vq_quantlist__8c1_s_p9_1,
  128428. NULL,
  128429. &_vq_auxt__8c1_s_p9_1,
  128430. NULL,
  128431. 0
  128432. };
  128433. static long _vq_quantlist__8c1_s_p9_2[] = {
  128434. 10,
  128435. 9,
  128436. 11,
  128437. 8,
  128438. 12,
  128439. 7,
  128440. 13,
  128441. 6,
  128442. 14,
  128443. 5,
  128444. 15,
  128445. 4,
  128446. 16,
  128447. 3,
  128448. 17,
  128449. 2,
  128450. 18,
  128451. 1,
  128452. 19,
  128453. 0,
  128454. 20,
  128455. };
  128456. static long _vq_lengthlist__8c1_s_p9_2[] = {
  128457. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  128458. 9, 9, 9, 9, 9,11,11,12, 7, 7, 7, 7, 8, 8, 9, 9,
  128459. 9, 9,10,10,10,10,10,10,10,10,11,11,11, 7, 7, 7,
  128460. 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,11,
  128461. 11,12, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,
  128462. 10,10,10,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  128463. 9,10,10,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  128464. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,11,11,
  128465. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  128466. 10,10,10,11,12,11, 9, 9, 8, 9, 9, 9, 9, 9,10,10,
  128467. 10,10,10,10,10,10,10,10,11,11,11,11,11, 8, 8, 9,
  128468. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,11,12,11,
  128469. 12,11, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  128470. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  128471. 10,10,10,10,10,10,10,12,11,12,11,11, 9, 9, 9,10,
  128472. 10,10,10,10,10,10,10,10,10,10,10,10,12,11,11,11,
  128473. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128474. 11,11,11,12,11,11,12,11,10,10,10,10,10,10,10,10,
  128475. 10,10,10,10,11,10,11,11,11,11,11,11,11,10,10,10,
  128476. 10,10,10,10,10,10,10,10,10,10,10,11,11,12,11,12,
  128477. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  128478. 11,11,12,11,12,11,11,11,11,10,10,10,10,10,10,10,
  128479. 10,10,10,10,10,11,11,12,11,11,12,11,11,12,10,10,
  128480. 11,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  128481. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,12,
  128482. 12,11,12,11,11,12,12,12,11,11,10,10,10,10,10,10,
  128483. 10,10,10,11,12,12,11,12,12,11,12,11,11,11,11,10,
  128484. 10,10,10,10,10,10,10,10,10,
  128485. };
  128486. static float _vq_quantthresh__8c1_s_p9_2[] = {
  128487. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  128488. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  128489. 6.5, 7.5, 8.5, 9.5,
  128490. };
  128491. static long _vq_quantmap__8c1_s_p9_2[] = {
  128492. 19, 17, 15, 13, 11, 9, 7, 5,
  128493. 3, 1, 0, 2, 4, 6, 8, 10,
  128494. 12, 14, 16, 18, 20,
  128495. };
  128496. static encode_aux_threshmatch _vq_auxt__8c1_s_p9_2 = {
  128497. _vq_quantthresh__8c1_s_p9_2,
  128498. _vq_quantmap__8c1_s_p9_2,
  128499. 21,
  128500. 21
  128501. };
  128502. static static_codebook _8c1_s_p9_2 = {
  128503. 2, 441,
  128504. _vq_lengthlist__8c1_s_p9_2,
  128505. 1, -529268736, 1611661312, 5, 0,
  128506. _vq_quantlist__8c1_s_p9_2,
  128507. NULL,
  128508. &_vq_auxt__8c1_s_p9_2,
  128509. NULL,
  128510. 0
  128511. };
  128512. static long _huff_lengthlist__8c1_s_single[] = {
  128513. 4, 6,18, 8,11, 8, 8, 9, 9,10, 4, 4,18, 5, 9, 5,
  128514. 6, 7, 8,10,18,18,18,18,17,17,17,17,17,17, 7, 5,
  128515. 17, 6,11, 6, 7, 8, 9,12,12, 9,17,12, 8, 8, 9,10,
  128516. 10,13, 7, 5,17, 6, 8, 4, 5, 6, 8,10, 6, 5,17, 6,
  128517. 8, 5, 4, 5, 7, 9, 7, 7,17, 8, 9, 6, 5, 5, 6, 8,
  128518. 8, 8,17, 9,11, 8, 6, 6, 6, 7, 9,10,17,12,12,10,
  128519. 9, 7, 7, 8,
  128520. };
  128521. static static_codebook _huff_book__8c1_s_single = {
  128522. 2, 100,
  128523. _huff_lengthlist__8c1_s_single,
  128524. 0, 0, 0, 0, 0,
  128525. NULL,
  128526. NULL,
  128527. NULL,
  128528. NULL,
  128529. 0
  128530. };
  128531. static long _huff_lengthlist__44c2_s_long[] = {
  128532. 6, 6,12,10,10,10, 9,10,12,12, 6, 1,10, 5, 6, 6,
  128533. 7, 9,11,14,12, 9, 8,11, 7, 8, 9,11,13,15,10, 5,
  128534. 12, 7, 8, 7, 9,12,14,15,10, 6, 7, 8, 5, 6, 7, 9,
  128535. 12,14, 9, 6, 8, 7, 6, 6, 7, 9,12,12, 9, 7, 9, 9,
  128536. 7, 6, 6, 7,10,10,10, 9,10,11, 8, 7, 6, 6, 8,10,
  128537. 12,11,13,13,11,10, 8, 8, 8,10,11,13,15,15,14,13,
  128538. 10, 8, 8, 9,
  128539. };
  128540. static static_codebook _huff_book__44c2_s_long = {
  128541. 2, 100,
  128542. _huff_lengthlist__44c2_s_long,
  128543. 0, 0, 0, 0, 0,
  128544. NULL,
  128545. NULL,
  128546. NULL,
  128547. NULL,
  128548. 0
  128549. };
  128550. static long _vq_quantlist__44c2_s_p1_0[] = {
  128551. 1,
  128552. 0,
  128553. 2,
  128554. };
  128555. static long _vq_lengthlist__44c2_s_p1_0[] = {
  128556. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  128557. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128561. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128562. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128566. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  128567. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  128602. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  128607. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  128612. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128647. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  128648. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128652. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  128653. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  128654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128657. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  128658. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  128659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  128966. 0,
  128967. };
  128968. static float _vq_quantthresh__44c2_s_p1_0[] = {
  128969. -0.5, 0.5,
  128970. };
  128971. static long _vq_quantmap__44c2_s_p1_0[] = {
  128972. 1, 0, 2,
  128973. };
  128974. static encode_aux_threshmatch _vq_auxt__44c2_s_p1_0 = {
  128975. _vq_quantthresh__44c2_s_p1_0,
  128976. _vq_quantmap__44c2_s_p1_0,
  128977. 3,
  128978. 3
  128979. };
  128980. static static_codebook _44c2_s_p1_0 = {
  128981. 8, 6561,
  128982. _vq_lengthlist__44c2_s_p1_0,
  128983. 1, -535822336, 1611661312, 2, 0,
  128984. _vq_quantlist__44c2_s_p1_0,
  128985. NULL,
  128986. &_vq_auxt__44c2_s_p1_0,
  128987. NULL,
  128988. 0
  128989. };
  128990. static long _vq_quantlist__44c2_s_p2_0[] = {
  128991. 2,
  128992. 1,
  128993. 3,
  128994. 0,
  128995. 4,
  128996. };
  128997. static long _vq_lengthlist__44c2_s_p2_0[] = {
  128998. 1, 4, 4, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0,
  128999. 8, 8, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  129000. 8, 0, 0, 0, 8, 8, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  129001. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0,
  129002. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129007. 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,11,11, 0, 0,
  129008. 0,11,11, 0, 0, 0,12,11, 0, 0, 0, 0, 0, 0, 0, 7,
  129009. 8, 8, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0, 0,11,
  129010. 12, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129015. 0, 0, 0, 6, 8, 8, 0, 0, 0,11,11, 0, 0, 0,11,11,
  129016. 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0,
  129017. 0, 0,10,11, 0, 0, 0,10,11, 0, 0, 0,11,11, 0, 0,
  129018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129023. 8, 9, 9, 0, 0, 0,11,12, 0, 0, 0,11,12, 0, 0, 0,
  129024. 12,11, 0, 0, 0, 0, 0, 0, 0, 8,10, 9, 0, 0, 0,12,
  129025. 11, 0, 0, 0,12,11, 0, 0, 0,11,12, 0, 0, 0, 0, 0,
  129026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129037. 0,
  129038. };
  129039. static float _vq_quantthresh__44c2_s_p2_0[] = {
  129040. -1.5, -0.5, 0.5, 1.5,
  129041. };
  129042. static long _vq_quantmap__44c2_s_p2_0[] = {
  129043. 3, 1, 0, 2, 4,
  129044. };
  129045. static encode_aux_threshmatch _vq_auxt__44c2_s_p2_0 = {
  129046. _vq_quantthresh__44c2_s_p2_0,
  129047. _vq_quantmap__44c2_s_p2_0,
  129048. 5,
  129049. 5
  129050. };
  129051. static static_codebook _44c2_s_p2_0 = {
  129052. 4, 625,
  129053. _vq_lengthlist__44c2_s_p2_0,
  129054. 1, -533725184, 1611661312, 3, 0,
  129055. _vq_quantlist__44c2_s_p2_0,
  129056. NULL,
  129057. &_vq_auxt__44c2_s_p2_0,
  129058. NULL,
  129059. 0
  129060. };
  129061. static long _vq_quantlist__44c2_s_p3_0[] = {
  129062. 2,
  129063. 1,
  129064. 3,
  129065. 0,
  129066. 4,
  129067. };
  129068. static long _vq_lengthlist__44c2_s_p3_0[] = {
  129069. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  129071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129072. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  129074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129075. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  129076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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,
  129109. };
  129110. static float _vq_quantthresh__44c2_s_p3_0[] = {
  129111. -1.5, -0.5, 0.5, 1.5,
  129112. };
  129113. static long _vq_quantmap__44c2_s_p3_0[] = {
  129114. 3, 1, 0, 2, 4,
  129115. };
  129116. static encode_aux_threshmatch _vq_auxt__44c2_s_p3_0 = {
  129117. _vq_quantthresh__44c2_s_p3_0,
  129118. _vq_quantmap__44c2_s_p3_0,
  129119. 5,
  129120. 5
  129121. };
  129122. static static_codebook _44c2_s_p3_0 = {
  129123. 4, 625,
  129124. _vq_lengthlist__44c2_s_p3_0,
  129125. 1, -533725184, 1611661312, 3, 0,
  129126. _vq_quantlist__44c2_s_p3_0,
  129127. NULL,
  129128. &_vq_auxt__44c2_s_p3_0,
  129129. NULL,
  129130. 0
  129131. };
  129132. static long _vq_quantlist__44c2_s_p4_0[] = {
  129133. 4,
  129134. 3,
  129135. 5,
  129136. 2,
  129137. 6,
  129138. 1,
  129139. 7,
  129140. 0,
  129141. 8,
  129142. };
  129143. static long _vq_lengthlist__44c2_s_p4_0[] = {
  129144. 1, 3, 3, 6, 6, 0, 0, 0, 0, 0, 6, 6, 6, 6, 0, 0,
  129145. 0, 0, 0, 6, 6, 6, 6, 0, 0, 0, 0, 0, 7, 7, 6, 6,
  129146. 0, 0, 0, 0, 0, 0, 0, 6, 7, 0, 0, 0, 0, 0, 0, 0,
  129147. 7, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  129148. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129149. 0,
  129150. };
  129151. static float _vq_quantthresh__44c2_s_p4_0[] = {
  129152. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129153. };
  129154. static long _vq_quantmap__44c2_s_p4_0[] = {
  129155. 7, 5, 3, 1, 0, 2, 4, 6,
  129156. 8,
  129157. };
  129158. static encode_aux_threshmatch _vq_auxt__44c2_s_p4_0 = {
  129159. _vq_quantthresh__44c2_s_p4_0,
  129160. _vq_quantmap__44c2_s_p4_0,
  129161. 9,
  129162. 9
  129163. };
  129164. static static_codebook _44c2_s_p4_0 = {
  129165. 2, 81,
  129166. _vq_lengthlist__44c2_s_p4_0,
  129167. 1, -531628032, 1611661312, 4, 0,
  129168. _vq_quantlist__44c2_s_p4_0,
  129169. NULL,
  129170. &_vq_auxt__44c2_s_p4_0,
  129171. NULL,
  129172. 0
  129173. };
  129174. static long _vq_quantlist__44c2_s_p5_0[] = {
  129175. 4,
  129176. 3,
  129177. 5,
  129178. 2,
  129179. 6,
  129180. 1,
  129181. 7,
  129182. 0,
  129183. 8,
  129184. };
  129185. static long _vq_lengthlist__44c2_s_p5_0[] = {
  129186. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 7, 7, 7, 7, 7, 7,
  129187. 9, 9, 0, 7, 7, 7, 7, 7, 7, 9, 9, 0, 8, 8, 7, 7,
  129188. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  129189. 9, 9, 8, 8,10,10, 0, 0, 0, 9, 9, 8, 8,10,10, 0,
  129190. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  129191. 11,
  129192. };
  129193. static float _vq_quantthresh__44c2_s_p5_0[] = {
  129194. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  129195. };
  129196. static long _vq_quantmap__44c2_s_p5_0[] = {
  129197. 7, 5, 3, 1, 0, 2, 4, 6,
  129198. 8,
  129199. };
  129200. static encode_aux_threshmatch _vq_auxt__44c2_s_p5_0 = {
  129201. _vq_quantthresh__44c2_s_p5_0,
  129202. _vq_quantmap__44c2_s_p5_0,
  129203. 9,
  129204. 9
  129205. };
  129206. static static_codebook _44c2_s_p5_0 = {
  129207. 2, 81,
  129208. _vq_lengthlist__44c2_s_p5_0,
  129209. 1, -531628032, 1611661312, 4, 0,
  129210. _vq_quantlist__44c2_s_p5_0,
  129211. NULL,
  129212. &_vq_auxt__44c2_s_p5_0,
  129213. NULL,
  129214. 0
  129215. };
  129216. static long _vq_quantlist__44c2_s_p6_0[] = {
  129217. 8,
  129218. 7,
  129219. 9,
  129220. 6,
  129221. 10,
  129222. 5,
  129223. 11,
  129224. 4,
  129225. 12,
  129226. 3,
  129227. 13,
  129228. 2,
  129229. 14,
  129230. 1,
  129231. 15,
  129232. 0,
  129233. 16,
  129234. };
  129235. static long _vq_lengthlist__44c2_s_p6_0[] = {
  129236. 1, 4, 3, 6, 6, 8, 8, 9, 9, 9, 9, 9, 9,10,10,11,
  129237. 11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  129238. 12,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  129239. 11,11,12, 0, 8, 8, 7, 7, 9, 9,10,10, 9, 9,10,10,
  129240. 11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10, 9,10,
  129241. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  129242. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  129243. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  129244. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  129245. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  129246. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  129247. 9,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  129248. 10,10,10,10,11,11,12,12,13,12,13,13, 0, 0, 0, 0,
  129249. 0, 0, 0,10,10,11,11,12,12,13,13,13,13, 0, 0, 0,
  129250. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  129251. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  129252. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  129253. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,13,13,14,
  129254. 14,
  129255. };
  129256. static float _vq_quantthresh__44c2_s_p6_0[] = {
  129257. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129258. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129259. };
  129260. static long _vq_quantmap__44c2_s_p6_0[] = {
  129261. 15, 13, 11, 9, 7, 5, 3, 1,
  129262. 0, 2, 4, 6, 8, 10, 12, 14,
  129263. 16,
  129264. };
  129265. static encode_aux_threshmatch _vq_auxt__44c2_s_p6_0 = {
  129266. _vq_quantthresh__44c2_s_p6_0,
  129267. _vq_quantmap__44c2_s_p6_0,
  129268. 17,
  129269. 17
  129270. };
  129271. static static_codebook _44c2_s_p6_0 = {
  129272. 2, 289,
  129273. _vq_lengthlist__44c2_s_p6_0,
  129274. 1, -529530880, 1611661312, 5, 0,
  129275. _vq_quantlist__44c2_s_p6_0,
  129276. NULL,
  129277. &_vq_auxt__44c2_s_p6_0,
  129278. NULL,
  129279. 0
  129280. };
  129281. static long _vq_quantlist__44c2_s_p7_0[] = {
  129282. 1,
  129283. 0,
  129284. 2,
  129285. };
  129286. static long _vq_lengthlist__44c2_s_p7_0[] = {
  129287. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  129288. 9, 9, 4, 7, 7,10, 9, 9,10, 9, 9, 7,10,10,11,10,
  129289. 11,11,10,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  129290. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 6,
  129291. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,12,10,
  129292. 11,
  129293. };
  129294. static float _vq_quantthresh__44c2_s_p7_0[] = {
  129295. -5.5, 5.5,
  129296. };
  129297. static long _vq_quantmap__44c2_s_p7_0[] = {
  129298. 1, 0, 2,
  129299. };
  129300. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_0 = {
  129301. _vq_quantthresh__44c2_s_p7_0,
  129302. _vq_quantmap__44c2_s_p7_0,
  129303. 3,
  129304. 3
  129305. };
  129306. static static_codebook _44c2_s_p7_0 = {
  129307. 4, 81,
  129308. _vq_lengthlist__44c2_s_p7_0,
  129309. 1, -529137664, 1618345984, 2, 0,
  129310. _vq_quantlist__44c2_s_p7_0,
  129311. NULL,
  129312. &_vq_auxt__44c2_s_p7_0,
  129313. NULL,
  129314. 0
  129315. };
  129316. static long _vq_quantlist__44c2_s_p7_1[] = {
  129317. 5,
  129318. 4,
  129319. 6,
  129320. 3,
  129321. 7,
  129322. 2,
  129323. 8,
  129324. 1,
  129325. 9,
  129326. 0,
  129327. 10,
  129328. };
  129329. static long _vq_lengthlist__44c2_s_p7_1[] = {
  129330. 2, 3, 4, 6, 6, 7, 7, 7, 7, 7, 7, 9, 7, 7, 6, 6,
  129331. 7, 7, 8, 8, 8, 8, 9, 6, 6, 6, 6, 7, 7, 8, 8, 8,
  129332. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  129333. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  129334. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  129335. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  129336. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  129337. 10,10,10, 8, 8, 8, 8, 8, 8,
  129338. };
  129339. static float _vq_quantthresh__44c2_s_p7_1[] = {
  129340. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  129341. 3.5, 4.5,
  129342. };
  129343. static long _vq_quantmap__44c2_s_p7_1[] = {
  129344. 9, 7, 5, 3, 1, 0, 2, 4,
  129345. 6, 8, 10,
  129346. };
  129347. static encode_aux_threshmatch _vq_auxt__44c2_s_p7_1 = {
  129348. _vq_quantthresh__44c2_s_p7_1,
  129349. _vq_quantmap__44c2_s_p7_1,
  129350. 11,
  129351. 11
  129352. };
  129353. static static_codebook _44c2_s_p7_1 = {
  129354. 2, 121,
  129355. _vq_lengthlist__44c2_s_p7_1,
  129356. 1, -531365888, 1611661312, 4, 0,
  129357. _vq_quantlist__44c2_s_p7_1,
  129358. NULL,
  129359. &_vq_auxt__44c2_s_p7_1,
  129360. NULL,
  129361. 0
  129362. };
  129363. static long _vq_quantlist__44c2_s_p8_0[] = {
  129364. 6,
  129365. 5,
  129366. 7,
  129367. 4,
  129368. 8,
  129369. 3,
  129370. 9,
  129371. 2,
  129372. 10,
  129373. 1,
  129374. 11,
  129375. 0,
  129376. 12,
  129377. };
  129378. static long _vq_lengthlist__44c2_s_p8_0[] = {
  129379. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 6, 5, 5,
  129380. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  129381. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  129382. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  129383. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  129384. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  129385. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  129386. 11,12,12,12,12, 0, 0, 0,14,14,10,11,11,11,12,12,
  129387. 13,13, 0, 0, 0,14,14,11,10,11,11,13,12,13,13, 0,
  129388. 0, 0, 0, 0,12,12,11,12,13,12,14,14, 0, 0, 0, 0,
  129389. 0,12,12,12,12,13,12,14,14,
  129390. };
  129391. static float _vq_quantthresh__44c2_s_p8_0[] = {
  129392. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  129393. 12.5, 17.5, 22.5, 27.5,
  129394. };
  129395. static long _vq_quantmap__44c2_s_p8_0[] = {
  129396. 11, 9, 7, 5, 3, 1, 0, 2,
  129397. 4, 6, 8, 10, 12,
  129398. };
  129399. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_0 = {
  129400. _vq_quantthresh__44c2_s_p8_0,
  129401. _vq_quantmap__44c2_s_p8_0,
  129402. 13,
  129403. 13
  129404. };
  129405. static static_codebook _44c2_s_p8_0 = {
  129406. 2, 169,
  129407. _vq_lengthlist__44c2_s_p8_0,
  129408. 1, -526516224, 1616117760, 4, 0,
  129409. _vq_quantlist__44c2_s_p8_0,
  129410. NULL,
  129411. &_vq_auxt__44c2_s_p8_0,
  129412. NULL,
  129413. 0
  129414. };
  129415. static long _vq_quantlist__44c2_s_p8_1[] = {
  129416. 2,
  129417. 1,
  129418. 3,
  129419. 0,
  129420. 4,
  129421. };
  129422. static long _vq_lengthlist__44c2_s_p8_1[] = {
  129423. 2, 4, 4, 5, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  129424. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  129425. };
  129426. static float _vq_quantthresh__44c2_s_p8_1[] = {
  129427. -1.5, -0.5, 0.5, 1.5,
  129428. };
  129429. static long _vq_quantmap__44c2_s_p8_1[] = {
  129430. 3, 1, 0, 2, 4,
  129431. };
  129432. static encode_aux_threshmatch _vq_auxt__44c2_s_p8_1 = {
  129433. _vq_quantthresh__44c2_s_p8_1,
  129434. _vq_quantmap__44c2_s_p8_1,
  129435. 5,
  129436. 5
  129437. };
  129438. static static_codebook _44c2_s_p8_1 = {
  129439. 2, 25,
  129440. _vq_lengthlist__44c2_s_p8_1,
  129441. 1, -533725184, 1611661312, 3, 0,
  129442. _vq_quantlist__44c2_s_p8_1,
  129443. NULL,
  129444. &_vq_auxt__44c2_s_p8_1,
  129445. NULL,
  129446. 0
  129447. };
  129448. static long _vq_quantlist__44c2_s_p9_0[] = {
  129449. 6,
  129450. 5,
  129451. 7,
  129452. 4,
  129453. 8,
  129454. 3,
  129455. 9,
  129456. 2,
  129457. 10,
  129458. 1,
  129459. 11,
  129460. 0,
  129461. 12,
  129462. };
  129463. static long _vq_lengthlist__44c2_s_p9_0[] = {
  129464. 1, 5, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  129465. 11,11,11,11,11,11,11,11,11,11, 2, 8, 7,11,11,11,
  129466. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129467. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  129468. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129469. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129470. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129471. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129472. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129473. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  129474. 11,11,11,11,11,11,11,11,11,
  129475. };
  129476. static float _vq_quantthresh__44c2_s_p9_0[] = {
  129477. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  129478. 552.5, 773.5, 994.5, 1215.5,
  129479. };
  129480. static long _vq_quantmap__44c2_s_p9_0[] = {
  129481. 11, 9, 7, 5, 3, 1, 0, 2,
  129482. 4, 6, 8, 10, 12,
  129483. };
  129484. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_0 = {
  129485. _vq_quantthresh__44c2_s_p9_0,
  129486. _vq_quantmap__44c2_s_p9_0,
  129487. 13,
  129488. 13
  129489. };
  129490. static static_codebook _44c2_s_p9_0 = {
  129491. 2, 169,
  129492. _vq_lengthlist__44c2_s_p9_0,
  129493. 1, -514541568, 1627103232, 4, 0,
  129494. _vq_quantlist__44c2_s_p9_0,
  129495. NULL,
  129496. &_vq_auxt__44c2_s_p9_0,
  129497. NULL,
  129498. 0
  129499. };
  129500. static long _vq_quantlist__44c2_s_p9_1[] = {
  129501. 6,
  129502. 5,
  129503. 7,
  129504. 4,
  129505. 8,
  129506. 3,
  129507. 9,
  129508. 2,
  129509. 10,
  129510. 1,
  129511. 11,
  129512. 0,
  129513. 12,
  129514. };
  129515. static long _vq_lengthlist__44c2_s_p9_1[] = {
  129516. 1, 4, 4, 6, 6, 7, 6, 8, 8,10, 9,10,10, 6, 5, 5,
  129517. 7, 7, 8, 7,10, 9,11,11,12,13, 6, 5, 5, 7, 7, 8,
  129518. 8,10,10,11,11,13,13,18, 8, 8, 8, 8, 9, 9,10,10,
  129519. 12,12,12,13,18, 8, 8, 8, 8, 9, 9,10,10,12,12,13,
  129520. 13,18,11,11, 8, 8,10,10,11,11,12,11,13,12,18,11,
  129521. 11, 9, 7,10,10,11,11,11,12,12,13,17,17,17,10,10,
  129522. 11,11,12,12,12,10,12,12,17,17,17,11,10,11,10,13,
  129523. 12,11,12,12,12,17,17,17,15,14,11,11,12,11,13,10,
  129524. 13,12,17,17,17,14,14,12,10,11,11,13,13,13,13,17,
  129525. 17,16,17,16,13,13,12,10,13,10,14,13,17,16,17,16,
  129526. 17,13,12,12,10,13,11,14,14,
  129527. };
  129528. static float _vq_quantthresh__44c2_s_p9_1[] = {
  129529. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  129530. 42.5, 59.5, 76.5, 93.5,
  129531. };
  129532. static long _vq_quantmap__44c2_s_p9_1[] = {
  129533. 11, 9, 7, 5, 3, 1, 0, 2,
  129534. 4, 6, 8, 10, 12,
  129535. };
  129536. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_1 = {
  129537. _vq_quantthresh__44c2_s_p9_1,
  129538. _vq_quantmap__44c2_s_p9_1,
  129539. 13,
  129540. 13
  129541. };
  129542. static static_codebook _44c2_s_p9_1 = {
  129543. 2, 169,
  129544. _vq_lengthlist__44c2_s_p9_1,
  129545. 1, -522616832, 1620115456, 4, 0,
  129546. _vq_quantlist__44c2_s_p9_1,
  129547. NULL,
  129548. &_vq_auxt__44c2_s_p9_1,
  129549. NULL,
  129550. 0
  129551. };
  129552. static long _vq_quantlist__44c2_s_p9_2[] = {
  129553. 8,
  129554. 7,
  129555. 9,
  129556. 6,
  129557. 10,
  129558. 5,
  129559. 11,
  129560. 4,
  129561. 12,
  129562. 3,
  129563. 13,
  129564. 2,
  129565. 14,
  129566. 1,
  129567. 15,
  129568. 0,
  129569. 16,
  129570. };
  129571. static long _vq_lengthlist__44c2_s_p9_2[] = {
  129572. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  129573. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  129574. 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  129575. 9, 9, 9,10, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  129576. 9, 9, 9, 9,10,10,10, 8, 7, 8, 8, 8, 8, 9, 9, 9,
  129577. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  129578. 9, 9,10, 9, 9, 9,10,11,10, 8, 8, 8, 8, 9, 9, 9,
  129579. 9, 9, 9, 9,10,10,10,10,11,10, 8, 8, 9, 9, 9, 9,
  129580. 9, 9,10, 9, 9,10, 9,10,11,10,11,11,11, 8, 8, 9,
  129581. 9, 9, 9, 9, 9, 9, 9,10,10,11,11,11,11,11, 9, 9,
  129582. 9, 9, 9, 9,10, 9, 9, 9,10,10,11,11,11,11,11, 9,
  129583. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,11,11,11,11,11,
  129584. 9, 9, 9, 9,10,10, 9, 9, 9,10,10,10,11,11,11,11,
  129585. 11,11,11, 9, 9, 9,10, 9, 9,10,10,10,10,11,11,10,
  129586. 11,11,11,11,10, 9,10,10, 9, 9, 9, 9,10,10,11,10,
  129587. 11,11,11,11,11, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  129588. 10,11,11,11,11,11,10,10, 9, 9,10, 9,10,10,10,10,
  129589. 10,10,10,11,11,11,11,11,11, 9, 9,10, 9,10, 9,10,
  129590. 10,
  129591. };
  129592. static float _vq_quantthresh__44c2_s_p9_2[] = {
  129593. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  129594. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  129595. };
  129596. static long _vq_quantmap__44c2_s_p9_2[] = {
  129597. 15, 13, 11, 9, 7, 5, 3, 1,
  129598. 0, 2, 4, 6, 8, 10, 12, 14,
  129599. 16,
  129600. };
  129601. static encode_aux_threshmatch _vq_auxt__44c2_s_p9_2 = {
  129602. _vq_quantthresh__44c2_s_p9_2,
  129603. _vq_quantmap__44c2_s_p9_2,
  129604. 17,
  129605. 17
  129606. };
  129607. static static_codebook _44c2_s_p9_2 = {
  129608. 2, 289,
  129609. _vq_lengthlist__44c2_s_p9_2,
  129610. 1, -529530880, 1611661312, 5, 0,
  129611. _vq_quantlist__44c2_s_p9_2,
  129612. NULL,
  129613. &_vq_auxt__44c2_s_p9_2,
  129614. NULL,
  129615. 0
  129616. };
  129617. static long _huff_lengthlist__44c2_s_short[] = {
  129618. 11, 9,13,12,12,11,12,12,13,15, 8, 2,11, 4, 8, 5,
  129619. 7,10,12,15,13, 7,10, 9, 8, 8,10,13,17,17,11, 4,
  129620. 12, 5, 9, 5, 8,11,14,16,12, 6, 8, 7, 6, 6, 8,11,
  129621. 13,16,11, 4, 9, 5, 6, 4, 6,10,13,16,11, 6,11, 7,
  129622. 7, 6, 7,10,13,15,13, 9,12, 9, 8, 6, 8,10,12,14,
  129623. 14,10,10, 8, 6, 5, 6, 9,11,13,15,11,11, 9, 6, 5,
  129624. 6, 8, 9,12,
  129625. };
  129626. static static_codebook _huff_book__44c2_s_short = {
  129627. 2, 100,
  129628. _huff_lengthlist__44c2_s_short,
  129629. 0, 0, 0, 0, 0,
  129630. NULL,
  129631. NULL,
  129632. NULL,
  129633. NULL,
  129634. 0
  129635. };
  129636. static long _huff_lengthlist__44c3_s_long[] = {
  129637. 5, 6,11,11,11,11,10,10,12,11, 5, 2,11, 5, 6, 6,
  129638. 7, 9,11,13,13,10, 7,11, 6, 7, 8, 9,10,12,11, 5,
  129639. 11, 6, 8, 7, 9,11,14,15,11, 6, 6, 8, 4, 5, 7, 8,
  129640. 10,13,10, 5, 7, 7, 5, 5, 6, 8,10,11,10, 7, 7, 8,
  129641. 6, 5, 5, 7, 9, 9,11, 8, 8,11, 8, 7, 6, 6, 7, 9,
  129642. 12,11,10,13, 9, 9, 7, 7, 7, 9,11,13,12,15,12,11,
  129643. 9, 8, 8, 8,
  129644. };
  129645. static static_codebook _huff_book__44c3_s_long = {
  129646. 2, 100,
  129647. _huff_lengthlist__44c3_s_long,
  129648. 0, 0, 0, 0, 0,
  129649. NULL,
  129650. NULL,
  129651. NULL,
  129652. NULL,
  129653. 0
  129654. };
  129655. static long _vq_quantlist__44c3_s_p1_0[] = {
  129656. 1,
  129657. 0,
  129658. 2,
  129659. };
  129660. static long _vq_lengthlist__44c3_s_p1_0[] = {
  129661. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  129662. 0, 0, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129666. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129667. 0, 0, 0, 6, 7, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129671. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  129672. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  129707. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  129712. 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  129717. 0, 0, 0, 0, 7, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129752. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  129753. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129757. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  129758. 0, 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  129759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129762. 0, 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  129763. 0, 0, 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 0,
  129764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129948. 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129953. 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  129987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  129999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130071. 0,
  130072. };
  130073. static float _vq_quantthresh__44c3_s_p1_0[] = {
  130074. -0.5, 0.5,
  130075. };
  130076. static long _vq_quantmap__44c3_s_p1_0[] = {
  130077. 1, 0, 2,
  130078. };
  130079. static encode_aux_threshmatch _vq_auxt__44c3_s_p1_0 = {
  130080. _vq_quantthresh__44c3_s_p1_0,
  130081. _vq_quantmap__44c3_s_p1_0,
  130082. 3,
  130083. 3
  130084. };
  130085. static static_codebook _44c3_s_p1_0 = {
  130086. 8, 6561,
  130087. _vq_lengthlist__44c3_s_p1_0,
  130088. 1, -535822336, 1611661312, 2, 0,
  130089. _vq_quantlist__44c3_s_p1_0,
  130090. NULL,
  130091. &_vq_auxt__44c3_s_p1_0,
  130092. NULL,
  130093. 0
  130094. };
  130095. static long _vq_quantlist__44c3_s_p2_0[] = {
  130096. 2,
  130097. 1,
  130098. 3,
  130099. 0,
  130100. 4,
  130101. };
  130102. static long _vq_lengthlist__44c3_s_p2_0[] = {
  130103. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  130104. 7, 8, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  130105. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  130106. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  130107. 0, 0,10,10, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0,
  130113. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  130114. 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  130115. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  130121. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  130122. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 8,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  130129. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  130130. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  130143. };
  130144. static float _vq_quantthresh__44c3_s_p2_0[] = {
  130145. -1.5, -0.5, 0.5, 1.5,
  130146. };
  130147. static long _vq_quantmap__44c3_s_p2_0[] = {
  130148. 3, 1, 0, 2, 4,
  130149. };
  130150. static encode_aux_threshmatch _vq_auxt__44c3_s_p2_0 = {
  130151. _vq_quantthresh__44c3_s_p2_0,
  130152. _vq_quantmap__44c3_s_p2_0,
  130153. 5,
  130154. 5
  130155. };
  130156. static static_codebook _44c3_s_p2_0 = {
  130157. 4, 625,
  130158. _vq_lengthlist__44c3_s_p2_0,
  130159. 1, -533725184, 1611661312, 3, 0,
  130160. _vq_quantlist__44c3_s_p2_0,
  130161. NULL,
  130162. &_vq_auxt__44c3_s_p2_0,
  130163. NULL,
  130164. 0
  130165. };
  130166. static long _vq_quantlist__44c3_s_p3_0[] = {
  130167. 2,
  130168. 1,
  130169. 3,
  130170. 0,
  130171. 4,
  130172. };
  130173. static long _vq_lengthlist__44c3_s_p3_0[] = {
  130174. 2, 4, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  130176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130177. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  130179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130180. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  130214. };
  130215. static float _vq_quantthresh__44c3_s_p3_0[] = {
  130216. -1.5, -0.5, 0.5, 1.5,
  130217. };
  130218. static long _vq_quantmap__44c3_s_p3_0[] = {
  130219. 3, 1, 0, 2, 4,
  130220. };
  130221. static encode_aux_threshmatch _vq_auxt__44c3_s_p3_0 = {
  130222. _vq_quantthresh__44c3_s_p3_0,
  130223. _vq_quantmap__44c3_s_p3_0,
  130224. 5,
  130225. 5
  130226. };
  130227. static static_codebook _44c3_s_p3_0 = {
  130228. 4, 625,
  130229. _vq_lengthlist__44c3_s_p3_0,
  130230. 1, -533725184, 1611661312, 3, 0,
  130231. _vq_quantlist__44c3_s_p3_0,
  130232. NULL,
  130233. &_vq_auxt__44c3_s_p3_0,
  130234. NULL,
  130235. 0
  130236. };
  130237. static long _vq_quantlist__44c3_s_p4_0[] = {
  130238. 4,
  130239. 3,
  130240. 5,
  130241. 2,
  130242. 6,
  130243. 1,
  130244. 7,
  130245. 0,
  130246. 8,
  130247. };
  130248. static long _vq_lengthlist__44c3_s_p4_0[] = {
  130249. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  130250. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  130251. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  130252. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  130253. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130254. 0,
  130255. };
  130256. static float _vq_quantthresh__44c3_s_p4_0[] = {
  130257. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130258. };
  130259. static long _vq_quantmap__44c3_s_p4_0[] = {
  130260. 7, 5, 3, 1, 0, 2, 4, 6,
  130261. 8,
  130262. };
  130263. static encode_aux_threshmatch _vq_auxt__44c3_s_p4_0 = {
  130264. _vq_quantthresh__44c3_s_p4_0,
  130265. _vq_quantmap__44c3_s_p4_0,
  130266. 9,
  130267. 9
  130268. };
  130269. static static_codebook _44c3_s_p4_0 = {
  130270. 2, 81,
  130271. _vq_lengthlist__44c3_s_p4_0,
  130272. 1, -531628032, 1611661312, 4, 0,
  130273. _vq_quantlist__44c3_s_p4_0,
  130274. NULL,
  130275. &_vq_auxt__44c3_s_p4_0,
  130276. NULL,
  130277. 0
  130278. };
  130279. static long _vq_quantlist__44c3_s_p5_0[] = {
  130280. 4,
  130281. 3,
  130282. 5,
  130283. 2,
  130284. 6,
  130285. 1,
  130286. 7,
  130287. 0,
  130288. 8,
  130289. };
  130290. static long _vq_lengthlist__44c3_s_p5_0[] = {
  130291. 1, 3, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 7, 8,
  130292. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  130293. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  130294. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  130295. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  130296. 11,
  130297. };
  130298. static float _vq_quantthresh__44c3_s_p5_0[] = {
  130299. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  130300. };
  130301. static long _vq_quantmap__44c3_s_p5_0[] = {
  130302. 7, 5, 3, 1, 0, 2, 4, 6,
  130303. 8,
  130304. };
  130305. static encode_aux_threshmatch _vq_auxt__44c3_s_p5_0 = {
  130306. _vq_quantthresh__44c3_s_p5_0,
  130307. _vq_quantmap__44c3_s_p5_0,
  130308. 9,
  130309. 9
  130310. };
  130311. static static_codebook _44c3_s_p5_0 = {
  130312. 2, 81,
  130313. _vq_lengthlist__44c3_s_p5_0,
  130314. 1, -531628032, 1611661312, 4, 0,
  130315. _vq_quantlist__44c3_s_p5_0,
  130316. NULL,
  130317. &_vq_auxt__44c3_s_p5_0,
  130318. NULL,
  130319. 0
  130320. };
  130321. static long _vq_quantlist__44c3_s_p6_0[] = {
  130322. 8,
  130323. 7,
  130324. 9,
  130325. 6,
  130326. 10,
  130327. 5,
  130328. 11,
  130329. 4,
  130330. 12,
  130331. 3,
  130332. 13,
  130333. 2,
  130334. 14,
  130335. 1,
  130336. 15,
  130337. 0,
  130338. 16,
  130339. };
  130340. static long _vq_lengthlist__44c3_s_p6_0[] = {
  130341. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  130342. 10, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  130343. 11,11, 0, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  130344. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  130345. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  130346. 10,11,11,11,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130347. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  130348. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  130349. 10,10,11,10,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  130350. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 8,
  130351. 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8,
  130352. 8, 9, 9,10,10,11,11,12,11,12,12, 0, 0, 0, 0, 0,
  130353. 9,10,10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0,
  130354. 0, 0, 0,10,10,10,10,11,11,12,12,13,13, 0, 0, 0,
  130355. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  130356. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  130357. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13,
  130358. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  130359. 13,
  130360. };
  130361. static float _vq_quantthresh__44c3_s_p6_0[] = {
  130362. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130363. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130364. };
  130365. static long _vq_quantmap__44c3_s_p6_0[] = {
  130366. 15, 13, 11, 9, 7, 5, 3, 1,
  130367. 0, 2, 4, 6, 8, 10, 12, 14,
  130368. 16,
  130369. };
  130370. static encode_aux_threshmatch _vq_auxt__44c3_s_p6_0 = {
  130371. _vq_quantthresh__44c3_s_p6_0,
  130372. _vq_quantmap__44c3_s_p6_0,
  130373. 17,
  130374. 17
  130375. };
  130376. static static_codebook _44c3_s_p6_0 = {
  130377. 2, 289,
  130378. _vq_lengthlist__44c3_s_p6_0,
  130379. 1, -529530880, 1611661312, 5, 0,
  130380. _vq_quantlist__44c3_s_p6_0,
  130381. NULL,
  130382. &_vq_auxt__44c3_s_p6_0,
  130383. NULL,
  130384. 0
  130385. };
  130386. static long _vq_quantlist__44c3_s_p7_0[] = {
  130387. 1,
  130388. 0,
  130389. 2,
  130390. };
  130391. static long _vq_lengthlist__44c3_s_p7_0[] = {
  130392. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  130393. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  130394. 10,12,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  130395. 11,10,10,11,10,10, 7,11,11,11,11,11,12,11,11, 6,
  130396. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  130397. 10,
  130398. };
  130399. static float _vq_quantthresh__44c3_s_p7_0[] = {
  130400. -5.5, 5.5,
  130401. };
  130402. static long _vq_quantmap__44c3_s_p7_0[] = {
  130403. 1, 0, 2,
  130404. };
  130405. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_0 = {
  130406. _vq_quantthresh__44c3_s_p7_0,
  130407. _vq_quantmap__44c3_s_p7_0,
  130408. 3,
  130409. 3
  130410. };
  130411. static static_codebook _44c3_s_p7_0 = {
  130412. 4, 81,
  130413. _vq_lengthlist__44c3_s_p7_0,
  130414. 1, -529137664, 1618345984, 2, 0,
  130415. _vq_quantlist__44c3_s_p7_0,
  130416. NULL,
  130417. &_vq_auxt__44c3_s_p7_0,
  130418. NULL,
  130419. 0
  130420. };
  130421. static long _vq_quantlist__44c3_s_p7_1[] = {
  130422. 5,
  130423. 4,
  130424. 6,
  130425. 3,
  130426. 7,
  130427. 2,
  130428. 8,
  130429. 1,
  130430. 9,
  130431. 0,
  130432. 10,
  130433. };
  130434. static long _vq_lengthlist__44c3_s_p7_1[] = {
  130435. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  130436. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  130437. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  130438. 7, 8, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  130439. 8, 8,10,10,10, 7, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  130440. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  130441. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  130442. 10,10,10, 8, 8, 8, 8, 8, 8,
  130443. };
  130444. static float _vq_quantthresh__44c3_s_p7_1[] = {
  130445. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  130446. 3.5, 4.5,
  130447. };
  130448. static long _vq_quantmap__44c3_s_p7_1[] = {
  130449. 9, 7, 5, 3, 1, 0, 2, 4,
  130450. 6, 8, 10,
  130451. };
  130452. static encode_aux_threshmatch _vq_auxt__44c3_s_p7_1 = {
  130453. _vq_quantthresh__44c3_s_p7_1,
  130454. _vq_quantmap__44c3_s_p7_1,
  130455. 11,
  130456. 11
  130457. };
  130458. static static_codebook _44c3_s_p7_1 = {
  130459. 2, 121,
  130460. _vq_lengthlist__44c3_s_p7_1,
  130461. 1, -531365888, 1611661312, 4, 0,
  130462. _vq_quantlist__44c3_s_p7_1,
  130463. NULL,
  130464. &_vq_auxt__44c3_s_p7_1,
  130465. NULL,
  130466. 0
  130467. };
  130468. static long _vq_quantlist__44c3_s_p8_0[] = {
  130469. 6,
  130470. 5,
  130471. 7,
  130472. 4,
  130473. 8,
  130474. 3,
  130475. 9,
  130476. 2,
  130477. 10,
  130478. 1,
  130479. 11,
  130480. 0,
  130481. 12,
  130482. };
  130483. static long _vq_lengthlist__44c3_s_p8_0[] = {
  130484. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  130485. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  130486. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  130487. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  130488. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,12, 0,13,
  130489. 13, 9, 9,10,10,10,10,11,11,12,12, 0, 0, 0,10,10,
  130490. 10,10,11,11,12,12,12,12, 0, 0, 0,10,10,10,10,11,
  130491. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  130492. 13,13, 0, 0, 0,14,14,11,11,11,11,12,12,13,13, 0,
  130493. 0, 0, 0, 0,12,12,12,12,13,13,14,13, 0, 0, 0, 0,
  130494. 0,13,13,12,12,13,12,14,13,
  130495. };
  130496. static float _vq_quantthresh__44c3_s_p8_0[] = {
  130497. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  130498. 12.5, 17.5, 22.5, 27.5,
  130499. };
  130500. static long _vq_quantmap__44c3_s_p8_0[] = {
  130501. 11, 9, 7, 5, 3, 1, 0, 2,
  130502. 4, 6, 8, 10, 12,
  130503. };
  130504. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_0 = {
  130505. _vq_quantthresh__44c3_s_p8_0,
  130506. _vq_quantmap__44c3_s_p8_0,
  130507. 13,
  130508. 13
  130509. };
  130510. static static_codebook _44c3_s_p8_0 = {
  130511. 2, 169,
  130512. _vq_lengthlist__44c3_s_p8_0,
  130513. 1, -526516224, 1616117760, 4, 0,
  130514. _vq_quantlist__44c3_s_p8_0,
  130515. NULL,
  130516. &_vq_auxt__44c3_s_p8_0,
  130517. NULL,
  130518. 0
  130519. };
  130520. static long _vq_quantlist__44c3_s_p8_1[] = {
  130521. 2,
  130522. 1,
  130523. 3,
  130524. 0,
  130525. 4,
  130526. };
  130527. static long _vq_lengthlist__44c3_s_p8_1[] = {
  130528. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  130529. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  130530. };
  130531. static float _vq_quantthresh__44c3_s_p8_1[] = {
  130532. -1.5, -0.5, 0.5, 1.5,
  130533. };
  130534. static long _vq_quantmap__44c3_s_p8_1[] = {
  130535. 3, 1, 0, 2, 4,
  130536. };
  130537. static encode_aux_threshmatch _vq_auxt__44c3_s_p8_1 = {
  130538. _vq_quantthresh__44c3_s_p8_1,
  130539. _vq_quantmap__44c3_s_p8_1,
  130540. 5,
  130541. 5
  130542. };
  130543. static static_codebook _44c3_s_p8_1 = {
  130544. 2, 25,
  130545. _vq_lengthlist__44c3_s_p8_1,
  130546. 1, -533725184, 1611661312, 3, 0,
  130547. _vq_quantlist__44c3_s_p8_1,
  130548. NULL,
  130549. &_vq_auxt__44c3_s_p8_1,
  130550. NULL,
  130551. 0
  130552. };
  130553. static long _vq_quantlist__44c3_s_p9_0[] = {
  130554. 6,
  130555. 5,
  130556. 7,
  130557. 4,
  130558. 8,
  130559. 3,
  130560. 9,
  130561. 2,
  130562. 10,
  130563. 1,
  130564. 11,
  130565. 0,
  130566. 12,
  130567. };
  130568. static long _vq_lengthlist__44c3_s_p9_0[] = {
  130569. 1, 4, 4,12,12,12,12,12,12,12,12,12,12, 4, 9, 8,
  130570. 12,12,12,12,12,12,12,12,12,12, 2, 9, 7,12,12,12,
  130571. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130572. 12,12,12,12,12,12,11,12,12,12,12,12,12,12,12,12,
  130573. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130574. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130575. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130576. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  130577. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  130578. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  130579. 11,11,11,11,11,11,11,11,11,
  130580. };
  130581. static float _vq_quantthresh__44c3_s_p9_0[] = {
  130582. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  130583. 637.5, 892.5, 1147.5, 1402.5,
  130584. };
  130585. static long _vq_quantmap__44c3_s_p9_0[] = {
  130586. 11, 9, 7, 5, 3, 1, 0, 2,
  130587. 4, 6, 8, 10, 12,
  130588. };
  130589. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_0 = {
  130590. _vq_quantthresh__44c3_s_p9_0,
  130591. _vq_quantmap__44c3_s_p9_0,
  130592. 13,
  130593. 13
  130594. };
  130595. static static_codebook _44c3_s_p9_0 = {
  130596. 2, 169,
  130597. _vq_lengthlist__44c3_s_p9_0,
  130598. 1, -514332672, 1627381760, 4, 0,
  130599. _vq_quantlist__44c3_s_p9_0,
  130600. NULL,
  130601. &_vq_auxt__44c3_s_p9_0,
  130602. NULL,
  130603. 0
  130604. };
  130605. static long _vq_quantlist__44c3_s_p9_1[] = {
  130606. 7,
  130607. 6,
  130608. 8,
  130609. 5,
  130610. 9,
  130611. 4,
  130612. 10,
  130613. 3,
  130614. 11,
  130615. 2,
  130616. 12,
  130617. 1,
  130618. 13,
  130619. 0,
  130620. 14,
  130621. };
  130622. static long _vq_lengthlist__44c3_s_p9_1[] = {
  130623. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 9,10,10,10,10, 6,
  130624. 5, 5, 7, 7, 8, 8,10, 8,11,10,12,12,13,13, 6, 5,
  130625. 5, 7, 7, 8, 8,10, 9,11,11,12,12,13,12,18, 8, 8,
  130626. 8, 8, 9, 9,10, 9,11,10,12,12,13,13,18, 8, 8, 8,
  130627. 8, 9, 9,10,10,11,11,13,12,14,13,18,11,11, 9, 9,
  130628. 10,10,11,11,11,12,13,12,13,14,18,11,11, 9, 8,11,
  130629. 10,11,11,11,11,12,12,14,13,18,18,18,10,11,10,11,
  130630. 12,12,12,12,13,12,14,13,18,18,18,10,11,11, 9,12,
  130631. 11,12,12,12,13,13,13,18,18,17,14,14,11,11,12,12,
  130632. 13,12,14,12,14,13,18,18,18,14,14,11,10,12, 9,12,
  130633. 13,13,13,13,13,18,18,17,16,18,13,13,12,12,13,11,
  130634. 14,12,14,14,17,18,18,17,18,13,12,13,10,12,11,14,
  130635. 14,14,14,17,18,18,18,18,15,16,12,12,13,10,14,12,
  130636. 14,15,18,18,18,16,17,16,14,12,11,13,10,13,13,14,
  130637. 15,
  130638. };
  130639. static float _vq_quantthresh__44c3_s_p9_1[] = {
  130640. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  130641. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  130642. };
  130643. static long _vq_quantmap__44c3_s_p9_1[] = {
  130644. 13, 11, 9, 7, 5, 3, 1, 0,
  130645. 2, 4, 6, 8, 10, 12, 14,
  130646. };
  130647. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_1 = {
  130648. _vq_quantthresh__44c3_s_p9_1,
  130649. _vq_quantmap__44c3_s_p9_1,
  130650. 15,
  130651. 15
  130652. };
  130653. static static_codebook _44c3_s_p9_1 = {
  130654. 2, 225,
  130655. _vq_lengthlist__44c3_s_p9_1,
  130656. 1, -522338304, 1620115456, 4, 0,
  130657. _vq_quantlist__44c3_s_p9_1,
  130658. NULL,
  130659. &_vq_auxt__44c3_s_p9_1,
  130660. NULL,
  130661. 0
  130662. };
  130663. static long _vq_quantlist__44c3_s_p9_2[] = {
  130664. 8,
  130665. 7,
  130666. 9,
  130667. 6,
  130668. 10,
  130669. 5,
  130670. 11,
  130671. 4,
  130672. 12,
  130673. 3,
  130674. 13,
  130675. 2,
  130676. 14,
  130677. 1,
  130678. 15,
  130679. 0,
  130680. 16,
  130681. };
  130682. static long _vq_lengthlist__44c3_s_p9_2[] = {
  130683. 2, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8,
  130684. 8,10, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 8, 9, 9, 9,
  130685. 9, 9,10, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  130686. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  130687. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  130688. 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  130689. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  130690. 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 9, 9, 9, 9, 9,
  130691. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 9, 9, 9,
  130692. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  130693. 9, 9, 9, 9,10,10, 9, 9,10, 9,11,10,11,11,11, 9,
  130694. 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,11,11,11,11,11,
  130695. 9, 9, 9, 9,10,10, 9, 9, 9, 9,10, 9,11,11,11,11,
  130696. 11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11,
  130697. 11,11,11,11,10, 9,10,10, 9,10, 9, 9,10, 9,11,10,
  130698. 10,11,11,11,11, 9,10, 9, 9, 9, 9,10,10,10,10,11,
  130699. 11,11,11,11,11,10,10,10, 9, 9,10, 9,10, 9,10,10,
  130700. 10,10,11,11,11,11,11,11,11, 9, 9, 9, 9, 9,10,10,
  130701. 10,
  130702. };
  130703. static float _vq_quantthresh__44c3_s_p9_2[] = {
  130704. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  130705. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  130706. };
  130707. static long _vq_quantmap__44c3_s_p9_2[] = {
  130708. 15, 13, 11, 9, 7, 5, 3, 1,
  130709. 0, 2, 4, 6, 8, 10, 12, 14,
  130710. 16,
  130711. };
  130712. static encode_aux_threshmatch _vq_auxt__44c3_s_p9_2 = {
  130713. _vq_quantthresh__44c3_s_p9_2,
  130714. _vq_quantmap__44c3_s_p9_2,
  130715. 17,
  130716. 17
  130717. };
  130718. static static_codebook _44c3_s_p9_2 = {
  130719. 2, 289,
  130720. _vq_lengthlist__44c3_s_p9_2,
  130721. 1, -529530880, 1611661312, 5, 0,
  130722. _vq_quantlist__44c3_s_p9_2,
  130723. NULL,
  130724. &_vq_auxt__44c3_s_p9_2,
  130725. NULL,
  130726. 0
  130727. };
  130728. static long _huff_lengthlist__44c3_s_short[] = {
  130729. 10, 9,13,11,14,10,12,13,13,14, 7, 2,12, 5,10, 5,
  130730. 7,10,12,14,12, 6, 9, 8, 7, 7, 9,11,13,16,10, 4,
  130731. 12, 5,10, 6, 8,12,14,16,12, 6, 8, 7, 6, 5, 7,11,
  130732. 12,16,10, 4, 8, 5, 6, 4, 6, 9,13,16,10, 6,10, 7,
  130733. 7, 6, 7, 9,13,15,12, 9,11, 9, 8, 6, 7,10,12,14,
  130734. 14,11,10, 9, 6, 5, 6, 9,11,13,15,13,11,10, 6, 5,
  130735. 6, 8, 9,11,
  130736. };
  130737. static static_codebook _huff_book__44c3_s_short = {
  130738. 2, 100,
  130739. _huff_lengthlist__44c3_s_short,
  130740. 0, 0, 0, 0, 0,
  130741. NULL,
  130742. NULL,
  130743. NULL,
  130744. NULL,
  130745. 0
  130746. };
  130747. static long _huff_lengthlist__44c4_s_long[] = {
  130748. 4, 7,11,11,11,11,10,11,12,11, 5, 2,11, 5, 6, 6,
  130749. 7, 9,11,12,11, 9, 6,10, 6, 7, 8, 9,10,11,11, 5,
  130750. 11, 7, 8, 8, 9,11,13,14,11, 6, 5, 8, 4, 5, 7, 8,
  130751. 10,11,10, 6, 7, 7, 5, 5, 6, 8, 9,11,10, 7, 8, 9,
  130752. 6, 6, 6, 7, 8, 9,11, 9, 9,11, 7, 7, 6, 6, 7, 9,
  130753. 12,12,10,13, 9, 8, 7, 7, 7, 8,11,13,11,14,11,10,
  130754. 9, 8, 7, 7,
  130755. };
  130756. static static_codebook _huff_book__44c4_s_long = {
  130757. 2, 100,
  130758. _huff_lengthlist__44c4_s_long,
  130759. 0, 0, 0, 0, 0,
  130760. NULL,
  130761. NULL,
  130762. NULL,
  130763. NULL,
  130764. 0
  130765. };
  130766. static long _vq_quantlist__44c4_s_p1_0[] = {
  130767. 1,
  130768. 0,
  130769. 2,
  130770. };
  130771. static long _vq_lengthlist__44c4_s_p1_0[] = {
  130772. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 0,
  130773. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130777. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130778. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130782. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 6, 8, 7, 0, 0,
  130783. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  130818. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  130823. 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  130828. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130863. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  130864. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130868. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  130869. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  130870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130873. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  130874. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  130875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  130999. 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131004. 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  131038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131182. 0,
  131183. };
  131184. static float _vq_quantthresh__44c4_s_p1_0[] = {
  131185. -0.5, 0.5,
  131186. };
  131187. static long _vq_quantmap__44c4_s_p1_0[] = {
  131188. 1, 0, 2,
  131189. };
  131190. static encode_aux_threshmatch _vq_auxt__44c4_s_p1_0 = {
  131191. _vq_quantthresh__44c4_s_p1_0,
  131192. _vq_quantmap__44c4_s_p1_0,
  131193. 3,
  131194. 3
  131195. };
  131196. static static_codebook _44c4_s_p1_0 = {
  131197. 8, 6561,
  131198. _vq_lengthlist__44c4_s_p1_0,
  131199. 1, -535822336, 1611661312, 2, 0,
  131200. _vq_quantlist__44c4_s_p1_0,
  131201. NULL,
  131202. &_vq_auxt__44c4_s_p1_0,
  131203. NULL,
  131204. 0
  131205. };
  131206. static long _vq_quantlist__44c4_s_p2_0[] = {
  131207. 2,
  131208. 1,
  131209. 3,
  131210. 0,
  131211. 4,
  131212. };
  131213. static long _vq_lengthlist__44c4_s_p2_0[] = {
  131214. 2, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  131215. 7, 7, 0, 0, 0, 0, 0, 0, 0, 5, 6, 6, 0, 0, 0, 7,
  131216. 7, 0, 0, 0, 7, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  131217. 0, 0, 5, 6, 6, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0,
  131218. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 7, 7, 0, 0,
  131224. 0, 7, 7, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5,
  131225. 7, 8, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9,
  131226. 9, 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, 5, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 7, 7,
  131232. 0, 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0,
  131233. 0, 0, 7, 7, 0, 0, 0, 7, 7, 0, 0, 0, 9, 9, 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. 7,10,10, 0, 0, 0, 9, 9, 0, 0, 0, 9, 9, 0, 0, 0,
  131240. 10,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0, 9,
  131241. 9, 0, 0, 0, 9, 9, 0, 0, 0,10,10, 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,
  131254. };
  131255. static float _vq_quantthresh__44c4_s_p2_0[] = {
  131256. -1.5, -0.5, 0.5, 1.5,
  131257. };
  131258. static long _vq_quantmap__44c4_s_p2_0[] = {
  131259. 3, 1, 0, 2, 4,
  131260. };
  131261. static encode_aux_threshmatch _vq_auxt__44c4_s_p2_0 = {
  131262. _vq_quantthresh__44c4_s_p2_0,
  131263. _vq_quantmap__44c4_s_p2_0,
  131264. 5,
  131265. 5
  131266. };
  131267. static static_codebook _44c4_s_p2_0 = {
  131268. 4, 625,
  131269. _vq_lengthlist__44c4_s_p2_0,
  131270. 1, -533725184, 1611661312, 3, 0,
  131271. _vq_quantlist__44c4_s_p2_0,
  131272. NULL,
  131273. &_vq_auxt__44c4_s_p2_0,
  131274. NULL,
  131275. 0
  131276. };
  131277. static long _vq_quantlist__44c4_s_p3_0[] = {
  131278. 2,
  131279. 1,
  131280. 3,
  131281. 0,
  131282. 4,
  131283. };
  131284. static long _vq_lengthlist__44c4_s_p3_0[] = {
  131285. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 4, 6, 6, 0, 0,
  131287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131288. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  131290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131291. 0, 0, 0, 0, 6, 6, 7, 9, 9, 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,
  131325. };
  131326. static float _vq_quantthresh__44c4_s_p3_0[] = {
  131327. -1.5, -0.5, 0.5, 1.5,
  131328. };
  131329. static long _vq_quantmap__44c4_s_p3_0[] = {
  131330. 3, 1, 0, 2, 4,
  131331. };
  131332. static encode_aux_threshmatch _vq_auxt__44c4_s_p3_0 = {
  131333. _vq_quantthresh__44c4_s_p3_0,
  131334. _vq_quantmap__44c4_s_p3_0,
  131335. 5,
  131336. 5
  131337. };
  131338. static static_codebook _44c4_s_p3_0 = {
  131339. 4, 625,
  131340. _vq_lengthlist__44c4_s_p3_0,
  131341. 1, -533725184, 1611661312, 3, 0,
  131342. _vq_quantlist__44c4_s_p3_0,
  131343. NULL,
  131344. &_vq_auxt__44c4_s_p3_0,
  131345. NULL,
  131346. 0
  131347. };
  131348. static long _vq_quantlist__44c4_s_p4_0[] = {
  131349. 4,
  131350. 3,
  131351. 5,
  131352. 2,
  131353. 6,
  131354. 1,
  131355. 7,
  131356. 0,
  131357. 8,
  131358. };
  131359. static long _vq_lengthlist__44c4_s_p4_0[] = {
  131360. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  131361. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  131362. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  131363. 7, 8, 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0,
  131364. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131365. 0,
  131366. };
  131367. static float _vq_quantthresh__44c4_s_p4_0[] = {
  131368. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131369. };
  131370. static long _vq_quantmap__44c4_s_p4_0[] = {
  131371. 7, 5, 3, 1, 0, 2, 4, 6,
  131372. 8,
  131373. };
  131374. static encode_aux_threshmatch _vq_auxt__44c4_s_p4_0 = {
  131375. _vq_quantthresh__44c4_s_p4_0,
  131376. _vq_quantmap__44c4_s_p4_0,
  131377. 9,
  131378. 9
  131379. };
  131380. static static_codebook _44c4_s_p4_0 = {
  131381. 2, 81,
  131382. _vq_lengthlist__44c4_s_p4_0,
  131383. 1, -531628032, 1611661312, 4, 0,
  131384. _vq_quantlist__44c4_s_p4_0,
  131385. NULL,
  131386. &_vq_auxt__44c4_s_p4_0,
  131387. NULL,
  131388. 0
  131389. };
  131390. static long _vq_quantlist__44c4_s_p5_0[] = {
  131391. 4,
  131392. 3,
  131393. 5,
  131394. 2,
  131395. 6,
  131396. 1,
  131397. 7,
  131398. 0,
  131399. 8,
  131400. };
  131401. static long _vq_lengthlist__44c4_s_p5_0[] = {
  131402. 2, 3, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  131403. 9, 9, 0, 4, 5, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  131404. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10, 9, 0, 0, 0,
  131405. 9, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  131406. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,10,
  131407. 10,
  131408. };
  131409. static float _vq_quantthresh__44c4_s_p5_0[] = {
  131410. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  131411. };
  131412. static long _vq_quantmap__44c4_s_p5_0[] = {
  131413. 7, 5, 3, 1, 0, 2, 4, 6,
  131414. 8,
  131415. };
  131416. static encode_aux_threshmatch _vq_auxt__44c4_s_p5_0 = {
  131417. _vq_quantthresh__44c4_s_p5_0,
  131418. _vq_quantmap__44c4_s_p5_0,
  131419. 9,
  131420. 9
  131421. };
  131422. static static_codebook _44c4_s_p5_0 = {
  131423. 2, 81,
  131424. _vq_lengthlist__44c4_s_p5_0,
  131425. 1, -531628032, 1611661312, 4, 0,
  131426. _vq_quantlist__44c4_s_p5_0,
  131427. NULL,
  131428. &_vq_auxt__44c4_s_p5_0,
  131429. NULL,
  131430. 0
  131431. };
  131432. static long _vq_quantlist__44c4_s_p6_0[] = {
  131433. 8,
  131434. 7,
  131435. 9,
  131436. 6,
  131437. 10,
  131438. 5,
  131439. 11,
  131440. 4,
  131441. 12,
  131442. 3,
  131443. 13,
  131444. 2,
  131445. 14,
  131446. 1,
  131447. 15,
  131448. 0,
  131449. 16,
  131450. };
  131451. static long _vq_lengthlist__44c4_s_p6_0[] = {
  131452. 2, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  131453. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  131454. 11,11, 0, 4, 4, 7, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  131455. 11,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  131456. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  131457. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131458. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9,
  131459. 9,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  131460. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  131461. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  131462. 9,10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9,
  131463. 9, 9, 9,10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0,
  131464. 10,10,10,10,11,11,11,11,12,12,13,12, 0, 0, 0, 0,
  131465. 0, 0, 0,10,10,11,11,11,11,12,12,12,12, 0, 0, 0,
  131466. 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0, 0,
  131467. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  131468. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,13,13,
  131469. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,
  131470. 13,
  131471. };
  131472. static float _vq_quantthresh__44c4_s_p6_0[] = {
  131473. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  131474. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  131475. };
  131476. static long _vq_quantmap__44c4_s_p6_0[] = {
  131477. 15, 13, 11, 9, 7, 5, 3, 1,
  131478. 0, 2, 4, 6, 8, 10, 12, 14,
  131479. 16,
  131480. };
  131481. static encode_aux_threshmatch _vq_auxt__44c4_s_p6_0 = {
  131482. _vq_quantthresh__44c4_s_p6_0,
  131483. _vq_quantmap__44c4_s_p6_0,
  131484. 17,
  131485. 17
  131486. };
  131487. static static_codebook _44c4_s_p6_0 = {
  131488. 2, 289,
  131489. _vq_lengthlist__44c4_s_p6_0,
  131490. 1, -529530880, 1611661312, 5, 0,
  131491. _vq_quantlist__44c4_s_p6_0,
  131492. NULL,
  131493. &_vq_auxt__44c4_s_p6_0,
  131494. NULL,
  131495. 0
  131496. };
  131497. static long _vq_quantlist__44c4_s_p7_0[] = {
  131498. 1,
  131499. 0,
  131500. 2,
  131501. };
  131502. static long _vq_lengthlist__44c4_s_p7_0[] = {
  131503. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  131504. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  131505. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  131506. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  131507. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  131508. 10,
  131509. };
  131510. static float _vq_quantthresh__44c4_s_p7_0[] = {
  131511. -5.5, 5.5,
  131512. };
  131513. static long _vq_quantmap__44c4_s_p7_0[] = {
  131514. 1, 0, 2,
  131515. };
  131516. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_0 = {
  131517. _vq_quantthresh__44c4_s_p7_0,
  131518. _vq_quantmap__44c4_s_p7_0,
  131519. 3,
  131520. 3
  131521. };
  131522. static static_codebook _44c4_s_p7_0 = {
  131523. 4, 81,
  131524. _vq_lengthlist__44c4_s_p7_0,
  131525. 1, -529137664, 1618345984, 2, 0,
  131526. _vq_quantlist__44c4_s_p7_0,
  131527. NULL,
  131528. &_vq_auxt__44c4_s_p7_0,
  131529. NULL,
  131530. 0
  131531. };
  131532. static long _vq_quantlist__44c4_s_p7_1[] = {
  131533. 5,
  131534. 4,
  131535. 6,
  131536. 3,
  131537. 7,
  131538. 2,
  131539. 8,
  131540. 1,
  131541. 9,
  131542. 0,
  131543. 10,
  131544. };
  131545. static long _vq_lengthlist__44c4_s_p7_1[] = {
  131546. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  131547. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  131548. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  131549. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  131550. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  131551. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  131552. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 9, 8,10,10,
  131553. 10,10,10, 8, 8, 8, 8, 9, 9,
  131554. };
  131555. static float _vq_quantthresh__44c4_s_p7_1[] = {
  131556. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  131557. 3.5, 4.5,
  131558. };
  131559. static long _vq_quantmap__44c4_s_p7_1[] = {
  131560. 9, 7, 5, 3, 1, 0, 2, 4,
  131561. 6, 8, 10,
  131562. };
  131563. static encode_aux_threshmatch _vq_auxt__44c4_s_p7_1 = {
  131564. _vq_quantthresh__44c4_s_p7_1,
  131565. _vq_quantmap__44c4_s_p7_1,
  131566. 11,
  131567. 11
  131568. };
  131569. static static_codebook _44c4_s_p7_1 = {
  131570. 2, 121,
  131571. _vq_lengthlist__44c4_s_p7_1,
  131572. 1, -531365888, 1611661312, 4, 0,
  131573. _vq_quantlist__44c4_s_p7_1,
  131574. NULL,
  131575. &_vq_auxt__44c4_s_p7_1,
  131576. NULL,
  131577. 0
  131578. };
  131579. static long _vq_quantlist__44c4_s_p8_0[] = {
  131580. 6,
  131581. 5,
  131582. 7,
  131583. 4,
  131584. 8,
  131585. 3,
  131586. 9,
  131587. 2,
  131588. 10,
  131589. 1,
  131590. 11,
  131591. 0,
  131592. 12,
  131593. };
  131594. static long _vq_lengthlist__44c4_s_p8_0[] = {
  131595. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  131596. 7, 7, 8, 8, 8, 8, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  131597. 8, 9, 9,10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  131598. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  131599. 11, 0,12,12, 9, 9, 9, 9,10,10,10,10,11,11, 0,13,
  131600. 13, 9, 9,10, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  131601. 10,10,10,10,11,11,12,12, 0, 0, 0,10,10,10,10,10,
  131602. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  131603. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,13, 0,
  131604. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  131605. 0,13,12,12,12,12,12,13,13,
  131606. };
  131607. static float _vq_quantthresh__44c4_s_p8_0[] = {
  131608. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  131609. 12.5, 17.5, 22.5, 27.5,
  131610. };
  131611. static long _vq_quantmap__44c4_s_p8_0[] = {
  131612. 11, 9, 7, 5, 3, 1, 0, 2,
  131613. 4, 6, 8, 10, 12,
  131614. };
  131615. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_0 = {
  131616. _vq_quantthresh__44c4_s_p8_0,
  131617. _vq_quantmap__44c4_s_p8_0,
  131618. 13,
  131619. 13
  131620. };
  131621. static static_codebook _44c4_s_p8_0 = {
  131622. 2, 169,
  131623. _vq_lengthlist__44c4_s_p8_0,
  131624. 1, -526516224, 1616117760, 4, 0,
  131625. _vq_quantlist__44c4_s_p8_0,
  131626. NULL,
  131627. &_vq_auxt__44c4_s_p8_0,
  131628. NULL,
  131629. 0
  131630. };
  131631. static long _vq_quantlist__44c4_s_p8_1[] = {
  131632. 2,
  131633. 1,
  131634. 3,
  131635. 0,
  131636. 4,
  131637. };
  131638. static long _vq_lengthlist__44c4_s_p8_1[] = {
  131639. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 5, 4, 5, 5, 6,
  131640. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  131641. };
  131642. static float _vq_quantthresh__44c4_s_p8_1[] = {
  131643. -1.5, -0.5, 0.5, 1.5,
  131644. };
  131645. static long _vq_quantmap__44c4_s_p8_1[] = {
  131646. 3, 1, 0, 2, 4,
  131647. };
  131648. static encode_aux_threshmatch _vq_auxt__44c4_s_p8_1 = {
  131649. _vq_quantthresh__44c4_s_p8_1,
  131650. _vq_quantmap__44c4_s_p8_1,
  131651. 5,
  131652. 5
  131653. };
  131654. static static_codebook _44c4_s_p8_1 = {
  131655. 2, 25,
  131656. _vq_lengthlist__44c4_s_p8_1,
  131657. 1, -533725184, 1611661312, 3, 0,
  131658. _vq_quantlist__44c4_s_p8_1,
  131659. NULL,
  131660. &_vq_auxt__44c4_s_p8_1,
  131661. NULL,
  131662. 0
  131663. };
  131664. static long _vq_quantlist__44c4_s_p9_0[] = {
  131665. 6,
  131666. 5,
  131667. 7,
  131668. 4,
  131669. 8,
  131670. 3,
  131671. 9,
  131672. 2,
  131673. 10,
  131674. 1,
  131675. 11,
  131676. 0,
  131677. 12,
  131678. };
  131679. static long _vq_lengthlist__44c4_s_p9_0[] = {
  131680. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 4, 7, 7,
  131681. 12,12,12,12,12,12,12,12,12,12, 3, 8, 8,12,12,12,
  131682. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131683. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131684. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131685. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131686. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131687. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131688. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131689. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  131690. 12,12,12,12,12,12,12,12,12,
  131691. };
  131692. static float _vq_quantthresh__44c4_s_p9_0[] = {
  131693. -1732.5, -1417.5, -1102.5, -787.5, -472.5, -157.5, 157.5, 472.5,
  131694. 787.5, 1102.5, 1417.5, 1732.5,
  131695. };
  131696. static long _vq_quantmap__44c4_s_p9_0[] = {
  131697. 11, 9, 7, 5, 3, 1, 0, 2,
  131698. 4, 6, 8, 10, 12,
  131699. };
  131700. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_0 = {
  131701. _vq_quantthresh__44c4_s_p9_0,
  131702. _vq_quantmap__44c4_s_p9_0,
  131703. 13,
  131704. 13
  131705. };
  131706. static static_codebook _44c4_s_p9_0 = {
  131707. 2, 169,
  131708. _vq_lengthlist__44c4_s_p9_0,
  131709. 1, -513964032, 1628680192, 4, 0,
  131710. _vq_quantlist__44c4_s_p9_0,
  131711. NULL,
  131712. &_vq_auxt__44c4_s_p9_0,
  131713. NULL,
  131714. 0
  131715. };
  131716. static long _vq_quantlist__44c4_s_p9_1[] = {
  131717. 7,
  131718. 6,
  131719. 8,
  131720. 5,
  131721. 9,
  131722. 4,
  131723. 10,
  131724. 3,
  131725. 11,
  131726. 2,
  131727. 12,
  131728. 1,
  131729. 13,
  131730. 0,
  131731. 14,
  131732. };
  131733. static long _vq_lengthlist__44c4_s_p9_1[] = {
  131734. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,10,10, 6,
  131735. 5, 5, 7, 7, 9, 8,10, 9,11,10,12,12,13,13, 6, 5,
  131736. 5, 7, 7, 9, 9,10,10,11,11,12,12,12,13,19, 8, 8,
  131737. 8, 8, 9, 9,10,10,12,11,12,12,13,13,19, 8, 8, 8,
  131738. 8, 9, 9,11,11,12,12,13,13,13,13,19,12,12, 9, 9,
  131739. 11,11,11,11,12,11,13,12,13,13,18,12,12, 9, 9,11,
  131740. 10,11,11,12,12,12,13,13,14,19,18,18,11,11,11,11,
  131741. 12,12,13,12,13,13,14,14,16,18,18,11,11,11,10,12,
  131742. 11,13,13,13,13,13,14,17,18,18,14,15,11,12,12,13,
  131743. 13,13,13,14,14,14,18,18,18,15,15,12,10,13,10,13,
  131744. 13,13,13,13,14,18,17,18,17,18,12,13,12,13,13,13,
  131745. 14,14,16,14,18,17,18,18,17,13,12,13,10,12,12,14,
  131746. 14,14,14,17,18,18,18,18,14,15,12,12,13,12,14,14,
  131747. 15,15,18,18,18,17,18,15,14,12,11,12,12,14,14,14,
  131748. 15,
  131749. };
  131750. static float _vq_quantthresh__44c4_s_p9_1[] = {
  131751. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  131752. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  131753. };
  131754. static long _vq_quantmap__44c4_s_p9_1[] = {
  131755. 13, 11, 9, 7, 5, 3, 1, 0,
  131756. 2, 4, 6, 8, 10, 12, 14,
  131757. };
  131758. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_1 = {
  131759. _vq_quantthresh__44c4_s_p9_1,
  131760. _vq_quantmap__44c4_s_p9_1,
  131761. 15,
  131762. 15
  131763. };
  131764. static static_codebook _44c4_s_p9_1 = {
  131765. 2, 225,
  131766. _vq_lengthlist__44c4_s_p9_1,
  131767. 1, -520986624, 1620377600, 4, 0,
  131768. _vq_quantlist__44c4_s_p9_1,
  131769. NULL,
  131770. &_vq_auxt__44c4_s_p9_1,
  131771. NULL,
  131772. 0
  131773. };
  131774. static long _vq_quantlist__44c4_s_p9_2[] = {
  131775. 10,
  131776. 9,
  131777. 11,
  131778. 8,
  131779. 12,
  131780. 7,
  131781. 13,
  131782. 6,
  131783. 14,
  131784. 5,
  131785. 15,
  131786. 4,
  131787. 16,
  131788. 3,
  131789. 17,
  131790. 2,
  131791. 18,
  131792. 1,
  131793. 19,
  131794. 0,
  131795. 20,
  131796. };
  131797. static long _vq_lengthlist__44c4_s_p9_2[] = {
  131798. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  131799. 8, 9, 9, 9, 9,11, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  131800. 9, 9, 9, 9, 9, 9,10,10,10,10,11, 6, 6, 7, 7, 8,
  131801. 8, 8, 8, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,
  131802. 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  131803. 10,10,10,10,12,11,11, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  131804. 9,10,10,10,10,10,10,10,10,12,11,12, 8, 8, 8, 8,
  131805. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,11,
  131806. 11, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,
  131807. 10,10,10,11,11,12, 9, 9, 9, 9, 9, 9,10, 9,10,10,
  131808. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  131809. 9,10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,
  131810. 11,11, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  131811. 10,10,11,11,11,11,11, 9, 9, 9, 9,10,10,10,10,10,
  131812. 10,10,10,10,10,10,10,11,11,11,12,12,10,10,10,10,
  131813. 10,10,10,10,10,10,10,10,10,10,10,10,11,12,11,12,
  131814. 11,11,11, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  131815. 10,11,12,11,11,11,11,11,10,10,10,10,10,10,10,10,
  131816. 10,10,10,10,10,10,11,11,11,12,11,11,11,10,10,10,
  131817. 10,10,10,10,10,10,10,10,10,10,10,12,11,11,12,11,
  131818. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  131819. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  131820. 10,10,10,10,10,11,11,11,11,12,12,11,11,11,11,11,
  131821. 11,11,10,10,10,10,10,10,10,10,12,12,12,11,11,11,
  131822. 12,11,11,11,10,10,10,10,10,10,10,10,10,10,10,12,
  131823. 11,12,12,12,12,12,11,12,11,11,10,10,10,10,10,10,
  131824. 10,10,10,10,12,12,12,12,11,11,11,11,11,11,11,10,
  131825. 10,10,10,10,10,10,10,10,10,
  131826. };
  131827. static float _vq_quantthresh__44c4_s_p9_2[] = {
  131828. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  131829. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  131830. 6.5, 7.5, 8.5, 9.5,
  131831. };
  131832. static long _vq_quantmap__44c4_s_p9_2[] = {
  131833. 19, 17, 15, 13, 11, 9, 7, 5,
  131834. 3, 1, 0, 2, 4, 6, 8, 10,
  131835. 12, 14, 16, 18, 20,
  131836. };
  131837. static encode_aux_threshmatch _vq_auxt__44c4_s_p9_2 = {
  131838. _vq_quantthresh__44c4_s_p9_2,
  131839. _vq_quantmap__44c4_s_p9_2,
  131840. 21,
  131841. 21
  131842. };
  131843. static static_codebook _44c4_s_p9_2 = {
  131844. 2, 441,
  131845. _vq_lengthlist__44c4_s_p9_2,
  131846. 1, -529268736, 1611661312, 5, 0,
  131847. _vq_quantlist__44c4_s_p9_2,
  131848. NULL,
  131849. &_vq_auxt__44c4_s_p9_2,
  131850. NULL,
  131851. 0
  131852. };
  131853. static long _huff_lengthlist__44c4_s_short[] = {
  131854. 4, 7,14,10,15,10,12,15,16,15, 4, 2,11, 5,10, 6,
  131855. 8,11,14,14,14,10, 7,11, 6, 8,10,11,13,15, 9, 4,
  131856. 11, 5, 9, 6, 9,12,14,15,14, 9, 6, 9, 4, 5, 7,10,
  131857. 12,13, 9, 5, 7, 6, 5, 5, 7,10,13,13,10, 8, 9, 8,
  131858. 7, 6, 8,10,14,14,13,11,10,10, 7, 7, 8,11,14,15,
  131859. 13,12, 9, 9, 6, 5, 7,10,14,17,15,13,11,10, 6, 6,
  131860. 7, 9,12,17,
  131861. };
  131862. static static_codebook _huff_book__44c4_s_short = {
  131863. 2, 100,
  131864. _huff_lengthlist__44c4_s_short,
  131865. 0, 0, 0, 0, 0,
  131866. NULL,
  131867. NULL,
  131868. NULL,
  131869. NULL,
  131870. 0
  131871. };
  131872. static long _huff_lengthlist__44c5_s_long[] = {
  131873. 3, 8, 9,13,10,12,12,12,12,12, 6, 4, 6, 8, 6, 8,
  131874. 10,10,11,12, 8, 5, 4,10, 4, 7, 8, 9,10,11,13, 8,
  131875. 10, 8, 9, 9,11,12,13,14,10, 6, 4, 9, 3, 5, 6, 8,
  131876. 10,11,11, 8, 6, 9, 5, 5, 6, 7, 9,11,12, 9, 7,11,
  131877. 6, 6, 6, 7, 8,10,12,11, 9,12, 7, 7, 6, 6, 7, 9,
  131878. 13,12,10,13, 9, 8, 7, 7, 7, 8,11,15,11,15,11,10,
  131879. 9, 8, 7, 7,
  131880. };
  131881. static static_codebook _huff_book__44c5_s_long = {
  131882. 2, 100,
  131883. _huff_lengthlist__44c5_s_long,
  131884. 0, 0, 0, 0, 0,
  131885. NULL,
  131886. NULL,
  131887. NULL,
  131888. NULL,
  131889. 0
  131890. };
  131891. static long _vq_quantlist__44c5_s_p1_0[] = {
  131892. 1,
  131893. 0,
  131894. 2,
  131895. };
  131896. static long _vq_lengthlist__44c5_s_p1_0[] = {
  131897. 2, 4, 4, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131898. 0, 0, 4, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131902. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131903. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131907. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  131908. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  131943. 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  131948. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  131949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131953. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  131954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131988. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  131989. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131993. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  131994. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  131995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  131998. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  131999. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  132000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132021. 0, 0, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132026. 0, 0, 0, 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, 0, 0, 0, 0, 0, 0, 0,
  132060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132117. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132118. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132119. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132120. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132121. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132122. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132123. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132124. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132125. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132126. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132127. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132128. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132129. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132132. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132135. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132168. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132169. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132170. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132171. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132172. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132173. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132174. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132175. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132176. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132177. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132178. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132179. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132180. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132181. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132182. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132183. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132184. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132185. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132186. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132187. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132188. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132189. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132190. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132191. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132192. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132193. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132194. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132195. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132196. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132197. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132198. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132199. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132200. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132201. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132202. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132203. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132204. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132205. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132206. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132207. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132208. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132209. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132210. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132211. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132212. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132213. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132214. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132215. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132216. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132217. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132218. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132219. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132220. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132221. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132222. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132223. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132224. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132225. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132226. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132227. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132228. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132229. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132230. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132231. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132232. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132233. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132234. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132235. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132236. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132237. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132238. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132239. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132240. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132241. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132242. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132243. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132244. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132245. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132246. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132247. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132248. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132249. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132250. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132251. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132252. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132253. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132254. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132255. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132256. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132257. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132258. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132259. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132260. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132261. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132262. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132263. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132264. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132265. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132266. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132267. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132268. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132269. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132270. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132271. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132272. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132273. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132274. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132275. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132276. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132277. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132278. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132279. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132280. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132281. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132282. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132283. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132284. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132285. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132286. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132287. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132288. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132289. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132290. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132291. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132292. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132293. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132294. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132295. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132296. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132297. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132298. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132299. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132300. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132301. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132302. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132303. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132304. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132305. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132306. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132307. 0,
  132308. };
  132309. static float _vq_quantthresh__44c5_s_p1_0[] = {
  132310. -0.5, 0.5,
  132311. };
  132312. static long _vq_quantmap__44c5_s_p1_0[] = {
  132313. 1, 0, 2,
  132314. };
  132315. static encode_aux_threshmatch _vq_auxt__44c5_s_p1_0 = {
  132316. _vq_quantthresh__44c5_s_p1_0,
  132317. _vq_quantmap__44c5_s_p1_0,
  132318. 3,
  132319. 3
  132320. };
  132321. static static_codebook _44c5_s_p1_0 = {
  132322. 8, 6561,
  132323. _vq_lengthlist__44c5_s_p1_0,
  132324. 1, -535822336, 1611661312, 2, 0,
  132325. _vq_quantlist__44c5_s_p1_0,
  132326. NULL,
  132327. &_vq_auxt__44c5_s_p1_0,
  132328. NULL,
  132329. 0
  132330. };
  132331. static long _vq_quantlist__44c5_s_p2_0[] = {
  132332. 2,
  132333. 1,
  132334. 3,
  132335. 0,
  132336. 4,
  132337. };
  132338. static long _vq_lengthlist__44c5_s_p2_0[] = {
  132339. 2, 4, 4, 0, 0, 0, 5, 5, 0, 0, 0, 5, 5, 0, 0, 0,
  132340. 8, 7, 0, 0, 0, 0, 0, 0, 0, 4, 6, 6, 0, 0, 0, 8,
  132341. 8, 0, 0, 0, 8, 7, 0, 0, 0,10,10, 0, 0, 0, 0, 0,
  132342. 0, 0, 4, 6, 6, 0, 0, 0, 8, 8, 0, 0, 0, 7, 8, 0,
  132343. 0, 0,10,10, 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, 5, 8, 7, 0, 0, 0, 8, 8, 0, 0,
  132349. 0, 8, 8, 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5,
  132350. 7, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,
  132351. 10, 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, 5, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0, 8, 8,
  132357. 0, 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0,
  132358. 0, 0, 8, 8, 0, 0, 0, 8, 8, 0, 0, 0,10,10, 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. 8,10,10, 0, 0, 0,10,10, 0, 0, 0, 9,10, 0, 0, 0,
  132365. 11,10, 0, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0, 0,10,
  132366. 10, 0, 0, 0,10,10, 0, 0, 0,10,11, 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,
  132379. };
  132380. static float _vq_quantthresh__44c5_s_p2_0[] = {
  132381. -1.5, -0.5, 0.5, 1.5,
  132382. };
  132383. static long _vq_quantmap__44c5_s_p2_0[] = {
  132384. 3, 1, 0, 2, 4,
  132385. };
  132386. static encode_aux_threshmatch _vq_auxt__44c5_s_p2_0 = {
  132387. _vq_quantthresh__44c5_s_p2_0,
  132388. _vq_quantmap__44c5_s_p2_0,
  132389. 5,
  132390. 5
  132391. };
  132392. static static_codebook _44c5_s_p2_0 = {
  132393. 4, 625,
  132394. _vq_lengthlist__44c5_s_p2_0,
  132395. 1, -533725184, 1611661312, 3, 0,
  132396. _vq_quantlist__44c5_s_p2_0,
  132397. NULL,
  132398. &_vq_auxt__44c5_s_p2_0,
  132399. NULL,
  132400. 0
  132401. };
  132402. static long _vq_quantlist__44c5_s_p3_0[] = {
  132403. 2,
  132404. 1,
  132405. 3,
  132406. 0,
  132407. 4,
  132408. };
  132409. static long _vq_lengthlist__44c5_s_p3_0[] = {
  132410. 2, 4, 3, 5, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132411. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 6, 6, 0, 0,
  132412. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132413. 0, 0, 3, 5, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132414. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  132415. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132416. 0, 0, 0, 0, 5, 6, 6, 8, 8, 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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132425. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132426. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132427. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132428. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132429. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132430. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132431. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132432. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132433. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132434. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132435. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132436. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132437. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132438. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132439. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132440. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132441. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132442. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132443. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132444. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132445. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132446. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132447. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132448. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132449. 0,
  132450. };
  132451. static float _vq_quantthresh__44c5_s_p3_0[] = {
  132452. -1.5, -0.5, 0.5, 1.5,
  132453. };
  132454. static long _vq_quantmap__44c5_s_p3_0[] = {
  132455. 3, 1, 0, 2, 4,
  132456. };
  132457. static encode_aux_threshmatch _vq_auxt__44c5_s_p3_0 = {
  132458. _vq_quantthresh__44c5_s_p3_0,
  132459. _vq_quantmap__44c5_s_p3_0,
  132460. 5,
  132461. 5
  132462. };
  132463. static static_codebook _44c5_s_p3_0 = {
  132464. 4, 625,
  132465. _vq_lengthlist__44c5_s_p3_0,
  132466. 1, -533725184, 1611661312, 3, 0,
  132467. _vq_quantlist__44c5_s_p3_0,
  132468. NULL,
  132469. &_vq_auxt__44c5_s_p3_0,
  132470. NULL,
  132471. 0
  132472. };
  132473. static long _vq_quantlist__44c5_s_p4_0[] = {
  132474. 4,
  132475. 3,
  132476. 5,
  132477. 2,
  132478. 6,
  132479. 1,
  132480. 7,
  132481. 0,
  132482. 8,
  132483. };
  132484. static long _vq_lengthlist__44c5_s_p4_0[] = {
  132485. 2, 3, 3, 6, 6, 0, 0, 0, 0, 0, 4, 4, 6, 6, 0, 0,
  132486. 0, 0, 0, 4, 4, 6, 6, 0, 0, 0, 0, 0, 5, 5, 6, 6,
  132487. 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0,
  132488. 7, 7, 0, 0, 0, 0, 0, 0, 0, 8, 7, 0, 0, 0, 0, 0,
  132489. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  132490. 0,
  132491. };
  132492. static float _vq_quantthresh__44c5_s_p4_0[] = {
  132493. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132494. };
  132495. static long _vq_quantmap__44c5_s_p4_0[] = {
  132496. 7, 5, 3, 1, 0, 2, 4, 6,
  132497. 8,
  132498. };
  132499. static encode_aux_threshmatch _vq_auxt__44c5_s_p4_0 = {
  132500. _vq_quantthresh__44c5_s_p4_0,
  132501. _vq_quantmap__44c5_s_p4_0,
  132502. 9,
  132503. 9
  132504. };
  132505. static static_codebook _44c5_s_p4_0 = {
  132506. 2, 81,
  132507. _vq_lengthlist__44c5_s_p4_0,
  132508. 1, -531628032, 1611661312, 4, 0,
  132509. _vq_quantlist__44c5_s_p4_0,
  132510. NULL,
  132511. &_vq_auxt__44c5_s_p4_0,
  132512. NULL,
  132513. 0
  132514. };
  132515. static long _vq_quantlist__44c5_s_p5_0[] = {
  132516. 4,
  132517. 3,
  132518. 5,
  132519. 2,
  132520. 6,
  132521. 1,
  132522. 7,
  132523. 0,
  132524. 8,
  132525. };
  132526. static long _vq_lengthlist__44c5_s_p5_0[] = {
  132527. 2, 4, 3, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  132528. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7,
  132529. 7, 7, 9, 9, 0, 0, 0, 7, 6, 7, 7, 9, 9, 0, 0, 0,
  132530. 8, 8, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  132531. 0, 0, 9, 9, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  132532. 10,
  132533. };
  132534. static float _vq_quantthresh__44c5_s_p5_0[] = {
  132535. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  132536. };
  132537. static long _vq_quantmap__44c5_s_p5_0[] = {
  132538. 7, 5, 3, 1, 0, 2, 4, 6,
  132539. 8,
  132540. };
  132541. static encode_aux_threshmatch _vq_auxt__44c5_s_p5_0 = {
  132542. _vq_quantthresh__44c5_s_p5_0,
  132543. _vq_quantmap__44c5_s_p5_0,
  132544. 9,
  132545. 9
  132546. };
  132547. static static_codebook _44c5_s_p5_0 = {
  132548. 2, 81,
  132549. _vq_lengthlist__44c5_s_p5_0,
  132550. 1, -531628032, 1611661312, 4, 0,
  132551. _vq_quantlist__44c5_s_p5_0,
  132552. NULL,
  132553. &_vq_auxt__44c5_s_p5_0,
  132554. NULL,
  132555. 0
  132556. };
  132557. static long _vq_quantlist__44c5_s_p6_0[] = {
  132558. 8,
  132559. 7,
  132560. 9,
  132561. 6,
  132562. 10,
  132563. 5,
  132564. 11,
  132565. 4,
  132566. 12,
  132567. 3,
  132568. 13,
  132569. 2,
  132570. 14,
  132571. 1,
  132572. 15,
  132573. 0,
  132574. 16,
  132575. };
  132576. static long _vq_lengthlist__44c5_s_p6_0[] = {
  132577. 2, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,11,
  132578. 11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,11,
  132579. 12,12, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,
  132580. 11,12,12, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  132581. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  132582. 10,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  132583. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 9,10,10,10,
  132584. 10,11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,
  132585. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  132586. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  132587. 10,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9,
  132588. 9, 9,10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  132589. 10,10,10,10,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  132590. 0, 0, 0,10,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  132591. 0, 0, 0, 0,11,11,11,11,12,12,12,13,13,13, 0, 0,
  132592. 0, 0, 0, 0, 0,11,11,11,11,12,12,12,12,13,13, 0,
  132593. 0, 0, 0, 0, 0, 0,12,12,12,12,13,12,13,13,13,13,
  132594. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,
  132595. 13,
  132596. };
  132597. static float _vq_quantthresh__44c5_s_p6_0[] = {
  132598. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  132599. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  132600. };
  132601. static long _vq_quantmap__44c5_s_p6_0[] = {
  132602. 15, 13, 11, 9, 7, 5, 3, 1,
  132603. 0, 2, 4, 6, 8, 10, 12, 14,
  132604. 16,
  132605. };
  132606. static encode_aux_threshmatch _vq_auxt__44c5_s_p6_0 = {
  132607. _vq_quantthresh__44c5_s_p6_0,
  132608. _vq_quantmap__44c5_s_p6_0,
  132609. 17,
  132610. 17
  132611. };
  132612. static static_codebook _44c5_s_p6_0 = {
  132613. 2, 289,
  132614. _vq_lengthlist__44c5_s_p6_0,
  132615. 1, -529530880, 1611661312, 5, 0,
  132616. _vq_quantlist__44c5_s_p6_0,
  132617. NULL,
  132618. &_vq_auxt__44c5_s_p6_0,
  132619. NULL,
  132620. 0
  132621. };
  132622. static long _vq_quantlist__44c5_s_p7_0[] = {
  132623. 1,
  132624. 0,
  132625. 2,
  132626. };
  132627. static long _vq_lengthlist__44c5_s_p7_0[] = {
  132628. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  132629. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  132630. 10,11,11,11, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  132631. 11,10,10,11,10,10, 7,11,11,12,11,11,12,11,11, 6,
  132632. 9, 9,11,10,10,11,10,10, 6, 9, 9,11,10,10,11,10,
  132633. 10,
  132634. };
  132635. static float _vq_quantthresh__44c5_s_p7_0[] = {
  132636. -5.5, 5.5,
  132637. };
  132638. static long _vq_quantmap__44c5_s_p7_0[] = {
  132639. 1, 0, 2,
  132640. };
  132641. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_0 = {
  132642. _vq_quantthresh__44c5_s_p7_0,
  132643. _vq_quantmap__44c5_s_p7_0,
  132644. 3,
  132645. 3
  132646. };
  132647. static static_codebook _44c5_s_p7_0 = {
  132648. 4, 81,
  132649. _vq_lengthlist__44c5_s_p7_0,
  132650. 1, -529137664, 1618345984, 2, 0,
  132651. _vq_quantlist__44c5_s_p7_0,
  132652. NULL,
  132653. &_vq_auxt__44c5_s_p7_0,
  132654. NULL,
  132655. 0
  132656. };
  132657. static long _vq_quantlist__44c5_s_p7_1[] = {
  132658. 5,
  132659. 4,
  132660. 6,
  132661. 3,
  132662. 7,
  132663. 2,
  132664. 8,
  132665. 1,
  132666. 9,
  132667. 0,
  132668. 10,
  132669. };
  132670. static long _vq_lengthlist__44c5_s_p7_1[] = {
  132671. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6,
  132672. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  132673. 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  132674. 7, 8, 8, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  132675. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  132676. 8, 8, 8, 8, 8, 8, 8, 9,10,10,10,10,10, 8, 8, 8,
  132677. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  132678. 10,10,10, 8, 8, 8, 8, 8, 8,
  132679. };
  132680. static float _vq_quantthresh__44c5_s_p7_1[] = {
  132681. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  132682. 3.5, 4.5,
  132683. };
  132684. static long _vq_quantmap__44c5_s_p7_1[] = {
  132685. 9, 7, 5, 3, 1, 0, 2, 4,
  132686. 6, 8, 10,
  132687. };
  132688. static encode_aux_threshmatch _vq_auxt__44c5_s_p7_1 = {
  132689. _vq_quantthresh__44c5_s_p7_1,
  132690. _vq_quantmap__44c5_s_p7_1,
  132691. 11,
  132692. 11
  132693. };
  132694. static static_codebook _44c5_s_p7_1 = {
  132695. 2, 121,
  132696. _vq_lengthlist__44c5_s_p7_1,
  132697. 1, -531365888, 1611661312, 4, 0,
  132698. _vq_quantlist__44c5_s_p7_1,
  132699. NULL,
  132700. &_vq_auxt__44c5_s_p7_1,
  132701. NULL,
  132702. 0
  132703. };
  132704. static long _vq_quantlist__44c5_s_p8_0[] = {
  132705. 6,
  132706. 5,
  132707. 7,
  132708. 4,
  132709. 8,
  132710. 3,
  132711. 9,
  132712. 2,
  132713. 10,
  132714. 1,
  132715. 11,
  132716. 0,
  132717. 12,
  132718. };
  132719. static long _vq_lengthlist__44c5_s_p8_0[] = {
  132720. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  132721. 7, 7, 8, 8, 8, 9,10,10,10,10, 7, 5, 5, 7, 7, 8,
  132722. 8, 9, 9,10,10,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  132723. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  132724. 11, 0,12,12, 9, 9, 9,10,10,10,10,10,11,11, 0,13,
  132725. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  132726. 10,10,10,10,11,11,11,11, 0, 0, 0,10,10,10,10,10,
  132727. 10,11,11,12,12, 0, 0, 0,14,14,11,11,11,11,12,12,
  132728. 12,12, 0, 0, 0,14,14,11,11,11,11,12,12,12,12, 0,
  132729. 0, 0, 0, 0,12,12,12,12,12,12,13,13, 0, 0, 0, 0,
  132730. 0,12,12,12,12,12,12,13,13,
  132731. };
  132732. static float _vq_quantthresh__44c5_s_p8_0[] = {
  132733. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  132734. 12.5, 17.5, 22.5, 27.5,
  132735. };
  132736. static long _vq_quantmap__44c5_s_p8_0[] = {
  132737. 11, 9, 7, 5, 3, 1, 0, 2,
  132738. 4, 6, 8, 10, 12,
  132739. };
  132740. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_0 = {
  132741. _vq_quantthresh__44c5_s_p8_0,
  132742. _vq_quantmap__44c5_s_p8_0,
  132743. 13,
  132744. 13
  132745. };
  132746. static static_codebook _44c5_s_p8_0 = {
  132747. 2, 169,
  132748. _vq_lengthlist__44c5_s_p8_0,
  132749. 1, -526516224, 1616117760, 4, 0,
  132750. _vq_quantlist__44c5_s_p8_0,
  132751. NULL,
  132752. &_vq_auxt__44c5_s_p8_0,
  132753. NULL,
  132754. 0
  132755. };
  132756. static long _vq_quantlist__44c5_s_p8_1[] = {
  132757. 2,
  132758. 1,
  132759. 3,
  132760. 0,
  132761. 4,
  132762. };
  132763. static long _vq_lengthlist__44c5_s_p8_1[] = {
  132764. 2, 4, 4, 5, 5, 6, 5, 5, 5, 5, 6, 4, 5, 5, 5, 6,
  132765. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  132766. };
  132767. static float _vq_quantthresh__44c5_s_p8_1[] = {
  132768. -1.5, -0.5, 0.5, 1.5,
  132769. };
  132770. static long _vq_quantmap__44c5_s_p8_1[] = {
  132771. 3, 1, 0, 2, 4,
  132772. };
  132773. static encode_aux_threshmatch _vq_auxt__44c5_s_p8_1 = {
  132774. _vq_quantthresh__44c5_s_p8_1,
  132775. _vq_quantmap__44c5_s_p8_1,
  132776. 5,
  132777. 5
  132778. };
  132779. static static_codebook _44c5_s_p8_1 = {
  132780. 2, 25,
  132781. _vq_lengthlist__44c5_s_p8_1,
  132782. 1, -533725184, 1611661312, 3, 0,
  132783. _vq_quantlist__44c5_s_p8_1,
  132784. NULL,
  132785. &_vq_auxt__44c5_s_p8_1,
  132786. NULL,
  132787. 0
  132788. };
  132789. static long _vq_quantlist__44c5_s_p9_0[] = {
  132790. 7,
  132791. 6,
  132792. 8,
  132793. 5,
  132794. 9,
  132795. 4,
  132796. 10,
  132797. 3,
  132798. 11,
  132799. 2,
  132800. 12,
  132801. 1,
  132802. 13,
  132803. 0,
  132804. 14,
  132805. };
  132806. static long _vq_lengthlist__44c5_s_p9_0[] = {
  132807. 1, 3, 3,13,13,13,13,13,13,13,13,13,13,13,13, 4,
  132808. 7, 7,13,13,13,13,13,13,13,13,13,13,13,13, 3, 8,
  132809. 6,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132810. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132811. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132812. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132813. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132814. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132815. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132816. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132817. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132818. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132819. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  132820. 13,13,13,13,13,13,13,13,13,12,12,12,12,12,12,12,
  132821. 12,
  132822. };
  132823. static float _vq_quantthresh__44c5_s_p9_0[] = {
  132824. -2320.5, -1963.5, -1606.5, -1249.5, -892.5, -535.5, -178.5, 178.5,
  132825. 535.5, 892.5, 1249.5, 1606.5, 1963.5, 2320.5,
  132826. };
  132827. static long _vq_quantmap__44c5_s_p9_0[] = {
  132828. 13, 11, 9, 7, 5, 3, 1, 0,
  132829. 2, 4, 6, 8, 10, 12, 14,
  132830. };
  132831. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_0 = {
  132832. _vq_quantthresh__44c5_s_p9_0,
  132833. _vq_quantmap__44c5_s_p9_0,
  132834. 15,
  132835. 15
  132836. };
  132837. static static_codebook _44c5_s_p9_0 = {
  132838. 2, 225,
  132839. _vq_lengthlist__44c5_s_p9_0,
  132840. 1, -512522752, 1628852224, 4, 0,
  132841. _vq_quantlist__44c5_s_p9_0,
  132842. NULL,
  132843. &_vq_auxt__44c5_s_p9_0,
  132844. NULL,
  132845. 0
  132846. };
  132847. static long _vq_quantlist__44c5_s_p9_1[] = {
  132848. 8,
  132849. 7,
  132850. 9,
  132851. 6,
  132852. 10,
  132853. 5,
  132854. 11,
  132855. 4,
  132856. 12,
  132857. 3,
  132858. 13,
  132859. 2,
  132860. 14,
  132861. 1,
  132862. 15,
  132863. 0,
  132864. 16,
  132865. };
  132866. static long _vq_lengthlist__44c5_s_p9_1[] = {
  132867. 1, 4, 4, 5, 5, 7, 7, 9, 8,10, 9,10,10,11,10,11,
  132868. 11, 6, 5, 5, 7, 7, 8, 9,10,10,11,10,12,11,12,11,
  132869. 13,12, 6, 5, 5, 7, 7, 9, 9,10,10,11,11,12,12,13,
  132870. 12,13,13,18, 8, 8, 8, 8, 9, 9,10,11,11,11,12,11,
  132871. 13,11,13,12,18, 8, 8, 8, 8,10,10,11,11,12,12,13,
  132872. 13,13,13,13,14,18,12,12, 9, 9,11,11,11,11,12,12,
  132873. 13,12,13,12,13,13,20,13,12, 9, 9,11,11,11,11,12,
  132874. 12,13,13,13,14,14,13,20,18,19,11,12,11,11,12,12,
  132875. 13,13,13,13,13,13,14,13,18,19,19,12,11,11,11,12,
  132876. 12,13,12,13,13,13,14,14,13,18,17,19,14,15,12,12,
  132877. 12,13,13,13,14,14,14,14,14,14,19,19,19,16,15,12,
  132878. 11,13,12,14,14,14,13,13,14,14,14,19,18,19,18,19,
  132879. 13,13,13,13,14,14,14,13,14,14,14,14,18,17,19,19,
  132880. 19,13,13,13,11,13,11,13,14,14,14,14,14,19,17,17,
  132881. 18,18,16,16,13,13,13,13,14,13,15,15,14,14,19,19,
  132882. 17,17,18,16,16,13,11,14,10,13,12,14,14,14,14,19,
  132883. 19,19,19,19,18,17,13,14,13,11,14,13,14,14,15,15,
  132884. 19,19,19,17,19,18,18,14,13,12,11,14,11,15,15,15,
  132885. 15,
  132886. };
  132887. static float _vq_quantthresh__44c5_s_p9_1[] = {
  132888. -157.5, -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5,
  132889. 10.5, 31.5, 52.5, 73.5, 94.5, 115.5, 136.5, 157.5,
  132890. };
  132891. static long _vq_quantmap__44c5_s_p9_1[] = {
  132892. 15, 13, 11, 9, 7, 5, 3, 1,
  132893. 0, 2, 4, 6, 8, 10, 12, 14,
  132894. 16,
  132895. };
  132896. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_1 = {
  132897. _vq_quantthresh__44c5_s_p9_1,
  132898. _vq_quantmap__44c5_s_p9_1,
  132899. 17,
  132900. 17
  132901. };
  132902. static static_codebook _44c5_s_p9_1 = {
  132903. 2, 289,
  132904. _vq_lengthlist__44c5_s_p9_1,
  132905. 1, -520814592, 1620377600, 5, 0,
  132906. _vq_quantlist__44c5_s_p9_1,
  132907. NULL,
  132908. &_vq_auxt__44c5_s_p9_1,
  132909. NULL,
  132910. 0
  132911. };
  132912. static long _vq_quantlist__44c5_s_p9_2[] = {
  132913. 10,
  132914. 9,
  132915. 11,
  132916. 8,
  132917. 12,
  132918. 7,
  132919. 13,
  132920. 6,
  132921. 14,
  132922. 5,
  132923. 15,
  132924. 4,
  132925. 16,
  132926. 3,
  132927. 17,
  132928. 2,
  132929. 18,
  132930. 1,
  132931. 19,
  132932. 0,
  132933. 20,
  132934. };
  132935. static long _vq_lengthlist__44c5_s_p9_2[] = {
  132936. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  132937. 8, 8, 8, 8, 9,11, 5, 6, 7, 7, 8, 7, 8, 8, 8, 8,
  132938. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11, 5, 5, 7, 7, 7,
  132939. 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  132940. 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  132941. 9,10, 9,10,11,11,11, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  132942. 9, 9, 9,10,10,10,10,10,10,11,11,11, 8, 8, 8, 8,
  132943. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,11,11,
  132944. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,
  132945. 10,10,10,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  132946. 10,10,10,10,10,10,10,10,11,11,11,11,11, 9, 9, 9,
  132947. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,11,11,11,
  132948. 11,11, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,
  132949. 10,10,11,11,11,11,11, 9, 9, 9, 9, 9, 9,10,10,10,
  132950. 10,10,10,10,10,10,10,11,11,11,11,11, 9, 9,10, 9,
  132951. 10,10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,
  132952. 11,11,11, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  132953. 10,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132954. 10,10,10,10,10,10,11,11,11,11,11,11,11,10,10,10,
  132955. 10,10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,
  132956. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  132957. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  132958. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  132959. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  132960. 11,11,11,10,10,10,10,10,10,10,10,10,10,10,10,11,
  132961. 11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,10,
  132962. 10,10,10,10,11,11,11,11,11,11,11,11,11,11,11,10,
  132963. 10,10,10,10,10,10,10,10,10,
  132964. };
  132965. static float _vq_quantthresh__44c5_s_p9_2[] = {
  132966. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  132967. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  132968. 6.5, 7.5, 8.5, 9.5,
  132969. };
  132970. static long _vq_quantmap__44c5_s_p9_2[] = {
  132971. 19, 17, 15, 13, 11, 9, 7, 5,
  132972. 3, 1, 0, 2, 4, 6, 8, 10,
  132973. 12, 14, 16, 18, 20,
  132974. };
  132975. static encode_aux_threshmatch _vq_auxt__44c5_s_p9_2 = {
  132976. _vq_quantthresh__44c5_s_p9_2,
  132977. _vq_quantmap__44c5_s_p9_2,
  132978. 21,
  132979. 21
  132980. };
  132981. static static_codebook _44c5_s_p9_2 = {
  132982. 2, 441,
  132983. _vq_lengthlist__44c5_s_p9_2,
  132984. 1, -529268736, 1611661312, 5, 0,
  132985. _vq_quantlist__44c5_s_p9_2,
  132986. NULL,
  132987. &_vq_auxt__44c5_s_p9_2,
  132988. NULL,
  132989. 0
  132990. };
  132991. static long _huff_lengthlist__44c5_s_short[] = {
  132992. 5, 8,10,14,11,11,12,16,15,17, 5, 5, 7, 9, 7, 8,
  132993. 10,13,17,17, 7, 5, 5,10, 5, 7, 8,11,13,15,10, 8,
  132994. 10, 8, 8, 8,11,15,18,18, 8, 5, 5, 8, 3, 4, 6,10,
  132995. 14,16, 9, 7, 6, 7, 4, 3, 5, 9,14,18,10, 9, 8,10,
  132996. 6, 5, 6, 9,14,18,12,12,11,12, 8, 7, 8,11,14,18,
  132997. 14,13,12,10, 7, 5, 6, 9,14,18,14,14,13,10, 6, 5,
  132998. 6, 8,11,16,
  132999. };
  133000. static static_codebook _huff_book__44c5_s_short = {
  133001. 2, 100,
  133002. _huff_lengthlist__44c5_s_short,
  133003. 0, 0, 0, 0, 0,
  133004. NULL,
  133005. NULL,
  133006. NULL,
  133007. NULL,
  133008. 0
  133009. };
  133010. static long _huff_lengthlist__44c6_s_long[] = {
  133011. 3, 8,11,13,14,14,13,13,16,14, 6, 3, 4, 7, 9, 9,
  133012. 10,11,14,13,10, 4, 3, 5, 7, 7, 9,10,13,15,12, 7,
  133013. 4, 4, 6, 6, 8,10,13,15,12, 8, 6, 6, 6, 6, 8,10,
  133014. 13,14,11, 9, 7, 6, 6, 6, 7, 8,12,11,13,10, 9, 8,
  133015. 7, 6, 6, 7,11,11,13,11,10, 9, 9, 7, 7, 6,10,11,
  133016. 13,13,13,13,13,11, 9, 8,10,12,12,15,15,16,15,12,
  133017. 11,10,10,12,
  133018. };
  133019. static static_codebook _huff_book__44c6_s_long = {
  133020. 2, 100,
  133021. _huff_lengthlist__44c6_s_long,
  133022. 0, 0, 0, 0, 0,
  133023. NULL,
  133024. NULL,
  133025. NULL,
  133026. NULL,
  133027. 0
  133028. };
  133029. static long _vq_quantlist__44c6_s_p1_0[] = {
  133030. 1,
  133031. 0,
  133032. 2,
  133033. };
  133034. static long _vq_lengthlist__44c6_s_p1_0[] = {
  133035. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133036. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133037. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133038. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133039. 9, 9, 0, 8, 8, 0, 8, 8, 5, 9, 9, 0, 8, 8, 0, 8,
  133040. 8,
  133041. };
  133042. static float _vq_quantthresh__44c6_s_p1_0[] = {
  133043. -0.5, 0.5,
  133044. };
  133045. static long _vq_quantmap__44c6_s_p1_0[] = {
  133046. 1, 0, 2,
  133047. };
  133048. static encode_aux_threshmatch _vq_auxt__44c6_s_p1_0 = {
  133049. _vq_quantthresh__44c6_s_p1_0,
  133050. _vq_quantmap__44c6_s_p1_0,
  133051. 3,
  133052. 3
  133053. };
  133054. static static_codebook _44c6_s_p1_0 = {
  133055. 4, 81,
  133056. _vq_lengthlist__44c6_s_p1_0,
  133057. 1, -535822336, 1611661312, 2, 0,
  133058. _vq_quantlist__44c6_s_p1_0,
  133059. NULL,
  133060. &_vq_auxt__44c6_s_p1_0,
  133061. NULL,
  133062. 0
  133063. };
  133064. static long _vq_quantlist__44c6_s_p2_0[] = {
  133065. 2,
  133066. 1,
  133067. 3,
  133068. 0,
  133069. 4,
  133070. };
  133071. static long _vq_lengthlist__44c6_s_p2_0[] = {
  133072. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133073. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133074. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133075. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133076. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,11,
  133077. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133078. 0, 0,14,13, 8, 9, 9,11,11, 0,11,11,12,12, 0,10,
  133079. 11,12,12, 0,14,13,14,14, 0, 0, 0,13,14, 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, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133082. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133083. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133084. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133085. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133086. 13, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,12,12,
  133087. 0,12,12,13,13, 0, 0, 0,13,13, 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, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133090. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,11,
  133091. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,11,
  133092. 0, 0, 0,10,11, 8,10,10,12,12, 0,10,10,12,12, 0,
  133093. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,14,13, 8,10,
  133094. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133095. 13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133097. 7,10,10,14,13, 0, 9, 9,13,12, 0, 9, 9,12,12, 0,
  133098. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133099. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133100. 12,12, 9,11,11,14,13, 0,11,10,14,13, 0,11,11,13,
  133101. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133102. 0,10,11,13,14, 0,11,11,13,13, 0,12,12,13,13, 0,
  133103. 0, 0,13,13, 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, 9,
  133108. 11,11,14,14, 0,11,11,13,13, 0,11,10,13,13, 0,12,
  133109. 12,13,13, 0, 0, 0,13,13, 9,11,11,14,14, 0,11,11,
  133110. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133111. 13,
  133112. };
  133113. static float _vq_quantthresh__44c6_s_p2_0[] = {
  133114. -1.5, -0.5, 0.5, 1.5,
  133115. };
  133116. static long _vq_quantmap__44c6_s_p2_0[] = {
  133117. 3, 1, 0, 2, 4,
  133118. };
  133119. static encode_aux_threshmatch _vq_auxt__44c6_s_p2_0 = {
  133120. _vq_quantthresh__44c6_s_p2_0,
  133121. _vq_quantmap__44c6_s_p2_0,
  133122. 5,
  133123. 5
  133124. };
  133125. static static_codebook _44c6_s_p2_0 = {
  133126. 4, 625,
  133127. _vq_lengthlist__44c6_s_p2_0,
  133128. 1, -533725184, 1611661312, 3, 0,
  133129. _vq_quantlist__44c6_s_p2_0,
  133130. NULL,
  133131. &_vq_auxt__44c6_s_p2_0,
  133132. NULL,
  133133. 0
  133134. };
  133135. static long _vq_quantlist__44c6_s_p3_0[] = {
  133136. 4,
  133137. 3,
  133138. 5,
  133139. 2,
  133140. 6,
  133141. 1,
  133142. 7,
  133143. 0,
  133144. 8,
  133145. };
  133146. static long _vq_lengthlist__44c6_s_p3_0[] = {
  133147. 2, 3, 4, 6, 6, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133148. 9,10, 0, 4, 4, 6, 6, 7, 7,10, 9, 0, 5, 5, 7, 7,
  133149. 8, 8,10,10, 0, 0, 0, 7, 6, 8, 8,10,10, 0, 0, 0,
  133150. 7, 7, 9, 9,11,11, 0, 0, 0, 7, 7, 9, 9,11,11, 0,
  133151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133152. 0,
  133153. };
  133154. static float _vq_quantthresh__44c6_s_p3_0[] = {
  133155. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  133156. };
  133157. static long _vq_quantmap__44c6_s_p3_0[] = {
  133158. 7, 5, 3, 1, 0, 2, 4, 6,
  133159. 8,
  133160. };
  133161. static encode_aux_threshmatch _vq_auxt__44c6_s_p3_0 = {
  133162. _vq_quantthresh__44c6_s_p3_0,
  133163. _vq_quantmap__44c6_s_p3_0,
  133164. 9,
  133165. 9
  133166. };
  133167. static static_codebook _44c6_s_p3_0 = {
  133168. 2, 81,
  133169. _vq_lengthlist__44c6_s_p3_0,
  133170. 1, -531628032, 1611661312, 4, 0,
  133171. _vq_quantlist__44c6_s_p3_0,
  133172. NULL,
  133173. &_vq_auxt__44c6_s_p3_0,
  133174. NULL,
  133175. 0
  133176. };
  133177. static long _vq_quantlist__44c6_s_p4_0[] = {
  133178. 8,
  133179. 7,
  133180. 9,
  133181. 6,
  133182. 10,
  133183. 5,
  133184. 11,
  133185. 4,
  133186. 12,
  133187. 3,
  133188. 13,
  133189. 2,
  133190. 14,
  133191. 1,
  133192. 15,
  133193. 0,
  133194. 16,
  133195. };
  133196. static long _vq_lengthlist__44c6_s_p4_0[] = {
  133197. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,10,10,
  133198. 10, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  133199. 11,11, 0, 4, 4, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  133200. 10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  133201. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  133202. 10,11,11,11,11, 0, 0, 0, 7, 7, 9, 9,10,10,10,10,
  133203. 11,11,11,11,12,12, 0, 0, 0, 7, 7, 9, 9,10,10,10,
  133204. 10,11,11,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  133205. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 8, 8, 9,
  133206. 9,10,10,11,11,12,12,12,12, 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,
  133216. };
  133217. static float _vq_quantthresh__44c6_s_p4_0[] = {
  133218. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133219. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133220. };
  133221. static long _vq_quantmap__44c6_s_p4_0[] = {
  133222. 15, 13, 11, 9, 7, 5, 3, 1,
  133223. 0, 2, 4, 6, 8, 10, 12, 14,
  133224. 16,
  133225. };
  133226. static encode_aux_threshmatch _vq_auxt__44c6_s_p4_0 = {
  133227. _vq_quantthresh__44c6_s_p4_0,
  133228. _vq_quantmap__44c6_s_p4_0,
  133229. 17,
  133230. 17
  133231. };
  133232. static static_codebook _44c6_s_p4_0 = {
  133233. 2, 289,
  133234. _vq_lengthlist__44c6_s_p4_0,
  133235. 1, -529530880, 1611661312, 5, 0,
  133236. _vq_quantlist__44c6_s_p4_0,
  133237. NULL,
  133238. &_vq_auxt__44c6_s_p4_0,
  133239. NULL,
  133240. 0
  133241. };
  133242. static long _vq_quantlist__44c6_s_p5_0[] = {
  133243. 1,
  133244. 0,
  133245. 2,
  133246. };
  133247. static long _vq_lengthlist__44c6_s_p5_0[] = {
  133248. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 6, 9, 9,10,10,
  133249. 10, 9, 4, 6, 6, 9,10, 9,10, 9,10, 6, 9, 9,10,12,
  133250. 11,10,11,11, 7,10, 9,11,12,12,12,12,12, 7,10,10,
  133251. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  133252. 9,10,11,12,12,12,12,12, 7,10, 9,12,12,12,12,12,
  133253. 12,
  133254. };
  133255. static float _vq_quantthresh__44c6_s_p5_0[] = {
  133256. -5.5, 5.5,
  133257. };
  133258. static long _vq_quantmap__44c6_s_p5_0[] = {
  133259. 1, 0, 2,
  133260. };
  133261. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_0 = {
  133262. _vq_quantthresh__44c6_s_p5_0,
  133263. _vq_quantmap__44c6_s_p5_0,
  133264. 3,
  133265. 3
  133266. };
  133267. static static_codebook _44c6_s_p5_0 = {
  133268. 4, 81,
  133269. _vq_lengthlist__44c6_s_p5_0,
  133270. 1, -529137664, 1618345984, 2, 0,
  133271. _vq_quantlist__44c6_s_p5_0,
  133272. NULL,
  133273. &_vq_auxt__44c6_s_p5_0,
  133274. NULL,
  133275. 0
  133276. };
  133277. static long _vq_quantlist__44c6_s_p5_1[] = {
  133278. 5,
  133279. 4,
  133280. 6,
  133281. 3,
  133282. 7,
  133283. 2,
  133284. 8,
  133285. 1,
  133286. 9,
  133287. 0,
  133288. 10,
  133289. };
  133290. static long _vq_lengthlist__44c6_s_p5_1[] = {
  133291. 3, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  133292. 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6, 7, 7, 8, 8, 8,
  133293. 8,11, 6, 6, 6, 6, 8, 8, 8, 8, 9, 9,11,11,11, 6,
  133294. 6, 7, 8, 8, 8, 8, 9,11,11,11, 7, 7, 8, 8, 8, 8,
  133295. 8, 8,11,11,11, 7, 7, 8, 8, 8, 8, 8, 8,11,11,11,
  133296. 8, 8, 8, 8, 8, 8, 8, 8,11,11,11,10,10, 8, 8, 8,
  133297. 8, 8, 8,11,11,11,10,10, 8, 8, 8, 8, 8, 8,11,11,
  133298. 11,10,10, 7, 7, 8, 8, 8, 8,
  133299. };
  133300. static float _vq_quantthresh__44c6_s_p5_1[] = {
  133301. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133302. 3.5, 4.5,
  133303. };
  133304. static long _vq_quantmap__44c6_s_p5_1[] = {
  133305. 9, 7, 5, 3, 1, 0, 2, 4,
  133306. 6, 8, 10,
  133307. };
  133308. static encode_aux_threshmatch _vq_auxt__44c6_s_p5_1 = {
  133309. _vq_quantthresh__44c6_s_p5_1,
  133310. _vq_quantmap__44c6_s_p5_1,
  133311. 11,
  133312. 11
  133313. };
  133314. static static_codebook _44c6_s_p5_1 = {
  133315. 2, 121,
  133316. _vq_lengthlist__44c6_s_p5_1,
  133317. 1, -531365888, 1611661312, 4, 0,
  133318. _vq_quantlist__44c6_s_p5_1,
  133319. NULL,
  133320. &_vq_auxt__44c6_s_p5_1,
  133321. NULL,
  133322. 0
  133323. };
  133324. static long _vq_quantlist__44c6_s_p6_0[] = {
  133325. 6,
  133326. 5,
  133327. 7,
  133328. 4,
  133329. 8,
  133330. 3,
  133331. 9,
  133332. 2,
  133333. 10,
  133334. 1,
  133335. 11,
  133336. 0,
  133337. 12,
  133338. };
  133339. static long _vq_lengthlist__44c6_s_p6_0[] = {
  133340. 1, 4, 4, 6, 6, 8, 8, 8, 8,10, 9,10,10, 6, 5, 5,
  133341. 7, 7, 9, 9, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 9,
  133342. 9,10, 9,11,10,11,11, 0, 6, 6, 7, 7, 9, 9,10,10,
  133343. 11,11,12,12, 0, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  133344. 12, 0,11,11, 8, 8,10,10,11,11,12,12,12,12, 0,11,
  133345. 12, 9, 8,10,10,11,11,12,12,13,13, 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,
  133351. };
  133352. static float _vq_quantthresh__44c6_s_p6_0[] = {
  133353. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  133354. 12.5, 17.5, 22.5, 27.5,
  133355. };
  133356. static long _vq_quantmap__44c6_s_p6_0[] = {
  133357. 11, 9, 7, 5, 3, 1, 0, 2,
  133358. 4, 6, 8, 10, 12,
  133359. };
  133360. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_0 = {
  133361. _vq_quantthresh__44c6_s_p6_0,
  133362. _vq_quantmap__44c6_s_p6_0,
  133363. 13,
  133364. 13
  133365. };
  133366. static static_codebook _44c6_s_p6_0 = {
  133367. 2, 169,
  133368. _vq_lengthlist__44c6_s_p6_0,
  133369. 1, -526516224, 1616117760, 4, 0,
  133370. _vq_quantlist__44c6_s_p6_0,
  133371. NULL,
  133372. &_vq_auxt__44c6_s_p6_0,
  133373. NULL,
  133374. 0
  133375. };
  133376. static long _vq_quantlist__44c6_s_p6_1[] = {
  133377. 2,
  133378. 1,
  133379. 3,
  133380. 0,
  133381. 4,
  133382. };
  133383. static long _vq_lengthlist__44c6_s_p6_1[] = {
  133384. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  133385. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  133386. };
  133387. static float _vq_quantthresh__44c6_s_p6_1[] = {
  133388. -1.5, -0.5, 0.5, 1.5,
  133389. };
  133390. static long _vq_quantmap__44c6_s_p6_1[] = {
  133391. 3, 1, 0, 2, 4,
  133392. };
  133393. static encode_aux_threshmatch _vq_auxt__44c6_s_p6_1 = {
  133394. _vq_quantthresh__44c6_s_p6_1,
  133395. _vq_quantmap__44c6_s_p6_1,
  133396. 5,
  133397. 5
  133398. };
  133399. static static_codebook _44c6_s_p6_1 = {
  133400. 2, 25,
  133401. _vq_lengthlist__44c6_s_p6_1,
  133402. 1, -533725184, 1611661312, 3, 0,
  133403. _vq_quantlist__44c6_s_p6_1,
  133404. NULL,
  133405. &_vq_auxt__44c6_s_p6_1,
  133406. NULL,
  133407. 0
  133408. };
  133409. static long _vq_quantlist__44c6_s_p7_0[] = {
  133410. 6,
  133411. 5,
  133412. 7,
  133413. 4,
  133414. 8,
  133415. 3,
  133416. 9,
  133417. 2,
  133418. 10,
  133419. 1,
  133420. 11,
  133421. 0,
  133422. 12,
  133423. };
  133424. static long _vq_lengthlist__44c6_s_p7_0[] = {
  133425. 1, 4, 4, 6, 6, 8, 8, 8, 8,10,10,11,10, 6, 5, 5,
  133426. 7, 7, 8, 8, 9, 9,10,10,12,11, 6, 5, 5, 7, 7, 8,
  133427. 8, 9, 9,10,10,12,11,21, 7, 7, 7, 7, 9, 9,10,10,
  133428. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,11,11,12,
  133429. 12,21,12,12, 9, 9,10,10,11,11,11,11,12,12,21,12,
  133430. 12, 9, 9,10,10,11,11,12,12,12,12,21,21,21,11,11,
  133431. 10,10,11,12,12,12,13,13,21,21,21,11,11,10,10,12,
  133432. 12,12,12,13,13,21,21,21,15,15,11,11,12,12,13,13,
  133433. 13,13,21,21,21,15,16,11,11,12,12,13,13,14,14,21,
  133434. 21,21,21,20,13,13,13,13,13,13,14,14,20,20,20,20,
  133435. 20,13,13,13,13,13,13,14,14,
  133436. };
  133437. static float _vq_quantthresh__44c6_s_p7_0[] = {
  133438. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  133439. 27.5, 38.5, 49.5, 60.5,
  133440. };
  133441. static long _vq_quantmap__44c6_s_p7_0[] = {
  133442. 11, 9, 7, 5, 3, 1, 0, 2,
  133443. 4, 6, 8, 10, 12,
  133444. };
  133445. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_0 = {
  133446. _vq_quantthresh__44c6_s_p7_0,
  133447. _vq_quantmap__44c6_s_p7_0,
  133448. 13,
  133449. 13
  133450. };
  133451. static static_codebook _44c6_s_p7_0 = {
  133452. 2, 169,
  133453. _vq_lengthlist__44c6_s_p7_0,
  133454. 1, -523206656, 1618345984, 4, 0,
  133455. _vq_quantlist__44c6_s_p7_0,
  133456. NULL,
  133457. &_vq_auxt__44c6_s_p7_0,
  133458. NULL,
  133459. 0
  133460. };
  133461. static long _vq_quantlist__44c6_s_p7_1[] = {
  133462. 5,
  133463. 4,
  133464. 6,
  133465. 3,
  133466. 7,
  133467. 2,
  133468. 8,
  133469. 1,
  133470. 9,
  133471. 0,
  133472. 10,
  133473. };
  133474. static long _vq_lengthlist__44c6_s_p7_1[] = {
  133475. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 9, 5, 5, 6, 6,
  133476. 7, 7, 7, 7, 8, 7, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7,
  133477. 7, 9, 6, 6, 7, 7, 7, 7, 8, 7, 7, 8, 9, 9, 9, 7,
  133478. 7, 7, 7, 7, 7, 7, 8, 9, 9, 9, 7, 7, 7, 7, 8, 8,
  133479. 8, 8, 9, 9, 9, 7, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  133480. 8, 8, 8, 8, 7, 7, 8, 8, 9, 9, 9, 9, 8, 8, 8, 7,
  133481. 7, 8, 8, 9, 9, 9, 8, 8, 8, 8, 7, 7, 8, 8, 9, 9,
  133482. 9, 8, 8, 7, 7, 7, 7, 8, 8,
  133483. };
  133484. static float _vq_quantthresh__44c6_s_p7_1[] = {
  133485. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  133486. 3.5, 4.5,
  133487. };
  133488. static long _vq_quantmap__44c6_s_p7_1[] = {
  133489. 9, 7, 5, 3, 1, 0, 2, 4,
  133490. 6, 8, 10,
  133491. };
  133492. static encode_aux_threshmatch _vq_auxt__44c6_s_p7_1 = {
  133493. _vq_quantthresh__44c6_s_p7_1,
  133494. _vq_quantmap__44c6_s_p7_1,
  133495. 11,
  133496. 11
  133497. };
  133498. static static_codebook _44c6_s_p7_1 = {
  133499. 2, 121,
  133500. _vq_lengthlist__44c6_s_p7_1,
  133501. 1, -531365888, 1611661312, 4, 0,
  133502. _vq_quantlist__44c6_s_p7_1,
  133503. NULL,
  133504. &_vq_auxt__44c6_s_p7_1,
  133505. NULL,
  133506. 0
  133507. };
  133508. static long _vq_quantlist__44c6_s_p8_0[] = {
  133509. 7,
  133510. 6,
  133511. 8,
  133512. 5,
  133513. 9,
  133514. 4,
  133515. 10,
  133516. 3,
  133517. 11,
  133518. 2,
  133519. 12,
  133520. 1,
  133521. 13,
  133522. 0,
  133523. 14,
  133524. };
  133525. static long _vq_lengthlist__44c6_s_p8_0[] = {
  133526. 1, 4, 4, 7, 7, 8, 8, 7, 7, 8, 7, 9, 8,10, 9, 6,
  133527. 5, 5, 8, 8, 9, 9, 8, 8, 9, 9,11,10,11,10, 6, 5,
  133528. 5, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,11,18, 8, 8,
  133529. 9, 8,10,10, 9, 9,10,10,10,10,11,10,18, 8, 8, 9,
  133530. 9,10,10, 9, 9,10,10,11,11,12,12,18,12,13, 9,10,
  133531. 10,10, 9,10,10,10,11,11,12,11,18,13,13, 9, 9,10,
  133532. 10,10,10,10,10,11,11,12,12,18,18,18,10,10, 9, 9,
  133533. 11,11,11,11,11,12,12,12,18,18,18,10, 9,10, 9,11,
  133534. 10,11,11,11,11,13,12,18,18,18,14,13,10,10,11,11,
  133535. 12,12,12,12,12,12,18,18,18,14,13,10,10,11,10,12,
  133536. 12,12,12,12,12,18,18,18,18,18,12,12,11,11,12,12,
  133537. 13,13,13,14,18,18,18,18,18,12,12,11,11,12,11,13,
  133538. 13,14,13,18,18,18,18,18,16,16,11,12,12,13,13,13,
  133539. 14,13,18,18,18,18,18,16,15,12,11,12,11,13,11,15,
  133540. 14,
  133541. };
  133542. static float _vq_quantthresh__44c6_s_p8_0[] = {
  133543. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  133544. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  133545. };
  133546. static long _vq_quantmap__44c6_s_p8_0[] = {
  133547. 13, 11, 9, 7, 5, 3, 1, 0,
  133548. 2, 4, 6, 8, 10, 12, 14,
  133549. };
  133550. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_0 = {
  133551. _vq_quantthresh__44c6_s_p8_0,
  133552. _vq_quantmap__44c6_s_p8_0,
  133553. 15,
  133554. 15
  133555. };
  133556. static static_codebook _44c6_s_p8_0 = {
  133557. 2, 225,
  133558. _vq_lengthlist__44c6_s_p8_0,
  133559. 1, -520986624, 1620377600, 4, 0,
  133560. _vq_quantlist__44c6_s_p8_0,
  133561. NULL,
  133562. &_vq_auxt__44c6_s_p8_0,
  133563. NULL,
  133564. 0
  133565. };
  133566. static long _vq_quantlist__44c6_s_p8_1[] = {
  133567. 10,
  133568. 9,
  133569. 11,
  133570. 8,
  133571. 12,
  133572. 7,
  133573. 13,
  133574. 6,
  133575. 14,
  133576. 5,
  133577. 15,
  133578. 4,
  133579. 16,
  133580. 3,
  133581. 17,
  133582. 2,
  133583. 18,
  133584. 1,
  133585. 19,
  133586. 0,
  133587. 20,
  133588. };
  133589. static long _vq_lengthlist__44c6_s_p8_1[] = {
  133590. 3, 5, 5, 6, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 8,
  133591. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8,
  133592. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  133593. 8, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10,
  133594. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133595. 9, 9, 9, 9,10,11,11, 8, 7, 8, 8, 8, 9, 9, 9, 9,
  133596. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11, 8, 8, 8, 8,
  133597. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,
  133598. 11, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133599. 9, 9, 9,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  133600. 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9, 9,
  133601. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,
  133602. 11,11, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9,10, 9, 9,
  133603. 10, 9,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,10,10,
  133604. 10,10, 9,10,10, 9,10,11,11,11,11,11, 9, 9, 9, 9,
  133605. 10,10,10, 9,10,10,10,10, 9,10,10, 9,11,11,11,11,
  133606. 11,11,11, 9, 9, 9, 9,10,10,10,10, 9,10,10,10,10,
  133607. 10,11,11,11,11,11,11,11,10, 9,10,10,10,10,10,10,
  133608. 10, 9,10, 9,10,10,11,11,11,11,11,11,11,10, 9,10,
  133609. 9,10,10, 9,10,10,10,10,10,10,10,11,11,11,11,11,
  133610. 11,11,10,10,10,10,10,10,10, 9,10,10,10,10,10, 9,
  133611. 11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,10,
  133612. 10,10,10,10,10,11,11,11,11,11,11,11,11,11,10,10,
  133613. 10,10,10,10,10,10,10,10,10,10,11,11,11,11,11,11,
  133614. 11,11,11,10,10,10,10,10,10,10,10,10, 9,10,10,11,
  133615. 11,11,11,11,11,11,11,11,10,10,10, 9,10,10,10,10,
  133616. 10,10,10,10,10,11,11,11,11,11,11,11,11,10,11, 9,
  133617. 10,10,10,10,10,10,10,10,10,
  133618. };
  133619. static float _vq_quantthresh__44c6_s_p8_1[] = {
  133620. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  133621. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  133622. 6.5, 7.5, 8.5, 9.5,
  133623. };
  133624. static long _vq_quantmap__44c6_s_p8_1[] = {
  133625. 19, 17, 15, 13, 11, 9, 7, 5,
  133626. 3, 1, 0, 2, 4, 6, 8, 10,
  133627. 12, 14, 16, 18, 20,
  133628. };
  133629. static encode_aux_threshmatch _vq_auxt__44c6_s_p8_1 = {
  133630. _vq_quantthresh__44c6_s_p8_1,
  133631. _vq_quantmap__44c6_s_p8_1,
  133632. 21,
  133633. 21
  133634. };
  133635. static static_codebook _44c6_s_p8_1 = {
  133636. 2, 441,
  133637. _vq_lengthlist__44c6_s_p8_1,
  133638. 1, -529268736, 1611661312, 5, 0,
  133639. _vq_quantlist__44c6_s_p8_1,
  133640. NULL,
  133641. &_vq_auxt__44c6_s_p8_1,
  133642. NULL,
  133643. 0
  133644. };
  133645. static long _vq_quantlist__44c6_s_p9_0[] = {
  133646. 6,
  133647. 5,
  133648. 7,
  133649. 4,
  133650. 8,
  133651. 3,
  133652. 9,
  133653. 2,
  133654. 10,
  133655. 1,
  133656. 11,
  133657. 0,
  133658. 12,
  133659. };
  133660. static long _vq_lengthlist__44c6_s_p9_0[] = {
  133661. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 7, 7,
  133662. 11,11,11,11,11,11,11,11,11,11, 5, 8, 9,11,11,11,
  133663. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  133664. 11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,10,
  133665. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133666. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133667. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133668. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133669. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133670. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  133671. 10,10,10,10,10,10,10,10,10,
  133672. };
  133673. static float _vq_quantthresh__44c6_s_p9_0[] = {
  133674. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  133675. 1592.5, 2229.5, 2866.5, 3503.5,
  133676. };
  133677. static long _vq_quantmap__44c6_s_p9_0[] = {
  133678. 11, 9, 7, 5, 3, 1, 0, 2,
  133679. 4, 6, 8, 10, 12,
  133680. };
  133681. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_0 = {
  133682. _vq_quantthresh__44c6_s_p9_0,
  133683. _vq_quantmap__44c6_s_p9_0,
  133684. 13,
  133685. 13
  133686. };
  133687. static static_codebook _44c6_s_p9_0 = {
  133688. 2, 169,
  133689. _vq_lengthlist__44c6_s_p9_0,
  133690. 1, -511845376, 1630791680, 4, 0,
  133691. _vq_quantlist__44c6_s_p9_0,
  133692. NULL,
  133693. &_vq_auxt__44c6_s_p9_0,
  133694. NULL,
  133695. 0
  133696. };
  133697. static long _vq_quantlist__44c6_s_p9_1[] = {
  133698. 6,
  133699. 5,
  133700. 7,
  133701. 4,
  133702. 8,
  133703. 3,
  133704. 9,
  133705. 2,
  133706. 10,
  133707. 1,
  133708. 11,
  133709. 0,
  133710. 12,
  133711. };
  133712. static long _vq_lengthlist__44c6_s_p9_1[] = {
  133713. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  133714. 8, 8, 8, 8, 8, 7, 9, 8,10,10, 5, 6, 6, 8, 8, 9,
  133715. 9, 8, 8,10,10,10,10,16, 9, 9, 9, 9, 9, 9, 9, 8,
  133716. 10, 9,11,11,16, 8, 9, 9, 9, 9, 9, 9, 9,10,10,11,
  133717. 11,16,13,13, 9, 9,10, 9, 9,10,11,11,11,12,16,13,
  133718. 14, 9, 8,10, 8, 9, 9,10,10,12,11,16,14,16, 9, 9,
  133719. 9, 9,11,11,12,11,12,11,16,16,16, 9, 7, 9, 6,11,
  133720. 11,11,10,11,11,16,16,16,11,12, 9,10,11,11,12,11,
  133721. 13,13,16,16,16,12,11,10, 7,12,10,12,12,12,12,16,
  133722. 16,15,16,16,10,11,10,11,13,13,14,12,16,16,16,15,
  133723. 15,12,10,11,11,13,11,12,13,
  133724. };
  133725. static float _vq_quantthresh__44c6_s_p9_1[] = {
  133726. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  133727. 122.5, 171.5, 220.5, 269.5,
  133728. };
  133729. static long _vq_quantmap__44c6_s_p9_1[] = {
  133730. 11, 9, 7, 5, 3, 1, 0, 2,
  133731. 4, 6, 8, 10, 12,
  133732. };
  133733. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_1 = {
  133734. _vq_quantthresh__44c6_s_p9_1,
  133735. _vq_quantmap__44c6_s_p9_1,
  133736. 13,
  133737. 13
  133738. };
  133739. static static_codebook _44c6_s_p9_1 = {
  133740. 2, 169,
  133741. _vq_lengthlist__44c6_s_p9_1,
  133742. 1, -518889472, 1622704128, 4, 0,
  133743. _vq_quantlist__44c6_s_p9_1,
  133744. NULL,
  133745. &_vq_auxt__44c6_s_p9_1,
  133746. NULL,
  133747. 0
  133748. };
  133749. static long _vq_quantlist__44c6_s_p9_2[] = {
  133750. 24,
  133751. 23,
  133752. 25,
  133753. 22,
  133754. 26,
  133755. 21,
  133756. 27,
  133757. 20,
  133758. 28,
  133759. 19,
  133760. 29,
  133761. 18,
  133762. 30,
  133763. 17,
  133764. 31,
  133765. 16,
  133766. 32,
  133767. 15,
  133768. 33,
  133769. 14,
  133770. 34,
  133771. 13,
  133772. 35,
  133773. 12,
  133774. 36,
  133775. 11,
  133776. 37,
  133777. 10,
  133778. 38,
  133779. 9,
  133780. 39,
  133781. 8,
  133782. 40,
  133783. 7,
  133784. 41,
  133785. 6,
  133786. 42,
  133787. 5,
  133788. 43,
  133789. 4,
  133790. 44,
  133791. 3,
  133792. 45,
  133793. 2,
  133794. 46,
  133795. 1,
  133796. 47,
  133797. 0,
  133798. 48,
  133799. };
  133800. static long _vq_lengthlist__44c6_s_p9_2[] = {
  133801. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  133802. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133803. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  133804. 7,
  133805. };
  133806. static float _vq_quantthresh__44c6_s_p9_2[] = {
  133807. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  133808. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  133809. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  133810. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  133811. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  133812. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  133813. };
  133814. static long _vq_quantmap__44c6_s_p9_2[] = {
  133815. 47, 45, 43, 41, 39, 37, 35, 33,
  133816. 31, 29, 27, 25, 23, 21, 19, 17,
  133817. 15, 13, 11, 9, 7, 5, 3, 1,
  133818. 0, 2, 4, 6, 8, 10, 12, 14,
  133819. 16, 18, 20, 22, 24, 26, 28, 30,
  133820. 32, 34, 36, 38, 40, 42, 44, 46,
  133821. 48,
  133822. };
  133823. static encode_aux_threshmatch _vq_auxt__44c6_s_p9_2 = {
  133824. _vq_quantthresh__44c6_s_p9_2,
  133825. _vq_quantmap__44c6_s_p9_2,
  133826. 49,
  133827. 49
  133828. };
  133829. static static_codebook _44c6_s_p9_2 = {
  133830. 1, 49,
  133831. _vq_lengthlist__44c6_s_p9_2,
  133832. 1, -526909440, 1611661312, 6, 0,
  133833. _vq_quantlist__44c6_s_p9_2,
  133834. NULL,
  133835. &_vq_auxt__44c6_s_p9_2,
  133836. NULL,
  133837. 0
  133838. };
  133839. static long _huff_lengthlist__44c6_s_short[] = {
  133840. 3, 9,11,11,13,14,19,17,17,19, 5, 4, 5, 8,10,10,
  133841. 13,16,18,19, 7, 4, 4, 5, 8, 9,12,14,17,19, 8, 6,
  133842. 5, 5, 7, 7,10,13,16,18,10, 8, 7, 6, 5, 5, 8,11,
  133843. 17,19,11, 9, 7, 7, 5, 4, 5, 8,17,19,13,11, 8, 7,
  133844. 7, 5, 5, 7,16,18,14,13, 8, 6, 6, 5, 5, 7,16,18,
  133845. 18,16,10, 8, 8, 7, 7, 9,16,18,18,18,12,10,10, 9,
  133846. 9,10,17,18,
  133847. };
  133848. static static_codebook _huff_book__44c6_s_short = {
  133849. 2, 100,
  133850. _huff_lengthlist__44c6_s_short,
  133851. 0, 0, 0, 0, 0,
  133852. NULL,
  133853. NULL,
  133854. NULL,
  133855. NULL,
  133856. 0
  133857. };
  133858. static long _huff_lengthlist__44c7_s_long[] = {
  133859. 3, 8,11,13,15,14,14,13,15,14, 6, 4, 5, 7, 9,10,
  133860. 11,11,14,13,10, 4, 3, 5, 7, 8, 9,10,13,13,12, 7,
  133861. 4, 4, 5, 6, 8, 9,12,14,13, 9, 6, 5, 5, 6, 8, 9,
  133862. 12,14,12, 9, 7, 6, 5, 5, 6, 8,11,11,12,11, 9, 8,
  133863. 7, 6, 6, 7,10,11,13,11,10, 9, 8, 7, 6, 6, 9,11,
  133864. 13,13,12,12,12,10, 9, 8, 9,11,12,14,15,15,14,12,
  133865. 11,10,10,12,
  133866. };
  133867. static static_codebook _huff_book__44c7_s_long = {
  133868. 2, 100,
  133869. _huff_lengthlist__44c7_s_long,
  133870. 0, 0, 0, 0, 0,
  133871. NULL,
  133872. NULL,
  133873. NULL,
  133874. NULL,
  133875. 0
  133876. };
  133877. static long _vq_quantlist__44c7_s_p1_0[] = {
  133878. 1,
  133879. 0,
  133880. 2,
  133881. };
  133882. static long _vq_lengthlist__44c7_s_p1_0[] = {
  133883. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 8, 7, 0, 9, 9, 0,
  133884. 9, 8, 5, 7, 8, 0, 9, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  133885. 0, 0, 0, 0, 5, 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  133886. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  133887. 9, 9, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  133888. 8,
  133889. };
  133890. static float _vq_quantthresh__44c7_s_p1_0[] = {
  133891. -0.5, 0.5,
  133892. };
  133893. static long _vq_quantmap__44c7_s_p1_0[] = {
  133894. 1, 0, 2,
  133895. };
  133896. static encode_aux_threshmatch _vq_auxt__44c7_s_p1_0 = {
  133897. _vq_quantthresh__44c7_s_p1_0,
  133898. _vq_quantmap__44c7_s_p1_0,
  133899. 3,
  133900. 3
  133901. };
  133902. static static_codebook _44c7_s_p1_0 = {
  133903. 4, 81,
  133904. _vq_lengthlist__44c7_s_p1_0,
  133905. 1, -535822336, 1611661312, 2, 0,
  133906. _vq_quantlist__44c7_s_p1_0,
  133907. NULL,
  133908. &_vq_auxt__44c7_s_p1_0,
  133909. NULL,
  133910. 0
  133911. };
  133912. static long _vq_quantlist__44c7_s_p2_0[] = {
  133913. 2,
  133914. 1,
  133915. 3,
  133916. 0,
  133917. 4,
  133918. };
  133919. static long _vq_lengthlist__44c7_s_p2_0[] = {
  133920. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  133921. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  133922. 8,10,10, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  133923. 11,11, 5, 7, 7, 9, 9, 0, 8, 8,10,10, 0, 7, 8, 9,
  133924. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  133925. 0,11,11,12,12, 0,11,10,12,12, 0,13,14,14,14, 0,
  133926. 0, 0,14,13, 8, 9, 9,10,11, 0,11,11,12,12, 0,10,
  133927. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  133928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133929. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  133930. 0, 7, 7,10,10, 0, 9, 9,11,10, 0, 0, 0,11,11, 5,
  133931. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  133932. 9,10,11, 0, 0, 0,11,11, 8,10, 9,12,12, 0,10,10,
  133933. 12,12, 0,10,10,12,12, 0,12,12,13,13, 0, 0, 0,13,
  133934. 13, 8, 9,10,12,12, 0,10,10,12,12, 0,10,10,11,12,
  133935. 0,12,12,13,13, 0, 0, 0,13,13, 0, 0, 0, 0, 0, 0,
  133936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133937. 0, 0, 0, 5, 8, 8,11,11, 0, 7, 7,10,10, 0, 7, 7,
  133938. 10,10, 0, 9, 9,10,11, 0, 0, 0,11,10, 5, 8, 8,10,
  133939. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,11,10,
  133940. 0, 0, 0,10,11, 9,10,10,12,12, 0,10,10,12,12, 0,
  133941. 10,10,12,12, 0,12,13,13,13, 0, 0, 0,13,12, 9,10,
  133942. 10,12,12, 0,10,10,12,12, 0,10,10,12,12, 0,13,12,
  133943. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133945. 7,10,10,14,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  133946. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,14, 0, 9,
  133947. 9,12,13, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  133948. 12,12, 9,11,11,14,13, 0,11,10,13,12, 0,11,11,13,
  133949. 13, 0,12,12,13,13, 0, 0, 0,13,13, 9,11,11,13,14,
  133950. 0,10,11,12,13, 0,11,11,13,13, 0,12,12,13,13, 0,
  133951. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  133955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  133956. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,12,
  133957. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  133958. 13,13, 0,10,11,13,13, 0,12,12,14,13, 0, 0, 0,13,
  133959. 13,
  133960. };
  133961. static float _vq_quantthresh__44c7_s_p2_0[] = {
  133962. -1.5, -0.5, 0.5, 1.5,
  133963. };
  133964. static long _vq_quantmap__44c7_s_p2_0[] = {
  133965. 3, 1, 0, 2, 4,
  133966. };
  133967. static encode_aux_threshmatch _vq_auxt__44c7_s_p2_0 = {
  133968. _vq_quantthresh__44c7_s_p2_0,
  133969. _vq_quantmap__44c7_s_p2_0,
  133970. 5,
  133971. 5
  133972. };
  133973. static static_codebook _44c7_s_p2_0 = {
  133974. 4, 625,
  133975. _vq_lengthlist__44c7_s_p2_0,
  133976. 1, -533725184, 1611661312, 3, 0,
  133977. _vq_quantlist__44c7_s_p2_0,
  133978. NULL,
  133979. &_vq_auxt__44c7_s_p2_0,
  133980. NULL,
  133981. 0
  133982. };
  133983. static long _vq_quantlist__44c7_s_p3_0[] = {
  133984. 4,
  133985. 3,
  133986. 5,
  133987. 2,
  133988. 6,
  133989. 1,
  133990. 7,
  133991. 0,
  133992. 8,
  133993. };
  133994. static long _vq_lengthlist__44c7_s_p3_0[] = {
  133995. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  133996. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  133997. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  133998. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  133999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134000. 0,
  134001. };
  134002. static float _vq_quantthresh__44c7_s_p3_0[] = {
  134003. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134004. };
  134005. static long _vq_quantmap__44c7_s_p3_0[] = {
  134006. 7, 5, 3, 1, 0, 2, 4, 6,
  134007. 8,
  134008. };
  134009. static encode_aux_threshmatch _vq_auxt__44c7_s_p3_0 = {
  134010. _vq_quantthresh__44c7_s_p3_0,
  134011. _vq_quantmap__44c7_s_p3_0,
  134012. 9,
  134013. 9
  134014. };
  134015. static static_codebook _44c7_s_p3_0 = {
  134016. 2, 81,
  134017. _vq_lengthlist__44c7_s_p3_0,
  134018. 1, -531628032, 1611661312, 4, 0,
  134019. _vq_quantlist__44c7_s_p3_0,
  134020. NULL,
  134021. &_vq_auxt__44c7_s_p3_0,
  134022. NULL,
  134023. 0
  134024. };
  134025. static long _vq_quantlist__44c7_s_p4_0[] = {
  134026. 8,
  134027. 7,
  134028. 9,
  134029. 6,
  134030. 10,
  134031. 5,
  134032. 11,
  134033. 4,
  134034. 12,
  134035. 3,
  134036. 13,
  134037. 2,
  134038. 14,
  134039. 1,
  134040. 15,
  134041. 0,
  134042. 16,
  134043. };
  134044. static long _vq_lengthlist__44c7_s_p4_0[] = {
  134045. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134046. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  134047. 12,12, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134048. 11,12,12, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,
  134049. 11,12,12,12, 0, 0, 0, 6, 6, 8, 7, 9, 9, 9, 9,10,
  134050. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134051. 11,11,12,12,13,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134052. 10,11,11,12,12,12,13, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134053. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134054. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134063. 0,
  134064. };
  134065. static float _vq_quantthresh__44c7_s_p4_0[] = {
  134066. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134067. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134068. };
  134069. static long _vq_quantmap__44c7_s_p4_0[] = {
  134070. 15, 13, 11, 9, 7, 5, 3, 1,
  134071. 0, 2, 4, 6, 8, 10, 12, 14,
  134072. 16,
  134073. };
  134074. static encode_aux_threshmatch _vq_auxt__44c7_s_p4_0 = {
  134075. _vq_quantthresh__44c7_s_p4_0,
  134076. _vq_quantmap__44c7_s_p4_0,
  134077. 17,
  134078. 17
  134079. };
  134080. static static_codebook _44c7_s_p4_0 = {
  134081. 2, 289,
  134082. _vq_lengthlist__44c7_s_p4_0,
  134083. 1, -529530880, 1611661312, 5, 0,
  134084. _vq_quantlist__44c7_s_p4_0,
  134085. NULL,
  134086. &_vq_auxt__44c7_s_p4_0,
  134087. NULL,
  134088. 0
  134089. };
  134090. static long _vq_quantlist__44c7_s_p5_0[] = {
  134091. 1,
  134092. 0,
  134093. 2,
  134094. };
  134095. static long _vq_lengthlist__44c7_s_p5_0[] = {
  134096. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 6, 7,10,10,10,10,
  134097. 10, 9, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134098. 12,10,11,12, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134099. 11,12,12,12,12,12, 6,10,10,10,12,12,11,12,12, 7,
  134100. 10,10,12,12,12,12,11,12, 7,10,10,11,12,12,12,12,
  134101. 12,
  134102. };
  134103. static float _vq_quantthresh__44c7_s_p5_0[] = {
  134104. -5.5, 5.5,
  134105. };
  134106. static long _vq_quantmap__44c7_s_p5_0[] = {
  134107. 1, 0, 2,
  134108. };
  134109. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_0 = {
  134110. _vq_quantthresh__44c7_s_p5_0,
  134111. _vq_quantmap__44c7_s_p5_0,
  134112. 3,
  134113. 3
  134114. };
  134115. static static_codebook _44c7_s_p5_0 = {
  134116. 4, 81,
  134117. _vq_lengthlist__44c7_s_p5_0,
  134118. 1, -529137664, 1618345984, 2, 0,
  134119. _vq_quantlist__44c7_s_p5_0,
  134120. NULL,
  134121. &_vq_auxt__44c7_s_p5_0,
  134122. NULL,
  134123. 0
  134124. };
  134125. static long _vq_quantlist__44c7_s_p5_1[] = {
  134126. 5,
  134127. 4,
  134128. 6,
  134129. 3,
  134130. 7,
  134131. 2,
  134132. 8,
  134133. 1,
  134134. 9,
  134135. 0,
  134136. 10,
  134137. };
  134138. static long _vq_lengthlist__44c7_s_p5_1[] = {
  134139. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 4, 6, 6,
  134140. 7, 7, 8, 8, 9, 9,11, 4, 4, 6, 6, 7, 7, 8, 8, 9,
  134141. 9,12, 5, 5, 6, 6, 7, 7, 9, 9, 9, 9,12,12,12, 6,
  134142. 6, 7, 7, 9, 9, 9, 9,11,11,11, 7, 7, 7, 7, 8, 8,
  134143. 9, 9,11,11,11, 7, 7, 7, 7, 8, 8, 9, 9,11,11,11,
  134144. 7, 7, 8, 8, 8, 8, 9, 9,11,11,11,11,11, 8, 8, 8,
  134145. 8, 8, 9,11,11,11,11,11, 8, 8, 8, 8, 8, 8,11,11,
  134146. 11,11,11, 7, 7, 8, 8, 8, 8,
  134147. };
  134148. static float _vq_quantthresh__44c7_s_p5_1[] = {
  134149. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134150. 3.5, 4.5,
  134151. };
  134152. static long _vq_quantmap__44c7_s_p5_1[] = {
  134153. 9, 7, 5, 3, 1, 0, 2, 4,
  134154. 6, 8, 10,
  134155. };
  134156. static encode_aux_threshmatch _vq_auxt__44c7_s_p5_1 = {
  134157. _vq_quantthresh__44c7_s_p5_1,
  134158. _vq_quantmap__44c7_s_p5_1,
  134159. 11,
  134160. 11
  134161. };
  134162. static static_codebook _44c7_s_p5_1 = {
  134163. 2, 121,
  134164. _vq_lengthlist__44c7_s_p5_1,
  134165. 1, -531365888, 1611661312, 4, 0,
  134166. _vq_quantlist__44c7_s_p5_1,
  134167. NULL,
  134168. &_vq_auxt__44c7_s_p5_1,
  134169. NULL,
  134170. 0
  134171. };
  134172. static long _vq_quantlist__44c7_s_p6_0[] = {
  134173. 6,
  134174. 5,
  134175. 7,
  134176. 4,
  134177. 8,
  134178. 3,
  134179. 9,
  134180. 2,
  134181. 10,
  134182. 1,
  134183. 11,
  134184. 0,
  134185. 12,
  134186. };
  134187. static long _vq_lengthlist__44c7_s_p6_0[] = {
  134188. 1, 4, 4, 6, 6, 7, 7, 8, 7, 9, 8,10,10, 6, 5, 5,
  134189. 7, 7, 8, 8, 9, 9, 9,10,11,11, 7, 5, 5, 7, 7, 8,
  134190. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 8, 9, 9,
  134191. 10,10,11,11, 0, 8, 8, 7, 7, 8, 9, 9, 9,10,10,11,
  134192. 11, 0,11,11, 9, 9,10,10,11,10,11,11,12,12, 0,12,
  134193. 12, 9, 9,10,10,11,11,11,11,12,12, 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,
  134199. };
  134200. static float _vq_quantthresh__44c7_s_p6_0[] = {
  134201. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  134202. 12.5, 17.5, 22.5, 27.5,
  134203. };
  134204. static long _vq_quantmap__44c7_s_p6_0[] = {
  134205. 11, 9, 7, 5, 3, 1, 0, 2,
  134206. 4, 6, 8, 10, 12,
  134207. };
  134208. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_0 = {
  134209. _vq_quantthresh__44c7_s_p6_0,
  134210. _vq_quantmap__44c7_s_p6_0,
  134211. 13,
  134212. 13
  134213. };
  134214. static static_codebook _44c7_s_p6_0 = {
  134215. 2, 169,
  134216. _vq_lengthlist__44c7_s_p6_0,
  134217. 1, -526516224, 1616117760, 4, 0,
  134218. _vq_quantlist__44c7_s_p6_0,
  134219. NULL,
  134220. &_vq_auxt__44c7_s_p6_0,
  134221. NULL,
  134222. 0
  134223. };
  134224. static long _vq_quantlist__44c7_s_p6_1[] = {
  134225. 2,
  134226. 1,
  134227. 3,
  134228. 0,
  134229. 4,
  134230. };
  134231. static long _vq_lengthlist__44c7_s_p6_1[] = {
  134232. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  134233. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  134234. };
  134235. static float _vq_quantthresh__44c7_s_p6_1[] = {
  134236. -1.5, -0.5, 0.5, 1.5,
  134237. };
  134238. static long _vq_quantmap__44c7_s_p6_1[] = {
  134239. 3, 1, 0, 2, 4,
  134240. };
  134241. static encode_aux_threshmatch _vq_auxt__44c7_s_p6_1 = {
  134242. _vq_quantthresh__44c7_s_p6_1,
  134243. _vq_quantmap__44c7_s_p6_1,
  134244. 5,
  134245. 5
  134246. };
  134247. static static_codebook _44c7_s_p6_1 = {
  134248. 2, 25,
  134249. _vq_lengthlist__44c7_s_p6_1,
  134250. 1, -533725184, 1611661312, 3, 0,
  134251. _vq_quantlist__44c7_s_p6_1,
  134252. NULL,
  134253. &_vq_auxt__44c7_s_p6_1,
  134254. NULL,
  134255. 0
  134256. };
  134257. static long _vq_quantlist__44c7_s_p7_0[] = {
  134258. 6,
  134259. 5,
  134260. 7,
  134261. 4,
  134262. 8,
  134263. 3,
  134264. 9,
  134265. 2,
  134266. 10,
  134267. 1,
  134268. 11,
  134269. 0,
  134270. 12,
  134271. };
  134272. static long _vq_lengthlist__44c7_s_p7_0[] = {
  134273. 1, 4, 4, 6, 6, 7, 8, 9, 9,10,10,12,11, 6, 5, 5,
  134274. 7, 7, 8, 8, 9,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  134275. 8,10,10,11,11,12,12,20, 7, 7, 7, 7, 8, 9,10,10,
  134276. 11,11,12,13,20, 7, 7, 7, 7, 9, 9,10,10,11,12,13,
  134277. 13,20,11,11, 8, 8, 9, 9,11,11,12,12,13,13,20,11,
  134278. 11, 8, 8, 9, 9,11,11,12,12,13,13,20,20,20,10,10,
  134279. 10,10,12,12,13,13,13,13,20,20,20,10,10,10,10,12,
  134280. 12,13,13,13,14,20,20,20,14,14,11,11,12,12,13,13,
  134281. 14,14,20,20,20,14,14,11,11,12,12,13,13,14,14,20,
  134282. 20,20,20,19,13,13,13,13,14,14,15,14,19,19,19,19,
  134283. 19,13,13,13,13,14,14,15,15,
  134284. };
  134285. static float _vq_quantthresh__44c7_s_p7_0[] = {
  134286. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  134287. 27.5, 38.5, 49.5, 60.5,
  134288. };
  134289. static long _vq_quantmap__44c7_s_p7_0[] = {
  134290. 11, 9, 7, 5, 3, 1, 0, 2,
  134291. 4, 6, 8, 10, 12,
  134292. };
  134293. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_0 = {
  134294. _vq_quantthresh__44c7_s_p7_0,
  134295. _vq_quantmap__44c7_s_p7_0,
  134296. 13,
  134297. 13
  134298. };
  134299. static static_codebook _44c7_s_p7_0 = {
  134300. 2, 169,
  134301. _vq_lengthlist__44c7_s_p7_0,
  134302. 1, -523206656, 1618345984, 4, 0,
  134303. _vq_quantlist__44c7_s_p7_0,
  134304. NULL,
  134305. &_vq_auxt__44c7_s_p7_0,
  134306. NULL,
  134307. 0
  134308. };
  134309. static long _vq_quantlist__44c7_s_p7_1[] = {
  134310. 5,
  134311. 4,
  134312. 6,
  134313. 3,
  134314. 7,
  134315. 2,
  134316. 8,
  134317. 1,
  134318. 9,
  134319. 0,
  134320. 10,
  134321. };
  134322. static long _vq_lengthlist__44c7_s_p7_1[] = {
  134323. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 7, 7,
  134324. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  134325. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  134326. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134327. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  134328. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  134329. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  134330. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  134331. };
  134332. static float _vq_quantthresh__44c7_s_p7_1[] = {
  134333. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134334. 3.5, 4.5,
  134335. };
  134336. static long _vq_quantmap__44c7_s_p7_1[] = {
  134337. 9, 7, 5, 3, 1, 0, 2, 4,
  134338. 6, 8, 10,
  134339. };
  134340. static encode_aux_threshmatch _vq_auxt__44c7_s_p7_1 = {
  134341. _vq_quantthresh__44c7_s_p7_1,
  134342. _vq_quantmap__44c7_s_p7_1,
  134343. 11,
  134344. 11
  134345. };
  134346. static static_codebook _44c7_s_p7_1 = {
  134347. 2, 121,
  134348. _vq_lengthlist__44c7_s_p7_1,
  134349. 1, -531365888, 1611661312, 4, 0,
  134350. _vq_quantlist__44c7_s_p7_1,
  134351. NULL,
  134352. &_vq_auxt__44c7_s_p7_1,
  134353. NULL,
  134354. 0
  134355. };
  134356. static long _vq_quantlist__44c7_s_p8_0[] = {
  134357. 7,
  134358. 6,
  134359. 8,
  134360. 5,
  134361. 9,
  134362. 4,
  134363. 10,
  134364. 3,
  134365. 11,
  134366. 2,
  134367. 12,
  134368. 1,
  134369. 13,
  134370. 0,
  134371. 14,
  134372. };
  134373. static long _vq_lengthlist__44c7_s_p8_0[] = {
  134374. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8, 9, 9,10,10, 6,
  134375. 5, 5, 7, 7, 9, 9, 8, 8,10, 9,11,10,12,11, 6, 5,
  134376. 5, 8, 7, 9, 9, 8, 8,10,10,11,11,12,11,19, 8, 8,
  134377. 8, 8,10,10, 9, 9,10,10,11,11,12,11,19, 8, 8, 8,
  134378. 8,10,10, 9, 9,10,10,11,11,12,12,19,12,12, 9, 9,
  134379. 10,10, 9,10,10,10,11,11,12,12,19,12,12, 9, 9,10,
  134380. 10,10,10,10,10,12,12,12,12,19,19,19, 9, 9, 9, 9,
  134381. 11,10,11,11,12,11,13,13,19,19,19, 9, 9, 9, 9,11,
  134382. 10,11,11,11,12,13,13,19,19,19,13,13,10,10,11,11,
  134383. 12,12,12,12,13,12,19,19,19,14,13,10,10,11,11,12,
  134384. 12,12,13,13,13,19,19,19,19,19,12,12,12,11,12,13,
  134385. 14,13,13,13,19,19,19,19,19,12,12,12,11,12,12,13,
  134386. 14,13,14,19,19,19,19,19,16,16,12,13,12,13,13,14,
  134387. 15,14,19,18,18,18,18,16,15,12,11,12,11,14,12,14,
  134388. 14,
  134389. };
  134390. static float _vq_quantthresh__44c7_s_p8_0[] = {
  134391. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  134392. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  134393. };
  134394. static long _vq_quantmap__44c7_s_p8_0[] = {
  134395. 13, 11, 9, 7, 5, 3, 1, 0,
  134396. 2, 4, 6, 8, 10, 12, 14,
  134397. };
  134398. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_0 = {
  134399. _vq_quantthresh__44c7_s_p8_0,
  134400. _vq_quantmap__44c7_s_p8_0,
  134401. 15,
  134402. 15
  134403. };
  134404. static static_codebook _44c7_s_p8_0 = {
  134405. 2, 225,
  134406. _vq_lengthlist__44c7_s_p8_0,
  134407. 1, -520986624, 1620377600, 4, 0,
  134408. _vq_quantlist__44c7_s_p8_0,
  134409. NULL,
  134410. &_vq_auxt__44c7_s_p8_0,
  134411. NULL,
  134412. 0
  134413. };
  134414. static long _vq_quantlist__44c7_s_p8_1[] = {
  134415. 10,
  134416. 9,
  134417. 11,
  134418. 8,
  134419. 12,
  134420. 7,
  134421. 13,
  134422. 6,
  134423. 14,
  134424. 5,
  134425. 15,
  134426. 4,
  134427. 16,
  134428. 3,
  134429. 17,
  134430. 2,
  134431. 18,
  134432. 1,
  134433. 19,
  134434. 0,
  134435. 20,
  134436. };
  134437. static long _vq_lengthlist__44c7_s_p8_1[] = {
  134438. 3, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  134439. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  134440. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  134441. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  134442. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134443. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  134444. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  134445. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  134446. 10, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134447. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  134448. 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,10,10, 9, 9, 9,
  134449. 9, 9, 9, 9, 9, 9, 9,10, 9, 9,10, 9, 9,10,11,10,
  134450. 11,10, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9, 9,
  134451. 9, 9,11,10,11,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,
  134452. 10, 9, 9,10, 9, 9,10,11,10,10,11,10, 9, 9, 9, 9,
  134453. 9,10,10, 9,10,10,10,10, 9,10,10,10,10,10,10,11,
  134454. 11,11,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  134455. 10,10,10,11,11,10,10,10,10,10,10,10,10,10,10,10,
  134456. 10, 9,10,10, 9,10,11,11,10,11,10,11,10, 9,10,10,
  134457. 9,10,10,10,10,10,10,10,10,10,10,11,11,11,11,10,
  134458. 11,11,10,10,10,10,10,10, 9,10, 9,10,10, 9,10, 9,
  134459. 10,10,10,11,10,11,10,11,11,10,10,10,10,10,10, 9,
  134460. 10,10,10,10,10,10,10,11,10,10,10,10,10,10,10,10,
  134461. 10,10,10,10,10,10,10,10,10,10,10,10,10,11,10,11,
  134462. 11,10,10,10,10, 9, 9,10,10, 9, 9,10, 9,10,10,10,
  134463. 10,11,11,10,10,10,10,10,10,10, 9, 9,10,10,10, 9,
  134464. 9,10,10,10,10,10,11,10,11,10,10,10,10,10,10, 9,
  134465. 10,10,10,10,10,10,10,10,10,
  134466. };
  134467. static float _vq_quantthresh__44c7_s_p8_1[] = {
  134468. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  134469. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  134470. 6.5, 7.5, 8.5, 9.5,
  134471. };
  134472. static long _vq_quantmap__44c7_s_p8_1[] = {
  134473. 19, 17, 15, 13, 11, 9, 7, 5,
  134474. 3, 1, 0, 2, 4, 6, 8, 10,
  134475. 12, 14, 16, 18, 20,
  134476. };
  134477. static encode_aux_threshmatch _vq_auxt__44c7_s_p8_1 = {
  134478. _vq_quantthresh__44c7_s_p8_1,
  134479. _vq_quantmap__44c7_s_p8_1,
  134480. 21,
  134481. 21
  134482. };
  134483. static static_codebook _44c7_s_p8_1 = {
  134484. 2, 441,
  134485. _vq_lengthlist__44c7_s_p8_1,
  134486. 1, -529268736, 1611661312, 5, 0,
  134487. _vq_quantlist__44c7_s_p8_1,
  134488. NULL,
  134489. &_vq_auxt__44c7_s_p8_1,
  134490. NULL,
  134491. 0
  134492. };
  134493. static long _vq_quantlist__44c7_s_p9_0[] = {
  134494. 6,
  134495. 5,
  134496. 7,
  134497. 4,
  134498. 8,
  134499. 3,
  134500. 9,
  134501. 2,
  134502. 10,
  134503. 1,
  134504. 11,
  134505. 0,
  134506. 12,
  134507. };
  134508. static long _vq_lengthlist__44c7_s_p9_0[] = {
  134509. 1, 3, 3,11,11,11,11,11,11,11,11,11,11, 4, 6, 6,
  134510. 11,11,11,11,11,11,11,11,11,11, 4, 7, 7,11,11,11,
  134511. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134512. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134513. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134514. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134515. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134516. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134517. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134518. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  134519. 11,11,11,11,11,11,11,11,11,
  134520. };
  134521. static float _vq_quantthresh__44c7_s_p9_0[] = {
  134522. -3503.5, -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5,
  134523. 1592.5, 2229.5, 2866.5, 3503.5,
  134524. };
  134525. static long _vq_quantmap__44c7_s_p9_0[] = {
  134526. 11, 9, 7, 5, 3, 1, 0, 2,
  134527. 4, 6, 8, 10, 12,
  134528. };
  134529. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_0 = {
  134530. _vq_quantthresh__44c7_s_p9_0,
  134531. _vq_quantmap__44c7_s_p9_0,
  134532. 13,
  134533. 13
  134534. };
  134535. static static_codebook _44c7_s_p9_0 = {
  134536. 2, 169,
  134537. _vq_lengthlist__44c7_s_p9_0,
  134538. 1, -511845376, 1630791680, 4, 0,
  134539. _vq_quantlist__44c7_s_p9_0,
  134540. NULL,
  134541. &_vq_auxt__44c7_s_p9_0,
  134542. NULL,
  134543. 0
  134544. };
  134545. static long _vq_quantlist__44c7_s_p9_1[] = {
  134546. 6,
  134547. 5,
  134548. 7,
  134549. 4,
  134550. 8,
  134551. 3,
  134552. 9,
  134553. 2,
  134554. 10,
  134555. 1,
  134556. 11,
  134557. 0,
  134558. 12,
  134559. };
  134560. static long _vq_lengthlist__44c7_s_p9_1[] = {
  134561. 1, 4, 4, 7, 7, 7, 7, 7, 6, 8, 8, 8, 8, 6, 6, 6,
  134562. 8, 8, 9, 8, 8, 7, 9, 8,11,10, 5, 6, 6, 8, 8, 9,
  134563. 8, 8, 8,10, 9,11,11,16, 8, 8, 9, 8, 9, 9, 9, 8,
  134564. 10, 9,11,10,16, 8, 8, 9, 9,10,10, 9, 9,10,10,11,
  134565. 11,16,13,13, 9, 9,10,10, 9,10,11,11,12,11,16,13,
  134566. 13, 9, 8,10, 9,10,10,10,10,11,11,16,14,16, 8, 9,
  134567. 9, 9,11,10,11,11,12,11,16,16,16, 9, 7,10, 7,11,
  134568. 10,11,11,12,11,16,16,16,12,12, 9,10,11,11,12,11,
  134569. 12,12,16,16,16,12,10,10, 7,11, 8,12,11,12,12,16,
  134570. 16,15,16,16,11,12,10,10,12,11,12,12,16,16,16,15,
  134571. 15,11,11,10,10,12,12,12,12,
  134572. };
  134573. static float _vq_quantthresh__44c7_s_p9_1[] = {
  134574. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  134575. 122.5, 171.5, 220.5, 269.5,
  134576. };
  134577. static long _vq_quantmap__44c7_s_p9_1[] = {
  134578. 11, 9, 7, 5, 3, 1, 0, 2,
  134579. 4, 6, 8, 10, 12,
  134580. };
  134581. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_1 = {
  134582. _vq_quantthresh__44c7_s_p9_1,
  134583. _vq_quantmap__44c7_s_p9_1,
  134584. 13,
  134585. 13
  134586. };
  134587. static static_codebook _44c7_s_p9_1 = {
  134588. 2, 169,
  134589. _vq_lengthlist__44c7_s_p9_1,
  134590. 1, -518889472, 1622704128, 4, 0,
  134591. _vq_quantlist__44c7_s_p9_1,
  134592. NULL,
  134593. &_vq_auxt__44c7_s_p9_1,
  134594. NULL,
  134595. 0
  134596. };
  134597. static long _vq_quantlist__44c7_s_p9_2[] = {
  134598. 24,
  134599. 23,
  134600. 25,
  134601. 22,
  134602. 26,
  134603. 21,
  134604. 27,
  134605. 20,
  134606. 28,
  134607. 19,
  134608. 29,
  134609. 18,
  134610. 30,
  134611. 17,
  134612. 31,
  134613. 16,
  134614. 32,
  134615. 15,
  134616. 33,
  134617. 14,
  134618. 34,
  134619. 13,
  134620. 35,
  134621. 12,
  134622. 36,
  134623. 11,
  134624. 37,
  134625. 10,
  134626. 38,
  134627. 9,
  134628. 39,
  134629. 8,
  134630. 40,
  134631. 7,
  134632. 41,
  134633. 6,
  134634. 42,
  134635. 5,
  134636. 43,
  134637. 4,
  134638. 44,
  134639. 3,
  134640. 45,
  134641. 2,
  134642. 46,
  134643. 1,
  134644. 47,
  134645. 0,
  134646. 48,
  134647. };
  134648. static long _vq_lengthlist__44c7_s_p9_2[] = {
  134649. 2, 4, 3, 4, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6,
  134650. 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134651. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  134652. 7,
  134653. };
  134654. static float _vq_quantthresh__44c7_s_p9_2[] = {
  134655. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  134656. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  134657. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134658. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134659. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  134660. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  134661. };
  134662. static long _vq_quantmap__44c7_s_p9_2[] = {
  134663. 47, 45, 43, 41, 39, 37, 35, 33,
  134664. 31, 29, 27, 25, 23, 21, 19, 17,
  134665. 15, 13, 11, 9, 7, 5, 3, 1,
  134666. 0, 2, 4, 6, 8, 10, 12, 14,
  134667. 16, 18, 20, 22, 24, 26, 28, 30,
  134668. 32, 34, 36, 38, 40, 42, 44, 46,
  134669. 48,
  134670. };
  134671. static encode_aux_threshmatch _vq_auxt__44c7_s_p9_2 = {
  134672. _vq_quantthresh__44c7_s_p9_2,
  134673. _vq_quantmap__44c7_s_p9_2,
  134674. 49,
  134675. 49
  134676. };
  134677. static static_codebook _44c7_s_p9_2 = {
  134678. 1, 49,
  134679. _vq_lengthlist__44c7_s_p9_2,
  134680. 1, -526909440, 1611661312, 6, 0,
  134681. _vq_quantlist__44c7_s_p9_2,
  134682. NULL,
  134683. &_vq_auxt__44c7_s_p9_2,
  134684. NULL,
  134685. 0
  134686. };
  134687. static long _huff_lengthlist__44c7_s_short[] = {
  134688. 4,11,12,14,15,15,17,17,18,18, 5, 6, 6, 8, 9,10,
  134689. 13,17,18,19, 7, 5, 4, 6, 8, 9,11,15,19,19, 8, 6,
  134690. 5, 5, 6, 7,11,14,16,17, 9, 7, 7, 6, 7, 7,10,13,
  134691. 15,19,10, 8, 7, 6, 7, 6, 7, 9,14,16,12,10, 9, 7,
  134692. 7, 6, 4, 5,10,15,14,13,11, 7, 6, 6, 4, 2, 7,13,
  134693. 16,16,15, 9, 8, 8, 8, 6, 9,13,19,19,17,12,11,10,
  134694. 10, 9,11,14,
  134695. };
  134696. static static_codebook _huff_book__44c7_s_short = {
  134697. 2, 100,
  134698. _huff_lengthlist__44c7_s_short,
  134699. 0, 0, 0, 0, 0,
  134700. NULL,
  134701. NULL,
  134702. NULL,
  134703. NULL,
  134704. 0
  134705. };
  134706. static long _huff_lengthlist__44c8_s_long[] = {
  134707. 3, 8,12,13,14,14,14,13,14,14, 6, 4, 5, 8,10,10,
  134708. 11,11,14,13, 9, 5, 4, 5, 7, 8, 9,10,13,13,12, 7,
  134709. 5, 4, 5, 6, 8, 9,12,13,13, 9, 6, 5, 5, 5, 7, 9,
  134710. 11,14,12,10, 7, 6, 5, 4, 6, 7,10,11,12,11, 9, 8,
  134711. 7, 5, 5, 6,10,10,13,12,10, 9, 8, 6, 6, 5, 8,10,
  134712. 14,13,12,12,11,10, 9, 7, 8,10,12,13,14,14,13,12,
  134713. 11, 9, 9,10,
  134714. };
  134715. static static_codebook _huff_book__44c8_s_long = {
  134716. 2, 100,
  134717. _huff_lengthlist__44c8_s_long,
  134718. 0, 0, 0, 0, 0,
  134719. NULL,
  134720. NULL,
  134721. NULL,
  134722. NULL,
  134723. 0
  134724. };
  134725. static long _vq_quantlist__44c8_s_p1_0[] = {
  134726. 1,
  134727. 0,
  134728. 2,
  134729. };
  134730. static long _vq_lengthlist__44c8_s_p1_0[] = {
  134731. 1, 5, 5, 0, 5, 5, 0, 5, 5, 5, 7, 7, 0, 9, 8, 0,
  134732. 9, 8, 6, 7, 7, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  134733. 0, 0, 0, 0, 5, 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9,
  134734. 0, 8, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  134735. 9, 8, 0, 8, 8, 0, 8, 8, 5, 8, 9, 0, 8, 8, 0, 8,
  134736. 8,
  134737. };
  134738. static float _vq_quantthresh__44c8_s_p1_0[] = {
  134739. -0.5, 0.5,
  134740. };
  134741. static long _vq_quantmap__44c8_s_p1_0[] = {
  134742. 1, 0, 2,
  134743. };
  134744. static encode_aux_threshmatch _vq_auxt__44c8_s_p1_0 = {
  134745. _vq_quantthresh__44c8_s_p1_0,
  134746. _vq_quantmap__44c8_s_p1_0,
  134747. 3,
  134748. 3
  134749. };
  134750. static static_codebook _44c8_s_p1_0 = {
  134751. 4, 81,
  134752. _vq_lengthlist__44c8_s_p1_0,
  134753. 1, -535822336, 1611661312, 2, 0,
  134754. _vq_quantlist__44c8_s_p1_0,
  134755. NULL,
  134756. &_vq_auxt__44c8_s_p1_0,
  134757. NULL,
  134758. 0
  134759. };
  134760. static long _vq_quantlist__44c8_s_p2_0[] = {
  134761. 2,
  134762. 1,
  134763. 3,
  134764. 0,
  134765. 4,
  134766. };
  134767. static long _vq_lengthlist__44c8_s_p2_0[] = {
  134768. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  134769. 7, 7, 9, 9, 0, 0, 0, 9, 9, 5, 7, 7, 9, 9, 0, 8,
  134770. 7,10, 9, 0, 8, 7,10, 9, 0,10,10,11,11, 0, 0, 0,
  134771. 11,11, 5, 7, 7, 9, 9, 0, 7, 8, 9,10, 0, 7, 8, 9,
  134772. 10, 0,10,10,11,11, 0, 0, 0,11,11, 8, 9, 9,11,10,
  134773. 0,11,10,12,11, 0,11,10,12,12, 0,13,13,14,14, 0,
  134774. 0, 0,14,13, 8, 9, 9,10,11, 0,10,11,12,12, 0,10,
  134775. 11,12,12, 0,13,13,14,14, 0, 0, 0,13,14, 0, 0, 0,
  134776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134777. 0, 0, 0, 0, 0, 0, 5, 8, 7,11,10, 0, 7, 7,10,10,
  134778. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,11,10, 5,
  134779. 7, 8,10,11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9,
  134780. 9,10,10, 0, 0, 0,10,10, 8,10, 9,12,12, 0,10,10,
  134781. 12,11, 0,10,10,12,12, 0,12,12,13,12, 0, 0, 0,13,
  134782. 12, 8, 9,10,12,12, 0,10,10,11,12, 0,10,10,11,12,
  134783. 0,12,12,13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0,
  134784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134785. 0, 0, 0, 6, 8, 7,11,10, 0, 7, 7,10,10, 0, 7, 7,
  134786. 10,10, 0, 9, 9,10,11, 0, 0, 0,10,10, 6, 7, 8,10,
  134787. 11, 0, 7, 7,10,10, 0, 7, 7,10,10, 0, 9, 9,10,10,
  134788. 0, 0, 0,10,10, 9,10, 9,12,12, 0,10,10,12,12, 0,
  134789. 10,10,12,11, 0,12,12,13,13, 0, 0, 0,13,12, 8, 9,
  134790. 10,12,12, 0,10,10,12,12, 0,10,10,11,12, 0,12,12,
  134791. 13,13, 0, 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134793. 7,10,10,13,13, 0, 9, 9,12,12, 0, 9, 9,12,12, 0,
  134794. 10,10,12,12, 0, 0, 0,12,12, 7,10,10,13,13, 0, 9,
  134795. 9,12,12, 0, 9, 9,12,12, 0,10,10,12,12, 0, 0, 0,
  134796. 12,12, 9,11,11,14,13, 0,10,10,13,12, 0,11,10,13,
  134797. 12, 0,12,12,13,12, 0, 0, 0,13,13, 9,11,11,13,14,
  134798. 0,10,11,12,13, 0,10,11,13,13, 0,12,12,12,13, 0,
  134799. 0, 0,13,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  134804. 11,11,14,14, 0,10,11,13,13, 0,11,10,13,13, 0,11,
  134805. 12,13,13, 0, 0, 0,13,12, 9,11,11,14,14, 0,11,10,
  134806. 13,13, 0,10,11,13,13, 0,12,12,13,13, 0, 0, 0,12,
  134807. 13,
  134808. };
  134809. static float _vq_quantthresh__44c8_s_p2_0[] = {
  134810. -1.5, -0.5, 0.5, 1.5,
  134811. };
  134812. static long _vq_quantmap__44c8_s_p2_0[] = {
  134813. 3, 1, 0, 2, 4,
  134814. };
  134815. static encode_aux_threshmatch _vq_auxt__44c8_s_p2_0 = {
  134816. _vq_quantthresh__44c8_s_p2_0,
  134817. _vq_quantmap__44c8_s_p2_0,
  134818. 5,
  134819. 5
  134820. };
  134821. static static_codebook _44c8_s_p2_0 = {
  134822. 4, 625,
  134823. _vq_lengthlist__44c8_s_p2_0,
  134824. 1, -533725184, 1611661312, 3, 0,
  134825. _vq_quantlist__44c8_s_p2_0,
  134826. NULL,
  134827. &_vq_auxt__44c8_s_p2_0,
  134828. NULL,
  134829. 0
  134830. };
  134831. static long _vq_quantlist__44c8_s_p3_0[] = {
  134832. 4,
  134833. 3,
  134834. 5,
  134835. 2,
  134836. 6,
  134837. 1,
  134838. 7,
  134839. 0,
  134840. 8,
  134841. };
  134842. static long _vq_lengthlist__44c8_s_p3_0[] = {
  134843. 2, 4, 4, 5, 5, 7, 7, 9, 9, 0, 4, 4, 6, 6, 7, 7,
  134844. 9, 9, 0, 4, 4, 6, 6, 7, 7, 9, 9, 0, 5, 5, 6, 6,
  134845. 8, 8,10,10, 0, 0, 0, 6, 6, 8, 8,10,10, 0, 0, 0,
  134846. 7, 7, 9, 9,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0,
  134847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134848. 0,
  134849. };
  134850. static float _vq_quantthresh__44c8_s_p3_0[] = {
  134851. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  134852. };
  134853. static long _vq_quantmap__44c8_s_p3_0[] = {
  134854. 7, 5, 3, 1, 0, 2, 4, 6,
  134855. 8,
  134856. };
  134857. static encode_aux_threshmatch _vq_auxt__44c8_s_p3_0 = {
  134858. _vq_quantthresh__44c8_s_p3_0,
  134859. _vq_quantmap__44c8_s_p3_0,
  134860. 9,
  134861. 9
  134862. };
  134863. static static_codebook _44c8_s_p3_0 = {
  134864. 2, 81,
  134865. _vq_lengthlist__44c8_s_p3_0,
  134866. 1, -531628032, 1611661312, 4, 0,
  134867. _vq_quantlist__44c8_s_p3_0,
  134868. NULL,
  134869. &_vq_auxt__44c8_s_p3_0,
  134870. NULL,
  134871. 0
  134872. };
  134873. static long _vq_quantlist__44c8_s_p4_0[] = {
  134874. 8,
  134875. 7,
  134876. 9,
  134877. 6,
  134878. 10,
  134879. 5,
  134880. 11,
  134881. 4,
  134882. 12,
  134883. 3,
  134884. 13,
  134885. 2,
  134886. 14,
  134887. 1,
  134888. 15,
  134889. 0,
  134890. 16,
  134891. };
  134892. static long _vq_lengthlist__44c8_s_p4_0[] = {
  134893. 3, 4, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  134894. 11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 8,10,10,11,11,
  134895. 11,11, 0, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  134896. 11,11,11, 0, 6, 5, 6, 6, 7, 7, 9, 9, 9, 9,10,10,
  134897. 11,11,12,12, 0, 0, 0, 6, 6, 7, 7, 9, 9, 9, 9,10,
  134898. 10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,
  134899. 11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,
  134900. 10,11,11,11,12,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  134901. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  134902. 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 0, 0,
  134903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  134911. 0,
  134912. };
  134913. static float _vq_quantthresh__44c8_s_p4_0[] = {
  134914. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  134915. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  134916. };
  134917. static long _vq_quantmap__44c8_s_p4_0[] = {
  134918. 15, 13, 11, 9, 7, 5, 3, 1,
  134919. 0, 2, 4, 6, 8, 10, 12, 14,
  134920. 16,
  134921. };
  134922. static encode_aux_threshmatch _vq_auxt__44c8_s_p4_0 = {
  134923. _vq_quantthresh__44c8_s_p4_0,
  134924. _vq_quantmap__44c8_s_p4_0,
  134925. 17,
  134926. 17
  134927. };
  134928. static static_codebook _44c8_s_p4_0 = {
  134929. 2, 289,
  134930. _vq_lengthlist__44c8_s_p4_0,
  134931. 1, -529530880, 1611661312, 5, 0,
  134932. _vq_quantlist__44c8_s_p4_0,
  134933. NULL,
  134934. &_vq_auxt__44c8_s_p4_0,
  134935. NULL,
  134936. 0
  134937. };
  134938. static long _vq_quantlist__44c8_s_p5_0[] = {
  134939. 1,
  134940. 0,
  134941. 2,
  134942. };
  134943. static long _vq_lengthlist__44c8_s_p5_0[] = {
  134944. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6,10,10,10,10,
  134945. 10,10, 4, 6, 6,10,10,10,10, 9,10, 5,10,10, 9,11,
  134946. 11,10,11,11, 7,10,10,11,12,12,12,12,12, 7,10,10,
  134947. 11,12,12,12,12,12, 6,10,10,10,12,12,10,12,12, 7,
  134948. 10,10,11,12,12,12,12,12, 7,10,10,11,12,12,12,12,
  134949. 12,
  134950. };
  134951. static float _vq_quantthresh__44c8_s_p5_0[] = {
  134952. -5.5, 5.5,
  134953. };
  134954. static long _vq_quantmap__44c8_s_p5_0[] = {
  134955. 1, 0, 2,
  134956. };
  134957. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_0 = {
  134958. _vq_quantthresh__44c8_s_p5_0,
  134959. _vq_quantmap__44c8_s_p5_0,
  134960. 3,
  134961. 3
  134962. };
  134963. static static_codebook _44c8_s_p5_0 = {
  134964. 4, 81,
  134965. _vq_lengthlist__44c8_s_p5_0,
  134966. 1, -529137664, 1618345984, 2, 0,
  134967. _vq_quantlist__44c8_s_p5_0,
  134968. NULL,
  134969. &_vq_auxt__44c8_s_p5_0,
  134970. NULL,
  134971. 0
  134972. };
  134973. static long _vq_quantlist__44c8_s_p5_1[] = {
  134974. 5,
  134975. 4,
  134976. 6,
  134977. 3,
  134978. 7,
  134979. 2,
  134980. 8,
  134981. 1,
  134982. 9,
  134983. 0,
  134984. 10,
  134985. };
  134986. static long _vq_lengthlist__44c8_s_p5_1[] = {
  134987. 3, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11, 4, 5, 6, 6,
  134988. 7, 7, 8, 8, 8, 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  134989. 9,12, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,12,12,12, 6,
  134990. 6, 7, 7, 8, 8, 9, 9,11,11,11, 6, 6, 7, 7, 8, 8,
  134991. 8, 8,11,11,11, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11,
  134992. 7, 7, 7, 8, 8, 8, 8, 8,11,11,11,11,11, 7, 7, 8,
  134993. 8, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 8, 8,11,11,
  134994. 11,11,11, 7, 7, 7, 7, 8, 8,
  134995. };
  134996. static float _vq_quantthresh__44c8_s_p5_1[] = {
  134997. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  134998. 3.5, 4.5,
  134999. };
  135000. static long _vq_quantmap__44c8_s_p5_1[] = {
  135001. 9, 7, 5, 3, 1, 0, 2, 4,
  135002. 6, 8, 10,
  135003. };
  135004. static encode_aux_threshmatch _vq_auxt__44c8_s_p5_1 = {
  135005. _vq_quantthresh__44c8_s_p5_1,
  135006. _vq_quantmap__44c8_s_p5_1,
  135007. 11,
  135008. 11
  135009. };
  135010. static static_codebook _44c8_s_p5_1 = {
  135011. 2, 121,
  135012. _vq_lengthlist__44c8_s_p5_1,
  135013. 1, -531365888, 1611661312, 4, 0,
  135014. _vq_quantlist__44c8_s_p5_1,
  135015. NULL,
  135016. &_vq_auxt__44c8_s_p5_1,
  135017. NULL,
  135018. 0
  135019. };
  135020. static long _vq_quantlist__44c8_s_p6_0[] = {
  135021. 6,
  135022. 5,
  135023. 7,
  135024. 4,
  135025. 8,
  135026. 3,
  135027. 9,
  135028. 2,
  135029. 10,
  135030. 1,
  135031. 11,
  135032. 0,
  135033. 12,
  135034. };
  135035. static long _vq_lengthlist__44c8_s_p6_0[] = {
  135036. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  135037. 7, 7, 8, 8, 9, 9,10,10,11,11, 6, 5, 5, 7, 7, 8,
  135038. 8, 9, 9,10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,
  135039. 10,10,11,11, 0, 7, 7, 7, 7, 9, 9,10,10,10,10,11,
  135040. 11, 0,11,11, 9, 9,10,10,11,11,11,11,12,12, 0,12,
  135041. 12, 9, 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0,
  135042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135046. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135047. };
  135048. static float _vq_quantthresh__44c8_s_p6_0[] = {
  135049. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135050. 12.5, 17.5, 22.5, 27.5,
  135051. };
  135052. static long _vq_quantmap__44c8_s_p6_0[] = {
  135053. 11, 9, 7, 5, 3, 1, 0, 2,
  135054. 4, 6, 8, 10, 12,
  135055. };
  135056. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_0 = {
  135057. _vq_quantthresh__44c8_s_p6_0,
  135058. _vq_quantmap__44c8_s_p6_0,
  135059. 13,
  135060. 13
  135061. };
  135062. static static_codebook _44c8_s_p6_0 = {
  135063. 2, 169,
  135064. _vq_lengthlist__44c8_s_p6_0,
  135065. 1, -526516224, 1616117760, 4, 0,
  135066. _vq_quantlist__44c8_s_p6_0,
  135067. NULL,
  135068. &_vq_auxt__44c8_s_p6_0,
  135069. NULL,
  135070. 0
  135071. };
  135072. static long _vq_quantlist__44c8_s_p6_1[] = {
  135073. 2,
  135074. 1,
  135075. 3,
  135076. 0,
  135077. 4,
  135078. };
  135079. static long _vq_lengthlist__44c8_s_p6_1[] = {
  135080. 3, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 6,
  135081. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  135082. };
  135083. static float _vq_quantthresh__44c8_s_p6_1[] = {
  135084. -1.5, -0.5, 0.5, 1.5,
  135085. };
  135086. static long _vq_quantmap__44c8_s_p6_1[] = {
  135087. 3, 1, 0, 2, 4,
  135088. };
  135089. static encode_aux_threshmatch _vq_auxt__44c8_s_p6_1 = {
  135090. _vq_quantthresh__44c8_s_p6_1,
  135091. _vq_quantmap__44c8_s_p6_1,
  135092. 5,
  135093. 5
  135094. };
  135095. static static_codebook _44c8_s_p6_1 = {
  135096. 2, 25,
  135097. _vq_lengthlist__44c8_s_p6_1,
  135098. 1, -533725184, 1611661312, 3, 0,
  135099. _vq_quantlist__44c8_s_p6_1,
  135100. NULL,
  135101. &_vq_auxt__44c8_s_p6_1,
  135102. NULL,
  135103. 0
  135104. };
  135105. static long _vq_quantlist__44c8_s_p7_0[] = {
  135106. 6,
  135107. 5,
  135108. 7,
  135109. 4,
  135110. 8,
  135111. 3,
  135112. 9,
  135113. 2,
  135114. 10,
  135115. 1,
  135116. 11,
  135117. 0,
  135118. 12,
  135119. };
  135120. static long _vq_lengthlist__44c8_s_p7_0[] = {
  135121. 1, 4, 4, 6, 6, 8, 7, 9, 9,10,10,12,12, 6, 5, 5,
  135122. 7, 7, 8, 8,10,10,11,11,12,12, 7, 5, 5, 7, 7, 8,
  135123. 8,10,10,11,11,12,12,21, 7, 7, 7, 7, 8, 9,10,10,
  135124. 11,11,12,12,21, 7, 7, 7, 7, 9, 9,10,10,12,12,13,
  135125. 13,21,11,11, 8, 8, 9, 9,11,11,12,12,13,13,21,11,
  135126. 11, 8, 8, 9, 9,11,11,12,12,13,13,21,21,21,10,10,
  135127. 10,10,11,11,12,13,13,13,21,21,21,10,10,10,10,11,
  135128. 11,13,13,14,13,21,21,21,13,13,11,11,12,12,13,13,
  135129. 14,14,21,21,21,14,14,11,11,12,12,13,13,14,14,21,
  135130. 21,21,21,20,13,13,13,12,14,14,16,15,20,20,20,20,
  135131. 20,13,13,13,13,14,13,15,15,
  135132. };
  135133. static float _vq_quantthresh__44c8_s_p7_0[] = {
  135134. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  135135. 27.5, 38.5, 49.5, 60.5,
  135136. };
  135137. static long _vq_quantmap__44c8_s_p7_0[] = {
  135138. 11, 9, 7, 5, 3, 1, 0, 2,
  135139. 4, 6, 8, 10, 12,
  135140. };
  135141. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_0 = {
  135142. _vq_quantthresh__44c8_s_p7_0,
  135143. _vq_quantmap__44c8_s_p7_0,
  135144. 13,
  135145. 13
  135146. };
  135147. static static_codebook _44c8_s_p7_0 = {
  135148. 2, 169,
  135149. _vq_lengthlist__44c8_s_p7_0,
  135150. 1, -523206656, 1618345984, 4, 0,
  135151. _vq_quantlist__44c8_s_p7_0,
  135152. NULL,
  135153. &_vq_auxt__44c8_s_p7_0,
  135154. NULL,
  135155. 0
  135156. };
  135157. static long _vq_quantlist__44c8_s_p7_1[] = {
  135158. 5,
  135159. 4,
  135160. 6,
  135161. 3,
  135162. 7,
  135163. 2,
  135164. 8,
  135165. 1,
  135166. 9,
  135167. 0,
  135168. 10,
  135169. };
  135170. static long _vq_lengthlist__44c8_s_p7_1[] = {
  135171. 4, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 7,
  135172. 7, 7, 7, 7, 7, 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  135173. 7, 8, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7,
  135174. 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135175. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  135176. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  135177. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  135178. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  135179. };
  135180. static float _vq_quantthresh__44c8_s_p7_1[] = {
  135181. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135182. 3.5, 4.5,
  135183. };
  135184. static long _vq_quantmap__44c8_s_p7_1[] = {
  135185. 9, 7, 5, 3, 1, 0, 2, 4,
  135186. 6, 8, 10,
  135187. };
  135188. static encode_aux_threshmatch _vq_auxt__44c8_s_p7_1 = {
  135189. _vq_quantthresh__44c8_s_p7_1,
  135190. _vq_quantmap__44c8_s_p7_1,
  135191. 11,
  135192. 11
  135193. };
  135194. static static_codebook _44c8_s_p7_1 = {
  135195. 2, 121,
  135196. _vq_lengthlist__44c8_s_p7_1,
  135197. 1, -531365888, 1611661312, 4, 0,
  135198. _vq_quantlist__44c8_s_p7_1,
  135199. NULL,
  135200. &_vq_auxt__44c8_s_p7_1,
  135201. NULL,
  135202. 0
  135203. };
  135204. static long _vq_quantlist__44c8_s_p8_0[] = {
  135205. 7,
  135206. 6,
  135207. 8,
  135208. 5,
  135209. 9,
  135210. 4,
  135211. 10,
  135212. 3,
  135213. 11,
  135214. 2,
  135215. 12,
  135216. 1,
  135217. 13,
  135218. 0,
  135219. 14,
  135220. };
  135221. static long _vq_lengthlist__44c8_s_p8_0[] = {
  135222. 1, 4, 4, 7, 6, 8, 8, 8, 7, 9, 8,10,10,11,10, 6,
  135223. 5, 5, 7, 7, 9, 9, 8, 8,10,10,11,11,12,11, 6, 5,
  135224. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8,
  135225. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,20, 8, 8, 8,
  135226. 8,10, 9, 9, 9,10,10,11,11,12,12,20,12,12, 9, 9,
  135227. 10,10,10,10,10,11,12,12,12,12,20,12,12, 9, 9,10,
  135228. 10,10,10,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,
  135229. 11,10,11,11,12,12,12,13,20,19,19, 9, 9, 9, 9,11,
  135230. 11,11,12,12,12,13,13,19,19,19,13,13,10,10,11,11,
  135231. 12,12,13,13,13,13,19,19,19,14,13,11,10,11,11,12,
  135232. 12,12,13,13,13,19,19,19,19,19,12,12,12,12,13,13,
  135233. 13,13,14,13,19,19,19,19,19,12,12,12,11,12,12,13,
  135234. 14,14,14,19,19,19,19,19,16,15,13,12,13,13,13,14,
  135235. 14,14,19,19,19,19,19,17,17,13,12,13,11,14,13,15,
  135236. 15,
  135237. };
  135238. static float _vq_quantthresh__44c8_s_p8_0[] = {
  135239. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  135240. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  135241. };
  135242. static long _vq_quantmap__44c8_s_p8_0[] = {
  135243. 13, 11, 9, 7, 5, 3, 1, 0,
  135244. 2, 4, 6, 8, 10, 12, 14,
  135245. };
  135246. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_0 = {
  135247. _vq_quantthresh__44c8_s_p8_0,
  135248. _vq_quantmap__44c8_s_p8_0,
  135249. 15,
  135250. 15
  135251. };
  135252. static static_codebook _44c8_s_p8_0 = {
  135253. 2, 225,
  135254. _vq_lengthlist__44c8_s_p8_0,
  135255. 1, -520986624, 1620377600, 4, 0,
  135256. _vq_quantlist__44c8_s_p8_0,
  135257. NULL,
  135258. &_vq_auxt__44c8_s_p8_0,
  135259. NULL,
  135260. 0
  135261. };
  135262. static long _vq_quantlist__44c8_s_p8_1[] = {
  135263. 10,
  135264. 9,
  135265. 11,
  135266. 8,
  135267. 12,
  135268. 7,
  135269. 13,
  135270. 6,
  135271. 14,
  135272. 5,
  135273. 15,
  135274. 4,
  135275. 16,
  135276. 3,
  135277. 17,
  135278. 2,
  135279. 18,
  135280. 1,
  135281. 19,
  135282. 0,
  135283. 20,
  135284. };
  135285. static long _vq_lengthlist__44c8_s_p8_1[] = {
  135286. 4, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  135287. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  135288. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  135289. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  135290. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135291. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  135292. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 9,
  135293. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  135294. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135295. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135296. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  135297. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  135298. 10,10, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9,
  135299. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  135300. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  135301. 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,10,10,10,10,
  135302. 10,10,10, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  135303. 9,10,10,10,10,10,10,10, 9,10,10, 9,10,10,10,10,
  135304. 9,10, 9,10,10, 9,10,10,10,10,10,10,10, 9,10,10,
  135305. 10,10,10,10, 9, 9,10,10, 9,10,10,10,10,10,10,10,
  135306. 10,10,10,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9, 9,
  135307. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  135308. 10, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  135309. 10,10,10,10, 9, 9,10, 9, 9, 9,10,10,10,10,10,10,
  135310. 10,10,10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9,10,10,
  135311. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10, 9,
  135312. 9,10, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  135313. 10, 9, 9,10,10, 9,10, 9, 9,
  135314. };
  135315. static float _vq_quantthresh__44c8_s_p8_1[] = {
  135316. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  135317. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  135318. 6.5, 7.5, 8.5, 9.5,
  135319. };
  135320. static long _vq_quantmap__44c8_s_p8_1[] = {
  135321. 19, 17, 15, 13, 11, 9, 7, 5,
  135322. 3, 1, 0, 2, 4, 6, 8, 10,
  135323. 12, 14, 16, 18, 20,
  135324. };
  135325. static encode_aux_threshmatch _vq_auxt__44c8_s_p8_1 = {
  135326. _vq_quantthresh__44c8_s_p8_1,
  135327. _vq_quantmap__44c8_s_p8_1,
  135328. 21,
  135329. 21
  135330. };
  135331. static static_codebook _44c8_s_p8_1 = {
  135332. 2, 441,
  135333. _vq_lengthlist__44c8_s_p8_1,
  135334. 1, -529268736, 1611661312, 5, 0,
  135335. _vq_quantlist__44c8_s_p8_1,
  135336. NULL,
  135337. &_vq_auxt__44c8_s_p8_1,
  135338. NULL,
  135339. 0
  135340. };
  135341. static long _vq_quantlist__44c8_s_p9_0[] = {
  135342. 8,
  135343. 7,
  135344. 9,
  135345. 6,
  135346. 10,
  135347. 5,
  135348. 11,
  135349. 4,
  135350. 12,
  135351. 3,
  135352. 13,
  135353. 2,
  135354. 14,
  135355. 1,
  135356. 15,
  135357. 0,
  135358. 16,
  135359. };
  135360. static long _vq_lengthlist__44c8_s_p9_0[] = {
  135361. 1, 4, 3,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135362. 11, 4, 7, 7,11,11,11,11,11,11,11,11,11,11,11,11,
  135363. 11,11, 4, 8,11,11,11,11,11,11,11,11,11,11,11,11,
  135364. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135365. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135366. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135367. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135368. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135369. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135370. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135371. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135372. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135373. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135374. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  135375. 11,11,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135376. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135377. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135378. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  135379. 10,
  135380. };
  135381. static float _vq_quantthresh__44c8_s_p9_0[] = {
  135382. -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5,
  135383. 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5, 6982.5,
  135384. };
  135385. static long _vq_quantmap__44c8_s_p9_0[] = {
  135386. 15, 13, 11, 9, 7, 5, 3, 1,
  135387. 0, 2, 4, 6, 8, 10, 12, 14,
  135388. 16,
  135389. };
  135390. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_0 = {
  135391. _vq_quantthresh__44c8_s_p9_0,
  135392. _vq_quantmap__44c8_s_p9_0,
  135393. 17,
  135394. 17
  135395. };
  135396. static static_codebook _44c8_s_p9_0 = {
  135397. 2, 289,
  135398. _vq_lengthlist__44c8_s_p9_0,
  135399. 1, -509798400, 1631393792, 5, 0,
  135400. _vq_quantlist__44c8_s_p9_0,
  135401. NULL,
  135402. &_vq_auxt__44c8_s_p9_0,
  135403. NULL,
  135404. 0
  135405. };
  135406. static long _vq_quantlist__44c8_s_p9_1[] = {
  135407. 9,
  135408. 8,
  135409. 10,
  135410. 7,
  135411. 11,
  135412. 6,
  135413. 12,
  135414. 5,
  135415. 13,
  135416. 4,
  135417. 14,
  135418. 3,
  135419. 15,
  135420. 2,
  135421. 16,
  135422. 1,
  135423. 17,
  135424. 0,
  135425. 18,
  135426. };
  135427. static long _vq_lengthlist__44c8_s_p9_1[] = {
  135428. 1, 4, 4, 7, 6, 7, 7, 7, 7, 8, 8, 9, 9,10,10,10,
  135429. 10,11,11, 6, 6, 6, 8, 8, 9, 8, 8, 7,10, 8,11,10,
  135430. 12,11,12,12,13,13, 5, 5, 6, 8, 8, 9, 9, 8, 8,10,
  135431. 9,11,11,12,12,13,13,13,13,17, 8, 8, 9, 9, 9, 9,
  135432. 9, 9,10, 9,12,10,12,12,13,12,13,13,17, 9, 8, 9,
  135433. 9, 9, 9, 9, 9,10,10,12,12,12,12,13,13,13,13,17,
  135434. 13,13, 9, 9,10,10,10,10,11,11,12,11,13,12,13,13,
  135435. 14,15,17,13,13, 9, 8,10, 9,10,10,11,11,12,12,14,
  135436. 13,15,13,14,15,17,17,17, 9,10, 9,10,11,11,12,12,
  135437. 12,12,13,13,14,14,15,15,17,17,17, 9, 8, 9, 8,11,
  135438. 11,12,12,12,12,14,13,14,14,14,15,17,17,17,12,14,
  135439. 9,10,11,11,12,12,14,13,13,14,15,13,15,15,17,17,
  135440. 17,13,11,10, 8,11, 9,13,12,13,13,13,13,13,14,14,
  135441. 14,17,17,17,17,17,11,12,11,11,13,13,14,13,15,14,
  135442. 13,15,16,15,17,17,17,17,17,11,11,12, 8,13,12,14,
  135443. 13,17,14,15,14,15,14,17,17,17,17,17,15,15,12,12,
  135444. 12,12,13,14,14,14,15,14,17,14,17,17,17,17,17,16,
  135445. 17,12,12,13,12,13,13,14,14,14,14,14,14,17,17,17,
  135446. 17,17,17,17,14,14,13,12,13,13,15,15,14,13,15,17,
  135447. 17,17,17,17,17,17,17,13,14,13,13,13,13,14,15,15,
  135448. 15,14,15,17,17,17,17,17,17,17,16,15,13,14,13,13,
  135449. 14,14,15,14,14,16,17,17,17,17,17,17,17,16,16,13,
  135450. 14,13,13,14,14,15,14,15,14,
  135451. };
  135452. static float _vq_quantthresh__44c8_s_p9_1[] = {
  135453. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  135454. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  135455. 367.5, 416.5,
  135456. };
  135457. static long _vq_quantmap__44c8_s_p9_1[] = {
  135458. 17, 15, 13, 11, 9, 7, 5, 3,
  135459. 1, 0, 2, 4, 6, 8, 10, 12,
  135460. 14, 16, 18,
  135461. };
  135462. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_1 = {
  135463. _vq_quantthresh__44c8_s_p9_1,
  135464. _vq_quantmap__44c8_s_p9_1,
  135465. 19,
  135466. 19
  135467. };
  135468. static static_codebook _44c8_s_p9_1 = {
  135469. 2, 361,
  135470. _vq_lengthlist__44c8_s_p9_1,
  135471. 1, -518287360, 1622704128, 5, 0,
  135472. _vq_quantlist__44c8_s_p9_1,
  135473. NULL,
  135474. &_vq_auxt__44c8_s_p9_1,
  135475. NULL,
  135476. 0
  135477. };
  135478. static long _vq_quantlist__44c8_s_p9_2[] = {
  135479. 24,
  135480. 23,
  135481. 25,
  135482. 22,
  135483. 26,
  135484. 21,
  135485. 27,
  135486. 20,
  135487. 28,
  135488. 19,
  135489. 29,
  135490. 18,
  135491. 30,
  135492. 17,
  135493. 31,
  135494. 16,
  135495. 32,
  135496. 15,
  135497. 33,
  135498. 14,
  135499. 34,
  135500. 13,
  135501. 35,
  135502. 12,
  135503. 36,
  135504. 11,
  135505. 37,
  135506. 10,
  135507. 38,
  135508. 9,
  135509. 39,
  135510. 8,
  135511. 40,
  135512. 7,
  135513. 41,
  135514. 6,
  135515. 42,
  135516. 5,
  135517. 43,
  135518. 4,
  135519. 44,
  135520. 3,
  135521. 45,
  135522. 2,
  135523. 46,
  135524. 1,
  135525. 47,
  135526. 0,
  135527. 48,
  135528. };
  135529. static long _vq_lengthlist__44c8_s_p9_2[] = {
  135530. 2, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  135531. 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135532. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  135533. 7,
  135534. };
  135535. static float _vq_quantthresh__44c8_s_p9_2[] = {
  135536. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  135537. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  135538. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135539. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135540. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  135541. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  135542. };
  135543. static long _vq_quantmap__44c8_s_p9_2[] = {
  135544. 47, 45, 43, 41, 39, 37, 35, 33,
  135545. 31, 29, 27, 25, 23, 21, 19, 17,
  135546. 15, 13, 11, 9, 7, 5, 3, 1,
  135547. 0, 2, 4, 6, 8, 10, 12, 14,
  135548. 16, 18, 20, 22, 24, 26, 28, 30,
  135549. 32, 34, 36, 38, 40, 42, 44, 46,
  135550. 48,
  135551. };
  135552. static encode_aux_threshmatch _vq_auxt__44c8_s_p9_2 = {
  135553. _vq_quantthresh__44c8_s_p9_2,
  135554. _vq_quantmap__44c8_s_p9_2,
  135555. 49,
  135556. 49
  135557. };
  135558. static static_codebook _44c8_s_p9_2 = {
  135559. 1, 49,
  135560. _vq_lengthlist__44c8_s_p9_2,
  135561. 1, -526909440, 1611661312, 6, 0,
  135562. _vq_quantlist__44c8_s_p9_2,
  135563. NULL,
  135564. &_vq_auxt__44c8_s_p9_2,
  135565. NULL,
  135566. 0
  135567. };
  135568. static long _huff_lengthlist__44c8_s_short[] = {
  135569. 4,11,13,14,15,15,18,17,19,17, 5, 6, 8, 9,10,10,
  135570. 12,15,19,19, 6, 6, 6, 6, 8, 8,11,14,18,19, 8, 6,
  135571. 5, 4, 6, 7,10,13,16,17, 9, 7, 6, 5, 6, 7, 9,12,
  135572. 15,19,10, 8, 7, 6, 6, 6, 7, 9,13,15,12,10, 9, 8,
  135573. 7, 6, 4, 5,10,15,13,13,11, 8, 6, 6, 4, 2, 7,12,
  135574. 17,15,16,10, 8, 8, 7, 6, 9,12,19,18,17,13,11,10,
  135575. 10, 9,11,14,
  135576. };
  135577. static static_codebook _huff_book__44c8_s_short = {
  135578. 2, 100,
  135579. _huff_lengthlist__44c8_s_short,
  135580. 0, 0, 0, 0, 0,
  135581. NULL,
  135582. NULL,
  135583. NULL,
  135584. NULL,
  135585. 0
  135586. };
  135587. static long _huff_lengthlist__44c9_s_long[] = {
  135588. 3, 8,12,14,15,15,15,13,15,15, 6, 5, 8,10,12,12,
  135589. 13,12,14,13,10, 6, 5, 6, 8, 9,11,11,13,13,13, 8,
  135590. 5, 4, 5, 6, 8,10,11,13,14,10, 7, 5, 4, 5, 7, 9,
  135591. 11,12,13,11, 8, 6, 5, 4, 5, 7, 9,11,12,11,10, 8,
  135592. 7, 5, 4, 5, 9,10,13,13,11,10, 8, 6, 5, 4, 7, 9,
  135593. 15,14,13,12,10, 9, 8, 7, 8, 9,12,12,14,13,12,11,
  135594. 10, 9, 8, 9,
  135595. };
  135596. static static_codebook _huff_book__44c9_s_long = {
  135597. 2, 100,
  135598. _huff_lengthlist__44c9_s_long,
  135599. 0, 0, 0, 0, 0,
  135600. NULL,
  135601. NULL,
  135602. NULL,
  135603. NULL,
  135604. 0
  135605. };
  135606. static long _vq_quantlist__44c9_s_p1_0[] = {
  135607. 1,
  135608. 0,
  135609. 2,
  135610. };
  135611. static long _vq_lengthlist__44c9_s_p1_0[] = {
  135612. 1, 5, 5, 0, 5, 5, 0, 5, 5, 6, 8, 8, 0, 9, 8, 0,
  135613. 9, 8, 6, 8, 8, 0, 8, 9, 0, 8, 9, 0, 0, 0, 0, 0,
  135614. 0, 0, 0, 0, 5, 8, 8, 0, 7, 7, 0, 8, 8, 5, 8, 8,
  135615. 0, 7, 8, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5,
  135616. 9, 8, 0, 8, 8, 0, 7, 7, 5, 8, 9, 0, 8, 8, 0, 7,
  135617. 7,
  135618. };
  135619. static float _vq_quantthresh__44c9_s_p1_0[] = {
  135620. -0.5, 0.5,
  135621. };
  135622. static long _vq_quantmap__44c9_s_p1_0[] = {
  135623. 1, 0, 2,
  135624. };
  135625. static encode_aux_threshmatch _vq_auxt__44c9_s_p1_0 = {
  135626. _vq_quantthresh__44c9_s_p1_0,
  135627. _vq_quantmap__44c9_s_p1_0,
  135628. 3,
  135629. 3
  135630. };
  135631. static static_codebook _44c9_s_p1_0 = {
  135632. 4, 81,
  135633. _vq_lengthlist__44c9_s_p1_0,
  135634. 1, -535822336, 1611661312, 2, 0,
  135635. _vq_quantlist__44c9_s_p1_0,
  135636. NULL,
  135637. &_vq_auxt__44c9_s_p1_0,
  135638. NULL,
  135639. 0
  135640. };
  135641. static long _vq_quantlist__44c9_s_p2_0[] = {
  135642. 2,
  135643. 1,
  135644. 3,
  135645. 0,
  135646. 4,
  135647. };
  135648. static long _vq_lengthlist__44c9_s_p2_0[] = {
  135649. 3, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0, 5, 5, 8, 8, 0,
  135650. 7, 7, 9, 9, 0, 0, 0, 9, 9, 6, 7, 7, 9, 8, 0, 8,
  135651. 8, 9, 9, 0, 8, 7, 9, 9, 0, 9,10,10,10, 0, 0, 0,
  135652. 11,10, 6, 7, 7, 8, 9, 0, 8, 8, 9, 9, 0, 7, 8, 9,
  135653. 9, 0,10, 9,11,10, 0, 0, 0,10,10, 8, 9, 8,10,10,
  135654. 0,10,10,12,11, 0,10,10,11,11, 0,12,13,13,13, 0,
  135655. 0, 0,13,12, 8, 8, 9,10,10, 0,10,10,11,12, 0,10,
  135656. 10,11,11, 0,13,12,13,13, 0, 0, 0,13,13, 0, 0, 0,
  135657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135658. 0, 0, 0, 0, 0, 0, 6, 8, 7,10,10, 0, 7, 7,10, 9,
  135659. 0, 7, 7,10,10, 0, 9, 9,10,10, 0, 0, 0,10,10, 6,
  135660. 7, 8,10,10, 0, 7, 7, 9,10, 0, 7, 7,10,10, 0, 9,
  135661. 9,10,10, 0, 0, 0,10,10, 8, 9, 9,11,11, 0,10,10,
  135662. 11,11, 0,10,10,11,11, 0,12,12,12,12, 0, 0, 0,12,
  135663. 12, 8, 9,10,11,11, 0, 9,10,11,11, 0,10,10,11,11,
  135664. 0,12,12,12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0,
  135665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135666. 0, 0, 0, 5, 8, 7,10,10, 0, 7, 7,10,10, 0, 7, 7,
  135667. 10, 9, 0, 9, 9,10,10, 0, 0, 0,10,10, 6, 7, 8,10,
  135668. 10, 0, 7, 7,10,10, 0, 7, 7, 9,10, 0, 9, 9,10,10,
  135669. 0, 0, 0,10,10, 8,10, 9,12,11, 0,10,10,12,11, 0,
  135670. 10, 9,11,11, 0,11,12,12,12, 0, 0, 0,12,12, 8, 9,
  135671. 10,11,12, 0,10,10,11,11, 0, 9,10,11,11, 0,12,11,
  135672. 12,12, 0, 0, 0,12,12, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135674. 7,10, 9,12,12, 0, 9, 9,12,11, 0, 9, 9,11,11, 0,
  135675. 10,10,12,11, 0, 0, 0,11,12, 7, 9,10,12,12, 0, 9,
  135676. 9,11,12, 0, 9, 9,11,11, 0,10,10,11,12, 0, 0, 0,
  135677. 11,11, 9,11,10,13,12, 0,10,10,12,12, 0,10,10,12,
  135678. 12, 0,11,11,12,12, 0, 0, 0,13,12, 9,10,11,12,13,
  135679. 0,10,10,12,12, 0,10,10,12,12, 0,11,12,12,12, 0,
  135680. 0, 0,12,13, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9,
  135685. 11,10,13,13, 0,10,10,12,12, 0,10,10,12,12, 0,11,
  135686. 12,12,12, 0, 0, 0,12,12, 9,10,11,13,13, 0,10,10,
  135687. 12,12, 0,10,10,12,12, 0,12,11,13,12, 0, 0, 0,12,
  135688. 12,
  135689. };
  135690. static float _vq_quantthresh__44c9_s_p2_0[] = {
  135691. -1.5, -0.5, 0.5, 1.5,
  135692. };
  135693. static long _vq_quantmap__44c9_s_p2_0[] = {
  135694. 3, 1, 0, 2, 4,
  135695. };
  135696. static encode_aux_threshmatch _vq_auxt__44c9_s_p2_0 = {
  135697. _vq_quantthresh__44c9_s_p2_0,
  135698. _vq_quantmap__44c9_s_p2_0,
  135699. 5,
  135700. 5
  135701. };
  135702. static static_codebook _44c9_s_p2_0 = {
  135703. 4, 625,
  135704. _vq_lengthlist__44c9_s_p2_0,
  135705. 1, -533725184, 1611661312, 3, 0,
  135706. _vq_quantlist__44c9_s_p2_0,
  135707. NULL,
  135708. &_vq_auxt__44c9_s_p2_0,
  135709. NULL,
  135710. 0
  135711. };
  135712. static long _vq_quantlist__44c9_s_p3_0[] = {
  135713. 4,
  135714. 3,
  135715. 5,
  135716. 2,
  135717. 6,
  135718. 1,
  135719. 7,
  135720. 0,
  135721. 8,
  135722. };
  135723. static long _vq_lengthlist__44c9_s_p3_0[] = {
  135724. 3, 4, 4, 5, 5, 6, 6, 8, 8, 0, 4, 4, 5, 5, 6, 7,
  135725. 8, 8, 0, 4, 4, 5, 5, 7, 7, 8, 8, 0, 5, 5, 6, 6,
  135726. 7, 7, 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0,
  135727. 7, 7, 8, 8, 9, 9, 0, 0, 0, 7, 7, 8, 8, 9, 9, 0,
  135728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135729. 0,
  135730. };
  135731. static float _vq_quantthresh__44c9_s_p3_0[] = {
  135732. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  135733. };
  135734. static long _vq_quantmap__44c9_s_p3_0[] = {
  135735. 7, 5, 3, 1, 0, 2, 4, 6,
  135736. 8,
  135737. };
  135738. static encode_aux_threshmatch _vq_auxt__44c9_s_p3_0 = {
  135739. _vq_quantthresh__44c9_s_p3_0,
  135740. _vq_quantmap__44c9_s_p3_0,
  135741. 9,
  135742. 9
  135743. };
  135744. static static_codebook _44c9_s_p3_0 = {
  135745. 2, 81,
  135746. _vq_lengthlist__44c9_s_p3_0,
  135747. 1, -531628032, 1611661312, 4, 0,
  135748. _vq_quantlist__44c9_s_p3_0,
  135749. NULL,
  135750. &_vq_auxt__44c9_s_p3_0,
  135751. NULL,
  135752. 0
  135753. };
  135754. static long _vq_quantlist__44c9_s_p4_0[] = {
  135755. 8,
  135756. 7,
  135757. 9,
  135758. 6,
  135759. 10,
  135760. 5,
  135761. 11,
  135762. 4,
  135763. 12,
  135764. 3,
  135765. 13,
  135766. 2,
  135767. 14,
  135768. 1,
  135769. 15,
  135770. 0,
  135771. 16,
  135772. };
  135773. static long _vq_lengthlist__44c9_s_p4_0[] = {
  135774. 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,10,
  135775. 10, 0, 5, 4, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  135776. 11,11, 0, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  135777. 10,11,11, 0, 6, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,
  135778. 11,11,11,12, 0, 0, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,
  135779. 10,11,11,12,12, 0, 0, 0, 7, 7, 7, 7, 9, 9, 9, 9,
  135780. 10,10,11,11,12,12, 0, 0, 0, 7, 7, 7, 8, 9, 9, 9,
  135781. 9,10,10,11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,
  135782. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 8, 8, 9,
  135783. 9,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 0, 0,
  135784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135792. 0,
  135793. };
  135794. static float _vq_quantthresh__44c9_s_p4_0[] = {
  135795. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  135796. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  135797. };
  135798. static long _vq_quantmap__44c9_s_p4_0[] = {
  135799. 15, 13, 11, 9, 7, 5, 3, 1,
  135800. 0, 2, 4, 6, 8, 10, 12, 14,
  135801. 16,
  135802. };
  135803. static encode_aux_threshmatch _vq_auxt__44c9_s_p4_0 = {
  135804. _vq_quantthresh__44c9_s_p4_0,
  135805. _vq_quantmap__44c9_s_p4_0,
  135806. 17,
  135807. 17
  135808. };
  135809. static static_codebook _44c9_s_p4_0 = {
  135810. 2, 289,
  135811. _vq_lengthlist__44c9_s_p4_0,
  135812. 1, -529530880, 1611661312, 5, 0,
  135813. _vq_quantlist__44c9_s_p4_0,
  135814. NULL,
  135815. &_vq_auxt__44c9_s_p4_0,
  135816. NULL,
  135817. 0
  135818. };
  135819. static long _vq_quantlist__44c9_s_p5_0[] = {
  135820. 1,
  135821. 0,
  135822. 2,
  135823. };
  135824. static long _vq_lengthlist__44c9_s_p5_0[] = {
  135825. 1, 4, 4, 5, 7, 7, 6, 7, 7, 4, 7, 6, 9,10,10,10,
  135826. 10, 9, 4, 6, 7, 9,10,10,10, 9,10, 5, 9, 9, 9,11,
  135827. 11,10,11,11, 7,10, 9,11,12,11,12,12,12, 7, 9,10,
  135828. 11,11,12,12,12,12, 6,10,10,10,12,12,10,12,11, 7,
  135829. 10,10,11,12,12,11,12,12, 7,10,10,11,12,12,12,12,
  135830. 12,
  135831. };
  135832. static float _vq_quantthresh__44c9_s_p5_0[] = {
  135833. -5.5, 5.5,
  135834. };
  135835. static long _vq_quantmap__44c9_s_p5_0[] = {
  135836. 1, 0, 2,
  135837. };
  135838. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_0 = {
  135839. _vq_quantthresh__44c9_s_p5_0,
  135840. _vq_quantmap__44c9_s_p5_0,
  135841. 3,
  135842. 3
  135843. };
  135844. static static_codebook _44c9_s_p5_0 = {
  135845. 4, 81,
  135846. _vq_lengthlist__44c9_s_p5_0,
  135847. 1, -529137664, 1618345984, 2, 0,
  135848. _vq_quantlist__44c9_s_p5_0,
  135849. NULL,
  135850. &_vq_auxt__44c9_s_p5_0,
  135851. NULL,
  135852. 0
  135853. };
  135854. static long _vq_quantlist__44c9_s_p5_1[] = {
  135855. 5,
  135856. 4,
  135857. 6,
  135858. 3,
  135859. 7,
  135860. 2,
  135861. 8,
  135862. 1,
  135863. 9,
  135864. 0,
  135865. 10,
  135866. };
  135867. static long _vq_lengthlist__44c9_s_p5_1[] = {
  135868. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7,11, 5, 5, 6, 6,
  135869. 7, 7, 7, 7, 8, 8,11, 5, 5, 6, 6, 7, 7, 7, 7, 8,
  135870. 8,11, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8,11,11,11, 6,
  135871. 6, 7, 7, 7, 8, 8, 8,11,11,11, 6, 6, 7, 7, 7, 8,
  135872. 8, 8,11,11,11, 6, 6, 7, 7, 7, 7, 8, 8,11,11,11,
  135873. 7, 7, 7, 7, 7, 7, 8, 8,11,11,11,10,10, 7, 7, 7,
  135874. 7, 8, 8,11,11,11,11,11, 7, 7, 7, 7, 7, 7,11,11,
  135875. 11,11,11, 7, 7, 7, 7, 7, 7,
  135876. };
  135877. static float _vq_quantthresh__44c9_s_p5_1[] = {
  135878. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  135879. 3.5, 4.5,
  135880. };
  135881. static long _vq_quantmap__44c9_s_p5_1[] = {
  135882. 9, 7, 5, 3, 1, 0, 2, 4,
  135883. 6, 8, 10,
  135884. };
  135885. static encode_aux_threshmatch _vq_auxt__44c9_s_p5_1 = {
  135886. _vq_quantthresh__44c9_s_p5_1,
  135887. _vq_quantmap__44c9_s_p5_1,
  135888. 11,
  135889. 11
  135890. };
  135891. static static_codebook _44c9_s_p5_1 = {
  135892. 2, 121,
  135893. _vq_lengthlist__44c9_s_p5_1,
  135894. 1, -531365888, 1611661312, 4, 0,
  135895. _vq_quantlist__44c9_s_p5_1,
  135896. NULL,
  135897. &_vq_auxt__44c9_s_p5_1,
  135898. NULL,
  135899. 0
  135900. };
  135901. static long _vq_quantlist__44c9_s_p6_0[] = {
  135902. 6,
  135903. 5,
  135904. 7,
  135905. 4,
  135906. 8,
  135907. 3,
  135908. 9,
  135909. 2,
  135910. 10,
  135911. 1,
  135912. 11,
  135913. 0,
  135914. 12,
  135915. };
  135916. static long _vq_lengthlist__44c9_s_p6_0[] = {
  135917. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 5, 4, 4,
  135918. 6, 6, 8, 8, 9, 9, 9, 9,10,10, 6, 4, 4, 6, 6, 8,
  135919. 8, 9, 9, 9, 9,10,10, 0, 6, 6, 7, 7, 8, 8, 9, 9,
  135920. 10,10,11,11, 0, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  135921. 11, 0,10,10, 8, 8, 9, 9,10,10,11,11,12,12, 0,11,
  135922. 11, 8, 8, 9, 9,10,10,11,11,12,12, 0, 0, 0, 0, 0,
  135923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135927. 0, 0, 0, 0, 0, 0, 0, 0, 0,
  135928. };
  135929. static float _vq_quantthresh__44c9_s_p6_0[] = {
  135930. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  135931. 12.5, 17.5, 22.5, 27.5,
  135932. };
  135933. static long _vq_quantmap__44c9_s_p6_0[] = {
  135934. 11, 9, 7, 5, 3, 1, 0, 2,
  135935. 4, 6, 8, 10, 12,
  135936. };
  135937. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_0 = {
  135938. _vq_quantthresh__44c9_s_p6_0,
  135939. _vq_quantmap__44c9_s_p6_0,
  135940. 13,
  135941. 13
  135942. };
  135943. static static_codebook _44c9_s_p6_0 = {
  135944. 2, 169,
  135945. _vq_lengthlist__44c9_s_p6_0,
  135946. 1, -526516224, 1616117760, 4, 0,
  135947. _vq_quantlist__44c9_s_p6_0,
  135948. NULL,
  135949. &_vq_auxt__44c9_s_p6_0,
  135950. NULL,
  135951. 0
  135952. };
  135953. static long _vq_quantlist__44c9_s_p6_1[] = {
  135954. 2,
  135955. 1,
  135956. 3,
  135957. 0,
  135958. 4,
  135959. };
  135960. static long _vq_lengthlist__44c9_s_p6_1[] = {
  135961. 4, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5, 4, 4, 5, 5, 5,
  135962. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  135963. };
  135964. static float _vq_quantthresh__44c9_s_p6_1[] = {
  135965. -1.5, -0.5, 0.5, 1.5,
  135966. };
  135967. static long _vq_quantmap__44c9_s_p6_1[] = {
  135968. 3, 1, 0, 2, 4,
  135969. };
  135970. static encode_aux_threshmatch _vq_auxt__44c9_s_p6_1 = {
  135971. _vq_quantthresh__44c9_s_p6_1,
  135972. _vq_quantmap__44c9_s_p6_1,
  135973. 5,
  135974. 5
  135975. };
  135976. static static_codebook _44c9_s_p6_1 = {
  135977. 2, 25,
  135978. _vq_lengthlist__44c9_s_p6_1,
  135979. 1, -533725184, 1611661312, 3, 0,
  135980. _vq_quantlist__44c9_s_p6_1,
  135981. NULL,
  135982. &_vq_auxt__44c9_s_p6_1,
  135983. NULL,
  135984. 0
  135985. };
  135986. static long _vq_quantlist__44c9_s_p7_0[] = {
  135987. 6,
  135988. 5,
  135989. 7,
  135990. 4,
  135991. 8,
  135992. 3,
  135993. 9,
  135994. 2,
  135995. 10,
  135996. 1,
  135997. 11,
  135998. 0,
  135999. 12,
  136000. };
  136001. static long _vq_lengthlist__44c9_s_p7_0[] = {
  136002. 2, 4, 4, 6, 6, 7, 7, 8, 8,10,10,11,11, 6, 4, 4,
  136003. 6, 6, 8, 8, 9, 9,10,10,12,12, 6, 4, 5, 6, 6, 8,
  136004. 8, 9, 9,10,10,12,12,20, 6, 6, 6, 6, 8, 8, 9,10,
  136005. 11,11,12,12,20, 6, 6, 6, 6, 8, 8,10,10,11,11,12,
  136006. 12,20,10,10, 7, 7, 9, 9,10,10,11,11,12,12,20,11,
  136007. 11, 7, 7, 9, 9,10,10,11,11,12,12,20,20,20, 9, 9,
  136008. 9, 9,11,11,12,12,13,13,20,20,20, 9, 9, 9, 9,11,
  136009. 11,12,12,13,13,20,20,20,13,13,10,10,11,11,12,13,
  136010. 13,13,20,20,20,13,13,10,10,11,11,12,13,13,13,20,
  136011. 20,20,20,19,12,12,12,12,13,13,14,15,19,19,19,19,
  136012. 19,12,12,12,12,13,13,14,14,
  136013. };
  136014. static float _vq_quantthresh__44c9_s_p7_0[] = {
  136015. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  136016. 27.5, 38.5, 49.5, 60.5,
  136017. };
  136018. static long _vq_quantmap__44c9_s_p7_0[] = {
  136019. 11, 9, 7, 5, 3, 1, 0, 2,
  136020. 4, 6, 8, 10, 12,
  136021. };
  136022. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_0 = {
  136023. _vq_quantthresh__44c9_s_p7_0,
  136024. _vq_quantmap__44c9_s_p7_0,
  136025. 13,
  136026. 13
  136027. };
  136028. static static_codebook _44c9_s_p7_0 = {
  136029. 2, 169,
  136030. _vq_lengthlist__44c9_s_p7_0,
  136031. 1, -523206656, 1618345984, 4, 0,
  136032. _vq_quantlist__44c9_s_p7_0,
  136033. NULL,
  136034. &_vq_auxt__44c9_s_p7_0,
  136035. NULL,
  136036. 0
  136037. };
  136038. static long _vq_quantlist__44c9_s_p7_1[] = {
  136039. 5,
  136040. 4,
  136041. 6,
  136042. 3,
  136043. 7,
  136044. 2,
  136045. 8,
  136046. 1,
  136047. 9,
  136048. 0,
  136049. 10,
  136050. };
  136051. static long _vq_lengthlist__44c9_s_p7_1[] = {
  136052. 5, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6,
  136053. 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  136054. 7, 8, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 6,
  136055. 6, 7, 7, 7, 7, 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7,
  136056. 7, 7, 8, 8, 8, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  136057. 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  136058. 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 7, 8, 8,
  136059. 8, 8, 8, 7, 7, 7, 7, 7, 7,
  136060. };
  136061. static float _vq_quantthresh__44c9_s_p7_1[] = {
  136062. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  136063. 3.5, 4.5,
  136064. };
  136065. static long _vq_quantmap__44c9_s_p7_1[] = {
  136066. 9, 7, 5, 3, 1, 0, 2, 4,
  136067. 6, 8, 10,
  136068. };
  136069. static encode_aux_threshmatch _vq_auxt__44c9_s_p7_1 = {
  136070. _vq_quantthresh__44c9_s_p7_1,
  136071. _vq_quantmap__44c9_s_p7_1,
  136072. 11,
  136073. 11
  136074. };
  136075. static static_codebook _44c9_s_p7_1 = {
  136076. 2, 121,
  136077. _vq_lengthlist__44c9_s_p7_1,
  136078. 1, -531365888, 1611661312, 4, 0,
  136079. _vq_quantlist__44c9_s_p7_1,
  136080. NULL,
  136081. &_vq_auxt__44c9_s_p7_1,
  136082. NULL,
  136083. 0
  136084. };
  136085. static long _vq_quantlist__44c9_s_p8_0[] = {
  136086. 7,
  136087. 6,
  136088. 8,
  136089. 5,
  136090. 9,
  136091. 4,
  136092. 10,
  136093. 3,
  136094. 11,
  136095. 2,
  136096. 12,
  136097. 1,
  136098. 13,
  136099. 0,
  136100. 14,
  136101. };
  136102. static long _vq_lengthlist__44c9_s_p8_0[] = {
  136103. 1, 4, 4, 7, 6, 8, 8, 8, 8, 9, 9,10,10,11,10, 6,
  136104. 5, 5, 7, 7, 9, 9, 8, 9,10,10,11,11,12,12, 6, 5,
  136105. 5, 7, 7, 9, 9, 9, 9,10,10,11,11,12,12,21, 7, 8,
  136106. 8, 8, 9, 9, 9, 9,10,10,11,11,12,12,21, 8, 8, 8,
  136107. 8, 9, 9, 9, 9,10,10,11,11,12,12,21,11,12, 9, 9,
  136108. 10,10,10,10,10,11,11,12,12,12,21,12,12, 9, 8,10,
  136109. 10,10,10,11,11,12,12,13,13,21,21,21, 9, 9, 9, 9,
  136110. 11,11,11,11,12,12,12,13,21,20,20, 9, 9, 9, 9,10,
  136111. 11,11,11,12,12,13,13,20,20,20,13,13,10,10,11,11,
  136112. 12,12,13,13,13,13,20,20,20,13,13,10,10,11,11,12,
  136113. 12,13,13,13,13,20,20,20,20,20,12,12,12,12,12,12,
  136114. 13,13,14,14,20,20,20,20,20,12,12,12,11,13,12,13,
  136115. 13,14,14,20,20,20,20,20,15,16,13,12,13,13,14,13,
  136116. 14,14,20,20,20,20,20,16,15,12,12,13,12,14,13,14,
  136117. 14,
  136118. };
  136119. static float _vq_quantthresh__44c9_s_p8_0[] = {
  136120. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  136121. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  136122. };
  136123. static long _vq_quantmap__44c9_s_p8_0[] = {
  136124. 13, 11, 9, 7, 5, 3, 1, 0,
  136125. 2, 4, 6, 8, 10, 12, 14,
  136126. };
  136127. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_0 = {
  136128. _vq_quantthresh__44c9_s_p8_0,
  136129. _vq_quantmap__44c9_s_p8_0,
  136130. 15,
  136131. 15
  136132. };
  136133. static static_codebook _44c9_s_p8_0 = {
  136134. 2, 225,
  136135. _vq_lengthlist__44c9_s_p8_0,
  136136. 1, -520986624, 1620377600, 4, 0,
  136137. _vq_quantlist__44c9_s_p8_0,
  136138. NULL,
  136139. &_vq_auxt__44c9_s_p8_0,
  136140. NULL,
  136141. 0
  136142. };
  136143. static long _vq_quantlist__44c9_s_p8_1[] = {
  136144. 10,
  136145. 9,
  136146. 11,
  136147. 8,
  136148. 12,
  136149. 7,
  136150. 13,
  136151. 6,
  136152. 14,
  136153. 5,
  136154. 15,
  136155. 4,
  136156. 16,
  136157. 3,
  136158. 17,
  136159. 2,
  136160. 18,
  136161. 1,
  136162. 19,
  136163. 0,
  136164. 20,
  136165. };
  136166. static long _vq_lengthlist__44c9_s_p8_1[] = {
  136167. 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  136168. 8, 8, 8, 8, 8,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  136169. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 6, 6, 7, 7, 8,
  136170. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,
  136171. 7, 7, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  136172. 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  136173. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8,
  136174. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  136175. 10, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  136176. 9, 9, 9,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  136177. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  136178. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  136179. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  136180. 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  136181. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9,
  136182. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,
  136183. 10,10,10, 9, 9, 9, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,
  136184. 9,10,10,10,10,10,10,10, 9, 9, 9,10,10,10,10,10,
  136185. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10, 9, 9,10,
  136186. 9,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  136187. 10,10,10,10, 9, 9,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  136188. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  136189. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  136190. 10,10, 9, 9,10, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  136191. 10,10,10,10,10, 9, 9,10,10, 9, 9,10, 9, 9, 9,10,
  136192. 10,10,10,10,10,10,10,10,10,10, 9, 9,10, 9, 9, 9,
  136193. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9,
  136194. 9, 9, 9,10, 9, 9, 9, 9, 9,
  136195. };
  136196. static float _vq_quantthresh__44c9_s_p8_1[] = {
  136197. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  136198. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  136199. 6.5, 7.5, 8.5, 9.5,
  136200. };
  136201. static long _vq_quantmap__44c9_s_p8_1[] = {
  136202. 19, 17, 15, 13, 11, 9, 7, 5,
  136203. 3, 1, 0, 2, 4, 6, 8, 10,
  136204. 12, 14, 16, 18, 20,
  136205. };
  136206. static encode_aux_threshmatch _vq_auxt__44c9_s_p8_1 = {
  136207. _vq_quantthresh__44c9_s_p8_1,
  136208. _vq_quantmap__44c9_s_p8_1,
  136209. 21,
  136210. 21
  136211. };
  136212. static static_codebook _44c9_s_p8_1 = {
  136213. 2, 441,
  136214. _vq_lengthlist__44c9_s_p8_1,
  136215. 1, -529268736, 1611661312, 5, 0,
  136216. _vq_quantlist__44c9_s_p8_1,
  136217. NULL,
  136218. &_vq_auxt__44c9_s_p8_1,
  136219. NULL,
  136220. 0
  136221. };
  136222. static long _vq_quantlist__44c9_s_p9_0[] = {
  136223. 9,
  136224. 8,
  136225. 10,
  136226. 7,
  136227. 11,
  136228. 6,
  136229. 12,
  136230. 5,
  136231. 13,
  136232. 4,
  136233. 14,
  136234. 3,
  136235. 15,
  136236. 2,
  136237. 16,
  136238. 1,
  136239. 17,
  136240. 0,
  136241. 18,
  136242. };
  136243. static long _vq_lengthlist__44c9_s_p9_0[] = {
  136244. 1, 4, 3,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136245. 12,12,12, 4, 5, 6,12,12,12,12,12,12,12,12,12,12,
  136246. 12,12,12,12,12,12, 4, 6, 6,12,12,12,12,12,12,12,
  136247. 12,12,12,12,12,12,12,12,12,12,12,11,12,12,12,12,
  136248. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136249. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136250. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136251. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136252. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136253. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136254. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136255. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136256. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136257. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136258. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136259. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  136260. 12,12,12,12,12,12,12,12,12,12,11,11,11,11,11,11,
  136261. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136262. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  136266. 11,11,11,11,11,11,11,11,11,
  136267. };
  136268. static float _vq_quantthresh__44c9_s_p9_0[] = {
  136269. -7913.5, -6982.5, -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5,
  136270. -465.5, 465.5, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  136271. 6982.5, 7913.5,
  136272. };
  136273. static long _vq_quantmap__44c9_s_p9_0[] = {
  136274. 17, 15, 13, 11, 9, 7, 5, 3,
  136275. 1, 0, 2, 4, 6, 8, 10, 12,
  136276. 14, 16, 18,
  136277. };
  136278. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_0 = {
  136279. _vq_quantthresh__44c9_s_p9_0,
  136280. _vq_quantmap__44c9_s_p9_0,
  136281. 19,
  136282. 19
  136283. };
  136284. static static_codebook _44c9_s_p9_0 = {
  136285. 2, 361,
  136286. _vq_lengthlist__44c9_s_p9_0,
  136287. 1, -508535424, 1631393792, 5, 0,
  136288. _vq_quantlist__44c9_s_p9_0,
  136289. NULL,
  136290. &_vq_auxt__44c9_s_p9_0,
  136291. NULL,
  136292. 0
  136293. };
  136294. static long _vq_quantlist__44c9_s_p9_1[] = {
  136295. 9,
  136296. 8,
  136297. 10,
  136298. 7,
  136299. 11,
  136300. 6,
  136301. 12,
  136302. 5,
  136303. 13,
  136304. 4,
  136305. 14,
  136306. 3,
  136307. 15,
  136308. 2,
  136309. 16,
  136310. 1,
  136311. 17,
  136312. 0,
  136313. 18,
  136314. };
  136315. static long _vq_lengthlist__44c9_s_p9_1[] = {
  136316. 1, 4, 4, 7, 7, 7, 7, 8, 7, 9, 8, 9, 9,10,10,11,
  136317. 11,11,11, 6, 5, 5, 8, 8, 9, 9, 9, 8,10, 9,11,10,
  136318. 12,12,13,12,13,13, 5, 5, 5, 8, 8, 9, 9, 9, 9,10,
  136319. 10,11,11,12,12,13,12,13,13,17, 8, 8, 9, 9, 9, 9,
  136320. 9, 9,10,10,12,11,13,12,13,13,13,13,18, 8, 8, 9,
  136321. 9, 9, 9, 9, 9,11,11,12,12,13,13,13,13,13,13,17,
  136322. 13,12, 9, 9,10,10,10,10,11,11,12,12,12,13,13,13,
  136323. 14,14,18,13,12, 9, 9,10,10,10,10,11,11,12,12,13,
  136324. 13,13,14,14,14,17,18,18,10,10,10,10,11,11,11,12,
  136325. 12,12,14,13,14,13,13,14,18,18,18,10, 9,10, 9,11,
  136326. 11,12,12,12,12,13,13,15,14,14,14,18,18,16,13,14,
  136327. 10,11,11,11,12,13,13,13,13,14,13,13,14,14,18,18,
  136328. 18,14,12,11, 9,11,10,13,12,13,13,13,14,14,14,13,
  136329. 14,18,18,17,18,18,11,12,12,12,13,13,14,13,14,14,
  136330. 13,14,14,14,18,18,18,18,17,12,10,12, 9,13,11,13,
  136331. 14,14,14,14,14,15,14,18,18,17,17,18,14,15,12,13,
  136332. 13,13,14,13,14,14,15,14,15,14,18,17,18,18,18,15,
  136333. 15,12,10,14,10,14,14,13,13,14,14,14,14,18,16,18,
  136334. 18,18,18,17,14,14,13,14,14,13,13,14,14,14,15,15,
  136335. 18,18,18,18,17,17,17,14,14,14,12,14,13,14,14,15,
  136336. 14,15,14,18,18,18,18,18,18,18,17,16,13,13,13,14,
  136337. 14,14,14,15,16,15,18,18,18,18,18,18,18,17,17,13,
  136338. 13,13,13,14,13,14,15,15,15,
  136339. };
  136340. static float _vq_quantthresh__44c9_s_p9_1[] = {
  136341. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  136342. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  136343. 367.5, 416.5,
  136344. };
  136345. static long _vq_quantmap__44c9_s_p9_1[] = {
  136346. 17, 15, 13, 11, 9, 7, 5, 3,
  136347. 1, 0, 2, 4, 6, 8, 10, 12,
  136348. 14, 16, 18,
  136349. };
  136350. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_1 = {
  136351. _vq_quantthresh__44c9_s_p9_1,
  136352. _vq_quantmap__44c9_s_p9_1,
  136353. 19,
  136354. 19
  136355. };
  136356. static static_codebook _44c9_s_p9_1 = {
  136357. 2, 361,
  136358. _vq_lengthlist__44c9_s_p9_1,
  136359. 1, -518287360, 1622704128, 5, 0,
  136360. _vq_quantlist__44c9_s_p9_1,
  136361. NULL,
  136362. &_vq_auxt__44c9_s_p9_1,
  136363. NULL,
  136364. 0
  136365. };
  136366. static long _vq_quantlist__44c9_s_p9_2[] = {
  136367. 24,
  136368. 23,
  136369. 25,
  136370. 22,
  136371. 26,
  136372. 21,
  136373. 27,
  136374. 20,
  136375. 28,
  136376. 19,
  136377. 29,
  136378. 18,
  136379. 30,
  136380. 17,
  136381. 31,
  136382. 16,
  136383. 32,
  136384. 15,
  136385. 33,
  136386. 14,
  136387. 34,
  136388. 13,
  136389. 35,
  136390. 12,
  136391. 36,
  136392. 11,
  136393. 37,
  136394. 10,
  136395. 38,
  136396. 9,
  136397. 39,
  136398. 8,
  136399. 40,
  136400. 7,
  136401. 41,
  136402. 6,
  136403. 42,
  136404. 5,
  136405. 43,
  136406. 4,
  136407. 44,
  136408. 3,
  136409. 45,
  136410. 2,
  136411. 46,
  136412. 1,
  136413. 47,
  136414. 0,
  136415. 48,
  136416. };
  136417. static long _vq_lengthlist__44c9_s_p9_2[] = {
  136418. 2, 4, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  136419. 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  136420. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  136421. 7,
  136422. };
  136423. static float _vq_quantthresh__44c9_s_p9_2[] = {
  136424. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  136425. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  136426. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  136427. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  136428. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  136429. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  136430. };
  136431. static long _vq_quantmap__44c9_s_p9_2[] = {
  136432. 47, 45, 43, 41, 39, 37, 35, 33,
  136433. 31, 29, 27, 25, 23, 21, 19, 17,
  136434. 15, 13, 11, 9, 7, 5, 3, 1,
  136435. 0, 2, 4, 6, 8, 10, 12, 14,
  136436. 16, 18, 20, 22, 24, 26, 28, 30,
  136437. 32, 34, 36, 38, 40, 42, 44, 46,
  136438. 48,
  136439. };
  136440. static encode_aux_threshmatch _vq_auxt__44c9_s_p9_2 = {
  136441. _vq_quantthresh__44c9_s_p9_2,
  136442. _vq_quantmap__44c9_s_p9_2,
  136443. 49,
  136444. 49
  136445. };
  136446. static static_codebook _44c9_s_p9_2 = {
  136447. 1, 49,
  136448. _vq_lengthlist__44c9_s_p9_2,
  136449. 1, -526909440, 1611661312, 6, 0,
  136450. _vq_quantlist__44c9_s_p9_2,
  136451. NULL,
  136452. &_vq_auxt__44c9_s_p9_2,
  136453. NULL,
  136454. 0
  136455. };
  136456. static long _huff_lengthlist__44c9_s_short[] = {
  136457. 5,13,18,16,17,17,19,18,19,19, 5, 7,10,11,12,12,
  136458. 13,16,17,18, 6, 6, 7, 7, 9, 9,10,14,17,19, 8, 7,
  136459. 6, 5, 6, 7, 9,12,19,17, 8, 7, 7, 6, 5, 6, 8,11,
  136460. 15,19, 9, 8, 7, 6, 5, 5, 6, 8,13,15,11,10, 8, 8,
  136461. 7, 5, 4, 4,10,14,12,13,11, 9, 7, 6, 4, 2, 6,12,
  136462. 18,16,16,13, 8, 7, 7, 5, 8,13,16,17,18,15,11, 9,
  136463. 9, 8,10,13,
  136464. };
  136465. static static_codebook _huff_book__44c9_s_short = {
  136466. 2, 100,
  136467. _huff_lengthlist__44c9_s_short,
  136468. 0, 0, 0, 0, 0,
  136469. NULL,
  136470. NULL,
  136471. NULL,
  136472. NULL,
  136473. 0
  136474. };
  136475. static long _huff_lengthlist__44c0_s_long[] = {
  136476. 5, 4, 8, 9, 8, 9,10,12,15, 4, 1, 5, 5, 6, 8,11,
  136477. 12,12, 8, 5, 8, 9, 9,11,13,12,12, 9, 5, 8, 5, 7,
  136478. 9,12,13,13, 8, 6, 8, 7, 7, 9,11,11,11, 9, 7, 9,
  136479. 7, 7, 7, 7,10,12,10,10,11, 9, 8, 7, 7, 9,11,11,
  136480. 12,13,12,11, 9, 8, 9,11,13,16,16,15,15,12,10,11,
  136481. 12,
  136482. };
  136483. static static_codebook _huff_book__44c0_s_long = {
  136484. 2, 81,
  136485. _huff_lengthlist__44c0_s_long,
  136486. 0, 0, 0, 0, 0,
  136487. NULL,
  136488. NULL,
  136489. NULL,
  136490. NULL,
  136491. 0
  136492. };
  136493. static long _vq_quantlist__44c0_s_p1_0[] = {
  136494. 1,
  136495. 0,
  136496. 2,
  136497. };
  136498. static long _vq_lengthlist__44c0_s_p1_0[] = {
  136499. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136500. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136501. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136502. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136503. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136504. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136505. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136506. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136507. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136508. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136509. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136510. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136511. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136512. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136513. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136514. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136515. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136516. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136517. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136518. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136519. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136520. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136521. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136522. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136523. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136524. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136525. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136526. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136527. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136528. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136529. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136530. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136531. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136532. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136533. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136534. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136535. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136536. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136537. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136538. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136539. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136540. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136541. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136542. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136543. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136544. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  136545. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136546. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136547. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136548. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136549. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  136550. 0, 0, 0, 9,10,11, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  136551. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136555. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 9,10,11,
  136556. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136560. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136561. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136590. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  136591. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136595. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,11,10, 0,
  136596. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  136597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136600. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,11,
  136601. 0, 0, 0, 0, 0, 0, 9,11,10, 0, 0, 0, 0, 0, 0, 0,
  136602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136909. 0,
  136910. };
  136911. static float _vq_quantthresh__44c0_s_p1_0[] = {
  136912. -0.5, 0.5,
  136913. };
  136914. static long _vq_quantmap__44c0_s_p1_0[] = {
  136915. 1, 0, 2,
  136916. };
  136917. static encode_aux_threshmatch _vq_auxt__44c0_s_p1_0 = {
  136918. _vq_quantthresh__44c0_s_p1_0,
  136919. _vq_quantmap__44c0_s_p1_0,
  136920. 3,
  136921. 3
  136922. };
  136923. static static_codebook _44c0_s_p1_0 = {
  136924. 8, 6561,
  136925. _vq_lengthlist__44c0_s_p1_0,
  136926. 1, -535822336, 1611661312, 2, 0,
  136927. _vq_quantlist__44c0_s_p1_0,
  136928. NULL,
  136929. &_vq_auxt__44c0_s_p1_0,
  136930. NULL,
  136931. 0
  136932. };
  136933. static long _vq_quantlist__44c0_s_p2_0[] = {
  136934. 2,
  136935. 1,
  136936. 3,
  136937. 0,
  136938. 4,
  136939. };
  136940. static long _vq_lengthlist__44c0_s_p2_0[] = {
  136941. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 6, 0, 0,
  136943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136944. 0, 0, 4, 5, 6, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  136946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136947. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  136948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  136980. 0,
  136981. };
  136982. static float _vq_quantthresh__44c0_s_p2_0[] = {
  136983. -1.5, -0.5, 0.5, 1.5,
  136984. };
  136985. static long _vq_quantmap__44c0_s_p2_0[] = {
  136986. 3, 1, 0, 2, 4,
  136987. };
  136988. static encode_aux_threshmatch _vq_auxt__44c0_s_p2_0 = {
  136989. _vq_quantthresh__44c0_s_p2_0,
  136990. _vq_quantmap__44c0_s_p2_0,
  136991. 5,
  136992. 5
  136993. };
  136994. static static_codebook _44c0_s_p2_0 = {
  136995. 4, 625,
  136996. _vq_lengthlist__44c0_s_p2_0,
  136997. 1, -533725184, 1611661312, 3, 0,
  136998. _vq_quantlist__44c0_s_p2_0,
  136999. NULL,
  137000. &_vq_auxt__44c0_s_p2_0,
  137001. NULL,
  137002. 0
  137003. };
  137004. static long _vq_quantlist__44c0_s_p3_0[] = {
  137005. 4,
  137006. 3,
  137007. 5,
  137008. 2,
  137009. 6,
  137010. 1,
  137011. 7,
  137012. 0,
  137013. 8,
  137014. };
  137015. static long _vq_lengthlist__44c0_s_p3_0[] = {
  137016. 1, 3, 2, 8, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  137017. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  137018. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  137019. 8, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  137020. 0, 0, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137021. 0,
  137022. };
  137023. static float _vq_quantthresh__44c0_s_p3_0[] = {
  137024. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137025. };
  137026. static long _vq_quantmap__44c0_s_p3_0[] = {
  137027. 7, 5, 3, 1, 0, 2, 4, 6,
  137028. 8,
  137029. };
  137030. static encode_aux_threshmatch _vq_auxt__44c0_s_p3_0 = {
  137031. _vq_quantthresh__44c0_s_p3_0,
  137032. _vq_quantmap__44c0_s_p3_0,
  137033. 9,
  137034. 9
  137035. };
  137036. static static_codebook _44c0_s_p3_0 = {
  137037. 2, 81,
  137038. _vq_lengthlist__44c0_s_p3_0,
  137039. 1, -531628032, 1611661312, 4, 0,
  137040. _vq_quantlist__44c0_s_p3_0,
  137041. NULL,
  137042. &_vq_auxt__44c0_s_p3_0,
  137043. NULL,
  137044. 0
  137045. };
  137046. static long _vq_quantlist__44c0_s_p4_0[] = {
  137047. 4,
  137048. 3,
  137049. 5,
  137050. 2,
  137051. 6,
  137052. 1,
  137053. 7,
  137054. 0,
  137055. 8,
  137056. };
  137057. static long _vq_lengthlist__44c0_s_p4_0[] = {
  137058. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  137059. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  137060. 7, 8, 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0,
  137061. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 9, 8, 8,10,10, 0,
  137062. 0, 0,10,10, 9, 9,10,10, 0, 0, 0, 0, 0, 9, 9,10,
  137063. 10,
  137064. };
  137065. static float _vq_quantthresh__44c0_s_p4_0[] = {
  137066. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  137067. };
  137068. static long _vq_quantmap__44c0_s_p4_0[] = {
  137069. 7, 5, 3, 1, 0, 2, 4, 6,
  137070. 8,
  137071. };
  137072. static encode_aux_threshmatch _vq_auxt__44c0_s_p4_0 = {
  137073. _vq_quantthresh__44c0_s_p4_0,
  137074. _vq_quantmap__44c0_s_p4_0,
  137075. 9,
  137076. 9
  137077. };
  137078. static static_codebook _44c0_s_p4_0 = {
  137079. 2, 81,
  137080. _vq_lengthlist__44c0_s_p4_0,
  137081. 1, -531628032, 1611661312, 4, 0,
  137082. _vq_quantlist__44c0_s_p4_0,
  137083. NULL,
  137084. &_vq_auxt__44c0_s_p4_0,
  137085. NULL,
  137086. 0
  137087. };
  137088. static long _vq_quantlist__44c0_s_p5_0[] = {
  137089. 8,
  137090. 7,
  137091. 9,
  137092. 6,
  137093. 10,
  137094. 5,
  137095. 11,
  137096. 4,
  137097. 12,
  137098. 3,
  137099. 13,
  137100. 2,
  137101. 14,
  137102. 1,
  137103. 15,
  137104. 0,
  137105. 16,
  137106. };
  137107. static long _vq_lengthlist__44c0_s_p5_0[] = {
  137108. 1, 4, 3, 6, 6, 8, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  137109. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9, 9,10,10,10,
  137110. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  137111. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  137112. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  137113. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  137114. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  137115. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  137116. 10,10,11,11,11,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  137117. 10,10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,
  137118. 10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  137119. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  137120. 10,10,11,11,11,11,11,12,12,12,13,13, 0, 0, 0, 0,
  137121. 0, 0, 0,11,10,11,11,11,11,12,12,13,13, 0, 0, 0,
  137122. 0, 0, 0, 0,11,11,12,11,12,12,12,12,13,13, 0, 0,
  137123. 0, 0, 0, 0, 0,11,11,11,12,12,12,12,13,13,13, 0,
  137124. 0, 0, 0, 0, 0, 0,12,12,12,12,12,13,13,13,14,14,
  137125. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  137126. 14,
  137127. };
  137128. static float _vq_quantthresh__44c0_s_p5_0[] = {
  137129. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137130. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137131. };
  137132. static long _vq_quantmap__44c0_s_p5_0[] = {
  137133. 15, 13, 11, 9, 7, 5, 3, 1,
  137134. 0, 2, 4, 6, 8, 10, 12, 14,
  137135. 16,
  137136. };
  137137. static encode_aux_threshmatch _vq_auxt__44c0_s_p5_0 = {
  137138. _vq_quantthresh__44c0_s_p5_0,
  137139. _vq_quantmap__44c0_s_p5_0,
  137140. 17,
  137141. 17
  137142. };
  137143. static static_codebook _44c0_s_p5_0 = {
  137144. 2, 289,
  137145. _vq_lengthlist__44c0_s_p5_0,
  137146. 1, -529530880, 1611661312, 5, 0,
  137147. _vq_quantlist__44c0_s_p5_0,
  137148. NULL,
  137149. &_vq_auxt__44c0_s_p5_0,
  137150. NULL,
  137151. 0
  137152. };
  137153. static long _vq_quantlist__44c0_s_p6_0[] = {
  137154. 1,
  137155. 0,
  137156. 2,
  137157. };
  137158. static long _vq_lengthlist__44c0_s_p6_0[] = {
  137159. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,10,
  137160. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,11,11,
  137161. 11,12,10,11, 6, 9, 9,11,10,11,11,10,10, 6, 9, 9,
  137162. 11,10,11,11,10,10, 7,11,10,12,11,11,11,11,11, 7,
  137163. 9, 9,10,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  137164. 10,
  137165. };
  137166. static float _vq_quantthresh__44c0_s_p6_0[] = {
  137167. -5.5, 5.5,
  137168. };
  137169. static long _vq_quantmap__44c0_s_p6_0[] = {
  137170. 1, 0, 2,
  137171. };
  137172. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_0 = {
  137173. _vq_quantthresh__44c0_s_p6_0,
  137174. _vq_quantmap__44c0_s_p6_0,
  137175. 3,
  137176. 3
  137177. };
  137178. static static_codebook _44c0_s_p6_0 = {
  137179. 4, 81,
  137180. _vq_lengthlist__44c0_s_p6_0,
  137181. 1, -529137664, 1618345984, 2, 0,
  137182. _vq_quantlist__44c0_s_p6_0,
  137183. NULL,
  137184. &_vq_auxt__44c0_s_p6_0,
  137185. NULL,
  137186. 0
  137187. };
  137188. static long _vq_quantlist__44c0_s_p6_1[] = {
  137189. 5,
  137190. 4,
  137191. 6,
  137192. 3,
  137193. 7,
  137194. 2,
  137195. 8,
  137196. 1,
  137197. 9,
  137198. 0,
  137199. 10,
  137200. };
  137201. static long _vq_lengthlist__44c0_s_p6_1[] = {
  137202. 2, 3, 3, 6, 6, 7, 7, 7, 7, 7, 8,10,10,10, 6, 6,
  137203. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  137204. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  137205. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 7, 8, 8, 8, 8,
  137206. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  137207. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  137208. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  137209. 10,10,10, 8, 8, 8, 8, 8, 8,
  137210. };
  137211. static float _vq_quantthresh__44c0_s_p6_1[] = {
  137212. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  137213. 3.5, 4.5,
  137214. };
  137215. static long _vq_quantmap__44c0_s_p6_1[] = {
  137216. 9, 7, 5, 3, 1, 0, 2, 4,
  137217. 6, 8, 10,
  137218. };
  137219. static encode_aux_threshmatch _vq_auxt__44c0_s_p6_1 = {
  137220. _vq_quantthresh__44c0_s_p6_1,
  137221. _vq_quantmap__44c0_s_p6_1,
  137222. 11,
  137223. 11
  137224. };
  137225. static static_codebook _44c0_s_p6_1 = {
  137226. 2, 121,
  137227. _vq_lengthlist__44c0_s_p6_1,
  137228. 1, -531365888, 1611661312, 4, 0,
  137229. _vq_quantlist__44c0_s_p6_1,
  137230. NULL,
  137231. &_vq_auxt__44c0_s_p6_1,
  137232. NULL,
  137233. 0
  137234. };
  137235. static long _vq_quantlist__44c0_s_p7_0[] = {
  137236. 6,
  137237. 5,
  137238. 7,
  137239. 4,
  137240. 8,
  137241. 3,
  137242. 9,
  137243. 2,
  137244. 10,
  137245. 1,
  137246. 11,
  137247. 0,
  137248. 12,
  137249. };
  137250. static long _vq_lengthlist__44c0_s_p7_0[] = {
  137251. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  137252. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  137253. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  137254. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  137255. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  137256. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  137257. 10,10,11,11,11,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  137258. 11,11,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  137259. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  137260. 0, 0, 0, 0,11,11,11,11,13,12,13,13, 0, 0, 0, 0,
  137261. 0,12,12,11,11,12,12,13,13,
  137262. };
  137263. static float _vq_quantthresh__44c0_s_p7_0[] = {
  137264. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  137265. 12.5, 17.5, 22.5, 27.5,
  137266. };
  137267. static long _vq_quantmap__44c0_s_p7_0[] = {
  137268. 11, 9, 7, 5, 3, 1, 0, 2,
  137269. 4, 6, 8, 10, 12,
  137270. };
  137271. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_0 = {
  137272. _vq_quantthresh__44c0_s_p7_0,
  137273. _vq_quantmap__44c0_s_p7_0,
  137274. 13,
  137275. 13
  137276. };
  137277. static static_codebook _44c0_s_p7_0 = {
  137278. 2, 169,
  137279. _vq_lengthlist__44c0_s_p7_0,
  137280. 1, -526516224, 1616117760, 4, 0,
  137281. _vq_quantlist__44c0_s_p7_0,
  137282. NULL,
  137283. &_vq_auxt__44c0_s_p7_0,
  137284. NULL,
  137285. 0
  137286. };
  137287. static long _vq_quantlist__44c0_s_p7_1[] = {
  137288. 2,
  137289. 1,
  137290. 3,
  137291. 0,
  137292. 4,
  137293. };
  137294. static long _vq_lengthlist__44c0_s_p7_1[] = {
  137295. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  137296. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  137297. };
  137298. static float _vq_quantthresh__44c0_s_p7_1[] = {
  137299. -1.5, -0.5, 0.5, 1.5,
  137300. };
  137301. static long _vq_quantmap__44c0_s_p7_1[] = {
  137302. 3, 1, 0, 2, 4,
  137303. };
  137304. static encode_aux_threshmatch _vq_auxt__44c0_s_p7_1 = {
  137305. _vq_quantthresh__44c0_s_p7_1,
  137306. _vq_quantmap__44c0_s_p7_1,
  137307. 5,
  137308. 5
  137309. };
  137310. static static_codebook _44c0_s_p7_1 = {
  137311. 2, 25,
  137312. _vq_lengthlist__44c0_s_p7_1,
  137313. 1, -533725184, 1611661312, 3, 0,
  137314. _vq_quantlist__44c0_s_p7_1,
  137315. NULL,
  137316. &_vq_auxt__44c0_s_p7_1,
  137317. NULL,
  137318. 0
  137319. };
  137320. static long _vq_quantlist__44c0_s_p8_0[] = {
  137321. 2,
  137322. 1,
  137323. 3,
  137324. 0,
  137325. 4,
  137326. };
  137327. static long _vq_lengthlist__44c0_s_p8_0[] = {
  137328. 1, 5, 5,10,10, 6, 9, 8,10,10, 6,10, 9,10,10,10,
  137329. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137330. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137331. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137332. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137333. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137334. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137335. 10,10,10,10,10,10,10,10,10,10,10,10,10, 8,10,10,
  137336. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137337. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137338. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137339. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  137340. 10,10,10,10,10,10,10,10,11,11,11,11,11,11,11,11,
  137341. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137342. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137343. 11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,
  137344. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137345. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137346. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137347. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137348. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137349. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137350. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137351. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137352. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137353. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137354. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137355. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137356. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137357. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137358. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137359. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137360. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137361. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137362. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137363. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137364. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137365. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137366. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  137367. 11,
  137368. };
  137369. static float _vq_quantthresh__44c0_s_p8_0[] = {
  137370. -331.5, -110.5, 110.5, 331.5,
  137371. };
  137372. static long _vq_quantmap__44c0_s_p8_0[] = {
  137373. 3, 1, 0, 2, 4,
  137374. };
  137375. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_0 = {
  137376. _vq_quantthresh__44c0_s_p8_0,
  137377. _vq_quantmap__44c0_s_p8_0,
  137378. 5,
  137379. 5
  137380. };
  137381. static static_codebook _44c0_s_p8_0 = {
  137382. 4, 625,
  137383. _vq_lengthlist__44c0_s_p8_0,
  137384. 1, -518283264, 1627103232, 3, 0,
  137385. _vq_quantlist__44c0_s_p8_0,
  137386. NULL,
  137387. &_vq_auxt__44c0_s_p8_0,
  137388. NULL,
  137389. 0
  137390. };
  137391. static long _vq_quantlist__44c0_s_p8_1[] = {
  137392. 6,
  137393. 5,
  137394. 7,
  137395. 4,
  137396. 8,
  137397. 3,
  137398. 9,
  137399. 2,
  137400. 10,
  137401. 1,
  137402. 11,
  137403. 0,
  137404. 12,
  137405. };
  137406. static long _vq_lengthlist__44c0_s_p8_1[] = {
  137407. 1, 4, 4, 6, 6, 7, 7, 9, 9,11,12,13,12, 6, 5, 5,
  137408. 7, 7, 8, 8,10, 9,12,12,12,12, 6, 5, 5, 7, 7, 8,
  137409. 8,10, 9,12,11,11,13,16, 7, 7, 8, 8, 9, 9,10,10,
  137410. 12,12,13,12,16, 7, 7, 8, 7, 9, 9,10,10,11,12,12,
  137411. 13,16,10,10, 8, 8,10,10,11,12,12,12,13,13,16,11,
  137412. 10, 8, 7,11,10,11,11,12,11,13,13,16,16,16,10,10,
  137413. 10,10,11,11,13,12,13,13,16,16,16,11, 9,11, 9,15,
  137414. 13,12,13,13,13,16,16,16,15,13,11,11,12,13,12,12,
  137415. 14,13,16,16,16,14,13,11,11,13,12,14,13,13,13,16,
  137416. 16,16,16,16,13,13,13,12,14,13,14,14,16,16,16,16,
  137417. 16,13,13,12,12,14,14,15,13,
  137418. };
  137419. static float _vq_quantthresh__44c0_s_p8_1[] = {
  137420. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  137421. 42.5, 59.5, 76.5, 93.5,
  137422. };
  137423. static long _vq_quantmap__44c0_s_p8_1[] = {
  137424. 11, 9, 7, 5, 3, 1, 0, 2,
  137425. 4, 6, 8, 10, 12,
  137426. };
  137427. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_1 = {
  137428. _vq_quantthresh__44c0_s_p8_1,
  137429. _vq_quantmap__44c0_s_p8_1,
  137430. 13,
  137431. 13
  137432. };
  137433. static static_codebook _44c0_s_p8_1 = {
  137434. 2, 169,
  137435. _vq_lengthlist__44c0_s_p8_1,
  137436. 1, -522616832, 1620115456, 4, 0,
  137437. _vq_quantlist__44c0_s_p8_1,
  137438. NULL,
  137439. &_vq_auxt__44c0_s_p8_1,
  137440. NULL,
  137441. 0
  137442. };
  137443. static long _vq_quantlist__44c0_s_p8_2[] = {
  137444. 8,
  137445. 7,
  137446. 9,
  137447. 6,
  137448. 10,
  137449. 5,
  137450. 11,
  137451. 4,
  137452. 12,
  137453. 3,
  137454. 13,
  137455. 2,
  137456. 14,
  137457. 1,
  137458. 15,
  137459. 0,
  137460. 16,
  137461. };
  137462. static long _vq_lengthlist__44c0_s_p8_2[] = {
  137463. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  137464. 8,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  137465. 9, 9,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  137466. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  137467. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  137468. 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 8, 9, 9,
  137469. 9, 9, 9,10, 9,10,10,10,10, 7, 7, 8, 8, 9, 9, 9,
  137470. 9, 9, 9,10, 9,10,10,10,10,10, 8, 8, 8, 9, 9, 9,
  137471. 9, 9, 9, 9,10,10,10, 9,11,10,10,10,10, 8, 8, 9,
  137472. 9, 9, 9, 9,10, 9, 9, 9,10,10,10,10,11,11, 9, 9,
  137473. 9, 9, 9, 9, 9, 9,10, 9, 9,10,11,10,10,11,11, 9,
  137474. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  137475. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,10,11,
  137476. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  137477. 11,11,11,11, 9,10, 9,10, 9, 9, 9, 9,10, 9,10,11,
  137478. 10,11,10,10,10,10,10, 9, 9, 9,10, 9, 9, 9,10,11,
  137479. 11,10,11,11,10,11,10,10,10, 9, 9, 9, 9,10, 9, 9,
  137480. 10,11,10,11,11,11,11,10,11,10,10, 9,10, 9, 9, 9,
  137481. 10,
  137482. };
  137483. static float _vq_quantthresh__44c0_s_p8_2[] = {
  137484. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  137485. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  137486. };
  137487. static long _vq_quantmap__44c0_s_p8_2[] = {
  137488. 15, 13, 11, 9, 7, 5, 3, 1,
  137489. 0, 2, 4, 6, 8, 10, 12, 14,
  137490. 16,
  137491. };
  137492. static encode_aux_threshmatch _vq_auxt__44c0_s_p8_2 = {
  137493. _vq_quantthresh__44c0_s_p8_2,
  137494. _vq_quantmap__44c0_s_p8_2,
  137495. 17,
  137496. 17
  137497. };
  137498. static static_codebook _44c0_s_p8_2 = {
  137499. 2, 289,
  137500. _vq_lengthlist__44c0_s_p8_2,
  137501. 1, -529530880, 1611661312, 5, 0,
  137502. _vq_quantlist__44c0_s_p8_2,
  137503. NULL,
  137504. &_vq_auxt__44c0_s_p8_2,
  137505. NULL,
  137506. 0
  137507. };
  137508. static long _huff_lengthlist__44c0_s_short[] = {
  137509. 9, 8,12,11,12,13,14,14,16, 6, 1, 5, 6, 6, 9,12,
  137510. 14,17, 9, 4, 5, 9, 7, 9,13,15,16, 8, 5, 8, 6, 8,
  137511. 10,13,17,17, 9, 6, 7, 7, 8, 9,13,15,17,11, 8, 9,
  137512. 9, 9,10,12,16,16,13, 7, 8, 7, 7, 9,12,14,15,13,
  137513. 6, 7, 5, 5, 7,10,13,13,14, 7, 8, 5, 6, 7, 9,10,
  137514. 12,
  137515. };
  137516. static static_codebook _huff_book__44c0_s_short = {
  137517. 2, 81,
  137518. _huff_lengthlist__44c0_s_short,
  137519. 0, 0, 0, 0, 0,
  137520. NULL,
  137521. NULL,
  137522. NULL,
  137523. NULL,
  137524. 0
  137525. };
  137526. static long _huff_lengthlist__44c0_sm_long[] = {
  137527. 5, 4, 9,10, 9,10,11,12,13, 4, 1, 5, 7, 7, 9,11,
  137528. 12,14, 8, 5, 7, 9, 8,10,13,13,13,10, 7, 9, 4, 6,
  137529. 7,10,12,14, 9, 6, 7, 6, 6, 7,10,12,12, 9, 8, 9,
  137530. 7, 6, 7, 8,11,12,11,11,11, 9, 8, 7, 8,10,12,12,
  137531. 13,14,12,11, 9, 9, 9,12,12,17,17,15,16,12,10,11,
  137532. 13,
  137533. };
  137534. static static_codebook _huff_book__44c0_sm_long = {
  137535. 2, 81,
  137536. _huff_lengthlist__44c0_sm_long,
  137537. 0, 0, 0, 0, 0,
  137538. NULL,
  137539. NULL,
  137540. NULL,
  137541. NULL,
  137542. 0
  137543. };
  137544. static long _vq_quantlist__44c0_sm_p1_0[] = {
  137545. 1,
  137546. 0,
  137547. 2,
  137548. };
  137549. static long _vq_lengthlist__44c0_sm_p1_0[] = {
  137550. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  137551. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137552. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137553. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137554. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137555. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137556. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137557. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137558. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137559. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137560. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  137561. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137562. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137563. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137564. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137565. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137566. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137567. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137568. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137569. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137570. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137571. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137572. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137573. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137577. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137578. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137582. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137583. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  137596. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  137597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  137601. 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137606. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137641. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  137642. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137646. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  137647. 0, 0, 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  137648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137651. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  137652. 0, 0, 0, 0, 0, 0, 9,10,10, 0, 0, 0, 0, 0, 0, 0,
  137653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137960. 0,
  137961. };
  137962. static float _vq_quantthresh__44c0_sm_p1_0[] = {
  137963. -0.5, 0.5,
  137964. };
  137965. static long _vq_quantmap__44c0_sm_p1_0[] = {
  137966. 1, 0, 2,
  137967. };
  137968. static encode_aux_threshmatch _vq_auxt__44c0_sm_p1_0 = {
  137969. _vq_quantthresh__44c0_sm_p1_0,
  137970. _vq_quantmap__44c0_sm_p1_0,
  137971. 3,
  137972. 3
  137973. };
  137974. static static_codebook _44c0_sm_p1_0 = {
  137975. 8, 6561,
  137976. _vq_lengthlist__44c0_sm_p1_0,
  137977. 1, -535822336, 1611661312, 2, 0,
  137978. _vq_quantlist__44c0_sm_p1_0,
  137979. NULL,
  137980. &_vq_auxt__44c0_sm_p1_0,
  137981. NULL,
  137982. 0
  137983. };
  137984. static long _vq_quantlist__44c0_sm_p2_0[] = {
  137985. 2,
  137986. 1,
  137987. 3,
  137988. 0,
  137989. 4,
  137990. };
  137991. static long _vq_lengthlist__44c0_sm_p2_0[] = {
  137992. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  137994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137995. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  137997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  137998. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  137999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138031. 0,
  138032. };
  138033. static float _vq_quantthresh__44c0_sm_p2_0[] = {
  138034. -1.5, -0.5, 0.5, 1.5,
  138035. };
  138036. static long _vq_quantmap__44c0_sm_p2_0[] = {
  138037. 3, 1, 0, 2, 4,
  138038. };
  138039. static encode_aux_threshmatch _vq_auxt__44c0_sm_p2_0 = {
  138040. _vq_quantthresh__44c0_sm_p2_0,
  138041. _vq_quantmap__44c0_sm_p2_0,
  138042. 5,
  138043. 5
  138044. };
  138045. static static_codebook _44c0_sm_p2_0 = {
  138046. 4, 625,
  138047. _vq_lengthlist__44c0_sm_p2_0,
  138048. 1, -533725184, 1611661312, 3, 0,
  138049. _vq_quantlist__44c0_sm_p2_0,
  138050. NULL,
  138051. &_vq_auxt__44c0_sm_p2_0,
  138052. NULL,
  138053. 0
  138054. };
  138055. static long _vq_quantlist__44c0_sm_p3_0[] = {
  138056. 4,
  138057. 3,
  138058. 5,
  138059. 2,
  138060. 6,
  138061. 1,
  138062. 7,
  138063. 0,
  138064. 8,
  138065. };
  138066. static long _vq_lengthlist__44c0_sm_p3_0[] = {
  138067. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 4, 7, 7, 0, 0,
  138068. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  138069. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  138070. 9,10, 0, 0, 0, 0, 0, 0, 0, 9, 9, 0, 0, 0, 0, 0,
  138071. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138072. 0,
  138073. };
  138074. static float _vq_quantthresh__44c0_sm_p3_0[] = {
  138075. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138076. };
  138077. static long _vq_quantmap__44c0_sm_p3_0[] = {
  138078. 7, 5, 3, 1, 0, 2, 4, 6,
  138079. 8,
  138080. };
  138081. static encode_aux_threshmatch _vq_auxt__44c0_sm_p3_0 = {
  138082. _vq_quantthresh__44c0_sm_p3_0,
  138083. _vq_quantmap__44c0_sm_p3_0,
  138084. 9,
  138085. 9
  138086. };
  138087. static static_codebook _44c0_sm_p3_0 = {
  138088. 2, 81,
  138089. _vq_lengthlist__44c0_sm_p3_0,
  138090. 1, -531628032, 1611661312, 4, 0,
  138091. _vq_quantlist__44c0_sm_p3_0,
  138092. NULL,
  138093. &_vq_auxt__44c0_sm_p3_0,
  138094. NULL,
  138095. 0
  138096. };
  138097. static long _vq_quantlist__44c0_sm_p4_0[] = {
  138098. 4,
  138099. 3,
  138100. 5,
  138101. 2,
  138102. 6,
  138103. 1,
  138104. 7,
  138105. 0,
  138106. 8,
  138107. };
  138108. static long _vq_lengthlist__44c0_sm_p4_0[] = {
  138109. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  138110. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  138111. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  138112. 9, 9, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  138113. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  138114. 11,
  138115. };
  138116. static float _vq_quantthresh__44c0_sm_p4_0[] = {
  138117. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  138118. };
  138119. static long _vq_quantmap__44c0_sm_p4_0[] = {
  138120. 7, 5, 3, 1, 0, 2, 4, 6,
  138121. 8,
  138122. };
  138123. static encode_aux_threshmatch _vq_auxt__44c0_sm_p4_0 = {
  138124. _vq_quantthresh__44c0_sm_p4_0,
  138125. _vq_quantmap__44c0_sm_p4_0,
  138126. 9,
  138127. 9
  138128. };
  138129. static static_codebook _44c0_sm_p4_0 = {
  138130. 2, 81,
  138131. _vq_lengthlist__44c0_sm_p4_0,
  138132. 1, -531628032, 1611661312, 4, 0,
  138133. _vq_quantlist__44c0_sm_p4_0,
  138134. NULL,
  138135. &_vq_auxt__44c0_sm_p4_0,
  138136. NULL,
  138137. 0
  138138. };
  138139. static long _vq_quantlist__44c0_sm_p5_0[] = {
  138140. 8,
  138141. 7,
  138142. 9,
  138143. 6,
  138144. 10,
  138145. 5,
  138146. 11,
  138147. 4,
  138148. 12,
  138149. 3,
  138150. 13,
  138151. 2,
  138152. 14,
  138153. 1,
  138154. 15,
  138155. 0,
  138156. 16,
  138157. };
  138158. static long _vq_lengthlist__44c0_sm_p5_0[] = {
  138159. 1, 4, 4, 6, 6, 8, 8, 8, 8, 8, 8, 9, 9,10,10,11,
  138160. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,11,
  138161. 11,11, 0, 5, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  138162. 11,11,11, 0, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  138163. 11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,
  138164. 10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  138165. 11,11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  138166. 10,11,11,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  138167. 10,10,11,11,12,12,12,13, 0, 0, 0, 0, 0, 9, 9,10,
  138168. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  138169. 10,10,11,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  138170. 9,10,10,11,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  138171. 10,10,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0,
  138172. 0, 0, 0,10,10,11,11,12,12,12,13,13,13, 0, 0, 0,
  138173. 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14, 0, 0,
  138174. 0, 0, 0, 0, 0,11,11,12,11,12,12,13,13,13,13, 0,
  138175. 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,13,13,14,14,
  138176. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  138177. 14,
  138178. };
  138179. static float _vq_quantthresh__44c0_sm_p5_0[] = {
  138180. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138181. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138182. };
  138183. static long _vq_quantmap__44c0_sm_p5_0[] = {
  138184. 15, 13, 11, 9, 7, 5, 3, 1,
  138185. 0, 2, 4, 6, 8, 10, 12, 14,
  138186. 16,
  138187. };
  138188. static encode_aux_threshmatch _vq_auxt__44c0_sm_p5_0 = {
  138189. _vq_quantthresh__44c0_sm_p5_0,
  138190. _vq_quantmap__44c0_sm_p5_0,
  138191. 17,
  138192. 17
  138193. };
  138194. static static_codebook _44c0_sm_p5_0 = {
  138195. 2, 289,
  138196. _vq_lengthlist__44c0_sm_p5_0,
  138197. 1, -529530880, 1611661312, 5, 0,
  138198. _vq_quantlist__44c0_sm_p5_0,
  138199. NULL,
  138200. &_vq_auxt__44c0_sm_p5_0,
  138201. NULL,
  138202. 0
  138203. };
  138204. static long _vq_quantlist__44c0_sm_p6_0[] = {
  138205. 1,
  138206. 0,
  138207. 2,
  138208. };
  138209. static long _vq_lengthlist__44c0_sm_p6_0[] = {
  138210. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  138211. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  138212. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  138213. 11,10,11,11,10,10, 7,11,10,11,11,11,11,11,11, 6,
  138214. 9, 9,11,10,10,11,11,10, 6, 9, 9,11,10,10,11,10,
  138215. 11,
  138216. };
  138217. static float _vq_quantthresh__44c0_sm_p6_0[] = {
  138218. -5.5, 5.5,
  138219. };
  138220. static long _vq_quantmap__44c0_sm_p6_0[] = {
  138221. 1, 0, 2,
  138222. };
  138223. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_0 = {
  138224. _vq_quantthresh__44c0_sm_p6_0,
  138225. _vq_quantmap__44c0_sm_p6_0,
  138226. 3,
  138227. 3
  138228. };
  138229. static static_codebook _44c0_sm_p6_0 = {
  138230. 4, 81,
  138231. _vq_lengthlist__44c0_sm_p6_0,
  138232. 1, -529137664, 1618345984, 2, 0,
  138233. _vq_quantlist__44c0_sm_p6_0,
  138234. NULL,
  138235. &_vq_auxt__44c0_sm_p6_0,
  138236. NULL,
  138237. 0
  138238. };
  138239. static long _vq_quantlist__44c0_sm_p6_1[] = {
  138240. 5,
  138241. 4,
  138242. 6,
  138243. 3,
  138244. 7,
  138245. 2,
  138246. 8,
  138247. 1,
  138248. 9,
  138249. 0,
  138250. 10,
  138251. };
  138252. static long _vq_lengthlist__44c0_sm_p6_1[] = {
  138253. 2, 4, 4, 6, 6, 7, 7, 7, 7, 7, 8, 9, 5, 5, 6, 6,
  138254. 7, 7, 8, 8, 8, 8, 9, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  138255. 8,10, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  138256. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  138257. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  138258. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  138259. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  138260. 10,10,10, 8, 8, 8, 8, 8, 8,
  138261. };
  138262. static float _vq_quantthresh__44c0_sm_p6_1[] = {
  138263. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  138264. 3.5, 4.5,
  138265. };
  138266. static long _vq_quantmap__44c0_sm_p6_1[] = {
  138267. 9, 7, 5, 3, 1, 0, 2, 4,
  138268. 6, 8, 10,
  138269. };
  138270. static encode_aux_threshmatch _vq_auxt__44c0_sm_p6_1 = {
  138271. _vq_quantthresh__44c0_sm_p6_1,
  138272. _vq_quantmap__44c0_sm_p6_1,
  138273. 11,
  138274. 11
  138275. };
  138276. static static_codebook _44c0_sm_p6_1 = {
  138277. 2, 121,
  138278. _vq_lengthlist__44c0_sm_p6_1,
  138279. 1, -531365888, 1611661312, 4, 0,
  138280. _vq_quantlist__44c0_sm_p6_1,
  138281. NULL,
  138282. &_vq_auxt__44c0_sm_p6_1,
  138283. NULL,
  138284. 0
  138285. };
  138286. static long _vq_quantlist__44c0_sm_p7_0[] = {
  138287. 6,
  138288. 5,
  138289. 7,
  138290. 4,
  138291. 8,
  138292. 3,
  138293. 9,
  138294. 2,
  138295. 10,
  138296. 1,
  138297. 11,
  138298. 0,
  138299. 12,
  138300. };
  138301. static long _vq_lengthlist__44c0_sm_p7_0[] = {
  138302. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  138303. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 6, 5, 7, 7, 8,
  138304. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  138305. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  138306. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  138307. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0, 9,10,
  138308. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10, 9, 9,11,
  138309. 11,12,12,12,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  138310. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  138311. 0, 0, 0, 0,11,12,11,11,13,12,13,13, 0, 0, 0, 0,
  138312. 0,12,12,11,11,13,12,14,14,
  138313. };
  138314. static float _vq_quantthresh__44c0_sm_p7_0[] = {
  138315. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  138316. 12.5, 17.5, 22.5, 27.5,
  138317. };
  138318. static long _vq_quantmap__44c0_sm_p7_0[] = {
  138319. 11, 9, 7, 5, 3, 1, 0, 2,
  138320. 4, 6, 8, 10, 12,
  138321. };
  138322. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_0 = {
  138323. _vq_quantthresh__44c0_sm_p7_0,
  138324. _vq_quantmap__44c0_sm_p7_0,
  138325. 13,
  138326. 13
  138327. };
  138328. static static_codebook _44c0_sm_p7_0 = {
  138329. 2, 169,
  138330. _vq_lengthlist__44c0_sm_p7_0,
  138331. 1, -526516224, 1616117760, 4, 0,
  138332. _vq_quantlist__44c0_sm_p7_0,
  138333. NULL,
  138334. &_vq_auxt__44c0_sm_p7_0,
  138335. NULL,
  138336. 0
  138337. };
  138338. static long _vq_quantlist__44c0_sm_p7_1[] = {
  138339. 2,
  138340. 1,
  138341. 3,
  138342. 0,
  138343. 4,
  138344. };
  138345. static long _vq_lengthlist__44c0_sm_p7_1[] = {
  138346. 2, 4, 4, 4, 4, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  138347. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  138348. };
  138349. static float _vq_quantthresh__44c0_sm_p7_1[] = {
  138350. -1.5, -0.5, 0.5, 1.5,
  138351. };
  138352. static long _vq_quantmap__44c0_sm_p7_1[] = {
  138353. 3, 1, 0, 2, 4,
  138354. };
  138355. static encode_aux_threshmatch _vq_auxt__44c0_sm_p7_1 = {
  138356. _vq_quantthresh__44c0_sm_p7_1,
  138357. _vq_quantmap__44c0_sm_p7_1,
  138358. 5,
  138359. 5
  138360. };
  138361. static static_codebook _44c0_sm_p7_1 = {
  138362. 2, 25,
  138363. _vq_lengthlist__44c0_sm_p7_1,
  138364. 1, -533725184, 1611661312, 3, 0,
  138365. _vq_quantlist__44c0_sm_p7_1,
  138366. NULL,
  138367. &_vq_auxt__44c0_sm_p7_1,
  138368. NULL,
  138369. 0
  138370. };
  138371. static long _vq_quantlist__44c0_sm_p8_0[] = {
  138372. 4,
  138373. 3,
  138374. 5,
  138375. 2,
  138376. 6,
  138377. 1,
  138378. 7,
  138379. 0,
  138380. 8,
  138381. };
  138382. static long _vq_lengthlist__44c0_sm_p8_0[] = {
  138383. 1, 3, 3,11,11,11,11,11,11, 3, 7, 6,11,11,11,11,
  138384. 11,11, 4, 8, 7,11,11,11,11,11,11,11,11,11,11,11,
  138385. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  138386. 11,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138387. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  138388. 12,
  138389. };
  138390. static float _vq_quantthresh__44c0_sm_p8_0[] = {
  138391. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  138392. };
  138393. static long _vq_quantmap__44c0_sm_p8_0[] = {
  138394. 7, 5, 3, 1, 0, 2, 4, 6,
  138395. 8,
  138396. };
  138397. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_0 = {
  138398. _vq_quantthresh__44c0_sm_p8_0,
  138399. _vq_quantmap__44c0_sm_p8_0,
  138400. 9,
  138401. 9
  138402. };
  138403. static static_codebook _44c0_sm_p8_0 = {
  138404. 2, 81,
  138405. _vq_lengthlist__44c0_sm_p8_0,
  138406. 1, -516186112, 1627103232, 4, 0,
  138407. _vq_quantlist__44c0_sm_p8_0,
  138408. NULL,
  138409. &_vq_auxt__44c0_sm_p8_0,
  138410. NULL,
  138411. 0
  138412. };
  138413. static long _vq_quantlist__44c0_sm_p8_1[] = {
  138414. 6,
  138415. 5,
  138416. 7,
  138417. 4,
  138418. 8,
  138419. 3,
  138420. 9,
  138421. 2,
  138422. 10,
  138423. 1,
  138424. 11,
  138425. 0,
  138426. 12,
  138427. };
  138428. static long _vq_lengthlist__44c0_sm_p8_1[] = {
  138429. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  138430. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  138431. 8,10,10,12,11,12,12,17, 7, 7, 8, 8, 9, 9,10,10,
  138432. 12,12,13,13,18, 7, 7, 8, 7, 9, 9,10,10,12,12,12,
  138433. 13,19,10,10, 8, 8,10,10,11,11,12,12,13,14,19,11,
  138434. 10, 8, 7,10,10,11,11,12,12,13,12,19,19,19,10,10,
  138435. 10,10,11,11,12,12,13,13,19,19,19,11, 9,11, 9,14,
  138436. 12,13,12,13,13,19,20,18,13,14,11,11,12,12,13,13,
  138437. 14,13,20,20,20,15,13,11,10,13,11,13,13,14,13,20,
  138438. 20,20,20,20,13,14,12,12,13,13,13,13,20,20,20,20,
  138439. 20,13,13,12,12,16,13,15,13,
  138440. };
  138441. static float _vq_quantthresh__44c0_sm_p8_1[] = {
  138442. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  138443. 42.5, 59.5, 76.5, 93.5,
  138444. };
  138445. static long _vq_quantmap__44c0_sm_p8_1[] = {
  138446. 11, 9, 7, 5, 3, 1, 0, 2,
  138447. 4, 6, 8, 10, 12,
  138448. };
  138449. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_1 = {
  138450. _vq_quantthresh__44c0_sm_p8_1,
  138451. _vq_quantmap__44c0_sm_p8_1,
  138452. 13,
  138453. 13
  138454. };
  138455. static static_codebook _44c0_sm_p8_1 = {
  138456. 2, 169,
  138457. _vq_lengthlist__44c0_sm_p8_1,
  138458. 1, -522616832, 1620115456, 4, 0,
  138459. _vq_quantlist__44c0_sm_p8_1,
  138460. NULL,
  138461. &_vq_auxt__44c0_sm_p8_1,
  138462. NULL,
  138463. 0
  138464. };
  138465. static long _vq_quantlist__44c0_sm_p8_2[] = {
  138466. 8,
  138467. 7,
  138468. 9,
  138469. 6,
  138470. 10,
  138471. 5,
  138472. 11,
  138473. 4,
  138474. 12,
  138475. 3,
  138476. 13,
  138477. 2,
  138478. 14,
  138479. 1,
  138480. 15,
  138481. 0,
  138482. 16,
  138483. };
  138484. static long _vq_lengthlist__44c0_sm_p8_2[] = {
  138485. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  138486. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  138487. 9, 9,10, 6, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  138488. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  138489. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  138490. 9,10, 9, 9,10,10,10,11, 8, 8, 8, 8, 9, 9, 9, 9,
  138491. 9, 9, 9,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  138492. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  138493. 9, 9, 9, 9, 9, 9,10,10,10,10,10,11,11, 8, 8, 9,
  138494. 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,11,11,11, 9, 9,
  138495. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,10,11,11, 9,
  138496. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,11,10,11,11,
  138497. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,10,11,11,
  138498. 11,11,11, 9, 9,10, 9, 9, 9, 9, 9, 9, 9,10,11,10,
  138499. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  138500. 11,11,11,11,11, 9,10, 9, 9, 9, 9, 9, 9, 9, 9,11,
  138501. 11,10,11,11,11,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  138502. 10,11,10,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  138503. 9,
  138504. };
  138505. static float _vq_quantthresh__44c0_sm_p8_2[] = {
  138506. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  138507. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  138508. };
  138509. static long _vq_quantmap__44c0_sm_p8_2[] = {
  138510. 15, 13, 11, 9, 7, 5, 3, 1,
  138511. 0, 2, 4, 6, 8, 10, 12, 14,
  138512. 16,
  138513. };
  138514. static encode_aux_threshmatch _vq_auxt__44c0_sm_p8_2 = {
  138515. _vq_quantthresh__44c0_sm_p8_2,
  138516. _vq_quantmap__44c0_sm_p8_2,
  138517. 17,
  138518. 17
  138519. };
  138520. static static_codebook _44c0_sm_p8_2 = {
  138521. 2, 289,
  138522. _vq_lengthlist__44c0_sm_p8_2,
  138523. 1, -529530880, 1611661312, 5, 0,
  138524. _vq_quantlist__44c0_sm_p8_2,
  138525. NULL,
  138526. &_vq_auxt__44c0_sm_p8_2,
  138527. NULL,
  138528. 0
  138529. };
  138530. static long _huff_lengthlist__44c0_sm_short[] = {
  138531. 6, 6,12,13,13,14,16,17,17, 4, 2, 5, 8, 7, 9,12,
  138532. 15,15, 9, 4, 5, 9, 7, 9,12,16,18,11, 6, 7, 4, 6,
  138533. 8,11,14,18,10, 5, 6, 5, 5, 7,10,14,17,10, 5, 7,
  138534. 7, 6, 7,10,13,16,11, 5, 7, 7, 7, 8,10,12,15,13,
  138535. 6, 7, 5, 5, 7, 9,12,13,16, 8, 9, 6, 6, 7, 9,10,
  138536. 12,
  138537. };
  138538. static static_codebook _huff_book__44c0_sm_short = {
  138539. 2, 81,
  138540. _huff_lengthlist__44c0_sm_short,
  138541. 0, 0, 0, 0, 0,
  138542. NULL,
  138543. NULL,
  138544. NULL,
  138545. NULL,
  138546. 0
  138547. };
  138548. static long _huff_lengthlist__44c1_s_long[] = {
  138549. 5, 5, 9,10, 9, 9,10,11,12, 5, 1, 5, 6, 6, 7,10,
  138550. 12,14, 9, 5, 6, 8, 8,10,12,14,14,10, 5, 8, 5, 6,
  138551. 8,11,13,14, 9, 5, 7, 6, 6, 8,10,12,11, 9, 7, 9,
  138552. 7, 6, 6, 7,10,10,10, 9,12, 9, 8, 7, 7,10,12,11,
  138553. 11,13,12,10, 9, 8, 9,11,11,14,15,15,13,11, 9, 9,
  138554. 11,
  138555. };
  138556. static static_codebook _huff_book__44c1_s_long = {
  138557. 2, 81,
  138558. _huff_lengthlist__44c1_s_long,
  138559. 0, 0, 0, 0, 0,
  138560. NULL,
  138561. NULL,
  138562. NULL,
  138563. NULL,
  138564. 0
  138565. };
  138566. static long _vq_quantlist__44c1_s_p1_0[] = {
  138567. 1,
  138568. 0,
  138569. 2,
  138570. };
  138571. static long _vq_lengthlist__44c1_s_p1_0[] = {
  138572. 2, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 6, 0, 0, 0, 0,
  138573. 0, 0, 5, 6, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138574. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138575. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138576. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138577. 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138578. 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138579. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138580. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138581. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138582. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138583. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138584. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138585. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138586. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138587. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138588. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138589. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138590. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138591. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138592. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138593. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138594. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138595. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138596. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138597. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138598. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138599. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138600. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138601. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138602. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138603. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138604. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138605. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138609. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138610. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138614. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138615. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 7, 7, 0, 0, 0, 0,
  138618. 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0, 0,
  138623. 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0,
  138624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 8, 8, 0, 0,
  138628. 0, 0, 0, 0, 8, 9, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138663. 0, 0, 4, 7, 7, 0, 0, 0, 0, 0, 0, 7, 8, 8, 0, 0,
  138664. 0, 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138668. 0, 0, 0, 6, 8, 8, 0, 0, 0, 0, 0, 0, 8,10, 9, 0,
  138669. 0, 0, 0, 0, 0, 8, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0,
  138670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138673. 0, 0, 0, 0, 7, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9,
  138674. 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  138675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  138982. 0,
  138983. };
  138984. static float _vq_quantthresh__44c1_s_p1_0[] = {
  138985. -0.5, 0.5,
  138986. };
  138987. static long _vq_quantmap__44c1_s_p1_0[] = {
  138988. 1, 0, 2,
  138989. };
  138990. static encode_aux_threshmatch _vq_auxt__44c1_s_p1_0 = {
  138991. _vq_quantthresh__44c1_s_p1_0,
  138992. _vq_quantmap__44c1_s_p1_0,
  138993. 3,
  138994. 3
  138995. };
  138996. static static_codebook _44c1_s_p1_0 = {
  138997. 8, 6561,
  138998. _vq_lengthlist__44c1_s_p1_0,
  138999. 1, -535822336, 1611661312, 2, 0,
  139000. _vq_quantlist__44c1_s_p1_0,
  139001. NULL,
  139002. &_vq_auxt__44c1_s_p1_0,
  139003. NULL,
  139004. 0
  139005. };
  139006. static long _vq_quantlist__44c1_s_p2_0[] = {
  139007. 2,
  139008. 1,
  139009. 3,
  139010. 0,
  139011. 4,
  139012. };
  139013. static long _vq_lengthlist__44c1_s_p2_0[] = {
  139014. 2, 3, 4, 6, 5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  139016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139017. 0, 0, 4, 4, 5, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 8, 8,
  139019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139020. 0, 0, 0, 0, 6, 6, 6, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  139021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139053. 0,
  139054. };
  139055. static float _vq_quantthresh__44c1_s_p2_0[] = {
  139056. -1.5, -0.5, 0.5, 1.5,
  139057. };
  139058. static long _vq_quantmap__44c1_s_p2_0[] = {
  139059. 3, 1, 0, 2, 4,
  139060. };
  139061. static encode_aux_threshmatch _vq_auxt__44c1_s_p2_0 = {
  139062. _vq_quantthresh__44c1_s_p2_0,
  139063. _vq_quantmap__44c1_s_p2_0,
  139064. 5,
  139065. 5
  139066. };
  139067. static static_codebook _44c1_s_p2_0 = {
  139068. 4, 625,
  139069. _vq_lengthlist__44c1_s_p2_0,
  139070. 1, -533725184, 1611661312, 3, 0,
  139071. _vq_quantlist__44c1_s_p2_0,
  139072. NULL,
  139073. &_vq_auxt__44c1_s_p2_0,
  139074. NULL,
  139075. 0
  139076. };
  139077. static long _vq_quantlist__44c1_s_p3_0[] = {
  139078. 4,
  139079. 3,
  139080. 5,
  139081. 2,
  139082. 6,
  139083. 1,
  139084. 7,
  139085. 0,
  139086. 8,
  139087. };
  139088. static long _vq_lengthlist__44c1_s_p3_0[] = {
  139089. 1, 3, 2, 7, 7, 0, 0, 0, 0, 0,13,13, 6, 6, 0, 0,
  139090. 0, 0, 0,12, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  139091. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  139092. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  139093. 0, 0,11,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139094. 0,
  139095. };
  139096. static float _vq_quantthresh__44c1_s_p3_0[] = {
  139097. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139098. };
  139099. static long _vq_quantmap__44c1_s_p3_0[] = {
  139100. 7, 5, 3, 1, 0, 2, 4, 6,
  139101. 8,
  139102. };
  139103. static encode_aux_threshmatch _vq_auxt__44c1_s_p3_0 = {
  139104. _vq_quantthresh__44c1_s_p3_0,
  139105. _vq_quantmap__44c1_s_p3_0,
  139106. 9,
  139107. 9
  139108. };
  139109. static static_codebook _44c1_s_p3_0 = {
  139110. 2, 81,
  139111. _vq_lengthlist__44c1_s_p3_0,
  139112. 1, -531628032, 1611661312, 4, 0,
  139113. _vq_quantlist__44c1_s_p3_0,
  139114. NULL,
  139115. &_vq_auxt__44c1_s_p3_0,
  139116. NULL,
  139117. 0
  139118. };
  139119. static long _vq_quantlist__44c1_s_p4_0[] = {
  139120. 4,
  139121. 3,
  139122. 5,
  139123. 2,
  139124. 6,
  139125. 1,
  139126. 7,
  139127. 0,
  139128. 8,
  139129. };
  139130. static long _vq_lengthlist__44c1_s_p4_0[] = {
  139131. 1, 3, 3, 6, 5, 6, 6, 8, 8, 0, 0, 0, 7, 7, 7, 7,
  139132. 9, 9, 0, 0, 0, 7, 7, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  139133. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  139134. 9, 9, 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0,
  139135. 0, 0,10,10, 9, 9,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  139136. 11,
  139137. };
  139138. static float _vq_quantthresh__44c1_s_p4_0[] = {
  139139. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  139140. };
  139141. static long _vq_quantmap__44c1_s_p4_0[] = {
  139142. 7, 5, 3, 1, 0, 2, 4, 6,
  139143. 8,
  139144. };
  139145. static encode_aux_threshmatch _vq_auxt__44c1_s_p4_0 = {
  139146. _vq_quantthresh__44c1_s_p4_0,
  139147. _vq_quantmap__44c1_s_p4_0,
  139148. 9,
  139149. 9
  139150. };
  139151. static static_codebook _44c1_s_p4_0 = {
  139152. 2, 81,
  139153. _vq_lengthlist__44c1_s_p4_0,
  139154. 1, -531628032, 1611661312, 4, 0,
  139155. _vq_quantlist__44c1_s_p4_0,
  139156. NULL,
  139157. &_vq_auxt__44c1_s_p4_0,
  139158. NULL,
  139159. 0
  139160. };
  139161. static long _vq_quantlist__44c1_s_p5_0[] = {
  139162. 8,
  139163. 7,
  139164. 9,
  139165. 6,
  139166. 10,
  139167. 5,
  139168. 11,
  139169. 4,
  139170. 12,
  139171. 3,
  139172. 13,
  139173. 2,
  139174. 14,
  139175. 1,
  139176. 15,
  139177. 0,
  139178. 16,
  139179. };
  139180. static long _vq_lengthlist__44c1_s_p5_0[] = {
  139181. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  139182. 11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  139183. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  139184. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  139185. 11,11,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  139186. 10,11,11,12,11, 0, 0, 0, 8, 8, 9, 9, 9,10,10,10,
  139187. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10, 9,10,
  139188. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  139189. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  139190. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  139191. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  139192. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  139193. 10,10,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  139194. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  139195. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,13, 0, 0,
  139196. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  139197. 0, 0, 0, 0, 0, 0,12,12,12,12,12,12,13,13,14,14,
  139198. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  139199. 14,
  139200. };
  139201. static float _vq_quantthresh__44c1_s_p5_0[] = {
  139202. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139203. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139204. };
  139205. static long _vq_quantmap__44c1_s_p5_0[] = {
  139206. 15, 13, 11, 9, 7, 5, 3, 1,
  139207. 0, 2, 4, 6, 8, 10, 12, 14,
  139208. 16,
  139209. };
  139210. static encode_aux_threshmatch _vq_auxt__44c1_s_p5_0 = {
  139211. _vq_quantthresh__44c1_s_p5_0,
  139212. _vq_quantmap__44c1_s_p5_0,
  139213. 17,
  139214. 17
  139215. };
  139216. static static_codebook _44c1_s_p5_0 = {
  139217. 2, 289,
  139218. _vq_lengthlist__44c1_s_p5_0,
  139219. 1, -529530880, 1611661312, 5, 0,
  139220. _vq_quantlist__44c1_s_p5_0,
  139221. NULL,
  139222. &_vq_auxt__44c1_s_p5_0,
  139223. NULL,
  139224. 0
  139225. };
  139226. static long _vq_quantlist__44c1_s_p6_0[] = {
  139227. 1,
  139228. 0,
  139229. 2,
  139230. };
  139231. static long _vq_lengthlist__44c1_s_p6_0[] = {
  139232. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  139233. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 6,10,10,11,11,
  139234. 11,11,10,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  139235. 11,10,11,11,10,10, 7,11,10,11,11,11,12,11,11, 7,
  139236. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,12,10,
  139237. 11,
  139238. };
  139239. static float _vq_quantthresh__44c1_s_p6_0[] = {
  139240. -5.5, 5.5,
  139241. };
  139242. static long _vq_quantmap__44c1_s_p6_0[] = {
  139243. 1, 0, 2,
  139244. };
  139245. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_0 = {
  139246. _vq_quantthresh__44c1_s_p6_0,
  139247. _vq_quantmap__44c1_s_p6_0,
  139248. 3,
  139249. 3
  139250. };
  139251. static static_codebook _44c1_s_p6_0 = {
  139252. 4, 81,
  139253. _vq_lengthlist__44c1_s_p6_0,
  139254. 1, -529137664, 1618345984, 2, 0,
  139255. _vq_quantlist__44c1_s_p6_0,
  139256. NULL,
  139257. &_vq_auxt__44c1_s_p6_0,
  139258. NULL,
  139259. 0
  139260. };
  139261. static long _vq_quantlist__44c1_s_p6_1[] = {
  139262. 5,
  139263. 4,
  139264. 6,
  139265. 3,
  139266. 7,
  139267. 2,
  139268. 8,
  139269. 1,
  139270. 9,
  139271. 0,
  139272. 10,
  139273. };
  139274. static long _vq_lengthlist__44c1_s_p6_1[] = {
  139275. 2, 3, 3, 6, 6, 7, 7, 7, 7, 8, 8,10,10,10, 6, 6,
  139276. 7, 7, 8, 8, 8, 8,10,10,10, 6, 6, 7, 7, 8, 8, 8,
  139277. 8,10,10,10, 7, 7, 7, 7, 8, 8, 8, 8,10,10,10, 7,
  139278. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  139279. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  139280. 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,10,10, 8, 8, 8,
  139281. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  139282. 10,10,10, 8, 8, 8, 8, 8, 8,
  139283. };
  139284. static float _vq_quantthresh__44c1_s_p6_1[] = {
  139285. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  139286. 3.5, 4.5,
  139287. };
  139288. static long _vq_quantmap__44c1_s_p6_1[] = {
  139289. 9, 7, 5, 3, 1, 0, 2, 4,
  139290. 6, 8, 10,
  139291. };
  139292. static encode_aux_threshmatch _vq_auxt__44c1_s_p6_1 = {
  139293. _vq_quantthresh__44c1_s_p6_1,
  139294. _vq_quantmap__44c1_s_p6_1,
  139295. 11,
  139296. 11
  139297. };
  139298. static static_codebook _44c1_s_p6_1 = {
  139299. 2, 121,
  139300. _vq_lengthlist__44c1_s_p6_1,
  139301. 1, -531365888, 1611661312, 4, 0,
  139302. _vq_quantlist__44c1_s_p6_1,
  139303. NULL,
  139304. &_vq_auxt__44c1_s_p6_1,
  139305. NULL,
  139306. 0
  139307. };
  139308. static long _vq_quantlist__44c1_s_p7_0[] = {
  139309. 6,
  139310. 5,
  139311. 7,
  139312. 4,
  139313. 8,
  139314. 3,
  139315. 9,
  139316. 2,
  139317. 10,
  139318. 1,
  139319. 11,
  139320. 0,
  139321. 12,
  139322. };
  139323. static long _vq_lengthlist__44c1_s_p7_0[] = {
  139324. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 9, 7, 5, 6,
  139325. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 5, 7, 7, 8,
  139326. 8, 8, 8, 9, 9,10,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  139327. 10,10,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  139328. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,11, 0,13,
  139329. 13, 9, 9, 9, 9,10,10,11,11,11,11, 0, 0, 0,10,10,
  139330. 10,10,11,11,12,11,12,12, 0, 0, 0,10,10,10, 9,11,
  139331. 11,12,11,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  139332. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  139333. 0, 0, 0, 0,11,12,11,11,12,12,14,13, 0, 0, 0, 0,
  139334. 0,12,11,11,11,13,10,14,13,
  139335. };
  139336. static float _vq_quantthresh__44c1_s_p7_0[] = {
  139337. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  139338. 12.5, 17.5, 22.5, 27.5,
  139339. };
  139340. static long _vq_quantmap__44c1_s_p7_0[] = {
  139341. 11, 9, 7, 5, 3, 1, 0, 2,
  139342. 4, 6, 8, 10, 12,
  139343. };
  139344. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_0 = {
  139345. _vq_quantthresh__44c1_s_p7_0,
  139346. _vq_quantmap__44c1_s_p7_0,
  139347. 13,
  139348. 13
  139349. };
  139350. static static_codebook _44c1_s_p7_0 = {
  139351. 2, 169,
  139352. _vq_lengthlist__44c1_s_p7_0,
  139353. 1, -526516224, 1616117760, 4, 0,
  139354. _vq_quantlist__44c1_s_p7_0,
  139355. NULL,
  139356. &_vq_auxt__44c1_s_p7_0,
  139357. NULL,
  139358. 0
  139359. };
  139360. static long _vq_quantlist__44c1_s_p7_1[] = {
  139361. 2,
  139362. 1,
  139363. 3,
  139364. 0,
  139365. 4,
  139366. };
  139367. static long _vq_lengthlist__44c1_s_p7_1[] = {
  139368. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  139369. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  139370. };
  139371. static float _vq_quantthresh__44c1_s_p7_1[] = {
  139372. -1.5, -0.5, 0.5, 1.5,
  139373. };
  139374. static long _vq_quantmap__44c1_s_p7_1[] = {
  139375. 3, 1, 0, 2, 4,
  139376. };
  139377. static encode_aux_threshmatch _vq_auxt__44c1_s_p7_1 = {
  139378. _vq_quantthresh__44c1_s_p7_1,
  139379. _vq_quantmap__44c1_s_p7_1,
  139380. 5,
  139381. 5
  139382. };
  139383. static static_codebook _44c1_s_p7_1 = {
  139384. 2, 25,
  139385. _vq_lengthlist__44c1_s_p7_1,
  139386. 1, -533725184, 1611661312, 3, 0,
  139387. _vq_quantlist__44c1_s_p7_1,
  139388. NULL,
  139389. &_vq_auxt__44c1_s_p7_1,
  139390. NULL,
  139391. 0
  139392. };
  139393. static long _vq_quantlist__44c1_s_p8_0[] = {
  139394. 6,
  139395. 5,
  139396. 7,
  139397. 4,
  139398. 8,
  139399. 3,
  139400. 9,
  139401. 2,
  139402. 10,
  139403. 1,
  139404. 11,
  139405. 0,
  139406. 12,
  139407. };
  139408. static long _vq_lengthlist__44c1_s_p8_0[] = {
  139409. 1, 4, 3,10,10,10,10,10,10,10,10,10,10, 4, 8, 6,
  139410. 10,10,10,10,10,10,10,10,10,10, 4, 8, 7,10,10,10,
  139411. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139412. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139413. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139414. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139415. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139416. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139417. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139418. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  139419. 10,10,10,10,10,10,10,10,10,
  139420. };
  139421. static float _vq_quantthresh__44c1_s_p8_0[] = {
  139422. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  139423. 552.5, 773.5, 994.5, 1215.5,
  139424. };
  139425. static long _vq_quantmap__44c1_s_p8_0[] = {
  139426. 11, 9, 7, 5, 3, 1, 0, 2,
  139427. 4, 6, 8, 10, 12,
  139428. };
  139429. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_0 = {
  139430. _vq_quantthresh__44c1_s_p8_0,
  139431. _vq_quantmap__44c1_s_p8_0,
  139432. 13,
  139433. 13
  139434. };
  139435. static static_codebook _44c1_s_p8_0 = {
  139436. 2, 169,
  139437. _vq_lengthlist__44c1_s_p8_0,
  139438. 1, -514541568, 1627103232, 4, 0,
  139439. _vq_quantlist__44c1_s_p8_0,
  139440. NULL,
  139441. &_vq_auxt__44c1_s_p8_0,
  139442. NULL,
  139443. 0
  139444. };
  139445. static long _vq_quantlist__44c1_s_p8_1[] = {
  139446. 6,
  139447. 5,
  139448. 7,
  139449. 4,
  139450. 8,
  139451. 3,
  139452. 9,
  139453. 2,
  139454. 10,
  139455. 1,
  139456. 11,
  139457. 0,
  139458. 12,
  139459. };
  139460. static long _vq_lengthlist__44c1_s_p8_1[] = {
  139461. 1, 4, 4, 6, 5, 7, 7, 9, 9,10,10,12,12, 6, 5, 5,
  139462. 7, 7, 8, 8,10,10,12,11,12,12, 6, 5, 5, 7, 7, 8,
  139463. 8,10,10,11,11,12,12,15, 7, 7, 8, 8, 9, 9,11,11,
  139464. 12,12,13,12,15, 8, 8, 8, 7, 9, 9,10,10,12,12,13,
  139465. 13,16,11,10, 8, 8,10,10,11,11,12,12,13,13,16,11,
  139466. 11, 9, 8,11,10,11,11,12,12,13,12,16,16,16,10,11,
  139467. 10,11,12,12,12,12,13,13,16,16,16,11, 9,11, 9,14,
  139468. 12,12,12,13,13,16,16,16,12,14,11,12,12,12,13,13,
  139469. 14,13,16,16,16,15,13,12,10,13,10,13,14,13,13,16,
  139470. 16,16,16,16,13,14,12,13,13,12,13,13,16,16,16,16,
  139471. 16,13,12,12,11,14,12,15,13,
  139472. };
  139473. static float _vq_quantthresh__44c1_s_p8_1[] = {
  139474. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  139475. 42.5, 59.5, 76.5, 93.5,
  139476. };
  139477. static long _vq_quantmap__44c1_s_p8_1[] = {
  139478. 11, 9, 7, 5, 3, 1, 0, 2,
  139479. 4, 6, 8, 10, 12,
  139480. };
  139481. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_1 = {
  139482. _vq_quantthresh__44c1_s_p8_1,
  139483. _vq_quantmap__44c1_s_p8_1,
  139484. 13,
  139485. 13
  139486. };
  139487. static static_codebook _44c1_s_p8_1 = {
  139488. 2, 169,
  139489. _vq_lengthlist__44c1_s_p8_1,
  139490. 1, -522616832, 1620115456, 4, 0,
  139491. _vq_quantlist__44c1_s_p8_1,
  139492. NULL,
  139493. &_vq_auxt__44c1_s_p8_1,
  139494. NULL,
  139495. 0
  139496. };
  139497. static long _vq_quantlist__44c1_s_p8_2[] = {
  139498. 8,
  139499. 7,
  139500. 9,
  139501. 6,
  139502. 10,
  139503. 5,
  139504. 11,
  139505. 4,
  139506. 12,
  139507. 3,
  139508. 13,
  139509. 2,
  139510. 14,
  139511. 1,
  139512. 15,
  139513. 0,
  139514. 16,
  139515. };
  139516. static long _vq_lengthlist__44c1_s_p8_2[] = {
  139517. 2, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  139518. 8,10,10,10, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  139519. 9, 9,10,10,10, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  139520. 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  139521. 9,10, 9, 9,10,10,10, 7, 7, 8, 8, 9, 8, 9, 9, 9,
  139522. 9,10, 9, 9,10,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  139523. 9, 9,10, 9, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  139524. 9, 9, 9, 9, 9,10,10,11,11,11, 8, 8, 9, 9, 9, 9,
  139525. 9, 9, 9, 9, 9, 9,10,10,10,10,11,11,11, 8, 8, 9,
  139526. 9, 9, 9,10, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  139527. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 9,
  139528. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  139529. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10,11,11,
  139530. 11,11,11, 9, 9, 9,10, 9, 9, 9, 9, 9, 9,10,11,11,
  139531. 11,11,11,11,10,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  139532. 11,11,11,11,11, 9,10, 9, 9, 9, 9,10, 9, 9, 9,11,
  139533. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  139534. 11,11,10,11,11,11,11,10,11, 9, 9, 9, 9, 9, 9, 9,
  139535. 9,
  139536. };
  139537. static float _vq_quantthresh__44c1_s_p8_2[] = {
  139538. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  139539. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  139540. };
  139541. static long _vq_quantmap__44c1_s_p8_2[] = {
  139542. 15, 13, 11, 9, 7, 5, 3, 1,
  139543. 0, 2, 4, 6, 8, 10, 12, 14,
  139544. 16,
  139545. };
  139546. static encode_aux_threshmatch _vq_auxt__44c1_s_p8_2 = {
  139547. _vq_quantthresh__44c1_s_p8_2,
  139548. _vq_quantmap__44c1_s_p8_2,
  139549. 17,
  139550. 17
  139551. };
  139552. static static_codebook _44c1_s_p8_2 = {
  139553. 2, 289,
  139554. _vq_lengthlist__44c1_s_p8_2,
  139555. 1, -529530880, 1611661312, 5, 0,
  139556. _vq_quantlist__44c1_s_p8_2,
  139557. NULL,
  139558. &_vq_auxt__44c1_s_p8_2,
  139559. NULL,
  139560. 0
  139561. };
  139562. static long _huff_lengthlist__44c1_s_short[] = {
  139563. 6, 8,13,12,13,14,15,16,16, 4, 2, 4, 7, 6, 8,11,
  139564. 13,15,10, 4, 4, 8, 6, 8,11,14,17,11, 5, 6, 5, 6,
  139565. 8,12,14,17,11, 5, 5, 6, 5, 7,10,13,16,12, 6, 7,
  139566. 8, 7, 8,10,13,15,13, 8, 8, 7, 7, 8,10,12,15,15,
  139567. 7, 7, 5, 5, 7, 9,12,14,15, 8, 8, 6, 6, 7, 8,10,
  139568. 11,
  139569. };
  139570. static static_codebook _huff_book__44c1_s_short = {
  139571. 2, 81,
  139572. _huff_lengthlist__44c1_s_short,
  139573. 0, 0, 0, 0, 0,
  139574. NULL,
  139575. NULL,
  139576. NULL,
  139577. NULL,
  139578. 0
  139579. };
  139580. static long _huff_lengthlist__44c1_sm_long[] = {
  139581. 5, 4, 8,10, 9, 9,10,11,12, 4, 2, 5, 6, 6, 8,10,
  139582. 11,13, 8, 4, 6, 8, 7, 9,12,12,14,10, 6, 8, 4, 5,
  139583. 6, 9,11,12, 9, 5, 6, 5, 5, 6, 9,11,11, 9, 7, 9,
  139584. 6, 5, 5, 7,10,10,10, 9,11, 8, 7, 6, 7, 9,11,11,
  139585. 12,13,10,10, 9, 8, 9,11,11,15,15,12,13,11, 9,10,
  139586. 11,
  139587. };
  139588. static static_codebook _huff_book__44c1_sm_long = {
  139589. 2, 81,
  139590. _huff_lengthlist__44c1_sm_long,
  139591. 0, 0, 0, 0, 0,
  139592. NULL,
  139593. NULL,
  139594. NULL,
  139595. NULL,
  139596. 0
  139597. };
  139598. static long _vq_quantlist__44c1_sm_p1_0[] = {
  139599. 1,
  139600. 0,
  139601. 2,
  139602. };
  139603. static long _vq_lengthlist__44c1_sm_p1_0[] = {
  139604. 1, 5, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  139605. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139606. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139607. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139608. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139609. 0, 5, 8, 7, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139610. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139611. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139612. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139613. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139614. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  139615. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139616. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139617. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139618. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139619. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139620. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139621. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139622. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139623. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139624. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139625. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139626. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139627. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139628. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139629. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139630. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139631. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139632. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139633. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139634. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139635. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139636. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139637. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139641. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139642. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139646. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139647. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 7, 0, 0, 0, 0,
  139650. 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0, 0,
  139655. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  139660. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139682. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139687. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139692. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139695. 0, 0, 5, 7, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  139696. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139700. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  139701. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  139702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139705. 0, 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  139706. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  139707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139733. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139738. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  139999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140014. 0,
  140015. };
  140016. static float _vq_quantthresh__44c1_sm_p1_0[] = {
  140017. -0.5, 0.5,
  140018. };
  140019. static long _vq_quantmap__44c1_sm_p1_0[] = {
  140020. 1, 0, 2,
  140021. };
  140022. static encode_aux_threshmatch _vq_auxt__44c1_sm_p1_0 = {
  140023. _vq_quantthresh__44c1_sm_p1_0,
  140024. _vq_quantmap__44c1_sm_p1_0,
  140025. 3,
  140026. 3
  140027. };
  140028. static static_codebook _44c1_sm_p1_0 = {
  140029. 8, 6561,
  140030. _vq_lengthlist__44c1_sm_p1_0,
  140031. 1, -535822336, 1611661312, 2, 0,
  140032. _vq_quantlist__44c1_sm_p1_0,
  140033. NULL,
  140034. &_vq_auxt__44c1_sm_p1_0,
  140035. NULL,
  140036. 0
  140037. };
  140038. static long _vq_quantlist__44c1_sm_p2_0[] = {
  140039. 2,
  140040. 1,
  140041. 3,
  140042. 0,
  140043. 4,
  140044. };
  140045. static long _vq_lengthlist__44c1_sm_p2_0[] = {
  140046. 2, 3, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 6, 6, 0, 0,
  140048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140049. 0, 0, 4, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 6, 6, 9, 9,
  140051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140052. 0, 0, 0, 0, 6, 6, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  140053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140085. 0,
  140086. };
  140087. static float _vq_quantthresh__44c1_sm_p2_0[] = {
  140088. -1.5, -0.5, 0.5, 1.5,
  140089. };
  140090. static long _vq_quantmap__44c1_sm_p2_0[] = {
  140091. 3, 1, 0, 2, 4,
  140092. };
  140093. static encode_aux_threshmatch _vq_auxt__44c1_sm_p2_0 = {
  140094. _vq_quantthresh__44c1_sm_p2_0,
  140095. _vq_quantmap__44c1_sm_p2_0,
  140096. 5,
  140097. 5
  140098. };
  140099. static static_codebook _44c1_sm_p2_0 = {
  140100. 4, 625,
  140101. _vq_lengthlist__44c1_sm_p2_0,
  140102. 1, -533725184, 1611661312, 3, 0,
  140103. _vq_quantlist__44c1_sm_p2_0,
  140104. NULL,
  140105. &_vq_auxt__44c1_sm_p2_0,
  140106. NULL,
  140107. 0
  140108. };
  140109. static long _vq_quantlist__44c1_sm_p3_0[] = {
  140110. 4,
  140111. 3,
  140112. 5,
  140113. 2,
  140114. 6,
  140115. 1,
  140116. 7,
  140117. 0,
  140118. 8,
  140119. };
  140120. static long _vq_lengthlist__44c1_sm_p3_0[] = {
  140121. 1, 3, 3, 7, 7, 0, 0, 0, 0, 0, 5, 5, 6, 6, 0, 0,
  140122. 0, 0, 0, 5, 5, 7, 7, 0, 0, 0, 0, 0, 7, 7, 7, 7,
  140123. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  140124. 8, 9, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  140125. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140126. 0,
  140127. };
  140128. static float _vq_quantthresh__44c1_sm_p3_0[] = {
  140129. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140130. };
  140131. static long _vq_quantmap__44c1_sm_p3_0[] = {
  140132. 7, 5, 3, 1, 0, 2, 4, 6,
  140133. 8,
  140134. };
  140135. static encode_aux_threshmatch _vq_auxt__44c1_sm_p3_0 = {
  140136. _vq_quantthresh__44c1_sm_p3_0,
  140137. _vq_quantmap__44c1_sm_p3_0,
  140138. 9,
  140139. 9
  140140. };
  140141. static static_codebook _44c1_sm_p3_0 = {
  140142. 2, 81,
  140143. _vq_lengthlist__44c1_sm_p3_0,
  140144. 1, -531628032, 1611661312, 4, 0,
  140145. _vq_quantlist__44c1_sm_p3_0,
  140146. NULL,
  140147. &_vq_auxt__44c1_sm_p3_0,
  140148. NULL,
  140149. 0
  140150. };
  140151. static long _vq_quantlist__44c1_sm_p4_0[] = {
  140152. 4,
  140153. 3,
  140154. 5,
  140155. 2,
  140156. 6,
  140157. 1,
  140158. 7,
  140159. 0,
  140160. 8,
  140161. };
  140162. static long _vq_lengthlist__44c1_sm_p4_0[] = {
  140163. 1, 3, 3, 6, 6, 7, 7, 9, 9, 0, 6, 6, 7, 7, 8, 8,
  140164. 9, 9, 0, 6, 6, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  140165. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  140166. 8, 8, 9, 9,11,11, 0, 0, 0, 9, 9, 9, 9,11,11, 0,
  140167. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0, 9, 9,11,
  140168. 11,
  140169. };
  140170. static float _vq_quantthresh__44c1_sm_p4_0[] = {
  140171. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  140172. };
  140173. static long _vq_quantmap__44c1_sm_p4_0[] = {
  140174. 7, 5, 3, 1, 0, 2, 4, 6,
  140175. 8,
  140176. };
  140177. static encode_aux_threshmatch _vq_auxt__44c1_sm_p4_0 = {
  140178. _vq_quantthresh__44c1_sm_p4_0,
  140179. _vq_quantmap__44c1_sm_p4_0,
  140180. 9,
  140181. 9
  140182. };
  140183. static static_codebook _44c1_sm_p4_0 = {
  140184. 2, 81,
  140185. _vq_lengthlist__44c1_sm_p4_0,
  140186. 1, -531628032, 1611661312, 4, 0,
  140187. _vq_quantlist__44c1_sm_p4_0,
  140188. NULL,
  140189. &_vq_auxt__44c1_sm_p4_0,
  140190. NULL,
  140191. 0
  140192. };
  140193. static long _vq_quantlist__44c1_sm_p5_0[] = {
  140194. 8,
  140195. 7,
  140196. 9,
  140197. 6,
  140198. 10,
  140199. 5,
  140200. 11,
  140201. 4,
  140202. 12,
  140203. 3,
  140204. 13,
  140205. 2,
  140206. 14,
  140207. 1,
  140208. 15,
  140209. 0,
  140210. 16,
  140211. };
  140212. static long _vq_lengthlist__44c1_sm_p5_0[] = {
  140213. 2, 3, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  140214. 11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,10,
  140215. 11,11, 0, 5, 5, 6, 6, 8, 8, 9, 9, 9, 9,10,10,10,
  140216. 10,11,11, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  140217. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  140218. 10,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,10,
  140219. 10,11,11,11,12,12, 0, 0, 0, 8, 8, 8, 8, 9, 9,10,
  140220. 10,10,10,11,11,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  140221. 10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  140222. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  140223. 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  140224. 9, 9, 9,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  140225. 9, 9,10,10,11,11,12,12,12,12,13,13, 0, 0, 0, 0,
  140226. 0, 0, 0,10,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  140227. 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0, 0,
  140228. 0, 0, 0, 0, 0,11,11,11,11,12,12,13,13,13,13, 0,
  140229. 0, 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,14,14,
  140230. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,12,12,13,13,14,
  140231. 14,
  140232. };
  140233. static float _vq_quantthresh__44c1_sm_p5_0[] = {
  140234. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140235. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140236. };
  140237. static long _vq_quantmap__44c1_sm_p5_0[] = {
  140238. 15, 13, 11, 9, 7, 5, 3, 1,
  140239. 0, 2, 4, 6, 8, 10, 12, 14,
  140240. 16,
  140241. };
  140242. static encode_aux_threshmatch _vq_auxt__44c1_sm_p5_0 = {
  140243. _vq_quantthresh__44c1_sm_p5_0,
  140244. _vq_quantmap__44c1_sm_p5_0,
  140245. 17,
  140246. 17
  140247. };
  140248. static static_codebook _44c1_sm_p5_0 = {
  140249. 2, 289,
  140250. _vq_lengthlist__44c1_sm_p5_0,
  140251. 1, -529530880, 1611661312, 5, 0,
  140252. _vq_quantlist__44c1_sm_p5_0,
  140253. NULL,
  140254. &_vq_auxt__44c1_sm_p5_0,
  140255. NULL,
  140256. 0
  140257. };
  140258. static long _vq_quantlist__44c1_sm_p6_0[] = {
  140259. 1,
  140260. 0,
  140261. 2,
  140262. };
  140263. static long _vq_lengthlist__44c1_sm_p6_0[] = {
  140264. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 7,10, 9, 9,11,
  140265. 9, 9, 4, 7, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  140266. 11,11,10,10, 6, 9, 9,11,11,10,11,10,10, 6, 9, 9,
  140267. 11,10,11,11,10,10, 7,11,11,11,11,11,11,11,11, 6,
  140268. 9, 9,11,10,10,11,11,10, 6, 9, 9,10,10,10,11,10,
  140269. 11,
  140270. };
  140271. static float _vq_quantthresh__44c1_sm_p6_0[] = {
  140272. -5.5, 5.5,
  140273. };
  140274. static long _vq_quantmap__44c1_sm_p6_0[] = {
  140275. 1, 0, 2,
  140276. };
  140277. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_0 = {
  140278. _vq_quantthresh__44c1_sm_p6_0,
  140279. _vq_quantmap__44c1_sm_p6_0,
  140280. 3,
  140281. 3
  140282. };
  140283. static static_codebook _44c1_sm_p6_0 = {
  140284. 4, 81,
  140285. _vq_lengthlist__44c1_sm_p6_0,
  140286. 1, -529137664, 1618345984, 2, 0,
  140287. _vq_quantlist__44c1_sm_p6_0,
  140288. NULL,
  140289. &_vq_auxt__44c1_sm_p6_0,
  140290. NULL,
  140291. 0
  140292. };
  140293. static long _vq_quantlist__44c1_sm_p6_1[] = {
  140294. 5,
  140295. 4,
  140296. 6,
  140297. 3,
  140298. 7,
  140299. 2,
  140300. 8,
  140301. 1,
  140302. 9,
  140303. 0,
  140304. 10,
  140305. };
  140306. static long _vq_lengthlist__44c1_sm_p6_1[] = {
  140307. 2, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  140308. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  140309. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  140310. 7, 7, 7, 8, 8, 8, 8,10,10,10, 7, 7, 8, 8, 8, 8,
  140311. 8, 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10,
  140312. 8, 8, 8, 8, 8, 8, 9, 8,10,10,10,10,10, 8, 8, 8,
  140313. 8, 8, 8,10,10,10,10,10, 9, 9, 8, 8, 8, 8,10,10,
  140314. 10,10,10, 8, 8, 8, 8, 8, 8,
  140315. };
  140316. static float _vq_quantthresh__44c1_sm_p6_1[] = {
  140317. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  140318. 3.5, 4.5,
  140319. };
  140320. static long _vq_quantmap__44c1_sm_p6_1[] = {
  140321. 9, 7, 5, 3, 1, 0, 2, 4,
  140322. 6, 8, 10,
  140323. };
  140324. static encode_aux_threshmatch _vq_auxt__44c1_sm_p6_1 = {
  140325. _vq_quantthresh__44c1_sm_p6_1,
  140326. _vq_quantmap__44c1_sm_p6_1,
  140327. 11,
  140328. 11
  140329. };
  140330. static static_codebook _44c1_sm_p6_1 = {
  140331. 2, 121,
  140332. _vq_lengthlist__44c1_sm_p6_1,
  140333. 1, -531365888, 1611661312, 4, 0,
  140334. _vq_quantlist__44c1_sm_p6_1,
  140335. NULL,
  140336. &_vq_auxt__44c1_sm_p6_1,
  140337. NULL,
  140338. 0
  140339. };
  140340. static long _vq_quantlist__44c1_sm_p7_0[] = {
  140341. 6,
  140342. 5,
  140343. 7,
  140344. 4,
  140345. 8,
  140346. 3,
  140347. 9,
  140348. 2,
  140349. 10,
  140350. 1,
  140351. 11,
  140352. 0,
  140353. 12,
  140354. };
  140355. static long _vq_lengthlist__44c1_sm_p7_0[] = {
  140356. 1, 4, 4, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 7, 5, 5,
  140357. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 7, 5, 6, 7, 7, 8,
  140358. 8, 8, 8, 9, 9,11,10, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  140359. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  140360. 11, 0,12,12, 9, 9,10,10,10,10,11,11,11,11, 0,13,
  140361. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0, 9,10,
  140362. 9,10,11,11,12,11,13,12, 0, 0, 0,10,10, 9, 9,11,
  140363. 11,12,12,13,12, 0, 0, 0,13,13,10,10,11,11,12,12,
  140364. 13,13, 0, 0, 0,14,14,10,10,11,11,12,12,13,13, 0,
  140365. 0, 0, 0, 0,11,12,11,11,12,13,14,13, 0, 0, 0, 0,
  140366. 0,12,12,11,11,13,12,14,13,
  140367. };
  140368. static float _vq_quantthresh__44c1_sm_p7_0[] = {
  140369. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  140370. 12.5, 17.5, 22.5, 27.5,
  140371. };
  140372. static long _vq_quantmap__44c1_sm_p7_0[] = {
  140373. 11, 9, 7, 5, 3, 1, 0, 2,
  140374. 4, 6, 8, 10, 12,
  140375. };
  140376. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_0 = {
  140377. _vq_quantthresh__44c1_sm_p7_0,
  140378. _vq_quantmap__44c1_sm_p7_0,
  140379. 13,
  140380. 13
  140381. };
  140382. static static_codebook _44c1_sm_p7_0 = {
  140383. 2, 169,
  140384. _vq_lengthlist__44c1_sm_p7_0,
  140385. 1, -526516224, 1616117760, 4, 0,
  140386. _vq_quantlist__44c1_sm_p7_0,
  140387. NULL,
  140388. &_vq_auxt__44c1_sm_p7_0,
  140389. NULL,
  140390. 0
  140391. };
  140392. static long _vq_quantlist__44c1_sm_p7_1[] = {
  140393. 2,
  140394. 1,
  140395. 3,
  140396. 0,
  140397. 4,
  140398. };
  140399. static long _vq_lengthlist__44c1_sm_p7_1[] = {
  140400. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  140401. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  140402. };
  140403. static float _vq_quantthresh__44c1_sm_p7_1[] = {
  140404. -1.5, -0.5, 0.5, 1.5,
  140405. };
  140406. static long _vq_quantmap__44c1_sm_p7_1[] = {
  140407. 3, 1, 0, 2, 4,
  140408. };
  140409. static encode_aux_threshmatch _vq_auxt__44c1_sm_p7_1 = {
  140410. _vq_quantthresh__44c1_sm_p7_1,
  140411. _vq_quantmap__44c1_sm_p7_1,
  140412. 5,
  140413. 5
  140414. };
  140415. static static_codebook _44c1_sm_p7_1 = {
  140416. 2, 25,
  140417. _vq_lengthlist__44c1_sm_p7_1,
  140418. 1, -533725184, 1611661312, 3, 0,
  140419. _vq_quantlist__44c1_sm_p7_1,
  140420. NULL,
  140421. &_vq_auxt__44c1_sm_p7_1,
  140422. NULL,
  140423. 0
  140424. };
  140425. static long _vq_quantlist__44c1_sm_p8_0[] = {
  140426. 6,
  140427. 5,
  140428. 7,
  140429. 4,
  140430. 8,
  140431. 3,
  140432. 9,
  140433. 2,
  140434. 10,
  140435. 1,
  140436. 11,
  140437. 0,
  140438. 12,
  140439. };
  140440. static long _vq_lengthlist__44c1_sm_p8_0[] = {
  140441. 1, 3, 3,13,13,13,13,13,13,13,13,13,13, 3, 6, 6,
  140442. 13,13,13,13,13,13,13,13,13,13, 4, 8, 7,13,13,13,
  140443. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140444. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140445. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140446. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140447. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140448. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140449. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140450. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  140451. 13,13,13,13,13,13,13,13,13,
  140452. };
  140453. static float _vq_quantthresh__44c1_sm_p8_0[] = {
  140454. -1215.5, -994.5, -773.5, -552.5, -331.5, -110.5, 110.5, 331.5,
  140455. 552.5, 773.5, 994.5, 1215.5,
  140456. };
  140457. static long _vq_quantmap__44c1_sm_p8_0[] = {
  140458. 11, 9, 7, 5, 3, 1, 0, 2,
  140459. 4, 6, 8, 10, 12,
  140460. };
  140461. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_0 = {
  140462. _vq_quantthresh__44c1_sm_p8_0,
  140463. _vq_quantmap__44c1_sm_p8_0,
  140464. 13,
  140465. 13
  140466. };
  140467. static static_codebook _44c1_sm_p8_0 = {
  140468. 2, 169,
  140469. _vq_lengthlist__44c1_sm_p8_0,
  140470. 1, -514541568, 1627103232, 4, 0,
  140471. _vq_quantlist__44c1_sm_p8_0,
  140472. NULL,
  140473. &_vq_auxt__44c1_sm_p8_0,
  140474. NULL,
  140475. 0
  140476. };
  140477. static long _vq_quantlist__44c1_sm_p8_1[] = {
  140478. 6,
  140479. 5,
  140480. 7,
  140481. 4,
  140482. 8,
  140483. 3,
  140484. 9,
  140485. 2,
  140486. 10,
  140487. 1,
  140488. 11,
  140489. 0,
  140490. 12,
  140491. };
  140492. static long _vq_lengthlist__44c1_sm_p8_1[] = {
  140493. 1, 4, 4, 6, 6, 7, 7, 9, 9,10,11,12,12, 6, 5, 5,
  140494. 7, 7, 8, 7,10,10,11,11,12,12, 6, 5, 5, 7, 7, 8,
  140495. 8,10,10,11,11,12,12,16, 7, 7, 8, 8, 9, 9,11,11,
  140496. 12,12,13,13,17, 7, 7, 8, 7, 9, 9,11,10,12,12,13,
  140497. 13,19,11,10, 8, 8,10,10,11,11,12,12,13,13,19,11,
  140498. 11, 9, 7,11,10,11,11,12,12,13,12,19,19,19,10,10,
  140499. 10,10,11,12,12,12,13,14,18,19,19,11, 9,11, 9,13,
  140500. 12,12,12,13,13,19,20,19,13,15,11,11,12,12,13,13,
  140501. 14,13,18,19,20,15,13,12,10,13,10,13,13,13,14,20,
  140502. 20,20,20,20,13,14,12,12,13,12,13,13,20,20,20,20,
  140503. 20,13,12,12,12,14,12,14,13,
  140504. };
  140505. static float _vq_quantthresh__44c1_sm_p8_1[] = {
  140506. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  140507. 42.5, 59.5, 76.5, 93.5,
  140508. };
  140509. static long _vq_quantmap__44c1_sm_p8_1[] = {
  140510. 11, 9, 7, 5, 3, 1, 0, 2,
  140511. 4, 6, 8, 10, 12,
  140512. };
  140513. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_1 = {
  140514. _vq_quantthresh__44c1_sm_p8_1,
  140515. _vq_quantmap__44c1_sm_p8_1,
  140516. 13,
  140517. 13
  140518. };
  140519. static static_codebook _44c1_sm_p8_1 = {
  140520. 2, 169,
  140521. _vq_lengthlist__44c1_sm_p8_1,
  140522. 1, -522616832, 1620115456, 4, 0,
  140523. _vq_quantlist__44c1_sm_p8_1,
  140524. NULL,
  140525. &_vq_auxt__44c1_sm_p8_1,
  140526. NULL,
  140527. 0
  140528. };
  140529. static long _vq_quantlist__44c1_sm_p8_2[] = {
  140530. 8,
  140531. 7,
  140532. 9,
  140533. 6,
  140534. 10,
  140535. 5,
  140536. 11,
  140537. 4,
  140538. 12,
  140539. 3,
  140540. 13,
  140541. 2,
  140542. 14,
  140543. 1,
  140544. 15,
  140545. 0,
  140546. 16,
  140547. };
  140548. static long _vq_lengthlist__44c1_sm_p8_2[] = {
  140549. 2, 5, 5, 6, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 8,
  140550. 8,10, 6, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  140551. 9, 9,10, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  140552. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  140553. 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  140554. 9, 9, 9, 9, 9,10,11,11, 8, 8, 8, 8, 9, 9, 9, 9,
  140555. 9, 9,10,10, 9,10,10,10,10, 8, 8, 8, 8, 9, 9, 9,
  140556. 9, 9, 9, 9, 9,10,10,11,10,10, 8, 8, 9, 9, 9, 9,
  140557. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,11,11, 8, 8, 9,
  140558. 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,11,11,11, 9, 9,
  140559. 9, 9, 9, 9, 9, 9,10, 9,10, 9,11,11,11,11,11, 9,
  140560. 8, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,10,11,11,
  140561. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,11,11,11,11,
  140562. 11,11,11, 9, 9,10, 9, 9, 9, 9,10, 9,10,10,11,10,
  140563. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,10,11,
  140564. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,11,
  140565. 11,10,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9,10, 9,
  140566. 10,11,10,11,11,11,11,11,11, 9, 9,10, 9, 9, 9, 9,
  140567. 9,
  140568. };
  140569. static float _vq_quantthresh__44c1_sm_p8_2[] = {
  140570. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  140571. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  140572. };
  140573. static long _vq_quantmap__44c1_sm_p8_2[] = {
  140574. 15, 13, 11, 9, 7, 5, 3, 1,
  140575. 0, 2, 4, 6, 8, 10, 12, 14,
  140576. 16,
  140577. };
  140578. static encode_aux_threshmatch _vq_auxt__44c1_sm_p8_2 = {
  140579. _vq_quantthresh__44c1_sm_p8_2,
  140580. _vq_quantmap__44c1_sm_p8_2,
  140581. 17,
  140582. 17
  140583. };
  140584. static static_codebook _44c1_sm_p8_2 = {
  140585. 2, 289,
  140586. _vq_lengthlist__44c1_sm_p8_2,
  140587. 1, -529530880, 1611661312, 5, 0,
  140588. _vq_quantlist__44c1_sm_p8_2,
  140589. NULL,
  140590. &_vq_auxt__44c1_sm_p8_2,
  140591. NULL,
  140592. 0
  140593. };
  140594. static long _huff_lengthlist__44c1_sm_short[] = {
  140595. 4, 7,13,14,14,15,16,18,18, 4, 2, 5, 8, 7, 9,12,
  140596. 15,15,10, 4, 5,10, 6, 8,11,15,17,12, 5, 7, 5, 6,
  140597. 8,11,14,17,11, 5, 6, 6, 5, 6, 9,13,17,12, 6, 7,
  140598. 6, 5, 6, 8,12,14,14, 7, 8, 6, 6, 7, 9,11,14,14,
  140599. 8, 9, 6, 5, 6, 9,11,13,16,10,10, 7, 6, 7, 8,10,
  140600. 11,
  140601. };
  140602. static static_codebook _huff_book__44c1_sm_short = {
  140603. 2, 81,
  140604. _huff_lengthlist__44c1_sm_short,
  140605. 0, 0, 0, 0, 0,
  140606. NULL,
  140607. NULL,
  140608. NULL,
  140609. NULL,
  140610. 0
  140611. };
  140612. static long _huff_lengthlist__44cn1_s_long[] = {
  140613. 4, 4, 7, 8, 7, 8,10,12,17, 3, 1, 6, 6, 7, 8,10,
  140614. 12,15, 7, 6, 9, 9, 9,11,12,14,17, 8, 6, 9, 6, 7,
  140615. 9,11,13,17, 7, 6, 9, 7, 7, 8, 9,12,15, 8, 8,10,
  140616. 8, 7, 7, 7,10,14, 9,10,12,10, 8, 8, 8,10,14,11,
  140617. 13,15,13,12,11,11,12,16,17,18,18,19,20,18,16,16,
  140618. 20,
  140619. };
  140620. static static_codebook _huff_book__44cn1_s_long = {
  140621. 2, 81,
  140622. _huff_lengthlist__44cn1_s_long,
  140623. 0, 0, 0, 0, 0,
  140624. NULL,
  140625. NULL,
  140626. NULL,
  140627. NULL,
  140628. 0
  140629. };
  140630. static long _vq_quantlist__44cn1_s_p1_0[] = {
  140631. 1,
  140632. 0,
  140633. 2,
  140634. };
  140635. static long _vq_lengthlist__44cn1_s_p1_0[] = {
  140636. 1, 4, 4, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  140637. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140638. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140639. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140640. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140641. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  140642. 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140643. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140644. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140645. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140646. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0,
  140647. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140648. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140649. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140650. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140651. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140652. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140653. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140654. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140655. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140656. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140657. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140658. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140659. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140660. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140661. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140662. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140663. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140664. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140665. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140666. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140667. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140668. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140669. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140670. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140671. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140672. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140673. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140674. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140675. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140676. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140677. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140678. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140679. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140680. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140681. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  140682. 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 8, 9,10, 0, 0,
  140683. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140684. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140685. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140686. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0, 0,
  140687. 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140688. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10,10, 0, 0,
  140692. 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0,10,11,11,
  140693. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140697. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140698. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140727. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8,10,10, 0, 0,
  140728. 0, 0, 0, 0, 8,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140732. 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11, 0,
  140733. 0, 0, 0, 0, 0, 9, 9,11, 0, 0, 0, 0, 0, 0, 0, 0,
  140734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140737. 0, 0, 0, 0, 7,10,10, 0, 0, 0, 0, 0, 0,10,11,11,
  140738. 0, 0, 0, 0, 0, 0, 9,11, 9, 0, 0, 0, 0, 0, 0, 0,
  140739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140743. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140778. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140779. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140783. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140784. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140788. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140789. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  140999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141046. 0,
  141047. };
  141048. static float _vq_quantthresh__44cn1_s_p1_0[] = {
  141049. -0.5, 0.5,
  141050. };
  141051. static long _vq_quantmap__44cn1_s_p1_0[] = {
  141052. 1, 0, 2,
  141053. };
  141054. static encode_aux_threshmatch _vq_auxt__44cn1_s_p1_0 = {
  141055. _vq_quantthresh__44cn1_s_p1_0,
  141056. _vq_quantmap__44cn1_s_p1_0,
  141057. 3,
  141058. 3
  141059. };
  141060. static static_codebook _44cn1_s_p1_0 = {
  141061. 8, 6561,
  141062. _vq_lengthlist__44cn1_s_p1_0,
  141063. 1, -535822336, 1611661312, 2, 0,
  141064. _vq_quantlist__44cn1_s_p1_0,
  141065. NULL,
  141066. &_vq_auxt__44cn1_s_p1_0,
  141067. NULL,
  141068. 0
  141069. };
  141070. static long _vq_quantlist__44cn1_s_p2_0[] = {
  141071. 2,
  141072. 1,
  141073. 3,
  141074. 0,
  141075. 4,
  141076. };
  141077. static long _vq_lengthlist__44cn1_s_p2_0[] = {
  141078. 1, 4, 4, 7, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  141080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141081. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  141083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141084. 0, 0, 0, 0, 6, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  141085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141097. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141098. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141099. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141100. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141101. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141102. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141103. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141104. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141105. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141106. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141107. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141108. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141109. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141110. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141111. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141112. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141113. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141114. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141115. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141116. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141117. 0,
  141118. };
  141119. static float _vq_quantthresh__44cn1_s_p2_0[] = {
  141120. -1.5, -0.5, 0.5, 1.5,
  141121. };
  141122. static long _vq_quantmap__44cn1_s_p2_0[] = {
  141123. 3, 1, 0, 2, 4,
  141124. };
  141125. static encode_aux_threshmatch _vq_auxt__44cn1_s_p2_0 = {
  141126. _vq_quantthresh__44cn1_s_p2_0,
  141127. _vq_quantmap__44cn1_s_p2_0,
  141128. 5,
  141129. 5
  141130. };
  141131. static static_codebook _44cn1_s_p2_0 = {
  141132. 4, 625,
  141133. _vq_lengthlist__44cn1_s_p2_0,
  141134. 1, -533725184, 1611661312, 3, 0,
  141135. _vq_quantlist__44cn1_s_p2_0,
  141136. NULL,
  141137. &_vq_auxt__44cn1_s_p2_0,
  141138. NULL,
  141139. 0
  141140. };
  141141. static long _vq_quantlist__44cn1_s_p3_0[] = {
  141142. 4,
  141143. 3,
  141144. 5,
  141145. 2,
  141146. 6,
  141147. 1,
  141148. 7,
  141149. 0,
  141150. 8,
  141151. };
  141152. static long _vq_lengthlist__44cn1_s_p3_0[] = {
  141153. 1, 2, 3, 7, 7, 0, 0, 0, 0, 0, 0, 0, 6, 6, 0, 0,
  141154. 0, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 0, 0, 0, 7, 7,
  141155. 0, 0, 0, 0, 0, 0, 0, 7, 7, 0, 0, 0, 0, 0, 0, 0,
  141156. 9, 8, 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0,
  141157. 0, 0,10,10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141158. 0,
  141159. };
  141160. static float _vq_quantthresh__44cn1_s_p3_0[] = {
  141161. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141162. };
  141163. static long _vq_quantmap__44cn1_s_p3_0[] = {
  141164. 7, 5, 3, 1, 0, 2, 4, 6,
  141165. 8,
  141166. };
  141167. static encode_aux_threshmatch _vq_auxt__44cn1_s_p3_0 = {
  141168. _vq_quantthresh__44cn1_s_p3_0,
  141169. _vq_quantmap__44cn1_s_p3_0,
  141170. 9,
  141171. 9
  141172. };
  141173. static static_codebook _44cn1_s_p3_0 = {
  141174. 2, 81,
  141175. _vq_lengthlist__44cn1_s_p3_0,
  141176. 1, -531628032, 1611661312, 4, 0,
  141177. _vq_quantlist__44cn1_s_p3_0,
  141178. NULL,
  141179. &_vq_auxt__44cn1_s_p3_0,
  141180. NULL,
  141181. 0
  141182. };
  141183. static long _vq_quantlist__44cn1_s_p4_0[] = {
  141184. 4,
  141185. 3,
  141186. 5,
  141187. 2,
  141188. 6,
  141189. 1,
  141190. 7,
  141191. 0,
  141192. 8,
  141193. };
  141194. static long _vq_lengthlist__44cn1_s_p4_0[] = {
  141195. 1, 3, 3, 6, 6, 6, 6, 8, 8, 0, 0, 0, 6, 6, 7, 7,
  141196. 9, 9, 0, 0, 0, 6, 6, 7, 7, 9, 9, 0, 0, 0, 7, 7,
  141197. 8, 8,10,10, 0, 0, 0, 7, 7, 8, 8,10,10, 0, 0, 0,
  141198. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  141199. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  141200. 11,
  141201. };
  141202. static float _vq_quantthresh__44cn1_s_p4_0[] = {
  141203. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  141204. };
  141205. static long _vq_quantmap__44cn1_s_p4_0[] = {
  141206. 7, 5, 3, 1, 0, 2, 4, 6,
  141207. 8,
  141208. };
  141209. static encode_aux_threshmatch _vq_auxt__44cn1_s_p4_0 = {
  141210. _vq_quantthresh__44cn1_s_p4_0,
  141211. _vq_quantmap__44cn1_s_p4_0,
  141212. 9,
  141213. 9
  141214. };
  141215. static static_codebook _44cn1_s_p4_0 = {
  141216. 2, 81,
  141217. _vq_lengthlist__44cn1_s_p4_0,
  141218. 1, -531628032, 1611661312, 4, 0,
  141219. _vq_quantlist__44cn1_s_p4_0,
  141220. NULL,
  141221. &_vq_auxt__44cn1_s_p4_0,
  141222. NULL,
  141223. 0
  141224. };
  141225. static long _vq_quantlist__44cn1_s_p5_0[] = {
  141226. 8,
  141227. 7,
  141228. 9,
  141229. 6,
  141230. 10,
  141231. 5,
  141232. 11,
  141233. 4,
  141234. 12,
  141235. 3,
  141236. 13,
  141237. 2,
  141238. 14,
  141239. 1,
  141240. 15,
  141241. 0,
  141242. 16,
  141243. };
  141244. static long _vq_lengthlist__44cn1_s_p5_0[] = {
  141245. 1, 4, 3, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  141246. 10, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,10,
  141247. 11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,10,
  141248. 10,11,11, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  141249. 11,11,11,12, 0, 0, 0, 7, 7, 8, 8, 9, 9, 9, 9,10,
  141250. 10,11,11,11,11, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,10,
  141251. 10,10,11,11,12,12, 0, 0, 0, 8, 8, 9, 9, 9, 9,10,
  141252. 10,10,11,11,11,12,12, 0, 0, 0, 9, 9,10, 9,10,10,
  141253. 10,10,11,11,11,11,12,12, 0, 0, 0, 0, 0, 9, 9,10,
  141254. 10,10,10,11,11,12,12,12,12, 0, 0, 0, 0, 0, 9, 9,
  141255. 10,10,10,11,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9,
  141256. 9,10,10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0,
  141257. 10,10,11,10,11,11,11,12,13,12,13,13, 0, 0, 0, 0,
  141258. 0, 0, 0,11,10,11,11,12,12,12,12,13,13, 0, 0, 0,
  141259. 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0, 0,
  141260. 0, 0, 0, 0, 0,11,11,12,12,12,12,13,13,13,14, 0,
  141261. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,13,13,14,14,
  141262. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,12,13,13,14,
  141263. 14,
  141264. };
  141265. static float _vq_quantthresh__44cn1_s_p5_0[] = {
  141266. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141267. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141268. };
  141269. static long _vq_quantmap__44cn1_s_p5_0[] = {
  141270. 15, 13, 11, 9, 7, 5, 3, 1,
  141271. 0, 2, 4, 6, 8, 10, 12, 14,
  141272. 16,
  141273. };
  141274. static encode_aux_threshmatch _vq_auxt__44cn1_s_p5_0 = {
  141275. _vq_quantthresh__44cn1_s_p5_0,
  141276. _vq_quantmap__44cn1_s_p5_0,
  141277. 17,
  141278. 17
  141279. };
  141280. static static_codebook _44cn1_s_p5_0 = {
  141281. 2, 289,
  141282. _vq_lengthlist__44cn1_s_p5_0,
  141283. 1, -529530880, 1611661312, 5, 0,
  141284. _vq_quantlist__44cn1_s_p5_0,
  141285. NULL,
  141286. &_vq_auxt__44cn1_s_p5_0,
  141287. NULL,
  141288. 0
  141289. };
  141290. static long _vq_quantlist__44cn1_s_p6_0[] = {
  141291. 1,
  141292. 0,
  141293. 2,
  141294. };
  141295. static long _vq_lengthlist__44cn1_s_p6_0[] = {
  141296. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 6, 6,10, 9, 9,11,
  141297. 9, 9, 4, 6, 6,10, 9, 9,10, 9, 9, 7,10,10,11,11,
  141298. 11,12,11,11, 7, 9, 9,11,11,10,11,10,10, 7, 9, 9,
  141299. 11,10,11,11,10,10, 7,10,10,11,11,11,12,11,11, 7,
  141300. 9, 9,11,10,10,11,10,10, 7, 9, 9,11,10,10,11,10,
  141301. 10,
  141302. };
  141303. static float _vq_quantthresh__44cn1_s_p6_0[] = {
  141304. -5.5, 5.5,
  141305. };
  141306. static long _vq_quantmap__44cn1_s_p6_0[] = {
  141307. 1, 0, 2,
  141308. };
  141309. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_0 = {
  141310. _vq_quantthresh__44cn1_s_p6_0,
  141311. _vq_quantmap__44cn1_s_p6_0,
  141312. 3,
  141313. 3
  141314. };
  141315. static static_codebook _44cn1_s_p6_0 = {
  141316. 4, 81,
  141317. _vq_lengthlist__44cn1_s_p6_0,
  141318. 1, -529137664, 1618345984, 2, 0,
  141319. _vq_quantlist__44cn1_s_p6_0,
  141320. NULL,
  141321. &_vq_auxt__44cn1_s_p6_0,
  141322. NULL,
  141323. 0
  141324. };
  141325. static long _vq_quantlist__44cn1_s_p6_1[] = {
  141326. 5,
  141327. 4,
  141328. 6,
  141329. 3,
  141330. 7,
  141331. 2,
  141332. 8,
  141333. 1,
  141334. 9,
  141335. 0,
  141336. 10,
  141337. };
  141338. static long _vq_lengthlist__44cn1_s_p6_1[] = {
  141339. 1, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,10, 7, 6,
  141340. 8, 8, 8, 8, 8, 8,10,10,10, 7, 6, 7, 7, 8, 8, 8,
  141341. 8,10,10,10, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  141342. 7, 8, 8, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 9, 9,
  141343. 9, 9,10,10,10, 8, 8, 8, 8, 9, 9, 9, 9,10,10,10,
  141344. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10, 9, 9, 9,
  141345. 9, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,10,
  141346. 10,10,10, 9, 9, 9, 9, 9, 9,
  141347. };
  141348. static float _vq_quantthresh__44cn1_s_p6_1[] = {
  141349. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  141350. 3.5, 4.5,
  141351. };
  141352. static long _vq_quantmap__44cn1_s_p6_1[] = {
  141353. 9, 7, 5, 3, 1, 0, 2, 4,
  141354. 6, 8, 10,
  141355. };
  141356. static encode_aux_threshmatch _vq_auxt__44cn1_s_p6_1 = {
  141357. _vq_quantthresh__44cn1_s_p6_1,
  141358. _vq_quantmap__44cn1_s_p6_1,
  141359. 11,
  141360. 11
  141361. };
  141362. static static_codebook _44cn1_s_p6_1 = {
  141363. 2, 121,
  141364. _vq_lengthlist__44cn1_s_p6_1,
  141365. 1, -531365888, 1611661312, 4, 0,
  141366. _vq_quantlist__44cn1_s_p6_1,
  141367. NULL,
  141368. &_vq_auxt__44cn1_s_p6_1,
  141369. NULL,
  141370. 0
  141371. };
  141372. static long _vq_quantlist__44cn1_s_p7_0[] = {
  141373. 6,
  141374. 5,
  141375. 7,
  141376. 4,
  141377. 8,
  141378. 3,
  141379. 9,
  141380. 2,
  141381. 10,
  141382. 1,
  141383. 11,
  141384. 0,
  141385. 12,
  141386. };
  141387. static long _vq_lengthlist__44cn1_s_p7_0[] = {
  141388. 1, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 6, 5, 5,
  141389. 7, 7, 8, 8, 8, 8, 9, 9,11,11, 7, 5, 5, 7, 7, 8,
  141390. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  141391. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  141392. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,11,12, 0,13,
  141393. 13, 9, 9, 9, 9,10,10,11,11,11,12, 0, 0, 0,10,10,
  141394. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  141395. 11,12,12,13,12, 0, 0, 0,14,14,11,10,11,12,12,13,
  141396. 13,14, 0, 0, 0,15,15,11,11,12,11,12,12,14,13, 0,
  141397. 0, 0, 0, 0,12,12,12,12,13,13,14,14, 0, 0, 0, 0,
  141398. 0,13,13,12,12,13,13,13,14,
  141399. };
  141400. static float _vq_quantthresh__44cn1_s_p7_0[] = {
  141401. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  141402. 12.5, 17.5, 22.5, 27.5,
  141403. };
  141404. static long _vq_quantmap__44cn1_s_p7_0[] = {
  141405. 11, 9, 7, 5, 3, 1, 0, 2,
  141406. 4, 6, 8, 10, 12,
  141407. };
  141408. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_0 = {
  141409. _vq_quantthresh__44cn1_s_p7_0,
  141410. _vq_quantmap__44cn1_s_p7_0,
  141411. 13,
  141412. 13
  141413. };
  141414. static static_codebook _44cn1_s_p7_0 = {
  141415. 2, 169,
  141416. _vq_lengthlist__44cn1_s_p7_0,
  141417. 1, -526516224, 1616117760, 4, 0,
  141418. _vq_quantlist__44cn1_s_p7_0,
  141419. NULL,
  141420. &_vq_auxt__44cn1_s_p7_0,
  141421. NULL,
  141422. 0
  141423. };
  141424. static long _vq_quantlist__44cn1_s_p7_1[] = {
  141425. 2,
  141426. 1,
  141427. 3,
  141428. 0,
  141429. 4,
  141430. };
  141431. static long _vq_lengthlist__44cn1_s_p7_1[] = {
  141432. 2, 3, 3, 5, 5, 6, 6, 6, 5, 5, 6, 6, 6, 5, 5, 6,
  141433. 6, 6, 5, 5, 6, 6, 6, 5, 5,
  141434. };
  141435. static float _vq_quantthresh__44cn1_s_p7_1[] = {
  141436. -1.5, -0.5, 0.5, 1.5,
  141437. };
  141438. static long _vq_quantmap__44cn1_s_p7_1[] = {
  141439. 3, 1, 0, 2, 4,
  141440. };
  141441. static encode_aux_threshmatch _vq_auxt__44cn1_s_p7_1 = {
  141442. _vq_quantthresh__44cn1_s_p7_1,
  141443. _vq_quantmap__44cn1_s_p7_1,
  141444. 5,
  141445. 5
  141446. };
  141447. static static_codebook _44cn1_s_p7_1 = {
  141448. 2, 25,
  141449. _vq_lengthlist__44cn1_s_p7_1,
  141450. 1, -533725184, 1611661312, 3, 0,
  141451. _vq_quantlist__44cn1_s_p7_1,
  141452. NULL,
  141453. &_vq_auxt__44cn1_s_p7_1,
  141454. NULL,
  141455. 0
  141456. };
  141457. static long _vq_quantlist__44cn1_s_p8_0[] = {
  141458. 2,
  141459. 1,
  141460. 3,
  141461. 0,
  141462. 4,
  141463. };
  141464. static long _vq_lengthlist__44cn1_s_p8_0[] = {
  141465. 1, 7, 7,11,11, 8,11,11,11,11, 4,11, 3,11,11,11,
  141466. 11,11,11,11,11,11,11,11,11,11,11,10,11,11,11,11,
  141467. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141468. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  141469. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141470. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141471. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141472. 11,11,11,11,11,11,11,11,11,11,11,11,11, 7,11,11,
  141473. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141474. 11,11,11,11,11,11,10,11,11,11,11,11,11,11,11,11,
  141475. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  141476. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141477. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141478. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141479. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141480. 11,11,11,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  141481. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141482. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141483. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141484. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141485. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141486. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141487. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141488. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141489. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141490. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141491. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141492. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141493. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141494. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141495. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141496. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141497. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  141498. 11,11,11,11,11,11,11,12,12,12,12,12,12,12,12,12,
  141499. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141500. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141501. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141502. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141503. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  141504. 12,
  141505. };
  141506. static float _vq_quantthresh__44cn1_s_p8_0[] = {
  141507. -331.5, -110.5, 110.5, 331.5,
  141508. };
  141509. static long _vq_quantmap__44cn1_s_p8_0[] = {
  141510. 3, 1, 0, 2, 4,
  141511. };
  141512. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_0 = {
  141513. _vq_quantthresh__44cn1_s_p8_0,
  141514. _vq_quantmap__44cn1_s_p8_0,
  141515. 5,
  141516. 5
  141517. };
  141518. static static_codebook _44cn1_s_p8_0 = {
  141519. 4, 625,
  141520. _vq_lengthlist__44cn1_s_p8_0,
  141521. 1, -518283264, 1627103232, 3, 0,
  141522. _vq_quantlist__44cn1_s_p8_0,
  141523. NULL,
  141524. &_vq_auxt__44cn1_s_p8_0,
  141525. NULL,
  141526. 0
  141527. };
  141528. static long _vq_quantlist__44cn1_s_p8_1[] = {
  141529. 6,
  141530. 5,
  141531. 7,
  141532. 4,
  141533. 8,
  141534. 3,
  141535. 9,
  141536. 2,
  141537. 10,
  141538. 1,
  141539. 11,
  141540. 0,
  141541. 12,
  141542. };
  141543. static long _vq_lengthlist__44cn1_s_p8_1[] = {
  141544. 1, 4, 4, 6, 6, 8, 8, 9,10,10,11,11,11, 6, 5, 5,
  141545. 7, 7, 8, 8, 9,10, 9,11,11,12, 5, 5, 5, 7, 7, 8,
  141546. 9,10,10,12,12,14,13,15, 7, 7, 8, 8, 9,10,11,11,
  141547. 10,12,10,11,15, 7, 8, 8, 8, 9, 9,11,11,13,12,12,
  141548. 13,15,10,10, 8, 8,10,10,12,12,11,14,10,10,15,11,
  141549. 11, 8, 8,10,10,12,13,13,14,15,13,15,15,15,10,10,
  141550. 10,10,12,12,13,12,13,10,15,15,15,10,10,11,10,13,
  141551. 11,13,13,15,13,15,15,15,13,13,10,11,11,11,12,10,
  141552. 14,11,15,15,14,14,13,10,10,12,11,13,13,14,14,15,
  141553. 15,15,15,15,11,11,11,11,12,11,15,12,15,15,15,15,
  141554. 15,12,12,11,11,14,12,13,14,
  141555. };
  141556. static float _vq_quantthresh__44cn1_s_p8_1[] = {
  141557. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  141558. 42.5, 59.5, 76.5, 93.5,
  141559. };
  141560. static long _vq_quantmap__44cn1_s_p8_1[] = {
  141561. 11, 9, 7, 5, 3, 1, 0, 2,
  141562. 4, 6, 8, 10, 12,
  141563. };
  141564. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_1 = {
  141565. _vq_quantthresh__44cn1_s_p8_1,
  141566. _vq_quantmap__44cn1_s_p8_1,
  141567. 13,
  141568. 13
  141569. };
  141570. static static_codebook _44cn1_s_p8_1 = {
  141571. 2, 169,
  141572. _vq_lengthlist__44cn1_s_p8_1,
  141573. 1, -522616832, 1620115456, 4, 0,
  141574. _vq_quantlist__44cn1_s_p8_1,
  141575. NULL,
  141576. &_vq_auxt__44cn1_s_p8_1,
  141577. NULL,
  141578. 0
  141579. };
  141580. static long _vq_quantlist__44cn1_s_p8_2[] = {
  141581. 8,
  141582. 7,
  141583. 9,
  141584. 6,
  141585. 10,
  141586. 5,
  141587. 11,
  141588. 4,
  141589. 12,
  141590. 3,
  141591. 13,
  141592. 2,
  141593. 14,
  141594. 1,
  141595. 15,
  141596. 0,
  141597. 16,
  141598. };
  141599. static long _vq_lengthlist__44cn1_s_p8_2[] = {
  141600. 3, 4, 3, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  141601. 9,10,11,11, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  141602. 9, 9,10,10,10, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  141603. 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9,
  141604. 9, 9,10, 9,10,11,10, 7, 6, 7, 7, 8, 8, 9, 9, 9,
  141605. 9, 9, 9, 9,10,10,10,11, 7, 7, 8, 8, 8, 8, 9, 9,
  141606. 9, 9, 9, 9, 9, 9,10,10,10, 7, 7, 8, 8, 8, 8, 9,
  141607. 9, 9, 9, 9, 9, 9,10,11,11,11, 8, 8, 8, 8, 8, 8,
  141608. 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,11, 8, 8, 8,
  141609. 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,11,11, 9, 9,
  141610. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,11,10,11,11, 9,
  141611. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,10,11,10,11,11,
  141612. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,10,11,
  141613. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11,
  141614. 10,11,11,11, 9,10,10, 9, 9, 9, 9, 9, 9, 9,10,11,
  141615. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  141616. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  141617. 11,11,11,10,11,11,11,11,11, 9, 9, 9,10, 9, 9, 9,
  141618. 9,
  141619. };
  141620. static float _vq_quantthresh__44cn1_s_p8_2[] = {
  141621. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  141622. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  141623. };
  141624. static long _vq_quantmap__44cn1_s_p8_2[] = {
  141625. 15, 13, 11, 9, 7, 5, 3, 1,
  141626. 0, 2, 4, 6, 8, 10, 12, 14,
  141627. 16,
  141628. };
  141629. static encode_aux_threshmatch _vq_auxt__44cn1_s_p8_2 = {
  141630. _vq_quantthresh__44cn1_s_p8_2,
  141631. _vq_quantmap__44cn1_s_p8_2,
  141632. 17,
  141633. 17
  141634. };
  141635. static static_codebook _44cn1_s_p8_2 = {
  141636. 2, 289,
  141637. _vq_lengthlist__44cn1_s_p8_2,
  141638. 1, -529530880, 1611661312, 5, 0,
  141639. _vq_quantlist__44cn1_s_p8_2,
  141640. NULL,
  141641. &_vq_auxt__44cn1_s_p8_2,
  141642. NULL,
  141643. 0
  141644. };
  141645. static long _huff_lengthlist__44cn1_s_short[] = {
  141646. 10, 9,12,15,12,13,16,14,16, 7, 1, 5,14, 7,10,13,
  141647. 16,16, 9, 4, 6,16, 8,11,16,16,16,14, 4, 7,16, 9,
  141648. 12,14,16,16,10, 5, 7,14, 9,12,14,15,15,13, 8, 9,
  141649. 14,10,12,13,14,15,13, 9, 9, 7, 6, 8,11,12,12,14,
  141650. 8, 8, 5, 4, 5, 8,11,12,16,10,10, 6, 5, 6, 8, 9,
  141651. 10,
  141652. };
  141653. static static_codebook _huff_book__44cn1_s_short = {
  141654. 2, 81,
  141655. _huff_lengthlist__44cn1_s_short,
  141656. 0, 0, 0, 0, 0,
  141657. NULL,
  141658. NULL,
  141659. NULL,
  141660. NULL,
  141661. 0
  141662. };
  141663. static long _huff_lengthlist__44cn1_sm_long[] = {
  141664. 3, 3, 8, 8, 8, 8,10,12,14, 3, 2, 6, 7, 7, 8,10,
  141665. 12,16, 7, 6, 7, 9, 8,10,12,14,16, 8, 6, 8, 4, 5,
  141666. 7, 9,11,13, 7, 6, 8, 5, 6, 7, 9,11,14, 8, 8,10,
  141667. 7, 7, 6, 8,10,13, 9,11,12, 9, 9, 7, 8,10,12,10,
  141668. 13,15,11,11,10, 9,10,13,13,16,17,14,15,14,13,14,
  141669. 17,
  141670. };
  141671. static static_codebook _huff_book__44cn1_sm_long = {
  141672. 2, 81,
  141673. _huff_lengthlist__44cn1_sm_long,
  141674. 0, 0, 0, 0, 0,
  141675. NULL,
  141676. NULL,
  141677. NULL,
  141678. NULL,
  141679. 0
  141680. };
  141681. static long _vq_quantlist__44cn1_sm_p1_0[] = {
  141682. 1,
  141683. 0,
  141684. 2,
  141685. };
  141686. static long _vq_lengthlist__44cn1_sm_p1_0[] = {
  141687. 1, 4, 5, 0, 0, 0, 0, 0, 0, 5, 7, 7, 0, 0, 0, 0,
  141688. 0, 0, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141689. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141690. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141691. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141692. 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0, 0,
  141693. 0, 0, 0, 7, 8, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141694. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141695. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141696. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141697. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 7, 9, 8, 0, 0,
  141698. 0, 0, 0, 0, 8, 9, 9, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141699. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141700. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141701. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141702. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141703. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141704. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141705. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141706. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141707. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141708. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141709. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141710. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141711. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141712. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141713. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141714. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141715. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141716. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141717. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141718. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141719. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141720. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141721. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141722. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141723. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141724. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141725. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141726. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141727. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141728. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141729. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141730. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141731. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141732. 0, 0, 0, 0, 0, 0, 0, 0, 0, 5, 8, 8, 0, 0, 0, 0,
  141733. 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141734. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141735. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141736. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141737. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7,10, 9, 0, 0, 0,
  141738. 0, 0, 0, 9, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141739. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141740. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141741. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141742. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 7, 9, 9, 0, 0,
  141743. 0, 0, 0, 0, 8,10, 9, 0, 0, 0, 0, 0, 0, 9,10,10,
  141744. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141745. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141746. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141747. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141748. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141749. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141750. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141751. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141752. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141753. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141754. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141755. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141756. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141757. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141758. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141759. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141760. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141761. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141762. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141763. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141764. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141765. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141766. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141767. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141768. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141769. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141770. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141771. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141772. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141773. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141774. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141775. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141776. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141777. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141778. 0, 0, 5, 8, 8, 0, 0, 0, 0, 0, 0, 8, 9, 9, 0, 0,
  141779. 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141780. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141781. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141782. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141783. 0, 0, 0, 7, 9, 9, 0, 0, 0, 0, 0, 0, 9,10,10, 0,
  141784. 0, 0, 0, 0, 0, 8, 9,10, 0, 0, 0, 0, 0, 0, 0, 0,
  141785. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141786. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141787. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141788. 0, 0, 0, 0, 7, 9,10, 0, 0, 0, 0, 0, 0, 9,10,10,
  141789. 0, 0, 0, 0, 0, 0, 9,10, 9, 0, 0, 0, 0, 0, 0, 0,
  141790. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141791. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141792. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141793. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141794. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141795. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141796. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141797. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141798. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141799. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141800. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141801. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141802. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141803. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141804. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141805. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141806. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141807. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141808. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141809. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141810. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141811. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141812. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141813. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141814. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141815. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141816. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141817. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141818. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141819. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141820. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141821. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141822. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141823. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141824. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141825. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141826. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141827. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141828. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141829. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141830. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141831. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141832. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141833. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141834. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141835. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141836. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141837. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141838. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141839. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141840. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141841. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141842. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141843. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141844. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141845. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141846. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141847. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141848. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141849. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141850. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141851. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141852. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141853. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141854. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141855. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141856. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141857. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141858. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141859. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141860. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141861. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141862. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141863. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141864. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141865. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141866. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141867. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141868. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141869. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141870. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141871. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141872. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141873. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141874. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141875. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141876. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141877. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141878. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141879. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141880. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141881. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141882. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141883. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141884. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141885. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141886. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141887. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141888. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141889. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141890. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141891. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141892. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141893. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141894. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141895. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141896. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141897. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141898. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141899. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141900. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141901. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141902. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141903. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141904. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141905. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141906. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141907. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141908. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141909. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141910. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141911. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141912. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141913. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141914. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141915. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141916. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141917. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141918. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141919. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141920. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141921. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141922. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141923. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141924. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141925. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141926. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141927. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141928. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141929. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141930. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141931. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141932. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141933. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141934. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141935. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141936. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141937. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141938. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141939. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141940. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141941. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141942. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141943. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141944. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141945. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141946. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141947. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141948. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141949. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141950. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141951. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141952. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141953. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141954. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141955. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141956. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141957. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141958. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141959. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141960. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141961. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141962. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141963. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141964. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141965. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141966. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141967. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141968. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141969. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141970. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141971. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141972. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141973. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141974. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141975. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141976. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141977. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141978. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141979. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141980. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141981. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141982. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141983. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141984. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141985. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141986. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141987. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141988. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141989. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141990. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141991. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141992. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141993. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141994. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141995. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141996. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141997. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141998. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  141999. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142000. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142001. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142002. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142003. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142004. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142005. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142006. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142007. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142008. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142009. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142010. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142011. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142012. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142013. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142014. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142015. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142016. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142017. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142018. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142019. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142020. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142021. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142022. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142023. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142024. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142025. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142026. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142027. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142028. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142029. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142030. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142031. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142032. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142033. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142034. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142035. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142036. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142037. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142038. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142039. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142040. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142041. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142042. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142043. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142044. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142045. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142046. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142047. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142048. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142049. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142050. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142051. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142052. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142053. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142054. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142055. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142056. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142057. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142058. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142059. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142060. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142061. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142062. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142063. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142064. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142065. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142066. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142067. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142068. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142069. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142070. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142071. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142072. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142073. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142074. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142075. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142076. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142077. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142078. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142079. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142080. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142081. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142082. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142083. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142084. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142085. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142086. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142087. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142088. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142089. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142090. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142091. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142092. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142093. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142094. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142095. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142096. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142097. 0,
  142098. };
  142099. static float _vq_quantthresh__44cn1_sm_p1_0[] = {
  142100. -0.5, 0.5,
  142101. };
  142102. static long _vq_quantmap__44cn1_sm_p1_0[] = {
  142103. 1, 0, 2,
  142104. };
  142105. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p1_0 = {
  142106. _vq_quantthresh__44cn1_sm_p1_0,
  142107. _vq_quantmap__44cn1_sm_p1_0,
  142108. 3,
  142109. 3
  142110. };
  142111. static static_codebook _44cn1_sm_p1_0 = {
  142112. 8, 6561,
  142113. _vq_lengthlist__44cn1_sm_p1_0,
  142114. 1, -535822336, 1611661312, 2, 0,
  142115. _vq_quantlist__44cn1_sm_p1_0,
  142116. NULL,
  142117. &_vq_auxt__44cn1_sm_p1_0,
  142118. NULL,
  142119. 0
  142120. };
  142121. static long _vq_quantlist__44cn1_sm_p2_0[] = {
  142122. 2,
  142123. 1,
  142124. 3,
  142125. 0,
  142126. 4,
  142127. };
  142128. static long _vq_lengthlist__44cn1_sm_p2_0[] = {
  142129. 1, 4, 4, 6, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142130. 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 5, 5, 7, 7, 0, 0,
  142131. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142132. 0, 0, 4, 5, 5, 7, 7, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142133. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 6, 7, 7, 9, 9,
  142134. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142135. 0, 0, 0, 0, 7, 7, 7, 9, 9, 0, 0, 0, 0, 0, 0, 0,
  142136. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142137. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142138. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142139. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142140. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142141. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142142. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142143. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142144. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142145. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142146. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142147. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142148. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142149. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142150. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142151. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142152. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142153. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142154. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142155. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142156. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142157. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142158. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142159. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142160. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142161. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142162. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142163. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142164. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142165. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142166. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142167. 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142168. 0,
  142169. };
  142170. static float _vq_quantthresh__44cn1_sm_p2_0[] = {
  142171. -1.5, -0.5, 0.5, 1.5,
  142172. };
  142173. static long _vq_quantmap__44cn1_sm_p2_0[] = {
  142174. 3, 1, 0, 2, 4,
  142175. };
  142176. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p2_0 = {
  142177. _vq_quantthresh__44cn1_sm_p2_0,
  142178. _vq_quantmap__44cn1_sm_p2_0,
  142179. 5,
  142180. 5
  142181. };
  142182. static static_codebook _44cn1_sm_p2_0 = {
  142183. 4, 625,
  142184. _vq_lengthlist__44cn1_sm_p2_0,
  142185. 1, -533725184, 1611661312, 3, 0,
  142186. _vq_quantlist__44cn1_sm_p2_0,
  142187. NULL,
  142188. &_vq_auxt__44cn1_sm_p2_0,
  142189. NULL,
  142190. 0
  142191. };
  142192. static long _vq_quantlist__44cn1_sm_p3_0[] = {
  142193. 4,
  142194. 3,
  142195. 5,
  142196. 2,
  142197. 6,
  142198. 1,
  142199. 7,
  142200. 0,
  142201. 8,
  142202. };
  142203. static long _vq_lengthlist__44cn1_sm_p3_0[] = {
  142204. 1, 3, 4, 7, 7, 0, 0, 0, 0, 0, 4, 4, 7, 7, 0, 0,
  142205. 0, 0, 0, 4, 5, 7, 7, 0, 0, 0, 0, 0, 6, 7, 8, 8,
  142206. 0, 0, 0, 0, 0, 0, 0, 8, 8, 0, 0, 0, 0, 0, 0, 0,
  142207. 9, 9, 0, 0, 0, 0, 0, 0, 0,10, 9, 0, 0, 0, 0, 0,
  142208. 0, 0,11,11, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
  142209. 0,
  142210. };
  142211. static float _vq_quantthresh__44cn1_sm_p3_0[] = {
  142212. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142213. };
  142214. static long _vq_quantmap__44cn1_sm_p3_0[] = {
  142215. 7, 5, 3, 1, 0, 2, 4, 6,
  142216. 8,
  142217. };
  142218. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p3_0 = {
  142219. _vq_quantthresh__44cn1_sm_p3_0,
  142220. _vq_quantmap__44cn1_sm_p3_0,
  142221. 9,
  142222. 9
  142223. };
  142224. static static_codebook _44cn1_sm_p3_0 = {
  142225. 2, 81,
  142226. _vq_lengthlist__44cn1_sm_p3_0,
  142227. 1, -531628032, 1611661312, 4, 0,
  142228. _vq_quantlist__44cn1_sm_p3_0,
  142229. NULL,
  142230. &_vq_auxt__44cn1_sm_p3_0,
  142231. NULL,
  142232. 0
  142233. };
  142234. static long _vq_quantlist__44cn1_sm_p4_0[] = {
  142235. 4,
  142236. 3,
  142237. 5,
  142238. 2,
  142239. 6,
  142240. 1,
  142241. 7,
  142242. 0,
  142243. 8,
  142244. };
  142245. static long _vq_lengthlist__44cn1_sm_p4_0[] = {
  142246. 1, 4, 3, 6, 6, 7, 7, 9, 9, 0, 5, 5, 7, 7, 8, 7,
  142247. 9, 9, 0, 5, 5, 7, 7, 8, 8, 9, 9, 0, 7, 7, 8, 8,
  142248. 8, 8,10,10, 0, 0, 0, 8, 8, 8, 8,10,10, 0, 0, 0,
  142249. 9, 9, 9, 9,10,10, 0, 0, 0, 9, 9, 9, 9,10,10, 0,
  142250. 0, 0,10,10,10,10,11,11, 0, 0, 0, 0, 0,10,10,11,
  142251. 11,
  142252. };
  142253. static float _vq_quantthresh__44cn1_sm_p4_0[] = {
  142254. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  142255. };
  142256. static long _vq_quantmap__44cn1_sm_p4_0[] = {
  142257. 7, 5, 3, 1, 0, 2, 4, 6,
  142258. 8,
  142259. };
  142260. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p4_0 = {
  142261. _vq_quantthresh__44cn1_sm_p4_0,
  142262. _vq_quantmap__44cn1_sm_p4_0,
  142263. 9,
  142264. 9
  142265. };
  142266. static static_codebook _44cn1_sm_p4_0 = {
  142267. 2, 81,
  142268. _vq_lengthlist__44cn1_sm_p4_0,
  142269. 1, -531628032, 1611661312, 4, 0,
  142270. _vq_quantlist__44cn1_sm_p4_0,
  142271. NULL,
  142272. &_vq_auxt__44cn1_sm_p4_0,
  142273. NULL,
  142274. 0
  142275. };
  142276. static long _vq_quantlist__44cn1_sm_p5_0[] = {
  142277. 8,
  142278. 7,
  142279. 9,
  142280. 6,
  142281. 10,
  142282. 5,
  142283. 11,
  142284. 4,
  142285. 12,
  142286. 3,
  142287. 13,
  142288. 2,
  142289. 14,
  142290. 1,
  142291. 15,
  142292. 0,
  142293. 16,
  142294. };
  142295. static long _vq_lengthlist__44cn1_sm_p5_0[] = {
  142296. 1, 4, 4, 6, 6, 8, 8, 9, 9, 8, 8, 9, 9,10,10,11,
  142297. 11, 0, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  142298. 12,12, 0, 6, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  142299. 11,12,12, 0, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  142300. 11,11,12,12, 0, 0, 0, 7, 7, 8, 8, 9, 9,10,10,11,
  142301. 11,11,11,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,10,
  142302. 11,11,12,12,12,12, 0, 0, 0, 8, 8, 9, 9,10,10,10,
  142303. 10,11,11,12,12,12,12, 0, 0, 0, 9, 9, 9, 9,10,10,
  142304. 10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,10,
  142305. 10,10,10,11,11,12,12,13,13, 0, 0, 0, 0, 0, 9, 9,
  142306. 10,10,11,11,12,12,13,13,13,13, 0, 0, 0, 0, 0, 9,
  142307. 9,10,10,11,11,12,12,12,13,13,13, 0, 0, 0, 0, 0,
  142308. 10,10,11,11,11,11,12,12,13,13,14,14, 0, 0, 0, 0,
  142309. 0, 0, 0,11,11,11,11,12,12,13,13,14,14, 0, 0, 0,
  142310. 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0, 0,
  142311. 0, 0, 0, 0, 0,11,11,12,12,13,13,13,13,14,14, 0,
  142312. 0, 0, 0, 0, 0, 0,12,12,12,13,13,13,14,14,14,14,
  142313. 0, 0, 0, 0, 0, 0, 0, 0, 0,12,12,13,13,14,14,14,
  142314. 14,
  142315. };
  142316. static float _vq_quantthresh__44cn1_sm_p5_0[] = {
  142317. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142318. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142319. };
  142320. static long _vq_quantmap__44cn1_sm_p5_0[] = {
  142321. 15, 13, 11, 9, 7, 5, 3, 1,
  142322. 0, 2, 4, 6, 8, 10, 12, 14,
  142323. 16,
  142324. };
  142325. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p5_0 = {
  142326. _vq_quantthresh__44cn1_sm_p5_0,
  142327. _vq_quantmap__44cn1_sm_p5_0,
  142328. 17,
  142329. 17
  142330. };
  142331. static static_codebook _44cn1_sm_p5_0 = {
  142332. 2, 289,
  142333. _vq_lengthlist__44cn1_sm_p5_0,
  142334. 1, -529530880, 1611661312, 5, 0,
  142335. _vq_quantlist__44cn1_sm_p5_0,
  142336. NULL,
  142337. &_vq_auxt__44cn1_sm_p5_0,
  142338. NULL,
  142339. 0
  142340. };
  142341. static long _vq_quantlist__44cn1_sm_p6_0[] = {
  142342. 1,
  142343. 0,
  142344. 2,
  142345. };
  142346. static long _vq_lengthlist__44cn1_sm_p6_0[] = {
  142347. 1, 4, 4, 7, 6, 6, 7, 6, 6, 4, 7, 6,10, 9, 9,11,
  142348. 9, 9, 4, 6, 7,10, 9, 9,11, 9, 9, 7,10,10,10,11,
  142349. 11,11,11,10, 6, 9, 9,11,10,10,11,10,10, 6, 9, 9,
  142350. 11,10,11,11,10,10, 7,11,11,11,11,11,12,11,11, 7,
  142351. 9, 9,11,10,10,12,10,10, 7, 9, 9,11,10,10,11,10,
  142352. 10,
  142353. };
  142354. static float _vq_quantthresh__44cn1_sm_p6_0[] = {
  142355. -5.5, 5.5,
  142356. };
  142357. static long _vq_quantmap__44cn1_sm_p6_0[] = {
  142358. 1, 0, 2,
  142359. };
  142360. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_0 = {
  142361. _vq_quantthresh__44cn1_sm_p6_0,
  142362. _vq_quantmap__44cn1_sm_p6_0,
  142363. 3,
  142364. 3
  142365. };
  142366. static static_codebook _44cn1_sm_p6_0 = {
  142367. 4, 81,
  142368. _vq_lengthlist__44cn1_sm_p6_0,
  142369. 1, -529137664, 1618345984, 2, 0,
  142370. _vq_quantlist__44cn1_sm_p6_0,
  142371. NULL,
  142372. &_vq_auxt__44cn1_sm_p6_0,
  142373. NULL,
  142374. 0
  142375. };
  142376. static long _vq_quantlist__44cn1_sm_p6_1[] = {
  142377. 5,
  142378. 4,
  142379. 6,
  142380. 3,
  142381. 7,
  142382. 2,
  142383. 8,
  142384. 1,
  142385. 9,
  142386. 0,
  142387. 10,
  142388. };
  142389. static long _vq_lengthlist__44cn1_sm_p6_1[] = {
  142390. 2, 4, 4, 5, 5, 7, 7, 7, 7, 8, 8,10, 5, 5, 6, 6,
  142391. 7, 7, 8, 8, 8, 8,10, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  142392. 8,10, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8,10,10,10, 7,
  142393. 7, 7, 7, 8, 8, 8, 8,10,10,10, 8, 8, 8, 8, 8, 8,
  142394. 8, 8,10,10,10, 8, 8, 8, 8, 8, 8, 8, 8,10,10,10,
  142395. 8, 8, 8, 8, 8, 8, 9, 9,10,10,10,10,10, 8, 8, 8,
  142396. 8, 9, 9,10,10,10,10,10, 9, 9, 9, 9, 8, 9,10,10,
  142397. 10,10,10, 8, 9, 8, 8, 9, 8,
  142398. };
  142399. static float _vq_quantthresh__44cn1_sm_p6_1[] = {
  142400. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  142401. 3.5, 4.5,
  142402. };
  142403. static long _vq_quantmap__44cn1_sm_p6_1[] = {
  142404. 9, 7, 5, 3, 1, 0, 2, 4,
  142405. 6, 8, 10,
  142406. };
  142407. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p6_1 = {
  142408. _vq_quantthresh__44cn1_sm_p6_1,
  142409. _vq_quantmap__44cn1_sm_p6_1,
  142410. 11,
  142411. 11
  142412. };
  142413. static static_codebook _44cn1_sm_p6_1 = {
  142414. 2, 121,
  142415. _vq_lengthlist__44cn1_sm_p6_1,
  142416. 1, -531365888, 1611661312, 4, 0,
  142417. _vq_quantlist__44cn1_sm_p6_1,
  142418. NULL,
  142419. &_vq_auxt__44cn1_sm_p6_1,
  142420. NULL,
  142421. 0
  142422. };
  142423. static long _vq_quantlist__44cn1_sm_p7_0[] = {
  142424. 6,
  142425. 5,
  142426. 7,
  142427. 4,
  142428. 8,
  142429. 3,
  142430. 9,
  142431. 2,
  142432. 10,
  142433. 1,
  142434. 11,
  142435. 0,
  142436. 12,
  142437. };
  142438. static long _vq_lengthlist__44cn1_sm_p7_0[] = {
  142439. 1, 4, 4, 6, 6, 7, 7, 7, 7, 9, 9,10,10, 7, 5, 5,
  142440. 7, 7, 8, 8, 8, 8,10, 9,11,10, 7, 5, 5, 7, 7, 8,
  142441. 8, 8, 8, 9,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,
  142442. 10,10,11,11, 0, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,
  142443. 11, 0,12,12, 9, 9, 9,10,10,10,11,11,12,12, 0,13,
  142444. 13, 9, 9, 9, 9,10,10,11,11,12,12, 0, 0, 0,10,10,
  142445. 10,10,11,11,12,12,12,13, 0, 0, 0,10,10,10,10,11,
  142446. 11,12,12,12,12, 0, 0, 0,14,14,11,11,11,11,12,13,
  142447. 13,13, 0, 0, 0,14,14,11,10,11,11,12,12,13,13, 0,
  142448. 0, 0, 0, 0,12,12,12,12,13,13,13,14, 0, 0, 0, 0,
  142449. 0,13,12,12,12,13,13,13,14,
  142450. };
  142451. static float _vq_quantthresh__44cn1_sm_p7_0[] = {
  142452. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  142453. 12.5, 17.5, 22.5, 27.5,
  142454. };
  142455. static long _vq_quantmap__44cn1_sm_p7_0[] = {
  142456. 11, 9, 7, 5, 3, 1, 0, 2,
  142457. 4, 6, 8, 10, 12,
  142458. };
  142459. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_0 = {
  142460. _vq_quantthresh__44cn1_sm_p7_0,
  142461. _vq_quantmap__44cn1_sm_p7_0,
  142462. 13,
  142463. 13
  142464. };
  142465. static static_codebook _44cn1_sm_p7_0 = {
  142466. 2, 169,
  142467. _vq_lengthlist__44cn1_sm_p7_0,
  142468. 1, -526516224, 1616117760, 4, 0,
  142469. _vq_quantlist__44cn1_sm_p7_0,
  142470. NULL,
  142471. &_vq_auxt__44cn1_sm_p7_0,
  142472. NULL,
  142473. 0
  142474. };
  142475. static long _vq_quantlist__44cn1_sm_p7_1[] = {
  142476. 2,
  142477. 1,
  142478. 3,
  142479. 0,
  142480. 4,
  142481. };
  142482. static long _vq_lengthlist__44cn1_sm_p7_1[] = {
  142483. 2, 4, 4, 4, 5, 6, 5, 5, 5, 5, 6, 5, 5, 5, 5, 6,
  142484. 5, 5, 5, 5, 6, 6, 6, 5, 5,
  142485. };
  142486. static float _vq_quantthresh__44cn1_sm_p7_1[] = {
  142487. -1.5, -0.5, 0.5, 1.5,
  142488. };
  142489. static long _vq_quantmap__44cn1_sm_p7_1[] = {
  142490. 3, 1, 0, 2, 4,
  142491. };
  142492. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p7_1 = {
  142493. _vq_quantthresh__44cn1_sm_p7_1,
  142494. _vq_quantmap__44cn1_sm_p7_1,
  142495. 5,
  142496. 5
  142497. };
  142498. static static_codebook _44cn1_sm_p7_1 = {
  142499. 2, 25,
  142500. _vq_lengthlist__44cn1_sm_p7_1,
  142501. 1, -533725184, 1611661312, 3, 0,
  142502. _vq_quantlist__44cn1_sm_p7_1,
  142503. NULL,
  142504. &_vq_auxt__44cn1_sm_p7_1,
  142505. NULL,
  142506. 0
  142507. };
  142508. static long _vq_quantlist__44cn1_sm_p8_0[] = {
  142509. 4,
  142510. 3,
  142511. 5,
  142512. 2,
  142513. 6,
  142514. 1,
  142515. 7,
  142516. 0,
  142517. 8,
  142518. };
  142519. static long _vq_lengthlist__44cn1_sm_p8_0[] = {
  142520. 1, 4, 4,12,11,13,13,14,14, 4, 7, 7,11,13,14,14,
  142521. 14,14, 3, 8, 3,14,14,14,14,14,14,14,10,12,14,14,
  142522. 14,14,14,14,14,14, 5,14, 8,14,14,14,14,14,12,14,
  142523. 13,14,14,14,14,14,14,14,13,14,10,14,14,14,14,14,
  142524. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  142525. 14,
  142526. };
  142527. static float _vq_quantthresh__44cn1_sm_p8_0[] = {
  142528. -773.5, -552.5, -331.5, -110.5, 110.5, 331.5, 552.5, 773.5,
  142529. };
  142530. static long _vq_quantmap__44cn1_sm_p8_0[] = {
  142531. 7, 5, 3, 1, 0, 2, 4, 6,
  142532. 8,
  142533. };
  142534. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_0 = {
  142535. _vq_quantthresh__44cn1_sm_p8_0,
  142536. _vq_quantmap__44cn1_sm_p8_0,
  142537. 9,
  142538. 9
  142539. };
  142540. static static_codebook _44cn1_sm_p8_0 = {
  142541. 2, 81,
  142542. _vq_lengthlist__44cn1_sm_p8_0,
  142543. 1, -516186112, 1627103232, 4, 0,
  142544. _vq_quantlist__44cn1_sm_p8_0,
  142545. NULL,
  142546. &_vq_auxt__44cn1_sm_p8_0,
  142547. NULL,
  142548. 0
  142549. };
  142550. static long _vq_quantlist__44cn1_sm_p8_1[] = {
  142551. 6,
  142552. 5,
  142553. 7,
  142554. 4,
  142555. 8,
  142556. 3,
  142557. 9,
  142558. 2,
  142559. 10,
  142560. 1,
  142561. 11,
  142562. 0,
  142563. 12,
  142564. };
  142565. static long _vq_lengthlist__44cn1_sm_p8_1[] = {
  142566. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,11,11, 6, 5, 5,
  142567. 7, 7, 8, 8,10,10,10,11,11,11, 6, 5, 5, 7, 7, 8,
  142568. 8,10,10,11,12,12,12,14, 7, 7, 7, 8, 9, 9,11,11,
  142569. 11,12,11,12,17, 7, 7, 8, 7, 9, 9,11,11,12,12,12,
  142570. 12,14,11,11, 8, 8,10,10,11,12,12,13,11,12,14,11,
  142571. 11, 8, 8,10,10,11,12,12,13,13,12,14,15,14,10,10,
  142572. 10,10,11,12,12,12,12,11,14,13,16,10,10,10, 9,12,
  142573. 11,12,12,13,14,14,15,14,14,13,10,10,11,11,12,11,
  142574. 13,11,14,12,15,13,14,11,10,12,10,12,12,13,13,13,
  142575. 13,14,15,15,12,12,11,11,12,11,13,12,14,14,14,14,
  142576. 17,12,12,11,10,13,11,13,13,
  142577. };
  142578. static float _vq_quantthresh__44cn1_sm_p8_1[] = {
  142579. -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5, 25.5,
  142580. 42.5, 59.5, 76.5, 93.5,
  142581. };
  142582. static long _vq_quantmap__44cn1_sm_p8_1[] = {
  142583. 11, 9, 7, 5, 3, 1, 0, 2,
  142584. 4, 6, 8, 10, 12,
  142585. };
  142586. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_1 = {
  142587. _vq_quantthresh__44cn1_sm_p8_1,
  142588. _vq_quantmap__44cn1_sm_p8_1,
  142589. 13,
  142590. 13
  142591. };
  142592. static static_codebook _44cn1_sm_p8_1 = {
  142593. 2, 169,
  142594. _vq_lengthlist__44cn1_sm_p8_1,
  142595. 1, -522616832, 1620115456, 4, 0,
  142596. _vq_quantlist__44cn1_sm_p8_1,
  142597. NULL,
  142598. &_vq_auxt__44cn1_sm_p8_1,
  142599. NULL,
  142600. 0
  142601. };
  142602. static long _vq_quantlist__44cn1_sm_p8_2[] = {
  142603. 8,
  142604. 7,
  142605. 9,
  142606. 6,
  142607. 10,
  142608. 5,
  142609. 11,
  142610. 4,
  142611. 12,
  142612. 3,
  142613. 13,
  142614. 2,
  142615. 14,
  142616. 1,
  142617. 15,
  142618. 0,
  142619. 16,
  142620. };
  142621. static long _vq_lengthlist__44cn1_sm_p8_2[] = {
  142622. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  142623. 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9,
  142624. 9, 9,10, 6, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9,
  142625. 9, 9, 9,10, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,
  142626. 9, 9, 9, 9,10,10,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,
  142627. 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9, 9,
  142628. 9, 9, 9, 9, 9, 9,10,10,10, 8, 8, 8, 8, 8, 8, 9,
  142629. 9, 9, 9, 9, 9, 9, 9,11,10,11, 8, 8, 8, 8, 8, 8,
  142630. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,11,11, 8, 8, 8,
  142631. 8, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,11, 9, 9,
  142632. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,10,11,11, 9,
  142633. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,10,11,11,
  142634. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,10,11,11,
  142635. 11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,11,11,
  142636. 11,11,11,11, 9,10,10,10, 9, 9, 9, 9, 9, 9,11,10,
  142637. 11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,11,
  142638. 11,11,11,11,11,11,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  142639. 10,11,11,11,11,11,11,11,11, 9, 9, 9, 9, 9, 9, 9,
  142640. 9,
  142641. };
  142642. static float _vq_quantthresh__44cn1_sm_p8_2[] = {
  142643. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  142644. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  142645. };
  142646. static long _vq_quantmap__44cn1_sm_p8_2[] = {
  142647. 15, 13, 11, 9, 7, 5, 3, 1,
  142648. 0, 2, 4, 6, 8, 10, 12, 14,
  142649. 16,
  142650. };
  142651. static encode_aux_threshmatch _vq_auxt__44cn1_sm_p8_2 = {
  142652. _vq_quantthresh__44cn1_sm_p8_2,
  142653. _vq_quantmap__44cn1_sm_p8_2,
  142654. 17,
  142655. 17
  142656. };
  142657. static static_codebook _44cn1_sm_p8_2 = {
  142658. 2, 289,
  142659. _vq_lengthlist__44cn1_sm_p8_2,
  142660. 1, -529530880, 1611661312, 5, 0,
  142661. _vq_quantlist__44cn1_sm_p8_2,
  142662. NULL,
  142663. &_vq_auxt__44cn1_sm_p8_2,
  142664. NULL,
  142665. 0
  142666. };
  142667. static long _huff_lengthlist__44cn1_sm_short[] = {
  142668. 5, 6,12,14,12,14,16,17,18, 4, 2, 5,11, 7,10,12,
  142669. 14,15, 9, 4, 5,11, 7,10,13,15,18,15, 6, 7, 5, 6,
  142670. 8,11,13,16,11, 5, 6, 5, 5, 6, 9,13,15,12, 5, 7,
  142671. 6, 5, 6, 9,12,14,12, 6, 7, 8, 6, 7, 9,12,13,14,
  142672. 8, 8, 7, 5, 5, 8,10,12,16, 9, 9, 8, 6, 6, 7, 9,
  142673. 9,
  142674. };
  142675. static static_codebook _huff_book__44cn1_sm_short = {
  142676. 2, 81,
  142677. _huff_lengthlist__44cn1_sm_short,
  142678. 0, 0, 0, 0, 0,
  142679. NULL,
  142680. NULL,
  142681. NULL,
  142682. NULL,
  142683. 0
  142684. };
  142685. /********* End of inlined file: res_books_stereo.h *********/
  142686. /***** residue backends *********************************************/
  142687. static vorbis_info_residue0 _residue_44_low={
  142688. 0,-1, -1, 9,-1,
  142689. /* 0 1 2 3 4 5 6 7 */
  142690. {0},
  142691. {-1},
  142692. { .5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142693. { .5, .5, .5, 999., 4.5, 8.5, 16.5, 32.5},
  142694. };
  142695. static vorbis_info_residue0 _residue_44_mid={
  142696. 0,-1, -1, 10,-1,
  142697. /* 0 1 2 3 4 5 6 7 8 */
  142698. {0},
  142699. {-1},
  142700. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 8.5, 16.5, 32.5},
  142701. { .5, .5, 999., .5, 999., 4.5, 8.5, 16.5, 32.5},
  142702. };
  142703. static vorbis_info_residue0 _residue_44_high={
  142704. 0,-1, -1, 10,-1,
  142705. /* 0 1 2 3 4 5 6 7 8 */
  142706. {0},
  142707. {-1},
  142708. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  142709. { .5, 1.5, 2.5, 3.5, 4.5, 8.5, 16.5, 71.5,157.5},
  142710. };
  142711. static static_bookblock _resbook_44s_n1={
  142712. {
  142713. {0},{0,0,&_44cn1_s_p1_0},{0,0,&_44cn1_s_p2_0},
  142714. {0,0,&_44cn1_s_p3_0},{0,0,&_44cn1_s_p4_0},{0,0,&_44cn1_s_p5_0},
  142715. {&_44cn1_s_p6_0,&_44cn1_s_p6_1},{&_44cn1_s_p7_0,&_44cn1_s_p7_1},
  142716. {&_44cn1_s_p8_0,&_44cn1_s_p8_1,&_44cn1_s_p8_2}
  142717. }
  142718. };
  142719. static static_bookblock _resbook_44sm_n1={
  142720. {
  142721. {0},{0,0,&_44cn1_sm_p1_0},{0,0,&_44cn1_sm_p2_0},
  142722. {0,0,&_44cn1_sm_p3_0},{0,0,&_44cn1_sm_p4_0},{0,0,&_44cn1_sm_p5_0},
  142723. {&_44cn1_sm_p6_0,&_44cn1_sm_p6_1},{&_44cn1_sm_p7_0,&_44cn1_sm_p7_1},
  142724. {&_44cn1_sm_p8_0,&_44cn1_sm_p8_1,&_44cn1_sm_p8_2}
  142725. }
  142726. };
  142727. static static_bookblock _resbook_44s_0={
  142728. {
  142729. {0},{0,0,&_44c0_s_p1_0},{0,0,&_44c0_s_p2_0},
  142730. {0,0,&_44c0_s_p3_0},{0,0,&_44c0_s_p4_0},{0,0,&_44c0_s_p5_0},
  142731. {&_44c0_s_p6_0,&_44c0_s_p6_1},{&_44c0_s_p7_0,&_44c0_s_p7_1},
  142732. {&_44c0_s_p8_0,&_44c0_s_p8_1,&_44c0_s_p8_2}
  142733. }
  142734. };
  142735. static static_bookblock _resbook_44sm_0={
  142736. {
  142737. {0},{0,0,&_44c0_sm_p1_0},{0,0,&_44c0_sm_p2_0},
  142738. {0,0,&_44c0_sm_p3_0},{0,0,&_44c0_sm_p4_0},{0,0,&_44c0_sm_p5_0},
  142739. {&_44c0_sm_p6_0,&_44c0_sm_p6_1},{&_44c0_sm_p7_0,&_44c0_sm_p7_1},
  142740. {&_44c0_sm_p8_0,&_44c0_sm_p8_1,&_44c0_sm_p8_2}
  142741. }
  142742. };
  142743. static static_bookblock _resbook_44s_1={
  142744. {
  142745. {0},{0,0,&_44c1_s_p1_0},{0,0,&_44c1_s_p2_0},
  142746. {0,0,&_44c1_s_p3_0},{0,0,&_44c1_s_p4_0},{0,0,&_44c1_s_p5_0},
  142747. {&_44c1_s_p6_0,&_44c1_s_p6_1},{&_44c1_s_p7_0,&_44c1_s_p7_1},
  142748. {&_44c1_s_p8_0,&_44c1_s_p8_1,&_44c1_s_p8_2}
  142749. }
  142750. };
  142751. static static_bookblock _resbook_44sm_1={
  142752. {
  142753. {0},{0,0,&_44c1_sm_p1_0},{0,0,&_44c1_sm_p2_0},
  142754. {0,0,&_44c1_sm_p3_0},{0,0,&_44c1_sm_p4_0},{0,0,&_44c1_sm_p5_0},
  142755. {&_44c1_sm_p6_0,&_44c1_sm_p6_1},{&_44c1_sm_p7_0,&_44c1_sm_p7_1},
  142756. {&_44c1_sm_p8_0,&_44c1_sm_p8_1,&_44c1_sm_p8_2}
  142757. }
  142758. };
  142759. static static_bookblock _resbook_44s_2={
  142760. {
  142761. {0},{0,0,&_44c2_s_p1_0},{0,0,&_44c2_s_p2_0},{0,0,&_44c2_s_p3_0},
  142762. {0,0,&_44c2_s_p4_0},{0,0,&_44c2_s_p5_0},{0,0,&_44c2_s_p6_0},
  142763. {&_44c2_s_p7_0,&_44c2_s_p7_1},{&_44c2_s_p8_0,&_44c2_s_p8_1},
  142764. {&_44c2_s_p9_0,&_44c2_s_p9_1,&_44c2_s_p9_2}
  142765. }
  142766. };
  142767. static static_bookblock _resbook_44s_3={
  142768. {
  142769. {0},{0,0,&_44c3_s_p1_0},{0,0,&_44c3_s_p2_0},{0,0,&_44c3_s_p3_0},
  142770. {0,0,&_44c3_s_p4_0},{0,0,&_44c3_s_p5_0},{0,0,&_44c3_s_p6_0},
  142771. {&_44c3_s_p7_0,&_44c3_s_p7_1},{&_44c3_s_p8_0,&_44c3_s_p8_1},
  142772. {&_44c3_s_p9_0,&_44c3_s_p9_1,&_44c3_s_p9_2}
  142773. }
  142774. };
  142775. static static_bookblock _resbook_44s_4={
  142776. {
  142777. {0},{0,0,&_44c4_s_p1_0},{0,0,&_44c4_s_p2_0},{0,0,&_44c4_s_p3_0},
  142778. {0,0,&_44c4_s_p4_0},{0,0,&_44c4_s_p5_0},{0,0,&_44c4_s_p6_0},
  142779. {&_44c4_s_p7_0,&_44c4_s_p7_1},{&_44c4_s_p8_0,&_44c4_s_p8_1},
  142780. {&_44c4_s_p9_0,&_44c4_s_p9_1,&_44c4_s_p9_2}
  142781. }
  142782. };
  142783. static static_bookblock _resbook_44s_5={
  142784. {
  142785. {0},{0,0,&_44c5_s_p1_0},{0,0,&_44c5_s_p2_0},{0,0,&_44c5_s_p3_0},
  142786. {0,0,&_44c5_s_p4_0},{0,0,&_44c5_s_p5_0},{0,0,&_44c5_s_p6_0},
  142787. {&_44c5_s_p7_0,&_44c5_s_p7_1},{&_44c5_s_p8_0,&_44c5_s_p8_1},
  142788. {&_44c5_s_p9_0,&_44c5_s_p9_1,&_44c5_s_p9_2}
  142789. }
  142790. };
  142791. static static_bookblock _resbook_44s_6={
  142792. {
  142793. {0},{0,0,&_44c6_s_p1_0},{0,0,&_44c6_s_p2_0},{0,0,&_44c6_s_p3_0},
  142794. {0,0,&_44c6_s_p4_0},
  142795. {&_44c6_s_p5_0,&_44c6_s_p5_1},
  142796. {&_44c6_s_p6_0,&_44c6_s_p6_1},
  142797. {&_44c6_s_p7_0,&_44c6_s_p7_1},
  142798. {&_44c6_s_p8_0,&_44c6_s_p8_1},
  142799. {&_44c6_s_p9_0,&_44c6_s_p9_1,&_44c6_s_p9_2}
  142800. }
  142801. };
  142802. static static_bookblock _resbook_44s_7={
  142803. {
  142804. {0},{0,0,&_44c7_s_p1_0},{0,0,&_44c7_s_p2_0},{0,0,&_44c7_s_p3_0},
  142805. {0,0,&_44c7_s_p4_0},
  142806. {&_44c7_s_p5_0,&_44c7_s_p5_1},
  142807. {&_44c7_s_p6_0,&_44c7_s_p6_1},
  142808. {&_44c7_s_p7_0,&_44c7_s_p7_1},
  142809. {&_44c7_s_p8_0,&_44c7_s_p8_1},
  142810. {&_44c7_s_p9_0,&_44c7_s_p9_1,&_44c7_s_p9_2}
  142811. }
  142812. };
  142813. static static_bookblock _resbook_44s_8={
  142814. {
  142815. {0},{0,0,&_44c8_s_p1_0},{0,0,&_44c8_s_p2_0},{0,0,&_44c8_s_p3_0},
  142816. {0,0,&_44c8_s_p4_0},
  142817. {&_44c8_s_p5_0,&_44c8_s_p5_1},
  142818. {&_44c8_s_p6_0,&_44c8_s_p6_1},
  142819. {&_44c8_s_p7_0,&_44c8_s_p7_1},
  142820. {&_44c8_s_p8_0,&_44c8_s_p8_1},
  142821. {&_44c8_s_p9_0,&_44c8_s_p9_1,&_44c8_s_p9_2}
  142822. }
  142823. };
  142824. static static_bookblock _resbook_44s_9={
  142825. {
  142826. {0},{0,0,&_44c9_s_p1_0},{0,0,&_44c9_s_p2_0},{0,0,&_44c9_s_p3_0},
  142827. {0,0,&_44c9_s_p4_0},
  142828. {&_44c9_s_p5_0,&_44c9_s_p5_1},
  142829. {&_44c9_s_p6_0,&_44c9_s_p6_1},
  142830. {&_44c9_s_p7_0,&_44c9_s_p7_1},
  142831. {&_44c9_s_p8_0,&_44c9_s_p8_1},
  142832. {&_44c9_s_p9_0,&_44c9_s_p9_1,&_44c9_s_p9_2}
  142833. }
  142834. };
  142835. static vorbis_residue_template _res_44s_n1[]={
  142836. {2,0, &_residue_44_low,
  142837. &_huff_book__44cn1_s_short,&_huff_book__44cn1_sm_short,
  142838. &_resbook_44s_n1,&_resbook_44sm_n1},
  142839. {2,0, &_residue_44_low,
  142840. &_huff_book__44cn1_s_long,&_huff_book__44cn1_sm_long,
  142841. &_resbook_44s_n1,&_resbook_44sm_n1}
  142842. };
  142843. static vorbis_residue_template _res_44s_0[]={
  142844. {2,0, &_residue_44_low,
  142845. &_huff_book__44c0_s_short,&_huff_book__44c0_sm_short,
  142846. &_resbook_44s_0,&_resbook_44sm_0},
  142847. {2,0, &_residue_44_low,
  142848. &_huff_book__44c0_s_long,&_huff_book__44c0_sm_long,
  142849. &_resbook_44s_0,&_resbook_44sm_0}
  142850. };
  142851. static vorbis_residue_template _res_44s_1[]={
  142852. {2,0, &_residue_44_low,
  142853. &_huff_book__44c1_s_short,&_huff_book__44c1_sm_short,
  142854. &_resbook_44s_1,&_resbook_44sm_1},
  142855. {2,0, &_residue_44_low,
  142856. &_huff_book__44c1_s_long,&_huff_book__44c1_sm_long,
  142857. &_resbook_44s_1,&_resbook_44sm_1}
  142858. };
  142859. static vorbis_residue_template _res_44s_2[]={
  142860. {2,0, &_residue_44_mid,
  142861. &_huff_book__44c2_s_short,&_huff_book__44c2_s_short,
  142862. &_resbook_44s_2,&_resbook_44s_2},
  142863. {2,0, &_residue_44_mid,
  142864. &_huff_book__44c2_s_long,&_huff_book__44c2_s_long,
  142865. &_resbook_44s_2,&_resbook_44s_2}
  142866. };
  142867. static vorbis_residue_template _res_44s_3[]={
  142868. {2,0, &_residue_44_mid,
  142869. &_huff_book__44c3_s_short,&_huff_book__44c3_s_short,
  142870. &_resbook_44s_3,&_resbook_44s_3},
  142871. {2,0, &_residue_44_mid,
  142872. &_huff_book__44c3_s_long,&_huff_book__44c3_s_long,
  142873. &_resbook_44s_3,&_resbook_44s_3}
  142874. };
  142875. static vorbis_residue_template _res_44s_4[]={
  142876. {2,0, &_residue_44_mid,
  142877. &_huff_book__44c4_s_short,&_huff_book__44c4_s_short,
  142878. &_resbook_44s_4,&_resbook_44s_4},
  142879. {2,0, &_residue_44_mid,
  142880. &_huff_book__44c4_s_long,&_huff_book__44c4_s_long,
  142881. &_resbook_44s_4,&_resbook_44s_4}
  142882. };
  142883. static vorbis_residue_template _res_44s_5[]={
  142884. {2,0, &_residue_44_mid,
  142885. &_huff_book__44c5_s_short,&_huff_book__44c5_s_short,
  142886. &_resbook_44s_5,&_resbook_44s_5},
  142887. {2,0, &_residue_44_mid,
  142888. &_huff_book__44c5_s_long,&_huff_book__44c5_s_long,
  142889. &_resbook_44s_5,&_resbook_44s_5}
  142890. };
  142891. static vorbis_residue_template _res_44s_6[]={
  142892. {2,0, &_residue_44_high,
  142893. &_huff_book__44c6_s_short,&_huff_book__44c6_s_short,
  142894. &_resbook_44s_6,&_resbook_44s_6},
  142895. {2,0, &_residue_44_high,
  142896. &_huff_book__44c6_s_long,&_huff_book__44c6_s_long,
  142897. &_resbook_44s_6,&_resbook_44s_6}
  142898. };
  142899. static vorbis_residue_template _res_44s_7[]={
  142900. {2,0, &_residue_44_high,
  142901. &_huff_book__44c7_s_short,&_huff_book__44c7_s_short,
  142902. &_resbook_44s_7,&_resbook_44s_7},
  142903. {2,0, &_residue_44_high,
  142904. &_huff_book__44c7_s_long,&_huff_book__44c7_s_long,
  142905. &_resbook_44s_7,&_resbook_44s_7}
  142906. };
  142907. static vorbis_residue_template _res_44s_8[]={
  142908. {2,0, &_residue_44_high,
  142909. &_huff_book__44c8_s_short,&_huff_book__44c8_s_short,
  142910. &_resbook_44s_8,&_resbook_44s_8},
  142911. {2,0, &_residue_44_high,
  142912. &_huff_book__44c8_s_long,&_huff_book__44c8_s_long,
  142913. &_resbook_44s_8,&_resbook_44s_8}
  142914. };
  142915. static vorbis_residue_template _res_44s_9[]={
  142916. {2,0, &_residue_44_high,
  142917. &_huff_book__44c9_s_short,&_huff_book__44c9_s_short,
  142918. &_resbook_44s_9,&_resbook_44s_9},
  142919. {2,0, &_residue_44_high,
  142920. &_huff_book__44c9_s_long,&_huff_book__44c9_s_long,
  142921. &_resbook_44s_9,&_resbook_44s_9}
  142922. };
  142923. static vorbis_mapping_template _mapres_template_44_stereo[]={
  142924. { _map_nominal, _res_44s_n1 }, /* -1 */
  142925. { _map_nominal, _res_44s_0 }, /* 0 */
  142926. { _map_nominal, _res_44s_1 }, /* 1 */
  142927. { _map_nominal, _res_44s_2 }, /* 2 */
  142928. { _map_nominal, _res_44s_3 }, /* 3 */
  142929. { _map_nominal, _res_44s_4 }, /* 4 */
  142930. { _map_nominal, _res_44s_5 }, /* 5 */
  142931. { _map_nominal, _res_44s_6 }, /* 6 */
  142932. { _map_nominal, _res_44s_7 }, /* 7 */
  142933. { _map_nominal, _res_44s_8 }, /* 8 */
  142934. { _map_nominal, _res_44s_9 }, /* 9 */
  142935. };
  142936. /********* End of inlined file: residue_44.h *********/
  142937. /********* Start of inlined file: psych_44.h *********/
  142938. /* preecho trigger settings *****************************************/
  142939. static vorbis_info_psy_global _psy_global_44[5]={
  142940. {8, /* lines per eighth octave */
  142941. {20.f,14.f,12.f,12.f,12.f,12.f,12.f},
  142942. {-60.f,-30.f,-40.f,-40.f,-40.f,-40.f,-40.f}, 2,-75.f,
  142943. -6.f,
  142944. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142945. },
  142946. {8, /* lines per eighth octave */
  142947. {14.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142948. {-40.f,-30.f,-25.f,-25.f,-25.f,-25.f,-25.f}, 2,-80.f,
  142949. -6.f,
  142950. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142951. },
  142952. {8, /* lines per eighth octave */
  142953. {12.f,10.f,10.f,10.f,10.f,10.f,10.f},
  142954. {-20.f,-20.f,-15.f,-15.f,-15.f,-15.f,-15.f}, 0,-80.f,
  142955. -6.f,
  142956. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142957. },
  142958. {8, /* lines per eighth octave */
  142959. {10.f,8.f,8.f,8.f,8.f,8.f,8.f},
  142960. {-20.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-80.f,
  142961. -6.f,
  142962. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142963. },
  142964. {8, /* lines per eighth octave */
  142965. {10.f,6.f,6.f,6.f,6.f,6.f,6.f},
  142966. {-15.f,-15.f,-12.f,-12.f,-12.f,-12.f,-12.f}, 0,-85.f,
  142967. -6.f,
  142968. {99.},{{99.},{99.}},{0},{0},{{0.},{0.}}
  142969. },
  142970. };
  142971. /* noise compander lookups * low, mid, high quality ****************/
  142972. static compandblock _psy_compand_44[6]={
  142973. /* sub-mode Z short */
  142974. {{
  142975. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  142976. 8, 9,10,11,12,13,14, 15, /* 15dB */
  142977. 16,17,18,19,20,21,22, 23, /* 23dB */
  142978. 24,25,26,27,28,29,30, 31, /* 31dB */
  142979. 32,33,34,35,36,37,38, 39, /* 39dB */
  142980. }},
  142981. /* mode_Z nominal short */
  142982. {{
  142983. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  142984. 7, 7, 7, 7, 6, 6, 6, 7, /* 15dB */
  142985. 7, 8, 9,10,11,12,13, 14, /* 23dB */
  142986. 15,16,17,17,17,18,18, 19, /* 31dB */
  142987. 19,19,20,21,22,23,24, 25, /* 39dB */
  142988. }},
  142989. /* mode A short */
  142990. {{
  142991. 0, 1, 2, 3, 4, 5, 5, 5, /* 7dB */
  142992. 6, 6, 6, 5, 4, 4, 4, 4, /* 15dB */
  142993. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  142994. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  142995. 11,12,13,14,15,16,17, 18, /* 39dB */
  142996. }},
  142997. /* sub-mode Z long */
  142998. {{
  142999. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  143000. 8, 9,10,11,12,13,14, 15, /* 15dB */
  143001. 16,17,18,19,20,21,22, 23, /* 23dB */
  143002. 24,25,26,27,28,29,30, 31, /* 31dB */
  143003. 32,33,34,35,36,37,38, 39, /* 39dB */
  143004. }},
  143005. /* mode_Z nominal long */
  143006. {{
  143007. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  143008. 8, 9,10,11,12,12,13, 13, /* 15dB */
  143009. 13,14,14,14,15,15,15, 15, /* 23dB */
  143010. 16,16,17,17,17,18,18, 19, /* 31dB */
  143011. 19,19,20,21,22,23,24, 25, /* 39dB */
  143012. }},
  143013. /* mode A long */
  143014. {{
  143015. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  143016. 8, 8, 7, 6, 5, 4, 4, 4, /* 15dB */
  143017. 4, 4, 5, 5, 5, 6, 6, 6, /* 23dB */
  143018. 7, 7, 7, 8, 8, 8, 9, 10, /* 31dB */
  143019. 11,12,13,14,15,16,17, 18, /* 39dB */
  143020. }}
  143021. };
  143022. /* tonal masking curve level adjustments *************************/
  143023. static vp_adjblock _vp_tonemask_adj_longblock[12]={
  143024. /* 63 125 250 500 1 2 4 8 16 */
  143025. {{ -3, -8,-13,-15,-10,-10,-10,-10,-10,-10,-10, 0, 0, 0, 0, 0, 0}}, /* -1 */
  143026. /* {{-15,-15,-15,-15,-10, -8, -4, -2, 0, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  143027. {{ -4,-10,-14,-16,-15,-14,-13,-12,-12,-12,-11, -1, -1, -1, -1, -1, 0}}, /* 0 */
  143028. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  143029. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, -1, -1, 0}}, /* 1 */
  143030. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  143031. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -6, -3, -1, -1, -1, 0}}, /* 2 */
  143032. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  143033. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, -1, -1, 0}}, /* 3 */
  143034. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, *//* 4 */
  143035. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  143036. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  143037. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  143038. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  143039. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  143040. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  143041. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  143042. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  143043. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  143044. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  143045. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  143046. /* {{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  143047. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  143048. };
  143049. static vp_adjblock _vp_tonemask_adj_otherblock[12]={
  143050. /* 63 125 250 500 1 2 4 8 16 */
  143051. {{ -3, -8,-13,-15,-10,-10, -9, -9, -9, -9, -9, 1, 1, 1, 1, 1, 1}}, /* -1 */
  143052. /* {{-20,-20,-20,-20,-14,-12,-10, -8, -4, 0, 0, 10, 0, 0, 0, 0, 0}}, 0 */
  143053. {{ -4,-10,-14,-16,-14,-13,-12,-12,-11,-11,-10, 0, 0, 0, 0, 0, 0}}, /* 0 */
  143054. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 5, 0, 0, 0, 0, 0}}, 1 */
  143055. {{ -6,-12,-14,-16,-15,-15,-14,-13,-13,-12,-12, -2, -2, -1, 0, 0, 0}}, /* 1 */
  143056. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 2 */
  143057. {{-12,-13,-14,-16,-16,-16,-15,-14,-13,-12,-12, -5, -2, -1, 0, 0, 0}}, /* 2 */
  143058. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 3 */
  143059. {{-15,-15,-15,-16,-16,-16,-16,-14,-13,-13,-13,-10, -4, -2, 0, 0, 0}}, /* 3 */
  143060. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 4 */
  143061. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 4 */
  143062. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 5 */
  143063. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-13,-11, -7 -3, -1, -1 , 0}}, /* 5 */
  143064. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 6 */
  143065. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -8, -4, -2, -2, 0}}, /* 6 */
  143066. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 7 */
  143067. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 7 */
  143068. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 8 */
  143069. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 8 */
  143070. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 9 */
  143071. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 9 */
  143072. /* {{-20,-20,-20,-20,-20,-18,-16,-14,-10, 0, 0, 0, 0, 0, 0, 0, 0}}, 10 */
  143073. {{-16,-16,-16,-16,-16,-16,-16,-15,-14,-14,-14,-12, -9, -4, -2, -2, 0}}, /* 10 */
  143074. };
  143075. /* noise bias (transition block) */
  143076. static noise3 _psy_noisebias_trans[12]={
  143077. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  143078. /* -1 */
  143079. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  143080. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  143081. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  143082. /* 0
  143083. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  143084. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 4, 10},
  143085. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  143086. {{{-15,-15,-15,-15,-15,-12, -6, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  143087. {-30,-30,-30,-30,-26,-22,-20,-14, -8, -4, 0, 0, 0, 0, 2, 3, 6},
  143088. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -4, -4, -4, -2}}},
  143089. /* 1
  143090. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  143091. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  143092. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  143093. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  143094. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  143095. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  143096. /* 2
  143097. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  143098. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  143099. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}}, */
  143100. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  143101. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  143102. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -7, -4}}},
  143103. /* 3
  143104. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  143105. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  143106. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  143107. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  143108. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  143109. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  143110. /* 4
  143111. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  143112. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  143113. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  143114. {{{-20,-20,-20,-20,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  143115. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  143116. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  143117. /* 5
  143118. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  143119. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  143120. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}}, */
  143121. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  143122. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  143123. {-34,-34,-34,-34,-30,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},
  143124. /* 6
  143125. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  143126. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  143127. {-34,-34,-34,-34,-30,-26,-24,-18,-17,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  143128. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  143129. {-32,-32,-32,-32,-28,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  143130. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},
  143131. /* 7
  143132. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  143133. {-32,-32,-32,-32,-28,-24,-24,-18,-14,-12,-10, -8, -8, -8, -6, -4, 0},
  143134. {-34,-34,-34,-34,-30,-26,-26,-24,-22,-19,-19,-19,-19,-18,-17,-16,-12}}},*/
  143135. {{{-24,-24,-24,-24,-20,-18,-14, -8, -1, 1, 1, 1, 2, 3, 3, 4, 7},
  143136. {-32,-32,-32,-32,-28,-24,-24,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  143137. {-34,-34,-34,-34,-30,-26,-26,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  143138. /* 8
  143139. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  143140. {-36,-36,-36,-36,-30,-30,-30,-24,-18,-14,-12,-10,-10,-10, -8, -6, -2},
  143141. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  143142. {{{-24,-24,-24,-24,-22,-20,-15,-10, -8, -2, 0, 0, 0, 1, 2, 3, 7},
  143143. {-36,-36,-36,-36,-30,-30,-30,-24,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  143144. {-36,-36,-36,-36,-34,-30,-28,-26,-24,-30,-30,-30,-30,-30,-30,-24,-20}}},
  143145. /* 9
  143146. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  143147. {-36,-36,-36,-36,-34,-32,-32,-28,-20,-16,-16,-16,-16,-14,-12,-10, -7},
  143148. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  143149. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  143150. {-38,-38,-38,-38,-36,-34,-34,-30,-24,-20,-20,-20,-20,-18,-16,-12,-10},
  143151. {-40,-40,-40,-40,-40,-40,-40,-38,-35,-35,-35,-35,-35,-35,-35,-35,-30}}},
  143152. /* 10 */
  143153. {{{-30,-30,-30,-30,-30,-30,-30,-28,-20,-14,-14,-14,-14,-14,-14,-12,-10},
  143154. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-20},
  143155. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  143156. };
  143157. /* noise bias (long block) */
  143158. static noise3 _psy_noisebias_long[12]={
  143159. /*63 125 250 500 1k 2k 4k 8k 16k*/
  143160. /* -1 */
  143161. {{{-10,-10,-10,-10,-10, -4, 0, 0, 0, 6, 6, 6, 6, 10, 10, 12, 20},
  143162. {-20,-20,-20,-20,-20,-20,-10, -2, 0, 0, 0, 0, 0, 2, 4, 6, 15},
  143163. {-20,-20,-20,-20,-20,-20,-20,-10, -6, -6, -6, -6, -6, -4, -4, -4, -2}}},
  143164. /* 0 */
  143165. /* {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  143166. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 4, 10},
  143167. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},*/
  143168. {{{-10,-10,-10,-10,-10,-10, -8, 2, 2, 2, 4, 4, 5, 5, 5, 8, 10},
  143169. {-20,-20,-20,-20,-20,-20,-20,-14, -6, 0, 0, 0, 0, 0, 2, 3, 6},
  143170. {-20,-20,-20,-20,-20,-20,-20,-14, -8, -6, -6, -6, -6, -4, -4, -4, -2}}},
  143171. /* 1 */
  143172. /* {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  143173. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 8},
  143174. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},*/
  143175. {{{-10,-10,-10,-10,-10,-10, -8, -4, 0, 2, 4, 4, 5, 5, 5, 8, 10},
  143176. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 1, 4},
  143177. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -8, -8, -8, -8, -6, -6, -6, -4}}},
  143178. /* 2 */
  143179. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  143180. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -2, -2, -2, -2, 0, 2, 6},
  143181. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  143182. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 5, 6, 10},
  143183. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -2, -1, 0, 3},
  143184. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},
  143185. /* 3 */
  143186. /* {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  143187. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 6},
  143188. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  143189. {{{-10,-10,-10,-10,-10,-10,-10, -8, 0, 2, 2, 2, 4, 4, 4, 5, 8},
  143190. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, 0, 2},
  143191. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -5}}},
  143192. /* 4 */
  143193. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  143194. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -1, 1, 5},
  143195. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -4}}},*/
  143196. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  143197. {-20,-20,-20,-20,-20,-20,-20,-14,-10, -4, -3, -3, -3, -3, -2, -1, 1},
  143198. {-20,-20,-20,-20,-20,-20,-20,-14,-10,-10,-10,-10,-10, -8, -8, -8, -7}}},
  143199. /* 5 */
  143200. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  143201. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -2, -1, 2},
  143202. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -5}}},*/
  143203. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  143204. {-22,-22,-22,-22,-22,-22,-22,-16,-12, -6, -4, -4, -4, -4, -3, -1, 0},
  143205. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-12,-12,-12,-12,-10,-10, -9, -8}}},
  143206. /* 6 */
  143207. /* {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  143208. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -4, -2, 1},
  143209. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12, -8}}},*/
  143210. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  143211. {-24,-24,-24,-24,-24,-24,-24,-18,-14, -8, -6, -6, -6, -6, -5, -2, 0},
  143212. {-26,-26,-26,-26,-26,-26,-26,-18,-16,-15,-15,-15,-15,-13,-13,-12,-10}}},
  143213. /* 7 */
  143214. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 1, 1, 1, 2, 3, 3, 4, 7},
  143215. {-24,-24,-24,-24,-24,-24,-24,-18,-14,-10, -8, -8, -8, -8, -6, -4, 0},
  143216. {-26,-26,-26,-26,-26,-26,-26,-22,-20,-19,-19,-19,-19,-18,-17,-16,-12}}},
  143217. /* 8 */
  143218. {{{-15,-15,-15,-15,-15,-15,-15,-10, -4, 0, 0, 0, 0, 1, 2, 3, 7},
  143219. {-26,-26,-26,-26,-26,-26,-26,-20,-16,-12,-10,-10,-10,-10, -8, -6, -2},
  143220. {-28,-28,-28,-28,-28,-28,-28,-26,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},
  143221. /* 9 */
  143222. {{{-22,-22,-22,-22,-22,-22,-22,-18,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  143223. {-26,-26,-26,-26,-26,-26,-26,-22,-18,-16,-16,-16,-16,-14,-12,-10, -7},
  143224. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  143225. /* 10 */
  143226. {{{-24,-24,-24,-24,-24,-24,-24,-24,-24,-18,-14,-14,-14,-14,-14,-12,-10},
  143227. {-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-30,-20},
  143228. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  143229. };
  143230. /* noise bias (impulse block) */
  143231. static noise3 _psy_noisebias_impulse[12]={
  143232. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  143233. /* -1 */
  143234. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  143235. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  143236. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  143237. /* 0 */
  143238. /* {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  143239. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 4, 10},
  143240. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},*/
  143241. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 4, 8, 8, 8, 10, 12, 14, 20},
  143242. {-30,-30,-30,-30,-26,-22,-20,-14, -6, -2, 0, 0, 0, 0, 2, 3, 6},
  143243. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  143244. /* 1 */
  143245. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  143246. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -4, -4, -2, -2, -2, -2, 2},
  143247. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8,-10,-10, -8, -8, -8, -6, -4}}},
  143248. /* 2 */
  143249. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  143250. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  143251. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  143252. /* 3 */
  143253. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  143254. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  143255. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  143256. /* 4 */
  143257. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  143258. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -4, -4, -4, -2, 0},
  143259. {-30,-30,-30,-30,-26,-22,-20,-14,-10,-10,-10,-10,-10,-10,-10, -8, -4}}},
  143260. /* 5 */
  143261. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  143262. {-32,-32,-32,-32,-28,-24,-22,-16,-10, -6, -8, -8, -6, -6, -6, -4, -2},
  143263. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-12,-12,-12,-12,-12,-10, -9, -5}}},
  143264. /* 6
  143265. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  143266. {-34,-34,-34,-34,-30,-30,-24,-20,-12,-12,-14,-14,-10, -9, -8, -6, -4},
  143267. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-15,-15,-15,-15,-15,-13,-12, -8}}},*/
  143268. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 4, 6, 11},
  143269. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-16,-16,-16,-16,-16,-14,-14,-12},
  143270. {-36,-36,-36,-36,-36,-34,-28,-24,-20,-20,-20,-20,-20,-20,-20,-18,-16}}},
  143271. /* 7 */
  143272. /* {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  143273. {-34,-34,-34,-34,-30,-30,-24,-20,-14,-14,-16,-16,-14,-12,-10,-10,-10},
  143274. {-34,-34,-34,-34,-32,-32,-30,-24,-20,-19,-19,-19,-19,-19,-17,-16,-12}}},*/
  143275. {{{-22,-22,-22,-22,-22,-20,-14,-10, -6, 0, 0, 0, 0, 4, 4, 6, 11},
  143276. {-34,-34,-34,-34,-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-24,-22},
  143277. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  143278. /* 8 */
  143279. /* {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  143280. {-34,-34,-34,-34,-30,-30,-30,-24,-20,-20,-20,-20,-20,-18,-16,-16,-14},
  143281. {-36,-36,-36,-36,-36,-34,-28,-24,-24,-24,-24,-24,-24,-24,-24,-20,-16}}},*/
  143282. {{{-24,-24,-24,-24,-24,-22,-14,-10, -6, -1, -1, -1, -1, 3, 3, 5, 10},
  143283. {-34,-34,-34,-34,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-24},
  143284. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-30,-24}}},
  143285. /* 9 */
  143286. /* {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  143287. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-22,-20,-20,-18},
  143288. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},*/
  143289. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -4, -4, -4, -4, -4, -2, 2},
  143290. {-36,-36,-36,-36,-34,-32,-32,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26},
  143291. {-40,-40,-40,-40,-40,-40,-40,-32,-30,-30,-30,-30,-30,-30,-30,-24,-20}}},
  143292. /* 10 */
  143293. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-16,-16,-16,-16,-16,-14,-12},
  143294. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-30,-30,-30,-30,-30,-30,-26},
  143295. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  143296. };
  143297. /* noise bias (padding block) */
  143298. static noise3 _psy_noisebias_padding[12]={
  143299. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  143300. /* -1 */
  143301. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  143302. {-30,-30,-30,-30,-26,-20,-16, -8, -6, -6, -2, 2, 2, 3, 6, 6, 15},
  143303. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -4, -2}}},
  143304. /* 0 */
  143305. {{{-10,-10,-10,-10,-10, -4, 0, 0, 4, 8, 8, 8, 8, 10, 12, 14, 20},
  143306. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -2, 2, 3, 6, 6, 8, 10},
  143307. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, -4, -4, -4, -4, -2, 0, 2}}},
  143308. /* 1 */
  143309. {{{-12,-12,-12,-12,-12, -8, -6, -4, 0, 4, 4, 4, 4, 10, 12, 14, 20},
  143310. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  143311. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -6, -6, -6, -6, -4, -2, 0}}},
  143312. /* 2 */
  143313. /* {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  143314. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -4, 0, 0, 0, 2, 2, 4, 8},
  143315. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},*/
  143316. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 8, 10, 10, 16},
  143317. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  143318. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  143319. /* 3 */
  143320. {{{-14,-14,-14,-14,-14,-10, -8, -6, -2, 2, 2, 2, 2, 6, 8, 8, 14},
  143321. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, 0, 0, 2, 6},
  143322. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  143323. /* 4 */
  143324. {{{-16,-16,-16,-16,-16,-12,-10, -6, -2, 0, 0, 0, 0, 4, 6, 6, 12},
  143325. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -6, -1, -1, -1, -1, 0, 2, 6},
  143326. {-30,-30,-30,-30,-26,-22,-20,-14,-10, -8, -8, -8, -8, -8, -6, -4, -2}}},
  143327. /* 5 */
  143328. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  143329. {-32,-32,-32,-32,-28,-24,-22,-16,-12, -6, -3, -3, -3, -3, -2, 0, 4},
  143330. {-34,-34,-34,-34,-30,-26,-24,-18,-14,-10,-10,-10,-10,-10, -8, -5, -3}}},
  143331. /* 6 */
  143332. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  143333. {-34,-34,-34,-34,-30,-30,-24,-20,-14, -8, -4, -4, -4, -4, -3, -1, 4},
  143334. {-34,-34,-34,-34,-34,-30,-26,-20,-16,-13,-13,-13,-13,-13,-11, -8, -6}}},
  143335. /* 7 */
  143336. {{{-20,-20,-20,-20,-20,-18,-14,-10, -4, 0, 0, 0, 0, 4, 6, 6, 12},
  143337. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-10, -8, -6, -6, -6, -5, -3, 1},
  143338. {-34,-34,-34,-34,-32,-32,-28,-22,-18,-16,-16,-16,-16,-16,-14,-12,-10}}},
  143339. /* 8 */
  143340. {{{-22,-22,-22,-22,-22,-20,-14,-10, -4, 0, 0, 0, 0, 3, 5, 5, 11},
  143341. {-34,-34,-34,-34,-30,-30,-30,-24,-16,-12,-10, -8, -8, -8, -7, -5, -2},
  143342. {-36,-36,-36,-36,-36,-34,-28,-22,-20,-20,-20,-20,-20,-20,-20,-16,-14}}},
  143343. /* 9 */
  143344. {{{-28,-28,-28,-28,-28,-28,-28,-20,-14, -8, -2, -2, -2, -2, 0, 2, 6},
  143345. {-36,-36,-36,-36,-34,-32,-32,-24,-16,-12,-12,-12,-12,-12,-10, -8, -5},
  143346. {-40,-40,-40,-40,-40,-40,-40,-32,-26,-24,-24,-24,-24,-24,-24,-20,-18}}},
  143347. /* 10 */
  143348. {{{-30,-30,-30,-30,-30,-26,-24,-24,-24,-20,-12,-12,-12,-12,-12,-10, -8},
  143349. {-40,-40,-40,-40,-40,-40,-40,-40,-35,-30,-25,-25,-25,-25,-25,-25,-15},
  143350. {-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40,-40}}},
  143351. };
  143352. static noiseguard _psy_noiseguards_44[4]={
  143353. {3,3,15},
  143354. {3,3,15},
  143355. {10,10,100},
  143356. {10,10,100},
  143357. };
  143358. static int _psy_tone_suppress[12]={
  143359. -20,-20,-20,-20,-20,-24,-30,-40,-40,-45,-45,-45,
  143360. };
  143361. static int _psy_tone_0dB[12]={
  143362. 90,90,95,95,95,95,105,105,105,105,105,105,
  143363. };
  143364. static int _psy_noise_suppress[12]={
  143365. -20,-20,-24,-24,-24,-24,-30,-40,-40,-45,-45,-45,
  143366. };
  143367. static vorbis_info_psy _psy_info_template={
  143368. /* blockflag */
  143369. -1,
  143370. /* ath_adjatt, ath_maxatt */
  143371. -140.,-140.,
  143372. /* tonemask att boost/decay,suppr,curves */
  143373. {0.f,0.f,0.f}, 0.,0., -40.f, {0.},
  143374. /*noisemaskp,supp, low/high window, low/hi guard, minimum */
  143375. 1, -0.f, .5f, .5f, 0,0,0,
  143376. /* noiseoffset*3, noisecompand, max_curve_dB */
  143377. {{-1},{-1},{-1}},{-1},105.f,
  143378. /* noise normalization - channel_p, point_p, start, partition, thresh. */
  143379. 0,0,-1,-1,0.,
  143380. };
  143381. /* ath ****************/
  143382. static int _psy_ath_floater[12]={
  143383. -100,-100,-100,-100,-100,-100,-105,-105,-105,-105,-110,-120,
  143384. };
  143385. static int _psy_ath_abs[12]={
  143386. -130,-130,-130,-130,-140,-140,-140,-140,-140,-140,-140,-150,
  143387. };
  143388. /* stereo setup. These don't map directly to quality level, there's
  143389. an additional indirection as several of the below may be used in a
  143390. single bitmanaged stream
  143391. ****************/
  143392. /* various stereo possibilities */
  143393. /* stereo mode by base quality level */
  143394. static adj_stereo _psy_stereo_modes_44[12]={
  143395. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 -1 */
  143396. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  143397. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  143398. { 1, 2, 3, 4, 4, 4, 4, 4, 4, 5, 6, 7, 8, 8, 8},
  143399. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  143400. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 0 */
  143401. /*{{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 2, 1, 0, 0, 0, 0},
  143402. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 5, 4, 3},
  143403. { 1, 2, 3, 4, 5, 5, 6, 6, 6, 6, 6, 7, 8, 8, 8},
  143404. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  143405. {{ 4, 4, 4, 4, 4, 4, 4, 3, 2, 1, 0, 0, 0, 0, 0},
  143406. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  143407. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  143408. { 12,12.5, 13,13.5, 14,14.5, 15, 99, 99, 99, 99, 99, 99, 99, 99}},
  143409. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 1 */
  143410. {{ 3, 3, 3, 3, 3, 3, 3, 3, 2, 1, 0, 0, 0, 0, 0},
  143411. { 8, 8, 8, 8, 6, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3},
  143412. { 1, 2, 3, 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  143413. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143414. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 2 */
  143415. /* {{ 3, 3, 3, 3, 3, 3, 2, 2, 2, 1, 0, 0, 0, 0, 0},
  143416. { 8, 8, 8, 6, 5, 5, 5, 5, 5, 5, 5, 4, 3, 2, 1},
  143417. { 3, 4, 4, 4, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  143418. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  143419. {{ 3, 3, 3, 3, 3, 3, 3, 2, 1, 1, 0, 0, 0, 0, 0},
  143420. { 8, 8, 6, 6, 5, 5, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  143421. { 3, 4, 4, 5, 5, 6, 6, 6, 6, 6, 6, 8, 8, 8, 8},
  143422. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143423. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 3 */
  143424. {{ 2, 2, 2, 2, 2, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0},
  143425. { 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 2, 1},
  143426. { 4, 4, 5, 6, 6, 6, 6, 6, 8, 8, 10, 10, 10, 10, 10},
  143427. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143428. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 4 */
  143429. {{ 2, 2, 2, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143430. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 2, 1, 0},
  143431. { 6, 6, 6, 8, 8, 8, 8, 8, 8, 8, 10, 10, 10, 10, 10},
  143432. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143433. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 5 */
  143434. /* {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143435. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  143436. { 6, 6, 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  143437. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  143438. {{ 2, 2, 2, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143439. { 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 0, 0, 0, 0},
  143440. { 6, 7, 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12},
  143441. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143442. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 6 */
  143443. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143444. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143445. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  143446. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}}, */
  143447. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143448. { 3, 3, 3, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143449. { 8, 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  143450. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143451. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 7 */
  143452. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143453. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143454. { 8, 8, 8, 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  143455. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  143456. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143457. { 3, 3, 3, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143458. { 8, 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  143459. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143460. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 8 */
  143461. /* {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143462. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143463. { 8, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10},
  143464. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},*/
  143465. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143466. { 2, 2, 2, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143467. { 8, 10, 10, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12},
  143468. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143469. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 9 */
  143470. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143471. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143472. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  143473. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143474. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 10 */
  143475. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143476. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  143477. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  143478. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  143479. };
  143480. /* tone master attenuation by base quality mode and bitrate tweak */
  143481. static att3 _psy_tone_masteratt_44[12]={
  143482. {{ 35, 21, 9}, 0, 0}, /* -1 */
  143483. {{ 30, 20, 8}, -2, 1.25}, /* 0 */
  143484. /* {{ 25, 14, 4}, 0, 0}, *//* 1 */
  143485. {{ 25, 12, 2}, 0, 0}, /* 1 */
  143486. /* {{ 20, 10, -2}, 0, 0}, *//* 2 */
  143487. {{ 20, 9, -3}, 0, 0}, /* 2 */
  143488. {{ 20, 9, -4}, 0, 0}, /* 3 */
  143489. {{ 20, 9, -4}, 0, 0}, /* 4 */
  143490. {{ 20, 6, -6}, 0, 0}, /* 5 */
  143491. {{ 20, 3, -10}, 0, 0}, /* 6 */
  143492. {{ 18, 1, -14}, 0, 0}, /* 7 */
  143493. {{ 18, 0, -16}, 0, 0}, /* 8 */
  143494. {{ 18, -2, -16}, 0, 0}, /* 9 */
  143495. {{ 12, -2, -20}, 0, 0}, /* 10 */
  143496. };
  143497. /* lowpass by mode **************/
  143498. static double _psy_lowpass_44[12]={
  143499. /* 15.1,15.8,16.5,17.9,20.5,48.,999.,999.,999.,999.,999. */
  143500. 13.9,15.1,15.8,16.5,17.2,18.9,20.1,48.,999.,999.,999.,999.
  143501. };
  143502. /* noise normalization **********/
  143503. static int _noise_start_short_44[11]={
  143504. /* 16,16,16,16,32,32,9999,9999,9999,9999 */
  143505. 32,16,16,16,32,9999,9999,9999,9999,9999,9999
  143506. };
  143507. static int _noise_start_long_44[11]={
  143508. /* 128,128,128,256,512,512,9999,9999,9999,9999 */
  143509. 256,128,128,256,512,9999,9999,9999,9999,9999,9999
  143510. };
  143511. static int _noise_part_short_44[11]={
  143512. 8,8,8,8,8,8,8,8,8,8,8
  143513. };
  143514. static int _noise_part_long_44[11]={
  143515. 32,32,32,32,32,32,32,32,32,32,32
  143516. };
  143517. static double _noise_thresh_44[11]={
  143518. /* .2,.2,.3,.4,.5,.5,9999.,9999.,9999.,9999., */
  143519. .2,.2,.2,.4,.6,9999.,9999.,9999.,9999.,9999.,9999.,
  143520. };
  143521. static double _noise_thresh_5only[2]={
  143522. .5,.5,
  143523. };
  143524. /********* End of inlined file: psych_44.h *********/
  143525. static double rate_mapping_44_stereo[12]={
  143526. 22500.,32000.,40000.,48000.,56000.,64000.,
  143527. 80000.,96000.,112000.,128000.,160000.,250001.
  143528. };
  143529. static double quality_mapping_44[12]={
  143530. -.1,.0,.1,.2,.3,.4,.5,.6,.7,.8,.9,1.0
  143531. };
  143532. static int blocksize_short_44[11]={
  143533. 512,256,256,256,256,256,256,256,256,256,256
  143534. };
  143535. static int blocksize_long_44[11]={
  143536. 4096,2048,2048,2048,2048,2048,2048,2048,2048,2048,2048
  143537. };
  143538. static double _psy_compand_short_mapping[12]={
  143539. 0.5, 1., 1., 1.3, 1.6, 2., 2., 2., 2., 2., 2., 2.
  143540. };
  143541. static double _psy_compand_long_mapping[12]={
  143542. 3.5, 4., 4., 4.3, 4.6, 5., 5., 5., 5., 5., 5., 5.
  143543. };
  143544. static double _global_mapping_44[12]={
  143545. /* 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.5, 4., 4. */
  143546. 0., 1., 1., 1.5, 2., 2., 2.5, 2.7, 3.0, 3.7, 4., 4.
  143547. };
  143548. static int _floor_short_mapping_44[11]={
  143549. 1,0,0,2,2,4,5,5,5,5,5
  143550. };
  143551. static int _floor_long_mapping_44[11]={
  143552. 8,7,7,7,7,7,7,7,7,7,7
  143553. };
  143554. ve_setup_data_template ve_setup_44_stereo={
  143555. 11,
  143556. rate_mapping_44_stereo,
  143557. quality_mapping_44,
  143558. 2,
  143559. 40000,
  143560. 50000,
  143561. blocksize_short_44,
  143562. blocksize_long_44,
  143563. _psy_tone_masteratt_44,
  143564. _psy_tone_0dB,
  143565. _psy_tone_suppress,
  143566. _vp_tonemask_adj_otherblock,
  143567. _vp_tonemask_adj_longblock,
  143568. _vp_tonemask_adj_otherblock,
  143569. _psy_noiseguards_44,
  143570. _psy_noisebias_impulse,
  143571. _psy_noisebias_padding,
  143572. _psy_noisebias_trans,
  143573. _psy_noisebias_long,
  143574. _psy_noise_suppress,
  143575. _psy_compand_44,
  143576. _psy_compand_short_mapping,
  143577. _psy_compand_long_mapping,
  143578. {_noise_start_short_44,_noise_start_long_44},
  143579. {_noise_part_short_44,_noise_part_long_44},
  143580. _noise_thresh_44,
  143581. _psy_ath_floater,
  143582. _psy_ath_abs,
  143583. _psy_lowpass_44,
  143584. _psy_global_44,
  143585. _global_mapping_44,
  143586. _psy_stereo_modes_44,
  143587. _floor_books,
  143588. _floor,
  143589. _floor_short_mapping_44,
  143590. _floor_long_mapping_44,
  143591. _mapres_template_44_stereo
  143592. };
  143593. /********* End of inlined file: setup_44.h *********/
  143594. /********* Start of inlined file: setup_44u.h *********/
  143595. /********* Start of inlined file: residue_44u.h *********/
  143596. /********* Start of inlined file: res_books_uncoupled.h *********/
  143597. static long _vq_quantlist__16u0__p1_0[] = {
  143598. 1,
  143599. 0,
  143600. 2,
  143601. };
  143602. static long _vq_lengthlist__16u0__p1_0[] = {
  143603. 1, 4, 4, 5, 7, 7, 5, 7, 8, 5, 8, 8, 8,10,10, 8,
  143604. 10,11, 5, 8, 8, 8,10,10, 8,10,10, 4, 9, 9, 9,12,
  143605. 11, 8,11,11, 8,12,11,10,12,14,10,13,13, 7,11,11,
  143606. 10,14,12,11,14,14, 4, 9, 9, 8,11,11, 9,11,12, 7,
  143607. 11,11,10,13,14,10,12,14, 8,11,12,10,14,14,10,13,
  143608. 12,
  143609. };
  143610. static float _vq_quantthresh__16u0__p1_0[] = {
  143611. -0.5, 0.5,
  143612. };
  143613. static long _vq_quantmap__16u0__p1_0[] = {
  143614. 1, 0, 2,
  143615. };
  143616. static encode_aux_threshmatch _vq_auxt__16u0__p1_0 = {
  143617. _vq_quantthresh__16u0__p1_0,
  143618. _vq_quantmap__16u0__p1_0,
  143619. 3,
  143620. 3
  143621. };
  143622. static static_codebook _16u0__p1_0 = {
  143623. 4, 81,
  143624. _vq_lengthlist__16u0__p1_0,
  143625. 1, -535822336, 1611661312, 2, 0,
  143626. _vq_quantlist__16u0__p1_0,
  143627. NULL,
  143628. &_vq_auxt__16u0__p1_0,
  143629. NULL,
  143630. 0
  143631. };
  143632. static long _vq_quantlist__16u0__p2_0[] = {
  143633. 1,
  143634. 0,
  143635. 2,
  143636. };
  143637. static long _vq_lengthlist__16u0__p2_0[] = {
  143638. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 9, 7,
  143639. 8, 9, 5, 7, 7, 7, 9, 8, 7, 9, 7, 4, 7, 7, 7, 9,
  143640. 9, 7, 8, 8, 6, 9, 8, 7, 8,11, 9,11,10, 6, 8, 9,
  143641. 8,11, 8, 9,10,11, 4, 7, 7, 7, 8, 8, 7, 9, 9, 6,
  143642. 9, 8, 9,11,10, 8, 8,11, 6, 8, 9, 9,10,11, 8,11,
  143643. 8,
  143644. };
  143645. static float _vq_quantthresh__16u0__p2_0[] = {
  143646. -0.5, 0.5,
  143647. };
  143648. static long _vq_quantmap__16u0__p2_0[] = {
  143649. 1, 0, 2,
  143650. };
  143651. static encode_aux_threshmatch _vq_auxt__16u0__p2_0 = {
  143652. _vq_quantthresh__16u0__p2_0,
  143653. _vq_quantmap__16u0__p2_0,
  143654. 3,
  143655. 3
  143656. };
  143657. static static_codebook _16u0__p2_0 = {
  143658. 4, 81,
  143659. _vq_lengthlist__16u0__p2_0,
  143660. 1, -535822336, 1611661312, 2, 0,
  143661. _vq_quantlist__16u0__p2_0,
  143662. NULL,
  143663. &_vq_auxt__16u0__p2_0,
  143664. NULL,
  143665. 0
  143666. };
  143667. static long _vq_quantlist__16u0__p3_0[] = {
  143668. 2,
  143669. 1,
  143670. 3,
  143671. 0,
  143672. 4,
  143673. };
  143674. static long _vq_lengthlist__16u0__p3_0[] = {
  143675. 1, 5, 5, 7, 7, 6, 7, 7, 8, 8, 6, 7, 8, 8, 8, 8,
  143676. 9, 9,11,11, 8, 9, 9,11,11, 6, 9, 8,10,10, 8,10,
  143677. 10,11,11, 8,10,10,11,11,10,11,10,13,12, 9,11,10,
  143678. 13,13, 6, 8, 9,10,10, 8,10,10,11,11, 8,10,10,11,
  143679. 11, 9,10,11,13,12,10,10,11,12,12, 8,11,11,14,13,
  143680. 10,12,11,15,13, 9,12,11,15,14,12,14,13,16,14,12,
  143681. 13,13,17,14, 8,11,11,13,14, 9,11,12,14,15,10,11,
  143682. 12,13,15,11,13,13,14,16,12,13,14,14,16, 5, 9, 9,
  143683. 11,11, 9,11,11,12,12, 8,11,11,12,12,11,12,12,15,
  143684. 14,10,12,12,15,15, 8,11,11,13,12,10,12,12,13,13,
  143685. 10,12,12,14,13,12,12,13,14,15,11,13,13,17,16, 7,
  143686. 11,11,13,13,10,12,12,14,13,10,12,12,13,14,12,13,
  143687. 12,15,14,11,13,13,15,14, 9,12,12,16,15,11,13,13,
  143688. 17,16,10,13,13,16,16,13,14,15,15,16,13,15,14,19,
  143689. 17, 9,12,12,14,16,11,13,13,15,16,10,13,13,17,16,
  143690. 13,14,13,17,15,12,15,15,16,17, 5, 9, 9,11,11, 8,
  143691. 11,11,13,12, 9,11,11,12,12,10,12,12,14,15,11,12,
  143692. 12,14,14, 7,11,10,13,12,10,12,12,14,13,10,11,12,
  143693. 13,13,11,13,13,15,16,12,12,13,15,15, 7,11,11,13,
  143694. 13,10,13,13,14,14,10,12,12,13,13,11,13,13,16,15,
  143695. 12,13,13,15,14, 9,12,12,15,15,10,13,13,17,16,11,
  143696. 12,13,15,15,12,15,14,18,18,13,14,14,16,17, 9,12,
  143697. 12,15,16,10,13,13,15,16,11,13,13,15,16,13,15,15,
  143698. 17,17,13,15,14,16,15, 7,11,11,15,16,10,13,12,16,
  143699. 17,10,12,13,15,17,15,16,16,18,17,13,15,15,17,18,
  143700. 8,12,12,16,16,11,13,14,17,18,11,13,13,18,16,15,
  143701. 17,16,17,19,14,15,15,17,16, 8,12,12,16,15,11,14,
  143702. 13,18,17,11,13,14,18,17,15,16,16,18,17,13,16,16,
  143703. 18,18,11,15,14,18,17,13,14,15,18, 0,12,15,15, 0,
  143704. 17,17,16,17,17,18,14,16,18,18, 0,11,14,14,17, 0,
  143705. 12,15,14,17,19,12,15,14,18, 0,15,18,16, 0,17,14,
  143706. 18,16,18, 0, 7,11,11,16,15,10,12,12,18,16,10,13,
  143707. 13,16,15,13,15,14,17,17,14,16,16,19,18, 8,12,12,
  143708. 16,16,11,13,13,18,16,11,13,14,17,16,14,15,15,19,
  143709. 18,15,16,16, 0,19, 8,12,12,16,17,11,13,13,17,17,
  143710. 11,14,13,17,17,13,15,15,17,19,15,17,17,19, 0,11,
  143711. 14,15,19,17,12,15,16,18,18,12,14,15,19,17,14,16,
  143712. 17, 0,18,16,16,19,17, 0,11,14,14,18,19,12,15,14,
  143713. 17,17,13,16,14,17,16,14,17,16,18,18,15,18,15, 0,
  143714. 18,
  143715. };
  143716. static float _vq_quantthresh__16u0__p3_0[] = {
  143717. -1.5, -0.5, 0.5, 1.5,
  143718. };
  143719. static long _vq_quantmap__16u0__p3_0[] = {
  143720. 3, 1, 0, 2, 4,
  143721. };
  143722. static encode_aux_threshmatch _vq_auxt__16u0__p3_0 = {
  143723. _vq_quantthresh__16u0__p3_0,
  143724. _vq_quantmap__16u0__p3_0,
  143725. 5,
  143726. 5
  143727. };
  143728. static static_codebook _16u0__p3_0 = {
  143729. 4, 625,
  143730. _vq_lengthlist__16u0__p3_0,
  143731. 1, -533725184, 1611661312, 3, 0,
  143732. _vq_quantlist__16u0__p3_0,
  143733. NULL,
  143734. &_vq_auxt__16u0__p3_0,
  143735. NULL,
  143736. 0
  143737. };
  143738. static long _vq_quantlist__16u0__p4_0[] = {
  143739. 2,
  143740. 1,
  143741. 3,
  143742. 0,
  143743. 4,
  143744. };
  143745. static long _vq_lengthlist__16u0__p4_0[] = {
  143746. 3, 5, 5, 8, 8, 6, 6, 6, 9, 9, 6, 6, 6, 9, 9, 9,
  143747. 10, 9,11,11, 9, 9, 9,11,11, 6, 7, 7,10,10, 7, 7,
  143748. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  143749. 11,12, 6, 7, 7,10,10, 7, 8, 7,10,10, 7, 8, 7,10,
  143750. 10,10,11,10,12,11,10,10,10,13,10, 9,10,10,12,12,
  143751. 10,11,10,14,12, 9,11,11,13,13,11,12,13,13,13,11,
  143752. 12,12,15,13, 9,10,10,12,13, 9,11,10,12,13,10,10,
  143753. 11,12,13,11,12,12,12,13,11,12,12,13,13, 5, 7, 7,
  143754. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  143755. 13,10,10,11,12,12, 6, 8, 8,11,10, 7, 8, 9,10,12,
  143756. 8, 9, 9,11,11,11,10,11,11,12,10,11,11,13,12, 7,
  143757. 8, 8,10,11, 8, 9, 8,11,10, 8, 9, 9,11,11,10,12,
  143758. 10,13,11,10,11,11,13,13,10,11,10,14,13,10,10,11,
  143759. 13,13,10,12,11,14,13,12,11,13,12,13,13,12,13,14,
  143760. 14,10,11,11,13,13,10,11,10,12,13,10,12,12,12,14,
  143761. 12,12,12,14,12,12,13,12,17,15, 5, 7, 7,10,10, 7,
  143762. 8, 8,10,10, 7, 8, 8,11,10,10,10,11,12,12,10,11,
  143763. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  143764. 10,11,11,11,11,12,12,10,10,11,12,13, 6, 8, 8,10,
  143765. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,12,12,13,13,
  143766. 11,11,10,13,11, 9,11,10,14,13,11,11,11,15,13,10,
  143767. 10,11,13,13,12,13,13,14,14,12,11,12,12,13,10,11,
  143768. 11,12,13,10,11,12,13,13,10,11,10,13,12,12,12,13,
  143769. 14, 0,12,13,11,13,11, 8,10,10,13,13,10,11,11,14,
  143770. 13,10,11,11,13,12,13,14,14,14,15,12,12,12,15,14,
  143771. 9,11,10,13,12,10,10,11,13,14,11,11,11,15,12,13,
  143772. 12,14,15,16,13,13,13,14,13, 9,11,11,12,12,10,12,
  143773. 11,13,13,10,11,11,13,14,13,13,13,15,15,13,13,14,
  143774. 17,15,11,12,12,14,14,10,11,12,13,15,12,13,13, 0,
  143775. 15,13,11,14,12,16,14,16,14, 0,15,11,12,12,14,16,
  143776. 11,13,12,16,15,12,13,13,14,15,12,14,12,15,13,15,
  143777. 14,14,16,16, 8,10,10,13,13,10,11,10,13,14,10,11,
  143778. 11,13,13,13,13,12,14,14,14,13,13,16,17, 9,10,10,
  143779. 12,14,10,12,11,14,13,10,11,12,13,14,12,12,12,15,
  143780. 15,13,13,13,14,14, 9,10,10,13,13,10,11,12,12,14,
  143781. 10,11,10,13,13,13,13,13,14,16,13,13,13,14,14,11,
  143782. 12,13,15,13,12,14,13,14,16,12,12,13,13,14,13,14,
  143783. 14,17,15,13,12,17,13,16,11,12,13,14,15,12,13,14,
  143784. 14,17,11,12,11,14,14,13,16,14,16, 0,14,15,11,15,
  143785. 11,
  143786. };
  143787. static float _vq_quantthresh__16u0__p4_0[] = {
  143788. -1.5, -0.5, 0.5, 1.5,
  143789. };
  143790. static long _vq_quantmap__16u0__p4_0[] = {
  143791. 3, 1, 0, 2, 4,
  143792. };
  143793. static encode_aux_threshmatch _vq_auxt__16u0__p4_0 = {
  143794. _vq_quantthresh__16u0__p4_0,
  143795. _vq_quantmap__16u0__p4_0,
  143796. 5,
  143797. 5
  143798. };
  143799. static static_codebook _16u0__p4_0 = {
  143800. 4, 625,
  143801. _vq_lengthlist__16u0__p4_0,
  143802. 1, -533725184, 1611661312, 3, 0,
  143803. _vq_quantlist__16u0__p4_0,
  143804. NULL,
  143805. &_vq_auxt__16u0__p4_0,
  143806. NULL,
  143807. 0
  143808. };
  143809. static long _vq_quantlist__16u0__p5_0[] = {
  143810. 4,
  143811. 3,
  143812. 5,
  143813. 2,
  143814. 6,
  143815. 1,
  143816. 7,
  143817. 0,
  143818. 8,
  143819. };
  143820. static long _vq_lengthlist__16u0__p5_0[] = {
  143821. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  143822. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  143823. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 7, 8, 8,
  143824. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  143825. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,10,11,11,12,
  143826. 12,
  143827. };
  143828. static float _vq_quantthresh__16u0__p5_0[] = {
  143829. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  143830. };
  143831. static long _vq_quantmap__16u0__p5_0[] = {
  143832. 7, 5, 3, 1, 0, 2, 4, 6,
  143833. 8,
  143834. };
  143835. static encode_aux_threshmatch _vq_auxt__16u0__p5_0 = {
  143836. _vq_quantthresh__16u0__p5_0,
  143837. _vq_quantmap__16u0__p5_0,
  143838. 9,
  143839. 9
  143840. };
  143841. static static_codebook _16u0__p5_0 = {
  143842. 2, 81,
  143843. _vq_lengthlist__16u0__p5_0,
  143844. 1, -531628032, 1611661312, 4, 0,
  143845. _vq_quantlist__16u0__p5_0,
  143846. NULL,
  143847. &_vq_auxt__16u0__p5_0,
  143848. NULL,
  143849. 0
  143850. };
  143851. static long _vq_quantlist__16u0__p6_0[] = {
  143852. 6,
  143853. 5,
  143854. 7,
  143855. 4,
  143856. 8,
  143857. 3,
  143858. 9,
  143859. 2,
  143860. 10,
  143861. 1,
  143862. 11,
  143863. 0,
  143864. 12,
  143865. };
  143866. static long _vq_lengthlist__16u0__p6_0[] = {
  143867. 1, 4, 4, 7, 7,10,10,12,12,13,13,18,17, 3, 6, 6,
  143868. 9, 9,11,11,13,13,14,14,18,17, 3, 6, 6, 9, 9,11,
  143869. 11,13,13,14,14,17,18, 7, 9, 9,11,11,13,13,14,14,
  143870. 15,15, 0, 0, 7, 9, 9,11,11,13,13,14,14,15,16,19,
  143871. 18,10,11,11,13,13,14,14,16,15,17,18, 0, 0,10,11,
  143872. 11,13,13,14,14,15,15,16,18, 0, 0,11,13,13,14,14,
  143873. 15,15,17,17, 0,19, 0, 0,11,13,13,14,14,14,15,16,
  143874. 18, 0,19, 0, 0,13,14,14,15,15,18,17,18,18, 0,19,
  143875. 0, 0,13,14,14,15,16,16,16,18,18,19, 0, 0, 0,16,
  143876. 17,17, 0,17,19,19, 0,19, 0, 0, 0, 0,16,19,16,17,
  143877. 18, 0,19, 0, 0, 0, 0, 0, 0,
  143878. };
  143879. static float _vq_quantthresh__16u0__p6_0[] = {
  143880. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  143881. 12.5, 17.5, 22.5, 27.5,
  143882. };
  143883. static long _vq_quantmap__16u0__p6_0[] = {
  143884. 11, 9, 7, 5, 3, 1, 0, 2,
  143885. 4, 6, 8, 10, 12,
  143886. };
  143887. static encode_aux_threshmatch _vq_auxt__16u0__p6_0 = {
  143888. _vq_quantthresh__16u0__p6_0,
  143889. _vq_quantmap__16u0__p6_0,
  143890. 13,
  143891. 13
  143892. };
  143893. static static_codebook _16u0__p6_0 = {
  143894. 2, 169,
  143895. _vq_lengthlist__16u0__p6_0,
  143896. 1, -526516224, 1616117760, 4, 0,
  143897. _vq_quantlist__16u0__p6_0,
  143898. NULL,
  143899. &_vq_auxt__16u0__p6_0,
  143900. NULL,
  143901. 0
  143902. };
  143903. static long _vq_quantlist__16u0__p6_1[] = {
  143904. 2,
  143905. 1,
  143906. 3,
  143907. 0,
  143908. 4,
  143909. };
  143910. static long _vq_lengthlist__16u0__p6_1[] = {
  143911. 1, 4, 5, 6, 6, 4, 6, 6, 6, 6, 4, 6, 6, 6, 6, 6,
  143912. 6, 6, 7, 7, 6, 6, 6, 7, 7,
  143913. };
  143914. static float _vq_quantthresh__16u0__p6_1[] = {
  143915. -1.5, -0.5, 0.5, 1.5,
  143916. };
  143917. static long _vq_quantmap__16u0__p6_1[] = {
  143918. 3, 1, 0, 2, 4,
  143919. };
  143920. static encode_aux_threshmatch _vq_auxt__16u0__p6_1 = {
  143921. _vq_quantthresh__16u0__p6_1,
  143922. _vq_quantmap__16u0__p6_1,
  143923. 5,
  143924. 5
  143925. };
  143926. static static_codebook _16u0__p6_1 = {
  143927. 2, 25,
  143928. _vq_lengthlist__16u0__p6_1,
  143929. 1, -533725184, 1611661312, 3, 0,
  143930. _vq_quantlist__16u0__p6_1,
  143931. NULL,
  143932. &_vq_auxt__16u0__p6_1,
  143933. NULL,
  143934. 0
  143935. };
  143936. static long _vq_quantlist__16u0__p7_0[] = {
  143937. 1,
  143938. 0,
  143939. 2,
  143940. };
  143941. static long _vq_lengthlist__16u0__p7_0[] = {
  143942. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143943. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  143944. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143945. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143946. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  143947. 7,
  143948. };
  143949. static float _vq_quantthresh__16u0__p7_0[] = {
  143950. -157.5, 157.5,
  143951. };
  143952. static long _vq_quantmap__16u0__p7_0[] = {
  143953. 1, 0, 2,
  143954. };
  143955. static encode_aux_threshmatch _vq_auxt__16u0__p7_0 = {
  143956. _vq_quantthresh__16u0__p7_0,
  143957. _vq_quantmap__16u0__p7_0,
  143958. 3,
  143959. 3
  143960. };
  143961. static static_codebook _16u0__p7_0 = {
  143962. 4, 81,
  143963. _vq_lengthlist__16u0__p7_0,
  143964. 1, -518803456, 1628680192, 2, 0,
  143965. _vq_quantlist__16u0__p7_0,
  143966. NULL,
  143967. &_vq_auxt__16u0__p7_0,
  143968. NULL,
  143969. 0
  143970. };
  143971. static long _vq_quantlist__16u0__p7_1[] = {
  143972. 7,
  143973. 6,
  143974. 8,
  143975. 5,
  143976. 9,
  143977. 4,
  143978. 10,
  143979. 3,
  143980. 11,
  143981. 2,
  143982. 12,
  143983. 1,
  143984. 13,
  143985. 0,
  143986. 14,
  143987. };
  143988. static long _vq_lengthlist__16u0__p7_1[] = {
  143989. 1, 5, 5, 6, 5, 9,10,11,11,10,10,10,10,10,10, 5,
  143990. 8, 8, 8,10,10,10,10,10,10,10,10,10,10,10, 5, 8,
  143991. 9, 9, 9,10,10,10,10,10,10,10,10,10,10, 5,10, 8,
  143992. 10,10,10,10,10,10,10,10,10,10,10,10, 4, 8, 9,10,
  143993. 10,10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,
  143994. 10,10,10,10,10,10,10,10,10,10, 9,10,10,10,10,10,
  143995. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143996. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143997. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143998. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  143999. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144000. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144001. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144002. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144003. 10,
  144004. };
  144005. static float _vq_quantthresh__16u0__p7_1[] = {
  144006. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  144007. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  144008. };
  144009. static long _vq_quantmap__16u0__p7_1[] = {
  144010. 13, 11, 9, 7, 5, 3, 1, 0,
  144011. 2, 4, 6, 8, 10, 12, 14,
  144012. };
  144013. static encode_aux_threshmatch _vq_auxt__16u0__p7_1 = {
  144014. _vq_quantthresh__16u0__p7_1,
  144015. _vq_quantmap__16u0__p7_1,
  144016. 15,
  144017. 15
  144018. };
  144019. static static_codebook _16u0__p7_1 = {
  144020. 2, 225,
  144021. _vq_lengthlist__16u0__p7_1,
  144022. 1, -520986624, 1620377600, 4, 0,
  144023. _vq_quantlist__16u0__p7_1,
  144024. NULL,
  144025. &_vq_auxt__16u0__p7_1,
  144026. NULL,
  144027. 0
  144028. };
  144029. static long _vq_quantlist__16u0__p7_2[] = {
  144030. 10,
  144031. 9,
  144032. 11,
  144033. 8,
  144034. 12,
  144035. 7,
  144036. 13,
  144037. 6,
  144038. 14,
  144039. 5,
  144040. 15,
  144041. 4,
  144042. 16,
  144043. 3,
  144044. 17,
  144045. 2,
  144046. 18,
  144047. 1,
  144048. 19,
  144049. 0,
  144050. 20,
  144051. };
  144052. static long _vq_lengthlist__16u0__p7_2[] = {
  144053. 1, 6, 6, 7, 8, 7, 7,10, 9,10, 9,11,10, 9,11,10,
  144054. 9, 9, 9, 9,10, 6, 8, 7, 9, 9, 8, 8,10,10, 9,11,
  144055. 11,12,12,10, 9,11, 9,12,10, 9, 6, 9, 8, 9,12, 8,
  144056. 8,11, 9,11,11,12,11,12,12,10,11,11,10,10,11, 7,
  144057. 10, 9, 9, 9, 9, 9,10, 9,10, 9,10,10,12,10,10,10,
  144058. 11,12,10,10, 7, 9, 9, 9,10, 9, 9,10,10, 9, 9, 9,
  144059. 11,11,10,10,10,10, 9, 9,12, 7, 9,10, 9,11, 9,10,
  144060. 9,10,11,11,11,10,11,12, 9,12,11,10,10,10, 7, 9,
  144061. 9, 9, 9,10,12,10, 9,11,12,10,11,12,12,11, 9,10,
  144062. 11,10,11, 7, 9,10,10,11,10, 9,10,11,11,11,10,12,
  144063. 12,12,11,11,10,11,11,12, 8, 9,10,12,11,10,10,12,
  144064. 12,12,12,12,10,11,11, 9,11,10,12,11,11, 8, 9,10,
  144065. 10,11,12,11,11,10,10,10,12,12,12, 9,10,12,12,12,
  144066. 12,12, 8,10,11,10,10,12, 9,11,12,12,11,12,12,12,
  144067. 12,10,12,10,10,10,10, 8,12,11,11,11,10,10,11,12,
  144068. 12,12,12,11,12,12,12,11,11,11,12,10, 9,10,10,12,
  144069. 10,12,10,12,12,10,10,10,11,12,12,12,11,12,12,12,
  144070. 11,10,11,12,12,12,11,12,12,11,12,12,11,12,12,12,
  144071. 12,11,12,12,10,10,10,10,11,11,12,11,12,12,12,12,
  144072. 12,12,12,11,12,11,10,11,11,12,11,11, 9,10,10,10,
  144073. 12,10,10,11, 9,11,12,11,12,11,12,12,10,11,10,12,
  144074. 9, 9, 9,12,11,10,11,10,12,10,12,10,12,12,12,11,
  144075. 11,11,11,11,10, 9,10,10,11,10,11,11,12,11,10,11,
  144076. 12,12,12,11,11, 9,12,10,12, 9,10,12,10,10,11,10,
  144077. 11,11,12,11,10,11,10,11,11,11,11,12,11,11,10, 9,
  144078. 10,10,10, 9,11,11,10, 9,12,10,11,12,11,12,12,11,
  144079. 12,11,12,11,10,11,10,12,11,12,11,12,11,12,10,11,
  144080. 10,10,12,11,10,11,11,11,10,
  144081. };
  144082. static float _vq_quantthresh__16u0__p7_2[] = {
  144083. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  144084. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  144085. 6.5, 7.5, 8.5, 9.5,
  144086. };
  144087. static long _vq_quantmap__16u0__p7_2[] = {
  144088. 19, 17, 15, 13, 11, 9, 7, 5,
  144089. 3, 1, 0, 2, 4, 6, 8, 10,
  144090. 12, 14, 16, 18, 20,
  144091. };
  144092. static encode_aux_threshmatch _vq_auxt__16u0__p7_2 = {
  144093. _vq_quantthresh__16u0__p7_2,
  144094. _vq_quantmap__16u0__p7_2,
  144095. 21,
  144096. 21
  144097. };
  144098. static static_codebook _16u0__p7_2 = {
  144099. 2, 441,
  144100. _vq_lengthlist__16u0__p7_2,
  144101. 1, -529268736, 1611661312, 5, 0,
  144102. _vq_quantlist__16u0__p7_2,
  144103. NULL,
  144104. &_vq_auxt__16u0__p7_2,
  144105. NULL,
  144106. 0
  144107. };
  144108. static long _huff_lengthlist__16u0__single[] = {
  144109. 3, 5, 8, 7,14, 8, 9,19, 5, 2, 5, 5, 9, 6, 9,19,
  144110. 8, 4, 5, 7, 8, 9,13,19, 7, 4, 6, 5, 9, 6, 9,19,
  144111. 12, 8, 7, 9,10,11,13,19, 8, 5, 8, 6, 9, 6, 7,19,
  144112. 8, 8,10, 7, 7, 4, 5,19,12,17,19,15,18,13,11,18,
  144113. };
  144114. static static_codebook _huff_book__16u0__single = {
  144115. 2, 64,
  144116. _huff_lengthlist__16u0__single,
  144117. 0, 0, 0, 0, 0,
  144118. NULL,
  144119. NULL,
  144120. NULL,
  144121. NULL,
  144122. 0
  144123. };
  144124. static long _huff_lengthlist__16u1__long[] = {
  144125. 3, 6,10, 8,12, 8,14, 8,14,19, 5, 3, 5, 5, 7, 6,
  144126. 11, 7,16,19, 7, 5, 6, 7, 7, 9,11,12,19,19, 6, 4,
  144127. 7, 5, 7, 6,10, 7,18,18, 8, 6, 7, 7, 7, 7, 8, 9,
  144128. 18,18, 7, 5, 8, 5, 7, 5, 8, 6,18,18,12, 9,10, 9,
  144129. 9, 9, 8, 9,18,18, 8, 7,10, 6, 8, 5, 6, 4,11,18,
  144130. 11,15,16,12,11, 8, 8, 6, 9,18,14,18,18,18,16,16,
  144131. 16,13,16,18,
  144132. };
  144133. static static_codebook _huff_book__16u1__long = {
  144134. 2, 100,
  144135. _huff_lengthlist__16u1__long,
  144136. 0, 0, 0, 0, 0,
  144137. NULL,
  144138. NULL,
  144139. NULL,
  144140. NULL,
  144141. 0
  144142. };
  144143. static long _vq_quantlist__16u1__p1_0[] = {
  144144. 1,
  144145. 0,
  144146. 2,
  144147. };
  144148. static long _vq_lengthlist__16u1__p1_0[] = {
  144149. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 7, 7,10,10, 7,
  144150. 9,10, 5, 7, 8, 7,10, 9, 7,10,10, 5, 8, 8, 8,10,
  144151. 10, 8,10,10, 7,10,10,10,11,12,10,12,13, 7,10,10,
  144152. 9,13,11,10,12,13, 5, 8, 8, 8,10,10, 8,10,10, 7,
  144153. 10,10,10,12,12, 9,11,12, 7,10,11,10,12,12,10,13,
  144154. 11,
  144155. };
  144156. static float _vq_quantthresh__16u1__p1_0[] = {
  144157. -0.5, 0.5,
  144158. };
  144159. static long _vq_quantmap__16u1__p1_0[] = {
  144160. 1, 0, 2,
  144161. };
  144162. static encode_aux_threshmatch _vq_auxt__16u1__p1_0 = {
  144163. _vq_quantthresh__16u1__p1_0,
  144164. _vq_quantmap__16u1__p1_0,
  144165. 3,
  144166. 3
  144167. };
  144168. static static_codebook _16u1__p1_0 = {
  144169. 4, 81,
  144170. _vq_lengthlist__16u1__p1_0,
  144171. 1, -535822336, 1611661312, 2, 0,
  144172. _vq_quantlist__16u1__p1_0,
  144173. NULL,
  144174. &_vq_auxt__16u1__p1_0,
  144175. NULL,
  144176. 0
  144177. };
  144178. static long _vq_quantlist__16u1__p2_0[] = {
  144179. 1,
  144180. 0,
  144181. 2,
  144182. };
  144183. static long _vq_lengthlist__16u1__p2_0[] = {
  144184. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 7, 8, 6,
  144185. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 6, 8,
  144186. 8, 6, 8, 8, 6, 8, 8, 7, 7,10, 8, 9, 9, 6, 8, 8,
  144187. 7, 9, 8, 8, 9,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  144188. 8, 8, 8,10, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 7,10,
  144189. 8,
  144190. };
  144191. static float _vq_quantthresh__16u1__p2_0[] = {
  144192. -0.5, 0.5,
  144193. };
  144194. static long _vq_quantmap__16u1__p2_0[] = {
  144195. 1, 0, 2,
  144196. };
  144197. static encode_aux_threshmatch _vq_auxt__16u1__p2_0 = {
  144198. _vq_quantthresh__16u1__p2_0,
  144199. _vq_quantmap__16u1__p2_0,
  144200. 3,
  144201. 3
  144202. };
  144203. static static_codebook _16u1__p2_0 = {
  144204. 4, 81,
  144205. _vq_lengthlist__16u1__p2_0,
  144206. 1, -535822336, 1611661312, 2, 0,
  144207. _vq_quantlist__16u1__p2_0,
  144208. NULL,
  144209. &_vq_auxt__16u1__p2_0,
  144210. NULL,
  144211. 0
  144212. };
  144213. static long _vq_quantlist__16u1__p3_0[] = {
  144214. 2,
  144215. 1,
  144216. 3,
  144217. 0,
  144218. 4,
  144219. };
  144220. static long _vq_lengthlist__16u1__p3_0[] = {
  144221. 1, 5, 5, 8, 8, 6, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144222. 10, 9,11,11, 9, 9,10,11,11, 6, 8, 8,10,10, 8, 9,
  144223. 10,11,11, 8, 9,10,11,11,10,11,11,12,13,10,11,11,
  144224. 13,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  144225. 11,10,11,11,13,13,10,11,11,13,12, 9,11,11,14,13,
  144226. 10,12,12,15,14,10,12,11,14,13,12,13,13,15,15,12,
  144227. 13,13,16,14, 9,11,11,13,14,10,11,12,14,14,10,12,
  144228. 12,14,15,12,13,13,14,15,12,13,14,15,16, 5, 8, 8,
  144229. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  144230. 14,11,12,12,14,14, 8,10,10,12,12, 9,11,12,12,13,
  144231. 10,12,12,13,13,12,12,13,14,15,11,13,13,15,15, 7,
  144232. 10,10,12,12, 9,12,11,13,12,10,11,12,13,13,12,13,
  144233. 12,15,14,11,12,13,15,15,10,12,12,15,14,11,13,13,
  144234. 16,15,11,13,13,16,15,14,13,14,15,16,13,15,15,17,
  144235. 17,10,12,12,14,15,11,12,12,15,15,11,13,13,15,16,
  144236. 13,15,13,16,15,13,15,15,16,17, 5, 8, 8,11,11, 8,
  144237. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  144238. 12,14,14, 7,10,10,12,12,10,12,12,14,13, 9,11,12,
  144239. 12,13,12,13,13,15,15,12,12,13,13,15, 7,10,10,12,
  144240. 13,10,11,12,13,13,10,12,11,13,13,11,13,13,15,15,
  144241. 12,13,12,15,14, 9,12,12,15,14,11,13,13,15,15,11,
  144242. 12,13,15,15,13,14,14,17,19,13,13,14,16,16,10,12,
  144243. 12,14,15,11,13,13,15,16,11,13,12,16,15,13,15,15,
  144244. 17,18,14,15,13,16,15, 8,11,11,15,14,10,12,12,16,
  144245. 15,10,12,12,16,16,14,15,15,18,17,13,14,15,16,18,
  144246. 9,12,12,15,15,11,12,14,16,17,11,13,13,16,15,15,
  144247. 15,15,17,18,14,15,16,17,17, 9,12,12,15,15,11,14,
  144248. 13,16,16,11,13,13,16,16,15,16,15,17,18,14,16,15,
  144249. 17,16,12,14,14,17,16,12,14,15,18,17,13,15,15,17,
  144250. 17,15,15,18,16,20,15,16,17,18,18,11,14,14,16,17,
  144251. 13,15,14,18,17,13,15,15,17,17,15,17,15,18,17,15,
  144252. 17,16,19,18, 8,11,11,14,15,10,12,12,15,15,10,12,
  144253. 12,16,16,13,14,14,17,16,14,15,15,17,17, 9,12,12,
  144254. 15,16,11,13,13,16,16,11,12,13,16,16,14,16,15,20,
  144255. 17,14,16,16,17,17, 9,12,12,15,16,11,13,13,16,17,
  144256. 11,13,13,17,16,14,15,15,17,18,15,15,15,18,18,11,
  144257. 14,14,17,16,13,15,15,17,17,13,14,14,18,17,15,16,
  144258. 16,18,19,15,15,17,17,19,11,14,14,16,17,13,15,14,
  144259. 17,19,13,15,14,18,17,15,17,16,18,18,15,17,15,18,
  144260. 16,
  144261. };
  144262. static float _vq_quantthresh__16u1__p3_0[] = {
  144263. -1.5, -0.5, 0.5, 1.5,
  144264. };
  144265. static long _vq_quantmap__16u1__p3_0[] = {
  144266. 3, 1, 0, 2, 4,
  144267. };
  144268. static encode_aux_threshmatch _vq_auxt__16u1__p3_0 = {
  144269. _vq_quantthresh__16u1__p3_0,
  144270. _vq_quantmap__16u1__p3_0,
  144271. 5,
  144272. 5
  144273. };
  144274. static static_codebook _16u1__p3_0 = {
  144275. 4, 625,
  144276. _vq_lengthlist__16u1__p3_0,
  144277. 1, -533725184, 1611661312, 3, 0,
  144278. _vq_quantlist__16u1__p3_0,
  144279. NULL,
  144280. &_vq_auxt__16u1__p3_0,
  144281. NULL,
  144282. 0
  144283. };
  144284. static long _vq_quantlist__16u1__p4_0[] = {
  144285. 2,
  144286. 1,
  144287. 3,
  144288. 0,
  144289. 4,
  144290. };
  144291. static long _vq_lengthlist__16u1__p4_0[] = {
  144292. 4, 5, 5, 8, 8, 6, 6, 7, 9, 9, 6, 6, 6, 9, 9, 9,
  144293. 10, 9,11,11, 9, 9,10,11,11, 6, 7, 7,10, 9, 7, 7,
  144294. 8, 9,10, 7, 7, 8,10,10,10,10,10,10,12, 9, 9,10,
  144295. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 7,10,
  144296. 10, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  144297. 10,10,10,12,12, 9,10,10,12,12,12,11,12,13,13,11,
  144298. 11,12,12,13, 9,10,10,11,12, 9,10,10,12,12,10,10,
  144299. 10,12,12,11,12,11,14,13,11,12,12,14,13, 5, 7, 7,
  144300. 10,10, 7, 8, 8,10,10, 7, 8, 7,10,10,10,10,10,12,
  144301. 12,10,10,10,12,12, 6, 8, 7,10,10, 7, 7, 9,10,11,
  144302. 8, 9, 9,11,10,10,10,11,11,13,10,10,11,12,13, 6,
  144303. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,10,11,10,11,
  144304. 10,13,11,10,11,10,12,12,10,11,10,12,11,10,10,10,
  144305. 12,13,10,11,11,13,12,11,11,13,11,14,12,12,13,14,
  144306. 14, 9,10,10,12,13,10,11,10,13,12,10,11,11,12,13,
  144307. 11,12,11,14,12,12,13,13,15,14, 5, 7, 7,10,10, 7,
  144308. 7, 8,10,10, 7, 8, 8,10,10,10,10,10,11,12,10,10,
  144309. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  144310. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 7, 8,10,
  144311. 10, 8, 8, 9,10,11, 7, 9, 7,11,10,10,11,11,13,12,
  144312. 11,11,10,13,11, 9,10,10,12,12,10,11,11,13,12,10,
  144313. 10,11,12,12,12,13,13,14,14,11,11,12,12,14,10,10,
  144314. 11,12,12,10,11,11,12,13,10,10,10,13,12,12,13,13,
  144315. 15,14,12,13,10,14,11, 8,10,10,12,12,10,11,10,13,
  144316. 13, 9,10,10,12,12,12,13,13,15,14,11,12,12,13,13,
  144317. 9,10,10,13,12,10,10,11,13,13,10,11,10,13,12,12,
  144318. 12,13,14,15,12,13,12,15,13, 9,10,10,12,13,10,11,
  144319. 10,13,12,10,10,11,12,13,12,14,12,15,13,12,12,13,
  144320. 14,15,11,12,11,14,13,11,11,12,14,15,12,13,12,15,
  144321. 14,13,11,15,11,16,13,14,14,16,15,11,12,12,14,14,
  144322. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,12,14,
  144323. 14,14,15,15, 8,10,10,12,12, 9,10,10,12,12,10,10,
  144324. 11,13,13,11,12,12,13,13,12,13,13,14,15, 9,10,10,
  144325. 13,12,10,11,11,13,12,10,10,11,13,13,12,13,12,15,
  144326. 14,12,12,13,13,16, 9, 9,10,12,13,10,10,11,12,13,
  144327. 10,11,10,13,13,12,12,13,13,15,13,13,12,15,13,11,
  144328. 12,12,14,14,12,13,12,15,14,11,11,12,13,14,14,14,
  144329. 14,16,15,13,12,15,12,16,11,11,12,13,14,12,13,13,
  144330. 14,15,10,12,11,14,13,14,15,14,16,16,13,14,11,15,
  144331. 11,
  144332. };
  144333. static float _vq_quantthresh__16u1__p4_0[] = {
  144334. -1.5, -0.5, 0.5, 1.5,
  144335. };
  144336. static long _vq_quantmap__16u1__p4_0[] = {
  144337. 3, 1, 0, 2, 4,
  144338. };
  144339. static encode_aux_threshmatch _vq_auxt__16u1__p4_0 = {
  144340. _vq_quantthresh__16u1__p4_0,
  144341. _vq_quantmap__16u1__p4_0,
  144342. 5,
  144343. 5
  144344. };
  144345. static static_codebook _16u1__p4_0 = {
  144346. 4, 625,
  144347. _vq_lengthlist__16u1__p4_0,
  144348. 1, -533725184, 1611661312, 3, 0,
  144349. _vq_quantlist__16u1__p4_0,
  144350. NULL,
  144351. &_vq_auxt__16u1__p4_0,
  144352. NULL,
  144353. 0
  144354. };
  144355. static long _vq_quantlist__16u1__p5_0[] = {
  144356. 4,
  144357. 3,
  144358. 5,
  144359. 2,
  144360. 6,
  144361. 1,
  144362. 7,
  144363. 0,
  144364. 8,
  144365. };
  144366. static long _vq_lengthlist__16u1__p5_0[] = {
  144367. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  144368. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  144369. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  144370. 10, 9,11,11,12,11, 7, 8, 8, 9, 9,11,11,12,12, 9,
  144371. 10,10,11,11,12,12,13,12, 9,10,10,11,11,12,12,12,
  144372. 13,
  144373. };
  144374. static float _vq_quantthresh__16u1__p5_0[] = {
  144375. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144376. };
  144377. static long _vq_quantmap__16u1__p5_0[] = {
  144378. 7, 5, 3, 1, 0, 2, 4, 6,
  144379. 8,
  144380. };
  144381. static encode_aux_threshmatch _vq_auxt__16u1__p5_0 = {
  144382. _vq_quantthresh__16u1__p5_0,
  144383. _vq_quantmap__16u1__p5_0,
  144384. 9,
  144385. 9
  144386. };
  144387. static static_codebook _16u1__p5_0 = {
  144388. 2, 81,
  144389. _vq_lengthlist__16u1__p5_0,
  144390. 1, -531628032, 1611661312, 4, 0,
  144391. _vq_quantlist__16u1__p5_0,
  144392. NULL,
  144393. &_vq_auxt__16u1__p5_0,
  144394. NULL,
  144395. 0
  144396. };
  144397. static long _vq_quantlist__16u1__p6_0[] = {
  144398. 4,
  144399. 3,
  144400. 5,
  144401. 2,
  144402. 6,
  144403. 1,
  144404. 7,
  144405. 0,
  144406. 8,
  144407. };
  144408. static long _vq_lengthlist__16u1__p6_0[] = {
  144409. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 4, 6, 6, 8, 8,
  144410. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  144411. 8, 8,10, 9, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144412. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144413. 9, 9,10,10,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144414. 11,
  144415. };
  144416. static float _vq_quantthresh__16u1__p6_0[] = {
  144417. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144418. };
  144419. static long _vq_quantmap__16u1__p6_0[] = {
  144420. 7, 5, 3, 1, 0, 2, 4, 6,
  144421. 8,
  144422. };
  144423. static encode_aux_threshmatch _vq_auxt__16u1__p6_0 = {
  144424. _vq_quantthresh__16u1__p6_0,
  144425. _vq_quantmap__16u1__p6_0,
  144426. 9,
  144427. 9
  144428. };
  144429. static static_codebook _16u1__p6_0 = {
  144430. 2, 81,
  144431. _vq_lengthlist__16u1__p6_0,
  144432. 1, -531628032, 1611661312, 4, 0,
  144433. _vq_quantlist__16u1__p6_0,
  144434. NULL,
  144435. &_vq_auxt__16u1__p6_0,
  144436. NULL,
  144437. 0
  144438. };
  144439. static long _vq_quantlist__16u1__p7_0[] = {
  144440. 1,
  144441. 0,
  144442. 2,
  144443. };
  144444. static long _vq_lengthlist__16u1__p7_0[] = {
  144445. 1, 4, 4, 4, 8, 8, 4, 8, 8, 5,11, 9, 8,12,11, 8,
  144446. 12,11, 5,10,11, 8,11,12, 8,11,12, 4,11,11,11,14,
  144447. 13,10,13,13, 8,14,13,12,14,16,12,16,15, 8,14,14,
  144448. 13,16,14,12,15,16, 4,11,11,10,14,13,11,14,14, 8,
  144449. 15,14,12,15,15,12,14,16, 8,14,14,11,16,15,12,15,
  144450. 13,
  144451. };
  144452. static float _vq_quantthresh__16u1__p7_0[] = {
  144453. -5.5, 5.5,
  144454. };
  144455. static long _vq_quantmap__16u1__p7_0[] = {
  144456. 1, 0, 2,
  144457. };
  144458. static encode_aux_threshmatch _vq_auxt__16u1__p7_0 = {
  144459. _vq_quantthresh__16u1__p7_0,
  144460. _vq_quantmap__16u1__p7_0,
  144461. 3,
  144462. 3
  144463. };
  144464. static static_codebook _16u1__p7_0 = {
  144465. 4, 81,
  144466. _vq_lengthlist__16u1__p7_0,
  144467. 1, -529137664, 1618345984, 2, 0,
  144468. _vq_quantlist__16u1__p7_0,
  144469. NULL,
  144470. &_vq_auxt__16u1__p7_0,
  144471. NULL,
  144472. 0
  144473. };
  144474. static long _vq_quantlist__16u1__p7_1[] = {
  144475. 5,
  144476. 4,
  144477. 6,
  144478. 3,
  144479. 7,
  144480. 2,
  144481. 8,
  144482. 1,
  144483. 9,
  144484. 0,
  144485. 10,
  144486. };
  144487. static long _vq_lengthlist__16u1__p7_1[] = {
  144488. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 5, 7, 7,
  144489. 8, 8, 8, 8, 8, 8, 4, 5, 6, 7, 7, 8, 8, 8, 8, 8,
  144490. 8, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  144491. 8, 8, 8, 9, 9, 9, 9, 7, 8, 8, 8, 8, 9, 9, 9,10,
  144492. 9,10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10, 9, 8, 8, 8,
  144493. 9, 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,10,
  144494. 10,10,10, 8, 8, 8, 9, 9, 9,10,10,10,10,10, 8, 8,
  144495. 8, 9, 9,10,10,10,10,10,10,
  144496. };
  144497. static float _vq_quantthresh__16u1__p7_1[] = {
  144498. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144499. 3.5, 4.5,
  144500. };
  144501. static long _vq_quantmap__16u1__p7_1[] = {
  144502. 9, 7, 5, 3, 1, 0, 2, 4,
  144503. 6, 8, 10,
  144504. };
  144505. static encode_aux_threshmatch _vq_auxt__16u1__p7_1 = {
  144506. _vq_quantthresh__16u1__p7_1,
  144507. _vq_quantmap__16u1__p7_1,
  144508. 11,
  144509. 11
  144510. };
  144511. static static_codebook _16u1__p7_1 = {
  144512. 2, 121,
  144513. _vq_lengthlist__16u1__p7_1,
  144514. 1, -531365888, 1611661312, 4, 0,
  144515. _vq_quantlist__16u1__p7_1,
  144516. NULL,
  144517. &_vq_auxt__16u1__p7_1,
  144518. NULL,
  144519. 0
  144520. };
  144521. static long _vq_quantlist__16u1__p8_0[] = {
  144522. 5,
  144523. 4,
  144524. 6,
  144525. 3,
  144526. 7,
  144527. 2,
  144528. 8,
  144529. 1,
  144530. 9,
  144531. 0,
  144532. 10,
  144533. };
  144534. static long _vq_lengthlist__16u1__p8_0[] = {
  144535. 1, 4, 4, 5, 5, 8, 8,10,10,12,12, 4, 7, 7, 8, 8,
  144536. 9, 9,12,11,14,13, 4, 7, 7, 7, 8, 9,10,11,11,13,
  144537. 12, 5, 8, 8, 9, 9,11,11,12,13,15,14, 5, 7, 8, 9,
  144538. 9,11,11,13,13,17,15, 8, 9,10,11,11,12,13,17,14,
  144539. 17,16, 8,10, 9,11,11,12,12,13,15,15,17,10,11,11,
  144540. 12,13,14,15,15,16,16,17, 9,11,11,12,12,14,15,17,
  144541. 15,15,16,11,14,12,14,15,16,15,16,16,16,15,11,13,
  144542. 13,14,14,15,15,16,16,15,16,
  144543. };
  144544. static float _vq_quantthresh__16u1__p8_0[] = {
  144545. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  144546. 38.5, 49.5,
  144547. };
  144548. static long _vq_quantmap__16u1__p8_0[] = {
  144549. 9, 7, 5, 3, 1, 0, 2, 4,
  144550. 6, 8, 10,
  144551. };
  144552. static encode_aux_threshmatch _vq_auxt__16u1__p8_0 = {
  144553. _vq_quantthresh__16u1__p8_0,
  144554. _vq_quantmap__16u1__p8_0,
  144555. 11,
  144556. 11
  144557. };
  144558. static static_codebook _16u1__p8_0 = {
  144559. 2, 121,
  144560. _vq_lengthlist__16u1__p8_0,
  144561. 1, -524582912, 1618345984, 4, 0,
  144562. _vq_quantlist__16u1__p8_0,
  144563. NULL,
  144564. &_vq_auxt__16u1__p8_0,
  144565. NULL,
  144566. 0
  144567. };
  144568. static long _vq_quantlist__16u1__p8_1[] = {
  144569. 5,
  144570. 4,
  144571. 6,
  144572. 3,
  144573. 7,
  144574. 2,
  144575. 8,
  144576. 1,
  144577. 9,
  144578. 0,
  144579. 10,
  144580. };
  144581. static long _vq_lengthlist__16u1__p8_1[] = {
  144582. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7,
  144583. 8, 7, 8, 8, 8, 8, 4, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  144584. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 9, 6, 7, 7, 7,
  144585. 7, 8, 8, 8, 8, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  144586. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  144587. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  144588. 9, 9, 9, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  144589. 8, 9, 9, 9, 9, 9, 9, 9, 9,
  144590. };
  144591. static float _vq_quantthresh__16u1__p8_1[] = {
  144592. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  144593. 3.5, 4.5,
  144594. };
  144595. static long _vq_quantmap__16u1__p8_1[] = {
  144596. 9, 7, 5, 3, 1, 0, 2, 4,
  144597. 6, 8, 10,
  144598. };
  144599. static encode_aux_threshmatch _vq_auxt__16u1__p8_1 = {
  144600. _vq_quantthresh__16u1__p8_1,
  144601. _vq_quantmap__16u1__p8_1,
  144602. 11,
  144603. 11
  144604. };
  144605. static static_codebook _16u1__p8_1 = {
  144606. 2, 121,
  144607. _vq_lengthlist__16u1__p8_1,
  144608. 1, -531365888, 1611661312, 4, 0,
  144609. _vq_quantlist__16u1__p8_1,
  144610. NULL,
  144611. &_vq_auxt__16u1__p8_1,
  144612. NULL,
  144613. 0
  144614. };
  144615. static long _vq_quantlist__16u1__p9_0[] = {
  144616. 7,
  144617. 6,
  144618. 8,
  144619. 5,
  144620. 9,
  144621. 4,
  144622. 10,
  144623. 3,
  144624. 11,
  144625. 2,
  144626. 12,
  144627. 1,
  144628. 13,
  144629. 0,
  144630. 14,
  144631. };
  144632. static long _vq_lengthlist__16u1__p9_0[] = {
  144633. 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144634. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144635. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144636. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144637. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144638. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144639. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144640. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144641. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144642. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144643. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144644. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144645. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144646. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  144647. 8,
  144648. };
  144649. static float _vq_quantthresh__16u1__p9_0[] = {
  144650. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  144651. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  144652. };
  144653. static long _vq_quantmap__16u1__p9_0[] = {
  144654. 13, 11, 9, 7, 5, 3, 1, 0,
  144655. 2, 4, 6, 8, 10, 12, 14,
  144656. };
  144657. static encode_aux_threshmatch _vq_auxt__16u1__p9_0 = {
  144658. _vq_quantthresh__16u1__p9_0,
  144659. _vq_quantmap__16u1__p9_0,
  144660. 15,
  144661. 15
  144662. };
  144663. static static_codebook _16u1__p9_0 = {
  144664. 2, 225,
  144665. _vq_lengthlist__16u1__p9_0,
  144666. 1, -514071552, 1627381760, 4, 0,
  144667. _vq_quantlist__16u1__p9_0,
  144668. NULL,
  144669. &_vq_auxt__16u1__p9_0,
  144670. NULL,
  144671. 0
  144672. };
  144673. static long _vq_quantlist__16u1__p9_1[] = {
  144674. 7,
  144675. 6,
  144676. 8,
  144677. 5,
  144678. 9,
  144679. 4,
  144680. 10,
  144681. 3,
  144682. 11,
  144683. 2,
  144684. 12,
  144685. 1,
  144686. 13,
  144687. 0,
  144688. 14,
  144689. };
  144690. static long _vq_lengthlist__16u1__p9_1[] = {
  144691. 1, 6, 5, 9, 9,10,10, 6, 7, 9, 9,10,10,10,10, 5,
  144692. 10, 8,10, 8,10,10, 8, 8,10, 9,10,10,10,10, 5, 8,
  144693. 9,10,10,10,10, 8,10,10,10,10,10,10,10, 9,10,10,
  144694. 10,10,10,10, 9, 9,10,10,10,10,10,10, 9, 9, 8, 9,
  144695. 10,10,10, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  144696. 10,10,10,10,10,10,10,10,10,10,10, 8,10,10,10,10,
  144697. 10,10,10,10,10,10,10,10,10, 6, 8, 8,10,10,10, 8,
  144698. 10,10,10,10,10,10,10,10, 5, 8, 8,10,10,10, 9, 9,
  144699. 10,10,10,10,10,10,10,10, 9,10,10,10,10,10,10,10,
  144700. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  144701. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,
  144702. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144703. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144704. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  144705. 9,
  144706. };
  144707. static float _vq_quantthresh__16u1__p9_1[] = {
  144708. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  144709. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  144710. };
  144711. static long _vq_quantmap__16u1__p9_1[] = {
  144712. 13, 11, 9, 7, 5, 3, 1, 0,
  144713. 2, 4, 6, 8, 10, 12, 14,
  144714. };
  144715. static encode_aux_threshmatch _vq_auxt__16u1__p9_1 = {
  144716. _vq_quantthresh__16u1__p9_1,
  144717. _vq_quantmap__16u1__p9_1,
  144718. 15,
  144719. 15
  144720. };
  144721. static static_codebook _16u1__p9_1 = {
  144722. 2, 225,
  144723. _vq_lengthlist__16u1__p9_1,
  144724. 1, -522338304, 1620115456, 4, 0,
  144725. _vq_quantlist__16u1__p9_1,
  144726. NULL,
  144727. &_vq_auxt__16u1__p9_1,
  144728. NULL,
  144729. 0
  144730. };
  144731. static long _vq_quantlist__16u1__p9_2[] = {
  144732. 8,
  144733. 7,
  144734. 9,
  144735. 6,
  144736. 10,
  144737. 5,
  144738. 11,
  144739. 4,
  144740. 12,
  144741. 3,
  144742. 13,
  144743. 2,
  144744. 14,
  144745. 1,
  144746. 15,
  144747. 0,
  144748. 16,
  144749. };
  144750. static long _vq_lengthlist__16u1__p9_2[] = {
  144751. 1, 6, 6, 7, 8, 8,11,10, 9, 9,11, 9,10, 9,11,11,
  144752. 9, 6, 7, 6,11, 8,11, 9,10,10,11, 9,11,10,10,10,
  144753. 11, 9, 5, 7, 7, 8, 8,10,11, 8, 8,11, 9, 9,10,11,
  144754. 9,10,11, 8, 9, 6, 8, 8, 9, 9,10,10,11,11,11, 9,
  144755. 11,10, 9,11, 8, 8, 8, 9, 8, 9,10,11, 9, 9,11,11,
  144756. 10, 9, 9,11,10, 8,11, 8, 9, 8,11, 9,10, 9,10,11,
  144757. 11,10,10, 9,10,10, 8, 8, 9,10,10,10, 9,11, 9,10,
  144758. 11,11,11,11,10, 9,11, 9, 9,11,11,10, 8,11,11,11,
  144759. 9,10,10,11,10,11,11, 9,11,10, 9,11,10,10,10,10,
  144760. 9,11,10,11,10, 9, 9,10,11, 9, 8,10,11,11,10,10,
  144761. 11, 9,11,10,11,11,10,11, 9, 9, 8,10, 8, 9,11, 9,
  144762. 8,10,10, 9,11,10,11,10,11, 9,11, 8,10,11,11,11,
  144763. 11,10,10,11,11,11,11,10,11,11,10, 9, 8,10,10, 9,
  144764. 11,10,11,11,11, 9, 9, 9,11,11,11,10,10, 9, 9,10,
  144765. 9,11,11,11,11, 8,10,11,10,11,11,10,11,11, 9, 9,
  144766. 9,10, 9,11, 9,11,11,11,11,11,10,11,11,10,11,10,
  144767. 11,11, 9,11,10,11,10, 9,10, 9,10,10,11,11,11,11,
  144768. 9,10, 9,10,11,11,10,11,11,11,11,11,11,10,11,11,
  144769. 10,
  144770. };
  144771. static float _vq_quantthresh__16u1__p9_2[] = {
  144772. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  144773. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  144774. };
  144775. static long _vq_quantmap__16u1__p9_2[] = {
  144776. 15, 13, 11, 9, 7, 5, 3, 1,
  144777. 0, 2, 4, 6, 8, 10, 12, 14,
  144778. 16,
  144779. };
  144780. static encode_aux_threshmatch _vq_auxt__16u1__p9_2 = {
  144781. _vq_quantthresh__16u1__p9_2,
  144782. _vq_quantmap__16u1__p9_2,
  144783. 17,
  144784. 17
  144785. };
  144786. static static_codebook _16u1__p9_2 = {
  144787. 2, 289,
  144788. _vq_lengthlist__16u1__p9_2,
  144789. 1, -529530880, 1611661312, 5, 0,
  144790. _vq_quantlist__16u1__p9_2,
  144791. NULL,
  144792. &_vq_auxt__16u1__p9_2,
  144793. NULL,
  144794. 0
  144795. };
  144796. static long _huff_lengthlist__16u1__short[] = {
  144797. 5, 7,10, 9,11,10,15,11,13,16, 6, 4, 6, 6, 7, 7,
  144798. 10, 9,12,16,10, 6, 5, 6, 6, 7,10,11,16,16, 9, 6,
  144799. 7, 6, 7, 7,10, 8,14,16,11, 6, 5, 4, 5, 6, 8, 9,
  144800. 15,16, 9, 6, 6, 5, 6, 6, 9, 8,14,16,12, 7, 6, 6,
  144801. 5, 6, 6, 7,13,16, 8, 6, 7, 6, 5, 5, 4, 4,11,16,
  144802. 9, 8, 9, 9, 7, 7, 6, 5,13,16,14,14,16,15,16,15,
  144803. 16,16,16,16,
  144804. };
  144805. static static_codebook _huff_book__16u1__short = {
  144806. 2, 100,
  144807. _huff_lengthlist__16u1__short,
  144808. 0, 0, 0, 0, 0,
  144809. NULL,
  144810. NULL,
  144811. NULL,
  144812. NULL,
  144813. 0
  144814. };
  144815. static long _huff_lengthlist__16u2__long[] = {
  144816. 5, 7,10,10,10,11,11,13,18,19, 6, 5, 5, 6, 7, 8,
  144817. 9,12,19,19, 8, 5, 4, 4, 6, 7, 9,13,19,19, 8, 5,
  144818. 4, 4, 5, 6, 8,12,17,19, 7, 5, 5, 4, 4, 5, 7,12,
  144819. 18,18, 8, 7, 7, 6, 5, 5, 6,10,18,18, 9, 9, 9, 8,
  144820. 6, 5, 6, 9,18,18,11,13,13,13, 8, 7, 7, 9,16,18,
  144821. 13,17,18,16,11, 9, 9, 9,17,18,15,18,18,18,15,13,
  144822. 13,14,18,18,
  144823. };
  144824. static static_codebook _huff_book__16u2__long = {
  144825. 2, 100,
  144826. _huff_lengthlist__16u2__long,
  144827. 0, 0, 0, 0, 0,
  144828. NULL,
  144829. NULL,
  144830. NULL,
  144831. NULL,
  144832. 0
  144833. };
  144834. static long _huff_lengthlist__16u2__short[] = {
  144835. 8,11,12,12,14,15,16,16,16,16, 9, 7, 7, 8, 9,11,
  144836. 13,14,16,16,13, 7, 6, 6, 7, 9,12,13,15,16,15, 7,
  144837. 6, 5, 4, 6,10,11,14,16,12, 8, 7, 4, 2, 4, 7,10,
  144838. 14,16,11, 9, 7, 5, 3, 4, 6, 9,14,16,11,10, 9, 7,
  144839. 5, 5, 6, 9,16,16,10,10, 9, 8, 6, 6, 7,10,16,16,
  144840. 11,11,11,10,10,10,11,14,16,16,16,14,14,13,14,16,
  144841. 16,16,16,16,
  144842. };
  144843. static static_codebook _huff_book__16u2__short = {
  144844. 2, 100,
  144845. _huff_lengthlist__16u2__short,
  144846. 0, 0, 0, 0, 0,
  144847. NULL,
  144848. NULL,
  144849. NULL,
  144850. NULL,
  144851. 0
  144852. };
  144853. static long _vq_quantlist__16u2_p1_0[] = {
  144854. 1,
  144855. 0,
  144856. 2,
  144857. };
  144858. static long _vq_lengthlist__16u2_p1_0[] = {
  144859. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  144860. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 8, 9,
  144861. 9, 7, 9, 9, 7, 9, 9, 9,10,10, 9,10,10, 7, 9, 9,
  144862. 9,10,10, 9,10,11, 5, 7, 8, 8, 9, 9, 8, 9, 9, 7,
  144863. 9, 9, 9,10,10, 9, 9,10, 7, 9, 9, 9,10,10, 9,11,
  144864. 10,
  144865. };
  144866. static float _vq_quantthresh__16u2_p1_0[] = {
  144867. -0.5, 0.5,
  144868. };
  144869. static long _vq_quantmap__16u2_p1_0[] = {
  144870. 1, 0, 2,
  144871. };
  144872. static encode_aux_threshmatch _vq_auxt__16u2_p1_0 = {
  144873. _vq_quantthresh__16u2_p1_0,
  144874. _vq_quantmap__16u2_p1_0,
  144875. 3,
  144876. 3
  144877. };
  144878. static static_codebook _16u2_p1_0 = {
  144879. 4, 81,
  144880. _vq_lengthlist__16u2_p1_0,
  144881. 1, -535822336, 1611661312, 2, 0,
  144882. _vq_quantlist__16u2_p1_0,
  144883. NULL,
  144884. &_vq_auxt__16u2_p1_0,
  144885. NULL,
  144886. 0
  144887. };
  144888. static long _vq_quantlist__16u2_p2_0[] = {
  144889. 2,
  144890. 1,
  144891. 3,
  144892. 0,
  144893. 4,
  144894. };
  144895. static long _vq_lengthlist__16u2_p2_0[] = {
  144896. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 9,
  144897. 10, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  144898. 8,10,10, 7, 8, 8,10,10,10,10,10,12,12, 9,10,10,
  144899. 11,12, 5, 7, 7, 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,
  144900. 10, 9,10,10,12,11,10,10,10,12,12, 9,10,10,12,12,
  144901. 10,11,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  144902. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,12,10,10,
  144903. 10,12,12,11,12,12,14,13,12,13,12,14,14, 5, 7, 7,
  144904. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,12,
  144905. 12,10,10,11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  144906. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,12,13, 7,
  144907. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  144908. 10,13,12,10,11,11,13,13, 9,11,10,13,13,10,11,11,
  144909. 13,13,10,11,11,13,13,12,12,13,13,15,12,12,13,14,
  144910. 15, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  144911. 11,13,11,14,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  144912. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  144913. 11,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  144914. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  144915. 11, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,12,
  144916. 11,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  144917. 10,11,12,13,12,13,13,15,14,11,11,13,12,14,10,10,
  144918. 11,13,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  144919. 14,14,12,13,12,14,13, 8,10, 9,12,12, 9,11,10,13,
  144920. 13, 9,10,10,12,13,12,13,13,14,14,12,12,13,14,14,
  144921. 9,11,10,13,13,10,11,11,13,13,10,11,11,13,13,12,
  144922. 13,13,15,15,13,13,13,14,15, 9,10,10,12,13,10,11,
  144923. 10,13,12,10,11,11,13,13,12,13,12,15,14,13,13,13,
  144924. 14,15,11,12,12,15,14,12,12,13,15,15,12,13,13,15,
  144925. 14,14,13,15,14,16,13,14,15,16,16,11,12,12,14,14,
  144926. 11,12,12,15,14,12,13,13,15,15,13,14,13,16,14,14,
  144927. 14,14,16,16, 8, 9, 9,12,12, 9,10,10,13,12, 9,10,
  144928. 10,13,13,12,12,12,14,14,12,12,13,15,15, 9,10,10,
  144929. 13,12,10,11,11,13,13,10,10,11,13,14,12,13,13,15,
  144930. 15,12,12,13,14,15, 9,10,10,13,13,10,11,11,13,13,
  144931. 10,11,11,13,13,12,13,13,14,14,13,14,13,15,14,11,
  144932. 12,12,14,14,12,13,13,15,14,11,12,12,14,15,14,14,
  144933. 14,16,15,13,12,14,14,16,11,12,13,14,15,12,13,13,
  144934. 14,16,12,13,12,15,14,13,15,14,16,16,14,15,13,16,
  144935. 13,
  144936. };
  144937. static float _vq_quantthresh__16u2_p2_0[] = {
  144938. -1.5, -0.5, 0.5, 1.5,
  144939. };
  144940. static long _vq_quantmap__16u2_p2_0[] = {
  144941. 3, 1, 0, 2, 4,
  144942. };
  144943. static encode_aux_threshmatch _vq_auxt__16u2_p2_0 = {
  144944. _vq_quantthresh__16u2_p2_0,
  144945. _vq_quantmap__16u2_p2_0,
  144946. 5,
  144947. 5
  144948. };
  144949. static static_codebook _16u2_p2_0 = {
  144950. 4, 625,
  144951. _vq_lengthlist__16u2_p2_0,
  144952. 1, -533725184, 1611661312, 3, 0,
  144953. _vq_quantlist__16u2_p2_0,
  144954. NULL,
  144955. &_vq_auxt__16u2_p2_0,
  144956. NULL,
  144957. 0
  144958. };
  144959. static long _vq_quantlist__16u2_p3_0[] = {
  144960. 4,
  144961. 3,
  144962. 5,
  144963. 2,
  144964. 6,
  144965. 1,
  144966. 7,
  144967. 0,
  144968. 8,
  144969. };
  144970. static long _vq_lengthlist__16u2_p3_0[] = {
  144971. 2, 4, 4, 6, 6, 7, 7, 9, 9, 4, 5, 5, 6, 6, 8, 7,
  144972. 9, 9, 4, 5, 5, 6, 6, 7, 8, 9, 9, 6, 6, 6, 7, 7,
  144973. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8, 9,10, 7, 8, 7,
  144974. 8, 8, 9, 9,10,10, 7, 8, 8, 8, 8, 9, 9,10,10, 9,
  144975. 9, 9,10, 9,10,10,11,11, 9, 9, 9,10,10,10,10,11,
  144976. 11,
  144977. };
  144978. static float _vq_quantthresh__16u2_p3_0[] = {
  144979. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  144980. };
  144981. static long _vq_quantmap__16u2_p3_0[] = {
  144982. 7, 5, 3, 1, 0, 2, 4, 6,
  144983. 8,
  144984. };
  144985. static encode_aux_threshmatch _vq_auxt__16u2_p3_0 = {
  144986. _vq_quantthresh__16u2_p3_0,
  144987. _vq_quantmap__16u2_p3_0,
  144988. 9,
  144989. 9
  144990. };
  144991. static static_codebook _16u2_p3_0 = {
  144992. 2, 81,
  144993. _vq_lengthlist__16u2_p3_0,
  144994. 1, -531628032, 1611661312, 4, 0,
  144995. _vq_quantlist__16u2_p3_0,
  144996. NULL,
  144997. &_vq_auxt__16u2_p3_0,
  144998. NULL,
  144999. 0
  145000. };
  145001. static long _vq_quantlist__16u2_p4_0[] = {
  145002. 8,
  145003. 7,
  145004. 9,
  145005. 6,
  145006. 10,
  145007. 5,
  145008. 11,
  145009. 4,
  145010. 12,
  145011. 3,
  145012. 13,
  145013. 2,
  145014. 14,
  145015. 1,
  145016. 15,
  145017. 0,
  145018. 16,
  145019. };
  145020. static long _vq_lengthlist__16u2_p4_0[] = {
  145021. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,11,
  145022. 11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,11,
  145023. 12,11, 5, 5, 5, 7, 7, 8, 8, 9, 9, 9, 9,10,10,11,
  145024. 11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  145025. 11,11,12,12, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,10,
  145026. 10,11,11,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,
  145027. 11,11,12,12,12,12, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  145028. 10,11,11,11,12,12,12, 9, 9, 9, 9, 9, 9,10,10,10,
  145029. 10,10,11,11,12,12,13,13, 8, 9, 9, 9, 9,10, 9,10,
  145030. 10,10,10,11,11,12,12,13,13, 9, 9, 9, 9, 9,10,10,
  145031. 10,10,11,11,11,12,12,12,13,13, 9, 9, 9, 9, 9,10,
  145032. 10,10,10,11,11,12,11,12,12,13,13,10,10,10,10,10,
  145033. 11,11,11,11,11,12,12,12,12,13,13,14,10,10,10,10,
  145034. 10,11,11,11,11,12,11,12,12,13,12,13,13,11,11,11,
  145035. 11,11,12,12,12,12,12,12,13,13,13,13,14,14,11,11,
  145036. 11,11,11,12,12,12,12,12,12,13,12,13,13,14,14,11,
  145037. 12,12,12,12,12,12,13,13,13,13,13,13,14,14,14,14,
  145038. 11,12,12,12,12,12,12,13,13,13,13,14,13,14,14,14,
  145039. 14,
  145040. };
  145041. static float _vq_quantthresh__16u2_p4_0[] = {
  145042. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145043. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145044. };
  145045. static long _vq_quantmap__16u2_p4_0[] = {
  145046. 15, 13, 11, 9, 7, 5, 3, 1,
  145047. 0, 2, 4, 6, 8, 10, 12, 14,
  145048. 16,
  145049. };
  145050. static encode_aux_threshmatch _vq_auxt__16u2_p4_0 = {
  145051. _vq_quantthresh__16u2_p4_0,
  145052. _vq_quantmap__16u2_p4_0,
  145053. 17,
  145054. 17
  145055. };
  145056. static static_codebook _16u2_p4_0 = {
  145057. 2, 289,
  145058. _vq_lengthlist__16u2_p4_0,
  145059. 1, -529530880, 1611661312, 5, 0,
  145060. _vq_quantlist__16u2_p4_0,
  145061. NULL,
  145062. &_vq_auxt__16u2_p4_0,
  145063. NULL,
  145064. 0
  145065. };
  145066. static long _vq_quantlist__16u2_p5_0[] = {
  145067. 1,
  145068. 0,
  145069. 2,
  145070. };
  145071. static long _vq_lengthlist__16u2_p5_0[] = {
  145072. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10, 9, 7,
  145073. 10, 9, 5, 8, 9, 7, 9,10, 7, 9,10, 4, 9, 9, 9,11,
  145074. 11, 8,11,11, 7,11,11,10,10,13,10,14,13, 7,11,11,
  145075. 10,13,11,10,13,14, 5, 9, 9, 8,11,11, 9,11,11, 7,
  145076. 11,11,10,14,13,10,12,14, 7,11,11,10,13,13,10,13,
  145077. 10,
  145078. };
  145079. static float _vq_quantthresh__16u2_p5_0[] = {
  145080. -5.5, 5.5,
  145081. };
  145082. static long _vq_quantmap__16u2_p5_0[] = {
  145083. 1, 0, 2,
  145084. };
  145085. static encode_aux_threshmatch _vq_auxt__16u2_p5_0 = {
  145086. _vq_quantthresh__16u2_p5_0,
  145087. _vq_quantmap__16u2_p5_0,
  145088. 3,
  145089. 3
  145090. };
  145091. static static_codebook _16u2_p5_0 = {
  145092. 4, 81,
  145093. _vq_lengthlist__16u2_p5_0,
  145094. 1, -529137664, 1618345984, 2, 0,
  145095. _vq_quantlist__16u2_p5_0,
  145096. NULL,
  145097. &_vq_auxt__16u2_p5_0,
  145098. NULL,
  145099. 0
  145100. };
  145101. static long _vq_quantlist__16u2_p5_1[] = {
  145102. 5,
  145103. 4,
  145104. 6,
  145105. 3,
  145106. 7,
  145107. 2,
  145108. 8,
  145109. 1,
  145110. 9,
  145111. 0,
  145112. 10,
  145113. };
  145114. static long _vq_lengthlist__16u2_p5_1[] = {
  145115. 2, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 5, 5, 5, 7, 7,
  145116. 7, 7, 8, 8, 8, 8, 5, 5, 6, 7, 7, 7, 7, 8, 8, 8,
  145117. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  145118. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 9, 9,
  145119. 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  145120. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  145121. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  145122. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  145123. };
  145124. static float _vq_quantthresh__16u2_p5_1[] = {
  145125. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145126. 3.5, 4.5,
  145127. };
  145128. static long _vq_quantmap__16u2_p5_1[] = {
  145129. 9, 7, 5, 3, 1, 0, 2, 4,
  145130. 6, 8, 10,
  145131. };
  145132. static encode_aux_threshmatch _vq_auxt__16u2_p5_1 = {
  145133. _vq_quantthresh__16u2_p5_1,
  145134. _vq_quantmap__16u2_p5_1,
  145135. 11,
  145136. 11
  145137. };
  145138. static static_codebook _16u2_p5_1 = {
  145139. 2, 121,
  145140. _vq_lengthlist__16u2_p5_1,
  145141. 1, -531365888, 1611661312, 4, 0,
  145142. _vq_quantlist__16u2_p5_1,
  145143. NULL,
  145144. &_vq_auxt__16u2_p5_1,
  145145. NULL,
  145146. 0
  145147. };
  145148. static long _vq_quantlist__16u2_p6_0[] = {
  145149. 6,
  145150. 5,
  145151. 7,
  145152. 4,
  145153. 8,
  145154. 3,
  145155. 9,
  145156. 2,
  145157. 10,
  145158. 1,
  145159. 11,
  145160. 0,
  145161. 12,
  145162. };
  145163. static long _vq_lengthlist__16u2_p6_0[] = {
  145164. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6,
  145165. 8, 8, 9, 9, 9, 9,10,10,12,11, 4, 6, 6, 8, 8, 9,
  145166. 9, 9, 9,10,10,11,12, 7, 8, 8, 9, 9,10,10,10,10,
  145167. 12,12,13,12, 7, 8, 8, 9, 9,10,10,10,10,11,12,12,
  145168. 12, 8, 9, 9,10,10,11,11,11,11,12,12,13,13, 8, 9,
  145169. 9,10,10,11,11,11,11,12,13,13,13, 8, 9, 9,10,10,
  145170. 11,11,12,12,13,13,14,14, 8, 9, 9,10,10,11,11,12,
  145171. 12,13,13,14,14, 9,10,10,11,12,13,12,13,14,14,14,
  145172. 14,14, 9,10,10,11,12,12,13,13,13,14,14,14,14,10,
  145173. 11,11,12,12,13,13,14,14,15,15,15,15,10,11,11,12,
  145174. 12,13,13,14,14,14,14,15,15,
  145175. };
  145176. static float _vq_quantthresh__16u2_p6_0[] = {
  145177. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145178. 12.5, 17.5, 22.5, 27.5,
  145179. };
  145180. static long _vq_quantmap__16u2_p6_0[] = {
  145181. 11, 9, 7, 5, 3, 1, 0, 2,
  145182. 4, 6, 8, 10, 12,
  145183. };
  145184. static encode_aux_threshmatch _vq_auxt__16u2_p6_0 = {
  145185. _vq_quantthresh__16u2_p6_0,
  145186. _vq_quantmap__16u2_p6_0,
  145187. 13,
  145188. 13
  145189. };
  145190. static static_codebook _16u2_p6_0 = {
  145191. 2, 169,
  145192. _vq_lengthlist__16u2_p6_0,
  145193. 1, -526516224, 1616117760, 4, 0,
  145194. _vq_quantlist__16u2_p6_0,
  145195. NULL,
  145196. &_vq_auxt__16u2_p6_0,
  145197. NULL,
  145198. 0
  145199. };
  145200. static long _vq_quantlist__16u2_p6_1[] = {
  145201. 2,
  145202. 1,
  145203. 3,
  145204. 0,
  145205. 4,
  145206. };
  145207. static long _vq_lengthlist__16u2_p6_1[] = {
  145208. 2, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5,
  145209. 5, 5, 6, 6, 5, 5, 5, 6, 6,
  145210. };
  145211. static float _vq_quantthresh__16u2_p6_1[] = {
  145212. -1.5, -0.5, 0.5, 1.5,
  145213. };
  145214. static long _vq_quantmap__16u2_p6_1[] = {
  145215. 3, 1, 0, 2, 4,
  145216. };
  145217. static encode_aux_threshmatch _vq_auxt__16u2_p6_1 = {
  145218. _vq_quantthresh__16u2_p6_1,
  145219. _vq_quantmap__16u2_p6_1,
  145220. 5,
  145221. 5
  145222. };
  145223. static static_codebook _16u2_p6_1 = {
  145224. 2, 25,
  145225. _vq_lengthlist__16u2_p6_1,
  145226. 1, -533725184, 1611661312, 3, 0,
  145227. _vq_quantlist__16u2_p6_1,
  145228. NULL,
  145229. &_vq_auxt__16u2_p6_1,
  145230. NULL,
  145231. 0
  145232. };
  145233. static long _vq_quantlist__16u2_p7_0[] = {
  145234. 6,
  145235. 5,
  145236. 7,
  145237. 4,
  145238. 8,
  145239. 3,
  145240. 9,
  145241. 2,
  145242. 10,
  145243. 1,
  145244. 11,
  145245. 0,
  145246. 12,
  145247. };
  145248. static long _vq_lengthlist__16u2_p7_0[] = {
  145249. 1, 4, 4, 7, 7, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 6,
  145250. 9, 9, 9, 9, 9, 9,10,10,11,11, 4, 6, 6, 8, 9, 9,
  145251. 9, 9, 9,10,11,12,11, 7, 8, 9,10,10,10,10,11,10,
  145252. 11,12,12,13, 7, 9, 9,10,10,10,10,10,10,11,12,13,
  145253. 13, 7, 9, 8,10,10,11,11,11,12,12,13,13,14, 7, 9,
  145254. 9,10,10,11,11,11,12,13,13,13,13, 8, 9, 9,10,11,
  145255. 11,12,12,12,13,13,13,13, 8, 9, 9,10,11,11,11,12,
  145256. 12,13,13,14,14, 9,10,10,12,11,12,13,13,13,14,13,
  145257. 13,13, 9,10,10,11,11,12,12,13,14,13,13,14,13,10,
  145258. 11,11,12,13,14,14,14,15,14,14,14,14,10,11,11,12,
  145259. 12,13,13,13,14,14,14,15,14,
  145260. };
  145261. static float _vq_quantthresh__16u2_p7_0[] = {
  145262. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  145263. 27.5, 38.5, 49.5, 60.5,
  145264. };
  145265. static long _vq_quantmap__16u2_p7_0[] = {
  145266. 11, 9, 7, 5, 3, 1, 0, 2,
  145267. 4, 6, 8, 10, 12,
  145268. };
  145269. static encode_aux_threshmatch _vq_auxt__16u2_p7_0 = {
  145270. _vq_quantthresh__16u2_p7_0,
  145271. _vq_quantmap__16u2_p7_0,
  145272. 13,
  145273. 13
  145274. };
  145275. static static_codebook _16u2_p7_0 = {
  145276. 2, 169,
  145277. _vq_lengthlist__16u2_p7_0,
  145278. 1, -523206656, 1618345984, 4, 0,
  145279. _vq_quantlist__16u2_p7_0,
  145280. NULL,
  145281. &_vq_auxt__16u2_p7_0,
  145282. NULL,
  145283. 0
  145284. };
  145285. static long _vq_quantlist__16u2_p7_1[] = {
  145286. 5,
  145287. 4,
  145288. 6,
  145289. 3,
  145290. 7,
  145291. 2,
  145292. 8,
  145293. 1,
  145294. 9,
  145295. 0,
  145296. 10,
  145297. };
  145298. static long _vq_lengthlist__16u2_p7_1[] = {
  145299. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  145300. 7, 7, 7, 7, 8, 8, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8,
  145301. 8, 6, 6, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 7, 7, 7,
  145302. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  145303. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  145304. 8, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8,
  145305. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  145306. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  145307. };
  145308. static float _vq_quantthresh__16u2_p7_1[] = {
  145309. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  145310. 3.5, 4.5,
  145311. };
  145312. static long _vq_quantmap__16u2_p7_1[] = {
  145313. 9, 7, 5, 3, 1, 0, 2, 4,
  145314. 6, 8, 10,
  145315. };
  145316. static encode_aux_threshmatch _vq_auxt__16u2_p7_1 = {
  145317. _vq_quantthresh__16u2_p7_1,
  145318. _vq_quantmap__16u2_p7_1,
  145319. 11,
  145320. 11
  145321. };
  145322. static static_codebook _16u2_p7_1 = {
  145323. 2, 121,
  145324. _vq_lengthlist__16u2_p7_1,
  145325. 1, -531365888, 1611661312, 4, 0,
  145326. _vq_quantlist__16u2_p7_1,
  145327. NULL,
  145328. &_vq_auxt__16u2_p7_1,
  145329. NULL,
  145330. 0
  145331. };
  145332. static long _vq_quantlist__16u2_p8_0[] = {
  145333. 7,
  145334. 6,
  145335. 8,
  145336. 5,
  145337. 9,
  145338. 4,
  145339. 10,
  145340. 3,
  145341. 11,
  145342. 2,
  145343. 12,
  145344. 1,
  145345. 13,
  145346. 0,
  145347. 14,
  145348. };
  145349. static long _vq_lengthlist__16u2_p8_0[] = {
  145350. 1, 5, 5, 7, 7, 8, 8, 7, 7, 8, 8,10, 9,11,11, 4,
  145351. 6, 6, 8, 8,10, 9, 9, 8, 9, 9,10,10,12,14, 4, 6,
  145352. 7, 8, 9, 9,10, 9, 8, 9, 9,10,12,12,11, 7, 8, 8,
  145353. 10,10,10,10, 9, 9,10,10,11,13,13,12, 7, 8, 8, 9,
  145354. 11,11,10, 9, 9,11,10,12,11,11,14, 8, 9, 9,11,10,
  145355. 11,11,10,10,11,11,13,12,14,12, 8, 9, 9,11,12,11,
  145356. 11,10,10,12,11,12,12,12,14, 7, 8, 8, 9, 9,10,10,
  145357. 10,11,12,11,13,13,14,12, 7, 8, 9, 9, 9,10,10,11,
  145358. 11,11,12,12,14,14,14, 8,10, 9,10,11,11,11,11,14,
  145359. 12,12,13,14,14,13, 9, 9, 9,10,11,11,11,12,12,12,
  145360. 14,12,14,13,14,10,10,10,12,11,12,11,14,13,14,13,
  145361. 14,14,13,14, 9,10,10,11,12,11,13,12,13,13,14,14,
  145362. 14,13,14,10,13,13,12,12,11,12,14,13,14,13,14,12,
  145363. 14,13,10,11,11,12,11,12,12,14,14,14,13,14,14,14,
  145364. 14,
  145365. };
  145366. static float _vq_quantthresh__16u2_p8_0[] = {
  145367. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  145368. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  145369. };
  145370. static long _vq_quantmap__16u2_p8_0[] = {
  145371. 13, 11, 9, 7, 5, 3, 1, 0,
  145372. 2, 4, 6, 8, 10, 12, 14,
  145373. };
  145374. static encode_aux_threshmatch _vq_auxt__16u2_p8_0 = {
  145375. _vq_quantthresh__16u2_p8_0,
  145376. _vq_quantmap__16u2_p8_0,
  145377. 15,
  145378. 15
  145379. };
  145380. static static_codebook _16u2_p8_0 = {
  145381. 2, 225,
  145382. _vq_lengthlist__16u2_p8_0,
  145383. 1, -520986624, 1620377600, 4, 0,
  145384. _vq_quantlist__16u2_p8_0,
  145385. NULL,
  145386. &_vq_auxt__16u2_p8_0,
  145387. NULL,
  145388. 0
  145389. };
  145390. static long _vq_quantlist__16u2_p8_1[] = {
  145391. 10,
  145392. 9,
  145393. 11,
  145394. 8,
  145395. 12,
  145396. 7,
  145397. 13,
  145398. 6,
  145399. 14,
  145400. 5,
  145401. 15,
  145402. 4,
  145403. 16,
  145404. 3,
  145405. 17,
  145406. 2,
  145407. 18,
  145408. 1,
  145409. 19,
  145410. 0,
  145411. 20,
  145412. };
  145413. static long _vq_lengthlist__16u2_p8_1[] = {
  145414. 2, 5, 5, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,10, 9, 9,
  145415. 9,10,10,10,10, 5, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,
  145416. 10, 9,10,10,10,10,10,10,11,10, 5, 6, 6, 7, 7, 8,
  145417. 8, 8, 9, 9,10,10,10,10,10,10,10,10,10,10,10, 7,
  145418. 7, 7, 8, 8, 9, 8, 9, 9,10, 9,10,10,10,10,10,10,
  145419. 11,10,11,10, 7, 7, 7, 8, 8, 8, 9, 9, 9,10, 9,10,
  145420. 10,10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9,
  145421. 10, 9,10,10,10,10,10,10,10,11,10,10,11,10, 8, 8,
  145422. 8, 8, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,11,
  145423. 11,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,
  145424. 11,10,11,10,11,10,11,10, 8, 9, 9, 9, 9, 9,10,10,
  145425. 10,10,10,10,10,10,10,10,11,11,10,10,10, 9,10, 9,
  145426. 9,10,10,10,11,10,10,10,10,10,10,10,10,11,11,11,
  145427. 11,11, 9, 9, 9,10, 9,10,10,10,10,10,10,11,10,11,
  145428. 10,11,11,11,11,10,10, 9,10, 9,10,10,10,10,11,10,
  145429. 10,10,10,10,11,10,11,10,11,10,10,11, 9,10,10,10,
  145430. 10,10,10,10,10,10,11,10,10,11,11,10,11,11,11,11,
  145431. 11, 9, 9,10,10,10,10,10,11,10,10,11,10,10,11,10,
  145432. 10,11,11,11,11,11, 9,10,10,10,10,10,10,10,11,10,
  145433. 11,10,11,10,11,11,11,11,11,10,11,10,10,10,10,10,
  145434. 10,10,10,10,11,11,11,11,11,11,11,11,11,10,11,11,
  145435. 10,10,10,10,10,11,10,10,10,11,10,11,11,11,11,10,
  145436. 12,11,11,11,10,10,10,10,10,10,11,10,10,10,11,11,
  145437. 12,11,11,11,11,11,11,11,11,11,10,10,10,11,10,11,
  145438. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  145439. 10,10,11,10,11,10,10,11,11,11,11,11,11,11,11,11,
  145440. 11,11,11,10,10,10,10,10,10,10,11,11,10,11,11,10,
  145441. 11,11,10,11,11,11,10,11,11,
  145442. };
  145443. static float _vq_quantthresh__16u2_p8_1[] = {
  145444. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  145445. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  145446. 6.5, 7.5, 8.5, 9.5,
  145447. };
  145448. static long _vq_quantmap__16u2_p8_1[] = {
  145449. 19, 17, 15, 13, 11, 9, 7, 5,
  145450. 3, 1, 0, 2, 4, 6, 8, 10,
  145451. 12, 14, 16, 18, 20,
  145452. };
  145453. static encode_aux_threshmatch _vq_auxt__16u2_p8_1 = {
  145454. _vq_quantthresh__16u2_p8_1,
  145455. _vq_quantmap__16u2_p8_1,
  145456. 21,
  145457. 21
  145458. };
  145459. static static_codebook _16u2_p8_1 = {
  145460. 2, 441,
  145461. _vq_lengthlist__16u2_p8_1,
  145462. 1, -529268736, 1611661312, 5, 0,
  145463. _vq_quantlist__16u2_p8_1,
  145464. NULL,
  145465. &_vq_auxt__16u2_p8_1,
  145466. NULL,
  145467. 0
  145468. };
  145469. static long _vq_quantlist__16u2_p9_0[] = {
  145470. 5586,
  145471. 4655,
  145472. 6517,
  145473. 3724,
  145474. 7448,
  145475. 2793,
  145476. 8379,
  145477. 1862,
  145478. 9310,
  145479. 931,
  145480. 10241,
  145481. 0,
  145482. 11172,
  145483. 5521,
  145484. 5651,
  145485. };
  145486. static long _vq_lengthlist__16u2_p9_0[] = {
  145487. 1,10,10,10,10,10,10,10,10,10,10,10,10, 5, 4,10,
  145488. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145489. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145490. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145491. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145492. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145493. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145494. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145495. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145496. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145497. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145498. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  145499. 10,10,10, 4,10,10,10,10,10,10,10,10,10,10,10,10,
  145500. 6, 6, 5,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 5,
  145501. 5,
  145502. };
  145503. static float _vq_quantthresh__16u2_p9_0[] = {
  145504. -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -498, -32.5, 32.5,
  145505. 498, 1396.5, 2327.5, 3258.5, 4189.5, 5120.5,
  145506. };
  145507. static long _vq_quantmap__16u2_p9_0[] = {
  145508. 11, 9, 7, 5, 3, 1, 13, 0,
  145509. 14, 2, 4, 6, 8, 10, 12,
  145510. };
  145511. static encode_aux_threshmatch _vq_auxt__16u2_p9_0 = {
  145512. _vq_quantthresh__16u2_p9_0,
  145513. _vq_quantmap__16u2_p9_0,
  145514. 15,
  145515. 15
  145516. };
  145517. static static_codebook _16u2_p9_0 = {
  145518. 2, 225,
  145519. _vq_lengthlist__16u2_p9_0,
  145520. 1, -510275072, 1611661312, 14, 0,
  145521. _vq_quantlist__16u2_p9_0,
  145522. NULL,
  145523. &_vq_auxt__16u2_p9_0,
  145524. NULL,
  145525. 0
  145526. };
  145527. static long _vq_quantlist__16u2_p9_1[] = {
  145528. 392,
  145529. 343,
  145530. 441,
  145531. 294,
  145532. 490,
  145533. 245,
  145534. 539,
  145535. 196,
  145536. 588,
  145537. 147,
  145538. 637,
  145539. 98,
  145540. 686,
  145541. 49,
  145542. 735,
  145543. 0,
  145544. 784,
  145545. 388,
  145546. 396,
  145547. };
  145548. static long _vq_lengthlist__16u2_p9_1[] = {
  145549. 1,12,10,12,10,12,10,12,11,12,12,12,12,12,12,12,
  145550. 12, 5, 5, 9,10,12,11,11,12,12,12,12,12,12,12,12,
  145551. 12,12,12,12,10, 9, 9,11, 9,11,11,12,11,12,12,12,
  145552. 12,12,12,12,12,12,12, 8, 8,10,11, 9,12,11,12,12,
  145553. 12,12,12,12,12,12,12,12,12,12, 9, 8,10,11,12,11,
  145554. 12,11,12,12,12,12,12,12,12,12,12,12,12, 8, 9,11,
  145555. 11,10,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145556. 9,10,11,12,11,12,11,12,12,12,12,12,12,12,12,12,
  145557. 12,12,12, 9, 9,11,12,12,12,12,12,12,12,12,12,12,
  145558. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145559. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145560. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145561. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145562. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  145563. 12,12,12,12,11,11,11,11,11,11,11,11,11,11,11,11,
  145564. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145565. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145566. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145567. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145568. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  145569. 11,11,11, 5, 8, 9, 9, 8,11, 9,11,11,11,11,11,11,
  145570. 11,11,11,11, 5, 5, 4, 8, 8, 8, 8,10, 9,10,10,11,
  145571. 11,11,11,11,11,11,11, 5, 4,
  145572. };
  145573. static float _vq_quantthresh__16u2_p9_1[] = {
  145574. -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5, -26.5,
  145575. -2, 2, 26.5, 73.5, 122.5, 171.5, 220.5, 269.5,
  145576. 318.5, 367.5,
  145577. };
  145578. static long _vq_quantmap__16u2_p9_1[] = {
  145579. 15, 13, 11, 9, 7, 5, 3, 1,
  145580. 17, 0, 18, 2, 4, 6, 8, 10,
  145581. 12, 14, 16,
  145582. };
  145583. static encode_aux_threshmatch _vq_auxt__16u2_p9_1 = {
  145584. _vq_quantthresh__16u2_p9_1,
  145585. _vq_quantmap__16u2_p9_1,
  145586. 19,
  145587. 19
  145588. };
  145589. static static_codebook _16u2_p9_1 = {
  145590. 2, 361,
  145591. _vq_lengthlist__16u2_p9_1,
  145592. 1, -518488064, 1611661312, 10, 0,
  145593. _vq_quantlist__16u2_p9_1,
  145594. NULL,
  145595. &_vq_auxt__16u2_p9_1,
  145596. NULL,
  145597. 0
  145598. };
  145599. static long _vq_quantlist__16u2_p9_2[] = {
  145600. 24,
  145601. 23,
  145602. 25,
  145603. 22,
  145604. 26,
  145605. 21,
  145606. 27,
  145607. 20,
  145608. 28,
  145609. 19,
  145610. 29,
  145611. 18,
  145612. 30,
  145613. 17,
  145614. 31,
  145615. 16,
  145616. 32,
  145617. 15,
  145618. 33,
  145619. 14,
  145620. 34,
  145621. 13,
  145622. 35,
  145623. 12,
  145624. 36,
  145625. 11,
  145626. 37,
  145627. 10,
  145628. 38,
  145629. 9,
  145630. 39,
  145631. 8,
  145632. 40,
  145633. 7,
  145634. 41,
  145635. 6,
  145636. 42,
  145637. 5,
  145638. 43,
  145639. 4,
  145640. 44,
  145641. 3,
  145642. 45,
  145643. 2,
  145644. 46,
  145645. 1,
  145646. 47,
  145647. 0,
  145648. 48,
  145649. };
  145650. static long _vq_lengthlist__16u2_p9_2[] = {
  145651. 1, 3, 3, 4, 7, 7, 7, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  145652. 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 9, 9, 8, 9, 9,
  145653. 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,12,12,10,
  145654. 11,
  145655. };
  145656. static float _vq_quantthresh__16u2_p9_2[] = {
  145657. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  145658. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  145659. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  145660. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  145661. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  145662. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  145663. };
  145664. static long _vq_quantmap__16u2_p9_2[] = {
  145665. 47, 45, 43, 41, 39, 37, 35, 33,
  145666. 31, 29, 27, 25, 23, 21, 19, 17,
  145667. 15, 13, 11, 9, 7, 5, 3, 1,
  145668. 0, 2, 4, 6, 8, 10, 12, 14,
  145669. 16, 18, 20, 22, 24, 26, 28, 30,
  145670. 32, 34, 36, 38, 40, 42, 44, 46,
  145671. 48,
  145672. };
  145673. static encode_aux_threshmatch _vq_auxt__16u2_p9_2 = {
  145674. _vq_quantthresh__16u2_p9_2,
  145675. _vq_quantmap__16u2_p9_2,
  145676. 49,
  145677. 49
  145678. };
  145679. static static_codebook _16u2_p9_2 = {
  145680. 1, 49,
  145681. _vq_lengthlist__16u2_p9_2,
  145682. 1, -526909440, 1611661312, 6, 0,
  145683. _vq_quantlist__16u2_p9_2,
  145684. NULL,
  145685. &_vq_auxt__16u2_p9_2,
  145686. NULL,
  145687. 0
  145688. };
  145689. static long _vq_quantlist__8u0__p1_0[] = {
  145690. 1,
  145691. 0,
  145692. 2,
  145693. };
  145694. static long _vq_lengthlist__8u0__p1_0[] = {
  145695. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  145696. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 4, 9, 8, 8,11,
  145697. 11, 8,11,11, 7,11,11,10,11,13,10,13,13, 7,11,11,
  145698. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 8,11,11, 7,
  145699. 11,11, 9,13,13,10,12,13, 7,11,11,10,13,13,10,13,
  145700. 11,
  145701. };
  145702. static float _vq_quantthresh__8u0__p1_0[] = {
  145703. -0.5, 0.5,
  145704. };
  145705. static long _vq_quantmap__8u0__p1_0[] = {
  145706. 1, 0, 2,
  145707. };
  145708. static encode_aux_threshmatch _vq_auxt__8u0__p1_0 = {
  145709. _vq_quantthresh__8u0__p1_0,
  145710. _vq_quantmap__8u0__p1_0,
  145711. 3,
  145712. 3
  145713. };
  145714. static static_codebook _8u0__p1_0 = {
  145715. 4, 81,
  145716. _vq_lengthlist__8u0__p1_0,
  145717. 1, -535822336, 1611661312, 2, 0,
  145718. _vq_quantlist__8u0__p1_0,
  145719. NULL,
  145720. &_vq_auxt__8u0__p1_0,
  145721. NULL,
  145722. 0
  145723. };
  145724. static long _vq_quantlist__8u0__p2_0[] = {
  145725. 1,
  145726. 0,
  145727. 2,
  145728. };
  145729. static long _vq_lengthlist__8u0__p2_0[] = {
  145730. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 6, 7, 8, 6,
  145731. 7, 8, 5, 7, 7, 6, 8, 8, 7, 9, 7, 5, 7, 7, 7, 9,
  145732. 9, 7, 8, 8, 6, 9, 8, 7, 7,10, 8,10,10, 6, 8, 8,
  145733. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  145734. 8, 8, 8,10,10, 8, 8,10, 6, 8, 9, 8,10,10, 7,10,
  145735. 8,
  145736. };
  145737. static float _vq_quantthresh__8u0__p2_0[] = {
  145738. -0.5, 0.5,
  145739. };
  145740. static long _vq_quantmap__8u0__p2_0[] = {
  145741. 1, 0, 2,
  145742. };
  145743. static encode_aux_threshmatch _vq_auxt__8u0__p2_0 = {
  145744. _vq_quantthresh__8u0__p2_0,
  145745. _vq_quantmap__8u0__p2_0,
  145746. 3,
  145747. 3
  145748. };
  145749. static static_codebook _8u0__p2_0 = {
  145750. 4, 81,
  145751. _vq_lengthlist__8u0__p2_0,
  145752. 1, -535822336, 1611661312, 2, 0,
  145753. _vq_quantlist__8u0__p2_0,
  145754. NULL,
  145755. &_vq_auxt__8u0__p2_0,
  145756. NULL,
  145757. 0
  145758. };
  145759. static long _vq_quantlist__8u0__p3_0[] = {
  145760. 2,
  145761. 1,
  145762. 3,
  145763. 0,
  145764. 4,
  145765. };
  145766. static long _vq_lengthlist__8u0__p3_0[] = {
  145767. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  145768. 10, 9,11,11, 8, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  145769. 10,11,11, 8,10,10,11,11,10,11,11,12,12,10,11,11,
  145770. 12,13, 6, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  145771. 11, 9,10,11,12,12,10,11,11,12,12, 8,11,11,14,13,
  145772. 10,12,11,15,13,10,12,11,14,14,12,13,12,16,14,12,
  145773. 14,12,16,15, 8,11,11,13,14,10,11,12,13,15,10,11,
  145774. 12,13,15,11,12,13,14,15,12,12,14,14,16, 5, 8, 8,
  145775. 11,11, 9,11,11,12,12, 8,10,11,12,12,11,12,12,15,
  145776. 14,11,12,12,14,14, 7,11,10,13,12,10,11,12,13,14,
  145777. 10,12,12,14,13,12,13,13,14,15,12,13,13,15,15, 7,
  145778. 10,11,12,13,10,12,11,14,13,10,12,13,13,15,12,13,
  145779. 12,14,14,11,13,13,15,16, 9,12,12,15,14,11,13,13,
  145780. 15,16,11,13,13,16,16,13,14,15,15,15,12,14,15,17,
  145781. 16, 9,12,12,14,15,11,13,13,15,16,11,13,13,16,18,
  145782. 13,14,14,17,16,13,15,15,17,18, 5, 8, 9,11,11, 8,
  145783. 11,11,12,12, 8,10,11,12,12,11,12,12,14,14,11,12,
  145784. 12,14,15, 7,11,10,12,13,10,12,12,14,13,10,11,12,
  145785. 13,14,11,13,13,15,14,12,13,13,14,15, 7,10,11,13,
  145786. 13,10,12,12,13,14,10,12,12,13,13,11,13,13,16,16,
  145787. 12,13,13,15,14, 9,12,12,16,15,10,13,13,15,15,11,
  145788. 13,13,17,15,12,15,15,18,17,13,14,14,15,16, 9,12,
  145789. 12,15,15,11,13,13,15,16,11,13,13,15,15,12,15,15,
  145790. 16,16,13,15,14,17,15, 7,11,11,15,15,10,13,13,16,
  145791. 15,10,13,13,15,16,14,15,15,17,19,13,15,14,15,18,
  145792. 9,12,12,16,16,11,13,14,17,16,11,13,13,17,16,15,
  145793. 15,16,17,19,13,15,16, 0,18, 9,12,12,16,15,11,14,
  145794. 13,17,17,11,13,14,16,16,15,16,16,19,18,13,15,15,
  145795. 17,19,11,14,14,19,16,12,14,15, 0,18,12,16,15,18,
  145796. 17,15,15,18,16,19,14,15,17,19,19,11,14,14,18,19,
  145797. 13,15,14,19,19,12,16,15,18,17,15,17,15, 0,16,14,
  145798. 17,16,19, 0, 7,11,11,14,14,10,12,12,15,15,10,13,
  145799. 13,16,15,13,15,15,17, 0,14,15,15,16,19, 9,12,12,
  145800. 16,16,11,14,14,16,16,11,13,13,16,16,14,17,16,19,
  145801. 0,14,18,17,17,19, 9,12,12,15,16,11,13,13,15,17,
  145802. 12,14,13,19,16,13,15,15,17,19,15,17,16,17,19,11,
  145803. 14,14,19,16,12,15,15,19,17,13,14,15,17,19,14,16,
  145804. 17,19,19,16,15,16,17,19,11,15,14,16,16,12,15,15,
  145805. 19, 0,12,14,15,19,19,14,16,16, 0,18,15,19,14,18,
  145806. 16,
  145807. };
  145808. static float _vq_quantthresh__8u0__p3_0[] = {
  145809. -1.5, -0.5, 0.5, 1.5,
  145810. };
  145811. static long _vq_quantmap__8u0__p3_0[] = {
  145812. 3, 1, 0, 2, 4,
  145813. };
  145814. static encode_aux_threshmatch _vq_auxt__8u0__p3_0 = {
  145815. _vq_quantthresh__8u0__p3_0,
  145816. _vq_quantmap__8u0__p3_0,
  145817. 5,
  145818. 5
  145819. };
  145820. static static_codebook _8u0__p3_0 = {
  145821. 4, 625,
  145822. _vq_lengthlist__8u0__p3_0,
  145823. 1, -533725184, 1611661312, 3, 0,
  145824. _vq_quantlist__8u0__p3_0,
  145825. NULL,
  145826. &_vq_auxt__8u0__p3_0,
  145827. NULL,
  145828. 0
  145829. };
  145830. static long _vq_quantlist__8u0__p4_0[] = {
  145831. 2,
  145832. 1,
  145833. 3,
  145834. 0,
  145835. 4,
  145836. };
  145837. static long _vq_lengthlist__8u0__p4_0[] = {
  145838. 3, 5, 5, 8, 8, 5, 6, 7, 9, 9, 6, 7, 6, 9, 9, 9,
  145839. 9, 9,10,11, 9, 9, 9,11,10, 6, 7, 7,10,10, 7, 7,
  145840. 8,10,10, 7, 8, 8,10,10,10,10,10,10,11, 9,10,10,
  145841. 11,12, 6, 7, 7,10,10, 7, 8, 8,10,10, 7, 8, 7,10,
  145842. 10, 9,10,10,12,11,10,10,10,11,10, 9,10,10,12,11,
  145843. 10,10,10,13,11, 9,10,10,12,12,11,11,12,12,13,11,
  145844. 11,11,12,13, 9,10,10,12,12,10,10,11,12,12,10,10,
  145845. 11,12,12,11,11,11,13,13,11,12,12,13,13, 5, 7, 7,
  145846. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,11,12,
  145847. 12,10,11,10,12,12, 7, 8, 8,11,11, 7, 8, 9,10,11,
  145848. 8, 9, 9,11,11,11,10,11,10,12,10,11,11,12,13, 7,
  145849. 8, 8,10,11, 8, 9, 8,12,10, 8, 9, 9,11,12,10,11,
  145850. 10,13,11,10,11,11,13,12, 9,11,10,13,12,10,10,11,
  145851. 12,12,10,11,11,13,13,12,10,13,11,14,11,12,12,15,
  145852. 13, 9,11,11,13,13,10,11,11,13,12,10,11,11,12,14,
  145853. 12,13,11,14,12,12,12,12,14,14, 5, 7, 7,10,10, 7,
  145854. 8, 8,10,10, 7, 8, 8,11,10,10,11,11,12,12,10,11,
  145855. 10,12,12, 7, 8, 8,10,11, 8, 9, 9,12,11, 8, 8, 9,
  145856. 10,11,10,11,11,12,13,11,10,11,11,13, 6, 8, 8,10,
  145857. 11, 8, 9, 9,11,11, 7, 9, 7,11,10,10,11,11,12,12,
  145858. 10,11,10,13,10, 9,11,10,13,12,10,12,11,13,13,10,
  145859. 10,11,12,13,11,12,13,15,14,11,11,13,12,13, 9,10,
  145860. 11,12,13,10,11,11,12,13,10,11,10,13,12,12,13,13,
  145861. 13,14,12,12,11,14,11, 8,10,10,12,13,10,11,11,13,
  145862. 13,10,11,10,13,13,12,13,14,15,14,12,12,12,14,13,
  145863. 9,10,10,13,12,10,10,12,13,13,10,11,11,15,12,12,
  145864. 12,13,15,14,12,13,13,15,13, 9,10,11,12,13,10,12,
  145865. 10,13,12,10,11,11,12,13,12,14,12,15,13,12,12,12,
  145866. 15,14,11,12,11,14,13,11,11,12,14,14,12,13,13,14,
  145867. 13,13,11,15,11,15,14,14,14,16,15,11,12,12,13,14,
  145868. 11,13,11,14,14,12,12,13,14,15,12,14,12,15,12,13,
  145869. 15,14,16,15, 8,10,10,12,12,10,10,10,12,13,10,11,
  145870. 11,13,13,12,12,12,13,14,13,13,13,15,15, 9,10,10,
  145871. 12,12,10,11,11,13,12,10,10,11,13,13,12,12,12,14,
  145872. 14,12,12,13,15,14, 9,10,10,13,12,10,10,12,12,13,
  145873. 10,11,10,13,13,12,13,13,14,14,12,13,12,14,13,11,
  145874. 12,12,14,13,12,13,12,14,14,10,12,12,14,14,14,14,
  145875. 14,16,14,13,12,14,12,15,10,12,12,14,15,12,13,13,
  145876. 14,16,11,12,11,15,14,13,14,14,14,15,13,14,11,14,
  145877. 12,
  145878. };
  145879. static float _vq_quantthresh__8u0__p4_0[] = {
  145880. -1.5, -0.5, 0.5, 1.5,
  145881. };
  145882. static long _vq_quantmap__8u0__p4_0[] = {
  145883. 3, 1, 0, 2, 4,
  145884. };
  145885. static encode_aux_threshmatch _vq_auxt__8u0__p4_0 = {
  145886. _vq_quantthresh__8u0__p4_0,
  145887. _vq_quantmap__8u0__p4_0,
  145888. 5,
  145889. 5
  145890. };
  145891. static static_codebook _8u0__p4_0 = {
  145892. 4, 625,
  145893. _vq_lengthlist__8u0__p4_0,
  145894. 1, -533725184, 1611661312, 3, 0,
  145895. _vq_quantlist__8u0__p4_0,
  145896. NULL,
  145897. &_vq_auxt__8u0__p4_0,
  145898. NULL,
  145899. 0
  145900. };
  145901. static long _vq_quantlist__8u0__p5_0[] = {
  145902. 4,
  145903. 3,
  145904. 5,
  145905. 2,
  145906. 6,
  145907. 1,
  145908. 7,
  145909. 0,
  145910. 8,
  145911. };
  145912. static long _vq_lengthlist__8u0__p5_0[] = {
  145913. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 7, 8, 8,
  145914. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 6, 8, 8, 9, 9,
  145915. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 7, 8, 8,
  145916. 9, 9,10,10,12,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  145917. 10,10,11,11,11,12,12,12, 9,10,10,11,11,12,12,12,
  145918. 12,
  145919. };
  145920. static float _vq_quantthresh__8u0__p5_0[] = {
  145921. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  145922. };
  145923. static long _vq_quantmap__8u0__p5_0[] = {
  145924. 7, 5, 3, 1, 0, 2, 4, 6,
  145925. 8,
  145926. };
  145927. static encode_aux_threshmatch _vq_auxt__8u0__p5_0 = {
  145928. _vq_quantthresh__8u0__p5_0,
  145929. _vq_quantmap__8u0__p5_0,
  145930. 9,
  145931. 9
  145932. };
  145933. static static_codebook _8u0__p5_0 = {
  145934. 2, 81,
  145935. _vq_lengthlist__8u0__p5_0,
  145936. 1, -531628032, 1611661312, 4, 0,
  145937. _vq_quantlist__8u0__p5_0,
  145938. NULL,
  145939. &_vq_auxt__8u0__p5_0,
  145940. NULL,
  145941. 0
  145942. };
  145943. static long _vq_quantlist__8u0__p6_0[] = {
  145944. 6,
  145945. 5,
  145946. 7,
  145947. 4,
  145948. 8,
  145949. 3,
  145950. 9,
  145951. 2,
  145952. 10,
  145953. 1,
  145954. 11,
  145955. 0,
  145956. 12,
  145957. };
  145958. static long _vq_lengthlist__8u0__p6_0[] = {
  145959. 1, 4, 4, 7, 7, 9, 9,11,11,12,12,16,16, 3, 6, 6,
  145960. 9, 9,11,11,12,12,13,14,18,16, 3, 6, 7, 9, 9,11,
  145961. 11,13,12,14,14,17,16, 7, 9, 9,11,11,12,12,14,14,
  145962. 14,14,17,16, 7, 9, 9,11,11,13,12,13,13,14,14,17,
  145963. 0, 9,11,11,12,13,14,14,14,13,15,14,17,17, 9,11,
  145964. 11,12,12,14,14,13,14,14,15, 0, 0,11,12,12,15,14,
  145965. 15,14,15,14,15,16,17, 0,11,12,13,13,13,14,14,15,
  145966. 14,15,15, 0, 0,12,14,14,15,15,14,16,15,15,17,16,
  145967. 0,18,13,14,14,15,14,15,14,15,16,17,16, 0, 0,17,
  145968. 17,18, 0,16,18,16, 0, 0, 0,17, 0, 0,16, 0, 0,16,
  145969. 16, 0,15, 0,17, 0, 0, 0, 0,
  145970. };
  145971. static float _vq_quantthresh__8u0__p6_0[] = {
  145972. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  145973. 12.5, 17.5, 22.5, 27.5,
  145974. };
  145975. static long _vq_quantmap__8u0__p6_0[] = {
  145976. 11, 9, 7, 5, 3, 1, 0, 2,
  145977. 4, 6, 8, 10, 12,
  145978. };
  145979. static encode_aux_threshmatch _vq_auxt__8u0__p6_0 = {
  145980. _vq_quantthresh__8u0__p6_0,
  145981. _vq_quantmap__8u0__p6_0,
  145982. 13,
  145983. 13
  145984. };
  145985. static static_codebook _8u0__p6_0 = {
  145986. 2, 169,
  145987. _vq_lengthlist__8u0__p6_0,
  145988. 1, -526516224, 1616117760, 4, 0,
  145989. _vq_quantlist__8u0__p6_0,
  145990. NULL,
  145991. &_vq_auxt__8u0__p6_0,
  145992. NULL,
  145993. 0
  145994. };
  145995. static long _vq_quantlist__8u0__p6_1[] = {
  145996. 2,
  145997. 1,
  145998. 3,
  145999. 0,
  146000. 4,
  146001. };
  146002. static long _vq_lengthlist__8u0__p6_1[] = {
  146003. 1, 4, 4, 6, 6, 4, 6, 5, 7, 7, 4, 5, 6, 7, 7, 6,
  146004. 7, 7, 7, 7, 6, 7, 7, 7, 7,
  146005. };
  146006. static float _vq_quantthresh__8u0__p6_1[] = {
  146007. -1.5, -0.5, 0.5, 1.5,
  146008. };
  146009. static long _vq_quantmap__8u0__p6_1[] = {
  146010. 3, 1, 0, 2, 4,
  146011. };
  146012. static encode_aux_threshmatch _vq_auxt__8u0__p6_1 = {
  146013. _vq_quantthresh__8u0__p6_1,
  146014. _vq_quantmap__8u0__p6_1,
  146015. 5,
  146016. 5
  146017. };
  146018. static static_codebook _8u0__p6_1 = {
  146019. 2, 25,
  146020. _vq_lengthlist__8u0__p6_1,
  146021. 1, -533725184, 1611661312, 3, 0,
  146022. _vq_quantlist__8u0__p6_1,
  146023. NULL,
  146024. &_vq_auxt__8u0__p6_1,
  146025. NULL,
  146026. 0
  146027. };
  146028. static long _vq_quantlist__8u0__p7_0[] = {
  146029. 1,
  146030. 0,
  146031. 2,
  146032. };
  146033. static long _vq_lengthlist__8u0__p7_0[] = {
  146034. 1, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146035. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146036. 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146037. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146038. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  146039. 7,
  146040. };
  146041. static float _vq_quantthresh__8u0__p7_0[] = {
  146042. -157.5, 157.5,
  146043. };
  146044. static long _vq_quantmap__8u0__p7_0[] = {
  146045. 1, 0, 2,
  146046. };
  146047. static encode_aux_threshmatch _vq_auxt__8u0__p7_0 = {
  146048. _vq_quantthresh__8u0__p7_0,
  146049. _vq_quantmap__8u0__p7_0,
  146050. 3,
  146051. 3
  146052. };
  146053. static static_codebook _8u0__p7_0 = {
  146054. 4, 81,
  146055. _vq_lengthlist__8u0__p7_0,
  146056. 1, -518803456, 1628680192, 2, 0,
  146057. _vq_quantlist__8u0__p7_0,
  146058. NULL,
  146059. &_vq_auxt__8u0__p7_0,
  146060. NULL,
  146061. 0
  146062. };
  146063. static long _vq_quantlist__8u0__p7_1[] = {
  146064. 7,
  146065. 6,
  146066. 8,
  146067. 5,
  146068. 9,
  146069. 4,
  146070. 10,
  146071. 3,
  146072. 11,
  146073. 2,
  146074. 12,
  146075. 1,
  146076. 13,
  146077. 0,
  146078. 14,
  146079. };
  146080. static long _vq_lengthlist__8u0__p7_1[] = {
  146081. 1, 5, 5, 5, 5,10,10,11,11,11,11,11,11,11,11, 5,
  146082. 7, 6, 8, 8, 9,10,11,11,11,11,11,11,11,11, 6, 6,
  146083. 7, 9, 7,11,10,11,11,11,11,11,11,11,11, 5, 6, 6,
  146084. 11, 8,11,11,11,11,11,11,11,11,11,11, 5, 6, 6, 9,
  146085. 10,11,10,11,11,11,11,11,11,11,11, 7,10,10,11,11,
  146086. 11,11,11,11,11,11,11,11,11,11, 7,11, 8,11,11,11,
  146087. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146088. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146089. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146090. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146091. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146092. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146093. 11,11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,
  146094. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146095. 10,
  146096. };
  146097. static float _vq_quantthresh__8u0__p7_1[] = {
  146098. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  146099. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  146100. };
  146101. static long _vq_quantmap__8u0__p7_1[] = {
  146102. 13, 11, 9, 7, 5, 3, 1, 0,
  146103. 2, 4, 6, 8, 10, 12, 14,
  146104. };
  146105. static encode_aux_threshmatch _vq_auxt__8u0__p7_1 = {
  146106. _vq_quantthresh__8u0__p7_1,
  146107. _vq_quantmap__8u0__p7_1,
  146108. 15,
  146109. 15
  146110. };
  146111. static static_codebook _8u0__p7_1 = {
  146112. 2, 225,
  146113. _vq_lengthlist__8u0__p7_1,
  146114. 1, -520986624, 1620377600, 4, 0,
  146115. _vq_quantlist__8u0__p7_1,
  146116. NULL,
  146117. &_vq_auxt__8u0__p7_1,
  146118. NULL,
  146119. 0
  146120. };
  146121. static long _vq_quantlist__8u0__p7_2[] = {
  146122. 10,
  146123. 9,
  146124. 11,
  146125. 8,
  146126. 12,
  146127. 7,
  146128. 13,
  146129. 6,
  146130. 14,
  146131. 5,
  146132. 15,
  146133. 4,
  146134. 16,
  146135. 3,
  146136. 17,
  146137. 2,
  146138. 18,
  146139. 1,
  146140. 19,
  146141. 0,
  146142. 20,
  146143. };
  146144. static long _vq_lengthlist__8u0__p7_2[] = {
  146145. 1, 6, 5, 7, 7, 9, 9, 9, 9,10,12,12,10,11,11,10,
  146146. 11,11,11,10,11, 6, 8, 8, 9, 9,10,10, 9,10,11,11,
  146147. 10,11,11,11,11,10,11,11,11,11, 6, 7, 8, 9, 9, 9,
  146148. 10,11,10,11,12,11,10,11,11,11,11,11,11,12,10, 8,
  146149. 9, 9,10, 9,10,10, 9,10,10,10,10,10, 9,10,10,10,
  146150. 10, 9,10,10, 9, 9, 9, 9,10,10, 9, 9,10,10,11,10,
  146151. 9,12,10,11,10, 9,10,10,10, 8, 9, 9,10, 9,10, 9,
  146152. 9,10,10, 9,10, 9,11,10,10,10,10,10, 9,10, 8, 8,
  146153. 9, 9,10, 9,11, 9, 8, 9, 9,10,11,10,10,10,11,12,
  146154. 9, 9,11, 8, 9, 8,11,10,11,10,10, 9,11,10,10,10,
  146155. 10,10,10,10,11,11,11,11, 8, 9, 9, 9,10,10,10,11,
  146156. 11,12,11,12,11,10,10,10,12,11,11,11,10, 8,10, 9,
  146157. 11,10,10,11,12,10,11,12,11,11,12,11,12,12,10,11,
  146158. 11,10, 9, 9,10,11,12,10,10,10,11,10,11,11,10,12,
  146159. 12,10,11,10,11,12,10, 9,10,10,11,10,11,11,11,11,
  146160. 11,12,11,11,11, 9,11,10,11,10,11,10, 9, 9,10,11,
  146161. 11,11,10,10,11,12,12,11,12,11,11,11,12,12,12,12,
  146162. 11, 9,11,11,12,10,11,11,11,11,11,11,12,11,11,12,
  146163. 11,11,11,10,11,11, 9,11,10,11,11,11,10,10,10,11,
  146164. 11,11,12,10,11,10,11,11,11,11,12, 9,11,10,11,11,
  146165. 10,10,11,11, 9,11,11,12,10,10,10,10,10,11,11,10,
  146166. 9,10,11,11,12,11,10,10,12,11,11,12,11,12,11,11,
  146167. 10,10,11,11,10,12,11,10,11,10,11,10,10,10,11,11,
  146168. 10,10,11,11,11,11,10,10,10,12,11,11,11,11,10, 9,
  146169. 10,11,11,11,12,11,11,11,12,10,11,11,11, 9,10,11,
  146170. 11,11,11,11,11,10,10,11,11,12,11,10,11,12,11,10,
  146171. 10,11, 9,10,11,11,11,11,11,10,11,11,10,12,11,11,
  146172. 11,12,11,11,11,10,10,11,11,
  146173. };
  146174. static float _vq_quantthresh__8u0__p7_2[] = {
  146175. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  146176. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  146177. 6.5, 7.5, 8.5, 9.5,
  146178. };
  146179. static long _vq_quantmap__8u0__p7_2[] = {
  146180. 19, 17, 15, 13, 11, 9, 7, 5,
  146181. 3, 1, 0, 2, 4, 6, 8, 10,
  146182. 12, 14, 16, 18, 20,
  146183. };
  146184. static encode_aux_threshmatch _vq_auxt__8u0__p7_2 = {
  146185. _vq_quantthresh__8u0__p7_2,
  146186. _vq_quantmap__8u0__p7_2,
  146187. 21,
  146188. 21
  146189. };
  146190. static static_codebook _8u0__p7_2 = {
  146191. 2, 441,
  146192. _vq_lengthlist__8u0__p7_2,
  146193. 1, -529268736, 1611661312, 5, 0,
  146194. _vq_quantlist__8u0__p7_2,
  146195. NULL,
  146196. &_vq_auxt__8u0__p7_2,
  146197. NULL,
  146198. 0
  146199. };
  146200. static long _huff_lengthlist__8u0__single[] = {
  146201. 4, 7,11, 9,12, 8, 7,10, 6, 4, 5, 5, 7, 5, 6,16,
  146202. 9, 5, 5, 6, 7, 7, 9,16, 7, 4, 6, 5, 7, 5, 7,17,
  146203. 10, 7, 7, 8, 7, 7, 8,18, 7, 5, 6, 4, 5, 4, 5,15,
  146204. 7, 6, 7, 5, 6, 4, 5,15,12,13,18,12,17,11, 9,17,
  146205. };
  146206. static static_codebook _huff_book__8u0__single = {
  146207. 2, 64,
  146208. _huff_lengthlist__8u0__single,
  146209. 0, 0, 0, 0, 0,
  146210. NULL,
  146211. NULL,
  146212. NULL,
  146213. NULL,
  146214. 0
  146215. };
  146216. static long _vq_quantlist__8u1__p1_0[] = {
  146217. 1,
  146218. 0,
  146219. 2,
  146220. };
  146221. static long _vq_lengthlist__8u1__p1_0[] = {
  146222. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 7, 9,10, 7,
  146223. 9, 9, 5, 8, 8, 7,10, 9, 7, 9, 9, 5, 8, 8, 8,10,
  146224. 10, 8,10,10, 7,10,10, 9,10,12,10,12,12, 7,10,10,
  146225. 9,12,11,10,12,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  146226. 10,10,10,12,12, 9,11,12, 7,10,10,10,12,12, 9,12,
  146227. 10,
  146228. };
  146229. static float _vq_quantthresh__8u1__p1_0[] = {
  146230. -0.5, 0.5,
  146231. };
  146232. static long _vq_quantmap__8u1__p1_0[] = {
  146233. 1, 0, 2,
  146234. };
  146235. static encode_aux_threshmatch _vq_auxt__8u1__p1_0 = {
  146236. _vq_quantthresh__8u1__p1_0,
  146237. _vq_quantmap__8u1__p1_0,
  146238. 3,
  146239. 3
  146240. };
  146241. static static_codebook _8u1__p1_0 = {
  146242. 4, 81,
  146243. _vq_lengthlist__8u1__p1_0,
  146244. 1, -535822336, 1611661312, 2, 0,
  146245. _vq_quantlist__8u1__p1_0,
  146246. NULL,
  146247. &_vq_auxt__8u1__p1_0,
  146248. NULL,
  146249. 0
  146250. };
  146251. static long _vq_quantlist__8u1__p2_0[] = {
  146252. 1,
  146253. 0,
  146254. 2,
  146255. };
  146256. static long _vq_lengthlist__8u1__p2_0[] = {
  146257. 3, 4, 5, 5, 6, 6, 5, 6, 6, 5, 7, 6, 6, 7, 8, 6,
  146258. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 7, 5, 6, 6, 7, 8,
  146259. 8, 6, 7, 7, 6, 8, 7, 7, 7, 9, 8, 9, 9, 6, 7, 8,
  146260. 7, 9, 7, 8, 9, 9, 5, 6, 6, 6, 7, 7, 7, 8, 8, 6,
  146261. 8, 7, 8, 9, 9, 7, 7, 9, 6, 7, 8, 8, 9, 9, 7, 9,
  146262. 7,
  146263. };
  146264. static float _vq_quantthresh__8u1__p2_0[] = {
  146265. -0.5, 0.5,
  146266. };
  146267. static long _vq_quantmap__8u1__p2_0[] = {
  146268. 1, 0, 2,
  146269. };
  146270. static encode_aux_threshmatch _vq_auxt__8u1__p2_0 = {
  146271. _vq_quantthresh__8u1__p2_0,
  146272. _vq_quantmap__8u1__p2_0,
  146273. 3,
  146274. 3
  146275. };
  146276. static static_codebook _8u1__p2_0 = {
  146277. 4, 81,
  146278. _vq_lengthlist__8u1__p2_0,
  146279. 1, -535822336, 1611661312, 2, 0,
  146280. _vq_quantlist__8u1__p2_0,
  146281. NULL,
  146282. &_vq_auxt__8u1__p2_0,
  146283. NULL,
  146284. 0
  146285. };
  146286. static long _vq_quantlist__8u1__p3_0[] = {
  146287. 2,
  146288. 1,
  146289. 3,
  146290. 0,
  146291. 4,
  146292. };
  146293. static long _vq_lengthlist__8u1__p3_0[] = {
  146294. 1, 5, 5, 7, 7, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  146295. 10, 9,11,11, 9, 9, 9,11,11, 6, 8, 8,10,10, 8,10,
  146296. 10,11,11, 8, 9,10,11,11,10,11,11,12,12,10,11,11,
  146297. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10, 9,11,
  146298. 11,10,11,11,12,12,10,11,11,12,12, 9,11,11,14,13,
  146299. 10,12,11,14,14,10,12,11,14,13,12,13,13,15,14,12,
  146300. 13,13,15,14, 8,11,11,13,14,10,11,12,13,15,10,11,
  146301. 12,14,14,12,13,13,14,15,12,13,13,14,15, 5, 8, 8,
  146302. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  146303. 13,11,12,12,13,14, 8,10,10,12,12, 9,11,12,13,14,
  146304. 10,12,12,13,13,12,12,13,14,14,11,13,13,15,15, 7,
  146305. 10,10,12,12, 9,12,11,14,12,10,11,12,13,14,12,13,
  146306. 12,14,14,12,13,13,15,16,10,12,12,15,14,11,12,13,
  146307. 15,15,11,13,13,15,16,14,14,15,15,16,13,14,15,17,
  146308. 15, 9,12,12,14,15,11,13,12,15,15,11,13,13,15,15,
  146309. 13,14,13,15,14,13,14,14,17, 0, 5, 8, 8,11,11, 8,
  146310. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  146311. 12,14,14, 7,10,10,12,12,10,12,12,13,13, 9,11,12,
  146312. 12,13,11,12,13,15,15,11,12,13,14,15, 8,10,10,12,
  146313. 12,10,12,11,13,13,10,12,11,13,13,11,13,13,15,14,
  146314. 12,13,12,15,13, 9,12,12,14,14,11,13,13,16,15,11,
  146315. 12,13,16,15,13,14,15,16,16,13,13,15,15,16,10,12,
  146316. 12,15,14,11,13,13,14,16,11,13,13,15,16,13,15,15,
  146317. 16,17,13,15,14,16,15, 8,11,11,14,15,10,12,12,15,
  146318. 15,10,12,12,15,16,14,15,15,16,17,13,14,14,16,16,
  146319. 9,12,12,15,15,11,13,14,15,17,11,13,13,15,16,14,
  146320. 15,16,19,17,13,15,15, 0,17, 9,12,12,15,15,11,14,
  146321. 13,16,15,11,13,13,15,16,15,15,15,18,17,13,15,15,
  146322. 17,17,11,15,14,18,16,12,14,15,17,17,12,15,15,18,
  146323. 18,15,15,16,15,19,14,16,16, 0, 0,11,14,14,16,17,
  146324. 12,15,14,18,17,12,15,15,18,18,15,17,15,18,16,14,
  146325. 16,16,18,18, 7,11,11,14,14,10,12,12,15,15,10,12,
  146326. 13,15,15,13,14,15,16,16,14,15,15,18,18, 9,12,12,
  146327. 15,15,11,13,13,16,15,11,12,13,16,16,14,15,15,17,
  146328. 16,15,16,16,17,17, 9,12,12,15,15,11,13,13,15,17,
  146329. 11,14,13,16,15,13,15,15,17,17,15,15,15,18,17,11,
  146330. 14,14,17,15,12,14,15,17,18,13,13,15,17,17,14,16,
  146331. 16,19,18,16,15,17,17, 0,11,14,14,17,17,12,15,15,
  146332. 18, 0,12,15,14,18,16,14,17,17,19, 0,16,18,15, 0,
  146333. 16,
  146334. };
  146335. static float _vq_quantthresh__8u1__p3_0[] = {
  146336. -1.5, -0.5, 0.5, 1.5,
  146337. };
  146338. static long _vq_quantmap__8u1__p3_0[] = {
  146339. 3, 1, 0, 2, 4,
  146340. };
  146341. static encode_aux_threshmatch _vq_auxt__8u1__p3_0 = {
  146342. _vq_quantthresh__8u1__p3_0,
  146343. _vq_quantmap__8u1__p3_0,
  146344. 5,
  146345. 5
  146346. };
  146347. static static_codebook _8u1__p3_0 = {
  146348. 4, 625,
  146349. _vq_lengthlist__8u1__p3_0,
  146350. 1, -533725184, 1611661312, 3, 0,
  146351. _vq_quantlist__8u1__p3_0,
  146352. NULL,
  146353. &_vq_auxt__8u1__p3_0,
  146354. NULL,
  146355. 0
  146356. };
  146357. static long _vq_quantlist__8u1__p4_0[] = {
  146358. 2,
  146359. 1,
  146360. 3,
  146361. 0,
  146362. 4,
  146363. };
  146364. static long _vq_lengthlist__8u1__p4_0[] = {
  146365. 4, 5, 5, 9, 9, 6, 7, 7, 9, 9, 6, 7, 7, 9, 9, 9,
  146366. 9, 9,11,11, 9, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 7,
  146367. 8, 9,10, 7, 7, 8, 9,10, 9, 9,10,10,11, 9, 9,10,
  146368. 10,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 7,10,
  146369. 9, 9,10, 9,12,11,10,10, 9,12,10, 9,10,10,12,11,
  146370. 9,10,10,12,11, 9,10,10,12,12,11,11,12,12,13,11,
  146371. 11,12,12,13, 9, 9,10,12,11, 9,10,10,12,12,10,10,
  146372. 10,12,12,11,12,11,13,12,11,12,11,13,12, 6, 7, 7,
  146373. 9, 9, 7, 8, 8,10,10, 7, 8, 7,10, 9,10,10,10,12,
  146374. 12,10,10,10,12,11, 7, 8, 7,10,10, 7, 7, 9,10,11,
  146375. 8, 9, 9,11,10,10,10,11,10,12,10,10,11,12,12, 7,
  146376. 8, 8,10,10, 7, 9, 8,11,10, 8, 8, 9,11,11,10,11,
  146377. 10,12,11,10,11,11,12,12, 9,10,10,12,12, 9,10,10,
  146378. 12,12,10,11,11,13,12,11,10,12,10,14,12,12,12,13,
  146379. 14, 9,10,10,12,12, 9,11,10,12,12,10,11,11,12,12,
  146380. 11,12,11,14,12,12,12,12,14,14, 5, 7, 7, 9, 9, 7,
  146381. 7, 7, 9,10, 7, 8, 8,10,10,10,10,10,11,11,10,10,
  146382. 10,12,12, 7, 8, 8,10,10, 8, 9, 8,11,10, 7, 8, 9,
  146383. 10,11,10,10,10,11,12,10,10,11,11,13, 6, 7, 8,10,
  146384. 10, 8, 9, 9,10,10, 7, 9, 7,11,10,10,11,10,12,12,
  146385. 10,11,10,12,10, 9,10,10,12,12,10,11,11,13,12, 9,
  146386. 10,10,12,12,12,12,12,14,13,11,11,12,11,14, 9,10,
  146387. 10,11,12,10,11,11,12,13, 9,10,10,12,12,12,12,12,
  146388. 14,13,11,12,10,14,11, 9, 9,10,11,12, 9,10,10,12,
  146389. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,13,12,
  146390. 9,10, 9,12,12, 9,10,11,12,13,10,11,10,13,11,12,
  146391. 12,13,13,14,12,12,12,13,13, 9,10,10,12,12,10,11,
  146392. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,12,
  146393. 13,14,11,12,11,14,13,10,10,11,13,13,12,12,12,14,
  146394. 13,12,10,14,10,15,13,14,14,14,14,11,11,12,13,14,
  146395. 10,12,11,13,13,12,12,12,13,15,12,13,11,15,12,13,
  146396. 13,14,14,14, 9,10, 9,12,12, 9,10,10,12,12,10,10,
  146397. 10,12,12,11,11,12,12,13,12,12,12,14,14, 9,10,10,
  146398. 12,12,10,11,10,13,12,10,10,11,12,13,12,12,12,14,
  146399. 13,12,12,13,13,14, 9,10,10,12,13,10,10,11,11,12,
  146400. 9,11,10,13,12,12,12,12,13,14,12,13,12,14,13,11,
  146401. 12,11,13,13,12,13,12,14,13,10,11,12,13,13,13,13,
  146402. 13,14,15,12,11,14,12,14,11,11,12,12,13,12,12,12,
  146403. 13,14,10,12,10,14,13,13,13,13,14,15,12,14,11,15,
  146404. 10,
  146405. };
  146406. static float _vq_quantthresh__8u1__p4_0[] = {
  146407. -1.5, -0.5, 0.5, 1.5,
  146408. };
  146409. static long _vq_quantmap__8u1__p4_0[] = {
  146410. 3, 1, 0, 2, 4,
  146411. };
  146412. static encode_aux_threshmatch _vq_auxt__8u1__p4_0 = {
  146413. _vq_quantthresh__8u1__p4_0,
  146414. _vq_quantmap__8u1__p4_0,
  146415. 5,
  146416. 5
  146417. };
  146418. static static_codebook _8u1__p4_0 = {
  146419. 4, 625,
  146420. _vq_lengthlist__8u1__p4_0,
  146421. 1, -533725184, 1611661312, 3, 0,
  146422. _vq_quantlist__8u1__p4_0,
  146423. NULL,
  146424. &_vq_auxt__8u1__p4_0,
  146425. NULL,
  146426. 0
  146427. };
  146428. static long _vq_quantlist__8u1__p5_0[] = {
  146429. 4,
  146430. 3,
  146431. 5,
  146432. 2,
  146433. 6,
  146434. 1,
  146435. 7,
  146436. 0,
  146437. 8,
  146438. };
  146439. static long _vq_lengthlist__8u1__p5_0[] = {
  146440. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  146441. 10,10, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  146442. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  146443. 9, 9,10,10,12,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  146444. 10,10,11,11,11,11,13,12, 9,10,10,11,11,12,12,12,
  146445. 13,
  146446. };
  146447. static float _vq_quantthresh__8u1__p5_0[] = {
  146448. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146449. };
  146450. static long _vq_quantmap__8u1__p5_0[] = {
  146451. 7, 5, 3, 1, 0, 2, 4, 6,
  146452. 8,
  146453. };
  146454. static encode_aux_threshmatch _vq_auxt__8u1__p5_0 = {
  146455. _vq_quantthresh__8u1__p5_0,
  146456. _vq_quantmap__8u1__p5_0,
  146457. 9,
  146458. 9
  146459. };
  146460. static static_codebook _8u1__p5_0 = {
  146461. 2, 81,
  146462. _vq_lengthlist__8u1__p5_0,
  146463. 1, -531628032, 1611661312, 4, 0,
  146464. _vq_quantlist__8u1__p5_0,
  146465. NULL,
  146466. &_vq_auxt__8u1__p5_0,
  146467. NULL,
  146468. 0
  146469. };
  146470. static long _vq_quantlist__8u1__p6_0[] = {
  146471. 4,
  146472. 3,
  146473. 5,
  146474. 2,
  146475. 6,
  146476. 1,
  146477. 7,
  146478. 0,
  146479. 8,
  146480. };
  146481. static long _vq_lengthlist__8u1__p6_0[] = {
  146482. 3, 4, 4, 6, 6, 7, 7, 9, 9, 4, 4, 5, 6, 6, 7, 7,
  146483. 9, 9, 4, 4, 4, 6, 6, 7, 7, 9, 9, 6, 6, 6, 7, 7,
  146484. 8, 8, 9, 9, 6, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  146485. 8, 8, 8, 9,10,10, 7, 7, 7, 8, 8, 9, 8,10,10, 9,
  146486. 9, 9, 9, 9,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146487. 10,
  146488. };
  146489. static float _vq_quantthresh__8u1__p6_0[] = {
  146490. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  146491. };
  146492. static long _vq_quantmap__8u1__p6_0[] = {
  146493. 7, 5, 3, 1, 0, 2, 4, 6,
  146494. 8,
  146495. };
  146496. static encode_aux_threshmatch _vq_auxt__8u1__p6_0 = {
  146497. _vq_quantthresh__8u1__p6_0,
  146498. _vq_quantmap__8u1__p6_0,
  146499. 9,
  146500. 9
  146501. };
  146502. static static_codebook _8u1__p6_0 = {
  146503. 2, 81,
  146504. _vq_lengthlist__8u1__p6_0,
  146505. 1, -531628032, 1611661312, 4, 0,
  146506. _vq_quantlist__8u1__p6_0,
  146507. NULL,
  146508. &_vq_auxt__8u1__p6_0,
  146509. NULL,
  146510. 0
  146511. };
  146512. static long _vq_quantlist__8u1__p7_0[] = {
  146513. 1,
  146514. 0,
  146515. 2,
  146516. };
  146517. static long _vq_lengthlist__8u1__p7_0[] = {
  146518. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,10,10, 8,
  146519. 10,10, 5, 9, 9, 7,10,10, 8,10,10, 4,10,10, 9,12,
  146520. 12, 9,11,11, 7,12,11,10,11,13,10,13,13, 7,12,12,
  146521. 10,13,12,10,13,13, 4,10,10, 9,12,12, 9,12,12, 7,
  146522. 12,12,10,13,13,10,12,13, 7,11,12,10,13,13,10,13,
  146523. 11,
  146524. };
  146525. static float _vq_quantthresh__8u1__p7_0[] = {
  146526. -5.5, 5.5,
  146527. };
  146528. static long _vq_quantmap__8u1__p7_0[] = {
  146529. 1, 0, 2,
  146530. };
  146531. static encode_aux_threshmatch _vq_auxt__8u1__p7_0 = {
  146532. _vq_quantthresh__8u1__p7_0,
  146533. _vq_quantmap__8u1__p7_0,
  146534. 3,
  146535. 3
  146536. };
  146537. static static_codebook _8u1__p7_0 = {
  146538. 4, 81,
  146539. _vq_lengthlist__8u1__p7_0,
  146540. 1, -529137664, 1618345984, 2, 0,
  146541. _vq_quantlist__8u1__p7_0,
  146542. NULL,
  146543. &_vq_auxt__8u1__p7_0,
  146544. NULL,
  146545. 0
  146546. };
  146547. static long _vq_quantlist__8u1__p7_1[] = {
  146548. 5,
  146549. 4,
  146550. 6,
  146551. 3,
  146552. 7,
  146553. 2,
  146554. 8,
  146555. 1,
  146556. 9,
  146557. 0,
  146558. 10,
  146559. };
  146560. static long _vq_lengthlist__8u1__p7_1[] = {
  146561. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  146562. 8, 8, 9, 9, 9, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 9,
  146563. 9, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  146564. 8, 8, 8, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146565. 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  146566. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  146567. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  146568. 9, 9, 9, 9, 9,10,10,10,10,
  146569. };
  146570. static float _vq_quantthresh__8u1__p7_1[] = {
  146571. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146572. 3.5, 4.5,
  146573. };
  146574. static long _vq_quantmap__8u1__p7_1[] = {
  146575. 9, 7, 5, 3, 1, 0, 2, 4,
  146576. 6, 8, 10,
  146577. };
  146578. static encode_aux_threshmatch _vq_auxt__8u1__p7_1 = {
  146579. _vq_quantthresh__8u1__p7_1,
  146580. _vq_quantmap__8u1__p7_1,
  146581. 11,
  146582. 11
  146583. };
  146584. static static_codebook _8u1__p7_1 = {
  146585. 2, 121,
  146586. _vq_lengthlist__8u1__p7_1,
  146587. 1, -531365888, 1611661312, 4, 0,
  146588. _vq_quantlist__8u1__p7_1,
  146589. NULL,
  146590. &_vq_auxt__8u1__p7_1,
  146591. NULL,
  146592. 0
  146593. };
  146594. static long _vq_quantlist__8u1__p8_0[] = {
  146595. 5,
  146596. 4,
  146597. 6,
  146598. 3,
  146599. 7,
  146600. 2,
  146601. 8,
  146602. 1,
  146603. 9,
  146604. 0,
  146605. 10,
  146606. };
  146607. static long _vq_lengthlist__8u1__p8_0[] = {
  146608. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  146609. 9, 9,11,11,13,12, 4, 6, 6, 7, 7, 9, 9,11,11,12,
  146610. 12, 6, 7, 7, 9, 9,11,11,12,12,13,13, 6, 7, 7, 9,
  146611. 9,11,11,12,12,13,13, 8, 9, 9,11,11,12,12,13,13,
  146612. 14,14, 8, 9, 9,11,11,12,12,13,13,14,14, 9,11,11,
  146613. 12,12,13,13,14,14,15,15, 9,11,11,12,12,13,13,14,
  146614. 14,15,14,11,12,12,13,13,14,14,15,15,16,16,11,12,
  146615. 12,13,13,14,14,15,15,15,15,
  146616. };
  146617. static float _vq_quantthresh__8u1__p8_0[] = {
  146618. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  146619. 38.5, 49.5,
  146620. };
  146621. static long _vq_quantmap__8u1__p8_0[] = {
  146622. 9, 7, 5, 3, 1, 0, 2, 4,
  146623. 6, 8, 10,
  146624. };
  146625. static encode_aux_threshmatch _vq_auxt__8u1__p8_0 = {
  146626. _vq_quantthresh__8u1__p8_0,
  146627. _vq_quantmap__8u1__p8_0,
  146628. 11,
  146629. 11
  146630. };
  146631. static static_codebook _8u1__p8_0 = {
  146632. 2, 121,
  146633. _vq_lengthlist__8u1__p8_0,
  146634. 1, -524582912, 1618345984, 4, 0,
  146635. _vq_quantlist__8u1__p8_0,
  146636. NULL,
  146637. &_vq_auxt__8u1__p8_0,
  146638. NULL,
  146639. 0
  146640. };
  146641. static long _vq_quantlist__8u1__p8_1[] = {
  146642. 5,
  146643. 4,
  146644. 6,
  146645. 3,
  146646. 7,
  146647. 2,
  146648. 8,
  146649. 1,
  146650. 9,
  146651. 0,
  146652. 10,
  146653. };
  146654. static long _vq_lengthlist__8u1__p8_1[] = {
  146655. 2, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 6, 6, 7, 7,
  146656. 7, 7, 8, 8, 8, 8, 5, 6, 6, 7, 7, 7, 7, 8, 8, 8,
  146657. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  146658. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  146659. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  146660. 8, 8, 8, 8, 9, 8, 9, 9, 7, 8, 8, 8, 8, 8, 8, 9,
  146661. 8, 9, 9, 8, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8,
  146662. 8, 8, 8, 8, 8, 9, 9, 9, 9,
  146663. };
  146664. static float _vq_quantthresh__8u1__p8_1[] = {
  146665. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  146666. 3.5, 4.5,
  146667. };
  146668. static long _vq_quantmap__8u1__p8_1[] = {
  146669. 9, 7, 5, 3, 1, 0, 2, 4,
  146670. 6, 8, 10,
  146671. };
  146672. static encode_aux_threshmatch _vq_auxt__8u1__p8_1 = {
  146673. _vq_quantthresh__8u1__p8_1,
  146674. _vq_quantmap__8u1__p8_1,
  146675. 11,
  146676. 11
  146677. };
  146678. static static_codebook _8u1__p8_1 = {
  146679. 2, 121,
  146680. _vq_lengthlist__8u1__p8_1,
  146681. 1, -531365888, 1611661312, 4, 0,
  146682. _vq_quantlist__8u1__p8_1,
  146683. NULL,
  146684. &_vq_auxt__8u1__p8_1,
  146685. NULL,
  146686. 0
  146687. };
  146688. static long _vq_quantlist__8u1__p9_0[] = {
  146689. 7,
  146690. 6,
  146691. 8,
  146692. 5,
  146693. 9,
  146694. 4,
  146695. 10,
  146696. 3,
  146697. 11,
  146698. 2,
  146699. 12,
  146700. 1,
  146701. 13,
  146702. 0,
  146703. 14,
  146704. };
  146705. static long _vq_lengthlist__8u1__p9_0[] = {
  146706. 1, 4, 4,11,11,11,11,11,11,11,11,11,11,11,11, 3,
  146707. 11, 8,11,11,11,11,11,11,11,11,11,11,11,11, 3, 9,
  146708. 9,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146709. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146710. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146711. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146712. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146713. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146714. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146715. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146716. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146717. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  146718. 11,11,11,11,11,11,11,11,11,11,10,10,10,10,10,10,
  146719. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146720. 10,
  146721. };
  146722. static float _vq_quantthresh__8u1__p9_0[] = {
  146723. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  146724. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  146725. };
  146726. static long _vq_quantmap__8u1__p9_0[] = {
  146727. 13, 11, 9, 7, 5, 3, 1, 0,
  146728. 2, 4, 6, 8, 10, 12, 14,
  146729. };
  146730. static encode_aux_threshmatch _vq_auxt__8u1__p9_0 = {
  146731. _vq_quantthresh__8u1__p9_0,
  146732. _vq_quantmap__8u1__p9_0,
  146733. 15,
  146734. 15
  146735. };
  146736. static static_codebook _8u1__p9_0 = {
  146737. 2, 225,
  146738. _vq_lengthlist__8u1__p9_0,
  146739. 1, -514071552, 1627381760, 4, 0,
  146740. _vq_quantlist__8u1__p9_0,
  146741. NULL,
  146742. &_vq_auxt__8u1__p9_0,
  146743. NULL,
  146744. 0
  146745. };
  146746. static long _vq_quantlist__8u1__p9_1[] = {
  146747. 7,
  146748. 6,
  146749. 8,
  146750. 5,
  146751. 9,
  146752. 4,
  146753. 10,
  146754. 3,
  146755. 11,
  146756. 2,
  146757. 12,
  146758. 1,
  146759. 13,
  146760. 0,
  146761. 14,
  146762. };
  146763. static long _vq_lengthlist__8u1__p9_1[] = {
  146764. 1, 4, 4, 7, 7, 9, 9, 7, 7, 8, 8,10,10,11,11, 4,
  146765. 7, 7, 9, 9,10,10, 8, 8,10,10,10,11,10,11, 4, 7,
  146766. 7, 9, 9,10,10, 8, 8,10, 9,11,11,11,11, 7, 9, 9,
  146767. 12,12,11,12,10,10,11,10,12,11,11,11, 7, 9, 9,11,
  146768. 11,13,12, 9, 9,11,10,11,11,12,11, 9,10,10,12,12,
  146769. 14,14,10,10,11,12,12,11,11,11, 9,10,11,11,13,14,
  146770. 13,10,11,11,11,12,11,12,12, 7, 8, 8,10, 9,11,10,
  146771. 11,12,12,11,12,14,12,13, 7, 8, 8, 9,10,10,11,12,
  146772. 12,12,11,12,12,12,13, 9, 9, 9,11,11,13,12,12,12,
  146773. 12,11,12,12,13,12, 8,10,10,11,10,11,12,12,12,12,
  146774. 12,12,14,12,12, 9,11,11,11,12,12,12,12,13,13,12,
  146775. 12,13,13,12,10,11,11,12,11,12,12,12,11,12,13,12,
  146776. 12,12,13,11,11,12,12,12,13,12,12,11,12,13,13,12,
  146777. 12,13,12,11,12,12,13,13,12,13,12,13,13,13,13,14,
  146778. 13,
  146779. };
  146780. static float _vq_quantthresh__8u1__p9_1[] = {
  146781. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  146782. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  146783. };
  146784. static long _vq_quantmap__8u1__p9_1[] = {
  146785. 13, 11, 9, 7, 5, 3, 1, 0,
  146786. 2, 4, 6, 8, 10, 12, 14,
  146787. };
  146788. static encode_aux_threshmatch _vq_auxt__8u1__p9_1 = {
  146789. _vq_quantthresh__8u1__p9_1,
  146790. _vq_quantmap__8u1__p9_1,
  146791. 15,
  146792. 15
  146793. };
  146794. static static_codebook _8u1__p9_1 = {
  146795. 2, 225,
  146796. _vq_lengthlist__8u1__p9_1,
  146797. 1, -522338304, 1620115456, 4, 0,
  146798. _vq_quantlist__8u1__p9_1,
  146799. NULL,
  146800. &_vq_auxt__8u1__p9_1,
  146801. NULL,
  146802. 0
  146803. };
  146804. static long _vq_quantlist__8u1__p9_2[] = {
  146805. 8,
  146806. 7,
  146807. 9,
  146808. 6,
  146809. 10,
  146810. 5,
  146811. 11,
  146812. 4,
  146813. 12,
  146814. 3,
  146815. 13,
  146816. 2,
  146817. 14,
  146818. 1,
  146819. 15,
  146820. 0,
  146821. 16,
  146822. };
  146823. static long _vq_lengthlist__8u1__p9_2[] = {
  146824. 2, 5, 4, 6, 6, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146825. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  146826. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  146827. 9, 9, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  146828. 9,10,10, 9, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146829. 9, 9, 9,10,10, 8, 8, 8, 9, 9, 9, 9,10,10,10, 9,
  146830. 10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  146831. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,
  146832. 10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,10,
  146833. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  146834. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  146835. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  146836. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  146837. 9,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  146838. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,10,
  146839. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  146840. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146841. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  146842. 10,
  146843. };
  146844. static float _vq_quantthresh__8u1__p9_2[] = {
  146845. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  146846. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  146847. };
  146848. static long _vq_quantmap__8u1__p9_2[] = {
  146849. 15, 13, 11, 9, 7, 5, 3, 1,
  146850. 0, 2, 4, 6, 8, 10, 12, 14,
  146851. 16,
  146852. };
  146853. static encode_aux_threshmatch _vq_auxt__8u1__p9_2 = {
  146854. _vq_quantthresh__8u1__p9_2,
  146855. _vq_quantmap__8u1__p9_2,
  146856. 17,
  146857. 17
  146858. };
  146859. static static_codebook _8u1__p9_2 = {
  146860. 2, 289,
  146861. _vq_lengthlist__8u1__p9_2,
  146862. 1, -529530880, 1611661312, 5, 0,
  146863. _vq_quantlist__8u1__p9_2,
  146864. NULL,
  146865. &_vq_auxt__8u1__p9_2,
  146866. NULL,
  146867. 0
  146868. };
  146869. static long _huff_lengthlist__8u1__single[] = {
  146870. 4, 7,13, 9,15, 9,16, 8,10,13, 7, 5, 8, 6, 9, 7,
  146871. 10, 7,10,11,11, 6, 7, 8, 8, 9, 9, 9,12,16, 8, 5,
  146872. 8, 6, 8, 6, 9, 7,10,12,11, 7, 7, 7, 6, 7, 7, 7,
  146873. 11,15, 7, 5, 8, 6, 7, 5, 7, 6, 9,13,13, 9, 9, 8,
  146874. 6, 6, 5, 5, 9,14, 8, 6, 8, 6, 6, 4, 5, 3, 5,13,
  146875. 9, 9,11, 8,10, 7, 8, 4, 5,12,11,16,17,15,17,12,
  146876. 13, 8, 8,15,
  146877. };
  146878. static static_codebook _huff_book__8u1__single = {
  146879. 2, 100,
  146880. _huff_lengthlist__8u1__single,
  146881. 0, 0, 0, 0, 0,
  146882. NULL,
  146883. NULL,
  146884. NULL,
  146885. NULL,
  146886. 0
  146887. };
  146888. static long _huff_lengthlist__44u0__long[] = {
  146889. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  146890. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  146891. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  146892. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  146893. };
  146894. static static_codebook _huff_book__44u0__long = {
  146895. 2, 64,
  146896. _huff_lengthlist__44u0__long,
  146897. 0, 0, 0, 0, 0,
  146898. NULL,
  146899. NULL,
  146900. NULL,
  146901. NULL,
  146902. 0
  146903. };
  146904. static long _vq_quantlist__44u0__p1_0[] = {
  146905. 1,
  146906. 0,
  146907. 2,
  146908. };
  146909. static long _vq_lengthlist__44u0__p1_0[] = {
  146910. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  146911. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  146912. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  146913. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  146914. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  146915. 13,
  146916. };
  146917. static float _vq_quantthresh__44u0__p1_0[] = {
  146918. -0.5, 0.5,
  146919. };
  146920. static long _vq_quantmap__44u0__p1_0[] = {
  146921. 1, 0, 2,
  146922. };
  146923. static encode_aux_threshmatch _vq_auxt__44u0__p1_0 = {
  146924. _vq_quantthresh__44u0__p1_0,
  146925. _vq_quantmap__44u0__p1_0,
  146926. 3,
  146927. 3
  146928. };
  146929. static static_codebook _44u0__p1_0 = {
  146930. 4, 81,
  146931. _vq_lengthlist__44u0__p1_0,
  146932. 1, -535822336, 1611661312, 2, 0,
  146933. _vq_quantlist__44u0__p1_0,
  146934. NULL,
  146935. &_vq_auxt__44u0__p1_0,
  146936. NULL,
  146937. 0
  146938. };
  146939. static long _vq_quantlist__44u0__p2_0[] = {
  146940. 1,
  146941. 0,
  146942. 2,
  146943. };
  146944. static long _vq_lengthlist__44u0__p2_0[] = {
  146945. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  146946. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  146947. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  146948. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  146949. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  146950. 9,
  146951. };
  146952. static float _vq_quantthresh__44u0__p2_0[] = {
  146953. -0.5, 0.5,
  146954. };
  146955. static long _vq_quantmap__44u0__p2_0[] = {
  146956. 1, 0, 2,
  146957. };
  146958. static encode_aux_threshmatch _vq_auxt__44u0__p2_0 = {
  146959. _vq_quantthresh__44u0__p2_0,
  146960. _vq_quantmap__44u0__p2_0,
  146961. 3,
  146962. 3
  146963. };
  146964. static static_codebook _44u0__p2_0 = {
  146965. 4, 81,
  146966. _vq_lengthlist__44u0__p2_0,
  146967. 1, -535822336, 1611661312, 2, 0,
  146968. _vq_quantlist__44u0__p2_0,
  146969. NULL,
  146970. &_vq_auxt__44u0__p2_0,
  146971. NULL,
  146972. 0
  146973. };
  146974. static long _vq_quantlist__44u0__p3_0[] = {
  146975. 2,
  146976. 1,
  146977. 3,
  146978. 0,
  146979. 4,
  146980. };
  146981. static long _vq_lengthlist__44u0__p3_0[] = {
  146982. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  146983. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  146984. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  146985. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  146986. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  146987. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  146988. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  146989. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  146990. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  146991. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  146992. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  146993. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  146994. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  146995. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  146996. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  146997. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  146998. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  146999. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  147000. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  147001. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  147002. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  147003. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  147004. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  147005. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  147006. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  147007. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  147008. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  147009. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  147010. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  147011. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  147012. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  147013. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  147014. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  147015. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  147016. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  147017. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  147018. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  147019. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  147020. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  147021. 19,
  147022. };
  147023. static float _vq_quantthresh__44u0__p3_0[] = {
  147024. -1.5, -0.5, 0.5, 1.5,
  147025. };
  147026. static long _vq_quantmap__44u0__p3_0[] = {
  147027. 3, 1, 0, 2, 4,
  147028. };
  147029. static encode_aux_threshmatch _vq_auxt__44u0__p3_0 = {
  147030. _vq_quantthresh__44u0__p3_0,
  147031. _vq_quantmap__44u0__p3_0,
  147032. 5,
  147033. 5
  147034. };
  147035. static static_codebook _44u0__p3_0 = {
  147036. 4, 625,
  147037. _vq_lengthlist__44u0__p3_0,
  147038. 1, -533725184, 1611661312, 3, 0,
  147039. _vq_quantlist__44u0__p3_0,
  147040. NULL,
  147041. &_vq_auxt__44u0__p3_0,
  147042. NULL,
  147043. 0
  147044. };
  147045. static long _vq_quantlist__44u0__p4_0[] = {
  147046. 2,
  147047. 1,
  147048. 3,
  147049. 0,
  147050. 4,
  147051. };
  147052. static long _vq_lengthlist__44u0__p4_0[] = {
  147053. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  147054. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  147055. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  147056. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  147057. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  147058. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  147059. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  147060. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  147061. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  147062. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  147063. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  147064. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147065. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  147066. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  147067. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  147068. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  147069. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  147070. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  147071. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  147072. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  147073. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  147074. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  147075. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  147076. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  147077. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  147078. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  147079. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  147080. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  147081. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  147082. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  147083. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  147084. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  147085. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  147086. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  147087. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  147088. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  147089. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  147090. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  147091. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  147092. 12,
  147093. };
  147094. static float _vq_quantthresh__44u0__p4_0[] = {
  147095. -1.5, -0.5, 0.5, 1.5,
  147096. };
  147097. static long _vq_quantmap__44u0__p4_0[] = {
  147098. 3, 1, 0, 2, 4,
  147099. };
  147100. static encode_aux_threshmatch _vq_auxt__44u0__p4_0 = {
  147101. _vq_quantthresh__44u0__p4_0,
  147102. _vq_quantmap__44u0__p4_0,
  147103. 5,
  147104. 5
  147105. };
  147106. static static_codebook _44u0__p4_0 = {
  147107. 4, 625,
  147108. _vq_lengthlist__44u0__p4_0,
  147109. 1, -533725184, 1611661312, 3, 0,
  147110. _vq_quantlist__44u0__p4_0,
  147111. NULL,
  147112. &_vq_auxt__44u0__p4_0,
  147113. NULL,
  147114. 0
  147115. };
  147116. static long _vq_quantlist__44u0__p5_0[] = {
  147117. 4,
  147118. 3,
  147119. 5,
  147120. 2,
  147121. 6,
  147122. 1,
  147123. 7,
  147124. 0,
  147125. 8,
  147126. };
  147127. static long _vq_lengthlist__44u0__p5_0[] = {
  147128. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147129. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147130. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147131. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147132. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147133. 12,
  147134. };
  147135. static float _vq_quantthresh__44u0__p5_0[] = {
  147136. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147137. };
  147138. static long _vq_quantmap__44u0__p5_0[] = {
  147139. 7, 5, 3, 1, 0, 2, 4, 6,
  147140. 8,
  147141. };
  147142. static encode_aux_threshmatch _vq_auxt__44u0__p5_0 = {
  147143. _vq_quantthresh__44u0__p5_0,
  147144. _vq_quantmap__44u0__p5_0,
  147145. 9,
  147146. 9
  147147. };
  147148. static static_codebook _44u0__p5_0 = {
  147149. 2, 81,
  147150. _vq_lengthlist__44u0__p5_0,
  147151. 1, -531628032, 1611661312, 4, 0,
  147152. _vq_quantlist__44u0__p5_0,
  147153. NULL,
  147154. &_vq_auxt__44u0__p5_0,
  147155. NULL,
  147156. 0
  147157. };
  147158. static long _vq_quantlist__44u0__p6_0[] = {
  147159. 6,
  147160. 5,
  147161. 7,
  147162. 4,
  147163. 8,
  147164. 3,
  147165. 9,
  147166. 2,
  147167. 10,
  147168. 1,
  147169. 11,
  147170. 0,
  147171. 12,
  147172. };
  147173. static long _vq_lengthlist__44u0__p6_0[] = {
  147174. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147175. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147176. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147177. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147178. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147179. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147180. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147181. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147182. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147183. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147184. 15,17,16,17,18,17,17,18, 0,
  147185. };
  147186. static float _vq_quantthresh__44u0__p6_0[] = {
  147187. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147188. 12.5, 17.5, 22.5, 27.5,
  147189. };
  147190. static long _vq_quantmap__44u0__p6_0[] = {
  147191. 11, 9, 7, 5, 3, 1, 0, 2,
  147192. 4, 6, 8, 10, 12,
  147193. };
  147194. static encode_aux_threshmatch _vq_auxt__44u0__p6_0 = {
  147195. _vq_quantthresh__44u0__p6_0,
  147196. _vq_quantmap__44u0__p6_0,
  147197. 13,
  147198. 13
  147199. };
  147200. static static_codebook _44u0__p6_0 = {
  147201. 2, 169,
  147202. _vq_lengthlist__44u0__p6_0,
  147203. 1, -526516224, 1616117760, 4, 0,
  147204. _vq_quantlist__44u0__p6_0,
  147205. NULL,
  147206. &_vq_auxt__44u0__p6_0,
  147207. NULL,
  147208. 0
  147209. };
  147210. static long _vq_quantlist__44u0__p6_1[] = {
  147211. 2,
  147212. 1,
  147213. 3,
  147214. 0,
  147215. 4,
  147216. };
  147217. static long _vq_lengthlist__44u0__p6_1[] = {
  147218. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147219. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147220. };
  147221. static float _vq_quantthresh__44u0__p6_1[] = {
  147222. -1.5, -0.5, 0.5, 1.5,
  147223. };
  147224. static long _vq_quantmap__44u0__p6_1[] = {
  147225. 3, 1, 0, 2, 4,
  147226. };
  147227. static encode_aux_threshmatch _vq_auxt__44u0__p6_1 = {
  147228. _vq_quantthresh__44u0__p6_1,
  147229. _vq_quantmap__44u0__p6_1,
  147230. 5,
  147231. 5
  147232. };
  147233. static static_codebook _44u0__p6_1 = {
  147234. 2, 25,
  147235. _vq_lengthlist__44u0__p6_1,
  147236. 1, -533725184, 1611661312, 3, 0,
  147237. _vq_quantlist__44u0__p6_1,
  147238. NULL,
  147239. &_vq_auxt__44u0__p6_1,
  147240. NULL,
  147241. 0
  147242. };
  147243. static long _vq_quantlist__44u0__p7_0[] = {
  147244. 2,
  147245. 1,
  147246. 3,
  147247. 0,
  147248. 4,
  147249. };
  147250. static long _vq_lengthlist__44u0__p7_0[] = {
  147251. 1, 4, 4,11,11, 9,11,11,11,11,11,11,11,11,11,11,
  147252. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147253. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147254. 11,11, 9,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147255. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147256. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147257. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147258. 11,11,11,11,11,11,11,11,11,11,11,11,11,10,11,11,
  147259. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147260. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147261. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147262. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147263. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147264. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147265. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147266. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147267. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147268. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147269. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147270. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147271. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147272. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147273. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147274. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147275. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147276. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147277. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147278. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147279. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147280. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  147281. 11,11,11,11,11,11,10,10,10,10,10,10,10,10,10,10,
  147282. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147283. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147284. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147285. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147286. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147287. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147288. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147289. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  147290. 10,
  147291. };
  147292. static float _vq_quantthresh__44u0__p7_0[] = {
  147293. -253.5, -84.5, 84.5, 253.5,
  147294. };
  147295. static long _vq_quantmap__44u0__p7_0[] = {
  147296. 3, 1, 0, 2, 4,
  147297. };
  147298. static encode_aux_threshmatch _vq_auxt__44u0__p7_0 = {
  147299. _vq_quantthresh__44u0__p7_0,
  147300. _vq_quantmap__44u0__p7_0,
  147301. 5,
  147302. 5
  147303. };
  147304. static static_codebook _44u0__p7_0 = {
  147305. 4, 625,
  147306. _vq_lengthlist__44u0__p7_0,
  147307. 1, -518709248, 1626677248, 3, 0,
  147308. _vq_quantlist__44u0__p7_0,
  147309. NULL,
  147310. &_vq_auxt__44u0__p7_0,
  147311. NULL,
  147312. 0
  147313. };
  147314. static long _vq_quantlist__44u0__p7_1[] = {
  147315. 6,
  147316. 5,
  147317. 7,
  147318. 4,
  147319. 8,
  147320. 3,
  147321. 9,
  147322. 2,
  147323. 10,
  147324. 1,
  147325. 11,
  147326. 0,
  147327. 12,
  147328. };
  147329. static long _vq_lengthlist__44u0__p7_1[] = {
  147330. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147331. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147332. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147333. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147334. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147335. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147336. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147337. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147338. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147339. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147340. 15,15,15,15,15,15,15,15,15,
  147341. };
  147342. static float _vq_quantthresh__44u0__p7_1[] = {
  147343. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147344. 32.5, 45.5, 58.5, 71.5,
  147345. };
  147346. static long _vq_quantmap__44u0__p7_1[] = {
  147347. 11, 9, 7, 5, 3, 1, 0, 2,
  147348. 4, 6, 8, 10, 12,
  147349. };
  147350. static encode_aux_threshmatch _vq_auxt__44u0__p7_1 = {
  147351. _vq_quantthresh__44u0__p7_1,
  147352. _vq_quantmap__44u0__p7_1,
  147353. 13,
  147354. 13
  147355. };
  147356. static static_codebook _44u0__p7_1 = {
  147357. 2, 169,
  147358. _vq_lengthlist__44u0__p7_1,
  147359. 1, -523010048, 1618608128, 4, 0,
  147360. _vq_quantlist__44u0__p7_1,
  147361. NULL,
  147362. &_vq_auxt__44u0__p7_1,
  147363. NULL,
  147364. 0
  147365. };
  147366. static long _vq_quantlist__44u0__p7_2[] = {
  147367. 6,
  147368. 5,
  147369. 7,
  147370. 4,
  147371. 8,
  147372. 3,
  147373. 9,
  147374. 2,
  147375. 10,
  147376. 1,
  147377. 11,
  147378. 0,
  147379. 12,
  147380. };
  147381. static long _vq_lengthlist__44u0__p7_2[] = {
  147382. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147383. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147384. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147385. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147386. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147387. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147388. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147389. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147390. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147391. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147392. 9, 9, 9,10, 9, 9,10,10, 9,
  147393. };
  147394. static float _vq_quantthresh__44u0__p7_2[] = {
  147395. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147396. 2.5, 3.5, 4.5, 5.5,
  147397. };
  147398. static long _vq_quantmap__44u0__p7_2[] = {
  147399. 11, 9, 7, 5, 3, 1, 0, 2,
  147400. 4, 6, 8, 10, 12,
  147401. };
  147402. static encode_aux_threshmatch _vq_auxt__44u0__p7_2 = {
  147403. _vq_quantthresh__44u0__p7_2,
  147404. _vq_quantmap__44u0__p7_2,
  147405. 13,
  147406. 13
  147407. };
  147408. static static_codebook _44u0__p7_2 = {
  147409. 2, 169,
  147410. _vq_lengthlist__44u0__p7_2,
  147411. 1, -531103744, 1611661312, 4, 0,
  147412. _vq_quantlist__44u0__p7_2,
  147413. NULL,
  147414. &_vq_auxt__44u0__p7_2,
  147415. NULL,
  147416. 0
  147417. };
  147418. static long _huff_lengthlist__44u0__short[] = {
  147419. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147420. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147421. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147422. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147423. };
  147424. static static_codebook _huff_book__44u0__short = {
  147425. 2, 64,
  147426. _huff_lengthlist__44u0__short,
  147427. 0, 0, 0, 0, 0,
  147428. NULL,
  147429. NULL,
  147430. NULL,
  147431. NULL,
  147432. 0
  147433. };
  147434. static long _huff_lengthlist__44u1__long[] = {
  147435. 5, 8,13,10,17,11,11,15, 7, 2, 4, 5, 8, 7, 9,16,
  147436. 13, 4, 3, 5, 6, 8,11,20,10, 4, 5, 5, 7, 6, 8,18,
  147437. 15, 7, 6, 7, 8,10,14,20,10, 6, 7, 6, 9, 7, 8,17,
  147438. 9, 8,10, 8,10, 5, 4,11,12,17,19,14,16,10, 7,12,
  147439. };
  147440. static static_codebook _huff_book__44u1__long = {
  147441. 2, 64,
  147442. _huff_lengthlist__44u1__long,
  147443. 0, 0, 0, 0, 0,
  147444. NULL,
  147445. NULL,
  147446. NULL,
  147447. NULL,
  147448. 0
  147449. };
  147450. static long _vq_quantlist__44u1__p1_0[] = {
  147451. 1,
  147452. 0,
  147453. 2,
  147454. };
  147455. static long _vq_lengthlist__44u1__p1_0[] = {
  147456. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147457. 10,10, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147458. 11, 8,11,11, 8,12,11,11,13,13,11,13,14, 7,11,11,
  147459. 10,13,12,11,13,14, 4, 8, 8, 8,11,11, 8,11,12, 8,
  147460. 11,11,11,13,13,10,12,13, 8,11,11,11,14,13,11,14,
  147461. 13,
  147462. };
  147463. static float _vq_quantthresh__44u1__p1_0[] = {
  147464. -0.5, 0.5,
  147465. };
  147466. static long _vq_quantmap__44u1__p1_0[] = {
  147467. 1, 0, 2,
  147468. };
  147469. static encode_aux_threshmatch _vq_auxt__44u1__p1_0 = {
  147470. _vq_quantthresh__44u1__p1_0,
  147471. _vq_quantmap__44u1__p1_0,
  147472. 3,
  147473. 3
  147474. };
  147475. static static_codebook _44u1__p1_0 = {
  147476. 4, 81,
  147477. _vq_lengthlist__44u1__p1_0,
  147478. 1, -535822336, 1611661312, 2, 0,
  147479. _vq_quantlist__44u1__p1_0,
  147480. NULL,
  147481. &_vq_auxt__44u1__p1_0,
  147482. NULL,
  147483. 0
  147484. };
  147485. static long _vq_quantlist__44u1__p2_0[] = {
  147486. 1,
  147487. 0,
  147488. 2,
  147489. };
  147490. static long _vq_lengthlist__44u1__p2_0[] = {
  147491. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  147492. 8, 8, 5, 7, 7, 6, 8, 8, 7, 8, 8, 4, 7, 7, 7, 8,
  147493. 8, 7, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  147494. 8,10, 8, 8,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 8, 6,
  147495. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  147496. 9,
  147497. };
  147498. static float _vq_quantthresh__44u1__p2_0[] = {
  147499. -0.5, 0.5,
  147500. };
  147501. static long _vq_quantmap__44u1__p2_0[] = {
  147502. 1, 0, 2,
  147503. };
  147504. static encode_aux_threshmatch _vq_auxt__44u1__p2_0 = {
  147505. _vq_quantthresh__44u1__p2_0,
  147506. _vq_quantmap__44u1__p2_0,
  147507. 3,
  147508. 3
  147509. };
  147510. static static_codebook _44u1__p2_0 = {
  147511. 4, 81,
  147512. _vq_lengthlist__44u1__p2_0,
  147513. 1, -535822336, 1611661312, 2, 0,
  147514. _vq_quantlist__44u1__p2_0,
  147515. NULL,
  147516. &_vq_auxt__44u1__p2_0,
  147517. NULL,
  147518. 0
  147519. };
  147520. static long _vq_quantlist__44u1__p3_0[] = {
  147521. 2,
  147522. 1,
  147523. 3,
  147524. 0,
  147525. 4,
  147526. };
  147527. static long _vq_lengthlist__44u1__p3_0[] = {
  147528. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  147529. 10, 9,12,12, 9, 9,10,12,12, 6, 8, 8,11,10, 8,10,
  147530. 10,11,11, 8, 9,10,11,11,10,11,11,14,13,10,11,11,
  147531. 13,13, 5, 8, 8,10,10, 8,10,10,11,11, 8,10,10,11,
  147532. 11,10,11,11,13,13,10,11,11,13,13, 9,11,11,15,14,
  147533. 10,12,12,15,14,10,12,11,15,14,13,14,14,16,16,12,
  147534. 14,13,17,15, 9,11,11,14,15,10,11,12,14,16,10,11,
  147535. 12,14,16,12,13,14,16,16,13,13,15,15,18, 5, 8, 8,
  147536. 11,11, 8,10,10,12,12, 8,10,10,12,13,11,12,12,14,
  147537. 14,11,12,12,15,15, 8,10,10,13,13,10,12,12,13,13,
  147538. 10,12,12,14,14,12,13,13,15,15,12,13,13,16,16, 7,
  147539. 10,10,12,12,10,12,11,13,13,10,12,12,13,14,12,13,
  147540. 12,15,14,12,13,13,16,16,10,12,12,17,16,12,13,13,
  147541. 16,15,11,13,13,17,17,15,15,15,16,17,14,15,15,19,
  147542. 19,10,12,12,15,16,11,13,12,15,18,11,13,13,16,16,
  147543. 14,15,15,17,17,14,15,15,17,19, 5, 8, 8,11,11, 8,
  147544. 10,10,12,12, 8,10,10,12,12,11,12,12,16,15,11,12,
  147545. 12,14,15, 7,10,10,13,13,10,12,12,14,13,10,11,12,
  147546. 13,13,12,13,13,16,16,12,12,13,15,15, 8,10,10,13,
  147547. 13,10,12,12,14,14,10,12,12,13,13,12,13,13,16,16,
  147548. 12,13,13,15,15,10,12,12,16,15,11,13,13,17,16,11,
  147549. 12,13,16,15,13,15,15,19,17,14,15,14,17,16,10,12,
  147550. 12,16,16,11,13,13,16,17,12,13,13,15,17,14,15,15,
  147551. 17,19,14,15,15,17,17, 8,11,11,16,16,10,13,12,17,
  147552. 17,10,12,13,16,16,15,17,16,20,19,14,15,17,18,19,
  147553. 9,12,12,16,17,11,13,14,17,18,11,13,13,19,18,16,
  147554. 17,18,19,19,15,16,16,19,19, 9,12,12,16,17,11,14,
  147555. 13,18,17,11,13,13,17,17,16,17,16,20,19,14,16,16,
  147556. 18,18,12,15,15,19,17,14,15,16, 0,20,13,15,16,20,
  147557. 17,18,16,20, 0, 0,15,16,19,20, 0,12,15,14,18,19,
  147558. 13,16,15,20,19,13,16,15,20,18,17,18,17, 0,20,16,
  147559. 17,16, 0, 0, 8,11,11,16,15,10,12,12,17,17,10,13,
  147560. 13,17,16,14,16,15,18,20,15,16,16,19,19, 9,12,12,
  147561. 16,16,11,13,13,17,16,11,13,14,17,18,15,15,16,20,
  147562. 20,16,16,17,19,19, 9,13,12,16,17,11,14,13,17,17,
  147563. 11,14,14,18,17,14,16,15,18,19,16,17,18,18,19,12,
  147564. 14,15,19,18,13,15,16,18, 0,13,14,15, 0, 0,16,16,
  147565. 17,20, 0,17,17,20,20, 0,12,15,15,19,20,13,15,15,
  147566. 0, 0,14,16,15, 0, 0,15,18,16, 0, 0,17,18,16, 0,
  147567. 19,
  147568. };
  147569. static float _vq_quantthresh__44u1__p3_0[] = {
  147570. -1.5, -0.5, 0.5, 1.5,
  147571. };
  147572. static long _vq_quantmap__44u1__p3_0[] = {
  147573. 3, 1, 0, 2, 4,
  147574. };
  147575. static encode_aux_threshmatch _vq_auxt__44u1__p3_0 = {
  147576. _vq_quantthresh__44u1__p3_0,
  147577. _vq_quantmap__44u1__p3_0,
  147578. 5,
  147579. 5
  147580. };
  147581. static static_codebook _44u1__p3_0 = {
  147582. 4, 625,
  147583. _vq_lengthlist__44u1__p3_0,
  147584. 1, -533725184, 1611661312, 3, 0,
  147585. _vq_quantlist__44u1__p3_0,
  147586. NULL,
  147587. &_vq_auxt__44u1__p3_0,
  147588. NULL,
  147589. 0
  147590. };
  147591. static long _vq_quantlist__44u1__p4_0[] = {
  147592. 2,
  147593. 1,
  147594. 3,
  147595. 0,
  147596. 4,
  147597. };
  147598. static long _vq_lengthlist__44u1__p4_0[] = {
  147599. 4, 5, 5, 9, 9, 5, 6, 6, 9, 9, 5, 6, 6, 9, 9, 9,
  147600. 10, 9,12,12, 9, 9,10,12,12, 5, 7, 7,10,10, 7, 7,
  147601. 8,10,10, 6, 7, 8,10,10,10,10,10,11,13,10, 9,10,
  147602. 12,13, 5, 7, 7,10,10, 6, 8, 7,10,10, 7, 8, 7,10,
  147603. 10, 9,10,10,12,12,10,10,10,13,11, 9,10,10,13,13,
  147604. 10,11,10,13,13,10,10,10,13,13,12,12,13,14,14,12,
  147605. 12,13,14,14, 9,10,10,13,13,10,10,10,13,13,10,10,
  147606. 10,13,13,12,13,12,15,14,12,13,12,15,15, 5, 7, 6,
  147607. 10,10, 7, 8, 8,10,10, 7, 8, 8,10,10,10,11,10,13,
  147608. 13,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,10,11,
  147609. 8, 9, 9,11,11,11,10,11,11,14,11,11,11,13,13, 6,
  147610. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  147611. 10,14,11,10,11,11,13,13,10,11,11,14,13,10,10,11,
  147612. 14,13,10,11,11,14,14,12,11,13,12,16,13,14,14,15,
  147613. 15,10,10,11,13,14,10,11,10,14,13,10,11,11,14,14,
  147614. 12,13,12,15,13,13,13,14,15,16, 5, 7, 7,10,10, 7,
  147615. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,13,13,10,10,
  147616. 11,12,13, 6, 8, 8,11,10, 8, 9, 9,11,11, 7, 8, 9,
  147617. 10,11,10,11,11,13,13,10,10,11,11,13, 6, 8, 8,10,
  147618. 11, 8, 9, 9,11,11, 8, 9, 8,12,10,10,11,11,13,13,
  147619. 10,11,10,14,11,10,10,10,14,13,10,11,11,14,13,10,
  147620. 10,11,13,13,12,14,14,16,16,12,12,13,13,15,10,11,
  147621. 11,13,14,10,11,11,14,15,10,11,10,13,13,13,14,13,
  147622. 16,16,12,13,11,15,12, 9,10,10,13,13,10,11,11,14,
  147623. 13,10,10,11,13,14,13,14,13,16,16,13,13,13,15,16,
  147624. 9,10,10,13,13,10,10,11,13,14,10,11,11,15,13,13,
  147625. 13,14,14,18,13,13,14,16,15, 9,10,10,13,14,10,11,
  147626. 10,14,13,10,11,11,13,14,13,14,13,16,15,13,13,14,
  147627. 15,16,12,13,12,16,14,11,11,13,15,15,13,14,13,16,
  147628. 15,15,12,16,12,17,14,15,15,17,17,12,13,13,14,16,
  147629. 11,13,11,16,15,12,13,14,15,16,14,15,13, 0,14,14,
  147630. 16,16, 0, 0, 9,10,10,13,13,10,11,10,14,14,10,11,
  147631. 11,13,13,12,13,13,14,16,13,14,14,16,16, 9,10,10,
  147632. 14,14,11,11,11,14,13,10,10,11,14,14,13,13,13,16,
  147633. 16,13,13,14,14,17, 9,10,10,13,14,10,11,11,13,15,
  147634. 10,11,10,14,14,13,13,13,14,17,13,14,13,17,14,12,
  147635. 13,13,16,14,13,14,13,16,15,12,12,13,15,16,15,15,
  147636. 16,18,16,15,13,15,14, 0,12,12,13,14,16,13,13,14,
  147637. 15,16,11,12,11,16,14,15,16,16,17,17,14,15,12,17,
  147638. 12,
  147639. };
  147640. static float _vq_quantthresh__44u1__p4_0[] = {
  147641. -1.5, -0.5, 0.5, 1.5,
  147642. };
  147643. static long _vq_quantmap__44u1__p4_0[] = {
  147644. 3, 1, 0, 2, 4,
  147645. };
  147646. static encode_aux_threshmatch _vq_auxt__44u1__p4_0 = {
  147647. _vq_quantthresh__44u1__p4_0,
  147648. _vq_quantmap__44u1__p4_0,
  147649. 5,
  147650. 5
  147651. };
  147652. static static_codebook _44u1__p4_0 = {
  147653. 4, 625,
  147654. _vq_lengthlist__44u1__p4_0,
  147655. 1, -533725184, 1611661312, 3, 0,
  147656. _vq_quantlist__44u1__p4_0,
  147657. NULL,
  147658. &_vq_auxt__44u1__p4_0,
  147659. NULL,
  147660. 0
  147661. };
  147662. static long _vq_quantlist__44u1__p5_0[] = {
  147663. 4,
  147664. 3,
  147665. 5,
  147666. 2,
  147667. 6,
  147668. 1,
  147669. 7,
  147670. 0,
  147671. 8,
  147672. };
  147673. static long _vq_lengthlist__44u1__p5_0[] = {
  147674. 1, 4, 4, 7, 7, 7, 7, 9, 9, 4, 6, 6, 8, 8, 8, 8,
  147675. 9, 9, 4, 6, 6, 8, 8, 8, 8, 9, 9, 7, 8, 8, 9, 9,
  147676. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,10, 7, 8, 8,
  147677. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  147678. 9, 9,10,10,11,11,12,12, 9, 9, 9,10,11,11,11,12,
  147679. 12,
  147680. };
  147681. static float _vq_quantthresh__44u1__p5_0[] = {
  147682. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  147683. };
  147684. static long _vq_quantmap__44u1__p5_0[] = {
  147685. 7, 5, 3, 1, 0, 2, 4, 6,
  147686. 8,
  147687. };
  147688. static encode_aux_threshmatch _vq_auxt__44u1__p5_0 = {
  147689. _vq_quantthresh__44u1__p5_0,
  147690. _vq_quantmap__44u1__p5_0,
  147691. 9,
  147692. 9
  147693. };
  147694. static static_codebook _44u1__p5_0 = {
  147695. 2, 81,
  147696. _vq_lengthlist__44u1__p5_0,
  147697. 1, -531628032, 1611661312, 4, 0,
  147698. _vq_quantlist__44u1__p5_0,
  147699. NULL,
  147700. &_vq_auxt__44u1__p5_0,
  147701. NULL,
  147702. 0
  147703. };
  147704. static long _vq_quantlist__44u1__p6_0[] = {
  147705. 6,
  147706. 5,
  147707. 7,
  147708. 4,
  147709. 8,
  147710. 3,
  147711. 9,
  147712. 2,
  147713. 10,
  147714. 1,
  147715. 11,
  147716. 0,
  147717. 12,
  147718. };
  147719. static long _vq_lengthlist__44u1__p6_0[] = {
  147720. 1, 4, 4, 6, 6, 8, 8,10, 9,11,10,14,13, 4, 6, 5,
  147721. 8, 8, 9, 9,11,10,11,11,14,14, 4, 5, 6, 8, 8, 9,
  147722. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  147723. 12,12,16,15, 7, 8, 8, 9, 9,10,10,11,11,12,12,15,
  147724. 15, 9,10,10,10,10,11,11,12,12,12,12,15,15, 9,10,
  147725. 9,10,11,11,11,12,12,12,13,15,15,10,10,11,11,11,
  147726. 12,12,13,12,13,13,16,15,10,11,11,11,11,12,12,13,
  147727. 12,13,13,16,17,11,11,12,12,12,13,13,13,14,14,15,
  147728. 17,17,11,11,12,12,12,13,13,13,14,14,14,16,18,14,
  147729. 15,15,15,15,16,16,16,16,17,18, 0, 0,14,15,15,15,
  147730. 15,17,16,17,18,17,17,18, 0,
  147731. };
  147732. static float _vq_quantthresh__44u1__p6_0[] = {
  147733. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  147734. 12.5, 17.5, 22.5, 27.5,
  147735. };
  147736. static long _vq_quantmap__44u1__p6_0[] = {
  147737. 11, 9, 7, 5, 3, 1, 0, 2,
  147738. 4, 6, 8, 10, 12,
  147739. };
  147740. static encode_aux_threshmatch _vq_auxt__44u1__p6_0 = {
  147741. _vq_quantthresh__44u1__p6_0,
  147742. _vq_quantmap__44u1__p6_0,
  147743. 13,
  147744. 13
  147745. };
  147746. static static_codebook _44u1__p6_0 = {
  147747. 2, 169,
  147748. _vq_lengthlist__44u1__p6_0,
  147749. 1, -526516224, 1616117760, 4, 0,
  147750. _vq_quantlist__44u1__p6_0,
  147751. NULL,
  147752. &_vq_auxt__44u1__p6_0,
  147753. NULL,
  147754. 0
  147755. };
  147756. static long _vq_quantlist__44u1__p6_1[] = {
  147757. 2,
  147758. 1,
  147759. 3,
  147760. 0,
  147761. 4,
  147762. };
  147763. static long _vq_lengthlist__44u1__p6_1[] = {
  147764. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  147765. 6, 6, 6, 6, 5, 6, 6, 6, 6,
  147766. };
  147767. static float _vq_quantthresh__44u1__p6_1[] = {
  147768. -1.5, -0.5, 0.5, 1.5,
  147769. };
  147770. static long _vq_quantmap__44u1__p6_1[] = {
  147771. 3, 1, 0, 2, 4,
  147772. };
  147773. static encode_aux_threshmatch _vq_auxt__44u1__p6_1 = {
  147774. _vq_quantthresh__44u1__p6_1,
  147775. _vq_quantmap__44u1__p6_1,
  147776. 5,
  147777. 5
  147778. };
  147779. static static_codebook _44u1__p6_1 = {
  147780. 2, 25,
  147781. _vq_lengthlist__44u1__p6_1,
  147782. 1, -533725184, 1611661312, 3, 0,
  147783. _vq_quantlist__44u1__p6_1,
  147784. NULL,
  147785. &_vq_auxt__44u1__p6_1,
  147786. NULL,
  147787. 0
  147788. };
  147789. static long _vq_quantlist__44u1__p7_0[] = {
  147790. 3,
  147791. 2,
  147792. 4,
  147793. 1,
  147794. 5,
  147795. 0,
  147796. 6,
  147797. };
  147798. static long _vq_lengthlist__44u1__p7_0[] = {
  147799. 1, 3, 2, 9, 9, 7, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147800. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147801. 9, 9, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  147802. 8,
  147803. };
  147804. static float _vq_quantthresh__44u1__p7_0[] = {
  147805. -422.5, -253.5, -84.5, 84.5, 253.5, 422.5,
  147806. };
  147807. static long _vq_quantmap__44u1__p7_0[] = {
  147808. 5, 3, 1, 0, 2, 4, 6,
  147809. };
  147810. static encode_aux_threshmatch _vq_auxt__44u1__p7_0 = {
  147811. _vq_quantthresh__44u1__p7_0,
  147812. _vq_quantmap__44u1__p7_0,
  147813. 7,
  147814. 7
  147815. };
  147816. static static_codebook _44u1__p7_0 = {
  147817. 2, 49,
  147818. _vq_lengthlist__44u1__p7_0,
  147819. 1, -518017024, 1626677248, 3, 0,
  147820. _vq_quantlist__44u1__p7_0,
  147821. NULL,
  147822. &_vq_auxt__44u1__p7_0,
  147823. NULL,
  147824. 0
  147825. };
  147826. static long _vq_quantlist__44u1__p7_1[] = {
  147827. 6,
  147828. 5,
  147829. 7,
  147830. 4,
  147831. 8,
  147832. 3,
  147833. 9,
  147834. 2,
  147835. 10,
  147836. 1,
  147837. 11,
  147838. 0,
  147839. 12,
  147840. };
  147841. static long _vq_lengthlist__44u1__p7_1[] = {
  147842. 1, 4, 4, 6, 6, 6, 6, 7, 7, 8, 8, 9, 9, 5, 7, 7,
  147843. 8, 7, 7, 7, 9, 8,10, 9,10,11, 5, 7, 7, 8, 8, 7,
  147844. 7, 8, 9,10,10,11,11, 6, 8, 8, 9, 9, 9, 9,11,10,
  147845. 12,12,15,12, 6, 8, 8, 9, 9, 9, 9,11,11,12,11,14,
  147846. 12, 7, 8, 8,10,10,12,12,13,13,13,15,13,13, 7, 8,
  147847. 8,10,10,11,11,13,12,14,15,15,15, 9,10,10,11,12,
  147848. 13,13,14,15,14,15,14,15, 8,10,10,12,12,14,14,15,
  147849. 14,14,15,15,14,10,12,12,14,14,15,14,15,15,15,14,
  147850. 15,15,10,12,12,13,14,15,14,15,15,14,15,15,15,12,
  147851. 15,13,15,14,15,15,15,15,15,15,15,15,13,13,15,15,
  147852. 15,15,15,15,15,15,15,15,15,
  147853. };
  147854. static float _vq_quantthresh__44u1__p7_1[] = {
  147855. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  147856. 32.5, 45.5, 58.5, 71.5,
  147857. };
  147858. static long _vq_quantmap__44u1__p7_1[] = {
  147859. 11, 9, 7, 5, 3, 1, 0, 2,
  147860. 4, 6, 8, 10, 12,
  147861. };
  147862. static encode_aux_threshmatch _vq_auxt__44u1__p7_1 = {
  147863. _vq_quantthresh__44u1__p7_1,
  147864. _vq_quantmap__44u1__p7_1,
  147865. 13,
  147866. 13
  147867. };
  147868. static static_codebook _44u1__p7_1 = {
  147869. 2, 169,
  147870. _vq_lengthlist__44u1__p7_1,
  147871. 1, -523010048, 1618608128, 4, 0,
  147872. _vq_quantlist__44u1__p7_1,
  147873. NULL,
  147874. &_vq_auxt__44u1__p7_1,
  147875. NULL,
  147876. 0
  147877. };
  147878. static long _vq_quantlist__44u1__p7_2[] = {
  147879. 6,
  147880. 5,
  147881. 7,
  147882. 4,
  147883. 8,
  147884. 3,
  147885. 9,
  147886. 2,
  147887. 10,
  147888. 1,
  147889. 11,
  147890. 0,
  147891. 12,
  147892. };
  147893. static long _vq_lengthlist__44u1__p7_2[] = {
  147894. 2, 5, 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 5, 5, 6,
  147895. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 5, 6, 5, 7, 7, 8,
  147896. 8, 8, 8, 9, 9, 9, 9, 6, 7, 7, 8, 8, 8, 8, 9, 8,
  147897. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  147898. 9, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 7, 8,
  147899. 8, 9, 8, 9, 8, 9, 9, 9, 9, 9, 9, 8, 9, 8, 9, 9,
  147900. 9, 9, 9, 9, 9, 9,10,10, 8, 8, 9, 9, 9, 9, 9, 9,
  147901. 9, 9,10, 9,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147902. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  147903. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9, 9, 9, 9, 9,
  147904. 9, 9, 9,10, 9, 9,10,10, 9,
  147905. };
  147906. static float _vq_quantthresh__44u1__p7_2[] = {
  147907. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  147908. 2.5, 3.5, 4.5, 5.5,
  147909. };
  147910. static long _vq_quantmap__44u1__p7_2[] = {
  147911. 11, 9, 7, 5, 3, 1, 0, 2,
  147912. 4, 6, 8, 10, 12,
  147913. };
  147914. static encode_aux_threshmatch _vq_auxt__44u1__p7_2 = {
  147915. _vq_quantthresh__44u1__p7_2,
  147916. _vq_quantmap__44u1__p7_2,
  147917. 13,
  147918. 13
  147919. };
  147920. static static_codebook _44u1__p7_2 = {
  147921. 2, 169,
  147922. _vq_lengthlist__44u1__p7_2,
  147923. 1, -531103744, 1611661312, 4, 0,
  147924. _vq_quantlist__44u1__p7_2,
  147925. NULL,
  147926. &_vq_auxt__44u1__p7_2,
  147927. NULL,
  147928. 0
  147929. };
  147930. static long _huff_lengthlist__44u1__short[] = {
  147931. 12,13,14,13,17,12,15,17, 5, 5, 6,10,10,11,15,16,
  147932. 4, 3, 3, 7, 5, 7,10,16, 7, 7, 7,10, 9,11,12,16,
  147933. 6, 5, 5, 9, 5, 6,10,16, 8, 7, 7, 9, 6, 7, 9,16,
  147934. 11, 7, 3, 6, 4, 5, 8,16,12, 9, 4, 8, 5, 7, 9,16,
  147935. };
  147936. static static_codebook _huff_book__44u1__short = {
  147937. 2, 64,
  147938. _huff_lengthlist__44u1__short,
  147939. 0, 0, 0, 0, 0,
  147940. NULL,
  147941. NULL,
  147942. NULL,
  147943. NULL,
  147944. 0
  147945. };
  147946. static long _huff_lengthlist__44u2__long[] = {
  147947. 5, 9,14,12,15,13,10,13, 7, 4, 5, 6, 8, 7, 8,12,
  147948. 13, 4, 3, 5, 5, 6, 9,15,12, 6, 5, 6, 6, 6, 7,14,
  147949. 14, 7, 4, 6, 4, 6, 8,15,12, 6, 6, 5, 5, 5, 6,14,
  147950. 9, 7, 8, 6, 7, 5, 4,10,10,13,14,14,15,10, 6, 8,
  147951. };
  147952. static static_codebook _huff_book__44u2__long = {
  147953. 2, 64,
  147954. _huff_lengthlist__44u2__long,
  147955. 0, 0, 0, 0, 0,
  147956. NULL,
  147957. NULL,
  147958. NULL,
  147959. NULL,
  147960. 0
  147961. };
  147962. static long _vq_quantlist__44u2__p1_0[] = {
  147963. 1,
  147964. 0,
  147965. 2,
  147966. };
  147967. static long _vq_lengthlist__44u2__p1_0[] = {
  147968. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,11,11, 8,
  147969. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  147970. 11, 8,11,11, 8,11,11,11,13,14,11,13,13, 7,11,11,
  147971. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 8,
  147972. 11,11,11,14,13,10,12,13, 8,11,11,11,13,13,11,13,
  147973. 13,
  147974. };
  147975. static float _vq_quantthresh__44u2__p1_0[] = {
  147976. -0.5, 0.5,
  147977. };
  147978. static long _vq_quantmap__44u2__p1_0[] = {
  147979. 1, 0, 2,
  147980. };
  147981. static encode_aux_threshmatch _vq_auxt__44u2__p1_0 = {
  147982. _vq_quantthresh__44u2__p1_0,
  147983. _vq_quantmap__44u2__p1_0,
  147984. 3,
  147985. 3
  147986. };
  147987. static static_codebook _44u2__p1_0 = {
  147988. 4, 81,
  147989. _vq_lengthlist__44u2__p1_0,
  147990. 1, -535822336, 1611661312, 2, 0,
  147991. _vq_quantlist__44u2__p1_0,
  147992. NULL,
  147993. &_vq_auxt__44u2__p1_0,
  147994. NULL,
  147995. 0
  147996. };
  147997. static long _vq_quantlist__44u2__p2_0[] = {
  147998. 1,
  147999. 0,
  148000. 2,
  148001. };
  148002. static long _vq_lengthlist__44u2__p2_0[] = {
  148003. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148004. 8, 8, 5, 6, 6, 6, 8, 7, 7, 8, 8, 5, 6, 6, 7, 8,
  148005. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148006. 7,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  148007. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  148008. 9,
  148009. };
  148010. static float _vq_quantthresh__44u2__p2_0[] = {
  148011. -0.5, 0.5,
  148012. };
  148013. static long _vq_quantmap__44u2__p2_0[] = {
  148014. 1, 0, 2,
  148015. };
  148016. static encode_aux_threshmatch _vq_auxt__44u2__p2_0 = {
  148017. _vq_quantthresh__44u2__p2_0,
  148018. _vq_quantmap__44u2__p2_0,
  148019. 3,
  148020. 3
  148021. };
  148022. static static_codebook _44u2__p2_0 = {
  148023. 4, 81,
  148024. _vq_lengthlist__44u2__p2_0,
  148025. 1, -535822336, 1611661312, 2, 0,
  148026. _vq_quantlist__44u2__p2_0,
  148027. NULL,
  148028. &_vq_auxt__44u2__p2_0,
  148029. NULL,
  148030. 0
  148031. };
  148032. static long _vq_quantlist__44u2__p3_0[] = {
  148033. 2,
  148034. 1,
  148035. 3,
  148036. 0,
  148037. 4,
  148038. };
  148039. static long _vq_lengthlist__44u2__p3_0[] = {
  148040. 2, 4, 4, 7, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148041. 9, 9,12,11, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  148042. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  148043. 12,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  148044. 11, 9,11,10,13,13,10,11,11,13,13, 8,10,10,14,13,
  148045. 10,11,11,15,14, 9,11,11,15,14,13,14,13,16,14,12,
  148046. 13,13,15,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  148047. 11,14,15,12,13,13,15,15,12,13,14,15,16, 5, 7, 7,
  148048. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  148049. 13,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  148050. 9,11,11,13,13,12,13,12,14,14,11,12,13,15,15, 7,
  148051. 9, 9,12,12, 8,11,10,13,12, 9,11,11,13,13,11,13,
  148052. 12,15,13,11,13,13,15,16, 9,12,11,15,15,11,12,12,
  148053. 16,15,11,12,13,16,16,13,14,15,16,15,13,15,15,17,
  148054. 17, 9,11,11,14,15,10,12,12,15,15,11,13,12,15,16,
  148055. 13,15,14,16,16,13,15,15,17,19, 5, 7, 7,10,10, 7,
  148056. 9, 9,12,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  148057. 11,13,14, 7, 9, 9,12,12, 9,11,11,13,13, 9,10,11,
  148058. 12,13,11,13,12,16,15,11,12,12,14,15, 7, 9, 9,12,
  148059. 12, 9,11,11,13,13, 9,11,11,13,12,11,13,12,15,16,
  148060. 12,13,13,15,14, 9,11,11,15,14,11,13,12,16,15,10,
  148061. 11,12,15,15,13,14,14,18,17,13,14,14,15,17,10,11,
  148062. 11,14,15,11,13,12,15,17,11,13,12,15,16,13,15,14,
  148063. 18,17,14,15,15,16,18, 7,10,10,14,14,10,12,12,15,
  148064. 15,10,12,12,15,15,14,15,15,18,17,13,15,15,16,16,
  148065. 9,11,11,16,15,11,13,13,16,18,11,13,13,16,16,15,
  148066. 16,16, 0, 0,14,15,16,18,17, 9,11,11,15,15,10,13,
  148067. 12,17,16,11,12,13,16,17,14,15,16,19,19,14,15,15,
  148068. 0,20,12,14,14, 0, 0,13,14,16,19,18,13,15,16,20,
  148069. 17,16,18, 0, 0, 0,15,16,17,18,19,11,14,14, 0,19,
  148070. 12,15,14,17,17,13,15,15, 0, 0,16,17,15,20,19,15,
  148071. 17,16,19, 0, 8,10,10,14,15,10,12,11,15,15,10,11,
  148072. 12,16,15,13,14,14,19,17,14,15,15, 0, 0, 9,11,11,
  148073. 16,15,11,13,13,17,16,10,12,13,16,17,14,15,15,18,
  148074. 18,14,15,16,20,19, 9,12,12, 0,15,11,13,13,16,17,
  148075. 11,13,13,19,17,14,16,16,18,17,15,16,16,17,19,11,
  148076. 14,14,18,18,13,14,15, 0, 0,12,14,15,19,18,15,16,
  148077. 19, 0,19,15,16,19,19,17,12,14,14,16,19,13,15,15,
  148078. 0,17,13,15,14,18,18,15,16,15, 0,18,16,17,17, 0,
  148079. 0,
  148080. };
  148081. static float _vq_quantthresh__44u2__p3_0[] = {
  148082. -1.5, -0.5, 0.5, 1.5,
  148083. };
  148084. static long _vq_quantmap__44u2__p3_0[] = {
  148085. 3, 1, 0, 2, 4,
  148086. };
  148087. static encode_aux_threshmatch _vq_auxt__44u2__p3_0 = {
  148088. _vq_quantthresh__44u2__p3_0,
  148089. _vq_quantmap__44u2__p3_0,
  148090. 5,
  148091. 5
  148092. };
  148093. static static_codebook _44u2__p3_0 = {
  148094. 4, 625,
  148095. _vq_lengthlist__44u2__p3_0,
  148096. 1, -533725184, 1611661312, 3, 0,
  148097. _vq_quantlist__44u2__p3_0,
  148098. NULL,
  148099. &_vq_auxt__44u2__p3_0,
  148100. NULL,
  148101. 0
  148102. };
  148103. static long _vq_quantlist__44u2__p4_0[] = {
  148104. 2,
  148105. 1,
  148106. 3,
  148107. 0,
  148108. 4,
  148109. };
  148110. static long _vq_lengthlist__44u2__p4_0[] = {
  148111. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148112. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148113. 8,10,10, 7, 7, 8,10,10,10,10,10,11,12, 9,10,10,
  148114. 11,12, 5, 7, 7, 9, 9, 6, 8, 7,10,10, 7, 8, 8,10,
  148115. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10,10,12,12,
  148116. 10,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  148117. 12,12,13,14, 9,10,10,12,12, 9,10,10,12,13,10,10,
  148118. 10,12,13,11,12,12,14,13,12,12,12,14,13, 5, 7, 7,
  148119. 10, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148120. 12,10,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148121. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,13,13, 6,
  148122. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148123. 10,13,11,10,11,11,13,13, 9,10,10,13,13,10,11,11,
  148124. 13,13,10,11,11,14,13,12,11,13,12,15,12,13,13,15,
  148125. 15, 9,10,10,12,13,10,11,10,13,13,10,11,11,13,13,
  148126. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9,10, 7,
  148127. 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,12,10,10,
  148128. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148129. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148130. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  148131. 10,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148132. 10,11,13,13,12,13,13,15,15,12,11,13,12,14, 9,10,
  148133. 10,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  148134. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148135. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  148136. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,12,13,
  148137. 13,14,14,16,12,13,13,15,14, 9,10,10,13,13,10,11,
  148138. 10,14,13,10,11,11,13,14,12,14,13,16,14,13,13,13,
  148139. 14,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  148140. 15,14,12,15,12,16,14,15,15,17,16,11,12,12,14,15,
  148141. 11,13,11,15,14,12,13,13,15,16,13,15,12,17,13,14,
  148142. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,13,13, 9,10,
  148143. 10,13,13,12,13,12,14,14,12,13,13,15,15, 9,10,10,
  148144. 13,13,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  148145. 14,12,12,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  148146. 10,11,11,14,13,13,13,13,15,15,13,14,13,16,14,11,
  148147. 12,12,14,14,12,13,13,16,15,11,12,13,14,15,14,15,
  148148. 15,16,16,14,13,15,13,17,11,12,12,14,15,12,13,13,
  148149. 15,16,11,13,12,15,15,14,15,14,16,16,14,15,12,17,
  148150. 13,
  148151. };
  148152. static float _vq_quantthresh__44u2__p4_0[] = {
  148153. -1.5, -0.5, 0.5, 1.5,
  148154. };
  148155. static long _vq_quantmap__44u2__p4_0[] = {
  148156. 3, 1, 0, 2, 4,
  148157. };
  148158. static encode_aux_threshmatch _vq_auxt__44u2__p4_0 = {
  148159. _vq_quantthresh__44u2__p4_0,
  148160. _vq_quantmap__44u2__p4_0,
  148161. 5,
  148162. 5
  148163. };
  148164. static static_codebook _44u2__p4_0 = {
  148165. 4, 625,
  148166. _vq_lengthlist__44u2__p4_0,
  148167. 1, -533725184, 1611661312, 3, 0,
  148168. _vq_quantlist__44u2__p4_0,
  148169. NULL,
  148170. &_vq_auxt__44u2__p4_0,
  148171. NULL,
  148172. 0
  148173. };
  148174. static long _vq_quantlist__44u2__p5_0[] = {
  148175. 4,
  148176. 3,
  148177. 5,
  148178. 2,
  148179. 6,
  148180. 1,
  148181. 7,
  148182. 0,
  148183. 8,
  148184. };
  148185. static long _vq_lengthlist__44u2__p5_0[] = {
  148186. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 8, 8, 8,
  148187. 10,10, 4, 5, 6, 8, 8, 8, 8,10,10, 7, 8, 8, 9, 9,
  148188. 9, 9,11,11, 7, 8, 8, 9, 9, 9, 9,11,11, 8, 8, 8,
  148189. 9, 9,10,11,12,12, 8, 8, 8, 9, 9,10,10,12,12,10,
  148190. 10,10,11,11,12,12,13,13,10,10,10,11,11,12,12,13,
  148191. 13,
  148192. };
  148193. static float _vq_quantthresh__44u2__p5_0[] = {
  148194. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148195. };
  148196. static long _vq_quantmap__44u2__p5_0[] = {
  148197. 7, 5, 3, 1, 0, 2, 4, 6,
  148198. 8,
  148199. };
  148200. static encode_aux_threshmatch _vq_auxt__44u2__p5_0 = {
  148201. _vq_quantthresh__44u2__p5_0,
  148202. _vq_quantmap__44u2__p5_0,
  148203. 9,
  148204. 9
  148205. };
  148206. static static_codebook _44u2__p5_0 = {
  148207. 2, 81,
  148208. _vq_lengthlist__44u2__p5_0,
  148209. 1, -531628032, 1611661312, 4, 0,
  148210. _vq_quantlist__44u2__p5_0,
  148211. NULL,
  148212. &_vq_auxt__44u2__p5_0,
  148213. NULL,
  148214. 0
  148215. };
  148216. static long _vq_quantlist__44u2__p6_0[] = {
  148217. 6,
  148218. 5,
  148219. 7,
  148220. 4,
  148221. 8,
  148222. 3,
  148223. 9,
  148224. 2,
  148225. 10,
  148226. 1,
  148227. 11,
  148228. 0,
  148229. 12,
  148230. };
  148231. static long _vq_lengthlist__44u2__p6_0[] = {
  148232. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,14,13, 4, 6, 5,
  148233. 8, 8, 9, 9,11,10,12,11,15,14, 4, 5, 6, 8, 8, 9,
  148234. 9,11,11,11,11,14,14, 6, 8, 8,10, 9,11,11,11,11,
  148235. 12,12,15,15, 6, 8, 8, 9, 9,11,11,11,12,12,12,15,
  148236. 15, 8,10,10,11,11,11,11,12,12,13,13,15,16, 8,10,
  148237. 10,11,11,11,11,12,12,13,13,16,16,10,11,11,12,12,
  148238. 12,12,13,13,13,13,17,16,10,11,11,12,12,12,12,13,
  148239. 13,13,14,16,17,11,12,12,13,13,13,13,14,14,15,14,
  148240. 18,17,11,12,12,13,13,13,13,14,14,14,15,19,18,14,
  148241. 15,15,15,15,16,16,18,19,18,18, 0, 0,14,15,15,16,
  148242. 15,17,17,16,18,17,18, 0, 0,
  148243. };
  148244. static float _vq_quantthresh__44u2__p6_0[] = {
  148245. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148246. 12.5, 17.5, 22.5, 27.5,
  148247. };
  148248. static long _vq_quantmap__44u2__p6_0[] = {
  148249. 11, 9, 7, 5, 3, 1, 0, 2,
  148250. 4, 6, 8, 10, 12,
  148251. };
  148252. static encode_aux_threshmatch _vq_auxt__44u2__p6_0 = {
  148253. _vq_quantthresh__44u2__p6_0,
  148254. _vq_quantmap__44u2__p6_0,
  148255. 13,
  148256. 13
  148257. };
  148258. static static_codebook _44u2__p6_0 = {
  148259. 2, 169,
  148260. _vq_lengthlist__44u2__p6_0,
  148261. 1, -526516224, 1616117760, 4, 0,
  148262. _vq_quantlist__44u2__p6_0,
  148263. NULL,
  148264. &_vq_auxt__44u2__p6_0,
  148265. NULL,
  148266. 0
  148267. };
  148268. static long _vq_quantlist__44u2__p6_1[] = {
  148269. 2,
  148270. 1,
  148271. 3,
  148272. 0,
  148273. 4,
  148274. };
  148275. static long _vq_lengthlist__44u2__p6_1[] = {
  148276. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148277. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148278. };
  148279. static float _vq_quantthresh__44u2__p6_1[] = {
  148280. -1.5, -0.5, 0.5, 1.5,
  148281. };
  148282. static long _vq_quantmap__44u2__p6_1[] = {
  148283. 3, 1, 0, 2, 4,
  148284. };
  148285. static encode_aux_threshmatch _vq_auxt__44u2__p6_1 = {
  148286. _vq_quantthresh__44u2__p6_1,
  148287. _vq_quantmap__44u2__p6_1,
  148288. 5,
  148289. 5
  148290. };
  148291. static static_codebook _44u2__p6_1 = {
  148292. 2, 25,
  148293. _vq_lengthlist__44u2__p6_1,
  148294. 1, -533725184, 1611661312, 3, 0,
  148295. _vq_quantlist__44u2__p6_1,
  148296. NULL,
  148297. &_vq_auxt__44u2__p6_1,
  148298. NULL,
  148299. 0
  148300. };
  148301. static long _vq_quantlist__44u2__p7_0[] = {
  148302. 4,
  148303. 3,
  148304. 5,
  148305. 2,
  148306. 6,
  148307. 1,
  148308. 7,
  148309. 0,
  148310. 8,
  148311. };
  148312. static long _vq_lengthlist__44u2__p7_0[] = {
  148313. 1, 3, 2,12,12,12,12,12,12, 4,12,12,12,12,12,12,
  148314. 12,12, 5,12,12,12,12,12,12,12,12,12,12,11,11,11,
  148315. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148316. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148317. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  148318. 11,
  148319. };
  148320. static float _vq_quantthresh__44u2__p7_0[] = {
  148321. -591.5, -422.5, -253.5, -84.5, 84.5, 253.5, 422.5, 591.5,
  148322. };
  148323. static long _vq_quantmap__44u2__p7_0[] = {
  148324. 7, 5, 3, 1, 0, 2, 4, 6,
  148325. 8,
  148326. };
  148327. static encode_aux_threshmatch _vq_auxt__44u2__p7_0 = {
  148328. _vq_quantthresh__44u2__p7_0,
  148329. _vq_quantmap__44u2__p7_0,
  148330. 9,
  148331. 9
  148332. };
  148333. static static_codebook _44u2__p7_0 = {
  148334. 2, 81,
  148335. _vq_lengthlist__44u2__p7_0,
  148336. 1, -516612096, 1626677248, 4, 0,
  148337. _vq_quantlist__44u2__p7_0,
  148338. NULL,
  148339. &_vq_auxt__44u2__p7_0,
  148340. NULL,
  148341. 0
  148342. };
  148343. static long _vq_quantlist__44u2__p7_1[] = {
  148344. 6,
  148345. 5,
  148346. 7,
  148347. 4,
  148348. 8,
  148349. 3,
  148350. 9,
  148351. 2,
  148352. 10,
  148353. 1,
  148354. 11,
  148355. 0,
  148356. 12,
  148357. };
  148358. static long _vq_lengthlist__44u2__p7_1[] = {
  148359. 1, 4, 4, 7, 6, 7, 6, 8, 7, 9, 7, 9, 8, 4, 7, 6,
  148360. 8, 8, 9, 8,10, 9,10,10,11,11, 4, 7, 7, 8, 8, 8,
  148361. 8, 9,10,11,11,11,11, 6, 8, 8,10,10,10,10,11,11,
  148362. 12,12,12,12, 7, 8, 8,10,10,10,10,11,11,12,12,13,
  148363. 13, 7, 9, 9,11,10,12,12,13,13,14,13,14,14, 7, 9,
  148364. 9,10,11,11,12,13,13,13,13,16,14, 9,10,10,12,12,
  148365. 13,13,14,14,15,16,15,16, 9,10,10,12,12,12,13,14,
  148366. 14,14,15,16,15,10,12,12,13,13,15,13,16,16,15,17,
  148367. 17,17,10,11,11,12,14,14,14,15,15,17,17,15,17,11,
  148368. 12,12,14,14,14,15,15,15,17,16,17,17,10,12,12,13,
  148369. 14,14,14,17,15,17,17,17,17,
  148370. };
  148371. static float _vq_quantthresh__44u2__p7_1[] = {
  148372. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  148373. 32.5, 45.5, 58.5, 71.5,
  148374. };
  148375. static long _vq_quantmap__44u2__p7_1[] = {
  148376. 11, 9, 7, 5, 3, 1, 0, 2,
  148377. 4, 6, 8, 10, 12,
  148378. };
  148379. static encode_aux_threshmatch _vq_auxt__44u2__p7_1 = {
  148380. _vq_quantthresh__44u2__p7_1,
  148381. _vq_quantmap__44u2__p7_1,
  148382. 13,
  148383. 13
  148384. };
  148385. static static_codebook _44u2__p7_1 = {
  148386. 2, 169,
  148387. _vq_lengthlist__44u2__p7_1,
  148388. 1, -523010048, 1618608128, 4, 0,
  148389. _vq_quantlist__44u2__p7_1,
  148390. NULL,
  148391. &_vq_auxt__44u2__p7_1,
  148392. NULL,
  148393. 0
  148394. };
  148395. static long _vq_quantlist__44u2__p7_2[] = {
  148396. 6,
  148397. 5,
  148398. 7,
  148399. 4,
  148400. 8,
  148401. 3,
  148402. 9,
  148403. 2,
  148404. 10,
  148405. 1,
  148406. 11,
  148407. 0,
  148408. 12,
  148409. };
  148410. static long _vq_lengthlist__44u2__p7_2[] = {
  148411. 2, 5, 5, 6, 6, 7, 7, 8, 7, 8, 8, 8, 8, 5, 6, 6,
  148412. 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 5, 6, 6, 7, 7, 8,
  148413. 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7, 8, 8, 8, 8, 8,
  148414. 9, 9, 9, 9, 6, 7, 7, 8, 7, 8, 8, 9, 9, 9, 9, 9,
  148415. 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 7, 8,
  148416. 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 9,
  148417. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  148418. 9, 9, 9, 9, 9, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148419. 9, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8,
  148420. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9,
  148421. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148422. };
  148423. static float _vq_quantthresh__44u2__p7_2[] = {
  148424. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  148425. 2.5, 3.5, 4.5, 5.5,
  148426. };
  148427. static long _vq_quantmap__44u2__p7_2[] = {
  148428. 11, 9, 7, 5, 3, 1, 0, 2,
  148429. 4, 6, 8, 10, 12,
  148430. };
  148431. static encode_aux_threshmatch _vq_auxt__44u2__p7_2 = {
  148432. _vq_quantthresh__44u2__p7_2,
  148433. _vq_quantmap__44u2__p7_2,
  148434. 13,
  148435. 13
  148436. };
  148437. static static_codebook _44u2__p7_2 = {
  148438. 2, 169,
  148439. _vq_lengthlist__44u2__p7_2,
  148440. 1, -531103744, 1611661312, 4, 0,
  148441. _vq_quantlist__44u2__p7_2,
  148442. NULL,
  148443. &_vq_auxt__44u2__p7_2,
  148444. NULL,
  148445. 0
  148446. };
  148447. static long _huff_lengthlist__44u2__short[] = {
  148448. 13,15,17,17,15,15,12,17,11, 9, 7,10,10, 9,12,17,
  148449. 10, 6, 3, 6, 5, 7,10,17,15,10, 6, 9, 8, 9,11,17,
  148450. 15, 8, 4, 7, 3, 5, 9,16,16,10, 5, 8, 4, 5, 8,16,
  148451. 13,11, 5, 8, 3, 3, 5,14,13,12, 7,10, 5, 5, 7,14,
  148452. };
  148453. static static_codebook _huff_book__44u2__short = {
  148454. 2, 64,
  148455. _huff_lengthlist__44u2__short,
  148456. 0, 0, 0, 0, 0,
  148457. NULL,
  148458. NULL,
  148459. NULL,
  148460. NULL,
  148461. 0
  148462. };
  148463. static long _huff_lengthlist__44u3__long[] = {
  148464. 6, 9,13,12,14,11,10,13, 8, 4, 5, 7, 8, 7, 8,12,
  148465. 11, 4, 3, 5, 5, 7, 9,14,11, 6, 5, 6, 6, 6, 7,13,
  148466. 13, 7, 5, 6, 4, 5, 7,14,11, 7, 6, 6, 5, 5, 6,13,
  148467. 9, 7, 8, 6, 7, 5, 3, 9, 9,12,13,12,14,10, 6, 7,
  148468. };
  148469. static static_codebook _huff_book__44u3__long = {
  148470. 2, 64,
  148471. _huff_lengthlist__44u3__long,
  148472. 0, 0, 0, 0, 0,
  148473. NULL,
  148474. NULL,
  148475. NULL,
  148476. NULL,
  148477. 0
  148478. };
  148479. static long _vq_quantlist__44u3__p1_0[] = {
  148480. 1,
  148481. 0,
  148482. 2,
  148483. };
  148484. static long _vq_lengthlist__44u3__p1_0[] = {
  148485. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  148486. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  148487. 11, 8,11,11, 8,11,11,11,13,14,11,14,14, 8,11,11,
  148488. 10,14,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  148489. 11,11,11,14,14,10,12,14, 8,11,11,11,14,14,11,14,
  148490. 13,
  148491. };
  148492. static float _vq_quantthresh__44u3__p1_0[] = {
  148493. -0.5, 0.5,
  148494. };
  148495. static long _vq_quantmap__44u3__p1_0[] = {
  148496. 1, 0, 2,
  148497. };
  148498. static encode_aux_threshmatch _vq_auxt__44u3__p1_0 = {
  148499. _vq_quantthresh__44u3__p1_0,
  148500. _vq_quantmap__44u3__p1_0,
  148501. 3,
  148502. 3
  148503. };
  148504. static static_codebook _44u3__p1_0 = {
  148505. 4, 81,
  148506. _vq_lengthlist__44u3__p1_0,
  148507. 1, -535822336, 1611661312, 2, 0,
  148508. _vq_quantlist__44u3__p1_0,
  148509. NULL,
  148510. &_vq_auxt__44u3__p1_0,
  148511. NULL,
  148512. 0
  148513. };
  148514. static long _vq_quantlist__44u3__p2_0[] = {
  148515. 1,
  148516. 0,
  148517. 2,
  148518. };
  148519. static long _vq_lengthlist__44u3__p2_0[] = {
  148520. 2, 5, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  148521. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 7, 8,
  148522. 8, 6, 8, 8, 7, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  148523. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 7, 8, 8, 6,
  148524. 8, 8, 8,10,10, 8, 8,10, 7, 8, 8, 8,10,10, 8,10,
  148525. 9,
  148526. };
  148527. static float _vq_quantthresh__44u3__p2_0[] = {
  148528. -0.5, 0.5,
  148529. };
  148530. static long _vq_quantmap__44u3__p2_0[] = {
  148531. 1, 0, 2,
  148532. };
  148533. static encode_aux_threshmatch _vq_auxt__44u3__p2_0 = {
  148534. _vq_quantthresh__44u3__p2_0,
  148535. _vq_quantmap__44u3__p2_0,
  148536. 3,
  148537. 3
  148538. };
  148539. static static_codebook _44u3__p2_0 = {
  148540. 4, 81,
  148541. _vq_lengthlist__44u3__p2_0,
  148542. 1, -535822336, 1611661312, 2, 0,
  148543. _vq_quantlist__44u3__p2_0,
  148544. NULL,
  148545. &_vq_auxt__44u3__p2_0,
  148546. NULL,
  148547. 0
  148548. };
  148549. static long _vq_quantlist__44u3__p3_0[] = {
  148550. 2,
  148551. 1,
  148552. 3,
  148553. 0,
  148554. 4,
  148555. };
  148556. static long _vq_lengthlist__44u3__p3_0[] = {
  148557. 2, 4, 4, 7, 7, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  148558. 9, 9,12,12, 8, 9, 9,11,12, 5, 7, 7,10,10, 7, 9,
  148559. 9,11,11, 7, 9, 9,10,11,10,11,11,13,13, 9,10,11,
  148560. 13,13, 5, 7, 7,10,10, 7, 9, 9,11,10, 7, 9, 9,11,
  148561. 11, 9,11,10,13,13,10,11,11,14,13, 8,10,10,14,13,
  148562. 10,11,11,15,14, 9,11,11,14,14,13,14,13,16,16,12,
  148563. 13,13,15,15, 8,10,10,13,14, 9,11,11,14,14,10,11,
  148564. 11,14,15,12,13,13,15,15,13,14,14,15,16, 5, 7, 7,
  148565. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,12,10,11,11,14,
  148566. 14,10,11,11,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  148567. 9,11,11,13,13,12,12,13,15,15,11,12,13,15,16, 7,
  148568. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  148569. 12,15,13,11,13,13,15,16, 9,12,11,15,14,11,12,13,
  148570. 16,15,11,13,13,15,16,14,14,15,17,16,13,15,16, 0,
  148571. 17, 9,11,11,15,15,10,13,12,15,15,11,13,13,15,16,
  148572. 13,15,13,16,15,14,16,15, 0,19, 5, 7, 7,10,10, 7,
  148573. 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,14,10,11,
  148574. 12,14,14, 7, 9, 9,12,12, 9,11,11,14,13, 9,10,11,
  148575. 12,13,11,13,13,16,16,11,12,13,13,16, 7, 9, 9,12,
  148576. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,15,
  148577. 12,13,12,15,14, 9,11,11,15,14,11,13,12,16,16,10,
  148578. 12,12,15,15,13,15,15,17,19,13,14,15,16,17,10,12,
  148579. 12,15,15,11,13,13,16,16,11,13,13,15,16,13,15,15,
  148580. 0, 0,14,15,15,16,16, 8,10,10,14,14,10,12,12,15,
  148581. 15,10,12,11,15,16,14,15,15,19,20,13,14,14,18,16,
  148582. 9,11,11,15,15,11,13,13,17,16,11,13,13,16,16,15,
  148583. 17,17,20,20,14,15,16,17,20, 9,11,11,15,15,10,13,
  148584. 12,16,15,11,13,13,15,17,14,16,15,18, 0,14,16,15,
  148585. 18,20,12,14,14, 0, 0,14,14,16, 0, 0,13,16,15, 0,
  148586. 0,17,17,18, 0, 0,16,17,19,19, 0,12,14,14,18, 0,
  148587. 12,16,14, 0,17,13,15,15,18, 0,16,18,17, 0,17,16,
  148588. 18,17, 0, 0, 7,10,10,14,14,10,12,11,15,15,10,12,
  148589. 12,16,15,13,15,15,18, 0,14,15,15,17, 0, 9,11,11,
  148590. 15,15,11,13,13,16,16,11,12,13,16,16,14,15,16,17,
  148591. 17,14,16,16,16,18, 9,11,12,16,16,11,13,13,17,17,
  148592. 11,14,13,20,17,15,16,16,19, 0,15,16,17, 0,19,11,
  148593. 13,14,17,16,14,15,15,20,18,13,14,15,17,19,16,18,
  148594. 18, 0,20,16,16,19,17, 0,12,15,14,17, 0,14,15,15,
  148595. 18,19,13,16,15,19,20,15,18,18, 0,20,17, 0,16, 0,
  148596. 0,
  148597. };
  148598. static float _vq_quantthresh__44u3__p3_0[] = {
  148599. -1.5, -0.5, 0.5, 1.5,
  148600. };
  148601. static long _vq_quantmap__44u3__p3_0[] = {
  148602. 3, 1, 0, 2, 4,
  148603. };
  148604. static encode_aux_threshmatch _vq_auxt__44u3__p3_0 = {
  148605. _vq_quantthresh__44u3__p3_0,
  148606. _vq_quantmap__44u3__p3_0,
  148607. 5,
  148608. 5
  148609. };
  148610. static static_codebook _44u3__p3_0 = {
  148611. 4, 625,
  148612. _vq_lengthlist__44u3__p3_0,
  148613. 1, -533725184, 1611661312, 3, 0,
  148614. _vq_quantlist__44u3__p3_0,
  148615. NULL,
  148616. &_vq_auxt__44u3__p3_0,
  148617. NULL,
  148618. 0
  148619. };
  148620. static long _vq_quantlist__44u3__p4_0[] = {
  148621. 2,
  148622. 1,
  148623. 3,
  148624. 0,
  148625. 4,
  148626. };
  148627. static long _vq_lengthlist__44u3__p4_0[] = {
  148628. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  148629. 9, 9,11,11, 9, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  148630. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  148631. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  148632. 10, 9,10, 9,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  148633. 9,10,10,13,12, 9,10,10,12,13,12,12,12,14,14,11,
  148634. 12,12,13,14, 9, 9,10,12,12, 9,10,10,12,12, 9,10,
  148635. 10,12,13,11,12,11,14,13,12,12,12,14,13, 5, 7, 7,
  148636. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  148637. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  148638. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  148639. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  148640. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  148641. 13,13,10,11,11,13,13,12,12,13,12,15,12,13,13,15,
  148642. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  148643. 12,13,11,15,13,12,13,13,15,15, 5, 7, 7, 9, 9, 7,
  148644. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  148645. 11,12,12, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  148646. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  148647. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  148648. 11,11,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  148649. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  148650. 11,12,13,10,11,11,13,13,10,11,11,13,13,12,13,13,
  148651. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  148652. 13, 9,10,10,13,13,12,13,13,15,14,12,12,12,14,13,
  148653. 9,10,10,13,12,10,11,11,13,13,10,11,11,14,12,13,
  148654. 13,14,14,16,12,13,13,15,15, 9,10,10,13,13,10,11,
  148655. 10,14,13,10,11,11,13,14,12,14,13,15,14,13,13,13,
  148656. 15,15,11,13,12,15,14,11,12,13,14,15,12,13,13,16,
  148657. 14,14,12,15,12,16,14,15,15,17,15,11,12,12,14,14,
  148658. 11,13,11,15,14,12,13,13,15,15,13,15,12,17,13,14,
  148659. 15,15,16,16, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  148660. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  148661. 13,12,10,11,11,14,13,10,10,11,13,14,12,13,13,15,
  148662. 15,12,12,13,14,16, 9,10,10,13,13,10,11,11,13,14,
  148663. 10,11,11,14,13,12,13,13,14,15,13,14,13,16,14,11,
  148664. 12,12,14,14,12,13,13,15,14,11,12,13,14,15,14,15,
  148665. 15,16,16,13,13,15,13,16,11,12,12,14,15,12,13,13,
  148666. 14,15,11,13,12,15,14,14,15,15,16,16,14,15,12,16,
  148667. 13,
  148668. };
  148669. static float _vq_quantthresh__44u3__p4_0[] = {
  148670. -1.5, -0.5, 0.5, 1.5,
  148671. };
  148672. static long _vq_quantmap__44u3__p4_0[] = {
  148673. 3, 1, 0, 2, 4,
  148674. };
  148675. static encode_aux_threshmatch _vq_auxt__44u3__p4_0 = {
  148676. _vq_quantthresh__44u3__p4_0,
  148677. _vq_quantmap__44u3__p4_0,
  148678. 5,
  148679. 5
  148680. };
  148681. static static_codebook _44u3__p4_0 = {
  148682. 4, 625,
  148683. _vq_lengthlist__44u3__p4_0,
  148684. 1, -533725184, 1611661312, 3, 0,
  148685. _vq_quantlist__44u3__p4_0,
  148686. NULL,
  148687. &_vq_auxt__44u3__p4_0,
  148688. NULL,
  148689. 0
  148690. };
  148691. static long _vq_quantlist__44u3__p5_0[] = {
  148692. 4,
  148693. 3,
  148694. 5,
  148695. 2,
  148696. 6,
  148697. 1,
  148698. 7,
  148699. 0,
  148700. 8,
  148701. };
  148702. static long _vq_lengthlist__44u3__p5_0[] = {
  148703. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  148704. 10,10, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  148705. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,10, 7, 8, 8,
  148706. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  148707. 10,10,11,10,11,11,12,12, 9,10,10,10,10,11,11,12,
  148708. 12,
  148709. };
  148710. static float _vq_quantthresh__44u3__p5_0[] = {
  148711. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  148712. };
  148713. static long _vq_quantmap__44u3__p5_0[] = {
  148714. 7, 5, 3, 1, 0, 2, 4, 6,
  148715. 8,
  148716. };
  148717. static encode_aux_threshmatch _vq_auxt__44u3__p5_0 = {
  148718. _vq_quantthresh__44u3__p5_0,
  148719. _vq_quantmap__44u3__p5_0,
  148720. 9,
  148721. 9
  148722. };
  148723. static static_codebook _44u3__p5_0 = {
  148724. 2, 81,
  148725. _vq_lengthlist__44u3__p5_0,
  148726. 1, -531628032, 1611661312, 4, 0,
  148727. _vq_quantlist__44u3__p5_0,
  148728. NULL,
  148729. &_vq_auxt__44u3__p5_0,
  148730. NULL,
  148731. 0
  148732. };
  148733. static long _vq_quantlist__44u3__p6_0[] = {
  148734. 6,
  148735. 5,
  148736. 7,
  148737. 4,
  148738. 8,
  148739. 3,
  148740. 9,
  148741. 2,
  148742. 10,
  148743. 1,
  148744. 11,
  148745. 0,
  148746. 12,
  148747. };
  148748. static long _vq_lengthlist__44u3__p6_0[] = {
  148749. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,11,13,14, 4, 6, 5,
  148750. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  148751. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  148752. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  148753. 15, 8, 9, 9,11,10,11,11,12,12,13,13,15,16, 8, 9,
  148754. 9,10,11,11,11,12,12,13,13,16,16,10,10,11,11,11,
  148755. 12,12,13,13,13,14,17,16, 9,10,11,12,11,12,12,13,
  148756. 13,13,13,16,18,11,12,11,12,12,13,13,13,14,15,14,
  148757. 17,17,11,11,12,12,12,13,13,13,14,14,15,18,17,14,
  148758. 15,15,15,15,16,16,17,17,19,18, 0,20,14,15,14,15,
  148759. 15,16,16,16,17,18,16,20,18,
  148760. };
  148761. static float _vq_quantthresh__44u3__p6_0[] = {
  148762. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  148763. 12.5, 17.5, 22.5, 27.5,
  148764. };
  148765. static long _vq_quantmap__44u3__p6_0[] = {
  148766. 11, 9, 7, 5, 3, 1, 0, 2,
  148767. 4, 6, 8, 10, 12,
  148768. };
  148769. static encode_aux_threshmatch _vq_auxt__44u3__p6_0 = {
  148770. _vq_quantthresh__44u3__p6_0,
  148771. _vq_quantmap__44u3__p6_0,
  148772. 13,
  148773. 13
  148774. };
  148775. static static_codebook _44u3__p6_0 = {
  148776. 2, 169,
  148777. _vq_lengthlist__44u3__p6_0,
  148778. 1, -526516224, 1616117760, 4, 0,
  148779. _vq_quantlist__44u3__p6_0,
  148780. NULL,
  148781. &_vq_auxt__44u3__p6_0,
  148782. NULL,
  148783. 0
  148784. };
  148785. static long _vq_quantlist__44u3__p6_1[] = {
  148786. 2,
  148787. 1,
  148788. 3,
  148789. 0,
  148790. 4,
  148791. };
  148792. static long _vq_lengthlist__44u3__p6_1[] = {
  148793. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  148794. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  148795. };
  148796. static float _vq_quantthresh__44u3__p6_1[] = {
  148797. -1.5, -0.5, 0.5, 1.5,
  148798. };
  148799. static long _vq_quantmap__44u3__p6_1[] = {
  148800. 3, 1, 0, 2, 4,
  148801. };
  148802. static encode_aux_threshmatch _vq_auxt__44u3__p6_1 = {
  148803. _vq_quantthresh__44u3__p6_1,
  148804. _vq_quantmap__44u3__p6_1,
  148805. 5,
  148806. 5
  148807. };
  148808. static static_codebook _44u3__p6_1 = {
  148809. 2, 25,
  148810. _vq_lengthlist__44u3__p6_1,
  148811. 1, -533725184, 1611661312, 3, 0,
  148812. _vq_quantlist__44u3__p6_1,
  148813. NULL,
  148814. &_vq_auxt__44u3__p6_1,
  148815. NULL,
  148816. 0
  148817. };
  148818. static long _vq_quantlist__44u3__p7_0[] = {
  148819. 4,
  148820. 3,
  148821. 5,
  148822. 2,
  148823. 6,
  148824. 1,
  148825. 7,
  148826. 0,
  148827. 8,
  148828. };
  148829. static long _vq_lengthlist__44u3__p7_0[] = {
  148830. 1, 3, 3,10,10,10,10,10,10, 4,10,10,10,10,10,10,
  148831. 10,10, 4,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148832. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148833. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148834. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  148835. 9,
  148836. };
  148837. static float _vq_quantthresh__44u3__p7_0[] = {
  148838. -892.5, -637.5, -382.5, -127.5, 127.5, 382.5, 637.5, 892.5,
  148839. };
  148840. static long _vq_quantmap__44u3__p7_0[] = {
  148841. 7, 5, 3, 1, 0, 2, 4, 6,
  148842. 8,
  148843. };
  148844. static encode_aux_threshmatch _vq_auxt__44u3__p7_0 = {
  148845. _vq_quantthresh__44u3__p7_0,
  148846. _vq_quantmap__44u3__p7_0,
  148847. 9,
  148848. 9
  148849. };
  148850. static static_codebook _44u3__p7_0 = {
  148851. 2, 81,
  148852. _vq_lengthlist__44u3__p7_0,
  148853. 1, -515907584, 1627381760, 4, 0,
  148854. _vq_quantlist__44u3__p7_0,
  148855. NULL,
  148856. &_vq_auxt__44u3__p7_0,
  148857. NULL,
  148858. 0
  148859. };
  148860. static long _vq_quantlist__44u3__p7_1[] = {
  148861. 7,
  148862. 6,
  148863. 8,
  148864. 5,
  148865. 9,
  148866. 4,
  148867. 10,
  148868. 3,
  148869. 11,
  148870. 2,
  148871. 12,
  148872. 1,
  148873. 13,
  148874. 0,
  148875. 14,
  148876. };
  148877. static long _vq_lengthlist__44u3__p7_1[] = {
  148878. 1, 4, 4, 6, 6, 7, 6, 8, 7, 9, 8,10, 9,11,11, 4,
  148879. 7, 7, 8, 7, 9, 9,10,10,11,11,11,11,12,12, 4, 7,
  148880. 7, 7, 7, 9, 9,10,10,11,11,12,12,12,11, 6, 8, 8,
  148881. 9, 9,10,10,11,11,12,12,13,12,13,13, 6, 8, 8, 9,
  148882. 9,10,11,11,11,12,12,13,14,13,13, 8, 9, 9,11,11,
  148883. 12,12,12,13,14,13,14,14,14,15, 8, 9, 9,11,11,11,
  148884. 12,13,14,13,14,15,17,14,15, 9,10,10,12,12,13,13,
  148885. 13,14,15,15,15,16,16,16, 9,11,11,12,12,13,13,14,
  148886. 14,14,15,16,16,16,16,10,12,12,13,13,14,14,15,15,
  148887. 15,16,17,17,17,17,10,12,11,13,13,15,14,15,14,16,
  148888. 17,16,16,16,16,11,13,12,14,14,14,14,15,16,17,16,
  148889. 17,17,17,17,11,13,12,14,14,14,15,17,16,17,17,17,
  148890. 17,17,17,12,13,13,15,16,15,16,17,17,16,16,17,17,
  148891. 17,17,12,13,13,15,15,15,16,17,17,17,16,17,16,17,
  148892. 17,
  148893. };
  148894. static float _vq_quantthresh__44u3__p7_1[] = {
  148895. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  148896. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  148897. };
  148898. static long _vq_quantmap__44u3__p7_1[] = {
  148899. 13, 11, 9, 7, 5, 3, 1, 0,
  148900. 2, 4, 6, 8, 10, 12, 14,
  148901. };
  148902. static encode_aux_threshmatch _vq_auxt__44u3__p7_1 = {
  148903. _vq_quantthresh__44u3__p7_1,
  148904. _vq_quantmap__44u3__p7_1,
  148905. 15,
  148906. 15
  148907. };
  148908. static static_codebook _44u3__p7_1 = {
  148909. 2, 225,
  148910. _vq_lengthlist__44u3__p7_1,
  148911. 1, -522338304, 1620115456, 4, 0,
  148912. _vq_quantlist__44u3__p7_1,
  148913. NULL,
  148914. &_vq_auxt__44u3__p7_1,
  148915. NULL,
  148916. 0
  148917. };
  148918. static long _vq_quantlist__44u3__p7_2[] = {
  148919. 8,
  148920. 7,
  148921. 9,
  148922. 6,
  148923. 10,
  148924. 5,
  148925. 11,
  148926. 4,
  148927. 12,
  148928. 3,
  148929. 13,
  148930. 2,
  148931. 14,
  148932. 1,
  148933. 15,
  148934. 0,
  148935. 16,
  148936. };
  148937. static long _vq_lengthlist__44u3__p7_2[] = {
  148938. 2, 5, 5, 7, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  148939. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148940. 10,10, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9,
  148941. 9,10, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148942. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  148943. 9,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148944. 10,10,10,10,10,10, 7, 8, 8, 9, 8, 9, 9, 9, 9,10,
  148945. 9,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  148946. 9,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9,10,
  148947. 9,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,10,
  148948. 9,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  148949. 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,
  148950. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10,
  148951. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  148952. 10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,10,
  148953. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,11, 9,
  148954. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  148955. 9,10,10,10,10,10,10,10,10,10,10,10,11,11,11,10,
  148956. 11,
  148957. };
  148958. static float _vq_quantthresh__44u3__p7_2[] = {
  148959. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  148960. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  148961. };
  148962. static long _vq_quantmap__44u3__p7_2[] = {
  148963. 15, 13, 11, 9, 7, 5, 3, 1,
  148964. 0, 2, 4, 6, 8, 10, 12, 14,
  148965. 16,
  148966. };
  148967. static encode_aux_threshmatch _vq_auxt__44u3__p7_2 = {
  148968. _vq_quantthresh__44u3__p7_2,
  148969. _vq_quantmap__44u3__p7_2,
  148970. 17,
  148971. 17
  148972. };
  148973. static static_codebook _44u3__p7_2 = {
  148974. 2, 289,
  148975. _vq_lengthlist__44u3__p7_2,
  148976. 1, -529530880, 1611661312, 5, 0,
  148977. _vq_quantlist__44u3__p7_2,
  148978. NULL,
  148979. &_vq_auxt__44u3__p7_2,
  148980. NULL,
  148981. 0
  148982. };
  148983. static long _huff_lengthlist__44u3__short[] = {
  148984. 14,14,14,15,13,15,12,16,10, 8, 7, 9, 9, 8,12,16,
  148985. 10, 5, 4, 6, 5, 6, 9,16,14, 8, 6, 8, 7, 8,10,16,
  148986. 14, 7, 4, 6, 3, 5, 8,16,15, 9, 5, 7, 4, 4, 7,16,
  148987. 13,10, 6, 7, 4, 3, 4,13,13,12, 7, 9, 5, 5, 6,12,
  148988. };
  148989. static static_codebook _huff_book__44u3__short = {
  148990. 2, 64,
  148991. _huff_lengthlist__44u3__short,
  148992. 0, 0, 0, 0, 0,
  148993. NULL,
  148994. NULL,
  148995. NULL,
  148996. NULL,
  148997. 0
  148998. };
  148999. static long _huff_lengthlist__44u4__long[] = {
  149000. 3, 8,12,12,13,12,11,13, 5, 4, 6, 7, 8, 8, 9,13,
  149001. 9, 5, 4, 5, 5, 7, 9,13, 9, 6, 5, 6, 6, 7, 8,12,
  149002. 12, 7, 5, 6, 4, 5, 8,13,11, 7, 6, 6, 5, 5, 6,12,
  149003. 10, 8, 8, 7, 7, 5, 3, 8,10,12,13,12,12, 9, 6, 7,
  149004. };
  149005. static static_codebook _huff_book__44u4__long = {
  149006. 2, 64,
  149007. _huff_lengthlist__44u4__long,
  149008. 0, 0, 0, 0, 0,
  149009. NULL,
  149010. NULL,
  149011. NULL,
  149012. NULL,
  149013. 0
  149014. };
  149015. static long _vq_quantlist__44u4__p1_0[] = {
  149016. 1,
  149017. 0,
  149018. 2,
  149019. };
  149020. static long _vq_lengthlist__44u4__p1_0[] = {
  149021. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  149022. 10,11, 5, 8, 8, 8,11,10, 8,11,11, 4, 8, 8, 8,11,
  149023. 11, 8,11,11, 8,11,11,11,13,14,11,15,14, 8,11,11,
  149024. 10,13,12,11,14,14, 4, 8, 8, 8,11,11, 8,11,11, 7,
  149025. 11,11,11,15,14,10,12,14, 8,11,11,11,14,14,11,14,
  149026. 13,
  149027. };
  149028. static float _vq_quantthresh__44u4__p1_0[] = {
  149029. -0.5, 0.5,
  149030. };
  149031. static long _vq_quantmap__44u4__p1_0[] = {
  149032. 1, 0, 2,
  149033. };
  149034. static encode_aux_threshmatch _vq_auxt__44u4__p1_0 = {
  149035. _vq_quantthresh__44u4__p1_0,
  149036. _vq_quantmap__44u4__p1_0,
  149037. 3,
  149038. 3
  149039. };
  149040. static static_codebook _44u4__p1_0 = {
  149041. 4, 81,
  149042. _vq_lengthlist__44u4__p1_0,
  149043. 1, -535822336, 1611661312, 2, 0,
  149044. _vq_quantlist__44u4__p1_0,
  149045. NULL,
  149046. &_vq_auxt__44u4__p1_0,
  149047. NULL,
  149048. 0
  149049. };
  149050. static long _vq_quantlist__44u4__p2_0[] = {
  149051. 1,
  149052. 0,
  149053. 2,
  149054. };
  149055. static long _vq_lengthlist__44u4__p2_0[] = {
  149056. 2, 5, 5, 5, 6, 6, 5, 6, 6, 5, 6, 6, 7, 8, 8, 6,
  149057. 8, 8, 5, 6, 6, 6, 8, 8, 7, 8, 8, 5, 7, 6, 6, 8,
  149058. 8, 6, 8, 8, 6, 8, 8, 8, 9,10, 8,10,10, 6, 8, 8,
  149059. 8,10, 8, 8,10,10, 5, 6, 6, 6, 8, 8, 6, 8, 8, 6,
  149060. 8, 8, 8,10,10, 8, 8,10, 6, 8, 8, 8,10,10, 8,10,
  149061. 9,
  149062. };
  149063. static float _vq_quantthresh__44u4__p2_0[] = {
  149064. -0.5, 0.5,
  149065. };
  149066. static long _vq_quantmap__44u4__p2_0[] = {
  149067. 1, 0, 2,
  149068. };
  149069. static encode_aux_threshmatch _vq_auxt__44u4__p2_0 = {
  149070. _vq_quantthresh__44u4__p2_0,
  149071. _vq_quantmap__44u4__p2_0,
  149072. 3,
  149073. 3
  149074. };
  149075. static static_codebook _44u4__p2_0 = {
  149076. 4, 81,
  149077. _vq_lengthlist__44u4__p2_0,
  149078. 1, -535822336, 1611661312, 2, 0,
  149079. _vq_quantlist__44u4__p2_0,
  149080. NULL,
  149081. &_vq_auxt__44u4__p2_0,
  149082. NULL,
  149083. 0
  149084. };
  149085. static long _vq_quantlist__44u4__p3_0[] = {
  149086. 2,
  149087. 1,
  149088. 3,
  149089. 0,
  149090. 4,
  149091. };
  149092. static long _vq_lengthlist__44u4__p3_0[] = {
  149093. 2, 4, 4, 8, 8, 5, 7, 7, 9, 9, 5, 7, 7, 9, 9, 8,
  149094. 10, 9,12,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  149095. 9,11,11, 7, 9, 9,11,11,10,12,11,14,14, 9,10,11,
  149096. 13,14, 5, 7, 7,10,10, 7, 9, 9,11,11, 7, 9, 9,11,
  149097. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  149098. 10,12,12,15,14, 9,11,11,15,14,13,14,14,17,17,12,
  149099. 14,14,16,16, 8,10,10,14,14, 9,11,11,14,15,10,12,
  149100. 12,14,15,12,14,13,16,16,13,14,15,15,18, 4, 7, 7,
  149101. 10,10, 7, 9, 9,12,11, 7, 9, 9,11,12,10,12,11,15,
  149102. 14,10,11,12,14,15, 7, 9, 9,12,12, 9,11,12,13,13,
  149103. 9,11,12,13,13,12,13,13,15,16,11,13,13,15,16, 7,
  149104. 9, 9,12,12, 9,11,10,13,12, 9,11,12,13,14,11,13,
  149105. 12,16,14,12,13,13,15,16,10,12,12,16,15,11,13,13,
  149106. 17,16,11,13,13,17,16,14,15,15,17,17,14,16,16,18,
  149107. 20, 9,11,11,15,16,11,13,12,16,16,11,13,13,16,17,
  149108. 14,15,14,18,16,14,16,16,17,20, 5, 7, 7,10,10, 7,
  149109. 9, 9,12,11, 7, 9,10,11,12,10,12,11,15,15,10,12,
  149110. 12,14,14, 7, 9, 9,12,12, 9,12,11,14,13, 9,10,11,
  149111. 12,13,12,13,14,16,16,11,12,13,14,16, 7, 9, 9,12,
  149112. 12, 9,12,11,13,13, 9,12,11,13,13,11,13,13,16,16,
  149113. 12,13,13,16,15, 9,11,11,16,14,11,13,13,16,16,11,
  149114. 12,13,16,16,14,16,16,17,17,13,14,15,16,17,10,12,
  149115. 12,15,15,11,13,13,16,17,11,13,13,16,16,14,16,15,
  149116. 19,19,14,15,15,17,18, 8,10,10,14,14,10,12,12,15,
  149117. 15,10,12,12,16,16,14,16,15,20,19,13,15,15,17,16,
  149118. 9,12,12,16,16,11,13,13,16,18,11,14,13,16,17,16,
  149119. 17,16,20, 0,15,16,18,18,20, 9,11,11,15,15,11,14,
  149120. 12,17,16,11,13,13,17,17,15,17,15,20,20,14,16,16,
  149121. 17, 0,13,15,14,18,16,14,15,16, 0,18,14,16,16, 0,
  149122. 0,18,16, 0, 0,20,16,18,18, 0, 0,12,14,14,17,18,
  149123. 13,15,14,20,18,14,16,15,19,19,16,20,16, 0,18,16,
  149124. 19,17,19, 0, 8,10,10,14,14,10,12,12,16,15,10,12,
  149125. 12,16,16,13,15,15,18,17,14,16,16,19, 0, 9,11,11,
  149126. 16,15,11,14,13,18,17,11,12,13,17,18,14,17,16,18,
  149127. 18,15,16,17,18,18, 9,12,12,16,16,11,13,13,16,18,
  149128. 11,14,13,17,17,15,16,16,18,20,16,17,17,20,20,12,
  149129. 14,14,18,17,14,16,16, 0,19,13,14,15,18, 0,16, 0,
  149130. 0, 0, 0,16,16, 0,19,20,13,15,14, 0, 0,14,16,16,
  149131. 18,19,14,16,15, 0,20,16,20,18, 0,20,17,20,17, 0,
  149132. 0,
  149133. };
  149134. static float _vq_quantthresh__44u4__p3_0[] = {
  149135. -1.5, -0.5, 0.5, 1.5,
  149136. };
  149137. static long _vq_quantmap__44u4__p3_0[] = {
  149138. 3, 1, 0, 2, 4,
  149139. };
  149140. static encode_aux_threshmatch _vq_auxt__44u4__p3_0 = {
  149141. _vq_quantthresh__44u4__p3_0,
  149142. _vq_quantmap__44u4__p3_0,
  149143. 5,
  149144. 5
  149145. };
  149146. static static_codebook _44u4__p3_0 = {
  149147. 4, 625,
  149148. _vq_lengthlist__44u4__p3_0,
  149149. 1, -533725184, 1611661312, 3, 0,
  149150. _vq_quantlist__44u4__p3_0,
  149151. NULL,
  149152. &_vq_auxt__44u4__p3_0,
  149153. NULL,
  149154. 0
  149155. };
  149156. static long _vq_quantlist__44u4__p4_0[] = {
  149157. 2,
  149158. 1,
  149159. 3,
  149160. 0,
  149161. 4,
  149162. };
  149163. static long _vq_lengthlist__44u4__p4_0[] = {
  149164. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 9,
  149165. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  149166. 8,10,10, 7, 7, 8,10,10, 9,10,10,11,12, 9,10,10,
  149167. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  149168. 10, 9,10,10,12,11, 9,10,10,12,11, 9,10, 9,12,12,
  149169. 9,10,10,13,12, 9,10,10,12,12,12,12,12,14,14,11,
  149170. 12,12,13,14, 9, 9,10,12,12, 9,10,10,13,13, 9,10,
  149171. 10,12,13,11,12,12,14,13,11,12,12,14,14, 5, 7, 7,
  149172. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10,10,10,10,12,
  149173. 12, 9,10,10,12,12, 7, 8, 8,11,10, 8, 8, 9,11,11,
  149174. 8, 9, 9,11,11,11,11,11,12,13,10,11,11,13,13, 6,
  149175. 8, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149176. 10,13,11,10,11,11,13,13, 9,11,10,13,12,10,11,11,
  149177. 13,14,10,11,11,14,13,12,12,13,12,15,12,13,13,15,
  149178. 15, 9,10,10,12,13,10,11,10,13,12,10,11,11,13,14,
  149179. 12,13,11,15,13,13,13,13,15,15, 5, 7, 7, 9, 9, 7,
  149180. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12,10,10,
  149181. 11,12,13, 6, 8, 8,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149182. 10,11,10,11,11,13,13,10,10,11,11,13, 7, 8, 8,10,
  149183. 11, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,11,13,13,
  149184. 11,12,11,13,12, 9,10,10,13,12,10,11,11,14,13,10,
  149185. 10,11,12,13,12,13,13,15,15,12,11,13,13,14, 9,10,
  149186. 11,12,13,10,11,11,13,14,10,11,11,13,13,12,13,13,
  149187. 15,15,12,13,12,15,12, 8, 9, 9,12,12, 9,11,10,13,
  149188. 13, 9,10,10,13,13,12,13,13,15,15,12,12,12,14,14,
  149189. 9,10,10,13,13,10,11,11,13,14,10,11,11,14,13,13,
  149190. 13,14,14,16,13,13,13,15,15, 9,10,10,13,13,10,11,
  149191. 10,14,13,10,11,11,13,14,12,14,13,16,14,12,13,13,
  149192. 14,15,11,12,12,15,14,11,12,13,14,15,12,13,13,16,
  149193. 15,14,12,15,12,16,14,15,15,16,16,11,12,12,14,14,
  149194. 11,13,12,15,14,12,13,13,15,16,13,15,13,17,13,14,
  149195. 15,15,16,17, 8, 9, 9,12,12, 9,10,10,12,13, 9,10,
  149196. 10,13,13,12,12,12,14,14,12,13,13,15,15, 9,10,10,
  149197. 13,12,10,11,11,14,13,10,10,11,13,14,13,13,13,15,
  149198. 15,12,13,14,14,16, 9,10,10,13,13,10,11,11,13,14,
  149199. 10,11,11,14,14,13,13,13,15,15,13,14,13,16,14,11,
  149200. 12,12,15,14,12,13,13,16,15,11,12,13,14,15,14,15,
  149201. 15,17,16,13,13,15,13,16,11,12,13,14,15,13,13,13,
  149202. 15,16,11,13,12,15,14,14,15,15,16,16,14,15,12,17,
  149203. 13,
  149204. };
  149205. static float _vq_quantthresh__44u4__p4_0[] = {
  149206. -1.5, -0.5, 0.5, 1.5,
  149207. };
  149208. static long _vq_quantmap__44u4__p4_0[] = {
  149209. 3, 1, 0, 2, 4,
  149210. };
  149211. static encode_aux_threshmatch _vq_auxt__44u4__p4_0 = {
  149212. _vq_quantthresh__44u4__p4_0,
  149213. _vq_quantmap__44u4__p4_0,
  149214. 5,
  149215. 5
  149216. };
  149217. static static_codebook _44u4__p4_0 = {
  149218. 4, 625,
  149219. _vq_lengthlist__44u4__p4_0,
  149220. 1, -533725184, 1611661312, 3, 0,
  149221. _vq_quantlist__44u4__p4_0,
  149222. NULL,
  149223. &_vq_auxt__44u4__p4_0,
  149224. NULL,
  149225. 0
  149226. };
  149227. static long _vq_quantlist__44u4__p5_0[] = {
  149228. 4,
  149229. 3,
  149230. 5,
  149231. 2,
  149232. 6,
  149233. 1,
  149234. 7,
  149235. 0,
  149236. 8,
  149237. };
  149238. static long _vq_lengthlist__44u4__p5_0[] = {
  149239. 2, 3, 3, 6, 6, 7, 7, 9, 9, 4, 5, 5, 7, 7, 8, 8,
  149240. 10, 9, 4, 5, 5, 7, 7, 8, 8,10,10, 6, 7, 7, 8, 8,
  149241. 9, 9,11,10, 6, 7, 7, 8, 8, 9, 9,10,11, 7, 8, 8,
  149242. 9, 9,10,10,11,11, 7, 8, 8, 9, 9,10,10,11,11, 9,
  149243. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  149244. 12,
  149245. };
  149246. static float _vq_quantthresh__44u4__p5_0[] = {
  149247. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149248. };
  149249. static long _vq_quantmap__44u4__p5_0[] = {
  149250. 7, 5, 3, 1, 0, 2, 4, 6,
  149251. 8,
  149252. };
  149253. static encode_aux_threshmatch _vq_auxt__44u4__p5_0 = {
  149254. _vq_quantthresh__44u4__p5_0,
  149255. _vq_quantmap__44u4__p5_0,
  149256. 9,
  149257. 9
  149258. };
  149259. static static_codebook _44u4__p5_0 = {
  149260. 2, 81,
  149261. _vq_lengthlist__44u4__p5_0,
  149262. 1, -531628032, 1611661312, 4, 0,
  149263. _vq_quantlist__44u4__p5_0,
  149264. NULL,
  149265. &_vq_auxt__44u4__p5_0,
  149266. NULL,
  149267. 0
  149268. };
  149269. static long _vq_quantlist__44u4__p6_0[] = {
  149270. 6,
  149271. 5,
  149272. 7,
  149273. 4,
  149274. 8,
  149275. 3,
  149276. 9,
  149277. 2,
  149278. 10,
  149279. 1,
  149280. 11,
  149281. 0,
  149282. 12,
  149283. };
  149284. static long _vq_lengthlist__44u4__p6_0[] = {
  149285. 1, 4, 4, 6, 6, 8, 8, 9, 9,11,10,13,13, 4, 6, 5,
  149286. 8, 8, 9, 9,10,10,11,11,14,14, 4, 6, 6, 8, 8, 9,
  149287. 9,10,10,11,11,14,14, 6, 8, 8, 9, 9,10,10,11,11,
  149288. 12,12,15,15, 6, 8, 8, 9, 9,10,11,11,11,12,12,15,
  149289. 15, 8, 9, 9,11,10,11,11,12,12,13,13,16,16, 8, 9,
  149290. 9,10,10,11,11,12,12,13,13,16,16,10,10,10,12,11,
  149291. 12,12,13,13,14,14,16,16,10,10,10,11,12,12,12,13,
  149292. 13,13,14,16,17,11,12,11,12,12,13,13,14,14,15,14,
  149293. 18,17,11,11,12,12,12,13,13,14,14,14,15,19,18,14,
  149294. 15,14,15,15,17,16,17,17,17,17,21, 0,14,15,15,16,
  149295. 16,16,16,17,17,18,17,20,21,
  149296. };
  149297. static float _vq_quantthresh__44u4__p6_0[] = {
  149298. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  149299. 12.5, 17.5, 22.5, 27.5,
  149300. };
  149301. static long _vq_quantmap__44u4__p6_0[] = {
  149302. 11, 9, 7, 5, 3, 1, 0, 2,
  149303. 4, 6, 8, 10, 12,
  149304. };
  149305. static encode_aux_threshmatch _vq_auxt__44u4__p6_0 = {
  149306. _vq_quantthresh__44u4__p6_0,
  149307. _vq_quantmap__44u4__p6_0,
  149308. 13,
  149309. 13
  149310. };
  149311. static static_codebook _44u4__p6_0 = {
  149312. 2, 169,
  149313. _vq_lengthlist__44u4__p6_0,
  149314. 1, -526516224, 1616117760, 4, 0,
  149315. _vq_quantlist__44u4__p6_0,
  149316. NULL,
  149317. &_vq_auxt__44u4__p6_0,
  149318. NULL,
  149319. 0
  149320. };
  149321. static long _vq_quantlist__44u4__p6_1[] = {
  149322. 2,
  149323. 1,
  149324. 3,
  149325. 0,
  149326. 4,
  149327. };
  149328. static long _vq_lengthlist__44u4__p6_1[] = {
  149329. 2, 4, 4, 5, 5, 4, 5, 5, 6, 5, 4, 5, 5, 5, 6, 5,
  149330. 6, 5, 6, 6, 5, 5, 6, 6, 6,
  149331. };
  149332. static float _vq_quantthresh__44u4__p6_1[] = {
  149333. -1.5, -0.5, 0.5, 1.5,
  149334. };
  149335. static long _vq_quantmap__44u4__p6_1[] = {
  149336. 3, 1, 0, 2, 4,
  149337. };
  149338. static encode_aux_threshmatch _vq_auxt__44u4__p6_1 = {
  149339. _vq_quantthresh__44u4__p6_1,
  149340. _vq_quantmap__44u4__p6_1,
  149341. 5,
  149342. 5
  149343. };
  149344. static static_codebook _44u4__p6_1 = {
  149345. 2, 25,
  149346. _vq_lengthlist__44u4__p6_1,
  149347. 1, -533725184, 1611661312, 3, 0,
  149348. _vq_quantlist__44u4__p6_1,
  149349. NULL,
  149350. &_vq_auxt__44u4__p6_1,
  149351. NULL,
  149352. 0
  149353. };
  149354. static long _vq_quantlist__44u4__p7_0[] = {
  149355. 6,
  149356. 5,
  149357. 7,
  149358. 4,
  149359. 8,
  149360. 3,
  149361. 9,
  149362. 2,
  149363. 10,
  149364. 1,
  149365. 11,
  149366. 0,
  149367. 12,
  149368. };
  149369. static long _vq_lengthlist__44u4__p7_0[] = {
  149370. 1, 3, 3,12,12,12,12,12,12,12,12,12,12, 3,12,11,
  149371. 12,12,12,12,12,12,12,12,12,12, 4,11,10,12,12,12,
  149372. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149373. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149374. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  149375. 12,12,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149376. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149377. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149378. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149379. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  149380. 11,11,11,11,11,11,11,11,11,
  149381. };
  149382. static float _vq_quantthresh__44u4__p7_0[] = {
  149383. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  149384. 637.5, 892.5, 1147.5, 1402.5,
  149385. };
  149386. static long _vq_quantmap__44u4__p7_0[] = {
  149387. 11, 9, 7, 5, 3, 1, 0, 2,
  149388. 4, 6, 8, 10, 12,
  149389. };
  149390. static encode_aux_threshmatch _vq_auxt__44u4__p7_0 = {
  149391. _vq_quantthresh__44u4__p7_0,
  149392. _vq_quantmap__44u4__p7_0,
  149393. 13,
  149394. 13
  149395. };
  149396. static static_codebook _44u4__p7_0 = {
  149397. 2, 169,
  149398. _vq_lengthlist__44u4__p7_0,
  149399. 1, -514332672, 1627381760, 4, 0,
  149400. _vq_quantlist__44u4__p7_0,
  149401. NULL,
  149402. &_vq_auxt__44u4__p7_0,
  149403. NULL,
  149404. 0
  149405. };
  149406. static long _vq_quantlist__44u4__p7_1[] = {
  149407. 7,
  149408. 6,
  149409. 8,
  149410. 5,
  149411. 9,
  149412. 4,
  149413. 10,
  149414. 3,
  149415. 11,
  149416. 2,
  149417. 12,
  149418. 1,
  149419. 13,
  149420. 0,
  149421. 14,
  149422. };
  149423. static long _vq_lengthlist__44u4__p7_1[] = {
  149424. 1, 4, 4, 6, 6, 7, 7, 9, 8,10, 8,10, 9,11,11, 4,
  149425. 7, 6, 8, 7, 9, 9,10,10,11,10,11,10,12,10, 4, 6,
  149426. 7, 8, 8, 9, 9,10,10,11,11,11,11,12,12, 6, 8, 8,
  149427. 10, 9,11,10,12,11,12,12,12,12,13,13, 6, 8, 8,10,
  149428. 10,10,11,11,11,12,12,13,12,13,13, 8, 9, 9,11,11,
  149429. 12,11,12,12,13,13,13,13,13,13, 8, 9, 9,11,11,11,
  149430. 12,12,12,13,13,13,13,13,13, 9,10,10,12,11,13,13,
  149431. 13,13,14,13,13,14,14,14, 9,10,11,11,12,12,13,13,
  149432. 13,13,13,14,15,14,14,10,11,11,12,12,13,13,14,14,
  149433. 14,14,14,15,16,16,10,11,11,12,13,13,13,13,15,14,
  149434. 14,15,16,15,16,10,12,12,13,13,14,14,14,15,15,15,
  149435. 15,15,15,16,11,12,12,13,13,14,14,14,15,15,15,16,
  149436. 15,17,16,11,12,12,13,13,13,15,15,14,16,16,16,16,
  149437. 16,17,11,12,12,13,13,14,14,15,14,15,15,17,17,16,
  149438. 16,
  149439. };
  149440. static float _vq_quantthresh__44u4__p7_1[] = {
  149441. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  149442. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  149443. };
  149444. static long _vq_quantmap__44u4__p7_1[] = {
  149445. 13, 11, 9, 7, 5, 3, 1, 0,
  149446. 2, 4, 6, 8, 10, 12, 14,
  149447. };
  149448. static encode_aux_threshmatch _vq_auxt__44u4__p7_1 = {
  149449. _vq_quantthresh__44u4__p7_1,
  149450. _vq_quantmap__44u4__p7_1,
  149451. 15,
  149452. 15
  149453. };
  149454. static static_codebook _44u4__p7_1 = {
  149455. 2, 225,
  149456. _vq_lengthlist__44u4__p7_1,
  149457. 1, -522338304, 1620115456, 4, 0,
  149458. _vq_quantlist__44u4__p7_1,
  149459. NULL,
  149460. &_vq_auxt__44u4__p7_1,
  149461. NULL,
  149462. 0
  149463. };
  149464. static long _vq_quantlist__44u4__p7_2[] = {
  149465. 8,
  149466. 7,
  149467. 9,
  149468. 6,
  149469. 10,
  149470. 5,
  149471. 11,
  149472. 4,
  149473. 12,
  149474. 3,
  149475. 13,
  149476. 2,
  149477. 14,
  149478. 1,
  149479. 15,
  149480. 0,
  149481. 16,
  149482. };
  149483. static long _vq_lengthlist__44u4__p7_2[] = {
  149484. 2, 5, 5, 7, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149485. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149486. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149487. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149488. 10,10,10,10, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,
  149489. 9,10, 9,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  149490. 10,10,10,10,10,10, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  149491. 9,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  149492. 10,10,10,10,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  149493. 10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,10,
  149494. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  149495. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,10,
  149496. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  149497. 10,10,10,10,10,10,10,10,10,11,10,10,10, 9, 9, 9,
  149498. 10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9,
  149499. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  149500. 10, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  149501. 9,10, 9,10,10,10,10,10,10,10,10,10,10,11,10,10,
  149502. 10,
  149503. };
  149504. static float _vq_quantthresh__44u4__p7_2[] = {
  149505. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  149506. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  149507. };
  149508. static long _vq_quantmap__44u4__p7_2[] = {
  149509. 15, 13, 11, 9, 7, 5, 3, 1,
  149510. 0, 2, 4, 6, 8, 10, 12, 14,
  149511. 16,
  149512. };
  149513. static encode_aux_threshmatch _vq_auxt__44u4__p7_2 = {
  149514. _vq_quantthresh__44u4__p7_2,
  149515. _vq_quantmap__44u4__p7_2,
  149516. 17,
  149517. 17
  149518. };
  149519. static static_codebook _44u4__p7_2 = {
  149520. 2, 289,
  149521. _vq_lengthlist__44u4__p7_2,
  149522. 1, -529530880, 1611661312, 5, 0,
  149523. _vq_quantlist__44u4__p7_2,
  149524. NULL,
  149525. &_vq_auxt__44u4__p7_2,
  149526. NULL,
  149527. 0
  149528. };
  149529. static long _huff_lengthlist__44u4__short[] = {
  149530. 14,17,15,17,16,14,13,16,10, 7, 7,10,13,10,15,16,
  149531. 9, 4, 4, 6, 5, 7, 9,16,12, 8, 7, 8, 8, 8,11,16,
  149532. 14, 7, 4, 6, 3, 5, 8,15,13, 8, 5, 7, 4, 5, 7,16,
  149533. 12, 9, 6, 8, 3, 3, 5,16,14,13, 7,10, 5, 5, 7,15,
  149534. };
  149535. static static_codebook _huff_book__44u4__short = {
  149536. 2, 64,
  149537. _huff_lengthlist__44u4__short,
  149538. 0, 0, 0, 0, 0,
  149539. NULL,
  149540. NULL,
  149541. NULL,
  149542. NULL,
  149543. 0
  149544. };
  149545. static long _huff_lengthlist__44u5__long[] = {
  149546. 3, 8,13,12,14,12,16,11,13,14, 5, 4, 5, 6, 7, 8,
  149547. 10, 9,12,15,10, 5, 5, 5, 6, 8, 9, 9,13,15,10, 5,
  149548. 5, 6, 6, 7, 8, 8,11,13,12, 7, 5, 6, 4, 6, 7, 7,
  149549. 11,14,11, 7, 7, 6, 6, 6, 7, 6,10,14,14, 9, 8, 8,
  149550. 6, 7, 7, 7,11,16,11, 8, 8, 7, 6, 6, 7, 4, 7,12,
  149551. 10,10,12,10,10, 9,10, 5, 6, 9,10,12,15,13,14,14,
  149552. 14, 8, 7, 8,
  149553. };
  149554. static static_codebook _huff_book__44u5__long = {
  149555. 2, 100,
  149556. _huff_lengthlist__44u5__long,
  149557. 0, 0, 0, 0, 0,
  149558. NULL,
  149559. NULL,
  149560. NULL,
  149561. NULL,
  149562. 0
  149563. };
  149564. static long _vq_quantlist__44u5__p1_0[] = {
  149565. 1,
  149566. 0,
  149567. 2,
  149568. };
  149569. static long _vq_lengthlist__44u5__p1_0[] = {
  149570. 1, 4, 4, 5, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  149571. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  149572. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  149573. 10,13,11,10,13,13, 4, 8, 8, 8,11,10, 8,10,10, 7,
  149574. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  149575. 12,
  149576. };
  149577. static float _vq_quantthresh__44u5__p1_0[] = {
  149578. -0.5, 0.5,
  149579. };
  149580. static long _vq_quantmap__44u5__p1_0[] = {
  149581. 1, 0, 2,
  149582. };
  149583. static encode_aux_threshmatch _vq_auxt__44u5__p1_0 = {
  149584. _vq_quantthresh__44u5__p1_0,
  149585. _vq_quantmap__44u5__p1_0,
  149586. 3,
  149587. 3
  149588. };
  149589. static static_codebook _44u5__p1_0 = {
  149590. 4, 81,
  149591. _vq_lengthlist__44u5__p1_0,
  149592. 1, -535822336, 1611661312, 2, 0,
  149593. _vq_quantlist__44u5__p1_0,
  149594. NULL,
  149595. &_vq_auxt__44u5__p1_0,
  149596. NULL,
  149597. 0
  149598. };
  149599. static long _vq_quantlist__44u5__p2_0[] = {
  149600. 1,
  149601. 0,
  149602. 2,
  149603. };
  149604. static long _vq_lengthlist__44u5__p2_0[] = {
  149605. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  149606. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  149607. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  149608. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  149609. 8, 7, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  149610. 9,
  149611. };
  149612. static float _vq_quantthresh__44u5__p2_0[] = {
  149613. -0.5, 0.5,
  149614. };
  149615. static long _vq_quantmap__44u5__p2_0[] = {
  149616. 1, 0, 2,
  149617. };
  149618. static encode_aux_threshmatch _vq_auxt__44u5__p2_0 = {
  149619. _vq_quantthresh__44u5__p2_0,
  149620. _vq_quantmap__44u5__p2_0,
  149621. 3,
  149622. 3
  149623. };
  149624. static static_codebook _44u5__p2_0 = {
  149625. 4, 81,
  149626. _vq_lengthlist__44u5__p2_0,
  149627. 1, -535822336, 1611661312, 2, 0,
  149628. _vq_quantlist__44u5__p2_0,
  149629. NULL,
  149630. &_vq_auxt__44u5__p2_0,
  149631. NULL,
  149632. 0
  149633. };
  149634. static long _vq_quantlist__44u5__p3_0[] = {
  149635. 2,
  149636. 1,
  149637. 3,
  149638. 0,
  149639. 4,
  149640. };
  149641. static long _vq_lengthlist__44u5__p3_0[] = {
  149642. 2, 4, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  149643. 10, 9,13,12, 8, 9,10,12,12, 5, 7, 7,10,10, 7, 9,
  149644. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  149645. 13,14, 5, 7, 7, 9,10, 7, 9, 8,11,11, 7, 9, 9,11,
  149646. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,13,13,
  149647. 10,11,11,15,14, 9,11,11,14,14,13,14,14,17,16,12,
  149648. 13,13,15,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  149649. 11,14,15,12,14,13,16,16,13,15,14,15,17, 5, 7, 7,
  149650. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,
  149651. 14,10,11,12,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  149652. 9,11,11,13,13,12,13,13,15,16,11,12,13,15,16, 6,
  149653. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,14,11,13,
  149654. 12,16,14,11,13,13,16,17,10,12,11,15,15,11,13,13,
  149655. 16,16,11,13,13,17,16,14,15,15,17,17,14,16,16,17,
  149656. 18, 9,11,11,14,15,10,12,12,15,15,11,13,13,16,17,
  149657. 13,15,13,17,15,14,15,16,18, 0, 5, 7, 7,10,10, 7,
  149658. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  149659. 12,14,15, 6, 9, 9,12,11, 9,11,11,13,13, 8,10,11,
  149660. 12,13,11,13,13,16,15,11,12,13,14,15, 7, 9, 9,11,
  149661. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,15,16,
  149662. 11,13,13,15,14, 9,11,11,15,14,11,13,13,17,15,10,
  149663. 12,12,15,15,14,16,16,17,17,13,13,15,15,17,10,11,
  149664. 12,15,15,11,13,13,16,16,11,13,13,15,15,14,15,15,
  149665. 18,18,14,15,15,17,17, 8,10,10,13,13,10,12,11,15,
  149666. 15,10,11,12,15,15,14,15,15,18,18,13,14,14,18,18,
  149667. 9,11,11,15,16,11,13,13,17,17,11,13,13,16,16,15,
  149668. 15,16,17, 0,14,15,17, 0, 0, 9,11,11,15,15,10,13,
  149669. 12,18,16,11,13,13,15,16,14,16,15,20,20,14,15,16,
  149670. 17, 0,13,14,14,20,16,14,15,16,19,18,14,15,15,19,
  149671. 0,18,16, 0,20,20,16,18,18, 0, 0,12,14,14,18,18,
  149672. 13,15,14,18,16,14,15,16,18,20,16,19,16, 0,17,17,
  149673. 18,18,19, 0, 8,10,10,14,14,10,11,11,14,15,10,11,
  149674. 12,15,15,13,15,14,19,17,13,15,15,17, 0, 9,11,11,
  149675. 16,15,11,13,13,16,16,10,12,13,15,17,14,16,16,18,
  149676. 18,14,15,15,18, 0, 9,11,11,15,15,11,13,13,16,17,
  149677. 11,13,13,18,17,14,18,16,18,18,15,17,17,18, 0,12,
  149678. 14,14,18,18,14,15,15,20, 0,13,14,15,17, 0,16,18,
  149679. 17, 0, 0,16,16, 0,17,20,12,14,14,18,18,14,16,15,
  149680. 0,18,14,16,15,18, 0,16,19,17, 0, 0,17,18,16, 0,
  149681. 0,
  149682. };
  149683. static float _vq_quantthresh__44u5__p3_0[] = {
  149684. -1.5, -0.5, 0.5, 1.5,
  149685. };
  149686. static long _vq_quantmap__44u5__p3_0[] = {
  149687. 3, 1, 0, 2, 4,
  149688. };
  149689. static encode_aux_threshmatch _vq_auxt__44u5__p3_0 = {
  149690. _vq_quantthresh__44u5__p3_0,
  149691. _vq_quantmap__44u5__p3_0,
  149692. 5,
  149693. 5
  149694. };
  149695. static static_codebook _44u5__p3_0 = {
  149696. 4, 625,
  149697. _vq_lengthlist__44u5__p3_0,
  149698. 1, -533725184, 1611661312, 3, 0,
  149699. _vq_quantlist__44u5__p3_0,
  149700. NULL,
  149701. &_vq_auxt__44u5__p3_0,
  149702. NULL,
  149703. 0
  149704. };
  149705. static long _vq_quantlist__44u5__p4_0[] = {
  149706. 2,
  149707. 1,
  149708. 3,
  149709. 0,
  149710. 4,
  149711. };
  149712. static long _vq_lengthlist__44u5__p4_0[] = {
  149713. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  149714. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  149715. 8,10,10, 6, 7, 8, 9,10, 9,10,10,11,12, 9, 9,10,
  149716. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  149717. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,12,11,
  149718. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  149719. 11,12,13,14, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149720. 10,12,12,11,12,11,14,13,11,12,12,13,13, 5, 7, 7,
  149721. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  149722. 12, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,10,11,
  149723. 8, 9, 9,11,11,10,10,11,11,13,10,11,11,12,13, 6,
  149724. 7, 8,10,10, 7, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  149725. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  149726. 12,13,10,11,11,13,13,12,11,13,12,15,12,13,13,14,
  149727. 15, 9,10,10,12,12, 9,11,10,13,12,10,11,11,13,13,
  149728. 11,13,11,14,12,12,13,13,14,15, 5, 7, 7, 9, 9, 7,
  149729. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  149730. 10,12,12, 6, 8, 7,10,10, 8, 9, 9,11,11, 7, 8, 9,
  149731. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  149732. 10, 8, 9, 9,11,11, 8, 9, 8,11,10,10,11,11,13,12,
  149733. 10,11,10,13,11, 9,10,10,12,12,10,11,11,13,12, 9,
  149734. 10,10,12,13,12,13,13,14,15,11,11,13,12,14, 9,10,
  149735. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,13,13,
  149736. 14,14,12,13,11,14,12, 8, 9, 9,12,12, 9,10,10,12,
  149737. 12, 9,10,10,12,12,12,12,12,14,14,11,12,12,14,13,
  149738. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  149739. 12,13,14,15,12,13,13,15,14, 9,10,10,12,12,10,11,
  149740. 10,13,12,10,11,11,12,13,12,13,12,15,13,12,13,13,
  149741. 14,15,11,12,12,14,13,11,12,12,14,15,12,13,13,15,
  149742. 14,13,12,14,12,16,13,14,14,15,15,11,11,12,14,14,
  149743. 11,12,11,14,13,12,13,13,14,15,13,14,12,16,12,14,
  149744. 14,15,16,16, 8, 9, 9,11,12, 9,10,10,12,12, 9,10,
  149745. 10,12,13,11,12,12,13,13,12,12,13,14,14, 9,10,10,
  149746. 12,12,10,11,10,13,12,10,10,11,12,13,12,13,13,15,
  149747. 14,12,12,13,13,15, 9,10,10,12,13,10,11,11,12,13,
  149748. 10,11,11,13,13,12,13,13,14,15,12,13,12,15,14,11,
  149749. 12,11,14,13,12,13,13,15,14,11,11,12,13,14,14,15,
  149750. 14,16,15,13,12,14,13,16,11,12,12,13,14,12,13,13,
  149751. 14,15,11,12,11,14,14,14,14,14,15,16,13,15,12,16,
  149752. 12,
  149753. };
  149754. static float _vq_quantthresh__44u5__p4_0[] = {
  149755. -1.5, -0.5, 0.5, 1.5,
  149756. };
  149757. static long _vq_quantmap__44u5__p4_0[] = {
  149758. 3, 1, 0, 2, 4,
  149759. };
  149760. static encode_aux_threshmatch _vq_auxt__44u5__p4_0 = {
  149761. _vq_quantthresh__44u5__p4_0,
  149762. _vq_quantmap__44u5__p4_0,
  149763. 5,
  149764. 5
  149765. };
  149766. static static_codebook _44u5__p4_0 = {
  149767. 4, 625,
  149768. _vq_lengthlist__44u5__p4_0,
  149769. 1, -533725184, 1611661312, 3, 0,
  149770. _vq_quantlist__44u5__p4_0,
  149771. NULL,
  149772. &_vq_auxt__44u5__p4_0,
  149773. NULL,
  149774. 0
  149775. };
  149776. static long _vq_quantlist__44u5__p5_0[] = {
  149777. 4,
  149778. 3,
  149779. 5,
  149780. 2,
  149781. 6,
  149782. 1,
  149783. 7,
  149784. 0,
  149785. 8,
  149786. };
  149787. static long _vq_lengthlist__44u5__p5_0[] = {
  149788. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  149789. 11,10, 3, 5, 5, 7, 8, 8, 8,10,11, 6, 8, 7,10, 9,
  149790. 10,10,11,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  149791. 10,10,11,11,13,12, 8, 8, 9, 9,10,11,11,12,13,10,
  149792. 11,10,12,11,13,12,14,14,10,10,11,11,12,12,13,14,
  149793. 14,
  149794. };
  149795. static float _vq_quantthresh__44u5__p5_0[] = {
  149796. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149797. };
  149798. static long _vq_quantmap__44u5__p5_0[] = {
  149799. 7, 5, 3, 1, 0, 2, 4, 6,
  149800. 8,
  149801. };
  149802. static encode_aux_threshmatch _vq_auxt__44u5__p5_0 = {
  149803. _vq_quantthresh__44u5__p5_0,
  149804. _vq_quantmap__44u5__p5_0,
  149805. 9,
  149806. 9
  149807. };
  149808. static static_codebook _44u5__p5_0 = {
  149809. 2, 81,
  149810. _vq_lengthlist__44u5__p5_0,
  149811. 1, -531628032, 1611661312, 4, 0,
  149812. _vq_quantlist__44u5__p5_0,
  149813. NULL,
  149814. &_vq_auxt__44u5__p5_0,
  149815. NULL,
  149816. 0
  149817. };
  149818. static long _vq_quantlist__44u5__p6_0[] = {
  149819. 4,
  149820. 3,
  149821. 5,
  149822. 2,
  149823. 6,
  149824. 1,
  149825. 7,
  149826. 0,
  149827. 8,
  149828. };
  149829. static long _vq_lengthlist__44u5__p6_0[] = {
  149830. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  149831. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  149832. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  149833. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  149834. 9, 9,10,10,11,10,11,11, 9, 9, 9,10,10,11,10,11,
  149835. 11,
  149836. };
  149837. static float _vq_quantthresh__44u5__p6_0[] = {
  149838. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  149839. };
  149840. static long _vq_quantmap__44u5__p6_0[] = {
  149841. 7, 5, 3, 1, 0, 2, 4, 6,
  149842. 8,
  149843. };
  149844. static encode_aux_threshmatch _vq_auxt__44u5__p6_0 = {
  149845. _vq_quantthresh__44u5__p6_0,
  149846. _vq_quantmap__44u5__p6_0,
  149847. 9,
  149848. 9
  149849. };
  149850. static static_codebook _44u5__p6_0 = {
  149851. 2, 81,
  149852. _vq_lengthlist__44u5__p6_0,
  149853. 1, -531628032, 1611661312, 4, 0,
  149854. _vq_quantlist__44u5__p6_0,
  149855. NULL,
  149856. &_vq_auxt__44u5__p6_0,
  149857. NULL,
  149858. 0
  149859. };
  149860. static long _vq_quantlist__44u5__p7_0[] = {
  149861. 1,
  149862. 0,
  149863. 2,
  149864. };
  149865. static long _vq_lengthlist__44u5__p7_0[] = {
  149866. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 9, 8,11,10, 7,
  149867. 11,10, 5, 9, 9, 7,10,10, 8,10,11, 4, 9, 9, 9,12,
  149868. 12, 9,12,12, 8,12,12,11,12,12,10,12,13, 7,12,12,
  149869. 11,12,12,10,12,13, 4, 9, 9, 9,12,12, 9,12,12, 7,
  149870. 12,11,10,13,13,11,12,12, 7,12,12,10,13,13,11,12,
  149871. 12,
  149872. };
  149873. static float _vq_quantthresh__44u5__p7_0[] = {
  149874. -5.5, 5.5,
  149875. };
  149876. static long _vq_quantmap__44u5__p7_0[] = {
  149877. 1, 0, 2,
  149878. };
  149879. static encode_aux_threshmatch _vq_auxt__44u5__p7_0 = {
  149880. _vq_quantthresh__44u5__p7_0,
  149881. _vq_quantmap__44u5__p7_0,
  149882. 3,
  149883. 3
  149884. };
  149885. static static_codebook _44u5__p7_0 = {
  149886. 4, 81,
  149887. _vq_lengthlist__44u5__p7_0,
  149888. 1, -529137664, 1618345984, 2, 0,
  149889. _vq_quantlist__44u5__p7_0,
  149890. NULL,
  149891. &_vq_auxt__44u5__p7_0,
  149892. NULL,
  149893. 0
  149894. };
  149895. static long _vq_quantlist__44u5__p7_1[] = {
  149896. 5,
  149897. 4,
  149898. 6,
  149899. 3,
  149900. 7,
  149901. 2,
  149902. 8,
  149903. 1,
  149904. 9,
  149905. 0,
  149906. 10,
  149907. };
  149908. static long _vq_lengthlist__44u5__p7_1[] = {
  149909. 2, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 7,
  149910. 8, 8, 9, 8, 8, 9, 4, 5, 5, 7, 7, 8, 8, 9, 9, 8,
  149911. 9, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 6, 7, 7, 8,
  149912. 8, 9, 9, 9, 9, 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9,
  149913. 9, 9, 7, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9,
  149914. 9, 9, 9, 9,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  149915. 10,10,10, 8, 9, 9, 9, 9, 9, 9,10,10,10,10, 8, 9,
  149916. 9, 9, 9, 9, 9,10,10,10,10,
  149917. };
  149918. static float _vq_quantthresh__44u5__p7_1[] = {
  149919. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  149920. 3.5, 4.5,
  149921. };
  149922. static long _vq_quantmap__44u5__p7_1[] = {
  149923. 9, 7, 5, 3, 1, 0, 2, 4,
  149924. 6, 8, 10,
  149925. };
  149926. static encode_aux_threshmatch _vq_auxt__44u5__p7_1 = {
  149927. _vq_quantthresh__44u5__p7_1,
  149928. _vq_quantmap__44u5__p7_1,
  149929. 11,
  149930. 11
  149931. };
  149932. static static_codebook _44u5__p7_1 = {
  149933. 2, 121,
  149934. _vq_lengthlist__44u5__p7_1,
  149935. 1, -531365888, 1611661312, 4, 0,
  149936. _vq_quantlist__44u5__p7_1,
  149937. NULL,
  149938. &_vq_auxt__44u5__p7_1,
  149939. NULL,
  149940. 0
  149941. };
  149942. static long _vq_quantlist__44u5__p8_0[] = {
  149943. 5,
  149944. 4,
  149945. 6,
  149946. 3,
  149947. 7,
  149948. 2,
  149949. 8,
  149950. 1,
  149951. 9,
  149952. 0,
  149953. 10,
  149954. };
  149955. static long _vq_lengthlist__44u5__p8_0[] = {
  149956. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  149957. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  149958. 11, 6, 8, 7, 9, 9,10,10,11,11,13,12, 6, 8, 8, 9,
  149959. 9,10,10,11,11,12,13, 8, 9, 9,10,10,12,12,13,12,
  149960. 14,13, 8, 9, 9,10,10,12,12,13,13,14,14, 9,11,11,
  149961. 12,12,13,13,14,14,15,14, 9,11,11,12,12,13,13,14,
  149962. 14,15,14,11,12,12,13,13,14,14,15,14,15,14,11,11,
  149963. 12,13,13,14,14,14,14,15,15,
  149964. };
  149965. static float _vq_quantthresh__44u5__p8_0[] = {
  149966. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  149967. 38.5, 49.5,
  149968. };
  149969. static long _vq_quantmap__44u5__p8_0[] = {
  149970. 9, 7, 5, 3, 1, 0, 2, 4,
  149971. 6, 8, 10,
  149972. };
  149973. static encode_aux_threshmatch _vq_auxt__44u5__p8_0 = {
  149974. _vq_quantthresh__44u5__p8_0,
  149975. _vq_quantmap__44u5__p8_0,
  149976. 11,
  149977. 11
  149978. };
  149979. static static_codebook _44u5__p8_0 = {
  149980. 2, 121,
  149981. _vq_lengthlist__44u5__p8_0,
  149982. 1, -524582912, 1618345984, 4, 0,
  149983. _vq_quantlist__44u5__p8_0,
  149984. NULL,
  149985. &_vq_auxt__44u5__p8_0,
  149986. NULL,
  149987. 0
  149988. };
  149989. static long _vq_quantlist__44u5__p8_1[] = {
  149990. 5,
  149991. 4,
  149992. 6,
  149993. 3,
  149994. 7,
  149995. 2,
  149996. 8,
  149997. 1,
  149998. 9,
  149999. 0,
  150000. 10,
  150001. };
  150002. static long _vq_lengthlist__44u5__p8_1[] = {
  150003. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 6,
  150004. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8,
  150005. 8, 6, 7, 6, 7, 7, 8, 8, 8, 8, 8, 8, 6, 6, 7, 7,
  150006. 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150007. 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8,
  150008. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150009. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150010. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150011. };
  150012. static float _vq_quantthresh__44u5__p8_1[] = {
  150013. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150014. 3.5, 4.5,
  150015. };
  150016. static long _vq_quantmap__44u5__p8_1[] = {
  150017. 9, 7, 5, 3, 1, 0, 2, 4,
  150018. 6, 8, 10,
  150019. };
  150020. static encode_aux_threshmatch _vq_auxt__44u5__p8_1 = {
  150021. _vq_quantthresh__44u5__p8_1,
  150022. _vq_quantmap__44u5__p8_1,
  150023. 11,
  150024. 11
  150025. };
  150026. static static_codebook _44u5__p8_1 = {
  150027. 2, 121,
  150028. _vq_lengthlist__44u5__p8_1,
  150029. 1, -531365888, 1611661312, 4, 0,
  150030. _vq_quantlist__44u5__p8_1,
  150031. NULL,
  150032. &_vq_auxt__44u5__p8_1,
  150033. NULL,
  150034. 0
  150035. };
  150036. static long _vq_quantlist__44u5__p9_0[] = {
  150037. 6,
  150038. 5,
  150039. 7,
  150040. 4,
  150041. 8,
  150042. 3,
  150043. 9,
  150044. 2,
  150045. 10,
  150046. 1,
  150047. 11,
  150048. 0,
  150049. 12,
  150050. };
  150051. static long _vq_lengthlist__44u5__p9_0[] = {
  150052. 1, 3, 2,12,10,13,13,13,13,13,13,13,13, 4, 9, 9,
  150053. 13,13,13,13,13,13,13,13,13,13, 5,10, 9,13,13,13,
  150054. 13,13,13,13,13,13,13,12,13,13,13,13,13,13,13,13,
  150055. 13,13,13,13,11,13,13,13,13,13,13,13,13,13,13,13,
  150056. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  150057. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  150058. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  150059. 13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,13,
  150060. 13,13,13,13,13,13,13,13,13,13,13,13,13,12,12,12,
  150061. 12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,12,
  150062. 12,12,12,12,12,12,12,12,12,
  150063. };
  150064. static float _vq_quantthresh__44u5__p9_0[] = {
  150065. -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5, 382.5,
  150066. 637.5, 892.5, 1147.5, 1402.5,
  150067. };
  150068. static long _vq_quantmap__44u5__p9_0[] = {
  150069. 11, 9, 7, 5, 3, 1, 0, 2,
  150070. 4, 6, 8, 10, 12,
  150071. };
  150072. static encode_aux_threshmatch _vq_auxt__44u5__p9_0 = {
  150073. _vq_quantthresh__44u5__p9_0,
  150074. _vq_quantmap__44u5__p9_0,
  150075. 13,
  150076. 13
  150077. };
  150078. static static_codebook _44u5__p9_0 = {
  150079. 2, 169,
  150080. _vq_lengthlist__44u5__p9_0,
  150081. 1, -514332672, 1627381760, 4, 0,
  150082. _vq_quantlist__44u5__p9_0,
  150083. NULL,
  150084. &_vq_auxt__44u5__p9_0,
  150085. NULL,
  150086. 0
  150087. };
  150088. static long _vq_quantlist__44u5__p9_1[] = {
  150089. 7,
  150090. 6,
  150091. 8,
  150092. 5,
  150093. 9,
  150094. 4,
  150095. 10,
  150096. 3,
  150097. 11,
  150098. 2,
  150099. 12,
  150100. 1,
  150101. 13,
  150102. 0,
  150103. 14,
  150104. };
  150105. static long _vq_lengthlist__44u5__p9_1[] = {
  150106. 1, 4, 4, 7, 7, 8, 8, 8, 7, 8, 7, 9, 8, 9, 9, 4,
  150107. 7, 6, 9, 8,10,10, 9, 8, 9, 9, 9, 9, 9, 8, 5, 6,
  150108. 6, 8, 9,10,10, 9, 9, 9,10,10,10,10,11, 7, 8, 8,
  150109. 10,10,11,11,10,10,11,11,11,12,11,11, 7, 8, 8,10,
  150110. 10,11,11,10,10,11,11,12,11,11,11, 8, 9, 9,11,11,
  150111. 12,12,11,11,12,11,12,12,12,12, 8, 9,10,11,11,12,
  150112. 12,11,11,12,12,12,12,12,12, 8, 9, 9,10,10,12,11,
  150113. 12,12,12,12,12,12,12,13, 8, 9, 9,11,11,11,11,12,
  150114. 12,12,12,13,12,13,13, 9,10,10,11,11,12,12,12,13,
  150115. 12,13,13,13,14,13, 9,10,10,11,11,12,12,12,13,13,
  150116. 12,13,13,14,13, 9,11,10,12,11,13,12,12,13,13,13,
  150117. 13,13,13,14, 9,10,10,12,12,12,12,12,13,13,13,13,
  150118. 13,14,14,10,11,11,12,12,12,13,13,13,14,14,13,14,
  150119. 14,14,10,11,11,12,12,12,12,13,12,13,14,13,14,14,
  150120. 14,
  150121. };
  150122. static float _vq_quantthresh__44u5__p9_1[] = {
  150123. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150124. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150125. };
  150126. static long _vq_quantmap__44u5__p9_1[] = {
  150127. 13, 11, 9, 7, 5, 3, 1, 0,
  150128. 2, 4, 6, 8, 10, 12, 14,
  150129. };
  150130. static encode_aux_threshmatch _vq_auxt__44u5__p9_1 = {
  150131. _vq_quantthresh__44u5__p9_1,
  150132. _vq_quantmap__44u5__p9_1,
  150133. 15,
  150134. 15
  150135. };
  150136. static static_codebook _44u5__p9_1 = {
  150137. 2, 225,
  150138. _vq_lengthlist__44u5__p9_1,
  150139. 1, -522338304, 1620115456, 4, 0,
  150140. _vq_quantlist__44u5__p9_1,
  150141. NULL,
  150142. &_vq_auxt__44u5__p9_1,
  150143. NULL,
  150144. 0
  150145. };
  150146. static long _vq_quantlist__44u5__p9_2[] = {
  150147. 8,
  150148. 7,
  150149. 9,
  150150. 6,
  150151. 10,
  150152. 5,
  150153. 11,
  150154. 4,
  150155. 12,
  150156. 3,
  150157. 13,
  150158. 2,
  150159. 14,
  150160. 1,
  150161. 15,
  150162. 0,
  150163. 16,
  150164. };
  150165. static long _vq_lengthlist__44u5__p9_2[] = {
  150166. 2, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150167. 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  150168. 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  150169. 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9,
  150170. 9, 9, 9, 9, 7, 7, 7, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  150171. 9, 9, 9, 9, 9, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  150172. 9,10, 9,10,10,10, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9,
  150173. 9, 9,10, 9,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  150174. 9,10, 9,10,10,10,10,10, 8, 9, 9, 9, 9, 9, 9,10,
  150175. 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,10, 9,
  150176. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9,
  150177. 9,10, 9,10, 9,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  150178. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  150179. 9, 9,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  150180. 9,10,10, 9,10,10,10,10,10,10,10,10,10,10, 9, 9,
  150181. 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  150182. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  150183. 9, 9, 9,10, 9,10,10,10,10,10,10,10,10,10,10,10,
  150184. 10,
  150185. };
  150186. static float _vq_quantthresh__44u5__p9_2[] = {
  150187. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150188. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150189. };
  150190. static long _vq_quantmap__44u5__p9_2[] = {
  150191. 15, 13, 11, 9, 7, 5, 3, 1,
  150192. 0, 2, 4, 6, 8, 10, 12, 14,
  150193. 16,
  150194. };
  150195. static encode_aux_threshmatch _vq_auxt__44u5__p9_2 = {
  150196. _vq_quantthresh__44u5__p9_2,
  150197. _vq_quantmap__44u5__p9_2,
  150198. 17,
  150199. 17
  150200. };
  150201. static static_codebook _44u5__p9_2 = {
  150202. 2, 289,
  150203. _vq_lengthlist__44u5__p9_2,
  150204. 1, -529530880, 1611661312, 5, 0,
  150205. _vq_quantlist__44u5__p9_2,
  150206. NULL,
  150207. &_vq_auxt__44u5__p9_2,
  150208. NULL,
  150209. 0
  150210. };
  150211. static long _huff_lengthlist__44u5__short[] = {
  150212. 4,10,17,13,17,13,17,17,17,17, 3, 6, 8, 9,11, 9,
  150213. 15,12,16,17, 6, 5, 5, 7, 7, 8,10,11,17,17, 7, 8,
  150214. 7, 9, 9,10,13,13,17,17, 8, 6, 5, 7, 4, 7, 5, 8,
  150215. 14,17, 9, 9, 8, 9, 7, 9, 8,10,16,17,12,10, 7, 8,
  150216. 4, 7, 4, 7,16,17,12,11, 9,10, 6, 9, 5, 7,14,17,
  150217. 14,13,10,15, 4, 8, 3, 5,14,17,17,14,11,15, 6,10,
  150218. 6, 8,15,17,
  150219. };
  150220. static static_codebook _huff_book__44u5__short = {
  150221. 2, 100,
  150222. _huff_lengthlist__44u5__short,
  150223. 0, 0, 0, 0, 0,
  150224. NULL,
  150225. NULL,
  150226. NULL,
  150227. NULL,
  150228. 0
  150229. };
  150230. static long _huff_lengthlist__44u6__long[] = {
  150231. 3, 9,14,13,14,13,16,12,13,14, 5, 4, 6, 6, 8, 9,
  150232. 11,10,12,15,10, 5, 5, 6, 6, 8,10,10,13,16,10, 6,
  150233. 6, 6, 6, 8, 9, 9,12,14,13, 7, 6, 6, 4, 6, 6, 7,
  150234. 11,14,10, 7, 7, 7, 6, 6, 6, 7,10,13,15,10, 9, 8,
  150235. 5, 6, 5, 6,10,14,10, 9, 8, 8, 6, 6, 5, 4, 6,11,
  150236. 11,11,12,11,10, 9, 9, 5, 5, 9,10,12,15,13,13,13,
  150237. 13, 8, 7, 7,
  150238. };
  150239. static static_codebook _huff_book__44u6__long = {
  150240. 2, 100,
  150241. _huff_lengthlist__44u6__long,
  150242. 0, 0, 0, 0, 0,
  150243. NULL,
  150244. NULL,
  150245. NULL,
  150246. NULL,
  150247. 0
  150248. };
  150249. static long _vq_quantlist__44u6__p1_0[] = {
  150250. 1,
  150251. 0,
  150252. 2,
  150253. };
  150254. static long _vq_lengthlist__44u6__p1_0[] = {
  150255. 1, 4, 4, 4, 8, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150256. 9,10, 5, 8, 8, 7,10, 9, 8,10,10, 5, 8, 8, 8,10,
  150257. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150258. 10,13,11,10,13,13, 5, 8, 8, 8,11,10, 8,10,10, 7,
  150259. 10,10,10,13,13,10,11,13, 8,10,11,10,13,13,10,13,
  150260. 12,
  150261. };
  150262. static float _vq_quantthresh__44u6__p1_0[] = {
  150263. -0.5, 0.5,
  150264. };
  150265. static long _vq_quantmap__44u6__p1_0[] = {
  150266. 1, 0, 2,
  150267. };
  150268. static encode_aux_threshmatch _vq_auxt__44u6__p1_0 = {
  150269. _vq_quantthresh__44u6__p1_0,
  150270. _vq_quantmap__44u6__p1_0,
  150271. 3,
  150272. 3
  150273. };
  150274. static static_codebook _44u6__p1_0 = {
  150275. 4, 81,
  150276. _vq_lengthlist__44u6__p1_0,
  150277. 1, -535822336, 1611661312, 2, 0,
  150278. _vq_quantlist__44u6__p1_0,
  150279. NULL,
  150280. &_vq_auxt__44u6__p1_0,
  150281. NULL,
  150282. 0
  150283. };
  150284. static long _vq_quantlist__44u6__p2_0[] = {
  150285. 1,
  150286. 0,
  150287. 2,
  150288. };
  150289. static long _vq_lengthlist__44u6__p2_0[] = {
  150290. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150291. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150292. 8, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 7, 7,
  150293. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150294. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150295. 9,
  150296. };
  150297. static float _vq_quantthresh__44u6__p2_0[] = {
  150298. -0.5, 0.5,
  150299. };
  150300. static long _vq_quantmap__44u6__p2_0[] = {
  150301. 1, 0, 2,
  150302. };
  150303. static encode_aux_threshmatch _vq_auxt__44u6__p2_0 = {
  150304. _vq_quantthresh__44u6__p2_0,
  150305. _vq_quantmap__44u6__p2_0,
  150306. 3,
  150307. 3
  150308. };
  150309. static static_codebook _44u6__p2_0 = {
  150310. 4, 81,
  150311. _vq_lengthlist__44u6__p2_0,
  150312. 1, -535822336, 1611661312, 2, 0,
  150313. _vq_quantlist__44u6__p2_0,
  150314. NULL,
  150315. &_vq_auxt__44u6__p2_0,
  150316. NULL,
  150317. 0
  150318. };
  150319. static long _vq_quantlist__44u6__p3_0[] = {
  150320. 2,
  150321. 1,
  150322. 3,
  150323. 0,
  150324. 4,
  150325. };
  150326. static long _vq_lengthlist__44u6__p3_0[] = {
  150327. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  150328. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  150329. 9,11,11, 7, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  150330. 13,14, 5, 7, 7, 9,10, 6, 9, 8,11,11, 7, 9, 9,11,
  150331. 11, 9,11,10,14,13,10,11,11,14,13, 8,10,10,13,13,
  150332. 10,11,11,15,15, 9,11,11,14,14,13,14,14,17,16,12,
  150333. 13,14,16,16, 8,10,10,13,14, 9,11,11,14,15,10,11,
  150334. 12,14,15,12,14,13,16,15,13,14,14,15,17, 5, 7, 7,
  150335. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,14,
  150336. 14,10,11,11,14,14, 7, 9, 9,12,11, 9,11,11,13,13,
  150337. 9,11,11,13,13,11,13,13,14,15,11,12,13,15,16, 6,
  150338. 9, 9,11,12, 8,11,10,13,12, 9,11,11,13,14,11,13,
  150339. 12,16,14,11,13,13,15,16,10,12,11,14,15,11,13,13,
  150340. 15,17,11,13,13,17,16,15,15,16,17,16,14,15,16,18,
  150341. 0, 9,11,11,14,15,10,12,12,16,15,11,13,13,16,16,
  150342. 13,15,14,18,15,14,16,16, 0, 0, 5, 7, 7,10,10, 7,
  150343. 9, 9,11,11, 7, 9, 9,11,11,10,11,11,14,14,10,11,
  150344. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  150345. 12,13,11,13,13,16,15,11,12,13,14,16, 7, 9, 9,11,
  150346. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,13,16,15,
  150347. 11,13,12,15,15, 9,11,11,15,14,11,13,13,17,16,10,
  150348. 12,13,15,16,14,16,16, 0,18,14,14,15,15,17,10,11,
  150349. 12,15,15,11,13,13,16,16,11,13,13,16,16,14,16,16,
  150350. 19,17,14,15,15,17,17, 8,10,10,14,14,10,12,11,15,
  150351. 15,10,11,12,16,15,14,15,15,18,20,13,14,16,17,18,
  150352. 9,11,11,15,16,11,13,13,17,17,11,13,13,17,16,15,
  150353. 16,16, 0, 0,15,16,16, 0, 0, 9,11,11,15,15,10,13,
  150354. 12,17,15,11,13,13,17,16,15,17,15,20,19,15,16,16,
  150355. 19, 0,13,15,14, 0,17,14,15,16, 0,20,15,16,16, 0,
  150356. 19,17,18, 0, 0, 0,16,17,18, 0, 0,12,14,14,19,18,
  150357. 13,15,14, 0,17,14,15,16,19,19,16,18,16, 0,19,19,
  150358. 20,17,20, 0, 8,10,10,13,14,10,11,11,15,15,10,12,
  150359. 12,15,16,14,15,14,19,16,14,15,15, 0,18, 9,11,11,
  150360. 16,15,11,13,13, 0,16,11,12,13,16,17,14,16,17, 0,
  150361. 19,15,16,16,18, 0, 9,11,11,15,16,11,13,13,16,16,
  150362. 11,14,13,18,17,15,16,16,18,20,15,17,19, 0, 0,12,
  150363. 14,14,17,17,14,16,15, 0, 0,13,14,15,19, 0,16,18,
  150364. 20, 0, 0,16,16,18,18, 0,12,14,14,17,20,14,16,16,
  150365. 19, 0,14,16,14, 0,20,16,20,17, 0, 0,17, 0,15, 0,
  150366. 19,
  150367. };
  150368. static float _vq_quantthresh__44u6__p3_0[] = {
  150369. -1.5, -0.5, 0.5, 1.5,
  150370. };
  150371. static long _vq_quantmap__44u6__p3_0[] = {
  150372. 3, 1, 0, 2, 4,
  150373. };
  150374. static encode_aux_threshmatch _vq_auxt__44u6__p3_0 = {
  150375. _vq_quantthresh__44u6__p3_0,
  150376. _vq_quantmap__44u6__p3_0,
  150377. 5,
  150378. 5
  150379. };
  150380. static static_codebook _44u6__p3_0 = {
  150381. 4, 625,
  150382. _vq_lengthlist__44u6__p3_0,
  150383. 1, -533725184, 1611661312, 3, 0,
  150384. _vq_quantlist__44u6__p3_0,
  150385. NULL,
  150386. &_vq_auxt__44u6__p3_0,
  150387. NULL,
  150388. 0
  150389. };
  150390. static long _vq_quantlist__44u6__p4_0[] = {
  150391. 2,
  150392. 1,
  150393. 3,
  150394. 0,
  150395. 4,
  150396. };
  150397. static long _vq_lengthlist__44u6__p4_0[] = {
  150398. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  150399. 9, 9,11,11, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  150400. 8,10,10, 7, 7, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  150401. 11,12, 6, 7, 7, 9, 9, 7, 8, 7,10, 9, 7, 8, 8,10,
  150402. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  150403. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,13,11,
  150404. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150405. 10,12,12,11,12,11,13,12,11,12,12,13,13, 5, 7, 7,
  150406. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  150407. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  150408. 8, 9, 9,11,11,10,10,11,12,13,10,10,11,12,12, 6,
  150409. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  150410. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  150411. 13,13,10,11,11,12,13,12,12,12,13,14,12,12,13,14,
  150412. 14, 9,10,10,12,12, 9,10,10,13,12,10,11,11,13,13,
  150413. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  150414. 8, 7,10,10, 7, 8, 8,10,10, 9,10,10,12,11, 9,10,
  150415. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  150416. 10,11,10,11,11,12,12,10,10,11,11,13, 7, 8, 8,10,
  150417. 10, 8, 9, 9,11,11, 8, 9, 8,11,11,10,11,10,13,12,
  150418. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,12, 9,
  150419. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  150420. 10,12,12,10,11,11,13,13,10,11,10,13,12,12,12,12,
  150421. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  150422. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,14,
  150423. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  150424. 12,13,14,15,12,12,13,14,14, 9,10,10,12,12, 9,11,
  150425. 10,13,12,10,10,11,12,13,12,13,12,14,13,12,12,13,
  150426. 14,15,11,12,12,14,13,11,12,12,14,14,12,13,13,14,
  150427. 14,13,13,14,14,16,13,14,14,15,15,11,12,11,13,13,
  150428. 11,12,11,14,13,12,12,13,14,15,12,14,12,15,12,13,
  150429. 14,15,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  150430. 10,12,12,11,12,12,14,13,11,12,12,13,13, 9,10,10,
  150431. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  150432. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  150433. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  150434. 11,11,13,13,12,13,12,14,14,11,11,12,13,14,14,14,
  150435. 14,16,15,12,12,14,12,15,11,12,12,13,14,12,13,13,
  150436. 14,15,11,12,12,14,14,13,14,14,16,16,13,14,13,16,
  150437. 13,
  150438. };
  150439. static float _vq_quantthresh__44u6__p4_0[] = {
  150440. -1.5, -0.5, 0.5, 1.5,
  150441. };
  150442. static long _vq_quantmap__44u6__p4_0[] = {
  150443. 3, 1, 0, 2, 4,
  150444. };
  150445. static encode_aux_threshmatch _vq_auxt__44u6__p4_0 = {
  150446. _vq_quantthresh__44u6__p4_0,
  150447. _vq_quantmap__44u6__p4_0,
  150448. 5,
  150449. 5
  150450. };
  150451. static static_codebook _44u6__p4_0 = {
  150452. 4, 625,
  150453. _vq_lengthlist__44u6__p4_0,
  150454. 1, -533725184, 1611661312, 3, 0,
  150455. _vq_quantlist__44u6__p4_0,
  150456. NULL,
  150457. &_vq_auxt__44u6__p4_0,
  150458. NULL,
  150459. 0
  150460. };
  150461. static long _vq_quantlist__44u6__p5_0[] = {
  150462. 4,
  150463. 3,
  150464. 5,
  150465. 2,
  150466. 6,
  150467. 1,
  150468. 7,
  150469. 0,
  150470. 8,
  150471. };
  150472. static long _vq_lengthlist__44u6__p5_0[] = {
  150473. 2, 3, 3, 6, 6, 8, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  150474. 11,11, 3, 5, 5, 7, 8, 8, 8,11,11, 6, 8, 7, 9, 9,
  150475. 10, 9,12,11, 6, 7, 8, 9, 9, 9,10,11,12, 8, 8, 8,
  150476. 10, 9,12,11,13,13, 8, 8, 9, 9,10,11,12,13,13,10,
  150477. 11,11,12,12,13,13,14,14,10,10,11,11,12,13,13,14,
  150478. 14,
  150479. };
  150480. static float _vq_quantthresh__44u6__p5_0[] = {
  150481. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150482. };
  150483. static long _vq_quantmap__44u6__p5_0[] = {
  150484. 7, 5, 3, 1, 0, 2, 4, 6,
  150485. 8,
  150486. };
  150487. static encode_aux_threshmatch _vq_auxt__44u6__p5_0 = {
  150488. _vq_quantthresh__44u6__p5_0,
  150489. _vq_quantmap__44u6__p5_0,
  150490. 9,
  150491. 9
  150492. };
  150493. static static_codebook _44u6__p5_0 = {
  150494. 2, 81,
  150495. _vq_lengthlist__44u6__p5_0,
  150496. 1, -531628032, 1611661312, 4, 0,
  150497. _vq_quantlist__44u6__p5_0,
  150498. NULL,
  150499. &_vq_auxt__44u6__p5_0,
  150500. NULL,
  150501. 0
  150502. };
  150503. static long _vq_quantlist__44u6__p6_0[] = {
  150504. 4,
  150505. 3,
  150506. 5,
  150507. 2,
  150508. 6,
  150509. 1,
  150510. 7,
  150511. 0,
  150512. 8,
  150513. };
  150514. static long _vq_lengthlist__44u6__p6_0[] = {
  150515. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  150516. 9, 9, 4, 4, 5, 6, 6, 7, 8, 9, 9, 5, 6, 6, 7, 7,
  150517. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  150518. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,10,11, 9,
  150519. 9, 9,10,10,11,11,12,11, 9, 9, 9,10,10,11,11,11,
  150520. 12,
  150521. };
  150522. static float _vq_quantthresh__44u6__p6_0[] = {
  150523. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  150524. };
  150525. static long _vq_quantmap__44u6__p6_0[] = {
  150526. 7, 5, 3, 1, 0, 2, 4, 6,
  150527. 8,
  150528. };
  150529. static encode_aux_threshmatch _vq_auxt__44u6__p6_0 = {
  150530. _vq_quantthresh__44u6__p6_0,
  150531. _vq_quantmap__44u6__p6_0,
  150532. 9,
  150533. 9
  150534. };
  150535. static static_codebook _44u6__p6_0 = {
  150536. 2, 81,
  150537. _vq_lengthlist__44u6__p6_0,
  150538. 1, -531628032, 1611661312, 4, 0,
  150539. _vq_quantlist__44u6__p6_0,
  150540. NULL,
  150541. &_vq_auxt__44u6__p6_0,
  150542. NULL,
  150543. 0
  150544. };
  150545. static long _vq_quantlist__44u6__p7_0[] = {
  150546. 1,
  150547. 0,
  150548. 2,
  150549. };
  150550. static long _vq_lengthlist__44u6__p7_0[] = {
  150551. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 7,10,10, 8,
  150552. 10,10, 5, 8, 9, 7,10,10, 7,10, 9, 4, 8, 8, 9,11,
  150553. 11, 8,11,11, 7,11,11,10,10,13,10,13,13, 7,11,11,
  150554. 10,13,12,10,13,13, 5, 9, 8, 8,11,11, 9,11,11, 7,
  150555. 11,11,10,13,13,10,12,13, 7,11,11,10,13,13, 9,13,
  150556. 10,
  150557. };
  150558. static float _vq_quantthresh__44u6__p7_0[] = {
  150559. -5.5, 5.5,
  150560. };
  150561. static long _vq_quantmap__44u6__p7_0[] = {
  150562. 1, 0, 2,
  150563. };
  150564. static encode_aux_threshmatch _vq_auxt__44u6__p7_0 = {
  150565. _vq_quantthresh__44u6__p7_0,
  150566. _vq_quantmap__44u6__p7_0,
  150567. 3,
  150568. 3
  150569. };
  150570. static static_codebook _44u6__p7_0 = {
  150571. 4, 81,
  150572. _vq_lengthlist__44u6__p7_0,
  150573. 1, -529137664, 1618345984, 2, 0,
  150574. _vq_quantlist__44u6__p7_0,
  150575. NULL,
  150576. &_vq_auxt__44u6__p7_0,
  150577. NULL,
  150578. 0
  150579. };
  150580. static long _vq_quantlist__44u6__p7_1[] = {
  150581. 5,
  150582. 4,
  150583. 6,
  150584. 3,
  150585. 7,
  150586. 2,
  150587. 8,
  150588. 1,
  150589. 9,
  150590. 0,
  150591. 10,
  150592. };
  150593. static long _vq_lengthlist__44u6__p7_1[] = {
  150594. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 7, 6,
  150595. 8, 8, 8, 8, 8, 8, 4, 5, 5, 6, 7, 8, 8, 8, 8, 8,
  150596. 8, 6, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 6, 7, 7, 7,
  150597. 7, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 9, 9,
  150598. 9, 9, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9, 8, 8, 8,
  150599. 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9,
  150600. 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8,
  150601. 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150602. };
  150603. static float _vq_quantthresh__44u6__p7_1[] = {
  150604. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150605. 3.5, 4.5,
  150606. };
  150607. static long _vq_quantmap__44u6__p7_1[] = {
  150608. 9, 7, 5, 3, 1, 0, 2, 4,
  150609. 6, 8, 10,
  150610. };
  150611. static encode_aux_threshmatch _vq_auxt__44u6__p7_1 = {
  150612. _vq_quantthresh__44u6__p7_1,
  150613. _vq_quantmap__44u6__p7_1,
  150614. 11,
  150615. 11
  150616. };
  150617. static static_codebook _44u6__p7_1 = {
  150618. 2, 121,
  150619. _vq_lengthlist__44u6__p7_1,
  150620. 1, -531365888, 1611661312, 4, 0,
  150621. _vq_quantlist__44u6__p7_1,
  150622. NULL,
  150623. &_vq_auxt__44u6__p7_1,
  150624. NULL,
  150625. 0
  150626. };
  150627. static long _vq_quantlist__44u6__p8_0[] = {
  150628. 5,
  150629. 4,
  150630. 6,
  150631. 3,
  150632. 7,
  150633. 2,
  150634. 8,
  150635. 1,
  150636. 9,
  150637. 0,
  150638. 10,
  150639. };
  150640. static long _vq_lengthlist__44u6__p8_0[] = {
  150641. 1, 4, 4, 6, 6, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7,
  150642. 9, 9,10,10,11,11, 4, 6, 6, 7, 7, 9, 9,10,10,11,
  150643. 11, 6, 8, 8, 9, 9,10,10,11,11,12,12, 6, 8, 8, 9,
  150644. 9,10,10,11,11,12,12, 8, 9, 9,10,10,11,11,12,12,
  150645. 13,13, 8, 9, 9,10,10,11,11,12,12,13,13,10,10,10,
  150646. 11,11,13,13,13,13,15,14, 9,10,10,12,11,12,13,13,
  150647. 13,14,15,11,12,12,13,13,13,13,15,14,15,15,11,11,
  150648. 12,13,13,14,14,14,15,15,15,
  150649. };
  150650. static float _vq_quantthresh__44u6__p8_0[] = {
  150651. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  150652. 38.5, 49.5,
  150653. };
  150654. static long _vq_quantmap__44u6__p8_0[] = {
  150655. 9, 7, 5, 3, 1, 0, 2, 4,
  150656. 6, 8, 10,
  150657. };
  150658. static encode_aux_threshmatch _vq_auxt__44u6__p8_0 = {
  150659. _vq_quantthresh__44u6__p8_0,
  150660. _vq_quantmap__44u6__p8_0,
  150661. 11,
  150662. 11
  150663. };
  150664. static static_codebook _44u6__p8_0 = {
  150665. 2, 121,
  150666. _vq_lengthlist__44u6__p8_0,
  150667. 1, -524582912, 1618345984, 4, 0,
  150668. _vq_quantlist__44u6__p8_0,
  150669. NULL,
  150670. &_vq_auxt__44u6__p8_0,
  150671. NULL,
  150672. 0
  150673. };
  150674. static long _vq_quantlist__44u6__p8_1[] = {
  150675. 5,
  150676. 4,
  150677. 6,
  150678. 3,
  150679. 7,
  150680. 2,
  150681. 8,
  150682. 1,
  150683. 9,
  150684. 0,
  150685. 10,
  150686. };
  150687. static long _vq_lengthlist__44u6__p8_1[] = {
  150688. 3, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 5, 7, 7,
  150689. 7, 7, 8, 7, 8, 8, 5, 5, 6, 6, 7, 7, 7, 7, 7, 8,
  150690. 8, 6, 7, 7, 7, 7, 8, 7, 8, 8, 8, 8, 6, 6, 7, 7,
  150691. 7, 7, 8, 8, 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8,
  150692. 8, 8, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 7, 7, 7,
  150693. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  150694. 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  150695. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  150696. };
  150697. static float _vq_quantthresh__44u6__p8_1[] = {
  150698. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  150699. 3.5, 4.5,
  150700. };
  150701. static long _vq_quantmap__44u6__p8_1[] = {
  150702. 9, 7, 5, 3, 1, 0, 2, 4,
  150703. 6, 8, 10,
  150704. };
  150705. static encode_aux_threshmatch _vq_auxt__44u6__p8_1 = {
  150706. _vq_quantthresh__44u6__p8_1,
  150707. _vq_quantmap__44u6__p8_1,
  150708. 11,
  150709. 11
  150710. };
  150711. static static_codebook _44u6__p8_1 = {
  150712. 2, 121,
  150713. _vq_lengthlist__44u6__p8_1,
  150714. 1, -531365888, 1611661312, 4, 0,
  150715. _vq_quantlist__44u6__p8_1,
  150716. NULL,
  150717. &_vq_auxt__44u6__p8_1,
  150718. NULL,
  150719. 0
  150720. };
  150721. static long _vq_quantlist__44u6__p9_0[] = {
  150722. 7,
  150723. 6,
  150724. 8,
  150725. 5,
  150726. 9,
  150727. 4,
  150728. 10,
  150729. 3,
  150730. 11,
  150731. 2,
  150732. 12,
  150733. 1,
  150734. 13,
  150735. 0,
  150736. 14,
  150737. };
  150738. static long _vq_lengthlist__44u6__p9_0[] = {
  150739. 1, 3, 2, 9, 8,15,15,15,15,15,15,15,15,15,15, 4,
  150740. 8, 9,13,14,14,14,14,14,14,14,14,14,14,14, 5, 8,
  150741. 9,14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,
  150742. 14,14,14,14,14,14,14,14,14,14,14,14,11,14,14,14,
  150743. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150744. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150745. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150746. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150747. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150748. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150749. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150750. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150751. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150752. 14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,14,
  150753. 14,
  150754. };
  150755. static float _vq_quantthresh__44u6__p9_0[] = {
  150756. -1657.5, -1402.5, -1147.5, -892.5, -637.5, -382.5, -127.5, 127.5,
  150757. 382.5, 637.5, 892.5, 1147.5, 1402.5, 1657.5,
  150758. };
  150759. static long _vq_quantmap__44u6__p9_0[] = {
  150760. 13, 11, 9, 7, 5, 3, 1, 0,
  150761. 2, 4, 6, 8, 10, 12, 14,
  150762. };
  150763. static encode_aux_threshmatch _vq_auxt__44u6__p9_0 = {
  150764. _vq_quantthresh__44u6__p9_0,
  150765. _vq_quantmap__44u6__p9_0,
  150766. 15,
  150767. 15
  150768. };
  150769. static static_codebook _44u6__p9_0 = {
  150770. 2, 225,
  150771. _vq_lengthlist__44u6__p9_0,
  150772. 1, -514071552, 1627381760, 4, 0,
  150773. _vq_quantlist__44u6__p9_0,
  150774. NULL,
  150775. &_vq_auxt__44u6__p9_0,
  150776. NULL,
  150777. 0
  150778. };
  150779. static long _vq_quantlist__44u6__p9_1[] = {
  150780. 7,
  150781. 6,
  150782. 8,
  150783. 5,
  150784. 9,
  150785. 4,
  150786. 10,
  150787. 3,
  150788. 11,
  150789. 2,
  150790. 12,
  150791. 1,
  150792. 13,
  150793. 0,
  150794. 14,
  150795. };
  150796. static long _vq_lengthlist__44u6__p9_1[] = {
  150797. 1, 4, 4, 7, 7, 8, 9, 8, 8, 9, 8, 9, 8, 9, 9, 4,
  150798. 7, 6, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 4, 7,
  150799. 6, 9, 9,10,10, 9, 9,10,10,10,10,11,11, 7, 9, 8,
  150800. 10,10,11,11,10,10,11,11,11,11,11,11, 7, 8, 9,10,
  150801. 10,11,11,10,10,11,11,11,11,11,12, 8,10,10,11,11,
  150802. 12,12,11,11,12,12,12,12,13,12, 8,10,10,11,11,12,
  150803. 11,11,11,11,12,12,12,12,13, 8, 9, 9,11,10,11,11,
  150804. 12,12,12,12,13,12,13,12, 8, 9, 9,11,11,11,11,12,
  150805. 12,12,12,12,13,13,13, 9,10,10,11,12,12,12,12,12,
  150806. 13,13,13,13,13,13, 9,10,10,11,11,12,12,12,12,13,
  150807. 13,13,13,14,13,10,10,10,12,11,12,12,13,13,13,13,
  150808. 13,13,13,13,10,10,11,11,11,12,12,13,13,13,13,13,
  150809. 13,13,13,10,11,11,12,12,13,12,12,13,13,13,13,13,
  150810. 13,14,10,11,11,12,12,13,12,13,13,13,14,13,13,14,
  150811. 13,
  150812. };
  150813. static float _vq_quantthresh__44u6__p9_1[] = {
  150814. -110.5, -93.5, -76.5, -59.5, -42.5, -25.5, -8.5, 8.5,
  150815. 25.5, 42.5, 59.5, 76.5, 93.5, 110.5,
  150816. };
  150817. static long _vq_quantmap__44u6__p9_1[] = {
  150818. 13, 11, 9, 7, 5, 3, 1, 0,
  150819. 2, 4, 6, 8, 10, 12, 14,
  150820. };
  150821. static encode_aux_threshmatch _vq_auxt__44u6__p9_1 = {
  150822. _vq_quantthresh__44u6__p9_1,
  150823. _vq_quantmap__44u6__p9_1,
  150824. 15,
  150825. 15
  150826. };
  150827. static static_codebook _44u6__p9_1 = {
  150828. 2, 225,
  150829. _vq_lengthlist__44u6__p9_1,
  150830. 1, -522338304, 1620115456, 4, 0,
  150831. _vq_quantlist__44u6__p9_1,
  150832. NULL,
  150833. &_vq_auxt__44u6__p9_1,
  150834. NULL,
  150835. 0
  150836. };
  150837. static long _vq_quantlist__44u6__p9_2[] = {
  150838. 8,
  150839. 7,
  150840. 9,
  150841. 6,
  150842. 10,
  150843. 5,
  150844. 11,
  150845. 4,
  150846. 12,
  150847. 3,
  150848. 13,
  150849. 2,
  150850. 14,
  150851. 1,
  150852. 15,
  150853. 0,
  150854. 16,
  150855. };
  150856. static long _vq_lengthlist__44u6__p9_2[] = {
  150857. 3, 5, 5, 7, 7, 8, 8, 8, 8, 8, 8, 9, 8, 8, 9, 9,
  150858. 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9, 9,
  150859. 9, 9, 5, 6, 6, 7, 7, 8, 8, 8, 8, 8, 8, 9, 9, 9,
  150860. 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150861. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150862. 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150863. 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  150864. 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9, 9,
  150865. 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  150866. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 9, 9, 9, 9, 9, 9,
  150867. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 8, 9, 9, 9, 9, 9,
  150868. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  150869. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9, 9, 9, 9, 9,
  150870. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,
  150871. 9, 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9, 9,
  150872. 9, 9, 9, 9, 9, 9, 9,10, 9, 9, 9,10, 9, 9,10, 9,
  150873. 9, 9, 9, 9, 9, 9, 9, 9,10,10,10, 9,10, 9,10,10,
  150874. 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10,10, 9, 9,
  150875. 10,
  150876. };
  150877. static float _vq_quantthresh__44u6__p9_2[] = {
  150878. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  150879. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  150880. };
  150881. static long _vq_quantmap__44u6__p9_2[] = {
  150882. 15, 13, 11, 9, 7, 5, 3, 1,
  150883. 0, 2, 4, 6, 8, 10, 12, 14,
  150884. 16,
  150885. };
  150886. static encode_aux_threshmatch _vq_auxt__44u6__p9_2 = {
  150887. _vq_quantthresh__44u6__p9_2,
  150888. _vq_quantmap__44u6__p9_2,
  150889. 17,
  150890. 17
  150891. };
  150892. static static_codebook _44u6__p9_2 = {
  150893. 2, 289,
  150894. _vq_lengthlist__44u6__p9_2,
  150895. 1, -529530880, 1611661312, 5, 0,
  150896. _vq_quantlist__44u6__p9_2,
  150897. NULL,
  150898. &_vq_auxt__44u6__p9_2,
  150899. NULL,
  150900. 0
  150901. };
  150902. static long _huff_lengthlist__44u6__short[] = {
  150903. 4,11,16,13,17,13,17,16,17,17, 4, 7, 9, 9,13,10,
  150904. 16,12,16,17, 7, 6, 5, 7, 8, 9,12,12,16,17, 6, 9,
  150905. 7, 9,10,10,15,15,17,17, 6, 7, 5, 7, 5, 7, 7,10,
  150906. 16,17, 7, 9, 8, 9, 8,10,11,11,15,17, 7, 7, 7, 8,
  150907. 5, 8, 8, 9,15,17, 8, 7, 9, 9, 7, 8, 7, 2, 7,15,
  150908. 14,13,13,15, 5,10, 4, 3, 6,17,17,15,13,17, 7,11,
  150909. 7, 6, 9,16,
  150910. };
  150911. static static_codebook _huff_book__44u6__short = {
  150912. 2, 100,
  150913. _huff_lengthlist__44u6__short,
  150914. 0, 0, 0, 0, 0,
  150915. NULL,
  150916. NULL,
  150917. NULL,
  150918. NULL,
  150919. 0
  150920. };
  150921. static long _huff_lengthlist__44u7__long[] = {
  150922. 3, 9,14,13,15,14,16,13,13,14, 5, 5, 7, 7, 8, 9,
  150923. 11,10,12,15,10, 6, 5, 6, 6, 9,10,10,13,16,10, 6,
  150924. 6, 6, 6, 8, 9, 9,12,15,14, 7, 6, 6, 5, 6, 6, 8,
  150925. 12,15,10, 8, 7, 7, 6, 7, 7, 7,11,13,14,10, 9, 8,
  150926. 5, 6, 4, 5, 9,12,10, 9, 9, 8, 6, 6, 5, 3, 6,11,
  150927. 12,11,12,12,10, 9, 8, 5, 5, 8,10,11,15,13,13,13,
  150928. 12, 8, 6, 7,
  150929. };
  150930. static static_codebook _huff_book__44u7__long = {
  150931. 2, 100,
  150932. _huff_lengthlist__44u7__long,
  150933. 0, 0, 0, 0, 0,
  150934. NULL,
  150935. NULL,
  150936. NULL,
  150937. NULL,
  150938. 0
  150939. };
  150940. static long _vq_quantlist__44u7__p1_0[] = {
  150941. 1,
  150942. 0,
  150943. 2,
  150944. };
  150945. static long _vq_lengthlist__44u7__p1_0[] = {
  150946. 1, 4, 4, 4, 7, 7, 5, 7, 7, 5, 8, 8, 8,10,10, 7,
  150947. 10,10, 5, 8, 8, 7,10,10, 8,10,10, 5, 8, 8, 8,11,
  150948. 10, 8,10,10, 8,10,10,10,12,13,10,13,13, 7,10,10,
  150949. 10,13,12,10,13,13, 5, 8, 8, 8,11,10, 8,10,11, 7,
  150950. 10,10,10,13,13,10,12,13, 8,11,11,10,13,13,10,13,
  150951. 12,
  150952. };
  150953. static float _vq_quantthresh__44u7__p1_0[] = {
  150954. -0.5, 0.5,
  150955. };
  150956. static long _vq_quantmap__44u7__p1_0[] = {
  150957. 1, 0, 2,
  150958. };
  150959. static encode_aux_threshmatch _vq_auxt__44u7__p1_0 = {
  150960. _vq_quantthresh__44u7__p1_0,
  150961. _vq_quantmap__44u7__p1_0,
  150962. 3,
  150963. 3
  150964. };
  150965. static static_codebook _44u7__p1_0 = {
  150966. 4, 81,
  150967. _vq_lengthlist__44u7__p1_0,
  150968. 1, -535822336, 1611661312, 2, 0,
  150969. _vq_quantlist__44u7__p1_0,
  150970. NULL,
  150971. &_vq_auxt__44u7__p1_0,
  150972. NULL,
  150973. 0
  150974. };
  150975. static long _vq_quantlist__44u7__p2_0[] = {
  150976. 1,
  150977. 0,
  150978. 2,
  150979. };
  150980. static long _vq_lengthlist__44u7__p2_0[] = {
  150981. 3, 4, 4, 5, 6, 6, 5, 6, 6, 5, 6, 6, 6, 8, 8, 6,
  150982. 7, 8, 5, 6, 6, 6, 8, 7, 6, 8, 8, 5, 6, 6, 6, 8,
  150983. 7, 6, 8, 8, 6, 8, 8, 8, 9, 9, 8, 9, 9, 6, 8, 7,
  150984. 7, 9, 8, 8, 9, 9, 5, 6, 6, 6, 8, 7, 6, 8, 8, 6,
  150985. 8, 8, 8, 9, 9, 7, 8, 9, 6, 8, 8, 8, 9, 9, 8, 9,
  150986. 9,
  150987. };
  150988. static float _vq_quantthresh__44u7__p2_0[] = {
  150989. -0.5, 0.5,
  150990. };
  150991. static long _vq_quantmap__44u7__p2_0[] = {
  150992. 1, 0, 2,
  150993. };
  150994. static encode_aux_threshmatch _vq_auxt__44u7__p2_0 = {
  150995. _vq_quantthresh__44u7__p2_0,
  150996. _vq_quantmap__44u7__p2_0,
  150997. 3,
  150998. 3
  150999. };
  151000. static static_codebook _44u7__p2_0 = {
  151001. 4, 81,
  151002. _vq_lengthlist__44u7__p2_0,
  151003. 1, -535822336, 1611661312, 2, 0,
  151004. _vq_quantlist__44u7__p2_0,
  151005. NULL,
  151006. &_vq_auxt__44u7__p2_0,
  151007. NULL,
  151008. 0
  151009. };
  151010. static long _vq_quantlist__44u7__p3_0[] = {
  151011. 2,
  151012. 1,
  151013. 3,
  151014. 0,
  151015. 4,
  151016. };
  151017. static long _vq_lengthlist__44u7__p3_0[] = {
  151018. 2, 5, 4, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151019. 9, 9,13,12, 8, 9,10,12,13, 5, 7, 7,10, 9, 7, 9,
  151020. 9,11,11, 6, 8, 9,11,11,10,11,11,14,14, 9,10,11,
  151021. 13,14, 5, 7, 7, 9, 9, 7, 9, 8,11,11, 7, 9, 9,11,
  151022. 11, 9,11,10,14,13,10,11,11,14,14, 8,10,10,14,13,
  151023. 10,11,12,15,14, 9,11,11,15,14,13,14,14,16,16,12,
  151024. 13,14,17,16, 8,10,10,13,13, 9,11,11,14,15,10,11,
  151025. 12,14,15,12,14,13,16,16,13,14,15,15,17, 5, 7, 7,
  151026. 10,10, 7, 9, 9,11,11, 7, 9, 9,11,11,10,12,11,15,
  151027. 14,10,11,12,14,14, 7, 9, 9,12,12, 9,11,11,13,13,
  151028. 9,11,11,13,13,11,13,13,14,17,11,13,13,15,16, 6,
  151029. 9, 9,11,11, 8,11,10,13,12, 9,11,11,13,13,11,13,
  151030. 12,16,14,11,13,13,16,16,10,12,12,15,15,11,13,13,
  151031. 16,16,11,13,13,16,15,14,16,17,17,19,14,16,16,18,
  151032. 0, 9,11,11,14,15,10,13,12,16,15,11,13,13,16,16,
  151033. 14,15,14, 0,16,14,16,16,18, 0, 5, 7, 7,10,10, 7,
  151034. 9, 9,12,11, 7, 9, 9,11,12,10,11,11,15,14,10,11,
  151035. 12,14,14, 6, 9, 9,11,11, 9,11,11,13,13, 8,10,11,
  151036. 12,13,11,13,13,17,15,11,12,13,14,15, 7, 9, 9,11,
  151037. 12, 9,11,11,13,13, 9,11,11,13,13,11,13,12,16,16,
  151038. 11,13,13,15,14, 9,11,11,14,15,11,13,13,16,15,10,
  151039. 12,13,16,16,15,16,16, 0, 0,14,13,15,16,18,10,11,
  151040. 11,15,15,11,13,14,16,18,11,13,13,16,15,15,16,16,
  151041. 19, 0,14,15,15,16,16, 8,10,10,13,13,10,12,11,16,
  151042. 15,10,11,11,16,15,13,15,16,18, 0,13,14,15,17,17,
  151043. 9,11,11,15,15,11,13,13,16,18,11,13,13,16,17,15,
  151044. 16,16, 0, 0,15,18,16, 0,17, 9,11,11,15,15,11,13,
  151045. 12,17,15,11,13,14,16,17,15,18,15, 0,17,15,16,16,
  151046. 18,19,13,15,14, 0,18,14,16,16,19,18,14,16,15,19,
  151047. 19,16,18,19, 0, 0,16,17, 0, 0, 0,12,14,14,17,17,
  151048. 13,16,14, 0,18,14,16,15,18, 0,16,18,16,19,17,18,
  151049. 19,17, 0, 0, 8,10,10,14,14, 9,12,11,15,15,10,11,
  151050. 12,15,17,13,15,15,18,16,14,16,15,18,17, 9,11,11,
  151051. 16,15,11,13,13, 0,16,11,12,13,16,15,15,16,16, 0,
  151052. 17,15,15,16,18,17, 9,12,11,15,17,11,13,13,16,16,
  151053. 11,14,13,16,16,15,15,16,18,19,16,18,16, 0, 0,12,
  151054. 14,14, 0,16,14,16,16, 0,18,13,14,15,16, 0,17,16,
  151055. 18, 0, 0,16,16,17,19, 0,13,14,14,17, 0,14,17,16,
  151056. 0,19,14,15,15,18,19,17,16,18, 0, 0,15,19,16, 0,
  151057. 0,
  151058. };
  151059. static float _vq_quantthresh__44u7__p3_0[] = {
  151060. -1.5, -0.5, 0.5, 1.5,
  151061. };
  151062. static long _vq_quantmap__44u7__p3_0[] = {
  151063. 3, 1, 0, 2, 4,
  151064. };
  151065. static encode_aux_threshmatch _vq_auxt__44u7__p3_0 = {
  151066. _vq_quantthresh__44u7__p3_0,
  151067. _vq_quantmap__44u7__p3_0,
  151068. 5,
  151069. 5
  151070. };
  151071. static static_codebook _44u7__p3_0 = {
  151072. 4, 625,
  151073. _vq_lengthlist__44u7__p3_0,
  151074. 1, -533725184, 1611661312, 3, 0,
  151075. _vq_quantlist__44u7__p3_0,
  151076. NULL,
  151077. &_vq_auxt__44u7__p3_0,
  151078. NULL,
  151079. 0
  151080. };
  151081. static long _vq_quantlist__44u7__p4_0[] = {
  151082. 2,
  151083. 1,
  151084. 3,
  151085. 0,
  151086. 4,
  151087. };
  151088. static long _vq_lengthlist__44u7__p4_0[] = {
  151089. 4, 5, 5, 8, 8, 6, 7, 6, 9, 9, 6, 6, 7, 9, 9, 8,
  151090. 9, 9,11,11, 8, 9, 9,10,11, 6, 7, 7, 9, 9, 7, 8,
  151091. 8,10,10, 6, 7, 8, 9,10, 9,10,10,12,12, 9, 9,10,
  151092. 11,12, 6, 7, 7, 9, 9, 6, 8, 7,10, 9, 7, 8, 8,10,
  151093. 10, 9,10, 9,12,11, 9,10,10,12,11, 8, 9, 9,11,11,
  151094. 9,10,10,12,12, 9,10,10,12,12,11,12,12,13,14,11,
  151095. 11,12,13,13, 8, 9, 9,11,11, 9,10,10,12,11, 9,10,
  151096. 10,12,12,11,12,11,13,13,11,12,12,13,13, 6, 7, 7,
  151097. 9, 9, 7, 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,
  151098. 11, 9,10,10,12,12, 7, 8, 8,10,10, 8, 8, 9,11,11,
  151099. 8, 9, 9,11,11,10,11,11,12,12,10,10,11,12,13, 6,
  151100. 7, 7,10,10, 7, 9, 8,11,10, 8, 8, 9,10,11,10,11,
  151101. 10,13,11,10,11,11,12,12, 9,10,10,12,12,10,10,11,
  151102. 13,13,10,11,11,13,12,12,12,13,13,14,12,12,13,14,
  151103. 14, 9,10,10,12,12, 9,10,10,12,12,10,11,11,13,13,
  151104. 11,12,11,14,12,12,13,13,14,14, 6, 7, 7, 9, 9, 7,
  151105. 8, 7,10,10, 7, 7, 8,10,10, 9,10,10,12,11, 9,10,
  151106. 10,11,12, 6, 7, 7,10,10, 8, 9, 8,11,10, 7, 8, 9,
  151107. 10,11,10,11,11,13,12,10,10,11,11,13, 7, 8, 8,10,
  151108. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,10,13,12,
  151109. 10,11,11,12,12, 9,10,10,12,12,10,11,11,13,12, 9,
  151110. 10,10,12,13,12,13,12,14,14,11,11,12,12,14, 9,10,
  151111. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,12,
  151112. 14,14,12,13,12,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151113. 12, 9,10,10,12,12,11,12,12,14,13,11,12,12,13,13,
  151114. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,12,12,
  151115. 13,13,14,14,12,12,13,14,14, 9,10,10,12,12, 9,11,
  151116. 10,13,12,10,10,11,12,13,11,13,12,14,13,12,12,13,
  151117. 14,14,11,12,12,13,13,11,12,13,14,14,12,13,13,14,
  151118. 14,13,13,14,14,16,13,14,14,16,16,11,11,11,13,13,
  151119. 11,12,11,14,13,12,12,13,14,15,13,14,12,16,13,14,
  151120. 14,14,15,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151121. 10,12,12,11,12,12,14,13,11,12,12,13,14, 9,10,10,
  151122. 12,12,10,11,10,13,12, 9,10,11,12,13,12,13,12,14,
  151123. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,12,13,
  151124. 10,11,11,13,13,12,13,12,14,14,12,13,13,14,14,11,
  151125. 12,12,13,13,12,13,12,14,14,11,11,12,13,14,13,15,
  151126. 14,16,15,13,12,14,13,16,11,12,12,13,13,12,13,13,
  151127. 14,14,12,12,12,14,14,13,14,14,15,15,13,14,13,16,
  151128. 14,
  151129. };
  151130. static float _vq_quantthresh__44u7__p4_0[] = {
  151131. -1.5, -0.5, 0.5, 1.5,
  151132. };
  151133. static long _vq_quantmap__44u7__p4_0[] = {
  151134. 3, 1, 0, 2, 4,
  151135. };
  151136. static encode_aux_threshmatch _vq_auxt__44u7__p4_0 = {
  151137. _vq_quantthresh__44u7__p4_0,
  151138. _vq_quantmap__44u7__p4_0,
  151139. 5,
  151140. 5
  151141. };
  151142. static static_codebook _44u7__p4_0 = {
  151143. 4, 625,
  151144. _vq_lengthlist__44u7__p4_0,
  151145. 1, -533725184, 1611661312, 3, 0,
  151146. _vq_quantlist__44u7__p4_0,
  151147. NULL,
  151148. &_vq_auxt__44u7__p4_0,
  151149. NULL,
  151150. 0
  151151. };
  151152. static long _vq_quantlist__44u7__p5_0[] = {
  151153. 4,
  151154. 3,
  151155. 5,
  151156. 2,
  151157. 6,
  151158. 1,
  151159. 7,
  151160. 0,
  151161. 8,
  151162. };
  151163. static long _vq_lengthlist__44u7__p5_0[] = {
  151164. 2, 3, 3, 6, 6, 7, 8,10,10, 4, 5, 5, 8, 7, 8, 8,
  151165. 11,11, 3, 5, 5, 7, 7, 8, 9,11,11, 6, 8, 7, 9, 9,
  151166. 10,10,12,12, 6, 7, 8, 9,10,10,10,12,12, 8, 8, 8,
  151167. 10,10,12,11,13,13, 8, 8, 9,10,10,11,11,13,13,10,
  151168. 11,11,12,12,13,13,14,14,10,11,11,12,12,13,13,14,
  151169. 14,
  151170. };
  151171. static float _vq_quantthresh__44u7__p5_0[] = {
  151172. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151173. };
  151174. static long _vq_quantmap__44u7__p5_0[] = {
  151175. 7, 5, 3, 1, 0, 2, 4, 6,
  151176. 8,
  151177. };
  151178. static encode_aux_threshmatch _vq_auxt__44u7__p5_0 = {
  151179. _vq_quantthresh__44u7__p5_0,
  151180. _vq_quantmap__44u7__p5_0,
  151181. 9,
  151182. 9
  151183. };
  151184. static static_codebook _44u7__p5_0 = {
  151185. 2, 81,
  151186. _vq_lengthlist__44u7__p5_0,
  151187. 1, -531628032, 1611661312, 4, 0,
  151188. _vq_quantlist__44u7__p5_0,
  151189. NULL,
  151190. &_vq_auxt__44u7__p5_0,
  151191. NULL,
  151192. 0
  151193. };
  151194. static long _vq_quantlist__44u7__p6_0[] = {
  151195. 4,
  151196. 3,
  151197. 5,
  151198. 2,
  151199. 6,
  151200. 1,
  151201. 7,
  151202. 0,
  151203. 8,
  151204. };
  151205. static long _vq_lengthlist__44u7__p6_0[] = {
  151206. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 8, 7,
  151207. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151208. 8, 8,10,10, 5, 6, 6, 7, 7, 8, 8,10,10, 7, 8, 7,
  151209. 8, 8,10, 9,11,11, 7, 7, 8, 8, 8, 9,10,11,11, 9,
  151210. 9, 9,10,10,11,10,12,11, 9, 9, 9,10,10,11,11,11,
  151211. 12,
  151212. };
  151213. static float _vq_quantthresh__44u7__p6_0[] = {
  151214. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151215. };
  151216. static long _vq_quantmap__44u7__p6_0[] = {
  151217. 7, 5, 3, 1, 0, 2, 4, 6,
  151218. 8,
  151219. };
  151220. static encode_aux_threshmatch _vq_auxt__44u7__p6_0 = {
  151221. _vq_quantthresh__44u7__p6_0,
  151222. _vq_quantmap__44u7__p6_0,
  151223. 9,
  151224. 9
  151225. };
  151226. static static_codebook _44u7__p6_0 = {
  151227. 2, 81,
  151228. _vq_lengthlist__44u7__p6_0,
  151229. 1, -531628032, 1611661312, 4, 0,
  151230. _vq_quantlist__44u7__p6_0,
  151231. NULL,
  151232. &_vq_auxt__44u7__p6_0,
  151233. NULL,
  151234. 0
  151235. };
  151236. static long _vq_quantlist__44u7__p7_0[] = {
  151237. 1,
  151238. 0,
  151239. 2,
  151240. };
  151241. static long _vq_lengthlist__44u7__p7_0[] = {
  151242. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 9, 8, 8, 9, 9, 7,
  151243. 10,10, 5, 8, 9, 7, 9,10, 8, 9, 9, 4, 9, 9, 9,11,
  151244. 10, 8,10,10, 7,11,10,10,10,12,10,12,12, 7,10,10,
  151245. 10,12,11,10,12,12, 5, 9, 9, 8,10,10, 9,11,11, 7,
  151246. 11,10,10,12,12,10,11,12, 7,10,11,10,12,12,10,12,
  151247. 10,
  151248. };
  151249. static float _vq_quantthresh__44u7__p7_0[] = {
  151250. -5.5, 5.5,
  151251. };
  151252. static long _vq_quantmap__44u7__p7_0[] = {
  151253. 1, 0, 2,
  151254. };
  151255. static encode_aux_threshmatch _vq_auxt__44u7__p7_0 = {
  151256. _vq_quantthresh__44u7__p7_0,
  151257. _vq_quantmap__44u7__p7_0,
  151258. 3,
  151259. 3
  151260. };
  151261. static static_codebook _44u7__p7_0 = {
  151262. 4, 81,
  151263. _vq_lengthlist__44u7__p7_0,
  151264. 1, -529137664, 1618345984, 2, 0,
  151265. _vq_quantlist__44u7__p7_0,
  151266. NULL,
  151267. &_vq_auxt__44u7__p7_0,
  151268. NULL,
  151269. 0
  151270. };
  151271. static long _vq_quantlist__44u7__p7_1[] = {
  151272. 5,
  151273. 4,
  151274. 6,
  151275. 3,
  151276. 7,
  151277. 2,
  151278. 8,
  151279. 1,
  151280. 9,
  151281. 0,
  151282. 10,
  151283. };
  151284. static long _vq_lengthlist__44u7__p7_1[] = {
  151285. 3, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6,
  151286. 8, 7, 8, 8, 8, 8, 4, 5, 5, 6, 6, 7, 8, 8, 8, 8,
  151287. 8, 6, 7, 6, 7, 7, 8, 8, 9, 9, 9, 9, 6, 6, 7, 7,
  151288. 7, 8, 8, 9, 9, 9, 9, 7, 8, 7, 8, 8, 9, 9, 9, 9,
  151289. 9, 9, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  151290. 9, 9, 9, 9,10, 9, 9, 9, 8, 8, 8, 9, 9, 9, 9, 9,
  151291. 9, 9,10, 8, 8, 8, 9, 9, 9, 9,10, 9,10,10, 8, 8,
  151292. 8, 9, 9, 9, 9, 9,10,10,10,
  151293. };
  151294. static float _vq_quantthresh__44u7__p7_1[] = {
  151295. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151296. 3.5, 4.5,
  151297. };
  151298. static long _vq_quantmap__44u7__p7_1[] = {
  151299. 9, 7, 5, 3, 1, 0, 2, 4,
  151300. 6, 8, 10,
  151301. };
  151302. static encode_aux_threshmatch _vq_auxt__44u7__p7_1 = {
  151303. _vq_quantthresh__44u7__p7_1,
  151304. _vq_quantmap__44u7__p7_1,
  151305. 11,
  151306. 11
  151307. };
  151308. static static_codebook _44u7__p7_1 = {
  151309. 2, 121,
  151310. _vq_lengthlist__44u7__p7_1,
  151311. 1, -531365888, 1611661312, 4, 0,
  151312. _vq_quantlist__44u7__p7_1,
  151313. NULL,
  151314. &_vq_auxt__44u7__p7_1,
  151315. NULL,
  151316. 0
  151317. };
  151318. static long _vq_quantlist__44u7__p8_0[] = {
  151319. 5,
  151320. 4,
  151321. 6,
  151322. 3,
  151323. 7,
  151324. 2,
  151325. 8,
  151326. 1,
  151327. 9,
  151328. 0,
  151329. 10,
  151330. };
  151331. static long _vq_lengthlist__44u7__p8_0[] = {
  151332. 1, 4, 4, 6, 6, 8, 8,10,10,11,11, 4, 6, 6, 7, 7,
  151333. 9, 9,11,10,12,12, 5, 6, 5, 7, 7, 9, 9,10,11,12,
  151334. 12, 6, 7, 7, 8, 8,10,10,11,11,13,13, 6, 7, 7, 8,
  151335. 8,10,10,11,12,13,13, 8, 9, 9,10,10,11,11,12,12,
  151336. 14,14, 8, 9, 9,10,10,11,11,12,12,14,14,10,10,10,
  151337. 11,11,13,12,14,14,15,15,10,10,10,12,12,13,13,14,
  151338. 14,15,15,11,12,12,13,13,14,14,15,14,16,15,11,12,
  151339. 12,13,13,14,14,15,15,15,16,
  151340. };
  151341. static float _vq_quantthresh__44u7__p8_0[] = {
  151342. -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5, 27.5,
  151343. 38.5, 49.5,
  151344. };
  151345. static long _vq_quantmap__44u7__p8_0[] = {
  151346. 9, 7, 5, 3, 1, 0, 2, 4,
  151347. 6, 8, 10,
  151348. };
  151349. static encode_aux_threshmatch _vq_auxt__44u7__p8_0 = {
  151350. _vq_quantthresh__44u7__p8_0,
  151351. _vq_quantmap__44u7__p8_0,
  151352. 11,
  151353. 11
  151354. };
  151355. static static_codebook _44u7__p8_0 = {
  151356. 2, 121,
  151357. _vq_lengthlist__44u7__p8_0,
  151358. 1, -524582912, 1618345984, 4, 0,
  151359. _vq_quantlist__44u7__p8_0,
  151360. NULL,
  151361. &_vq_auxt__44u7__p8_0,
  151362. NULL,
  151363. 0
  151364. };
  151365. static long _vq_quantlist__44u7__p8_1[] = {
  151366. 5,
  151367. 4,
  151368. 6,
  151369. 3,
  151370. 7,
  151371. 2,
  151372. 8,
  151373. 1,
  151374. 9,
  151375. 0,
  151376. 10,
  151377. };
  151378. static long _vq_lengthlist__44u7__p8_1[] = {
  151379. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  151380. 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 7, 7, 7, 7, 7, 7,
  151381. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  151382. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  151383. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  151384. 7, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  151385. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  151386. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  151387. };
  151388. static float _vq_quantthresh__44u7__p8_1[] = {
  151389. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151390. 3.5, 4.5,
  151391. };
  151392. static long _vq_quantmap__44u7__p8_1[] = {
  151393. 9, 7, 5, 3, 1, 0, 2, 4,
  151394. 6, 8, 10,
  151395. };
  151396. static encode_aux_threshmatch _vq_auxt__44u7__p8_1 = {
  151397. _vq_quantthresh__44u7__p8_1,
  151398. _vq_quantmap__44u7__p8_1,
  151399. 11,
  151400. 11
  151401. };
  151402. static static_codebook _44u7__p8_1 = {
  151403. 2, 121,
  151404. _vq_lengthlist__44u7__p8_1,
  151405. 1, -531365888, 1611661312, 4, 0,
  151406. _vq_quantlist__44u7__p8_1,
  151407. NULL,
  151408. &_vq_auxt__44u7__p8_1,
  151409. NULL,
  151410. 0
  151411. };
  151412. static long _vq_quantlist__44u7__p9_0[] = {
  151413. 5,
  151414. 4,
  151415. 6,
  151416. 3,
  151417. 7,
  151418. 2,
  151419. 8,
  151420. 1,
  151421. 9,
  151422. 0,
  151423. 10,
  151424. };
  151425. static long _vq_lengthlist__44u7__p9_0[] = {
  151426. 1, 3, 3,10,10,10,10,10,10,10,10, 4,10,10,10,10,
  151427. 10,10,10,10,10,10, 4,10,10,10,10,10,10,10,10,10,
  151428. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151429. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151430. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151431. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  151432. 10,10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9,
  151433. 9, 9, 9, 9, 9, 9, 9, 9, 9,
  151434. };
  151435. static float _vq_quantthresh__44u7__p9_0[] = {
  151436. -2866.5, -2229.5, -1592.5, -955.5, -318.5, 318.5, 955.5, 1592.5,
  151437. 2229.5, 2866.5,
  151438. };
  151439. static long _vq_quantmap__44u7__p9_0[] = {
  151440. 9, 7, 5, 3, 1, 0, 2, 4,
  151441. 6, 8, 10,
  151442. };
  151443. static encode_aux_threshmatch _vq_auxt__44u7__p9_0 = {
  151444. _vq_quantthresh__44u7__p9_0,
  151445. _vq_quantmap__44u7__p9_0,
  151446. 11,
  151447. 11
  151448. };
  151449. static static_codebook _44u7__p9_0 = {
  151450. 2, 121,
  151451. _vq_lengthlist__44u7__p9_0,
  151452. 1, -512171520, 1630791680, 4, 0,
  151453. _vq_quantlist__44u7__p9_0,
  151454. NULL,
  151455. &_vq_auxt__44u7__p9_0,
  151456. NULL,
  151457. 0
  151458. };
  151459. static long _vq_quantlist__44u7__p9_1[] = {
  151460. 6,
  151461. 5,
  151462. 7,
  151463. 4,
  151464. 8,
  151465. 3,
  151466. 9,
  151467. 2,
  151468. 10,
  151469. 1,
  151470. 11,
  151471. 0,
  151472. 12,
  151473. };
  151474. static long _vq_lengthlist__44u7__p9_1[] = {
  151475. 1, 4, 4, 6, 5, 8, 6, 9, 8,10, 9,11,10, 4, 6, 6,
  151476. 8, 8, 9, 9,11,10,11,11,11,11, 4, 6, 6, 8, 8,10,
  151477. 9,11,11,11,11,11,12, 6, 8, 8,10,10,11,11,12,12,
  151478. 13,12,13,13, 6, 8, 8,10,10,11,11,12,12,12,13,14,
  151479. 13, 8,10,10,11,11,12,13,14,14,14,14,15,15, 8,10,
  151480. 10,11,12,12,13,13,14,14,14,14,15, 9,11,11,13,13,
  151481. 14,14,15,14,16,15,17,15, 9,11,11,12,13,14,14,15,
  151482. 14,15,15,15,16,10,12,12,13,14,15,15,15,15,16,17,
  151483. 16,17,10,13,12,13,14,14,16,16,16,16,15,16,17,11,
  151484. 13,13,14,15,14,17,15,16,17,17,17,17,11,13,13,14,
  151485. 15,15,15,15,17,17,16,17,16,
  151486. };
  151487. static float _vq_quantthresh__44u7__p9_1[] = {
  151488. -269.5, -220.5, -171.5, -122.5, -73.5, -24.5, 24.5, 73.5,
  151489. 122.5, 171.5, 220.5, 269.5,
  151490. };
  151491. static long _vq_quantmap__44u7__p9_1[] = {
  151492. 11, 9, 7, 5, 3, 1, 0, 2,
  151493. 4, 6, 8, 10, 12,
  151494. };
  151495. static encode_aux_threshmatch _vq_auxt__44u7__p9_1 = {
  151496. _vq_quantthresh__44u7__p9_1,
  151497. _vq_quantmap__44u7__p9_1,
  151498. 13,
  151499. 13
  151500. };
  151501. static static_codebook _44u7__p9_1 = {
  151502. 2, 169,
  151503. _vq_lengthlist__44u7__p9_1,
  151504. 1, -518889472, 1622704128, 4, 0,
  151505. _vq_quantlist__44u7__p9_1,
  151506. NULL,
  151507. &_vq_auxt__44u7__p9_1,
  151508. NULL,
  151509. 0
  151510. };
  151511. static long _vq_quantlist__44u7__p9_2[] = {
  151512. 24,
  151513. 23,
  151514. 25,
  151515. 22,
  151516. 26,
  151517. 21,
  151518. 27,
  151519. 20,
  151520. 28,
  151521. 19,
  151522. 29,
  151523. 18,
  151524. 30,
  151525. 17,
  151526. 31,
  151527. 16,
  151528. 32,
  151529. 15,
  151530. 33,
  151531. 14,
  151532. 34,
  151533. 13,
  151534. 35,
  151535. 12,
  151536. 36,
  151537. 11,
  151538. 37,
  151539. 10,
  151540. 38,
  151541. 9,
  151542. 39,
  151543. 8,
  151544. 40,
  151545. 7,
  151546. 41,
  151547. 6,
  151548. 42,
  151549. 5,
  151550. 43,
  151551. 4,
  151552. 44,
  151553. 3,
  151554. 45,
  151555. 2,
  151556. 46,
  151557. 1,
  151558. 47,
  151559. 0,
  151560. 48,
  151561. };
  151562. static long _vq_lengthlist__44u7__p9_2[] = {
  151563. 2, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  151564. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  151565. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8,
  151566. 8,
  151567. };
  151568. static float _vq_quantthresh__44u7__p9_2[] = {
  151569. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  151570. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  151571. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151572. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151573. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  151574. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  151575. };
  151576. static long _vq_quantmap__44u7__p9_2[] = {
  151577. 47, 45, 43, 41, 39, 37, 35, 33,
  151578. 31, 29, 27, 25, 23, 21, 19, 17,
  151579. 15, 13, 11, 9, 7, 5, 3, 1,
  151580. 0, 2, 4, 6, 8, 10, 12, 14,
  151581. 16, 18, 20, 22, 24, 26, 28, 30,
  151582. 32, 34, 36, 38, 40, 42, 44, 46,
  151583. 48,
  151584. };
  151585. static encode_aux_threshmatch _vq_auxt__44u7__p9_2 = {
  151586. _vq_quantthresh__44u7__p9_2,
  151587. _vq_quantmap__44u7__p9_2,
  151588. 49,
  151589. 49
  151590. };
  151591. static static_codebook _44u7__p9_2 = {
  151592. 1, 49,
  151593. _vq_lengthlist__44u7__p9_2,
  151594. 1, -526909440, 1611661312, 6, 0,
  151595. _vq_quantlist__44u7__p9_2,
  151596. NULL,
  151597. &_vq_auxt__44u7__p9_2,
  151598. NULL,
  151599. 0
  151600. };
  151601. static long _huff_lengthlist__44u7__short[] = {
  151602. 5,12,17,16,16,17,17,17,17,17, 4, 7,11,11,12, 9,
  151603. 17,10,17,17, 7, 7, 8, 9, 7, 9,11,10,15,17, 7, 9,
  151604. 10,11,10,12,14,12,16,17, 7, 8, 5, 7, 4, 7, 7, 8,
  151605. 16,16, 6,10, 9,10, 7,10,11,11,16,17, 6, 8, 8, 9,
  151606. 5, 7, 5, 8,16,17, 5, 5, 8, 7, 6, 7, 7, 6, 6,14,
  151607. 12,10,12,11, 7,11, 4, 4, 2, 7,17,15,15,15, 8,15,
  151608. 6, 8, 5, 9,
  151609. };
  151610. static static_codebook _huff_book__44u7__short = {
  151611. 2, 100,
  151612. _huff_lengthlist__44u7__short,
  151613. 0, 0, 0, 0, 0,
  151614. NULL,
  151615. NULL,
  151616. NULL,
  151617. NULL,
  151618. 0
  151619. };
  151620. static long _huff_lengthlist__44u8__long[] = {
  151621. 3, 9,13,14,14,15,14,14,15,15, 5, 4, 6, 8,10,12,
  151622. 12,14,15,15, 9, 5, 4, 5, 8,10,11,13,16,16,10, 7,
  151623. 4, 3, 5, 7, 9,11,13,13,10, 9, 7, 4, 4, 6, 8,10,
  151624. 12,14,13,11, 9, 6, 5, 5, 6, 8,12,14,13,11,10, 8,
  151625. 7, 6, 6, 7,10,14,13,11,12,10, 8, 7, 6, 6, 9,13,
  151626. 12,11,14,12,11, 9, 8, 7, 9,11,11,12,14,13,14,11,
  151627. 10, 8, 8, 9,
  151628. };
  151629. static static_codebook _huff_book__44u8__long = {
  151630. 2, 100,
  151631. _huff_lengthlist__44u8__long,
  151632. 0, 0, 0, 0, 0,
  151633. NULL,
  151634. NULL,
  151635. NULL,
  151636. NULL,
  151637. 0
  151638. };
  151639. static long _huff_lengthlist__44u8__short[] = {
  151640. 6,14,18,18,17,17,17,17,17,17, 4, 7, 9, 9,10,13,
  151641. 15,17,17,17, 6, 7, 5, 6, 8,11,16,17,16,17, 5, 7,
  151642. 5, 4, 6,10,14,17,17,17, 6, 6, 6, 5, 7,10,13,16,
  151643. 17,17, 7, 6, 7, 7, 7, 8, 7,10,15,16,12, 9, 9, 6,
  151644. 6, 5, 3, 5,11,15,14,14,13, 5, 5, 7, 3, 4, 8,15,
  151645. 17,17,13, 7, 7,10, 6, 6,10,15,17,17,16,10,11,14,
  151646. 10,10,15,17,
  151647. };
  151648. static static_codebook _huff_book__44u8__short = {
  151649. 2, 100,
  151650. _huff_lengthlist__44u8__short,
  151651. 0, 0, 0, 0, 0,
  151652. NULL,
  151653. NULL,
  151654. NULL,
  151655. NULL,
  151656. 0
  151657. };
  151658. static long _vq_quantlist__44u8_p1_0[] = {
  151659. 1,
  151660. 0,
  151661. 2,
  151662. };
  151663. static long _vq_lengthlist__44u8_p1_0[] = {
  151664. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 8, 9, 9, 7,
  151665. 9, 9, 5, 7, 7, 7, 9, 9, 8, 9, 9, 5, 7, 7, 7, 9,
  151666. 9, 7, 9, 9, 7, 9, 9, 9,10,11, 9,11,10, 7, 9, 9,
  151667. 9,11,10, 9,10,11, 5, 7, 7, 7, 9, 9, 7, 9, 9, 7,
  151668. 9, 9, 9,11,10, 9,10,10, 8, 9, 9, 9,11,11, 9,11,
  151669. 10,
  151670. };
  151671. static float _vq_quantthresh__44u8_p1_0[] = {
  151672. -0.5, 0.5,
  151673. };
  151674. static long _vq_quantmap__44u8_p1_0[] = {
  151675. 1, 0, 2,
  151676. };
  151677. static encode_aux_threshmatch _vq_auxt__44u8_p1_0 = {
  151678. _vq_quantthresh__44u8_p1_0,
  151679. _vq_quantmap__44u8_p1_0,
  151680. 3,
  151681. 3
  151682. };
  151683. static static_codebook _44u8_p1_0 = {
  151684. 4, 81,
  151685. _vq_lengthlist__44u8_p1_0,
  151686. 1, -535822336, 1611661312, 2, 0,
  151687. _vq_quantlist__44u8_p1_0,
  151688. NULL,
  151689. &_vq_auxt__44u8_p1_0,
  151690. NULL,
  151691. 0
  151692. };
  151693. static long _vq_quantlist__44u8_p2_0[] = {
  151694. 2,
  151695. 1,
  151696. 3,
  151697. 0,
  151698. 4,
  151699. };
  151700. static long _vq_lengthlist__44u8_p2_0[] = {
  151701. 4, 5, 5, 8, 8, 5, 7, 6, 9, 9, 5, 6, 7, 9, 9, 8,
  151702. 9, 9,11,11, 8, 9, 9,11,11, 5, 7, 7, 9, 9, 7, 8,
  151703. 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,10,
  151704. 11,12, 5, 7, 7, 9, 9, 7, 8, 7,10,10, 7, 8, 8,10,
  151705. 10, 9,10, 9,12,11, 9,10,10,12,12, 8, 9, 9,12,11,
  151706. 9,10,10,12,12, 9,10,10,12,12,11,12,12,14,14,11,
  151707. 11,12,13,14, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151708. 10,12,12,11,12,11,13,13,11,12,12,14,14, 5, 7, 7,
  151709. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  151710. 12, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  151711. 8, 9, 9,11,11,10,11,11,12,13,10,11,11,12,13, 6,
  151712. 8, 8,10,10, 8, 9, 8,11,10, 8, 9, 9,11,11,10,11,
  151713. 10,13,12,10,11,11,13,13, 9,10,10,12,12,10,11,11,
  151714. 13,13,10,11,11,13,13,12,12,13,13,14,12,13,13,14,
  151715. 14, 9,10,10,12,12,10,11,10,13,12,10,11,11,13,13,
  151716. 11,13,12,14,13,12,13,13,14,14, 5, 7, 7, 9, 9, 7,
  151717. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,12, 9,10,
  151718. 10,12,12, 7, 8, 8,10,10, 8, 9, 9,11,11, 8, 8, 9,
  151719. 10,11,10,11,11,13,13,10,10,11,12,13, 7, 8, 8,10,
  151720. 10, 8, 9, 9,11,11, 8, 9, 9,11,11,10,11,11,13,13,
  151721. 10,11,11,13,12, 9,10,10,12,12,10,11,11,13,13,10,
  151722. 10,11,12,13,12,13,13,14,14,12,12,13,13,14, 9,10,
  151723. 10,12,12,10,11,11,13,13,10,11,11,13,13,12,13,13,
  151724. 15,14,12,13,13,14,13, 8, 9, 9,11,11, 9,10,10,12,
  151725. 12, 9,10,10,12,12,12,12,12,14,13,11,12,12,14,14,
  151726. 9,10,10,12,12,10,11,11,13,13,10,11,11,13,13,12,
  151727. 13,13,14,15,12,13,13,14,15, 9,10,10,12,12,10,11,
  151728. 10,13,12,10,11,11,13,13,12,13,12,15,14,12,13,13,
  151729. 14,15,11,12,12,14,14,12,13,13,14,14,12,13,13,15,
  151730. 14,14,14,14,14,16,14,14,15,16,16,11,12,12,14,14,
  151731. 11,12,12,14,14,12,13,13,14,15,13,14,13,16,14,14,
  151732. 14,14,16,16, 8, 9, 9,11,11, 9,10,10,12,12, 9,10,
  151733. 10,12,12,11,12,12,14,13,11,12,12,14,14, 9,10,10,
  151734. 12,12,10,11,11,13,13,10,10,11,12,13,12,13,13,15,
  151735. 14,12,12,13,13,14, 9,10,10,12,12,10,11,11,13,13,
  151736. 10,11,11,13,13,12,13,13,14,14,12,13,13,15,14,11,
  151737. 12,12,14,13,12,13,13,15,14,11,12,12,13,14,14,15,
  151738. 14,16,15,13,13,14,13,16,11,12,12,14,14,12,13,13,
  151739. 14,15,12,13,12,15,14,14,14,14,16,15,14,15,13,16,
  151740. 14,
  151741. };
  151742. static float _vq_quantthresh__44u8_p2_0[] = {
  151743. -1.5, -0.5, 0.5, 1.5,
  151744. };
  151745. static long _vq_quantmap__44u8_p2_0[] = {
  151746. 3, 1, 0, 2, 4,
  151747. };
  151748. static encode_aux_threshmatch _vq_auxt__44u8_p2_0 = {
  151749. _vq_quantthresh__44u8_p2_0,
  151750. _vq_quantmap__44u8_p2_0,
  151751. 5,
  151752. 5
  151753. };
  151754. static static_codebook _44u8_p2_0 = {
  151755. 4, 625,
  151756. _vq_lengthlist__44u8_p2_0,
  151757. 1, -533725184, 1611661312, 3, 0,
  151758. _vq_quantlist__44u8_p2_0,
  151759. NULL,
  151760. &_vq_auxt__44u8_p2_0,
  151761. NULL,
  151762. 0
  151763. };
  151764. static long _vq_quantlist__44u8_p3_0[] = {
  151765. 4,
  151766. 3,
  151767. 5,
  151768. 2,
  151769. 6,
  151770. 1,
  151771. 7,
  151772. 0,
  151773. 8,
  151774. };
  151775. static long _vq_lengthlist__44u8_p3_0[] = {
  151776. 3, 4, 4, 5, 5, 7, 7, 9, 9, 4, 5, 4, 6, 6, 7, 7,
  151777. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  151778. 8, 8,10,10, 6, 6, 6, 7, 7, 8, 8,10,10, 7, 7, 7,
  151779. 8, 8, 9, 9,11,10, 7, 7, 7, 8, 8, 9, 9,10,11, 9,
  151780. 9, 9,10,10,11,10,12,11, 9, 9, 9, 9,10,11,11,11,
  151781. 12,
  151782. };
  151783. static float _vq_quantthresh__44u8_p3_0[] = {
  151784. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  151785. };
  151786. static long _vq_quantmap__44u8_p3_0[] = {
  151787. 7, 5, 3, 1, 0, 2, 4, 6,
  151788. 8,
  151789. };
  151790. static encode_aux_threshmatch _vq_auxt__44u8_p3_0 = {
  151791. _vq_quantthresh__44u8_p3_0,
  151792. _vq_quantmap__44u8_p3_0,
  151793. 9,
  151794. 9
  151795. };
  151796. static static_codebook _44u8_p3_0 = {
  151797. 2, 81,
  151798. _vq_lengthlist__44u8_p3_0,
  151799. 1, -531628032, 1611661312, 4, 0,
  151800. _vq_quantlist__44u8_p3_0,
  151801. NULL,
  151802. &_vq_auxt__44u8_p3_0,
  151803. NULL,
  151804. 0
  151805. };
  151806. static long _vq_quantlist__44u8_p4_0[] = {
  151807. 8,
  151808. 7,
  151809. 9,
  151810. 6,
  151811. 10,
  151812. 5,
  151813. 11,
  151814. 4,
  151815. 12,
  151816. 3,
  151817. 13,
  151818. 2,
  151819. 14,
  151820. 1,
  151821. 15,
  151822. 0,
  151823. 16,
  151824. };
  151825. static long _vq_lengthlist__44u8_p4_0[] = {
  151826. 4, 4, 4, 6, 6, 7, 7, 8, 8, 8, 8,10,10,11,11,11,
  151827. 11, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,
  151828. 12,12, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9,10,10,11,
  151829. 11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,10,
  151830. 11,11,12,12, 6, 6, 6, 7, 7, 8, 8, 9, 9, 9, 9,10,
  151831. 10,11,11,12,12, 7, 7, 7, 8, 8, 9, 8,10, 9,10, 9,
  151832. 11,10,12,11,13,12, 7, 7, 7, 8, 8, 8, 9, 9,10, 9,
  151833. 10,10,11,11,12,12,13, 8, 8, 8, 9, 9, 9, 9,10,10,
  151834. 11,10,11,11,12,12,13,13, 8, 8, 8, 9, 9, 9,10,10,
  151835. 10,10,11,11,11,12,12,12,13, 8, 9, 9, 9, 9,10, 9,
  151836. 11,10,11,11,12,11,13,12,13,13, 8, 9, 9, 9, 9, 9,
  151837. 10,10,11,11,11,11,12,12,13,13,13,10,10,10,10,10,
  151838. 11,10,11,11,12,11,13,12,13,13,14,13,10,10,10,10,
  151839. 10,10,11,11,11,11,12,12,13,13,13,13,14,11,11,11,
  151840. 11,11,12,11,12,12,13,12,13,13,14,13,14,14,11,11,
  151841. 11,11,11,11,12,12,12,12,13,13,13,13,14,14,14,11,
  151842. 12,12,12,12,13,12,13,12,13,13,14,13,14,14,14,14,
  151843. 11,12,12,12,12,12,12,13,13,13,13,13,14,14,14,14,
  151844. 14,
  151845. };
  151846. static float _vq_quantthresh__44u8_p4_0[] = {
  151847. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  151848. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  151849. };
  151850. static long _vq_quantmap__44u8_p4_0[] = {
  151851. 15, 13, 11, 9, 7, 5, 3, 1,
  151852. 0, 2, 4, 6, 8, 10, 12, 14,
  151853. 16,
  151854. };
  151855. static encode_aux_threshmatch _vq_auxt__44u8_p4_0 = {
  151856. _vq_quantthresh__44u8_p4_0,
  151857. _vq_quantmap__44u8_p4_0,
  151858. 17,
  151859. 17
  151860. };
  151861. static static_codebook _44u8_p4_0 = {
  151862. 2, 289,
  151863. _vq_lengthlist__44u8_p4_0,
  151864. 1, -529530880, 1611661312, 5, 0,
  151865. _vq_quantlist__44u8_p4_0,
  151866. NULL,
  151867. &_vq_auxt__44u8_p4_0,
  151868. NULL,
  151869. 0
  151870. };
  151871. static long _vq_quantlist__44u8_p5_0[] = {
  151872. 1,
  151873. 0,
  151874. 2,
  151875. };
  151876. static long _vq_lengthlist__44u8_p5_0[] = {
  151877. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  151878. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  151879. 10, 8,10,10, 7,10,10, 9,10,12, 9,12,11, 7,10,10,
  151880. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  151881. 10,10, 9,11,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  151882. 10,
  151883. };
  151884. static float _vq_quantthresh__44u8_p5_0[] = {
  151885. -5.5, 5.5,
  151886. };
  151887. static long _vq_quantmap__44u8_p5_0[] = {
  151888. 1, 0, 2,
  151889. };
  151890. static encode_aux_threshmatch _vq_auxt__44u8_p5_0 = {
  151891. _vq_quantthresh__44u8_p5_0,
  151892. _vq_quantmap__44u8_p5_0,
  151893. 3,
  151894. 3
  151895. };
  151896. static static_codebook _44u8_p5_0 = {
  151897. 4, 81,
  151898. _vq_lengthlist__44u8_p5_0,
  151899. 1, -529137664, 1618345984, 2, 0,
  151900. _vq_quantlist__44u8_p5_0,
  151901. NULL,
  151902. &_vq_auxt__44u8_p5_0,
  151903. NULL,
  151904. 0
  151905. };
  151906. static long _vq_quantlist__44u8_p5_1[] = {
  151907. 5,
  151908. 4,
  151909. 6,
  151910. 3,
  151911. 7,
  151912. 2,
  151913. 8,
  151914. 1,
  151915. 9,
  151916. 0,
  151917. 10,
  151918. };
  151919. static long _vq_lengthlist__44u8_p5_1[] = {
  151920. 4, 5, 5, 6, 6, 7, 7, 7, 7, 8, 8, 5, 5, 5, 6, 6,
  151921. 7, 7, 8, 8, 8, 8, 5, 5, 5, 6, 6, 7, 7, 7, 8, 8,
  151922. 8, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 8, 6, 6, 6, 7,
  151923. 7, 7, 7, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8,
  151924. 8, 8, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 7, 8, 7,
  151925. 8, 8, 8, 8, 8, 8, 8, 8, 7, 8, 8, 8, 8, 8, 8, 8,
  151926. 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 9, 9, 8, 8,
  151927. 8, 8, 8, 8, 8, 8, 8, 9, 9,
  151928. };
  151929. static float _vq_quantthresh__44u8_p5_1[] = {
  151930. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  151931. 3.5, 4.5,
  151932. };
  151933. static long _vq_quantmap__44u8_p5_1[] = {
  151934. 9, 7, 5, 3, 1, 0, 2, 4,
  151935. 6, 8, 10,
  151936. };
  151937. static encode_aux_threshmatch _vq_auxt__44u8_p5_1 = {
  151938. _vq_quantthresh__44u8_p5_1,
  151939. _vq_quantmap__44u8_p5_1,
  151940. 11,
  151941. 11
  151942. };
  151943. static static_codebook _44u8_p5_1 = {
  151944. 2, 121,
  151945. _vq_lengthlist__44u8_p5_1,
  151946. 1, -531365888, 1611661312, 4, 0,
  151947. _vq_quantlist__44u8_p5_1,
  151948. NULL,
  151949. &_vq_auxt__44u8_p5_1,
  151950. NULL,
  151951. 0
  151952. };
  151953. static long _vq_quantlist__44u8_p6_0[] = {
  151954. 6,
  151955. 5,
  151956. 7,
  151957. 4,
  151958. 8,
  151959. 3,
  151960. 9,
  151961. 2,
  151962. 10,
  151963. 1,
  151964. 11,
  151965. 0,
  151966. 12,
  151967. };
  151968. static long _vq_lengthlist__44u8_p6_0[] = {
  151969. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  151970. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 6, 6, 7, 7, 8,
  151971. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 7, 8, 8, 8, 8, 9,
  151972. 9,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 8,10, 9,11,
  151973. 10, 7, 8, 8, 8, 8, 8, 9, 9, 9,10,10,11,11, 7, 8,
  151974. 8, 8, 8, 9, 8, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  151975. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  151976. 9,10,10,11,11, 9, 9, 9, 9,10,10,10,10,10,10,11,
  151977. 11,12, 9, 9, 9,10, 9,10,10,10,10,11,10,12,11,10,
  151978. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  151979. 11,11,11,11,11,12,11,12,12,
  151980. };
  151981. static float _vq_quantthresh__44u8_p6_0[] = {
  151982. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  151983. 12.5, 17.5, 22.5, 27.5,
  151984. };
  151985. static long _vq_quantmap__44u8_p6_0[] = {
  151986. 11, 9, 7, 5, 3, 1, 0, 2,
  151987. 4, 6, 8, 10, 12,
  151988. };
  151989. static encode_aux_threshmatch _vq_auxt__44u8_p6_0 = {
  151990. _vq_quantthresh__44u8_p6_0,
  151991. _vq_quantmap__44u8_p6_0,
  151992. 13,
  151993. 13
  151994. };
  151995. static static_codebook _44u8_p6_0 = {
  151996. 2, 169,
  151997. _vq_lengthlist__44u8_p6_0,
  151998. 1, -526516224, 1616117760, 4, 0,
  151999. _vq_quantlist__44u8_p6_0,
  152000. NULL,
  152001. &_vq_auxt__44u8_p6_0,
  152002. NULL,
  152003. 0
  152004. };
  152005. static long _vq_quantlist__44u8_p6_1[] = {
  152006. 2,
  152007. 1,
  152008. 3,
  152009. 0,
  152010. 4,
  152011. };
  152012. static long _vq_lengthlist__44u8_p6_1[] = {
  152013. 3, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 5, 5, 5,
  152014. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152015. };
  152016. static float _vq_quantthresh__44u8_p6_1[] = {
  152017. -1.5, -0.5, 0.5, 1.5,
  152018. };
  152019. static long _vq_quantmap__44u8_p6_1[] = {
  152020. 3, 1, 0, 2, 4,
  152021. };
  152022. static encode_aux_threshmatch _vq_auxt__44u8_p6_1 = {
  152023. _vq_quantthresh__44u8_p6_1,
  152024. _vq_quantmap__44u8_p6_1,
  152025. 5,
  152026. 5
  152027. };
  152028. static static_codebook _44u8_p6_1 = {
  152029. 2, 25,
  152030. _vq_lengthlist__44u8_p6_1,
  152031. 1, -533725184, 1611661312, 3, 0,
  152032. _vq_quantlist__44u8_p6_1,
  152033. NULL,
  152034. &_vq_auxt__44u8_p6_1,
  152035. NULL,
  152036. 0
  152037. };
  152038. static long _vq_quantlist__44u8_p7_0[] = {
  152039. 6,
  152040. 5,
  152041. 7,
  152042. 4,
  152043. 8,
  152044. 3,
  152045. 9,
  152046. 2,
  152047. 10,
  152048. 1,
  152049. 11,
  152050. 0,
  152051. 12,
  152052. };
  152053. static long _vq_lengthlist__44u8_p7_0[] = {
  152054. 1, 4, 5, 6, 6, 7, 7, 8, 8,10,10,11,11, 5, 6, 6,
  152055. 7, 7, 8, 8, 9, 9,11,10,12,11, 5, 6, 6, 7, 7, 8,
  152056. 8, 9, 9,10,11,11,12, 6, 7, 7, 8, 8, 9, 9,10,10,
  152057. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,12,13,
  152058. 12, 7, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152059. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152060. 11,11,12,12,13,13,14,14, 9, 9, 9,10,10,11,11,12,
  152061. 12,13,13,14,14,10,11,11,12,11,13,12,13,13,14,14,
  152062. 15,15,10,11,11,11,12,12,13,13,14,14,14,15,15,11,
  152063. 12,12,13,13,14,13,15,14,15,15,16,15,11,11,12,13,
  152064. 13,13,14,14,14,15,15,15,16,
  152065. };
  152066. static float _vq_quantthresh__44u8_p7_0[] = {
  152067. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152068. 27.5, 38.5, 49.5, 60.5,
  152069. };
  152070. static long _vq_quantmap__44u8_p7_0[] = {
  152071. 11, 9, 7, 5, 3, 1, 0, 2,
  152072. 4, 6, 8, 10, 12,
  152073. };
  152074. static encode_aux_threshmatch _vq_auxt__44u8_p7_0 = {
  152075. _vq_quantthresh__44u8_p7_0,
  152076. _vq_quantmap__44u8_p7_0,
  152077. 13,
  152078. 13
  152079. };
  152080. static static_codebook _44u8_p7_0 = {
  152081. 2, 169,
  152082. _vq_lengthlist__44u8_p7_0,
  152083. 1, -523206656, 1618345984, 4, 0,
  152084. _vq_quantlist__44u8_p7_0,
  152085. NULL,
  152086. &_vq_auxt__44u8_p7_0,
  152087. NULL,
  152088. 0
  152089. };
  152090. static long _vq_quantlist__44u8_p7_1[] = {
  152091. 5,
  152092. 4,
  152093. 6,
  152094. 3,
  152095. 7,
  152096. 2,
  152097. 8,
  152098. 1,
  152099. 9,
  152100. 0,
  152101. 10,
  152102. };
  152103. static long _vq_lengthlist__44u8_p7_1[] = {
  152104. 4, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7,
  152105. 7, 7, 7, 7, 7, 7, 5, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152106. 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 6, 7, 7, 7,
  152107. 7, 7, 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8,
  152108. 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 7, 7, 7,
  152109. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 7, 8, 8, 8,
  152110. 8, 8, 8, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 7,
  152111. 7, 8, 8, 8, 8, 8, 8, 8, 8,
  152112. };
  152113. static float _vq_quantthresh__44u8_p7_1[] = {
  152114. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152115. 3.5, 4.5,
  152116. };
  152117. static long _vq_quantmap__44u8_p7_1[] = {
  152118. 9, 7, 5, 3, 1, 0, 2, 4,
  152119. 6, 8, 10,
  152120. };
  152121. static encode_aux_threshmatch _vq_auxt__44u8_p7_1 = {
  152122. _vq_quantthresh__44u8_p7_1,
  152123. _vq_quantmap__44u8_p7_1,
  152124. 11,
  152125. 11
  152126. };
  152127. static static_codebook _44u8_p7_1 = {
  152128. 2, 121,
  152129. _vq_lengthlist__44u8_p7_1,
  152130. 1, -531365888, 1611661312, 4, 0,
  152131. _vq_quantlist__44u8_p7_1,
  152132. NULL,
  152133. &_vq_auxt__44u8_p7_1,
  152134. NULL,
  152135. 0
  152136. };
  152137. static long _vq_quantlist__44u8_p8_0[] = {
  152138. 7,
  152139. 6,
  152140. 8,
  152141. 5,
  152142. 9,
  152143. 4,
  152144. 10,
  152145. 3,
  152146. 11,
  152147. 2,
  152148. 12,
  152149. 1,
  152150. 13,
  152151. 0,
  152152. 14,
  152153. };
  152154. static long _vq_lengthlist__44u8_p8_0[] = {
  152155. 1, 4, 4, 7, 7, 8, 8, 8, 7, 9, 8,10, 9,11,10, 4,
  152156. 6, 6, 8, 8,10, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  152157. 6, 8, 8,10,10, 9, 9,10,10,11,11,11,12, 7, 8, 8,
  152158. 10,10,11,11,11,10,12,11,12,12,13,11, 7, 8, 8,10,
  152159. 10,11,11,10,10,11,11,12,12,13,13, 8,10,10,11,11,
  152160. 12,11,12,11,13,12,13,12,14,13, 8,10, 9,11,11,12,
  152161. 12,12,12,12,12,13,13,14,13, 8, 9, 9,11,10,12,11,
  152162. 13,12,13,13,14,13,14,13, 8, 9, 9,10,11,12,12,12,
  152163. 12,13,13,14,15,14,14, 9,10,10,12,11,13,12,13,13,
  152164. 14,13,14,14,14,14, 9,10,10,12,12,12,12,13,13,14,
  152165. 14,14,15,14,14,10,11,11,13,12,13,12,14,14,14,14,
  152166. 14,14,15,15,10,11,11,12,12,13,13,14,14,14,15,15,
  152167. 14,16,15,11,12,12,13,12,14,14,14,13,15,14,15,15,
  152168. 15,17,11,12,12,13,13,14,14,14,15,15,14,15,15,14,
  152169. 17,
  152170. };
  152171. static float _vq_quantthresh__44u8_p8_0[] = {
  152172. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  152173. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  152174. };
  152175. static long _vq_quantmap__44u8_p8_0[] = {
  152176. 13, 11, 9, 7, 5, 3, 1, 0,
  152177. 2, 4, 6, 8, 10, 12, 14,
  152178. };
  152179. static encode_aux_threshmatch _vq_auxt__44u8_p8_0 = {
  152180. _vq_quantthresh__44u8_p8_0,
  152181. _vq_quantmap__44u8_p8_0,
  152182. 15,
  152183. 15
  152184. };
  152185. static static_codebook _44u8_p8_0 = {
  152186. 2, 225,
  152187. _vq_lengthlist__44u8_p8_0,
  152188. 1, -520986624, 1620377600, 4, 0,
  152189. _vq_quantlist__44u8_p8_0,
  152190. NULL,
  152191. &_vq_auxt__44u8_p8_0,
  152192. NULL,
  152193. 0
  152194. };
  152195. static long _vq_quantlist__44u8_p8_1[] = {
  152196. 10,
  152197. 9,
  152198. 11,
  152199. 8,
  152200. 12,
  152201. 7,
  152202. 13,
  152203. 6,
  152204. 14,
  152205. 5,
  152206. 15,
  152207. 4,
  152208. 16,
  152209. 3,
  152210. 17,
  152211. 2,
  152212. 18,
  152213. 1,
  152214. 19,
  152215. 0,
  152216. 20,
  152217. };
  152218. static long _vq_lengthlist__44u8_p8_1[] = {
  152219. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  152220. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152221. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 5, 6, 6, 7, 7, 8,
  152222. 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  152223. 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152224. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  152225. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  152226. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10, 9,10, 8, 8,
  152227. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  152228. 10, 9,10, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,
  152229. 10,10,10,10,10,10,10,10, 8, 9, 8, 9, 9, 9, 9, 9,
  152230. 9, 9, 9, 9, 9, 9,10,10,10,10, 9,10,10, 9, 9, 9,
  152231. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152232. 10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,
  152233. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,
  152234. 10,10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  152235. 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,
  152236. 10, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  152237. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  152238. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  152239. 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  152240. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  152241. 10,10,10,10,10, 9, 9, 9,10, 9,10,10,10,10,10,10,
  152242. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,10,
  152243. 9,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  152244. 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,
  152245. 10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,10,
  152246. 10,10,10,10,10,10,10,10,10,
  152247. };
  152248. static float _vq_quantthresh__44u8_p8_1[] = {
  152249. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  152250. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  152251. 6.5, 7.5, 8.5, 9.5,
  152252. };
  152253. static long _vq_quantmap__44u8_p8_1[] = {
  152254. 19, 17, 15, 13, 11, 9, 7, 5,
  152255. 3, 1, 0, 2, 4, 6, 8, 10,
  152256. 12, 14, 16, 18, 20,
  152257. };
  152258. static encode_aux_threshmatch _vq_auxt__44u8_p8_1 = {
  152259. _vq_quantthresh__44u8_p8_1,
  152260. _vq_quantmap__44u8_p8_1,
  152261. 21,
  152262. 21
  152263. };
  152264. static static_codebook _44u8_p8_1 = {
  152265. 2, 441,
  152266. _vq_lengthlist__44u8_p8_1,
  152267. 1, -529268736, 1611661312, 5, 0,
  152268. _vq_quantlist__44u8_p8_1,
  152269. NULL,
  152270. &_vq_auxt__44u8_p8_1,
  152271. NULL,
  152272. 0
  152273. };
  152274. static long _vq_quantlist__44u8_p9_0[] = {
  152275. 4,
  152276. 3,
  152277. 5,
  152278. 2,
  152279. 6,
  152280. 1,
  152281. 7,
  152282. 0,
  152283. 8,
  152284. };
  152285. static long _vq_lengthlist__44u8_p9_0[] = {
  152286. 1, 3, 3, 9, 9, 9, 9, 9, 9, 4, 9, 9, 9, 9, 9, 9,
  152287. 9, 9, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152288. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152289. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  152290. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8,
  152291. 8,
  152292. };
  152293. static float _vq_quantthresh__44u8_p9_0[] = {
  152294. -3258.5, -2327.5, -1396.5, -465.5, 465.5, 1396.5, 2327.5, 3258.5,
  152295. };
  152296. static long _vq_quantmap__44u8_p9_0[] = {
  152297. 7, 5, 3, 1, 0, 2, 4, 6,
  152298. 8,
  152299. };
  152300. static encode_aux_threshmatch _vq_auxt__44u8_p9_0 = {
  152301. _vq_quantthresh__44u8_p9_0,
  152302. _vq_quantmap__44u8_p9_0,
  152303. 9,
  152304. 9
  152305. };
  152306. static static_codebook _44u8_p9_0 = {
  152307. 2, 81,
  152308. _vq_lengthlist__44u8_p9_0,
  152309. 1, -511895552, 1631393792, 4, 0,
  152310. _vq_quantlist__44u8_p9_0,
  152311. NULL,
  152312. &_vq_auxt__44u8_p9_0,
  152313. NULL,
  152314. 0
  152315. };
  152316. static long _vq_quantlist__44u8_p9_1[] = {
  152317. 9,
  152318. 8,
  152319. 10,
  152320. 7,
  152321. 11,
  152322. 6,
  152323. 12,
  152324. 5,
  152325. 13,
  152326. 4,
  152327. 14,
  152328. 3,
  152329. 15,
  152330. 2,
  152331. 16,
  152332. 1,
  152333. 17,
  152334. 0,
  152335. 18,
  152336. };
  152337. static long _vq_lengthlist__44u8_p9_1[] = {
  152338. 1, 4, 4, 7, 7, 8, 7, 8, 6, 9, 7,10, 8,11,10,11,
  152339. 11,11,11, 4, 7, 6, 9, 9,10, 9, 9, 9,10,10,11,10,
  152340. 11,10,11,11,13,11, 4, 7, 7, 9, 9, 9, 9, 9, 9,10,
  152341. 10,11,10,11,11,11,12,11,12, 7, 9, 8,11,11,11,11,
  152342. 10,10,11,11,12,12,12,12,12,12,14,13, 7, 8, 9,10,
  152343. 11,11,11,10,10,11,11,11,11,12,12,14,12,13,14, 8,
  152344. 9, 9,11,11,11,11,11,11,12,12,14,12,15,14,14,14,
  152345. 15,14, 8, 9, 9,11,11,11,11,12,11,12,12,13,13,13,
  152346. 13,13,13,14,14, 8, 9, 9,11,10,12,11,12,12,13,13,
  152347. 13,13,15,14,14,14,16,16, 8, 9, 9,10,11,11,12,12,
  152348. 12,13,13,13,14,14,14,15,16,15,15, 9,10,10,11,12,
  152349. 12,13,13,13,14,14,16,14,14,16,16,16,16,15, 9,10,
  152350. 10,11,11,12,13,13,14,15,14,16,14,15,16,16,16,16,
  152351. 15,10,11,11,12,13,13,14,15,15,15,15,15,16,15,16,
  152352. 15,16,15,15,10,11,11,13,13,14,13,13,15,14,15,15,
  152353. 16,15,15,15,16,15,16,10,12,12,14,14,14,14,14,16,
  152354. 16,15,15,15,16,16,16,16,16,16,11,12,12,14,14,14,
  152355. 14,15,15,16,15,16,15,16,15,16,16,16,16,12,12,13,
  152356. 14,14,15,16,16,16,16,16,16,15,16,16,16,16,16,16,
  152357. 12,13,13,14,14,14,14,15,16,15,16,16,16,16,16,16,
  152358. 16,16,16,12,13,14,14,14,16,15,16,15,16,16,16,16,
  152359. 16,16,16,16,16,16,12,14,13,14,15,15,15,16,15,16,
  152360. 16,15,16,16,16,16,16,16,16,
  152361. };
  152362. static float _vq_quantthresh__44u8_p9_1[] = {
  152363. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  152364. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  152365. 367.5, 416.5,
  152366. };
  152367. static long _vq_quantmap__44u8_p9_1[] = {
  152368. 17, 15, 13, 11, 9, 7, 5, 3,
  152369. 1, 0, 2, 4, 6, 8, 10, 12,
  152370. 14, 16, 18,
  152371. };
  152372. static encode_aux_threshmatch _vq_auxt__44u8_p9_1 = {
  152373. _vq_quantthresh__44u8_p9_1,
  152374. _vq_quantmap__44u8_p9_1,
  152375. 19,
  152376. 19
  152377. };
  152378. static static_codebook _44u8_p9_1 = {
  152379. 2, 361,
  152380. _vq_lengthlist__44u8_p9_1,
  152381. 1, -518287360, 1622704128, 5, 0,
  152382. _vq_quantlist__44u8_p9_1,
  152383. NULL,
  152384. &_vq_auxt__44u8_p9_1,
  152385. NULL,
  152386. 0
  152387. };
  152388. static long _vq_quantlist__44u8_p9_2[] = {
  152389. 24,
  152390. 23,
  152391. 25,
  152392. 22,
  152393. 26,
  152394. 21,
  152395. 27,
  152396. 20,
  152397. 28,
  152398. 19,
  152399. 29,
  152400. 18,
  152401. 30,
  152402. 17,
  152403. 31,
  152404. 16,
  152405. 32,
  152406. 15,
  152407. 33,
  152408. 14,
  152409. 34,
  152410. 13,
  152411. 35,
  152412. 12,
  152413. 36,
  152414. 11,
  152415. 37,
  152416. 10,
  152417. 38,
  152418. 9,
  152419. 39,
  152420. 8,
  152421. 40,
  152422. 7,
  152423. 41,
  152424. 6,
  152425. 42,
  152426. 5,
  152427. 43,
  152428. 4,
  152429. 44,
  152430. 3,
  152431. 45,
  152432. 2,
  152433. 46,
  152434. 1,
  152435. 47,
  152436. 0,
  152437. 48,
  152438. };
  152439. static long _vq_lengthlist__44u8_p9_2[] = {
  152440. 2, 3, 4, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6,
  152441. 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152442. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152443. 7,
  152444. };
  152445. static float _vq_quantthresh__44u8_p9_2[] = {
  152446. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  152447. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  152448. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152449. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152450. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  152451. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  152452. };
  152453. static long _vq_quantmap__44u8_p9_2[] = {
  152454. 47, 45, 43, 41, 39, 37, 35, 33,
  152455. 31, 29, 27, 25, 23, 21, 19, 17,
  152456. 15, 13, 11, 9, 7, 5, 3, 1,
  152457. 0, 2, 4, 6, 8, 10, 12, 14,
  152458. 16, 18, 20, 22, 24, 26, 28, 30,
  152459. 32, 34, 36, 38, 40, 42, 44, 46,
  152460. 48,
  152461. };
  152462. static encode_aux_threshmatch _vq_auxt__44u8_p9_2 = {
  152463. _vq_quantthresh__44u8_p9_2,
  152464. _vq_quantmap__44u8_p9_2,
  152465. 49,
  152466. 49
  152467. };
  152468. static static_codebook _44u8_p9_2 = {
  152469. 1, 49,
  152470. _vq_lengthlist__44u8_p9_2,
  152471. 1, -526909440, 1611661312, 6, 0,
  152472. _vq_quantlist__44u8_p9_2,
  152473. NULL,
  152474. &_vq_auxt__44u8_p9_2,
  152475. NULL,
  152476. 0
  152477. };
  152478. static long _huff_lengthlist__44u9__long[] = {
  152479. 3, 9,13,13,14,15,14,14,15,15, 5, 5, 9,10,12,12,
  152480. 13,14,16,15,10, 6, 6, 6, 8,11,12,13,16,15,11, 7,
  152481. 5, 3, 5, 8,10,12,15,15,10,10, 7, 4, 3, 5, 8,10,
  152482. 12,12,12,12, 9, 7, 5, 4, 6, 8,10,13,13,12,11, 9,
  152483. 7, 5, 5, 6, 9,12,14,12,12,10, 8, 6, 6, 6, 7,11,
  152484. 13,12,14,13,10, 8, 7, 7, 7,10,11,11,12,13,12,11,
  152485. 10, 8, 8, 9,
  152486. };
  152487. static static_codebook _huff_book__44u9__long = {
  152488. 2, 100,
  152489. _huff_lengthlist__44u9__long,
  152490. 0, 0, 0, 0, 0,
  152491. NULL,
  152492. NULL,
  152493. NULL,
  152494. NULL,
  152495. 0
  152496. };
  152497. static long _huff_lengthlist__44u9__short[] = {
  152498. 9,16,18,18,17,17,17,17,17,17, 5, 8,11,12,11,12,
  152499. 17,17,16,16, 6, 6, 8, 8, 9,10,14,15,16,16, 6, 7,
  152500. 7, 4, 6, 9,13,16,16,16, 6, 6, 7, 4, 5, 8,11,15,
  152501. 17,16, 7, 6, 7, 6, 6, 8, 9,10,14,16,11, 8, 8, 7,
  152502. 6, 6, 3, 4,10,15,14,12,12,10, 5, 6, 3, 3, 8,13,
  152503. 15,17,15,11, 6, 8, 6, 6, 9,14,17,15,15,12, 8,10,
  152504. 9, 9,12,15,
  152505. };
  152506. static static_codebook _huff_book__44u9__short = {
  152507. 2, 100,
  152508. _huff_lengthlist__44u9__short,
  152509. 0, 0, 0, 0, 0,
  152510. NULL,
  152511. NULL,
  152512. NULL,
  152513. NULL,
  152514. 0
  152515. };
  152516. static long _vq_quantlist__44u9_p1_0[] = {
  152517. 1,
  152518. 0,
  152519. 2,
  152520. };
  152521. static long _vq_lengthlist__44u9_p1_0[] = {
  152522. 1, 5, 5, 5, 7, 7, 5, 7, 7, 5, 7, 7, 7, 9, 9, 7,
  152523. 9, 9, 5, 7, 7, 7, 9, 9, 7, 9, 9, 5, 7, 7, 7, 9,
  152524. 9, 7, 9, 9, 8, 9, 9, 9,10,11, 9,11,11, 7, 9, 9,
  152525. 9,11,10, 9,11,11, 5, 7, 7, 7, 9, 9, 8, 9,10, 7,
  152526. 9, 9, 9,11,11, 9,10,11, 7, 9,10, 9,11,11, 9,11,
  152527. 10,
  152528. };
  152529. static float _vq_quantthresh__44u9_p1_0[] = {
  152530. -0.5, 0.5,
  152531. };
  152532. static long _vq_quantmap__44u9_p1_0[] = {
  152533. 1, 0, 2,
  152534. };
  152535. static encode_aux_threshmatch _vq_auxt__44u9_p1_0 = {
  152536. _vq_quantthresh__44u9_p1_0,
  152537. _vq_quantmap__44u9_p1_0,
  152538. 3,
  152539. 3
  152540. };
  152541. static static_codebook _44u9_p1_0 = {
  152542. 4, 81,
  152543. _vq_lengthlist__44u9_p1_0,
  152544. 1, -535822336, 1611661312, 2, 0,
  152545. _vq_quantlist__44u9_p1_0,
  152546. NULL,
  152547. &_vq_auxt__44u9_p1_0,
  152548. NULL,
  152549. 0
  152550. };
  152551. static long _vq_quantlist__44u9_p2_0[] = {
  152552. 2,
  152553. 1,
  152554. 3,
  152555. 0,
  152556. 4,
  152557. };
  152558. static long _vq_lengthlist__44u9_p2_0[] = {
  152559. 3, 5, 5, 8, 8, 5, 7, 7, 9, 9, 6, 7, 7, 9, 9, 8,
  152560. 9, 9,11,10, 8, 9, 9,11,11, 6, 7, 7, 9, 9, 7, 8,
  152561. 8,10,10, 7, 8, 8, 9,10, 9,10,10,11,11, 9, 9,10,
  152562. 11,11, 6, 7, 7, 9, 9, 7, 8, 8,10, 9, 7, 8, 8,10,
  152563. 10, 9,10, 9,11,11, 9,10,10,11,11, 8, 9, 9,11,11,
  152564. 9,10,10,12,11, 9,10,10,11,12,11,11,11,13,13,11,
  152565. 11,11,12,13, 8, 9, 9,11,11, 9,10,10,11,11, 9,10,
  152566. 10,12,11,11,12,11,13,12,11,11,12,13,13, 6, 7, 7,
  152567. 9, 9, 7, 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,12,
  152568. 11, 9,10,10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,11,
  152569. 8, 9, 9,10,10,10,11,11,12,12,10,10,11,12,12, 7,
  152570. 8, 8,10,10, 8, 9, 8,10,10, 8, 9, 9,10,10,10,11,
  152571. 10,12,11,10,10,11,12,12, 9,10,10,11,12,10,11,11,
  152572. 12,12,10,11,10,12,12,12,12,12,13,13,11,12,12,13,
  152573. 13, 9,10,10,11,11, 9,10,10,12,12,10,11,11,12,13,
  152574. 11,12,11,13,12,12,12,12,13,14, 6, 7, 7, 9, 9, 7,
  152575. 8, 8,10,10, 7, 8, 8,10,10, 9,10,10,11,11, 9,10,
  152576. 10,11,12, 7, 8, 8,10,10, 8, 9, 9,11,10, 8, 8, 9,
  152577. 10,10,10,11,10,12,12,10,10,11,11,12, 7, 8, 8,10,
  152578. 10, 8, 9, 9,10,10, 8, 9, 9,10,10,10,11,10,12,12,
  152579. 10,11,10,12,12, 9,10,10,12,11,10,11,11,12,12, 9,
  152580. 10,10,12,12,12,12,12,13,13,11,11,12,12,14, 9,10,
  152581. 10,11,12,10,11,11,12,12,10,11,11,12,12,11,12,12,
  152582. 14,14,12,12,12,13,13, 8, 9, 9,11,11, 9,10,10,12,
  152583. 11, 9,10,10,12,12,11,12,11,13,13,11,11,12,13,13,
  152584. 9,10,10,12,12,10,11,11,12,12,10,11,11,12,12,12,
  152585. 12,12,14,14,12,12,12,13,13, 9,10,10,12,11,10,11,
  152586. 10,12,12,10,11,11,12,12,11,12,12,14,13,12,12,12,
  152587. 13,14,11,12,11,13,13,11,12,12,13,13,12,12,12,14,
  152588. 14,13,13,13,13,15,13,13,14,15,15,11,11,11,13,13,
  152589. 11,12,11,13,13,11,12,12,13,13,12,13,12,15,13,13,
  152590. 13,14,14,15, 8, 9, 9,11,11, 9,10,10,11,12, 9,10,
  152591. 10,11,12,11,12,11,13,13,11,12,12,13,13, 9,10,10,
  152592. 11,12,10,11,10,12,12,10,10,11,12,13,12,12,12,14,
  152593. 13,11,12,12,13,14, 9,10,10,12,12,10,11,11,12,12,
  152594. 10,11,11,12,12,12,12,12,14,13,12,12,12,14,13,11,
  152595. 11,11,13,13,11,12,12,14,13,11,11,12,13,13,13,13,
  152596. 13,15,14,12,12,13,13,15,11,12,12,13,13,12,12,12,
  152597. 13,14,11,12,12,13,13,13,13,14,14,15,13,13,13,14,
  152598. 14,
  152599. };
  152600. static float _vq_quantthresh__44u9_p2_0[] = {
  152601. -1.5, -0.5, 0.5, 1.5,
  152602. };
  152603. static long _vq_quantmap__44u9_p2_0[] = {
  152604. 3, 1, 0, 2, 4,
  152605. };
  152606. static encode_aux_threshmatch _vq_auxt__44u9_p2_0 = {
  152607. _vq_quantthresh__44u9_p2_0,
  152608. _vq_quantmap__44u9_p2_0,
  152609. 5,
  152610. 5
  152611. };
  152612. static static_codebook _44u9_p2_0 = {
  152613. 4, 625,
  152614. _vq_lengthlist__44u9_p2_0,
  152615. 1, -533725184, 1611661312, 3, 0,
  152616. _vq_quantlist__44u9_p2_0,
  152617. NULL,
  152618. &_vq_auxt__44u9_p2_0,
  152619. NULL,
  152620. 0
  152621. };
  152622. static long _vq_quantlist__44u9_p3_0[] = {
  152623. 4,
  152624. 3,
  152625. 5,
  152626. 2,
  152627. 6,
  152628. 1,
  152629. 7,
  152630. 0,
  152631. 8,
  152632. };
  152633. static long _vq_lengthlist__44u9_p3_0[] = {
  152634. 3, 4, 4, 5, 5, 7, 7, 8, 8, 4, 5, 5, 6, 6, 7, 7,
  152635. 9, 9, 4, 4, 5, 6, 6, 7, 7, 9, 9, 5, 6, 6, 7, 7,
  152636. 8, 8, 9, 9, 5, 6, 6, 7, 7, 8, 8, 9, 9, 7, 7, 7,
  152637. 8, 8, 9, 9,10,10, 7, 7, 7, 8, 8, 9, 9,10,10, 8,
  152638. 9, 9,10, 9,10,10,11,11, 8, 9, 9, 9,10,10,10,11,
  152639. 11,
  152640. };
  152641. static float _vq_quantthresh__44u9_p3_0[] = {
  152642. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  152643. };
  152644. static long _vq_quantmap__44u9_p3_0[] = {
  152645. 7, 5, 3, 1, 0, 2, 4, 6,
  152646. 8,
  152647. };
  152648. static encode_aux_threshmatch _vq_auxt__44u9_p3_0 = {
  152649. _vq_quantthresh__44u9_p3_0,
  152650. _vq_quantmap__44u9_p3_0,
  152651. 9,
  152652. 9
  152653. };
  152654. static static_codebook _44u9_p3_0 = {
  152655. 2, 81,
  152656. _vq_lengthlist__44u9_p3_0,
  152657. 1, -531628032, 1611661312, 4, 0,
  152658. _vq_quantlist__44u9_p3_0,
  152659. NULL,
  152660. &_vq_auxt__44u9_p3_0,
  152661. NULL,
  152662. 0
  152663. };
  152664. static long _vq_quantlist__44u9_p4_0[] = {
  152665. 8,
  152666. 7,
  152667. 9,
  152668. 6,
  152669. 10,
  152670. 5,
  152671. 11,
  152672. 4,
  152673. 12,
  152674. 3,
  152675. 13,
  152676. 2,
  152677. 14,
  152678. 1,
  152679. 15,
  152680. 0,
  152681. 16,
  152682. };
  152683. static long _vq_lengthlist__44u9_p4_0[] = {
  152684. 4, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,11,
  152685. 11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,
  152686. 11,11, 5, 5, 5, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,
  152687. 10,11,11, 6, 6, 6, 7, 6, 7, 7, 8, 8, 9, 9,10,10,
  152688. 11,11,12,11, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,10,
  152689. 10,11,11,11,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9,
  152690. 10,10,11,11,12,12, 7, 7, 7, 7, 7, 8, 8, 9, 9, 9,
  152691. 9,10,10,11,11,12,12, 8, 8, 8, 8, 8, 9, 8,10, 9,
  152692. 10,10,11,10,12,11,13,12, 8, 8, 8, 8, 8, 9, 9, 9,
  152693. 10,10,10,10,11,11,12,12,12, 8, 8, 8, 9, 9, 9, 9,
  152694. 10,10,11,10,12,11,12,12,13,12, 8, 8, 8, 9, 9, 9,
  152695. 9,10,10,10,11,11,11,12,12,12,13, 9, 9, 9,10,10,
  152696. 10,10,11,10,11,11,12,11,13,12,13,13, 9, 9,10,10,
  152697. 10,10,10,10,11,11,11,11,12,12,13,13,13,10,11,10,
  152698. 11,11,11,11,12,11,12,12,13,12,13,13,14,13,10,10,
  152699. 10,11,11,11,11,11,12,12,12,12,13,13,13,13,14,11,
  152700. 11,11,12,11,12,12,12,12,13,13,13,13,14,13,14,14,
  152701. 11,11,11,11,12,12,12,12,12,12,13,13,13,13,14,14,
  152702. 14,
  152703. };
  152704. static float _vq_quantthresh__44u9_p4_0[] = {
  152705. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  152706. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  152707. };
  152708. static long _vq_quantmap__44u9_p4_0[] = {
  152709. 15, 13, 11, 9, 7, 5, 3, 1,
  152710. 0, 2, 4, 6, 8, 10, 12, 14,
  152711. 16,
  152712. };
  152713. static encode_aux_threshmatch _vq_auxt__44u9_p4_0 = {
  152714. _vq_quantthresh__44u9_p4_0,
  152715. _vq_quantmap__44u9_p4_0,
  152716. 17,
  152717. 17
  152718. };
  152719. static static_codebook _44u9_p4_0 = {
  152720. 2, 289,
  152721. _vq_lengthlist__44u9_p4_0,
  152722. 1, -529530880, 1611661312, 5, 0,
  152723. _vq_quantlist__44u9_p4_0,
  152724. NULL,
  152725. &_vq_auxt__44u9_p4_0,
  152726. NULL,
  152727. 0
  152728. };
  152729. static long _vq_quantlist__44u9_p5_0[] = {
  152730. 1,
  152731. 0,
  152732. 2,
  152733. };
  152734. static long _vq_lengthlist__44u9_p5_0[] = {
  152735. 1, 4, 4, 5, 7, 7, 5, 7, 7, 5, 8, 8, 8, 9, 9, 7,
  152736. 9, 9, 5, 8, 8, 7, 9, 9, 8, 9, 9, 5, 8, 8, 8,10,
  152737. 10, 8,10,10, 7,10,10, 9,10,12, 9,11,11, 7,10,10,
  152738. 9,11,10, 9,11,12, 5, 8, 8, 8,10,10, 8,10,10, 7,
  152739. 10,10, 9,12,11, 9,10,11, 7,10,10, 9,11,11,10,12,
  152740. 10,
  152741. };
  152742. static float _vq_quantthresh__44u9_p5_0[] = {
  152743. -5.5, 5.5,
  152744. };
  152745. static long _vq_quantmap__44u9_p5_0[] = {
  152746. 1, 0, 2,
  152747. };
  152748. static encode_aux_threshmatch _vq_auxt__44u9_p5_0 = {
  152749. _vq_quantthresh__44u9_p5_0,
  152750. _vq_quantmap__44u9_p5_0,
  152751. 3,
  152752. 3
  152753. };
  152754. static static_codebook _44u9_p5_0 = {
  152755. 4, 81,
  152756. _vq_lengthlist__44u9_p5_0,
  152757. 1, -529137664, 1618345984, 2, 0,
  152758. _vq_quantlist__44u9_p5_0,
  152759. NULL,
  152760. &_vq_auxt__44u9_p5_0,
  152761. NULL,
  152762. 0
  152763. };
  152764. static long _vq_quantlist__44u9_p5_1[] = {
  152765. 5,
  152766. 4,
  152767. 6,
  152768. 3,
  152769. 7,
  152770. 2,
  152771. 8,
  152772. 1,
  152773. 9,
  152774. 0,
  152775. 10,
  152776. };
  152777. static long _vq_lengthlist__44u9_p5_1[] = {
  152778. 5, 5, 5, 6, 6, 7, 7, 7, 7, 7, 7, 5, 6, 6, 6, 6,
  152779. 7, 7, 7, 7, 8, 7, 5, 6, 6, 6, 6, 7, 7, 7, 7, 7,
  152780. 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 8, 8, 6, 6, 6, 7,
  152781. 7, 7, 7, 7, 7, 8, 8, 7, 7, 7, 7, 7, 8, 7, 8, 8,
  152782. 8, 8, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 7, 7, 7,
  152783. 8, 7, 8, 8, 8, 8, 8, 8, 7, 7, 7, 7, 8, 8, 8, 8,
  152784. 8, 8, 8, 7, 8, 7, 8, 8, 8, 8, 8, 8, 8, 8, 7, 8,
  152785. 8, 8, 8, 8, 8, 8, 8, 8, 8,
  152786. };
  152787. static float _vq_quantthresh__44u9_p5_1[] = {
  152788. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152789. 3.5, 4.5,
  152790. };
  152791. static long _vq_quantmap__44u9_p5_1[] = {
  152792. 9, 7, 5, 3, 1, 0, 2, 4,
  152793. 6, 8, 10,
  152794. };
  152795. static encode_aux_threshmatch _vq_auxt__44u9_p5_1 = {
  152796. _vq_quantthresh__44u9_p5_1,
  152797. _vq_quantmap__44u9_p5_1,
  152798. 11,
  152799. 11
  152800. };
  152801. static static_codebook _44u9_p5_1 = {
  152802. 2, 121,
  152803. _vq_lengthlist__44u9_p5_1,
  152804. 1, -531365888, 1611661312, 4, 0,
  152805. _vq_quantlist__44u9_p5_1,
  152806. NULL,
  152807. &_vq_auxt__44u9_p5_1,
  152808. NULL,
  152809. 0
  152810. };
  152811. static long _vq_quantlist__44u9_p6_0[] = {
  152812. 6,
  152813. 5,
  152814. 7,
  152815. 4,
  152816. 8,
  152817. 3,
  152818. 9,
  152819. 2,
  152820. 10,
  152821. 1,
  152822. 11,
  152823. 0,
  152824. 12,
  152825. };
  152826. static long _vq_lengthlist__44u9_p6_0[] = {
  152827. 2, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9,10,10, 4, 6, 5,
  152828. 7, 7, 8, 8, 8, 8, 9, 9,10,10, 4, 5, 6, 7, 7, 8,
  152829. 8, 8, 8, 9, 9,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  152830. 10,10,10,10, 6, 7, 7, 8, 8, 8, 8, 9, 9,10,10,10,
  152831. 10, 7, 8, 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 7, 8,
  152832. 8, 8, 8, 9, 9, 9, 9,10,10,11,11, 8, 8, 8, 9, 9,
  152833. 9, 9, 9,10,10,10,11,11, 8, 8, 8, 9, 9, 9, 9,10,
  152834. 9,10,10,11,11, 9, 9, 9,10,10,10,10,10,11,11,11,
  152835. 11,12, 9, 9, 9,10,10,10,10,10,10,11,10,12,11,10,
  152836. 10,10,10,10,11,11,11,11,11,12,12,12,10,10,10,10,
  152837. 10,11,11,11,11,12,11,12,12,
  152838. };
  152839. static float _vq_quantthresh__44u9_p6_0[] = {
  152840. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  152841. 12.5, 17.5, 22.5, 27.5,
  152842. };
  152843. static long _vq_quantmap__44u9_p6_0[] = {
  152844. 11, 9, 7, 5, 3, 1, 0, 2,
  152845. 4, 6, 8, 10, 12,
  152846. };
  152847. static encode_aux_threshmatch _vq_auxt__44u9_p6_0 = {
  152848. _vq_quantthresh__44u9_p6_0,
  152849. _vq_quantmap__44u9_p6_0,
  152850. 13,
  152851. 13
  152852. };
  152853. static static_codebook _44u9_p6_0 = {
  152854. 2, 169,
  152855. _vq_lengthlist__44u9_p6_0,
  152856. 1, -526516224, 1616117760, 4, 0,
  152857. _vq_quantlist__44u9_p6_0,
  152858. NULL,
  152859. &_vq_auxt__44u9_p6_0,
  152860. NULL,
  152861. 0
  152862. };
  152863. static long _vq_quantlist__44u9_p6_1[] = {
  152864. 2,
  152865. 1,
  152866. 3,
  152867. 0,
  152868. 4,
  152869. };
  152870. static long _vq_lengthlist__44u9_p6_1[] = {
  152871. 4, 4, 4, 5, 5, 4, 5, 4, 5, 5, 4, 4, 5, 5, 5, 5,
  152872. 5, 5, 5, 5, 5, 5, 5, 5, 5,
  152873. };
  152874. static float _vq_quantthresh__44u9_p6_1[] = {
  152875. -1.5, -0.5, 0.5, 1.5,
  152876. };
  152877. static long _vq_quantmap__44u9_p6_1[] = {
  152878. 3, 1, 0, 2, 4,
  152879. };
  152880. static encode_aux_threshmatch _vq_auxt__44u9_p6_1 = {
  152881. _vq_quantthresh__44u9_p6_1,
  152882. _vq_quantmap__44u9_p6_1,
  152883. 5,
  152884. 5
  152885. };
  152886. static static_codebook _44u9_p6_1 = {
  152887. 2, 25,
  152888. _vq_lengthlist__44u9_p6_1,
  152889. 1, -533725184, 1611661312, 3, 0,
  152890. _vq_quantlist__44u9_p6_1,
  152891. NULL,
  152892. &_vq_auxt__44u9_p6_1,
  152893. NULL,
  152894. 0
  152895. };
  152896. static long _vq_quantlist__44u9_p7_0[] = {
  152897. 6,
  152898. 5,
  152899. 7,
  152900. 4,
  152901. 8,
  152902. 3,
  152903. 9,
  152904. 2,
  152905. 10,
  152906. 1,
  152907. 11,
  152908. 0,
  152909. 12,
  152910. };
  152911. static long _vq_lengthlist__44u9_p7_0[] = {
  152912. 1, 4, 5, 6, 6, 7, 7, 8, 9,10,10,11,11, 5, 6, 6,
  152913. 7, 7, 8, 8, 9, 9,10,10,11,11, 5, 6, 6, 7, 7, 8,
  152914. 8, 9, 9,10,10,11,11, 6, 7, 7, 8, 8, 9, 9,10,10,
  152915. 11,11,12,12, 6, 7, 7, 8, 8, 9, 9,10,10,11,11,12,
  152916. 12, 8, 8, 8, 9, 9,10,10,11,11,12,12,13,13, 8, 8,
  152917. 8, 9, 9,10,10,11,11,12,12,13,13, 9, 9, 9,10,10,
  152918. 11,11,12,12,13,13,13,13, 9, 9, 9,10,10,11,11,12,
  152919. 12,13,13,14,14,10,10,10,11,11,12,12,13,13,14,13,
  152920. 15,14,10,10,10,11,11,12,12,13,13,14,14,14,14,11,
  152921. 11,12,12,12,13,13,14,14,14,14,15,15,11,11,12,12,
  152922. 12,13,13,14,14,14,15,15,15,
  152923. };
  152924. static float _vq_quantthresh__44u9_p7_0[] = {
  152925. -60.5, -49.5, -38.5, -27.5, -16.5, -5.5, 5.5, 16.5,
  152926. 27.5, 38.5, 49.5, 60.5,
  152927. };
  152928. static long _vq_quantmap__44u9_p7_0[] = {
  152929. 11, 9, 7, 5, 3, 1, 0, 2,
  152930. 4, 6, 8, 10, 12,
  152931. };
  152932. static encode_aux_threshmatch _vq_auxt__44u9_p7_0 = {
  152933. _vq_quantthresh__44u9_p7_0,
  152934. _vq_quantmap__44u9_p7_0,
  152935. 13,
  152936. 13
  152937. };
  152938. static static_codebook _44u9_p7_0 = {
  152939. 2, 169,
  152940. _vq_lengthlist__44u9_p7_0,
  152941. 1, -523206656, 1618345984, 4, 0,
  152942. _vq_quantlist__44u9_p7_0,
  152943. NULL,
  152944. &_vq_auxt__44u9_p7_0,
  152945. NULL,
  152946. 0
  152947. };
  152948. static long _vq_quantlist__44u9_p7_1[] = {
  152949. 5,
  152950. 4,
  152951. 6,
  152952. 3,
  152953. 7,
  152954. 2,
  152955. 8,
  152956. 1,
  152957. 9,
  152958. 0,
  152959. 10,
  152960. };
  152961. static long _vq_lengthlist__44u9_p7_1[] = {
  152962. 5, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7,
  152963. 7, 7, 7, 7, 7, 7, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7,
  152964. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 6, 7, 7, 7,
  152965. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152966. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152967. 7, 7, 7, 7, 8, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  152968. 7, 8, 8, 7, 7, 7, 7, 7, 7, 7, 8, 7, 8, 8, 7, 7,
  152969. 7, 7, 7, 7, 7, 8, 8, 8, 8,
  152970. };
  152971. static float _vq_quantthresh__44u9_p7_1[] = {
  152972. -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5,
  152973. 3.5, 4.5,
  152974. };
  152975. static long _vq_quantmap__44u9_p7_1[] = {
  152976. 9, 7, 5, 3, 1, 0, 2, 4,
  152977. 6, 8, 10,
  152978. };
  152979. static encode_aux_threshmatch _vq_auxt__44u9_p7_1 = {
  152980. _vq_quantthresh__44u9_p7_1,
  152981. _vq_quantmap__44u9_p7_1,
  152982. 11,
  152983. 11
  152984. };
  152985. static static_codebook _44u9_p7_1 = {
  152986. 2, 121,
  152987. _vq_lengthlist__44u9_p7_1,
  152988. 1, -531365888, 1611661312, 4, 0,
  152989. _vq_quantlist__44u9_p7_1,
  152990. NULL,
  152991. &_vq_auxt__44u9_p7_1,
  152992. NULL,
  152993. 0
  152994. };
  152995. static long _vq_quantlist__44u9_p8_0[] = {
  152996. 7,
  152997. 6,
  152998. 8,
  152999. 5,
  153000. 9,
  153001. 4,
  153002. 10,
  153003. 3,
  153004. 11,
  153005. 2,
  153006. 12,
  153007. 1,
  153008. 13,
  153009. 0,
  153010. 14,
  153011. };
  153012. static long _vq_lengthlist__44u9_p8_0[] = {
  153013. 1, 4, 4, 7, 7, 8, 8, 8, 8, 9, 9,10, 9,11,10, 4,
  153014. 6, 6, 8, 8, 9, 9, 9, 9,10,10,11,10,12,10, 4, 6,
  153015. 6, 8, 8, 9,10, 9, 9,10,10,11,11,12,12, 7, 8, 8,
  153016. 10,10,11,11,10,10,11,11,12,12,13,12, 7, 8, 8,10,
  153017. 10,11,11,10,10,11,11,12,12,12,13, 8,10, 9,11,11,
  153018. 12,12,11,11,12,12,13,13,14,13, 8, 9, 9,11,11,12,
  153019. 12,11,12,12,12,13,13,14,13, 8, 9, 9,10,10,12,11,
  153020. 13,12,13,13,14,13,15,14, 8, 9, 9,10,10,11,12,12,
  153021. 12,13,13,13,14,14,14, 9,10,10,12,11,13,12,13,13,
  153022. 14,13,14,14,14,15, 9,10,10,11,12,12,12,13,13,14,
  153023. 14,14,15,15,15,10,11,11,12,12,13,13,14,14,14,14,
  153024. 15,14,16,15,10,11,11,12,12,13,13,13,14,14,14,14,
  153025. 14,15,16,11,12,12,13,13,14,13,14,14,15,14,15,16,
  153026. 16,16,11,12,12,13,13,14,13,14,14,15,15,15,16,15,
  153027. 15,
  153028. };
  153029. static float _vq_quantthresh__44u9_p8_0[] = {
  153030. -136.5, -115.5, -94.5, -73.5, -52.5, -31.5, -10.5, 10.5,
  153031. 31.5, 52.5, 73.5, 94.5, 115.5, 136.5,
  153032. };
  153033. static long _vq_quantmap__44u9_p8_0[] = {
  153034. 13, 11, 9, 7, 5, 3, 1, 0,
  153035. 2, 4, 6, 8, 10, 12, 14,
  153036. };
  153037. static encode_aux_threshmatch _vq_auxt__44u9_p8_0 = {
  153038. _vq_quantthresh__44u9_p8_0,
  153039. _vq_quantmap__44u9_p8_0,
  153040. 15,
  153041. 15
  153042. };
  153043. static static_codebook _44u9_p8_0 = {
  153044. 2, 225,
  153045. _vq_lengthlist__44u9_p8_0,
  153046. 1, -520986624, 1620377600, 4, 0,
  153047. _vq_quantlist__44u9_p8_0,
  153048. NULL,
  153049. &_vq_auxt__44u9_p8_0,
  153050. NULL,
  153051. 0
  153052. };
  153053. static long _vq_quantlist__44u9_p8_1[] = {
  153054. 10,
  153055. 9,
  153056. 11,
  153057. 8,
  153058. 12,
  153059. 7,
  153060. 13,
  153061. 6,
  153062. 14,
  153063. 5,
  153064. 15,
  153065. 4,
  153066. 16,
  153067. 3,
  153068. 17,
  153069. 2,
  153070. 18,
  153071. 1,
  153072. 19,
  153073. 0,
  153074. 20,
  153075. };
  153076. static long _vq_lengthlist__44u9_p8_1[] = {
  153077. 4, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9,
  153078. 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8, 8, 8, 8, 9, 9,
  153079. 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 6, 6, 6, 7, 7, 8,
  153080. 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 7,
  153081. 7, 7, 8, 8, 8, 8, 9, 8, 9, 9, 9, 9, 9, 9, 9, 9,
  153082. 9, 9, 9, 9, 7, 7, 7, 8, 8, 8, 8, 9, 9, 9, 9, 9,
  153083. 9, 9, 9, 9, 9, 9, 9, 9, 9, 8, 8, 8, 8, 8, 9, 9,
  153084. 9, 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10, 8, 8,
  153085. 8, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  153086. 9,10,10, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  153087. 10, 9,10, 9,10,10,10,10, 8, 8, 8, 9, 9, 9, 9, 9,
  153088. 9, 9, 9, 9, 9,10,10, 9,10,10,10,10,10, 9, 9, 9,
  153089. 9, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  153090. 10,10, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9,10,10,10,
  153091. 10,10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9, 9,
  153092. 9, 9,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9,
  153093. 9, 9, 9, 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  153094. 10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10,10,10,
  153095. 10,10,10,10,10,10, 9, 9, 9, 9, 9, 9, 9, 9,10,10,
  153096. 10,10,10,10,10,10,10,10,10,10,10, 9, 9, 9, 9, 9,
  153097. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153098. 9, 9, 9, 9,10, 9, 9,10,10,10,10,10,10,10,10,10,
  153099. 10,10,10,10,10, 9, 9, 9,10, 9,10, 9,10,10,10,10,
  153100. 10,10,10,10,10,10,10,10,10,10, 9, 9, 9,10, 9,10,
  153101. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10, 9,
  153102. 9, 9, 9, 9,10,10,10,10,10,10,10,10,10,10,10,10,
  153103. 10,10,10,10, 9, 9, 9,10,10,10,10,10,10,10,10,10,
  153104. 10,10,10,10,10,10,10,10,10,
  153105. };
  153106. static float _vq_quantthresh__44u9_p8_1[] = {
  153107. -9.5, -8.5, -7.5, -6.5, -5.5, -4.5, -3.5, -2.5,
  153108. -1.5, -0.5, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5,
  153109. 6.5, 7.5, 8.5, 9.5,
  153110. };
  153111. static long _vq_quantmap__44u9_p8_1[] = {
  153112. 19, 17, 15, 13, 11, 9, 7, 5,
  153113. 3, 1, 0, 2, 4, 6, 8, 10,
  153114. 12, 14, 16, 18, 20,
  153115. };
  153116. static encode_aux_threshmatch _vq_auxt__44u9_p8_1 = {
  153117. _vq_quantthresh__44u9_p8_1,
  153118. _vq_quantmap__44u9_p8_1,
  153119. 21,
  153120. 21
  153121. };
  153122. static static_codebook _44u9_p8_1 = {
  153123. 2, 441,
  153124. _vq_lengthlist__44u9_p8_1,
  153125. 1, -529268736, 1611661312, 5, 0,
  153126. _vq_quantlist__44u9_p8_1,
  153127. NULL,
  153128. &_vq_auxt__44u9_p8_1,
  153129. NULL,
  153130. 0
  153131. };
  153132. static long _vq_quantlist__44u9_p9_0[] = {
  153133. 7,
  153134. 6,
  153135. 8,
  153136. 5,
  153137. 9,
  153138. 4,
  153139. 10,
  153140. 3,
  153141. 11,
  153142. 2,
  153143. 12,
  153144. 1,
  153145. 13,
  153146. 0,
  153147. 14,
  153148. };
  153149. static long _vq_lengthlist__44u9_p9_0[] = {
  153150. 1, 3, 3,11,11,11,11,11,11,11,11,11,11,11,11, 4,
  153151. 10,11,11,11,11,11,11,11,11,11,11,11,11,11, 4,10,
  153152. 10,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153153. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153154. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153155. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153156. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153157. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153158. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153159. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153160. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153161. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153162. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153163. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153164. 10,
  153165. };
  153166. static float _vq_quantthresh__44u9_p9_0[] = {
  153167. -6051.5, -5120.5, -4189.5, -3258.5, -2327.5, -1396.5, -465.5, 465.5,
  153168. 1396.5, 2327.5, 3258.5, 4189.5, 5120.5, 6051.5,
  153169. };
  153170. static long _vq_quantmap__44u9_p9_0[] = {
  153171. 13, 11, 9, 7, 5, 3, 1, 0,
  153172. 2, 4, 6, 8, 10, 12, 14,
  153173. };
  153174. static encode_aux_threshmatch _vq_auxt__44u9_p9_0 = {
  153175. _vq_quantthresh__44u9_p9_0,
  153176. _vq_quantmap__44u9_p9_0,
  153177. 15,
  153178. 15
  153179. };
  153180. static static_codebook _44u9_p9_0 = {
  153181. 2, 225,
  153182. _vq_lengthlist__44u9_p9_0,
  153183. 1, -510036736, 1631393792, 4, 0,
  153184. _vq_quantlist__44u9_p9_0,
  153185. NULL,
  153186. &_vq_auxt__44u9_p9_0,
  153187. NULL,
  153188. 0
  153189. };
  153190. static long _vq_quantlist__44u9_p9_1[] = {
  153191. 9,
  153192. 8,
  153193. 10,
  153194. 7,
  153195. 11,
  153196. 6,
  153197. 12,
  153198. 5,
  153199. 13,
  153200. 4,
  153201. 14,
  153202. 3,
  153203. 15,
  153204. 2,
  153205. 16,
  153206. 1,
  153207. 17,
  153208. 0,
  153209. 18,
  153210. };
  153211. static long _vq_lengthlist__44u9_p9_1[] = {
  153212. 1, 4, 4, 7, 7, 8, 7, 8, 7, 9, 8,10, 9,10,10,11,
  153213. 11,12,12, 4, 7, 6, 9, 9,10, 9, 9, 8,10,10,11,10,
  153214. 12,10,13,12,13,12, 4, 6, 6, 9, 9, 9, 9, 9, 9,10,
  153215. 10,11,11,11,12,12,12,12,12, 7, 9, 8,11,10,10,10,
  153216. 11,10,11,11,12,12,13,12,13,13,13,13, 7, 8, 9,10,
  153217. 10,11,11,10,10,11,11,11,12,13,13,13,13,14,14, 8,
  153218. 9, 9,11,11,12,11,12,12,13,12,12,13,13,14,15,14,
  153219. 14,14, 8, 9, 9,10,11,11,11,12,12,13,12,13,13,14,
  153220. 14,14,15,14,16, 8, 9, 9,11,10,12,12,12,12,15,13,
  153221. 13,13,17,14,15,15,15,14, 8, 9, 9,10,11,11,12,13,
  153222. 12,13,13,13,14,15,14,14,14,16,15, 9,11,10,12,12,
  153223. 13,13,13,13,14,14,16,15,14,14,14,15,15,17, 9,10,
  153224. 10,11,11,13,13,13,14,14,13,15,14,15,14,15,16,15,
  153225. 16,10,11,11,12,12,13,14,15,14,15,14,14,15,17,16,
  153226. 15,15,17,17,10,12,11,13,12,14,14,13,14,15,15,15,
  153227. 15,16,17,17,15,17,16,11,12,12,14,13,15,14,15,16,
  153228. 17,15,17,15,17,15,15,16,17,15,11,11,12,14,14,14,
  153229. 14,14,15,15,16,15,17,17,17,16,17,16,15,12,12,13,
  153230. 14,14,14,15,14,15,15,16,16,17,16,17,15,17,17,16,
  153231. 12,14,12,14,14,15,15,15,14,14,16,16,16,15,16,16,
  153232. 15,17,15,12,13,13,14,15,14,15,17,15,17,16,17,17,
  153233. 17,16,17,16,17,17,12,13,13,14,16,15,15,15,16,15,
  153234. 17,17,15,17,15,17,16,16,17,
  153235. };
  153236. static float _vq_quantthresh__44u9_p9_1[] = {
  153237. -416.5, -367.5, -318.5, -269.5, -220.5, -171.5, -122.5, -73.5,
  153238. -24.5, 24.5, 73.5, 122.5, 171.5, 220.5, 269.5, 318.5,
  153239. 367.5, 416.5,
  153240. };
  153241. static long _vq_quantmap__44u9_p9_1[] = {
  153242. 17, 15, 13, 11, 9, 7, 5, 3,
  153243. 1, 0, 2, 4, 6, 8, 10, 12,
  153244. 14, 16, 18,
  153245. };
  153246. static encode_aux_threshmatch _vq_auxt__44u9_p9_1 = {
  153247. _vq_quantthresh__44u9_p9_1,
  153248. _vq_quantmap__44u9_p9_1,
  153249. 19,
  153250. 19
  153251. };
  153252. static static_codebook _44u9_p9_1 = {
  153253. 2, 361,
  153254. _vq_lengthlist__44u9_p9_1,
  153255. 1, -518287360, 1622704128, 5, 0,
  153256. _vq_quantlist__44u9_p9_1,
  153257. NULL,
  153258. &_vq_auxt__44u9_p9_1,
  153259. NULL,
  153260. 0
  153261. };
  153262. static long _vq_quantlist__44u9_p9_2[] = {
  153263. 24,
  153264. 23,
  153265. 25,
  153266. 22,
  153267. 26,
  153268. 21,
  153269. 27,
  153270. 20,
  153271. 28,
  153272. 19,
  153273. 29,
  153274. 18,
  153275. 30,
  153276. 17,
  153277. 31,
  153278. 16,
  153279. 32,
  153280. 15,
  153281. 33,
  153282. 14,
  153283. 34,
  153284. 13,
  153285. 35,
  153286. 12,
  153287. 36,
  153288. 11,
  153289. 37,
  153290. 10,
  153291. 38,
  153292. 9,
  153293. 39,
  153294. 8,
  153295. 40,
  153296. 7,
  153297. 41,
  153298. 6,
  153299. 42,
  153300. 5,
  153301. 43,
  153302. 4,
  153303. 44,
  153304. 3,
  153305. 45,
  153306. 2,
  153307. 46,
  153308. 1,
  153309. 47,
  153310. 0,
  153311. 48,
  153312. };
  153313. static long _vq_lengthlist__44u9_p9_2[] = {
  153314. 2, 4, 4, 5, 4, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6,
  153315. 6, 6, 6, 7, 6, 7, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  153316. 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7,
  153317. 7,
  153318. };
  153319. static float _vq_quantthresh__44u9_p9_2[] = {
  153320. -23.5, -22.5, -21.5, -20.5, -19.5, -18.5, -17.5, -16.5,
  153321. -15.5, -14.5, -13.5, -12.5, -11.5, -10.5, -9.5, -8.5,
  153322. -7.5, -6.5, -5.5, -4.5, -3.5, -2.5, -1.5, -0.5,
  153323. 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5,
  153324. 8.5, 9.5, 10.5, 11.5, 12.5, 13.5, 14.5, 15.5,
  153325. 16.5, 17.5, 18.5, 19.5, 20.5, 21.5, 22.5, 23.5,
  153326. };
  153327. static long _vq_quantmap__44u9_p9_2[] = {
  153328. 47, 45, 43, 41, 39, 37, 35, 33,
  153329. 31, 29, 27, 25, 23, 21, 19, 17,
  153330. 15, 13, 11, 9, 7, 5, 3, 1,
  153331. 0, 2, 4, 6, 8, 10, 12, 14,
  153332. 16, 18, 20, 22, 24, 26, 28, 30,
  153333. 32, 34, 36, 38, 40, 42, 44, 46,
  153334. 48,
  153335. };
  153336. static encode_aux_threshmatch _vq_auxt__44u9_p9_2 = {
  153337. _vq_quantthresh__44u9_p9_2,
  153338. _vq_quantmap__44u9_p9_2,
  153339. 49,
  153340. 49
  153341. };
  153342. static static_codebook _44u9_p9_2 = {
  153343. 1, 49,
  153344. _vq_lengthlist__44u9_p9_2,
  153345. 1, -526909440, 1611661312, 6, 0,
  153346. _vq_quantlist__44u9_p9_2,
  153347. NULL,
  153348. &_vq_auxt__44u9_p9_2,
  153349. NULL,
  153350. 0
  153351. };
  153352. static long _huff_lengthlist__44un1__long[] = {
  153353. 5, 6,12, 9,14, 9, 9,19, 6, 1, 5, 5, 8, 7, 9,19,
  153354. 12, 4, 4, 7, 7, 9,11,18, 9, 5, 6, 6, 8, 7, 8,17,
  153355. 14, 8, 7, 8, 8,10,12,18, 9, 6, 8, 6, 8, 6, 8,18,
  153356. 9, 8,11, 8,11, 7, 5,15,16,18,18,18,17,15,11,18,
  153357. };
  153358. static static_codebook _huff_book__44un1__long = {
  153359. 2, 64,
  153360. _huff_lengthlist__44un1__long,
  153361. 0, 0, 0, 0, 0,
  153362. NULL,
  153363. NULL,
  153364. NULL,
  153365. NULL,
  153366. 0
  153367. };
  153368. static long _vq_quantlist__44un1__p1_0[] = {
  153369. 1,
  153370. 0,
  153371. 2,
  153372. };
  153373. static long _vq_lengthlist__44un1__p1_0[] = {
  153374. 1, 4, 4, 5, 8, 7, 5, 7, 8, 5, 8, 8, 8,10,11, 8,
  153375. 10,11, 5, 8, 8, 8,11,10, 8,11,10, 4, 9, 9, 8,11,
  153376. 11, 8,11,11, 8,12,11,10,12,14,11,13,13, 7,11,11,
  153377. 10,13,11,11,13,14, 4, 8, 9, 8,11,11, 8,11,12, 7,
  153378. 11,11,11,14,13,10,11,13, 8,11,12,11,13,13,10,14,
  153379. 12,
  153380. };
  153381. static float _vq_quantthresh__44un1__p1_0[] = {
  153382. -0.5, 0.5,
  153383. };
  153384. static long _vq_quantmap__44un1__p1_0[] = {
  153385. 1, 0, 2,
  153386. };
  153387. static encode_aux_threshmatch _vq_auxt__44un1__p1_0 = {
  153388. _vq_quantthresh__44un1__p1_0,
  153389. _vq_quantmap__44un1__p1_0,
  153390. 3,
  153391. 3
  153392. };
  153393. static static_codebook _44un1__p1_0 = {
  153394. 4, 81,
  153395. _vq_lengthlist__44un1__p1_0,
  153396. 1, -535822336, 1611661312, 2, 0,
  153397. _vq_quantlist__44un1__p1_0,
  153398. NULL,
  153399. &_vq_auxt__44un1__p1_0,
  153400. NULL,
  153401. 0
  153402. };
  153403. static long _vq_quantlist__44un1__p2_0[] = {
  153404. 1,
  153405. 0,
  153406. 2,
  153407. };
  153408. static long _vq_lengthlist__44un1__p2_0[] = {
  153409. 2, 4, 4, 5, 6, 6, 5, 6, 6, 5, 7, 7, 7, 8, 8, 6,
  153410. 7, 9, 5, 7, 7, 6, 8, 7, 7, 9, 8, 4, 7, 7, 7, 9,
  153411. 8, 7, 8, 8, 7, 9, 8, 8, 8,10, 9,10,10, 6, 8, 8,
  153412. 7,10, 8, 9,10,10, 5, 7, 7, 7, 8, 8, 7, 8, 9, 6,
  153413. 8, 8, 9,10,10, 7, 8,10, 6, 8, 9, 9,10,10, 8,10,
  153414. 8,
  153415. };
  153416. static float _vq_quantthresh__44un1__p2_0[] = {
  153417. -0.5, 0.5,
  153418. };
  153419. static long _vq_quantmap__44un1__p2_0[] = {
  153420. 1, 0, 2,
  153421. };
  153422. static encode_aux_threshmatch _vq_auxt__44un1__p2_0 = {
  153423. _vq_quantthresh__44un1__p2_0,
  153424. _vq_quantmap__44un1__p2_0,
  153425. 3,
  153426. 3
  153427. };
  153428. static static_codebook _44un1__p2_0 = {
  153429. 4, 81,
  153430. _vq_lengthlist__44un1__p2_0,
  153431. 1, -535822336, 1611661312, 2, 0,
  153432. _vq_quantlist__44un1__p2_0,
  153433. NULL,
  153434. &_vq_auxt__44un1__p2_0,
  153435. NULL,
  153436. 0
  153437. };
  153438. static long _vq_quantlist__44un1__p3_0[] = {
  153439. 2,
  153440. 1,
  153441. 3,
  153442. 0,
  153443. 4,
  153444. };
  153445. static long _vq_lengthlist__44un1__p3_0[] = {
  153446. 1, 5, 5, 8, 8, 5, 8, 7, 9, 9, 5, 7, 8, 9, 9, 9,
  153447. 10, 9,12,12, 9, 9,10,11,12, 6, 8, 8,10,10, 8,10,
  153448. 10,11,11, 8, 9,10,11,11,10,11,11,13,13,10,11,11,
  153449. 12,13, 6, 8, 8,10,10, 8,10, 9,11,11, 8,10,10,11,
  153450. 11,10,11,11,13,12,10,11,11,13,12, 9,11,11,15,13,
  153451. 10,12,11,15,13,10,11,11,15,14,12,14,13,16,15,12,
  153452. 13,13,17,16, 9,11,11,13,15,10,11,12,14,15,10,11,
  153453. 12,14,15,12,13,13,15,16,12,13,13,16,16, 5, 8, 8,
  153454. 11,11, 8,10,10,12,12, 8,10,10,12,12,11,12,12,14,
  153455. 14,11,12,12,14,14, 8,11,10,13,12,10,11,12,12,13,
  153456. 10,12,12,13,13,12,12,13,13,15,11,12,13,15,14, 7,
  153457. 10,10,12,12, 9,12,11,13,12,10,12,12,13,14,12,13,
  153458. 12,15,13,11,13,12,14,15,10,12,12,16,14,11,12,12,
  153459. 16,15,11,13,12,17,16,13,13,15,15,17,13,15,15,20,
  153460. 17,10,12,12,14,16,11,12,12,15,15,11,13,13,15,18,
  153461. 13,14,13,15,15,13,15,14,16,16, 5, 8, 8,11,11, 8,
  153462. 10,10,12,12, 8,10,10,12,12,11,12,12,14,14,11,12,
  153463. 12,14,15, 7,10,10,13,12,10,12,12,14,13, 9,10,12,
  153464. 12,13,11,13,13,15,15,11,12,13,13,15, 8,10,10,12,
  153465. 13,10,12,12,13,13,10,12,11,13,13,11,13,12,15,15,
  153466. 12,13,12,15,13,10,12,12,16,14,11,12,12,16,15,10,
  153467. 12,12,16,14,14,15,14,18,16,13,13,14,15,16,10,12,
  153468. 12,14,16,11,13,13,16,16,11,13,12,14,16,13,15,15,
  153469. 18,18,13,15,13,16,14, 8,11,11,16,16,10,13,13,17,
  153470. 16,10,12,12,16,15,14,16,15,20,17,13,14,14,17,17,
  153471. 9,12,12,16,16,11,13,14,16,17,11,13,13,16,16,15,
  153472. 15,19,18, 0,14,15,15,18,18, 9,12,12,17,16,11,13,
  153473. 12,17,16,11,12,13,15,17,15,16,15, 0,19,14,15,14,
  153474. 19,18,12,14,14, 0,16,13,14,14,19,18,13,15,16,17,
  153475. 16,15,15,17,18, 0,14,16,16,19, 0,12,14,14,16,18,
  153476. 13,15,13,17,18,13,15,14,17,18,15,18,14,18,18,16,
  153477. 17,16, 0,17, 8,11,11,15,15,10,12,12,16,16,10,13,
  153478. 13,16,16,13,15,14,17,17,14,15,17,17,18, 9,12,12,
  153479. 16,15,11,13,13,16,16,11,12,13,17,17,14,14,15,17,
  153480. 17,14,15,16, 0,18, 9,12,12,16,17,11,13,13,16,17,
  153481. 11,14,13,18,17,14,16,14,17,17,15,17,17,18,18,12,
  153482. 14,14, 0,16,13,15,15,19, 0,12,13,15, 0, 0,14,17,
  153483. 16,19, 0,16,15,18,18, 0,12,14,14,17, 0,13,14,14,
  153484. 17, 0,13,15,14, 0,18,15,16,16, 0,18,15,18,15, 0,
  153485. 17,
  153486. };
  153487. static float _vq_quantthresh__44un1__p3_0[] = {
  153488. -1.5, -0.5, 0.5, 1.5,
  153489. };
  153490. static long _vq_quantmap__44un1__p3_0[] = {
  153491. 3, 1, 0, 2, 4,
  153492. };
  153493. static encode_aux_threshmatch _vq_auxt__44un1__p3_0 = {
  153494. _vq_quantthresh__44un1__p3_0,
  153495. _vq_quantmap__44un1__p3_0,
  153496. 5,
  153497. 5
  153498. };
  153499. static static_codebook _44un1__p3_0 = {
  153500. 4, 625,
  153501. _vq_lengthlist__44un1__p3_0,
  153502. 1, -533725184, 1611661312, 3, 0,
  153503. _vq_quantlist__44un1__p3_0,
  153504. NULL,
  153505. &_vq_auxt__44un1__p3_0,
  153506. NULL,
  153507. 0
  153508. };
  153509. static long _vq_quantlist__44un1__p4_0[] = {
  153510. 2,
  153511. 1,
  153512. 3,
  153513. 0,
  153514. 4,
  153515. };
  153516. static long _vq_lengthlist__44un1__p4_0[] = {
  153517. 3, 5, 5, 9, 9, 5, 6, 6,10, 9, 5, 6, 6, 9,10,10,
  153518. 10,10,12,11, 9,10,10,12,12, 5, 7, 7,10,10, 7, 7,
  153519. 8,10,11, 7, 7, 8,10,11,10,10,11,11,13,10,10,11,
  153520. 11,13, 6, 7, 7,10,10, 7, 8, 7,11,10, 7, 8, 7,10,
  153521. 10,10,11, 9,13,11,10,11,10,13,11,10,10,10,14,13,
  153522. 10,11,11,14,13,10,10,11,13,14,12,12,13,15,15,12,
  153523. 12,13,13,14,10,10,10,12,13,10,11,10,13,13,10,11,
  153524. 11,13,13,12,13,12,14,13,12,13,13,14,13, 5, 7, 7,
  153525. 10,10, 7, 8, 8,11,10, 7, 8, 8,10,10,11,11,11,13,
  153526. 13,10,11,11,12,12, 7, 8, 8,11,11, 7, 8, 9,10,12,
  153527. 8, 9, 9,11,11,11,10,12,11,14,11,11,12,13,13, 6,
  153528. 8, 8,10,11, 7, 9, 7,12,10, 8, 9,10,11,12,10,12,
  153529. 10,14,11,11,12,11,13,13,10,11,11,14,14,10,10,11,
  153530. 13,14,11,12,12,15,13,12,11,14,12,16,12,13,14,15,
  153531. 16,10,10,11,13,14,10,11,10,14,12,11,12,12,13,14,
  153532. 12,13,11,15,12,14,14,14,15,15, 5, 7, 7,10,10, 7,
  153533. 8, 8,10,10, 7, 8, 8,10,11,10,11,10,12,12,10,11,
  153534. 11,12,13, 6, 8, 8,11,11, 8, 9, 9,12,11, 7, 7, 9,
  153535. 10,12,11,11,11,12,13,11,10,12,11,15, 7, 8, 8,11,
  153536. 11, 8, 9, 9,11,11, 7, 9, 8,12,10,11,12,11,13,12,
  153537. 11,12,10,15,11,10,11,10,14,12,11,12,11,14,13,10,
  153538. 10,11,13,14,13,13,13,17,15,12,11,14,12,15,10,10,
  153539. 11,13,14,11,12,12,14,14,10,11,10,14,13,13,14,13,
  153540. 16,17,12,14,11,16,12, 9,10,10,14,13,10,11,10,14,
  153541. 14,10,11,11,13,13,13,14,14,16,15,12,13,13,14,14,
  153542. 9,11,10,14,13,10,10,12,13,14,11,12,11,14,13,13,
  153543. 14,14,14,15,13,14,14,15,15, 9,10,11,13,14,10,11,
  153544. 10,15,13,11,11,12,12,15,13,14,12,15,14,13,13,14,
  153545. 14,15,12,13,12,16,14,11,11,12,15,14,13,15,13,16,
  153546. 14,13,12,15,12,17,15,16,15,16,16,12,12,13,13,15,
  153547. 11,13,11,15,14,13,13,14,15,17,13,14,12, 0,13,14,
  153548. 15,14,15, 0, 9,10,10,13,13,10,11,11,13,13,10,11,
  153549. 11,13,13,12,13,12,14,14,13,14,14,15,17, 9,10,10,
  153550. 13,13,11,12,11,15,12,10,10,11,13,16,13,14,13,15,
  153551. 14,13,13,14,15,16,10,10,11,13,14,11,11,12,13,14,
  153552. 10,12,11,14,14,13,13,13,14,15,13,15,13,16,15,12,
  153553. 13,12,15,13,12,15,13,15,15,11,11,13,14,15,15,15,
  153554. 15,15,17,13,12,14,13,17,12,12,14,14,15,13,13,14,
  153555. 14,16,11,13,11,16,15,14,16,16,17, 0,14,13,11,16,
  153556. 12,
  153557. };
  153558. static float _vq_quantthresh__44un1__p4_0[] = {
  153559. -1.5, -0.5, 0.5, 1.5,
  153560. };
  153561. static long _vq_quantmap__44un1__p4_0[] = {
  153562. 3, 1, 0, 2, 4,
  153563. };
  153564. static encode_aux_threshmatch _vq_auxt__44un1__p4_0 = {
  153565. _vq_quantthresh__44un1__p4_0,
  153566. _vq_quantmap__44un1__p4_0,
  153567. 5,
  153568. 5
  153569. };
  153570. static static_codebook _44un1__p4_0 = {
  153571. 4, 625,
  153572. _vq_lengthlist__44un1__p4_0,
  153573. 1, -533725184, 1611661312, 3, 0,
  153574. _vq_quantlist__44un1__p4_0,
  153575. NULL,
  153576. &_vq_auxt__44un1__p4_0,
  153577. NULL,
  153578. 0
  153579. };
  153580. static long _vq_quantlist__44un1__p5_0[] = {
  153581. 4,
  153582. 3,
  153583. 5,
  153584. 2,
  153585. 6,
  153586. 1,
  153587. 7,
  153588. 0,
  153589. 8,
  153590. };
  153591. static long _vq_lengthlist__44un1__p5_0[] = {
  153592. 1, 4, 4, 7, 7, 8, 8, 9, 9, 4, 6, 5, 8, 7, 8, 8,
  153593. 10, 9, 4, 6, 6, 8, 8, 8, 8,10,10, 7, 8, 7, 9, 9,
  153594. 9, 9,11,10, 7, 8, 8, 9, 9, 9, 9,10,11, 8, 8, 8,
  153595. 9, 9,10,10,11,11, 8, 8, 8, 9, 9,10,10,11,11, 9,
  153596. 10,10,11,10,11,11,12,12, 9,10,10,10,11,11,11,12,
  153597. 12,
  153598. };
  153599. static float _vq_quantthresh__44un1__p5_0[] = {
  153600. -3.5, -2.5, -1.5, -0.5, 0.5, 1.5, 2.5, 3.5,
  153601. };
  153602. static long _vq_quantmap__44un1__p5_0[] = {
  153603. 7, 5, 3, 1, 0, 2, 4, 6,
  153604. 8,
  153605. };
  153606. static encode_aux_threshmatch _vq_auxt__44un1__p5_0 = {
  153607. _vq_quantthresh__44un1__p5_0,
  153608. _vq_quantmap__44un1__p5_0,
  153609. 9,
  153610. 9
  153611. };
  153612. static static_codebook _44un1__p5_0 = {
  153613. 2, 81,
  153614. _vq_lengthlist__44un1__p5_0,
  153615. 1, -531628032, 1611661312, 4, 0,
  153616. _vq_quantlist__44un1__p5_0,
  153617. NULL,
  153618. &_vq_auxt__44un1__p5_0,
  153619. NULL,
  153620. 0
  153621. };
  153622. static long _vq_quantlist__44un1__p6_0[] = {
  153623. 6,
  153624. 5,
  153625. 7,
  153626. 4,
  153627. 8,
  153628. 3,
  153629. 9,
  153630. 2,
  153631. 10,
  153632. 1,
  153633. 11,
  153634. 0,
  153635. 12,
  153636. };
  153637. static long _vq_lengthlist__44un1__p6_0[] = {
  153638. 1, 4, 4, 6, 6, 8, 8,10,10,11,11,15,15, 4, 5, 5,
  153639. 8, 8, 9, 9,11,11,12,12,16,16, 4, 5, 6, 8, 8, 9,
  153640. 9,11,11,12,12,14,14, 7, 8, 8, 9, 9,10,10,11,12,
  153641. 13,13,16,17, 7, 8, 8, 9, 9,10,10,12,12,12,13,15,
  153642. 15, 9,10,10,10,10,11,11,12,12,13,13,15,16, 9, 9,
  153643. 9,10,10,11,11,13,12,13,13,17,17,10,11,11,11,12,
  153644. 12,12,13,13,14,15, 0,18,10,11,11,12,12,12,13,14,
  153645. 13,14,14,17,16,11,12,12,13,13,14,14,14,14,15,16,
  153646. 17,16,11,12,12,13,13,14,14,14,14,15,15,17,17,14,
  153647. 15,15,16,16,16,17,17,16, 0,17, 0,18,14,15,15,16,
  153648. 16, 0,15,18,18, 0,16, 0, 0,
  153649. };
  153650. static float _vq_quantthresh__44un1__p6_0[] = {
  153651. -27.5, -22.5, -17.5, -12.5, -7.5, -2.5, 2.5, 7.5,
  153652. 12.5, 17.5, 22.5, 27.5,
  153653. };
  153654. static long _vq_quantmap__44un1__p6_0[] = {
  153655. 11, 9, 7, 5, 3, 1, 0, 2,
  153656. 4, 6, 8, 10, 12,
  153657. };
  153658. static encode_aux_threshmatch _vq_auxt__44un1__p6_0 = {
  153659. _vq_quantthresh__44un1__p6_0,
  153660. _vq_quantmap__44un1__p6_0,
  153661. 13,
  153662. 13
  153663. };
  153664. static static_codebook _44un1__p6_0 = {
  153665. 2, 169,
  153666. _vq_lengthlist__44un1__p6_0,
  153667. 1, -526516224, 1616117760, 4, 0,
  153668. _vq_quantlist__44un1__p6_0,
  153669. NULL,
  153670. &_vq_auxt__44un1__p6_0,
  153671. NULL,
  153672. 0
  153673. };
  153674. static long _vq_quantlist__44un1__p6_1[] = {
  153675. 2,
  153676. 1,
  153677. 3,
  153678. 0,
  153679. 4,
  153680. };
  153681. static long _vq_lengthlist__44un1__p6_1[] = {
  153682. 2, 4, 4, 5, 5, 4, 5, 5, 5, 5, 4, 5, 5, 6, 5, 5,
  153683. 6, 5, 6, 6, 5, 6, 6, 6, 6,
  153684. };
  153685. static float _vq_quantthresh__44un1__p6_1[] = {
  153686. -1.5, -0.5, 0.5, 1.5,
  153687. };
  153688. static long _vq_quantmap__44un1__p6_1[] = {
  153689. 3, 1, 0, 2, 4,
  153690. };
  153691. static encode_aux_threshmatch _vq_auxt__44un1__p6_1 = {
  153692. _vq_quantthresh__44un1__p6_1,
  153693. _vq_quantmap__44un1__p6_1,
  153694. 5,
  153695. 5
  153696. };
  153697. static static_codebook _44un1__p6_1 = {
  153698. 2, 25,
  153699. _vq_lengthlist__44un1__p6_1,
  153700. 1, -533725184, 1611661312, 3, 0,
  153701. _vq_quantlist__44un1__p6_1,
  153702. NULL,
  153703. &_vq_auxt__44un1__p6_1,
  153704. NULL,
  153705. 0
  153706. };
  153707. static long _vq_quantlist__44un1__p7_0[] = {
  153708. 2,
  153709. 1,
  153710. 3,
  153711. 0,
  153712. 4,
  153713. };
  153714. static long _vq_lengthlist__44un1__p7_0[] = {
  153715. 1, 5, 3,11,11,11,11,11,11,11, 8,11,11,11,11,11,
  153716. 11,11,11,11,11,11,11,11,11,10,11,11,11,11,11,11,
  153717. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153718. 11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153719. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153720. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153721. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153722. 11,11,11,11,11,11,11,11,11,11,11,11,11, 8,11,11,
  153723. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153724. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153725. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,10,
  153726. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153727. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153728. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153729. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153730. 11,11,11,11,11,11,11,11,11,11, 7,11,11,11,11,11,
  153731. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153732. 11,11,11,10,11,11,11,11,11,11,11,11,11,11,11,11,
  153733. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153734. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153735. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153736. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153737. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153738. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153739. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153740. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153741. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153742. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153743. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153744. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153745. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153746. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153747. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153748. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153749. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153750. 11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,11,
  153751. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153752. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153753. 10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,10,
  153754. 10,
  153755. };
  153756. static float _vq_quantthresh__44un1__p7_0[] = {
  153757. -253.5, -84.5, 84.5, 253.5,
  153758. };
  153759. static long _vq_quantmap__44un1__p7_0[] = {
  153760. 3, 1, 0, 2, 4,
  153761. };
  153762. static encode_aux_threshmatch _vq_auxt__44un1__p7_0 = {
  153763. _vq_quantthresh__44un1__p7_0,
  153764. _vq_quantmap__44un1__p7_0,
  153765. 5,
  153766. 5
  153767. };
  153768. static static_codebook _44un1__p7_0 = {
  153769. 4, 625,
  153770. _vq_lengthlist__44un1__p7_0,
  153771. 1, -518709248, 1626677248, 3, 0,
  153772. _vq_quantlist__44un1__p7_0,
  153773. NULL,
  153774. &_vq_auxt__44un1__p7_0,
  153775. NULL,
  153776. 0
  153777. };
  153778. static long _vq_quantlist__44un1__p7_1[] = {
  153779. 6,
  153780. 5,
  153781. 7,
  153782. 4,
  153783. 8,
  153784. 3,
  153785. 9,
  153786. 2,
  153787. 10,
  153788. 1,
  153789. 11,
  153790. 0,
  153791. 12,
  153792. };
  153793. static long _vq_lengthlist__44un1__p7_1[] = {
  153794. 1, 4, 4, 6, 6, 6, 6, 9, 8, 9, 8, 8, 8, 5, 7, 7,
  153795. 7, 7, 8, 8, 8,10, 8,10, 8, 9, 5, 7, 7, 8, 7, 7,
  153796. 8,10,10,11,10,12,11, 7, 8, 8, 9, 9, 9,10,11,11,
  153797. 11,11,11,11, 7, 8, 8, 8, 9, 9, 9,10,10,10,11,11,
  153798. 12, 7, 8, 8, 9, 9,10,11,11,12,11,12,11,11, 7, 8,
  153799. 8, 9, 9,10,10,11,11,11,12,12,11, 8,10,10,10,10,
  153800. 11,11,14,11,12,12,12,13, 9,10,10,10,10,12,11,14,
  153801. 11,14,11,12,13,10,11,11,11,11,13,11,14,14,13,13,
  153802. 13,14,11,11,11,12,11,12,12,12,13,14,14,13,14,12,
  153803. 11,12,12,12,12,13,13,13,14,13,14,14,11,12,12,14,
  153804. 12,13,13,12,13,13,14,14,14,
  153805. };
  153806. static float _vq_quantthresh__44un1__p7_1[] = {
  153807. -71.5, -58.5, -45.5, -32.5, -19.5, -6.5, 6.5, 19.5,
  153808. 32.5, 45.5, 58.5, 71.5,
  153809. };
  153810. static long _vq_quantmap__44un1__p7_1[] = {
  153811. 11, 9, 7, 5, 3, 1, 0, 2,
  153812. 4, 6, 8, 10, 12,
  153813. };
  153814. static encode_aux_threshmatch _vq_auxt__44un1__p7_1 = {
  153815. _vq_quantthresh__44un1__p7_1,
  153816. _vq_quantmap__44un1__p7_1,
  153817. 13,
  153818. 13
  153819. };
  153820. static static_codebook _44un1__p7_1 = {
  153821. 2, 169,
  153822. _vq_lengthlist__44un1__p7_1,
  153823. 1, -523010048, 1618608128, 4, 0,
  153824. _vq_quantlist__44un1__p7_1,
  153825. NULL,
  153826. &_vq_auxt__44un1__p7_1,
  153827. NULL,
  153828. 0
  153829. };
  153830. static long _vq_quantlist__44un1__p7_2[] = {
  153831. 6,
  153832. 5,
  153833. 7,
  153834. 4,
  153835. 8,
  153836. 3,
  153837. 9,
  153838. 2,
  153839. 10,
  153840. 1,
  153841. 11,
  153842. 0,
  153843. 12,
  153844. };
  153845. static long _vq_lengthlist__44un1__p7_2[] = {
  153846. 3, 4, 4, 6, 6, 7, 7, 8, 8, 9, 9, 9, 8, 4, 5, 5,
  153847. 6, 6, 8, 8, 9, 8, 9, 9, 9, 9, 4, 5, 5, 7, 6, 8,
  153848. 8, 8, 8, 9, 8, 9, 8, 6, 7, 7, 7, 8, 8, 8, 9, 9,
  153849. 9, 9, 9, 9, 6, 7, 7, 7, 7, 8, 8, 9, 9, 9, 9, 9,
  153850. 9, 7, 8, 8, 8, 8, 9, 8, 9, 9,10, 9, 9,10, 7, 8,
  153851. 8, 8, 8, 9, 9, 9, 9, 9, 9,10,10, 8, 9, 9, 9, 9,
  153852. 9, 9, 9, 9,10,10, 9,10, 8, 9, 9, 9, 9, 9, 9, 9,
  153853. 9, 9, 9,10,10, 9, 9, 9,10, 9, 9,10, 9, 9,10,10,
  153854. 10,10, 9, 9, 9, 9, 9, 9, 9,10, 9,10,10,10,10, 9,
  153855. 9, 9,10, 9, 9,10,10, 9,10,10,10,10, 9, 9, 9,10,
  153856. 9, 9, 9,10,10,10,10,10,10,
  153857. };
  153858. static float _vq_quantthresh__44un1__p7_2[] = {
  153859. -5.5, -4.5, -3.5, -2.5, -1.5, -0.5, 0.5, 1.5,
  153860. 2.5, 3.5, 4.5, 5.5,
  153861. };
  153862. static long _vq_quantmap__44un1__p7_2[] = {
  153863. 11, 9, 7, 5, 3, 1, 0, 2,
  153864. 4, 6, 8, 10, 12,
  153865. };
  153866. static encode_aux_threshmatch _vq_auxt__44un1__p7_2 = {
  153867. _vq_quantthresh__44un1__p7_2,
  153868. _vq_quantmap__44un1__p7_2,
  153869. 13,
  153870. 13
  153871. };
  153872. static static_codebook _44un1__p7_2 = {
  153873. 2, 169,
  153874. _vq_lengthlist__44un1__p7_2,
  153875. 1, -531103744, 1611661312, 4, 0,
  153876. _vq_quantlist__44un1__p7_2,
  153877. NULL,
  153878. &_vq_auxt__44un1__p7_2,
  153879. NULL,
  153880. 0
  153881. };
  153882. static long _huff_lengthlist__44un1__short[] = {
  153883. 12,12,14,12,14,14,14,14,12, 6, 6, 8, 9, 9,11,14,
  153884. 12, 4, 2, 6, 6, 7,11,14,13, 6, 5, 7, 8, 9,11,14,
  153885. 13, 8, 5, 8, 6, 8,12,14,12, 7, 7, 8, 8, 8,10,14,
  153886. 12, 6, 3, 4, 4, 4, 7,14,11, 7, 4, 6, 6, 6, 8,14,
  153887. };
  153888. static static_codebook _huff_book__44un1__short = {
  153889. 2, 64,
  153890. _huff_lengthlist__44un1__short,
  153891. 0, 0, 0, 0, 0,
  153892. NULL,
  153893. NULL,
  153894. NULL,
  153895. NULL,
  153896. 0
  153897. };
  153898. /********* End of inlined file: res_books_uncoupled.h *********/
  153899. /***** residue backends *********************************************/
  153900. static vorbis_info_residue0 _residue_44_low_un={
  153901. 0,-1, -1, 8,-1,
  153902. {0},
  153903. {-1},
  153904. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 28.5},
  153905. { -1, 25, -1, 45, -1, -1, -1}
  153906. };
  153907. static vorbis_info_residue0 _residue_44_mid_un={
  153908. 0,-1, -1, 10,-1,
  153909. /* 0 1 2 3 4 5 6 7 8 9 */
  153910. {0},
  153911. {-1},
  153912. { .5, 1.5, 1.5, 2.5, 2.5, 4.5, 4.5, 16.5, 60.5},
  153913. { -1, 30, -1, 50, -1, 80, -1, -1, -1}
  153914. };
  153915. static vorbis_info_residue0 _residue_44_hi_un={
  153916. 0,-1, -1, 10,-1,
  153917. /* 0 1 2 3 4 5 6 7 8 9 */
  153918. {0},
  153919. {-1},
  153920. { .5, 1.5, 2.5, 4.5, 8.5, 16.5, 32.5, 71.5,157.5},
  153921. { -1, -1, -1, -1, -1, -1, -1, -1, -1}
  153922. };
  153923. /* mapping conventions:
  153924. only one submap (this would change for efficient 5.1 support for example)*/
  153925. /* Four psychoacoustic profiles are used, one for each blocktype */
  153926. static vorbis_info_mapping0 _map_nominal_u[2]={
  153927. {1, {0,0}, {0}, {0}, 0,{0},{0}},
  153928. {1, {0,0}, {1}, {1}, 0,{0},{0}}
  153929. };
  153930. static static_bookblock _resbook_44u_n1={
  153931. {
  153932. {0},
  153933. {0,0,&_44un1__p1_0},
  153934. {0,0,&_44un1__p2_0},
  153935. {0,0,&_44un1__p3_0},
  153936. {0,0,&_44un1__p4_0},
  153937. {0,0,&_44un1__p5_0},
  153938. {&_44un1__p6_0,&_44un1__p6_1},
  153939. {&_44un1__p7_0,&_44un1__p7_1,&_44un1__p7_2}
  153940. }
  153941. };
  153942. static static_bookblock _resbook_44u_0={
  153943. {
  153944. {0},
  153945. {0,0,&_44u0__p1_0},
  153946. {0,0,&_44u0__p2_0},
  153947. {0,0,&_44u0__p3_0},
  153948. {0,0,&_44u0__p4_0},
  153949. {0,0,&_44u0__p5_0},
  153950. {&_44u0__p6_0,&_44u0__p6_1},
  153951. {&_44u0__p7_0,&_44u0__p7_1,&_44u0__p7_2}
  153952. }
  153953. };
  153954. static static_bookblock _resbook_44u_1={
  153955. {
  153956. {0},
  153957. {0,0,&_44u1__p1_0},
  153958. {0,0,&_44u1__p2_0},
  153959. {0,0,&_44u1__p3_0},
  153960. {0,0,&_44u1__p4_0},
  153961. {0,0,&_44u1__p5_0},
  153962. {&_44u1__p6_0,&_44u1__p6_1},
  153963. {&_44u1__p7_0,&_44u1__p7_1,&_44u1__p7_2}
  153964. }
  153965. };
  153966. static static_bookblock _resbook_44u_2={
  153967. {
  153968. {0},
  153969. {0,0,&_44u2__p1_0},
  153970. {0,0,&_44u2__p2_0},
  153971. {0,0,&_44u2__p3_0},
  153972. {0,0,&_44u2__p4_0},
  153973. {0,0,&_44u2__p5_0},
  153974. {&_44u2__p6_0,&_44u2__p6_1},
  153975. {&_44u2__p7_0,&_44u2__p7_1,&_44u2__p7_2}
  153976. }
  153977. };
  153978. static static_bookblock _resbook_44u_3={
  153979. {
  153980. {0},
  153981. {0,0,&_44u3__p1_0},
  153982. {0,0,&_44u3__p2_0},
  153983. {0,0,&_44u3__p3_0},
  153984. {0,0,&_44u3__p4_0},
  153985. {0,0,&_44u3__p5_0},
  153986. {&_44u3__p6_0,&_44u3__p6_1},
  153987. {&_44u3__p7_0,&_44u3__p7_1,&_44u3__p7_2}
  153988. }
  153989. };
  153990. static static_bookblock _resbook_44u_4={
  153991. {
  153992. {0},
  153993. {0,0,&_44u4__p1_0},
  153994. {0,0,&_44u4__p2_0},
  153995. {0,0,&_44u4__p3_0},
  153996. {0,0,&_44u4__p4_0},
  153997. {0,0,&_44u4__p5_0},
  153998. {&_44u4__p6_0,&_44u4__p6_1},
  153999. {&_44u4__p7_0,&_44u4__p7_1,&_44u4__p7_2}
  154000. }
  154001. };
  154002. static static_bookblock _resbook_44u_5={
  154003. {
  154004. {0},
  154005. {0,0,&_44u5__p1_0},
  154006. {0,0,&_44u5__p2_0},
  154007. {0,0,&_44u5__p3_0},
  154008. {0,0,&_44u5__p4_0},
  154009. {0,0,&_44u5__p5_0},
  154010. {0,0,&_44u5__p6_0},
  154011. {&_44u5__p7_0,&_44u5__p7_1},
  154012. {&_44u5__p8_0,&_44u5__p8_1},
  154013. {&_44u5__p9_0,&_44u5__p9_1,&_44u5__p9_2}
  154014. }
  154015. };
  154016. static static_bookblock _resbook_44u_6={
  154017. {
  154018. {0},
  154019. {0,0,&_44u6__p1_0},
  154020. {0,0,&_44u6__p2_0},
  154021. {0,0,&_44u6__p3_0},
  154022. {0,0,&_44u6__p4_0},
  154023. {0,0,&_44u6__p5_0},
  154024. {0,0,&_44u6__p6_0},
  154025. {&_44u6__p7_0,&_44u6__p7_1},
  154026. {&_44u6__p8_0,&_44u6__p8_1},
  154027. {&_44u6__p9_0,&_44u6__p9_1,&_44u6__p9_2}
  154028. }
  154029. };
  154030. static static_bookblock _resbook_44u_7={
  154031. {
  154032. {0},
  154033. {0,0,&_44u7__p1_0},
  154034. {0,0,&_44u7__p2_0},
  154035. {0,0,&_44u7__p3_0},
  154036. {0,0,&_44u7__p4_0},
  154037. {0,0,&_44u7__p5_0},
  154038. {0,0,&_44u7__p6_0},
  154039. {&_44u7__p7_0,&_44u7__p7_1},
  154040. {&_44u7__p8_0,&_44u7__p8_1},
  154041. {&_44u7__p9_0,&_44u7__p9_1,&_44u7__p9_2}
  154042. }
  154043. };
  154044. static static_bookblock _resbook_44u_8={
  154045. {
  154046. {0},
  154047. {0,0,&_44u8_p1_0},
  154048. {0,0,&_44u8_p2_0},
  154049. {0,0,&_44u8_p3_0},
  154050. {0,0,&_44u8_p4_0},
  154051. {&_44u8_p5_0,&_44u8_p5_1},
  154052. {&_44u8_p6_0,&_44u8_p6_1},
  154053. {&_44u8_p7_0,&_44u8_p7_1},
  154054. {&_44u8_p8_0,&_44u8_p8_1},
  154055. {&_44u8_p9_0,&_44u8_p9_1,&_44u8_p9_2}
  154056. }
  154057. };
  154058. static static_bookblock _resbook_44u_9={
  154059. {
  154060. {0},
  154061. {0,0,&_44u9_p1_0},
  154062. {0,0,&_44u9_p2_0},
  154063. {0,0,&_44u9_p3_0},
  154064. {0,0,&_44u9_p4_0},
  154065. {&_44u9_p5_0,&_44u9_p5_1},
  154066. {&_44u9_p6_0,&_44u9_p6_1},
  154067. {&_44u9_p7_0,&_44u9_p7_1},
  154068. {&_44u9_p8_0,&_44u9_p8_1},
  154069. {&_44u9_p9_0,&_44u9_p9_1,&_44u9_p9_2}
  154070. }
  154071. };
  154072. static vorbis_residue_template _res_44u_n1[]={
  154073. {1,0, &_residue_44_low_un,
  154074. &_huff_book__44un1__short,&_huff_book__44un1__short,
  154075. &_resbook_44u_n1,&_resbook_44u_n1},
  154076. {1,0, &_residue_44_low_un,
  154077. &_huff_book__44un1__long,&_huff_book__44un1__long,
  154078. &_resbook_44u_n1,&_resbook_44u_n1}
  154079. };
  154080. static vorbis_residue_template _res_44u_0[]={
  154081. {1,0, &_residue_44_low_un,
  154082. &_huff_book__44u0__short,&_huff_book__44u0__short,
  154083. &_resbook_44u_0,&_resbook_44u_0},
  154084. {1,0, &_residue_44_low_un,
  154085. &_huff_book__44u0__long,&_huff_book__44u0__long,
  154086. &_resbook_44u_0,&_resbook_44u_0}
  154087. };
  154088. static vorbis_residue_template _res_44u_1[]={
  154089. {1,0, &_residue_44_low_un,
  154090. &_huff_book__44u1__short,&_huff_book__44u1__short,
  154091. &_resbook_44u_1,&_resbook_44u_1},
  154092. {1,0, &_residue_44_low_un,
  154093. &_huff_book__44u1__long,&_huff_book__44u1__long,
  154094. &_resbook_44u_1,&_resbook_44u_1}
  154095. };
  154096. static vorbis_residue_template _res_44u_2[]={
  154097. {1,0, &_residue_44_low_un,
  154098. &_huff_book__44u2__short,&_huff_book__44u2__short,
  154099. &_resbook_44u_2,&_resbook_44u_2},
  154100. {1,0, &_residue_44_low_un,
  154101. &_huff_book__44u2__long,&_huff_book__44u2__long,
  154102. &_resbook_44u_2,&_resbook_44u_2}
  154103. };
  154104. static vorbis_residue_template _res_44u_3[]={
  154105. {1,0, &_residue_44_low_un,
  154106. &_huff_book__44u3__short,&_huff_book__44u3__short,
  154107. &_resbook_44u_3,&_resbook_44u_3},
  154108. {1,0, &_residue_44_low_un,
  154109. &_huff_book__44u3__long,&_huff_book__44u3__long,
  154110. &_resbook_44u_3,&_resbook_44u_3}
  154111. };
  154112. static vorbis_residue_template _res_44u_4[]={
  154113. {1,0, &_residue_44_low_un,
  154114. &_huff_book__44u4__short,&_huff_book__44u4__short,
  154115. &_resbook_44u_4,&_resbook_44u_4},
  154116. {1,0, &_residue_44_low_un,
  154117. &_huff_book__44u4__long,&_huff_book__44u4__long,
  154118. &_resbook_44u_4,&_resbook_44u_4}
  154119. };
  154120. static vorbis_residue_template _res_44u_5[]={
  154121. {1,0, &_residue_44_mid_un,
  154122. &_huff_book__44u5__short,&_huff_book__44u5__short,
  154123. &_resbook_44u_5,&_resbook_44u_5},
  154124. {1,0, &_residue_44_mid_un,
  154125. &_huff_book__44u5__long,&_huff_book__44u5__long,
  154126. &_resbook_44u_5,&_resbook_44u_5}
  154127. };
  154128. static vorbis_residue_template _res_44u_6[]={
  154129. {1,0, &_residue_44_mid_un,
  154130. &_huff_book__44u6__short,&_huff_book__44u6__short,
  154131. &_resbook_44u_6,&_resbook_44u_6},
  154132. {1,0, &_residue_44_mid_un,
  154133. &_huff_book__44u6__long,&_huff_book__44u6__long,
  154134. &_resbook_44u_6,&_resbook_44u_6}
  154135. };
  154136. static vorbis_residue_template _res_44u_7[]={
  154137. {1,0, &_residue_44_mid_un,
  154138. &_huff_book__44u7__short,&_huff_book__44u7__short,
  154139. &_resbook_44u_7,&_resbook_44u_7},
  154140. {1,0, &_residue_44_mid_un,
  154141. &_huff_book__44u7__long,&_huff_book__44u7__long,
  154142. &_resbook_44u_7,&_resbook_44u_7}
  154143. };
  154144. static vorbis_residue_template _res_44u_8[]={
  154145. {1,0, &_residue_44_hi_un,
  154146. &_huff_book__44u8__short,&_huff_book__44u8__short,
  154147. &_resbook_44u_8,&_resbook_44u_8},
  154148. {1,0, &_residue_44_hi_un,
  154149. &_huff_book__44u8__long,&_huff_book__44u8__long,
  154150. &_resbook_44u_8,&_resbook_44u_8}
  154151. };
  154152. static vorbis_residue_template _res_44u_9[]={
  154153. {1,0, &_residue_44_hi_un,
  154154. &_huff_book__44u9__short,&_huff_book__44u9__short,
  154155. &_resbook_44u_9,&_resbook_44u_9},
  154156. {1,0, &_residue_44_hi_un,
  154157. &_huff_book__44u9__long,&_huff_book__44u9__long,
  154158. &_resbook_44u_9,&_resbook_44u_9}
  154159. };
  154160. static vorbis_mapping_template _mapres_template_44_uncoupled[]={
  154161. { _map_nominal_u, _res_44u_n1 }, /* -1 */
  154162. { _map_nominal_u, _res_44u_0 }, /* 0 */
  154163. { _map_nominal_u, _res_44u_1 }, /* 1 */
  154164. { _map_nominal_u, _res_44u_2 }, /* 2 */
  154165. { _map_nominal_u, _res_44u_3 }, /* 3 */
  154166. { _map_nominal_u, _res_44u_4 }, /* 4 */
  154167. { _map_nominal_u, _res_44u_5 }, /* 5 */
  154168. { _map_nominal_u, _res_44u_6 }, /* 6 */
  154169. { _map_nominal_u, _res_44u_7 }, /* 7 */
  154170. { _map_nominal_u, _res_44u_8 }, /* 8 */
  154171. { _map_nominal_u, _res_44u_9 }, /* 9 */
  154172. };
  154173. /********* End of inlined file: residue_44u.h *********/
  154174. static double rate_mapping_44_un[12]={
  154175. 32000.,48000.,60000.,70000.,80000.,86000.,
  154176. 96000.,110000.,120000.,140000.,160000.,240001.
  154177. };
  154178. ve_setup_data_template ve_setup_44_uncoupled={
  154179. 11,
  154180. rate_mapping_44_un,
  154181. quality_mapping_44,
  154182. -1,
  154183. 40000,
  154184. 50000,
  154185. blocksize_short_44,
  154186. blocksize_long_44,
  154187. _psy_tone_masteratt_44,
  154188. _psy_tone_0dB,
  154189. _psy_tone_suppress,
  154190. _vp_tonemask_adj_otherblock,
  154191. _vp_tonemask_adj_longblock,
  154192. _vp_tonemask_adj_otherblock,
  154193. _psy_noiseguards_44,
  154194. _psy_noisebias_impulse,
  154195. _psy_noisebias_padding,
  154196. _psy_noisebias_trans,
  154197. _psy_noisebias_long,
  154198. _psy_noise_suppress,
  154199. _psy_compand_44,
  154200. _psy_compand_short_mapping,
  154201. _psy_compand_long_mapping,
  154202. {_noise_start_short_44,_noise_start_long_44},
  154203. {_noise_part_short_44,_noise_part_long_44},
  154204. _noise_thresh_44,
  154205. _psy_ath_floater,
  154206. _psy_ath_abs,
  154207. _psy_lowpass_44,
  154208. _psy_global_44,
  154209. _global_mapping_44,
  154210. NULL,
  154211. _floor_books,
  154212. _floor,
  154213. _floor_short_mapping_44,
  154214. _floor_long_mapping_44,
  154215. _mapres_template_44_uncoupled
  154216. };
  154217. /********* End of inlined file: setup_44u.h *********/
  154218. /********* Start of inlined file: setup_32.h *********/
  154219. static double rate_mapping_32[12]={
  154220. 18000.,28000.,35000.,45000.,56000.,60000.,
  154221. 75000.,90000.,100000.,115000.,150000.,190000.,
  154222. };
  154223. static double rate_mapping_32_un[12]={
  154224. 30000.,42000.,52000.,64000.,72000.,78000.,
  154225. 86000.,92000.,110000.,120000.,140000.,190000.,
  154226. };
  154227. static double _psy_lowpass_32[12]={
  154228. 12.3,13.,13.,14.,15.,99.,99.,99.,99.,99.,99.,99.
  154229. };
  154230. ve_setup_data_template ve_setup_32_stereo={
  154231. 11,
  154232. rate_mapping_32,
  154233. quality_mapping_44,
  154234. 2,
  154235. 26000,
  154236. 40000,
  154237. blocksize_short_44,
  154238. blocksize_long_44,
  154239. _psy_tone_masteratt_44,
  154240. _psy_tone_0dB,
  154241. _psy_tone_suppress,
  154242. _vp_tonemask_adj_otherblock,
  154243. _vp_tonemask_adj_longblock,
  154244. _vp_tonemask_adj_otherblock,
  154245. _psy_noiseguards_44,
  154246. _psy_noisebias_impulse,
  154247. _psy_noisebias_padding,
  154248. _psy_noisebias_trans,
  154249. _psy_noisebias_long,
  154250. _psy_noise_suppress,
  154251. _psy_compand_44,
  154252. _psy_compand_short_mapping,
  154253. _psy_compand_long_mapping,
  154254. {_noise_start_short_44,_noise_start_long_44},
  154255. {_noise_part_short_44,_noise_part_long_44},
  154256. _noise_thresh_44,
  154257. _psy_ath_floater,
  154258. _psy_ath_abs,
  154259. _psy_lowpass_32,
  154260. _psy_global_44,
  154261. _global_mapping_44,
  154262. _psy_stereo_modes_44,
  154263. _floor_books,
  154264. _floor,
  154265. _floor_short_mapping_44,
  154266. _floor_long_mapping_44,
  154267. _mapres_template_44_stereo
  154268. };
  154269. ve_setup_data_template ve_setup_32_uncoupled={
  154270. 11,
  154271. rate_mapping_32_un,
  154272. quality_mapping_44,
  154273. -1,
  154274. 26000,
  154275. 40000,
  154276. blocksize_short_44,
  154277. blocksize_long_44,
  154278. _psy_tone_masteratt_44,
  154279. _psy_tone_0dB,
  154280. _psy_tone_suppress,
  154281. _vp_tonemask_adj_otherblock,
  154282. _vp_tonemask_adj_longblock,
  154283. _vp_tonemask_adj_otherblock,
  154284. _psy_noiseguards_44,
  154285. _psy_noisebias_impulse,
  154286. _psy_noisebias_padding,
  154287. _psy_noisebias_trans,
  154288. _psy_noisebias_long,
  154289. _psy_noise_suppress,
  154290. _psy_compand_44,
  154291. _psy_compand_short_mapping,
  154292. _psy_compand_long_mapping,
  154293. {_noise_start_short_44,_noise_start_long_44},
  154294. {_noise_part_short_44,_noise_part_long_44},
  154295. _noise_thresh_44,
  154296. _psy_ath_floater,
  154297. _psy_ath_abs,
  154298. _psy_lowpass_32,
  154299. _psy_global_44,
  154300. _global_mapping_44,
  154301. NULL,
  154302. _floor_books,
  154303. _floor,
  154304. _floor_short_mapping_44,
  154305. _floor_long_mapping_44,
  154306. _mapres_template_44_uncoupled
  154307. };
  154308. /********* End of inlined file: setup_32.h *********/
  154309. /********* Start of inlined file: setup_8.h *********/
  154310. /********* Start of inlined file: psych_8.h *********/
  154311. static att3 _psy_tone_masteratt_8[3]={
  154312. {{ 32, 25, 12}, 0, 0}, /* 0 */
  154313. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154314. {{ 20, 0, -14}, 0, 0}, /* 0 */
  154315. };
  154316. static vp_adjblock _vp_tonemask_adj_8[3]={
  154317. /* adjust for mode zero */
  154318. /* 63 125 250 500 1 2 4 8 16 */
  154319. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  154320. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0,10, 0, 0,99,99,99}}, /* 1 */
  154321. {{-15,-15,-15,-15,-10,-10, -6, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 1 */
  154322. };
  154323. static noise3 _psy_noisebias_8[3]={
  154324. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154325. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  154326. {-10,-10,-10,-10, -5, -5, -5, 0, 0, 4, 4, 4, 4, 4, 99, 99, 99},
  154327. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154328. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 8, 8, 8, 10, 10, 99, 99, 99},
  154329. {-10,-10,-10,-10,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  154330. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154331. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  154332. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  154333. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  154334. };
  154335. /* stereo mode by base quality level */
  154336. static adj_stereo _psy_stereo_modes_8[3]={
  154337. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154338. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154339. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154340. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  154341. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154342. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154343. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154344. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  154345. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154346. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154347. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154348. { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1},
  154349. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154350. };
  154351. static noiseguard _psy_noiseguards_8[2]={
  154352. {10,10,-1},
  154353. {10,10,-1},
  154354. };
  154355. static compandblock _psy_compand_8[2]={
  154356. {{
  154357. 0, 1, 2, 3, 4, 5, 6, 7, /* 7dB */
  154358. 8, 8, 9, 9,10,10,11, 11, /* 15dB */
  154359. 12,12,13,13,14,14,15, 15, /* 23dB */
  154360. 16,16,17,17,17,18,18, 19, /* 31dB */
  154361. 19,19,20,21,22,23,24, 25, /* 39dB */
  154362. }},
  154363. {{
  154364. 0, 1, 2, 3, 4, 5, 6, 6, /* 7dB */
  154365. 7, 7, 6, 6, 5, 5, 4, 4, /* 15dB */
  154366. 3, 3, 3, 4, 5, 6, 7, 8, /* 23dB */
  154367. 9,10,11,12,13,14,15, 16, /* 31dB */
  154368. 17,18,19,20,21,22,23, 24, /* 39dB */
  154369. }},
  154370. };
  154371. static double _psy_lowpass_8[3]={3.,4.,4.};
  154372. static int _noise_start_8[2]={
  154373. 64,64,
  154374. };
  154375. static int _noise_part_8[2]={
  154376. 8,8,
  154377. };
  154378. static int _psy_ath_floater_8[3]={
  154379. -100,-100,-105,
  154380. };
  154381. static int _psy_ath_abs_8[3]={
  154382. -130,-130,-140,
  154383. };
  154384. /********* End of inlined file: psych_8.h *********/
  154385. /********* Start of inlined file: residue_8.h *********/
  154386. /***** residue backends *********************************************/
  154387. static static_bookblock _resbook_8s_0={
  154388. {
  154389. {0},{0,0,&_8c0_s_p1_0},{0,0,&_8c0_s_p2_0},{0,0,&_8c0_s_p3_0},
  154390. {0,0,&_8c0_s_p4_0},{0,0,&_8c0_s_p5_0},{0,0,&_8c0_s_p6_0},
  154391. {&_8c0_s_p7_0,&_8c0_s_p7_1},{&_8c0_s_p8_0,&_8c0_s_p8_1},
  154392. {&_8c0_s_p9_0,&_8c0_s_p9_1,&_8c0_s_p9_2}
  154393. }
  154394. };
  154395. static static_bookblock _resbook_8s_1={
  154396. {
  154397. {0},{0,0,&_8c1_s_p1_0},{0,0,&_8c1_s_p2_0},{0,0,&_8c1_s_p3_0},
  154398. {0,0,&_8c1_s_p4_0},{0,0,&_8c1_s_p5_0},{0,0,&_8c1_s_p6_0},
  154399. {&_8c1_s_p7_0,&_8c1_s_p7_1},{&_8c1_s_p8_0,&_8c1_s_p8_1},
  154400. {&_8c1_s_p9_0,&_8c1_s_p9_1,&_8c1_s_p9_2}
  154401. }
  154402. };
  154403. static vorbis_residue_template _res_8s_0[]={
  154404. {2,0, &_residue_44_mid,
  154405. &_huff_book__8c0_s_single,&_huff_book__8c0_s_single,
  154406. &_resbook_8s_0,&_resbook_8s_0},
  154407. };
  154408. static vorbis_residue_template _res_8s_1[]={
  154409. {2,0, &_residue_44_mid,
  154410. &_huff_book__8c1_s_single,&_huff_book__8c1_s_single,
  154411. &_resbook_8s_1,&_resbook_8s_1},
  154412. };
  154413. static vorbis_mapping_template _mapres_template_8_stereo[2]={
  154414. { _map_nominal, _res_8s_0 }, /* 0 */
  154415. { _map_nominal, _res_8s_1 }, /* 1 */
  154416. };
  154417. static static_bookblock _resbook_8u_0={
  154418. {
  154419. {0},
  154420. {0,0,&_8u0__p1_0},
  154421. {0,0,&_8u0__p2_0},
  154422. {0,0,&_8u0__p3_0},
  154423. {0,0,&_8u0__p4_0},
  154424. {0,0,&_8u0__p5_0},
  154425. {&_8u0__p6_0,&_8u0__p6_1},
  154426. {&_8u0__p7_0,&_8u0__p7_1,&_8u0__p7_2}
  154427. }
  154428. };
  154429. static static_bookblock _resbook_8u_1={
  154430. {
  154431. {0},
  154432. {0,0,&_8u1__p1_0},
  154433. {0,0,&_8u1__p2_0},
  154434. {0,0,&_8u1__p3_0},
  154435. {0,0,&_8u1__p4_0},
  154436. {0,0,&_8u1__p5_0},
  154437. {0,0,&_8u1__p6_0},
  154438. {&_8u1__p7_0,&_8u1__p7_1},
  154439. {&_8u1__p8_0,&_8u1__p8_1},
  154440. {&_8u1__p9_0,&_8u1__p9_1,&_8u1__p9_2}
  154441. }
  154442. };
  154443. static vorbis_residue_template _res_8u_0[]={
  154444. {1,0, &_residue_44_low_un,
  154445. &_huff_book__8u0__single,&_huff_book__8u0__single,
  154446. &_resbook_8u_0,&_resbook_8u_0},
  154447. };
  154448. static vorbis_residue_template _res_8u_1[]={
  154449. {1,0, &_residue_44_mid_un,
  154450. &_huff_book__8u1__single,&_huff_book__8u1__single,
  154451. &_resbook_8u_1,&_resbook_8u_1},
  154452. };
  154453. static vorbis_mapping_template _mapres_template_8_uncoupled[2]={
  154454. { _map_nominal_u, _res_8u_0 }, /* 0 */
  154455. { _map_nominal_u, _res_8u_1 }, /* 1 */
  154456. };
  154457. /********* End of inlined file: residue_8.h *********/
  154458. static int blocksize_8[2]={
  154459. 512,512
  154460. };
  154461. static int _floor_mapping_8[2]={
  154462. 6,6,
  154463. };
  154464. static double rate_mapping_8[3]={
  154465. 6000.,9000.,32000.,
  154466. };
  154467. static double rate_mapping_8_uncoupled[3]={
  154468. 8000.,14000.,42000.,
  154469. };
  154470. static double quality_mapping_8[3]={
  154471. -.1,.0,1.
  154472. };
  154473. static double _psy_compand_8_mapping[3]={ 0., 1., 1.};
  154474. static double _global_mapping_8[3]={ 1., 2., 3. };
  154475. ve_setup_data_template ve_setup_8_stereo={
  154476. 2,
  154477. rate_mapping_8,
  154478. quality_mapping_8,
  154479. 2,
  154480. 8000,
  154481. 9000,
  154482. blocksize_8,
  154483. blocksize_8,
  154484. _psy_tone_masteratt_8,
  154485. _psy_tone_0dB,
  154486. _psy_tone_suppress,
  154487. _vp_tonemask_adj_8,
  154488. NULL,
  154489. _vp_tonemask_adj_8,
  154490. _psy_noiseguards_8,
  154491. _psy_noisebias_8,
  154492. _psy_noisebias_8,
  154493. NULL,
  154494. NULL,
  154495. _psy_noise_suppress,
  154496. _psy_compand_8,
  154497. _psy_compand_8_mapping,
  154498. NULL,
  154499. {_noise_start_8,_noise_start_8},
  154500. {_noise_part_8,_noise_part_8},
  154501. _noise_thresh_5only,
  154502. _psy_ath_floater_8,
  154503. _psy_ath_abs_8,
  154504. _psy_lowpass_8,
  154505. _psy_global_44,
  154506. _global_mapping_8,
  154507. _psy_stereo_modes_8,
  154508. _floor_books,
  154509. _floor,
  154510. _floor_mapping_8,
  154511. NULL,
  154512. _mapres_template_8_stereo
  154513. };
  154514. ve_setup_data_template ve_setup_8_uncoupled={
  154515. 2,
  154516. rate_mapping_8_uncoupled,
  154517. quality_mapping_8,
  154518. -1,
  154519. 8000,
  154520. 9000,
  154521. blocksize_8,
  154522. blocksize_8,
  154523. _psy_tone_masteratt_8,
  154524. _psy_tone_0dB,
  154525. _psy_tone_suppress,
  154526. _vp_tonemask_adj_8,
  154527. NULL,
  154528. _vp_tonemask_adj_8,
  154529. _psy_noiseguards_8,
  154530. _psy_noisebias_8,
  154531. _psy_noisebias_8,
  154532. NULL,
  154533. NULL,
  154534. _psy_noise_suppress,
  154535. _psy_compand_8,
  154536. _psy_compand_8_mapping,
  154537. NULL,
  154538. {_noise_start_8,_noise_start_8},
  154539. {_noise_part_8,_noise_part_8},
  154540. _noise_thresh_5only,
  154541. _psy_ath_floater_8,
  154542. _psy_ath_abs_8,
  154543. _psy_lowpass_8,
  154544. _psy_global_44,
  154545. _global_mapping_8,
  154546. _psy_stereo_modes_8,
  154547. _floor_books,
  154548. _floor,
  154549. _floor_mapping_8,
  154550. NULL,
  154551. _mapres_template_8_uncoupled
  154552. };
  154553. /********* End of inlined file: setup_8.h *********/
  154554. /********* Start of inlined file: setup_11.h *********/
  154555. /********* Start of inlined file: psych_11.h *********/
  154556. static double _psy_lowpass_11[3]={4.5,5.5,30.,};
  154557. static att3 _psy_tone_masteratt_11[3]={
  154558. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154559. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154560. {{ 20, 0, -14}, 0, 0}, /* 0 */
  154561. };
  154562. static vp_adjblock _vp_tonemask_adj_11[3]={
  154563. /* adjust for mode zero */
  154564. /* 63 125 250 500 1 2 4 8 16 */
  154565. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 2, 0,99,99,99}}, /* 0 */
  154566. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 5, 0, 0,99,99,99}}, /* 1 */
  154567. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0,99,99,99}}, /* 2 */
  154568. };
  154569. static noise3 _psy_noisebias_11[3]={
  154570. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154571. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154572. {-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 4, 5, 5, 10, 99, 99, 99},
  154573. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154574. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 10, 10, 12, 12, 12, 99, 99, 99},
  154575. {-15,-15,-15,-15,-10,-10, -5, -5, -5, 0, 0, 0, 0, 0, 99, 99, 99},
  154576. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, 99, 99, 99}}},
  154577. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 99, 99, 99},
  154578. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10, 99, 99, 99},
  154579. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24, 99, 99, 99}}},
  154580. };
  154581. static double _noise_thresh_11[3]={ .3,.5,.5 };
  154582. /********* End of inlined file: psych_11.h *********/
  154583. static int blocksize_11[2]={
  154584. 512,512
  154585. };
  154586. static int _floor_mapping_11[2]={
  154587. 6,6,
  154588. };
  154589. static double rate_mapping_11[3]={
  154590. 8000.,13000.,44000.,
  154591. };
  154592. static double rate_mapping_11_uncoupled[3]={
  154593. 12000.,20000.,50000.,
  154594. };
  154595. static double quality_mapping_11[3]={
  154596. -.1,.0,1.
  154597. };
  154598. ve_setup_data_template ve_setup_11_stereo={
  154599. 2,
  154600. rate_mapping_11,
  154601. quality_mapping_11,
  154602. 2,
  154603. 9000,
  154604. 15000,
  154605. blocksize_11,
  154606. blocksize_11,
  154607. _psy_tone_masteratt_11,
  154608. _psy_tone_0dB,
  154609. _psy_tone_suppress,
  154610. _vp_tonemask_adj_11,
  154611. NULL,
  154612. _vp_tonemask_adj_11,
  154613. _psy_noiseguards_8,
  154614. _psy_noisebias_11,
  154615. _psy_noisebias_11,
  154616. NULL,
  154617. NULL,
  154618. _psy_noise_suppress,
  154619. _psy_compand_8,
  154620. _psy_compand_8_mapping,
  154621. NULL,
  154622. {_noise_start_8,_noise_start_8},
  154623. {_noise_part_8,_noise_part_8},
  154624. _noise_thresh_11,
  154625. _psy_ath_floater_8,
  154626. _psy_ath_abs_8,
  154627. _psy_lowpass_11,
  154628. _psy_global_44,
  154629. _global_mapping_8,
  154630. _psy_stereo_modes_8,
  154631. _floor_books,
  154632. _floor,
  154633. _floor_mapping_11,
  154634. NULL,
  154635. _mapres_template_8_stereo
  154636. };
  154637. ve_setup_data_template ve_setup_11_uncoupled={
  154638. 2,
  154639. rate_mapping_11_uncoupled,
  154640. quality_mapping_11,
  154641. -1,
  154642. 9000,
  154643. 15000,
  154644. blocksize_11,
  154645. blocksize_11,
  154646. _psy_tone_masteratt_11,
  154647. _psy_tone_0dB,
  154648. _psy_tone_suppress,
  154649. _vp_tonemask_adj_11,
  154650. NULL,
  154651. _vp_tonemask_adj_11,
  154652. _psy_noiseguards_8,
  154653. _psy_noisebias_11,
  154654. _psy_noisebias_11,
  154655. NULL,
  154656. NULL,
  154657. _psy_noise_suppress,
  154658. _psy_compand_8,
  154659. _psy_compand_8_mapping,
  154660. NULL,
  154661. {_noise_start_8,_noise_start_8},
  154662. {_noise_part_8,_noise_part_8},
  154663. _noise_thresh_11,
  154664. _psy_ath_floater_8,
  154665. _psy_ath_abs_8,
  154666. _psy_lowpass_11,
  154667. _psy_global_44,
  154668. _global_mapping_8,
  154669. _psy_stereo_modes_8,
  154670. _floor_books,
  154671. _floor,
  154672. _floor_mapping_11,
  154673. NULL,
  154674. _mapres_template_8_uncoupled
  154675. };
  154676. /********* End of inlined file: setup_11.h *********/
  154677. /********* Start of inlined file: setup_16.h *********/
  154678. /********* Start of inlined file: psych_16.h *********/
  154679. /* stereo mode by base quality level */
  154680. static adj_stereo _psy_stereo_modes_16[4]={
  154681. /* 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 */
  154682. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154683. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154684. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 4, 4},
  154685. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154686. {{ 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154687. { 6, 5, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154688. { 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 4, 4, 4, 4},
  154689. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154690. {{ 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154691. { 5, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3},
  154692. { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
  154693. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154694. {{ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154695. { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0},
  154696. { 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8},
  154697. { 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99, 99}},
  154698. };
  154699. static double _psy_lowpass_16[4]={6.5,8,30.,99.};
  154700. static att3 _psy_tone_masteratt_16[4]={
  154701. {{ 30, 25, 12}, 0, 0}, /* 0 */
  154702. {{ 25, 22, 12}, 0, 0}, /* 0 */
  154703. {{ 20, 12, 0}, 0, 0}, /* 0 */
  154704. {{ 15, 0, -14}, 0, 0}, /* 0 */
  154705. };
  154706. static vp_adjblock _vp_tonemask_adj_16[4]={
  154707. /* adjust for mode zero */
  154708. /* 63 125 250 500 1 2 4 8 16 */
  154709. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 0 */
  154710. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0,10, 0, 0, 0, 0, 0}}, /* 1 */
  154711. {{-20,-20,-20,-20,-20,-16,-10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154712. {{-30,-30,-30,-30,-30,-26,-20,-10, -5, 0, 0, 0, 0, 0, 0, 0, 0}}, /* 2 */
  154713. };
  154714. static noise3 _psy_noisebias_16_short[4]={
  154715. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154716. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154717. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154718. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154719. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154720. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 4, 5, 6, 8, 8, 15},
  154721. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154722. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154723. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10, -8, 0, 0, 0, 0, 2, 5},
  154724. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154725. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154726. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154727. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154728. };
  154729. static noise3 _psy_noisebias_16_impulse[4]={
  154730. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154731. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 10, 10, 10, 10, 12, 12, 14, 20},
  154732. {-15,-15,-15,-15,-15,-10,-10, -5, 0, 0, 4, 5, 5, 6, 8, 8, 15},
  154733. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154734. {{{-15,-15,-15,-15,-15,-10,-10,-5, 4, 4, 4, 4, 5, 5, 6, 8, 15},
  154735. {-15,-15,-15,-15,-15,-15,-15,-10, -5, -5, -5, 0, 0, 0, 0, 4, 10},
  154736. {-30,-30,-30,-30,-30,-24,-20,-14,-10,-10,-10,-10,-10,-10,-10,-10,-10}}},
  154737. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 0, 0, 0, 0, 0, 0, 4, 10},
  154738. {-20,-20,-20,-20,-16,-12,-20,-14,-10,-10,-10,-10,-10,-10,-10, -7, -5},
  154739. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154740. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154741. {-30,-30,-30,-30,-26,-22,-20,-18,-18,-18,-20,-20,-20,-20,-20,-20,-16},
  154742. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154743. };
  154744. static noise3 _psy_noisebias_16[4]={
  154745. /* 63 125 250 500 1k 2k 4k 8k 16k*/
  154746. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 8, 8, 10, 10, 10, 14, 20},
  154747. {-10,-10,-10,-10,-10, -5, -2, -2, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154748. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154749. {{{-10,-10,-10,-10, -5, -5, -5, 0, 4, 6, 6, 6, 6, 8, 10, 12, 20},
  154750. {-15,-15,-15,-15,-15,-10, -5, -5, 0, 0, 0, 4, 5, 6, 8, 8, 15},
  154751. {-30,-30,-30,-30,-30,-24,-20,-14,-10, -6, -8, -8, -6, -6, -6, -6, -6}}},
  154752. {{{-15,-15,-15,-15,-15,-12,-10, -8, 0, 2, 4, 4, 5, 5, 5, 8, 12},
  154753. {-20,-20,-20,-20,-16,-12,-20,-10, -5, -5, 0, 0, 0, 0, 0, 2, 5},
  154754. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154755. {{{-15,-15,-15,-15,-15,-12,-10, -8, -5, -5, -5, -5, -5, 0, 0, 0, 6},
  154756. {-30,-30,-30,-30,-26,-22,-20,-14,-12,-12,-10,-10,-10,-10,-10,-10, -6},
  154757. {-30,-30,-30,-30,-26,-26,-26,-26,-26,-26,-26,-26,-26,-24,-20,-20,-20}}},
  154758. };
  154759. static double _noise_thresh_16[4]={ .3,.5,.5,.5 };
  154760. static int _noise_start_16[3]={ 256,256,9999 };
  154761. static int _noise_part_16[4]={ 8,8,8,8 };
  154762. static int _psy_ath_floater_16[4]={
  154763. -100,-100,-100,-105,
  154764. };
  154765. static int _psy_ath_abs_16[4]={
  154766. -130,-130,-130,-140,
  154767. };
  154768. /********* End of inlined file: psych_16.h *********/
  154769. /********* Start of inlined file: residue_16.h *********/
  154770. /***** residue backends *********************************************/
  154771. static static_bookblock _resbook_16s_0={
  154772. {
  154773. {0},
  154774. {0,0,&_16c0_s_p1_0},
  154775. {0,0,&_16c0_s_p2_0},
  154776. {0,0,&_16c0_s_p3_0},
  154777. {0,0,&_16c0_s_p4_0},
  154778. {0,0,&_16c0_s_p5_0},
  154779. {0,0,&_16c0_s_p6_0},
  154780. {&_16c0_s_p7_0,&_16c0_s_p7_1},
  154781. {&_16c0_s_p8_0,&_16c0_s_p8_1},
  154782. {&_16c0_s_p9_0,&_16c0_s_p9_1,&_16c0_s_p9_2}
  154783. }
  154784. };
  154785. static static_bookblock _resbook_16s_1={
  154786. {
  154787. {0},
  154788. {0,0,&_16c1_s_p1_0},
  154789. {0,0,&_16c1_s_p2_0},
  154790. {0,0,&_16c1_s_p3_0},
  154791. {0,0,&_16c1_s_p4_0},
  154792. {0,0,&_16c1_s_p5_0},
  154793. {0,0,&_16c1_s_p6_0},
  154794. {&_16c1_s_p7_0,&_16c1_s_p7_1},
  154795. {&_16c1_s_p8_0,&_16c1_s_p8_1},
  154796. {&_16c1_s_p9_0,&_16c1_s_p9_1,&_16c1_s_p9_2}
  154797. }
  154798. };
  154799. static static_bookblock _resbook_16s_2={
  154800. {
  154801. {0},
  154802. {0,0,&_16c2_s_p1_0},
  154803. {0,0,&_16c2_s_p2_0},
  154804. {0,0,&_16c2_s_p3_0},
  154805. {0,0,&_16c2_s_p4_0},
  154806. {&_16c2_s_p5_0,&_16c2_s_p5_1},
  154807. {&_16c2_s_p6_0,&_16c2_s_p6_1},
  154808. {&_16c2_s_p7_0,&_16c2_s_p7_1},
  154809. {&_16c2_s_p8_0,&_16c2_s_p8_1},
  154810. {&_16c2_s_p9_0,&_16c2_s_p9_1,&_16c2_s_p9_2}
  154811. }
  154812. };
  154813. static vorbis_residue_template _res_16s_0[]={
  154814. {2,0, &_residue_44_mid,
  154815. &_huff_book__16c0_s_single,&_huff_book__16c0_s_single,
  154816. &_resbook_16s_0,&_resbook_16s_0},
  154817. };
  154818. static vorbis_residue_template _res_16s_1[]={
  154819. {2,0, &_residue_44_mid,
  154820. &_huff_book__16c1_s_short,&_huff_book__16c1_s_short,
  154821. &_resbook_16s_1,&_resbook_16s_1},
  154822. {2,0, &_residue_44_mid,
  154823. &_huff_book__16c1_s_long,&_huff_book__16c1_s_long,
  154824. &_resbook_16s_1,&_resbook_16s_1}
  154825. };
  154826. static vorbis_residue_template _res_16s_2[]={
  154827. {2,0, &_residue_44_high,
  154828. &_huff_book__16c2_s_short,&_huff_book__16c2_s_short,
  154829. &_resbook_16s_2,&_resbook_16s_2},
  154830. {2,0, &_residue_44_high,
  154831. &_huff_book__16c2_s_long,&_huff_book__16c2_s_long,
  154832. &_resbook_16s_2,&_resbook_16s_2}
  154833. };
  154834. static vorbis_mapping_template _mapres_template_16_stereo[3]={
  154835. { _map_nominal, _res_16s_0 }, /* 0 */
  154836. { _map_nominal, _res_16s_1 }, /* 1 */
  154837. { _map_nominal, _res_16s_2 }, /* 2 */
  154838. };
  154839. static static_bookblock _resbook_16u_0={
  154840. {
  154841. {0},
  154842. {0,0,&_16u0__p1_0},
  154843. {0,0,&_16u0__p2_0},
  154844. {0,0,&_16u0__p3_0},
  154845. {0,0,&_16u0__p4_0},
  154846. {0,0,&_16u0__p5_0},
  154847. {&_16u0__p6_0,&_16u0__p6_1},
  154848. {&_16u0__p7_0,&_16u0__p7_1,&_16u0__p7_2}
  154849. }
  154850. };
  154851. static static_bookblock _resbook_16u_1={
  154852. {
  154853. {0},
  154854. {0,0,&_16u1__p1_0},
  154855. {0,0,&_16u1__p2_0},
  154856. {0,0,&_16u1__p3_0},
  154857. {0,0,&_16u1__p4_0},
  154858. {0,0,&_16u1__p5_0},
  154859. {0,0,&_16u1__p6_0},
  154860. {&_16u1__p7_0,&_16u1__p7_1},
  154861. {&_16u1__p8_0,&_16u1__p8_1},
  154862. {&_16u1__p9_0,&_16u1__p9_1,&_16u1__p9_2}
  154863. }
  154864. };
  154865. static static_bookblock _resbook_16u_2={
  154866. {
  154867. {0},
  154868. {0,0,&_16u2_p1_0},
  154869. {0,0,&_16u2_p2_0},
  154870. {0,0,&_16u2_p3_0},
  154871. {0,0,&_16u2_p4_0},
  154872. {&_16u2_p5_0,&_16u2_p5_1},
  154873. {&_16u2_p6_0,&_16u2_p6_1},
  154874. {&_16u2_p7_0,&_16u2_p7_1},
  154875. {&_16u2_p8_0,&_16u2_p8_1},
  154876. {&_16u2_p9_0,&_16u2_p9_1,&_16u2_p9_2}
  154877. }
  154878. };
  154879. static vorbis_residue_template _res_16u_0[]={
  154880. {1,0, &_residue_44_low_un,
  154881. &_huff_book__16u0__single,&_huff_book__16u0__single,
  154882. &_resbook_16u_0,&_resbook_16u_0},
  154883. };
  154884. static vorbis_residue_template _res_16u_1[]={
  154885. {1,0, &_residue_44_mid_un,
  154886. &_huff_book__16u1__short,&_huff_book__16u1__short,
  154887. &_resbook_16u_1,&_resbook_16u_1},
  154888. {1,0, &_residue_44_mid_un,
  154889. &_huff_book__16u1__long,&_huff_book__16u1__long,
  154890. &_resbook_16u_1,&_resbook_16u_1}
  154891. };
  154892. static vorbis_residue_template _res_16u_2[]={
  154893. {1,0, &_residue_44_hi_un,
  154894. &_huff_book__16u2__short,&_huff_book__16u2__short,
  154895. &_resbook_16u_2,&_resbook_16u_2},
  154896. {1,0, &_residue_44_hi_un,
  154897. &_huff_book__16u2__long,&_huff_book__16u2__long,
  154898. &_resbook_16u_2,&_resbook_16u_2}
  154899. };
  154900. static vorbis_mapping_template _mapres_template_16_uncoupled[3]={
  154901. { _map_nominal_u, _res_16u_0 }, /* 0 */
  154902. { _map_nominal_u, _res_16u_1 }, /* 1 */
  154903. { _map_nominal_u, _res_16u_2 }, /* 2 */
  154904. };
  154905. /********* End of inlined file: residue_16.h *********/
  154906. static int blocksize_16_short[3]={
  154907. 1024,512,512
  154908. };
  154909. static int blocksize_16_long[3]={
  154910. 1024,1024,1024
  154911. };
  154912. static int _floor_mapping_16_short[3]={
  154913. 9,3,3
  154914. };
  154915. static int _floor_mapping_16[3]={
  154916. 9,9,9
  154917. };
  154918. static double rate_mapping_16[4]={
  154919. 12000.,20000.,44000.,86000.
  154920. };
  154921. static double rate_mapping_16_uncoupled[4]={
  154922. 16000.,28000.,64000.,100000.
  154923. };
  154924. static double _global_mapping_16[4]={ 1., 2., 3., 4. };
  154925. static double quality_mapping_16[4]={ -.1,.05,.5,1. };
  154926. static double _psy_compand_16_mapping[4]={ 0., .8, 1., 1.};
  154927. ve_setup_data_template ve_setup_16_stereo={
  154928. 3,
  154929. rate_mapping_16,
  154930. quality_mapping_16,
  154931. 2,
  154932. 15000,
  154933. 19000,
  154934. blocksize_16_short,
  154935. blocksize_16_long,
  154936. _psy_tone_masteratt_16,
  154937. _psy_tone_0dB,
  154938. _psy_tone_suppress,
  154939. _vp_tonemask_adj_16,
  154940. _vp_tonemask_adj_16,
  154941. _vp_tonemask_adj_16,
  154942. _psy_noiseguards_8,
  154943. _psy_noisebias_16_impulse,
  154944. _psy_noisebias_16_short,
  154945. _psy_noisebias_16_short,
  154946. _psy_noisebias_16,
  154947. _psy_noise_suppress,
  154948. _psy_compand_8,
  154949. _psy_compand_16_mapping,
  154950. _psy_compand_16_mapping,
  154951. {_noise_start_16,_noise_start_16},
  154952. { _noise_part_16, _noise_part_16},
  154953. _noise_thresh_16,
  154954. _psy_ath_floater_16,
  154955. _psy_ath_abs_16,
  154956. _psy_lowpass_16,
  154957. _psy_global_44,
  154958. _global_mapping_16,
  154959. _psy_stereo_modes_16,
  154960. _floor_books,
  154961. _floor,
  154962. _floor_mapping_16_short,
  154963. _floor_mapping_16,
  154964. _mapres_template_16_stereo
  154965. };
  154966. ve_setup_data_template ve_setup_16_uncoupled={
  154967. 3,
  154968. rate_mapping_16_uncoupled,
  154969. quality_mapping_16,
  154970. -1,
  154971. 15000,
  154972. 19000,
  154973. blocksize_16_short,
  154974. blocksize_16_long,
  154975. _psy_tone_masteratt_16,
  154976. _psy_tone_0dB,
  154977. _psy_tone_suppress,
  154978. _vp_tonemask_adj_16,
  154979. _vp_tonemask_adj_16,
  154980. _vp_tonemask_adj_16,
  154981. _psy_noiseguards_8,
  154982. _psy_noisebias_16_impulse,
  154983. _psy_noisebias_16_short,
  154984. _psy_noisebias_16_short,
  154985. _psy_noisebias_16,
  154986. _psy_noise_suppress,
  154987. _psy_compand_8,
  154988. _psy_compand_16_mapping,
  154989. _psy_compand_16_mapping,
  154990. {_noise_start_16,_noise_start_16},
  154991. { _noise_part_16, _noise_part_16},
  154992. _noise_thresh_16,
  154993. _psy_ath_floater_16,
  154994. _psy_ath_abs_16,
  154995. _psy_lowpass_16,
  154996. _psy_global_44,
  154997. _global_mapping_16,
  154998. _psy_stereo_modes_16,
  154999. _floor_books,
  155000. _floor,
  155001. _floor_mapping_16_short,
  155002. _floor_mapping_16,
  155003. _mapres_template_16_uncoupled
  155004. };
  155005. /********* End of inlined file: setup_16.h *********/
  155006. /********* Start of inlined file: setup_22.h *********/
  155007. static double rate_mapping_22[4]={
  155008. 15000.,20000.,44000.,86000.
  155009. };
  155010. static double rate_mapping_22_uncoupled[4]={
  155011. 16000.,28000.,50000.,90000.
  155012. };
  155013. static double _psy_lowpass_22[4]={9.5,11.,30.,99.};
  155014. ve_setup_data_template ve_setup_22_stereo={
  155015. 3,
  155016. rate_mapping_22,
  155017. quality_mapping_16,
  155018. 2,
  155019. 19000,
  155020. 26000,
  155021. blocksize_16_short,
  155022. blocksize_16_long,
  155023. _psy_tone_masteratt_16,
  155024. _psy_tone_0dB,
  155025. _psy_tone_suppress,
  155026. _vp_tonemask_adj_16,
  155027. _vp_tonemask_adj_16,
  155028. _vp_tonemask_adj_16,
  155029. _psy_noiseguards_8,
  155030. _psy_noisebias_16_impulse,
  155031. _psy_noisebias_16_short,
  155032. _psy_noisebias_16_short,
  155033. _psy_noisebias_16,
  155034. _psy_noise_suppress,
  155035. _psy_compand_8,
  155036. _psy_compand_8_mapping,
  155037. _psy_compand_8_mapping,
  155038. {_noise_start_16,_noise_start_16},
  155039. { _noise_part_16, _noise_part_16},
  155040. _noise_thresh_16,
  155041. _psy_ath_floater_16,
  155042. _psy_ath_abs_16,
  155043. _psy_lowpass_22,
  155044. _psy_global_44,
  155045. _global_mapping_16,
  155046. _psy_stereo_modes_16,
  155047. _floor_books,
  155048. _floor,
  155049. _floor_mapping_16_short,
  155050. _floor_mapping_16,
  155051. _mapres_template_16_stereo
  155052. };
  155053. ve_setup_data_template ve_setup_22_uncoupled={
  155054. 3,
  155055. rate_mapping_22_uncoupled,
  155056. quality_mapping_16,
  155057. -1,
  155058. 19000,
  155059. 26000,
  155060. blocksize_16_short,
  155061. blocksize_16_long,
  155062. _psy_tone_masteratt_16,
  155063. _psy_tone_0dB,
  155064. _psy_tone_suppress,
  155065. _vp_tonemask_adj_16,
  155066. _vp_tonemask_adj_16,
  155067. _vp_tonemask_adj_16,
  155068. _psy_noiseguards_8,
  155069. _psy_noisebias_16_impulse,
  155070. _psy_noisebias_16_short,
  155071. _psy_noisebias_16_short,
  155072. _psy_noisebias_16,
  155073. _psy_noise_suppress,
  155074. _psy_compand_8,
  155075. _psy_compand_8_mapping,
  155076. _psy_compand_8_mapping,
  155077. {_noise_start_16,_noise_start_16},
  155078. { _noise_part_16, _noise_part_16},
  155079. _noise_thresh_16,
  155080. _psy_ath_floater_16,
  155081. _psy_ath_abs_16,
  155082. _psy_lowpass_22,
  155083. _psy_global_44,
  155084. _global_mapping_16,
  155085. _psy_stereo_modes_16,
  155086. _floor_books,
  155087. _floor,
  155088. _floor_mapping_16_short,
  155089. _floor_mapping_16,
  155090. _mapres_template_16_uncoupled
  155091. };
  155092. /********* End of inlined file: setup_22.h *********/
  155093. /********* Start of inlined file: setup_X.h *********/
  155094. static double rate_mapping_X[12]={
  155095. -1.,-1.,-1.,-1.,-1.,-1.,
  155096. -1.,-1.,-1.,-1.,-1.,-1.
  155097. };
  155098. ve_setup_data_template ve_setup_X_stereo={
  155099. 11,
  155100. rate_mapping_X,
  155101. quality_mapping_44,
  155102. 2,
  155103. 50000,
  155104. 200000,
  155105. blocksize_short_44,
  155106. blocksize_long_44,
  155107. _psy_tone_masteratt_44,
  155108. _psy_tone_0dB,
  155109. _psy_tone_suppress,
  155110. _vp_tonemask_adj_otherblock,
  155111. _vp_tonemask_adj_longblock,
  155112. _vp_tonemask_adj_otherblock,
  155113. _psy_noiseguards_44,
  155114. _psy_noisebias_impulse,
  155115. _psy_noisebias_padding,
  155116. _psy_noisebias_trans,
  155117. _psy_noisebias_long,
  155118. _psy_noise_suppress,
  155119. _psy_compand_44,
  155120. _psy_compand_short_mapping,
  155121. _psy_compand_long_mapping,
  155122. {_noise_start_short_44,_noise_start_long_44},
  155123. {_noise_part_short_44,_noise_part_long_44},
  155124. _noise_thresh_44,
  155125. _psy_ath_floater,
  155126. _psy_ath_abs,
  155127. _psy_lowpass_44,
  155128. _psy_global_44,
  155129. _global_mapping_44,
  155130. _psy_stereo_modes_44,
  155131. _floor_books,
  155132. _floor,
  155133. _floor_short_mapping_44,
  155134. _floor_long_mapping_44,
  155135. _mapres_template_44_stereo
  155136. };
  155137. ve_setup_data_template ve_setup_X_uncoupled={
  155138. 11,
  155139. rate_mapping_X,
  155140. quality_mapping_44,
  155141. -1,
  155142. 50000,
  155143. 200000,
  155144. blocksize_short_44,
  155145. blocksize_long_44,
  155146. _psy_tone_masteratt_44,
  155147. _psy_tone_0dB,
  155148. _psy_tone_suppress,
  155149. _vp_tonemask_adj_otherblock,
  155150. _vp_tonemask_adj_longblock,
  155151. _vp_tonemask_adj_otherblock,
  155152. _psy_noiseguards_44,
  155153. _psy_noisebias_impulse,
  155154. _psy_noisebias_padding,
  155155. _psy_noisebias_trans,
  155156. _psy_noisebias_long,
  155157. _psy_noise_suppress,
  155158. _psy_compand_44,
  155159. _psy_compand_short_mapping,
  155160. _psy_compand_long_mapping,
  155161. {_noise_start_short_44,_noise_start_long_44},
  155162. {_noise_part_short_44,_noise_part_long_44},
  155163. _noise_thresh_44,
  155164. _psy_ath_floater,
  155165. _psy_ath_abs,
  155166. _psy_lowpass_44,
  155167. _psy_global_44,
  155168. _global_mapping_44,
  155169. NULL,
  155170. _floor_books,
  155171. _floor,
  155172. _floor_short_mapping_44,
  155173. _floor_long_mapping_44,
  155174. _mapres_template_44_uncoupled
  155175. };
  155176. ve_setup_data_template ve_setup_XX_stereo={
  155177. 2,
  155178. rate_mapping_X,
  155179. quality_mapping_8,
  155180. 2,
  155181. 0,
  155182. 8000,
  155183. blocksize_8,
  155184. blocksize_8,
  155185. _psy_tone_masteratt_8,
  155186. _psy_tone_0dB,
  155187. _psy_tone_suppress,
  155188. _vp_tonemask_adj_8,
  155189. NULL,
  155190. _vp_tonemask_adj_8,
  155191. _psy_noiseguards_8,
  155192. _psy_noisebias_8,
  155193. _psy_noisebias_8,
  155194. NULL,
  155195. NULL,
  155196. _psy_noise_suppress,
  155197. _psy_compand_8,
  155198. _psy_compand_8_mapping,
  155199. NULL,
  155200. {_noise_start_8,_noise_start_8},
  155201. {_noise_part_8,_noise_part_8},
  155202. _noise_thresh_5only,
  155203. _psy_ath_floater_8,
  155204. _psy_ath_abs_8,
  155205. _psy_lowpass_8,
  155206. _psy_global_44,
  155207. _global_mapping_8,
  155208. _psy_stereo_modes_8,
  155209. _floor_books,
  155210. _floor,
  155211. _floor_mapping_8,
  155212. NULL,
  155213. _mapres_template_8_stereo
  155214. };
  155215. ve_setup_data_template ve_setup_XX_uncoupled={
  155216. 2,
  155217. rate_mapping_X,
  155218. quality_mapping_8,
  155219. -1,
  155220. 0,
  155221. 8000,
  155222. blocksize_8,
  155223. blocksize_8,
  155224. _psy_tone_masteratt_8,
  155225. _psy_tone_0dB,
  155226. _psy_tone_suppress,
  155227. _vp_tonemask_adj_8,
  155228. NULL,
  155229. _vp_tonemask_adj_8,
  155230. _psy_noiseguards_8,
  155231. _psy_noisebias_8,
  155232. _psy_noisebias_8,
  155233. NULL,
  155234. NULL,
  155235. _psy_noise_suppress,
  155236. _psy_compand_8,
  155237. _psy_compand_8_mapping,
  155238. NULL,
  155239. {_noise_start_8,_noise_start_8},
  155240. {_noise_part_8,_noise_part_8},
  155241. _noise_thresh_5only,
  155242. _psy_ath_floater_8,
  155243. _psy_ath_abs_8,
  155244. _psy_lowpass_8,
  155245. _psy_global_44,
  155246. _global_mapping_8,
  155247. _psy_stereo_modes_8,
  155248. _floor_books,
  155249. _floor,
  155250. _floor_mapping_8,
  155251. NULL,
  155252. _mapres_template_8_uncoupled
  155253. };
  155254. /********* End of inlined file: setup_X.h *********/
  155255. static ve_setup_data_template *setup_list[]={
  155256. &ve_setup_44_stereo,
  155257. &ve_setup_44_uncoupled,
  155258. &ve_setup_32_stereo,
  155259. &ve_setup_32_uncoupled,
  155260. &ve_setup_22_stereo,
  155261. &ve_setup_22_uncoupled,
  155262. &ve_setup_16_stereo,
  155263. &ve_setup_16_uncoupled,
  155264. &ve_setup_11_stereo,
  155265. &ve_setup_11_uncoupled,
  155266. &ve_setup_8_stereo,
  155267. &ve_setup_8_uncoupled,
  155268. &ve_setup_X_stereo,
  155269. &ve_setup_X_uncoupled,
  155270. &ve_setup_XX_stereo,
  155271. &ve_setup_XX_uncoupled,
  155272. 0
  155273. };
  155274. static int vorbis_encode_toplevel_setup(vorbis_info *vi,int ch,long rate){
  155275. if(vi && vi->codec_setup){
  155276. vi->version=0;
  155277. vi->channels=ch;
  155278. vi->rate=rate;
  155279. return(0);
  155280. }
  155281. return(OV_EINVAL);
  155282. }
  155283. static void vorbis_encode_floor_setup(vorbis_info *vi,double s,int block,
  155284. static_codebook ***books,
  155285. vorbis_info_floor1 *in,
  155286. int *x){
  155287. int i,k,is=s;
  155288. vorbis_info_floor1 *f=(vorbis_info_floor1*) _ogg_calloc(1,sizeof(*f));
  155289. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155290. memcpy(f,in+x[is],sizeof(*f));
  155291. /* fill in the lowpass field, even if it's temporary */
  155292. f->n=ci->blocksizes[block]>>1;
  155293. /* books */
  155294. {
  155295. int partitions=f->partitions;
  155296. int maxclass=-1;
  155297. int maxbook=-1;
  155298. for(i=0;i<partitions;i++)
  155299. if(f->partitionclass[i]>maxclass)maxclass=f->partitionclass[i];
  155300. for(i=0;i<=maxclass;i++){
  155301. if(f->class_book[i]>maxbook)maxbook=f->class_book[i];
  155302. f->class_book[i]+=ci->books;
  155303. for(k=0;k<(1<<f->class_subs[i]);k++){
  155304. if(f->class_subbook[i][k]>maxbook)maxbook=f->class_subbook[i][k];
  155305. if(f->class_subbook[i][k]>=0)f->class_subbook[i][k]+=ci->books;
  155306. }
  155307. }
  155308. for(i=0;i<=maxbook;i++)
  155309. ci->book_param[ci->books++]=books[x[is]][i];
  155310. }
  155311. /* for now, we're only using floor 1 */
  155312. ci->floor_type[ci->floors]=1;
  155313. ci->floor_param[ci->floors]=f;
  155314. ci->floors++;
  155315. return;
  155316. }
  155317. static void vorbis_encode_global_psych_setup(vorbis_info *vi,double s,
  155318. vorbis_info_psy_global *in,
  155319. double *x){
  155320. int i,is=s;
  155321. double ds=s-is;
  155322. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155323. vorbis_info_psy_global *g=&ci->psy_g_param;
  155324. memcpy(g,in+(int)x[is],sizeof(*g));
  155325. ds=x[is]*(1.-ds)+x[is+1]*ds;
  155326. is=(int)ds;
  155327. ds-=is;
  155328. if(ds==0 && is>0){
  155329. is--;
  155330. ds=1.;
  155331. }
  155332. /* interpolate the trigger threshholds */
  155333. for(i=0;i<4;i++){
  155334. g->preecho_thresh[i]=in[is].preecho_thresh[i]*(1.-ds)+in[is+1].preecho_thresh[i]*ds;
  155335. g->postecho_thresh[i]=in[is].postecho_thresh[i]*(1.-ds)+in[is+1].postecho_thresh[i]*ds;
  155336. }
  155337. g->ampmax_att_per_sec=ci->hi.amplitude_track_dBpersec;
  155338. return;
  155339. }
  155340. static void vorbis_encode_global_stereo(vorbis_info *vi,
  155341. highlevel_encode_setup *hi,
  155342. adj_stereo *p){
  155343. float s=hi->stereo_point_setting;
  155344. int i,is=s;
  155345. double ds=s-is;
  155346. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155347. vorbis_info_psy_global *g=&ci->psy_g_param;
  155348. if(p){
  155349. memcpy(g->coupling_prepointamp,p[is].pre,sizeof(*p[is].pre)*PACKETBLOBS);
  155350. memcpy(g->coupling_postpointamp,p[is].post,sizeof(*p[is].post)*PACKETBLOBS);
  155351. if(hi->managed){
  155352. /* interpolate the kHz threshholds */
  155353. for(i=0;i<PACKETBLOBS;i++){
  155354. float kHz=p[is].kHz[i]*(1.-ds)+p[is+1].kHz[i]*ds;
  155355. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  155356. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  155357. g->coupling_pkHz[i]=kHz;
  155358. kHz=p[is].lowpasskHz[i]*(1.-ds)+p[is+1].lowpasskHz[i]*ds;
  155359. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  155360. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  155361. }
  155362. }else{
  155363. float kHz=p[is].kHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].kHz[PACKETBLOBS/2]*ds;
  155364. for(i=0;i<PACKETBLOBS;i++){
  155365. g->coupling_pointlimit[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  155366. g->coupling_pointlimit[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  155367. g->coupling_pkHz[i]=kHz;
  155368. }
  155369. kHz=p[is].lowpasskHz[PACKETBLOBS/2]*(1.-ds)+p[is+1].lowpasskHz[PACKETBLOBS/2]*ds;
  155370. for(i=0;i<PACKETBLOBS;i++){
  155371. g->sliding_lowpass[0][i]=kHz*1000./vi->rate*ci->blocksizes[0];
  155372. g->sliding_lowpass[1][i]=kHz*1000./vi->rate*ci->blocksizes[1];
  155373. }
  155374. }
  155375. }else{
  155376. for(i=0;i<PACKETBLOBS;i++){
  155377. g->sliding_lowpass[0][i]=ci->blocksizes[0];
  155378. g->sliding_lowpass[1][i]=ci->blocksizes[1];
  155379. }
  155380. }
  155381. return;
  155382. }
  155383. static void vorbis_encode_psyset_setup(vorbis_info *vi,double s,
  155384. int *nn_start,
  155385. int *nn_partition,
  155386. double *nn_thresh,
  155387. int block){
  155388. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155389. vorbis_info_psy *p=ci->psy_param[block];
  155390. highlevel_encode_setup *hi=&ci->hi;
  155391. int is=s;
  155392. if(block>=ci->psys)
  155393. ci->psys=block+1;
  155394. if(!p){
  155395. p=(vorbis_info_psy*)_ogg_calloc(1,sizeof(*p));
  155396. ci->psy_param[block]=p;
  155397. }
  155398. memcpy(p,&_psy_info_template,sizeof(*p));
  155399. p->blockflag=block>>1;
  155400. if(hi->noise_normalize_p){
  155401. p->normal_channel_p=1;
  155402. p->normal_point_p=1;
  155403. p->normal_start=nn_start[is];
  155404. p->normal_partition=nn_partition[is];
  155405. p->normal_thresh=nn_thresh[is];
  155406. }
  155407. return;
  155408. }
  155409. static void vorbis_encode_tonemask_setup(vorbis_info *vi,double s,int block,
  155410. att3 *att,
  155411. int *max,
  155412. vp_adjblock *in){
  155413. int i,is=s;
  155414. double ds=s-is;
  155415. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155416. vorbis_info_psy *p=ci->psy_param[block];
  155417. /* 0 and 2 are only used by bitmanagement, but there's no harm to always
  155418. filling the values in here */
  155419. p->tone_masteratt[0]=att[is].att[0]*(1.-ds)+att[is+1].att[0]*ds;
  155420. p->tone_masteratt[1]=att[is].att[1]*(1.-ds)+att[is+1].att[1]*ds;
  155421. p->tone_masteratt[2]=att[is].att[2]*(1.-ds)+att[is+1].att[2]*ds;
  155422. p->tone_centerboost=att[is].boost*(1.-ds)+att[is+1].boost*ds;
  155423. p->tone_decay=att[is].decay*(1.-ds)+att[is+1].decay*ds;
  155424. p->max_curve_dB=max[is]*(1.-ds)+max[is+1]*ds;
  155425. for(i=0;i<P_BANDS;i++)
  155426. p->toneatt[i]=in[is].block[i]*(1.-ds)+in[is+1].block[i]*ds;
  155427. return;
  155428. }
  155429. static void vorbis_encode_compand_setup(vorbis_info *vi,double s,int block,
  155430. compandblock *in, double *x){
  155431. int i,is=s;
  155432. double ds=s-is;
  155433. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155434. vorbis_info_psy *p=ci->psy_param[block];
  155435. ds=x[is]*(1.-ds)+x[is+1]*ds;
  155436. is=(int)ds;
  155437. ds-=is;
  155438. if(ds==0 && is>0){
  155439. is--;
  155440. ds=1.;
  155441. }
  155442. /* interpolate the compander settings */
  155443. for(i=0;i<NOISE_COMPAND_LEVELS;i++)
  155444. p->noisecompand[i]=in[is].data[i]*(1.-ds)+in[is+1].data[i]*ds;
  155445. return;
  155446. }
  155447. static void vorbis_encode_peak_setup(vorbis_info *vi,double s,int block,
  155448. int *suppress){
  155449. int is=s;
  155450. double ds=s-is;
  155451. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155452. vorbis_info_psy *p=ci->psy_param[block];
  155453. p->tone_abs_limit=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  155454. return;
  155455. }
  155456. static void vorbis_encode_noisebias_setup(vorbis_info *vi,double s,int block,
  155457. int *suppress,
  155458. noise3 *in,
  155459. noiseguard *guard,
  155460. double userbias){
  155461. int i,is=s,j;
  155462. double ds=s-is;
  155463. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155464. vorbis_info_psy *p=ci->psy_param[block];
  155465. p->noisemaxsupp=suppress[is]*(1.-ds)+suppress[is+1]*ds;
  155466. p->noisewindowlomin=guard[block].lo;
  155467. p->noisewindowhimin=guard[block].hi;
  155468. p->noisewindowfixed=guard[block].fixed;
  155469. for(j=0;j<P_NOISECURVES;j++)
  155470. for(i=0;i<P_BANDS;i++)
  155471. p->noiseoff[j][i]=in[is].data[j][i]*(1.-ds)+in[is+1].data[j][i]*ds;
  155472. /* impulse blocks may take a user specified bias to boost the
  155473. nominal/high noise encoding depth */
  155474. for(j=0;j<P_NOISECURVES;j++){
  155475. float min=p->noiseoff[j][0]+6; /* the lowest it can go */
  155476. for(i=0;i<P_BANDS;i++){
  155477. p->noiseoff[j][i]+=userbias;
  155478. if(p->noiseoff[j][i]<min)p->noiseoff[j][i]=min;
  155479. }
  155480. }
  155481. return;
  155482. }
  155483. static void vorbis_encode_ath_setup(vorbis_info *vi,int block){
  155484. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155485. vorbis_info_psy *p=ci->psy_param[block];
  155486. p->ath_adjatt=ci->hi.ath_floating_dB;
  155487. p->ath_maxatt=ci->hi.ath_absolute_dB;
  155488. return;
  155489. }
  155490. static int book_dup_or_new(codec_setup_info *ci,static_codebook *book){
  155491. int i;
  155492. for(i=0;i<ci->books;i++)
  155493. if(ci->book_param[i]==book)return(i);
  155494. return(ci->books++);
  155495. }
  155496. static void vorbis_encode_blocksize_setup(vorbis_info *vi,double s,
  155497. int *shortb,int *longb){
  155498. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155499. int is=s;
  155500. int blockshort=shortb[is];
  155501. int blocklong=longb[is];
  155502. ci->blocksizes[0]=blockshort;
  155503. ci->blocksizes[1]=blocklong;
  155504. }
  155505. static void vorbis_encode_residue_setup(vorbis_info *vi,
  155506. int number, int block,
  155507. vorbis_residue_template *res){
  155508. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155509. int i,n;
  155510. vorbis_info_residue0 *r=(vorbis_info_residue0*)(ci->residue_param[number]=
  155511. (vorbis_info_residue0*)_ogg_malloc(sizeof(*r)));
  155512. memcpy(r,res->res,sizeof(*r));
  155513. if(ci->residues<=number)ci->residues=number+1;
  155514. switch(ci->blocksizes[block]){
  155515. case 64:case 128:case 256:
  155516. r->grouping=16;
  155517. break;
  155518. default:
  155519. r->grouping=32;
  155520. break;
  155521. }
  155522. ci->residue_type[number]=res->res_type;
  155523. /* to be adjusted by lowpass/pointlimit later */
  155524. n=r->end=ci->blocksizes[block]>>1;
  155525. if(res->res_type==2)
  155526. n=r->end*=vi->channels;
  155527. /* fill in all the books */
  155528. {
  155529. int booklist=0,k;
  155530. if(ci->hi.managed){
  155531. for(i=0;i<r->partitions;i++)
  155532. for(k=0;k<3;k++)
  155533. if(res->books_base_managed->books[i][k])
  155534. r->secondstages[i]|=(1<<k);
  155535. r->groupbook=book_dup_or_new(ci,res->book_aux_managed);
  155536. ci->book_param[r->groupbook]=res->book_aux_managed;
  155537. for(i=0;i<r->partitions;i++){
  155538. for(k=0;k<3;k++){
  155539. if(res->books_base_managed->books[i][k]){
  155540. int bookid=book_dup_or_new(ci,res->books_base_managed->books[i][k]);
  155541. r->booklist[booklist++]=bookid;
  155542. ci->book_param[bookid]=res->books_base_managed->books[i][k];
  155543. }
  155544. }
  155545. }
  155546. }else{
  155547. for(i=0;i<r->partitions;i++)
  155548. for(k=0;k<3;k++)
  155549. if(res->books_base->books[i][k])
  155550. r->secondstages[i]|=(1<<k);
  155551. r->groupbook=book_dup_or_new(ci,res->book_aux);
  155552. ci->book_param[r->groupbook]=res->book_aux;
  155553. for(i=0;i<r->partitions;i++){
  155554. for(k=0;k<3;k++){
  155555. if(res->books_base->books[i][k]){
  155556. int bookid=book_dup_or_new(ci,res->books_base->books[i][k]);
  155557. r->booklist[booklist++]=bookid;
  155558. ci->book_param[bookid]=res->books_base->books[i][k];
  155559. }
  155560. }
  155561. }
  155562. }
  155563. }
  155564. /* lowpass setup/pointlimit */
  155565. {
  155566. double freq=ci->hi.lowpass_kHz*1000.;
  155567. vorbis_info_floor1 *f=(vorbis_info_floor1*)ci->floor_param[block]; /* by convention */
  155568. double nyq=vi->rate/2.;
  155569. long blocksize=ci->blocksizes[block]>>1;
  155570. /* lowpass needs to be set in the floor and the residue. */
  155571. if(freq>nyq)freq=nyq;
  155572. /* in the floor, the granularity can be very fine; it doesn't alter
  155573. the encoding structure, only the samples used to fit the floor
  155574. approximation */
  155575. f->n=freq/nyq*blocksize;
  155576. /* this res may by limited by the maximum pointlimit of the mode,
  155577. not the lowpass. the floor is always lowpass limited. */
  155578. if(res->limit_type){
  155579. if(ci->hi.managed)
  155580. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS-1]*1000.;
  155581. else
  155582. freq=ci->psy_g_param.coupling_pkHz[PACKETBLOBS/2]*1000.;
  155583. if(freq>nyq)freq=nyq;
  155584. }
  155585. /* in the residue, we're constrained, physically, by partition
  155586. boundaries. We still lowpass 'wherever', but we have to round up
  155587. here to next boundary, or the vorbis spec will round it *down* to
  155588. previous boundary in encode/decode */
  155589. if(ci->residue_type[block]==2)
  155590. r->end=(int)((freq/nyq*blocksize*2)/r->grouping+.9)* /* round up only if we're well past */
  155591. r->grouping;
  155592. else
  155593. r->end=(int)((freq/nyq*blocksize)/r->grouping+.9)* /* round up only if we're well past */
  155594. r->grouping;
  155595. }
  155596. }
  155597. /* we assume two maps in this encoder */
  155598. static void vorbis_encode_map_n_res_setup(vorbis_info *vi,double s,
  155599. vorbis_mapping_template *maps){
  155600. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155601. int i,j,is=s,modes=2;
  155602. vorbis_info_mapping0 *map=maps[is].map;
  155603. vorbis_info_mode *mode=_mode_template;
  155604. vorbis_residue_template *res=maps[is].res;
  155605. if(ci->blocksizes[0]==ci->blocksizes[1])modes=1;
  155606. for(i=0;i<modes;i++){
  155607. ci->map_param[i]=_ogg_calloc(1,sizeof(*map));
  155608. ci->mode_param[i]=(vorbis_info_mode*)_ogg_calloc(1,sizeof(*mode));
  155609. memcpy(ci->mode_param[i],mode+i,sizeof(*_mode_template));
  155610. if(i>=ci->modes)ci->modes=i+1;
  155611. ci->map_type[i]=0;
  155612. memcpy(ci->map_param[i],map+i,sizeof(*map));
  155613. if(i>=ci->maps)ci->maps=i+1;
  155614. for(j=0;j<map[i].submaps;j++)
  155615. vorbis_encode_residue_setup(vi,map[i].residuesubmap[j],i
  155616. ,res+map[i].residuesubmap[j]);
  155617. }
  155618. }
  155619. static double setting_to_approx_bitrate(vorbis_info *vi){
  155620. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155621. highlevel_encode_setup *hi=&ci->hi;
  155622. ve_setup_data_template *setup=(ve_setup_data_template *)hi->setup;
  155623. int is=hi->base_setting;
  155624. double ds=hi->base_setting-is;
  155625. int ch=vi->channels;
  155626. double *r=setup->rate_mapping;
  155627. if(r==NULL)
  155628. return(-1);
  155629. return((r[is]*(1.-ds)+r[is+1]*ds)*ch);
  155630. }
  155631. static void get_setup_template(vorbis_info *vi,
  155632. long ch,long srate,
  155633. double req,int q_or_bitrate){
  155634. int i=0,j;
  155635. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155636. highlevel_encode_setup *hi=&ci->hi;
  155637. if(q_or_bitrate)req/=ch;
  155638. while(setup_list[i]){
  155639. if(setup_list[i]->coupling_restriction==-1 ||
  155640. setup_list[i]->coupling_restriction==ch){
  155641. if(srate>=setup_list[i]->samplerate_min_restriction &&
  155642. srate<=setup_list[i]->samplerate_max_restriction){
  155643. int mappings=setup_list[i]->mappings;
  155644. double *map=(q_or_bitrate?
  155645. setup_list[i]->rate_mapping:
  155646. setup_list[i]->quality_mapping);
  155647. /* the template matches. Does the requested quality mode
  155648. fall within this template's modes? */
  155649. if(req<map[0]){++i;continue;}
  155650. if(req>map[setup_list[i]->mappings]){++i;continue;}
  155651. for(j=0;j<mappings;j++)
  155652. if(req>=map[j] && req<map[j+1])break;
  155653. /* an all-points match */
  155654. hi->setup=setup_list[i];
  155655. if(j==mappings)
  155656. hi->base_setting=j-.001;
  155657. else{
  155658. float low=map[j];
  155659. float high=map[j+1];
  155660. float del=(req-low)/(high-low);
  155661. hi->base_setting=j+del;
  155662. }
  155663. return;
  155664. }
  155665. }
  155666. i++;
  155667. }
  155668. hi->setup=NULL;
  155669. }
  155670. /* encoders will need to use vorbis_info_init beforehand and call
  155671. vorbis_info clear when all done */
  155672. /* two interfaces; this, more detailed one, and later a convenience
  155673. layer on top */
  155674. /* the final setup call */
  155675. int vorbis_encode_setup_init(vorbis_info *vi){
  155676. int i0=0,singleblock=0;
  155677. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155678. ve_setup_data_template *setup=NULL;
  155679. highlevel_encode_setup *hi=&ci->hi;
  155680. if(ci==NULL)return(OV_EINVAL);
  155681. if(!hi->impulse_block_p)i0=1;
  155682. /* too low/high an ATH floater is nonsensical, but doesn't break anything */
  155683. if(hi->ath_floating_dB>-80)hi->ath_floating_dB=-80;
  155684. if(hi->ath_floating_dB<-200)hi->ath_floating_dB=-200;
  155685. /* again, bound this to avoid the app shooting itself int he foot
  155686. too badly */
  155687. if(hi->amplitude_track_dBpersec>0.)hi->amplitude_track_dBpersec=0.;
  155688. if(hi->amplitude_track_dBpersec<-99999.)hi->amplitude_track_dBpersec=-99999.;
  155689. /* get the appropriate setup template; matches the fetch in previous
  155690. stages */
  155691. setup=(ve_setup_data_template *)hi->setup;
  155692. if(setup==NULL)return(OV_EINVAL);
  155693. hi->set_in_stone=1;
  155694. /* choose block sizes from configured sizes as well as paying
  155695. attention to long_block_p and short_block_p. If the configured
  155696. short and long blocks are the same length, we set long_block_p
  155697. and unset short_block_p */
  155698. vorbis_encode_blocksize_setup(vi,hi->base_setting,
  155699. setup->blocksize_short,
  155700. setup->blocksize_long);
  155701. if(ci->blocksizes[0]==ci->blocksizes[1])singleblock=1;
  155702. /* floor setup; choose proper floor params. Allocated on the floor
  155703. stack in order; if we alloc only long floor, it's 0 */
  155704. vorbis_encode_floor_setup(vi,hi->short_setting,0,
  155705. setup->floor_books,
  155706. setup->floor_params,
  155707. setup->floor_short_mapping);
  155708. if(!singleblock)
  155709. vorbis_encode_floor_setup(vi,hi->long_setting,1,
  155710. setup->floor_books,
  155711. setup->floor_params,
  155712. setup->floor_long_mapping);
  155713. /* setup of [mostly] short block detection and stereo*/
  155714. vorbis_encode_global_psych_setup(vi,hi->trigger_setting,
  155715. setup->global_params,
  155716. setup->global_mapping);
  155717. vorbis_encode_global_stereo(vi,hi,setup->stereo_modes);
  155718. /* basic psych setup and noise normalization */
  155719. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155720. setup->psy_noise_normal_start[0],
  155721. setup->psy_noise_normal_partition[0],
  155722. setup->psy_noise_normal_thresh,
  155723. 0);
  155724. vorbis_encode_psyset_setup(vi,hi->short_setting,
  155725. setup->psy_noise_normal_start[0],
  155726. setup->psy_noise_normal_partition[0],
  155727. setup->psy_noise_normal_thresh,
  155728. 1);
  155729. if(!singleblock){
  155730. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155731. setup->psy_noise_normal_start[1],
  155732. setup->psy_noise_normal_partition[1],
  155733. setup->psy_noise_normal_thresh,
  155734. 2);
  155735. vorbis_encode_psyset_setup(vi,hi->long_setting,
  155736. setup->psy_noise_normal_start[1],
  155737. setup->psy_noise_normal_partition[1],
  155738. setup->psy_noise_normal_thresh,
  155739. 3);
  155740. }
  155741. /* tone masking setup */
  155742. vorbis_encode_tonemask_setup(vi,hi->block[i0].tone_mask_setting,0,
  155743. setup->psy_tone_masteratt,
  155744. setup->psy_tone_0dB,
  155745. setup->psy_tone_adj_impulse);
  155746. vorbis_encode_tonemask_setup(vi,hi->block[1].tone_mask_setting,1,
  155747. setup->psy_tone_masteratt,
  155748. setup->psy_tone_0dB,
  155749. setup->psy_tone_adj_other);
  155750. if(!singleblock){
  155751. vorbis_encode_tonemask_setup(vi,hi->block[2].tone_mask_setting,2,
  155752. setup->psy_tone_masteratt,
  155753. setup->psy_tone_0dB,
  155754. setup->psy_tone_adj_other);
  155755. vorbis_encode_tonemask_setup(vi,hi->block[3].tone_mask_setting,3,
  155756. setup->psy_tone_masteratt,
  155757. setup->psy_tone_0dB,
  155758. setup->psy_tone_adj_long);
  155759. }
  155760. /* noise companding setup */
  155761. vorbis_encode_compand_setup(vi,hi->block[i0].noise_compand_setting,0,
  155762. setup->psy_noise_compand,
  155763. setup->psy_noise_compand_short_mapping);
  155764. vorbis_encode_compand_setup(vi,hi->block[1].noise_compand_setting,1,
  155765. setup->psy_noise_compand,
  155766. setup->psy_noise_compand_short_mapping);
  155767. if(!singleblock){
  155768. vorbis_encode_compand_setup(vi,hi->block[2].noise_compand_setting,2,
  155769. setup->psy_noise_compand,
  155770. setup->psy_noise_compand_long_mapping);
  155771. vorbis_encode_compand_setup(vi,hi->block[3].noise_compand_setting,3,
  155772. setup->psy_noise_compand,
  155773. setup->psy_noise_compand_long_mapping);
  155774. }
  155775. /* peak guarding setup */
  155776. vorbis_encode_peak_setup(vi,hi->block[i0].tone_peaklimit_setting,0,
  155777. setup->psy_tone_dBsuppress);
  155778. vorbis_encode_peak_setup(vi,hi->block[1].tone_peaklimit_setting,1,
  155779. setup->psy_tone_dBsuppress);
  155780. if(!singleblock){
  155781. vorbis_encode_peak_setup(vi,hi->block[2].tone_peaklimit_setting,2,
  155782. setup->psy_tone_dBsuppress);
  155783. vorbis_encode_peak_setup(vi,hi->block[3].tone_peaklimit_setting,3,
  155784. setup->psy_tone_dBsuppress);
  155785. }
  155786. /* noise bias setup */
  155787. vorbis_encode_noisebias_setup(vi,hi->block[i0].noise_bias_setting,0,
  155788. setup->psy_noise_dBsuppress,
  155789. setup->psy_noise_bias_impulse,
  155790. setup->psy_noiseguards,
  155791. (i0==0?hi->impulse_noisetune:0.));
  155792. vorbis_encode_noisebias_setup(vi,hi->block[1].noise_bias_setting,1,
  155793. setup->psy_noise_dBsuppress,
  155794. setup->psy_noise_bias_padding,
  155795. setup->psy_noiseguards,0.);
  155796. if(!singleblock){
  155797. vorbis_encode_noisebias_setup(vi,hi->block[2].noise_bias_setting,2,
  155798. setup->psy_noise_dBsuppress,
  155799. setup->psy_noise_bias_trans,
  155800. setup->psy_noiseguards,0.);
  155801. vorbis_encode_noisebias_setup(vi,hi->block[3].noise_bias_setting,3,
  155802. setup->psy_noise_dBsuppress,
  155803. setup->psy_noise_bias_long,
  155804. setup->psy_noiseguards,0.);
  155805. }
  155806. vorbis_encode_ath_setup(vi,0);
  155807. vorbis_encode_ath_setup(vi,1);
  155808. if(!singleblock){
  155809. vorbis_encode_ath_setup(vi,2);
  155810. vorbis_encode_ath_setup(vi,3);
  155811. }
  155812. vorbis_encode_map_n_res_setup(vi,hi->base_setting,setup->maps);
  155813. /* set bitrate readonlies and management */
  155814. if(hi->bitrate_av>0)
  155815. vi->bitrate_nominal=hi->bitrate_av;
  155816. else{
  155817. vi->bitrate_nominal=setting_to_approx_bitrate(vi);
  155818. }
  155819. vi->bitrate_lower=hi->bitrate_min;
  155820. vi->bitrate_upper=hi->bitrate_max;
  155821. if(hi->bitrate_av)
  155822. vi->bitrate_window=(double)hi->bitrate_reservoir/hi->bitrate_av;
  155823. else
  155824. vi->bitrate_window=0.;
  155825. if(hi->managed){
  155826. ci->bi.avg_rate=hi->bitrate_av;
  155827. ci->bi.min_rate=hi->bitrate_min;
  155828. ci->bi.max_rate=hi->bitrate_max;
  155829. ci->bi.reservoir_bits=hi->bitrate_reservoir;
  155830. ci->bi.reservoir_bias=
  155831. hi->bitrate_reservoir_bias;
  155832. ci->bi.slew_damp=hi->bitrate_av_damp;
  155833. }
  155834. return(0);
  155835. }
  155836. static int vorbis_encode_setup_setting(vorbis_info *vi,
  155837. long channels,
  155838. long rate){
  155839. int ret=0,i,is;
  155840. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155841. highlevel_encode_setup *hi=&ci->hi;
  155842. ve_setup_data_template *setup=(ve_setup_data_template*) hi->setup;
  155843. double ds;
  155844. ret=vorbis_encode_toplevel_setup(vi,channels,rate);
  155845. if(ret)return(ret);
  155846. is=hi->base_setting;
  155847. ds=hi->base_setting-is;
  155848. hi->short_setting=hi->base_setting;
  155849. hi->long_setting=hi->base_setting;
  155850. hi->managed=0;
  155851. hi->impulse_block_p=1;
  155852. hi->noise_normalize_p=1;
  155853. hi->stereo_point_setting=hi->base_setting;
  155854. hi->lowpass_kHz=
  155855. setup->psy_lowpass[is]*(1.-ds)+setup->psy_lowpass[is+1]*ds;
  155856. hi->ath_floating_dB=setup->psy_ath_float[is]*(1.-ds)+
  155857. setup->psy_ath_float[is+1]*ds;
  155858. hi->ath_absolute_dB=setup->psy_ath_abs[is]*(1.-ds)+
  155859. setup->psy_ath_abs[is+1]*ds;
  155860. hi->amplitude_track_dBpersec=-6.;
  155861. hi->trigger_setting=hi->base_setting;
  155862. for(i=0;i<4;i++){
  155863. hi->block[i].tone_mask_setting=hi->base_setting;
  155864. hi->block[i].tone_peaklimit_setting=hi->base_setting;
  155865. hi->block[i].noise_bias_setting=hi->base_setting;
  155866. hi->block[i].noise_compand_setting=hi->base_setting;
  155867. }
  155868. return(ret);
  155869. }
  155870. int vorbis_encode_setup_vbr(vorbis_info *vi,
  155871. long channels,
  155872. long rate,
  155873. float quality){
  155874. codec_setup_info *ci=(codec_setup_info*) vi->codec_setup;
  155875. highlevel_encode_setup *hi=&ci->hi;
  155876. quality+=.0000001;
  155877. if(quality>=1.)quality=.9999;
  155878. get_setup_template(vi,channels,rate,quality,0);
  155879. if(!hi->setup)return OV_EIMPL;
  155880. return vorbis_encode_setup_setting(vi,channels,rate);
  155881. }
  155882. int vorbis_encode_init_vbr(vorbis_info *vi,
  155883. long channels,
  155884. long rate,
  155885. float base_quality /* 0. to 1. */
  155886. ){
  155887. int ret=0;
  155888. ret=vorbis_encode_setup_vbr(vi,channels,rate,base_quality);
  155889. if(ret){
  155890. vorbis_info_clear(vi);
  155891. return ret;
  155892. }
  155893. ret=vorbis_encode_setup_init(vi);
  155894. if(ret)
  155895. vorbis_info_clear(vi);
  155896. return(ret);
  155897. }
  155898. int vorbis_encode_setup_managed(vorbis_info *vi,
  155899. long channels,
  155900. long rate,
  155901. long max_bitrate,
  155902. long nominal_bitrate,
  155903. long min_bitrate){
  155904. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155905. highlevel_encode_setup *hi=&ci->hi;
  155906. double tnominal=nominal_bitrate;
  155907. int ret=0;
  155908. if(nominal_bitrate<=0.){
  155909. if(max_bitrate>0.){
  155910. if(min_bitrate>0.)
  155911. nominal_bitrate=(max_bitrate+min_bitrate)*.5;
  155912. else
  155913. nominal_bitrate=max_bitrate*.875;
  155914. }else{
  155915. if(min_bitrate>0.){
  155916. nominal_bitrate=min_bitrate;
  155917. }else{
  155918. return(OV_EINVAL);
  155919. }
  155920. }
  155921. }
  155922. get_setup_template(vi,channels,rate,nominal_bitrate,1);
  155923. if(!hi->setup)return OV_EIMPL;
  155924. ret=vorbis_encode_setup_setting(vi,channels,rate);
  155925. if(ret){
  155926. vorbis_info_clear(vi);
  155927. return ret;
  155928. }
  155929. /* initialize management with sane defaults */
  155930. hi->managed=1;
  155931. hi->bitrate_min=min_bitrate;
  155932. hi->bitrate_max=max_bitrate;
  155933. hi->bitrate_av=tnominal;
  155934. hi->bitrate_av_damp=1.5f; /* full range in no less than 1.5 second */
  155935. hi->bitrate_reservoir=nominal_bitrate*2;
  155936. hi->bitrate_reservoir_bias=.1; /* bias toward hoarding bits */
  155937. return(ret);
  155938. }
  155939. int vorbis_encode_init(vorbis_info *vi,
  155940. long channels,
  155941. long rate,
  155942. long max_bitrate,
  155943. long nominal_bitrate,
  155944. long min_bitrate){
  155945. int ret=vorbis_encode_setup_managed(vi,channels,rate,
  155946. max_bitrate,
  155947. nominal_bitrate,
  155948. min_bitrate);
  155949. if(ret){
  155950. vorbis_info_clear(vi);
  155951. return(ret);
  155952. }
  155953. ret=vorbis_encode_setup_init(vi);
  155954. if(ret)
  155955. vorbis_info_clear(vi);
  155956. return(ret);
  155957. }
  155958. int vorbis_encode_ctl(vorbis_info *vi,int number,void *arg){
  155959. if(vi){
  155960. codec_setup_info *ci=(codec_setup_info*)vi->codec_setup;
  155961. highlevel_encode_setup *hi=&ci->hi;
  155962. int setp=(number&0xf); /* a read request has a low nibble of 0 */
  155963. if(setp && hi->set_in_stone)return(OV_EINVAL);
  155964. switch(number){
  155965. /* now deprecated *****************/
  155966. case OV_ECTL_RATEMANAGE_GET:
  155967. {
  155968. struct ovectl_ratemanage_arg *ai=
  155969. (struct ovectl_ratemanage_arg *)arg;
  155970. ai->management_active=hi->managed;
  155971. ai->bitrate_hard_window=ai->bitrate_av_window=
  155972. (double)hi->bitrate_reservoir/vi->rate;
  155973. ai->bitrate_av_window_center=1.;
  155974. ai->bitrate_hard_min=hi->bitrate_min;
  155975. ai->bitrate_hard_max=hi->bitrate_max;
  155976. ai->bitrate_av_lo=hi->bitrate_av;
  155977. ai->bitrate_av_hi=hi->bitrate_av;
  155978. }
  155979. return(0);
  155980. /* now deprecated *****************/
  155981. case OV_ECTL_RATEMANAGE_SET:
  155982. {
  155983. struct ovectl_ratemanage_arg *ai=
  155984. (struct ovectl_ratemanage_arg *)arg;
  155985. if(ai==NULL){
  155986. hi->managed=0;
  155987. }else{
  155988. hi->managed=ai->management_active;
  155989. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_AVG,arg);
  155990. vorbis_encode_ctl(vi,OV_ECTL_RATEMANAGE_HARD,arg);
  155991. }
  155992. }
  155993. return 0;
  155994. /* now deprecated *****************/
  155995. case OV_ECTL_RATEMANAGE_AVG:
  155996. {
  155997. struct ovectl_ratemanage_arg *ai=
  155998. (struct ovectl_ratemanage_arg *)arg;
  155999. if(ai==NULL){
  156000. hi->bitrate_av=0;
  156001. }else{
  156002. hi->bitrate_av=(ai->bitrate_av_lo+ai->bitrate_av_hi)*.5;
  156003. }
  156004. }
  156005. return(0);
  156006. /* now deprecated *****************/
  156007. case OV_ECTL_RATEMANAGE_HARD:
  156008. {
  156009. struct ovectl_ratemanage_arg *ai=
  156010. (struct ovectl_ratemanage_arg *)arg;
  156011. if(ai==NULL){
  156012. hi->bitrate_min=0;
  156013. hi->bitrate_max=0;
  156014. }else{
  156015. hi->bitrate_min=ai->bitrate_hard_min;
  156016. hi->bitrate_max=ai->bitrate_hard_max;
  156017. hi->bitrate_reservoir=ai->bitrate_hard_window*
  156018. (hi->bitrate_max+hi->bitrate_min)*.5;
  156019. }
  156020. if(hi->bitrate_reservoir<128.)
  156021. hi->bitrate_reservoir=128.;
  156022. }
  156023. return(0);
  156024. /* replacement ratemanage interface */
  156025. case OV_ECTL_RATEMANAGE2_GET:
  156026. {
  156027. struct ovectl_ratemanage2_arg *ai=
  156028. (struct ovectl_ratemanage2_arg *)arg;
  156029. if(ai==NULL)return OV_EINVAL;
  156030. ai->management_active=hi->managed;
  156031. ai->bitrate_limit_min_kbps=hi->bitrate_min/1000;
  156032. ai->bitrate_limit_max_kbps=hi->bitrate_max/1000;
  156033. ai->bitrate_average_kbps=hi->bitrate_av/1000;
  156034. ai->bitrate_average_damping=hi->bitrate_av_damp;
  156035. ai->bitrate_limit_reservoir_bits=hi->bitrate_reservoir;
  156036. ai->bitrate_limit_reservoir_bias=hi->bitrate_reservoir_bias;
  156037. }
  156038. return (0);
  156039. case OV_ECTL_RATEMANAGE2_SET:
  156040. {
  156041. struct ovectl_ratemanage2_arg *ai=
  156042. (struct ovectl_ratemanage2_arg *)arg;
  156043. if(ai==NULL){
  156044. hi->managed=0;
  156045. }else{
  156046. /* sanity check; only catch invariant violations */
  156047. if(ai->bitrate_limit_min_kbps>0 &&
  156048. ai->bitrate_average_kbps>0 &&
  156049. ai->bitrate_limit_min_kbps>ai->bitrate_average_kbps)
  156050. return OV_EINVAL;
  156051. if(ai->bitrate_limit_max_kbps>0 &&
  156052. ai->bitrate_average_kbps>0 &&
  156053. ai->bitrate_limit_max_kbps<ai->bitrate_average_kbps)
  156054. return OV_EINVAL;
  156055. if(ai->bitrate_limit_min_kbps>0 &&
  156056. ai->bitrate_limit_max_kbps>0 &&
  156057. ai->bitrate_limit_min_kbps>ai->bitrate_limit_max_kbps)
  156058. return OV_EINVAL;
  156059. if(ai->bitrate_average_damping <= 0.)
  156060. return OV_EINVAL;
  156061. if(ai->bitrate_limit_reservoir_bits < 0)
  156062. return OV_EINVAL;
  156063. if(ai->bitrate_limit_reservoir_bias < 0.)
  156064. return OV_EINVAL;
  156065. if(ai->bitrate_limit_reservoir_bias > 1.)
  156066. return OV_EINVAL;
  156067. hi->managed=ai->management_active;
  156068. hi->bitrate_min=ai->bitrate_limit_min_kbps * 1000;
  156069. hi->bitrate_max=ai->bitrate_limit_max_kbps * 1000;
  156070. hi->bitrate_av=ai->bitrate_average_kbps * 1000;
  156071. hi->bitrate_av_damp=ai->bitrate_average_damping;
  156072. hi->bitrate_reservoir=ai->bitrate_limit_reservoir_bits;
  156073. hi->bitrate_reservoir_bias=ai->bitrate_limit_reservoir_bias;
  156074. }
  156075. }
  156076. return 0;
  156077. case OV_ECTL_LOWPASS_GET:
  156078. {
  156079. double *farg=(double *)arg;
  156080. *farg=hi->lowpass_kHz;
  156081. }
  156082. return(0);
  156083. case OV_ECTL_LOWPASS_SET:
  156084. {
  156085. double *farg=(double *)arg;
  156086. hi->lowpass_kHz=*farg;
  156087. if(hi->lowpass_kHz<2.)hi->lowpass_kHz=2.;
  156088. if(hi->lowpass_kHz>99.)hi->lowpass_kHz=99.;
  156089. }
  156090. return(0);
  156091. case OV_ECTL_IBLOCK_GET:
  156092. {
  156093. double *farg=(double *)arg;
  156094. *farg=hi->impulse_noisetune;
  156095. }
  156096. return(0);
  156097. case OV_ECTL_IBLOCK_SET:
  156098. {
  156099. double *farg=(double *)arg;
  156100. hi->impulse_noisetune=*farg;
  156101. if(hi->impulse_noisetune>0.)hi->impulse_noisetune=0.;
  156102. if(hi->impulse_noisetune<-15.)hi->impulse_noisetune=-15.;
  156103. }
  156104. return(0);
  156105. }
  156106. return(OV_EIMPL);
  156107. }
  156108. return(OV_EINVAL);
  156109. }
  156110. #endif
  156111. /********* End of inlined file: vorbisenc.c *********/
  156112. /********* Start of inlined file: vorbisfile.c *********/
  156113. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  156114. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  156115. // tasks..
  156116. /********* Start of inlined file: juce_Config.h *********/
  156117. #ifndef __JUCE_CONFIG_JUCEHEADER__
  156118. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  156119. /*
  156120. This file contains macros that enable/disable various JUCE features.
  156121. */
  156122. /** The name of the namespace that all Juce classes and functions will be
  156123. put inside. If this is not defined, no namespace will be used.
  156124. */
  156125. #ifndef JUCE_NAMESPACE
  156126. #define JUCE_NAMESPACE juce
  156127. #endif
  156128. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  156129. but if you define this value, you can override this can force it to be true or
  156130. false.
  156131. */
  156132. #ifndef JUCE_FORCE_DEBUG
  156133. //#define JUCE_FORCE_DEBUG 1
  156134. #endif
  156135. /** If this flag is enabled, the the jassert and jassertfalse macros will
  156136. always use Logger::writeToLog() to write a message when an assertion happens.
  156137. Enabling it will also leave this turned on in release builds. When it's disabled,
  156138. however, the jassert and jassertfalse macros will not be compiled in a
  156139. release build.
  156140. @see jassert, jassertfalse, Logger
  156141. */
  156142. #ifndef JUCE_LOG_ASSERTIONS
  156143. // #define JUCE_LOG_ASSERTIONS 1
  156144. #endif
  156145. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  156146. which the ASIOAudioIODevice class can't be built. See the comments in the
  156147. ASIOAudioIODevice class's header file for more info about this.
  156148. (This only affects a Win32 build)
  156149. */
  156150. #ifndef JUCE_ASIO
  156151. #define JUCE_ASIO 1
  156152. #endif
  156153. /** Comment out this macro to disable building of ALSA device support on Linux.
  156154. */
  156155. #ifndef JUCE_ALSA
  156156. #define JUCE_ALSA 1
  156157. #endif
  156158. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  156159. have the SDK installed.
  156160. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  156161. classes will be unavailable.
  156162. On Windows, if you enable this, you'll need to have the QuickTime SDK
  156163. installed, and its header files will need to be on your include path.
  156164. */
  156165. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  156166. #define JUCE_QUICKTIME 1
  156167. #endif
  156168. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  156169. have the appropriate headers and libraries available. If it's not enabled, the
  156170. OpenGLComponent class will be unavailable.
  156171. */
  156172. #ifndef JUCE_OPENGL
  156173. #define JUCE_OPENGL 1
  156174. #endif
  156175. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  156176. If you're not going to need either of these formats, turn off the flags to
  156177. avoid bloating your codebase with them.
  156178. */
  156179. #ifndef JUCE_USE_FLAC
  156180. #define JUCE_USE_FLAC 1
  156181. #endif
  156182. #ifndef JUCE_USE_OGGVORBIS
  156183. #define JUCE_USE_OGGVORBIS 1
  156184. #endif
  156185. /** This flag lets you enable support for CD-burning. You might want to disable
  156186. it to build without the MS SDK under windows.
  156187. */
  156188. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  156189. #define JUCE_USE_CDBURNER 1
  156190. #endif
  156191. /** Enabling this macro means that all regions that get repainted will have a coloured
  156192. line drawn around them.
  156193. This is handy if you're trying to optimise drawing, because it lets you easily see
  156194. when anything is being repainted unnecessarily.
  156195. */
  156196. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  156197. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  156198. #endif
  156199. /** Enable this under Linux to use Xinerama for multi-monitor support.
  156200. */
  156201. #ifndef JUCE_USE_XINERAMA
  156202. #define JUCE_USE_XINERAMA 1
  156203. #endif
  156204. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  156205. */
  156206. #ifndef JUCE_USE_XSHM
  156207. #define JUCE_USE_XSHM 1
  156208. #endif
  156209. /** Enabling this builds support for VST audio plugins.
  156210. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  156211. */
  156212. #ifndef JUCE_PLUGINHOST_VST
  156213. // #define JUCE_PLUGINHOST_VST 1
  156214. #endif
  156215. /** Enabling this builds support for AudioUnit audio plugins.
  156216. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  156217. */
  156218. #ifndef JUCE_PLUGINHOST_AU
  156219. // #define JUCE_PLUGINHOST_AU 1
  156220. #endif
  156221. /** Disabling this will avoid linking to any UI code. This is handy for
  156222. writing command-line utilities, e.g. on linux boxes which don't have some
  156223. of the UI libraries installed.
  156224. (On mac and windows, this won't generally make much difference to the build).
  156225. */
  156226. #ifndef JUCE_BUILD_GUI_CLASSES
  156227. #define JUCE_BUILD_GUI_CLASSES 1
  156228. #endif
  156229. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  156230. */
  156231. #ifndef JUCE_WEB_BROWSER
  156232. #define JUCE_WEB_BROWSER 1
  156233. #endif
  156234. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  156235. codebase - you might need to use this if you're linking to some of these libraries
  156236. yourself.
  156237. */
  156238. #ifndef JUCE_INCLUDE_ZLIB_CODE
  156239. #define JUCE_INCLUDE_ZLIB_CODE 1
  156240. #endif
  156241. #ifndef JUCE_INCLUDE_FLAC_CODE
  156242. #define JUCE_INCLUDE_FLAC_CODE 1
  156243. #endif
  156244. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  156245. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  156246. #endif
  156247. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  156248. #define JUCE_INCLUDE_PNGLIB_CODE 1
  156249. #endif
  156250. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  156251. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  156252. #endif
  156253. /** Enable this to add extra memory-leak info to the new and delete operators.
  156254. (Currently, this only affects Windows builds in debug mode).
  156255. */
  156256. #ifndef JUCE_CHECK_MEMORY_LEAKS
  156257. #define JUCE_CHECK_MEMORY_LEAKS 1
  156258. #endif
  156259. /** Enable this to turn on juce's internal catching of exceptions.
  156260. Turning it off will avoid any exception catching. With it on, all exceptions
  156261. are passed to the JUCEApplication::unhandledException() callback for logging.
  156262. */
  156263. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  156264. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  156265. #endif
  156266. /** If this macro is set, the Juce String class will use unicode as its
  156267. internal representation. If it isn't set, it'll use ANSI.
  156268. */
  156269. #ifndef JUCE_STRINGS_ARE_UNICODE
  156270. #define JUCE_STRINGS_ARE_UNICODE 1
  156271. #endif
  156272. #endif
  156273. /********* End of inlined file: juce_Config.h *********/
  156274. #ifdef _MSC_VER
  156275. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  156276. #endif
  156277. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  156278. #if JUCE_USE_OGGVORBIS
  156279. #include <stdlib.h>
  156280. #include <stdio.h>
  156281. #include <errno.h>
  156282. #include <string.h>
  156283. #include <math.h>
  156284. /* A 'chained bitstream' is a Vorbis bitstream that contains more than
  156285. one logical bitstream arranged end to end (the only form of Ogg
  156286. multiplexing allowed in a Vorbis bitstream; grouping [parallel
  156287. multiplexing] is not allowed in Vorbis) */
  156288. /* A Vorbis file can be played beginning to end (streamed) without
  156289. worrying ahead of time about chaining (see decoder_example.c). If
  156290. we have the whole file, however, and want random access
  156291. (seeking/scrubbing) or desire to know the total length/time of a
  156292. file, we need to account for the possibility of chaining. */
  156293. /* We can handle things a number of ways; we can determine the entire
  156294. bitstream structure right off the bat, or find pieces on demand.
  156295. This example determines and caches structure for the entire
  156296. bitstream, but builds a virtual decoder on the fly when moving
  156297. between links in the chain. */
  156298. /* There are also different ways to implement seeking. Enough
  156299. information exists in an Ogg bitstream to seek to
  156300. sample-granularity positions in the output. Or, one can seek by
  156301. picking some portion of the stream roughly in the desired area if
  156302. we only want coarse navigation through the stream. */
  156303. /*************************************************************************
  156304. * Many, many internal helpers. The intention is not to be confusing;
  156305. * rampant duplication and monolithic function implementation would be
  156306. * harder to understand anyway. The high level functions are last. Begin
  156307. * grokking near the end of the file */
  156308. /* read a little more data from the file/pipe into the ogg_sync framer
  156309. */
  156310. #define CHUNKSIZE 8500 /* a shade over 8k; anyone using pages well
  156311. over 8k gets what they deserve */
  156312. static long _get_data(OggVorbis_File *vf){
  156313. errno=0;
  156314. if(vf->datasource){
  156315. char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
  156316. long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
  156317. if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
  156318. if(bytes==0 && errno)return(-1);
  156319. return(bytes);
  156320. }else
  156321. return(0);
  156322. }
  156323. /* save a tiny smidge of verbosity to make the code more readable */
  156324. static void _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
  156325. if(vf->datasource){
  156326. (vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET);
  156327. vf->offset=offset;
  156328. ogg_sync_reset(&vf->oy);
  156329. }else{
  156330. /* shouldn't happen unless someone writes a broken callback */
  156331. return;
  156332. }
  156333. }
  156334. /* The read/seek functions track absolute position within the stream */
  156335. /* from the head of the stream, get the next page. boundary specifies
  156336. if the function is allowed to fetch more data from the stream (and
  156337. how much) or only use internally buffered data.
  156338. boundary: -1) unbounded search
  156339. 0) read no additional data; use cached only
  156340. n) search for a new page beginning for n bytes
  156341. return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
  156342. n) found a page at absolute offset n */
  156343. static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
  156344. ogg_int64_t boundary){
  156345. if(boundary>0)boundary+=vf->offset;
  156346. while(1){
  156347. long more;
  156348. if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
  156349. more=ogg_sync_pageseek(&vf->oy,og);
  156350. if(more<0){
  156351. /* skipped n bytes */
  156352. vf->offset-=more;
  156353. }else{
  156354. if(more==0){
  156355. /* send more paramedics */
  156356. if(!boundary)return(OV_FALSE);
  156357. {
  156358. long ret=_get_data(vf);
  156359. if(ret==0)return(OV_EOF);
  156360. if(ret<0)return(OV_EREAD);
  156361. }
  156362. }else{
  156363. /* got a page. Return the offset at the page beginning,
  156364. advance the internal offset past the page end */
  156365. ogg_int64_t ret=vf->offset;
  156366. vf->offset+=more;
  156367. return(ret);
  156368. }
  156369. }
  156370. }
  156371. }
  156372. /* find the latest page beginning before the current stream cursor
  156373. position. Much dirtier than the above as Ogg doesn't have any
  156374. backward search linkage. no 'readp' as it will certainly have to
  156375. read. */
  156376. /* returns offset or OV_EREAD, OV_FAULT */
  156377. static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
  156378. ogg_int64_t begin=vf->offset;
  156379. ogg_int64_t end=begin;
  156380. ogg_int64_t ret;
  156381. ogg_int64_t offset=-1;
  156382. while(offset==-1){
  156383. begin-=CHUNKSIZE;
  156384. if(begin<0)
  156385. begin=0;
  156386. _seek_helper(vf,begin);
  156387. while(vf->offset<end){
  156388. ret=_get_next_page(vf,og,end-vf->offset);
  156389. if(ret==OV_EREAD)return(OV_EREAD);
  156390. if(ret<0){
  156391. break;
  156392. }else{
  156393. offset=ret;
  156394. }
  156395. }
  156396. }
  156397. /* we have the offset. Actually snork and hold the page now */
  156398. _seek_helper(vf,offset);
  156399. ret=_get_next_page(vf,og,CHUNKSIZE);
  156400. if(ret<0)
  156401. /* this shouldn't be possible */
  156402. return(OV_EFAULT);
  156403. return(offset);
  156404. }
  156405. /* finds each bitstream link one at a time using a bisection search
  156406. (has to begin by knowing the offset of the lb's initial page).
  156407. Recurses for each link so it can alloc the link storage after
  156408. finding them all, then unroll and fill the cache at the same time */
  156409. static int _bisect_forward_serialno(OggVorbis_File *vf,
  156410. ogg_int64_t begin,
  156411. ogg_int64_t searched,
  156412. ogg_int64_t end,
  156413. long currentno,
  156414. long m){
  156415. ogg_int64_t endsearched=end;
  156416. ogg_int64_t next=end;
  156417. ogg_page og;
  156418. ogg_int64_t ret;
  156419. /* the below guards against garbage seperating the last and
  156420. first pages of two links. */
  156421. while(searched<endsearched){
  156422. ogg_int64_t bisect;
  156423. if(endsearched-searched<CHUNKSIZE){
  156424. bisect=searched;
  156425. }else{
  156426. bisect=(searched+endsearched)/2;
  156427. }
  156428. _seek_helper(vf,bisect);
  156429. ret=_get_next_page(vf,&og,-1);
  156430. if(ret==OV_EREAD)return(OV_EREAD);
  156431. if(ret<0 || ogg_page_serialno(&og)!=currentno){
  156432. endsearched=bisect;
  156433. if(ret>=0)next=ret;
  156434. }else{
  156435. searched=ret+og.header_len+og.body_len;
  156436. }
  156437. }
  156438. _seek_helper(vf,next);
  156439. ret=_get_next_page(vf,&og,-1);
  156440. if(ret==OV_EREAD)return(OV_EREAD);
  156441. if(searched>=end || ret<0){
  156442. vf->links=m+1;
  156443. vf->offsets=(ogg_int64_t*)_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
  156444. vf->serialnos=(long*)_ogg_malloc(vf->links*sizeof(*vf->serialnos));
  156445. vf->offsets[m+1]=searched;
  156446. }else{
  156447. ret=_bisect_forward_serialno(vf,next,vf->offset,
  156448. end,ogg_page_serialno(&og),m+1);
  156449. if(ret==OV_EREAD)return(OV_EREAD);
  156450. }
  156451. vf->offsets[m]=begin;
  156452. vf->serialnos[m]=currentno;
  156453. return(0);
  156454. }
  156455. /* uses the local ogg_stream storage in vf; this is important for
  156456. non-streaming input sources */
  156457. static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
  156458. long *serialno,ogg_page *og_ptr){
  156459. ogg_page og;
  156460. ogg_packet op;
  156461. int i,ret;
  156462. if(!og_ptr){
  156463. ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
  156464. if(llret==OV_EREAD)return(OV_EREAD);
  156465. if(llret<0)return OV_ENOTVORBIS;
  156466. og_ptr=&og;
  156467. }
  156468. ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
  156469. if(serialno)*serialno=vf->os.serialno;
  156470. vf->ready_state=STREAMSET;
  156471. /* extract the initial header from the first page and verify that the
  156472. Ogg bitstream is in fact Vorbis data */
  156473. vorbis_info_init(vi);
  156474. vorbis_comment_init(vc);
  156475. i=0;
  156476. while(i<3){
  156477. ogg_stream_pagein(&vf->os,og_ptr);
  156478. while(i<3){
  156479. int result=ogg_stream_packetout(&vf->os,&op);
  156480. if(result==0)break;
  156481. if(result==-1){
  156482. ret=OV_EBADHEADER;
  156483. goto bail_header;
  156484. }
  156485. if((ret=vorbis_synthesis_headerin(vi,vc,&op))){
  156486. goto bail_header;
  156487. }
  156488. i++;
  156489. }
  156490. if(i<3)
  156491. if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
  156492. ret=OV_EBADHEADER;
  156493. goto bail_header;
  156494. }
  156495. }
  156496. return 0;
  156497. bail_header:
  156498. vorbis_info_clear(vi);
  156499. vorbis_comment_clear(vc);
  156500. vf->ready_state=OPENED;
  156501. return ret;
  156502. }
  156503. /* last step of the OggVorbis_File initialization; get all the
  156504. vorbis_info structs and PCM positions. Only called by the seekable
  156505. initialization (local stream storage is hacked slightly; pay
  156506. attention to how that's done) */
  156507. /* this is void and does not propogate errors up because we want to be
  156508. able to open and use damaged bitstreams as well as we can. Just
  156509. watch out for missing information for links in the OggVorbis_File
  156510. struct */
  156511. static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
  156512. ogg_page og;
  156513. int i;
  156514. ogg_int64_t ret;
  156515. vf->vi=(vorbis_info*) _ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
  156516. vf->vc=(vorbis_comment*) _ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
  156517. vf->dataoffsets=(ogg_int64_t*) _ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
  156518. vf->pcmlengths=(ogg_int64_t*) _ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
  156519. for(i=0;i<vf->links;i++){
  156520. if(i==0){
  156521. /* we already grabbed the initial header earlier. Just set the offset */
  156522. vf->dataoffsets[i]=dataoffset;
  156523. _seek_helper(vf,dataoffset);
  156524. }else{
  156525. /* seek to the location of the initial header */
  156526. _seek_helper(vf,vf->offsets[i]);
  156527. if(_fetch_headers(vf,vf->vi+i,vf->vc+i,NULL,NULL)<0){
  156528. vf->dataoffsets[i]=-1;
  156529. }else{
  156530. vf->dataoffsets[i]=vf->offset;
  156531. }
  156532. }
  156533. /* fetch beginning PCM offset */
  156534. if(vf->dataoffsets[i]!=-1){
  156535. ogg_int64_t accumulated=0;
  156536. long lastblock=-1;
  156537. int result;
  156538. ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
  156539. while(1){
  156540. ogg_packet op;
  156541. ret=_get_next_page(vf,&og,-1);
  156542. if(ret<0)
  156543. /* this should not be possible unless the file is
  156544. truncated/mangled */
  156545. break;
  156546. if(ogg_page_serialno(&og)!=vf->serialnos[i])
  156547. break;
  156548. /* count blocksizes of all frames in the page */
  156549. ogg_stream_pagein(&vf->os,&og);
  156550. while((result=ogg_stream_packetout(&vf->os,&op))){
  156551. if(result>0){ /* ignore holes */
  156552. long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
  156553. if(lastblock!=-1)
  156554. accumulated+=(lastblock+thisblock)>>2;
  156555. lastblock=thisblock;
  156556. }
  156557. }
  156558. if(ogg_page_granulepos(&og)!=-1){
  156559. /* pcm offset of last packet on the first audio page */
  156560. accumulated= ogg_page_granulepos(&og)-accumulated;
  156561. break;
  156562. }
  156563. }
  156564. /* less than zero? This is a stream with samples trimmed off
  156565. the beginning, a normal occurrence; set the offset to zero */
  156566. if(accumulated<0)accumulated=0;
  156567. vf->pcmlengths[i*2]=accumulated;
  156568. }
  156569. /* get the PCM length of this link. To do this,
  156570. get the last page of the stream */
  156571. {
  156572. ogg_int64_t end=vf->offsets[i+1];
  156573. _seek_helper(vf,end);
  156574. while(1){
  156575. ret=_get_prev_page(vf,&og);
  156576. if(ret<0){
  156577. /* this should not be possible */
  156578. vorbis_info_clear(vf->vi+i);
  156579. vorbis_comment_clear(vf->vc+i);
  156580. break;
  156581. }
  156582. if(ogg_page_granulepos(&og)!=-1){
  156583. vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
  156584. break;
  156585. }
  156586. vf->offset=ret;
  156587. }
  156588. }
  156589. }
  156590. }
  156591. static int _make_decode_ready(OggVorbis_File *vf){
  156592. if(vf->ready_state>STREAMSET)return 0;
  156593. if(vf->ready_state<STREAMSET)return OV_EFAULT;
  156594. if(vf->seekable){
  156595. if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
  156596. return OV_EBADLINK;
  156597. }else{
  156598. if(vorbis_synthesis_init(&vf->vd,vf->vi))
  156599. return OV_EBADLINK;
  156600. }
  156601. vorbis_block_init(&vf->vd,&vf->vb);
  156602. vf->ready_state=INITSET;
  156603. vf->bittrack=0.f;
  156604. vf->samptrack=0.f;
  156605. return 0;
  156606. }
  156607. static int _open_seekable2(OggVorbis_File *vf){
  156608. long serialno=vf->current_serialno;
  156609. ogg_int64_t dataoffset=vf->offset, end;
  156610. ogg_page og;
  156611. /* we're partially open and have a first link header state in
  156612. storage in vf */
  156613. /* we can seek, so set out learning all about this file */
  156614. (vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
  156615. vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
  156616. /* We get the offset for the last page of the physical bitstream.
  156617. Most OggVorbis files will contain a single logical bitstream */
  156618. end=_get_prev_page(vf,&og);
  156619. if(end<0)return(end);
  156620. /* more than one logical bitstream? */
  156621. if(ogg_page_serialno(&og)!=serialno){
  156622. /* Chained bitstream. Bisect-search each logical bitstream
  156623. section. Do so based on serial number only */
  156624. if(_bisect_forward_serialno(vf,0,0,end+1,serialno,0)<0)return(OV_EREAD);
  156625. }else{
  156626. /* Only one logical bitstream */
  156627. if(_bisect_forward_serialno(vf,0,end,end+1,serialno,0))return(OV_EREAD);
  156628. }
  156629. /* the initial header memory is referenced by vf after; don't free it */
  156630. _prefetch_all_headers(vf,dataoffset);
  156631. return(ov_raw_seek(vf,0));
  156632. }
  156633. /* clear out the current logical bitstream decoder */
  156634. static void _decode_clear(OggVorbis_File *vf){
  156635. vorbis_dsp_clear(&vf->vd);
  156636. vorbis_block_clear(&vf->vb);
  156637. vf->ready_state=OPENED;
  156638. }
  156639. /* fetch and process a packet. Handles the case where we're at a
  156640. bitstream boundary and dumps the decoding machine. If the decoding
  156641. machine is unloaded, it loads it. It also keeps pcm_offset up to
  156642. date (seek and read both use this. seek uses a special hack with
  156643. readp).
  156644. return: <0) error, OV_HOLE (lost packet) or OV_EOF
  156645. 0) need more data (only if readp==0)
  156646. 1) got a packet
  156647. */
  156648. static int _fetch_and_process_packet(OggVorbis_File *vf,
  156649. ogg_packet *op_in,
  156650. int readp,
  156651. int spanp){
  156652. ogg_page og;
  156653. /* handle one packet. Try to fetch it from current stream state */
  156654. /* extract packets from page */
  156655. while(1){
  156656. /* process a packet if we can. If the machine isn't loaded,
  156657. neither is a page */
  156658. if(vf->ready_state==INITSET){
  156659. while(1) {
  156660. ogg_packet op;
  156661. ogg_packet *op_ptr=(op_in?op_in:&op);
  156662. int result=ogg_stream_packetout(&vf->os,op_ptr);
  156663. ogg_int64_t granulepos;
  156664. op_in=NULL;
  156665. if(result==-1)return(OV_HOLE); /* hole in the data. */
  156666. if(result>0){
  156667. /* got a packet. process it */
  156668. granulepos=op_ptr->granulepos;
  156669. if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
  156670. header handling. The
  156671. header packets aren't
  156672. audio, so if/when we
  156673. submit them,
  156674. vorbis_synthesis will
  156675. reject them */
  156676. /* suck in the synthesis data and track bitrate */
  156677. {
  156678. int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156679. /* for proper use of libvorbis within libvorbisfile,
  156680. oldsamples will always be zero. */
  156681. if(oldsamples)return(OV_EFAULT);
  156682. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  156683. vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
  156684. vf->bittrack+=op_ptr->bytes*8;
  156685. }
  156686. /* update the pcm offset. */
  156687. if(granulepos!=-1 && !op_ptr->e_o_s){
  156688. int link=(vf->seekable?vf->current_link:0);
  156689. int i,samples;
  156690. /* this packet has a pcm_offset on it (the last packet
  156691. completed on a page carries the offset) After processing
  156692. (above), we know the pcm position of the *last* sample
  156693. ready to be returned. Find the offset of the *first*
  156694. As an aside, this trick is inaccurate if we begin
  156695. reading anew right at the last page; the end-of-stream
  156696. granulepos declares the last frame in the stream, and the
  156697. last packet of the last page may be a partial frame.
  156698. So, we need a previous granulepos from an in-sequence page
  156699. to have a reference point. Thus the !op_ptr->e_o_s clause
  156700. above */
  156701. if(vf->seekable && link>0)
  156702. granulepos-=vf->pcmlengths[link*2];
  156703. if(granulepos<0)granulepos=0; /* actually, this
  156704. shouldn't be possible
  156705. here unless the stream
  156706. is very broken */
  156707. samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  156708. granulepos-=samples;
  156709. for(i=0;i<link;i++)
  156710. granulepos+=vf->pcmlengths[i*2+1];
  156711. vf->pcm_offset=granulepos;
  156712. }
  156713. return(1);
  156714. }
  156715. }
  156716. else
  156717. break;
  156718. }
  156719. }
  156720. if(vf->ready_state>=OPENED){
  156721. ogg_int64_t ret;
  156722. if(!readp)return(0);
  156723. if((ret=_get_next_page(vf,&og,-1))<0){
  156724. return(OV_EOF); /* eof.
  156725. leave unitialized */
  156726. }
  156727. /* bitrate tracking; add the header's bytes here, the body bytes
  156728. are done by packet above */
  156729. vf->bittrack+=og.header_len*8;
  156730. /* has our decoding just traversed a bitstream boundary? */
  156731. if(vf->ready_state==INITSET){
  156732. if(vf->current_serialno!=ogg_page_serialno(&og)){
  156733. if(!spanp)
  156734. return(OV_EOF);
  156735. _decode_clear(vf);
  156736. if(!vf->seekable){
  156737. vorbis_info_clear(vf->vi);
  156738. vorbis_comment_clear(vf->vc);
  156739. }
  156740. }
  156741. }
  156742. }
  156743. /* Do we need to load a new machine before submitting the page? */
  156744. /* This is different in the seekable and non-seekable cases.
  156745. In the seekable case, we already have all the header
  156746. information loaded and cached; we just initialize the machine
  156747. with it and continue on our merry way.
  156748. In the non-seekable (streaming) case, we'll only be at a
  156749. boundary if we just left the previous logical bitstream and
  156750. we're now nominally at the header of the next bitstream
  156751. */
  156752. if(vf->ready_state!=INITSET){
  156753. int link;
  156754. if(vf->ready_state<STREAMSET){
  156755. if(vf->seekable){
  156756. vf->current_serialno=ogg_page_serialno(&og);
  156757. /* match the serialno to bitstream section. We use this rather than
  156758. offset positions to avoid problems near logical bitstream
  156759. boundaries */
  156760. for(link=0;link<vf->links;link++)
  156761. if(vf->serialnos[link]==vf->current_serialno)break;
  156762. if(link==vf->links)return(OV_EBADLINK); /* sign of a bogus
  156763. stream. error out,
  156764. leave machine
  156765. uninitialized */
  156766. vf->current_link=link;
  156767. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  156768. vf->ready_state=STREAMSET;
  156769. }else{
  156770. /* we're streaming */
  156771. /* fetch the three header packets, build the info struct */
  156772. int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
  156773. if(ret)return(ret);
  156774. vf->current_link++;
  156775. link=0;
  156776. }
  156777. }
  156778. {
  156779. int ret=_make_decode_ready(vf);
  156780. if(ret<0)return ret;
  156781. }
  156782. }
  156783. ogg_stream_pagein(&vf->os,&og);
  156784. }
  156785. }
  156786. /* if, eg, 64 bit stdio is configured by default, this will build with
  156787. fseek64 */
  156788. static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
  156789. if(f==NULL)return(-1);
  156790. return fseek(f,off,whence);
  156791. }
  156792. static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
  156793. long ibytes, ov_callbacks callbacks){
  156794. int offsettest=(f?callbacks.seek_func(f,0,SEEK_CUR):-1);
  156795. int ret;
  156796. memset(vf,0,sizeof(*vf));
  156797. vf->datasource=f;
  156798. vf->callbacks = callbacks;
  156799. /* init the framing state */
  156800. ogg_sync_init(&vf->oy);
  156801. /* perhaps some data was previously read into a buffer for testing
  156802. against other stream types. Allow initialization from this
  156803. previously read data (as we may be reading from a non-seekable
  156804. stream) */
  156805. if(initial){
  156806. char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
  156807. memcpy(buffer,initial,ibytes);
  156808. ogg_sync_wrote(&vf->oy,ibytes);
  156809. }
  156810. /* can we seek? Stevens suggests the seek test was portable */
  156811. if(offsettest!=-1)vf->seekable=1;
  156812. /* No seeking yet; Set up a 'single' (current) logical bitstream
  156813. entry for partial open */
  156814. vf->links=1;
  156815. vf->vi=(vorbis_info*) _ogg_calloc(vf->links,sizeof(*vf->vi));
  156816. vf->vc=(vorbis_comment*) _ogg_calloc(vf->links,sizeof(*vf->vc));
  156817. ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
  156818. /* Try to fetch the headers, maintaining all the storage */
  156819. if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
  156820. vf->datasource=NULL;
  156821. ov_clear(vf);
  156822. }else
  156823. vf->ready_state=PARTOPEN;
  156824. return(ret);
  156825. }
  156826. static int _ov_open2(OggVorbis_File *vf){
  156827. if(vf->ready_state != PARTOPEN) return OV_EINVAL;
  156828. vf->ready_state=OPENED;
  156829. if(vf->seekable){
  156830. int ret=_open_seekable2(vf);
  156831. if(ret){
  156832. vf->datasource=NULL;
  156833. ov_clear(vf);
  156834. }
  156835. return(ret);
  156836. }else
  156837. vf->ready_state=STREAMSET;
  156838. return 0;
  156839. }
  156840. /* clear out the OggVorbis_File struct */
  156841. int ov_clear(OggVorbis_File *vf){
  156842. if(vf){
  156843. vorbis_block_clear(&vf->vb);
  156844. vorbis_dsp_clear(&vf->vd);
  156845. ogg_stream_clear(&vf->os);
  156846. if(vf->vi && vf->links){
  156847. int i;
  156848. for(i=0;i<vf->links;i++){
  156849. vorbis_info_clear(vf->vi+i);
  156850. vorbis_comment_clear(vf->vc+i);
  156851. }
  156852. _ogg_free(vf->vi);
  156853. _ogg_free(vf->vc);
  156854. }
  156855. if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
  156856. if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
  156857. if(vf->serialnos)_ogg_free(vf->serialnos);
  156858. if(vf->offsets)_ogg_free(vf->offsets);
  156859. ogg_sync_clear(&vf->oy);
  156860. if(vf->datasource)(vf->callbacks.close_func)(vf->datasource);
  156861. memset(vf,0,sizeof(*vf));
  156862. }
  156863. #ifdef DEBUG_LEAKS
  156864. _VDBG_dump();
  156865. #endif
  156866. return(0);
  156867. }
  156868. /* inspects the OggVorbis file and finds/documents all the logical
  156869. bitstreams contained in it. Tries to be tolerant of logical
  156870. bitstream sections that are truncated/woogie.
  156871. return: -1) error
  156872. 0) OK
  156873. */
  156874. int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156875. ov_callbacks callbacks){
  156876. int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
  156877. if(ret)return ret;
  156878. return _ov_open2(vf);
  156879. }
  156880. int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156881. ov_callbacks callbacks = {
  156882. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156883. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156884. (int (*)(void *)) fclose,
  156885. (long (*)(void *)) ftell
  156886. };
  156887. return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156888. }
  156889. /* cheap hack for game usage where downsampling is desirable; there's
  156890. no need for SRC as we can just do it cheaply in libvorbis. */
  156891. int ov_halfrate(OggVorbis_File *vf,int flag){
  156892. int i;
  156893. if(vf->vi==NULL)return OV_EINVAL;
  156894. if(!vf->seekable)return OV_EINVAL;
  156895. if(vf->ready_state>=STREAMSET)
  156896. _decode_clear(vf); /* clear out stream state; later on libvorbis
  156897. will be able to swap this on the fly, but
  156898. for now dumping the decode machine is needed
  156899. to reinit the MDCT lookups. 1.1 libvorbis
  156900. is planned to be able to switch on the fly */
  156901. for(i=0;i<vf->links;i++){
  156902. if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
  156903. ov_halfrate(vf,0);
  156904. return OV_EINVAL;
  156905. }
  156906. }
  156907. return 0;
  156908. }
  156909. int ov_halfrate_p(OggVorbis_File *vf){
  156910. if(vf->vi==NULL)return OV_EINVAL;
  156911. return vorbis_synthesis_halfrate_p(vf->vi);
  156912. }
  156913. /* Only partially open the vorbis file; test for Vorbisness, and load
  156914. the headers for the first chain. Do not seek (although test for
  156915. seekability). Use ov_test_open to finish opening the file, else
  156916. ov_clear to close/free it. Same return codes as open. */
  156917. int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
  156918. ov_callbacks callbacks)
  156919. {
  156920. return _ov_open1(f,vf,initial,ibytes,callbacks);
  156921. }
  156922. int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
  156923. ov_callbacks callbacks = {
  156924. (size_t (*)(void *, size_t, size_t, void *)) fread,
  156925. (int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
  156926. (int (*)(void *)) fclose,
  156927. (long (*)(void *)) ftell
  156928. };
  156929. return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
  156930. }
  156931. int ov_test_open(OggVorbis_File *vf){
  156932. if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
  156933. return _ov_open2(vf);
  156934. }
  156935. /* How many logical bitstreams in this physical bitstream? */
  156936. long ov_streams(OggVorbis_File *vf){
  156937. return vf->links;
  156938. }
  156939. /* Is the FILE * associated with vf seekable? */
  156940. long ov_seekable(OggVorbis_File *vf){
  156941. return vf->seekable;
  156942. }
  156943. /* returns the bitrate for a given logical bitstream or the entire
  156944. physical bitstream. If the file is open for random access, it will
  156945. find the *actual* average bitrate. If the file is streaming, it
  156946. returns the nominal bitrate (if set) else the average of the
  156947. upper/lower bounds (if set) else -1 (unset).
  156948. If you want the actual bitrate field settings, get them from the
  156949. vorbis_info structs */
  156950. long ov_bitrate(OggVorbis_File *vf,int i){
  156951. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156952. if(i>=vf->links)return(OV_EINVAL);
  156953. if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
  156954. if(i<0){
  156955. ogg_int64_t bits=0;
  156956. int i;
  156957. float br;
  156958. for(i=0;i<vf->links;i++)
  156959. bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
  156960. /* This once read: return(rint(bits/ov_time_total(vf,-1)));
  156961. * gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
  156962. * so this is slightly transformed to make it work.
  156963. */
  156964. br = bits/ov_time_total(vf,-1);
  156965. return(rint(br));
  156966. }else{
  156967. if(vf->seekable){
  156968. /* return the actual bitrate */
  156969. return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
  156970. }else{
  156971. /* return nominal if set */
  156972. if(vf->vi[i].bitrate_nominal>0){
  156973. return vf->vi[i].bitrate_nominal;
  156974. }else{
  156975. if(vf->vi[i].bitrate_upper>0){
  156976. if(vf->vi[i].bitrate_lower>0){
  156977. return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
  156978. }else{
  156979. return vf->vi[i].bitrate_upper;
  156980. }
  156981. }
  156982. return(OV_FALSE);
  156983. }
  156984. }
  156985. }
  156986. }
  156987. /* returns the actual bitrate since last call. returns -1 if no
  156988. additional data to offer since last call (or at beginning of stream),
  156989. EINVAL if stream is only partially open
  156990. */
  156991. long ov_bitrate_instant(OggVorbis_File *vf){
  156992. int link=(vf->seekable?vf->current_link:0);
  156993. long ret;
  156994. if(vf->ready_state<OPENED)return(OV_EINVAL);
  156995. if(vf->samptrack==0)return(OV_FALSE);
  156996. ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
  156997. vf->bittrack=0.f;
  156998. vf->samptrack=0.f;
  156999. return(ret);
  157000. }
  157001. /* Guess */
  157002. long ov_serialnumber(OggVorbis_File *vf,int i){
  157003. if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
  157004. if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
  157005. if(i<0){
  157006. return(vf->current_serialno);
  157007. }else{
  157008. return(vf->serialnos[i]);
  157009. }
  157010. }
  157011. /* returns: total raw (compressed) length of content if i==-1
  157012. raw (compressed) length of that logical bitstream for i==0 to n
  157013. OV_EINVAL if the stream is not seekable (we can't know the length)
  157014. or if stream is only partially open
  157015. */
  157016. ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
  157017. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157018. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  157019. if(i<0){
  157020. ogg_int64_t acc=0;
  157021. int i;
  157022. for(i=0;i<vf->links;i++)
  157023. acc+=ov_raw_total(vf,i);
  157024. return(acc);
  157025. }else{
  157026. return(vf->offsets[i+1]-vf->offsets[i]);
  157027. }
  157028. }
  157029. /* returns: total PCM length (samples) of content if i==-1 PCM length
  157030. (samples) of that logical bitstream for i==0 to n
  157031. OV_EINVAL if the stream is not seekable (we can't know the
  157032. length) or only partially open
  157033. */
  157034. ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
  157035. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157036. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  157037. if(i<0){
  157038. ogg_int64_t acc=0;
  157039. int i;
  157040. for(i=0;i<vf->links;i++)
  157041. acc+=ov_pcm_total(vf,i);
  157042. return(acc);
  157043. }else{
  157044. return(vf->pcmlengths[i*2+1]);
  157045. }
  157046. }
  157047. /* returns: total seconds of content if i==-1
  157048. seconds in that logical bitstream for i==0 to n
  157049. OV_EINVAL if the stream is not seekable (we can't know the
  157050. length) or only partially open
  157051. */
  157052. double ov_time_total(OggVorbis_File *vf,int i){
  157053. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157054. if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
  157055. if(i<0){
  157056. double acc=0;
  157057. int i;
  157058. for(i=0;i<vf->links;i++)
  157059. acc+=ov_time_total(vf,i);
  157060. return(acc);
  157061. }else{
  157062. return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
  157063. }
  157064. }
  157065. /* seek to an offset relative to the *compressed* data. This also
  157066. scans packets to update the PCM cursor. It will cross a logical
  157067. bitstream boundary, but only if it can't get any packets out of the
  157068. tail of the bitstream we seek to (so no surprises).
  157069. returns zero on success, nonzero on failure */
  157070. int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
  157071. ogg_stream_state work_os;
  157072. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157073. if(!vf->seekable)
  157074. return(OV_ENOSEEK); /* don't dump machine if we can't seek */
  157075. if(pos<0 || pos>vf->end)return(OV_EINVAL);
  157076. /* don't yet clear out decoding machine (if it's initialized), in
  157077. the case we're in the same link. Restart the decode lapping, and
  157078. let _fetch_and_process_packet deal with a potential bitstream
  157079. boundary */
  157080. vf->pcm_offset=-1;
  157081. ogg_stream_reset_serialno(&vf->os,
  157082. vf->current_serialno); /* must set serialno */
  157083. vorbis_synthesis_restart(&vf->vd);
  157084. _seek_helper(vf,pos);
  157085. /* we need to make sure the pcm_offset is set, but we don't want to
  157086. advance the raw cursor past good packets just to get to the first
  157087. with a granulepos. That's not equivalent behavior to beginning
  157088. decoding as immediately after the seek position as possible.
  157089. So, a hack. We use two stream states; a local scratch state and
  157090. the shared vf->os stream state. We use the local state to
  157091. scan, and the shared state as a buffer for later decode.
  157092. Unfortuantely, on the last page we still advance to last packet
  157093. because the granulepos on the last page is not necessarily on a
  157094. packet boundary, and we need to make sure the granpos is
  157095. correct.
  157096. */
  157097. {
  157098. ogg_page og;
  157099. ogg_packet op;
  157100. int lastblock=0;
  157101. int accblock=0;
  157102. int thisblock;
  157103. int eosflag;
  157104. ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
  157105. ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
  157106. return from not necessarily
  157107. starting from the beginning */
  157108. while(1){
  157109. if(vf->ready_state>=STREAMSET){
  157110. /* snarf/scan a packet if we can */
  157111. int result=ogg_stream_packetout(&work_os,&op);
  157112. if(result>0){
  157113. if(vf->vi[vf->current_link].codec_setup){
  157114. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  157115. if(thisblock<0){
  157116. ogg_stream_packetout(&vf->os,NULL);
  157117. thisblock=0;
  157118. }else{
  157119. if(eosflag)
  157120. ogg_stream_packetout(&vf->os,NULL);
  157121. else
  157122. if(lastblock)accblock+=(lastblock+thisblock)>>2;
  157123. }
  157124. if(op.granulepos!=-1){
  157125. int i,link=vf->current_link;
  157126. ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
  157127. if(granulepos<0)granulepos=0;
  157128. for(i=0;i<link;i++)
  157129. granulepos+=vf->pcmlengths[i*2+1];
  157130. vf->pcm_offset=granulepos-accblock;
  157131. break;
  157132. }
  157133. lastblock=thisblock;
  157134. continue;
  157135. }else
  157136. ogg_stream_packetout(&vf->os,NULL);
  157137. }
  157138. }
  157139. if(!lastblock){
  157140. if(_get_next_page(vf,&og,-1)<0){
  157141. vf->pcm_offset=ov_pcm_total(vf,-1);
  157142. break;
  157143. }
  157144. }else{
  157145. /* huh? Bogus stream with packets but no granulepos */
  157146. vf->pcm_offset=-1;
  157147. break;
  157148. }
  157149. /* has our decoding just traversed a bitstream boundary? */
  157150. if(vf->ready_state>=STREAMSET)
  157151. if(vf->current_serialno!=ogg_page_serialno(&og)){
  157152. _decode_clear(vf); /* clear out stream state */
  157153. ogg_stream_clear(&work_os);
  157154. }
  157155. if(vf->ready_state<STREAMSET){
  157156. int link;
  157157. vf->current_serialno=ogg_page_serialno(&og);
  157158. for(link=0;link<vf->links;link++)
  157159. if(vf->serialnos[link]==vf->current_serialno)break;
  157160. if(link==vf->links)goto seek_error; /* sign of a bogus stream.
  157161. error out, leave
  157162. machine uninitialized */
  157163. vf->current_link=link;
  157164. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  157165. ogg_stream_reset_serialno(&work_os,vf->current_serialno);
  157166. vf->ready_state=STREAMSET;
  157167. }
  157168. ogg_stream_pagein(&vf->os,&og);
  157169. ogg_stream_pagein(&work_os,&og);
  157170. eosflag=ogg_page_eos(&og);
  157171. }
  157172. }
  157173. ogg_stream_clear(&work_os);
  157174. vf->bittrack=0.f;
  157175. vf->samptrack=0.f;
  157176. return(0);
  157177. seek_error:
  157178. /* dump the machine so we're in a known state */
  157179. vf->pcm_offset=-1;
  157180. ogg_stream_clear(&work_os);
  157181. _decode_clear(vf);
  157182. return OV_EBADLINK;
  157183. }
  157184. /* Page granularity seek (faster than sample granularity because we
  157185. don't do the last bit of decode to find a specific sample).
  157186. Seek to the last [granule marked] page preceeding the specified pos
  157187. location, such that decoding past the returned point will quickly
  157188. arrive at the requested position. */
  157189. int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
  157190. int link=-1;
  157191. ogg_int64_t result=0;
  157192. ogg_int64_t total=ov_pcm_total(vf,-1);
  157193. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157194. if(!vf->seekable)return(OV_ENOSEEK);
  157195. if(pos<0 || pos>total)return(OV_EINVAL);
  157196. /* which bitstream section does this pcm offset occur in? */
  157197. for(link=vf->links-1;link>=0;link--){
  157198. total-=vf->pcmlengths[link*2+1];
  157199. if(pos>=total)break;
  157200. }
  157201. /* search within the logical bitstream for the page with the highest
  157202. pcm_pos preceeding (or equal to) pos. There is a danger here;
  157203. missing pages or incorrect frame number information in the
  157204. bitstream could make our task impossible. Account for that (it
  157205. would be an error condition) */
  157206. /* new search algorithm by HB (Nicholas Vinen) */
  157207. {
  157208. ogg_int64_t end=vf->offsets[link+1];
  157209. ogg_int64_t begin=vf->offsets[link];
  157210. ogg_int64_t begintime = vf->pcmlengths[link*2];
  157211. ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
  157212. ogg_int64_t target=pos-total+begintime;
  157213. ogg_int64_t best=begin;
  157214. ogg_page og;
  157215. while(begin<end){
  157216. ogg_int64_t bisect;
  157217. if(end-begin<CHUNKSIZE){
  157218. bisect=begin;
  157219. }else{
  157220. /* take a (pretty decent) guess. */
  157221. bisect=begin +
  157222. (target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
  157223. if(bisect<=begin)
  157224. bisect=begin+1;
  157225. }
  157226. _seek_helper(vf,bisect);
  157227. while(begin<end){
  157228. result=_get_next_page(vf,&og,end-vf->offset);
  157229. if(result==OV_EREAD) goto seek_error;
  157230. if(result<0){
  157231. if(bisect<=begin+1)
  157232. end=begin; /* found it */
  157233. else{
  157234. if(bisect==0) goto seek_error;
  157235. bisect-=CHUNKSIZE;
  157236. if(bisect<=begin)bisect=begin+1;
  157237. _seek_helper(vf,bisect);
  157238. }
  157239. }else{
  157240. ogg_int64_t granulepos=ogg_page_granulepos(&og);
  157241. if(granulepos==-1)continue;
  157242. if(granulepos<target){
  157243. best=result; /* raw offset of packet with granulepos */
  157244. begin=vf->offset; /* raw offset of next page */
  157245. begintime=granulepos;
  157246. if(target-begintime>44100)break;
  157247. bisect=begin; /* *not* begin + 1 */
  157248. }else{
  157249. if(bisect<=begin+1)
  157250. end=begin; /* found it */
  157251. else{
  157252. if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
  157253. end=result;
  157254. bisect-=CHUNKSIZE; /* an endless loop otherwise. */
  157255. if(bisect<=begin)bisect=begin+1;
  157256. _seek_helper(vf,bisect);
  157257. }else{
  157258. end=result;
  157259. endtime=granulepos;
  157260. break;
  157261. }
  157262. }
  157263. }
  157264. }
  157265. }
  157266. }
  157267. /* found our page. seek to it, update pcm offset. Easier case than
  157268. raw_seek, don't keep packets preceeding granulepos. */
  157269. {
  157270. ogg_page og;
  157271. ogg_packet op;
  157272. /* seek */
  157273. _seek_helper(vf,best);
  157274. vf->pcm_offset=-1;
  157275. if(_get_next_page(vf,&og,-1)<0)return(OV_EOF); /* shouldn't happen */
  157276. if(link!=vf->current_link){
  157277. /* Different link; dump entire decode machine */
  157278. _decode_clear(vf);
  157279. vf->current_link=link;
  157280. vf->current_serialno=ogg_page_serialno(&og);
  157281. vf->ready_state=STREAMSET;
  157282. }else{
  157283. vorbis_synthesis_restart(&vf->vd);
  157284. }
  157285. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  157286. ogg_stream_pagein(&vf->os,&og);
  157287. /* pull out all but last packet; the one with granulepos */
  157288. while(1){
  157289. result=ogg_stream_packetpeek(&vf->os,&op);
  157290. if(result==0){
  157291. /* !!! the packet finishing this page originated on a
  157292. preceeding page. Keep fetching previous pages until we
  157293. get one with a granulepos or without the 'continued' flag
  157294. set. Then just use raw_seek for simplicity. */
  157295. _seek_helper(vf,best);
  157296. while(1){
  157297. result=_get_prev_page(vf,&og);
  157298. if(result<0) goto seek_error;
  157299. if(ogg_page_granulepos(&og)>-1 ||
  157300. !ogg_page_continued(&og)){
  157301. return ov_raw_seek(vf,result);
  157302. }
  157303. vf->offset=result;
  157304. }
  157305. }
  157306. if(result<0){
  157307. result = OV_EBADPACKET;
  157308. goto seek_error;
  157309. }
  157310. if(op.granulepos!=-1){
  157311. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  157312. if(vf->pcm_offset<0)vf->pcm_offset=0;
  157313. vf->pcm_offset+=total;
  157314. break;
  157315. }else
  157316. result=ogg_stream_packetout(&vf->os,NULL);
  157317. }
  157318. }
  157319. }
  157320. /* verify result */
  157321. if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
  157322. result=OV_EFAULT;
  157323. goto seek_error;
  157324. }
  157325. vf->bittrack=0.f;
  157326. vf->samptrack=0.f;
  157327. return(0);
  157328. seek_error:
  157329. /* dump machine so we're in a known state */
  157330. vf->pcm_offset=-1;
  157331. _decode_clear(vf);
  157332. return (int)result;
  157333. }
  157334. /* seek to a sample offset relative to the decompressed pcm stream
  157335. returns zero on success, nonzero on failure */
  157336. int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
  157337. int thisblock,lastblock=0;
  157338. int ret=ov_pcm_seek_page(vf,pos);
  157339. if(ret<0)return(ret);
  157340. if((ret=_make_decode_ready(vf)))return ret;
  157341. /* discard leading packets we don't need for the lapping of the
  157342. position we want; don't decode them */
  157343. while(1){
  157344. ogg_packet op;
  157345. ogg_page og;
  157346. int ret=ogg_stream_packetpeek(&vf->os,&op);
  157347. if(ret>0){
  157348. thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
  157349. if(thisblock<0){
  157350. ogg_stream_packetout(&vf->os,NULL);
  157351. continue; /* non audio packet */
  157352. }
  157353. if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
  157354. if(vf->pcm_offset+((thisblock+
  157355. vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
  157356. /* remove the packet from packet queue and track its granulepos */
  157357. ogg_stream_packetout(&vf->os,NULL);
  157358. vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
  157359. only tracking, no
  157360. pcm_decode */
  157361. vorbis_synthesis_blockin(&vf->vd,&vf->vb);
  157362. /* end of logical stream case is hard, especially with exact
  157363. length positioning. */
  157364. if(op.granulepos>-1){
  157365. int i;
  157366. /* always believe the stream markers */
  157367. vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
  157368. if(vf->pcm_offset<0)vf->pcm_offset=0;
  157369. for(i=0;i<vf->current_link;i++)
  157370. vf->pcm_offset+=vf->pcmlengths[i*2+1];
  157371. }
  157372. lastblock=thisblock;
  157373. }else{
  157374. if(ret<0 && ret!=OV_HOLE)break;
  157375. /* suck in a new page */
  157376. if(_get_next_page(vf,&og,-1)<0)break;
  157377. if(vf->current_serialno!=ogg_page_serialno(&og))_decode_clear(vf);
  157378. if(vf->ready_state<STREAMSET){
  157379. int link;
  157380. vf->current_serialno=ogg_page_serialno(&og);
  157381. for(link=0;link<vf->links;link++)
  157382. if(vf->serialnos[link]==vf->current_serialno)break;
  157383. if(link==vf->links)return(OV_EBADLINK);
  157384. vf->current_link=link;
  157385. ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
  157386. vf->ready_state=STREAMSET;
  157387. ret=_make_decode_ready(vf);
  157388. if(ret)return ret;
  157389. lastblock=0;
  157390. }
  157391. ogg_stream_pagein(&vf->os,&og);
  157392. }
  157393. }
  157394. vf->bittrack=0.f;
  157395. vf->samptrack=0.f;
  157396. /* discard samples until we reach the desired position. Crossing a
  157397. logical bitstream boundary with abandon is OK. */
  157398. while(vf->pcm_offset<pos){
  157399. ogg_int64_t target=pos-vf->pcm_offset;
  157400. long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
  157401. if(samples>target)samples=target;
  157402. vorbis_synthesis_read(&vf->vd,samples);
  157403. vf->pcm_offset+=samples;
  157404. if(samples<target)
  157405. if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
  157406. vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
  157407. }
  157408. return 0;
  157409. }
  157410. /* seek to a playback time relative to the decompressed pcm stream
  157411. returns zero on success, nonzero on failure */
  157412. int ov_time_seek(OggVorbis_File *vf,double seconds){
  157413. /* translate time to PCM position and call ov_pcm_seek */
  157414. int link=-1;
  157415. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  157416. double time_total=ov_time_total(vf,-1);
  157417. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157418. if(!vf->seekable)return(OV_ENOSEEK);
  157419. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  157420. /* which bitstream section does this time offset occur in? */
  157421. for(link=vf->links-1;link>=0;link--){
  157422. pcm_total-=vf->pcmlengths[link*2+1];
  157423. time_total-=ov_time_total(vf,link);
  157424. if(seconds>=time_total)break;
  157425. }
  157426. /* enough information to convert time offset to pcm offset */
  157427. {
  157428. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  157429. return(ov_pcm_seek(vf,target));
  157430. }
  157431. }
  157432. /* page-granularity version of ov_time_seek
  157433. returns zero on success, nonzero on failure */
  157434. int ov_time_seek_page(OggVorbis_File *vf,double seconds){
  157435. /* translate time to PCM position and call ov_pcm_seek */
  157436. int link=-1;
  157437. ogg_int64_t pcm_total=ov_pcm_total(vf,-1);
  157438. double time_total=ov_time_total(vf,-1);
  157439. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157440. if(!vf->seekable)return(OV_ENOSEEK);
  157441. if(seconds<0 || seconds>time_total)return(OV_EINVAL);
  157442. /* which bitstream section does this time offset occur in? */
  157443. for(link=vf->links-1;link>=0;link--){
  157444. pcm_total-=vf->pcmlengths[link*2+1];
  157445. time_total-=ov_time_total(vf,link);
  157446. if(seconds>=time_total)break;
  157447. }
  157448. /* enough information to convert time offset to pcm offset */
  157449. {
  157450. ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
  157451. return(ov_pcm_seek_page(vf,target));
  157452. }
  157453. }
  157454. /* tell the current stream offset cursor. Note that seek followed by
  157455. tell will likely not give the set offset due to caching */
  157456. ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
  157457. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157458. return(vf->offset);
  157459. }
  157460. /* return PCM offset (sample) of next PCM sample to be read */
  157461. ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
  157462. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157463. return(vf->pcm_offset);
  157464. }
  157465. /* return time offset (seconds) of next PCM sample to be read */
  157466. double ov_time_tell(OggVorbis_File *vf){
  157467. int link=0;
  157468. ogg_int64_t pcm_total=0;
  157469. double time_total=0.f;
  157470. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157471. if(vf->seekable){
  157472. pcm_total=ov_pcm_total(vf,-1);
  157473. time_total=ov_time_total(vf,-1);
  157474. /* which bitstream section does this time offset occur in? */
  157475. for(link=vf->links-1;link>=0;link--){
  157476. pcm_total-=vf->pcmlengths[link*2+1];
  157477. time_total-=ov_time_total(vf,link);
  157478. if(vf->pcm_offset>=pcm_total)break;
  157479. }
  157480. }
  157481. return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
  157482. }
  157483. /* link: -1) return the vorbis_info struct for the bitstream section
  157484. currently being decoded
  157485. 0-n) to request information for a specific bitstream section
  157486. In the case of a non-seekable bitstream, any call returns the
  157487. current bitstream. NULL in the case that the machine is not
  157488. initialized */
  157489. vorbis_info *ov_info(OggVorbis_File *vf,int link){
  157490. if(vf->seekable){
  157491. if(link<0)
  157492. if(vf->ready_state>=STREAMSET)
  157493. return vf->vi+vf->current_link;
  157494. else
  157495. return vf->vi;
  157496. else
  157497. if(link>=vf->links)
  157498. return NULL;
  157499. else
  157500. return vf->vi+link;
  157501. }else{
  157502. return vf->vi;
  157503. }
  157504. }
  157505. /* grr, strong typing, grr, no templates/inheritence, grr */
  157506. vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
  157507. if(vf->seekable){
  157508. if(link<0)
  157509. if(vf->ready_state>=STREAMSET)
  157510. return vf->vc+vf->current_link;
  157511. else
  157512. return vf->vc;
  157513. else
  157514. if(link>=vf->links)
  157515. return NULL;
  157516. else
  157517. return vf->vc+link;
  157518. }else{
  157519. return vf->vc;
  157520. }
  157521. }
  157522. static int host_is_big_endian() {
  157523. ogg_int32_t pattern = 0xfeedface; /* deadbeef */
  157524. unsigned char *bytewise = (unsigned char *)&pattern;
  157525. if (bytewise[0] == 0xfe) return 1;
  157526. return 0;
  157527. }
  157528. /* up to this point, everything could more or less hide the multiple
  157529. logical bitstream nature of chaining from the toplevel application
  157530. if the toplevel application didn't particularly care. However, at
  157531. the point that we actually read audio back, the multiple-section
  157532. nature must surface: Multiple bitstream sections do not necessarily
  157533. have to have the same number of channels or sampling rate.
  157534. ov_read returns the sequential logical bitstream number currently
  157535. being decoded along with the PCM data in order that the toplevel
  157536. application can take action on channel/sample rate changes. This
  157537. number will be incremented even for streamed (non-seekable) streams
  157538. (for seekable streams, it represents the actual logical bitstream
  157539. index within the physical bitstream. Note that the accessor
  157540. functions above are aware of this dichotomy).
  157541. input values: buffer) a buffer to hold packed PCM data for return
  157542. length) the byte length requested to be placed into buffer
  157543. bigendianp) should the data be packed LSB first (0) or
  157544. MSB first (1)
  157545. word) word size for output. currently 1 (byte) or
  157546. 2 (16 bit short)
  157547. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  157548. 0) EOF
  157549. n) number of bytes of PCM actually returned. The
  157550. below works on a packet-by-packet basis, so the
  157551. return length is not related to the 'length' passed
  157552. in, just guaranteed to fit.
  157553. *section) set to the logical bitstream number */
  157554. long ov_read(OggVorbis_File *vf,char *buffer,int length,
  157555. int bigendianp,int word,int sgned,int *bitstream){
  157556. int i,j;
  157557. int host_endian = host_is_big_endian();
  157558. float **pcm;
  157559. long samples;
  157560. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157561. while(1){
  157562. if(vf->ready_state==INITSET){
  157563. samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  157564. if(samples)break;
  157565. }
  157566. /* suck in another packet */
  157567. {
  157568. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  157569. if(ret==OV_EOF)
  157570. return(0);
  157571. if(ret<=0)
  157572. return(ret);
  157573. }
  157574. }
  157575. if(samples>0){
  157576. /* yay! proceed to pack data into the byte buffer */
  157577. long channels=ov_info(vf,-1)->channels;
  157578. long bytespersample=word * channels;
  157579. vorbis_fpu_control fpu;
  157580. (void) fpu; // (to avoid a warning about it being unused)
  157581. if(samples>length/bytespersample)samples=length/bytespersample;
  157582. if(samples <= 0)
  157583. return OV_EINVAL;
  157584. /* a tight loop to pack each size */
  157585. {
  157586. int val;
  157587. if(word==1){
  157588. int off=(sgned?0:128);
  157589. vorbis_fpu_setround(&fpu);
  157590. for(j=0;j<samples;j++)
  157591. for(i=0;i<channels;i++){
  157592. val=vorbis_ftoi(pcm[i][j]*128.f);
  157593. if(val>127)val=127;
  157594. else if(val<-128)val=-128;
  157595. *buffer++=val+off;
  157596. }
  157597. vorbis_fpu_restore(fpu);
  157598. }else{
  157599. int off=(sgned?0:32768);
  157600. if(host_endian==bigendianp){
  157601. if(sgned){
  157602. vorbis_fpu_setround(&fpu);
  157603. for(i=0;i<channels;i++) { /* It's faster in this order */
  157604. float *src=pcm[i];
  157605. short *dest=((short *)buffer)+i;
  157606. for(j=0;j<samples;j++) {
  157607. val=vorbis_ftoi(src[j]*32768.f);
  157608. if(val>32767)val=32767;
  157609. else if(val<-32768)val=-32768;
  157610. *dest=val;
  157611. dest+=channels;
  157612. }
  157613. }
  157614. vorbis_fpu_restore(fpu);
  157615. }else{
  157616. vorbis_fpu_setround(&fpu);
  157617. for(i=0;i<channels;i++) {
  157618. float *src=pcm[i];
  157619. short *dest=((short *)buffer)+i;
  157620. for(j=0;j<samples;j++) {
  157621. val=vorbis_ftoi(src[j]*32768.f);
  157622. if(val>32767)val=32767;
  157623. else if(val<-32768)val=-32768;
  157624. *dest=val+off;
  157625. dest+=channels;
  157626. }
  157627. }
  157628. vorbis_fpu_restore(fpu);
  157629. }
  157630. }else if(bigendianp){
  157631. vorbis_fpu_setround(&fpu);
  157632. for(j=0;j<samples;j++)
  157633. for(i=0;i<channels;i++){
  157634. val=vorbis_ftoi(pcm[i][j]*32768.f);
  157635. if(val>32767)val=32767;
  157636. else if(val<-32768)val=-32768;
  157637. val+=off;
  157638. *buffer++=(val>>8);
  157639. *buffer++=(val&0xff);
  157640. }
  157641. vorbis_fpu_restore(fpu);
  157642. }else{
  157643. int val;
  157644. vorbis_fpu_setround(&fpu);
  157645. for(j=0;j<samples;j++)
  157646. for(i=0;i<channels;i++){
  157647. val=vorbis_ftoi(pcm[i][j]*32768.f);
  157648. if(val>32767)val=32767;
  157649. else if(val<-32768)val=-32768;
  157650. val+=off;
  157651. *buffer++=(val&0xff);
  157652. *buffer++=(val>>8);
  157653. }
  157654. vorbis_fpu_restore(fpu);
  157655. }
  157656. }
  157657. }
  157658. vorbis_synthesis_read(&vf->vd,samples);
  157659. vf->pcm_offset+=samples;
  157660. if(bitstream)*bitstream=vf->current_link;
  157661. return(samples*bytespersample);
  157662. }else{
  157663. return(samples);
  157664. }
  157665. }
  157666. /* input values: pcm_channels) a float vector per channel of output
  157667. length) the sample length being read by the app
  157668. return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
  157669. 0) EOF
  157670. n) number of samples of PCM actually returned. The
  157671. below works on a packet-by-packet basis, so the
  157672. return length is not related to the 'length' passed
  157673. in, just guaranteed to fit.
  157674. *section) set to the logical bitstream number */
  157675. long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
  157676. int *bitstream){
  157677. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157678. while(1){
  157679. if(vf->ready_state==INITSET){
  157680. float **pcm;
  157681. long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
  157682. if(samples){
  157683. if(pcm_channels)*pcm_channels=pcm;
  157684. if(samples>length)samples=length;
  157685. vorbis_synthesis_read(&vf->vd,samples);
  157686. vf->pcm_offset+=samples;
  157687. if(bitstream)*bitstream=vf->current_link;
  157688. return samples;
  157689. }
  157690. }
  157691. /* suck in another packet */
  157692. {
  157693. int ret=_fetch_and_process_packet(vf,NULL,1,1);
  157694. if(ret==OV_EOF)return(0);
  157695. if(ret<=0)return(ret);
  157696. }
  157697. }
  157698. }
  157699. extern float *vorbis_window(vorbis_dsp_state *v,int W);
  157700. extern void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,
  157701. ogg_int64_t off);
  157702. static void _ov_splice(float **pcm,float **lappcm,
  157703. int n1, int n2,
  157704. int ch1, int ch2,
  157705. float *w1, float *w2){
  157706. int i,j;
  157707. float *w=w1;
  157708. int n=n1;
  157709. if(n1>n2){
  157710. n=n2;
  157711. w=w2;
  157712. }
  157713. /* splice */
  157714. for(j=0;j<ch1 && j<ch2;j++){
  157715. float *s=lappcm[j];
  157716. float *d=pcm[j];
  157717. for(i=0;i<n;i++){
  157718. float wd=w[i]*w[i];
  157719. float ws=1.-wd;
  157720. d[i]=d[i]*wd + s[i]*ws;
  157721. }
  157722. }
  157723. /* window from zero */
  157724. for(;j<ch2;j++){
  157725. float *d=pcm[j];
  157726. for(i=0;i<n;i++){
  157727. float wd=w[i]*w[i];
  157728. d[i]=d[i]*wd;
  157729. }
  157730. }
  157731. }
  157732. /* make sure vf is INITSET */
  157733. static int _ov_initset(OggVorbis_File *vf){
  157734. while(1){
  157735. if(vf->ready_state==INITSET)break;
  157736. /* suck in another packet */
  157737. {
  157738. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157739. if(ret<0 && ret!=OV_HOLE)return(ret);
  157740. }
  157741. }
  157742. return 0;
  157743. }
  157744. /* make sure vf is INITSET and that we have a primed buffer; if
  157745. we're crosslapping at a stream section boundary, this also makes
  157746. sure we're sanity checking against the right stream information */
  157747. static int _ov_initprime(OggVorbis_File *vf){
  157748. vorbis_dsp_state *vd=&vf->vd;
  157749. while(1){
  157750. if(vf->ready_state==INITSET)
  157751. if(vorbis_synthesis_pcmout(vd,NULL))break;
  157752. /* suck in another packet */
  157753. {
  157754. int ret=_fetch_and_process_packet(vf,NULL,1,0);
  157755. if(ret<0 && ret!=OV_HOLE)return(ret);
  157756. }
  157757. }
  157758. return 0;
  157759. }
  157760. /* grab enough data for lapping from vf; this may be in the form of
  157761. unreturned, already-decoded pcm, remaining PCM we will need to
  157762. decode, or synthetic postextrapolation from last packets. */
  157763. static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
  157764. float **lappcm,int lapsize){
  157765. int lapcount=0,i;
  157766. float **pcm;
  157767. /* try first to decode the lapping data */
  157768. while(lapcount<lapsize){
  157769. int samples=vorbis_synthesis_pcmout(vd,&pcm);
  157770. if(samples){
  157771. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157772. for(i=0;i<vi->channels;i++)
  157773. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157774. lapcount+=samples;
  157775. vorbis_synthesis_read(vd,samples);
  157776. }else{
  157777. /* suck in another packet */
  157778. int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
  157779. if(ret==OV_EOF)break;
  157780. }
  157781. }
  157782. if(lapcount<lapsize){
  157783. /* failed to get lapping data from normal decode; pry it from the
  157784. postextrapolation buffering, or the second half of the MDCT
  157785. from the last packet */
  157786. int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
  157787. if(samples==0){
  157788. for(i=0;i<vi->channels;i++)
  157789. memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
  157790. lapcount=lapsize;
  157791. }else{
  157792. if(samples>lapsize-lapcount)samples=lapsize-lapcount;
  157793. for(i=0;i<vi->channels;i++)
  157794. memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
  157795. lapcount+=samples;
  157796. }
  157797. }
  157798. }
  157799. /* this sets up crosslapping of a sample by using trailing data from
  157800. sample 1 and lapping it into the windowing buffer of sample 2 */
  157801. int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
  157802. vorbis_info *vi1,*vi2;
  157803. float **lappcm;
  157804. float **pcm;
  157805. float *w1,*w2;
  157806. int n1,n2,i,ret,hs1,hs2;
  157807. if(vf1==vf2)return(0); /* degenerate case */
  157808. if(vf1->ready_state<OPENED)return(OV_EINVAL);
  157809. if(vf2->ready_state<OPENED)return(OV_EINVAL);
  157810. /* the relevant overlap buffers must be pre-checked and pre-primed
  157811. before looking at settings in the event that priming would cross
  157812. a bitstream boundary. So, do it now */
  157813. ret=_ov_initset(vf1);
  157814. if(ret)return(ret);
  157815. ret=_ov_initprime(vf2);
  157816. if(ret)return(ret);
  157817. vi1=ov_info(vf1,-1);
  157818. vi2=ov_info(vf2,-1);
  157819. hs1=ov_halfrate_p(vf1);
  157820. hs2=ov_halfrate_p(vf2);
  157821. lappcm=(float**) alloca(sizeof(*lappcm)*vi1->channels);
  157822. n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
  157823. n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
  157824. w1=vorbis_window(&vf1->vd,0);
  157825. w2=vorbis_window(&vf2->vd,0);
  157826. for(i=0;i<vi1->channels;i++)
  157827. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157828. _ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
  157829. /* have a lapping buffer from vf1; now to splice it into the lapping
  157830. buffer of vf2 */
  157831. /* consolidate and expose the buffer. */
  157832. vorbis_synthesis_lapout(&vf2->vd,&pcm);
  157833. _analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
  157834. _analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
  157835. /* splice */
  157836. _ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
  157837. /* done */
  157838. return(0);
  157839. }
  157840. static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
  157841. int (*localseek)(OggVorbis_File *,ogg_int64_t)){
  157842. vorbis_info *vi;
  157843. float **lappcm;
  157844. float **pcm;
  157845. float *w1,*w2;
  157846. int n1,n2,ch1,ch2,hs;
  157847. int i,ret;
  157848. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157849. ret=_ov_initset(vf);
  157850. if(ret)return(ret);
  157851. vi=ov_info(vf,-1);
  157852. hs=ov_halfrate_p(vf);
  157853. ch1=vi->channels;
  157854. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157855. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157856. persistent; even if the decode state
  157857. from this link gets dumped, this
  157858. window array continues to exist */
  157859. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157860. for(i=0;i<ch1;i++)
  157861. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157862. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157863. /* have lapping data; seek and prime the buffer */
  157864. ret=localseek(vf,pos);
  157865. if(ret)return ret;
  157866. ret=_ov_initprime(vf);
  157867. if(ret)return(ret);
  157868. /* Guard against cross-link changes; they're perfectly legal */
  157869. vi=ov_info(vf,-1);
  157870. ch2=vi->channels;
  157871. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157872. w2=vorbis_window(&vf->vd,0);
  157873. /* consolidate and expose the buffer. */
  157874. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157875. /* splice */
  157876. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157877. /* done */
  157878. return(0);
  157879. }
  157880. int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157881. return _ov_64_seek_lap(vf,pos,ov_raw_seek);
  157882. }
  157883. int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157884. return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
  157885. }
  157886. int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
  157887. return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
  157888. }
  157889. static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
  157890. int (*localseek)(OggVorbis_File *,double)){
  157891. vorbis_info *vi;
  157892. float **lappcm;
  157893. float **pcm;
  157894. float *w1,*w2;
  157895. int n1,n2,ch1,ch2,hs;
  157896. int i,ret;
  157897. if(vf->ready_state<OPENED)return(OV_EINVAL);
  157898. ret=_ov_initset(vf);
  157899. if(ret)return(ret);
  157900. vi=ov_info(vf,-1);
  157901. hs=ov_halfrate_p(vf);
  157902. ch1=vi->channels;
  157903. n1=vorbis_info_blocksize(vi,0)>>(1+hs);
  157904. w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
  157905. persistent; even if the decode state
  157906. from this link gets dumped, this
  157907. window array continues to exist */
  157908. lappcm=(float**) alloca(sizeof(*lappcm)*ch1);
  157909. for(i=0;i<ch1;i++)
  157910. lappcm[i]=(float*) alloca(sizeof(**lappcm)*n1);
  157911. _ov_getlap(vf,vi,&vf->vd,lappcm,n1);
  157912. /* have lapping data; seek and prime the buffer */
  157913. ret=localseek(vf,pos);
  157914. if(ret)return ret;
  157915. ret=_ov_initprime(vf);
  157916. if(ret)return(ret);
  157917. /* Guard against cross-link changes; they're perfectly legal */
  157918. vi=ov_info(vf,-1);
  157919. ch2=vi->channels;
  157920. n2=vorbis_info_blocksize(vi,0)>>(1+hs);
  157921. w2=vorbis_window(&vf->vd,0);
  157922. /* consolidate and expose the buffer. */
  157923. vorbis_synthesis_lapout(&vf->vd,&pcm);
  157924. /* splice */
  157925. _ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
  157926. /* done */
  157927. return(0);
  157928. }
  157929. int ov_time_seek_lap(OggVorbis_File *vf,double pos){
  157930. return _ov_d_seek_lap(vf,pos,ov_time_seek);
  157931. }
  157932. int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
  157933. return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
  157934. }
  157935. #endif
  157936. /********* End of inlined file: vorbisfile.c *********/
  157937. /********* Start of inlined file: window.c *********/
  157938. /********* Start of inlined file: juce_OggVorbisHeader.h *********/
  157939. // This file is included at the start of each Ogg-Vorbis .c file, just to do a few housekeeping
  157940. // tasks..
  157941. /********* Start of inlined file: juce_Config.h *********/
  157942. #ifndef __JUCE_CONFIG_JUCEHEADER__
  157943. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  157944. /*
  157945. This file contains macros that enable/disable various JUCE features.
  157946. */
  157947. /** The name of the namespace that all Juce classes and functions will be
  157948. put inside. If this is not defined, no namespace will be used.
  157949. */
  157950. #ifndef JUCE_NAMESPACE
  157951. #define JUCE_NAMESPACE juce
  157952. #endif
  157953. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  157954. but if you define this value, you can override this can force it to be true or
  157955. false.
  157956. */
  157957. #ifndef JUCE_FORCE_DEBUG
  157958. //#define JUCE_FORCE_DEBUG 1
  157959. #endif
  157960. /** If this flag is enabled, the the jassert and jassertfalse macros will
  157961. always use Logger::writeToLog() to write a message when an assertion happens.
  157962. Enabling it will also leave this turned on in release builds. When it's disabled,
  157963. however, the jassert and jassertfalse macros will not be compiled in a
  157964. release build.
  157965. @see jassert, jassertfalse, Logger
  157966. */
  157967. #ifndef JUCE_LOG_ASSERTIONS
  157968. // #define JUCE_LOG_ASSERTIONS 1
  157969. #endif
  157970. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  157971. which the ASIOAudioIODevice class can't be built. See the comments in the
  157972. ASIOAudioIODevice class's header file for more info about this.
  157973. (This only affects a Win32 build)
  157974. */
  157975. #ifndef JUCE_ASIO
  157976. #define JUCE_ASIO 1
  157977. #endif
  157978. /** Comment out this macro to disable building of ALSA device support on Linux.
  157979. */
  157980. #ifndef JUCE_ALSA
  157981. #define JUCE_ALSA 1
  157982. #endif
  157983. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  157984. have the SDK installed.
  157985. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  157986. classes will be unavailable.
  157987. On Windows, if you enable this, you'll need to have the QuickTime SDK
  157988. installed, and its header files will need to be on your include path.
  157989. */
  157990. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  157991. #define JUCE_QUICKTIME 1
  157992. #endif
  157993. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  157994. have the appropriate headers and libraries available. If it's not enabled, the
  157995. OpenGLComponent class will be unavailable.
  157996. */
  157997. #ifndef JUCE_OPENGL
  157998. #define JUCE_OPENGL 1
  157999. #endif
  158000. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  158001. If you're not going to need either of these formats, turn off the flags to
  158002. avoid bloating your codebase with them.
  158003. */
  158004. #ifndef JUCE_USE_FLAC
  158005. #define JUCE_USE_FLAC 1
  158006. #endif
  158007. #ifndef JUCE_USE_OGGVORBIS
  158008. #define JUCE_USE_OGGVORBIS 1
  158009. #endif
  158010. /** This flag lets you enable support for CD-burning. You might want to disable
  158011. it to build without the MS SDK under windows.
  158012. */
  158013. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  158014. #define JUCE_USE_CDBURNER 1
  158015. #endif
  158016. /** Enabling this macro means that all regions that get repainted will have a coloured
  158017. line drawn around them.
  158018. This is handy if you're trying to optimise drawing, because it lets you easily see
  158019. when anything is being repainted unnecessarily.
  158020. */
  158021. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  158022. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  158023. #endif
  158024. /** Enable this under Linux to use Xinerama for multi-monitor support.
  158025. */
  158026. #ifndef JUCE_USE_XINERAMA
  158027. #define JUCE_USE_XINERAMA 1
  158028. #endif
  158029. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  158030. */
  158031. #ifndef JUCE_USE_XSHM
  158032. #define JUCE_USE_XSHM 1
  158033. #endif
  158034. /** Enabling this builds support for VST audio plugins.
  158035. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  158036. */
  158037. #ifndef JUCE_PLUGINHOST_VST
  158038. // #define JUCE_PLUGINHOST_VST 1
  158039. #endif
  158040. /** Enabling this builds support for AudioUnit audio plugins.
  158041. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  158042. */
  158043. #ifndef JUCE_PLUGINHOST_AU
  158044. // #define JUCE_PLUGINHOST_AU 1
  158045. #endif
  158046. /** Disabling this will avoid linking to any UI code. This is handy for
  158047. writing command-line utilities, e.g. on linux boxes which don't have some
  158048. of the UI libraries installed.
  158049. (On mac and windows, this won't generally make much difference to the build).
  158050. */
  158051. #ifndef JUCE_BUILD_GUI_CLASSES
  158052. #define JUCE_BUILD_GUI_CLASSES 1
  158053. #endif
  158054. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  158055. */
  158056. #ifndef JUCE_WEB_BROWSER
  158057. #define JUCE_WEB_BROWSER 1
  158058. #endif
  158059. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  158060. codebase - you might need to use this if you're linking to some of these libraries
  158061. yourself.
  158062. */
  158063. #ifndef JUCE_INCLUDE_ZLIB_CODE
  158064. #define JUCE_INCLUDE_ZLIB_CODE 1
  158065. #endif
  158066. #ifndef JUCE_INCLUDE_FLAC_CODE
  158067. #define JUCE_INCLUDE_FLAC_CODE 1
  158068. #endif
  158069. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  158070. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  158071. #endif
  158072. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  158073. #define JUCE_INCLUDE_PNGLIB_CODE 1
  158074. #endif
  158075. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  158076. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  158077. #endif
  158078. /** Enable this to add extra memory-leak info to the new and delete operators.
  158079. (Currently, this only affects Windows builds in debug mode).
  158080. */
  158081. #ifndef JUCE_CHECK_MEMORY_LEAKS
  158082. #define JUCE_CHECK_MEMORY_LEAKS 1
  158083. #endif
  158084. /** Enable this to turn on juce's internal catching of exceptions.
  158085. Turning it off will avoid any exception catching. With it on, all exceptions
  158086. are passed to the JUCEApplication::unhandledException() callback for logging.
  158087. */
  158088. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  158089. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  158090. #endif
  158091. /** If this macro is set, the Juce String class will use unicode as its
  158092. internal representation. If it isn't set, it'll use ANSI.
  158093. */
  158094. #ifndef JUCE_STRINGS_ARE_UNICODE
  158095. #define JUCE_STRINGS_ARE_UNICODE 1
  158096. #endif
  158097. #endif
  158098. /********* End of inlined file: juce_Config.h *********/
  158099. #ifdef _MSC_VER
  158100. #pragma warning (disable: 4267 4127 4244 4996 4100 4701 4702 4013 4133 4206 4305 4189 4706)
  158101. #endif
  158102. /********* End of inlined file: juce_OggVorbisHeader.h *********/
  158103. #if JUCE_USE_OGGVORBIS
  158104. #include <stdlib.h>
  158105. #include <math.h>
  158106. static float vwin64[32] = {
  158107. 0.0009460463F, 0.0085006468F, 0.0235352254F, 0.0458950567F,
  158108. 0.0753351908F, 0.1115073077F, 0.1539457973F, 0.2020557475F,
  158109. 0.2551056759F, 0.3122276645F, 0.3724270287F, 0.4346027792F,
  158110. 0.4975789974F, 0.5601459521F, 0.6211085051F, 0.6793382689F,
  158111. 0.7338252629F, 0.7837245849F, 0.8283939355F, 0.8674186656F,
  158112. 0.9006222429F, 0.9280614787F, 0.9500073081F, 0.9669131782F,
  158113. 0.9793740220F, 0.9880792941F, 0.9937636139F, 0.9971582668F,
  158114. 0.9989462667F, 0.9997230082F, 0.9999638688F, 0.9999995525F,
  158115. };
  158116. static float vwin128[64] = {
  158117. 0.0002365472F, 0.0021280687F, 0.0059065254F, 0.0115626550F,
  158118. 0.0190823442F, 0.0284463735F, 0.0396300935F, 0.0526030430F,
  158119. 0.0673285281F, 0.0837631763F, 0.1018564887F, 0.1215504095F,
  158120. 0.1427789367F, 0.1654677960F, 0.1895342001F, 0.2148867160F,
  158121. 0.2414252576F, 0.2690412240F, 0.2976177952F, 0.3270303960F,
  158122. 0.3571473350F, 0.3878306189F, 0.4189369387F, 0.4503188188F,
  158123. 0.4818259135F, 0.5133064334F, 0.5446086751F, 0.5755826278F,
  158124. 0.6060816248F, 0.6359640047F, 0.6650947483F, 0.6933470543F,
  158125. 0.7206038179F, 0.7467589810F, 0.7717187213F, 0.7954024542F,
  158126. 0.8177436264F, 0.8386902831F, 0.8582053981F, 0.8762669622F,
  158127. 0.8928678298F, 0.9080153310F, 0.9217306608F, 0.9340480615F,
  158128. 0.9450138200F, 0.9546851041F, 0.9631286621F, 0.9704194171F,
  158129. 0.9766389810F, 0.9818741197F, 0.9862151938F, 0.9897546035F,
  158130. 0.9925852598F, 0.9947991032F, 0.9964856900F, 0.9977308602F,
  158131. 0.9986155015F, 0.9992144193F, 0.9995953200F, 0.9998179155F,
  158132. 0.9999331503F, 0.9999825563F, 0.9999977357F, 0.9999999720F,
  158133. };
  158134. static float vwin256[128] = {
  158135. 0.0000591390F, 0.0005321979F, 0.0014780301F, 0.0028960636F,
  158136. 0.0047854363F, 0.0071449926F, 0.0099732775F, 0.0132685298F,
  158137. 0.0170286741F, 0.0212513119F, 0.0259337111F, 0.0310727950F,
  158138. 0.0366651302F, 0.0427069140F, 0.0491939614F, 0.0561216907F,
  158139. 0.0634851102F, 0.0712788035F, 0.0794969160F, 0.0881331402F,
  158140. 0.0971807028F, 0.1066323515F, 0.1164803426F, 0.1267164297F,
  158141. 0.1373318534F, 0.1483173323F, 0.1596630553F, 0.1713586755F,
  158142. 0.1833933062F, 0.1957555184F, 0.2084333404F, 0.2214142599F,
  158143. 0.2346852280F, 0.2482326664F, 0.2620424757F, 0.2761000481F,
  158144. 0.2903902813F, 0.3048975959F, 0.3196059553F, 0.3344988887F,
  158145. 0.3495595160F, 0.3647705766F, 0.3801144597F, 0.3955732382F,
  158146. 0.4111287047F, 0.4267624093F, 0.4424557009F, 0.4581897696F,
  158147. 0.4739456913F, 0.4897044744F, 0.5054471075F, 0.5211546088F,
  158148. 0.5368080763F, 0.5523887395F, 0.5678780103F, 0.5832575361F,
  158149. 0.5985092508F, 0.6136154277F, 0.6285587300F, 0.6433222619F,
  158150. 0.6578896175F, 0.6722449294F, 0.6863729144F, 0.7002589187F,
  158151. 0.7138889597F, 0.7272497662F, 0.7403288154F, 0.7531143679F,
  158152. 0.7655954985F, 0.7777621249F, 0.7896050322F, 0.8011158947F,
  158153. 0.8122872932F, 0.8231127294F, 0.8335866365F, 0.8437043850F,
  158154. 0.8534622861F, 0.8628575905F, 0.8718884835F, 0.8805540765F,
  158155. 0.8888543947F, 0.8967903616F, 0.9043637797F, 0.9115773078F,
  158156. 0.9184344360F, 0.9249394562F, 0.9310974312F, 0.9369141608F,
  158157. 0.9423961446F, 0.9475505439F, 0.9523851406F, 0.9569082947F,
  158158. 0.9611289005F, 0.9650563408F, 0.9687004405F, 0.9720714191F,
  158159. 0.9751798427F, 0.9780365753F, 0.9806527301F, 0.9830396204F,
  158160. 0.9852087111F, 0.9871715701F, 0.9889398207F, 0.9905250941F,
  158161. 0.9919389832F, 0.9931929973F, 0.9942985174F, 0.9952667537F,
  158162. 0.9961087037F, 0.9968351119F, 0.9974564312F, 0.9979827858F,
  158163. 0.9984239359F, 0.9987892441F, 0.9990876435F, 0.9993276081F,
  158164. 0.9995171241F, 0.9996636648F, 0.9997741654F, 0.9998550016F,
  158165. 0.9999119692F, 0.9999502656F, 0.9999744742F, 0.9999885497F,
  158166. 0.9999958064F, 0.9999989077F, 0.9999998584F, 0.9999999983F,
  158167. };
  158168. static float vwin512[256] = {
  158169. 0.0000147849F, 0.0001330607F, 0.0003695946F, 0.0007243509F,
  158170. 0.0011972759F, 0.0017882983F, 0.0024973285F, 0.0033242588F,
  158171. 0.0042689632F, 0.0053312973F, 0.0065110982F, 0.0078081841F,
  158172. 0.0092223540F, 0.0107533880F, 0.0124010466F, 0.0141650703F,
  158173. 0.0160451800F, 0.0180410758F, 0.0201524373F, 0.0223789233F,
  158174. 0.0247201710F, 0.0271757958F, 0.0297453914F, 0.0324285286F,
  158175. 0.0352247556F, 0.0381335972F, 0.0411545545F, 0.0442871045F,
  158176. 0.0475306997F, 0.0508847676F, 0.0543487103F, 0.0579219038F,
  158177. 0.0616036982F, 0.0653934164F, 0.0692903546F, 0.0732937809F,
  158178. 0.0774029356F, 0.0816170305F, 0.0859352485F, 0.0903567428F,
  158179. 0.0948806375F, 0.0995060259F, 0.1042319712F, 0.1090575056F,
  158180. 0.1139816300F, 0.1190033137F, 0.1241214941F, 0.1293350764F,
  158181. 0.1346429333F, 0.1400439046F, 0.1455367974F, 0.1511203852F,
  158182. 0.1567934083F, 0.1625545735F, 0.1684025537F, 0.1743359881F,
  158183. 0.1803534820F, 0.1864536069F, 0.1926349000F, 0.1988958650F,
  158184. 0.2052349715F, 0.2116506555F, 0.2181413191F, 0.2247053313F,
  158185. 0.2313410275F, 0.2380467105F, 0.2448206500F, 0.2516610835F,
  158186. 0.2585662164F, 0.2655342226F, 0.2725632448F, 0.2796513950F,
  158187. 0.2867967551F, 0.2939973773F, 0.3012512852F, 0.3085564739F,
  158188. 0.3159109111F, 0.3233125375F, 0.3307592680F, 0.3382489922F,
  158189. 0.3457795756F, 0.3533488602F, 0.3609546657F, 0.3685947904F,
  158190. 0.3762670121F, 0.3839690896F, 0.3916987634F, 0.3994537572F,
  158191. 0.4072317788F, 0.4150305215F, 0.4228476653F, 0.4306808783F,
  158192. 0.4385278181F, 0.4463861329F, 0.4542534630F, 0.4621274424F,
  158193. 0.4700057001F, 0.4778858615F, 0.4857655502F, 0.4936423891F,
  158194. 0.5015140023F, 0.5093780165F, 0.5172320626F, 0.5250737772F,
  158195. 0.5329008043F, 0.5407107971F, 0.5485014192F, 0.5562703465F,
  158196. 0.5640152688F, 0.5717338914F, 0.5794239366F, 0.5870831457F,
  158197. 0.5947092801F, 0.6023001235F, 0.6098534829F, 0.6173671907F,
  158198. 0.6248391059F, 0.6322671161F, 0.6396491384F, 0.6469831217F,
  158199. 0.6542670475F, 0.6614989319F, 0.6686768267F, 0.6757988210F,
  158200. 0.6828630426F, 0.6898676592F, 0.6968108799F, 0.7036909564F,
  158201. 0.7105061843F, 0.7172549043F, 0.7239355032F, 0.7305464154F,
  158202. 0.7370861235F, 0.7435531598F, 0.7499461068F, 0.7562635986F,
  158203. 0.7625043214F, 0.7686670148F, 0.7747504721F, 0.7807535410F,
  158204. 0.7866751247F, 0.7925141825F, 0.7982697296F, 0.8039408387F,
  158205. 0.8095266395F, 0.8150263196F, 0.8204391248F, 0.8257643590F,
  158206. 0.8310013848F, 0.8361496236F, 0.8412085555F, 0.8461777194F,
  158207. 0.8510567129F, 0.8558451924F, 0.8605428730F, 0.8651495278F,
  158208. 0.8696649882F, 0.8740891432F, 0.8784219392F, 0.8826633797F,
  158209. 0.8868135244F, 0.8908724888F, 0.8948404441F, 0.8987176157F,
  158210. 0.9025042831F, 0.9062007791F, 0.9098074886F, 0.9133248482F,
  158211. 0.9167533451F, 0.9200935163F, 0.9233459472F, 0.9265112712F,
  158212. 0.9295901680F, 0.9325833632F, 0.9354916263F, 0.9383157705F,
  158213. 0.9410566504F, 0.9437151618F, 0.9462922398F, 0.9487888576F,
  158214. 0.9512060252F, 0.9535447882F, 0.9558062262F, 0.9579914516F,
  158215. 0.9601016078F, 0.9621378683F, 0.9641014348F, 0.9659935361F,
  158216. 0.9678154261F, 0.9695683830F, 0.9712537071F, 0.9728727198F,
  158217. 0.9744267618F, 0.9759171916F, 0.9773453842F, 0.9787127293F,
  158218. 0.9800206298F, 0.9812705006F, 0.9824637665F, 0.9836018613F,
  158219. 0.9846862258F, 0.9857183066F, 0.9866995544F, 0.9876314227F,
  158220. 0.9885153662F, 0.9893528393F, 0.9901452948F, 0.9908941823F,
  158221. 0.9916009470F, 0.9922670279F, 0.9928938570F, 0.9934828574F,
  158222. 0.9940354423F, 0.9945530133F, 0.9950369595F, 0.9954886562F,
  158223. 0.9959094633F, 0.9963007242F, 0.9966637649F, 0.9969998925F,
  158224. 0.9973103939F, 0.9975965351F, 0.9978595598F, 0.9981006885F,
  158225. 0.9983211172F, 0.9985220166F, 0.9987045311F, 0.9988697776F,
  158226. 0.9990188449F, 0.9991527924F, 0.9992726499F, 0.9993794157F,
  158227. 0.9994740570F, 0.9995575079F, 0.9996306699F, 0.9996944099F,
  158228. 0.9997495605F, 0.9997969190F, 0.9998372465F, 0.9998712678F,
  158229. 0.9998996704F, 0.9999231041F, 0.9999421807F, 0.9999574732F,
  158230. 0.9999695157F, 0.9999788026F, 0.9999857885F, 0.9999908879F,
  158231. 0.9999944746F, 0.9999968817F, 0.9999984010F, 0.9999992833F,
  158232. 0.9999997377F, 0.9999999317F, 0.9999999911F, 0.9999999999F,
  158233. };
  158234. static float vwin1024[512] = {
  158235. 0.0000036962F, 0.0000332659F, 0.0000924041F, 0.0001811086F,
  158236. 0.0002993761F, 0.0004472021F, 0.0006245811F, 0.0008315063F,
  158237. 0.0010679699F, 0.0013339631F, 0.0016294757F, 0.0019544965F,
  158238. 0.0023090133F, 0.0026930125F, 0.0031064797F, 0.0035493989F,
  158239. 0.0040217533F, 0.0045235250F, 0.0050546946F, 0.0056152418F,
  158240. 0.0062051451F, 0.0068243817F, 0.0074729278F, 0.0081507582F,
  158241. 0.0088578466F, 0.0095941655F, 0.0103596863F, 0.0111543789F,
  158242. 0.0119782122F, 0.0128311538F, 0.0137131701F, 0.0146242260F,
  158243. 0.0155642855F, 0.0165333111F, 0.0175312640F, 0.0185581042F,
  158244. 0.0196137903F, 0.0206982797F, 0.0218115284F, 0.0229534910F,
  158245. 0.0241241208F, 0.0253233698F, 0.0265511886F, 0.0278075263F,
  158246. 0.0290923308F, 0.0304055484F, 0.0317471241F, 0.0331170013F,
  158247. 0.0345151222F, 0.0359414274F, 0.0373958560F, 0.0388783456F,
  158248. 0.0403888325F, 0.0419272511F, 0.0434935347F, 0.0450876148F,
  158249. 0.0467094213F, 0.0483588828F, 0.0500359261F, 0.0517404765F,
  158250. 0.0534724575F, 0.0552317913F, 0.0570183983F, 0.0588321971F,
  158251. 0.0606731048F, 0.0625410369F, 0.0644359070F, 0.0663576272F,
  158252. 0.0683061077F, 0.0702812571F, 0.0722829821F, 0.0743111878F,
  158253. 0.0763657775F, 0.0784466526F, 0.0805537129F, 0.0826868561F,
  158254. 0.0848459782F, 0.0870309736F, 0.0892417345F, 0.0914781514F,
  158255. 0.0937401128F, 0.0960275056F, 0.0983402145F, 0.1006781223F,
  158256. 0.1030411101F, 0.1054290568F, 0.1078418397F, 0.1102793336F,
  158257. 0.1127414119F, 0.1152279457F, 0.1177388042F, 0.1202738544F,
  158258. 0.1228329618F, 0.1254159892F, 0.1280227980F, 0.1306532471F,
  158259. 0.1333071937F, 0.1359844927F, 0.1386849970F, 0.1414085575F,
  158260. 0.1441550230F, 0.1469242403F, 0.1497160539F, 0.1525303063F,
  158261. 0.1553668381F, 0.1582254875F, 0.1611060909F, 0.1640084822F,
  158262. 0.1669324936F, 0.1698779549F, 0.1728446939F, 0.1758325362F,
  158263. 0.1788413055F, 0.1818708232F, 0.1849209084F, 0.1879913785F,
  158264. 0.1910820485F, 0.1941927312F, 0.1973232376F, 0.2004733764F,
  158265. 0.2036429541F, 0.2068317752F, 0.2100396421F, 0.2132663552F,
  158266. 0.2165117125F, 0.2197755102F, 0.2230575422F, 0.2263576007F,
  158267. 0.2296754753F, 0.2330109540F, 0.2363638225F, 0.2397338646F,
  158268. 0.2431208619F, 0.2465245941F, 0.2499448389F, 0.2533813719F,
  158269. 0.2568339669F, 0.2603023956F, 0.2637864277F, 0.2672858312F,
  158270. 0.2708003718F, 0.2743298135F, 0.2778739186F, 0.2814324472F,
  158271. 0.2850051576F, 0.2885918065F, 0.2921921485F, 0.2958059366F,
  158272. 0.2994329219F, 0.3030728538F, 0.3067254799F, 0.3103905462F,
  158273. 0.3140677969F, 0.3177569747F, 0.3214578205F, 0.3251700736F,
  158274. 0.3288934718F, 0.3326277513F, 0.3363726468F, 0.3401278914F,
  158275. 0.3438932168F, 0.3476683533F, 0.3514530297F, 0.3552469734F,
  158276. 0.3590499106F, 0.3628615659F, 0.3666816630F, 0.3705099239F,
  158277. 0.3743460698F, 0.3781898204F, 0.3820408945F, 0.3858990095F,
  158278. 0.3897638820F, 0.3936352274F, 0.3975127601F, 0.4013961936F,
  158279. 0.4052852405F, 0.4091796123F, 0.4130790198F, 0.4169831732F,
  158280. 0.4208917815F, 0.4248045534F, 0.4287211965F, 0.4326414181F,
  158281. 0.4365649248F, 0.4404914225F, 0.4444206167F, 0.4483522125F,
  158282. 0.4522859146F, 0.4562214270F, 0.4601584538F, 0.4640966984F,
  158283. 0.4680358644F, 0.4719756548F, 0.4759157726F, 0.4798559209F,
  158284. 0.4837958024F, 0.4877351199F, 0.4916735765F, 0.4956108751F,
  158285. 0.4995467188F, 0.5034808109F, 0.5074128550F, 0.5113425550F,
  158286. 0.5152696149F, 0.5191937395F, 0.5231146336F, 0.5270320028F,
  158287. 0.5309455530F, 0.5348549910F, 0.5387600239F, 0.5426603597F,
  158288. 0.5465557070F, 0.5504457754F, 0.5543302752F, 0.5582089175F,
  158289. 0.5620814145F, 0.5659474793F, 0.5698068262F, 0.5736591704F,
  158290. 0.5775042283F, 0.5813417176F, 0.5851713571F, 0.5889928670F,
  158291. 0.5928059689F, 0.5966103856F, 0.6004058415F, 0.6041920626F,
  158292. 0.6079687761F, 0.6117357113F, 0.6154925986F, 0.6192391705F,
  158293. 0.6229751612F, 0.6267003064F, 0.6304143441F, 0.6341170137F,
  158294. 0.6378080569F, 0.6414872173F, 0.6451542405F, 0.6488088741F,
  158295. 0.6524508681F, 0.6560799742F, 0.6596959469F, 0.6632985424F,
  158296. 0.6668875197F, 0.6704626398F, 0.6740236662F, 0.6775703649F,
  158297. 0.6811025043F, 0.6846198554F, 0.6881221916F, 0.6916092892F,
  158298. 0.6950809269F, 0.6985368861F, 0.7019769510F, 0.7054009085F,
  158299. 0.7088085484F, 0.7121996632F, 0.7155740484F, 0.7189315023F,
  158300. 0.7222718263F, 0.7255948245F, 0.7289003043F, 0.7321880760F,
  158301. 0.7354579530F, 0.7387097518F, 0.7419432921F, 0.7451583966F,
  158302. 0.7483548915F, 0.7515326059F, 0.7546913723F, 0.7578310265F,
  158303. 0.7609514077F, 0.7640523581F, 0.7671337237F, 0.7701953535F,
  158304. 0.7732371001F, 0.7762588195F, 0.7792603711F, 0.7822416178F,
  158305. 0.7852024259F, 0.7881426654F, 0.7910622097F, 0.7939609356F,
  158306. 0.7968387237F, 0.7996954579F, 0.8025310261F, 0.8053453193F,
  158307. 0.8081382324F, 0.8109096638F, 0.8136595156F, 0.8163876936F,
  158308. 0.8190941071F, 0.8217786690F, 0.8244412960F, 0.8270819086F,
  158309. 0.8297004305F, 0.8322967896F, 0.8348709171F, 0.8374227481F,
  158310. 0.8399522213F, 0.8424592789F, 0.8449438672F, 0.8474059356F,
  158311. 0.8498454378F, 0.8522623306F, 0.8546565748F, 0.8570281348F,
  158312. 0.8593769787F, 0.8617030779F, 0.8640064080F, 0.8662869477F,
  158313. 0.8685446796F, 0.8707795899F, 0.8729916682F, 0.8751809079F,
  158314. 0.8773473059F, 0.8794908626F, 0.8816115819F, 0.8837094713F,
  158315. 0.8857845418F, 0.8878368079F, 0.8898662874F, 0.8918730019F,
  158316. 0.8938569760F, 0.8958182380F, 0.8977568194F, 0.8996727552F,
  158317. 0.9015660837F, 0.9034368465F, 0.9052850885F, 0.9071108577F,
  158318. 0.9089142057F, 0.9106951869F, 0.9124538591F, 0.9141902832F,
  158319. 0.9159045233F, 0.9175966464F, 0.9192667228F, 0.9209148257F,
  158320. 0.9225410313F, 0.9241454187F, 0.9257280701F, 0.9272890704F,
  158321. 0.9288285075F, 0.9303464720F, 0.9318430576F, 0.9333183603F,
  158322. 0.9347724792F, 0.9362055158F, 0.9376175745F, 0.9390087622F,
  158323. 0.9403791881F, 0.9417289644F, 0.9430582055F, 0.9443670283F,
  158324. 0.9456555521F, 0.9469238986F, 0.9481721917F, 0.9494005577F,
  158325. 0.9506091252F, 0.9517980248F, 0.9529673894F, 0.9541173540F,
  158326. 0.9552480557F, 0.9563596334F, 0.9574522282F, 0.9585259830F,
  158327. 0.9595810428F, 0.9606175542F, 0.9616356656F, 0.9626355274F,
  158328. 0.9636172915F, 0.9645811114F, 0.9655271425F, 0.9664555414F,
  158329. 0.9673664664F, 0.9682600774F, 0.9691365355F, 0.9699960034F,
  158330. 0.9708386448F, 0.9716646250F, 0.9724741103F, 0.9732672685F,
  158331. 0.9740442683F, 0.9748052795F, 0.9755504729F, 0.9762800205F,
  158332. 0.9769940950F, 0.9776928703F, 0.9783765210F, 0.9790452223F,
  158333. 0.9796991504F, 0.9803384823F, 0.9809633954F, 0.9815740679F,
  158334. 0.9821706784F, 0.9827534063F, 0.9833224312F, 0.9838779332F,
  158335. 0.9844200928F, 0.9849490910F, 0.9854651087F, 0.9859683274F,
  158336. 0.9864589286F, 0.9869370940F, 0.9874030054F, 0.9878568447F,
  158337. 0.9882987937F, 0.9887290343F, 0.9891477481F, 0.9895551169F,
  158338. 0.9899513220F, 0.9903365446F, 0.9907109658F, 0.9910747662F,
  158339. 0.9914281260F, 0.9917712252F, 0.9921042433F, 0.9924273593F,
  158340. 0.9927407516F, 0.9930445982F, 0.9933390763F, 0.9936243626F,
  158341. 0.9939006331F, 0.9941680631F, 0.9944268269F, 0.9946770982F,
  158342. 0.9949190498F, 0.9951528537F, 0.9953786808F, 0.9955967011F,
  158343. 0.9958070836F, 0.9960099963F, 0.9962056061F, 0.9963940787F,
  158344. 0.9965755786F, 0.9967502693F, 0.9969183129F, 0.9970798704F,
  158345. 0.9972351013F, 0.9973841640F, 0.9975272151F, 0.9976644103F,
  158346. 0.9977959036F, 0.9979218476F, 0.9980423932F, 0.9981576901F,
  158347. 0.9982678862F, 0.9983731278F, 0.9984735596F, 0.9985693247F,
  158348. 0.9986605645F, 0.9987474186F, 0.9988300248F, 0.9989085193F,
  158349. 0.9989830364F, 0.9990537085F, 0.9991206662F, 0.9991840382F,
  158350. 0.9992439513F, 0.9993005303F, 0.9993538982F, 0.9994041757F,
  158351. 0.9994514817F, 0.9994959330F, 0.9995376444F, 0.9995767286F,
  158352. 0.9996132960F, 0.9996474550F, 0.9996793121F, 0.9997089710F,
  158353. 0.9997365339F, 0.9997621003F, 0.9997857677F, 0.9998076311F,
  158354. 0.9998277836F, 0.9998463156F, 0.9998633155F, 0.9998788692F,
  158355. 0.9998930603F, 0.9999059701F, 0.9999176774F, 0.9999282586F,
  158356. 0.9999377880F, 0.9999463370F, 0.9999539749F, 0.9999607685F,
  158357. 0.9999667820F, 0.9999720773F, 0.9999767136F, 0.9999807479F,
  158358. 0.9999842344F, 0.9999872249F, 0.9999897688F, 0.9999919127F,
  158359. 0.9999937009F, 0.9999951749F, 0.9999963738F, 0.9999973342F,
  158360. 0.9999980900F, 0.9999986724F, 0.9999991103F, 0.9999994297F,
  158361. 0.9999996543F, 0.9999998049F, 0.9999999000F, 0.9999999552F,
  158362. 0.9999999836F, 0.9999999957F, 0.9999999994F, 1.0000000000F,
  158363. };
  158364. static float vwin2048[1024] = {
  158365. 0.0000009241F, 0.0000083165F, 0.0000231014F, 0.0000452785F,
  158366. 0.0000748476F, 0.0001118085F, 0.0001561608F, 0.0002079041F,
  158367. 0.0002670379F, 0.0003335617F, 0.0004074748F, 0.0004887765F,
  158368. 0.0005774661F, 0.0006735427F, 0.0007770054F, 0.0008878533F,
  158369. 0.0010060853F, 0.0011317002F, 0.0012646969F, 0.0014050742F,
  158370. 0.0015528307F, 0.0017079650F, 0.0018704756F, 0.0020403610F,
  158371. 0.0022176196F, 0.0024022497F, 0.0025942495F, 0.0027936173F,
  158372. 0.0030003511F, 0.0032144490F, 0.0034359088F, 0.0036647286F,
  158373. 0.0039009061F, 0.0041444391F, 0.0043953253F, 0.0046535621F,
  158374. 0.0049191472F, 0.0051920781F, 0.0054723520F, 0.0057599664F,
  158375. 0.0060549184F, 0.0063572052F, 0.0066668239F, 0.0069837715F,
  158376. 0.0073080449F, 0.0076396410F, 0.0079785566F, 0.0083247884F,
  158377. 0.0086783330F, 0.0090391871F, 0.0094073470F, 0.0097828092F,
  158378. 0.0101655700F, 0.0105556258F, 0.0109529726F, 0.0113576065F,
  158379. 0.0117695237F, 0.0121887200F, 0.0126151913F, 0.0130489335F,
  158380. 0.0134899422F, 0.0139382130F, 0.0143937415F, 0.0148565233F,
  158381. 0.0153265536F, 0.0158038279F, 0.0162883413F, 0.0167800889F,
  158382. 0.0172790660F, 0.0177852675F, 0.0182986882F, 0.0188193231F,
  158383. 0.0193471668F, 0.0198822141F, 0.0204244594F, 0.0209738974F,
  158384. 0.0215305225F, 0.0220943289F, 0.0226653109F, 0.0232434627F,
  158385. 0.0238287784F, 0.0244212519F, 0.0250208772F, 0.0256276481F,
  158386. 0.0262415582F, 0.0268626014F, 0.0274907711F, 0.0281260608F,
  158387. 0.0287684638F, 0.0294179736F, 0.0300745833F, 0.0307382859F,
  158388. 0.0314090747F, 0.0320869424F, 0.0327718819F, 0.0334638860F,
  158389. 0.0341629474F, 0.0348690586F, 0.0355822122F, 0.0363024004F,
  158390. 0.0370296157F, 0.0377638502F, 0.0385050960F, 0.0392533451F,
  158391. 0.0400085896F, 0.0407708211F, 0.0415400315F, 0.0423162123F,
  158392. 0.0430993552F, 0.0438894515F, 0.0446864926F, 0.0454904698F,
  158393. 0.0463013742F, 0.0471191969F, 0.0479439288F, 0.0487755607F,
  158394. 0.0496140836F, 0.0504594879F, 0.0513117642F, 0.0521709031F,
  158395. 0.0530368949F, 0.0539097297F, 0.0547893979F, 0.0556758894F,
  158396. 0.0565691941F, 0.0574693019F, 0.0583762026F, 0.0592898858F,
  158397. 0.0602103410F, 0.0611375576F, 0.0620715250F, 0.0630122324F,
  158398. 0.0639596688F, 0.0649138234F, 0.0658746848F, 0.0668422421F,
  158399. 0.0678164838F, 0.0687973985F, 0.0697849746F, 0.0707792005F,
  158400. 0.0717800645F, 0.0727875547F, 0.0738016591F, 0.0748223656F,
  158401. 0.0758496620F, 0.0768835359F, 0.0779239751F, 0.0789709668F,
  158402. 0.0800244985F, 0.0810845574F, 0.0821511306F, 0.0832242052F,
  158403. 0.0843037679F, 0.0853898056F, 0.0864823050F, 0.0875812525F,
  158404. 0.0886866347F, 0.0897984378F, 0.0909166480F, 0.0920412513F,
  158405. 0.0931722338F, 0.0943095813F, 0.0954532795F, 0.0966033140F,
  158406. 0.0977596702F, 0.0989223336F, 0.1000912894F, 0.1012665227F,
  158407. 0.1024480185F, 0.1036357616F, 0.1048297369F, 0.1060299290F,
  158408. 0.1072363224F, 0.1084489014F, 0.1096676504F, 0.1108925534F,
  158409. 0.1121235946F, 0.1133607577F, 0.1146040267F, 0.1158533850F,
  158410. 0.1171088163F, 0.1183703040F, 0.1196378312F, 0.1209113812F,
  158411. 0.1221909370F, 0.1234764815F, 0.1247679974F, 0.1260654674F,
  158412. 0.1273688740F, 0.1286781995F, 0.1299934263F, 0.1313145365F,
  158413. 0.1326415121F, 0.1339743349F, 0.1353129866F, 0.1366574490F,
  158414. 0.1380077035F, 0.1393637315F, 0.1407255141F, 0.1420930325F,
  158415. 0.1434662677F, 0.1448452004F, 0.1462298115F, 0.1476200814F,
  158416. 0.1490159906F, 0.1504175195F, 0.1518246482F, 0.1532373569F,
  158417. 0.1546556253F, 0.1560794333F, 0.1575087606F, 0.1589435866F,
  158418. 0.1603838909F, 0.1618296526F, 0.1632808509F, 0.1647374648F,
  158419. 0.1661994731F, 0.1676668546F, 0.1691395880F, 0.1706176516F,
  158420. 0.1721010238F, 0.1735896829F, 0.1750836068F, 0.1765827736F,
  158421. 0.1780871610F, 0.1795967468F, 0.1811115084F, 0.1826314234F,
  158422. 0.1841564689F, 0.1856866221F, 0.1872218600F, 0.1887621595F,
  158423. 0.1903074974F, 0.1918578503F, 0.1934131947F, 0.1949735068F,
  158424. 0.1965387630F, 0.1981089393F, 0.1996840117F, 0.2012639560F,
  158425. 0.2028487479F, 0.2044383630F, 0.2060327766F, 0.2076319642F,
  158426. 0.2092359007F, 0.2108445614F, 0.2124579211F, 0.2140759545F,
  158427. 0.2156986364F, 0.2173259411F, 0.2189578432F, 0.2205943168F,
  158428. 0.2222353361F, 0.2238808751F, 0.2255309076F, 0.2271854073F,
  158429. 0.2288443480F, 0.2305077030F, 0.2321754457F, 0.2338475493F,
  158430. 0.2355239869F, 0.2372047315F, 0.2388897560F, 0.2405790329F,
  158431. 0.2422725350F, 0.2439702347F, 0.2456721043F, 0.2473781159F,
  158432. 0.2490882418F, 0.2508024539F, 0.2525207240F, 0.2542430237F,
  158433. 0.2559693248F, 0.2576995986F, 0.2594338166F, 0.2611719498F,
  158434. 0.2629139695F, 0.2646598466F, 0.2664095520F, 0.2681630564F,
  158435. 0.2699203304F, 0.2716813445F, 0.2734460691F, 0.2752144744F,
  158436. 0.2769865307F, 0.2787622079F, 0.2805414760F, 0.2823243047F,
  158437. 0.2841106637F, 0.2859005227F, 0.2876938509F, 0.2894906179F,
  158438. 0.2912907928F, 0.2930943447F, 0.2949012426F, 0.2967114554F,
  158439. 0.2985249520F, 0.3003417009F, 0.3021616708F, 0.3039848301F,
  158440. 0.3058111471F, 0.3076405901F, 0.3094731273F, 0.3113087266F,
  158441. 0.3131473560F, 0.3149889833F, 0.3168335762F, 0.3186811024F,
  158442. 0.3205315294F, 0.3223848245F, 0.3242409552F, 0.3260998886F,
  158443. 0.3279615918F, 0.3298260319F, 0.3316931758F, 0.3335629903F,
  158444. 0.3354354423F, 0.3373104982F, 0.3391881247F, 0.3410682882F,
  158445. 0.3429509551F, 0.3448360917F, 0.3467236642F, 0.3486136387F,
  158446. 0.3505059811F, 0.3524006575F, 0.3542976336F, 0.3561968753F,
  158447. 0.3580983482F, 0.3600020179F, 0.3619078499F, 0.3638158096F,
  158448. 0.3657258625F, 0.3676379737F, 0.3695521086F, 0.3714682321F,
  158449. 0.3733863094F, 0.3753063055F, 0.3772281852F, 0.3791519134F,
  158450. 0.3810774548F, 0.3830047742F, 0.3849338362F, 0.3868646053F,
  158451. 0.3887970459F, 0.3907311227F, 0.3926667998F, 0.3946040417F,
  158452. 0.3965428125F, 0.3984830765F, 0.4004247978F, 0.4023679403F,
  158453. 0.4043124683F, 0.4062583455F, 0.4082055359F, 0.4101540034F,
  158454. 0.4121037117F, 0.4140546246F, 0.4160067058F, 0.4179599190F,
  158455. 0.4199142277F, 0.4218695956F, 0.4238259861F, 0.4257833627F,
  158456. 0.4277416888F, 0.4297009279F, 0.4316610433F, 0.4336219983F,
  158457. 0.4355837562F, 0.4375462803F, 0.4395095337F, 0.4414734797F,
  158458. 0.4434380815F, 0.4454033021F, 0.4473691046F, 0.4493354521F,
  158459. 0.4513023078F, 0.4532696345F, 0.4552373954F, 0.4572055533F,
  158460. 0.4591740713F, 0.4611429123F, 0.4631120393F, 0.4650814151F,
  158461. 0.4670510028F, 0.4690207650F, 0.4709906649F, 0.4729606651F,
  158462. 0.4749307287F, 0.4769008185F, 0.4788708972F, 0.4808409279F,
  158463. 0.4828108732F, 0.4847806962F, 0.4867503597F, 0.4887198264F,
  158464. 0.4906890593F, 0.4926580213F, 0.4946266753F, 0.4965949840F,
  158465. 0.4985629105F, 0.5005304176F, 0.5024974683F, 0.5044640255F,
  158466. 0.5064300522F, 0.5083955114F, 0.5103603659F, 0.5123245790F,
  158467. 0.5142881136F, 0.5162509328F, 0.5182129997F, 0.5201742774F,
  158468. 0.5221347290F, 0.5240943178F, 0.5260530070F, 0.5280107598F,
  158469. 0.5299675395F, 0.5319233095F, 0.5338780330F, 0.5358316736F,
  158470. 0.5377841946F, 0.5397355596F, 0.5416857320F, 0.5436346755F,
  158471. 0.5455823538F, 0.5475287304F, 0.5494737691F, 0.5514174337F,
  158472. 0.5533596881F, 0.5553004962F, 0.5572398218F, 0.5591776291F,
  158473. 0.5611138821F, 0.5630485449F, 0.5649815818F, 0.5669129570F,
  158474. 0.5688426349F, 0.5707705799F, 0.5726967564F, 0.5746211290F,
  158475. 0.5765436624F, 0.5784643212F, 0.5803830702F, 0.5822998743F,
  158476. 0.5842146984F, 0.5861275076F, 0.5880382669F, 0.5899469416F,
  158477. 0.5918534968F, 0.5937578981F, 0.5956601107F, 0.5975601004F,
  158478. 0.5994578326F, 0.6013532732F, 0.6032463880F, 0.6051371429F,
  158479. 0.6070255039F, 0.6089114372F, 0.6107949090F, 0.6126758856F,
  158480. 0.6145543334F, 0.6164302191F, 0.6183035092F, 0.6201741706F,
  158481. 0.6220421700F, 0.6239074745F, 0.6257700513F, 0.6276298674F,
  158482. 0.6294868903F, 0.6313410873F, 0.6331924262F, 0.6350408745F,
  158483. 0.6368864001F, 0.6387289710F, 0.6405685552F, 0.6424051209F,
  158484. 0.6442386364F, 0.6460690702F, 0.6478963910F, 0.6497205673F,
  158485. 0.6515415682F, 0.6533593625F, 0.6551739194F, 0.6569852082F,
  158486. 0.6587931984F, 0.6605978593F, 0.6623991609F, 0.6641970728F,
  158487. 0.6659915652F, 0.6677826081F, 0.6695701718F, 0.6713542268F,
  158488. 0.6731347437F, 0.6749116932F, 0.6766850461F, 0.6784547736F,
  158489. 0.6802208469F, 0.6819832374F, 0.6837419164F, 0.6854968559F,
  158490. 0.6872480275F, 0.6889954034F, 0.6907389556F, 0.6924786566F,
  158491. 0.6942144788F, 0.6959463950F, 0.6976743780F, 0.6993984008F,
  158492. 0.7011184365F, 0.7028344587F, 0.7045464407F, 0.7062543564F,
  158493. 0.7079581796F, 0.7096578844F, 0.7113534450F, 0.7130448359F,
  158494. 0.7147320316F, 0.7164150070F, 0.7180937371F, 0.7197681970F,
  158495. 0.7214383620F, 0.7231042077F, 0.7247657098F, 0.7264228443F,
  158496. 0.7280755871F, 0.7297239147F, 0.7313678035F, 0.7330072301F,
  158497. 0.7346421715F, 0.7362726046F, 0.7378985069F, 0.7395198556F,
  158498. 0.7411366285F, 0.7427488034F, 0.7443563584F, 0.7459592717F,
  158499. 0.7475575218F, 0.7491510873F, 0.7507399471F, 0.7523240803F,
  158500. 0.7539034661F, 0.7554780839F, 0.7570479136F, 0.7586129349F,
  158501. 0.7601731279F, 0.7617284730F, 0.7632789506F, 0.7648245416F,
  158502. 0.7663652267F, 0.7679009872F, 0.7694318044F, 0.7709576599F,
  158503. 0.7724785354F, 0.7739944130F, 0.7755052749F, 0.7770111035F,
  158504. 0.7785118815F, 0.7800075916F, 0.7814982170F, 0.7829837410F,
  158505. 0.7844641472F, 0.7859394191F, 0.7874095408F, 0.7888744965F,
  158506. 0.7903342706F, 0.7917888476F, 0.7932382124F, 0.7946823501F,
  158507. 0.7961212460F, 0.7975548855F, 0.7989832544F, 0.8004063386F,
  158508. 0.8018241244F, 0.8032365981F, 0.8046437463F, 0.8060455560F,
  158509. 0.8074420141F, 0.8088331080F, 0.8102188253F, 0.8115991536F,
  158510. 0.8129740810F, 0.8143435957F, 0.8157076861F, 0.8170663409F,
  158511. 0.8184195489F, 0.8197672994F, 0.8211095817F, 0.8224463853F,
  158512. 0.8237777001F, 0.8251035161F, 0.8264238235F, 0.8277386129F,
  158513. 0.8290478750F, 0.8303516008F, 0.8316497814F, 0.8329424083F,
  158514. 0.8342294731F, 0.8355109677F, 0.8367868841F, 0.8380572148F,
  158515. 0.8393219523F, 0.8405810893F, 0.8418346190F, 0.8430825345F,
  158516. 0.8443248294F, 0.8455614974F, 0.8467925323F, 0.8480179285F,
  158517. 0.8492376802F, 0.8504517822F, 0.8516602292F, 0.8528630164F,
  158518. 0.8540601391F, 0.8552515928F, 0.8564373733F, 0.8576174766F,
  158519. 0.8587918990F, 0.8599606368F, 0.8611236868F, 0.8622810460F,
  158520. 0.8634327113F, 0.8645786802F, 0.8657189504F, 0.8668535195F,
  158521. 0.8679823857F, 0.8691055472F, 0.8702230025F, 0.8713347503F,
  158522. 0.8724407896F, 0.8735411194F, 0.8746357394F, 0.8757246489F,
  158523. 0.8768078479F, 0.8778853364F, 0.8789571146F, 0.8800231832F,
  158524. 0.8810835427F, 0.8821381942F, 0.8831871387F, 0.8842303777F,
  158525. 0.8852679127F, 0.8862997456F, 0.8873258784F, 0.8883463132F,
  158526. 0.8893610527F, 0.8903700994F, 0.8913734562F, 0.8923711263F,
  158527. 0.8933631129F, 0.8943494196F, 0.8953300500F, 0.8963050083F,
  158528. 0.8972742985F, 0.8982379249F, 0.8991958922F, 0.9001482052F,
  158529. 0.9010948688F, 0.9020358883F, 0.9029712690F, 0.9039010165F,
  158530. 0.9048251367F, 0.9057436357F, 0.9066565195F, 0.9075637946F,
  158531. 0.9084654678F, 0.9093615456F, 0.9102520353F, 0.9111369440F,
  158532. 0.9120162792F, 0.9128900484F, 0.9137582595F, 0.9146209204F,
  158533. 0.9154780394F, 0.9163296248F, 0.9171756853F, 0.9180162296F,
  158534. 0.9188512667F, 0.9196808057F, 0.9205048559F, 0.9213234270F,
  158535. 0.9221365285F, 0.9229441704F, 0.9237463629F, 0.9245431160F,
  158536. 0.9253344404F, 0.9261203465F, 0.9269008453F, 0.9276759477F,
  158537. 0.9284456648F, 0.9292100080F, 0.9299689889F, 0.9307226190F,
  158538. 0.9314709103F, 0.9322138747F, 0.9329515245F, 0.9336838721F,
  158539. 0.9344109300F, 0.9351327108F, 0.9358492275F, 0.9365604931F,
  158540. 0.9372665208F, 0.9379673239F, 0.9386629160F, 0.9393533107F,
  158541. 0.9400385220F, 0.9407185637F, 0.9413934501F, 0.9420631954F,
  158542. 0.9427278141F, 0.9433873208F, 0.9440417304F, 0.9446910576F,
  158543. 0.9453353176F, 0.9459745255F, 0.9466086968F, 0.9472378469F,
  158544. 0.9478619915F, 0.9484811463F, 0.9490953274F, 0.9497045506F,
  158545. 0.9503088323F, 0.9509081888F, 0.9515026365F, 0.9520921921F,
  158546. 0.9526768723F, 0.9532566940F, 0.9538316742F, 0.9544018300F,
  158547. 0.9549671786F, 0.9555277375F, 0.9560835241F, 0.9566345562F,
  158548. 0.9571808513F, 0.9577224275F, 0.9582593027F, 0.9587914949F,
  158549. 0.9593190225F, 0.9598419038F, 0.9603601571F, 0.9608738012F,
  158550. 0.9613828546F, 0.9618873361F, 0.9623872646F, 0.9628826591F,
  158551. 0.9633735388F, 0.9638599227F, 0.9643418303F, 0.9648192808F,
  158552. 0.9652922939F, 0.9657608890F, 0.9662250860F, 0.9666849046F,
  158553. 0.9671403646F, 0.9675914861F, 0.9680382891F, 0.9684807937F,
  158554. 0.9689190202F, 0.9693529890F, 0.9697827203F, 0.9702082347F,
  158555. 0.9706295529F, 0.9710466953F, 0.9714596828F, 0.9718685362F,
  158556. 0.9722732762F, 0.9726739240F, 0.9730705005F, 0.9734630267F,
  158557. 0.9738515239F, 0.9742360134F, 0.9746165163F, 0.9749930540F,
  158558. 0.9753656481F, 0.9757343198F, 0.9760990909F, 0.9764599829F,
  158559. 0.9768170175F, 0.9771702164F, 0.9775196013F, 0.9778651941F,
  158560. 0.9782070167F, 0.9785450909F, 0.9788794388F, 0.9792100824F,
  158561. 0.9795370437F, 0.9798603449F, 0.9801800080F, 0.9804960554F,
  158562. 0.9808085092F, 0.9811173916F, 0.9814227251F, 0.9817245318F,
  158563. 0.9820228343F, 0.9823176549F, 0.9826090160F, 0.9828969402F,
  158564. 0.9831814498F, 0.9834625674F, 0.9837403156F, 0.9840147169F,
  158565. 0.9842857939F, 0.9845535692F, 0.9848180654F, 0.9850793052F,
  158566. 0.9853373113F, 0.9855921062F, 0.9858437127F, 0.9860921535F,
  158567. 0.9863374512F, 0.9865796287F, 0.9868187085F, 0.9870547136F,
  158568. 0.9872876664F, 0.9875175899F, 0.9877445067F, 0.9879684396F,
  158569. 0.9881894112F, 0.9884074444F, 0.9886225619F, 0.9888347863F,
  158570. 0.9890441404F, 0.9892506468F, 0.9894543284F, 0.9896552077F,
  158571. 0.9898533074F, 0.9900486502F, 0.9902412587F, 0.9904311555F,
  158572. 0.9906183633F, 0.9908029045F, 0.9909848019F, 0.9911640779F,
  158573. 0.9913407550F, 0.9915148557F, 0.9916864025F, 0.9918554179F,
  158574. 0.9920219241F, 0.9921859437F, 0.9923474989F, 0.9925066120F,
  158575. 0.9926633054F, 0.9928176012F, 0.9929695218F, 0.9931190891F,
  158576. 0.9932663254F, 0.9934112527F, 0.9935538932F, 0.9936942686F,
  158577. 0.9938324012F, 0.9939683126F, 0.9941020248F, 0.9942335597F,
  158578. 0.9943629388F, 0.9944901841F, 0.9946153170F, 0.9947383593F,
  158579. 0.9948593325F, 0.9949782579F, 0.9950951572F, 0.9952100516F,
  158580. 0.9953229625F, 0.9954339111F, 0.9955429186F, 0.9956500062F,
  158581. 0.9957551948F, 0.9958585056F, 0.9959599593F, 0.9960595769F,
  158582. 0.9961573792F, 0.9962533869F, 0.9963476206F, 0.9964401009F,
  158583. 0.9965308483F, 0.9966198833F, 0.9967072261F, 0.9967928971F,
  158584. 0.9968769164F, 0.9969593041F, 0.9970400804F, 0.9971192651F,
  158585. 0.9971968781F, 0.9972729391F, 0.9973474680F, 0.9974204842F,
  158586. 0.9974920074F, 0.9975620569F, 0.9976306521F, 0.9976978122F,
  158587. 0.9977635565F, 0.9978279039F, 0.9978908736F, 0.9979524842F,
  158588. 0.9980127547F, 0.9980717037F, 0.9981293499F, 0.9981857116F,
  158589. 0.9982408073F, 0.9982946554F, 0.9983472739F, 0.9983986810F,
  158590. 0.9984488947F, 0.9984979328F, 0.9985458132F, 0.9985925534F,
  158591. 0.9986381711F, 0.9986826838F, 0.9987261086F, 0.9987684630F,
  158592. 0.9988097640F, 0.9988500286F, 0.9988892738F, 0.9989275163F,
  158593. 0.9989647727F, 0.9990010597F, 0.9990363938F, 0.9990707911F,
  158594. 0.9991042679F, 0.9991368404F, 0.9991685244F, 0.9991993358F,
  158595. 0.9992292905F, 0.9992584038F, 0.9992866914F, 0.9993141686F,
  158596. 0.9993408506F, 0.9993667526F, 0.9993918895F, 0.9994162761F,
  158597. 0.9994399273F, 0.9994628576F, 0.9994850815F, 0.9995066133F,
  158598. 0.9995274672F, 0.9995476574F, 0.9995671978F, 0.9995861021F,
  158599. 0.9996043841F, 0.9996220573F, 0.9996391352F, 0.9996556310F,
  158600. 0.9996715579F, 0.9996869288F, 0.9997017568F, 0.9997160543F,
  158601. 0.9997298342F, 0.9997431088F, 0.9997558905F, 0.9997681914F,
  158602. 0.9997800236F, 0.9997913990F, 0.9998023292F, 0.9998128261F,
  158603. 0.9998229009F, 0.9998325650F, 0.9998418296F, 0.9998507058F,
  158604. 0.9998592044F, 0.9998673362F, 0.9998751117F, 0.9998825415F,
  158605. 0.9998896358F, 0.9998964047F, 0.9999028584F, 0.9999090066F,
  158606. 0.9999148590F, 0.9999204253F, 0.9999257148F, 0.9999307368F,
  158607. 0.9999355003F, 0.9999400144F, 0.9999442878F, 0.9999483293F,
  158608. 0.9999521472F, 0.9999557499F, 0.9999591457F, 0.9999623426F,
  158609. 0.9999653483F, 0.9999681708F, 0.9999708175F, 0.9999732959F,
  158610. 0.9999756132F, 0.9999777765F, 0.9999797928F, 0.9999816688F,
  158611. 0.9999834113F, 0.9999850266F, 0.9999865211F, 0.9999879009F,
  158612. 0.9999891721F, 0.9999903405F, 0.9999914118F, 0.9999923914F,
  158613. 0.9999932849F, 0.9999940972F, 0.9999948336F, 0.9999954989F,
  158614. 0.9999960978F, 0.9999966349F, 0.9999971146F, 0.9999975411F,
  158615. 0.9999979185F, 0.9999982507F, 0.9999985414F, 0.9999987944F,
  158616. 0.9999990129F, 0.9999992003F, 0.9999993596F, 0.9999994939F,
  158617. 0.9999996059F, 0.9999996981F, 0.9999997732F, 0.9999998333F,
  158618. 0.9999998805F, 0.9999999170F, 0.9999999444F, 0.9999999643F,
  158619. 0.9999999784F, 0.9999999878F, 0.9999999937F, 0.9999999972F,
  158620. 0.9999999990F, 0.9999999997F, 1.0000000000F, 1.0000000000F,
  158621. };
  158622. static float vwin4096[2048] = {
  158623. 0.0000002310F, 0.0000020791F, 0.0000057754F, 0.0000113197F,
  158624. 0.0000187121F, 0.0000279526F, 0.0000390412F, 0.0000519777F,
  158625. 0.0000667623F, 0.0000833949F, 0.0001018753F, 0.0001222036F,
  158626. 0.0001443798F, 0.0001684037F, 0.0001942754F, 0.0002219947F,
  158627. 0.0002515616F, 0.0002829761F, 0.0003162380F, 0.0003513472F,
  158628. 0.0003883038F, 0.0004271076F, 0.0004677584F, 0.0005102563F,
  158629. 0.0005546011F, 0.0006007928F, 0.0006488311F, 0.0006987160F,
  158630. 0.0007504474F, 0.0008040251F, 0.0008594490F, 0.0009167191F,
  158631. 0.0009758351F, 0.0010367969F, 0.0010996044F, 0.0011642574F,
  158632. 0.0012307558F, 0.0012990994F, 0.0013692880F, 0.0014413216F,
  158633. 0.0015151998F, 0.0015909226F, 0.0016684898F, 0.0017479011F,
  158634. 0.0018291565F, 0.0019122556F, 0.0019971983F, 0.0020839845F,
  158635. 0.0021726138F, 0.0022630861F, 0.0023554012F, 0.0024495588F,
  158636. 0.0025455588F, 0.0026434008F, 0.0027430847F, 0.0028446103F,
  158637. 0.0029479772F, 0.0030531853F, 0.0031602342F, 0.0032691238F,
  158638. 0.0033798538F, 0.0034924239F, 0.0036068338F, 0.0037230833F,
  158639. 0.0038411721F, 0.0039610999F, 0.0040828664F, 0.0042064714F,
  158640. 0.0043319145F, 0.0044591954F, 0.0045883139F, 0.0047192696F,
  158641. 0.0048520622F, 0.0049866914F, 0.0051231569F, 0.0052614583F,
  158642. 0.0054015953F, 0.0055435676F, 0.0056873748F, 0.0058330166F,
  158643. 0.0059804926F, 0.0061298026F, 0.0062809460F, 0.0064339226F,
  158644. 0.0065887320F, 0.0067453738F, 0.0069038476F, 0.0070641531F,
  158645. 0.0072262899F, 0.0073902575F, 0.0075560556F, 0.0077236838F,
  158646. 0.0078931417F, 0.0080644288F, 0.0082375447F, 0.0084124891F,
  158647. 0.0085892615F, 0.0087678614F, 0.0089482885F, 0.0091305422F,
  158648. 0.0093146223F, 0.0095005281F, 0.0096882592F, 0.0098778153F,
  158649. 0.0100691958F, 0.0102624002F, 0.0104574281F, 0.0106542791F,
  158650. 0.0108529525F, 0.0110534480F, 0.0112557651F, 0.0114599032F,
  158651. 0.0116658618F, 0.0118736405F, 0.0120832387F, 0.0122946560F,
  158652. 0.0125078917F, 0.0127229454F, 0.0129398166F, 0.0131585046F,
  158653. 0.0133790090F, 0.0136013292F, 0.0138254647F, 0.0140514149F,
  158654. 0.0142791792F, 0.0145087572F, 0.0147401481F, 0.0149733515F,
  158655. 0.0152083667F, 0.0154451932F, 0.0156838304F, 0.0159242777F,
  158656. 0.0161665345F, 0.0164106001F, 0.0166564741F, 0.0169041557F,
  158657. 0.0171536443F, 0.0174049393F, 0.0176580401F, 0.0179129461F,
  158658. 0.0181696565F, 0.0184281708F, 0.0186884883F, 0.0189506084F,
  158659. 0.0192145303F, 0.0194802535F, 0.0197477772F, 0.0200171008F,
  158660. 0.0202882236F, 0.0205611449F, 0.0208358639F, 0.0211123801F,
  158661. 0.0213906927F, 0.0216708011F, 0.0219527043F, 0.0222364019F,
  158662. 0.0225218930F, 0.0228091769F, 0.0230982529F, 0.0233891203F,
  158663. 0.0236817782F, 0.0239762259F, 0.0242724628F, 0.0245704880F,
  158664. 0.0248703007F, 0.0251719002F, 0.0254752858F, 0.0257804565F,
  158665. 0.0260874117F, 0.0263961506F, 0.0267066722F, 0.0270189760F,
  158666. 0.0273330609F, 0.0276489263F, 0.0279665712F, 0.0282859949F,
  158667. 0.0286071966F, 0.0289301753F, 0.0292549303F, 0.0295814607F,
  158668. 0.0299097656F, 0.0302398442F, 0.0305716957F, 0.0309053191F,
  158669. 0.0312407135F, 0.0315778782F, 0.0319168122F, 0.0322575145F,
  158670. 0.0325999844F, 0.0329442209F, 0.0332902231F, 0.0336379900F,
  158671. 0.0339875208F, 0.0343388146F, 0.0346918703F, 0.0350466871F,
  158672. 0.0354032640F, 0.0357616000F, 0.0361216943F, 0.0364835458F,
  158673. 0.0368471535F, 0.0372125166F, 0.0375796339F, 0.0379485046F,
  158674. 0.0383191276F, 0.0386915020F, 0.0390656267F, 0.0394415008F,
  158675. 0.0398191231F, 0.0401984927F, 0.0405796086F, 0.0409624698F,
  158676. 0.0413470751F, 0.0417334235F, 0.0421215141F, 0.0425113457F,
  158677. 0.0429029172F, 0.0432962277F, 0.0436912760F, 0.0440880610F,
  158678. 0.0444865817F, 0.0448868370F, 0.0452888257F, 0.0456925468F,
  158679. 0.0460979992F, 0.0465051816F, 0.0469140931F, 0.0473247325F,
  158680. 0.0477370986F, 0.0481511902F, 0.0485670064F, 0.0489845458F,
  158681. 0.0494038074F, 0.0498247899F, 0.0502474922F, 0.0506719131F,
  158682. 0.0510980514F, 0.0515259060F, 0.0519554756F, 0.0523867590F,
  158683. 0.0528197550F, 0.0532544624F, 0.0536908800F, 0.0541290066F,
  158684. 0.0545688408F, 0.0550103815F, 0.0554536274F, 0.0558985772F,
  158685. 0.0563452297F, 0.0567935837F, 0.0572436377F, 0.0576953907F,
  158686. 0.0581488412F, 0.0586039880F, 0.0590608297F, 0.0595193651F,
  158687. 0.0599795929F, 0.0604415117F, 0.0609051202F, 0.0613704170F,
  158688. 0.0618374009F, 0.0623060704F, 0.0627764243F, 0.0632484611F,
  158689. 0.0637221795F, 0.0641975781F, 0.0646746555F, 0.0651534104F,
  158690. 0.0656338413F, 0.0661159469F, 0.0665997257F, 0.0670851763F,
  158691. 0.0675722973F, 0.0680610873F, 0.0685515448F, 0.0690436684F,
  158692. 0.0695374567F, 0.0700329081F, 0.0705300213F, 0.0710287947F,
  158693. 0.0715292269F, 0.0720313163F, 0.0725350616F, 0.0730404612F,
  158694. 0.0735475136F, 0.0740562172F, 0.0745665707F, 0.0750785723F,
  158695. 0.0755922207F, 0.0761075143F, 0.0766244515F, 0.0771430307F,
  158696. 0.0776632505F, 0.0781851092F, 0.0787086052F, 0.0792337371F,
  158697. 0.0797605032F, 0.0802889018F, 0.0808189315F, 0.0813505905F,
  158698. 0.0818838773F, 0.0824187903F, 0.0829553277F, 0.0834934881F,
  158699. 0.0840332697F, 0.0845746708F, 0.0851176899F, 0.0856623252F,
  158700. 0.0862085751F, 0.0867564379F, 0.0873059119F, 0.0878569954F,
  158701. 0.0884096867F, 0.0889639840F, 0.0895198858F, 0.0900773902F,
  158702. 0.0906364955F, 0.0911972000F, 0.0917595019F, 0.0923233995F,
  158703. 0.0928888909F, 0.0934559745F, 0.0940246485F, 0.0945949110F,
  158704. 0.0951667604F, 0.0957401946F, 0.0963152121F, 0.0968918109F,
  158705. 0.0974699893F, 0.0980497454F, 0.0986310773F, 0.0992139832F,
  158706. 0.0997984614F, 0.1003845098F, 0.1009721267F, 0.1015613101F,
  158707. 0.1021520582F, 0.1027443692F, 0.1033382410F, 0.1039336718F,
  158708. 0.1045306597F, 0.1051292027F, 0.1057292990F, 0.1063309466F,
  158709. 0.1069341435F, 0.1075388878F, 0.1081451776F, 0.1087530108F,
  158710. 0.1093623856F, 0.1099732998F, 0.1105857516F, 0.1111997389F,
  158711. 0.1118152597F, 0.1124323121F, 0.1130508939F, 0.1136710032F,
  158712. 0.1142926379F, 0.1149157960F, 0.1155404755F, 0.1161666742F,
  158713. 0.1167943901F, 0.1174236211F, 0.1180543652F, 0.1186866202F,
  158714. 0.1193203841F, 0.1199556548F, 0.1205924300F, 0.1212307078F,
  158715. 0.1218704860F, 0.1225117624F, 0.1231545349F, 0.1237988013F,
  158716. 0.1244445596F, 0.1250918074F, 0.1257405427F, 0.1263907632F,
  158717. 0.1270424667F, 0.1276956512F, 0.1283503142F, 0.1290064537F,
  158718. 0.1296640674F, 0.1303231530F, 0.1309837084F, 0.1316457312F,
  158719. 0.1323092193F, 0.1329741703F, 0.1336405820F, 0.1343084520F,
  158720. 0.1349777782F, 0.1356485582F, 0.1363207897F, 0.1369944704F,
  158721. 0.1376695979F, 0.1383461700F, 0.1390241842F, 0.1397036384F,
  158722. 0.1403845300F, 0.1410668567F, 0.1417506162F, 0.1424358061F,
  158723. 0.1431224240F, 0.1438104674F, 0.1444999341F, 0.1451908216F,
  158724. 0.1458831274F, 0.1465768492F, 0.1472719844F, 0.1479685308F,
  158725. 0.1486664857F, 0.1493658468F, 0.1500666115F, 0.1507687775F,
  158726. 0.1514723422F, 0.1521773031F, 0.1528836577F, 0.1535914035F,
  158727. 0.1543005380F, 0.1550110587F, 0.1557229631F, 0.1564362485F,
  158728. 0.1571509124F, 0.1578669524F, 0.1585843657F, 0.1593031499F,
  158729. 0.1600233024F, 0.1607448205F, 0.1614677017F, 0.1621919433F,
  158730. 0.1629175428F, 0.1636444975F, 0.1643728047F, 0.1651024619F,
  158731. 0.1658334665F, 0.1665658156F, 0.1672995067F, 0.1680345371F,
  158732. 0.1687709041F, 0.1695086050F, 0.1702476372F, 0.1709879978F,
  158733. 0.1717296843F, 0.1724726938F, 0.1732170237F, 0.1739626711F,
  158734. 0.1747096335F, 0.1754579079F, 0.1762074916F, 0.1769583819F,
  158735. 0.1777105760F, 0.1784640710F, 0.1792188642F, 0.1799749529F,
  158736. 0.1807323340F, 0.1814910049F, 0.1822509628F, 0.1830122046F,
  158737. 0.1837747277F, 0.1845385292F, 0.1853036062F, 0.1860699558F,
  158738. 0.1868375751F, 0.1876064613F, 0.1883766114F, 0.1891480226F,
  158739. 0.1899206919F, 0.1906946164F, 0.1914697932F, 0.1922462194F,
  158740. 0.1930238919F, 0.1938028079F, 0.1945829643F, 0.1953643583F,
  158741. 0.1961469868F, 0.1969308468F, 0.1977159353F, 0.1985022494F,
  158742. 0.1992897859F, 0.2000785420F, 0.2008685145F, 0.2016597005F,
  158743. 0.2024520968F, 0.2032457005F, 0.2040405084F, 0.2048365175F,
  158744. 0.2056337247F, 0.2064321269F, 0.2072317211F, 0.2080325041F,
  158745. 0.2088344727F, 0.2096376240F, 0.2104419547F, 0.2112474618F,
  158746. 0.2120541420F, 0.2128619923F, 0.2136710094F, 0.2144811902F,
  158747. 0.2152925315F, 0.2161050301F, 0.2169186829F, 0.2177334866F,
  158748. 0.2185494381F, 0.2193665340F, 0.2201847712F, 0.2210041465F,
  158749. 0.2218246565F, 0.2226462981F, 0.2234690680F, 0.2242929629F,
  158750. 0.2251179796F, 0.2259441147F, 0.2267713650F, 0.2275997272F,
  158751. 0.2284291979F, 0.2292597739F, 0.2300914518F, 0.2309242283F,
  158752. 0.2317581001F, 0.2325930638F, 0.2334291160F, 0.2342662534F,
  158753. 0.2351044727F, 0.2359437703F, 0.2367841431F, 0.2376255875F,
  158754. 0.2384681001F, 0.2393116776F, 0.2401563165F, 0.2410020134F,
  158755. 0.2418487649F, 0.2426965675F, 0.2435454178F, 0.2443953122F,
  158756. 0.2452462474F, 0.2460982199F, 0.2469512262F, 0.2478052628F,
  158757. 0.2486603262F, 0.2495164129F, 0.2503735194F, 0.2512316421F,
  158758. 0.2520907776F, 0.2529509222F, 0.2538120726F, 0.2546742250F,
  158759. 0.2555373760F, 0.2564015219F, 0.2572666593F, 0.2581327845F,
  158760. 0.2589998939F, 0.2598679840F, 0.2607370510F, 0.2616070916F,
  158761. 0.2624781019F, 0.2633500783F, 0.2642230173F, 0.2650969152F,
  158762. 0.2659717684F, 0.2668475731F, 0.2677243257F, 0.2686020226F,
  158763. 0.2694806601F, 0.2703602344F, 0.2712407419F, 0.2721221789F,
  158764. 0.2730045417F, 0.2738878265F, 0.2747720297F, 0.2756571474F,
  158765. 0.2765431760F, 0.2774301117F, 0.2783179508F, 0.2792066895F,
  158766. 0.2800963240F, 0.2809868505F, 0.2818782654F, 0.2827705647F,
  158767. 0.2836637447F, 0.2845578016F, 0.2854527315F, 0.2863485307F,
  158768. 0.2872451953F, 0.2881427215F, 0.2890411055F, 0.2899403433F,
  158769. 0.2908404312F, 0.2917413654F, 0.2926431418F, 0.2935457567F,
  158770. 0.2944492061F, 0.2953534863F, 0.2962585932F, 0.2971645230F,
  158771. 0.2980712717F, 0.2989788356F, 0.2998872105F, 0.3007963927F,
  158772. 0.3017063781F, 0.3026171629F, 0.3035287430F, 0.3044411145F,
  158773. 0.3053542736F, 0.3062682161F, 0.3071829381F, 0.3080984356F,
  158774. 0.3090147047F, 0.3099317413F, 0.3108495414F, 0.3117681011F,
  158775. 0.3126874163F, 0.3136074830F, 0.3145282972F, 0.3154498548F,
  158776. 0.3163721517F, 0.3172951841F, 0.3182189477F, 0.3191434385F,
  158777. 0.3200686525F, 0.3209945856F, 0.3219212336F, 0.3228485927F,
  158778. 0.3237766585F, 0.3247054271F, 0.3256348943F, 0.3265650560F,
  158779. 0.3274959081F, 0.3284274465F, 0.3293596671F, 0.3302925657F,
  158780. 0.3312261382F, 0.3321603804F, 0.3330952882F, 0.3340308574F,
  158781. 0.3349670838F, 0.3359039634F, 0.3368414919F, 0.3377796651F,
  158782. 0.3387184789F, 0.3396579290F, 0.3405980113F, 0.3415387216F,
  158783. 0.3424800556F, 0.3434220091F, 0.3443645779F, 0.3453077578F,
  158784. 0.3462515446F, 0.3471959340F, 0.3481409217F, 0.3490865036F,
  158785. 0.3500326754F, 0.3509794328F, 0.3519267715F, 0.3528746873F,
  158786. 0.3538231759F, 0.3547722330F, 0.3557218544F, 0.3566720357F,
  158787. 0.3576227727F, 0.3585740610F, 0.3595258964F, 0.3604782745F,
  158788. 0.3614311910F, 0.3623846417F, 0.3633386221F, 0.3642931280F,
  158789. 0.3652481549F, 0.3662036987F, 0.3671597548F, 0.3681163191F,
  158790. 0.3690733870F, 0.3700309544F, 0.3709890167F, 0.3719475696F,
  158791. 0.3729066089F, 0.3738661299F, 0.3748261285F, 0.3757866002F,
  158792. 0.3767475406F, 0.3777089453F, 0.3786708100F, 0.3796331302F,
  158793. 0.3805959014F, 0.3815591194F, 0.3825227796F, 0.3834868777F,
  158794. 0.3844514093F, 0.3854163698F, 0.3863817549F, 0.3873475601F,
  158795. 0.3883137810F, 0.3892804131F, 0.3902474521F, 0.3912148933F,
  158796. 0.3921827325F, 0.3931509650F, 0.3941195865F, 0.3950885925F,
  158797. 0.3960579785F, 0.3970277400F, 0.3979978725F, 0.3989683716F,
  158798. 0.3999392328F, 0.4009104516F, 0.4018820234F, 0.4028539438F,
  158799. 0.4038262084F, 0.4047988125F, 0.4057717516F, 0.4067450214F,
  158800. 0.4077186172F, 0.4086925345F, 0.4096667688F, 0.4106413155F,
  158801. 0.4116161703F, 0.4125913284F, 0.4135667854F, 0.4145425368F,
  158802. 0.4155185780F, 0.4164949044F, 0.4174715116F, 0.4184483949F,
  158803. 0.4194255498F, 0.4204029718F, 0.4213806563F, 0.4223585987F,
  158804. 0.4233367946F, 0.4243152392F, 0.4252939281F, 0.4262728566F,
  158805. 0.4272520202F, 0.4282314144F, 0.4292110345F, 0.4301908760F,
  158806. 0.4311709343F, 0.4321512047F, 0.4331316828F, 0.4341123639F,
  158807. 0.4350932435F, 0.4360743168F, 0.4370555794F, 0.4380370267F,
  158808. 0.4390186540F, 0.4400004567F, 0.4409824303F, 0.4419645701F,
  158809. 0.4429468716F, 0.4439293300F, 0.4449119409F, 0.4458946996F,
  158810. 0.4468776014F, 0.4478606418F, 0.4488438162F, 0.4498271199F,
  158811. 0.4508105483F, 0.4517940967F, 0.4527777607F, 0.4537615355F,
  158812. 0.4547454165F, 0.4557293991F, 0.4567134786F, 0.4576976505F,
  158813. 0.4586819101F, 0.4596662527F, 0.4606506738F, 0.4616351687F,
  158814. 0.4626197328F, 0.4636043614F, 0.4645890499F, 0.4655737936F,
  158815. 0.4665585880F, 0.4675434284F, 0.4685283101F, 0.4695132286F,
  158816. 0.4704981791F, 0.4714831570F, 0.4724681577F, 0.4734531766F,
  158817. 0.4744382089F, 0.4754232501F, 0.4764082956F, 0.4773933406F,
  158818. 0.4783783806F, 0.4793634108F, 0.4803484267F, 0.4813334237F,
  158819. 0.4823183969F, 0.4833033419F, 0.4842882540F, 0.4852731285F,
  158820. 0.4862579608F, 0.4872427462F, 0.4882274802F, 0.4892121580F,
  158821. 0.4901967751F, 0.4911813267F, 0.4921658083F, 0.4931502151F,
  158822. 0.4941345427F, 0.4951187863F, 0.4961029412F, 0.4970870029F,
  158823. 0.4980709667F, 0.4990548280F, 0.5000385822F, 0.5010222245F,
  158824. 0.5020057505F, 0.5029891553F, 0.5039724345F, 0.5049555834F,
  158825. 0.5059385973F, 0.5069214716F, 0.5079042018F, 0.5088867831F,
  158826. 0.5098692110F, 0.5108514808F, 0.5118335879F, 0.5128155277F,
  158827. 0.5137972956F, 0.5147788869F, 0.5157602971F, 0.5167415215F,
  158828. 0.5177225555F, 0.5187033945F, 0.5196840339F, 0.5206644692F,
  158829. 0.5216446956F, 0.5226247086F, 0.5236045035F, 0.5245840759F,
  158830. 0.5255634211F, 0.5265425344F, 0.5275214114F, 0.5285000474F,
  158831. 0.5294784378F, 0.5304565781F, 0.5314344637F, 0.5324120899F,
  158832. 0.5333894522F, 0.5343665461F, 0.5353433670F, 0.5363199102F,
  158833. 0.5372961713F, 0.5382721457F, 0.5392478287F, 0.5402232159F,
  158834. 0.5411983027F, 0.5421730845F, 0.5431475569F, 0.5441217151F,
  158835. 0.5450955548F, 0.5460690714F, 0.5470422602F, 0.5480151169F,
  158836. 0.5489876368F, 0.5499598155F, 0.5509316484F, 0.5519031310F,
  158837. 0.5528742587F, 0.5538450271F, 0.5548154317F, 0.5557854680F,
  158838. 0.5567551314F, 0.5577244174F, 0.5586933216F, 0.5596618395F,
  158839. 0.5606299665F, 0.5615976983F, 0.5625650302F, 0.5635319580F,
  158840. 0.5644984770F, 0.5654645828F, 0.5664302709F, 0.5673955370F,
  158841. 0.5683603765F, 0.5693247850F, 0.5702887580F, 0.5712522912F,
  158842. 0.5722153800F, 0.5731780200F, 0.5741402069F, 0.5751019362F,
  158843. 0.5760632034F, 0.5770240042F, 0.5779843341F, 0.5789441889F,
  158844. 0.5799035639F, 0.5808624549F, 0.5818208575F, 0.5827787673F,
  158845. 0.5837361800F, 0.5846930910F, 0.5856494961F, 0.5866053910F,
  158846. 0.5875607712F, 0.5885156324F, 0.5894699703F, 0.5904237804F,
  158847. 0.5913770586F, 0.5923298004F, 0.5932820016F, 0.5942336578F,
  158848. 0.5951847646F, 0.5961353179F, 0.5970853132F, 0.5980347464F,
  158849. 0.5989836131F, 0.5999319090F, 0.6008796298F, 0.6018267713F,
  158850. 0.6027733292F, 0.6037192993F, 0.6046646773F, 0.6056094589F,
  158851. 0.6065536400F, 0.6074972162F, 0.6084401833F, 0.6093825372F,
  158852. 0.6103242736F, 0.6112653884F, 0.6122058772F, 0.6131457359F,
  158853. 0.6140849604F, 0.6150235464F, 0.6159614897F, 0.6168987862F,
  158854. 0.6178354318F, 0.6187714223F, 0.6197067535F, 0.6206414213F,
  158855. 0.6215754215F, 0.6225087501F, 0.6234414028F, 0.6243733757F,
  158856. 0.6253046646F, 0.6262352654F, 0.6271651739F, 0.6280943862F,
  158857. 0.6290228982F, 0.6299507057F, 0.6308778048F, 0.6318041913F,
  158858. 0.6327298612F, 0.6336548105F, 0.6345790352F, 0.6355025312F,
  158859. 0.6364252945F, 0.6373473211F, 0.6382686070F, 0.6391891483F,
  158860. 0.6401089409F, 0.6410279808F, 0.6419462642F, 0.6428637869F,
  158861. 0.6437805452F, 0.6446965350F, 0.6456117524F, 0.6465261935F,
  158862. 0.6474398544F, 0.6483527311F, 0.6492648197F, 0.6501761165F,
  158863. 0.6510866174F, 0.6519963186F, 0.6529052162F, 0.6538133064F,
  158864. 0.6547205854F, 0.6556270492F, 0.6565326941F, 0.6574375162F,
  158865. 0.6583415117F, 0.6592446769F, 0.6601470079F, 0.6610485009F,
  158866. 0.6619491521F, 0.6628489578F, 0.6637479143F, 0.6646460177F,
  158867. 0.6655432643F, 0.6664396505F, 0.6673351724F, 0.6682298264F,
  158868. 0.6691236087F, 0.6700165157F, 0.6709085436F, 0.6717996889F,
  158869. 0.6726899478F, 0.6735793167F, 0.6744677918F, 0.6753553697F,
  158870. 0.6762420466F, 0.6771278190F, 0.6780126832F, 0.6788966357F,
  158871. 0.6797796728F, 0.6806617909F, 0.6815429866F, 0.6824232562F,
  158872. 0.6833025961F, 0.6841810030F, 0.6850584731F, 0.6859350031F,
  158873. 0.6868105894F, 0.6876852284F, 0.6885589168F, 0.6894316510F,
  158874. 0.6903034275F, 0.6911742430F, 0.6920440939F, 0.6929129769F,
  158875. 0.6937808884F, 0.6946478251F, 0.6955137837F, 0.6963787606F,
  158876. 0.6972427525F, 0.6981057560F, 0.6989677678F, 0.6998287845F,
  158877. 0.7006888028F, 0.7015478194F, 0.7024058309F, 0.7032628340F,
  158878. 0.7041188254F, 0.7049738019F, 0.7058277601F, 0.7066806969F,
  158879. 0.7075326089F, 0.7083834929F, 0.7092333457F, 0.7100821640F,
  158880. 0.7109299447F, 0.7117766846F, 0.7126223804F, 0.7134670291F,
  158881. 0.7143106273F, 0.7151531721F, 0.7159946602F, 0.7168350885F,
  158882. 0.7176744539F, 0.7185127534F, 0.7193499837F, 0.7201861418F,
  158883. 0.7210212247F, 0.7218552293F, 0.7226881526F, 0.7235199914F,
  158884. 0.7243507428F, 0.7251804039F, 0.7260089715F, 0.7268364426F,
  158885. 0.7276628144F, 0.7284880839F, 0.7293122481F, 0.7301353040F,
  158886. 0.7309572487F, 0.7317780794F, 0.7325977930F, 0.7334163868F,
  158887. 0.7342338579F, 0.7350502033F, 0.7358654202F, 0.7366795059F,
  158888. 0.7374924573F, 0.7383042718F, 0.7391149465F, 0.7399244787F,
  158889. 0.7407328655F, 0.7415401041F, 0.7423461920F, 0.7431511261F,
  158890. 0.7439549040F, 0.7447575227F, 0.7455589797F, 0.7463592723F,
  158891. 0.7471583976F, 0.7479563532F, 0.7487531363F, 0.7495487443F,
  158892. 0.7503431745F, 0.7511364244F, 0.7519284913F, 0.7527193726F,
  158893. 0.7535090658F, 0.7542975683F, 0.7550848776F, 0.7558709910F,
  158894. 0.7566559062F, 0.7574396205F, 0.7582221314F, 0.7590034366F,
  158895. 0.7597835334F, 0.7605624194F, 0.7613400923F, 0.7621165495F,
  158896. 0.7628917886F, 0.7636658072F, 0.7644386030F, 0.7652101735F,
  158897. 0.7659805164F, 0.7667496292F, 0.7675175098F, 0.7682841556F,
  158898. 0.7690495645F, 0.7698137341F, 0.7705766622F, 0.7713383463F,
  158899. 0.7720987844F, 0.7728579741F, 0.7736159132F, 0.7743725994F,
  158900. 0.7751280306F, 0.7758822046F, 0.7766351192F, 0.7773867722F,
  158901. 0.7781371614F, 0.7788862848F, 0.7796341401F, 0.7803807253F,
  158902. 0.7811260383F, 0.7818700769F, 0.7826128392F, 0.7833543230F,
  158903. 0.7840945263F, 0.7848334471F, 0.7855710833F, 0.7863074330F,
  158904. 0.7870424941F, 0.7877762647F, 0.7885087428F, 0.7892399264F,
  158905. 0.7899698137F, 0.7906984026F, 0.7914256914F, 0.7921516780F,
  158906. 0.7928763607F, 0.7935997375F, 0.7943218065F, 0.7950425661F,
  158907. 0.7957620142F, 0.7964801492F, 0.7971969692F, 0.7979124724F,
  158908. 0.7986266570F, 0.7993395214F, 0.8000510638F, 0.8007612823F,
  158909. 0.8014701754F, 0.8021777413F, 0.8028839784F, 0.8035888849F,
  158910. 0.8042924592F, 0.8049946997F, 0.8056956048F, 0.8063951727F,
  158911. 0.8070934020F, 0.8077902910F, 0.8084858381F, 0.8091800419F,
  158912. 0.8098729007F, 0.8105644130F, 0.8112545774F, 0.8119433922F,
  158913. 0.8126308561F, 0.8133169676F, 0.8140017251F, 0.8146851272F,
  158914. 0.8153671726F, 0.8160478598F, 0.8167271874F, 0.8174051539F,
  158915. 0.8180817582F, 0.8187569986F, 0.8194308741F, 0.8201033831F,
  158916. 0.8207745244F, 0.8214442966F, 0.8221126986F, 0.8227797290F,
  158917. 0.8234453865F, 0.8241096700F, 0.8247725781F, 0.8254341097F,
  158918. 0.8260942636F, 0.8267530385F, 0.8274104334F, 0.8280664470F,
  158919. 0.8287210782F, 0.8293743259F, 0.8300261889F, 0.8306766662F,
  158920. 0.8313257566F, 0.8319734591F, 0.8326197727F, 0.8332646963F,
  158921. 0.8339082288F, 0.8345503692F, 0.8351911167F, 0.8358304700F,
  158922. 0.8364684284F, 0.8371049907F, 0.8377401562F, 0.8383739238F,
  158923. 0.8390062927F, 0.8396372618F, 0.8402668305F, 0.8408949977F,
  158924. 0.8415217626F, 0.8421471245F, 0.8427710823F, 0.8433936354F,
  158925. 0.8440147830F, 0.8446345242F, 0.8452528582F, 0.8458697844F,
  158926. 0.8464853020F, 0.8470994102F, 0.8477121084F, 0.8483233958F,
  158927. 0.8489332718F, 0.8495417356F, 0.8501487866F, 0.8507544243F,
  158928. 0.8513586479F, 0.8519614568F, 0.8525628505F, 0.8531628283F,
  158929. 0.8537613897F, 0.8543585341F, 0.8549542611F, 0.8555485699F,
  158930. 0.8561414603F, 0.8567329315F, 0.8573229832F, 0.8579116149F,
  158931. 0.8584988262F, 0.8590846165F, 0.8596689855F, 0.8602519327F,
  158932. 0.8608334577F, 0.8614135603F, 0.8619922399F, 0.8625694962F,
  158933. 0.8631453289F, 0.8637197377F, 0.8642927222F, 0.8648642821F,
  158934. 0.8654344172F, 0.8660031272F, 0.8665704118F, 0.8671362708F,
  158935. 0.8677007039F, 0.8682637109F, 0.8688252917F, 0.8693854460F,
  158936. 0.8699441737F, 0.8705014745F, 0.8710573485F, 0.8716117953F,
  158937. 0.8721648150F, 0.8727164073F, 0.8732665723F, 0.8738153098F,
  158938. 0.8743626197F, 0.8749085021F, 0.8754529569F, 0.8759959840F,
  158939. 0.8765375835F, 0.8770777553F, 0.8776164996F, 0.8781538162F,
  158940. 0.8786897054F, 0.8792241670F, 0.8797572013F, 0.8802888082F,
  158941. 0.8808189880F, 0.8813477407F, 0.8818750664F, 0.8824009653F,
  158942. 0.8829254375F, 0.8834484833F, 0.8839701028F, 0.8844902961F,
  158943. 0.8850090636F, 0.8855264054F, 0.8860423218F, 0.8865568131F,
  158944. 0.8870698794F, 0.8875815212F, 0.8880917386F, 0.8886005319F,
  158945. 0.8891079016F, 0.8896138479F, 0.8901183712F, 0.8906214719F,
  158946. 0.8911231503F, 0.8916234067F, 0.8921222417F, 0.8926196556F,
  158947. 0.8931156489F, 0.8936102219F, 0.8941033752F, 0.8945951092F,
  158948. 0.8950854244F, 0.8955743212F, 0.8960618003F, 0.8965478621F,
  158949. 0.8970325071F, 0.8975157359F, 0.8979975490F, 0.8984779471F,
  158950. 0.8989569307F, 0.8994345004F, 0.8999106568F, 0.9003854005F,
  158951. 0.9008587323F, 0.9013306526F, 0.9018011623F, 0.9022702619F,
  158952. 0.9027379521F, 0.9032042337F, 0.9036691074F, 0.9041325739F,
  158953. 0.9045946339F, 0.9050552882F, 0.9055145376F, 0.9059723828F,
  158954. 0.9064288246F, 0.9068838638F, 0.9073375013F, 0.9077897379F,
  158955. 0.9082405743F, 0.9086900115F, 0.9091380503F, 0.9095846917F,
  158956. 0.9100299364F, 0.9104737854F, 0.9109162397F, 0.9113573001F,
  158957. 0.9117969675F, 0.9122352430F, 0.9126721275F, 0.9131076219F,
  158958. 0.9135417273F, 0.9139744447F, 0.9144057750F, 0.9148357194F,
  158959. 0.9152642787F, 0.9156914542F, 0.9161172468F, 0.9165416576F,
  158960. 0.9169646877F, 0.9173863382F, 0.9178066102F, 0.9182255048F,
  158961. 0.9186430232F, 0.9190591665F, 0.9194739359F, 0.9198873324F,
  158962. 0.9202993574F, 0.9207100120F, 0.9211192973F, 0.9215272147F,
  158963. 0.9219337653F, 0.9223389504F, 0.9227427713F, 0.9231452290F,
  158964. 0.9235463251F, 0.9239460607F, 0.9243444371F, 0.9247414557F,
  158965. 0.9251371177F, 0.9255314245F, 0.9259243774F, 0.9263159778F,
  158966. 0.9267062270F, 0.9270951264F, 0.9274826774F, 0.9278688814F,
  158967. 0.9282537398F, 0.9286372540F, 0.9290194254F, 0.9294002555F,
  158968. 0.9297797458F, 0.9301578976F, 0.9305347125F, 0.9309101919F,
  158969. 0.9312843373F, 0.9316571503F, 0.9320286323F, 0.9323987849F,
  158970. 0.9327676097F, 0.9331351080F, 0.9335012816F, 0.9338661320F,
  158971. 0.9342296607F, 0.9345918694F, 0.9349527596F, 0.9353123330F,
  158972. 0.9356705911F, 0.9360275357F, 0.9363831683F, 0.9367374905F,
  158973. 0.9370905042F, 0.9374422108F, 0.9377926122F, 0.9381417099F,
  158974. 0.9384895057F, 0.9388360014F, 0.9391811985F, 0.9395250989F,
  158975. 0.9398677043F, 0.9402090165F, 0.9405490371F, 0.9408877680F,
  158976. 0.9412252110F, 0.9415613678F, 0.9418962402F, 0.9422298301F,
  158977. 0.9425621392F, 0.9428931695F, 0.9432229226F, 0.9435514005F,
  158978. 0.9438786050F, 0.9442045381F, 0.9445292014F, 0.9448525971F,
  158979. 0.9451747268F, 0.9454955926F, 0.9458151963F, 0.9461335399F,
  158980. 0.9464506253F, 0.9467664545F, 0.9470810293F, 0.9473943517F,
  158981. 0.9477064238F, 0.9480172474F, 0.9483268246F, 0.9486351573F,
  158982. 0.9489422475F, 0.9492480973F, 0.9495527087F, 0.9498560837F,
  158983. 0.9501582243F, 0.9504591325F, 0.9507588105F, 0.9510572603F,
  158984. 0.9513544839F, 0.9516504834F, 0.9519452609F, 0.9522388186F,
  158985. 0.9525311584F, 0.9528222826F, 0.9531121932F, 0.9534008923F,
  158986. 0.9536883821F, 0.9539746647F, 0.9542597424F, 0.9545436171F,
  158987. 0.9548262912F, 0.9551077667F, 0.9553880459F, 0.9556671309F,
  158988. 0.9559450239F, 0.9562217272F, 0.9564972429F, 0.9567715733F,
  158989. 0.9570447206F, 0.9573166871F, 0.9575874749F, 0.9578570863F,
  158990. 0.9581255236F, 0.9583927890F, 0.9586588849F, 0.9589238134F,
  158991. 0.9591875769F, 0.9594501777F, 0.9597116180F, 0.9599719003F,
  158992. 0.9602310267F, 0.9604889995F, 0.9607458213F, 0.9610014942F,
  158993. 0.9612560206F, 0.9615094028F, 0.9617616433F, 0.9620127443F,
  158994. 0.9622627083F, 0.9625115376F, 0.9627592345F, 0.9630058016F,
  158995. 0.9632512411F, 0.9634955555F, 0.9637387471F, 0.9639808185F,
  158996. 0.9642217720F, 0.9644616100F, 0.9647003349F, 0.9649379493F,
  158997. 0.9651744556F, 0.9654098561F, 0.9656441534F, 0.9658773499F,
  158998. 0.9661094480F, 0.9663404504F, 0.9665703593F, 0.9667991774F,
  158999. 0.9670269071F, 0.9672535509F, 0.9674791114F, 0.9677035909F,
  159000. 0.9679269921F, 0.9681493174F, 0.9683705694F, 0.9685907506F,
  159001. 0.9688098636F, 0.9690279108F, 0.9692448948F, 0.9694608182F,
  159002. 0.9696756836F, 0.9698894934F, 0.9701022503F, 0.9703139569F,
  159003. 0.9705246156F, 0.9707342291F, 0.9709428000F, 0.9711503309F,
  159004. 0.9713568243F, 0.9715622829F, 0.9717667093F, 0.9719701060F,
  159005. 0.9721724757F, 0.9723738210F, 0.9725741446F, 0.9727734490F,
  159006. 0.9729717369F, 0.9731690109F, 0.9733652737F, 0.9735605279F,
  159007. 0.9737547762F, 0.9739480212F, 0.9741402656F, 0.9743315120F,
  159008. 0.9745217631F, 0.9747110216F, 0.9748992901F, 0.9750865714F,
  159009. 0.9752728681F, 0.9754581829F, 0.9756425184F, 0.9758258775F,
  159010. 0.9760082627F, 0.9761896768F, 0.9763701224F, 0.9765496024F,
  159011. 0.9767281193F, 0.9769056760F, 0.9770822751F, 0.9772579193F,
  159012. 0.9774326114F, 0.9776063542F, 0.9777791502F, 0.9779510023F,
  159013. 0.9781219133F, 0.9782918858F, 0.9784609226F, 0.9786290264F,
  159014. 0.9787962000F, 0.9789624461F, 0.9791277676F, 0.9792921671F,
  159015. 0.9794556474F, 0.9796182113F, 0.9797798615F, 0.9799406009F,
  159016. 0.9801004321F, 0.9802593580F, 0.9804173813F, 0.9805745049F,
  159017. 0.9807307314F, 0.9808860637F, 0.9810405046F, 0.9811940568F,
  159018. 0.9813467232F, 0.9814985065F, 0.9816494095F, 0.9817994351F,
  159019. 0.9819485860F, 0.9820968650F, 0.9822442750F, 0.9823908186F,
  159020. 0.9825364988F, 0.9826813184F, 0.9828252801F, 0.9829683868F,
  159021. 0.9831106413F, 0.9832520463F, 0.9833926048F, 0.9835323195F,
  159022. 0.9836711932F, 0.9838092288F, 0.9839464291F, 0.9840827969F,
  159023. 0.9842183351F, 0.9843530464F, 0.9844869337F, 0.9846199998F,
  159024. 0.9847522475F, 0.9848836798F, 0.9850142993F, 0.9851441090F,
  159025. 0.9852731117F, 0.9854013101F, 0.9855287073F, 0.9856553058F,
  159026. 0.9857811087F, 0.9859061188F, 0.9860303388F, 0.9861537717F,
  159027. 0.9862764202F, 0.9863982872F, 0.9865193756F, 0.9866396882F,
  159028. 0.9867592277F, 0.9868779972F, 0.9869959993F, 0.9871132370F,
  159029. 0.9872297131F, 0.9873454304F, 0.9874603918F, 0.9875746001F,
  159030. 0.9876880581F, 0.9878007688F, 0.9879127348F, 0.9880239592F,
  159031. 0.9881344447F, 0.9882441941F, 0.9883532104F, 0.9884614962F,
  159032. 0.9885690546F, 0.9886758883F, 0.9887820001F, 0.9888873930F,
  159033. 0.9889920697F, 0.9890960331F, 0.9891992859F, 0.9893018312F,
  159034. 0.9894036716F, 0.9895048100F, 0.9896052493F, 0.9897049923F,
  159035. 0.9898040418F, 0.9899024006F, 0.9900000717F, 0.9900970577F,
  159036. 0.9901933616F, 0.9902889862F, 0.9903839343F, 0.9904782087F,
  159037. 0.9905718122F, 0.9906647477F, 0.9907570180F, 0.9908486259F,
  159038. 0.9909395742F, 0.9910298658F, 0.9911195034F, 0.9912084899F,
  159039. 0.9912968281F, 0.9913845208F, 0.9914715708F, 0.9915579810F,
  159040. 0.9916437540F, 0.9917288928F, 0.9918134001F, 0.9918972788F,
  159041. 0.9919805316F, 0.9920631613F, 0.9921451707F, 0.9922265626F,
  159042. 0.9923073399F, 0.9923875052F, 0.9924670615F, 0.9925460114F,
  159043. 0.9926243577F, 0.9927021033F, 0.9927792508F, 0.9928558032F,
  159044. 0.9929317631F, 0.9930071333F, 0.9930819167F, 0.9931561158F,
  159045. 0.9932297337F, 0.9933027728F, 0.9933752362F, 0.9934471264F,
  159046. 0.9935184462F, 0.9935891985F, 0.9936593859F, 0.9937290112F,
  159047. 0.9937980771F, 0.9938665864F, 0.9939345418F, 0.9940019460F,
  159048. 0.9940688018F, 0.9941351118F, 0.9942008789F, 0.9942661057F,
  159049. 0.9943307950F, 0.9943949494F, 0.9944585717F, 0.9945216645F,
  159050. 0.9945842307F, 0.9946462728F, 0.9947077936F, 0.9947687957F,
  159051. 0.9948292820F, 0.9948892550F, 0.9949487174F, 0.9950076719F,
  159052. 0.9950661212F, 0.9951240679F, 0.9951815148F, 0.9952384645F,
  159053. 0.9952949196F, 0.9953508828F, 0.9954063568F, 0.9954613442F,
  159054. 0.9955158476F, 0.9955698697F, 0.9956234132F, 0.9956764806F,
  159055. 0.9957290746F, 0.9957811978F, 0.9958328528F, 0.9958840423F,
  159056. 0.9959347688F, 0.9959850351F, 0.9960348435F, 0.9960841969F,
  159057. 0.9961330977F, 0.9961815486F, 0.9962295521F, 0.9962771108F,
  159058. 0.9963242274F, 0.9963709043F, 0.9964171441F, 0.9964629494F,
  159059. 0.9965083228F, 0.9965532668F, 0.9965977840F, 0.9966418768F,
  159060. 0.9966855479F, 0.9967287998F, 0.9967716350F, 0.9968140559F,
  159061. 0.9968560653F, 0.9968976655F, 0.9969388591F, 0.9969796485F,
  159062. 0.9970200363F, 0.9970600250F, 0.9970996170F, 0.9971388149F,
  159063. 0.9971776211F, 0.9972160380F, 0.9972540683F, 0.9972917142F,
  159064. 0.9973289783F, 0.9973658631F, 0.9974023709F, 0.9974385042F,
  159065. 0.9974742655F, 0.9975096571F, 0.9975446816F, 0.9975793413F,
  159066. 0.9976136386F, 0.9976475759F, 0.9976811557F, 0.9977143803F,
  159067. 0.9977472521F, 0.9977797736F, 0.9978119470F, 0.9978437748F,
  159068. 0.9978752593F, 0.9979064029F, 0.9979372079F, 0.9979676768F,
  159069. 0.9979978117F, 0.9980276151F, 0.9980570893F, 0.9980862367F,
  159070. 0.9981150595F, 0.9981435600F, 0.9981717406F, 0.9981996035F,
  159071. 0.9982271511F, 0.9982543856F, 0.9982813093F, 0.9983079246F,
  159072. 0.9983342336F, 0.9983602386F, 0.9983859418F, 0.9984113456F,
  159073. 0.9984364522F, 0.9984612638F, 0.9984857825F, 0.9985100108F,
  159074. 0.9985339507F, 0.9985576044F, 0.9985809743F, 0.9986040624F,
  159075. 0.9986268710F, 0.9986494022F, 0.9986716583F, 0.9986936413F,
  159076. 0.9987153535F, 0.9987367969F, 0.9987579738F, 0.9987788864F,
  159077. 0.9987995366F, 0.9988199267F, 0.9988400587F, 0.9988599348F,
  159078. 0.9988795572F, 0.9988989278F, 0.9989180487F, 0.9989369222F,
  159079. 0.9989555501F, 0.9989739347F, 0.9989920780F, 0.9990099820F,
  159080. 0.9990276487F, 0.9990450803F, 0.9990622787F, 0.9990792460F,
  159081. 0.9990959841F, 0.9991124952F, 0.9991287812F, 0.9991448440F,
  159082. 0.9991606858F, 0.9991763084F, 0.9991917139F, 0.9992069042F,
  159083. 0.9992218813F, 0.9992366471F, 0.9992512035F, 0.9992655525F,
  159084. 0.9992796961F, 0.9992936361F, 0.9993073744F, 0.9993209131F,
  159085. 0.9993342538F, 0.9993473987F, 0.9993603494F, 0.9993731080F,
  159086. 0.9993856762F, 0.9993980559F, 0.9994102490F, 0.9994222573F,
  159087. 0.9994340827F, 0.9994457269F, 0.9994571918F, 0.9994684793F,
  159088. 0.9994795910F, 0.9994905288F, 0.9995012945F, 0.9995118898F,
  159089. 0.9995223165F, 0.9995325765F, 0.9995426713F, 0.9995526029F,
  159090. 0.9995623728F, 0.9995719829F, 0.9995814349F, 0.9995907304F,
  159091. 0.9995998712F, 0.9996088590F, 0.9996176954F, 0.9996263821F,
  159092. 0.9996349208F, 0.9996433132F, 0.9996515609F, 0.9996596656F,
  159093. 0.9996676288F, 0.9996754522F, 0.9996831375F, 0.9996906862F,
  159094. 0.9996981000F, 0.9997053804F, 0.9997125290F, 0.9997195474F,
  159095. 0.9997264371F, 0.9997331998F, 0.9997398369F, 0.9997463500F,
  159096. 0.9997527406F, 0.9997590103F, 0.9997651606F, 0.9997711930F,
  159097. 0.9997771089F, 0.9997829098F, 0.9997885973F, 0.9997941728F,
  159098. 0.9997996378F, 0.9998049936F, 0.9998102419F, 0.9998153839F,
  159099. 0.9998204211F, 0.9998253550F, 0.9998301868F, 0.9998349182F,
  159100. 0.9998395503F, 0.9998440847F, 0.9998485226F, 0.9998528654F,
  159101. 0.9998571146F, 0.9998612713F, 0.9998653370F, 0.9998693130F,
  159102. 0.9998732007F, 0.9998770012F, 0.9998807159F, 0.9998843461F,
  159103. 0.9998878931F, 0.9998913581F, 0.9998947424F, 0.9998980473F,
  159104. 0.9999012740F, 0.9999044237F, 0.9999074976F, 0.9999104971F,
  159105. 0.9999134231F, 0.9999162771F, 0.9999190601F, 0.9999217733F,
  159106. 0.9999244179F, 0.9999269950F, 0.9999295058F, 0.9999319515F,
  159107. 0.9999343332F, 0.9999366519F, 0.9999389088F, 0.9999411050F,
  159108. 0.9999432416F, 0.9999453196F, 0.9999473402F, 0.9999493044F,
  159109. 0.9999512132F, 0.9999530677F, 0.9999548690F, 0.9999566180F,
  159110. 0.9999583157F, 0.9999599633F, 0.9999615616F, 0.9999631116F,
  159111. 0.9999646144F, 0.9999660709F, 0.9999674820F, 0.9999688487F,
  159112. 0.9999701719F, 0.9999714526F, 0.9999726917F, 0.9999738900F,
  159113. 0.9999750486F, 0.9999761682F, 0.9999772497F, 0.9999782941F,
  159114. 0.9999793021F, 0.9999802747F, 0.9999812126F, 0.9999821167F,
  159115. 0.9999829878F, 0.9999838268F, 0.9999846343F, 0.9999854113F,
  159116. 0.9999861584F, 0.9999868765F, 0.9999875664F, 0.9999882287F,
  159117. 0.9999888642F, 0.9999894736F, 0.9999900577F, 0.9999906172F,
  159118. 0.9999911528F, 0.9999916651F, 0.9999921548F, 0.9999926227F,
  159119. 0.9999930693F, 0.9999934954F, 0.9999939015F, 0.9999942883F,
  159120. 0.9999946564F, 0.9999950064F, 0.9999953390F, 0.9999956547F,
  159121. 0.9999959541F, 0.9999962377F, 0.9999965062F, 0.9999967601F,
  159122. 0.9999969998F, 0.9999972260F, 0.9999974392F, 0.9999976399F,
  159123. 0.9999978285F, 0.9999980056F, 0.9999981716F, 0.9999983271F,
  159124. 0.9999984724F, 0.9999986081F, 0.9999987345F, 0.9999988521F,
  159125. 0.9999989613F, 0.9999990625F, 0.9999991562F, 0.9999992426F,
  159126. 0.9999993223F, 0.9999993954F, 0.9999994625F, 0.9999995239F,
  159127. 0.9999995798F, 0.9999996307F, 0.9999996768F, 0.9999997184F,
  159128. 0.9999997559F, 0.9999997895F, 0.9999998195F, 0.9999998462F,
  159129. 0.9999998698F, 0.9999998906F, 0.9999999088F, 0.9999999246F,
  159130. 0.9999999383F, 0.9999999500F, 0.9999999600F, 0.9999999684F,
  159131. 0.9999999754F, 0.9999999811F, 0.9999999858F, 0.9999999896F,
  159132. 0.9999999925F, 0.9999999948F, 0.9999999965F, 0.9999999978F,
  159133. 0.9999999986F, 0.9999999992F, 0.9999999996F, 0.9999999998F,
  159134. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  159135. };
  159136. static float vwin8192[4096] = {
  159137. 0.0000000578F, 0.0000005198F, 0.0000014438F, 0.0000028299F,
  159138. 0.0000046780F, 0.0000069882F, 0.0000097604F, 0.0000129945F,
  159139. 0.0000166908F, 0.0000208490F, 0.0000254692F, 0.0000305515F,
  159140. 0.0000360958F, 0.0000421021F, 0.0000485704F, 0.0000555006F,
  159141. 0.0000628929F, 0.0000707472F, 0.0000790635F, 0.0000878417F,
  159142. 0.0000970820F, 0.0001067842F, 0.0001169483F, 0.0001275744F,
  159143. 0.0001386625F, 0.0001502126F, 0.0001622245F, 0.0001746984F,
  159144. 0.0001876343F, 0.0002010320F, 0.0002148917F, 0.0002292132F,
  159145. 0.0002439967F, 0.0002592421F, 0.0002749493F, 0.0002911184F,
  159146. 0.0003077493F, 0.0003248421F, 0.0003423967F, 0.0003604132F,
  159147. 0.0003788915F, 0.0003978316F, 0.0004172335F, 0.0004370971F,
  159148. 0.0004574226F, 0.0004782098F, 0.0004994587F, 0.0005211694F,
  159149. 0.0005433418F, 0.0005659759F, 0.0005890717F, 0.0006126292F,
  159150. 0.0006366484F, 0.0006611292F, 0.0006860716F, 0.0007114757F,
  159151. 0.0007373414F, 0.0007636687F, 0.0007904576F, 0.0008177080F,
  159152. 0.0008454200F, 0.0008735935F, 0.0009022285F, 0.0009313250F,
  159153. 0.0009608830F, 0.0009909025F, 0.0010213834F, 0.0010523257F,
  159154. 0.0010837295F, 0.0011155946F, 0.0011479211F, 0.0011807090F,
  159155. 0.0012139582F, 0.0012476687F, 0.0012818405F, 0.0013164736F,
  159156. 0.0013515679F, 0.0013871235F, 0.0014231402F, 0.0014596182F,
  159157. 0.0014965573F, 0.0015339576F, 0.0015718190F, 0.0016101415F,
  159158. 0.0016489251F, 0.0016881698F, 0.0017278754F, 0.0017680421F,
  159159. 0.0018086698F, 0.0018497584F, 0.0018913080F, 0.0019333185F,
  159160. 0.0019757898F, 0.0020187221F, 0.0020621151F, 0.0021059690F,
  159161. 0.0021502837F, 0.0021950591F, 0.0022402953F, 0.0022859921F,
  159162. 0.0023321497F, 0.0023787679F, 0.0024258467F, 0.0024733861F,
  159163. 0.0025213861F, 0.0025698466F, 0.0026187676F, 0.0026681491F,
  159164. 0.0027179911F, 0.0027682935F, 0.0028190562F, 0.0028702794F,
  159165. 0.0029219628F, 0.0029741066F, 0.0030267107F, 0.0030797749F,
  159166. 0.0031332994F, 0.0031872841F, 0.0032417289F, 0.0032966338F,
  159167. 0.0033519988F, 0.0034078238F, 0.0034641089F, 0.0035208539F,
  159168. 0.0035780589F, 0.0036357237F, 0.0036938485F, 0.0037524331F,
  159169. 0.0038114775F, 0.0038709817F, 0.0039309456F, 0.0039913692F,
  159170. 0.0040522524F, 0.0041135953F, 0.0041753978F, 0.0042376599F,
  159171. 0.0043003814F, 0.0043635624F, 0.0044272029F, 0.0044913028F,
  159172. 0.0045558620F, 0.0046208806F, 0.0046863585F, 0.0047522955F,
  159173. 0.0048186919F, 0.0048855473F, 0.0049528619F, 0.0050206356F,
  159174. 0.0050888684F, 0.0051575601F, 0.0052267108F, 0.0052963204F,
  159175. 0.0053663890F, 0.0054369163F, 0.0055079025F, 0.0055793474F,
  159176. 0.0056512510F, 0.0057236133F, 0.0057964342F, 0.0058697137F,
  159177. 0.0059434517F, 0.0060176482F, 0.0060923032F, 0.0061674166F,
  159178. 0.0062429883F, 0.0063190183F, 0.0063955066F, 0.0064724532F,
  159179. 0.0065498579F, 0.0066277207F, 0.0067060416F, 0.0067848205F,
  159180. 0.0068640575F, 0.0069437523F, 0.0070239051F, 0.0071045157F,
  159181. 0.0071855840F, 0.0072671102F, 0.0073490940F, 0.0074315355F,
  159182. 0.0075144345F, 0.0075977911F, 0.0076816052F, 0.0077658768F,
  159183. 0.0078506057F, 0.0079357920F, 0.0080214355F, 0.0081075363F,
  159184. 0.0081940943F, 0.0082811094F, 0.0083685816F, 0.0084565108F,
  159185. 0.0085448970F, 0.0086337401F, 0.0087230401F, 0.0088127969F,
  159186. 0.0089030104F, 0.0089936807F, 0.0090848076F, 0.0091763911F,
  159187. 0.0092684311F, 0.0093609276F, 0.0094538805F, 0.0095472898F,
  159188. 0.0096411554F, 0.0097354772F, 0.0098302552F, 0.0099254894F,
  159189. 0.0100211796F, 0.0101173259F, 0.0102139281F, 0.0103109863F,
  159190. 0.0104085002F, 0.0105064700F, 0.0106048955F, 0.0107037766F,
  159191. 0.0108031133F, 0.0109029056F, 0.0110031534F, 0.0111038565F,
  159192. 0.0112050151F, 0.0113066289F, 0.0114086980F, 0.0115112222F,
  159193. 0.0116142015F, 0.0117176359F, 0.0118215252F, 0.0119258695F,
  159194. 0.0120306686F, 0.0121359225F, 0.0122416312F, 0.0123477944F,
  159195. 0.0124544123F, 0.0125614847F, 0.0126690116F, 0.0127769928F,
  159196. 0.0128854284F, 0.0129943182F, 0.0131036623F, 0.0132134604F,
  159197. 0.0133237126F, 0.0134344188F, 0.0135455790F, 0.0136571929F,
  159198. 0.0137692607F, 0.0138817821F, 0.0139947572F, 0.0141081859F,
  159199. 0.0142220681F, 0.0143364037F, 0.0144511927F, 0.0145664350F,
  159200. 0.0146821304F, 0.0147982791F, 0.0149148808F, 0.0150319355F,
  159201. 0.0151494431F, 0.0152674036F, 0.0153858168F, 0.0155046828F,
  159202. 0.0156240014F, 0.0157437726F, 0.0158639962F, 0.0159846723F,
  159203. 0.0161058007F, 0.0162273814F, 0.0163494142F, 0.0164718991F,
  159204. 0.0165948361F, 0.0167182250F, 0.0168420658F, 0.0169663584F,
  159205. 0.0170911027F, 0.0172162987F, 0.0173419462F, 0.0174680452F,
  159206. 0.0175945956F, 0.0177215974F, 0.0178490504F, 0.0179769545F,
  159207. 0.0181053098F, 0.0182341160F, 0.0183633732F, 0.0184930812F,
  159208. 0.0186232399F, 0.0187538494F, 0.0188849094F, 0.0190164200F,
  159209. 0.0191483809F, 0.0192807923F, 0.0194136539F, 0.0195469656F,
  159210. 0.0196807275F, 0.0198149394F, 0.0199496012F, 0.0200847128F,
  159211. 0.0202202742F, 0.0203562853F, 0.0204927460F, 0.0206296561F,
  159212. 0.0207670157F, 0.0209048245F, 0.0210430826F, 0.0211817899F,
  159213. 0.0213209462F, 0.0214605515F, 0.0216006057F, 0.0217411086F,
  159214. 0.0218820603F, 0.0220234605F, 0.0221653093F, 0.0223076066F,
  159215. 0.0224503521F, 0.0225935459F, 0.0227371879F, 0.0228812779F,
  159216. 0.0230258160F, 0.0231708018F, 0.0233162355F, 0.0234621169F,
  159217. 0.0236084459F, 0.0237552224F, 0.0239024462F, 0.0240501175F,
  159218. 0.0241982359F, 0.0243468015F, 0.0244958141F, 0.0246452736F,
  159219. 0.0247951800F, 0.0249455331F, 0.0250963329F, 0.0252475792F,
  159220. 0.0253992720F, 0.0255514111F, 0.0257039965F, 0.0258570281F,
  159221. 0.0260105057F, 0.0261644293F, 0.0263187987F, 0.0264736139F,
  159222. 0.0266288747F, 0.0267845811F, 0.0269407330F, 0.0270973302F,
  159223. 0.0272543727F, 0.0274118604F, 0.0275697930F, 0.0277281707F,
  159224. 0.0278869932F, 0.0280462604F, 0.0282059723F, 0.0283661287F,
  159225. 0.0285267295F, 0.0286877747F, 0.0288492641F, 0.0290111976F,
  159226. 0.0291735751F, 0.0293363965F, 0.0294996617F, 0.0296633706F,
  159227. 0.0298275231F, 0.0299921190F, 0.0301571583F, 0.0303226409F,
  159228. 0.0304885667F, 0.0306549354F, 0.0308217472F, 0.0309890017F,
  159229. 0.0311566989F, 0.0313248388F, 0.0314934211F, 0.0316624459F,
  159230. 0.0318319128F, 0.0320018220F, 0.0321721732F, 0.0323429663F,
  159231. 0.0325142013F, 0.0326858779F, 0.0328579962F, 0.0330305559F,
  159232. 0.0332035570F, 0.0333769994F, 0.0335508829F, 0.0337252074F,
  159233. 0.0338999728F, 0.0340751790F, 0.0342508259F, 0.0344269134F,
  159234. 0.0346034412F, 0.0347804094F, 0.0349578178F, 0.0351356663F,
  159235. 0.0353139548F, 0.0354926831F, 0.0356718511F, 0.0358514588F,
  159236. 0.0360315059F, 0.0362119924F, 0.0363929182F, 0.0365742831F,
  159237. 0.0367560870F, 0.0369383297F, 0.0371210113F, 0.0373041315F,
  159238. 0.0374876902F, 0.0376716873F, 0.0378561226F, 0.0380409961F,
  159239. 0.0382263077F, 0.0384120571F, 0.0385982443F, 0.0387848691F,
  159240. 0.0389719315F, 0.0391594313F, 0.0393473683F, 0.0395357425F,
  159241. 0.0397245537F, 0.0399138017F, 0.0401034866F, 0.0402936080F,
  159242. 0.0404841660F, 0.0406751603F, 0.0408665909F, 0.0410584576F,
  159243. 0.0412507603F, 0.0414434988F, 0.0416366731F, 0.0418302829F,
  159244. 0.0420243282F, 0.0422188088F, 0.0424137246F, 0.0426090755F,
  159245. 0.0428048613F, 0.0430010819F, 0.0431977371F, 0.0433948269F,
  159246. 0.0435923511F, 0.0437903095F, 0.0439887020F, 0.0441875285F,
  159247. 0.0443867889F, 0.0445864830F, 0.0447866106F, 0.0449871717F,
  159248. 0.0451881661F, 0.0453895936F, 0.0455914542F, 0.0457937477F,
  159249. 0.0459964738F, 0.0461996326F, 0.0464032239F, 0.0466072475F,
  159250. 0.0468117032F, 0.0470165910F, 0.0472219107F, 0.0474276622F,
  159251. 0.0476338452F, 0.0478404597F, 0.0480475056F, 0.0482549827F,
  159252. 0.0484628907F, 0.0486712297F, 0.0488799994F, 0.0490891998F,
  159253. 0.0492988306F, 0.0495088917F, 0.0497193830F, 0.0499303043F,
  159254. 0.0501416554F, 0.0503534363F, 0.0505656468F, 0.0507782867F,
  159255. 0.0509913559F, 0.0512048542F, 0.0514187815F, 0.0516331376F,
  159256. 0.0518479225F, 0.0520631358F, 0.0522787775F, 0.0524948475F,
  159257. 0.0527113455F, 0.0529282715F, 0.0531456252F, 0.0533634066F,
  159258. 0.0535816154F, 0.0538002515F, 0.0540193148F, 0.0542388051F,
  159259. 0.0544587222F, 0.0546790660F, 0.0548998364F, 0.0551210331F,
  159260. 0.0553426561F, 0.0555647051F, 0.0557871801F, 0.0560100807F,
  159261. 0.0562334070F, 0.0564571587F, 0.0566813357F, 0.0569059378F,
  159262. 0.0571309649F, 0.0573564168F, 0.0575822933F, 0.0578085942F,
  159263. 0.0580353195F, 0.0582624689F, 0.0584900423F, 0.0587180396F,
  159264. 0.0589464605F, 0.0591753049F, 0.0594045726F, 0.0596342635F,
  159265. 0.0598643774F, 0.0600949141F, 0.0603258735F, 0.0605572555F,
  159266. 0.0607890597F, 0.0610212862F, 0.0612539346F, 0.0614870049F,
  159267. 0.0617204968F, 0.0619544103F, 0.0621887451F, 0.0624235010F,
  159268. 0.0626586780F, 0.0628942758F, 0.0631302942F, 0.0633667331F,
  159269. 0.0636035923F, 0.0638408717F, 0.0640785710F, 0.0643166901F,
  159270. 0.0645552288F, 0.0647941870F, 0.0650335645F, 0.0652733610F,
  159271. 0.0655135765F, 0.0657542108F, 0.0659952636F, 0.0662367348F,
  159272. 0.0664786242F, 0.0667209316F, 0.0669636570F, 0.0672068000F,
  159273. 0.0674503605F, 0.0676943384F, 0.0679387334F, 0.0681835454F,
  159274. 0.0684287742F, 0.0686744196F, 0.0689204814F, 0.0691669595F,
  159275. 0.0694138536F, 0.0696611637F, 0.0699088894F, 0.0701570307F,
  159276. 0.0704055873F, 0.0706545590F, 0.0709039458F, 0.0711537473F,
  159277. 0.0714039634F, 0.0716545939F, 0.0719056387F, 0.0721570975F,
  159278. 0.0724089702F, 0.0726612565F, 0.0729139563F, 0.0731670694F,
  159279. 0.0734205956F, 0.0736745347F, 0.0739288866F, 0.0741836510F,
  159280. 0.0744388277F, 0.0746944166F, 0.0749504175F, 0.0752068301F,
  159281. 0.0754636543F, 0.0757208899F, 0.0759785367F, 0.0762365946F,
  159282. 0.0764950632F, 0.0767539424F, 0.0770132320F, 0.0772729319F,
  159283. 0.0775330418F, 0.0777935616F, 0.0780544909F, 0.0783158298F,
  159284. 0.0785775778F, 0.0788397349F, 0.0791023009F, 0.0793652755F,
  159285. 0.0796286585F, 0.0798924498F, 0.0801566492F, 0.0804212564F,
  159286. 0.0806862712F, 0.0809516935F, 0.0812175231F, 0.0814837597F,
  159287. 0.0817504031F, 0.0820174532F, 0.0822849097F, 0.0825527724F,
  159288. 0.0828210412F, 0.0830897158F, 0.0833587960F, 0.0836282816F,
  159289. 0.0838981724F, 0.0841684682F, 0.0844391688F, 0.0847102740F,
  159290. 0.0849817835F, 0.0852536973F, 0.0855260150F, 0.0857987364F,
  159291. 0.0860718614F, 0.0863453897F, 0.0866193211F, 0.0868936554F,
  159292. 0.0871683924F, 0.0874435319F, 0.0877190737F, 0.0879950175F,
  159293. 0.0882713632F, 0.0885481105F, 0.0888252592F, 0.0891028091F,
  159294. 0.0893807600F, 0.0896591117F, 0.0899378639F, 0.0902170165F,
  159295. 0.0904965692F, 0.0907765218F, 0.0910568740F, 0.0913376258F,
  159296. 0.0916187767F, 0.0919003268F, 0.0921822756F, 0.0924646230F,
  159297. 0.0927473687F, 0.0930305126F, 0.0933140545F, 0.0935979940F,
  159298. 0.0938823310F, 0.0941670653F, 0.0944521966F, 0.0947377247F,
  159299. 0.0950236494F, 0.0953099704F, 0.0955966876F, 0.0958838007F,
  159300. 0.0961713094F, 0.0964592136F, 0.0967475131F, 0.0970362075F,
  159301. 0.0973252967F, 0.0976147805F, 0.0979046585F, 0.0981949307F,
  159302. 0.0984855967F, 0.0987766563F, 0.0990681093F, 0.0993599555F,
  159303. 0.0996521945F, 0.0999448263F, 0.1002378506F, 0.1005312671F,
  159304. 0.1008250755F, 0.1011192757F, 0.1014138675F, 0.1017088505F,
  159305. 0.1020042246F, 0.1022999895F, 0.1025961450F, 0.1028926909F,
  159306. 0.1031896268F, 0.1034869526F, 0.1037846680F, 0.1040827729F,
  159307. 0.1043812668F, 0.1046801497F, 0.1049794213F, 0.1052790813F,
  159308. 0.1055791294F, 0.1058795656F, 0.1061803894F, 0.1064816006F,
  159309. 0.1067831991F, 0.1070851846F, 0.1073875568F, 0.1076903155F,
  159310. 0.1079934604F, 0.1082969913F, 0.1086009079F, 0.1089052101F,
  159311. 0.1092098975F, 0.1095149699F, 0.1098204270F, 0.1101262687F,
  159312. 0.1104324946F, 0.1107391045F, 0.1110460982F, 0.1113534754F,
  159313. 0.1116612359F, 0.1119693793F, 0.1122779055F, 0.1125868142F,
  159314. 0.1128961052F, 0.1132057781F, 0.1135158328F, 0.1138262690F,
  159315. 0.1141370863F, 0.1144482847F, 0.1147598638F, 0.1150718233F,
  159316. 0.1153841631F, 0.1156968828F, 0.1160099822F, 0.1163234610F,
  159317. 0.1166373190F, 0.1169515559F, 0.1172661714F, 0.1175811654F,
  159318. 0.1178965374F, 0.1182122874F, 0.1185284149F, 0.1188449198F,
  159319. 0.1191618018F, 0.1194790606F, 0.1197966960F, 0.1201147076F,
  159320. 0.1204330953F, 0.1207518587F, 0.1210709976F, 0.1213905118F,
  159321. 0.1217104009F, 0.1220306647F, 0.1223513029F, 0.1226723153F,
  159322. 0.1229937016F, 0.1233154615F, 0.1236375948F, 0.1239601011F,
  159323. 0.1242829803F, 0.1246062319F, 0.1249298559F, 0.1252538518F,
  159324. 0.1255782195F, 0.1259029586F, 0.1262280689F, 0.1265535501F,
  159325. 0.1268794019F, 0.1272056241F, 0.1275322163F, 0.1278591784F,
  159326. 0.1281865099F, 0.1285142108F, 0.1288422805F, 0.1291707190F,
  159327. 0.1294995259F, 0.1298287009F, 0.1301582437F, 0.1304881542F,
  159328. 0.1308184319F, 0.1311490766F, 0.1314800881F, 0.1318114660F,
  159329. 0.1321432100F, 0.1324753200F, 0.1328077955F, 0.1331406364F,
  159330. 0.1334738422F, 0.1338074129F, 0.1341413479F, 0.1344756472F,
  159331. 0.1348103103F, 0.1351453370F, 0.1354807270F, 0.1358164801F,
  159332. 0.1361525959F, 0.1364890741F, 0.1368259145F, 0.1371631167F,
  159333. 0.1375006805F, 0.1378386056F, 0.1381768917F, 0.1385155384F,
  159334. 0.1388545456F, 0.1391939129F, 0.1395336400F, 0.1398737266F,
  159335. 0.1402141724F, 0.1405549772F, 0.1408961406F, 0.1412376623F,
  159336. 0.1415795421F, 0.1419217797F, 0.1422643746F, 0.1426073268F,
  159337. 0.1429506358F, 0.1432943013F, 0.1436383231F, 0.1439827008F,
  159338. 0.1443274342F, 0.1446725229F, 0.1450179667F, 0.1453637652F,
  159339. 0.1457099181F, 0.1460564252F, 0.1464032861F, 0.1467505006F,
  159340. 0.1470980682F, 0.1474459888F, 0.1477942620F, 0.1481428875F,
  159341. 0.1484918651F, 0.1488411942F, 0.1491908748F, 0.1495409065F,
  159342. 0.1498912889F, 0.1502420218F, 0.1505931048F, 0.1509445376F,
  159343. 0.1512963200F, 0.1516484516F, 0.1520009321F, 0.1523537612F,
  159344. 0.1527069385F, 0.1530604638F, 0.1534143368F, 0.1537685571F,
  159345. 0.1541231244F, 0.1544780384F, 0.1548332987F, 0.1551889052F,
  159346. 0.1555448574F, 0.1559011550F, 0.1562577978F, 0.1566147853F,
  159347. 0.1569721173F, 0.1573297935F, 0.1576878135F, 0.1580461771F,
  159348. 0.1584048838F, 0.1587639334F, 0.1591233255F, 0.1594830599F,
  159349. 0.1598431361F, 0.1602035540F, 0.1605643131F, 0.1609254131F,
  159350. 0.1612868537F, 0.1616486346F, 0.1620107555F, 0.1623732160F,
  159351. 0.1627360158F, 0.1630991545F, 0.1634626319F, 0.1638264476F,
  159352. 0.1641906013F, 0.1645550926F, 0.1649199212F, 0.1652850869F,
  159353. 0.1656505892F, 0.1660164278F, 0.1663826024F, 0.1667491127F,
  159354. 0.1671159583F, 0.1674831388F, 0.1678506541F, 0.1682185036F,
  159355. 0.1685866872F, 0.1689552044F, 0.1693240549F, 0.1696932384F,
  159356. 0.1700627545F, 0.1704326029F, 0.1708027833F, 0.1711732952F,
  159357. 0.1715441385F, 0.1719153127F, 0.1722868175F, 0.1726586526F,
  159358. 0.1730308176F, 0.1734033121F, 0.1737761359F, 0.1741492886F,
  159359. 0.1745227698F, 0.1748965792F, 0.1752707164F, 0.1756451812F,
  159360. 0.1760199731F, 0.1763950918F, 0.1767705370F, 0.1771463083F,
  159361. 0.1775224054F, 0.1778988279F, 0.1782755754F, 0.1786526477F,
  159362. 0.1790300444F, 0.1794077651F, 0.1797858094F, 0.1801641771F,
  159363. 0.1805428677F, 0.1809218810F, 0.1813012165F, 0.1816808739F,
  159364. 0.1820608528F, 0.1824411530F, 0.1828217739F, 0.1832027154F,
  159365. 0.1835839770F, 0.1839655584F, 0.1843474592F, 0.1847296790F,
  159366. 0.1851122175F, 0.1854950744F, 0.1858782492F, 0.1862617417F,
  159367. 0.1866455514F, 0.1870296780F, 0.1874141211F, 0.1877988804F,
  159368. 0.1881839555F, 0.1885693461F, 0.1889550517F, 0.1893410721F,
  159369. 0.1897274068F, 0.1901140555F, 0.1905010178F, 0.1908882933F,
  159370. 0.1912758818F, 0.1916637828F, 0.1920519959F, 0.1924405208F,
  159371. 0.1928293571F, 0.1932185044F, 0.1936079625F, 0.1939977308F,
  159372. 0.1943878091F, 0.1947781969F, 0.1951688939F, 0.1955598998F,
  159373. 0.1959512141F, 0.1963428364F, 0.1967347665F, 0.1971270038F,
  159374. 0.1975195482F, 0.1979123990F, 0.1983055561F, 0.1986990190F,
  159375. 0.1990927873F, 0.1994868607F, 0.1998812388F, 0.2002759212F,
  159376. 0.2006709075F, 0.2010661974F, 0.2014617904F, 0.2018576862F,
  159377. 0.2022538844F, 0.2026503847F, 0.2030471865F, 0.2034442897F,
  159378. 0.2038416937F, 0.2042393982F, 0.2046374028F, 0.2050357071F,
  159379. 0.2054343107F, 0.2058332133F, 0.2062324145F, 0.2066319138F,
  159380. 0.2070317110F, 0.2074318055F, 0.2078321970F, 0.2082328852F,
  159381. 0.2086338696F, 0.2090351498F, 0.2094367255F, 0.2098385962F,
  159382. 0.2102407617F, 0.2106432213F, 0.2110459749F, 0.2114490220F,
  159383. 0.2118523621F, 0.2122559950F, 0.2126599202F, 0.2130641373F,
  159384. 0.2134686459F, 0.2138734456F, 0.2142785361F, 0.2146839168F,
  159385. 0.2150895875F, 0.2154955478F, 0.2159017972F, 0.2163083353F,
  159386. 0.2167151617F, 0.2171222761F, 0.2175296780F, 0.2179373670F,
  159387. 0.2183453428F, 0.2187536049F, 0.2191621529F, 0.2195709864F,
  159388. 0.2199801051F, 0.2203895085F, 0.2207991961F, 0.2212091677F,
  159389. 0.2216194228F, 0.2220299610F, 0.2224407818F, 0.2228518850F,
  159390. 0.2232632699F, 0.2236749364F, 0.2240868839F, 0.2244991121F,
  159391. 0.2249116204F, 0.2253244086F, 0.2257374763F, 0.2261508229F,
  159392. 0.2265644481F, 0.2269783514F, 0.2273925326F, 0.2278069911F,
  159393. 0.2282217265F, 0.2286367384F, 0.2290520265F, 0.2294675902F,
  159394. 0.2298834292F, 0.2302995431F, 0.2307159314F, 0.2311325937F,
  159395. 0.2315495297F, 0.2319667388F, 0.2323842207F, 0.2328019749F,
  159396. 0.2332200011F, 0.2336382988F, 0.2340568675F, 0.2344757070F,
  159397. 0.2348948166F, 0.2353141961F, 0.2357338450F, 0.2361537629F,
  159398. 0.2365739493F, 0.2369944038F, 0.2374151261F, 0.2378361156F,
  159399. 0.2382573720F, 0.2386788948F, 0.2391006836F, 0.2395227380F,
  159400. 0.2399450575F, 0.2403676417F, 0.2407904902F, 0.2412136026F,
  159401. 0.2416369783F, 0.2420606171F, 0.2424845185F, 0.2429086820F,
  159402. 0.2433331072F, 0.2437577936F, 0.2441827409F, 0.2446079486F,
  159403. 0.2450334163F, 0.2454591435F, 0.2458851298F, 0.2463113747F,
  159404. 0.2467378779F, 0.2471646389F, 0.2475916573F, 0.2480189325F,
  159405. 0.2484464643F, 0.2488742521F, 0.2493022955F, 0.2497305940F,
  159406. 0.2501591473F, 0.2505879549F, 0.2510170163F, 0.2514463311F,
  159407. 0.2518758989F, 0.2523057193F, 0.2527357916F, 0.2531661157F,
  159408. 0.2535966909F, 0.2540275169F, 0.2544585931F, 0.2548899193F,
  159409. 0.2553214948F, 0.2557533193F, 0.2561853924F, 0.2566177135F,
  159410. 0.2570502822F, 0.2574830981F, 0.2579161608F, 0.2583494697F,
  159411. 0.2587830245F, 0.2592168246F, 0.2596508697F, 0.2600851593F,
  159412. 0.2605196929F, 0.2609544701F, 0.2613894904F, 0.2618247534F,
  159413. 0.2622602586F, 0.2626960055F, 0.2631319938F, 0.2635682230F,
  159414. 0.2640046925F, 0.2644414021F, 0.2648783511F, 0.2653155391F,
  159415. 0.2657529657F, 0.2661906305F, 0.2666285329F, 0.2670666725F,
  159416. 0.2675050489F, 0.2679436616F, 0.2683825101F, 0.2688215940F,
  159417. 0.2692609127F, 0.2697004660F, 0.2701402532F, 0.2705802739F,
  159418. 0.2710205278F, 0.2714610142F, 0.2719017327F, 0.2723426830F,
  159419. 0.2727838644F, 0.2732252766F, 0.2736669191F, 0.2741087914F,
  159420. 0.2745508930F, 0.2749932235F, 0.2754357824F, 0.2758785693F,
  159421. 0.2763215837F, 0.2767648251F, 0.2772082930F, 0.2776519870F,
  159422. 0.2780959066F, 0.2785400513F, 0.2789844207F, 0.2794290143F,
  159423. 0.2798738316F, 0.2803188722F, 0.2807641355F, 0.2812096211F,
  159424. 0.2816553286F, 0.2821012574F, 0.2825474071F, 0.2829937773F,
  159425. 0.2834403673F, 0.2838871768F, 0.2843342053F, 0.2847814523F,
  159426. 0.2852289174F, 0.2856765999F, 0.2861244996F, 0.2865726159F,
  159427. 0.2870209482F, 0.2874694962F, 0.2879182594F, 0.2883672372F,
  159428. 0.2888164293F, 0.2892658350F, 0.2897154540F, 0.2901652858F,
  159429. 0.2906153298F, 0.2910655856F, 0.2915160527F, 0.2919667306F,
  159430. 0.2924176189F, 0.2928687171F, 0.2933200246F, 0.2937715409F,
  159431. 0.2942232657F, 0.2946751984F, 0.2951273386F, 0.2955796856F,
  159432. 0.2960322391F, 0.2964849986F, 0.2969379636F, 0.2973911335F,
  159433. 0.2978445080F, 0.2982980864F, 0.2987518684F, 0.2992058534F,
  159434. 0.2996600409F, 0.3001144305F, 0.3005690217F, 0.3010238139F,
  159435. 0.3014788067F, 0.3019339995F, 0.3023893920F, 0.3028449835F,
  159436. 0.3033007736F, 0.3037567618F, 0.3042129477F, 0.3046693306F,
  159437. 0.3051259102F, 0.3055826859F, 0.3060396572F, 0.3064968236F,
  159438. 0.3069541847F, 0.3074117399F, 0.3078694887F, 0.3083274307F,
  159439. 0.3087855653F, 0.3092438920F, 0.3097024104F, 0.3101611199F,
  159440. 0.3106200200F, 0.3110791103F, 0.3115383902F, 0.3119978592F,
  159441. 0.3124575169F, 0.3129173627F, 0.3133773961F, 0.3138376166F,
  159442. 0.3142980238F, 0.3147586170F, 0.3152193959F, 0.3156803598F,
  159443. 0.3161415084F, 0.3166028410F, 0.3170643573F, 0.3175260566F,
  159444. 0.3179879384F, 0.3184500023F, 0.3189122478F, 0.3193746743F,
  159445. 0.3198372814F, 0.3203000685F, 0.3207630351F, 0.3212261807F,
  159446. 0.3216895048F, 0.3221530069F, 0.3226166865F, 0.3230805430F,
  159447. 0.3235445760F, 0.3240087849F, 0.3244731693F, 0.3249377285F,
  159448. 0.3254024622F, 0.3258673698F, 0.3263324507F, 0.3267977045F,
  159449. 0.3272631306F, 0.3277287286F, 0.3281944978F, 0.3286604379F,
  159450. 0.3291265482F, 0.3295928284F, 0.3300592777F, 0.3305258958F,
  159451. 0.3309926821F, 0.3314596361F, 0.3319267573F, 0.3323940451F,
  159452. 0.3328614990F, 0.3333291186F, 0.3337969033F, 0.3342648525F,
  159453. 0.3347329658F, 0.3352012427F, 0.3356696825F, 0.3361382849F,
  159454. 0.3366070492F, 0.3370759749F, 0.3375450616F, 0.3380143087F,
  159455. 0.3384837156F, 0.3389532819F, 0.3394230071F, 0.3398928905F,
  159456. 0.3403629317F, 0.3408331302F, 0.3413034854F, 0.3417739967F,
  159457. 0.3422446638F, 0.3427154860F, 0.3431864628F, 0.3436575938F,
  159458. 0.3441288782F, 0.3446003158F, 0.3450719058F, 0.3455436478F,
  159459. 0.3460155412F, 0.3464875856F, 0.3469597804F, 0.3474321250F,
  159460. 0.3479046189F, 0.3483772617F, 0.3488500527F, 0.3493229914F,
  159461. 0.3497960774F, 0.3502693100F, 0.3507426887F, 0.3512162131F,
  159462. 0.3516898825F, 0.3521636965F, 0.3526376545F, 0.3531117559F,
  159463. 0.3535860003F, 0.3540603870F, 0.3545349157F, 0.3550095856F,
  159464. 0.3554843964F, 0.3559593474F, 0.3564344381F, 0.3569096680F,
  159465. 0.3573850366F, 0.3578605432F, 0.3583361875F, 0.3588119687F,
  159466. 0.3592878865F, 0.3597639402F, 0.3602401293F, 0.3607164533F,
  159467. 0.3611929117F, 0.3616695038F, 0.3621462292F, 0.3626230873F,
  159468. 0.3631000776F, 0.3635771995F, 0.3640544525F, 0.3645318360F,
  159469. 0.3650093496F, 0.3654869926F, 0.3659647645F, 0.3664426648F,
  159470. 0.3669206930F, 0.3673988484F, 0.3678771306F, 0.3683555390F,
  159471. 0.3688340731F, 0.3693127322F, 0.3697915160F, 0.3702704237F,
  159472. 0.3707494549F, 0.3712286091F, 0.3717078857F, 0.3721872840F,
  159473. 0.3726668037F, 0.3731464441F, 0.3736262047F, 0.3741060850F,
  159474. 0.3745860843F, 0.3750662023F, 0.3755464382F, 0.3760267915F,
  159475. 0.3765072618F, 0.3769878484F, 0.3774685509F, 0.3779493686F,
  159476. 0.3784303010F, 0.3789113475F, 0.3793925076F, 0.3798737809F,
  159477. 0.3803551666F, 0.3808366642F, 0.3813182733F, 0.3817999932F,
  159478. 0.3822818234F, 0.3827637633F, 0.3832458124F, 0.3837279702F,
  159479. 0.3842102360F, 0.3846926093F, 0.3851750897F, 0.3856576764F,
  159480. 0.3861403690F, 0.3866231670F, 0.3871060696F, 0.3875890765F,
  159481. 0.3880721870F, 0.3885554007F, 0.3890387168F, 0.3895221349F,
  159482. 0.3900056544F, 0.3904892748F, 0.3909729955F, 0.3914568160F,
  159483. 0.3919407356F, 0.3924247539F, 0.3929088702F, 0.3933930841F,
  159484. 0.3938773949F, 0.3943618021F, 0.3948463052F, 0.3953309035F,
  159485. 0.3958155966F, 0.3963003838F, 0.3967852646F, 0.3972702385F,
  159486. 0.3977553048F, 0.3982404631F, 0.3987257127F, 0.3992110531F,
  159487. 0.3996964838F, 0.4001820041F, 0.4006676136F, 0.4011533116F,
  159488. 0.4016390976F, 0.4021249710F, 0.4026109313F, 0.4030969779F,
  159489. 0.4035831102F, 0.4040693277F, 0.4045556299F, 0.4050420160F,
  159490. 0.4055284857F, 0.4060150383F, 0.4065016732F, 0.4069883899F,
  159491. 0.4074751879F, 0.4079620665F, 0.4084490252F, 0.4089360635F,
  159492. 0.4094231807F, 0.4099103763F, 0.4103976498F, 0.4108850005F,
  159493. 0.4113724280F, 0.4118599315F, 0.4123475107F, 0.4128351648F,
  159494. 0.4133228934F, 0.4138106959F, 0.4142985716F, 0.4147865201F,
  159495. 0.4152745408F, 0.4157626330F, 0.4162507963F, 0.4167390301F,
  159496. 0.4172273337F, 0.4177157067F, 0.4182041484F, 0.4186926583F,
  159497. 0.4191812359F, 0.4196698805F, 0.4201585915F, 0.4206473685F,
  159498. 0.4211362108F, 0.4216251179F, 0.4221140892F, 0.4226031241F,
  159499. 0.4230922221F, 0.4235813826F, 0.4240706050F, 0.4245598887F,
  159500. 0.4250492332F, 0.4255386379F, 0.4260281022F, 0.4265176256F,
  159501. 0.4270072075F, 0.4274968473F, 0.4279865445F, 0.4284762984F,
  159502. 0.4289661086F, 0.4294559743F, 0.4299458951F, 0.4304358704F,
  159503. 0.4309258996F, 0.4314159822F, 0.4319061175F, 0.4323963050F,
  159504. 0.4328865441F, 0.4333768342F, 0.4338671749F, 0.4343575654F,
  159505. 0.4348480052F, 0.4353384938F, 0.4358290306F, 0.4363196149F,
  159506. 0.4368102463F, 0.4373009241F, 0.4377916478F, 0.4382824168F,
  159507. 0.4387732305F, 0.4392640884F, 0.4397549899F, 0.4402459343F,
  159508. 0.4407369212F, 0.4412279499F, 0.4417190198F, 0.4422101305F,
  159509. 0.4427012813F, 0.4431924717F, 0.4436837010F, 0.4441749686F,
  159510. 0.4446662742F, 0.4451576169F, 0.4456489963F, 0.4461404118F,
  159511. 0.4466318628F, 0.4471233487F, 0.4476148690F, 0.4481064230F,
  159512. 0.4485980103F, 0.4490896302F, 0.4495812821F, 0.4500729654F,
  159513. 0.4505646797F, 0.4510564243F, 0.4515481986F, 0.4520400021F,
  159514. 0.4525318341F, 0.4530236942F, 0.4535155816F, 0.4540074959F,
  159515. 0.4544994365F, 0.4549914028F, 0.4554833941F, 0.4559754100F,
  159516. 0.4564674499F, 0.4569595131F, 0.4574515991F, 0.4579437074F,
  159517. 0.4584358372F, 0.4589279881F, 0.4594201595F, 0.4599123508F,
  159518. 0.4604045615F, 0.4608967908F, 0.4613890383F, 0.4618813034F,
  159519. 0.4623735855F, 0.4628658841F, 0.4633581984F, 0.4638505281F,
  159520. 0.4643428724F, 0.4648352308F, 0.4653276028F, 0.4658199877F,
  159521. 0.4663123849F, 0.4668047940F, 0.4672972143F, 0.4677896451F,
  159522. 0.4682820861F, 0.4687745365F, 0.4692669958F, 0.4697594634F,
  159523. 0.4702519387F, 0.4707444211F, 0.4712369102F, 0.4717294052F,
  159524. 0.4722219056F, 0.4727144109F, 0.4732069204F, 0.4736994336F,
  159525. 0.4741919498F, 0.4746844686F, 0.4751769893F, 0.4756695113F,
  159526. 0.4761620341F, 0.4766545571F, 0.4771470797F, 0.4776396013F,
  159527. 0.4781321213F, 0.4786246392F, 0.4791171544F, 0.4796096663F,
  159528. 0.4801021744F, 0.4805946779F, 0.4810871765F, 0.4815796694F,
  159529. 0.4820721561F, 0.4825646360F, 0.4830571086F, 0.4835495732F,
  159530. 0.4840420293F, 0.4845344763F, 0.4850269136F, 0.4855193407F,
  159531. 0.4860117569F, 0.4865041617F, 0.4869965545F, 0.4874889347F,
  159532. 0.4879813018F, 0.4884736551F, 0.4889659941F, 0.4894583182F,
  159533. 0.4899506268F, 0.4904429193F, 0.4909351952F, 0.4914274538F,
  159534. 0.4919196947F, 0.4924119172F, 0.4929041207F, 0.4933963046F,
  159535. 0.4938884685F, 0.4943806116F, 0.4948727335F, 0.4953648335F,
  159536. 0.4958569110F, 0.4963489656F, 0.4968409965F, 0.4973330032F,
  159537. 0.4978249852F, 0.4983169419F, 0.4988088726F, 0.4993007768F,
  159538. 0.4997926539F, 0.5002845034F, 0.5007763247F, 0.5012681171F,
  159539. 0.5017598801F, 0.5022516132F, 0.5027433157F, 0.5032349871F,
  159540. 0.5037266268F, 0.5042182341F, 0.5047098086F, 0.5052013497F,
  159541. 0.5056928567F, 0.5061843292F, 0.5066757664F, 0.5071671679F,
  159542. 0.5076585330F, 0.5081498613F, 0.5086411520F, 0.5091324047F,
  159543. 0.5096236187F, 0.5101147934F, 0.5106059284F, 0.5110970230F,
  159544. 0.5115880766F, 0.5120790887F, 0.5125700587F, 0.5130609860F,
  159545. 0.5135518700F, 0.5140427102F, 0.5145335059F, 0.5150242566F,
  159546. 0.5155149618F, 0.5160056208F, 0.5164962331F, 0.5169867980F,
  159547. 0.5174773151F, 0.5179677837F, 0.5184582033F, 0.5189485733F,
  159548. 0.5194388931F, 0.5199291621F, 0.5204193798F, 0.5209095455F,
  159549. 0.5213996588F, 0.5218897190F, 0.5223797256F, 0.5228696779F,
  159550. 0.5233595755F, 0.5238494177F, 0.5243392039F, 0.5248289337F,
  159551. 0.5253186063F, 0.5258082213F, 0.5262977781F, 0.5267872760F,
  159552. 0.5272767146F, 0.5277660932F, 0.5282554112F, 0.5287446682F,
  159553. 0.5292338635F, 0.5297229965F, 0.5302120667F, 0.5307010736F,
  159554. 0.5311900164F, 0.5316788947F, 0.5321677079F, 0.5326564554F,
  159555. 0.5331451366F, 0.5336337511F, 0.5341222981F, 0.5346107771F,
  159556. 0.5350991876F, 0.5355875290F, 0.5360758007F, 0.5365640021F,
  159557. 0.5370521327F, 0.5375401920F, 0.5380281792F, 0.5385160939F,
  159558. 0.5390039355F, 0.5394917034F, 0.5399793971F, 0.5404670159F,
  159559. 0.5409545594F, 0.5414420269F, 0.5419294179F, 0.5424167318F,
  159560. 0.5429039680F, 0.5433911261F, 0.5438782053F, 0.5443652051F,
  159561. 0.5448521250F, 0.5453389644F, 0.5458257228F, 0.5463123995F,
  159562. 0.5467989940F, 0.5472855057F, 0.5477719341F, 0.5482582786F,
  159563. 0.5487445387F, 0.5492307137F, 0.5497168031F, 0.5502028063F,
  159564. 0.5506887228F, 0.5511745520F, 0.5516602934F, 0.5521459463F,
  159565. 0.5526315103F, 0.5531169847F, 0.5536023690F, 0.5540876626F,
  159566. 0.5545728649F, 0.5550579755F, 0.5555429937F, 0.5560279189F,
  159567. 0.5565127507F, 0.5569974884F, 0.5574821315F, 0.5579666794F,
  159568. 0.5584511316F, 0.5589354875F, 0.5594197465F, 0.5599039080F,
  159569. 0.5603879716F, 0.5608719367F, 0.5613558026F, 0.5618395689F,
  159570. 0.5623232350F, 0.5628068002F, 0.5632902642F, 0.5637736262F,
  159571. 0.5642568858F, 0.5647400423F, 0.5652230953F, 0.5657060442F,
  159572. 0.5661888883F, 0.5666716272F, 0.5671542603F, 0.5676367870F,
  159573. 0.5681192069F, 0.5686015192F, 0.5690837235F, 0.5695658192F,
  159574. 0.5700478058F, 0.5705296827F, 0.5710114494F, 0.5714931052F,
  159575. 0.5719746497F, 0.5724560822F, 0.5729374023F, 0.5734186094F,
  159576. 0.5738997029F, 0.5743806823F, 0.5748615470F, 0.5753422965F,
  159577. 0.5758229301F, 0.5763034475F, 0.5767838480F, 0.5772641310F,
  159578. 0.5777442960F, 0.5782243426F, 0.5787042700F, 0.5791840778F,
  159579. 0.5796637654F, 0.5801433322F, 0.5806227778F, 0.5811021016F,
  159580. 0.5815813029F, 0.5820603814F, 0.5825393363F, 0.5830181673F,
  159581. 0.5834968737F, 0.5839754549F, 0.5844539105F, 0.5849322399F,
  159582. 0.5854104425F, 0.5858885179F, 0.5863664653F, 0.5868442844F,
  159583. 0.5873219746F, 0.5877995353F, 0.5882769660F, 0.5887542661F,
  159584. 0.5892314351F, 0.5897084724F, 0.5901853776F, 0.5906621500F,
  159585. 0.5911387892F, 0.5916152945F, 0.5920916655F, 0.5925679016F,
  159586. 0.5930440022F, 0.5935199669F, 0.5939957950F, 0.5944714861F,
  159587. 0.5949470396F, 0.5954224550F, 0.5958977317F, 0.5963728692F,
  159588. 0.5968478669F, 0.5973227244F, 0.5977974411F, 0.5982720163F,
  159589. 0.5987464497F, 0.5992207407F, 0.5996948887F, 0.6001688932F,
  159590. 0.6006427537F, 0.6011164696F, 0.6015900405F, 0.6020634657F,
  159591. 0.6025367447F, 0.6030098770F, 0.6034828621F, 0.6039556995F,
  159592. 0.6044283885F, 0.6049009288F, 0.6053733196F, 0.6058455606F,
  159593. 0.6063176512F, 0.6067895909F, 0.6072613790F, 0.6077330152F,
  159594. 0.6082044989F, 0.6086758295F, 0.6091470065F, 0.6096180294F,
  159595. 0.6100888977F, 0.6105596108F, 0.6110301682F, 0.6115005694F,
  159596. 0.6119708139F, 0.6124409011F, 0.6129108305F, 0.6133806017F,
  159597. 0.6138502139F, 0.6143196669F, 0.6147889599F, 0.6152580926F,
  159598. 0.6157270643F, 0.6161958746F, 0.6166645230F, 0.6171330088F,
  159599. 0.6176013317F, 0.6180694910F, 0.6185374863F, 0.6190053171F,
  159600. 0.6194729827F, 0.6199404828F, 0.6204078167F, 0.6208749841F,
  159601. 0.6213419842F, 0.6218088168F, 0.6222754811F, 0.6227419768F,
  159602. 0.6232083032F, 0.6236744600F, 0.6241404465F, 0.6246062622F,
  159603. 0.6250719067F, 0.6255373795F, 0.6260026799F, 0.6264678076F,
  159604. 0.6269327619F, 0.6273975425F, 0.6278621487F, 0.6283265800F,
  159605. 0.6287908361F, 0.6292549163F, 0.6297188201F, 0.6301825471F,
  159606. 0.6306460966F, 0.6311094683F, 0.6315726617F, 0.6320356761F,
  159607. 0.6324985111F, 0.6329611662F, 0.6334236410F, 0.6338859348F,
  159608. 0.6343480472F, 0.6348099777F, 0.6352717257F, 0.6357332909F,
  159609. 0.6361946726F, 0.6366558704F, 0.6371168837F, 0.6375777122F,
  159610. 0.6380383552F, 0.6384988123F, 0.6389590830F, 0.6394191668F,
  159611. 0.6398790631F, 0.6403387716F, 0.6407982916F, 0.6412576228F,
  159612. 0.6417167645F, 0.6421757163F, 0.6426344778F, 0.6430930483F,
  159613. 0.6435514275F, 0.6440096149F, 0.6444676098F, 0.6449254119F,
  159614. 0.6453830207F, 0.6458404356F, 0.6462976562F, 0.6467546820F,
  159615. 0.6472115125F, 0.6476681472F, 0.6481245856F, 0.6485808273F,
  159616. 0.6490368717F, 0.6494927183F, 0.6499483667F, 0.6504038164F,
  159617. 0.6508590670F, 0.6513141178F, 0.6517689684F, 0.6522236185F,
  159618. 0.6526780673F, 0.6531323146F, 0.6535863598F, 0.6540402024F,
  159619. 0.6544938419F, 0.6549472779F, 0.6554005099F, 0.6558535373F,
  159620. 0.6563063598F, 0.6567589769F, 0.6572113880F, 0.6576635927F,
  159621. 0.6581155906F, 0.6585673810F, 0.6590189637F, 0.6594703380F,
  159622. 0.6599215035F, 0.6603724598F, 0.6608232064F, 0.6612737427F,
  159623. 0.6617240684F, 0.6621741829F, 0.6626240859F, 0.6630737767F,
  159624. 0.6635232550F, 0.6639725202F, 0.6644215720F, 0.6648704098F,
  159625. 0.6653190332F, 0.6657674417F, 0.6662156348F, 0.6666636121F,
  159626. 0.6671113731F, 0.6675589174F, 0.6680062445F, 0.6684533538F,
  159627. 0.6689002450F, 0.6693469177F, 0.6697933712F, 0.6702396052F,
  159628. 0.6706856193F, 0.6711314129F, 0.6715769855F, 0.6720223369F,
  159629. 0.6724674664F, 0.6729123736F, 0.6733570581F, 0.6738015194F,
  159630. 0.6742457570F, 0.6746897706F, 0.6751335596F, 0.6755771236F,
  159631. 0.6760204621F, 0.6764635747F, 0.6769064609F, 0.6773491204F,
  159632. 0.6777915525F, 0.6782337570F, 0.6786757332F, 0.6791174809F,
  159633. 0.6795589995F, 0.6800002886F, 0.6804413477F, 0.6808821765F,
  159634. 0.6813227743F, 0.6817631409F, 0.6822032758F, 0.6826431785F,
  159635. 0.6830828485F, 0.6835222855F, 0.6839614890F, 0.6844004585F,
  159636. 0.6848391936F, 0.6852776939F, 0.6857159589F, 0.6861539883F,
  159637. 0.6865917815F, 0.6870293381F, 0.6874666576F, 0.6879037398F,
  159638. 0.6883405840F, 0.6887771899F, 0.6892135571F, 0.6896496850F,
  159639. 0.6900855733F, 0.6905212216F, 0.6909566294F, 0.6913917963F,
  159640. 0.6918267218F, 0.6922614055F, 0.6926958471F, 0.6931300459F,
  159641. 0.6935640018F, 0.6939977141F, 0.6944311825F, 0.6948644066F,
  159642. 0.6952973859F, 0.6957301200F, 0.6961626085F, 0.6965948510F,
  159643. 0.6970268470F, 0.6974585961F, 0.6978900980F, 0.6983213521F,
  159644. 0.6987523580F, 0.6991831154F, 0.6996136238F, 0.7000438828F,
  159645. 0.7004738921F, 0.7009036510F, 0.7013331594F, 0.7017624166F,
  159646. 0.7021914224F, 0.7026201763F, 0.7030486779F, 0.7034769268F,
  159647. 0.7039049226F, 0.7043326648F, 0.7047601531F, 0.7051873870F,
  159648. 0.7056143662F, 0.7060410902F, 0.7064675586F, 0.7068937711F,
  159649. 0.7073197271F, 0.7077454264F, 0.7081708684F, 0.7085960529F,
  159650. 0.7090209793F, 0.7094456474F, 0.7098700566F, 0.7102942066F,
  159651. 0.7107180970F, 0.7111417274F, 0.7115650974F, 0.7119882066F,
  159652. 0.7124110545F, 0.7128336409F, 0.7132559653F, 0.7136780272F,
  159653. 0.7140998264F, 0.7145213624F, 0.7149426348F, 0.7153636433F,
  159654. 0.7157843874F, 0.7162048668F, 0.7166250810F, 0.7170450296F,
  159655. 0.7174647124F, 0.7178841289F, 0.7183032786F, 0.7187221613F,
  159656. 0.7191407765F, 0.7195591239F, 0.7199772030F, 0.7203950135F,
  159657. 0.7208125550F, 0.7212298271F, 0.7216468294F, 0.7220635616F,
  159658. 0.7224800233F, 0.7228962140F, 0.7233121335F, 0.7237277813F,
  159659. 0.7241431571F, 0.7245582604F, 0.7249730910F, 0.7253876484F,
  159660. 0.7258019322F, 0.7262159422F, 0.7266296778F, 0.7270431388F,
  159661. 0.7274563247F, 0.7278692353F, 0.7282818700F, 0.7286942287F,
  159662. 0.7291063108F, 0.7295181160F, 0.7299296440F, 0.7303408944F,
  159663. 0.7307518669F, 0.7311625609F, 0.7315729763F, 0.7319831126F,
  159664. 0.7323929695F, 0.7328025466F, 0.7332118435F, 0.7336208600F,
  159665. 0.7340295955F, 0.7344380499F, 0.7348462226F, 0.7352541134F,
  159666. 0.7356617220F, 0.7360690478F, 0.7364760907F, 0.7368828502F,
  159667. 0.7372893259F, 0.7376955176F, 0.7381014249F, 0.7385070475F,
  159668. 0.7389123849F, 0.7393174368F, 0.7397222029F, 0.7401266829F,
  159669. 0.7405308763F, 0.7409347829F, 0.7413384023F, 0.7417417341F,
  159670. 0.7421447780F, 0.7425475338F, 0.7429500009F, 0.7433521791F,
  159671. 0.7437540681F, 0.7441556674F, 0.7445569769F, 0.7449579960F,
  159672. 0.7453587245F, 0.7457591621F, 0.7461593084F, 0.7465591631F,
  159673. 0.7469587259F, 0.7473579963F, 0.7477569741F, 0.7481556590F,
  159674. 0.7485540506F, 0.7489521486F, 0.7493499526F, 0.7497474623F,
  159675. 0.7501446775F, 0.7505415977F, 0.7509382227F, 0.7513345521F,
  159676. 0.7517305856F, 0.7521263229F, 0.7525217636F, 0.7529169074F,
  159677. 0.7533117541F, 0.7537063032F, 0.7541005545F, 0.7544945076F,
  159678. 0.7548881623F, 0.7552815182F, 0.7556745749F, 0.7560673323F,
  159679. 0.7564597899F, 0.7568519474F, 0.7572438046F, 0.7576353611F,
  159680. 0.7580266166F, 0.7584175708F, 0.7588082235F, 0.7591985741F,
  159681. 0.7595886226F, 0.7599783685F, 0.7603678116F, 0.7607569515F,
  159682. 0.7611457879F, 0.7615343206F, 0.7619225493F, 0.7623104735F,
  159683. 0.7626980931F, 0.7630854078F, 0.7634724171F, 0.7638591209F,
  159684. 0.7642455188F, 0.7646316106F, 0.7650173959F, 0.7654028744F,
  159685. 0.7657880459F, 0.7661729100F, 0.7665574664F, 0.7669417150F,
  159686. 0.7673256553F, 0.7677092871F, 0.7680926100F, 0.7684756239F,
  159687. 0.7688583284F, 0.7692407232F, 0.7696228080F, 0.7700045826F,
  159688. 0.7703860467F, 0.7707671999F, 0.7711480420F, 0.7715285728F,
  159689. 0.7719087918F, 0.7722886989F, 0.7726682938F, 0.7730475762F,
  159690. 0.7734265458F, 0.7738052023F, 0.7741835454F, 0.7745615750F,
  159691. 0.7749392906F, 0.7753166921F, 0.7756937791F, 0.7760705514F,
  159692. 0.7764470087F, 0.7768231508F, 0.7771989773F, 0.7775744880F,
  159693. 0.7779496827F, 0.7783245610F, 0.7786991227F, 0.7790733676F,
  159694. 0.7794472953F, 0.7798209056F, 0.7801941982F, 0.7805671729F,
  159695. 0.7809398294F, 0.7813121675F, 0.7816841869F, 0.7820558873F,
  159696. 0.7824272684F, 0.7827983301F, 0.7831690720F, 0.7835394940F,
  159697. 0.7839095957F, 0.7842793768F, 0.7846488373F, 0.7850179767F,
  159698. 0.7853867948F, 0.7857552914F, 0.7861234663F, 0.7864913191F,
  159699. 0.7868588497F, 0.7872260578F, 0.7875929431F, 0.7879595055F,
  159700. 0.7883257445F, 0.7886916601F, 0.7890572520F, 0.7894225198F,
  159701. 0.7897874635F, 0.7901520827F, 0.7905163772F, 0.7908803468F,
  159702. 0.7912439912F, 0.7916073102F, 0.7919703035F, 0.7923329710F,
  159703. 0.7926953124F, 0.7930573274F, 0.7934190158F, 0.7937803774F,
  159704. 0.7941414120F, 0.7945021193F, 0.7948624991F, 0.7952225511F,
  159705. 0.7955822752F, 0.7959416711F, 0.7963007387F, 0.7966594775F,
  159706. 0.7970178875F, 0.7973759685F, 0.7977337201F, 0.7980911422F,
  159707. 0.7984482346F, 0.7988049970F, 0.7991614292F, 0.7995175310F,
  159708. 0.7998733022F, 0.8002287426F, 0.8005838519F, 0.8009386299F,
  159709. 0.8012930765F, 0.8016471914F, 0.8020009744F, 0.8023544253F,
  159710. 0.8027075438F, 0.8030603298F, 0.8034127831F, 0.8037649035F,
  159711. 0.8041166906F, 0.8044681445F, 0.8048192647F, 0.8051700512F,
  159712. 0.8055205038F, 0.8058706222F, 0.8062204062F, 0.8065698556F,
  159713. 0.8069189702F, 0.8072677499F, 0.8076161944F, 0.8079643036F,
  159714. 0.8083120772F, 0.8086595151F, 0.8090066170F, 0.8093533827F,
  159715. 0.8096998122F, 0.8100459051F, 0.8103916613F, 0.8107370806F,
  159716. 0.8110821628F, 0.8114269077F, 0.8117713151F, 0.8121153849F,
  159717. 0.8124591169F, 0.8128025108F, 0.8131455666F, 0.8134882839F,
  159718. 0.8138306627F, 0.8141727027F, 0.8145144038F, 0.8148557658F,
  159719. 0.8151967886F, 0.8155374718F, 0.8158778154F, 0.8162178192F,
  159720. 0.8165574830F, 0.8168968067F, 0.8172357900F, 0.8175744328F,
  159721. 0.8179127349F, 0.8182506962F, 0.8185883164F, 0.8189255955F,
  159722. 0.8192625332F, 0.8195991295F, 0.8199353840F, 0.8202712967F,
  159723. 0.8206068673F, 0.8209420958F, 0.8212769820F, 0.8216115256F,
  159724. 0.8219457266F, 0.8222795848F, 0.8226131000F, 0.8229462721F,
  159725. 0.8232791009F, 0.8236115863F, 0.8239437280F, 0.8242755260F,
  159726. 0.8246069801F, 0.8249380901F, 0.8252688559F, 0.8255992774F,
  159727. 0.8259293544F, 0.8262590867F, 0.8265884741F, 0.8269175167F,
  159728. 0.8272462141F, 0.8275745663F, 0.8279025732F, 0.8282302344F,
  159729. 0.8285575501F, 0.8288845199F, 0.8292111437F, 0.8295374215F,
  159730. 0.8298633530F, 0.8301889382F, 0.8305141768F, 0.8308390688F,
  159731. 0.8311636141F, 0.8314878124F, 0.8318116637F, 0.8321351678F,
  159732. 0.8324583246F, 0.8327811340F, 0.8331035957F, 0.8334257098F,
  159733. 0.8337474761F, 0.8340688944F, 0.8343899647F, 0.8347106867F,
  159734. 0.8350310605F, 0.8353510857F, 0.8356707624F, 0.8359900904F,
  159735. 0.8363090696F, 0.8366276999F, 0.8369459811F, 0.8372639131F,
  159736. 0.8375814958F, 0.8378987292F, 0.8382156130F, 0.8385321472F,
  159737. 0.8388483316F, 0.8391641662F, 0.8394796508F, 0.8397947853F,
  159738. 0.8401095697F, 0.8404240037F, 0.8407380873F, 0.8410518204F,
  159739. 0.8413652029F, 0.8416782347F, 0.8419909156F, 0.8423032456F,
  159740. 0.8426152245F, 0.8429268523F, 0.8432381289F, 0.8435490541F,
  159741. 0.8438596279F, 0.8441698502F, 0.8444797208F, 0.8447892396F,
  159742. 0.8450984067F, 0.8454072218F, 0.8457156849F, 0.8460237959F,
  159743. 0.8463315547F, 0.8466389612F, 0.8469460154F, 0.8472527170F,
  159744. 0.8475590661F, 0.8478650625F, 0.8481707063F, 0.8484759971F,
  159745. 0.8487809351F, 0.8490855201F, 0.8493897521F, 0.8496936308F,
  159746. 0.8499971564F, 0.8503003286F, 0.8506031474F, 0.8509056128F,
  159747. 0.8512077246F, 0.8515094828F, 0.8518108872F, 0.8521119379F,
  159748. 0.8524126348F, 0.8527129777F, 0.8530129666F, 0.8533126015F,
  159749. 0.8536118822F, 0.8539108087F, 0.8542093809F, 0.8545075988F,
  159750. 0.8548054623F, 0.8551029712F, 0.8554001257F, 0.8556969255F,
  159751. 0.8559933707F, 0.8562894611F, 0.8565851968F, 0.8568805775F,
  159752. 0.8571756034F, 0.8574702743F, 0.8577645902F, 0.8580585509F,
  159753. 0.8583521566F, 0.8586454070F, 0.8589383021F, 0.8592308420F,
  159754. 0.8595230265F, 0.8598148556F, 0.8601063292F, 0.8603974473F,
  159755. 0.8606882098F, 0.8609786167F, 0.8612686680F, 0.8615583636F,
  159756. 0.8618477034F, 0.8621366874F, 0.8624253156F, 0.8627135878F,
  159757. 0.8630015042F, 0.8632890646F, 0.8635762690F, 0.8638631173F,
  159758. 0.8641496096F, 0.8644357457F, 0.8647215257F, 0.8650069495F,
  159759. 0.8652920171F, 0.8655767283F, 0.8658610833F, 0.8661450820F,
  159760. 0.8664287243F, 0.8667120102F, 0.8669949397F, 0.8672775127F,
  159761. 0.8675597293F, 0.8678415894F, 0.8681230929F, 0.8684042398F,
  159762. 0.8686850302F, 0.8689654640F, 0.8692455412F, 0.8695252617F,
  159763. 0.8698046255F, 0.8700836327F, 0.8703622831F, 0.8706405768F,
  159764. 0.8709185138F, 0.8711960940F, 0.8714733174F, 0.8717501840F,
  159765. 0.8720266939F, 0.8723028469F, 0.8725786430F, 0.8728540824F,
  159766. 0.8731291648F, 0.8734038905F, 0.8736782592F, 0.8739522711F,
  159767. 0.8742259261F, 0.8744992242F, 0.8747721653F, 0.8750447496F,
  159768. 0.8753169770F, 0.8755888475F, 0.8758603611F, 0.8761315177F,
  159769. 0.8764023175F, 0.8766727603F, 0.8769428462F, 0.8772125752F,
  159770. 0.8774819474F, 0.8777509626F, 0.8780196209F, 0.8782879224F,
  159771. 0.8785558669F, 0.8788234546F, 0.8790906854F, 0.8793575594F,
  159772. 0.8796240765F, 0.8798902368F, 0.8801560403F, 0.8804214870F,
  159773. 0.8806865768F, 0.8809513099F, 0.8812156863F, 0.8814797059F,
  159774. 0.8817433687F, 0.8820066749F, 0.8822696243F, 0.8825322171F,
  159775. 0.8827944532F, 0.8830563327F, 0.8833178556F, 0.8835790219F,
  159776. 0.8838398316F, 0.8841002848F, 0.8843603815F, 0.8846201217F,
  159777. 0.8848795054F, 0.8851385327F, 0.8853972036F, 0.8856555182F,
  159778. 0.8859134764F, 0.8861710783F, 0.8864283239F, 0.8866852133F,
  159779. 0.8869417464F, 0.8871979234F, 0.8874537443F, 0.8877092090F,
  159780. 0.8879643177F, 0.8882190704F, 0.8884734671F, 0.8887275078F,
  159781. 0.8889811927F, 0.8892345216F, 0.8894874948F, 0.8897401122F,
  159782. 0.8899923738F, 0.8902442798F, 0.8904958301F, 0.8907470248F,
  159783. 0.8909978640F, 0.8912483477F, 0.8914984759F, 0.8917482487F,
  159784. 0.8919976662F, 0.8922467284F, 0.8924954353F, 0.8927437871F,
  159785. 0.8929917837F, 0.8932394252F, 0.8934867118F, 0.8937336433F,
  159786. 0.8939802199F, 0.8942264417F, 0.8944723087F, 0.8947178210F,
  159787. 0.8949629785F, 0.8952077815F, 0.8954522299F, 0.8956963239F,
  159788. 0.8959400634F, 0.8961834486F, 0.8964264795F, 0.8966691561F,
  159789. 0.8969114786F, 0.8971534470F, 0.8973950614F, 0.8976363219F,
  159790. 0.8978772284F, 0.8981177812F, 0.8983579802F, 0.8985978256F,
  159791. 0.8988373174F, 0.8990764556F, 0.8993152405F, 0.8995536720F,
  159792. 0.8997917502F, 0.9000294751F, 0.9002668470F, 0.9005038658F,
  159793. 0.9007405317F, 0.9009768446F, 0.9012128048F, 0.9014484123F,
  159794. 0.9016836671F, 0.9019185693F, 0.9021531191F, 0.9023873165F,
  159795. 0.9026211616F, 0.9028546546F, 0.9030877954F, 0.9033205841F,
  159796. 0.9035530210F, 0.9037851059F, 0.9040168392F, 0.9042482207F,
  159797. 0.9044792507F, 0.9047099293F, 0.9049402564F, 0.9051702323F,
  159798. 0.9053998569F, 0.9056291305F, 0.9058580531F, 0.9060866248F,
  159799. 0.9063148457F, 0.9065427159F, 0.9067702355F, 0.9069974046F,
  159800. 0.9072242233F, 0.9074506917F, 0.9076768100F, 0.9079025782F,
  159801. 0.9081279964F, 0.9083530647F, 0.9085777833F, 0.9088021523F,
  159802. 0.9090261717F, 0.9092498417F, 0.9094731623F, 0.9096961338F,
  159803. 0.9099187561F, 0.9101410295F, 0.9103629540F, 0.9105845297F,
  159804. 0.9108057568F, 0.9110266354F, 0.9112471656F, 0.9114673475F,
  159805. 0.9116871812F, 0.9119066668F, 0.9121258046F, 0.9123445945F,
  159806. 0.9125630367F, 0.9127811314F, 0.9129988786F, 0.9132162785F,
  159807. 0.9134333312F, 0.9136500368F, 0.9138663954F, 0.9140824073F,
  159808. 0.9142980724F, 0.9145133910F, 0.9147283632F, 0.9149429890F,
  159809. 0.9151572687F, 0.9153712023F, 0.9155847900F, 0.9157980319F,
  159810. 0.9160109282F, 0.9162234790F, 0.9164356844F, 0.9166475445F,
  159811. 0.9168590595F, 0.9170702296F, 0.9172810548F, 0.9174915354F,
  159812. 0.9177016714F, 0.9179114629F, 0.9181209102F, 0.9183300134F,
  159813. 0.9185387726F, 0.9187471879F, 0.9189552595F, 0.9191629876F,
  159814. 0.9193703723F, 0.9195774136F, 0.9197841119F, 0.9199904672F,
  159815. 0.9201964797F, 0.9204021495F, 0.9206074767F, 0.9208124616F,
  159816. 0.9210171043F, 0.9212214049F, 0.9214253636F, 0.9216289805F,
  159817. 0.9218322558F, 0.9220351896F, 0.9222377821F, 0.9224400335F,
  159818. 0.9226419439F, 0.9228435134F, 0.9230447423F, 0.9232456307F,
  159819. 0.9234461787F, 0.9236463865F, 0.9238462543F, 0.9240457822F,
  159820. 0.9242449704F, 0.9244438190F, 0.9246423282F, 0.9248404983F,
  159821. 0.9250383293F, 0.9252358214F, 0.9254329747F, 0.9256297896F,
  159822. 0.9258262660F, 0.9260224042F, 0.9262182044F, 0.9264136667F,
  159823. 0.9266087913F, 0.9268035783F, 0.9269980280F, 0.9271921405F,
  159824. 0.9273859160F, 0.9275793546F, 0.9277724566F, 0.9279652221F,
  159825. 0.9281576513F, 0.9283497443F, 0.9285415014F, 0.9287329227F,
  159826. 0.9289240084F, 0.9291147586F, 0.9293051737F, 0.9294952536F,
  159827. 0.9296849987F, 0.9298744091F, 0.9300634850F, 0.9302522266F,
  159828. 0.9304406340F, 0.9306287074F, 0.9308164471F, 0.9310038532F,
  159829. 0.9311909259F, 0.9313776654F, 0.9315640719F, 0.9317501455F,
  159830. 0.9319358865F, 0.9321212951F, 0.9323063713F, 0.9324911155F,
  159831. 0.9326755279F, 0.9328596085F, 0.9330433577F, 0.9332267756F,
  159832. 0.9334098623F, 0.9335926182F, 0.9337750434F, 0.9339571380F,
  159833. 0.9341389023F, 0.9343203366F, 0.9345014409F, 0.9346822155F,
  159834. 0.9348626606F, 0.9350427763F, 0.9352225630F, 0.9354020207F,
  159835. 0.9355811498F, 0.9357599503F, 0.9359384226F, 0.9361165667F,
  159836. 0.9362943830F, 0.9364718716F, 0.9366490327F, 0.9368258666F,
  159837. 0.9370023733F, 0.9371785533F, 0.9373544066F, 0.9375299335F,
  159838. 0.9377051341F, 0.9378800087F, 0.9380545576F, 0.9382287809F,
  159839. 0.9384026787F, 0.9385762515F, 0.9387494993F, 0.9389224223F,
  159840. 0.9390950209F, 0.9392672951F, 0.9394392453F, 0.9396108716F,
  159841. 0.9397821743F, 0.9399531536F, 0.9401238096F, 0.9402941427F,
  159842. 0.9404641530F, 0.9406338407F, 0.9408032061F, 0.9409722495F,
  159843. 0.9411409709F, 0.9413093707F, 0.9414774491F, 0.9416452062F,
  159844. 0.9418126424F, 0.9419797579F, 0.9421465528F, 0.9423130274F,
  159845. 0.9424791819F, 0.9426450166F, 0.9428105317F, 0.9429757274F,
  159846. 0.9431406039F, 0.9433051616F, 0.9434694005F, 0.9436333209F,
  159847. 0.9437969232F, 0.9439602074F, 0.9441231739F, 0.9442858229F,
  159848. 0.9444481545F, 0.9446101691F, 0.9447718669F, 0.9449332481F,
  159849. 0.9450943129F, 0.9452550617F, 0.9454154945F, 0.9455756118F,
  159850. 0.9457354136F, 0.9458949003F, 0.9460540721F, 0.9462129292F,
  159851. 0.9463714719F, 0.9465297003F, 0.9466876149F, 0.9468452157F,
  159852. 0.9470025031F, 0.9471594772F, 0.9473161384F, 0.9474724869F,
  159853. 0.9476285229F, 0.9477842466F, 0.9479396584F, 0.9480947585F,
  159854. 0.9482495470F, 0.9484040243F, 0.9485581906F, 0.9487120462F,
  159855. 0.9488655913F, 0.9490188262F, 0.9491717511F, 0.9493243662F,
  159856. 0.9494766718F, 0.9496286683F, 0.9497803557F, 0.9499317345F,
  159857. 0.9500828047F, 0.9502335668F, 0.9503840209F, 0.9505341673F,
  159858. 0.9506840062F, 0.9508335380F, 0.9509827629F, 0.9511316810F,
  159859. 0.9512802928F, 0.9514285984F, 0.9515765982F, 0.9517242923F,
  159860. 0.9518716810F, 0.9520187646F, 0.9521655434F, 0.9523120176F,
  159861. 0.9524581875F, 0.9526040534F, 0.9527496154F, 0.9528948739F,
  159862. 0.9530398292F, 0.9531844814F, 0.9533288310F, 0.9534728780F,
  159863. 0.9536166229F, 0.9537600659F, 0.9539032071F, 0.9540460470F,
  159864. 0.9541885858F, 0.9543308237F, 0.9544727611F, 0.9546143981F,
  159865. 0.9547557351F, 0.9548967723F, 0.9550375100F, 0.9551779485F,
  159866. 0.9553180881F, 0.9554579290F, 0.9555974714F, 0.9557367158F,
  159867. 0.9558756623F, 0.9560143112F, 0.9561526628F, 0.9562907174F,
  159868. 0.9564284752F, 0.9565659366F, 0.9567031017F, 0.9568399710F,
  159869. 0.9569765446F, 0.9571128229F, 0.9572488061F, 0.9573844944F,
  159870. 0.9575198883F, 0.9576549879F, 0.9577897936F, 0.9579243056F,
  159871. 0.9580585242F, 0.9581924497F, 0.9583260824F, 0.9584594226F,
  159872. 0.9585924705F, 0.9587252264F, 0.9588576906F, 0.9589898634F,
  159873. 0.9591217452F, 0.9592533360F, 0.9593846364F, 0.9595156465F,
  159874. 0.9596463666F, 0.9597767971F, 0.9599069382F, 0.9600367901F,
  159875. 0.9601663533F, 0.9602956279F, 0.9604246143F, 0.9605533128F,
  159876. 0.9606817236F, 0.9608098471F, 0.9609376835F, 0.9610652332F,
  159877. 0.9611924963F, 0.9613194733F, 0.9614461644F, 0.9615725699F,
  159878. 0.9616986901F, 0.9618245253F, 0.9619500757F, 0.9620753418F,
  159879. 0.9622003238F, 0.9623250219F, 0.9624494365F, 0.9625735679F,
  159880. 0.9626974163F, 0.9628209821F, 0.9629442656F, 0.9630672671F,
  159881. 0.9631899868F, 0.9633124251F, 0.9634345822F, 0.9635564585F,
  159882. 0.9636780543F, 0.9637993699F, 0.9639204056F, 0.9640411616F,
  159883. 0.9641616383F, 0.9642818359F, 0.9644017549F, 0.9645213955F,
  159884. 0.9646407579F, 0.9647598426F, 0.9648786497F, 0.9649971797F,
  159885. 0.9651154328F, 0.9652334092F, 0.9653511095F, 0.9654685337F,
  159886. 0.9655856823F, 0.9657025556F, 0.9658191538F, 0.9659354773F,
  159887. 0.9660515263F, 0.9661673013F, 0.9662828024F, 0.9663980300F,
  159888. 0.9665129845F, 0.9666276660F, 0.9667420750F, 0.9668562118F,
  159889. 0.9669700766F, 0.9670836698F, 0.9671969917F, 0.9673100425F,
  159890. 0.9674228227F, 0.9675353325F, 0.9676475722F, 0.9677595422F,
  159891. 0.9678712428F, 0.9679826742F, 0.9680938368F, 0.9682047309F,
  159892. 0.9683153569F, 0.9684257150F, 0.9685358056F, 0.9686456289F,
  159893. 0.9687551853F, 0.9688644752F, 0.9689734987F, 0.9690822564F,
  159894. 0.9691907483F, 0.9692989750F, 0.9694069367F, 0.9695146337F,
  159895. 0.9696220663F, 0.9697292349F, 0.9698361398F, 0.9699427813F,
  159896. 0.9700491597F, 0.9701552754F, 0.9702611286F, 0.9703667197F,
  159897. 0.9704720490F, 0.9705771169F, 0.9706819236F, 0.9707864695F,
  159898. 0.9708907549F, 0.9709947802F, 0.9710985456F, 0.9712020514F,
  159899. 0.9713052981F, 0.9714082859F, 0.9715110151F, 0.9716134862F,
  159900. 0.9717156993F, 0.9718176549F, 0.9719193532F, 0.9720207946F,
  159901. 0.9721219794F, 0.9722229080F, 0.9723235806F, 0.9724239976F,
  159902. 0.9725241593F, 0.9726240661F, 0.9727237183F, 0.9728231161F,
  159903. 0.9729222601F, 0.9730211503F, 0.9731197873F, 0.9732181713F,
  159904. 0.9733163027F, 0.9734141817F, 0.9735118088F, 0.9736091842F,
  159905. 0.9737063083F, 0.9738031814F, 0.9738998039F, 0.9739961760F,
  159906. 0.9740922981F, 0.9741881706F, 0.9742837938F, 0.9743791680F,
  159907. 0.9744742935F, 0.9745691707F, 0.9746637999F, 0.9747581814F,
  159908. 0.9748523157F, 0.9749462029F, 0.9750398435F, 0.9751332378F,
  159909. 0.9752263861F, 0.9753192887F, 0.9754119461F, 0.9755043585F,
  159910. 0.9755965262F, 0.9756884496F, 0.9757801291F, 0.9758715650F,
  159911. 0.9759627575F, 0.9760537071F, 0.9761444141F, 0.9762348789F,
  159912. 0.9763251016F, 0.9764150828F, 0.9765048228F, 0.9765943218F,
  159913. 0.9766835802F, 0.9767725984F, 0.9768613767F, 0.9769499154F,
  159914. 0.9770382149F, 0.9771262755F, 0.9772140976F, 0.9773016815F,
  159915. 0.9773890275F, 0.9774761360F, 0.9775630073F, 0.9776496418F,
  159916. 0.9777360398F, 0.9778222016F, 0.9779081277F, 0.9779938182F,
  159917. 0.9780792736F, 0.9781644943F, 0.9782494805F, 0.9783342326F,
  159918. 0.9784187509F, 0.9785030359F, 0.9785870877F, 0.9786709069F,
  159919. 0.9787544936F, 0.9788378484F, 0.9789209714F, 0.9790038631F,
  159920. 0.9790865238F, 0.9791689538F, 0.9792511535F, 0.9793331232F,
  159921. 0.9794148633F, 0.9794963742F, 0.9795776561F, 0.9796587094F,
  159922. 0.9797395345F, 0.9798201316F, 0.9799005013F, 0.9799806437F,
  159923. 0.9800605593F, 0.9801402483F, 0.9802197112F, 0.9802989483F,
  159924. 0.9803779600F, 0.9804567465F, 0.9805353082F, 0.9806136455F,
  159925. 0.9806917587F, 0.9807696482F, 0.9808473143F, 0.9809247574F,
  159926. 0.9810019778F, 0.9810789759F, 0.9811557519F, 0.9812323064F,
  159927. 0.9813086395F, 0.9813847517F, 0.9814606433F, 0.9815363147F,
  159928. 0.9816117662F, 0.9816869981F, 0.9817620108F, 0.9818368047F,
  159929. 0.9819113801F, 0.9819857374F, 0.9820598769F, 0.9821337989F,
  159930. 0.9822075038F, 0.9822809920F, 0.9823542638F, 0.9824273195F,
  159931. 0.9825001596F, 0.9825727843F, 0.9826451940F, 0.9827173891F,
  159932. 0.9827893700F, 0.9828611368F, 0.9829326901F, 0.9830040302F,
  159933. 0.9830751574F, 0.9831460720F, 0.9832167745F, 0.9832872652F,
  159934. 0.9833575444F, 0.9834276124F, 0.9834974697F, 0.9835671166F,
  159935. 0.9836365535F, 0.9837057806F, 0.9837747983F, 0.9838436071F,
  159936. 0.9839122072F, 0.9839805990F, 0.9840487829F, 0.9841167591F,
  159937. 0.9841845282F, 0.9842520903F, 0.9843194459F, 0.9843865953F,
  159938. 0.9844535389F, 0.9845202771F, 0.9845868101F, 0.9846531383F,
  159939. 0.9847192622F, 0.9847851820F, 0.9848508980F, 0.9849164108F,
  159940. 0.9849817205F, 0.9850468276F, 0.9851117324F, 0.9851764352F,
  159941. 0.9852409365F, 0.9853052366F, 0.9853693358F, 0.9854332344F,
  159942. 0.9854969330F, 0.9855604317F, 0.9856237309F, 0.9856868310F,
  159943. 0.9857497325F, 0.9858124355F, 0.9858749404F, 0.9859372477F,
  159944. 0.9859993577F, 0.9860612707F, 0.9861229871F, 0.9861845072F,
  159945. 0.9862458315F, 0.9863069601F, 0.9863678936F, 0.9864286322F,
  159946. 0.9864891764F, 0.9865495264F, 0.9866096826F, 0.9866696454F,
  159947. 0.9867294152F, 0.9867889922F, 0.9868483769F, 0.9869075695F,
  159948. 0.9869665706F, 0.9870253803F, 0.9870839991F, 0.9871424273F,
  159949. 0.9872006653F, 0.9872587135F, 0.9873165721F, 0.9873742415F,
  159950. 0.9874317222F, 0.9874890144F, 0.9875461185F, 0.9876030348F,
  159951. 0.9876597638F, 0.9877163057F, 0.9877726610F, 0.9878288300F,
  159952. 0.9878848130F, 0.9879406104F, 0.9879962225F, 0.9880516497F,
  159953. 0.9881068924F, 0.9881619509F, 0.9882168256F, 0.9882715168F,
  159954. 0.9883260249F, 0.9883803502F, 0.9884344931F, 0.9884884539F,
  159955. 0.9885422331F, 0.9885958309F, 0.9886492477F, 0.9887024838F,
  159956. 0.9887555397F, 0.9888084157F, 0.9888611120F, 0.9889136292F,
  159957. 0.9889659675F, 0.9890181273F, 0.9890701089F, 0.9891219128F,
  159958. 0.9891735392F, 0.9892249885F, 0.9892762610F, 0.9893273572F,
  159959. 0.9893782774F, 0.9894290219F, 0.9894795911F, 0.9895299853F,
  159960. 0.9895802049F, 0.9896302502F, 0.9896801217F, 0.9897298196F,
  159961. 0.9897793443F, 0.9898286961F, 0.9898778755F, 0.9899268828F,
  159962. 0.9899757183F, 0.9900243823F, 0.9900728753F, 0.9901211976F,
  159963. 0.9901693495F, 0.9902173314F, 0.9902651436F, 0.9903127865F,
  159964. 0.9903602605F, 0.9904075659F, 0.9904547031F, 0.9905016723F,
  159965. 0.9905484740F, 0.9905951086F, 0.9906415763F, 0.9906878775F,
  159966. 0.9907340126F, 0.9907799819F, 0.9908257858F, 0.9908714247F,
  159967. 0.9909168988F, 0.9909622086F, 0.9910073543F, 0.9910523364F,
  159968. 0.9910971552F, 0.9911418110F, 0.9911863042F, 0.9912306351F,
  159969. 0.9912748042F, 0.9913188117F, 0.9913626580F, 0.9914063435F,
  159970. 0.9914498684F, 0.9914932333F, 0.9915364383F, 0.9915794839F,
  159971. 0.9916223703F, 0.9916650981F, 0.9917076674F, 0.9917500787F,
  159972. 0.9917923323F, 0.9918344286F, 0.9918763679F, 0.9919181505F,
  159973. 0.9919597769F, 0.9920012473F, 0.9920425621F, 0.9920837217F,
  159974. 0.9921247263F, 0.9921655765F, 0.9922062724F, 0.9922468145F,
  159975. 0.9922872030F, 0.9923274385F, 0.9923675211F, 0.9924074513F,
  159976. 0.9924472294F, 0.9924868557F, 0.9925263306F, 0.9925656544F,
  159977. 0.9926048275F, 0.9926438503F, 0.9926827230F, 0.9927214461F,
  159978. 0.9927600199F, 0.9927984446F, 0.9928367208F, 0.9928748486F,
  159979. 0.9929128285F, 0.9929506608F, 0.9929883459F, 0.9930258841F,
  159980. 0.9930632757F, 0.9931005211F, 0.9931376207F, 0.9931745747F,
  159981. 0.9932113836F, 0.9932480476F, 0.9932845671F, 0.9933209425F,
  159982. 0.9933571742F, 0.9933932623F, 0.9934292074F, 0.9934650097F,
  159983. 0.9935006696F, 0.9935361874F, 0.9935715635F, 0.9936067982F,
  159984. 0.9936418919F, 0.9936768448F, 0.9937116574F, 0.9937463300F,
  159985. 0.9937808629F, 0.9938152565F, 0.9938495111F, 0.9938836271F,
  159986. 0.9939176047F, 0.9939514444F, 0.9939851465F, 0.9940187112F,
  159987. 0.9940521391F, 0.9940854303F, 0.9941185853F, 0.9941516044F,
  159988. 0.9941844879F, 0.9942172361F, 0.9942498495F, 0.9942823283F,
  159989. 0.9943146729F, 0.9943468836F, 0.9943789608F, 0.9944109047F,
  159990. 0.9944427158F, 0.9944743944F, 0.9945059408F, 0.9945373553F,
  159991. 0.9945686384F, 0.9945997902F, 0.9946308112F, 0.9946617017F,
  159992. 0.9946924621F, 0.9947230926F, 0.9947535937F, 0.9947839656F,
  159993. 0.9948142086F, 0.9948443232F, 0.9948743097F, 0.9949041683F,
  159994. 0.9949338995F, 0.9949635035F, 0.9949929807F, 0.9950223315F,
  159995. 0.9950515561F, 0.9950806549F, 0.9951096282F, 0.9951384764F,
  159996. 0.9951671998F, 0.9951957987F, 0.9952242735F, 0.9952526245F,
  159997. 0.9952808520F, 0.9953089564F, 0.9953369380F, 0.9953647971F,
  159998. 0.9953925340F, 0.9954201491F, 0.9954476428F, 0.9954750153F,
  159999. 0.9955022670F, 0.9955293981F, 0.9955564092F, 0.9955833003F,
  160000. 0.9956100720F, 0.9956367245F, 0.9956632582F, 0.9956896733F,
  160001. 0.9957159703F, 0.9957421494F, 0.9957682110F, 0.9957941553F,
  160002. 0.9958199828F, 0.9958456937F, 0.9958712884F, 0.9958967672F,
  160003. 0.9959221305F, 0.9959473784F, 0.9959725115F, 0.9959975300F,
  160004. 0.9960224342F, 0.9960472244F, 0.9960719011F, 0.9960964644F,
  160005. 0.9961209148F, 0.9961452525F, 0.9961694779F, 0.9961935913F,
  160006. 0.9962175930F, 0.9962414834F, 0.9962652627F, 0.9962889313F,
  160007. 0.9963124895F, 0.9963359377F, 0.9963592761F, 0.9963825051F,
  160008. 0.9964056250F, 0.9964286361F, 0.9964515387F, 0.9964743332F,
  160009. 0.9964970198F, 0.9965195990F, 0.9965420709F, 0.9965644360F,
  160010. 0.9965866946F, 0.9966088469F, 0.9966308932F, 0.9966528340F,
  160011. 0.9966746695F, 0.9966964001F, 0.9967180260F, 0.9967395475F,
  160012. 0.9967609651F, 0.9967822789F, 0.9968034894F, 0.9968245968F,
  160013. 0.9968456014F, 0.9968665036F, 0.9968873037F, 0.9969080019F,
  160014. 0.9969285987F, 0.9969490942F, 0.9969694889F, 0.9969897830F,
  160015. 0.9970099769F, 0.9970300708F, 0.9970500651F, 0.9970699601F,
  160016. 0.9970897561F, 0.9971094533F, 0.9971290522F, 0.9971485531F,
  160017. 0.9971679561F, 0.9971872617F, 0.9972064702F, 0.9972255818F,
  160018. 0.9972445968F, 0.9972635157F, 0.9972823386F, 0.9973010659F,
  160019. 0.9973196980F, 0.9973382350F, 0.9973566773F, 0.9973750253F,
  160020. 0.9973932791F, 0.9974114392F, 0.9974295059F, 0.9974474793F,
  160021. 0.9974653599F, 0.9974831480F, 0.9975008438F, 0.9975184476F,
  160022. 0.9975359598F, 0.9975533806F, 0.9975707104F, 0.9975879495F,
  160023. 0.9976050981F, 0.9976221566F, 0.9976391252F, 0.9976560043F,
  160024. 0.9976727941F, 0.9976894950F, 0.9977061073F, 0.9977226312F,
  160025. 0.9977390671F, 0.9977554152F, 0.9977716759F, 0.9977878495F,
  160026. 0.9978039361F, 0.9978199363F, 0.9978358501F, 0.9978516780F,
  160027. 0.9978674202F, 0.9978830771F, 0.9978986488F, 0.9979141358F,
  160028. 0.9979295383F, 0.9979448566F, 0.9979600909F, 0.9979752417F,
  160029. 0.9979903091F, 0.9980052936F, 0.9980201952F, 0.9980350145F,
  160030. 0.9980497515F, 0.9980644067F, 0.9980789804F, 0.9980934727F,
  160031. 0.9981078841F, 0.9981222147F, 0.9981364649F, 0.9981506350F,
  160032. 0.9981647253F, 0.9981787360F, 0.9981926674F, 0.9982065199F,
  160033. 0.9982202936F, 0.9982339890F, 0.9982476062F, 0.9982611456F,
  160034. 0.9982746074F, 0.9982879920F, 0.9983012996F, 0.9983145304F,
  160035. 0.9983276849F, 0.9983407632F, 0.9983537657F, 0.9983666926F,
  160036. 0.9983795442F, 0.9983923208F, 0.9984050226F, 0.9984176501F,
  160037. 0.9984302033F, 0.9984426827F, 0.9984550884F, 0.9984674208F,
  160038. 0.9984796802F, 0.9984918667F, 0.9985039808F, 0.9985160227F,
  160039. 0.9985279926F, 0.9985398909F, 0.9985517177F, 0.9985634734F,
  160040. 0.9985751583F, 0.9985867727F, 0.9985983167F, 0.9986097907F,
  160041. 0.9986211949F, 0.9986325297F, 0.9986437953F, 0.9986549919F,
  160042. 0.9986661199F, 0.9986771795F, 0.9986881710F, 0.9986990946F,
  160043. 0.9987099507F, 0.9987207394F, 0.9987314611F, 0.9987421161F,
  160044. 0.9987527045F, 0.9987632267F, 0.9987736829F, 0.9987840734F,
  160045. 0.9987943985F, 0.9988046584F, 0.9988148534F, 0.9988249838F,
  160046. 0.9988350498F, 0.9988450516F, 0.9988549897F, 0.9988648641F,
  160047. 0.9988746753F, 0.9988844233F, 0.9988941086F, 0.9989037313F,
  160048. 0.9989132918F, 0.9989227902F, 0.9989322269F, 0.9989416021F,
  160049. 0.9989509160F, 0.9989601690F, 0.9989693613F, 0.9989784931F,
  160050. 0.9989875647F, 0.9989965763F, 0.9990055283F, 0.9990144208F,
  160051. 0.9990232541F, 0.9990320286F, 0.9990407443F, 0.9990494016F,
  160052. 0.9990580008F, 0.9990665421F, 0.9990750257F, 0.9990834519F,
  160053. 0.9990918209F, 0.9991001331F, 0.9991083886F, 0.9991165877F,
  160054. 0.9991247307F, 0.9991328177F, 0.9991408491F, 0.9991488251F,
  160055. 0.9991567460F, 0.9991646119F, 0.9991724232F, 0.9991801801F,
  160056. 0.9991878828F, 0.9991955316F, 0.9992031267F, 0.9992106684F,
  160057. 0.9992181569F, 0.9992255925F, 0.9992329753F, 0.9992403057F,
  160058. 0.9992475839F, 0.9992548101F, 0.9992619846F, 0.9992691076F,
  160059. 0.9992761793F, 0.9992832001F, 0.9992901701F, 0.9992970895F,
  160060. 0.9993039587F, 0.9993107777F, 0.9993175470F, 0.9993242667F,
  160061. 0.9993309371F, 0.9993375583F, 0.9993441307F, 0.9993506545F,
  160062. 0.9993571298F, 0.9993635570F, 0.9993699362F, 0.9993762678F,
  160063. 0.9993825519F, 0.9993887887F, 0.9993949785F, 0.9994011216F,
  160064. 0.9994072181F, 0.9994132683F, 0.9994192725F, 0.9994252307F,
  160065. 0.9994311434F, 0.9994370107F, 0.9994428327F, 0.9994486099F,
  160066. 0.9994543423F, 0.9994600303F, 0.9994656739F, 0.9994712736F,
  160067. 0.9994768294F, 0.9994823417F, 0.9994878105F, 0.9994932363F,
  160068. 0.9994986191F, 0.9995039592F, 0.9995092568F, 0.9995145122F,
  160069. 0.9995197256F, 0.9995248971F, 0.9995300270F, 0.9995351156F,
  160070. 0.9995401630F, 0.9995451695F, 0.9995501352F, 0.9995550604F,
  160071. 0.9995599454F, 0.9995647903F, 0.9995695953F, 0.9995743607F,
  160072. 0.9995790866F, 0.9995837734F, 0.9995884211F, 0.9995930300F,
  160073. 0.9995976004F, 0.9996021324F, 0.9996066263F, 0.9996110822F,
  160074. 0.9996155004F, 0.9996198810F, 0.9996242244F, 0.9996285306F,
  160075. 0.9996327999F, 0.9996370326F, 0.9996412287F, 0.9996453886F,
  160076. 0.9996495125F, 0.9996536004F, 0.9996576527F, 0.9996616696F,
  160077. 0.9996656512F, 0.9996695977F, 0.9996735094F, 0.9996773865F,
  160078. 0.9996812291F, 0.9996850374F, 0.9996888118F, 0.9996925523F,
  160079. 0.9996962591F, 0.9996999325F, 0.9997035727F, 0.9997071798F,
  160080. 0.9997107541F, 0.9997142957F, 0.9997178049F, 0.9997212818F,
  160081. 0.9997247266F, 0.9997281396F, 0.9997315209F, 0.9997348708F,
  160082. 0.9997381893F, 0.9997414767F, 0.9997447333F, 0.9997479591F,
  160083. 0.9997511544F, 0.9997543194F, 0.9997574542F, 0.9997605591F,
  160084. 0.9997636342F, 0.9997666797F, 0.9997696958F, 0.9997726828F,
  160085. 0.9997756407F, 0.9997785698F, 0.9997814703F, 0.9997843423F,
  160086. 0.9997871860F, 0.9997900016F, 0.9997927894F, 0.9997955494F,
  160087. 0.9997982818F, 0.9998009869F, 0.9998036648F, 0.9998063157F,
  160088. 0.9998089398F, 0.9998115373F, 0.9998141082F, 0.9998166529F,
  160089. 0.9998191715F, 0.9998216642F, 0.9998241311F, 0.9998265724F,
  160090. 0.9998289884F, 0.9998313790F, 0.9998337447F, 0.9998360854F,
  160091. 0.9998384015F, 0.9998406930F, 0.9998429602F, 0.9998452031F,
  160092. 0.9998474221F, 0.9998496171F, 0.9998517885F, 0.9998539364F,
  160093. 0.9998560610F, 0.9998581624F, 0.9998602407F, 0.9998622962F,
  160094. 0.9998643291F, 0.9998663394F, 0.9998683274F, 0.9998702932F,
  160095. 0.9998722370F, 0.9998741589F, 0.9998760591F, 0.9998779378F,
  160096. 0.9998797952F, 0.9998816313F, 0.9998834464F, 0.9998852406F,
  160097. 0.9998870141F, 0.9998887670F, 0.9998904995F, 0.9998922117F,
  160098. 0.9998939039F, 0.9998955761F, 0.9998972285F, 0.9998988613F,
  160099. 0.9999004746F, 0.9999020686F, 0.9999036434F, 0.9999051992F,
  160100. 0.9999067362F, 0.9999082544F, 0.9999097541F, 0.9999112354F,
  160101. 0.9999126984F, 0.9999141433F, 0.9999155703F, 0.9999169794F,
  160102. 0.9999183709F, 0.9999197449F, 0.9999211014F, 0.9999224408F,
  160103. 0.9999237631F, 0.9999250684F, 0.9999263570F, 0.9999276289F,
  160104. 0.9999288843F, 0.9999301233F, 0.9999313461F, 0.9999325529F,
  160105. 0.9999337437F, 0.9999349187F, 0.9999360780F, 0.9999372218F,
  160106. 0.9999383503F, 0.9999394635F, 0.9999405616F, 0.9999416447F,
  160107. 0.9999427129F, 0.9999437665F, 0.9999448055F, 0.9999458301F,
  160108. 0.9999468404F, 0.9999478365F, 0.9999488185F, 0.9999497867F,
  160109. 0.9999507411F, 0.9999516819F, 0.9999526091F, 0.9999535230F,
  160110. 0.9999544236F, 0.9999553111F, 0.9999561856F, 0.9999570472F,
  160111. 0.9999578960F, 0.9999587323F, 0.9999595560F, 0.9999603674F,
  160112. 0.9999611666F, 0.9999619536F, 0.9999627286F, 0.9999634917F,
  160113. 0.9999642431F, 0.9999649828F, 0.9999657110F, 0.9999664278F,
  160114. 0.9999671334F, 0.9999678278F, 0.9999685111F, 0.9999691835F,
  160115. 0.9999698451F, 0.9999704960F, 0.9999711364F, 0.9999717662F,
  160116. 0.9999723858F, 0.9999729950F, 0.9999735942F, 0.9999741834F,
  160117. 0.9999747626F, 0.9999753321F, 0.9999758919F, 0.9999764421F,
  160118. 0.9999769828F, 0.9999775143F, 0.9999780364F, 0.9999785495F,
  160119. 0.9999790535F, 0.9999795485F, 0.9999800348F, 0.9999805124F,
  160120. 0.9999809813F, 0.9999814417F, 0.9999818938F, 0.9999823375F,
  160121. 0.9999827731F, 0.9999832005F, 0.9999836200F, 0.9999840316F,
  160122. 0.9999844353F, 0.9999848314F, 0.9999852199F, 0.9999856008F,
  160123. 0.9999859744F, 0.9999863407F, 0.9999866997F, 0.9999870516F,
  160124. 0.9999873965F, 0.9999877345F, 0.9999880656F, 0.9999883900F,
  160125. 0.9999887078F, 0.9999890190F, 0.9999893237F, 0.9999896220F,
  160126. 0.9999899140F, 0.9999901999F, 0.9999904796F, 0.9999907533F,
  160127. 0.9999910211F, 0.9999912830F, 0.9999915391F, 0.9999917896F,
  160128. 0.9999920345F, 0.9999922738F, 0.9999925077F, 0.9999927363F,
  160129. 0.9999929596F, 0.9999931777F, 0.9999933907F, 0.9999935987F,
  160130. 0.9999938018F, 0.9999940000F, 0.9999941934F, 0.9999943820F,
  160131. 0.9999945661F, 0.9999947456F, 0.9999949206F, 0.9999950912F,
  160132. 0.9999952575F, 0.9999954195F, 0.9999955773F, 0.9999957311F,
  160133. 0.9999958807F, 0.9999960265F, 0.9999961683F, 0.9999963063F,
  160134. 0.9999964405F, 0.9999965710F, 0.9999966979F, 0.9999968213F,
  160135. 0.9999969412F, 0.9999970576F, 0.9999971707F, 0.9999972805F,
  160136. 0.9999973871F, 0.9999974905F, 0.9999975909F, 0.9999976881F,
  160137. 0.9999977824F, 0.9999978738F, 0.9999979624F, 0.9999980481F,
  160138. 0.9999981311F, 0.9999982115F, 0.9999982892F, 0.9999983644F,
  160139. 0.9999984370F, 0.9999985072F, 0.9999985750F, 0.9999986405F,
  160140. 0.9999987037F, 0.9999987647F, 0.9999988235F, 0.9999988802F,
  160141. 0.9999989348F, 0.9999989873F, 0.9999990379F, 0.9999990866F,
  160142. 0.9999991334F, 0.9999991784F, 0.9999992217F, 0.9999992632F,
  160143. 0.9999993030F, 0.9999993411F, 0.9999993777F, 0.9999994128F,
  160144. 0.9999994463F, 0.9999994784F, 0.9999995091F, 0.9999995384F,
  160145. 0.9999995663F, 0.9999995930F, 0.9999996184F, 0.9999996426F,
  160146. 0.9999996657F, 0.9999996876F, 0.9999997084F, 0.9999997282F,
  160147. 0.9999997469F, 0.9999997647F, 0.9999997815F, 0.9999997973F,
  160148. 0.9999998123F, 0.9999998265F, 0.9999998398F, 0.9999998524F,
  160149. 0.9999998642F, 0.9999998753F, 0.9999998857F, 0.9999998954F,
  160150. 0.9999999045F, 0.9999999130F, 0.9999999209F, 0.9999999282F,
  160151. 0.9999999351F, 0.9999999414F, 0.9999999472F, 0.9999999526F,
  160152. 0.9999999576F, 0.9999999622F, 0.9999999664F, 0.9999999702F,
  160153. 0.9999999737F, 0.9999999769F, 0.9999999798F, 0.9999999824F,
  160154. 0.9999999847F, 0.9999999868F, 0.9999999887F, 0.9999999904F,
  160155. 0.9999999919F, 0.9999999932F, 0.9999999943F, 0.9999999953F,
  160156. 0.9999999961F, 0.9999999969F, 0.9999999975F, 0.9999999980F,
  160157. 0.9999999985F, 0.9999999988F, 0.9999999991F, 0.9999999993F,
  160158. 0.9999999995F, 0.9999999997F, 0.9999999998F, 0.9999999999F,
  160159. 0.9999999999F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  160160. 1.0000000000F, 1.0000000000F, 1.0000000000F, 1.0000000000F,
  160161. };
  160162. static float *vwin[8] = {
  160163. vwin64,
  160164. vwin128,
  160165. vwin256,
  160166. vwin512,
  160167. vwin1024,
  160168. vwin2048,
  160169. vwin4096,
  160170. vwin8192,
  160171. };
  160172. float *_vorbis_window_get(int n){
  160173. return vwin[n];
  160174. }
  160175. void _vorbis_apply_window(float *d,int *winno,long *blocksizes,
  160176. int lW,int W,int nW){
  160177. lW=(W?lW:0);
  160178. nW=(W?nW:0);
  160179. {
  160180. float *windowLW=vwin[winno[lW]];
  160181. float *windowNW=vwin[winno[nW]];
  160182. long n=blocksizes[W];
  160183. long ln=blocksizes[lW];
  160184. long rn=blocksizes[nW];
  160185. long leftbegin=n/4-ln/4;
  160186. long leftend=leftbegin+ln/2;
  160187. long rightbegin=n/2+n/4-rn/4;
  160188. long rightend=rightbegin+rn/2;
  160189. int i,p;
  160190. for(i=0;i<leftbegin;i++)
  160191. d[i]=0.f;
  160192. for(p=0;i<leftend;i++,p++)
  160193. d[i]*=windowLW[p];
  160194. for(i=rightbegin,p=rn/2-1;i<rightend;i++,p--)
  160195. d[i]*=windowNW[p];
  160196. for(;i<n;i++)
  160197. d[i]=0.f;
  160198. }
  160199. }
  160200. #endif
  160201. /********* End of inlined file: window.c *********/
  160202. #else
  160203. #include <vorbis/vorbisenc.h>
  160204. #include <vorbis/codec.h>
  160205. #include <vorbis/vorbisfile.h>
  160206. #endif
  160207. }
  160208. BEGIN_JUCE_NAMESPACE
  160209. using namespace OggVorbisNamespace;
  160210. #define oggFormatName TRANS("Ogg-Vorbis file")
  160211. static const tchar* const oggExtensions[] = { T(".ogg"), 0 };
  160212. class OggReader : public AudioFormatReader
  160213. {
  160214. OggVorbis_File ovFile;
  160215. ov_callbacks callbacks;
  160216. AudioSampleBuffer reservoir;
  160217. int reservoirStart, samplesInReservoir;
  160218. public:
  160219. OggReader (InputStream* const inp)
  160220. : AudioFormatReader (inp, oggFormatName),
  160221. reservoir (2, 4096),
  160222. reservoirStart (0),
  160223. samplesInReservoir (0)
  160224. {
  160225. sampleRate = 0;
  160226. usesFloatingPointData = true;
  160227. callbacks.read_func = &oggReadCallback;
  160228. callbacks.seek_func = &oggSeekCallback;
  160229. callbacks.close_func = &oggCloseCallback;
  160230. callbacks.tell_func = &oggTellCallback;
  160231. const int err = ov_open_callbacks (input, &ovFile, 0, 0, callbacks);
  160232. if (err == 0)
  160233. {
  160234. vorbis_info* info = ov_info (&ovFile, -1);
  160235. lengthInSamples = (uint32) ov_pcm_total (&ovFile, -1);
  160236. numChannels = info->channels;
  160237. bitsPerSample = 16;
  160238. sampleRate = info->rate;
  160239. reservoir.setSize (numChannels,
  160240. (int) jmin (lengthInSamples, (int64) reservoir.getNumSamples()));
  160241. }
  160242. }
  160243. ~OggReader()
  160244. {
  160245. ov_clear (&ovFile);
  160246. }
  160247. bool read (int** destSamples,
  160248. int64 startSampleInFile,
  160249. int numSamples)
  160250. {
  160251. int startOffsetInDestBuffer = 0;
  160252. if (startSampleInFile < 0)
  160253. {
  160254. const int silence = (int) jmin (-startSampleInFile, (int64) numSamples);
  160255. int** destChan = destSamples;
  160256. for (int i = 2; --i >= 0;)
  160257. {
  160258. if (*destChan != 0)
  160259. {
  160260. zeromem (*destChan, sizeof (int) * silence);
  160261. ++destChan;
  160262. }
  160263. }
  160264. startOffsetInDestBuffer += silence;
  160265. numSamples -= silence;
  160266. }
  160267. while (numSamples > 0)
  160268. {
  160269. const int numAvailable = reservoirStart + samplesInReservoir - startSampleInFile;
  160270. if (startSampleInFile >= reservoirStart && numAvailable > 0)
  160271. {
  160272. // got a few samples overlapping, so use them before seeking..
  160273. const int numToUse = jmin (numSamples, numAvailable);
  160274. for (unsigned int i = 0; i < numChannels; ++i)
  160275. {
  160276. if (destSamples[i] == 0)
  160277. break;
  160278. memcpy (destSamples[i] + startOffsetInDestBuffer,
  160279. reservoir.getSampleData (jmin (i, reservoir.getNumChannels()),
  160280. (int) (startSampleInFile - reservoirStart)),
  160281. sizeof (float) * numToUse);
  160282. }
  160283. startSampleInFile += numToUse;
  160284. numSamples -= numToUse;
  160285. startOffsetInDestBuffer += numToUse;
  160286. if (numSamples == 0)
  160287. break;
  160288. }
  160289. if (startSampleInFile < reservoirStart
  160290. || startSampleInFile + numSamples > reservoirStart + samplesInReservoir)
  160291. {
  160292. // buffer miss, so refill the reservoir
  160293. int bitStream = 0;
  160294. reservoirStart = jmax (0, (int) startSampleInFile);
  160295. samplesInReservoir = reservoir.getNumSamples();
  160296. if (reservoirStart != (int) ov_pcm_tell (&ovFile))
  160297. ov_pcm_seek (&ovFile, reservoirStart);
  160298. int offset = 0;
  160299. int numToRead = samplesInReservoir;
  160300. while (numToRead > 0)
  160301. {
  160302. float** dataIn = 0;
  160303. const int samps = ov_read_float (&ovFile, &dataIn, numToRead, &bitStream);
  160304. if (samps == 0)
  160305. break;
  160306. jassert (samps <= numToRead);
  160307. for (int i = jmin (numChannels, reservoir.getNumChannels()); --i >= 0;)
  160308. {
  160309. memcpy (reservoir.getSampleData (i, offset),
  160310. dataIn[i],
  160311. sizeof (float) * samps);
  160312. }
  160313. numToRead -= samps;
  160314. offset += samps;
  160315. }
  160316. if (numToRead > 0)
  160317. reservoir.clear (offset, numToRead);
  160318. }
  160319. }
  160320. return true;
  160321. }
  160322. static size_t oggReadCallback (void* ptr, size_t size, size_t nmemb, void* datasource)
  160323. {
  160324. return (size_t) (((InputStream*) datasource)->read (ptr, (int) (size * nmemb)) / size);
  160325. }
  160326. static int oggSeekCallback (void* datasource, ogg_int64_t offset, int whence)
  160327. {
  160328. InputStream* const in = (InputStream*) datasource;
  160329. if (whence == SEEK_CUR)
  160330. offset += in->getPosition();
  160331. else if (whence == SEEK_END)
  160332. offset += in->getTotalLength();
  160333. in->setPosition (offset);
  160334. return 0;
  160335. }
  160336. static int oggCloseCallback (void*)
  160337. {
  160338. return 0;
  160339. }
  160340. static long oggTellCallback (void* datasource)
  160341. {
  160342. return (long) ((InputStream*) datasource)->getPosition();
  160343. }
  160344. juce_UseDebuggingNewOperator
  160345. };
  160346. class OggWriter : public AudioFormatWriter
  160347. {
  160348. ogg_stream_state os;
  160349. ogg_page og;
  160350. ogg_packet op;
  160351. vorbis_info vi;
  160352. vorbis_comment vc;
  160353. vorbis_dsp_state vd;
  160354. vorbis_block vb;
  160355. public:
  160356. bool ok;
  160357. OggWriter (OutputStream* const out,
  160358. const double sampleRate,
  160359. const int numChannels,
  160360. const int bitsPerSample,
  160361. const int qualityIndex)
  160362. : AudioFormatWriter (out, oggFormatName,
  160363. sampleRate,
  160364. numChannels,
  160365. bitsPerSample)
  160366. {
  160367. ok = false;
  160368. vorbis_info_init (&vi);
  160369. if (vorbis_encode_init_vbr (&vi,
  160370. numChannels,
  160371. (int) sampleRate,
  160372. jlimit (0.0f, 1.0f, qualityIndex * 0.5f)) == 0)
  160373. {
  160374. vorbis_comment_init (&vc);
  160375. if (JUCEApplication::getInstance() != 0)
  160376. vorbis_comment_add_tag (&vc, "ENCODER",
  160377. (char*) (const char*) JUCEApplication::getInstance()->getApplicationName());
  160378. vorbis_analysis_init (&vd, &vi);
  160379. vorbis_block_init (&vd, &vb);
  160380. ogg_stream_init (&os, Random::getSystemRandom().nextInt());
  160381. ogg_packet header;
  160382. ogg_packet header_comm;
  160383. ogg_packet header_code;
  160384. vorbis_analysis_headerout (&vd, &vc, &header, &header_comm, &header_code);
  160385. ogg_stream_packetin (&os, &header);
  160386. ogg_stream_packetin (&os, &header_comm);
  160387. ogg_stream_packetin (&os, &header_code);
  160388. for (;;)
  160389. {
  160390. if (ogg_stream_flush (&os, &og) == 0)
  160391. break;
  160392. output->write (og.header, og.header_len);
  160393. output->write (og.body, og.body_len);
  160394. }
  160395. ok = true;
  160396. }
  160397. }
  160398. ~OggWriter()
  160399. {
  160400. if (ok)
  160401. {
  160402. ogg_stream_clear (&os);
  160403. vorbis_block_clear (&vb);
  160404. vorbis_dsp_clear (&vd);
  160405. vorbis_comment_clear (&vc);
  160406. vorbis_info_clear (&vi);
  160407. output->flush();
  160408. }
  160409. else
  160410. {
  160411. vorbis_info_clear (&vi);
  160412. output = 0; // to stop the base class deleting this, as it needs to be returned
  160413. // to the caller of createWriter()
  160414. }
  160415. }
  160416. bool write (const int** samplesToWrite, int numSamples)
  160417. {
  160418. if (! ok)
  160419. return false;
  160420. if (numSamples > 0)
  160421. {
  160422. const double gain = 1.0 / 0x80000000u;
  160423. float** const vorbisBuffer = vorbis_analysis_buffer (&vd, numSamples);
  160424. for (int i = numChannels; --i >= 0;)
  160425. {
  160426. float* const dst = vorbisBuffer[i];
  160427. const int* const src = samplesToWrite [i];
  160428. if (src != 0 && dst != 0)
  160429. {
  160430. for (int j = 0; j < numSamples; ++j)
  160431. dst[j] = (float) (src[j] * gain);
  160432. }
  160433. }
  160434. }
  160435. vorbis_analysis_wrote (&vd, numSamples);
  160436. while (vorbis_analysis_blockout (&vd, &vb) == 1)
  160437. {
  160438. vorbis_analysis (&vb, 0);
  160439. vorbis_bitrate_addblock (&vb);
  160440. while (vorbis_bitrate_flushpacket (&vd, &op))
  160441. {
  160442. ogg_stream_packetin (&os, &op);
  160443. for (;;)
  160444. {
  160445. if (ogg_stream_pageout (&os, &og) == 0)
  160446. break;
  160447. output->write (og.header, og.header_len);
  160448. output->write (og.body, og.body_len);
  160449. if (ogg_page_eos (&og))
  160450. break;
  160451. }
  160452. }
  160453. }
  160454. return true;
  160455. }
  160456. juce_UseDebuggingNewOperator
  160457. };
  160458. OggVorbisAudioFormat::OggVorbisAudioFormat()
  160459. : AudioFormat (oggFormatName, (const tchar**) oggExtensions)
  160460. {
  160461. }
  160462. OggVorbisAudioFormat::~OggVorbisAudioFormat()
  160463. {
  160464. }
  160465. const Array <int> OggVorbisAudioFormat::getPossibleSampleRates()
  160466. {
  160467. const int rates[] = { 22050, 32000, 44100, 48000, 0 };
  160468. return Array <int> (rates);
  160469. }
  160470. const Array <int> OggVorbisAudioFormat::getPossibleBitDepths()
  160471. {
  160472. Array <int> depths;
  160473. depths.add (32);
  160474. return depths;
  160475. }
  160476. bool OggVorbisAudioFormat::canDoStereo()
  160477. {
  160478. return true;
  160479. }
  160480. bool OggVorbisAudioFormat::canDoMono()
  160481. {
  160482. return true;
  160483. }
  160484. AudioFormatReader* OggVorbisAudioFormat::createReaderFor (InputStream* in,
  160485. const bool deleteStreamIfOpeningFails)
  160486. {
  160487. OggReader* r = new OggReader (in);
  160488. if (r->sampleRate == 0)
  160489. {
  160490. if (! deleteStreamIfOpeningFails)
  160491. r->input = 0;
  160492. deleteAndZero (r);
  160493. }
  160494. return r;
  160495. }
  160496. AudioFormatWriter* OggVorbisAudioFormat::createWriterFor (OutputStream* out,
  160497. double sampleRate,
  160498. unsigned int numChannels,
  160499. int bitsPerSample,
  160500. const StringPairArray& /*metadataValues*/,
  160501. int qualityOptionIndex)
  160502. {
  160503. OggWriter* w = new OggWriter (out,
  160504. sampleRate,
  160505. numChannels,
  160506. bitsPerSample,
  160507. qualityOptionIndex);
  160508. if (! w->ok)
  160509. deleteAndZero (w);
  160510. return w;
  160511. }
  160512. bool OggVorbisAudioFormat::isCompressed()
  160513. {
  160514. return true;
  160515. }
  160516. const StringArray OggVorbisAudioFormat::getQualityOptions()
  160517. {
  160518. StringArray s;
  160519. s.add ("Low Quality");
  160520. s.add ("Medium Quality");
  160521. s.add ("High Quality");
  160522. return s;
  160523. }
  160524. int OggVorbisAudioFormat::estimateOggFileQuality (const File& source)
  160525. {
  160526. FileInputStream* const in = source.createInputStream();
  160527. if (in != 0)
  160528. {
  160529. AudioFormatReader* const r = createReaderFor (in, true);
  160530. if (r != 0)
  160531. {
  160532. const int64 numSamps = r->lengthInSamples;
  160533. delete r;
  160534. const int64 fileNumSamps = source.getSize() / 4;
  160535. const double ratio = numSamps / (double) fileNumSamps;
  160536. if (ratio > 12.0)
  160537. return 0;
  160538. else if (ratio > 6.0)
  160539. return 1;
  160540. else
  160541. return 2;
  160542. }
  160543. }
  160544. return 1;
  160545. }
  160546. END_JUCE_NAMESPACE
  160547. #endif
  160548. /********* End of inlined file: juce_OggVorbisAudioFormat.cpp *********/
  160549. /********* Start of inlined file: juce_JPEGLoader.cpp *********/
  160550. #if JUCE_MSVC
  160551. #pragma warning (push)
  160552. #endif
  160553. namespace jpeglibNamespace
  160554. {
  160555. #if JUCE_INCLUDE_JPEGLIB_CODE
  160556. extern "C"
  160557. {
  160558. #define JPEG_INTERNALS
  160559. #undef FAR
  160560. /********* Start of inlined file: jpeglib.h *********/
  160561. #ifndef JPEGLIB_H
  160562. #define JPEGLIB_H
  160563. /*
  160564. * First we include the configuration files that record how this
  160565. * installation of the JPEG library is set up. jconfig.h can be
  160566. * generated automatically for many systems. jmorecfg.h contains
  160567. * manual configuration options that most people need not worry about.
  160568. */
  160569. #ifndef JCONFIG_INCLUDED /* in case jinclude.h already did */
  160570. /********* Start of inlined file: jconfig.h *********/
  160571. /* see jconfig.doc for explanations */
  160572. // disable all the warnings under MSVC
  160573. #ifdef _MSC_VER
  160574. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  160575. #endif
  160576. #ifdef __BORLANDC__
  160577. #pragma warn -8057
  160578. #pragma warn -8019
  160579. #pragma warn -8004
  160580. #pragma warn -8008
  160581. #endif
  160582. #define HAVE_PROTOTYPES
  160583. #define HAVE_UNSIGNED_CHAR
  160584. #define HAVE_UNSIGNED_SHORT
  160585. /* #define void char */
  160586. /* #define const */
  160587. #undef CHAR_IS_UNSIGNED
  160588. #define HAVE_STDDEF_H
  160589. #define HAVE_STDLIB_H
  160590. #undef NEED_BSD_STRINGS
  160591. #undef NEED_SYS_TYPES_H
  160592. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  160593. #undef NEED_SHORT_EXTERNAL_NAMES
  160594. #undef INCOMPLETE_TYPES_BROKEN
  160595. /* Define "boolean" as unsigned char, not int, per Windows custom */
  160596. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  160597. typedef unsigned char boolean;
  160598. #endif
  160599. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  160600. #ifdef JPEG_INTERNALS
  160601. #undef RIGHT_SHIFT_IS_UNSIGNED
  160602. #endif /* JPEG_INTERNALS */
  160603. #ifdef JPEG_CJPEG_DJPEG
  160604. #define BMP_SUPPORTED /* BMP image file format */
  160605. #define GIF_SUPPORTED /* GIF image file format */
  160606. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  160607. #undef RLE_SUPPORTED /* Utah RLE image file format */
  160608. #define TARGA_SUPPORTED /* Targa image file format */
  160609. #define TWO_FILE_COMMANDLINE /* optional */
  160610. #define USE_SETMODE /* Microsoft has setmode() */
  160611. #undef NEED_SIGNAL_CATCHER
  160612. #undef DONT_USE_B_MODE
  160613. #undef PROGRESS_REPORT /* optional */
  160614. #endif /* JPEG_CJPEG_DJPEG */
  160615. /********* End of inlined file: jconfig.h *********/
  160616. /* widely used configuration options */
  160617. #endif
  160618. /********* Start of inlined file: jmorecfg.h *********/
  160619. /*
  160620. * Define BITS_IN_JSAMPLE as either
  160621. * 8 for 8-bit sample values (the usual setting)
  160622. * 12 for 12-bit sample values
  160623. * Only 8 and 12 are legal data precisions for lossy JPEG according to the
  160624. * JPEG standard, and the IJG code does not support anything else!
  160625. * We do not support run-time selection of data precision, sorry.
  160626. */
  160627. #define BITS_IN_JSAMPLE 8 /* use 8 or 12 */
  160628. /*
  160629. * Maximum number of components (color channels) allowed in JPEG image.
  160630. * To meet the letter of the JPEG spec, set this to 255. However, darn
  160631. * few applications need more than 4 channels (maybe 5 for CMYK + alpha
  160632. * mask). We recommend 10 as a reasonable compromise; use 4 if you are
  160633. * really short on memory. (Each allowed component costs a hundred or so
  160634. * bytes of storage, whether actually used in an image or not.)
  160635. */
  160636. #define MAX_COMPONENTS 10 /* maximum number of image components */
  160637. /*
  160638. * Basic data types.
  160639. * You may need to change these if you have a machine with unusual data
  160640. * type sizes; for example, "char" not 8 bits, "short" not 16 bits,
  160641. * or "long" not 32 bits. We don't care whether "int" is 16 or 32 bits,
  160642. * but it had better be at least 16.
  160643. */
  160644. /* Representation of a single sample (pixel element value).
  160645. * We frequently allocate large arrays of these, so it's important to keep
  160646. * them small. But if you have memory to burn and access to char or short
  160647. * arrays is very slow on your hardware, you might want to change these.
  160648. */
  160649. #if BITS_IN_JSAMPLE == 8
  160650. /* JSAMPLE should be the smallest type that will hold the values 0..255.
  160651. * You can use a signed char by having GETJSAMPLE mask it with 0xFF.
  160652. */
  160653. #ifdef HAVE_UNSIGNED_CHAR
  160654. typedef unsigned char JSAMPLE;
  160655. #define GETJSAMPLE(value) ((int) (value))
  160656. #else /* not HAVE_UNSIGNED_CHAR */
  160657. typedef char JSAMPLE;
  160658. #ifdef CHAR_IS_UNSIGNED
  160659. #define GETJSAMPLE(value) ((int) (value))
  160660. #else
  160661. #define GETJSAMPLE(value) ((int) (value) & 0xFF)
  160662. #endif /* CHAR_IS_UNSIGNED */
  160663. #endif /* HAVE_UNSIGNED_CHAR */
  160664. #define MAXJSAMPLE 255
  160665. #define CENTERJSAMPLE 128
  160666. #endif /* BITS_IN_JSAMPLE == 8 */
  160667. #if BITS_IN_JSAMPLE == 12
  160668. /* JSAMPLE should be the smallest type that will hold the values 0..4095.
  160669. * On nearly all machines "short" will do nicely.
  160670. */
  160671. typedef short JSAMPLE;
  160672. #define GETJSAMPLE(value) ((int) (value))
  160673. #define MAXJSAMPLE 4095
  160674. #define CENTERJSAMPLE 2048
  160675. #endif /* BITS_IN_JSAMPLE == 12 */
  160676. /* Representation of a DCT frequency coefficient.
  160677. * This should be a signed value of at least 16 bits; "short" is usually OK.
  160678. * Again, we allocate large arrays of these, but you can change to int
  160679. * if you have memory to burn and "short" is really slow.
  160680. */
  160681. typedef short JCOEF;
  160682. /* Compressed datastreams are represented as arrays of JOCTET.
  160683. * These must be EXACTLY 8 bits wide, at least once they are written to
  160684. * external storage. Note that when using the stdio data source/destination
  160685. * managers, this is also the data type passed to fread/fwrite.
  160686. */
  160687. #ifdef HAVE_UNSIGNED_CHAR
  160688. typedef unsigned char JOCTET;
  160689. #define GETJOCTET(value) (value)
  160690. #else /* not HAVE_UNSIGNED_CHAR */
  160691. typedef char JOCTET;
  160692. #ifdef CHAR_IS_UNSIGNED
  160693. #define GETJOCTET(value) (value)
  160694. #else
  160695. #define GETJOCTET(value) ((value) & 0xFF)
  160696. #endif /* CHAR_IS_UNSIGNED */
  160697. #endif /* HAVE_UNSIGNED_CHAR */
  160698. /* These typedefs are used for various table entries and so forth.
  160699. * They must be at least as wide as specified; but making them too big
  160700. * won't cost a huge amount of memory, so we don't provide special
  160701. * extraction code like we did for JSAMPLE. (In other words, these
  160702. * typedefs live at a different point on the speed/space tradeoff curve.)
  160703. */
  160704. /* UINT8 must hold at least the values 0..255. */
  160705. #ifdef HAVE_UNSIGNED_CHAR
  160706. typedef unsigned char UINT8;
  160707. #else /* not HAVE_UNSIGNED_CHAR */
  160708. #ifdef CHAR_IS_UNSIGNED
  160709. typedef char UINT8;
  160710. #else /* not CHAR_IS_UNSIGNED */
  160711. typedef short UINT8;
  160712. #endif /* CHAR_IS_UNSIGNED */
  160713. #endif /* HAVE_UNSIGNED_CHAR */
  160714. /* UINT16 must hold at least the values 0..65535. */
  160715. #ifdef HAVE_UNSIGNED_SHORT
  160716. typedef unsigned short UINT16;
  160717. #else /* not HAVE_UNSIGNED_SHORT */
  160718. typedef unsigned int UINT16;
  160719. #endif /* HAVE_UNSIGNED_SHORT */
  160720. /* INT16 must hold at least the values -32768..32767. */
  160721. #ifndef XMD_H /* X11/xmd.h correctly defines INT16 */
  160722. typedef short INT16;
  160723. #endif
  160724. /* INT32 must hold at least signed 32-bit values. */
  160725. #ifndef XMD_H /* X11/xmd.h correctly defines INT32 */
  160726. typedef long INT32;
  160727. #endif
  160728. /* Datatype used for image dimensions. The JPEG standard only supports
  160729. * images up to 64K*64K due to 16-bit fields in SOF markers. Therefore
  160730. * "unsigned int" is sufficient on all machines. However, if you need to
  160731. * handle larger images and you don't mind deviating from the spec, you
  160732. * can change this datatype.
  160733. */
  160734. typedef unsigned int JDIMENSION;
  160735. #define JPEG_MAX_DIMENSION 65500L /* a tad under 64K to prevent overflows */
  160736. /* These macros are used in all function definitions and extern declarations.
  160737. * You could modify them if you need to change function linkage conventions;
  160738. * in particular, you'll need to do that to make the library a Windows DLL.
  160739. * Another application is to make all functions global for use with debuggers
  160740. * or code profilers that require it.
  160741. */
  160742. /* a function called through method pointers: */
  160743. #define METHODDEF(type) static type
  160744. /* a function used only in its module: */
  160745. #define LOCAL(type) static type
  160746. /* a function referenced thru EXTERNs: */
  160747. #define GLOBAL(type) type
  160748. /* a reference to a GLOBAL function: */
  160749. #define EXTERN(type) extern type
  160750. /* This macro is used to declare a "method", that is, a function pointer.
  160751. * We want to supply prototype parameters if the compiler can cope.
  160752. * Note that the arglist parameter must be parenthesized!
  160753. * Again, you can customize this if you need special linkage keywords.
  160754. */
  160755. #ifdef HAVE_PROTOTYPES
  160756. #define JMETHOD(type,methodname,arglist) type (*methodname) arglist
  160757. #else
  160758. #define JMETHOD(type,methodname,arglist) type (*methodname) ()
  160759. #endif
  160760. /* Here is the pseudo-keyword for declaring pointers that must be "far"
  160761. * on 80x86 machines. Most of the specialized coding for 80x86 is handled
  160762. * by just saying "FAR *" where such a pointer is needed. In a few places
  160763. * explicit coding is needed; see uses of the NEED_FAR_POINTERS symbol.
  160764. */
  160765. #ifdef NEED_FAR_POINTERS
  160766. #define FAR far
  160767. #else
  160768. #define FAR
  160769. #endif
  160770. /*
  160771. * On a few systems, type boolean and/or its values FALSE, TRUE may appear
  160772. * in standard header files. Or you may have conflicts with application-
  160773. * specific header files that you want to include together with these files.
  160774. * Defining HAVE_BOOLEAN before including jpeglib.h should make it work.
  160775. */
  160776. #ifndef HAVE_BOOLEAN
  160777. typedef int boolean;
  160778. #endif
  160779. #ifndef FALSE /* in case these macros already exist */
  160780. #define FALSE 0 /* values of boolean */
  160781. #endif
  160782. #ifndef TRUE
  160783. #define TRUE 1
  160784. #endif
  160785. /*
  160786. * The remaining options affect code selection within the JPEG library,
  160787. * but they don't need to be visible to most applications using the library.
  160788. * To minimize application namespace pollution, the symbols won't be
  160789. * defined unless JPEG_INTERNALS or JPEG_INTERNAL_OPTIONS has been defined.
  160790. */
  160791. #ifdef JPEG_INTERNALS
  160792. #define JPEG_INTERNAL_OPTIONS
  160793. #endif
  160794. #ifdef JPEG_INTERNAL_OPTIONS
  160795. /*
  160796. * These defines indicate whether to include various optional functions.
  160797. * Undefining some of these symbols will produce a smaller but less capable
  160798. * library. Note that you can leave certain source files out of the
  160799. * compilation/linking process if you've #undef'd the corresponding symbols.
  160800. * (You may HAVE to do that if your compiler doesn't like null source files.)
  160801. */
  160802. /* Arithmetic coding is unsupported for legal reasons. Complaints to IBM. */
  160803. /* Capability options common to encoder and decoder: */
  160804. #define DCT_ISLOW_SUPPORTED /* slow but accurate integer algorithm */
  160805. #define DCT_IFAST_SUPPORTED /* faster, less accurate integer method */
  160806. #define DCT_FLOAT_SUPPORTED /* floating-point: accurate, fast on fast HW */
  160807. /* Encoder capability options: */
  160808. #undef C_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160809. #define C_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160810. #define C_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160811. #define ENTROPY_OPT_SUPPORTED /* Optimization of entropy coding parms? */
  160812. /* Note: if you selected 12-bit data precision, it is dangerous to turn off
  160813. * ENTROPY_OPT_SUPPORTED. The standard Huffman tables are only good for 8-bit
  160814. * precision, so jchuff.c normally uses entropy optimization to compute
  160815. * usable tables for higher precision. If you don't want to do optimization,
  160816. * you'll have to supply different default Huffman tables.
  160817. * The exact same statements apply for progressive JPEG: the default tables
  160818. * don't work for progressive mode. (This may get fixed, however.)
  160819. */
  160820. #define INPUT_SMOOTHING_SUPPORTED /* Input image smoothing option? */
  160821. /* Decoder capability options: */
  160822. #undef D_ARITH_CODING_SUPPORTED /* Arithmetic coding back end? */
  160823. #define D_MULTISCAN_FILES_SUPPORTED /* Multiple-scan JPEG files? */
  160824. #define D_PROGRESSIVE_SUPPORTED /* Progressive JPEG? (Requires MULTISCAN)*/
  160825. #define SAVE_MARKERS_SUPPORTED /* jpeg_save_markers() needed? */
  160826. #define BLOCK_SMOOTHING_SUPPORTED /* Block smoothing? (Progressive only) */
  160827. #define IDCT_SCALING_SUPPORTED /* Output rescaling via IDCT? */
  160828. #undef UPSAMPLE_SCALING_SUPPORTED /* Output rescaling at upsample stage? */
  160829. #define UPSAMPLE_MERGING_SUPPORTED /* Fast path for sloppy upsampling? */
  160830. #define QUANT_1PASS_SUPPORTED /* 1-pass color quantization? */
  160831. #define QUANT_2PASS_SUPPORTED /* 2-pass color quantization? */
  160832. /* more capability options later, no doubt */
  160833. /*
  160834. * Ordering of RGB data in scanlines passed to or from the application.
  160835. * If your application wants to deal with data in the order B,G,R, just
  160836. * change these macros. You can also deal with formats such as R,G,B,X
  160837. * (one extra byte per pixel) by changing RGB_PIXELSIZE. Note that changing
  160838. * the offsets will also change the order in which colormap data is organized.
  160839. * RESTRICTIONS:
  160840. * 1. The sample applications cjpeg,djpeg do NOT support modified RGB formats.
  160841. * 2. These macros only affect RGB<=>YCbCr color conversion, so they are not
  160842. * useful if you are using JPEG color spaces other than YCbCr or grayscale.
  160843. * 3. The color quantizer modules will not behave desirably if RGB_PIXELSIZE
  160844. * is not 3 (they don't understand about dummy color components!). So you
  160845. * can't use color quantization if you change that value.
  160846. */
  160847. #define RGB_RED 0 /* Offset of Red in an RGB scanline element */
  160848. #define RGB_GREEN 1 /* Offset of Green */
  160849. #define RGB_BLUE 2 /* Offset of Blue */
  160850. #define RGB_PIXELSIZE 3 /* JSAMPLEs per RGB scanline element */
  160851. /* Definitions for speed-related optimizations. */
  160852. /* If your compiler supports inline functions, define INLINE
  160853. * as the inline keyword; otherwise define it as empty.
  160854. */
  160855. #ifndef INLINE
  160856. #ifdef __GNUC__ /* for instance, GNU C knows about inline */
  160857. #define INLINE __inline__
  160858. #endif
  160859. #ifndef INLINE
  160860. #define INLINE /* default is to define it as empty */
  160861. #endif
  160862. #endif
  160863. /* On some machines (notably 68000 series) "int" is 32 bits, but multiplying
  160864. * two 16-bit shorts is faster than multiplying two ints. Define MULTIPLIER
  160865. * as short on such a machine. MULTIPLIER must be at least 16 bits wide.
  160866. */
  160867. #ifndef MULTIPLIER
  160868. #define MULTIPLIER int /* type for fastest integer multiply */
  160869. #endif
  160870. /* FAST_FLOAT should be either float or double, whichever is done faster
  160871. * by your compiler. (Note that this type is only used in the floating point
  160872. * DCT routines, so it only matters if you've defined DCT_FLOAT_SUPPORTED.)
  160873. * Typically, float is faster in ANSI C compilers, while double is faster in
  160874. * pre-ANSI compilers (because they insist on converting to double anyway).
  160875. * The code below therefore chooses float if we have ANSI-style prototypes.
  160876. */
  160877. #ifndef FAST_FLOAT
  160878. #ifdef HAVE_PROTOTYPES
  160879. #define FAST_FLOAT float
  160880. #else
  160881. #define FAST_FLOAT double
  160882. #endif
  160883. #endif
  160884. #endif /* JPEG_INTERNAL_OPTIONS */
  160885. /********* End of inlined file: jmorecfg.h *********/
  160886. /* seldom changed options */
  160887. /* Version ID for the JPEG library.
  160888. * Might be useful for tests like "#if JPEG_LIB_VERSION >= 60".
  160889. */
  160890. #define JPEG_LIB_VERSION 62 /* Version 6b */
  160891. /* Various constants determining the sizes of things.
  160892. * All of these are specified by the JPEG standard, so don't change them
  160893. * if you want to be compatible.
  160894. */
  160895. #define DCTSIZE 8 /* The basic DCT block is 8x8 samples */
  160896. #define DCTSIZE2 64 /* DCTSIZE squared; # of elements in a block */
  160897. #define NUM_QUANT_TBLS 4 /* Quantization tables are numbered 0..3 */
  160898. #define NUM_HUFF_TBLS 4 /* Huffman tables are numbered 0..3 */
  160899. #define NUM_ARITH_TBLS 16 /* Arith-coding tables are numbered 0..15 */
  160900. #define MAX_COMPS_IN_SCAN 4 /* JPEG limit on # of components in one scan */
  160901. #define MAX_SAMP_FACTOR 4 /* JPEG limit on sampling factors */
  160902. /* Unfortunately, some bozo at Adobe saw no reason to be bound by the standard;
  160903. * the PostScript DCT filter can emit files with many more than 10 blocks/MCU.
  160904. * If you happen to run across such a file, you can up D_MAX_BLOCKS_IN_MCU
  160905. * to handle it. We even let you do this from the jconfig.h file. However,
  160906. * we strongly discourage changing C_MAX_BLOCKS_IN_MCU; just because Adobe
  160907. * sometimes emits noncompliant files doesn't mean you should too.
  160908. */
  160909. #define C_MAX_BLOCKS_IN_MCU 10 /* compressor's limit on blocks per MCU */
  160910. #ifndef D_MAX_BLOCKS_IN_MCU
  160911. #define D_MAX_BLOCKS_IN_MCU 10 /* decompressor's limit on blocks per MCU */
  160912. #endif
  160913. /* Data structures for images (arrays of samples and of DCT coefficients).
  160914. * On 80x86 machines, the image arrays are too big for near pointers,
  160915. * but the pointer arrays can fit in near memory.
  160916. */
  160917. typedef JSAMPLE FAR *JSAMPROW; /* ptr to one image row of pixel samples. */
  160918. typedef JSAMPROW *JSAMPARRAY; /* ptr to some rows (a 2-D sample array) */
  160919. typedef JSAMPARRAY *JSAMPIMAGE; /* a 3-D sample array: top index is color */
  160920. typedef JCOEF JBLOCK[DCTSIZE2]; /* one block of coefficients */
  160921. typedef JBLOCK FAR *JBLOCKROW; /* pointer to one row of coefficient blocks */
  160922. typedef JBLOCKROW *JBLOCKARRAY; /* a 2-D array of coefficient blocks */
  160923. typedef JBLOCKARRAY *JBLOCKIMAGE; /* a 3-D array of coefficient blocks */
  160924. typedef JCOEF FAR *JCOEFPTR; /* useful in a couple of places */
  160925. /* Types for JPEG compression parameters and working tables. */
  160926. /* DCT coefficient quantization tables. */
  160927. typedef struct {
  160928. /* This array gives the coefficient quantizers in natural array order
  160929. * (not the zigzag order in which they are stored in a JPEG DQT marker).
  160930. * CAUTION: IJG versions prior to v6a kept this array in zigzag order.
  160931. */
  160932. UINT16 quantval[DCTSIZE2]; /* quantization step for each coefficient */
  160933. /* This field is used only during compression. It's initialized FALSE when
  160934. * the table is created, and set TRUE when it's been output to the file.
  160935. * You could suppress output of a table by setting this to TRUE.
  160936. * (See jpeg_suppress_tables for an example.)
  160937. */
  160938. boolean sent_table; /* TRUE when table has been output */
  160939. } JQUANT_TBL;
  160940. /* Huffman coding tables. */
  160941. typedef struct {
  160942. /* These two fields directly represent the contents of a JPEG DHT marker */
  160943. UINT8 bits[17]; /* bits[k] = # of symbols with codes of */
  160944. /* length k bits; bits[0] is unused */
  160945. UINT8 huffval[256]; /* The symbols, in order of incr code length */
  160946. /* This field is used only during compression. It's initialized FALSE when
  160947. * the table is created, and set TRUE when it's been output to the file.
  160948. * You could suppress output of a table by setting this to TRUE.
  160949. * (See jpeg_suppress_tables for an example.)
  160950. */
  160951. boolean sent_table; /* TRUE when table has been output */
  160952. } JHUFF_TBL;
  160953. /* Basic info about one component (color channel). */
  160954. typedef struct {
  160955. /* These values are fixed over the whole image. */
  160956. /* For compression, they must be supplied by parameter setup; */
  160957. /* for decompression, they are read from the SOF marker. */
  160958. int component_id; /* identifier for this component (0..255) */
  160959. int component_index; /* its index in SOF or cinfo->comp_info[] */
  160960. int h_samp_factor; /* horizontal sampling factor (1..4) */
  160961. int v_samp_factor; /* vertical sampling factor (1..4) */
  160962. int quant_tbl_no; /* quantization table selector (0..3) */
  160963. /* These values may vary between scans. */
  160964. /* For compression, they must be supplied by parameter setup; */
  160965. /* for decompression, they are read from the SOS marker. */
  160966. /* The decompressor output side may not use these variables. */
  160967. int dc_tbl_no; /* DC entropy table selector (0..3) */
  160968. int ac_tbl_no; /* AC entropy table selector (0..3) */
  160969. /* Remaining fields should be treated as private by applications. */
  160970. /* These values are computed during compression or decompression startup: */
  160971. /* Component's size in DCT blocks.
  160972. * Any dummy blocks added to complete an MCU are not counted; therefore
  160973. * these values do not depend on whether a scan is interleaved or not.
  160974. */
  160975. JDIMENSION width_in_blocks;
  160976. JDIMENSION height_in_blocks;
  160977. /* Size of a DCT block in samples. Always DCTSIZE for compression.
  160978. * For decompression this is the size of the output from one DCT block,
  160979. * reflecting any scaling we choose to apply during the IDCT step.
  160980. * Values of 1,2,4,8 are likely to be supported. Note that different
  160981. * components may receive different IDCT scalings.
  160982. */
  160983. int DCT_scaled_size;
  160984. /* The downsampled dimensions are the component's actual, unpadded number
  160985. * of samples at the main buffer (preprocessing/compression interface), thus
  160986. * downsampled_width = ceil(image_width * Hi/Hmax)
  160987. * and similarly for height. For decompression, IDCT scaling is included, so
  160988. * downsampled_width = ceil(image_width * Hi/Hmax * DCT_scaled_size/DCTSIZE)
  160989. */
  160990. JDIMENSION downsampled_width; /* actual width in samples */
  160991. JDIMENSION downsampled_height; /* actual height in samples */
  160992. /* This flag is used only for decompression. In cases where some of the
  160993. * components will be ignored (eg grayscale output from YCbCr image),
  160994. * we can skip most computations for the unused components.
  160995. */
  160996. boolean component_needed; /* do we need the value of this component? */
  160997. /* These values are computed before starting a scan of the component. */
  160998. /* The decompressor output side may not use these variables. */
  160999. int MCU_width; /* number of blocks per MCU, horizontally */
  161000. int MCU_height; /* number of blocks per MCU, vertically */
  161001. int MCU_blocks; /* MCU_width * MCU_height */
  161002. int MCU_sample_width; /* MCU width in samples, MCU_width*DCT_scaled_size */
  161003. int last_col_width; /* # of non-dummy blocks across in last MCU */
  161004. int last_row_height; /* # of non-dummy blocks down in last MCU */
  161005. /* Saved quantization table for component; NULL if none yet saved.
  161006. * See jdinput.c comments about the need for this information.
  161007. * This field is currently used only for decompression.
  161008. */
  161009. JQUANT_TBL * quant_table;
  161010. /* Private per-component storage for DCT or IDCT subsystem. */
  161011. void * dct_table;
  161012. } jpeg_component_info;
  161013. /* The script for encoding a multiple-scan file is an array of these: */
  161014. typedef struct {
  161015. int comps_in_scan; /* number of components encoded in this scan */
  161016. int component_index[MAX_COMPS_IN_SCAN]; /* their SOF/comp_info[] indexes */
  161017. int Ss, Se; /* progressive JPEG spectral selection parms */
  161018. int Ah, Al; /* progressive JPEG successive approx. parms */
  161019. } jpeg_scan_info;
  161020. /* The decompressor can save APPn and COM markers in a list of these: */
  161021. typedef struct jpeg_marker_struct FAR * jpeg_saved_marker_ptr;
  161022. struct jpeg_marker_struct {
  161023. jpeg_saved_marker_ptr next; /* next in list, or NULL */
  161024. UINT8 marker; /* marker code: JPEG_COM, or JPEG_APP0+n */
  161025. unsigned int original_length; /* # bytes of data in the file */
  161026. unsigned int data_length; /* # bytes of data saved at data[] */
  161027. JOCTET FAR * data; /* the data contained in the marker */
  161028. /* the marker length word is not counted in data_length or original_length */
  161029. };
  161030. /* Known color spaces. */
  161031. typedef enum {
  161032. JCS_UNKNOWN, /* error/unspecified */
  161033. JCS_GRAYSCALE, /* monochrome */
  161034. JCS_RGB, /* red/green/blue */
  161035. JCS_YCbCr, /* Y/Cb/Cr (also known as YUV) */
  161036. JCS_CMYK, /* C/M/Y/K */
  161037. JCS_YCCK /* Y/Cb/Cr/K */
  161038. } J_COLOR_SPACE;
  161039. /* DCT/IDCT algorithm options. */
  161040. typedef enum {
  161041. JDCT_ISLOW, /* slow but accurate integer algorithm */
  161042. JDCT_IFAST, /* faster, less accurate integer method */
  161043. JDCT_FLOAT /* floating-point: accurate, fast on fast HW */
  161044. } J_DCT_METHOD;
  161045. #ifndef JDCT_DEFAULT /* may be overridden in jconfig.h */
  161046. #define JDCT_DEFAULT JDCT_ISLOW
  161047. #endif
  161048. #ifndef JDCT_FASTEST /* may be overridden in jconfig.h */
  161049. #define JDCT_FASTEST JDCT_IFAST
  161050. #endif
  161051. /* Dithering options for decompression. */
  161052. typedef enum {
  161053. JDITHER_NONE, /* no dithering */
  161054. JDITHER_ORDERED, /* simple ordered dither */
  161055. JDITHER_FS /* Floyd-Steinberg error diffusion dither */
  161056. } J_DITHER_MODE;
  161057. /* Common fields between JPEG compression and decompression master structs. */
  161058. #define jpeg_common_fields \
  161059. struct jpeg_error_mgr * err; /* Error handler module */\
  161060. struct jpeg_memory_mgr * mem; /* Memory manager module */\
  161061. struct jpeg_progress_mgr * progress; /* Progress monitor, or NULL if none */\
  161062. void * client_data; /* Available for use by application */\
  161063. boolean is_decompressor; /* So common code can tell which is which */\
  161064. int global_state /* For checking call sequence validity */
  161065. /* Routines that are to be used by both halves of the library are declared
  161066. * to receive a pointer to this structure. There are no actual instances of
  161067. * jpeg_common_struct, only of jpeg_compress_struct and jpeg_decompress_struct.
  161068. */
  161069. struct jpeg_common_struct {
  161070. jpeg_common_fields; /* Fields common to both master struct types */
  161071. /* Additional fields follow in an actual jpeg_compress_struct or
  161072. * jpeg_decompress_struct. All three structs must agree on these
  161073. * initial fields! (This would be a lot cleaner in C++.)
  161074. */
  161075. };
  161076. typedef struct jpeg_common_struct * j_common_ptr;
  161077. typedef struct jpeg_compress_struct * j_compress_ptr;
  161078. typedef struct jpeg_decompress_struct * j_decompress_ptr;
  161079. /* Master record for a compression instance */
  161080. struct jpeg_compress_struct {
  161081. jpeg_common_fields; /* Fields shared with jpeg_decompress_struct */
  161082. /* Destination for compressed data */
  161083. struct jpeg_destination_mgr * dest;
  161084. /* Description of source image --- these fields must be filled in by
  161085. * outer application before starting compression. in_color_space must
  161086. * be correct before you can even call jpeg_set_defaults().
  161087. */
  161088. JDIMENSION image_width; /* input image width */
  161089. JDIMENSION image_height; /* input image height */
  161090. int input_components; /* # of color components in input image */
  161091. J_COLOR_SPACE in_color_space; /* colorspace of input image */
  161092. double input_gamma; /* image gamma of input image */
  161093. /* Compression parameters --- these fields must be set before calling
  161094. * jpeg_start_compress(). We recommend calling jpeg_set_defaults() to
  161095. * initialize everything to reasonable defaults, then changing anything
  161096. * the application specifically wants to change. That way you won't get
  161097. * burnt when new parameters are added. Also note that there are several
  161098. * helper routines to simplify changing parameters.
  161099. */
  161100. int data_precision; /* bits of precision in image data */
  161101. int num_components; /* # of color components in JPEG image */
  161102. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  161103. jpeg_component_info * comp_info;
  161104. /* comp_info[i] describes component that appears i'th in SOF */
  161105. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  161106. /* ptrs to coefficient quantization tables, or NULL if not defined */
  161107. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  161108. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  161109. /* ptrs to Huffman coding tables, or NULL if not defined */
  161110. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  161111. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  161112. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  161113. int num_scans; /* # of entries in scan_info array */
  161114. const jpeg_scan_info * scan_info; /* script for multi-scan file, or NULL */
  161115. /* The default value of scan_info is NULL, which causes a single-scan
  161116. * sequential JPEG file to be emitted. To create a multi-scan file,
  161117. * set num_scans and scan_info to point to an array of scan definitions.
  161118. */
  161119. boolean raw_data_in; /* TRUE=caller supplies downsampled data */
  161120. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  161121. boolean optimize_coding; /* TRUE=optimize entropy encoding parms */
  161122. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  161123. int smoothing_factor; /* 1..100, or 0 for no input smoothing */
  161124. J_DCT_METHOD dct_method; /* DCT algorithm selector */
  161125. /* The restart interval can be specified in absolute MCUs by setting
  161126. * restart_interval, or in MCU rows by setting restart_in_rows
  161127. * (in which case the correct restart_interval will be figured
  161128. * for each scan).
  161129. */
  161130. unsigned int restart_interval; /* MCUs per restart, or 0 for no restart */
  161131. int restart_in_rows; /* if > 0, MCU rows per restart interval */
  161132. /* Parameters controlling emission of special markers. */
  161133. boolean write_JFIF_header; /* should a JFIF marker be written? */
  161134. UINT8 JFIF_major_version; /* What to write for the JFIF version number */
  161135. UINT8 JFIF_minor_version;
  161136. /* These three values are not used by the JPEG code, merely copied */
  161137. /* into the JFIF APP0 marker. density_unit can be 0 for unknown, */
  161138. /* 1 for dots/inch, or 2 for dots/cm. Note that the pixel aspect */
  161139. /* ratio is defined by X_density/Y_density even when density_unit=0. */
  161140. UINT8 density_unit; /* JFIF code for pixel size units */
  161141. UINT16 X_density; /* Horizontal pixel density */
  161142. UINT16 Y_density; /* Vertical pixel density */
  161143. boolean write_Adobe_marker; /* should an Adobe marker be written? */
  161144. /* State variable: index of next scanline to be written to
  161145. * jpeg_write_scanlines(). Application may use this to control its
  161146. * processing loop, e.g., "while (next_scanline < image_height)".
  161147. */
  161148. JDIMENSION next_scanline; /* 0 .. image_height-1 */
  161149. /* Remaining fields are known throughout compressor, but generally
  161150. * should not be touched by a surrounding application.
  161151. */
  161152. /*
  161153. * These fields are computed during compression startup
  161154. */
  161155. boolean progressive_mode; /* TRUE if scan script uses progressive mode */
  161156. int max_h_samp_factor; /* largest h_samp_factor */
  161157. int max_v_samp_factor; /* largest v_samp_factor */
  161158. JDIMENSION total_iMCU_rows; /* # of iMCU rows to be input to coef ctlr */
  161159. /* The coefficient controller receives data in units of MCU rows as defined
  161160. * for fully interleaved scans (whether the JPEG file is interleaved or not).
  161161. * There are v_samp_factor * DCTSIZE sample rows of each component in an
  161162. * "iMCU" (interleaved MCU) row.
  161163. */
  161164. /*
  161165. * These fields are valid during any one scan.
  161166. * They describe the components and MCUs actually appearing in the scan.
  161167. */
  161168. int comps_in_scan; /* # of JPEG components in this scan */
  161169. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  161170. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  161171. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  161172. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  161173. int blocks_in_MCU; /* # of DCT blocks per MCU */
  161174. int MCU_membership[C_MAX_BLOCKS_IN_MCU];
  161175. /* MCU_membership[i] is index in cur_comp_info of component owning */
  161176. /* i'th block in an MCU */
  161177. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  161178. /*
  161179. * Links to compression subobjects (methods and private variables of modules)
  161180. */
  161181. struct jpeg_comp_master * master;
  161182. struct jpeg_c_main_controller * main;
  161183. struct jpeg_c_prep_controller * prep;
  161184. struct jpeg_c_coef_controller * coef;
  161185. struct jpeg_marker_writer * marker;
  161186. struct jpeg_color_converter * cconvert;
  161187. struct jpeg_downsampler * downsample;
  161188. struct jpeg_forward_dct * fdct;
  161189. struct jpeg_entropy_encoder * entropy;
  161190. jpeg_scan_info * script_space; /* workspace for jpeg_simple_progression */
  161191. int script_space_size;
  161192. };
  161193. /* Master record for a decompression instance */
  161194. struct jpeg_decompress_struct {
  161195. jpeg_common_fields; /* Fields shared with jpeg_compress_struct */
  161196. /* Source of compressed data */
  161197. struct jpeg_source_mgr * src;
  161198. /* Basic description of image --- filled in by jpeg_read_header(). */
  161199. /* Application may inspect these values to decide how to process image. */
  161200. JDIMENSION image_width; /* nominal image width (from SOF marker) */
  161201. JDIMENSION image_height; /* nominal image height */
  161202. int num_components; /* # of color components in JPEG image */
  161203. J_COLOR_SPACE jpeg_color_space; /* colorspace of JPEG image */
  161204. /* Decompression processing parameters --- these fields must be set before
  161205. * calling jpeg_start_decompress(). Note that jpeg_read_header() initializes
  161206. * them to default values.
  161207. */
  161208. J_COLOR_SPACE out_color_space; /* colorspace for output */
  161209. unsigned int scale_num, scale_denom; /* fraction by which to scale image */
  161210. double output_gamma; /* image gamma wanted in output */
  161211. boolean buffered_image; /* TRUE=multiple output passes */
  161212. boolean raw_data_out; /* TRUE=downsampled data wanted */
  161213. J_DCT_METHOD dct_method; /* IDCT algorithm selector */
  161214. boolean do_fancy_upsampling; /* TRUE=apply fancy upsampling */
  161215. boolean do_block_smoothing; /* TRUE=apply interblock smoothing */
  161216. boolean quantize_colors; /* TRUE=colormapped output wanted */
  161217. /* the following are ignored if not quantize_colors: */
  161218. J_DITHER_MODE dither_mode; /* type of color dithering to use */
  161219. boolean two_pass_quantize; /* TRUE=use two-pass color quantization */
  161220. int desired_number_of_colors; /* max # colors to use in created colormap */
  161221. /* these are significant only in buffered-image mode: */
  161222. boolean enable_1pass_quant; /* enable future use of 1-pass quantizer */
  161223. boolean enable_external_quant;/* enable future use of external colormap */
  161224. boolean enable_2pass_quant; /* enable future use of 2-pass quantizer */
  161225. /* Description of actual output image that will be returned to application.
  161226. * These fields are computed by jpeg_start_decompress().
  161227. * You can also use jpeg_calc_output_dimensions() to determine these values
  161228. * in advance of calling jpeg_start_decompress().
  161229. */
  161230. JDIMENSION output_width; /* scaled image width */
  161231. JDIMENSION output_height; /* scaled image height */
  161232. int out_color_components; /* # of color components in out_color_space */
  161233. int output_components; /* # of color components returned */
  161234. /* output_components is 1 (a colormap index) when quantizing colors;
  161235. * otherwise it equals out_color_components.
  161236. */
  161237. int rec_outbuf_height; /* min recommended height of scanline buffer */
  161238. /* If the buffer passed to jpeg_read_scanlines() is less than this many rows
  161239. * high, space and time will be wasted due to unnecessary data copying.
  161240. * Usually rec_outbuf_height will be 1 or 2, at most 4.
  161241. */
  161242. /* When quantizing colors, the output colormap is described by these fields.
  161243. * The application can supply a colormap by setting colormap non-NULL before
  161244. * calling jpeg_start_decompress; otherwise a colormap is created during
  161245. * jpeg_start_decompress or jpeg_start_output.
  161246. * The map has out_color_components rows and actual_number_of_colors columns.
  161247. */
  161248. int actual_number_of_colors; /* number of entries in use */
  161249. JSAMPARRAY colormap; /* The color map as a 2-D pixel array */
  161250. /* State variables: these variables indicate the progress of decompression.
  161251. * The application may examine these but must not modify them.
  161252. */
  161253. /* Row index of next scanline to be read from jpeg_read_scanlines().
  161254. * Application may use this to control its processing loop, e.g.,
  161255. * "while (output_scanline < output_height)".
  161256. */
  161257. JDIMENSION output_scanline; /* 0 .. output_height-1 */
  161258. /* Current input scan number and number of iMCU rows completed in scan.
  161259. * These indicate the progress of the decompressor input side.
  161260. */
  161261. int input_scan_number; /* Number of SOS markers seen so far */
  161262. JDIMENSION input_iMCU_row; /* Number of iMCU rows completed */
  161263. /* The "output scan number" is the notional scan being displayed by the
  161264. * output side. The decompressor will not allow output scan/row number
  161265. * to get ahead of input scan/row, but it can fall arbitrarily far behind.
  161266. */
  161267. int output_scan_number; /* Nominal scan number being displayed */
  161268. JDIMENSION output_iMCU_row; /* Number of iMCU rows read */
  161269. /* Current progression status. coef_bits[c][i] indicates the precision
  161270. * with which component c's DCT coefficient i (in zigzag order) is known.
  161271. * It is -1 when no data has yet been received, otherwise it is the point
  161272. * transform (shift) value for the most recent scan of the coefficient
  161273. * (thus, 0 at completion of the progression).
  161274. * This pointer is NULL when reading a non-progressive file.
  161275. */
  161276. int (*coef_bits)[DCTSIZE2]; /* -1 or current Al value for each coef */
  161277. /* Internal JPEG parameters --- the application usually need not look at
  161278. * these fields. Note that the decompressor output side may not use
  161279. * any parameters that can change between scans.
  161280. */
  161281. /* Quantization and Huffman tables are carried forward across input
  161282. * datastreams when processing abbreviated JPEG datastreams.
  161283. */
  161284. JQUANT_TBL * quant_tbl_ptrs[NUM_QUANT_TBLS];
  161285. /* ptrs to coefficient quantization tables, or NULL if not defined */
  161286. JHUFF_TBL * dc_huff_tbl_ptrs[NUM_HUFF_TBLS];
  161287. JHUFF_TBL * ac_huff_tbl_ptrs[NUM_HUFF_TBLS];
  161288. /* ptrs to Huffman coding tables, or NULL if not defined */
  161289. /* These parameters are never carried across datastreams, since they
  161290. * are given in SOF/SOS markers or defined to be reset by SOI.
  161291. */
  161292. int data_precision; /* bits of precision in image data */
  161293. jpeg_component_info * comp_info;
  161294. /* comp_info[i] describes component that appears i'th in SOF */
  161295. boolean progressive_mode; /* TRUE if SOFn specifies progressive mode */
  161296. boolean arith_code; /* TRUE=arithmetic coding, FALSE=Huffman */
  161297. UINT8 arith_dc_L[NUM_ARITH_TBLS]; /* L values for DC arith-coding tables */
  161298. UINT8 arith_dc_U[NUM_ARITH_TBLS]; /* U values for DC arith-coding tables */
  161299. UINT8 arith_ac_K[NUM_ARITH_TBLS]; /* Kx values for AC arith-coding tables */
  161300. unsigned int restart_interval; /* MCUs per restart interval, or 0 for no restart */
  161301. /* These fields record data obtained from optional markers recognized by
  161302. * the JPEG library.
  161303. */
  161304. boolean saw_JFIF_marker; /* TRUE iff a JFIF APP0 marker was found */
  161305. /* Data copied from JFIF marker; only valid if saw_JFIF_marker is TRUE: */
  161306. UINT8 JFIF_major_version; /* JFIF version number */
  161307. UINT8 JFIF_minor_version;
  161308. UINT8 density_unit; /* JFIF code for pixel size units */
  161309. UINT16 X_density; /* Horizontal pixel density */
  161310. UINT16 Y_density; /* Vertical pixel density */
  161311. boolean saw_Adobe_marker; /* TRUE iff an Adobe APP14 marker was found */
  161312. UINT8 Adobe_transform; /* Color transform code from Adobe marker */
  161313. boolean CCIR601_sampling; /* TRUE=first samples are cosited */
  161314. /* Aside from the specific data retained from APPn markers known to the
  161315. * library, the uninterpreted contents of any or all APPn and COM markers
  161316. * can be saved in a list for examination by the application.
  161317. */
  161318. jpeg_saved_marker_ptr marker_list; /* Head of list of saved markers */
  161319. /* Remaining fields are known throughout decompressor, but generally
  161320. * should not be touched by a surrounding application.
  161321. */
  161322. /*
  161323. * These fields are computed during decompression startup
  161324. */
  161325. int max_h_samp_factor; /* largest h_samp_factor */
  161326. int max_v_samp_factor; /* largest v_samp_factor */
  161327. int min_DCT_scaled_size; /* smallest DCT_scaled_size of any component */
  161328. JDIMENSION total_iMCU_rows; /* # of iMCU rows in image */
  161329. /* The coefficient controller's input and output progress is measured in
  161330. * units of "iMCU" (interleaved MCU) rows. These are the same as MCU rows
  161331. * in fully interleaved JPEG scans, but are used whether the scan is
  161332. * interleaved or not. We define an iMCU row as v_samp_factor DCT block
  161333. * rows of each component. Therefore, the IDCT output contains
  161334. * v_samp_factor*DCT_scaled_size sample rows of a component per iMCU row.
  161335. */
  161336. JSAMPLE * sample_range_limit; /* table for fast range-limiting */
  161337. /*
  161338. * These fields are valid during any one scan.
  161339. * They describe the components and MCUs actually appearing in the scan.
  161340. * Note that the decompressor output side must not use these fields.
  161341. */
  161342. int comps_in_scan; /* # of JPEG components in this scan */
  161343. jpeg_component_info * cur_comp_info[MAX_COMPS_IN_SCAN];
  161344. /* *cur_comp_info[i] describes component that appears i'th in SOS */
  161345. JDIMENSION MCUs_per_row; /* # of MCUs across the image */
  161346. JDIMENSION MCU_rows_in_scan; /* # of MCU rows in the image */
  161347. int blocks_in_MCU; /* # of DCT blocks per MCU */
  161348. int MCU_membership[D_MAX_BLOCKS_IN_MCU];
  161349. /* MCU_membership[i] is index in cur_comp_info of component owning */
  161350. /* i'th block in an MCU */
  161351. int Ss, Se, Ah, Al; /* progressive JPEG parameters for scan */
  161352. /* This field is shared between entropy decoder and marker parser.
  161353. * It is either zero or the code of a JPEG marker that has been
  161354. * read from the data source, but has not yet been processed.
  161355. */
  161356. int unread_marker;
  161357. /*
  161358. * Links to decompression subobjects (methods, private variables of modules)
  161359. */
  161360. struct jpeg_decomp_master * master;
  161361. struct jpeg_d_main_controller * main;
  161362. struct jpeg_d_coef_controller * coef;
  161363. struct jpeg_d_post_controller * post;
  161364. struct jpeg_input_controller * inputctl;
  161365. struct jpeg_marker_reader * marker;
  161366. struct jpeg_entropy_decoder * entropy;
  161367. struct jpeg_inverse_dct * idct;
  161368. struct jpeg_upsampler * upsample;
  161369. struct jpeg_color_deconverter * cconvert;
  161370. struct jpeg_color_quantizer * cquantize;
  161371. };
  161372. /* "Object" declarations for JPEG modules that may be supplied or called
  161373. * directly by the surrounding application.
  161374. * As with all objects in the JPEG library, these structs only define the
  161375. * publicly visible methods and state variables of a module. Additional
  161376. * private fields may exist after the public ones.
  161377. */
  161378. /* Error handler object */
  161379. struct jpeg_error_mgr {
  161380. /* Error exit handler: does not return to caller */
  161381. JMETHOD(void, error_exit, (j_common_ptr cinfo));
  161382. /* Conditionally emit a trace or warning message */
  161383. JMETHOD(void, emit_message, (j_common_ptr cinfo, int msg_level));
  161384. /* Routine that actually outputs a trace or error message */
  161385. JMETHOD(void, output_message, (j_common_ptr cinfo));
  161386. /* Format a message string for the most recent JPEG error or message */
  161387. JMETHOD(void, format_message, (j_common_ptr cinfo, char * buffer));
  161388. #define JMSG_LENGTH_MAX 200 /* recommended size of format_message buffer */
  161389. /* Reset error state variables at start of a new image */
  161390. JMETHOD(void, reset_error_mgr, (j_common_ptr cinfo));
  161391. /* The message ID code and any parameters are saved here.
  161392. * A message can have one string parameter or up to 8 int parameters.
  161393. */
  161394. int msg_code;
  161395. #define JMSG_STR_PARM_MAX 80
  161396. union {
  161397. int i[8];
  161398. char s[JMSG_STR_PARM_MAX];
  161399. } msg_parm;
  161400. /* Standard state variables for error facility */
  161401. int trace_level; /* max msg_level that will be displayed */
  161402. /* For recoverable corrupt-data errors, we emit a warning message,
  161403. * but keep going unless emit_message chooses to abort. emit_message
  161404. * should count warnings in num_warnings. The surrounding application
  161405. * can check for bad data by seeing if num_warnings is nonzero at the
  161406. * end of processing.
  161407. */
  161408. long num_warnings; /* number of corrupt-data warnings */
  161409. /* These fields point to the table(s) of error message strings.
  161410. * An application can change the table pointer to switch to a different
  161411. * message list (typically, to change the language in which errors are
  161412. * reported). Some applications may wish to add additional error codes
  161413. * that will be handled by the JPEG library error mechanism; the second
  161414. * table pointer is used for this purpose.
  161415. *
  161416. * First table includes all errors generated by JPEG library itself.
  161417. * Error code 0 is reserved for a "no such error string" message.
  161418. */
  161419. const char * const * jpeg_message_table; /* Library errors */
  161420. int last_jpeg_message; /* Table contains strings 0..last_jpeg_message */
  161421. /* Second table can be added by application (see cjpeg/djpeg for example).
  161422. * It contains strings numbered first_addon_message..last_addon_message.
  161423. */
  161424. const char * const * addon_message_table; /* Non-library errors */
  161425. int first_addon_message; /* code for first string in addon table */
  161426. int last_addon_message; /* code for last string in addon table */
  161427. };
  161428. /* Progress monitor object */
  161429. struct jpeg_progress_mgr {
  161430. JMETHOD(void, progress_monitor, (j_common_ptr cinfo));
  161431. long pass_counter; /* work units completed in this pass */
  161432. long pass_limit; /* total number of work units in this pass */
  161433. int completed_passes; /* passes completed so far */
  161434. int total_passes; /* total number of passes expected */
  161435. };
  161436. /* Data destination object for compression */
  161437. struct jpeg_destination_mgr {
  161438. JOCTET * next_output_byte; /* => next byte to write in buffer */
  161439. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  161440. JMETHOD(void, init_destination, (j_compress_ptr cinfo));
  161441. JMETHOD(boolean, empty_output_buffer, (j_compress_ptr cinfo));
  161442. JMETHOD(void, term_destination, (j_compress_ptr cinfo));
  161443. };
  161444. /* Data source object for decompression */
  161445. struct jpeg_source_mgr {
  161446. const JOCTET * next_input_byte; /* => next byte to read from buffer */
  161447. size_t bytes_in_buffer; /* # of bytes remaining in buffer */
  161448. JMETHOD(void, init_source, (j_decompress_ptr cinfo));
  161449. JMETHOD(boolean, fill_input_buffer, (j_decompress_ptr cinfo));
  161450. JMETHOD(void, skip_input_data, (j_decompress_ptr cinfo, long num_bytes));
  161451. JMETHOD(boolean, resync_to_restart, (j_decompress_ptr cinfo, int desired));
  161452. JMETHOD(void, term_source, (j_decompress_ptr cinfo));
  161453. };
  161454. /* Memory manager object.
  161455. * Allocates "small" objects (a few K total), "large" objects (tens of K),
  161456. * and "really big" objects (virtual arrays with backing store if needed).
  161457. * The memory manager does not allow individual objects to be freed; rather,
  161458. * each created object is assigned to a pool, and whole pools can be freed
  161459. * at once. This is faster and more convenient than remembering exactly what
  161460. * to free, especially where malloc()/free() are not too speedy.
  161461. * NB: alloc routines never return NULL. They exit to error_exit if not
  161462. * successful.
  161463. */
  161464. #define JPOOL_PERMANENT 0 /* lasts until master record is destroyed */
  161465. #define JPOOL_IMAGE 1 /* lasts until done with image/datastream */
  161466. #define JPOOL_NUMPOOLS 2
  161467. typedef struct jvirt_sarray_control * jvirt_sarray_ptr;
  161468. typedef struct jvirt_barray_control * jvirt_barray_ptr;
  161469. struct jpeg_memory_mgr {
  161470. /* Method pointers */
  161471. JMETHOD(void *, alloc_small, (j_common_ptr cinfo, int pool_id,
  161472. size_t sizeofobject));
  161473. JMETHOD(void FAR *, alloc_large, (j_common_ptr cinfo, int pool_id,
  161474. size_t sizeofobject));
  161475. JMETHOD(JSAMPARRAY, alloc_sarray, (j_common_ptr cinfo, int pool_id,
  161476. JDIMENSION samplesperrow,
  161477. JDIMENSION numrows));
  161478. JMETHOD(JBLOCKARRAY, alloc_barray, (j_common_ptr cinfo, int pool_id,
  161479. JDIMENSION blocksperrow,
  161480. JDIMENSION numrows));
  161481. JMETHOD(jvirt_sarray_ptr, request_virt_sarray, (j_common_ptr cinfo,
  161482. int pool_id,
  161483. boolean pre_zero,
  161484. JDIMENSION samplesperrow,
  161485. JDIMENSION numrows,
  161486. JDIMENSION maxaccess));
  161487. JMETHOD(jvirt_barray_ptr, request_virt_barray, (j_common_ptr cinfo,
  161488. int pool_id,
  161489. boolean pre_zero,
  161490. JDIMENSION blocksperrow,
  161491. JDIMENSION numrows,
  161492. JDIMENSION maxaccess));
  161493. JMETHOD(void, realize_virt_arrays, (j_common_ptr cinfo));
  161494. JMETHOD(JSAMPARRAY, access_virt_sarray, (j_common_ptr cinfo,
  161495. jvirt_sarray_ptr ptr,
  161496. JDIMENSION start_row,
  161497. JDIMENSION num_rows,
  161498. boolean writable));
  161499. JMETHOD(JBLOCKARRAY, access_virt_barray, (j_common_ptr cinfo,
  161500. jvirt_barray_ptr ptr,
  161501. JDIMENSION start_row,
  161502. JDIMENSION num_rows,
  161503. boolean writable));
  161504. JMETHOD(void, free_pool, (j_common_ptr cinfo, int pool_id));
  161505. JMETHOD(void, self_destruct, (j_common_ptr cinfo));
  161506. /* Limit on memory allocation for this JPEG object. (Note that this is
  161507. * merely advisory, not a guaranteed maximum; it only affects the space
  161508. * used for virtual-array buffers.) May be changed by outer application
  161509. * after creating the JPEG object.
  161510. */
  161511. long max_memory_to_use;
  161512. /* Maximum allocation request accepted by alloc_large. */
  161513. long max_alloc_chunk;
  161514. };
  161515. /* Routine signature for application-supplied marker processing methods.
  161516. * Need not pass marker code since it is stored in cinfo->unread_marker.
  161517. */
  161518. typedef JMETHOD(boolean, jpeg_marker_parser_method, (j_decompress_ptr cinfo));
  161519. /* Declarations for routines called by application.
  161520. * The JPP macro hides prototype parameters from compilers that can't cope.
  161521. * Note JPP requires double parentheses.
  161522. */
  161523. #ifdef HAVE_PROTOTYPES
  161524. #define JPP(arglist) arglist
  161525. #else
  161526. #define JPP(arglist) ()
  161527. #endif
  161528. /* Short forms of external names for systems with brain-damaged linkers.
  161529. * We shorten external names to be unique in the first six letters, which
  161530. * is good enough for all known systems.
  161531. * (If your compiler itself needs names to be unique in less than 15
  161532. * characters, you are out of luck. Get a better compiler.)
  161533. */
  161534. #ifdef NEED_SHORT_EXTERNAL_NAMES
  161535. #define jpeg_std_error jStdError
  161536. #define jpeg_CreateCompress jCreaCompress
  161537. #define jpeg_CreateDecompress jCreaDecompress
  161538. #define jpeg_destroy_compress jDestCompress
  161539. #define jpeg_destroy_decompress jDestDecompress
  161540. #define jpeg_stdio_dest jStdDest
  161541. #define jpeg_stdio_src jStdSrc
  161542. #define jpeg_set_defaults jSetDefaults
  161543. #define jpeg_set_colorspace jSetColorspace
  161544. #define jpeg_default_colorspace jDefColorspace
  161545. #define jpeg_set_quality jSetQuality
  161546. #define jpeg_set_linear_quality jSetLQuality
  161547. #define jpeg_add_quant_table jAddQuantTable
  161548. #define jpeg_quality_scaling jQualityScaling
  161549. #define jpeg_simple_progression jSimProgress
  161550. #define jpeg_suppress_tables jSuppressTables
  161551. #define jpeg_alloc_quant_table jAlcQTable
  161552. #define jpeg_alloc_huff_table jAlcHTable
  161553. #define jpeg_start_compress jStrtCompress
  161554. #define jpeg_write_scanlines jWrtScanlines
  161555. #define jpeg_finish_compress jFinCompress
  161556. #define jpeg_write_raw_data jWrtRawData
  161557. #define jpeg_write_marker jWrtMarker
  161558. #define jpeg_write_m_header jWrtMHeader
  161559. #define jpeg_write_m_byte jWrtMByte
  161560. #define jpeg_write_tables jWrtTables
  161561. #define jpeg_read_header jReadHeader
  161562. #define jpeg_start_decompress jStrtDecompress
  161563. #define jpeg_read_scanlines jReadScanlines
  161564. #define jpeg_finish_decompress jFinDecompress
  161565. #define jpeg_read_raw_data jReadRawData
  161566. #define jpeg_has_multiple_scans jHasMultScn
  161567. #define jpeg_start_output jStrtOutput
  161568. #define jpeg_finish_output jFinOutput
  161569. #define jpeg_input_complete jInComplete
  161570. #define jpeg_new_colormap jNewCMap
  161571. #define jpeg_consume_input jConsumeInput
  161572. #define jpeg_calc_output_dimensions jCalcDimensions
  161573. #define jpeg_save_markers jSaveMarkers
  161574. #define jpeg_set_marker_processor jSetMarker
  161575. #define jpeg_read_coefficients jReadCoefs
  161576. #define jpeg_write_coefficients jWrtCoefs
  161577. #define jpeg_copy_critical_parameters jCopyCrit
  161578. #define jpeg_abort_compress jAbrtCompress
  161579. #define jpeg_abort_decompress jAbrtDecompress
  161580. #define jpeg_abort jAbort
  161581. #define jpeg_destroy jDestroy
  161582. #define jpeg_resync_to_restart jResyncRestart
  161583. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  161584. /* Default error-management setup */
  161585. EXTERN(struct jpeg_error_mgr *) jpeg_std_error
  161586. JPP((struct jpeg_error_mgr * err));
  161587. /* Initialization of JPEG compression objects.
  161588. * jpeg_create_compress() and jpeg_create_decompress() are the exported
  161589. * names that applications should call. These expand to calls on
  161590. * jpeg_CreateCompress and jpeg_CreateDecompress with additional information
  161591. * passed for version mismatch checking.
  161592. * NB: you must set up the error-manager BEFORE calling jpeg_create_xxx.
  161593. */
  161594. #define jpeg_create_compress(cinfo) \
  161595. jpeg_CreateCompress((cinfo), JPEG_LIB_VERSION, \
  161596. (size_t) sizeof(struct jpeg_compress_struct))
  161597. #define jpeg_create_decompress(cinfo) \
  161598. jpeg_CreateDecompress((cinfo), JPEG_LIB_VERSION, \
  161599. (size_t) sizeof(struct jpeg_decompress_struct))
  161600. EXTERN(void) jpeg_CreateCompress JPP((j_compress_ptr cinfo,
  161601. int version, size_t structsize));
  161602. EXTERN(void) jpeg_CreateDecompress JPP((j_decompress_ptr cinfo,
  161603. int version, size_t structsize));
  161604. /* Destruction of JPEG compression objects */
  161605. EXTERN(void) jpeg_destroy_compress JPP((j_compress_ptr cinfo));
  161606. EXTERN(void) jpeg_destroy_decompress JPP((j_decompress_ptr cinfo));
  161607. /* Standard data source and destination managers: stdio streams. */
  161608. /* Caller is responsible for opening the file before and closing after. */
  161609. EXTERN(void) jpeg_stdio_dest JPP((j_compress_ptr cinfo, FILE * outfile));
  161610. EXTERN(void) jpeg_stdio_src JPP((j_decompress_ptr cinfo, FILE * infile));
  161611. /* Default parameter setup for compression */
  161612. EXTERN(void) jpeg_set_defaults JPP((j_compress_ptr cinfo));
  161613. /* Compression parameter setup aids */
  161614. EXTERN(void) jpeg_set_colorspace JPP((j_compress_ptr cinfo,
  161615. J_COLOR_SPACE colorspace));
  161616. EXTERN(void) jpeg_default_colorspace JPP((j_compress_ptr cinfo));
  161617. EXTERN(void) jpeg_set_quality JPP((j_compress_ptr cinfo, int quality,
  161618. boolean force_baseline));
  161619. EXTERN(void) jpeg_set_linear_quality JPP((j_compress_ptr cinfo,
  161620. int scale_factor,
  161621. boolean force_baseline));
  161622. EXTERN(void) jpeg_add_quant_table JPP((j_compress_ptr cinfo, int which_tbl,
  161623. const unsigned int *basic_table,
  161624. int scale_factor,
  161625. boolean force_baseline));
  161626. EXTERN(int) jpeg_quality_scaling JPP((int quality));
  161627. EXTERN(void) jpeg_simple_progression JPP((j_compress_ptr cinfo));
  161628. EXTERN(void) jpeg_suppress_tables JPP((j_compress_ptr cinfo,
  161629. boolean suppress));
  161630. EXTERN(JQUANT_TBL *) jpeg_alloc_quant_table JPP((j_common_ptr cinfo));
  161631. EXTERN(JHUFF_TBL *) jpeg_alloc_huff_table JPP((j_common_ptr cinfo));
  161632. /* Main entry points for compression */
  161633. EXTERN(void) jpeg_start_compress JPP((j_compress_ptr cinfo,
  161634. boolean write_all_tables));
  161635. EXTERN(JDIMENSION) jpeg_write_scanlines JPP((j_compress_ptr cinfo,
  161636. JSAMPARRAY scanlines,
  161637. JDIMENSION num_lines));
  161638. EXTERN(void) jpeg_finish_compress JPP((j_compress_ptr cinfo));
  161639. /* Replaces jpeg_write_scanlines when writing raw downsampled data. */
  161640. EXTERN(JDIMENSION) jpeg_write_raw_data JPP((j_compress_ptr cinfo,
  161641. JSAMPIMAGE data,
  161642. JDIMENSION num_lines));
  161643. /* Write a special marker. See libjpeg.doc concerning safe usage. */
  161644. EXTERN(void) jpeg_write_marker
  161645. JPP((j_compress_ptr cinfo, int marker,
  161646. const JOCTET * dataptr, unsigned int datalen));
  161647. /* Same, but piecemeal. */
  161648. EXTERN(void) jpeg_write_m_header
  161649. JPP((j_compress_ptr cinfo, int marker, unsigned int datalen));
  161650. EXTERN(void) jpeg_write_m_byte
  161651. JPP((j_compress_ptr cinfo, int val));
  161652. /* Alternate compression function: just write an abbreviated table file */
  161653. EXTERN(void) jpeg_write_tables JPP((j_compress_ptr cinfo));
  161654. /* Decompression startup: read start of JPEG datastream to see what's there */
  161655. EXTERN(int) jpeg_read_header JPP((j_decompress_ptr cinfo,
  161656. boolean require_image));
  161657. /* Return value is one of: */
  161658. #define JPEG_SUSPENDED 0 /* Suspended due to lack of input data */
  161659. #define JPEG_HEADER_OK 1 /* Found valid image datastream */
  161660. #define JPEG_HEADER_TABLES_ONLY 2 /* Found valid table-specs-only datastream */
  161661. /* If you pass require_image = TRUE (normal case), you need not check for
  161662. * a TABLES_ONLY return code; an abbreviated file will cause an error exit.
  161663. * JPEG_SUSPENDED is only possible if you use a data source module that can
  161664. * give a suspension return (the stdio source module doesn't).
  161665. */
  161666. /* Main entry points for decompression */
  161667. EXTERN(boolean) jpeg_start_decompress JPP((j_decompress_ptr cinfo));
  161668. EXTERN(JDIMENSION) jpeg_read_scanlines JPP((j_decompress_ptr cinfo,
  161669. JSAMPARRAY scanlines,
  161670. JDIMENSION max_lines));
  161671. EXTERN(boolean) jpeg_finish_decompress JPP((j_decompress_ptr cinfo));
  161672. /* Replaces jpeg_read_scanlines when reading raw downsampled data. */
  161673. EXTERN(JDIMENSION) jpeg_read_raw_data JPP((j_decompress_ptr cinfo,
  161674. JSAMPIMAGE data,
  161675. JDIMENSION max_lines));
  161676. /* Additional entry points for buffered-image mode. */
  161677. EXTERN(boolean) jpeg_has_multiple_scans JPP((j_decompress_ptr cinfo));
  161678. EXTERN(boolean) jpeg_start_output JPP((j_decompress_ptr cinfo,
  161679. int scan_number));
  161680. EXTERN(boolean) jpeg_finish_output JPP((j_decompress_ptr cinfo));
  161681. EXTERN(boolean) jpeg_input_complete JPP((j_decompress_ptr cinfo));
  161682. EXTERN(void) jpeg_new_colormap JPP((j_decompress_ptr cinfo));
  161683. EXTERN(int) jpeg_consume_input JPP((j_decompress_ptr cinfo));
  161684. /* Return value is one of: */
  161685. /* #define JPEG_SUSPENDED 0 Suspended due to lack of input data */
  161686. #define JPEG_REACHED_SOS 1 /* Reached start of new scan */
  161687. #define JPEG_REACHED_EOI 2 /* Reached end of image */
  161688. #define JPEG_ROW_COMPLETED 3 /* Completed one iMCU row */
  161689. #define JPEG_SCAN_COMPLETED 4 /* Completed last iMCU row of a scan */
  161690. /* Precalculate output dimensions for current decompression parameters. */
  161691. EXTERN(void) jpeg_calc_output_dimensions JPP((j_decompress_ptr cinfo));
  161692. /* Control saving of COM and APPn markers into marker_list. */
  161693. EXTERN(void) jpeg_save_markers
  161694. JPP((j_decompress_ptr cinfo, int marker_code,
  161695. unsigned int length_limit));
  161696. /* Install a special processing method for COM or APPn markers. */
  161697. EXTERN(void) jpeg_set_marker_processor
  161698. JPP((j_decompress_ptr cinfo, int marker_code,
  161699. jpeg_marker_parser_method routine));
  161700. /* Read or write raw DCT coefficients --- useful for lossless transcoding. */
  161701. EXTERN(jvirt_barray_ptr *) jpeg_read_coefficients JPP((j_decompress_ptr cinfo));
  161702. EXTERN(void) jpeg_write_coefficients JPP((j_compress_ptr cinfo,
  161703. jvirt_barray_ptr * coef_arrays));
  161704. EXTERN(void) jpeg_copy_critical_parameters JPP((j_decompress_ptr srcinfo,
  161705. j_compress_ptr dstinfo));
  161706. /* If you choose to abort compression or decompression before completing
  161707. * jpeg_finish_(de)compress, then you need to clean up to release memory,
  161708. * temporary files, etc. You can just call jpeg_destroy_(de)compress
  161709. * if you're done with the JPEG object, but if you want to clean it up and
  161710. * reuse it, call this:
  161711. */
  161712. EXTERN(void) jpeg_abort_compress JPP((j_compress_ptr cinfo));
  161713. EXTERN(void) jpeg_abort_decompress JPP((j_decompress_ptr cinfo));
  161714. /* Generic versions of jpeg_abort and jpeg_destroy that work on either
  161715. * flavor of JPEG object. These may be more convenient in some places.
  161716. */
  161717. EXTERN(void) jpeg_abort JPP((j_common_ptr cinfo));
  161718. EXTERN(void) jpeg_destroy JPP((j_common_ptr cinfo));
  161719. /* Default restart-marker-resync procedure for use by data source modules */
  161720. EXTERN(boolean) jpeg_resync_to_restart JPP((j_decompress_ptr cinfo,
  161721. int desired));
  161722. /* These marker codes are exported since applications and data source modules
  161723. * are likely to want to use them.
  161724. */
  161725. #define JPEG_RST0 0xD0 /* RST0 marker code */
  161726. #define JPEG_EOI 0xD9 /* EOI marker code */
  161727. #define JPEG_APP0 0xE0 /* APP0 marker code */
  161728. #define JPEG_COM 0xFE /* COM marker code */
  161729. /* If we have a brain-damaged compiler that emits warnings (or worse, errors)
  161730. * for structure definitions that are never filled in, keep it quiet by
  161731. * supplying dummy definitions for the various substructures.
  161732. */
  161733. #ifdef INCOMPLETE_TYPES_BROKEN
  161734. #ifndef JPEG_INTERNALS /* will be defined in jpegint.h */
  161735. struct jvirt_sarray_control { long dummy; };
  161736. struct jvirt_barray_control { long dummy; };
  161737. struct jpeg_comp_master { long dummy; };
  161738. struct jpeg_c_main_controller { long dummy; };
  161739. struct jpeg_c_prep_controller { long dummy; };
  161740. struct jpeg_c_coef_controller { long dummy; };
  161741. struct jpeg_marker_writer { long dummy; };
  161742. struct jpeg_color_converter { long dummy; };
  161743. struct jpeg_downsampler { long dummy; };
  161744. struct jpeg_forward_dct { long dummy; };
  161745. struct jpeg_entropy_encoder { long dummy; };
  161746. struct jpeg_decomp_master { long dummy; };
  161747. struct jpeg_d_main_controller { long dummy; };
  161748. struct jpeg_d_coef_controller { long dummy; };
  161749. struct jpeg_d_post_controller { long dummy; };
  161750. struct jpeg_input_controller { long dummy; };
  161751. struct jpeg_marker_reader { long dummy; };
  161752. struct jpeg_entropy_decoder { long dummy; };
  161753. struct jpeg_inverse_dct { long dummy; };
  161754. struct jpeg_upsampler { long dummy; };
  161755. struct jpeg_color_deconverter { long dummy; };
  161756. struct jpeg_color_quantizer { long dummy; };
  161757. #endif /* JPEG_INTERNALS */
  161758. #endif /* INCOMPLETE_TYPES_BROKEN */
  161759. /*
  161760. * The JPEG library modules define JPEG_INTERNALS before including this file.
  161761. * The internal structure declarations are read only when that is true.
  161762. * Applications using the library should not include jpegint.h, but may wish
  161763. * to include jerror.h.
  161764. */
  161765. #ifdef JPEG_INTERNALS
  161766. /********* Start of inlined file: jpegint.h *********/
  161767. /* Declarations for both compression & decompression */
  161768. typedef enum { /* Operating modes for buffer controllers */
  161769. JBUF_PASS_THRU, /* Plain stripwise operation */
  161770. /* Remaining modes require a full-image buffer to have been created */
  161771. JBUF_SAVE_SOURCE, /* Run source subobject only, save output */
  161772. JBUF_CRANK_DEST, /* Run dest subobject only, using saved data */
  161773. JBUF_SAVE_AND_PASS /* Run both subobjects, save output */
  161774. } J_BUF_MODE;
  161775. /* Values of global_state field (jdapi.c has some dependencies on ordering!) */
  161776. #define CSTATE_START 100 /* after create_compress */
  161777. #define CSTATE_SCANNING 101 /* start_compress done, write_scanlines OK */
  161778. #define CSTATE_RAW_OK 102 /* start_compress done, write_raw_data OK */
  161779. #define CSTATE_WRCOEFS 103 /* jpeg_write_coefficients done */
  161780. #define DSTATE_START 200 /* after create_decompress */
  161781. #define DSTATE_INHEADER 201 /* reading header markers, no SOS yet */
  161782. #define DSTATE_READY 202 /* found SOS, ready for start_decompress */
  161783. #define DSTATE_PRELOAD 203 /* reading multiscan file in start_decompress*/
  161784. #define DSTATE_PRESCAN 204 /* performing dummy pass for 2-pass quant */
  161785. #define DSTATE_SCANNING 205 /* start_decompress done, read_scanlines OK */
  161786. #define DSTATE_RAW_OK 206 /* start_decompress done, read_raw_data OK */
  161787. #define DSTATE_BUFIMAGE 207 /* expecting jpeg_start_output */
  161788. #define DSTATE_BUFPOST 208 /* looking for SOS/EOI in jpeg_finish_output */
  161789. #define DSTATE_RDCOEFS 209 /* reading file in jpeg_read_coefficients */
  161790. #define DSTATE_STOPPING 210 /* looking for EOI in jpeg_finish_decompress */
  161791. /* Declarations for compression modules */
  161792. /* Master control module */
  161793. struct jpeg_comp_master {
  161794. JMETHOD(void, prepare_for_pass, (j_compress_ptr cinfo));
  161795. JMETHOD(void, pass_startup, (j_compress_ptr cinfo));
  161796. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  161797. /* State variables made visible to other modules */
  161798. boolean call_pass_startup; /* True if pass_startup must be called */
  161799. boolean is_last_pass; /* True during last pass */
  161800. };
  161801. /* Main buffer control (downsampled-data buffer) */
  161802. struct jpeg_c_main_controller {
  161803. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161804. JMETHOD(void, process_data, (j_compress_ptr cinfo,
  161805. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  161806. JDIMENSION in_rows_avail));
  161807. };
  161808. /* Compression preprocessing (downsampling input buffer control) */
  161809. struct jpeg_c_prep_controller {
  161810. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161811. JMETHOD(void, pre_process_data, (j_compress_ptr cinfo,
  161812. JSAMPARRAY input_buf,
  161813. JDIMENSION *in_row_ctr,
  161814. JDIMENSION in_rows_avail,
  161815. JSAMPIMAGE output_buf,
  161816. JDIMENSION *out_row_group_ctr,
  161817. JDIMENSION out_row_groups_avail));
  161818. };
  161819. /* Coefficient buffer control */
  161820. struct jpeg_c_coef_controller {
  161821. JMETHOD(void, start_pass, (j_compress_ptr cinfo, J_BUF_MODE pass_mode));
  161822. JMETHOD(boolean, compress_data, (j_compress_ptr cinfo,
  161823. JSAMPIMAGE input_buf));
  161824. };
  161825. /* Colorspace conversion */
  161826. struct jpeg_color_converter {
  161827. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161828. JMETHOD(void, color_convert, (j_compress_ptr cinfo,
  161829. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  161830. JDIMENSION output_row, int num_rows));
  161831. };
  161832. /* Downsampling */
  161833. struct jpeg_downsampler {
  161834. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161835. JMETHOD(void, downsample, (j_compress_ptr cinfo,
  161836. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  161837. JSAMPIMAGE output_buf,
  161838. JDIMENSION out_row_group_index));
  161839. boolean need_context_rows; /* TRUE if need rows above & below */
  161840. };
  161841. /* Forward DCT (also controls coefficient quantization) */
  161842. struct jpeg_forward_dct {
  161843. JMETHOD(void, start_pass, (j_compress_ptr cinfo));
  161844. /* perhaps this should be an array??? */
  161845. JMETHOD(void, forward_DCT, (j_compress_ptr cinfo,
  161846. jpeg_component_info * compptr,
  161847. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  161848. JDIMENSION start_row, JDIMENSION start_col,
  161849. JDIMENSION num_blocks));
  161850. };
  161851. /* Entropy encoding */
  161852. struct jpeg_entropy_encoder {
  161853. JMETHOD(void, start_pass, (j_compress_ptr cinfo, boolean gather_statistics));
  161854. JMETHOD(boolean, encode_mcu, (j_compress_ptr cinfo, JBLOCKROW *MCU_data));
  161855. JMETHOD(void, finish_pass, (j_compress_ptr cinfo));
  161856. };
  161857. /* Marker writing */
  161858. struct jpeg_marker_writer {
  161859. JMETHOD(void, write_file_header, (j_compress_ptr cinfo));
  161860. JMETHOD(void, write_frame_header, (j_compress_ptr cinfo));
  161861. JMETHOD(void, write_scan_header, (j_compress_ptr cinfo));
  161862. JMETHOD(void, write_file_trailer, (j_compress_ptr cinfo));
  161863. JMETHOD(void, write_tables_only, (j_compress_ptr cinfo));
  161864. /* These routines are exported to allow insertion of extra markers */
  161865. /* Probably only COM and APPn markers should be written this way */
  161866. JMETHOD(void, write_marker_header, (j_compress_ptr cinfo, int marker,
  161867. unsigned int datalen));
  161868. JMETHOD(void, write_marker_byte, (j_compress_ptr cinfo, int val));
  161869. };
  161870. /* Declarations for decompression modules */
  161871. /* Master control module */
  161872. struct jpeg_decomp_master {
  161873. JMETHOD(void, prepare_for_output_pass, (j_decompress_ptr cinfo));
  161874. JMETHOD(void, finish_output_pass, (j_decompress_ptr cinfo));
  161875. /* State variables made visible to other modules */
  161876. boolean is_dummy_pass; /* True during 1st pass for 2-pass quant */
  161877. };
  161878. /* Input control module */
  161879. struct jpeg_input_controller {
  161880. JMETHOD(int, consume_input, (j_decompress_ptr cinfo));
  161881. JMETHOD(void, reset_input_controller, (j_decompress_ptr cinfo));
  161882. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161883. JMETHOD(void, finish_input_pass, (j_decompress_ptr cinfo));
  161884. /* State variables made visible to other modules */
  161885. boolean has_multiple_scans; /* True if file has multiple scans */
  161886. boolean eoi_reached; /* True when EOI has been consumed */
  161887. };
  161888. /* Main buffer control (downsampled-data buffer) */
  161889. struct jpeg_d_main_controller {
  161890. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161891. JMETHOD(void, process_data, (j_decompress_ptr cinfo,
  161892. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  161893. JDIMENSION out_rows_avail));
  161894. };
  161895. /* Coefficient buffer control */
  161896. struct jpeg_d_coef_controller {
  161897. JMETHOD(void, start_input_pass, (j_decompress_ptr cinfo));
  161898. JMETHOD(int, consume_data, (j_decompress_ptr cinfo));
  161899. JMETHOD(void, start_output_pass, (j_decompress_ptr cinfo));
  161900. JMETHOD(int, decompress_data, (j_decompress_ptr cinfo,
  161901. JSAMPIMAGE output_buf));
  161902. /* Pointer to array of coefficient virtual arrays, or NULL if none */
  161903. jvirt_barray_ptr *coef_arrays;
  161904. };
  161905. /* Decompression postprocessing (color quantization buffer control) */
  161906. struct jpeg_d_post_controller {
  161907. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, J_BUF_MODE pass_mode));
  161908. JMETHOD(void, post_process_data, (j_decompress_ptr cinfo,
  161909. JSAMPIMAGE input_buf,
  161910. JDIMENSION *in_row_group_ctr,
  161911. JDIMENSION in_row_groups_avail,
  161912. JSAMPARRAY output_buf,
  161913. JDIMENSION *out_row_ctr,
  161914. JDIMENSION out_rows_avail));
  161915. };
  161916. /* Marker reading & parsing */
  161917. struct jpeg_marker_reader {
  161918. JMETHOD(void, reset_marker_reader, (j_decompress_ptr cinfo));
  161919. /* Read markers until SOS or EOI.
  161920. * Returns same codes as are defined for jpeg_consume_input:
  161921. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  161922. */
  161923. JMETHOD(int, read_markers, (j_decompress_ptr cinfo));
  161924. /* Read a restart marker --- exported for use by entropy decoder only */
  161925. jpeg_marker_parser_method read_restart_marker;
  161926. /* State of marker reader --- nominally internal, but applications
  161927. * supplying COM or APPn handlers might like to know the state.
  161928. */
  161929. boolean saw_SOI; /* found SOI? */
  161930. boolean saw_SOF; /* found SOF? */
  161931. int next_restart_num; /* next restart number expected (0-7) */
  161932. unsigned int discarded_bytes; /* # of bytes skipped looking for a marker */
  161933. };
  161934. /* Entropy decoding */
  161935. struct jpeg_entropy_decoder {
  161936. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161937. JMETHOD(boolean, decode_mcu, (j_decompress_ptr cinfo,
  161938. JBLOCKROW *MCU_data));
  161939. /* This is here to share code between baseline and progressive decoders; */
  161940. /* other modules probably should not use it */
  161941. boolean insufficient_data; /* set TRUE after emitting warning */
  161942. };
  161943. /* Inverse DCT (also performs dequantization) */
  161944. typedef JMETHOD(void, inverse_DCT_method_ptr,
  161945. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  161946. JCOEFPTR coef_block,
  161947. JSAMPARRAY output_buf, JDIMENSION output_col));
  161948. struct jpeg_inverse_dct {
  161949. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161950. /* It is useful to allow each component to have a separate IDCT method. */
  161951. inverse_DCT_method_ptr inverse_DCT[MAX_COMPONENTS];
  161952. };
  161953. /* Upsampling (note that upsampler must also call color converter) */
  161954. struct jpeg_upsampler {
  161955. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161956. JMETHOD(void, upsample, (j_decompress_ptr cinfo,
  161957. JSAMPIMAGE input_buf,
  161958. JDIMENSION *in_row_group_ctr,
  161959. JDIMENSION in_row_groups_avail,
  161960. JSAMPARRAY output_buf,
  161961. JDIMENSION *out_row_ctr,
  161962. JDIMENSION out_rows_avail));
  161963. boolean need_context_rows; /* TRUE if need rows above & below */
  161964. };
  161965. /* Colorspace conversion */
  161966. struct jpeg_color_deconverter {
  161967. JMETHOD(void, start_pass, (j_decompress_ptr cinfo));
  161968. JMETHOD(void, color_convert, (j_decompress_ptr cinfo,
  161969. JSAMPIMAGE input_buf, JDIMENSION input_row,
  161970. JSAMPARRAY output_buf, int num_rows));
  161971. };
  161972. /* Color quantization or color precision reduction */
  161973. struct jpeg_color_quantizer {
  161974. JMETHOD(void, start_pass, (j_decompress_ptr cinfo, boolean is_pre_scan));
  161975. JMETHOD(void, color_quantize, (j_decompress_ptr cinfo,
  161976. JSAMPARRAY input_buf, JSAMPARRAY output_buf,
  161977. int num_rows));
  161978. JMETHOD(void, finish_pass, (j_decompress_ptr cinfo));
  161979. JMETHOD(void, new_color_map, (j_decompress_ptr cinfo));
  161980. };
  161981. /* Miscellaneous useful macros */
  161982. #undef MAX
  161983. #define MAX(a,b) ((a) > (b) ? (a) : (b))
  161984. #undef MIN
  161985. #define MIN(a,b) ((a) < (b) ? (a) : (b))
  161986. /* We assume that right shift corresponds to signed division by 2 with
  161987. * rounding towards minus infinity. This is correct for typical "arithmetic
  161988. * shift" instructions that shift in copies of the sign bit. But some
  161989. * C compilers implement >> with an unsigned shift. For these machines you
  161990. * must define RIGHT_SHIFT_IS_UNSIGNED.
  161991. * RIGHT_SHIFT provides a proper signed right shift of an INT32 quantity.
  161992. * It is only applied with constant shift counts. SHIFT_TEMPS must be
  161993. * included in the variables of any routine using RIGHT_SHIFT.
  161994. */
  161995. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  161996. #define SHIFT_TEMPS INT32 shift_temp;
  161997. #define RIGHT_SHIFT(x,shft) \
  161998. ((shift_temp = (x)) < 0 ? \
  161999. (shift_temp >> (shft)) | ((~((INT32) 0)) << (32-(shft))) : \
  162000. (shift_temp >> (shft)))
  162001. #else
  162002. #define SHIFT_TEMPS
  162003. #define RIGHT_SHIFT(x,shft) ((x) >> (shft))
  162004. #endif
  162005. /* Short forms of external names for systems with brain-damaged linkers. */
  162006. #ifdef NEED_SHORT_EXTERNAL_NAMES
  162007. #define jinit_compress_master jICompress
  162008. #define jinit_c_master_control jICMaster
  162009. #define jinit_c_main_controller jICMainC
  162010. #define jinit_c_prep_controller jICPrepC
  162011. #define jinit_c_coef_controller jICCoefC
  162012. #define jinit_color_converter jICColor
  162013. #define jinit_downsampler jIDownsampler
  162014. #define jinit_forward_dct jIFDCT
  162015. #define jinit_huff_encoder jIHEncoder
  162016. #define jinit_phuff_encoder jIPHEncoder
  162017. #define jinit_marker_writer jIMWriter
  162018. #define jinit_master_decompress jIDMaster
  162019. #define jinit_d_main_controller jIDMainC
  162020. #define jinit_d_coef_controller jIDCoefC
  162021. #define jinit_d_post_controller jIDPostC
  162022. #define jinit_input_controller jIInCtlr
  162023. #define jinit_marker_reader jIMReader
  162024. #define jinit_huff_decoder jIHDecoder
  162025. #define jinit_phuff_decoder jIPHDecoder
  162026. #define jinit_inverse_dct jIIDCT
  162027. #define jinit_upsampler jIUpsampler
  162028. #define jinit_color_deconverter jIDColor
  162029. #define jinit_1pass_quantizer jI1Quant
  162030. #define jinit_2pass_quantizer jI2Quant
  162031. #define jinit_merged_upsampler jIMUpsampler
  162032. #define jinit_memory_mgr jIMemMgr
  162033. #define jdiv_round_up jDivRound
  162034. #define jround_up jRound
  162035. #define jcopy_sample_rows jCopySamples
  162036. #define jcopy_block_row jCopyBlocks
  162037. #define jzero_far jZeroFar
  162038. #define jpeg_zigzag_order jZIGTable
  162039. #define jpeg_natural_order jZAGTable
  162040. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  162041. /* Compression module initialization routines */
  162042. EXTERN(void) jinit_compress_master JPP((j_compress_ptr cinfo));
  162043. EXTERN(void) jinit_c_master_control JPP((j_compress_ptr cinfo,
  162044. boolean transcode_only));
  162045. EXTERN(void) jinit_c_main_controller JPP((j_compress_ptr cinfo,
  162046. boolean need_full_buffer));
  162047. EXTERN(void) jinit_c_prep_controller JPP((j_compress_ptr cinfo,
  162048. boolean need_full_buffer));
  162049. EXTERN(void) jinit_c_coef_controller JPP((j_compress_ptr cinfo,
  162050. boolean need_full_buffer));
  162051. EXTERN(void) jinit_color_converter JPP((j_compress_ptr cinfo));
  162052. EXTERN(void) jinit_downsampler JPP((j_compress_ptr cinfo));
  162053. EXTERN(void) jinit_forward_dct JPP((j_compress_ptr cinfo));
  162054. EXTERN(void) jinit_huff_encoder JPP((j_compress_ptr cinfo));
  162055. EXTERN(void) jinit_phuff_encoder JPP((j_compress_ptr cinfo));
  162056. EXTERN(void) jinit_marker_writer JPP((j_compress_ptr cinfo));
  162057. /* Decompression module initialization routines */
  162058. EXTERN(void) jinit_master_decompress JPP((j_decompress_ptr cinfo));
  162059. EXTERN(void) jinit_d_main_controller JPP((j_decompress_ptr cinfo,
  162060. boolean need_full_buffer));
  162061. EXTERN(void) jinit_d_coef_controller JPP((j_decompress_ptr cinfo,
  162062. boolean need_full_buffer));
  162063. EXTERN(void) jinit_d_post_controller JPP((j_decompress_ptr cinfo,
  162064. boolean need_full_buffer));
  162065. EXTERN(void) jinit_input_controller JPP((j_decompress_ptr cinfo));
  162066. EXTERN(void) jinit_marker_reader JPP((j_decompress_ptr cinfo));
  162067. EXTERN(void) jinit_huff_decoder JPP((j_decompress_ptr cinfo));
  162068. EXTERN(void) jinit_phuff_decoder JPP((j_decompress_ptr cinfo));
  162069. EXTERN(void) jinit_inverse_dct JPP((j_decompress_ptr cinfo));
  162070. EXTERN(void) jinit_upsampler JPP((j_decompress_ptr cinfo));
  162071. EXTERN(void) jinit_color_deconverter JPP((j_decompress_ptr cinfo));
  162072. EXTERN(void) jinit_1pass_quantizer JPP((j_decompress_ptr cinfo));
  162073. EXTERN(void) jinit_2pass_quantizer JPP((j_decompress_ptr cinfo));
  162074. EXTERN(void) jinit_merged_upsampler JPP((j_decompress_ptr cinfo));
  162075. /* Memory manager initialization */
  162076. EXTERN(void) jinit_memory_mgr JPP((j_common_ptr cinfo));
  162077. /* Utility routines in jutils.c */
  162078. EXTERN(long) jdiv_round_up JPP((long a, long b));
  162079. EXTERN(long) jround_up JPP((long a, long b));
  162080. EXTERN(void) jcopy_sample_rows JPP((JSAMPARRAY input_array, int source_row,
  162081. JSAMPARRAY output_array, int dest_row,
  162082. int num_rows, JDIMENSION num_cols));
  162083. EXTERN(void) jcopy_block_row JPP((JBLOCKROW input_row, JBLOCKROW output_row,
  162084. JDIMENSION num_blocks));
  162085. EXTERN(void) jzero_far JPP((void FAR * target, size_t bytestozero));
  162086. /* Constant tables in jutils.c */
  162087. #if 0 /* This table is not actually needed in v6a */
  162088. extern const int jpeg_zigzag_order[]; /* natural coef order to zigzag order */
  162089. #endif
  162090. extern const int jpeg_natural_order[]; /* zigzag coef order to natural order */
  162091. /* Suppress undefined-structure complaints if necessary. */
  162092. #ifdef INCOMPLETE_TYPES_BROKEN
  162093. #ifndef AM_MEMORY_MANAGER /* only jmemmgr.c defines these */
  162094. struct jvirt_sarray_control { long dummy; };
  162095. struct jvirt_barray_control { long dummy; };
  162096. #endif
  162097. #endif /* INCOMPLETE_TYPES_BROKEN */
  162098. /********* End of inlined file: jpegint.h *********/
  162099. /* fetch private declarations */
  162100. /********* Start of inlined file: jerror.h *********/
  162101. /*
  162102. * To define the enum list of message codes, include this file without
  162103. * defining macro JMESSAGE. To create a message string table, include it
  162104. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  162105. */
  162106. #ifndef JMESSAGE
  162107. #ifndef JERROR_H
  162108. /* First time through, define the enum list */
  162109. #define JMAKE_ENUM_LIST
  162110. #else
  162111. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  162112. #define JMESSAGE(code,string)
  162113. #endif /* JERROR_H */
  162114. #endif /* JMESSAGE */
  162115. #ifdef JMAKE_ENUM_LIST
  162116. typedef enum {
  162117. #define JMESSAGE(code,string) code ,
  162118. #endif /* JMAKE_ENUM_LIST */
  162119. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  162120. /* For maintenance convenience, list is alphabetical by message code name */
  162121. JMESSAGE(JERR_ARITH_NOTIMPL,
  162122. "Sorry, there are legal restrictions on arithmetic coding")
  162123. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  162124. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  162125. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  162126. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  162127. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  162128. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  162129. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  162130. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  162131. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  162132. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  162133. JMESSAGE(JERR_BAD_LIB_VERSION,
  162134. "Wrong JPEG library version: library is %d, caller expects %d")
  162135. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  162136. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  162137. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  162138. JMESSAGE(JERR_BAD_PROGRESSION,
  162139. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  162140. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  162141. "Invalid progressive parameters at scan script entry %d")
  162142. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  162143. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  162144. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  162145. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  162146. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  162147. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  162148. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  162149. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  162150. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  162151. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  162152. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  162153. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  162154. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  162155. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  162156. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  162157. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  162158. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  162159. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  162160. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  162161. JMESSAGE(JERR_FILE_READ, "Input file read error")
  162162. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  162163. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  162164. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  162165. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  162166. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  162167. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  162168. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  162169. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  162170. "Cannot transcode due to multiple use of quantization table %d")
  162171. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  162172. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  162173. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  162174. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  162175. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  162176. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  162177. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  162178. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  162179. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  162180. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  162181. JMESSAGE(JERR_QUANT_COMPONENTS,
  162182. "Cannot quantize more than %d color components")
  162183. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  162184. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  162185. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  162186. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  162187. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  162188. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  162189. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  162190. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  162191. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  162192. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  162193. JMESSAGE(JERR_TFILE_WRITE,
  162194. "Write failed on temporary file --- out of disk space?")
  162195. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  162196. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  162197. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  162198. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  162199. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  162200. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  162201. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  162202. JMESSAGE(JMSG_VERSION, JVERSION)
  162203. JMESSAGE(JTRC_16BIT_TABLES,
  162204. "Caution: quantization tables are too coarse for baseline JPEG")
  162205. JMESSAGE(JTRC_ADOBE,
  162206. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  162207. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  162208. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  162209. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  162210. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  162211. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  162212. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  162213. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  162214. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  162215. JMESSAGE(JTRC_EOI, "End Of Image")
  162216. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  162217. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  162218. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  162219. "Warning: thumbnail image size does not match data length %u")
  162220. JMESSAGE(JTRC_JFIF_EXTENSION,
  162221. "JFIF extension marker: type 0x%02x, length %u")
  162222. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  162223. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  162224. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  162225. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  162226. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  162227. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  162228. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  162229. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  162230. JMESSAGE(JTRC_RST, "RST%d")
  162231. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  162232. "Smoothing not supported with nonstandard sampling ratios")
  162233. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  162234. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  162235. JMESSAGE(JTRC_SOI, "Start of Image")
  162236. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  162237. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  162238. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  162239. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  162240. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  162241. JMESSAGE(JTRC_THUMB_JPEG,
  162242. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  162243. JMESSAGE(JTRC_THUMB_PALETTE,
  162244. "JFIF extension marker: palette thumbnail image, length %u")
  162245. JMESSAGE(JTRC_THUMB_RGB,
  162246. "JFIF extension marker: RGB thumbnail image, length %u")
  162247. JMESSAGE(JTRC_UNKNOWN_IDS,
  162248. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  162249. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  162250. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  162251. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  162252. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  162253. "Inconsistent progression sequence for component %d coefficient %d")
  162254. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  162255. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  162256. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  162257. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  162258. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  162259. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  162260. JMESSAGE(JWRN_MUST_RESYNC,
  162261. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  162262. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  162263. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  162264. #ifdef JMAKE_ENUM_LIST
  162265. JMSG_LASTMSGCODE
  162266. } J_MESSAGE_CODE;
  162267. #undef JMAKE_ENUM_LIST
  162268. #endif /* JMAKE_ENUM_LIST */
  162269. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  162270. #undef JMESSAGE
  162271. #ifndef JERROR_H
  162272. #define JERROR_H
  162273. /* Macros to simplify using the error and trace message stuff */
  162274. /* The first parameter is either type of cinfo pointer */
  162275. /* Fatal errors (print message and exit) */
  162276. #define ERREXIT(cinfo,code) \
  162277. ((cinfo)->err->msg_code = (code), \
  162278. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162279. #define ERREXIT1(cinfo,code,p1) \
  162280. ((cinfo)->err->msg_code = (code), \
  162281. (cinfo)->err->msg_parm.i[0] = (p1), \
  162282. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162283. #define ERREXIT2(cinfo,code,p1,p2) \
  162284. ((cinfo)->err->msg_code = (code), \
  162285. (cinfo)->err->msg_parm.i[0] = (p1), \
  162286. (cinfo)->err->msg_parm.i[1] = (p2), \
  162287. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162288. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  162289. ((cinfo)->err->msg_code = (code), \
  162290. (cinfo)->err->msg_parm.i[0] = (p1), \
  162291. (cinfo)->err->msg_parm.i[1] = (p2), \
  162292. (cinfo)->err->msg_parm.i[2] = (p3), \
  162293. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162294. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  162295. ((cinfo)->err->msg_code = (code), \
  162296. (cinfo)->err->msg_parm.i[0] = (p1), \
  162297. (cinfo)->err->msg_parm.i[1] = (p2), \
  162298. (cinfo)->err->msg_parm.i[2] = (p3), \
  162299. (cinfo)->err->msg_parm.i[3] = (p4), \
  162300. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162301. #define ERREXITS(cinfo,code,str) \
  162302. ((cinfo)->err->msg_code = (code), \
  162303. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  162304. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  162305. #define MAKESTMT(stuff) do { stuff } while (0)
  162306. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  162307. #define WARNMS(cinfo,code) \
  162308. ((cinfo)->err->msg_code = (code), \
  162309. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  162310. #define WARNMS1(cinfo,code,p1) \
  162311. ((cinfo)->err->msg_code = (code), \
  162312. (cinfo)->err->msg_parm.i[0] = (p1), \
  162313. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  162314. #define WARNMS2(cinfo,code,p1,p2) \
  162315. ((cinfo)->err->msg_code = (code), \
  162316. (cinfo)->err->msg_parm.i[0] = (p1), \
  162317. (cinfo)->err->msg_parm.i[1] = (p2), \
  162318. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  162319. /* Informational/debugging messages */
  162320. #define TRACEMS(cinfo,lvl,code) \
  162321. ((cinfo)->err->msg_code = (code), \
  162322. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162323. #define TRACEMS1(cinfo,lvl,code,p1) \
  162324. ((cinfo)->err->msg_code = (code), \
  162325. (cinfo)->err->msg_parm.i[0] = (p1), \
  162326. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162327. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  162328. ((cinfo)->err->msg_code = (code), \
  162329. (cinfo)->err->msg_parm.i[0] = (p1), \
  162330. (cinfo)->err->msg_parm.i[1] = (p2), \
  162331. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162332. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  162333. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162334. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  162335. (cinfo)->err->msg_code = (code); \
  162336. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162337. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  162338. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162339. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  162340. (cinfo)->err->msg_code = (code); \
  162341. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162342. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  162343. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162344. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  162345. _mp[4] = (p5); \
  162346. (cinfo)->err->msg_code = (code); \
  162347. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162348. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  162349. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  162350. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  162351. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  162352. (cinfo)->err->msg_code = (code); \
  162353. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  162354. #define TRACEMSS(cinfo,lvl,code,str) \
  162355. ((cinfo)->err->msg_code = (code), \
  162356. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  162357. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  162358. #endif /* JERROR_H */
  162359. /********* End of inlined file: jerror.h *********/
  162360. /* fetch error codes too */
  162361. #endif
  162362. #endif /* JPEGLIB_H */
  162363. /********* End of inlined file: jpeglib.h *********/
  162364. /********* Start of inlined file: jcapimin.c *********/
  162365. #define JPEG_INTERNALS
  162366. /********* Start of inlined file: jinclude.h *********/
  162367. /* Include auto-config file to find out which system include files we need. */
  162368. #ifndef __jinclude_h__
  162369. #define __jinclude_h__
  162370. /********* Start of inlined file: jconfig.h *********/
  162371. /* see jconfig.doc for explanations */
  162372. // disable all the warnings under MSVC
  162373. #ifdef _MSC_VER
  162374. #pragma warning (disable: 4996 4267 4100 4127 4702 4244)
  162375. #endif
  162376. #ifdef __BORLANDC__
  162377. #pragma warn -8057
  162378. #pragma warn -8019
  162379. #pragma warn -8004
  162380. #pragma warn -8008
  162381. #endif
  162382. #define HAVE_PROTOTYPES
  162383. #define HAVE_UNSIGNED_CHAR
  162384. #define HAVE_UNSIGNED_SHORT
  162385. /* #define void char */
  162386. /* #define const */
  162387. #undef CHAR_IS_UNSIGNED
  162388. #define HAVE_STDDEF_H
  162389. #define HAVE_STDLIB_H
  162390. #undef NEED_BSD_STRINGS
  162391. #undef NEED_SYS_TYPES_H
  162392. #undef NEED_FAR_POINTERS /* we presume a 32-bit flat memory model */
  162393. #undef NEED_SHORT_EXTERNAL_NAMES
  162394. #undef INCOMPLETE_TYPES_BROKEN
  162395. /* Define "boolean" as unsigned char, not int, per Windows custom */
  162396. #ifndef __RPCNDR_H__ /* don't conflict if rpcndr.h already read */
  162397. typedef unsigned char boolean;
  162398. #endif
  162399. #define HAVE_BOOLEAN /* prevent jmorecfg.h from redefining it */
  162400. #ifdef JPEG_INTERNALS
  162401. #undef RIGHT_SHIFT_IS_UNSIGNED
  162402. #endif /* JPEG_INTERNALS */
  162403. #ifdef JPEG_CJPEG_DJPEG
  162404. #define BMP_SUPPORTED /* BMP image file format */
  162405. #define GIF_SUPPORTED /* GIF image file format */
  162406. #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */
  162407. #undef RLE_SUPPORTED /* Utah RLE image file format */
  162408. #define TARGA_SUPPORTED /* Targa image file format */
  162409. #define TWO_FILE_COMMANDLINE /* optional */
  162410. #define USE_SETMODE /* Microsoft has setmode() */
  162411. #undef NEED_SIGNAL_CATCHER
  162412. #undef DONT_USE_B_MODE
  162413. #undef PROGRESS_REPORT /* optional */
  162414. #endif /* JPEG_CJPEG_DJPEG */
  162415. /********* End of inlined file: jconfig.h *********/
  162416. /* auto configuration options */
  162417. #define JCONFIG_INCLUDED /* so that jpeglib.h doesn't do it again */
  162418. /*
  162419. * We need the NULL macro and size_t typedef.
  162420. * On an ANSI-conforming system it is sufficient to include <stddef.h>.
  162421. * Otherwise, we get them from <stdlib.h> or <stdio.h>; we may have to
  162422. * pull in <sys/types.h> as well.
  162423. * Note that the core JPEG library does not require <stdio.h>;
  162424. * only the default error handler and data source/destination modules do.
  162425. * But we must pull it in because of the references to FILE in jpeglib.h.
  162426. * You can remove those references if you want to compile without <stdio.h>.
  162427. */
  162428. #ifdef HAVE_STDDEF_H
  162429. #include <stddef.h>
  162430. #endif
  162431. #ifdef HAVE_STDLIB_H
  162432. #include <stdlib.h>
  162433. #endif
  162434. #ifdef NEED_SYS_TYPES_H
  162435. #include <sys/types.h>
  162436. #endif
  162437. #include <stdio.h>
  162438. /*
  162439. * We need memory copying and zeroing functions, plus strncpy().
  162440. * ANSI and System V implementations declare these in <string.h>.
  162441. * BSD doesn't have the mem() functions, but it does have bcopy()/bzero().
  162442. * Some systems may declare memset and memcpy in <memory.h>.
  162443. *
  162444. * NOTE: we assume the size parameters to these functions are of type size_t.
  162445. * Change the casts in these macros if not!
  162446. */
  162447. #ifdef NEED_BSD_STRINGS
  162448. #include <strings.h>
  162449. #define MEMZERO(target,size) bzero((void *)(target), (size_t)(size))
  162450. #define MEMCOPY(dest,src,size) bcopy((const void *)(src), (void *)(dest), (size_t)(size))
  162451. #else /* not BSD, assume ANSI/SysV string lib */
  162452. #include <string.h>
  162453. #define MEMZERO(target,size) memset((void *)(target), 0, (size_t)(size))
  162454. #define MEMCOPY(dest,src,size) memcpy((void *)(dest), (const void *)(src), (size_t)(size))
  162455. #endif
  162456. /*
  162457. * In ANSI C, and indeed any rational implementation, size_t is also the
  162458. * type returned by sizeof(). However, it seems there are some irrational
  162459. * implementations out there, in which sizeof() returns an int even though
  162460. * size_t is defined as long or unsigned long. To ensure consistent results
  162461. * we always use this SIZEOF() macro in place of using sizeof() directly.
  162462. */
  162463. #define SIZEOF(object) ((size_t) sizeof(object))
  162464. /*
  162465. * The modules that use fread() and fwrite() always invoke them through
  162466. * these macros. On some systems you may need to twiddle the argument casts.
  162467. * CAUTION: argument order is different from underlying functions!
  162468. */
  162469. #define JFREAD(file,buf,sizeofbuf) \
  162470. ((size_t) fread((void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  162471. #define JFWRITE(file,buf,sizeofbuf) \
  162472. ((size_t) fwrite((const void *) (buf), (size_t) 1, (size_t) (sizeofbuf), (file)))
  162473. typedef enum { /* JPEG marker codes */
  162474. M_SOF0 = 0xc0,
  162475. M_SOF1 = 0xc1,
  162476. M_SOF2 = 0xc2,
  162477. M_SOF3 = 0xc3,
  162478. M_SOF5 = 0xc5,
  162479. M_SOF6 = 0xc6,
  162480. M_SOF7 = 0xc7,
  162481. M_JPG = 0xc8,
  162482. M_SOF9 = 0xc9,
  162483. M_SOF10 = 0xca,
  162484. M_SOF11 = 0xcb,
  162485. M_SOF13 = 0xcd,
  162486. M_SOF14 = 0xce,
  162487. M_SOF15 = 0xcf,
  162488. M_DHT = 0xc4,
  162489. M_DAC = 0xcc,
  162490. M_RST0 = 0xd0,
  162491. M_RST1 = 0xd1,
  162492. M_RST2 = 0xd2,
  162493. M_RST3 = 0xd3,
  162494. M_RST4 = 0xd4,
  162495. M_RST5 = 0xd5,
  162496. M_RST6 = 0xd6,
  162497. M_RST7 = 0xd7,
  162498. M_SOI = 0xd8,
  162499. M_EOI = 0xd9,
  162500. M_SOS = 0xda,
  162501. M_DQT = 0xdb,
  162502. M_DNL = 0xdc,
  162503. M_DRI = 0xdd,
  162504. M_DHP = 0xde,
  162505. M_EXP = 0xdf,
  162506. M_APP0 = 0xe0,
  162507. M_APP1 = 0xe1,
  162508. M_APP2 = 0xe2,
  162509. M_APP3 = 0xe3,
  162510. M_APP4 = 0xe4,
  162511. M_APP5 = 0xe5,
  162512. M_APP6 = 0xe6,
  162513. M_APP7 = 0xe7,
  162514. M_APP8 = 0xe8,
  162515. M_APP9 = 0xe9,
  162516. M_APP10 = 0xea,
  162517. M_APP11 = 0xeb,
  162518. M_APP12 = 0xec,
  162519. M_APP13 = 0xed,
  162520. M_APP14 = 0xee,
  162521. M_APP15 = 0xef,
  162522. M_JPG0 = 0xf0,
  162523. M_JPG13 = 0xfd,
  162524. M_COM = 0xfe,
  162525. M_TEM = 0x01,
  162526. M_ERROR = 0x100
  162527. } JPEG_MARKER;
  162528. /*
  162529. * Figure F.12: extend sign bit.
  162530. * On some machines, a shift and add will be faster than a table lookup.
  162531. */
  162532. #ifdef AVOID_TABLES
  162533. #define HUFF_EXTEND(x,s) ((x) < (1<<((s)-1)) ? (x) + (((-1)<<(s)) + 1) : (x))
  162534. #else
  162535. #define HUFF_EXTEND(x,s) ((x) < extend_test[s] ? (x) + extend_offset[s] : (x))
  162536. static const int extend_test[16] = /* entry n is 2**(n-1) */
  162537. { 0, 0x0001, 0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080,
  162538. 0x0100, 0x0200, 0x0400, 0x0800, 0x1000, 0x2000, 0x4000 };
  162539. static const int extend_offset[16] = /* entry n is (-1 << n) + 1 */
  162540. { 0, ((-1)<<1) + 1, ((-1)<<2) + 1, ((-1)<<3) + 1, ((-1)<<4) + 1,
  162541. ((-1)<<5) + 1, ((-1)<<6) + 1, ((-1)<<7) + 1, ((-1)<<8) + 1,
  162542. ((-1)<<9) + 1, ((-1)<<10) + 1, ((-1)<<11) + 1, ((-1)<<12) + 1,
  162543. ((-1)<<13) + 1, ((-1)<<14) + 1, ((-1)<<15) + 1 };
  162544. #endif /* AVOID_TABLES */
  162545. #endif
  162546. /********* End of inlined file: jinclude.h *********/
  162547. /*
  162548. * Initialization of a JPEG compression object.
  162549. * The error manager must already be set up (in case memory manager fails).
  162550. */
  162551. GLOBAL(void)
  162552. jpeg_CreateCompress (j_compress_ptr cinfo, int version, size_t structsize)
  162553. {
  162554. int i;
  162555. /* Guard against version mismatches between library and caller. */
  162556. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  162557. if (version != JPEG_LIB_VERSION)
  162558. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  162559. if (structsize != SIZEOF(struct jpeg_compress_struct))
  162560. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  162561. (int) SIZEOF(struct jpeg_compress_struct), (int) structsize);
  162562. /* For debugging purposes, we zero the whole master structure.
  162563. * But the application has already set the err pointer, and may have set
  162564. * client_data, so we have to save and restore those fields.
  162565. * Note: if application hasn't set client_data, tools like Purify may
  162566. * complain here.
  162567. */
  162568. {
  162569. struct jpeg_error_mgr * err = cinfo->err;
  162570. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  162571. MEMZERO(cinfo, SIZEOF(struct jpeg_compress_struct));
  162572. cinfo->err = err;
  162573. cinfo->client_data = client_data;
  162574. }
  162575. cinfo->is_decompressor = FALSE;
  162576. /* Initialize a memory manager instance for this object */
  162577. jinit_memory_mgr((j_common_ptr) cinfo);
  162578. /* Zero out pointers to permanent structures. */
  162579. cinfo->progress = NULL;
  162580. cinfo->dest = NULL;
  162581. cinfo->comp_info = NULL;
  162582. for (i = 0; i < NUM_QUANT_TBLS; i++)
  162583. cinfo->quant_tbl_ptrs[i] = NULL;
  162584. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  162585. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  162586. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  162587. }
  162588. cinfo->script_space = NULL;
  162589. cinfo->input_gamma = 1.0; /* in case application forgets */
  162590. /* OK, I'm ready */
  162591. cinfo->global_state = CSTATE_START;
  162592. }
  162593. /*
  162594. * Destruction of a JPEG compression object
  162595. */
  162596. GLOBAL(void)
  162597. jpeg_destroy_compress (j_compress_ptr cinfo)
  162598. {
  162599. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  162600. }
  162601. /*
  162602. * Abort processing of a JPEG compression operation,
  162603. * but don't destroy the object itself.
  162604. */
  162605. GLOBAL(void)
  162606. jpeg_abort_compress (j_compress_ptr cinfo)
  162607. {
  162608. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  162609. }
  162610. /*
  162611. * Forcibly suppress or un-suppress all quantization and Huffman tables.
  162612. * Marks all currently defined tables as already written (if suppress)
  162613. * or not written (if !suppress). This will control whether they get emitted
  162614. * by a subsequent jpeg_start_compress call.
  162615. *
  162616. * This routine is exported for use by applications that want to produce
  162617. * abbreviated JPEG datastreams. It logically belongs in jcparam.c, but
  162618. * since it is called by jpeg_start_compress, we put it here --- otherwise
  162619. * jcparam.o would be linked whether the application used it or not.
  162620. */
  162621. GLOBAL(void)
  162622. jpeg_suppress_tables (j_compress_ptr cinfo, boolean suppress)
  162623. {
  162624. int i;
  162625. JQUANT_TBL * qtbl;
  162626. JHUFF_TBL * htbl;
  162627. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  162628. if ((qtbl = cinfo->quant_tbl_ptrs[i]) != NULL)
  162629. qtbl->sent_table = suppress;
  162630. }
  162631. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  162632. if ((htbl = cinfo->dc_huff_tbl_ptrs[i]) != NULL)
  162633. htbl->sent_table = suppress;
  162634. if ((htbl = cinfo->ac_huff_tbl_ptrs[i]) != NULL)
  162635. htbl->sent_table = suppress;
  162636. }
  162637. }
  162638. /*
  162639. * Finish JPEG compression.
  162640. *
  162641. * If a multipass operating mode was selected, this may do a great deal of
  162642. * work including most of the actual output.
  162643. */
  162644. GLOBAL(void)
  162645. jpeg_finish_compress (j_compress_ptr cinfo)
  162646. {
  162647. JDIMENSION iMCU_row;
  162648. if (cinfo->global_state == CSTATE_SCANNING ||
  162649. cinfo->global_state == CSTATE_RAW_OK) {
  162650. /* Terminate first pass */
  162651. if (cinfo->next_scanline < cinfo->image_height)
  162652. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  162653. (*cinfo->master->finish_pass) (cinfo);
  162654. } else if (cinfo->global_state != CSTATE_WRCOEFS)
  162655. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162656. /* Perform any remaining passes */
  162657. while (! cinfo->master->is_last_pass) {
  162658. (*cinfo->master->prepare_for_pass) (cinfo);
  162659. for (iMCU_row = 0; iMCU_row < cinfo->total_iMCU_rows; iMCU_row++) {
  162660. if (cinfo->progress != NULL) {
  162661. cinfo->progress->pass_counter = (long) iMCU_row;
  162662. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows;
  162663. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162664. }
  162665. /* We bypass the main controller and invoke coef controller directly;
  162666. * all work is being done from the coefficient buffer.
  162667. */
  162668. if (! (*cinfo->coef->compress_data) (cinfo, (JSAMPIMAGE) NULL))
  162669. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  162670. }
  162671. (*cinfo->master->finish_pass) (cinfo);
  162672. }
  162673. /* Write EOI, do final cleanup */
  162674. (*cinfo->marker->write_file_trailer) (cinfo);
  162675. (*cinfo->dest->term_destination) (cinfo);
  162676. /* We can use jpeg_abort to release memory and reset global_state */
  162677. jpeg_abort((j_common_ptr) cinfo);
  162678. }
  162679. /*
  162680. * Write a special marker.
  162681. * This is only recommended for writing COM or APPn markers.
  162682. * Must be called after jpeg_start_compress() and before
  162683. * first call to jpeg_write_scanlines() or jpeg_write_raw_data().
  162684. */
  162685. GLOBAL(void)
  162686. jpeg_write_marker (j_compress_ptr cinfo, int marker,
  162687. const JOCTET *dataptr, unsigned int datalen)
  162688. {
  162689. JMETHOD(void, write_marker_byte, (j_compress_ptr info, int val));
  162690. if (cinfo->next_scanline != 0 ||
  162691. (cinfo->global_state != CSTATE_SCANNING &&
  162692. cinfo->global_state != CSTATE_RAW_OK &&
  162693. cinfo->global_state != CSTATE_WRCOEFS))
  162694. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162695. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  162696. write_marker_byte = cinfo->marker->write_marker_byte; /* copy for speed */
  162697. while (datalen--) {
  162698. (*write_marker_byte) (cinfo, *dataptr);
  162699. dataptr++;
  162700. }
  162701. }
  162702. /* Same, but piecemeal. */
  162703. GLOBAL(void)
  162704. jpeg_write_m_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  162705. {
  162706. if (cinfo->next_scanline != 0 ||
  162707. (cinfo->global_state != CSTATE_SCANNING &&
  162708. cinfo->global_state != CSTATE_RAW_OK &&
  162709. cinfo->global_state != CSTATE_WRCOEFS))
  162710. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162711. (*cinfo->marker->write_marker_header) (cinfo, marker, datalen);
  162712. }
  162713. GLOBAL(void)
  162714. jpeg_write_m_byte (j_compress_ptr cinfo, int val)
  162715. {
  162716. (*cinfo->marker->write_marker_byte) (cinfo, val);
  162717. }
  162718. /*
  162719. * Alternate compression function: just write an abbreviated table file.
  162720. * Before calling this, all parameters and a data destination must be set up.
  162721. *
  162722. * To produce a pair of files containing abbreviated tables and abbreviated
  162723. * image data, one would proceed as follows:
  162724. *
  162725. * initialize JPEG object
  162726. * set JPEG parameters
  162727. * set destination to table file
  162728. * jpeg_write_tables(cinfo);
  162729. * set destination to image file
  162730. * jpeg_start_compress(cinfo, FALSE);
  162731. * write data...
  162732. * jpeg_finish_compress(cinfo);
  162733. *
  162734. * jpeg_write_tables has the side effect of marking all tables written
  162735. * (same as jpeg_suppress_tables(..., TRUE)). Thus a subsequent start_compress
  162736. * will not re-emit the tables unless it is passed write_all_tables=TRUE.
  162737. */
  162738. GLOBAL(void)
  162739. jpeg_write_tables (j_compress_ptr cinfo)
  162740. {
  162741. if (cinfo->global_state != CSTATE_START)
  162742. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162743. /* (Re)initialize error mgr and destination modules */
  162744. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  162745. (*cinfo->dest->init_destination) (cinfo);
  162746. /* Initialize the marker writer ... bit of a crock to do it here. */
  162747. jinit_marker_writer(cinfo);
  162748. /* Write them tables! */
  162749. (*cinfo->marker->write_tables_only) (cinfo);
  162750. /* And clean up. */
  162751. (*cinfo->dest->term_destination) (cinfo);
  162752. /*
  162753. * In library releases up through v6a, we called jpeg_abort() here to free
  162754. * any working memory allocated by the destination manager and marker
  162755. * writer. Some applications had a problem with that: they allocated space
  162756. * of their own from the library memory manager, and didn't want it to go
  162757. * away during write_tables. So now we do nothing. This will cause a
  162758. * memory leak if an app calls write_tables repeatedly without doing a full
  162759. * compression cycle or otherwise resetting the JPEG object. However, that
  162760. * seems less bad than unexpectedly freeing memory in the normal case.
  162761. * An app that prefers the old behavior can call jpeg_abort for itself after
  162762. * each call to jpeg_write_tables().
  162763. */
  162764. }
  162765. /********* End of inlined file: jcapimin.c *********/
  162766. /********* Start of inlined file: jcapistd.c *********/
  162767. #define JPEG_INTERNALS
  162768. /*
  162769. * Compression initialization.
  162770. * Before calling this, all parameters and a data destination must be set up.
  162771. *
  162772. * We require a write_all_tables parameter as a failsafe check when writing
  162773. * multiple datastreams from the same compression object. Since prior runs
  162774. * will have left all the tables marked sent_table=TRUE, a subsequent run
  162775. * would emit an abbreviated stream (no tables) by default. This may be what
  162776. * is wanted, but for safety's sake it should not be the default behavior:
  162777. * programmers should have to make a deliberate choice to emit abbreviated
  162778. * images. Therefore the documentation and examples should encourage people
  162779. * to pass write_all_tables=TRUE; then it will take active thought to do the
  162780. * wrong thing.
  162781. */
  162782. GLOBAL(void)
  162783. jpeg_start_compress (j_compress_ptr cinfo, boolean write_all_tables)
  162784. {
  162785. if (cinfo->global_state != CSTATE_START)
  162786. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162787. if (write_all_tables)
  162788. jpeg_suppress_tables(cinfo, FALSE); /* mark all tables to be written */
  162789. /* (Re)initialize error mgr and destination modules */
  162790. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  162791. (*cinfo->dest->init_destination) (cinfo);
  162792. /* Perform master selection of active modules */
  162793. jinit_compress_master(cinfo);
  162794. /* Set up for the first pass */
  162795. (*cinfo->master->prepare_for_pass) (cinfo);
  162796. /* Ready for application to drive first pass through jpeg_write_scanlines
  162797. * or jpeg_write_raw_data.
  162798. */
  162799. cinfo->next_scanline = 0;
  162800. cinfo->global_state = (cinfo->raw_data_in ? CSTATE_RAW_OK : CSTATE_SCANNING);
  162801. }
  162802. /*
  162803. * Write some scanlines of data to the JPEG compressor.
  162804. *
  162805. * The return value will be the number of lines actually written.
  162806. * This should be less than the supplied num_lines only in case that
  162807. * the data destination module has requested suspension of the compressor,
  162808. * or if more than image_height scanlines are passed in.
  162809. *
  162810. * Note: we warn about excess calls to jpeg_write_scanlines() since
  162811. * this likely signals an application programmer error. However,
  162812. * excess scanlines passed in the last valid call are *silently* ignored,
  162813. * so that the application need not adjust num_lines for end-of-image
  162814. * when using a multiple-scanline buffer.
  162815. */
  162816. GLOBAL(JDIMENSION)
  162817. jpeg_write_scanlines (j_compress_ptr cinfo, JSAMPARRAY scanlines,
  162818. JDIMENSION num_lines)
  162819. {
  162820. JDIMENSION row_ctr, rows_left;
  162821. if (cinfo->global_state != CSTATE_SCANNING)
  162822. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162823. if (cinfo->next_scanline >= cinfo->image_height)
  162824. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162825. /* Call progress monitor hook if present */
  162826. if (cinfo->progress != NULL) {
  162827. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162828. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162829. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162830. }
  162831. /* Give master control module another chance if this is first call to
  162832. * jpeg_write_scanlines. This lets output of the frame/scan headers be
  162833. * delayed so that application can write COM, etc, markers between
  162834. * jpeg_start_compress and jpeg_write_scanlines.
  162835. */
  162836. if (cinfo->master->call_pass_startup)
  162837. (*cinfo->master->pass_startup) (cinfo);
  162838. /* Ignore any extra scanlines at bottom of image. */
  162839. rows_left = cinfo->image_height - cinfo->next_scanline;
  162840. if (num_lines > rows_left)
  162841. num_lines = rows_left;
  162842. row_ctr = 0;
  162843. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, num_lines);
  162844. cinfo->next_scanline += row_ctr;
  162845. return row_ctr;
  162846. }
  162847. /*
  162848. * Alternate entry point to write raw data.
  162849. * Processes exactly one iMCU row per call, unless suspended.
  162850. */
  162851. GLOBAL(JDIMENSION)
  162852. jpeg_write_raw_data (j_compress_ptr cinfo, JSAMPIMAGE data,
  162853. JDIMENSION num_lines)
  162854. {
  162855. JDIMENSION lines_per_iMCU_row;
  162856. if (cinfo->global_state != CSTATE_RAW_OK)
  162857. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  162858. if (cinfo->next_scanline >= cinfo->image_height) {
  162859. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  162860. return 0;
  162861. }
  162862. /* Call progress monitor hook if present */
  162863. if (cinfo->progress != NULL) {
  162864. cinfo->progress->pass_counter = (long) cinfo->next_scanline;
  162865. cinfo->progress->pass_limit = (long) cinfo->image_height;
  162866. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  162867. }
  162868. /* Give master control module another chance if this is first call to
  162869. * jpeg_write_raw_data. This lets output of the frame/scan headers be
  162870. * delayed so that application can write COM, etc, markers between
  162871. * jpeg_start_compress and jpeg_write_raw_data.
  162872. */
  162873. if (cinfo->master->call_pass_startup)
  162874. (*cinfo->master->pass_startup) (cinfo);
  162875. /* Verify that at least one iMCU row has been passed. */
  162876. lines_per_iMCU_row = cinfo->max_v_samp_factor * DCTSIZE;
  162877. if (num_lines < lines_per_iMCU_row)
  162878. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  162879. /* Directly compress the row. */
  162880. if (! (*cinfo->coef->compress_data) (cinfo, data)) {
  162881. /* If compressor did not consume the whole row, suspend processing. */
  162882. return 0;
  162883. }
  162884. /* OK, we processed one iMCU row. */
  162885. cinfo->next_scanline += lines_per_iMCU_row;
  162886. return lines_per_iMCU_row;
  162887. }
  162888. /********* End of inlined file: jcapistd.c *********/
  162889. /********* Start of inlined file: jccoefct.c *********/
  162890. #define JPEG_INTERNALS
  162891. /* We use a full-image coefficient buffer when doing Huffman optimization,
  162892. * and also for writing multiple-scan JPEG files. In all cases, the DCT
  162893. * step is run during the first pass, and subsequent passes need only read
  162894. * the buffered coefficients.
  162895. */
  162896. #ifdef ENTROPY_OPT_SUPPORTED
  162897. #define FULL_COEF_BUFFER_SUPPORTED
  162898. #else
  162899. #ifdef C_MULTISCAN_FILES_SUPPORTED
  162900. #define FULL_COEF_BUFFER_SUPPORTED
  162901. #endif
  162902. #endif
  162903. /* Private buffer controller object */
  162904. typedef struct {
  162905. struct jpeg_c_coef_controller pub; /* public fields */
  162906. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  162907. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  162908. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  162909. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  162910. /* For single-pass compression, it's sufficient to buffer just one MCU
  162911. * (although this may prove a bit slow in practice). We allocate a
  162912. * workspace of C_MAX_BLOCKS_IN_MCU coefficient blocks, and reuse it for each
  162913. * MCU constructed and sent. (On 80x86, the workspace is FAR even though
  162914. * it's not really very big; this is to keep the module interfaces unchanged
  162915. * when a large coefficient buffer is necessary.)
  162916. * In multi-pass modes, this array points to the current MCU's blocks
  162917. * within the virtual arrays.
  162918. */
  162919. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  162920. /* In multi-pass modes, we need a virtual block array for each component. */
  162921. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  162922. } my_coef_controller;
  162923. typedef my_coef_controller * my_coef_ptr;
  162924. /* Forward declarations */
  162925. METHODDEF(boolean) compress_data
  162926. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162927. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162928. METHODDEF(boolean) compress_first_pass
  162929. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162930. METHODDEF(boolean) compress_output
  162931. JPP((j_compress_ptr cinfo, JSAMPIMAGE input_buf));
  162932. #endif
  162933. LOCAL(void)
  162934. start_iMCU_row (j_compress_ptr cinfo)
  162935. /* Reset within-iMCU-row counters for a new row */
  162936. {
  162937. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162938. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  162939. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  162940. * But at the bottom of the image, process only what's left.
  162941. */
  162942. if (cinfo->comps_in_scan > 1) {
  162943. coef->MCU_rows_per_iMCU_row = 1;
  162944. } else {
  162945. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  162946. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  162947. else
  162948. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  162949. }
  162950. coef->mcu_ctr = 0;
  162951. coef->MCU_vert_offset = 0;
  162952. }
  162953. /*
  162954. * Initialize for a processing pass.
  162955. */
  162956. METHODDEF(void)
  162957. start_pass_coef (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  162958. {
  162959. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162960. coef->iMCU_row_num = 0;
  162961. start_iMCU_row(cinfo);
  162962. switch (pass_mode) {
  162963. case JBUF_PASS_THRU:
  162964. if (coef->whole_image[0] != NULL)
  162965. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162966. coef->pub.compress_data = compress_data;
  162967. break;
  162968. #ifdef FULL_COEF_BUFFER_SUPPORTED
  162969. case JBUF_SAVE_AND_PASS:
  162970. if (coef->whole_image[0] == NULL)
  162971. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162972. coef->pub.compress_data = compress_first_pass;
  162973. break;
  162974. case JBUF_CRANK_DEST:
  162975. if (coef->whole_image[0] == NULL)
  162976. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162977. coef->pub.compress_data = compress_output;
  162978. break;
  162979. #endif
  162980. default:
  162981. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  162982. break;
  162983. }
  162984. }
  162985. /*
  162986. * Process some data in the single-pass case.
  162987. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  162988. * per call, ie, v_samp_factor block rows for each component in the image.
  162989. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  162990. *
  162991. * NB: input_buf contains a plane for each component in image,
  162992. * which we index according to the component's SOF position.
  162993. */
  162994. METHODDEF(boolean)
  162995. compress_data (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  162996. {
  162997. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  162998. JDIMENSION MCU_col_num; /* index of current MCU within row */
  162999. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  163000. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  163001. int blkn, bi, ci, yindex, yoffset, blockcnt;
  163002. JDIMENSION ypos, xpos;
  163003. jpeg_component_info *compptr;
  163004. /* Loop to write as much as one whole iMCU row */
  163005. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  163006. yoffset++) {
  163007. for (MCU_col_num = coef->mcu_ctr; MCU_col_num <= last_MCU_col;
  163008. MCU_col_num++) {
  163009. /* Determine where data comes from in input_buf and do the DCT thing.
  163010. * Each call on forward_DCT processes a horizontal row of DCT blocks
  163011. * as wide as an MCU; we rely on having allocated the MCU_buffer[] blocks
  163012. * sequentially. Dummy blocks at the right or bottom edge are filled in
  163013. * specially. The data in them does not matter for image reconstruction,
  163014. * so we fill them with values that will encode to the smallest amount of
  163015. * data, viz: all zeroes in the AC entries, DC entries equal to previous
  163016. * block's DC value. (Thanks to Thomas Kinsman for this idea.)
  163017. */
  163018. blkn = 0;
  163019. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163020. compptr = cinfo->cur_comp_info[ci];
  163021. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  163022. : compptr->last_col_width;
  163023. xpos = MCU_col_num * compptr->MCU_sample_width;
  163024. ypos = yoffset * DCTSIZE; /* ypos == (yoffset+yindex) * DCTSIZE */
  163025. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  163026. if (coef->iMCU_row_num < last_iMCU_row ||
  163027. yoffset+yindex < compptr->last_row_height) {
  163028. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  163029. input_buf[compptr->component_index],
  163030. coef->MCU_buffer[blkn],
  163031. ypos, xpos, (JDIMENSION) blockcnt);
  163032. if (blockcnt < compptr->MCU_width) {
  163033. /* Create some dummy blocks at the right edge of the image. */
  163034. jzero_far((void FAR *) coef->MCU_buffer[blkn + blockcnt],
  163035. (compptr->MCU_width - blockcnt) * SIZEOF(JBLOCK));
  163036. for (bi = blockcnt; bi < compptr->MCU_width; bi++) {
  163037. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn+bi-1][0][0];
  163038. }
  163039. }
  163040. } else {
  163041. /* Create a row of dummy blocks at the bottom of the image. */
  163042. jzero_far((void FAR *) coef->MCU_buffer[blkn],
  163043. compptr->MCU_width * SIZEOF(JBLOCK));
  163044. for (bi = 0; bi < compptr->MCU_width; bi++) {
  163045. coef->MCU_buffer[blkn+bi][0][0] = coef->MCU_buffer[blkn-1][0][0];
  163046. }
  163047. }
  163048. blkn += compptr->MCU_width;
  163049. ypos += DCTSIZE;
  163050. }
  163051. }
  163052. /* Try to write the MCU. In event of a suspension failure, we will
  163053. * re-DCT the MCU on restart (a bit inefficient, could be fixed...)
  163054. */
  163055. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  163056. /* Suspension forced; update state counters and exit */
  163057. coef->MCU_vert_offset = yoffset;
  163058. coef->mcu_ctr = MCU_col_num;
  163059. return FALSE;
  163060. }
  163061. }
  163062. /* Completed an MCU row, but perhaps not an iMCU row */
  163063. coef->mcu_ctr = 0;
  163064. }
  163065. /* Completed the iMCU row, advance counters for next one */
  163066. coef->iMCU_row_num++;
  163067. start_iMCU_row(cinfo);
  163068. return TRUE;
  163069. }
  163070. #ifdef FULL_COEF_BUFFER_SUPPORTED
  163071. /*
  163072. * Process some data in the first pass of a multi-pass case.
  163073. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  163074. * per call, ie, v_samp_factor block rows for each component in the image.
  163075. * This amount of data is read from the source buffer, DCT'd and quantized,
  163076. * and saved into the virtual arrays. We also generate suitable dummy blocks
  163077. * as needed at the right and lower edges. (The dummy blocks are constructed
  163078. * in the virtual arrays, which have been padded appropriately.) This makes
  163079. * it possible for subsequent passes not to worry about real vs. dummy blocks.
  163080. *
  163081. * We must also emit the data to the entropy encoder. This is conveniently
  163082. * done by calling compress_output() after we've loaded the current strip
  163083. * of the virtual arrays.
  163084. *
  163085. * NB: input_buf contains a plane for each component in image. All
  163086. * components are DCT'd and loaded into the virtual arrays in this pass.
  163087. * However, it may be that only a subset of the components are emitted to
  163088. * the entropy encoder during this first pass; be careful about looking
  163089. * at the scan-dependent variables (MCU dimensions, etc).
  163090. */
  163091. METHODDEF(boolean)
  163092. compress_first_pass (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  163093. {
  163094. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  163095. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  163096. JDIMENSION blocks_across, MCUs_across, MCUindex;
  163097. int bi, ci, h_samp_factor, block_row, block_rows, ndummy;
  163098. JCOEF lastDC;
  163099. jpeg_component_info *compptr;
  163100. JBLOCKARRAY buffer;
  163101. JBLOCKROW thisblockrow, lastblockrow;
  163102. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163103. ci++, compptr++) {
  163104. /* Align the virtual buffer for this component. */
  163105. buffer = (*cinfo->mem->access_virt_barray)
  163106. ((j_common_ptr) cinfo, coef->whole_image[ci],
  163107. coef->iMCU_row_num * compptr->v_samp_factor,
  163108. (JDIMENSION) compptr->v_samp_factor, TRUE);
  163109. /* Count non-dummy DCT block rows in this iMCU row. */
  163110. if (coef->iMCU_row_num < last_iMCU_row)
  163111. block_rows = compptr->v_samp_factor;
  163112. else {
  163113. /* NB: can't use last_row_height here, since may not be set! */
  163114. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  163115. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  163116. }
  163117. blocks_across = compptr->width_in_blocks;
  163118. h_samp_factor = compptr->h_samp_factor;
  163119. /* Count number of dummy blocks to be added at the right margin. */
  163120. ndummy = (int) (blocks_across % h_samp_factor);
  163121. if (ndummy > 0)
  163122. ndummy = h_samp_factor - ndummy;
  163123. /* Perform DCT for all non-dummy blocks in this iMCU row. Each call
  163124. * on forward_DCT processes a complete horizontal row of DCT blocks.
  163125. */
  163126. for (block_row = 0; block_row < block_rows; block_row++) {
  163127. thisblockrow = buffer[block_row];
  163128. (*cinfo->fdct->forward_DCT) (cinfo, compptr,
  163129. input_buf[ci], thisblockrow,
  163130. (JDIMENSION) (block_row * DCTSIZE),
  163131. (JDIMENSION) 0, blocks_across);
  163132. if (ndummy > 0) {
  163133. /* Create dummy blocks at the right edge of the image. */
  163134. thisblockrow += blocks_across; /* => first dummy block */
  163135. jzero_far((void FAR *) thisblockrow, ndummy * SIZEOF(JBLOCK));
  163136. lastDC = thisblockrow[-1][0];
  163137. for (bi = 0; bi < ndummy; bi++) {
  163138. thisblockrow[bi][0] = lastDC;
  163139. }
  163140. }
  163141. }
  163142. /* If at end of image, create dummy block rows as needed.
  163143. * The tricky part here is that within each MCU, we want the DC values
  163144. * of the dummy blocks to match the last real block's DC value.
  163145. * This squeezes a few more bytes out of the resulting file...
  163146. */
  163147. if (coef->iMCU_row_num == last_iMCU_row) {
  163148. blocks_across += ndummy; /* include lower right corner */
  163149. MCUs_across = blocks_across / h_samp_factor;
  163150. for (block_row = block_rows; block_row < compptr->v_samp_factor;
  163151. block_row++) {
  163152. thisblockrow = buffer[block_row];
  163153. lastblockrow = buffer[block_row-1];
  163154. jzero_far((void FAR *) thisblockrow,
  163155. (size_t) (blocks_across * SIZEOF(JBLOCK)));
  163156. for (MCUindex = 0; MCUindex < MCUs_across; MCUindex++) {
  163157. lastDC = lastblockrow[h_samp_factor-1][0];
  163158. for (bi = 0; bi < h_samp_factor; bi++) {
  163159. thisblockrow[bi][0] = lastDC;
  163160. }
  163161. thisblockrow += h_samp_factor; /* advance to next MCU in row */
  163162. lastblockrow += h_samp_factor;
  163163. }
  163164. }
  163165. }
  163166. }
  163167. /* NB: compress_output will increment iMCU_row_num if successful.
  163168. * A suspension return will result in redoing all the work above next time.
  163169. */
  163170. /* Emit data to the entropy encoder, sharing code with subsequent passes */
  163171. return compress_output(cinfo, input_buf);
  163172. }
  163173. /*
  163174. * Process some data in subsequent passes of a multi-pass case.
  163175. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  163176. * per call, ie, v_samp_factor block rows for each component in the scan.
  163177. * The data is obtained from the virtual arrays and fed to the entropy coder.
  163178. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  163179. *
  163180. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  163181. */
  163182. METHODDEF(boolean)
  163183. compress_output (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  163184. {
  163185. my_coef_ptr coef = (my_coef_ptr) cinfo->coef;
  163186. JDIMENSION MCU_col_num; /* index of current MCU within row */
  163187. int blkn, ci, xindex, yindex, yoffset;
  163188. JDIMENSION start_col;
  163189. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  163190. JBLOCKROW buffer_ptr;
  163191. jpeg_component_info *compptr;
  163192. /* Align the virtual buffers for the components used in this scan.
  163193. * NB: during first pass, this is safe only because the buffers will
  163194. * already be aligned properly, so jmemmgr.c won't need to do any I/O.
  163195. */
  163196. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163197. compptr = cinfo->cur_comp_info[ci];
  163198. buffer[ci] = (*cinfo->mem->access_virt_barray)
  163199. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  163200. coef->iMCU_row_num * compptr->v_samp_factor,
  163201. (JDIMENSION) compptr->v_samp_factor, FALSE);
  163202. }
  163203. /* Loop to process one whole iMCU row */
  163204. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  163205. yoffset++) {
  163206. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  163207. MCU_col_num++) {
  163208. /* Construct list of pointers to DCT blocks belonging to this MCU */
  163209. blkn = 0; /* index of current DCT block within MCU */
  163210. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  163211. compptr = cinfo->cur_comp_info[ci];
  163212. start_col = MCU_col_num * compptr->MCU_width;
  163213. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  163214. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  163215. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  163216. coef->MCU_buffer[blkn++] = buffer_ptr++;
  163217. }
  163218. }
  163219. }
  163220. /* Try to write the MCU. */
  163221. if (! (*cinfo->entropy->encode_mcu) (cinfo, coef->MCU_buffer)) {
  163222. /* Suspension forced; update state counters and exit */
  163223. coef->MCU_vert_offset = yoffset;
  163224. coef->mcu_ctr = MCU_col_num;
  163225. return FALSE;
  163226. }
  163227. }
  163228. /* Completed an MCU row, but perhaps not an iMCU row */
  163229. coef->mcu_ctr = 0;
  163230. }
  163231. /* Completed the iMCU row, advance counters for next one */
  163232. coef->iMCU_row_num++;
  163233. start_iMCU_row(cinfo);
  163234. return TRUE;
  163235. }
  163236. #endif /* FULL_COEF_BUFFER_SUPPORTED */
  163237. /*
  163238. * Initialize coefficient buffer controller.
  163239. */
  163240. GLOBAL(void)
  163241. jinit_c_coef_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  163242. {
  163243. my_coef_ptr coef;
  163244. coef = (my_coef_ptr)
  163245. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163246. SIZEOF(my_coef_controller));
  163247. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  163248. coef->pub.start_pass = start_pass_coef;
  163249. /* Create the coefficient buffer. */
  163250. if (need_full_buffer) {
  163251. #ifdef FULL_COEF_BUFFER_SUPPORTED
  163252. /* Allocate a full-image virtual array for each component, */
  163253. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  163254. int ci;
  163255. jpeg_component_info *compptr;
  163256. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163257. ci++, compptr++) {
  163258. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  163259. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  163260. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  163261. (long) compptr->h_samp_factor),
  163262. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  163263. (long) compptr->v_samp_factor),
  163264. (JDIMENSION) compptr->v_samp_factor);
  163265. }
  163266. #else
  163267. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  163268. #endif
  163269. } else {
  163270. /* We only need a single-MCU buffer. */
  163271. JBLOCKROW buffer;
  163272. int i;
  163273. buffer = (JBLOCKROW)
  163274. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163275. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  163276. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  163277. coef->MCU_buffer[i] = buffer + i;
  163278. }
  163279. coef->whole_image[0] = NULL; /* flag for no virtual arrays */
  163280. }
  163281. }
  163282. /********* End of inlined file: jccoefct.c *********/
  163283. /********* Start of inlined file: jccolor.c *********/
  163284. #define JPEG_INTERNALS
  163285. /* Private subobject */
  163286. typedef struct {
  163287. struct jpeg_color_converter pub; /* public fields */
  163288. /* Private state for RGB->YCC conversion */
  163289. INT32 * rgb_ycc_tab; /* => table for RGB to YCbCr conversion */
  163290. } my_color_converter;
  163291. typedef my_color_converter * my_cconvert_ptr;
  163292. /**************** RGB -> YCbCr conversion: most common case **************/
  163293. /*
  163294. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  163295. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  163296. * The conversion equations to be implemented are therefore
  163297. * Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
  163298. * Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
  163299. * Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
  163300. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  163301. * Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
  163302. * rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
  163303. * negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
  163304. * were not represented exactly. Now we sacrifice exact representation of
  163305. * maximum red and maximum blue in order to get exact grayscales.
  163306. *
  163307. * To avoid floating-point arithmetic, we represent the fractional constants
  163308. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  163309. * the products by 2^16, with appropriate rounding, to get the correct answer.
  163310. *
  163311. * For even more speed, we avoid doing any multiplications in the inner loop
  163312. * by precalculating the constants times R,G,B for all possible values.
  163313. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  163314. * for 12-bit samples it is still acceptable. It's not very reasonable for
  163315. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  163316. * colorspace anyway.
  163317. * The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
  163318. * in the tables to save adding them separately in the inner loop.
  163319. */
  163320. #define SCALEBITS 16 /* speediest right-shift on some machines */
  163321. #define CBCR_OFFSET ((INT32) CENTERJSAMPLE << SCALEBITS)
  163322. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  163323. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  163324. /* We allocate one big table and divide it up into eight parts, instead of
  163325. * doing eight alloc_small requests. This lets us use a single table base
  163326. * address, which can be held in a register in the inner loops on many
  163327. * machines (more than can hold all eight addresses, anyway).
  163328. */
  163329. #define R_Y_OFF 0 /* offset to R => Y section */
  163330. #define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
  163331. #define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
  163332. #define R_CB_OFF (3*(MAXJSAMPLE+1))
  163333. #define G_CB_OFF (4*(MAXJSAMPLE+1))
  163334. #define B_CB_OFF (5*(MAXJSAMPLE+1))
  163335. #define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
  163336. #define G_CR_OFF (6*(MAXJSAMPLE+1))
  163337. #define B_CR_OFF (7*(MAXJSAMPLE+1))
  163338. #define TABLE_SIZE (8*(MAXJSAMPLE+1))
  163339. /*
  163340. * Initialize for RGB->YCC colorspace conversion.
  163341. */
  163342. METHODDEF(void)
  163343. rgb_ycc_start (j_compress_ptr cinfo)
  163344. {
  163345. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  163346. INT32 * rgb_ycc_tab;
  163347. INT32 i;
  163348. /* Allocate and fill in the conversion tables. */
  163349. cconvert->rgb_ycc_tab = rgb_ycc_tab = (INT32 *)
  163350. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163351. (TABLE_SIZE * SIZEOF(INT32)));
  163352. for (i = 0; i <= MAXJSAMPLE; i++) {
  163353. rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
  163354. rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
  163355. rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
  163356. rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
  163357. rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
  163358. /* We use a rounding fudge-factor of 0.5-epsilon for Cb and Cr.
  163359. * This ensures that the maximum output will round to MAXJSAMPLE
  163360. * not MAXJSAMPLE+1, and thus that we don't have to range-limit.
  163361. */
  163362. rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  163363. /* B=>Cb and R=>Cr tables are the same
  163364. rgb_ycc_tab[i+R_CR_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
  163365. */
  163366. rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
  163367. rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
  163368. }
  163369. }
  163370. /*
  163371. * Convert some rows of samples to the JPEG colorspace.
  163372. *
  163373. * Note that we change from the application's interleaved-pixel format
  163374. * to our internal noninterleaved, one-plane-per-component format.
  163375. * The input buffer is therefore three times as wide as the output buffer.
  163376. *
  163377. * A starting row offset is provided only for the output buffer. The caller
  163378. * can easily adjust the passed input_buf value to accommodate any row
  163379. * offset required on that side.
  163380. */
  163381. METHODDEF(void)
  163382. rgb_ycc_convert (j_compress_ptr cinfo,
  163383. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  163384. JDIMENSION output_row, int num_rows)
  163385. {
  163386. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  163387. register int r, g, b;
  163388. register INT32 * ctab = cconvert->rgb_ycc_tab;
  163389. register JSAMPROW inptr;
  163390. register JSAMPROW outptr0, outptr1, outptr2;
  163391. register JDIMENSION col;
  163392. JDIMENSION num_cols = cinfo->image_width;
  163393. while (--num_rows >= 0) {
  163394. inptr = *input_buf++;
  163395. outptr0 = output_buf[0][output_row];
  163396. outptr1 = output_buf[1][output_row];
  163397. outptr2 = output_buf[2][output_row];
  163398. output_row++;
  163399. for (col = 0; col < num_cols; col++) {
  163400. r = GETJSAMPLE(inptr[RGB_RED]);
  163401. g = GETJSAMPLE(inptr[RGB_GREEN]);
  163402. b = GETJSAMPLE(inptr[RGB_BLUE]);
  163403. inptr += RGB_PIXELSIZE;
  163404. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  163405. * must be too; we do not need an explicit range-limiting operation.
  163406. * Hence the value being shifted is never negative, and we don't
  163407. * need the general RIGHT_SHIFT macro.
  163408. */
  163409. /* Y */
  163410. outptr0[col] = (JSAMPLE)
  163411. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  163412. >> SCALEBITS);
  163413. /* Cb */
  163414. outptr1[col] = (JSAMPLE)
  163415. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  163416. >> SCALEBITS);
  163417. /* Cr */
  163418. outptr2[col] = (JSAMPLE)
  163419. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  163420. >> SCALEBITS);
  163421. }
  163422. }
  163423. }
  163424. /**************** Cases other than RGB -> YCbCr **************/
  163425. /*
  163426. * Convert some rows of samples to the JPEG colorspace.
  163427. * This version handles RGB->grayscale conversion, which is the same
  163428. * as the RGB->Y portion of RGB->YCbCr.
  163429. * We assume rgb_ycc_start has been called (we only use the Y tables).
  163430. */
  163431. METHODDEF(void)
  163432. rgb_gray_convert (j_compress_ptr cinfo,
  163433. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  163434. JDIMENSION output_row, int num_rows)
  163435. {
  163436. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  163437. register int r, g, b;
  163438. register INT32 * ctab = cconvert->rgb_ycc_tab;
  163439. register JSAMPROW inptr;
  163440. register JSAMPROW outptr;
  163441. register JDIMENSION col;
  163442. JDIMENSION num_cols = cinfo->image_width;
  163443. while (--num_rows >= 0) {
  163444. inptr = *input_buf++;
  163445. outptr = output_buf[0][output_row];
  163446. output_row++;
  163447. for (col = 0; col < num_cols; col++) {
  163448. r = GETJSAMPLE(inptr[RGB_RED]);
  163449. g = GETJSAMPLE(inptr[RGB_GREEN]);
  163450. b = GETJSAMPLE(inptr[RGB_BLUE]);
  163451. inptr += RGB_PIXELSIZE;
  163452. /* Y */
  163453. outptr[col] = (JSAMPLE)
  163454. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  163455. >> SCALEBITS);
  163456. }
  163457. }
  163458. }
  163459. /*
  163460. * Convert some rows of samples to the JPEG colorspace.
  163461. * This version handles Adobe-style CMYK->YCCK conversion,
  163462. * where we convert R=1-C, G=1-M, and B=1-Y to YCbCr using the same
  163463. * conversion as above, while passing K (black) unchanged.
  163464. * We assume rgb_ycc_start has been called.
  163465. */
  163466. METHODDEF(void)
  163467. cmyk_ycck_convert (j_compress_ptr cinfo,
  163468. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  163469. JDIMENSION output_row, int num_rows)
  163470. {
  163471. my_cconvert_ptr cconvert = (my_cconvert_ptr) cinfo->cconvert;
  163472. register int r, g, b;
  163473. register INT32 * ctab = cconvert->rgb_ycc_tab;
  163474. register JSAMPROW inptr;
  163475. register JSAMPROW outptr0, outptr1, outptr2, outptr3;
  163476. register JDIMENSION col;
  163477. JDIMENSION num_cols = cinfo->image_width;
  163478. while (--num_rows >= 0) {
  163479. inptr = *input_buf++;
  163480. outptr0 = output_buf[0][output_row];
  163481. outptr1 = output_buf[1][output_row];
  163482. outptr2 = output_buf[2][output_row];
  163483. outptr3 = output_buf[3][output_row];
  163484. output_row++;
  163485. for (col = 0; col < num_cols; col++) {
  163486. r = MAXJSAMPLE - GETJSAMPLE(inptr[0]);
  163487. g = MAXJSAMPLE - GETJSAMPLE(inptr[1]);
  163488. b = MAXJSAMPLE - GETJSAMPLE(inptr[2]);
  163489. /* K passes through as-is */
  163490. outptr3[col] = inptr[3]; /* don't need GETJSAMPLE here */
  163491. inptr += 4;
  163492. /* If the inputs are 0..MAXJSAMPLE, the outputs of these equations
  163493. * must be too; we do not need an explicit range-limiting operation.
  163494. * Hence the value being shifted is never negative, and we don't
  163495. * need the general RIGHT_SHIFT macro.
  163496. */
  163497. /* Y */
  163498. outptr0[col] = (JSAMPLE)
  163499. ((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF])
  163500. >> SCALEBITS);
  163501. /* Cb */
  163502. outptr1[col] = (JSAMPLE)
  163503. ((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])
  163504. >> SCALEBITS);
  163505. /* Cr */
  163506. outptr2[col] = (JSAMPLE)
  163507. ((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])
  163508. >> SCALEBITS);
  163509. }
  163510. }
  163511. }
  163512. /*
  163513. * Convert some rows of samples to the JPEG colorspace.
  163514. * This version handles grayscale output with no conversion.
  163515. * The source can be either plain grayscale or YCbCr (since Y == gray).
  163516. */
  163517. METHODDEF(void)
  163518. grayscale_convert (j_compress_ptr cinfo,
  163519. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  163520. JDIMENSION output_row, int num_rows)
  163521. {
  163522. register JSAMPROW inptr;
  163523. register JSAMPROW outptr;
  163524. register JDIMENSION col;
  163525. JDIMENSION num_cols = cinfo->image_width;
  163526. int instride = cinfo->input_components;
  163527. while (--num_rows >= 0) {
  163528. inptr = *input_buf++;
  163529. outptr = output_buf[0][output_row];
  163530. output_row++;
  163531. for (col = 0; col < num_cols; col++) {
  163532. outptr[col] = inptr[0]; /* don't need GETJSAMPLE() here */
  163533. inptr += instride;
  163534. }
  163535. }
  163536. }
  163537. /*
  163538. * Convert some rows of samples to the JPEG colorspace.
  163539. * This version handles multi-component colorspaces without conversion.
  163540. * We assume input_components == num_components.
  163541. */
  163542. METHODDEF(void)
  163543. null_convert (j_compress_ptr cinfo,
  163544. JSAMPARRAY input_buf, JSAMPIMAGE output_buf,
  163545. JDIMENSION output_row, int num_rows)
  163546. {
  163547. register JSAMPROW inptr;
  163548. register JSAMPROW outptr;
  163549. register JDIMENSION col;
  163550. register int ci;
  163551. int nc = cinfo->num_components;
  163552. JDIMENSION num_cols = cinfo->image_width;
  163553. while (--num_rows >= 0) {
  163554. /* It seems fastest to make a separate pass for each component. */
  163555. for (ci = 0; ci < nc; ci++) {
  163556. inptr = *input_buf;
  163557. outptr = output_buf[ci][output_row];
  163558. for (col = 0; col < num_cols; col++) {
  163559. outptr[col] = inptr[ci]; /* don't need GETJSAMPLE() here */
  163560. inptr += nc;
  163561. }
  163562. }
  163563. input_buf++;
  163564. output_row++;
  163565. }
  163566. }
  163567. /*
  163568. * Empty method for start_pass.
  163569. */
  163570. METHODDEF(void)
  163571. null_method (j_compress_ptr cinfo)
  163572. {
  163573. /* no work needed */
  163574. }
  163575. /*
  163576. * Module initialization routine for input colorspace conversion.
  163577. */
  163578. GLOBAL(void)
  163579. jinit_color_converter (j_compress_ptr cinfo)
  163580. {
  163581. my_cconvert_ptr cconvert;
  163582. cconvert = (my_cconvert_ptr)
  163583. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163584. SIZEOF(my_color_converter));
  163585. cinfo->cconvert = (struct jpeg_color_converter *) cconvert;
  163586. /* set start_pass to null method until we find out differently */
  163587. cconvert->pub.start_pass = null_method;
  163588. /* Make sure input_components agrees with in_color_space */
  163589. switch (cinfo->in_color_space) {
  163590. case JCS_GRAYSCALE:
  163591. if (cinfo->input_components != 1)
  163592. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  163593. break;
  163594. case JCS_RGB:
  163595. #if RGB_PIXELSIZE != 3
  163596. if (cinfo->input_components != RGB_PIXELSIZE)
  163597. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  163598. break;
  163599. #endif /* else share code with YCbCr */
  163600. case JCS_YCbCr:
  163601. if (cinfo->input_components != 3)
  163602. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  163603. break;
  163604. case JCS_CMYK:
  163605. case JCS_YCCK:
  163606. if (cinfo->input_components != 4)
  163607. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  163608. break;
  163609. default: /* JCS_UNKNOWN can be anything */
  163610. if (cinfo->input_components < 1)
  163611. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  163612. break;
  163613. }
  163614. /* Check num_components, set conversion method based on requested space */
  163615. switch (cinfo->jpeg_color_space) {
  163616. case JCS_GRAYSCALE:
  163617. if (cinfo->num_components != 1)
  163618. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163619. if (cinfo->in_color_space == JCS_GRAYSCALE)
  163620. cconvert->pub.color_convert = grayscale_convert;
  163621. else if (cinfo->in_color_space == JCS_RGB) {
  163622. cconvert->pub.start_pass = rgb_ycc_start;
  163623. cconvert->pub.color_convert = rgb_gray_convert;
  163624. } else if (cinfo->in_color_space == JCS_YCbCr)
  163625. cconvert->pub.color_convert = grayscale_convert;
  163626. else
  163627. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163628. break;
  163629. case JCS_RGB:
  163630. if (cinfo->num_components != 3)
  163631. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163632. if (cinfo->in_color_space == JCS_RGB && RGB_PIXELSIZE == 3)
  163633. cconvert->pub.color_convert = null_convert;
  163634. else
  163635. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163636. break;
  163637. case JCS_YCbCr:
  163638. if (cinfo->num_components != 3)
  163639. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163640. if (cinfo->in_color_space == JCS_RGB) {
  163641. cconvert->pub.start_pass = rgb_ycc_start;
  163642. cconvert->pub.color_convert = rgb_ycc_convert;
  163643. } else if (cinfo->in_color_space == JCS_YCbCr)
  163644. cconvert->pub.color_convert = null_convert;
  163645. else
  163646. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163647. break;
  163648. case JCS_CMYK:
  163649. if (cinfo->num_components != 4)
  163650. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163651. if (cinfo->in_color_space == JCS_CMYK)
  163652. cconvert->pub.color_convert = null_convert;
  163653. else
  163654. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163655. break;
  163656. case JCS_YCCK:
  163657. if (cinfo->num_components != 4)
  163658. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  163659. if (cinfo->in_color_space == JCS_CMYK) {
  163660. cconvert->pub.start_pass = rgb_ycc_start;
  163661. cconvert->pub.color_convert = cmyk_ycck_convert;
  163662. } else if (cinfo->in_color_space == JCS_YCCK)
  163663. cconvert->pub.color_convert = null_convert;
  163664. else
  163665. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163666. break;
  163667. default: /* allow null conversion of JCS_UNKNOWN */
  163668. if (cinfo->jpeg_color_space != cinfo->in_color_space ||
  163669. cinfo->num_components != cinfo->input_components)
  163670. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  163671. cconvert->pub.color_convert = null_convert;
  163672. break;
  163673. }
  163674. }
  163675. /********* End of inlined file: jccolor.c *********/
  163676. #undef FIX
  163677. /********* Start of inlined file: jcdctmgr.c *********/
  163678. #define JPEG_INTERNALS
  163679. /********* Start of inlined file: jdct.h *********/
  163680. /*
  163681. * A forward DCT routine is given a pointer to a work area of type DCTELEM[];
  163682. * the DCT is to be performed in-place in that buffer. Type DCTELEM is int
  163683. * for 8-bit samples, INT32 for 12-bit samples. (NOTE: Floating-point DCT
  163684. * implementations use an array of type FAST_FLOAT, instead.)
  163685. * The DCT inputs are expected to be signed (range +-CENTERJSAMPLE).
  163686. * The DCT outputs are returned scaled up by a factor of 8; they therefore
  163687. * have a range of +-8K for 8-bit data, +-128K for 12-bit data. This
  163688. * convention improves accuracy in integer implementations and saves some
  163689. * work in floating-point ones.
  163690. * Quantization of the output coefficients is done by jcdctmgr.c.
  163691. */
  163692. #ifndef __jdct_h__
  163693. #define __jdct_h__
  163694. #if BITS_IN_JSAMPLE == 8
  163695. typedef int DCTELEM; /* 16 or 32 bits is fine */
  163696. #else
  163697. typedef INT32 DCTELEM; /* must have 32 bits */
  163698. #endif
  163699. typedef JMETHOD(void, forward_DCT_method_ptr, (DCTELEM * data));
  163700. typedef JMETHOD(void, float_DCT_method_ptr, (FAST_FLOAT * data));
  163701. /*
  163702. * An inverse DCT routine is given a pointer to the input JBLOCK and a pointer
  163703. * to an output sample array. The routine must dequantize the input data as
  163704. * well as perform the IDCT; for dequantization, it uses the multiplier table
  163705. * pointed to by compptr->dct_table. The output data is to be placed into the
  163706. * sample array starting at a specified column. (Any row offset needed will
  163707. * be applied to the array pointer before it is passed to the IDCT code.)
  163708. * Note that the number of samples emitted by the IDCT routine is
  163709. * DCT_scaled_size * DCT_scaled_size.
  163710. */
  163711. /* typedef inverse_DCT_method_ptr is declared in jpegint.h */
  163712. /*
  163713. * Each IDCT routine has its own ideas about the best dct_table element type.
  163714. */
  163715. typedef MULTIPLIER ISLOW_MULT_TYPE; /* short or int, whichever is faster */
  163716. #if BITS_IN_JSAMPLE == 8
  163717. typedef MULTIPLIER IFAST_MULT_TYPE; /* 16 bits is OK, use short if faster */
  163718. #define IFAST_SCALE_BITS 2 /* fractional bits in scale factors */
  163719. #else
  163720. typedef INT32 IFAST_MULT_TYPE; /* need 32 bits for scaled quantizers */
  163721. #define IFAST_SCALE_BITS 13 /* fractional bits in scale factors */
  163722. #endif
  163723. typedef FAST_FLOAT FLOAT_MULT_TYPE; /* preferred floating type */
  163724. /*
  163725. * Each IDCT routine is responsible for range-limiting its results and
  163726. * converting them to unsigned form (0..MAXJSAMPLE). The raw outputs could
  163727. * be quite far out of range if the input data is corrupt, so a bulletproof
  163728. * range-limiting step is required. We use a mask-and-table-lookup method
  163729. * to do the combined operations quickly. See the comments with
  163730. * prepare_range_limit_table (in jdmaster.c) for more info.
  163731. */
  163732. #define IDCT_range_limit(cinfo) ((cinfo)->sample_range_limit + CENTERJSAMPLE)
  163733. #define RANGE_MASK (MAXJSAMPLE * 4 + 3) /* 2 bits wider than legal samples */
  163734. /* Short forms of external names for systems with brain-damaged linkers. */
  163735. #ifdef NEED_SHORT_EXTERNAL_NAMES
  163736. #define jpeg_fdct_islow jFDislow
  163737. #define jpeg_fdct_ifast jFDifast
  163738. #define jpeg_fdct_float jFDfloat
  163739. #define jpeg_idct_islow jRDislow
  163740. #define jpeg_idct_ifast jRDifast
  163741. #define jpeg_idct_float jRDfloat
  163742. #define jpeg_idct_4x4 jRD4x4
  163743. #define jpeg_idct_2x2 jRD2x2
  163744. #define jpeg_idct_1x1 jRD1x1
  163745. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  163746. /* Extern declarations for the forward and inverse DCT routines. */
  163747. EXTERN(void) jpeg_fdct_islow JPP((DCTELEM * data));
  163748. EXTERN(void) jpeg_fdct_ifast JPP((DCTELEM * data));
  163749. EXTERN(void) jpeg_fdct_float JPP((FAST_FLOAT * data));
  163750. EXTERN(void) jpeg_idct_islow
  163751. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  163752. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  163753. EXTERN(void) jpeg_idct_ifast
  163754. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  163755. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  163756. EXTERN(void) jpeg_idct_float
  163757. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  163758. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  163759. EXTERN(void) jpeg_idct_4x4
  163760. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  163761. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  163762. EXTERN(void) jpeg_idct_2x2
  163763. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  163764. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  163765. EXTERN(void) jpeg_idct_1x1
  163766. JPP((j_decompress_ptr cinfo, jpeg_component_info * compptr,
  163767. JCOEFPTR coef_block, JSAMPARRAY output_buf, JDIMENSION output_col));
  163768. /*
  163769. * Macros for handling fixed-point arithmetic; these are used by many
  163770. * but not all of the DCT/IDCT modules.
  163771. *
  163772. * All values are expected to be of type INT32.
  163773. * Fractional constants are scaled left by CONST_BITS bits.
  163774. * CONST_BITS is defined within each module using these macros,
  163775. * and may differ from one module to the next.
  163776. */
  163777. #define ONE ((INT32) 1)
  163778. #define CONST_SCALE (ONE << CONST_BITS)
  163779. /* Convert a positive real constant to an integer scaled by CONST_SCALE.
  163780. * Caution: some C compilers fail to reduce "FIX(constant)" at compile time,
  163781. * thus causing a lot of useless floating-point operations at run time.
  163782. */
  163783. #define FIX(x) ((INT32) ((x) * CONST_SCALE + 0.5))
  163784. /* Descale and correctly round an INT32 value that's scaled by N bits.
  163785. * We assume RIGHT_SHIFT rounds towards minus infinity, so adding
  163786. * the fudge factor is correct for either sign of X.
  163787. */
  163788. #define DESCALE(x,n) RIGHT_SHIFT((x) + (ONE << ((n)-1)), n)
  163789. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  163790. * This macro is used only when the two inputs will actually be no more than
  163791. * 16 bits wide, so that a 16x16->32 bit multiply can be used instead of a
  163792. * full 32x32 multiply. This provides a useful speedup on many machines.
  163793. * Unfortunately there is no way to specify a 16x16->32 multiply portably
  163794. * in C, but some C compilers will do the right thing if you provide the
  163795. * correct combination of casts.
  163796. */
  163797. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  163798. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT16) (const)))
  163799. #endif
  163800. #ifdef SHORTxLCONST_32 /* known to work with Microsoft C 6.0 */
  163801. #define MULTIPLY16C16(var,const) (((INT16) (var)) * ((INT32) (const)))
  163802. #endif
  163803. #ifndef MULTIPLY16C16 /* default definition */
  163804. #define MULTIPLY16C16(var,const) ((var) * (const))
  163805. #endif
  163806. /* Same except both inputs are variables. */
  163807. #ifdef SHORTxSHORT_32 /* may work if 'int' is 32 bits */
  163808. #define MULTIPLY16V16(var1,var2) (((INT16) (var1)) * ((INT16) (var2)))
  163809. #endif
  163810. #ifndef MULTIPLY16V16 /* default definition */
  163811. #define MULTIPLY16V16(var1,var2) ((var1) * (var2))
  163812. #endif
  163813. #endif
  163814. /********* End of inlined file: jdct.h *********/
  163815. /* Private declarations for DCT subsystem */
  163816. /* Private subobject for this module */
  163817. typedef struct {
  163818. struct jpeg_forward_dct pub; /* public fields */
  163819. /* Pointer to the DCT routine actually in use */
  163820. forward_DCT_method_ptr do_dct;
  163821. /* The actual post-DCT divisors --- not identical to the quant table
  163822. * entries, because of scaling (especially for an unnormalized DCT).
  163823. * Each table is given in normal array order.
  163824. */
  163825. DCTELEM * divisors[NUM_QUANT_TBLS];
  163826. #ifdef DCT_FLOAT_SUPPORTED
  163827. /* Same as above for the floating-point case. */
  163828. float_DCT_method_ptr do_float_dct;
  163829. FAST_FLOAT * float_divisors[NUM_QUANT_TBLS];
  163830. #endif
  163831. } my_fdct_controller;
  163832. typedef my_fdct_controller * my_fdct_ptr;
  163833. /*
  163834. * Initialize for a processing pass.
  163835. * Verify that all referenced Q-tables are present, and set up
  163836. * the divisor table for each one.
  163837. * In the current implementation, DCT of all components is done during
  163838. * the first pass, even if only some components will be output in the
  163839. * first scan. Hence all components should be examined here.
  163840. */
  163841. METHODDEF(void)
  163842. start_pass_fdctmgr (j_compress_ptr cinfo)
  163843. {
  163844. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163845. int ci, qtblno, i;
  163846. jpeg_component_info *compptr;
  163847. JQUANT_TBL * qtbl;
  163848. DCTELEM * dtbl;
  163849. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  163850. ci++, compptr++) {
  163851. qtblno = compptr->quant_tbl_no;
  163852. /* Make sure specified quantization table is present */
  163853. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  163854. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  163855. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  163856. qtbl = cinfo->quant_tbl_ptrs[qtblno];
  163857. /* Compute divisors for this quant table */
  163858. /* We may do this more than once for same table, but it's not a big deal */
  163859. switch (cinfo->dct_method) {
  163860. #ifdef DCT_ISLOW_SUPPORTED
  163861. case JDCT_ISLOW:
  163862. /* For LL&M IDCT method, divisors are equal to raw quantization
  163863. * coefficients multiplied by 8 (to counteract scaling).
  163864. */
  163865. if (fdct->divisors[qtblno] == NULL) {
  163866. fdct->divisors[qtblno] = (DCTELEM *)
  163867. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163868. DCTSIZE2 * SIZEOF(DCTELEM));
  163869. }
  163870. dtbl = fdct->divisors[qtblno];
  163871. for (i = 0; i < DCTSIZE2; i++) {
  163872. dtbl[i] = ((DCTELEM) qtbl->quantval[i]) << 3;
  163873. }
  163874. break;
  163875. #endif
  163876. #ifdef DCT_IFAST_SUPPORTED
  163877. case JDCT_IFAST:
  163878. {
  163879. /* For AA&N IDCT method, divisors are equal to quantization
  163880. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163881. * scalefactor[0] = 1
  163882. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163883. * We apply a further scale factor of 8.
  163884. */
  163885. #define CONST_BITS 14
  163886. static const INT16 aanscales[DCTSIZE2] = {
  163887. /* precomputed values scaled up by 14 bits */
  163888. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163889. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  163890. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  163891. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  163892. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  163893. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  163894. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  163895. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  163896. };
  163897. SHIFT_TEMPS
  163898. if (fdct->divisors[qtblno] == NULL) {
  163899. fdct->divisors[qtblno] = (DCTELEM *)
  163900. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163901. DCTSIZE2 * SIZEOF(DCTELEM));
  163902. }
  163903. dtbl = fdct->divisors[qtblno];
  163904. for (i = 0; i < DCTSIZE2; i++) {
  163905. dtbl[i] = (DCTELEM)
  163906. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  163907. (INT32) aanscales[i]),
  163908. CONST_BITS-3);
  163909. }
  163910. }
  163911. break;
  163912. #endif
  163913. #ifdef DCT_FLOAT_SUPPORTED
  163914. case JDCT_FLOAT:
  163915. {
  163916. /* For float AA&N IDCT method, divisors are equal to quantization
  163917. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  163918. * scalefactor[0] = 1
  163919. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  163920. * We apply a further scale factor of 8.
  163921. * What's actually stored is 1/divisor so that the inner loop can
  163922. * use a multiplication rather than a division.
  163923. */
  163924. FAST_FLOAT * fdtbl;
  163925. int row, col;
  163926. static const double aanscalefactor[DCTSIZE] = {
  163927. 1.0, 1.387039845, 1.306562965, 1.175875602,
  163928. 1.0, 0.785694958, 0.541196100, 0.275899379
  163929. };
  163930. if (fdct->float_divisors[qtblno] == NULL) {
  163931. fdct->float_divisors[qtblno] = (FAST_FLOAT *)
  163932. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  163933. DCTSIZE2 * SIZEOF(FAST_FLOAT));
  163934. }
  163935. fdtbl = fdct->float_divisors[qtblno];
  163936. i = 0;
  163937. for (row = 0; row < DCTSIZE; row++) {
  163938. for (col = 0; col < DCTSIZE; col++) {
  163939. fdtbl[i] = (FAST_FLOAT)
  163940. (1.0 / (((double) qtbl->quantval[i] *
  163941. aanscalefactor[row] * aanscalefactor[col] * 8.0)));
  163942. i++;
  163943. }
  163944. }
  163945. }
  163946. break;
  163947. #endif
  163948. default:
  163949. ERREXIT(cinfo, JERR_NOT_COMPILED);
  163950. break;
  163951. }
  163952. }
  163953. }
  163954. /*
  163955. * Perform forward DCT on one or more blocks of a component.
  163956. *
  163957. * The input samples are taken from the sample_data[] array starting at
  163958. * position start_row/start_col, and moving to the right for any additional
  163959. * blocks. The quantized coefficients are returned in coef_blocks[].
  163960. */
  163961. METHODDEF(void)
  163962. forward_DCT (j_compress_ptr cinfo, jpeg_component_info * compptr,
  163963. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  163964. JDIMENSION start_row, JDIMENSION start_col,
  163965. JDIMENSION num_blocks)
  163966. /* This version is used for integer DCT implementations. */
  163967. {
  163968. /* This routine is heavily used, so it's worth coding it tightly. */
  163969. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  163970. forward_DCT_method_ptr do_dct = fdct->do_dct;
  163971. DCTELEM * divisors = fdct->divisors[compptr->quant_tbl_no];
  163972. DCTELEM workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  163973. JDIMENSION bi;
  163974. sample_data += start_row; /* fold in the vertical offset once */
  163975. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  163976. /* Load data into workspace, applying unsigned->signed conversion */
  163977. { register DCTELEM *workspaceptr;
  163978. register JSAMPROW elemptr;
  163979. register int elemr;
  163980. workspaceptr = workspace;
  163981. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  163982. elemptr = sample_data[elemr] + start_col;
  163983. #if DCTSIZE == 8 /* unroll the inner loop */
  163984. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163985. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163986. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163987. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163988. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163989. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163990. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163991. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163992. #else
  163993. { register int elemc;
  163994. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  163995. *workspaceptr++ = GETJSAMPLE(*elemptr++) - CENTERJSAMPLE;
  163996. }
  163997. }
  163998. #endif
  163999. }
  164000. }
  164001. /* Perform the DCT */
  164002. (*do_dct) (workspace);
  164003. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  164004. { register DCTELEM temp, qval;
  164005. register int i;
  164006. register JCOEFPTR output_ptr = coef_blocks[bi];
  164007. for (i = 0; i < DCTSIZE2; i++) {
  164008. qval = divisors[i];
  164009. temp = workspace[i];
  164010. /* Divide the coefficient value by qval, ensuring proper rounding.
  164011. * Since C does not specify the direction of rounding for negative
  164012. * quotients, we have to force the dividend positive for portability.
  164013. *
  164014. * In most files, at least half of the output values will be zero
  164015. * (at default quantization settings, more like three-quarters...)
  164016. * so we should ensure that this case is fast. On many machines,
  164017. * a comparison is enough cheaper than a divide to make a special test
  164018. * a win. Since both inputs will be nonnegative, we need only test
  164019. * for a < b to discover whether a/b is 0.
  164020. * If your machine's division is fast enough, define FAST_DIVIDE.
  164021. */
  164022. #ifdef FAST_DIVIDE
  164023. #define DIVIDE_BY(a,b) a /= b
  164024. #else
  164025. #define DIVIDE_BY(a,b) if (a >= b) a /= b; else a = 0
  164026. #endif
  164027. if (temp < 0) {
  164028. temp = -temp;
  164029. temp += qval>>1; /* for rounding */
  164030. DIVIDE_BY(temp, qval);
  164031. temp = -temp;
  164032. } else {
  164033. temp += qval>>1; /* for rounding */
  164034. DIVIDE_BY(temp, qval);
  164035. }
  164036. output_ptr[i] = (JCOEF) temp;
  164037. }
  164038. }
  164039. }
  164040. }
  164041. #ifdef DCT_FLOAT_SUPPORTED
  164042. METHODDEF(void)
  164043. forward_DCT_float (j_compress_ptr cinfo, jpeg_component_info * compptr,
  164044. JSAMPARRAY sample_data, JBLOCKROW coef_blocks,
  164045. JDIMENSION start_row, JDIMENSION start_col,
  164046. JDIMENSION num_blocks)
  164047. /* This version is used for floating-point DCT implementations. */
  164048. {
  164049. /* This routine is heavily used, so it's worth coding it tightly. */
  164050. my_fdct_ptr fdct = (my_fdct_ptr) cinfo->fdct;
  164051. float_DCT_method_ptr do_dct = fdct->do_float_dct;
  164052. FAST_FLOAT * divisors = fdct->float_divisors[compptr->quant_tbl_no];
  164053. FAST_FLOAT workspace[DCTSIZE2]; /* work area for FDCT subroutine */
  164054. JDIMENSION bi;
  164055. sample_data += start_row; /* fold in the vertical offset once */
  164056. for (bi = 0; bi < num_blocks; bi++, start_col += DCTSIZE) {
  164057. /* Load data into workspace, applying unsigned->signed conversion */
  164058. { register FAST_FLOAT *workspaceptr;
  164059. register JSAMPROW elemptr;
  164060. register int elemr;
  164061. workspaceptr = workspace;
  164062. for (elemr = 0; elemr < DCTSIZE; elemr++) {
  164063. elemptr = sample_data[elemr] + start_col;
  164064. #if DCTSIZE == 8 /* unroll the inner loop */
  164065. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  164066. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  164067. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  164068. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  164069. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  164070. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  164071. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  164072. *workspaceptr++ = (FAST_FLOAT)(GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  164073. #else
  164074. { register int elemc;
  164075. for (elemc = DCTSIZE; elemc > 0; elemc--) {
  164076. *workspaceptr++ = (FAST_FLOAT)
  164077. (GETJSAMPLE(*elemptr++) - CENTERJSAMPLE);
  164078. }
  164079. }
  164080. #endif
  164081. }
  164082. }
  164083. /* Perform the DCT */
  164084. (*do_dct) (workspace);
  164085. /* Quantize/descale the coefficients, and store into coef_blocks[] */
  164086. { register FAST_FLOAT temp;
  164087. register int i;
  164088. register JCOEFPTR output_ptr = coef_blocks[bi];
  164089. for (i = 0; i < DCTSIZE2; i++) {
  164090. /* Apply the quantization and scaling factor */
  164091. temp = workspace[i] * divisors[i];
  164092. /* Round to nearest integer.
  164093. * Since C does not specify the direction of rounding for negative
  164094. * quotients, we have to force the dividend positive for portability.
  164095. * The maximum coefficient size is +-16K (for 12-bit data), so this
  164096. * code should work for either 16-bit or 32-bit ints.
  164097. */
  164098. output_ptr[i] = (JCOEF) ((int) (temp + (FAST_FLOAT) 16384.5) - 16384);
  164099. }
  164100. }
  164101. }
  164102. }
  164103. #endif /* DCT_FLOAT_SUPPORTED */
  164104. /*
  164105. * Initialize FDCT manager.
  164106. */
  164107. GLOBAL(void)
  164108. jinit_forward_dct (j_compress_ptr cinfo)
  164109. {
  164110. my_fdct_ptr fdct;
  164111. int i;
  164112. fdct = (my_fdct_ptr)
  164113. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164114. SIZEOF(my_fdct_controller));
  164115. cinfo->fdct = (struct jpeg_forward_dct *) fdct;
  164116. fdct->pub.start_pass = start_pass_fdctmgr;
  164117. switch (cinfo->dct_method) {
  164118. #ifdef DCT_ISLOW_SUPPORTED
  164119. case JDCT_ISLOW:
  164120. fdct->pub.forward_DCT = forward_DCT;
  164121. fdct->do_dct = jpeg_fdct_islow;
  164122. break;
  164123. #endif
  164124. #ifdef DCT_IFAST_SUPPORTED
  164125. case JDCT_IFAST:
  164126. fdct->pub.forward_DCT = forward_DCT;
  164127. fdct->do_dct = jpeg_fdct_ifast;
  164128. break;
  164129. #endif
  164130. #ifdef DCT_FLOAT_SUPPORTED
  164131. case JDCT_FLOAT:
  164132. fdct->pub.forward_DCT = forward_DCT_float;
  164133. fdct->do_float_dct = jpeg_fdct_float;
  164134. break;
  164135. #endif
  164136. default:
  164137. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164138. break;
  164139. }
  164140. /* Mark divisor tables unallocated */
  164141. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  164142. fdct->divisors[i] = NULL;
  164143. #ifdef DCT_FLOAT_SUPPORTED
  164144. fdct->float_divisors[i] = NULL;
  164145. #endif
  164146. }
  164147. }
  164148. /********* End of inlined file: jcdctmgr.c *********/
  164149. #undef CONST_BITS
  164150. /********* Start of inlined file: jchuff.c *********/
  164151. #define JPEG_INTERNALS
  164152. /********* Start of inlined file: jchuff.h *********/
  164153. /* The legal range of a DCT coefficient is
  164154. * -1024 .. +1023 for 8-bit data;
  164155. * -16384 .. +16383 for 12-bit data.
  164156. * Hence the magnitude should always fit in 10 or 14 bits respectively.
  164157. */
  164158. #ifndef _jchuff_h_
  164159. #define _jchuff_h_
  164160. #if BITS_IN_JSAMPLE == 8
  164161. #define MAX_COEF_BITS 10
  164162. #else
  164163. #define MAX_COEF_BITS 14
  164164. #endif
  164165. /* Derived data constructed for each Huffman table */
  164166. typedef struct {
  164167. unsigned int ehufco[256]; /* code for each symbol */
  164168. char ehufsi[256]; /* length of code for each symbol */
  164169. /* If no code has been allocated for a symbol S, ehufsi[S] contains 0 */
  164170. } c_derived_tbl;
  164171. /* Short forms of external names for systems with brain-damaged linkers. */
  164172. #ifdef NEED_SHORT_EXTERNAL_NAMES
  164173. #define jpeg_make_c_derived_tbl jMkCDerived
  164174. #define jpeg_gen_optimal_table jGenOptTbl
  164175. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  164176. /* Expand a Huffman table definition into the derived format */
  164177. EXTERN(void) jpeg_make_c_derived_tbl
  164178. JPP((j_compress_ptr cinfo, boolean isDC, int tblno,
  164179. c_derived_tbl ** pdtbl));
  164180. /* Generate an optimal table definition given the specified counts */
  164181. EXTERN(void) jpeg_gen_optimal_table
  164182. JPP((j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[]));
  164183. #endif
  164184. /********* End of inlined file: jchuff.h *********/
  164185. /* Declarations shared with jcphuff.c */
  164186. /* Expanded entropy encoder object for Huffman encoding.
  164187. *
  164188. * The savable_state subrecord contains fields that change within an MCU,
  164189. * but must not be updated permanently until we complete the MCU.
  164190. */
  164191. typedef struct {
  164192. INT32 put_buffer; /* current bit-accumulation buffer */
  164193. int put_bits; /* # of bits now in it */
  164194. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  164195. } savable_state;
  164196. /* This macro is to work around compilers with missing or broken
  164197. * structure assignment. You'll need to fix this code if you have
  164198. * such a compiler and you change MAX_COMPS_IN_SCAN.
  164199. */
  164200. #ifndef NO_STRUCT_ASSIGN
  164201. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  164202. #else
  164203. #if MAX_COMPS_IN_SCAN == 4
  164204. #define ASSIGN_STATE(dest,src) \
  164205. ((dest).put_buffer = (src).put_buffer, \
  164206. (dest).put_bits = (src).put_bits, \
  164207. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  164208. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  164209. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  164210. (dest).last_dc_val[3] = (src).last_dc_val[3])
  164211. #endif
  164212. #endif
  164213. typedef struct {
  164214. struct jpeg_entropy_encoder pub; /* public fields */
  164215. savable_state saved; /* Bit buffer & DC state at start of MCU */
  164216. /* These fields are NOT loaded into local working state. */
  164217. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  164218. int next_restart_num; /* next restart number to write (0-7) */
  164219. /* Pointers to derived tables (these workspaces have image lifespan) */
  164220. c_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  164221. c_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  164222. #ifdef ENTROPY_OPT_SUPPORTED /* Statistics tables for optimization */
  164223. long * dc_count_ptrs[NUM_HUFF_TBLS];
  164224. long * ac_count_ptrs[NUM_HUFF_TBLS];
  164225. #endif
  164226. } huff_entropy_encoder;
  164227. typedef huff_entropy_encoder * huff_entropy_ptr;
  164228. /* Working state while writing an MCU.
  164229. * This struct contains all the fields that are needed by subroutines.
  164230. */
  164231. typedef struct {
  164232. JOCTET * next_output_byte; /* => next byte to write in buffer */
  164233. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  164234. savable_state cur; /* Current bit buffer & DC state */
  164235. j_compress_ptr cinfo; /* dump_buffer needs access to this */
  164236. } working_state;
  164237. /* Forward declarations */
  164238. METHODDEF(boolean) encode_mcu_huff JPP((j_compress_ptr cinfo,
  164239. JBLOCKROW *MCU_data));
  164240. METHODDEF(void) finish_pass_huff JPP((j_compress_ptr cinfo));
  164241. #ifdef ENTROPY_OPT_SUPPORTED
  164242. METHODDEF(boolean) encode_mcu_gather JPP((j_compress_ptr cinfo,
  164243. JBLOCKROW *MCU_data));
  164244. METHODDEF(void) finish_pass_gather JPP((j_compress_ptr cinfo));
  164245. #endif
  164246. /*
  164247. * Initialize for a Huffman-compressed scan.
  164248. * If gather_statistics is TRUE, we do not output anything during the scan,
  164249. * just count the Huffman symbols used and generate Huffman code tables.
  164250. */
  164251. METHODDEF(void)
  164252. start_pass_huff (j_compress_ptr cinfo, boolean gather_statistics)
  164253. {
  164254. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  164255. int ci, dctbl, actbl;
  164256. jpeg_component_info * compptr;
  164257. if (gather_statistics) {
  164258. #ifdef ENTROPY_OPT_SUPPORTED
  164259. entropy->pub.encode_mcu = encode_mcu_gather;
  164260. entropy->pub.finish_pass = finish_pass_gather;
  164261. #else
  164262. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164263. #endif
  164264. } else {
  164265. entropy->pub.encode_mcu = encode_mcu_huff;
  164266. entropy->pub.finish_pass = finish_pass_huff;
  164267. }
  164268. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164269. compptr = cinfo->cur_comp_info[ci];
  164270. dctbl = compptr->dc_tbl_no;
  164271. actbl = compptr->ac_tbl_no;
  164272. if (gather_statistics) {
  164273. #ifdef ENTROPY_OPT_SUPPORTED
  164274. /* Check for invalid table indexes */
  164275. /* (make_c_derived_tbl does this in the other path) */
  164276. if (dctbl < 0 || dctbl >= NUM_HUFF_TBLS)
  164277. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, dctbl);
  164278. if (actbl < 0 || actbl >= NUM_HUFF_TBLS)
  164279. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, actbl);
  164280. /* Allocate and zero the statistics tables */
  164281. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  164282. if (entropy->dc_count_ptrs[dctbl] == NULL)
  164283. entropy->dc_count_ptrs[dctbl] = (long *)
  164284. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164285. 257 * SIZEOF(long));
  164286. MEMZERO(entropy->dc_count_ptrs[dctbl], 257 * SIZEOF(long));
  164287. if (entropy->ac_count_ptrs[actbl] == NULL)
  164288. entropy->ac_count_ptrs[actbl] = (long *)
  164289. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164290. 257 * SIZEOF(long));
  164291. MEMZERO(entropy->ac_count_ptrs[actbl], 257 * SIZEOF(long));
  164292. #endif
  164293. } else {
  164294. /* Compute derived values for Huffman tables */
  164295. /* We may do this more than once for a table, but it's not expensive */
  164296. jpeg_make_c_derived_tbl(cinfo, TRUE, dctbl,
  164297. & entropy->dc_derived_tbls[dctbl]);
  164298. jpeg_make_c_derived_tbl(cinfo, FALSE, actbl,
  164299. & entropy->ac_derived_tbls[actbl]);
  164300. }
  164301. /* Initialize DC predictions to 0 */
  164302. entropy->saved.last_dc_val[ci] = 0;
  164303. }
  164304. /* Initialize bit buffer to empty */
  164305. entropy->saved.put_buffer = 0;
  164306. entropy->saved.put_bits = 0;
  164307. /* Initialize restart stuff */
  164308. entropy->restarts_to_go = cinfo->restart_interval;
  164309. entropy->next_restart_num = 0;
  164310. }
  164311. /*
  164312. * Compute the derived values for a Huffman table.
  164313. * This routine also performs some validation checks on the table.
  164314. *
  164315. * Note this is also used by jcphuff.c.
  164316. */
  164317. GLOBAL(void)
  164318. jpeg_make_c_derived_tbl (j_compress_ptr cinfo, boolean isDC, int tblno,
  164319. c_derived_tbl ** pdtbl)
  164320. {
  164321. JHUFF_TBL *htbl;
  164322. c_derived_tbl *dtbl;
  164323. int p, i, l, lastp, si, maxsymbol;
  164324. char huffsize[257];
  164325. unsigned int huffcode[257];
  164326. unsigned int code;
  164327. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  164328. * paralleling the order of the symbols themselves in htbl->huffval[].
  164329. */
  164330. /* Find the input Huffman table */
  164331. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  164332. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  164333. htbl =
  164334. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  164335. if (htbl == NULL)
  164336. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  164337. /* Allocate a workspace if we haven't already done so. */
  164338. if (*pdtbl == NULL)
  164339. *pdtbl = (c_derived_tbl *)
  164340. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164341. SIZEOF(c_derived_tbl));
  164342. dtbl = *pdtbl;
  164343. /* Figure C.1: make table of Huffman code length for each symbol */
  164344. p = 0;
  164345. for (l = 1; l <= 16; l++) {
  164346. i = (int) htbl->bits[l];
  164347. if (i < 0 || p + i > 256) /* protect against table overrun */
  164348. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164349. while (i--)
  164350. huffsize[p++] = (char) l;
  164351. }
  164352. huffsize[p] = 0;
  164353. lastp = p;
  164354. /* Figure C.2: generate the codes themselves */
  164355. /* We also validate that the counts represent a legal Huffman code tree. */
  164356. code = 0;
  164357. si = huffsize[0];
  164358. p = 0;
  164359. while (huffsize[p]) {
  164360. while (((int) huffsize[p]) == si) {
  164361. huffcode[p++] = code;
  164362. code++;
  164363. }
  164364. /* code is now 1 more than the last code used for codelength si; but
  164365. * it must still fit in si bits, since no code is allowed to be all ones.
  164366. */
  164367. if (((INT32) code) >= (((INT32) 1) << si))
  164368. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164369. code <<= 1;
  164370. si++;
  164371. }
  164372. /* Figure C.3: generate encoding tables */
  164373. /* These are code and size indexed by symbol value */
  164374. /* Set all codeless symbols to have code length 0;
  164375. * this lets us detect duplicate VAL entries here, and later
  164376. * allows emit_bits to detect any attempt to emit such symbols.
  164377. */
  164378. MEMZERO(dtbl->ehufsi, SIZEOF(dtbl->ehufsi));
  164379. /* This is also a convenient place to check for out-of-range
  164380. * and duplicated VAL entries. We allow 0..255 for AC symbols
  164381. * but only 0..15 for DC. (We could constrain them further
  164382. * based on data depth and mode, but this seems enough.)
  164383. */
  164384. maxsymbol = isDC ? 15 : 255;
  164385. for (p = 0; p < lastp; p++) {
  164386. i = htbl->huffval[p];
  164387. if (i < 0 || i > maxsymbol || dtbl->ehufsi[i])
  164388. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  164389. dtbl->ehufco[i] = huffcode[p];
  164390. dtbl->ehufsi[i] = huffsize[p];
  164391. }
  164392. }
  164393. /* Outputting bytes to the file */
  164394. /* Emit a byte, taking 'action' if must suspend. */
  164395. #define emit_byte(state,val,action) \
  164396. { *(state)->next_output_byte++ = (JOCTET) (val); \
  164397. if (--(state)->free_in_buffer == 0) \
  164398. if (! dump_buffer(state)) \
  164399. { action; } }
  164400. LOCAL(boolean)
  164401. dump_buffer (working_state * state)
  164402. /* Empty the output buffer; return TRUE if successful, FALSE if must suspend */
  164403. {
  164404. struct jpeg_destination_mgr * dest = state->cinfo->dest;
  164405. if (! (*dest->empty_output_buffer) (state->cinfo))
  164406. return FALSE;
  164407. /* After a successful buffer dump, must reset buffer pointers */
  164408. state->next_output_byte = dest->next_output_byte;
  164409. state->free_in_buffer = dest->free_in_buffer;
  164410. return TRUE;
  164411. }
  164412. /* Outputting bits to the file */
  164413. /* Only the right 24 bits of put_buffer are used; the valid bits are
  164414. * left-justified in this part. At most 16 bits can be passed to emit_bits
  164415. * in one call, and we never retain more than 7 bits in put_buffer
  164416. * between calls, so 24 bits are sufficient.
  164417. */
  164418. INLINE
  164419. LOCAL(boolean)
  164420. emit_bits (working_state * state, unsigned int code, int size)
  164421. /* Emit some bits; return TRUE if successful, FALSE if must suspend */
  164422. {
  164423. /* This routine is heavily used, so it's worth coding tightly. */
  164424. register INT32 put_buffer = (INT32) code;
  164425. register int put_bits = state->cur.put_bits;
  164426. /* if size is 0, caller used an invalid Huffman table entry */
  164427. if (size == 0)
  164428. ERREXIT(state->cinfo, JERR_HUFF_MISSING_CODE);
  164429. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  164430. put_bits += size; /* new number of bits in buffer */
  164431. put_buffer <<= 24 - put_bits; /* align incoming bits */
  164432. put_buffer |= state->cur.put_buffer; /* and merge with old buffer contents */
  164433. while (put_bits >= 8) {
  164434. int c = (int) ((put_buffer >> 16) & 0xFF);
  164435. emit_byte(state, c, return FALSE);
  164436. if (c == 0xFF) { /* need to stuff a zero byte? */
  164437. emit_byte(state, 0, return FALSE);
  164438. }
  164439. put_buffer <<= 8;
  164440. put_bits -= 8;
  164441. }
  164442. state->cur.put_buffer = put_buffer; /* update state variables */
  164443. state->cur.put_bits = put_bits;
  164444. return TRUE;
  164445. }
  164446. LOCAL(boolean)
  164447. flush_bits (working_state * state)
  164448. {
  164449. if (! emit_bits(state, 0x7F, 7)) /* fill any partial byte with ones */
  164450. return FALSE;
  164451. state->cur.put_buffer = 0; /* and reset bit-buffer to empty */
  164452. state->cur.put_bits = 0;
  164453. return TRUE;
  164454. }
  164455. /* Encode a single block's worth of coefficients */
  164456. LOCAL(boolean)
  164457. encode_one_block (working_state * state, JCOEFPTR block, int last_dc_val,
  164458. c_derived_tbl *dctbl, c_derived_tbl *actbl)
  164459. {
  164460. register int temp, temp2;
  164461. register int nbits;
  164462. register int k, r, i;
  164463. /* Encode the DC coefficient difference per section F.1.2.1 */
  164464. temp = temp2 = block[0] - last_dc_val;
  164465. if (temp < 0) {
  164466. temp = -temp; /* temp is abs value of input */
  164467. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  164468. /* This code assumes we are on a two's complement machine */
  164469. temp2--;
  164470. }
  164471. /* Find the number of bits needed for the magnitude of the coefficient */
  164472. nbits = 0;
  164473. while (temp) {
  164474. nbits++;
  164475. temp >>= 1;
  164476. }
  164477. /* Check for out-of-range coefficient values.
  164478. * Since we're encoding a difference, the range limit is twice as much.
  164479. */
  164480. if (nbits > MAX_COEF_BITS+1)
  164481. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  164482. /* Emit the Huffman-coded symbol for the number of bits */
  164483. if (! emit_bits(state, dctbl->ehufco[nbits], dctbl->ehufsi[nbits]))
  164484. return FALSE;
  164485. /* Emit that number of bits of the value, if positive, */
  164486. /* or the complement of its magnitude, if negative. */
  164487. if (nbits) /* emit_bits rejects calls with size 0 */
  164488. if (! emit_bits(state, (unsigned int) temp2, nbits))
  164489. return FALSE;
  164490. /* Encode the AC coefficients per section F.1.2.2 */
  164491. r = 0; /* r = run length of zeros */
  164492. for (k = 1; k < DCTSIZE2; k++) {
  164493. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  164494. r++;
  164495. } else {
  164496. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  164497. while (r > 15) {
  164498. if (! emit_bits(state, actbl->ehufco[0xF0], actbl->ehufsi[0xF0]))
  164499. return FALSE;
  164500. r -= 16;
  164501. }
  164502. temp2 = temp;
  164503. if (temp < 0) {
  164504. temp = -temp; /* temp is abs value of input */
  164505. /* This code assumes we are on a two's complement machine */
  164506. temp2--;
  164507. }
  164508. /* Find the number of bits needed for the magnitude of the coefficient */
  164509. nbits = 1; /* there must be at least one 1 bit */
  164510. while ((temp >>= 1))
  164511. nbits++;
  164512. /* Check for out-of-range coefficient values */
  164513. if (nbits > MAX_COEF_BITS)
  164514. ERREXIT(state->cinfo, JERR_BAD_DCT_COEF);
  164515. /* Emit Huffman symbol for run length / number of bits */
  164516. i = (r << 4) + nbits;
  164517. if (! emit_bits(state, actbl->ehufco[i], actbl->ehufsi[i]))
  164518. return FALSE;
  164519. /* Emit that number of bits of the value, if positive, */
  164520. /* or the complement of its magnitude, if negative. */
  164521. if (! emit_bits(state, (unsigned int) temp2, nbits))
  164522. return FALSE;
  164523. r = 0;
  164524. }
  164525. }
  164526. /* If the last coef(s) were zero, emit an end-of-block code */
  164527. if (r > 0)
  164528. if (! emit_bits(state, actbl->ehufco[0], actbl->ehufsi[0]))
  164529. return FALSE;
  164530. return TRUE;
  164531. }
  164532. /*
  164533. * Emit a restart marker & resynchronize predictions.
  164534. */
  164535. LOCAL(boolean)
  164536. emit_restart (working_state * state, int restart_num)
  164537. {
  164538. int ci;
  164539. if (! flush_bits(state))
  164540. return FALSE;
  164541. emit_byte(state, 0xFF, return FALSE);
  164542. emit_byte(state, JPEG_RST0 + restart_num, return FALSE);
  164543. /* Re-initialize DC predictions to 0 */
  164544. for (ci = 0; ci < state->cinfo->comps_in_scan; ci++)
  164545. state->cur.last_dc_val[ci] = 0;
  164546. /* The restart counter is not updated until we successfully write the MCU. */
  164547. return TRUE;
  164548. }
  164549. /*
  164550. * Encode and output one MCU's worth of Huffman-compressed coefficients.
  164551. */
  164552. METHODDEF(boolean)
  164553. encode_mcu_huff (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  164554. {
  164555. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  164556. working_state state;
  164557. int blkn, ci;
  164558. jpeg_component_info * compptr;
  164559. /* Load up working state */
  164560. state.next_output_byte = cinfo->dest->next_output_byte;
  164561. state.free_in_buffer = cinfo->dest->free_in_buffer;
  164562. ASSIGN_STATE(state.cur, entropy->saved);
  164563. state.cinfo = cinfo;
  164564. /* Emit restart marker if needed */
  164565. if (cinfo->restart_interval) {
  164566. if (entropy->restarts_to_go == 0)
  164567. if (! emit_restart(&state, entropy->next_restart_num))
  164568. return FALSE;
  164569. }
  164570. /* Encode the MCU data blocks */
  164571. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  164572. ci = cinfo->MCU_membership[blkn];
  164573. compptr = cinfo->cur_comp_info[ci];
  164574. if (! encode_one_block(&state,
  164575. MCU_data[blkn][0], state.cur.last_dc_val[ci],
  164576. entropy->dc_derived_tbls[compptr->dc_tbl_no],
  164577. entropy->ac_derived_tbls[compptr->ac_tbl_no]))
  164578. return FALSE;
  164579. /* Update last_dc_val */
  164580. state.cur.last_dc_val[ci] = MCU_data[blkn][0][0];
  164581. }
  164582. /* Completed MCU, so update state */
  164583. cinfo->dest->next_output_byte = state.next_output_byte;
  164584. cinfo->dest->free_in_buffer = state.free_in_buffer;
  164585. ASSIGN_STATE(entropy->saved, state.cur);
  164586. /* Update restart-interval state too */
  164587. if (cinfo->restart_interval) {
  164588. if (entropy->restarts_to_go == 0) {
  164589. entropy->restarts_to_go = cinfo->restart_interval;
  164590. entropy->next_restart_num++;
  164591. entropy->next_restart_num &= 7;
  164592. }
  164593. entropy->restarts_to_go--;
  164594. }
  164595. return TRUE;
  164596. }
  164597. /*
  164598. * Finish up at the end of a Huffman-compressed scan.
  164599. */
  164600. METHODDEF(void)
  164601. finish_pass_huff (j_compress_ptr cinfo)
  164602. {
  164603. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  164604. working_state state;
  164605. /* Load up working state ... flush_bits needs it */
  164606. state.next_output_byte = cinfo->dest->next_output_byte;
  164607. state.free_in_buffer = cinfo->dest->free_in_buffer;
  164608. ASSIGN_STATE(state.cur, entropy->saved);
  164609. state.cinfo = cinfo;
  164610. /* Flush out the last data */
  164611. if (! flush_bits(&state))
  164612. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  164613. /* Update state */
  164614. cinfo->dest->next_output_byte = state.next_output_byte;
  164615. cinfo->dest->free_in_buffer = state.free_in_buffer;
  164616. ASSIGN_STATE(entropy->saved, state.cur);
  164617. }
  164618. /*
  164619. * Huffman coding optimization.
  164620. *
  164621. * We first scan the supplied data and count the number of uses of each symbol
  164622. * that is to be Huffman-coded. (This process MUST agree with the code above.)
  164623. * Then we build a Huffman coding tree for the observed counts.
  164624. * Symbols which are not needed at all for the particular image are not
  164625. * assigned any code, which saves space in the DHT marker as well as in
  164626. * the compressed data.
  164627. */
  164628. #ifdef ENTROPY_OPT_SUPPORTED
  164629. /* Process a single block's worth of coefficients */
  164630. LOCAL(void)
  164631. htest_one_block (j_compress_ptr cinfo, JCOEFPTR block, int last_dc_val,
  164632. long dc_counts[], long ac_counts[])
  164633. {
  164634. register int temp;
  164635. register int nbits;
  164636. register int k, r;
  164637. /* Encode the DC coefficient difference per section F.1.2.1 */
  164638. temp = block[0] - last_dc_val;
  164639. if (temp < 0)
  164640. temp = -temp;
  164641. /* Find the number of bits needed for the magnitude of the coefficient */
  164642. nbits = 0;
  164643. while (temp) {
  164644. nbits++;
  164645. temp >>= 1;
  164646. }
  164647. /* Check for out-of-range coefficient values.
  164648. * Since we're encoding a difference, the range limit is twice as much.
  164649. */
  164650. if (nbits > MAX_COEF_BITS+1)
  164651. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  164652. /* Count the Huffman symbol for the number of bits */
  164653. dc_counts[nbits]++;
  164654. /* Encode the AC coefficients per section F.1.2.2 */
  164655. r = 0; /* r = run length of zeros */
  164656. for (k = 1; k < DCTSIZE2; k++) {
  164657. if ((temp = block[jpeg_natural_order[k]]) == 0) {
  164658. r++;
  164659. } else {
  164660. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  164661. while (r > 15) {
  164662. ac_counts[0xF0]++;
  164663. r -= 16;
  164664. }
  164665. /* Find the number of bits needed for the magnitude of the coefficient */
  164666. if (temp < 0)
  164667. temp = -temp;
  164668. /* Find the number of bits needed for the magnitude of the coefficient */
  164669. nbits = 1; /* there must be at least one 1 bit */
  164670. while ((temp >>= 1))
  164671. nbits++;
  164672. /* Check for out-of-range coefficient values */
  164673. if (nbits > MAX_COEF_BITS)
  164674. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  164675. /* Count Huffman symbol for run length / number of bits */
  164676. ac_counts[(r << 4) + nbits]++;
  164677. r = 0;
  164678. }
  164679. }
  164680. /* If the last coef(s) were zero, emit an end-of-block code */
  164681. if (r > 0)
  164682. ac_counts[0]++;
  164683. }
  164684. /*
  164685. * Trial-encode one MCU's worth of Huffman-compressed coefficients.
  164686. * No data is actually output, so no suspension return is possible.
  164687. */
  164688. METHODDEF(boolean)
  164689. encode_mcu_gather (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  164690. {
  164691. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  164692. int blkn, ci;
  164693. jpeg_component_info * compptr;
  164694. /* Take care of restart intervals if needed */
  164695. if (cinfo->restart_interval) {
  164696. if (entropy->restarts_to_go == 0) {
  164697. /* Re-initialize DC predictions to 0 */
  164698. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  164699. entropy->saved.last_dc_val[ci] = 0;
  164700. /* Update restart state */
  164701. entropy->restarts_to_go = cinfo->restart_interval;
  164702. }
  164703. entropy->restarts_to_go--;
  164704. }
  164705. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  164706. ci = cinfo->MCU_membership[blkn];
  164707. compptr = cinfo->cur_comp_info[ci];
  164708. htest_one_block(cinfo, MCU_data[blkn][0], entropy->saved.last_dc_val[ci],
  164709. entropy->dc_count_ptrs[compptr->dc_tbl_no],
  164710. entropy->ac_count_ptrs[compptr->ac_tbl_no]);
  164711. entropy->saved.last_dc_val[ci] = MCU_data[blkn][0][0];
  164712. }
  164713. return TRUE;
  164714. }
  164715. /*
  164716. * Generate the best Huffman code table for the given counts, fill htbl.
  164717. * Note this is also used by jcphuff.c.
  164718. *
  164719. * The JPEG standard requires that no symbol be assigned a codeword of all
  164720. * one bits (so that padding bits added at the end of a compressed segment
  164721. * can't look like a valid code). Because of the canonical ordering of
  164722. * codewords, this just means that there must be an unused slot in the
  164723. * longest codeword length category. Section K.2 of the JPEG spec suggests
  164724. * reserving such a slot by pretending that symbol 256 is a valid symbol
  164725. * with count 1. In theory that's not optimal; giving it count zero but
  164726. * including it in the symbol set anyway should give a better Huffman code.
  164727. * But the theoretically better code actually seems to come out worse in
  164728. * practice, because it produces more all-ones bytes (which incur stuffed
  164729. * zero bytes in the final file). In any case the difference is tiny.
  164730. *
  164731. * The JPEG standard requires Huffman codes to be no more than 16 bits long.
  164732. * If some symbols have a very small but nonzero probability, the Huffman tree
  164733. * must be adjusted to meet the code length restriction. We currently use
  164734. * the adjustment method suggested in JPEG section K.2. This method is *not*
  164735. * optimal; it may not choose the best possible limited-length code. But
  164736. * typically only very-low-frequency symbols will be given less-than-optimal
  164737. * lengths, so the code is almost optimal. Experimental comparisons against
  164738. * an optimal limited-length-code algorithm indicate that the difference is
  164739. * microscopic --- usually less than a hundredth of a percent of total size.
  164740. * So the extra complexity of an optimal algorithm doesn't seem worthwhile.
  164741. */
  164742. GLOBAL(void)
  164743. jpeg_gen_optimal_table (j_compress_ptr cinfo, JHUFF_TBL * htbl, long freq[])
  164744. {
  164745. #define MAX_CLEN 32 /* assumed maximum initial code length */
  164746. UINT8 bits[MAX_CLEN+1]; /* bits[k] = # of symbols with code length k */
  164747. int codesize[257]; /* codesize[k] = code length of symbol k */
  164748. int others[257]; /* next symbol in current branch of tree */
  164749. int c1, c2;
  164750. int p, i, j;
  164751. long v;
  164752. /* This algorithm is explained in section K.2 of the JPEG standard */
  164753. MEMZERO(bits, SIZEOF(bits));
  164754. MEMZERO(codesize, SIZEOF(codesize));
  164755. for (i = 0; i < 257; i++)
  164756. others[i] = -1; /* init links to empty */
  164757. freq[256] = 1; /* make sure 256 has a nonzero count */
  164758. /* Including the pseudo-symbol 256 in the Huffman procedure guarantees
  164759. * that no real symbol is given code-value of all ones, because 256
  164760. * will be placed last in the largest codeword category.
  164761. */
  164762. /* Huffman's basic algorithm to assign optimal code lengths to symbols */
  164763. for (;;) {
  164764. /* Find the smallest nonzero frequency, set c1 = its symbol */
  164765. /* In case of ties, take the larger symbol number */
  164766. c1 = -1;
  164767. v = 1000000000L;
  164768. for (i = 0; i <= 256; i++) {
  164769. if (freq[i] && freq[i] <= v) {
  164770. v = freq[i];
  164771. c1 = i;
  164772. }
  164773. }
  164774. /* Find the next smallest nonzero frequency, set c2 = its symbol */
  164775. /* In case of ties, take the larger symbol number */
  164776. c2 = -1;
  164777. v = 1000000000L;
  164778. for (i = 0; i <= 256; i++) {
  164779. if (freq[i] && freq[i] <= v && i != c1) {
  164780. v = freq[i];
  164781. c2 = i;
  164782. }
  164783. }
  164784. /* Done if we've merged everything into one frequency */
  164785. if (c2 < 0)
  164786. break;
  164787. /* Else merge the two counts/trees */
  164788. freq[c1] += freq[c2];
  164789. freq[c2] = 0;
  164790. /* Increment the codesize of everything in c1's tree branch */
  164791. codesize[c1]++;
  164792. while (others[c1] >= 0) {
  164793. c1 = others[c1];
  164794. codesize[c1]++;
  164795. }
  164796. others[c1] = c2; /* chain c2 onto c1's tree branch */
  164797. /* Increment the codesize of everything in c2's tree branch */
  164798. codesize[c2]++;
  164799. while (others[c2] >= 0) {
  164800. c2 = others[c2];
  164801. codesize[c2]++;
  164802. }
  164803. }
  164804. /* Now count the number of symbols of each code length */
  164805. for (i = 0; i <= 256; i++) {
  164806. if (codesize[i]) {
  164807. /* The JPEG standard seems to think that this can't happen, */
  164808. /* but I'm paranoid... */
  164809. if (codesize[i] > MAX_CLEN)
  164810. ERREXIT(cinfo, JERR_HUFF_CLEN_OVERFLOW);
  164811. bits[codesize[i]]++;
  164812. }
  164813. }
  164814. /* JPEG doesn't allow symbols with code lengths over 16 bits, so if the pure
  164815. * Huffman procedure assigned any such lengths, we must adjust the coding.
  164816. * Here is what the JPEG spec says about how this next bit works:
  164817. * Since symbols are paired for the longest Huffman code, the symbols are
  164818. * removed from this length category two at a time. The prefix for the pair
  164819. * (which is one bit shorter) is allocated to one of the pair; then,
  164820. * skipping the BITS entry for that prefix length, a code word from the next
  164821. * shortest nonzero BITS entry is converted into a prefix for two code words
  164822. * one bit longer.
  164823. */
  164824. for (i = MAX_CLEN; i > 16; i--) {
  164825. while (bits[i] > 0) {
  164826. j = i - 2; /* find length of new prefix to be used */
  164827. while (bits[j] == 0)
  164828. j--;
  164829. bits[i] -= 2; /* remove two symbols */
  164830. bits[i-1]++; /* one goes in this length */
  164831. bits[j+1] += 2; /* two new symbols in this length */
  164832. bits[j]--; /* symbol of this length is now a prefix */
  164833. }
  164834. }
  164835. /* Remove the count for the pseudo-symbol 256 from the largest codelength */
  164836. while (bits[i] == 0) /* find largest codelength still in use */
  164837. i--;
  164838. bits[i]--;
  164839. /* Return final symbol counts (only for lengths 0..16) */
  164840. MEMCOPY(htbl->bits, bits, SIZEOF(htbl->bits));
  164841. /* Return a list of the symbols sorted by code length */
  164842. /* It's not real clear to me why we don't need to consider the codelength
  164843. * changes made above, but the JPEG spec seems to think this works.
  164844. */
  164845. p = 0;
  164846. for (i = 1; i <= MAX_CLEN; i++) {
  164847. for (j = 0; j <= 255; j++) {
  164848. if (codesize[j] == i) {
  164849. htbl->huffval[p] = (UINT8) j;
  164850. p++;
  164851. }
  164852. }
  164853. }
  164854. /* Set sent_table FALSE so updated table will be written to JPEG file. */
  164855. htbl->sent_table = FALSE;
  164856. }
  164857. /*
  164858. * Finish up a statistics-gathering pass and create the new Huffman tables.
  164859. */
  164860. METHODDEF(void)
  164861. finish_pass_gather (j_compress_ptr cinfo)
  164862. {
  164863. huff_entropy_ptr entropy = (huff_entropy_ptr) cinfo->entropy;
  164864. int ci, dctbl, actbl;
  164865. jpeg_component_info * compptr;
  164866. JHUFF_TBL **htblptr;
  164867. boolean did_dc[NUM_HUFF_TBLS];
  164868. boolean did_ac[NUM_HUFF_TBLS];
  164869. /* It's important not to apply jpeg_gen_optimal_table more than once
  164870. * per table, because it clobbers the input frequency counts!
  164871. */
  164872. MEMZERO(did_dc, SIZEOF(did_dc));
  164873. MEMZERO(did_ac, SIZEOF(did_ac));
  164874. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  164875. compptr = cinfo->cur_comp_info[ci];
  164876. dctbl = compptr->dc_tbl_no;
  164877. actbl = compptr->ac_tbl_no;
  164878. if (! did_dc[dctbl]) {
  164879. htblptr = & cinfo->dc_huff_tbl_ptrs[dctbl];
  164880. if (*htblptr == NULL)
  164881. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164882. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->dc_count_ptrs[dctbl]);
  164883. did_dc[dctbl] = TRUE;
  164884. }
  164885. if (! did_ac[actbl]) {
  164886. htblptr = & cinfo->ac_huff_tbl_ptrs[actbl];
  164887. if (*htblptr == NULL)
  164888. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  164889. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->ac_count_ptrs[actbl]);
  164890. did_ac[actbl] = TRUE;
  164891. }
  164892. }
  164893. }
  164894. #endif /* ENTROPY_OPT_SUPPORTED */
  164895. /*
  164896. * Module initialization routine for Huffman entropy encoding.
  164897. */
  164898. GLOBAL(void)
  164899. jinit_huff_encoder (j_compress_ptr cinfo)
  164900. {
  164901. huff_entropy_ptr entropy;
  164902. int i;
  164903. entropy = (huff_entropy_ptr)
  164904. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  164905. SIZEOF(huff_entropy_encoder));
  164906. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  164907. entropy->pub.start_pass = start_pass_huff;
  164908. /* Mark tables unallocated */
  164909. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  164910. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  164911. #ifdef ENTROPY_OPT_SUPPORTED
  164912. entropy->dc_count_ptrs[i] = entropy->ac_count_ptrs[i] = NULL;
  164913. #endif
  164914. }
  164915. }
  164916. /********* End of inlined file: jchuff.c *********/
  164917. #undef emit_byte
  164918. /********* Start of inlined file: jcinit.c *********/
  164919. #define JPEG_INTERNALS
  164920. /*
  164921. * Master selection of compression modules.
  164922. * This is done once at the start of processing an image. We determine
  164923. * which modules will be used and give them appropriate initialization calls.
  164924. */
  164925. GLOBAL(void)
  164926. jinit_compress_master (j_compress_ptr cinfo)
  164927. {
  164928. /* Initialize master control (includes parameter checking/processing) */
  164929. jinit_c_master_control(cinfo, FALSE /* full compression */);
  164930. /* Preprocessing */
  164931. if (! cinfo->raw_data_in) {
  164932. jinit_color_converter(cinfo);
  164933. jinit_downsampler(cinfo);
  164934. jinit_c_prep_controller(cinfo, FALSE /* never need full buffer here */);
  164935. }
  164936. /* Forward DCT */
  164937. jinit_forward_dct(cinfo);
  164938. /* Entropy encoding: either Huffman or arithmetic coding. */
  164939. if (cinfo->arith_code) {
  164940. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  164941. } else {
  164942. if (cinfo->progressive_mode) {
  164943. #ifdef C_PROGRESSIVE_SUPPORTED
  164944. jinit_phuff_encoder(cinfo);
  164945. #else
  164946. ERREXIT(cinfo, JERR_NOT_COMPILED);
  164947. #endif
  164948. } else
  164949. jinit_huff_encoder(cinfo);
  164950. }
  164951. /* Need a full-image coefficient buffer in any multi-pass mode. */
  164952. jinit_c_coef_controller(cinfo,
  164953. (boolean) (cinfo->num_scans > 1 || cinfo->optimize_coding));
  164954. jinit_c_main_controller(cinfo, FALSE /* never need full buffer here */);
  164955. jinit_marker_writer(cinfo);
  164956. /* We can now tell the memory manager to allocate virtual arrays. */
  164957. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  164958. /* Write the datastream header (SOI) immediately.
  164959. * Frame and scan headers are postponed till later.
  164960. * This lets application insert special markers after the SOI.
  164961. */
  164962. (*cinfo->marker->write_file_header) (cinfo);
  164963. }
  164964. /********* End of inlined file: jcinit.c *********/
  164965. /********* Start of inlined file: jcmainct.c *********/
  164966. #define JPEG_INTERNALS
  164967. /* Note: currently, there is no operating mode in which a full-image buffer
  164968. * is needed at this step. If there were, that mode could not be used with
  164969. * "raw data" input, since this module is bypassed in that case. However,
  164970. * we've left the code here for possible use in special applications.
  164971. */
  164972. #undef FULL_MAIN_BUFFER_SUPPORTED
  164973. /* Private buffer controller object */
  164974. typedef struct {
  164975. struct jpeg_c_main_controller pub; /* public fields */
  164976. JDIMENSION cur_iMCU_row; /* number of current iMCU row */
  164977. JDIMENSION rowgroup_ctr; /* counts row groups received in iMCU row */
  164978. boolean suspended; /* remember if we suspended output */
  164979. J_BUF_MODE pass_mode; /* current operating mode */
  164980. /* If using just a strip buffer, this points to the entire set of buffers
  164981. * (we allocate one for each component). In the full-image case, this
  164982. * points to the currently accessible strips of the virtual arrays.
  164983. */
  164984. JSAMPARRAY buffer[MAX_COMPONENTS];
  164985. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164986. /* If using full-image storage, this array holds pointers to virtual-array
  164987. * control blocks for each component. Unused if not full-image storage.
  164988. */
  164989. jvirt_sarray_ptr whole_image[MAX_COMPONENTS];
  164990. #endif
  164991. } my_main_controller;
  164992. typedef my_main_controller * my_main_ptr;
  164993. /* Forward declarations */
  164994. METHODDEF(void) process_data_simple_main
  164995. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  164996. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  164997. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  164998. METHODDEF(void) process_data_buffer_main
  164999. JPP((j_compress_ptr cinfo, JSAMPARRAY input_buf,
  165000. JDIMENSION *in_row_ctr, JDIMENSION in_rows_avail));
  165001. #endif
  165002. /*
  165003. * Initialize for a processing pass.
  165004. */
  165005. METHODDEF(void)
  165006. start_pass_main (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  165007. {
  165008. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  165009. /* Do nothing in raw-data mode. */
  165010. if (cinfo->raw_data_in)
  165011. return;
  165012. main_->cur_iMCU_row = 0; /* initialize counters */
  165013. main_->rowgroup_ctr = 0;
  165014. main_->suspended = FALSE;
  165015. main_->pass_mode = pass_mode; /* save mode for use by process_data */
  165016. switch (pass_mode) {
  165017. case JBUF_PASS_THRU:
  165018. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  165019. if (main_->whole_image[0] != NULL)
  165020. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165021. #endif
  165022. main_->pub.process_data = process_data_simple_main;
  165023. break;
  165024. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  165025. case JBUF_SAVE_SOURCE:
  165026. case JBUF_CRANK_DEST:
  165027. case JBUF_SAVE_AND_PASS:
  165028. if (main_->whole_image[0] == NULL)
  165029. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165030. main_->pub.process_data = process_data_buffer_main;
  165031. break;
  165032. #endif
  165033. default:
  165034. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165035. break;
  165036. }
  165037. }
  165038. /*
  165039. * Process some data.
  165040. * This routine handles the simple pass-through mode,
  165041. * where we have only a strip buffer.
  165042. */
  165043. METHODDEF(void)
  165044. process_data_simple_main (j_compress_ptr cinfo,
  165045. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  165046. JDIMENSION in_rows_avail)
  165047. {
  165048. my_main_ptr main_ = (my_main_ptr) cinfo->main;
  165049. while (main_->cur_iMCU_row < cinfo->total_iMCU_rows) {
  165050. /* Read input data if we haven't filled the main buffer yet */
  165051. if (main_->rowgroup_ctr < DCTSIZE)
  165052. (*cinfo->prep->pre_process_data) (cinfo,
  165053. input_buf, in_row_ctr, in_rows_avail,
  165054. main_->buffer, &main_->rowgroup_ctr,
  165055. (JDIMENSION) DCTSIZE);
  165056. /* If we don't have a full iMCU row buffered, return to application for
  165057. * more data. Note that preprocessor will always pad to fill the iMCU row
  165058. * at the bottom of the image.
  165059. */
  165060. if (main_->rowgroup_ctr != DCTSIZE)
  165061. return;
  165062. /* Send the completed row to the compressor */
  165063. if (! (*cinfo->coef->compress_data) (cinfo, main_->buffer)) {
  165064. /* If compressor did not consume the whole row, then we must need to
  165065. * suspend processing and return to the application. In this situation
  165066. * we pretend we didn't yet consume the last input row; otherwise, if
  165067. * it happened to be the last row of the image, the application would
  165068. * think we were done.
  165069. */
  165070. if (! main_->suspended) {
  165071. (*in_row_ctr)--;
  165072. main_->suspended = TRUE;
  165073. }
  165074. return;
  165075. }
  165076. /* We did finish the row. Undo our little suspension hack if a previous
  165077. * call suspended; then mark the main buffer empty.
  165078. */
  165079. if (main_->suspended) {
  165080. (*in_row_ctr)++;
  165081. main_->suspended = FALSE;
  165082. }
  165083. main_->rowgroup_ctr = 0;
  165084. main_->cur_iMCU_row++;
  165085. }
  165086. }
  165087. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  165088. /*
  165089. * Process some data.
  165090. * This routine handles all of the modes that use a full-size buffer.
  165091. */
  165092. METHODDEF(void)
  165093. process_data_buffer_main (j_compress_ptr cinfo,
  165094. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  165095. JDIMENSION in_rows_avail)
  165096. {
  165097. my_main_ptr main = (my_main_ptr) cinfo->main;
  165098. int ci;
  165099. jpeg_component_info *compptr;
  165100. boolean writing = (main->pass_mode != JBUF_CRANK_DEST);
  165101. while (main->cur_iMCU_row < cinfo->total_iMCU_rows) {
  165102. /* Realign the virtual buffers if at the start of an iMCU row. */
  165103. if (main->rowgroup_ctr == 0) {
  165104. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165105. ci++, compptr++) {
  165106. main->buffer[ci] = (*cinfo->mem->access_virt_sarray)
  165107. ((j_common_ptr) cinfo, main->whole_image[ci],
  165108. main->cur_iMCU_row * (compptr->v_samp_factor * DCTSIZE),
  165109. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE), writing);
  165110. }
  165111. /* In a read pass, pretend we just read some source data. */
  165112. if (! writing) {
  165113. *in_row_ctr += cinfo->max_v_samp_factor * DCTSIZE;
  165114. main->rowgroup_ctr = DCTSIZE;
  165115. }
  165116. }
  165117. /* If a write pass, read input data until the current iMCU row is full. */
  165118. /* Note: preprocessor will pad if necessary to fill the last iMCU row. */
  165119. if (writing) {
  165120. (*cinfo->prep->pre_process_data) (cinfo,
  165121. input_buf, in_row_ctr, in_rows_avail,
  165122. main->buffer, &main->rowgroup_ctr,
  165123. (JDIMENSION) DCTSIZE);
  165124. /* Return to application if we need more data to fill the iMCU row. */
  165125. if (main->rowgroup_ctr < DCTSIZE)
  165126. return;
  165127. }
  165128. /* Emit data, unless this is a sink-only pass. */
  165129. if (main->pass_mode != JBUF_SAVE_SOURCE) {
  165130. if (! (*cinfo->coef->compress_data) (cinfo, main->buffer)) {
  165131. /* If compressor did not consume the whole row, then we must need to
  165132. * suspend processing and return to the application. In this situation
  165133. * we pretend we didn't yet consume the last input row; otherwise, if
  165134. * it happened to be the last row of the image, the application would
  165135. * think we were done.
  165136. */
  165137. if (! main->suspended) {
  165138. (*in_row_ctr)--;
  165139. main->suspended = TRUE;
  165140. }
  165141. return;
  165142. }
  165143. /* We did finish the row. Undo our little suspension hack if a previous
  165144. * call suspended; then mark the main buffer empty.
  165145. */
  165146. if (main->suspended) {
  165147. (*in_row_ctr)++;
  165148. main->suspended = FALSE;
  165149. }
  165150. }
  165151. /* If get here, we are done with this iMCU row. Mark buffer empty. */
  165152. main->rowgroup_ctr = 0;
  165153. main->cur_iMCU_row++;
  165154. }
  165155. }
  165156. #endif /* FULL_MAIN_BUFFER_SUPPORTED */
  165157. /*
  165158. * Initialize main buffer controller.
  165159. */
  165160. GLOBAL(void)
  165161. jinit_c_main_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  165162. {
  165163. my_main_ptr main_;
  165164. int ci;
  165165. jpeg_component_info *compptr;
  165166. main_ = (my_main_ptr)
  165167. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165168. SIZEOF(my_main_controller));
  165169. cinfo->main = (struct jpeg_c_main_controller *) main_;
  165170. main_->pub.start_pass = start_pass_main;
  165171. /* We don't need to create a buffer in raw-data mode. */
  165172. if (cinfo->raw_data_in)
  165173. return;
  165174. /* Create the buffer. It holds downsampled data, so each component
  165175. * may be of a different size.
  165176. */
  165177. if (need_full_buffer) {
  165178. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  165179. /* Allocate a full-image virtual array for each component */
  165180. /* Note we pad the bottom to a multiple of the iMCU height */
  165181. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165182. ci++, compptr++) {
  165183. main->whole_image[ci] = (*cinfo->mem->request_virt_sarray)
  165184. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  165185. compptr->width_in_blocks * DCTSIZE,
  165186. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  165187. (long) compptr->v_samp_factor) * DCTSIZE,
  165188. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  165189. }
  165190. #else
  165191. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  165192. #endif
  165193. } else {
  165194. #ifdef FULL_MAIN_BUFFER_SUPPORTED
  165195. main_->whole_image[0] = NULL; /* flag for no virtual arrays */
  165196. #endif
  165197. /* Allocate a strip buffer for each component */
  165198. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165199. ci++, compptr++) {
  165200. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  165201. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165202. compptr->width_in_blocks * DCTSIZE,
  165203. (JDIMENSION) (compptr->v_samp_factor * DCTSIZE));
  165204. }
  165205. }
  165206. }
  165207. /********* End of inlined file: jcmainct.c *********/
  165208. /********* Start of inlined file: jcmarker.c *********/
  165209. #define JPEG_INTERNALS
  165210. /* Private state */
  165211. typedef struct {
  165212. struct jpeg_marker_writer pub; /* public fields */
  165213. unsigned int last_restart_interval; /* last DRI value emitted; 0 after SOI */
  165214. } my_marker_writer;
  165215. typedef my_marker_writer * my_marker_ptr;
  165216. /*
  165217. * Basic output routines.
  165218. *
  165219. * Note that we do not support suspension while writing a marker.
  165220. * Therefore, an application using suspension must ensure that there is
  165221. * enough buffer space for the initial markers (typ. 600-700 bytes) before
  165222. * calling jpeg_start_compress, and enough space to write the trailing EOI
  165223. * (a few bytes) before calling jpeg_finish_compress. Multipass compression
  165224. * modes are not supported at all with suspension, so those two are the only
  165225. * points where markers will be written.
  165226. */
  165227. LOCAL(void)
  165228. emit_byte (j_compress_ptr cinfo, int val)
  165229. /* Emit a byte */
  165230. {
  165231. struct jpeg_destination_mgr * dest = cinfo->dest;
  165232. *(dest->next_output_byte)++ = (JOCTET) val;
  165233. if (--dest->free_in_buffer == 0) {
  165234. if (! (*dest->empty_output_buffer) (cinfo))
  165235. ERREXIT(cinfo, JERR_CANT_SUSPEND);
  165236. }
  165237. }
  165238. LOCAL(void)
  165239. emit_marker (j_compress_ptr cinfo, JPEG_MARKER mark)
  165240. /* Emit a marker code */
  165241. {
  165242. emit_byte(cinfo, 0xFF);
  165243. emit_byte(cinfo, (int) mark);
  165244. }
  165245. LOCAL(void)
  165246. emit_2bytes (j_compress_ptr cinfo, int value)
  165247. /* Emit a 2-byte integer; these are always MSB first in JPEG files */
  165248. {
  165249. emit_byte(cinfo, (value >> 8) & 0xFF);
  165250. emit_byte(cinfo, value & 0xFF);
  165251. }
  165252. /*
  165253. * Routines to write specific marker types.
  165254. */
  165255. LOCAL(int)
  165256. emit_dqt (j_compress_ptr cinfo, int index)
  165257. /* Emit a DQT marker */
  165258. /* Returns the precision used (0 = 8bits, 1 = 16bits) for baseline checking */
  165259. {
  165260. JQUANT_TBL * qtbl = cinfo->quant_tbl_ptrs[index];
  165261. int prec;
  165262. int i;
  165263. if (qtbl == NULL)
  165264. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, index);
  165265. prec = 0;
  165266. for (i = 0; i < DCTSIZE2; i++) {
  165267. if (qtbl->quantval[i] > 255)
  165268. prec = 1;
  165269. }
  165270. if (! qtbl->sent_table) {
  165271. emit_marker(cinfo, M_DQT);
  165272. emit_2bytes(cinfo, prec ? DCTSIZE2*2 + 1 + 2 : DCTSIZE2 + 1 + 2);
  165273. emit_byte(cinfo, index + (prec<<4));
  165274. for (i = 0; i < DCTSIZE2; i++) {
  165275. /* The table entries must be emitted in zigzag order. */
  165276. unsigned int qval = qtbl->quantval[jpeg_natural_order[i]];
  165277. if (prec)
  165278. emit_byte(cinfo, (int) (qval >> 8));
  165279. emit_byte(cinfo, (int) (qval & 0xFF));
  165280. }
  165281. qtbl->sent_table = TRUE;
  165282. }
  165283. return prec;
  165284. }
  165285. LOCAL(void)
  165286. emit_dht (j_compress_ptr cinfo, int index, boolean is_ac)
  165287. /* Emit a DHT marker */
  165288. {
  165289. JHUFF_TBL * htbl;
  165290. int length, i;
  165291. if (is_ac) {
  165292. htbl = cinfo->ac_huff_tbl_ptrs[index];
  165293. index += 0x10; /* output index has AC bit set */
  165294. } else {
  165295. htbl = cinfo->dc_huff_tbl_ptrs[index];
  165296. }
  165297. if (htbl == NULL)
  165298. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, index);
  165299. if (! htbl->sent_table) {
  165300. emit_marker(cinfo, M_DHT);
  165301. length = 0;
  165302. for (i = 1; i <= 16; i++)
  165303. length += htbl->bits[i];
  165304. emit_2bytes(cinfo, length + 2 + 1 + 16);
  165305. emit_byte(cinfo, index);
  165306. for (i = 1; i <= 16; i++)
  165307. emit_byte(cinfo, htbl->bits[i]);
  165308. for (i = 0; i < length; i++)
  165309. emit_byte(cinfo, htbl->huffval[i]);
  165310. htbl->sent_table = TRUE;
  165311. }
  165312. }
  165313. LOCAL(void)
  165314. emit_dac (j_compress_ptr cinfo)
  165315. /* Emit a DAC marker */
  165316. /* Since the useful info is so small, we want to emit all the tables in */
  165317. /* one DAC marker. Therefore this routine does its own scan of the table. */
  165318. {
  165319. #ifdef C_ARITH_CODING_SUPPORTED
  165320. char dc_in_use[NUM_ARITH_TBLS];
  165321. char ac_in_use[NUM_ARITH_TBLS];
  165322. int length, i;
  165323. jpeg_component_info *compptr;
  165324. for (i = 0; i < NUM_ARITH_TBLS; i++)
  165325. dc_in_use[i] = ac_in_use[i] = 0;
  165326. for (i = 0; i < cinfo->comps_in_scan; i++) {
  165327. compptr = cinfo->cur_comp_info[i];
  165328. dc_in_use[compptr->dc_tbl_no] = 1;
  165329. ac_in_use[compptr->ac_tbl_no] = 1;
  165330. }
  165331. length = 0;
  165332. for (i = 0; i < NUM_ARITH_TBLS; i++)
  165333. length += dc_in_use[i] + ac_in_use[i];
  165334. emit_marker(cinfo, M_DAC);
  165335. emit_2bytes(cinfo, length*2 + 2);
  165336. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  165337. if (dc_in_use[i]) {
  165338. emit_byte(cinfo, i);
  165339. emit_byte(cinfo, cinfo->arith_dc_L[i] + (cinfo->arith_dc_U[i]<<4));
  165340. }
  165341. if (ac_in_use[i]) {
  165342. emit_byte(cinfo, i + 0x10);
  165343. emit_byte(cinfo, cinfo->arith_ac_K[i]);
  165344. }
  165345. }
  165346. #endif /* C_ARITH_CODING_SUPPORTED */
  165347. }
  165348. LOCAL(void)
  165349. emit_dri (j_compress_ptr cinfo)
  165350. /* Emit a DRI marker */
  165351. {
  165352. emit_marker(cinfo, M_DRI);
  165353. emit_2bytes(cinfo, 4); /* fixed length */
  165354. emit_2bytes(cinfo, (int) cinfo->restart_interval);
  165355. }
  165356. LOCAL(void)
  165357. emit_sof (j_compress_ptr cinfo, JPEG_MARKER code)
  165358. /* Emit a SOF marker */
  165359. {
  165360. int ci;
  165361. jpeg_component_info *compptr;
  165362. emit_marker(cinfo, code);
  165363. emit_2bytes(cinfo, 3 * cinfo->num_components + 2 + 5 + 1); /* length */
  165364. /* Make sure image isn't bigger than SOF field can handle */
  165365. if ((long) cinfo->image_height > 65535L ||
  165366. (long) cinfo->image_width > 65535L)
  165367. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) 65535);
  165368. emit_byte(cinfo, cinfo->data_precision);
  165369. emit_2bytes(cinfo, (int) cinfo->image_height);
  165370. emit_2bytes(cinfo, (int) cinfo->image_width);
  165371. emit_byte(cinfo, cinfo->num_components);
  165372. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165373. ci++, compptr++) {
  165374. emit_byte(cinfo, compptr->component_id);
  165375. emit_byte(cinfo, (compptr->h_samp_factor << 4) + compptr->v_samp_factor);
  165376. emit_byte(cinfo, compptr->quant_tbl_no);
  165377. }
  165378. }
  165379. LOCAL(void)
  165380. emit_sos (j_compress_ptr cinfo)
  165381. /* Emit a SOS marker */
  165382. {
  165383. int i, td, ta;
  165384. jpeg_component_info *compptr;
  165385. emit_marker(cinfo, M_SOS);
  165386. emit_2bytes(cinfo, 2 * cinfo->comps_in_scan + 2 + 1 + 3); /* length */
  165387. emit_byte(cinfo, cinfo->comps_in_scan);
  165388. for (i = 0; i < cinfo->comps_in_scan; i++) {
  165389. compptr = cinfo->cur_comp_info[i];
  165390. emit_byte(cinfo, compptr->component_id);
  165391. td = compptr->dc_tbl_no;
  165392. ta = compptr->ac_tbl_no;
  165393. if (cinfo->progressive_mode) {
  165394. /* Progressive mode: only DC or only AC tables are used in one scan;
  165395. * furthermore, Huffman coding of DC refinement uses no table at all.
  165396. * We emit 0 for unused field(s); this is recommended by the P&M text
  165397. * but does not seem to be specified in the standard.
  165398. */
  165399. if (cinfo->Ss == 0) {
  165400. ta = 0; /* DC scan */
  165401. if (cinfo->Ah != 0 && !cinfo->arith_code)
  165402. td = 0; /* no DC table either */
  165403. } else {
  165404. td = 0; /* AC scan */
  165405. }
  165406. }
  165407. emit_byte(cinfo, (td << 4) + ta);
  165408. }
  165409. emit_byte(cinfo, cinfo->Ss);
  165410. emit_byte(cinfo, cinfo->Se);
  165411. emit_byte(cinfo, (cinfo->Ah << 4) + cinfo->Al);
  165412. }
  165413. LOCAL(void)
  165414. emit_jfif_app0 (j_compress_ptr cinfo)
  165415. /* Emit a JFIF-compliant APP0 marker */
  165416. {
  165417. /*
  165418. * Length of APP0 block (2 bytes)
  165419. * Block ID (4 bytes - ASCII "JFIF")
  165420. * Zero byte (1 byte to terminate the ID string)
  165421. * Version Major, Minor (2 bytes - major first)
  165422. * Units (1 byte - 0x00 = none, 0x01 = inch, 0x02 = cm)
  165423. * Xdpu (2 bytes - dots per unit horizontal)
  165424. * Ydpu (2 bytes - dots per unit vertical)
  165425. * Thumbnail X size (1 byte)
  165426. * Thumbnail Y size (1 byte)
  165427. */
  165428. emit_marker(cinfo, M_APP0);
  165429. emit_2bytes(cinfo, 2 + 4 + 1 + 2 + 1 + 2 + 2 + 1 + 1); /* length */
  165430. emit_byte(cinfo, 0x4A); /* Identifier: ASCII "JFIF" */
  165431. emit_byte(cinfo, 0x46);
  165432. emit_byte(cinfo, 0x49);
  165433. emit_byte(cinfo, 0x46);
  165434. emit_byte(cinfo, 0);
  165435. emit_byte(cinfo, cinfo->JFIF_major_version); /* Version fields */
  165436. emit_byte(cinfo, cinfo->JFIF_minor_version);
  165437. emit_byte(cinfo, cinfo->density_unit); /* Pixel size information */
  165438. emit_2bytes(cinfo, (int) cinfo->X_density);
  165439. emit_2bytes(cinfo, (int) cinfo->Y_density);
  165440. emit_byte(cinfo, 0); /* No thumbnail image */
  165441. emit_byte(cinfo, 0);
  165442. }
  165443. LOCAL(void)
  165444. emit_adobe_app14 (j_compress_ptr cinfo)
  165445. /* Emit an Adobe APP14 marker */
  165446. {
  165447. /*
  165448. * Length of APP14 block (2 bytes)
  165449. * Block ID (5 bytes - ASCII "Adobe")
  165450. * Version Number (2 bytes - currently 100)
  165451. * Flags0 (2 bytes - currently 0)
  165452. * Flags1 (2 bytes - currently 0)
  165453. * Color transform (1 byte)
  165454. *
  165455. * Although Adobe TN 5116 mentions Version = 101, all the Adobe files
  165456. * now in circulation seem to use Version = 100, so that's what we write.
  165457. *
  165458. * We write the color transform byte as 1 if the JPEG color space is
  165459. * YCbCr, 2 if it's YCCK, 0 otherwise. Adobe's definition has to do with
  165460. * whether the encoder performed a transformation, which is pretty useless.
  165461. */
  165462. emit_marker(cinfo, M_APP14);
  165463. emit_2bytes(cinfo, 2 + 5 + 2 + 2 + 2 + 1); /* length */
  165464. emit_byte(cinfo, 0x41); /* Identifier: ASCII "Adobe" */
  165465. emit_byte(cinfo, 0x64);
  165466. emit_byte(cinfo, 0x6F);
  165467. emit_byte(cinfo, 0x62);
  165468. emit_byte(cinfo, 0x65);
  165469. emit_2bytes(cinfo, 100); /* Version */
  165470. emit_2bytes(cinfo, 0); /* Flags0 */
  165471. emit_2bytes(cinfo, 0); /* Flags1 */
  165472. switch (cinfo->jpeg_color_space) {
  165473. case JCS_YCbCr:
  165474. emit_byte(cinfo, 1); /* Color transform = 1 */
  165475. break;
  165476. case JCS_YCCK:
  165477. emit_byte(cinfo, 2); /* Color transform = 2 */
  165478. break;
  165479. default:
  165480. emit_byte(cinfo, 0); /* Color transform = 0 */
  165481. break;
  165482. }
  165483. }
  165484. /*
  165485. * These routines allow writing an arbitrary marker with parameters.
  165486. * The only intended use is to emit COM or APPn markers after calling
  165487. * write_file_header and before calling write_frame_header.
  165488. * Other uses are not guaranteed to produce desirable results.
  165489. * Counting the parameter bytes properly is the caller's responsibility.
  165490. */
  165491. METHODDEF(void)
  165492. write_marker_header (j_compress_ptr cinfo, int marker, unsigned int datalen)
  165493. /* Emit an arbitrary marker header */
  165494. {
  165495. if (datalen > (unsigned int) 65533) /* safety check */
  165496. ERREXIT(cinfo, JERR_BAD_LENGTH);
  165497. emit_marker(cinfo, (JPEG_MARKER) marker);
  165498. emit_2bytes(cinfo, (int) (datalen + 2)); /* total length */
  165499. }
  165500. METHODDEF(void)
  165501. write_marker_byte (j_compress_ptr cinfo, int val)
  165502. /* Emit one byte of marker parameters following write_marker_header */
  165503. {
  165504. emit_byte(cinfo, val);
  165505. }
  165506. /*
  165507. * Write datastream header.
  165508. * This consists of an SOI and optional APPn markers.
  165509. * We recommend use of the JFIF marker, but not the Adobe marker,
  165510. * when using YCbCr or grayscale data. The JFIF marker should NOT
  165511. * be used for any other JPEG colorspace. The Adobe marker is helpful
  165512. * to distinguish RGB, CMYK, and YCCK colorspaces.
  165513. * Note that an application can write additional header markers after
  165514. * jpeg_start_compress returns.
  165515. */
  165516. METHODDEF(void)
  165517. write_file_header (j_compress_ptr cinfo)
  165518. {
  165519. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  165520. emit_marker(cinfo, M_SOI); /* first the SOI */
  165521. /* SOI is defined to reset restart interval to 0 */
  165522. marker->last_restart_interval = 0;
  165523. if (cinfo->write_JFIF_header) /* next an optional JFIF APP0 */
  165524. emit_jfif_app0(cinfo);
  165525. if (cinfo->write_Adobe_marker) /* next an optional Adobe APP14 */
  165526. emit_adobe_app14(cinfo);
  165527. }
  165528. /*
  165529. * Write frame header.
  165530. * This consists of DQT and SOFn markers.
  165531. * Note that we do not emit the SOF until we have emitted the DQT(s).
  165532. * This avoids compatibility problems with incorrect implementations that
  165533. * try to error-check the quant table numbers as soon as they see the SOF.
  165534. */
  165535. METHODDEF(void)
  165536. write_frame_header (j_compress_ptr cinfo)
  165537. {
  165538. int ci, prec;
  165539. boolean is_baseline;
  165540. jpeg_component_info *compptr;
  165541. /* Emit DQT for each quantization table.
  165542. * Note that emit_dqt() suppresses any duplicate tables.
  165543. */
  165544. prec = 0;
  165545. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165546. ci++, compptr++) {
  165547. prec += emit_dqt(cinfo, compptr->quant_tbl_no);
  165548. }
  165549. /* now prec is nonzero iff there are any 16-bit quant tables. */
  165550. /* Check for a non-baseline specification.
  165551. * Note we assume that Huffman table numbers won't be changed later.
  165552. */
  165553. if (cinfo->arith_code || cinfo->progressive_mode ||
  165554. cinfo->data_precision != 8) {
  165555. is_baseline = FALSE;
  165556. } else {
  165557. is_baseline = TRUE;
  165558. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165559. ci++, compptr++) {
  165560. if (compptr->dc_tbl_no > 1 || compptr->ac_tbl_no > 1)
  165561. is_baseline = FALSE;
  165562. }
  165563. if (prec && is_baseline) {
  165564. is_baseline = FALSE;
  165565. /* If it's baseline except for quantizer size, warn the user */
  165566. TRACEMS(cinfo, 0, JTRC_16BIT_TABLES);
  165567. }
  165568. }
  165569. /* Emit the proper SOF marker */
  165570. if (cinfo->arith_code) {
  165571. emit_sof(cinfo, M_SOF9); /* SOF code for arithmetic coding */
  165572. } else {
  165573. if (cinfo->progressive_mode)
  165574. emit_sof(cinfo, M_SOF2); /* SOF code for progressive Huffman */
  165575. else if (is_baseline)
  165576. emit_sof(cinfo, M_SOF0); /* SOF code for baseline implementation */
  165577. else
  165578. emit_sof(cinfo, M_SOF1); /* SOF code for non-baseline Huffman file */
  165579. }
  165580. }
  165581. /*
  165582. * Write scan header.
  165583. * This consists of DHT or DAC markers, optional DRI, and SOS.
  165584. * Compressed data will be written following the SOS.
  165585. */
  165586. METHODDEF(void)
  165587. write_scan_header (j_compress_ptr cinfo)
  165588. {
  165589. my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
  165590. int i;
  165591. jpeg_component_info *compptr;
  165592. if (cinfo->arith_code) {
  165593. /* Emit arith conditioning info. We may have some duplication
  165594. * if the file has multiple scans, but it's so small it's hardly
  165595. * worth worrying about.
  165596. */
  165597. emit_dac(cinfo);
  165598. } else {
  165599. /* Emit Huffman tables.
  165600. * Note that emit_dht() suppresses any duplicate tables.
  165601. */
  165602. for (i = 0; i < cinfo->comps_in_scan; i++) {
  165603. compptr = cinfo->cur_comp_info[i];
  165604. if (cinfo->progressive_mode) {
  165605. /* Progressive mode: only DC or only AC tables are used in one scan */
  165606. if (cinfo->Ss == 0) {
  165607. if (cinfo->Ah == 0) /* DC needs no table for refinement scan */
  165608. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  165609. } else {
  165610. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  165611. }
  165612. } else {
  165613. /* Sequential mode: need both DC and AC tables */
  165614. emit_dht(cinfo, compptr->dc_tbl_no, FALSE);
  165615. emit_dht(cinfo, compptr->ac_tbl_no, TRUE);
  165616. }
  165617. }
  165618. }
  165619. /* Emit DRI if required --- note that DRI value could change for each scan.
  165620. * We avoid wasting space with unnecessary DRIs, however.
  165621. */
  165622. if (cinfo->restart_interval != marker->last_restart_interval) {
  165623. emit_dri(cinfo);
  165624. marker->last_restart_interval = cinfo->restart_interval;
  165625. }
  165626. emit_sos(cinfo);
  165627. }
  165628. /*
  165629. * Write datastream trailer.
  165630. */
  165631. METHODDEF(void)
  165632. write_file_trailer (j_compress_ptr cinfo)
  165633. {
  165634. emit_marker(cinfo, M_EOI);
  165635. }
  165636. /*
  165637. * Write an abbreviated table-specification datastream.
  165638. * This consists of SOI, DQT and DHT tables, and EOI.
  165639. * Any table that is defined and not marked sent_table = TRUE will be
  165640. * emitted. Note that all tables will be marked sent_table = TRUE at exit.
  165641. */
  165642. METHODDEF(void)
  165643. write_tables_only (j_compress_ptr cinfo)
  165644. {
  165645. int i;
  165646. emit_marker(cinfo, M_SOI);
  165647. for (i = 0; i < NUM_QUANT_TBLS; i++) {
  165648. if (cinfo->quant_tbl_ptrs[i] != NULL)
  165649. (void) emit_dqt(cinfo, i);
  165650. }
  165651. if (! cinfo->arith_code) {
  165652. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  165653. if (cinfo->dc_huff_tbl_ptrs[i] != NULL)
  165654. emit_dht(cinfo, i, FALSE);
  165655. if (cinfo->ac_huff_tbl_ptrs[i] != NULL)
  165656. emit_dht(cinfo, i, TRUE);
  165657. }
  165658. }
  165659. emit_marker(cinfo, M_EOI);
  165660. }
  165661. /*
  165662. * Initialize the marker writer module.
  165663. */
  165664. GLOBAL(void)
  165665. jinit_marker_writer (j_compress_ptr cinfo)
  165666. {
  165667. my_marker_ptr marker;
  165668. /* Create the subobject */
  165669. marker = (my_marker_ptr)
  165670. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  165671. SIZEOF(my_marker_writer));
  165672. cinfo->marker = (struct jpeg_marker_writer *) marker;
  165673. /* Initialize method pointers */
  165674. marker->pub.write_file_header = write_file_header;
  165675. marker->pub.write_frame_header = write_frame_header;
  165676. marker->pub.write_scan_header = write_scan_header;
  165677. marker->pub.write_file_trailer = write_file_trailer;
  165678. marker->pub.write_tables_only = write_tables_only;
  165679. marker->pub.write_marker_header = write_marker_header;
  165680. marker->pub.write_marker_byte = write_marker_byte;
  165681. /* Initialize private state */
  165682. marker->last_restart_interval = 0;
  165683. }
  165684. /********* End of inlined file: jcmarker.c *********/
  165685. /********* Start of inlined file: jcmaster.c *********/
  165686. #define JPEG_INTERNALS
  165687. /* Private state */
  165688. typedef enum {
  165689. main_pass, /* input data, also do first output step */
  165690. huff_opt_pass, /* Huffman code optimization pass */
  165691. output_pass /* data output pass */
  165692. } c_pass_type;
  165693. typedef struct {
  165694. struct jpeg_comp_master pub; /* public fields */
  165695. c_pass_type pass_type; /* the type of the current pass */
  165696. int pass_number; /* # of passes completed */
  165697. int total_passes; /* total # of passes needed */
  165698. int scan_number; /* current index in scan_info[] */
  165699. } my_comp_master;
  165700. typedef my_comp_master * my_master_ptr;
  165701. /*
  165702. * Support routines that do various essential calculations.
  165703. */
  165704. LOCAL(void)
  165705. initial_setup (j_compress_ptr cinfo)
  165706. /* Do computations that are needed before master selection phase */
  165707. {
  165708. int ci;
  165709. jpeg_component_info *compptr;
  165710. long samplesperrow;
  165711. JDIMENSION jd_samplesperrow;
  165712. /* Sanity check on image dimensions */
  165713. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  165714. || cinfo->num_components <= 0 || cinfo->input_components <= 0)
  165715. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  165716. /* Make sure image isn't bigger than I can handle */
  165717. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  165718. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  165719. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  165720. /* Width of an input scanline must be representable as JDIMENSION. */
  165721. samplesperrow = (long) cinfo->image_width * (long) cinfo->input_components;
  165722. jd_samplesperrow = (JDIMENSION) samplesperrow;
  165723. if ((long) jd_samplesperrow != samplesperrow)
  165724. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  165725. /* For now, precision must match compiled-in value... */
  165726. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  165727. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  165728. /* Check that number of components won't exceed internal array sizes */
  165729. if (cinfo->num_components > MAX_COMPONENTS)
  165730. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165731. MAX_COMPONENTS);
  165732. /* Compute maximum sampling factors; check factor validity */
  165733. cinfo->max_h_samp_factor = 1;
  165734. cinfo->max_v_samp_factor = 1;
  165735. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165736. ci++, compptr++) {
  165737. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  165738. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  165739. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  165740. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  165741. compptr->h_samp_factor);
  165742. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  165743. compptr->v_samp_factor);
  165744. }
  165745. /* Compute dimensions of components */
  165746. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  165747. ci++, compptr++) {
  165748. /* Fill in the correct component_index value; don't rely on application */
  165749. compptr->component_index = ci;
  165750. /* For compression, we never do DCT scaling. */
  165751. compptr->DCT_scaled_size = DCTSIZE;
  165752. /* Size in DCT blocks */
  165753. compptr->width_in_blocks = (JDIMENSION)
  165754. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  165755. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  165756. compptr->height_in_blocks = (JDIMENSION)
  165757. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  165758. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  165759. /* Size in samples */
  165760. compptr->downsampled_width = (JDIMENSION)
  165761. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  165762. (long) cinfo->max_h_samp_factor);
  165763. compptr->downsampled_height = (JDIMENSION)
  165764. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  165765. (long) cinfo->max_v_samp_factor);
  165766. /* Mark component needed (this flag isn't actually used for compression) */
  165767. compptr->component_needed = TRUE;
  165768. }
  165769. /* Compute number of fully interleaved MCU rows (number of times that
  165770. * main controller will call coefficient controller).
  165771. */
  165772. cinfo->total_iMCU_rows = (JDIMENSION)
  165773. jdiv_round_up((long) cinfo->image_height,
  165774. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165775. }
  165776. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165777. LOCAL(void)
  165778. validate_script (j_compress_ptr cinfo)
  165779. /* Verify that the scan script in cinfo->scan_info[] is valid; also
  165780. * determine whether it uses progressive JPEG, and set cinfo->progressive_mode.
  165781. */
  165782. {
  165783. const jpeg_scan_info * scanptr;
  165784. int scanno, ncomps, ci, coefi, thisi;
  165785. int Ss, Se, Ah, Al;
  165786. boolean component_sent[MAX_COMPONENTS];
  165787. #ifdef C_PROGRESSIVE_SUPPORTED
  165788. int * last_bitpos_ptr;
  165789. int last_bitpos[MAX_COMPONENTS][DCTSIZE2];
  165790. /* -1 until that coefficient has been seen; then last Al for it */
  165791. #endif
  165792. if (cinfo->num_scans <= 0)
  165793. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, 0);
  165794. /* For sequential JPEG, all scans must have Ss=0, Se=DCTSIZE2-1;
  165795. * for progressive JPEG, no scan can have this.
  165796. */
  165797. scanptr = cinfo->scan_info;
  165798. if (scanptr->Ss != 0 || scanptr->Se != DCTSIZE2-1) {
  165799. #ifdef C_PROGRESSIVE_SUPPORTED
  165800. cinfo->progressive_mode = TRUE;
  165801. last_bitpos_ptr = & last_bitpos[0][0];
  165802. for (ci = 0; ci < cinfo->num_components; ci++)
  165803. for (coefi = 0; coefi < DCTSIZE2; coefi++)
  165804. *last_bitpos_ptr++ = -1;
  165805. #else
  165806. ERREXIT(cinfo, JERR_NOT_COMPILED);
  165807. #endif
  165808. } else {
  165809. cinfo->progressive_mode = FALSE;
  165810. for (ci = 0; ci < cinfo->num_components; ci++)
  165811. component_sent[ci] = FALSE;
  165812. }
  165813. for (scanno = 1; scanno <= cinfo->num_scans; scanptr++, scanno++) {
  165814. /* Validate component indexes */
  165815. ncomps = scanptr->comps_in_scan;
  165816. if (ncomps <= 0 || ncomps > MAX_COMPS_IN_SCAN)
  165817. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, ncomps, MAX_COMPS_IN_SCAN);
  165818. for (ci = 0; ci < ncomps; ci++) {
  165819. thisi = scanptr->component_index[ci];
  165820. if (thisi < 0 || thisi >= cinfo->num_components)
  165821. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165822. /* Components must appear in SOF order within each scan */
  165823. if (ci > 0 && thisi <= scanptr->component_index[ci-1])
  165824. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165825. }
  165826. /* Validate progression parameters */
  165827. Ss = scanptr->Ss;
  165828. Se = scanptr->Se;
  165829. Ah = scanptr->Ah;
  165830. Al = scanptr->Al;
  165831. if (cinfo->progressive_mode) {
  165832. #ifdef C_PROGRESSIVE_SUPPORTED
  165833. /* The JPEG spec simply gives the ranges 0..13 for Ah and Al, but that
  165834. * seems wrong: the upper bound ought to depend on data precision.
  165835. * Perhaps they really meant 0..N+1 for N-bit precision.
  165836. * Here we allow 0..10 for 8-bit data; Al larger than 10 results in
  165837. * out-of-range reconstructed DC values during the first DC scan,
  165838. * which might cause problems for some decoders.
  165839. */
  165840. #if BITS_IN_JSAMPLE == 8
  165841. #define MAX_AH_AL 10
  165842. #else
  165843. #define MAX_AH_AL 13
  165844. #endif
  165845. if (Ss < 0 || Ss >= DCTSIZE2 || Se < Ss || Se >= DCTSIZE2 ||
  165846. Ah < 0 || Ah > MAX_AH_AL || Al < 0 || Al > MAX_AH_AL)
  165847. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165848. if (Ss == 0) {
  165849. if (Se != 0) /* DC and AC together not OK */
  165850. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165851. } else {
  165852. if (ncomps != 1) /* AC scans must be for only one component */
  165853. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165854. }
  165855. for (ci = 0; ci < ncomps; ci++) {
  165856. last_bitpos_ptr = & last_bitpos[scanptr->component_index[ci]][0];
  165857. if (Ss != 0 && last_bitpos_ptr[0] < 0) /* AC without prior DC scan */
  165858. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165859. for (coefi = Ss; coefi <= Se; coefi++) {
  165860. if (last_bitpos_ptr[coefi] < 0) {
  165861. /* first scan of this coefficient */
  165862. if (Ah != 0)
  165863. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165864. } else {
  165865. /* not first scan */
  165866. if (Ah != last_bitpos_ptr[coefi] || Al != Ah-1)
  165867. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165868. }
  165869. last_bitpos_ptr[coefi] = Al;
  165870. }
  165871. }
  165872. #endif
  165873. } else {
  165874. /* For sequential JPEG, all progression parameters must be these: */
  165875. if (Ss != 0 || Se != DCTSIZE2-1 || Ah != 0 || Al != 0)
  165876. ERREXIT1(cinfo, JERR_BAD_PROG_SCRIPT, scanno);
  165877. /* Make sure components are not sent twice */
  165878. for (ci = 0; ci < ncomps; ci++) {
  165879. thisi = scanptr->component_index[ci];
  165880. if (component_sent[thisi])
  165881. ERREXIT1(cinfo, JERR_BAD_SCAN_SCRIPT, scanno);
  165882. component_sent[thisi] = TRUE;
  165883. }
  165884. }
  165885. }
  165886. /* Now verify that everything got sent. */
  165887. if (cinfo->progressive_mode) {
  165888. #ifdef C_PROGRESSIVE_SUPPORTED
  165889. /* For progressive mode, we only check that at least some DC data
  165890. * got sent for each component; the spec does not require that all bits
  165891. * of all coefficients be transmitted. Would it be wiser to enforce
  165892. * transmission of all coefficient bits??
  165893. */
  165894. for (ci = 0; ci < cinfo->num_components; ci++) {
  165895. if (last_bitpos[ci][0] < 0)
  165896. ERREXIT(cinfo, JERR_MISSING_DATA);
  165897. }
  165898. #endif
  165899. } else {
  165900. for (ci = 0; ci < cinfo->num_components; ci++) {
  165901. if (! component_sent[ci])
  165902. ERREXIT(cinfo, JERR_MISSING_DATA);
  165903. }
  165904. }
  165905. }
  165906. #endif /* C_MULTISCAN_FILES_SUPPORTED */
  165907. LOCAL(void)
  165908. select_scan_parameters (j_compress_ptr cinfo)
  165909. /* Set up the scan parameters for the current scan */
  165910. {
  165911. int ci;
  165912. #ifdef C_MULTISCAN_FILES_SUPPORTED
  165913. if (cinfo->scan_info != NULL) {
  165914. /* Prepare for current scan --- the script is already validated */
  165915. my_master_ptr master = (my_master_ptr) cinfo->master;
  165916. const jpeg_scan_info * scanptr = cinfo->scan_info + master->scan_number;
  165917. cinfo->comps_in_scan = scanptr->comps_in_scan;
  165918. for (ci = 0; ci < scanptr->comps_in_scan; ci++) {
  165919. cinfo->cur_comp_info[ci] =
  165920. &cinfo->comp_info[scanptr->component_index[ci]];
  165921. }
  165922. cinfo->Ss = scanptr->Ss;
  165923. cinfo->Se = scanptr->Se;
  165924. cinfo->Ah = scanptr->Ah;
  165925. cinfo->Al = scanptr->Al;
  165926. }
  165927. else
  165928. #endif
  165929. {
  165930. /* Prepare for single sequential-JPEG scan containing all components */
  165931. if (cinfo->num_components > MAX_COMPS_IN_SCAN)
  165932. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  165933. MAX_COMPS_IN_SCAN);
  165934. cinfo->comps_in_scan = cinfo->num_components;
  165935. for (ci = 0; ci < cinfo->num_components; ci++) {
  165936. cinfo->cur_comp_info[ci] = &cinfo->comp_info[ci];
  165937. }
  165938. cinfo->Ss = 0;
  165939. cinfo->Se = DCTSIZE2-1;
  165940. cinfo->Ah = 0;
  165941. cinfo->Al = 0;
  165942. }
  165943. }
  165944. LOCAL(void)
  165945. per_scan_setup (j_compress_ptr cinfo)
  165946. /* Do computations that are needed before processing a JPEG scan */
  165947. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] are already set */
  165948. {
  165949. int ci, mcublks, tmp;
  165950. jpeg_component_info *compptr;
  165951. if (cinfo->comps_in_scan == 1) {
  165952. /* Noninterleaved (single-component) scan */
  165953. compptr = cinfo->cur_comp_info[0];
  165954. /* Overall image size in MCUs */
  165955. cinfo->MCUs_per_row = compptr->width_in_blocks;
  165956. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  165957. /* For noninterleaved scan, always one block per MCU */
  165958. compptr->MCU_width = 1;
  165959. compptr->MCU_height = 1;
  165960. compptr->MCU_blocks = 1;
  165961. compptr->MCU_sample_width = DCTSIZE;
  165962. compptr->last_col_width = 1;
  165963. /* For noninterleaved scans, it is convenient to define last_row_height
  165964. * as the number of block rows present in the last iMCU row.
  165965. */
  165966. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  165967. if (tmp == 0) tmp = compptr->v_samp_factor;
  165968. compptr->last_row_height = tmp;
  165969. /* Prepare array describing MCU composition */
  165970. cinfo->blocks_in_MCU = 1;
  165971. cinfo->MCU_membership[0] = 0;
  165972. } else {
  165973. /* Interleaved (multi-component) scan */
  165974. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  165975. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  165976. MAX_COMPS_IN_SCAN);
  165977. /* Overall image size in MCUs */
  165978. cinfo->MCUs_per_row = (JDIMENSION)
  165979. jdiv_round_up((long) cinfo->image_width,
  165980. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  165981. cinfo->MCU_rows_in_scan = (JDIMENSION)
  165982. jdiv_round_up((long) cinfo->image_height,
  165983. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  165984. cinfo->blocks_in_MCU = 0;
  165985. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  165986. compptr = cinfo->cur_comp_info[ci];
  165987. /* Sampling factors give # of blocks of component in each MCU */
  165988. compptr->MCU_width = compptr->h_samp_factor;
  165989. compptr->MCU_height = compptr->v_samp_factor;
  165990. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  165991. compptr->MCU_sample_width = compptr->MCU_width * DCTSIZE;
  165992. /* Figure number of non-dummy blocks in last MCU column & row */
  165993. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  165994. if (tmp == 0) tmp = compptr->MCU_width;
  165995. compptr->last_col_width = tmp;
  165996. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  165997. if (tmp == 0) tmp = compptr->MCU_height;
  165998. compptr->last_row_height = tmp;
  165999. /* Prepare array describing MCU composition */
  166000. mcublks = compptr->MCU_blocks;
  166001. if (cinfo->blocks_in_MCU + mcublks > C_MAX_BLOCKS_IN_MCU)
  166002. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  166003. while (mcublks-- > 0) {
  166004. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  166005. }
  166006. }
  166007. }
  166008. /* Convert restart specified in rows to actual MCU count. */
  166009. /* Note that count must fit in 16 bits, so we provide limiting. */
  166010. if (cinfo->restart_in_rows > 0) {
  166011. long nominal = (long) cinfo->restart_in_rows * (long) cinfo->MCUs_per_row;
  166012. cinfo->restart_interval = (unsigned int) MIN(nominal, 65535L);
  166013. }
  166014. }
  166015. /*
  166016. * Per-pass setup.
  166017. * This is called at the beginning of each pass. We determine which modules
  166018. * will be active during this pass and give them appropriate start_pass calls.
  166019. * We also set is_last_pass to indicate whether any more passes will be
  166020. * required.
  166021. */
  166022. METHODDEF(void)
  166023. prepare_for_pass (j_compress_ptr cinfo)
  166024. {
  166025. my_master_ptr master = (my_master_ptr) cinfo->master;
  166026. switch (master->pass_type) {
  166027. case main_pass:
  166028. /* Initial pass: will collect input data, and do either Huffman
  166029. * optimization or data output for the first scan.
  166030. */
  166031. select_scan_parameters(cinfo);
  166032. per_scan_setup(cinfo);
  166033. if (! cinfo->raw_data_in) {
  166034. (*cinfo->cconvert->start_pass) (cinfo);
  166035. (*cinfo->downsample->start_pass) (cinfo);
  166036. (*cinfo->prep->start_pass) (cinfo, JBUF_PASS_THRU);
  166037. }
  166038. (*cinfo->fdct->start_pass) (cinfo);
  166039. (*cinfo->entropy->start_pass) (cinfo, cinfo->optimize_coding);
  166040. (*cinfo->coef->start_pass) (cinfo,
  166041. (master->total_passes > 1 ?
  166042. JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  166043. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  166044. if (cinfo->optimize_coding) {
  166045. /* No immediate data output; postpone writing frame/scan headers */
  166046. master->pub.call_pass_startup = FALSE;
  166047. } else {
  166048. /* Will write frame/scan headers at first jpeg_write_scanlines call */
  166049. master->pub.call_pass_startup = TRUE;
  166050. }
  166051. break;
  166052. #ifdef ENTROPY_OPT_SUPPORTED
  166053. case huff_opt_pass:
  166054. /* Do Huffman optimization for a scan after the first one. */
  166055. select_scan_parameters(cinfo);
  166056. per_scan_setup(cinfo);
  166057. if (cinfo->Ss != 0 || cinfo->Ah == 0 || cinfo->arith_code) {
  166058. (*cinfo->entropy->start_pass) (cinfo, TRUE);
  166059. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  166060. master->pub.call_pass_startup = FALSE;
  166061. break;
  166062. }
  166063. /* Special case: Huffman DC refinement scans need no Huffman table
  166064. * and therefore we can skip the optimization pass for them.
  166065. */
  166066. master->pass_type = output_pass;
  166067. master->pass_number++;
  166068. /*FALLTHROUGH*/
  166069. #endif
  166070. case output_pass:
  166071. /* Do a data-output pass. */
  166072. /* We need not repeat per-scan setup if prior optimization pass did it. */
  166073. if (! cinfo->optimize_coding) {
  166074. select_scan_parameters(cinfo);
  166075. per_scan_setup(cinfo);
  166076. }
  166077. (*cinfo->entropy->start_pass) (cinfo, FALSE);
  166078. (*cinfo->coef->start_pass) (cinfo, JBUF_CRANK_DEST);
  166079. /* We emit frame/scan headers now */
  166080. if (master->scan_number == 0)
  166081. (*cinfo->marker->write_frame_header) (cinfo);
  166082. (*cinfo->marker->write_scan_header) (cinfo);
  166083. master->pub.call_pass_startup = FALSE;
  166084. break;
  166085. default:
  166086. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166087. }
  166088. master->pub.is_last_pass = (master->pass_number == master->total_passes-1);
  166089. /* Set up progress monitor's pass info if present */
  166090. if (cinfo->progress != NULL) {
  166091. cinfo->progress->completed_passes = master->pass_number;
  166092. cinfo->progress->total_passes = master->total_passes;
  166093. }
  166094. }
  166095. /*
  166096. * Special start-of-pass hook.
  166097. * This is called by jpeg_write_scanlines if call_pass_startup is TRUE.
  166098. * In single-pass processing, we need this hook because we don't want to
  166099. * write frame/scan headers during jpeg_start_compress; we want to let the
  166100. * application write COM markers etc. between jpeg_start_compress and the
  166101. * jpeg_write_scanlines loop.
  166102. * In multi-pass processing, this routine is not used.
  166103. */
  166104. METHODDEF(void)
  166105. pass_startup (j_compress_ptr cinfo)
  166106. {
  166107. cinfo->master->call_pass_startup = FALSE; /* reset flag so call only once */
  166108. (*cinfo->marker->write_frame_header) (cinfo);
  166109. (*cinfo->marker->write_scan_header) (cinfo);
  166110. }
  166111. /*
  166112. * Finish up at end of pass.
  166113. */
  166114. METHODDEF(void)
  166115. finish_pass_master (j_compress_ptr cinfo)
  166116. {
  166117. my_master_ptr master = (my_master_ptr) cinfo->master;
  166118. /* The entropy coder always needs an end-of-pass call,
  166119. * either to analyze statistics or to flush its output buffer.
  166120. */
  166121. (*cinfo->entropy->finish_pass) (cinfo);
  166122. /* Update state for next pass */
  166123. switch (master->pass_type) {
  166124. case main_pass:
  166125. /* next pass is either output of scan 0 (after optimization)
  166126. * or output of scan 1 (if no optimization).
  166127. */
  166128. master->pass_type = output_pass;
  166129. if (! cinfo->optimize_coding)
  166130. master->scan_number++;
  166131. break;
  166132. case huff_opt_pass:
  166133. /* next pass is always output of current scan */
  166134. master->pass_type = output_pass;
  166135. break;
  166136. case output_pass:
  166137. /* next pass is either optimization or output of next scan */
  166138. if (cinfo->optimize_coding)
  166139. master->pass_type = huff_opt_pass;
  166140. master->scan_number++;
  166141. break;
  166142. }
  166143. master->pass_number++;
  166144. }
  166145. /*
  166146. * Initialize master compression control.
  166147. */
  166148. GLOBAL(void)
  166149. jinit_c_master_control (j_compress_ptr cinfo, boolean transcode_only)
  166150. {
  166151. my_master_ptr master;
  166152. master = (my_master_ptr)
  166153. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166154. SIZEOF(my_comp_master));
  166155. cinfo->master = (struct jpeg_comp_master *) master;
  166156. master->pub.prepare_for_pass = prepare_for_pass;
  166157. master->pub.pass_startup = pass_startup;
  166158. master->pub.finish_pass = finish_pass_master;
  166159. master->pub.is_last_pass = FALSE;
  166160. /* Validate parameters, determine derived values */
  166161. initial_setup(cinfo);
  166162. if (cinfo->scan_info != NULL) {
  166163. #ifdef C_MULTISCAN_FILES_SUPPORTED
  166164. validate_script(cinfo);
  166165. #else
  166166. ERREXIT(cinfo, JERR_NOT_COMPILED);
  166167. #endif
  166168. } else {
  166169. cinfo->progressive_mode = FALSE;
  166170. cinfo->num_scans = 1;
  166171. }
  166172. if (cinfo->progressive_mode) /* TEMPORARY HACK ??? */
  166173. cinfo->optimize_coding = TRUE; /* assume default tables no good for progressive mode */
  166174. /* Initialize my private state */
  166175. if (transcode_only) {
  166176. /* no main pass in transcoding */
  166177. if (cinfo->optimize_coding)
  166178. master->pass_type = huff_opt_pass;
  166179. else
  166180. master->pass_type = output_pass;
  166181. } else {
  166182. /* for normal compression, first pass is always this type: */
  166183. master->pass_type = main_pass;
  166184. }
  166185. master->scan_number = 0;
  166186. master->pass_number = 0;
  166187. if (cinfo->optimize_coding)
  166188. master->total_passes = cinfo->num_scans * 2;
  166189. else
  166190. master->total_passes = cinfo->num_scans;
  166191. }
  166192. /********* End of inlined file: jcmaster.c *********/
  166193. /********* Start of inlined file: jcomapi.c *********/
  166194. #define JPEG_INTERNALS
  166195. /*
  166196. * Abort processing of a JPEG compression or decompression operation,
  166197. * but don't destroy the object itself.
  166198. *
  166199. * For this, we merely clean up all the nonpermanent memory pools.
  166200. * Note that temp files (virtual arrays) are not allowed to belong to
  166201. * the permanent pool, so we will be able to close all temp files here.
  166202. * Closing a data source or destination, if necessary, is the application's
  166203. * responsibility.
  166204. */
  166205. GLOBAL(void)
  166206. jpeg_abort (j_common_ptr cinfo)
  166207. {
  166208. int pool;
  166209. /* Do nothing if called on a not-initialized or destroyed JPEG object. */
  166210. if (cinfo->mem == NULL)
  166211. return;
  166212. /* Releasing pools in reverse order might help avoid fragmentation
  166213. * with some (brain-damaged) malloc libraries.
  166214. */
  166215. for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
  166216. (*cinfo->mem->free_pool) (cinfo, pool);
  166217. }
  166218. /* Reset overall state for possible reuse of object */
  166219. if (cinfo->is_decompressor) {
  166220. cinfo->global_state = DSTATE_START;
  166221. /* Try to keep application from accessing now-deleted marker list.
  166222. * A bit kludgy to do it here, but this is the most central place.
  166223. */
  166224. ((j_decompress_ptr) cinfo)->marker_list = NULL;
  166225. } else {
  166226. cinfo->global_state = CSTATE_START;
  166227. }
  166228. }
  166229. /*
  166230. * Destruction of a JPEG object.
  166231. *
  166232. * Everything gets deallocated except the master jpeg_compress_struct itself
  166233. * and the error manager struct. Both of these are supplied by the application
  166234. * and must be freed, if necessary, by the application. (Often they are on
  166235. * the stack and so don't need to be freed anyway.)
  166236. * Closing a data source or destination, if necessary, is the application's
  166237. * responsibility.
  166238. */
  166239. GLOBAL(void)
  166240. jpeg_destroy (j_common_ptr cinfo)
  166241. {
  166242. /* We need only tell the memory manager to release everything. */
  166243. /* NB: mem pointer is NULL if memory mgr failed to initialize. */
  166244. if (cinfo->mem != NULL)
  166245. (*cinfo->mem->self_destruct) (cinfo);
  166246. cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
  166247. cinfo->global_state = 0; /* mark it destroyed */
  166248. }
  166249. /*
  166250. * Convenience routines for allocating quantization and Huffman tables.
  166251. * (Would jutils.c be a more reasonable place to put these?)
  166252. */
  166253. GLOBAL(JQUANT_TBL *)
  166254. jpeg_alloc_quant_table (j_common_ptr cinfo)
  166255. {
  166256. JQUANT_TBL *tbl;
  166257. tbl = (JQUANT_TBL *)
  166258. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
  166259. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  166260. return tbl;
  166261. }
  166262. GLOBAL(JHUFF_TBL *)
  166263. jpeg_alloc_huff_table (j_common_ptr cinfo)
  166264. {
  166265. JHUFF_TBL *tbl;
  166266. tbl = (JHUFF_TBL *)
  166267. (*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
  166268. tbl->sent_table = FALSE; /* make sure this is false in any new table */
  166269. return tbl;
  166270. }
  166271. /********* End of inlined file: jcomapi.c *********/
  166272. /********* Start of inlined file: jcparam.c *********/
  166273. #define JPEG_INTERNALS
  166274. /*
  166275. * Quantization table setup routines
  166276. */
  166277. GLOBAL(void)
  166278. jpeg_add_quant_table (j_compress_ptr cinfo, int which_tbl,
  166279. const unsigned int *basic_table,
  166280. int scale_factor, boolean force_baseline)
  166281. /* Define a quantization table equal to the basic_table times
  166282. * a scale factor (given as a percentage).
  166283. * If force_baseline is TRUE, the computed quantization table entries
  166284. * are limited to 1..255 for JPEG baseline compatibility.
  166285. */
  166286. {
  166287. JQUANT_TBL ** qtblptr;
  166288. int i;
  166289. long temp;
  166290. /* Safety check to ensure start_compress not called yet. */
  166291. if (cinfo->global_state != CSTATE_START)
  166292. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166293. if (which_tbl < 0 || which_tbl >= NUM_QUANT_TBLS)
  166294. ERREXIT1(cinfo, JERR_DQT_INDEX, which_tbl);
  166295. qtblptr = & cinfo->quant_tbl_ptrs[which_tbl];
  166296. if (*qtblptr == NULL)
  166297. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  166298. for (i = 0; i < DCTSIZE2; i++) {
  166299. temp = ((long) basic_table[i] * scale_factor + 50L) / 100L;
  166300. /* limit the values to the valid range */
  166301. if (temp <= 0L) temp = 1L;
  166302. if (temp > 32767L) temp = 32767L; /* max quantizer needed for 12 bits */
  166303. if (force_baseline && temp > 255L)
  166304. temp = 255L; /* limit to baseline range if requested */
  166305. (*qtblptr)->quantval[i] = (UINT16) temp;
  166306. }
  166307. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  166308. (*qtblptr)->sent_table = FALSE;
  166309. }
  166310. GLOBAL(void)
  166311. jpeg_set_linear_quality (j_compress_ptr cinfo, int scale_factor,
  166312. boolean force_baseline)
  166313. /* Set or change the 'quality' (quantization) setting, using default tables
  166314. * and a straight percentage-scaling quality scale. In most cases it's better
  166315. * to use jpeg_set_quality (below); this entry point is provided for
  166316. * applications that insist on a linear percentage scaling.
  166317. */
  166318. {
  166319. /* These are the sample quantization tables given in JPEG spec section K.1.
  166320. * The spec says that the values given produce "good" quality, and
  166321. * when divided by 2, "very good" quality.
  166322. */
  166323. static const unsigned int std_luminance_quant_tbl[DCTSIZE2] = {
  166324. 16, 11, 10, 16, 24, 40, 51, 61,
  166325. 12, 12, 14, 19, 26, 58, 60, 55,
  166326. 14, 13, 16, 24, 40, 57, 69, 56,
  166327. 14, 17, 22, 29, 51, 87, 80, 62,
  166328. 18, 22, 37, 56, 68, 109, 103, 77,
  166329. 24, 35, 55, 64, 81, 104, 113, 92,
  166330. 49, 64, 78, 87, 103, 121, 120, 101,
  166331. 72, 92, 95, 98, 112, 100, 103, 99
  166332. };
  166333. static const unsigned int std_chrominance_quant_tbl[DCTSIZE2] = {
  166334. 17, 18, 24, 47, 99, 99, 99, 99,
  166335. 18, 21, 26, 66, 99, 99, 99, 99,
  166336. 24, 26, 56, 99, 99, 99, 99, 99,
  166337. 47, 66, 99, 99, 99, 99, 99, 99,
  166338. 99, 99, 99, 99, 99, 99, 99, 99,
  166339. 99, 99, 99, 99, 99, 99, 99, 99,
  166340. 99, 99, 99, 99, 99, 99, 99, 99,
  166341. 99, 99, 99, 99, 99, 99, 99, 99
  166342. };
  166343. /* Set up two quantization tables using the specified scaling */
  166344. jpeg_add_quant_table(cinfo, 0, std_luminance_quant_tbl,
  166345. scale_factor, force_baseline);
  166346. jpeg_add_quant_table(cinfo, 1, std_chrominance_quant_tbl,
  166347. scale_factor, force_baseline);
  166348. }
  166349. GLOBAL(int)
  166350. jpeg_quality_scaling (int quality)
  166351. /* Convert a user-specified quality rating to a percentage scaling factor
  166352. * for an underlying quantization table, using our recommended scaling curve.
  166353. * The input 'quality' factor should be 0 (terrible) to 100 (very good).
  166354. */
  166355. {
  166356. /* Safety limit on quality factor. Convert 0 to 1 to avoid zero divide. */
  166357. if (quality <= 0) quality = 1;
  166358. if (quality > 100) quality = 100;
  166359. /* The basic table is used as-is (scaling 100) for a quality of 50.
  166360. * Qualities 50..100 are converted to scaling percentage 200 - 2*Q;
  166361. * note that at Q=100 the scaling is 0, which will cause jpeg_add_quant_table
  166362. * to make all the table entries 1 (hence, minimum quantization loss).
  166363. * Qualities 1..50 are converted to scaling percentage 5000/Q.
  166364. */
  166365. if (quality < 50)
  166366. quality = 5000 / quality;
  166367. else
  166368. quality = 200 - quality*2;
  166369. return quality;
  166370. }
  166371. GLOBAL(void)
  166372. jpeg_set_quality (j_compress_ptr cinfo, int quality, boolean force_baseline)
  166373. /* Set or change the 'quality' (quantization) setting, using default tables.
  166374. * This is the standard quality-adjusting entry point for typical user
  166375. * interfaces; only those who want detailed control over quantization tables
  166376. * would use the preceding three routines directly.
  166377. */
  166378. {
  166379. /* Convert user 0-100 rating to percentage scaling */
  166380. quality = jpeg_quality_scaling(quality);
  166381. /* Set up standard quality tables */
  166382. jpeg_set_linear_quality(cinfo, quality, force_baseline);
  166383. }
  166384. /*
  166385. * Huffman table setup routines
  166386. */
  166387. LOCAL(void)
  166388. add_huff_table (j_compress_ptr cinfo,
  166389. JHUFF_TBL **htblptr, const UINT8 *bits, const UINT8 *val)
  166390. /* Define a Huffman table */
  166391. {
  166392. int nsymbols, len;
  166393. if (*htblptr == NULL)
  166394. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  166395. /* Copy the number-of-symbols-of-each-code-length counts */
  166396. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  166397. /* Validate the counts. We do this here mainly so we can copy the right
  166398. * number of symbols from the val[] array, without risking marching off
  166399. * the end of memory. jchuff.c will do a more thorough test later.
  166400. */
  166401. nsymbols = 0;
  166402. for (len = 1; len <= 16; len++)
  166403. nsymbols += bits[len];
  166404. if (nsymbols < 1 || nsymbols > 256)
  166405. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  166406. MEMCOPY((*htblptr)->huffval, val, nsymbols * SIZEOF(UINT8));
  166407. /* Initialize sent_table FALSE so table will be written to JPEG file. */
  166408. (*htblptr)->sent_table = FALSE;
  166409. }
  166410. LOCAL(void)
  166411. std_huff_tables (j_compress_ptr cinfo)
  166412. /* Set up the standard Huffman tables (cf. JPEG standard section K.3) */
  166413. /* IMPORTANT: these are only valid for 8-bit data precision! */
  166414. {
  166415. static const UINT8 bits_dc_luminance[17] =
  166416. { /* 0-base */ 0, 0, 1, 5, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 };
  166417. static const UINT8 val_dc_luminance[] =
  166418. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  166419. static const UINT8 bits_dc_chrominance[17] =
  166420. { /* 0-base */ 0, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0 };
  166421. static const UINT8 val_dc_chrominance[] =
  166422. { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 };
  166423. static const UINT8 bits_ac_luminance[17] =
  166424. { /* 0-base */ 0, 0, 2, 1, 3, 3, 2, 4, 3, 5, 5, 4, 4, 0, 0, 1, 0x7d };
  166425. static const UINT8 val_ac_luminance[] =
  166426. { 0x01, 0x02, 0x03, 0x00, 0x04, 0x11, 0x05, 0x12,
  166427. 0x21, 0x31, 0x41, 0x06, 0x13, 0x51, 0x61, 0x07,
  166428. 0x22, 0x71, 0x14, 0x32, 0x81, 0x91, 0xa1, 0x08,
  166429. 0x23, 0x42, 0xb1, 0xc1, 0x15, 0x52, 0xd1, 0xf0,
  166430. 0x24, 0x33, 0x62, 0x72, 0x82, 0x09, 0x0a, 0x16,
  166431. 0x17, 0x18, 0x19, 0x1a, 0x25, 0x26, 0x27, 0x28,
  166432. 0x29, 0x2a, 0x34, 0x35, 0x36, 0x37, 0x38, 0x39,
  166433. 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49,
  166434. 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58, 0x59,
  166435. 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69,
  166436. 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78, 0x79,
  166437. 0x7a, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89,
  166438. 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97, 0x98,
  166439. 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
  166440. 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6,
  166441. 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3, 0xc4, 0xc5,
  166442. 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2, 0xd3, 0xd4,
  166443. 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda, 0xe1, 0xe2,
  166444. 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9, 0xea,
  166445. 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  166446. 0xf9, 0xfa };
  166447. static const UINT8 bits_ac_chrominance[17] =
  166448. { /* 0-base */ 0, 0, 2, 1, 2, 4, 4, 3, 4, 7, 5, 4, 4, 0, 1, 2, 0x77 };
  166449. static const UINT8 val_ac_chrominance[] =
  166450. { 0x00, 0x01, 0x02, 0x03, 0x11, 0x04, 0x05, 0x21,
  166451. 0x31, 0x06, 0x12, 0x41, 0x51, 0x07, 0x61, 0x71,
  166452. 0x13, 0x22, 0x32, 0x81, 0x08, 0x14, 0x42, 0x91,
  166453. 0xa1, 0xb1, 0xc1, 0x09, 0x23, 0x33, 0x52, 0xf0,
  166454. 0x15, 0x62, 0x72, 0xd1, 0x0a, 0x16, 0x24, 0x34,
  166455. 0xe1, 0x25, 0xf1, 0x17, 0x18, 0x19, 0x1a, 0x26,
  166456. 0x27, 0x28, 0x29, 0x2a, 0x35, 0x36, 0x37, 0x38,
  166457. 0x39, 0x3a, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48,
  166458. 0x49, 0x4a, 0x53, 0x54, 0x55, 0x56, 0x57, 0x58,
  166459. 0x59, 0x5a, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68,
  166460. 0x69, 0x6a, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78,
  166461. 0x79, 0x7a, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
  166462. 0x88, 0x89, 0x8a, 0x92, 0x93, 0x94, 0x95, 0x96,
  166463. 0x97, 0x98, 0x99, 0x9a, 0xa2, 0xa3, 0xa4, 0xa5,
  166464. 0xa6, 0xa7, 0xa8, 0xa9, 0xaa, 0xb2, 0xb3, 0xb4,
  166465. 0xb5, 0xb6, 0xb7, 0xb8, 0xb9, 0xba, 0xc2, 0xc3,
  166466. 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0xd2,
  166467. 0xd3, 0xd4, 0xd5, 0xd6, 0xd7, 0xd8, 0xd9, 0xda,
  166468. 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7, 0xe8, 0xe9,
  166469. 0xea, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7, 0xf8,
  166470. 0xf9, 0xfa };
  166471. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[0],
  166472. bits_dc_luminance, val_dc_luminance);
  166473. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[0],
  166474. bits_ac_luminance, val_ac_luminance);
  166475. add_huff_table(cinfo, &cinfo->dc_huff_tbl_ptrs[1],
  166476. bits_dc_chrominance, val_dc_chrominance);
  166477. add_huff_table(cinfo, &cinfo->ac_huff_tbl_ptrs[1],
  166478. bits_ac_chrominance, val_ac_chrominance);
  166479. }
  166480. /*
  166481. * Default parameter setup for compression.
  166482. *
  166483. * Applications that don't choose to use this routine must do their
  166484. * own setup of all these parameters. Alternately, you can call this
  166485. * to establish defaults and then alter parameters selectively. This
  166486. * is the recommended approach since, if we add any new parameters,
  166487. * your code will still work (they'll be set to reasonable defaults).
  166488. */
  166489. GLOBAL(void)
  166490. jpeg_set_defaults (j_compress_ptr cinfo)
  166491. {
  166492. int i;
  166493. /* Safety check to ensure start_compress not called yet. */
  166494. if (cinfo->global_state != CSTATE_START)
  166495. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166496. /* Allocate comp_info array large enough for maximum component count.
  166497. * Array is made permanent in case application wants to compress
  166498. * multiple images at same param settings.
  166499. */
  166500. if (cinfo->comp_info == NULL)
  166501. cinfo->comp_info = (jpeg_component_info *)
  166502. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  166503. MAX_COMPONENTS * SIZEOF(jpeg_component_info));
  166504. /* Initialize everything not dependent on the color space */
  166505. cinfo->data_precision = BITS_IN_JSAMPLE;
  166506. /* Set up two quantization tables using default quality of 75 */
  166507. jpeg_set_quality(cinfo, 75, TRUE);
  166508. /* Set up two Huffman tables */
  166509. std_huff_tables(cinfo);
  166510. /* Initialize default arithmetic coding conditioning */
  166511. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  166512. cinfo->arith_dc_L[i] = 0;
  166513. cinfo->arith_dc_U[i] = 1;
  166514. cinfo->arith_ac_K[i] = 5;
  166515. }
  166516. /* Default is no multiple-scan output */
  166517. cinfo->scan_info = NULL;
  166518. cinfo->num_scans = 0;
  166519. /* Expect normal source image, not raw downsampled data */
  166520. cinfo->raw_data_in = FALSE;
  166521. /* Use Huffman coding, not arithmetic coding, by default */
  166522. cinfo->arith_code = FALSE;
  166523. /* By default, don't do extra passes to optimize entropy coding */
  166524. cinfo->optimize_coding = FALSE;
  166525. /* The standard Huffman tables are only valid for 8-bit data precision.
  166526. * If the precision is higher, force optimization on so that usable
  166527. * tables will be computed. This test can be removed if default tables
  166528. * are supplied that are valid for the desired precision.
  166529. */
  166530. if (cinfo->data_precision > 8)
  166531. cinfo->optimize_coding = TRUE;
  166532. /* By default, use the simpler non-cosited sampling alignment */
  166533. cinfo->CCIR601_sampling = FALSE;
  166534. /* No input smoothing */
  166535. cinfo->smoothing_factor = 0;
  166536. /* DCT algorithm preference */
  166537. cinfo->dct_method = JDCT_DEFAULT;
  166538. /* No restart markers */
  166539. cinfo->restart_interval = 0;
  166540. cinfo->restart_in_rows = 0;
  166541. /* Fill in default JFIF marker parameters. Note that whether the marker
  166542. * will actually be written is determined by jpeg_set_colorspace.
  166543. *
  166544. * By default, the library emits JFIF version code 1.01.
  166545. * An application that wants to emit JFIF 1.02 extension markers should set
  166546. * JFIF_minor_version to 2. We could probably get away with just defaulting
  166547. * to 1.02, but there may still be some decoders in use that will complain
  166548. * about that; saying 1.01 should minimize compatibility problems.
  166549. */
  166550. cinfo->JFIF_major_version = 1; /* Default JFIF version = 1.01 */
  166551. cinfo->JFIF_minor_version = 1;
  166552. cinfo->density_unit = 0; /* Pixel size is unknown by default */
  166553. cinfo->X_density = 1; /* Pixel aspect ratio is square by default */
  166554. cinfo->Y_density = 1;
  166555. /* Choose JPEG colorspace based on input space, set defaults accordingly */
  166556. jpeg_default_colorspace(cinfo);
  166557. }
  166558. /*
  166559. * Select an appropriate JPEG colorspace for in_color_space.
  166560. */
  166561. GLOBAL(void)
  166562. jpeg_default_colorspace (j_compress_ptr cinfo)
  166563. {
  166564. switch (cinfo->in_color_space) {
  166565. case JCS_GRAYSCALE:
  166566. jpeg_set_colorspace(cinfo, JCS_GRAYSCALE);
  166567. break;
  166568. case JCS_RGB:
  166569. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  166570. break;
  166571. case JCS_YCbCr:
  166572. jpeg_set_colorspace(cinfo, JCS_YCbCr);
  166573. break;
  166574. case JCS_CMYK:
  166575. jpeg_set_colorspace(cinfo, JCS_CMYK); /* By default, no translation */
  166576. break;
  166577. case JCS_YCCK:
  166578. jpeg_set_colorspace(cinfo, JCS_YCCK);
  166579. break;
  166580. case JCS_UNKNOWN:
  166581. jpeg_set_colorspace(cinfo, JCS_UNKNOWN);
  166582. break;
  166583. default:
  166584. ERREXIT(cinfo, JERR_BAD_IN_COLORSPACE);
  166585. }
  166586. }
  166587. /*
  166588. * Set the JPEG colorspace, and choose colorspace-dependent default values.
  166589. */
  166590. GLOBAL(void)
  166591. jpeg_set_colorspace (j_compress_ptr cinfo, J_COLOR_SPACE colorspace)
  166592. {
  166593. jpeg_component_info * compptr;
  166594. int ci;
  166595. #define SET_COMP(index,id,hsamp,vsamp,quant,dctbl,actbl) \
  166596. (compptr = &cinfo->comp_info[index], \
  166597. compptr->component_id = (id), \
  166598. compptr->h_samp_factor = (hsamp), \
  166599. compptr->v_samp_factor = (vsamp), \
  166600. compptr->quant_tbl_no = (quant), \
  166601. compptr->dc_tbl_no = (dctbl), \
  166602. compptr->ac_tbl_no = (actbl) )
  166603. /* Safety check to ensure start_compress not called yet. */
  166604. if (cinfo->global_state != CSTATE_START)
  166605. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166606. /* For all colorspaces, we use Q and Huff tables 0 for luminance components,
  166607. * tables 1 for chrominance components.
  166608. */
  166609. cinfo->jpeg_color_space = colorspace;
  166610. cinfo->write_JFIF_header = FALSE; /* No marker for non-JFIF colorspaces */
  166611. cinfo->write_Adobe_marker = FALSE; /* write no Adobe marker by default */
  166612. switch (colorspace) {
  166613. case JCS_GRAYSCALE:
  166614. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  166615. cinfo->num_components = 1;
  166616. /* JFIF specifies component ID 1 */
  166617. SET_COMP(0, 1, 1,1, 0, 0,0);
  166618. break;
  166619. case JCS_RGB:
  166620. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag RGB */
  166621. cinfo->num_components = 3;
  166622. SET_COMP(0, 0x52 /* 'R' */, 1,1, 0, 0,0);
  166623. SET_COMP(1, 0x47 /* 'G' */, 1,1, 0, 0,0);
  166624. SET_COMP(2, 0x42 /* 'B' */, 1,1, 0, 0,0);
  166625. break;
  166626. case JCS_YCbCr:
  166627. cinfo->write_JFIF_header = TRUE; /* Write a JFIF marker */
  166628. cinfo->num_components = 3;
  166629. /* JFIF specifies component IDs 1,2,3 */
  166630. /* We default to 2x2 subsamples of chrominance */
  166631. SET_COMP(0, 1, 2,2, 0, 0,0);
  166632. SET_COMP(1, 2, 1,1, 1, 1,1);
  166633. SET_COMP(2, 3, 1,1, 1, 1,1);
  166634. break;
  166635. case JCS_CMYK:
  166636. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag CMYK */
  166637. cinfo->num_components = 4;
  166638. SET_COMP(0, 0x43 /* 'C' */, 1,1, 0, 0,0);
  166639. SET_COMP(1, 0x4D /* 'M' */, 1,1, 0, 0,0);
  166640. SET_COMP(2, 0x59 /* 'Y' */, 1,1, 0, 0,0);
  166641. SET_COMP(3, 0x4B /* 'K' */, 1,1, 0, 0,0);
  166642. break;
  166643. case JCS_YCCK:
  166644. cinfo->write_Adobe_marker = TRUE; /* write Adobe marker to flag YCCK */
  166645. cinfo->num_components = 4;
  166646. SET_COMP(0, 1, 2,2, 0, 0,0);
  166647. SET_COMP(1, 2, 1,1, 1, 1,1);
  166648. SET_COMP(2, 3, 1,1, 1, 1,1);
  166649. SET_COMP(3, 4, 2,2, 0, 0,0);
  166650. break;
  166651. case JCS_UNKNOWN:
  166652. cinfo->num_components = cinfo->input_components;
  166653. if (cinfo->num_components < 1 || cinfo->num_components > MAX_COMPONENTS)
  166654. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  166655. MAX_COMPONENTS);
  166656. for (ci = 0; ci < cinfo->num_components; ci++) {
  166657. SET_COMP(ci, ci, 1,1, 0, 0,0);
  166658. }
  166659. break;
  166660. default:
  166661. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  166662. }
  166663. }
  166664. #ifdef C_PROGRESSIVE_SUPPORTED
  166665. LOCAL(jpeg_scan_info *)
  166666. fill_a_scan (jpeg_scan_info * scanptr, int ci,
  166667. int Ss, int Se, int Ah, int Al)
  166668. /* Support routine: generate one scan for specified component */
  166669. {
  166670. scanptr->comps_in_scan = 1;
  166671. scanptr->component_index[0] = ci;
  166672. scanptr->Ss = Ss;
  166673. scanptr->Se = Se;
  166674. scanptr->Ah = Ah;
  166675. scanptr->Al = Al;
  166676. scanptr++;
  166677. return scanptr;
  166678. }
  166679. LOCAL(jpeg_scan_info *)
  166680. fill_scans (jpeg_scan_info * scanptr, int ncomps,
  166681. int Ss, int Se, int Ah, int Al)
  166682. /* Support routine: generate one scan for each component */
  166683. {
  166684. int ci;
  166685. for (ci = 0; ci < ncomps; ci++) {
  166686. scanptr->comps_in_scan = 1;
  166687. scanptr->component_index[0] = ci;
  166688. scanptr->Ss = Ss;
  166689. scanptr->Se = Se;
  166690. scanptr->Ah = Ah;
  166691. scanptr->Al = Al;
  166692. scanptr++;
  166693. }
  166694. return scanptr;
  166695. }
  166696. LOCAL(jpeg_scan_info *)
  166697. fill_dc_scans (jpeg_scan_info * scanptr, int ncomps, int Ah, int Al)
  166698. /* Support routine: generate interleaved DC scan if possible, else N scans */
  166699. {
  166700. int ci;
  166701. if (ncomps <= MAX_COMPS_IN_SCAN) {
  166702. /* Single interleaved DC scan */
  166703. scanptr->comps_in_scan = ncomps;
  166704. for (ci = 0; ci < ncomps; ci++)
  166705. scanptr->component_index[ci] = ci;
  166706. scanptr->Ss = scanptr->Se = 0;
  166707. scanptr->Ah = Ah;
  166708. scanptr->Al = Al;
  166709. scanptr++;
  166710. } else {
  166711. /* Noninterleaved DC scan for each component */
  166712. scanptr = fill_scans(scanptr, ncomps, 0, 0, Ah, Al);
  166713. }
  166714. return scanptr;
  166715. }
  166716. /*
  166717. * Create a recommended progressive-JPEG script.
  166718. * cinfo->num_components and cinfo->jpeg_color_space must be correct.
  166719. */
  166720. GLOBAL(void)
  166721. jpeg_simple_progression (j_compress_ptr cinfo)
  166722. {
  166723. int ncomps = cinfo->num_components;
  166724. int nscans;
  166725. jpeg_scan_info * scanptr;
  166726. /* Safety check to ensure start_compress not called yet. */
  166727. if (cinfo->global_state != CSTATE_START)
  166728. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  166729. /* Figure space needed for script. Calculation must match code below! */
  166730. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  166731. /* Custom script for YCbCr color images. */
  166732. nscans = 10;
  166733. } else {
  166734. /* All-purpose script for other color spaces. */
  166735. if (ncomps > MAX_COMPS_IN_SCAN)
  166736. nscans = 6 * ncomps; /* 2 DC + 4 AC scans per component */
  166737. else
  166738. nscans = 2 + 4 * ncomps; /* 2 DC scans; 4 AC scans per component */
  166739. }
  166740. /* Allocate space for script.
  166741. * We need to put it in the permanent pool in case the application performs
  166742. * multiple compressions without changing the settings. To avoid a memory
  166743. * leak if jpeg_simple_progression is called repeatedly for the same JPEG
  166744. * object, we try to re-use previously allocated space, and we allocate
  166745. * enough space to handle YCbCr even if initially asked for grayscale.
  166746. */
  166747. if (cinfo->script_space == NULL || cinfo->script_space_size < nscans) {
  166748. cinfo->script_space_size = MAX(nscans, 10);
  166749. cinfo->script_space = (jpeg_scan_info *)
  166750. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  166751. cinfo->script_space_size * SIZEOF(jpeg_scan_info));
  166752. }
  166753. scanptr = cinfo->script_space;
  166754. cinfo->scan_info = scanptr;
  166755. cinfo->num_scans = nscans;
  166756. if (ncomps == 3 && cinfo->jpeg_color_space == JCS_YCbCr) {
  166757. /* Custom script for YCbCr color images. */
  166758. /* Initial DC scan */
  166759. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  166760. /* Initial AC scan: get some luma data out in a hurry */
  166761. scanptr = fill_a_scan(scanptr, 0, 1, 5, 0, 2);
  166762. /* Chroma data is too small to be worth expending many scans on */
  166763. scanptr = fill_a_scan(scanptr, 2, 1, 63, 0, 1);
  166764. scanptr = fill_a_scan(scanptr, 1, 1, 63, 0, 1);
  166765. /* Complete spectral selection for luma AC */
  166766. scanptr = fill_a_scan(scanptr, 0, 6, 63, 0, 2);
  166767. /* Refine next bit of luma AC */
  166768. scanptr = fill_a_scan(scanptr, 0, 1, 63, 2, 1);
  166769. /* Finish DC successive approximation */
  166770. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  166771. /* Finish AC successive approximation */
  166772. scanptr = fill_a_scan(scanptr, 2, 1, 63, 1, 0);
  166773. scanptr = fill_a_scan(scanptr, 1, 1, 63, 1, 0);
  166774. /* Luma bottom bit comes last since it's usually largest scan */
  166775. scanptr = fill_a_scan(scanptr, 0, 1, 63, 1, 0);
  166776. } else {
  166777. /* All-purpose script for other color spaces. */
  166778. /* Successive approximation first pass */
  166779. scanptr = fill_dc_scans(scanptr, ncomps, 0, 1);
  166780. scanptr = fill_scans(scanptr, ncomps, 1, 5, 0, 2);
  166781. scanptr = fill_scans(scanptr, ncomps, 6, 63, 0, 2);
  166782. /* Successive approximation second pass */
  166783. scanptr = fill_scans(scanptr, ncomps, 1, 63, 2, 1);
  166784. /* Successive approximation final pass */
  166785. scanptr = fill_dc_scans(scanptr, ncomps, 1, 0);
  166786. scanptr = fill_scans(scanptr, ncomps, 1, 63, 1, 0);
  166787. }
  166788. }
  166789. #endif /* C_PROGRESSIVE_SUPPORTED */
  166790. /********* End of inlined file: jcparam.c *********/
  166791. /********* Start of inlined file: jcphuff.c *********/
  166792. #define JPEG_INTERNALS
  166793. #ifdef C_PROGRESSIVE_SUPPORTED
  166794. /* Expanded entropy encoder object for progressive Huffman encoding. */
  166795. typedef struct {
  166796. struct jpeg_entropy_encoder pub; /* public fields */
  166797. /* Mode flag: TRUE for optimization, FALSE for actual data output */
  166798. boolean gather_statistics;
  166799. /* Bit-level coding status.
  166800. * next_output_byte/free_in_buffer are local copies of cinfo->dest fields.
  166801. */
  166802. JOCTET * next_output_byte; /* => next byte to write in buffer */
  166803. size_t free_in_buffer; /* # of byte spaces remaining in buffer */
  166804. INT32 put_buffer; /* current bit-accumulation buffer */
  166805. int put_bits; /* # of bits now in it */
  166806. j_compress_ptr cinfo; /* link to cinfo (needed for dump_buffer) */
  166807. /* Coding status for DC components */
  166808. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  166809. /* Coding status for AC components */
  166810. int ac_tbl_no; /* the table number of the single component */
  166811. unsigned int EOBRUN; /* run length of EOBs */
  166812. unsigned int BE; /* # of buffered correction bits before MCU */
  166813. char * bit_buffer; /* buffer for correction bits (1 per char) */
  166814. /* packing correction bits tightly would save some space but cost time... */
  166815. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  166816. int next_restart_num; /* next restart number to write (0-7) */
  166817. /* Pointers to derived tables (these workspaces have image lifespan).
  166818. * Since any one scan codes only DC or only AC, we only need one set
  166819. * of tables, not one for DC and one for AC.
  166820. */
  166821. c_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  166822. /* Statistics tables for optimization; again, one set is enough */
  166823. long * count_ptrs[NUM_HUFF_TBLS];
  166824. } phuff_entropy_encoder;
  166825. typedef phuff_entropy_encoder * phuff_entropy_ptr;
  166826. /* MAX_CORR_BITS is the number of bits the AC refinement correction-bit
  166827. * buffer can hold. Larger sizes may slightly improve compression, but
  166828. * 1000 is already well into the realm of overkill.
  166829. * The minimum safe size is 64 bits.
  166830. */
  166831. #define MAX_CORR_BITS 1000 /* Max # of correction bits I can buffer */
  166832. /* IRIGHT_SHIFT is like RIGHT_SHIFT, but works on int rather than INT32.
  166833. * We assume that int right shift is unsigned if INT32 right shift is,
  166834. * which should be safe.
  166835. */
  166836. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  166837. #define ISHIFT_TEMPS int ishift_temp;
  166838. #define IRIGHT_SHIFT(x,shft) \
  166839. ((ishift_temp = (x)) < 0 ? \
  166840. (ishift_temp >> (shft)) | ((~0) << (16-(shft))) : \
  166841. (ishift_temp >> (shft)))
  166842. #else
  166843. #define ISHIFT_TEMPS
  166844. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  166845. #endif
  166846. /* Forward declarations */
  166847. METHODDEF(boolean) encode_mcu_DC_first JPP((j_compress_ptr cinfo,
  166848. JBLOCKROW *MCU_data));
  166849. METHODDEF(boolean) encode_mcu_AC_first JPP((j_compress_ptr cinfo,
  166850. JBLOCKROW *MCU_data));
  166851. METHODDEF(boolean) encode_mcu_DC_refine JPP((j_compress_ptr cinfo,
  166852. JBLOCKROW *MCU_data));
  166853. METHODDEF(boolean) encode_mcu_AC_refine JPP((j_compress_ptr cinfo,
  166854. JBLOCKROW *MCU_data));
  166855. METHODDEF(void) finish_pass_phuff JPP((j_compress_ptr cinfo));
  166856. METHODDEF(void) finish_pass_gather_phuff JPP((j_compress_ptr cinfo));
  166857. /*
  166858. * Initialize for a Huffman-compressed scan using progressive JPEG.
  166859. */
  166860. METHODDEF(void)
  166861. start_pass_phuff (j_compress_ptr cinfo, boolean gather_statistics)
  166862. {
  166863. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  166864. boolean is_DC_band;
  166865. int ci, tbl;
  166866. jpeg_component_info * compptr;
  166867. entropy->cinfo = cinfo;
  166868. entropy->gather_statistics = gather_statistics;
  166869. is_DC_band = (cinfo->Ss == 0);
  166870. /* We assume jcmaster.c already validated the scan parameters. */
  166871. /* Select execution routines */
  166872. if (cinfo->Ah == 0) {
  166873. if (is_DC_band)
  166874. entropy->pub.encode_mcu = encode_mcu_DC_first;
  166875. else
  166876. entropy->pub.encode_mcu = encode_mcu_AC_first;
  166877. } else {
  166878. if (is_DC_band)
  166879. entropy->pub.encode_mcu = encode_mcu_DC_refine;
  166880. else {
  166881. entropy->pub.encode_mcu = encode_mcu_AC_refine;
  166882. /* AC refinement needs a correction bit buffer */
  166883. if (entropy->bit_buffer == NULL)
  166884. entropy->bit_buffer = (char *)
  166885. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166886. MAX_CORR_BITS * SIZEOF(char));
  166887. }
  166888. }
  166889. if (gather_statistics)
  166890. entropy->pub.finish_pass = finish_pass_gather_phuff;
  166891. else
  166892. entropy->pub.finish_pass = finish_pass_phuff;
  166893. /* Only DC coefficients may be interleaved, so cinfo->comps_in_scan = 1
  166894. * for AC coefficients.
  166895. */
  166896. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  166897. compptr = cinfo->cur_comp_info[ci];
  166898. /* Initialize DC predictions to 0 */
  166899. entropy->last_dc_val[ci] = 0;
  166900. /* Get table index */
  166901. if (is_DC_band) {
  166902. if (cinfo->Ah != 0) /* DC refinement needs no table */
  166903. continue;
  166904. tbl = compptr->dc_tbl_no;
  166905. } else {
  166906. entropy->ac_tbl_no = tbl = compptr->ac_tbl_no;
  166907. }
  166908. if (gather_statistics) {
  166909. /* Check for invalid table index */
  166910. /* (make_c_derived_tbl does this in the other path) */
  166911. if (tbl < 0 || tbl >= NUM_HUFF_TBLS)
  166912. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tbl);
  166913. /* Allocate and zero the statistics tables */
  166914. /* Note that jpeg_gen_optimal_table expects 257 entries in each table! */
  166915. if (entropy->count_ptrs[tbl] == NULL)
  166916. entropy->count_ptrs[tbl] = (long *)
  166917. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  166918. 257 * SIZEOF(long));
  166919. MEMZERO(entropy->count_ptrs[tbl], 257 * SIZEOF(long));
  166920. } else {
  166921. /* Compute derived values for Huffman table */
  166922. /* We may do this more than once for a table, but it's not expensive */
  166923. jpeg_make_c_derived_tbl(cinfo, is_DC_band, tbl,
  166924. & entropy->derived_tbls[tbl]);
  166925. }
  166926. }
  166927. /* Initialize AC stuff */
  166928. entropy->EOBRUN = 0;
  166929. entropy->BE = 0;
  166930. /* Initialize bit buffer to empty */
  166931. entropy->put_buffer = 0;
  166932. entropy->put_bits = 0;
  166933. /* Initialize restart stuff */
  166934. entropy->restarts_to_go = cinfo->restart_interval;
  166935. entropy->next_restart_num = 0;
  166936. }
  166937. /* Outputting bytes to the file.
  166938. * NB: these must be called only when actually outputting,
  166939. * that is, entropy->gather_statistics == FALSE.
  166940. */
  166941. /* Emit a byte */
  166942. #define emit_byte(entropy,val) \
  166943. { *(entropy)->next_output_byte++ = (JOCTET) (val); \
  166944. if (--(entropy)->free_in_buffer == 0) \
  166945. dump_buffer_p(entropy); }
  166946. LOCAL(void)
  166947. dump_buffer_p (phuff_entropy_ptr entropy)
  166948. /* Empty the output buffer; we do not support suspension in this module. */
  166949. {
  166950. struct jpeg_destination_mgr * dest = entropy->cinfo->dest;
  166951. if (! (*dest->empty_output_buffer) (entropy->cinfo))
  166952. ERREXIT(entropy->cinfo, JERR_CANT_SUSPEND);
  166953. /* After a successful buffer dump, must reset buffer pointers */
  166954. entropy->next_output_byte = dest->next_output_byte;
  166955. entropy->free_in_buffer = dest->free_in_buffer;
  166956. }
  166957. /* Outputting bits to the file */
  166958. /* Only the right 24 bits of put_buffer are used; the valid bits are
  166959. * left-justified in this part. At most 16 bits can be passed to emit_bits
  166960. * in one call, and we never retain more than 7 bits in put_buffer
  166961. * between calls, so 24 bits are sufficient.
  166962. */
  166963. INLINE
  166964. LOCAL(void)
  166965. emit_bits_p (phuff_entropy_ptr entropy, unsigned int code, int size)
  166966. /* Emit some bits, unless we are in gather mode */
  166967. {
  166968. /* This routine is heavily used, so it's worth coding tightly. */
  166969. register INT32 put_buffer = (INT32) code;
  166970. register int put_bits = entropy->put_bits;
  166971. /* if size is 0, caller used an invalid Huffman table entry */
  166972. if (size == 0)
  166973. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  166974. if (entropy->gather_statistics)
  166975. return; /* do nothing if we're only getting stats */
  166976. put_buffer &= (((INT32) 1)<<size) - 1; /* mask off any extra bits in code */
  166977. put_bits += size; /* new number of bits in buffer */
  166978. put_buffer <<= 24 - put_bits; /* align incoming bits */
  166979. put_buffer |= entropy->put_buffer; /* and merge with old buffer contents */
  166980. while (put_bits >= 8) {
  166981. int c = (int) ((put_buffer >> 16) & 0xFF);
  166982. emit_byte(entropy, c);
  166983. if (c == 0xFF) { /* need to stuff a zero byte? */
  166984. emit_byte(entropy, 0);
  166985. }
  166986. put_buffer <<= 8;
  166987. put_bits -= 8;
  166988. }
  166989. entropy->put_buffer = put_buffer; /* update variables */
  166990. entropy->put_bits = put_bits;
  166991. }
  166992. LOCAL(void)
  166993. flush_bits_p (phuff_entropy_ptr entropy)
  166994. {
  166995. emit_bits_p(entropy, 0x7F, 7); /* fill any partial byte with ones */
  166996. entropy->put_buffer = 0; /* and reset bit-buffer to empty */
  166997. entropy->put_bits = 0;
  166998. }
  166999. /*
  167000. * Emit (or just count) a Huffman symbol.
  167001. */
  167002. INLINE
  167003. LOCAL(void)
  167004. emit_symbol (phuff_entropy_ptr entropy, int tbl_no, int symbol)
  167005. {
  167006. if (entropy->gather_statistics)
  167007. entropy->count_ptrs[tbl_no][symbol]++;
  167008. else {
  167009. c_derived_tbl * tbl = entropy->derived_tbls[tbl_no];
  167010. emit_bits_p(entropy, tbl->ehufco[symbol], tbl->ehufsi[symbol]);
  167011. }
  167012. }
  167013. /*
  167014. * Emit bits from a correction bit buffer.
  167015. */
  167016. LOCAL(void)
  167017. emit_buffered_bits (phuff_entropy_ptr entropy, char * bufstart,
  167018. unsigned int nbits)
  167019. {
  167020. if (entropy->gather_statistics)
  167021. return; /* no real work */
  167022. while (nbits > 0) {
  167023. emit_bits_p(entropy, (unsigned int) (*bufstart), 1);
  167024. bufstart++;
  167025. nbits--;
  167026. }
  167027. }
  167028. /*
  167029. * Emit any pending EOBRUN symbol.
  167030. */
  167031. LOCAL(void)
  167032. emit_eobrun (phuff_entropy_ptr entropy)
  167033. {
  167034. register int temp, nbits;
  167035. if (entropy->EOBRUN > 0) { /* if there is any pending EOBRUN */
  167036. temp = entropy->EOBRUN;
  167037. nbits = 0;
  167038. while ((temp >>= 1))
  167039. nbits++;
  167040. /* safety check: shouldn't happen given limited correction-bit buffer */
  167041. if (nbits > 14)
  167042. ERREXIT(entropy->cinfo, JERR_HUFF_MISSING_CODE);
  167043. emit_symbol(entropy, entropy->ac_tbl_no, nbits << 4);
  167044. if (nbits)
  167045. emit_bits_p(entropy, entropy->EOBRUN, nbits);
  167046. entropy->EOBRUN = 0;
  167047. /* Emit any buffered correction bits */
  167048. emit_buffered_bits(entropy, entropy->bit_buffer, entropy->BE);
  167049. entropy->BE = 0;
  167050. }
  167051. }
  167052. /*
  167053. * Emit a restart marker & resynchronize predictions.
  167054. */
  167055. LOCAL(void)
  167056. emit_restart_p (phuff_entropy_ptr entropy, int restart_num)
  167057. {
  167058. int ci;
  167059. emit_eobrun(entropy);
  167060. if (! entropy->gather_statistics) {
  167061. flush_bits_p(entropy);
  167062. emit_byte(entropy, 0xFF);
  167063. emit_byte(entropy, JPEG_RST0 + restart_num);
  167064. }
  167065. if (entropy->cinfo->Ss == 0) {
  167066. /* Re-initialize DC predictions to 0 */
  167067. for (ci = 0; ci < entropy->cinfo->comps_in_scan; ci++)
  167068. entropy->last_dc_val[ci] = 0;
  167069. } else {
  167070. /* Re-initialize all AC-related fields to 0 */
  167071. entropy->EOBRUN = 0;
  167072. entropy->BE = 0;
  167073. }
  167074. }
  167075. /*
  167076. * MCU encoding for DC initial scan (either spectral selection,
  167077. * or first pass of successive approximation).
  167078. */
  167079. METHODDEF(boolean)
  167080. encode_mcu_DC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  167081. {
  167082. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  167083. register int temp, temp2;
  167084. register int nbits;
  167085. int blkn, ci;
  167086. int Al = cinfo->Al;
  167087. JBLOCKROW block;
  167088. jpeg_component_info * compptr;
  167089. ISHIFT_TEMPS
  167090. entropy->next_output_byte = cinfo->dest->next_output_byte;
  167091. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  167092. /* Emit restart marker if needed */
  167093. if (cinfo->restart_interval)
  167094. if (entropy->restarts_to_go == 0)
  167095. emit_restart_p(entropy, entropy->next_restart_num);
  167096. /* Encode the MCU data blocks */
  167097. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  167098. block = MCU_data[blkn];
  167099. ci = cinfo->MCU_membership[blkn];
  167100. compptr = cinfo->cur_comp_info[ci];
  167101. /* Compute the DC value after the required point transform by Al.
  167102. * This is simply an arithmetic right shift.
  167103. */
  167104. temp2 = IRIGHT_SHIFT((int) ((*block)[0]), Al);
  167105. /* DC differences are figured on the point-transformed values. */
  167106. temp = temp2 - entropy->last_dc_val[ci];
  167107. entropy->last_dc_val[ci] = temp2;
  167108. /* Encode the DC coefficient difference per section G.1.2.1 */
  167109. temp2 = temp;
  167110. if (temp < 0) {
  167111. temp = -temp; /* temp is abs value of input */
  167112. /* For a negative input, want temp2 = bitwise complement of abs(input) */
  167113. /* This code assumes we are on a two's complement machine */
  167114. temp2--;
  167115. }
  167116. /* Find the number of bits needed for the magnitude of the coefficient */
  167117. nbits = 0;
  167118. while (temp) {
  167119. nbits++;
  167120. temp >>= 1;
  167121. }
  167122. /* Check for out-of-range coefficient values.
  167123. * Since we're encoding a difference, the range limit is twice as much.
  167124. */
  167125. if (nbits > MAX_COEF_BITS+1)
  167126. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  167127. /* Count/emit the Huffman-coded symbol for the number of bits */
  167128. emit_symbol(entropy, compptr->dc_tbl_no, nbits);
  167129. /* Emit that number of bits of the value, if positive, */
  167130. /* or the complement of its magnitude, if negative. */
  167131. if (nbits) /* emit_bits rejects calls with size 0 */
  167132. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  167133. }
  167134. cinfo->dest->next_output_byte = entropy->next_output_byte;
  167135. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  167136. /* Update restart-interval state too */
  167137. if (cinfo->restart_interval) {
  167138. if (entropy->restarts_to_go == 0) {
  167139. entropy->restarts_to_go = cinfo->restart_interval;
  167140. entropy->next_restart_num++;
  167141. entropy->next_restart_num &= 7;
  167142. }
  167143. entropy->restarts_to_go--;
  167144. }
  167145. return TRUE;
  167146. }
  167147. /*
  167148. * MCU encoding for AC initial scan (either spectral selection,
  167149. * or first pass of successive approximation).
  167150. */
  167151. METHODDEF(boolean)
  167152. encode_mcu_AC_first (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  167153. {
  167154. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  167155. register int temp, temp2;
  167156. register int nbits;
  167157. register int r, k;
  167158. int Se = cinfo->Se;
  167159. int Al = cinfo->Al;
  167160. JBLOCKROW block;
  167161. entropy->next_output_byte = cinfo->dest->next_output_byte;
  167162. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  167163. /* Emit restart marker if needed */
  167164. if (cinfo->restart_interval)
  167165. if (entropy->restarts_to_go == 0)
  167166. emit_restart_p(entropy, entropy->next_restart_num);
  167167. /* Encode the MCU data block */
  167168. block = MCU_data[0];
  167169. /* Encode the AC coefficients per section G.1.2.2, fig. G.3 */
  167170. r = 0; /* r = run length of zeros */
  167171. for (k = cinfo->Ss; k <= Se; k++) {
  167172. if ((temp = (*block)[jpeg_natural_order[k]]) == 0) {
  167173. r++;
  167174. continue;
  167175. }
  167176. /* We must apply the point transform by Al. For AC coefficients this
  167177. * is an integer division with rounding towards 0. To do this portably
  167178. * in C, we shift after obtaining the absolute value; so the code is
  167179. * interwoven with finding the abs value (temp) and output bits (temp2).
  167180. */
  167181. if (temp < 0) {
  167182. temp = -temp; /* temp is abs value of input */
  167183. temp >>= Al; /* apply the point transform */
  167184. /* For a negative coef, want temp2 = bitwise complement of abs(coef) */
  167185. temp2 = ~temp;
  167186. } else {
  167187. temp >>= Al; /* apply the point transform */
  167188. temp2 = temp;
  167189. }
  167190. /* Watch out for case that nonzero coef is zero after point transform */
  167191. if (temp == 0) {
  167192. r++;
  167193. continue;
  167194. }
  167195. /* Emit any pending EOBRUN */
  167196. if (entropy->EOBRUN > 0)
  167197. emit_eobrun(entropy);
  167198. /* if run length > 15, must emit special run-length-16 codes (0xF0) */
  167199. while (r > 15) {
  167200. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  167201. r -= 16;
  167202. }
  167203. /* Find the number of bits needed for the magnitude of the coefficient */
  167204. nbits = 1; /* there must be at least one 1 bit */
  167205. while ((temp >>= 1))
  167206. nbits++;
  167207. /* Check for out-of-range coefficient values */
  167208. if (nbits > MAX_COEF_BITS)
  167209. ERREXIT(cinfo, JERR_BAD_DCT_COEF);
  167210. /* Count/emit Huffman symbol for run length / number of bits */
  167211. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + nbits);
  167212. /* Emit that number of bits of the value, if positive, */
  167213. /* or the complement of its magnitude, if negative. */
  167214. emit_bits_p(entropy, (unsigned int) temp2, nbits);
  167215. r = 0; /* reset zero run length */
  167216. }
  167217. if (r > 0) { /* If there are trailing zeroes, */
  167218. entropy->EOBRUN++; /* count an EOB */
  167219. if (entropy->EOBRUN == 0x7FFF)
  167220. emit_eobrun(entropy); /* force it out to avoid overflow */
  167221. }
  167222. cinfo->dest->next_output_byte = entropy->next_output_byte;
  167223. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  167224. /* Update restart-interval state too */
  167225. if (cinfo->restart_interval) {
  167226. if (entropy->restarts_to_go == 0) {
  167227. entropy->restarts_to_go = cinfo->restart_interval;
  167228. entropy->next_restart_num++;
  167229. entropy->next_restart_num &= 7;
  167230. }
  167231. entropy->restarts_to_go--;
  167232. }
  167233. return TRUE;
  167234. }
  167235. /*
  167236. * MCU encoding for DC successive approximation refinement scan.
  167237. * Note: we assume such scans can be multi-component, although the spec
  167238. * is not very clear on the point.
  167239. */
  167240. METHODDEF(boolean)
  167241. encode_mcu_DC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  167242. {
  167243. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  167244. register int temp;
  167245. int blkn;
  167246. int Al = cinfo->Al;
  167247. JBLOCKROW block;
  167248. entropy->next_output_byte = cinfo->dest->next_output_byte;
  167249. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  167250. /* Emit restart marker if needed */
  167251. if (cinfo->restart_interval)
  167252. if (entropy->restarts_to_go == 0)
  167253. emit_restart_p(entropy, entropy->next_restart_num);
  167254. /* Encode the MCU data blocks */
  167255. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  167256. block = MCU_data[blkn];
  167257. /* We simply emit the Al'th bit of the DC coefficient value. */
  167258. temp = (*block)[0];
  167259. emit_bits_p(entropy, (unsigned int) (temp >> Al), 1);
  167260. }
  167261. cinfo->dest->next_output_byte = entropy->next_output_byte;
  167262. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  167263. /* Update restart-interval state too */
  167264. if (cinfo->restart_interval) {
  167265. if (entropy->restarts_to_go == 0) {
  167266. entropy->restarts_to_go = cinfo->restart_interval;
  167267. entropy->next_restart_num++;
  167268. entropy->next_restart_num &= 7;
  167269. }
  167270. entropy->restarts_to_go--;
  167271. }
  167272. return TRUE;
  167273. }
  167274. /*
  167275. * MCU encoding for AC successive approximation refinement scan.
  167276. */
  167277. METHODDEF(boolean)
  167278. encode_mcu_AC_refine (j_compress_ptr cinfo, JBLOCKROW *MCU_data)
  167279. {
  167280. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  167281. register int temp;
  167282. register int r, k;
  167283. int EOB;
  167284. char *BR_buffer;
  167285. unsigned int BR;
  167286. int Se = cinfo->Se;
  167287. int Al = cinfo->Al;
  167288. JBLOCKROW block;
  167289. int absvalues[DCTSIZE2];
  167290. entropy->next_output_byte = cinfo->dest->next_output_byte;
  167291. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  167292. /* Emit restart marker if needed */
  167293. if (cinfo->restart_interval)
  167294. if (entropy->restarts_to_go == 0)
  167295. emit_restart_p(entropy, entropy->next_restart_num);
  167296. /* Encode the MCU data block */
  167297. block = MCU_data[0];
  167298. /* It is convenient to make a pre-pass to determine the transformed
  167299. * coefficients' absolute values and the EOB position.
  167300. */
  167301. EOB = 0;
  167302. for (k = cinfo->Ss; k <= Se; k++) {
  167303. temp = (*block)[jpeg_natural_order[k]];
  167304. /* We must apply the point transform by Al. For AC coefficients this
  167305. * is an integer division with rounding towards 0. To do this portably
  167306. * in C, we shift after obtaining the absolute value.
  167307. */
  167308. if (temp < 0)
  167309. temp = -temp; /* temp is abs value of input */
  167310. temp >>= Al; /* apply the point transform */
  167311. absvalues[k] = temp; /* save abs value for main pass */
  167312. if (temp == 1)
  167313. EOB = k; /* EOB = index of last newly-nonzero coef */
  167314. }
  167315. /* Encode the AC coefficients per section G.1.2.3, fig. G.7 */
  167316. r = 0; /* r = run length of zeros */
  167317. BR = 0; /* BR = count of buffered bits added now */
  167318. BR_buffer = entropy->bit_buffer + entropy->BE; /* Append bits to buffer */
  167319. for (k = cinfo->Ss; k <= Se; k++) {
  167320. if ((temp = absvalues[k]) == 0) {
  167321. r++;
  167322. continue;
  167323. }
  167324. /* Emit any required ZRLs, but not if they can be folded into EOB */
  167325. while (r > 15 && k <= EOB) {
  167326. /* emit any pending EOBRUN and the BE correction bits */
  167327. emit_eobrun(entropy);
  167328. /* Emit ZRL */
  167329. emit_symbol(entropy, entropy->ac_tbl_no, 0xF0);
  167330. r -= 16;
  167331. /* Emit buffered correction bits that must be associated with ZRL */
  167332. emit_buffered_bits(entropy, BR_buffer, BR);
  167333. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  167334. BR = 0;
  167335. }
  167336. /* If the coef was previously nonzero, it only needs a correction bit.
  167337. * NOTE: a straight translation of the spec's figure G.7 would suggest
  167338. * that we also need to test r > 15. But if r > 15, we can only get here
  167339. * if k > EOB, which implies that this coefficient is not 1.
  167340. */
  167341. if (temp > 1) {
  167342. /* The correction bit is the next bit of the absolute value. */
  167343. BR_buffer[BR++] = (char) (temp & 1);
  167344. continue;
  167345. }
  167346. /* Emit any pending EOBRUN and the BE correction bits */
  167347. emit_eobrun(entropy);
  167348. /* Count/emit Huffman symbol for run length / number of bits */
  167349. emit_symbol(entropy, entropy->ac_tbl_no, (r << 4) + 1);
  167350. /* Emit output bit for newly-nonzero coef */
  167351. temp = ((*block)[jpeg_natural_order[k]] < 0) ? 0 : 1;
  167352. emit_bits_p(entropy, (unsigned int) temp, 1);
  167353. /* Emit buffered correction bits that must be associated with this code */
  167354. emit_buffered_bits(entropy, BR_buffer, BR);
  167355. BR_buffer = entropy->bit_buffer; /* BE bits are gone now */
  167356. BR = 0;
  167357. r = 0; /* reset zero run length */
  167358. }
  167359. if (r > 0 || BR > 0) { /* If there are trailing zeroes, */
  167360. entropy->EOBRUN++; /* count an EOB */
  167361. entropy->BE += BR; /* concat my correction bits to older ones */
  167362. /* We force out the EOB if we risk either:
  167363. * 1. overflow of the EOB counter;
  167364. * 2. overflow of the correction bit buffer during the next MCU.
  167365. */
  167366. if (entropy->EOBRUN == 0x7FFF || entropy->BE > (MAX_CORR_BITS-DCTSIZE2+1))
  167367. emit_eobrun(entropy);
  167368. }
  167369. cinfo->dest->next_output_byte = entropy->next_output_byte;
  167370. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  167371. /* Update restart-interval state too */
  167372. if (cinfo->restart_interval) {
  167373. if (entropy->restarts_to_go == 0) {
  167374. entropy->restarts_to_go = cinfo->restart_interval;
  167375. entropy->next_restart_num++;
  167376. entropy->next_restart_num &= 7;
  167377. }
  167378. entropy->restarts_to_go--;
  167379. }
  167380. return TRUE;
  167381. }
  167382. /*
  167383. * Finish up at the end of a Huffman-compressed progressive scan.
  167384. */
  167385. METHODDEF(void)
  167386. finish_pass_phuff (j_compress_ptr cinfo)
  167387. {
  167388. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  167389. entropy->next_output_byte = cinfo->dest->next_output_byte;
  167390. entropy->free_in_buffer = cinfo->dest->free_in_buffer;
  167391. /* Flush out any buffered data */
  167392. emit_eobrun(entropy);
  167393. flush_bits_p(entropy);
  167394. cinfo->dest->next_output_byte = entropy->next_output_byte;
  167395. cinfo->dest->free_in_buffer = entropy->free_in_buffer;
  167396. }
  167397. /*
  167398. * Finish up a statistics-gathering pass and create the new Huffman tables.
  167399. */
  167400. METHODDEF(void)
  167401. finish_pass_gather_phuff (j_compress_ptr cinfo)
  167402. {
  167403. phuff_entropy_ptr entropy = (phuff_entropy_ptr) cinfo->entropy;
  167404. boolean is_DC_band;
  167405. int ci, tbl;
  167406. jpeg_component_info * compptr;
  167407. JHUFF_TBL **htblptr;
  167408. boolean did[NUM_HUFF_TBLS];
  167409. /* Flush out buffered data (all we care about is counting the EOB symbol) */
  167410. emit_eobrun(entropy);
  167411. is_DC_band = (cinfo->Ss == 0);
  167412. /* It's important not to apply jpeg_gen_optimal_table more than once
  167413. * per table, because it clobbers the input frequency counts!
  167414. */
  167415. MEMZERO(did, SIZEOF(did));
  167416. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  167417. compptr = cinfo->cur_comp_info[ci];
  167418. if (is_DC_band) {
  167419. if (cinfo->Ah != 0) /* DC refinement needs no table */
  167420. continue;
  167421. tbl = compptr->dc_tbl_no;
  167422. } else {
  167423. tbl = compptr->ac_tbl_no;
  167424. }
  167425. if (! did[tbl]) {
  167426. if (is_DC_band)
  167427. htblptr = & cinfo->dc_huff_tbl_ptrs[tbl];
  167428. else
  167429. htblptr = & cinfo->ac_huff_tbl_ptrs[tbl];
  167430. if (*htblptr == NULL)
  167431. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  167432. jpeg_gen_optimal_table(cinfo, *htblptr, entropy->count_ptrs[tbl]);
  167433. did[tbl] = TRUE;
  167434. }
  167435. }
  167436. }
  167437. /*
  167438. * Module initialization routine for progressive Huffman entropy encoding.
  167439. */
  167440. GLOBAL(void)
  167441. jinit_phuff_encoder (j_compress_ptr cinfo)
  167442. {
  167443. phuff_entropy_ptr entropy;
  167444. int i;
  167445. entropy = (phuff_entropy_ptr)
  167446. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167447. SIZEOF(phuff_entropy_encoder));
  167448. cinfo->entropy = (struct jpeg_entropy_encoder *) entropy;
  167449. entropy->pub.start_pass = start_pass_phuff;
  167450. /* Mark tables unallocated */
  167451. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  167452. entropy->derived_tbls[i] = NULL;
  167453. entropy->count_ptrs[i] = NULL;
  167454. }
  167455. entropy->bit_buffer = NULL; /* needed only in AC refinement scan */
  167456. }
  167457. #endif /* C_PROGRESSIVE_SUPPORTED */
  167458. /********* End of inlined file: jcphuff.c *********/
  167459. /********* Start of inlined file: jcprepct.c *********/
  167460. #define JPEG_INTERNALS
  167461. /* At present, jcsample.c can request context rows only for smoothing.
  167462. * In the future, we might also need context rows for CCIR601 sampling
  167463. * or other more-complex downsampling procedures. The code to support
  167464. * context rows should be compiled only if needed.
  167465. */
  167466. #ifdef INPUT_SMOOTHING_SUPPORTED
  167467. #define CONTEXT_ROWS_SUPPORTED
  167468. #endif
  167469. /*
  167470. * For the simple (no-context-row) case, we just need to buffer one
  167471. * row group's worth of pixels for the downsampling step. At the bottom of
  167472. * the image, we pad to a full row group by replicating the last pixel row.
  167473. * The downsampler's last output row is then replicated if needed to pad
  167474. * out to a full iMCU row.
  167475. *
  167476. * When providing context rows, we must buffer three row groups' worth of
  167477. * pixels. Three row groups are physically allocated, but the row pointer
  167478. * arrays are made five row groups high, with the extra pointers above and
  167479. * below "wrapping around" to point to the last and first real row groups.
  167480. * This allows the downsampler to access the proper context rows.
  167481. * At the top and bottom of the image, we create dummy context rows by
  167482. * copying the first or last real pixel row. This copying could be avoided
  167483. * by pointer hacking as is done in jdmainct.c, but it doesn't seem worth the
  167484. * trouble on the compression side.
  167485. */
  167486. /* Private buffer controller object */
  167487. typedef struct {
  167488. struct jpeg_c_prep_controller pub; /* public fields */
  167489. /* Downsampling input buffer. This buffer holds color-converted data
  167490. * until we have enough to do a downsample step.
  167491. */
  167492. JSAMPARRAY color_buf[MAX_COMPONENTS];
  167493. JDIMENSION rows_to_go; /* counts rows remaining in source image */
  167494. int next_buf_row; /* index of next row to store in color_buf */
  167495. #ifdef CONTEXT_ROWS_SUPPORTED /* only needed for context case */
  167496. int this_row_group; /* starting row index of group to process */
  167497. int next_buf_stop; /* downsample when we reach this index */
  167498. #endif
  167499. } my_prep_controller;
  167500. typedef my_prep_controller * my_prep_ptr;
  167501. /*
  167502. * Initialize for a processing pass.
  167503. */
  167504. METHODDEF(void)
  167505. start_pass_prep (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  167506. {
  167507. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  167508. if (pass_mode != JBUF_PASS_THRU)
  167509. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167510. /* Initialize total-height counter for detecting bottom of image */
  167511. prep->rows_to_go = cinfo->image_height;
  167512. /* Mark the conversion buffer empty */
  167513. prep->next_buf_row = 0;
  167514. #ifdef CONTEXT_ROWS_SUPPORTED
  167515. /* Preset additional state variables for context mode.
  167516. * These aren't used in non-context mode, so we needn't test which mode.
  167517. */
  167518. prep->this_row_group = 0;
  167519. /* Set next_buf_stop to stop after two row groups have been read in. */
  167520. prep->next_buf_stop = 2 * cinfo->max_v_samp_factor;
  167521. #endif
  167522. }
  167523. /*
  167524. * Expand an image vertically from height input_rows to height output_rows,
  167525. * by duplicating the bottom row.
  167526. */
  167527. LOCAL(void)
  167528. expand_bottom_edge (JSAMPARRAY image_data, JDIMENSION num_cols,
  167529. int input_rows, int output_rows)
  167530. {
  167531. register int row;
  167532. for (row = input_rows; row < output_rows; row++) {
  167533. jcopy_sample_rows(image_data, input_rows-1, image_data, row,
  167534. 1, num_cols);
  167535. }
  167536. }
  167537. /*
  167538. * Process some data in the simple no-context case.
  167539. *
  167540. * Preprocessor output data is counted in "row groups". A row group
  167541. * is defined to be v_samp_factor sample rows of each component.
  167542. * Downsampling will produce this much data from each max_v_samp_factor
  167543. * input rows.
  167544. */
  167545. METHODDEF(void)
  167546. pre_process_data (j_compress_ptr cinfo,
  167547. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  167548. JDIMENSION in_rows_avail,
  167549. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  167550. JDIMENSION out_row_groups_avail)
  167551. {
  167552. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  167553. int numrows, ci;
  167554. JDIMENSION inrows;
  167555. jpeg_component_info * compptr;
  167556. while (*in_row_ctr < in_rows_avail &&
  167557. *out_row_group_ctr < out_row_groups_avail) {
  167558. /* Do color conversion to fill the conversion buffer. */
  167559. inrows = in_rows_avail - *in_row_ctr;
  167560. numrows = cinfo->max_v_samp_factor - prep->next_buf_row;
  167561. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  167562. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  167563. prep->color_buf,
  167564. (JDIMENSION) prep->next_buf_row,
  167565. numrows);
  167566. *in_row_ctr += numrows;
  167567. prep->next_buf_row += numrows;
  167568. prep->rows_to_go -= numrows;
  167569. /* If at bottom of image, pad to fill the conversion buffer. */
  167570. if (prep->rows_to_go == 0 &&
  167571. prep->next_buf_row < cinfo->max_v_samp_factor) {
  167572. for (ci = 0; ci < cinfo->num_components; ci++) {
  167573. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  167574. prep->next_buf_row, cinfo->max_v_samp_factor);
  167575. }
  167576. prep->next_buf_row = cinfo->max_v_samp_factor;
  167577. }
  167578. /* If we've filled the conversion buffer, empty it. */
  167579. if (prep->next_buf_row == cinfo->max_v_samp_factor) {
  167580. (*cinfo->downsample->downsample) (cinfo,
  167581. prep->color_buf, (JDIMENSION) 0,
  167582. output_buf, *out_row_group_ctr);
  167583. prep->next_buf_row = 0;
  167584. (*out_row_group_ctr)++;
  167585. }
  167586. /* If at bottom of image, pad the output to a full iMCU height.
  167587. * Note we assume the caller is providing a one-iMCU-height output buffer!
  167588. */
  167589. if (prep->rows_to_go == 0 &&
  167590. *out_row_group_ctr < out_row_groups_avail) {
  167591. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167592. ci++, compptr++) {
  167593. expand_bottom_edge(output_buf[ci],
  167594. compptr->width_in_blocks * DCTSIZE,
  167595. (int) (*out_row_group_ctr * compptr->v_samp_factor),
  167596. (int) (out_row_groups_avail * compptr->v_samp_factor));
  167597. }
  167598. *out_row_group_ctr = out_row_groups_avail;
  167599. break; /* can exit outer loop without test */
  167600. }
  167601. }
  167602. }
  167603. #ifdef CONTEXT_ROWS_SUPPORTED
  167604. /*
  167605. * Process some data in the context case.
  167606. */
  167607. METHODDEF(void)
  167608. pre_process_context (j_compress_ptr cinfo,
  167609. JSAMPARRAY input_buf, JDIMENSION *in_row_ctr,
  167610. JDIMENSION in_rows_avail,
  167611. JSAMPIMAGE output_buf, JDIMENSION *out_row_group_ctr,
  167612. JDIMENSION out_row_groups_avail)
  167613. {
  167614. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  167615. int numrows, ci;
  167616. int buf_height = cinfo->max_v_samp_factor * 3;
  167617. JDIMENSION inrows;
  167618. while (*out_row_group_ctr < out_row_groups_avail) {
  167619. if (*in_row_ctr < in_rows_avail) {
  167620. /* Do color conversion to fill the conversion buffer. */
  167621. inrows = in_rows_avail - *in_row_ctr;
  167622. numrows = prep->next_buf_stop - prep->next_buf_row;
  167623. numrows = (int) MIN((JDIMENSION) numrows, inrows);
  167624. (*cinfo->cconvert->color_convert) (cinfo, input_buf + *in_row_ctr,
  167625. prep->color_buf,
  167626. (JDIMENSION) prep->next_buf_row,
  167627. numrows);
  167628. /* Pad at top of image, if first time through */
  167629. if (prep->rows_to_go == cinfo->image_height) {
  167630. for (ci = 0; ci < cinfo->num_components; ci++) {
  167631. int row;
  167632. for (row = 1; row <= cinfo->max_v_samp_factor; row++) {
  167633. jcopy_sample_rows(prep->color_buf[ci], 0,
  167634. prep->color_buf[ci], -row,
  167635. 1, cinfo->image_width);
  167636. }
  167637. }
  167638. }
  167639. *in_row_ctr += numrows;
  167640. prep->next_buf_row += numrows;
  167641. prep->rows_to_go -= numrows;
  167642. } else {
  167643. /* Return for more data, unless we are at the bottom of the image. */
  167644. if (prep->rows_to_go != 0)
  167645. break;
  167646. /* When at bottom of image, pad to fill the conversion buffer. */
  167647. if (prep->next_buf_row < prep->next_buf_stop) {
  167648. for (ci = 0; ci < cinfo->num_components; ci++) {
  167649. expand_bottom_edge(prep->color_buf[ci], cinfo->image_width,
  167650. prep->next_buf_row, prep->next_buf_stop);
  167651. }
  167652. prep->next_buf_row = prep->next_buf_stop;
  167653. }
  167654. }
  167655. /* If we've gotten enough data, downsample a row group. */
  167656. if (prep->next_buf_row == prep->next_buf_stop) {
  167657. (*cinfo->downsample->downsample) (cinfo,
  167658. prep->color_buf,
  167659. (JDIMENSION) prep->this_row_group,
  167660. output_buf, *out_row_group_ctr);
  167661. (*out_row_group_ctr)++;
  167662. /* Advance pointers with wraparound as necessary. */
  167663. prep->this_row_group += cinfo->max_v_samp_factor;
  167664. if (prep->this_row_group >= buf_height)
  167665. prep->this_row_group = 0;
  167666. if (prep->next_buf_row >= buf_height)
  167667. prep->next_buf_row = 0;
  167668. prep->next_buf_stop = prep->next_buf_row + cinfo->max_v_samp_factor;
  167669. }
  167670. }
  167671. }
  167672. /*
  167673. * Create the wrapped-around downsampling input buffer needed for context mode.
  167674. */
  167675. LOCAL(void)
  167676. create_context_buffer (j_compress_ptr cinfo)
  167677. {
  167678. my_prep_ptr prep = (my_prep_ptr) cinfo->prep;
  167679. int rgroup_height = cinfo->max_v_samp_factor;
  167680. int ci, i;
  167681. jpeg_component_info * compptr;
  167682. JSAMPARRAY true_buffer, fake_buffer;
  167683. /* Grab enough space for fake row pointers for all the components;
  167684. * we need five row groups' worth of pointers for each component.
  167685. */
  167686. fake_buffer = (JSAMPARRAY)
  167687. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167688. (cinfo->num_components * 5 * rgroup_height) *
  167689. SIZEOF(JSAMPROW));
  167690. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167691. ci++, compptr++) {
  167692. /* Allocate the actual buffer space (3 row groups) for this component.
  167693. * We make the buffer wide enough to allow the downsampler to edge-expand
  167694. * horizontally within the buffer, if it so chooses.
  167695. */
  167696. true_buffer = (*cinfo->mem->alloc_sarray)
  167697. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167698. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  167699. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  167700. (JDIMENSION) (3 * rgroup_height));
  167701. /* Copy true buffer row pointers into the middle of the fake row array */
  167702. MEMCOPY(fake_buffer + rgroup_height, true_buffer,
  167703. 3 * rgroup_height * SIZEOF(JSAMPROW));
  167704. /* Fill in the above and below wraparound pointers */
  167705. for (i = 0; i < rgroup_height; i++) {
  167706. fake_buffer[i] = true_buffer[2 * rgroup_height + i];
  167707. fake_buffer[4 * rgroup_height + i] = true_buffer[i];
  167708. }
  167709. prep->color_buf[ci] = fake_buffer + rgroup_height;
  167710. fake_buffer += 5 * rgroup_height; /* point to space for next component */
  167711. }
  167712. }
  167713. #endif /* CONTEXT_ROWS_SUPPORTED */
  167714. /*
  167715. * Initialize preprocessing controller.
  167716. */
  167717. GLOBAL(void)
  167718. jinit_c_prep_controller (j_compress_ptr cinfo, boolean need_full_buffer)
  167719. {
  167720. my_prep_ptr prep;
  167721. int ci;
  167722. jpeg_component_info * compptr;
  167723. if (need_full_buffer) /* safety check */
  167724. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  167725. prep = (my_prep_ptr)
  167726. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167727. SIZEOF(my_prep_controller));
  167728. cinfo->prep = (struct jpeg_c_prep_controller *) prep;
  167729. prep->pub.start_pass = start_pass_prep;
  167730. /* Allocate the color conversion buffer.
  167731. * We make the buffer wide enough to allow the downsampler to edge-expand
  167732. * horizontally within the buffer, if it so chooses.
  167733. */
  167734. if (cinfo->downsample->need_context_rows) {
  167735. /* Set up to provide context rows */
  167736. #ifdef CONTEXT_ROWS_SUPPORTED
  167737. prep->pub.pre_process_data = pre_process_context;
  167738. create_context_buffer(cinfo);
  167739. #else
  167740. ERREXIT(cinfo, JERR_NOT_COMPILED);
  167741. #endif
  167742. } else {
  167743. /* No context, just make it tall enough for one row group */
  167744. prep->pub.pre_process_data = pre_process_data;
  167745. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167746. ci++, compptr++) {
  167747. prep->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  167748. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  167749. (JDIMENSION) (((long) compptr->width_in_blocks * DCTSIZE *
  167750. cinfo->max_h_samp_factor) / compptr->h_samp_factor),
  167751. (JDIMENSION) cinfo->max_v_samp_factor);
  167752. }
  167753. }
  167754. }
  167755. /********* End of inlined file: jcprepct.c *********/
  167756. /********* Start of inlined file: jcsample.c *********/
  167757. #define JPEG_INTERNALS
  167758. /* Pointer to routine to downsample a single component */
  167759. typedef JMETHOD(void, downsample1_ptr,
  167760. (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167761. JSAMPARRAY input_data, JSAMPARRAY output_data));
  167762. /* Private subobject */
  167763. typedef struct {
  167764. struct jpeg_downsampler pub; /* public fields */
  167765. /* Downsampling method pointers, one per component */
  167766. downsample1_ptr methods[MAX_COMPONENTS];
  167767. } my_downsampler;
  167768. typedef my_downsampler * my_downsample_ptr;
  167769. /*
  167770. * Initialize for a downsampling pass.
  167771. */
  167772. METHODDEF(void)
  167773. start_pass_downsample (j_compress_ptr cinfo)
  167774. {
  167775. /* no work for now */
  167776. }
  167777. /*
  167778. * Expand a component horizontally from width input_cols to width output_cols,
  167779. * by duplicating the rightmost samples.
  167780. */
  167781. LOCAL(void)
  167782. expand_right_edge (JSAMPARRAY image_data, int num_rows,
  167783. JDIMENSION input_cols, JDIMENSION output_cols)
  167784. {
  167785. register JSAMPROW ptr;
  167786. register JSAMPLE pixval;
  167787. register int count;
  167788. int row;
  167789. int numcols = (int) (output_cols - input_cols);
  167790. if (numcols > 0) {
  167791. for (row = 0; row < num_rows; row++) {
  167792. ptr = image_data[row] + input_cols;
  167793. pixval = ptr[-1]; /* don't need GETJSAMPLE() here */
  167794. for (count = numcols; count > 0; count--)
  167795. *ptr++ = pixval;
  167796. }
  167797. }
  167798. }
  167799. /*
  167800. * Do downsampling for a whole row group (all components).
  167801. *
  167802. * In this version we simply downsample each component independently.
  167803. */
  167804. METHODDEF(void)
  167805. sep_downsample (j_compress_ptr cinfo,
  167806. JSAMPIMAGE input_buf, JDIMENSION in_row_index,
  167807. JSAMPIMAGE output_buf, JDIMENSION out_row_group_index)
  167808. {
  167809. my_downsample_ptr downsample = (my_downsample_ptr) cinfo->downsample;
  167810. int ci;
  167811. jpeg_component_info * compptr;
  167812. JSAMPARRAY in_ptr, out_ptr;
  167813. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  167814. ci++, compptr++) {
  167815. in_ptr = input_buf[ci] + in_row_index;
  167816. out_ptr = output_buf[ci] + (out_row_group_index * compptr->v_samp_factor);
  167817. (*downsample->methods[ci]) (cinfo, compptr, in_ptr, out_ptr);
  167818. }
  167819. }
  167820. /*
  167821. * Downsample pixel values of a single component.
  167822. * One row group is processed per call.
  167823. * This version handles arbitrary integral sampling ratios, without smoothing.
  167824. * Note that this version is not actually used for customary sampling ratios.
  167825. */
  167826. METHODDEF(void)
  167827. int_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167828. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167829. {
  167830. int inrow, outrow, h_expand, v_expand, numpix, numpix2, h, v;
  167831. JDIMENSION outcol, outcol_h; /* outcol_h == outcol*h_expand */
  167832. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167833. JSAMPROW inptr, outptr;
  167834. INT32 outvalue;
  167835. h_expand = cinfo->max_h_samp_factor / compptr->h_samp_factor;
  167836. v_expand = cinfo->max_v_samp_factor / compptr->v_samp_factor;
  167837. numpix = h_expand * v_expand;
  167838. numpix2 = numpix/2;
  167839. /* Expand input data enough to let all the output samples be generated
  167840. * by the standard loop. Special-casing padded output would be more
  167841. * efficient.
  167842. */
  167843. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167844. cinfo->image_width, output_cols * h_expand);
  167845. inrow = 0;
  167846. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167847. outptr = output_data[outrow];
  167848. for (outcol = 0, outcol_h = 0; outcol < output_cols;
  167849. outcol++, outcol_h += h_expand) {
  167850. outvalue = 0;
  167851. for (v = 0; v < v_expand; v++) {
  167852. inptr = input_data[inrow+v] + outcol_h;
  167853. for (h = 0; h < h_expand; h++) {
  167854. outvalue += (INT32) GETJSAMPLE(*inptr++);
  167855. }
  167856. }
  167857. *outptr++ = (JSAMPLE) ((outvalue + numpix2) / numpix);
  167858. }
  167859. inrow += v_expand;
  167860. }
  167861. }
  167862. /*
  167863. * Downsample pixel values of a single component.
  167864. * This version handles the special case of a full-size component,
  167865. * without smoothing.
  167866. */
  167867. METHODDEF(void)
  167868. fullsize_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167869. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167870. {
  167871. /* Copy the data */
  167872. jcopy_sample_rows(input_data, 0, output_data, 0,
  167873. cinfo->max_v_samp_factor, cinfo->image_width);
  167874. /* Edge-expand */
  167875. expand_right_edge(output_data, cinfo->max_v_samp_factor,
  167876. cinfo->image_width, compptr->width_in_blocks * DCTSIZE);
  167877. }
  167878. /*
  167879. * Downsample pixel values of a single component.
  167880. * This version handles the common case of 2:1 horizontal and 1:1 vertical,
  167881. * without smoothing.
  167882. *
  167883. * A note about the "bias" calculations: when rounding fractional values to
  167884. * integer, we do not want to always round 0.5 up to the next integer.
  167885. * If we did that, we'd introduce a noticeable bias towards larger values.
  167886. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  167887. * alternate pixel locations (a simple ordered dither pattern).
  167888. */
  167889. METHODDEF(void)
  167890. h2v1_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167891. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167892. {
  167893. int outrow;
  167894. JDIMENSION outcol;
  167895. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167896. register JSAMPROW inptr, outptr;
  167897. register int bias;
  167898. /* Expand input data enough to let all the output samples be generated
  167899. * by the standard loop. Special-casing padded output would be more
  167900. * efficient.
  167901. */
  167902. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167903. cinfo->image_width, output_cols * 2);
  167904. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167905. outptr = output_data[outrow];
  167906. inptr = input_data[outrow];
  167907. bias = 0; /* bias = 0,1,0,1,... for successive samples */
  167908. for (outcol = 0; outcol < output_cols; outcol++) {
  167909. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr) + GETJSAMPLE(inptr[1])
  167910. + bias) >> 1);
  167911. bias ^= 1; /* 0=>1, 1=>0 */
  167912. inptr += 2;
  167913. }
  167914. }
  167915. }
  167916. /*
  167917. * Downsample pixel values of a single component.
  167918. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167919. * without smoothing.
  167920. */
  167921. METHODDEF(void)
  167922. h2v2_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167923. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167924. {
  167925. int inrow, outrow;
  167926. JDIMENSION outcol;
  167927. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167928. register JSAMPROW inptr0, inptr1, outptr;
  167929. register int bias;
  167930. /* Expand input data enough to let all the output samples be generated
  167931. * by the standard loop. Special-casing padded output would be more
  167932. * efficient.
  167933. */
  167934. expand_right_edge(input_data, cinfo->max_v_samp_factor,
  167935. cinfo->image_width, output_cols * 2);
  167936. inrow = 0;
  167937. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167938. outptr = output_data[outrow];
  167939. inptr0 = input_data[inrow];
  167940. inptr1 = input_data[inrow+1];
  167941. bias = 1; /* bias = 1,2,1,2,... for successive samples */
  167942. for (outcol = 0; outcol < output_cols; outcol++) {
  167943. *outptr++ = (JSAMPLE) ((GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167944. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1])
  167945. + bias) >> 2);
  167946. bias ^= 3; /* 1=>2, 2=>1 */
  167947. inptr0 += 2; inptr1 += 2;
  167948. }
  167949. inrow += 2;
  167950. }
  167951. }
  167952. #ifdef INPUT_SMOOTHING_SUPPORTED
  167953. /*
  167954. * Downsample pixel values of a single component.
  167955. * This version handles the standard case of 2:1 horizontal and 2:1 vertical,
  167956. * with smoothing. One row of context is required.
  167957. */
  167958. METHODDEF(void)
  167959. h2v2_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info * compptr,
  167960. JSAMPARRAY input_data, JSAMPARRAY output_data)
  167961. {
  167962. int inrow, outrow;
  167963. JDIMENSION colctr;
  167964. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  167965. register JSAMPROW inptr0, inptr1, above_ptr, below_ptr, outptr;
  167966. INT32 membersum, neighsum, memberscale, neighscale;
  167967. /* Expand input data enough to let all the output samples be generated
  167968. * by the standard loop. Special-casing padded output would be more
  167969. * efficient.
  167970. */
  167971. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  167972. cinfo->image_width, output_cols * 2);
  167973. /* We don't bother to form the individual "smoothed" input pixel values;
  167974. * we can directly compute the output which is the average of the four
  167975. * smoothed values. Each of the four member pixels contributes a fraction
  167976. * (1-8*SF) to its own smoothed image and a fraction SF to each of the three
  167977. * other smoothed pixels, therefore a total fraction (1-5*SF)/4 to the final
  167978. * output. The four corner-adjacent neighbor pixels contribute a fraction
  167979. * SF to just one smoothed pixel, or SF/4 to the final output; while the
  167980. * eight edge-adjacent neighbors contribute SF to each of two smoothed
  167981. * pixels, or SF/2 overall. In order to use integer arithmetic, these
  167982. * factors are scaled by 2^16 = 65536.
  167983. * Also recall that SF = smoothing_factor / 1024.
  167984. */
  167985. memberscale = 16384 - cinfo->smoothing_factor * 80; /* scaled (1-5*SF)/4 */
  167986. neighscale = cinfo->smoothing_factor * 16; /* scaled SF/4 */
  167987. inrow = 0;
  167988. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  167989. outptr = output_data[outrow];
  167990. inptr0 = input_data[inrow];
  167991. inptr1 = input_data[inrow+1];
  167992. above_ptr = input_data[inrow-1];
  167993. below_ptr = input_data[inrow+2];
  167994. /* Special case for first column: pretend column -1 is same as column 0 */
  167995. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  167996. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  167997. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  167998. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  167999. GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[2]) +
  168000. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[2]);
  168001. neighsum += neighsum;
  168002. neighsum += GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[2]) +
  168003. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[2]);
  168004. membersum = membersum * memberscale + neighsum * neighscale;
  168005. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  168006. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  168007. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  168008. /* sum of pixels directly mapped to this output element */
  168009. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  168010. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  168011. /* sum of edge-neighbor pixels */
  168012. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  168013. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  168014. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[2]) +
  168015. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[2]);
  168016. /* The edge-neighbors count twice as much as corner-neighbors */
  168017. neighsum += neighsum;
  168018. /* Add in the corner-neighbors */
  168019. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[2]) +
  168020. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[2]);
  168021. /* form final output scaled up by 2^16 */
  168022. membersum = membersum * memberscale + neighsum * neighscale;
  168023. /* round, descale and output it */
  168024. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  168025. inptr0 += 2; inptr1 += 2; above_ptr += 2; below_ptr += 2;
  168026. }
  168027. /* Special case for last column */
  168028. membersum = GETJSAMPLE(*inptr0) + GETJSAMPLE(inptr0[1]) +
  168029. GETJSAMPLE(*inptr1) + GETJSAMPLE(inptr1[1]);
  168030. neighsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(above_ptr[1]) +
  168031. GETJSAMPLE(*below_ptr) + GETJSAMPLE(below_ptr[1]) +
  168032. GETJSAMPLE(inptr0[-1]) + GETJSAMPLE(inptr0[1]) +
  168033. GETJSAMPLE(inptr1[-1]) + GETJSAMPLE(inptr1[1]);
  168034. neighsum += neighsum;
  168035. neighsum += GETJSAMPLE(above_ptr[-1]) + GETJSAMPLE(above_ptr[1]) +
  168036. GETJSAMPLE(below_ptr[-1]) + GETJSAMPLE(below_ptr[1]);
  168037. membersum = membersum * memberscale + neighsum * neighscale;
  168038. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  168039. inrow += 2;
  168040. }
  168041. }
  168042. /*
  168043. * Downsample pixel values of a single component.
  168044. * This version handles the special case of a full-size component,
  168045. * with smoothing. One row of context is required.
  168046. */
  168047. METHODDEF(void)
  168048. fullsize_smooth_downsample (j_compress_ptr cinfo, jpeg_component_info *compptr,
  168049. JSAMPARRAY input_data, JSAMPARRAY output_data)
  168050. {
  168051. int outrow;
  168052. JDIMENSION colctr;
  168053. JDIMENSION output_cols = compptr->width_in_blocks * DCTSIZE;
  168054. register JSAMPROW inptr, above_ptr, below_ptr, outptr;
  168055. INT32 membersum, neighsum, memberscale, neighscale;
  168056. int colsum, lastcolsum, nextcolsum;
  168057. /* Expand input data enough to let all the output samples be generated
  168058. * by the standard loop. Special-casing padded output would be more
  168059. * efficient.
  168060. */
  168061. expand_right_edge(input_data - 1, cinfo->max_v_samp_factor + 2,
  168062. cinfo->image_width, output_cols);
  168063. /* Each of the eight neighbor pixels contributes a fraction SF to the
  168064. * smoothed pixel, while the main pixel contributes (1-8*SF). In order
  168065. * to use integer arithmetic, these factors are multiplied by 2^16 = 65536.
  168066. * Also recall that SF = smoothing_factor / 1024.
  168067. */
  168068. memberscale = 65536L - cinfo->smoothing_factor * 512L; /* scaled 1-8*SF */
  168069. neighscale = cinfo->smoothing_factor * 64; /* scaled SF */
  168070. for (outrow = 0; outrow < compptr->v_samp_factor; outrow++) {
  168071. outptr = output_data[outrow];
  168072. inptr = input_data[outrow];
  168073. above_ptr = input_data[outrow-1];
  168074. below_ptr = input_data[outrow+1];
  168075. /* Special case for first column */
  168076. colsum = GETJSAMPLE(*above_ptr++) + GETJSAMPLE(*below_ptr++) +
  168077. GETJSAMPLE(*inptr);
  168078. membersum = GETJSAMPLE(*inptr++);
  168079. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  168080. GETJSAMPLE(*inptr);
  168081. neighsum = colsum + (colsum - membersum) + nextcolsum;
  168082. membersum = membersum * memberscale + neighsum * neighscale;
  168083. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  168084. lastcolsum = colsum; colsum = nextcolsum;
  168085. for (colctr = output_cols - 2; colctr > 0; colctr--) {
  168086. membersum = GETJSAMPLE(*inptr++);
  168087. above_ptr++; below_ptr++;
  168088. nextcolsum = GETJSAMPLE(*above_ptr) + GETJSAMPLE(*below_ptr) +
  168089. GETJSAMPLE(*inptr);
  168090. neighsum = lastcolsum + (colsum - membersum) + nextcolsum;
  168091. membersum = membersum * memberscale + neighsum * neighscale;
  168092. *outptr++ = (JSAMPLE) ((membersum + 32768) >> 16);
  168093. lastcolsum = colsum; colsum = nextcolsum;
  168094. }
  168095. /* Special case for last column */
  168096. membersum = GETJSAMPLE(*inptr);
  168097. neighsum = lastcolsum + (colsum - membersum) + colsum;
  168098. membersum = membersum * memberscale + neighsum * neighscale;
  168099. *outptr = (JSAMPLE) ((membersum + 32768) >> 16);
  168100. }
  168101. }
  168102. #endif /* INPUT_SMOOTHING_SUPPORTED */
  168103. /*
  168104. * Module initialization routine for downsampling.
  168105. * Note that we must select a routine for each component.
  168106. */
  168107. GLOBAL(void)
  168108. jinit_downsampler (j_compress_ptr cinfo)
  168109. {
  168110. my_downsample_ptr downsample;
  168111. int ci;
  168112. jpeg_component_info * compptr;
  168113. boolean smoothok = TRUE;
  168114. downsample = (my_downsample_ptr)
  168115. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168116. SIZEOF(my_downsampler));
  168117. cinfo->downsample = (struct jpeg_downsampler *) downsample;
  168118. downsample->pub.start_pass = start_pass_downsample;
  168119. downsample->pub.downsample = sep_downsample;
  168120. downsample->pub.need_context_rows = FALSE;
  168121. if (cinfo->CCIR601_sampling)
  168122. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  168123. /* Verify we can handle the sampling factors, and set up method pointers */
  168124. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  168125. ci++, compptr++) {
  168126. if (compptr->h_samp_factor == cinfo->max_h_samp_factor &&
  168127. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  168128. #ifdef INPUT_SMOOTHING_SUPPORTED
  168129. if (cinfo->smoothing_factor) {
  168130. downsample->methods[ci] = fullsize_smooth_downsample;
  168131. downsample->pub.need_context_rows = TRUE;
  168132. } else
  168133. #endif
  168134. downsample->methods[ci] = fullsize_downsample;
  168135. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  168136. compptr->v_samp_factor == cinfo->max_v_samp_factor) {
  168137. smoothok = FALSE;
  168138. downsample->methods[ci] = h2v1_downsample;
  168139. } else if (compptr->h_samp_factor * 2 == cinfo->max_h_samp_factor &&
  168140. compptr->v_samp_factor * 2 == cinfo->max_v_samp_factor) {
  168141. #ifdef INPUT_SMOOTHING_SUPPORTED
  168142. if (cinfo->smoothing_factor) {
  168143. downsample->methods[ci] = h2v2_smooth_downsample;
  168144. downsample->pub.need_context_rows = TRUE;
  168145. } else
  168146. #endif
  168147. downsample->methods[ci] = h2v2_downsample;
  168148. } else if ((cinfo->max_h_samp_factor % compptr->h_samp_factor) == 0 &&
  168149. (cinfo->max_v_samp_factor % compptr->v_samp_factor) == 0) {
  168150. smoothok = FALSE;
  168151. downsample->methods[ci] = int_downsample;
  168152. } else
  168153. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  168154. }
  168155. #ifdef INPUT_SMOOTHING_SUPPORTED
  168156. if (cinfo->smoothing_factor && !smoothok)
  168157. TRACEMS(cinfo, 0, JTRC_SMOOTH_NOTIMPL);
  168158. #endif
  168159. }
  168160. /********* End of inlined file: jcsample.c *********/
  168161. /********* Start of inlined file: jctrans.c *********/
  168162. #define JPEG_INTERNALS
  168163. /* Forward declarations */
  168164. LOCAL(void) transencode_master_selection
  168165. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  168166. LOCAL(void) transencode_coef_controller
  168167. JPP((j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays));
  168168. /*
  168169. * Compression initialization for writing raw-coefficient data.
  168170. * Before calling this, all parameters and a data destination must be set up.
  168171. * Call jpeg_finish_compress() to actually write the data.
  168172. *
  168173. * The number of passed virtual arrays must match cinfo->num_components.
  168174. * Note that the virtual arrays need not be filled or even realized at
  168175. * the time write_coefficients is called; indeed, if the virtual arrays
  168176. * were requested from this compression object's memory manager, they
  168177. * typically will be realized during this routine and filled afterwards.
  168178. */
  168179. GLOBAL(void)
  168180. jpeg_write_coefficients (j_compress_ptr cinfo, jvirt_barray_ptr * coef_arrays)
  168181. {
  168182. if (cinfo->global_state != CSTATE_START)
  168183. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168184. /* Mark all tables to be written */
  168185. jpeg_suppress_tables(cinfo, FALSE);
  168186. /* (Re)initialize error mgr and destination modules */
  168187. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  168188. (*cinfo->dest->init_destination) (cinfo);
  168189. /* Perform master selection of active modules */
  168190. transencode_master_selection(cinfo, coef_arrays);
  168191. /* Wait for jpeg_finish_compress() call */
  168192. cinfo->next_scanline = 0; /* so jpeg_write_marker works */
  168193. cinfo->global_state = CSTATE_WRCOEFS;
  168194. }
  168195. /*
  168196. * Initialize the compression object with default parameters,
  168197. * then copy from the source object all parameters needed for lossless
  168198. * transcoding. Parameters that can be varied without loss (such as
  168199. * scan script and Huffman optimization) are left in their default states.
  168200. */
  168201. GLOBAL(void)
  168202. jpeg_copy_critical_parameters (j_decompress_ptr srcinfo,
  168203. j_compress_ptr dstinfo)
  168204. {
  168205. JQUANT_TBL ** qtblptr;
  168206. jpeg_component_info *incomp, *outcomp;
  168207. JQUANT_TBL *c_quant, *slot_quant;
  168208. int tblno, ci, coefi;
  168209. /* Safety check to ensure start_compress not called yet. */
  168210. if (dstinfo->global_state != CSTATE_START)
  168211. ERREXIT1(dstinfo, JERR_BAD_STATE, dstinfo->global_state);
  168212. /* Copy fundamental image dimensions */
  168213. dstinfo->image_width = srcinfo->image_width;
  168214. dstinfo->image_height = srcinfo->image_height;
  168215. dstinfo->input_components = srcinfo->num_components;
  168216. dstinfo->in_color_space = srcinfo->jpeg_color_space;
  168217. /* Initialize all parameters to default values */
  168218. jpeg_set_defaults(dstinfo);
  168219. /* jpeg_set_defaults may choose wrong colorspace, eg YCbCr if input is RGB.
  168220. * Fix it to get the right header markers for the image colorspace.
  168221. */
  168222. jpeg_set_colorspace(dstinfo, srcinfo->jpeg_color_space);
  168223. dstinfo->data_precision = srcinfo->data_precision;
  168224. dstinfo->CCIR601_sampling = srcinfo->CCIR601_sampling;
  168225. /* Copy the source's quantization tables. */
  168226. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  168227. if (srcinfo->quant_tbl_ptrs[tblno] != NULL) {
  168228. qtblptr = & dstinfo->quant_tbl_ptrs[tblno];
  168229. if (*qtblptr == NULL)
  168230. *qtblptr = jpeg_alloc_quant_table((j_common_ptr) dstinfo);
  168231. MEMCOPY((*qtblptr)->quantval,
  168232. srcinfo->quant_tbl_ptrs[tblno]->quantval,
  168233. SIZEOF((*qtblptr)->quantval));
  168234. (*qtblptr)->sent_table = FALSE;
  168235. }
  168236. }
  168237. /* Copy the source's per-component info.
  168238. * Note we assume jpeg_set_defaults has allocated the dest comp_info array.
  168239. */
  168240. dstinfo->num_components = srcinfo->num_components;
  168241. if (dstinfo->num_components < 1 || dstinfo->num_components > MAX_COMPONENTS)
  168242. ERREXIT2(dstinfo, JERR_COMPONENT_COUNT, dstinfo->num_components,
  168243. MAX_COMPONENTS);
  168244. for (ci = 0, incomp = srcinfo->comp_info, outcomp = dstinfo->comp_info;
  168245. ci < dstinfo->num_components; ci++, incomp++, outcomp++) {
  168246. outcomp->component_id = incomp->component_id;
  168247. outcomp->h_samp_factor = incomp->h_samp_factor;
  168248. outcomp->v_samp_factor = incomp->v_samp_factor;
  168249. outcomp->quant_tbl_no = incomp->quant_tbl_no;
  168250. /* Make sure saved quantization table for component matches the qtable
  168251. * slot. If not, the input file re-used this qtable slot.
  168252. * IJG encoder currently cannot duplicate this.
  168253. */
  168254. tblno = outcomp->quant_tbl_no;
  168255. if (tblno < 0 || tblno >= NUM_QUANT_TBLS ||
  168256. srcinfo->quant_tbl_ptrs[tblno] == NULL)
  168257. ERREXIT1(dstinfo, JERR_NO_QUANT_TABLE, tblno);
  168258. slot_quant = srcinfo->quant_tbl_ptrs[tblno];
  168259. c_quant = incomp->quant_table;
  168260. if (c_quant != NULL) {
  168261. for (coefi = 0; coefi < DCTSIZE2; coefi++) {
  168262. if (c_quant->quantval[coefi] != slot_quant->quantval[coefi])
  168263. ERREXIT1(dstinfo, JERR_MISMATCHED_QUANT_TABLE, tblno);
  168264. }
  168265. }
  168266. /* Note: we do not copy the source's Huffman table assignments;
  168267. * instead we rely on jpeg_set_colorspace to have made a suitable choice.
  168268. */
  168269. }
  168270. /* Also copy JFIF version and resolution information, if available.
  168271. * Strictly speaking this isn't "critical" info, but it's nearly
  168272. * always appropriate to copy it if available. In particular,
  168273. * if the application chooses to copy JFIF 1.02 extension markers from
  168274. * the source file, we need to copy the version to make sure we don't
  168275. * emit a file that has 1.02 extensions but a claimed version of 1.01.
  168276. * We will *not*, however, copy version info from mislabeled "2.01" files.
  168277. */
  168278. if (srcinfo->saw_JFIF_marker) {
  168279. if (srcinfo->JFIF_major_version == 1) {
  168280. dstinfo->JFIF_major_version = srcinfo->JFIF_major_version;
  168281. dstinfo->JFIF_minor_version = srcinfo->JFIF_minor_version;
  168282. }
  168283. dstinfo->density_unit = srcinfo->density_unit;
  168284. dstinfo->X_density = srcinfo->X_density;
  168285. dstinfo->Y_density = srcinfo->Y_density;
  168286. }
  168287. }
  168288. /*
  168289. * Master selection of compression modules for transcoding.
  168290. * This substitutes for jcinit.c's initialization of the full compressor.
  168291. */
  168292. LOCAL(void)
  168293. transencode_master_selection (j_compress_ptr cinfo,
  168294. jvirt_barray_ptr * coef_arrays)
  168295. {
  168296. /* Although we don't actually use input_components for transcoding,
  168297. * jcmaster.c's initial_setup will complain if input_components is 0.
  168298. */
  168299. cinfo->input_components = 1;
  168300. /* Initialize master control (includes parameter checking/processing) */
  168301. jinit_c_master_control(cinfo, TRUE /* transcode only */);
  168302. /* Entropy encoding: either Huffman or arithmetic coding. */
  168303. if (cinfo->arith_code) {
  168304. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  168305. } else {
  168306. if (cinfo->progressive_mode) {
  168307. #ifdef C_PROGRESSIVE_SUPPORTED
  168308. jinit_phuff_encoder(cinfo);
  168309. #else
  168310. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168311. #endif
  168312. } else
  168313. jinit_huff_encoder(cinfo);
  168314. }
  168315. /* We need a special coefficient buffer controller. */
  168316. transencode_coef_controller(cinfo, coef_arrays);
  168317. jinit_marker_writer(cinfo);
  168318. /* We can now tell the memory manager to allocate virtual arrays. */
  168319. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  168320. /* Write the datastream header (SOI, JFIF) immediately.
  168321. * Frame and scan headers are postponed till later.
  168322. * This lets application insert special markers after the SOI.
  168323. */
  168324. (*cinfo->marker->write_file_header) (cinfo);
  168325. }
  168326. /*
  168327. * The rest of this file is a special implementation of the coefficient
  168328. * buffer controller. This is similar to jccoefct.c, but it handles only
  168329. * output from presupplied virtual arrays. Furthermore, we generate any
  168330. * dummy padding blocks on-the-fly rather than expecting them to be present
  168331. * in the arrays.
  168332. */
  168333. /* Private buffer controller object */
  168334. typedef struct {
  168335. struct jpeg_c_coef_controller pub; /* public fields */
  168336. JDIMENSION iMCU_row_num; /* iMCU row # within image */
  168337. JDIMENSION mcu_ctr; /* counts MCUs processed in current row */
  168338. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  168339. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  168340. /* Virtual block array for each component. */
  168341. jvirt_barray_ptr * whole_image;
  168342. /* Workspace for constructing dummy blocks at right/bottom edges. */
  168343. JBLOCKROW dummy_buffer[C_MAX_BLOCKS_IN_MCU];
  168344. } my_coef_controller2;
  168345. typedef my_coef_controller2 * my_coef_ptr2;
  168346. LOCAL(void)
  168347. start_iMCU_row2 (j_compress_ptr cinfo)
  168348. /* Reset within-iMCU-row counters for a new row */
  168349. {
  168350. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  168351. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  168352. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  168353. * But at the bottom of the image, process only what's left.
  168354. */
  168355. if (cinfo->comps_in_scan > 1) {
  168356. coef->MCU_rows_per_iMCU_row = 1;
  168357. } else {
  168358. if (coef->iMCU_row_num < (cinfo->total_iMCU_rows-1))
  168359. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  168360. else
  168361. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  168362. }
  168363. coef->mcu_ctr = 0;
  168364. coef->MCU_vert_offset = 0;
  168365. }
  168366. /*
  168367. * Initialize for a processing pass.
  168368. */
  168369. METHODDEF(void)
  168370. start_pass_coef2 (j_compress_ptr cinfo, J_BUF_MODE pass_mode)
  168371. {
  168372. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  168373. if (pass_mode != JBUF_CRANK_DEST)
  168374. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  168375. coef->iMCU_row_num = 0;
  168376. start_iMCU_row2(cinfo);
  168377. }
  168378. /*
  168379. * Process some data.
  168380. * We process the equivalent of one fully interleaved MCU row ("iMCU" row)
  168381. * per call, ie, v_samp_factor block rows for each component in the scan.
  168382. * The data is obtained from the virtual arrays and fed to the entropy coder.
  168383. * Returns TRUE if the iMCU row is completed, FALSE if suspended.
  168384. *
  168385. * NB: input_buf is ignored; it is likely to be a NULL pointer.
  168386. */
  168387. METHODDEF(boolean)
  168388. compress_output2 (j_compress_ptr cinfo, JSAMPIMAGE input_buf)
  168389. {
  168390. my_coef_ptr2 coef = (my_coef_ptr2) cinfo->coef;
  168391. JDIMENSION MCU_col_num; /* index of current MCU within row */
  168392. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  168393. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  168394. int blkn, ci, xindex, yindex, yoffset, blockcnt;
  168395. JDIMENSION start_col;
  168396. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  168397. JBLOCKROW MCU_buffer[C_MAX_BLOCKS_IN_MCU];
  168398. JBLOCKROW buffer_ptr;
  168399. jpeg_component_info *compptr;
  168400. /* Align the virtual buffers for the components used in this scan. */
  168401. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168402. compptr = cinfo->cur_comp_info[ci];
  168403. buffer[ci] = (*cinfo->mem->access_virt_barray)
  168404. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  168405. coef->iMCU_row_num * compptr->v_samp_factor,
  168406. (JDIMENSION) compptr->v_samp_factor, FALSE);
  168407. }
  168408. /* Loop to process one whole iMCU row */
  168409. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  168410. yoffset++) {
  168411. for (MCU_col_num = coef->mcu_ctr; MCU_col_num < cinfo->MCUs_per_row;
  168412. MCU_col_num++) {
  168413. /* Construct list of pointers to DCT blocks belonging to this MCU */
  168414. blkn = 0; /* index of current DCT block within MCU */
  168415. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  168416. compptr = cinfo->cur_comp_info[ci];
  168417. start_col = MCU_col_num * compptr->MCU_width;
  168418. blockcnt = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  168419. : compptr->last_col_width;
  168420. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  168421. if (coef->iMCU_row_num < last_iMCU_row ||
  168422. yindex+yoffset < compptr->last_row_height) {
  168423. /* Fill in pointers to real blocks in this row */
  168424. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  168425. for (xindex = 0; xindex < blockcnt; xindex++)
  168426. MCU_buffer[blkn++] = buffer_ptr++;
  168427. } else {
  168428. /* At bottom of image, need a whole row of dummy blocks */
  168429. xindex = 0;
  168430. }
  168431. /* Fill in any dummy blocks needed in this row.
  168432. * Dummy blocks are filled in the same way as in jccoefct.c:
  168433. * all zeroes in the AC entries, DC entries equal to previous
  168434. * block's DC value. The init routine has already zeroed the
  168435. * AC entries, so we need only set the DC entries correctly.
  168436. */
  168437. for (; xindex < compptr->MCU_width; xindex++) {
  168438. MCU_buffer[blkn] = coef->dummy_buffer[blkn];
  168439. MCU_buffer[blkn][0][0] = MCU_buffer[blkn-1][0][0];
  168440. blkn++;
  168441. }
  168442. }
  168443. }
  168444. /* Try to write the MCU. */
  168445. if (! (*cinfo->entropy->encode_mcu) (cinfo, MCU_buffer)) {
  168446. /* Suspension forced; update state counters and exit */
  168447. coef->MCU_vert_offset = yoffset;
  168448. coef->mcu_ctr = MCU_col_num;
  168449. return FALSE;
  168450. }
  168451. }
  168452. /* Completed an MCU row, but perhaps not an iMCU row */
  168453. coef->mcu_ctr = 0;
  168454. }
  168455. /* Completed the iMCU row, advance counters for next one */
  168456. coef->iMCU_row_num++;
  168457. start_iMCU_row2(cinfo);
  168458. return TRUE;
  168459. }
  168460. /*
  168461. * Initialize coefficient buffer controller.
  168462. *
  168463. * Each passed coefficient array must be the right size for that
  168464. * coefficient: width_in_blocks wide and height_in_blocks high,
  168465. * with unitheight at least v_samp_factor.
  168466. */
  168467. LOCAL(void)
  168468. transencode_coef_controller (j_compress_ptr cinfo,
  168469. jvirt_barray_ptr * coef_arrays)
  168470. {
  168471. my_coef_ptr2 coef;
  168472. JBLOCKROW buffer;
  168473. int i;
  168474. coef = (my_coef_ptr2)
  168475. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168476. SIZEOF(my_coef_controller2));
  168477. cinfo->coef = (struct jpeg_c_coef_controller *) coef;
  168478. coef->pub.start_pass = start_pass_coef2;
  168479. coef->pub.compress_data = compress_output2;
  168480. /* Save pointer to virtual arrays */
  168481. coef->whole_image = coef_arrays;
  168482. /* Allocate and pre-zero space for dummy DCT blocks. */
  168483. buffer = (JBLOCKROW)
  168484. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  168485. C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168486. jzero_far((void FAR *) buffer, C_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  168487. for (i = 0; i < C_MAX_BLOCKS_IN_MCU; i++) {
  168488. coef->dummy_buffer[i] = buffer + i;
  168489. }
  168490. }
  168491. /********* End of inlined file: jctrans.c *********/
  168492. /********* Start of inlined file: jdapistd.c *********/
  168493. #define JPEG_INTERNALS
  168494. /* Forward declarations */
  168495. LOCAL(boolean) output_pass_setup JPP((j_decompress_ptr cinfo));
  168496. /*
  168497. * Decompression initialization.
  168498. * jpeg_read_header must be completed before calling this.
  168499. *
  168500. * If a multipass operating mode was selected, this will do all but the
  168501. * last pass, and thus may take a great deal of time.
  168502. *
  168503. * Returns FALSE if suspended. The return value need be inspected only if
  168504. * a suspending data source is used.
  168505. */
  168506. GLOBAL(boolean)
  168507. jpeg_start_decompress (j_decompress_ptr cinfo)
  168508. {
  168509. if (cinfo->global_state == DSTATE_READY) {
  168510. /* First call: initialize master control, select active modules */
  168511. jinit_master_decompress(cinfo);
  168512. if (cinfo->buffered_image) {
  168513. /* No more work here; expecting jpeg_start_output next */
  168514. cinfo->global_state = DSTATE_BUFIMAGE;
  168515. return TRUE;
  168516. }
  168517. cinfo->global_state = DSTATE_PRELOAD;
  168518. }
  168519. if (cinfo->global_state == DSTATE_PRELOAD) {
  168520. /* If file has multiple scans, absorb them all into the coef buffer */
  168521. if (cinfo->inputctl->has_multiple_scans) {
  168522. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168523. for (;;) {
  168524. int retcode;
  168525. /* Call progress monitor hook if present */
  168526. if (cinfo->progress != NULL)
  168527. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  168528. /* Absorb some more input */
  168529. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168530. if (retcode == JPEG_SUSPENDED)
  168531. return FALSE;
  168532. if (retcode == JPEG_REACHED_EOI)
  168533. break;
  168534. /* Advance progress counter if appropriate */
  168535. if (cinfo->progress != NULL &&
  168536. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  168537. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  168538. /* jdmaster underestimated number of scans; ratchet up one scan */
  168539. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  168540. }
  168541. }
  168542. }
  168543. #else
  168544. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168545. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168546. }
  168547. cinfo->output_scan_number = cinfo->input_scan_number;
  168548. } else if (cinfo->global_state != DSTATE_PRESCAN)
  168549. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168550. /* Perform any dummy output passes, and set up for the final pass */
  168551. return output_pass_setup(cinfo);
  168552. }
  168553. /*
  168554. * Set up for an output pass, and perform any dummy pass(es) needed.
  168555. * Common subroutine for jpeg_start_decompress and jpeg_start_output.
  168556. * Entry: global_state = DSTATE_PRESCAN only if previously suspended.
  168557. * Exit: If done, returns TRUE and sets global_state for proper output mode.
  168558. * If suspended, returns FALSE and sets global_state = DSTATE_PRESCAN.
  168559. */
  168560. LOCAL(boolean)
  168561. output_pass_setup (j_decompress_ptr cinfo)
  168562. {
  168563. if (cinfo->global_state != DSTATE_PRESCAN) {
  168564. /* First call: do pass setup */
  168565. (*cinfo->master->prepare_for_output_pass) (cinfo);
  168566. cinfo->output_scanline = 0;
  168567. cinfo->global_state = DSTATE_PRESCAN;
  168568. }
  168569. /* Loop over any required dummy passes */
  168570. while (cinfo->master->is_dummy_pass) {
  168571. #ifdef QUANT_2PASS_SUPPORTED
  168572. /* Crank through the dummy pass */
  168573. while (cinfo->output_scanline < cinfo->output_height) {
  168574. JDIMENSION last_scanline;
  168575. /* Call progress monitor hook if present */
  168576. if (cinfo->progress != NULL) {
  168577. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  168578. cinfo->progress->pass_limit = (long) cinfo->output_height;
  168579. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  168580. }
  168581. /* Process some data */
  168582. last_scanline = cinfo->output_scanline;
  168583. (*cinfo->main->process_data) (cinfo, (JSAMPARRAY) NULL,
  168584. &cinfo->output_scanline, (JDIMENSION) 0);
  168585. if (cinfo->output_scanline == last_scanline)
  168586. return FALSE; /* No progress made, must suspend */
  168587. }
  168588. /* Finish up dummy pass, and set up for another one */
  168589. (*cinfo->master->finish_output_pass) (cinfo);
  168590. (*cinfo->master->prepare_for_output_pass) (cinfo);
  168591. cinfo->output_scanline = 0;
  168592. #else
  168593. ERREXIT(cinfo, JERR_NOT_COMPILED);
  168594. #endif /* QUANT_2PASS_SUPPORTED */
  168595. }
  168596. /* Ready for application to drive output pass through
  168597. * jpeg_read_scanlines or jpeg_read_raw_data.
  168598. */
  168599. cinfo->global_state = cinfo->raw_data_out ? DSTATE_RAW_OK : DSTATE_SCANNING;
  168600. return TRUE;
  168601. }
  168602. /*
  168603. * Read some scanlines of data from the JPEG decompressor.
  168604. *
  168605. * The return value will be the number of lines actually read.
  168606. * This may be less than the number requested in several cases,
  168607. * including bottom of image, data source suspension, and operating
  168608. * modes that emit multiple scanlines at a time.
  168609. *
  168610. * Note: we warn about excess calls to jpeg_read_scanlines() since
  168611. * this likely signals an application programmer error. However,
  168612. * an oversize buffer (max_lines > scanlines remaining) is not an error.
  168613. */
  168614. GLOBAL(JDIMENSION)
  168615. jpeg_read_scanlines (j_decompress_ptr cinfo, JSAMPARRAY scanlines,
  168616. JDIMENSION max_lines)
  168617. {
  168618. JDIMENSION row_ctr;
  168619. if (cinfo->global_state != DSTATE_SCANNING)
  168620. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168621. if (cinfo->output_scanline >= cinfo->output_height) {
  168622. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  168623. return 0;
  168624. }
  168625. /* Call progress monitor hook if present */
  168626. if (cinfo->progress != NULL) {
  168627. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  168628. cinfo->progress->pass_limit = (long) cinfo->output_height;
  168629. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  168630. }
  168631. /* Process some data */
  168632. row_ctr = 0;
  168633. (*cinfo->main->process_data) (cinfo, scanlines, &row_ctr, max_lines);
  168634. cinfo->output_scanline += row_ctr;
  168635. return row_ctr;
  168636. }
  168637. /*
  168638. * Alternate entry point to read raw data.
  168639. * Processes exactly one iMCU row per call, unless suspended.
  168640. */
  168641. GLOBAL(JDIMENSION)
  168642. jpeg_read_raw_data (j_decompress_ptr cinfo, JSAMPIMAGE data,
  168643. JDIMENSION max_lines)
  168644. {
  168645. JDIMENSION lines_per_iMCU_row;
  168646. if (cinfo->global_state != DSTATE_RAW_OK)
  168647. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168648. if (cinfo->output_scanline >= cinfo->output_height) {
  168649. WARNMS(cinfo, JWRN_TOO_MUCH_DATA);
  168650. return 0;
  168651. }
  168652. /* Call progress monitor hook if present */
  168653. if (cinfo->progress != NULL) {
  168654. cinfo->progress->pass_counter = (long) cinfo->output_scanline;
  168655. cinfo->progress->pass_limit = (long) cinfo->output_height;
  168656. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  168657. }
  168658. /* Verify that at least one iMCU row can be returned. */
  168659. lines_per_iMCU_row = cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size;
  168660. if (max_lines < lines_per_iMCU_row)
  168661. ERREXIT(cinfo, JERR_BUFFER_SIZE);
  168662. /* Decompress directly into user's buffer. */
  168663. if (! (*cinfo->coef->decompress_data) (cinfo, data))
  168664. return 0; /* suspension forced, can do nothing more */
  168665. /* OK, we processed one iMCU row. */
  168666. cinfo->output_scanline += lines_per_iMCU_row;
  168667. return lines_per_iMCU_row;
  168668. }
  168669. /* Additional entry points for buffered-image mode. */
  168670. #ifdef D_MULTISCAN_FILES_SUPPORTED
  168671. /*
  168672. * Initialize for an output pass in buffered-image mode.
  168673. */
  168674. GLOBAL(boolean)
  168675. jpeg_start_output (j_decompress_ptr cinfo, int scan_number)
  168676. {
  168677. if (cinfo->global_state != DSTATE_BUFIMAGE &&
  168678. cinfo->global_state != DSTATE_PRESCAN)
  168679. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168680. /* Limit scan number to valid range */
  168681. if (scan_number <= 0)
  168682. scan_number = 1;
  168683. if (cinfo->inputctl->eoi_reached &&
  168684. scan_number > cinfo->input_scan_number)
  168685. scan_number = cinfo->input_scan_number;
  168686. cinfo->output_scan_number = scan_number;
  168687. /* Perform any dummy output passes, and set up for the real pass */
  168688. return output_pass_setup(cinfo);
  168689. }
  168690. /*
  168691. * Finish up after an output pass in buffered-image mode.
  168692. *
  168693. * Returns FALSE if suspended. The return value need be inspected only if
  168694. * a suspending data source is used.
  168695. */
  168696. GLOBAL(boolean)
  168697. jpeg_finish_output (j_decompress_ptr cinfo)
  168698. {
  168699. if ((cinfo->global_state == DSTATE_SCANNING ||
  168700. cinfo->global_state == DSTATE_RAW_OK) && cinfo->buffered_image) {
  168701. /* Terminate this pass. */
  168702. /* We do not require the whole pass to have been completed. */
  168703. (*cinfo->master->finish_output_pass) (cinfo);
  168704. cinfo->global_state = DSTATE_BUFPOST;
  168705. } else if (cinfo->global_state != DSTATE_BUFPOST) {
  168706. /* BUFPOST = repeat call after a suspension, anything else is error */
  168707. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168708. }
  168709. /* Read markers looking for SOS or EOI */
  168710. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  168711. ! cinfo->inputctl->eoi_reached) {
  168712. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  168713. return FALSE; /* Suspend, come back later */
  168714. }
  168715. cinfo->global_state = DSTATE_BUFIMAGE;
  168716. return TRUE;
  168717. }
  168718. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  168719. /********* End of inlined file: jdapistd.c *********/
  168720. /********* Start of inlined file: jdapimin.c *********/
  168721. #define JPEG_INTERNALS
  168722. /*
  168723. * Initialization of a JPEG decompression object.
  168724. * The error manager must already be set up (in case memory manager fails).
  168725. */
  168726. GLOBAL(void)
  168727. jpeg_CreateDecompress (j_decompress_ptr cinfo, int version, size_t structsize)
  168728. {
  168729. int i;
  168730. /* Guard against version mismatches between library and caller. */
  168731. cinfo->mem = NULL; /* so jpeg_destroy knows mem mgr not called */
  168732. if (version != JPEG_LIB_VERSION)
  168733. ERREXIT2(cinfo, JERR_BAD_LIB_VERSION, JPEG_LIB_VERSION, version);
  168734. if (structsize != SIZEOF(struct jpeg_decompress_struct))
  168735. ERREXIT2(cinfo, JERR_BAD_STRUCT_SIZE,
  168736. (int) SIZEOF(struct jpeg_decompress_struct), (int) structsize);
  168737. /* For debugging purposes, we zero the whole master structure.
  168738. * But the application has already set the err pointer, and may have set
  168739. * client_data, so we have to save and restore those fields.
  168740. * Note: if application hasn't set client_data, tools like Purify may
  168741. * complain here.
  168742. */
  168743. {
  168744. struct jpeg_error_mgr * err = cinfo->err;
  168745. void * client_data = cinfo->client_data; /* ignore Purify complaint here */
  168746. MEMZERO(cinfo, SIZEOF(struct jpeg_decompress_struct));
  168747. cinfo->err = err;
  168748. cinfo->client_data = client_data;
  168749. }
  168750. cinfo->is_decompressor = TRUE;
  168751. /* Initialize a memory manager instance for this object */
  168752. jinit_memory_mgr((j_common_ptr) cinfo);
  168753. /* Zero out pointers to permanent structures. */
  168754. cinfo->progress = NULL;
  168755. cinfo->src = NULL;
  168756. for (i = 0; i < NUM_QUANT_TBLS; i++)
  168757. cinfo->quant_tbl_ptrs[i] = NULL;
  168758. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  168759. cinfo->dc_huff_tbl_ptrs[i] = NULL;
  168760. cinfo->ac_huff_tbl_ptrs[i] = NULL;
  168761. }
  168762. /* Initialize marker processor so application can override methods
  168763. * for COM, APPn markers before calling jpeg_read_header.
  168764. */
  168765. cinfo->marker_list = NULL;
  168766. jinit_marker_reader(cinfo);
  168767. /* And initialize the overall input controller. */
  168768. jinit_input_controller(cinfo);
  168769. /* OK, I'm ready */
  168770. cinfo->global_state = DSTATE_START;
  168771. }
  168772. /*
  168773. * Destruction of a JPEG decompression object
  168774. */
  168775. GLOBAL(void)
  168776. jpeg_destroy_decompress (j_decompress_ptr cinfo)
  168777. {
  168778. jpeg_destroy((j_common_ptr) cinfo); /* use common routine */
  168779. }
  168780. /*
  168781. * Abort processing of a JPEG decompression operation,
  168782. * but don't destroy the object itself.
  168783. */
  168784. GLOBAL(void)
  168785. jpeg_abort_decompress (j_decompress_ptr cinfo)
  168786. {
  168787. jpeg_abort((j_common_ptr) cinfo); /* use common routine */
  168788. }
  168789. /*
  168790. * Set default decompression parameters.
  168791. */
  168792. LOCAL(void)
  168793. default_decompress_parms (j_decompress_ptr cinfo)
  168794. {
  168795. /* Guess the input colorspace, and set output colorspace accordingly. */
  168796. /* (Wish JPEG committee had provided a real way to specify this...) */
  168797. /* Note application may override our guesses. */
  168798. switch (cinfo->num_components) {
  168799. case 1:
  168800. cinfo->jpeg_color_space = JCS_GRAYSCALE;
  168801. cinfo->out_color_space = JCS_GRAYSCALE;
  168802. break;
  168803. case 3:
  168804. if (cinfo->saw_JFIF_marker) {
  168805. cinfo->jpeg_color_space = JCS_YCbCr; /* JFIF implies YCbCr */
  168806. } else if (cinfo->saw_Adobe_marker) {
  168807. switch (cinfo->Adobe_transform) {
  168808. case 0:
  168809. cinfo->jpeg_color_space = JCS_RGB;
  168810. break;
  168811. case 1:
  168812. cinfo->jpeg_color_space = JCS_YCbCr;
  168813. break;
  168814. default:
  168815. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168816. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168817. break;
  168818. }
  168819. } else {
  168820. /* Saw no special markers, try to guess from the component IDs */
  168821. int cid0 = cinfo->comp_info[0].component_id;
  168822. int cid1 = cinfo->comp_info[1].component_id;
  168823. int cid2 = cinfo->comp_info[2].component_id;
  168824. if (cid0 == 1 && cid1 == 2 && cid2 == 3)
  168825. cinfo->jpeg_color_space = JCS_YCbCr; /* assume JFIF w/out marker */
  168826. else if (cid0 == 82 && cid1 == 71 && cid2 == 66)
  168827. cinfo->jpeg_color_space = JCS_RGB; /* ASCII 'R', 'G', 'B' */
  168828. else {
  168829. TRACEMS3(cinfo, 1, JTRC_UNKNOWN_IDS, cid0, cid1, cid2);
  168830. cinfo->jpeg_color_space = JCS_YCbCr; /* assume it's YCbCr */
  168831. }
  168832. }
  168833. /* Always guess RGB is proper output colorspace. */
  168834. cinfo->out_color_space = JCS_RGB;
  168835. break;
  168836. case 4:
  168837. if (cinfo->saw_Adobe_marker) {
  168838. switch (cinfo->Adobe_transform) {
  168839. case 0:
  168840. cinfo->jpeg_color_space = JCS_CMYK;
  168841. break;
  168842. case 2:
  168843. cinfo->jpeg_color_space = JCS_YCCK;
  168844. break;
  168845. default:
  168846. WARNMS1(cinfo, JWRN_ADOBE_XFORM, cinfo->Adobe_transform);
  168847. cinfo->jpeg_color_space = JCS_YCCK; /* assume it's YCCK */
  168848. break;
  168849. }
  168850. } else {
  168851. /* No special markers, assume straight CMYK. */
  168852. cinfo->jpeg_color_space = JCS_CMYK;
  168853. }
  168854. cinfo->out_color_space = JCS_CMYK;
  168855. break;
  168856. default:
  168857. cinfo->jpeg_color_space = JCS_UNKNOWN;
  168858. cinfo->out_color_space = JCS_UNKNOWN;
  168859. break;
  168860. }
  168861. /* Set defaults for other decompression parameters. */
  168862. cinfo->scale_num = 1; /* 1:1 scaling */
  168863. cinfo->scale_denom = 1;
  168864. cinfo->output_gamma = 1.0;
  168865. cinfo->buffered_image = FALSE;
  168866. cinfo->raw_data_out = FALSE;
  168867. cinfo->dct_method = JDCT_DEFAULT;
  168868. cinfo->do_fancy_upsampling = TRUE;
  168869. cinfo->do_block_smoothing = TRUE;
  168870. cinfo->quantize_colors = FALSE;
  168871. /* We set these in case application only sets quantize_colors. */
  168872. cinfo->dither_mode = JDITHER_FS;
  168873. #ifdef QUANT_2PASS_SUPPORTED
  168874. cinfo->two_pass_quantize = TRUE;
  168875. #else
  168876. cinfo->two_pass_quantize = FALSE;
  168877. #endif
  168878. cinfo->desired_number_of_colors = 256;
  168879. cinfo->colormap = NULL;
  168880. /* Initialize for no mode change in buffered-image mode. */
  168881. cinfo->enable_1pass_quant = FALSE;
  168882. cinfo->enable_external_quant = FALSE;
  168883. cinfo->enable_2pass_quant = FALSE;
  168884. }
  168885. /*
  168886. * Decompression startup: read start of JPEG datastream to see what's there.
  168887. * Need only initialize JPEG object and supply a data source before calling.
  168888. *
  168889. * This routine will read as far as the first SOS marker (ie, actual start of
  168890. * compressed data), and will save all tables and parameters in the JPEG
  168891. * object. It will also initialize the decompression parameters to default
  168892. * values, and finally return JPEG_HEADER_OK. On return, the application may
  168893. * adjust the decompression parameters and then call jpeg_start_decompress.
  168894. * (Or, if the application only wanted to determine the image parameters,
  168895. * the data need not be decompressed. In that case, call jpeg_abort or
  168896. * jpeg_destroy to release any temporary space.)
  168897. * If an abbreviated (tables only) datastream is presented, the routine will
  168898. * return JPEG_HEADER_TABLES_ONLY upon reaching EOI. The application may then
  168899. * re-use the JPEG object to read the abbreviated image datastream(s).
  168900. * It is unnecessary (but OK) to call jpeg_abort in this case.
  168901. * The JPEG_SUSPENDED return code only occurs if the data source module
  168902. * requests suspension of the decompressor. In this case the application
  168903. * should load more source data and then re-call jpeg_read_header to resume
  168904. * processing.
  168905. * If a non-suspending data source is used and require_image is TRUE, then the
  168906. * return code need not be inspected since only JPEG_HEADER_OK is possible.
  168907. *
  168908. * This routine is now just a front end to jpeg_consume_input, with some
  168909. * extra error checking.
  168910. */
  168911. GLOBAL(int)
  168912. jpeg_read_header (j_decompress_ptr cinfo, boolean require_image)
  168913. {
  168914. int retcode;
  168915. if (cinfo->global_state != DSTATE_START &&
  168916. cinfo->global_state != DSTATE_INHEADER)
  168917. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168918. retcode = jpeg_consume_input(cinfo);
  168919. switch (retcode) {
  168920. case JPEG_REACHED_SOS:
  168921. retcode = JPEG_HEADER_OK;
  168922. break;
  168923. case JPEG_REACHED_EOI:
  168924. if (require_image) /* Complain if application wanted an image */
  168925. ERREXIT(cinfo, JERR_NO_IMAGE);
  168926. /* Reset to start state; it would be safer to require the application to
  168927. * call jpeg_abort, but we can't change it now for compatibility reasons.
  168928. * A side effect is to free any temporary memory (there shouldn't be any).
  168929. */
  168930. jpeg_abort((j_common_ptr) cinfo); /* sets state = DSTATE_START */
  168931. retcode = JPEG_HEADER_TABLES_ONLY;
  168932. break;
  168933. case JPEG_SUSPENDED:
  168934. /* no work */
  168935. break;
  168936. }
  168937. return retcode;
  168938. }
  168939. /*
  168940. * Consume data in advance of what the decompressor requires.
  168941. * This can be called at any time once the decompressor object has
  168942. * been created and a data source has been set up.
  168943. *
  168944. * This routine is essentially a state machine that handles a couple
  168945. * of critical state-transition actions, namely initial setup and
  168946. * transition from header scanning to ready-for-start_decompress.
  168947. * All the actual input is done via the input controller's consume_input
  168948. * method.
  168949. */
  168950. GLOBAL(int)
  168951. jpeg_consume_input (j_decompress_ptr cinfo)
  168952. {
  168953. int retcode = JPEG_SUSPENDED;
  168954. /* NB: every possible DSTATE value should be listed in this switch */
  168955. switch (cinfo->global_state) {
  168956. case DSTATE_START:
  168957. /* Start-of-datastream actions: reset appropriate modules */
  168958. (*cinfo->inputctl->reset_input_controller) (cinfo);
  168959. /* Initialize application's data source module */
  168960. (*cinfo->src->init_source) (cinfo);
  168961. cinfo->global_state = DSTATE_INHEADER;
  168962. /*FALLTHROUGH*/
  168963. case DSTATE_INHEADER:
  168964. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168965. if (retcode == JPEG_REACHED_SOS) { /* Found SOS, prepare to decompress */
  168966. /* Set up default parameters based on header data */
  168967. default_decompress_parms(cinfo);
  168968. /* Set global state: ready for start_decompress */
  168969. cinfo->global_state = DSTATE_READY;
  168970. }
  168971. break;
  168972. case DSTATE_READY:
  168973. /* Can't advance past first SOS until start_decompress is called */
  168974. retcode = JPEG_REACHED_SOS;
  168975. break;
  168976. case DSTATE_PRELOAD:
  168977. case DSTATE_PRESCAN:
  168978. case DSTATE_SCANNING:
  168979. case DSTATE_RAW_OK:
  168980. case DSTATE_BUFIMAGE:
  168981. case DSTATE_BUFPOST:
  168982. case DSTATE_STOPPING:
  168983. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  168984. break;
  168985. default:
  168986. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  168987. }
  168988. return retcode;
  168989. }
  168990. /*
  168991. * Have we finished reading the input file?
  168992. */
  168993. GLOBAL(boolean)
  168994. jpeg_input_complete (j_decompress_ptr cinfo)
  168995. {
  168996. /* Check for valid jpeg object */
  168997. if (cinfo->global_state < DSTATE_START ||
  168998. cinfo->global_state > DSTATE_STOPPING)
  168999. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169000. return cinfo->inputctl->eoi_reached;
  169001. }
  169002. /*
  169003. * Is there more than one scan?
  169004. */
  169005. GLOBAL(boolean)
  169006. jpeg_has_multiple_scans (j_decompress_ptr cinfo)
  169007. {
  169008. /* Only valid after jpeg_read_header completes */
  169009. if (cinfo->global_state < DSTATE_READY ||
  169010. cinfo->global_state > DSTATE_STOPPING)
  169011. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169012. return cinfo->inputctl->has_multiple_scans;
  169013. }
  169014. /*
  169015. * Finish JPEG decompression.
  169016. *
  169017. * This will normally just verify the file trailer and release temp storage.
  169018. *
  169019. * Returns FALSE if suspended. The return value need be inspected only if
  169020. * a suspending data source is used.
  169021. */
  169022. GLOBAL(boolean)
  169023. jpeg_finish_decompress (j_decompress_ptr cinfo)
  169024. {
  169025. if ((cinfo->global_state == DSTATE_SCANNING ||
  169026. cinfo->global_state == DSTATE_RAW_OK) && ! cinfo->buffered_image) {
  169027. /* Terminate final pass of non-buffered mode */
  169028. if (cinfo->output_scanline < cinfo->output_height)
  169029. ERREXIT(cinfo, JERR_TOO_LITTLE_DATA);
  169030. (*cinfo->master->finish_output_pass) (cinfo);
  169031. cinfo->global_state = DSTATE_STOPPING;
  169032. } else if (cinfo->global_state == DSTATE_BUFIMAGE) {
  169033. /* Finishing after a buffered-image operation */
  169034. cinfo->global_state = DSTATE_STOPPING;
  169035. } else if (cinfo->global_state != DSTATE_STOPPING) {
  169036. /* STOPPING = repeat call after a suspension, anything else is error */
  169037. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  169038. }
  169039. /* Read until EOI */
  169040. while (! cinfo->inputctl->eoi_reached) {
  169041. if ((*cinfo->inputctl->consume_input) (cinfo) == JPEG_SUSPENDED)
  169042. return FALSE; /* Suspend, come back later */
  169043. }
  169044. /* Do final cleanup */
  169045. (*cinfo->src->term_source) (cinfo);
  169046. /* We can use jpeg_abort to release memory and reset global_state */
  169047. jpeg_abort((j_common_ptr) cinfo);
  169048. return TRUE;
  169049. }
  169050. /********* End of inlined file: jdapimin.c *********/
  169051. /********* Start of inlined file: jdatasrc.c *********/
  169052. /* this is not a core library module, so it doesn't define JPEG_INTERNALS */
  169053. /********* Start of inlined file: jerror.h *********/
  169054. /*
  169055. * To define the enum list of message codes, include this file without
  169056. * defining macro JMESSAGE. To create a message string table, include it
  169057. * again with a suitable JMESSAGE definition (see jerror.c for an example).
  169058. */
  169059. #ifndef JMESSAGE
  169060. #ifndef JERROR_H
  169061. /* First time through, define the enum list */
  169062. #define JMAKE_ENUM_LIST
  169063. #else
  169064. /* Repeated inclusions of this file are no-ops unless JMESSAGE is defined */
  169065. #define JMESSAGE(code,string)
  169066. #endif /* JERROR_H */
  169067. #endif /* JMESSAGE */
  169068. #ifdef JMAKE_ENUM_LIST
  169069. typedef enum {
  169070. #define JMESSAGE(code,string) code ,
  169071. #endif /* JMAKE_ENUM_LIST */
  169072. JMESSAGE(JMSG_NOMESSAGE, "Bogus message code %d") /* Must be first entry! */
  169073. /* For maintenance convenience, list is alphabetical by message code name */
  169074. JMESSAGE(JERR_ARITH_NOTIMPL,
  169075. "Sorry, there are legal restrictions on arithmetic coding")
  169076. JMESSAGE(JERR_BAD_ALIGN_TYPE, "ALIGN_TYPE is wrong, please fix")
  169077. JMESSAGE(JERR_BAD_ALLOC_CHUNK, "MAX_ALLOC_CHUNK is wrong, please fix")
  169078. JMESSAGE(JERR_BAD_BUFFER_MODE, "Bogus buffer control mode")
  169079. JMESSAGE(JERR_BAD_COMPONENT_ID, "Invalid component ID %d in SOS")
  169080. JMESSAGE(JERR_BAD_DCT_COEF, "DCT coefficient out of range")
  169081. JMESSAGE(JERR_BAD_DCTSIZE, "IDCT output block size %d not supported")
  169082. JMESSAGE(JERR_BAD_HUFF_TABLE, "Bogus Huffman table definition")
  169083. JMESSAGE(JERR_BAD_IN_COLORSPACE, "Bogus input colorspace")
  169084. JMESSAGE(JERR_BAD_J_COLORSPACE, "Bogus JPEG colorspace")
  169085. JMESSAGE(JERR_BAD_LENGTH, "Bogus marker length")
  169086. JMESSAGE(JERR_BAD_LIB_VERSION,
  169087. "Wrong JPEG library version: library is %d, caller expects %d")
  169088. JMESSAGE(JERR_BAD_MCU_SIZE, "Sampling factors too large for interleaved scan")
  169089. JMESSAGE(JERR_BAD_POOL_ID, "Invalid memory pool code %d")
  169090. JMESSAGE(JERR_BAD_PRECISION, "Unsupported JPEG data precision %d")
  169091. JMESSAGE(JERR_BAD_PROGRESSION,
  169092. "Invalid progressive parameters Ss=%d Se=%d Ah=%d Al=%d")
  169093. JMESSAGE(JERR_BAD_PROG_SCRIPT,
  169094. "Invalid progressive parameters at scan script entry %d")
  169095. JMESSAGE(JERR_BAD_SAMPLING, "Bogus sampling factors")
  169096. JMESSAGE(JERR_BAD_SCAN_SCRIPT, "Invalid scan script at entry %d")
  169097. JMESSAGE(JERR_BAD_STATE, "Improper call to JPEG library in state %d")
  169098. JMESSAGE(JERR_BAD_STRUCT_SIZE,
  169099. "JPEG parameter struct mismatch: library thinks size is %u, caller expects %u")
  169100. JMESSAGE(JERR_BAD_VIRTUAL_ACCESS, "Bogus virtual array access")
  169101. JMESSAGE(JERR_BUFFER_SIZE, "Buffer passed to JPEG library is too small")
  169102. JMESSAGE(JERR_CANT_SUSPEND, "Suspension not allowed here")
  169103. JMESSAGE(JERR_CCIR601_NOTIMPL, "CCIR601 sampling not implemented yet")
  169104. JMESSAGE(JERR_COMPONENT_COUNT, "Too many color components: %d, max %d")
  169105. JMESSAGE(JERR_CONVERSION_NOTIMPL, "Unsupported color conversion request")
  169106. JMESSAGE(JERR_DAC_INDEX, "Bogus DAC index %d")
  169107. JMESSAGE(JERR_DAC_VALUE, "Bogus DAC value 0x%x")
  169108. JMESSAGE(JERR_DHT_INDEX, "Bogus DHT index %d")
  169109. JMESSAGE(JERR_DQT_INDEX, "Bogus DQT index %d")
  169110. JMESSAGE(JERR_EMPTY_IMAGE, "Empty JPEG image (DNL not supported)")
  169111. JMESSAGE(JERR_EMS_READ, "Read from EMS failed")
  169112. JMESSAGE(JERR_EMS_WRITE, "Write to EMS failed")
  169113. JMESSAGE(JERR_EOI_EXPECTED, "Didn't expect more than one scan")
  169114. JMESSAGE(JERR_FILE_READ, "Input file read error")
  169115. JMESSAGE(JERR_FILE_WRITE, "Output file write error --- out of disk space?")
  169116. JMESSAGE(JERR_FRACT_SAMPLE_NOTIMPL, "Fractional sampling not implemented yet")
  169117. JMESSAGE(JERR_HUFF_CLEN_OVERFLOW, "Huffman code size table overflow")
  169118. JMESSAGE(JERR_HUFF_MISSING_CODE, "Missing Huffman code table entry")
  169119. JMESSAGE(JERR_IMAGE_TOO_BIG, "Maximum supported image dimension is %u pixels")
  169120. JMESSAGE(JERR_INPUT_EMPTY, "Empty input file")
  169121. JMESSAGE(JERR_INPUT_EOF, "Premature end of input file")
  169122. JMESSAGE(JERR_MISMATCHED_QUANT_TABLE,
  169123. "Cannot transcode due to multiple use of quantization table %d")
  169124. JMESSAGE(JERR_MISSING_DATA, "Scan script does not transmit all data")
  169125. JMESSAGE(JERR_MODE_CHANGE, "Invalid color quantization mode change")
  169126. JMESSAGE(JERR_NOTIMPL, "Not implemented yet")
  169127. JMESSAGE(JERR_NOT_COMPILED, "Requested feature was omitted at compile time")
  169128. JMESSAGE(JERR_NO_BACKING_STORE, "Backing store not supported")
  169129. JMESSAGE(JERR_NO_HUFF_TABLE, "Huffman table 0x%02x was not defined")
  169130. JMESSAGE(JERR_NO_IMAGE, "JPEG datastream contains no image")
  169131. JMESSAGE(JERR_NO_QUANT_TABLE, "Quantization table 0x%02x was not defined")
  169132. JMESSAGE(JERR_NO_SOI, "Not a JPEG file: starts with 0x%02x 0x%02x")
  169133. JMESSAGE(JERR_OUT_OF_MEMORY, "Insufficient memory (case %d)")
  169134. JMESSAGE(JERR_QUANT_COMPONENTS,
  169135. "Cannot quantize more than %d color components")
  169136. JMESSAGE(JERR_QUANT_FEW_COLORS, "Cannot quantize to fewer than %d colors")
  169137. JMESSAGE(JERR_QUANT_MANY_COLORS, "Cannot quantize to more than %d colors")
  169138. JMESSAGE(JERR_SOF_DUPLICATE, "Invalid JPEG file structure: two SOF markers")
  169139. JMESSAGE(JERR_SOF_NO_SOS, "Invalid JPEG file structure: missing SOS marker")
  169140. JMESSAGE(JERR_SOF_UNSUPPORTED, "Unsupported JPEG process: SOF type 0x%02x")
  169141. JMESSAGE(JERR_SOI_DUPLICATE, "Invalid JPEG file structure: two SOI markers")
  169142. JMESSAGE(JERR_SOS_NO_SOF, "Invalid JPEG file structure: SOS before SOF")
  169143. JMESSAGE(JERR_TFILE_CREATE, "Failed to create temporary file %s")
  169144. JMESSAGE(JERR_TFILE_READ, "Read failed on temporary file")
  169145. JMESSAGE(JERR_TFILE_SEEK, "Seek failed on temporary file")
  169146. JMESSAGE(JERR_TFILE_WRITE,
  169147. "Write failed on temporary file --- out of disk space?")
  169148. JMESSAGE(JERR_TOO_LITTLE_DATA, "Application transferred too few scanlines")
  169149. JMESSAGE(JERR_UNKNOWN_MARKER, "Unsupported marker type 0x%02x")
  169150. JMESSAGE(JERR_VIRTUAL_BUG, "Virtual array controller messed up")
  169151. JMESSAGE(JERR_WIDTH_OVERFLOW, "Image too wide for this implementation")
  169152. JMESSAGE(JERR_XMS_READ, "Read from XMS failed")
  169153. JMESSAGE(JERR_XMS_WRITE, "Write to XMS failed")
  169154. JMESSAGE(JMSG_COPYRIGHT, JCOPYRIGHT)
  169155. JMESSAGE(JMSG_VERSION, JVERSION)
  169156. JMESSAGE(JTRC_16BIT_TABLES,
  169157. "Caution: quantization tables are too coarse for baseline JPEG")
  169158. JMESSAGE(JTRC_ADOBE,
  169159. "Adobe APP14 marker: version %d, flags 0x%04x 0x%04x, transform %d")
  169160. JMESSAGE(JTRC_APP0, "Unknown APP0 marker (not JFIF), length %u")
  169161. JMESSAGE(JTRC_APP14, "Unknown APP14 marker (not Adobe), length %u")
  169162. JMESSAGE(JTRC_DAC, "Define Arithmetic Table 0x%02x: 0x%02x")
  169163. JMESSAGE(JTRC_DHT, "Define Huffman Table 0x%02x")
  169164. JMESSAGE(JTRC_DQT, "Define Quantization Table %d precision %d")
  169165. JMESSAGE(JTRC_DRI, "Define Restart Interval %u")
  169166. JMESSAGE(JTRC_EMS_CLOSE, "Freed EMS handle %u")
  169167. JMESSAGE(JTRC_EMS_OPEN, "Obtained EMS handle %u")
  169168. JMESSAGE(JTRC_EOI, "End Of Image")
  169169. JMESSAGE(JTRC_HUFFBITS, " %3d %3d %3d %3d %3d %3d %3d %3d")
  169170. JMESSAGE(JTRC_JFIF, "JFIF APP0 marker: version %d.%02d, density %dx%d %d")
  169171. JMESSAGE(JTRC_JFIF_BADTHUMBNAILSIZE,
  169172. "Warning: thumbnail image size does not match data length %u")
  169173. JMESSAGE(JTRC_JFIF_EXTENSION,
  169174. "JFIF extension marker: type 0x%02x, length %u")
  169175. JMESSAGE(JTRC_JFIF_THUMBNAIL, " with %d x %d thumbnail image")
  169176. JMESSAGE(JTRC_MISC_MARKER, "Miscellaneous marker 0x%02x, length %u")
  169177. JMESSAGE(JTRC_PARMLESS_MARKER, "Unexpected marker 0x%02x")
  169178. JMESSAGE(JTRC_QUANTVALS, " %4u %4u %4u %4u %4u %4u %4u %4u")
  169179. JMESSAGE(JTRC_QUANT_3_NCOLORS, "Quantizing to %d = %d*%d*%d colors")
  169180. JMESSAGE(JTRC_QUANT_NCOLORS, "Quantizing to %d colors")
  169181. JMESSAGE(JTRC_QUANT_SELECTED, "Selected %d colors for quantization")
  169182. JMESSAGE(JTRC_RECOVERY_ACTION, "At marker 0x%02x, recovery action %d")
  169183. JMESSAGE(JTRC_RST, "RST%d")
  169184. JMESSAGE(JTRC_SMOOTH_NOTIMPL,
  169185. "Smoothing not supported with nonstandard sampling ratios")
  169186. JMESSAGE(JTRC_SOF, "Start Of Frame 0x%02x: width=%u, height=%u, components=%d")
  169187. JMESSAGE(JTRC_SOF_COMPONENT, " Component %d: %dhx%dv q=%d")
  169188. JMESSAGE(JTRC_SOI, "Start of Image")
  169189. JMESSAGE(JTRC_SOS, "Start Of Scan: %d components")
  169190. JMESSAGE(JTRC_SOS_COMPONENT, " Component %d: dc=%d ac=%d")
  169191. JMESSAGE(JTRC_SOS_PARAMS, " Ss=%d, Se=%d, Ah=%d, Al=%d")
  169192. JMESSAGE(JTRC_TFILE_CLOSE, "Closed temporary file %s")
  169193. JMESSAGE(JTRC_TFILE_OPEN, "Opened temporary file %s")
  169194. JMESSAGE(JTRC_THUMB_JPEG,
  169195. "JFIF extension marker: JPEG-compressed thumbnail image, length %u")
  169196. JMESSAGE(JTRC_THUMB_PALETTE,
  169197. "JFIF extension marker: palette thumbnail image, length %u")
  169198. JMESSAGE(JTRC_THUMB_RGB,
  169199. "JFIF extension marker: RGB thumbnail image, length %u")
  169200. JMESSAGE(JTRC_UNKNOWN_IDS,
  169201. "Unrecognized component IDs %d %d %d, assuming YCbCr")
  169202. JMESSAGE(JTRC_XMS_CLOSE, "Freed XMS handle %u")
  169203. JMESSAGE(JTRC_XMS_OPEN, "Obtained XMS handle %u")
  169204. JMESSAGE(JWRN_ADOBE_XFORM, "Unknown Adobe color transform code %d")
  169205. JMESSAGE(JWRN_BOGUS_PROGRESSION,
  169206. "Inconsistent progression sequence for component %d coefficient %d")
  169207. JMESSAGE(JWRN_EXTRANEOUS_DATA,
  169208. "Corrupt JPEG data: %u extraneous bytes before marker 0x%02x")
  169209. JMESSAGE(JWRN_HIT_MARKER, "Corrupt JPEG data: premature end of data segment")
  169210. JMESSAGE(JWRN_HUFF_BAD_CODE, "Corrupt JPEG data: bad Huffman code")
  169211. JMESSAGE(JWRN_JFIF_MAJOR, "Warning: unknown JFIF revision number %d.%02d")
  169212. JMESSAGE(JWRN_JPEG_EOF, "Premature end of JPEG file")
  169213. JMESSAGE(JWRN_MUST_RESYNC,
  169214. "Corrupt JPEG data: found marker 0x%02x instead of RST%d")
  169215. JMESSAGE(JWRN_NOT_SEQUENTIAL, "Invalid SOS parameters for sequential JPEG")
  169216. JMESSAGE(JWRN_TOO_MUCH_DATA, "Application transferred too many scanlines")
  169217. #ifdef JMAKE_ENUM_LIST
  169218. JMSG_LASTMSGCODE
  169219. } J_MESSAGE_CODE;
  169220. #undef JMAKE_ENUM_LIST
  169221. #endif /* JMAKE_ENUM_LIST */
  169222. /* Zap JMESSAGE macro so that future re-inclusions do nothing by default */
  169223. #undef JMESSAGE
  169224. #ifndef JERROR_H
  169225. #define JERROR_H
  169226. /* Macros to simplify using the error and trace message stuff */
  169227. /* The first parameter is either type of cinfo pointer */
  169228. /* Fatal errors (print message and exit) */
  169229. #define ERREXIT(cinfo,code) \
  169230. ((cinfo)->err->msg_code = (code), \
  169231. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  169232. #define ERREXIT1(cinfo,code,p1) \
  169233. ((cinfo)->err->msg_code = (code), \
  169234. (cinfo)->err->msg_parm.i[0] = (p1), \
  169235. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  169236. #define ERREXIT2(cinfo,code,p1,p2) \
  169237. ((cinfo)->err->msg_code = (code), \
  169238. (cinfo)->err->msg_parm.i[0] = (p1), \
  169239. (cinfo)->err->msg_parm.i[1] = (p2), \
  169240. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  169241. #define ERREXIT3(cinfo,code,p1,p2,p3) \
  169242. ((cinfo)->err->msg_code = (code), \
  169243. (cinfo)->err->msg_parm.i[0] = (p1), \
  169244. (cinfo)->err->msg_parm.i[1] = (p2), \
  169245. (cinfo)->err->msg_parm.i[2] = (p3), \
  169246. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  169247. #define ERREXIT4(cinfo,code,p1,p2,p3,p4) \
  169248. ((cinfo)->err->msg_code = (code), \
  169249. (cinfo)->err->msg_parm.i[0] = (p1), \
  169250. (cinfo)->err->msg_parm.i[1] = (p2), \
  169251. (cinfo)->err->msg_parm.i[2] = (p3), \
  169252. (cinfo)->err->msg_parm.i[3] = (p4), \
  169253. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  169254. #define ERREXITS(cinfo,code,str) \
  169255. ((cinfo)->err->msg_code = (code), \
  169256. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  169257. (*(cinfo)->err->error_exit) ((j_common_ptr) (cinfo)))
  169258. #define MAKESTMT(stuff) do { stuff } while (0)
  169259. /* Nonfatal errors (we can keep going, but the data is probably corrupt) */
  169260. #define WARNMS(cinfo,code) \
  169261. ((cinfo)->err->msg_code = (code), \
  169262. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  169263. #define WARNMS1(cinfo,code,p1) \
  169264. ((cinfo)->err->msg_code = (code), \
  169265. (cinfo)->err->msg_parm.i[0] = (p1), \
  169266. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  169267. #define WARNMS2(cinfo,code,p1,p2) \
  169268. ((cinfo)->err->msg_code = (code), \
  169269. (cinfo)->err->msg_parm.i[0] = (p1), \
  169270. (cinfo)->err->msg_parm.i[1] = (p2), \
  169271. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), -1))
  169272. /* Informational/debugging messages */
  169273. #define TRACEMS(cinfo,lvl,code) \
  169274. ((cinfo)->err->msg_code = (code), \
  169275. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  169276. #define TRACEMS1(cinfo,lvl,code,p1) \
  169277. ((cinfo)->err->msg_code = (code), \
  169278. (cinfo)->err->msg_parm.i[0] = (p1), \
  169279. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  169280. #define TRACEMS2(cinfo,lvl,code,p1,p2) \
  169281. ((cinfo)->err->msg_code = (code), \
  169282. (cinfo)->err->msg_parm.i[0] = (p1), \
  169283. (cinfo)->err->msg_parm.i[1] = (p2), \
  169284. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  169285. #define TRACEMS3(cinfo,lvl,code,p1,p2,p3) \
  169286. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  169287. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); \
  169288. (cinfo)->err->msg_code = (code); \
  169289. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  169290. #define TRACEMS4(cinfo,lvl,code,p1,p2,p3,p4) \
  169291. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  169292. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  169293. (cinfo)->err->msg_code = (code); \
  169294. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  169295. #define TRACEMS5(cinfo,lvl,code,p1,p2,p3,p4,p5) \
  169296. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  169297. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  169298. _mp[4] = (p5); \
  169299. (cinfo)->err->msg_code = (code); \
  169300. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  169301. #define TRACEMS8(cinfo,lvl,code,p1,p2,p3,p4,p5,p6,p7,p8) \
  169302. MAKESTMT(int * _mp = (cinfo)->err->msg_parm.i; \
  169303. _mp[0] = (p1); _mp[1] = (p2); _mp[2] = (p3); _mp[3] = (p4); \
  169304. _mp[4] = (p5); _mp[5] = (p6); _mp[6] = (p7); _mp[7] = (p8); \
  169305. (cinfo)->err->msg_code = (code); \
  169306. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)); )
  169307. #define TRACEMSS(cinfo,lvl,code,str) \
  169308. ((cinfo)->err->msg_code = (code), \
  169309. strncpy((cinfo)->err->msg_parm.s, (str), JMSG_STR_PARM_MAX), \
  169310. (*(cinfo)->err->emit_message) ((j_common_ptr) (cinfo), (lvl)))
  169311. #endif /* JERROR_H */
  169312. /********* End of inlined file: jerror.h *********/
  169313. /* Expanded data source object for stdio input */
  169314. typedef struct {
  169315. struct jpeg_source_mgr pub; /* public fields */
  169316. FILE * infile; /* source stream */
  169317. JOCTET * buffer; /* start of buffer */
  169318. boolean start_of_file; /* have we gotten any data yet? */
  169319. } my_source_mgr;
  169320. typedef my_source_mgr * my_src_ptr;
  169321. #define INPUT_BUF_SIZE 4096 /* choose an efficiently fread'able size */
  169322. /*
  169323. * Initialize source --- called by jpeg_read_header
  169324. * before any data is actually read.
  169325. */
  169326. METHODDEF(void)
  169327. init_source (j_decompress_ptr cinfo)
  169328. {
  169329. my_src_ptr src = (my_src_ptr) cinfo->src;
  169330. /* We reset the empty-input-file flag for each image,
  169331. * but we don't clear the input buffer.
  169332. * This is correct behavior for reading a series of images from one source.
  169333. */
  169334. src->start_of_file = TRUE;
  169335. }
  169336. /*
  169337. * Fill the input buffer --- called whenever buffer is emptied.
  169338. *
  169339. * In typical applications, this should read fresh data into the buffer
  169340. * (ignoring the current state of next_input_byte & bytes_in_buffer),
  169341. * reset the pointer & count to the start of the buffer, and return TRUE
  169342. * indicating that the buffer has been reloaded. It is not necessary to
  169343. * fill the buffer entirely, only to obtain at least one more byte.
  169344. *
  169345. * There is no such thing as an EOF return. If the end of the file has been
  169346. * reached, the routine has a choice of ERREXIT() or inserting fake data into
  169347. * the buffer. In most cases, generating a warning message and inserting a
  169348. * fake EOI marker is the best course of action --- this will allow the
  169349. * decompressor to output however much of the image is there. However,
  169350. * the resulting error message is misleading if the real problem is an empty
  169351. * input file, so we handle that case specially.
  169352. *
  169353. * In applications that need to be able to suspend compression due to input
  169354. * not being available yet, a FALSE return indicates that no more data can be
  169355. * obtained right now, but more may be forthcoming later. In this situation,
  169356. * the decompressor will return to its caller (with an indication of the
  169357. * number of scanlines it has read, if any). The application should resume
  169358. * decompression after it has loaded more data into the input buffer. Note
  169359. * that there are substantial restrictions on the use of suspension --- see
  169360. * the documentation.
  169361. *
  169362. * When suspending, the decompressor will back up to a convenient restart point
  169363. * (typically the start of the current MCU). next_input_byte & bytes_in_buffer
  169364. * indicate where the restart point will be if the current call returns FALSE.
  169365. * Data beyond this point must be rescanned after resumption, so move it to
  169366. * the front of the buffer rather than discarding it.
  169367. */
  169368. METHODDEF(boolean)
  169369. fill_input_buffer (j_decompress_ptr cinfo)
  169370. {
  169371. my_src_ptr src = (my_src_ptr) cinfo->src;
  169372. size_t nbytes;
  169373. nbytes = JFREAD(src->infile, src->buffer, INPUT_BUF_SIZE);
  169374. if (nbytes <= 0) {
  169375. if (src->start_of_file) /* Treat empty input file as fatal error */
  169376. ERREXIT(cinfo, JERR_INPUT_EMPTY);
  169377. WARNMS(cinfo, JWRN_JPEG_EOF);
  169378. /* Insert a fake EOI marker */
  169379. src->buffer[0] = (JOCTET) 0xFF;
  169380. src->buffer[1] = (JOCTET) JPEG_EOI;
  169381. nbytes = 2;
  169382. }
  169383. src->pub.next_input_byte = src->buffer;
  169384. src->pub.bytes_in_buffer = nbytes;
  169385. src->start_of_file = FALSE;
  169386. return TRUE;
  169387. }
  169388. /*
  169389. * Skip data --- used to skip over a potentially large amount of
  169390. * uninteresting data (such as an APPn marker).
  169391. *
  169392. * Writers of suspendable-input applications must note that skip_input_data
  169393. * is not granted the right to give a suspension return. If the skip extends
  169394. * beyond the data currently in the buffer, the buffer can be marked empty so
  169395. * that the next read will cause a fill_input_buffer call that can suspend.
  169396. * Arranging for additional bytes to be discarded before reloading the input
  169397. * buffer is the application writer's problem.
  169398. */
  169399. METHODDEF(void)
  169400. skip_input_data (j_decompress_ptr cinfo, long num_bytes)
  169401. {
  169402. my_src_ptr src = (my_src_ptr) cinfo->src;
  169403. /* Just a dumb implementation for now. Could use fseek() except
  169404. * it doesn't work on pipes. Not clear that being smart is worth
  169405. * any trouble anyway --- large skips are infrequent.
  169406. */
  169407. if (num_bytes > 0) {
  169408. while (num_bytes > (long) src->pub.bytes_in_buffer) {
  169409. num_bytes -= (long) src->pub.bytes_in_buffer;
  169410. (void) fill_input_buffer(cinfo);
  169411. /* note we assume that fill_input_buffer will never return FALSE,
  169412. * so suspension need not be handled.
  169413. */
  169414. }
  169415. src->pub.next_input_byte += (size_t) num_bytes;
  169416. src->pub.bytes_in_buffer -= (size_t) num_bytes;
  169417. }
  169418. }
  169419. /*
  169420. * An additional method that can be provided by data source modules is the
  169421. * resync_to_restart method for error recovery in the presence of RST markers.
  169422. * For the moment, this source module just uses the default resync method
  169423. * provided by the JPEG library. That method assumes that no backtracking
  169424. * is possible.
  169425. */
  169426. /*
  169427. * Terminate source --- called by jpeg_finish_decompress
  169428. * after all data has been read. Often a no-op.
  169429. *
  169430. * NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
  169431. * application must deal with any cleanup that should happen even
  169432. * for error exit.
  169433. */
  169434. METHODDEF(void)
  169435. term_source (j_decompress_ptr cinfo)
  169436. {
  169437. /* no work necessary here */
  169438. }
  169439. /*
  169440. * Prepare for input from a stdio stream.
  169441. * The caller must have already opened the stream, and is responsible
  169442. * for closing it after finishing decompression.
  169443. */
  169444. GLOBAL(void)
  169445. jpeg_stdio_src (j_decompress_ptr cinfo, FILE * infile)
  169446. {
  169447. my_src_ptr src;
  169448. /* The source object and input buffer are made permanent so that a series
  169449. * of JPEG images can be read from the same file by calling jpeg_stdio_src
  169450. * only before the first one. (If we discarded the buffer at the end of
  169451. * one image, we'd likely lose the start of the next one.)
  169452. * This makes it unsafe to use this manager and a different source
  169453. * manager serially with the same JPEG object. Caveat programmer.
  169454. */
  169455. if (cinfo->src == NULL) { /* first time for this JPEG object? */
  169456. cinfo->src = (struct jpeg_source_mgr *)
  169457. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  169458. SIZEOF(my_source_mgr));
  169459. src = (my_src_ptr) cinfo->src;
  169460. src->buffer = (JOCTET *)
  169461. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  169462. INPUT_BUF_SIZE * SIZEOF(JOCTET));
  169463. }
  169464. src = (my_src_ptr) cinfo->src;
  169465. src->pub.init_source = init_source;
  169466. src->pub.fill_input_buffer = fill_input_buffer;
  169467. src->pub.skip_input_data = skip_input_data;
  169468. src->pub.resync_to_restart = jpeg_resync_to_restart; /* use default method */
  169469. src->pub.term_source = term_source;
  169470. src->infile = infile;
  169471. src->pub.bytes_in_buffer = 0; /* forces fill_input_buffer on first read */
  169472. src->pub.next_input_byte = NULL; /* until buffer loaded */
  169473. }
  169474. /********* End of inlined file: jdatasrc.c *********/
  169475. /********* Start of inlined file: jdcoefct.c *********/
  169476. #define JPEG_INTERNALS
  169477. /* Block smoothing is only applicable for progressive JPEG, so: */
  169478. #ifndef D_PROGRESSIVE_SUPPORTED
  169479. #undef BLOCK_SMOOTHING_SUPPORTED
  169480. #endif
  169481. /* Private buffer controller object */
  169482. typedef struct {
  169483. struct jpeg_d_coef_controller pub; /* public fields */
  169484. /* These variables keep track of the current location of the input side. */
  169485. /* cinfo->input_iMCU_row is also used for this. */
  169486. JDIMENSION MCU_ctr; /* counts MCUs processed in current row */
  169487. int MCU_vert_offset; /* counts MCU rows within iMCU row */
  169488. int MCU_rows_per_iMCU_row; /* number of such rows needed */
  169489. /* The output side's location is represented by cinfo->output_iMCU_row. */
  169490. /* In single-pass modes, it's sufficient to buffer just one MCU.
  169491. * We allocate a workspace of D_MAX_BLOCKS_IN_MCU coefficient blocks,
  169492. * and let the entropy decoder write into that workspace each time.
  169493. * (On 80x86, the workspace is FAR even though it's not really very big;
  169494. * this is to keep the module interfaces unchanged when a large coefficient
  169495. * buffer is necessary.)
  169496. * In multi-pass modes, this array points to the current MCU's blocks
  169497. * within the virtual arrays; it is used only by the input side.
  169498. */
  169499. JBLOCKROW MCU_buffer[D_MAX_BLOCKS_IN_MCU];
  169500. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169501. /* In multi-pass modes, we need a virtual block array for each component. */
  169502. jvirt_barray_ptr whole_image[MAX_COMPONENTS];
  169503. #endif
  169504. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169505. /* When doing block smoothing, we latch coefficient Al values here */
  169506. int * coef_bits_latch;
  169507. #define SAVED_COEFS 6 /* we save coef_bits[0..5] */
  169508. #endif
  169509. } my_coef_controller3;
  169510. typedef my_coef_controller3 * my_coef_ptr3;
  169511. /* Forward declarations */
  169512. METHODDEF(int) decompress_onepass
  169513. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  169514. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169515. METHODDEF(int) decompress_data
  169516. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  169517. #endif
  169518. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169519. LOCAL(boolean) smoothing_ok JPP((j_decompress_ptr cinfo));
  169520. METHODDEF(int) decompress_smooth_data
  169521. JPP((j_decompress_ptr cinfo, JSAMPIMAGE output_buf));
  169522. #endif
  169523. LOCAL(void)
  169524. start_iMCU_row3 (j_decompress_ptr cinfo)
  169525. /* Reset within-iMCU-row counters for a new row (input side) */
  169526. {
  169527. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169528. /* In an interleaved scan, an MCU row is the same as an iMCU row.
  169529. * In a noninterleaved scan, an iMCU row has v_samp_factor MCU rows.
  169530. * But at the bottom of the image, process only what's left.
  169531. */
  169532. if (cinfo->comps_in_scan > 1) {
  169533. coef->MCU_rows_per_iMCU_row = 1;
  169534. } else {
  169535. if (cinfo->input_iMCU_row < (cinfo->total_iMCU_rows-1))
  169536. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->v_samp_factor;
  169537. else
  169538. coef->MCU_rows_per_iMCU_row = cinfo->cur_comp_info[0]->last_row_height;
  169539. }
  169540. coef->MCU_ctr = 0;
  169541. coef->MCU_vert_offset = 0;
  169542. }
  169543. /*
  169544. * Initialize for an input processing pass.
  169545. */
  169546. METHODDEF(void)
  169547. start_input_pass (j_decompress_ptr cinfo)
  169548. {
  169549. cinfo->input_iMCU_row = 0;
  169550. start_iMCU_row3(cinfo);
  169551. }
  169552. /*
  169553. * Initialize for an output processing pass.
  169554. */
  169555. METHODDEF(void)
  169556. start_output_pass (j_decompress_ptr cinfo)
  169557. {
  169558. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169559. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169560. /* If multipass, check to see whether to use block smoothing on this pass */
  169561. if (coef->pub.coef_arrays != NULL) {
  169562. if (cinfo->do_block_smoothing && smoothing_ok(cinfo))
  169563. coef->pub.decompress_data = decompress_smooth_data;
  169564. else
  169565. coef->pub.decompress_data = decompress_data;
  169566. }
  169567. #endif
  169568. cinfo->output_iMCU_row = 0;
  169569. }
  169570. /*
  169571. * Decompress and return some data in the single-pass case.
  169572. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  169573. * Input and output must run in lockstep since we have only a one-MCU buffer.
  169574. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  169575. *
  169576. * NB: output_buf contains a plane for each component in image,
  169577. * which we index according to the component's SOF position.
  169578. */
  169579. METHODDEF(int)
  169580. decompress_onepass (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  169581. {
  169582. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169583. JDIMENSION MCU_col_num; /* index of current MCU within row */
  169584. JDIMENSION last_MCU_col = cinfo->MCUs_per_row - 1;
  169585. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  169586. int blkn, ci, xindex, yindex, yoffset, useful_width;
  169587. JSAMPARRAY output_ptr;
  169588. JDIMENSION start_col, output_col;
  169589. jpeg_component_info *compptr;
  169590. inverse_DCT_method_ptr inverse_DCT;
  169591. /* Loop to process as much as one whole iMCU row */
  169592. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  169593. yoffset++) {
  169594. for (MCU_col_num = coef->MCU_ctr; MCU_col_num <= last_MCU_col;
  169595. MCU_col_num++) {
  169596. /* Try to fetch an MCU. Entropy decoder expects buffer to be zeroed. */
  169597. jzero_far((void FAR *) coef->MCU_buffer[0],
  169598. (size_t) (cinfo->blocks_in_MCU * SIZEOF(JBLOCK)));
  169599. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  169600. /* Suspension forced; update state counters and exit */
  169601. coef->MCU_vert_offset = yoffset;
  169602. coef->MCU_ctr = MCU_col_num;
  169603. return JPEG_SUSPENDED;
  169604. }
  169605. /* Determine where data should go in output_buf and do the IDCT thing.
  169606. * We skip dummy blocks at the right and bottom edges (but blkn gets
  169607. * incremented past them!). Note the inner loop relies on having
  169608. * allocated the MCU_buffer[] blocks sequentially.
  169609. */
  169610. blkn = 0; /* index of current DCT block within MCU */
  169611. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169612. compptr = cinfo->cur_comp_info[ci];
  169613. /* Don't bother to IDCT an uninteresting component. */
  169614. if (! compptr->component_needed) {
  169615. blkn += compptr->MCU_blocks;
  169616. continue;
  169617. }
  169618. inverse_DCT = cinfo->idct->inverse_DCT[compptr->component_index];
  169619. useful_width = (MCU_col_num < last_MCU_col) ? compptr->MCU_width
  169620. : compptr->last_col_width;
  169621. output_ptr = output_buf[compptr->component_index] +
  169622. yoffset * compptr->DCT_scaled_size;
  169623. start_col = MCU_col_num * compptr->MCU_sample_width;
  169624. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  169625. if (cinfo->input_iMCU_row < last_iMCU_row ||
  169626. yoffset+yindex < compptr->last_row_height) {
  169627. output_col = start_col;
  169628. for (xindex = 0; xindex < useful_width; xindex++) {
  169629. (*inverse_DCT) (cinfo, compptr,
  169630. (JCOEFPTR) coef->MCU_buffer[blkn+xindex],
  169631. output_ptr, output_col);
  169632. output_col += compptr->DCT_scaled_size;
  169633. }
  169634. }
  169635. blkn += compptr->MCU_width;
  169636. output_ptr += compptr->DCT_scaled_size;
  169637. }
  169638. }
  169639. }
  169640. /* Completed an MCU row, but perhaps not an iMCU row */
  169641. coef->MCU_ctr = 0;
  169642. }
  169643. /* Completed the iMCU row, advance counters for next one */
  169644. cinfo->output_iMCU_row++;
  169645. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  169646. start_iMCU_row3(cinfo);
  169647. return JPEG_ROW_COMPLETED;
  169648. }
  169649. /* Completed the scan */
  169650. (*cinfo->inputctl->finish_input_pass) (cinfo);
  169651. return JPEG_SCAN_COMPLETED;
  169652. }
  169653. /*
  169654. * Dummy consume-input routine for single-pass operation.
  169655. */
  169656. METHODDEF(int)
  169657. dummy_consume_data (j_decompress_ptr cinfo)
  169658. {
  169659. return JPEG_SUSPENDED; /* Always indicate nothing was done */
  169660. }
  169661. #ifdef D_MULTISCAN_FILES_SUPPORTED
  169662. /*
  169663. * Consume input data and store it in the full-image coefficient buffer.
  169664. * We read as much as one fully interleaved MCU row ("iMCU" row) per call,
  169665. * ie, v_samp_factor block rows for each component in the scan.
  169666. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  169667. */
  169668. METHODDEF(int)
  169669. consume_data (j_decompress_ptr cinfo)
  169670. {
  169671. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169672. JDIMENSION MCU_col_num; /* index of current MCU within row */
  169673. int blkn, ci, xindex, yindex, yoffset;
  169674. JDIMENSION start_col;
  169675. JBLOCKARRAY buffer[MAX_COMPS_IN_SCAN];
  169676. JBLOCKROW buffer_ptr;
  169677. jpeg_component_info *compptr;
  169678. /* Align the virtual buffers for the components used in this scan. */
  169679. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169680. compptr = cinfo->cur_comp_info[ci];
  169681. buffer[ci] = (*cinfo->mem->access_virt_barray)
  169682. ((j_common_ptr) cinfo, coef->whole_image[compptr->component_index],
  169683. cinfo->input_iMCU_row * compptr->v_samp_factor,
  169684. (JDIMENSION) compptr->v_samp_factor, TRUE);
  169685. /* Note: entropy decoder expects buffer to be zeroed,
  169686. * but this is handled automatically by the memory manager
  169687. * because we requested a pre-zeroed array.
  169688. */
  169689. }
  169690. /* Loop to process one whole iMCU row */
  169691. for (yoffset = coef->MCU_vert_offset; yoffset < coef->MCU_rows_per_iMCU_row;
  169692. yoffset++) {
  169693. for (MCU_col_num = coef->MCU_ctr; MCU_col_num < cinfo->MCUs_per_row;
  169694. MCU_col_num++) {
  169695. /* Construct list of pointers to DCT blocks belonging to this MCU */
  169696. blkn = 0; /* index of current DCT block within MCU */
  169697. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  169698. compptr = cinfo->cur_comp_info[ci];
  169699. start_col = MCU_col_num * compptr->MCU_width;
  169700. for (yindex = 0; yindex < compptr->MCU_height; yindex++) {
  169701. buffer_ptr = buffer[ci][yindex+yoffset] + start_col;
  169702. for (xindex = 0; xindex < compptr->MCU_width; xindex++) {
  169703. coef->MCU_buffer[blkn++] = buffer_ptr++;
  169704. }
  169705. }
  169706. }
  169707. /* Try to fetch the MCU. */
  169708. if (! (*cinfo->entropy->decode_mcu) (cinfo, coef->MCU_buffer)) {
  169709. /* Suspension forced; update state counters and exit */
  169710. coef->MCU_vert_offset = yoffset;
  169711. coef->MCU_ctr = MCU_col_num;
  169712. return JPEG_SUSPENDED;
  169713. }
  169714. }
  169715. /* Completed an MCU row, but perhaps not an iMCU row */
  169716. coef->MCU_ctr = 0;
  169717. }
  169718. /* Completed the iMCU row, advance counters for next one */
  169719. if (++(cinfo->input_iMCU_row) < cinfo->total_iMCU_rows) {
  169720. start_iMCU_row3(cinfo);
  169721. return JPEG_ROW_COMPLETED;
  169722. }
  169723. /* Completed the scan */
  169724. (*cinfo->inputctl->finish_input_pass) (cinfo);
  169725. return JPEG_SCAN_COMPLETED;
  169726. }
  169727. /*
  169728. * Decompress and return some data in the multi-pass case.
  169729. * Always attempts to emit one fully interleaved MCU row ("iMCU" row).
  169730. * Return value is JPEG_ROW_COMPLETED, JPEG_SCAN_COMPLETED, or JPEG_SUSPENDED.
  169731. *
  169732. * NB: output_buf contains a plane for each component in image.
  169733. */
  169734. METHODDEF(int)
  169735. decompress_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  169736. {
  169737. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169738. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  169739. JDIMENSION block_num;
  169740. int ci, block_row, block_rows;
  169741. JBLOCKARRAY buffer;
  169742. JBLOCKROW buffer_ptr;
  169743. JSAMPARRAY output_ptr;
  169744. JDIMENSION output_col;
  169745. jpeg_component_info *compptr;
  169746. inverse_DCT_method_ptr inverse_DCT;
  169747. /* Force some input to be done if we are getting ahead of the input. */
  169748. while (cinfo->input_scan_number < cinfo->output_scan_number ||
  169749. (cinfo->input_scan_number == cinfo->output_scan_number &&
  169750. cinfo->input_iMCU_row <= cinfo->output_iMCU_row)) {
  169751. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  169752. return JPEG_SUSPENDED;
  169753. }
  169754. /* OK, output from the virtual arrays. */
  169755. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169756. ci++, compptr++) {
  169757. /* Don't bother to IDCT an uninteresting component. */
  169758. if (! compptr->component_needed)
  169759. continue;
  169760. /* Align the virtual buffer for this component. */
  169761. buffer = (*cinfo->mem->access_virt_barray)
  169762. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169763. cinfo->output_iMCU_row * compptr->v_samp_factor,
  169764. (JDIMENSION) compptr->v_samp_factor, FALSE);
  169765. /* Count non-dummy DCT block rows in this iMCU row. */
  169766. if (cinfo->output_iMCU_row < last_iMCU_row)
  169767. block_rows = compptr->v_samp_factor;
  169768. else {
  169769. /* NB: can't use last_row_height here; it is input-side-dependent! */
  169770. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169771. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  169772. }
  169773. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  169774. output_ptr = output_buf[ci];
  169775. /* Loop over all DCT blocks to be processed. */
  169776. for (block_row = 0; block_row < block_rows; block_row++) {
  169777. buffer_ptr = buffer[block_row];
  169778. output_col = 0;
  169779. for (block_num = 0; block_num < compptr->width_in_blocks; block_num++) {
  169780. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) buffer_ptr,
  169781. output_ptr, output_col);
  169782. buffer_ptr++;
  169783. output_col += compptr->DCT_scaled_size;
  169784. }
  169785. output_ptr += compptr->DCT_scaled_size;
  169786. }
  169787. }
  169788. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  169789. return JPEG_ROW_COMPLETED;
  169790. return JPEG_SCAN_COMPLETED;
  169791. }
  169792. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  169793. #ifdef BLOCK_SMOOTHING_SUPPORTED
  169794. /*
  169795. * This code applies interblock smoothing as described by section K.8
  169796. * of the JPEG standard: the first 5 AC coefficients are estimated from
  169797. * the DC values of a DCT block and its 8 neighboring blocks.
  169798. * We apply smoothing only for progressive JPEG decoding, and only if
  169799. * the coefficients it can estimate are not yet known to full precision.
  169800. */
  169801. /* Natural-order array positions of the first 5 zigzag-order coefficients */
  169802. #define Q01_POS 1
  169803. #define Q10_POS 8
  169804. #define Q20_POS 16
  169805. #define Q11_POS 9
  169806. #define Q02_POS 2
  169807. /*
  169808. * Determine whether block smoothing is applicable and safe.
  169809. * We also latch the current states of the coef_bits[] entries for the
  169810. * AC coefficients; otherwise, if the input side of the decompressor
  169811. * advances into a new scan, we might think the coefficients are known
  169812. * more accurately than they really are.
  169813. */
  169814. LOCAL(boolean)
  169815. smoothing_ok (j_decompress_ptr cinfo)
  169816. {
  169817. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169818. boolean smoothing_useful = FALSE;
  169819. int ci, coefi;
  169820. jpeg_component_info *compptr;
  169821. JQUANT_TBL * qtable;
  169822. int * coef_bits;
  169823. int * coef_bits_latch;
  169824. if (! cinfo->progressive_mode || cinfo->coef_bits == NULL)
  169825. return FALSE;
  169826. /* Allocate latch area if not already done */
  169827. if (coef->coef_bits_latch == NULL)
  169828. coef->coef_bits_latch = (int *)
  169829. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  169830. cinfo->num_components *
  169831. (SAVED_COEFS * SIZEOF(int)));
  169832. coef_bits_latch = coef->coef_bits_latch;
  169833. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169834. ci++, compptr++) {
  169835. /* All components' quantization values must already be latched. */
  169836. if ((qtable = compptr->quant_table) == NULL)
  169837. return FALSE;
  169838. /* Verify DC & first 5 AC quantizers are nonzero to avoid zero-divide. */
  169839. if (qtable->quantval[0] == 0 ||
  169840. qtable->quantval[Q01_POS] == 0 ||
  169841. qtable->quantval[Q10_POS] == 0 ||
  169842. qtable->quantval[Q20_POS] == 0 ||
  169843. qtable->quantval[Q11_POS] == 0 ||
  169844. qtable->quantval[Q02_POS] == 0)
  169845. return FALSE;
  169846. /* DC values must be at least partly known for all components. */
  169847. coef_bits = cinfo->coef_bits[ci];
  169848. if (coef_bits[0] < 0)
  169849. return FALSE;
  169850. /* Block smoothing is helpful if some AC coefficients remain inaccurate. */
  169851. for (coefi = 1; coefi <= 5; coefi++) {
  169852. coef_bits_latch[coefi] = coef_bits[coefi];
  169853. if (coef_bits[coefi] != 0)
  169854. smoothing_useful = TRUE;
  169855. }
  169856. coef_bits_latch += SAVED_COEFS;
  169857. }
  169858. return smoothing_useful;
  169859. }
  169860. /*
  169861. * Variant of decompress_data for use when doing block smoothing.
  169862. */
  169863. METHODDEF(int)
  169864. decompress_smooth_data (j_decompress_ptr cinfo, JSAMPIMAGE output_buf)
  169865. {
  169866. my_coef_ptr3 coef = (my_coef_ptr3) cinfo->coef;
  169867. JDIMENSION last_iMCU_row = cinfo->total_iMCU_rows - 1;
  169868. JDIMENSION block_num, last_block_column;
  169869. int ci, block_row, block_rows, access_rows;
  169870. JBLOCKARRAY buffer;
  169871. JBLOCKROW buffer_ptr, prev_block_row, next_block_row;
  169872. JSAMPARRAY output_ptr;
  169873. JDIMENSION output_col;
  169874. jpeg_component_info *compptr;
  169875. inverse_DCT_method_ptr inverse_DCT;
  169876. boolean first_row, last_row;
  169877. JBLOCK workspace;
  169878. int *coef_bits;
  169879. JQUANT_TBL *quanttbl;
  169880. INT32 Q00,Q01,Q02,Q10,Q11,Q20, num;
  169881. int DC1,DC2,DC3,DC4,DC5,DC6,DC7,DC8,DC9;
  169882. int Al, pred;
  169883. /* Force some input to be done if we are getting ahead of the input. */
  169884. while (cinfo->input_scan_number <= cinfo->output_scan_number &&
  169885. ! cinfo->inputctl->eoi_reached) {
  169886. if (cinfo->input_scan_number == cinfo->output_scan_number) {
  169887. /* If input is working on current scan, we ordinarily want it to
  169888. * have completed the current row. But if input scan is DC,
  169889. * we want it to keep one row ahead so that next block row's DC
  169890. * values are up to date.
  169891. */
  169892. JDIMENSION delta = (cinfo->Ss == 0) ? 1 : 0;
  169893. if (cinfo->input_iMCU_row > cinfo->output_iMCU_row+delta)
  169894. break;
  169895. }
  169896. if ((*cinfo->inputctl->consume_input)(cinfo) == JPEG_SUSPENDED)
  169897. return JPEG_SUSPENDED;
  169898. }
  169899. /* OK, output from the virtual arrays. */
  169900. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  169901. ci++, compptr++) {
  169902. /* Don't bother to IDCT an uninteresting component. */
  169903. if (! compptr->component_needed)
  169904. continue;
  169905. /* Count non-dummy DCT block rows in this iMCU row. */
  169906. if (cinfo->output_iMCU_row < last_iMCU_row) {
  169907. block_rows = compptr->v_samp_factor;
  169908. access_rows = block_rows * 2; /* this and next iMCU row */
  169909. last_row = FALSE;
  169910. } else {
  169911. /* NB: can't use last_row_height here; it is input-side-dependent! */
  169912. block_rows = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  169913. if (block_rows == 0) block_rows = compptr->v_samp_factor;
  169914. access_rows = block_rows; /* this iMCU row only */
  169915. last_row = TRUE;
  169916. }
  169917. /* Align the virtual buffer for this component. */
  169918. if (cinfo->output_iMCU_row > 0) {
  169919. access_rows += compptr->v_samp_factor; /* prior iMCU row too */
  169920. buffer = (*cinfo->mem->access_virt_barray)
  169921. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169922. (cinfo->output_iMCU_row - 1) * compptr->v_samp_factor,
  169923. (JDIMENSION) access_rows, FALSE);
  169924. buffer += compptr->v_samp_factor; /* point to current iMCU row */
  169925. first_row = FALSE;
  169926. } else {
  169927. buffer = (*cinfo->mem->access_virt_barray)
  169928. ((j_common_ptr) cinfo, coef->whole_image[ci],
  169929. (JDIMENSION) 0, (JDIMENSION) access_rows, FALSE);
  169930. first_row = TRUE;
  169931. }
  169932. /* Fetch component-dependent info */
  169933. coef_bits = coef->coef_bits_latch + (ci * SAVED_COEFS);
  169934. quanttbl = compptr->quant_table;
  169935. Q00 = quanttbl->quantval[0];
  169936. Q01 = quanttbl->quantval[Q01_POS];
  169937. Q10 = quanttbl->quantval[Q10_POS];
  169938. Q20 = quanttbl->quantval[Q20_POS];
  169939. Q11 = quanttbl->quantval[Q11_POS];
  169940. Q02 = quanttbl->quantval[Q02_POS];
  169941. inverse_DCT = cinfo->idct->inverse_DCT[ci];
  169942. output_ptr = output_buf[ci];
  169943. /* Loop over all DCT blocks to be processed. */
  169944. for (block_row = 0; block_row < block_rows; block_row++) {
  169945. buffer_ptr = buffer[block_row];
  169946. if (first_row && block_row == 0)
  169947. prev_block_row = buffer_ptr;
  169948. else
  169949. prev_block_row = buffer[block_row-1];
  169950. if (last_row && block_row == block_rows-1)
  169951. next_block_row = buffer_ptr;
  169952. else
  169953. next_block_row = buffer[block_row+1];
  169954. /* We fetch the surrounding DC values using a sliding-register approach.
  169955. * Initialize all nine here so as to do the right thing on narrow pics.
  169956. */
  169957. DC1 = DC2 = DC3 = (int) prev_block_row[0][0];
  169958. DC4 = DC5 = DC6 = (int) buffer_ptr[0][0];
  169959. DC7 = DC8 = DC9 = (int) next_block_row[0][0];
  169960. output_col = 0;
  169961. last_block_column = compptr->width_in_blocks - 1;
  169962. for (block_num = 0; block_num <= last_block_column; block_num++) {
  169963. /* Fetch current DCT block into workspace so we can modify it. */
  169964. jcopy_block_row(buffer_ptr, (JBLOCKROW) workspace, (JDIMENSION) 1);
  169965. /* Update DC values */
  169966. if (block_num < last_block_column) {
  169967. DC3 = (int) prev_block_row[1][0];
  169968. DC6 = (int) buffer_ptr[1][0];
  169969. DC9 = (int) next_block_row[1][0];
  169970. }
  169971. /* Compute coefficient estimates per K.8.
  169972. * An estimate is applied only if coefficient is still zero,
  169973. * and is not known to be fully accurate.
  169974. */
  169975. /* AC01 */
  169976. if ((Al=coef_bits[1]) != 0 && workspace[1] == 0) {
  169977. num = 36 * Q00 * (DC4 - DC6);
  169978. if (num >= 0) {
  169979. pred = (int) (((Q01<<7) + num) / (Q01<<8));
  169980. if (Al > 0 && pred >= (1<<Al))
  169981. pred = (1<<Al)-1;
  169982. } else {
  169983. pred = (int) (((Q01<<7) - num) / (Q01<<8));
  169984. if (Al > 0 && pred >= (1<<Al))
  169985. pred = (1<<Al)-1;
  169986. pred = -pred;
  169987. }
  169988. workspace[1] = (JCOEF) pred;
  169989. }
  169990. /* AC10 */
  169991. if ((Al=coef_bits[2]) != 0 && workspace[8] == 0) {
  169992. num = 36 * Q00 * (DC2 - DC8);
  169993. if (num >= 0) {
  169994. pred = (int) (((Q10<<7) + num) / (Q10<<8));
  169995. if (Al > 0 && pred >= (1<<Al))
  169996. pred = (1<<Al)-1;
  169997. } else {
  169998. pred = (int) (((Q10<<7) - num) / (Q10<<8));
  169999. if (Al > 0 && pred >= (1<<Al))
  170000. pred = (1<<Al)-1;
  170001. pred = -pred;
  170002. }
  170003. workspace[8] = (JCOEF) pred;
  170004. }
  170005. /* AC20 */
  170006. if ((Al=coef_bits[3]) != 0 && workspace[16] == 0) {
  170007. num = 9 * Q00 * (DC2 + DC8 - 2*DC5);
  170008. if (num >= 0) {
  170009. pred = (int) (((Q20<<7) + num) / (Q20<<8));
  170010. if (Al > 0 && pred >= (1<<Al))
  170011. pred = (1<<Al)-1;
  170012. } else {
  170013. pred = (int) (((Q20<<7) - num) / (Q20<<8));
  170014. if (Al > 0 && pred >= (1<<Al))
  170015. pred = (1<<Al)-1;
  170016. pred = -pred;
  170017. }
  170018. workspace[16] = (JCOEF) pred;
  170019. }
  170020. /* AC11 */
  170021. if ((Al=coef_bits[4]) != 0 && workspace[9] == 0) {
  170022. num = 5 * Q00 * (DC1 - DC3 - DC7 + DC9);
  170023. if (num >= 0) {
  170024. pred = (int) (((Q11<<7) + num) / (Q11<<8));
  170025. if (Al > 0 && pred >= (1<<Al))
  170026. pred = (1<<Al)-1;
  170027. } else {
  170028. pred = (int) (((Q11<<7) - num) / (Q11<<8));
  170029. if (Al > 0 && pred >= (1<<Al))
  170030. pred = (1<<Al)-1;
  170031. pred = -pred;
  170032. }
  170033. workspace[9] = (JCOEF) pred;
  170034. }
  170035. /* AC02 */
  170036. if ((Al=coef_bits[5]) != 0 && workspace[2] == 0) {
  170037. num = 9 * Q00 * (DC4 + DC6 - 2*DC5);
  170038. if (num >= 0) {
  170039. pred = (int) (((Q02<<7) + num) / (Q02<<8));
  170040. if (Al > 0 && pred >= (1<<Al))
  170041. pred = (1<<Al)-1;
  170042. } else {
  170043. pred = (int) (((Q02<<7) - num) / (Q02<<8));
  170044. if (Al > 0 && pred >= (1<<Al))
  170045. pred = (1<<Al)-1;
  170046. pred = -pred;
  170047. }
  170048. workspace[2] = (JCOEF) pred;
  170049. }
  170050. /* OK, do the IDCT */
  170051. (*inverse_DCT) (cinfo, compptr, (JCOEFPTR) workspace,
  170052. output_ptr, output_col);
  170053. /* Advance for next column */
  170054. DC1 = DC2; DC2 = DC3;
  170055. DC4 = DC5; DC5 = DC6;
  170056. DC7 = DC8; DC8 = DC9;
  170057. buffer_ptr++, prev_block_row++, next_block_row++;
  170058. output_col += compptr->DCT_scaled_size;
  170059. }
  170060. output_ptr += compptr->DCT_scaled_size;
  170061. }
  170062. }
  170063. if (++(cinfo->output_iMCU_row) < cinfo->total_iMCU_rows)
  170064. return JPEG_ROW_COMPLETED;
  170065. return JPEG_SCAN_COMPLETED;
  170066. }
  170067. #endif /* BLOCK_SMOOTHING_SUPPORTED */
  170068. /*
  170069. * Initialize coefficient buffer controller.
  170070. */
  170071. GLOBAL(void)
  170072. jinit_d_coef_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  170073. {
  170074. my_coef_ptr3 coef;
  170075. coef = (my_coef_ptr3)
  170076. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170077. SIZEOF(my_coef_controller3));
  170078. cinfo->coef = (struct jpeg_d_coef_controller *) coef;
  170079. coef->pub.start_input_pass = start_input_pass;
  170080. coef->pub.start_output_pass = start_output_pass;
  170081. #ifdef BLOCK_SMOOTHING_SUPPORTED
  170082. coef->coef_bits_latch = NULL;
  170083. #endif
  170084. /* Create the coefficient buffer. */
  170085. if (need_full_buffer) {
  170086. #ifdef D_MULTISCAN_FILES_SUPPORTED
  170087. /* Allocate a full-image virtual array for each component, */
  170088. /* padded to a multiple of samp_factor DCT blocks in each direction. */
  170089. /* Note we ask for a pre-zeroed array. */
  170090. int ci, access_rows;
  170091. jpeg_component_info *compptr;
  170092. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170093. ci++, compptr++) {
  170094. access_rows = compptr->v_samp_factor;
  170095. #ifdef BLOCK_SMOOTHING_SUPPORTED
  170096. /* If block smoothing could be used, need a bigger window */
  170097. if (cinfo->progressive_mode)
  170098. access_rows *= 3;
  170099. #endif
  170100. coef->whole_image[ci] = (*cinfo->mem->request_virt_barray)
  170101. ((j_common_ptr) cinfo, JPOOL_IMAGE, TRUE,
  170102. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  170103. (long) compptr->h_samp_factor),
  170104. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  170105. (long) compptr->v_samp_factor),
  170106. (JDIMENSION) access_rows);
  170107. }
  170108. coef->pub.consume_data = consume_data;
  170109. coef->pub.decompress_data = decompress_data;
  170110. coef->pub.coef_arrays = coef->whole_image; /* link to virtual arrays */
  170111. #else
  170112. ERREXIT(cinfo, JERR_NOT_COMPILED);
  170113. #endif
  170114. } else {
  170115. /* We only need a single-MCU buffer. */
  170116. JBLOCKROW buffer;
  170117. int i;
  170118. buffer = (JBLOCKROW)
  170119. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170120. D_MAX_BLOCKS_IN_MCU * SIZEOF(JBLOCK));
  170121. for (i = 0; i < D_MAX_BLOCKS_IN_MCU; i++) {
  170122. coef->MCU_buffer[i] = buffer + i;
  170123. }
  170124. coef->pub.consume_data = dummy_consume_data;
  170125. coef->pub.decompress_data = decompress_onepass;
  170126. coef->pub.coef_arrays = NULL; /* flag for no virtual arrays */
  170127. }
  170128. }
  170129. /********* End of inlined file: jdcoefct.c *********/
  170130. #undef FIX
  170131. /********* Start of inlined file: jdcolor.c *********/
  170132. #define JPEG_INTERNALS
  170133. /* Private subobject */
  170134. typedef struct {
  170135. struct jpeg_color_deconverter pub; /* public fields */
  170136. /* Private state for YCC->RGB conversion */
  170137. int * Cr_r_tab; /* => table for Cr to R conversion */
  170138. int * Cb_b_tab; /* => table for Cb to B conversion */
  170139. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  170140. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  170141. } my_color_deconverter2;
  170142. typedef my_color_deconverter2 * my_cconvert_ptr2;
  170143. /**************** YCbCr -> RGB conversion: most common case **************/
  170144. /*
  170145. * YCbCr is defined per CCIR 601-1, except that Cb and Cr are
  170146. * normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
  170147. * The conversion equations to be implemented are therefore
  170148. * R = Y + 1.40200 * Cr
  170149. * G = Y - 0.34414 * Cb - 0.71414 * Cr
  170150. * B = Y + 1.77200 * Cb
  170151. * where Cb and Cr represent the incoming values less CENTERJSAMPLE.
  170152. * (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
  170153. *
  170154. * To avoid floating-point arithmetic, we represent the fractional constants
  170155. * as integers scaled up by 2^16 (about 4 digits precision); we have to divide
  170156. * the products by 2^16, with appropriate rounding, to get the correct answer.
  170157. * Notice that Y, being an integral input, does not contribute any fraction
  170158. * so it need not participate in the rounding.
  170159. *
  170160. * For even more speed, we avoid doing any multiplications in the inner loop
  170161. * by precalculating the constants times Cb and Cr for all possible values.
  170162. * For 8-bit JSAMPLEs this is very reasonable (only 256 entries per table);
  170163. * for 12-bit samples it is still acceptable. It's not very reasonable for
  170164. * 16-bit samples, but if you want lossless storage you shouldn't be changing
  170165. * colorspace anyway.
  170166. * The Cr=>R and Cb=>B values can be rounded to integers in advance; the
  170167. * values for the G calculation are left scaled up, since we must add them
  170168. * together before rounding.
  170169. */
  170170. #define SCALEBITS 16 /* speediest right-shift on some machines */
  170171. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  170172. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  170173. /*
  170174. * Initialize tables for YCC->RGB colorspace conversion.
  170175. */
  170176. LOCAL(void)
  170177. build_ycc_rgb_table (j_decompress_ptr cinfo)
  170178. {
  170179. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  170180. int i;
  170181. INT32 x;
  170182. SHIFT_TEMPS
  170183. cconvert->Cr_r_tab = (int *)
  170184. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170185. (MAXJSAMPLE+1) * SIZEOF(int));
  170186. cconvert->Cb_b_tab = (int *)
  170187. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170188. (MAXJSAMPLE+1) * SIZEOF(int));
  170189. cconvert->Cr_g_tab = (INT32 *)
  170190. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170191. (MAXJSAMPLE+1) * SIZEOF(INT32));
  170192. cconvert->Cb_g_tab = (INT32 *)
  170193. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170194. (MAXJSAMPLE+1) * SIZEOF(INT32));
  170195. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  170196. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  170197. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  170198. /* Cr=>R value is nearest int to 1.40200 * x */
  170199. cconvert->Cr_r_tab[i] = (int)
  170200. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  170201. /* Cb=>B value is nearest int to 1.77200 * x */
  170202. cconvert->Cb_b_tab[i] = (int)
  170203. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  170204. /* Cr=>G value is scaled-up -0.71414 * x */
  170205. cconvert->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  170206. /* Cb=>G value is scaled-up -0.34414 * x */
  170207. /* We also add in ONE_HALF so that need not do it in inner loop */
  170208. cconvert->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  170209. }
  170210. }
  170211. /*
  170212. * Convert some rows of samples to the output colorspace.
  170213. *
  170214. * Note that we change from noninterleaved, one-plane-per-component format
  170215. * to interleaved-pixel format. The output buffer is therefore three times
  170216. * as wide as the input buffer.
  170217. * A starting row offset is provided only for the input buffer. The caller
  170218. * can easily adjust the passed output_buf value to accommodate any row
  170219. * offset required on that side.
  170220. */
  170221. METHODDEF(void)
  170222. ycc_rgb_convert (j_decompress_ptr cinfo,
  170223. JSAMPIMAGE input_buf, JDIMENSION input_row,
  170224. JSAMPARRAY output_buf, int num_rows)
  170225. {
  170226. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  170227. register int y, cb, cr;
  170228. register JSAMPROW outptr;
  170229. register JSAMPROW inptr0, inptr1, inptr2;
  170230. register JDIMENSION col;
  170231. JDIMENSION num_cols = cinfo->output_width;
  170232. /* copy these pointers into registers if possible */
  170233. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  170234. register int * Crrtab = cconvert->Cr_r_tab;
  170235. register int * Cbbtab = cconvert->Cb_b_tab;
  170236. register INT32 * Crgtab = cconvert->Cr_g_tab;
  170237. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  170238. SHIFT_TEMPS
  170239. while (--num_rows >= 0) {
  170240. inptr0 = input_buf[0][input_row];
  170241. inptr1 = input_buf[1][input_row];
  170242. inptr2 = input_buf[2][input_row];
  170243. input_row++;
  170244. outptr = *output_buf++;
  170245. for (col = 0; col < num_cols; col++) {
  170246. y = GETJSAMPLE(inptr0[col]);
  170247. cb = GETJSAMPLE(inptr1[col]);
  170248. cr = GETJSAMPLE(inptr2[col]);
  170249. /* Range-limiting is essential due to noise introduced by DCT losses. */
  170250. outptr[RGB_RED] = range_limit[y + Crrtab[cr]];
  170251. outptr[RGB_GREEN] = range_limit[y +
  170252. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  170253. SCALEBITS))];
  170254. outptr[RGB_BLUE] = range_limit[y + Cbbtab[cb]];
  170255. outptr += RGB_PIXELSIZE;
  170256. }
  170257. }
  170258. }
  170259. /**************** Cases other than YCbCr -> RGB **************/
  170260. /*
  170261. * Color conversion for no colorspace change: just copy the data,
  170262. * converting from separate-planes to interleaved representation.
  170263. */
  170264. METHODDEF(void)
  170265. null_convert2 (j_decompress_ptr cinfo,
  170266. JSAMPIMAGE input_buf, JDIMENSION input_row,
  170267. JSAMPARRAY output_buf, int num_rows)
  170268. {
  170269. register JSAMPROW inptr, outptr;
  170270. register JDIMENSION count;
  170271. register int num_components = cinfo->num_components;
  170272. JDIMENSION num_cols = cinfo->output_width;
  170273. int ci;
  170274. while (--num_rows >= 0) {
  170275. for (ci = 0; ci < num_components; ci++) {
  170276. inptr = input_buf[ci][input_row];
  170277. outptr = output_buf[0] + ci;
  170278. for (count = num_cols; count > 0; count--) {
  170279. *outptr = *inptr++; /* needn't bother with GETJSAMPLE() here */
  170280. outptr += num_components;
  170281. }
  170282. }
  170283. input_row++;
  170284. output_buf++;
  170285. }
  170286. }
  170287. /*
  170288. * Color conversion for grayscale: just copy the data.
  170289. * This also works for YCbCr -> grayscale conversion, in which
  170290. * we just copy the Y (luminance) component and ignore chrominance.
  170291. */
  170292. METHODDEF(void)
  170293. grayscale_convert2 (j_decompress_ptr cinfo,
  170294. JSAMPIMAGE input_buf, JDIMENSION input_row,
  170295. JSAMPARRAY output_buf, int num_rows)
  170296. {
  170297. jcopy_sample_rows(input_buf[0], (int) input_row, output_buf, 0,
  170298. num_rows, cinfo->output_width);
  170299. }
  170300. /*
  170301. * Convert grayscale to RGB: just duplicate the graylevel three times.
  170302. * This is provided to support applications that don't want to cope
  170303. * with grayscale as a separate case.
  170304. */
  170305. METHODDEF(void)
  170306. gray_rgb_convert (j_decompress_ptr cinfo,
  170307. JSAMPIMAGE input_buf, JDIMENSION input_row,
  170308. JSAMPARRAY output_buf, int num_rows)
  170309. {
  170310. register JSAMPROW inptr, outptr;
  170311. register JDIMENSION col;
  170312. JDIMENSION num_cols = cinfo->output_width;
  170313. while (--num_rows >= 0) {
  170314. inptr = input_buf[0][input_row++];
  170315. outptr = *output_buf++;
  170316. for (col = 0; col < num_cols; col++) {
  170317. /* We can dispense with GETJSAMPLE() here */
  170318. outptr[RGB_RED] = outptr[RGB_GREEN] = outptr[RGB_BLUE] = inptr[col];
  170319. outptr += RGB_PIXELSIZE;
  170320. }
  170321. }
  170322. }
  170323. /*
  170324. * Adobe-style YCCK->CMYK conversion.
  170325. * We convert YCbCr to R=1-C, G=1-M, and B=1-Y using the same
  170326. * conversion as above, while passing K (black) unchanged.
  170327. * We assume build_ycc_rgb_table has been called.
  170328. */
  170329. METHODDEF(void)
  170330. ycck_cmyk_convert (j_decompress_ptr cinfo,
  170331. JSAMPIMAGE input_buf, JDIMENSION input_row,
  170332. JSAMPARRAY output_buf, int num_rows)
  170333. {
  170334. my_cconvert_ptr2 cconvert = (my_cconvert_ptr2) cinfo->cconvert;
  170335. register int y, cb, cr;
  170336. register JSAMPROW outptr;
  170337. register JSAMPROW inptr0, inptr1, inptr2, inptr3;
  170338. register JDIMENSION col;
  170339. JDIMENSION num_cols = cinfo->output_width;
  170340. /* copy these pointers into registers if possible */
  170341. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  170342. register int * Crrtab = cconvert->Cr_r_tab;
  170343. register int * Cbbtab = cconvert->Cb_b_tab;
  170344. register INT32 * Crgtab = cconvert->Cr_g_tab;
  170345. register INT32 * Cbgtab = cconvert->Cb_g_tab;
  170346. SHIFT_TEMPS
  170347. while (--num_rows >= 0) {
  170348. inptr0 = input_buf[0][input_row];
  170349. inptr1 = input_buf[1][input_row];
  170350. inptr2 = input_buf[2][input_row];
  170351. inptr3 = input_buf[3][input_row];
  170352. input_row++;
  170353. outptr = *output_buf++;
  170354. for (col = 0; col < num_cols; col++) {
  170355. y = GETJSAMPLE(inptr0[col]);
  170356. cb = GETJSAMPLE(inptr1[col]);
  170357. cr = GETJSAMPLE(inptr2[col]);
  170358. /* Range-limiting is essential due to noise introduced by DCT losses. */
  170359. outptr[0] = range_limit[MAXJSAMPLE - (y + Crrtab[cr])]; /* red */
  170360. outptr[1] = range_limit[MAXJSAMPLE - (y + /* green */
  170361. ((int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr],
  170362. SCALEBITS)))];
  170363. outptr[2] = range_limit[MAXJSAMPLE - (y + Cbbtab[cb])]; /* blue */
  170364. /* K passes through unchanged */
  170365. outptr[3] = inptr3[col]; /* don't need GETJSAMPLE here */
  170366. outptr += 4;
  170367. }
  170368. }
  170369. }
  170370. /*
  170371. * Empty method for start_pass.
  170372. */
  170373. METHODDEF(void)
  170374. start_pass_dcolor (j_decompress_ptr cinfo)
  170375. {
  170376. /* no work needed */
  170377. }
  170378. /*
  170379. * Module initialization routine for output colorspace conversion.
  170380. */
  170381. GLOBAL(void)
  170382. jinit_color_deconverter (j_decompress_ptr cinfo)
  170383. {
  170384. my_cconvert_ptr2 cconvert;
  170385. int ci;
  170386. cconvert = (my_cconvert_ptr2)
  170387. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170388. SIZEOF(my_color_deconverter2));
  170389. cinfo->cconvert = (struct jpeg_color_deconverter *) cconvert;
  170390. cconvert->pub.start_pass = start_pass_dcolor;
  170391. /* Make sure num_components agrees with jpeg_color_space */
  170392. switch (cinfo->jpeg_color_space) {
  170393. case JCS_GRAYSCALE:
  170394. if (cinfo->num_components != 1)
  170395. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  170396. break;
  170397. case JCS_RGB:
  170398. case JCS_YCbCr:
  170399. if (cinfo->num_components != 3)
  170400. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  170401. break;
  170402. case JCS_CMYK:
  170403. case JCS_YCCK:
  170404. if (cinfo->num_components != 4)
  170405. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  170406. break;
  170407. default: /* JCS_UNKNOWN can be anything */
  170408. if (cinfo->num_components < 1)
  170409. ERREXIT(cinfo, JERR_BAD_J_COLORSPACE);
  170410. break;
  170411. }
  170412. /* Set out_color_components and conversion method based on requested space.
  170413. * Also clear the component_needed flags for any unused components,
  170414. * so that earlier pipeline stages can avoid useless computation.
  170415. */
  170416. switch (cinfo->out_color_space) {
  170417. case JCS_GRAYSCALE:
  170418. cinfo->out_color_components = 1;
  170419. if (cinfo->jpeg_color_space == JCS_GRAYSCALE ||
  170420. cinfo->jpeg_color_space == JCS_YCbCr) {
  170421. cconvert->pub.color_convert = grayscale_convert2;
  170422. /* For color->grayscale conversion, only the Y (0) component is needed */
  170423. for (ci = 1; ci < cinfo->num_components; ci++)
  170424. cinfo->comp_info[ci].component_needed = FALSE;
  170425. } else
  170426. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  170427. break;
  170428. case JCS_RGB:
  170429. cinfo->out_color_components = RGB_PIXELSIZE;
  170430. if (cinfo->jpeg_color_space == JCS_YCbCr) {
  170431. cconvert->pub.color_convert = ycc_rgb_convert;
  170432. build_ycc_rgb_table(cinfo);
  170433. } else if (cinfo->jpeg_color_space == JCS_GRAYSCALE) {
  170434. cconvert->pub.color_convert = gray_rgb_convert;
  170435. } else if (cinfo->jpeg_color_space == JCS_RGB && RGB_PIXELSIZE == 3) {
  170436. cconvert->pub.color_convert = null_convert2;
  170437. } else
  170438. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  170439. break;
  170440. case JCS_CMYK:
  170441. cinfo->out_color_components = 4;
  170442. if (cinfo->jpeg_color_space == JCS_YCCK) {
  170443. cconvert->pub.color_convert = ycck_cmyk_convert;
  170444. build_ycc_rgb_table(cinfo);
  170445. } else if (cinfo->jpeg_color_space == JCS_CMYK) {
  170446. cconvert->pub.color_convert = null_convert2;
  170447. } else
  170448. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  170449. break;
  170450. default:
  170451. /* Permit null conversion to same output space */
  170452. if (cinfo->out_color_space == cinfo->jpeg_color_space) {
  170453. cinfo->out_color_components = cinfo->num_components;
  170454. cconvert->pub.color_convert = null_convert2;
  170455. } else /* unsupported non-null conversion */
  170456. ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
  170457. break;
  170458. }
  170459. if (cinfo->quantize_colors)
  170460. cinfo->output_components = 1; /* single colormapped output component */
  170461. else
  170462. cinfo->output_components = cinfo->out_color_components;
  170463. }
  170464. /********* End of inlined file: jdcolor.c *********/
  170465. #undef FIX
  170466. /********* Start of inlined file: jddctmgr.c *********/
  170467. #define JPEG_INTERNALS
  170468. /*
  170469. * The decompressor input side (jdinput.c) saves away the appropriate
  170470. * quantization table for each component at the start of the first scan
  170471. * involving that component. (This is necessary in order to correctly
  170472. * decode files that reuse Q-table slots.)
  170473. * When we are ready to make an output pass, the saved Q-table is converted
  170474. * to a multiplier table that will actually be used by the IDCT routine.
  170475. * The multiplier table contents are IDCT-method-dependent. To support
  170476. * application changes in IDCT method between scans, we can remake the
  170477. * multiplier tables if necessary.
  170478. * In buffered-image mode, the first output pass may occur before any data
  170479. * has been seen for some components, and thus before their Q-tables have
  170480. * been saved away. To handle this case, multiplier tables are preset
  170481. * to zeroes; the result of the IDCT will be a neutral gray level.
  170482. */
  170483. /* Private subobject for this module */
  170484. typedef struct {
  170485. struct jpeg_inverse_dct pub; /* public fields */
  170486. /* This array contains the IDCT method code that each multiplier table
  170487. * is currently set up for, or -1 if it's not yet set up.
  170488. * The actual multiplier tables are pointed to by dct_table in the
  170489. * per-component comp_info structures.
  170490. */
  170491. int cur_method[MAX_COMPONENTS];
  170492. } my_idct_controller;
  170493. typedef my_idct_controller * my_idct_ptr;
  170494. /* Allocated multiplier tables: big enough for any supported variant */
  170495. typedef union {
  170496. ISLOW_MULT_TYPE islow_array[DCTSIZE2];
  170497. #ifdef DCT_IFAST_SUPPORTED
  170498. IFAST_MULT_TYPE ifast_array[DCTSIZE2];
  170499. #endif
  170500. #ifdef DCT_FLOAT_SUPPORTED
  170501. FLOAT_MULT_TYPE float_array[DCTSIZE2];
  170502. #endif
  170503. } multiplier_table;
  170504. /* The current scaled-IDCT routines require ISLOW-style multiplier tables,
  170505. * so be sure to compile that code if either ISLOW or SCALING is requested.
  170506. */
  170507. #ifdef DCT_ISLOW_SUPPORTED
  170508. #define PROVIDE_ISLOW_TABLES
  170509. #else
  170510. #ifdef IDCT_SCALING_SUPPORTED
  170511. #define PROVIDE_ISLOW_TABLES
  170512. #endif
  170513. #endif
  170514. /*
  170515. * Prepare for an output pass.
  170516. * Here we select the proper IDCT routine for each component and build
  170517. * a matching multiplier table.
  170518. */
  170519. METHODDEF(void)
  170520. start_pass (j_decompress_ptr cinfo)
  170521. {
  170522. my_idct_ptr idct = (my_idct_ptr) cinfo->idct;
  170523. int ci, i;
  170524. jpeg_component_info *compptr;
  170525. int method = 0;
  170526. inverse_DCT_method_ptr method_ptr = NULL;
  170527. JQUANT_TBL * qtbl;
  170528. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170529. ci++, compptr++) {
  170530. /* Select the proper IDCT routine for this component's scaling */
  170531. switch (compptr->DCT_scaled_size) {
  170532. #ifdef IDCT_SCALING_SUPPORTED
  170533. case 1:
  170534. method_ptr = jpeg_idct_1x1;
  170535. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  170536. break;
  170537. case 2:
  170538. method_ptr = jpeg_idct_2x2;
  170539. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  170540. break;
  170541. case 4:
  170542. method_ptr = jpeg_idct_4x4;
  170543. method = JDCT_ISLOW; /* jidctred uses islow-style table */
  170544. break;
  170545. #endif
  170546. case DCTSIZE:
  170547. switch (cinfo->dct_method) {
  170548. #ifdef DCT_ISLOW_SUPPORTED
  170549. case JDCT_ISLOW:
  170550. method_ptr = jpeg_idct_islow;
  170551. method = JDCT_ISLOW;
  170552. break;
  170553. #endif
  170554. #ifdef DCT_IFAST_SUPPORTED
  170555. case JDCT_IFAST:
  170556. method_ptr = jpeg_idct_ifast;
  170557. method = JDCT_IFAST;
  170558. break;
  170559. #endif
  170560. #ifdef DCT_FLOAT_SUPPORTED
  170561. case JDCT_FLOAT:
  170562. method_ptr = jpeg_idct_float;
  170563. method = JDCT_FLOAT;
  170564. break;
  170565. #endif
  170566. default:
  170567. ERREXIT(cinfo, JERR_NOT_COMPILED);
  170568. break;
  170569. }
  170570. break;
  170571. default:
  170572. ERREXIT1(cinfo, JERR_BAD_DCTSIZE, compptr->DCT_scaled_size);
  170573. break;
  170574. }
  170575. idct->pub.inverse_DCT[ci] = method_ptr;
  170576. /* Create multiplier table from quant table.
  170577. * However, we can skip this if the component is uninteresting
  170578. * or if we already built the table. Also, if no quant table
  170579. * has yet been saved for the component, we leave the
  170580. * multiplier table all-zero; we'll be reading zeroes from the
  170581. * coefficient controller's buffer anyway.
  170582. */
  170583. if (! compptr->component_needed || idct->cur_method[ci] == method)
  170584. continue;
  170585. qtbl = compptr->quant_table;
  170586. if (qtbl == NULL) /* happens if no data yet for component */
  170587. continue;
  170588. idct->cur_method[ci] = method;
  170589. switch (method) {
  170590. #ifdef PROVIDE_ISLOW_TABLES
  170591. case JDCT_ISLOW:
  170592. {
  170593. /* For LL&M IDCT method, multipliers are equal to raw quantization
  170594. * coefficients, but are stored as ints to ensure access efficiency.
  170595. */
  170596. ISLOW_MULT_TYPE * ismtbl = (ISLOW_MULT_TYPE *) compptr->dct_table;
  170597. for (i = 0; i < DCTSIZE2; i++) {
  170598. ismtbl[i] = (ISLOW_MULT_TYPE) qtbl->quantval[i];
  170599. }
  170600. }
  170601. break;
  170602. #endif
  170603. #ifdef DCT_IFAST_SUPPORTED
  170604. case JDCT_IFAST:
  170605. {
  170606. /* For AA&N IDCT method, multipliers are equal to quantization
  170607. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  170608. * scalefactor[0] = 1
  170609. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  170610. * For integer operation, the multiplier table is to be scaled by
  170611. * IFAST_SCALE_BITS.
  170612. */
  170613. IFAST_MULT_TYPE * ifmtbl = (IFAST_MULT_TYPE *) compptr->dct_table;
  170614. #define CONST_BITS 14
  170615. static const INT16 aanscales[DCTSIZE2] = {
  170616. /* precomputed values scaled up by 14 bits */
  170617. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  170618. 22725, 31521, 29692, 26722, 22725, 17855, 12299, 6270,
  170619. 21407, 29692, 27969, 25172, 21407, 16819, 11585, 5906,
  170620. 19266, 26722, 25172, 22654, 19266, 15137, 10426, 5315,
  170621. 16384, 22725, 21407, 19266, 16384, 12873, 8867, 4520,
  170622. 12873, 17855, 16819, 15137, 12873, 10114, 6967, 3552,
  170623. 8867, 12299, 11585, 10426, 8867, 6967, 4799, 2446,
  170624. 4520, 6270, 5906, 5315, 4520, 3552, 2446, 1247
  170625. };
  170626. SHIFT_TEMPS
  170627. for (i = 0; i < DCTSIZE2; i++) {
  170628. ifmtbl[i] = (IFAST_MULT_TYPE)
  170629. DESCALE(MULTIPLY16V16((INT32) qtbl->quantval[i],
  170630. (INT32) aanscales[i]),
  170631. CONST_BITS-IFAST_SCALE_BITS);
  170632. }
  170633. }
  170634. break;
  170635. #endif
  170636. #ifdef DCT_FLOAT_SUPPORTED
  170637. case JDCT_FLOAT:
  170638. {
  170639. /* For float AA&N IDCT method, multipliers are equal to quantization
  170640. * coefficients scaled by scalefactor[row]*scalefactor[col], where
  170641. * scalefactor[0] = 1
  170642. * scalefactor[k] = cos(k*PI/16) * sqrt(2) for k=1..7
  170643. */
  170644. FLOAT_MULT_TYPE * fmtbl = (FLOAT_MULT_TYPE *) compptr->dct_table;
  170645. int row, col;
  170646. static const double aanscalefactor[DCTSIZE] = {
  170647. 1.0, 1.387039845, 1.306562965, 1.175875602,
  170648. 1.0, 0.785694958, 0.541196100, 0.275899379
  170649. };
  170650. i = 0;
  170651. for (row = 0; row < DCTSIZE; row++) {
  170652. for (col = 0; col < DCTSIZE; col++) {
  170653. fmtbl[i] = (FLOAT_MULT_TYPE)
  170654. ((double) qtbl->quantval[i] *
  170655. aanscalefactor[row] * aanscalefactor[col]);
  170656. i++;
  170657. }
  170658. }
  170659. }
  170660. break;
  170661. #endif
  170662. default:
  170663. ERREXIT(cinfo, JERR_NOT_COMPILED);
  170664. break;
  170665. }
  170666. }
  170667. }
  170668. /*
  170669. * Initialize IDCT manager.
  170670. */
  170671. GLOBAL(void)
  170672. jinit_inverse_dct (j_decompress_ptr cinfo)
  170673. {
  170674. my_idct_ptr idct;
  170675. int ci;
  170676. jpeg_component_info *compptr;
  170677. idct = (my_idct_ptr)
  170678. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170679. SIZEOF(my_idct_controller));
  170680. cinfo->idct = (struct jpeg_inverse_dct *) idct;
  170681. idct->pub.start_pass = start_pass;
  170682. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  170683. ci++, compptr++) {
  170684. /* Allocate and pre-zero a multiplier table for each component */
  170685. compptr->dct_table =
  170686. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170687. SIZEOF(multiplier_table));
  170688. MEMZERO(compptr->dct_table, SIZEOF(multiplier_table));
  170689. /* Mark multiplier table not yet set up for any method */
  170690. idct->cur_method[ci] = -1;
  170691. }
  170692. }
  170693. /********* End of inlined file: jddctmgr.c *********/
  170694. #undef CONST_BITS
  170695. #undef ASSIGN_STATE
  170696. /********* Start of inlined file: jdhuff.c *********/
  170697. #define JPEG_INTERNALS
  170698. /********* Start of inlined file: jdhuff.h *********/
  170699. /* Short forms of external names for systems with brain-damaged linkers. */
  170700. #ifndef __jdhuff_h__
  170701. #define __jdhuff_h__
  170702. #ifdef NEED_SHORT_EXTERNAL_NAMES
  170703. #define jpeg_make_d_derived_tbl jMkDDerived
  170704. #define jpeg_fill_bit_buffer jFilBitBuf
  170705. #define jpeg_huff_decode jHufDecode
  170706. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  170707. /* Derived data constructed for each Huffman table */
  170708. #define HUFF_LOOKAHEAD 8 /* # of bits of lookahead */
  170709. typedef struct {
  170710. /* Basic tables: (element [0] of each array is unused) */
  170711. INT32 maxcode[18]; /* largest code of length k (-1 if none) */
  170712. /* (maxcode[17] is a sentinel to ensure jpeg_huff_decode terminates) */
  170713. INT32 valoffset[17]; /* huffval[] offset for codes of length k */
  170714. /* valoffset[k] = huffval[] index of 1st symbol of code length k, less
  170715. * the smallest code of length k; so given a code of length k, the
  170716. * corresponding symbol is huffval[code + valoffset[k]]
  170717. */
  170718. /* Link to public Huffman table (needed only in jpeg_huff_decode) */
  170719. JHUFF_TBL *pub;
  170720. /* Lookahead tables: indexed by the next HUFF_LOOKAHEAD bits of
  170721. * the input data stream. If the next Huffman code is no more
  170722. * than HUFF_LOOKAHEAD bits long, we can obtain its length and
  170723. * the corresponding symbol directly from these tables.
  170724. */
  170725. int look_nbits[1<<HUFF_LOOKAHEAD]; /* # bits, or 0 if too long */
  170726. UINT8 look_sym[1<<HUFF_LOOKAHEAD]; /* symbol, or unused */
  170727. } d_derived_tbl;
  170728. /* Expand a Huffman table definition into the derived format */
  170729. EXTERN(void) jpeg_make_d_derived_tbl
  170730. JPP((j_decompress_ptr cinfo, boolean isDC, int tblno,
  170731. d_derived_tbl ** pdtbl));
  170732. /*
  170733. * Fetching the next N bits from the input stream is a time-critical operation
  170734. * for the Huffman decoders. We implement it with a combination of inline
  170735. * macros and out-of-line subroutines. Note that N (the number of bits
  170736. * demanded at one time) never exceeds 15 for JPEG use.
  170737. *
  170738. * We read source bytes into get_buffer and dole out bits as needed.
  170739. * If get_buffer already contains enough bits, they are fetched in-line
  170740. * by the macros CHECK_BIT_BUFFER and GET_BITS. When there aren't enough
  170741. * bits, jpeg_fill_bit_buffer is called; it will attempt to fill get_buffer
  170742. * as full as possible (not just to the number of bits needed; this
  170743. * prefetching reduces the overhead cost of calling jpeg_fill_bit_buffer).
  170744. * Note that jpeg_fill_bit_buffer may return FALSE to indicate suspension.
  170745. * On TRUE return, jpeg_fill_bit_buffer guarantees that get_buffer contains
  170746. * at least the requested number of bits --- dummy zeroes are inserted if
  170747. * necessary.
  170748. */
  170749. typedef INT32 bit_buf_type; /* type of bit-extraction buffer */
  170750. #define BIT_BUF_SIZE 32 /* size of buffer in bits */
  170751. /* If long is > 32 bits on your machine, and shifting/masking longs is
  170752. * reasonably fast, making bit_buf_type be long and setting BIT_BUF_SIZE
  170753. * appropriately should be a win. Unfortunately we can't define the size
  170754. * with something like #define BIT_BUF_SIZE (sizeof(bit_buf_type)*8)
  170755. * because not all machines measure sizeof in 8-bit bytes.
  170756. */
  170757. typedef struct { /* Bitreading state saved across MCUs */
  170758. bit_buf_type get_buffer; /* current bit-extraction buffer */
  170759. int bits_left; /* # of unused bits in it */
  170760. } bitread_perm_state;
  170761. typedef struct { /* Bitreading working state within an MCU */
  170762. /* Current data source location */
  170763. /* We need a copy, rather than munging the original, in case of suspension */
  170764. const JOCTET * next_input_byte; /* => next byte to read from source */
  170765. size_t bytes_in_buffer; /* # of bytes remaining in source buffer */
  170766. /* Bit input buffer --- note these values are kept in register variables,
  170767. * not in this struct, inside the inner loops.
  170768. */
  170769. bit_buf_type get_buffer; /* current bit-extraction buffer */
  170770. int bits_left; /* # of unused bits in it */
  170771. /* Pointer needed by jpeg_fill_bit_buffer. */
  170772. j_decompress_ptr cinfo; /* back link to decompress master record */
  170773. } bitread_working_state;
  170774. /* Macros to declare and load/save bitread local variables. */
  170775. #define BITREAD_STATE_VARS \
  170776. register bit_buf_type get_buffer; \
  170777. register int bits_left; \
  170778. bitread_working_state br_state
  170779. #define BITREAD_LOAD_STATE(cinfop,permstate) \
  170780. br_state.cinfo = cinfop; \
  170781. br_state.next_input_byte = cinfop->src->next_input_byte; \
  170782. br_state.bytes_in_buffer = cinfop->src->bytes_in_buffer; \
  170783. get_buffer = permstate.get_buffer; \
  170784. bits_left = permstate.bits_left;
  170785. #define BITREAD_SAVE_STATE(cinfop,permstate) \
  170786. cinfop->src->next_input_byte = br_state.next_input_byte; \
  170787. cinfop->src->bytes_in_buffer = br_state.bytes_in_buffer; \
  170788. permstate.get_buffer = get_buffer; \
  170789. permstate.bits_left = bits_left
  170790. /*
  170791. * These macros provide the in-line portion of bit fetching.
  170792. * Use CHECK_BIT_BUFFER to ensure there are N bits in get_buffer
  170793. * before using GET_BITS, PEEK_BITS, or DROP_BITS.
  170794. * The variables get_buffer and bits_left are assumed to be locals,
  170795. * but the state struct might not be (jpeg_huff_decode needs this).
  170796. * CHECK_BIT_BUFFER(state,n,action);
  170797. * Ensure there are N bits in get_buffer; if suspend, take action.
  170798. * val = GET_BITS(n);
  170799. * Fetch next N bits.
  170800. * val = PEEK_BITS(n);
  170801. * Fetch next N bits without removing them from the buffer.
  170802. * DROP_BITS(n);
  170803. * Discard next N bits.
  170804. * The value N should be a simple variable, not an expression, because it
  170805. * is evaluated multiple times.
  170806. */
  170807. #define CHECK_BIT_BUFFER(state,nbits,action) \
  170808. { if (bits_left < (nbits)) { \
  170809. if (! jpeg_fill_bit_buffer(&(state),get_buffer,bits_left,nbits)) \
  170810. { action; } \
  170811. get_buffer = (state).get_buffer; bits_left = (state).bits_left; } }
  170812. #define GET_BITS(nbits) \
  170813. (((int) (get_buffer >> (bits_left -= (nbits)))) & ((1<<(nbits))-1))
  170814. #define PEEK_BITS(nbits) \
  170815. (((int) (get_buffer >> (bits_left - (nbits)))) & ((1<<(nbits))-1))
  170816. #define DROP_BITS(nbits) \
  170817. (bits_left -= (nbits))
  170818. /* Load up the bit buffer to a depth of at least nbits */
  170819. EXTERN(boolean) jpeg_fill_bit_buffer
  170820. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170821. register int bits_left, int nbits));
  170822. /*
  170823. * Code for extracting next Huffman-coded symbol from input bit stream.
  170824. * Again, this is time-critical and we make the main paths be macros.
  170825. *
  170826. * We use a lookahead table to process codes of up to HUFF_LOOKAHEAD bits
  170827. * without looping. Usually, more than 95% of the Huffman codes will be 8
  170828. * or fewer bits long. The few overlength codes are handled with a loop,
  170829. * which need not be inline code.
  170830. *
  170831. * Notes about the HUFF_DECODE macro:
  170832. * 1. Near the end of the data segment, we may fail to get enough bits
  170833. * for a lookahead. In that case, we do it the hard way.
  170834. * 2. If the lookahead table contains no entry, the next code must be
  170835. * more than HUFF_LOOKAHEAD bits long.
  170836. * 3. jpeg_huff_decode returns -1 if forced to suspend.
  170837. */
  170838. #define HUFF_DECODE(result,state,htbl,failaction,slowlabel) \
  170839. { register int nb, look; \
  170840. if (bits_left < HUFF_LOOKAHEAD) { \
  170841. if (! jpeg_fill_bit_buffer(&state,get_buffer,bits_left, 0)) {failaction;} \
  170842. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170843. if (bits_left < HUFF_LOOKAHEAD) { \
  170844. nb = 1; goto slowlabel; \
  170845. } \
  170846. } \
  170847. look = PEEK_BITS(HUFF_LOOKAHEAD); \
  170848. if ((nb = htbl->look_nbits[look]) != 0) { \
  170849. DROP_BITS(nb); \
  170850. result = htbl->look_sym[look]; \
  170851. } else { \
  170852. nb = HUFF_LOOKAHEAD+1; \
  170853. slowlabel: \
  170854. if ((result=jpeg_huff_decode(&state,get_buffer,bits_left,htbl,nb)) < 0) \
  170855. { failaction; } \
  170856. get_buffer = state.get_buffer; bits_left = state.bits_left; \
  170857. } \
  170858. }
  170859. /* Out-of-line case for Huffman code fetching */
  170860. EXTERN(int) jpeg_huff_decode
  170861. JPP((bitread_working_state * state, register bit_buf_type get_buffer,
  170862. register int bits_left, d_derived_tbl * htbl, int min_bits));
  170863. #endif
  170864. /********* End of inlined file: jdhuff.h *********/
  170865. /* Declarations shared with jdphuff.c */
  170866. /*
  170867. * Expanded entropy decoder object for Huffman decoding.
  170868. *
  170869. * The savable_state subrecord contains fields that change within an MCU,
  170870. * but must not be updated permanently until we complete the MCU.
  170871. */
  170872. typedef struct {
  170873. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  170874. } savable_state2;
  170875. /* This macro is to work around compilers with missing or broken
  170876. * structure assignment. You'll need to fix this code if you have
  170877. * such a compiler and you change MAX_COMPS_IN_SCAN.
  170878. */
  170879. #ifndef NO_STRUCT_ASSIGN
  170880. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  170881. #else
  170882. #if MAX_COMPS_IN_SCAN == 4
  170883. #define ASSIGN_STATE(dest,src) \
  170884. ((dest).last_dc_val[0] = (src).last_dc_val[0], \
  170885. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  170886. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  170887. (dest).last_dc_val[3] = (src).last_dc_val[3])
  170888. #endif
  170889. #endif
  170890. typedef struct {
  170891. struct jpeg_entropy_decoder pub; /* public fields */
  170892. /* These fields are loaded into local variables at start of each MCU.
  170893. * In case of suspension, we exit WITHOUT updating them.
  170894. */
  170895. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  170896. savable_state2 saved; /* Other state at start of MCU */
  170897. /* These fields are NOT loaded into local working state. */
  170898. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  170899. /* Pointers to derived tables (these workspaces have image lifespan) */
  170900. d_derived_tbl * dc_derived_tbls[NUM_HUFF_TBLS];
  170901. d_derived_tbl * ac_derived_tbls[NUM_HUFF_TBLS];
  170902. /* Precalculated info set up by start_pass for use in decode_mcu: */
  170903. /* Pointers to derived tables to be used for each block within an MCU */
  170904. d_derived_tbl * dc_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170905. d_derived_tbl * ac_cur_tbls[D_MAX_BLOCKS_IN_MCU];
  170906. /* Whether we care about the DC and AC coefficient values for each block */
  170907. boolean dc_needed[D_MAX_BLOCKS_IN_MCU];
  170908. boolean ac_needed[D_MAX_BLOCKS_IN_MCU];
  170909. } huff_entropy_decoder2;
  170910. typedef huff_entropy_decoder2 * huff_entropy_ptr2;
  170911. /*
  170912. * Initialize for a Huffman-compressed scan.
  170913. */
  170914. METHODDEF(void)
  170915. start_pass_huff_decoder (j_decompress_ptr cinfo)
  170916. {
  170917. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  170918. int ci, blkn, dctbl, actbl;
  170919. jpeg_component_info * compptr;
  170920. /* Check that the scan parameters Ss, Se, Ah/Al are OK for sequential JPEG.
  170921. * This ought to be an error condition, but we make it a warning because
  170922. * there are some baseline files out there with all zeroes in these bytes.
  170923. */
  170924. if (cinfo->Ss != 0 || cinfo->Se != DCTSIZE2-1 ||
  170925. cinfo->Ah != 0 || cinfo->Al != 0)
  170926. WARNMS(cinfo, JWRN_NOT_SEQUENTIAL);
  170927. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  170928. compptr = cinfo->cur_comp_info[ci];
  170929. dctbl = compptr->dc_tbl_no;
  170930. actbl = compptr->ac_tbl_no;
  170931. /* Compute derived values for Huffman tables */
  170932. /* We may do this more than once for a table, but it's not expensive */
  170933. jpeg_make_d_derived_tbl(cinfo, TRUE, dctbl,
  170934. & entropy->dc_derived_tbls[dctbl]);
  170935. jpeg_make_d_derived_tbl(cinfo, FALSE, actbl,
  170936. & entropy->ac_derived_tbls[actbl]);
  170937. /* Initialize DC predictions to 0 */
  170938. entropy->saved.last_dc_val[ci] = 0;
  170939. }
  170940. /* Precalculate decoding info for each block in an MCU of this scan */
  170941. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  170942. ci = cinfo->MCU_membership[blkn];
  170943. compptr = cinfo->cur_comp_info[ci];
  170944. /* Precalculate which table to use for each block */
  170945. entropy->dc_cur_tbls[blkn] = entropy->dc_derived_tbls[compptr->dc_tbl_no];
  170946. entropy->ac_cur_tbls[blkn] = entropy->ac_derived_tbls[compptr->ac_tbl_no];
  170947. /* Decide whether we really care about the coefficient values */
  170948. if (compptr->component_needed) {
  170949. entropy->dc_needed[blkn] = TRUE;
  170950. /* we don't need the ACs if producing a 1/8th-size image */
  170951. entropy->ac_needed[blkn] = (compptr->DCT_scaled_size > 1);
  170952. } else {
  170953. entropy->dc_needed[blkn] = entropy->ac_needed[blkn] = FALSE;
  170954. }
  170955. }
  170956. /* Initialize bitread state variables */
  170957. entropy->bitstate.bits_left = 0;
  170958. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  170959. entropy->pub.insufficient_data = FALSE;
  170960. /* Initialize restart counter */
  170961. entropy->restarts_to_go = cinfo->restart_interval;
  170962. }
  170963. /*
  170964. * Compute the derived values for a Huffman table.
  170965. * This routine also performs some validation checks on the table.
  170966. *
  170967. * Note this is also used by jdphuff.c.
  170968. */
  170969. GLOBAL(void)
  170970. jpeg_make_d_derived_tbl (j_decompress_ptr cinfo, boolean isDC, int tblno,
  170971. d_derived_tbl ** pdtbl)
  170972. {
  170973. JHUFF_TBL *htbl;
  170974. d_derived_tbl *dtbl;
  170975. int p, i, l, si, numsymbols;
  170976. int lookbits, ctr;
  170977. char huffsize[257];
  170978. unsigned int huffcode[257];
  170979. unsigned int code;
  170980. /* Note that huffsize[] and huffcode[] are filled in code-length order,
  170981. * paralleling the order of the symbols themselves in htbl->huffval[].
  170982. */
  170983. /* Find the input Huffman table */
  170984. if (tblno < 0 || tblno >= NUM_HUFF_TBLS)
  170985. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170986. htbl =
  170987. isDC ? cinfo->dc_huff_tbl_ptrs[tblno] : cinfo->ac_huff_tbl_ptrs[tblno];
  170988. if (htbl == NULL)
  170989. ERREXIT1(cinfo, JERR_NO_HUFF_TABLE, tblno);
  170990. /* Allocate a workspace if we haven't already done so. */
  170991. if (*pdtbl == NULL)
  170992. *pdtbl = (d_derived_tbl *)
  170993. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  170994. SIZEOF(d_derived_tbl));
  170995. dtbl = *pdtbl;
  170996. dtbl->pub = htbl; /* fill in back link */
  170997. /* Figure C.1: make table of Huffman code length for each symbol */
  170998. p = 0;
  170999. for (l = 1; l <= 16; l++) {
  171000. i = (int) htbl->bits[l];
  171001. if (i < 0 || p + i > 256) /* protect against table overrun */
  171002. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171003. while (i--)
  171004. huffsize[p++] = (char) l;
  171005. }
  171006. huffsize[p] = 0;
  171007. numsymbols = p;
  171008. /* Figure C.2: generate the codes themselves */
  171009. /* We also validate that the counts represent a legal Huffman code tree. */
  171010. code = 0;
  171011. si = huffsize[0];
  171012. p = 0;
  171013. while (huffsize[p]) {
  171014. while (((int) huffsize[p]) == si) {
  171015. huffcode[p++] = code;
  171016. code++;
  171017. }
  171018. /* code is now 1 more than the last code used for codelength si; but
  171019. * it must still fit in si bits, since no code is allowed to be all ones.
  171020. */
  171021. if (((INT32) code) >= (((INT32) 1) << si))
  171022. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171023. code <<= 1;
  171024. si++;
  171025. }
  171026. /* Figure F.15: generate decoding tables for bit-sequential decoding */
  171027. p = 0;
  171028. for (l = 1; l <= 16; l++) {
  171029. if (htbl->bits[l]) {
  171030. /* valoffset[l] = huffval[] index of 1st symbol of code length l,
  171031. * minus the minimum code of length l
  171032. */
  171033. dtbl->valoffset[l] = (INT32) p - (INT32) huffcode[p];
  171034. p += htbl->bits[l];
  171035. dtbl->maxcode[l] = huffcode[p-1]; /* maximum code of length l */
  171036. } else {
  171037. dtbl->maxcode[l] = -1; /* -1 if no codes of this length */
  171038. }
  171039. }
  171040. dtbl->maxcode[17] = 0xFFFFFL; /* ensures jpeg_huff_decode terminates */
  171041. /* Compute lookahead tables to speed up decoding.
  171042. * First we set all the table entries to 0, indicating "too long";
  171043. * then we iterate through the Huffman codes that are short enough and
  171044. * fill in all the entries that correspond to bit sequences starting
  171045. * with that code.
  171046. */
  171047. MEMZERO(dtbl->look_nbits, SIZEOF(dtbl->look_nbits));
  171048. p = 0;
  171049. for (l = 1; l <= HUFF_LOOKAHEAD; l++) {
  171050. for (i = 1; i <= (int) htbl->bits[l]; i++, p++) {
  171051. /* l = current code's length, p = its index in huffcode[] & huffval[]. */
  171052. /* Generate left-justified code followed by all possible bit sequences */
  171053. lookbits = huffcode[p] << (HUFF_LOOKAHEAD-l);
  171054. for (ctr = 1 << (HUFF_LOOKAHEAD-l); ctr > 0; ctr--) {
  171055. dtbl->look_nbits[lookbits] = l;
  171056. dtbl->look_sym[lookbits] = htbl->huffval[p];
  171057. lookbits++;
  171058. }
  171059. }
  171060. }
  171061. /* Validate symbols as being reasonable.
  171062. * For AC tables, we make no check, but accept all byte values 0..255.
  171063. * For DC tables, we require the symbols to be in range 0..15.
  171064. * (Tighter bounds could be applied depending on the data depth and mode,
  171065. * but this is sufficient to ensure safe decoding.)
  171066. */
  171067. if (isDC) {
  171068. for (i = 0; i < numsymbols; i++) {
  171069. int sym = htbl->huffval[i];
  171070. if (sym < 0 || sym > 15)
  171071. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  171072. }
  171073. }
  171074. }
  171075. /*
  171076. * Out-of-line code for bit fetching (shared with jdphuff.c).
  171077. * See jdhuff.h for info about usage.
  171078. * Note: current values of get_buffer and bits_left are passed as parameters,
  171079. * but are returned in the corresponding fields of the state struct.
  171080. *
  171081. * On most machines MIN_GET_BITS should be 25 to allow the full 32-bit width
  171082. * of get_buffer to be used. (On machines with wider words, an even larger
  171083. * buffer could be used.) However, on some machines 32-bit shifts are
  171084. * quite slow and take time proportional to the number of places shifted.
  171085. * (This is true with most PC compilers, for instance.) In this case it may
  171086. * be a win to set MIN_GET_BITS to the minimum value of 15. This reduces the
  171087. * average shift distance at the cost of more calls to jpeg_fill_bit_buffer.
  171088. */
  171089. #ifdef SLOW_SHIFT_32
  171090. #define MIN_GET_BITS 15 /* minimum allowable value */
  171091. #else
  171092. #define MIN_GET_BITS (BIT_BUF_SIZE-7)
  171093. #endif
  171094. GLOBAL(boolean)
  171095. jpeg_fill_bit_buffer (bitread_working_state * state,
  171096. register bit_buf_type get_buffer, register int bits_left,
  171097. int nbits)
  171098. /* Load up the bit buffer to a depth of at least nbits */
  171099. {
  171100. /* Copy heavily used state fields into locals (hopefully registers) */
  171101. register const JOCTET * next_input_byte = state->next_input_byte;
  171102. register size_t bytes_in_buffer = state->bytes_in_buffer;
  171103. j_decompress_ptr cinfo = state->cinfo;
  171104. /* Attempt to load at least MIN_GET_BITS bits into get_buffer. */
  171105. /* (It is assumed that no request will be for more than that many bits.) */
  171106. /* We fail to do so only if we hit a marker or are forced to suspend. */
  171107. if (cinfo->unread_marker == 0) { /* cannot advance past a marker */
  171108. while (bits_left < MIN_GET_BITS) {
  171109. register int c;
  171110. /* Attempt to read a byte */
  171111. if (bytes_in_buffer == 0) {
  171112. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  171113. return FALSE;
  171114. next_input_byte = cinfo->src->next_input_byte;
  171115. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  171116. }
  171117. bytes_in_buffer--;
  171118. c = GETJOCTET(*next_input_byte++);
  171119. /* If it's 0xFF, check and discard stuffed zero byte */
  171120. if (c == 0xFF) {
  171121. /* Loop here to discard any padding FF's on terminating marker,
  171122. * so that we can save a valid unread_marker value. NOTE: we will
  171123. * accept multiple FF's followed by a 0 as meaning a single FF data
  171124. * byte. This data pattern is not valid according to the standard.
  171125. */
  171126. do {
  171127. if (bytes_in_buffer == 0) {
  171128. if (! (*cinfo->src->fill_input_buffer) (cinfo))
  171129. return FALSE;
  171130. next_input_byte = cinfo->src->next_input_byte;
  171131. bytes_in_buffer = cinfo->src->bytes_in_buffer;
  171132. }
  171133. bytes_in_buffer--;
  171134. c = GETJOCTET(*next_input_byte++);
  171135. } while (c == 0xFF);
  171136. if (c == 0) {
  171137. /* Found FF/00, which represents an FF data byte */
  171138. c = 0xFF;
  171139. } else {
  171140. /* Oops, it's actually a marker indicating end of compressed data.
  171141. * Save the marker code for later use.
  171142. * Fine point: it might appear that we should save the marker into
  171143. * bitread working state, not straight into permanent state. But
  171144. * once we have hit a marker, we cannot need to suspend within the
  171145. * current MCU, because we will read no more bytes from the data
  171146. * source. So it is OK to update permanent state right away.
  171147. */
  171148. cinfo->unread_marker = c;
  171149. /* See if we need to insert some fake zero bits. */
  171150. goto no_more_bytes;
  171151. }
  171152. }
  171153. /* OK, load c into get_buffer */
  171154. get_buffer = (get_buffer << 8) | c;
  171155. bits_left += 8;
  171156. } /* end while */
  171157. } else {
  171158. no_more_bytes:
  171159. /* We get here if we've read the marker that terminates the compressed
  171160. * data segment. There should be enough bits in the buffer register
  171161. * to satisfy the request; if so, no problem.
  171162. */
  171163. if (nbits > bits_left) {
  171164. /* Uh-oh. Report corrupted data to user and stuff zeroes into
  171165. * the data stream, so that we can produce some kind of image.
  171166. * We use a nonvolatile flag to ensure that only one warning message
  171167. * appears per data segment.
  171168. */
  171169. if (! cinfo->entropy->insufficient_data) {
  171170. WARNMS(cinfo, JWRN_HIT_MARKER);
  171171. cinfo->entropy->insufficient_data = TRUE;
  171172. }
  171173. /* Fill the buffer with zero bits */
  171174. get_buffer <<= MIN_GET_BITS - bits_left;
  171175. bits_left = MIN_GET_BITS;
  171176. }
  171177. }
  171178. /* Unload the local registers */
  171179. state->next_input_byte = next_input_byte;
  171180. state->bytes_in_buffer = bytes_in_buffer;
  171181. state->get_buffer = get_buffer;
  171182. state->bits_left = bits_left;
  171183. return TRUE;
  171184. }
  171185. /*
  171186. * Out-of-line code for Huffman code decoding.
  171187. * See jdhuff.h for info about usage.
  171188. */
  171189. GLOBAL(int)
  171190. jpeg_huff_decode (bitread_working_state * state,
  171191. register bit_buf_type get_buffer, register int bits_left,
  171192. d_derived_tbl * htbl, int min_bits)
  171193. {
  171194. register int l = min_bits;
  171195. register INT32 code;
  171196. /* HUFF_DECODE has determined that the code is at least min_bits */
  171197. /* bits long, so fetch that many bits in one swoop. */
  171198. CHECK_BIT_BUFFER(*state, l, return -1);
  171199. code = GET_BITS(l);
  171200. /* Collect the rest of the Huffman code one bit at a time. */
  171201. /* This is per Figure F.16 in the JPEG spec. */
  171202. while (code > htbl->maxcode[l]) {
  171203. code <<= 1;
  171204. CHECK_BIT_BUFFER(*state, 1, return -1);
  171205. code |= GET_BITS(1);
  171206. l++;
  171207. }
  171208. /* Unload the local registers */
  171209. state->get_buffer = get_buffer;
  171210. state->bits_left = bits_left;
  171211. /* With garbage input we may reach the sentinel value l = 17. */
  171212. if (l > 16) {
  171213. WARNMS(state->cinfo, JWRN_HUFF_BAD_CODE);
  171214. return 0; /* fake a zero as the safest result */
  171215. }
  171216. return htbl->pub->huffval[ (int) (code + htbl->valoffset[l]) ];
  171217. }
  171218. /*
  171219. * Check for a restart marker & resynchronize decoder.
  171220. * Returns FALSE if must suspend.
  171221. */
  171222. LOCAL(boolean)
  171223. process_restart (j_decompress_ptr cinfo)
  171224. {
  171225. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  171226. int ci;
  171227. /* Throw away any unused bits remaining in bit buffer; */
  171228. /* include any full bytes in next_marker's count of discarded bytes */
  171229. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  171230. entropy->bitstate.bits_left = 0;
  171231. /* Advance past the RSTn marker */
  171232. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  171233. return FALSE;
  171234. /* Re-initialize DC predictions to 0 */
  171235. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  171236. entropy->saved.last_dc_val[ci] = 0;
  171237. /* Reset restart counter */
  171238. entropy->restarts_to_go = cinfo->restart_interval;
  171239. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  171240. * against a marker. In that case we will end up treating the next data
  171241. * segment as empty, and we can avoid producing bogus output pixels by
  171242. * leaving the flag set.
  171243. */
  171244. if (cinfo->unread_marker == 0)
  171245. entropy->pub.insufficient_data = FALSE;
  171246. return TRUE;
  171247. }
  171248. /*
  171249. * Decode and return one MCU's worth of Huffman-compressed coefficients.
  171250. * The coefficients are reordered from zigzag order into natural array order,
  171251. * but are not dequantized.
  171252. *
  171253. * The i'th block of the MCU is stored into the block pointed to by
  171254. * MCU_data[i]. WE ASSUME THIS AREA HAS BEEN ZEROED BY THE CALLER.
  171255. * (Wholesale zeroing is usually a little faster than retail...)
  171256. *
  171257. * Returns FALSE if data source requested suspension. In that case no
  171258. * changes have been made to permanent state. (Exception: some output
  171259. * coefficients may already have been assigned. This is harmless for
  171260. * this module, since we'll just re-assign them on the next call.)
  171261. */
  171262. METHODDEF(boolean)
  171263. decode_mcu (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  171264. {
  171265. huff_entropy_ptr2 entropy = (huff_entropy_ptr2) cinfo->entropy;
  171266. int blkn;
  171267. BITREAD_STATE_VARS;
  171268. savable_state2 state;
  171269. /* Process restart marker if needed; may have to suspend */
  171270. if (cinfo->restart_interval) {
  171271. if (entropy->restarts_to_go == 0)
  171272. if (! process_restart(cinfo))
  171273. return FALSE;
  171274. }
  171275. /* If we've run out of data, just leave the MCU set to zeroes.
  171276. * This way, we return uniform gray for the remainder of the segment.
  171277. */
  171278. if (! entropy->pub.insufficient_data) {
  171279. /* Load up working state */
  171280. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  171281. ASSIGN_STATE(state, entropy->saved);
  171282. /* Outer loop handles each block in the MCU */
  171283. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  171284. JBLOCKROW block = MCU_data[blkn];
  171285. d_derived_tbl * dctbl = entropy->dc_cur_tbls[blkn];
  171286. d_derived_tbl * actbl = entropy->ac_cur_tbls[blkn];
  171287. register int s, k, r;
  171288. /* Decode a single block's worth of coefficients */
  171289. /* Section F.2.2.1: decode the DC coefficient difference */
  171290. HUFF_DECODE(s, br_state, dctbl, return FALSE, label1);
  171291. if (s) {
  171292. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  171293. r = GET_BITS(s);
  171294. s = HUFF_EXTEND(r, s);
  171295. }
  171296. if (entropy->dc_needed[blkn]) {
  171297. /* Convert DC difference to actual value, update last_dc_val */
  171298. int ci = cinfo->MCU_membership[blkn];
  171299. s += state.last_dc_val[ci];
  171300. state.last_dc_val[ci] = s;
  171301. /* Output the DC coefficient (assumes jpeg_natural_order[0] = 0) */
  171302. (*block)[0] = (JCOEF) s;
  171303. }
  171304. if (entropy->ac_needed[blkn]) {
  171305. /* Section F.2.2.2: decode the AC coefficients */
  171306. /* Since zeroes are skipped, output area must be cleared beforehand */
  171307. for (k = 1; k < DCTSIZE2; k++) {
  171308. HUFF_DECODE(s, br_state, actbl, return FALSE, label2);
  171309. r = s >> 4;
  171310. s &= 15;
  171311. if (s) {
  171312. k += r;
  171313. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  171314. r = GET_BITS(s);
  171315. s = HUFF_EXTEND(r, s);
  171316. /* Output coefficient in natural (dezigzagged) order.
  171317. * Note: the extra entries in jpeg_natural_order[] will save us
  171318. * if k >= DCTSIZE2, which could happen if the data is corrupted.
  171319. */
  171320. (*block)[jpeg_natural_order[k]] = (JCOEF) s;
  171321. } else {
  171322. if (r != 15)
  171323. break;
  171324. k += 15;
  171325. }
  171326. }
  171327. } else {
  171328. /* Section F.2.2.2: decode the AC coefficients */
  171329. /* In this path we just discard the values */
  171330. for (k = 1; k < DCTSIZE2; k++) {
  171331. HUFF_DECODE(s, br_state, actbl, return FALSE, label3);
  171332. r = s >> 4;
  171333. s &= 15;
  171334. if (s) {
  171335. k += r;
  171336. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  171337. DROP_BITS(s);
  171338. } else {
  171339. if (r != 15)
  171340. break;
  171341. k += 15;
  171342. }
  171343. }
  171344. }
  171345. }
  171346. /* Completed MCU, so update state */
  171347. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  171348. ASSIGN_STATE(entropy->saved, state);
  171349. }
  171350. /* Account for restart interval (no-op if not using restarts) */
  171351. entropy->restarts_to_go--;
  171352. return TRUE;
  171353. }
  171354. /*
  171355. * Module initialization routine for Huffman entropy decoding.
  171356. */
  171357. GLOBAL(void)
  171358. jinit_huff_decoder (j_decompress_ptr cinfo)
  171359. {
  171360. huff_entropy_ptr2 entropy;
  171361. int i;
  171362. entropy = (huff_entropy_ptr2)
  171363. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171364. SIZEOF(huff_entropy_decoder2));
  171365. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  171366. entropy->pub.start_pass = start_pass_huff_decoder;
  171367. entropy->pub.decode_mcu = decode_mcu;
  171368. /* Mark tables unallocated */
  171369. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  171370. entropy->dc_derived_tbls[i] = entropy->ac_derived_tbls[i] = NULL;
  171371. }
  171372. }
  171373. /********* End of inlined file: jdhuff.c *********/
  171374. /********* Start of inlined file: jdinput.c *********/
  171375. #define JPEG_INTERNALS
  171376. /* Private state */
  171377. typedef struct {
  171378. struct jpeg_input_controller pub; /* public fields */
  171379. boolean inheaders; /* TRUE until first SOS is reached */
  171380. } my_input_controller;
  171381. typedef my_input_controller * my_inputctl_ptr;
  171382. /* Forward declarations */
  171383. METHODDEF(int) consume_markers JPP((j_decompress_ptr cinfo));
  171384. /*
  171385. * Routines to calculate various quantities related to the size of the image.
  171386. */
  171387. LOCAL(void)
  171388. initial_setup2 (j_decompress_ptr cinfo)
  171389. /* Called once, when first SOS marker is reached */
  171390. {
  171391. int ci;
  171392. jpeg_component_info *compptr;
  171393. /* Make sure image isn't bigger than I can handle */
  171394. if ((long) cinfo->image_height > (long) JPEG_MAX_DIMENSION ||
  171395. (long) cinfo->image_width > (long) JPEG_MAX_DIMENSION)
  171396. ERREXIT1(cinfo, JERR_IMAGE_TOO_BIG, (unsigned int) JPEG_MAX_DIMENSION);
  171397. /* For now, precision must match compiled-in value... */
  171398. if (cinfo->data_precision != BITS_IN_JSAMPLE)
  171399. ERREXIT1(cinfo, JERR_BAD_PRECISION, cinfo->data_precision);
  171400. /* Check that number of components won't exceed internal array sizes */
  171401. if (cinfo->num_components > MAX_COMPONENTS)
  171402. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->num_components,
  171403. MAX_COMPONENTS);
  171404. /* Compute maximum sampling factors; check factor validity */
  171405. cinfo->max_h_samp_factor = 1;
  171406. cinfo->max_v_samp_factor = 1;
  171407. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171408. ci++, compptr++) {
  171409. if (compptr->h_samp_factor<=0 || compptr->h_samp_factor>MAX_SAMP_FACTOR ||
  171410. compptr->v_samp_factor<=0 || compptr->v_samp_factor>MAX_SAMP_FACTOR)
  171411. ERREXIT(cinfo, JERR_BAD_SAMPLING);
  171412. cinfo->max_h_samp_factor = MAX(cinfo->max_h_samp_factor,
  171413. compptr->h_samp_factor);
  171414. cinfo->max_v_samp_factor = MAX(cinfo->max_v_samp_factor,
  171415. compptr->v_samp_factor);
  171416. }
  171417. /* We initialize DCT_scaled_size and min_DCT_scaled_size to DCTSIZE.
  171418. * In the full decompressor, this will be overridden by jdmaster.c;
  171419. * but in the transcoder, jdmaster.c is not used, so we must do it here.
  171420. */
  171421. cinfo->min_DCT_scaled_size = DCTSIZE;
  171422. /* Compute dimensions of components */
  171423. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171424. ci++, compptr++) {
  171425. compptr->DCT_scaled_size = DCTSIZE;
  171426. /* Size in DCT blocks */
  171427. compptr->width_in_blocks = (JDIMENSION)
  171428. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  171429. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  171430. compptr->height_in_blocks = (JDIMENSION)
  171431. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  171432. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  171433. /* downsampled_width and downsampled_height will also be overridden by
  171434. * jdmaster.c if we are doing full decompression. The transcoder library
  171435. * doesn't use these values, but the calling application might.
  171436. */
  171437. /* Size in samples */
  171438. compptr->downsampled_width = (JDIMENSION)
  171439. jdiv_round_up((long) cinfo->image_width * (long) compptr->h_samp_factor,
  171440. (long) cinfo->max_h_samp_factor);
  171441. compptr->downsampled_height = (JDIMENSION)
  171442. jdiv_round_up((long) cinfo->image_height * (long) compptr->v_samp_factor,
  171443. (long) cinfo->max_v_samp_factor);
  171444. /* Mark component needed, until color conversion says otherwise */
  171445. compptr->component_needed = TRUE;
  171446. /* Mark no quantization table yet saved for component */
  171447. compptr->quant_table = NULL;
  171448. }
  171449. /* Compute number of fully interleaved MCU rows. */
  171450. cinfo->total_iMCU_rows = (JDIMENSION)
  171451. jdiv_round_up((long) cinfo->image_height,
  171452. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  171453. /* Decide whether file contains multiple scans */
  171454. if (cinfo->comps_in_scan < cinfo->num_components || cinfo->progressive_mode)
  171455. cinfo->inputctl->has_multiple_scans = TRUE;
  171456. else
  171457. cinfo->inputctl->has_multiple_scans = FALSE;
  171458. }
  171459. LOCAL(void)
  171460. per_scan_setup2 (j_decompress_ptr cinfo)
  171461. /* Do computations that are needed before processing a JPEG scan */
  171462. /* cinfo->comps_in_scan and cinfo->cur_comp_info[] were set from SOS marker */
  171463. {
  171464. int ci, mcublks, tmp;
  171465. jpeg_component_info *compptr;
  171466. if (cinfo->comps_in_scan == 1) {
  171467. /* Noninterleaved (single-component) scan */
  171468. compptr = cinfo->cur_comp_info[0];
  171469. /* Overall image size in MCUs */
  171470. cinfo->MCUs_per_row = compptr->width_in_blocks;
  171471. cinfo->MCU_rows_in_scan = compptr->height_in_blocks;
  171472. /* For noninterleaved scan, always one block per MCU */
  171473. compptr->MCU_width = 1;
  171474. compptr->MCU_height = 1;
  171475. compptr->MCU_blocks = 1;
  171476. compptr->MCU_sample_width = compptr->DCT_scaled_size;
  171477. compptr->last_col_width = 1;
  171478. /* For noninterleaved scans, it is convenient to define last_row_height
  171479. * as the number of block rows present in the last iMCU row.
  171480. */
  171481. tmp = (int) (compptr->height_in_blocks % compptr->v_samp_factor);
  171482. if (tmp == 0) tmp = compptr->v_samp_factor;
  171483. compptr->last_row_height = tmp;
  171484. /* Prepare array describing MCU composition */
  171485. cinfo->blocks_in_MCU = 1;
  171486. cinfo->MCU_membership[0] = 0;
  171487. } else {
  171488. /* Interleaved (multi-component) scan */
  171489. if (cinfo->comps_in_scan <= 0 || cinfo->comps_in_scan > MAX_COMPS_IN_SCAN)
  171490. ERREXIT2(cinfo, JERR_COMPONENT_COUNT, cinfo->comps_in_scan,
  171491. MAX_COMPS_IN_SCAN);
  171492. /* Overall image size in MCUs */
  171493. cinfo->MCUs_per_row = (JDIMENSION)
  171494. jdiv_round_up((long) cinfo->image_width,
  171495. (long) (cinfo->max_h_samp_factor*DCTSIZE));
  171496. cinfo->MCU_rows_in_scan = (JDIMENSION)
  171497. jdiv_round_up((long) cinfo->image_height,
  171498. (long) (cinfo->max_v_samp_factor*DCTSIZE));
  171499. cinfo->blocks_in_MCU = 0;
  171500. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  171501. compptr = cinfo->cur_comp_info[ci];
  171502. /* Sampling factors give # of blocks of component in each MCU */
  171503. compptr->MCU_width = compptr->h_samp_factor;
  171504. compptr->MCU_height = compptr->v_samp_factor;
  171505. compptr->MCU_blocks = compptr->MCU_width * compptr->MCU_height;
  171506. compptr->MCU_sample_width = compptr->MCU_width * compptr->DCT_scaled_size;
  171507. /* Figure number of non-dummy blocks in last MCU column & row */
  171508. tmp = (int) (compptr->width_in_blocks % compptr->MCU_width);
  171509. if (tmp == 0) tmp = compptr->MCU_width;
  171510. compptr->last_col_width = tmp;
  171511. tmp = (int) (compptr->height_in_blocks % compptr->MCU_height);
  171512. if (tmp == 0) tmp = compptr->MCU_height;
  171513. compptr->last_row_height = tmp;
  171514. /* Prepare array describing MCU composition */
  171515. mcublks = compptr->MCU_blocks;
  171516. if (cinfo->blocks_in_MCU + mcublks > D_MAX_BLOCKS_IN_MCU)
  171517. ERREXIT(cinfo, JERR_BAD_MCU_SIZE);
  171518. while (mcublks-- > 0) {
  171519. cinfo->MCU_membership[cinfo->blocks_in_MCU++] = ci;
  171520. }
  171521. }
  171522. }
  171523. }
  171524. /*
  171525. * Save away a copy of the Q-table referenced by each component present
  171526. * in the current scan, unless already saved during a prior scan.
  171527. *
  171528. * In a multiple-scan JPEG file, the encoder could assign different components
  171529. * the same Q-table slot number, but change table definitions between scans
  171530. * so that each component uses a different Q-table. (The IJG encoder is not
  171531. * currently capable of doing this, but other encoders might.) Since we want
  171532. * to be able to dequantize all the components at the end of the file, this
  171533. * means that we have to save away the table actually used for each component.
  171534. * We do this by copying the table at the start of the first scan containing
  171535. * the component.
  171536. * The JPEG spec prohibits the encoder from changing the contents of a Q-table
  171537. * slot between scans of a component using that slot. If the encoder does so
  171538. * anyway, this decoder will simply use the Q-table values that were current
  171539. * at the start of the first scan for the component.
  171540. *
  171541. * The decompressor output side looks only at the saved quant tables,
  171542. * not at the current Q-table slots.
  171543. */
  171544. LOCAL(void)
  171545. latch_quant_tables (j_decompress_ptr cinfo)
  171546. {
  171547. int ci, qtblno;
  171548. jpeg_component_info *compptr;
  171549. JQUANT_TBL * qtbl;
  171550. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  171551. compptr = cinfo->cur_comp_info[ci];
  171552. /* No work if we already saved Q-table for this component */
  171553. if (compptr->quant_table != NULL)
  171554. continue;
  171555. /* Make sure specified quantization table is present */
  171556. qtblno = compptr->quant_tbl_no;
  171557. if (qtblno < 0 || qtblno >= NUM_QUANT_TBLS ||
  171558. cinfo->quant_tbl_ptrs[qtblno] == NULL)
  171559. ERREXIT1(cinfo, JERR_NO_QUANT_TABLE, qtblno);
  171560. /* OK, save away the quantization table */
  171561. qtbl = (JQUANT_TBL *)
  171562. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171563. SIZEOF(JQUANT_TBL));
  171564. MEMCOPY(qtbl, cinfo->quant_tbl_ptrs[qtblno], SIZEOF(JQUANT_TBL));
  171565. compptr->quant_table = qtbl;
  171566. }
  171567. }
  171568. /*
  171569. * Initialize the input modules to read a scan of compressed data.
  171570. * The first call to this is done by jdmaster.c after initializing
  171571. * the entire decompressor (during jpeg_start_decompress).
  171572. * Subsequent calls come from consume_markers, below.
  171573. */
  171574. METHODDEF(void)
  171575. start_input_pass2 (j_decompress_ptr cinfo)
  171576. {
  171577. per_scan_setup2(cinfo);
  171578. latch_quant_tables(cinfo);
  171579. (*cinfo->entropy->start_pass) (cinfo);
  171580. (*cinfo->coef->start_input_pass) (cinfo);
  171581. cinfo->inputctl->consume_input = cinfo->coef->consume_data;
  171582. }
  171583. /*
  171584. * Finish up after inputting a compressed-data scan.
  171585. * This is called by the coefficient controller after it's read all
  171586. * the expected data of the scan.
  171587. */
  171588. METHODDEF(void)
  171589. finish_input_pass (j_decompress_ptr cinfo)
  171590. {
  171591. cinfo->inputctl->consume_input = consume_markers;
  171592. }
  171593. /*
  171594. * Read JPEG markers before, between, or after compressed-data scans.
  171595. * Change state as necessary when a new scan is reached.
  171596. * Return value is JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  171597. *
  171598. * The consume_input method pointer points either here or to the
  171599. * coefficient controller's consume_data routine, depending on whether
  171600. * we are reading a compressed data segment or inter-segment markers.
  171601. */
  171602. METHODDEF(int)
  171603. consume_markers (j_decompress_ptr cinfo)
  171604. {
  171605. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  171606. int val;
  171607. if (inputctl->pub.eoi_reached) /* After hitting EOI, read no further */
  171608. return JPEG_REACHED_EOI;
  171609. val = (*cinfo->marker->read_markers) (cinfo);
  171610. switch (val) {
  171611. case JPEG_REACHED_SOS: /* Found SOS */
  171612. if (inputctl->inheaders) { /* 1st SOS */
  171613. initial_setup2(cinfo);
  171614. inputctl->inheaders = FALSE;
  171615. /* Note: start_input_pass must be called by jdmaster.c
  171616. * before any more input can be consumed. jdapimin.c is
  171617. * responsible for enforcing this sequencing.
  171618. */
  171619. } else { /* 2nd or later SOS marker */
  171620. if (! inputctl->pub.has_multiple_scans)
  171621. ERREXIT(cinfo, JERR_EOI_EXPECTED); /* Oops, I wasn't expecting this! */
  171622. start_input_pass2(cinfo);
  171623. }
  171624. break;
  171625. case JPEG_REACHED_EOI: /* Found EOI */
  171626. inputctl->pub.eoi_reached = TRUE;
  171627. if (inputctl->inheaders) { /* Tables-only datastream, apparently */
  171628. if (cinfo->marker->saw_SOF)
  171629. ERREXIT(cinfo, JERR_SOF_NO_SOS);
  171630. } else {
  171631. /* Prevent infinite loop in coef ctlr's decompress_data routine
  171632. * if user set output_scan_number larger than number of scans.
  171633. */
  171634. if (cinfo->output_scan_number > cinfo->input_scan_number)
  171635. cinfo->output_scan_number = cinfo->input_scan_number;
  171636. }
  171637. break;
  171638. case JPEG_SUSPENDED:
  171639. break;
  171640. }
  171641. return val;
  171642. }
  171643. /*
  171644. * Reset state to begin a fresh datastream.
  171645. */
  171646. METHODDEF(void)
  171647. reset_input_controller (j_decompress_ptr cinfo)
  171648. {
  171649. my_inputctl_ptr inputctl = (my_inputctl_ptr) cinfo->inputctl;
  171650. inputctl->pub.consume_input = consume_markers;
  171651. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  171652. inputctl->pub.eoi_reached = FALSE;
  171653. inputctl->inheaders = TRUE;
  171654. /* Reset other modules */
  171655. (*cinfo->err->reset_error_mgr) ((j_common_ptr) cinfo);
  171656. (*cinfo->marker->reset_marker_reader) (cinfo);
  171657. /* Reset progression state -- would be cleaner if entropy decoder did this */
  171658. cinfo->coef_bits = NULL;
  171659. }
  171660. /*
  171661. * Initialize the input controller module.
  171662. * This is called only once, when the decompression object is created.
  171663. */
  171664. GLOBAL(void)
  171665. jinit_input_controller (j_decompress_ptr cinfo)
  171666. {
  171667. my_inputctl_ptr inputctl;
  171668. /* Create subobject in permanent pool */
  171669. inputctl = (my_inputctl_ptr)
  171670. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  171671. SIZEOF(my_input_controller));
  171672. cinfo->inputctl = (struct jpeg_input_controller *) inputctl;
  171673. /* Initialize method pointers */
  171674. inputctl->pub.consume_input = consume_markers;
  171675. inputctl->pub.reset_input_controller = reset_input_controller;
  171676. inputctl->pub.start_input_pass = start_input_pass2;
  171677. inputctl->pub.finish_input_pass = finish_input_pass;
  171678. /* Initialize state: can't use reset_input_controller since we don't
  171679. * want to try to reset other modules yet.
  171680. */
  171681. inputctl->pub.has_multiple_scans = FALSE; /* "unknown" would be better */
  171682. inputctl->pub.eoi_reached = FALSE;
  171683. inputctl->inheaders = TRUE;
  171684. }
  171685. /********* End of inlined file: jdinput.c *********/
  171686. /********* Start of inlined file: jdmainct.c *********/
  171687. #define JPEG_INTERNALS
  171688. /*
  171689. * In the current system design, the main buffer need never be a full-image
  171690. * buffer; any full-height buffers will be found inside the coefficient or
  171691. * postprocessing controllers. Nonetheless, the main controller is not
  171692. * trivial. Its responsibility is to provide context rows for upsampling/
  171693. * rescaling, and doing this in an efficient fashion is a bit tricky.
  171694. *
  171695. * Postprocessor input data is counted in "row groups". A row group
  171696. * is defined to be (v_samp_factor * DCT_scaled_size / min_DCT_scaled_size)
  171697. * sample rows of each component. (We require DCT_scaled_size values to be
  171698. * chosen such that these numbers are integers. In practice DCT_scaled_size
  171699. * values will likely be powers of two, so we actually have the stronger
  171700. * condition that DCT_scaled_size / min_DCT_scaled_size is an integer.)
  171701. * Upsampling will typically produce max_v_samp_factor pixel rows from each
  171702. * row group (times any additional scale factor that the upsampler is
  171703. * applying).
  171704. *
  171705. * The coefficient controller will deliver data to us one iMCU row at a time;
  171706. * each iMCU row contains v_samp_factor * DCT_scaled_size sample rows, or
  171707. * exactly min_DCT_scaled_size row groups. (This amount of data corresponds
  171708. * to one row of MCUs when the image is fully interleaved.) Note that the
  171709. * number of sample rows varies across components, but the number of row
  171710. * groups does not. Some garbage sample rows may be included in the last iMCU
  171711. * row at the bottom of the image.
  171712. *
  171713. * Depending on the vertical scaling algorithm used, the upsampler may need
  171714. * access to the sample row(s) above and below its current input row group.
  171715. * The upsampler is required to set need_context_rows TRUE at global selection
  171716. * time if so. When need_context_rows is FALSE, this controller can simply
  171717. * obtain one iMCU row at a time from the coefficient controller and dole it
  171718. * out as row groups to the postprocessor.
  171719. *
  171720. * When need_context_rows is TRUE, this controller guarantees that the buffer
  171721. * passed to postprocessing contains at least one row group's worth of samples
  171722. * above and below the row group(s) being processed. Note that the context
  171723. * rows "above" the first passed row group appear at negative row offsets in
  171724. * the passed buffer. At the top and bottom of the image, the required
  171725. * context rows are manufactured by duplicating the first or last real sample
  171726. * row; this avoids having special cases in the upsampling inner loops.
  171727. *
  171728. * The amount of context is fixed at one row group just because that's a
  171729. * convenient number for this controller to work with. The existing
  171730. * upsamplers really only need one sample row of context. An upsampler
  171731. * supporting arbitrary output rescaling might wish for more than one row
  171732. * group of context when shrinking the image; tough, we don't handle that.
  171733. * (This is justified by the assumption that downsizing will be handled mostly
  171734. * by adjusting the DCT_scaled_size values, so that the actual scale factor at
  171735. * the upsample step needn't be much less than one.)
  171736. *
  171737. * To provide the desired context, we have to retain the last two row groups
  171738. * of one iMCU row while reading in the next iMCU row. (The last row group
  171739. * can't be processed until we have another row group for its below-context,
  171740. * and so we have to save the next-to-last group too for its above-context.)
  171741. * We could do this most simply by copying data around in our buffer, but
  171742. * that'd be very slow. We can avoid copying any data by creating a rather
  171743. * strange pointer structure. Here's how it works. We allocate a workspace
  171744. * consisting of M+2 row groups (where M = min_DCT_scaled_size is the number
  171745. * of row groups per iMCU row). We create two sets of redundant pointers to
  171746. * the workspace. Labeling the physical row groups 0 to M+1, the synthesized
  171747. * pointer lists look like this:
  171748. * M+1 M-1
  171749. * master pointer --> 0 master pointer --> 0
  171750. * 1 1
  171751. * ... ...
  171752. * M-3 M-3
  171753. * M-2 M
  171754. * M-1 M+1
  171755. * M M-2
  171756. * M+1 M-1
  171757. * 0 0
  171758. * We read alternate iMCU rows using each master pointer; thus the last two
  171759. * row groups of the previous iMCU row remain un-overwritten in the workspace.
  171760. * The pointer lists are set up so that the required context rows appear to
  171761. * be adjacent to the proper places when we pass the pointer lists to the
  171762. * upsampler.
  171763. *
  171764. * The above pictures describe the normal state of the pointer lists.
  171765. * At top and bottom of the image, we diddle the pointer lists to duplicate
  171766. * the first or last sample row as necessary (this is cheaper than copying
  171767. * sample rows around).
  171768. *
  171769. * This scheme breaks down if M < 2, ie, min_DCT_scaled_size is 1. In that
  171770. * situation each iMCU row provides only one row group so the buffering logic
  171771. * must be different (eg, we must read two iMCU rows before we can emit the
  171772. * first row group). For now, we simply do not support providing context
  171773. * rows when min_DCT_scaled_size is 1. That combination seems unlikely to
  171774. * be worth providing --- if someone wants a 1/8th-size preview, they probably
  171775. * want it quick and dirty, so a context-free upsampler is sufficient.
  171776. */
  171777. /* Private buffer controller object */
  171778. typedef struct {
  171779. struct jpeg_d_main_controller pub; /* public fields */
  171780. /* Pointer to allocated workspace (M or M+2 row groups). */
  171781. JSAMPARRAY buffer[MAX_COMPONENTS];
  171782. boolean buffer_full; /* Have we gotten an iMCU row from decoder? */
  171783. JDIMENSION rowgroup_ctr; /* counts row groups output to postprocessor */
  171784. /* Remaining fields are only used in the context case. */
  171785. /* These are the master pointers to the funny-order pointer lists. */
  171786. JSAMPIMAGE xbuffer[2]; /* pointers to weird pointer lists */
  171787. int whichptr; /* indicates which pointer set is now in use */
  171788. int context_state; /* process_data state machine status */
  171789. JDIMENSION rowgroups_avail; /* row groups available to postprocessor */
  171790. JDIMENSION iMCU_row_ctr; /* counts iMCU rows to detect image top/bot */
  171791. } my_main_controller4;
  171792. typedef my_main_controller4 * my_main_ptr4;
  171793. /* context_state values: */
  171794. #define CTX_PREPARE_FOR_IMCU 0 /* need to prepare for MCU row */
  171795. #define CTX_PROCESS_IMCU 1 /* feeding iMCU to postprocessor */
  171796. #define CTX_POSTPONED_ROW 2 /* feeding postponed row group */
  171797. /* Forward declarations */
  171798. METHODDEF(void) process_data_simple_main2
  171799. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171800. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171801. METHODDEF(void) process_data_context_main
  171802. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171803. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171804. #ifdef QUANT_2PASS_SUPPORTED
  171805. METHODDEF(void) process_data_crank_post
  171806. JPP((j_decompress_ptr cinfo, JSAMPARRAY output_buf,
  171807. JDIMENSION *out_row_ctr, JDIMENSION out_rows_avail));
  171808. #endif
  171809. LOCAL(void)
  171810. alloc_funny_pointers (j_decompress_ptr cinfo)
  171811. /* Allocate space for the funny pointer lists.
  171812. * This is done only once, not once per pass.
  171813. */
  171814. {
  171815. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171816. int ci, rgroup;
  171817. int M = cinfo->min_DCT_scaled_size;
  171818. jpeg_component_info *compptr;
  171819. JSAMPARRAY xbuf;
  171820. /* Get top-level space for component array pointers.
  171821. * We alloc both arrays with one call to save a few cycles.
  171822. */
  171823. main_->xbuffer[0] = (JSAMPIMAGE)
  171824. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171825. cinfo->num_components * 2 * SIZEOF(JSAMPARRAY));
  171826. main_->xbuffer[1] = main_->xbuffer[0] + cinfo->num_components;
  171827. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171828. ci++, compptr++) {
  171829. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171830. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171831. /* Get space for pointer lists --- M+4 row groups in each list.
  171832. * We alloc both pointer lists with one call to save a few cycles.
  171833. */
  171834. xbuf = (JSAMPARRAY)
  171835. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  171836. 2 * (rgroup * (M + 4)) * SIZEOF(JSAMPROW));
  171837. xbuf += rgroup; /* want one row group at negative offsets */
  171838. main_->xbuffer[0][ci] = xbuf;
  171839. xbuf += rgroup * (M + 4);
  171840. main_->xbuffer[1][ci] = xbuf;
  171841. }
  171842. }
  171843. LOCAL(void)
  171844. make_funny_pointers (j_decompress_ptr cinfo)
  171845. /* Create the funny pointer lists discussed in the comments above.
  171846. * The actual workspace is already allocated (in main->buffer),
  171847. * and the space for the pointer lists is allocated too.
  171848. * This routine just fills in the curiously ordered lists.
  171849. * This will be repeated at the beginning of each pass.
  171850. */
  171851. {
  171852. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171853. int ci, i, rgroup;
  171854. int M = cinfo->min_DCT_scaled_size;
  171855. jpeg_component_info *compptr;
  171856. JSAMPARRAY buf, xbuf0, xbuf1;
  171857. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171858. ci++, compptr++) {
  171859. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171860. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171861. xbuf0 = main_->xbuffer[0][ci];
  171862. xbuf1 = main_->xbuffer[1][ci];
  171863. /* First copy the workspace pointers as-is */
  171864. buf = main_->buffer[ci];
  171865. for (i = 0; i < rgroup * (M + 2); i++) {
  171866. xbuf0[i] = xbuf1[i] = buf[i];
  171867. }
  171868. /* In the second list, put the last four row groups in swapped order */
  171869. for (i = 0; i < rgroup * 2; i++) {
  171870. xbuf1[rgroup*(M-2) + i] = buf[rgroup*M + i];
  171871. xbuf1[rgroup*M + i] = buf[rgroup*(M-2) + i];
  171872. }
  171873. /* The wraparound pointers at top and bottom will be filled later
  171874. * (see set_wraparound_pointers, below). Initially we want the "above"
  171875. * pointers to duplicate the first actual data line. This only needs
  171876. * to happen in xbuffer[0].
  171877. */
  171878. for (i = 0; i < rgroup; i++) {
  171879. xbuf0[i - rgroup] = xbuf0[0];
  171880. }
  171881. }
  171882. }
  171883. LOCAL(void)
  171884. set_wraparound_pointers (j_decompress_ptr cinfo)
  171885. /* Set up the "wraparound" pointers at top and bottom of the pointer lists.
  171886. * This changes the pointer list state from top-of-image to the normal state.
  171887. */
  171888. {
  171889. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171890. int ci, i, rgroup;
  171891. int M = cinfo->min_DCT_scaled_size;
  171892. jpeg_component_info *compptr;
  171893. JSAMPARRAY xbuf0, xbuf1;
  171894. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171895. ci++, compptr++) {
  171896. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  171897. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  171898. xbuf0 = main_->xbuffer[0][ci];
  171899. xbuf1 = main_->xbuffer[1][ci];
  171900. for (i = 0; i < rgroup; i++) {
  171901. xbuf0[i - rgroup] = xbuf0[rgroup*(M+1) + i];
  171902. xbuf1[i - rgroup] = xbuf1[rgroup*(M+1) + i];
  171903. xbuf0[rgroup*(M+2) + i] = xbuf0[i];
  171904. xbuf1[rgroup*(M+2) + i] = xbuf1[i];
  171905. }
  171906. }
  171907. }
  171908. LOCAL(void)
  171909. set_bottom_pointers (j_decompress_ptr cinfo)
  171910. /* Change the pointer lists to duplicate the last sample row at the bottom
  171911. * of the image. whichptr indicates which xbuffer holds the final iMCU row.
  171912. * Also sets rowgroups_avail to indicate number of nondummy row groups in row.
  171913. */
  171914. {
  171915. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171916. int ci, i, rgroup, iMCUheight, rows_left;
  171917. jpeg_component_info *compptr;
  171918. JSAMPARRAY xbuf;
  171919. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  171920. ci++, compptr++) {
  171921. /* Count sample rows in one iMCU row and in one row group */
  171922. iMCUheight = compptr->v_samp_factor * compptr->DCT_scaled_size;
  171923. rgroup = iMCUheight / cinfo->min_DCT_scaled_size;
  171924. /* Count nondummy sample rows remaining for this component */
  171925. rows_left = (int) (compptr->downsampled_height % (JDIMENSION) iMCUheight);
  171926. if (rows_left == 0) rows_left = iMCUheight;
  171927. /* Count nondummy row groups. Should get same answer for each component,
  171928. * so we need only do it once.
  171929. */
  171930. if (ci == 0) {
  171931. main_->rowgroups_avail = (JDIMENSION) ((rows_left-1) / rgroup + 1);
  171932. }
  171933. /* Duplicate the last real sample row rgroup*2 times; this pads out the
  171934. * last partial rowgroup and ensures at least one full rowgroup of context.
  171935. */
  171936. xbuf = main_->xbuffer[main_->whichptr][ci];
  171937. for (i = 0; i < rgroup * 2; i++) {
  171938. xbuf[rows_left + i] = xbuf[rows_left-1];
  171939. }
  171940. }
  171941. }
  171942. /*
  171943. * Initialize for a processing pass.
  171944. */
  171945. METHODDEF(void)
  171946. start_pass_main2 (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  171947. {
  171948. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171949. switch (pass_mode) {
  171950. case JBUF_PASS_THRU:
  171951. if (cinfo->upsample->need_context_rows) {
  171952. main_->pub.process_data = process_data_context_main;
  171953. make_funny_pointers(cinfo); /* Create the xbuffer[] lists */
  171954. main_->whichptr = 0; /* Read first iMCU row into xbuffer[0] */
  171955. main_->context_state = CTX_PREPARE_FOR_IMCU;
  171956. main_->iMCU_row_ctr = 0;
  171957. } else {
  171958. /* Simple case with no context needed */
  171959. main_->pub.process_data = process_data_simple_main2;
  171960. }
  171961. main_->buffer_full = FALSE; /* Mark buffer empty */
  171962. main_->rowgroup_ctr = 0;
  171963. break;
  171964. #ifdef QUANT_2PASS_SUPPORTED
  171965. case JBUF_CRANK_DEST:
  171966. /* For last pass of 2-pass quantization, just crank the postprocessor */
  171967. main_->pub.process_data = process_data_crank_post;
  171968. break;
  171969. #endif
  171970. default:
  171971. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  171972. break;
  171973. }
  171974. }
  171975. /*
  171976. * Process some data.
  171977. * This handles the simple case where no context is required.
  171978. */
  171979. METHODDEF(void)
  171980. process_data_simple_main2 (j_decompress_ptr cinfo,
  171981. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  171982. JDIMENSION out_rows_avail)
  171983. {
  171984. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  171985. JDIMENSION rowgroups_avail;
  171986. /* Read input data if we haven't filled the main buffer yet */
  171987. if (! main_->buffer_full) {
  171988. if (! (*cinfo->coef->decompress_data) (cinfo, main_->buffer))
  171989. return; /* suspension forced, can do nothing more */
  171990. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  171991. }
  171992. /* There are always min_DCT_scaled_size row groups in an iMCU row. */
  171993. rowgroups_avail = (JDIMENSION) cinfo->min_DCT_scaled_size;
  171994. /* Note: at the bottom of the image, we may pass extra garbage row groups
  171995. * to the postprocessor. The postprocessor has to check for bottom
  171996. * of image anyway (at row resolution), so no point in us doing it too.
  171997. */
  171998. /* Feed the postprocessor */
  171999. (*cinfo->post->post_process_data) (cinfo, main_->buffer,
  172000. &main_->rowgroup_ctr, rowgroups_avail,
  172001. output_buf, out_row_ctr, out_rows_avail);
  172002. /* Has postprocessor consumed all the data yet? If so, mark buffer empty */
  172003. if (main_->rowgroup_ctr >= rowgroups_avail) {
  172004. main_->buffer_full = FALSE;
  172005. main_->rowgroup_ctr = 0;
  172006. }
  172007. }
  172008. /*
  172009. * Process some data.
  172010. * This handles the case where context rows must be provided.
  172011. */
  172012. METHODDEF(void)
  172013. process_data_context_main (j_decompress_ptr cinfo,
  172014. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172015. JDIMENSION out_rows_avail)
  172016. {
  172017. my_main_ptr4 main_ = (my_main_ptr4) cinfo->main;
  172018. /* Read input data if we haven't filled the main buffer yet */
  172019. if (! main_->buffer_full) {
  172020. if (! (*cinfo->coef->decompress_data) (cinfo,
  172021. main_->xbuffer[main_->whichptr]))
  172022. return; /* suspension forced, can do nothing more */
  172023. main_->buffer_full = TRUE; /* OK, we have an iMCU row to work with */
  172024. main_->iMCU_row_ctr++; /* count rows received */
  172025. }
  172026. /* Postprocessor typically will not swallow all the input data it is handed
  172027. * in one call (due to filling the output buffer first). Must be prepared
  172028. * to exit and restart. This switch lets us keep track of how far we got.
  172029. * Note that each case falls through to the next on successful completion.
  172030. */
  172031. switch (main_->context_state) {
  172032. case CTX_POSTPONED_ROW:
  172033. /* Call postprocessor using previously set pointers for postponed row */
  172034. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  172035. &main_->rowgroup_ctr, main_->rowgroups_avail,
  172036. output_buf, out_row_ctr, out_rows_avail);
  172037. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  172038. return; /* Need to suspend */
  172039. main_->context_state = CTX_PREPARE_FOR_IMCU;
  172040. if (*out_row_ctr >= out_rows_avail)
  172041. return; /* Postprocessor exactly filled output buf */
  172042. /*FALLTHROUGH*/
  172043. case CTX_PREPARE_FOR_IMCU:
  172044. /* Prepare to process first M-1 row groups of this iMCU row */
  172045. main_->rowgroup_ctr = 0;
  172046. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size - 1);
  172047. /* Check for bottom of image: if so, tweak pointers to "duplicate"
  172048. * the last sample row, and adjust rowgroups_avail to ignore padding rows.
  172049. */
  172050. if (main_->iMCU_row_ctr == cinfo->total_iMCU_rows)
  172051. set_bottom_pointers(cinfo);
  172052. main_->context_state = CTX_PROCESS_IMCU;
  172053. /*FALLTHROUGH*/
  172054. case CTX_PROCESS_IMCU:
  172055. /* Call postprocessor using previously set pointers */
  172056. (*cinfo->post->post_process_data) (cinfo, main_->xbuffer[main_->whichptr],
  172057. &main_->rowgroup_ctr, main_->rowgroups_avail,
  172058. output_buf, out_row_ctr, out_rows_avail);
  172059. if (main_->rowgroup_ctr < main_->rowgroups_avail)
  172060. return; /* Need to suspend */
  172061. /* After the first iMCU, change wraparound pointers to normal state */
  172062. if (main_->iMCU_row_ctr == 1)
  172063. set_wraparound_pointers(cinfo);
  172064. /* Prepare to load new iMCU row using other xbuffer list */
  172065. main_->whichptr ^= 1; /* 0=>1 or 1=>0 */
  172066. main_->buffer_full = FALSE;
  172067. /* Still need to process last row group of this iMCU row, */
  172068. /* which is saved at index M+1 of the other xbuffer */
  172069. main_->rowgroup_ctr = (JDIMENSION) (cinfo->min_DCT_scaled_size + 1);
  172070. main_->rowgroups_avail = (JDIMENSION) (cinfo->min_DCT_scaled_size + 2);
  172071. main_->context_state = CTX_POSTPONED_ROW;
  172072. }
  172073. }
  172074. /*
  172075. * Process some data.
  172076. * Final pass of two-pass quantization: just call the postprocessor.
  172077. * Source data will be the postprocessor controller's internal buffer.
  172078. */
  172079. #ifdef QUANT_2PASS_SUPPORTED
  172080. METHODDEF(void)
  172081. process_data_crank_post (j_decompress_ptr cinfo,
  172082. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  172083. JDIMENSION out_rows_avail)
  172084. {
  172085. (*cinfo->post->post_process_data) (cinfo, (JSAMPIMAGE) NULL,
  172086. (JDIMENSION *) NULL, (JDIMENSION) 0,
  172087. output_buf, out_row_ctr, out_rows_avail);
  172088. }
  172089. #endif /* QUANT_2PASS_SUPPORTED */
  172090. /*
  172091. * Initialize main buffer controller.
  172092. */
  172093. GLOBAL(void)
  172094. jinit_d_main_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  172095. {
  172096. my_main_ptr4 main_;
  172097. int ci, rgroup, ngroups;
  172098. jpeg_component_info *compptr;
  172099. main_ = (my_main_ptr4)
  172100. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172101. SIZEOF(my_main_controller4));
  172102. cinfo->main = (struct jpeg_d_main_controller *) main_;
  172103. main_->pub.start_pass = start_pass_main2;
  172104. if (need_full_buffer) /* shouldn't happen */
  172105. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  172106. /* Allocate the workspace.
  172107. * ngroups is the number of row groups we need.
  172108. */
  172109. if (cinfo->upsample->need_context_rows) {
  172110. if (cinfo->min_DCT_scaled_size < 2) /* unsupported, see comments above */
  172111. ERREXIT(cinfo, JERR_NOTIMPL);
  172112. alloc_funny_pointers(cinfo); /* Alloc space for xbuffer[] lists */
  172113. ngroups = cinfo->min_DCT_scaled_size + 2;
  172114. } else {
  172115. ngroups = cinfo->min_DCT_scaled_size;
  172116. }
  172117. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172118. ci++, compptr++) {
  172119. rgroup = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  172120. cinfo->min_DCT_scaled_size; /* height of a row group of component */
  172121. main_->buffer[ci] = (*cinfo->mem->alloc_sarray)
  172122. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172123. compptr->width_in_blocks * compptr->DCT_scaled_size,
  172124. (JDIMENSION) (rgroup * ngroups));
  172125. }
  172126. }
  172127. /********* End of inlined file: jdmainct.c *********/
  172128. /********* Start of inlined file: jdmarker.c *********/
  172129. #define JPEG_INTERNALS
  172130. /* Private state */
  172131. typedef struct {
  172132. struct jpeg_marker_reader pub; /* public fields */
  172133. /* Application-overridable marker processing methods */
  172134. jpeg_marker_parser_method process_COM;
  172135. jpeg_marker_parser_method process_APPn[16];
  172136. /* Limit on marker data length to save for each marker type */
  172137. unsigned int length_limit_COM;
  172138. unsigned int length_limit_APPn[16];
  172139. /* Status of COM/APPn marker saving */
  172140. jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
  172141. unsigned int bytes_read; /* data bytes read so far in marker */
  172142. /* Note: cur_marker is not linked into marker_list until it's all read. */
  172143. } my_marker_reader;
  172144. typedef my_marker_reader * my_marker_ptr2;
  172145. /*
  172146. * Macros for fetching data from the data source module.
  172147. *
  172148. * At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
  172149. * the current restart point; we update them only when we have reached a
  172150. * suitable place to restart if a suspension occurs.
  172151. */
  172152. /* Declare and initialize local copies of input pointer/count */
  172153. #define INPUT_VARS(cinfo) \
  172154. struct jpeg_source_mgr * datasrc = (cinfo)->src; \
  172155. const JOCTET * next_input_byte = datasrc->next_input_byte; \
  172156. size_t bytes_in_buffer = datasrc->bytes_in_buffer
  172157. /* Unload the local copies --- do this only at a restart boundary */
  172158. #define INPUT_SYNC(cinfo) \
  172159. ( datasrc->next_input_byte = next_input_byte, \
  172160. datasrc->bytes_in_buffer = bytes_in_buffer )
  172161. /* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
  172162. #define INPUT_RELOAD(cinfo) \
  172163. ( next_input_byte = datasrc->next_input_byte, \
  172164. bytes_in_buffer = datasrc->bytes_in_buffer )
  172165. /* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
  172166. * Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
  172167. * but we must reload the local copies after a successful fill.
  172168. */
  172169. #define MAKE_BYTE_AVAIL(cinfo,action) \
  172170. if (bytes_in_buffer == 0) { \
  172171. if (! (*datasrc->fill_input_buffer) (cinfo)) \
  172172. { action; } \
  172173. INPUT_RELOAD(cinfo); \
  172174. }
  172175. /* Read a byte into variable V.
  172176. * If must suspend, take the specified action (typically "return FALSE").
  172177. */
  172178. #define INPUT_BYTE(cinfo,V,action) \
  172179. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  172180. bytes_in_buffer--; \
  172181. V = GETJOCTET(*next_input_byte++); )
  172182. /* As above, but read two bytes interpreted as an unsigned 16-bit integer.
  172183. * V should be declared unsigned int or perhaps INT32.
  172184. */
  172185. #define INPUT_2BYTES(cinfo,V,action) \
  172186. MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
  172187. bytes_in_buffer--; \
  172188. V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
  172189. MAKE_BYTE_AVAIL(cinfo,action); \
  172190. bytes_in_buffer--; \
  172191. V += GETJOCTET(*next_input_byte++); )
  172192. /*
  172193. * Routines to process JPEG markers.
  172194. *
  172195. * Entry condition: JPEG marker itself has been read and its code saved
  172196. * in cinfo->unread_marker; input restart point is just after the marker.
  172197. *
  172198. * Exit: if return TRUE, have read and processed any parameters, and have
  172199. * updated the restart point to point after the parameters.
  172200. * If return FALSE, was forced to suspend before reaching end of
  172201. * marker parameters; restart point has not been moved. Same routine
  172202. * will be called again after application supplies more input data.
  172203. *
  172204. * This approach to suspension assumes that all of a marker's parameters
  172205. * can fit into a single input bufferload. This should hold for "normal"
  172206. * markers. Some COM/APPn markers might have large parameter segments
  172207. * that might not fit. If we are simply dropping such a marker, we use
  172208. * skip_input_data to get past it, and thereby put the problem on the
  172209. * source manager's shoulders. If we are saving the marker's contents
  172210. * into memory, we use a slightly different convention: when forced to
  172211. * suspend, the marker processor updates the restart point to the end of
  172212. * what it's consumed (ie, the end of the buffer) before returning FALSE.
  172213. * On resumption, cinfo->unread_marker still contains the marker code,
  172214. * but the data source will point to the next chunk of marker data.
  172215. * The marker processor must retain internal state to deal with this.
  172216. *
  172217. * Note that we don't bother to avoid duplicate trace messages if a
  172218. * suspension occurs within marker parameters. Other side effects
  172219. * require more care.
  172220. */
  172221. LOCAL(boolean)
  172222. get_soi (j_decompress_ptr cinfo)
  172223. /* Process an SOI marker */
  172224. {
  172225. int i;
  172226. TRACEMS(cinfo, 1, JTRC_SOI);
  172227. if (cinfo->marker->saw_SOI)
  172228. ERREXIT(cinfo, JERR_SOI_DUPLICATE);
  172229. /* Reset all parameters that are defined to be reset by SOI */
  172230. for (i = 0; i < NUM_ARITH_TBLS; i++) {
  172231. cinfo->arith_dc_L[i] = 0;
  172232. cinfo->arith_dc_U[i] = 1;
  172233. cinfo->arith_ac_K[i] = 5;
  172234. }
  172235. cinfo->restart_interval = 0;
  172236. /* Set initial assumptions for colorspace etc */
  172237. cinfo->jpeg_color_space = JCS_UNKNOWN;
  172238. cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
  172239. cinfo->saw_JFIF_marker = FALSE;
  172240. cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
  172241. cinfo->JFIF_minor_version = 1;
  172242. cinfo->density_unit = 0;
  172243. cinfo->X_density = 1;
  172244. cinfo->Y_density = 1;
  172245. cinfo->saw_Adobe_marker = FALSE;
  172246. cinfo->Adobe_transform = 0;
  172247. cinfo->marker->saw_SOI = TRUE;
  172248. return TRUE;
  172249. }
  172250. LOCAL(boolean)
  172251. get_sof (j_decompress_ptr cinfo, boolean is_prog, boolean is_arith)
  172252. /* Process a SOFn marker */
  172253. {
  172254. INT32 length;
  172255. int c, ci;
  172256. jpeg_component_info * compptr;
  172257. INPUT_VARS(cinfo);
  172258. cinfo->progressive_mode = is_prog;
  172259. cinfo->arith_code = is_arith;
  172260. INPUT_2BYTES(cinfo, length, return FALSE);
  172261. INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
  172262. INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
  172263. INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
  172264. INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
  172265. length -= 8;
  172266. TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
  172267. (int) cinfo->image_width, (int) cinfo->image_height,
  172268. cinfo->num_components);
  172269. if (cinfo->marker->saw_SOF)
  172270. ERREXIT(cinfo, JERR_SOF_DUPLICATE);
  172271. /* We don't support files in which the image height is initially specified */
  172272. /* as 0 and is later redefined by DNL. As long as we have to check that, */
  172273. /* might as well have a general sanity check. */
  172274. if (cinfo->image_height <= 0 || cinfo->image_width <= 0
  172275. || cinfo->num_components <= 0)
  172276. ERREXIT(cinfo, JERR_EMPTY_IMAGE);
  172277. if (length != (cinfo->num_components * 3))
  172278. ERREXIT(cinfo, JERR_BAD_LENGTH);
  172279. if (cinfo->comp_info == NULL) /* do only once, even if suspend */
  172280. cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
  172281. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172282. cinfo->num_components * SIZEOF(jpeg_component_info));
  172283. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172284. ci++, compptr++) {
  172285. compptr->component_index = ci;
  172286. INPUT_BYTE(cinfo, compptr->component_id, return FALSE);
  172287. INPUT_BYTE(cinfo, c, return FALSE);
  172288. compptr->h_samp_factor = (c >> 4) & 15;
  172289. compptr->v_samp_factor = (c ) & 15;
  172290. INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
  172291. TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
  172292. compptr->component_id, compptr->h_samp_factor,
  172293. compptr->v_samp_factor, compptr->quant_tbl_no);
  172294. }
  172295. cinfo->marker->saw_SOF = TRUE;
  172296. INPUT_SYNC(cinfo);
  172297. return TRUE;
  172298. }
  172299. LOCAL(boolean)
  172300. get_sos (j_decompress_ptr cinfo)
  172301. /* Process a SOS marker */
  172302. {
  172303. INT32 length;
  172304. int i, ci, n, c, cc;
  172305. jpeg_component_info * compptr;
  172306. INPUT_VARS(cinfo);
  172307. if (! cinfo->marker->saw_SOF)
  172308. ERREXIT(cinfo, JERR_SOS_NO_SOF);
  172309. INPUT_2BYTES(cinfo, length, return FALSE);
  172310. INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
  172311. TRACEMS1(cinfo, 1, JTRC_SOS, n);
  172312. if (length != (n * 2 + 6) || n < 1 || n > MAX_COMPS_IN_SCAN)
  172313. ERREXIT(cinfo, JERR_BAD_LENGTH);
  172314. cinfo->comps_in_scan = n;
  172315. /* Collect the component-spec parameters */
  172316. for (i = 0; i < n; i++) {
  172317. INPUT_BYTE(cinfo, cc, return FALSE);
  172318. INPUT_BYTE(cinfo, c, return FALSE);
  172319. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  172320. ci++, compptr++) {
  172321. if (cc == compptr->component_id)
  172322. goto id_found;
  172323. }
  172324. ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, cc);
  172325. id_found:
  172326. cinfo->cur_comp_info[i] = compptr;
  172327. compptr->dc_tbl_no = (c >> 4) & 15;
  172328. compptr->ac_tbl_no = (c ) & 15;
  172329. TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, cc,
  172330. compptr->dc_tbl_no, compptr->ac_tbl_no);
  172331. }
  172332. /* Collect the additional scan parameters Ss, Se, Ah/Al. */
  172333. INPUT_BYTE(cinfo, c, return FALSE);
  172334. cinfo->Ss = c;
  172335. INPUT_BYTE(cinfo, c, return FALSE);
  172336. cinfo->Se = c;
  172337. INPUT_BYTE(cinfo, c, return FALSE);
  172338. cinfo->Ah = (c >> 4) & 15;
  172339. cinfo->Al = (c ) & 15;
  172340. TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
  172341. cinfo->Ah, cinfo->Al);
  172342. /* Prepare to scan data & restart markers */
  172343. cinfo->marker->next_restart_num = 0;
  172344. /* Count another SOS marker */
  172345. cinfo->input_scan_number++;
  172346. INPUT_SYNC(cinfo);
  172347. return TRUE;
  172348. }
  172349. #ifdef D_ARITH_CODING_SUPPORTED
  172350. LOCAL(boolean)
  172351. get_dac (j_decompress_ptr cinfo)
  172352. /* Process a DAC marker */
  172353. {
  172354. INT32 length;
  172355. int index, val;
  172356. INPUT_VARS(cinfo);
  172357. INPUT_2BYTES(cinfo, length, return FALSE);
  172358. length -= 2;
  172359. while (length > 0) {
  172360. INPUT_BYTE(cinfo, index, return FALSE);
  172361. INPUT_BYTE(cinfo, val, return FALSE);
  172362. length -= 2;
  172363. TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
  172364. if (index < 0 || index >= (2*NUM_ARITH_TBLS))
  172365. ERREXIT1(cinfo, JERR_DAC_INDEX, index);
  172366. if (index >= NUM_ARITH_TBLS) { /* define AC table */
  172367. cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
  172368. } else { /* define DC table */
  172369. cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
  172370. cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
  172371. if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
  172372. ERREXIT1(cinfo, JERR_DAC_VALUE, val);
  172373. }
  172374. }
  172375. if (length != 0)
  172376. ERREXIT(cinfo, JERR_BAD_LENGTH);
  172377. INPUT_SYNC(cinfo);
  172378. return TRUE;
  172379. }
  172380. #else /* ! D_ARITH_CODING_SUPPORTED */
  172381. #define get_dac(cinfo) skip_variable(cinfo)
  172382. #endif /* D_ARITH_CODING_SUPPORTED */
  172383. LOCAL(boolean)
  172384. get_dht (j_decompress_ptr cinfo)
  172385. /* Process a DHT marker */
  172386. {
  172387. INT32 length;
  172388. UINT8 bits[17];
  172389. UINT8 huffval[256];
  172390. int i, index, count;
  172391. JHUFF_TBL **htblptr;
  172392. INPUT_VARS(cinfo);
  172393. INPUT_2BYTES(cinfo, length, return FALSE);
  172394. length -= 2;
  172395. while (length > 16) {
  172396. INPUT_BYTE(cinfo, index, return FALSE);
  172397. TRACEMS1(cinfo, 1, JTRC_DHT, index);
  172398. bits[0] = 0;
  172399. count = 0;
  172400. for (i = 1; i <= 16; i++) {
  172401. INPUT_BYTE(cinfo, bits[i], return FALSE);
  172402. count += bits[i];
  172403. }
  172404. length -= 1 + 16;
  172405. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  172406. bits[1], bits[2], bits[3], bits[4],
  172407. bits[5], bits[6], bits[7], bits[8]);
  172408. TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
  172409. bits[9], bits[10], bits[11], bits[12],
  172410. bits[13], bits[14], bits[15], bits[16]);
  172411. /* Here we just do minimal validation of the counts to avoid walking
  172412. * off the end of our table space. jdhuff.c will check more carefully.
  172413. */
  172414. if (count > 256 || ((INT32) count) > length)
  172415. ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
  172416. for (i = 0; i < count; i++)
  172417. INPUT_BYTE(cinfo, huffval[i], return FALSE);
  172418. length -= count;
  172419. if (index & 0x10) { /* AC table definition */
  172420. index -= 0x10;
  172421. htblptr = &cinfo->ac_huff_tbl_ptrs[index];
  172422. } else { /* DC table definition */
  172423. htblptr = &cinfo->dc_huff_tbl_ptrs[index];
  172424. }
  172425. if (index < 0 || index >= NUM_HUFF_TBLS)
  172426. ERREXIT1(cinfo, JERR_DHT_INDEX, index);
  172427. if (*htblptr == NULL)
  172428. *htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
  172429. MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
  172430. MEMCOPY((*htblptr)->huffval, huffval, SIZEOF((*htblptr)->huffval));
  172431. }
  172432. if (length != 0)
  172433. ERREXIT(cinfo, JERR_BAD_LENGTH);
  172434. INPUT_SYNC(cinfo);
  172435. return TRUE;
  172436. }
  172437. LOCAL(boolean)
  172438. get_dqt (j_decompress_ptr cinfo)
  172439. /* Process a DQT marker */
  172440. {
  172441. INT32 length;
  172442. int n, i, prec;
  172443. unsigned int tmp;
  172444. JQUANT_TBL *quant_ptr;
  172445. INPUT_VARS(cinfo);
  172446. INPUT_2BYTES(cinfo, length, return FALSE);
  172447. length -= 2;
  172448. while (length > 0) {
  172449. INPUT_BYTE(cinfo, n, return FALSE);
  172450. prec = n >> 4;
  172451. n &= 0x0F;
  172452. TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
  172453. if (n >= NUM_QUANT_TBLS)
  172454. ERREXIT1(cinfo, JERR_DQT_INDEX, n);
  172455. if (cinfo->quant_tbl_ptrs[n] == NULL)
  172456. cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
  172457. quant_ptr = cinfo->quant_tbl_ptrs[n];
  172458. for (i = 0; i < DCTSIZE2; i++) {
  172459. if (prec)
  172460. INPUT_2BYTES(cinfo, tmp, return FALSE);
  172461. else
  172462. INPUT_BYTE(cinfo, tmp, return FALSE);
  172463. /* We convert the zigzag-order table to natural array order. */
  172464. quant_ptr->quantval[jpeg_natural_order[i]] = (UINT16) tmp;
  172465. }
  172466. if (cinfo->err->trace_level >= 2) {
  172467. for (i = 0; i < DCTSIZE2; i += 8) {
  172468. TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
  172469. quant_ptr->quantval[i], quant_ptr->quantval[i+1],
  172470. quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
  172471. quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
  172472. quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
  172473. }
  172474. }
  172475. length -= DCTSIZE2+1;
  172476. if (prec) length -= DCTSIZE2;
  172477. }
  172478. if (length != 0)
  172479. ERREXIT(cinfo, JERR_BAD_LENGTH);
  172480. INPUT_SYNC(cinfo);
  172481. return TRUE;
  172482. }
  172483. LOCAL(boolean)
  172484. get_dri (j_decompress_ptr cinfo)
  172485. /* Process a DRI marker */
  172486. {
  172487. INT32 length;
  172488. unsigned int tmp;
  172489. INPUT_VARS(cinfo);
  172490. INPUT_2BYTES(cinfo, length, return FALSE);
  172491. if (length != 4)
  172492. ERREXIT(cinfo, JERR_BAD_LENGTH);
  172493. INPUT_2BYTES(cinfo, tmp, return FALSE);
  172494. TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
  172495. cinfo->restart_interval = tmp;
  172496. INPUT_SYNC(cinfo);
  172497. return TRUE;
  172498. }
  172499. /*
  172500. * Routines for processing APPn and COM markers.
  172501. * These are either saved in memory or discarded, per application request.
  172502. * APP0 and APP14 are specially checked to see if they are
  172503. * JFIF and Adobe markers, respectively.
  172504. */
  172505. #define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
  172506. #define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
  172507. #define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
  172508. LOCAL(void)
  172509. examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
  172510. unsigned int datalen, INT32 remaining)
  172511. /* Examine first few bytes from an APP0.
  172512. * Take appropriate action if it is a JFIF marker.
  172513. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  172514. */
  172515. {
  172516. INT32 totallen = (INT32) datalen + remaining;
  172517. if (datalen >= APP0_DATA_LEN &&
  172518. GETJOCTET(data[0]) == 0x4A &&
  172519. GETJOCTET(data[1]) == 0x46 &&
  172520. GETJOCTET(data[2]) == 0x49 &&
  172521. GETJOCTET(data[3]) == 0x46 &&
  172522. GETJOCTET(data[4]) == 0) {
  172523. /* Found JFIF APP0 marker: save info */
  172524. cinfo->saw_JFIF_marker = TRUE;
  172525. cinfo->JFIF_major_version = GETJOCTET(data[5]);
  172526. cinfo->JFIF_minor_version = GETJOCTET(data[6]);
  172527. cinfo->density_unit = GETJOCTET(data[7]);
  172528. cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
  172529. cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
  172530. /* Check version.
  172531. * Major version must be 1, anything else signals an incompatible change.
  172532. * (We used to treat this as an error, but now it's a nonfatal warning,
  172533. * because some bozo at Hijaak couldn't read the spec.)
  172534. * Minor version should be 0..2, but process anyway if newer.
  172535. */
  172536. if (cinfo->JFIF_major_version != 1)
  172537. WARNMS2(cinfo, JWRN_JFIF_MAJOR,
  172538. cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
  172539. /* Generate trace messages */
  172540. TRACEMS5(cinfo, 1, JTRC_JFIF,
  172541. cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
  172542. cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
  172543. /* Validate thumbnail dimensions and issue appropriate messages */
  172544. if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
  172545. TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
  172546. GETJOCTET(data[12]), GETJOCTET(data[13]));
  172547. totallen -= APP0_DATA_LEN;
  172548. if (totallen !=
  172549. ((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
  172550. TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
  172551. } else if (datalen >= 6 &&
  172552. GETJOCTET(data[0]) == 0x4A &&
  172553. GETJOCTET(data[1]) == 0x46 &&
  172554. GETJOCTET(data[2]) == 0x58 &&
  172555. GETJOCTET(data[3]) == 0x58 &&
  172556. GETJOCTET(data[4]) == 0) {
  172557. /* Found JFIF "JFXX" extension APP0 marker */
  172558. /* The library doesn't actually do anything with these,
  172559. * but we try to produce a helpful trace message.
  172560. */
  172561. switch (GETJOCTET(data[5])) {
  172562. case 0x10:
  172563. TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
  172564. break;
  172565. case 0x11:
  172566. TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
  172567. break;
  172568. case 0x13:
  172569. TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
  172570. break;
  172571. default:
  172572. TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
  172573. GETJOCTET(data[5]), (int) totallen);
  172574. break;
  172575. }
  172576. } else {
  172577. /* Start of APP0 does not match "JFIF" or "JFXX", or too short */
  172578. TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
  172579. }
  172580. }
  172581. LOCAL(void)
  172582. examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
  172583. unsigned int datalen, INT32 remaining)
  172584. /* Examine first few bytes from an APP14.
  172585. * Take appropriate action if it is an Adobe marker.
  172586. * datalen is # of bytes at data[], remaining is length of rest of marker data.
  172587. */
  172588. {
  172589. unsigned int version, flags0, flags1, transform;
  172590. if (datalen >= APP14_DATA_LEN &&
  172591. GETJOCTET(data[0]) == 0x41 &&
  172592. GETJOCTET(data[1]) == 0x64 &&
  172593. GETJOCTET(data[2]) == 0x6F &&
  172594. GETJOCTET(data[3]) == 0x62 &&
  172595. GETJOCTET(data[4]) == 0x65) {
  172596. /* Found Adobe APP14 marker */
  172597. version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
  172598. flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
  172599. flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
  172600. transform = GETJOCTET(data[11]);
  172601. TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
  172602. cinfo->saw_Adobe_marker = TRUE;
  172603. cinfo->Adobe_transform = (UINT8) transform;
  172604. } else {
  172605. /* Start of APP14 does not match "Adobe", or too short */
  172606. TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
  172607. }
  172608. }
  172609. METHODDEF(boolean)
  172610. get_interesting_appn (j_decompress_ptr cinfo)
  172611. /* Process an APP0 or APP14 marker without saving it */
  172612. {
  172613. INT32 length;
  172614. JOCTET b[APPN_DATA_LEN];
  172615. unsigned int i, numtoread;
  172616. INPUT_VARS(cinfo);
  172617. INPUT_2BYTES(cinfo, length, return FALSE);
  172618. length -= 2;
  172619. /* get the interesting part of the marker data */
  172620. if (length >= APPN_DATA_LEN)
  172621. numtoread = APPN_DATA_LEN;
  172622. else if (length > 0)
  172623. numtoread = (unsigned int) length;
  172624. else
  172625. numtoread = 0;
  172626. for (i = 0; i < numtoread; i++)
  172627. INPUT_BYTE(cinfo, b[i], return FALSE);
  172628. length -= numtoread;
  172629. /* process it */
  172630. switch (cinfo->unread_marker) {
  172631. case M_APP0:
  172632. examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
  172633. break;
  172634. case M_APP14:
  172635. examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
  172636. break;
  172637. default:
  172638. /* can't get here unless jpeg_save_markers chooses wrong processor */
  172639. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  172640. break;
  172641. }
  172642. /* skip any remaining data -- could be lots */
  172643. INPUT_SYNC(cinfo);
  172644. if (length > 0)
  172645. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  172646. return TRUE;
  172647. }
  172648. #ifdef SAVE_MARKERS_SUPPORTED
  172649. METHODDEF(boolean)
  172650. save_marker (j_decompress_ptr cinfo)
  172651. /* Save an APPn or COM marker into the marker list */
  172652. {
  172653. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  172654. jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
  172655. unsigned int bytes_read, data_length;
  172656. JOCTET FAR * data;
  172657. INT32 length = 0;
  172658. INPUT_VARS(cinfo);
  172659. if (cur_marker == NULL) {
  172660. /* begin reading a marker */
  172661. INPUT_2BYTES(cinfo, length, return FALSE);
  172662. length -= 2;
  172663. if (length >= 0) { /* watch out for bogus length word */
  172664. /* figure out how much we want to save */
  172665. unsigned int limit;
  172666. if (cinfo->unread_marker == (int) M_COM)
  172667. limit = marker->length_limit_COM;
  172668. else
  172669. limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
  172670. if ((unsigned int) length < limit)
  172671. limit = (unsigned int) length;
  172672. /* allocate and initialize the marker item */
  172673. cur_marker = (jpeg_saved_marker_ptr)
  172674. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  172675. SIZEOF(struct jpeg_marker_struct) + limit);
  172676. cur_marker->next = NULL;
  172677. cur_marker->marker = (UINT8) cinfo->unread_marker;
  172678. cur_marker->original_length = (unsigned int) length;
  172679. cur_marker->data_length = limit;
  172680. /* data area is just beyond the jpeg_marker_struct */
  172681. data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
  172682. marker->cur_marker = cur_marker;
  172683. marker->bytes_read = 0;
  172684. bytes_read = 0;
  172685. data_length = limit;
  172686. } else {
  172687. /* deal with bogus length word */
  172688. bytes_read = data_length = 0;
  172689. data = NULL;
  172690. }
  172691. } else {
  172692. /* resume reading a marker */
  172693. bytes_read = marker->bytes_read;
  172694. data_length = cur_marker->data_length;
  172695. data = cur_marker->data + bytes_read;
  172696. }
  172697. while (bytes_read < data_length) {
  172698. INPUT_SYNC(cinfo); /* move the restart point to here */
  172699. marker->bytes_read = bytes_read;
  172700. /* If there's not at least one byte in buffer, suspend */
  172701. MAKE_BYTE_AVAIL(cinfo, return FALSE);
  172702. /* Copy bytes with reasonable rapidity */
  172703. while (bytes_read < data_length && bytes_in_buffer > 0) {
  172704. *data++ = *next_input_byte++;
  172705. bytes_in_buffer--;
  172706. bytes_read++;
  172707. }
  172708. }
  172709. /* Done reading what we want to read */
  172710. if (cur_marker != NULL) { /* will be NULL if bogus length word */
  172711. /* Add new marker to end of list */
  172712. if (cinfo->marker_list == NULL) {
  172713. cinfo->marker_list = cur_marker;
  172714. } else {
  172715. jpeg_saved_marker_ptr prev = cinfo->marker_list;
  172716. while (prev->next != NULL)
  172717. prev = prev->next;
  172718. prev->next = cur_marker;
  172719. }
  172720. /* Reset pointer & calc remaining data length */
  172721. data = cur_marker->data;
  172722. length = cur_marker->original_length - data_length;
  172723. }
  172724. /* Reset to initial state for next marker */
  172725. marker->cur_marker = NULL;
  172726. /* Process the marker if interesting; else just make a generic trace msg */
  172727. switch (cinfo->unread_marker) {
  172728. case M_APP0:
  172729. examine_app0(cinfo, data, data_length, length);
  172730. break;
  172731. case M_APP14:
  172732. examine_app14(cinfo, data, data_length, length);
  172733. break;
  172734. default:
  172735. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
  172736. (int) (data_length + length));
  172737. break;
  172738. }
  172739. /* skip any remaining data -- could be lots */
  172740. INPUT_SYNC(cinfo); /* do before skip_input_data */
  172741. if (length > 0)
  172742. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  172743. return TRUE;
  172744. }
  172745. #endif /* SAVE_MARKERS_SUPPORTED */
  172746. METHODDEF(boolean)
  172747. skip_variable (j_decompress_ptr cinfo)
  172748. /* Skip over an unknown or uninteresting variable-length marker */
  172749. {
  172750. INT32 length;
  172751. INPUT_VARS(cinfo);
  172752. INPUT_2BYTES(cinfo, length, return FALSE);
  172753. length -= 2;
  172754. TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
  172755. INPUT_SYNC(cinfo); /* do before skip_input_data */
  172756. if (length > 0)
  172757. (*cinfo->src->skip_input_data) (cinfo, (long) length);
  172758. return TRUE;
  172759. }
  172760. /*
  172761. * Find the next JPEG marker, save it in cinfo->unread_marker.
  172762. * Returns FALSE if had to suspend before reaching a marker;
  172763. * in that case cinfo->unread_marker is unchanged.
  172764. *
  172765. * Note that the result might not be a valid marker code,
  172766. * but it will never be 0 or FF.
  172767. */
  172768. LOCAL(boolean)
  172769. next_marker (j_decompress_ptr cinfo)
  172770. {
  172771. int c;
  172772. INPUT_VARS(cinfo);
  172773. for (;;) {
  172774. INPUT_BYTE(cinfo, c, return FALSE);
  172775. /* Skip any non-FF bytes.
  172776. * This may look a bit inefficient, but it will not occur in a valid file.
  172777. * We sync after each discarded byte so that a suspending data source
  172778. * can discard the byte from its buffer.
  172779. */
  172780. while (c != 0xFF) {
  172781. cinfo->marker->discarded_bytes++;
  172782. INPUT_SYNC(cinfo);
  172783. INPUT_BYTE(cinfo, c, return FALSE);
  172784. }
  172785. /* This loop swallows any duplicate FF bytes. Extra FFs are legal as
  172786. * pad bytes, so don't count them in discarded_bytes. We assume there
  172787. * will not be so many consecutive FF bytes as to overflow a suspending
  172788. * data source's input buffer.
  172789. */
  172790. do {
  172791. INPUT_BYTE(cinfo, c, return FALSE);
  172792. } while (c == 0xFF);
  172793. if (c != 0)
  172794. break; /* found a valid marker, exit loop */
  172795. /* Reach here if we found a stuffed-zero data sequence (FF/00).
  172796. * Discard it and loop back to try again.
  172797. */
  172798. cinfo->marker->discarded_bytes += 2;
  172799. INPUT_SYNC(cinfo);
  172800. }
  172801. if (cinfo->marker->discarded_bytes != 0) {
  172802. WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
  172803. cinfo->marker->discarded_bytes = 0;
  172804. }
  172805. cinfo->unread_marker = c;
  172806. INPUT_SYNC(cinfo);
  172807. return TRUE;
  172808. }
  172809. LOCAL(boolean)
  172810. first_marker (j_decompress_ptr cinfo)
  172811. /* Like next_marker, but used to obtain the initial SOI marker. */
  172812. /* For this marker, we do not allow preceding garbage or fill; otherwise,
  172813. * we might well scan an entire input file before realizing it ain't JPEG.
  172814. * If an application wants to process non-JFIF files, it must seek to the
  172815. * SOI before calling the JPEG library.
  172816. */
  172817. {
  172818. int c, c2;
  172819. INPUT_VARS(cinfo);
  172820. INPUT_BYTE(cinfo, c, return FALSE);
  172821. INPUT_BYTE(cinfo, c2, return FALSE);
  172822. if (c != 0xFF || c2 != (int) M_SOI)
  172823. ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
  172824. cinfo->unread_marker = c2;
  172825. INPUT_SYNC(cinfo);
  172826. return TRUE;
  172827. }
  172828. /*
  172829. * Read markers until SOS or EOI.
  172830. *
  172831. * Returns same codes as are defined for jpeg_consume_input:
  172832. * JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
  172833. */
  172834. METHODDEF(int)
  172835. read_markers (j_decompress_ptr cinfo)
  172836. {
  172837. /* Outer loop repeats once for each marker. */
  172838. for (;;) {
  172839. /* Collect the marker proper, unless we already did. */
  172840. /* NB: first_marker() enforces the requirement that SOI appear first. */
  172841. if (cinfo->unread_marker == 0) {
  172842. if (! cinfo->marker->saw_SOI) {
  172843. if (! first_marker(cinfo))
  172844. return JPEG_SUSPENDED;
  172845. } else {
  172846. if (! next_marker(cinfo))
  172847. return JPEG_SUSPENDED;
  172848. }
  172849. }
  172850. /* At this point cinfo->unread_marker contains the marker code and the
  172851. * input point is just past the marker proper, but before any parameters.
  172852. * A suspension will cause us to return with this state still true.
  172853. */
  172854. switch (cinfo->unread_marker) {
  172855. case M_SOI:
  172856. if (! get_soi(cinfo))
  172857. return JPEG_SUSPENDED;
  172858. break;
  172859. case M_SOF0: /* Baseline */
  172860. case M_SOF1: /* Extended sequential, Huffman */
  172861. if (! get_sof(cinfo, FALSE, FALSE))
  172862. return JPEG_SUSPENDED;
  172863. break;
  172864. case M_SOF2: /* Progressive, Huffman */
  172865. if (! get_sof(cinfo, TRUE, FALSE))
  172866. return JPEG_SUSPENDED;
  172867. break;
  172868. case M_SOF9: /* Extended sequential, arithmetic */
  172869. if (! get_sof(cinfo, FALSE, TRUE))
  172870. return JPEG_SUSPENDED;
  172871. break;
  172872. case M_SOF10: /* Progressive, arithmetic */
  172873. if (! get_sof(cinfo, TRUE, TRUE))
  172874. return JPEG_SUSPENDED;
  172875. break;
  172876. /* Currently unsupported SOFn types */
  172877. case M_SOF3: /* Lossless, Huffman */
  172878. case M_SOF5: /* Differential sequential, Huffman */
  172879. case M_SOF6: /* Differential progressive, Huffman */
  172880. case M_SOF7: /* Differential lossless, Huffman */
  172881. case M_JPG: /* Reserved for JPEG extensions */
  172882. case M_SOF11: /* Lossless, arithmetic */
  172883. case M_SOF13: /* Differential sequential, arithmetic */
  172884. case M_SOF14: /* Differential progressive, arithmetic */
  172885. case M_SOF15: /* Differential lossless, arithmetic */
  172886. ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
  172887. break;
  172888. case M_SOS:
  172889. if (! get_sos(cinfo))
  172890. return JPEG_SUSPENDED;
  172891. cinfo->unread_marker = 0; /* processed the marker */
  172892. return JPEG_REACHED_SOS;
  172893. case M_EOI:
  172894. TRACEMS(cinfo, 1, JTRC_EOI);
  172895. cinfo->unread_marker = 0; /* processed the marker */
  172896. return JPEG_REACHED_EOI;
  172897. case M_DAC:
  172898. if (! get_dac(cinfo))
  172899. return JPEG_SUSPENDED;
  172900. break;
  172901. case M_DHT:
  172902. if (! get_dht(cinfo))
  172903. return JPEG_SUSPENDED;
  172904. break;
  172905. case M_DQT:
  172906. if (! get_dqt(cinfo))
  172907. return JPEG_SUSPENDED;
  172908. break;
  172909. case M_DRI:
  172910. if (! get_dri(cinfo))
  172911. return JPEG_SUSPENDED;
  172912. break;
  172913. case M_APP0:
  172914. case M_APP1:
  172915. case M_APP2:
  172916. case M_APP3:
  172917. case M_APP4:
  172918. case M_APP5:
  172919. case M_APP6:
  172920. case M_APP7:
  172921. case M_APP8:
  172922. case M_APP9:
  172923. case M_APP10:
  172924. case M_APP11:
  172925. case M_APP12:
  172926. case M_APP13:
  172927. case M_APP14:
  172928. case M_APP15:
  172929. if (! (*((my_marker_ptr2) cinfo->marker)->process_APPn[
  172930. cinfo->unread_marker - (int) M_APP0]) (cinfo))
  172931. return JPEG_SUSPENDED;
  172932. break;
  172933. case M_COM:
  172934. if (! (*((my_marker_ptr2) cinfo->marker)->process_COM) (cinfo))
  172935. return JPEG_SUSPENDED;
  172936. break;
  172937. case M_RST0: /* these are all parameterless */
  172938. case M_RST1:
  172939. case M_RST2:
  172940. case M_RST3:
  172941. case M_RST4:
  172942. case M_RST5:
  172943. case M_RST6:
  172944. case M_RST7:
  172945. case M_TEM:
  172946. TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
  172947. break;
  172948. case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
  172949. if (! skip_variable(cinfo))
  172950. return JPEG_SUSPENDED;
  172951. break;
  172952. default: /* must be DHP, EXP, JPGn, or RESn */
  172953. /* For now, we treat the reserved markers as fatal errors since they are
  172954. * likely to be used to signal incompatible JPEG Part 3 extensions.
  172955. * Once the JPEG 3 version-number marker is well defined, this code
  172956. * ought to change!
  172957. */
  172958. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
  172959. break;
  172960. }
  172961. /* Successfully processed marker, so reset state variable */
  172962. cinfo->unread_marker = 0;
  172963. } /* end loop */
  172964. }
  172965. /*
  172966. * Read a restart marker, which is expected to appear next in the datastream;
  172967. * if the marker is not there, take appropriate recovery action.
  172968. * Returns FALSE if suspension is required.
  172969. *
  172970. * This is called by the entropy decoder after it has read an appropriate
  172971. * number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
  172972. * has already read a marker from the data source. Under normal conditions
  172973. * cinfo->unread_marker will be reset to 0 before returning; if not reset,
  172974. * it holds a marker which the decoder will be unable to read past.
  172975. */
  172976. METHODDEF(boolean)
  172977. read_restart_marker (j_decompress_ptr cinfo)
  172978. {
  172979. /* Obtain a marker unless we already did. */
  172980. /* Note that next_marker will complain if it skips any data. */
  172981. if (cinfo->unread_marker == 0) {
  172982. if (! next_marker(cinfo))
  172983. return FALSE;
  172984. }
  172985. if (cinfo->unread_marker ==
  172986. ((int) M_RST0 + cinfo->marker->next_restart_num)) {
  172987. /* Normal case --- swallow the marker and let entropy decoder continue */
  172988. TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
  172989. cinfo->unread_marker = 0;
  172990. } else {
  172991. /* Uh-oh, the restart markers have been messed up. */
  172992. /* Let the data source manager determine how to resync. */
  172993. if (! (*cinfo->src->resync_to_restart) (cinfo,
  172994. cinfo->marker->next_restart_num))
  172995. return FALSE;
  172996. }
  172997. /* Update next-restart state */
  172998. cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
  172999. return TRUE;
  173000. }
  173001. /*
  173002. * This is the default resync_to_restart method for data source managers
  173003. * to use if they don't have any better approach. Some data source managers
  173004. * may be able to back up, or may have additional knowledge about the data
  173005. * which permits a more intelligent recovery strategy; such managers would
  173006. * presumably supply their own resync method.
  173007. *
  173008. * read_restart_marker calls resync_to_restart if it finds a marker other than
  173009. * the restart marker it was expecting. (This code is *not* used unless
  173010. * a nonzero restart interval has been declared.) cinfo->unread_marker is
  173011. * the marker code actually found (might be anything, except 0 or FF).
  173012. * The desired restart marker number (0..7) is passed as a parameter.
  173013. * This routine is supposed to apply whatever error recovery strategy seems
  173014. * appropriate in order to position the input stream to the next data segment.
  173015. * Note that cinfo->unread_marker is treated as a marker appearing before
  173016. * the current data-source input point; usually it should be reset to zero
  173017. * before returning.
  173018. * Returns FALSE if suspension is required.
  173019. *
  173020. * This implementation is substantially constrained by wanting to treat the
  173021. * input as a data stream; this means we can't back up. Therefore, we have
  173022. * only the following actions to work with:
  173023. * 1. Simply discard the marker and let the entropy decoder resume at next
  173024. * byte of file.
  173025. * 2. Read forward until we find another marker, discarding intervening
  173026. * data. (In theory we could look ahead within the current bufferload,
  173027. * without having to discard data if we don't find the desired marker.
  173028. * This idea is not implemented here, in part because it makes behavior
  173029. * dependent on buffer size and chance buffer-boundary positions.)
  173030. * 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
  173031. * This will cause the entropy decoder to process an empty data segment,
  173032. * inserting dummy zeroes, and then we will reprocess the marker.
  173033. *
  173034. * #2 is appropriate if we think the desired marker lies ahead, while #3 is
  173035. * appropriate if the found marker is a future restart marker (indicating
  173036. * that we have missed the desired restart marker, probably because it got
  173037. * corrupted).
  173038. * We apply #2 or #3 if the found marker is a restart marker no more than
  173039. * two counts behind or ahead of the expected one. We also apply #2 if the
  173040. * found marker is not a legal JPEG marker code (it's certainly bogus data).
  173041. * If the found marker is a restart marker more than 2 counts away, we do #1
  173042. * (too much risk that the marker is erroneous; with luck we will be able to
  173043. * resync at some future point).
  173044. * For any valid non-restart JPEG marker, we apply #3. This keeps us from
  173045. * overrunning the end of a scan. An implementation limited to single-scan
  173046. * files might find it better to apply #2 for markers other than EOI, since
  173047. * any other marker would have to be bogus data in that case.
  173048. */
  173049. GLOBAL(boolean)
  173050. jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
  173051. {
  173052. int marker = cinfo->unread_marker;
  173053. int action = 1;
  173054. /* Always put up a warning. */
  173055. WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
  173056. /* Outer loop handles repeated decision after scanning forward. */
  173057. for (;;) {
  173058. if (marker < (int) M_SOF0)
  173059. action = 2; /* invalid marker */
  173060. else if (marker < (int) M_RST0 || marker > (int) M_RST7)
  173061. action = 3; /* valid non-restart marker */
  173062. else {
  173063. if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
  173064. marker == ((int) M_RST0 + ((desired+2) & 7)))
  173065. action = 3; /* one of the next two expected restarts */
  173066. else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
  173067. marker == ((int) M_RST0 + ((desired-2) & 7)))
  173068. action = 2; /* a prior restart, so advance */
  173069. else
  173070. action = 1; /* desired restart or too far away */
  173071. }
  173072. TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
  173073. switch (action) {
  173074. case 1:
  173075. /* Discard marker and let entropy decoder resume processing. */
  173076. cinfo->unread_marker = 0;
  173077. return TRUE;
  173078. case 2:
  173079. /* Scan to the next marker, and repeat the decision loop. */
  173080. if (! next_marker(cinfo))
  173081. return FALSE;
  173082. marker = cinfo->unread_marker;
  173083. break;
  173084. case 3:
  173085. /* Return without advancing past this marker. */
  173086. /* Entropy decoder will be forced to process an empty segment. */
  173087. return TRUE;
  173088. }
  173089. } /* end loop */
  173090. }
  173091. /*
  173092. * Reset marker processing state to begin a fresh datastream.
  173093. */
  173094. METHODDEF(void)
  173095. reset_marker_reader (j_decompress_ptr cinfo)
  173096. {
  173097. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  173098. cinfo->comp_info = NULL; /* until allocated by get_sof */
  173099. cinfo->input_scan_number = 0; /* no SOS seen yet */
  173100. cinfo->unread_marker = 0; /* no pending marker */
  173101. marker->pub.saw_SOI = FALSE; /* set internal state too */
  173102. marker->pub.saw_SOF = FALSE;
  173103. marker->pub.discarded_bytes = 0;
  173104. marker->cur_marker = NULL;
  173105. }
  173106. /*
  173107. * Initialize the marker reader module.
  173108. * This is called only once, when the decompression object is created.
  173109. */
  173110. GLOBAL(void)
  173111. jinit_marker_reader (j_decompress_ptr cinfo)
  173112. {
  173113. my_marker_ptr2 marker;
  173114. int i;
  173115. /* Create subobject in permanent pool */
  173116. marker = (my_marker_ptr2)
  173117. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
  173118. SIZEOF(my_marker_reader));
  173119. cinfo->marker = (struct jpeg_marker_reader *) marker;
  173120. /* Initialize public method pointers */
  173121. marker->pub.reset_marker_reader = reset_marker_reader;
  173122. marker->pub.read_markers = read_markers;
  173123. marker->pub.read_restart_marker = read_restart_marker;
  173124. /* Initialize COM/APPn processing.
  173125. * By default, we examine and then discard APP0 and APP14,
  173126. * but simply discard COM and all other APPn.
  173127. */
  173128. marker->process_COM = skip_variable;
  173129. marker->length_limit_COM = 0;
  173130. for (i = 0; i < 16; i++) {
  173131. marker->process_APPn[i] = skip_variable;
  173132. marker->length_limit_APPn[i] = 0;
  173133. }
  173134. marker->process_APPn[0] = get_interesting_appn;
  173135. marker->process_APPn[14] = get_interesting_appn;
  173136. /* Reset marker processing state */
  173137. reset_marker_reader(cinfo);
  173138. }
  173139. /*
  173140. * Control saving of COM and APPn markers into marker_list.
  173141. */
  173142. #ifdef SAVE_MARKERS_SUPPORTED
  173143. GLOBAL(void)
  173144. jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
  173145. unsigned int length_limit)
  173146. {
  173147. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  173148. long maxlength;
  173149. jpeg_marker_parser_method processor;
  173150. /* Length limit mustn't be larger than what we can allocate
  173151. * (should only be a concern in a 16-bit environment).
  173152. */
  173153. maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
  173154. if (((long) length_limit) > maxlength)
  173155. length_limit = (unsigned int) maxlength;
  173156. /* Choose processor routine to use.
  173157. * APP0/APP14 have special requirements.
  173158. */
  173159. if (length_limit) {
  173160. processor = save_marker;
  173161. /* If saving APP0/APP14, save at least enough for our internal use. */
  173162. if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
  173163. length_limit = APP0_DATA_LEN;
  173164. else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
  173165. length_limit = APP14_DATA_LEN;
  173166. } else {
  173167. processor = skip_variable;
  173168. /* If discarding APP0/APP14, use our regular on-the-fly processor. */
  173169. if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
  173170. processor = get_interesting_appn;
  173171. }
  173172. if (marker_code == (int) M_COM) {
  173173. marker->process_COM = processor;
  173174. marker->length_limit_COM = length_limit;
  173175. } else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
  173176. marker->process_APPn[marker_code - (int) M_APP0] = processor;
  173177. marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
  173178. } else
  173179. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  173180. }
  173181. #endif /* SAVE_MARKERS_SUPPORTED */
  173182. /*
  173183. * Install a special processing method for COM or APPn markers.
  173184. */
  173185. GLOBAL(void)
  173186. jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
  173187. jpeg_marker_parser_method routine)
  173188. {
  173189. my_marker_ptr2 marker = (my_marker_ptr2) cinfo->marker;
  173190. if (marker_code == (int) M_COM)
  173191. marker->process_COM = routine;
  173192. else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
  173193. marker->process_APPn[marker_code - (int) M_APP0] = routine;
  173194. else
  173195. ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
  173196. }
  173197. /********* End of inlined file: jdmarker.c *********/
  173198. /********* Start of inlined file: jdmaster.c *********/
  173199. #define JPEG_INTERNALS
  173200. /* Private state */
  173201. typedef struct {
  173202. struct jpeg_decomp_master pub; /* public fields */
  173203. int pass_number; /* # of passes completed */
  173204. boolean using_merged_upsample; /* TRUE if using merged upsample/cconvert */
  173205. /* Saved references to initialized quantizer modules,
  173206. * in case we need to switch modes.
  173207. */
  173208. struct jpeg_color_quantizer * quantizer_1pass;
  173209. struct jpeg_color_quantizer * quantizer_2pass;
  173210. } my_decomp_master;
  173211. typedef my_decomp_master * my_master_ptr6;
  173212. /*
  173213. * Determine whether merged upsample/color conversion should be used.
  173214. * CRUCIAL: this must match the actual capabilities of jdmerge.c!
  173215. */
  173216. LOCAL(boolean)
  173217. use_merged_upsample (j_decompress_ptr cinfo)
  173218. {
  173219. #ifdef UPSAMPLE_MERGING_SUPPORTED
  173220. /* Merging is the equivalent of plain box-filter upsampling */
  173221. if (cinfo->do_fancy_upsampling || cinfo->CCIR601_sampling)
  173222. return FALSE;
  173223. /* jdmerge.c only supports YCC=>RGB color conversion */
  173224. if (cinfo->jpeg_color_space != JCS_YCbCr || cinfo->num_components != 3 ||
  173225. cinfo->out_color_space != JCS_RGB ||
  173226. cinfo->out_color_components != RGB_PIXELSIZE)
  173227. return FALSE;
  173228. /* and it only handles 2h1v or 2h2v sampling ratios */
  173229. if (cinfo->comp_info[0].h_samp_factor != 2 ||
  173230. cinfo->comp_info[1].h_samp_factor != 1 ||
  173231. cinfo->comp_info[2].h_samp_factor != 1 ||
  173232. cinfo->comp_info[0].v_samp_factor > 2 ||
  173233. cinfo->comp_info[1].v_samp_factor != 1 ||
  173234. cinfo->comp_info[2].v_samp_factor != 1)
  173235. return FALSE;
  173236. /* furthermore, it doesn't work if we've scaled the IDCTs differently */
  173237. if (cinfo->comp_info[0].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  173238. cinfo->comp_info[1].DCT_scaled_size != cinfo->min_DCT_scaled_size ||
  173239. cinfo->comp_info[2].DCT_scaled_size != cinfo->min_DCT_scaled_size)
  173240. return FALSE;
  173241. /* ??? also need to test for upsample-time rescaling, when & if supported */
  173242. return TRUE; /* by golly, it'll work... */
  173243. #else
  173244. return FALSE;
  173245. #endif
  173246. }
  173247. /*
  173248. * Compute output image dimensions and related values.
  173249. * NOTE: this is exported for possible use by application.
  173250. * Hence it mustn't do anything that can't be done twice.
  173251. * Also note that it may be called before the master module is initialized!
  173252. */
  173253. GLOBAL(void)
  173254. jpeg_calc_output_dimensions (j_decompress_ptr cinfo)
  173255. /* Do computations that are needed before master selection phase */
  173256. {
  173257. #ifdef IDCT_SCALING_SUPPORTED
  173258. int ci;
  173259. jpeg_component_info *compptr;
  173260. #endif
  173261. /* Prevent application from calling me at wrong times */
  173262. if (cinfo->global_state != DSTATE_READY)
  173263. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  173264. #ifdef IDCT_SCALING_SUPPORTED
  173265. /* Compute actual output image dimensions and DCT scaling choices. */
  173266. if (cinfo->scale_num * 8 <= cinfo->scale_denom) {
  173267. /* Provide 1/8 scaling */
  173268. cinfo->output_width = (JDIMENSION)
  173269. jdiv_round_up((long) cinfo->image_width, 8L);
  173270. cinfo->output_height = (JDIMENSION)
  173271. jdiv_round_up((long) cinfo->image_height, 8L);
  173272. cinfo->min_DCT_scaled_size = 1;
  173273. } else if (cinfo->scale_num * 4 <= cinfo->scale_denom) {
  173274. /* Provide 1/4 scaling */
  173275. cinfo->output_width = (JDIMENSION)
  173276. jdiv_round_up((long) cinfo->image_width, 4L);
  173277. cinfo->output_height = (JDIMENSION)
  173278. jdiv_round_up((long) cinfo->image_height, 4L);
  173279. cinfo->min_DCT_scaled_size = 2;
  173280. } else if (cinfo->scale_num * 2 <= cinfo->scale_denom) {
  173281. /* Provide 1/2 scaling */
  173282. cinfo->output_width = (JDIMENSION)
  173283. jdiv_round_up((long) cinfo->image_width, 2L);
  173284. cinfo->output_height = (JDIMENSION)
  173285. jdiv_round_up((long) cinfo->image_height, 2L);
  173286. cinfo->min_DCT_scaled_size = 4;
  173287. } else {
  173288. /* Provide 1/1 scaling */
  173289. cinfo->output_width = cinfo->image_width;
  173290. cinfo->output_height = cinfo->image_height;
  173291. cinfo->min_DCT_scaled_size = DCTSIZE;
  173292. }
  173293. /* In selecting the actual DCT scaling for each component, we try to
  173294. * scale up the chroma components via IDCT scaling rather than upsampling.
  173295. * This saves time if the upsampler gets to use 1:1 scaling.
  173296. * Note this code assumes that the supported DCT scalings are powers of 2.
  173297. */
  173298. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173299. ci++, compptr++) {
  173300. int ssize = cinfo->min_DCT_scaled_size;
  173301. while (ssize < DCTSIZE &&
  173302. (compptr->h_samp_factor * ssize * 2 <=
  173303. cinfo->max_h_samp_factor * cinfo->min_DCT_scaled_size) &&
  173304. (compptr->v_samp_factor * ssize * 2 <=
  173305. cinfo->max_v_samp_factor * cinfo->min_DCT_scaled_size)) {
  173306. ssize = ssize * 2;
  173307. }
  173308. compptr->DCT_scaled_size = ssize;
  173309. }
  173310. /* Recompute downsampled dimensions of components;
  173311. * application needs to know these if using raw downsampled data.
  173312. */
  173313. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  173314. ci++, compptr++) {
  173315. /* Size in samples, after IDCT scaling */
  173316. compptr->downsampled_width = (JDIMENSION)
  173317. jdiv_round_up((long) cinfo->image_width *
  173318. (long) (compptr->h_samp_factor * compptr->DCT_scaled_size),
  173319. (long) (cinfo->max_h_samp_factor * DCTSIZE));
  173320. compptr->downsampled_height = (JDIMENSION)
  173321. jdiv_round_up((long) cinfo->image_height *
  173322. (long) (compptr->v_samp_factor * compptr->DCT_scaled_size),
  173323. (long) (cinfo->max_v_samp_factor * DCTSIZE));
  173324. }
  173325. #else /* !IDCT_SCALING_SUPPORTED */
  173326. /* Hardwire it to "no scaling" */
  173327. cinfo->output_width = cinfo->image_width;
  173328. cinfo->output_height = cinfo->image_height;
  173329. /* jdinput.c has already initialized DCT_scaled_size to DCTSIZE,
  173330. * and has computed unscaled downsampled_width and downsampled_height.
  173331. */
  173332. #endif /* IDCT_SCALING_SUPPORTED */
  173333. /* Report number of components in selected colorspace. */
  173334. /* Probably this should be in the color conversion module... */
  173335. switch (cinfo->out_color_space) {
  173336. case JCS_GRAYSCALE:
  173337. cinfo->out_color_components = 1;
  173338. break;
  173339. case JCS_RGB:
  173340. #if RGB_PIXELSIZE != 3
  173341. cinfo->out_color_components = RGB_PIXELSIZE;
  173342. break;
  173343. #endif /* else share code with YCbCr */
  173344. case JCS_YCbCr:
  173345. cinfo->out_color_components = 3;
  173346. break;
  173347. case JCS_CMYK:
  173348. case JCS_YCCK:
  173349. cinfo->out_color_components = 4;
  173350. break;
  173351. default: /* else must be same colorspace as in file */
  173352. cinfo->out_color_components = cinfo->num_components;
  173353. break;
  173354. }
  173355. cinfo->output_components = (cinfo->quantize_colors ? 1 :
  173356. cinfo->out_color_components);
  173357. /* See if upsampler will want to emit more than one row at a time */
  173358. if (use_merged_upsample(cinfo))
  173359. cinfo->rec_outbuf_height = cinfo->max_v_samp_factor;
  173360. else
  173361. cinfo->rec_outbuf_height = 1;
  173362. }
  173363. /*
  173364. * Several decompression processes need to range-limit values to the range
  173365. * 0..MAXJSAMPLE; the input value may fall somewhat outside this range
  173366. * due to noise introduced by quantization, roundoff error, etc. These
  173367. * processes are inner loops and need to be as fast as possible. On most
  173368. * machines, particularly CPUs with pipelines or instruction prefetch,
  173369. * a (subscript-check-less) C table lookup
  173370. * x = sample_range_limit[x];
  173371. * is faster than explicit tests
  173372. * if (x < 0) x = 0;
  173373. * else if (x > MAXJSAMPLE) x = MAXJSAMPLE;
  173374. * These processes all use a common table prepared by the routine below.
  173375. *
  173376. * For most steps we can mathematically guarantee that the initial value
  173377. * of x is within MAXJSAMPLE+1 of the legal range, so a table running from
  173378. * -(MAXJSAMPLE+1) to 2*MAXJSAMPLE+1 is sufficient. But for the initial
  173379. * limiting step (just after the IDCT), a wildly out-of-range value is
  173380. * possible if the input data is corrupt. To avoid any chance of indexing
  173381. * off the end of memory and getting a bad-pointer trap, we perform the
  173382. * post-IDCT limiting thus:
  173383. * x = range_limit[x & MASK];
  173384. * where MASK is 2 bits wider than legal sample data, ie 10 bits for 8-bit
  173385. * samples. Under normal circumstances this is more than enough range and
  173386. * a correct output will be generated; with bogus input data the mask will
  173387. * cause wraparound, and we will safely generate a bogus-but-in-range output.
  173388. * For the post-IDCT step, we want to convert the data from signed to unsigned
  173389. * representation by adding CENTERJSAMPLE at the same time that we limit it.
  173390. * So the post-IDCT limiting table ends up looking like this:
  173391. * CENTERJSAMPLE,CENTERJSAMPLE+1,...,MAXJSAMPLE,
  173392. * MAXJSAMPLE (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  173393. * 0 (repeat 2*(MAXJSAMPLE+1)-CENTERJSAMPLE times),
  173394. * 0,1,...,CENTERJSAMPLE-1
  173395. * Negative inputs select values from the upper half of the table after
  173396. * masking.
  173397. *
  173398. * We can save some space by overlapping the start of the post-IDCT table
  173399. * with the simpler range limiting table. The post-IDCT table begins at
  173400. * sample_range_limit + CENTERJSAMPLE.
  173401. *
  173402. * Note that the table is allocated in near data space on PCs; it's small
  173403. * enough and used often enough to justify this.
  173404. */
  173405. LOCAL(void)
  173406. prepare_range_limit_table (j_decompress_ptr cinfo)
  173407. /* Allocate and fill in the sample_range_limit table */
  173408. {
  173409. JSAMPLE * table;
  173410. int i;
  173411. table = (JSAMPLE *)
  173412. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173413. (5 * (MAXJSAMPLE+1) + CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  173414. table += (MAXJSAMPLE+1); /* allow negative subscripts of simple table */
  173415. cinfo->sample_range_limit = table;
  173416. /* First segment of "simple" table: limit[x] = 0 for x < 0 */
  173417. MEMZERO(table - (MAXJSAMPLE+1), (MAXJSAMPLE+1) * SIZEOF(JSAMPLE));
  173418. /* Main part of "simple" table: limit[x] = x */
  173419. for (i = 0; i <= MAXJSAMPLE; i++)
  173420. table[i] = (JSAMPLE) i;
  173421. table += CENTERJSAMPLE; /* Point to where post-IDCT table starts */
  173422. /* End of simple table, rest of first half of post-IDCT table */
  173423. for (i = CENTERJSAMPLE; i < 2*(MAXJSAMPLE+1); i++)
  173424. table[i] = MAXJSAMPLE;
  173425. /* Second half of post-IDCT table */
  173426. MEMZERO(table + (2 * (MAXJSAMPLE+1)),
  173427. (2 * (MAXJSAMPLE+1) - CENTERJSAMPLE) * SIZEOF(JSAMPLE));
  173428. MEMCOPY(table + (4 * (MAXJSAMPLE+1) - CENTERJSAMPLE),
  173429. cinfo->sample_range_limit, CENTERJSAMPLE * SIZEOF(JSAMPLE));
  173430. }
  173431. /*
  173432. * Master selection of decompression modules.
  173433. * This is done once at jpeg_start_decompress time. We determine
  173434. * which modules will be used and give them appropriate initialization calls.
  173435. * We also initialize the decompressor input side to begin consuming data.
  173436. *
  173437. * Since jpeg_read_header has finished, we know what is in the SOF
  173438. * and (first) SOS markers. We also have all the application parameter
  173439. * settings.
  173440. */
  173441. LOCAL(void)
  173442. master_selection (j_decompress_ptr cinfo)
  173443. {
  173444. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  173445. boolean use_c_buffer;
  173446. long samplesperrow;
  173447. JDIMENSION jd_samplesperrow;
  173448. /* Initialize dimensions and other stuff */
  173449. jpeg_calc_output_dimensions(cinfo);
  173450. prepare_range_limit_table(cinfo);
  173451. /* Width of an output scanline must be representable as JDIMENSION. */
  173452. samplesperrow = (long) cinfo->output_width * (long) cinfo->out_color_components;
  173453. jd_samplesperrow = (JDIMENSION) samplesperrow;
  173454. if ((long) jd_samplesperrow != samplesperrow)
  173455. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  173456. /* Initialize my private state */
  173457. master->pass_number = 0;
  173458. master->using_merged_upsample = use_merged_upsample(cinfo);
  173459. /* Color quantizer selection */
  173460. master->quantizer_1pass = NULL;
  173461. master->quantizer_2pass = NULL;
  173462. /* No mode changes if not using buffered-image mode. */
  173463. if (! cinfo->quantize_colors || ! cinfo->buffered_image) {
  173464. cinfo->enable_1pass_quant = FALSE;
  173465. cinfo->enable_external_quant = FALSE;
  173466. cinfo->enable_2pass_quant = FALSE;
  173467. }
  173468. if (cinfo->quantize_colors) {
  173469. if (cinfo->raw_data_out)
  173470. ERREXIT(cinfo, JERR_NOTIMPL);
  173471. /* 2-pass quantizer only works in 3-component color space. */
  173472. if (cinfo->out_color_components != 3) {
  173473. cinfo->enable_1pass_quant = TRUE;
  173474. cinfo->enable_external_quant = FALSE;
  173475. cinfo->enable_2pass_quant = FALSE;
  173476. cinfo->colormap = NULL;
  173477. } else if (cinfo->colormap != NULL) {
  173478. cinfo->enable_external_quant = TRUE;
  173479. } else if (cinfo->two_pass_quantize) {
  173480. cinfo->enable_2pass_quant = TRUE;
  173481. } else {
  173482. cinfo->enable_1pass_quant = TRUE;
  173483. }
  173484. if (cinfo->enable_1pass_quant) {
  173485. #ifdef QUANT_1PASS_SUPPORTED
  173486. jinit_1pass_quantizer(cinfo);
  173487. master->quantizer_1pass = cinfo->cquantize;
  173488. #else
  173489. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173490. #endif
  173491. }
  173492. /* We use the 2-pass code to map to external colormaps. */
  173493. if (cinfo->enable_2pass_quant || cinfo->enable_external_quant) {
  173494. #ifdef QUANT_2PASS_SUPPORTED
  173495. jinit_2pass_quantizer(cinfo);
  173496. master->quantizer_2pass = cinfo->cquantize;
  173497. #else
  173498. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173499. #endif
  173500. }
  173501. /* If both quantizers are initialized, the 2-pass one is left active;
  173502. * this is necessary for starting with quantization to an external map.
  173503. */
  173504. }
  173505. /* Post-processing: in particular, color conversion first */
  173506. if (! cinfo->raw_data_out) {
  173507. if (master->using_merged_upsample) {
  173508. #ifdef UPSAMPLE_MERGING_SUPPORTED
  173509. jinit_merged_upsampler(cinfo); /* does color conversion too */
  173510. #else
  173511. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173512. #endif
  173513. } else {
  173514. jinit_color_deconverter(cinfo);
  173515. jinit_upsampler(cinfo);
  173516. }
  173517. jinit_d_post_controller(cinfo, cinfo->enable_2pass_quant);
  173518. }
  173519. /* Inverse DCT */
  173520. jinit_inverse_dct(cinfo);
  173521. /* Entropy decoding: either Huffman or arithmetic coding. */
  173522. if (cinfo->arith_code) {
  173523. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  173524. } else {
  173525. if (cinfo->progressive_mode) {
  173526. #ifdef D_PROGRESSIVE_SUPPORTED
  173527. jinit_phuff_decoder(cinfo);
  173528. #else
  173529. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173530. #endif
  173531. } else
  173532. jinit_huff_decoder(cinfo);
  173533. }
  173534. /* Initialize principal buffer controllers. */
  173535. use_c_buffer = cinfo->inputctl->has_multiple_scans || cinfo->buffered_image;
  173536. jinit_d_coef_controller(cinfo, use_c_buffer);
  173537. if (! cinfo->raw_data_out)
  173538. jinit_d_main_controller(cinfo, FALSE /* never need full buffer here */);
  173539. /* We can now tell the memory manager to allocate virtual arrays. */
  173540. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  173541. /* Initialize input side of decompressor to consume first scan. */
  173542. (*cinfo->inputctl->start_input_pass) (cinfo);
  173543. #ifdef D_MULTISCAN_FILES_SUPPORTED
  173544. /* If jpeg_start_decompress will read the whole file, initialize
  173545. * progress monitoring appropriately. The input step is counted
  173546. * as one pass.
  173547. */
  173548. if (cinfo->progress != NULL && ! cinfo->buffered_image &&
  173549. cinfo->inputctl->has_multiple_scans) {
  173550. int nscans;
  173551. /* Estimate number of scans to set pass_limit. */
  173552. if (cinfo->progressive_mode) {
  173553. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  173554. nscans = 2 + 3 * cinfo->num_components;
  173555. } else {
  173556. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  173557. nscans = cinfo->num_components;
  173558. }
  173559. cinfo->progress->pass_counter = 0L;
  173560. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  173561. cinfo->progress->completed_passes = 0;
  173562. cinfo->progress->total_passes = (cinfo->enable_2pass_quant ? 3 : 2);
  173563. /* Count the input pass as done */
  173564. master->pass_number++;
  173565. }
  173566. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  173567. }
  173568. /*
  173569. * Per-pass setup.
  173570. * This is called at the beginning of each output pass. We determine which
  173571. * modules will be active during this pass and give them appropriate
  173572. * start_pass calls. We also set is_dummy_pass to indicate whether this
  173573. * is a "real" output pass or a dummy pass for color quantization.
  173574. * (In the latter case, jdapistd.c will crank the pass to completion.)
  173575. */
  173576. METHODDEF(void)
  173577. prepare_for_output_pass (j_decompress_ptr cinfo)
  173578. {
  173579. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  173580. if (master->pub.is_dummy_pass) {
  173581. #ifdef QUANT_2PASS_SUPPORTED
  173582. /* Final pass of 2-pass quantization */
  173583. master->pub.is_dummy_pass = FALSE;
  173584. (*cinfo->cquantize->start_pass) (cinfo, FALSE);
  173585. (*cinfo->post->start_pass) (cinfo, JBUF_CRANK_DEST);
  173586. (*cinfo->main->start_pass) (cinfo, JBUF_CRANK_DEST);
  173587. #else
  173588. ERREXIT(cinfo, JERR_NOT_COMPILED);
  173589. #endif /* QUANT_2PASS_SUPPORTED */
  173590. } else {
  173591. if (cinfo->quantize_colors && cinfo->colormap == NULL) {
  173592. /* Select new quantization method */
  173593. if (cinfo->two_pass_quantize && cinfo->enable_2pass_quant) {
  173594. cinfo->cquantize = master->quantizer_2pass;
  173595. master->pub.is_dummy_pass = TRUE;
  173596. } else if (cinfo->enable_1pass_quant) {
  173597. cinfo->cquantize = master->quantizer_1pass;
  173598. } else {
  173599. ERREXIT(cinfo, JERR_MODE_CHANGE);
  173600. }
  173601. }
  173602. (*cinfo->idct->start_pass) (cinfo);
  173603. (*cinfo->coef->start_output_pass) (cinfo);
  173604. if (! cinfo->raw_data_out) {
  173605. if (! master->using_merged_upsample)
  173606. (*cinfo->cconvert->start_pass) (cinfo);
  173607. (*cinfo->upsample->start_pass) (cinfo);
  173608. if (cinfo->quantize_colors)
  173609. (*cinfo->cquantize->start_pass) (cinfo, master->pub.is_dummy_pass);
  173610. (*cinfo->post->start_pass) (cinfo,
  173611. (master->pub.is_dummy_pass ? JBUF_SAVE_AND_PASS : JBUF_PASS_THRU));
  173612. (*cinfo->main->start_pass) (cinfo, JBUF_PASS_THRU);
  173613. }
  173614. }
  173615. /* Set up progress monitor's pass info if present */
  173616. if (cinfo->progress != NULL) {
  173617. cinfo->progress->completed_passes = master->pass_number;
  173618. cinfo->progress->total_passes = master->pass_number +
  173619. (master->pub.is_dummy_pass ? 2 : 1);
  173620. /* In buffered-image mode, we assume one more output pass if EOI not
  173621. * yet reached, but no more passes if EOI has been reached.
  173622. */
  173623. if (cinfo->buffered_image && ! cinfo->inputctl->eoi_reached) {
  173624. cinfo->progress->total_passes += (cinfo->enable_2pass_quant ? 2 : 1);
  173625. }
  173626. }
  173627. }
  173628. /*
  173629. * Finish up at end of an output pass.
  173630. */
  173631. METHODDEF(void)
  173632. finish_output_pass (j_decompress_ptr cinfo)
  173633. {
  173634. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  173635. if (cinfo->quantize_colors)
  173636. (*cinfo->cquantize->finish_pass) (cinfo);
  173637. master->pass_number++;
  173638. }
  173639. #ifdef D_MULTISCAN_FILES_SUPPORTED
  173640. /*
  173641. * Switch to a new external colormap between output passes.
  173642. */
  173643. GLOBAL(void)
  173644. jpeg_new_colormap (j_decompress_ptr cinfo)
  173645. {
  173646. my_master_ptr6 master = (my_master_ptr6) cinfo->master;
  173647. /* Prevent application from calling me at wrong times */
  173648. if (cinfo->global_state != DSTATE_BUFIMAGE)
  173649. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  173650. if (cinfo->quantize_colors && cinfo->enable_external_quant &&
  173651. cinfo->colormap != NULL) {
  173652. /* Select 2-pass quantizer for external colormap use */
  173653. cinfo->cquantize = master->quantizer_2pass;
  173654. /* Notify quantizer of colormap change */
  173655. (*cinfo->cquantize->new_color_map) (cinfo);
  173656. master->pub.is_dummy_pass = FALSE; /* just in case */
  173657. } else
  173658. ERREXIT(cinfo, JERR_MODE_CHANGE);
  173659. }
  173660. #endif /* D_MULTISCAN_FILES_SUPPORTED */
  173661. /*
  173662. * Initialize master decompression control and select active modules.
  173663. * This is performed at the start of jpeg_start_decompress.
  173664. */
  173665. GLOBAL(void)
  173666. jinit_master_decompress (j_decompress_ptr cinfo)
  173667. {
  173668. my_master_ptr6 master;
  173669. master = (my_master_ptr6)
  173670. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173671. SIZEOF(my_decomp_master));
  173672. cinfo->master = (struct jpeg_decomp_master *) master;
  173673. master->pub.prepare_for_output_pass = prepare_for_output_pass;
  173674. master->pub.finish_output_pass = finish_output_pass;
  173675. master->pub.is_dummy_pass = FALSE;
  173676. master_selection(cinfo);
  173677. }
  173678. /********* End of inlined file: jdmaster.c *********/
  173679. #undef FIX
  173680. /********* Start of inlined file: jdmerge.c *********/
  173681. #define JPEG_INTERNALS
  173682. #ifdef UPSAMPLE_MERGING_SUPPORTED
  173683. /* Private subobject */
  173684. typedef struct {
  173685. struct jpeg_upsampler pub; /* public fields */
  173686. /* Pointer to routine to do actual upsampling/conversion of one row group */
  173687. JMETHOD(void, upmethod, (j_decompress_ptr cinfo,
  173688. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173689. JSAMPARRAY output_buf));
  173690. /* Private state for YCC->RGB conversion */
  173691. int * Cr_r_tab; /* => table for Cr to R conversion */
  173692. int * Cb_b_tab; /* => table for Cb to B conversion */
  173693. INT32 * Cr_g_tab; /* => table for Cr to G conversion */
  173694. INT32 * Cb_g_tab; /* => table for Cb to G conversion */
  173695. /* For 2:1 vertical sampling, we produce two output rows at a time.
  173696. * We need a "spare" row buffer to hold the second output row if the
  173697. * application provides just a one-row buffer; we also use the spare
  173698. * to discard the dummy last row if the image height is odd.
  173699. */
  173700. JSAMPROW spare_row;
  173701. boolean spare_full; /* T if spare buffer is occupied */
  173702. JDIMENSION out_row_width; /* samples per output row */
  173703. JDIMENSION rows_to_go; /* counts rows remaining in image */
  173704. } my_upsampler;
  173705. typedef my_upsampler * my_upsample_ptr;
  173706. #define SCALEBITS 16 /* speediest right-shift on some machines */
  173707. #define ONE_HALF ((INT32) 1 << (SCALEBITS-1))
  173708. #define FIX(x) ((INT32) ((x) * (1L<<SCALEBITS) + 0.5))
  173709. /*
  173710. * Initialize tables for YCC->RGB colorspace conversion.
  173711. * This is taken directly from jdcolor.c; see that file for more info.
  173712. */
  173713. LOCAL(void)
  173714. build_ycc_rgb_table2 (j_decompress_ptr cinfo)
  173715. {
  173716. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173717. int i;
  173718. INT32 x;
  173719. SHIFT_TEMPS
  173720. upsample->Cr_r_tab = (int *)
  173721. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173722. (MAXJSAMPLE+1) * SIZEOF(int));
  173723. upsample->Cb_b_tab = (int *)
  173724. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173725. (MAXJSAMPLE+1) * SIZEOF(int));
  173726. upsample->Cr_g_tab = (INT32 *)
  173727. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173728. (MAXJSAMPLE+1) * SIZEOF(INT32));
  173729. upsample->Cb_g_tab = (INT32 *)
  173730. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173731. (MAXJSAMPLE+1) * SIZEOF(INT32));
  173732. for (i = 0, x = -CENTERJSAMPLE; i <= MAXJSAMPLE; i++, x++) {
  173733. /* i is the actual input pixel value, in the range 0..MAXJSAMPLE */
  173734. /* The Cb or Cr value we are thinking of is x = i - CENTERJSAMPLE */
  173735. /* Cr=>R value is nearest int to 1.40200 * x */
  173736. upsample->Cr_r_tab[i] = (int)
  173737. RIGHT_SHIFT(FIX(1.40200) * x + ONE_HALF, SCALEBITS);
  173738. /* Cb=>B value is nearest int to 1.77200 * x */
  173739. upsample->Cb_b_tab[i] = (int)
  173740. RIGHT_SHIFT(FIX(1.77200) * x + ONE_HALF, SCALEBITS);
  173741. /* Cr=>G value is scaled-up -0.71414 * x */
  173742. upsample->Cr_g_tab[i] = (- FIX(0.71414)) * x;
  173743. /* Cb=>G value is scaled-up -0.34414 * x */
  173744. /* We also add in ONE_HALF so that need not do it in inner loop */
  173745. upsample->Cb_g_tab[i] = (- FIX(0.34414)) * x + ONE_HALF;
  173746. }
  173747. }
  173748. /*
  173749. * Initialize for an upsampling pass.
  173750. */
  173751. METHODDEF(void)
  173752. start_pass_merged_upsample (j_decompress_ptr cinfo)
  173753. {
  173754. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173755. /* Mark the spare buffer empty */
  173756. upsample->spare_full = FALSE;
  173757. /* Initialize total-height counter for detecting bottom of image */
  173758. upsample->rows_to_go = cinfo->output_height;
  173759. }
  173760. /*
  173761. * Control routine to do upsampling (and color conversion).
  173762. *
  173763. * The control routine just handles the row buffering considerations.
  173764. */
  173765. METHODDEF(void)
  173766. merged_2v_upsample (j_decompress_ptr cinfo,
  173767. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173768. JDIMENSION in_row_groups_avail,
  173769. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173770. JDIMENSION out_rows_avail)
  173771. /* 2:1 vertical sampling case: may need a spare row. */
  173772. {
  173773. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173774. JSAMPROW work_ptrs[2];
  173775. JDIMENSION num_rows; /* number of rows returned to caller */
  173776. if (upsample->spare_full) {
  173777. /* If we have a spare row saved from a previous cycle, just return it. */
  173778. jcopy_sample_rows(& upsample->spare_row, 0, output_buf + *out_row_ctr, 0,
  173779. 1, upsample->out_row_width);
  173780. num_rows = 1;
  173781. upsample->spare_full = FALSE;
  173782. } else {
  173783. /* Figure number of rows to return to caller. */
  173784. num_rows = 2;
  173785. /* Not more than the distance to the end of the image. */
  173786. if (num_rows > upsample->rows_to_go)
  173787. num_rows = upsample->rows_to_go;
  173788. /* And not more than what the client can accept: */
  173789. out_rows_avail -= *out_row_ctr;
  173790. if (num_rows > out_rows_avail)
  173791. num_rows = out_rows_avail;
  173792. /* Create output pointer array for upsampler. */
  173793. work_ptrs[0] = output_buf[*out_row_ctr];
  173794. if (num_rows > 1) {
  173795. work_ptrs[1] = output_buf[*out_row_ctr + 1];
  173796. } else {
  173797. work_ptrs[1] = upsample->spare_row;
  173798. upsample->spare_full = TRUE;
  173799. }
  173800. /* Now do the upsampling. */
  173801. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr, work_ptrs);
  173802. }
  173803. /* Adjust counts */
  173804. *out_row_ctr += num_rows;
  173805. upsample->rows_to_go -= num_rows;
  173806. /* When the buffer is emptied, declare this input row group consumed */
  173807. if (! upsample->spare_full)
  173808. (*in_row_group_ctr)++;
  173809. }
  173810. METHODDEF(void)
  173811. merged_1v_upsample (j_decompress_ptr cinfo,
  173812. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  173813. JDIMENSION in_row_groups_avail,
  173814. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  173815. JDIMENSION out_rows_avail)
  173816. /* 1:1 vertical sampling case: much easier, never need a spare row. */
  173817. {
  173818. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173819. /* Just do the upsampling. */
  173820. (*upsample->upmethod) (cinfo, input_buf, *in_row_group_ctr,
  173821. output_buf + *out_row_ctr);
  173822. /* Adjust counts */
  173823. (*out_row_ctr)++;
  173824. (*in_row_group_ctr)++;
  173825. }
  173826. /*
  173827. * These are the routines invoked by the control routines to do
  173828. * the actual upsampling/conversion. One row group is processed per call.
  173829. *
  173830. * Note: since we may be writing directly into application-supplied buffers,
  173831. * we have to be honest about the output width; we can't assume the buffer
  173832. * has been rounded up to an even width.
  173833. */
  173834. /*
  173835. * Upsample and color convert for the case of 2:1 horizontal and 1:1 vertical.
  173836. */
  173837. METHODDEF(void)
  173838. h2v1_merged_upsample (j_decompress_ptr cinfo,
  173839. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173840. JSAMPARRAY output_buf)
  173841. {
  173842. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173843. register int y, cred, cgreen, cblue;
  173844. int cb, cr;
  173845. register JSAMPROW outptr;
  173846. JSAMPROW inptr0, inptr1, inptr2;
  173847. JDIMENSION col;
  173848. /* copy these pointers into registers if possible */
  173849. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173850. int * Crrtab = upsample->Cr_r_tab;
  173851. int * Cbbtab = upsample->Cb_b_tab;
  173852. INT32 * Crgtab = upsample->Cr_g_tab;
  173853. INT32 * Cbgtab = upsample->Cb_g_tab;
  173854. SHIFT_TEMPS
  173855. inptr0 = input_buf[0][in_row_group_ctr];
  173856. inptr1 = input_buf[1][in_row_group_ctr];
  173857. inptr2 = input_buf[2][in_row_group_ctr];
  173858. outptr = output_buf[0];
  173859. /* Loop for each pair of output pixels */
  173860. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173861. /* Do the chroma part of the calculation */
  173862. cb = GETJSAMPLE(*inptr1++);
  173863. cr = GETJSAMPLE(*inptr2++);
  173864. cred = Crrtab[cr];
  173865. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173866. cblue = Cbbtab[cb];
  173867. /* Fetch 2 Y values and emit 2 pixels */
  173868. y = GETJSAMPLE(*inptr0++);
  173869. outptr[RGB_RED] = range_limit[y + cred];
  173870. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173871. outptr[RGB_BLUE] = range_limit[y + cblue];
  173872. outptr += RGB_PIXELSIZE;
  173873. y = GETJSAMPLE(*inptr0++);
  173874. outptr[RGB_RED] = range_limit[y + cred];
  173875. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173876. outptr[RGB_BLUE] = range_limit[y + cblue];
  173877. outptr += RGB_PIXELSIZE;
  173878. }
  173879. /* If image width is odd, do the last output column separately */
  173880. if (cinfo->output_width & 1) {
  173881. cb = GETJSAMPLE(*inptr1);
  173882. cr = GETJSAMPLE(*inptr2);
  173883. cred = Crrtab[cr];
  173884. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173885. cblue = Cbbtab[cb];
  173886. y = GETJSAMPLE(*inptr0);
  173887. outptr[RGB_RED] = range_limit[y + cred];
  173888. outptr[RGB_GREEN] = range_limit[y + cgreen];
  173889. outptr[RGB_BLUE] = range_limit[y + cblue];
  173890. }
  173891. }
  173892. /*
  173893. * Upsample and color convert for the case of 2:1 horizontal and 2:1 vertical.
  173894. */
  173895. METHODDEF(void)
  173896. h2v2_merged_upsample (j_decompress_ptr cinfo,
  173897. JSAMPIMAGE input_buf, JDIMENSION in_row_group_ctr,
  173898. JSAMPARRAY output_buf)
  173899. {
  173900. my_upsample_ptr upsample = (my_upsample_ptr) cinfo->upsample;
  173901. register int y, cred, cgreen, cblue;
  173902. int cb, cr;
  173903. register JSAMPROW outptr0, outptr1;
  173904. JSAMPROW inptr00, inptr01, inptr1, inptr2;
  173905. JDIMENSION col;
  173906. /* copy these pointers into registers if possible */
  173907. register JSAMPLE * range_limit = cinfo->sample_range_limit;
  173908. int * Crrtab = upsample->Cr_r_tab;
  173909. int * Cbbtab = upsample->Cb_b_tab;
  173910. INT32 * Crgtab = upsample->Cr_g_tab;
  173911. INT32 * Cbgtab = upsample->Cb_g_tab;
  173912. SHIFT_TEMPS
  173913. inptr00 = input_buf[0][in_row_group_ctr*2];
  173914. inptr01 = input_buf[0][in_row_group_ctr*2 + 1];
  173915. inptr1 = input_buf[1][in_row_group_ctr];
  173916. inptr2 = input_buf[2][in_row_group_ctr];
  173917. outptr0 = output_buf[0];
  173918. outptr1 = output_buf[1];
  173919. /* Loop for each group of output pixels */
  173920. for (col = cinfo->output_width >> 1; col > 0; col--) {
  173921. /* Do the chroma part of the calculation */
  173922. cb = GETJSAMPLE(*inptr1++);
  173923. cr = GETJSAMPLE(*inptr2++);
  173924. cred = Crrtab[cr];
  173925. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173926. cblue = Cbbtab[cb];
  173927. /* Fetch 4 Y values and emit 4 pixels */
  173928. y = GETJSAMPLE(*inptr00++);
  173929. outptr0[RGB_RED] = range_limit[y + cred];
  173930. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173931. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173932. outptr0 += RGB_PIXELSIZE;
  173933. y = GETJSAMPLE(*inptr00++);
  173934. outptr0[RGB_RED] = range_limit[y + cred];
  173935. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173936. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173937. outptr0 += RGB_PIXELSIZE;
  173938. y = GETJSAMPLE(*inptr01++);
  173939. outptr1[RGB_RED] = range_limit[y + cred];
  173940. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173941. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173942. outptr1 += RGB_PIXELSIZE;
  173943. y = GETJSAMPLE(*inptr01++);
  173944. outptr1[RGB_RED] = range_limit[y + cred];
  173945. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173946. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173947. outptr1 += RGB_PIXELSIZE;
  173948. }
  173949. /* If image width is odd, do the last output column separately */
  173950. if (cinfo->output_width & 1) {
  173951. cb = GETJSAMPLE(*inptr1);
  173952. cr = GETJSAMPLE(*inptr2);
  173953. cred = Crrtab[cr];
  173954. cgreen = (int) RIGHT_SHIFT(Cbgtab[cb] + Crgtab[cr], SCALEBITS);
  173955. cblue = Cbbtab[cb];
  173956. y = GETJSAMPLE(*inptr00);
  173957. outptr0[RGB_RED] = range_limit[y + cred];
  173958. outptr0[RGB_GREEN] = range_limit[y + cgreen];
  173959. outptr0[RGB_BLUE] = range_limit[y + cblue];
  173960. y = GETJSAMPLE(*inptr01);
  173961. outptr1[RGB_RED] = range_limit[y + cred];
  173962. outptr1[RGB_GREEN] = range_limit[y + cgreen];
  173963. outptr1[RGB_BLUE] = range_limit[y + cblue];
  173964. }
  173965. }
  173966. /*
  173967. * Module initialization routine for merged upsampling/color conversion.
  173968. *
  173969. * NB: this is called under the conditions determined by use_merged_upsample()
  173970. * in jdmaster.c. That routine MUST correspond to the actual capabilities
  173971. * of this module; no safety checks are made here.
  173972. */
  173973. GLOBAL(void)
  173974. jinit_merged_upsampler (j_decompress_ptr cinfo)
  173975. {
  173976. my_upsample_ptr upsample;
  173977. upsample = (my_upsample_ptr)
  173978. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173979. SIZEOF(my_upsampler));
  173980. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  173981. upsample->pub.start_pass = start_pass_merged_upsample;
  173982. upsample->pub.need_context_rows = FALSE;
  173983. upsample->out_row_width = cinfo->output_width * cinfo->out_color_components;
  173984. if (cinfo->max_v_samp_factor == 2) {
  173985. upsample->pub.upsample = merged_2v_upsample;
  173986. upsample->upmethod = h2v2_merged_upsample;
  173987. /* Allocate a spare row buffer */
  173988. upsample->spare_row = (JSAMPROW)
  173989. (*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  173990. (size_t) (upsample->out_row_width * SIZEOF(JSAMPLE)));
  173991. } else {
  173992. upsample->pub.upsample = merged_1v_upsample;
  173993. upsample->upmethod = h2v1_merged_upsample;
  173994. /* No spare row needed */
  173995. upsample->spare_row = NULL;
  173996. }
  173997. build_ycc_rgb_table2(cinfo);
  173998. }
  173999. #endif /* UPSAMPLE_MERGING_SUPPORTED */
  174000. /********* End of inlined file: jdmerge.c *********/
  174001. #undef ASSIGN_STATE
  174002. /********* Start of inlined file: jdphuff.c *********/
  174003. #define JPEG_INTERNALS
  174004. #ifdef D_PROGRESSIVE_SUPPORTED
  174005. /*
  174006. * Expanded entropy decoder object for progressive Huffman decoding.
  174007. *
  174008. * The savable_state subrecord contains fields that change within an MCU,
  174009. * but must not be updated permanently until we complete the MCU.
  174010. */
  174011. typedef struct {
  174012. unsigned int EOBRUN; /* remaining EOBs in EOBRUN */
  174013. int last_dc_val[MAX_COMPS_IN_SCAN]; /* last DC coef for each component */
  174014. } savable_state3;
  174015. /* This macro is to work around compilers with missing or broken
  174016. * structure assignment. You'll need to fix this code if you have
  174017. * such a compiler and you change MAX_COMPS_IN_SCAN.
  174018. */
  174019. #ifndef NO_STRUCT_ASSIGN
  174020. #define ASSIGN_STATE(dest,src) ((dest) = (src))
  174021. #else
  174022. #if MAX_COMPS_IN_SCAN == 4
  174023. #define ASSIGN_STATE(dest,src) \
  174024. ((dest).EOBRUN = (src).EOBRUN, \
  174025. (dest).last_dc_val[0] = (src).last_dc_val[0], \
  174026. (dest).last_dc_val[1] = (src).last_dc_val[1], \
  174027. (dest).last_dc_val[2] = (src).last_dc_val[2], \
  174028. (dest).last_dc_val[3] = (src).last_dc_val[3])
  174029. #endif
  174030. #endif
  174031. typedef struct {
  174032. struct jpeg_entropy_decoder pub; /* public fields */
  174033. /* These fields are loaded into local variables at start of each MCU.
  174034. * In case of suspension, we exit WITHOUT updating them.
  174035. */
  174036. bitread_perm_state bitstate; /* Bit buffer at start of MCU */
  174037. savable_state3 saved; /* Other state at start of MCU */
  174038. /* These fields are NOT loaded into local working state. */
  174039. unsigned int restarts_to_go; /* MCUs left in this restart interval */
  174040. /* Pointers to derived tables (these workspaces have image lifespan) */
  174041. d_derived_tbl * derived_tbls[NUM_HUFF_TBLS];
  174042. d_derived_tbl * ac_derived_tbl; /* active table during an AC scan */
  174043. } phuff_entropy_decoder;
  174044. typedef phuff_entropy_decoder * phuff_entropy_ptr2;
  174045. /* Forward declarations */
  174046. METHODDEF(boolean) decode_mcu_DC_first JPP((j_decompress_ptr cinfo,
  174047. JBLOCKROW *MCU_data));
  174048. METHODDEF(boolean) decode_mcu_AC_first JPP((j_decompress_ptr cinfo,
  174049. JBLOCKROW *MCU_data));
  174050. METHODDEF(boolean) decode_mcu_DC_refine JPP((j_decompress_ptr cinfo,
  174051. JBLOCKROW *MCU_data));
  174052. METHODDEF(boolean) decode_mcu_AC_refine JPP((j_decompress_ptr cinfo,
  174053. JBLOCKROW *MCU_data));
  174054. /*
  174055. * Initialize for a Huffman-compressed scan.
  174056. */
  174057. METHODDEF(void)
  174058. start_pass_phuff_decoder (j_decompress_ptr cinfo)
  174059. {
  174060. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  174061. boolean is_DC_band, bad;
  174062. int ci, coefi, tbl;
  174063. int *coef_bit_ptr;
  174064. jpeg_component_info * compptr;
  174065. is_DC_band = (cinfo->Ss == 0);
  174066. /* Validate scan parameters */
  174067. bad = FALSE;
  174068. if (is_DC_band) {
  174069. if (cinfo->Se != 0)
  174070. bad = TRUE;
  174071. } else {
  174072. /* need not check Ss/Se < 0 since they came from unsigned bytes */
  174073. if (cinfo->Ss > cinfo->Se || cinfo->Se >= DCTSIZE2)
  174074. bad = TRUE;
  174075. /* AC scans may have only one component */
  174076. if (cinfo->comps_in_scan != 1)
  174077. bad = TRUE;
  174078. }
  174079. if (cinfo->Ah != 0) {
  174080. /* Successive approximation refinement scan: must have Al = Ah-1. */
  174081. if (cinfo->Al != cinfo->Ah-1)
  174082. bad = TRUE;
  174083. }
  174084. if (cinfo->Al > 13) /* need not check for < 0 */
  174085. bad = TRUE;
  174086. /* Arguably the maximum Al value should be less than 13 for 8-bit precision,
  174087. * but the spec doesn't say so, and we try to be liberal about what we
  174088. * accept. Note: large Al values could result in out-of-range DC
  174089. * coefficients during early scans, leading to bizarre displays due to
  174090. * overflows in the IDCT math. But we won't crash.
  174091. */
  174092. if (bad)
  174093. ERREXIT4(cinfo, JERR_BAD_PROGRESSION,
  174094. cinfo->Ss, cinfo->Se, cinfo->Ah, cinfo->Al);
  174095. /* Update progression status, and verify that scan order is legal.
  174096. * Note that inter-scan inconsistencies are treated as warnings
  174097. * not fatal errors ... not clear if this is right way to behave.
  174098. */
  174099. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  174100. int cindex = cinfo->cur_comp_info[ci]->component_index;
  174101. coef_bit_ptr = & cinfo->coef_bits[cindex][0];
  174102. if (!is_DC_band && coef_bit_ptr[0] < 0) /* AC without prior DC scan */
  174103. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, 0);
  174104. for (coefi = cinfo->Ss; coefi <= cinfo->Se; coefi++) {
  174105. int expected = (coef_bit_ptr[coefi] < 0) ? 0 : coef_bit_ptr[coefi];
  174106. if (cinfo->Ah != expected)
  174107. WARNMS2(cinfo, JWRN_BOGUS_PROGRESSION, cindex, coefi);
  174108. coef_bit_ptr[coefi] = cinfo->Al;
  174109. }
  174110. }
  174111. /* Select MCU decoding routine */
  174112. if (cinfo->Ah == 0) {
  174113. if (is_DC_band)
  174114. entropy->pub.decode_mcu = decode_mcu_DC_first;
  174115. else
  174116. entropy->pub.decode_mcu = decode_mcu_AC_first;
  174117. } else {
  174118. if (is_DC_band)
  174119. entropy->pub.decode_mcu = decode_mcu_DC_refine;
  174120. else
  174121. entropy->pub.decode_mcu = decode_mcu_AC_refine;
  174122. }
  174123. for (ci = 0; ci < cinfo->comps_in_scan; ci++) {
  174124. compptr = cinfo->cur_comp_info[ci];
  174125. /* Make sure requested tables are present, and compute derived tables.
  174126. * We may build same derived table more than once, but it's not expensive.
  174127. */
  174128. if (is_DC_band) {
  174129. if (cinfo->Ah == 0) { /* DC refinement needs no table */
  174130. tbl = compptr->dc_tbl_no;
  174131. jpeg_make_d_derived_tbl(cinfo, TRUE, tbl,
  174132. & entropy->derived_tbls[tbl]);
  174133. }
  174134. } else {
  174135. tbl = compptr->ac_tbl_no;
  174136. jpeg_make_d_derived_tbl(cinfo, FALSE, tbl,
  174137. & entropy->derived_tbls[tbl]);
  174138. /* remember the single active table */
  174139. entropy->ac_derived_tbl = entropy->derived_tbls[tbl];
  174140. }
  174141. /* Initialize DC predictions to 0 */
  174142. entropy->saved.last_dc_val[ci] = 0;
  174143. }
  174144. /* Initialize bitread state variables */
  174145. entropy->bitstate.bits_left = 0;
  174146. entropy->bitstate.get_buffer = 0; /* unnecessary, but keeps Purify quiet */
  174147. entropy->pub.insufficient_data = FALSE;
  174148. /* Initialize private state variables */
  174149. entropy->saved.EOBRUN = 0;
  174150. /* Initialize restart counter */
  174151. entropy->restarts_to_go = cinfo->restart_interval;
  174152. }
  174153. /*
  174154. * Check for a restart marker & resynchronize decoder.
  174155. * Returns FALSE if must suspend.
  174156. */
  174157. LOCAL(boolean)
  174158. process_restartp (j_decompress_ptr cinfo)
  174159. {
  174160. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  174161. int ci;
  174162. /* Throw away any unused bits remaining in bit buffer; */
  174163. /* include any full bytes in next_marker's count of discarded bytes */
  174164. cinfo->marker->discarded_bytes += entropy->bitstate.bits_left / 8;
  174165. entropy->bitstate.bits_left = 0;
  174166. /* Advance past the RSTn marker */
  174167. if (! (*cinfo->marker->read_restart_marker) (cinfo))
  174168. return FALSE;
  174169. /* Re-initialize DC predictions to 0 */
  174170. for (ci = 0; ci < cinfo->comps_in_scan; ci++)
  174171. entropy->saved.last_dc_val[ci] = 0;
  174172. /* Re-init EOB run count, too */
  174173. entropy->saved.EOBRUN = 0;
  174174. /* Reset restart counter */
  174175. entropy->restarts_to_go = cinfo->restart_interval;
  174176. /* Reset out-of-data flag, unless read_restart_marker left us smack up
  174177. * against a marker. In that case we will end up treating the next data
  174178. * segment as empty, and we can avoid producing bogus output pixels by
  174179. * leaving the flag set.
  174180. */
  174181. if (cinfo->unread_marker == 0)
  174182. entropy->pub.insufficient_data = FALSE;
  174183. return TRUE;
  174184. }
  174185. /*
  174186. * Huffman MCU decoding.
  174187. * Each of these routines decodes and returns one MCU's worth of
  174188. * Huffman-compressed coefficients.
  174189. * The coefficients are reordered from zigzag order into natural array order,
  174190. * but are not dequantized.
  174191. *
  174192. * The i'th block of the MCU is stored into the block pointed to by
  174193. * MCU_data[i]. WE ASSUME THIS AREA IS INITIALLY ZEROED BY THE CALLER.
  174194. *
  174195. * We return FALSE if data source requested suspension. In that case no
  174196. * changes have been made to permanent state. (Exception: some output
  174197. * coefficients may already have been assigned. This is harmless for
  174198. * spectral selection, since we'll just re-assign them on the next call.
  174199. * Successive approximation AC refinement has to be more careful, however.)
  174200. */
  174201. /*
  174202. * MCU decoding for DC initial scan (either spectral selection,
  174203. * or first pass of successive approximation).
  174204. */
  174205. METHODDEF(boolean)
  174206. decode_mcu_DC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  174207. {
  174208. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  174209. int Al = cinfo->Al;
  174210. register int s, r;
  174211. int blkn, ci;
  174212. JBLOCKROW block;
  174213. BITREAD_STATE_VARS;
  174214. savable_state3 state;
  174215. d_derived_tbl * tbl;
  174216. jpeg_component_info * compptr;
  174217. /* Process restart marker if needed; may have to suspend */
  174218. if (cinfo->restart_interval) {
  174219. if (entropy->restarts_to_go == 0)
  174220. if (! process_restartp(cinfo))
  174221. return FALSE;
  174222. }
  174223. /* If we've run out of data, just leave the MCU set to zeroes.
  174224. * This way, we return uniform gray for the remainder of the segment.
  174225. */
  174226. if (! entropy->pub.insufficient_data) {
  174227. /* Load up working state */
  174228. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  174229. ASSIGN_STATE(state, entropy->saved);
  174230. /* Outer loop handles each block in the MCU */
  174231. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  174232. block = MCU_data[blkn];
  174233. ci = cinfo->MCU_membership[blkn];
  174234. compptr = cinfo->cur_comp_info[ci];
  174235. tbl = entropy->derived_tbls[compptr->dc_tbl_no];
  174236. /* Decode a single block's worth of coefficients */
  174237. /* Section F.2.2.1: decode the DC coefficient difference */
  174238. HUFF_DECODE(s, br_state, tbl, return FALSE, label1);
  174239. if (s) {
  174240. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  174241. r = GET_BITS(s);
  174242. s = HUFF_EXTEND(r, s);
  174243. }
  174244. /* Convert DC difference to actual value, update last_dc_val */
  174245. s += state.last_dc_val[ci];
  174246. state.last_dc_val[ci] = s;
  174247. /* Scale and output the coefficient (assumes jpeg_natural_order[0]=0) */
  174248. (*block)[0] = (JCOEF) (s << Al);
  174249. }
  174250. /* Completed MCU, so update state */
  174251. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  174252. ASSIGN_STATE(entropy->saved, state);
  174253. }
  174254. /* Account for restart interval (no-op if not using restarts) */
  174255. entropy->restarts_to_go--;
  174256. return TRUE;
  174257. }
  174258. /*
  174259. * MCU decoding for AC initial scan (either spectral selection,
  174260. * or first pass of successive approximation).
  174261. */
  174262. METHODDEF(boolean)
  174263. decode_mcu_AC_first (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  174264. {
  174265. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  174266. int Se = cinfo->Se;
  174267. int Al = cinfo->Al;
  174268. register int s, k, r;
  174269. unsigned int EOBRUN;
  174270. JBLOCKROW block;
  174271. BITREAD_STATE_VARS;
  174272. d_derived_tbl * tbl;
  174273. /* Process restart marker if needed; may have to suspend */
  174274. if (cinfo->restart_interval) {
  174275. if (entropy->restarts_to_go == 0)
  174276. if (! process_restartp(cinfo))
  174277. return FALSE;
  174278. }
  174279. /* If we've run out of data, just leave the MCU set to zeroes.
  174280. * This way, we return uniform gray for the remainder of the segment.
  174281. */
  174282. if (! entropy->pub.insufficient_data) {
  174283. /* Load up working state.
  174284. * We can avoid loading/saving bitread state if in an EOB run.
  174285. */
  174286. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  174287. /* There is always only one block per MCU */
  174288. if (EOBRUN > 0) /* if it's a band of zeroes... */
  174289. EOBRUN--; /* ...process it now (we do nothing) */
  174290. else {
  174291. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  174292. block = MCU_data[0];
  174293. tbl = entropy->ac_derived_tbl;
  174294. for (k = cinfo->Ss; k <= Se; k++) {
  174295. HUFF_DECODE(s, br_state, tbl, return FALSE, label2);
  174296. r = s >> 4;
  174297. s &= 15;
  174298. if (s) {
  174299. k += r;
  174300. CHECK_BIT_BUFFER(br_state, s, return FALSE);
  174301. r = GET_BITS(s);
  174302. s = HUFF_EXTEND(r, s);
  174303. /* Scale and output coefficient in natural (dezigzagged) order */
  174304. (*block)[jpeg_natural_order[k]] = (JCOEF) (s << Al);
  174305. } else {
  174306. if (r == 15) { /* ZRL */
  174307. k += 15; /* skip 15 zeroes in band */
  174308. } else { /* EOBr, run length is 2^r + appended bits */
  174309. EOBRUN = 1 << r;
  174310. if (r) { /* EOBr, r > 0 */
  174311. CHECK_BIT_BUFFER(br_state, r, return FALSE);
  174312. r = GET_BITS(r);
  174313. EOBRUN += r;
  174314. }
  174315. EOBRUN--; /* this band is processed at this moment */
  174316. break; /* force end-of-band */
  174317. }
  174318. }
  174319. }
  174320. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  174321. }
  174322. /* Completed MCU, so update state */
  174323. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  174324. }
  174325. /* Account for restart interval (no-op if not using restarts) */
  174326. entropy->restarts_to_go--;
  174327. return TRUE;
  174328. }
  174329. /*
  174330. * MCU decoding for DC successive approximation refinement scan.
  174331. * Note: we assume such scans can be multi-component, although the spec
  174332. * is not very clear on the point.
  174333. */
  174334. METHODDEF(boolean)
  174335. decode_mcu_DC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  174336. {
  174337. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  174338. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  174339. int blkn;
  174340. JBLOCKROW block;
  174341. BITREAD_STATE_VARS;
  174342. /* Process restart marker if needed; may have to suspend */
  174343. if (cinfo->restart_interval) {
  174344. if (entropy->restarts_to_go == 0)
  174345. if (! process_restartp(cinfo))
  174346. return FALSE;
  174347. }
  174348. /* Not worth the cycles to check insufficient_data here,
  174349. * since we will not change the data anyway if we read zeroes.
  174350. */
  174351. /* Load up working state */
  174352. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  174353. /* Outer loop handles each block in the MCU */
  174354. for (blkn = 0; blkn < cinfo->blocks_in_MCU; blkn++) {
  174355. block = MCU_data[blkn];
  174356. /* Encoded data is simply the next bit of the two's-complement DC value */
  174357. CHECK_BIT_BUFFER(br_state, 1, return FALSE);
  174358. if (GET_BITS(1))
  174359. (*block)[0] |= p1;
  174360. /* Note: since we use |=, repeating the assignment later is safe */
  174361. }
  174362. /* Completed MCU, so update state */
  174363. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  174364. /* Account for restart interval (no-op if not using restarts) */
  174365. entropy->restarts_to_go--;
  174366. return TRUE;
  174367. }
  174368. /*
  174369. * MCU decoding for AC successive approximation refinement scan.
  174370. */
  174371. METHODDEF(boolean)
  174372. decode_mcu_AC_refine (j_decompress_ptr cinfo, JBLOCKROW *MCU_data)
  174373. {
  174374. phuff_entropy_ptr2 entropy = (phuff_entropy_ptr2) cinfo->entropy;
  174375. int Se = cinfo->Se;
  174376. int p1 = 1 << cinfo->Al; /* 1 in the bit position being coded */
  174377. int m1 = (-1) << cinfo->Al; /* -1 in the bit position being coded */
  174378. register int s, k, r;
  174379. unsigned int EOBRUN;
  174380. JBLOCKROW block;
  174381. JCOEFPTR thiscoef;
  174382. BITREAD_STATE_VARS;
  174383. d_derived_tbl * tbl;
  174384. int num_newnz;
  174385. int newnz_pos[DCTSIZE2];
  174386. /* Process restart marker if needed; may have to suspend */
  174387. if (cinfo->restart_interval) {
  174388. if (entropy->restarts_to_go == 0)
  174389. if (! process_restartp(cinfo))
  174390. return FALSE;
  174391. }
  174392. /* If we've run out of data, don't modify the MCU.
  174393. */
  174394. if (! entropy->pub.insufficient_data) {
  174395. /* Load up working state */
  174396. BITREAD_LOAD_STATE(cinfo,entropy->bitstate);
  174397. EOBRUN = entropy->saved.EOBRUN; /* only part of saved state we need */
  174398. /* There is always only one block per MCU */
  174399. block = MCU_data[0];
  174400. tbl = entropy->ac_derived_tbl;
  174401. /* If we are forced to suspend, we must undo the assignments to any newly
  174402. * nonzero coefficients in the block, because otherwise we'd get confused
  174403. * next time about which coefficients were already nonzero.
  174404. * But we need not undo addition of bits to already-nonzero coefficients;
  174405. * instead, we can test the current bit to see if we already did it.
  174406. */
  174407. num_newnz = 0;
  174408. /* initialize coefficient loop counter to start of band */
  174409. k = cinfo->Ss;
  174410. if (EOBRUN == 0) {
  174411. for (; k <= Se; k++) {
  174412. HUFF_DECODE(s, br_state, tbl, goto undoit, label3);
  174413. r = s >> 4;
  174414. s &= 15;
  174415. if (s) {
  174416. if (s != 1) /* size of new coef should always be 1 */
  174417. WARNMS(cinfo, JWRN_HUFF_BAD_CODE);
  174418. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  174419. if (GET_BITS(1))
  174420. s = p1; /* newly nonzero coef is positive */
  174421. else
  174422. s = m1; /* newly nonzero coef is negative */
  174423. } else {
  174424. if (r != 15) {
  174425. EOBRUN = 1 << r; /* EOBr, run length is 2^r + appended bits */
  174426. if (r) {
  174427. CHECK_BIT_BUFFER(br_state, r, goto undoit);
  174428. r = GET_BITS(r);
  174429. EOBRUN += r;
  174430. }
  174431. break; /* rest of block is handled by EOB logic */
  174432. }
  174433. /* note s = 0 for processing ZRL */
  174434. }
  174435. /* Advance over already-nonzero coefs and r still-zero coefs,
  174436. * appending correction bits to the nonzeroes. A correction bit is 1
  174437. * if the absolute value of the coefficient must be increased.
  174438. */
  174439. do {
  174440. thiscoef = *block + jpeg_natural_order[k];
  174441. if (*thiscoef != 0) {
  174442. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  174443. if (GET_BITS(1)) {
  174444. if ((*thiscoef & p1) == 0) { /* do nothing if already set it */
  174445. if (*thiscoef >= 0)
  174446. *thiscoef += p1;
  174447. else
  174448. *thiscoef += m1;
  174449. }
  174450. }
  174451. } else {
  174452. if (--r < 0)
  174453. break; /* reached target zero coefficient */
  174454. }
  174455. k++;
  174456. } while (k <= Se);
  174457. if (s) {
  174458. int pos = jpeg_natural_order[k];
  174459. /* Output newly nonzero coefficient */
  174460. (*block)[pos] = (JCOEF) s;
  174461. /* Remember its position in case we have to suspend */
  174462. newnz_pos[num_newnz++] = pos;
  174463. }
  174464. }
  174465. }
  174466. if (EOBRUN > 0) {
  174467. /* Scan any remaining coefficient positions after the end-of-band
  174468. * (the last newly nonzero coefficient, if any). Append a correction
  174469. * bit to each already-nonzero coefficient. A correction bit is 1
  174470. * if the absolute value of the coefficient must be increased.
  174471. */
  174472. for (; k <= Se; k++) {
  174473. thiscoef = *block + jpeg_natural_order[k];
  174474. if (*thiscoef != 0) {
  174475. CHECK_BIT_BUFFER(br_state, 1, goto undoit);
  174476. if (GET_BITS(1)) {
  174477. if ((*thiscoef & p1) == 0) { /* do nothing if already changed it */
  174478. if (*thiscoef >= 0)
  174479. *thiscoef += p1;
  174480. else
  174481. *thiscoef += m1;
  174482. }
  174483. }
  174484. }
  174485. }
  174486. /* Count one block completed in EOB run */
  174487. EOBRUN--;
  174488. }
  174489. /* Completed MCU, so update state */
  174490. BITREAD_SAVE_STATE(cinfo,entropy->bitstate);
  174491. entropy->saved.EOBRUN = EOBRUN; /* only part of saved state we need */
  174492. }
  174493. /* Account for restart interval (no-op if not using restarts) */
  174494. entropy->restarts_to_go--;
  174495. return TRUE;
  174496. undoit:
  174497. /* Re-zero any output coefficients that we made newly nonzero */
  174498. while (num_newnz > 0)
  174499. (*block)[newnz_pos[--num_newnz]] = 0;
  174500. return FALSE;
  174501. }
  174502. /*
  174503. * Module initialization routine for progressive Huffman entropy decoding.
  174504. */
  174505. GLOBAL(void)
  174506. jinit_phuff_decoder (j_decompress_ptr cinfo)
  174507. {
  174508. phuff_entropy_ptr2 entropy;
  174509. int *coef_bit_ptr;
  174510. int ci, i;
  174511. entropy = (phuff_entropy_ptr2)
  174512. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174513. SIZEOF(phuff_entropy_decoder));
  174514. cinfo->entropy = (struct jpeg_entropy_decoder *) entropy;
  174515. entropy->pub.start_pass = start_pass_phuff_decoder;
  174516. /* Mark derived tables unallocated */
  174517. for (i = 0; i < NUM_HUFF_TBLS; i++) {
  174518. entropy->derived_tbls[i] = NULL;
  174519. }
  174520. /* Create progression status table */
  174521. cinfo->coef_bits = (int (*)[DCTSIZE2])
  174522. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174523. cinfo->num_components*DCTSIZE2*SIZEOF(int));
  174524. coef_bit_ptr = & cinfo->coef_bits[0][0];
  174525. for (ci = 0; ci < cinfo->num_components; ci++)
  174526. for (i = 0; i < DCTSIZE2; i++)
  174527. *coef_bit_ptr++ = -1;
  174528. }
  174529. #endif /* D_PROGRESSIVE_SUPPORTED */
  174530. /********* End of inlined file: jdphuff.c *********/
  174531. /********* Start of inlined file: jdpostct.c *********/
  174532. #define JPEG_INTERNALS
  174533. /* Private buffer controller object */
  174534. typedef struct {
  174535. struct jpeg_d_post_controller pub; /* public fields */
  174536. /* Color quantization source buffer: this holds output data from
  174537. * the upsample/color conversion step to be passed to the quantizer.
  174538. * For two-pass color quantization, we need a full-image buffer;
  174539. * for one-pass operation, a strip buffer is sufficient.
  174540. */
  174541. jvirt_sarray_ptr whole_image; /* virtual array, or NULL if one-pass */
  174542. JSAMPARRAY buffer; /* strip buffer, or current strip of virtual */
  174543. JDIMENSION strip_height; /* buffer size in rows */
  174544. /* for two-pass mode only: */
  174545. JDIMENSION starting_row; /* row # of first row in current strip */
  174546. JDIMENSION next_row; /* index of next row to fill/empty in strip */
  174547. } my_post_controller;
  174548. typedef my_post_controller * my_post_ptr;
  174549. /* Forward declarations */
  174550. METHODDEF(void) post_process_1pass
  174551. JPP((j_decompress_ptr cinfo,
  174552. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  174553. JDIMENSION in_row_groups_avail,
  174554. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  174555. JDIMENSION out_rows_avail));
  174556. #ifdef QUANT_2PASS_SUPPORTED
  174557. METHODDEF(void) post_process_prepass
  174558. JPP((j_decompress_ptr cinfo,
  174559. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  174560. JDIMENSION in_row_groups_avail,
  174561. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  174562. JDIMENSION out_rows_avail));
  174563. METHODDEF(void) post_process_2pass
  174564. JPP((j_decompress_ptr cinfo,
  174565. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  174566. JDIMENSION in_row_groups_avail,
  174567. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  174568. JDIMENSION out_rows_avail));
  174569. #endif
  174570. /*
  174571. * Initialize for a processing pass.
  174572. */
  174573. METHODDEF(void)
  174574. start_pass_dpost (j_decompress_ptr cinfo, J_BUF_MODE pass_mode)
  174575. {
  174576. my_post_ptr post = (my_post_ptr) cinfo->post;
  174577. switch (pass_mode) {
  174578. case JBUF_PASS_THRU:
  174579. if (cinfo->quantize_colors) {
  174580. /* Single-pass processing with color quantization. */
  174581. post->pub.post_process_data = post_process_1pass;
  174582. /* We could be doing buffered-image output before starting a 2-pass
  174583. * color quantization; in that case, jinit_d_post_controller did not
  174584. * allocate a strip buffer. Use the virtual-array buffer as workspace.
  174585. */
  174586. if (post->buffer == NULL) {
  174587. post->buffer = (*cinfo->mem->access_virt_sarray)
  174588. ((j_common_ptr) cinfo, post->whole_image,
  174589. (JDIMENSION) 0, post->strip_height, TRUE);
  174590. }
  174591. } else {
  174592. /* For single-pass processing without color quantization,
  174593. * I have no work to do; just call the upsampler directly.
  174594. */
  174595. post->pub.post_process_data = cinfo->upsample->upsample;
  174596. }
  174597. break;
  174598. #ifdef QUANT_2PASS_SUPPORTED
  174599. case JBUF_SAVE_AND_PASS:
  174600. /* First pass of 2-pass quantization */
  174601. if (post->whole_image == NULL)
  174602. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  174603. post->pub.post_process_data = post_process_prepass;
  174604. break;
  174605. case JBUF_CRANK_DEST:
  174606. /* Second pass of 2-pass quantization */
  174607. if (post->whole_image == NULL)
  174608. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  174609. post->pub.post_process_data = post_process_2pass;
  174610. break;
  174611. #endif /* QUANT_2PASS_SUPPORTED */
  174612. default:
  174613. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  174614. break;
  174615. }
  174616. post->starting_row = post->next_row = 0;
  174617. }
  174618. /*
  174619. * Process some data in the one-pass (strip buffer) case.
  174620. * This is used for color precision reduction as well as one-pass quantization.
  174621. */
  174622. METHODDEF(void)
  174623. post_process_1pass (j_decompress_ptr cinfo,
  174624. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  174625. JDIMENSION in_row_groups_avail,
  174626. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  174627. JDIMENSION out_rows_avail)
  174628. {
  174629. my_post_ptr post = (my_post_ptr) cinfo->post;
  174630. JDIMENSION num_rows, max_rows;
  174631. /* Fill the buffer, but not more than what we can dump out in one go. */
  174632. /* Note we rely on the upsampler to detect bottom of image. */
  174633. max_rows = out_rows_avail - *out_row_ctr;
  174634. if (max_rows > post->strip_height)
  174635. max_rows = post->strip_height;
  174636. num_rows = 0;
  174637. (*cinfo->upsample->upsample) (cinfo,
  174638. input_buf, in_row_group_ctr, in_row_groups_avail,
  174639. post->buffer, &num_rows, max_rows);
  174640. /* Quantize and emit data. */
  174641. (*cinfo->cquantize->color_quantize) (cinfo,
  174642. post->buffer, output_buf + *out_row_ctr, (int) num_rows);
  174643. *out_row_ctr += num_rows;
  174644. }
  174645. #ifdef QUANT_2PASS_SUPPORTED
  174646. /*
  174647. * Process some data in the first pass of 2-pass quantization.
  174648. */
  174649. METHODDEF(void)
  174650. post_process_prepass (j_decompress_ptr cinfo,
  174651. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  174652. JDIMENSION in_row_groups_avail,
  174653. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  174654. JDIMENSION out_rows_avail)
  174655. {
  174656. my_post_ptr post = (my_post_ptr) cinfo->post;
  174657. JDIMENSION old_next_row, num_rows;
  174658. /* Reposition virtual buffer if at start of strip. */
  174659. if (post->next_row == 0) {
  174660. post->buffer = (*cinfo->mem->access_virt_sarray)
  174661. ((j_common_ptr) cinfo, post->whole_image,
  174662. post->starting_row, post->strip_height, TRUE);
  174663. }
  174664. /* Upsample some data (up to a strip height's worth). */
  174665. old_next_row = post->next_row;
  174666. (*cinfo->upsample->upsample) (cinfo,
  174667. input_buf, in_row_group_ctr, in_row_groups_avail,
  174668. post->buffer, &post->next_row, post->strip_height);
  174669. /* Allow quantizer to scan new data. No data is emitted, */
  174670. /* but we advance out_row_ctr so outer loop can tell when we're done. */
  174671. if (post->next_row > old_next_row) {
  174672. num_rows = post->next_row - old_next_row;
  174673. (*cinfo->cquantize->color_quantize) (cinfo, post->buffer + old_next_row,
  174674. (JSAMPARRAY) NULL, (int) num_rows);
  174675. *out_row_ctr += num_rows;
  174676. }
  174677. /* Advance if we filled the strip. */
  174678. if (post->next_row >= post->strip_height) {
  174679. post->starting_row += post->strip_height;
  174680. post->next_row = 0;
  174681. }
  174682. }
  174683. /*
  174684. * Process some data in the second pass of 2-pass quantization.
  174685. */
  174686. METHODDEF(void)
  174687. post_process_2pass (j_decompress_ptr cinfo,
  174688. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  174689. JDIMENSION in_row_groups_avail,
  174690. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  174691. JDIMENSION out_rows_avail)
  174692. {
  174693. my_post_ptr post = (my_post_ptr) cinfo->post;
  174694. JDIMENSION num_rows, max_rows;
  174695. /* Reposition virtual buffer if at start of strip. */
  174696. if (post->next_row == 0) {
  174697. post->buffer = (*cinfo->mem->access_virt_sarray)
  174698. ((j_common_ptr) cinfo, post->whole_image,
  174699. post->starting_row, post->strip_height, FALSE);
  174700. }
  174701. /* Determine number of rows to emit. */
  174702. num_rows = post->strip_height - post->next_row; /* available in strip */
  174703. max_rows = out_rows_avail - *out_row_ctr; /* available in output area */
  174704. if (num_rows > max_rows)
  174705. num_rows = max_rows;
  174706. /* We have to check bottom of image here, can't depend on upsampler. */
  174707. max_rows = cinfo->output_height - post->starting_row;
  174708. if (num_rows > max_rows)
  174709. num_rows = max_rows;
  174710. /* Quantize and emit data. */
  174711. (*cinfo->cquantize->color_quantize) (cinfo,
  174712. post->buffer + post->next_row, output_buf + *out_row_ctr,
  174713. (int) num_rows);
  174714. *out_row_ctr += num_rows;
  174715. /* Advance if we filled the strip. */
  174716. post->next_row += num_rows;
  174717. if (post->next_row >= post->strip_height) {
  174718. post->starting_row += post->strip_height;
  174719. post->next_row = 0;
  174720. }
  174721. }
  174722. #endif /* QUANT_2PASS_SUPPORTED */
  174723. /*
  174724. * Initialize postprocessing controller.
  174725. */
  174726. GLOBAL(void)
  174727. jinit_d_post_controller (j_decompress_ptr cinfo, boolean need_full_buffer)
  174728. {
  174729. my_post_ptr post;
  174730. post = (my_post_ptr)
  174731. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174732. SIZEOF(my_post_controller));
  174733. cinfo->post = (struct jpeg_d_post_controller *) post;
  174734. post->pub.start_pass = start_pass_dpost;
  174735. post->whole_image = NULL; /* flag for no virtual arrays */
  174736. post->buffer = NULL; /* flag for no strip buffer */
  174737. /* Create the quantization buffer, if needed */
  174738. if (cinfo->quantize_colors) {
  174739. /* The buffer strip height is max_v_samp_factor, which is typically
  174740. * an efficient number of rows for upsampling to return.
  174741. * (In the presence of output rescaling, we might want to be smarter?)
  174742. */
  174743. post->strip_height = (JDIMENSION) cinfo->max_v_samp_factor;
  174744. if (need_full_buffer) {
  174745. /* Two-pass color quantization: need full-image storage. */
  174746. /* We round up the number of rows to a multiple of the strip height. */
  174747. #ifdef QUANT_2PASS_SUPPORTED
  174748. post->whole_image = (*cinfo->mem->request_virt_sarray)
  174749. ((j_common_ptr) cinfo, JPOOL_IMAGE, FALSE,
  174750. cinfo->output_width * cinfo->out_color_components,
  174751. (JDIMENSION) jround_up((long) cinfo->output_height,
  174752. (long) post->strip_height),
  174753. post->strip_height);
  174754. #else
  174755. ERREXIT(cinfo, JERR_BAD_BUFFER_MODE);
  174756. #endif /* QUANT_2PASS_SUPPORTED */
  174757. } else {
  174758. /* One-pass color quantization: just make a strip buffer. */
  174759. post->buffer = (*cinfo->mem->alloc_sarray)
  174760. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  174761. cinfo->output_width * cinfo->out_color_components,
  174762. post->strip_height);
  174763. }
  174764. }
  174765. }
  174766. /********* End of inlined file: jdpostct.c *********/
  174767. #undef FIX
  174768. /********* Start of inlined file: jdsample.c *********/
  174769. #define JPEG_INTERNALS
  174770. /* Pointer to routine to upsample a single component */
  174771. typedef JMETHOD(void, upsample1_ptr,
  174772. (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174773. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr));
  174774. /* Private subobject */
  174775. typedef struct {
  174776. struct jpeg_upsampler pub; /* public fields */
  174777. /* Color conversion buffer. When using separate upsampling and color
  174778. * conversion steps, this buffer holds one upsampled row group until it
  174779. * has been color converted and output.
  174780. * Note: we do not allocate any storage for component(s) which are full-size,
  174781. * ie do not need rescaling. The corresponding entry of color_buf[] is
  174782. * simply set to point to the input data array, thereby avoiding copying.
  174783. */
  174784. JSAMPARRAY color_buf[MAX_COMPONENTS];
  174785. /* Per-component upsampling method pointers */
  174786. upsample1_ptr methods[MAX_COMPONENTS];
  174787. int next_row_out; /* counts rows emitted from color_buf */
  174788. JDIMENSION rows_to_go; /* counts rows remaining in image */
  174789. /* Height of an input row group for each component. */
  174790. int rowgroup_height[MAX_COMPONENTS];
  174791. /* These arrays save pixel expansion factors so that int_expand need not
  174792. * recompute them each time. They are unused for other upsampling methods.
  174793. */
  174794. UINT8 h_expand[MAX_COMPONENTS];
  174795. UINT8 v_expand[MAX_COMPONENTS];
  174796. } my_upsampler2;
  174797. typedef my_upsampler2 * my_upsample_ptr2;
  174798. /*
  174799. * Initialize for an upsampling pass.
  174800. */
  174801. METHODDEF(void)
  174802. start_pass_upsample (j_decompress_ptr cinfo)
  174803. {
  174804. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174805. /* Mark the conversion buffer empty */
  174806. upsample->next_row_out = cinfo->max_v_samp_factor;
  174807. /* Initialize total-height counter for detecting bottom of image */
  174808. upsample->rows_to_go = cinfo->output_height;
  174809. }
  174810. /*
  174811. * Control routine to do upsampling (and color conversion).
  174812. *
  174813. * In this version we upsample each component independently.
  174814. * We upsample one row group into the conversion buffer, then apply
  174815. * color conversion a row at a time.
  174816. */
  174817. METHODDEF(void)
  174818. sep_upsample (j_decompress_ptr cinfo,
  174819. JSAMPIMAGE input_buf, JDIMENSION *in_row_group_ctr,
  174820. JDIMENSION in_row_groups_avail,
  174821. JSAMPARRAY output_buf, JDIMENSION *out_row_ctr,
  174822. JDIMENSION out_rows_avail)
  174823. {
  174824. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174825. int ci;
  174826. jpeg_component_info * compptr;
  174827. JDIMENSION num_rows;
  174828. /* Fill the conversion buffer, if it's empty */
  174829. if (upsample->next_row_out >= cinfo->max_v_samp_factor) {
  174830. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  174831. ci++, compptr++) {
  174832. /* Invoke per-component upsample method. Notice we pass a POINTER
  174833. * to color_buf[ci], so that fullsize_upsample can change it.
  174834. */
  174835. (*upsample->methods[ci]) (cinfo, compptr,
  174836. input_buf[ci] + (*in_row_group_ctr * upsample->rowgroup_height[ci]),
  174837. upsample->color_buf + ci);
  174838. }
  174839. upsample->next_row_out = 0;
  174840. }
  174841. /* Color-convert and emit rows */
  174842. /* How many we have in the buffer: */
  174843. num_rows = (JDIMENSION) (cinfo->max_v_samp_factor - upsample->next_row_out);
  174844. /* Not more than the distance to the end of the image. Need this test
  174845. * in case the image height is not a multiple of max_v_samp_factor:
  174846. */
  174847. if (num_rows > upsample->rows_to_go)
  174848. num_rows = upsample->rows_to_go;
  174849. /* And not more than what the client can accept: */
  174850. out_rows_avail -= *out_row_ctr;
  174851. if (num_rows > out_rows_avail)
  174852. num_rows = out_rows_avail;
  174853. (*cinfo->cconvert->color_convert) (cinfo, upsample->color_buf,
  174854. (JDIMENSION) upsample->next_row_out,
  174855. output_buf + *out_row_ctr,
  174856. (int) num_rows);
  174857. /* Adjust counts */
  174858. *out_row_ctr += num_rows;
  174859. upsample->rows_to_go -= num_rows;
  174860. upsample->next_row_out += num_rows;
  174861. /* When the buffer is emptied, declare this input row group consumed */
  174862. if (upsample->next_row_out >= cinfo->max_v_samp_factor)
  174863. (*in_row_group_ctr)++;
  174864. }
  174865. /*
  174866. * These are the routines invoked by sep_upsample to upsample pixel values
  174867. * of a single component. One row group is processed per call.
  174868. */
  174869. /*
  174870. * For full-size components, we just make color_buf[ci] point at the
  174871. * input buffer, and thus avoid copying any data. Note that this is
  174872. * safe only because sep_upsample doesn't declare the input row group
  174873. * "consumed" until we are done color converting and emitting it.
  174874. */
  174875. METHODDEF(void)
  174876. fullsize_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174877. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174878. {
  174879. *output_data_ptr = input_data;
  174880. }
  174881. /*
  174882. * This is a no-op version used for "uninteresting" components.
  174883. * These components will not be referenced by color conversion.
  174884. */
  174885. METHODDEF(void)
  174886. noop_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174887. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174888. {
  174889. *output_data_ptr = NULL; /* safety check */
  174890. }
  174891. /*
  174892. * This version handles any integral sampling ratios.
  174893. * This is not used for typical JPEG files, so it need not be fast.
  174894. * Nor, for that matter, is it particularly accurate: the algorithm is
  174895. * simple replication of the input pixel onto the corresponding output
  174896. * pixels. The hi-falutin sampling literature refers to this as a
  174897. * "box filter". A box filter tends to introduce visible artifacts,
  174898. * so if you are actually going to use 3:1 or 4:1 sampling ratios
  174899. * you would be well advised to improve this code.
  174900. */
  174901. METHODDEF(void)
  174902. int_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174903. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174904. {
  174905. my_upsample_ptr2 upsample = (my_upsample_ptr2) cinfo->upsample;
  174906. JSAMPARRAY output_data = *output_data_ptr;
  174907. register JSAMPROW inptr, outptr;
  174908. register JSAMPLE invalue;
  174909. register int h;
  174910. JSAMPROW outend;
  174911. int h_expand, v_expand;
  174912. int inrow, outrow;
  174913. h_expand = upsample->h_expand[compptr->component_index];
  174914. v_expand = upsample->v_expand[compptr->component_index];
  174915. inrow = outrow = 0;
  174916. while (outrow < cinfo->max_v_samp_factor) {
  174917. /* Generate one output row with proper horizontal expansion */
  174918. inptr = input_data[inrow];
  174919. outptr = output_data[outrow];
  174920. outend = outptr + cinfo->output_width;
  174921. while (outptr < outend) {
  174922. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174923. for (h = h_expand; h > 0; h--) {
  174924. *outptr++ = invalue;
  174925. }
  174926. }
  174927. /* Generate any additional output rows by duplicating the first one */
  174928. if (v_expand > 1) {
  174929. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174930. v_expand-1, cinfo->output_width);
  174931. }
  174932. inrow++;
  174933. outrow += v_expand;
  174934. }
  174935. }
  174936. /*
  174937. * Fast processing for the common case of 2:1 horizontal and 1:1 vertical.
  174938. * It's still a box filter.
  174939. */
  174940. METHODDEF(void)
  174941. h2v1_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174942. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174943. {
  174944. JSAMPARRAY output_data = *output_data_ptr;
  174945. register JSAMPROW inptr, outptr;
  174946. register JSAMPLE invalue;
  174947. JSAMPROW outend;
  174948. int inrow;
  174949. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  174950. inptr = input_data[inrow];
  174951. outptr = output_data[inrow];
  174952. outend = outptr + cinfo->output_width;
  174953. while (outptr < outend) {
  174954. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174955. *outptr++ = invalue;
  174956. *outptr++ = invalue;
  174957. }
  174958. }
  174959. }
  174960. /*
  174961. * Fast processing for the common case of 2:1 horizontal and 2:1 vertical.
  174962. * It's still a box filter.
  174963. */
  174964. METHODDEF(void)
  174965. h2v2_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  174966. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  174967. {
  174968. JSAMPARRAY output_data = *output_data_ptr;
  174969. register JSAMPROW inptr, outptr;
  174970. register JSAMPLE invalue;
  174971. JSAMPROW outend;
  174972. int inrow, outrow;
  174973. inrow = outrow = 0;
  174974. while (outrow < cinfo->max_v_samp_factor) {
  174975. inptr = input_data[inrow];
  174976. outptr = output_data[outrow];
  174977. outend = outptr + cinfo->output_width;
  174978. while (outptr < outend) {
  174979. invalue = *inptr++; /* don't need GETJSAMPLE() here */
  174980. *outptr++ = invalue;
  174981. *outptr++ = invalue;
  174982. }
  174983. jcopy_sample_rows(output_data, outrow, output_data, outrow+1,
  174984. 1, cinfo->output_width);
  174985. inrow++;
  174986. outrow += 2;
  174987. }
  174988. }
  174989. /*
  174990. * Fancy processing for the common case of 2:1 horizontal and 1:1 vertical.
  174991. *
  174992. * The upsampling algorithm is linear interpolation between pixel centers,
  174993. * also known as a "triangle filter". This is a good compromise between
  174994. * speed and visual quality. The centers of the output pixels are 1/4 and 3/4
  174995. * of the way between input pixel centers.
  174996. *
  174997. * A note about the "bias" calculations: when rounding fractional values to
  174998. * integer, we do not want to always round 0.5 up to the next integer.
  174999. * If we did that, we'd introduce a noticeable bias towards larger values.
  175000. * Instead, this code is arranged so that 0.5 will be rounded up or down at
  175001. * alternate pixel locations (a simple ordered dither pattern).
  175002. */
  175003. METHODDEF(void)
  175004. h2v1_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175005. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  175006. {
  175007. JSAMPARRAY output_data = *output_data_ptr;
  175008. register JSAMPROW inptr, outptr;
  175009. register int invalue;
  175010. register JDIMENSION colctr;
  175011. int inrow;
  175012. for (inrow = 0; inrow < cinfo->max_v_samp_factor; inrow++) {
  175013. inptr = input_data[inrow];
  175014. outptr = output_data[inrow];
  175015. /* Special case for first column */
  175016. invalue = GETJSAMPLE(*inptr++);
  175017. *outptr++ = (JSAMPLE) invalue;
  175018. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(*inptr) + 2) >> 2);
  175019. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  175020. /* General case: 3/4 * nearer pixel + 1/4 * further pixel */
  175021. invalue = GETJSAMPLE(*inptr++) * 3;
  175022. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(inptr[-2]) + 1) >> 2);
  175023. *outptr++ = (JSAMPLE) ((invalue + GETJSAMPLE(*inptr) + 2) >> 2);
  175024. }
  175025. /* Special case for last column */
  175026. invalue = GETJSAMPLE(*inptr);
  175027. *outptr++ = (JSAMPLE) ((invalue * 3 + GETJSAMPLE(inptr[-1]) + 1) >> 2);
  175028. *outptr++ = (JSAMPLE) invalue;
  175029. }
  175030. }
  175031. /*
  175032. * Fancy processing for the common case of 2:1 horizontal and 2:1 vertical.
  175033. * Again a triangle filter; see comments for h2v1 case, above.
  175034. *
  175035. * It is OK for us to reference the adjacent input rows because we demanded
  175036. * context from the main buffer controller (see initialization code).
  175037. */
  175038. METHODDEF(void)
  175039. h2v2_fancy_upsample (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175040. JSAMPARRAY input_data, JSAMPARRAY * output_data_ptr)
  175041. {
  175042. JSAMPARRAY output_data = *output_data_ptr;
  175043. register JSAMPROW inptr0, inptr1, outptr;
  175044. #if BITS_IN_JSAMPLE == 8
  175045. register int thiscolsum, lastcolsum, nextcolsum;
  175046. #else
  175047. register INT32 thiscolsum, lastcolsum, nextcolsum;
  175048. #endif
  175049. register JDIMENSION colctr;
  175050. int inrow, outrow, v;
  175051. inrow = outrow = 0;
  175052. while (outrow < cinfo->max_v_samp_factor) {
  175053. for (v = 0; v < 2; v++) {
  175054. /* inptr0 points to nearest input row, inptr1 points to next nearest */
  175055. inptr0 = input_data[inrow];
  175056. if (v == 0) /* next nearest is row above */
  175057. inptr1 = input_data[inrow-1];
  175058. else /* next nearest is row below */
  175059. inptr1 = input_data[inrow+1];
  175060. outptr = output_data[outrow++];
  175061. /* Special case for first column */
  175062. thiscolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  175063. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  175064. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 8) >> 4);
  175065. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  175066. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  175067. for (colctr = compptr->downsampled_width - 2; colctr > 0; colctr--) {
  175068. /* General case: 3/4 * nearer pixel + 1/4 * further pixel in each */
  175069. /* dimension, thus 9/16, 3/16, 3/16, 1/16 overall */
  175070. nextcolsum = GETJSAMPLE(*inptr0++) * 3 + GETJSAMPLE(*inptr1++);
  175071. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  175072. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + nextcolsum + 7) >> 4);
  175073. lastcolsum = thiscolsum; thiscolsum = nextcolsum;
  175074. }
  175075. /* Special case for last column */
  175076. *outptr++ = (JSAMPLE) ((thiscolsum * 3 + lastcolsum + 8) >> 4);
  175077. *outptr++ = (JSAMPLE) ((thiscolsum * 4 + 7) >> 4);
  175078. }
  175079. inrow++;
  175080. }
  175081. }
  175082. /*
  175083. * Module initialization routine for upsampling.
  175084. */
  175085. GLOBAL(void)
  175086. jinit_upsampler (j_decompress_ptr cinfo)
  175087. {
  175088. my_upsample_ptr2 upsample;
  175089. int ci;
  175090. jpeg_component_info * compptr;
  175091. boolean need_buffer, do_fancy;
  175092. int h_in_group, v_in_group, h_out_group, v_out_group;
  175093. upsample = (my_upsample_ptr2)
  175094. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  175095. SIZEOF(my_upsampler2));
  175096. cinfo->upsample = (struct jpeg_upsampler *) upsample;
  175097. upsample->pub.start_pass = start_pass_upsample;
  175098. upsample->pub.upsample = sep_upsample;
  175099. upsample->pub.need_context_rows = FALSE; /* until we find out differently */
  175100. if (cinfo->CCIR601_sampling) /* this isn't supported */
  175101. ERREXIT(cinfo, JERR_CCIR601_NOTIMPL);
  175102. /* jdmainct.c doesn't support context rows when min_DCT_scaled_size = 1,
  175103. * so don't ask for it.
  175104. */
  175105. do_fancy = cinfo->do_fancy_upsampling && cinfo->min_DCT_scaled_size > 1;
  175106. /* Verify we can handle the sampling factors, select per-component methods,
  175107. * and create storage as needed.
  175108. */
  175109. for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
  175110. ci++, compptr++) {
  175111. /* Compute size of an "input group" after IDCT scaling. This many samples
  175112. * are to be converted to max_h_samp_factor * max_v_samp_factor pixels.
  175113. */
  175114. h_in_group = (compptr->h_samp_factor * compptr->DCT_scaled_size) /
  175115. cinfo->min_DCT_scaled_size;
  175116. v_in_group = (compptr->v_samp_factor * compptr->DCT_scaled_size) /
  175117. cinfo->min_DCT_scaled_size;
  175118. h_out_group = cinfo->max_h_samp_factor;
  175119. v_out_group = cinfo->max_v_samp_factor;
  175120. upsample->rowgroup_height[ci] = v_in_group; /* save for use later */
  175121. need_buffer = TRUE;
  175122. if (! compptr->component_needed) {
  175123. /* Don't bother to upsample an uninteresting component. */
  175124. upsample->methods[ci] = noop_upsample;
  175125. need_buffer = FALSE;
  175126. } else if (h_in_group == h_out_group && v_in_group == v_out_group) {
  175127. /* Fullsize components can be processed without any work. */
  175128. upsample->methods[ci] = fullsize_upsample;
  175129. need_buffer = FALSE;
  175130. } else if (h_in_group * 2 == h_out_group &&
  175131. v_in_group == v_out_group) {
  175132. /* Special cases for 2h1v upsampling */
  175133. if (do_fancy && compptr->downsampled_width > 2)
  175134. upsample->methods[ci] = h2v1_fancy_upsample;
  175135. else
  175136. upsample->methods[ci] = h2v1_upsample;
  175137. } else if (h_in_group * 2 == h_out_group &&
  175138. v_in_group * 2 == v_out_group) {
  175139. /* Special cases for 2h2v upsampling */
  175140. if (do_fancy && compptr->downsampled_width > 2) {
  175141. upsample->methods[ci] = h2v2_fancy_upsample;
  175142. upsample->pub.need_context_rows = TRUE;
  175143. } else
  175144. upsample->methods[ci] = h2v2_upsample;
  175145. } else if ((h_out_group % h_in_group) == 0 &&
  175146. (v_out_group % v_in_group) == 0) {
  175147. /* Generic integral-factors upsampling method */
  175148. upsample->methods[ci] = int_upsample;
  175149. upsample->h_expand[ci] = (UINT8) (h_out_group / h_in_group);
  175150. upsample->v_expand[ci] = (UINT8) (v_out_group / v_in_group);
  175151. } else
  175152. ERREXIT(cinfo, JERR_FRACT_SAMPLE_NOTIMPL);
  175153. if (need_buffer) {
  175154. upsample->color_buf[ci] = (*cinfo->mem->alloc_sarray)
  175155. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  175156. (JDIMENSION) jround_up((long) cinfo->output_width,
  175157. (long) cinfo->max_h_samp_factor),
  175158. (JDIMENSION) cinfo->max_v_samp_factor);
  175159. }
  175160. }
  175161. }
  175162. /********* End of inlined file: jdsample.c *********/
  175163. /********* Start of inlined file: jdtrans.c *********/
  175164. #define JPEG_INTERNALS
  175165. /* Forward declarations */
  175166. LOCAL(void) transdecode_master_selection JPP((j_decompress_ptr cinfo));
  175167. /*
  175168. * Read the coefficient arrays from a JPEG file.
  175169. * jpeg_read_header must be completed before calling this.
  175170. *
  175171. * The entire image is read into a set of virtual coefficient-block arrays,
  175172. * one per component. The return value is a pointer to the array of
  175173. * virtual-array descriptors. These can be manipulated directly via the
  175174. * JPEG memory manager, or handed off to jpeg_write_coefficients().
  175175. * To release the memory occupied by the virtual arrays, call
  175176. * jpeg_finish_decompress() when done with the data.
  175177. *
  175178. * An alternative usage is to simply obtain access to the coefficient arrays
  175179. * during a buffered-image-mode decompression operation. This is allowed
  175180. * after any jpeg_finish_output() call. The arrays can be accessed until
  175181. * jpeg_finish_decompress() is called. (Note that any call to the library
  175182. * may reposition the arrays, so don't rely on access_virt_barray() results
  175183. * to stay valid across library calls.)
  175184. *
  175185. * Returns NULL if suspended. This case need be checked only if
  175186. * a suspending data source is used.
  175187. */
  175188. GLOBAL(jvirt_barray_ptr *)
  175189. jpeg_read_coefficients (j_decompress_ptr cinfo)
  175190. {
  175191. if (cinfo->global_state == DSTATE_READY) {
  175192. /* First call: initialize active modules */
  175193. transdecode_master_selection(cinfo);
  175194. cinfo->global_state = DSTATE_RDCOEFS;
  175195. }
  175196. if (cinfo->global_state == DSTATE_RDCOEFS) {
  175197. /* Absorb whole file into the coef buffer */
  175198. for (;;) {
  175199. int retcode;
  175200. /* Call progress monitor hook if present */
  175201. if (cinfo->progress != NULL)
  175202. (*cinfo->progress->progress_monitor) ((j_common_ptr) cinfo);
  175203. /* Absorb some more input */
  175204. retcode = (*cinfo->inputctl->consume_input) (cinfo);
  175205. if (retcode == JPEG_SUSPENDED)
  175206. return NULL;
  175207. if (retcode == JPEG_REACHED_EOI)
  175208. break;
  175209. /* Advance progress counter if appropriate */
  175210. if (cinfo->progress != NULL &&
  175211. (retcode == JPEG_ROW_COMPLETED || retcode == JPEG_REACHED_SOS)) {
  175212. if (++cinfo->progress->pass_counter >= cinfo->progress->pass_limit) {
  175213. /* startup underestimated number of scans; ratchet up one scan */
  175214. cinfo->progress->pass_limit += (long) cinfo->total_iMCU_rows;
  175215. }
  175216. }
  175217. }
  175218. /* Set state so that jpeg_finish_decompress does the right thing */
  175219. cinfo->global_state = DSTATE_STOPPING;
  175220. }
  175221. /* At this point we should be in state DSTATE_STOPPING if being used
  175222. * standalone, or in state DSTATE_BUFIMAGE if being invoked to get access
  175223. * to the coefficients during a full buffered-image-mode decompression.
  175224. */
  175225. if ((cinfo->global_state == DSTATE_STOPPING ||
  175226. cinfo->global_state == DSTATE_BUFIMAGE) && cinfo->buffered_image) {
  175227. return cinfo->coef->coef_arrays;
  175228. }
  175229. /* Oops, improper usage */
  175230. ERREXIT1(cinfo, JERR_BAD_STATE, cinfo->global_state);
  175231. return NULL; /* keep compiler happy */
  175232. }
  175233. /*
  175234. * Master selection of decompression modules for transcoding.
  175235. * This substitutes for jdmaster.c's initialization of the full decompressor.
  175236. */
  175237. LOCAL(void)
  175238. transdecode_master_selection (j_decompress_ptr cinfo)
  175239. {
  175240. /* This is effectively a buffered-image operation. */
  175241. cinfo->buffered_image = TRUE;
  175242. /* Entropy decoding: either Huffman or arithmetic coding. */
  175243. if (cinfo->arith_code) {
  175244. ERREXIT(cinfo, JERR_ARITH_NOTIMPL);
  175245. } else {
  175246. if (cinfo->progressive_mode) {
  175247. #ifdef D_PROGRESSIVE_SUPPORTED
  175248. jinit_phuff_decoder(cinfo);
  175249. #else
  175250. ERREXIT(cinfo, JERR_NOT_COMPILED);
  175251. #endif
  175252. } else
  175253. jinit_huff_decoder(cinfo);
  175254. }
  175255. /* Always get a full-image coefficient buffer. */
  175256. jinit_d_coef_controller(cinfo, TRUE);
  175257. /* We can now tell the memory manager to allocate virtual arrays. */
  175258. (*cinfo->mem->realize_virt_arrays) ((j_common_ptr) cinfo);
  175259. /* Initialize input side of decompressor to consume first scan. */
  175260. (*cinfo->inputctl->start_input_pass) (cinfo);
  175261. /* Initialize progress monitoring. */
  175262. if (cinfo->progress != NULL) {
  175263. int nscans;
  175264. /* Estimate number of scans to set pass_limit. */
  175265. if (cinfo->progressive_mode) {
  175266. /* Arbitrarily estimate 2 interleaved DC scans + 3 AC scans/component. */
  175267. nscans = 2 + 3 * cinfo->num_components;
  175268. } else if (cinfo->inputctl->has_multiple_scans) {
  175269. /* For a nonprogressive multiscan file, estimate 1 scan per component. */
  175270. nscans = cinfo->num_components;
  175271. } else {
  175272. nscans = 1;
  175273. }
  175274. cinfo->progress->pass_counter = 0L;
  175275. cinfo->progress->pass_limit = (long) cinfo->total_iMCU_rows * nscans;
  175276. cinfo->progress->completed_passes = 0;
  175277. cinfo->progress->total_passes = 1;
  175278. }
  175279. }
  175280. /********* End of inlined file: jdtrans.c *********/
  175281. /********* Start of inlined file: jfdctflt.c *********/
  175282. #define JPEG_INTERNALS
  175283. #ifdef DCT_FLOAT_SUPPORTED
  175284. /*
  175285. * This module is specialized to the case DCTSIZE = 8.
  175286. */
  175287. #if DCTSIZE != 8
  175288. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175289. #endif
  175290. /*
  175291. * Perform the forward DCT on one block of samples.
  175292. */
  175293. GLOBAL(void)
  175294. jpeg_fdct_float (FAST_FLOAT * data)
  175295. {
  175296. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175297. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  175298. FAST_FLOAT z1, z2, z3, z4, z5, z11, z13;
  175299. FAST_FLOAT *dataptr;
  175300. int ctr;
  175301. /* Pass 1: process rows. */
  175302. dataptr = data;
  175303. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  175304. tmp0 = dataptr[0] + dataptr[7];
  175305. tmp7 = dataptr[0] - dataptr[7];
  175306. tmp1 = dataptr[1] + dataptr[6];
  175307. tmp6 = dataptr[1] - dataptr[6];
  175308. tmp2 = dataptr[2] + dataptr[5];
  175309. tmp5 = dataptr[2] - dataptr[5];
  175310. tmp3 = dataptr[3] + dataptr[4];
  175311. tmp4 = dataptr[3] - dataptr[4];
  175312. /* Even part */
  175313. tmp10 = tmp0 + tmp3; /* phase 2 */
  175314. tmp13 = tmp0 - tmp3;
  175315. tmp11 = tmp1 + tmp2;
  175316. tmp12 = tmp1 - tmp2;
  175317. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  175318. dataptr[4] = tmp10 - tmp11;
  175319. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  175320. dataptr[2] = tmp13 + z1; /* phase 5 */
  175321. dataptr[6] = tmp13 - z1;
  175322. /* Odd part */
  175323. tmp10 = tmp4 + tmp5; /* phase 2 */
  175324. tmp11 = tmp5 + tmp6;
  175325. tmp12 = tmp6 + tmp7;
  175326. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  175327. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  175328. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  175329. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  175330. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  175331. z11 = tmp7 + z3; /* phase 5 */
  175332. z13 = tmp7 - z3;
  175333. dataptr[5] = z13 + z2; /* phase 6 */
  175334. dataptr[3] = z13 - z2;
  175335. dataptr[1] = z11 + z4;
  175336. dataptr[7] = z11 - z4;
  175337. dataptr += DCTSIZE; /* advance pointer to next row */
  175338. }
  175339. /* Pass 2: process columns. */
  175340. dataptr = data;
  175341. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  175342. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  175343. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  175344. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  175345. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  175346. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  175347. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  175348. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  175349. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  175350. /* Even part */
  175351. tmp10 = tmp0 + tmp3; /* phase 2 */
  175352. tmp13 = tmp0 - tmp3;
  175353. tmp11 = tmp1 + tmp2;
  175354. tmp12 = tmp1 - tmp2;
  175355. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  175356. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  175357. z1 = (tmp12 + tmp13) * ((FAST_FLOAT) 0.707106781); /* c4 */
  175358. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  175359. dataptr[DCTSIZE*6] = tmp13 - z1;
  175360. /* Odd part */
  175361. tmp10 = tmp4 + tmp5; /* phase 2 */
  175362. tmp11 = tmp5 + tmp6;
  175363. tmp12 = tmp6 + tmp7;
  175364. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  175365. z5 = (tmp10 - tmp12) * ((FAST_FLOAT) 0.382683433); /* c6 */
  175366. z2 = ((FAST_FLOAT) 0.541196100) * tmp10 + z5; /* c2-c6 */
  175367. z4 = ((FAST_FLOAT) 1.306562965) * tmp12 + z5; /* c2+c6 */
  175368. z3 = tmp11 * ((FAST_FLOAT) 0.707106781); /* c4 */
  175369. z11 = tmp7 + z3; /* phase 5 */
  175370. z13 = tmp7 - z3;
  175371. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  175372. dataptr[DCTSIZE*3] = z13 - z2;
  175373. dataptr[DCTSIZE*1] = z11 + z4;
  175374. dataptr[DCTSIZE*7] = z11 - z4;
  175375. dataptr++; /* advance pointer to next column */
  175376. }
  175377. }
  175378. #endif /* DCT_FLOAT_SUPPORTED */
  175379. /********* End of inlined file: jfdctflt.c *********/
  175380. /********* Start of inlined file: jfdctint.c *********/
  175381. #define JPEG_INTERNALS
  175382. #ifdef DCT_ISLOW_SUPPORTED
  175383. /*
  175384. * This module is specialized to the case DCTSIZE = 8.
  175385. */
  175386. #if DCTSIZE != 8
  175387. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175388. #endif
  175389. /*
  175390. * The poop on this scaling stuff is as follows:
  175391. *
  175392. * Each 1-D DCT step produces outputs which are a factor of sqrt(N)
  175393. * larger than the true DCT outputs. The final outputs are therefore
  175394. * a factor of N larger than desired; since N=8 this can be cured by
  175395. * a simple right shift at the end of the algorithm. The advantage of
  175396. * this arrangement is that we save two multiplications per 1-D DCT,
  175397. * because the y0 and y4 outputs need not be divided by sqrt(N).
  175398. * In the IJG code, this factor of 8 is removed by the quantization step
  175399. * (in jcdctmgr.c), NOT in this module.
  175400. *
  175401. * We have to do addition and subtraction of the integer inputs, which
  175402. * is no problem, and multiplication by fractional constants, which is
  175403. * a problem to do in integer arithmetic. We multiply all the constants
  175404. * by CONST_SCALE and convert them to integer constants (thus retaining
  175405. * CONST_BITS bits of precision in the constants). After doing a
  175406. * multiplication we have to divide the product by CONST_SCALE, with proper
  175407. * rounding, to produce the correct output. This division can be done
  175408. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  175409. * as long as possible so that partial sums can be added together with
  175410. * full fractional precision.
  175411. *
  175412. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  175413. * they are represented to better-than-integral precision. These outputs
  175414. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  175415. * with the recommended scaling. (For 12-bit sample data, the intermediate
  175416. * array is INT32 anyway.)
  175417. *
  175418. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  175419. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  175420. * shows that the values given below are the most effective.
  175421. */
  175422. #if BITS_IN_JSAMPLE == 8
  175423. #define CONST_BITS 13
  175424. #define PASS1_BITS 2
  175425. #else
  175426. #define CONST_BITS 13
  175427. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175428. #endif
  175429. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175430. * causing a lot of useless floating-point operations at run time.
  175431. * To get around this we use the following pre-calculated constants.
  175432. * If you change CONST_BITS you may want to add appropriate values.
  175433. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175434. */
  175435. #if CONST_BITS == 13
  175436. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  175437. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  175438. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  175439. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  175440. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  175441. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  175442. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  175443. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  175444. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  175445. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  175446. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  175447. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  175448. #else
  175449. #define FIX_0_298631336 FIX(0.298631336)
  175450. #define FIX_0_390180644 FIX(0.390180644)
  175451. #define FIX_0_541196100 FIX(0.541196100)
  175452. #define FIX_0_765366865 FIX(0.765366865)
  175453. #define FIX_0_899976223 FIX(0.899976223)
  175454. #define FIX_1_175875602 FIX(1.175875602)
  175455. #define FIX_1_501321110 FIX(1.501321110)
  175456. #define FIX_1_847759065 FIX(1.847759065)
  175457. #define FIX_1_961570560 FIX(1.961570560)
  175458. #define FIX_2_053119869 FIX(2.053119869)
  175459. #define FIX_2_562915447 FIX(2.562915447)
  175460. #define FIX_3_072711026 FIX(3.072711026)
  175461. #endif
  175462. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  175463. * For 8-bit samples with the recommended scaling, all the variable
  175464. * and constant values involved are no more than 16 bits wide, so a
  175465. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  175466. * For 12-bit samples, a full 32-bit multiplication will be needed.
  175467. */
  175468. #if BITS_IN_JSAMPLE == 8
  175469. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  175470. #else
  175471. #define MULTIPLY(var,const) ((var) * (const))
  175472. #endif
  175473. /*
  175474. * Perform the forward DCT on one block of samples.
  175475. */
  175476. GLOBAL(void)
  175477. jpeg_fdct_islow (DCTELEM * data)
  175478. {
  175479. INT32 tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175480. INT32 tmp10, tmp11, tmp12, tmp13;
  175481. INT32 z1, z2, z3, z4, z5;
  175482. DCTELEM *dataptr;
  175483. int ctr;
  175484. SHIFT_TEMPS
  175485. /* Pass 1: process rows. */
  175486. /* Note results are scaled up by sqrt(8) compared to a true DCT; */
  175487. /* furthermore, we scale the results by 2**PASS1_BITS. */
  175488. dataptr = data;
  175489. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  175490. tmp0 = dataptr[0] + dataptr[7];
  175491. tmp7 = dataptr[0] - dataptr[7];
  175492. tmp1 = dataptr[1] + dataptr[6];
  175493. tmp6 = dataptr[1] - dataptr[6];
  175494. tmp2 = dataptr[2] + dataptr[5];
  175495. tmp5 = dataptr[2] - dataptr[5];
  175496. tmp3 = dataptr[3] + dataptr[4];
  175497. tmp4 = dataptr[3] - dataptr[4];
  175498. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  175499. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  175500. */
  175501. tmp10 = tmp0 + tmp3;
  175502. tmp13 = tmp0 - tmp3;
  175503. tmp11 = tmp1 + tmp2;
  175504. tmp12 = tmp1 - tmp2;
  175505. dataptr[0] = (DCTELEM) ((tmp10 + tmp11) << PASS1_BITS);
  175506. dataptr[4] = (DCTELEM) ((tmp10 - tmp11) << PASS1_BITS);
  175507. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  175508. dataptr[2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  175509. CONST_BITS-PASS1_BITS);
  175510. dataptr[6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  175511. CONST_BITS-PASS1_BITS);
  175512. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  175513. * cK represents cos(K*pi/16).
  175514. * i0..i3 in the paper are tmp4..tmp7 here.
  175515. */
  175516. z1 = tmp4 + tmp7;
  175517. z2 = tmp5 + tmp6;
  175518. z3 = tmp4 + tmp6;
  175519. z4 = tmp5 + tmp7;
  175520. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175521. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175522. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175523. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175524. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175525. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175526. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175527. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175528. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175529. z3 += z5;
  175530. z4 += z5;
  175531. dataptr[7] = (DCTELEM) DESCALE(tmp4 + z1 + z3, CONST_BITS-PASS1_BITS);
  175532. dataptr[5] = (DCTELEM) DESCALE(tmp5 + z2 + z4, CONST_BITS-PASS1_BITS);
  175533. dataptr[3] = (DCTELEM) DESCALE(tmp6 + z2 + z3, CONST_BITS-PASS1_BITS);
  175534. dataptr[1] = (DCTELEM) DESCALE(tmp7 + z1 + z4, CONST_BITS-PASS1_BITS);
  175535. dataptr += DCTSIZE; /* advance pointer to next row */
  175536. }
  175537. /* Pass 2: process columns.
  175538. * We remove the PASS1_BITS scaling, but leave the results scaled up
  175539. * by an overall factor of 8.
  175540. */
  175541. dataptr = data;
  175542. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  175543. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  175544. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  175545. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  175546. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  175547. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  175548. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  175549. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  175550. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  175551. /* Even part per LL&M figure 1 --- note that published figure is faulty;
  175552. * rotator "sqrt(2)*c1" should be "sqrt(2)*c6".
  175553. */
  175554. tmp10 = tmp0 + tmp3;
  175555. tmp13 = tmp0 - tmp3;
  175556. tmp11 = tmp1 + tmp2;
  175557. tmp12 = tmp1 - tmp2;
  175558. dataptr[DCTSIZE*0] = (DCTELEM) DESCALE(tmp10 + tmp11, PASS1_BITS);
  175559. dataptr[DCTSIZE*4] = (DCTELEM) DESCALE(tmp10 - tmp11, PASS1_BITS);
  175560. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_541196100);
  175561. dataptr[DCTSIZE*2] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp13, FIX_0_765366865),
  175562. CONST_BITS+PASS1_BITS);
  175563. dataptr[DCTSIZE*6] = (DCTELEM) DESCALE(z1 + MULTIPLY(tmp12, - FIX_1_847759065),
  175564. CONST_BITS+PASS1_BITS);
  175565. /* Odd part per figure 8 --- note paper omits factor of sqrt(2).
  175566. * cK represents cos(K*pi/16).
  175567. * i0..i3 in the paper are tmp4..tmp7 here.
  175568. */
  175569. z1 = tmp4 + tmp7;
  175570. z2 = tmp5 + tmp6;
  175571. z3 = tmp4 + tmp6;
  175572. z4 = tmp5 + tmp7;
  175573. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  175574. tmp4 = MULTIPLY(tmp4, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  175575. tmp5 = MULTIPLY(tmp5, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  175576. tmp6 = MULTIPLY(tmp6, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  175577. tmp7 = MULTIPLY(tmp7, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  175578. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  175579. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  175580. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  175581. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  175582. z3 += z5;
  175583. z4 += z5;
  175584. dataptr[DCTSIZE*7] = (DCTELEM) DESCALE(tmp4 + z1 + z3,
  175585. CONST_BITS+PASS1_BITS);
  175586. dataptr[DCTSIZE*5] = (DCTELEM) DESCALE(tmp5 + z2 + z4,
  175587. CONST_BITS+PASS1_BITS);
  175588. dataptr[DCTSIZE*3] = (DCTELEM) DESCALE(tmp6 + z2 + z3,
  175589. CONST_BITS+PASS1_BITS);
  175590. dataptr[DCTSIZE*1] = (DCTELEM) DESCALE(tmp7 + z1 + z4,
  175591. CONST_BITS+PASS1_BITS);
  175592. dataptr++; /* advance pointer to next column */
  175593. }
  175594. }
  175595. #endif /* DCT_ISLOW_SUPPORTED */
  175596. /********* End of inlined file: jfdctint.c *********/
  175597. #undef CONST_BITS
  175598. #undef MULTIPLY
  175599. #undef FIX_0_541196100
  175600. /********* Start of inlined file: jfdctfst.c *********/
  175601. #define JPEG_INTERNALS
  175602. #ifdef DCT_IFAST_SUPPORTED
  175603. /*
  175604. * This module is specialized to the case DCTSIZE = 8.
  175605. */
  175606. #if DCTSIZE != 8
  175607. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175608. #endif
  175609. /* Scaling decisions are generally the same as in the LL&M algorithm;
  175610. * see jfdctint.c for more details. However, we choose to descale
  175611. * (right shift) multiplication products as soon as they are formed,
  175612. * rather than carrying additional fractional bits into subsequent additions.
  175613. * This compromises accuracy slightly, but it lets us save a few shifts.
  175614. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  175615. * everywhere except in the multiplications proper; this saves a good deal
  175616. * of work on 16-bit-int machines.
  175617. *
  175618. * Again to save a few shifts, the intermediate results between pass 1 and
  175619. * pass 2 are not upscaled, but are represented only to integral precision.
  175620. *
  175621. * A final compromise is to represent the multiplicative constants to only
  175622. * 8 fractional bits, rather than 13. This saves some shifting work on some
  175623. * machines, and may also reduce the cost of multiplication (since there
  175624. * are fewer one-bits in the constants).
  175625. */
  175626. #define CONST_BITS 8
  175627. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175628. * causing a lot of useless floating-point operations at run time.
  175629. * To get around this we use the following pre-calculated constants.
  175630. * If you change CONST_BITS you may want to add appropriate values.
  175631. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175632. */
  175633. #if CONST_BITS == 8
  175634. #define FIX_0_382683433 ((INT32) 98) /* FIX(0.382683433) */
  175635. #define FIX_0_541196100 ((INT32) 139) /* FIX(0.541196100) */
  175636. #define FIX_0_707106781 ((INT32) 181) /* FIX(0.707106781) */
  175637. #define FIX_1_306562965 ((INT32) 334) /* FIX(1.306562965) */
  175638. #else
  175639. #define FIX_0_382683433 FIX(0.382683433)
  175640. #define FIX_0_541196100 FIX(0.541196100)
  175641. #define FIX_0_707106781 FIX(0.707106781)
  175642. #define FIX_1_306562965 FIX(1.306562965)
  175643. #endif
  175644. /* We can gain a little more speed, with a further compromise in accuracy,
  175645. * by omitting the addition in a descaling shift. This yields an incorrectly
  175646. * rounded result half the time...
  175647. */
  175648. #ifndef USE_ACCURATE_ROUNDING
  175649. #undef DESCALE
  175650. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  175651. #endif
  175652. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  175653. * descale to yield a DCTELEM result.
  175654. */
  175655. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  175656. /*
  175657. * Perform the forward DCT on one block of samples.
  175658. */
  175659. GLOBAL(void)
  175660. jpeg_fdct_ifast (DCTELEM * data)
  175661. {
  175662. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175663. DCTELEM tmp10, tmp11, tmp12, tmp13;
  175664. DCTELEM z1, z2, z3, z4, z5, z11, z13;
  175665. DCTELEM *dataptr;
  175666. int ctr;
  175667. SHIFT_TEMPS
  175668. /* Pass 1: process rows. */
  175669. dataptr = data;
  175670. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  175671. tmp0 = dataptr[0] + dataptr[7];
  175672. tmp7 = dataptr[0] - dataptr[7];
  175673. tmp1 = dataptr[1] + dataptr[6];
  175674. tmp6 = dataptr[1] - dataptr[6];
  175675. tmp2 = dataptr[2] + dataptr[5];
  175676. tmp5 = dataptr[2] - dataptr[5];
  175677. tmp3 = dataptr[3] + dataptr[4];
  175678. tmp4 = dataptr[3] - dataptr[4];
  175679. /* Even part */
  175680. tmp10 = tmp0 + tmp3; /* phase 2 */
  175681. tmp13 = tmp0 - tmp3;
  175682. tmp11 = tmp1 + tmp2;
  175683. tmp12 = tmp1 - tmp2;
  175684. dataptr[0] = tmp10 + tmp11; /* phase 3 */
  175685. dataptr[4] = tmp10 - tmp11;
  175686. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  175687. dataptr[2] = tmp13 + z1; /* phase 5 */
  175688. dataptr[6] = tmp13 - z1;
  175689. /* Odd part */
  175690. tmp10 = tmp4 + tmp5; /* phase 2 */
  175691. tmp11 = tmp5 + tmp6;
  175692. tmp12 = tmp6 + tmp7;
  175693. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  175694. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  175695. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  175696. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  175697. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  175698. z11 = tmp7 + z3; /* phase 5 */
  175699. z13 = tmp7 - z3;
  175700. dataptr[5] = z13 + z2; /* phase 6 */
  175701. dataptr[3] = z13 - z2;
  175702. dataptr[1] = z11 + z4;
  175703. dataptr[7] = z11 - z4;
  175704. dataptr += DCTSIZE; /* advance pointer to next row */
  175705. }
  175706. /* Pass 2: process columns. */
  175707. dataptr = data;
  175708. for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
  175709. tmp0 = dataptr[DCTSIZE*0] + dataptr[DCTSIZE*7];
  175710. tmp7 = dataptr[DCTSIZE*0] - dataptr[DCTSIZE*7];
  175711. tmp1 = dataptr[DCTSIZE*1] + dataptr[DCTSIZE*6];
  175712. tmp6 = dataptr[DCTSIZE*1] - dataptr[DCTSIZE*6];
  175713. tmp2 = dataptr[DCTSIZE*2] + dataptr[DCTSIZE*5];
  175714. tmp5 = dataptr[DCTSIZE*2] - dataptr[DCTSIZE*5];
  175715. tmp3 = dataptr[DCTSIZE*3] + dataptr[DCTSIZE*4];
  175716. tmp4 = dataptr[DCTSIZE*3] - dataptr[DCTSIZE*4];
  175717. /* Even part */
  175718. tmp10 = tmp0 + tmp3; /* phase 2 */
  175719. tmp13 = tmp0 - tmp3;
  175720. tmp11 = tmp1 + tmp2;
  175721. tmp12 = tmp1 - tmp2;
  175722. dataptr[DCTSIZE*0] = tmp10 + tmp11; /* phase 3 */
  175723. dataptr[DCTSIZE*4] = tmp10 - tmp11;
  175724. z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
  175725. dataptr[DCTSIZE*2] = tmp13 + z1; /* phase 5 */
  175726. dataptr[DCTSIZE*6] = tmp13 - z1;
  175727. /* Odd part */
  175728. tmp10 = tmp4 + tmp5; /* phase 2 */
  175729. tmp11 = tmp5 + tmp6;
  175730. tmp12 = tmp6 + tmp7;
  175731. /* The rotator is modified from fig 4-8 to avoid extra negations. */
  175732. z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
  175733. z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
  175734. z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
  175735. z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
  175736. z11 = tmp7 + z3; /* phase 5 */
  175737. z13 = tmp7 - z3;
  175738. dataptr[DCTSIZE*5] = z13 + z2; /* phase 6 */
  175739. dataptr[DCTSIZE*3] = z13 - z2;
  175740. dataptr[DCTSIZE*1] = z11 + z4;
  175741. dataptr[DCTSIZE*7] = z11 - z4;
  175742. dataptr++; /* advance pointer to next column */
  175743. }
  175744. }
  175745. #endif /* DCT_IFAST_SUPPORTED */
  175746. /********* End of inlined file: jfdctfst.c *********/
  175747. #undef FIX_0_541196100
  175748. /********* Start of inlined file: jidctflt.c *********/
  175749. #define JPEG_INTERNALS
  175750. #ifdef DCT_FLOAT_SUPPORTED
  175751. /*
  175752. * This module is specialized to the case DCTSIZE = 8.
  175753. */
  175754. #if DCTSIZE != 8
  175755. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175756. #endif
  175757. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175758. * entry; produce a float result.
  175759. */
  175760. #define DEQUANTIZE(coef,quantval) (((FAST_FLOAT) (coef)) * (quantval))
  175761. /*
  175762. * Perform dequantization and inverse DCT on one block of coefficients.
  175763. */
  175764. GLOBAL(void)
  175765. jpeg_idct_float (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  175766. JCOEFPTR coef_block,
  175767. JSAMPARRAY output_buf, JDIMENSION output_col)
  175768. {
  175769. FAST_FLOAT tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  175770. FAST_FLOAT tmp10, tmp11, tmp12, tmp13;
  175771. FAST_FLOAT z5, z10, z11, z12, z13;
  175772. JCOEFPTR inptr;
  175773. FLOAT_MULT_TYPE * quantptr;
  175774. FAST_FLOAT * wsptr;
  175775. JSAMPROW outptr;
  175776. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  175777. int ctr;
  175778. FAST_FLOAT workspace[DCTSIZE2]; /* buffers data between passes */
  175779. SHIFT_TEMPS
  175780. /* Pass 1: process columns from input, store into work array. */
  175781. inptr = coef_block;
  175782. quantptr = (FLOAT_MULT_TYPE *) compptr->dct_table;
  175783. wsptr = workspace;
  175784. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  175785. /* Due to quantization, we will usually find that many of the input
  175786. * coefficients are zero, especially the AC terms. We can exploit this
  175787. * by short-circuiting the IDCT calculation for any column in which all
  175788. * the AC terms are zero. In that case each output is equal to the
  175789. * DC coefficient (with scale factor as needed).
  175790. * With typical images and quantization tables, half or more of the
  175791. * column DCT calculations can be simplified this way.
  175792. */
  175793. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  175794. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  175795. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  175796. inptr[DCTSIZE*7] == 0) {
  175797. /* AC terms all zero */
  175798. FAST_FLOAT dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175799. wsptr[DCTSIZE*0] = dcval;
  175800. wsptr[DCTSIZE*1] = dcval;
  175801. wsptr[DCTSIZE*2] = dcval;
  175802. wsptr[DCTSIZE*3] = dcval;
  175803. wsptr[DCTSIZE*4] = dcval;
  175804. wsptr[DCTSIZE*5] = dcval;
  175805. wsptr[DCTSIZE*6] = dcval;
  175806. wsptr[DCTSIZE*7] = dcval;
  175807. inptr++; /* advance pointers to next column */
  175808. quantptr++;
  175809. wsptr++;
  175810. continue;
  175811. }
  175812. /* Even part */
  175813. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  175814. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  175815. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  175816. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  175817. tmp10 = tmp0 + tmp2; /* phase 3 */
  175818. tmp11 = tmp0 - tmp2;
  175819. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  175820. tmp12 = (tmp1 - tmp3) * ((FAST_FLOAT) 1.414213562) - tmp13; /* 2*c4 */
  175821. tmp0 = tmp10 + tmp13; /* phase 2 */
  175822. tmp3 = tmp10 - tmp13;
  175823. tmp1 = tmp11 + tmp12;
  175824. tmp2 = tmp11 - tmp12;
  175825. /* Odd part */
  175826. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  175827. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  175828. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  175829. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  175830. z13 = tmp6 + tmp5; /* phase 6 */
  175831. z10 = tmp6 - tmp5;
  175832. z11 = tmp4 + tmp7;
  175833. z12 = tmp4 - tmp7;
  175834. tmp7 = z11 + z13; /* phase 5 */
  175835. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562); /* 2*c4 */
  175836. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175837. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175838. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175839. tmp6 = tmp12 - tmp7; /* phase 2 */
  175840. tmp5 = tmp11 - tmp6;
  175841. tmp4 = tmp10 + tmp5;
  175842. wsptr[DCTSIZE*0] = tmp0 + tmp7;
  175843. wsptr[DCTSIZE*7] = tmp0 - tmp7;
  175844. wsptr[DCTSIZE*1] = tmp1 + tmp6;
  175845. wsptr[DCTSIZE*6] = tmp1 - tmp6;
  175846. wsptr[DCTSIZE*2] = tmp2 + tmp5;
  175847. wsptr[DCTSIZE*5] = tmp2 - tmp5;
  175848. wsptr[DCTSIZE*4] = tmp3 + tmp4;
  175849. wsptr[DCTSIZE*3] = tmp3 - tmp4;
  175850. inptr++; /* advance pointers to next column */
  175851. quantptr++;
  175852. wsptr++;
  175853. }
  175854. /* Pass 2: process rows from work array, store into output array. */
  175855. /* Note that we must descale the results by a factor of 8 == 2**3. */
  175856. wsptr = workspace;
  175857. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  175858. outptr = output_buf[ctr] + output_col;
  175859. /* Rows of zeroes can be exploited in the same way as we did with columns.
  175860. * However, the column calculation has created many nonzero AC terms, so
  175861. * the simplification applies less often (typically 5% to 10% of the time).
  175862. * And testing floats for zero is relatively expensive, so we don't bother.
  175863. */
  175864. /* Even part */
  175865. tmp10 = wsptr[0] + wsptr[4];
  175866. tmp11 = wsptr[0] - wsptr[4];
  175867. tmp13 = wsptr[2] + wsptr[6];
  175868. tmp12 = (wsptr[2] - wsptr[6]) * ((FAST_FLOAT) 1.414213562) - tmp13;
  175869. tmp0 = tmp10 + tmp13;
  175870. tmp3 = tmp10 - tmp13;
  175871. tmp1 = tmp11 + tmp12;
  175872. tmp2 = tmp11 - tmp12;
  175873. /* Odd part */
  175874. z13 = wsptr[5] + wsptr[3];
  175875. z10 = wsptr[5] - wsptr[3];
  175876. z11 = wsptr[1] + wsptr[7];
  175877. z12 = wsptr[1] - wsptr[7];
  175878. tmp7 = z11 + z13;
  175879. tmp11 = (z11 - z13) * ((FAST_FLOAT) 1.414213562);
  175880. z5 = (z10 + z12) * ((FAST_FLOAT) 1.847759065); /* 2*c2 */
  175881. tmp10 = ((FAST_FLOAT) 1.082392200) * z12 - z5; /* 2*(c2-c6) */
  175882. tmp12 = ((FAST_FLOAT) -2.613125930) * z10 + z5; /* -2*(c2+c6) */
  175883. tmp6 = tmp12 - tmp7;
  175884. tmp5 = tmp11 - tmp6;
  175885. tmp4 = tmp10 + tmp5;
  175886. /* Final output stage: scale down by a factor of 8 and range-limit */
  175887. outptr[0] = range_limit[(int) DESCALE((INT32) (tmp0 + tmp7), 3)
  175888. & RANGE_MASK];
  175889. outptr[7] = range_limit[(int) DESCALE((INT32) (tmp0 - tmp7), 3)
  175890. & RANGE_MASK];
  175891. outptr[1] = range_limit[(int) DESCALE((INT32) (tmp1 + tmp6), 3)
  175892. & RANGE_MASK];
  175893. outptr[6] = range_limit[(int) DESCALE((INT32) (tmp1 - tmp6), 3)
  175894. & RANGE_MASK];
  175895. outptr[2] = range_limit[(int) DESCALE((INT32) (tmp2 + tmp5), 3)
  175896. & RANGE_MASK];
  175897. outptr[5] = range_limit[(int) DESCALE((INT32) (tmp2 - tmp5), 3)
  175898. & RANGE_MASK];
  175899. outptr[4] = range_limit[(int) DESCALE((INT32) (tmp3 + tmp4), 3)
  175900. & RANGE_MASK];
  175901. outptr[3] = range_limit[(int) DESCALE((INT32) (tmp3 - tmp4), 3)
  175902. & RANGE_MASK];
  175903. wsptr += DCTSIZE; /* advance pointer to next row */
  175904. }
  175905. }
  175906. #endif /* DCT_FLOAT_SUPPORTED */
  175907. /********* End of inlined file: jidctflt.c *********/
  175908. #undef CONST_BITS
  175909. #undef FIX_1_847759065
  175910. #undef MULTIPLY
  175911. #undef DEQUANTIZE
  175912. #undef DESCALE
  175913. /********* Start of inlined file: jidctfst.c *********/
  175914. #define JPEG_INTERNALS
  175915. #ifdef DCT_IFAST_SUPPORTED
  175916. /*
  175917. * This module is specialized to the case DCTSIZE = 8.
  175918. */
  175919. #if DCTSIZE != 8
  175920. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  175921. #endif
  175922. /* Scaling decisions are generally the same as in the LL&M algorithm;
  175923. * see jidctint.c for more details. However, we choose to descale
  175924. * (right shift) multiplication products as soon as they are formed,
  175925. * rather than carrying additional fractional bits into subsequent additions.
  175926. * This compromises accuracy slightly, but it lets us save a few shifts.
  175927. * More importantly, 16-bit arithmetic is then adequate (for 8-bit samples)
  175928. * everywhere except in the multiplications proper; this saves a good deal
  175929. * of work on 16-bit-int machines.
  175930. *
  175931. * The dequantized coefficients are not integers because the AA&N scaling
  175932. * factors have been incorporated. We represent them scaled up by PASS1_BITS,
  175933. * so that the first and second IDCT rounds have the same input scaling.
  175934. * For 8-bit JSAMPLEs, we choose IFAST_SCALE_BITS = PASS1_BITS so as to
  175935. * avoid a descaling shift; this compromises accuracy rather drastically
  175936. * for small quantization table entries, but it saves a lot of shifts.
  175937. * For 12-bit JSAMPLEs, there's no hope of using 16x16 multiplies anyway,
  175938. * so we use a much larger scaling factor to preserve accuracy.
  175939. *
  175940. * A final compromise is to represent the multiplicative constants to only
  175941. * 8 fractional bits, rather than 13. This saves some shifting work on some
  175942. * machines, and may also reduce the cost of multiplication (since there
  175943. * are fewer one-bits in the constants).
  175944. */
  175945. #if BITS_IN_JSAMPLE == 8
  175946. #define CONST_BITS 8
  175947. #define PASS1_BITS 2
  175948. #else
  175949. #define CONST_BITS 8
  175950. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  175951. #endif
  175952. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  175953. * causing a lot of useless floating-point operations at run time.
  175954. * To get around this we use the following pre-calculated constants.
  175955. * If you change CONST_BITS you may want to add appropriate values.
  175956. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  175957. */
  175958. #if CONST_BITS == 8
  175959. #define FIX_1_082392200 ((INT32) 277) /* FIX(1.082392200) */
  175960. #define FIX_1_414213562 ((INT32) 362) /* FIX(1.414213562) */
  175961. #define FIX_1_847759065 ((INT32) 473) /* FIX(1.847759065) */
  175962. #define FIX_2_613125930 ((INT32) 669) /* FIX(2.613125930) */
  175963. #else
  175964. #define FIX_1_082392200 FIX(1.082392200)
  175965. #define FIX_1_414213562 FIX(1.414213562)
  175966. #define FIX_1_847759065 FIX(1.847759065)
  175967. #define FIX_2_613125930 FIX(2.613125930)
  175968. #endif
  175969. /* We can gain a little more speed, with a further compromise in accuracy,
  175970. * by omitting the addition in a descaling shift. This yields an incorrectly
  175971. * rounded result half the time...
  175972. */
  175973. #ifndef USE_ACCURATE_ROUNDING
  175974. #undef DESCALE
  175975. #define DESCALE(x,n) RIGHT_SHIFT(x, n)
  175976. #endif
  175977. /* Multiply a DCTELEM variable by an INT32 constant, and immediately
  175978. * descale to yield a DCTELEM result.
  175979. */
  175980. #define MULTIPLY(var,const) ((DCTELEM) DESCALE((var) * (const), CONST_BITS))
  175981. /* Dequantize a coefficient by multiplying it by the multiplier-table
  175982. * entry; produce a DCTELEM result. For 8-bit data a 16x16->16
  175983. * multiplication will do. For 12-bit data, the multiplier table is
  175984. * declared INT32, so a 32-bit multiply will be used.
  175985. */
  175986. #if BITS_IN_JSAMPLE == 8
  175987. #define DEQUANTIZE(coef,quantval) (((IFAST_MULT_TYPE) (coef)) * (quantval))
  175988. #else
  175989. #define DEQUANTIZE(coef,quantval) \
  175990. DESCALE((coef)*(quantval), IFAST_SCALE_BITS-PASS1_BITS)
  175991. #endif
  175992. /* Like DESCALE, but applies to a DCTELEM and produces an int.
  175993. * We assume that int right shift is unsigned if INT32 right shift is.
  175994. */
  175995. #ifdef RIGHT_SHIFT_IS_UNSIGNED
  175996. #define ISHIFT_TEMPS DCTELEM ishift_temp;
  175997. #if BITS_IN_JSAMPLE == 8
  175998. #define DCTELEMBITS 16 /* DCTELEM may be 16 or 32 bits */
  175999. #else
  176000. #define DCTELEMBITS 32 /* DCTELEM must be 32 bits */
  176001. #endif
  176002. #define IRIGHT_SHIFT(x,shft) \
  176003. ((ishift_temp = (x)) < 0 ? \
  176004. (ishift_temp >> (shft)) | ((~((DCTELEM) 0)) << (DCTELEMBITS-(shft))) : \
  176005. (ishift_temp >> (shft)))
  176006. #else
  176007. #define ISHIFT_TEMPS
  176008. #define IRIGHT_SHIFT(x,shft) ((x) >> (shft))
  176009. #endif
  176010. #ifdef USE_ACCURATE_ROUNDING
  176011. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT((x) + (1 << ((n)-1)), n))
  176012. #else
  176013. #define IDESCALE(x,n) ((int) IRIGHT_SHIFT(x, n))
  176014. #endif
  176015. /*
  176016. * Perform dequantization and inverse DCT on one block of coefficients.
  176017. */
  176018. GLOBAL(void)
  176019. jpeg_idct_ifast (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  176020. JCOEFPTR coef_block,
  176021. JSAMPARRAY output_buf, JDIMENSION output_col)
  176022. {
  176023. DCTELEM tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
  176024. DCTELEM tmp10, tmp11, tmp12, tmp13;
  176025. DCTELEM z5, z10, z11, z12, z13;
  176026. JCOEFPTR inptr;
  176027. IFAST_MULT_TYPE * quantptr;
  176028. int * wsptr;
  176029. JSAMPROW outptr;
  176030. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  176031. int ctr;
  176032. int workspace[DCTSIZE2]; /* buffers data between passes */
  176033. SHIFT_TEMPS /* for DESCALE */
  176034. ISHIFT_TEMPS /* for IDESCALE */
  176035. /* Pass 1: process columns from input, store into work array. */
  176036. inptr = coef_block;
  176037. quantptr = (IFAST_MULT_TYPE *) compptr->dct_table;
  176038. wsptr = workspace;
  176039. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  176040. /* Due to quantization, we will usually find that many of the input
  176041. * coefficients are zero, especially the AC terms. We can exploit this
  176042. * by short-circuiting the IDCT calculation for any column in which all
  176043. * the AC terms are zero. In that case each output is equal to the
  176044. * DC coefficient (with scale factor as needed).
  176045. * With typical images and quantization tables, half or more of the
  176046. * column DCT calculations can be simplified this way.
  176047. */
  176048. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  176049. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  176050. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  176051. inptr[DCTSIZE*7] == 0) {
  176052. /* AC terms all zero */
  176053. int dcval = (int) DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  176054. wsptr[DCTSIZE*0] = dcval;
  176055. wsptr[DCTSIZE*1] = dcval;
  176056. wsptr[DCTSIZE*2] = dcval;
  176057. wsptr[DCTSIZE*3] = dcval;
  176058. wsptr[DCTSIZE*4] = dcval;
  176059. wsptr[DCTSIZE*5] = dcval;
  176060. wsptr[DCTSIZE*6] = dcval;
  176061. wsptr[DCTSIZE*7] = dcval;
  176062. inptr++; /* advance pointers to next column */
  176063. quantptr++;
  176064. wsptr++;
  176065. continue;
  176066. }
  176067. /* Even part */
  176068. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  176069. tmp1 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  176070. tmp2 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  176071. tmp3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  176072. tmp10 = tmp0 + tmp2; /* phase 3 */
  176073. tmp11 = tmp0 - tmp2;
  176074. tmp13 = tmp1 + tmp3; /* phases 5-3 */
  176075. tmp12 = MULTIPLY(tmp1 - tmp3, FIX_1_414213562) - tmp13; /* 2*c4 */
  176076. tmp0 = tmp10 + tmp13; /* phase 2 */
  176077. tmp3 = tmp10 - tmp13;
  176078. tmp1 = tmp11 + tmp12;
  176079. tmp2 = tmp11 - tmp12;
  176080. /* Odd part */
  176081. tmp4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  176082. tmp5 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  176083. tmp6 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  176084. tmp7 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  176085. z13 = tmp6 + tmp5; /* phase 6 */
  176086. z10 = tmp6 - tmp5;
  176087. z11 = tmp4 + tmp7;
  176088. z12 = tmp4 - tmp7;
  176089. tmp7 = z11 + z13; /* phase 5 */
  176090. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  176091. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  176092. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  176093. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  176094. tmp6 = tmp12 - tmp7; /* phase 2 */
  176095. tmp5 = tmp11 - tmp6;
  176096. tmp4 = tmp10 + tmp5;
  176097. wsptr[DCTSIZE*0] = (int) (tmp0 + tmp7);
  176098. wsptr[DCTSIZE*7] = (int) (tmp0 - tmp7);
  176099. wsptr[DCTSIZE*1] = (int) (tmp1 + tmp6);
  176100. wsptr[DCTSIZE*6] = (int) (tmp1 - tmp6);
  176101. wsptr[DCTSIZE*2] = (int) (tmp2 + tmp5);
  176102. wsptr[DCTSIZE*5] = (int) (tmp2 - tmp5);
  176103. wsptr[DCTSIZE*4] = (int) (tmp3 + tmp4);
  176104. wsptr[DCTSIZE*3] = (int) (tmp3 - tmp4);
  176105. inptr++; /* advance pointers to next column */
  176106. quantptr++;
  176107. wsptr++;
  176108. }
  176109. /* Pass 2: process rows from work array, store into output array. */
  176110. /* Note that we must descale the results by a factor of 8 == 2**3, */
  176111. /* and also undo the PASS1_BITS scaling. */
  176112. wsptr = workspace;
  176113. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  176114. outptr = output_buf[ctr] + output_col;
  176115. /* Rows of zeroes can be exploited in the same way as we did with columns.
  176116. * However, the column calculation has created many nonzero AC terms, so
  176117. * the simplification applies less often (typically 5% to 10% of the time).
  176118. * On machines with very fast multiplication, it's possible that the
  176119. * test takes more time than it's worth. In that case this section
  176120. * may be commented out.
  176121. */
  176122. #ifndef NO_ZERO_ROW_TEST
  176123. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  176124. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  176125. /* AC terms all zero */
  176126. JSAMPLE dcval = range_limit[IDESCALE(wsptr[0], PASS1_BITS+3)
  176127. & RANGE_MASK];
  176128. outptr[0] = dcval;
  176129. outptr[1] = dcval;
  176130. outptr[2] = dcval;
  176131. outptr[3] = dcval;
  176132. outptr[4] = dcval;
  176133. outptr[5] = dcval;
  176134. outptr[6] = dcval;
  176135. outptr[7] = dcval;
  176136. wsptr += DCTSIZE; /* advance pointer to next row */
  176137. continue;
  176138. }
  176139. #endif
  176140. /* Even part */
  176141. tmp10 = ((DCTELEM) wsptr[0] + (DCTELEM) wsptr[4]);
  176142. tmp11 = ((DCTELEM) wsptr[0] - (DCTELEM) wsptr[4]);
  176143. tmp13 = ((DCTELEM) wsptr[2] + (DCTELEM) wsptr[6]);
  176144. tmp12 = MULTIPLY((DCTELEM) wsptr[2] - (DCTELEM) wsptr[6], FIX_1_414213562)
  176145. - tmp13;
  176146. tmp0 = tmp10 + tmp13;
  176147. tmp3 = tmp10 - tmp13;
  176148. tmp1 = tmp11 + tmp12;
  176149. tmp2 = tmp11 - tmp12;
  176150. /* Odd part */
  176151. z13 = (DCTELEM) wsptr[5] + (DCTELEM) wsptr[3];
  176152. z10 = (DCTELEM) wsptr[5] - (DCTELEM) wsptr[3];
  176153. z11 = (DCTELEM) wsptr[1] + (DCTELEM) wsptr[7];
  176154. z12 = (DCTELEM) wsptr[1] - (DCTELEM) wsptr[7];
  176155. tmp7 = z11 + z13; /* phase 5 */
  176156. tmp11 = MULTIPLY(z11 - z13, FIX_1_414213562); /* 2*c4 */
  176157. z5 = MULTIPLY(z10 + z12, FIX_1_847759065); /* 2*c2 */
  176158. tmp10 = MULTIPLY(z12, FIX_1_082392200) - z5; /* 2*(c2-c6) */
  176159. tmp12 = MULTIPLY(z10, - FIX_2_613125930) + z5; /* -2*(c2+c6) */
  176160. tmp6 = tmp12 - tmp7; /* phase 2 */
  176161. tmp5 = tmp11 - tmp6;
  176162. tmp4 = tmp10 + tmp5;
  176163. /* Final output stage: scale down by a factor of 8 and range-limit */
  176164. outptr[0] = range_limit[IDESCALE(tmp0 + tmp7, PASS1_BITS+3)
  176165. & RANGE_MASK];
  176166. outptr[7] = range_limit[IDESCALE(tmp0 - tmp7, PASS1_BITS+3)
  176167. & RANGE_MASK];
  176168. outptr[1] = range_limit[IDESCALE(tmp1 + tmp6, PASS1_BITS+3)
  176169. & RANGE_MASK];
  176170. outptr[6] = range_limit[IDESCALE(tmp1 - tmp6, PASS1_BITS+3)
  176171. & RANGE_MASK];
  176172. outptr[2] = range_limit[IDESCALE(tmp2 + tmp5, PASS1_BITS+3)
  176173. & RANGE_MASK];
  176174. outptr[5] = range_limit[IDESCALE(tmp2 - tmp5, PASS1_BITS+3)
  176175. & RANGE_MASK];
  176176. outptr[4] = range_limit[IDESCALE(tmp3 + tmp4, PASS1_BITS+3)
  176177. & RANGE_MASK];
  176178. outptr[3] = range_limit[IDESCALE(tmp3 - tmp4, PASS1_BITS+3)
  176179. & RANGE_MASK];
  176180. wsptr += DCTSIZE; /* advance pointer to next row */
  176181. }
  176182. }
  176183. #endif /* DCT_IFAST_SUPPORTED */
  176184. /********* End of inlined file: jidctfst.c *********/
  176185. #undef CONST_BITS
  176186. #undef FIX_1_847759065
  176187. #undef MULTIPLY
  176188. #undef DEQUANTIZE
  176189. /********* Start of inlined file: jidctint.c *********/
  176190. #define JPEG_INTERNALS
  176191. #ifdef DCT_ISLOW_SUPPORTED
  176192. /*
  176193. * This module is specialized to the case DCTSIZE = 8.
  176194. */
  176195. #if DCTSIZE != 8
  176196. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  176197. #endif
  176198. /*
  176199. * The poop on this scaling stuff is as follows:
  176200. *
  176201. * Each 1-D IDCT step produces outputs which are a factor of sqrt(N)
  176202. * larger than the true IDCT outputs. The final outputs are therefore
  176203. * a factor of N larger than desired; since N=8 this can be cured by
  176204. * a simple right shift at the end of the algorithm. The advantage of
  176205. * this arrangement is that we save two multiplications per 1-D IDCT,
  176206. * because the y0 and y4 inputs need not be divided by sqrt(N).
  176207. *
  176208. * We have to do addition and subtraction of the integer inputs, which
  176209. * is no problem, and multiplication by fractional constants, which is
  176210. * a problem to do in integer arithmetic. We multiply all the constants
  176211. * by CONST_SCALE and convert them to integer constants (thus retaining
  176212. * CONST_BITS bits of precision in the constants). After doing a
  176213. * multiplication we have to divide the product by CONST_SCALE, with proper
  176214. * rounding, to produce the correct output. This division can be done
  176215. * cheaply as a right shift of CONST_BITS bits. We postpone shifting
  176216. * as long as possible so that partial sums can be added together with
  176217. * full fractional precision.
  176218. *
  176219. * The outputs of the first pass are scaled up by PASS1_BITS bits so that
  176220. * they are represented to better-than-integral precision. These outputs
  176221. * require BITS_IN_JSAMPLE + PASS1_BITS + 3 bits; this fits in a 16-bit word
  176222. * with the recommended scaling. (To scale up 12-bit sample data further, an
  176223. * intermediate INT32 array would be needed.)
  176224. *
  176225. * To avoid overflow of the 32-bit intermediate results in pass 2, we must
  176226. * have BITS_IN_JSAMPLE + CONST_BITS + PASS1_BITS <= 26. Error analysis
  176227. * shows that the values given below are the most effective.
  176228. */
  176229. #if BITS_IN_JSAMPLE == 8
  176230. #define CONST_BITS 13
  176231. #define PASS1_BITS 2
  176232. #else
  176233. #define CONST_BITS 13
  176234. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  176235. #endif
  176236. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  176237. * causing a lot of useless floating-point operations at run time.
  176238. * To get around this we use the following pre-calculated constants.
  176239. * If you change CONST_BITS you may want to add appropriate values.
  176240. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  176241. */
  176242. #if CONST_BITS == 13
  176243. #define FIX_0_298631336 ((INT32) 2446) /* FIX(0.298631336) */
  176244. #define FIX_0_390180644 ((INT32) 3196) /* FIX(0.390180644) */
  176245. #define FIX_0_541196100 ((INT32) 4433) /* FIX(0.541196100) */
  176246. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  176247. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  176248. #define FIX_1_175875602 ((INT32) 9633) /* FIX(1.175875602) */
  176249. #define FIX_1_501321110 ((INT32) 12299) /* FIX(1.501321110) */
  176250. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  176251. #define FIX_1_961570560 ((INT32) 16069) /* FIX(1.961570560) */
  176252. #define FIX_2_053119869 ((INT32) 16819) /* FIX(2.053119869) */
  176253. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  176254. #define FIX_3_072711026 ((INT32) 25172) /* FIX(3.072711026) */
  176255. #else
  176256. #define FIX_0_298631336 FIX(0.298631336)
  176257. #define FIX_0_390180644 FIX(0.390180644)
  176258. #define FIX_0_541196100 FIX(0.541196100)
  176259. #define FIX_0_765366865 FIX(0.765366865)
  176260. #define FIX_0_899976223 FIX(0.899976223)
  176261. #define FIX_1_175875602 FIX(1.175875602)
  176262. #define FIX_1_501321110 FIX(1.501321110)
  176263. #define FIX_1_847759065 FIX(1.847759065)
  176264. #define FIX_1_961570560 FIX(1.961570560)
  176265. #define FIX_2_053119869 FIX(2.053119869)
  176266. #define FIX_2_562915447 FIX(2.562915447)
  176267. #define FIX_3_072711026 FIX(3.072711026)
  176268. #endif
  176269. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  176270. * For 8-bit samples with the recommended scaling, all the variable
  176271. * and constant values involved are no more than 16 bits wide, so a
  176272. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  176273. * For 12-bit samples, a full 32-bit multiplication will be needed.
  176274. */
  176275. #if BITS_IN_JSAMPLE == 8
  176276. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  176277. #else
  176278. #define MULTIPLY(var,const) ((var) * (const))
  176279. #endif
  176280. /* Dequantize a coefficient by multiplying it by the multiplier-table
  176281. * entry; produce an int result. In this module, both inputs and result
  176282. * are 16 bits or less, so either int or short multiply will work.
  176283. */
  176284. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  176285. /*
  176286. * Perform dequantization and inverse DCT on one block of coefficients.
  176287. */
  176288. GLOBAL(void)
  176289. jpeg_idct_islow (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  176290. JCOEFPTR coef_block,
  176291. JSAMPARRAY output_buf, JDIMENSION output_col)
  176292. {
  176293. INT32 tmp0, tmp1, tmp2, tmp3;
  176294. INT32 tmp10, tmp11, tmp12, tmp13;
  176295. INT32 z1, z2, z3, z4, z5;
  176296. JCOEFPTR inptr;
  176297. ISLOW_MULT_TYPE * quantptr;
  176298. int * wsptr;
  176299. JSAMPROW outptr;
  176300. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  176301. int ctr;
  176302. int workspace[DCTSIZE2]; /* buffers data between passes */
  176303. SHIFT_TEMPS
  176304. /* Pass 1: process columns from input, store into work array. */
  176305. /* Note results are scaled up by sqrt(8) compared to a true IDCT; */
  176306. /* furthermore, we scale the results by 2**PASS1_BITS. */
  176307. inptr = coef_block;
  176308. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  176309. wsptr = workspace;
  176310. for (ctr = DCTSIZE; ctr > 0; ctr--) {
  176311. /* Due to quantization, we will usually find that many of the input
  176312. * coefficients are zero, especially the AC terms. We can exploit this
  176313. * by short-circuiting the IDCT calculation for any column in which all
  176314. * the AC terms are zero. In that case each output is equal to the
  176315. * DC coefficient (with scale factor as needed).
  176316. * With typical images and quantization tables, half or more of the
  176317. * column DCT calculations can be simplified this way.
  176318. */
  176319. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  176320. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*4] == 0 &&
  176321. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*6] == 0 &&
  176322. inptr[DCTSIZE*7] == 0) {
  176323. /* AC terms all zero */
  176324. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  176325. wsptr[DCTSIZE*0] = dcval;
  176326. wsptr[DCTSIZE*1] = dcval;
  176327. wsptr[DCTSIZE*2] = dcval;
  176328. wsptr[DCTSIZE*3] = dcval;
  176329. wsptr[DCTSIZE*4] = dcval;
  176330. wsptr[DCTSIZE*5] = dcval;
  176331. wsptr[DCTSIZE*6] = dcval;
  176332. wsptr[DCTSIZE*7] = dcval;
  176333. inptr++; /* advance pointers to next column */
  176334. quantptr++;
  176335. wsptr++;
  176336. continue;
  176337. }
  176338. /* Even part: reverse the even part of the forward DCT. */
  176339. /* The rotator is sqrt(2)*c(-6). */
  176340. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  176341. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  176342. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  176343. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  176344. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  176345. z2 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  176346. z3 = DEQUANTIZE(inptr[DCTSIZE*4], quantptr[DCTSIZE*4]);
  176347. tmp0 = (z2 + z3) << CONST_BITS;
  176348. tmp1 = (z2 - z3) << CONST_BITS;
  176349. tmp10 = tmp0 + tmp3;
  176350. tmp13 = tmp0 - tmp3;
  176351. tmp11 = tmp1 + tmp2;
  176352. tmp12 = tmp1 - tmp2;
  176353. /* Odd part per figure 8; the matrix is unitary and hence its
  176354. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  176355. */
  176356. tmp0 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  176357. tmp1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  176358. tmp2 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  176359. tmp3 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  176360. z1 = tmp0 + tmp3;
  176361. z2 = tmp1 + tmp2;
  176362. z3 = tmp0 + tmp2;
  176363. z4 = tmp1 + tmp3;
  176364. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  176365. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  176366. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  176367. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  176368. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  176369. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  176370. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  176371. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  176372. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  176373. z3 += z5;
  176374. z4 += z5;
  176375. tmp0 += z1 + z3;
  176376. tmp1 += z2 + z4;
  176377. tmp2 += z2 + z3;
  176378. tmp3 += z1 + z4;
  176379. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  176380. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp3, CONST_BITS-PASS1_BITS);
  176381. wsptr[DCTSIZE*7] = (int) DESCALE(tmp10 - tmp3, CONST_BITS-PASS1_BITS);
  176382. wsptr[DCTSIZE*1] = (int) DESCALE(tmp11 + tmp2, CONST_BITS-PASS1_BITS);
  176383. wsptr[DCTSIZE*6] = (int) DESCALE(tmp11 - tmp2, CONST_BITS-PASS1_BITS);
  176384. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 + tmp1, CONST_BITS-PASS1_BITS);
  176385. wsptr[DCTSIZE*5] = (int) DESCALE(tmp12 - tmp1, CONST_BITS-PASS1_BITS);
  176386. wsptr[DCTSIZE*3] = (int) DESCALE(tmp13 + tmp0, CONST_BITS-PASS1_BITS);
  176387. wsptr[DCTSIZE*4] = (int) DESCALE(tmp13 - tmp0, CONST_BITS-PASS1_BITS);
  176388. inptr++; /* advance pointers to next column */
  176389. quantptr++;
  176390. wsptr++;
  176391. }
  176392. /* Pass 2: process rows from work array, store into output array. */
  176393. /* Note that we must descale the results by a factor of 8 == 2**3, */
  176394. /* and also undo the PASS1_BITS scaling. */
  176395. wsptr = workspace;
  176396. for (ctr = 0; ctr < DCTSIZE; ctr++) {
  176397. outptr = output_buf[ctr] + output_col;
  176398. /* Rows of zeroes can be exploited in the same way as we did with columns.
  176399. * However, the column calculation has created many nonzero AC terms, so
  176400. * the simplification applies less often (typically 5% to 10% of the time).
  176401. * On machines with very fast multiplication, it's possible that the
  176402. * test takes more time than it's worth. In that case this section
  176403. * may be commented out.
  176404. */
  176405. #ifndef NO_ZERO_ROW_TEST
  176406. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 && wsptr[4] == 0 &&
  176407. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  176408. /* AC terms all zero */
  176409. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  176410. & RANGE_MASK];
  176411. outptr[0] = dcval;
  176412. outptr[1] = dcval;
  176413. outptr[2] = dcval;
  176414. outptr[3] = dcval;
  176415. outptr[4] = dcval;
  176416. outptr[5] = dcval;
  176417. outptr[6] = dcval;
  176418. outptr[7] = dcval;
  176419. wsptr += DCTSIZE; /* advance pointer to next row */
  176420. continue;
  176421. }
  176422. #endif
  176423. /* Even part: reverse the even part of the forward DCT. */
  176424. /* The rotator is sqrt(2)*c(-6). */
  176425. z2 = (INT32) wsptr[2];
  176426. z3 = (INT32) wsptr[6];
  176427. z1 = MULTIPLY(z2 + z3, FIX_0_541196100);
  176428. tmp2 = z1 + MULTIPLY(z3, - FIX_1_847759065);
  176429. tmp3 = z1 + MULTIPLY(z2, FIX_0_765366865);
  176430. tmp0 = ((INT32) wsptr[0] + (INT32) wsptr[4]) << CONST_BITS;
  176431. tmp1 = ((INT32) wsptr[0] - (INT32) wsptr[4]) << CONST_BITS;
  176432. tmp10 = tmp0 + tmp3;
  176433. tmp13 = tmp0 - tmp3;
  176434. tmp11 = tmp1 + tmp2;
  176435. tmp12 = tmp1 - tmp2;
  176436. /* Odd part per figure 8; the matrix is unitary and hence its
  176437. * transpose is its inverse. i0..i3 are y7,y5,y3,y1 respectively.
  176438. */
  176439. tmp0 = (INT32) wsptr[7];
  176440. tmp1 = (INT32) wsptr[5];
  176441. tmp2 = (INT32) wsptr[3];
  176442. tmp3 = (INT32) wsptr[1];
  176443. z1 = tmp0 + tmp3;
  176444. z2 = tmp1 + tmp2;
  176445. z3 = tmp0 + tmp2;
  176446. z4 = tmp1 + tmp3;
  176447. z5 = MULTIPLY(z3 + z4, FIX_1_175875602); /* sqrt(2) * c3 */
  176448. tmp0 = MULTIPLY(tmp0, FIX_0_298631336); /* sqrt(2) * (-c1+c3+c5-c7) */
  176449. tmp1 = MULTIPLY(tmp1, FIX_2_053119869); /* sqrt(2) * ( c1+c3-c5+c7) */
  176450. tmp2 = MULTIPLY(tmp2, FIX_3_072711026); /* sqrt(2) * ( c1+c3+c5-c7) */
  176451. tmp3 = MULTIPLY(tmp3, FIX_1_501321110); /* sqrt(2) * ( c1+c3-c5-c7) */
  176452. z1 = MULTIPLY(z1, - FIX_0_899976223); /* sqrt(2) * (c7-c3) */
  176453. z2 = MULTIPLY(z2, - FIX_2_562915447); /* sqrt(2) * (-c1-c3) */
  176454. z3 = MULTIPLY(z3, - FIX_1_961570560); /* sqrt(2) * (-c3-c5) */
  176455. z4 = MULTIPLY(z4, - FIX_0_390180644); /* sqrt(2) * (c5-c3) */
  176456. z3 += z5;
  176457. z4 += z5;
  176458. tmp0 += z1 + z3;
  176459. tmp1 += z2 + z4;
  176460. tmp2 += z2 + z3;
  176461. tmp3 += z1 + z4;
  176462. /* Final output stage: inputs are tmp10..tmp13, tmp0..tmp3 */
  176463. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp3,
  176464. CONST_BITS+PASS1_BITS+3)
  176465. & RANGE_MASK];
  176466. outptr[7] = range_limit[(int) DESCALE(tmp10 - tmp3,
  176467. CONST_BITS+PASS1_BITS+3)
  176468. & RANGE_MASK];
  176469. outptr[1] = range_limit[(int) DESCALE(tmp11 + tmp2,
  176470. CONST_BITS+PASS1_BITS+3)
  176471. & RANGE_MASK];
  176472. outptr[6] = range_limit[(int) DESCALE(tmp11 - tmp2,
  176473. CONST_BITS+PASS1_BITS+3)
  176474. & RANGE_MASK];
  176475. outptr[2] = range_limit[(int) DESCALE(tmp12 + tmp1,
  176476. CONST_BITS+PASS1_BITS+3)
  176477. & RANGE_MASK];
  176478. outptr[5] = range_limit[(int) DESCALE(tmp12 - tmp1,
  176479. CONST_BITS+PASS1_BITS+3)
  176480. & RANGE_MASK];
  176481. outptr[3] = range_limit[(int) DESCALE(tmp13 + tmp0,
  176482. CONST_BITS+PASS1_BITS+3)
  176483. & RANGE_MASK];
  176484. outptr[4] = range_limit[(int) DESCALE(tmp13 - tmp0,
  176485. CONST_BITS+PASS1_BITS+3)
  176486. & RANGE_MASK];
  176487. wsptr += DCTSIZE; /* advance pointer to next row */
  176488. }
  176489. }
  176490. #endif /* DCT_ISLOW_SUPPORTED */
  176491. /********* End of inlined file: jidctint.c *********/
  176492. /********* Start of inlined file: jidctred.c *********/
  176493. #define JPEG_INTERNALS
  176494. #ifdef IDCT_SCALING_SUPPORTED
  176495. /*
  176496. * This module is specialized to the case DCTSIZE = 8.
  176497. */
  176498. #if DCTSIZE != 8
  176499. Sorry, this code only copes with 8x8 DCTs. /* deliberate syntax err */
  176500. #endif
  176501. /* Scaling is the same as in jidctint.c. */
  176502. #if BITS_IN_JSAMPLE == 8
  176503. #define CONST_BITS 13
  176504. #define PASS1_BITS 2
  176505. #else
  176506. #define CONST_BITS 13
  176507. #define PASS1_BITS 1 /* lose a little precision to avoid overflow */
  176508. #endif
  176509. /* Some C compilers fail to reduce "FIX(constant)" at compile time, thus
  176510. * causing a lot of useless floating-point operations at run time.
  176511. * To get around this we use the following pre-calculated constants.
  176512. * If you change CONST_BITS you may want to add appropriate values.
  176513. * (With a reasonable C compiler, you can just rely on the FIX() macro...)
  176514. */
  176515. #if CONST_BITS == 13
  176516. #define FIX_0_211164243 ((INT32) 1730) /* FIX(0.211164243) */
  176517. #define FIX_0_509795579 ((INT32) 4176) /* FIX(0.509795579) */
  176518. #define FIX_0_601344887 ((INT32) 4926) /* FIX(0.601344887) */
  176519. #define FIX_0_720959822 ((INT32) 5906) /* FIX(0.720959822) */
  176520. #define FIX_0_765366865 ((INT32) 6270) /* FIX(0.765366865) */
  176521. #define FIX_0_850430095 ((INT32) 6967) /* FIX(0.850430095) */
  176522. #define FIX_0_899976223 ((INT32) 7373) /* FIX(0.899976223) */
  176523. #define FIX_1_061594337 ((INT32) 8697) /* FIX(1.061594337) */
  176524. #define FIX_1_272758580 ((INT32) 10426) /* FIX(1.272758580) */
  176525. #define FIX_1_451774981 ((INT32) 11893) /* FIX(1.451774981) */
  176526. #define FIX_1_847759065 ((INT32) 15137) /* FIX(1.847759065) */
  176527. #define FIX_2_172734803 ((INT32) 17799) /* FIX(2.172734803) */
  176528. #define FIX_2_562915447 ((INT32) 20995) /* FIX(2.562915447) */
  176529. #define FIX_3_624509785 ((INT32) 29692) /* FIX(3.624509785) */
  176530. #else
  176531. #define FIX_0_211164243 FIX(0.211164243)
  176532. #define FIX_0_509795579 FIX(0.509795579)
  176533. #define FIX_0_601344887 FIX(0.601344887)
  176534. #define FIX_0_720959822 FIX(0.720959822)
  176535. #define FIX_0_765366865 FIX(0.765366865)
  176536. #define FIX_0_850430095 FIX(0.850430095)
  176537. #define FIX_0_899976223 FIX(0.899976223)
  176538. #define FIX_1_061594337 FIX(1.061594337)
  176539. #define FIX_1_272758580 FIX(1.272758580)
  176540. #define FIX_1_451774981 FIX(1.451774981)
  176541. #define FIX_1_847759065 FIX(1.847759065)
  176542. #define FIX_2_172734803 FIX(2.172734803)
  176543. #define FIX_2_562915447 FIX(2.562915447)
  176544. #define FIX_3_624509785 FIX(3.624509785)
  176545. #endif
  176546. /* Multiply an INT32 variable by an INT32 constant to yield an INT32 result.
  176547. * For 8-bit samples with the recommended scaling, all the variable
  176548. * and constant values involved are no more than 16 bits wide, so a
  176549. * 16x16->32 bit multiply can be used instead of a full 32x32 multiply.
  176550. * For 12-bit samples, a full 32-bit multiplication will be needed.
  176551. */
  176552. #if BITS_IN_JSAMPLE == 8
  176553. #define MULTIPLY(var,const) MULTIPLY16C16(var,const)
  176554. #else
  176555. #define MULTIPLY(var,const) ((var) * (const))
  176556. #endif
  176557. /* Dequantize a coefficient by multiplying it by the multiplier-table
  176558. * entry; produce an int result. In this module, both inputs and result
  176559. * are 16 bits or less, so either int or short multiply will work.
  176560. */
  176561. #define DEQUANTIZE(coef,quantval) (((ISLOW_MULT_TYPE) (coef)) * (quantval))
  176562. /*
  176563. * Perform dequantization and inverse DCT on one block of coefficients,
  176564. * producing a reduced-size 4x4 output block.
  176565. */
  176566. GLOBAL(void)
  176567. jpeg_idct_4x4 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  176568. JCOEFPTR coef_block,
  176569. JSAMPARRAY output_buf, JDIMENSION output_col)
  176570. {
  176571. INT32 tmp0, tmp2, tmp10, tmp12;
  176572. INT32 z1, z2, z3, z4;
  176573. JCOEFPTR inptr;
  176574. ISLOW_MULT_TYPE * quantptr;
  176575. int * wsptr;
  176576. JSAMPROW outptr;
  176577. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  176578. int ctr;
  176579. int workspace[DCTSIZE*4]; /* buffers data between passes */
  176580. SHIFT_TEMPS
  176581. /* Pass 1: process columns from input, store into work array. */
  176582. inptr = coef_block;
  176583. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  176584. wsptr = workspace;
  176585. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  176586. /* Don't bother to process column 4, because second pass won't use it */
  176587. if (ctr == DCTSIZE-4)
  176588. continue;
  176589. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*2] == 0 &&
  176590. inptr[DCTSIZE*3] == 0 && inptr[DCTSIZE*5] == 0 &&
  176591. inptr[DCTSIZE*6] == 0 && inptr[DCTSIZE*7] == 0) {
  176592. /* AC terms all zero; we need not examine term 4 for 4x4 output */
  176593. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  176594. wsptr[DCTSIZE*0] = dcval;
  176595. wsptr[DCTSIZE*1] = dcval;
  176596. wsptr[DCTSIZE*2] = dcval;
  176597. wsptr[DCTSIZE*3] = dcval;
  176598. continue;
  176599. }
  176600. /* Even part */
  176601. tmp0 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  176602. tmp0 <<= (CONST_BITS+1);
  176603. z2 = DEQUANTIZE(inptr[DCTSIZE*2], quantptr[DCTSIZE*2]);
  176604. z3 = DEQUANTIZE(inptr[DCTSIZE*6], quantptr[DCTSIZE*6]);
  176605. tmp2 = MULTIPLY(z2, FIX_1_847759065) + MULTIPLY(z3, - FIX_0_765366865);
  176606. tmp10 = tmp0 + tmp2;
  176607. tmp12 = tmp0 - tmp2;
  176608. /* Odd part */
  176609. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  176610. z2 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  176611. z3 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  176612. z4 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  176613. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  176614. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  176615. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  176616. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  176617. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  176618. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  176619. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  176620. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  176621. /* Final output stage */
  176622. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp2, CONST_BITS-PASS1_BITS+1);
  176623. wsptr[DCTSIZE*3] = (int) DESCALE(tmp10 - tmp2, CONST_BITS-PASS1_BITS+1);
  176624. wsptr[DCTSIZE*1] = (int) DESCALE(tmp12 + tmp0, CONST_BITS-PASS1_BITS+1);
  176625. wsptr[DCTSIZE*2] = (int) DESCALE(tmp12 - tmp0, CONST_BITS-PASS1_BITS+1);
  176626. }
  176627. /* Pass 2: process 4 rows from work array, store into output array. */
  176628. wsptr = workspace;
  176629. for (ctr = 0; ctr < 4; ctr++) {
  176630. outptr = output_buf[ctr] + output_col;
  176631. /* It's not clear whether a zero row test is worthwhile here ... */
  176632. #ifndef NO_ZERO_ROW_TEST
  176633. if (wsptr[1] == 0 && wsptr[2] == 0 && wsptr[3] == 0 &&
  176634. wsptr[5] == 0 && wsptr[6] == 0 && wsptr[7] == 0) {
  176635. /* AC terms all zero */
  176636. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  176637. & RANGE_MASK];
  176638. outptr[0] = dcval;
  176639. outptr[1] = dcval;
  176640. outptr[2] = dcval;
  176641. outptr[3] = dcval;
  176642. wsptr += DCTSIZE; /* advance pointer to next row */
  176643. continue;
  176644. }
  176645. #endif
  176646. /* Even part */
  176647. tmp0 = ((INT32) wsptr[0]) << (CONST_BITS+1);
  176648. tmp2 = MULTIPLY((INT32) wsptr[2], FIX_1_847759065)
  176649. + MULTIPLY((INT32) wsptr[6], - FIX_0_765366865);
  176650. tmp10 = tmp0 + tmp2;
  176651. tmp12 = tmp0 - tmp2;
  176652. /* Odd part */
  176653. z1 = (INT32) wsptr[7];
  176654. z2 = (INT32) wsptr[5];
  176655. z3 = (INT32) wsptr[3];
  176656. z4 = (INT32) wsptr[1];
  176657. tmp0 = MULTIPLY(z1, - FIX_0_211164243) /* sqrt(2) * (c3-c1) */
  176658. + MULTIPLY(z2, FIX_1_451774981) /* sqrt(2) * (c3+c7) */
  176659. + MULTIPLY(z3, - FIX_2_172734803) /* sqrt(2) * (-c1-c5) */
  176660. + MULTIPLY(z4, FIX_1_061594337); /* sqrt(2) * (c5+c7) */
  176661. tmp2 = MULTIPLY(z1, - FIX_0_509795579) /* sqrt(2) * (c7-c5) */
  176662. + MULTIPLY(z2, - FIX_0_601344887) /* sqrt(2) * (c5-c1) */
  176663. + MULTIPLY(z3, FIX_0_899976223) /* sqrt(2) * (c3-c7) */
  176664. + MULTIPLY(z4, FIX_2_562915447); /* sqrt(2) * (c1+c3) */
  176665. /* Final output stage */
  176666. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp2,
  176667. CONST_BITS+PASS1_BITS+3+1)
  176668. & RANGE_MASK];
  176669. outptr[3] = range_limit[(int) DESCALE(tmp10 - tmp2,
  176670. CONST_BITS+PASS1_BITS+3+1)
  176671. & RANGE_MASK];
  176672. outptr[1] = range_limit[(int) DESCALE(tmp12 + tmp0,
  176673. CONST_BITS+PASS1_BITS+3+1)
  176674. & RANGE_MASK];
  176675. outptr[2] = range_limit[(int) DESCALE(tmp12 - tmp0,
  176676. CONST_BITS+PASS1_BITS+3+1)
  176677. & RANGE_MASK];
  176678. wsptr += DCTSIZE; /* advance pointer to next row */
  176679. }
  176680. }
  176681. /*
  176682. * Perform dequantization and inverse DCT on one block of coefficients,
  176683. * producing a reduced-size 2x2 output block.
  176684. */
  176685. GLOBAL(void)
  176686. jpeg_idct_2x2 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  176687. JCOEFPTR coef_block,
  176688. JSAMPARRAY output_buf, JDIMENSION output_col)
  176689. {
  176690. INT32 tmp0, tmp10, z1;
  176691. JCOEFPTR inptr;
  176692. ISLOW_MULT_TYPE * quantptr;
  176693. int * wsptr;
  176694. JSAMPROW outptr;
  176695. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  176696. int ctr;
  176697. int workspace[DCTSIZE*2]; /* buffers data between passes */
  176698. SHIFT_TEMPS
  176699. /* Pass 1: process columns from input, store into work array. */
  176700. inptr = coef_block;
  176701. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  176702. wsptr = workspace;
  176703. for (ctr = DCTSIZE; ctr > 0; inptr++, quantptr++, wsptr++, ctr--) {
  176704. /* Don't bother to process columns 2,4,6 */
  176705. if (ctr == DCTSIZE-2 || ctr == DCTSIZE-4 || ctr == DCTSIZE-6)
  176706. continue;
  176707. if (inptr[DCTSIZE*1] == 0 && inptr[DCTSIZE*3] == 0 &&
  176708. inptr[DCTSIZE*5] == 0 && inptr[DCTSIZE*7] == 0) {
  176709. /* AC terms all zero; we need not examine terms 2,4,6 for 2x2 output */
  176710. int dcval = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]) << PASS1_BITS;
  176711. wsptr[DCTSIZE*0] = dcval;
  176712. wsptr[DCTSIZE*1] = dcval;
  176713. continue;
  176714. }
  176715. /* Even part */
  176716. z1 = DEQUANTIZE(inptr[DCTSIZE*0], quantptr[DCTSIZE*0]);
  176717. tmp10 = z1 << (CONST_BITS+2);
  176718. /* Odd part */
  176719. z1 = DEQUANTIZE(inptr[DCTSIZE*7], quantptr[DCTSIZE*7]);
  176720. tmp0 = MULTIPLY(z1, - FIX_0_720959822); /* sqrt(2) * (c7-c5+c3-c1) */
  176721. z1 = DEQUANTIZE(inptr[DCTSIZE*5], quantptr[DCTSIZE*5]);
  176722. tmp0 += MULTIPLY(z1, FIX_0_850430095); /* sqrt(2) * (-c1+c3+c5+c7) */
  176723. z1 = DEQUANTIZE(inptr[DCTSIZE*3], quantptr[DCTSIZE*3]);
  176724. tmp0 += MULTIPLY(z1, - FIX_1_272758580); /* sqrt(2) * (-c1+c3-c5-c7) */
  176725. z1 = DEQUANTIZE(inptr[DCTSIZE*1], quantptr[DCTSIZE*1]);
  176726. tmp0 += MULTIPLY(z1, FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  176727. /* Final output stage */
  176728. wsptr[DCTSIZE*0] = (int) DESCALE(tmp10 + tmp0, CONST_BITS-PASS1_BITS+2);
  176729. wsptr[DCTSIZE*1] = (int) DESCALE(tmp10 - tmp0, CONST_BITS-PASS1_BITS+2);
  176730. }
  176731. /* Pass 2: process 2 rows from work array, store into output array. */
  176732. wsptr = workspace;
  176733. for (ctr = 0; ctr < 2; ctr++) {
  176734. outptr = output_buf[ctr] + output_col;
  176735. /* It's not clear whether a zero row test is worthwhile here ... */
  176736. #ifndef NO_ZERO_ROW_TEST
  176737. if (wsptr[1] == 0 && wsptr[3] == 0 && wsptr[5] == 0 && wsptr[7] == 0) {
  176738. /* AC terms all zero */
  176739. JSAMPLE dcval = range_limit[(int) DESCALE((INT32) wsptr[0], PASS1_BITS+3)
  176740. & RANGE_MASK];
  176741. outptr[0] = dcval;
  176742. outptr[1] = dcval;
  176743. wsptr += DCTSIZE; /* advance pointer to next row */
  176744. continue;
  176745. }
  176746. #endif
  176747. /* Even part */
  176748. tmp10 = ((INT32) wsptr[0]) << (CONST_BITS+2);
  176749. /* Odd part */
  176750. tmp0 = MULTIPLY((INT32) wsptr[7], - FIX_0_720959822) /* sqrt(2) * (c7-c5+c3-c1) */
  176751. + MULTIPLY((INT32) wsptr[5], FIX_0_850430095) /* sqrt(2) * (-c1+c3+c5+c7) */
  176752. + MULTIPLY((INT32) wsptr[3], - FIX_1_272758580) /* sqrt(2) * (-c1+c3-c5-c7) */
  176753. + MULTIPLY((INT32) wsptr[1], FIX_3_624509785); /* sqrt(2) * (c1+c3+c5+c7) */
  176754. /* Final output stage */
  176755. outptr[0] = range_limit[(int) DESCALE(tmp10 + tmp0,
  176756. CONST_BITS+PASS1_BITS+3+2)
  176757. & RANGE_MASK];
  176758. outptr[1] = range_limit[(int) DESCALE(tmp10 - tmp0,
  176759. CONST_BITS+PASS1_BITS+3+2)
  176760. & RANGE_MASK];
  176761. wsptr += DCTSIZE; /* advance pointer to next row */
  176762. }
  176763. }
  176764. /*
  176765. * Perform dequantization and inverse DCT on one block of coefficients,
  176766. * producing a reduced-size 1x1 output block.
  176767. */
  176768. GLOBAL(void)
  176769. jpeg_idct_1x1 (j_decompress_ptr cinfo, jpeg_component_info * compptr,
  176770. JCOEFPTR coef_block,
  176771. JSAMPARRAY output_buf, JDIMENSION output_col)
  176772. {
  176773. int dcval;
  176774. ISLOW_MULT_TYPE * quantptr;
  176775. JSAMPLE *range_limit = IDCT_range_limit(cinfo);
  176776. SHIFT_TEMPS
  176777. /* We hardly need an inverse DCT routine for this: just take the
  176778. * average pixel value, which is one-eighth of the DC coefficient.
  176779. */
  176780. quantptr = (ISLOW_MULT_TYPE *) compptr->dct_table;
  176781. dcval = DEQUANTIZE(coef_block[0], quantptr[0]);
  176782. dcval = (int) DESCALE((INT32) dcval, 3);
  176783. output_buf[0][output_col] = range_limit[dcval & RANGE_MASK];
  176784. }
  176785. #endif /* IDCT_SCALING_SUPPORTED */
  176786. /********* End of inlined file: jidctred.c *********/
  176787. /********* Start of inlined file: jmemmgr.c *********/
  176788. #define JPEG_INTERNALS
  176789. #define AM_MEMORY_MANAGER /* we define jvirt_Xarray_control structs */
  176790. /********* Start of inlined file: jmemsys.h *********/
  176791. #ifndef __jmemsys_h__
  176792. #define __jmemsys_h__
  176793. /* Short forms of external names for systems with brain-damaged linkers. */
  176794. #ifdef NEED_SHORT_EXTERNAL_NAMES
  176795. #define jpeg_get_small jGetSmall
  176796. #define jpeg_free_small jFreeSmall
  176797. #define jpeg_get_large jGetLarge
  176798. #define jpeg_free_large jFreeLarge
  176799. #define jpeg_mem_available jMemAvail
  176800. #define jpeg_open_backing_store jOpenBackStore
  176801. #define jpeg_mem_init jMemInit
  176802. #define jpeg_mem_term jMemTerm
  176803. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  176804. /*
  176805. * These two functions are used to allocate and release small chunks of
  176806. * memory. (Typically the total amount requested through jpeg_get_small is
  176807. * no more than 20K or so; this will be requested in chunks of a few K each.)
  176808. * Behavior should be the same as for the standard library functions malloc
  176809. * and free; in particular, jpeg_get_small must return NULL on failure.
  176810. * On most systems, these ARE malloc and free. jpeg_free_small is passed the
  176811. * size of the object being freed, just in case it's needed.
  176812. * On an 80x86 machine using small-data memory model, these manage near heap.
  176813. */
  176814. EXTERN(void *) jpeg_get_small JPP((j_common_ptr cinfo, size_t sizeofobject));
  176815. EXTERN(void) jpeg_free_small JPP((j_common_ptr cinfo, void * object,
  176816. size_t sizeofobject));
  176817. /*
  176818. * These two functions are used to allocate and release large chunks of
  176819. * memory (up to the total free space designated by jpeg_mem_available).
  176820. * The interface is the same as above, except that on an 80x86 machine,
  176821. * far pointers are used. On most other machines these are identical to
  176822. * the jpeg_get/free_small routines; but we keep them separate anyway,
  176823. * in case a different allocation strategy is desirable for large chunks.
  176824. */
  176825. EXTERN(void FAR *) jpeg_get_large JPP((j_common_ptr cinfo,
  176826. size_t sizeofobject));
  176827. EXTERN(void) jpeg_free_large JPP((j_common_ptr cinfo, void FAR * object,
  176828. size_t sizeofobject));
  176829. /*
  176830. * The macro MAX_ALLOC_CHUNK designates the maximum number of bytes that may
  176831. * be requested in a single call to jpeg_get_large (and jpeg_get_small for that
  176832. * matter, but that case should never come into play). This macro is needed
  176833. * to model the 64Kb-segment-size limit of far addressing on 80x86 machines.
  176834. * On those machines, we expect that jconfig.h will provide a proper value.
  176835. * On machines with 32-bit flat address spaces, any large constant may be used.
  176836. *
  176837. * NB: jmemmgr.c expects that MAX_ALLOC_CHUNK will be representable as type
  176838. * size_t and will be a multiple of sizeof(align_type).
  176839. */
  176840. #ifndef MAX_ALLOC_CHUNK /* may be overridden in jconfig.h */
  176841. #define MAX_ALLOC_CHUNK 1000000000L
  176842. #endif
  176843. /*
  176844. * This routine computes the total space still available for allocation by
  176845. * jpeg_get_large. If more space than this is needed, backing store will be
  176846. * used. NOTE: any memory already allocated must not be counted.
  176847. *
  176848. * There is a minimum space requirement, corresponding to the minimum
  176849. * feasible buffer sizes; jmemmgr.c will request that much space even if
  176850. * jpeg_mem_available returns zero. The maximum space needed, enough to hold
  176851. * all working storage in memory, is also passed in case it is useful.
  176852. * Finally, the total space already allocated is passed. If no better
  176853. * method is available, cinfo->mem->max_memory_to_use - already_allocated
  176854. * is often a suitable calculation.
  176855. *
  176856. * It is OK for jpeg_mem_available to underestimate the space available
  176857. * (that'll just lead to more backing-store access than is really necessary).
  176858. * However, an overestimate will lead to failure. Hence it's wise to subtract
  176859. * a slop factor from the true available space. 5% should be enough.
  176860. *
  176861. * On machines with lots of virtual memory, any large constant may be returned.
  176862. * Conversely, zero may be returned to always use the minimum amount of memory.
  176863. */
  176864. EXTERN(long) jpeg_mem_available JPP((j_common_ptr cinfo,
  176865. long min_bytes_needed,
  176866. long max_bytes_needed,
  176867. long already_allocated));
  176868. /*
  176869. * This structure holds whatever state is needed to access a single
  176870. * backing-store object. The read/write/close method pointers are called
  176871. * by jmemmgr.c to manipulate the backing-store object; all other fields
  176872. * are private to the system-dependent backing store routines.
  176873. */
  176874. #define TEMP_NAME_LENGTH 64 /* max length of a temporary file's name */
  176875. #ifdef USE_MSDOS_MEMMGR /* DOS-specific junk */
  176876. typedef unsigned short XMSH; /* type of extended-memory handles */
  176877. typedef unsigned short EMSH; /* type of expanded-memory handles */
  176878. typedef union {
  176879. short file_handle; /* DOS file handle if it's a temp file */
  176880. XMSH xms_handle; /* handle if it's a chunk of XMS */
  176881. EMSH ems_handle; /* handle if it's a chunk of EMS */
  176882. } handle_union;
  176883. #endif /* USE_MSDOS_MEMMGR */
  176884. #ifdef USE_MAC_MEMMGR /* Mac-specific junk */
  176885. #include <Files.h>
  176886. #endif /* USE_MAC_MEMMGR */
  176887. //typedef struct backing_store_struct * backing_store_ptr;
  176888. typedef struct backing_store_struct {
  176889. /* Methods for reading/writing/closing this backing-store object */
  176890. JMETHOD(void, read_backing_store, (j_common_ptr cinfo,
  176891. struct backing_store_struct *info,
  176892. void FAR * buffer_address,
  176893. long file_offset, long byte_count));
  176894. JMETHOD(void, write_backing_store, (j_common_ptr cinfo,
  176895. struct backing_store_struct *info,
  176896. void FAR * buffer_address,
  176897. long file_offset, long byte_count));
  176898. JMETHOD(void, close_backing_store, (j_common_ptr cinfo,
  176899. struct backing_store_struct *info));
  176900. /* Private fields for system-dependent backing-store management */
  176901. #ifdef USE_MSDOS_MEMMGR
  176902. /* For the MS-DOS manager (jmemdos.c), we need: */
  176903. handle_union handle; /* reference to backing-store storage object */
  176904. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176905. #else
  176906. #ifdef USE_MAC_MEMMGR
  176907. /* For the Mac manager (jmemmac.c), we need: */
  176908. short temp_file; /* file reference number to temp file */
  176909. FSSpec tempSpec; /* the FSSpec for the temp file */
  176910. char temp_name[TEMP_NAME_LENGTH]; /* name if it's a file */
  176911. #else
  176912. /* For a typical implementation with temp files, we need: */
  176913. FILE * temp_file; /* stdio reference to temp file */
  176914. char temp_name[TEMP_NAME_LENGTH]; /* name of temp file */
  176915. #endif
  176916. #endif
  176917. } backing_store_info;
  176918. /*
  176919. * Initial opening of a backing-store object. This must fill in the
  176920. * read/write/close pointers in the object. The read/write routines
  176921. * may take an error exit if the specified maximum file size is exceeded.
  176922. * (If jpeg_mem_available always returns a large value, this routine can
  176923. * just take an error exit.)
  176924. */
  176925. EXTERN(void) jpeg_open_backing_store JPP((j_common_ptr cinfo,
  176926. struct backing_store_struct *info,
  176927. long total_bytes_needed));
  176928. /*
  176929. * These routines take care of any system-dependent initialization and
  176930. * cleanup required. jpeg_mem_init will be called before anything is
  176931. * allocated (and, therefore, nothing in cinfo is of use except the error
  176932. * manager pointer). It should return a suitable default value for
  176933. * max_memory_to_use; this may subsequently be overridden by the surrounding
  176934. * application. (Note that max_memory_to_use is only important if
  176935. * jpeg_mem_available chooses to consult it ... no one else will.)
  176936. * jpeg_mem_term may assume that all requested memory has been freed and that
  176937. * all opened backing-store objects have been closed.
  176938. */
  176939. EXTERN(long) jpeg_mem_init JPP((j_common_ptr cinfo));
  176940. EXTERN(void) jpeg_mem_term JPP((j_common_ptr cinfo));
  176941. #endif
  176942. /********* End of inlined file: jmemsys.h *********/
  176943. /* import the system-dependent declarations */
  176944. #ifndef NO_GETENV
  176945. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare getenv() */
  176946. extern char * getenv JPP((const char * name));
  176947. #endif
  176948. #endif
  176949. /*
  176950. * Some important notes:
  176951. * The allocation routines provided here must never return NULL.
  176952. * They should exit to error_exit if unsuccessful.
  176953. *
  176954. * It's not a good idea to try to merge the sarray and barray routines,
  176955. * even though they are textually almost the same, because samples are
  176956. * usually stored as bytes while coefficients are shorts or ints. Thus,
  176957. * in machines where byte pointers have a different representation from
  176958. * word pointers, the resulting machine code could not be the same.
  176959. */
  176960. /*
  176961. * Many machines require storage alignment: longs must start on 4-byte
  176962. * boundaries, doubles on 8-byte boundaries, etc. On such machines, malloc()
  176963. * always returns pointers that are multiples of the worst-case alignment
  176964. * requirement, and we had better do so too.
  176965. * There isn't any really portable way to determine the worst-case alignment
  176966. * requirement. This module assumes that the alignment requirement is
  176967. * multiples of sizeof(ALIGN_TYPE).
  176968. * By default, we define ALIGN_TYPE as double. This is necessary on some
  176969. * workstations (where doubles really do need 8-byte alignment) and will work
  176970. * fine on nearly everything. If your machine has lesser alignment needs,
  176971. * you can save a few bytes by making ALIGN_TYPE smaller.
  176972. * The only place I know of where this will NOT work is certain Macintosh
  176973. * 680x0 compilers that define double as a 10-byte IEEE extended float.
  176974. * Doing 10-byte alignment is counterproductive because longwords won't be
  176975. * aligned well. Put "#define ALIGN_TYPE long" in jconfig.h if you have
  176976. * such a compiler.
  176977. */
  176978. #ifndef ALIGN_TYPE /* so can override from jconfig.h */
  176979. #define ALIGN_TYPE double
  176980. #endif
  176981. /*
  176982. * We allocate objects from "pools", where each pool is gotten with a single
  176983. * request to jpeg_get_small() or jpeg_get_large(). There is no per-object
  176984. * overhead within a pool, except for alignment padding. Each pool has a
  176985. * header with a link to the next pool of the same class.
  176986. * Small and large pool headers are identical except that the latter's
  176987. * link pointer must be FAR on 80x86 machines.
  176988. * Notice that the "real" header fields are union'ed with a dummy ALIGN_TYPE
  176989. * field. This forces the compiler to make SIZEOF(small_pool_hdr) a multiple
  176990. * of the alignment requirement of ALIGN_TYPE.
  176991. */
  176992. typedef union small_pool_struct * small_pool_ptr;
  176993. typedef union small_pool_struct {
  176994. struct {
  176995. small_pool_ptr next; /* next in list of pools */
  176996. size_t bytes_used; /* how many bytes already used within pool */
  176997. size_t bytes_left; /* bytes still available in this pool */
  176998. } hdr;
  176999. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  177000. } small_pool_hdr;
  177001. typedef union large_pool_struct FAR * large_pool_ptr;
  177002. typedef union large_pool_struct {
  177003. struct {
  177004. large_pool_ptr next; /* next in list of pools */
  177005. size_t bytes_used; /* how many bytes already used within pool */
  177006. size_t bytes_left; /* bytes still available in this pool */
  177007. } hdr;
  177008. ALIGN_TYPE dummy; /* included in union to ensure alignment */
  177009. } large_pool_hdr;
  177010. /*
  177011. * Here is the full definition of a memory manager object.
  177012. */
  177013. typedef struct {
  177014. struct jpeg_memory_mgr pub; /* public fields */
  177015. /* Each pool identifier (lifetime class) names a linked list of pools. */
  177016. small_pool_ptr small_list[JPOOL_NUMPOOLS];
  177017. large_pool_ptr large_list[JPOOL_NUMPOOLS];
  177018. /* Since we only have one lifetime class of virtual arrays, only one
  177019. * linked list is necessary (for each datatype). Note that the virtual
  177020. * array control blocks being linked together are actually stored somewhere
  177021. * in the small-pool list.
  177022. */
  177023. jvirt_sarray_ptr virt_sarray_list;
  177024. jvirt_barray_ptr virt_barray_list;
  177025. /* This counts total space obtained from jpeg_get_small/large */
  177026. long total_space_allocated;
  177027. /* alloc_sarray and alloc_barray set this value for use by virtual
  177028. * array routines.
  177029. */
  177030. JDIMENSION last_rowsperchunk; /* from most recent alloc_sarray/barray */
  177031. } my_memory_mgr;
  177032. typedef my_memory_mgr * my_mem_ptr;
  177033. /*
  177034. * The control blocks for virtual arrays.
  177035. * Note that these blocks are allocated in the "small" pool area.
  177036. * System-dependent info for the associated backing store (if any) is hidden
  177037. * inside the backing_store_info struct.
  177038. */
  177039. struct jvirt_sarray_control {
  177040. JSAMPARRAY mem_buffer; /* => the in-memory buffer */
  177041. JDIMENSION rows_in_array; /* total virtual array height */
  177042. JDIMENSION samplesperrow; /* width of array (and of memory buffer) */
  177043. JDIMENSION maxaccess; /* max rows accessed by access_virt_sarray */
  177044. JDIMENSION rows_in_mem; /* height of memory buffer */
  177045. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  177046. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  177047. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  177048. boolean pre_zero; /* pre-zero mode requested? */
  177049. boolean dirty; /* do current buffer contents need written? */
  177050. boolean b_s_open; /* is backing-store data valid? */
  177051. jvirt_sarray_ptr next; /* link to next virtual sarray control block */
  177052. backing_store_info b_s_info; /* System-dependent control info */
  177053. };
  177054. struct jvirt_barray_control {
  177055. JBLOCKARRAY mem_buffer; /* => the in-memory buffer */
  177056. JDIMENSION rows_in_array; /* total virtual array height */
  177057. JDIMENSION blocksperrow; /* width of array (and of memory buffer) */
  177058. JDIMENSION maxaccess; /* max rows accessed by access_virt_barray */
  177059. JDIMENSION rows_in_mem; /* height of memory buffer */
  177060. JDIMENSION rowsperchunk; /* allocation chunk size in mem_buffer */
  177061. JDIMENSION cur_start_row; /* first logical row # in the buffer */
  177062. JDIMENSION first_undef_row; /* row # of first uninitialized row */
  177063. boolean pre_zero; /* pre-zero mode requested? */
  177064. boolean dirty; /* do current buffer contents need written? */
  177065. boolean b_s_open; /* is backing-store data valid? */
  177066. jvirt_barray_ptr next; /* link to next virtual barray control block */
  177067. backing_store_info b_s_info; /* System-dependent control info */
  177068. };
  177069. #ifdef MEM_STATS /* optional extra stuff for statistics */
  177070. LOCAL(void)
  177071. print_mem_stats (j_common_ptr cinfo, int pool_id)
  177072. {
  177073. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  177074. small_pool_ptr shdr_ptr;
  177075. large_pool_ptr lhdr_ptr;
  177076. /* Since this is only a debugging stub, we can cheat a little by using
  177077. * fprintf directly rather than going through the trace message code.
  177078. * This is helpful because message parm array can't handle longs.
  177079. */
  177080. fprintf(stderr, "Freeing pool %d, total space = %ld\n",
  177081. pool_id, mem->total_space_allocated);
  177082. for (lhdr_ptr = mem->large_list[pool_id]; lhdr_ptr != NULL;
  177083. lhdr_ptr = lhdr_ptr->hdr.next) {
  177084. fprintf(stderr, " Large chunk used %ld\n",
  177085. (long) lhdr_ptr->hdr.bytes_used);
  177086. }
  177087. for (shdr_ptr = mem->small_list[pool_id]; shdr_ptr != NULL;
  177088. shdr_ptr = shdr_ptr->hdr.next) {
  177089. fprintf(stderr, " Small chunk used %ld free %ld\n",
  177090. (long) shdr_ptr->hdr.bytes_used,
  177091. (long) shdr_ptr->hdr.bytes_left);
  177092. }
  177093. }
  177094. #endif /* MEM_STATS */
  177095. LOCAL(void)
  177096. out_of_memory (j_common_ptr cinfo, int which)
  177097. /* Report an out-of-memory error and stop execution */
  177098. /* If we compiled MEM_STATS support, report alloc requests before dying */
  177099. {
  177100. #ifdef MEM_STATS
  177101. cinfo->err->trace_level = 2; /* force self_destruct to report stats */
  177102. #endif
  177103. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, which);
  177104. }
  177105. /*
  177106. * Allocation of "small" objects.
  177107. *
  177108. * For these, we use pooled storage. When a new pool must be created,
  177109. * we try to get enough space for the current request plus a "slop" factor,
  177110. * where the slop will be the amount of leftover space in the new pool.
  177111. * The speed vs. space tradeoff is largely determined by the slop values.
  177112. * A different slop value is provided for each pool class (lifetime),
  177113. * and we also distinguish the first pool of a class from later ones.
  177114. * NOTE: the values given work fairly well on both 16- and 32-bit-int
  177115. * machines, but may be too small if longs are 64 bits or more.
  177116. */
  177117. static const size_t first_pool_slop[JPOOL_NUMPOOLS] =
  177118. {
  177119. 1600, /* first PERMANENT pool */
  177120. 16000 /* first IMAGE pool */
  177121. };
  177122. static const size_t extra_pool_slop[JPOOL_NUMPOOLS] =
  177123. {
  177124. 0, /* additional PERMANENT pools */
  177125. 5000 /* additional IMAGE pools */
  177126. };
  177127. #define MIN_SLOP 50 /* greater than 0 to avoid futile looping */
  177128. METHODDEF(void *)
  177129. alloc_small (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  177130. /* Allocate a "small" object */
  177131. {
  177132. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  177133. small_pool_ptr hdr_ptr, prev_hdr_ptr;
  177134. char * data_ptr;
  177135. size_t odd_bytes, min_request, slop;
  177136. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  177137. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(small_pool_hdr)))
  177138. out_of_memory(cinfo, 1); /* request exceeds malloc's ability */
  177139. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  177140. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  177141. if (odd_bytes > 0)
  177142. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  177143. /* See if space is available in any existing pool */
  177144. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  177145. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  177146. prev_hdr_ptr = NULL;
  177147. hdr_ptr = mem->small_list[pool_id];
  177148. while (hdr_ptr != NULL) {
  177149. if (hdr_ptr->hdr.bytes_left >= sizeofobject)
  177150. break; /* found pool with enough space */
  177151. prev_hdr_ptr = hdr_ptr;
  177152. hdr_ptr = hdr_ptr->hdr.next;
  177153. }
  177154. /* Time to make a new pool? */
  177155. if (hdr_ptr == NULL) {
  177156. /* min_request is what we need now, slop is what will be leftover */
  177157. min_request = sizeofobject + SIZEOF(small_pool_hdr);
  177158. if (prev_hdr_ptr == NULL) /* first pool in class? */
  177159. slop = first_pool_slop[pool_id];
  177160. else
  177161. slop = extra_pool_slop[pool_id];
  177162. /* Don't ask for more than MAX_ALLOC_CHUNK */
  177163. if (slop > (size_t) (MAX_ALLOC_CHUNK-min_request))
  177164. slop = (size_t) (MAX_ALLOC_CHUNK-min_request);
  177165. /* Try to get space, if fail reduce slop and try again */
  177166. for (;;) {
  177167. hdr_ptr = (small_pool_ptr) jpeg_get_small(cinfo, min_request + slop);
  177168. if (hdr_ptr != NULL)
  177169. break;
  177170. slop /= 2;
  177171. if (slop < MIN_SLOP) /* give up when it gets real small */
  177172. out_of_memory(cinfo, 2); /* jpeg_get_small failed */
  177173. }
  177174. mem->total_space_allocated += min_request + slop;
  177175. /* Success, initialize the new pool header and add to end of list */
  177176. hdr_ptr->hdr.next = NULL;
  177177. hdr_ptr->hdr.bytes_used = 0;
  177178. hdr_ptr->hdr.bytes_left = sizeofobject + slop;
  177179. if (prev_hdr_ptr == NULL) /* first pool in class? */
  177180. mem->small_list[pool_id] = hdr_ptr;
  177181. else
  177182. prev_hdr_ptr->hdr.next = hdr_ptr;
  177183. }
  177184. /* OK, allocate the object from the current pool */
  177185. data_ptr = (char *) (hdr_ptr + 1); /* point to first data byte in pool */
  177186. data_ptr += hdr_ptr->hdr.bytes_used; /* point to place for object */
  177187. hdr_ptr->hdr.bytes_used += sizeofobject;
  177188. hdr_ptr->hdr.bytes_left -= sizeofobject;
  177189. return (void *) data_ptr;
  177190. }
  177191. /*
  177192. * Allocation of "large" objects.
  177193. *
  177194. * The external semantics of these are the same as "small" objects,
  177195. * except that FAR pointers are used on 80x86. However the pool
  177196. * management heuristics are quite different. We assume that each
  177197. * request is large enough that it may as well be passed directly to
  177198. * jpeg_get_large; the pool management just links everything together
  177199. * so that we can free it all on demand.
  177200. * Note: the major use of "large" objects is in JSAMPARRAY and JBLOCKARRAY
  177201. * structures. The routines that create these structures (see below)
  177202. * deliberately bunch rows together to ensure a large request size.
  177203. */
  177204. METHODDEF(void FAR *)
  177205. alloc_large (j_common_ptr cinfo, int pool_id, size_t sizeofobject)
  177206. /* Allocate a "large" object */
  177207. {
  177208. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  177209. large_pool_ptr hdr_ptr;
  177210. size_t odd_bytes;
  177211. /* Check for unsatisfiable request (do now to ensure no overflow below) */
  177212. if (sizeofobject > (size_t) (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)))
  177213. out_of_memory(cinfo, 3); /* request exceeds malloc's ability */
  177214. /* Round up the requested size to a multiple of SIZEOF(ALIGN_TYPE) */
  177215. odd_bytes = sizeofobject % SIZEOF(ALIGN_TYPE);
  177216. if (odd_bytes > 0)
  177217. sizeofobject += SIZEOF(ALIGN_TYPE) - odd_bytes;
  177218. /* Always make a new pool */
  177219. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  177220. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  177221. hdr_ptr = (large_pool_ptr) jpeg_get_large(cinfo, sizeofobject +
  177222. SIZEOF(large_pool_hdr));
  177223. if (hdr_ptr == NULL)
  177224. out_of_memory(cinfo, 4); /* jpeg_get_large failed */
  177225. mem->total_space_allocated += sizeofobject + SIZEOF(large_pool_hdr);
  177226. /* Success, initialize the new pool header and add to list */
  177227. hdr_ptr->hdr.next = mem->large_list[pool_id];
  177228. /* We maintain space counts in each pool header for statistical purposes,
  177229. * even though they are not needed for allocation.
  177230. */
  177231. hdr_ptr->hdr.bytes_used = sizeofobject;
  177232. hdr_ptr->hdr.bytes_left = 0;
  177233. mem->large_list[pool_id] = hdr_ptr;
  177234. return (void FAR *) (hdr_ptr + 1); /* point to first data byte in pool */
  177235. }
  177236. /*
  177237. * Creation of 2-D sample arrays.
  177238. * The pointers are in near heap, the samples themselves in FAR heap.
  177239. *
  177240. * To minimize allocation overhead and to allow I/O of large contiguous
  177241. * blocks, we allocate the sample rows in groups of as many rows as possible
  177242. * without exceeding MAX_ALLOC_CHUNK total bytes per allocation request.
  177243. * NB: the virtual array control routines, later in this file, know about
  177244. * this chunking of rows. The rowsperchunk value is left in the mem manager
  177245. * object so that it can be saved away if this sarray is the workspace for
  177246. * a virtual array.
  177247. */
  177248. METHODDEF(JSAMPARRAY)
  177249. alloc_sarray (j_common_ptr cinfo, int pool_id,
  177250. JDIMENSION samplesperrow, JDIMENSION numrows)
  177251. /* Allocate a 2-D sample array */
  177252. {
  177253. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  177254. JSAMPARRAY result;
  177255. JSAMPROW workspace;
  177256. JDIMENSION rowsperchunk, currow, i;
  177257. long ltemp;
  177258. /* Calculate max # of rows allowed in one allocation chunk */
  177259. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  177260. ((long) samplesperrow * SIZEOF(JSAMPLE));
  177261. if (ltemp <= 0)
  177262. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  177263. if (ltemp < (long) numrows)
  177264. rowsperchunk = (JDIMENSION) ltemp;
  177265. else
  177266. rowsperchunk = numrows;
  177267. mem->last_rowsperchunk = rowsperchunk;
  177268. /* Get space for row pointers (small object) */
  177269. result = (JSAMPARRAY) alloc_small(cinfo, pool_id,
  177270. (size_t) (numrows * SIZEOF(JSAMPROW)));
  177271. /* Get the rows themselves (large objects) */
  177272. currow = 0;
  177273. while (currow < numrows) {
  177274. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  177275. workspace = (JSAMPROW) alloc_large(cinfo, pool_id,
  177276. (size_t) ((size_t) rowsperchunk * (size_t) samplesperrow
  177277. * SIZEOF(JSAMPLE)));
  177278. for (i = rowsperchunk; i > 0; i--) {
  177279. result[currow++] = workspace;
  177280. workspace += samplesperrow;
  177281. }
  177282. }
  177283. return result;
  177284. }
  177285. /*
  177286. * Creation of 2-D coefficient-block arrays.
  177287. * This is essentially the same as the code for sample arrays, above.
  177288. */
  177289. METHODDEF(JBLOCKARRAY)
  177290. alloc_barray (j_common_ptr cinfo, int pool_id,
  177291. JDIMENSION blocksperrow, JDIMENSION numrows)
  177292. /* Allocate a 2-D coefficient-block array */
  177293. {
  177294. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  177295. JBLOCKARRAY result;
  177296. JBLOCKROW workspace;
  177297. JDIMENSION rowsperchunk, currow, i;
  177298. long ltemp;
  177299. /* Calculate max # of rows allowed in one allocation chunk */
  177300. ltemp = (MAX_ALLOC_CHUNK-SIZEOF(large_pool_hdr)) /
  177301. ((long) blocksperrow * SIZEOF(JBLOCK));
  177302. if (ltemp <= 0)
  177303. ERREXIT(cinfo, JERR_WIDTH_OVERFLOW);
  177304. if (ltemp < (long) numrows)
  177305. rowsperchunk = (JDIMENSION) ltemp;
  177306. else
  177307. rowsperchunk = numrows;
  177308. mem->last_rowsperchunk = rowsperchunk;
  177309. /* Get space for row pointers (small object) */
  177310. result = (JBLOCKARRAY) alloc_small(cinfo, pool_id,
  177311. (size_t) (numrows * SIZEOF(JBLOCKROW)));
  177312. /* Get the rows themselves (large objects) */
  177313. currow = 0;
  177314. while (currow < numrows) {
  177315. rowsperchunk = MIN(rowsperchunk, numrows - currow);
  177316. workspace = (JBLOCKROW) alloc_large(cinfo, pool_id,
  177317. (size_t) ((size_t) rowsperchunk * (size_t) blocksperrow
  177318. * SIZEOF(JBLOCK)));
  177319. for (i = rowsperchunk; i > 0; i--) {
  177320. result[currow++] = workspace;
  177321. workspace += blocksperrow;
  177322. }
  177323. }
  177324. return result;
  177325. }
  177326. /*
  177327. * About virtual array management:
  177328. *
  177329. * The above "normal" array routines are only used to allocate strip buffers
  177330. * (as wide as the image, but just a few rows high). Full-image-sized buffers
  177331. * are handled as "virtual" arrays. The array is still accessed a strip at a
  177332. * time, but the memory manager must save the whole array for repeated
  177333. * accesses. The intended implementation is that there is a strip buffer in
  177334. * memory (as high as is possible given the desired memory limit), plus a
  177335. * backing file that holds the rest of the array.
  177336. *
  177337. * The request_virt_array routines are told the total size of the image and
  177338. * the maximum number of rows that will be accessed at once. The in-memory
  177339. * buffer must be at least as large as the maxaccess value.
  177340. *
  177341. * The request routines create control blocks but not the in-memory buffers.
  177342. * That is postponed until realize_virt_arrays is called. At that time the
  177343. * total amount of space needed is known (approximately, anyway), so free
  177344. * memory can be divided up fairly.
  177345. *
  177346. * The access_virt_array routines are responsible for making a specific strip
  177347. * area accessible (after reading or writing the backing file, if necessary).
  177348. * Note that the access routines are told whether the caller intends to modify
  177349. * the accessed strip; during a read-only pass this saves having to rewrite
  177350. * data to disk. The access routines are also responsible for pre-zeroing
  177351. * any newly accessed rows, if pre-zeroing was requested.
  177352. *
  177353. * In current usage, the access requests are usually for nonoverlapping
  177354. * strips; that is, successive access start_row numbers differ by exactly
  177355. * num_rows = maxaccess. This means we can get good performance with simple
  177356. * buffer dump/reload logic, by making the in-memory buffer be a multiple
  177357. * of the access height; then there will never be accesses across bufferload
  177358. * boundaries. The code will still work with overlapping access requests,
  177359. * but it doesn't handle bufferload overlaps very efficiently.
  177360. */
  177361. METHODDEF(jvirt_sarray_ptr)
  177362. request_virt_sarray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  177363. JDIMENSION samplesperrow, JDIMENSION numrows,
  177364. JDIMENSION maxaccess)
  177365. /* Request a virtual 2-D sample array */
  177366. {
  177367. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  177368. jvirt_sarray_ptr result;
  177369. /* Only IMAGE-lifetime virtual arrays are currently supported */
  177370. if (pool_id != JPOOL_IMAGE)
  177371. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  177372. /* get control block */
  177373. result = (jvirt_sarray_ptr) alloc_small(cinfo, pool_id,
  177374. SIZEOF(struct jvirt_sarray_control));
  177375. result->mem_buffer = NULL; /* marks array not yet realized */
  177376. result->rows_in_array = numrows;
  177377. result->samplesperrow = samplesperrow;
  177378. result->maxaccess = maxaccess;
  177379. result->pre_zero = pre_zero;
  177380. result->b_s_open = FALSE; /* no associated backing-store object */
  177381. result->next = mem->virt_sarray_list; /* add to list of virtual arrays */
  177382. mem->virt_sarray_list = result;
  177383. return result;
  177384. }
  177385. METHODDEF(jvirt_barray_ptr)
  177386. request_virt_barray (j_common_ptr cinfo, int pool_id, boolean pre_zero,
  177387. JDIMENSION blocksperrow, JDIMENSION numrows,
  177388. JDIMENSION maxaccess)
  177389. /* Request a virtual 2-D coefficient-block array */
  177390. {
  177391. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  177392. jvirt_barray_ptr result;
  177393. /* Only IMAGE-lifetime virtual arrays are currently supported */
  177394. if (pool_id != JPOOL_IMAGE)
  177395. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  177396. /* get control block */
  177397. result = (jvirt_barray_ptr) alloc_small(cinfo, pool_id,
  177398. SIZEOF(struct jvirt_barray_control));
  177399. result->mem_buffer = NULL; /* marks array not yet realized */
  177400. result->rows_in_array = numrows;
  177401. result->blocksperrow = blocksperrow;
  177402. result->maxaccess = maxaccess;
  177403. result->pre_zero = pre_zero;
  177404. result->b_s_open = FALSE; /* no associated backing-store object */
  177405. result->next = mem->virt_barray_list; /* add to list of virtual arrays */
  177406. mem->virt_barray_list = result;
  177407. return result;
  177408. }
  177409. METHODDEF(void)
  177410. realize_virt_arrays (j_common_ptr cinfo)
  177411. /* Allocate the in-memory buffers for any unrealized virtual arrays */
  177412. {
  177413. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  177414. long space_per_minheight, maximum_space, avail_mem;
  177415. long minheights, max_minheights;
  177416. jvirt_sarray_ptr sptr;
  177417. jvirt_barray_ptr bptr;
  177418. /* Compute the minimum space needed (maxaccess rows in each buffer)
  177419. * and the maximum space needed (full image height in each buffer).
  177420. * These may be of use to the system-dependent jpeg_mem_available routine.
  177421. */
  177422. space_per_minheight = 0;
  177423. maximum_space = 0;
  177424. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  177425. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  177426. space_per_minheight += (long) sptr->maxaccess *
  177427. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  177428. maximum_space += (long) sptr->rows_in_array *
  177429. (long) sptr->samplesperrow * SIZEOF(JSAMPLE);
  177430. }
  177431. }
  177432. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  177433. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  177434. space_per_minheight += (long) bptr->maxaccess *
  177435. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  177436. maximum_space += (long) bptr->rows_in_array *
  177437. (long) bptr->blocksperrow * SIZEOF(JBLOCK);
  177438. }
  177439. }
  177440. if (space_per_minheight <= 0)
  177441. return; /* no unrealized arrays, no work */
  177442. /* Determine amount of memory to actually use; this is system-dependent. */
  177443. avail_mem = jpeg_mem_available(cinfo, space_per_minheight, maximum_space,
  177444. mem->total_space_allocated);
  177445. /* If the maximum space needed is available, make all the buffers full
  177446. * height; otherwise parcel it out with the same number of minheights
  177447. * in each buffer.
  177448. */
  177449. if (avail_mem >= maximum_space)
  177450. max_minheights = 1000000000L;
  177451. else {
  177452. max_minheights = avail_mem / space_per_minheight;
  177453. /* If there doesn't seem to be enough space, try to get the minimum
  177454. * anyway. This allows a "stub" implementation of jpeg_mem_available().
  177455. */
  177456. if (max_minheights <= 0)
  177457. max_minheights = 1;
  177458. }
  177459. /* Allocate the in-memory buffers and initialize backing store as needed. */
  177460. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  177461. if (sptr->mem_buffer == NULL) { /* if not realized yet */
  177462. minheights = ((long) sptr->rows_in_array - 1L) / sptr->maxaccess + 1L;
  177463. if (minheights <= max_minheights) {
  177464. /* This buffer fits in memory */
  177465. sptr->rows_in_mem = sptr->rows_in_array;
  177466. } else {
  177467. /* It doesn't fit in memory, create backing store. */
  177468. sptr->rows_in_mem = (JDIMENSION) (max_minheights * sptr->maxaccess);
  177469. jpeg_open_backing_store(cinfo, & sptr->b_s_info,
  177470. (long) sptr->rows_in_array *
  177471. (long) sptr->samplesperrow *
  177472. (long) SIZEOF(JSAMPLE));
  177473. sptr->b_s_open = TRUE;
  177474. }
  177475. sptr->mem_buffer = alloc_sarray(cinfo, JPOOL_IMAGE,
  177476. sptr->samplesperrow, sptr->rows_in_mem);
  177477. sptr->rowsperchunk = mem->last_rowsperchunk;
  177478. sptr->cur_start_row = 0;
  177479. sptr->first_undef_row = 0;
  177480. sptr->dirty = FALSE;
  177481. }
  177482. }
  177483. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  177484. if (bptr->mem_buffer == NULL) { /* if not realized yet */
  177485. minheights = ((long) bptr->rows_in_array - 1L) / bptr->maxaccess + 1L;
  177486. if (minheights <= max_minheights) {
  177487. /* This buffer fits in memory */
  177488. bptr->rows_in_mem = bptr->rows_in_array;
  177489. } else {
  177490. /* It doesn't fit in memory, create backing store. */
  177491. bptr->rows_in_mem = (JDIMENSION) (max_minheights * bptr->maxaccess);
  177492. jpeg_open_backing_store(cinfo, & bptr->b_s_info,
  177493. (long) bptr->rows_in_array *
  177494. (long) bptr->blocksperrow *
  177495. (long) SIZEOF(JBLOCK));
  177496. bptr->b_s_open = TRUE;
  177497. }
  177498. bptr->mem_buffer = alloc_barray(cinfo, JPOOL_IMAGE,
  177499. bptr->blocksperrow, bptr->rows_in_mem);
  177500. bptr->rowsperchunk = mem->last_rowsperchunk;
  177501. bptr->cur_start_row = 0;
  177502. bptr->first_undef_row = 0;
  177503. bptr->dirty = FALSE;
  177504. }
  177505. }
  177506. }
  177507. LOCAL(void)
  177508. do_sarray_io (j_common_ptr cinfo, jvirt_sarray_ptr ptr, boolean writing)
  177509. /* Do backing store read or write of a virtual sample array */
  177510. {
  177511. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  177512. bytesperrow = (long) ptr->samplesperrow * SIZEOF(JSAMPLE);
  177513. file_offset = ptr->cur_start_row * bytesperrow;
  177514. /* Loop to read or write each allocation chunk in mem_buffer */
  177515. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  177516. /* One chunk, but check for short chunk at end of buffer */
  177517. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  177518. /* Transfer no more than is currently defined */
  177519. thisrow = (long) ptr->cur_start_row + i;
  177520. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  177521. /* Transfer no more than fits in file */
  177522. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  177523. if (rows <= 0) /* this chunk might be past end of file! */
  177524. break;
  177525. byte_count = rows * bytesperrow;
  177526. if (writing)
  177527. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  177528. (void FAR *) ptr->mem_buffer[i],
  177529. file_offset, byte_count);
  177530. else
  177531. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  177532. (void FAR *) ptr->mem_buffer[i],
  177533. file_offset, byte_count);
  177534. file_offset += byte_count;
  177535. }
  177536. }
  177537. LOCAL(void)
  177538. do_barray_io (j_common_ptr cinfo, jvirt_barray_ptr ptr, boolean writing)
  177539. /* Do backing store read or write of a virtual coefficient-block array */
  177540. {
  177541. long bytesperrow, file_offset, byte_count, rows, thisrow, i;
  177542. bytesperrow = (long) ptr->blocksperrow * SIZEOF(JBLOCK);
  177543. file_offset = ptr->cur_start_row * bytesperrow;
  177544. /* Loop to read or write each allocation chunk in mem_buffer */
  177545. for (i = 0; i < (long) ptr->rows_in_mem; i += ptr->rowsperchunk) {
  177546. /* One chunk, but check for short chunk at end of buffer */
  177547. rows = MIN((long) ptr->rowsperchunk, (long) ptr->rows_in_mem - i);
  177548. /* Transfer no more than is currently defined */
  177549. thisrow = (long) ptr->cur_start_row + i;
  177550. rows = MIN(rows, (long) ptr->first_undef_row - thisrow);
  177551. /* Transfer no more than fits in file */
  177552. rows = MIN(rows, (long) ptr->rows_in_array - thisrow);
  177553. if (rows <= 0) /* this chunk might be past end of file! */
  177554. break;
  177555. byte_count = rows * bytesperrow;
  177556. if (writing)
  177557. (*ptr->b_s_info.write_backing_store) (cinfo, & ptr->b_s_info,
  177558. (void FAR *) ptr->mem_buffer[i],
  177559. file_offset, byte_count);
  177560. else
  177561. (*ptr->b_s_info.read_backing_store) (cinfo, & ptr->b_s_info,
  177562. (void FAR *) ptr->mem_buffer[i],
  177563. file_offset, byte_count);
  177564. file_offset += byte_count;
  177565. }
  177566. }
  177567. METHODDEF(JSAMPARRAY)
  177568. access_virt_sarray (j_common_ptr cinfo, jvirt_sarray_ptr ptr,
  177569. JDIMENSION start_row, JDIMENSION num_rows,
  177570. boolean writable)
  177571. /* Access the part of a virtual sample array starting at start_row */
  177572. /* and extending for num_rows rows. writable is true if */
  177573. /* caller intends to modify the accessed area. */
  177574. {
  177575. JDIMENSION end_row = start_row + num_rows;
  177576. JDIMENSION undef_row;
  177577. /* debugging check */
  177578. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  177579. ptr->mem_buffer == NULL)
  177580. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  177581. /* Make the desired part of the virtual array accessible */
  177582. if (start_row < ptr->cur_start_row ||
  177583. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  177584. if (! ptr->b_s_open)
  177585. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  177586. /* Flush old buffer contents if necessary */
  177587. if (ptr->dirty) {
  177588. do_sarray_io(cinfo, ptr, TRUE);
  177589. ptr->dirty = FALSE;
  177590. }
  177591. /* Decide what part of virtual array to access.
  177592. * Algorithm: if target address > current window, assume forward scan,
  177593. * load starting at target address. If target address < current window,
  177594. * assume backward scan, load so that target area is top of window.
  177595. * Note that when switching from forward write to forward read, will have
  177596. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  177597. */
  177598. if (start_row > ptr->cur_start_row) {
  177599. ptr->cur_start_row = start_row;
  177600. } else {
  177601. /* use long arithmetic here to avoid overflow & unsigned problems */
  177602. long ltemp;
  177603. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  177604. if (ltemp < 0)
  177605. ltemp = 0; /* don't fall off front end of file */
  177606. ptr->cur_start_row = (JDIMENSION) ltemp;
  177607. }
  177608. /* Read in the selected part of the array.
  177609. * During the initial write pass, we will do no actual read
  177610. * because the selected part is all undefined.
  177611. */
  177612. do_sarray_io(cinfo, ptr, FALSE);
  177613. }
  177614. /* Ensure the accessed part of the array is defined; prezero if needed.
  177615. * To improve locality of access, we only prezero the part of the array
  177616. * that the caller is about to access, not the entire in-memory array.
  177617. */
  177618. if (ptr->first_undef_row < end_row) {
  177619. if (ptr->first_undef_row < start_row) {
  177620. if (writable) /* writer skipped over a section of array */
  177621. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  177622. undef_row = start_row; /* but reader is allowed to read ahead */
  177623. } else {
  177624. undef_row = ptr->first_undef_row;
  177625. }
  177626. if (writable)
  177627. ptr->first_undef_row = end_row;
  177628. if (ptr->pre_zero) {
  177629. size_t bytesperrow = (size_t) ptr->samplesperrow * SIZEOF(JSAMPLE);
  177630. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  177631. end_row -= ptr->cur_start_row;
  177632. while (undef_row < end_row) {
  177633. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  177634. undef_row++;
  177635. }
  177636. } else {
  177637. if (! writable) /* reader looking at undefined data */
  177638. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  177639. }
  177640. }
  177641. /* Flag the buffer dirty if caller will write in it */
  177642. if (writable)
  177643. ptr->dirty = TRUE;
  177644. /* Return address of proper part of the buffer */
  177645. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  177646. }
  177647. METHODDEF(JBLOCKARRAY)
  177648. access_virt_barray (j_common_ptr cinfo, jvirt_barray_ptr ptr,
  177649. JDIMENSION start_row, JDIMENSION num_rows,
  177650. boolean writable)
  177651. /* Access the part of a virtual block array starting at start_row */
  177652. /* and extending for num_rows rows. writable is true if */
  177653. /* caller intends to modify the accessed area. */
  177654. {
  177655. JDIMENSION end_row = start_row + num_rows;
  177656. JDIMENSION undef_row;
  177657. /* debugging check */
  177658. if (end_row > ptr->rows_in_array || num_rows > ptr->maxaccess ||
  177659. ptr->mem_buffer == NULL)
  177660. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  177661. /* Make the desired part of the virtual array accessible */
  177662. if (start_row < ptr->cur_start_row ||
  177663. end_row > ptr->cur_start_row+ptr->rows_in_mem) {
  177664. if (! ptr->b_s_open)
  177665. ERREXIT(cinfo, JERR_VIRTUAL_BUG);
  177666. /* Flush old buffer contents if necessary */
  177667. if (ptr->dirty) {
  177668. do_barray_io(cinfo, ptr, TRUE);
  177669. ptr->dirty = FALSE;
  177670. }
  177671. /* Decide what part of virtual array to access.
  177672. * Algorithm: if target address > current window, assume forward scan,
  177673. * load starting at target address. If target address < current window,
  177674. * assume backward scan, load so that target area is top of window.
  177675. * Note that when switching from forward write to forward read, will have
  177676. * start_row = 0, so the limiting case applies and we load from 0 anyway.
  177677. */
  177678. if (start_row > ptr->cur_start_row) {
  177679. ptr->cur_start_row = start_row;
  177680. } else {
  177681. /* use long arithmetic here to avoid overflow & unsigned problems */
  177682. long ltemp;
  177683. ltemp = (long) end_row - (long) ptr->rows_in_mem;
  177684. if (ltemp < 0)
  177685. ltemp = 0; /* don't fall off front end of file */
  177686. ptr->cur_start_row = (JDIMENSION) ltemp;
  177687. }
  177688. /* Read in the selected part of the array.
  177689. * During the initial write pass, we will do no actual read
  177690. * because the selected part is all undefined.
  177691. */
  177692. do_barray_io(cinfo, ptr, FALSE);
  177693. }
  177694. /* Ensure the accessed part of the array is defined; prezero if needed.
  177695. * To improve locality of access, we only prezero the part of the array
  177696. * that the caller is about to access, not the entire in-memory array.
  177697. */
  177698. if (ptr->first_undef_row < end_row) {
  177699. if (ptr->first_undef_row < start_row) {
  177700. if (writable) /* writer skipped over a section of array */
  177701. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  177702. undef_row = start_row; /* but reader is allowed to read ahead */
  177703. } else {
  177704. undef_row = ptr->first_undef_row;
  177705. }
  177706. if (writable)
  177707. ptr->first_undef_row = end_row;
  177708. if (ptr->pre_zero) {
  177709. size_t bytesperrow = (size_t) ptr->blocksperrow * SIZEOF(JBLOCK);
  177710. undef_row -= ptr->cur_start_row; /* make indexes relative to buffer */
  177711. end_row -= ptr->cur_start_row;
  177712. while (undef_row < end_row) {
  177713. jzero_far((void FAR *) ptr->mem_buffer[undef_row], bytesperrow);
  177714. undef_row++;
  177715. }
  177716. } else {
  177717. if (! writable) /* reader looking at undefined data */
  177718. ERREXIT(cinfo, JERR_BAD_VIRTUAL_ACCESS);
  177719. }
  177720. }
  177721. /* Flag the buffer dirty if caller will write in it */
  177722. if (writable)
  177723. ptr->dirty = TRUE;
  177724. /* Return address of proper part of the buffer */
  177725. return ptr->mem_buffer + (start_row - ptr->cur_start_row);
  177726. }
  177727. /*
  177728. * Release all objects belonging to a specified pool.
  177729. */
  177730. METHODDEF(void)
  177731. free_pool (j_common_ptr cinfo, int pool_id)
  177732. {
  177733. my_mem_ptr mem = (my_mem_ptr) cinfo->mem;
  177734. small_pool_ptr shdr_ptr;
  177735. large_pool_ptr lhdr_ptr;
  177736. size_t space_freed;
  177737. if (pool_id < 0 || pool_id >= JPOOL_NUMPOOLS)
  177738. ERREXIT1(cinfo, JERR_BAD_POOL_ID, pool_id); /* safety check */
  177739. #ifdef MEM_STATS
  177740. if (cinfo->err->trace_level > 1)
  177741. print_mem_stats(cinfo, pool_id); /* print pool's memory usage statistics */
  177742. #endif
  177743. /* If freeing IMAGE pool, close any virtual arrays first */
  177744. if (pool_id == JPOOL_IMAGE) {
  177745. jvirt_sarray_ptr sptr;
  177746. jvirt_barray_ptr bptr;
  177747. for (sptr = mem->virt_sarray_list; sptr != NULL; sptr = sptr->next) {
  177748. if (sptr->b_s_open) { /* there may be no backing store */
  177749. sptr->b_s_open = FALSE; /* prevent recursive close if error */
  177750. (*sptr->b_s_info.close_backing_store) (cinfo, & sptr->b_s_info);
  177751. }
  177752. }
  177753. mem->virt_sarray_list = NULL;
  177754. for (bptr = mem->virt_barray_list; bptr != NULL; bptr = bptr->next) {
  177755. if (bptr->b_s_open) { /* there may be no backing store */
  177756. bptr->b_s_open = FALSE; /* prevent recursive close if error */
  177757. (*bptr->b_s_info.close_backing_store) (cinfo, & bptr->b_s_info);
  177758. }
  177759. }
  177760. mem->virt_barray_list = NULL;
  177761. }
  177762. /* Release large objects */
  177763. lhdr_ptr = mem->large_list[pool_id];
  177764. mem->large_list[pool_id] = NULL;
  177765. while (lhdr_ptr != NULL) {
  177766. large_pool_ptr next_lhdr_ptr = lhdr_ptr->hdr.next;
  177767. space_freed = lhdr_ptr->hdr.bytes_used +
  177768. lhdr_ptr->hdr.bytes_left +
  177769. SIZEOF(large_pool_hdr);
  177770. jpeg_free_large(cinfo, (void FAR *) lhdr_ptr, space_freed);
  177771. mem->total_space_allocated -= space_freed;
  177772. lhdr_ptr = next_lhdr_ptr;
  177773. }
  177774. /* Release small objects */
  177775. shdr_ptr = mem->small_list[pool_id];
  177776. mem->small_list[pool_id] = NULL;
  177777. while (shdr_ptr != NULL) {
  177778. small_pool_ptr next_shdr_ptr = shdr_ptr->hdr.next;
  177779. space_freed = shdr_ptr->hdr.bytes_used +
  177780. shdr_ptr->hdr.bytes_left +
  177781. SIZEOF(small_pool_hdr);
  177782. jpeg_free_small(cinfo, (void *) shdr_ptr, space_freed);
  177783. mem->total_space_allocated -= space_freed;
  177784. shdr_ptr = next_shdr_ptr;
  177785. }
  177786. }
  177787. /*
  177788. * Close up shop entirely.
  177789. * Note that this cannot be called unless cinfo->mem is non-NULL.
  177790. */
  177791. METHODDEF(void)
  177792. self_destruct (j_common_ptr cinfo)
  177793. {
  177794. int pool;
  177795. /* Close all backing store, release all memory.
  177796. * Releasing pools in reverse order might help avoid fragmentation
  177797. * with some (brain-damaged) malloc libraries.
  177798. */
  177799. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  177800. free_pool(cinfo, pool);
  177801. }
  177802. /* Release the memory manager control block too. */
  177803. jpeg_free_small(cinfo, (void *) cinfo->mem, SIZEOF(my_memory_mgr));
  177804. cinfo->mem = NULL; /* ensures I will be called only once */
  177805. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177806. }
  177807. /*
  177808. * Memory manager initialization.
  177809. * When this is called, only the error manager pointer is valid in cinfo!
  177810. */
  177811. GLOBAL(void)
  177812. jinit_memory_mgr (j_common_ptr cinfo)
  177813. {
  177814. my_mem_ptr mem;
  177815. long max_to_use;
  177816. int pool;
  177817. size_t test_mac;
  177818. cinfo->mem = NULL; /* for safety if init fails */
  177819. /* Check for configuration errors.
  177820. * SIZEOF(ALIGN_TYPE) should be a power of 2; otherwise, it probably
  177821. * doesn't reflect any real hardware alignment requirement.
  177822. * The test is a little tricky: for X>0, X and X-1 have no one-bits
  177823. * in common if and only if X is a power of 2, ie has only one one-bit.
  177824. * Some compilers may give an "unreachable code" warning here; ignore it.
  177825. */
  177826. if ((SIZEOF(ALIGN_TYPE) & (SIZEOF(ALIGN_TYPE)-1)) != 0)
  177827. ERREXIT(cinfo, JERR_BAD_ALIGN_TYPE);
  177828. /* MAX_ALLOC_CHUNK must be representable as type size_t, and must be
  177829. * a multiple of SIZEOF(ALIGN_TYPE).
  177830. * Again, an "unreachable code" warning may be ignored here.
  177831. * But a "constant too large" warning means you need to fix MAX_ALLOC_CHUNK.
  177832. */
  177833. test_mac = (size_t) MAX_ALLOC_CHUNK;
  177834. if ((long) test_mac != MAX_ALLOC_CHUNK ||
  177835. (MAX_ALLOC_CHUNK % SIZEOF(ALIGN_TYPE)) != 0)
  177836. ERREXIT(cinfo, JERR_BAD_ALLOC_CHUNK);
  177837. max_to_use = jpeg_mem_init(cinfo); /* system-dependent initialization */
  177838. /* Attempt to allocate memory manager's control block */
  177839. mem = (my_mem_ptr) jpeg_get_small(cinfo, SIZEOF(my_memory_mgr));
  177840. if (mem == NULL) {
  177841. jpeg_mem_term(cinfo); /* system-dependent cleanup */
  177842. ERREXIT1(cinfo, JERR_OUT_OF_MEMORY, 0);
  177843. }
  177844. /* OK, fill in the method pointers */
  177845. mem->pub.alloc_small = alloc_small;
  177846. mem->pub.alloc_large = alloc_large;
  177847. mem->pub.alloc_sarray = alloc_sarray;
  177848. mem->pub.alloc_barray = alloc_barray;
  177849. mem->pub.request_virt_sarray = request_virt_sarray;
  177850. mem->pub.request_virt_barray = request_virt_barray;
  177851. mem->pub.realize_virt_arrays = realize_virt_arrays;
  177852. mem->pub.access_virt_sarray = access_virt_sarray;
  177853. mem->pub.access_virt_barray = access_virt_barray;
  177854. mem->pub.free_pool = free_pool;
  177855. mem->pub.self_destruct = self_destruct;
  177856. /* Make MAX_ALLOC_CHUNK accessible to other modules */
  177857. mem->pub.max_alloc_chunk = MAX_ALLOC_CHUNK;
  177858. /* Initialize working state */
  177859. mem->pub.max_memory_to_use = max_to_use;
  177860. for (pool = JPOOL_NUMPOOLS-1; pool >= JPOOL_PERMANENT; pool--) {
  177861. mem->small_list[pool] = NULL;
  177862. mem->large_list[pool] = NULL;
  177863. }
  177864. mem->virt_sarray_list = NULL;
  177865. mem->virt_barray_list = NULL;
  177866. mem->total_space_allocated = SIZEOF(my_memory_mgr);
  177867. /* Declare ourselves open for business */
  177868. cinfo->mem = & mem->pub;
  177869. /* Check for an environment variable JPEGMEM; if found, override the
  177870. * default max_memory setting from jpeg_mem_init. Note that the
  177871. * surrounding application may again override this value.
  177872. * If your system doesn't support getenv(), define NO_GETENV to disable
  177873. * this feature.
  177874. */
  177875. #ifndef NO_GETENV
  177876. { char * memenv;
  177877. if ((memenv = getenv("JPEGMEM")) != NULL) {
  177878. char ch = 'x';
  177879. if (sscanf(memenv, "%ld%c", &max_to_use, &ch) > 0) {
  177880. if (ch == 'm' || ch == 'M')
  177881. max_to_use *= 1000L;
  177882. mem->pub.max_memory_to_use = max_to_use * 1000L;
  177883. }
  177884. }
  177885. }
  177886. #endif
  177887. }
  177888. /********* End of inlined file: jmemmgr.c *********/
  177889. /********* Start of inlined file: jmemnobs.c *********/
  177890. #define JPEG_INTERNALS
  177891. #ifndef HAVE_STDLIB_H /* <stdlib.h> should declare malloc(),free() */
  177892. extern void * malloc JPP((size_t size));
  177893. extern void free JPP((void *ptr));
  177894. #endif
  177895. /*
  177896. * Memory allocation and freeing are controlled by the regular library
  177897. * routines malloc() and free().
  177898. */
  177899. GLOBAL(void *)
  177900. jpeg_get_small (j_common_ptr cinfo, size_t sizeofobject)
  177901. {
  177902. return (void *) malloc(sizeofobject);
  177903. }
  177904. GLOBAL(void)
  177905. jpeg_free_small (j_common_ptr cinfo, void * object, size_t sizeofobject)
  177906. {
  177907. free(object);
  177908. }
  177909. /*
  177910. * "Large" objects are treated the same as "small" ones.
  177911. * NB: although we include FAR keywords in the routine declarations,
  177912. * this file won't actually work in 80x86 small/medium model; at least,
  177913. * you probably won't be able to process useful-size images in only 64KB.
  177914. */
  177915. GLOBAL(void FAR *)
  177916. jpeg_get_large (j_common_ptr cinfo, size_t sizeofobject)
  177917. {
  177918. return (void FAR *) malloc(sizeofobject);
  177919. }
  177920. GLOBAL(void)
  177921. jpeg_free_large (j_common_ptr cinfo, void FAR * object, size_t sizeofobject)
  177922. {
  177923. free(object);
  177924. }
  177925. /*
  177926. * This routine computes the total memory space available for allocation.
  177927. * Here we always say, "we got all you want bud!"
  177928. */
  177929. GLOBAL(long)
  177930. jpeg_mem_available (j_common_ptr cinfo, long min_bytes_needed,
  177931. long max_bytes_needed, long already_allocated)
  177932. {
  177933. return max_bytes_needed;
  177934. }
  177935. /*
  177936. * Backing store (temporary file) management.
  177937. * Since jpeg_mem_available always promised the moon,
  177938. * this should never be called and we can just error out.
  177939. */
  177940. GLOBAL(void)
  177941. jpeg_open_backing_store (j_common_ptr cinfo, struct backing_store_struct *info,
  177942. long total_bytes_needed)
  177943. {
  177944. ERREXIT(cinfo, JERR_NO_BACKING_STORE);
  177945. }
  177946. /*
  177947. * These routines take care of any system-dependent initialization and
  177948. * cleanup required. Here, there isn't any.
  177949. */
  177950. GLOBAL(long)
  177951. jpeg_mem_init (j_common_ptr cinfo)
  177952. {
  177953. return 0; /* just set max_memory_to_use to 0 */
  177954. }
  177955. GLOBAL(void)
  177956. jpeg_mem_term (j_common_ptr cinfo)
  177957. {
  177958. /* no work */
  177959. }
  177960. /********* End of inlined file: jmemnobs.c *********/
  177961. /********* Start of inlined file: jquant1.c *********/
  177962. #define JPEG_INTERNALS
  177963. #ifdef QUANT_1PASS_SUPPORTED
  177964. /*
  177965. * The main purpose of 1-pass quantization is to provide a fast, if not very
  177966. * high quality, colormapped output capability. A 2-pass quantizer usually
  177967. * gives better visual quality; however, for quantized grayscale output this
  177968. * quantizer is perfectly adequate. Dithering is highly recommended with this
  177969. * quantizer, though you can turn it off if you really want to.
  177970. *
  177971. * In 1-pass quantization the colormap must be chosen in advance of seeing the
  177972. * image. We use a map consisting of all combinations of Ncolors[i] color
  177973. * values for the i'th component. The Ncolors[] values are chosen so that
  177974. * their product, the total number of colors, is no more than that requested.
  177975. * (In most cases, the product will be somewhat less.)
  177976. *
  177977. * Since the colormap is orthogonal, the representative value for each color
  177978. * component can be determined without considering the other components;
  177979. * then these indexes can be combined into a colormap index by a standard
  177980. * N-dimensional-array-subscript calculation. Most of the arithmetic involved
  177981. * can be precalculated and stored in the lookup table colorindex[].
  177982. * colorindex[i][j] maps pixel value j in component i to the nearest
  177983. * representative value (grid plane) for that component; this index is
  177984. * multiplied by the array stride for component i, so that the
  177985. * index of the colormap entry closest to a given pixel value is just
  177986. * sum( colorindex[component-number][pixel-component-value] )
  177987. * Aside from being fast, this scheme allows for variable spacing between
  177988. * representative values with no additional lookup cost.
  177989. *
  177990. * If gamma correction has been applied in color conversion, it might be wise
  177991. * to adjust the color grid spacing so that the representative colors are
  177992. * equidistant in linear space. At this writing, gamma correction is not
  177993. * implemented by jdcolor, so nothing is done here.
  177994. */
  177995. /* Declarations for ordered dithering.
  177996. *
  177997. * We use a standard 16x16 ordered dither array. The basic concept of ordered
  177998. * dithering is described in many references, for instance Dale Schumacher's
  177999. * chapter II.2 of Graphics Gems II (James Arvo, ed. Academic Press, 1991).
  178000. * In place of Schumacher's comparisons against a "threshold" value, we add a
  178001. * "dither" value to the input pixel and then round the result to the nearest
  178002. * output value. The dither value is equivalent to (0.5 - threshold) times
  178003. * the distance between output values. For ordered dithering, we assume that
  178004. * the output colors are equally spaced; if not, results will probably be
  178005. * worse, since the dither may be too much or too little at a given point.
  178006. *
  178007. * The normal calculation would be to form pixel value + dither, range-limit
  178008. * this to 0..MAXJSAMPLE, and then index into the colorindex table as usual.
  178009. * We can skip the separate range-limiting step by extending the colorindex
  178010. * table in both directions.
  178011. */
  178012. #define ODITHER_SIZE 16 /* dimension of dither matrix */
  178013. /* NB: if ODITHER_SIZE is not a power of 2, ODITHER_MASK uses will break */
  178014. #define ODITHER_CELLS (ODITHER_SIZE*ODITHER_SIZE) /* # cells in matrix */
  178015. #define ODITHER_MASK (ODITHER_SIZE-1) /* mask for wrapping around counters */
  178016. typedef int ODITHER_MATRIX[ODITHER_SIZE][ODITHER_SIZE];
  178017. typedef int (*ODITHER_MATRIX_PTR)[ODITHER_SIZE];
  178018. static const UINT8 base_dither_matrix[ODITHER_SIZE][ODITHER_SIZE] = {
  178019. /* Bayer's order-4 dither array. Generated by the code given in
  178020. * Stephen Hawley's article "Ordered Dithering" in Graphics Gems I.
  178021. * The values in this array must range from 0 to ODITHER_CELLS-1.
  178022. */
  178023. { 0,192, 48,240, 12,204, 60,252, 3,195, 51,243, 15,207, 63,255 },
  178024. { 128, 64,176,112,140, 76,188,124,131, 67,179,115,143, 79,191,127 },
  178025. { 32,224, 16,208, 44,236, 28,220, 35,227, 19,211, 47,239, 31,223 },
  178026. { 160, 96,144, 80,172,108,156, 92,163, 99,147, 83,175,111,159, 95 },
  178027. { 8,200, 56,248, 4,196, 52,244, 11,203, 59,251, 7,199, 55,247 },
  178028. { 136, 72,184,120,132, 68,180,116,139, 75,187,123,135, 71,183,119 },
  178029. { 40,232, 24,216, 36,228, 20,212, 43,235, 27,219, 39,231, 23,215 },
  178030. { 168,104,152, 88,164,100,148, 84,171,107,155, 91,167,103,151, 87 },
  178031. { 2,194, 50,242, 14,206, 62,254, 1,193, 49,241, 13,205, 61,253 },
  178032. { 130, 66,178,114,142, 78,190,126,129, 65,177,113,141, 77,189,125 },
  178033. { 34,226, 18,210, 46,238, 30,222, 33,225, 17,209, 45,237, 29,221 },
  178034. { 162, 98,146, 82,174,110,158, 94,161, 97,145, 81,173,109,157, 93 },
  178035. { 10,202, 58,250, 6,198, 54,246, 9,201, 57,249, 5,197, 53,245 },
  178036. { 138, 74,186,122,134, 70,182,118,137, 73,185,121,133, 69,181,117 },
  178037. { 42,234, 26,218, 38,230, 22,214, 41,233, 25,217, 37,229, 21,213 },
  178038. { 170,106,154, 90,166,102,150, 86,169,105,153, 89,165,101,149, 85 }
  178039. };
  178040. /* Declarations for Floyd-Steinberg dithering.
  178041. *
  178042. * Errors are accumulated into the array fserrors[], at a resolution of
  178043. * 1/16th of a pixel count. The error at a given pixel is propagated
  178044. * to its not-yet-processed neighbors using the standard F-S fractions,
  178045. * ... (here) 7/16
  178046. * 3/16 5/16 1/16
  178047. * We work left-to-right on even rows, right-to-left on odd rows.
  178048. *
  178049. * We can get away with a single array (holding one row's worth of errors)
  178050. * by using it to store the current row's errors at pixel columns not yet
  178051. * processed, but the next row's errors at columns already processed. We
  178052. * need only a few extra variables to hold the errors immediately around the
  178053. * current column. (If we are lucky, those variables are in registers, but
  178054. * even if not, they're probably cheaper to access than array elements are.)
  178055. *
  178056. * The fserrors[] array is indexed [component#][position].
  178057. * We provide (#columns + 2) entries per component; the extra entry at each
  178058. * end saves us from special-casing the first and last pixels.
  178059. *
  178060. * Note: on a wide image, we might not have enough room in a PC's near data
  178061. * segment to hold the error array; so it is allocated with alloc_large.
  178062. */
  178063. #if BITS_IN_JSAMPLE == 8
  178064. typedef INT16 FSERROR; /* 16 bits should be enough */
  178065. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  178066. #else
  178067. typedef INT32 FSERROR; /* may need more than 16 bits */
  178068. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  178069. #endif
  178070. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  178071. /* Private subobject */
  178072. #define MAX_Q_COMPS 4 /* max components I can handle */
  178073. typedef struct {
  178074. struct jpeg_color_quantizer pub; /* public fields */
  178075. /* Initially allocated colormap is saved here */
  178076. JSAMPARRAY sv_colormap; /* The color map as a 2-D pixel array */
  178077. int sv_actual; /* number of entries in use */
  178078. JSAMPARRAY colorindex; /* Precomputed mapping for speed */
  178079. /* colorindex[i][j] = index of color closest to pixel value j in component i,
  178080. * premultiplied as described above. Since colormap indexes must fit into
  178081. * JSAMPLEs, the entries of this array will too.
  178082. */
  178083. boolean is_padded; /* is the colorindex padded for odither? */
  178084. int Ncolors[MAX_Q_COMPS]; /* # of values alloced to each component */
  178085. /* Variables for ordered dithering */
  178086. int row_index; /* cur row's vertical index in dither matrix */
  178087. ODITHER_MATRIX_PTR odither[MAX_Q_COMPS]; /* one dither array per component */
  178088. /* Variables for Floyd-Steinberg dithering */
  178089. FSERRPTR fserrors[MAX_Q_COMPS]; /* accumulated errors */
  178090. boolean on_odd_row; /* flag to remember which row we are on */
  178091. } my_cquantizer;
  178092. typedef my_cquantizer * my_cquantize_ptr;
  178093. /*
  178094. * Policy-making subroutines for create_colormap and create_colorindex.
  178095. * These routines determine the colormap to be used. The rest of the module
  178096. * only assumes that the colormap is orthogonal.
  178097. *
  178098. * * select_ncolors decides how to divvy up the available colors
  178099. * among the components.
  178100. * * output_value defines the set of representative values for a component.
  178101. * * largest_input_value defines the mapping from input values to
  178102. * representative values for a component.
  178103. * Note that the latter two routines may impose different policies for
  178104. * different components, though this is not currently done.
  178105. */
  178106. LOCAL(int)
  178107. select_ncolors (j_decompress_ptr cinfo, int Ncolors[])
  178108. /* Determine allocation of desired colors to components, */
  178109. /* and fill in Ncolors[] array to indicate choice. */
  178110. /* Return value is total number of colors (product of Ncolors[] values). */
  178111. {
  178112. int nc = cinfo->out_color_components; /* number of color components */
  178113. int max_colors = cinfo->desired_number_of_colors;
  178114. int total_colors, iroot, i, j;
  178115. boolean changed;
  178116. long temp;
  178117. static const int RGB_order[3] = { RGB_GREEN, RGB_RED, RGB_BLUE };
  178118. /* We can allocate at least the nc'th root of max_colors per component. */
  178119. /* Compute floor(nc'th root of max_colors). */
  178120. iroot = 1;
  178121. do {
  178122. iroot++;
  178123. temp = iroot; /* set temp = iroot ** nc */
  178124. for (i = 1; i < nc; i++)
  178125. temp *= iroot;
  178126. } while (temp <= (long) max_colors); /* repeat till iroot exceeds root */
  178127. iroot--; /* now iroot = floor(root) */
  178128. /* Must have at least 2 color values per component */
  178129. if (iroot < 2)
  178130. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, (int) temp);
  178131. /* Initialize to iroot color values for each component */
  178132. total_colors = 1;
  178133. for (i = 0; i < nc; i++) {
  178134. Ncolors[i] = iroot;
  178135. total_colors *= iroot;
  178136. }
  178137. /* We may be able to increment the count for one or more components without
  178138. * exceeding max_colors, though we know not all can be incremented.
  178139. * Sometimes, the first component can be incremented more than once!
  178140. * (Example: for 16 colors, we start at 2*2*2, go to 3*2*2, then 4*2*2.)
  178141. * In RGB colorspace, try to increment G first, then R, then B.
  178142. */
  178143. do {
  178144. changed = FALSE;
  178145. for (i = 0; i < nc; i++) {
  178146. j = (cinfo->out_color_space == JCS_RGB ? RGB_order[i] : i);
  178147. /* calculate new total_colors if Ncolors[j] is incremented */
  178148. temp = total_colors / Ncolors[j];
  178149. temp *= Ncolors[j]+1; /* done in long arith to avoid oflo */
  178150. if (temp > (long) max_colors)
  178151. break; /* won't fit, done with this pass */
  178152. Ncolors[j]++; /* OK, apply the increment */
  178153. total_colors = (int) temp;
  178154. changed = TRUE;
  178155. }
  178156. } while (changed);
  178157. return total_colors;
  178158. }
  178159. LOCAL(int)
  178160. output_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  178161. /* Return j'th output value, where j will range from 0 to maxj */
  178162. /* The output values must fall in 0..MAXJSAMPLE in increasing order */
  178163. {
  178164. /* We always provide values 0 and MAXJSAMPLE for each component;
  178165. * any additional values are equally spaced between these limits.
  178166. * (Forcing the upper and lower values to the limits ensures that
  178167. * dithering can't produce a color outside the selected gamut.)
  178168. */
  178169. return (int) (((INT32) j * MAXJSAMPLE + maxj/2) / maxj);
  178170. }
  178171. LOCAL(int)
  178172. largest_input_value (j_decompress_ptr cinfo, int ci, int j, int maxj)
  178173. /* Return largest input value that should map to j'th output value */
  178174. /* Must have largest(j=0) >= 0, and largest(j=maxj) >= MAXJSAMPLE */
  178175. {
  178176. /* Breakpoints are halfway between values returned by output_value */
  178177. return (int) (((INT32) (2*j + 1) * MAXJSAMPLE + maxj) / (2*maxj));
  178178. }
  178179. /*
  178180. * Create the colormap.
  178181. */
  178182. LOCAL(void)
  178183. create_colormap (j_decompress_ptr cinfo)
  178184. {
  178185. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  178186. JSAMPARRAY colormap; /* Created colormap */
  178187. int total_colors; /* Number of distinct output colors */
  178188. int i,j,k, nci, blksize, blkdist, ptr, val;
  178189. /* Select number of colors for each component */
  178190. total_colors = select_ncolors(cinfo, cquantize->Ncolors);
  178191. /* Report selected color counts */
  178192. if (cinfo->out_color_components == 3)
  178193. TRACEMS4(cinfo, 1, JTRC_QUANT_3_NCOLORS,
  178194. total_colors, cquantize->Ncolors[0],
  178195. cquantize->Ncolors[1], cquantize->Ncolors[2]);
  178196. else
  178197. TRACEMS1(cinfo, 1, JTRC_QUANT_NCOLORS, total_colors);
  178198. /* Allocate and fill in the colormap. */
  178199. /* The colors are ordered in the map in standard row-major order, */
  178200. /* i.e. rightmost (highest-indexed) color changes most rapidly. */
  178201. colormap = (*cinfo->mem->alloc_sarray)
  178202. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178203. (JDIMENSION) total_colors, (JDIMENSION) cinfo->out_color_components);
  178204. /* blksize is number of adjacent repeated entries for a component */
  178205. /* blkdist is distance between groups of identical entries for a component */
  178206. blkdist = total_colors;
  178207. for (i = 0; i < cinfo->out_color_components; i++) {
  178208. /* fill in colormap entries for i'th color component */
  178209. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  178210. blksize = blkdist / nci;
  178211. for (j = 0; j < nci; j++) {
  178212. /* Compute j'th output value (out of nci) for component */
  178213. val = output_value(cinfo, i, j, nci-1);
  178214. /* Fill in all colormap entries that have this value of this component */
  178215. for (ptr = j * blksize; ptr < total_colors; ptr += blkdist) {
  178216. /* fill in blksize entries beginning at ptr */
  178217. for (k = 0; k < blksize; k++)
  178218. colormap[i][ptr+k] = (JSAMPLE) val;
  178219. }
  178220. }
  178221. blkdist = blksize; /* blksize of this color is blkdist of next */
  178222. }
  178223. /* Save the colormap in private storage,
  178224. * where it will survive color quantization mode changes.
  178225. */
  178226. cquantize->sv_colormap = colormap;
  178227. cquantize->sv_actual = total_colors;
  178228. }
  178229. /*
  178230. * Create the color index table.
  178231. */
  178232. LOCAL(void)
  178233. create_colorindex (j_decompress_ptr cinfo)
  178234. {
  178235. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  178236. JSAMPROW indexptr;
  178237. int i,j,k, nci, blksize, val, pad;
  178238. /* For ordered dither, we pad the color index tables by MAXJSAMPLE in
  178239. * each direction (input index values can be -MAXJSAMPLE .. 2*MAXJSAMPLE).
  178240. * This is not necessary in the other dithering modes. However, we
  178241. * flag whether it was done in case user changes dithering mode.
  178242. */
  178243. if (cinfo->dither_mode == JDITHER_ORDERED) {
  178244. pad = MAXJSAMPLE*2;
  178245. cquantize->is_padded = TRUE;
  178246. } else {
  178247. pad = 0;
  178248. cquantize->is_padded = FALSE;
  178249. }
  178250. cquantize->colorindex = (*cinfo->mem->alloc_sarray)
  178251. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178252. (JDIMENSION) (MAXJSAMPLE+1 + pad),
  178253. (JDIMENSION) cinfo->out_color_components);
  178254. /* blksize is number of adjacent repeated entries for a component */
  178255. blksize = cquantize->sv_actual;
  178256. for (i = 0; i < cinfo->out_color_components; i++) {
  178257. /* fill in colorindex entries for i'th color component */
  178258. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  178259. blksize = blksize / nci;
  178260. /* adjust colorindex pointers to provide padding at negative indexes. */
  178261. if (pad)
  178262. cquantize->colorindex[i] += MAXJSAMPLE;
  178263. /* in loop, val = index of current output value, */
  178264. /* and k = largest j that maps to current val */
  178265. indexptr = cquantize->colorindex[i];
  178266. val = 0;
  178267. k = largest_input_value(cinfo, i, 0, nci-1);
  178268. for (j = 0; j <= MAXJSAMPLE; j++) {
  178269. while (j > k) /* advance val if past boundary */
  178270. k = largest_input_value(cinfo, i, ++val, nci-1);
  178271. /* premultiply so that no multiplication needed in main processing */
  178272. indexptr[j] = (JSAMPLE) (val * blksize);
  178273. }
  178274. /* Pad at both ends if necessary */
  178275. if (pad)
  178276. for (j = 1; j <= MAXJSAMPLE; j++) {
  178277. indexptr[-j] = indexptr[0];
  178278. indexptr[MAXJSAMPLE+j] = indexptr[MAXJSAMPLE];
  178279. }
  178280. }
  178281. }
  178282. /*
  178283. * Create an ordered-dither array for a component having ncolors
  178284. * distinct output values.
  178285. */
  178286. LOCAL(ODITHER_MATRIX_PTR)
  178287. make_odither_array (j_decompress_ptr cinfo, int ncolors)
  178288. {
  178289. ODITHER_MATRIX_PTR odither;
  178290. int j,k;
  178291. INT32 num,den;
  178292. odither = (ODITHER_MATRIX_PTR)
  178293. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178294. SIZEOF(ODITHER_MATRIX));
  178295. /* The inter-value distance for this color is MAXJSAMPLE/(ncolors-1).
  178296. * Hence the dither value for the matrix cell with fill order f
  178297. * (f=0..N-1) should be (N-1-2*f)/(2*N) * MAXJSAMPLE/(ncolors-1).
  178298. * On 16-bit-int machine, be careful to avoid overflow.
  178299. */
  178300. den = 2 * ODITHER_CELLS * ((INT32) (ncolors - 1));
  178301. for (j = 0; j < ODITHER_SIZE; j++) {
  178302. for (k = 0; k < ODITHER_SIZE; k++) {
  178303. num = ((INT32) (ODITHER_CELLS-1 - 2*((int)base_dither_matrix[j][k])))
  178304. * MAXJSAMPLE;
  178305. /* Ensure round towards zero despite C's lack of consistency
  178306. * about rounding negative values in integer division...
  178307. */
  178308. odither[j][k] = (int) (num<0 ? -((-num)/den) : num/den);
  178309. }
  178310. }
  178311. return odither;
  178312. }
  178313. /*
  178314. * Create the ordered-dither tables.
  178315. * Components having the same number of representative colors may
  178316. * share a dither table.
  178317. */
  178318. LOCAL(void)
  178319. create_odither_tables (j_decompress_ptr cinfo)
  178320. {
  178321. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  178322. ODITHER_MATRIX_PTR odither;
  178323. int i, j, nci;
  178324. for (i = 0; i < cinfo->out_color_components; i++) {
  178325. nci = cquantize->Ncolors[i]; /* # of distinct values for this color */
  178326. odither = NULL; /* search for matching prior component */
  178327. for (j = 0; j < i; j++) {
  178328. if (nci == cquantize->Ncolors[j]) {
  178329. odither = cquantize->odither[j];
  178330. break;
  178331. }
  178332. }
  178333. if (odither == NULL) /* need a new table? */
  178334. odither = make_odither_array(cinfo, nci);
  178335. cquantize->odither[i] = odither;
  178336. }
  178337. }
  178338. /*
  178339. * Map some rows of pixels to the output colormapped representation.
  178340. */
  178341. METHODDEF(void)
  178342. color_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  178343. JSAMPARRAY output_buf, int num_rows)
  178344. /* General case, no dithering */
  178345. {
  178346. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  178347. JSAMPARRAY colorindex = cquantize->colorindex;
  178348. register int pixcode, ci;
  178349. register JSAMPROW ptrin, ptrout;
  178350. int row;
  178351. JDIMENSION col;
  178352. JDIMENSION width = cinfo->output_width;
  178353. register int nc = cinfo->out_color_components;
  178354. for (row = 0; row < num_rows; row++) {
  178355. ptrin = input_buf[row];
  178356. ptrout = output_buf[row];
  178357. for (col = width; col > 0; col--) {
  178358. pixcode = 0;
  178359. for (ci = 0; ci < nc; ci++) {
  178360. pixcode += GETJSAMPLE(colorindex[ci][GETJSAMPLE(*ptrin++)]);
  178361. }
  178362. *ptrout++ = (JSAMPLE) pixcode;
  178363. }
  178364. }
  178365. }
  178366. METHODDEF(void)
  178367. color_quantize3 (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  178368. JSAMPARRAY output_buf, int num_rows)
  178369. /* Fast path for out_color_components==3, no dithering */
  178370. {
  178371. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  178372. register int pixcode;
  178373. register JSAMPROW ptrin, ptrout;
  178374. JSAMPROW colorindex0 = cquantize->colorindex[0];
  178375. JSAMPROW colorindex1 = cquantize->colorindex[1];
  178376. JSAMPROW colorindex2 = cquantize->colorindex[2];
  178377. int row;
  178378. JDIMENSION col;
  178379. JDIMENSION width = cinfo->output_width;
  178380. for (row = 0; row < num_rows; row++) {
  178381. ptrin = input_buf[row];
  178382. ptrout = output_buf[row];
  178383. for (col = width; col > 0; col--) {
  178384. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*ptrin++)]);
  178385. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*ptrin++)]);
  178386. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*ptrin++)]);
  178387. *ptrout++ = (JSAMPLE) pixcode;
  178388. }
  178389. }
  178390. }
  178391. METHODDEF(void)
  178392. quantize_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  178393. JSAMPARRAY output_buf, int num_rows)
  178394. /* General case, with ordered dithering */
  178395. {
  178396. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  178397. register JSAMPROW input_ptr;
  178398. register JSAMPROW output_ptr;
  178399. JSAMPROW colorindex_ci;
  178400. int * dither; /* points to active row of dither matrix */
  178401. int row_index, col_index; /* current indexes into dither matrix */
  178402. int nc = cinfo->out_color_components;
  178403. int ci;
  178404. int row;
  178405. JDIMENSION col;
  178406. JDIMENSION width = cinfo->output_width;
  178407. for (row = 0; row < num_rows; row++) {
  178408. /* Initialize output values to 0 so can process components separately */
  178409. jzero_far((void FAR *) output_buf[row],
  178410. (size_t) (width * SIZEOF(JSAMPLE)));
  178411. row_index = cquantize->row_index;
  178412. for (ci = 0; ci < nc; ci++) {
  178413. input_ptr = input_buf[row] + ci;
  178414. output_ptr = output_buf[row];
  178415. colorindex_ci = cquantize->colorindex[ci];
  178416. dither = cquantize->odither[ci][row_index];
  178417. col_index = 0;
  178418. for (col = width; col > 0; col--) {
  178419. /* Form pixel value + dither, range-limit to 0..MAXJSAMPLE,
  178420. * select output value, accumulate into output code for this pixel.
  178421. * Range-limiting need not be done explicitly, as we have extended
  178422. * the colorindex table to produce the right answers for out-of-range
  178423. * inputs. The maximum dither is +- MAXJSAMPLE; this sets the
  178424. * required amount of padding.
  178425. */
  178426. *output_ptr += colorindex_ci[GETJSAMPLE(*input_ptr)+dither[col_index]];
  178427. input_ptr += nc;
  178428. output_ptr++;
  178429. col_index = (col_index + 1) & ODITHER_MASK;
  178430. }
  178431. }
  178432. /* Advance row index for next row */
  178433. row_index = (row_index + 1) & ODITHER_MASK;
  178434. cquantize->row_index = row_index;
  178435. }
  178436. }
  178437. METHODDEF(void)
  178438. quantize3_ord_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  178439. JSAMPARRAY output_buf, int num_rows)
  178440. /* Fast path for out_color_components==3, with ordered dithering */
  178441. {
  178442. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  178443. register int pixcode;
  178444. register JSAMPROW input_ptr;
  178445. register JSAMPROW output_ptr;
  178446. JSAMPROW colorindex0 = cquantize->colorindex[0];
  178447. JSAMPROW colorindex1 = cquantize->colorindex[1];
  178448. JSAMPROW colorindex2 = cquantize->colorindex[2];
  178449. int * dither0; /* points to active row of dither matrix */
  178450. int * dither1;
  178451. int * dither2;
  178452. int row_index, col_index; /* current indexes into dither matrix */
  178453. int row;
  178454. JDIMENSION col;
  178455. JDIMENSION width = cinfo->output_width;
  178456. for (row = 0; row < num_rows; row++) {
  178457. row_index = cquantize->row_index;
  178458. input_ptr = input_buf[row];
  178459. output_ptr = output_buf[row];
  178460. dither0 = cquantize->odither[0][row_index];
  178461. dither1 = cquantize->odither[1][row_index];
  178462. dither2 = cquantize->odither[2][row_index];
  178463. col_index = 0;
  178464. for (col = width; col > 0; col--) {
  178465. pixcode = GETJSAMPLE(colorindex0[GETJSAMPLE(*input_ptr++) +
  178466. dither0[col_index]]);
  178467. pixcode += GETJSAMPLE(colorindex1[GETJSAMPLE(*input_ptr++) +
  178468. dither1[col_index]]);
  178469. pixcode += GETJSAMPLE(colorindex2[GETJSAMPLE(*input_ptr++) +
  178470. dither2[col_index]]);
  178471. *output_ptr++ = (JSAMPLE) pixcode;
  178472. col_index = (col_index + 1) & ODITHER_MASK;
  178473. }
  178474. row_index = (row_index + 1) & ODITHER_MASK;
  178475. cquantize->row_index = row_index;
  178476. }
  178477. }
  178478. METHODDEF(void)
  178479. quantize_fs_dither (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  178480. JSAMPARRAY output_buf, int num_rows)
  178481. /* General case, with Floyd-Steinberg dithering */
  178482. {
  178483. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  178484. register LOCFSERROR cur; /* current error or pixel value */
  178485. LOCFSERROR belowerr; /* error for pixel below cur */
  178486. LOCFSERROR bpreverr; /* error for below/prev col */
  178487. LOCFSERROR bnexterr; /* error for below/next col */
  178488. LOCFSERROR delta;
  178489. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  178490. register JSAMPROW input_ptr;
  178491. register JSAMPROW output_ptr;
  178492. JSAMPROW colorindex_ci;
  178493. JSAMPROW colormap_ci;
  178494. int pixcode;
  178495. int nc = cinfo->out_color_components;
  178496. int dir; /* 1 for left-to-right, -1 for right-to-left */
  178497. int dirnc; /* dir * nc */
  178498. int ci;
  178499. int row;
  178500. JDIMENSION col;
  178501. JDIMENSION width = cinfo->output_width;
  178502. JSAMPLE *range_limit = cinfo->sample_range_limit;
  178503. SHIFT_TEMPS
  178504. for (row = 0; row < num_rows; row++) {
  178505. /* Initialize output values to 0 so can process components separately */
  178506. jzero_far((void FAR *) output_buf[row],
  178507. (size_t) (width * SIZEOF(JSAMPLE)));
  178508. for (ci = 0; ci < nc; ci++) {
  178509. input_ptr = input_buf[row] + ci;
  178510. output_ptr = output_buf[row];
  178511. if (cquantize->on_odd_row) {
  178512. /* work right to left in this row */
  178513. input_ptr += (width-1) * nc; /* so point to rightmost pixel */
  178514. output_ptr += width-1;
  178515. dir = -1;
  178516. dirnc = -nc;
  178517. errorptr = cquantize->fserrors[ci] + (width+1); /* => entry after last column */
  178518. } else {
  178519. /* work left to right in this row */
  178520. dir = 1;
  178521. dirnc = nc;
  178522. errorptr = cquantize->fserrors[ci]; /* => entry before first column */
  178523. }
  178524. colorindex_ci = cquantize->colorindex[ci];
  178525. colormap_ci = cquantize->sv_colormap[ci];
  178526. /* Preset error values: no error propagated to first pixel from left */
  178527. cur = 0;
  178528. /* and no error propagated to row below yet */
  178529. belowerr = bpreverr = 0;
  178530. for (col = width; col > 0; col--) {
  178531. /* cur holds the error propagated from the previous pixel on the
  178532. * current line. Add the error propagated from the previous line
  178533. * to form the complete error correction term for this pixel, and
  178534. * round the error term (which is expressed * 16) to an integer.
  178535. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  178536. * for either sign of the error value.
  178537. * Note: errorptr points to *previous* column's array entry.
  178538. */
  178539. cur = RIGHT_SHIFT(cur + errorptr[dir] + 8, 4);
  178540. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  178541. * The maximum error is +- MAXJSAMPLE; this sets the required size
  178542. * of the range_limit array.
  178543. */
  178544. cur += GETJSAMPLE(*input_ptr);
  178545. cur = GETJSAMPLE(range_limit[cur]);
  178546. /* Select output value, accumulate into output code for this pixel */
  178547. pixcode = GETJSAMPLE(colorindex_ci[cur]);
  178548. *output_ptr += (JSAMPLE) pixcode;
  178549. /* Compute actual representation error at this pixel */
  178550. /* Note: we can do this even though we don't have the final */
  178551. /* pixel code, because the colormap is orthogonal. */
  178552. cur -= GETJSAMPLE(colormap_ci[pixcode]);
  178553. /* Compute error fractions to be propagated to adjacent pixels.
  178554. * Add these into the running sums, and simultaneously shift the
  178555. * next-line error sums left by 1 column.
  178556. */
  178557. bnexterr = cur;
  178558. delta = cur * 2;
  178559. cur += delta; /* form error * 3 */
  178560. errorptr[0] = (FSERROR) (bpreverr + cur);
  178561. cur += delta; /* form error * 5 */
  178562. bpreverr = belowerr + cur;
  178563. belowerr = bnexterr;
  178564. cur += delta; /* form error * 7 */
  178565. /* At this point cur contains the 7/16 error value to be propagated
  178566. * to the next pixel on the current line, and all the errors for the
  178567. * next line have been shifted over. We are therefore ready to move on.
  178568. */
  178569. input_ptr += dirnc; /* advance input ptr to next column */
  178570. output_ptr += dir; /* advance output ptr to next column */
  178571. errorptr += dir; /* advance errorptr to current column */
  178572. }
  178573. /* Post-loop cleanup: we must unload the final error value into the
  178574. * final fserrors[] entry. Note we need not unload belowerr because
  178575. * it is for the dummy column before or after the actual array.
  178576. */
  178577. errorptr[0] = (FSERROR) bpreverr; /* unload prev err into array */
  178578. }
  178579. cquantize->on_odd_row = (cquantize->on_odd_row ? FALSE : TRUE);
  178580. }
  178581. }
  178582. /*
  178583. * Allocate workspace for Floyd-Steinberg errors.
  178584. */
  178585. LOCAL(void)
  178586. alloc_fs_workspace (j_decompress_ptr cinfo)
  178587. {
  178588. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  178589. size_t arraysize;
  178590. int i;
  178591. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  178592. for (i = 0; i < cinfo->out_color_components; i++) {
  178593. cquantize->fserrors[i] = (FSERRPTR)
  178594. (*cinfo->mem->alloc_large)((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  178595. }
  178596. }
  178597. /*
  178598. * Initialize for one-pass color quantization.
  178599. */
  178600. METHODDEF(void)
  178601. start_pass_1_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  178602. {
  178603. my_cquantize_ptr cquantize = (my_cquantize_ptr) cinfo->cquantize;
  178604. size_t arraysize;
  178605. int i;
  178606. /* Install my colormap. */
  178607. cinfo->colormap = cquantize->sv_colormap;
  178608. cinfo->actual_number_of_colors = cquantize->sv_actual;
  178609. /* Initialize for desired dithering mode. */
  178610. switch (cinfo->dither_mode) {
  178611. case JDITHER_NONE:
  178612. if (cinfo->out_color_components == 3)
  178613. cquantize->pub.color_quantize = color_quantize3;
  178614. else
  178615. cquantize->pub.color_quantize = color_quantize;
  178616. break;
  178617. case JDITHER_ORDERED:
  178618. if (cinfo->out_color_components == 3)
  178619. cquantize->pub.color_quantize = quantize3_ord_dither;
  178620. else
  178621. cquantize->pub.color_quantize = quantize_ord_dither;
  178622. cquantize->row_index = 0; /* initialize state for ordered dither */
  178623. /* If user changed to ordered dither from another mode,
  178624. * we must recreate the color index table with padding.
  178625. * This will cost extra space, but probably isn't very likely.
  178626. */
  178627. if (! cquantize->is_padded)
  178628. create_colorindex(cinfo);
  178629. /* Create ordered-dither tables if we didn't already. */
  178630. if (cquantize->odither[0] == NULL)
  178631. create_odither_tables(cinfo);
  178632. break;
  178633. case JDITHER_FS:
  178634. cquantize->pub.color_quantize = quantize_fs_dither;
  178635. cquantize->on_odd_row = FALSE; /* initialize state for F-S dither */
  178636. /* Allocate Floyd-Steinberg workspace if didn't already. */
  178637. if (cquantize->fserrors[0] == NULL)
  178638. alloc_fs_workspace(cinfo);
  178639. /* Initialize the propagated errors to zero. */
  178640. arraysize = (size_t) ((cinfo->output_width + 2) * SIZEOF(FSERROR));
  178641. for (i = 0; i < cinfo->out_color_components; i++)
  178642. jzero_far((void FAR *) cquantize->fserrors[i], arraysize);
  178643. break;
  178644. default:
  178645. ERREXIT(cinfo, JERR_NOT_COMPILED);
  178646. break;
  178647. }
  178648. }
  178649. /*
  178650. * Finish up at the end of the pass.
  178651. */
  178652. METHODDEF(void)
  178653. finish_pass_1_quant (j_decompress_ptr cinfo)
  178654. {
  178655. /* no work in 1-pass case */
  178656. }
  178657. /*
  178658. * Switch to a new external colormap between output passes.
  178659. * Shouldn't get to this module!
  178660. */
  178661. METHODDEF(void)
  178662. new_color_map_1_quant (j_decompress_ptr cinfo)
  178663. {
  178664. ERREXIT(cinfo, JERR_MODE_CHANGE);
  178665. }
  178666. /*
  178667. * Module initialization routine for 1-pass color quantization.
  178668. */
  178669. GLOBAL(void)
  178670. jinit_1pass_quantizer (j_decompress_ptr cinfo)
  178671. {
  178672. my_cquantize_ptr cquantize;
  178673. cquantize = (my_cquantize_ptr)
  178674. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  178675. SIZEOF(my_cquantizer));
  178676. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  178677. cquantize->pub.start_pass = start_pass_1_quant;
  178678. cquantize->pub.finish_pass = finish_pass_1_quant;
  178679. cquantize->pub.new_color_map = new_color_map_1_quant;
  178680. cquantize->fserrors[0] = NULL; /* Flag FS workspace not allocated */
  178681. cquantize->odither[0] = NULL; /* Also flag odither arrays not allocated */
  178682. /* Make sure my internal arrays won't overflow */
  178683. if (cinfo->out_color_components > MAX_Q_COMPS)
  178684. ERREXIT1(cinfo, JERR_QUANT_COMPONENTS, MAX_Q_COMPS);
  178685. /* Make sure colormap indexes can be represented by JSAMPLEs */
  178686. if (cinfo->desired_number_of_colors > (MAXJSAMPLE+1))
  178687. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXJSAMPLE+1);
  178688. /* Create the colormap and color index table. */
  178689. create_colormap(cinfo);
  178690. create_colorindex(cinfo);
  178691. /* Allocate Floyd-Steinberg workspace now if requested.
  178692. * We do this now since it is FAR storage and may affect the memory
  178693. * manager's space calculations. If the user changes to FS dither
  178694. * mode in a later pass, we will allocate the space then, and will
  178695. * possibly overrun the max_memory_to_use setting.
  178696. */
  178697. if (cinfo->dither_mode == JDITHER_FS)
  178698. alloc_fs_workspace(cinfo);
  178699. }
  178700. #endif /* QUANT_1PASS_SUPPORTED */
  178701. /********* End of inlined file: jquant1.c *********/
  178702. /********* Start of inlined file: jquant2.c *********/
  178703. #define JPEG_INTERNALS
  178704. #ifdef QUANT_2PASS_SUPPORTED
  178705. /*
  178706. * This module implements the well-known Heckbert paradigm for color
  178707. * quantization. Most of the ideas used here can be traced back to
  178708. * Heckbert's seminal paper
  178709. * Heckbert, Paul. "Color Image Quantization for Frame Buffer Display",
  178710. * Proc. SIGGRAPH '82, Computer Graphics v.16 #3 (July 1982), pp 297-304.
  178711. *
  178712. * In the first pass over the image, we accumulate a histogram showing the
  178713. * usage count of each possible color. To keep the histogram to a reasonable
  178714. * size, we reduce the precision of the input; typical practice is to retain
  178715. * 5 or 6 bits per color, so that 8 or 4 different input values are counted
  178716. * in the same histogram cell.
  178717. *
  178718. * Next, the color-selection step begins with a box representing the whole
  178719. * color space, and repeatedly splits the "largest" remaining box until we
  178720. * have as many boxes as desired colors. Then the mean color in each
  178721. * remaining box becomes one of the possible output colors.
  178722. *
  178723. * The second pass over the image maps each input pixel to the closest output
  178724. * color (optionally after applying a Floyd-Steinberg dithering correction).
  178725. * This mapping is logically trivial, but making it go fast enough requires
  178726. * considerable care.
  178727. *
  178728. * Heckbert-style quantizers vary a good deal in their policies for choosing
  178729. * the "largest" box and deciding where to cut it. The particular policies
  178730. * used here have proved out well in experimental comparisons, but better ones
  178731. * may yet be found.
  178732. *
  178733. * In earlier versions of the IJG code, this module quantized in YCbCr color
  178734. * space, processing the raw upsampled data without a color conversion step.
  178735. * This allowed the color conversion math to be done only once per colormap
  178736. * entry, not once per pixel. However, that optimization precluded other
  178737. * useful optimizations (such as merging color conversion with upsampling)
  178738. * and it also interfered with desired capabilities such as quantizing to an
  178739. * externally-supplied colormap. We have therefore abandoned that approach.
  178740. * The present code works in the post-conversion color space, typically RGB.
  178741. *
  178742. * To improve the visual quality of the results, we actually work in scaled
  178743. * RGB space, giving G distances more weight than R, and R in turn more than
  178744. * B. To do everything in integer math, we must use integer scale factors.
  178745. * The 2/3/1 scale factors used here correspond loosely to the relative
  178746. * weights of the colors in the NTSC grayscale equation.
  178747. * If you want to use this code to quantize a non-RGB color space, you'll
  178748. * probably need to change these scale factors.
  178749. */
  178750. #define R_SCALE 2 /* scale R distances by this much */
  178751. #define G_SCALE 3 /* scale G distances by this much */
  178752. #define B_SCALE 1 /* and B by this much */
  178753. /* Relabel R/G/B as components 0/1/2, respecting the RGB ordering defined
  178754. * in jmorecfg.h. As the code stands, it will do the right thing for R,G,B
  178755. * and B,G,R orders. If you define some other weird order in jmorecfg.h,
  178756. * you'll get compile errors until you extend this logic. In that case
  178757. * you'll probably want to tweak the histogram sizes too.
  178758. */
  178759. #if RGB_RED == 0
  178760. #define C0_SCALE R_SCALE
  178761. #endif
  178762. #if RGB_BLUE == 0
  178763. #define C0_SCALE B_SCALE
  178764. #endif
  178765. #if RGB_GREEN == 1
  178766. #define C1_SCALE G_SCALE
  178767. #endif
  178768. #if RGB_RED == 2
  178769. #define C2_SCALE R_SCALE
  178770. #endif
  178771. #if RGB_BLUE == 2
  178772. #define C2_SCALE B_SCALE
  178773. #endif
  178774. /*
  178775. * First we have the histogram data structure and routines for creating it.
  178776. *
  178777. * The number of bits of precision can be adjusted by changing these symbols.
  178778. * We recommend keeping 6 bits for G and 5 each for R and B.
  178779. * If you have plenty of memory and cycles, 6 bits all around gives marginally
  178780. * better results; if you are short of memory, 5 bits all around will save
  178781. * some space but degrade the results.
  178782. * To maintain a fully accurate histogram, we'd need to allocate a "long"
  178783. * (preferably unsigned long) for each cell. In practice this is overkill;
  178784. * we can get by with 16 bits per cell. Few of the cell counts will overflow,
  178785. * and clamping those that do overflow to the maximum value will give close-
  178786. * enough results. This reduces the recommended histogram size from 256Kb
  178787. * to 128Kb, which is a useful savings on PC-class machines.
  178788. * (In the second pass the histogram space is re-used for pixel mapping data;
  178789. * in that capacity, each cell must be able to store zero to the number of
  178790. * desired colors. 16 bits/cell is plenty for that too.)
  178791. * Since the JPEG code is intended to run in small memory model on 80x86
  178792. * machines, we can't just allocate the histogram in one chunk. Instead
  178793. * of a true 3-D array, we use a row of pointers to 2-D arrays. Each
  178794. * pointer corresponds to a C0 value (typically 2^5 = 32 pointers) and
  178795. * each 2-D array has 2^6*2^5 = 2048 or 2^6*2^6 = 4096 entries. Note that
  178796. * on 80x86 machines, the pointer row is in near memory but the actual
  178797. * arrays are in far memory (same arrangement as we use for image arrays).
  178798. */
  178799. #define MAXNUMCOLORS (MAXJSAMPLE+1) /* maximum size of colormap */
  178800. /* These will do the right thing for either R,G,B or B,G,R color order,
  178801. * but you may not like the results for other color orders.
  178802. */
  178803. #define HIST_C0_BITS 5 /* bits of precision in R/B histogram */
  178804. #define HIST_C1_BITS 6 /* bits of precision in G histogram */
  178805. #define HIST_C2_BITS 5 /* bits of precision in B/R histogram */
  178806. /* Number of elements along histogram axes. */
  178807. #define HIST_C0_ELEMS (1<<HIST_C0_BITS)
  178808. #define HIST_C1_ELEMS (1<<HIST_C1_BITS)
  178809. #define HIST_C2_ELEMS (1<<HIST_C2_BITS)
  178810. /* These are the amounts to shift an input value to get a histogram index. */
  178811. #define C0_SHIFT (BITS_IN_JSAMPLE-HIST_C0_BITS)
  178812. #define C1_SHIFT (BITS_IN_JSAMPLE-HIST_C1_BITS)
  178813. #define C2_SHIFT (BITS_IN_JSAMPLE-HIST_C2_BITS)
  178814. typedef UINT16 histcell; /* histogram cell; prefer an unsigned type */
  178815. typedef histcell FAR * histptr; /* for pointers to histogram cells */
  178816. typedef histcell hist1d[HIST_C2_ELEMS]; /* typedefs for the array */
  178817. typedef hist1d FAR * hist2d; /* type for the 2nd-level pointers */
  178818. typedef hist2d * hist3d; /* type for top-level pointer */
  178819. /* Declarations for Floyd-Steinberg dithering.
  178820. *
  178821. * Errors are accumulated into the array fserrors[], at a resolution of
  178822. * 1/16th of a pixel count. The error at a given pixel is propagated
  178823. * to its not-yet-processed neighbors using the standard F-S fractions,
  178824. * ... (here) 7/16
  178825. * 3/16 5/16 1/16
  178826. * We work left-to-right on even rows, right-to-left on odd rows.
  178827. *
  178828. * We can get away with a single array (holding one row's worth of errors)
  178829. * by using it to store the current row's errors at pixel columns not yet
  178830. * processed, but the next row's errors at columns already processed. We
  178831. * need only a few extra variables to hold the errors immediately around the
  178832. * current column. (If we are lucky, those variables are in registers, but
  178833. * even if not, they're probably cheaper to access than array elements are.)
  178834. *
  178835. * The fserrors[] array has (#columns + 2) entries; the extra entry at
  178836. * each end saves us from special-casing the first and last pixels.
  178837. * Each entry is three values long, one value for each color component.
  178838. *
  178839. * Note: on a wide image, we might not have enough room in a PC's near data
  178840. * segment to hold the error array; so it is allocated with alloc_large.
  178841. */
  178842. #if BITS_IN_JSAMPLE == 8
  178843. typedef INT16 FSERROR; /* 16 bits should be enough */
  178844. typedef int LOCFSERROR; /* use 'int' for calculation temps */
  178845. #else
  178846. typedef INT32 FSERROR; /* may need more than 16 bits */
  178847. typedef INT32 LOCFSERROR; /* be sure calculation temps are big enough */
  178848. #endif
  178849. typedef FSERROR FAR *FSERRPTR; /* pointer to error array (in FAR storage!) */
  178850. /* Private subobject */
  178851. typedef struct {
  178852. struct jpeg_color_quantizer pub; /* public fields */
  178853. /* Space for the eventually created colormap is stashed here */
  178854. JSAMPARRAY sv_colormap; /* colormap allocated at init time */
  178855. int desired; /* desired # of colors = size of colormap */
  178856. /* Variables for accumulating image statistics */
  178857. hist3d histogram; /* pointer to the histogram */
  178858. boolean needs_zeroed; /* TRUE if next pass must zero histogram */
  178859. /* Variables for Floyd-Steinberg dithering */
  178860. FSERRPTR fserrors; /* accumulated errors */
  178861. boolean on_odd_row; /* flag to remember which row we are on */
  178862. int * error_limiter; /* table for clamping the applied error */
  178863. } my_cquantizer2;
  178864. typedef my_cquantizer2 * my_cquantize_ptr2;
  178865. /*
  178866. * Prescan some rows of pixels.
  178867. * In this module the prescan simply updates the histogram, which has been
  178868. * initialized to zeroes by start_pass.
  178869. * An output_buf parameter is required by the method signature, but no data
  178870. * is actually output (in fact the buffer controller is probably passing a
  178871. * NULL pointer).
  178872. */
  178873. METHODDEF(void)
  178874. prescan_quantize (j_decompress_ptr cinfo, JSAMPARRAY input_buf,
  178875. JSAMPARRAY output_buf, int num_rows)
  178876. {
  178877. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178878. register JSAMPROW ptr;
  178879. register histptr histp;
  178880. register hist3d histogram = cquantize->histogram;
  178881. int row;
  178882. JDIMENSION col;
  178883. JDIMENSION width = cinfo->output_width;
  178884. for (row = 0; row < num_rows; row++) {
  178885. ptr = input_buf[row];
  178886. for (col = width; col > 0; col--) {
  178887. /* get pixel value and index into the histogram */
  178888. histp = & histogram[GETJSAMPLE(ptr[0]) >> C0_SHIFT]
  178889. [GETJSAMPLE(ptr[1]) >> C1_SHIFT]
  178890. [GETJSAMPLE(ptr[2]) >> C2_SHIFT];
  178891. /* increment, check for overflow and undo increment if so. */
  178892. if (++(*histp) <= 0)
  178893. (*histp)--;
  178894. ptr += 3;
  178895. }
  178896. }
  178897. }
  178898. /*
  178899. * Next we have the really interesting routines: selection of a colormap
  178900. * given the completed histogram.
  178901. * These routines work with a list of "boxes", each representing a rectangular
  178902. * subset of the input color space (to histogram precision).
  178903. */
  178904. typedef struct {
  178905. /* The bounds of the box (inclusive); expressed as histogram indexes */
  178906. int c0min, c0max;
  178907. int c1min, c1max;
  178908. int c2min, c2max;
  178909. /* The volume (actually 2-norm) of the box */
  178910. INT32 volume;
  178911. /* The number of nonzero histogram cells within this box */
  178912. long colorcount;
  178913. } box;
  178914. typedef box * boxptr;
  178915. LOCAL(boxptr)
  178916. find_biggest_color_pop (boxptr boxlist, int numboxes)
  178917. /* Find the splittable box with the largest color population */
  178918. /* Returns NULL if no splittable boxes remain */
  178919. {
  178920. register boxptr boxp;
  178921. register int i;
  178922. register long maxc = 0;
  178923. boxptr which = NULL;
  178924. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178925. if (boxp->colorcount > maxc && boxp->volume > 0) {
  178926. which = boxp;
  178927. maxc = boxp->colorcount;
  178928. }
  178929. }
  178930. return which;
  178931. }
  178932. LOCAL(boxptr)
  178933. find_biggest_volume (boxptr boxlist, int numboxes)
  178934. /* Find the splittable box with the largest (scaled) volume */
  178935. /* Returns NULL if no splittable boxes remain */
  178936. {
  178937. register boxptr boxp;
  178938. register int i;
  178939. register INT32 maxv = 0;
  178940. boxptr which = NULL;
  178941. for (i = 0, boxp = boxlist; i < numboxes; i++, boxp++) {
  178942. if (boxp->volume > maxv) {
  178943. which = boxp;
  178944. maxv = boxp->volume;
  178945. }
  178946. }
  178947. return which;
  178948. }
  178949. LOCAL(void)
  178950. update_box (j_decompress_ptr cinfo, boxptr boxp)
  178951. /* Shrink the min/max bounds of a box to enclose only nonzero elements, */
  178952. /* and recompute its volume and population */
  178953. {
  178954. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  178955. hist3d histogram = cquantize->histogram;
  178956. histptr histp;
  178957. int c0,c1,c2;
  178958. int c0min,c0max,c1min,c1max,c2min,c2max;
  178959. INT32 dist0,dist1,dist2;
  178960. long ccount;
  178961. c0min = boxp->c0min; c0max = boxp->c0max;
  178962. c1min = boxp->c1min; c1max = boxp->c1max;
  178963. c2min = boxp->c2min; c2max = boxp->c2max;
  178964. if (c0max > c0min)
  178965. for (c0 = c0min; c0 <= c0max; c0++)
  178966. for (c1 = c1min; c1 <= c1max; c1++) {
  178967. histp = & histogram[c0][c1][c2min];
  178968. for (c2 = c2min; c2 <= c2max; c2++)
  178969. if (*histp++ != 0) {
  178970. boxp->c0min = c0min = c0;
  178971. goto have_c0min;
  178972. }
  178973. }
  178974. have_c0min:
  178975. if (c0max > c0min)
  178976. for (c0 = c0max; c0 >= c0min; c0--)
  178977. for (c1 = c1min; c1 <= c1max; c1++) {
  178978. histp = & histogram[c0][c1][c2min];
  178979. for (c2 = c2min; c2 <= c2max; c2++)
  178980. if (*histp++ != 0) {
  178981. boxp->c0max = c0max = c0;
  178982. goto have_c0max;
  178983. }
  178984. }
  178985. have_c0max:
  178986. if (c1max > c1min)
  178987. for (c1 = c1min; c1 <= c1max; c1++)
  178988. for (c0 = c0min; c0 <= c0max; c0++) {
  178989. histp = & histogram[c0][c1][c2min];
  178990. for (c2 = c2min; c2 <= c2max; c2++)
  178991. if (*histp++ != 0) {
  178992. boxp->c1min = c1min = c1;
  178993. goto have_c1min;
  178994. }
  178995. }
  178996. have_c1min:
  178997. if (c1max > c1min)
  178998. for (c1 = c1max; c1 >= c1min; c1--)
  178999. for (c0 = c0min; c0 <= c0max; c0++) {
  179000. histp = & histogram[c0][c1][c2min];
  179001. for (c2 = c2min; c2 <= c2max; c2++)
  179002. if (*histp++ != 0) {
  179003. boxp->c1max = c1max = c1;
  179004. goto have_c1max;
  179005. }
  179006. }
  179007. have_c1max:
  179008. if (c2max > c2min)
  179009. for (c2 = c2min; c2 <= c2max; c2++)
  179010. for (c0 = c0min; c0 <= c0max; c0++) {
  179011. histp = & histogram[c0][c1min][c2];
  179012. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  179013. if (*histp != 0) {
  179014. boxp->c2min = c2min = c2;
  179015. goto have_c2min;
  179016. }
  179017. }
  179018. have_c2min:
  179019. if (c2max > c2min)
  179020. for (c2 = c2max; c2 >= c2min; c2--)
  179021. for (c0 = c0min; c0 <= c0max; c0++) {
  179022. histp = & histogram[c0][c1min][c2];
  179023. for (c1 = c1min; c1 <= c1max; c1++, histp += HIST_C2_ELEMS)
  179024. if (*histp != 0) {
  179025. boxp->c2max = c2max = c2;
  179026. goto have_c2max;
  179027. }
  179028. }
  179029. have_c2max:
  179030. /* Update box volume.
  179031. * We use 2-norm rather than real volume here; this biases the method
  179032. * against making long narrow boxes, and it has the side benefit that
  179033. * a box is splittable iff norm > 0.
  179034. * Since the differences are expressed in histogram-cell units,
  179035. * we have to shift back to JSAMPLE units to get consistent distances;
  179036. * after which, we scale according to the selected distance scale factors.
  179037. */
  179038. dist0 = ((c0max - c0min) << C0_SHIFT) * C0_SCALE;
  179039. dist1 = ((c1max - c1min) << C1_SHIFT) * C1_SCALE;
  179040. dist2 = ((c2max - c2min) << C2_SHIFT) * C2_SCALE;
  179041. boxp->volume = dist0*dist0 + dist1*dist1 + dist2*dist2;
  179042. /* Now scan remaining volume of box and compute population */
  179043. ccount = 0;
  179044. for (c0 = c0min; c0 <= c0max; c0++)
  179045. for (c1 = c1min; c1 <= c1max; c1++) {
  179046. histp = & histogram[c0][c1][c2min];
  179047. for (c2 = c2min; c2 <= c2max; c2++, histp++)
  179048. if (*histp != 0) {
  179049. ccount++;
  179050. }
  179051. }
  179052. boxp->colorcount = ccount;
  179053. }
  179054. LOCAL(int)
  179055. median_cut (j_decompress_ptr cinfo, boxptr boxlist, int numboxes,
  179056. int desired_colors)
  179057. /* Repeatedly select and split the largest box until we have enough boxes */
  179058. {
  179059. int n,lb;
  179060. int c0,c1,c2,cmax;
  179061. register boxptr b1,b2;
  179062. while (numboxes < desired_colors) {
  179063. /* Select box to split.
  179064. * Current algorithm: by population for first half, then by volume.
  179065. */
  179066. if (numboxes*2 <= desired_colors) {
  179067. b1 = find_biggest_color_pop(boxlist, numboxes);
  179068. } else {
  179069. b1 = find_biggest_volume(boxlist, numboxes);
  179070. }
  179071. if (b1 == NULL) /* no splittable boxes left! */
  179072. break;
  179073. b2 = &boxlist[numboxes]; /* where new box will go */
  179074. /* Copy the color bounds to the new box. */
  179075. b2->c0max = b1->c0max; b2->c1max = b1->c1max; b2->c2max = b1->c2max;
  179076. b2->c0min = b1->c0min; b2->c1min = b1->c1min; b2->c2min = b1->c2min;
  179077. /* Choose which axis to split the box on.
  179078. * Current algorithm: longest scaled axis.
  179079. * See notes in update_box about scaling distances.
  179080. */
  179081. c0 = ((b1->c0max - b1->c0min) << C0_SHIFT) * C0_SCALE;
  179082. c1 = ((b1->c1max - b1->c1min) << C1_SHIFT) * C1_SCALE;
  179083. c2 = ((b1->c2max - b1->c2min) << C2_SHIFT) * C2_SCALE;
  179084. /* We want to break any ties in favor of green, then red, blue last.
  179085. * This code does the right thing for R,G,B or B,G,R color orders only.
  179086. */
  179087. #if RGB_RED == 0
  179088. cmax = c1; n = 1;
  179089. if (c0 > cmax) { cmax = c0; n = 0; }
  179090. if (c2 > cmax) { n = 2; }
  179091. #else
  179092. cmax = c1; n = 1;
  179093. if (c2 > cmax) { cmax = c2; n = 2; }
  179094. if (c0 > cmax) { n = 0; }
  179095. #endif
  179096. /* Choose split point along selected axis, and update box bounds.
  179097. * Current algorithm: split at halfway point.
  179098. * (Since the box has been shrunk to minimum volume,
  179099. * any split will produce two nonempty subboxes.)
  179100. * Note that lb value is max for lower box, so must be < old max.
  179101. */
  179102. switch (n) {
  179103. case 0:
  179104. lb = (b1->c0max + b1->c0min) / 2;
  179105. b1->c0max = lb;
  179106. b2->c0min = lb+1;
  179107. break;
  179108. case 1:
  179109. lb = (b1->c1max + b1->c1min) / 2;
  179110. b1->c1max = lb;
  179111. b2->c1min = lb+1;
  179112. break;
  179113. case 2:
  179114. lb = (b1->c2max + b1->c2min) / 2;
  179115. b1->c2max = lb;
  179116. b2->c2min = lb+1;
  179117. break;
  179118. }
  179119. /* Update stats for boxes */
  179120. update_box(cinfo, b1);
  179121. update_box(cinfo, b2);
  179122. numboxes++;
  179123. }
  179124. return numboxes;
  179125. }
  179126. LOCAL(void)
  179127. compute_color (j_decompress_ptr cinfo, boxptr boxp, int icolor)
  179128. /* Compute representative color for a box, put it in colormap[icolor] */
  179129. {
  179130. /* Current algorithm: mean weighted by pixels (not colors) */
  179131. /* Note it is important to get the rounding correct! */
  179132. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  179133. hist3d histogram = cquantize->histogram;
  179134. histptr histp;
  179135. int c0,c1,c2;
  179136. int c0min,c0max,c1min,c1max,c2min,c2max;
  179137. long count;
  179138. long total = 0;
  179139. long c0total = 0;
  179140. long c1total = 0;
  179141. long c2total = 0;
  179142. c0min = boxp->c0min; c0max = boxp->c0max;
  179143. c1min = boxp->c1min; c1max = boxp->c1max;
  179144. c2min = boxp->c2min; c2max = boxp->c2max;
  179145. for (c0 = c0min; c0 <= c0max; c0++)
  179146. for (c1 = c1min; c1 <= c1max; c1++) {
  179147. histp = & histogram[c0][c1][c2min];
  179148. for (c2 = c2min; c2 <= c2max; c2++) {
  179149. if ((count = *histp++) != 0) {
  179150. total += count;
  179151. c0total += ((c0 << C0_SHIFT) + ((1<<C0_SHIFT)>>1)) * count;
  179152. c1total += ((c1 << C1_SHIFT) + ((1<<C1_SHIFT)>>1)) * count;
  179153. c2total += ((c2 << C2_SHIFT) + ((1<<C2_SHIFT)>>1)) * count;
  179154. }
  179155. }
  179156. }
  179157. cinfo->colormap[0][icolor] = (JSAMPLE) ((c0total + (total>>1)) / total);
  179158. cinfo->colormap[1][icolor] = (JSAMPLE) ((c1total + (total>>1)) / total);
  179159. cinfo->colormap[2][icolor] = (JSAMPLE) ((c2total + (total>>1)) / total);
  179160. }
  179161. LOCAL(void)
  179162. select_colors (j_decompress_ptr cinfo, int desired_colors)
  179163. /* Master routine for color selection */
  179164. {
  179165. boxptr boxlist;
  179166. int numboxes;
  179167. int i;
  179168. /* Allocate workspace for box list */
  179169. boxlist = (boxptr) (*cinfo->mem->alloc_small)
  179170. ((j_common_ptr) cinfo, JPOOL_IMAGE, desired_colors * SIZEOF(box));
  179171. /* Initialize one box containing whole space */
  179172. numboxes = 1;
  179173. boxlist[0].c0min = 0;
  179174. boxlist[0].c0max = MAXJSAMPLE >> C0_SHIFT;
  179175. boxlist[0].c1min = 0;
  179176. boxlist[0].c1max = MAXJSAMPLE >> C1_SHIFT;
  179177. boxlist[0].c2min = 0;
  179178. boxlist[0].c2max = MAXJSAMPLE >> C2_SHIFT;
  179179. /* Shrink it to actually-used volume and set its statistics */
  179180. update_box(cinfo, & boxlist[0]);
  179181. /* Perform median-cut to produce final box list */
  179182. numboxes = median_cut(cinfo, boxlist, numboxes, desired_colors);
  179183. /* Compute the representative color for each box, fill colormap */
  179184. for (i = 0; i < numboxes; i++)
  179185. compute_color(cinfo, & boxlist[i], i);
  179186. cinfo->actual_number_of_colors = numboxes;
  179187. TRACEMS1(cinfo, 1, JTRC_QUANT_SELECTED, numboxes);
  179188. }
  179189. /*
  179190. * These routines are concerned with the time-critical task of mapping input
  179191. * colors to the nearest color in the selected colormap.
  179192. *
  179193. * We re-use the histogram space as an "inverse color map", essentially a
  179194. * cache for the results of nearest-color searches. All colors within a
  179195. * histogram cell will be mapped to the same colormap entry, namely the one
  179196. * closest to the cell's center. This may not be quite the closest entry to
  179197. * the actual input color, but it's almost as good. A zero in the cache
  179198. * indicates we haven't found the nearest color for that cell yet; the array
  179199. * is cleared to zeroes before starting the mapping pass. When we find the
  179200. * nearest color for a cell, its colormap index plus one is recorded in the
  179201. * cache for future use. The pass2 scanning routines call fill_inverse_cmap
  179202. * when they need to use an unfilled entry in the cache.
  179203. *
  179204. * Our method of efficiently finding nearest colors is based on the "locally
  179205. * sorted search" idea described by Heckbert and on the incremental distance
  179206. * calculation described by Spencer W. Thomas in chapter III.1 of Graphics
  179207. * Gems II (James Arvo, ed. Academic Press, 1991). Thomas points out that
  179208. * the distances from a given colormap entry to each cell of the histogram can
  179209. * be computed quickly using an incremental method: the differences between
  179210. * distances to adjacent cells themselves differ by a constant. This allows a
  179211. * fairly fast implementation of the "brute force" approach of computing the
  179212. * distance from every colormap entry to every histogram cell. Unfortunately,
  179213. * it needs a work array to hold the best-distance-so-far for each histogram
  179214. * cell (because the inner loop has to be over cells, not colormap entries).
  179215. * The work array elements have to be INT32s, so the work array would need
  179216. * 256Kb at our recommended precision. This is not feasible in DOS machines.
  179217. *
  179218. * To get around these problems, we apply Thomas' method to compute the
  179219. * nearest colors for only the cells within a small subbox of the histogram.
  179220. * The work array need be only as big as the subbox, so the memory usage
  179221. * problem is solved. Furthermore, we need not fill subboxes that are never
  179222. * referenced in pass2; many images use only part of the color gamut, so a
  179223. * fair amount of work is saved. An additional advantage of this
  179224. * approach is that we can apply Heckbert's locality criterion to quickly
  179225. * eliminate colormap entries that are far away from the subbox; typically
  179226. * three-fourths of the colormap entries are rejected by Heckbert's criterion,
  179227. * and we need not compute their distances to individual cells in the subbox.
  179228. * The speed of this approach is heavily influenced by the subbox size: too
  179229. * small means too much overhead, too big loses because Heckbert's criterion
  179230. * can't eliminate as many colormap entries. Empirically the best subbox
  179231. * size seems to be about 1/512th of the histogram (1/8th in each direction).
  179232. *
  179233. * Thomas' article also describes a refined method which is asymptotically
  179234. * faster than the brute-force method, but it is also far more complex and
  179235. * cannot efficiently be applied to small subboxes. It is therefore not
  179236. * useful for programs intended to be portable to DOS machines. On machines
  179237. * with plenty of memory, filling the whole histogram in one shot with Thomas'
  179238. * refined method might be faster than the present code --- but then again,
  179239. * it might not be any faster, and it's certainly more complicated.
  179240. */
  179241. /* log2(histogram cells in update box) for each axis; this can be adjusted */
  179242. #define BOX_C0_LOG (HIST_C0_BITS-3)
  179243. #define BOX_C1_LOG (HIST_C1_BITS-3)
  179244. #define BOX_C2_LOG (HIST_C2_BITS-3)
  179245. #define BOX_C0_ELEMS (1<<BOX_C0_LOG) /* # of hist cells in update box */
  179246. #define BOX_C1_ELEMS (1<<BOX_C1_LOG)
  179247. #define BOX_C2_ELEMS (1<<BOX_C2_LOG)
  179248. #define BOX_C0_SHIFT (C0_SHIFT + BOX_C0_LOG)
  179249. #define BOX_C1_SHIFT (C1_SHIFT + BOX_C1_LOG)
  179250. #define BOX_C2_SHIFT (C2_SHIFT + BOX_C2_LOG)
  179251. /*
  179252. * The next three routines implement inverse colormap filling. They could
  179253. * all be folded into one big routine, but splitting them up this way saves
  179254. * some stack space (the mindist[] and bestdist[] arrays need not coexist)
  179255. * and may allow some compilers to produce better code by registerizing more
  179256. * inner-loop variables.
  179257. */
  179258. LOCAL(int)
  179259. find_nearby_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  179260. JSAMPLE colorlist[])
  179261. /* Locate the colormap entries close enough to an update box to be candidates
  179262. * for the nearest entry to some cell(s) in the update box. The update box
  179263. * is specified by the center coordinates of its first cell. The number of
  179264. * candidate colormap entries is returned, and their colormap indexes are
  179265. * placed in colorlist[].
  179266. * This routine uses Heckbert's "locally sorted search" criterion to select
  179267. * the colors that need further consideration.
  179268. */
  179269. {
  179270. int numcolors = cinfo->actual_number_of_colors;
  179271. int maxc0, maxc1, maxc2;
  179272. int centerc0, centerc1, centerc2;
  179273. int i, x, ncolors;
  179274. INT32 minmaxdist, min_dist, max_dist, tdist;
  179275. INT32 mindist[MAXNUMCOLORS]; /* min distance to colormap entry i */
  179276. /* Compute true coordinates of update box's upper corner and center.
  179277. * Actually we compute the coordinates of the center of the upper-corner
  179278. * histogram cell, which are the upper bounds of the volume we care about.
  179279. * Note that since ">>" rounds down, the "center" values may be closer to
  179280. * min than to max; hence comparisons to them must be "<=", not "<".
  179281. */
  179282. maxc0 = minc0 + ((1 << BOX_C0_SHIFT) - (1 << C0_SHIFT));
  179283. centerc0 = (minc0 + maxc0) >> 1;
  179284. maxc1 = minc1 + ((1 << BOX_C1_SHIFT) - (1 << C1_SHIFT));
  179285. centerc1 = (minc1 + maxc1) >> 1;
  179286. maxc2 = minc2 + ((1 << BOX_C2_SHIFT) - (1 << C2_SHIFT));
  179287. centerc2 = (minc2 + maxc2) >> 1;
  179288. /* For each color in colormap, find:
  179289. * 1. its minimum squared-distance to any point in the update box
  179290. * (zero if color is within update box);
  179291. * 2. its maximum squared-distance to any point in the update box.
  179292. * Both of these can be found by considering only the corners of the box.
  179293. * We save the minimum distance for each color in mindist[];
  179294. * only the smallest maximum distance is of interest.
  179295. */
  179296. minmaxdist = 0x7FFFFFFFL;
  179297. for (i = 0; i < numcolors; i++) {
  179298. /* We compute the squared-c0-distance term, then add in the other two. */
  179299. x = GETJSAMPLE(cinfo->colormap[0][i]);
  179300. if (x < minc0) {
  179301. tdist = (x - minc0) * C0_SCALE;
  179302. min_dist = tdist*tdist;
  179303. tdist = (x - maxc0) * C0_SCALE;
  179304. max_dist = tdist*tdist;
  179305. } else if (x > maxc0) {
  179306. tdist = (x - maxc0) * C0_SCALE;
  179307. min_dist = tdist*tdist;
  179308. tdist = (x - minc0) * C0_SCALE;
  179309. max_dist = tdist*tdist;
  179310. } else {
  179311. /* within cell range so no contribution to min_dist */
  179312. min_dist = 0;
  179313. if (x <= centerc0) {
  179314. tdist = (x - maxc0) * C0_SCALE;
  179315. max_dist = tdist*tdist;
  179316. } else {
  179317. tdist = (x - minc0) * C0_SCALE;
  179318. max_dist = tdist*tdist;
  179319. }
  179320. }
  179321. x = GETJSAMPLE(cinfo->colormap[1][i]);
  179322. if (x < minc1) {
  179323. tdist = (x - minc1) * C1_SCALE;
  179324. min_dist += tdist*tdist;
  179325. tdist = (x - maxc1) * C1_SCALE;
  179326. max_dist += tdist*tdist;
  179327. } else if (x > maxc1) {
  179328. tdist = (x - maxc1) * C1_SCALE;
  179329. min_dist += tdist*tdist;
  179330. tdist = (x - minc1) * C1_SCALE;
  179331. max_dist += tdist*tdist;
  179332. } else {
  179333. /* within cell range so no contribution to min_dist */
  179334. if (x <= centerc1) {
  179335. tdist = (x - maxc1) * C1_SCALE;
  179336. max_dist += tdist*tdist;
  179337. } else {
  179338. tdist = (x - minc1) * C1_SCALE;
  179339. max_dist += tdist*tdist;
  179340. }
  179341. }
  179342. x = GETJSAMPLE(cinfo->colormap[2][i]);
  179343. if (x < minc2) {
  179344. tdist = (x - minc2) * C2_SCALE;
  179345. min_dist += tdist*tdist;
  179346. tdist = (x - maxc2) * C2_SCALE;
  179347. max_dist += tdist*tdist;
  179348. } else if (x > maxc2) {
  179349. tdist = (x - maxc2) * C2_SCALE;
  179350. min_dist += tdist*tdist;
  179351. tdist = (x - minc2) * C2_SCALE;
  179352. max_dist += tdist*tdist;
  179353. } else {
  179354. /* within cell range so no contribution to min_dist */
  179355. if (x <= centerc2) {
  179356. tdist = (x - maxc2) * C2_SCALE;
  179357. max_dist += tdist*tdist;
  179358. } else {
  179359. tdist = (x - minc2) * C2_SCALE;
  179360. max_dist += tdist*tdist;
  179361. }
  179362. }
  179363. mindist[i] = min_dist; /* save away the results */
  179364. if (max_dist < minmaxdist)
  179365. minmaxdist = max_dist;
  179366. }
  179367. /* Now we know that no cell in the update box is more than minmaxdist
  179368. * away from some colormap entry. Therefore, only colors that are
  179369. * within minmaxdist of some part of the box need be considered.
  179370. */
  179371. ncolors = 0;
  179372. for (i = 0; i < numcolors; i++) {
  179373. if (mindist[i] <= minmaxdist)
  179374. colorlist[ncolors++] = (JSAMPLE) i;
  179375. }
  179376. return ncolors;
  179377. }
  179378. LOCAL(void)
  179379. find_best_colors (j_decompress_ptr cinfo, int minc0, int minc1, int minc2,
  179380. int numcolors, JSAMPLE colorlist[], JSAMPLE bestcolor[])
  179381. /* Find the closest colormap entry for each cell in the update box,
  179382. * given the list of candidate colors prepared by find_nearby_colors.
  179383. * Return the indexes of the closest entries in the bestcolor[] array.
  179384. * This routine uses Thomas' incremental distance calculation method to
  179385. * find the distance from a colormap entry to successive cells in the box.
  179386. */
  179387. {
  179388. int ic0, ic1, ic2;
  179389. int i, icolor;
  179390. register INT32 * bptr; /* pointer into bestdist[] array */
  179391. JSAMPLE * cptr; /* pointer into bestcolor[] array */
  179392. INT32 dist0, dist1; /* initial distance values */
  179393. register INT32 dist2; /* current distance in inner loop */
  179394. INT32 xx0, xx1; /* distance increments */
  179395. register INT32 xx2;
  179396. INT32 inc0, inc1, inc2; /* initial values for increments */
  179397. /* This array holds the distance to the nearest-so-far color for each cell */
  179398. INT32 bestdist[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  179399. /* Initialize best-distance for each cell of the update box */
  179400. bptr = bestdist;
  179401. for (i = BOX_C0_ELEMS*BOX_C1_ELEMS*BOX_C2_ELEMS-1; i >= 0; i--)
  179402. *bptr++ = 0x7FFFFFFFL;
  179403. /* For each color selected by find_nearby_colors,
  179404. * compute its distance to the center of each cell in the box.
  179405. * If that's less than best-so-far, update best distance and color number.
  179406. */
  179407. /* Nominal steps between cell centers ("x" in Thomas article) */
  179408. #define STEP_C0 ((1 << C0_SHIFT) * C0_SCALE)
  179409. #define STEP_C1 ((1 << C1_SHIFT) * C1_SCALE)
  179410. #define STEP_C2 ((1 << C2_SHIFT) * C2_SCALE)
  179411. for (i = 0; i < numcolors; i++) {
  179412. icolor = GETJSAMPLE(colorlist[i]);
  179413. /* Compute (square of) distance from minc0/c1/c2 to this color */
  179414. inc0 = (minc0 - GETJSAMPLE(cinfo->colormap[0][icolor])) * C0_SCALE;
  179415. dist0 = inc0*inc0;
  179416. inc1 = (minc1 - GETJSAMPLE(cinfo->colormap[1][icolor])) * C1_SCALE;
  179417. dist0 += inc1*inc1;
  179418. inc2 = (minc2 - GETJSAMPLE(cinfo->colormap[2][icolor])) * C2_SCALE;
  179419. dist0 += inc2*inc2;
  179420. /* Form the initial difference increments */
  179421. inc0 = inc0 * (2 * STEP_C0) + STEP_C0 * STEP_C0;
  179422. inc1 = inc1 * (2 * STEP_C1) + STEP_C1 * STEP_C1;
  179423. inc2 = inc2 * (2 * STEP_C2) + STEP_C2 * STEP_C2;
  179424. /* Now loop over all cells in box, updating distance per Thomas method */
  179425. bptr = bestdist;
  179426. cptr = bestcolor;
  179427. xx0 = inc0;
  179428. for (ic0 = BOX_C0_ELEMS-1; ic0 >= 0; ic0--) {
  179429. dist1 = dist0;
  179430. xx1 = inc1;
  179431. for (ic1 = BOX_C1_ELEMS-1; ic1 >= 0; ic1--) {
  179432. dist2 = dist1;
  179433. xx2 = inc2;
  179434. for (ic2 = BOX_C2_ELEMS-1; ic2 >= 0; ic2--) {
  179435. if (dist2 < *bptr) {
  179436. *bptr = dist2;
  179437. *cptr = (JSAMPLE) icolor;
  179438. }
  179439. dist2 += xx2;
  179440. xx2 += 2 * STEP_C2 * STEP_C2;
  179441. bptr++;
  179442. cptr++;
  179443. }
  179444. dist1 += xx1;
  179445. xx1 += 2 * STEP_C1 * STEP_C1;
  179446. }
  179447. dist0 += xx0;
  179448. xx0 += 2 * STEP_C0 * STEP_C0;
  179449. }
  179450. }
  179451. }
  179452. LOCAL(void)
  179453. fill_inverse_cmap (j_decompress_ptr cinfo, int c0, int c1, int c2)
  179454. /* Fill the inverse-colormap entries in the update box that contains */
  179455. /* histogram cell c0/c1/c2. (Only that one cell MUST be filled, but */
  179456. /* we can fill as many others as we wish.) */
  179457. {
  179458. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  179459. hist3d histogram = cquantize->histogram;
  179460. int minc0, minc1, minc2; /* lower left corner of update box */
  179461. int ic0, ic1, ic2;
  179462. register JSAMPLE * cptr; /* pointer into bestcolor[] array */
  179463. register histptr cachep; /* pointer into main cache array */
  179464. /* This array lists the candidate colormap indexes. */
  179465. JSAMPLE colorlist[MAXNUMCOLORS];
  179466. int numcolors; /* number of candidate colors */
  179467. /* This array holds the actually closest colormap index for each cell. */
  179468. JSAMPLE bestcolor[BOX_C0_ELEMS * BOX_C1_ELEMS * BOX_C2_ELEMS];
  179469. /* Convert cell coordinates to update box ID */
  179470. c0 >>= BOX_C0_LOG;
  179471. c1 >>= BOX_C1_LOG;
  179472. c2 >>= BOX_C2_LOG;
  179473. /* Compute true coordinates of update box's origin corner.
  179474. * Actually we compute the coordinates of the center of the corner
  179475. * histogram cell, which are the lower bounds of the volume we care about.
  179476. */
  179477. minc0 = (c0 << BOX_C0_SHIFT) + ((1 << C0_SHIFT) >> 1);
  179478. minc1 = (c1 << BOX_C1_SHIFT) + ((1 << C1_SHIFT) >> 1);
  179479. minc2 = (c2 << BOX_C2_SHIFT) + ((1 << C2_SHIFT) >> 1);
  179480. /* Determine which colormap entries are close enough to be candidates
  179481. * for the nearest entry to some cell in the update box.
  179482. */
  179483. numcolors = find_nearby_colors(cinfo, minc0, minc1, minc2, colorlist);
  179484. /* Determine the actually nearest colors. */
  179485. find_best_colors(cinfo, minc0, minc1, minc2, numcolors, colorlist,
  179486. bestcolor);
  179487. /* Save the best color numbers (plus 1) in the main cache array */
  179488. c0 <<= BOX_C0_LOG; /* convert ID back to base cell indexes */
  179489. c1 <<= BOX_C1_LOG;
  179490. c2 <<= BOX_C2_LOG;
  179491. cptr = bestcolor;
  179492. for (ic0 = 0; ic0 < BOX_C0_ELEMS; ic0++) {
  179493. for (ic1 = 0; ic1 < BOX_C1_ELEMS; ic1++) {
  179494. cachep = & histogram[c0+ic0][c1+ic1][c2];
  179495. for (ic2 = 0; ic2 < BOX_C2_ELEMS; ic2++) {
  179496. *cachep++ = (histcell) (GETJSAMPLE(*cptr++) + 1);
  179497. }
  179498. }
  179499. }
  179500. }
  179501. /*
  179502. * Map some rows of pixels to the output colormapped representation.
  179503. */
  179504. METHODDEF(void)
  179505. pass2_no_dither (j_decompress_ptr cinfo,
  179506. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  179507. /* This version performs no dithering */
  179508. {
  179509. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  179510. hist3d histogram = cquantize->histogram;
  179511. register JSAMPROW inptr, outptr;
  179512. register histptr cachep;
  179513. register int c0, c1, c2;
  179514. int row;
  179515. JDIMENSION col;
  179516. JDIMENSION width = cinfo->output_width;
  179517. for (row = 0; row < num_rows; row++) {
  179518. inptr = input_buf[row];
  179519. outptr = output_buf[row];
  179520. for (col = width; col > 0; col--) {
  179521. /* get pixel value and index into the cache */
  179522. c0 = GETJSAMPLE(*inptr++) >> C0_SHIFT;
  179523. c1 = GETJSAMPLE(*inptr++) >> C1_SHIFT;
  179524. c2 = GETJSAMPLE(*inptr++) >> C2_SHIFT;
  179525. cachep = & histogram[c0][c1][c2];
  179526. /* If we have not seen this color before, find nearest colormap entry */
  179527. /* and update the cache */
  179528. if (*cachep == 0)
  179529. fill_inverse_cmap(cinfo, c0,c1,c2);
  179530. /* Now emit the colormap index for this cell */
  179531. *outptr++ = (JSAMPLE) (*cachep - 1);
  179532. }
  179533. }
  179534. }
  179535. METHODDEF(void)
  179536. pass2_fs_dither (j_decompress_ptr cinfo,
  179537. JSAMPARRAY input_buf, JSAMPARRAY output_buf, int num_rows)
  179538. /* This version performs Floyd-Steinberg dithering */
  179539. {
  179540. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  179541. hist3d histogram = cquantize->histogram;
  179542. register LOCFSERROR cur0, cur1, cur2; /* current error or pixel value */
  179543. LOCFSERROR belowerr0, belowerr1, belowerr2; /* error for pixel below cur */
  179544. LOCFSERROR bpreverr0, bpreverr1, bpreverr2; /* error for below/prev col */
  179545. register FSERRPTR errorptr; /* => fserrors[] at column before current */
  179546. JSAMPROW inptr; /* => current input pixel */
  179547. JSAMPROW outptr; /* => current output pixel */
  179548. histptr cachep;
  179549. int dir; /* +1 or -1 depending on direction */
  179550. int dir3; /* 3*dir, for advancing inptr & errorptr */
  179551. int row;
  179552. JDIMENSION col;
  179553. JDIMENSION width = cinfo->output_width;
  179554. JSAMPLE *range_limit = cinfo->sample_range_limit;
  179555. int *error_limit = cquantize->error_limiter;
  179556. JSAMPROW colormap0 = cinfo->colormap[0];
  179557. JSAMPROW colormap1 = cinfo->colormap[1];
  179558. JSAMPROW colormap2 = cinfo->colormap[2];
  179559. SHIFT_TEMPS
  179560. for (row = 0; row < num_rows; row++) {
  179561. inptr = input_buf[row];
  179562. outptr = output_buf[row];
  179563. if (cquantize->on_odd_row) {
  179564. /* work right to left in this row */
  179565. inptr += (width-1) * 3; /* so point to rightmost pixel */
  179566. outptr += width-1;
  179567. dir = -1;
  179568. dir3 = -3;
  179569. errorptr = cquantize->fserrors + (width+1)*3; /* => entry after last column */
  179570. cquantize->on_odd_row = FALSE; /* flip for next time */
  179571. } else {
  179572. /* work left to right in this row */
  179573. dir = 1;
  179574. dir3 = 3;
  179575. errorptr = cquantize->fserrors; /* => entry before first real column */
  179576. cquantize->on_odd_row = TRUE; /* flip for next time */
  179577. }
  179578. /* Preset error values: no error propagated to first pixel from left */
  179579. cur0 = cur1 = cur2 = 0;
  179580. /* and no error propagated to row below yet */
  179581. belowerr0 = belowerr1 = belowerr2 = 0;
  179582. bpreverr0 = bpreverr1 = bpreverr2 = 0;
  179583. for (col = width; col > 0; col--) {
  179584. /* curN holds the error propagated from the previous pixel on the
  179585. * current line. Add the error propagated from the previous line
  179586. * to form the complete error correction term for this pixel, and
  179587. * round the error term (which is expressed * 16) to an integer.
  179588. * RIGHT_SHIFT rounds towards minus infinity, so adding 8 is correct
  179589. * for either sign of the error value.
  179590. * Note: errorptr points to *previous* column's array entry.
  179591. */
  179592. cur0 = RIGHT_SHIFT(cur0 + errorptr[dir3+0] + 8, 4);
  179593. cur1 = RIGHT_SHIFT(cur1 + errorptr[dir3+1] + 8, 4);
  179594. cur2 = RIGHT_SHIFT(cur2 + errorptr[dir3+2] + 8, 4);
  179595. /* Limit the error using transfer function set by init_error_limit.
  179596. * See comments with init_error_limit for rationale.
  179597. */
  179598. cur0 = error_limit[cur0];
  179599. cur1 = error_limit[cur1];
  179600. cur2 = error_limit[cur2];
  179601. /* Form pixel value + error, and range-limit to 0..MAXJSAMPLE.
  179602. * The maximum error is +- MAXJSAMPLE (or less with error limiting);
  179603. * this sets the required size of the range_limit array.
  179604. */
  179605. cur0 += GETJSAMPLE(inptr[0]);
  179606. cur1 += GETJSAMPLE(inptr[1]);
  179607. cur2 += GETJSAMPLE(inptr[2]);
  179608. cur0 = GETJSAMPLE(range_limit[cur0]);
  179609. cur1 = GETJSAMPLE(range_limit[cur1]);
  179610. cur2 = GETJSAMPLE(range_limit[cur2]);
  179611. /* Index into the cache with adjusted pixel value */
  179612. cachep = & histogram[cur0>>C0_SHIFT][cur1>>C1_SHIFT][cur2>>C2_SHIFT];
  179613. /* If we have not seen this color before, find nearest colormap */
  179614. /* entry and update the cache */
  179615. if (*cachep == 0)
  179616. fill_inverse_cmap(cinfo, cur0>>C0_SHIFT,cur1>>C1_SHIFT,cur2>>C2_SHIFT);
  179617. /* Now emit the colormap index for this cell */
  179618. { register int pixcode = *cachep - 1;
  179619. *outptr = (JSAMPLE) pixcode;
  179620. /* Compute representation error for this pixel */
  179621. cur0 -= GETJSAMPLE(colormap0[pixcode]);
  179622. cur1 -= GETJSAMPLE(colormap1[pixcode]);
  179623. cur2 -= GETJSAMPLE(colormap2[pixcode]);
  179624. }
  179625. /* Compute error fractions to be propagated to adjacent pixels.
  179626. * Add these into the running sums, and simultaneously shift the
  179627. * next-line error sums left by 1 column.
  179628. */
  179629. { register LOCFSERROR bnexterr, delta;
  179630. bnexterr = cur0; /* Process component 0 */
  179631. delta = cur0 * 2;
  179632. cur0 += delta; /* form error * 3 */
  179633. errorptr[0] = (FSERROR) (bpreverr0 + cur0);
  179634. cur0 += delta; /* form error * 5 */
  179635. bpreverr0 = belowerr0 + cur0;
  179636. belowerr0 = bnexterr;
  179637. cur0 += delta; /* form error * 7 */
  179638. bnexterr = cur1; /* Process component 1 */
  179639. delta = cur1 * 2;
  179640. cur1 += delta; /* form error * 3 */
  179641. errorptr[1] = (FSERROR) (bpreverr1 + cur1);
  179642. cur1 += delta; /* form error * 5 */
  179643. bpreverr1 = belowerr1 + cur1;
  179644. belowerr1 = bnexterr;
  179645. cur1 += delta; /* form error * 7 */
  179646. bnexterr = cur2; /* Process component 2 */
  179647. delta = cur2 * 2;
  179648. cur2 += delta; /* form error * 3 */
  179649. errorptr[2] = (FSERROR) (bpreverr2 + cur2);
  179650. cur2 += delta; /* form error * 5 */
  179651. bpreverr2 = belowerr2 + cur2;
  179652. belowerr2 = bnexterr;
  179653. cur2 += delta; /* form error * 7 */
  179654. }
  179655. /* At this point curN contains the 7/16 error value to be propagated
  179656. * to the next pixel on the current line, and all the errors for the
  179657. * next line have been shifted over. We are therefore ready to move on.
  179658. */
  179659. inptr += dir3; /* Advance pixel pointers to next column */
  179660. outptr += dir;
  179661. errorptr += dir3; /* advance errorptr to current column */
  179662. }
  179663. /* Post-loop cleanup: we must unload the final error values into the
  179664. * final fserrors[] entry. Note we need not unload belowerrN because
  179665. * it is for the dummy column before or after the actual array.
  179666. */
  179667. errorptr[0] = (FSERROR) bpreverr0; /* unload prev errs into array */
  179668. errorptr[1] = (FSERROR) bpreverr1;
  179669. errorptr[2] = (FSERROR) bpreverr2;
  179670. }
  179671. }
  179672. /*
  179673. * Initialize the error-limiting transfer function (lookup table).
  179674. * The raw F-S error computation can potentially compute error values of up to
  179675. * +- MAXJSAMPLE. But we want the maximum correction applied to a pixel to be
  179676. * much less, otherwise obviously wrong pixels will be created. (Typical
  179677. * effects include weird fringes at color-area boundaries, isolated bright
  179678. * pixels in a dark area, etc.) The standard advice for avoiding this problem
  179679. * is to ensure that the "corners" of the color cube are allocated as output
  179680. * colors; then repeated errors in the same direction cannot cause cascading
  179681. * error buildup. However, that only prevents the error from getting
  179682. * completely out of hand; Aaron Giles reports that error limiting improves
  179683. * the results even with corner colors allocated.
  179684. * A simple clamping of the error values to about +- MAXJSAMPLE/8 works pretty
  179685. * well, but the smoother transfer function used below is even better. Thanks
  179686. * to Aaron Giles for this idea.
  179687. */
  179688. LOCAL(void)
  179689. init_error_limit (j_decompress_ptr cinfo)
  179690. /* Allocate and fill in the error_limiter table */
  179691. {
  179692. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  179693. int * table;
  179694. int in, out;
  179695. table = (int *) (*cinfo->mem->alloc_small)
  179696. ((j_common_ptr) cinfo, JPOOL_IMAGE, (MAXJSAMPLE*2+1) * SIZEOF(int));
  179697. table += MAXJSAMPLE; /* so can index -MAXJSAMPLE .. +MAXJSAMPLE */
  179698. cquantize->error_limiter = table;
  179699. #define STEPSIZE ((MAXJSAMPLE+1)/16)
  179700. /* Map errors 1:1 up to +- MAXJSAMPLE/16 */
  179701. out = 0;
  179702. for (in = 0; in < STEPSIZE; in++, out++) {
  179703. table[in] = out; table[-in] = -out;
  179704. }
  179705. /* Map errors 1:2 up to +- 3*MAXJSAMPLE/16 */
  179706. for (; in < STEPSIZE*3; in++, out += (in&1) ? 0 : 1) {
  179707. table[in] = out; table[-in] = -out;
  179708. }
  179709. /* Clamp the rest to final out value (which is (MAXJSAMPLE+1)/8) */
  179710. for (; in <= MAXJSAMPLE; in++) {
  179711. table[in] = out; table[-in] = -out;
  179712. }
  179713. #undef STEPSIZE
  179714. }
  179715. /*
  179716. * Finish up at the end of each pass.
  179717. */
  179718. METHODDEF(void)
  179719. finish_pass1 (j_decompress_ptr cinfo)
  179720. {
  179721. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  179722. /* Select the representative colors and fill in cinfo->colormap */
  179723. cinfo->colormap = cquantize->sv_colormap;
  179724. select_colors(cinfo, cquantize->desired);
  179725. /* Force next pass to zero the color index table */
  179726. cquantize->needs_zeroed = TRUE;
  179727. }
  179728. METHODDEF(void)
  179729. finish_pass2 (j_decompress_ptr cinfo)
  179730. {
  179731. /* no work */
  179732. }
  179733. /*
  179734. * Initialize for each processing pass.
  179735. */
  179736. METHODDEF(void)
  179737. start_pass_2_quant (j_decompress_ptr cinfo, boolean is_pre_scan)
  179738. {
  179739. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  179740. hist3d histogram = cquantize->histogram;
  179741. int i;
  179742. /* Only F-S dithering or no dithering is supported. */
  179743. /* If user asks for ordered dither, give him F-S. */
  179744. if (cinfo->dither_mode != JDITHER_NONE)
  179745. cinfo->dither_mode = JDITHER_FS;
  179746. if (is_pre_scan) {
  179747. /* Set up method pointers */
  179748. cquantize->pub.color_quantize = prescan_quantize;
  179749. cquantize->pub.finish_pass = finish_pass1;
  179750. cquantize->needs_zeroed = TRUE; /* Always zero histogram */
  179751. } else {
  179752. /* Set up method pointers */
  179753. if (cinfo->dither_mode == JDITHER_FS)
  179754. cquantize->pub.color_quantize = pass2_fs_dither;
  179755. else
  179756. cquantize->pub.color_quantize = pass2_no_dither;
  179757. cquantize->pub.finish_pass = finish_pass2;
  179758. /* Make sure color count is acceptable */
  179759. i = cinfo->actual_number_of_colors;
  179760. if (i < 1)
  179761. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 1);
  179762. if (i > MAXNUMCOLORS)
  179763. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  179764. if (cinfo->dither_mode == JDITHER_FS) {
  179765. size_t arraysize = (size_t) ((cinfo->output_width + 2) *
  179766. (3 * SIZEOF(FSERROR)));
  179767. /* Allocate Floyd-Steinberg workspace if we didn't already. */
  179768. if (cquantize->fserrors == NULL)
  179769. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  179770. ((j_common_ptr) cinfo, JPOOL_IMAGE, arraysize);
  179771. /* Initialize the propagated errors to zero. */
  179772. jzero_far((void FAR *) cquantize->fserrors, arraysize);
  179773. /* Make the error-limit table if we didn't already. */
  179774. if (cquantize->error_limiter == NULL)
  179775. init_error_limit(cinfo);
  179776. cquantize->on_odd_row = FALSE;
  179777. }
  179778. }
  179779. /* Zero the histogram or inverse color map, if necessary */
  179780. if (cquantize->needs_zeroed) {
  179781. for (i = 0; i < HIST_C0_ELEMS; i++) {
  179782. jzero_far((void FAR *) histogram[i],
  179783. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  179784. }
  179785. cquantize->needs_zeroed = FALSE;
  179786. }
  179787. }
  179788. /*
  179789. * Switch to a new external colormap between output passes.
  179790. */
  179791. METHODDEF(void)
  179792. new_color_map_2_quant (j_decompress_ptr cinfo)
  179793. {
  179794. my_cquantize_ptr2 cquantize = (my_cquantize_ptr2) cinfo->cquantize;
  179795. /* Reset the inverse color map */
  179796. cquantize->needs_zeroed = TRUE;
  179797. }
  179798. /*
  179799. * Module initialization routine for 2-pass color quantization.
  179800. */
  179801. GLOBAL(void)
  179802. jinit_2pass_quantizer (j_decompress_ptr cinfo)
  179803. {
  179804. my_cquantize_ptr2 cquantize;
  179805. int i;
  179806. cquantize = (my_cquantize_ptr2)
  179807. (*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179808. SIZEOF(my_cquantizer2));
  179809. cinfo->cquantize = (struct jpeg_color_quantizer *) cquantize;
  179810. cquantize->pub.start_pass = start_pass_2_quant;
  179811. cquantize->pub.new_color_map = new_color_map_2_quant;
  179812. cquantize->fserrors = NULL; /* flag optional arrays not allocated */
  179813. cquantize->error_limiter = NULL;
  179814. /* Make sure jdmaster didn't give me a case I can't handle */
  179815. if (cinfo->out_color_components != 3)
  179816. ERREXIT(cinfo, JERR_NOTIMPL);
  179817. /* Allocate the histogram/inverse colormap storage */
  179818. cquantize->histogram = (hist3d) (*cinfo->mem->alloc_small)
  179819. ((j_common_ptr) cinfo, JPOOL_IMAGE, HIST_C0_ELEMS * SIZEOF(hist2d));
  179820. for (i = 0; i < HIST_C0_ELEMS; i++) {
  179821. cquantize->histogram[i] = (hist2d) (*cinfo->mem->alloc_large)
  179822. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179823. HIST_C1_ELEMS*HIST_C2_ELEMS * SIZEOF(histcell));
  179824. }
  179825. cquantize->needs_zeroed = TRUE; /* histogram is garbage now */
  179826. /* Allocate storage for the completed colormap, if required.
  179827. * We do this now since it is FAR storage and may affect
  179828. * the memory manager's space calculations.
  179829. */
  179830. if (cinfo->enable_2pass_quant) {
  179831. /* Make sure color count is acceptable */
  179832. int desired = cinfo->desired_number_of_colors;
  179833. /* Lower bound on # of colors ... somewhat arbitrary as long as > 0 */
  179834. if (desired < 8)
  179835. ERREXIT1(cinfo, JERR_QUANT_FEW_COLORS, 8);
  179836. /* Make sure colormap indexes can be represented by JSAMPLEs */
  179837. if (desired > MAXNUMCOLORS)
  179838. ERREXIT1(cinfo, JERR_QUANT_MANY_COLORS, MAXNUMCOLORS);
  179839. cquantize->sv_colormap = (*cinfo->mem->alloc_sarray)
  179840. ((j_common_ptr) cinfo,JPOOL_IMAGE, (JDIMENSION) desired, (JDIMENSION) 3);
  179841. cquantize->desired = desired;
  179842. } else
  179843. cquantize->sv_colormap = NULL;
  179844. /* Only F-S dithering or no dithering is supported. */
  179845. /* If user asks for ordered dither, give him F-S. */
  179846. if (cinfo->dither_mode != JDITHER_NONE)
  179847. cinfo->dither_mode = JDITHER_FS;
  179848. /* Allocate Floyd-Steinberg workspace if necessary.
  179849. * This isn't really needed until pass 2, but again it is FAR storage.
  179850. * Although we will cope with a later change in dither_mode,
  179851. * we do not promise to honor max_memory_to_use if dither_mode changes.
  179852. */
  179853. if (cinfo->dither_mode == JDITHER_FS) {
  179854. cquantize->fserrors = (FSERRPTR) (*cinfo->mem->alloc_large)
  179855. ((j_common_ptr) cinfo, JPOOL_IMAGE,
  179856. (size_t) ((cinfo->output_width + 2) * (3 * SIZEOF(FSERROR))));
  179857. /* Might as well create the error-limiting table too. */
  179858. init_error_limit(cinfo);
  179859. }
  179860. }
  179861. #endif /* QUANT_2PASS_SUPPORTED */
  179862. /********* End of inlined file: jquant2.c *********/
  179863. /********* Start of inlined file: jutils.c *********/
  179864. #define JPEG_INTERNALS
  179865. /*
  179866. * jpeg_zigzag_order[i] is the zigzag-order position of the i'th element
  179867. * of a DCT block read in natural order (left to right, top to bottom).
  179868. */
  179869. #if 0 /* This table is not actually needed in v6a */
  179870. const int jpeg_zigzag_order[DCTSIZE2] = {
  179871. 0, 1, 5, 6, 14, 15, 27, 28,
  179872. 2, 4, 7, 13, 16, 26, 29, 42,
  179873. 3, 8, 12, 17, 25, 30, 41, 43,
  179874. 9, 11, 18, 24, 31, 40, 44, 53,
  179875. 10, 19, 23, 32, 39, 45, 52, 54,
  179876. 20, 22, 33, 38, 46, 51, 55, 60,
  179877. 21, 34, 37, 47, 50, 56, 59, 61,
  179878. 35, 36, 48, 49, 57, 58, 62, 63
  179879. };
  179880. #endif
  179881. /*
  179882. * jpeg_natural_order[i] is the natural-order position of the i'th element
  179883. * of zigzag order.
  179884. *
  179885. * When reading corrupted data, the Huffman decoders could attempt
  179886. * to reference an entry beyond the end of this array (if the decoded
  179887. * zero run length reaches past the end of the block). To prevent
  179888. * wild stores without adding an inner-loop test, we put some extra
  179889. * "63"s after the real entries. This will cause the extra coefficient
  179890. * to be stored in location 63 of the block, not somewhere random.
  179891. * The worst case would be a run-length of 15, which means we need 16
  179892. * fake entries.
  179893. */
  179894. const int jpeg_natural_order[DCTSIZE2+16] = {
  179895. 0, 1, 8, 16, 9, 2, 3, 10,
  179896. 17, 24, 32, 25, 18, 11, 4, 5,
  179897. 12, 19, 26, 33, 40, 48, 41, 34,
  179898. 27, 20, 13, 6, 7, 14, 21, 28,
  179899. 35, 42, 49, 56, 57, 50, 43, 36,
  179900. 29, 22, 15, 23, 30, 37, 44, 51,
  179901. 58, 59, 52, 45, 38, 31, 39, 46,
  179902. 53, 60, 61, 54, 47, 55, 62, 63,
  179903. 63, 63, 63, 63, 63, 63, 63, 63, /* extra entries for safety in decoder */
  179904. 63, 63, 63, 63, 63, 63, 63, 63
  179905. };
  179906. /*
  179907. * Arithmetic utilities
  179908. */
  179909. GLOBAL(long)
  179910. jdiv_round_up (long a, long b)
  179911. /* Compute a/b rounded up to next integer, ie, ceil(a/b) */
  179912. /* Assumes a >= 0, b > 0 */
  179913. {
  179914. return (a + b - 1L) / b;
  179915. }
  179916. GLOBAL(long)
  179917. jround_up (long a, long b)
  179918. /* Compute a rounded up to next multiple of b, ie, ceil(a/b)*b */
  179919. /* Assumes a >= 0, b > 0 */
  179920. {
  179921. a += b - 1L;
  179922. return a - (a % b);
  179923. }
  179924. /* On normal machines we can apply MEMCOPY() and MEMZERO() to sample arrays
  179925. * and coefficient-block arrays. This won't work on 80x86 because the arrays
  179926. * are FAR and we're assuming a small-pointer memory model. However, some
  179927. * DOS compilers provide far-pointer versions of memcpy() and memset() even
  179928. * in the small-model libraries. These will be used if USE_FMEM is defined.
  179929. * Otherwise, the routines below do it the hard way. (The performance cost
  179930. * is not all that great, because these routines aren't very heavily used.)
  179931. */
  179932. #ifndef NEED_FAR_POINTERS /* normal case, same as regular macros */
  179933. #define FMEMCOPY(dest,src,size) MEMCOPY(dest,src,size)
  179934. #define FMEMZERO(target,size) MEMZERO(target,size)
  179935. #else /* 80x86 case, define if we can */
  179936. #ifdef USE_FMEM
  179937. #define FMEMCOPY(dest,src,size) _fmemcpy((void FAR *)(dest), (const void FAR *)(src), (size_t)(size))
  179938. #define FMEMZERO(target,size) _fmemset((void FAR *)(target), 0, (size_t)(size))
  179939. #endif
  179940. #endif
  179941. GLOBAL(void)
  179942. jcopy_sample_rows (JSAMPARRAY input_array, int source_row,
  179943. JSAMPARRAY output_array, int dest_row,
  179944. int num_rows, JDIMENSION num_cols)
  179945. /* Copy some rows of samples from one place to another.
  179946. * num_rows rows are copied from input_array[source_row++]
  179947. * to output_array[dest_row++]; these areas may overlap for duplication.
  179948. * The source and destination arrays must be at least as wide as num_cols.
  179949. */
  179950. {
  179951. register JSAMPROW inptr, outptr;
  179952. #ifdef FMEMCOPY
  179953. register size_t count = (size_t) (num_cols * SIZEOF(JSAMPLE));
  179954. #else
  179955. register JDIMENSION count;
  179956. #endif
  179957. register int row;
  179958. input_array += source_row;
  179959. output_array += dest_row;
  179960. for (row = num_rows; row > 0; row--) {
  179961. inptr = *input_array++;
  179962. outptr = *output_array++;
  179963. #ifdef FMEMCOPY
  179964. FMEMCOPY(outptr, inptr, count);
  179965. #else
  179966. for (count = num_cols; count > 0; count--)
  179967. *outptr++ = *inptr++; /* needn't bother with GETJSAMPLE() here */
  179968. #endif
  179969. }
  179970. }
  179971. GLOBAL(void)
  179972. jcopy_block_row (JBLOCKROW input_row, JBLOCKROW output_row,
  179973. JDIMENSION num_blocks)
  179974. /* Copy a row of coefficient blocks from one place to another. */
  179975. {
  179976. #ifdef FMEMCOPY
  179977. FMEMCOPY(output_row, input_row, num_blocks * (DCTSIZE2 * SIZEOF(JCOEF)));
  179978. #else
  179979. register JCOEFPTR inptr, outptr;
  179980. register long count;
  179981. inptr = (JCOEFPTR) input_row;
  179982. outptr = (JCOEFPTR) output_row;
  179983. for (count = (long) num_blocks * DCTSIZE2; count > 0; count--) {
  179984. *outptr++ = *inptr++;
  179985. }
  179986. #endif
  179987. }
  179988. GLOBAL(void)
  179989. jzero_far (void FAR * target, size_t bytestozero)
  179990. /* Zero out a chunk of FAR memory. */
  179991. /* This might be sample-array data, block-array data, or alloc_large data. */
  179992. {
  179993. #ifdef FMEMZERO
  179994. FMEMZERO(target, bytestozero);
  179995. #else
  179996. register char FAR * ptr = (char FAR *) target;
  179997. register size_t count;
  179998. for (count = bytestozero; count > 0; count--) {
  179999. *ptr++ = 0;
  180000. }
  180001. #endif
  180002. }
  180003. /********* End of inlined file: jutils.c *********/
  180004. /********* Start of inlined file: transupp.c *********/
  180005. /* Although this file really shouldn't have access to the library internals,
  180006. * it's helpful to let it call jround_up() and jcopy_block_row().
  180007. */
  180008. #define JPEG_INTERNALS
  180009. /********* Start of inlined file: transupp.h *********/
  180010. /* If you happen not to want the image transform support, disable it here */
  180011. #ifndef TRANSFORMS_SUPPORTED
  180012. #define TRANSFORMS_SUPPORTED 1 /* 0 disables transform code */
  180013. #endif
  180014. /* Short forms of external names for systems with brain-damaged linkers. */
  180015. #ifdef NEED_SHORT_EXTERNAL_NAMES
  180016. #define jtransform_request_workspace jTrRequest
  180017. #define jtransform_adjust_parameters jTrAdjust
  180018. #define jtransform_execute_transformation jTrExec
  180019. #define jcopy_markers_setup jCMrkSetup
  180020. #define jcopy_markers_execute jCMrkExec
  180021. #endif /* NEED_SHORT_EXTERNAL_NAMES */
  180022. /*
  180023. * Codes for supported types of image transformations.
  180024. */
  180025. typedef enum {
  180026. JXFORM_NONE, /* no transformation */
  180027. JXFORM_FLIP_H, /* horizontal flip */
  180028. JXFORM_FLIP_V, /* vertical flip */
  180029. JXFORM_TRANSPOSE, /* transpose across UL-to-LR axis */
  180030. JXFORM_TRANSVERSE, /* transpose across UR-to-LL axis */
  180031. JXFORM_ROT_90, /* 90-degree clockwise rotation */
  180032. JXFORM_ROT_180, /* 180-degree rotation */
  180033. JXFORM_ROT_270 /* 270-degree clockwise (or 90 ccw) */
  180034. } JXFORM_CODE;
  180035. /*
  180036. * Although rotating and flipping data expressed as DCT coefficients is not
  180037. * hard, there is an asymmetry in the JPEG format specification for images
  180038. * whose dimensions aren't multiples of the iMCU size. The right and bottom
  180039. * image edges are padded out to the next iMCU boundary with junk data; but
  180040. * no padding is possible at the top and left edges. If we were to flip
  180041. * the whole image including the pad data, then pad garbage would become
  180042. * visible at the top and/or left, and real pixels would disappear into the
  180043. * pad margins --- perhaps permanently, since encoders & decoders may not
  180044. * bother to preserve DCT blocks that appear to be completely outside the
  180045. * nominal image area. So, we have to exclude any partial iMCUs from the
  180046. * basic transformation.
  180047. *
  180048. * Transpose is the only transformation that can handle partial iMCUs at the
  180049. * right and bottom edges completely cleanly. flip_h can flip partial iMCUs
  180050. * at the bottom, but leaves any partial iMCUs at the right edge untouched.
  180051. * Similarly flip_v leaves any partial iMCUs at the bottom edge untouched.
  180052. * The other transforms are defined as combinations of these basic transforms
  180053. * and process edge blocks in a way that preserves the equivalence.
  180054. *
  180055. * The "trim" option causes untransformable partial iMCUs to be dropped;
  180056. * this is not strictly lossless, but it usually gives the best-looking
  180057. * result for odd-size images. Note that when this option is active,
  180058. * the expected mathematical equivalences between the transforms may not hold.
  180059. * (For example, -rot 270 -trim trims only the bottom edge, but -rot 90 -trim
  180060. * followed by -rot 180 -trim trims both edges.)
  180061. *
  180062. * We also offer a "force to grayscale" option, which simply discards the
  180063. * chrominance channels of a YCbCr image. This is lossless in the sense that
  180064. * the luminance channel is preserved exactly. It's not the same kind of
  180065. * thing as the rotate/flip transformations, but it's convenient to handle it
  180066. * as part of this package, mainly because the transformation routines have to
  180067. * be aware of the option to know how many components to work on.
  180068. */
  180069. typedef struct {
  180070. /* Options: set by caller */
  180071. JXFORM_CODE transform; /* image transform operator */
  180072. boolean trim; /* if TRUE, trim partial MCUs as needed */
  180073. boolean force_grayscale; /* if TRUE, convert color image to grayscale */
  180074. /* Internal workspace: caller should not touch these */
  180075. int num_components; /* # of components in workspace */
  180076. jvirt_barray_ptr * workspace_coef_arrays; /* workspace for transformations */
  180077. } jpeg_transform_info;
  180078. #if TRANSFORMS_SUPPORTED
  180079. /* Request any required workspace */
  180080. EXTERN(void) jtransform_request_workspace
  180081. JPP((j_decompress_ptr srcinfo, jpeg_transform_info *info));
  180082. /* Adjust output image parameters */
  180083. EXTERN(jvirt_barray_ptr *) jtransform_adjust_parameters
  180084. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180085. jvirt_barray_ptr *src_coef_arrays,
  180086. jpeg_transform_info *info));
  180087. /* Execute the actual transformation, if any */
  180088. EXTERN(void) jtransform_execute_transformation
  180089. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180090. jvirt_barray_ptr *src_coef_arrays,
  180091. jpeg_transform_info *info));
  180092. #endif /* TRANSFORMS_SUPPORTED */
  180093. /*
  180094. * Support for copying optional markers from source to destination file.
  180095. */
  180096. typedef enum {
  180097. JCOPYOPT_NONE, /* copy no optional markers */
  180098. JCOPYOPT_COMMENTS, /* copy only comment (COM) markers */
  180099. JCOPYOPT_ALL /* copy all optional markers */
  180100. } JCOPY_OPTION;
  180101. #define JCOPYOPT_DEFAULT JCOPYOPT_COMMENTS /* recommended default */
  180102. /* Setup decompression object to save desired markers in memory */
  180103. EXTERN(void) jcopy_markers_setup
  180104. JPP((j_decompress_ptr srcinfo, JCOPY_OPTION option));
  180105. /* Copy markers saved in the given source object to the destination object */
  180106. EXTERN(void) jcopy_markers_execute
  180107. JPP((j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180108. JCOPY_OPTION option));
  180109. /********* End of inlined file: transupp.h *********/
  180110. /* My own external interface */
  180111. #if TRANSFORMS_SUPPORTED
  180112. /*
  180113. * Lossless image transformation routines. These routines work on DCT
  180114. * coefficient arrays and thus do not require any lossy decompression
  180115. * or recompression of the image.
  180116. * Thanks to Guido Vollbeding for the initial design and code of this feature.
  180117. *
  180118. * Horizontal flipping is done in-place, using a single top-to-bottom
  180119. * pass through the virtual source array. It will thus be much the
  180120. * fastest option for images larger than main memory.
  180121. *
  180122. * The other routines require a set of destination virtual arrays, so they
  180123. * need twice as much memory as jpegtran normally does. The destination
  180124. * arrays are always written in normal scan order (top to bottom) because
  180125. * the virtual array manager expects this. The source arrays will be scanned
  180126. * in the corresponding order, which means multiple passes through the source
  180127. * arrays for most of the transforms. That could result in much thrashing
  180128. * if the image is larger than main memory.
  180129. *
  180130. * Some notes about the operating environment of the individual transform
  180131. * routines:
  180132. * 1. Both the source and destination virtual arrays are allocated from the
  180133. * source JPEG object, and therefore should be manipulated by calling the
  180134. * source's memory manager.
  180135. * 2. The destination's component count should be used. It may be smaller
  180136. * than the source's when forcing to grayscale.
  180137. * 3. Likewise the destination's sampling factors should be used. When
  180138. * forcing to grayscale the destination's sampling factors will be all 1,
  180139. * and we may as well take that as the effective iMCU size.
  180140. * 4. When "trim" is in effect, the destination's dimensions will be the
  180141. * trimmed values but the source's will be untrimmed.
  180142. * 5. All the routines assume that the source and destination buffers are
  180143. * padded out to a full iMCU boundary. This is true, although for the
  180144. * source buffer it is an undocumented property of jdcoefct.c.
  180145. * Notes 2,3,4 boil down to this: generally we should use the destination's
  180146. * dimensions and ignore the source's.
  180147. */
  180148. LOCAL(void)
  180149. do_flip_h (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180150. jvirt_barray_ptr *src_coef_arrays)
  180151. /* Horizontal flip; done in-place, so no separate dest array is required */
  180152. {
  180153. JDIMENSION MCU_cols, comp_width, blk_x, blk_y;
  180154. int ci, k, offset_y;
  180155. JBLOCKARRAY buffer;
  180156. JCOEFPTR ptr1, ptr2;
  180157. JCOEF temp1, temp2;
  180158. jpeg_component_info *compptr;
  180159. /* Horizontal mirroring of DCT blocks is accomplished by swapping
  180160. * pairs of blocks in-place. Within a DCT block, we perform horizontal
  180161. * mirroring by changing the signs of odd-numbered columns.
  180162. * Partial iMCUs at the right edge are left untouched.
  180163. */
  180164. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  180165. for (ci = 0; ci < dstinfo->num_components; ci++) {
  180166. compptr = dstinfo->comp_info + ci;
  180167. comp_width = MCU_cols * compptr->h_samp_factor;
  180168. for (blk_y = 0; blk_y < compptr->height_in_blocks;
  180169. blk_y += compptr->v_samp_factor) {
  180170. buffer = (*srcinfo->mem->access_virt_barray)
  180171. ((j_common_ptr) srcinfo, src_coef_arrays[ci], blk_y,
  180172. (JDIMENSION) compptr->v_samp_factor, TRUE);
  180173. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  180174. for (blk_x = 0; blk_x * 2 < comp_width; blk_x++) {
  180175. ptr1 = buffer[offset_y][blk_x];
  180176. ptr2 = buffer[offset_y][comp_width - blk_x - 1];
  180177. /* this unrolled loop doesn't need to know which row it's on... */
  180178. for (k = 0; k < DCTSIZE2; k += 2) {
  180179. temp1 = *ptr1; /* swap even column */
  180180. temp2 = *ptr2;
  180181. *ptr1++ = temp2;
  180182. *ptr2++ = temp1;
  180183. temp1 = *ptr1; /* swap odd column with sign change */
  180184. temp2 = *ptr2;
  180185. *ptr1++ = -temp2;
  180186. *ptr2++ = -temp1;
  180187. }
  180188. }
  180189. }
  180190. }
  180191. }
  180192. }
  180193. LOCAL(void)
  180194. do_flip_v (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180195. jvirt_barray_ptr *src_coef_arrays,
  180196. jvirt_barray_ptr *dst_coef_arrays)
  180197. /* Vertical flip */
  180198. {
  180199. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  180200. int ci, i, j, offset_y;
  180201. JBLOCKARRAY src_buffer, dst_buffer;
  180202. JBLOCKROW src_row_ptr, dst_row_ptr;
  180203. JCOEFPTR src_ptr, dst_ptr;
  180204. jpeg_component_info *compptr;
  180205. /* We output into a separate array because we can't touch different
  180206. * rows of the source virtual array simultaneously. Otherwise, this
  180207. * is a pretty straightforward analog of horizontal flip.
  180208. * Within a DCT block, vertical mirroring is done by changing the signs
  180209. * of odd-numbered rows.
  180210. * Partial iMCUs at the bottom edge are copied verbatim.
  180211. */
  180212. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  180213. for (ci = 0; ci < dstinfo->num_components; ci++) {
  180214. compptr = dstinfo->comp_info + ci;
  180215. comp_height = MCU_rows * compptr->v_samp_factor;
  180216. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  180217. dst_blk_y += compptr->v_samp_factor) {
  180218. dst_buffer = (*srcinfo->mem->access_virt_barray)
  180219. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  180220. (JDIMENSION) compptr->v_samp_factor, TRUE);
  180221. if (dst_blk_y < comp_height) {
  180222. /* Row is within the mirrorable area. */
  180223. src_buffer = (*srcinfo->mem->access_virt_barray)
  180224. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  180225. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  180226. (JDIMENSION) compptr->v_samp_factor, FALSE);
  180227. } else {
  180228. /* Bottom-edge blocks will be copied verbatim. */
  180229. src_buffer = (*srcinfo->mem->access_virt_barray)
  180230. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  180231. (JDIMENSION) compptr->v_samp_factor, FALSE);
  180232. }
  180233. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  180234. if (dst_blk_y < comp_height) {
  180235. /* Row is within the mirrorable area. */
  180236. dst_row_ptr = dst_buffer[offset_y];
  180237. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  180238. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  180239. dst_blk_x++) {
  180240. dst_ptr = dst_row_ptr[dst_blk_x];
  180241. src_ptr = src_row_ptr[dst_blk_x];
  180242. for (i = 0; i < DCTSIZE; i += 2) {
  180243. /* copy even row */
  180244. for (j = 0; j < DCTSIZE; j++)
  180245. *dst_ptr++ = *src_ptr++;
  180246. /* copy odd row with sign change */
  180247. for (j = 0; j < DCTSIZE; j++)
  180248. *dst_ptr++ = - *src_ptr++;
  180249. }
  180250. }
  180251. } else {
  180252. /* Just copy row verbatim. */
  180253. jcopy_block_row(src_buffer[offset_y], dst_buffer[offset_y],
  180254. compptr->width_in_blocks);
  180255. }
  180256. }
  180257. }
  180258. }
  180259. }
  180260. LOCAL(void)
  180261. do_transpose (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180262. jvirt_barray_ptr *src_coef_arrays,
  180263. jvirt_barray_ptr *dst_coef_arrays)
  180264. /* Transpose source into destination */
  180265. {
  180266. JDIMENSION dst_blk_x, dst_blk_y;
  180267. int ci, i, j, offset_x, offset_y;
  180268. JBLOCKARRAY src_buffer, dst_buffer;
  180269. JCOEFPTR src_ptr, dst_ptr;
  180270. jpeg_component_info *compptr;
  180271. /* Transposing pixels within a block just requires transposing the
  180272. * DCT coefficients.
  180273. * Partial iMCUs at the edges require no special treatment; we simply
  180274. * process all the available DCT blocks for every component.
  180275. */
  180276. for (ci = 0; ci < dstinfo->num_components; ci++) {
  180277. compptr = dstinfo->comp_info + ci;
  180278. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  180279. dst_blk_y += compptr->v_samp_factor) {
  180280. dst_buffer = (*srcinfo->mem->access_virt_barray)
  180281. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  180282. (JDIMENSION) compptr->v_samp_factor, TRUE);
  180283. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  180284. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  180285. dst_blk_x += compptr->h_samp_factor) {
  180286. src_buffer = (*srcinfo->mem->access_virt_barray)
  180287. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  180288. (JDIMENSION) compptr->h_samp_factor, FALSE);
  180289. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  180290. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  180291. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  180292. for (i = 0; i < DCTSIZE; i++)
  180293. for (j = 0; j < DCTSIZE; j++)
  180294. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  180295. }
  180296. }
  180297. }
  180298. }
  180299. }
  180300. }
  180301. LOCAL(void)
  180302. do_rot_90 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180303. jvirt_barray_ptr *src_coef_arrays,
  180304. jvirt_barray_ptr *dst_coef_arrays)
  180305. /* 90 degree rotation is equivalent to
  180306. * 1. Transposing the image;
  180307. * 2. Horizontal mirroring.
  180308. * These two steps are merged into a single processing routine.
  180309. */
  180310. {
  180311. JDIMENSION MCU_cols, comp_width, dst_blk_x, dst_blk_y;
  180312. int ci, i, j, offset_x, offset_y;
  180313. JBLOCKARRAY src_buffer, dst_buffer;
  180314. JCOEFPTR src_ptr, dst_ptr;
  180315. jpeg_component_info *compptr;
  180316. /* Because of the horizontal mirror step, we can't process partial iMCUs
  180317. * at the (output) right edge properly. They just get transposed and
  180318. * not mirrored.
  180319. */
  180320. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  180321. for (ci = 0; ci < dstinfo->num_components; ci++) {
  180322. compptr = dstinfo->comp_info + ci;
  180323. comp_width = MCU_cols * compptr->h_samp_factor;
  180324. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  180325. dst_blk_y += compptr->v_samp_factor) {
  180326. dst_buffer = (*srcinfo->mem->access_virt_barray)
  180327. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  180328. (JDIMENSION) compptr->v_samp_factor, TRUE);
  180329. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  180330. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  180331. dst_blk_x += compptr->h_samp_factor) {
  180332. src_buffer = (*srcinfo->mem->access_virt_barray)
  180333. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  180334. (JDIMENSION) compptr->h_samp_factor, FALSE);
  180335. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  180336. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  180337. if (dst_blk_x < comp_width) {
  180338. /* Block is within the mirrorable area. */
  180339. dst_ptr = dst_buffer[offset_y]
  180340. [comp_width - dst_blk_x - offset_x - 1];
  180341. for (i = 0; i < DCTSIZE; i++) {
  180342. for (j = 0; j < DCTSIZE; j++)
  180343. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  180344. i++;
  180345. for (j = 0; j < DCTSIZE; j++)
  180346. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  180347. }
  180348. } else {
  180349. /* Edge blocks are transposed but not mirrored. */
  180350. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  180351. for (i = 0; i < DCTSIZE; i++)
  180352. for (j = 0; j < DCTSIZE; j++)
  180353. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  180354. }
  180355. }
  180356. }
  180357. }
  180358. }
  180359. }
  180360. }
  180361. LOCAL(void)
  180362. do_rot_270 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180363. jvirt_barray_ptr *src_coef_arrays,
  180364. jvirt_barray_ptr *dst_coef_arrays)
  180365. /* 270 degree rotation is equivalent to
  180366. * 1. Horizontal mirroring;
  180367. * 2. Transposing the image.
  180368. * These two steps are merged into a single processing routine.
  180369. */
  180370. {
  180371. JDIMENSION MCU_rows, comp_height, dst_blk_x, dst_blk_y;
  180372. int ci, i, j, offset_x, offset_y;
  180373. JBLOCKARRAY src_buffer, dst_buffer;
  180374. JCOEFPTR src_ptr, dst_ptr;
  180375. jpeg_component_info *compptr;
  180376. /* Because of the horizontal mirror step, we can't process partial iMCUs
  180377. * at the (output) bottom edge properly. They just get transposed and
  180378. * not mirrored.
  180379. */
  180380. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  180381. for (ci = 0; ci < dstinfo->num_components; ci++) {
  180382. compptr = dstinfo->comp_info + ci;
  180383. comp_height = MCU_rows * compptr->v_samp_factor;
  180384. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  180385. dst_blk_y += compptr->v_samp_factor) {
  180386. dst_buffer = (*srcinfo->mem->access_virt_barray)
  180387. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  180388. (JDIMENSION) compptr->v_samp_factor, TRUE);
  180389. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  180390. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  180391. dst_blk_x += compptr->h_samp_factor) {
  180392. src_buffer = (*srcinfo->mem->access_virt_barray)
  180393. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  180394. (JDIMENSION) compptr->h_samp_factor, FALSE);
  180395. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  180396. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  180397. if (dst_blk_y < comp_height) {
  180398. /* Block is within the mirrorable area. */
  180399. src_ptr = src_buffer[offset_x]
  180400. [comp_height - dst_blk_y - offset_y - 1];
  180401. for (i = 0; i < DCTSIZE; i++) {
  180402. for (j = 0; j < DCTSIZE; j++) {
  180403. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  180404. j++;
  180405. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  180406. }
  180407. }
  180408. } else {
  180409. /* Edge blocks are transposed but not mirrored. */
  180410. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  180411. for (i = 0; i < DCTSIZE; i++)
  180412. for (j = 0; j < DCTSIZE; j++)
  180413. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  180414. }
  180415. }
  180416. }
  180417. }
  180418. }
  180419. }
  180420. }
  180421. LOCAL(void)
  180422. do_rot_180 (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180423. jvirt_barray_ptr *src_coef_arrays,
  180424. jvirt_barray_ptr *dst_coef_arrays)
  180425. /* 180 degree rotation is equivalent to
  180426. * 1. Vertical mirroring;
  180427. * 2. Horizontal mirroring.
  180428. * These two steps are merged into a single processing routine.
  180429. */
  180430. {
  180431. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  180432. int ci, i, j, offset_y;
  180433. JBLOCKARRAY src_buffer, dst_buffer;
  180434. JBLOCKROW src_row_ptr, dst_row_ptr;
  180435. JCOEFPTR src_ptr, dst_ptr;
  180436. jpeg_component_info *compptr;
  180437. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  180438. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  180439. for (ci = 0; ci < dstinfo->num_components; ci++) {
  180440. compptr = dstinfo->comp_info + ci;
  180441. comp_width = MCU_cols * compptr->h_samp_factor;
  180442. comp_height = MCU_rows * compptr->v_samp_factor;
  180443. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  180444. dst_blk_y += compptr->v_samp_factor) {
  180445. dst_buffer = (*srcinfo->mem->access_virt_barray)
  180446. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  180447. (JDIMENSION) compptr->v_samp_factor, TRUE);
  180448. if (dst_blk_y < comp_height) {
  180449. /* Row is within the vertically mirrorable area. */
  180450. src_buffer = (*srcinfo->mem->access_virt_barray)
  180451. ((j_common_ptr) srcinfo, src_coef_arrays[ci],
  180452. comp_height - dst_blk_y - (JDIMENSION) compptr->v_samp_factor,
  180453. (JDIMENSION) compptr->v_samp_factor, FALSE);
  180454. } else {
  180455. /* Bottom-edge rows are only mirrored horizontally. */
  180456. src_buffer = (*srcinfo->mem->access_virt_barray)
  180457. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_y,
  180458. (JDIMENSION) compptr->v_samp_factor, FALSE);
  180459. }
  180460. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  180461. if (dst_blk_y < comp_height) {
  180462. /* Row is within the mirrorable area. */
  180463. dst_row_ptr = dst_buffer[offset_y];
  180464. src_row_ptr = src_buffer[compptr->v_samp_factor - offset_y - 1];
  180465. /* Process the blocks that can be mirrored both ways. */
  180466. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  180467. dst_ptr = dst_row_ptr[dst_blk_x];
  180468. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  180469. for (i = 0; i < DCTSIZE; i += 2) {
  180470. /* For even row, negate every odd column. */
  180471. for (j = 0; j < DCTSIZE; j += 2) {
  180472. *dst_ptr++ = *src_ptr++;
  180473. *dst_ptr++ = - *src_ptr++;
  180474. }
  180475. /* For odd row, negate every even column. */
  180476. for (j = 0; j < DCTSIZE; j += 2) {
  180477. *dst_ptr++ = - *src_ptr++;
  180478. *dst_ptr++ = *src_ptr++;
  180479. }
  180480. }
  180481. }
  180482. /* Any remaining right-edge blocks are only mirrored vertically. */
  180483. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  180484. dst_ptr = dst_row_ptr[dst_blk_x];
  180485. src_ptr = src_row_ptr[dst_blk_x];
  180486. for (i = 0; i < DCTSIZE; i += 2) {
  180487. for (j = 0; j < DCTSIZE; j++)
  180488. *dst_ptr++ = *src_ptr++;
  180489. for (j = 0; j < DCTSIZE; j++)
  180490. *dst_ptr++ = - *src_ptr++;
  180491. }
  180492. }
  180493. } else {
  180494. /* Remaining rows are just mirrored horizontally. */
  180495. dst_row_ptr = dst_buffer[offset_y];
  180496. src_row_ptr = src_buffer[offset_y];
  180497. /* Process the blocks that can be mirrored. */
  180498. for (dst_blk_x = 0; dst_blk_x < comp_width; dst_blk_x++) {
  180499. dst_ptr = dst_row_ptr[dst_blk_x];
  180500. src_ptr = src_row_ptr[comp_width - dst_blk_x - 1];
  180501. for (i = 0; i < DCTSIZE2; i += 2) {
  180502. *dst_ptr++ = *src_ptr++;
  180503. *dst_ptr++ = - *src_ptr++;
  180504. }
  180505. }
  180506. /* Any remaining right-edge blocks are only copied. */
  180507. for (; dst_blk_x < compptr->width_in_blocks; dst_blk_x++) {
  180508. dst_ptr = dst_row_ptr[dst_blk_x];
  180509. src_ptr = src_row_ptr[dst_blk_x];
  180510. for (i = 0; i < DCTSIZE2; i++)
  180511. *dst_ptr++ = *src_ptr++;
  180512. }
  180513. }
  180514. }
  180515. }
  180516. }
  180517. }
  180518. LOCAL(void)
  180519. do_transverse (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180520. jvirt_barray_ptr *src_coef_arrays,
  180521. jvirt_barray_ptr *dst_coef_arrays)
  180522. /* Transverse transpose is equivalent to
  180523. * 1. 180 degree rotation;
  180524. * 2. Transposition;
  180525. * or
  180526. * 1. Horizontal mirroring;
  180527. * 2. Transposition;
  180528. * 3. Horizontal mirroring.
  180529. * These steps are merged into a single processing routine.
  180530. */
  180531. {
  180532. JDIMENSION MCU_cols, MCU_rows, comp_width, comp_height, dst_blk_x, dst_blk_y;
  180533. int ci, i, j, offset_x, offset_y;
  180534. JBLOCKARRAY src_buffer, dst_buffer;
  180535. JCOEFPTR src_ptr, dst_ptr;
  180536. jpeg_component_info *compptr;
  180537. MCU_cols = dstinfo->image_width / (dstinfo->max_h_samp_factor * DCTSIZE);
  180538. MCU_rows = dstinfo->image_height / (dstinfo->max_v_samp_factor * DCTSIZE);
  180539. for (ci = 0; ci < dstinfo->num_components; ci++) {
  180540. compptr = dstinfo->comp_info + ci;
  180541. comp_width = MCU_cols * compptr->h_samp_factor;
  180542. comp_height = MCU_rows * compptr->v_samp_factor;
  180543. for (dst_blk_y = 0; dst_blk_y < compptr->height_in_blocks;
  180544. dst_blk_y += compptr->v_samp_factor) {
  180545. dst_buffer = (*srcinfo->mem->access_virt_barray)
  180546. ((j_common_ptr) srcinfo, dst_coef_arrays[ci], dst_blk_y,
  180547. (JDIMENSION) compptr->v_samp_factor, TRUE);
  180548. for (offset_y = 0; offset_y < compptr->v_samp_factor; offset_y++) {
  180549. for (dst_blk_x = 0; dst_blk_x < compptr->width_in_blocks;
  180550. dst_blk_x += compptr->h_samp_factor) {
  180551. src_buffer = (*srcinfo->mem->access_virt_barray)
  180552. ((j_common_ptr) srcinfo, src_coef_arrays[ci], dst_blk_x,
  180553. (JDIMENSION) compptr->h_samp_factor, FALSE);
  180554. for (offset_x = 0; offset_x < compptr->h_samp_factor; offset_x++) {
  180555. if (dst_blk_y < comp_height) {
  180556. src_ptr = src_buffer[offset_x]
  180557. [comp_height - dst_blk_y - offset_y - 1];
  180558. if (dst_blk_x < comp_width) {
  180559. /* Block is within the mirrorable area. */
  180560. dst_ptr = dst_buffer[offset_y]
  180561. [comp_width - dst_blk_x - offset_x - 1];
  180562. for (i = 0; i < DCTSIZE; i++) {
  180563. for (j = 0; j < DCTSIZE; j++) {
  180564. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  180565. j++;
  180566. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  180567. }
  180568. i++;
  180569. for (j = 0; j < DCTSIZE; j++) {
  180570. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  180571. j++;
  180572. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  180573. }
  180574. }
  180575. } else {
  180576. /* Right-edge blocks are mirrored in y only */
  180577. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  180578. for (i = 0; i < DCTSIZE; i++) {
  180579. for (j = 0; j < DCTSIZE; j++) {
  180580. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  180581. j++;
  180582. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  180583. }
  180584. }
  180585. }
  180586. } else {
  180587. src_ptr = src_buffer[offset_x][dst_blk_y + offset_y];
  180588. if (dst_blk_x < comp_width) {
  180589. /* Bottom-edge blocks are mirrored in x only */
  180590. dst_ptr = dst_buffer[offset_y]
  180591. [comp_width - dst_blk_x - offset_x - 1];
  180592. for (i = 0; i < DCTSIZE; i++) {
  180593. for (j = 0; j < DCTSIZE; j++)
  180594. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  180595. i++;
  180596. for (j = 0; j < DCTSIZE; j++)
  180597. dst_ptr[j*DCTSIZE+i] = -src_ptr[i*DCTSIZE+j];
  180598. }
  180599. } else {
  180600. /* At lower right corner, just transpose, no mirroring */
  180601. dst_ptr = dst_buffer[offset_y][dst_blk_x + offset_x];
  180602. for (i = 0; i < DCTSIZE; i++)
  180603. for (j = 0; j < DCTSIZE; j++)
  180604. dst_ptr[j*DCTSIZE+i] = src_ptr[i*DCTSIZE+j];
  180605. }
  180606. }
  180607. }
  180608. }
  180609. }
  180610. }
  180611. }
  180612. }
  180613. /* Request any required workspace.
  180614. *
  180615. * We allocate the workspace virtual arrays from the source decompression
  180616. * object, so that all the arrays (both the original data and the workspace)
  180617. * will be taken into account while making memory management decisions.
  180618. * Hence, this routine must be called after jpeg_read_header (which reads
  180619. * the image dimensions) and before jpeg_read_coefficients (which realizes
  180620. * the source's virtual arrays).
  180621. */
  180622. GLOBAL(void)
  180623. jtransform_request_workspace (j_decompress_ptr srcinfo,
  180624. jpeg_transform_info *info)
  180625. {
  180626. jvirt_barray_ptr *coef_arrays = NULL;
  180627. jpeg_component_info *compptr;
  180628. int ci;
  180629. if (info->force_grayscale &&
  180630. srcinfo->jpeg_color_space == JCS_YCbCr &&
  180631. srcinfo->num_components == 3) {
  180632. /* We'll only process the first component */
  180633. info->num_components = 1;
  180634. } else {
  180635. /* Process all the components */
  180636. info->num_components = srcinfo->num_components;
  180637. }
  180638. switch (info->transform) {
  180639. case JXFORM_NONE:
  180640. case JXFORM_FLIP_H:
  180641. /* Don't need a workspace array */
  180642. break;
  180643. case JXFORM_FLIP_V:
  180644. case JXFORM_ROT_180:
  180645. /* Need workspace arrays having same dimensions as source image.
  180646. * Note that we allocate arrays padded out to the next iMCU boundary,
  180647. * so that transform routines need not worry about missing edge blocks.
  180648. */
  180649. coef_arrays = (jvirt_barray_ptr *)
  180650. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  180651. SIZEOF(jvirt_barray_ptr) * info->num_components);
  180652. for (ci = 0; ci < info->num_components; ci++) {
  180653. compptr = srcinfo->comp_info + ci;
  180654. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  180655. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  180656. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  180657. (long) compptr->h_samp_factor),
  180658. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  180659. (long) compptr->v_samp_factor),
  180660. (JDIMENSION) compptr->v_samp_factor);
  180661. }
  180662. break;
  180663. case JXFORM_TRANSPOSE:
  180664. case JXFORM_TRANSVERSE:
  180665. case JXFORM_ROT_90:
  180666. case JXFORM_ROT_270:
  180667. /* Need workspace arrays having transposed dimensions.
  180668. * Note that we allocate arrays padded out to the next iMCU boundary,
  180669. * so that transform routines need not worry about missing edge blocks.
  180670. */
  180671. coef_arrays = (jvirt_barray_ptr *)
  180672. (*srcinfo->mem->alloc_small) ((j_common_ptr) srcinfo, JPOOL_IMAGE,
  180673. SIZEOF(jvirt_barray_ptr) * info->num_components);
  180674. for (ci = 0; ci < info->num_components; ci++) {
  180675. compptr = srcinfo->comp_info + ci;
  180676. coef_arrays[ci] = (*srcinfo->mem->request_virt_barray)
  180677. ((j_common_ptr) srcinfo, JPOOL_IMAGE, FALSE,
  180678. (JDIMENSION) jround_up((long) compptr->height_in_blocks,
  180679. (long) compptr->v_samp_factor),
  180680. (JDIMENSION) jround_up((long) compptr->width_in_blocks,
  180681. (long) compptr->h_samp_factor),
  180682. (JDIMENSION) compptr->h_samp_factor);
  180683. }
  180684. break;
  180685. }
  180686. info->workspace_coef_arrays = coef_arrays;
  180687. }
  180688. /* Transpose destination image parameters */
  180689. LOCAL(void)
  180690. transpose_critical_parameters (j_compress_ptr dstinfo)
  180691. {
  180692. int tblno, i, j, ci, itemp;
  180693. jpeg_component_info *compptr;
  180694. JQUANT_TBL *qtblptr;
  180695. JDIMENSION dtemp;
  180696. UINT16 qtemp;
  180697. /* Transpose basic image dimensions */
  180698. dtemp = dstinfo->image_width;
  180699. dstinfo->image_width = dstinfo->image_height;
  180700. dstinfo->image_height = dtemp;
  180701. /* Transpose sampling factors */
  180702. for (ci = 0; ci < dstinfo->num_components; ci++) {
  180703. compptr = dstinfo->comp_info + ci;
  180704. itemp = compptr->h_samp_factor;
  180705. compptr->h_samp_factor = compptr->v_samp_factor;
  180706. compptr->v_samp_factor = itemp;
  180707. }
  180708. /* Transpose quantization tables */
  180709. for (tblno = 0; tblno < NUM_QUANT_TBLS; tblno++) {
  180710. qtblptr = dstinfo->quant_tbl_ptrs[tblno];
  180711. if (qtblptr != NULL) {
  180712. for (i = 0; i < DCTSIZE; i++) {
  180713. for (j = 0; j < i; j++) {
  180714. qtemp = qtblptr->quantval[i*DCTSIZE+j];
  180715. qtblptr->quantval[i*DCTSIZE+j] = qtblptr->quantval[j*DCTSIZE+i];
  180716. qtblptr->quantval[j*DCTSIZE+i] = qtemp;
  180717. }
  180718. }
  180719. }
  180720. }
  180721. }
  180722. /* Trim off any partial iMCUs on the indicated destination edge */
  180723. LOCAL(void)
  180724. trim_right_edge (j_compress_ptr dstinfo)
  180725. {
  180726. int ci, max_h_samp_factor;
  180727. JDIMENSION MCU_cols;
  180728. /* We have to compute max_h_samp_factor ourselves,
  180729. * because it hasn't been set yet in the destination
  180730. * (and we don't want to use the source's value).
  180731. */
  180732. max_h_samp_factor = 1;
  180733. for (ci = 0; ci < dstinfo->num_components; ci++) {
  180734. int h_samp_factor = dstinfo->comp_info[ci].h_samp_factor;
  180735. max_h_samp_factor = MAX(max_h_samp_factor, h_samp_factor);
  180736. }
  180737. MCU_cols = dstinfo->image_width / (max_h_samp_factor * DCTSIZE);
  180738. if (MCU_cols > 0) /* can't trim to 0 pixels */
  180739. dstinfo->image_width = MCU_cols * (max_h_samp_factor * DCTSIZE);
  180740. }
  180741. LOCAL(void)
  180742. trim_bottom_edge (j_compress_ptr dstinfo)
  180743. {
  180744. int ci, max_v_samp_factor;
  180745. JDIMENSION MCU_rows;
  180746. /* We have to compute max_v_samp_factor ourselves,
  180747. * because it hasn't been set yet in the destination
  180748. * (and we don't want to use the source's value).
  180749. */
  180750. max_v_samp_factor = 1;
  180751. for (ci = 0; ci < dstinfo->num_components; ci++) {
  180752. int v_samp_factor = dstinfo->comp_info[ci].v_samp_factor;
  180753. max_v_samp_factor = MAX(max_v_samp_factor, v_samp_factor);
  180754. }
  180755. MCU_rows = dstinfo->image_height / (max_v_samp_factor * DCTSIZE);
  180756. if (MCU_rows > 0) /* can't trim to 0 pixels */
  180757. dstinfo->image_height = MCU_rows * (max_v_samp_factor * DCTSIZE);
  180758. }
  180759. /* Adjust output image parameters as needed.
  180760. *
  180761. * This must be called after jpeg_copy_critical_parameters()
  180762. * and before jpeg_write_coefficients().
  180763. *
  180764. * The return value is the set of virtual coefficient arrays to be written
  180765. * (either the ones allocated by jtransform_request_workspace, or the
  180766. * original source data arrays). The caller will need to pass this value
  180767. * to jpeg_write_coefficients().
  180768. */
  180769. GLOBAL(jvirt_barray_ptr *)
  180770. jtransform_adjust_parameters (j_decompress_ptr srcinfo,
  180771. j_compress_ptr dstinfo,
  180772. jvirt_barray_ptr *src_coef_arrays,
  180773. jpeg_transform_info *info)
  180774. {
  180775. /* If force-to-grayscale is requested, adjust destination parameters */
  180776. if (info->force_grayscale) {
  180777. /* We use jpeg_set_colorspace to make sure subsidiary settings get fixed
  180778. * properly. Among other things, the target h_samp_factor & v_samp_factor
  180779. * will get set to 1, which typically won't match the source.
  180780. * In fact we do this even if the source is already grayscale; that
  180781. * provides an easy way of coercing a grayscale JPEG with funny sampling
  180782. * factors to the customary 1,1. (Some decoders fail on other factors.)
  180783. */
  180784. if ((dstinfo->jpeg_color_space == JCS_YCbCr &&
  180785. dstinfo->num_components == 3) ||
  180786. (dstinfo->jpeg_color_space == JCS_GRAYSCALE &&
  180787. dstinfo->num_components == 1)) {
  180788. /* We have to preserve the source's quantization table number. */
  180789. int sv_quant_tbl_no = dstinfo->comp_info[0].quant_tbl_no;
  180790. jpeg_set_colorspace(dstinfo, JCS_GRAYSCALE);
  180791. dstinfo->comp_info[0].quant_tbl_no = sv_quant_tbl_no;
  180792. } else {
  180793. /* Sorry, can't do it */
  180794. ERREXIT(dstinfo, JERR_CONVERSION_NOTIMPL);
  180795. }
  180796. }
  180797. /* Correct the destination's image dimensions etc if necessary */
  180798. switch (info->transform) {
  180799. case JXFORM_NONE:
  180800. /* Nothing to do */
  180801. break;
  180802. case JXFORM_FLIP_H:
  180803. if (info->trim)
  180804. trim_right_edge(dstinfo);
  180805. break;
  180806. case JXFORM_FLIP_V:
  180807. if (info->trim)
  180808. trim_bottom_edge(dstinfo);
  180809. break;
  180810. case JXFORM_TRANSPOSE:
  180811. transpose_critical_parameters(dstinfo);
  180812. /* transpose does NOT have to trim anything */
  180813. break;
  180814. case JXFORM_TRANSVERSE:
  180815. transpose_critical_parameters(dstinfo);
  180816. if (info->trim) {
  180817. trim_right_edge(dstinfo);
  180818. trim_bottom_edge(dstinfo);
  180819. }
  180820. break;
  180821. case JXFORM_ROT_90:
  180822. transpose_critical_parameters(dstinfo);
  180823. if (info->trim)
  180824. trim_right_edge(dstinfo);
  180825. break;
  180826. case JXFORM_ROT_180:
  180827. if (info->trim) {
  180828. trim_right_edge(dstinfo);
  180829. trim_bottom_edge(dstinfo);
  180830. }
  180831. break;
  180832. case JXFORM_ROT_270:
  180833. transpose_critical_parameters(dstinfo);
  180834. if (info->trim)
  180835. trim_bottom_edge(dstinfo);
  180836. break;
  180837. }
  180838. /* Return the appropriate output data set */
  180839. if (info->workspace_coef_arrays != NULL)
  180840. return info->workspace_coef_arrays;
  180841. return src_coef_arrays;
  180842. }
  180843. /* Execute the actual transformation, if any.
  180844. *
  180845. * This must be called *after* jpeg_write_coefficients, because it depends
  180846. * on jpeg_write_coefficients to have computed subsidiary values such as
  180847. * the per-component width and height fields in the destination object.
  180848. *
  180849. * Note that some transformations will modify the source data arrays!
  180850. */
  180851. GLOBAL(void)
  180852. jtransform_execute_transformation (j_decompress_ptr srcinfo,
  180853. j_compress_ptr dstinfo,
  180854. jvirt_barray_ptr *src_coef_arrays,
  180855. jpeg_transform_info *info)
  180856. {
  180857. jvirt_barray_ptr *dst_coef_arrays = info->workspace_coef_arrays;
  180858. switch (info->transform) {
  180859. case JXFORM_NONE:
  180860. break;
  180861. case JXFORM_FLIP_H:
  180862. do_flip_h(srcinfo, dstinfo, src_coef_arrays);
  180863. break;
  180864. case JXFORM_FLIP_V:
  180865. do_flip_v(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180866. break;
  180867. case JXFORM_TRANSPOSE:
  180868. do_transpose(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180869. break;
  180870. case JXFORM_TRANSVERSE:
  180871. do_transverse(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180872. break;
  180873. case JXFORM_ROT_90:
  180874. do_rot_90(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180875. break;
  180876. case JXFORM_ROT_180:
  180877. do_rot_180(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180878. break;
  180879. case JXFORM_ROT_270:
  180880. do_rot_270(srcinfo, dstinfo, src_coef_arrays, dst_coef_arrays);
  180881. break;
  180882. }
  180883. }
  180884. #endif /* TRANSFORMS_SUPPORTED */
  180885. /* Setup decompression object to save desired markers in memory.
  180886. * This must be called before jpeg_read_header() to have the desired effect.
  180887. */
  180888. GLOBAL(void)
  180889. jcopy_markers_setup (j_decompress_ptr srcinfo, JCOPY_OPTION option)
  180890. {
  180891. #ifdef SAVE_MARKERS_SUPPORTED
  180892. int m;
  180893. /* Save comments except under NONE option */
  180894. if (option != JCOPYOPT_NONE) {
  180895. jpeg_save_markers(srcinfo, JPEG_COM, 0xFFFF);
  180896. }
  180897. /* Save all types of APPn markers iff ALL option */
  180898. if (option == JCOPYOPT_ALL) {
  180899. for (m = 0; m < 16; m++)
  180900. jpeg_save_markers(srcinfo, JPEG_APP0 + m, 0xFFFF);
  180901. }
  180902. #endif /* SAVE_MARKERS_SUPPORTED */
  180903. }
  180904. /* Copy markers saved in the given source object to the destination object.
  180905. * This should be called just after jpeg_start_compress() or
  180906. * jpeg_write_coefficients().
  180907. * Note that those routines will have written the SOI, and also the
  180908. * JFIF APP0 or Adobe APP14 markers if selected.
  180909. */
  180910. GLOBAL(void)
  180911. jcopy_markers_execute (j_decompress_ptr srcinfo, j_compress_ptr dstinfo,
  180912. JCOPY_OPTION option)
  180913. {
  180914. jpeg_saved_marker_ptr marker;
  180915. /* In the current implementation, we don't actually need to examine the
  180916. * option flag here; we just copy everything that got saved.
  180917. * But to avoid confusion, we do not output JFIF and Adobe APP14 markers
  180918. * if the encoder library already wrote one.
  180919. */
  180920. for (marker = srcinfo->marker_list; marker != NULL; marker = marker->next) {
  180921. if (dstinfo->write_JFIF_header &&
  180922. marker->marker == JPEG_APP0 &&
  180923. marker->data_length >= 5 &&
  180924. GETJOCTET(marker->data[0]) == 0x4A &&
  180925. GETJOCTET(marker->data[1]) == 0x46 &&
  180926. GETJOCTET(marker->data[2]) == 0x49 &&
  180927. GETJOCTET(marker->data[3]) == 0x46 &&
  180928. GETJOCTET(marker->data[4]) == 0)
  180929. continue; /* reject duplicate JFIF */
  180930. if (dstinfo->write_Adobe_marker &&
  180931. marker->marker == JPEG_APP0+14 &&
  180932. marker->data_length >= 5 &&
  180933. GETJOCTET(marker->data[0]) == 0x41 &&
  180934. GETJOCTET(marker->data[1]) == 0x64 &&
  180935. GETJOCTET(marker->data[2]) == 0x6F &&
  180936. GETJOCTET(marker->data[3]) == 0x62 &&
  180937. GETJOCTET(marker->data[4]) == 0x65)
  180938. continue; /* reject duplicate Adobe */
  180939. #ifdef NEED_FAR_POINTERS
  180940. /* We could use jpeg_write_marker if the data weren't FAR... */
  180941. {
  180942. unsigned int i;
  180943. jpeg_write_m_header(dstinfo, marker->marker, marker->data_length);
  180944. for (i = 0; i < marker->data_length; i++)
  180945. jpeg_write_m_byte(dstinfo, marker->data[i]);
  180946. }
  180947. #else
  180948. jpeg_write_marker(dstinfo, marker->marker,
  180949. marker->data, marker->data_length);
  180950. #endif
  180951. }
  180952. }
  180953. /********* End of inlined file: transupp.c *********/
  180954. }
  180955. #else
  180956. #define JPEG_INTERNALS
  180957. #undef FAR
  180958. #include <jpeglib.h>
  180959. #endif
  180960. }
  180961. #if JUCE_MSVC
  180962. #pragma warning (pop)
  180963. #endif
  180964. BEGIN_JUCE_NAMESPACE
  180965. using namespace jpeglibNamespace;
  180966. struct JPEGDecodingFailure {};
  180967. static void fatalErrorHandler (j_common_ptr)
  180968. {
  180969. throw JPEGDecodingFailure();
  180970. }
  180971. static void silentErrorCallback1 (j_common_ptr) {}
  180972. static void silentErrorCallback2 (j_common_ptr, int) {}
  180973. static void silentErrorCallback3 (j_common_ptr, char*) {}
  180974. static void setupSilentErrorHandler (struct jpeg_error_mgr& err)
  180975. {
  180976. zerostruct (err);
  180977. err.error_exit = fatalErrorHandler;
  180978. err.emit_message = silentErrorCallback2;
  180979. err.output_message = silentErrorCallback1;
  180980. err.format_message = silentErrorCallback3;
  180981. err.reset_error_mgr = silentErrorCallback1;
  180982. }
  180983. static void dummyCallback1 (j_decompress_ptr) throw()
  180984. {
  180985. }
  180986. static void jpegSkip (j_decompress_ptr decompStruct, long num) throw()
  180987. {
  180988. decompStruct->src->next_input_byte += num;
  180989. num = jmin (num, (int) decompStruct->src->bytes_in_buffer);
  180990. decompStruct->src->bytes_in_buffer -= num;
  180991. }
  180992. static boolean jpegFill (j_decompress_ptr) throw()
  180993. {
  180994. return 0;
  180995. }
  180996. Image* juce_loadJPEGImageFromStream (InputStream& in) throw()
  180997. {
  180998. MemoryBlock mb;
  180999. in.readIntoMemoryBlock (mb);
  181000. Image* image = 0;
  181001. if (mb.getSize() > 16)
  181002. {
  181003. struct jpeg_decompress_struct jpegDecompStruct;
  181004. struct jpeg_error_mgr jerr;
  181005. setupSilentErrorHandler (jerr);
  181006. jpegDecompStruct.err = &jerr;
  181007. jpeg_create_decompress (&jpegDecompStruct);
  181008. jpegDecompStruct.src = (jpeg_source_mgr*)(jpegDecompStruct.mem->alloc_small)
  181009. ((j_common_ptr)(&jpegDecompStruct), JPOOL_PERMANENT, sizeof (jpeg_source_mgr));
  181010. jpegDecompStruct.src->init_source = dummyCallback1;
  181011. jpegDecompStruct.src->fill_input_buffer = jpegFill;
  181012. jpegDecompStruct.src->skip_input_data = jpegSkip;
  181013. jpegDecompStruct.src->resync_to_restart = jpeg_resync_to_restart;
  181014. jpegDecompStruct.src->term_source = dummyCallback1;
  181015. jpegDecompStruct.src->next_input_byte = (const unsigned char*) mb.getData();
  181016. jpegDecompStruct.src->bytes_in_buffer = mb.getSize();
  181017. try
  181018. {
  181019. jpeg_read_header (&jpegDecompStruct, TRUE);
  181020. jpeg_calc_output_dimensions (&jpegDecompStruct);
  181021. const int width = jpegDecompStruct.output_width;
  181022. const int height = jpegDecompStruct.output_height;
  181023. jpegDecompStruct.out_color_space = JCS_RGB;
  181024. JSAMPARRAY buffer
  181025. = (*jpegDecompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegDecompStruct,
  181026. JPOOL_IMAGE,
  181027. width * 3, 1);
  181028. if (jpeg_start_decompress (&jpegDecompStruct))
  181029. {
  181030. image = new Image (Image::RGB, width, height, false);
  181031. for (int y = 0; y < height; ++y)
  181032. {
  181033. jpeg_read_scanlines (&jpegDecompStruct, buffer, 1);
  181034. int stride, pixelStride;
  181035. uint8* pixels = image->lockPixelDataReadWrite (0, y, width, 1, stride, pixelStride);
  181036. const uint8* src = *buffer;
  181037. uint8* dest = pixels;
  181038. for (int i = width; --i >= 0;)
  181039. {
  181040. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  181041. dest += pixelStride;
  181042. src += 3;
  181043. }
  181044. image->releasePixelDataReadWrite (pixels);
  181045. }
  181046. jpeg_finish_decompress (&jpegDecompStruct);
  181047. }
  181048. jpeg_destroy_decompress (&jpegDecompStruct);
  181049. }
  181050. catch (...)
  181051. {}
  181052. in.setPosition (((char*) jpegDecompStruct.src->next_input_byte) - (char*) mb.getData());
  181053. }
  181054. return image;
  181055. }
  181056. static const int bufferSize = 512;
  181057. struct JuceJpegDest : public jpeg_destination_mgr
  181058. {
  181059. OutputStream* output;
  181060. char* buffer;
  181061. };
  181062. static void jpegWriteInit (j_compress_ptr) throw()
  181063. {
  181064. }
  181065. static void jpegWriteTerminate (j_compress_ptr cinfo) throw()
  181066. {
  181067. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  181068. const int numToWrite = bufferSize - dest->free_in_buffer;
  181069. dest->output->write (dest->buffer, numToWrite);
  181070. }
  181071. static boolean jpegWriteFlush (j_compress_ptr cinfo) throw()
  181072. {
  181073. JuceJpegDest* const dest = (JuceJpegDest*) cinfo->dest;
  181074. const int numToWrite = bufferSize;
  181075. dest->next_output_byte = (JOCTET*) dest->buffer;
  181076. dest->free_in_buffer = bufferSize;
  181077. return dest->output->write (dest->buffer, numToWrite);
  181078. }
  181079. bool juce_writeJPEGImageToStream (const Image& image,
  181080. OutputStream& out,
  181081. float quality) throw()
  181082. {
  181083. if (image.hasAlphaChannel())
  181084. {
  181085. // this method could fill the background in white and still save the image..
  181086. jassertfalse
  181087. return true;
  181088. }
  181089. struct jpeg_compress_struct jpegCompStruct;
  181090. struct jpeg_error_mgr jerr;
  181091. setupSilentErrorHandler (jerr);
  181092. jpegCompStruct.err = &jerr;
  181093. jpeg_create_compress (&jpegCompStruct);
  181094. JuceJpegDest dest;
  181095. jpegCompStruct.dest = &dest;
  181096. dest.output = &out;
  181097. dest.buffer = (char*) juce_malloc (bufferSize);
  181098. dest.next_output_byte = (JOCTET*) dest.buffer;
  181099. dest.free_in_buffer = bufferSize;
  181100. dest.init_destination = jpegWriteInit;
  181101. dest.empty_output_buffer = jpegWriteFlush;
  181102. dest.term_destination = jpegWriteTerminate;
  181103. jpegCompStruct.image_width = image.getWidth();
  181104. jpegCompStruct.image_height = image.getHeight();
  181105. jpegCompStruct.input_components = 3;
  181106. jpegCompStruct.in_color_space = JCS_RGB;
  181107. jpegCompStruct.write_JFIF_header = 1;
  181108. jpegCompStruct.X_density = 72;
  181109. jpegCompStruct.Y_density = 72;
  181110. jpeg_set_defaults (&jpegCompStruct);
  181111. jpegCompStruct.dct_method = JDCT_FLOAT;
  181112. jpegCompStruct.optimize_coding = 1;
  181113. // jpegCompStruct.smoothing_factor = 10;
  181114. if (quality < 0.0f)
  181115. quality = 0.85f;
  181116. jpeg_set_quality (&jpegCompStruct, jlimit (0, 100, roundFloatToInt (quality * 100.0f)), TRUE);
  181117. jpeg_start_compress (&jpegCompStruct, TRUE);
  181118. const int strideBytes = jpegCompStruct.image_width * jpegCompStruct.input_components;
  181119. JSAMPARRAY buffer = (*jpegCompStruct.mem->alloc_sarray) ((j_common_ptr) &jpegCompStruct,
  181120. JPOOL_IMAGE,
  181121. strideBytes, 1);
  181122. while (jpegCompStruct.next_scanline < jpegCompStruct.image_height)
  181123. {
  181124. int stride, pixelStride;
  181125. const uint8* pixels = image.lockPixelDataReadOnly (0, jpegCompStruct.next_scanline, jpegCompStruct.image_width, 1, stride, pixelStride);
  181126. const uint8* src = pixels;
  181127. uint8* dst = *buffer;
  181128. for (int i = jpegCompStruct.image_width; --i >= 0;)
  181129. {
  181130. *dst++ = ((const PixelRGB*) src)->getRed();
  181131. *dst++ = ((const PixelRGB*) src)->getGreen();
  181132. *dst++ = ((const PixelRGB*) src)->getBlue();
  181133. src += pixelStride;
  181134. }
  181135. jpeg_write_scanlines (&jpegCompStruct, buffer, 1);
  181136. image.releasePixelDataReadOnly (pixels);
  181137. }
  181138. jpeg_finish_compress (&jpegCompStruct);
  181139. jpeg_destroy_compress (&jpegCompStruct);
  181140. juce_free (dest.buffer);
  181141. out.flush();
  181142. return true;
  181143. }
  181144. END_JUCE_NAMESPACE
  181145. /********* End of inlined file: juce_JPEGLoader.cpp *********/
  181146. /********* Start of inlined file: juce_PNGLoader.cpp *********/
  181147. #ifdef _MSC_VER
  181148. #pragma warning (push)
  181149. #pragma warning (disable: 4390 4611)
  181150. #endif
  181151. namespace zlibNamespace
  181152. {
  181153. #if JUCE_INCLUDE_ZLIB_CODE
  181154. #undef OS_CODE
  181155. #undef fdopen
  181156. #undef OS_CODE
  181157. #else
  181158. #include <zlib.h>
  181159. #endif
  181160. }
  181161. namespace pnglibNamespace
  181162. {
  181163. using namespace zlibNamespace;
  181164. #if JUCE_INCLUDE_PNGLIB_CODE
  181165. using ::malloc;
  181166. using ::free;
  181167. extern "C"
  181168. {
  181169. using ::abs;
  181170. #define PNG_INTERNAL
  181171. #define NO_DUMMY_DECL
  181172. #define PNG_SETJMP_NOT_SUPPORTED
  181173. /********* Start of inlined file: png.h *********/
  181174. /* png.h - header file for PNG reference library
  181175. *
  181176. * libpng version 1.2.21 - October 4, 2007
  181177. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181178. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181179. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181180. *
  181181. * Authors and maintainers:
  181182. * libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  181183. * libpng versions 0.89c, June 1996, through 0.96, May 1997: Andreas Dilger
  181184. * libpng versions 0.97, January 1998, through 1.2.21 - October 4, 2007: Glenn
  181185. * See also "Contributing Authors", below.
  181186. *
  181187. * Note about libpng version numbers:
  181188. *
  181189. * Due to various miscommunications, unforeseen code incompatibilities
  181190. * and occasional factors outside the authors' control, version numbering
  181191. * on the library has not always been consistent and straightforward.
  181192. * The following table summarizes matters since version 0.89c, which was
  181193. * the first widely used release:
  181194. *
  181195. * source png.h png.h shared-lib
  181196. * version string int version
  181197. * ------- ------ ----- ----------
  181198. * 0.89c "1.0 beta 3" 0.89 89 1.0.89
  181199. * 0.90 "1.0 beta 4" 0.90 90 0.90 [should have been 2.0.90]
  181200. * 0.95 "1.0 beta 5" 0.95 95 0.95 [should have been 2.0.95]
  181201. * 0.96 "1.0 beta 6" 0.96 96 0.96 [should have been 2.0.96]
  181202. * 0.97b "1.00.97 beta 7" 1.00.97 97 1.0.1 [should have been 2.0.97]
  181203. * 0.97c 0.97 97 2.0.97
  181204. * 0.98 0.98 98 2.0.98
  181205. * 0.99 0.99 98 2.0.99
  181206. * 0.99a-m 0.99 99 2.0.99
  181207. * 1.00 1.00 100 2.1.0 [100 should be 10000]
  181208. * 1.0.0 (from here on, the 100 2.1.0 [100 should be 10000]
  181209. * 1.0.1 png.h string is 10001 2.1.0
  181210. * 1.0.1a-e identical to the 10002 from here on, the shared library
  181211. * 1.0.2 source version) 10002 is 2.V where V is the source code
  181212. * 1.0.2a-b 10003 version, except as noted.
  181213. * 1.0.3 10003
  181214. * 1.0.3a-d 10004
  181215. * 1.0.4 10004
  181216. * 1.0.4a-f 10005
  181217. * 1.0.5 (+ 2 patches) 10005
  181218. * 1.0.5a-d 10006
  181219. * 1.0.5e-r 10100 (not source compatible)
  181220. * 1.0.5s-v 10006 (not binary compatible)
  181221. * 1.0.6 (+ 3 patches) 10006 (still binary incompatible)
  181222. * 1.0.6d-f 10007 (still binary incompatible)
  181223. * 1.0.6g 10007
  181224. * 1.0.6h 10007 10.6h (testing xy.z so-numbering)
  181225. * 1.0.6i 10007 10.6i
  181226. * 1.0.6j 10007 2.1.0.6j (incompatible with 1.0.0)
  181227. * 1.0.7beta11-14 DLLNUM 10007 2.1.0.7beta11-14 (binary compatible)
  181228. * 1.0.7beta15-18 1 10007 2.1.0.7beta15-18 (binary compatible)
  181229. * 1.0.7rc1-2 1 10007 2.1.0.7rc1-2 (binary compatible)
  181230. * 1.0.7 1 10007 (still compatible)
  181231. * 1.0.8beta1-4 1 10008 2.1.0.8beta1-4
  181232. * 1.0.8rc1 1 10008 2.1.0.8rc1
  181233. * 1.0.8 1 10008 2.1.0.8
  181234. * 1.0.9beta1-6 1 10009 2.1.0.9beta1-6
  181235. * 1.0.9rc1 1 10009 2.1.0.9rc1
  181236. * 1.0.9beta7-10 1 10009 2.1.0.9beta7-10
  181237. * 1.0.9rc2 1 10009 2.1.0.9rc2
  181238. * 1.0.9 1 10009 2.1.0.9
  181239. * 1.0.10beta1 1 10010 2.1.0.10beta1
  181240. * 1.0.10rc1 1 10010 2.1.0.10rc1
  181241. * 1.0.10 1 10010 2.1.0.10
  181242. * 1.0.11beta1-3 1 10011 2.1.0.11beta1-3
  181243. * 1.0.11rc1 1 10011 2.1.0.11rc1
  181244. * 1.0.11 1 10011 2.1.0.11
  181245. * 1.0.12beta1-2 2 10012 2.1.0.12beta1-2
  181246. * 1.0.12rc1 2 10012 2.1.0.12rc1
  181247. * 1.0.12 2 10012 2.1.0.12
  181248. * 1.1.0a-f - 10100 2.1.1.0a-f (branch abandoned)
  181249. * 1.2.0beta1-2 2 10200 2.1.2.0beta1-2
  181250. * 1.2.0beta3-5 3 10200 3.1.2.0beta3-5
  181251. * 1.2.0rc1 3 10200 3.1.2.0rc1
  181252. * 1.2.0 3 10200 3.1.2.0
  181253. * 1.2.1beta1-4 3 10201 3.1.2.1beta1-4
  181254. * 1.2.1rc1-2 3 10201 3.1.2.1rc1-2
  181255. * 1.2.1 3 10201 3.1.2.1
  181256. * 1.2.2beta1-6 12 10202 12.so.0.1.2.2beta1-6
  181257. * 1.0.13beta1 10 10013 10.so.0.1.0.13beta1
  181258. * 1.0.13rc1 10 10013 10.so.0.1.0.13rc1
  181259. * 1.2.2rc1 12 10202 12.so.0.1.2.2rc1
  181260. * 1.0.13 10 10013 10.so.0.1.0.13
  181261. * 1.2.2 12 10202 12.so.0.1.2.2
  181262. * 1.2.3rc1-6 12 10203 12.so.0.1.2.3rc1-6
  181263. * 1.2.3 12 10203 12.so.0.1.2.3
  181264. * 1.2.4beta1-3 13 10204 12.so.0.1.2.4beta1-3
  181265. * 1.0.14rc1 13 10014 10.so.0.1.0.14rc1
  181266. * 1.2.4rc1 13 10204 12.so.0.1.2.4rc1
  181267. * 1.0.14 10 10014 10.so.0.1.0.14
  181268. * 1.2.4 13 10204 12.so.0.1.2.4
  181269. * 1.2.5beta1-2 13 10205 12.so.0.1.2.5beta1-2
  181270. * 1.0.15rc1-3 10 10015 10.so.0.1.0.15rc1-3
  181271. * 1.2.5rc1-3 13 10205 12.so.0.1.2.5rc1-3
  181272. * 1.0.15 10 10015 10.so.0.1.0.15
  181273. * 1.2.5 13 10205 12.so.0.1.2.5
  181274. * 1.2.6beta1-4 13 10206 12.so.0.1.2.6beta1-4
  181275. * 1.0.16 10 10016 10.so.0.1.0.16
  181276. * 1.2.6 13 10206 12.so.0.1.2.6
  181277. * 1.2.7beta1-2 13 10207 12.so.0.1.2.7beta1-2
  181278. * 1.0.17rc1 10 10017 10.so.0.1.0.17rc1
  181279. * 1.2.7rc1 13 10207 12.so.0.1.2.7rc1
  181280. * 1.0.17 10 10017 10.so.0.1.0.17
  181281. * 1.2.7 13 10207 12.so.0.1.2.7
  181282. * 1.2.8beta1-5 13 10208 12.so.0.1.2.8beta1-5
  181283. * 1.0.18rc1-5 10 10018 10.so.0.1.0.18rc1-5
  181284. * 1.2.8rc1-5 13 10208 12.so.0.1.2.8rc1-5
  181285. * 1.0.18 10 10018 10.so.0.1.0.18
  181286. * 1.2.8 13 10208 12.so.0.1.2.8
  181287. * 1.2.9beta1-3 13 10209 12.so.0.1.2.9beta1-3
  181288. * 1.2.9beta4-11 13 10209 12.so.0.9[.0]
  181289. * 1.2.9rc1 13 10209 12.so.0.9[.0]
  181290. * 1.2.9 13 10209 12.so.0.9[.0]
  181291. * 1.2.10beta1-8 13 10210 12.so.0.10[.0]
  181292. * 1.2.10rc1-3 13 10210 12.so.0.10[.0]
  181293. * 1.2.10 13 10210 12.so.0.10[.0]
  181294. * 1.2.11beta1-4 13 10211 12.so.0.11[.0]
  181295. * 1.0.19rc1-5 10 10019 10.so.0.19[.0]
  181296. * 1.2.11rc1-5 13 10211 12.so.0.11[.0]
  181297. * 1.0.19 10 10019 10.so.0.19[.0]
  181298. * 1.2.11 13 10211 12.so.0.11[.0]
  181299. * 1.0.20 10 10020 10.so.0.20[.0]
  181300. * 1.2.12 13 10212 12.so.0.12[.0]
  181301. * 1.2.13beta1 13 10213 12.so.0.13[.0]
  181302. * 1.0.21 10 10021 10.so.0.21[.0]
  181303. * 1.2.13 13 10213 12.so.0.13[.0]
  181304. * 1.2.14beta1-2 13 10214 12.so.0.14[.0]
  181305. * 1.0.22rc1 10 10022 10.so.0.22[.0]
  181306. * 1.2.14rc1 13 10214 12.so.0.14[.0]
  181307. * 1.0.22 10 10022 10.so.0.22[.0]
  181308. * 1.2.14 13 10214 12.so.0.14[.0]
  181309. * 1.2.15beta1-6 13 10215 12.so.0.15[.0]
  181310. * 1.0.23rc1-5 10 10023 10.so.0.23[.0]
  181311. * 1.2.15rc1-5 13 10215 12.so.0.15[.0]
  181312. * 1.0.23 10 10023 10.so.0.23[.0]
  181313. * 1.2.15 13 10215 12.so.0.15[.0]
  181314. * 1.2.16beta1-2 13 10216 12.so.0.16[.0]
  181315. * 1.2.16rc1 13 10216 12.so.0.16[.0]
  181316. * 1.0.24 10 10024 10.so.0.24[.0]
  181317. * 1.2.16 13 10216 12.so.0.16[.0]
  181318. * 1.2.17beta1-2 13 10217 12.so.0.17[.0]
  181319. * 1.0.25rc1 10 10025 10.so.0.25[.0]
  181320. * 1.2.17rc1-3 13 10217 12.so.0.17[.0]
  181321. * 1.0.25 10 10025 10.so.0.25[.0]
  181322. * 1.2.17 13 10217 12.so.0.17[.0]
  181323. * 1.0.26 10 10026 10.so.0.26[.0]
  181324. * 1.2.18 13 10218 12.so.0.18[.0]
  181325. * 1.2.19beta1-31 13 10219 12.so.0.19[.0]
  181326. * 1.0.27rc1-6 10 10027 10.so.0.27[.0]
  181327. * 1.2.19rc1-6 13 10219 12.so.0.19[.0]
  181328. * 1.0.27 10 10027 10.so.0.27[.0]
  181329. * 1.2.19 13 10219 12.so.0.19[.0]
  181330. * 1.2.20beta01-04 13 10220 12.so.0.20[.0]
  181331. * 1.0.28rc1-6 10 10028 10.so.0.28[.0]
  181332. * 1.2.20rc1-6 13 10220 12.so.0.20[.0]
  181333. * 1.0.28 10 10028 10.so.0.28[.0]
  181334. * 1.2.20 13 10220 12.so.0.20[.0]
  181335. * 1.2.21beta1-2 13 10221 12.so.0.21[.0]
  181336. * 1.2.21rc1-3 13 10221 12.so.0.21[.0]
  181337. * 1.0.29 10 10029 10.so.0.29[.0]
  181338. * 1.2.21 13 10221 12.so.0.21[.0]
  181339. *
  181340. * Henceforth the source version will match the shared-library major
  181341. * and minor numbers; the shared-library major version number will be
  181342. * used for changes in backward compatibility, as it is intended. The
  181343. * PNG_LIBPNG_VER macro, which is not used within libpng but is available
  181344. * for applications, is an unsigned integer of the form xyyzz corresponding
  181345. * to the source version x.y.z (leading zeros in y and z). Beta versions
  181346. * were given the previous public release number plus a letter, until
  181347. * version 1.0.6j; from then on they were given the upcoming public
  181348. * release number plus "betaNN" or "rcN".
  181349. *
  181350. * Binary incompatibility exists only when applications make direct access
  181351. * to the info_ptr or png_ptr members through png.h, and the compiled
  181352. * application is loaded with a different version of the library.
  181353. *
  181354. * DLLNUM will change each time there are forward or backward changes
  181355. * in binary compatibility (e.g., when a new feature is added).
  181356. *
  181357. * See libpng.txt or libpng.3 for more information. The PNG specification
  181358. * is available as a W3C Recommendation and as an ISO Specification,
  181359. * <http://www.w3.org/TR/2003/REC-PNG-20031110/
  181360. */
  181361. /*
  181362. * COPYRIGHT NOTICE, DISCLAIMER, and LICENSE:
  181363. *
  181364. * If you modify libpng you may insert additional notices immediately following
  181365. * this sentence.
  181366. *
  181367. * libpng versions 1.2.6, August 15, 2004, through 1.2.21, October 4, 2007, are
  181368. * Copyright (c) 2004, 2006-2007 Glenn Randers-Pehrson, and are
  181369. * distributed according to the same disclaimer and license as libpng-1.2.5
  181370. * with the following individual added to the list of Contributing Authors:
  181371. *
  181372. * Cosmin Truta
  181373. *
  181374. * libpng versions 1.0.7, July 1, 2000, through 1.2.5, October 3, 2002, are
  181375. * Copyright (c) 2000-2002 Glenn Randers-Pehrson, and are
  181376. * distributed according to the same disclaimer and license as libpng-1.0.6
  181377. * with the following individuals added to the list of Contributing Authors:
  181378. *
  181379. * Simon-Pierre Cadieux
  181380. * Eric S. Raymond
  181381. * Gilles Vollant
  181382. *
  181383. * and with the following additions to the disclaimer:
  181384. *
  181385. * There is no warranty against interference with your enjoyment of the
  181386. * library or against infringement. There is no warranty that our
  181387. * efforts or the library will fulfill any of your particular purposes
  181388. * or needs. This library is provided with all faults, and the entire
  181389. * risk of satisfactory quality, performance, accuracy, and effort is with
  181390. * the user.
  181391. *
  181392. * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  181393. * Copyright (c) 1998, 1999, 2000 Glenn Randers-Pehrson, and are
  181394. * distributed according to the same disclaimer and license as libpng-0.96,
  181395. * with the following individuals added to the list of Contributing Authors:
  181396. *
  181397. * Tom Lane
  181398. * Glenn Randers-Pehrson
  181399. * Willem van Schaik
  181400. *
  181401. * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  181402. * Copyright (c) 1996, 1997 Andreas Dilger
  181403. * Distributed according to the same disclaimer and license as libpng-0.88,
  181404. * with the following individuals added to the list of Contributing Authors:
  181405. *
  181406. * John Bowler
  181407. * Kevin Bracey
  181408. * Sam Bushell
  181409. * Magnus Holmgren
  181410. * Greg Roelofs
  181411. * Tom Tanner
  181412. *
  181413. * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  181414. * Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.
  181415. *
  181416. * For the purposes of this copyright and license, "Contributing Authors"
  181417. * is defined as the following set of individuals:
  181418. *
  181419. * Andreas Dilger
  181420. * Dave Martindale
  181421. * Guy Eric Schalnat
  181422. * Paul Schmidt
  181423. * Tim Wegner
  181424. *
  181425. * The PNG Reference Library is supplied "AS IS". The Contributing Authors
  181426. * and Group 42, Inc. disclaim all warranties, expressed or implied,
  181427. * including, without limitation, the warranties of merchantability and of
  181428. * fitness for any purpose. The Contributing Authors and Group 42, Inc.
  181429. * assume no liability for direct, indirect, incidental, special, exemplary,
  181430. * or consequential damages, which may result from the use of the PNG
  181431. * Reference Library, even if advised of the possibility of such damage.
  181432. *
  181433. * Permission is hereby granted to use, copy, modify, and distribute this
  181434. * source code, or portions hereof, for any purpose, without fee, subject
  181435. * to the following restrictions:
  181436. *
  181437. * 1. The origin of this source code must not be misrepresented.
  181438. *
  181439. * 2. Altered versions must be plainly marked as such and
  181440. * must not be misrepresented as being the original source.
  181441. *
  181442. * 3. This Copyright notice may not be removed or altered from
  181443. * any source or altered source distribution.
  181444. *
  181445. * The Contributing Authors and Group 42, Inc. specifically permit, without
  181446. * fee, and encourage the use of this source code as a component to
  181447. * supporting the PNG file format in commercial products. If you use this
  181448. * source code in a product, acknowledgment is not required but would be
  181449. * appreciated.
  181450. */
  181451. /*
  181452. * A "png_get_copyright" function is available, for convenient use in "about"
  181453. * boxes and the like:
  181454. *
  181455. * printf("%s",png_get_copyright(NULL));
  181456. *
  181457. * Also, the PNG logo (in PNG format, of course) is supplied in the
  181458. * files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
  181459. */
  181460. /*
  181461. * Libpng is OSI Certified Open Source Software. OSI Certified is a
  181462. * certification mark of the Open Source Initiative.
  181463. */
  181464. /*
  181465. * The contributing authors would like to thank all those who helped
  181466. * with testing, bug fixes, and patience. This wouldn't have been
  181467. * possible without all of you.
  181468. *
  181469. * Thanks to Frank J. T. Wojcik for helping with the documentation.
  181470. */
  181471. /*
  181472. * Y2K compliance in libpng:
  181473. * =========================
  181474. *
  181475. * October 4, 2007
  181476. *
  181477. * Since the PNG Development group is an ad-hoc body, we can't make
  181478. * an official declaration.
  181479. *
  181480. * This is your unofficial assurance that libpng from version 0.71 and
  181481. * upward through 1.2.21 are Y2K compliant. It is my belief that earlier
  181482. * versions were also Y2K compliant.
  181483. *
  181484. * Libpng only has three year fields. One is a 2-byte unsigned integer
  181485. * that will hold years up to 65535. The other two hold the date in text
  181486. * format, and will hold years up to 9999.
  181487. *
  181488. * The integer is
  181489. * "png_uint_16 year" in png_time_struct.
  181490. *
  181491. * The strings are
  181492. * "png_charp time_buffer" in png_struct and
  181493. * "near_time_buffer", which is a local character string in png.c.
  181494. *
  181495. * There are seven time-related functions:
  181496. * png.c: png_convert_to_rfc_1123() in png.c
  181497. * (formerly png_convert_to_rfc_1152() in error)
  181498. * png_convert_from_struct_tm() in pngwrite.c, called in pngwrite.c
  181499. * png_convert_from_time_t() in pngwrite.c
  181500. * png_get_tIME() in pngget.c
  181501. * png_handle_tIME() in pngrutil.c, called in pngread.c
  181502. * png_set_tIME() in pngset.c
  181503. * png_write_tIME() in pngwutil.c, called in pngwrite.c
  181504. *
  181505. * All handle dates properly in a Y2K environment. The
  181506. * png_convert_from_time_t() function calls gmtime() to convert from system
  181507. * clock time, which returns (year - 1900), which we properly convert to
  181508. * the full 4-digit year. There is a possibility that applications using
  181509. * libpng are not passing 4-digit years into the png_convert_to_rfc_1123()
  181510. * function, or that they are incorrectly passing only a 2-digit year
  181511. * instead of "year - 1900" into the png_convert_from_struct_tm() function,
  181512. * but this is not under our control. The libpng documentation has always
  181513. * stated that it works with 4-digit years, and the APIs have been
  181514. * documented as such.
  181515. *
  181516. * The tIME chunk itself is also Y2K compliant. It uses a 2-byte unsigned
  181517. * integer to hold the year, and can hold years as large as 65535.
  181518. *
  181519. * zlib, upon which libpng depends, is also Y2K compliant. It contains
  181520. * no date-related code.
  181521. *
  181522. * Glenn Randers-Pehrson
  181523. * libpng maintainer
  181524. * PNG Development Group
  181525. */
  181526. #ifndef PNG_H
  181527. #define PNG_H
  181528. /* This is not the place to learn how to use libpng. The file libpng.txt
  181529. * describes how to use libpng, and the file example.c summarizes it
  181530. * with some code on which to build. This file is useful for looking
  181531. * at the actual function definitions and structure components.
  181532. */
  181533. /* Version information for png.h - this should match the version in png.c */
  181534. #define PNG_LIBPNG_VER_STRING "1.2.21"
  181535. #define PNG_HEADER_VERSION_STRING \
  181536. " libpng version 1.2.21 - October 4, 2007\n"
  181537. #define PNG_LIBPNG_VER_SONUM 0
  181538. #define PNG_LIBPNG_VER_DLLNUM 13
  181539. /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
  181540. #define PNG_LIBPNG_VER_MAJOR 1
  181541. #define PNG_LIBPNG_VER_MINOR 2
  181542. #define PNG_LIBPNG_VER_RELEASE 21
  181543. /* This should match the numeric part of the final component of
  181544. * PNG_LIBPNG_VER_STRING, omitting any leading zero: */
  181545. #define PNG_LIBPNG_VER_BUILD 0
  181546. /* Release Status */
  181547. #define PNG_LIBPNG_BUILD_ALPHA 1
  181548. #define PNG_LIBPNG_BUILD_BETA 2
  181549. #define PNG_LIBPNG_BUILD_RC 3
  181550. #define PNG_LIBPNG_BUILD_STABLE 4
  181551. #define PNG_LIBPNG_BUILD_RELEASE_STATUS_MASK 7
  181552. /* Release-Specific Flags */
  181553. #define PNG_LIBPNG_BUILD_PATCH 8 /* Can be OR'ed with
  181554. PNG_LIBPNG_BUILD_STABLE only */
  181555. #define PNG_LIBPNG_BUILD_PRIVATE 16 /* Cannot be OR'ed with
  181556. PNG_LIBPNG_BUILD_SPECIAL */
  181557. #define PNG_LIBPNG_BUILD_SPECIAL 32 /* Cannot be OR'ed with
  181558. PNG_LIBPNG_BUILD_PRIVATE */
  181559. #define PNG_LIBPNG_BUILD_BASE_TYPE PNG_LIBPNG_BUILD_STABLE
  181560. /* Careful here. At one time, Guy wanted to use 082, but that would be octal.
  181561. * We must not include leading zeros.
  181562. * Versions 0.7 through 1.0.0 were in the range 0 to 100 here (only
  181563. * version 1.0.0 was mis-numbered 100 instead of 10000). From
  181564. * version 1.0.1 it's xxyyzz, where x=major, y=minor, z=release */
  181565. #define PNG_LIBPNG_VER 10221 /* 1.2.21 */
  181566. #ifndef PNG_VERSION_INFO_ONLY
  181567. /* include the compression library's header */
  181568. #endif
  181569. /* include all user configurable info, including optional assembler routines */
  181570. /********* Start of inlined file: pngconf.h *********/
  181571. /* pngconf.h - machine configurable file for libpng
  181572. *
  181573. * libpng version 1.2.21 - October 4, 2007
  181574. * For conditions of distribution and use, see copyright notice in png.h
  181575. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  181576. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  181577. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  181578. */
  181579. /* Any machine specific code is near the front of this file, so if you
  181580. * are configuring libpng for a machine, you may want to read the section
  181581. * starting here down to where it starts to typedef png_color, png_text,
  181582. * and png_info.
  181583. */
  181584. #ifndef PNGCONF_H
  181585. #define PNGCONF_H
  181586. #define PNG_1_2_X
  181587. // These are some Juce config settings that should remove any unnecessary code bloat..
  181588. #define PNG_NO_STDIO 1
  181589. #define PNG_DEBUG 0
  181590. #define PNG_NO_WARNINGS 1
  181591. #define PNG_NO_ERROR_TEXT 1
  181592. #define PNG_NO_ERROR_NUMBERS 1
  181593. #define PNG_NO_USER_MEM 1
  181594. #define PNG_NO_READ_iCCP 1
  181595. #define PNG_NO_READ_UNKNOWN_CHUNKS 1
  181596. #define PNG_NO_READ_USER_CHUNKS 1
  181597. #define PNG_NO_READ_iTXt 1
  181598. #define PNG_NO_READ_sCAL 1
  181599. #define PNG_NO_READ_sPLT 1
  181600. #define png_error(a, b) png_err(a)
  181601. #define png_warning(a, b)
  181602. #define png_chunk_error(a, b) png_err(a)
  181603. #define png_chunk_warning(a, b)
  181604. /*
  181605. * PNG_USER_CONFIG has to be defined on the compiler command line. This
  181606. * includes the resource compiler for Windows DLL configurations.
  181607. */
  181608. #ifdef PNG_USER_CONFIG
  181609. # ifndef PNG_USER_PRIVATEBUILD
  181610. # define PNG_USER_PRIVATEBUILD
  181611. # endif
  181612. #include "pngusr.h"
  181613. #endif
  181614. /* PNG_CONFIGURE_LIBPNG is set by the "configure" script. */
  181615. #ifdef PNG_CONFIGURE_LIBPNG
  181616. #ifdef HAVE_CONFIG_H
  181617. #include "config.h"
  181618. #endif
  181619. #endif
  181620. /*
  181621. * Added at libpng-1.2.8
  181622. *
  181623. * If you create a private DLL you need to define in "pngusr.h" the followings:
  181624. * #define PNG_USER_PRIVATEBUILD <Describes by whom and why this version of
  181625. * the DLL was built>
  181626. * e.g. #define PNG_USER_PRIVATEBUILD "Build by MyCompany for xyz reasons."
  181627. * #define PNG_USER_DLLFNAME_POSTFIX <two-letter postfix that serve to
  181628. * distinguish your DLL from those of the official release. These
  181629. * correspond to the trailing letters that come after the version
  181630. * number and must match your private DLL name>
  181631. * e.g. // private DLL "libpng13gx.dll"
  181632. * #define PNG_USER_DLLFNAME_POSTFIX "gx"
  181633. *
  181634. * The following macros are also at your disposal if you want to complete the
  181635. * DLL VERSIONINFO structure.
  181636. * - PNG_USER_VERSIONINFO_COMMENTS
  181637. * - PNG_USER_VERSIONINFO_COMPANYNAME
  181638. * - PNG_USER_VERSIONINFO_LEGALTRADEMARKS
  181639. */
  181640. #ifdef __STDC__
  181641. #ifdef SPECIALBUILD
  181642. # pragma message("PNG_LIBPNG_SPECIALBUILD (and deprecated SPECIALBUILD)\
  181643. are now LIBPNG reserved macros. Use PNG_USER_PRIVATEBUILD instead.")
  181644. #endif
  181645. #ifdef PRIVATEBUILD
  181646. # pragma message("PRIVATEBUILD is deprecated.\
  181647. Use PNG_USER_PRIVATEBUILD instead.")
  181648. # define PNG_USER_PRIVATEBUILD PRIVATEBUILD
  181649. #endif
  181650. #endif /* __STDC__ */
  181651. #ifndef PNG_VERSION_INFO_ONLY
  181652. /* End of material added to libpng-1.2.8 */
  181653. /* Added at libpng-1.2.19, removed at libpng-1.2.20 because it caused trouble
  181654. Restored at libpng-1.2.21 */
  181655. # define PNG_WARN_UNINITIALIZED_ROW 1
  181656. /* End of material added at libpng-1.2.19/1.2.21 */
  181657. /* This is the size of the compression buffer, and thus the size of
  181658. * an IDAT chunk. Make this whatever size you feel is best for your
  181659. * machine. One of these will be allocated per png_struct. When this
  181660. * is full, it writes the data to the disk, and does some other
  181661. * calculations. Making this an extremely small size will slow
  181662. * the library down, but you may want to experiment to determine
  181663. * where it becomes significant, if you are concerned with memory
  181664. * usage. Note that zlib allocates at least 32Kb also. For readers,
  181665. * this describes the size of the buffer available to read the data in.
  181666. * Unless this gets smaller than the size of a row (compressed),
  181667. * it should not make much difference how big this is.
  181668. */
  181669. #ifndef PNG_ZBUF_SIZE
  181670. # define PNG_ZBUF_SIZE 8192
  181671. #endif
  181672. /* Enable if you want a write-only libpng */
  181673. #ifndef PNG_NO_READ_SUPPORTED
  181674. # define PNG_READ_SUPPORTED
  181675. #endif
  181676. /* Enable if you want a read-only libpng */
  181677. #ifndef PNG_NO_WRITE_SUPPORTED
  181678. # define PNG_WRITE_SUPPORTED
  181679. #endif
  181680. /* Enabled by default in 1.2.0. You can disable this if you don't need to
  181681. support PNGs that are embedded in MNG datastreams */
  181682. #if !defined(PNG_1_0_X) && !defined(PNG_NO_MNG_FEATURES)
  181683. # ifndef PNG_MNG_FEATURES_SUPPORTED
  181684. # define PNG_MNG_FEATURES_SUPPORTED
  181685. # endif
  181686. #endif
  181687. #ifndef PNG_NO_FLOATING_POINT_SUPPORTED
  181688. # ifndef PNG_FLOATING_POINT_SUPPORTED
  181689. # define PNG_FLOATING_POINT_SUPPORTED
  181690. # endif
  181691. #endif
  181692. /* If you are running on a machine where you cannot allocate more
  181693. * than 64K of memory at once, uncomment this. While libpng will not
  181694. * normally need that much memory in a chunk (unless you load up a very
  181695. * large file), zlib needs to know how big of a chunk it can use, and
  181696. * libpng thus makes sure to check any memory allocation to verify it
  181697. * will fit into memory.
  181698. #define PNG_MAX_MALLOC_64K
  181699. */
  181700. #if defined(MAXSEG_64K) && !defined(PNG_MAX_MALLOC_64K)
  181701. # define PNG_MAX_MALLOC_64K
  181702. #endif
  181703. /* Special munging to support doing things the 'cygwin' way:
  181704. * 'Normal' png-on-win32 defines/defaults:
  181705. * PNG_BUILD_DLL -- building dll
  181706. * PNG_USE_DLL -- building an application, linking to dll
  181707. * (no define) -- building static library, or building an
  181708. * application and linking to the static lib
  181709. * 'Cygwin' defines/defaults:
  181710. * PNG_BUILD_DLL -- (ignored) building the dll
  181711. * (no define) -- (ignored) building an application, linking to the dll
  181712. * PNG_STATIC -- (ignored) building the static lib, or building an
  181713. * application that links to the static lib.
  181714. * ALL_STATIC -- (ignored) building various static libs, or building an
  181715. * application that links to the static libs.
  181716. * Thus,
  181717. * a cygwin user should define either PNG_BUILD_DLL or PNG_STATIC, and
  181718. * this bit of #ifdefs will define the 'correct' config variables based on
  181719. * that. If a cygwin user *wants* to define 'PNG_USE_DLL' that's okay, but
  181720. * unnecessary.
  181721. *
  181722. * Also, the precedence order is:
  181723. * ALL_STATIC (since we can't #undef something outside our namespace)
  181724. * PNG_BUILD_DLL
  181725. * PNG_STATIC
  181726. * (nothing) == PNG_USE_DLL
  181727. *
  181728. * CYGWIN (2002-01-20): The preceding is now obsolete. With the advent
  181729. * of auto-import in binutils, we no longer need to worry about
  181730. * __declspec(dllexport) / __declspec(dllimport) and friends. Therefore,
  181731. * we don't need to worry about PNG_STATIC or ALL_STATIC when it comes
  181732. * to __declspec() stuff. However, we DO need to worry about
  181733. * PNG_BUILD_DLL and PNG_STATIC because those change some defaults
  181734. * such as CONSOLE_IO and whether GLOBAL_ARRAYS are allowed.
  181735. */
  181736. #if defined(__CYGWIN__)
  181737. # if defined(ALL_STATIC)
  181738. # if defined(PNG_BUILD_DLL)
  181739. # undef PNG_BUILD_DLL
  181740. # endif
  181741. # if defined(PNG_USE_DLL)
  181742. # undef PNG_USE_DLL
  181743. # endif
  181744. # if defined(PNG_DLL)
  181745. # undef PNG_DLL
  181746. # endif
  181747. # if !defined(PNG_STATIC)
  181748. # define PNG_STATIC
  181749. # endif
  181750. # else
  181751. # if defined (PNG_BUILD_DLL)
  181752. # if defined(PNG_STATIC)
  181753. # undef PNG_STATIC
  181754. # endif
  181755. # if defined(PNG_USE_DLL)
  181756. # undef PNG_USE_DLL
  181757. # endif
  181758. # if !defined(PNG_DLL)
  181759. # define PNG_DLL
  181760. # endif
  181761. # else
  181762. # if defined(PNG_STATIC)
  181763. # if defined(PNG_USE_DLL)
  181764. # undef PNG_USE_DLL
  181765. # endif
  181766. # if defined(PNG_DLL)
  181767. # undef PNG_DLL
  181768. # endif
  181769. # else
  181770. # if !defined(PNG_USE_DLL)
  181771. # define PNG_USE_DLL
  181772. # endif
  181773. # if !defined(PNG_DLL)
  181774. # define PNG_DLL
  181775. # endif
  181776. # endif
  181777. # endif
  181778. # endif
  181779. #endif
  181780. /* This protects us against compilers that run on a windowing system
  181781. * and thus don't have or would rather us not use the stdio types:
  181782. * stdin, stdout, and stderr. The only one currently used is stderr
  181783. * in png_error() and png_warning(). #defining PNG_NO_CONSOLE_IO will
  181784. * prevent these from being compiled and used. #defining PNG_NO_STDIO
  181785. * will also prevent these, plus will prevent the entire set of stdio
  181786. * macros and functions (FILE *, printf, etc.) from being compiled and used,
  181787. * unless (PNG_DEBUG > 0) has been #defined.
  181788. *
  181789. * #define PNG_NO_CONSOLE_IO
  181790. * #define PNG_NO_STDIO
  181791. */
  181792. #if defined(_WIN32_WCE)
  181793. # include <windows.h>
  181794. /* Console I/O functions are not supported on WindowsCE */
  181795. # define PNG_NO_CONSOLE_IO
  181796. # ifdef PNG_DEBUG
  181797. # undef PNG_DEBUG
  181798. # endif
  181799. #endif
  181800. #ifdef PNG_BUILD_DLL
  181801. # ifndef PNG_CONSOLE_IO_SUPPORTED
  181802. # ifndef PNG_NO_CONSOLE_IO
  181803. # define PNG_NO_CONSOLE_IO
  181804. # endif
  181805. # endif
  181806. #endif
  181807. # ifdef PNG_NO_STDIO
  181808. # ifndef PNG_NO_CONSOLE_IO
  181809. # define PNG_NO_CONSOLE_IO
  181810. # endif
  181811. # ifdef PNG_DEBUG
  181812. # if (PNG_DEBUG > 0)
  181813. # include <stdio.h>
  181814. # endif
  181815. # endif
  181816. # else
  181817. # if !defined(_WIN32_WCE)
  181818. /* "stdio.h" functions are not supported on WindowsCE */
  181819. # include <stdio.h>
  181820. # endif
  181821. # endif
  181822. /* This macro protects us against machines that don't have function
  181823. * prototypes (ie K&R style headers). If your compiler does not handle
  181824. * function prototypes, define this macro and use the included ansi2knr.
  181825. * I've always been able to use _NO_PROTO as the indicator, but you may
  181826. * need to drag the empty declaration out in front of here, or change the
  181827. * ifdef to suit your own needs.
  181828. */
  181829. #ifndef PNGARG
  181830. #ifdef OF /* zlib prototype munger */
  181831. # define PNGARG(arglist) OF(arglist)
  181832. #else
  181833. #ifdef _NO_PROTO
  181834. # define PNGARG(arglist) ()
  181835. # ifndef PNG_TYPECAST_NULL
  181836. # define PNG_TYPECAST_NULL
  181837. # endif
  181838. #else
  181839. # define PNGARG(arglist) arglist
  181840. #endif /* _NO_PROTO */
  181841. #endif /* OF */
  181842. #endif /* PNGARG */
  181843. /* Try to determine if we are compiling on a Mac. Note that testing for
  181844. * just __MWERKS__ is not good enough, because the Codewarrior is now used
  181845. * on non-Mac platforms.
  181846. */
  181847. #ifndef MACOS
  181848. # if (defined(__MWERKS__) && defined(macintosh)) || defined(applec) || \
  181849. defined(THINK_C) || defined(__SC__) || defined(TARGET_OS_MAC)
  181850. # define MACOS
  181851. # endif
  181852. #endif
  181853. /* enough people need this for various reasons to include it here */
  181854. #if !defined(MACOS) && !defined(RISCOS) && !defined(_WIN32_WCE)
  181855. # include <sys/types.h>
  181856. #endif
  181857. #if !defined(PNG_SETJMP_NOT_SUPPORTED) && !defined(PNG_NO_SETJMP_SUPPORTED)
  181858. # define PNG_SETJMP_SUPPORTED
  181859. #endif
  181860. #ifdef PNG_SETJMP_SUPPORTED
  181861. /* This is an attempt to force a single setjmp behaviour on Linux. If
  181862. * the X config stuff didn't define _BSD_SOURCE we wouldn't need this.
  181863. */
  181864. # ifdef __linux__
  181865. # ifdef _BSD_SOURCE
  181866. # define PNG_SAVE_BSD_SOURCE
  181867. # undef _BSD_SOURCE
  181868. # endif
  181869. # ifdef _SETJMP_H
  181870. /* If you encounter a compiler error here, see the explanation
  181871. * near the end of INSTALL.
  181872. */
  181873. __png.h__ already includes setjmp.h;
  181874. __dont__ include it again.;
  181875. # endif
  181876. # endif /* __linux__ */
  181877. /* include setjmp.h for error handling */
  181878. # include <setjmp.h>
  181879. # ifdef __linux__
  181880. # ifdef PNG_SAVE_BSD_SOURCE
  181881. # define _BSD_SOURCE
  181882. # undef PNG_SAVE_BSD_SOURCE
  181883. # endif
  181884. # endif /* __linux__ */
  181885. #endif /* PNG_SETJMP_SUPPORTED */
  181886. #ifdef BSD
  181887. # include <strings.h>
  181888. #else
  181889. # include <string.h>
  181890. #endif
  181891. /* Other defines for things like memory and the like can go here. */
  181892. #ifdef PNG_INTERNAL
  181893. #include <stdlib.h>
  181894. /* The functions exported by PNG_EXTERN are PNG_INTERNAL functions, which
  181895. * aren't usually used outside the library (as far as I know), so it is
  181896. * debatable if they should be exported at all. In the future, when it is
  181897. * possible to have run-time registry of chunk-handling functions, some of
  181898. * these will be made available again.
  181899. #define PNG_EXTERN extern
  181900. */
  181901. #define PNG_EXTERN
  181902. /* Other defines specific to compilers can go here. Try to keep
  181903. * them inside an appropriate ifdef/endif pair for portability.
  181904. */
  181905. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  181906. # if defined(MACOS)
  181907. /* We need to check that <math.h> hasn't already been included earlier
  181908. * as it seems it doesn't agree with <fp.h>, yet we should really use
  181909. * <fp.h> if possible.
  181910. */
  181911. # if !defined(__MATH_H__) && !defined(__MATH_H) && !defined(__cmath__)
  181912. # include <fp.h>
  181913. # endif
  181914. # else
  181915. # include <math.h>
  181916. # endif
  181917. # if defined(_AMIGA) && defined(__SASC) && defined(_M68881)
  181918. /* Amiga SAS/C: We must include builtin FPU functions when compiling using
  181919. * MATH=68881
  181920. */
  181921. # include <m68881.h>
  181922. # endif
  181923. #endif
  181924. /* Codewarrior on NT has linking problems without this. */
  181925. #if (defined(__MWERKS__) && defined(WIN32)) || defined(__STDC__)
  181926. # define PNG_ALWAYS_EXTERN
  181927. #endif
  181928. /* This provides the non-ANSI (far) memory allocation routines. */
  181929. #if defined(__TURBOC__) && defined(__MSDOS__)
  181930. # include <mem.h>
  181931. # include <alloc.h>
  181932. #endif
  181933. /* I have no idea why is this necessary... */
  181934. #if defined(_MSC_VER) && (defined(WIN32) || defined(_Windows) || \
  181935. defined(_WINDOWS) || defined(_WIN32) || defined(__WIN32__))
  181936. # include <malloc.h>
  181937. #endif
  181938. /* This controls how fine the dithering gets. As this allocates
  181939. * a largish chunk of memory (32K), those who are not as concerned
  181940. * with dithering quality can decrease some or all of these.
  181941. */
  181942. #ifndef PNG_DITHER_RED_BITS
  181943. # define PNG_DITHER_RED_BITS 5
  181944. #endif
  181945. #ifndef PNG_DITHER_GREEN_BITS
  181946. # define PNG_DITHER_GREEN_BITS 5
  181947. #endif
  181948. #ifndef PNG_DITHER_BLUE_BITS
  181949. # define PNG_DITHER_BLUE_BITS 5
  181950. #endif
  181951. /* This controls how fine the gamma correction becomes when you
  181952. * are only interested in 8 bits anyway. Increasing this value
  181953. * results in more memory being used, and more pow() functions
  181954. * being called to fill in the gamma tables. Don't set this value
  181955. * less then 8, and even that may not work (I haven't tested it).
  181956. */
  181957. #ifndef PNG_MAX_GAMMA_8
  181958. # define PNG_MAX_GAMMA_8 11
  181959. #endif
  181960. /* This controls how much a difference in gamma we can tolerate before
  181961. * we actually start doing gamma conversion.
  181962. */
  181963. #ifndef PNG_GAMMA_THRESHOLD
  181964. # define PNG_GAMMA_THRESHOLD 0.05
  181965. #endif
  181966. #endif /* PNG_INTERNAL */
  181967. /* The following uses const char * instead of char * for error
  181968. * and warning message functions, so some compilers won't complain.
  181969. * If you do not want to use const, define PNG_NO_CONST here.
  181970. */
  181971. #ifndef PNG_NO_CONST
  181972. # define PNG_CONST const
  181973. #else
  181974. # define PNG_CONST
  181975. #endif
  181976. /* The following defines give you the ability to remove code from the
  181977. * library that you will not be using. I wish I could figure out how to
  181978. * automate this, but I can't do that without making it seriously hard
  181979. * on the users. So if you are not using an ability, change the #define
  181980. * to and #undef, and that part of the library will not be compiled. If
  181981. * your linker can't find a function, you may want to make sure the
  181982. * ability is defined here. Some of these depend upon some others being
  181983. * defined. I haven't figured out all the interactions here, so you may
  181984. * have to experiment awhile to get everything to compile. If you are
  181985. * creating or using a shared library, you probably shouldn't touch this,
  181986. * as it will affect the size of the structures, and this will cause bad
  181987. * things to happen if the library and/or application ever change.
  181988. */
  181989. /* Any features you will not be using can be undef'ed here */
  181990. /* GR-P, 0.96a: Set "*TRANSFORMS_SUPPORTED as default but allow user
  181991. * to turn it off with "*TRANSFORMS_NOT_SUPPORTED" or *PNG_NO_*_TRANSFORMS
  181992. * on the compile line, then pick and choose which ones to define without
  181993. * having to edit this file. It is safe to use the *TRANSFORMS_NOT_SUPPORTED
  181994. * if you only want to have a png-compliant reader/writer but don't need
  181995. * any of the extra transformations. This saves about 80 kbytes in a
  181996. * typical installation of the library. (PNG_NO_* form added in version
  181997. * 1.0.1c, for consistency)
  181998. */
  181999. /* The size of the png_text structure changed in libpng-1.0.6 when
  182000. * iTXt support was added. iTXt support was turned off by default through
  182001. * libpng-1.2.x, to support old apps that malloc the png_text structure
  182002. * instead of calling png_set_text() and letting libpng malloc it. It
  182003. * was turned on by default in libpng-1.3.0.
  182004. */
  182005. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182006. # ifndef PNG_NO_iTXt_SUPPORTED
  182007. # define PNG_NO_iTXt_SUPPORTED
  182008. # endif
  182009. # ifndef PNG_NO_READ_iTXt
  182010. # define PNG_NO_READ_iTXt
  182011. # endif
  182012. # ifndef PNG_NO_WRITE_iTXt
  182013. # define PNG_NO_WRITE_iTXt
  182014. # endif
  182015. #endif
  182016. #if !defined(PNG_NO_iTXt_SUPPORTED)
  182017. # if !defined(PNG_READ_iTXt_SUPPORTED) && !defined(PNG_NO_READ_iTXt)
  182018. # define PNG_READ_iTXt
  182019. # endif
  182020. # if !defined(PNG_WRITE_iTXt_SUPPORTED) && !defined(PNG_NO_WRITE_iTXt)
  182021. # define PNG_WRITE_iTXt
  182022. # endif
  182023. #endif
  182024. /* The following support, added after version 1.0.0, can be turned off here en
  182025. * masse by defining PNG_LEGACY_SUPPORTED in case you need binary compatibility
  182026. * with old applications that require the length of png_struct and png_info
  182027. * to remain unchanged.
  182028. */
  182029. #ifdef PNG_LEGACY_SUPPORTED
  182030. # define PNG_NO_FREE_ME
  182031. # define PNG_NO_READ_UNKNOWN_CHUNKS
  182032. # define PNG_NO_WRITE_UNKNOWN_CHUNKS
  182033. # define PNG_NO_READ_USER_CHUNKS
  182034. # define PNG_NO_READ_iCCP
  182035. # define PNG_NO_WRITE_iCCP
  182036. # define PNG_NO_READ_iTXt
  182037. # define PNG_NO_WRITE_iTXt
  182038. # define PNG_NO_READ_sCAL
  182039. # define PNG_NO_WRITE_sCAL
  182040. # define PNG_NO_READ_sPLT
  182041. # define PNG_NO_WRITE_sPLT
  182042. # define PNG_NO_INFO_IMAGE
  182043. # define PNG_NO_READ_RGB_TO_GRAY
  182044. # define PNG_NO_READ_USER_TRANSFORM
  182045. # define PNG_NO_WRITE_USER_TRANSFORM
  182046. # define PNG_NO_USER_MEM
  182047. # define PNG_NO_READ_EMPTY_PLTE
  182048. # define PNG_NO_MNG_FEATURES
  182049. # define PNG_NO_FIXED_POINT_SUPPORTED
  182050. #endif
  182051. /* Ignore attempt to turn off both floating and fixed point support */
  182052. #if !defined(PNG_FLOATING_POINT_SUPPORTED) || \
  182053. !defined(PNG_NO_FIXED_POINT_SUPPORTED)
  182054. # define PNG_FIXED_POINT_SUPPORTED
  182055. #endif
  182056. #ifndef PNG_NO_FREE_ME
  182057. # define PNG_FREE_ME_SUPPORTED
  182058. #endif
  182059. #if defined(PNG_READ_SUPPORTED)
  182060. #if !defined(PNG_READ_TRANSFORMS_NOT_SUPPORTED) && \
  182061. !defined(PNG_NO_READ_TRANSFORMS)
  182062. # define PNG_READ_TRANSFORMS_SUPPORTED
  182063. #endif
  182064. #ifdef PNG_READ_TRANSFORMS_SUPPORTED
  182065. # ifndef PNG_NO_READ_EXPAND
  182066. # define PNG_READ_EXPAND_SUPPORTED
  182067. # endif
  182068. # ifndef PNG_NO_READ_SHIFT
  182069. # define PNG_READ_SHIFT_SUPPORTED
  182070. # endif
  182071. # ifndef PNG_NO_READ_PACK
  182072. # define PNG_READ_PACK_SUPPORTED
  182073. # endif
  182074. # ifndef PNG_NO_READ_BGR
  182075. # define PNG_READ_BGR_SUPPORTED
  182076. # endif
  182077. # ifndef PNG_NO_READ_SWAP
  182078. # define PNG_READ_SWAP_SUPPORTED
  182079. # endif
  182080. # ifndef PNG_NO_READ_PACKSWAP
  182081. # define PNG_READ_PACKSWAP_SUPPORTED
  182082. # endif
  182083. # ifndef PNG_NO_READ_INVERT
  182084. # define PNG_READ_INVERT_SUPPORTED
  182085. # endif
  182086. # ifndef PNG_NO_READ_DITHER
  182087. # define PNG_READ_DITHER_SUPPORTED
  182088. # endif
  182089. # ifndef PNG_NO_READ_BACKGROUND
  182090. # define PNG_READ_BACKGROUND_SUPPORTED
  182091. # endif
  182092. # ifndef PNG_NO_READ_16_TO_8
  182093. # define PNG_READ_16_TO_8_SUPPORTED
  182094. # endif
  182095. # ifndef PNG_NO_READ_FILLER
  182096. # define PNG_READ_FILLER_SUPPORTED
  182097. # endif
  182098. # ifndef PNG_NO_READ_GAMMA
  182099. # define PNG_READ_GAMMA_SUPPORTED
  182100. # endif
  182101. # ifndef PNG_NO_READ_GRAY_TO_RGB
  182102. # define PNG_READ_GRAY_TO_RGB_SUPPORTED
  182103. # endif
  182104. # ifndef PNG_NO_READ_SWAP_ALPHA
  182105. # define PNG_READ_SWAP_ALPHA_SUPPORTED
  182106. # endif
  182107. # ifndef PNG_NO_READ_INVERT_ALPHA
  182108. # define PNG_READ_INVERT_ALPHA_SUPPORTED
  182109. # endif
  182110. # ifndef PNG_NO_READ_STRIP_ALPHA
  182111. # define PNG_READ_STRIP_ALPHA_SUPPORTED
  182112. # endif
  182113. # ifndef PNG_NO_READ_USER_TRANSFORM
  182114. # define PNG_READ_USER_TRANSFORM_SUPPORTED
  182115. # endif
  182116. # ifndef PNG_NO_READ_RGB_TO_GRAY
  182117. # define PNG_READ_RGB_TO_GRAY_SUPPORTED
  182118. # endif
  182119. #endif /* PNG_READ_TRANSFORMS_SUPPORTED */
  182120. #if !defined(PNG_NO_PROGRESSIVE_READ) && \
  182121. !defined(PNG_PROGRESSIVE_READ_SUPPORTED) /* if you don't do progressive */
  182122. # define PNG_PROGRESSIVE_READ_SUPPORTED /* reading. This is not talking */
  182123. #endif /* about interlacing capability! You'll */
  182124. /* still have interlacing unless you change the following line: */
  182125. #define PNG_READ_INTERLACING_SUPPORTED /* required in PNG-compliant decoders */
  182126. #ifndef PNG_NO_READ_COMPOSITE_NODIV
  182127. # ifndef PNG_NO_READ_COMPOSITED_NODIV /* libpng-1.0.x misspelling */
  182128. # define PNG_READ_COMPOSITE_NODIV_SUPPORTED /* well tested on Intel, SGI */
  182129. # endif
  182130. #endif
  182131. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182132. /* Deprecated, will be removed from version 2.0.0.
  182133. Use PNG_MNG_FEATURES_SUPPORTED instead. */
  182134. #ifndef PNG_NO_READ_EMPTY_PLTE
  182135. # define PNG_READ_EMPTY_PLTE_SUPPORTED
  182136. #endif
  182137. #endif
  182138. #endif /* PNG_READ_SUPPORTED */
  182139. #if defined(PNG_WRITE_SUPPORTED)
  182140. # if !defined(PNG_WRITE_TRANSFORMS_NOT_SUPPORTED) && \
  182141. !defined(PNG_NO_WRITE_TRANSFORMS)
  182142. # define PNG_WRITE_TRANSFORMS_SUPPORTED
  182143. #endif
  182144. #ifdef PNG_WRITE_TRANSFORMS_SUPPORTED
  182145. # ifndef PNG_NO_WRITE_SHIFT
  182146. # define PNG_WRITE_SHIFT_SUPPORTED
  182147. # endif
  182148. # ifndef PNG_NO_WRITE_PACK
  182149. # define PNG_WRITE_PACK_SUPPORTED
  182150. # endif
  182151. # ifndef PNG_NO_WRITE_BGR
  182152. # define PNG_WRITE_BGR_SUPPORTED
  182153. # endif
  182154. # ifndef PNG_NO_WRITE_SWAP
  182155. # define PNG_WRITE_SWAP_SUPPORTED
  182156. # endif
  182157. # ifndef PNG_NO_WRITE_PACKSWAP
  182158. # define PNG_WRITE_PACKSWAP_SUPPORTED
  182159. # endif
  182160. # ifndef PNG_NO_WRITE_INVERT
  182161. # define PNG_WRITE_INVERT_SUPPORTED
  182162. # endif
  182163. # ifndef PNG_NO_WRITE_FILLER
  182164. # define PNG_WRITE_FILLER_SUPPORTED /* same as WRITE_STRIP_ALPHA */
  182165. # endif
  182166. # ifndef PNG_NO_WRITE_SWAP_ALPHA
  182167. # define PNG_WRITE_SWAP_ALPHA_SUPPORTED
  182168. # endif
  182169. # ifndef PNG_NO_WRITE_INVERT_ALPHA
  182170. # define PNG_WRITE_INVERT_ALPHA_SUPPORTED
  182171. # endif
  182172. # ifndef PNG_NO_WRITE_USER_TRANSFORM
  182173. # define PNG_WRITE_USER_TRANSFORM_SUPPORTED
  182174. # endif
  182175. #endif /* PNG_WRITE_TRANSFORMS_SUPPORTED */
  182176. #if !defined(PNG_NO_WRITE_INTERLACING_SUPPORTED) && \
  182177. !defined(PNG_WRITE_INTERLACING_SUPPORTED)
  182178. #define PNG_WRITE_INTERLACING_SUPPORTED /* not required for PNG-compliant
  182179. encoders, but can cause trouble
  182180. if left undefined */
  182181. #endif
  182182. #if !defined(PNG_NO_WRITE_WEIGHTED_FILTER) && \
  182183. !defined(PNG_WRITE_WEIGHTED_FILTER) && \
  182184. defined(PNG_FLOATING_POINT_SUPPORTED)
  182185. # define PNG_WRITE_WEIGHTED_FILTER_SUPPORTED
  182186. #endif
  182187. #ifndef PNG_NO_WRITE_FLUSH
  182188. # define PNG_WRITE_FLUSH_SUPPORTED
  182189. #endif
  182190. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  182191. /* Deprecated, see PNG_MNG_FEATURES_SUPPORTED, above */
  182192. #ifndef PNG_NO_WRITE_EMPTY_PLTE
  182193. # define PNG_WRITE_EMPTY_PLTE_SUPPORTED
  182194. #endif
  182195. #endif
  182196. #endif /* PNG_WRITE_SUPPORTED */
  182197. #ifndef PNG_1_0_X
  182198. # ifndef PNG_NO_ERROR_NUMBERS
  182199. # define PNG_ERROR_NUMBERS_SUPPORTED
  182200. # endif
  182201. #endif /* PNG_1_0_X */
  182202. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  182203. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  182204. # ifndef PNG_NO_USER_TRANSFORM_PTR
  182205. # define PNG_USER_TRANSFORM_PTR_SUPPORTED
  182206. # endif
  182207. #endif
  182208. #ifndef PNG_NO_STDIO
  182209. # define PNG_TIME_RFC1123_SUPPORTED
  182210. #endif
  182211. /* This adds extra functions in pngget.c for accessing data from the
  182212. * info pointer (added in version 0.99)
  182213. * png_get_image_width()
  182214. * png_get_image_height()
  182215. * png_get_bit_depth()
  182216. * png_get_color_type()
  182217. * png_get_compression_type()
  182218. * png_get_filter_type()
  182219. * png_get_interlace_type()
  182220. * png_get_pixel_aspect_ratio()
  182221. * png_get_pixels_per_meter()
  182222. * png_get_x_offset_pixels()
  182223. * png_get_y_offset_pixels()
  182224. * png_get_x_offset_microns()
  182225. * png_get_y_offset_microns()
  182226. */
  182227. #if !defined(PNG_NO_EASY_ACCESS) && !defined(PNG_EASY_ACCESS_SUPPORTED)
  182228. # define PNG_EASY_ACCESS_SUPPORTED
  182229. #endif
  182230. /* PNG_ASSEMBLER_CODE was enabled by default in version 1.2.0
  182231. * and removed from version 1.2.20. The following will be removed
  182232. * from libpng-1.4.0
  182233. */
  182234. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_OPTIMIZED_CODE)
  182235. # ifndef PNG_OPTIMIZED_CODE_SUPPORTED
  182236. # define PNG_OPTIMIZED_CODE_SUPPORTED
  182237. # endif
  182238. #endif
  182239. #if defined(PNG_READ_SUPPORTED) && !defined(PNG_NO_ASSEMBLER_CODE)
  182240. # ifndef PNG_ASSEMBLER_CODE_SUPPORTED
  182241. # define PNG_ASSEMBLER_CODE_SUPPORTED
  182242. # endif
  182243. # if defined(__GNUC__) && defined(__x86_64__) && (__GNUC__ < 4)
  182244. /* work around 64-bit gcc compiler bugs in gcc-3.x */
  182245. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  182246. # define PNG_NO_MMX_CODE
  182247. # endif
  182248. # endif
  182249. # if defined(__APPLE__)
  182250. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  182251. # define PNG_NO_MMX_CODE
  182252. # endif
  182253. # endif
  182254. # if (defined(__MWERKS__) && ((__MWERKS__ < 0x0900) || macintosh))
  182255. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  182256. # define PNG_NO_MMX_CODE
  182257. # endif
  182258. # endif
  182259. # if !defined(PNG_MMX_CODE_SUPPORTED) && !defined(PNG_NO_MMX_CODE)
  182260. # define PNG_MMX_CODE_SUPPORTED
  182261. # endif
  182262. #endif
  182263. /* end of obsolete code to be removed from libpng-1.4.0 */
  182264. #if !defined(PNG_1_0_X)
  182265. #if !defined(PNG_NO_USER_MEM) && !defined(PNG_USER_MEM_SUPPORTED)
  182266. # define PNG_USER_MEM_SUPPORTED
  182267. #endif
  182268. #endif /* PNG_1_0_X */
  182269. /* Added at libpng-1.2.6 */
  182270. #if !defined(PNG_1_0_X)
  182271. #ifndef PNG_SET_USER_LIMITS_SUPPORTED
  182272. #if !defined(PNG_NO_SET_USER_LIMITS) && !defined(PNG_SET_USER_LIMITS_SUPPORTED)
  182273. # define PNG_SET_USER_LIMITS_SUPPORTED
  182274. #endif
  182275. #endif
  182276. #endif /* PNG_1_0_X */
  182277. /* Added at libpng-1.0.16 and 1.2.6. To accept all valid PNGS no matter
  182278. * how large, set these limits to 0x7fffffffL
  182279. */
  182280. #ifndef PNG_USER_WIDTH_MAX
  182281. # define PNG_USER_WIDTH_MAX 1000000L
  182282. #endif
  182283. #ifndef PNG_USER_HEIGHT_MAX
  182284. # define PNG_USER_HEIGHT_MAX 1000000L
  182285. #endif
  182286. /* These are currently experimental features, define them if you want */
  182287. /* very little testing */
  182288. /*
  182289. #ifdef PNG_READ_SUPPORTED
  182290. # ifndef PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  182291. # define PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED
  182292. # endif
  182293. #endif
  182294. */
  182295. /* This is only for PowerPC big-endian and 680x0 systems */
  182296. /* some testing */
  182297. /*
  182298. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  182299. # define PNG_READ_BIG_ENDIAN_SUPPORTED
  182300. #endif
  182301. */
  182302. /* Buggy compilers (e.g., gcc 2.7.2.2) need this */
  182303. /*
  182304. #define PNG_NO_POINTER_INDEXING
  182305. */
  182306. /* These functions are turned off by default, as they will be phased out. */
  182307. /*
  182308. #define PNG_USELESS_TESTS_SUPPORTED
  182309. #define PNG_CORRECT_PALETTE_SUPPORTED
  182310. */
  182311. /* Any chunks you are not interested in, you can undef here. The
  182312. * ones that allocate memory may be expecially important (hIST,
  182313. * tEXt, zTXt, tRNS, pCAL). Others will just save time and make png_info
  182314. * a bit smaller.
  182315. */
  182316. #if defined(PNG_READ_SUPPORTED) && \
  182317. !defined(PNG_READ_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  182318. !defined(PNG_NO_READ_ANCILLARY_CHUNKS)
  182319. # define PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  182320. #endif
  182321. #if defined(PNG_WRITE_SUPPORTED) && \
  182322. !defined(PNG_WRITE_ANCILLARY_CHUNKS_NOT_SUPPORTED) && \
  182323. !defined(PNG_NO_WRITE_ANCILLARY_CHUNKS)
  182324. # define PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  182325. #endif
  182326. #ifdef PNG_READ_ANCILLARY_CHUNKS_SUPPORTED
  182327. #ifdef PNG_NO_READ_TEXT
  182328. # define PNG_NO_READ_iTXt
  182329. # define PNG_NO_READ_tEXt
  182330. # define PNG_NO_READ_zTXt
  182331. #endif
  182332. #ifndef PNG_NO_READ_bKGD
  182333. # define PNG_READ_bKGD_SUPPORTED
  182334. # define PNG_bKGD_SUPPORTED
  182335. #endif
  182336. #ifndef PNG_NO_READ_cHRM
  182337. # define PNG_READ_cHRM_SUPPORTED
  182338. # define PNG_cHRM_SUPPORTED
  182339. #endif
  182340. #ifndef PNG_NO_READ_gAMA
  182341. # define PNG_READ_gAMA_SUPPORTED
  182342. # define PNG_gAMA_SUPPORTED
  182343. #endif
  182344. #ifndef PNG_NO_READ_hIST
  182345. # define PNG_READ_hIST_SUPPORTED
  182346. # define PNG_hIST_SUPPORTED
  182347. #endif
  182348. #ifndef PNG_NO_READ_iCCP
  182349. # define PNG_READ_iCCP_SUPPORTED
  182350. # define PNG_iCCP_SUPPORTED
  182351. #endif
  182352. #ifndef PNG_NO_READ_iTXt
  182353. # ifndef PNG_READ_iTXt_SUPPORTED
  182354. # define PNG_READ_iTXt_SUPPORTED
  182355. # endif
  182356. # ifndef PNG_iTXt_SUPPORTED
  182357. # define PNG_iTXt_SUPPORTED
  182358. # endif
  182359. #endif
  182360. #ifndef PNG_NO_READ_oFFs
  182361. # define PNG_READ_oFFs_SUPPORTED
  182362. # define PNG_oFFs_SUPPORTED
  182363. #endif
  182364. #ifndef PNG_NO_READ_pCAL
  182365. # define PNG_READ_pCAL_SUPPORTED
  182366. # define PNG_pCAL_SUPPORTED
  182367. #endif
  182368. #ifndef PNG_NO_READ_sCAL
  182369. # define PNG_READ_sCAL_SUPPORTED
  182370. # define PNG_sCAL_SUPPORTED
  182371. #endif
  182372. #ifndef PNG_NO_READ_pHYs
  182373. # define PNG_READ_pHYs_SUPPORTED
  182374. # define PNG_pHYs_SUPPORTED
  182375. #endif
  182376. #ifndef PNG_NO_READ_sBIT
  182377. # define PNG_READ_sBIT_SUPPORTED
  182378. # define PNG_sBIT_SUPPORTED
  182379. #endif
  182380. #ifndef PNG_NO_READ_sPLT
  182381. # define PNG_READ_sPLT_SUPPORTED
  182382. # define PNG_sPLT_SUPPORTED
  182383. #endif
  182384. #ifndef PNG_NO_READ_sRGB
  182385. # define PNG_READ_sRGB_SUPPORTED
  182386. # define PNG_sRGB_SUPPORTED
  182387. #endif
  182388. #ifndef PNG_NO_READ_tEXt
  182389. # define PNG_READ_tEXt_SUPPORTED
  182390. # define PNG_tEXt_SUPPORTED
  182391. #endif
  182392. #ifndef PNG_NO_READ_tIME
  182393. # define PNG_READ_tIME_SUPPORTED
  182394. # define PNG_tIME_SUPPORTED
  182395. #endif
  182396. #ifndef PNG_NO_READ_tRNS
  182397. # define PNG_READ_tRNS_SUPPORTED
  182398. # define PNG_tRNS_SUPPORTED
  182399. #endif
  182400. #ifndef PNG_NO_READ_zTXt
  182401. # define PNG_READ_zTXt_SUPPORTED
  182402. # define PNG_zTXt_SUPPORTED
  182403. #endif
  182404. #ifndef PNG_NO_READ_UNKNOWN_CHUNKS
  182405. # define PNG_READ_UNKNOWN_CHUNKS_SUPPORTED
  182406. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  182407. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  182408. # endif
  182409. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  182410. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182411. # endif
  182412. #endif
  182413. #if !defined(PNG_NO_READ_USER_CHUNKS) && \
  182414. defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  182415. # define PNG_READ_USER_CHUNKS_SUPPORTED
  182416. # define PNG_USER_CHUNKS_SUPPORTED
  182417. # ifdef PNG_NO_READ_UNKNOWN_CHUNKS
  182418. # undef PNG_NO_READ_UNKNOWN_CHUNKS
  182419. # endif
  182420. # ifdef PNG_NO_HANDLE_AS_UNKNOWN
  182421. # undef PNG_NO_HANDLE_AS_UNKNOWN
  182422. # endif
  182423. #endif
  182424. #ifndef PNG_NO_READ_OPT_PLTE
  182425. # define PNG_READ_OPT_PLTE_SUPPORTED /* only affects support of the */
  182426. #endif /* optional PLTE chunk in RGB and RGBA images */
  182427. #if defined(PNG_READ_iTXt_SUPPORTED) || defined(PNG_READ_tEXt_SUPPORTED) || \
  182428. defined(PNG_READ_zTXt_SUPPORTED)
  182429. # define PNG_READ_TEXT_SUPPORTED
  182430. # define PNG_TEXT_SUPPORTED
  182431. #endif
  182432. #endif /* PNG_READ_ANCILLARY_CHUNKS_SUPPORTED */
  182433. #ifdef PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED
  182434. #ifdef PNG_NO_WRITE_TEXT
  182435. # define PNG_NO_WRITE_iTXt
  182436. # define PNG_NO_WRITE_tEXt
  182437. # define PNG_NO_WRITE_zTXt
  182438. #endif
  182439. #ifndef PNG_NO_WRITE_bKGD
  182440. # define PNG_WRITE_bKGD_SUPPORTED
  182441. # ifndef PNG_bKGD_SUPPORTED
  182442. # define PNG_bKGD_SUPPORTED
  182443. # endif
  182444. #endif
  182445. #ifndef PNG_NO_WRITE_cHRM
  182446. # define PNG_WRITE_cHRM_SUPPORTED
  182447. # ifndef PNG_cHRM_SUPPORTED
  182448. # define PNG_cHRM_SUPPORTED
  182449. # endif
  182450. #endif
  182451. #ifndef PNG_NO_WRITE_gAMA
  182452. # define PNG_WRITE_gAMA_SUPPORTED
  182453. # ifndef PNG_gAMA_SUPPORTED
  182454. # define PNG_gAMA_SUPPORTED
  182455. # endif
  182456. #endif
  182457. #ifndef PNG_NO_WRITE_hIST
  182458. # define PNG_WRITE_hIST_SUPPORTED
  182459. # ifndef PNG_hIST_SUPPORTED
  182460. # define PNG_hIST_SUPPORTED
  182461. # endif
  182462. #endif
  182463. #ifndef PNG_NO_WRITE_iCCP
  182464. # define PNG_WRITE_iCCP_SUPPORTED
  182465. # ifndef PNG_iCCP_SUPPORTED
  182466. # define PNG_iCCP_SUPPORTED
  182467. # endif
  182468. #endif
  182469. #ifndef PNG_NO_WRITE_iTXt
  182470. # ifndef PNG_WRITE_iTXt_SUPPORTED
  182471. # define PNG_WRITE_iTXt_SUPPORTED
  182472. # endif
  182473. # ifndef PNG_iTXt_SUPPORTED
  182474. # define PNG_iTXt_SUPPORTED
  182475. # endif
  182476. #endif
  182477. #ifndef PNG_NO_WRITE_oFFs
  182478. # define PNG_WRITE_oFFs_SUPPORTED
  182479. # ifndef PNG_oFFs_SUPPORTED
  182480. # define PNG_oFFs_SUPPORTED
  182481. # endif
  182482. #endif
  182483. #ifndef PNG_NO_WRITE_pCAL
  182484. # define PNG_WRITE_pCAL_SUPPORTED
  182485. # ifndef PNG_pCAL_SUPPORTED
  182486. # define PNG_pCAL_SUPPORTED
  182487. # endif
  182488. #endif
  182489. #ifndef PNG_NO_WRITE_sCAL
  182490. # define PNG_WRITE_sCAL_SUPPORTED
  182491. # ifndef PNG_sCAL_SUPPORTED
  182492. # define PNG_sCAL_SUPPORTED
  182493. # endif
  182494. #endif
  182495. #ifndef PNG_NO_WRITE_pHYs
  182496. # define PNG_WRITE_pHYs_SUPPORTED
  182497. # ifndef PNG_pHYs_SUPPORTED
  182498. # define PNG_pHYs_SUPPORTED
  182499. # endif
  182500. #endif
  182501. #ifndef PNG_NO_WRITE_sBIT
  182502. # define PNG_WRITE_sBIT_SUPPORTED
  182503. # ifndef PNG_sBIT_SUPPORTED
  182504. # define PNG_sBIT_SUPPORTED
  182505. # endif
  182506. #endif
  182507. #ifndef PNG_NO_WRITE_sPLT
  182508. # define PNG_WRITE_sPLT_SUPPORTED
  182509. # ifndef PNG_sPLT_SUPPORTED
  182510. # define PNG_sPLT_SUPPORTED
  182511. # endif
  182512. #endif
  182513. #ifndef PNG_NO_WRITE_sRGB
  182514. # define PNG_WRITE_sRGB_SUPPORTED
  182515. # ifndef PNG_sRGB_SUPPORTED
  182516. # define PNG_sRGB_SUPPORTED
  182517. # endif
  182518. #endif
  182519. #ifndef PNG_NO_WRITE_tEXt
  182520. # define PNG_WRITE_tEXt_SUPPORTED
  182521. # ifndef PNG_tEXt_SUPPORTED
  182522. # define PNG_tEXt_SUPPORTED
  182523. # endif
  182524. #endif
  182525. #ifndef PNG_NO_WRITE_tIME
  182526. # define PNG_WRITE_tIME_SUPPORTED
  182527. # ifndef PNG_tIME_SUPPORTED
  182528. # define PNG_tIME_SUPPORTED
  182529. # endif
  182530. #endif
  182531. #ifndef PNG_NO_WRITE_tRNS
  182532. # define PNG_WRITE_tRNS_SUPPORTED
  182533. # ifndef PNG_tRNS_SUPPORTED
  182534. # define PNG_tRNS_SUPPORTED
  182535. # endif
  182536. #endif
  182537. #ifndef PNG_NO_WRITE_zTXt
  182538. # define PNG_WRITE_zTXt_SUPPORTED
  182539. # ifndef PNG_zTXt_SUPPORTED
  182540. # define PNG_zTXt_SUPPORTED
  182541. # endif
  182542. #endif
  182543. #ifndef PNG_NO_WRITE_UNKNOWN_CHUNKS
  182544. # define PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED
  182545. # ifndef PNG_UNKNOWN_CHUNKS_SUPPORTED
  182546. # define PNG_UNKNOWN_CHUNKS_SUPPORTED
  182547. # endif
  182548. # ifndef PNG_NO_HANDLE_AS_UNKNOWN
  182549. # ifndef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182550. # define PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  182551. # endif
  182552. # endif
  182553. #endif
  182554. #if defined(PNG_WRITE_iTXt_SUPPORTED) || defined(PNG_WRITE_tEXt_SUPPORTED) || \
  182555. defined(PNG_WRITE_zTXt_SUPPORTED)
  182556. # define PNG_WRITE_TEXT_SUPPORTED
  182557. # ifndef PNG_TEXT_SUPPORTED
  182558. # define PNG_TEXT_SUPPORTED
  182559. # endif
  182560. #endif
  182561. #endif /* PNG_WRITE_ANCILLARY_CHUNKS_SUPPORTED */
  182562. /* Turn this off to disable png_read_png() and
  182563. * png_write_png() and leave the row_pointers member
  182564. * out of the info structure.
  182565. */
  182566. #ifndef PNG_NO_INFO_IMAGE
  182567. # define PNG_INFO_IMAGE_SUPPORTED
  182568. #endif
  182569. /* need the time information for reading tIME chunks */
  182570. #if defined(PNG_tIME_SUPPORTED)
  182571. # if !defined(_WIN32_WCE)
  182572. /* "time.h" functions are not supported on WindowsCE */
  182573. # include <time.h>
  182574. # endif
  182575. #endif
  182576. /* Some typedefs to get us started. These should be safe on most of the
  182577. * common platforms. The typedefs should be at least as large as the
  182578. * numbers suggest (a png_uint_32 must be at least 32 bits long), but they
  182579. * don't have to be exactly that size. Some compilers dislike passing
  182580. * unsigned shorts as function parameters, so you may be better off using
  182581. * unsigned int for png_uint_16. Likewise, for 64-bit systems, you may
  182582. * want to have unsigned int for png_uint_32 instead of unsigned long.
  182583. */
  182584. typedef unsigned long png_uint_32;
  182585. typedef long png_int_32;
  182586. typedef unsigned short png_uint_16;
  182587. typedef short png_int_16;
  182588. typedef unsigned char png_byte;
  182589. /* This is usually size_t. It is typedef'ed just in case you need it to
  182590. change (I'm not sure if you will or not, so I thought I'd be safe) */
  182591. #ifdef PNG_SIZE_T
  182592. typedef PNG_SIZE_T png_size_t;
  182593. # define png_sizeof(x) png_convert_size(sizeof (x))
  182594. #else
  182595. typedef size_t png_size_t;
  182596. # define png_sizeof(x) sizeof (x)
  182597. #endif
  182598. /* The following is needed for medium model support. It cannot be in the
  182599. * PNG_INTERNAL section. Needs modification for other compilers besides
  182600. * MSC. Model independent support declares all arrays and pointers to be
  182601. * large using the far keyword. The zlib version used must also support
  182602. * model independent data. As of version zlib 1.0.4, the necessary changes
  182603. * have been made in zlib. The USE_FAR_KEYWORD define triggers other
  182604. * changes that are needed. (Tim Wegner)
  182605. */
  182606. /* Separate compiler dependencies (problem here is that zlib.h always
  182607. defines FAR. (SJT) */
  182608. #ifdef __BORLANDC__
  182609. # if defined(__LARGE__) || defined(__HUGE__) || defined(__COMPACT__)
  182610. # define LDATA 1
  182611. # else
  182612. # define LDATA 0
  182613. # endif
  182614. /* GRR: why is Cygwin in here? Cygwin is not Borland C... */
  182615. # if !defined(__WIN32__) && !defined(__FLAT__) && !defined(__CYGWIN__)
  182616. # define PNG_MAX_MALLOC_64K
  182617. # if (LDATA != 1)
  182618. # ifndef FAR
  182619. # define FAR __far
  182620. # endif
  182621. # define USE_FAR_KEYWORD
  182622. # endif /* LDATA != 1 */
  182623. /* Possibly useful for moving data out of default segment.
  182624. * Uncomment it if you want. Could also define FARDATA as
  182625. * const if your compiler supports it. (SJT)
  182626. # define FARDATA FAR
  182627. */
  182628. # endif /* __WIN32__, __FLAT__, __CYGWIN__ */
  182629. #endif /* __BORLANDC__ */
  182630. /* Suggest testing for specific compiler first before testing for
  182631. * FAR. The Watcom compiler defines both __MEDIUM__ and M_I86MM,
  182632. * making reliance oncertain keywords suspect. (SJT)
  182633. */
  182634. /* MSC Medium model */
  182635. #if defined(FAR)
  182636. # if defined(M_I86MM)
  182637. # define USE_FAR_KEYWORD
  182638. # define FARDATA FAR
  182639. # include <dos.h>
  182640. # endif
  182641. #endif
  182642. /* SJT: default case */
  182643. #ifndef FAR
  182644. # define FAR
  182645. #endif
  182646. /* At this point FAR is always defined */
  182647. #ifndef FARDATA
  182648. # define FARDATA
  182649. #endif
  182650. /* Typedef for floating-point numbers that are converted
  182651. to fixed-point with a multiple of 100,000, e.g., int_gamma */
  182652. typedef png_int_32 png_fixed_point;
  182653. /* Add typedefs for pointers */
  182654. typedef void FAR * png_voidp;
  182655. typedef png_byte FAR * png_bytep;
  182656. typedef png_uint_32 FAR * png_uint_32p;
  182657. typedef png_int_32 FAR * png_int_32p;
  182658. typedef png_uint_16 FAR * png_uint_16p;
  182659. typedef png_int_16 FAR * png_int_16p;
  182660. typedef PNG_CONST char FAR * png_const_charp;
  182661. typedef char FAR * png_charp;
  182662. typedef png_fixed_point FAR * png_fixed_point_p;
  182663. #ifndef PNG_NO_STDIO
  182664. #if defined(_WIN32_WCE)
  182665. typedef HANDLE png_FILE_p;
  182666. #else
  182667. typedef FILE * png_FILE_p;
  182668. #endif
  182669. #endif
  182670. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182671. typedef double FAR * png_doublep;
  182672. #endif
  182673. /* Pointers to pointers; i.e. arrays */
  182674. typedef png_byte FAR * FAR * png_bytepp;
  182675. typedef png_uint_32 FAR * FAR * png_uint_32pp;
  182676. typedef png_int_32 FAR * FAR * png_int_32pp;
  182677. typedef png_uint_16 FAR * FAR * png_uint_16pp;
  182678. typedef png_int_16 FAR * FAR * png_int_16pp;
  182679. typedef PNG_CONST char FAR * FAR * png_const_charpp;
  182680. typedef char FAR * FAR * png_charpp;
  182681. typedef png_fixed_point FAR * FAR * png_fixed_point_pp;
  182682. #ifdef PNG_FLOATING_POINT_SUPPORTED
  182683. typedef double FAR * FAR * png_doublepp;
  182684. #endif
  182685. /* Pointers to pointers to pointers; i.e., pointer to array */
  182686. typedef char FAR * FAR * FAR * png_charppp;
  182687. #if 0
  182688. /* SPC - Is this stuff deprecated? */
  182689. /* It'll be removed as of libpng-1.3.0 - GR-P */
  182690. /* libpng typedefs for types in zlib. If zlib changes
  182691. * or another compression library is used, then change these.
  182692. * Eliminates need to change all the source files.
  182693. */
  182694. typedef charf * png_zcharp;
  182695. typedef charf * FAR * png_zcharpp;
  182696. typedef z_stream FAR * png_zstreamp;
  182697. #endif /* (PNG_1_0_X) || defined(PNG_1_2_X) */
  182698. /*
  182699. * Define PNG_BUILD_DLL if the module being built is a Windows
  182700. * LIBPNG DLL.
  182701. *
  182702. * Define PNG_USE_DLL if you want to *link* to the Windows LIBPNG DLL.
  182703. * It is equivalent to Microsoft predefined macro _DLL that is
  182704. * automatically defined when you compile using the share
  182705. * version of the CRT (C Run-Time library)
  182706. *
  182707. * The cygwin mods make this behavior a little different:
  182708. * Define PNG_BUILD_DLL if you are building a dll for use with cygwin
  182709. * Define PNG_STATIC if you are building a static library for use with cygwin,
  182710. * -or- if you are building an application that you want to link to the
  182711. * static library.
  182712. * PNG_USE_DLL is defined by default (no user action needed) unless one of
  182713. * the other flags is defined.
  182714. */
  182715. #if !defined(PNG_DLL) && (defined(PNG_BUILD_DLL) || defined(PNG_USE_DLL))
  182716. # define PNG_DLL
  182717. #endif
  182718. /* If CYGWIN, then disallow GLOBAL ARRAYS unless building a static lib.
  182719. * When building a static lib, default to no GLOBAL ARRAYS, but allow
  182720. * command-line override
  182721. */
  182722. #if defined(__CYGWIN__)
  182723. # if !defined(PNG_STATIC)
  182724. # if defined(PNG_USE_GLOBAL_ARRAYS)
  182725. # undef PNG_USE_GLOBAL_ARRAYS
  182726. # endif
  182727. # if !defined(PNG_USE_LOCAL_ARRAYS)
  182728. # define PNG_USE_LOCAL_ARRAYS
  182729. # endif
  182730. # else
  182731. # if defined(PNG_USE_LOCAL_ARRAYS) || defined(PNG_NO_GLOBAL_ARRAYS)
  182732. # if defined(PNG_USE_GLOBAL_ARRAYS)
  182733. # undef PNG_USE_GLOBAL_ARRAYS
  182734. # endif
  182735. # endif
  182736. # endif
  182737. # if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  182738. # define PNG_USE_LOCAL_ARRAYS
  182739. # endif
  182740. #endif
  182741. /* Do not use global arrays (helps with building DLL's)
  182742. * They are no longer used in libpng itself, since version 1.0.5c,
  182743. * but might be required for some pre-1.0.5c applications.
  182744. */
  182745. #if !defined(PNG_USE_LOCAL_ARRAYS) && !defined(PNG_USE_GLOBAL_ARRAYS)
  182746. # if defined(PNG_NO_GLOBAL_ARRAYS) || \
  182747. (defined(__GNUC__) && defined(PNG_DLL)) || defined(_MSC_VER)
  182748. # define PNG_USE_LOCAL_ARRAYS
  182749. # else
  182750. # define PNG_USE_GLOBAL_ARRAYS
  182751. # endif
  182752. #endif
  182753. #if defined(__CYGWIN__)
  182754. # undef PNGAPI
  182755. # define PNGAPI __cdecl
  182756. # undef PNG_IMPEXP
  182757. # define PNG_IMPEXP
  182758. #endif
  182759. /* If you define PNGAPI, e.g., with compiler option "-DPNGAPI=__stdcall",
  182760. * you may get warnings regarding the linkage of png_zalloc and png_zfree.
  182761. * Don't ignore those warnings; you must also reset the default calling
  182762. * convention in your compiler to match your PNGAPI, and you must build
  182763. * zlib and your applications the same way you build libpng.
  182764. */
  182765. #if defined(__MINGW32__) && !defined(PNG_MODULEDEF)
  182766. # ifndef PNG_NO_MODULEDEF
  182767. # define PNG_NO_MODULEDEF
  182768. # endif
  182769. #endif
  182770. #if !defined(PNG_IMPEXP) && defined(PNG_BUILD_DLL) && !defined(PNG_NO_MODULEDEF)
  182771. # define PNG_IMPEXP
  182772. #endif
  182773. #if defined(PNG_DLL) || defined(_DLL) || defined(__DLL__ ) || \
  182774. (( defined(_Windows) || defined(_WINDOWS) || \
  182775. defined(WIN32) || defined(_WIN32) || defined(__WIN32__) ))
  182776. # ifndef PNGAPI
  182777. # if defined(__GNUC__) || (defined (_MSC_VER) && (_MSC_VER >= 800))
  182778. # define PNGAPI __cdecl
  182779. # else
  182780. # define PNGAPI _cdecl
  182781. # endif
  182782. # endif
  182783. # if !defined(PNG_IMPEXP) && (!defined(PNG_DLL) || \
  182784. 0 /* WINCOMPILER_WITH_NO_SUPPORT_FOR_DECLIMPEXP */)
  182785. # define PNG_IMPEXP
  182786. # endif
  182787. # if !defined(PNG_IMPEXP)
  182788. # define PNG_EXPORT_TYPE1(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182789. # define PNG_EXPORT_TYPE2(type,symbol) type PNG_IMPEXP PNGAPI symbol
  182790. /* Borland/Microsoft */
  182791. # if defined(_MSC_VER) || defined(__BORLANDC__)
  182792. # if (_MSC_VER >= 800) || (__BORLANDC__ >= 0x500)
  182793. # define PNG_EXPORT PNG_EXPORT_TYPE1
  182794. # else
  182795. # define PNG_EXPORT PNG_EXPORT_TYPE2
  182796. # if defined(PNG_BUILD_DLL)
  182797. # define PNG_IMPEXP __export
  182798. # else
  182799. # define PNG_IMPEXP /*__import */ /* doesn't exist AFAIK in
  182800. VC++ */
  182801. # endif /* Exists in Borland C++ for
  182802. C++ classes (== huge) */
  182803. # endif
  182804. # endif
  182805. # if !defined(PNG_IMPEXP)
  182806. # if defined(PNG_BUILD_DLL)
  182807. # define PNG_IMPEXP __declspec(dllexport)
  182808. # else
  182809. # define PNG_IMPEXP __declspec(dllimport)
  182810. # endif
  182811. # endif
  182812. # endif /* PNG_IMPEXP */
  182813. #else /* !(DLL || non-cygwin WINDOWS) */
  182814. # if (defined(__IBMC__) || defined(__IBMCPP__)) && defined(__OS2__)
  182815. # ifndef PNGAPI
  182816. # define PNGAPI _System
  182817. # endif
  182818. # else
  182819. # if 0 /* ... other platforms, with other meanings */
  182820. # endif
  182821. # endif
  182822. #endif
  182823. #ifndef PNGAPI
  182824. # define PNGAPI
  182825. #endif
  182826. #ifndef PNG_IMPEXP
  182827. # define PNG_IMPEXP
  182828. #endif
  182829. #ifdef PNG_BUILDSYMS
  182830. # ifndef PNG_EXPORT
  182831. # define PNG_EXPORT(type,symbol) PNG_FUNCTION_EXPORT symbol END
  182832. # endif
  182833. # ifdef PNG_USE_GLOBAL_ARRAYS
  182834. # ifndef PNG_EXPORT_VAR
  182835. # define PNG_EXPORT_VAR(type) PNG_DATA_EXPORT
  182836. # endif
  182837. # endif
  182838. #endif
  182839. #ifndef PNG_EXPORT
  182840. # define PNG_EXPORT(type,symbol) PNG_IMPEXP type PNGAPI symbol
  182841. #endif
  182842. #ifdef PNG_USE_GLOBAL_ARRAYS
  182843. # ifndef PNG_EXPORT_VAR
  182844. # define PNG_EXPORT_VAR(type) extern PNG_IMPEXP type
  182845. # endif
  182846. #endif
  182847. /* User may want to use these so they are not in PNG_INTERNAL. Any library
  182848. * functions that are passed far data must be model independent.
  182849. */
  182850. #ifndef PNG_ABORT
  182851. # define PNG_ABORT() abort()
  182852. #endif
  182853. #ifdef PNG_SETJMP_SUPPORTED
  182854. # define png_jmpbuf(png_ptr) ((png_ptr)->jmpbuf)
  182855. #else
  182856. # define png_jmpbuf(png_ptr) \
  182857. (LIBPNG_WAS_COMPILED_WITH__PNG_SETJMP_NOT_SUPPORTED)
  182858. #endif
  182859. #if defined(USE_FAR_KEYWORD) /* memory model independent fns */
  182860. /* use this to make far-to-near assignments */
  182861. # define CHECK 1
  182862. # define NOCHECK 0
  182863. # define CVT_PTR(ptr) (png_far_to_near(png_ptr,ptr,CHECK))
  182864. # define CVT_PTR_NOCHECK(ptr) (png_far_to_near(png_ptr,ptr,NOCHECK))
  182865. # define png_snprintf _fsnprintf /* Added to v 1.2.19 */
  182866. # define png_strcpy _fstrcpy
  182867. # define png_strncpy _fstrncpy /* Added to v 1.2.6 */
  182868. # define png_strlen _fstrlen
  182869. # define png_memcmp _fmemcmp /* SJT: added */
  182870. # define png_memcpy _fmemcpy
  182871. # define png_memset _fmemset
  182872. #else /* use the usual functions */
  182873. # define CVT_PTR(ptr) (ptr)
  182874. # define CVT_PTR_NOCHECK(ptr) (ptr)
  182875. # ifndef PNG_NO_SNPRINTF
  182876. # ifdef _MSC_VER
  182877. # define png_snprintf _snprintf /* Added to v 1.2.19 */
  182878. # define png_snprintf2 _snprintf
  182879. # define png_snprintf6 _snprintf
  182880. # else
  182881. # define png_snprintf snprintf /* Added to v 1.2.19 */
  182882. # define png_snprintf2 snprintf
  182883. # define png_snprintf6 snprintf
  182884. # endif
  182885. # else
  182886. /* You don't have or don't want to use snprintf(). Caution: Using
  182887. * sprintf instead of snprintf exposes your application to accidental
  182888. * or malevolent buffer overflows. If you don't have snprintf()
  182889. * as a general rule you should provide one (you can get one from
  182890. * Portable OpenSSH). */
  182891. # define png_snprintf(s1,n,fmt,x1) sprintf(s1,fmt,x1)
  182892. # define png_snprintf2(s1,n,fmt,x1,x2) sprintf(s1,fmt,x1,x2)
  182893. # define png_snprintf6(s1,n,fmt,x1,x2,x3,x4,x5,x6) \
  182894. sprintf(s1,fmt,x1,x2,x3,x4,x5,x6)
  182895. # endif
  182896. # define png_strcpy strcpy
  182897. # define png_strncpy strncpy /* Added to v 1.2.6 */
  182898. # define png_strlen strlen
  182899. # define png_memcmp memcmp /* SJT: added */
  182900. # define png_memcpy memcpy
  182901. # define png_memset memset
  182902. #endif
  182903. /* End of memory model independent support */
  182904. /* Just a little check that someone hasn't tried to define something
  182905. * contradictory.
  182906. */
  182907. #if (PNG_ZBUF_SIZE > 65536L) && defined(PNG_MAX_MALLOC_64K)
  182908. # undef PNG_ZBUF_SIZE
  182909. # define PNG_ZBUF_SIZE 65536L
  182910. #endif
  182911. /* Added at libpng-1.2.8 */
  182912. #endif /* PNG_VERSION_INFO_ONLY */
  182913. #endif /* PNGCONF_H */
  182914. /********* End of inlined file: pngconf.h *********/
  182915. #ifdef _MSC_VER
  182916. #pragma warning (disable: 4996 4100)
  182917. #endif
  182918. /*
  182919. * Added at libpng-1.2.8 */
  182920. /* Ref MSDN: Private as priority over Special
  182921. * VS_FF_PRIVATEBUILD File *was not* built using standard release
  182922. * procedures. If this value is given, the StringFileInfo block must
  182923. * contain a PrivateBuild string.
  182924. *
  182925. * VS_FF_SPECIALBUILD File *was* built by the original company using
  182926. * standard release procedures but is a variation of the standard
  182927. * file of the same version number. If this value is given, the
  182928. * StringFileInfo block must contain a SpecialBuild string.
  182929. */
  182930. #if defined(PNG_USER_PRIVATEBUILD)
  182931. # define PNG_LIBPNG_BUILD_TYPE \
  182932. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_PRIVATE)
  182933. #else
  182934. # if defined(PNG_LIBPNG_SPECIALBUILD)
  182935. # define PNG_LIBPNG_BUILD_TYPE \
  182936. (PNG_LIBPNG_BUILD_BASE_TYPE | PNG_LIBPNG_BUILD_SPECIAL)
  182937. # else
  182938. # define PNG_LIBPNG_BUILD_TYPE (PNG_LIBPNG_BUILD_BASE_TYPE)
  182939. # endif
  182940. #endif
  182941. #ifndef PNG_VERSION_INFO_ONLY
  182942. /* Inhibit C++ name-mangling for libpng functions but not for system calls. */
  182943. #ifdef __cplusplus
  182944. extern "C" {
  182945. #endif /* __cplusplus */
  182946. /* This file is arranged in several sections. The first section contains
  182947. * structure and type definitions. The second section contains the external
  182948. * library functions, while the third has the internal library functions,
  182949. * which applications aren't expected to use directly.
  182950. */
  182951. #ifndef PNG_NO_TYPECAST_NULL
  182952. #define int_p_NULL (int *)NULL
  182953. #define png_bytep_NULL (png_bytep)NULL
  182954. #define png_bytepp_NULL (png_bytepp)NULL
  182955. #define png_doublep_NULL (png_doublep)NULL
  182956. #define png_error_ptr_NULL (png_error_ptr)NULL
  182957. #define png_flush_ptr_NULL (png_flush_ptr)NULL
  182958. #define png_free_ptr_NULL (png_free_ptr)NULL
  182959. #define png_infopp_NULL (png_infopp)NULL
  182960. #define png_malloc_ptr_NULL (png_malloc_ptr)NULL
  182961. #define png_read_status_ptr_NULL (png_read_status_ptr)NULL
  182962. #define png_rw_ptr_NULL (png_rw_ptr)NULL
  182963. #define png_structp_NULL (png_structp)NULL
  182964. #define png_uint_16p_NULL (png_uint_16p)NULL
  182965. #define png_voidp_NULL (png_voidp)NULL
  182966. #define png_write_status_ptr_NULL (png_write_status_ptr)NULL
  182967. #else
  182968. #define int_p_NULL NULL
  182969. #define png_bytep_NULL NULL
  182970. #define png_bytepp_NULL NULL
  182971. #define png_doublep_NULL NULL
  182972. #define png_error_ptr_NULL NULL
  182973. #define png_flush_ptr_NULL NULL
  182974. #define png_free_ptr_NULL NULL
  182975. #define png_infopp_NULL NULL
  182976. #define png_malloc_ptr_NULL NULL
  182977. #define png_read_status_ptr_NULL NULL
  182978. #define png_rw_ptr_NULL NULL
  182979. #define png_structp_NULL NULL
  182980. #define png_uint_16p_NULL NULL
  182981. #define png_voidp_NULL NULL
  182982. #define png_write_status_ptr_NULL NULL
  182983. #endif
  182984. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  182985. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  182986. /* Version information for C files, stored in png.c. This had better match
  182987. * the version above.
  182988. */
  182989. #ifdef PNG_USE_GLOBAL_ARRAYS
  182990. PNG_EXPORT_VAR (PNG_CONST char) png_libpng_ver[18];
  182991. /* need room for 99.99.99beta99z */
  182992. #else
  182993. #define png_libpng_ver png_get_header_ver(NULL)
  182994. #endif
  182995. #ifdef PNG_USE_GLOBAL_ARRAYS
  182996. /* This was removed in version 1.0.5c */
  182997. /* Structures to facilitate easy interlacing. See png.c for more details */
  182998. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_start[7];
  182999. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_inc[7];
  183000. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_ystart[7];
  183001. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_yinc[7];
  183002. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_mask[7];
  183003. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_dsp_mask[7];
  183004. /* This isn't currently used. If you need it, see png.c for more details.
  183005. PNG_EXPORT_VAR (PNG_CONST int FARDATA) png_pass_height[7];
  183006. */
  183007. #endif
  183008. #endif /* PNG_NO_EXTERN */
  183009. /* Three color definitions. The order of the red, green, and blue, (and the
  183010. * exact size) is not important, although the size of the fields need to
  183011. * be png_byte or png_uint_16 (as defined below).
  183012. */
  183013. typedef struct png_color_struct
  183014. {
  183015. png_byte red;
  183016. png_byte green;
  183017. png_byte blue;
  183018. } png_color;
  183019. typedef png_color FAR * png_colorp;
  183020. typedef png_color FAR * FAR * png_colorpp;
  183021. typedef struct png_color_16_struct
  183022. {
  183023. png_byte index; /* used for palette files */
  183024. png_uint_16 red; /* for use in red green blue files */
  183025. png_uint_16 green;
  183026. png_uint_16 blue;
  183027. png_uint_16 gray; /* for use in grayscale files */
  183028. } png_color_16;
  183029. typedef png_color_16 FAR * png_color_16p;
  183030. typedef png_color_16 FAR * FAR * png_color_16pp;
  183031. typedef struct png_color_8_struct
  183032. {
  183033. png_byte red; /* for use in red green blue files */
  183034. png_byte green;
  183035. png_byte blue;
  183036. png_byte gray; /* for use in grayscale files */
  183037. png_byte alpha; /* for alpha channel files */
  183038. } png_color_8;
  183039. typedef png_color_8 FAR * png_color_8p;
  183040. typedef png_color_8 FAR * FAR * png_color_8pp;
  183041. /*
  183042. * The following two structures are used for the in-core representation
  183043. * of sPLT chunks.
  183044. */
  183045. typedef struct png_sPLT_entry_struct
  183046. {
  183047. png_uint_16 red;
  183048. png_uint_16 green;
  183049. png_uint_16 blue;
  183050. png_uint_16 alpha;
  183051. png_uint_16 frequency;
  183052. } png_sPLT_entry;
  183053. typedef png_sPLT_entry FAR * png_sPLT_entryp;
  183054. typedef png_sPLT_entry FAR * FAR * png_sPLT_entrypp;
  183055. /* When the depth of the sPLT palette is 8 bits, the color and alpha samples
  183056. * occupy the LSB of their respective members, and the MSB of each member
  183057. * is zero-filled. The frequency member always occupies the full 16 bits.
  183058. */
  183059. typedef struct png_sPLT_struct
  183060. {
  183061. png_charp name; /* palette name */
  183062. png_byte depth; /* depth of palette samples */
  183063. png_sPLT_entryp entries; /* palette entries */
  183064. png_int_32 nentries; /* number of palette entries */
  183065. } png_sPLT_t;
  183066. typedef png_sPLT_t FAR * png_sPLT_tp;
  183067. typedef png_sPLT_t FAR * FAR * png_sPLT_tpp;
  183068. #ifdef PNG_TEXT_SUPPORTED
  183069. /* png_text holds the contents of a text/ztxt/itxt chunk in a PNG file,
  183070. * and whether that contents is compressed or not. The "key" field
  183071. * points to a regular zero-terminated C string. The "text", "lang", and
  183072. * "lang_key" fields can be regular C strings, empty strings, or NULL pointers.
  183073. * However, the * structure returned by png_get_text() will always contain
  183074. * regular zero-terminated C strings (possibly empty), never NULL pointers,
  183075. * so they can be safely used in printf() and other string-handling functions.
  183076. */
  183077. typedef struct png_text_struct
  183078. {
  183079. int compression; /* compression value:
  183080. -1: tEXt, none
  183081. 0: zTXt, deflate
  183082. 1: iTXt, none
  183083. 2: iTXt, deflate */
  183084. png_charp key; /* keyword, 1-79 character description of "text" */
  183085. png_charp text; /* comment, may be an empty string (ie "")
  183086. or a NULL pointer */
  183087. png_size_t text_length; /* length of the text string */
  183088. #ifdef PNG_iTXt_SUPPORTED
  183089. png_size_t itxt_length; /* length of the itxt string */
  183090. png_charp lang; /* language code, 0-79 characters
  183091. or a NULL pointer */
  183092. png_charp lang_key; /* keyword translated UTF-8 string, 0 or more
  183093. chars or a NULL pointer */
  183094. #endif
  183095. } png_text;
  183096. typedef png_text FAR * png_textp;
  183097. typedef png_text FAR * FAR * png_textpp;
  183098. #endif
  183099. /* Supported compression types for text in PNG files (tEXt, and zTXt).
  183100. * The values of the PNG_TEXT_COMPRESSION_ defines should NOT be changed. */
  183101. #define PNG_TEXT_COMPRESSION_NONE_WR -3
  183102. #define PNG_TEXT_COMPRESSION_zTXt_WR -2
  183103. #define PNG_TEXT_COMPRESSION_NONE -1
  183104. #define PNG_TEXT_COMPRESSION_zTXt 0
  183105. #define PNG_ITXT_COMPRESSION_NONE 1
  183106. #define PNG_ITXT_COMPRESSION_zTXt 2
  183107. #define PNG_TEXT_COMPRESSION_LAST 3 /* Not a valid value */
  183108. /* png_time is a way to hold the time in an machine independent way.
  183109. * Two conversions are provided, both from time_t and struct tm. There
  183110. * is no portable way to convert to either of these structures, as far
  183111. * as I know. If you know of a portable way, send it to me. As a side
  183112. * note - PNG has always been Year 2000 compliant!
  183113. */
  183114. typedef struct png_time_struct
  183115. {
  183116. png_uint_16 year; /* full year, as in, 1995 */
  183117. png_byte month; /* month of year, 1 - 12 */
  183118. png_byte day; /* day of month, 1 - 31 */
  183119. png_byte hour; /* hour of day, 0 - 23 */
  183120. png_byte minute; /* minute of hour, 0 - 59 */
  183121. png_byte second; /* second of minute, 0 - 60 (for leap seconds) */
  183122. } png_time;
  183123. typedef png_time FAR * png_timep;
  183124. typedef png_time FAR * FAR * png_timepp;
  183125. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183126. /* png_unknown_chunk is a structure to hold queued chunks for which there is
  183127. * no specific support. The idea is that we can use this to queue
  183128. * up private chunks for output even though the library doesn't actually
  183129. * know about their semantics.
  183130. */
  183131. typedef struct png_unknown_chunk_t
  183132. {
  183133. png_byte name[5];
  183134. png_byte *data;
  183135. png_size_t size;
  183136. /* libpng-using applications should NOT directly modify this byte. */
  183137. png_byte location; /* mode of operation at read time */
  183138. }
  183139. png_unknown_chunk;
  183140. typedef png_unknown_chunk FAR * png_unknown_chunkp;
  183141. typedef png_unknown_chunk FAR * FAR * png_unknown_chunkpp;
  183142. #endif
  183143. /* png_info is a structure that holds the information in a PNG file so
  183144. * that the application can find out the characteristics of the image.
  183145. * If you are reading the file, this structure will tell you what is
  183146. * in the PNG file. If you are writing the file, fill in the information
  183147. * you want to put into the PNG file, then call png_write_info().
  183148. * The names chosen should be very close to the PNG specification, so
  183149. * consult that document for information about the meaning of each field.
  183150. *
  183151. * With libpng < 0.95, it was only possible to directly set and read the
  183152. * the values in the png_info_struct, which meant that the contents and
  183153. * order of the values had to remain fixed. With libpng 0.95 and later,
  183154. * however, there are now functions that abstract the contents of
  183155. * png_info_struct from the application, so this makes it easier to use
  183156. * libpng with dynamic libraries, and even makes it possible to use
  183157. * libraries that don't have all of the libpng ancillary chunk-handing
  183158. * functionality.
  183159. *
  183160. * In any case, the order of the parameters in png_info_struct should NOT
  183161. * be changed for as long as possible to keep compatibility with applications
  183162. * that use the old direct-access method with png_info_struct.
  183163. *
  183164. * The following members may have allocated storage attached that should be
  183165. * cleaned up before the structure is discarded: palette, trans, text,
  183166. * pcal_purpose, pcal_units, pcal_params, hist, iccp_name, iccp_profile,
  183167. * splt_palettes, scal_unit, row_pointers, and unknowns. By default, these
  183168. * are automatically freed when the info structure is deallocated, if they were
  183169. * allocated internally by libpng. This behavior can be changed by means
  183170. * of the png_data_freer() function.
  183171. *
  183172. * More allocation details: all the chunk-reading functions that
  183173. * change these members go through the corresponding png_set_*
  183174. * functions. A function to clear these members is available: see
  183175. * png_free_data(). The png_set_* functions do not depend on being
  183176. * able to point info structure members to any of the storage they are
  183177. * passed (they make their own copies), EXCEPT that the png_set_text
  183178. * functions use the same storage passed to them in the text_ptr or
  183179. * itxt_ptr structure argument, and the png_set_rows and png_set_unknowns
  183180. * functions do not make their own copies.
  183181. */
  183182. typedef struct png_info_struct
  183183. {
  183184. /* the following are necessary for every PNG file */
  183185. png_uint_32 width; /* width of image in pixels (from IHDR) */
  183186. png_uint_32 height; /* height of image in pixels (from IHDR) */
  183187. png_uint_32 valid; /* valid chunk data (see PNG_INFO_ below) */
  183188. png_uint_32 rowbytes; /* bytes needed to hold an untransformed row */
  183189. png_colorp palette; /* array of color values (valid & PNG_INFO_PLTE) */
  183190. png_uint_16 num_palette; /* number of color entries in "palette" (PLTE) */
  183191. png_uint_16 num_trans; /* number of transparent palette color (tRNS) */
  183192. png_byte bit_depth; /* 1, 2, 4, 8, or 16 bits/channel (from IHDR) */
  183193. png_byte color_type; /* see PNG_COLOR_TYPE_ below (from IHDR) */
  183194. /* The following three should have been named *_method not *_type */
  183195. png_byte compression_type; /* must be PNG_COMPRESSION_TYPE_BASE (IHDR) */
  183196. png_byte filter_type; /* must be PNG_FILTER_TYPE_BASE (from IHDR) */
  183197. png_byte interlace_type; /* One of PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  183198. /* The following is informational only on read, and not used on writes. */
  183199. png_byte channels; /* number of data channels per pixel (1, 2, 3, 4) */
  183200. png_byte pixel_depth; /* number of bits per pixel */
  183201. png_byte spare_byte; /* to align the data, and for future use */
  183202. png_byte signature[8]; /* magic bytes read by libpng from start of file */
  183203. /* The rest of the data is optional. If you are reading, check the
  183204. * valid field to see if the information in these are valid. If you
  183205. * are writing, set the valid field to those chunks you want written,
  183206. * and initialize the appropriate fields below.
  183207. */
  183208. #if defined(PNG_gAMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  183209. /* The gAMA chunk describes the gamma characteristics of the system
  183210. * on which the image was created, normally in the range [1.0, 2.5].
  183211. * Data is valid if (valid & PNG_INFO_gAMA) is non-zero.
  183212. */
  183213. float gamma; /* gamma value of image, if (valid & PNG_INFO_gAMA) */
  183214. #endif
  183215. #if defined(PNG_sRGB_SUPPORTED)
  183216. /* GR-P, 0.96a */
  183217. /* Data valid if (valid & PNG_INFO_sRGB) non-zero. */
  183218. png_byte srgb_intent; /* sRGB rendering intent [0, 1, 2, or 3] */
  183219. #endif
  183220. #if defined(PNG_TEXT_SUPPORTED)
  183221. /* The tEXt, and zTXt chunks contain human-readable textual data in
  183222. * uncompressed, compressed, and optionally compressed forms, respectively.
  183223. * The data in "text" is an array of pointers to uncompressed,
  183224. * null-terminated C strings. Each chunk has a keyword that describes the
  183225. * textual data contained in that chunk. Keywords are not required to be
  183226. * unique, and the text string may be empty. Any number of text chunks may
  183227. * be in an image.
  183228. */
  183229. int num_text; /* number of comments read/to write */
  183230. int max_text; /* current size of text array */
  183231. png_textp text; /* array of comments read/to write */
  183232. #endif /* PNG_TEXT_SUPPORTED */
  183233. #if defined(PNG_tIME_SUPPORTED)
  183234. /* The tIME chunk holds the last time the displayed image data was
  183235. * modified. See the png_time struct for the contents of this struct.
  183236. */
  183237. png_time mod_time;
  183238. #endif
  183239. #if defined(PNG_sBIT_SUPPORTED)
  183240. /* The sBIT chunk specifies the number of significant high-order bits
  183241. * in the pixel data. Values are in the range [1, bit_depth], and are
  183242. * only specified for the channels in the pixel data. The contents of
  183243. * the low-order bits is not specified. Data is valid if
  183244. * (valid & PNG_INFO_sBIT) is non-zero.
  183245. */
  183246. png_color_8 sig_bit; /* significant bits in color channels */
  183247. #endif
  183248. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_EXPAND_SUPPORTED) || \
  183249. defined(PNG_READ_BACKGROUND_SUPPORTED)
  183250. /* The tRNS chunk supplies transparency data for paletted images and
  183251. * other image types that don't need a full alpha channel. There are
  183252. * "num_trans" transparency values for a paletted image, stored in the
  183253. * same order as the palette colors, starting from index 0. Values
  183254. * for the data are in the range [0, 255], ranging from fully transparent
  183255. * to fully opaque, respectively. For non-paletted images, there is a
  183256. * single color specified that should be treated as fully transparent.
  183257. * Data is valid if (valid & PNG_INFO_tRNS) is non-zero.
  183258. */
  183259. png_bytep trans; /* transparent values for paletted image */
  183260. png_color_16 trans_values; /* transparent color for non-palette image */
  183261. #endif
  183262. #if defined(PNG_bKGD_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183263. /* The bKGD chunk gives the suggested image background color if the
  183264. * display program does not have its own background color and the image
  183265. * is needs to composited onto a background before display. The colors
  183266. * in "background" are normally in the same color space/depth as the
  183267. * pixel data. Data is valid if (valid & PNG_INFO_bKGD) is non-zero.
  183268. */
  183269. png_color_16 background;
  183270. #endif
  183271. #if defined(PNG_oFFs_SUPPORTED)
  183272. /* The oFFs chunk gives the offset in "offset_unit_type" units rightwards
  183273. * and downwards from the top-left corner of the display, page, or other
  183274. * application-specific co-ordinate space. See the PNG_OFFSET_ defines
  183275. * below for the unit types. Valid if (valid & PNG_INFO_oFFs) non-zero.
  183276. */
  183277. png_int_32 x_offset; /* x offset on page */
  183278. png_int_32 y_offset; /* y offset on page */
  183279. png_byte offset_unit_type; /* offset units type */
  183280. #endif
  183281. #if defined(PNG_pHYs_SUPPORTED)
  183282. /* The pHYs chunk gives the physical pixel density of the image for
  183283. * display or printing in "phys_unit_type" units (see PNG_RESOLUTION_
  183284. * defines below). Data is valid if (valid & PNG_INFO_pHYs) is non-zero.
  183285. */
  183286. png_uint_32 x_pixels_per_unit; /* horizontal pixel density */
  183287. png_uint_32 y_pixels_per_unit; /* vertical pixel density */
  183288. png_byte phys_unit_type; /* resolution type (see PNG_RESOLUTION_ below) */
  183289. #endif
  183290. #if defined(PNG_hIST_SUPPORTED)
  183291. /* The hIST chunk contains the relative frequency or importance of the
  183292. * various palette entries, so that a viewer can intelligently select a
  183293. * reduced-color palette, if required. Data is an array of "num_palette"
  183294. * values in the range [0,65535]. Data valid if (valid & PNG_INFO_hIST)
  183295. * is non-zero.
  183296. */
  183297. png_uint_16p hist;
  183298. #endif
  183299. #ifdef PNG_cHRM_SUPPORTED
  183300. /* The cHRM chunk describes the CIE color characteristics of the monitor
  183301. * on which the PNG was created. This data allows the viewer to do gamut
  183302. * mapping of the input image to ensure that the viewer sees the same
  183303. * colors in the image as the creator. Values are in the range
  183304. * [0.0, 0.8]. Data valid if (valid & PNG_INFO_cHRM) non-zero.
  183305. */
  183306. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183307. float x_white;
  183308. float y_white;
  183309. float x_red;
  183310. float y_red;
  183311. float x_green;
  183312. float y_green;
  183313. float x_blue;
  183314. float y_blue;
  183315. #endif
  183316. #endif
  183317. #if defined(PNG_pCAL_SUPPORTED)
  183318. /* The pCAL chunk describes a transformation between the stored pixel
  183319. * values and original physical data values used to create the image.
  183320. * The integer range [0, 2^bit_depth - 1] maps to the floating-point
  183321. * range given by [pcal_X0, pcal_X1], and are further transformed by a
  183322. * (possibly non-linear) transformation function given by "pcal_type"
  183323. * and "pcal_params" into "pcal_units". Please see the PNG_EQUATION_
  183324. * defines below, and the PNG-Group's PNG extensions document for a
  183325. * complete description of the transformations and how they should be
  183326. * implemented, and for a description of the ASCII parameter strings.
  183327. * Data values are valid if (valid & PNG_INFO_pCAL) non-zero.
  183328. */
  183329. png_charp pcal_purpose; /* pCAL chunk description string */
  183330. png_int_32 pcal_X0; /* minimum value */
  183331. png_int_32 pcal_X1; /* maximum value */
  183332. png_charp pcal_units; /* Latin-1 string giving physical units */
  183333. png_charpp pcal_params; /* ASCII strings containing parameter values */
  183334. png_byte pcal_type; /* equation type (see PNG_EQUATION_ below) */
  183335. png_byte pcal_nparams; /* number of parameters given in pcal_params */
  183336. #endif
  183337. /* New members added in libpng-1.0.6 */
  183338. #ifdef PNG_FREE_ME_SUPPORTED
  183339. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  183340. #endif
  183341. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183342. /* storage for unknown chunks that the library doesn't recognize. */
  183343. png_unknown_chunkp unknown_chunks;
  183344. png_size_t unknown_chunks_num;
  183345. #endif
  183346. #if defined(PNG_iCCP_SUPPORTED)
  183347. /* iCCP chunk data. */
  183348. png_charp iccp_name; /* profile name */
  183349. png_charp iccp_profile; /* International Color Consortium profile data */
  183350. /* Note to maintainer: should be png_bytep */
  183351. png_uint_32 iccp_proflen; /* ICC profile data length */
  183352. png_byte iccp_compression; /* Always zero */
  183353. #endif
  183354. #if defined(PNG_sPLT_SUPPORTED)
  183355. /* data on sPLT chunks (there may be more than one). */
  183356. png_sPLT_tp splt_palettes;
  183357. png_uint_32 splt_palettes_num;
  183358. #endif
  183359. #if defined(PNG_sCAL_SUPPORTED)
  183360. /* The sCAL chunk describes the actual physical dimensions of the
  183361. * subject matter of the graphic. The chunk contains a unit specification
  183362. * a byte value, and two ASCII strings representing floating-point
  183363. * values. The values are width and height corresponsing to one pixel
  183364. * in the image. This external representation is converted to double
  183365. * here. Data values are valid if (valid & PNG_INFO_sCAL) is non-zero.
  183366. */
  183367. png_byte scal_unit; /* unit of physical scale */
  183368. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183369. double scal_pixel_width; /* width of one pixel */
  183370. double scal_pixel_height; /* height of one pixel */
  183371. #endif
  183372. #ifdef PNG_FIXED_POINT_SUPPORTED
  183373. png_charp scal_s_width; /* string containing height */
  183374. png_charp scal_s_height; /* string containing width */
  183375. #endif
  183376. #endif
  183377. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  183378. /* Memory has been allocated if (valid & PNG_ALLOCATED_INFO_ROWS) non-zero */
  183379. /* Data valid if (valid & PNG_INFO_IDAT) non-zero */
  183380. png_bytepp row_pointers; /* the image bits */
  183381. #endif
  183382. #if defined(PNG_FIXED_POINT_SUPPORTED) && defined(PNG_gAMA_SUPPORTED)
  183383. png_fixed_point int_gamma; /* gamma of image, if (valid & PNG_INFO_gAMA) */
  183384. #endif
  183385. #if defined(PNG_cHRM_SUPPORTED) && defined(PNG_FIXED_POINT_SUPPORTED)
  183386. png_fixed_point int_x_white;
  183387. png_fixed_point int_y_white;
  183388. png_fixed_point int_x_red;
  183389. png_fixed_point int_y_red;
  183390. png_fixed_point int_x_green;
  183391. png_fixed_point int_y_green;
  183392. png_fixed_point int_x_blue;
  183393. png_fixed_point int_y_blue;
  183394. #endif
  183395. } png_info;
  183396. typedef png_info FAR * png_infop;
  183397. typedef png_info FAR * FAR * png_infopp;
  183398. /* Maximum positive integer used in PNG is (2^31)-1 */
  183399. #define PNG_UINT_31_MAX ((png_uint_32)0x7fffffffL)
  183400. #define PNG_UINT_32_MAX ((png_uint_32)(-1))
  183401. #define PNG_SIZE_MAX ((png_size_t)(-1))
  183402. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183403. /* PNG_MAX_UINT is deprecated; use PNG_UINT_31_MAX instead. */
  183404. #define PNG_MAX_UINT PNG_UINT_31_MAX
  183405. #endif
  183406. /* These describe the color_type field in png_info. */
  183407. /* color type masks */
  183408. #define PNG_COLOR_MASK_PALETTE 1
  183409. #define PNG_COLOR_MASK_COLOR 2
  183410. #define PNG_COLOR_MASK_ALPHA 4
  183411. /* color types. Note that not all combinations are legal */
  183412. #define PNG_COLOR_TYPE_GRAY 0
  183413. #define PNG_COLOR_TYPE_PALETTE (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_PALETTE)
  183414. #define PNG_COLOR_TYPE_RGB (PNG_COLOR_MASK_COLOR)
  183415. #define PNG_COLOR_TYPE_RGB_ALPHA (PNG_COLOR_MASK_COLOR | PNG_COLOR_MASK_ALPHA)
  183416. #define PNG_COLOR_TYPE_GRAY_ALPHA (PNG_COLOR_MASK_ALPHA)
  183417. /* aliases */
  183418. #define PNG_COLOR_TYPE_RGBA PNG_COLOR_TYPE_RGB_ALPHA
  183419. #define PNG_COLOR_TYPE_GA PNG_COLOR_TYPE_GRAY_ALPHA
  183420. /* This is for compression type. PNG 1.0-1.2 only define the single type. */
  183421. #define PNG_COMPRESSION_TYPE_BASE 0 /* Deflate method 8, 32K window */
  183422. #define PNG_COMPRESSION_TYPE_DEFAULT PNG_COMPRESSION_TYPE_BASE
  183423. /* This is for filter type. PNG 1.0-1.2 only define the single type. */
  183424. #define PNG_FILTER_TYPE_BASE 0 /* Single row per-byte filtering */
  183425. #define PNG_INTRAPIXEL_DIFFERENCING 64 /* Used only in MNG datastreams */
  183426. #define PNG_FILTER_TYPE_DEFAULT PNG_FILTER_TYPE_BASE
  183427. /* These are for the interlacing type. These values should NOT be changed. */
  183428. #define PNG_INTERLACE_NONE 0 /* Non-interlaced image */
  183429. #define PNG_INTERLACE_ADAM7 1 /* Adam7 interlacing */
  183430. #define PNG_INTERLACE_LAST 2 /* Not a valid value */
  183431. /* These are for the oFFs chunk. These values should NOT be changed. */
  183432. #define PNG_OFFSET_PIXEL 0 /* Offset in pixels */
  183433. #define PNG_OFFSET_MICROMETER 1 /* Offset in micrometers (1/10^6 meter) */
  183434. #define PNG_OFFSET_LAST 2 /* Not a valid value */
  183435. /* These are for the pCAL chunk. These values should NOT be changed. */
  183436. #define PNG_EQUATION_LINEAR 0 /* Linear transformation */
  183437. #define PNG_EQUATION_BASE_E 1 /* Exponential base e transform */
  183438. #define PNG_EQUATION_ARBITRARY 2 /* Arbitrary base exponential transform */
  183439. #define PNG_EQUATION_HYPERBOLIC 3 /* Hyperbolic sine transformation */
  183440. #define PNG_EQUATION_LAST 4 /* Not a valid value */
  183441. /* These are for the sCAL chunk. These values should NOT be changed. */
  183442. #define PNG_SCALE_UNKNOWN 0 /* unknown unit (image scale) */
  183443. #define PNG_SCALE_METER 1 /* meters per pixel */
  183444. #define PNG_SCALE_RADIAN 2 /* radians per pixel */
  183445. #define PNG_SCALE_LAST 3 /* Not a valid value */
  183446. /* These are for the pHYs chunk. These values should NOT be changed. */
  183447. #define PNG_RESOLUTION_UNKNOWN 0 /* pixels/unknown unit (aspect ratio) */
  183448. #define PNG_RESOLUTION_METER 1 /* pixels/meter */
  183449. #define PNG_RESOLUTION_LAST 2 /* Not a valid value */
  183450. /* These are for the sRGB chunk. These values should NOT be changed. */
  183451. #define PNG_sRGB_INTENT_PERCEPTUAL 0
  183452. #define PNG_sRGB_INTENT_RELATIVE 1
  183453. #define PNG_sRGB_INTENT_SATURATION 2
  183454. #define PNG_sRGB_INTENT_ABSOLUTE 3
  183455. #define PNG_sRGB_INTENT_LAST 4 /* Not a valid value */
  183456. /* This is for text chunks */
  183457. #define PNG_KEYWORD_MAX_LENGTH 79
  183458. /* Maximum number of entries in PLTE/sPLT/tRNS arrays */
  183459. #define PNG_MAX_PALETTE_LENGTH 256
  183460. /* These determine if an ancillary chunk's data has been successfully read
  183461. * from the PNG header, or if the application has filled in the corresponding
  183462. * data in the info_struct to be written into the output file. The values
  183463. * of the PNG_INFO_<chunk> defines should NOT be changed.
  183464. */
  183465. #define PNG_INFO_gAMA 0x0001
  183466. #define PNG_INFO_sBIT 0x0002
  183467. #define PNG_INFO_cHRM 0x0004
  183468. #define PNG_INFO_PLTE 0x0008
  183469. #define PNG_INFO_tRNS 0x0010
  183470. #define PNG_INFO_bKGD 0x0020
  183471. #define PNG_INFO_hIST 0x0040
  183472. #define PNG_INFO_pHYs 0x0080
  183473. #define PNG_INFO_oFFs 0x0100
  183474. #define PNG_INFO_tIME 0x0200
  183475. #define PNG_INFO_pCAL 0x0400
  183476. #define PNG_INFO_sRGB 0x0800 /* GR-P, 0.96a */
  183477. #define PNG_INFO_iCCP 0x1000 /* ESR, 1.0.6 */
  183478. #define PNG_INFO_sPLT 0x2000 /* ESR, 1.0.6 */
  183479. #define PNG_INFO_sCAL 0x4000 /* ESR, 1.0.6 */
  183480. #define PNG_INFO_IDAT 0x8000L /* ESR, 1.0.6 */
  183481. /* This is used for the transformation routines, as some of them
  183482. * change these values for the row. It also should enable using
  183483. * the routines for other purposes.
  183484. */
  183485. typedef struct png_row_info_struct
  183486. {
  183487. png_uint_32 width; /* width of row */
  183488. png_uint_32 rowbytes; /* number of bytes in row */
  183489. png_byte color_type; /* color type of row */
  183490. png_byte bit_depth; /* bit depth of row */
  183491. png_byte channels; /* number of channels (1, 2, 3, or 4) */
  183492. png_byte pixel_depth; /* bits per pixel (depth * channels) */
  183493. } png_row_info;
  183494. typedef png_row_info FAR * png_row_infop;
  183495. typedef png_row_info FAR * FAR * png_row_infopp;
  183496. /* These are the function types for the I/O functions and for the functions
  183497. * that allow the user to override the default I/O functions with his or her
  183498. * own. The png_error_ptr type should match that of user-supplied warning
  183499. * and error functions, while the png_rw_ptr type should match that of the
  183500. * user read/write data functions.
  183501. */
  183502. typedef struct png_struct_def png_struct;
  183503. typedef png_struct FAR * png_structp;
  183504. typedef void (PNGAPI *png_error_ptr) PNGARG((png_structp, png_const_charp));
  183505. typedef void (PNGAPI *png_rw_ptr) PNGARG((png_structp, png_bytep, png_size_t));
  183506. typedef void (PNGAPI *png_flush_ptr) PNGARG((png_structp));
  183507. typedef void (PNGAPI *png_read_status_ptr) PNGARG((png_structp, png_uint_32,
  183508. int));
  183509. typedef void (PNGAPI *png_write_status_ptr) PNGARG((png_structp, png_uint_32,
  183510. int));
  183511. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183512. typedef void (PNGAPI *png_progressive_info_ptr) PNGARG((png_structp, png_infop));
  183513. typedef void (PNGAPI *png_progressive_end_ptr) PNGARG((png_structp, png_infop));
  183514. typedef void (PNGAPI *png_progressive_row_ptr) PNGARG((png_structp, png_bytep,
  183515. png_uint_32, int));
  183516. #endif
  183517. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183518. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  183519. defined(PNG_LEGACY_SUPPORTED)
  183520. typedef void (PNGAPI *png_user_transform_ptr) PNGARG((png_structp,
  183521. png_row_infop, png_bytep));
  183522. #endif
  183523. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  183524. typedef int (PNGAPI *png_user_chunk_ptr) PNGARG((png_structp, png_unknown_chunkp));
  183525. #endif
  183526. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183527. typedef void (PNGAPI *png_unknown_chunk_ptr) PNGARG((png_structp));
  183528. #endif
  183529. /* Transform masks for the high-level interface */
  183530. #define PNG_TRANSFORM_IDENTITY 0x0000 /* read and write */
  183531. #define PNG_TRANSFORM_STRIP_16 0x0001 /* read only */
  183532. #define PNG_TRANSFORM_STRIP_ALPHA 0x0002 /* read only */
  183533. #define PNG_TRANSFORM_PACKING 0x0004 /* read and write */
  183534. #define PNG_TRANSFORM_PACKSWAP 0x0008 /* read and write */
  183535. #define PNG_TRANSFORM_EXPAND 0x0010 /* read only */
  183536. #define PNG_TRANSFORM_INVERT_MONO 0x0020 /* read and write */
  183537. #define PNG_TRANSFORM_SHIFT 0x0040 /* read and write */
  183538. #define PNG_TRANSFORM_BGR 0x0080 /* read and write */
  183539. #define PNG_TRANSFORM_SWAP_ALPHA 0x0100 /* read and write */
  183540. #define PNG_TRANSFORM_SWAP_ENDIAN 0x0200 /* read and write */
  183541. #define PNG_TRANSFORM_INVERT_ALPHA 0x0400 /* read and write */
  183542. #define PNG_TRANSFORM_STRIP_FILLER 0x0800 /* WRITE only */
  183543. /* Flags for MNG supported features */
  183544. #define PNG_FLAG_MNG_EMPTY_PLTE 0x01
  183545. #define PNG_FLAG_MNG_FILTER_64 0x04
  183546. #define PNG_ALL_MNG_FEATURES 0x05
  183547. typedef png_voidp (*png_malloc_ptr) PNGARG((png_structp, png_size_t));
  183548. typedef void (*png_free_ptr) PNGARG((png_structp, png_voidp));
  183549. /* The structure that holds the information to read and write PNG files.
  183550. * The only people who need to care about what is inside of this are the
  183551. * people who will be modifying the library for their own special needs.
  183552. * It should NOT be accessed directly by an application, except to store
  183553. * the jmp_buf.
  183554. */
  183555. struct png_struct_def
  183556. {
  183557. #ifdef PNG_SETJMP_SUPPORTED
  183558. jmp_buf jmpbuf; /* used in png_error */
  183559. #endif
  183560. png_error_ptr error_fn; /* function for printing errors and aborting */
  183561. png_error_ptr warning_fn; /* function for printing warnings */
  183562. png_voidp error_ptr; /* user supplied struct for error functions */
  183563. png_rw_ptr write_data_fn; /* function for writing output data */
  183564. png_rw_ptr read_data_fn; /* function for reading input data */
  183565. png_voidp io_ptr; /* ptr to application struct for I/O functions */
  183566. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  183567. png_user_transform_ptr read_user_transform_fn; /* user read transform */
  183568. #endif
  183569. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  183570. png_user_transform_ptr write_user_transform_fn; /* user write transform */
  183571. #endif
  183572. /* These were added in libpng-1.0.2 */
  183573. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  183574. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  183575. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  183576. png_voidp user_transform_ptr; /* user supplied struct for user transform */
  183577. png_byte user_transform_depth; /* bit depth of user transformed pixels */
  183578. png_byte user_transform_channels; /* channels in user transformed pixels */
  183579. #endif
  183580. #endif
  183581. png_uint_32 mode; /* tells us where we are in the PNG file */
  183582. png_uint_32 flags; /* flags indicating various things to libpng */
  183583. png_uint_32 transformations; /* which transformations to perform */
  183584. z_stream zstream; /* pointer to decompression structure (below) */
  183585. png_bytep zbuf; /* buffer for zlib */
  183586. png_size_t zbuf_size; /* size of zbuf */
  183587. int zlib_level; /* holds zlib compression level */
  183588. int zlib_method; /* holds zlib compression method */
  183589. int zlib_window_bits; /* holds zlib compression window bits */
  183590. int zlib_mem_level; /* holds zlib compression memory level */
  183591. int zlib_strategy; /* holds zlib compression strategy */
  183592. png_uint_32 width; /* width of image in pixels */
  183593. png_uint_32 height; /* height of image in pixels */
  183594. png_uint_32 num_rows; /* number of rows in current pass */
  183595. png_uint_32 usr_width; /* width of row at start of write */
  183596. png_uint_32 rowbytes; /* size of row in bytes */
  183597. png_uint_32 irowbytes; /* size of current interlaced row in bytes */
  183598. png_uint_32 iwidth; /* width of current interlaced row in pixels */
  183599. png_uint_32 row_number; /* current row in interlace pass */
  183600. png_bytep prev_row; /* buffer to save previous (unfiltered) row */
  183601. png_bytep row_buf; /* buffer to save current (unfiltered) row */
  183602. png_bytep sub_row; /* buffer to save "sub" row when filtering */
  183603. png_bytep up_row; /* buffer to save "up" row when filtering */
  183604. png_bytep avg_row; /* buffer to save "avg" row when filtering */
  183605. png_bytep paeth_row; /* buffer to save "Paeth" row when filtering */
  183606. png_row_info row_info; /* used for transformation routines */
  183607. png_uint_32 idat_size; /* current IDAT size for read */
  183608. png_uint_32 crc; /* current chunk CRC value */
  183609. png_colorp palette; /* palette from the input file */
  183610. png_uint_16 num_palette; /* number of color entries in palette */
  183611. png_uint_16 num_trans; /* number of transparency values */
  183612. png_byte chunk_name[5]; /* null-terminated name of current chunk */
  183613. png_byte compression; /* file compression type (always 0) */
  183614. png_byte filter; /* file filter type (always 0) */
  183615. png_byte interlaced; /* PNG_INTERLACE_NONE, PNG_INTERLACE_ADAM7 */
  183616. png_byte pass; /* current interlace pass (0 - 6) */
  183617. png_byte do_filter; /* row filter flags (see PNG_FILTER_ below ) */
  183618. png_byte color_type; /* color type of file */
  183619. png_byte bit_depth; /* bit depth of file */
  183620. png_byte usr_bit_depth; /* bit depth of users row */
  183621. png_byte pixel_depth; /* number of bits per pixel */
  183622. png_byte channels; /* number of channels in file */
  183623. png_byte usr_channels; /* channels at start of write */
  183624. png_byte sig_bytes; /* magic bytes read/written from start of file */
  183625. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183626. #ifdef PNG_LEGACY_SUPPORTED
  183627. png_byte filler; /* filler byte for pixel expansion */
  183628. #else
  183629. png_uint_16 filler; /* filler bytes for pixel expansion */
  183630. #endif
  183631. #endif
  183632. #if defined(PNG_bKGD_SUPPORTED)
  183633. png_byte background_gamma_type;
  183634. # ifdef PNG_FLOATING_POINT_SUPPORTED
  183635. float background_gamma;
  183636. # endif
  183637. png_color_16 background; /* background color in screen gamma space */
  183638. #if defined(PNG_READ_GAMMA_SUPPORTED)
  183639. png_color_16 background_1; /* background normalized to gamma 1.0 */
  183640. #endif
  183641. #endif /* PNG_bKGD_SUPPORTED */
  183642. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  183643. png_flush_ptr output_flush_fn;/* Function for flushing output */
  183644. png_uint_32 flush_dist; /* how many rows apart to flush, 0 - no flush */
  183645. png_uint_32 flush_rows; /* number of rows written since last flush */
  183646. #endif
  183647. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183648. int gamma_shift; /* number of "insignificant" bits 16-bit gamma */
  183649. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183650. float gamma; /* file gamma value */
  183651. float screen_gamma; /* screen gamma value (display_exponent) */
  183652. #endif
  183653. #endif
  183654. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183655. png_bytep gamma_table; /* gamma table for 8-bit depth files */
  183656. png_bytep gamma_from_1; /* converts from 1.0 to screen */
  183657. png_bytep gamma_to_1; /* converts from file to 1.0 */
  183658. png_uint_16pp gamma_16_table; /* gamma table for 16-bit depth files */
  183659. png_uint_16pp gamma_16_from_1; /* converts from 1.0 to screen */
  183660. png_uint_16pp gamma_16_to_1; /* converts from file to 1.0 */
  183661. #endif
  183662. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_sBIT_SUPPORTED)
  183663. png_color_8 sig_bit; /* significant bits in each available channel */
  183664. #endif
  183665. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183666. png_color_8 shift; /* shift for significant bit tranformation */
  183667. #endif
  183668. #if defined(PNG_tRNS_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED) \
  183669. || defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183670. png_bytep trans; /* transparency values for paletted files */
  183671. png_color_16 trans_values; /* transparency values for non-paletted files */
  183672. #endif
  183673. png_read_status_ptr read_row_fn; /* called after each row is decoded */
  183674. png_write_status_ptr write_row_fn; /* called after each row is encoded */
  183675. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  183676. png_progressive_info_ptr info_fn; /* called after header data fully read */
  183677. png_progressive_row_ptr row_fn; /* called after each prog. row is decoded */
  183678. png_progressive_end_ptr end_fn; /* called after image is complete */
  183679. png_bytep save_buffer_ptr; /* current location in save_buffer */
  183680. png_bytep save_buffer; /* buffer for previously read data */
  183681. png_bytep current_buffer_ptr; /* current location in current_buffer */
  183682. png_bytep current_buffer; /* buffer for recently used data */
  183683. png_uint_32 push_length; /* size of current input chunk */
  183684. png_uint_32 skip_length; /* bytes to skip in input data */
  183685. png_size_t save_buffer_size; /* amount of data now in save_buffer */
  183686. png_size_t save_buffer_max; /* total size of save_buffer */
  183687. png_size_t buffer_size; /* total amount of available input data */
  183688. png_size_t current_buffer_size; /* amount of data now in current_buffer */
  183689. int process_mode; /* what push library is currently doing */
  183690. int cur_palette; /* current push library palette index */
  183691. # if defined(PNG_TEXT_SUPPORTED)
  183692. png_size_t current_text_size; /* current size of text input data */
  183693. png_size_t current_text_left; /* how much text left to read in input */
  183694. png_charp current_text; /* current text chunk buffer */
  183695. png_charp current_text_ptr; /* current location in current_text */
  183696. # endif /* PNG_TEXT_SUPPORTED */
  183697. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  183698. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  183699. /* for the Borland special 64K segment handler */
  183700. png_bytepp offset_table_ptr;
  183701. png_bytep offset_table;
  183702. png_uint_16 offset_table_number;
  183703. png_uint_16 offset_table_count;
  183704. png_uint_16 offset_table_count_free;
  183705. #endif
  183706. #if defined(PNG_READ_DITHER_SUPPORTED)
  183707. png_bytep palette_lookup; /* lookup table for dithering */
  183708. png_bytep dither_index; /* index translation for palette files */
  183709. #endif
  183710. #if defined(PNG_READ_DITHER_SUPPORTED) || defined(PNG_hIST_SUPPORTED)
  183711. png_uint_16p hist; /* histogram */
  183712. #endif
  183713. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  183714. png_byte heuristic_method; /* heuristic for row filter selection */
  183715. png_byte num_prev_filters; /* number of weights for previous rows */
  183716. png_bytep prev_filters; /* filter type(s) of previous row(s) */
  183717. png_uint_16p filter_weights; /* weight(s) for previous line(s) */
  183718. png_uint_16p inv_filter_weights; /* 1/weight(s) for previous line(s) */
  183719. png_uint_16p filter_costs; /* relative filter calculation cost */
  183720. png_uint_16p inv_filter_costs; /* 1/relative filter calculation cost */
  183721. #endif
  183722. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183723. png_charp time_buffer; /* String to hold RFC 1123 time text */
  183724. #endif
  183725. /* New members added in libpng-1.0.6 */
  183726. #ifdef PNG_FREE_ME_SUPPORTED
  183727. png_uint_32 free_me; /* flags items libpng is responsible for freeing */
  183728. #endif
  183729. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  183730. png_voidp user_chunk_ptr;
  183731. png_user_chunk_ptr read_user_chunk_fn; /* user read chunk handler */
  183732. #endif
  183733. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183734. int num_chunk_list;
  183735. png_bytep chunk_list;
  183736. #endif
  183737. /* New members added in libpng-1.0.3 */
  183738. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183739. png_byte rgb_to_gray_status;
  183740. /* These were changed from png_byte in libpng-1.0.6 */
  183741. png_uint_16 rgb_to_gray_red_coeff;
  183742. png_uint_16 rgb_to_gray_green_coeff;
  183743. png_uint_16 rgb_to_gray_blue_coeff;
  183744. #endif
  183745. /* New member added in libpng-1.0.4 (renamed in 1.0.9) */
  183746. #if defined(PNG_MNG_FEATURES_SUPPORTED) || \
  183747. defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  183748. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  183749. /* changed from png_byte to png_uint_32 at version 1.2.0 */
  183750. #ifdef PNG_1_0_X
  183751. png_byte mng_features_permitted;
  183752. #else
  183753. png_uint_32 mng_features_permitted;
  183754. #endif /* PNG_1_0_X */
  183755. #endif
  183756. /* New member added in libpng-1.0.7 */
  183757. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  183758. png_fixed_point int_gamma;
  183759. #endif
  183760. /* New member added in libpng-1.0.9, ifdef'ed out in 1.0.12, enabled in 1.2.0 */
  183761. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  183762. png_byte filter_type;
  183763. #endif
  183764. #if defined(PNG_1_0_X)
  183765. /* New member added in libpng-1.0.10, ifdef'ed out in 1.2.0 */
  183766. png_uint_32 row_buf_size;
  183767. #endif
  183768. /* New members added in libpng-1.2.0 */
  183769. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  183770. # if !defined(PNG_1_0_X)
  183771. # if defined(PNG_MMX_CODE_SUPPORTED)
  183772. png_byte mmx_bitdepth_threshold;
  183773. png_uint_32 mmx_rowbytes_threshold;
  183774. # endif
  183775. png_uint_32 asm_flags;
  183776. # endif
  183777. #endif
  183778. /* New members added in libpng-1.0.2 but first enabled by default in 1.2.0 */
  183779. #ifdef PNG_USER_MEM_SUPPORTED
  183780. png_voidp mem_ptr; /* user supplied struct for mem functions */
  183781. png_malloc_ptr malloc_fn; /* function for allocating memory */
  183782. png_free_ptr free_fn; /* function for freeing memory */
  183783. #endif
  183784. /* New member added in libpng-1.0.13 and 1.2.0 */
  183785. png_bytep big_row_buf; /* buffer to save current (unfiltered) row */
  183786. #if defined(PNG_READ_DITHER_SUPPORTED)
  183787. /* The following three members were added at version 1.0.14 and 1.2.4 */
  183788. png_bytep dither_sort; /* working sort array */
  183789. png_bytep index_to_palette; /* where the original index currently is */
  183790. /* in the palette */
  183791. png_bytep palette_to_index; /* which original index points to this */
  183792. /* palette color */
  183793. #endif
  183794. /* New members added in libpng-1.0.16 and 1.2.6 */
  183795. png_byte compression_type;
  183796. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  183797. png_uint_32 user_width_max;
  183798. png_uint_32 user_height_max;
  183799. #endif
  183800. /* New member added in libpng-1.0.25 and 1.2.17 */
  183801. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  183802. /* storage for unknown chunk that the library doesn't recognize. */
  183803. png_unknown_chunk unknown_chunk;
  183804. #endif
  183805. };
  183806. /* This triggers a compiler error in png.c, if png.c and png.h
  183807. * do not agree upon the version number.
  183808. */
  183809. typedef png_structp version_1_2_21;
  183810. typedef png_struct FAR * FAR * png_structpp;
  183811. /* Here are the function definitions most commonly used. This is not
  183812. * the place to find out how to use libpng. See libpng.txt for the
  183813. * full explanation, see example.c for the summary. This just provides
  183814. * a simple one line description of the use of each function.
  183815. */
  183816. /* Returns the version number of the library */
  183817. extern PNG_EXPORT(png_uint_32,png_access_version_number) PNGARG((void));
  183818. /* Tell lib we have already handled the first <num_bytes> magic bytes.
  183819. * Handling more than 8 bytes from the beginning of the file is an error.
  183820. */
  183821. extern PNG_EXPORT(void,png_set_sig_bytes) PNGARG((png_structp png_ptr,
  183822. int num_bytes));
  183823. /* Check sig[start] through sig[start + num_to_check - 1] to see if it's a
  183824. * PNG file. Returns zero if the supplied bytes match the 8-byte PNG
  183825. * signature, and non-zero otherwise. Having num_to_check == 0 or
  183826. * start > 7 will always fail (ie return non-zero).
  183827. */
  183828. extern PNG_EXPORT(int,png_sig_cmp) PNGARG((png_bytep sig, png_size_t start,
  183829. png_size_t num_to_check));
  183830. /* Simple signature checking function. This is the same as calling
  183831. * png_check_sig(sig, n) := !png_sig_cmp(sig, 0, n).
  183832. */
  183833. extern PNG_EXPORT(int,png_check_sig) PNGARG((png_bytep sig, int num));
  183834. /* Allocate and initialize png_ptr struct for reading, and any other memory. */
  183835. extern PNG_EXPORT(png_structp,png_create_read_struct)
  183836. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183837. png_error_ptr error_fn, png_error_ptr warn_fn));
  183838. /* Allocate and initialize png_ptr struct for writing, and any other memory */
  183839. extern PNG_EXPORT(png_structp,png_create_write_struct)
  183840. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183841. png_error_ptr error_fn, png_error_ptr warn_fn));
  183842. #ifdef PNG_WRITE_SUPPORTED
  183843. extern PNG_EXPORT(png_uint_32,png_get_compression_buffer_size)
  183844. PNGARG((png_structp png_ptr));
  183845. #endif
  183846. #ifdef PNG_WRITE_SUPPORTED
  183847. extern PNG_EXPORT(void,png_set_compression_buffer_size)
  183848. PNGARG((png_structp png_ptr, png_uint_32 size));
  183849. #endif
  183850. /* Reset the compression stream */
  183851. extern PNG_EXPORT(int,png_reset_zstream) PNGARG((png_structp png_ptr));
  183852. /* New functions added in libpng-1.0.2 (not enabled by default until 1.2.0) */
  183853. #ifdef PNG_USER_MEM_SUPPORTED
  183854. extern PNG_EXPORT(png_structp,png_create_read_struct_2)
  183855. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183856. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183857. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183858. extern PNG_EXPORT(png_structp,png_create_write_struct_2)
  183859. PNGARG((png_const_charp user_png_ver, png_voidp error_ptr,
  183860. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  183861. png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  183862. #endif
  183863. /* Write a PNG chunk - size, type, (optional) data, CRC. */
  183864. extern PNG_EXPORT(void,png_write_chunk) PNGARG((png_structp png_ptr,
  183865. png_bytep chunk_name, png_bytep data, png_size_t length));
  183866. /* Write the start of a PNG chunk - length and chunk name. */
  183867. extern PNG_EXPORT(void,png_write_chunk_start) PNGARG((png_structp png_ptr,
  183868. png_bytep chunk_name, png_uint_32 length));
  183869. /* Write the data of a PNG chunk started with png_write_chunk_start(). */
  183870. extern PNG_EXPORT(void,png_write_chunk_data) PNGARG((png_structp png_ptr,
  183871. png_bytep data, png_size_t length));
  183872. /* Finish a chunk started with png_write_chunk_start() (includes CRC). */
  183873. extern PNG_EXPORT(void,png_write_chunk_end) PNGARG((png_structp png_ptr));
  183874. /* Allocate and initialize the info structure */
  183875. extern PNG_EXPORT(png_infop,png_create_info_struct)
  183876. PNGARG((png_structp png_ptr));
  183877. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183878. /* Initialize the info structure (old interface - DEPRECATED) */
  183879. extern PNG_EXPORT(void,png_info_init) PNGARG((png_infop info_ptr));
  183880. #undef png_info_init
  183881. #define png_info_init(info_ptr) png_info_init_3(&info_ptr,\
  183882. png_sizeof(png_info));
  183883. #endif
  183884. extern PNG_EXPORT(void,png_info_init_3) PNGARG((png_infopp info_ptr,
  183885. png_size_t png_info_struct_size));
  183886. /* Writes all the PNG information before the image. */
  183887. extern PNG_EXPORT(void,png_write_info_before_PLTE) PNGARG((png_structp png_ptr,
  183888. png_infop info_ptr));
  183889. extern PNG_EXPORT(void,png_write_info) PNGARG((png_structp png_ptr,
  183890. png_infop info_ptr));
  183891. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  183892. /* read the information before the actual image data. */
  183893. extern PNG_EXPORT(void,png_read_info) PNGARG((png_structp png_ptr,
  183894. png_infop info_ptr));
  183895. #endif
  183896. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  183897. extern PNG_EXPORT(png_charp,png_convert_to_rfc1123)
  183898. PNGARG((png_structp png_ptr, png_timep ptime));
  183899. #endif
  183900. #if !defined(_WIN32_WCE)
  183901. /* "time.h" functions are not supported on WindowsCE */
  183902. #if defined(PNG_WRITE_tIME_SUPPORTED)
  183903. /* convert from a struct tm to png_time */
  183904. extern PNG_EXPORT(void,png_convert_from_struct_tm) PNGARG((png_timep ptime,
  183905. struct tm FAR * ttime));
  183906. /* convert from time_t to png_time. Uses gmtime() */
  183907. extern PNG_EXPORT(void,png_convert_from_time_t) PNGARG((png_timep ptime,
  183908. time_t ttime));
  183909. #endif /* PNG_WRITE_tIME_SUPPORTED */
  183910. #endif /* _WIN32_WCE */
  183911. #if defined(PNG_READ_EXPAND_SUPPORTED)
  183912. /* Expand data to 24-bit RGB, or 8-bit grayscale, with alpha if available. */
  183913. extern PNG_EXPORT(void,png_set_expand) PNGARG((png_structp png_ptr));
  183914. #if !defined(PNG_1_0_X)
  183915. extern PNG_EXPORT(void,png_set_expand_gray_1_2_4_to_8) PNGARG((png_structp
  183916. png_ptr));
  183917. #endif
  183918. extern PNG_EXPORT(void,png_set_palette_to_rgb) PNGARG((png_structp png_ptr));
  183919. extern PNG_EXPORT(void,png_set_tRNS_to_alpha) PNGARG((png_structp png_ptr));
  183920. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  183921. /* Deprecated */
  183922. extern PNG_EXPORT(void,png_set_gray_1_2_4_to_8) PNGARG((png_structp png_ptr));
  183923. #endif
  183924. #endif
  183925. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  183926. /* Use blue, green, red order for pixels. */
  183927. extern PNG_EXPORT(void,png_set_bgr) PNGARG((png_structp png_ptr));
  183928. #endif
  183929. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  183930. /* Expand the grayscale to 24-bit RGB if necessary. */
  183931. extern PNG_EXPORT(void,png_set_gray_to_rgb) PNGARG((png_structp png_ptr));
  183932. #endif
  183933. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  183934. /* Reduce RGB to grayscale. */
  183935. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183936. extern PNG_EXPORT(void,png_set_rgb_to_gray) PNGARG((png_structp png_ptr,
  183937. int error_action, double red, double green ));
  183938. #endif
  183939. extern PNG_EXPORT(void,png_set_rgb_to_gray_fixed) PNGARG((png_structp png_ptr,
  183940. int error_action, png_fixed_point red, png_fixed_point green ));
  183941. extern PNG_EXPORT(png_byte,png_get_rgb_to_gray_status) PNGARG((png_structp
  183942. png_ptr));
  183943. #endif
  183944. extern PNG_EXPORT(void,png_build_grayscale_palette) PNGARG((int bit_depth,
  183945. png_colorp palette));
  183946. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  183947. extern PNG_EXPORT(void,png_set_strip_alpha) PNGARG((png_structp png_ptr));
  183948. #endif
  183949. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  183950. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  183951. extern PNG_EXPORT(void,png_set_swap_alpha) PNGARG((png_structp png_ptr));
  183952. #endif
  183953. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  183954. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  183955. extern PNG_EXPORT(void,png_set_invert_alpha) PNGARG((png_structp png_ptr));
  183956. #endif
  183957. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  183958. /* Add a filler byte to 8-bit Gray or 24-bit RGB images. */
  183959. extern PNG_EXPORT(void,png_set_filler) PNGARG((png_structp png_ptr,
  183960. png_uint_32 filler, int flags));
  183961. /* The values of the PNG_FILLER_ defines should NOT be changed */
  183962. #define PNG_FILLER_BEFORE 0
  183963. #define PNG_FILLER_AFTER 1
  183964. /* Add an alpha byte to 8-bit Gray or 24-bit RGB images. */
  183965. #if !defined(PNG_1_0_X)
  183966. extern PNG_EXPORT(void,png_set_add_alpha) PNGARG((png_structp png_ptr,
  183967. png_uint_32 filler, int flags));
  183968. #endif
  183969. #endif /* PNG_READ_FILLER_SUPPORTED || PNG_WRITE_FILLER_SUPPORTED */
  183970. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  183971. /* Swap bytes in 16-bit depth files. */
  183972. extern PNG_EXPORT(void,png_set_swap) PNGARG((png_structp png_ptr));
  183973. #endif
  183974. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  183975. /* Use 1 byte per pixel in 1, 2, or 4-bit depth files. */
  183976. extern PNG_EXPORT(void,png_set_packing) PNGARG((png_structp png_ptr));
  183977. #endif
  183978. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  183979. /* Swap packing order of pixels in bytes. */
  183980. extern PNG_EXPORT(void,png_set_packswap) PNGARG((png_structp png_ptr));
  183981. #endif
  183982. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  183983. /* Converts files to legal bit depths. */
  183984. extern PNG_EXPORT(void,png_set_shift) PNGARG((png_structp png_ptr,
  183985. png_color_8p true_bits));
  183986. #endif
  183987. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  183988. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  183989. /* Have the code handle the interlacing. Returns the number of passes. */
  183990. extern PNG_EXPORT(int,png_set_interlace_handling) PNGARG((png_structp png_ptr));
  183991. #endif
  183992. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  183993. /* Invert monochrome files */
  183994. extern PNG_EXPORT(void,png_set_invert_mono) PNGARG((png_structp png_ptr));
  183995. #endif
  183996. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  183997. /* Handle alpha and tRNS by replacing with a background color. */
  183998. #ifdef PNG_FLOATING_POINT_SUPPORTED
  183999. extern PNG_EXPORT(void,png_set_background) PNGARG((png_structp png_ptr,
  184000. png_color_16p background_color, int background_gamma_code,
  184001. int need_expand, double background_gamma));
  184002. #endif
  184003. #define PNG_BACKGROUND_GAMMA_UNKNOWN 0
  184004. #define PNG_BACKGROUND_GAMMA_SCREEN 1
  184005. #define PNG_BACKGROUND_GAMMA_FILE 2
  184006. #define PNG_BACKGROUND_GAMMA_UNIQUE 3
  184007. #endif
  184008. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  184009. /* strip the second byte of information from a 16-bit depth file. */
  184010. extern PNG_EXPORT(void,png_set_strip_16) PNGARG((png_structp png_ptr));
  184011. #endif
  184012. #if defined(PNG_READ_DITHER_SUPPORTED)
  184013. /* Turn on dithering, and reduce the palette to the number of colors available. */
  184014. extern PNG_EXPORT(void,png_set_dither) PNGARG((png_structp png_ptr,
  184015. png_colorp palette, int num_palette, int maximum_colors,
  184016. png_uint_16p histogram, int full_dither));
  184017. #endif
  184018. #if defined(PNG_READ_GAMMA_SUPPORTED)
  184019. /* Handle gamma correction. Screen_gamma=(display_exponent) */
  184020. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184021. extern PNG_EXPORT(void,png_set_gamma) PNGARG((png_structp png_ptr,
  184022. double screen_gamma, double default_file_gamma));
  184023. #endif
  184024. #endif
  184025. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  184026. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  184027. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  184028. /* Permit or disallow empty PLTE (0: not permitted, 1: permitted) */
  184029. /* Deprecated and will be removed. Use png_permit_mng_features() instead. */
  184030. extern PNG_EXPORT(void,png_permit_empty_plte) PNGARG((png_structp png_ptr,
  184031. int empty_plte_permitted));
  184032. #endif
  184033. #endif
  184034. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  184035. /* Set how many lines between output flushes - 0 for no flushing */
  184036. extern PNG_EXPORT(void,png_set_flush) PNGARG((png_structp png_ptr, int nrows));
  184037. /* Flush the current PNG output buffer */
  184038. extern PNG_EXPORT(void,png_write_flush) PNGARG((png_structp png_ptr));
  184039. #endif
  184040. /* optional update palette with requested transformations */
  184041. extern PNG_EXPORT(void,png_start_read_image) PNGARG((png_structp png_ptr));
  184042. /* optional call to update the users info structure */
  184043. extern PNG_EXPORT(void,png_read_update_info) PNGARG((png_structp png_ptr,
  184044. png_infop info_ptr));
  184045. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184046. /* read one or more rows of image data. */
  184047. extern PNG_EXPORT(void,png_read_rows) PNGARG((png_structp png_ptr,
  184048. png_bytepp row, png_bytepp display_row, png_uint_32 num_rows));
  184049. #endif
  184050. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184051. /* read a row of data. */
  184052. extern PNG_EXPORT(void,png_read_row) PNGARG((png_structp png_ptr,
  184053. png_bytep row,
  184054. png_bytep display_row));
  184055. #endif
  184056. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184057. /* read the whole image into memory at once. */
  184058. extern PNG_EXPORT(void,png_read_image) PNGARG((png_structp png_ptr,
  184059. png_bytepp image));
  184060. #endif
  184061. /* write a row of image data */
  184062. extern PNG_EXPORT(void,png_write_row) PNGARG((png_structp png_ptr,
  184063. png_bytep row));
  184064. /* write a few rows of image data */
  184065. extern PNG_EXPORT(void,png_write_rows) PNGARG((png_structp png_ptr,
  184066. png_bytepp row, png_uint_32 num_rows));
  184067. /* write the image data */
  184068. extern PNG_EXPORT(void,png_write_image) PNGARG((png_structp png_ptr,
  184069. png_bytepp image));
  184070. /* writes the end of the PNG file. */
  184071. extern PNG_EXPORT(void,png_write_end) PNGARG((png_structp png_ptr,
  184072. png_infop info_ptr));
  184073. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  184074. /* read the end of the PNG file. */
  184075. extern PNG_EXPORT(void,png_read_end) PNGARG((png_structp png_ptr,
  184076. png_infop info_ptr));
  184077. #endif
  184078. /* free any memory associated with the png_info_struct */
  184079. extern PNG_EXPORT(void,png_destroy_info_struct) PNGARG((png_structp png_ptr,
  184080. png_infopp info_ptr_ptr));
  184081. /* free any memory associated with the png_struct and the png_info_structs */
  184082. extern PNG_EXPORT(void,png_destroy_read_struct) PNGARG((png_structpp
  184083. png_ptr_ptr, png_infopp info_ptr_ptr, png_infopp end_info_ptr_ptr));
  184084. /* free all memory used by the read (old method - NOT DLL EXPORTED) */
  184085. extern void png_read_destroy PNGARG((png_structp png_ptr, png_infop info_ptr,
  184086. png_infop end_info_ptr));
  184087. /* free any memory associated with the png_struct and the png_info_structs */
  184088. extern PNG_EXPORT(void,png_destroy_write_struct)
  184089. PNGARG((png_structpp png_ptr_ptr, png_infopp info_ptr_ptr));
  184090. /* free any memory used in png_ptr struct (old method - NOT DLL EXPORTED) */
  184091. extern void png_write_destroy PNGARG((png_structp png_ptr));
  184092. /* set the libpng method of handling chunk CRC errors */
  184093. extern PNG_EXPORT(void,png_set_crc_action) PNGARG((png_structp png_ptr,
  184094. int crit_action, int ancil_action));
  184095. /* Values for png_set_crc_action() to say how to handle CRC errors in
  184096. * ancillary and critical chunks, and whether to use the data contained
  184097. * therein. Note that it is impossible to "discard" data in a critical
  184098. * chunk. For versions prior to 0.90, the action was always error/quit,
  184099. * whereas in version 0.90 and later, the action for CRC errors in ancillary
  184100. * chunks is warn/discard. These values should NOT be changed.
  184101. *
  184102. * value action:critical action:ancillary
  184103. */
  184104. #define PNG_CRC_DEFAULT 0 /* error/quit warn/discard data */
  184105. #define PNG_CRC_ERROR_QUIT 1 /* error/quit error/quit */
  184106. #define PNG_CRC_WARN_DISCARD 2 /* (INVALID) warn/discard data */
  184107. #define PNG_CRC_WARN_USE 3 /* warn/use data warn/use data */
  184108. #define PNG_CRC_QUIET_USE 4 /* quiet/use data quiet/use data */
  184109. #define PNG_CRC_NO_CHANGE 5 /* use current value use current value */
  184110. /* These functions give the user control over the scan-line filtering in
  184111. * libpng and the compression methods used by zlib. These functions are
  184112. * mainly useful for testing, as the defaults should work with most users.
  184113. * Those users who are tight on memory or want faster performance at the
  184114. * expense of compression can modify them. See the compression library
  184115. * header file (zlib.h) for an explination of the compression functions.
  184116. */
  184117. /* set the filtering method(s) used by libpng. Currently, the only valid
  184118. * value for "method" is 0.
  184119. */
  184120. extern PNG_EXPORT(void,png_set_filter) PNGARG((png_structp png_ptr, int method,
  184121. int filters));
  184122. /* Flags for png_set_filter() to say which filters to use. The flags
  184123. * are chosen so that they don't conflict with real filter types
  184124. * below, in case they are supplied instead of the #defined constants.
  184125. * These values should NOT be changed.
  184126. */
  184127. #define PNG_NO_FILTERS 0x00
  184128. #define PNG_FILTER_NONE 0x08
  184129. #define PNG_FILTER_SUB 0x10
  184130. #define PNG_FILTER_UP 0x20
  184131. #define PNG_FILTER_AVG 0x40
  184132. #define PNG_FILTER_PAETH 0x80
  184133. #define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
  184134. PNG_FILTER_AVG | PNG_FILTER_PAETH)
  184135. /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  184136. * These defines should NOT be changed.
  184137. */
  184138. #define PNG_FILTER_VALUE_NONE 0
  184139. #define PNG_FILTER_VALUE_SUB 1
  184140. #define PNG_FILTER_VALUE_UP 2
  184141. #define PNG_FILTER_VALUE_AVG 3
  184142. #define PNG_FILTER_VALUE_PAETH 4
  184143. #define PNG_FILTER_VALUE_LAST 5
  184144. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* EXPERIMENTAL */
  184145. /* The "heuristic_method" is given by one of the PNG_FILTER_HEURISTIC_
  184146. * defines, either the default (minimum-sum-of-absolute-differences), or
  184147. * the experimental method (weighted-minimum-sum-of-absolute-differences).
  184148. *
  184149. * Weights are factors >= 1.0, indicating how important it is to keep the
  184150. * filter type consistent between rows. Larger numbers mean the current
  184151. * filter is that many times as likely to be the same as the "num_weights"
  184152. * previous filters. This is cumulative for each previous row with a weight.
  184153. * There needs to be "num_weights" values in "filter_weights", or it can be
  184154. * NULL if the weights aren't being specified. Weights have no influence on
  184155. * the selection of the first row filter. Well chosen weights can (in theory)
  184156. * improve the compression for a given image.
  184157. *
  184158. * Costs are factors >= 1.0 indicating the relative decoding costs of a
  184159. * filter type. Higher costs indicate more decoding expense, and are
  184160. * therefore less likely to be selected over a filter with lower computational
  184161. * costs. There needs to be a value in "filter_costs" for each valid filter
  184162. * type (given by PNG_FILTER_VALUE_LAST), or it can be NULL if you aren't
  184163. * setting the costs. Costs try to improve the speed of decompression without
  184164. * unduly increasing the compressed image size.
  184165. *
  184166. * A negative weight or cost indicates the default value is to be used, and
  184167. * values in the range [0.0, 1.0) indicate the value is to remain unchanged.
  184168. * The default values for both weights and costs are currently 1.0, but may
  184169. * change if good general weighting/cost heuristics can be found. If both
  184170. * the weights and costs are set to 1.0, this degenerates the WEIGHTED method
  184171. * to the UNWEIGHTED method, but with added encoding time/computation.
  184172. */
  184173. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184174. extern PNG_EXPORT(void,png_set_filter_heuristics) PNGARG((png_structp png_ptr,
  184175. int heuristic_method, int num_weights, png_doublep filter_weights,
  184176. png_doublep filter_costs));
  184177. #endif
  184178. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  184179. /* Heuristic used for row filter selection. These defines should NOT be
  184180. * changed.
  184181. */
  184182. #define PNG_FILTER_HEURISTIC_DEFAULT 0 /* Currently "UNWEIGHTED" */
  184183. #define PNG_FILTER_HEURISTIC_UNWEIGHTED 1 /* Used by libpng < 0.95 */
  184184. #define PNG_FILTER_HEURISTIC_WEIGHTED 2 /* Experimental feature */
  184185. #define PNG_FILTER_HEURISTIC_LAST 3 /* Not a valid value */
  184186. /* Set the library compression level. Currently, valid values range from
  184187. * 0 - 9, corresponding directly to the zlib compression levels 0 - 9
  184188. * (0 - no compression, 9 - "maximal" compression). Note that tests have
  184189. * shown that zlib compression levels 3-6 usually perform as well as level 9
  184190. * for PNG images, and do considerably fewer caclulations. In the future,
  184191. * these values may not correspond directly to the zlib compression levels.
  184192. */
  184193. extern PNG_EXPORT(void,png_set_compression_level) PNGARG((png_structp png_ptr,
  184194. int level));
  184195. extern PNG_EXPORT(void,png_set_compression_mem_level)
  184196. PNGARG((png_structp png_ptr, int mem_level));
  184197. extern PNG_EXPORT(void,png_set_compression_strategy)
  184198. PNGARG((png_structp png_ptr, int strategy));
  184199. extern PNG_EXPORT(void,png_set_compression_window_bits)
  184200. PNGARG((png_structp png_ptr, int window_bits));
  184201. extern PNG_EXPORT(void,png_set_compression_method) PNGARG((png_structp png_ptr,
  184202. int method));
  184203. /* These next functions are called for input/output, memory, and error
  184204. * handling. They are in the file pngrio.c, pngwio.c, and pngerror.c,
  184205. * and call standard C I/O routines such as fread(), fwrite(), and
  184206. * fprintf(). These functions can be made to use other I/O routines
  184207. * at run time for those applications that need to handle I/O in a
  184208. * different manner by calling png_set_???_fn(). See libpng.txt for
  184209. * more information.
  184210. */
  184211. #if !defined(PNG_NO_STDIO)
  184212. /* Initialize the input/output for the PNG file to the default functions. */
  184213. extern PNG_EXPORT(void,png_init_io) PNGARG((png_structp png_ptr, png_FILE_p fp));
  184214. #endif
  184215. /* Replace the (error and abort), and warning functions with user
  184216. * supplied functions. If no messages are to be printed you must still
  184217. * write and use replacement functions. The replacement error_fn should
  184218. * still do a longjmp to the last setjmp location if you are using this
  184219. * method of error handling. If error_fn or warning_fn is NULL, the
  184220. * default function will be used.
  184221. */
  184222. extern PNG_EXPORT(void,png_set_error_fn) PNGARG((png_structp png_ptr,
  184223. png_voidp error_ptr, png_error_ptr error_fn, png_error_ptr warning_fn));
  184224. /* Return the user pointer associated with the error functions */
  184225. extern PNG_EXPORT(png_voidp,png_get_error_ptr) PNGARG((png_structp png_ptr));
  184226. /* Replace the default data output functions with a user supplied one(s).
  184227. * If buffered output is not used, then output_flush_fn can be set to NULL.
  184228. * If PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile time
  184229. * output_flush_fn will be ignored (and thus can be NULL).
  184230. */
  184231. extern PNG_EXPORT(void,png_set_write_fn) PNGARG((png_structp png_ptr,
  184232. png_voidp io_ptr, png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn));
  184233. /* Replace the default data input function with a user supplied one. */
  184234. extern PNG_EXPORT(void,png_set_read_fn) PNGARG((png_structp png_ptr,
  184235. png_voidp io_ptr, png_rw_ptr read_data_fn));
  184236. /* Return the user pointer associated with the I/O functions */
  184237. extern PNG_EXPORT(png_voidp,png_get_io_ptr) PNGARG((png_structp png_ptr));
  184238. extern PNG_EXPORT(void,png_set_read_status_fn) PNGARG((png_structp png_ptr,
  184239. png_read_status_ptr read_row_fn));
  184240. extern PNG_EXPORT(void,png_set_write_status_fn) PNGARG((png_structp png_ptr,
  184241. png_write_status_ptr write_row_fn));
  184242. #ifdef PNG_USER_MEM_SUPPORTED
  184243. /* Replace the default memory allocation functions with user supplied one(s). */
  184244. extern PNG_EXPORT(void,png_set_mem_fn) PNGARG((png_structp png_ptr,
  184245. png_voidp mem_ptr, png_malloc_ptr malloc_fn, png_free_ptr free_fn));
  184246. /* Return the user pointer associated with the memory functions */
  184247. extern PNG_EXPORT(png_voidp,png_get_mem_ptr) PNGARG((png_structp png_ptr));
  184248. #endif
  184249. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  184250. defined(PNG_LEGACY_SUPPORTED)
  184251. extern PNG_EXPORT(void,png_set_read_user_transform_fn) PNGARG((png_structp
  184252. png_ptr, png_user_transform_ptr read_user_transform_fn));
  184253. #endif
  184254. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  184255. defined(PNG_LEGACY_SUPPORTED)
  184256. extern PNG_EXPORT(void,png_set_write_user_transform_fn) PNGARG((png_structp
  184257. png_ptr, png_user_transform_ptr write_user_transform_fn));
  184258. #endif
  184259. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  184260. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  184261. defined(PNG_LEGACY_SUPPORTED)
  184262. extern PNG_EXPORT(void,png_set_user_transform_info) PNGARG((png_structp
  184263. png_ptr, png_voidp user_transform_ptr, int user_transform_depth,
  184264. int user_transform_channels));
  184265. /* Return the user pointer associated with the user transform functions */
  184266. extern PNG_EXPORT(png_voidp,png_get_user_transform_ptr)
  184267. PNGARG((png_structp png_ptr));
  184268. #endif
  184269. #ifdef PNG_USER_CHUNKS_SUPPORTED
  184270. extern PNG_EXPORT(void,png_set_read_user_chunk_fn) PNGARG((png_structp png_ptr,
  184271. png_voidp user_chunk_ptr, png_user_chunk_ptr read_user_chunk_fn));
  184272. extern PNG_EXPORT(png_voidp,png_get_user_chunk_ptr) PNGARG((png_structp
  184273. png_ptr));
  184274. #endif
  184275. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  184276. /* Sets the function callbacks for the push reader, and a pointer to a
  184277. * user-defined structure available to the callback functions.
  184278. */
  184279. extern PNG_EXPORT(void,png_set_progressive_read_fn) PNGARG((png_structp png_ptr,
  184280. png_voidp progressive_ptr,
  184281. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  184282. png_progressive_end_ptr end_fn));
  184283. /* returns the user pointer associated with the push read functions */
  184284. extern PNG_EXPORT(png_voidp,png_get_progressive_ptr)
  184285. PNGARG((png_structp png_ptr));
  184286. /* function to be called when data becomes available */
  184287. extern PNG_EXPORT(void,png_process_data) PNGARG((png_structp png_ptr,
  184288. png_infop info_ptr, png_bytep buffer, png_size_t buffer_size));
  184289. /* function that combines rows. Not very much different than the
  184290. * png_combine_row() call. Is this even used?????
  184291. */
  184292. extern PNG_EXPORT(void,png_progressive_combine_row) PNGARG((png_structp png_ptr,
  184293. png_bytep old_row, png_bytep new_row));
  184294. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  184295. extern PNG_EXPORT(png_voidp,png_malloc) PNGARG((png_structp png_ptr,
  184296. png_uint_32 size));
  184297. #if defined(PNG_1_0_X)
  184298. # define png_malloc_warn png_malloc
  184299. #else
  184300. /* Added at libpng version 1.2.4 */
  184301. extern PNG_EXPORT(png_voidp,png_malloc_warn) PNGARG((png_structp png_ptr,
  184302. png_uint_32 size));
  184303. #endif
  184304. /* frees a pointer allocated by png_malloc() */
  184305. extern PNG_EXPORT(void,png_free) PNGARG((png_structp png_ptr, png_voidp ptr));
  184306. #if defined(PNG_1_0_X)
  184307. /* Function to allocate memory for zlib. */
  184308. extern PNG_EXPORT(voidpf,png_zalloc) PNGARG((voidpf png_ptr, uInt items,
  184309. uInt size));
  184310. /* Function to free memory for zlib */
  184311. extern PNG_EXPORT(void,png_zfree) PNGARG((voidpf png_ptr, voidpf ptr));
  184312. #endif
  184313. /* Free data that was allocated internally */
  184314. extern PNG_EXPORT(void,png_free_data) PNGARG((png_structp png_ptr,
  184315. png_infop info_ptr, png_uint_32 free_me, int num));
  184316. #ifdef PNG_FREE_ME_SUPPORTED
  184317. /* Reassign responsibility for freeing existing data, whether allocated
  184318. * by libpng or by the application */
  184319. extern PNG_EXPORT(void,png_data_freer) PNGARG((png_structp png_ptr,
  184320. png_infop info_ptr, int freer, png_uint_32 mask));
  184321. #endif
  184322. /* assignments for png_data_freer */
  184323. #define PNG_DESTROY_WILL_FREE_DATA 1
  184324. #define PNG_SET_WILL_FREE_DATA 1
  184325. #define PNG_USER_WILL_FREE_DATA 2
  184326. /* Flags for png_ptr->free_me and info_ptr->free_me */
  184327. #define PNG_FREE_HIST 0x0008
  184328. #define PNG_FREE_ICCP 0x0010
  184329. #define PNG_FREE_SPLT 0x0020
  184330. #define PNG_FREE_ROWS 0x0040
  184331. #define PNG_FREE_PCAL 0x0080
  184332. #define PNG_FREE_SCAL 0x0100
  184333. #define PNG_FREE_UNKN 0x0200
  184334. #define PNG_FREE_LIST 0x0400
  184335. #define PNG_FREE_PLTE 0x1000
  184336. #define PNG_FREE_TRNS 0x2000
  184337. #define PNG_FREE_TEXT 0x4000
  184338. #define PNG_FREE_ALL 0x7fff
  184339. #define PNG_FREE_MUL 0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
  184340. #ifdef PNG_USER_MEM_SUPPORTED
  184341. extern PNG_EXPORT(png_voidp,png_malloc_default) PNGARG((png_structp png_ptr,
  184342. png_uint_32 size));
  184343. extern PNG_EXPORT(void,png_free_default) PNGARG((png_structp png_ptr,
  184344. png_voidp ptr));
  184345. #endif
  184346. extern PNG_EXPORT(png_voidp,png_memcpy_check) PNGARG((png_structp png_ptr,
  184347. png_voidp s1, png_voidp s2, png_uint_32 size));
  184348. extern PNG_EXPORT(png_voidp,png_memset_check) PNGARG((png_structp png_ptr,
  184349. png_voidp s1, int value, png_uint_32 size));
  184350. #if defined(USE_FAR_KEYWORD) /* memory model conversion function */
  184351. extern void *png_far_to_near PNGARG((png_structp png_ptr,png_voidp ptr,
  184352. int check));
  184353. #endif /* USE_FAR_KEYWORD */
  184354. #ifndef PNG_NO_ERROR_TEXT
  184355. /* Fatal error in PNG image of libpng - can't continue */
  184356. extern PNG_EXPORT(void,png_error) PNGARG((png_structp png_ptr,
  184357. png_const_charp error_message));
  184358. /* The same, but the chunk name is prepended to the error string. */
  184359. extern PNG_EXPORT(void,png_chunk_error) PNGARG((png_structp png_ptr,
  184360. png_const_charp error_message));
  184361. #else
  184362. /* Fatal error in PNG image of libpng - can't continue */
  184363. extern PNG_EXPORT(void,png_err) PNGARG((png_structp png_ptr));
  184364. #endif
  184365. #ifndef PNG_NO_WARNINGS
  184366. /* Non-fatal error in libpng. Can continue, but may have a problem. */
  184367. extern PNG_EXPORT(void,png_warning) PNGARG((png_structp png_ptr,
  184368. png_const_charp warning_message));
  184369. #ifdef PNG_READ_SUPPORTED
  184370. /* Non-fatal error in libpng, chunk name is prepended to message. */
  184371. extern PNG_EXPORT(void,png_chunk_warning) PNGARG((png_structp png_ptr,
  184372. png_const_charp warning_message));
  184373. #endif /* PNG_READ_SUPPORTED */
  184374. #endif /* PNG_NO_WARNINGS */
  184375. /* The png_set_<chunk> functions are for storing values in the png_info_struct.
  184376. * Similarly, the png_get_<chunk> calls are used to read values from the
  184377. * png_info_struct, either storing the parameters in the passed variables, or
  184378. * setting pointers into the png_info_struct where the data is stored. The
  184379. * png_get_<chunk> functions return a non-zero value if the data was available
  184380. * in info_ptr, or return zero and do not change any of the parameters if the
  184381. * data was not available.
  184382. *
  184383. * These functions should be used instead of directly accessing png_info
  184384. * to avoid problems with future changes in the size and internal layout of
  184385. * png_info_struct.
  184386. */
  184387. /* Returns "flag" if chunk data is valid in info_ptr. */
  184388. extern PNG_EXPORT(png_uint_32,png_get_valid) PNGARG((png_structp png_ptr,
  184389. png_infop info_ptr, png_uint_32 flag));
  184390. /* Returns number of bytes needed to hold a transformed row. */
  184391. extern PNG_EXPORT(png_uint_32,png_get_rowbytes) PNGARG((png_structp png_ptr,
  184392. png_infop info_ptr));
  184393. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184394. /* Returns row_pointers, which is an array of pointers to scanlines that was
  184395. returned from png_read_png(). */
  184396. extern PNG_EXPORT(png_bytepp,png_get_rows) PNGARG((png_structp png_ptr,
  184397. png_infop info_ptr));
  184398. /* Set row_pointers, which is an array of pointers to scanlines for use
  184399. by png_write_png(). */
  184400. extern PNG_EXPORT(void,png_set_rows) PNGARG((png_structp png_ptr,
  184401. png_infop info_ptr, png_bytepp row_pointers));
  184402. #endif
  184403. /* Returns number of color channels in image. */
  184404. extern PNG_EXPORT(png_byte,png_get_channels) PNGARG((png_structp png_ptr,
  184405. png_infop info_ptr));
  184406. #ifdef PNG_EASY_ACCESS_SUPPORTED
  184407. /* Returns image width in pixels. */
  184408. extern PNG_EXPORT(png_uint_32, png_get_image_width) PNGARG((png_structp
  184409. png_ptr, png_infop info_ptr));
  184410. /* Returns image height in pixels. */
  184411. extern PNG_EXPORT(png_uint_32, png_get_image_height) PNGARG((png_structp
  184412. png_ptr, png_infop info_ptr));
  184413. /* Returns image bit_depth. */
  184414. extern PNG_EXPORT(png_byte, png_get_bit_depth) PNGARG((png_structp
  184415. png_ptr, png_infop info_ptr));
  184416. /* Returns image color_type. */
  184417. extern PNG_EXPORT(png_byte, png_get_color_type) PNGARG((png_structp
  184418. png_ptr, png_infop info_ptr));
  184419. /* Returns image filter_type. */
  184420. extern PNG_EXPORT(png_byte, png_get_filter_type) PNGARG((png_structp
  184421. png_ptr, png_infop info_ptr));
  184422. /* Returns image interlace_type. */
  184423. extern PNG_EXPORT(png_byte, png_get_interlace_type) PNGARG((png_structp
  184424. png_ptr, png_infop info_ptr));
  184425. /* Returns image compression_type. */
  184426. extern PNG_EXPORT(png_byte, png_get_compression_type) PNGARG((png_structp
  184427. png_ptr, png_infop info_ptr));
  184428. /* Returns image resolution in pixels per meter, from pHYs chunk data. */
  184429. extern PNG_EXPORT(png_uint_32, png_get_pixels_per_meter) PNGARG((png_structp
  184430. png_ptr, png_infop info_ptr));
  184431. extern PNG_EXPORT(png_uint_32, png_get_x_pixels_per_meter) PNGARG((png_structp
  184432. png_ptr, png_infop info_ptr));
  184433. extern PNG_EXPORT(png_uint_32, png_get_y_pixels_per_meter) PNGARG((png_structp
  184434. png_ptr, png_infop info_ptr));
  184435. /* Returns pixel aspect ratio, computed from pHYs chunk data. */
  184436. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184437. extern PNG_EXPORT(float, png_get_pixel_aspect_ratio) PNGARG((png_structp
  184438. png_ptr, png_infop info_ptr));
  184439. #endif
  184440. /* Returns image x, y offset in pixels or microns, from oFFs chunk data. */
  184441. extern PNG_EXPORT(png_int_32, png_get_x_offset_pixels) PNGARG((png_structp
  184442. png_ptr, png_infop info_ptr));
  184443. extern PNG_EXPORT(png_int_32, png_get_y_offset_pixels) PNGARG((png_structp
  184444. png_ptr, png_infop info_ptr));
  184445. extern PNG_EXPORT(png_int_32, png_get_x_offset_microns) PNGARG((png_structp
  184446. png_ptr, png_infop info_ptr));
  184447. extern PNG_EXPORT(png_int_32, png_get_y_offset_microns) PNGARG((png_structp
  184448. png_ptr, png_infop info_ptr));
  184449. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  184450. /* Returns pointer to signature string read from PNG header */
  184451. extern PNG_EXPORT(png_bytep,png_get_signature) PNGARG((png_structp png_ptr,
  184452. png_infop info_ptr));
  184453. #if defined(PNG_bKGD_SUPPORTED)
  184454. extern PNG_EXPORT(png_uint_32,png_get_bKGD) PNGARG((png_structp png_ptr,
  184455. png_infop info_ptr, png_color_16p *background));
  184456. #endif
  184457. #if defined(PNG_bKGD_SUPPORTED)
  184458. extern PNG_EXPORT(void,png_set_bKGD) PNGARG((png_structp png_ptr,
  184459. png_infop info_ptr, png_color_16p background));
  184460. #endif
  184461. #if defined(PNG_cHRM_SUPPORTED)
  184462. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184463. extern PNG_EXPORT(png_uint_32,png_get_cHRM) PNGARG((png_structp png_ptr,
  184464. png_infop info_ptr, double *white_x, double *white_y, double *red_x,
  184465. double *red_y, double *green_x, double *green_y, double *blue_x,
  184466. double *blue_y));
  184467. #endif
  184468. #ifdef PNG_FIXED_POINT_SUPPORTED
  184469. extern PNG_EXPORT(png_uint_32,png_get_cHRM_fixed) PNGARG((png_structp png_ptr,
  184470. png_infop info_ptr, png_fixed_point *int_white_x, png_fixed_point
  184471. *int_white_y, png_fixed_point *int_red_x, png_fixed_point *int_red_y,
  184472. png_fixed_point *int_green_x, png_fixed_point *int_green_y, png_fixed_point
  184473. *int_blue_x, png_fixed_point *int_blue_y));
  184474. #endif
  184475. #endif
  184476. #if defined(PNG_cHRM_SUPPORTED)
  184477. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184478. extern PNG_EXPORT(void,png_set_cHRM) PNGARG((png_structp png_ptr,
  184479. png_infop info_ptr, double white_x, double white_y, double red_x,
  184480. double red_y, double green_x, double green_y, double blue_x, double blue_y));
  184481. #endif
  184482. #ifdef PNG_FIXED_POINT_SUPPORTED
  184483. extern PNG_EXPORT(void,png_set_cHRM_fixed) PNGARG((png_structp png_ptr,
  184484. png_infop info_ptr, png_fixed_point int_white_x, png_fixed_point int_white_y,
  184485. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  184486. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  184487. png_fixed_point int_blue_y));
  184488. #endif
  184489. #endif
  184490. #if defined(PNG_gAMA_SUPPORTED)
  184491. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184492. extern PNG_EXPORT(png_uint_32,png_get_gAMA) PNGARG((png_structp png_ptr,
  184493. png_infop info_ptr, double *file_gamma));
  184494. #endif
  184495. extern PNG_EXPORT(png_uint_32,png_get_gAMA_fixed) PNGARG((png_structp png_ptr,
  184496. png_infop info_ptr, png_fixed_point *int_file_gamma));
  184497. #endif
  184498. #if defined(PNG_gAMA_SUPPORTED)
  184499. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184500. extern PNG_EXPORT(void,png_set_gAMA) PNGARG((png_structp png_ptr,
  184501. png_infop info_ptr, double file_gamma));
  184502. #endif
  184503. extern PNG_EXPORT(void,png_set_gAMA_fixed) PNGARG((png_structp png_ptr,
  184504. png_infop info_ptr, png_fixed_point int_file_gamma));
  184505. #endif
  184506. #if defined(PNG_hIST_SUPPORTED)
  184507. extern PNG_EXPORT(png_uint_32,png_get_hIST) PNGARG((png_structp png_ptr,
  184508. png_infop info_ptr, png_uint_16p *hist));
  184509. #endif
  184510. #if defined(PNG_hIST_SUPPORTED)
  184511. extern PNG_EXPORT(void,png_set_hIST) PNGARG((png_structp png_ptr,
  184512. png_infop info_ptr, png_uint_16p hist));
  184513. #endif
  184514. extern PNG_EXPORT(png_uint_32,png_get_IHDR) PNGARG((png_structp png_ptr,
  184515. png_infop info_ptr, png_uint_32 *width, png_uint_32 *height,
  184516. int *bit_depth, int *color_type, int *interlace_method,
  184517. int *compression_method, int *filter_method));
  184518. extern PNG_EXPORT(void,png_set_IHDR) PNGARG((png_structp png_ptr,
  184519. png_infop info_ptr, png_uint_32 width, png_uint_32 height, int bit_depth,
  184520. int color_type, int interlace_method, int compression_method,
  184521. int filter_method));
  184522. #if defined(PNG_oFFs_SUPPORTED)
  184523. extern PNG_EXPORT(png_uint_32,png_get_oFFs) PNGARG((png_structp png_ptr,
  184524. png_infop info_ptr, png_int_32 *offset_x, png_int_32 *offset_y,
  184525. int *unit_type));
  184526. #endif
  184527. #if defined(PNG_oFFs_SUPPORTED)
  184528. extern PNG_EXPORT(void,png_set_oFFs) PNGARG((png_structp png_ptr,
  184529. png_infop info_ptr, png_int_32 offset_x, png_int_32 offset_y,
  184530. int unit_type));
  184531. #endif
  184532. #if defined(PNG_pCAL_SUPPORTED)
  184533. extern PNG_EXPORT(png_uint_32,png_get_pCAL) PNGARG((png_structp png_ptr,
  184534. png_infop info_ptr, png_charp *purpose, png_int_32 *X0, png_int_32 *X1,
  184535. int *type, int *nparams, png_charp *units, png_charpp *params));
  184536. #endif
  184537. #if defined(PNG_pCAL_SUPPORTED)
  184538. extern PNG_EXPORT(void,png_set_pCAL) PNGARG((png_structp png_ptr,
  184539. png_infop info_ptr, png_charp purpose, png_int_32 X0, png_int_32 X1,
  184540. int type, int nparams, png_charp units, png_charpp params));
  184541. #endif
  184542. #if defined(PNG_pHYs_SUPPORTED)
  184543. extern PNG_EXPORT(png_uint_32,png_get_pHYs) PNGARG((png_structp png_ptr,
  184544. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  184545. #endif
  184546. #if defined(PNG_pHYs_SUPPORTED)
  184547. extern PNG_EXPORT(void,png_set_pHYs) PNGARG((png_structp png_ptr,
  184548. png_infop info_ptr, png_uint_32 res_x, png_uint_32 res_y, int unit_type));
  184549. #endif
  184550. extern PNG_EXPORT(png_uint_32,png_get_PLTE) PNGARG((png_structp png_ptr,
  184551. png_infop info_ptr, png_colorp *palette, int *num_palette));
  184552. extern PNG_EXPORT(void,png_set_PLTE) PNGARG((png_structp png_ptr,
  184553. png_infop info_ptr, png_colorp palette, int num_palette));
  184554. #if defined(PNG_sBIT_SUPPORTED)
  184555. extern PNG_EXPORT(png_uint_32,png_get_sBIT) PNGARG((png_structp png_ptr,
  184556. png_infop info_ptr, png_color_8p *sig_bit));
  184557. #endif
  184558. #if defined(PNG_sBIT_SUPPORTED)
  184559. extern PNG_EXPORT(void,png_set_sBIT) PNGARG((png_structp png_ptr,
  184560. png_infop info_ptr, png_color_8p sig_bit));
  184561. #endif
  184562. #if defined(PNG_sRGB_SUPPORTED)
  184563. extern PNG_EXPORT(png_uint_32,png_get_sRGB) PNGARG((png_structp png_ptr,
  184564. png_infop info_ptr, int *intent));
  184565. #endif
  184566. #if defined(PNG_sRGB_SUPPORTED)
  184567. extern PNG_EXPORT(void,png_set_sRGB) PNGARG((png_structp png_ptr,
  184568. png_infop info_ptr, int intent));
  184569. extern PNG_EXPORT(void,png_set_sRGB_gAMA_and_cHRM) PNGARG((png_structp png_ptr,
  184570. png_infop info_ptr, int intent));
  184571. #endif
  184572. #if defined(PNG_iCCP_SUPPORTED)
  184573. extern PNG_EXPORT(png_uint_32,png_get_iCCP) PNGARG((png_structp png_ptr,
  184574. png_infop info_ptr, png_charpp name, int *compression_type,
  184575. png_charpp profile, png_uint_32 *proflen));
  184576. /* Note to maintainer: profile should be png_bytepp */
  184577. #endif
  184578. #if defined(PNG_iCCP_SUPPORTED)
  184579. extern PNG_EXPORT(void,png_set_iCCP) PNGARG((png_structp png_ptr,
  184580. png_infop info_ptr, png_charp name, int compression_type,
  184581. png_charp profile, png_uint_32 proflen));
  184582. /* Note to maintainer: profile should be png_bytep */
  184583. #endif
  184584. #if defined(PNG_sPLT_SUPPORTED)
  184585. extern PNG_EXPORT(png_uint_32,png_get_sPLT) PNGARG((png_structp png_ptr,
  184586. png_infop info_ptr, png_sPLT_tpp entries));
  184587. #endif
  184588. #if defined(PNG_sPLT_SUPPORTED)
  184589. extern PNG_EXPORT(void,png_set_sPLT) PNGARG((png_structp png_ptr,
  184590. png_infop info_ptr, png_sPLT_tp entries, int nentries));
  184591. #endif
  184592. #if defined(PNG_TEXT_SUPPORTED)
  184593. /* png_get_text also returns the number of text chunks in *num_text */
  184594. extern PNG_EXPORT(png_uint_32,png_get_text) PNGARG((png_structp png_ptr,
  184595. png_infop info_ptr, png_textp *text_ptr, int *num_text));
  184596. #endif
  184597. /*
  184598. * Note while png_set_text() will accept a structure whose text,
  184599. * language, and translated keywords are NULL pointers, the structure
  184600. * returned by png_get_text will always contain regular
  184601. * zero-terminated C strings. They might be empty strings but
  184602. * they will never be NULL pointers.
  184603. */
  184604. #if defined(PNG_TEXT_SUPPORTED)
  184605. extern PNG_EXPORT(void,png_set_text) PNGARG((png_structp png_ptr,
  184606. png_infop info_ptr, png_textp text_ptr, int num_text));
  184607. #endif
  184608. #if defined(PNG_tIME_SUPPORTED)
  184609. extern PNG_EXPORT(png_uint_32,png_get_tIME) PNGARG((png_structp png_ptr,
  184610. png_infop info_ptr, png_timep *mod_time));
  184611. #endif
  184612. #if defined(PNG_tIME_SUPPORTED)
  184613. extern PNG_EXPORT(void,png_set_tIME) PNGARG((png_structp png_ptr,
  184614. png_infop info_ptr, png_timep mod_time));
  184615. #endif
  184616. #if defined(PNG_tRNS_SUPPORTED)
  184617. extern PNG_EXPORT(png_uint_32,png_get_tRNS) PNGARG((png_structp png_ptr,
  184618. png_infop info_ptr, png_bytep *trans, int *num_trans,
  184619. png_color_16p *trans_values));
  184620. #endif
  184621. #if defined(PNG_tRNS_SUPPORTED)
  184622. extern PNG_EXPORT(void,png_set_tRNS) PNGARG((png_structp png_ptr,
  184623. png_infop info_ptr, png_bytep trans, int num_trans,
  184624. png_color_16p trans_values));
  184625. #endif
  184626. #if defined(PNG_tRNS_SUPPORTED)
  184627. #endif
  184628. #if defined(PNG_sCAL_SUPPORTED)
  184629. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184630. extern PNG_EXPORT(png_uint_32,png_get_sCAL) PNGARG((png_structp png_ptr,
  184631. png_infop info_ptr, int *unit, double *width, double *height));
  184632. #else
  184633. #ifdef PNG_FIXED_POINT_SUPPORTED
  184634. extern PNG_EXPORT(png_uint_32,png_get_sCAL_s) PNGARG((png_structp png_ptr,
  184635. png_infop info_ptr, int *unit, png_charpp swidth, png_charpp sheight));
  184636. #endif
  184637. #endif
  184638. #endif /* PNG_sCAL_SUPPORTED */
  184639. #if defined(PNG_sCAL_SUPPORTED)
  184640. #ifdef PNG_FLOATING_POINT_SUPPORTED
  184641. extern PNG_EXPORT(void,png_set_sCAL) PNGARG((png_structp png_ptr,
  184642. png_infop info_ptr, int unit, double width, double height));
  184643. #else
  184644. #ifdef PNG_FIXED_POINT_SUPPORTED
  184645. extern PNG_EXPORT(void,png_set_sCAL_s) PNGARG((png_structp png_ptr,
  184646. png_infop info_ptr, int unit, png_charp swidth, png_charp sheight));
  184647. #endif
  184648. #endif
  184649. #endif /* PNG_sCAL_SUPPORTED || PNG_WRITE_sCAL_SUPPORTED */
  184650. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  184651. /* provide a list of chunks and how they are to be handled, if the built-in
  184652. handling or default unknown chunk handling is not desired. Any chunks not
  184653. listed will be handled in the default manner. The IHDR and IEND chunks
  184654. must not be listed.
  184655. keep = 0: follow default behaviour
  184656. = 1: do not keep
  184657. = 2: keep only if safe-to-copy
  184658. = 3: keep even if unsafe-to-copy
  184659. */
  184660. extern PNG_EXPORT(void, png_set_keep_unknown_chunks) PNGARG((png_structp
  184661. png_ptr, int keep, png_bytep chunk_list, int num_chunks));
  184662. extern PNG_EXPORT(void, png_set_unknown_chunks) PNGARG((png_structp png_ptr,
  184663. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns));
  184664. extern PNG_EXPORT(void, png_set_unknown_chunk_location)
  184665. PNGARG((png_structp png_ptr, png_infop info_ptr, int chunk, int location));
  184666. extern PNG_EXPORT(png_uint_32,png_get_unknown_chunks) PNGARG((png_structp
  184667. png_ptr, png_infop info_ptr, png_unknown_chunkpp entries));
  184668. #endif
  184669. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  184670. PNG_EXPORT(int,png_handle_as_unknown) PNGARG((png_structp png_ptr, png_bytep
  184671. chunk_name));
  184672. #endif
  184673. /* Png_free_data() will turn off the "valid" flag for anything it frees.
  184674. If you need to turn it off for a chunk that your application has freed,
  184675. you can use png_set_invalid(png_ptr, info_ptr, PNG_INFO_CHNK); */
  184676. extern PNG_EXPORT(void, png_set_invalid) PNGARG((png_structp png_ptr,
  184677. png_infop info_ptr, int mask));
  184678. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  184679. /* The "params" pointer is currently not used and is for future expansion. */
  184680. extern PNG_EXPORT(void, png_read_png) PNGARG((png_structp png_ptr,
  184681. png_infop info_ptr,
  184682. int transforms,
  184683. png_voidp params));
  184684. extern PNG_EXPORT(void, png_write_png) PNGARG((png_structp png_ptr,
  184685. png_infop info_ptr,
  184686. int transforms,
  184687. png_voidp params));
  184688. #endif
  184689. /* Define PNG_DEBUG at compile time for debugging information. Higher
  184690. * numbers for PNG_DEBUG mean more debugging information. This has
  184691. * only been added since version 0.95 so it is not implemented throughout
  184692. * libpng yet, but more support will be added as needed.
  184693. */
  184694. #ifdef PNG_DEBUG
  184695. #if (PNG_DEBUG > 0)
  184696. #if !defined(PNG_DEBUG_FILE) && defined(_MSC_VER)
  184697. #include <crtdbg.h>
  184698. #if (PNG_DEBUG > 1)
  184699. #define png_debug(l,m) _RPT0(_CRT_WARN,m)
  184700. #define png_debug1(l,m,p1) _RPT1(_CRT_WARN,m,p1)
  184701. #define png_debug2(l,m,p1,p2) _RPT2(_CRT_WARN,m,p1,p2)
  184702. #endif
  184703. #else /* PNG_DEBUG_FILE || !_MSC_VER */
  184704. #ifndef PNG_DEBUG_FILE
  184705. #define PNG_DEBUG_FILE stderr
  184706. #endif /* PNG_DEBUG_FILE */
  184707. #if (PNG_DEBUG > 1)
  184708. #define png_debug(l,m) \
  184709. { \
  184710. int num_tabs=l; \
  184711. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  184712. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":"")))); \
  184713. }
  184714. #define png_debug1(l,m,p1) \
  184715. { \
  184716. int num_tabs=l; \
  184717. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  184718. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1); \
  184719. }
  184720. #define png_debug2(l,m,p1,p2) \
  184721. { \
  184722. int num_tabs=l; \
  184723. fprintf(PNG_DEBUG_FILE,"%s"m,(num_tabs==1 ? "\t" : \
  184724. (num_tabs==2 ? "\t\t":(num_tabs>2 ? "\t\t\t":""))),p1,p2); \
  184725. }
  184726. #endif /* (PNG_DEBUG > 1) */
  184727. #endif /* _MSC_VER */
  184728. #endif /* (PNG_DEBUG > 0) */
  184729. #endif /* PNG_DEBUG */
  184730. #ifndef png_debug
  184731. #define png_debug(l, m)
  184732. #endif
  184733. #ifndef png_debug1
  184734. #define png_debug1(l, m, p1)
  184735. #endif
  184736. #ifndef png_debug2
  184737. #define png_debug2(l, m, p1, p2)
  184738. #endif
  184739. extern PNG_EXPORT(png_charp,png_get_copyright) PNGARG((png_structp png_ptr));
  184740. extern PNG_EXPORT(png_charp,png_get_header_ver) PNGARG((png_structp png_ptr));
  184741. extern PNG_EXPORT(png_charp,png_get_header_version) PNGARG((png_structp png_ptr));
  184742. extern PNG_EXPORT(png_charp,png_get_libpng_ver) PNGARG((png_structp png_ptr));
  184743. #ifdef PNG_MNG_FEATURES_SUPPORTED
  184744. extern PNG_EXPORT(png_uint_32,png_permit_mng_features) PNGARG((png_structp
  184745. png_ptr, png_uint_32 mng_features_permitted));
  184746. #endif
  184747. /* For use in png_set_keep_unknown, added to version 1.2.6 */
  184748. #define PNG_HANDLE_CHUNK_AS_DEFAULT 0
  184749. #define PNG_HANDLE_CHUNK_NEVER 1
  184750. #define PNG_HANDLE_CHUNK_IF_SAFE 2
  184751. #define PNG_HANDLE_CHUNK_ALWAYS 3
  184752. /* Added to version 1.2.0 */
  184753. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  184754. #if defined(PNG_MMX_CODE_SUPPORTED)
  184755. #define PNG_ASM_FLAG_MMX_SUPPORT_COMPILED 0x01 /* not user-settable */
  184756. #define PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU 0x02 /* not user-settable */
  184757. #define PNG_ASM_FLAG_MMX_READ_COMBINE_ROW 0x04
  184758. #define PNG_ASM_FLAG_MMX_READ_INTERLACE 0x08
  184759. #define PNG_ASM_FLAG_MMX_READ_FILTER_SUB 0x10
  184760. #define PNG_ASM_FLAG_MMX_READ_FILTER_UP 0x20
  184761. #define PNG_ASM_FLAG_MMX_READ_FILTER_AVG 0x40
  184762. #define PNG_ASM_FLAG_MMX_READ_FILTER_PAETH 0x80
  184763. #define PNG_ASM_FLAGS_INITIALIZED 0x80000000 /* not user-settable */
  184764. #define PNG_MMX_READ_FLAGS ( PNG_ASM_FLAG_MMX_READ_COMBINE_ROW \
  184765. | PNG_ASM_FLAG_MMX_READ_INTERLACE \
  184766. | PNG_ASM_FLAG_MMX_READ_FILTER_SUB \
  184767. | PNG_ASM_FLAG_MMX_READ_FILTER_UP \
  184768. | PNG_ASM_FLAG_MMX_READ_FILTER_AVG \
  184769. | PNG_ASM_FLAG_MMX_READ_FILTER_PAETH )
  184770. #define PNG_MMX_WRITE_FLAGS ( 0 )
  184771. #define PNG_MMX_FLAGS ( PNG_ASM_FLAG_MMX_SUPPORT_COMPILED \
  184772. | PNG_ASM_FLAG_MMX_SUPPORT_IN_CPU \
  184773. | PNG_MMX_READ_FLAGS \
  184774. | PNG_MMX_WRITE_FLAGS )
  184775. #define PNG_SELECT_READ 1
  184776. #define PNG_SELECT_WRITE 2
  184777. #endif /* PNG_MMX_CODE_SUPPORTED */
  184778. #if !defined(PNG_1_0_X)
  184779. /* pngget.c */
  184780. extern PNG_EXPORT(png_uint_32,png_get_mmx_flagmask)
  184781. PNGARG((int flag_select, int *compilerID));
  184782. /* pngget.c */
  184783. extern PNG_EXPORT(png_uint_32,png_get_asm_flagmask)
  184784. PNGARG((int flag_select));
  184785. /* pngget.c */
  184786. extern PNG_EXPORT(png_uint_32,png_get_asm_flags)
  184787. PNGARG((png_structp png_ptr));
  184788. /* pngget.c */
  184789. extern PNG_EXPORT(png_byte,png_get_mmx_bitdepth_threshold)
  184790. PNGARG((png_structp png_ptr));
  184791. /* pngget.c */
  184792. extern PNG_EXPORT(png_uint_32,png_get_mmx_rowbytes_threshold)
  184793. PNGARG((png_structp png_ptr));
  184794. /* pngset.c */
  184795. extern PNG_EXPORT(void,png_set_asm_flags)
  184796. PNGARG((png_structp png_ptr, png_uint_32 asm_flags));
  184797. /* pngset.c */
  184798. extern PNG_EXPORT(void,png_set_mmx_thresholds)
  184799. PNGARG((png_structp png_ptr, png_byte mmx_bitdepth_threshold,
  184800. png_uint_32 mmx_rowbytes_threshold));
  184801. #endif /* PNG_1_0_X */
  184802. #if !defined(PNG_1_0_X)
  184803. /* png.c, pnggccrd.c, or pngvcrd.c */
  184804. extern PNG_EXPORT(int,png_mmx_support) PNGARG((void));
  184805. #endif /* PNG_ASSEMBLER_CODE_SUPPORTED */
  184806. /* Strip the prepended error numbers ("#nnn ") from error and warning
  184807. * messages before passing them to the error or warning handler. */
  184808. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  184809. extern PNG_EXPORT(void,png_set_strip_error_numbers) PNGARG((png_structp
  184810. png_ptr, png_uint_32 strip_mode));
  184811. #endif
  184812. #endif /* PNG_1_0_X */
  184813. /* Added at libpng-1.2.6 */
  184814. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  184815. extern PNG_EXPORT(void,png_set_user_limits) PNGARG((png_structp
  184816. png_ptr, png_uint_32 user_width_max, png_uint_32 user_height_max));
  184817. extern PNG_EXPORT(png_uint_32,png_get_user_width_max) PNGARG((png_structp
  184818. png_ptr));
  184819. extern PNG_EXPORT(png_uint_32,png_get_user_height_max) PNGARG((png_structp
  184820. png_ptr));
  184821. #endif
  184822. /* Maintainer: Put new public prototypes here ^, in libpng.3, and project defs */
  184823. #ifdef PNG_READ_COMPOSITE_NODIV_SUPPORTED
  184824. /* With these routines we avoid an integer divide, which will be slower on
  184825. * most machines. However, it does take more operations than the corresponding
  184826. * divide method, so it may be slower on a few RISC systems. There are two
  184827. * shifts (by 8 or 16 bits) and an addition, versus a single integer divide.
  184828. *
  184829. * Note that the rounding factors are NOT supposed to be the same! 128 and
  184830. * 32768 are correct for the NODIV code; 127 and 32767 are correct for the
  184831. * standard method.
  184832. *
  184833. * [Optimized code by Greg Roelofs and Mark Adler...blame us for bugs. :-) ]
  184834. */
  184835. /* fg and bg should be in `gamma 1.0' space; alpha is the opacity */
  184836. # define png_composite(composite, fg, alpha, bg) \
  184837. { png_uint_16 temp = (png_uint_16)((png_uint_16)(fg) * (png_uint_16)(alpha) \
  184838. + (png_uint_16)(bg)*(png_uint_16)(255 - \
  184839. (png_uint_16)(alpha)) + (png_uint_16)128); \
  184840. (composite) = (png_byte)((temp + (temp >> 8)) >> 8); }
  184841. # define png_composite_16(composite, fg, alpha, bg) \
  184842. { png_uint_32 temp = (png_uint_32)((png_uint_32)(fg) * (png_uint_32)(alpha) \
  184843. + (png_uint_32)(bg)*(png_uint_32)(65535L - \
  184844. (png_uint_32)(alpha)) + (png_uint_32)32768L); \
  184845. (composite) = (png_uint_16)((temp + (temp >> 16)) >> 16); }
  184846. #else /* standard method using integer division */
  184847. # define png_composite(composite, fg, alpha, bg) \
  184848. (composite) = (png_byte)(((png_uint_16)(fg) * (png_uint_16)(alpha) + \
  184849. (png_uint_16)(bg) * (png_uint_16)(255 - (png_uint_16)(alpha)) + \
  184850. (png_uint_16)127) / 255)
  184851. # define png_composite_16(composite, fg, alpha, bg) \
  184852. (composite) = (png_uint_16)(((png_uint_32)(fg) * (png_uint_32)(alpha) + \
  184853. (png_uint_32)(bg)*(png_uint_32)(65535L - (png_uint_32)(alpha)) + \
  184854. (png_uint_32)32767) / (png_uint_32)65535L)
  184855. #endif /* PNG_READ_COMPOSITE_NODIV_SUPPORTED */
  184856. /* Inline macros to do direct reads of bytes from the input buffer. These
  184857. * require that you are using an architecture that uses PNG byte ordering
  184858. * (MSB first) and supports unaligned data storage. I think that PowerPC
  184859. * in big-endian mode and 680x0 are the only ones that will support this.
  184860. * The x86 line of processors definitely do not. The png_get_int_32()
  184861. * routine also assumes we are using two's complement format for negative
  184862. * values, which is almost certainly true.
  184863. */
  184864. #if defined(PNG_READ_BIG_ENDIAN_SUPPORTED)
  184865. # define png_get_uint_32(buf) ( *((png_uint_32p) (buf)))
  184866. # define png_get_uint_16(buf) ( *((png_uint_16p) (buf)))
  184867. # define png_get_int_32(buf) ( *((png_int_32p) (buf)))
  184868. #else
  184869. extern PNG_EXPORT(png_uint_32,png_get_uint_32) PNGARG((png_bytep buf));
  184870. extern PNG_EXPORT(png_uint_16,png_get_uint_16) PNGARG((png_bytep buf));
  184871. extern PNG_EXPORT(png_int_32,png_get_int_32) PNGARG((png_bytep buf));
  184872. #endif /* !PNG_READ_BIG_ENDIAN_SUPPORTED */
  184873. extern PNG_EXPORT(png_uint_32,png_get_uint_31)
  184874. PNGARG((png_structp png_ptr, png_bytep buf));
  184875. /* No png_get_int_16 -- may be added if there's a real need for it. */
  184876. /* Place a 32-bit number into a buffer in PNG byte order (big-endian).
  184877. */
  184878. extern PNG_EXPORT(void,png_save_uint_32)
  184879. PNGARG((png_bytep buf, png_uint_32 i));
  184880. extern PNG_EXPORT(void,png_save_int_32)
  184881. PNGARG((png_bytep buf, png_int_32 i));
  184882. /* Place a 16-bit number into a buffer in PNG byte order.
  184883. * The parameter is declared unsigned int, not png_uint_16,
  184884. * just to avoid potential problems on pre-ANSI C compilers.
  184885. */
  184886. extern PNG_EXPORT(void,png_save_uint_16)
  184887. PNGARG((png_bytep buf, unsigned int i));
  184888. /* No png_save_int_16 -- may be added if there's a real need for it. */
  184889. /* ************************************************************************* */
  184890. /* These next functions are used internally in the code. They generally
  184891. * shouldn't be used unless you are writing code to add or replace some
  184892. * functionality in libpng. More information about most functions can
  184893. * be found in the files where the functions are located.
  184894. */
  184895. /* Various modes of operation, that are visible to applications because
  184896. * they are used for unknown chunk location.
  184897. */
  184898. #define PNG_HAVE_IHDR 0x01
  184899. #define PNG_HAVE_PLTE 0x02
  184900. #define PNG_HAVE_IDAT 0x04
  184901. #define PNG_AFTER_IDAT 0x08 /* Have complete zlib datastream */
  184902. #define PNG_HAVE_IEND 0x10
  184903. #if defined(PNG_INTERNAL)
  184904. /* More modes of operation. Note that after an init, mode is set to
  184905. * zero automatically when the structure is created.
  184906. */
  184907. #define PNG_HAVE_gAMA 0x20
  184908. #define PNG_HAVE_cHRM 0x40
  184909. #define PNG_HAVE_sRGB 0x80
  184910. #define PNG_HAVE_CHUNK_HEADER 0x100
  184911. #define PNG_WROTE_tIME 0x200
  184912. #define PNG_WROTE_INFO_BEFORE_PLTE 0x400
  184913. #define PNG_BACKGROUND_IS_GRAY 0x800
  184914. #define PNG_HAVE_PNG_SIGNATURE 0x1000
  184915. #define PNG_HAVE_CHUNK_AFTER_IDAT 0x2000 /* Have another chunk after IDAT */
  184916. /* flags for the transformations the PNG library does on the image data */
  184917. #define PNG_BGR 0x0001
  184918. #define PNG_INTERLACE 0x0002
  184919. #define PNG_PACK 0x0004
  184920. #define PNG_SHIFT 0x0008
  184921. #define PNG_SWAP_BYTES 0x0010
  184922. #define PNG_INVERT_MONO 0x0020
  184923. #define PNG_DITHER 0x0040
  184924. #define PNG_BACKGROUND 0x0080
  184925. #define PNG_BACKGROUND_EXPAND 0x0100
  184926. /* 0x0200 unused */
  184927. #define PNG_16_TO_8 0x0400
  184928. #define PNG_RGBA 0x0800
  184929. #define PNG_EXPAND 0x1000
  184930. #define PNG_GAMMA 0x2000
  184931. #define PNG_GRAY_TO_RGB 0x4000
  184932. #define PNG_FILLER 0x8000L
  184933. #define PNG_PACKSWAP 0x10000L
  184934. #define PNG_SWAP_ALPHA 0x20000L
  184935. #define PNG_STRIP_ALPHA 0x40000L
  184936. #define PNG_INVERT_ALPHA 0x80000L
  184937. #define PNG_USER_TRANSFORM 0x100000L
  184938. #define PNG_RGB_TO_GRAY_ERR 0x200000L
  184939. #define PNG_RGB_TO_GRAY_WARN 0x400000L
  184940. #define PNG_RGB_TO_GRAY 0x600000L /* two bits, RGB_TO_GRAY_ERR|WARN */
  184941. /* 0x800000L Unused */
  184942. #define PNG_ADD_ALPHA 0x1000000L /* Added to libpng-1.2.7 */
  184943. #define PNG_EXPAND_tRNS 0x2000000L /* Added to libpng-1.2.9 */
  184944. /* 0x4000000L unused */
  184945. /* 0x8000000L unused */
  184946. /* 0x10000000L unused */
  184947. /* 0x20000000L unused */
  184948. /* 0x40000000L unused */
  184949. /* flags for png_create_struct */
  184950. #define PNG_STRUCT_PNG 0x0001
  184951. #define PNG_STRUCT_INFO 0x0002
  184952. /* Scaling factor for filter heuristic weighting calculations */
  184953. #define PNG_WEIGHT_SHIFT 8
  184954. #define PNG_WEIGHT_FACTOR (1<<(PNG_WEIGHT_SHIFT))
  184955. #define PNG_COST_SHIFT 3
  184956. #define PNG_COST_FACTOR (1<<(PNG_COST_SHIFT))
  184957. /* flags for the png_ptr->flags rather than declaring a byte for each one */
  184958. #define PNG_FLAG_ZLIB_CUSTOM_STRATEGY 0x0001
  184959. #define PNG_FLAG_ZLIB_CUSTOM_LEVEL 0x0002
  184960. #define PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL 0x0004
  184961. #define PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS 0x0008
  184962. #define PNG_FLAG_ZLIB_CUSTOM_METHOD 0x0010
  184963. #define PNG_FLAG_ZLIB_FINISHED 0x0020
  184964. #define PNG_FLAG_ROW_INIT 0x0040
  184965. #define PNG_FLAG_FILLER_AFTER 0x0080
  184966. #define PNG_FLAG_CRC_ANCILLARY_USE 0x0100
  184967. #define PNG_FLAG_CRC_ANCILLARY_NOWARN 0x0200
  184968. #define PNG_FLAG_CRC_CRITICAL_USE 0x0400
  184969. #define PNG_FLAG_CRC_CRITICAL_IGNORE 0x0800
  184970. #define PNG_FLAG_FREE_PLTE 0x1000
  184971. #define PNG_FLAG_FREE_TRNS 0x2000
  184972. #define PNG_FLAG_FREE_HIST 0x4000
  184973. #define PNG_FLAG_KEEP_UNKNOWN_CHUNKS 0x8000L
  184974. #define PNG_FLAG_KEEP_UNSAFE_CHUNKS 0x10000L
  184975. #define PNG_FLAG_LIBRARY_MISMATCH 0x20000L
  184976. #define PNG_FLAG_STRIP_ERROR_NUMBERS 0x40000L
  184977. #define PNG_FLAG_STRIP_ERROR_TEXT 0x80000L
  184978. #define PNG_FLAG_MALLOC_NULL_MEM_OK 0x100000L
  184979. #define PNG_FLAG_ADD_ALPHA 0x200000L /* Added to libpng-1.2.8 */
  184980. #define PNG_FLAG_STRIP_ALPHA 0x400000L /* Added to libpng-1.2.8 */
  184981. /* 0x800000L unused */
  184982. /* 0x1000000L unused */
  184983. /* 0x2000000L unused */
  184984. /* 0x4000000L unused */
  184985. /* 0x8000000L unused */
  184986. /* 0x10000000L unused */
  184987. /* 0x20000000L unused */
  184988. /* 0x40000000L unused */
  184989. #define PNG_FLAG_CRC_ANCILLARY_MASK (PNG_FLAG_CRC_ANCILLARY_USE | \
  184990. PNG_FLAG_CRC_ANCILLARY_NOWARN)
  184991. #define PNG_FLAG_CRC_CRITICAL_MASK (PNG_FLAG_CRC_CRITICAL_USE | \
  184992. PNG_FLAG_CRC_CRITICAL_IGNORE)
  184993. #define PNG_FLAG_CRC_MASK (PNG_FLAG_CRC_ANCILLARY_MASK | \
  184994. PNG_FLAG_CRC_CRITICAL_MASK)
  184995. /* save typing and make code easier to understand */
  184996. #define PNG_COLOR_DIST(c1, c2) (abs((int)((c1).red) - (int)((c2).red)) + \
  184997. abs((int)((c1).green) - (int)((c2).green)) + \
  184998. abs((int)((c1).blue) - (int)((c2).blue)))
  184999. /* Added to libpng-1.2.6 JB */
  185000. #define PNG_ROWBYTES(pixel_bits, width) \
  185001. ((pixel_bits) >= 8 ? \
  185002. ((width) * (((png_uint_32)(pixel_bits)) >> 3)) : \
  185003. (( ((width) * ((png_uint_32)(pixel_bits))) + 7) >> 3) )
  185004. /* PNG_OUT_OF_RANGE returns true if value is outside the range
  185005. ideal-delta..ideal+delta. Each argument is evaluated twice.
  185006. "ideal" and "delta" should be constants, normally simple
  185007. integers, "value" a variable. Added to libpng-1.2.6 JB */
  185008. #define PNG_OUT_OF_RANGE(value, ideal, delta) \
  185009. ( (value) < (ideal)-(delta) || (value) > (ideal)+(delta) )
  185010. /* variables declared in png.c - only it needs to define PNG_NO_EXTERN */
  185011. #if !defined(PNG_NO_EXTERN) || defined(PNG_ALWAYS_EXTERN)
  185012. /* place to hold the signature string for a PNG file. */
  185013. #ifdef PNG_USE_GLOBAL_ARRAYS
  185014. PNG_EXPORT_VAR (PNG_CONST png_byte FARDATA) png_sig[8];
  185015. #else
  185016. #endif
  185017. #endif /* PNG_NO_EXTERN */
  185018. /* Constant strings for known chunk types. If you need to add a chunk,
  185019. * define the name here, and add an invocation of the macro in png.c and
  185020. * wherever it's needed.
  185021. */
  185022. #define PNG_IHDR png_byte png_IHDR[5] = { 73, 72, 68, 82, '\0'}
  185023. #define PNG_IDAT png_byte png_IDAT[5] = { 73, 68, 65, 84, '\0'}
  185024. #define PNG_IEND png_byte png_IEND[5] = { 73, 69, 78, 68, '\0'}
  185025. #define PNG_PLTE png_byte png_PLTE[5] = { 80, 76, 84, 69, '\0'}
  185026. #define PNG_bKGD png_byte png_bKGD[5] = { 98, 75, 71, 68, '\0'}
  185027. #define PNG_cHRM png_byte png_cHRM[5] = { 99, 72, 82, 77, '\0'}
  185028. #define PNG_gAMA png_byte png_gAMA[5] = {103, 65, 77, 65, '\0'}
  185029. #define PNG_hIST png_byte png_hIST[5] = {104, 73, 83, 84, '\0'}
  185030. #define PNG_iCCP png_byte png_iCCP[5] = {105, 67, 67, 80, '\0'}
  185031. #define PNG_iTXt png_byte png_iTXt[5] = {105, 84, 88, 116, '\0'}
  185032. #define PNG_oFFs png_byte png_oFFs[5] = {111, 70, 70, 115, '\0'}
  185033. #define PNG_pCAL png_byte png_pCAL[5] = {112, 67, 65, 76, '\0'}
  185034. #define PNG_sCAL png_byte png_sCAL[5] = {115, 67, 65, 76, '\0'}
  185035. #define PNG_pHYs png_byte png_pHYs[5] = {112, 72, 89, 115, '\0'}
  185036. #define PNG_sBIT png_byte png_sBIT[5] = {115, 66, 73, 84, '\0'}
  185037. #define PNG_sPLT png_byte png_sPLT[5] = {115, 80, 76, 84, '\0'}
  185038. #define PNG_sRGB png_byte png_sRGB[5] = {115, 82, 71, 66, '\0'}
  185039. #define PNG_tEXt png_byte png_tEXt[5] = {116, 69, 88, 116, '\0'}
  185040. #define PNG_tIME png_byte png_tIME[5] = {116, 73, 77, 69, '\0'}
  185041. #define PNG_tRNS png_byte png_tRNS[5] = {116, 82, 78, 83, '\0'}
  185042. #define PNG_zTXt png_byte png_zTXt[5] = {122, 84, 88, 116, '\0'}
  185043. #ifdef PNG_USE_GLOBAL_ARRAYS
  185044. PNG_EXPORT_VAR (png_byte FARDATA) png_IHDR[5];
  185045. PNG_EXPORT_VAR (png_byte FARDATA) png_IDAT[5];
  185046. PNG_EXPORT_VAR (png_byte FARDATA) png_IEND[5];
  185047. PNG_EXPORT_VAR (png_byte FARDATA) png_PLTE[5];
  185048. PNG_EXPORT_VAR (png_byte FARDATA) png_bKGD[5];
  185049. PNG_EXPORT_VAR (png_byte FARDATA) png_cHRM[5];
  185050. PNG_EXPORT_VAR (png_byte FARDATA) png_gAMA[5];
  185051. PNG_EXPORT_VAR (png_byte FARDATA) png_hIST[5];
  185052. PNG_EXPORT_VAR (png_byte FARDATA) png_iCCP[5];
  185053. PNG_EXPORT_VAR (png_byte FARDATA) png_iTXt[5];
  185054. PNG_EXPORT_VAR (png_byte FARDATA) png_oFFs[5];
  185055. PNG_EXPORT_VAR (png_byte FARDATA) png_pCAL[5];
  185056. PNG_EXPORT_VAR (png_byte FARDATA) png_sCAL[5];
  185057. PNG_EXPORT_VAR (png_byte FARDATA) png_pHYs[5];
  185058. PNG_EXPORT_VAR (png_byte FARDATA) png_sBIT[5];
  185059. PNG_EXPORT_VAR (png_byte FARDATA) png_sPLT[5];
  185060. PNG_EXPORT_VAR (png_byte FARDATA) png_sRGB[5];
  185061. PNG_EXPORT_VAR (png_byte FARDATA) png_tEXt[5];
  185062. PNG_EXPORT_VAR (png_byte FARDATA) png_tIME[5];
  185063. PNG_EXPORT_VAR (png_byte FARDATA) png_tRNS[5];
  185064. PNG_EXPORT_VAR (png_byte FARDATA) png_zTXt[5];
  185065. #endif /* PNG_USE_GLOBAL_ARRAYS */
  185066. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  185067. /* Initialize png_ptr struct for reading, and allocate any other memory.
  185068. * (old interface - DEPRECATED - use png_create_read_struct instead).
  185069. */
  185070. extern PNG_EXPORT(void,png_read_init) PNGARG((png_structp png_ptr));
  185071. #undef png_read_init
  185072. #define png_read_init(png_ptr) png_read_init_3(&png_ptr, \
  185073. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  185074. #endif
  185075. extern PNG_EXPORT(void,png_read_init_3) PNGARG((png_structpp ptr_ptr,
  185076. png_const_charp user_png_ver, png_size_t png_struct_size));
  185077. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  185078. extern PNG_EXPORT(void,png_read_init_2) PNGARG((png_structp png_ptr,
  185079. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  185080. png_info_size));
  185081. #endif
  185082. #if defined(PNG_1_0_X) || defined (PNG_1_2_X)
  185083. /* Initialize png_ptr struct for writing, and allocate any other memory.
  185084. * (old interface - DEPRECATED - use png_create_write_struct instead).
  185085. */
  185086. extern PNG_EXPORT(void,png_write_init) PNGARG((png_structp png_ptr));
  185087. #undef png_write_init
  185088. #define png_write_init(png_ptr) png_write_init_3(&png_ptr, \
  185089. PNG_LIBPNG_VER_STRING, png_sizeof(png_struct));
  185090. #endif
  185091. extern PNG_EXPORT(void,png_write_init_3) PNGARG((png_structpp ptr_ptr,
  185092. png_const_charp user_png_ver, png_size_t png_struct_size));
  185093. extern PNG_EXPORT(void,png_write_init_2) PNGARG((png_structp png_ptr,
  185094. png_const_charp user_png_ver, png_size_t png_struct_size, png_size_t
  185095. png_info_size));
  185096. /* Allocate memory for an internal libpng struct */
  185097. PNG_EXTERN png_voidp png_create_struct PNGARG((int type));
  185098. /* Free memory from internal libpng struct */
  185099. PNG_EXTERN void png_destroy_struct PNGARG((png_voidp struct_ptr));
  185100. PNG_EXTERN png_voidp png_create_struct_2 PNGARG((int type, png_malloc_ptr
  185101. malloc_fn, png_voidp mem_ptr));
  185102. PNG_EXTERN void png_destroy_struct_2 PNGARG((png_voidp struct_ptr,
  185103. png_free_ptr free_fn, png_voidp mem_ptr));
  185104. /* Free any memory that info_ptr points to and reset struct. */
  185105. PNG_EXTERN void png_info_destroy PNGARG((png_structp png_ptr,
  185106. png_infop info_ptr));
  185107. #ifndef PNG_1_0_X
  185108. /* Function to allocate memory for zlib. */
  185109. PNG_EXTERN voidpf png_zalloc PNGARG((voidpf png_ptr, uInt items, uInt size));
  185110. /* Function to free memory for zlib */
  185111. PNG_EXTERN void png_zfree PNGARG((voidpf png_ptr, voidpf ptr));
  185112. #ifdef PNG_SIZE_T
  185113. /* Function to convert a sizeof an item to png_sizeof item */
  185114. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  185115. #endif
  185116. /* Next four functions are used internally as callbacks. PNGAPI is required
  185117. * but not PNG_EXPORT. PNGAPI added at libpng version 1.2.3. */
  185118. PNG_EXTERN void PNGAPI png_default_read_data PNGARG((png_structp png_ptr,
  185119. png_bytep data, png_size_t length));
  185120. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  185121. PNG_EXTERN void PNGAPI png_push_fill_buffer PNGARG((png_structp png_ptr,
  185122. png_bytep buffer, png_size_t length));
  185123. #endif
  185124. PNG_EXTERN void PNGAPI png_default_write_data PNGARG((png_structp png_ptr,
  185125. png_bytep data, png_size_t length));
  185126. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  185127. #if !defined(PNG_NO_STDIO)
  185128. PNG_EXTERN void PNGAPI png_default_flush PNGARG((png_structp png_ptr));
  185129. #endif
  185130. #endif
  185131. #else /* PNG_1_0_X */
  185132. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  185133. PNG_EXTERN void png_push_fill_buffer PNGARG((png_structp png_ptr,
  185134. png_bytep buffer, png_size_t length));
  185135. #endif
  185136. #endif /* PNG_1_0_X */
  185137. /* Reset the CRC variable */
  185138. PNG_EXTERN void png_reset_crc PNGARG((png_structp png_ptr));
  185139. /* Write the "data" buffer to whatever output you are using. */
  185140. PNG_EXTERN void png_write_data PNGARG((png_structp png_ptr, png_bytep data,
  185141. png_size_t length));
  185142. /* Read data from whatever input you are using into the "data" buffer */
  185143. PNG_EXTERN void png_read_data PNGARG((png_structp png_ptr, png_bytep data,
  185144. png_size_t length));
  185145. /* Read bytes into buf, and update png_ptr->crc */
  185146. PNG_EXTERN void png_crc_read PNGARG((png_structp png_ptr, png_bytep buf,
  185147. png_size_t length));
  185148. /* Decompress data in a chunk that uses compression */
  185149. #if defined(PNG_zTXt_SUPPORTED) || defined(PNG_iTXt_SUPPORTED) || \
  185150. defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
  185151. PNG_EXTERN png_charp png_decompress_chunk PNGARG((png_structp png_ptr,
  185152. int comp_type, png_charp chunkdata, png_size_t chunklength,
  185153. png_size_t prefix_length, png_size_t *data_length));
  185154. #endif
  185155. /* Read "skip" bytes, read the file crc, and (optionally) verify png_ptr->crc */
  185156. PNG_EXTERN int png_crc_finish PNGARG((png_structp png_ptr, png_uint_32 skip));
  185157. /* Read the CRC from the file and compare it to the libpng calculated CRC */
  185158. PNG_EXTERN int png_crc_error PNGARG((png_structp png_ptr));
  185159. /* Calculate the CRC over a section of data. Note that we are only
  185160. * passing a maximum of 64K on systems that have this as a memory limit,
  185161. * since this is the maximum buffer size we can specify.
  185162. */
  185163. PNG_EXTERN void png_calculate_crc PNGARG((png_structp png_ptr, png_bytep ptr,
  185164. png_size_t length));
  185165. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  185166. PNG_EXTERN void png_flush PNGARG((png_structp png_ptr));
  185167. #endif
  185168. /* simple function to write the signature */
  185169. PNG_EXTERN void png_write_sig PNGARG((png_structp png_ptr));
  185170. /* write various chunks */
  185171. /* Write the IHDR chunk, and update the png_struct with the necessary
  185172. * information.
  185173. */
  185174. PNG_EXTERN void png_write_IHDR PNGARG((png_structp png_ptr, png_uint_32 width,
  185175. png_uint_32 height,
  185176. int bit_depth, int color_type, int compression_method, int filter_method,
  185177. int interlace_method));
  185178. PNG_EXTERN void png_write_PLTE PNGARG((png_structp png_ptr, png_colorp palette,
  185179. png_uint_32 num_pal));
  185180. PNG_EXTERN void png_write_IDAT PNGARG((png_structp png_ptr, png_bytep data,
  185181. png_size_t length));
  185182. PNG_EXTERN void png_write_IEND PNGARG((png_structp png_ptr));
  185183. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  185184. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185185. PNG_EXTERN void png_write_gAMA PNGARG((png_structp png_ptr, double file_gamma));
  185186. #endif
  185187. #ifdef PNG_FIXED_POINT_SUPPORTED
  185188. PNG_EXTERN void png_write_gAMA_fixed PNGARG((png_structp png_ptr, png_fixed_point
  185189. file_gamma));
  185190. #endif
  185191. #endif
  185192. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  185193. PNG_EXTERN void png_write_sBIT PNGARG((png_structp png_ptr, png_color_8p sbit,
  185194. int color_type));
  185195. #endif
  185196. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  185197. #ifdef PNG_FLOATING_POINT_SUPPORTED
  185198. PNG_EXTERN void png_write_cHRM PNGARG((png_structp png_ptr,
  185199. double white_x, double white_y,
  185200. double red_x, double red_y, double green_x, double green_y,
  185201. double blue_x, double blue_y));
  185202. #endif
  185203. #ifdef PNG_FIXED_POINT_SUPPORTED
  185204. PNG_EXTERN void png_write_cHRM_fixed PNGARG((png_structp png_ptr,
  185205. png_fixed_point int_white_x, png_fixed_point int_white_y,
  185206. png_fixed_point int_red_x, png_fixed_point int_red_y, png_fixed_point
  185207. int_green_x, png_fixed_point int_green_y, png_fixed_point int_blue_x,
  185208. png_fixed_point int_blue_y));
  185209. #endif
  185210. #endif
  185211. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  185212. PNG_EXTERN void png_write_sRGB PNGARG((png_structp png_ptr,
  185213. int intent));
  185214. #endif
  185215. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  185216. PNG_EXTERN void png_write_iCCP PNGARG((png_structp png_ptr,
  185217. png_charp name, int compression_type,
  185218. png_charp profile, int proflen));
  185219. /* Note to maintainer: profile should be png_bytep */
  185220. #endif
  185221. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  185222. PNG_EXTERN void png_write_sPLT PNGARG((png_structp png_ptr,
  185223. png_sPLT_tp palette));
  185224. #endif
  185225. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  185226. PNG_EXTERN void png_write_tRNS PNGARG((png_structp png_ptr, png_bytep trans,
  185227. png_color_16p values, int number, int color_type));
  185228. #endif
  185229. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  185230. PNG_EXTERN void png_write_bKGD PNGARG((png_structp png_ptr,
  185231. png_color_16p values, int color_type));
  185232. #endif
  185233. #if defined(PNG_WRITE_hIST_SUPPORTED)
  185234. PNG_EXTERN void png_write_hIST PNGARG((png_structp png_ptr, png_uint_16p hist,
  185235. int num_hist));
  185236. #endif
  185237. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  185238. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  185239. PNG_EXTERN png_size_t png_check_keyword PNGARG((png_structp png_ptr,
  185240. png_charp key, png_charpp new_key));
  185241. #endif
  185242. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  185243. PNG_EXTERN void png_write_tEXt PNGARG((png_structp png_ptr, png_charp key,
  185244. png_charp text, png_size_t text_len));
  185245. #endif
  185246. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  185247. PNG_EXTERN void png_write_zTXt PNGARG((png_structp png_ptr, png_charp key,
  185248. png_charp text, png_size_t text_len, int compression));
  185249. #endif
  185250. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  185251. PNG_EXTERN void png_write_iTXt PNGARG((png_structp png_ptr,
  185252. int compression, png_charp key, png_charp lang, png_charp lang_key,
  185253. png_charp text));
  185254. #endif
  185255. #if defined(PNG_TEXT_SUPPORTED) /* Added at version 1.0.14 and 1.2.4 */
  185256. PNG_EXTERN int png_set_text_2 PNGARG((png_structp png_ptr,
  185257. png_infop info_ptr, png_textp text_ptr, int num_text));
  185258. #endif
  185259. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  185260. PNG_EXTERN void png_write_oFFs PNGARG((png_structp png_ptr,
  185261. png_int_32 x_offset, png_int_32 y_offset, int unit_type));
  185262. #endif
  185263. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  185264. PNG_EXTERN void png_write_pCAL PNGARG((png_structp png_ptr, png_charp purpose,
  185265. png_int_32 X0, png_int_32 X1, int type, int nparams,
  185266. png_charp units, png_charpp params));
  185267. #endif
  185268. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  185269. PNG_EXTERN void png_write_pHYs PNGARG((png_structp png_ptr,
  185270. png_uint_32 x_pixels_per_unit, png_uint_32 y_pixels_per_unit,
  185271. int unit_type));
  185272. #endif
  185273. #if defined(PNG_WRITE_tIME_SUPPORTED)
  185274. PNG_EXTERN void png_write_tIME PNGARG((png_structp png_ptr,
  185275. png_timep mod_time));
  185276. #endif
  185277. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  185278. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  185279. PNG_EXTERN void png_write_sCAL PNGARG((png_structp png_ptr,
  185280. int unit, double width, double height));
  185281. #else
  185282. #ifdef PNG_FIXED_POINT_SUPPORTED
  185283. PNG_EXTERN void png_write_sCAL_s PNGARG((png_structp png_ptr,
  185284. int unit, png_charp width, png_charp height));
  185285. #endif
  185286. #endif
  185287. #endif
  185288. /* Called when finished processing a row of data */
  185289. PNG_EXTERN void png_write_finish_row PNGARG((png_structp png_ptr));
  185290. /* Internal use only. Called before first row of data */
  185291. PNG_EXTERN void png_write_start_row PNGARG((png_structp png_ptr));
  185292. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185293. PNG_EXTERN void png_build_gamma_table PNGARG((png_structp png_ptr));
  185294. #endif
  185295. /* combine a row of data, dealing with alpha, etc. if requested */
  185296. PNG_EXTERN void png_combine_row PNGARG((png_structp png_ptr, png_bytep row,
  185297. int mask));
  185298. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  185299. /* expand an interlaced row */
  185300. /* OLD pre-1.0.9 interface:
  185301. PNG_EXTERN void png_do_read_interlace PNGARG((png_row_infop row_info,
  185302. png_bytep row, int pass, png_uint_32 transformations));
  185303. */
  185304. PNG_EXTERN void png_do_read_interlace PNGARG((png_structp png_ptr));
  185305. #endif
  185306. /* GRR TO DO (2.0 or whenever): simplify other internal calling interfaces */
  185307. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  185308. /* grab pixels out of a row for an interlaced pass */
  185309. PNG_EXTERN void png_do_write_interlace PNGARG((png_row_infop row_info,
  185310. png_bytep row, int pass));
  185311. #endif
  185312. /* unfilter a row */
  185313. PNG_EXTERN void png_read_filter_row PNGARG((png_structp png_ptr,
  185314. png_row_infop row_info, png_bytep row, png_bytep prev_row, int filter));
  185315. /* Choose the best filter to use and filter the row data */
  185316. PNG_EXTERN void png_write_find_filter PNGARG((png_structp png_ptr,
  185317. png_row_infop row_info));
  185318. /* Write out the filtered row. */
  185319. PNG_EXTERN void png_write_filtered_row PNGARG((png_structp png_ptr,
  185320. png_bytep filtered_row));
  185321. /* finish a row while reading, dealing with interlacing passes, etc. */
  185322. PNG_EXTERN void png_read_finish_row PNGARG((png_structp png_ptr));
  185323. /* initialize the row buffers, etc. */
  185324. PNG_EXTERN void png_read_start_row PNGARG((png_structp png_ptr));
  185325. /* optional call to update the users info structure */
  185326. PNG_EXTERN void png_read_transform_info PNGARG((png_structp png_ptr,
  185327. png_infop info_ptr));
  185328. /* these are the functions that do the transformations */
  185329. #if defined(PNG_READ_FILLER_SUPPORTED)
  185330. PNG_EXTERN void png_do_read_filler PNGARG((png_row_infop row_info,
  185331. png_bytep row, png_uint_32 filler, png_uint_32 flags));
  185332. #endif
  185333. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  185334. PNG_EXTERN void png_do_read_swap_alpha PNGARG((png_row_infop row_info,
  185335. png_bytep row));
  185336. #endif
  185337. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  185338. PNG_EXTERN void png_do_write_swap_alpha PNGARG((png_row_infop row_info,
  185339. png_bytep row));
  185340. #endif
  185341. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  185342. PNG_EXTERN void png_do_read_invert_alpha PNGARG((png_row_infop row_info,
  185343. png_bytep row));
  185344. #endif
  185345. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  185346. PNG_EXTERN void png_do_write_invert_alpha PNGARG((png_row_infop row_info,
  185347. png_bytep row));
  185348. #endif
  185349. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  185350. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  185351. PNG_EXTERN void png_do_strip_filler PNGARG((png_row_infop row_info,
  185352. png_bytep row, png_uint_32 flags));
  185353. #endif
  185354. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  185355. PNG_EXTERN void png_do_swap PNGARG((png_row_infop row_info, png_bytep row));
  185356. #endif
  185357. #if defined(PNG_READ_PACKSWAP_SUPPORTED) || defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  185358. PNG_EXTERN void png_do_packswap PNGARG((png_row_infop row_info, png_bytep row));
  185359. #endif
  185360. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  185361. PNG_EXTERN int png_do_rgb_to_gray PNGARG((png_structp png_ptr, png_row_infop
  185362. row_info, png_bytep row));
  185363. #endif
  185364. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  185365. PNG_EXTERN void png_do_gray_to_rgb PNGARG((png_row_infop row_info,
  185366. png_bytep row));
  185367. #endif
  185368. #if defined(PNG_READ_PACK_SUPPORTED)
  185369. PNG_EXTERN void png_do_unpack PNGARG((png_row_infop row_info, png_bytep row));
  185370. #endif
  185371. #if defined(PNG_READ_SHIFT_SUPPORTED)
  185372. PNG_EXTERN void png_do_unshift PNGARG((png_row_infop row_info, png_bytep row,
  185373. png_color_8p sig_bits));
  185374. #endif
  185375. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  185376. PNG_EXTERN void png_do_invert PNGARG((png_row_infop row_info, png_bytep row));
  185377. #endif
  185378. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  185379. PNG_EXTERN void png_do_chop PNGARG((png_row_infop row_info, png_bytep row));
  185380. #endif
  185381. #if defined(PNG_READ_DITHER_SUPPORTED)
  185382. PNG_EXTERN void png_do_dither PNGARG((png_row_infop row_info,
  185383. png_bytep row, png_bytep palette_lookup, png_bytep dither_lookup));
  185384. # if defined(PNG_CORRECT_PALETTE_SUPPORTED)
  185385. PNG_EXTERN void png_correct_palette PNGARG((png_structp png_ptr,
  185386. png_colorp palette, int num_palette));
  185387. # endif
  185388. #endif
  185389. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  185390. PNG_EXTERN void png_do_bgr PNGARG((png_row_infop row_info, png_bytep row));
  185391. #endif
  185392. #if defined(PNG_WRITE_PACK_SUPPORTED)
  185393. PNG_EXTERN void png_do_pack PNGARG((png_row_infop row_info,
  185394. png_bytep row, png_uint_32 bit_depth));
  185395. #endif
  185396. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  185397. PNG_EXTERN void png_do_shift PNGARG((png_row_infop row_info, png_bytep row,
  185398. png_color_8p bit_depth));
  185399. #endif
  185400. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  185401. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185402. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  185403. png_color_16p trans_values, png_color_16p background,
  185404. png_color_16p background_1,
  185405. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  185406. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  185407. png_uint_16pp gamma_16_to_1, int gamma_shift));
  185408. #else
  185409. PNG_EXTERN void png_do_background PNGARG((png_row_infop row_info, png_bytep row,
  185410. png_color_16p trans_values, png_color_16p background));
  185411. #endif
  185412. #endif
  185413. #if defined(PNG_READ_GAMMA_SUPPORTED)
  185414. PNG_EXTERN void png_do_gamma PNGARG((png_row_infop row_info, png_bytep row,
  185415. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  185416. int gamma_shift));
  185417. #endif
  185418. #if defined(PNG_READ_EXPAND_SUPPORTED)
  185419. PNG_EXTERN void png_do_expand_palette PNGARG((png_row_infop row_info,
  185420. png_bytep row, png_colorp palette, png_bytep trans, int num_trans));
  185421. PNG_EXTERN void png_do_expand PNGARG((png_row_infop row_info,
  185422. png_bytep row, png_color_16p trans_value));
  185423. #endif
  185424. /* The following decodes the appropriate chunks, and does error correction,
  185425. * then calls the appropriate callback for the chunk if it is valid.
  185426. */
  185427. /* decode the IHDR chunk */
  185428. PNG_EXTERN void png_handle_IHDR PNGARG((png_structp png_ptr, png_infop info_ptr,
  185429. png_uint_32 length));
  185430. PNG_EXTERN void png_handle_PLTE PNGARG((png_structp png_ptr, png_infop info_ptr,
  185431. png_uint_32 length));
  185432. PNG_EXTERN void png_handle_IEND PNGARG((png_structp png_ptr, png_infop info_ptr,
  185433. png_uint_32 length));
  185434. #if defined(PNG_READ_bKGD_SUPPORTED)
  185435. PNG_EXTERN void png_handle_bKGD PNGARG((png_structp png_ptr, png_infop info_ptr,
  185436. png_uint_32 length));
  185437. #endif
  185438. #if defined(PNG_READ_cHRM_SUPPORTED)
  185439. PNG_EXTERN void png_handle_cHRM PNGARG((png_structp png_ptr, png_infop info_ptr,
  185440. png_uint_32 length));
  185441. #endif
  185442. #if defined(PNG_READ_gAMA_SUPPORTED)
  185443. PNG_EXTERN void png_handle_gAMA PNGARG((png_structp png_ptr, png_infop info_ptr,
  185444. png_uint_32 length));
  185445. #endif
  185446. #if defined(PNG_READ_hIST_SUPPORTED)
  185447. PNG_EXTERN void png_handle_hIST PNGARG((png_structp png_ptr, png_infop info_ptr,
  185448. png_uint_32 length));
  185449. #endif
  185450. #if defined(PNG_READ_iCCP_SUPPORTED)
  185451. extern void png_handle_iCCP PNGARG((png_structp png_ptr, png_infop info_ptr,
  185452. png_uint_32 length));
  185453. #endif /* PNG_READ_iCCP_SUPPORTED */
  185454. #if defined(PNG_READ_iTXt_SUPPORTED)
  185455. PNG_EXTERN void png_handle_iTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  185456. png_uint_32 length));
  185457. #endif
  185458. #if defined(PNG_READ_oFFs_SUPPORTED)
  185459. PNG_EXTERN void png_handle_oFFs PNGARG((png_structp png_ptr, png_infop info_ptr,
  185460. png_uint_32 length));
  185461. #endif
  185462. #if defined(PNG_READ_pCAL_SUPPORTED)
  185463. PNG_EXTERN void png_handle_pCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  185464. png_uint_32 length));
  185465. #endif
  185466. #if defined(PNG_READ_pHYs_SUPPORTED)
  185467. PNG_EXTERN void png_handle_pHYs PNGARG((png_structp png_ptr, png_infop info_ptr,
  185468. png_uint_32 length));
  185469. #endif
  185470. #if defined(PNG_READ_sBIT_SUPPORTED)
  185471. PNG_EXTERN void png_handle_sBIT PNGARG((png_structp png_ptr, png_infop info_ptr,
  185472. png_uint_32 length));
  185473. #endif
  185474. #if defined(PNG_READ_sCAL_SUPPORTED)
  185475. PNG_EXTERN void png_handle_sCAL PNGARG((png_structp png_ptr, png_infop info_ptr,
  185476. png_uint_32 length));
  185477. #endif
  185478. #if defined(PNG_READ_sPLT_SUPPORTED)
  185479. extern void png_handle_sPLT PNGARG((png_structp png_ptr, png_infop info_ptr,
  185480. png_uint_32 length));
  185481. #endif /* PNG_READ_sPLT_SUPPORTED */
  185482. #if defined(PNG_READ_sRGB_SUPPORTED)
  185483. PNG_EXTERN void png_handle_sRGB PNGARG((png_structp png_ptr, png_infop info_ptr,
  185484. png_uint_32 length));
  185485. #endif
  185486. #if defined(PNG_READ_tEXt_SUPPORTED)
  185487. PNG_EXTERN void png_handle_tEXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  185488. png_uint_32 length));
  185489. #endif
  185490. #if defined(PNG_READ_tIME_SUPPORTED)
  185491. PNG_EXTERN void png_handle_tIME PNGARG((png_structp png_ptr, png_infop info_ptr,
  185492. png_uint_32 length));
  185493. #endif
  185494. #if defined(PNG_READ_tRNS_SUPPORTED)
  185495. PNG_EXTERN void png_handle_tRNS PNGARG((png_structp png_ptr, png_infop info_ptr,
  185496. png_uint_32 length));
  185497. #endif
  185498. #if defined(PNG_READ_zTXt_SUPPORTED)
  185499. PNG_EXTERN void png_handle_zTXt PNGARG((png_structp png_ptr, png_infop info_ptr,
  185500. png_uint_32 length));
  185501. #endif
  185502. PNG_EXTERN void png_handle_unknown PNGARG((png_structp png_ptr,
  185503. png_infop info_ptr, png_uint_32 length));
  185504. PNG_EXTERN void png_check_chunk_name PNGARG((png_structp png_ptr,
  185505. png_bytep chunk_name));
  185506. /* handle the transformations for reading and writing */
  185507. PNG_EXTERN void png_do_read_transformations PNGARG((png_structp png_ptr));
  185508. PNG_EXTERN void png_do_write_transformations PNGARG((png_structp png_ptr));
  185509. PNG_EXTERN void png_init_read_transformations PNGARG((png_structp png_ptr));
  185510. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  185511. PNG_EXTERN void png_push_read_chunk PNGARG((png_structp png_ptr,
  185512. png_infop info_ptr));
  185513. PNG_EXTERN void png_push_read_sig PNGARG((png_structp png_ptr,
  185514. png_infop info_ptr));
  185515. PNG_EXTERN void png_push_check_crc PNGARG((png_structp png_ptr));
  185516. PNG_EXTERN void png_push_crc_skip PNGARG((png_structp png_ptr,
  185517. png_uint_32 length));
  185518. PNG_EXTERN void png_push_crc_finish PNGARG((png_structp png_ptr));
  185519. PNG_EXTERN void png_push_save_buffer PNGARG((png_structp png_ptr));
  185520. PNG_EXTERN void png_push_restore_buffer PNGARG((png_structp png_ptr,
  185521. png_bytep buffer, png_size_t buffer_length));
  185522. PNG_EXTERN void png_push_read_IDAT PNGARG((png_structp png_ptr));
  185523. PNG_EXTERN void png_process_IDAT_data PNGARG((png_structp png_ptr,
  185524. png_bytep buffer, png_size_t buffer_length));
  185525. PNG_EXTERN void png_push_process_row PNGARG((png_structp png_ptr));
  185526. PNG_EXTERN void png_push_handle_unknown PNGARG((png_structp png_ptr,
  185527. png_infop info_ptr, png_uint_32 length));
  185528. PNG_EXTERN void png_push_have_info PNGARG((png_structp png_ptr,
  185529. png_infop info_ptr));
  185530. PNG_EXTERN void png_push_have_end PNGARG((png_structp png_ptr,
  185531. png_infop info_ptr));
  185532. PNG_EXTERN void png_push_have_row PNGARG((png_structp png_ptr, png_bytep row));
  185533. PNG_EXTERN void png_push_read_end PNGARG((png_structp png_ptr,
  185534. png_infop info_ptr));
  185535. PNG_EXTERN void png_process_some_data PNGARG((png_structp png_ptr,
  185536. png_infop info_ptr));
  185537. PNG_EXTERN void png_read_push_finish_row PNGARG((png_structp png_ptr));
  185538. #if defined(PNG_READ_tEXt_SUPPORTED)
  185539. PNG_EXTERN void png_push_handle_tEXt PNGARG((png_structp png_ptr,
  185540. png_infop info_ptr, png_uint_32 length));
  185541. PNG_EXTERN void png_push_read_tEXt PNGARG((png_structp png_ptr,
  185542. png_infop info_ptr));
  185543. #endif
  185544. #if defined(PNG_READ_zTXt_SUPPORTED)
  185545. PNG_EXTERN void png_push_handle_zTXt PNGARG((png_structp png_ptr,
  185546. png_infop info_ptr, png_uint_32 length));
  185547. PNG_EXTERN void png_push_read_zTXt PNGARG((png_structp png_ptr,
  185548. png_infop info_ptr));
  185549. #endif
  185550. #if defined(PNG_READ_iTXt_SUPPORTED)
  185551. PNG_EXTERN void png_push_handle_iTXt PNGARG((png_structp png_ptr,
  185552. png_infop info_ptr, png_uint_32 length));
  185553. PNG_EXTERN void png_push_read_iTXt PNGARG((png_structp png_ptr,
  185554. png_infop info_ptr));
  185555. #endif
  185556. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  185557. #ifdef PNG_MNG_FEATURES_SUPPORTED
  185558. PNG_EXTERN void png_do_read_intrapixel PNGARG((png_row_infop row_info,
  185559. png_bytep row));
  185560. PNG_EXTERN void png_do_write_intrapixel PNGARG((png_row_infop row_info,
  185561. png_bytep row));
  185562. #endif
  185563. #if defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  185564. #if defined(PNG_MMX_CODE_SUPPORTED)
  185565. /* png.c */ /* PRIVATE */
  185566. PNG_EXTERN void png_init_mmx_flags PNGARG((png_structp png_ptr));
  185567. #endif
  185568. #endif
  185569. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  185570. PNG_EXTERN png_uint_32 png_get_pixels_per_inch PNGARG((png_structp png_ptr,
  185571. png_infop info_ptr));
  185572. PNG_EXTERN png_uint_32 png_get_x_pixels_per_inch PNGARG((png_structp png_ptr,
  185573. png_infop info_ptr));
  185574. PNG_EXTERN png_uint_32 png_get_y_pixels_per_inch PNGARG((png_structp png_ptr,
  185575. png_infop info_ptr));
  185576. PNG_EXTERN float png_get_x_offset_inches PNGARG((png_structp png_ptr,
  185577. png_infop info_ptr));
  185578. PNG_EXTERN float png_get_y_offset_inches PNGARG((png_structp png_ptr,
  185579. png_infop info_ptr));
  185580. #if defined(PNG_pHYs_SUPPORTED)
  185581. PNG_EXTERN png_uint_32 png_get_pHYs_dpi PNGARG((png_structp png_ptr,
  185582. png_infop info_ptr, png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type));
  185583. #endif /* PNG_pHYs_SUPPORTED */
  185584. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  185585. /* Maintainer: Put new private prototypes here ^ and in libpngpf.3 */
  185586. #endif /* PNG_INTERNAL */
  185587. #ifdef __cplusplus
  185588. }
  185589. #endif
  185590. #endif /* PNG_VERSION_INFO_ONLY */
  185591. /* do not put anything past this line */
  185592. #endif /* PNG_H */
  185593. /********* End of inlined file: png.h *********/
  185594. #define PNG_NO_EXTERN
  185595. /********* Start of inlined file: png.c *********/
  185596. /* png.c - location for general purpose libpng functions
  185597. *
  185598. * Last changed in libpng 1.2.21 [October 4, 2007]
  185599. * For conditions of distribution and use, see copyright notice in png.h
  185600. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  185601. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  185602. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  185603. */
  185604. #define PNG_INTERNAL
  185605. #define PNG_NO_EXTERN
  185606. /* Generate a compiler error if there is an old png.h in the search path. */
  185607. typedef version_1_2_21 Your_png_h_is_not_version_1_2_21;
  185608. /* Version information for C files. This had better match the version
  185609. * string defined in png.h. */
  185610. #ifdef PNG_USE_GLOBAL_ARRAYS
  185611. /* png_libpng_ver was changed to a function in version 1.0.5c */
  185612. PNG_CONST char png_libpng_ver[18] = PNG_LIBPNG_VER_STRING;
  185613. #ifdef PNG_READ_SUPPORTED
  185614. /* png_sig was changed to a function in version 1.0.5c */
  185615. /* Place to hold the signature string for a PNG file. */
  185616. PNG_CONST png_byte FARDATA png_sig[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  185617. #endif /* PNG_READ_SUPPORTED */
  185618. /* Invoke global declarations for constant strings for known chunk types */
  185619. PNG_IHDR;
  185620. PNG_IDAT;
  185621. PNG_IEND;
  185622. PNG_PLTE;
  185623. PNG_bKGD;
  185624. PNG_cHRM;
  185625. PNG_gAMA;
  185626. PNG_hIST;
  185627. PNG_iCCP;
  185628. PNG_iTXt;
  185629. PNG_oFFs;
  185630. PNG_pCAL;
  185631. PNG_sCAL;
  185632. PNG_pHYs;
  185633. PNG_sBIT;
  185634. PNG_sPLT;
  185635. PNG_sRGB;
  185636. PNG_tEXt;
  185637. PNG_tIME;
  185638. PNG_tRNS;
  185639. PNG_zTXt;
  185640. #ifdef PNG_READ_SUPPORTED
  185641. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  185642. /* start of interlace block */
  185643. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  185644. /* offset to next interlace block */
  185645. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  185646. /* start of interlace block in the y direction */
  185647. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  185648. /* offset to next interlace block in the y direction */
  185649. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  185650. /* Height of interlace block. This is not currently used - if you need
  185651. * it, uncomment it here and in png.h
  185652. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  185653. */
  185654. /* Mask to determine which pixels are valid in a pass */
  185655. PNG_CONST int FARDATA png_pass_mask[] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  185656. /* Mask to determine which pixels to overwrite while displaying */
  185657. PNG_CONST int FARDATA png_pass_dsp_mask[]
  185658. = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  185659. #endif /* PNG_READ_SUPPORTED */
  185660. #endif /* PNG_USE_GLOBAL_ARRAYS */
  185661. /* Tells libpng that we have already handled the first "num_bytes" bytes
  185662. * of the PNG file signature. If the PNG data is embedded into another
  185663. * stream we can set num_bytes = 8 so that libpng will not attempt to read
  185664. * or write any of the magic bytes before it starts on the IHDR.
  185665. */
  185666. #ifdef PNG_READ_SUPPORTED
  185667. void PNGAPI
  185668. png_set_sig_bytes(png_structp png_ptr, int num_bytes)
  185669. {
  185670. if(png_ptr == NULL) return;
  185671. png_debug(1, "in png_set_sig_bytes\n");
  185672. if (num_bytes > 8)
  185673. png_error(png_ptr, "Too many bytes for PNG signature.");
  185674. png_ptr->sig_bytes = (png_byte)(num_bytes < 0 ? 0 : num_bytes);
  185675. }
  185676. /* Checks whether the supplied bytes match the PNG signature. We allow
  185677. * checking less than the full 8-byte signature so that those apps that
  185678. * already read the first few bytes of a file to determine the file type
  185679. * can simply check the remaining bytes for extra assurance. Returns
  185680. * an integer less than, equal to, or greater than zero if sig is found,
  185681. * respectively, to be less than, to match, or be greater than the correct
  185682. * PNG signature (this is the same behaviour as strcmp, memcmp, etc).
  185683. */
  185684. int PNGAPI
  185685. png_sig_cmp(png_bytep sig, png_size_t start, png_size_t num_to_check)
  185686. {
  185687. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  185688. if (num_to_check > 8)
  185689. num_to_check = 8;
  185690. else if (num_to_check < 1)
  185691. return (-1);
  185692. if (start > 7)
  185693. return (-1);
  185694. if (start + num_to_check > 8)
  185695. num_to_check = 8 - start;
  185696. return ((int)(png_memcmp(&sig[start], &png_signature[start], num_to_check)));
  185697. }
  185698. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  185699. /* (Obsolete) function to check signature bytes. It does not allow one
  185700. * to check a partial signature. This function might be removed in the
  185701. * future - use png_sig_cmp(). Returns true (nonzero) if the file is PNG.
  185702. */
  185703. int PNGAPI
  185704. png_check_sig(png_bytep sig, int num)
  185705. {
  185706. return ((int)!png_sig_cmp(sig, (png_size_t)0, (png_size_t)num));
  185707. }
  185708. #endif
  185709. #endif /* PNG_READ_SUPPORTED */
  185710. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  185711. /* Function to allocate memory for zlib and clear it to 0. */
  185712. #ifdef PNG_1_0_X
  185713. voidpf PNGAPI
  185714. #else
  185715. voidpf /* private */
  185716. #endif
  185717. png_zalloc(voidpf png_ptr, uInt items, uInt size)
  185718. {
  185719. png_voidp ptr;
  185720. png_structp p=(png_structp)png_ptr;
  185721. png_uint_32 save_flags=p->flags;
  185722. png_uint_32 num_bytes;
  185723. if(png_ptr == NULL) return (NULL);
  185724. if (items > PNG_UINT_32_MAX/size)
  185725. {
  185726. png_warning (p, "Potential overflow in png_zalloc()");
  185727. return (NULL);
  185728. }
  185729. num_bytes = (png_uint_32)items * size;
  185730. p->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  185731. ptr = (png_voidp)png_malloc((png_structp)png_ptr, num_bytes);
  185732. p->flags=save_flags;
  185733. #if defined(PNG_1_0_X) && !defined(PNG_NO_ZALLOC_ZERO)
  185734. if (ptr == NULL)
  185735. return ((voidpf)ptr);
  185736. if (num_bytes > (png_uint_32)0x8000L)
  185737. {
  185738. png_memset(ptr, 0, (png_size_t)0x8000L);
  185739. png_memset((png_bytep)ptr + (png_size_t)0x8000L, 0,
  185740. (png_size_t)(num_bytes - (png_uint_32)0x8000L));
  185741. }
  185742. else
  185743. {
  185744. png_memset(ptr, 0, (png_size_t)num_bytes);
  185745. }
  185746. #endif
  185747. return ((voidpf)ptr);
  185748. }
  185749. /* function to free memory for zlib */
  185750. #ifdef PNG_1_0_X
  185751. void PNGAPI
  185752. #else
  185753. void /* private */
  185754. #endif
  185755. png_zfree(voidpf png_ptr, voidpf ptr)
  185756. {
  185757. png_free((png_structp)png_ptr, (png_voidp)ptr);
  185758. }
  185759. /* Reset the CRC variable to 32 bits of 1's. Care must be taken
  185760. * in case CRC is > 32 bits to leave the top bits 0.
  185761. */
  185762. void /* PRIVATE */
  185763. png_reset_crc(png_structp png_ptr)
  185764. {
  185765. png_ptr->crc = crc32(0, Z_NULL, 0);
  185766. }
  185767. /* Calculate the CRC over a section of data. We can only pass as
  185768. * much data to this routine as the largest single buffer size. We
  185769. * also check that this data will actually be used before going to the
  185770. * trouble of calculating it.
  185771. */
  185772. void /* PRIVATE */
  185773. png_calculate_crc(png_structp png_ptr, png_bytep ptr, png_size_t length)
  185774. {
  185775. int need_crc = 1;
  185776. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  185777. {
  185778. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  185779. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  185780. need_crc = 0;
  185781. }
  185782. else /* critical */
  185783. {
  185784. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  185785. need_crc = 0;
  185786. }
  185787. if (need_crc)
  185788. png_ptr->crc = crc32(png_ptr->crc, ptr, (uInt)length);
  185789. }
  185790. /* Allocate the memory for an info_struct for the application. We don't
  185791. * really need the png_ptr, but it could potentially be useful in the
  185792. * future. This should be used in favour of malloc(png_sizeof(png_info))
  185793. * and png_info_init() so that applications that want to use a shared
  185794. * libpng don't have to be recompiled if png_info changes size.
  185795. */
  185796. png_infop PNGAPI
  185797. png_create_info_struct(png_structp png_ptr)
  185798. {
  185799. png_infop info_ptr;
  185800. png_debug(1, "in png_create_info_struct\n");
  185801. if(png_ptr == NULL) return (NULL);
  185802. #ifdef PNG_USER_MEM_SUPPORTED
  185803. info_ptr = (png_infop)png_create_struct_2(PNG_STRUCT_INFO,
  185804. png_ptr->malloc_fn, png_ptr->mem_ptr);
  185805. #else
  185806. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185807. #endif
  185808. if (info_ptr != NULL)
  185809. png_info_init_3(&info_ptr, png_sizeof(png_info));
  185810. return (info_ptr);
  185811. }
  185812. /* This function frees the memory associated with a single info struct.
  185813. * Normally, one would use either png_destroy_read_struct() or
  185814. * png_destroy_write_struct() to free an info struct, but this may be
  185815. * useful for some applications.
  185816. */
  185817. void PNGAPI
  185818. png_destroy_info_struct(png_structp png_ptr, png_infopp info_ptr_ptr)
  185819. {
  185820. png_infop info_ptr = NULL;
  185821. if(png_ptr == NULL) return;
  185822. png_debug(1, "in png_destroy_info_struct\n");
  185823. if (info_ptr_ptr != NULL)
  185824. info_ptr = *info_ptr_ptr;
  185825. if (info_ptr != NULL)
  185826. {
  185827. png_info_destroy(png_ptr, info_ptr);
  185828. #ifdef PNG_USER_MEM_SUPPORTED
  185829. png_destroy_struct_2((png_voidp)info_ptr, png_ptr->free_fn,
  185830. png_ptr->mem_ptr);
  185831. #else
  185832. png_destroy_struct((png_voidp)info_ptr);
  185833. #endif
  185834. *info_ptr_ptr = NULL;
  185835. }
  185836. }
  185837. /* Initialize the info structure. This is now an internal function (0.89)
  185838. * and applications using it are urged to use png_create_info_struct()
  185839. * instead.
  185840. */
  185841. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  185842. #undef png_info_init
  185843. void PNGAPI
  185844. png_info_init(png_infop info_ptr)
  185845. {
  185846. /* We only come here via pre-1.0.12-compiled applications */
  185847. png_info_init_3(&info_ptr, 0);
  185848. }
  185849. #endif
  185850. void PNGAPI
  185851. png_info_init_3(png_infopp ptr_ptr, png_size_t png_info_struct_size)
  185852. {
  185853. png_infop info_ptr = *ptr_ptr;
  185854. if(info_ptr == NULL) return;
  185855. png_debug(1, "in png_info_init_3\n");
  185856. if(png_sizeof(png_info) > png_info_struct_size)
  185857. {
  185858. png_destroy_struct(info_ptr);
  185859. info_ptr = (png_infop)png_create_struct(PNG_STRUCT_INFO);
  185860. *ptr_ptr = info_ptr;
  185861. }
  185862. /* set everything to 0 */
  185863. png_memset(info_ptr, 0, png_sizeof (png_info));
  185864. }
  185865. #ifdef PNG_FREE_ME_SUPPORTED
  185866. void PNGAPI
  185867. png_data_freer(png_structp png_ptr, png_infop info_ptr,
  185868. int freer, png_uint_32 mask)
  185869. {
  185870. png_debug(1, "in png_data_freer\n");
  185871. if (png_ptr == NULL || info_ptr == NULL)
  185872. return;
  185873. if(freer == PNG_DESTROY_WILL_FREE_DATA)
  185874. info_ptr->free_me |= mask;
  185875. else if(freer == PNG_USER_WILL_FREE_DATA)
  185876. info_ptr->free_me &= ~mask;
  185877. else
  185878. png_warning(png_ptr,
  185879. "Unknown freer parameter in png_data_freer.");
  185880. }
  185881. #endif
  185882. void PNGAPI
  185883. png_free_data(png_structp png_ptr, png_infop info_ptr, png_uint_32 mask,
  185884. int num)
  185885. {
  185886. png_debug(1, "in png_free_data\n");
  185887. if (png_ptr == NULL || info_ptr == NULL)
  185888. return;
  185889. #if defined(PNG_TEXT_SUPPORTED)
  185890. /* free text item num or (if num == -1) all text items */
  185891. #ifdef PNG_FREE_ME_SUPPORTED
  185892. if ((mask & PNG_FREE_TEXT) & info_ptr->free_me)
  185893. #else
  185894. if (mask & PNG_FREE_TEXT)
  185895. #endif
  185896. {
  185897. if (num != -1)
  185898. {
  185899. if (info_ptr->text && info_ptr->text[num].key)
  185900. {
  185901. png_free(png_ptr, info_ptr->text[num].key);
  185902. info_ptr->text[num].key = NULL;
  185903. }
  185904. }
  185905. else
  185906. {
  185907. int i;
  185908. for (i = 0; i < info_ptr->num_text; i++)
  185909. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, i);
  185910. png_free(png_ptr, info_ptr->text);
  185911. info_ptr->text = NULL;
  185912. info_ptr->num_text=0;
  185913. }
  185914. }
  185915. #endif
  185916. #if defined(PNG_tRNS_SUPPORTED)
  185917. /* free any tRNS entry */
  185918. #ifdef PNG_FREE_ME_SUPPORTED
  185919. if ((mask & PNG_FREE_TRNS) & info_ptr->free_me)
  185920. #else
  185921. if ((mask & PNG_FREE_TRNS) && (png_ptr->flags & PNG_FLAG_FREE_TRNS))
  185922. #endif
  185923. {
  185924. png_free(png_ptr, info_ptr->trans);
  185925. info_ptr->valid &= ~PNG_INFO_tRNS;
  185926. #ifndef PNG_FREE_ME_SUPPORTED
  185927. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  185928. #endif
  185929. info_ptr->trans = NULL;
  185930. }
  185931. #endif
  185932. #if defined(PNG_sCAL_SUPPORTED)
  185933. /* free any sCAL entry */
  185934. #ifdef PNG_FREE_ME_SUPPORTED
  185935. if ((mask & PNG_FREE_SCAL) & info_ptr->free_me)
  185936. #else
  185937. if (mask & PNG_FREE_SCAL)
  185938. #endif
  185939. {
  185940. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  185941. png_free(png_ptr, info_ptr->scal_s_width);
  185942. png_free(png_ptr, info_ptr->scal_s_height);
  185943. info_ptr->scal_s_width = NULL;
  185944. info_ptr->scal_s_height = NULL;
  185945. #endif
  185946. info_ptr->valid &= ~PNG_INFO_sCAL;
  185947. }
  185948. #endif
  185949. #if defined(PNG_pCAL_SUPPORTED)
  185950. /* free any pCAL entry */
  185951. #ifdef PNG_FREE_ME_SUPPORTED
  185952. if ((mask & PNG_FREE_PCAL) & info_ptr->free_me)
  185953. #else
  185954. if (mask & PNG_FREE_PCAL)
  185955. #endif
  185956. {
  185957. png_free(png_ptr, info_ptr->pcal_purpose);
  185958. png_free(png_ptr, info_ptr->pcal_units);
  185959. info_ptr->pcal_purpose = NULL;
  185960. info_ptr->pcal_units = NULL;
  185961. if (info_ptr->pcal_params != NULL)
  185962. {
  185963. int i;
  185964. for (i = 0; i < (int)info_ptr->pcal_nparams; i++)
  185965. {
  185966. png_free(png_ptr, info_ptr->pcal_params[i]);
  185967. info_ptr->pcal_params[i]=NULL;
  185968. }
  185969. png_free(png_ptr, info_ptr->pcal_params);
  185970. info_ptr->pcal_params = NULL;
  185971. }
  185972. info_ptr->valid &= ~PNG_INFO_pCAL;
  185973. }
  185974. #endif
  185975. #if defined(PNG_iCCP_SUPPORTED)
  185976. /* free any iCCP entry */
  185977. #ifdef PNG_FREE_ME_SUPPORTED
  185978. if ((mask & PNG_FREE_ICCP) & info_ptr->free_me)
  185979. #else
  185980. if (mask & PNG_FREE_ICCP)
  185981. #endif
  185982. {
  185983. png_free(png_ptr, info_ptr->iccp_name);
  185984. png_free(png_ptr, info_ptr->iccp_profile);
  185985. info_ptr->iccp_name = NULL;
  185986. info_ptr->iccp_profile = NULL;
  185987. info_ptr->valid &= ~PNG_INFO_iCCP;
  185988. }
  185989. #endif
  185990. #if defined(PNG_sPLT_SUPPORTED)
  185991. /* free a given sPLT entry, or (if num == -1) all sPLT entries */
  185992. #ifdef PNG_FREE_ME_SUPPORTED
  185993. if ((mask & PNG_FREE_SPLT) & info_ptr->free_me)
  185994. #else
  185995. if (mask & PNG_FREE_SPLT)
  185996. #endif
  185997. {
  185998. if (num != -1)
  185999. {
  186000. if(info_ptr->splt_palettes)
  186001. {
  186002. png_free(png_ptr, info_ptr->splt_palettes[num].name);
  186003. png_free(png_ptr, info_ptr->splt_palettes[num].entries);
  186004. info_ptr->splt_palettes[num].name = NULL;
  186005. info_ptr->splt_palettes[num].entries = NULL;
  186006. }
  186007. }
  186008. else
  186009. {
  186010. if(info_ptr->splt_palettes_num)
  186011. {
  186012. int i;
  186013. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  186014. png_free_data(png_ptr, info_ptr, PNG_FREE_SPLT, i);
  186015. png_free(png_ptr, info_ptr->splt_palettes);
  186016. info_ptr->splt_palettes = NULL;
  186017. info_ptr->splt_palettes_num = 0;
  186018. }
  186019. info_ptr->valid &= ~PNG_INFO_sPLT;
  186020. }
  186021. }
  186022. #endif
  186023. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186024. if(png_ptr->unknown_chunk.data)
  186025. {
  186026. png_free(png_ptr, png_ptr->unknown_chunk.data);
  186027. png_ptr->unknown_chunk.data = NULL;
  186028. }
  186029. #ifdef PNG_FREE_ME_SUPPORTED
  186030. if ((mask & PNG_FREE_UNKN) & info_ptr->free_me)
  186031. #else
  186032. if (mask & PNG_FREE_UNKN)
  186033. #endif
  186034. {
  186035. if (num != -1)
  186036. {
  186037. if(info_ptr->unknown_chunks)
  186038. {
  186039. png_free(png_ptr, info_ptr->unknown_chunks[num].data);
  186040. info_ptr->unknown_chunks[num].data = NULL;
  186041. }
  186042. }
  186043. else
  186044. {
  186045. int i;
  186046. if(info_ptr->unknown_chunks_num)
  186047. {
  186048. for (i = 0; i < (int)info_ptr->unknown_chunks_num; i++)
  186049. png_free_data(png_ptr, info_ptr, PNG_FREE_UNKN, i);
  186050. png_free(png_ptr, info_ptr->unknown_chunks);
  186051. info_ptr->unknown_chunks = NULL;
  186052. info_ptr->unknown_chunks_num = 0;
  186053. }
  186054. }
  186055. }
  186056. #endif
  186057. #if defined(PNG_hIST_SUPPORTED)
  186058. /* free any hIST entry */
  186059. #ifdef PNG_FREE_ME_SUPPORTED
  186060. if ((mask & PNG_FREE_HIST) & info_ptr->free_me)
  186061. #else
  186062. if ((mask & PNG_FREE_HIST) && (png_ptr->flags & PNG_FLAG_FREE_HIST))
  186063. #endif
  186064. {
  186065. png_free(png_ptr, info_ptr->hist);
  186066. info_ptr->hist = NULL;
  186067. info_ptr->valid &= ~PNG_INFO_hIST;
  186068. #ifndef PNG_FREE_ME_SUPPORTED
  186069. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  186070. #endif
  186071. }
  186072. #endif
  186073. /* free any PLTE entry that was internally allocated */
  186074. #ifdef PNG_FREE_ME_SUPPORTED
  186075. if ((mask & PNG_FREE_PLTE) & info_ptr->free_me)
  186076. #else
  186077. if ((mask & PNG_FREE_PLTE) && (png_ptr->flags & PNG_FLAG_FREE_PLTE))
  186078. #endif
  186079. {
  186080. png_zfree(png_ptr, info_ptr->palette);
  186081. info_ptr->palette = NULL;
  186082. info_ptr->valid &= ~PNG_INFO_PLTE;
  186083. #ifndef PNG_FREE_ME_SUPPORTED
  186084. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  186085. #endif
  186086. info_ptr->num_palette = 0;
  186087. }
  186088. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  186089. /* free any image bits attached to the info structure */
  186090. #ifdef PNG_FREE_ME_SUPPORTED
  186091. if ((mask & PNG_FREE_ROWS) & info_ptr->free_me)
  186092. #else
  186093. if (mask & PNG_FREE_ROWS)
  186094. #endif
  186095. {
  186096. if(info_ptr->row_pointers)
  186097. {
  186098. int row;
  186099. for (row = 0; row < (int)info_ptr->height; row++)
  186100. {
  186101. png_free(png_ptr, info_ptr->row_pointers[row]);
  186102. info_ptr->row_pointers[row]=NULL;
  186103. }
  186104. png_free(png_ptr, info_ptr->row_pointers);
  186105. info_ptr->row_pointers=NULL;
  186106. }
  186107. info_ptr->valid &= ~PNG_INFO_IDAT;
  186108. }
  186109. #endif
  186110. #ifdef PNG_FREE_ME_SUPPORTED
  186111. if(num == -1)
  186112. info_ptr->free_me &= ~mask;
  186113. else
  186114. info_ptr->free_me &= ~(mask & ~PNG_FREE_MUL);
  186115. #endif
  186116. }
  186117. /* This is an internal routine to free any memory that the info struct is
  186118. * pointing to before re-using it or freeing the struct itself. Recall
  186119. * that png_free() checks for NULL pointers for us.
  186120. */
  186121. void /* PRIVATE */
  186122. png_info_destroy(png_structp png_ptr, png_infop info_ptr)
  186123. {
  186124. png_debug(1, "in png_info_destroy\n");
  186125. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  186126. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  186127. if (png_ptr->num_chunk_list)
  186128. {
  186129. png_free(png_ptr, png_ptr->chunk_list);
  186130. png_ptr->chunk_list=NULL;
  186131. png_ptr->num_chunk_list=0;
  186132. }
  186133. #endif
  186134. png_info_init_3(&info_ptr, png_sizeof(png_info));
  186135. }
  186136. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  186137. /* This function returns a pointer to the io_ptr associated with the user
  186138. * functions. The application should free any memory associated with this
  186139. * pointer before png_write_destroy() or png_read_destroy() are called.
  186140. */
  186141. png_voidp PNGAPI
  186142. png_get_io_ptr(png_structp png_ptr)
  186143. {
  186144. if(png_ptr == NULL) return (NULL);
  186145. return (png_ptr->io_ptr);
  186146. }
  186147. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186148. #if !defined(PNG_NO_STDIO)
  186149. /* Initialize the default input/output functions for the PNG file. If you
  186150. * use your own read or write routines, you can call either png_set_read_fn()
  186151. * or png_set_write_fn() instead of png_init_io(). If you have defined
  186152. * PNG_NO_STDIO, you must use a function of your own because "FILE *" isn't
  186153. * necessarily available.
  186154. */
  186155. void PNGAPI
  186156. png_init_io(png_structp png_ptr, png_FILE_p fp)
  186157. {
  186158. png_debug(1, "in png_init_io\n");
  186159. if(png_ptr == NULL) return;
  186160. png_ptr->io_ptr = (png_voidp)fp;
  186161. }
  186162. #endif
  186163. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  186164. /* Convert the supplied time into an RFC 1123 string suitable for use in
  186165. * a "Creation Time" or other text-based time string.
  186166. */
  186167. png_charp PNGAPI
  186168. png_convert_to_rfc1123(png_structp png_ptr, png_timep ptime)
  186169. {
  186170. static PNG_CONST char short_months[12][4] =
  186171. {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
  186172. "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
  186173. if(png_ptr == NULL) return (NULL);
  186174. if (png_ptr->time_buffer == NULL)
  186175. {
  186176. png_ptr->time_buffer = (png_charp)png_malloc(png_ptr, (png_uint_32)(29*
  186177. png_sizeof(char)));
  186178. }
  186179. #if defined(_WIN32_WCE)
  186180. {
  186181. wchar_t time_buf[29];
  186182. wsprintf(time_buf, TEXT("%d %S %d %02d:%02d:%02d +0000"),
  186183. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  186184. ptime->year, ptime->hour % 24, ptime->minute % 60,
  186185. ptime->second % 61);
  186186. WideCharToMultiByte(CP_ACP, 0, time_buf, -1, png_ptr->time_buffer, 29,
  186187. NULL, NULL);
  186188. }
  186189. #else
  186190. #ifdef USE_FAR_KEYWORD
  186191. {
  186192. char near_time_buf[29];
  186193. png_snprintf6(near_time_buf,29,"%d %s %d %02d:%02d:%02d +0000",
  186194. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  186195. ptime->year, ptime->hour % 24, ptime->minute % 60,
  186196. ptime->second % 61);
  186197. png_memcpy(png_ptr->time_buffer, near_time_buf,
  186198. 29*png_sizeof(char));
  186199. }
  186200. #else
  186201. png_snprintf6(png_ptr->time_buffer,29,"%d %s %d %02d:%02d:%02d +0000",
  186202. ptime->day % 32, short_months[(ptime->month - 1) % 12],
  186203. ptime->year, ptime->hour % 24, ptime->minute % 60,
  186204. ptime->second % 61);
  186205. #endif
  186206. #endif /* _WIN32_WCE */
  186207. return ((png_charp)png_ptr->time_buffer);
  186208. }
  186209. #endif /* PNG_TIME_RFC1123_SUPPORTED */
  186210. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  186211. png_charp PNGAPI
  186212. png_get_copyright(png_structp png_ptr)
  186213. {
  186214. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  186215. return ((png_charp) "\n libpng version 1.2.21 - October 4, 2007\n\
  186216. Copyright (c) 1998-2007 Glenn Randers-Pehrson\n\
  186217. Copyright (c) 1996-1997 Andreas Dilger\n\
  186218. Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.\n");
  186219. }
  186220. /* The following return the library version as a short string in the
  186221. * format 1.0.0 through 99.99.99zz. To get the version of *.h files
  186222. * used with your application, print out PNG_LIBPNG_VER_STRING, which
  186223. * is defined in png.h.
  186224. * Note: now there is no difference between png_get_libpng_ver() and
  186225. * png_get_header_ver(). Due to the version_nn_nn_nn typedef guard,
  186226. * it is guaranteed that png.c uses the correct version of png.h.
  186227. */
  186228. png_charp PNGAPI
  186229. png_get_libpng_ver(png_structp png_ptr)
  186230. {
  186231. /* Version of *.c files used when building libpng */
  186232. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  186233. return ((png_charp) PNG_LIBPNG_VER_STRING);
  186234. }
  186235. png_charp PNGAPI
  186236. png_get_header_ver(png_structp png_ptr)
  186237. {
  186238. /* Version of *.h files used when building libpng */
  186239. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  186240. return ((png_charp) PNG_LIBPNG_VER_STRING);
  186241. }
  186242. png_charp PNGAPI
  186243. png_get_header_version(png_structp png_ptr)
  186244. {
  186245. /* Returns longer string containing both version and date */
  186246. png_ptr = png_ptr; /* silence compiler warning about unused png_ptr */
  186247. return ((png_charp) PNG_HEADER_VERSION_STRING
  186248. #ifndef PNG_READ_SUPPORTED
  186249. " (NO READ SUPPORT)"
  186250. #endif
  186251. "\n");
  186252. }
  186253. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186254. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  186255. int PNGAPI
  186256. png_handle_as_unknown(png_structp png_ptr, png_bytep chunk_name)
  186257. {
  186258. /* check chunk_name and return "keep" value if it's on the list, else 0 */
  186259. int i;
  186260. png_bytep p;
  186261. if(png_ptr == NULL || chunk_name == NULL || png_ptr->num_chunk_list<=0)
  186262. return 0;
  186263. p=png_ptr->chunk_list+png_ptr->num_chunk_list*5-5;
  186264. for (i = png_ptr->num_chunk_list; i; i--, p-=5)
  186265. if (!png_memcmp(chunk_name, p, 4))
  186266. return ((int)*(p+4));
  186267. return 0;
  186268. }
  186269. #endif
  186270. /* This function, added to libpng-1.0.6g, is untested. */
  186271. int PNGAPI
  186272. png_reset_zstream(png_structp png_ptr)
  186273. {
  186274. if (png_ptr == NULL) return Z_STREAM_ERROR;
  186275. return (inflateReset(&png_ptr->zstream));
  186276. }
  186277. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  186278. /* This function was added to libpng-1.0.7 */
  186279. png_uint_32 PNGAPI
  186280. png_access_version_number(void)
  186281. {
  186282. /* Version of *.c files used when building libpng */
  186283. return((png_uint_32) PNG_LIBPNG_VER);
  186284. }
  186285. #if defined(PNG_READ_SUPPORTED) && defined(PNG_ASSEMBLER_CODE_SUPPORTED)
  186286. #if !defined(PNG_1_0_X)
  186287. /* this function was added to libpng 1.2.0 */
  186288. int PNGAPI
  186289. png_mmx_support(void)
  186290. {
  186291. /* obsolete, to be removed from libpng-1.4.0 */
  186292. return -1;
  186293. }
  186294. #endif /* PNG_1_0_X */
  186295. #endif /* PNG_READ_SUPPORTED && PNG_ASSEMBLER_CODE_SUPPORTED */
  186296. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186297. #ifdef PNG_SIZE_T
  186298. /* Added at libpng version 1.2.6 */
  186299. PNG_EXTERN png_size_t PNGAPI png_convert_size PNGARG((size_t size));
  186300. png_size_t PNGAPI
  186301. png_convert_size(size_t size)
  186302. {
  186303. if (size > (png_size_t)-1)
  186304. PNG_ABORT(); /* We haven't got access to png_ptr, so no png_error() */
  186305. return ((png_size_t)size);
  186306. }
  186307. #endif /* PNG_SIZE_T */
  186308. #endif /* defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED) */
  186309. /********* End of inlined file: png.c *********/
  186310. /********* Start of inlined file: pngerror.c *********/
  186311. /* pngerror.c - stub functions for i/o and memory allocation
  186312. *
  186313. * Last changed in libpng 1.2.20 October 4, 2007
  186314. * For conditions of distribution and use, see copyright notice in png.h
  186315. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186316. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186317. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186318. *
  186319. * This file provides a location for all error handling. Users who
  186320. * need special error handling are expected to write replacement functions
  186321. * and use png_set_error_fn() to use those functions. See the instructions
  186322. * at each function.
  186323. */
  186324. #define PNG_INTERNAL
  186325. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186326. static void /* PRIVATE */
  186327. png_default_error PNGARG((png_structp png_ptr,
  186328. png_const_charp error_message));
  186329. #ifndef PNG_NO_WARNINGS
  186330. static void /* PRIVATE */
  186331. png_default_warning PNGARG((png_structp png_ptr,
  186332. png_const_charp warning_message));
  186333. #endif /* PNG_NO_WARNINGS */
  186334. /* This function is called whenever there is a fatal error. This function
  186335. * should not be changed. If there is a need to handle errors differently,
  186336. * you should supply a replacement error function and use png_set_error_fn()
  186337. * to replace the error function at run-time.
  186338. */
  186339. #ifndef PNG_NO_ERROR_TEXT
  186340. void PNGAPI
  186341. png_error(png_structp png_ptr, png_const_charp error_message)
  186342. {
  186343. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186344. char msg[16];
  186345. if (png_ptr != NULL)
  186346. {
  186347. if (png_ptr->flags&
  186348. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  186349. {
  186350. if (*error_message == '#')
  186351. {
  186352. int offset;
  186353. for (offset=1; offset<15; offset++)
  186354. if (*(error_message+offset) == ' ')
  186355. break;
  186356. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  186357. {
  186358. int i;
  186359. for (i=0; i<offset-1; i++)
  186360. msg[i]=error_message[i+1];
  186361. msg[i]='\0';
  186362. error_message=msg;
  186363. }
  186364. else
  186365. error_message+=offset;
  186366. }
  186367. else
  186368. {
  186369. if (png_ptr->flags&PNG_FLAG_STRIP_ERROR_TEXT)
  186370. {
  186371. msg[0]='0';
  186372. msg[1]='\0';
  186373. error_message=msg;
  186374. }
  186375. }
  186376. }
  186377. }
  186378. #endif
  186379. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  186380. (*(png_ptr->error_fn))(png_ptr, error_message);
  186381. /* If the custom handler doesn't exist, or if it returns,
  186382. use the default handler, which will not return. */
  186383. png_default_error(png_ptr, error_message);
  186384. }
  186385. #else
  186386. void PNGAPI
  186387. png_err(png_structp png_ptr)
  186388. {
  186389. if (png_ptr != NULL && png_ptr->error_fn != NULL)
  186390. (*(png_ptr->error_fn))(png_ptr, '\0');
  186391. /* If the custom handler doesn't exist, or if it returns,
  186392. use the default handler, which will not return. */
  186393. png_default_error(png_ptr, '\0');
  186394. }
  186395. #endif /* PNG_NO_ERROR_TEXT */
  186396. #ifndef PNG_NO_WARNINGS
  186397. /* This function is called whenever there is a non-fatal error. This function
  186398. * should not be changed. If there is a need to handle warnings differently,
  186399. * you should supply a replacement warning function and use
  186400. * png_set_error_fn() to replace the warning function at run-time.
  186401. */
  186402. void PNGAPI
  186403. png_warning(png_structp png_ptr, png_const_charp warning_message)
  186404. {
  186405. int offset = 0;
  186406. if (png_ptr != NULL)
  186407. {
  186408. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186409. if (png_ptr->flags&
  186410. (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))
  186411. #endif
  186412. {
  186413. if (*warning_message == '#')
  186414. {
  186415. for (offset=1; offset<15; offset++)
  186416. if (*(warning_message+offset) == ' ')
  186417. break;
  186418. }
  186419. }
  186420. if (png_ptr != NULL && png_ptr->warning_fn != NULL)
  186421. (*(png_ptr->warning_fn))(png_ptr, warning_message+offset);
  186422. }
  186423. else
  186424. png_default_warning(png_ptr, warning_message+offset);
  186425. }
  186426. #endif /* PNG_NO_WARNINGS */
  186427. /* These utilities are used internally to build an error message that relates
  186428. * to the current chunk. The chunk name comes from png_ptr->chunk_name,
  186429. * this is used to prefix the message. The message is limited in length
  186430. * to 63 bytes, the name characters are output as hex digits wrapped in []
  186431. * if the character is invalid.
  186432. */
  186433. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  186434. /*static PNG_CONST char png_digit[16] = {
  186435. '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
  186436. 'A', 'B', 'C', 'D', 'E', 'F'
  186437. };*/
  186438. #if !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT)
  186439. static void /* PRIVATE */
  186440. png_format_buffer(png_structp png_ptr, png_charp buffer, png_const_charp
  186441. error_message)
  186442. {
  186443. int iout = 0, iin = 0;
  186444. while (iin < 4)
  186445. {
  186446. int c = png_ptr->chunk_name[iin++];
  186447. if (isnonalpha(c))
  186448. {
  186449. buffer[iout++] = '[';
  186450. buffer[iout++] = png_digit[(c & 0xf0) >> 4];
  186451. buffer[iout++] = png_digit[c & 0x0f];
  186452. buffer[iout++] = ']';
  186453. }
  186454. else
  186455. {
  186456. buffer[iout++] = (png_byte)c;
  186457. }
  186458. }
  186459. if (error_message == NULL)
  186460. buffer[iout] = 0;
  186461. else
  186462. {
  186463. buffer[iout++] = ':';
  186464. buffer[iout++] = ' ';
  186465. png_strncpy(buffer+iout, error_message, 63);
  186466. buffer[iout+63] = 0;
  186467. }
  186468. }
  186469. #ifdef PNG_READ_SUPPORTED
  186470. void PNGAPI
  186471. png_chunk_error(png_structp png_ptr, png_const_charp error_message)
  186472. {
  186473. char msg[18+64];
  186474. if (png_ptr == NULL)
  186475. png_error(png_ptr, error_message);
  186476. else
  186477. {
  186478. png_format_buffer(png_ptr, msg, error_message);
  186479. png_error(png_ptr, msg);
  186480. }
  186481. }
  186482. #endif /* PNG_READ_SUPPORTED */
  186483. #endif /* !defined(PNG_NO_WARNINGS) || !defined(PNG_NO_ERROR_TEXT) */
  186484. #ifndef PNG_NO_WARNINGS
  186485. void PNGAPI
  186486. png_chunk_warning(png_structp png_ptr, png_const_charp warning_message)
  186487. {
  186488. char msg[18+64];
  186489. if (png_ptr == NULL)
  186490. png_warning(png_ptr, warning_message);
  186491. else
  186492. {
  186493. png_format_buffer(png_ptr, msg, warning_message);
  186494. png_warning(png_ptr, msg);
  186495. }
  186496. }
  186497. #endif /* PNG_NO_WARNINGS */
  186498. /* This is the default error handling function. Note that replacements for
  186499. * this function MUST NOT RETURN, or the program will likely crash. This
  186500. * function is used by default, or if the program supplies NULL for the
  186501. * error function pointer in png_set_error_fn().
  186502. */
  186503. static void /* PRIVATE */
  186504. png_default_error(png_structp png_ptr, png_const_charp error_message)
  186505. {
  186506. #ifndef PNG_NO_CONSOLE_IO
  186507. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186508. if (*error_message == '#')
  186509. {
  186510. int offset;
  186511. char error_number[16];
  186512. for (offset=0; offset<15; offset++)
  186513. {
  186514. error_number[offset] = *(error_message+offset+1);
  186515. if (*(error_message+offset) == ' ')
  186516. break;
  186517. }
  186518. if((offset > 1) && (offset < 15))
  186519. {
  186520. error_number[offset-1]='\0';
  186521. fprintf(stderr, "libpng error no. %s: %s\n", error_number,
  186522. error_message+offset);
  186523. }
  186524. else
  186525. fprintf(stderr, "libpng error: %s, offset=%d\n", error_message,offset);
  186526. }
  186527. else
  186528. #endif
  186529. fprintf(stderr, "libpng error: %s\n", error_message);
  186530. #endif
  186531. #ifdef PNG_SETJMP_SUPPORTED
  186532. if (png_ptr)
  186533. {
  186534. # ifdef USE_FAR_KEYWORD
  186535. {
  186536. jmp_buf jmpbuf;
  186537. png_memcpy(jmpbuf, png_ptr->jmpbuf, png_sizeof(jmp_buf));
  186538. longjmp(jmpbuf, 1);
  186539. }
  186540. # else
  186541. longjmp(png_ptr->jmpbuf, 1);
  186542. # endif
  186543. }
  186544. #else
  186545. PNG_ABORT();
  186546. #endif
  186547. #ifdef PNG_NO_CONSOLE_IO
  186548. error_message = error_message; /* make compiler happy */
  186549. #endif
  186550. }
  186551. #ifndef PNG_NO_WARNINGS
  186552. /* This function is called when there is a warning, but the library thinks
  186553. * it can continue anyway. Replacement functions don't have to do anything
  186554. * here if you don't want them to. In the default configuration, png_ptr is
  186555. * not used, but it is passed in case it may be useful.
  186556. */
  186557. static void /* PRIVATE */
  186558. png_default_warning(png_structp png_ptr, png_const_charp warning_message)
  186559. {
  186560. #ifndef PNG_NO_CONSOLE_IO
  186561. # ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186562. if (*warning_message == '#')
  186563. {
  186564. int offset;
  186565. char warning_number[16];
  186566. for (offset=0; offset<15; offset++)
  186567. {
  186568. warning_number[offset]=*(warning_message+offset+1);
  186569. if (*(warning_message+offset) == ' ')
  186570. break;
  186571. }
  186572. if((offset > 1) && (offset < 15))
  186573. {
  186574. warning_number[offset-1]='\0';
  186575. fprintf(stderr, "libpng warning no. %s: %s\n", warning_number,
  186576. warning_message+offset);
  186577. }
  186578. else
  186579. fprintf(stderr, "libpng warning: %s\n", warning_message);
  186580. }
  186581. else
  186582. # endif
  186583. fprintf(stderr, "libpng warning: %s\n", warning_message);
  186584. #else
  186585. warning_message = warning_message; /* make compiler happy */
  186586. #endif
  186587. png_ptr = png_ptr; /* make compiler happy */
  186588. }
  186589. #endif /* PNG_NO_WARNINGS */
  186590. /* This function is called when the application wants to use another method
  186591. * of handling errors and warnings. Note that the error function MUST NOT
  186592. * return to the calling routine or serious problems will occur. The return
  186593. * method used in the default routine calls longjmp(png_ptr->jmpbuf, 1)
  186594. */
  186595. void PNGAPI
  186596. png_set_error_fn(png_structp png_ptr, png_voidp error_ptr,
  186597. png_error_ptr error_fn, png_error_ptr warning_fn)
  186598. {
  186599. if (png_ptr == NULL)
  186600. return;
  186601. png_ptr->error_ptr = error_ptr;
  186602. png_ptr->error_fn = error_fn;
  186603. png_ptr->warning_fn = warning_fn;
  186604. }
  186605. /* This function returns a pointer to the error_ptr associated with the user
  186606. * functions. The application should free any memory associated with this
  186607. * pointer before png_write_destroy and png_read_destroy are called.
  186608. */
  186609. png_voidp PNGAPI
  186610. png_get_error_ptr(png_structp png_ptr)
  186611. {
  186612. if (png_ptr == NULL)
  186613. return NULL;
  186614. return ((png_voidp)png_ptr->error_ptr);
  186615. }
  186616. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  186617. void PNGAPI
  186618. png_set_strip_error_numbers(png_structp png_ptr, png_uint_32 strip_mode)
  186619. {
  186620. if(png_ptr != NULL)
  186621. {
  186622. png_ptr->flags &=
  186623. ((~(PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT))&strip_mode);
  186624. }
  186625. }
  186626. #endif
  186627. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  186628. /********* End of inlined file: pngerror.c *********/
  186629. /********* Start of inlined file: pngget.c *********/
  186630. /* pngget.c - retrieval of values from info struct
  186631. *
  186632. * Last changed in libpng 1.2.15 January 5, 2007
  186633. * For conditions of distribution and use, see copyright notice in png.h
  186634. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  186635. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  186636. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  186637. */
  186638. #define PNG_INTERNAL
  186639. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  186640. png_uint_32 PNGAPI
  186641. png_get_valid(png_structp png_ptr, png_infop info_ptr, png_uint_32 flag)
  186642. {
  186643. if (png_ptr != NULL && info_ptr != NULL)
  186644. return(info_ptr->valid & flag);
  186645. else
  186646. return(0);
  186647. }
  186648. png_uint_32 PNGAPI
  186649. png_get_rowbytes(png_structp png_ptr, png_infop info_ptr)
  186650. {
  186651. if (png_ptr != NULL && info_ptr != NULL)
  186652. return(info_ptr->rowbytes);
  186653. else
  186654. return(0);
  186655. }
  186656. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  186657. png_bytepp PNGAPI
  186658. png_get_rows(png_structp png_ptr, png_infop info_ptr)
  186659. {
  186660. if (png_ptr != NULL && info_ptr != NULL)
  186661. return(info_ptr->row_pointers);
  186662. else
  186663. return(0);
  186664. }
  186665. #endif
  186666. #ifdef PNG_EASY_ACCESS_SUPPORTED
  186667. /* easy access to info, added in libpng-0.99 */
  186668. png_uint_32 PNGAPI
  186669. png_get_image_width(png_structp png_ptr, png_infop info_ptr)
  186670. {
  186671. if (png_ptr != NULL && info_ptr != NULL)
  186672. {
  186673. return info_ptr->width;
  186674. }
  186675. return (0);
  186676. }
  186677. png_uint_32 PNGAPI
  186678. png_get_image_height(png_structp png_ptr, png_infop info_ptr)
  186679. {
  186680. if (png_ptr != NULL && info_ptr != NULL)
  186681. {
  186682. return info_ptr->height;
  186683. }
  186684. return (0);
  186685. }
  186686. png_byte PNGAPI
  186687. png_get_bit_depth(png_structp png_ptr, png_infop info_ptr)
  186688. {
  186689. if (png_ptr != NULL && info_ptr != NULL)
  186690. {
  186691. return info_ptr->bit_depth;
  186692. }
  186693. return (0);
  186694. }
  186695. png_byte PNGAPI
  186696. png_get_color_type(png_structp png_ptr, png_infop info_ptr)
  186697. {
  186698. if (png_ptr != NULL && info_ptr != NULL)
  186699. {
  186700. return info_ptr->color_type;
  186701. }
  186702. return (0);
  186703. }
  186704. png_byte PNGAPI
  186705. png_get_filter_type(png_structp png_ptr, png_infop info_ptr)
  186706. {
  186707. if (png_ptr != NULL && info_ptr != NULL)
  186708. {
  186709. return info_ptr->filter_type;
  186710. }
  186711. return (0);
  186712. }
  186713. png_byte PNGAPI
  186714. png_get_interlace_type(png_structp png_ptr, png_infop info_ptr)
  186715. {
  186716. if (png_ptr != NULL && info_ptr != NULL)
  186717. {
  186718. return info_ptr->interlace_type;
  186719. }
  186720. return (0);
  186721. }
  186722. png_byte PNGAPI
  186723. png_get_compression_type(png_structp png_ptr, png_infop info_ptr)
  186724. {
  186725. if (png_ptr != NULL && info_ptr != NULL)
  186726. {
  186727. return info_ptr->compression_type;
  186728. }
  186729. return (0);
  186730. }
  186731. png_uint_32 PNGAPI
  186732. png_get_x_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186733. {
  186734. if (png_ptr != NULL && info_ptr != NULL)
  186735. #if defined(PNG_pHYs_SUPPORTED)
  186736. if (info_ptr->valid & PNG_INFO_pHYs)
  186737. {
  186738. png_debug1(1, "in %s retrieval function\n", "png_get_x_pixels_per_meter");
  186739. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  186740. return (0);
  186741. else return (info_ptr->x_pixels_per_unit);
  186742. }
  186743. #else
  186744. return (0);
  186745. #endif
  186746. return (0);
  186747. }
  186748. png_uint_32 PNGAPI
  186749. png_get_y_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186750. {
  186751. if (png_ptr != NULL && info_ptr != NULL)
  186752. #if defined(PNG_pHYs_SUPPORTED)
  186753. if (info_ptr->valid & PNG_INFO_pHYs)
  186754. {
  186755. png_debug1(1, "in %s retrieval function\n", "png_get_y_pixels_per_meter");
  186756. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER)
  186757. return (0);
  186758. else return (info_ptr->y_pixels_per_unit);
  186759. }
  186760. #else
  186761. return (0);
  186762. #endif
  186763. return (0);
  186764. }
  186765. png_uint_32 PNGAPI
  186766. png_get_pixels_per_meter(png_structp png_ptr, png_infop info_ptr)
  186767. {
  186768. if (png_ptr != NULL && info_ptr != NULL)
  186769. #if defined(PNG_pHYs_SUPPORTED)
  186770. if (info_ptr->valid & PNG_INFO_pHYs)
  186771. {
  186772. png_debug1(1, "in %s retrieval function\n", "png_get_pixels_per_meter");
  186773. if(info_ptr->phys_unit_type != PNG_RESOLUTION_METER ||
  186774. info_ptr->x_pixels_per_unit != info_ptr->y_pixels_per_unit)
  186775. return (0);
  186776. else return (info_ptr->x_pixels_per_unit);
  186777. }
  186778. #else
  186779. return (0);
  186780. #endif
  186781. return (0);
  186782. }
  186783. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186784. float PNGAPI
  186785. png_get_pixel_aspect_ratio(png_structp png_ptr, png_infop info_ptr)
  186786. {
  186787. if (png_ptr != NULL && info_ptr != NULL)
  186788. #if defined(PNG_pHYs_SUPPORTED)
  186789. if (info_ptr->valid & PNG_INFO_pHYs)
  186790. {
  186791. png_debug1(1, "in %s retrieval function\n", "png_get_aspect_ratio");
  186792. if (info_ptr->x_pixels_per_unit == 0)
  186793. return ((float)0.0);
  186794. else
  186795. return ((float)((float)info_ptr->y_pixels_per_unit
  186796. /(float)info_ptr->x_pixels_per_unit));
  186797. }
  186798. #else
  186799. return (0.0);
  186800. #endif
  186801. return ((float)0.0);
  186802. }
  186803. #endif
  186804. png_int_32 PNGAPI
  186805. png_get_x_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186806. {
  186807. if (png_ptr != NULL && info_ptr != NULL)
  186808. #if defined(PNG_oFFs_SUPPORTED)
  186809. if (info_ptr->valid & PNG_INFO_oFFs)
  186810. {
  186811. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186812. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186813. return (0);
  186814. else return (info_ptr->x_offset);
  186815. }
  186816. #else
  186817. return (0);
  186818. #endif
  186819. return (0);
  186820. }
  186821. png_int_32 PNGAPI
  186822. png_get_y_offset_microns(png_structp png_ptr, png_infop info_ptr)
  186823. {
  186824. if (png_ptr != NULL && info_ptr != NULL)
  186825. #if defined(PNG_oFFs_SUPPORTED)
  186826. if (info_ptr->valid & PNG_INFO_oFFs)
  186827. {
  186828. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186829. if(info_ptr->offset_unit_type != PNG_OFFSET_MICROMETER)
  186830. return (0);
  186831. else return (info_ptr->y_offset);
  186832. }
  186833. #else
  186834. return (0);
  186835. #endif
  186836. return (0);
  186837. }
  186838. png_int_32 PNGAPI
  186839. png_get_x_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186840. {
  186841. if (png_ptr != NULL && info_ptr != NULL)
  186842. #if defined(PNG_oFFs_SUPPORTED)
  186843. if (info_ptr->valid & PNG_INFO_oFFs)
  186844. {
  186845. png_debug1(1, "in %s retrieval function\n", "png_get_x_offset_microns");
  186846. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186847. return (0);
  186848. else return (info_ptr->x_offset);
  186849. }
  186850. #else
  186851. return (0);
  186852. #endif
  186853. return (0);
  186854. }
  186855. png_int_32 PNGAPI
  186856. png_get_y_offset_pixels(png_structp png_ptr, png_infop info_ptr)
  186857. {
  186858. if (png_ptr != NULL && info_ptr != NULL)
  186859. #if defined(PNG_oFFs_SUPPORTED)
  186860. if (info_ptr->valid & PNG_INFO_oFFs)
  186861. {
  186862. png_debug1(1, "in %s retrieval function\n", "png_get_y_offset_microns");
  186863. if(info_ptr->offset_unit_type != PNG_OFFSET_PIXEL)
  186864. return (0);
  186865. else return (info_ptr->y_offset);
  186866. }
  186867. #else
  186868. return (0);
  186869. #endif
  186870. return (0);
  186871. }
  186872. #if defined(PNG_INCH_CONVERSIONS) && defined(PNG_FLOATING_POINT_SUPPORTED)
  186873. png_uint_32 PNGAPI
  186874. png_get_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186875. {
  186876. return ((png_uint_32)((float)png_get_pixels_per_meter(png_ptr, info_ptr)
  186877. *.0254 +.5));
  186878. }
  186879. png_uint_32 PNGAPI
  186880. png_get_x_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186881. {
  186882. return ((png_uint_32)((float)png_get_x_pixels_per_meter(png_ptr, info_ptr)
  186883. *.0254 +.5));
  186884. }
  186885. png_uint_32 PNGAPI
  186886. png_get_y_pixels_per_inch(png_structp png_ptr, png_infop info_ptr)
  186887. {
  186888. return ((png_uint_32)((float)png_get_y_pixels_per_meter(png_ptr, info_ptr)
  186889. *.0254 +.5));
  186890. }
  186891. float PNGAPI
  186892. png_get_x_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186893. {
  186894. return ((float)png_get_x_offset_microns(png_ptr, info_ptr)
  186895. *.00003937);
  186896. }
  186897. float PNGAPI
  186898. png_get_y_offset_inches(png_structp png_ptr, png_infop info_ptr)
  186899. {
  186900. return ((float)png_get_y_offset_microns(png_ptr, info_ptr)
  186901. *.00003937);
  186902. }
  186903. #if defined(PNG_pHYs_SUPPORTED)
  186904. png_uint_32 PNGAPI
  186905. png_get_pHYs_dpi(png_structp png_ptr, png_infop info_ptr,
  186906. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  186907. {
  186908. png_uint_32 retval = 0;
  186909. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  186910. {
  186911. png_debug1(1, "in %s retrieval function\n", "pHYs");
  186912. if (res_x != NULL)
  186913. {
  186914. *res_x = info_ptr->x_pixels_per_unit;
  186915. retval |= PNG_INFO_pHYs;
  186916. }
  186917. if (res_y != NULL)
  186918. {
  186919. *res_y = info_ptr->y_pixels_per_unit;
  186920. retval |= PNG_INFO_pHYs;
  186921. }
  186922. if (unit_type != NULL)
  186923. {
  186924. *unit_type = (int)info_ptr->phys_unit_type;
  186925. retval |= PNG_INFO_pHYs;
  186926. if(*unit_type == 1)
  186927. {
  186928. if (res_x != NULL) *res_x = (png_uint_32)(*res_x * .0254 + .50);
  186929. if (res_y != NULL) *res_y = (png_uint_32)(*res_y * .0254 + .50);
  186930. }
  186931. }
  186932. }
  186933. return (retval);
  186934. }
  186935. #endif /* PNG_pHYs_SUPPORTED */
  186936. #endif /* PNG_INCH_CONVERSIONS && PNG_FLOATING_POINT_SUPPORTED */
  186937. /* png_get_channels really belongs in here, too, but it's been around longer */
  186938. #endif /* PNG_EASY_ACCESS_SUPPORTED */
  186939. png_byte PNGAPI
  186940. png_get_channels(png_structp png_ptr, png_infop info_ptr)
  186941. {
  186942. if (png_ptr != NULL && info_ptr != NULL)
  186943. return(info_ptr->channels);
  186944. else
  186945. return (0);
  186946. }
  186947. png_bytep PNGAPI
  186948. png_get_signature(png_structp png_ptr, png_infop info_ptr)
  186949. {
  186950. if (png_ptr != NULL && info_ptr != NULL)
  186951. return(info_ptr->signature);
  186952. else
  186953. return (NULL);
  186954. }
  186955. #if defined(PNG_bKGD_SUPPORTED)
  186956. png_uint_32 PNGAPI
  186957. png_get_bKGD(png_structp png_ptr, png_infop info_ptr,
  186958. png_color_16p *background)
  186959. {
  186960. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD)
  186961. && background != NULL)
  186962. {
  186963. png_debug1(1, "in %s retrieval function\n", "bKGD");
  186964. *background = &(info_ptr->background);
  186965. return (PNG_INFO_bKGD);
  186966. }
  186967. return (0);
  186968. }
  186969. #endif
  186970. #if defined(PNG_cHRM_SUPPORTED)
  186971. #ifdef PNG_FLOATING_POINT_SUPPORTED
  186972. png_uint_32 PNGAPI
  186973. png_get_cHRM(png_structp png_ptr, png_infop info_ptr,
  186974. double *white_x, double *white_y, double *red_x, double *red_y,
  186975. double *green_x, double *green_y, double *blue_x, double *blue_y)
  186976. {
  186977. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  186978. {
  186979. png_debug1(1, "in %s retrieval function\n", "cHRM");
  186980. if (white_x != NULL)
  186981. *white_x = (double)info_ptr->x_white;
  186982. if (white_y != NULL)
  186983. *white_y = (double)info_ptr->y_white;
  186984. if (red_x != NULL)
  186985. *red_x = (double)info_ptr->x_red;
  186986. if (red_y != NULL)
  186987. *red_y = (double)info_ptr->y_red;
  186988. if (green_x != NULL)
  186989. *green_x = (double)info_ptr->x_green;
  186990. if (green_y != NULL)
  186991. *green_y = (double)info_ptr->y_green;
  186992. if (blue_x != NULL)
  186993. *blue_x = (double)info_ptr->x_blue;
  186994. if (blue_y != NULL)
  186995. *blue_y = (double)info_ptr->y_blue;
  186996. return (PNG_INFO_cHRM);
  186997. }
  186998. return (0);
  186999. }
  187000. #endif
  187001. #ifdef PNG_FIXED_POINT_SUPPORTED
  187002. png_uint_32 PNGAPI
  187003. png_get_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  187004. png_fixed_point *white_x, png_fixed_point *white_y, png_fixed_point *red_x,
  187005. png_fixed_point *red_y, png_fixed_point *green_x, png_fixed_point *green_y,
  187006. png_fixed_point *blue_x, png_fixed_point *blue_y)
  187007. {
  187008. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  187009. {
  187010. png_debug1(1, "in %s retrieval function\n", "cHRM");
  187011. if (white_x != NULL)
  187012. *white_x = info_ptr->int_x_white;
  187013. if (white_y != NULL)
  187014. *white_y = info_ptr->int_y_white;
  187015. if (red_x != NULL)
  187016. *red_x = info_ptr->int_x_red;
  187017. if (red_y != NULL)
  187018. *red_y = info_ptr->int_y_red;
  187019. if (green_x != NULL)
  187020. *green_x = info_ptr->int_x_green;
  187021. if (green_y != NULL)
  187022. *green_y = info_ptr->int_y_green;
  187023. if (blue_x != NULL)
  187024. *blue_x = info_ptr->int_x_blue;
  187025. if (blue_y != NULL)
  187026. *blue_y = info_ptr->int_y_blue;
  187027. return (PNG_INFO_cHRM);
  187028. }
  187029. return (0);
  187030. }
  187031. #endif
  187032. #endif
  187033. #if defined(PNG_gAMA_SUPPORTED)
  187034. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187035. png_uint_32 PNGAPI
  187036. png_get_gAMA(png_structp png_ptr, png_infop info_ptr, double *file_gamma)
  187037. {
  187038. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  187039. && file_gamma != NULL)
  187040. {
  187041. png_debug1(1, "in %s retrieval function\n", "gAMA");
  187042. *file_gamma = (double)info_ptr->gamma;
  187043. return (PNG_INFO_gAMA);
  187044. }
  187045. return (0);
  187046. }
  187047. #endif
  187048. #ifdef PNG_FIXED_POINT_SUPPORTED
  187049. png_uint_32 PNGAPI
  187050. png_get_gAMA_fixed(png_structp png_ptr, png_infop info_ptr,
  187051. png_fixed_point *int_file_gamma)
  187052. {
  187053. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  187054. && int_file_gamma != NULL)
  187055. {
  187056. png_debug1(1, "in %s retrieval function\n", "gAMA");
  187057. *int_file_gamma = info_ptr->int_gamma;
  187058. return (PNG_INFO_gAMA);
  187059. }
  187060. return (0);
  187061. }
  187062. #endif
  187063. #endif
  187064. #if defined(PNG_sRGB_SUPPORTED)
  187065. png_uint_32 PNGAPI
  187066. png_get_sRGB(png_structp png_ptr, png_infop info_ptr, int *file_srgb_intent)
  187067. {
  187068. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB)
  187069. && file_srgb_intent != NULL)
  187070. {
  187071. png_debug1(1, "in %s retrieval function\n", "sRGB");
  187072. *file_srgb_intent = (int)info_ptr->srgb_intent;
  187073. return (PNG_INFO_sRGB);
  187074. }
  187075. return (0);
  187076. }
  187077. #endif
  187078. #if defined(PNG_iCCP_SUPPORTED)
  187079. png_uint_32 PNGAPI
  187080. png_get_iCCP(png_structp png_ptr, png_infop info_ptr,
  187081. png_charpp name, int *compression_type,
  187082. png_charpp profile, png_uint_32 *proflen)
  187083. {
  187084. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP)
  187085. && name != NULL && profile != NULL && proflen != NULL)
  187086. {
  187087. png_debug1(1, "in %s retrieval function\n", "iCCP");
  187088. *name = info_ptr->iccp_name;
  187089. *profile = info_ptr->iccp_profile;
  187090. /* compression_type is a dummy so the API won't have to change
  187091. if we introduce multiple compression types later. */
  187092. *proflen = (int)info_ptr->iccp_proflen;
  187093. *compression_type = (int)info_ptr->iccp_compression;
  187094. return (PNG_INFO_iCCP);
  187095. }
  187096. return (0);
  187097. }
  187098. #endif
  187099. #if defined(PNG_sPLT_SUPPORTED)
  187100. png_uint_32 PNGAPI
  187101. png_get_sPLT(png_structp png_ptr, png_infop info_ptr,
  187102. png_sPLT_tpp spalettes)
  187103. {
  187104. if (png_ptr != NULL && info_ptr != NULL && spalettes != NULL)
  187105. {
  187106. *spalettes = info_ptr->splt_palettes;
  187107. return ((png_uint_32)info_ptr->splt_palettes_num);
  187108. }
  187109. return (0);
  187110. }
  187111. #endif
  187112. #if defined(PNG_hIST_SUPPORTED)
  187113. png_uint_32 PNGAPI
  187114. png_get_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p *hist)
  187115. {
  187116. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST)
  187117. && hist != NULL)
  187118. {
  187119. png_debug1(1, "in %s retrieval function\n", "hIST");
  187120. *hist = info_ptr->hist;
  187121. return (PNG_INFO_hIST);
  187122. }
  187123. return (0);
  187124. }
  187125. #endif
  187126. png_uint_32 PNGAPI
  187127. png_get_IHDR(png_structp png_ptr, png_infop info_ptr,
  187128. png_uint_32 *width, png_uint_32 *height, int *bit_depth,
  187129. int *color_type, int *interlace_type, int *compression_type,
  187130. int *filter_type)
  187131. {
  187132. if (png_ptr != NULL && info_ptr != NULL && width != NULL && height != NULL &&
  187133. bit_depth != NULL && color_type != NULL)
  187134. {
  187135. png_debug1(1, "in %s retrieval function\n", "IHDR");
  187136. *width = info_ptr->width;
  187137. *height = info_ptr->height;
  187138. *bit_depth = info_ptr->bit_depth;
  187139. if (info_ptr->bit_depth < 1 || info_ptr->bit_depth > 16)
  187140. png_error(png_ptr, "Invalid bit depth");
  187141. *color_type = info_ptr->color_type;
  187142. if (info_ptr->color_type > 6)
  187143. png_error(png_ptr, "Invalid color type");
  187144. if (compression_type != NULL)
  187145. *compression_type = info_ptr->compression_type;
  187146. if (filter_type != NULL)
  187147. *filter_type = info_ptr->filter_type;
  187148. if (interlace_type != NULL)
  187149. *interlace_type = info_ptr->interlace_type;
  187150. /* check for potential overflow of rowbytes */
  187151. if (*width == 0 || *width > PNG_UINT_31_MAX)
  187152. png_error(png_ptr, "Invalid image width");
  187153. if (*height == 0 || *height > PNG_UINT_31_MAX)
  187154. png_error(png_ptr, "Invalid image height");
  187155. if (info_ptr->width > (PNG_UINT_32_MAX
  187156. >> 3) /* 8-byte RGBA pixels */
  187157. - 64 /* bigrowbuf hack */
  187158. - 1 /* filter byte */
  187159. - 7*8 /* rounding of width to multiple of 8 pixels */
  187160. - 8) /* extra max_pixel_depth pad */
  187161. {
  187162. png_warning(png_ptr,
  187163. "Width too large for libpng to process image data.");
  187164. }
  187165. return (1);
  187166. }
  187167. return (0);
  187168. }
  187169. #if defined(PNG_oFFs_SUPPORTED)
  187170. png_uint_32 PNGAPI
  187171. png_get_oFFs(png_structp png_ptr, png_infop info_ptr,
  187172. png_int_32 *offset_x, png_int_32 *offset_y, int *unit_type)
  187173. {
  187174. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs)
  187175. && offset_x != NULL && offset_y != NULL && unit_type != NULL)
  187176. {
  187177. png_debug1(1, "in %s retrieval function\n", "oFFs");
  187178. *offset_x = info_ptr->x_offset;
  187179. *offset_y = info_ptr->y_offset;
  187180. *unit_type = (int)info_ptr->offset_unit_type;
  187181. return (PNG_INFO_oFFs);
  187182. }
  187183. return (0);
  187184. }
  187185. #endif
  187186. #if defined(PNG_pCAL_SUPPORTED)
  187187. png_uint_32 PNGAPI
  187188. png_get_pCAL(png_structp png_ptr, png_infop info_ptr,
  187189. png_charp *purpose, png_int_32 *X0, png_int_32 *X1, int *type, int *nparams,
  187190. png_charp *units, png_charpp *params)
  187191. {
  187192. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL)
  187193. && purpose != NULL && X0 != NULL && X1 != NULL && type != NULL &&
  187194. nparams != NULL && units != NULL && params != NULL)
  187195. {
  187196. png_debug1(1, "in %s retrieval function\n", "pCAL");
  187197. *purpose = info_ptr->pcal_purpose;
  187198. *X0 = info_ptr->pcal_X0;
  187199. *X1 = info_ptr->pcal_X1;
  187200. *type = (int)info_ptr->pcal_type;
  187201. *nparams = (int)info_ptr->pcal_nparams;
  187202. *units = info_ptr->pcal_units;
  187203. *params = info_ptr->pcal_params;
  187204. return (PNG_INFO_pCAL);
  187205. }
  187206. return (0);
  187207. }
  187208. #endif
  187209. #if defined(PNG_sCAL_SUPPORTED)
  187210. #ifdef PNG_FLOATING_POINT_SUPPORTED
  187211. png_uint_32 PNGAPI
  187212. png_get_sCAL(png_structp png_ptr, png_infop info_ptr,
  187213. int *unit, double *width, double *height)
  187214. {
  187215. if (png_ptr != NULL && info_ptr != NULL &&
  187216. (info_ptr->valid & PNG_INFO_sCAL))
  187217. {
  187218. *unit = info_ptr->scal_unit;
  187219. *width = info_ptr->scal_pixel_width;
  187220. *height = info_ptr->scal_pixel_height;
  187221. return (PNG_INFO_sCAL);
  187222. }
  187223. return(0);
  187224. }
  187225. #else
  187226. #ifdef PNG_FIXED_POINT_SUPPORTED
  187227. png_uint_32 PNGAPI
  187228. png_get_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  187229. int *unit, png_charpp width, png_charpp height)
  187230. {
  187231. if (png_ptr != NULL && info_ptr != NULL &&
  187232. (info_ptr->valid & PNG_INFO_sCAL))
  187233. {
  187234. *unit = info_ptr->scal_unit;
  187235. *width = info_ptr->scal_s_width;
  187236. *height = info_ptr->scal_s_height;
  187237. return (PNG_INFO_sCAL);
  187238. }
  187239. return(0);
  187240. }
  187241. #endif
  187242. #endif
  187243. #endif
  187244. #if defined(PNG_pHYs_SUPPORTED)
  187245. png_uint_32 PNGAPI
  187246. png_get_pHYs(png_structp png_ptr, png_infop info_ptr,
  187247. png_uint_32 *res_x, png_uint_32 *res_y, int *unit_type)
  187248. {
  187249. png_uint_32 retval = 0;
  187250. if (png_ptr != NULL && info_ptr != NULL &&
  187251. (info_ptr->valid & PNG_INFO_pHYs))
  187252. {
  187253. png_debug1(1, "in %s retrieval function\n", "pHYs");
  187254. if (res_x != NULL)
  187255. {
  187256. *res_x = info_ptr->x_pixels_per_unit;
  187257. retval |= PNG_INFO_pHYs;
  187258. }
  187259. if (res_y != NULL)
  187260. {
  187261. *res_y = info_ptr->y_pixels_per_unit;
  187262. retval |= PNG_INFO_pHYs;
  187263. }
  187264. if (unit_type != NULL)
  187265. {
  187266. *unit_type = (int)info_ptr->phys_unit_type;
  187267. retval |= PNG_INFO_pHYs;
  187268. }
  187269. }
  187270. return (retval);
  187271. }
  187272. #endif
  187273. png_uint_32 PNGAPI
  187274. png_get_PLTE(png_structp png_ptr, png_infop info_ptr, png_colorp *palette,
  187275. int *num_palette)
  187276. {
  187277. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_PLTE)
  187278. && palette != NULL)
  187279. {
  187280. png_debug1(1, "in %s retrieval function\n", "PLTE");
  187281. *palette = info_ptr->palette;
  187282. *num_palette = info_ptr->num_palette;
  187283. png_debug1(3, "num_palette = %d\n", *num_palette);
  187284. return (PNG_INFO_PLTE);
  187285. }
  187286. return (0);
  187287. }
  187288. #if defined(PNG_sBIT_SUPPORTED)
  187289. png_uint_32 PNGAPI
  187290. png_get_sBIT(png_structp png_ptr, png_infop info_ptr, png_color_8p *sig_bit)
  187291. {
  187292. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT)
  187293. && sig_bit != NULL)
  187294. {
  187295. png_debug1(1, "in %s retrieval function\n", "sBIT");
  187296. *sig_bit = &(info_ptr->sig_bit);
  187297. return (PNG_INFO_sBIT);
  187298. }
  187299. return (0);
  187300. }
  187301. #endif
  187302. #if defined(PNG_TEXT_SUPPORTED)
  187303. png_uint_32 PNGAPI
  187304. png_get_text(png_structp png_ptr, png_infop info_ptr, png_textp *text_ptr,
  187305. int *num_text)
  187306. {
  187307. if (png_ptr != NULL && info_ptr != NULL && info_ptr->num_text > 0)
  187308. {
  187309. png_debug1(1, "in %s retrieval function\n",
  187310. (png_ptr->chunk_name[0] == '\0' ? "text"
  187311. : (png_const_charp)png_ptr->chunk_name));
  187312. if (text_ptr != NULL)
  187313. *text_ptr = info_ptr->text;
  187314. if (num_text != NULL)
  187315. *num_text = info_ptr->num_text;
  187316. return ((png_uint_32)info_ptr->num_text);
  187317. }
  187318. if (num_text != NULL)
  187319. *num_text = 0;
  187320. return(0);
  187321. }
  187322. #endif
  187323. #if defined(PNG_tIME_SUPPORTED)
  187324. png_uint_32 PNGAPI
  187325. png_get_tIME(png_structp png_ptr, png_infop info_ptr, png_timep *mod_time)
  187326. {
  187327. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME)
  187328. && mod_time != NULL)
  187329. {
  187330. png_debug1(1, "in %s retrieval function\n", "tIME");
  187331. *mod_time = &(info_ptr->mod_time);
  187332. return (PNG_INFO_tIME);
  187333. }
  187334. return (0);
  187335. }
  187336. #endif
  187337. #if defined(PNG_tRNS_SUPPORTED)
  187338. png_uint_32 PNGAPI
  187339. png_get_tRNS(png_structp png_ptr, png_infop info_ptr,
  187340. png_bytep *trans, int *num_trans, png_color_16p *trans_values)
  187341. {
  187342. png_uint_32 retval = 0;
  187343. if (png_ptr != NULL && info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  187344. {
  187345. png_debug1(1, "in %s retrieval function\n", "tRNS");
  187346. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  187347. {
  187348. if (trans != NULL)
  187349. {
  187350. *trans = info_ptr->trans;
  187351. retval |= PNG_INFO_tRNS;
  187352. }
  187353. if (trans_values != NULL)
  187354. *trans_values = &(info_ptr->trans_values);
  187355. }
  187356. else /* if (info_ptr->color_type != PNG_COLOR_TYPE_PALETTE) */
  187357. {
  187358. if (trans_values != NULL)
  187359. {
  187360. *trans_values = &(info_ptr->trans_values);
  187361. retval |= PNG_INFO_tRNS;
  187362. }
  187363. if(trans != NULL)
  187364. *trans = NULL;
  187365. }
  187366. if(num_trans != NULL)
  187367. {
  187368. *num_trans = info_ptr->num_trans;
  187369. retval |= PNG_INFO_tRNS;
  187370. }
  187371. }
  187372. return (retval);
  187373. }
  187374. #endif
  187375. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  187376. png_uint_32 PNGAPI
  187377. png_get_unknown_chunks(png_structp png_ptr, png_infop info_ptr,
  187378. png_unknown_chunkpp unknowns)
  187379. {
  187380. if (png_ptr != NULL && info_ptr != NULL && unknowns != NULL)
  187381. {
  187382. *unknowns = info_ptr->unknown_chunks;
  187383. return ((png_uint_32)info_ptr->unknown_chunks_num);
  187384. }
  187385. return (0);
  187386. }
  187387. #endif
  187388. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  187389. png_byte PNGAPI
  187390. png_get_rgb_to_gray_status (png_structp png_ptr)
  187391. {
  187392. return (png_byte)(png_ptr? png_ptr->rgb_to_gray_status : 0);
  187393. }
  187394. #endif
  187395. #if defined(PNG_USER_CHUNKS_SUPPORTED)
  187396. png_voidp PNGAPI
  187397. png_get_user_chunk_ptr(png_structp png_ptr)
  187398. {
  187399. return (png_ptr? png_ptr->user_chunk_ptr : NULL);
  187400. }
  187401. #endif
  187402. #ifdef PNG_WRITE_SUPPORTED
  187403. png_uint_32 PNGAPI
  187404. png_get_compression_buffer_size(png_structp png_ptr)
  187405. {
  187406. return (png_uint_32)(png_ptr? png_ptr->zbuf_size : 0L);
  187407. }
  187408. #endif
  187409. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  187410. #ifndef PNG_1_0_X
  187411. /* this function was added to libpng 1.2.0 and should exist by default */
  187412. png_uint_32 PNGAPI
  187413. png_get_asm_flags (png_structp png_ptr)
  187414. {
  187415. /* obsolete, to be removed from libpng-1.4.0 */
  187416. return (png_ptr? 0L: 0L);
  187417. }
  187418. /* this function was added to libpng 1.2.0 and should exist by default */
  187419. png_uint_32 PNGAPI
  187420. png_get_asm_flagmask (int flag_select)
  187421. {
  187422. /* obsolete, to be removed from libpng-1.4.0 */
  187423. flag_select=flag_select;
  187424. return 0L;
  187425. }
  187426. /* GRR: could add this: && defined(PNG_MMX_CODE_SUPPORTED) */
  187427. /* this function was added to libpng 1.2.0 */
  187428. png_uint_32 PNGAPI
  187429. png_get_mmx_flagmask (int flag_select, int *compilerID)
  187430. {
  187431. /* obsolete, to be removed from libpng-1.4.0 */
  187432. flag_select=flag_select;
  187433. *compilerID = -1; /* unknown (i.e., no asm/MMX code compiled) */
  187434. return 0L;
  187435. }
  187436. /* this function was added to libpng 1.2.0 */
  187437. png_byte PNGAPI
  187438. png_get_mmx_bitdepth_threshold (png_structp png_ptr)
  187439. {
  187440. /* obsolete, to be removed from libpng-1.4.0 */
  187441. return (png_ptr? 0: 0);
  187442. }
  187443. /* this function was added to libpng 1.2.0 */
  187444. png_uint_32 PNGAPI
  187445. png_get_mmx_rowbytes_threshold (png_structp png_ptr)
  187446. {
  187447. /* obsolete, to be removed from libpng-1.4.0 */
  187448. return (png_ptr? 0L: 0L);
  187449. }
  187450. #endif /* ?PNG_1_0_X */
  187451. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  187452. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  187453. /* these functions were added to libpng 1.2.6 */
  187454. png_uint_32 PNGAPI
  187455. png_get_user_width_max (png_structp png_ptr)
  187456. {
  187457. return (png_ptr? png_ptr->user_width_max : 0);
  187458. }
  187459. png_uint_32 PNGAPI
  187460. png_get_user_height_max (png_structp png_ptr)
  187461. {
  187462. return (png_ptr? png_ptr->user_height_max : 0);
  187463. }
  187464. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  187465. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  187466. /********* End of inlined file: pngget.c *********/
  187467. /********* Start of inlined file: pngmem.c *********/
  187468. /* pngmem.c - stub functions for memory allocation
  187469. *
  187470. * Last changed in libpng 1.2.13 November 13, 2006
  187471. * For conditions of distribution and use, see copyright notice in png.h
  187472. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  187473. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  187474. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  187475. *
  187476. * This file provides a location for all memory allocation. Users who
  187477. * need special memory handling are expected to supply replacement
  187478. * functions for png_malloc() and png_free(), and to use
  187479. * png_create_read_struct_2() and png_create_write_struct_2() to
  187480. * identify the replacement functions.
  187481. */
  187482. #define PNG_INTERNAL
  187483. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  187484. /* Borland DOS special memory handler */
  187485. #if defined(__TURBOC__) && !defined(_Windows) && !defined(__FLAT__)
  187486. /* if you change this, be sure to change the one in png.h also */
  187487. /* Allocate memory for a png_struct. The malloc and memset can be replaced
  187488. by a single call to calloc() if this is thought to improve performance. */
  187489. png_voidp /* PRIVATE */
  187490. png_create_struct(int type)
  187491. {
  187492. #ifdef PNG_USER_MEM_SUPPORTED
  187493. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  187494. }
  187495. /* Alternate version of png_create_struct, for use with user-defined malloc. */
  187496. png_voidp /* PRIVATE */
  187497. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  187498. {
  187499. #endif /* PNG_USER_MEM_SUPPORTED */
  187500. png_size_t size;
  187501. png_voidp struct_ptr;
  187502. if (type == PNG_STRUCT_INFO)
  187503. size = png_sizeof(png_info);
  187504. else if (type == PNG_STRUCT_PNG)
  187505. size = png_sizeof(png_struct);
  187506. else
  187507. return (png_get_copyright(NULL));
  187508. #ifdef PNG_USER_MEM_SUPPORTED
  187509. if(malloc_fn != NULL)
  187510. {
  187511. png_struct dummy_struct;
  187512. png_structp png_ptr = &dummy_struct;
  187513. png_ptr->mem_ptr=mem_ptr;
  187514. struct_ptr = (*(malloc_fn))(png_ptr, (png_uint_32)size);
  187515. }
  187516. else
  187517. #endif /* PNG_USER_MEM_SUPPORTED */
  187518. struct_ptr = (png_voidp)farmalloc(size);
  187519. if (struct_ptr != NULL)
  187520. png_memset(struct_ptr, 0, size);
  187521. return (struct_ptr);
  187522. }
  187523. /* Free memory allocated by a png_create_struct() call */
  187524. void /* PRIVATE */
  187525. png_destroy_struct(png_voidp struct_ptr)
  187526. {
  187527. #ifdef PNG_USER_MEM_SUPPORTED
  187528. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  187529. }
  187530. /* Free memory allocated by a png_create_struct() call */
  187531. void /* PRIVATE */
  187532. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  187533. png_voidp mem_ptr)
  187534. {
  187535. #endif
  187536. if (struct_ptr != NULL)
  187537. {
  187538. #ifdef PNG_USER_MEM_SUPPORTED
  187539. if(free_fn != NULL)
  187540. {
  187541. png_struct dummy_struct;
  187542. png_structp png_ptr = &dummy_struct;
  187543. png_ptr->mem_ptr=mem_ptr;
  187544. (*(free_fn))(png_ptr, struct_ptr);
  187545. return;
  187546. }
  187547. #endif /* PNG_USER_MEM_SUPPORTED */
  187548. farfree (struct_ptr);
  187549. }
  187550. }
  187551. /* Allocate memory. For reasonable files, size should never exceed
  187552. * 64K. However, zlib may allocate more then 64K if you don't tell
  187553. * it not to. See zconf.h and png.h for more information. zlib does
  187554. * need to allocate exactly 64K, so whatever you call here must
  187555. * have the ability to do that.
  187556. *
  187557. * Borland seems to have a problem in DOS mode for exactly 64K.
  187558. * It gives you a segment with an offset of 8 (perhaps to store its
  187559. * memory stuff). zlib doesn't like this at all, so we have to
  187560. * detect and deal with it. This code should not be needed in
  187561. * Windows or OS/2 modes, and only in 16 bit mode. This code has
  187562. * been updated by Alexander Lehmann for version 0.89 to waste less
  187563. * memory.
  187564. *
  187565. * Note that we can't use png_size_t for the "size" declaration,
  187566. * since on some systems a png_size_t is a 16-bit quantity, and as a
  187567. * result, we would be truncating potentially larger memory requests
  187568. * (which should cause a fatal error) and introducing major problems.
  187569. */
  187570. png_voidp PNGAPI
  187571. png_malloc(png_structp png_ptr, png_uint_32 size)
  187572. {
  187573. png_voidp ret;
  187574. if (png_ptr == NULL || size == 0)
  187575. return (NULL);
  187576. #ifdef PNG_USER_MEM_SUPPORTED
  187577. if(png_ptr->malloc_fn != NULL)
  187578. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  187579. else
  187580. ret = (png_malloc_default(png_ptr, size));
  187581. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187582. png_error(png_ptr, "Out of memory!");
  187583. return (ret);
  187584. }
  187585. png_voidp PNGAPI
  187586. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  187587. {
  187588. png_voidp ret;
  187589. #endif /* PNG_USER_MEM_SUPPORTED */
  187590. if (png_ptr == NULL || size == 0)
  187591. return (NULL);
  187592. #ifdef PNG_MAX_MALLOC_64K
  187593. if (size > (png_uint_32)65536L)
  187594. {
  187595. png_warning(png_ptr, "Cannot Allocate > 64K");
  187596. ret = NULL;
  187597. }
  187598. else
  187599. #endif
  187600. if (size != (size_t)size)
  187601. ret = NULL;
  187602. else if (size == (png_uint_32)65536L)
  187603. {
  187604. if (png_ptr->offset_table == NULL)
  187605. {
  187606. /* try to see if we need to do any of this fancy stuff */
  187607. ret = farmalloc(size);
  187608. if (ret == NULL || ((png_size_t)ret & 0xffff))
  187609. {
  187610. int num_blocks;
  187611. png_uint_32 total_size;
  187612. png_bytep table;
  187613. int i;
  187614. png_byte huge * hptr;
  187615. if (ret != NULL)
  187616. {
  187617. farfree(ret);
  187618. ret = NULL;
  187619. }
  187620. if(png_ptr->zlib_window_bits > 14)
  187621. num_blocks = (int)(1 << (png_ptr->zlib_window_bits - 14));
  187622. else
  187623. num_blocks = 1;
  187624. if (png_ptr->zlib_mem_level >= 7)
  187625. num_blocks += (int)(1 << (png_ptr->zlib_mem_level - 7));
  187626. else
  187627. num_blocks++;
  187628. total_size = ((png_uint_32)65536L) * (png_uint_32)num_blocks+16;
  187629. table = farmalloc(total_size);
  187630. if (table == NULL)
  187631. {
  187632. #ifndef PNG_USER_MEM_SUPPORTED
  187633. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187634. png_error(png_ptr, "Out Of Memory."); /* Note "O" and "M" */
  187635. else
  187636. png_warning(png_ptr, "Out Of Memory.");
  187637. #endif
  187638. return (NULL);
  187639. }
  187640. if ((png_size_t)table & 0xfff0)
  187641. {
  187642. #ifndef PNG_USER_MEM_SUPPORTED
  187643. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187644. png_error(png_ptr,
  187645. "Farmalloc didn't return normalized pointer");
  187646. else
  187647. png_warning(png_ptr,
  187648. "Farmalloc didn't return normalized pointer");
  187649. #endif
  187650. return (NULL);
  187651. }
  187652. png_ptr->offset_table = table;
  187653. png_ptr->offset_table_ptr = farmalloc(num_blocks *
  187654. png_sizeof (png_bytep));
  187655. if (png_ptr->offset_table_ptr == NULL)
  187656. {
  187657. #ifndef PNG_USER_MEM_SUPPORTED
  187658. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187659. png_error(png_ptr, "Out Of memory."); /* Note "O" and "M" */
  187660. else
  187661. png_warning(png_ptr, "Out Of memory.");
  187662. #endif
  187663. return (NULL);
  187664. }
  187665. hptr = (png_byte huge *)table;
  187666. if ((png_size_t)hptr & 0xf)
  187667. {
  187668. hptr = (png_byte huge *)((long)(hptr) & 0xfffffff0L);
  187669. hptr = hptr + 16L; /* "hptr += 16L" fails on Turbo C++ 3.0 */
  187670. }
  187671. for (i = 0; i < num_blocks; i++)
  187672. {
  187673. png_ptr->offset_table_ptr[i] = (png_bytep)hptr;
  187674. hptr = hptr + (png_uint_32)65536L; /* "+=" fails on TC++3.0 */
  187675. }
  187676. png_ptr->offset_table_number = num_blocks;
  187677. png_ptr->offset_table_count = 0;
  187678. png_ptr->offset_table_count_free = 0;
  187679. }
  187680. }
  187681. if (png_ptr->offset_table_count >= png_ptr->offset_table_number)
  187682. {
  187683. #ifndef PNG_USER_MEM_SUPPORTED
  187684. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187685. png_error(png_ptr, "Out of Memory."); /* Note "o" and "M" */
  187686. else
  187687. png_warning(png_ptr, "Out of Memory.");
  187688. #endif
  187689. return (NULL);
  187690. }
  187691. ret = png_ptr->offset_table_ptr[png_ptr->offset_table_count++];
  187692. }
  187693. else
  187694. ret = farmalloc(size);
  187695. #ifndef PNG_USER_MEM_SUPPORTED
  187696. if (ret == NULL)
  187697. {
  187698. if ((png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187699. png_error(png_ptr, "Out of memory."); /* Note "o" and "m" */
  187700. else
  187701. png_warning(png_ptr, "Out of memory."); /* Note "o" and "m" */
  187702. }
  187703. #endif
  187704. return (ret);
  187705. }
  187706. /* free a pointer allocated by png_malloc(). In the default
  187707. configuration, png_ptr is not used, but is passed in case it
  187708. is needed. If ptr is NULL, return without taking any action. */
  187709. void PNGAPI
  187710. png_free(png_structp png_ptr, png_voidp ptr)
  187711. {
  187712. if (png_ptr == NULL || ptr == NULL)
  187713. return;
  187714. #ifdef PNG_USER_MEM_SUPPORTED
  187715. if (png_ptr->free_fn != NULL)
  187716. {
  187717. (*(png_ptr->free_fn))(png_ptr, ptr);
  187718. return;
  187719. }
  187720. else png_free_default(png_ptr, ptr);
  187721. }
  187722. void PNGAPI
  187723. png_free_default(png_structp png_ptr, png_voidp ptr)
  187724. {
  187725. #endif /* PNG_USER_MEM_SUPPORTED */
  187726. if(png_ptr == NULL) return;
  187727. if (png_ptr->offset_table != NULL)
  187728. {
  187729. int i;
  187730. for (i = 0; i < png_ptr->offset_table_count; i++)
  187731. {
  187732. if (ptr == png_ptr->offset_table_ptr[i])
  187733. {
  187734. ptr = NULL;
  187735. png_ptr->offset_table_count_free++;
  187736. break;
  187737. }
  187738. }
  187739. if (png_ptr->offset_table_count_free == png_ptr->offset_table_count)
  187740. {
  187741. farfree(png_ptr->offset_table);
  187742. farfree(png_ptr->offset_table_ptr);
  187743. png_ptr->offset_table = NULL;
  187744. png_ptr->offset_table_ptr = NULL;
  187745. }
  187746. }
  187747. if (ptr != NULL)
  187748. {
  187749. farfree(ptr);
  187750. }
  187751. }
  187752. #else /* Not the Borland DOS special memory handler */
  187753. /* Allocate memory for a png_struct or a png_info. The malloc and
  187754. memset can be replaced by a single call to calloc() if this is thought
  187755. to improve performance noticably. */
  187756. png_voidp /* PRIVATE */
  187757. png_create_struct(int type)
  187758. {
  187759. #ifdef PNG_USER_MEM_SUPPORTED
  187760. return (png_create_struct_2(type, png_malloc_ptr_NULL, png_voidp_NULL));
  187761. }
  187762. /* Allocate memory for a png_struct or a png_info. The malloc and
  187763. memset can be replaced by a single call to calloc() if this is thought
  187764. to improve performance noticably. */
  187765. png_voidp /* PRIVATE */
  187766. png_create_struct_2(int type, png_malloc_ptr malloc_fn, png_voidp mem_ptr)
  187767. {
  187768. #endif /* PNG_USER_MEM_SUPPORTED */
  187769. png_size_t size;
  187770. png_voidp struct_ptr;
  187771. if (type == PNG_STRUCT_INFO)
  187772. size = png_sizeof(png_info);
  187773. else if (type == PNG_STRUCT_PNG)
  187774. size = png_sizeof(png_struct);
  187775. else
  187776. return (NULL);
  187777. #ifdef PNG_USER_MEM_SUPPORTED
  187778. if(malloc_fn != NULL)
  187779. {
  187780. png_struct dummy_struct;
  187781. png_structp png_ptr = &dummy_struct;
  187782. png_ptr->mem_ptr=mem_ptr;
  187783. struct_ptr = (*(malloc_fn))(png_ptr, size);
  187784. if (struct_ptr != NULL)
  187785. png_memset(struct_ptr, 0, size);
  187786. return (struct_ptr);
  187787. }
  187788. #endif /* PNG_USER_MEM_SUPPORTED */
  187789. #if defined(__TURBOC__) && !defined(__FLAT__)
  187790. struct_ptr = (png_voidp)farmalloc(size);
  187791. #else
  187792. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187793. struct_ptr = (png_voidp)halloc(size,1);
  187794. # else
  187795. struct_ptr = (png_voidp)malloc(size);
  187796. # endif
  187797. #endif
  187798. if (struct_ptr != NULL)
  187799. png_memset(struct_ptr, 0, size);
  187800. return (struct_ptr);
  187801. }
  187802. /* Free memory allocated by a png_create_struct() call */
  187803. void /* PRIVATE */
  187804. png_destroy_struct(png_voidp struct_ptr)
  187805. {
  187806. #ifdef PNG_USER_MEM_SUPPORTED
  187807. png_destroy_struct_2(struct_ptr, png_free_ptr_NULL, png_voidp_NULL);
  187808. }
  187809. /* Free memory allocated by a png_create_struct() call */
  187810. void /* PRIVATE */
  187811. png_destroy_struct_2(png_voidp struct_ptr, png_free_ptr free_fn,
  187812. png_voidp mem_ptr)
  187813. {
  187814. #endif /* PNG_USER_MEM_SUPPORTED */
  187815. if (struct_ptr != NULL)
  187816. {
  187817. #ifdef PNG_USER_MEM_SUPPORTED
  187818. if(free_fn != NULL)
  187819. {
  187820. png_struct dummy_struct;
  187821. png_structp png_ptr = &dummy_struct;
  187822. png_ptr->mem_ptr=mem_ptr;
  187823. (*(free_fn))(png_ptr, struct_ptr);
  187824. return;
  187825. }
  187826. #endif /* PNG_USER_MEM_SUPPORTED */
  187827. #if defined(__TURBOC__) && !defined(__FLAT__)
  187828. farfree(struct_ptr);
  187829. #else
  187830. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187831. hfree(struct_ptr);
  187832. # else
  187833. free(struct_ptr);
  187834. # endif
  187835. #endif
  187836. }
  187837. }
  187838. /* Allocate memory. For reasonable files, size should never exceed
  187839. 64K. However, zlib may allocate more then 64K if you don't tell
  187840. it not to. See zconf.h and png.h for more information. zlib does
  187841. need to allocate exactly 64K, so whatever you call here must
  187842. have the ability to do that. */
  187843. png_voidp PNGAPI
  187844. png_malloc(png_structp png_ptr, png_uint_32 size)
  187845. {
  187846. png_voidp ret;
  187847. #ifdef PNG_USER_MEM_SUPPORTED
  187848. if (png_ptr == NULL || size == 0)
  187849. return (NULL);
  187850. if(png_ptr->malloc_fn != NULL)
  187851. ret = ((png_voidp)(*(png_ptr->malloc_fn))(png_ptr, (png_size_t)size));
  187852. else
  187853. ret = (png_malloc_default(png_ptr, size));
  187854. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187855. png_error(png_ptr, "Out of Memory!");
  187856. return (ret);
  187857. }
  187858. png_voidp PNGAPI
  187859. png_malloc_default(png_structp png_ptr, png_uint_32 size)
  187860. {
  187861. png_voidp ret;
  187862. #endif /* PNG_USER_MEM_SUPPORTED */
  187863. if (png_ptr == NULL || size == 0)
  187864. return (NULL);
  187865. #ifdef PNG_MAX_MALLOC_64K
  187866. if (size > (png_uint_32)65536L)
  187867. {
  187868. #ifndef PNG_USER_MEM_SUPPORTED
  187869. if(png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187870. png_error(png_ptr, "Cannot Allocate > 64K");
  187871. else
  187872. #endif
  187873. return NULL;
  187874. }
  187875. #endif
  187876. /* Check for overflow */
  187877. #if defined(__TURBOC__) && !defined(__FLAT__)
  187878. if (size != (unsigned long)size)
  187879. ret = NULL;
  187880. else
  187881. ret = farmalloc(size);
  187882. #else
  187883. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187884. if (size != (unsigned long)size)
  187885. ret = NULL;
  187886. else
  187887. ret = halloc(size, 1);
  187888. # else
  187889. if (size != (size_t)size)
  187890. ret = NULL;
  187891. else
  187892. ret = malloc((size_t)size);
  187893. # endif
  187894. #endif
  187895. #ifndef PNG_USER_MEM_SUPPORTED
  187896. if (ret == NULL && (png_ptr->flags&PNG_FLAG_MALLOC_NULL_MEM_OK) == 0)
  187897. png_error(png_ptr, "Out of Memory");
  187898. #endif
  187899. return (ret);
  187900. }
  187901. /* Free a pointer allocated by png_malloc(). If ptr is NULL, return
  187902. without taking any action. */
  187903. void PNGAPI
  187904. png_free(png_structp png_ptr, png_voidp ptr)
  187905. {
  187906. if (png_ptr == NULL || ptr == NULL)
  187907. return;
  187908. #ifdef PNG_USER_MEM_SUPPORTED
  187909. if (png_ptr->free_fn != NULL)
  187910. {
  187911. (*(png_ptr->free_fn))(png_ptr, ptr);
  187912. return;
  187913. }
  187914. else png_free_default(png_ptr, ptr);
  187915. }
  187916. void PNGAPI
  187917. png_free_default(png_structp png_ptr, png_voidp ptr)
  187918. {
  187919. if (png_ptr == NULL || ptr == NULL)
  187920. return;
  187921. #endif /* PNG_USER_MEM_SUPPORTED */
  187922. #if defined(__TURBOC__) && !defined(__FLAT__)
  187923. farfree(ptr);
  187924. #else
  187925. # if defined(_MSC_VER) && defined(MAXSEG_64K)
  187926. hfree(ptr);
  187927. # else
  187928. free(ptr);
  187929. # endif
  187930. #endif
  187931. }
  187932. #endif /* Not Borland DOS special memory handler */
  187933. #if defined(PNG_1_0_X)
  187934. # define png_malloc_warn png_malloc
  187935. #else
  187936. /* This function was added at libpng version 1.2.3. The png_malloc_warn()
  187937. * function will set up png_malloc() to issue a png_warning and return NULL
  187938. * instead of issuing a png_error, if it fails to allocate the requested
  187939. * memory.
  187940. */
  187941. png_voidp PNGAPI
  187942. png_malloc_warn(png_structp png_ptr, png_uint_32 size)
  187943. {
  187944. png_voidp ptr;
  187945. png_uint_32 save_flags;
  187946. if(png_ptr == NULL) return (NULL);
  187947. save_flags=png_ptr->flags;
  187948. png_ptr->flags|=PNG_FLAG_MALLOC_NULL_MEM_OK;
  187949. ptr = (png_voidp)png_malloc((png_structp)png_ptr, size);
  187950. png_ptr->flags=save_flags;
  187951. return(ptr);
  187952. }
  187953. #endif
  187954. png_voidp PNGAPI
  187955. png_memcpy_check (png_structp png_ptr, png_voidp s1, png_voidp s2,
  187956. png_uint_32 length)
  187957. {
  187958. png_size_t size;
  187959. size = (png_size_t)length;
  187960. if ((png_uint_32)size != length)
  187961. png_error(png_ptr,"Overflow in png_memcpy_check.");
  187962. return(png_memcpy (s1, s2, size));
  187963. }
  187964. png_voidp PNGAPI
  187965. png_memset_check (png_structp png_ptr, png_voidp s1, int value,
  187966. png_uint_32 length)
  187967. {
  187968. png_size_t size;
  187969. size = (png_size_t)length;
  187970. if ((png_uint_32)size != length)
  187971. png_error(png_ptr,"Overflow in png_memset_check.");
  187972. return (png_memset (s1, value, size));
  187973. }
  187974. #ifdef PNG_USER_MEM_SUPPORTED
  187975. /* This function is called when the application wants to use another method
  187976. * of allocating and freeing memory.
  187977. */
  187978. void PNGAPI
  187979. png_set_mem_fn(png_structp png_ptr, png_voidp mem_ptr, png_malloc_ptr
  187980. malloc_fn, png_free_ptr free_fn)
  187981. {
  187982. if(png_ptr != NULL) {
  187983. png_ptr->mem_ptr = mem_ptr;
  187984. png_ptr->malloc_fn = malloc_fn;
  187985. png_ptr->free_fn = free_fn;
  187986. }
  187987. }
  187988. /* This function returns a pointer to the mem_ptr associated with the user
  187989. * functions. The application should free any memory associated with this
  187990. * pointer before png_write_destroy and png_read_destroy are called.
  187991. */
  187992. png_voidp PNGAPI
  187993. png_get_mem_ptr(png_structp png_ptr)
  187994. {
  187995. if(png_ptr == NULL) return (NULL);
  187996. return ((png_voidp)png_ptr->mem_ptr);
  187997. }
  187998. #endif /* PNG_USER_MEM_SUPPORTED */
  187999. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  188000. /********* End of inlined file: pngmem.c *********/
  188001. /********* Start of inlined file: pngread.c *********/
  188002. /* pngread.c - read a PNG file
  188003. *
  188004. * Last changed in libpng 1.2.20 September 7, 2007
  188005. * For conditions of distribution and use, see copyright notice in png.h
  188006. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  188007. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  188008. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  188009. *
  188010. * This file contains routines that an application calls directly to
  188011. * read a PNG file or stream.
  188012. */
  188013. #define PNG_INTERNAL
  188014. #if defined(PNG_READ_SUPPORTED)
  188015. /* Create a PNG structure for reading, and allocate any memory needed. */
  188016. png_structp PNGAPI
  188017. png_create_read_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  188018. png_error_ptr error_fn, png_error_ptr warn_fn)
  188019. {
  188020. #ifdef PNG_USER_MEM_SUPPORTED
  188021. return (png_create_read_struct_2(user_png_ver, error_ptr, error_fn,
  188022. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  188023. }
  188024. /* Alternate create PNG structure for reading, and allocate any memory needed. */
  188025. png_structp PNGAPI
  188026. png_create_read_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  188027. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  188028. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  188029. {
  188030. #endif /* PNG_USER_MEM_SUPPORTED */
  188031. png_structp png_ptr;
  188032. #ifdef PNG_SETJMP_SUPPORTED
  188033. #ifdef USE_FAR_KEYWORD
  188034. jmp_buf jmpbuf;
  188035. #endif
  188036. #endif
  188037. int i;
  188038. png_debug(1, "in png_create_read_struct\n");
  188039. #ifdef PNG_USER_MEM_SUPPORTED
  188040. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  188041. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  188042. #else
  188043. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  188044. #endif
  188045. if (png_ptr == NULL)
  188046. return (NULL);
  188047. /* added at libpng-1.2.6 */
  188048. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  188049. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  188050. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  188051. #endif
  188052. #ifdef PNG_SETJMP_SUPPORTED
  188053. #ifdef USE_FAR_KEYWORD
  188054. if (setjmp(jmpbuf))
  188055. #else
  188056. if (setjmp(png_ptr->jmpbuf))
  188057. #endif
  188058. {
  188059. png_free(png_ptr, png_ptr->zbuf);
  188060. png_ptr->zbuf=NULL;
  188061. #ifdef PNG_USER_MEM_SUPPORTED
  188062. png_destroy_struct_2((png_voidp)png_ptr,
  188063. (png_free_ptr)free_fn, (png_voidp)mem_ptr);
  188064. #else
  188065. png_destroy_struct((png_voidp)png_ptr);
  188066. #endif
  188067. return (NULL);
  188068. }
  188069. #ifdef USE_FAR_KEYWORD
  188070. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  188071. #endif
  188072. #endif
  188073. #ifdef PNG_USER_MEM_SUPPORTED
  188074. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  188075. #endif
  188076. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  188077. i=0;
  188078. do
  188079. {
  188080. if(user_png_ver[i] != png_libpng_ver[i])
  188081. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  188082. } while (png_libpng_ver[i++]);
  188083. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  188084. {
  188085. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  188086. * we must recompile any applications that use any older library version.
  188087. * For versions after libpng 1.0, we will be compatible, so we need
  188088. * only check the first digit.
  188089. */
  188090. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  188091. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  188092. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  188093. {
  188094. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  188095. char msg[80];
  188096. if (user_png_ver)
  188097. {
  188098. png_snprintf(msg, 80,
  188099. "Application was compiled with png.h from libpng-%.20s",
  188100. user_png_ver);
  188101. png_warning(png_ptr, msg);
  188102. }
  188103. png_snprintf(msg, 80,
  188104. "Application is running with png.c from libpng-%.20s",
  188105. png_libpng_ver);
  188106. png_warning(png_ptr, msg);
  188107. #endif
  188108. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  188109. png_ptr->flags=0;
  188110. #endif
  188111. png_error(png_ptr,
  188112. "Incompatible libpng version in application and library");
  188113. }
  188114. }
  188115. /* initialize zbuf - compression buffer */
  188116. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  188117. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  188118. (png_uint_32)png_ptr->zbuf_size);
  188119. png_ptr->zstream.zalloc = png_zalloc;
  188120. png_ptr->zstream.zfree = png_zfree;
  188121. png_ptr->zstream.opaque = (voidpf)png_ptr;
  188122. switch (inflateInit(&png_ptr->zstream))
  188123. {
  188124. case Z_OK: /* Do nothing */ break;
  188125. case Z_MEM_ERROR:
  188126. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory error"); break;
  188127. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version error"); break;
  188128. default: png_error(png_ptr, "Unknown zlib error");
  188129. }
  188130. png_ptr->zstream.next_out = png_ptr->zbuf;
  188131. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188132. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  188133. #ifdef PNG_SETJMP_SUPPORTED
  188134. /* Applications that neglect to set up their own setjmp() and then encounter
  188135. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  188136. abort instead of returning. */
  188137. #ifdef USE_FAR_KEYWORD
  188138. if (setjmp(jmpbuf))
  188139. PNG_ABORT();
  188140. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  188141. #else
  188142. if (setjmp(png_ptr->jmpbuf))
  188143. PNG_ABORT();
  188144. #endif
  188145. #endif
  188146. return (png_ptr);
  188147. }
  188148. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  188149. /* Initialize PNG structure for reading, and allocate any memory needed.
  188150. This interface is deprecated in favour of the png_create_read_struct(),
  188151. and it will disappear as of libpng-1.3.0. */
  188152. #undef png_read_init
  188153. void PNGAPI
  188154. png_read_init(png_structp png_ptr)
  188155. {
  188156. /* We only come here via pre-1.0.7-compiled applications */
  188157. png_read_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  188158. }
  188159. void PNGAPI
  188160. png_read_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  188161. png_size_t png_struct_size, png_size_t png_info_size)
  188162. {
  188163. /* We only come here via pre-1.0.12-compiled applications */
  188164. if(png_ptr == NULL) return;
  188165. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  188166. if(png_sizeof(png_struct) > png_struct_size ||
  188167. png_sizeof(png_info) > png_info_size)
  188168. {
  188169. char msg[80];
  188170. png_ptr->warning_fn=NULL;
  188171. if (user_png_ver)
  188172. {
  188173. png_snprintf(msg, 80,
  188174. "Application was compiled with png.h from libpng-%.20s",
  188175. user_png_ver);
  188176. png_warning(png_ptr, msg);
  188177. }
  188178. png_snprintf(msg, 80,
  188179. "Application is running with png.c from libpng-%.20s",
  188180. png_libpng_ver);
  188181. png_warning(png_ptr, msg);
  188182. }
  188183. #endif
  188184. if(png_sizeof(png_struct) > png_struct_size)
  188185. {
  188186. png_ptr->error_fn=NULL;
  188187. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  188188. png_ptr->flags=0;
  188189. #endif
  188190. png_error(png_ptr,
  188191. "The png struct allocated by the application for reading is too small.");
  188192. }
  188193. if(png_sizeof(png_info) > png_info_size)
  188194. {
  188195. png_ptr->error_fn=NULL;
  188196. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  188197. png_ptr->flags=0;
  188198. #endif
  188199. png_error(png_ptr,
  188200. "The info struct allocated by application for reading is too small.");
  188201. }
  188202. png_read_init_3(&png_ptr, user_png_ver, png_struct_size);
  188203. }
  188204. #endif /* PNG_1_0_X || PNG_1_2_X */
  188205. void PNGAPI
  188206. png_read_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  188207. png_size_t png_struct_size)
  188208. {
  188209. #ifdef PNG_SETJMP_SUPPORTED
  188210. jmp_buf tmp_jmp; /* to save current jump buffer */
  188211. #endif
  188212. int i=0;
  188213. png_structp png_ptr=*ptr_ptr;
  188214. if(png_ptr == NULL) return;
  188215. do
  188216. {
  188217. if(user_png_ver[i] != png_libpng_ver[i])
  188218. {
  188219. #ifdef PNG_LEGACY_SUPPORTED
  188220. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  188221. #else
  188222. png_ptr->warning_fn=NULL;
  188223. png_warning(png_ptr,
  188224. "Application uses deprecated png_read_init() and should be recompiled.");
  188225. break;
  188226. #endif
  188227. }
  188228. } while (png_libpng_ver[i++]);
  188229. png_debug(1, "in png_read_init_3\n");
  188230. #ifdef PNG_SETJMP_SUPPORTED
  188231. /* save jump buffer and error functions */
  188232. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  188233. #endif
  188234. if(png_sizeof(png_struct) > png_struct_size)
  188235. {
  188236. png_destroy_struct(png_ptr);
  188237. *ptr_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  188238. png_ptr = *ptr_ptr;
  188239. }
  188240. /* reset all variables to 0 */
  188241. png_memset(png_ptr, 0, png_sizeof (png_struct));
  188242. #ifdef PNG_SETJMP_SUPPORTED
  188243. /* restore jump buffer */
  188244. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  188245. #endif
  188246. /* added at libpng-1.2.6 */
  188247. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  188248. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  188249. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  188250. #endif
  188251. /* initialize zbuf - compression buffer */
  188252. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  188253. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  188254. (png_uint_32)png_ptr->zbuf_size);
  188255. png_ptr->zstream.zalloc = png_zalloc;
  188256. png_ptr->zstream.zfree = png_zfree;
  188257. png_ptr->zstream.opaque = (voidpf)png_ptr;
  188258. switch (inflateInit(&png_ptr->zstream))
  188259. {
  188260. case Z_OK: /* Do nothing */ break;
  188261. case Z_MEM_ERROR:
  188262. case Z_STREAM_ERROR: png_error(png_ptr, "zlib memory"); break;
  188263. case Z_VERSION_ERROR: png_error(png_ptr, "zlib version"); break;
  188264. default: png_error(png_ptr, "Unknown zlib error");
  188265. }
  188266. png_ptr->zstream.next_out = png_ptr->zbuf;
  188267. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  188268. png_set_read_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL);
  188269. }
  188270. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188271. /* Read the information before the actual image data. This has been
  188272. * changed in v0.90 to allow reading a file that already has the magic
  188273. * bytes read from the stream. You can tell libpng how many bytes have
  188274. * been read from the beginning of the stream (up to the maximum of 8)
  188275. * via png_set_sig_bytes(), and we will only check the remaining bytes
  188276. * here. The application can then have access to the signature bytes we
  188277. * read if it is determined that this isn't a valid PNG file.
  188278. */
  188279. void PNGAPI
  188280. png_read_info(png_structp png_ptr, png_infop info_ptr)
  188281. {
  188282. if(png_ptr == NULL) return;
  188283. png_debug(1, "in png_read_info\n");
  188284. /* If we haven't checked all of the PNG signature bytes, do so now. */
  188285. if (png_ptr->sig_bytes < 8)
  188286. {
  188287. png_size_t num_checked = png_ptr->sig_bytes,
  188288. num_to_check = 8 - num_checked;
  188289. png_read_data(png_ptr, &(info_ptr->signature[num_checked]), num_to_check);
  188290. png_ptr->sig_bytes = 8;
  188291. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  188292. {
  188293. if (num_checked < 4 &&
  188294. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  188295. png_error(png_ptr, "Not a PNG file");
  188296. else
  188297. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  188298. }
  188299. if (num_checked < 3)
  188300. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  188301. }
  188302. for(;;)
  188303. {
  188304. #ifdef PNG_USE_LOCAL_ARRAYS
  188305. PNG_CONST PNG_IHDR;
  188306. PNG_CONST PNG_IDAT;
  188307. PNG_CONST PNG_IEND;
  188308. PNG_CONST PNG_PLTE;
  188309. #if defined(PNG_READ_bKGD_SUPPORTED)
  188310. PNG_CONST PNG_bKGD;
  188311. #endif
  188312. #if defined(PNG_READ_cHRM_SUPPORTED)
  188313. PNG_CONST PNG_cHRM;
  188314. #endif
  188315. #if defined(PNG_READ_gAMA_SUPPORTED)
  188316. PNG_CONST PNG_gAMA;
  188317. #endif
  188318. #if defined(PNG_READ_hIST_SUPPORTED)
  188319. PNG_CONST PNG_hIST;
  188320. #endif
  188321. #if defined(PNG_READ_iCCP_SUPPORTED)
  188322. PNG_CONST PNG_iCCP;
  188323. #endif
  188324. #if defined(PNG_READ_iTXt_SUPPORTED)
  188325. PNG_CONST PNG_iTXt;
  188326. #endif
  188327. #if defined(PNG_READ_oFFs_SUPPORTED)
  188328. PNG_CONST PNG_oFFs;
  188329. #endif
  188330. #if defined(PNG_READ_pCAL_SUPPORTED)
  188331. PNG_CONST PNG_pCAL;
  188332. #endif
  188333. #if defined(PNG_READ_pHYs_SUPPORTED)
  188334. PNG_CONST PNG_pHYs;
  188335. #endif
  188336. #if defined(PNG_READ_sBIT_SUPPORTED)
  188337. PNG_CONST PNG_sBIT;
  188338. #endif
  188339. #if defined(PNG_READ_sCAL_SUPPORTED)
  188340. PNG_CONST PNG_sCAL;
  188341. #endif
  188342. #if defined(PNG_READ_sPLT_SUPPORTED)
  188343. PNG_CONST PNG_sPLT;
  188344. #endif
  188345. #if defined(PNG_READ_sRGB_SUPPORTED)
  188346. PNG_CONST PNG_sRGB;
  188347. #endif
  188348. #if defined(PNG_READ_tEXt_SUPPORTED)
  188349. PNG_CONST PNG_tEXt;
  188350. #endif
  188351. #if defined(PNG_READ_tIME_SUPPORTED)
  188352. PNG_CONST PNG_tIME;
  188353. #endif
  188354. #if defined(PNG_READ_tRNS_SUPPORTED)
  188355. PNG_CONST PNG_tRNS;
  188356. #endif
  188357. #if defined(PNG_READ_zTXt_SUPPORTED)
  188358. PNG_CONST PNG_zTXt;
  188359. #endif
  188360. #endif /* PNG_USE_LOCAL_ARRAYS */
  188361. png_byte chunk_length[4];
  188362. png_uint_32 length;
  188363. png_read_data(png_ptr, chunk_length, 4);
  188364. length = png_get_uint_31(png_ptr,chunk_length);
  188365. png_reset_crc(png_ptr);
  188366. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188367. png_debug2(0, "Reading %s chunk, length=%lu.\n", png_ptr->chunk_name,
  188368. length);
  188369. /* This should be a binary subdivision search or a hash for
  188370. * matching the chunk name rather than a linear search.
  188371. */
  188372. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188373. if(png_ptr->mode & PNG_AFTER_IDAT)
  188374. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  188375. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188376. png_handle_IHDR(png_ptr, info_ptr, length);
  188377. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188378. png_handle_IEND(png_ptr, info_ptr, length);
  188379. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188380. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188381. {
  188382. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188383. png_ptr->mode |= PNG_HAVE_IDAT;
  188384. png_handle_unknown(png_ptr, info_ptr, length);
  188385. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188386. png_ptr->mode |= PNG_HAVE_PLTE;
  188387. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188388. {
  188389. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188390. png_error(png_ptr, "Missing IHDR before IDAT");
  188391. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188392. !(png_ptr->mode & PNG_HAVE_PLTE))
  188393. png_error(png_ptr, "Missing PLTE before IDAT");
  188394. break;
  188395. }
  188396. }
  188397. #endif
  188398. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188399. png_handle_PLTE(png_ptr, info_ptr, length);
  188400. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188401. {
  188402. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  188403. png_error(png_ptr, "Missing IHDR before IDAT");
  188404. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  188405. !(png_ptr->mode & PNG_HAVE_PLTE))
  188406. png_error(png_ptr, "Missing PLTE before IDAT");
  188407. png_ptr->idat_size = length;
  188408. png_ptr->mode |= PNG_HAVE_IDAT;
  188409. break;
  188410. }
  188411. #if defined(PNG_READ_bKGD_SUPPORTED)
  188412. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188413. png_handle_bKGD(png_ptr, info_ptr, length);
  188414. #endif
  188415. #if defined(PNG_READ_cHRM_SUPPORTED)
  188416. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188417. png_handle_cHRM(png_ptr, info_ptr, length);
  188418. #endif
  188419. #if defined(PNG_READ_gAMA_SUPPORTED)
  188420. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188421. png_handle_gAMA(png_ptr, info_ptr, length);
  188422. #endif
  188423. #if defined(PNG_READ_hIST_SUPPORTED)
  188424. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188425. png_handle_hIST(png_ptr, info_ptr, length);
  188426. #endif
  188427. #if defined(PNG_READ_oFFs_SUPPORTED)
  188428. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188429. png_handle_oFFs(png_ptr, info_ptr, length);
  188430. #endif
  188431. #if defined(PNG_READ_pCAL_SUPPORTED)
  188432. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188433. png_handle_pCAL(png_ptr, info_ptr, length);
  188434. #endif
  188435. #if defined(PNG_READ_sCAL_SUPPORTED)
  188436. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188437. png_handle_sCAL(png_ptr, info_ptr, length);
  188438. #endif
  188439. #if defined(PNG_READ_pHYs_SUPPORTED)
  188440. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188441. png_handle_pHYs(png_ptr, info_ptr, length);
  188442. #endif
  188443. #if defined(PNG_READ_sBIT_SUPPORTED)
  188444. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188445. png_handle_sBIT(png_ptr, info_ptr, length);
  188446. #endif
  188447. #if defined(PNG_READ_sRGB_SUPPORTED)
  188448. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188449. png_handle_sRGB(png_ptr, info_ptr, length);
  188450. #endif
  188451. #if defined(PNG_READ_iCCP_SUPPORTED)
  188452. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188453. png_handle_iCCP(png_ptr, info_ptr, length);
  188454. #endif
  188455. #if defined(PNG_READ_sPLT_SUPPORTED)
  188456. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188457. png_handle_sPLT(png_ptr, info_ptr, length);
  188458. #endif
  188459. #if defined(PNG_READ_tEXt_SUPPORTED)
  188460. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188461. png_handle_tEXt(png_ptr, info_ptr, length);
  188462. #endif
  188463. #if defined(PNG_READ_tIME_SUPPORTED)
  188464. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188465. png_handle_tIME(png_ptr, info_ptr, length);
  188466. #endif
  188467. #if defined(PNG_READ_tRNS_SUPPORTED)
  188468. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188469. png_handle_tRNS(png_ptr, info_ptr, length);
  188470. #endif
  188471. #if defined(PNG_READ_zTXt_SUPPORTED)
  188472. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188473. png_handle_zTXt(png_ptr, info_ptr, length);
  188474. #endif
  188475. #if defined(PNG_READ_iTXt_SUPPORTED)
  188476. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  188477. png_handle_iTXt(png_ptr, info_ptr, length);
  188478. #endif
  188479. else
  188480. png_handle_unknown(png_ptr, info_ptr, length);
  188481. }
  188482. }
  188483. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188484. /* optional call to update the users info_ptr structure */
  188485. void PNGAPI
  188486. png_read_update_info(png_structp png_ptr, png_infop info_ptr)
  188487. {
  188488. png_debug(1, "in png_read_update_info\n");
  188489. if(png_ptr == NULL) return;
  188490. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  188491. png_read_start_row(png_ptr);
  188492. else
  188493. png_warning(png_ptr,
  188494. "Ignoring extra png_read_update_info() call; row buffer not reallocated");
  188495. png_read_transform_info(png_ptr, info_ptr);
  188496. }
  188497. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188498. /* Initialize palette, background, etc, after transformations
  188499. * are set, but before any reading takes place. This allows
  188500. * the user to obtain a gamma-corrected palette, for example.
  188501. * If the user doesn't call this, we will do it ourselves.
  188502. */
  188503. void PNGAPI
  188504. png_start_read_image(png_structp png_ptr)
  188505. {
  188506. png_debug(1, "in png_start_read_image\n");
  188507. if(png_ptr == NULL) return;
  188508. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  188509. png_read_start_row(png_ptr);
  188510. }
  188511. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188512. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188513. void PNGAPI
  188514. png_read_row(png_structp png_ptr, png_bytep row, png_bytep dsp_row)
  188515. {
  188516. #ifdef PNG_USE_LOCAL_ARRAYS
  188517. PNG_CONST PNG_IDAT;
  188518. PNG_CONST int png_pass_dsp_mask[7] = {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55,
  188519. 0xff};
  188520. PNG_CONST int png_pass_mask[7] = {0x80, 0x08, 0x88, 0x22, 0xaa, 0x55, 0xff};
  188521. #endif
  188522. int ret;
  188523. if(png_ptr == NULL) return;
  188524. png_debug2(1, "in png_read_row (row %lu, pass %d)\n",
  188525. png_ptr->row_number, png_ptr->pass);
  188526. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  188527. png_read_start_row(png_ptr);
  188528. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  188529. {
  188530. /* check for transforms that have been set but were defined out */
  188531. #if defined(PNG_WRITE_INVERT_SUPPORTED) && !defined(PNG_READ_INVERT_SUPPORTED)
  188532. if (png_ptr->transformations & PNG_INVERT_MONO)
  188533. png_warning(png_ptr, "PNG_READ_INVERT_SUPPORTED is not defined.");
  188534. #endif
  188535. #if defined(PNG_WRITE_FILLER_SUPPORTED) && !defined(PNG_READ_FILLER_SUPPORTED)
  188536. if (png_ptr->transformations & PNG_FILLER)
  188537. png_warning(png_ptr, "PNG_READ_FILLER_SUPPORTED is not defined.");
  188538. #endif
  188539. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED) && !defined(PNG_READ_PACKSWAP_SUPPORTED)
  188540. if (png_ptr->transformations & PNG_PACKSWAP)
  188541. png_warning(png_ptr, "PNG_READ_PACKSWAP_SUPPORTED is not defined.");
  188542. #endif
  188543. #if defined(PNG_WRITE_PACK_SUPPORTED) && !defined(PNG_READ_PACK_SUPPORTED)
  188544. if (png_ptr->transformations & PNG_PACK)
  188545. png_warning(png_ptr, "PNG_READ_PACK_SUPPORTED is not defined.");
  188546. #endif
  188547. #if defined(PNG_WRITE_SHIFT_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED)
  188548. if (png_ptr->transformations & PNG_SHIFT)
  188549. png_warning(png_ptr, "PNG_READ_SHIFT_SUPPORTED is not defined.");
  188550. #endif
  188551. #if defined(PNG_WRITE_BGR_SUPPORTED) && !defined(PNG_READ_BGR_SUPPORTED)
  188552. if (png_ptr->transformations & PNG_BGR)
  188553. png_warning(png_ptr, "PNG_READ_BGR_SUPPORTED is not defined.");
  188554. #endif
  188555. #if defined(PNG_WRITE_SWAP_SUPPORTED) && !defined(PNG_READ_SWAP_SUPPORTED)
  188556. if (png_ptr->transformations & PNG_SWAP_BYTES)
  188557. png_warning(png_ptr, "PNG_READ_SWAP_SUPPORTED is not defined.");
  188558. #endif
  188559. }
  188560. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188561. /* if interlaced and we do not need a new row, combine row and return */
  188562. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  188563. {
  188564. switch (png_ptr->pass)
  188565. {
  188566. case 0:
  188567. if (png_ptr->row_number & 0x07)
  188568. {
  188569. if (dsp_row != NULL)
  188570. png_combine_row(png_ptr, dsp_row,
  188571. png_pass_dsp_mask[png_ptr->pass]);
  188572. png_read_finish_row(png_ptr);
  188573. return;
  188574. }
  188575. break;
  188576. case 1:
  188577. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  188578. {
  188579. if (dsp_row != NULL)
  188580. png_combine_row(png_ptr, dsp_row,
  188581. png_pass_dsp_mask[png_ptr->pass]);
  188582. png_read_finish_row(png_ptr);
  188583. return;
  188584. }
  188585. break;
  188586. case 2:
  188587. if ((png_ptr->row_number & 0x07) != 4)
  188588. {
  188589. if (dsp_row != NULL && (png_ptr->row_number & 4))
  188590. png_combine_row(png_ptr, dsp_row,
  188591. png_pass_dsp_mask[png_ptr->pass]);
  188592. png_read_finish_row(png_ptr);
  188593. return;
  188594. }
  188595. break;
  188596. case 3:
  188597. if ((png_ptr->row_number & 3) || png_ptr->width < 3)
  188598. {
  188599. if (dsp_row != NULL)
  188600. png_combine_row(png_ptr, dsp_row,
  188601. png_pass_dsp_mask[png_ptr->pass]);
  188602. png_read_finish_row(png_ptr);
  188603. return;
  188604. }
  188605. break;
  188606. case 4:
  188607. if ((png_ptr->row_number & 3) != 2)
  188608. {
  188609. if (dsp_row != NULL && (png_ptr->row_number & 2))
  188610. png_combine_row(png_ptr, dsp_row,
  188611. png_pass_dsp_mask[png_ptr->pass]);
  188612. png_read_finish_row(png_ptr);
  188613. return;
  188614. }
  188615. break;
  188616. case 5:
  188617. if ((png_ptr->row_number & 1) || png_ptr->width < 2)
  188618. {
  188619. if (dsp_row != NULL)
  188620. png_combine_row(png_ptr, dsp_row,
  188621. png_pass_dsp_mask[png_ptr->pass]);
  188622. png_read_finish_row(png_ptr);
  188623. return;
  188624. }
  188625. break;
  188626. case 6:
  188627. if (!(png_ptr->row_number & 1))
  188628. {
  188629. png_read_finish_row(png_ptr);
  188630. return;
  188631. }
  188632. break;
  188633. }
  188634. }
  188635. #endif
  188636. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  188637. png_error(png_ptr, "Invalid attempt to read row data");
  188638. png_ptr->zstream.next_out = png_ptr->row_buf;
  188639. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  188640. do
  188641. {
  188642. if (!(png_ptr->zstream.avail_in))
  188643. {
  188644. while (!png_ptr->idat_size)
  188645. {
  188646. png_byte chunk_length[4];
  188647. png_crc_finish(png_ptr, 0);
  188648. png_read_data(png_ptr, chunk_length, 4);
  188649. png_ptr->idat_size = png_get_uint_31(png_ptr,chunk_length);
  188650. png_reset_crc(png_ptr);
  188651. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188652. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188653. png_error(png_ptr, "Not enough image data");
  188654. }
  188655. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  188656. png_ptr->zstream.next_in = png_ptr->zbuf;
  188657. if (png_ptr->zbuf_size > png_ptr->idat_size)
  188658. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  188659. png_crc_read(png_ptr, png_ptr->zbuf,
  188660. (png_size_t)png_ptr->zstream.avail_in);
  188661. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  188662. }
  188663. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  188664. if (ret == Z_STREAM_END)
  188665. {
  188666. if (png_ptr->zstream.avail_out || png_ptr->zstream.avail_in ||
  188667. png_ptr->idat_size)
  188668. png_error(png_ptr, "Extra compressed data");
  188669. png_ptr->mode |= PNG_AFTER_IDAT;
  188670. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  188671. break;
  188672. }
  188673. if (ret != Z_OK)
  188674. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  188675. "Decompression error");
  188676. } while (png_ptr->zstream.avail_out);
  188677. png_ptr->row_info.color_type = png_ptr->color_type;
  188678. png_ptr->row_info.width = png_ptr->iwidth;
  188679. png_ptr->row_info.channels = png_ptr->channels;
  188680. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  188681. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  188682. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  188683. png_ptr->row_info.width);
  188684. if(png_ptr->row_buf[0])
  188685. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  188686. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  188687. (int)(png_ptr->row_buf[0]));
  188688. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  188689. png_ptr->rowbytes + 1);
  188690. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  188691. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  188692. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  188693. {
  188694. /* Intrapixel differencing */
  188695. png_do_read_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  188696. }
  188697. #endif
  188698. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  188699. png_do_read_transformations(png_ptr);
  188700. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  188701. /* blow up interlaced rows to full size */
  188702. if (png_ptr->interlaced &&
  188703. (png_ptr->transformations & PNG_INTERLACE))
  188704. {
  188705. if (png_ptr->pass < 6)
  188706. /* old interface (pre-1.0.9):
  188707. png_do_read_interlace(&(png_ptr->row_info),
  188708. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  188709. */
  188710. png_do_read_interlace(png_ptr);
  188711. if (dsp_row != NULL)
  188712. png_combine_row(png_ptr, dsp_row,
  188713. png_pass_dsp_mask[png_ptr->pass]);
  188714. if (row != NULL)
  188715. png_combine_row(png_ptr, row,
  188716. png_pass_mask[png_ptr->pass]);
  188717. }
  188718. else
  188719. #endif
  188720. {
  188721. if (row != NULL)
  188722. png_combine_row(png_ptr, row, 0xff);
  188723. if (dsp_row != NULL)
  188724. png_combine_row(png_ptr, dsp_row, 0xff);
  188725. }
  188726. png_read_finish_row(png_ptr);
  188727. if (png_ptr->read_row_fn != NULL)
  188728. (*(png_ptr->read_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  188729. }
  188730. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188731. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188732. /* Read one or more rows of image data. If the image is interlaced,
  188733. * and png_set_interlace_handling() has been called, the rows need to
  188734. * contain the contents of the rows from the previous pass. If the
  188735. * image has alpha or transparency, and png_handle_alpha()[*] has been
  188736. * called, the rows contents must be initialized to the contents of the
  188737. * screen.
  188738. *
  188739. * "row" holds the actual image, and pixels are placed in it
  188740. * as they arrive. If the image is displayed after each pass, it will
  188741. * appear to "sparkle" in. "display_row" can be used to display a
  188742. * "chunky" progressive image, with finer detail added as it becomes
  188743. * available. If you do not want this "chunky" display, you may pass
  188744. * NULL for display_row. If you do not want the sparkle display, and
  188745. * you have not called png_handle_alpha(), you may pass NULL for rows.
  188746. * If you have called png_handle_alpha(), and the image has either an
  188747. * alpha channel or a transparency chunk, you must provide a buffer for
  188748. * rows. In this case, you do not have to provide a display_row buffer
  188749. * also, but you may. If the image is not interlaced, or if you have
  188750. * not called png_set_interlace_handling(), the display_row buffer will
  188751. * be ignored, so pass NULL to it.
  188752. *
  188753. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188754. */
  188755. void PNGAPI
  188756. png_read_rows(png_structp png_ptr, png_bytepp row,
  188757. png_bytepp display_row, png_uint_32 num_rows)
  188758. {
  188759. png_uint_32 i;
  188760. png_bytepp rp;
  188761. png_bytepp dp;
  188762. png_debug(1, "in png_read_rows\n");
  188763. if(png_ptr == NULL) return;
  188764. rp = row;
  188765. dp = display_row;
  188766. if (rp != NULL && dp != NULL)
  188767. for (i = 0; i < num_rows; i++)
  188768. {
  188769. png_bytep rptr = *rp++;
  188770. png_bytep dptr = *dp++;
  188771. png_read_row(png_ptr, rptr, dptr);
  188772. }
  188773. else if(rp != NULL)
  188774. for (i = 0; i < num_rows; i++)
  188775. {
  188776. png_bytep rptr = *rp;
  188777. png_read_row(png_ptr, rptr, png_bytep_NULL);
  188778. rp++;
  188779. }
  188780. else if(dp != NULL)
  188781. for (i = 0; i < num_rows; i++)
  188782. {
  188783. png_bytep dptr = *dp;
  188784. png_read_row(png_ptr, png_bytep_NULL, dptr);
  188785. dp++;
  188786. }
  188787. }
  188788. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188789. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188790. /* Read the entire image. If the image has an alpha channel or a tRNS
  188791. * chunk, and you have called png_handle_alpha()[*], you will need to
  188792. * initialize the image to the current image that PNG will be overlaying.
  188793. * We set the num_rows again here, in case it was incorrectly set in
  188794. * png_read_start_row() by a call to png_read_update_info() or
  188795. * png_start_read_image() if png_set_interlace_handling() wasn't called
  188796. * prior to either of these functions like it should have been. You can
  188797. * only call this function once. If you desire to have an image for
  188798. * each pass of a interlaced image, use png_read_rows() instead.
  188799. *
  188800. * [*] png_handle_alpha() does not exist yet, as of this version of libpng
  188801. */
  188802. void PNGAPI
  188803. png_read_image(png_structp png_ptr, png_bytepp image)
  188804. {
  188805. png_uint_32 i,image_height;
  188806. int pass, j;
  188807. png_bytepp rp;
  188808. png_debug(1, "in png_read_image\n");
  188809. if(png_ptr == NULL) return;
  188810. #ifdef PNG_READ_INTERLACING_SUPPORTED
  188811. pass = png_set_interlace_handling(png_ptr);
  188812. #else
  188813. if (png_ptr->interlaced)
  188814. png_error(png_ptr,
  188815. "Cannot read interlaced image -- interlace handler disabled.");
  188816. pass = 1;
  188817. #endif
  188818. image_height=png_ptr->height;
  188819. png_ptr->num_rows = image_height; /* Make sure this is set correctly */
  188820. for (j = 0; j < pass; j++)
  188821. {
  188822. rp = image;
  188823. for (i = 0; i < image_height; i++)
  188824. {
  188825. png_read_row(png_ptr, *rp, png_bytep_NULL);
  188826. rp++;
  188827. }
  188828. }
  188829. }
  188830. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  188831. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  188832. /* Read the end of the PNG file. Will not read past the end of the
  188833. * file, will verify the end is accurate, and will read any comments
  188834. * or time information at the end of the file, if info is not NULL.
  188835. */
  188836. void PNGAPI
  188837. png_read_end(png_structp png_ptr, png_infop info_ptr)
  188838. {
  188839. png_byte chunk_length[4];
  188840. png_uint_32 length;
  188841. png_debug(1, "in png_read_end\n");
  188842. if(png_ptr == NULL) return;
  188843. png_crc_finish(png_ptr, 0); /* Finish off CRC from last IDAT chunk */
  188844. do
  188845. {
  188846. #ifdef PNG_USE_LOCAL_ARRAYS
  188847. PNG_CONST PNG_IHDR;
  188848. PNG_CONST PNG_IDAT;
  188849. PNG_CONST PNG_IEND;
  188850. PNG_CONST PNG_PLTE;
  188851. #if defined(PNG_READ_bKGD_SUPPORTED)
  188852. PNG_CONST PNG_bKGD;
  188853. #endif
  188854. #if defined(PNG_READ_cHRM_SUPPORTED)
  188855. PNG_CONST PNG_cHRM;
  188856. #endif
  188857. #if defined(PNG_READ_gAMA_SUPPORTED)
  188858. PNG_CONST PNG_gAMA;
  188859. #endif
  188860. #if defined(PNG_READ_hIST_SUPPORTED)
  188861. PNG_CONST PNG_hIST;
  188862. #endif
  188863. #if defined(PNG_READ_iCCP_SUPPORTED)
  188864. PNG_CONST PNG_iCCP;
  188865. #endif
  188866. #if defined(PNG_READ_iTXt_SUPPORTED)
  188867. PNG_CONST PNG_iTXt;
  188868. #endif
  188869. #if defined(PNG_READ_oFFs_SUPPORTED)
  188870. PNG_CONST PNG_oFFs;
  188871. #endif
  188872. #if defined(PNG_READ_pCAL_SUPPORTED)
  188873. PNG_CONST PNG_pCAL;
  188874. #endif
  188875. #if defined(PNG_READ_pHYs_SUPPORTED)
  188876. PNG_CONST PNG_pHYs;
  188877. #endif
  188878. #if defined(PNG_READ_sBIT_SUPPORTED)
  188879. PNG_CONST PNG_sBIT;
  188880. #endif
  188881. #if defined(PNG_READ_sCAL_SUPPORTED)
  188882. PNG_CONST PNG_sCAL;
  188883. #endif
  188884. #if defined(PNG_READ_sPLT_SUPPORTED)
  188885. PNG_CONST PNG_sPLT;
  188886. #endif
  188887. #if defined(PNG_READ_sRGB_SUPPORTED)
  188888. PNG_CONST PNG_sRGB;
  188889. #endif
  188890. #if defined(PNG_READ_tEXt_SUPPORTED)
  188891. PNG_CONST PNG_tEXt;
  188892. #endif
  188893. #if defined(PNG_READ_tIME_SUPPORTED)
  188894. PNG_CONST PNG_tIME;
  188895. #endif
  188896. #if defined(PNG_READ_tRNS_SUPPORTED)
  188897. PNG_CONST PNG_tRNS;
  188898. #endif
  188899. #if defined(PNG_READ_zTXt_SUPPORTED)
  188900. PNG_CONST PNG_zTXt;
  188901. #endif
  188902. #endif /* PNG_USE_LOCAL_ARRAYS */
  188903. png_read_data(png_ptr, chunk_length, 4);
  188904. length = png_get_uint_31(png_ptr,chunk_length);
  188905. png_reset_crc(png_ptr);
  188906. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  188907. png_debug1(0, "Reading %s chunk.\n", png_ptr->chunk_name);
  188908. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  188909. png_handle_IHDR(png_ptr, info_ptr, length);
  188910. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  188911. png_handle_IEND(png_ptr, info_ptr, length);
  188912. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  188913. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  188914. {
  188915. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188916. {
  188917. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188918. png_error(png_ptr, "Too many IDAT's found");
  188919. }
  188920. png_handle_unknown(png_ptr, info_ptr, length);
  188921. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188922. png_ptr->mode |= PNG_HAVE_PLTE;
  188923. }
  188924. #endif
  188925. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  188926. {
  188927. /* Zero length IDATs are legal after the last IDAT has been
  188928. * read, but not after other chunks have been read.
  188929. */
  188930. if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  188931. png_error(png_ptr, "Too many IDAT's found");
  188932. png_crc_finish(png_ptr, length);
  188933. }
  188934. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  188935. png_handle_PLTE(png_ptr, info_ptr, length);
  188936. #if defined(PNG_READ_bKGD_SUPPORTED)
  188937. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  188938. png_handle_bKGD(png_ptr, info_ptr, length);
  188939. #endif
  188940. #if defined(PNG_READ_cHRM_SUPPORTED)
  188941. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  188942. png_handle_cHRM(png_ptr, info_ptr, length);
  188943. #endif
  188944. #if defined(PNG_READ_gAMA_SUPPORTED)
  188945. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  188946. png_handle_gAMA(png_ptr, info_ptr, length);
  188947. #endif
  188948. #if defined(PNG_READ_hIST_SUPPORTED)
  188949. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  188950. png_handle_hIST(png_ptr, info_ptr, length);
  188951. #endif
  188952. #if defined(PNG_READ_oFFs_SUPPORTED)
  188953. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  188954. png_handle_oFFs(png_ptr, info_ptr, length);
  188955. #endif
  188956. #if defined(PNG_READ_pCAL_SUPPORTED)
  188957. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  188958. png_handle_pCAL(png_ptr, info_ptr, length);
  188959. #endif
  188960. #if defined(PNG_READ_sCAL_SUPPORTED)
  188961. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  188962. png_handle_sCAL(png_ptr, info_ptr, length);
  188963. #endif
  188964. #if defined(PNG_READ_pHYs_SUPPORTED)
  188965. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  188966. png_handle_pHYs(png_ptr, info_ptr, length);
  188967. #endif
  188968. #if defined(PNG_READ_sBIT_SUPPORTED)
  188969. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  188970. png_handle_sBIT(png_ptr, info_ptr, length);
  188971. #endif
  188972. #if defined(PNG_READ_sRGB_SUPPORTED)
  188973. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  188974. png_handle_sRGB(png_ptr, info_ptr, length);
  188975. #endif
  188976. #if defined(PNG_READ_iCCP_SUPPORTED)
  188977. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  188978. png_handle_iCCP(png_ptr, info_ptr, length);
  188979. #endif
  188980. #if defined(PNG_READ_sPLT_SUPPORTED)
  188981. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  188982. png_handle_sPLT(png_ptr, info_ptr, length);
  188983. #endif
  188984. #if defined(PNG_READ_tEXt_SUPPORTED)
  188985. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  188986. png_handle_tEXt(png_ptr, info_ptr, length);
  188987. #endif
  188988. #if defined(PNG_READ_tIME_SUPPORTED)
  188989. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  188990. png_handle_tIME(png_ptr, info_ptr, length);
  188991. #endif
  188992. #if defined(PNG_READ_tRNS_SUPPORTED)
  188993. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  188994. png_handle_tRNS(png_ptr, info_ptr, length);
  188995. #endif
  188996. #if defined(PNG_READ_zTXt_SUPPORTED)
  188997. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  188998. png_handle_zTXt(png_ptr, info_ptr, length);
  188999. #endif
  189000. #if defined(PNG_READ_iTXt_SUPPORTED)
  189001. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  189002. png_handle_iTXt(png_ptr, info_ptr, length);
  189003. #endif
  189004. else
  189005. png_handle_unknown(png_ptr, info_ptr, length);
  189006. } while (!(png_ptr->mode & PNG_HAVE_IEND));
  189007. }
  189008. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  189009. /* free all memory used by the read */
  189010. void PNGAPI
  189011. png_destroy_read_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr,
  189012. png_infopp end_info_ptr_ptr)
  189013. {
  189014. png_structp png_ptr = NULL;
  189015. png_infop info_ptr = NULL, end_info_ptr = NULL;
  189016. #ifdef PNG_USER_MEM_SUPPORTED
  189017. png_free_ptr free_fn;
  189018. png_voidp mem_ptr;
  189019. #endif
  189020. png_debug(1, "in png_destroy_read_struct\n");
  189021. if (png_ptr_ptr != NULL)
  189022. png_ptr = *png_ptr_ptr;
  189023. if (info_ptr_ptr != NULL)
  189024. info_ptr = *info_ptr_ptr;
  189025. if (end_info_ptr_ptr != NULL)
  189026. end_info_ptr = *end_info_ptr_ptr;
  189027. #ifdef PNG_USER_MEM_SUPPORTED
  189028. free_fn = png_ptr->free_fn;
  189029. mem_ptr = png_ptr->mem_ptr;
  189030. #endif
  189031. png_read_destroy(png_ptr, info_ptr, end_info_ptr);
  189032. if (info_ptr != NULL)
  189033. {
  189034. #if defined(PNG_TEXT_SUPPORTED)
  189035. png_free_data(png_ptr, info_ptr, PNG_FREE_TEXT, -1);
  189036. #endif
  189037. #ifdef PNG_USER_MEM_SUPPORTED
  189038. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  189039. (png_voidp)mem_ptr);
  189040. #else
  189041. png_destroy_struct((png_voidp)info_ptr);
  189042. #endif
  189043. *info_ptr_ptr = NULL;
  189044. }
  189045. if (end_info_ptr != NULL)
  189046. {
  189047. #if defined(PNG_READ_TEXT_SUPPORTED)
  189048. png_free_data(png_ptr, end_info_ptr, PNG_FREE_TEXT, -1);
  189049. #endif
  189050. #ifdef PNG_USER_MEM_SUPPORTED
  189051. png_destroy_struct_2((png_voidp)end_info_ptr, (png_free_ptr)free_fn,
  189052. (png_voidp)mem_ptr);
  189053. #else
  189054. png_destroy_struct((png_voidp)end_info_ptr);
  189055. #endif
  189056. *end_info_ptr_ptr = NULL;
  189057. }
  189058. if (png_ptr != NULL)
  189059. {
  189060. #ifdef PNG_USER_MEM_SUPPORTED
  189061. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  189062. (png_voidp)mem_ptr);
  189063. #else
  189064. png_destroy_struct((png_voidp)png_ptr);
  189065. #endif
  189066. *png_ptr_ptr = NULL;
  189067. }
  189068. }
  189069. /* free all memory used by the read (old method) */
  189070. void /* PRIVATE */
  189071. png_read_destroy(png_structp png_ptr, png_infop info_ptr, png_infop end_info_ptr)
  189072. {
  189073. #ifdef PNG_SETJMP_SUPPORTED
  189074. jmp_buf tmp_jmp;
  189075. #endif
  189076. png_error_ptr error_fn;
  189077. png_error_ptr warning_fn;
  189078. png_voidp error_ptr;
  189079. #ifdef PNG_USER_MEM_SUPPORTED
  189080. png_free_ptr free_fn;
  189081. #endif
  189082. png_debug(1, "in png_read_destroy\n");
  189083. if (info_ptr != NULL)
  189084. png_info_destroy(png_ptr, info_ptr);
  189085. if (end_info_ptr != NULL)
  189086. png_info_destroy(png_ptr, end_info_ptr);
  189087. png_free(png_ptr, png_ptr->zbuf);
  189088. png_free(png_ptr, png_ptr->big_row_buf);
  189089. png_free(png_ptr, png_ptr->prev_row);
  189090. #if defined(PNG_READ_DITHER_SUPPORTED)
  189091. png_free(png_ptr, png_ptr->palette_lookup);
  189092. png_free(png_ptr, png_ptr->dither_index);
  189093. #endif
  189094. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189095. png_free(png_ptr, png_ptr->gamma_table);
  189096. #endif
  189097. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189098. png_free(png_ptr, png_ptr->gamma_from_1);
  189099. png_free(png_ptr, png_ptr->gamma_to_1);
  189100. #endif
  189101. #ifdef PNG_FREE_ME_SUPPORTED
  189102. if (png_ptr->free_me & PNG_FREE_PLTE)
  189103. png_zfree(png_ptr, png_ptr->palette);
  189104. png_ptr->free_me &= ~PNG_FREE_PLTE;
  189105. #else
  189106. if (png_ptr->flags & PNG_FLAG_FREE_PLTE)
  189107. png_zfree(png_ptr, png_ptr->palette);
  189108. png_ptr->flags &= ~PNG_FLAG_FREE_PLTE;
  189109. #endif
  189110. #if defined(PNG_tRNS_SUPPORTED) || \
  189111. defined(PNG_READ_EXPAND_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  189112. #ifdef PNG_FREE_ME_SUPPORTED
  189113. if (png_ptr->free_me & PNG_FREE_TRNS)
  189114. png_free(png_ptr, png_ptr->trans);
  189115. png_ptr->free_me &= ~PNG_FREE_TRNS;
  189116. #else
  189117. if (png_ptr->flags & PNG_FLAG_FREE_TRNS)
  189118. png_free(png_ptr, png_ptr->trans);
  189119. png_ptr->flags &= ~PNG_FLAG_FREE_TRNS;
  189120. #endif
  189121. #endif
  189122. #if defined(PNG_READ_hIST_SUPPORTED)
  189123. #ifdef PNG_FREE_ME_SUPPORTED
  189124. if (png_ptr->free_me & PNG_FREE_HIST)
  189125. png_free(png_ptr, png_ptr->hist);
  189126. png_ptr->free_me &= ~PNG_FREE_HIST;
  189127. #else
  189128. if (png_ptr->flags & PNG_FLAG_FREE_HIST)
  189129. png_free(png_ptr, png_ptr->hist);
  189130. png_ptr->flags &= ~PNG_FLAG_FREE_HIST;
  189131. #endif
  189132. #endif
  189133. #if defined(PNG_READ_GAMMA_SUPPORTED)
  189134. if (png_ptr->gamma_16_table != NULL)
  189135. {
  189136. int i;
  189137. int istop = (1 << (8 - png_ptr->gamma_shift));
  189138. for (i = 0; i < istop; i++)
  189139. {
  189140. png_free(png_ptr, png_ptr->gamma_16_table[i]);
  189141. }
  189142. png_free(png_ptr, png_ptr->gamma_16_table);
  189143. }
  189144. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  189145. if (png_ptr->gamma_16_from_1 != NULL)
  189146. {
  189147. int i;
  189148. int istop = (1 << (8 - png_ptr->gamma_shift));
  189149. for (i = 0; i < istop; i++)
  189150. {
  189151. png_free(png_ptr, png_ptr->gamma_16_from_1[i]);
  189152. }
  189153. png_free(png_ptr, png_ptr->gamma_16_from_1);
  189154. }
  189155. if (png_ptr->gamma_16_to_1 != NULL)
  189156. {
  189157. int i;
  189158. int istop = (1 << (8 - png_ptr->gamma_shift));
  189159. for (i = 0; i < istop; i++)
  189160. {
  189161. png_free(png_ptr, png_ptr->gamma_16_to_1[i]);
  189162. }
  189163. png_free(png_ptr, png_ptr->gamma_16_to_1);
  189164. }
  189165. #endif
  189166. #endif
  189167. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  189168. png_free(png_ptr, png_ptr->time_buffer);
  189169. #endif
  189170. inflateEnd(&png_ptr->zstream);
  189171. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  189172. png_free(png_ptr, png_ptr->save_buffer);
  189173. #endif
  189174. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  189175. #ifdef PNG_TEXT_SUPPORTED
  189176. png_free(png_ptr, png_ptr->current_text);
  189177. #endif /* PNG_TEXT_SUPPORTED */
  189178. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  189179. /* Save the important info out of the png_struct, in case it is
  189180. * being used again.
  189181. */
  189182. #ifdef PNG_SETJMP_SUPPORTED
  189183. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  189184. #endif
  189185. error_fn = png_ptr->error_fn;
  189186. warning_fn = png_ptr->warning_fn;
  189187. error_ptr = png_ptr->error_ptr;
  189188. #ifdef PNG_USER_MEM_SUPPORTED
  189189. free_fn = png_ptr->free_fn;
  189190. #endif
  189191. png_memset(png_ptr, 0, png_sizeof (png_struct));
  189192. png_ptr->error_fn = error_fn;
  189193. png_ptr->warning_fn = warning_fn;
  189194. png_ptr->error_ptr = error_ptr;
  189195. #ifdef PNG_USER_MEM_SUPPORTED
  189196. png_ptr->free_fn = free_fn;
  189197. #endif
  189198. #ifdef PNG_SETJMP_SUPPORTED
  189199. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  189200. #endif
  189201. }
  189202. void PNGAPI
  189203. png_set_read_status_fn(png_structp png_ptr, png_read_status_ptr read_row_fn)
  189204. {
  189205. if(png_ptr == NULL) return;
  189206. png_ptr->read_row_fn = read_row_fn;
  189207. }
  189208. #ifndef PNG_NO_SEQUENTIAL_READ_SUPPORTED
  189209. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  189210. void PNGAPI
  189211. png_read_png(png_structp png_ptr, png_infop info_ptr,
  189212. int transforms,
  189213. voidp params)
  189214. {
  189215. int row;
  189216. if(png_ptr == NULL) return;
  189217. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  189218. /* invert the alpha channel from opacity to transparency
  189219. */
  189220. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  189221. png_set_invert_alpha(png_ptr);
  189222. #endif
  189223. /* png_read_info() gives us all of the information from the
  189224. * PNG file before the first IDAT (image data chunk).
  189225. */
  189226. png_read_info(png_ptr, info_ptr);
  189227. if (info_ptr->height > PNG_UINT_32_MAX/png_sizeof(png_bytep))
  189228. png_error(png_ptr,"Image is too high to process with png_read_png()");
  189229. /* -------------- image transformations start here ------------------- */
  189230. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  189231. /* tell libpng to strip 16 bit/color files down to 8 bits per color
  189232. */
  189233. if (transforms & PNG_TRANSFORM_STRIP_16)
  189234. png_set_strip_16(png_ptr);
  189235. #endif
  189236. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  189237. /* Strip alpha bytes from the input data without combining with
  189238. * the background (not recommended).
  189239. */
  189240. if (transforms & PNG_TRANSFORM_STRIP_ALPHA)
  189241. png_set_strip_alpha(png_ptr);
  189242. #endif
  189243. #if defined(PNG_READ_PACK_SUPPORTED) && !defined(PNG_READ_EXPAND_SUPPORTED)
  189244. /* Extract multiple pixels with bit depths of 1, 2, or 4 from a single
  189245. * byte into separate bytes (useful for paletted and grayscale images).
  189246. */
  189247. if (transforms & PNG_TRANSFORM_PACKING)
  189248. png_set_packing(png_ptr);
  189249. #endif
  189250. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  189251. /* Change the order of packed pixels to least significant bit first
  189252. * (not useful if you are using png_set_packing).
  189253. */
  189254. if (transforms & PNG_TRANSFORM_PACKSWAP)
  189255. png_set_packswap(png_ptr);
  189256. #endif
  189257. #if defined(PNG_READ_EXPAND_SUPPORTED)
  189258. /* Expand paletted colors into true RGB triplets
  189259. * Expand grayscale images to full 8 bits from 1, 2, or 4 bits/pixel
  189260. * Expand paletted or RGB images with transparency to full alpha
  189261. * channels so the data will be available as RGBA quartets.
  189262. */
  189263. if (transforms & PNG_TRANSFORM_EXPAND)
  189264. if ((png_ptr->bit_depth < 8) ||
  189265. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE) ||
  189266. (png_get_valid(png_ptr, info_ptr, PNG_INFO_tRNS)))
  189267. png_set_expand(png_ptr);
  189268. #endif
  189269. /* We don't handle background color or gamma transformation or dithering.
  189270. */
  189271. #if defined(PNG_READ_INVERT_SUPPORTED)
  189272. /* invert monochrome files to have 0 as white and 1 as black
  189273. */
  189274. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  189275. png_set_invert_mono(png_ptr);
  189276. #endif
  189277. #if defined(PNG_READ_SHIFT_SUPPORTED)
  189278. /* If you want to shift the pixel values from the range [0,255] or
  189279. * [0,65535] to the original [0,7] or [0,31], or whatever range the
  189280. * colors were originally in:
  189281. */
  189282. if ((transforms & PNG_TRANSFORM_SHIFT)
  189283. && png_get_valid(png_ptr, info_ptr, PNG_INFO_sBIT))
  189284. {
  189285. png_color_8p sig_bit;
  189286. png_get_sBIT(png_ptr, info_ptr, &sig_bit);
  189287. png_set_shift(png_ptr, sig_bit);
  189288. }
  189289. #endif
  189290. #if defined(PNG_READ_BGR_SUPPORTED)
  189291. /* flip the RGB pixels to BGR (or RGBA to BGRA)
  189292. */
  189293. if (transforms & PNG_TRANSFORM_BGR)
  189294. png_set_bgr(png_ptr);
  189295. #endif
  189296. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  189297. /* swap the RGBA or GA data to ARGB or AG (or BGRA to ABGR)
  189298. */
  189299. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  189300. png_set_swap_alpha(png_ptr);
  189301. #endif
  189302. #if defined(PNG_READ_SWAP_SUPPORTED)
  189303. /* swap bytes of 16 bit files to least significant byte first
  189304. */
  189305. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  189306. png_set_swap(png_ptr);
  189307. #endif
  189308. /* We don't handle adding filler bytes */
  189309. /* Optional call to gamma correct and add the background to the palette
  189310. * and update info structure. REQUIRED if you are expecting libpng to
  189311. * update the palette for you (i.e., you selected such a transform above).
  189312. */
  189313. png_read_update_info(png_ptr, info_ptr);
  189314. /* -------------- image transformations end here ------------------- */
  189315. #ifdef PNG_FREE_ME_SUPPORTED
  189316. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  189317. #endif
  189318. if(info_ptr->row_pointers == NULL)
  189319. {
  189320. info_ptr->row_pointers = (png_bytepp)png_malloc(png_ptr,
  189321. info_ptr->height * png_sizeof(png_bytep));
  189322. #ifdef PNG_FREE_ME_SUPPORTED
  189323. info_ptr->free_me |= PNG_FREE_ROWS;
  189324. #endif
  189325. for (row = 0; row < (int)info_ptr->height; row++)
  189326. {
  189327. info_ptr->row_pointers[row] = (png_bytep)png_malloc(png_ptr,
  189328. png_get_rowbytes(png_ptr, info_ptr));
  189329. }
  189330. }
  189331. png_read_image(png_ptr, info_ptr->row_pointers);
  189332. info_ptr->valid |= PNG_INFO_IDAT;
  189333. /* read rest of file, and get additional chunks in info_ptr - REQUIRED */
  189334. png_read_end(png_ptr, info_ptr);
  189335. transforms = transforms; /* quiet compiler warnings */
  189336. params = params;
  189337. }
  189338. #endif /* PNG_INFO_IMAGE_SUPPORTED */
  189339. #endif /* PNG_NO_SEQUENTIAL_READ_SUPPORTED */
  189340. #endif /* PNG_READ_SUPPORTED */
  189341. /********* End of inlined file: pngread.c *********/
  189342. /********* Start of inlined file: pngpread.c *********/
  189343. /* pngpread.c - read a png file in push mode
  189344. *
  189345. * Last changed in libpng 1.2.21 October 4, 2007
  189346. * For conditions of distribution and use, see copyright notice in png.h
  189347. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  189348. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  189349. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  189350. */
  189351. #define PNG_INTERNAL
  189352. #ifdef PNG_PROGRESSIVE_READ_SUPPORTED
  189353. /* push model modes */
  189354. #define PNG_READ_SIG_MODE 0
  189355. #define PNG_READ_CHUNK_MODE 1
  189356. #define PNG_READ_IDAT_MODE 2
  189357. #define PNG_SKIP_MODE 3
  189358. #define PNG_READ_tEXt_MODE 4
  189359. #define PNG_READ_zTXt_MODE 5
  189360. #define PNG_READ_DONE_MODE 6
  189361. #define PNG_READ_iTXt_MODE 7
  189362. #define PNG_ERROR_MODE 8
  189363. void PNGAPI
  189364. png_process_data(png_structp png_ptr, png_infop info_ptr,
  189365. png_bytep buffer, png_size_t buffer_size)
  189366. {
  189367. if(png_ptr == NULL) return;
  189368. png_push_restore_buffer(png_ptr, buffer, buffer_size);
  189369. while (png_ptr->buffer_size)
  189370. {
  189371. png_process_some_data(png_ptr, info_ptr);
  189372. }
  189373. }
  189374. /* What we do with the incoming data depends on what we were previously
  189375. * doing before we ran out of data...
  189376. */
  189377. void /* PRIVATE */
  189378. png_process_some_data(png_structp png_ptr, png_infop info_ptr)
  189379. {
  189380. if(png_ptr == NULL) return;
  189381. switch (png_ptr->process_mode)
  189382. {
  189383. case PNG_READ_SIG_MODE:
  189384. {
  189385. png_push_read_sig(png_ptr, info_ptr);
  189386. break;
  189387. }
  189388. case PNG_READ_CHUNK_MODE:
  189389. {
  189390. png_push_read_chunk(png_ptr, info_ptr);
  189391. break;
  189392. }
  189393. case PNG_READ_IDAT_MODE:
  189394. {
  189395. png_push_read_IDAT(png_ptr);
  189396. break;
  189397. }
  189398. #if defined(PNG_READ_tEXt_SUPPORTED)
  189399. case PNG_READ_tEXt_MODE:
  189400. {
  189401. png_push_read_tEXt(png_ptr, info_ptr);
  189402. break;
  189403. }
  189404. #endif
  189405. #if defined(PNG_READ_zTXt_SUPPORTED)
  189406. case PNG_READ_zTXt_MODE:
  189407. {
  189408. png_push_read_zTXt(png_ptr, info_ptr);
  189409. break;
  189410. }
  189411. #endif
  189412. #if defined(PNG_READ_iTXt_SUPPORTED)
  189413. case PNG_READ_iTXt_MODE:
  189414. {
  189415. png_push_read_iTXt(png_ptr, info_ptr);
  189416. break;
  189417. }
  189418. #endif
  189419. case PNG_SKIP_MODE:
  189420. {
  189421. png_push_crc_finish(png_ptr);
  189422. break;
  189423. }
  189424. default:
  189425. {
  189426. png_ptr->buffer_size = 0;
  189427. break;
  189428. }
  189429. }
  189430. }
  189431. /* Read any remaining signature bytes from the stream and compare them with
  189432. * the correct PNG signature. It is possible that this routine is called
  189433. * with bytes already read from the signature, either because they have been
  189434. * checked by the calling application, or because of multiple calls to this
  189435. * routine.
  189436. */
  189437. void /* PRIVATE */
  189438. png_push_read_sig(png_structp png_ptr, png_infop info_ptr)
  189439. {
  189440. png_size_t num_checked = png_ptr->sig_bytes,
  189441. num_to_check = 8 - num_checked;
  189442. if (png_ptr->buffer_size < num_to_check)
  189443. {
  189444. num_to_check = png_ptr->buffer_size;
  189445. }
  189446. png_push_fill_buffer(png_ptr, &(info_ptr->signature[num_checked]),
  189447. num_to_check);
  189448. png_ptr->sig_bytes = (png_byte)(png_ptr->sig_bytes+num_to_check);
  189449. if (png_sig_cmp(info_ptr->signature, num_checked, num_to_check))
  189450. {
  189451. if (num_checked < 4 &&
  189452. png_sig_cmp(info_ptr->signature, num_checked, num_to_check - 4))
  189453. png_error(png_ptr, "Not a PNG file");
  189454. else
  189455. png_error(png_ptr, "PNG file corrupted by ASCII conversion");
  189456. }
  189457. else
  189458. {
  189459. if (png_ptr->sig_bytes >= 8)
  189460. {
  189461. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189462. }
  189463. }
  189464. }
  189465. void /* PRIVATE */
  189466. png_push_read_chunk(png_structp png_ptr, png_infop info_ptr)
  189467. {
  189468. #ifdef PNG_USE_LOCAL_ARRAYS
  189469. PNG_CONST PNG_IHDR;
  189470. PNG_CONST PNG_IDAT;
  189471. PNG_CONST PNG_IEND;
  189472. PNG_CONST PNG_PLTE;
  189473. #if defined(PNG_READ_bKGD_SUPPORTED)
  189474. PNG_CONST PNG_bKGD;
  189475. #endif
  189476. #if defined(PNG_READ_cHRM_SUPPORTED)
  189477. PNG_CONST PNG_cHRM;
  189478. #endif
  189479. #if defined(PNG_READ_gAMA_SUPPORTED)
  189480. PNG_CONST PNG_gAMA;
  189481. #endif
  189482. #if defined(PNG_READ_hIST_SUPPORTED)
  189483. PNG_CONST PNG_hIST;
  189484. #endif
  189485. #if defined(PNG_READ_iCCP_SUPPORTED)
  189486. PNG_CONST PNG_iCCP;
  189487. #endif
  189488. #if defined(PNG_READ_iTXt_SUPPORTED)
  189489. PNG_CONST PNG_iTXt;
  189490. #endif
  189491. #if defined(PNG_READ_oFFs_SUPPORTED)
  189492. PNG_CONST PNG_oFFs;
  189493. #endif
  189494. #if defined(PNG_READ_pCAL_SUPPORTED)
  189495. PNG_CONST PNG_pCAL;
  189496. #endif
  189497. #if defined(PNG_READ_pHYs_SUPPORTED)
  189498. PNG_CONST PNG_pHYs;
  189499. #endif
  189500. #if defined(PNG_READ_sBIT_SUPPORTED)
  189501. PNG_CONST PNG_sBIT;
  189502. #endif
  189503. #if defined(PNG_READ_sCAL_SUPPORTED)
  189504. PNG_CONST PNG_sCAL;
  189505. #endif
  189506. #if defined(PNG_READ_sRGB_SUPPORTED)
  189507. PNG_CONST PNG_sRGB;
  189508. #endif
  189509. #if defined(PNG_READ_sPLT_SUPPORTED)
  189510. PNG_CONST PNG_sPLT;
  189511. #endif
  189512. #if defined(PNG_READ_tEXt_SUPPORTED)
  189513. PNG_CONST PNG_tEXt;
  189514. #endif
  189515. #if defined(PNG_READ_tIME_SUPPORTED)
  189516. PNG_CONST PNG_tIME;
  189517. #endif
  189518. #if defined(PNG_READ_tRNS_SUPPORTED)
  189519. PNG_CONST PNG_tRNS;
  189520. #endif
  189521. #if defined(PNG_READ_zTXt_SUPPORTED)
  189522. PNG_CONST PNG_zTXt;
  189523. #endif
  189524. #endif /* PNG_USE_LOCAL_ARRAYS */
  189525. /* First we make sure we have enough data for the 4 byte chunk name
  189526. * and the 4 byte chunk length before proceeding with decoding the
  189527. * chunk data. To fully decode each of these chunks, we also make
  189528. * sure we have enough data in the buffer for the 4 byte CRC at the
  189529. * end of every chunk (except IDAT, which is handled separately).
  189530. */
  189531. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189532. {
  189533. png_byte chunk_length[4];
  189534. if (png_ptr->buffer_size < 8)
  189535. {
  189536. png_push_save_buffer(png_ptr);
  189537. return;
  189538. }
  189539. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189540. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189541. png_reset_crc(png_ptr);
  189542. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189543. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189544. }
  189545. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189546. if(png_ptr->mode & PNG_AFTER_IDAT)
  189547. png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
  189548. if (!png_memcmp(png_ptr->chunk_name, png_IHDR, 4))
  189549. {
  189550. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189551. {
  189552. png_push_save_buffer(png_ptr);
  189553. return;
  189554. }
  189555. png_handle_IHDR(png_ptr, info_ptr, png_ptr->push_length);
  189556. }
  189557. else if (!png_memcmp(png_ptr->chunk_name, png_IEND, 4))
  189558. {
  189559. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189560. {
  189561. png_push_save_buffer(png_ptr);
  189562. return;
  189563. }
  189564. png_handle_IEND(png_ptr, info_ptr, png_ptr->push_length);
  189565. png_ptr->process_mode = PNG_READ_DONE_MODE;
  189566. png_push_have_end(png_ptr, info_ptr);
  189567. }
  189568. #ifdef PNG_HANDLE_AS_UNKNOWN_SUPPORTED
  189569. else if (png_handle_as_unknown(png_ptr, png_ptr->chunk_name))
  189570. {
  189571. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189572. {
  189573. png_push_save_buffer(png_ptr);
  189574. return;
  189575. }
  189576. if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189577. png_ptr->mode |= PNG_HAVE_IDAT;
  189578. png_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  189579. if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  189580. png_ptr->mode |= PNG_HAVE_PLTE;
  189581. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189582. {
  189583. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189584. png_error(png_ptr, "Missing IHDR before IDAT");
  189585. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  189586. !(png_ptr->mode & PNG_HAVE_PLTE))
  189587. png_error(png_ptr, "Missing PLTE before IDAT");
  189588. }
  189589. }
  189590. #endif
  189591. else if (!png_memcmp(png_ptr->chunk_name, png_PLTE, 4))
  189592. {
  189593. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189594. {
  189595. png_push_save_buffer(png_ptr);
  189596. return;
  189597. }
  189598. png_handle_PLTE(png_ptr, info_ptr, png_ptr->push_length);
  189599. }
  189600. else if (!png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189601. {
  189602. /* If we reach an IDAT chunk, this means we have read all of the
  189603. * header chunks, and we can start reading the image (or if this
  189604. * is called after the image has been read - we have an error).
  189605. */
  189606. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  189607. png_error(png_ptr, "Missing IHDR before IDAT");
  189608. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  189609. !(png_ptr->mode & PNG_HAVE_PLTE))
  189610. png_error(png_ptr, "Missing PLTE before IDAT");
  189611. if (png_ptr->mode & PNG_HAVE_IDAT)
  189612. {
  189613. if (!(png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT))
  189614. if (png_ptr->push_length == 0)
  189615. return;
  189616. if (png_ptr->mode & PNG_AFTER_IDAT)
  189617. png_error(png_ptr, "Too many IDAT's found");
  189618. }
  189619. png_ptr->idat_size = png_ptr->push_length;
  189620. png_ptr->mode |= PNG_HAVE_IDAT;
  189621. png_ptr->process_mode = PNG_READ_IDAT_MODE;
  189622. png_push_have_info(png_ptr, info_ptr);
  189623. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  189624. png_ptr->zstream.next_out = png_ptr->row_buf;
  189625. return;
  189626. }
  189627. #if defined(PNG_READ_gAMA_SUPPORTED)
  189628. else if (!png_memcmp(png_ptr->chunk_name, png_gAMA, 4))
  189629. {
  189630. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189631. {
  189632. png_push_save_buffer(png_ptr);
  189633. return;
  189634. }
  189635. png_handle_gAMA(png_ptr, info_ptr, png_ptr->push_length);
  189636. }
  189637. #endif
  189638. #if defined(PNG_READ_sBIT_SUPPORTED)
  189639. else if (!png_memcmp(png_ptr->chunk_name, png_sBIT, 4))
  189640. {
  189641. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189642. {
  189643. png_push_save_buffer(png_ptr);
  189644. return;
  189645. }
  189646. png_handle_sBIT(png_ptr, info_ptr, png_ptr->push_length);
  189647. }
  189648. #endif
  189649. #if defined(PNG_READ_cHRM_SUPPORTED)
  189650. else if (!png_memcmp(png_ptr->chunk_name, png_cHRM, 4))
  189651. {
  189652. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189653. {
  189654. png_push_save_buffer(png_ptr);
  189655. return;
  189656. }
  189657. png_handle_cHRM(png_ptr, info_ptr, png_ptr->push_length);
  189658. }
  189659. #endif
  189660. #if defined(PNG_READ_sRGB_SUPPORTED)
  189661. else if (!png_memcmp(png_ptr->chunk_name, png_sRGB, 4))
  189662. {
  189663. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189664. {
  189665. png_push_save_buffer(png_ptr);
  189666. return;
  189667. }
  189668. png_handle_sRGB(png_ptr, info_ptr, png_ptr->push_length);
  189669. }
  189670. #endif
  189671. #if defined(PNG_READ_iCCP_SUPPORTED)
  189672. else if (!png_memcmp(png_ptr->chunk_name, png_iCCP, 4))
  189673. {
  189674. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189675. {
  189676. png_push_save_buffer(png_ptr);
  189677. return;
  189678. }
  189679. png_handle_iCCP(png_ptr, info_ptr, png_ptr->push_length);
  189680. }
  189681. #endif
  189682. #if defined(PNG_READ_sPLT_SUPPORTED)
  189683. else if (!png_memcmp(png_ptr->chunk_name, png_sPLT, 4))
  189684. {
  189685. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189686. {
  189687. png_push_save_buffer(png_ptr);
  189688. return;
  189689. }
  189690. png_handle_sPLT(png_ptr, info_ptr, png_ptr->push_length);
  189691. }
  189692. #endif
  189693. #if defined(PNG_READ_tRNS_SUPPORTED)
  189694. else if (!png_memcmp(png_ptr->chunk_name, png_tRNS, 4))
  189695. {
  189696. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189697. {
  189698. png_push_save_buffer(png_ptr);
  189699. return;
  189700. }
  189701. png_handle_tRNS(png_ptr, info_ptr, png_ptr->push_length);
  189702. }
  189703. #endif
  189704. #if defined(PNG_READ_bKGD_SUPPORTED)
  189705. else if (!png_memcmp(png_ptr->chunk_name, png_bKGD, 4))
  189706. {
  189707. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189708. {
  189709. png_push_save_buffer(png_ptr);
  189710. return;
  189711. }
  189712. png_handle_bKGD(png_ptr, info_ptr, png_ptr->push_length);
  189713. }
  189714. #endif
  189715. #if defined(PNG_READ_hIST_SUPPORTED)
  189716. else if (!png_memcmp(png_ptr->chunk_name, png_hIST, 4))
  189717. {
  189718. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189719. {
  189720. png_push_save_buffer(png_ptr);
  189721. return;
  189722. }
  189723. png_handle_hIST(png_ptr, info_ptr, png_ptr->push_length);
  189724. }
  189725. #endif
  189726. #if defined(PNG_READ_pHYs_SUPPORTED)
  189727. else if (!png_memcmp(png_ptr->chunk_name, png_pHYs, 4))
  189728. {
  189729. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189730. {
  189731. png_push_save_buffer(png_ptr);
  189732. return;
  189733. }
  189734. png_handle_pHYs(png_ptr, info_ptr, png_ptr->push_length);
  189735. }
  189736. #endif
  189737. #if defined(PNG_READ_oFFs_SUPPORTED)
  189738. else if (!png_memcmp(png_ptr->chunk_name, png_oFFs, 4))
  189739. {
  189740. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189741. {
  189742. png_push_save_buffer(png_ptr);
  189743. return;
  189744. }
  189745. png_handle_oFFs(png_ptr, info_ptr, png_ptr->push_length);
  189746. }
  189747. #endif
  189748. #if defined(PNG_READ_pCAL_SUPPORTED)
  189749. else if (!png_memcmp(png_ptr->chunk_name, png_pCAL, 4))
  189750. {
  189751. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189752. {
  189753. png_push_save_buffer(png_ptr);
  189754. return;
  189755. }
  189756. png_handle_pCAL(png_ptr, info_ptr, png_ptr->push_length);
  189757. }
  189758. #endif
  189759. #if defined(PNG_READ_sCAL_SUPPORTED)
  189760. else if (!png_memcmp(png_ptr->chunk_name, png_sCAL, 4))
  189761. {
  189762. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189763. {
  189764. png_push_save_buffer(png_ptr);
  189765. return;
  189766. }
  189767. png_handle_sCAL(png_ptr, info_ptr, png_ptr->push_length);
  189768. }
  189769. #endif
  189770. #if defined(PNG_READ_tIME_SUPPORTED)
  189771. else if (!png_memcmp(png_ptr->chunk_name, png_tIME, 4))
  189772. {
  189773. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189774. {
  189775. png_push_save_buffer(png_ptr);
  189776. return;
  189777. }
  189778. png_handle_tIME(png_ptr, info_ptr, png_ptr->push_length);
  189779. }
  189780. #endif
  189781. #if defined(PNG_READ_tEXt_SUPPORTED)
  189782. else if (!png_memcmp(png_ptr->chunk_name, png_tEXt, 4))
  189783. {
  189784. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189785. {
  189786. png_push_save_buffer(png_ptr);
  189787. return;
  189788. }
  189789. png_push_handle_tEXt(png_ptr, info_ptr, png_ptr->push_length);
  189790. }
  189791. #endif
  189792. #if defined(PNG_READ_zTXt_SUPPORTED)
  189793. else if (!png_memcmp(png_ptr->chunk_name, png_zTXt, 4))
  189794. {
  189795. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189796. {
  189797. png_push_save_buffer(png_ptr);
  189798. return;
  189799. }
  189800. png_push_handle_zTXt(png_ptr, info_ptr, png_ptr->push_length);
  189801. }
  189802. #endif
  189803. #if defined(PNG_READ_iTXt_SUPPORTED)
  189804. else if (!png_memcmp(png_ptr->chunk_name, png_iTXt, 4))
  189805. {
  189806. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189807. {
  189808. png_push_save_buffer(png_ptr);
  189809. return;
  189810. }
  189811. png_push_handle_iTXt(png_ptr, info_ptr, png_ptr->push_length);
  189812. }
  189813. #endif
  189814. else
  189815. {
  189816. if (png_ptr->push_length + 4 > png_ptr->buffer_size)
  189817. {
  189818. png_push_save_buffer(png_ptr);
  189819. return;
  189820. }
  189821. png_push_handle_unknown(png_ptr, info_ptr, png_ptr->push_length);
  189822. }
  189823. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  189824. }
  189825. void /* PRIVATE */
  189826. png_push_crc_skip(png_structp png_ptr, png_uint_32 skip)
  189827. {
  189828. png_ptr->process_mode = PNG_SKIP_MODE;
  189829. png_ptr->skip_length = skip;
  189830. }
  189831. void /* PRIVATE */
  189832. png_push_crc_finish(png_structp png_ptr)
  189833. {
  189834. if (png_ptr->skip_length && png_ptr->save_buffer_size)
  189835. {
  189836. png_size_t save_size;
  189837. if (png_ptr->skip_length < (png_uint_32)png_ptr->save_buffer_size)
  189838. save_size = (png_size_t)png_ptr->skip_length;
  189839. else
  189840. save_size = png_ptr->save_buffer_size;
  189841. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  189842. png_ptr->skip_length -= save_size;
  189843. png_ptr->buffer_size -= save_size;
  189844. png_ptr->save_buffer_size -= save_size;
  189845. png_ptr->save_buffer_ptr += save_size;
  189846. }
  189847. if (png_ptr->skip_length && png_ptr->current_buffer_size)
  189848. {
  189849. png_size_t save_size;
  189850. if (png_ptr->skip_length < (png_uint_32)png_ptr->current_buffer_size)
  189851. save_size = (png_size_t)png_ptr->skip_length;
  189852. else
  189853. save_size = png_ptr->current_buffer_size;
  189854. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  189855. png_ptr->skip_length -= save_size;
  189856. png_ptr->buffer_size -= save_size;
  189857. png_ptr->current_buffer_size -= save_size;
  189858. png_ptr->current_buffer_ptr += save_size;
  189859. }
  189860. if (!png_ptr->skip_length)
  189861. {
  189862. if (png_ptr->buffer_size < 4)
  189863. {
  189864. png_push_save_buffer(png_ptr);
  189865. return;
  189866. }
  189867. png_crc_finish(png_ptr, 0);
  189868. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189869. }
  189870. }
  189871. void PNGAPI
  189872. png_push_fill_buffer(png_structp png_ptr, png_bytep buffer, png_size_t length)
  189873. {
  189874. png_bytep ptr;
  189875. if(png_ptr == NULL) return;
  189876. ptr = buffer;
  189877. if (png_ptr->save_buffer_size)
  189878. {
  189879. png_size_t save_size;
  189880. if (length < png_ptr->save_buffer_size)
  189881. save_size = length;
  189882. else
  189883. save_size = png_ptr->save_buffer_size;
  189884. png_memcpy(ptr, png_ptr->save_buffer_ptr, save_size);
  189885. length -= save_size;
  189886. ptr += save_size;
  189887. png_ptr->buffer_size -= save_size;
  189888. png_ptr->save_buffer_size -= save_size;
  189889. png_ptr->save_buffer_ptr += save_size;
  189890. }
  189891. if (length && png_ptr->current_buffer_size)
  189892. {
  189893. png_size_t save_size;
  189894. if (length < png_ptr->current_buffer_size)
  189895. save_size = length;
  189896. else
  189897. save_size = png_ptr->current_buffer_size;
  189898. png_memcpy(ptr, png_ptr->current_buffer_ptr, save_size);
  189899. png_ptr->buffer_size -= save_size;
  189900. png_ptr->current_buffer_size -= save_size;
  189901. png_ptr->current_buffer_ptr += save_size;
  189902. }
  189903. }
  189904. void /* PRIVATE */
  189905. png_push_save_buffer(png_structp png_ptr)
  189906. {
  189907. if (png_ptr->save_buffer_size)
  189908. {
  189909. if (png_ptr->save_buffer_ptr != png_ptr->save_buffer)
  189910. {
  189911. png_size_t i,istop;
  189912. png_bytep sp;
  189913. png_bytep dp;
  189914. istop = png_ptr->save_buffer_size;
  189915. for (i = 0, sp = png_ptr->save_buffer_ptr, dp = png_ptr->save_buffer;
  189916. i < istop; i++, sp++, dp++)
  189917. {
  189918. *dp = *sp;
  189919. }
  189920. }
  189921. }
  189922. if (png_ptr->save_buffer_size + png_ptr->current_buffer_size >
  189923. png_ptr->save_buffer_max)
  189924. {
  189925. png_size_t new_max;
  189926. png_bytep old_buffer;
  189927. if (png_ptr->save_buffer_size > PNG_SIZE_MAX -
  189928. (png_ptr->current_buffer_size + 256))
  189929. {
  189930. png_error(png_ptr, "Potential overflow of save_buffer");
  189931. }
  189932. new_max = png_ptr->save_buffer_size + png_ptr->current_buffer_size + 256;
  189933. old_buffer = png_ptr->save_buffer;
  189934. png_ptr->save_buffer = (png_bytep)png_malloc(png_ptr,
  189935. (png_uint_32)new_max);
  189936. png_memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
  189937. png_free(png_ptr, old_buffer);
  189938. png_ptr->save_buffer_max = new_max;
  189939. }
  189940. if (png_ptr->current_buffer_size)
  189941. {
  189942. png_memcpy(png_ptr->save_buffer + png_ptr->save_buffer_size,
  189943. png_ptr->current_buffer_ptr, png_ptr->current_buffer_size);
  189944. png_ptr->save_buffer_size += png_ptr->current_buffer_size;
  189945. png_ptr->current_buffer_size = 0;
  189946. }
  189947. png_ptr->save_buffer_ptr = png_ptr->save_buffer;
  189948. png_ptr->buffer_size = 0;
  189949. }
  189950. void /* PRIVATE */
  189951. png_push_restore_buffer(png_structp png_ptr, png_bytep buffer,
  189952. png_size_t buffer_length)
  189953. {
  189954. png_ptr->current_buffer = buffer;
  189955. png_ptr->current_buffer_size = buffer_length;
  189956. png_ptr->buffer_size = buffer_length + png_ptr->save_buffer_size;
  189957. png_ptr->current_buffer_ptr = png_ptr->current_buffer;
  189958. }
  189959. void /* PRIVATE */
  189960. png_push_read_IDAT(png_structp png_ptr)
  189961. {
  189962. #ifdef PNG_USE_LOCAL_ARRAYS
  189963. PNG_CONST PNG_IDAT;
  189964. #endif
  189965. if (!(png_ptr->mode & PNG_HAVE_CHUNK_HEADER))
  189966. {
  189967. png_byte chunk_length[4];
  189968. if (png_ptr->buffer_size < 8)
  189969. {
  189970. png_push_save_buffer(png_ptr);
  189971. return;
  189972. }
  189973. png_push_fill_buffer(png_ptr, chunk_length, 4);
  189974. png_ptr->push_length = png_get_uint_31(png_ptr,chunk_length);
  189975. png_reset_crc(png_ptr);
  189976. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  189977. png_ptr->mode |= PNG_HAVE_CHUNK_HEADER;
  189978. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  189979. {
  189980. png_ptr->process_mode = PNG_READ_CHUNK_MODE;
  189981. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  189982. png_error(png_ptr, "Not enough compressed data");
  189983. return;
  189984. }
  189985. png_ptr->idat_size = png_ptr->push_length;
  189986. }
  189987. if (png_ptr->idat_size && png_ptr->save_buffer_size)
  189988. {
  189989. png_size_t save_size;
  189990. if (png_ptr->idat_size < (png_uint_32)png_ptr->save_buffer_size)
  189991. {
  189992. save_size = (png_size_t)png_ptr->idat_size;
  189993. /* check for overflow */
  189994. if((png_uint_32)save_size != png_ptr->idat_size)
  189995. png_error(png_ptr, "save_size overflowed in pngpread");
  189996. }
  189997. else
  189998. save_size = png_ptr->save_buffer_size;
  189999. png_calculate_crc(png_ptr, png_ptr->save_buffer_ptr, save_size);
  190000. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  190001. png_process_IDAT_data(png_ptr, png_ptr->save_buffer_ptr, save_size);
  190002. png_ptr->idat_size -= save_size;
  190003. png_ptr->buffer_size -= save_size;
  190004. png_ptr->save_buffer_size -= save_size;
  190005. png_ptr->save_buffer_ptr += save_size;
  190006. }
  190007. if (png_ptr->idat_size && png_ptr->current_buffer_size)
  190008. {
  190009. png_size_t save_size;
  190010. if (png_ptr->idat_size < (png_uint_32)png_ptr->current_buffer_size)
  190011. {
  190012. save_size = (png_size_t)png_ptr->idat_size;
  190013. /* check for overflow */
  190014. if((png_uint_32)save_size != png_ptr->idat_size)
  190015. png_error(png_ptr, "save_size overflowed in pngpread");
  190016. }
  190017. else
  190018. save_size = png_ptr->current_buffer_size;
  190019. png_calculate_crc(png_ptr, png_ptr->current_buffer_ptr, save_size);
  190020. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  190021. png_process_IDAT_data(png_ptr, png_ptr->current_buffer_ptr, save_size);
  190022. png_ptr->idat_size -= save_size;
  190023. png_ptr->buffer_size -= save_size;
  190024. png_ptr->current_buffer_size -= save_size;
  190025. png_ptr->current_buffer_ptr += save_size;
  190026. }
  190027. if (!png_ptr->idat_size)
  190028. {
  190029. if (png_ptr->buffer_size < 4)
  190030. {
  190031. png_push_save_buffer(png_ptr);
  190032. return;
  190033. }
  190034. png_crc_finish(png_ptr, 0);
  190035. png_ptr->mode &= ~PNG_HAVE_CHUNK_HEADER;
  190036. png_ptr->mode |= PNG_AFTER_IDAT;
  190037. }
  190038. }
  190039. void /* PRIVATE */
  190040. png_process_IDAT_data(png_structp png_ptr, png_bytep buffer,
  190041. png_size_t buffer_length)
  190042. {
  190043. int ret;
  190044. if ((png_ptr->flags & PNG_FLAG_ZLIB_FINISHED) && buffer_length)
  190045. png_error(png_ptr, "Extra compression data");
  190046. png_ptr->zstream.next_in = buffer;
  190047. png_ptr->zstream.avail_in = (uInt)buffer_length;
  190048. for(;;)
  190049. {
  190050. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  190051. if (ret != Z_OK)
  190052. {
  190053. if (ret == Z_STREAM_END)
  190054. {
  190055. if (png_ptr->zstream.avail_in)
  190056. png_error(png_ptr, "Extra compressed data");
  190057. if (!(png_ptr->zstream.avail_out))
  190058. {
  190059. png_push_process_row(png_ptr);
  190060. }
  190061. png_ptr->mode |= PNG_AFTER_IDAT;
  190062. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  190063. break;
  190064. }
  190065. else if (ret == Z_BUF_ERROR)
  190066. break;
  190067. else
  190068. png_error(png_ptr, "Decompression Error");
  190069. }
  190070. if (!(png_ptr->zstream.avail_out))
  190071. {
  190072. if ((
  190073. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  190074. png_ptr->interlaced && png_ptr->pass > 6) ||
  190075. (!png_ptr->interlaced &&
  190076. #endif
  190077. png_ptr->row_number == png_ptr->num_rows))
  190078. {
  190079. if (png_ptr->zstream.avail_in)
  190080. {
  190081. png_warning(png_ptr, "Too much data in IDAT chunks");
  190082. }
  190083. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  190084. break;
  190085. }
  190086. png_push_process_row(png_ptr);
  190087. png_ptr->zstream.avail_out = (uInt)png_ptr->irowbytes;
  190088. png_ptr->zstream.next_out = png_ptr->row_buf;
  190089. }
  190090. else
  190091. break;
  190092. }
  190093. }
  190094. void /* PRIVATE */
  190095. png_push_process_row(png_structp png_ptr)
  190096. {
  190097. png_ptr->row_info.color_type = png_ptr->color_type;
  190098. png_ptr->row_info.width = png_ptr->iwidth;
  190099. png_ptr->row_info.channels = png_ptr->channels;
  190100. png_ptr->row_info.bit_depth = png_ptr->bit_depth;
  190101. png_ptr->row_info.pixel_depth = png_ptr->pixel_depth;
  190102. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  190103. png_ptr->row_info.width);
  190104. png_read_filter_row(png_ptr, &(png_ptr->row_info),
  190105. png_ptr->row_buf + 1, png_ptr->prev_row + 1,
  190106. (int)(png_ptr->row_buf[0]));
  190107. png_memcpy_check(png_ptr, png_ptr->prev_row, png_ptr->row_buf,
  190108. png_ptr->rowbytes + 1);
  190109. if (png_ptr->transformations || (png_ptr->flags&PNG_FLAG_STRIP_ALPHA))
  190110. png_do_read_transformations(png_ptr);
  190111. #if defined(PNG_READ_INTERLACING_SUPPORTED)
  190112. /* blow up interlaced rows to full size */
  190113. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  190114. {
  190115. if (png_ptr->pass < 6)
  190116. /* old interface (pre-1.0.9):
  190117. png_do_read_interlace(&(png_ptr->row_info),
  190118. png_ptr->row_buf + 1, png_ptr->pass, png_ptr->transformations);
  190119. */
  190120. png_do_read_interlace(png_ptr);
  190121. switch (png_ptr->pass)
  190122. {
  190123. case 0:
  190124. {
  190125. int i;
  190126. for (i = 0; i < 8 && png_ptr->pass == 0; i++)
  190127. {
  190128. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  190129. png_read_push_finish_row(png_ptr); /* updates png_ptr->pass */
  190130. }
  190131. if (png_ptr->pass == 2) /* pass 1 might be empty */
  190132. {
  190133. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  190134. {
  190135. png_push_have_row(png_ptr, png_bytep_NULL);
  190136. png_read_push_finish_row(png_ptr);
  190137. }
  190138. }
  190139. if (png_ptr->pass == 4 && png_ptr->height <= 4)
  190140. {
  190141. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  190142. {
  190143. png_push_have_row(png_ptr, png_bytep_NULL);
  190144. png_read_push_finish_row(png_ptr);
  190145. }
  190146. }
  190147. if (png_ptr->pass == 6 && png_ptr->height <= 4)
  190148. {
  190149. png_push_have_row(png_ptr, png_bytep_NULL);
  190150. png_read_push_finish_row(png_ptr);
  190151. }
  190152. break;
  190153. }
  190154. case 1:
  190155. {
  190156. int i;
  190157. for (i = 0; i < 8 && png_ptr->pass == 1; i++)
  190158. {
  190159. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  190160. png_read_push_finish_row(png_ptr);
  190161. }
  190162. if (png_ptr->pass == 2) /* skip top 4 generated rows */
  190163. {
  190164. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  190165. {
  190166. png_push_have_row(png_ptr, png_bytep_NULL);
  190167. png_read_push_finish_row(png_ptr);
  190168. }
  190169. }
  190170. break;
  190171. }
  190172. case 2:
  190173. {
  190174. int i;
  190175. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  190176. {
  190177. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  190178. png_read_push_finish_row(png_ptr);
  190179. }
  190180. for (i = 0; i < 4 && png_ptr->pass == 2; i++)
  190181. {
  190182. png_push_have_row(png_ptr, png_bytep_NULL);
  190183. png_read_push_finish_row(png_ptr);
  190184. }
  190185. if (png_ptr->pass == 4) /* pass 3 might be empty */
  190186. {
  190187. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  190188. {
  190189. png_push_have_row(png_ptr, png_bytep_NULL);
  190190. png_read_push_finish_row(png_ptr);
  190191. }
  190192. }
  190193. break;
  190194. }
  190195. case 3:
  190196. {
  190197. int i;
  190198. for (i = 0; i < 4 && png_ptr->pass == 3; i++)
  190199. {
  190200. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  190201. png_read_push_finish_row(png_ptr);
  190202. }
  190203. if (png_ptr->pass == 4) /* skip top two generated rows */
  190204. {
  190205. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  190206. {
  190207. png_push_have_row(png_ptr, png_bytep_NULL);
  190208. png_read_push_finish_row(png_ptr);
  190209. }
  190210. }
  190211. break;
  190212. }
  190213. case 4:
  190214. {
  190215. int i;
  190216. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  190217. {
  190218. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  190219. png_read_push_finish_row(png_ptr);
  190220. }
  190221. for (i = 0; i < 2 && png_ptr->pass == 4; i++)
  190222. {
  190223. png_push_have_row(png_ptr, png_bytep_NULL);
  190224. png_read_push_finish_row(png_ptr);
  190225. }
  190226. if (png_ptr->pass == 6) /* pass 5 might be empty */
  190227. {
  190228. png_push_have_row(png_ptr, png_bytep_NULL);
  190229. png_read_push_finish_row(png_ptr);
  190230. }
  190231. break;
  190232. }
  190233. case 5:
  190234. {
  190235. int i;
  190236. for (i = 0; i < 2 && png_ptr->pass == 5; i++)
  190237. {
  190238. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  190239. png_read_push_finish_row(png_ptr);
  190240. }
  190241. if (png_ptr->pass == 6) /* skip top generated row */
  190242. {
  190243. png_push_have_row(png_ptr, png_bytep_NULL);
  190244. png_read_push_finish_row(png_ptr);
  190245. }
  190246. break;
  190247. }
  190248. case 6:
  190249. {
  190250. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  190251. png_read_push_finish_row(png_ptr);
  190252. if (png_ptr->pass != 6)
  190253. break;
  190254. png_push_have_row(png_ptr, png_bytep_NULL);
  190255. png_read_push_finish_row(png_ptr);
  190256. }
  190257. }
  190258. }
  190259. else
  190260. #endif
  190261. {
  190262. png_push_have_row(png_ptr, png_ptr->row_buf + 1);
  190263. png_read_push_finish_row(png_ptr);
  190264. }
  190265. }
  190266. void /* PRIVATE */
  190267. png_read_push_finish_row(png_structp png_ptr)
  190268. {
  190269. #ifdef PNG_USE_LOCAL_ARRAYS
  190270. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  190271. /* start of interlace block */
  190272. PNG_CONST int FARDATA png_pass_start[] = {0, 4, 0, 2, 0, 1, 0};
  190273. /* offset to next interlace block */
  190274. PNG_CONST int FARDATA png_pass_inc[] = {8, 8, 4, 4, 2, 2, 1};
  190275. /* start of interlace block in the y direction */
  190276. PNG_CONST int FARDATA png_pass_ystart[] = {0, 0, 4, 0, 2, 0, 1};
  190277. /* offset to next interlace block in the y direction */
  190278. PNG_CONST int FARDATA png_pass_yinc[] = {8, 8, 8, 4, 4, 2, 2};
  190279. /* Height of interlace block. This is not currently used - if you need
  190280. * it, uncomment it here and in png.h
  190281. PNG_CONST int FARDATA png_pass_height[] = {8, 8, 4, 4, 2, 2, 1};
  190282. */
  190283. #endif
  190284. png_ptr->row_number++;
  190285. if (png_ptr->row_number < png_ptr->num_rows)
  190286. return;
  190287. if (png_ptr->interlaced)
  190288. {
  190289. png_ptr->row_number = 0;
  190290. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  190291. png_ptr->rowbytes + 1);
  190292. do
  190293. {
  190294. png_ptr->pass++;
  190295. if ((png_ptr->pass == 1 && png_ptr->width < 5) ||
  190296. (png_ptr->pass == 3 && png_ptr->width < 3) ||
  190297. (png_ptr->pass == 5 && png_ptr->width < 2))
  190298. png_ptr->pass++;
  190299. if (png_ptr->pass > 7)
  190300. png_ptr->pass--;
  190301. if (png_ptr->pass >= 7)
  190302. break;
  190303. png_ptr->iwidth = (png_ptr->width +
  190304. png_pass_inc[png_ptr->pass] - 1 -
  190305. png_pass_start[png_ptr->pass]) /
  190306. png_pass_inc[png_ptr->pass];
  190307. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  190308. png_ptr->iwidth) + 1;
  190309. if (png_ptr->transformations & PNG_INTERLACE)
  190310. break;
  190311. png_ptr->num_rows = (png_ptr->height +
  190312. png_pass_yinc[png_ptr->pass] - 1 -
  190313. png_pass_ystart[png_ptr->pass]) /
  190314. png_pass_yinc[png_ptr->pass];
  190315. } while (png_ptr->iwidth == 0 || png_ptr->num_rows == 0);
  190316. }
  190317. }
  190318. #if defined(PNG_READ_tEXt_SUPPORTED)
  190319. void /* PRIVATE */
  190320. png_push_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  190321. length)
  190322. {
  190323. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  190324. {
  190325. png_error(png_ptr, "Out of place tEXt");
  190326. info_ptr = info_ptr; /* to quiet some compiler warnings */
  190327. }
  190328. #ifdef PNG_MAX_MALLOC_64K
  190329. png_ptr->skip_length = 0; /* This may not be necessary */
  190330. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  190331. {
  190332. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  190333. png_ptr->skip_length = length - (png_uint_32)65535L;
  190334. length = (png_uint_32)65535L;
  190335. }
  190336. #endif
  190337. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  190338. (png_uint_32)(length+1));
  190339. png_ptr->current_text[length] = '\0';
  190340. png_ptr->current_text_ptr = png_ptr->current_text;
  190341. png_ptr->current_text_size = (png_size_t)length;
  190342. png_ptr->current_text_left = (png_size_t)length;
  190343. png_ptr->process_mode = PNG_READ_tEXt_MODE;
  190344. }
  190345. void /* PRIVATE */
  190346. png_push_read_tEXt(png_structp png_ptr, png_infop info_ptr)
  190347. {
  190348. if (png_ptr->buffer_size && png_ptr->current_text_left)
  190349. {
  190350. png_size_t text_size;
  190351. if (png_ptr->buffer_size < png_ptr->current_text_left)
  190352. text_size = png_ptr->buffer_size;
  190353. else
  190354. text_size = png_ptr->current_text_left;
  190355. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  190356. png_ptr->current_text_left -= text_size;
  190357. png_ptr->current_text_ptr += text_size;
  190358. }
  190359. if (!(png_ptr->current_text_left))
  190360. {
  190361. png_textp text_ptr;
  190362. png_charp text;
  190363. png_charp key;
  190364. int ret;
  190365. if (png_ptr->buffer_size < 4)
  190366. {
  190367. png_push_save_buffer(png_ptr);
  190368. return;
  190369. }
  190370. png_push_crc_finish(png_ptr);
  190371. #if defined(PNG_MAX_MALLOC_64K)
  190372. if (png_ptr->skip_length)
  190373. return;
  190374. #endif
  190375. key = png_ptr->current_text;
  190376. for (text = key; *text; text++)
  190377. /* empty loop */ ;
  190378. if (text < key + png_ptr->current_text_size)
  190379. text++;
  190380. text_ptr = (png_textp)png_malloc(png_ptr,
  190381. (png_uint_32)png_sizeof(png_text));
  190382. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  190383. text_ptr->key = key;
  190384. #ifdef PNG_iTXt_SUPPORTED
  190385. text_ptr->lang = NULL;
  190386. text_ptr->lang_key = NULL;
  190387. #endif
  190388. text_ptr->text = text;
  190389. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  190390. png_free(png_ptr, key);
  190391. png_free(png_ptr, text_ptr);
  190392. png_ptr->current_text = NULL;
  190393. if (ret)
  190394. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  190395. }
  190396. }
  190397. #endif
  190398. #if defined(PNG_READ_zTXt_SUPPORTED)
  190399. void /* PRIVATE */
  190400. png_push_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  190401. length)
  190402. {
  190403. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  190404. {
  190405. png_error(png_ptr, "Out of place zTXt");
  190406. info_ptr = info_ptr; /* to quiet some compiler warnings */
  190407. }
  190408. #ifdef PNG_MAX_MALLOC_64K
  190409. /* We can't handle zTXt chunks > 64K, since we don't have enough space
  190410. * to be able to store the uncompressed data. Actually, the threshold
  190411. * is probably around 32K, but it isn't as definite as 64K is.
  190412. */
  190413. if (length > (png_uint_32)65535L)
  190414. {
  190415. png_warning(png_ptr, "zTXt chunk too large to fit in memory");
  190416. png_push_crc_skip(png_ptr, length);
  190417. return;
  190418. }
  190419. #endif
  190420. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  190421. (png_uint_32)(length+1));
  190422. png_ptr->current_text[length] = '\0';
  190423. png_ptr->current_text_ptr = png_ptr->current_text;
  190424. png_ptr->current_text_size = (png_size_t)length;
  190425. png_ptr->current_text_left = (png_size_t)length;
  190426. png_ptr->process_mode = PNG_READ_zTXt_MODE;
  190427. }
  190428. void /* PRIVATE */
  190429. png_push_read_zTXt(png_structp png_ptr, png_infop info_ptr)
  190430. {
  190431. if (png_ptr->buffer_size && png_ptr->current_text_left)
  190432. {
  190433. png_size_t text_size;
  190434. if (png_ptr->buffer_size < (png_uint_32)png_ptr->current_text_left)
  190435. text_size = png_ptr->buffer_size;
  190436. else
  190437. text_size = png_ptr->current_text_left;
  190438. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  190439. png_ptr->current_text_left -= text_size;
  190440. png_ptr->current_text_ptr += text_size;
  190441. }
  190442. if (!(png_ptr->current_text_left))
  190443. {
  190444. png_textp text_ptr;
  190445. png_charp text;
  190446. png_charp key;
  190447. int ret;
  190448. png_size_t text_size, key_size;
  190449. if (png_ptr->buffer_size < 4)
  190450. {
  190451. png_push_save_buffer(png_ptr);
  190452. return;
  190453. }
  190454. png_push_crc_finish(png_ptr);
  190455. key = png_ptr->current_text;
  190456. for (text = key; *text; text++)
  190457. /* empty loop */ ;
  190458. /* zTXt can't have zero text */
  190459. if (text >= key + png_ptr->current_text_size)
  190460. {
  190461. png_ptr->current_text = NULL;
  190462. png_free(png_ptr, key);
  190463. return;
  190464. }
  190465. text++;
  190466. if (*text != PNG_TEXT_COMPRESSION_zTXt) /* check compression byte */
  190467. {
  190468. png_ptr->current_text = NULL;
  190469. png_free(png_ptr, key);
  190470. return;
  190471. }
  190472. text++;
  190473. png_ptr->zstream.next_in = (png_bytep )text;
  190474. png_ptr->zstream.avail_in = (uInt)(png_ptr->current_text_size -
  190475. (text - key));
  190476. png_ptr->zstream.next_out = png_ptr->zbuf;
  190477. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  190478. key_size = text - key;
  190479. text_size = 0;
  190480. text = NULL;
  190481. ret = Z_STREAM_END;
  190482. while (png_ptr->zstream.avail_in)
  190483. {
  190484. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  190485. if (ret != Z_OK && ret != Z_STREAM_END)
  190486. {
  190487. inflateReset(&png_ptr->zstream);
  190488. png_ptr->zstream.avail_in = 0;
  190489. png_ptr->current_text = NULL;
  190490. png_free(png_ptr, key);
  190491. png_free(png_ptr, text);
  190492. return;
  190493. }
  190494. if (!(png_ptr->zstream.avail_out) || ret == Z_STREAM_END)
  190495. {
  190496. if (text == NULL)
  190497. {
  190498. text = (png_charp)png_malloc(png_ptr,
  190499. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  190500. + key_size + 1));
  190501. png_memcpy(text + key_size, png_ptr->zbuf,
  190502. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  190503. png_memcpy(text, key, key_size);
  190504. text_size = key_size + png_ptr->zbuf_size -
  190505. png_ptr->zstream.avail_out;
  190506. *(text + text_size) = '\0';
  190507. }
  190508. else
  190509. {
  190510. png_charp tmp;
  190511. tmp = text;
  190512. text = (png_charp)png_malloc(png_ptr, text_size +
  190513. (png_uint_32)(png_ptr->zbuf_size - png_ptr->zstream.avail_out
  190514. + 1));
  190515. png_memcpy(text, tmp, text_size);
  190516. png_free(png_ptr, tmp);
  190517. png_memcpy(text + text_size, png_ptr->zbuf,
  190518. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  190519. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  190520. *(text + text_size) = '\0';
  190521. }
  190522. if (ret != Z_STREAM_END)
  190523. {
  190524. png_ptr->zstream.next_out = png_ptr->zbuf;
  190525. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  190526. }
  190527. }
  190528. else
  190529. {
  190530. break;
  190531. }
  190532. if (ret == Z_STREAM_END)
  190533. break;
  190534. }
  190535. inflateReset(&png_ptr->zstream);
  190536. png_ptr->zstream.avail_in = 0;
  190537. if (ret != Z_STREAM_END)
  190538. {
  190539. png_ptr->current_text = NULL;
  190540. png_free(png_ptr, key);
  190541. png_free(png_ptr, text);
  190542. return;
  190543. }
  190544. png_ptr->current_text = NULL;
  190545. png_free(png_ptr, key);
  190546. key = text;
  190547. text += key_size;
  190548. text_ptr = (png_textp)png_malloc(png_ptr,
  190549. (png_uint_32)png_sizeof(png_text));
  190550. text_ptr->compression = PNG_TEXT_COMPRESSION_zTXt;
  190551. text_ptr->key = key;
  190552. #ifdef PNG_iTXt_SUPPORTED
  190553. text_ptr->lang = NULL;
  190554. text_ptr->lang_key = NULL;
  190555. #endif
  190556. text_ptr->text = text;
  190557. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  190558. png_free(png_ptr, key);
  190559. png_free(png_ptr, text_ptr);
  190560. if (ret)
  190561. png_warning(png_ptr, "Insufficient memory to store text chunk.");
  190562. }
  190563. }
  190564. #endif
  190565. #if defined(PNG_READ_iTXt_SUPPORTED)
  190566. void /* PRIVATE */
  190567. png_push_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32
  190568. length)
  190569. {
  190570. if (!(png_ptr->mode & PNG_HAVE_IHDR) || (png_ptr->mode & PNG_HAVE_IEND))
  190571. {
  190572. png_error(png_ptr, "Out of place iTXt");
  190573. info_ptr = info_ptr; /* to quiet some compiler warnings */
  190574. }
  190575. #ifdef PNG_MAX_MALLOC_64K
  190576. png_ptr->skip_length = 0; /* This may not be necessary */
  190577. if (length > (png_uint_32)65535L) /* Can't hold entire string in memory */
  190578. {
  190579. png_warning(png_ptr, "iTXt chunk too large to fit in memory");
  190580. png_ptr->skip_length = length - (png_uint_32)65535L;
  190581. length = (png_uint_32)65535L;
  190582. }
  190583. #endif
  190584. png_ptr->current_text = (png_charp)png_malloc(png_ptr,
  190585. (png_uint_32)(length+1));
  190586. png_ptr->current_text[length] = '\0';
  190587. png_ptr->current_text_ptr = png_ptr->current_text;
  190588. png_ptr->current_text_size = (png_size_t)length;
  190589. png_ptr->current_text_left = (png_size_t)length;
  190590. png_ptr->process_mode = PNG_READ_iTXt_MODE;
  190591. }
  190592. void /* PRIVATE */
  190593. png_push_read_iTXt(png_structp png_ptr, png_infop info_ptr)
  190594. {
  190595. if (png_ptr->buffer_size && png_ptr->current_text_left)
  190596. {
  190597. png_size_t text_size;
  190598. if (png_ptr->buffer_size < png_ptr->current_text_left)
  190599. text_size = png_ptr->buffer_size;
  190600. else
  190601. text_size = png_ptr->current_text_left;
  190602. png_crc_read(png_ptr, (png_bytep)png_ptr->current_text_ptr, text_size);
  190603. png_ptr->current_text_left -= text_size;
  190604. png_ptr->current_text_ptr += text_size;
  190605. }
  190606. if (!(png_ptr->current_text_left))
  190607. {
  190608. png_textp text_ptr;
  190609. png_charp key;
  190610. int comp_flag;
  190611. png_charp lang;
  190612. png_charp lang_key;
  190613. png_charp text;
  190614. int ret;
  190615. if (png_ptr->buffer_size < 4)
  190616. {
  190617. png_push_save_buffer(png_ptr);
  190618. return;
  190619. }
  190620. png_push_crc_finish(png_ptr);
  190621. #if defined(PNG_MAX_MALLOC_64K)
  190622. if (png_ptr->skip_length)
  190623. return;
  190624. #endif
  190625. key = png_ptr->current_text;
  190626. for (lang = key; *lang; lang++)
  190627. /* empty loop */ ;
  190628. if (lang < key + png_ptr->current_text_size - 3)
  190629. lang++;
  190630. comp_flag = *lang++;
  190631. lang++; /* skip comp_type, always zero */
  190632. for (lang_key = lang; *lang_key; lang_key++)
  190633. /* empty loop */ ;
  190634. lang_key++; /* skip NUL separator */
  190635. text=lang_key;
  190636. if (lang_key < key + png_ptr->current_text_size - 1)
  190637. {
  190638. for (; *text; text++)
  190639. /* empty loop */ ;
  190640. }
  190641. if (text < key + png_ptr->current_text_size)
  190642. text++;
  190643. text_ptr = (png_textp)png_malloc(png_ptr,
  190644. (png_uint_32)png_sizeof(png_text));
  190645. text_ptr->compression = comp_flag + 2;
  190646. text_ptr->key = key;
  190647. text_ptr->lang = lang;
  190648. text_ptr->lang_key = lang_key;
  190649. text_ptr->text = text;
  190650. text_ptr->text_length = 0;
  190651. text_ptr->itxt_length = png_strlen(text);
  190652. ret = png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  190653. png_ptr->current_text = NULL;
  190654. png_free(png_ptr, text_ptr);
  190655. if (ret)
  190656. png_warning(png_ptr, "Insufficient memory to store iTXt chunk.");
  190657. }
  190658. }
  190659. #endif
  190660. /* This function is called when we haven't found a handler for this
  190661. * chunk. If there isn't a problem with the chunk itself (ie a bad chunk
  190662. * name or a critical chunk), the chunk is (currently) silently ignored.
  190663. */
  190664. void /* PRIVATE */
  190665. png_push_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32
  190666. length)
  190667. {
  190668. png_uint_32 skip=0;
  190669. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  190670. if (!(png_ptr->chunk_name[0] & 0x20))
  190671. {
  190672. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  190673. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  190674. PNG_HANDLE_CHUNK_ALWAYS
  190675. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  190676. && png_ptr->read_user_chunk_fn == NULL
  190677. #endif
  190678. )
  190679. #endif
  190680. png_chunk_error(png_ptr, "unknown critical chunk");
  190681. info_ptr = info_ptr; /* to quiet some compiler warnings */
  190682. }
  190683. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  190684. if (png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS)
  190685. {
  190686. #ifdef PNG_MAX_MALLOC_64K
  190687. if (length > (png_uint_32)65535L)
  190688. {
  190689. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  190690. skip = length - (png_uint_32)65535L;
  190691. length = (png_uint_32)65535L;
  190692. }
  190693. #endif
  190694. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  190695. (png_charp)png_ptr->chunk_name, 5);
  190696. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  190697. png_ptr->unknown_chunk.size = (png_size_t)length;
  190698. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  190699. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  190700. if(png_ptr->read_user_chunk_fn != NULL)
  190701. {
  190702. /* callback to user unknown chunk handler */
  190703. int ret;
  190704. ret = (*(png_ptr->read_user_chunk_fn))
  190705. (png_ptr, &png_ptr->unknown_chunk);
  190706. if (ret < 0)
  190707. png_chunk_error(png_ptr, "error in user chunk");
  190708. if (ret == 0)
  190709. {
  190710. if (!(png_ptr->chunk_name[0] & 0x20))
  190711. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  190712. PNG_HANDLE_CHUNK_ALWAYS)
  190713. png_chunk_error(png_ptr, "unknown critical chunk");
  190714. png_set_unknown_chunks(png_ptr, info_ptr,
  190715. &png_ptr->unknown_chunk, 1);
  190716. }
  190717. }
  190718. #else
  190719. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  190720. #endif
  190721. png_free(png_ptr, png_ptr->unknown_chunk.data);
  190722. png_ptr->unknown_chunk.data = NULL;
  190723. }
  190724. else
  190725. #endif
  190726. skip=length;
  190727. png_push_crc_skip(png_ptr, skip);
  190728. }
  190729. void /* PRIVATE */
  190730. png_push_have_info(png_structp png_ptr, png_infop info_ptr)
  190731. {
  190732. if (png_ptr->info_fn != NULL)
  190733. (*(png_ptr->info_fn))(png_ptr, info_ptr);
  190734. }
  190735. void /* PRIVATE */
  190736. png_push_have_end(png_structp png_ptr, png_infop info_ptr)
  190737. {
  190738. if (png_ptr->end_fn != NULL)
  190739. (*(png_ptr->end_fn))(png_ptr, info_ptr);
  190740. }
  190741. void /* PRIVATE */
  190742. png_push_have_row(png_structp png_ptr, png_bytep row)
  190743. {
  190744. if (png_ptr->row_fn != NULL)
  190745. (*(png_ptr->row_fn))(png_ptr, row, png_ptr->row_number,
  190746. (int)png_ptr->pass);
  190747. }
  190748. void PNGAPI
  190749. png_progressive_combine_row (png_structp png_ptr,
  190750. png_bytep old_row, png_bytep new_row)
  190751. {
  190752. #ifdef PNG_USE_LOCAL_ARRAYS
  190753. PNG_CONST int FARDATA png_pass_dsp_mask[7] =
  190754. {0xff, 0x0f, 0xff, 0x33, 0xff, 0x55, 0xff};
  190755. #endif
  190756. if(png_ptr == NULL) return;
  190757. if (new_row != NULL) /* new_row must == png_ptr->row_buf here. */
  190758. png_combine_row(png_ptr, old_row, png_pass_dsp_mask[png_ptr->pass]);
  190759. }
  190760. void PNGAPI
  190761. png_set_progressive_read_fn(png_structp png_ptr, png_voidp progressive_ptr,
  190762. png_progressive_info_ptr info_fn, png_progressive_row_ptr row_fn,
  190763. png_progressive_end_ptr end_fn)
  190764. {
  190765. if(png_ptr == NULL) return;
  190766. png_ptr->info_fn = info_fn;
  190767. png_ptr->row_fn = row_fn;
  190768. png_ptr->end_fn = end_fn;
  190769. png_set_read_fn(png_ptr, progressive_ptr, png_push_fill_buffer);
  190770. }
  190771. png_voidp PNGAPI
  190772. png_get_progressive_ptr(png_structp png_ptr)
  190773. {
  190774. if(png_ptr == NULL) return (NULL);
  190775. return png_ptr->io_ptr;
  190776. }
  190777. #endif /* PNG_PROGRESSIVE_READ_SUPPORTED */
  190778. /********* End of inlined file: pngpread.c *********/
  190779. /********* Start of inlined file: pngrio.c *********/
  190780. /* pngrio.c - functions for data input
  190781. *
  190782. * Last changed in libpng 1.2.13 November 13, 2006
  190783. * For conditions of distribution and use, see copyright notice in png.h
  190784. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  190785. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190786. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190787. *
  190788. * This file provides a location for all input. Users who need
  190789. * special handling are expected to write a function that has the same
  190790. * arguments as this and performs a similar function, but that possibly
  190791. * has a different input method. Note that you shouldn't change this
  190792. * function, but rather write a replacement function and then make
  190793. * libpng use it at run time with png_set_read_fn(...).
  190794. */
  190795. #define PNG_INTERNAL
  190796. #if defined(PNG_READ_SUPPORTED)
  190797. /* Read the data from whatever input you are using. The default routine
  190798. reads from a file pointer. Note that this routine sometimes gets called
  190799. with very small lengths, so you should implement some kind of simple
  190800. buffering if you are using unbuffered reads. This should never be asked
  190801. to read more then 64K on a 16 bit machine. */
  190802. void /* PRIVATE */
  190803. png_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190804. {
  190805. png_debug1(4,"reading %d bytes\n", (int)length);
  190806. if (png_ptr->read_data_fn != NULL)
  190807. (*(png_ptr->read_data_fn))(png_ptr, data, length);
  190808. else
  190809. png_error(png_ptr, "Call to NULL read function");
  190810. }
  190811. #if !defined(PNG_NO_STDIO)
  190812. /* This is the function that does the actual reading of data. If you are
  190813. not reading from a standard C stream, you should create a replacement
  190814. read_data function and use it at run time with png_set_read_fn(), rather
  190815. than changing the library. */
  190816. #ifndef USE_FAR_KEYWORD
  190817. void PNGAPI
  190818. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190819. {
  190820. png_size_t check;
  190821. if(png_ptr == NULL) return;
  190822. /* fread() returns 0 on error, so it is OK to store this in a png_size_t
  190823. * instead of an int, which is what fread() actually returns.
  190824. */
  190825. #if defined(_WIN32_WCE)
  190826. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190827. check = 0;
  190828. #else
  190829. check = (png_size_t)fread(data, (png_size_t)1, length,
  190830. (png_FILE_p)png_ptr->io_ptr);
  190831. #endif
  190832. if (check != length)
  190833. png_error(png_ptr, "Read Error");
  190834. }
  190835. #else
  190836. /* this is the model-independent version. Since the standard I/O library
  190837. can't handle far buffers in the medium and small models, we have to copy
  190838. the data.
  190839. */
  190840. #define NEAR_BUF_SIZE 1024
  190841. #define MIN(a,b) (a <= b ? a : b)
  190842. static void PNGAPI
  190843. png_default_read_data(png_structp png_ptr, png_bytep data, png_size_t length)
  190844. {
  190845. int check;
  190846. png_byte *n_data;
  190847. png_FILE_p io_ptr;
  190848. if(png_ptr == NULL) return;
  190849. /* Check if data really is near. If so, use usual code. */
  190850. n_data = (png_byte *)CVT_PTR_NOCHECK(data);
  190851. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  190852. if ((png_bytep)n_data == data)
  190853. {
  190854. #if defined(_WIN32_WCE)
  190855. if ( !ReadFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  190856. check = 0;
  190857. #else
  190858. check = fread(n_data, 1, length, io_ptr);
  190859. #endif
  190860. }
  190861. else
  190862. {
  190863. png_byte buf[NEAR_BUF_SIZE];
  190864. png_size_t read, remaining, err;
  190865. check = 0;
  190866. remaining = length;
  190867. do
  190868. {
  190869. read = MIN(NEAR_BUF_SIZE, remaining);
  190870. #if defined(_WIN32_WCE)
  190871. if ( !ReadFile((HANDLE)(io_ptr), buf, read, &err, NULL) )
  190872. err = 0;
  190873. #else
  190874. err = fread(buf, (png_size_t)1, read, io_ptr);
  190875. #endif
  190876. png_memcpy(data, buf, read); /* copy far buffer to near buffer */
  190877. if(err != read)
  190878. break;
  190879. else
  190880. check += err;
  190881. data += read;
  190882. remaining -= read;
  190883. }
  190884. while (remaining != 0);
  190885. }
  190886. if ((png_uint_32)check != (png_uint_32)length)
  190887. png_error(png_ptr, "read Error");
  190888. }
  190889. #endif
  190890. #endif
  190891. /* This function allows the application to supply a new input function
  190892. for libpng if standard C streams aren't being used.
  190893. This function takes as its arguments:
  190894. png_ptr - pointer to a png input data structure
  190895. io_ptr - pointer to user supplied structure containing info about
  190896. the input functions. May be NULL.
  190897. read_data_fn - pointer to a new input function that takes as its
  190898. arguments a pointer to a png_struct, a pointer to
  190899. a location where input data can be stored, and a 32-bit
  190900. unsigned int that is the number of bytes to be read.
  190901. To exit and output any fatal error messages the new write
  190902. function should call png_error(png_ptr, "Error msg"). */
  190903. void PNGAPI
  190904. png_set_read_fn(png_structp png_ptr, png_voidp io_ptr,
  190905. png_rw_ptr read_data_fn)
  190906. {
  190907. if(png_ptr == NULL) return;
  190908. png_ptr->io_ptr = io_ptr;
  190909. #if !defined(PNG_NO_STDIO)
  190910. if (read_data_fn != NULL)
  190911. png_ptr->read_data_fn = read_data_fn;
  190912. else
  190913. png_ptr->read_data_fn = png_default_read_data;
  190914. #else
  190915. png_ptr->read_data_fn = read_data_fn;
  190916. #endif
  190917. /* It is an error to write to a read device */
  190918. if (png_ptr->write_data_fn != NULL)
  190919. {
  190920. png_ptr->write_data_fn = NULL;
  190921. png_warning(png_ptr,
  190922. "It's an error to set both read_data_fn and write_data_fn in the ");
  190923. png_warning(png_ptr,
  190924. "same structure. Resetting write_data_fn to NULL.");
  190925. }
  190926. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  190927. png_ptr->output_flush_fn = NULL;
  190928. #endif
  190929. }
  190930. #endif /* PNG_READ_SUPPORTED */
  190931. /********* End of inlined file: pngrio.c *********/
  190932. /********* Start of inlined file: pngrtran.c *********/
  190933. /* pngrtran.c - transforms the data in a row for PNG readers
  190934. *
  190935. * Last changed in libpng 1.2.21 [October 4, 2007]
  190936. * For conditions of distribution and use, see copyright notice in png.h
  190937. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  190938. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  190939. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  190940. *
  190941. * This file contains functions optionally called by an application
  190942. * in order to tell libpng how to handle data when reading a PNG.
  190943. * Transformations that are used in both reading and writing are
  190944. * in pngtrans.c.
  190945. */
  190946. #define PNG_INTERNAL
  190947. #if defined(PNG_READ_SUPPORTED)
  190948. /* Set the action on getting a CRC error for an ancillary or critical chunk. */
  190949. void PNGAPI
  190950. png_set_crc_action(png_structp png_ptr, int crit_action, int ancil_action)
  190951. {
  190952. png_debug(1, "in png_set_crc_action\n");
  190953. /* Tell libpng how we react to CRC errors in critical chunks */
  190954. if(png_ptr == NULL) return;
  190955. switch (crit_action)
  190956. {
  190957. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190958. break;
  190959. case PNG_CRC_WARN_USE: /* warn/use data */
  190960. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190961. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE;
  190962. break;
  190963. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190964. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190965. png_ptr->flags |= PNG_FLAG_CRC_CRITICAL_USE |
  190966. PNG_FLAG_CRC_CRITICAL_IGNORE;
  190967. break;
  190968. case PNG_CRC_WARN_DISCARD: /* not a valid action for critical data */
  190969. png_warning(png_ptr, "Can't discard critical data on CRC error.");
  190970. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190971. case PNG_CRC_DEFAULT:
  190972. default:
  190973. png_ptr->flags &= ~PNG_FLAG_CRC_CRITICAL_MASK;
  190974. break;
  190975. }
  190976. switch (ancil_action)
  190977. {
  190978. case PNG_CRC_NO_CHANGE: /* leave setting as is */
  190979. break;
  190980. case PNG_CRC_WARN_USE: /* warn/use data */
  190981. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190982. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE;
  190983. break;
  190984. case PNG_CRC_QUIET_USE: /* quiet/use data */
  190985. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190986. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_USE |
  190987. PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190988. break;
  190989. case PNG_CRC_ERROR_QUIT: /* error/quit */
  190990. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190991. png_ptr->flags |= PNG_FLAG_CRC_ANCILLARY_NOWARN;
  190992. break;
  190993. case PNG_CRC_WARN_DISCARD: /* warn/discard data */
  190994. case PNG_CRC_DEFAULT:
  190995. default:
  190996. png_ptr->flags &= ~PNG_FLAG_CRC_ANCILLARY_MASK;
  190997. break;
  190998. }
  190999. }
  191000. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  191001. defined(PNG_FLOATING_POINT_SUPPORTED)
  191002. /* handle alpha and tRNS via a background color */
  191003. void PNGAPI
  191004. png_set_background(png_structp png_ptr,
  191005. png_color_16p background_color, int background_gamma_code,
  191006. int need_expand, double background_gamma)
  191007. {
  191008. png_debug(1, "in png_set_background\n");
  191009. if(png_ptr == NULL) return;
  191010. if (background_gamma_code == PNG_BACKGROUND_GAMMA_UNKNOWN)
  191011. {
  191012. png_warning(png_ptr, "Application must supply a known background gamma");
  191013. return;
  191014. }
  191015. png_ptr->transformations |= PNG_BACKGROUND;
  191016. png_memcpy(&(png_ptr->background), background_color,
  191017. png_sizeof(png_color_16));
  191018. png_ptr->background_gamma = (float)background_gamma;
  191019. png_ptr->background_gamma_type = (png_byte)(background_gamma_code);
  191020. png_ptr->transformations |= (need_expand ? PNG_BACKGROUND_EXPAND : 0);
  191021. }
  191022. #endif
  191023. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  191024. /* strip 16 bit depth files to 8 bit depth */
  191025. void PNGAPI
  191026. png_set_strip_16(png_structp png_ptr)
  191027. {
  191028. png_debug(1, "in png_set_strip_16\n");
  191029. if(png_ptr == NULL) return;
  191030. png_ptr->transformations |= PNG_16_TO_8;
  191031. }
  191032. #endif
  191033. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  191034. void PNGAPI
  191035. png_set_strip_alpha(png_structp png_ptr)
  191036. {
  191037. png_debug(1, "in png_set_strip_alpha\n");
  191038. if(png_ptr == NULL) return;
  191039. png_ptr->flags |= PNG_FLAG_STRIP_ALPHA;
  191040. }
  191041. #endif
  191042. #if defined(PNG_READ_DITHER_SUPPORTED)
  191043. /* Dither file to 8 bit. Supply a palette, the current number
  191044. * of elements in the palette, the maximum number of elements
  191045. * allowed, and a histogram if possible. If the current number
  191046. * of colors is greater then the maximum number, the palette will be
  191047. * modified to fit in the maximum number. "full_dither" indicates
  191048. * whether we need a dithering cube set up for RGB images, or if we
  191049. * simply are reducing the number of colors in a paletted image.
  191050. */
  191051. typedef struct png_dsort_struct
  191052. {
  191053. struct png_dsort_struct FAR * next;
  191054. png_byte left;
  191055. png_byte right;
  191056. } png_dsort;
  191057. typedef png_dsort FAR * png_dsortp;
  191058. typedef png_dsort FAR * FAR * png_dsortpp;
  191059. void PNGAPI
  191060. png_set_dither(png_structp png_ptr, png_colorp palette,
  191061. int num_palette, int maximum_colors, png_uint_16p histogram,
  191062. int full_dither)
  191063. {
  191064. png_debug(1, "in png_set_dither\n");
  191065. if(png_ptr == NULL) return;
  191066. png_ptr->transformations |= PNG_DITHER;
  191067. if (!full_dither)
  191068. {
  191069. int i;
  191070. png_ptr->dither_index = (png_bytep)png_malloc(png_ptr,
  191071. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  191072. for (i = 0; i < num_palette; i++)
  191073. png_ptr->dither_index[i] = (png_byte)i;
  191074. }
  191075. if (num_palette > maximum_colors)
  191076. {
  191077. if (histogram != NULL)
  191078. {
  191079. /* This is easy enough, just throw out the least used colors.
  191080. Perhaps not the best solution, but good enough. */
  191081. int i;
  191082. /* initialize an array to sort colors */
  191083. png_ptr->dither_sort = (png_bytep)png_malloc(png_ptr,
  191084. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  191085. /* initialize the dither_sort array */
  191086. for (i = 0; i < num_palette; i++)
  191087. png_ptr->dither_sort[i] = (png_byte)i;
  191088. /* Find the least used palette entries by starting a
  191089. bubble sort, and running it until we have sorted
  191090. out enough colors. Note that we don't care about
  191091. sorting all the colors, just finding which are
  191092. least used. */
  191093. for (i = num_palette - 1; i >= maximum_colors; i--)
  191094. {
  191095. int done; /* to stop early if the list is pre-sorted */
  191096. int j;
  191097. done = 1;
  191098. for (j = 0; j < i; j++)
  191099. {
  191100. if (histogram[png_ptr->dither_sort[j]]
  191101. < histogram[png_ptr->dither_sort[j + 1]])
  191102. {
  191103. png_byte t;
  191104. t = png_ptr->dither_sort[j];
  191105. png_ptr->dither_sort[j] = png_ptr->dither_sort[j + 1];
  191106. png_ptr->dither_sort[j + 1] = t;
  191107. done = 0;
  191108. }
  191109. }
  191110. if (done)
  191111. break;
  191112. }
  191113. /* swap the palette around, and set up a table, if necessary */
  191114. if (full_dither)
  191115. {
  191116. int j = num_palette;
  191117. /* put all the useful colors within the max, but don't
  191118. move the others */
  191119. for (i = 0; i < maximum_colors; i++)
  191120. {
  191121. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  191122. {
  191123. do
  191124. j--;
  191125. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  191126. palette[i] = palette[j];
  191127. }
  191128. }
  191129. }
  191130. else
  191131. {
  191132. int j = num_palette;
  191133. /* move all the used colors inside the max limit, and
  191134. develop a translation table */
  191135. for (i = 0; i < maximum_colors; i++)
  191136. {
  191137. /* only move the colors we need to */
  191138. if ((int)png_ptr->dither_sort[i] >= maximum_colors)
  191139. {
  191140. png_color tmp_color;
  191141. do
  191142. j--;
  191143. while ((int)png_ptr->dither_sort[j] >= maximum_colors);
  191144. tmp_color = palette[j];
  191145. palette[j] = palette[i];
  191146. palette[i] = tmp_color;
  191147. /* indicate where the color went */
  191148. png_ptr->dither_index[j] = (png_byte)i;
  191149. png_ptr->dither_index[i] = (png_byte)j;
  191150. }
  191151. }
  191152. /* find closest color for those colors we are not using */
  191153. for (i = 0; i < num_palette; i++)
  191154. {
  191155. if ((int)png_ptr->dither_index[i] >= maximum_colors)
  191156. {
  191157. int min_d, k, min_k, d_index;
  191158. /* find the closest color to one we threw out */
  191159. d_index = png_ptr->dither_index[i];
  191160. min_d = PNG_COLOR_DIST(palette[d_index], palette[0]);
  191161. for (k = 1, min_k = 0; k < maximum_colors; k++)
  191162. {
  191163. int d;
  191164. d = PNG_COLOR_DIST(palette[d_index], palette[k]);
  191165. if (d < min_d)
  191166. {
  191167. min_d = d;
  191168. min_k = k;
  191169. }
  191170. }
  191171. /* point to closest color */
  191172. png_ptr->dither_index[i] = (png_byte)min_k;
  191173. }
  191174. }
  191175. }
  191176. png_free(png_ptr, png_ptr->dither_sort);
  191177. png_ptr->dither_sort=NULL;
  191178. }
  191179. else
  191180. {
  191181. /* This is much harder to do simply (and quickly). Perhaps
  191182. we need to go through a median cut routine, but those
  191183. don't always behave themselves with only a few colors
  191184. as input. So we will just find the closest two colors,
  191185. and throw out one of them (chosen somewhat randomly).
  191186. [We don't understand this at all, so if someone wants to
  191187. work on improving it, be our guest - AED, GRP]
  191188. */
  191189. int i;
  191190. int max_d;
  191191. int num_new_palette;
  191192. png_dsortp t;
  191193. png_dsortpp hash;
  191194. t=NULL;
  191195. /* initialize palette index arrays */
  191196. png_ptr->index_to_palette = (png_bytep)png_malloc(png_ptr,
  191197. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  191198. png_ptr->palette_to_index = (png_bytep)png_malloc(png_ptr,
  191199. (png_uint_32)(num_palette * png_sizeof (png_byte)));
  191200. /* initialize the sort array */
  191201. for (i = 0; i < num_palette; i++)
  191202. {
  191203. png_ptr->index_to_palette[i] = (png_byte)i;
  191204. png_ptr->palette_to_index[i] = (png_byte)i;
  191205. }
  191206. hash = (png_dsortpp)png_malloc(png_ptr, (png_uint_32)(769 *
  191207. png_sizeof (png_dsortp)));
  191208. for (i = 0; i < 769; i++)
  191209. hash[i] = NULL;
  191210. /* png_memset(hash, 0, 769 * png_sizeof (png_dsortp)); */
  191211. num_new_palette = num_palette;
  191212. /* initial wild guess at how far apart the farthest pixel
  191213. pair we will be eliminating will be. Larger
  191214. numbers mean more areas will be allocated, Smaller
  191215. numbers run the risk of not saving enough data, and
  191216. having to do this all over again.
  191217. I have not done extensive checking on this number.
  191218. */
  191219. max_d = 96;
  191220. while (num_new_palette > maximum_colors)
  191221. {
  191222. for (i = 0; i < num_new_palette - 1; i++)
  191223. {
  191224. int j;
  191225. for (j = i + 1; j < num_new_palette; j++)
  191226. {
  191227. int d;
  191228. d = PNG_COLOR_DIST(palette[i], palette[j]);
  191229. if (d <= max_d)
  191230. {
  191231. t = (png_dsortp)png_malloc_warn(png_ptr,
  191232. (png_uint_32)(png_sizeof(png_dsort)));
  191233. if (t == NULL)
  191234. break;
  191235. t->next = hash[d];
  191236. t->left = (png_byte)i;
  191237. t->right = (png_byte)j;
  191238. hash[d] = t;
  191239. }
  191240. }
  191241. if (t == NULL)
  191242. break;
  191243. }
  191244. if (t != NULL)
  191245. for (i = 0; i <= max_d; i++)
  191246. {
  191247. if (hash[i] != NULL)
  191248. {
  191249. png_dsortp p;
  191250. for (p = hash[i]; p; p = p->next)
  191251. {
  191252. if ((int)png_ptr->index_to_palette[p->left]
  191253. < num_new_palette &&
  191254. (int)png_ptr->index_to_palette[p->right]
  191255. < num_new_palette)
  191256. {
  191257. int j, next_j;
  191258. if (num_new_palette & 0x01)
  191259. {
  191260. j = p->left;
  191261. next_j = p->right;
  191262. }
  191263. else
  191264. {
  191265. j = p->right;
  191266. next_j = p->left;
  191267. }
  191268. num_new_palette--;
  191269. palette[png_ptr->index_to_palette[j]]
  191270. = palette[num_new_palette];
  191271. if (!full_dither)
  191272. {
  191273. int k;
  191274. for (k = 0; k < num_palette; k++)
  191275. {
  191276. if (png_ptr->dither_index[k] ==
  191277. png_ptr->index_to_palette[j])
  191278. png_ptr->dither_index[k] =
  191279. png_ptr->index_to_palette[next_j];
  191280. if ((int)png_ptr->dither_index[k] ==
  191281. num_new_palette)
  191282. png_ptr->dither_index[k] =
  191283. png_ptr->index_to_palette[j];
  191284. }
  191285. }
  191286. png_ptr->index_to_palette[png_ptr->palette_to_index
  191287. [num_new_palette]] = png_ptr->index_to_palette[j];
  191288. png_ptr->palette_to_index[png_ptr->index_to_palette[j]]
  191289. = png_ptr->palette_to_index[num_new_palette];
  191290. png_ptr->index_to_palette[j] = (png_byte)num_new_palette;
  191291. png_ptr->palette_to_index[num_new_palette] = (png_byte)j;
  191292. }
  191293. if (num_new_palette <= maximum_colors)
  191294. break;
  191295. }
  191296. if (num_new_palette <= maximum_colors)
  191297. break;
  191298. }
  191299. }
  191300. for (i = 0; i < 769; i++)
  191301. {
  191302. if (hash[i] != NULL)
  191303. {
  191304. png_dsortp p = hash[i];
  191305. while (p)
  191306. {
  191307. t = p->next;
  191308. png_free(png_ptr, p);
  191309. p = t;
  191310. }
  191311. }
  191312. hash[i] = 0;
  191313. }
  191314. max_d += 96;
  191315. }
  191316. png_free(png_ptr, hash);
  191317. png_free(png_ptr, png_ptr->palette_to_index);
  191318. png_free(png_ptr, png_ptr->index_to_palette);
  191319. png_ptr->palette_to_index=NULL;
  191320. png_ptr->index_to_palette=NULL;
  191321. }
  191322. num_palette = maximum_colors;
  191323. }
  191324. if (png_ptr->palette == NULL)
  191325. {
  191326. png_ptr->palette = palette;
  191327. }
  191328. png_ptr->num_palette = (png_uint_16)num_palette;
  191329. if (full_dither)
  191330. {
  191331. int i;
  191332. png_bytep distance;
  191333. int total_bits = PNG_DITHER_RED_BITS + PNG_DITHER_GREEN_BITS +
  191334. PNG_DITHER_BLUE_BITS;
  191335. int num_red = (1 << PNG_DITHER_RED_BITS);
  191336. int num_green = (1 << PNG_DITHER_GREEN_BITS);
  191337. int num_blue = (1 << PNG_DITHER_BLUE_BITS);
  191338. png_size_t num_entries = ((png_size_t)1 << total_bits);
  191339. png_ptr->palette_lookup = (png_bytep )png_malloc(png_ptr,
  191340. (png_uint_32)(num_entries * png_sizeof (png_byte)));
  191341. png_memset(png_ptr->palette_lookup, 0, num_entries *
  191342. png_sizeof (png_byte));
  191343. distance = (png_bytep)png_malloc(png_ptr, (png_uint_32)(num_entries *
  191344. png_sizeof(png_byte)));
  191345. png_memset(distance, 0xff, num_entries * png_sizeof(png_byte));
  191346. for (i = 0; i < num_palette; i++)
  191347. {
  191348. int ir, ig, ib;
  191349. int r = (palette[i].red >> (8 - PNG_DITHER_RED_BITS));
  191350. int g = (palette[i].green >> (8 - PNG_DITHER_GREEN_BITS));
  191351. int b = (palette[i].blue >> (8 - PNG_DITHER_BLUE_BITS));
  191352. for (ir = 0; ir < num_red; ir++)
  191353. {
  191354. /* int dr = abs(ir - r); */
  191355. int dr = ((ir > r) ? ir - r : r - ir);
  191356. int index_r = (ir << (PNG_DITHER_BLUE_BITS + PNG_DITHER_GREEN_BITS));
  191357. for (ig = 0; ig < num_green; ig++)
  191358. {
  191359. /* int dg = abs(ig - g); */
  191360. int dg = ((ig > g) ? ig - g : g - ig);
  191361. int dt = dr + dg;
  191362. int dm = ((dr > dg) ? dr : dg);
  191363. int index_g = index_r | (ig << PNG_DITHER_BLUE_BITS);
  191364. for (ib = 0; ib < num_blue; ib++)
  191365. {
  191366. int d_index = index_g | ib;
  191367. /* int db = abs(ib - b); */
  191368. int db = ((ib > b) ? ib - b : b - ib);
  191369. int dmax = ((dm > db) ? dm : db);
  191370. int d = dmax + dt + db;
  191371. if (d < (int)distance[d_index])
  191372. {
  191373. distance[d_index] = (png_byte)d;
  191374. png_ptr->palette_lookup[d_index] = (png_byte)i;
  191375. }
  191376. }
  191377. }
  191378. }
  191379. }
  191380. png_free(png_ptr, distance);
  191381. }
  191382. }
  191383. #endif
  191384. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191385. /* Transform the image from the file_gamma to the screen_gamma. We
  191386. * only do transformations on images where the file_gamma and screen_gamma
  191387. * are not close reciprocals, otherwise it slows things down slightly, and
  191388. * also needlessly introduces small errors.
  191389. *
  191390. * We will turn off gamma transformation later if no semitransparent entries
  191391. * are present in the tRNS array for palette images. We can't do it here
  191392. * because we don't necessarily have the tRNS chunk yet.
  191393. */
  191394. void PNGAPI
  191395. png_set_gamma(png_structp png_ptr, double scrn_gamma, double file_gamma)
  191396. {
  191397. png_debug(1, "in png_set_gamma\n");
  191398. if(png_ptr == NULL) return;
  191399. if ((fabs(scrn_gamma * file_gamma - 1.0) > PNG_GAMMA_THRESHOLD) ||
  191400. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA) ||
  191401. (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE))
  191402. png_ptr->transformations |= PNG_GAMMA;
  191403. png_ptr->gamma = (float)file_gamma;
  191404. png_ptr->screen_gamma = (float)scrn_gamma;
  191405. }
  191406. #endif
  191407. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191408. /* Expand paletted images to RGB, expand grayscale images of
  191409. * less than 8-bit depth to 8-bit depth, and expand tRNS chunks
  191410. * to alpha channels.
  191411. */
  191412. void PNGAPI
  191413. png_set_expand(png_structp png_ptr)
  191414. {
  191415. png_debug(1, "in png_set_expand\n");
  191416. if(png_ptr == NULL) return;
  191417. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  191418. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191419. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  191420. #endif
  191421. }
  191422. /* GRR 19990627: the following three functions currently are identical
  191423. * to png_set_expand(). However, it is entirely reasonable that someone
  191424. * might wish to expand an indexed image to RGB but *not* expand a single,
  191425. * fully transparent palette entry to a full alpha channel--perhaps instead
  191426. * convert tRNS to the grayscale/RGB format (16-bit RGB value), or replace
  191427. * the transparent color with a particular RGB value, or drop tRNS entirely.
  191428. * IOW, a future version of the library may make the transformations flag
  191429. * a bit more fine-grained, with separate bits for each of these three
  191430. * functions.
  191431. *
  191432. * More to the point, these functions make it obvious what libpng will be
  191433. * doing, whereas "expand" can (and does) mean any number of things.
  191434. *
  191435. * GRP 20060307: In libpng-1.4.0, png_set_gray_1_2_4_to_8() was modified
  191436. * to expand only the sample depth but not to expand the tRNS to alpha.
  191437. */
  191438. /* Expand paletted images to RGB. */
  191439. void PNGAPI
  191440. png_set_palette_to_rgb(png_structp png_ptr)
  191441. {
  191442. png_debug(1, "in png_set_palette_to_rgb\n");
  191443. if(png_ptr == NULL) return;
  191444. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  191445. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191446. png_ptr->flags &= !(PNG_FLAG_ROW_INIT);
  191447. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  191448. #endif
  191449. }
  191450. #if !defined(PNG_1_0_X)
  191451. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  191452. void PNGAPI
  191453. png_set_expand_gray_1_2_4_to_8(png_structp png_ptr)
  191454. {
  191455. png_debug(1, "in png_set_expand_gray_1_2_4_to_8\n");
  191456. if(png_ptr == NULL) return;
  191457. png_ptr->transformations |= PNG_EXPAND;
  191458. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191459. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  191460. #endif
  191461. }
  191462. #endif
  191463. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  191464. /* Expand grayscale images of less than 8-bit depth to 8 bits. */
  191465. /* Deprecated as of libpng-1.2.9 */
  191466. void PNGAPI
  191467. png_set_gray_1_2_4_to_8(png_structp png_ptr)
  191468. {
  191469. png_debug(1, "in png_set_gray_1_2_4_to_8\n");
  191470. if(png_ptr == NULL) return;
  191471. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  191472. }
  191473. #endif
  191474. /* Expand tRNS chunks to alpha channels. */
  191475. void PNGAPI
  191476. png_set_tRNS_to_alpha(png_structp png_ptr)
  191477. {
  191478. png_debug(1, "in png_set_tRNS_to_alpha\n");
  191479. png_ptr->transformations |= (PNG_EXPAND | PNG_EXPAND_tRNS);
  191480. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191481. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  191482. #endif
  191483. }
  191484. #endif /* defined(PNG_READ_EXPAND_SUPPORTED) */
  191485. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191486. void PNGAPI
  191487. png_set_gray_to_rgb(png_structp png_ptr)
  191488. {
  191489. png_debug(1, "in png_set_gray_to_rgb\n");
  191490. png_ptr->transformations |= PNG_GRAY_TO_RGB;
  191491. #ifdef PNG_WARN_UNINITIALIZED_ROW
  191492. png_ptr->flags &= ~PNG_FLAG_ROW_INIT;
  191493. #endif
  191494. }
  191495. #endif
  191496. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  191497. #if defined(PNG_FLOATING_POINT_SUPPORTED)
  191498. /* Convert a RGB image to a grayscale of the same width. This allows us,
  191499. * for example, to convert a 24 bpp RGB image into an 8 bpp grayscale image.
  191500. */
  191501. void PNGAPI
  191502. png_set_rgb_to_gray(png_structp png_ptr, int error_action, double red,
  191503. double green)
  191504. {
  191505. int red_fixed = (int)((float)red*100000.0 + 0.5);
  191506. int green_fixed = (int)((float)green*100000.0 + 0.5);
  191507. if(png_ptr == NULL) return;
  191508. png_set_rgb_to_gray_fixed(png_ptr, error_action, red_fixed, green_fixed);
  191509. }
  191510. #endif
  191511. void PNGAPI
  191512. png_set_rgb_to_gray_fixed(png_structp png_ptr, int error_action,
  191513. png_fixed_point red, png_fixed_point green)
  191514. {
  191515. png_debug(1, "in png_set_rgb_to_gray\n");
  191516. if(png_ptr == NULL) return;
  191517. switch(error_action)
  191518. {
  191519. case 1: png_ptr->transformations |= PNG_RGB_TO_GRAY;
  191520. break;
  191521. case 2: png_ptr->transformations |= PNG_RGB_TO_GRAY_WARN;
  191522. break;
  191523. case 3: png_ptr->transformations |= PNG_RGB_TO_GRAY_ERR;
  191524. }
  191525. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191526. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191527. png_ptr->transformations |= PNG_EXPAND;
  191528. #else
  191529. {
  191530. png_warning(png_ptr, "Cannot do RGB_TO_GRAY without EXPAND_SUPPORTED.");
  191531. png_ptr->transformations &= ~PNG_RGB_TO_GRAY;
  191532. }
  191533. #endif
  191534. {
  191535. png_uint_16 red_int, green_int;
  191536. if(red < 0 || green < 0)
  191537. {
  191538. red_int = 6968; /* .212671 * 32768 + .5 */
  191539. green_int = 23434; /* .715160 * 32768 + .5 */
  191540. }
  191541. else if(red + green < 100000L)
  191542. {
  191543. red_int = (png_uint_16)(((png_uint_32)red*32768L)/100000L);
  191544. green_int = (png_uint_16)(((png_uint_32)green*32768L)/100000L);
  191545. }
  191546. else
  191547. {
  191548. png_warning(png_ptr, "ignoring out of range rgb_to_gray coefficients");
  191549. red_int = 6968;
  191550. green_int = 23434;
  191551. }
  191552. png_ptr->rgb_to_gray_red_coeff = red_int;
  191553. png_ptr->rgb_to_gray_green_coeff = green_int;
  191554. png_ptr->rgb_to_gray_blue_coeff = (png_uint_16)(32768-red_int-green_int);
  191555. }
  191556. }
  191557. #endif
  191558. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  191559. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  191560. defined(PNG_LEGACY_SUPPORTED)
  191561. void PNGAPI
  191562. png_set_read_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  191563. read_user_transform_fn)
  191564. {
  191565. png_debug(1, "in png_set_read_user_transform_fn\n");
  191566. if(png_ptr == NULL) return;
  191567. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  191568. png_ptr->transformations |= PNG_USER_TRANSFORM;
  191569. png_ptr->read_user_transform_fn = read_user_transform_fn;
  191570. #endif
  191571. #ifdef PNG_LEGACY_SUPPORTED
  191572. if(read_user_transform_fn)
  191573. png_warning(png_ptr,
  191574. "This version of libpng does not support user transforms");
  191575. #endif
  191576. }
  191577. #endif
  191578. /* Initialize everything needed for the read. This includes modifying
  191579. * the palette.
  191580. */
  191581. void /* PRIVATE */
  191582. png_init_read_transformations(png_structp png_ptr)
  191583. {
  191584. png_debug(1, "in png_init_read_transformations\n");
  191585. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  191586. if(png_ptr != NULL)
  191587. #endif
  191588. {
  191589. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || defined(PNG_READ_SHIFT_SUPPORTED) \
  191590. || defined(PNG_READ_GAMMA_SUPPORTED)
  191591. int color_type = png_ptr->color_type;
  191592. #endif
  191593. #if defined(PNG_READ_EXPAND_SUPPORTED) && defined(PNG_READ_BACKGROUND_SUPPORTED)
  191594. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  191595. /* Detect gray background and attempt to enable optimization
  191596. * for gray --> RGB case */
  191597. /* Note: if PNG_BACKGROUND_EXPAND is set and color_type is either RGB or
  191598. * RGB_ALPHA (in which case need_expand is superfluous anyway), the
  191599. * background color might actually be gray yet not be flagged as such.
  191600. * This is not a problem for the current code, which uses
  191601. * PNG_BACKGROUND_IS_GRAY only to decide when to do the
  191602. * png_do_gray_to_rgb() transformation.
  191603. */
  191604. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  191605. !(color_type & PNG_COLOR_MASK_COLOR))
  191606. {
  191607. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  191608. } else if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191609. !(png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  191610. (png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  191611. png_ptr->background.red == png_ptr->background.green &&
  191612. png_ptr->background.red == png_ptr->background.blue)
  191613. {
  191614. png_ptr->mode |= PNG_BACKGROUND_IS_GRAY;
  191615. png_ptr->background.gray = png_ptr->background.red;
  191616. }
  191617. #endif
  191618. if ((png_ptr->transformations & PNG_BACKGROUND_EXPAND) &&
  191619. (png_ptr->transformations & PNG_EXPAND))
  191620. {
  191621. if (!(color_type & PNG_COLOR_MASK_COLOR)) /* i.e., GRAY or GRAY_ALPHA */
  191622. {
  191623. /* expand background and tRNS chunks */
  191624. switch (png_ptr->bit_depth)
  191625. {
  191626. case 1:
  191627. png_ptr->background.gray *= (png_uint_16)0xff;
  191628. png_ptr->background.red = png_ptr->background.green
  191629. = png_ptr->background.blue = png_ptr->background.gray;
  191630. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  191631. {
  191632. png_ptr->trans_values.gray *= (png_uint_16)0xff;
  191633. png_ptr->trans_values.red = png_ptr->trans_values.green
  191634. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  191635. }
  191636. break;
  191637. case 2:
  191638. png_ptr->background.gray *= (png_uint_16)0x55;
  191639. png_ptr->background.red = png_ptr->background.green
  191640. = png_ptr->background.blue = png_ptr->background.gray;
  191641. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  191642. {
  191643. png_ptr->trans_values.gray *= (png_uint_16)0x55;
  191644. png_ptr->trans_values.red = png_ptr->trans_values.green
  191645. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  191646. }
  191647. break;
  191648. case 4:
  191649. png_ptr->background.gray *= (png_uint_16)0x11;
  191650. png_ptr->background.red = png_ptr->background.green
  191651. = png_ptr->background.blue = png_ptr->background.gray;
  191652. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  191653. {
  191654. png_ptr->trans_values.gray *= (png_uint_16)0x11;
  191655. png_ptr->trans_values.red = png_ptr->trans_values.green
  191656. = png_ptr->trans_values.blue = png_ptr->trans_values.gray;
  191657. }
  191658. break;
  191659. case 8:
  191660. case 16:
  191661. png_ptr->background.red = png_ptr->background.green
  191662. = png_ptr->background.blue = png_ptr->background.gray;
  191663. break;
  191664. }
  191665. }
  191666. else if (color_type == PNG_COLOR_TYPE_PALETTE)
  191667. {
  191668. png_ptr->background.red =
  191669. png_ptr->palette[png_ptr->background.index].red;
  191670. png_ptr->background.green =
  191671. png_ptr->palette[png_ptr->background.index].green;
  191672. png_ptr->background.blue =
  191673. png_ptr->palette[png_ptr->background.index].blue;
  191674. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  191675. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  191676. {
  191677. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191678. if (!(png_ptr->transformations & PNG_EXPAND_tRNS))
  191679. #endif
  191680. {
  191681. /* invert the alpha channel (in tRNS) unless the pixels are
  191682. going to be expanded, in which case leave it for later */
  191683. int i,istop;
  191684. istop=(int)png_ptr->num_trans;
  191685. for (i=0; i<istop; i++)
  191686. png_ptr->trans[i] = (png_byte)(255 - png_ptr->trans[i]);
  191687. }
  191688. }
  191689. #endif
  191690. }
  191691. }
  191692. #endif
  191693. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  191694. png_ptr->background_1 = png_ptr->background;
  191695. #endif
  191696. #if defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  191697. if ((color_type == PNG_COLOR_TYPE_PALETTE && png_ptr->num_trans != 0)
  191698. && (fabs(png_ptr->screen_gamma * png_ptr->gamma - 1.0)
  191699. < PNG_GAMMA_THRESHOLD))
  191700. {
  191701. int i,k;
  191702. k=0;
  191703. for (i=0; i<png_ptr->num_trans; i++)
  191704. {
  191705. if (png_ptr->trans[i] != 0 && png_ptr->trans[i] != 0xff)
  191706. k=1; /* partial transparency is present */
  191707. }
  191708. if (k == 0)
  191709. png_ptr->transformations &= (~PNG_GAMMA);
  191710. }
  191711. if ((png_ptr->transformations & (PNG_GAMMA | PNG_RGB_TO_GRAY)) &&
  191712. png_ptr->gamma != 0.0)
  191713. {
  191714. png_build_gamma_table(png_ptr);
  191715. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191716. if (png_ptr->transformations & PNG_BACKGROUND)
  191717. {
  191718. if (color_type == PNG_COLOR_TYPE_PALETTE)
  191719. {
  191720. /* could skip if no transparency and
  191721. */
  191722. png_color back, back_1;
  191723. png_colorp palette = png_ptr->palette;
  191724. int num_palette = png_ptr->num_palette;
  191725. int i;
  191726. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  191727. {
  191728. back.red = png_ptr->gamma_table[png_ptr->background.red];
  191729. back.green = png_ptr->gamma_table[png_ptr->background.green];
  191730. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  191731. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  191732. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  191733. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  191734. }
  191735. else
  191736. {
  191737. double g, gs;
  191738. switch (png_ptr->background_gamma_type)
  191739. {
  191740. case PNG_BACKGROUND_GAMMA_SCREEN:
  191741. g = (png_ptr->screen_gamma);
  191742. gs = 1.0;
  191743. break;
  191744. case PNG_BACKGROUND_GAMMA_FILE:
  191745. g = 1.0 / (png_ptr->gamma);
  191746. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  191747. break;
  191748. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191749. g = 1.0 / (png_ptr->background_gamma);
  191750. gs = 1.0 / (png_ptr->background_gamma *
  191751. png_ptr->screen_gamma);
  191752. break;
  191753. default:
  191754. g = 1.0; /* back_1 */
  191755. gs = 1.0; /* back */
  191756. }
  191757. if ( fabs(gs - 1.0) < PNG_GAMMA_THRESHOLD)
  191758. {
  191759. back.red = (png_byte)png_ptr->background.red;
  191760. back.green = (png_byte)png_ptr->background.green;
  191761. back.blue = (png_byte)png_ptr->background.blue;
  191762. }
  191763. else
  191764. {
  191765. back.red = (png_byte)(pow(
  191766. (double)png_ptr->background.red/255, gs) * 255.0 + .5);
  191767. back.green = (png_byte)(pow(
  191768. (double)png_ptr->background.green/255, gs) * 255.0 + .5);
  191769. back.blue = (png_byte)(pow(
  191770. (double)png_ptr->background.blue/255, gs) * 255.0 + .5);
  191771. }
  191772. back_1.red = (png_byte)(pow(
  191773. (double)png_ptr->background.red/255, g) * 255.0 + .5);
  191774. back_1.green = (png_byte)(pow(
  191775. (double)png_ptr->background.green/255, g) * 255.0 + .5);
  191776. back_1.blue = (png_byte)(pow(
  191777. (double)png_ptr->background.blue/255, g) * 255.0 + .5);
  191778. }
  191779. for (i = 0; i < num_palette; i++)
  191780. {
  191781. if (i < (int)png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  191782. {
  191783. if (png_ptr->trans[i] == 0)
  191784. {
  191785. palette[i] = back;
  191786. }
  191787. else /* if (png_ptr->trans[i] != 0xff) */
  191788. {
  191789. png_byte v, w;
  191790. v = png_ptr->gamma_to_1[palette[i].red];
  191791. png_composite(w, v, png_ptr->trans[i], back_1.red);
  191792. palette[i].red = png_ptr->gamma_from_1[w];
  191793. v = png_ptr->gamma_to_1[palette[i].green];
  191794. png_composite(w, v, png_ptr->trans[i], back_1.green);
  191795. palette[i].green = png_ptr->gamma_from_1[w];
  191796. v = png_ptr->gamma_to_1[palette[i].blue];
  191797. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  191798. palette[i].blue = png_ptr->gamma_from_1[w];
  191799. }
  191800. }
  191801. else
  191802. {
  191803. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191804. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191805. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191806. }
  191807. }
  191808. }
  191809. /* if (png_ptr->background_gamma_type!=PNG_BACKGROUND_GAMMA_UNKNOWN) */
  191810. else
  191811. /* color_type != PNG_COLOR_TYPE_PALETTE */
  191812. {
  191813. double m = (double)(((png_uint_32)1 << png_ptr->bit_depth) - 1);
  191814. double g = 1.0;
  191815. double gs = 1.0;
  191816. switch (png_ptr->background_gamma_type)
  191817. {
  191818. case PNG_BACKGROUND_GAMMA_SCREEN:
  191819. g = (png_ptr->screen_gamma);
  191820. gs = 1.0;
  191821. break;
  191822. case PNG_BACKGROUND_GAMMA_FILE:
  191823. g = 1.0 / (png_ptr->gamma);
  191824. gs = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  191825. break;
  191826. case PNG_BACKGROUND_GAMMA_UNIQUE:
  191827. g = 1.0 / (png_ptr->background_gamma);
  191828. gs = 1.0 / (png_ptr->background_gamma *
  191829. png_ptr->screen_gamma);
  191830. break;
  191831. }
  191832. png_ptr->background_1.gray = (png_uint_16)(pow(
  191833. (double)png_ptr->background.gray / m, g) * m + .5);
  191834. png_ptr->background.gray = (png_uint_16)(pow(
  191835. (double)png_ptr->background.gray / m, gs) * m + .5);
  191836. if ((png_ptr->background.red != png_ptr->background.green) ||
  191837. (png_ptr->background.red != png_ptr->background.blue) ||
  191838. (png_ptr->background.red != png_ptr->background.gray))
  191839. {
  191840. /* RGB or RGBA with color background */
  191841. png_ptr->background_1.red = (png_uint_16)(pow(
  191842. (double)png_ptr->background.red / m, g) * m + .5);
  191843. png_ptr->background_1.green = (png_uint_16)(pow(
  191844. (double)png_ptr->background.green / m, g) * m + .5);
  191845. png_ptr->background_1.blue = (png_uint_16)(pow(
  191846. (double)png_ptr->background.blue / m, g) * m + .5);
  191847. png_ptr->background.red = (png_uint_16)(pow(
  191848. (double)png_ptr->background.red / m, gs) * m + .5);
  191849. png_ptr->background.green = (png_uint_16)(pow(
  191850. (double)png_ptr->background.green / m, gs) * m + .5);
  191851. png_ptr->background.blue = (png_uint_16)(pow(
  191852. (double)png_ptr->background.blue / m, gs) * m + .5);
  191853. }
  191854. else
  191855. {
  191856. /* GRAY, GRAY ALPHA, RGB, or RGBA with gray background */
  191857. png_ptr->background_1.red = png_ptr->background_1.green
  191858. = png_ptr->background_1.blue = png_ptr->background_1.gray;
  191859. png_ptr->background.red = png_ptr->background.green
  191860. = png_ptr->background.blue = png_ptr->background.gray;
  191861. }
  191862. }
  191863. }
  191864. else
  191865. /* transformation does not include PNG_BACKGROUND */
  191866. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191867. if (color_type == PNG_COLOR_TYPE_PALETTE)
  191868. {
  191869. png_colorp palette = png_ptr->palette;
  191870. int num_palette = png_ptr->num_palette;
  191871. int i;
  191872. for (i = 0; i < num_palette; i++)
  191873. {
  191874. palette[i].red = png_ptr->gamma_table[palette[i].red];
  191875. palette[i].green = png_ptr->gamma_table[palette[i].green];
  191876. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  191877. }
  191878. }
  191879. }
  191880. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191881. else
  191882. #endif
  191883. #endif /* PNG_READ_GAMMA_SUPPORTED && PNG_FLOATING_POINT_SUPPORTED */
  191884. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191885. /* No GAMMA transformation */
  191886. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  191887. (color_type == PNG_COLOR_TYPE_PALETTE))
  191888. {
  191889. int i;
  191890. int istop = (int)png_ptr->num_trans;
  191891. png_color back;
  191892. png_colorp palette = png_ptr->palette;
  191893. back.red = (png_byte)png_ptr->background.red;
  191894. back.green = (png_byte)png_ptr->background.green;
  191895. back.blue = (png_byte)png_ptr->background.blue;
  191896. for (i = 0; i < istop; i++)
  191897. {
  191898. if (png_ptr->trans[i] == 0)
  191899. {
  191900. palette[i] = back;
  191901. }
  191902. else if (png_ptr->trans[i] != 0xff)
  191903. {
  191904. /* The png_composite() macro is defined in png.h */
  191905. png_composite(palette[i].red, palette[i].red,
  191906. png_ptr->trans[i], back.red);
  191907. png_composite(palette[i].green, palette[i].green,
  191908. png_ptr->trans[i], back.green);
  191909. png_composite(palette[i].blue, palette[i].blue,
  191910. png_ptr->trans[i], back.blue);
  191911. }
  191912. }
  191913. }
  191914. #endif /* PNG_READ_BACKGROUND_SUPPORTED */
  191915. #if defined(PNG_READ_SHIFT_SUPPORTED)
  191916. if ((png_ptr->transformations & PNG_SHIFT) &&
  191917. (color_type == PNG_COLOR_TYPE_PALETTE))
  191918. {
  191919. png_uint_16 i;
  191920. png_uint_16 istop = png_ptr->num_palette;
  191921. int sr = 8 - png_ptr->sig_bit.red;
  191922. int sg = 8 - png_ptr->sig_bit.green;
  191923. int sb = 8 - png_ptr->sig_bit.blue;
  191924. if (sr < 0 || sr > 8)
  191925. sr = 0;
  191926. if (sg < 0 || sg > 8)
  191927. sg = 0;
  191928. if (sb < 0 || sb > 8)
  191929. sb = 0;
  191930. for (i = 0; i < istop; i++)
  191931. {
  191932. png_ptr->palette[i].red >>= sr;
  191933. png_ptr->palette[i].green >>= sg;
  191934. png_ptr->palette[i].blue >>= sb;
  191935. }
  191936. }
  191937. #endif /* PNG_READ_SHIFT_SUPPORTED */
  191938. }
  191939. #if !defined(PNG_READ_GAMMA_SUPPORTED) && !defined(PNG_READ_SHIFT_SUPPORTED) \
  191940. && !defined(PNG_READ_BACKGROUND_SUPPORTED)
  191941. if(png_ptr)
  191942. return;
  191943. #endif
  191944. }
  191945. /* Modify the info structure to reflect the transformations. The
  191946. * info should be updated so a PNG file could be written with it,
  191947. * assuming the transformations result in valid PNG data.
  191948. */
  191949. void /* PRIVATE */
  191950. png_read_transform_info(png_structp png_ptr, png_infop info_ptr)
  191951. {
  191952. png_debug(1, "in png_read_transform_info\n");
  191953. #if defined(PNG_READ_EXPAND_SUPPORTED)
  191954. if (png_ptr->transformations & PNG_EXPAND)
  191955. {
  191956. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  191957. {
  191958. if (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND_tRNS))
  191959. info_ptr->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  191960. else
  191961. info_ptr->color_type = PNG_COLOR_TYPE_RGB;
  191962. info_ptr->bit_depth = 8;
  191963. info_ptr->num_trans = 0;
  191964. }
  191965. else
  191966. {
  191967. if (png_ptr->num_trans)
  191968. {
  191969. if (png_ptr->transformations & PNG_EXPAND_tRNS)
  191970. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  191971. else
  191972. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  191973. }
  191974. if (info_ptr->bit_depth < 8)
  191975. info_ptr->bit_depth = 8;
  191976. info_ptr->num_trans = 0;
  191977. }
  191978. }
  191979. #endif
  191980. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  191981. if (png_ptr->transformations & PNG_BACKGROUND)
  191982. {
  191983. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  191984. info_ptr->num_trans = 0;
  191985. info_ptr->background = png_ptr->background;
  191986. }
  191987. #endif
  191988. #if defined(PNG_READ_GAMMA_SUPPORTED)
  191989. if (png_ptr->transformations & PNG_GAMMA)
  191990. {
  191991. #ifdef PNG_FLOATING_POINT_SUPPORTED
  191992. info_ptr->gamma = png_ptr->gamma;
  191993. #endif
  191994. #ifdef PNG_FIXED_POINT_SUPPORTED
  191995. info_ptr->int_gamma = png_ptr->int_gamma;
  191996. #endif
  191997. }
  191998. #endif
  191999. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  192000. if ((png_ptr->transformations & PNG_16_TO_8) && (info_ptr->bit_depth == 16))
  192001. info_ptr->bit_depth = 8;
  192002. #endif
  192003. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192004. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  192005. info_ptr->color_type |= PNG_COLOR_MASK_COLOR;
  192006. #endif
  192007. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192008. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  192009. info_ptr->color_type &= ~PNG_COLOR_MASK_COLOR;
  192010. #endif
  192011. #if defined(PNG_READ_DITHER_SUPPORTED)
  192012. if (png_ptr->transformations & PNG_DITHER)
  192013. {
  192014. if (((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  192015. (info_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)) &&
  192016. png_ptr->palette_lookup && info_ptr->bit_depth == 8)
  192017. {
  192018. info_ptr->color_type = PNG_COLOR_TYPE_PALETTE;
  192019. }
  192020. }
  192021. #endif
  192022. #if defined(PNG_READ_PACK_SUPPORTED)
  192023. if ((png_ptr->transformations & PNG_PACK) && (info_ptr->bit_depth < 8))
  192024. info_ptr->bit_depth = 8;
  192025. #endif
  192026. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  192027. info_ptr->channels = 1;
  192028. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  192029. info_ptr->channels = 3;
  192030. else
  192031. info_ptr->channels = 1;
  192032. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  192033. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  192034. info_ptr->color_type &= ~PNG_COLOR_MASK_ALPHA;
  192035. #endif
  192036. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  192037. info_ptr->channels++;
  192038. #if defined(PNG_READ_FILLER_SUPPORTED)
  192039. /* STRIP_ALPHA and FILLER allowed: MASK_ALPHA bit stripped above */
  192040. if ((png_ptr->transformations & PNG_FILLER) &&
  192041. ((info_ptr->color_type == PNG_COLOR_TYPE_RGB) ||
  192042. (info_ptr->color_type == PNG_COLOR_TYPE_GRAY)))
  192043. {
  192044. info_ptr->channels++;
  192045. /* if adding a true alpha channel not just filler */
  192046. #if !defined(PNG_1_0_X)
  192047. if (png_ptr->transformations & PNG_ADD_ALPHA)
  192048. info_ptr->color_type |= PNG_COLOR_MASK_ALPHA;
  192049. #endif
  192050. }
  192051. #endif
  192052. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED) && \
  192053. defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  192054. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  192055. {
  192056. if(info_ptr->bit_depth < png_ptr->user_transform_depth)
  192057. info_ptr->bit_depth = png_ptr->user_transform_depth;
  192058. if(info_ptr->channels < png_ptr->user_transform_channels)
  192059. info_ptr->channels = png_ptr->user_transform_channels;
  192060. }
  192061. #endif
  192062. info_ptr->pixel_depth = (png_byte)(info_ptr->channels *
  192063. info_ptr->bit_depth);
  192064. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,info_ptr->width);
  192065. #if !defined(PNG_READ_EXPAND_SUPPORTED)
  192066. if(png_ptr)
  192067. return;
  192068. #endif
  192069. }
  192070. /* Transform the row. The order of transformations is significant,
  192071. * and is very touchy. If you add a transformation, take care to
  192072. * decide how it fits in with the other transformations here.
  192073. */
  192074. void /* PRIVATE */
  192075. png_do_read_transformations(png_structp png_ptr)
  192076. {
  192077. png_debug(1, "in png_do_read_transformations\n");
  192078. if (png_ptr->row_buf == NULL)
  192079. {
  192080. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  192081. char msg[50];
  192082. png_snprintf2(msg, 50,
  192083. "NULL row buffer for row %ld, pass %d", png_ptr->row_number,
  192084. png_ptr->pass);
  192085. png_error(png_ptr, msg);
  192086. #else
  192087. png_error(png_ptr, "NULL row buffer");
  192088. #endif
  192089. }
  192090. #ifdef PNG_WARN_UNINITIALIZED_ROW
  192091. if (!(png_ptr->flags & PNG_FLAG_ROW_INIT))
  192092. /* Application has failed to call either png_read_start_image()
  192093. * or png_read_update_info() after setting transforms that expand
  192094. * pixels. This check added to libpng-1.2.19 */
  192095. #if (PNG_WARN_UNINITIALIZED_ROW==1)
  192096. png_error(png_ptr, "Uninitialized row");
  192097. #else
  192098. png_warning(png_ptr, "Uninitialized row");
  192099. #endif
  192100. #endif
  192101. #if defined(PNG_READ_EXPAND_SUPPORTED)
  192102. if (png_ptr->transformations & PNG_EXPAND)
  192103. {
  192104. if (png_ptr->row_info.color_type == PNG_COLOR_TYPE_PALETTE)
  192105. {
  192106. png_do_expand_palette(&(png_ptr->row_info), png_ptr->row_buf + 1,
  192107. png_ptr->palette, png_ptr->trans, png_ptr->num_trans);
  192108. }
  192109. else
  192110. {
  192111. if (png_ptr->num_trans &&
  192112. (png_ptr->transformations & PNG_EXPAND_tRNS))
  192113. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  192114. &(png_ptr->trans_values));
  192115. else
  192116. png_do_expand(&(png_ptr->row_info), png_ptr->row_buf + 1,
  192117. NULL);
  192118. }
  192119. }
  192120. #endif
  192121. #if defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  192122. if (png_ptr->flags & PNG_FLAG_STRIP_ALPHA)
  192123. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  192124. PNG_FLAG_FILLER_AFTER | (png_ptr->flags & PNG_FLAG_STRIP_ALPHA));
  192125. #endif
  192126. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192127. if (png_ptr->transformations & PNG_RGB_TO_GRAY)
  192128. {
  192129. int rgb_error =
  192130. png_do_rgb_to_gray(png_ptr, &(png_ptr->row_info), png_ptr->row_buf + 1);
  192131. if(rgb_error)
  192132. {
  192133. png_ptr->rgb_to_gray_status=1;
  192134. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  192135. PNG_RGB_TO_GRAY_WARN)
  192136. png_warning(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  192137. if((png_ptr->transformations & PNG_RGB_TO_GRAY) ==
  192138. PNG_RGB_TO_GRAY_ERR)
  192139. png_error(png_ptr, "png_do_rgb_to_gray found nongray pixel");
  192140. }
  192141. }
  192142. #endif
  192143. /*
  192144. From Andreas Dilger e-mail to png-implement, 26 March 1998:
  192145. In most cases, the "simple transparency" should be done prior to doing
  192146. gray-to-RGB, or you will have to test 3x as many bytes to check if a
  192147. pixel is transparent. You would also need to make sure that the
  192148. transparency information is upgraded to RGB.
  192149. To summarize, the current flow is:
  192150. - Gray + simple transparency -> compare 1 or 2 gray bytes and composite
  192151. with background "in place" if transparent,
  192152. convert to RGB if necessary
  192153. - Gray + alpha -> composite with gray background and remove alpha bytes,
  192154. convert to RGB if necessary
  192155. To support RGB backgrounds for gray images we need:
  192156. - Gray + simple transparency -> convert to RGB + simple transparency, compare
  192157. 3 or 6 bytes and composite with background
  192158. "in place" if transparent (3x compare/pixel
  192159. compared to doing composite with gray bkgrnd)
  192160. - Gray + alpha -> convert to RGB + alpha, composite with background and
  192161. remove alpha bytes (3x float operations/pixel
  192162. compared with composite on gray background)
  192163. Greg's change will do this. The reason it wasn't done before is for
  192164. performance, as this increases the per-pixel operations. If we would check
  192165. in advance if the background was gray or RGB, and position the gray-to-RGB
  192166. transform appropriately, then it would save a lot of work/time.
  192167. */
  192168. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192169. /* if gray -> RGB, do so now only if background is non-gray; else do later
  192170. * for performance reasons */
  192171. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  192172. !(png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  192173. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  192174. #endif
  192175. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192176. if ((png_ptr->transformations & PNG_BACKGROUND) &&
  192177. ((png_ptr->num_trans != 0 ) ||
  192178. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA)))
  192179. png_do_background(&(png_ptr->row_info), png_ptr->row_buf + 1,
  192180. &(png_ptr->trans_values), &(png_ptr->background)
  192181. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192182. , &(png_ptr->background_1),
  192183. png_ptr->gamma_table, png_ptr->gamma_from_1,
  192184. png_ptr->gamma_to_1, png_ptr->gamma_16_table,
  192185. png_ptr->gamma_16_from_1, png_ptr->gamma_16_to_1,
  192186. png_ptr->gamma_shift
  192187. #endif
  192188. );
  192189. #endif
  192190. #if defined(PNG_READ_GAMMA_SUPPORTED)
  192191. if ((png_ptr->transformations & PNG_GAMMA) &&
  192192. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  192193. !((png_ptr->transformations & PNG_BACKGROUND) &&
  192194. ((png_ptr->num_trans != 0) ||
  192195. (png_ptr->color_type & PNG_COLOR_MASK_ALPHA))) &&
  192196. #endif
  192197. (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE))
  192198. png_do_gamma(&(png_ptr->row_info), png_ptr->row_buf + 1,
  192199. png_ptr->gamma_table, png_ptr->gamma_16_table,
  192200. png_ptr->gamma_shift);
  192201. #endif
  192202. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  192203. if (png_ptr->transformations & PNG_16_TO_8)
  192204. png_do_chop(&(png_ptr->row_info), png_ptr->row_buf + 1);
  192205. #endif
  192206. #if defined(PNG_READ_DITHER_SUPPORTED)
  192207. if (png_ptr->transformations & PNG_DITHER)
  192208. {
  192209. png_do_dither((png_row_infop)&(png_ptr->row_info), png_ptr->row_buf + 1,
  192210. png_ptr->palette_lookup, png_ptr->dither_index);
  192211. if(png_ptr->row_info.rowbytes == (png_uint_32)0)
  192212. png_error(png_ptr, "png_do_dither returned rowbytes=0");
  192213. }
  192214. #endif
  192215. #if defined(PNG_READ_INVERT_SUPPORTED)
  192216. if (png_ptr->transformations & PNG_INVERT_MONO)
  192217. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  192218. #endif
  192219. #if defined(PNG_READ_SHIFT_SUPPORTED)
  192220. if (png_ptr->transformations & PNG_SHIFT)
  192221. png_do_unshift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  192222. &(png_ptr->shift));
  192223. #endif
  192224. #if defined(PNG_READ_PACK_SUPPORTED)
  192225. if (png_ptr->transformations & PNG_PACK)
  192226. png_do_unpack(&(png_ptr->row_info), png_ptr->row_buf + 1);
  192227. #endif
  192228. #if defined(PNG_READ_BGR_SUPPORTED)
  192229. if (png_ptr->transformations & PNG_BGR)
  192230. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  192231. #endif
  192232. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  192233. if (png_ptr->transformations & PNG_PACKSWAP)
  192234. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  192235. #endif
  192236. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192237. /* if gray -> RGB, do so now only if we did not do so above */
  192238. if ((png_ptr->transformations & PNG_GRAY_TO_RGB) &&
  192239. (png_ptr->mode & PNG_BACKGROUND_IS_GRAY))
  192240. png_do_gray_to_rgb(&(png_ptr->row_info), png_ptr->row_buf + 1);
  192241. #endif
  192242. #if defined(PNG_READ_FILLER_SUPPORTED)
  192243. if (png_ptr->transformations & PNG_FILLER)
  192244. png_do_read_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  192245. (png_uint_32)png_ptr->filler, png_ptr->flags);
  192246. #endif
  192247. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  192248. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  192249. png_do_read_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  192250. #endif
  192251. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  192252. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  192253. png_do_read_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  192254. #endif
  192255. #if defined(PNG_READ_SWAP_SUPPORTED)
  192256. if (png_ptr->transformations & PNG_SWAP_BYTES)
  192257. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  192258. #endif
  192259. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED)
  192260. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  192261. {
  192262. if(png_ptr->read_user_transform_fn != NULL)
  192263. (*(png_ptr->read_user_transform_fn)) /* user read transform function */
  192264. (png_ptr, /* png_ptr */
  192265. &(png_ptr->row_info), /* row_info: */
  192266. /* png_uint_32 width; width of row */
  192267. /* png_uint_32 rowbytes; number of bytes in row */
  192268. /* png_byte color_type; color type of pixels */
  192269. /* png_byte bit_depth; bit depth of samples */
  192270. /* png_byte channels; number of channels (1-4) */
  192271. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  192272. png_ptr->row_buf + 1); /* start of pixel data for row */
  192273. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  192274. if(png_ptr->user_transform_depth)
  192275. png_ptr->row_info.bit_depth = png_ptr->user_transform_depth;
  192276. if(png_ptr->user_transform_channels)
  192277. png_ptr->row_info.channels = png_ptr->user_transform_channels;
  192278. #endif
  192279. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  192280. png_ptr->row_info.channels);
  192281. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  192282. png_ptr->row_info.width);
  192283. }
  192284. #endif
  192285. }
  192286. #if defined(PNG_READ_PACK_SUPPORTED)
  192287. /* Unpack pixels of 1, 2, or 4 bits per pixel into 1 byte per pixel,
  192288. * without changing the actual values. Thus, if you had a row with
  192289. * a bit depth of 1, you would end up with bytes that only contained
  192290. * the numbers 0 or 1. If you would rather they contain 0 and 255, use
  192291. * png_do_shift() after this.
  192292. */
  192293. void /* PRIVATE */
  192294. png_do_unpack(png_row_infop row_info, png_bytep row)
  192295. {
  192296. png_debug(1, "in png_do_unpack\n");
  192297. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192298. if (row != NULL && row_info != NULL && row_info->bit_depth < 8)
  192299. #else
  192300. if (row_info->bit_depth < 8)
  192301. #endif
  192302. {
  192303. png_uint_32 i;
  192304. png_uint_32 row_width=row_info->width;
  192305. switch (row_info->bit_depth)
  192306. {
  192307. case 1:
  192308. {
  192309. png_bytep sp = row + (png_size_t)((row_width - 1) >> 3);
  192310. png_bytep dp = row + (png_size_t)row_width - 1;
  192311. png_uint_32 shift = 7 - (int)((row_width + 7) & 0x07);
  192312. for (i = 0; i < row_width; i++)
  192313. {
  192314. *dp = (png_byte)((*sp >> shift) & 0x01);
  192315. if (shift == 7)
  192316. {
  192317. shift = 0;
  192318. sp--;
  192319. }
  192320. else
  192321. shift++;
  192322. dp--;
  192323. }
  192324. break;
  192325. }
  192326. case 2:
  192327. {
  192328. png_bytep sp = row + (png_size_t)((row_width - 1) >> 2);
  192329. png_bytep dp = row + (png_size_t)row_width - 1;
  192330. png_uint_32 shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  192331. for (i = 0; i < row_width; i++)
  192332. {
  192333. *dp = (png_byte)((*sp >> shift) & 0x03);
  192334. if (shift == 6)
  192335. {
  192336. shift = 0;
  192337. sp--;
  192338. }
  192339. else
  192340. shift += 2;
  192341. dp--;
  192342. }
  192343. break;
  192344. }
  192345. case 4:
  192346. {
  192347. png_bytep sp = row + (png_size_t)((row_width - 1) >> 1);
  192348. png_bytep dp = row + (png_size_t)row_width - 1;
  192349. png_uint_32 shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  192350. for (i = 0; i < row_width; i++)
  192351. {
  192352. *dp = (png_byte)((*sp >> shift) & 0x0f);
  192353. if (shift == 4)
  192354. {
  192355. shift = 0;
  192356. sp--;
  192357. }
  192358. else
  192359. shift = 4;
  192360. dp--;
  192361. }
  192362. break;
  192363. }
  192364. }
  192365. row_info->bit_depth = 8;
  192366. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  192367. row_info->rowbytes = row_width * row_info->channels;
  192368. }
  192369. }
  192370. #endif
  192371. #if defined(PNG_READ_SHIFT_SUPPORTED)
  192372. /* Reverse the effects of png_do_shift. This routine merely shifts the
  192373. * pixels back to their significant bits values. Thus, if you have
  192374. * a row of bit depth 8, but only 5 are significant, this will shift
  192375. * the values back to 0 through 31.
  192376. */
  192377. void /* PRIVATE */
  192378. png_do_unshift(png_row_infop row_info, png_bytep row, png_color_8p sig_bits)
  192379. {
  192380. png_debug(1, "in png_do_unshift\n");
  192381. if (
  192382. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192383. row != NULL && row_info != NULL && sig_bits != NULL &&
  192384. #endif
  192385. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  192386. {
  192387. int shift[4];
  192388. int channels = 0;
  192389. int c;
  192390. png_uint_16 value = 0;
  192391. png_uint_32 row_width = row_info->width;
  192392. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  192393. {
  192394. shift[channels++] = row_info->bit_depth - sig_bits->red;
  192395. shift[channels++] = row_info->bit_depth - sig_bits->green;
  192396. shift[channels++] = row_info->bit_depth - sig_bits->blue;
  192397. }
  192398. else
  192399. {
  192400. shift[channels++] = row_info->bit_depth - sig_bits->gray;
  192401. }
  192402. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  192403. {
  192404. shift[channels++] = row_info->bit_depth - sig_bits->alpha;
  192405. }
  192406. for (c = 0; c < channels; c++)
  192407. {
  192408. if (shift[c] <= 0)
  192409. shift[c] = 0;
  192410. else
  192411. value = 1;
  192412. }
  192413. if (!value)
  192414. return;
  192415. switch (row_info->bit_depth)
  192416. {
  192417. case 2:
  192418. {
  192419. png_bytep bp;
  192420. png_uint_32 i;
  192421. png_uint_32 istop = row_info->rowbytes;
  192422. for (bp = row, i = 0; i < istop; i++)
  192423. {
  192424. *bp >>= 1;
  192425. *bp++ &= 0x55;
  192426. }
  192427. break;
  192428. }
  192429. case 4:
  192430. {
  192431. png_bytep bp = row;
  192432. png_uint_32 i;
  192433. png_uint_32 istop = row_info->rowbytes;
  192434. png_byte mask = (png_byte)((((int)0xf0 >> shift[0]) & (int)0xf0) |
  192435. (png_byte)((int)0xf >> shift[0]));
  192436. for (i = 0; i < istop; i++)
  192437. {
  192438. *bp >>= shift[0];
  192439. *bp++ &= mask;
  192440. }
  192441. break;
  192442. }
  192443. case 8:
  192444. {
  192445. png_bytep bp = row;
  192446. png_uint_32 i;
  192447. png_uint_32 istop = row_width * channels;
  192448. for (i = 0; i < istop; i++)
  192449. {
  192450. *bp++ >>= shift[i%channels];
  192451. }
  192452. break;
  192453. }
  192454. case 16:
  192455. {
  192456. png_bytep bp = row;
  192457. png_uint_32 i;
  192458. png_uint_32 istop = channels * row_width;
  192459. for (i = 0; i < istop; i++)
  192460. {
  192461. value = (png_uint_16)((*bp << 8) + *(bp + 1));
  192462. value >>= shift[i%channels];
  192463. *bp++ = (png_byte)(value >> 8);
  192464. *bp++ = (png_byte)(value & 0xff);
  192465. }
  192466. break;
  192467. }
  192468. }
  192469. }
  192470. }
  192471. #endif
  192472. #if defined(PNG_READ_16_TO_8_SUPPORTED)
  192473. /* chop rows of bit depth 16 down to 8 */
  192474. void /* PRIVATE */
  192475. png_do_chop(png_row_infop row_info, png_bytep row)
  192476. {
  192477. png_debug(1, "in png_do_chop\n");
  192478. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192479. if (row != NULL && row_info != NULL && row_info->bit_depth == 16)
  192480. #else
  192481. if (row_info->bit_depth == 16)
  192482. #endif
  192483. {
  192484. png_bytep sp = row;
  192485. png_bytep dp = row;
  192486. png_uint_32 i;
  192487. png_uint_32 istop = row_info->width * row_info->channels;
  192488. for (i = 0; i<istop; i++, sp += 2, dp++)
  192489. {
  192490. #if defined(PNG_READ_16_TO_8_ACCURATE_SCALE_SUPPORTED)
  192491. /* This does a more accurate scaling of the 16-bit color
  192492. * value, rather than a simple low-byte truncation.
  192493. *
  192494. * What the ideal calculation should be:
  192495. * *dp = (((((png_uint_32)(*sp) << 8) |
  192496. * (png_uint_32)(*(sp + 1))) * 255 + 127) / (png_uint_32)65535L;
  192497. *
  192498. * GRR: no, I think this is what it really should be:
  192499. * *dp = (((((png_uint_32)(*sp) << 8) |
  192500. * (png_uint_32)(*(sp + 1))) + 128L) / (png_uint_32)257L;
  192501. *
  192502. * GRR: here's the exact calculation with shifts:
  192503. * temp = (((png_uint_32)(*sp) << 8) | (png_uint_32)(*(sp + 1))) + 128L;
  192504. * *dp = (temp - (temp >> 8)) >> 8;
  192505. *
  192506. * Approximate calculation with shift/add instead of multiply/divide:
  192507. * *dp = ((((png_uint_32)(*sp) << 8) |
  192508. * (png_uint_32)((int)(*(sp + 1)) - *sp)) + 128) >> 8;
  192509. *
  192510. * What we actually do to avoid extra shifting and conversion:
  192511. */
  192512. *dp = *sp + ((((int)(*(sp + 1)) - *sp) > 128) ? 1 : 0);
  192513. #else
  192514. /* Simply discard the low order byte */
  192515. *dp = *sp;
  192516. #endif
  192517. }
  192518. row_info->bit_depth = 8;
  192519. row_info->pixel_depth = (png_byte)(8 * row_info->channels);
  192520. row_info->rowbytes = row_info->width * row_info->channels;
  192521. }
  192522. }
  192523. #endif
  192524. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED)
  192525. void /* PRIVATE */
  192526. png_do_read_swap_alpha(png_row_infop row_info, png_bytep row)
  192527. {
  192528. png_debug(1, "in png_do_read_swap_alpha\n");
  192529. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192530. if (row != NULL && row_info != NULL)
  192531. #endif
  192532. {
  192533. png_uint_32 row_width = row_info->width;
  192534. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192535. {
  192536. /* This converts from RGBA to ARGB */
  192537. if (row_info->bit_depth == 8)
  192538. {
  192539. png_bytep sp = row + row_info->rowbytes;
  192540. png_bytep dp = sp;
  192541. png_byte save;
  192542. png_uint_32 i;
  192543. for (i = 0; i < row_width; i++)
  192544. {
  192545. save = *(--sp);
  192546. *(--dp) = *(--sp);
  192547. *(--dp) = *(--sp);
  192548. *(--dp) = *(--sp);
  192549. *(--dp) = save;
  192550. }
  192551. }
  192552. /* This converts from RRGGBBAA to AARRGGBB */
  192553. else
  192554. {
  192555. png_bytep sp = row + row_info->rowbytes;
  192556. png_bytep dp = sp;
  192557. png_byte save[2];
  192558. png_uint_32 i;
  192559. for (i = 0; i < row_width; i++)
  192560. {
  192561. save[0] = *(--sp);
  192562. save[1] = *(--sp);
  192563. *(--dp) = *(--sp);
  192564. *(--dp) = *(--sp);
  192565. *(--dp) = *(--sp);
  192566. *(--dp) = *(--sp);
  192567. *(--dp) = *(--sp);
  192568. *(--dp) = *(--sp);
  192569. *(--dp) = save[0];
  192570. *(--dp) = save[1];
  192571. }
  192572. }
  192573. }
  192574. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192575. {
  192576. /* This converts from GA to AG */
  192577. if (row_info->bit_depth == 8)
  192578. {
  192579. png_bytep sp = row + row_info->rowbytes;
  192580. png_bytep dp = sp;
  192581. png_byte save;
  192582. png_uint_32 i;
  192583. for (i = 0; i < row_width; i++)
  192584. {
  192585. save = *(--sp);
  192586. *(--dp) = *(--sp);
  192587. *(--dp) = save;
  192588. }
  192589. }
  192590. /* This converts from GGAA to AAGG */
  192591. else
  192592. {
  192593. png_bytep sp = row + row_info->rowbytes;
  192594. png_bytep dp = sp;
  192595. png_byte save[2];
  192596. png_uint_32 i;
  192597. for (i = 0; i < row_width; i++)
  192598. {
  192599. save[0] = *(--sp);
  192600. save[1] = *(--sp);
  192601. *(--dp) = *(--sp);
  192602. *(--dp) = *(--sp);
  192603. *(--dp) = save[0];
  192604. *(--dp) = save[1];
  192605. }
  192606. }
  192607. }
  192608. }
  192609. }
  192610. #endif
  192611. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED)
  192612. void /* PRIVATE */
  192613. png_do_read_invert_alpha(png_row_infop row_info, png_bytep row)
  192614. {
  192615. png_debug(1, "in png_do_read_invert_alpha\n");
  192616. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192617. if (row != NULL && row_info != NULL)
  192618. #endif
  192619. {
  192620. png_uint_32 row_width = row_info->width;
  192621. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  192622. {
  192623. /* This inverts the alpha channel in RGBA */
  192624. if (row_info->bit_depth == 8)
  192625. {
  192626. png_bytep sp = row + row_info->rowbytes;
  192627. png_bytep dp = sp;
  192628. png_uint_32 i;
  192629. for (i = 0; i < row_width; i++)
  192630. {
  192631. *(--dp) = (png_byte)(255 - *(--sp));
  192632. /* This does nothing:
  192633. *(--dp) = *(--sp);
  192634. *(--dp) = *(--sp);
  192635. *(--dp) = *(--sp);
  192636. We can replace it with:
  192637. */
  192638. sp-=3;
  192639. dp=sp;
  192640. }
  192641. }
  192642. /* This inverts the alpha channel in RRGGBBAA */
  192643. else
  192644. {
  192645. png_bytep sp = row + row_info->rowbytes;
  192646. png_bytep dp = sp;
  192647. png_uint_32 i;
  192648. for (i = 0; i < row_width; i++)
  192649. {
  192650. *(--dp) = (png_byte)(255 - *(--sp));
  192651. *(--dp) = (png_byte)(255 - *(--sp));
  192652. /* This does nothing:
  192653. *(--dp) = *(--sp);
  192654. *(--dp) = *(--sp);
  192655. *(--dp) = *(--sp);
  192656. *(--dp) = *(--sp);
  192657. *(--dp) = *(--sp);
  192658. *(--dp) = *(--sp);
  192659. We can replace it with:
  192660. */
  192661. sp-=6;
  192662. dp=sp;
  192663. }
  192664. }
  192665. }
  192666. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192667. {
  192668. /* This inverts the alpha channel in GA */
  192669. if (row_info->bit_depth == 8)
  192670. {
  192671. png_bytep sp = row + row_info->rowbytes;
  192672. png_bytep dp = sp;
  192673. png_uint_32 i;
  192674. for (i = 0; i < row_width; i++)
  192675. {
  192676. *(--dp) = (png_byte)(255 - *(--sp));
  192677. *(--dp) = *(--sp);
  192678. }
  192679. }
  192680. /* This inverts the alpha channel in GGAA */
  192681. else
  192682. {
  192683. png_bytep sp = row + row_info->rowbytes;
  192684. png_bytep dp = sp;
  192685. png_uint_32 i;
  192686. for (i = 0; i < row_width; i++)
  192687. {
  192688. *(--dp) = (png_byte)(255 - *(--sp));
  192689. *(--dp) = (png_byte)(255 - *(--sp));
  192690. /*
  192691. *(--dp) = *(--sp);
  192692. *(--dp) = *(--sp);
  192693. */
  192694. sp-=2;
  192695. dp=sp;
  192696. }
  192697. }
  192698. }
  192699. }
  192700. }
  192701. #endif
  192702. #if defined(PNG_READ_FILLER_SUPPORTED)
  192703. /* Add filler channel if we have RGB color */
  192704. void /* PRIVATE */
  192705. png_do_read_filler(png_row_infop row_info, png_bytep row,
  192706. png_uint_32 filler, png_uint_32 flags)
  192707. {
  192708. png_uint_32 i;
  192709. png_uint_32 row_width = row_info->width;
  192710. png_byte hi_filler = (png_byte)((filler>>8) & 0xff);
  192711. png_byte lo_filler = (png_byte)(filler & 0xff);
  192712. png_debug(1, "in png_do_read_filler\n");
  192713. if (
  192714. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192715. row != NULL && row_info != NULL &&
  192716. #endif
  192717. row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192718. {
  192719. if(row_info->bit_depth == 8)
  192720. {
  192721. /* This changes the data from G to GX */
  192722. if (flags & PNG_FLAG_FILLER_AFTER)
  192723. {
  192724. png_bytep sp = row + (png_size_t)row_width;
  192725. png_bytep dp = sp + (png_size_t)row_width;
  192726. for (i = 1; i < row_width; i++)
  192727. {
  192728. *(--dp) = lo_filler;
  192729. *(--dp) = *(--sp);
  192730. }
  192731. *(--dp) = lo_filler;
  192732. row_info->channels = 2;
  192733. row_info->pixel_depth = 16;
  192734. row_info->rowbytes = row_width * 2;
  192735. }
  192736. /* This changes the data from G to XG */
  192737. else
  192738. {
  192739. png_bytep sp = row + (png_size_t)row_width;
  192740. png_bytep dp = sp + (png_size_t)row_width;
  192741. for (i = 0; i < row_width; i++)
  192742. {
  192743. *(--dp) = *(--sp);
  192744. *(--dp) = lo_filler;
  192745. }
  192746. row_info->channels = 2;
  192747. row_info->pixel_depth = 16;
  192748. row_info->rowbytes = row_width * 2;
  192749. }
  192750. }
  192751. else if(row_info->bit_depth == 16)
  192752. {
  192753. /* This changes the data from GG to GGXX */
  192754. if (flags & PNG_FLAG_FILLER_AFTER)
  192755. {
  192756. png_bytep sp = row + (png_size_t)row_width * 2;
  192757. png_bytep dp = sp + (png_size_t)row_width * 2;
  192758. for (i = 1; i < row_width; i++)
  192759. {
  192760. *(--dp) = hi_filler;
  192761. *(--dp) = lo_filler;
  192762. *(--dp) = *(--sp);
  192763. *(--dp) = *(--sp);
  192764. }
  192765. *(--dp) = hi_filler;
  192766. *(--dp) = lo_filler;
  192767. row_info->channels = 2;
  192768. row_info->pixel_depth = 32;
  192769. row_info->rowbytes = row_width * 4;
  192770. }
  192771. /* This changes the data from GG to XXGG */
  192772. else
  192773. {
  192774. png_bytep sp = row + (png_size_t)row_width * 2;
  192775. png_bytep dp = sp + (png_size_t)row_width * 2;
  192776. for (i = 0; i < row_width; i++)
  192777. {
  192778. *(--dp) = *(--sp);
  192779. *(--dp) = *(--sp);
  192780. *(--dp) = hi_filler;
  192781. *(--dp) = lo_filler;
  192782. }
  192783. row_info->channels = 2;
  192784. row_info->pixel_depth = 32;
  192785. row_info->rowbytes = row_width * 4;
  192786. }
  192787. }
  192788. } /* COLOR_TYPE == GRAY */
  192789. else if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192790. {
  192791. if(row_info->bit_depth == 8)
  192792. {
  192793. /* This changes the data from RGB to RGBX */
  192794. if (flags & PNG_FLAG_FILLER_AFTER)
  192795. {
  192796. png_bytep sp = row + (png_size_t)row_width * 3;
  192797. png_bytep dp = sp + (png_size_t)row_width;
  192798. for (i = 1; i < row_width; i++)
  192799. {
  192800. *(--dp) = lo_filler;
  192801. *(--dp) = *(--sp);
  192802. *(--dp) = *(--sp);
  192803. *(--dp) = *(--sp);
  192804. }
  192805. *(--dp) = lo_filler;
  192806. row_info->channels = 4;
  192807. row_info->pixel_depth = 32;
  192808. row_info->rowbytes = row_width * 4;
  192809. }
  192810. /* This changes the data from RGB to XRGB */
  192811. else
  192812. {
  192813. png_bytep sp = row + (png_size_t)row_width * 3;
  192814. png_bytep dp = sp + (png_size_t)row_width;
  192815. for (i = 0; i < row_width; i++)
  192816. {
  192817. *(--dp) = *(--sp);
  192818. *(--dp) = *(--sp);
  192819. *(--dp) = *(--sp);
  192820. *(--dp) = lo_filler;
  192821. }
  192822. row_info->channels = 4;
  192823. row_info->pixel_depth = 32;
  192824. row_info->rowbytes = row_width * 4;
  192825. }
  192826. }
  192827. else if(row_info->bit_depth == 16)
  192828. {
  192829. /* This changes the data from RRGGBB to RRGGBBXX */
  192830. if (flags & PNG_FLAG_FILLER_AFTER)
  192831. {
  192832. png_bytep sp = row + (png_size_t)row_width * 6;
  192833. png_bytep dp = sp + (png_size_t)row_width * 2;
  192834. for (i = 1; i < row_width; i++)
  192835. {
  192836. *(--dp) = hi_filler;
  192837. *(--dp) = lo_filler;
  192838. *(--dp) = *(--sp);
  192839. *(--dp) = *(--sp);
  192840. *(--dp) = *(--sp);
  192841. *(--dp) = *(--sp);
  192842. *(--dp) = *(--sp);
  192843. *(--dp) = *(--sp);
  192844. }
  192845. *(--dp) = hi_filler;
  192846. *(--dp) = lo_filler;
  192847. row_info->channels = 4;
  192848. row_info->pixel_depth = 64;
  192849. row_info->rowbytes = row_width * 8;
  192850. }
  192851. /* This changes the data from RRGGBB to XXRRGGBB */
  192852. else
  192853. {
  192854. png_bytep sp = row + (png_size_t)row_width * 6;
  192855. png_bytep dp = sp + (png_size_t)row_width * 2;
  192856. for (i = 0; i < row_width; i++)
  192857. {
  192858. *(--dp) = *(--sp);
  192859. *(--dp) = *(--sp);
  192860. *(--dp) = *(--sp);
  192861. *(--dp) = *(--sp);
  192862. *(--dp) = *(--sp);
  192863. *(--dp) = *(--sp);
  192864. *(--dp) = hi_filler;
  192865. *(--dp) = lo_filler;
  192866. }
  192867. row_info->channels = 4;
  192868. row_info->pixel_depth = 64;
  192869. row_info->rowbytes = row_width * 8;
  192870. }
  192871. }
  192872. } /* COLOR_TYPE == RGB */
  192873. }
  192874. #endif
  192875. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  192876. /* expand grayscale files to RGB, with or without alpha */
  192877. void /* PRIVATE */
  192878. png_do_gray_to_rgb(png_row_infop row_info, png_bytep row)
  192879. {
  192880. png_uint_32 i;
  192881. png_uint_32 row_width = row_info->width;
  192882. png_debug(1, "in png_do_gray_to_rgb\n");
  192883. if (row_info->bit_depth >= 8 &&
  192884. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192885. row != NULL && row_info != NULL &&
  192886. #endif
  192887. !(row_info->color_type & PNG_COLOR_MASK_COLOR))
  192888. {
  192889. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  192890. {
  192891. if (row_info->bit_depth == 8)
  192892. {
  192893. png_bytep sp = row + (png_size_t)row_width - 1;
  192894. png_bytep dp = sp + (png_size_t)row_width * 2;
  192895. for (i = 0; i < row_width; i++)
  192896. {
  192897. *(dp--) = *sp;
  192898. *(dp--) = *sp;
  192899. *(dp--) = *(sp--);
  192900. }
  192901. }
  192902. else
  192903. {
  192904. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192905. png_bytep dp = sp + (png_size_t)row_width * 4;
  192906. for (i = 0; i < row_width; i++)
  192907. {
  192908. *(dp--) = *sp;
  192909. *(dp--) = *(sp - 1);
  192910. *(dp--) = *sp;
  192911. *(dp--) = *(sp - 1);
  192912. *(dp--) = *(sp--);
  192913. *(dp--) = *(sp--);
  192914. }
  192915. }
  192916. }
  192917. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  192918. {
  192919. if (row_info->bit_depth == 8)
  192920. {
  192921. png_bytep sp = row + (png_size_t)row_width * 2 - 1;
  192922. png_bytep dp = sp + (png_size_t)row_width * 2;
  192923. for (i = 0; i < row_width; i++)
  192924. {
  192925. *(dp--) = *(sp--);
  192926. *(dp--) = *sp;
  192927. *(dp--) = *sp;
  192928. *(dp--) = *(sp--);
  192929. }
  192930. }
  192931. else
  192932. {
  192933. png_bytep sp = row + (png_size_t)row_width * 4 - 1;
  192934. png_bytep dp = sp + (png_size_t)row_width * 4;
  192935. for (i = 0; i < row_width; i++)
  192936. {
  192937. *(dp--) = *(sp--);
  192938. *(dp--) = *(sp--);
  192939. *(dp--) = *sp;
  192940. *(dp--) = *(sp - 1);
  192941. *(dp--) = *sp;
  192942. *(dp--) = *(sp - 1);
  192943. *(dp--) = *(sp--);
  192944. *(dp--) = *(sp--);
  192945. }
  192946. }
  192947. }
  192948. row_info->channels += (png_byte)2;
  192949. row_info->color_type |= PNG_COLOR_MASK_COLOR;
  192950. row_info->pixel_depth = (png_byte)(row_info->channels *
  192951. row_info->bit_depth);
  192952. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  192953. }
  192954. }
  192955. #endif
  192956. #if defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  192957. /* reduce RGB files to grayscale, with or without alpha
  192958. * using the equation given in Poynton's ColorFAQ at
  192959. * <http://www.inforamp.net/~poynton/>
  192960. * Copyright (c) 1998-01-04 Charles Poynton poynton at inforamp.net
  192961. *
  192962. * Y = 0.212671 * R + 0.715160 * G + 0.072169 * B
  192963. *
  192964. * We approximate this with
  192965. *
  192966. * Y = 0.21268 * R + 0.7151 * G + 0.07217 * B
  192967. *
  192968. * which can be expressed with integers as
  192969. *
  192970. * Y = (6969 * R + 23434 * G + 2365 * B)/32768
  192971. *
  192972. * The calculation is to be done in a linear colorspace.
  192973. *
  192974. * Other integer coefficents can be used via png_set_rgb_to_gray().
  192975. */
  192976. int /* PRIVATE */
  192977. png_do_rgb_to_gray(png_structp png_ptr, png_row_infop row_info, png_bytep row)
  192978. {
  192979. png_uint_32 i;
  192980. png_uint_32 row_width = row_info->width;
  192981. int rgb_error = 0;
  192982. png_debug(1, "in png_do_rgb_to_gray\n");
  192983. if (
  192984. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  192985. row != NULL && row_info != NULL &&
  192986. #endif
  192987. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  192988. {
  192989. png_uint_32 rc = png_ptr->rgb_to_gray_red_coeff;
  192990. png_uint_32 gc = png_ptr->rgb_to_gray_green_coeff;
  192991. png_uint_32 bc = png_ptr->rgb_to_gray_blue_coeff;
  192992. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  192993. {
  192994. if (row_info->bit_depth == 8)
  192995. {
  192996. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  192997. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  192998. {
  192999. png_bytep sp = row;
  193000. png_bytep dp = row;
  193001. for (i = 0; i < row_width; i++)
  193002. {
  193003. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  193004. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  193005. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  193006. if(red != green || red != blue)
  193007. {
  193008. rgb_error |= 1;
  193009. *(dp++) = png_ptr->gamma_from_1[
  193010. (rc*red+gc*green+bc*blue)>>15];
  193011. }
  193012. else
  193013. *(dp++) = *(sp-1);
  193014. }
  193015. }
  193016. else
  193017. #endif
  193018. {
  193019. png_bytep sp = row;
  193020. png_bytep dp = row;
  193021. for (i = 0; i < row_width; i++)
  193022. {
  193023. png_byte red = *(sp++);
  193024. png_byte green = *(sp++);
  193025. png_byte blue = *(sp++);
  193026. if(red != green || red != blue)
  193027. {
  193028. rgb_error |= 1;
  193029. *(dp++) = (png_byte)((rc*red+gc*green+bc*blue)>>15);
  193030. }
  193031. else
  193032. *(dp++) = *(sp-1);
  193033. }
  193034. }
  193035. }
  193036. else /* RGB bit_depth == 16 */
  193037. {
  193038. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  193039. if (png_ptr->gamma_16_to_1 != NULL &&
  193040. png_ptr->gamma_16_from_1 != NULL)
  193041. {
  193042. png_bytep sp = row;
  193043. png_bytep dp = row;
  193044. for (i = 0; i < row_width; i++)
  193045. {
  193046. png_uint_16 red, green, blue, w;
  193047. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  193048. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  193049. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  193050. if(red == green && red == blue)
  193051. w = red;
  193052. else
  193053. {
  193054. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  193055. png_ptr->gamma_shift][red>>8];
  193056. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  193057. png_ptr->gamma_shift][green>>8];
  193058. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  193059. png_ptr->gamma_shift][blue>>8];
  193060. png_uint_16 gray16 = (png_uint_16)((rc*red_1 + gc*green_1
  193061. + bc*blue_1)>>15);
  193062. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  193063. png_ptr->gamma_shift][gray16 >> 8];
  193064. rgb_error |= 1;
  193065. }
  193066. *(dp++) = (png_byte)((w>>8) & 0xff);
  193067. *(dp++) = (png_byte)(w & 0xff);
  193068. }
  193069. }
  193070. else
  193071. #endif
  193072. {
  193073. png_bytep sp = row;
  193074. png_bytep dp = row;
  193075. for (i = 0; i < row_width; i++)
  193076. {
  193077. png_uint_16 red, green, blue, gray16;
  193078. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  193079. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  193080. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  193081. if(red != green || red != blue)
  193082. rgb_error |= 1;
  193083. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  193084. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  193085. *(dp++) = (png_byte)(gray16 & 0xff);
  193086. }
  193087. }
  193088. }
  193089. }
  193090. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  193091. {
  193092. if (row_info->bit_depth == 8)
  193093. {
  193094. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  193095. if (png_ptr->gamma_from_1 != NULL && png_ptr->gamma_to_1 != NULL)
  193096. {
  193097. png_bytep sp = row;
  193098. png_bytep dp = row;
  193099. for (i = 0; i < row_width; i++)
  193100. {
  193101. png_byte red = png_ptr->gamma_to_1[*(sp++)];
  193102. png_byte green = png_ptr->gamma_to_1[*(sp++)];
  193103. png_byte blue = png_ptr->gamma_to_1[*(sp++)];
  193104. if(red != green || red != blue)
  193105. rgb_error |= 1;
  193106. *(dp++) = png_ptr->gamma_from_1
  193107. [(rc*red + gc*green + bc*blue)>>15];
  193108. *(dp++) = *(sp++); /* alpha */
  193109. }
  193110. }
  193111. else
  193112. #endif
  193113. {
  193114. png_bytep sp = row;
  193115. png_bytep dp = row;
  193116. for (i = 0; i < row_width; i++)
  193117. {
  193118. png_byte red = *(sp++);
  193119. png_byte green = *(sp++);
  193120. png_byte blue = *(sp++);
  193121. if(red != green || red != blue)
  193122. rgb_error |= 1;
  193123. *(dp++) = (png_byte)((rc*red + gc*green + bc*blue)>>15);
  193124. *(dp++) = *(sp++); /* alpha */
  193125. }
  193126. }
  193127. }
  193128. else /* RGBA bit_depth == 16 */
  193129. {
  193130. #if defined(PNG_READ_GAMMA_SUPPORTED) || defined(PNG_READ_BACKGROUND_SUPPORTED)
  193131. if (png_ptr->gamma_16_to_1 != NULL &&
  193132. png_ptr->gamma_16_from_1 != NULL)
  193133. {
  193134. png_bytep sp = row;
  193135. png_bytep dp = row;
  193136. for (i = 0; i < row_width; i++)
  193137. {
  193138. png_uint_16 red, green, blue, w;
  193139. red = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  193140. green = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  193141. blue = (png_uint_16)(((*(sp))<<8) | *(sp+1)); sp+=2;
  193142. if(red == green && red == blue)
  193143. w = red;
  193144. else
  193145. {
  193146. png_uint_16 red_1 = png_ptr->gamma_16_to_1[(red&0xff) >>
  193147. png_ptr->gamma_shift][red>>8];
  193148. png_uint_16 green_1 = png_ptr->gamma_16_to_1[(green&0xff) >>
  193149. png_ptr->gamma_shift][green>>8];
  193150. png_uint_16 blue_1 = png_ptr->gamma_16_to_1[(blue&0xff) >>
  193151. png_ptr->gamma_shift][blue>>8];
  193152. png_uint_16 gray16 = (png_uint_16)((rc * red_1
  193153. + gc * green_1 + bc * blue_1)>>15);
  193154. w = png_ptr->gamma_16_from_1[(gray16&0xff) >>
  193155. png_ptr->gamma_shift][gray16 >> 8];
  193156. rgb_error |= 1;
  193157. }
  193158. *(dp++) = (png_byte)((w>>8) & 0xff);
  193159. *(dp++) = (png_byte)(w & 0xff);
  193160. *(dp++) = *(sp++); /* alpha */
  193161. *(dp++) = *(sp++);
  193162. }
  193163. }
  193164. else
  193165. #endif
  193166. {
  193167. png_bytep sp = row;
  193168. png_bytep dp = row;
  193169. for (i = 0; i < row_width; i++)
  193170. {
  193171. png_uint_16 red, green, blue, gray16;
  193172. red = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  193173. green = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  193174. blue = (png_uint_16)((*(sp)<<8) | *(sp+1)); sp+=2;
  193175. if(red != green || red != blue)
  193176. rgb_error |= 1;
  193177. gray16 = (png_uint_16)((rc*red + gc*green + bc*blue)>>15);
  193178. *(dp++) = (png_byte)((gray16>>8) & 0xff);
  193179. *(dp++) = (png_byte)(gray16 & 0xff);
  193180. *(dp++) = *(sp++); /* alpha */
  193181. *(dp++) = *(sp++);
  193182. }
  193183. }
  193184. }
  193185. }
  193186. row_info->channels -= (png_byte)2;
  193187. row_info->color_type &= ~PNG_COLOR_MASK_COLOR;
  193188. row_info->pixel_depth = (png_byte)(row_info->channels *
  193189. row_info->bit_depth);
  193190. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  193191. }
  193192. return rgb_error;
  193193. }
  193194. #endif
  193195. /* Build a grayscale palette. Palette is assumed to be 1 << bit_depth
  193196. * large of png_color. This lets grayscale images be treated as
  193197. * paletted. Most useful for gamma correction and simplification
  193198. * of code.
  193199. */
  193200. void PNGAPI
  193201. png_build_grayscale_palette(int bit_depth, png_colorp palette)
  193202. {
  193203. int num_palette;
  193204. int color_inc;
  193205. int i;
  193206. int v;
  193207. png_debug(1, "in png_do_build_grayscale_palette\n");
  193208. if (palette == NULL)
  193209. return;
  193210. switch (bit_depth)
  193211. {
  193212. case 1:
  193213. num_palette = 2;
  193214. color_inc = 0xff;
  193215. break;
  193216. case 2:
  193217. num_palette = 4;
  193218. color_inc = 0x55;
  193219. break;
  193220. case 4:
  193221. num_palette = 16;
  193222. color_inc = 0x11;
  193223. break;
  193224. case 8:
  193225. num_palette = 256;
  193226. color_inc = 1;
  193227. break;
  193228. default:
  193229. num_palette = 0;
  193230. color_inc = 0;
  193231. break;
  193232. }
  193233. for (i = 0, v = 0; i < num_palette; i++, v += color_inc)
  193234. {
  193235. palette[i].red = (png_byte)v;
  193236. palette[i].green = (png_byte)v;
  193237. palette[i].blue = (png_byte)v;
  193238. }
  193239. }
  193240. /* This function is currently unused. Do we really need it? */
  193241. #if defined(PNG_READ_DITHER_SUPPORTED) && defined(PNG_CORRECT_PALETTE_SUPPORTED)
  193242. void /* PRIVATE */
  193243. png_correct_palette(png_structp png_ptr, png_colorp palette,
  193244. int num_palette)
  193245. {
  193246. png_debug(1, "in png_correct_palette\n");
  193247. #if defined(PNG_READ_BACKGROUND_SUPPORTED) && \
  193248. defined(PNG_READ_GAMMA_SUPPORTED) && defined(PNG_FLOATING_POINT_SUPPORTED)
  193249. if (png_ptr->transformations & (PNG_GAMMA | PNG_BACKGROUND))
  193250. {
  193251. png_color back, back_1;
  193252. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_FILE)
  193253. {
  193254. back.red = png_ptr->gamma_table[png_ptr->background.red];
  193255. back.green = png_ptr->gamma_table[png_ptr->background.green];
  193256. back.blue = png_ptr->gamma_table[png_ptr->background.blue];
  193257. back_1.red = png_ptr->gamma_to_1[png_ptr->background.red];
  193258. back_1.green = png_ptr->gamma_to_1[png_ptr->background.green];
  193259. back_1.blue = png_ptr->gamma_to_1[png_ptr->background.blue];
  193260. }
  193261. else
  193262. {
  193263. double g;
  193264. g = 1.0 / (png_ptr->background_gamma * png_ptr->screen_gamma);
  193265. if (png_ptr->background_gamma_type == PNG_BACKGROUND_GAMMA_SCREEN ||
  193266. fabs(g - 1.0) < PNG_GAMMA_THRESHOLD)
  193267. {
  193268. back.red = png_ptr->background.red;
  193269. back.green = png_ptr->background.green;
  193270. back.blue = png_ptr->background.blue;
  193271. }
  193272. else
  193273. {
  193274. back.red =
  193275. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  193276. 255.0 + 0.5);
  193277. back.green =
  193278. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  193279. 255.0 + 0.5);
  193280. back.blue =
  193281. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  193282. 255.0 + 0.5);
  193283. }
  193284. g = 1.0 / png_ptr->background_gamma;
  193285. back_1.red =
  193286. (png_byte)(pow((double)png_ptr->background.red/255, g) *
  193287. 255.0 + 0.5);
  193288. back_1.green =
  193289. (png_byte)(pow((double)png_ptr->background.green/255, g) *
  193290. 255.0 + 0.5);
  193291. back_1.blue =
  193292. (png_byte)(pow((double)png_ptr->background.blue/255, g) *
  193293. 255.0 + 0.5);
  193294. }
  193295. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193296. {
  193297. png_uint_32 i;
  193298. for (i = 0; i < (png_uint_32)num_palette; i++)
  193299. {
  193300. if (i < png_ptr->num_trans && png_ptr->trans[i] == 0)
  193301. {
  193302. palette[i] = back;
  193303. }
  193304. else if (i < png_ptr->num_trans && png_ptr->trans[i] != 0xff)
  193305. {
  193306. png_byte v, w;
  193307. v = png_ptr->gamma_to_1[png_ptr->palette[i].red];
  193308. png_composite(w, v, png_ptr->trans[i], back_1.red);
  193309. palette[i].red = png_ptr->gamma_from_1[w];
  193310. v = png_ptr->gamma_to_1[png_ptr->palette[i].green];
  193311. png_composite(w, v, png_ptr->trans[i], back_1.green);
  193312. palette[i].green = png_ptr->gamma_from_1[w];
  193313. v = png_ptr->gamma_to_1[png_ptr->palette[i].blue];
  193314. png_composite(w, v, png_ptr->trans[i], back_1.blue);
  193315. palette[i].blue = png_ptr->gamma_from_1[w];
  193316. }
  193317. else
  193318. {
  193319. palette[i].red = png_ptr->gamma_table[palette[i].red];
  193320. palette[i].green = png_ptr->gamma_table[palette[i].green];
  193321. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  193322. }
  193323. }
  193324. }
  193325. else
  193326. {
  193327. int i;
  193328. for (i = 0; i < num_palette; i++)
  193329. {
  193330. if (palette[i].red == (png_byte)png_ptr->trans_values.gray)
  193331. {
  193332. palette[i] = back;
  193333. }
  193334. else
  193335. {
  193336. palette[i].red = png_ptr->gamma_table[palette[i].red];
  193337. palette[i].green = png_ptr->gamma_table[palette[i].green];
  193338. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  193339. }
  193340. }
  193341. }
  193342. }
  193343. else
  193344. #endif
  193345. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193346. if (png_ptr->transformations & PNG_GAMMA)
  193347. {
  193348. int i;
  193349. for (i = 0; i < num_palette; i++)
  193350. {
  193351. palette[i].red = png_ptr->gamma_table[palette[i].red];
  193352. palette[i].green = png_ptr->gamma_table[palette[i].green];
  193353. palette[i].blue = png_ptr->gamma_table[palette[i].blue];
  193354. }
  193355. }
  193356. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  193357. else
  193358. #endif
  193359. #endif
  193360. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  193361. if (png_ptr->transformations & PNG_BACKGROUND)
  193362. {
  193363. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  193364. {
  193365. png_color back;
  193366. back.red = (png_byte)png_ptr->background.red;
  193367. back.green = (png_byte)png_ptr->background.green;
  193368. back.blue = (png_byte)png_ptr->background.blue;
  193369. for (i = 0; i < (int)png_ptr->num_trans; i++)
  193370. {
  193371. if (png_ptr->trans[i] == 0)
  193372. {
  193373. palette[i].red = back.red;
  193374. palette[i].green = back.green;
  193375. palette[i].blue = back.blue;
  193376. }
  193377. else if (png_ptr->trans[i] != 0xff)
  193378. {
  193379. png_composite(palette[i].red, png_ptr->palette[i].red,
  193380. png_ptr->trans[i], back.red);
  193381. png_composite(palette[i].green, png_ptr->palette[i].green,
  193382. png_ptr->trans[i], back.green);
  193383. png_composite(palette[i].blue, png_ptr->palette[i].blue,
  193384. png_ptr->trans[i], back.blue);
  193385. }
  193386. }
  193387. }
  193388. else /* assume grayscale palette (what else could it be?) */
  193389. {
  193390. int i;
  193391. for (i = 0; i < num_palette; i++)
  193392. {
  193393. if (i == (png_byte)png_ptr->trans_values.gray)
  193394. {
  193395. palette[i].red = (png_byte)png_ptr->background.red;
  193396. palette[i].green = (png_byte)png_ptr->background.green;
  193397. palette[i].blue = (png_byte)png_ptr->background.blue;
  193398. }
  193399. }
  193400. }
  193401. }
  193402. #endif
  193403. }
  193404. #endif
  193405. #if defined(PNG_READ_BACKGROUND_SUPPORTED)
  193406. /* Replace any alpha or transparency with the supplied background color.
  193407. * "background" is already in the screen gamma, while "background_1" is
  193408. * at a gamma of 1.0. Paletted files have already been taken care of.
  193409. */
  193410. void /* PRIVATE */
  193411. png_do_background(png_row_infop row_info, png_bytep row,
  193412. png_color_16p trans_values, png_color_16p background
  193413. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193414. , png_color_16p background_1,
  193415. png_bytep gamma_table, png_bytep gamma_from_1, png_bytep gamma_to_1,
  193416. png_uint_16pp gamma_16, png_uint_16pp gamma_16_from_1,
  193417. png_uint_16pp gamma_16_to_1, int gamma_shift
  193418. #endif
  193419. )
  193420. {
  193421. png_bytep sp, dp;
  193422. png_uint_32 i;
  193423. png_uint_32 row_width=row_info->width;
  193424. int shift;
  193425. png_debug(1, "in png_do_background\n");
  193426. if (background != NULL &&
  193427. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  193428. row != NULL && row_info != NULL &&
  193429. #endif
  193430. (!(row_info->color_type & PNG_COLOR_MASK_ALPHA) ||
  193431. (row_info->color_type != PNG_COLOR_TYPE_PALETTE && trans_values)))
  193432. {
  193433. switch (row_info->color_type)
  193434. {
  193435. case PNG_COLOR_TYPE_GRAY:
  193436. {
  193437. switch (row_info->bit_depth)
  193438. {
  193439. case 1:
  193440. {
  193441. sp = row;
  193442. shift = 7;
  193443. for (i = 0; i < row_width; i++)
  193444. {
  193445. if ((png_uint_16)((*sp >> shift) & 0x01)
  193446. == trans_values->gray)
  193447. {
  193448. *sp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  193449. *sp |= (png_byte)(background->gray << shift);
  193450. }
  193451. if (!shift)
  193452. {
  193453. shift = 7;
  193454. sp++;
  193455. }
  193456. else
  193457. shift--;
  193458. }
  193459. break;
  193460. }
  193461. case 2:
  193462. {
  193463. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193464. if (gamma_table != NULL)
  193465. {
  193466. sp = row;
  193467. shift = 6;
  193468. for (i = 0; i < row_width; i++)
  193469. {
  193470. if ((png_uint_16)((*sp >> shift) & 0x03)
  193471. == trans_values->gray)
  193472. {
  193473. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  193474. *sp |= (png_byte)(background->gray << shift);
  193475. }
  193476. else
  193477. {
  193478. png_byte p = (png_byte)((*sp >> shift) & 0x03);
  193479. png_byte g = (png_byte)((gamma_table [p | (p << 2) |
  193480. (p << 4) | (p << 6)] >> 6) & 0x03);
  193481. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  193482. *sp |= (png_byte)(g << shift);
  193483. }
  193484. if (!shift)
  193485. {
  193486. shift = 6;
  193487. sp++;
  193488. }
  193489. else
  193490. shift -= 2;
  193491. }
  193492. }
  193493. else
  193494. #endif
  193495. {
  193496. sp = row;
  193497. shift = 6;
  193498. for (i = 0; i < row_width; i++)
  193499. {
  193500. if ((png_uint_16)((*sp >> shift) & 0x03)
  193501. == trans_values->gray)
  193502. {
  193503. *sp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  193504. *sp |= (png_byte)(background->gray << shift);
  193505. }
  193506. if (!shift)
  193507. {
  193508. shift = 6;
  193509. sp++;
  193510. }
  193511. else
  193512. shift -= 2;
  193513. }
  193514. }
  193515. break;
  193516. }
  193517. case 4:
  193518. {
  193519. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193520. if (gamma_table != NULL)
  193521. {
  193522. sp = row;
  193523. shift = 4;
  193524. for (i = 0; i < row_width; i++)
  193525. {
  193526. if ((png_uint_16)((*sp >> shift) & 0x0f)
  193527. == trans_values->gray)
  193528. {
  193529. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  193530. *sp |= (png_byte)(background->gray << shift);
  193531. }
  193532. else
  193533. {
  193534. png_byte p = (png_byte)((*sp >> shift) & 0x0f);
  193535. png_byte g = (png_byte)((gamma_table[p |
  193536. (p << 4)] >> 4) & 0x0f);
  193537. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  193538. *sp |= (png_byte)(g << shift);
  193539. }
  193540. if (!shift)
  193541. {
  193542. shift = 4;
  193543. sp++;
  193544. }
  193545. else
  193546. shift -= 4;
  193547. }
  193548. }
  193549. else
  193550. #endif
  193551. {
  193552. sp = row;
  193553. shift = 4;
  193554. for (i = 0; i < row_width; i++)
  193555. {
  193556. if ((png_uint_16)((*sp >> shift) & 0x0f)
  193557. == trans_values->gray)
  193558. {
  193559. *sp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  193560. *sp |= (png_byte)(background->gray << shift);
  193561. }
  193562. if (!shift)
  193563. {
  193564. shift = 4;
  193565. sp++;
  193566. }
  193567. else
  193568. shift -= 4;
  193569. }
  193570. }
  193571. break;
  193572. }
  193573. case 8:
  193574. {
  193575. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193576. if (gamma_table != NULL)
  193577. {
  193578. sp = row;
  193579. for (i = 0; i < row_width; i++, sp++)
  193580. {
  193581. if (*sp == trans_values->gray)
  193582. {
  193583. *sp = (png_byte)background->gray;
  193584. }
  193585. else
  193586. {
  193587. *sp = gamma_table[*sp];
  193588. }
  193589. }
  193590. }
  193591. else
  193592. #endif
  193593. {
  193594. sp = row;
  193595. for (i = 0; i < row_width; i++, sp++)
  193596. {
  193597. if (*sp == trans_values->gray)
  193598. {
  193599. *sp = (png_byte)background->gray;
  193600. }
  193601. }
  193602. }
  193603. break;
  193604. }
  193605. case 16:
  193606. {
  193607. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193608. if (gamma_16 != NULL)
  193609. {
  193610. sp = row;
  193611. for (i = 0; i < row_width; i++, sp += 2)
  193612. {
  193613. png_uint_16 v;
  193614. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193615. if (v == trans_values->gray)
  193616. {
  193617. /* background is already in screen gamma */
  193618. *sp = (png_byte)((background->gray >> 8) & 0xff);
  193619. *(sp + 1) = (png_byte)(background->gray & 0xff);
  193620. }
  193621. else
  193622. {
  193623. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193624. *sp = (png_byte)((v >> 8) & 0xff);
  193625. *(sp + 1) = (png_byte)(v & 0xff);
  193626. }
  193627. }
  193628. }
  193629. else
  193630. #endif
  193631. {
  193632. sp = row;
  193633. for (i = 0; i < row_width; i++, sp += 2)
  193634. {
  193635. png_uint_16 v;
  193636. v = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193637. if (v == trans_values->gray)
  193638. {
  193639. *sp = (png_byte)((background->gray >> 8) & 0xff);
  193640. *(sp + 1) = (png_byte)(background->gray & 0xff);
  193641. }
  193642. }
  193643. }
  193644. break;
  193645. }
  193646. }
  193647. break;
  193648. }
  193649. case PNG_COLOR_TYPE_RGB:
  193650. {
  193651. if (row_info->bit_depth == 8)
  193652. {
  193653. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193654. if (gamma_table != NULL)
  193655. {
  193656. sp = row;
  193657. for (i = 0; i < row_width; i++, sp += 3)
  193658. {
  193659. if (*sp == trans_values->red &&
  193660. *(sp + 1) == trans_values->green &&
  193661. *(sp + 2) == trans_values->blue)
  193662. {
  193663. *sp = (png_byte)background->red;
  193664. *(sp + 1) = (png_byte)background->green;
  193665. *(sp + 2) = (png_byte)background->blue;
  193666. }
  193667. else
  193668. {
  193669. *sp = gamma_table[*sp];
  193670. *(sp + 1) = gamma_table[*(sp + 1)];
  193671. *(sp + 2) = gamma_table[*(sp + 2)];
  193672. }
  193673. }
  193674. }
  193675. else
  193676. #endif
  193677. {
  193678. sp = row;
  193679. for (i = 0; i < row_width; i++, sp += 3)
  193680. {
  193681. if (*sp == trans_values->red &&
  193682. *(sp + 1) == trans_values->green &&
  193683. *(sp + 2) == trans_values->blue)
  193684. {
  193685. *sp = (png_byte)background->red;
  193686. *(sp + 1) = (png_byte)background->green;
  193687. *(sp + 2) = (png_byte)background->blue;
  193688. }
  193689. }
  193690. }
  193691. }
  193692. else /* if (row_info->bit_depth == 16) */
  193693. {
  193694. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193695. if (gamma_16 != NULL)
  193696. {
  193697. sp = row;
  193698. for (i = 0; i < row_width; i++, sp += 6)
  193699. {
  193700. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193701. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193702. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  193703. if (r == trans_values->red && g == trans_values->green &&
  193704. b == trans_values->blue)
  193705. {
  193706. /* background is already in screen gamma */
  193707. *sp = (png_byte)((background->red >> 8) & 0xff);
  193708. *(sp + 1) = (png_byte)(background->red & 0xff);
  193709. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193710. *(sp + 3) = (png_byte)(background->green & 0xff);
  193711. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193712. *(sp + 5) = (png_byte)(background->blue & 0xff);
  193713. }
  193714. else
  193715. {
  193716. png_uint_16 v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193717. *sp = (png_byte)((v >> 8) & 0xff);
  193718. *(sp + 1) = (png_byte)(v & 0xff);
  193719. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193720. *(sp + 2) = (png_byte)((v >> 8) & 0xff);
  193721. *(sp + 3) = (png_byte)(v & 0xff);
  193722. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193723. *(sp + 4) = (png_byte)((v >> 8) & 0xff);
  193724. *(sp + 5) = (png_byte)(v & 0xff);
  193725. }
  193726. }
  193727. }
  193728. else
  193729. #endif
  193730. {
  193731. sp = row;
  193732. for (i = 0; i < row_width; i++, sp += 6)
  193733. {
  193734. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp+1));
  193735. png_uint_16 g = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193736. png_uint_16 b = (png_uint_16)(((*(sp+4)) << 8) + *(sp+5));
  193737. if (r == trans_values->red && g == trans_values->green &&
  193738. b == trans_values->blue)
  193739. {
  193740. *sp = (png_byte)((background->red >> 8) & 0xff);
  193741. *(sp + 1) = (png_byte)(background->red & 0xff);
  193742. *(sp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193743. *(sp + 3) = (png_byte)(background->green & 0xff);
  193744. *(sp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193745. *(sp + 5) = (png_byte)(background->blue & 0xff);
  193746. }
  193747. }
  193748. }
  193749. }
  193750. break;
  193751. }
  193752. case PNG_COLOR_TYPE_GRAY_ALPHA:
  193753. {
  193754. if (row_info->bit_depth == 8)
  193755. {
  193756. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193757. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193758. gamma_table != NULL)
  193759. {
  193760. sp = row;
  193761. dp = row;
  193762. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193763. {
  193764. png_uint_16 a = *(sp + 1);
  193765. if (a == 0xff)
  193766. {
  193767. *dp = gamma_table[*sp];
  193768. }
  193769. else if (a == 0)
  193770. {
  193771. /* background is already in screen gamma */
  193772. *dp = (png_byte)background->gray;
  193773. }
  193774. else
  193775. {
  193776. png_byte v, w;
  193777. v = gamma_to_1[*sp];
  193778. png_composite(w, v, a, background_1->gray);
  193779. *dp = gamma_from_1[w];
  193780. }
  193781. }
  193782. }
  193783. else
  193784. #endif
  193785. {
  193786. sp = row;
  193787. dp = row;
  193788. for (i = 0; i < row_width; i++, sp += 2, dp++)
  193789. {
  193790. png_byte a = *(sp + 1);
  193791. if (a == 0xff)
  193792. {
  193793. *dp = *sp;
  193794. }
  193795. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193796. else if (a == 0)
  193797. {
  193798. *dp = (png_byte)background->gray;
  193799. }
  193800. else
  193801. {
  193802. png_composite(*dp, *sp, a, background_1->gray);
  193803. }
  193804. #else
  193805. *dp = (png_byte)background->gray;
  193806. #endif
  193807. }
  193808. }
  193809. }
  193810. else /* if (png_ptr->bit_depth == 16) */
  193811. {
  193812. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193813. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193814. gamma_16_to_1 != NULL)
  193815. {
  193816. sp = row;
  193817. dp = row;
  193818. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193819. {
  193820. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193821. if (a == (png_uint_16)0xffff)
  193822. {
  193823. png_uint_16 v;
  193824. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193825. *dp = (png_byte)((v >> 8) & 0xff);
  193826. *(dp + 1) = (png_byte)(v & 0xff);
  193827. }
  193828. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193829. else if (a == 0)
  193830. #else
  193831. else
  193832. #endif
  193833. {
  193834. /* background is already in screen gamma */
  193835. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193836. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193837. }
  193838. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193839. else
  193840. {
  193841. png_uint_16 g, v, w;
  193842. g = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193843. png_composite_16(v, g, a, background_1->gray);
  193844. w = gamma_16_from_1[(v&0xff) >> gamma_shift][v >> 8];
  193845. *dp = (png_byte)((w >> 8) & 0xff);
  193846. *(dp + 1) = (png_byte)(w & 0xff);
  193847. }
  193848. #endif
  193849. }
  193850. }
  193851. else
  193852. #endif
  193853. {
  193854. sp = row;
  193855. dp = row;
  193856. for (i = 0; i < row_width; i++, sp += 4, dp += 2)
  193857. {
  193858. png_uint_16 a = (png_uint_16)(((*(sp+2)) << 8) + *(sp+3));
  193859. if (a == (png_uint_16)0xffff)
  193860. {
  193861. png_memcpy(dp, sp, 2);
  193862. }
  193863. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193864. else if (a == 0)
  193865. #else
  193866. else
  193867. #endif
  193868. {
  193869. *dp = (png_byte)((background->gray >> 8) & 0xff);
  193870. *(dp + 1) = (png_byte)(background->gray & 0xff);
  193871. }
  193872. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193873. else
  193874. {
  193875. png_uint_16 g, v;
  193876. g = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  193877. png_composite_16(v, g, a, background_1->gray);
  193878. *dp = (png_byte)((v >> 8) & 0xff);
  193879. *(dp + 1) = (png_byte)(v & 0xff);
  193880. }
  193881. #endif
  193882. }
  193883. }
  193884. }
  193885. break;
  193886. }
  193887. case PNG_COLOR_TYPE_RGB_ALPHA:
  193888. {
  193889. if (row_info->bit_depth == 8)
  193890. {
  193891. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193892. if (gamma_to_1 != NULL && gamma_from_1 != NULL &&
  193893. gamma_table != NULL)
  193894. {
  193895. sp = row;
  193896. dp = row;
  193897. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193898. {
  193899. png_byte a = *(sp + 3);
  193900. if (a == 0xff)
  193901. {
  193902. *dp = gamma_table[*sp];
  193903. *(dp + 1) = gamma_table[*(sp + 1)];
  193904. *(dp + 2) = gamma_table[*(sp + 2)];
  193905. }
  193906. else if (a == 0)
  193907. {
  193908. /* background is already in screen gamma */
  193909. *dp = (png_byte)background->red;
  193910. *(dp + 1) = (png_byte)background->green;
  193911. *(dp + 2) = (png_byte)background->blue;
  193912. }
  193913. else
  193914. {
  193915. png_byte v, w;
  193916. v = gamma_to_1[*sp];
  193917. png_composite(w, v, a, background_1->red);
  193918. *dp = gamma_from_1[w];
  193919. v = gamma_to_1[*(sp + 1)];
  193920. png_composite(w, v, a, background_1->green);
  193921. *(dp + 1) = gamma_from_1[w];
  193922. v = gamma_to_1[*(sp + 2)];
  193923. png_composite(w, v, a, background_1->blue);
  193924. *(dp + 2) = gamma_from_1[w];
  193925. }
  193926. }
  193927. }
  193928. else
  193929. #endif
  193930. {
  193931. sp = row;
  193932. dp = row;
  193933. for (i = 0; i < row_width; i++, sp += 4, dp += 3)
  193934. {
  193935. png_byte a = *(sp + 3);
  193936. if (a == 0xff)
  193937. {
  193938. *dp = *sp;
  193939. *(dp + 1) = *(sp + 1);
  193940. *(dp + 2) = *(sp + 2);
  193941. }
  193942. else if (a == 0)
  193943. {
  193944. *dp = (png_byte)background->red;
  193945. *(dp + 1) = (png_byte)background->green;
  193946. *(dp + 2) = (png_byte)background->blue;
  193947. }
  193948. else
  193949. {
  193950. png_composite(*dp, *sp, a, background->red);
  193951. png_composite(*(dp + 1), *(sp + 1), a,
  193952. background->green);
  193953. png_composite(*(dp + 2), *(sp + 2), a,
  193954. background->blue);
  193955. }
  193956. }
  193957. }
  193958. }
  193959. else /* if (row_info->bit_depth == 16) */
  193960. {
  193961. #if defined(PNG_READ_GAMMA_SUPPORTED)
  193962. if (gamma_16 != NULL && gamma_16_from_1 != NULL &&
  193963. gamma_16_to_1 != NULL)
  193964. {
  193965. sp = row;
  193966. dp = row;
  193967. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  193968. {
  193969. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  193970. << 8) + (png_uint_16)(*(sp + 7)));
  193971. if (a == (png_uint_16)0xffff)
  193972. {
  193973. png_uint_16 v;
  193974. v = gamma_16[*(sp + 1) >> gamma_shift][*sp];
  193975. *dp = (png_byte)((v >> 8) & 0xff);
  193976. *(dp + 1) = (png_byte)(v & 0xff);
  193977. v = gamma_16[*(sp + 3) >> gamma_shift][*(sp + 2)];
  193978. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  193979. *(dp + 3) = (png_byte)(v & 0xff);
  193980. v = gamma_16[*(sp + 5) >> gamma_shift][*(sp + 4)];
  193981. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  193982. *(dp + 5) = (png_byte)(v & 0xff);
  193983. }
  193984. else if (a == 0)
  193985. {
  193986. /* background is already in screen gamma */
  193987. *dp = (png_byte)((background->red >> 8) & 0xff);
  193988. *(dp + 1) = (png_byte)(background->red & 0xff);
  193989. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  193990. *(dp + 3) = (png_byte)(background->green & 0xff);
  193991. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  193992. *(dp + 5) = (png_byte)(background->blue & 0xff);
  193993. }
  193994. else
  193995. {
  193996. png_uint_16 v, w, x;
  193997. v = gamma_16_to_1[*(sp + 1) >> gamma_shift][*sp];
  193998. png_composite_16(w, v, a, background_1->red);
  193999. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  194000. *dp = (png_byte)((x >> 8) & 0xff);
  194001. *(dp + 1) = (png_byte)(x & 0xff);
  194002. v = gamma_16_to_1[*(sp + 3) >> gamma_shift][*(sp + 2)];
  194003. png_composite_16(w, v, a, background_1->green);
  194004. x = gamma_16_from_1[((w&0xff) >> gamma_shift)][w >> 8];
  194005. *(dp + 2) = (png_byte)((x >> 8) & 0xff);
  194006. *(dp + 3) = (png_byte)(x & 0xff);
  194007. v = gamma_16_to_1[*(sp + 5) >> gamma_shift][*(sp + 4)];
  194008. png_composite_16(w, v, a, background_1->blue);
  194009. x = gamma_16_from_1[(w & 0xff) >> gamma_shift][w >> 8];
  194010. *(dp + 4) = (png_byte)((x >> 8) & 0xff);
  194011. *(dp + 5) = (png_byte)(x & 0xff);
  194012. }
  194013. }
  194014. }
  194015. else
  194016. #endif
  194017. {
  194018. sp = row;
  194019. dp = row;
  194020. for (i = 0; i < row_width; i++, sp += 8, dp += 6)
  194021. {
  194022. png_uint_16 a = (png_uint_16)(((png_uint_16)(*(sp + 6))
  194023. << 8) + (png_uint_16)(*(sp + 7)));
  194024. if (a == (png_uint_16)0xffff)
  194025. {
  194026. png_memcpy(dp, sp, 6);
  194027. }
  194028. else if (a == 0)
  194029. {
  194030. *dp = (png_byte)((background->red >> 8) & 0xff);
  194031. *(dp + 1) = (png_byte)(background->red & 0xff);
  194032. *(dp + 2) = (png_byte)((background->green >> 8) & 0xff);
  194033. *(dp + 3) = (png_byte)(background->green & 0xff);
  194034. *(dp + 4) = (png_byte)((background->blue >> 8) & 0xff);
  194035. *(dp + 5) = (png_byte)(background->blue & 0xff);
  194036. }
  194037. else
  194038. {
  194039. png_uint_16 v;
  194040. png_uint_16 r = (png_uint_16)(((*sp) << 8) + *(sp + 1));
  194041. png_uint_16 g = (png_uint_16)(((*(sp + 2)) << 8)
  194042. + *(sp + 3));
  194043. png_uint_16 b = (png_uint_16)(((*(sp + 4)) << 8)
  194044. + *(sp + 5));
  194045. png_composite_16(v, r, a, background->red);
  194046. *dp = (png_byte)((v >> 8) & 0xff);
  194047. *(dp + 1) = (png_byte)(v & 0xff);
  194048. png_composite_16(v, g, a, background->green);
  194049. *(dp + 2) = (png_byte)((v >> 8) & 0xff);
  194050. *(dp + 3) = (png_byte)(v & 0xff);
  194051. png_composite_16(v, b, a, background->blue);
  194052. *(dp + 4) = (png_byte)((v >> 8) & 0xff);
  194053. *(dp + 5) = (png_byte)(v & 0xff);
  194054. }
  194055. }
  194056. }
  194057. }
  194058. break;
  194059. }
  194060. }
  194061. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  194062. {
  194063. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  194064. row_info->channels--;
  194065. row_info->pixel_depth = (png_byte)(row_info->channels *
  194066. row_info->bit_depth);
  194067. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  194068. }
  194069. }
  194070. }
  194071. #endif
  194072. #if defined(PNG_READ_GAMMA_SUPPORTED)
  194073. /* Gamma correct the image, avoiding the alpha channel. Make sure
  194074. * you do this after you deal with the transparency issue on grayscale
  194075. * or RGB images. If your bit depth is 8, use gamma_table, if it
  194076. * is 16, use gamma_16_table and gamma_shift. Build these with
  194077. * build_gamma_table().
  194078. */
  194079. void /* PRIVATE */
  194080. png_do_gamma(png_row_infop row_info, png_bytep row,
  194081. png_bytep gamma_table, png_uint_16pp gamma_16_table,
  194082. int gamma_shift)
  194083. {
  194084. png_bytep sp;
  194085. png_uint_32 i;
  194086. png_uint_32 row_width=row_info->width;
  194087. png_debug(1, "in png_do_gamma\n");
  194088. if (
  194089. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194090. row != NULL && row_info != NULL &&
  194091. #endif
  194092. ((row_info->bit_depth <= 8 && gamma_table != NULL) ||
  194093. (row_info->bit_depth == 16 && gamma_16_table != NULL)))
  194094. {
  194095. switch (row_info->color_type)
  194096. {
  194097. case PNG_COLOR_TYPE_RGB:
  194098. {
  194099. if (row_info->bit_depth == 8)
  194100. {
  194101. sp = row;
  194102. for (i = 0; i < row_width; i++)
  194103. {
  194104. *sp = gamma_table[*sp];
  194105. sp++;
  194106. *sp = gamma_table[*sp];
  194107. sp++;
  194108. *sp = gamma_table[*sp];
  194109. sp++;
  194110. }
  194111. }
  194112. else /* if (row_info->bit_depth == 16) */
  194113. {
  194114. sp = row;
  194115. for (i = 0; i < row_width; i++)
  194116. {
  194117. png_uint_16 v;
  194118. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  194119. *sp = (png_byte)((v >> 8) & 0xff);
  194120. *(sp + 1) = (png_byte)(v & 0xff);
  194121. sp += 2;
  194122. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  194123. *sp = (png_byte)((v >> 8) & 0xff);
  194124. *(sp + 1) = (png_byte)(v & 0xff);
  194125. sp += 2;
  194126. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  194127. *sp = (png_byte)((v >> 8) & 0xff);
  194128. *(sp + 1) = (png_byte)(v & 0xff);
  194129. sp += 2;
  194130. }
  194131. }
  194132. break;
  194133. }
  194134. case PNG_COLOR_TYPE_RGB_ALPHA:
  194135. {
  194136. if (row_info->bit_depth == 8)
  194137. {
  194138. sp = row;
  194139. for (i = 0; i < row_width; i++)
  194140. {
  194141. *sp = gamma_table[*sp];
  194142. sp++;
  194143. *sp = gamma_table[*sp];
  194144. sp++;
  194145. *sp = gamma_table[*sp];
  194146. sp++;
  194147. sp++;
  194148. }
  194149. }
  194150. else /* if (row_info->bit_depth == 16) */
  194151. {
  194152. sp = row;
  194153. for (i = 0; i < row_width; i++)
  194154. {
  194155. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  194156. *sp = (png_byte)((v >> 8) & 0xff);
  194157. *(sp + 1) = (png_byte)(v & 0xff);
  194158. sp += 2;
  194159. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  194160. *sp = (png_byte)((v >> 8) & 0xff);
  194161. *(sp + 1) = (png_byte)(v & 0xff);
  194162. sp += 2;
  194163. v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  194164. *sp = (png_byte)((v >> 8) & 0xff);
  194165. *(sp + 1) = (png_byte)(v & 0xff);
  194166. sp += 4;
  194167. }
  194168. }
  194169. break;
  194170. }
  194171. case PNG_COLOR_TYPE_GRAY_ALPHA:
  194172. {
  194173. if (row_info->bit_depth == 8)
  194174. {
  194175. sp = row;
  194176. for (i = 0; i < row_width; i++)
  194177. {
  194178. *sp = gamma_table[*sp];
  194179. sp += 2;
  194180. }
  194181. }
  194182. else /* if (row_info->bit_depth == 16) */
  194183. {
  194184. sp = row;
  194185. for (i = 0; i < row_width; i++)
  194186. {
  194187. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  194188. *sp = (png_byte)((v >> 8) & 0xff);
  194189. *(sp + 1) = (png_byte)(v & 0xff);
  194190. sp += 4;
  194191. }
  194192. }
  194193. break;
  194194. }
  194195. case PNG_COLOR_TYPE_GRAY:
  194196. {
  194197. if (row_info->bit_depth == 2)
  194198. {
  194199. sp = row;
  194200. for (i = 0; i < row_width; i += 4)
  194201. {
  194202. int a = *sp & 0xc0;
  194203. int b = *sp & 0x30;
  194204. int c = *sp & 0x0c;
  194205. int d = *sp & 0x03;
  194206. *sp = (png_byte)(
  194207. ((((int)gamma_table[a|(a>>2)|(a>>4)|(a>>6)]) ) & 0xc0)|
  194208. ((((int)gamma_table[(b<<2)|b|(b>>2)|(b>>4)])>>2) & 0x30)|
  194209. ((((int)gamma_table[(c<<4)|(c<<2)|c|(c>>2)])>>4) & 0x0c)|
  194210. ((((int)gamma_table[(d<<6)|(d<<4)|(d<<2)|d])>>6) ));
  194211. sp++;
  194212. }
  194213. }
  194214. if (row_info->bit_depth == 4)
  194215. {
  194216. sp = row;
  194217. for (i = 0; i < row_width; i += 2)
  194218. {
  194219. int msb = *sp & 0xf0;
  194220. int lsb = *sp & 0x0f;
  194221. *sp = (png_byte)((((int)gamma_table[msb | (msb >> 4)]) & 0xf0)
  194222. | (((int)gamma_table[(lsb << 4) | lsb]) >> 4));
  194223. sp++;
  194224. }
  194225. }
  194226. else if (row_info->bit_depth == 8)
  194227. {
  194228. sp = row;
  194229. for (i = 0; i < row_width; i++)
  194230. {
  194231. *sp = gamma_table[*sp];
  194232. sp++;
  194233. }
  194234. }
  194235. else if (row_info->bit_depth == 16)
  194236. {
  194237. sp = row;
  194238. for (i = 0; i < row_width; i++)
  194239. {
  194240. png_uint_16 v = gamma_16_table[*(sp + 1) >> gamma_shift][*sp];
  194241. *sp = (png_byte)((v >> 8) & 0xff);
  194242. *(sp + 1) = (png_byte)(v & 0xff);
  194243. sp += 2;
  194244. }
  194245. }
  194246. break;
  194247. }
  194248. }
  194249. }
  194250. }
  194251. #endif
  194252. #if defined(PNG_READ_EXPAND_SUPPORTED)
  194253. /* Expands a palette row to an RGB or RGBA row depending
  194254. * upon whether you supply trans and num_trans.
  194255. */
  194256. void /* PRIVATE */
  194257. png_do_expand_palette(png_row_infop row_info, png_bytep row,
  194258. png_colorp palette, png_bytep trans, int num_trans)
  194259. {
  194260. int shift, value;
  194261. png_bytep sp, dp;
  194262. png_uint_32 i;
  194263. png_uint_32 row_width=row_info->width;
  194264. png_debug(1, "in png_do_expand_palette\n");
  194265. if (
  194266. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194267. row != NULL && row_info != NULL &&
  194268. #endif
  194269. row_info->color_type == PNG_COLOR_TYPE_PALETTE)
  194270. {
  194271. if (row_info->bit_depth < 8)
  194272. {
  194273. switch (row_info->bit_depth)
  194274. {
  194275. case 1:
  194276. {
  194277. sp = row + (png_size_t)((row_width - 1) >> 3);
  194278. dp = row + (png_size_t)row_width - 1;
  194279. shift = 7 - (int)((row_width + 7) & 0x07);
  194280. for (i = 0; i < row_width; i++)
  194281. {
  194282. if ((*sp >> shift) & 0x01)
  194283. *dp = 1;
  194284. else
  194285. *dp = 0;
  194286. if (shift == 7)
  194287. {
  194288. shift = 0;
  194289. sp--;
  194290. }
  194291. else
  194292. shift++;
  194293. dp--;
  194294. }
  194295. break;
  194296. }
  194297. case 2:
  194298. {
  194299. sp = row + (png_size_t)((row_width - 1) >> 2);
  194300. dp = row + (png_size_t)row_width - 1;
  194301. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  194302. for (i = 0; i < row_width; i++)
  194303. {
  194304. value = (*sp >> shift) & 0x03;
  194305. *dp = (png_byte)value;
  194306. if (shift == 6)
  194307. {
  194308. shift = 0;
  194309. sp--;
  194310. }
  194311. else
  194312. shift += 2;
  194313. dp--;
  194314. }
  194315. break;
  194316. }
  194317. case 4:
  194318. {
  194319. sp = row + (png_size_t)((row_width - 1) >> 1);
  194320. dp = row + (png_size_t)row_width - 1;
  194321. shift = (int)((row_width & 0x01) << 2);
  194322. for (i = 0; i < row_width; i++)
  194323. {
  194324. value = (*sp >> shift) & 0x0f;
  194325. *dp = (png_byte)value;
  194326. if (shift == 4)
  194327. {
  194328. shift = 0;
  194329. sp--;
  194330. }
  194331. else
  194332. shift += 4;
  194333. dp--;
  194334. }
  194335. break;
  194336. }
  194337. }
  194338. row_info->bit_depth = 8;
  194339. row_info->pixel_depth = 8;
  194340. row_info->rowbytes = row_width;
  194341. }
  194342. switch (row_info->bit_depth)
  194343. {
  194344. case 8:
  194345. {
  194346. if (trans != NULL)
  194347. {
  194348. sp = row + (png_size_t)row_width - 1;
  194349. dp = row + (png_size_t)(row_width << 2) - 1;
  194350. for (i = 0; i < row_width; i++)
  194351. {
  194352. if ((int)(*sp) >= num_trans)
  194353. *dp-- = 0xff;
  194354. else
  194355. *dp-- = trans[*sp];
  194356. *dp-- = palette[*sp].blue;
  194357. *dp-- = palette[*sp].green;
  194358. *dp-- = palette[*sp].red;
  194359. sp--;
  194360. }
  194361. row_info->bit_depth = 8;
  194362. row_info->pixel_depth = 32;
  194363. row_info->rowbytes = row_width * 4;
  194364. row_info->color_type = 6;
  194365. row_info->channels = 4;
  194366. }
  194367. else
  194368. {
  194369. sp = row + (png_size_t)row_width - 1;
  194370. dp = row + (png_size_t)(row_width * 3) - 1;
  194371. for (i = 0; i < row_width; i++)
  194372. {
  194373. *dp-- = palette[*sp].blue;
  194374. *dp-- = palette[*sp].green;
  194375. *dp-- = palette[*sp].red;
  194376. sp--;
  194377. }
  194378. row_info->bit_depth = 8;
  194379. row_info->pixel_depth = 24;
  194380. row_info->rowbytes = row_width * 3;
  194381. row_info->color_type = 2;
  194382. row_info->channels = 3;
  194383. }
  194384. break;
  194385. }
  194386. }
  194387. }
  194388. }
  194389. /* If the bit depth < 8, it is expanded to 8. Also, if the already
  194390. * expanded transparency value is supplied, an alpha channel is built.
  194391. */
  194392. void /* PRIVATE */
  194393. png_do_expand(png_row_infop row_info, png_bytep row,
  194394. png_color_16p trans_value)
  194395. {
  194396. int shift, value;
  194397. png_bytep sp, dp;
  194398. png_uint_32 i;
  194399. png_uint_32 row_width=row_info->width;
  194400. png_debug(1, "in png_do_expand\n");
  194401. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194402. if (row != NULL && row_info != NULL)
  194403. #endif
  194404. {
  194405. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  194406. {
  194407. png_uint_16 gray = (png_uint_16)(trans_value ? trans_value->gray : 0);
  194408. if (row_info->bit_depth < 8)
  194409. {
  194410. switch (row_info->bit_depth)
  194411. {
  194412. case 1:
  194413. {
  194414. gray = (png_uint_16)((gray&0x01)*0xff);
  194415. sp = row + (png_size_t)((row_width - 1) >> 3);
  194416. dp = row + (png_size_t)row_width - 1;
  194417. shift = 7 - (int)((row_width + 7) & 0x07);
  194418. for (i = 0; i < row_width; i++)
  194419. {
  194420. if ((*sp >> shift) & 0x01)
  194421. *dp = 0xff;
  194422. else
  194423. *dp = 0;
  194424. if (shift == 7)
  194425. {
  194426. shift = 0;
  194427. sp--;
  194428. }
  194429. else
  194430. shift++;
  194431. dp--;
  194432. }
  194433. break;
  194434. }
  194435. case 2:
  194436. {
  194437. gray = (png_uint_16)((gray&0x03)*0x55);
  194438. sp = row + (png_size_t)((row_width - 1) >> 2);
  194439. dp = row + (png_size_t)row_width - 1;
  194440. shift = (int)((3 - ((row_width + 3) & 0x03)) << 1);
  194441. for (i = 0; i < row_width; i++)
  194442. {
  194443. value = (*sp >> shift) & 0x03;
  194444. *dp = (png_byte)(value | (value << 2) | (value << 4) |
  194445. (value << 6));
  194446. if (shift == 6)
  194447. {
  194448. shift = 0;
  194449. sp--;
  194450. }
  194451. else
  194452. shift += 2;
  194453. dp--;
  194454. }
  194455. break;
  194456. }
  194457. case 4:
  194458. {
  194459. gray = (png_uint_16)((gray&0x0f)*0x11);
  194460. sp = row + (png_size_t)((row_width - 1) >> 1);
  194461. dp = row + (png_size_t)row_width - 1;
  194462. shift = (int)((1 - ((row_width + 1) & 0x01)) << 2);
  194463. for (i = 0; i < row_width; i++)
  194464. {
  194465. value = (*sp >> shift) & 0x0f;
  194466. *dp = (png_byte)(value | (value << 4));
  194467. if (shift == 4)
  194468. {
  194469. shift = 0;
  194470. sp--;
  194471. }
  194472. else
  194473. shift = 4;
  194474. dp--;
  194475. }
  194476. break;
  194477. }
  194478. }
  194479. row_info->bit_depth = 8;
  194480. row_info->pixel_depth = 8;
  194481. row_info->rowbytes = row_width;
  194482. }
  194483. if (trans_value != NULL)
  194484. {
  194485. if (row_info->bit_depth == 8)
  194486. {
  194487. gray = gray & 0xff;
  194488. sp = row + (png_size_t)row_width - 1;
  194489. dp = row + (png_size_t)(row_width << 1) - 1;
  194490. for (i = 0; i < row_width; i++)
  194491. {
  194492. if (*sp == gray)
  194493. *dp-- = 0;
  194494. else
  194495. *dp-- = 0xff;
  194496. *dp-- = *sp--;
  194497. }
  194498. }
  194499. else if (row_info->bit_depth == 16)
  194500. {
  194501. png_byte gray_high = (gray >> 8) & 0xff;
  194502. png_byte gray_low = gray & 0xff;
  194503. sp = row + row_info->rowbytes - 1;
  194504. dp = row + (row_info->rowbytes << 1) - 1;
  194505. for (i = 0; i < row_width; i++)
  194506. {
  194507. if (*(sp-1) == gray_high && *(sp) == gray_low)
  194508. {
  194509. *dp-- = 0;
  194510. *dp-- = 0;
  194511. }
  194512. else
  194513. {
  194514. *dp-- = 0xff;
  194515. *dp-- = 0xff;
  194516. }
  194517. *dp-- = *sp--;
  194518. *dp-- = *sp--;
  194519. }
  194520. }
  194521. row_info->color_type = PNG_COLOR_TYPE_GRAY_ALPHA;
  194522. row_info->channels = 2;
  194523. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 1);
  194524. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  194525. row_width);
  194526. }
  194527. }
  194528. else if (row_info->color_type == PNG_COLOR_TYPE_RGB && trans_value)
  194529. {
  194530. if (row_info->bit_depth == 8)
  194531. {
  194532. png_byte red = trans_value->red & 0xff;
  194533. png_byte green = trans_value->green & 0xff;
  194534. png_byte blue = trans_value->blue & 0xff;
  194535. sp = row + (png_size_t)row_info->rowbytes - 1;
  194536. dp = row + (png_size_t)(row_width << 2) - 1;
  194537. for (i = 0; i < row_width; i++)
  194538. {
  194539. if (*(sp - 2) == red && *(sp - 1) == green && *(sp) == blue)
  194540. *dp-- = 0;
  194541. else
  194542. *dp-- = 0xff;
  194543. *dp-- = *sp--;
  194544. *dp-- = *sp--;
  194545. *dp-- = *sp--;
  194546. }
  194547. }
  194548. else if (row_info->bit_depth == 16)
  194549. {
  194550. png_byte red_high = (trans_value->red >> 8) & 0xff;
  194551. png_byte green_high = (trans_value->green >> 8) & 0xff;
  194552. png_byte blue_high = (trans_value->blue >> 8) & 0xff;
  194553. png_byte red_low = trans_value->red & 0xff;
  194554. png_byte green_low = trans_value->green & 0xff;
  194555. png_byte blue_low = trans_value->blue & 0xff;
  194556. sp = row + row_info->rowbytes - 1;
  194557. dp = row + (png_size_t)(row_width << 3) - 1;
  194558. for (i = 0; i < row_width; i++)
  194559. {
  194560. if (*(sp - 5) == red_high &&
  194561. *(sp - 4) == red_low &&
  194562. *(sp - 3) == green_high &&
  194563. *(sp - 2) == green_low &&
  194564. *(sp - 1) == blue_high &&
  194565. *(sp ) == blue_low)
  194566. {
  194567. *dp-- = 0;
  194568. *dp-- = 0;
  194569. }
  194570. else
  194571. {
  194572. *dp-- = 0xff;
  194573. *dp-- = 0xff;
  194574. }
  194575. *dp-- = *sp--;
  194576. *dp-- = *sp--;
  194577. *dp-- = *sp--;
  194578. *dp-- = *sp--;
  194579. *dp-- = *sp--;
  194580. *dp-- = *sp--;
  194581. }
  194582. }
  194583. row_info->color_type = PNG_COLOR_TYPE_RGB_ALPHA;
  194584. row_info->channels = 4;
  194585. row_info->pixel_depth = (png_byte)(row_info->bit_depth << 2);
  194586. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  194587. }
  194588. }
  194589. }
  194590. #endif
  194591. #if defined(PNG_READ_DITHER_SUPPORTED)
  194592. void /* PRIVATE */
  194593. png_do_dither(png_row_infop row_info, png_bytep row,
  194594. png_bytep palette_lookup, png_bytep dither_lookup)
  194595. {
  194596. png_bytep sp, dp;
  194597. png_uint_32 i;
  194598. png_uint_32 row_width=row_info->width;
  194599. png_debug(1, "in png_do_dither\n");
  194600. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194601. if (row != NULL && row_info != NULL)
  194602. #endif
  194603. {
  194604. if (row_info->color_type == PNG_COLOR_TYPE_RGB &&
  194605. palette_lookup && row_info->bit_depth == 8)
  194606. {
  194607. int r, g, b, p;
  194608. sp = row;
  194609. dp = row;
  194610. for (i = 0; i < row_width; i++)
  194611. {
  194612. r = *sp++;
  194613. g = *sp++;
  194614. b = *sp++;
  194615. /* this looks real messy, but the compiler will reduce
  194616. it down to a reasonable formula. For example, with
  194617. 5 bits per color, we get:
  194618. p = (((r >> 3) & 0x1f) << 10) |
  194619. (((g >> 3) & 0x1f) << 5) |
  194620. ((b >> 3) & 0x1f);
  194621. */
  194622. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  194623. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  194624. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  194625. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  194626. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  194627. (PNG_DITHER_BLUE_BITS)) |
  194628. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  194629. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  194630. *dp++ = palette_lookup[p];
  194631. }
  194632. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  194633. row_info->channels = 1;
  194634. row_info->pixel_depth = row_info->bit_depth;
  194635. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  194636. }
  194637. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  194638. palette_lookup != NULL && row_info->bit_depth == 8)
  194639. {
  194640. int r, g, b, p;
  194641. sp = row;
  194642. dp = row;
  194643. for (i = 0; i < row_width; i++)
  194644. {
  194645. r = *sp++;
  194646. g = *sp++;
  194647. b = *sp++;
  194648. sp++;
  194649. p = (((r >> (8 - PNG_DITHER_RED_BITS)) &
  194650. ((1 << PNG_DITHER_RED_BITS) - 1)) <<
  194651. (PNG_DITHER_GREEN_BITS + PNG_DITHER_BLUE_BITS)) |
  194652. (((g >> (8 - PNG_DITHER_GREEN_BITS)) &
  194653. ((1 << PNG_DITHER_GREEN_BITS) - 1)) <<
  194654. (PNG_DITHER_BLUE_BITS)) |
  194655. ((b >> (8 - PNG_DITHER_BLUE_BITS)) &
  194656. ((1 << PNG_DITHER_BLUE_BITS) - 1));
  194657. *dp++ = palette_lookup[p];
  194658. }
  194659. row_info->color_type = PNG_COLOR_TYPE_PALETTE;
  194660. row_info->channels = 1;
  194661. row_info->pixel_depth = row_info->bit_depth;
  194662. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,row_width);
  194663. }
  194664. else if (row_info->color_type == PNG_COLOR_TYPE_PALETTE &&
  194665. dither_lookup && row_info->bit_depth == 8)
  194666. {
  194667. sp = row;
  194668. for (i = 0; i < row_width; i++, sp++)
  194669. {
  194670. *sp = dither_lookup[*sp];
  194671. }
  194672. }
  194673. }
  194674. }
  194675. #endif
  194676. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194677. #if defined(PNG_READ_GAMMA_SUPPORTED)
  194678. static PNG_CONST int png_gamma_shift[] =
  194679. {0x10, 0x21, 0x42, 0x84, 0x110, 0x248, 0x550, 0xff0, 0x00};
  194680. /* We build the 8- or 16-bit gamma tables here. Note that for 16-bit
  194681. * tables, we don't make a full table if we are reducing to 8-bit in
  194682. * the future. Note also how the gamma_16 tables are segmented so that
  194683. * we don't need to allocate > 64K chunks for a full 16-bit table.
  194684. */
  194685. void /* PRIVATE */
  194686. png_build_gamma_table(png_structp png_ptr)
  194687. {
  194688. png_debug(1, "in png_build_gamma_table\n");
  194689. if (png_ptr->bit_depth <= 8)
  194690. {
  194691. int i;
  194692. double g;
  194693. if (png_ptr->screen_gamma > .000001)
  194694. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  194695. else
  194696. g = 1.0;
  194697. png_ptr->gamma_table = (png_bytep)png_malloc(png_ptr,
  194698. (png_uint_32)256);
  194699. for (i = 0; i < 256; i++)
  194700. {
  194701. png_ptr->gamma_table[i] = (png_byte)(pow((double)i / 255.0,
  194702. g) * 255.0 + .5);
  194703. }
  194704. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  194705. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  194706. if (png_ptr->transformations & ((PNG_BACKGROUND) | PNG_RGB_TO_GRAY))
  194707. {
  194708. g = 1.0 / (png_ptr->gamma);
  194709. png_ptr->gamma_to_1 = (png_bytep)png_malloc(png_ptr,
  194710. (png_uint_32)256);
  194711. for (i = 0; i < 256; i++)
  194712. {
  194713. png_ptr->gamma_to_1[i] = (png_byte)(pow((double)i / 255.0,
  194714. g) * 255.0 + .5);
  194715. }
  194716. png_ptr->gamma_from_1 = (png_bytep)png_malloc(png_ptr,
  194717. (png_uint_32)256);
  194718. if(png_ptr->screen_gamma > 0.000001)
  194719. g = 1.0 / png_ptr->screen_gamma;
  194720. else
  194721. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  194722. for (i = 0; i < 256; i++)
  194723. {
  194724. png_ptr->gamma_from_1[i] = (png_byte)(pow((double)i / 255.0,
  194725. g) * 255.0 + .5);
  194726. }
  194727. }
  194728. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  194729. }
  194730. else
  194731. {
  194732. double g;
  194733. int i, j, shift, num;
  194734. int sig_bit;
  194735. png_uint_32 ig;
  194736. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  194737. {
  194738. sig_bit = (int)png_ptr->sig_bit.red;
  194739. if ((int)png_ptr->sig_bit.green > sig_bit)
  194740. sig_bit = png_ptr->sig_bit.green;
  194741. if ((int)png_ptr->sig_bit.blue > sig_bit)
  194742. sig_bit = png_ptr->sig_bit.blue;
  194743. }
  194744. else
  194745. {
  194746. sig_bit = (int)png_ptr->sig_bit.gray;
  194747. }
  194748. if (sig_bit > 0)
  194749. shift = 16 - sig_bit;
  194750. else
  194751. shift = 0;
  194752. if (png_ptr->transformations & PNG_16_TO_8)
  194753. {
  194754. if (shift < (16 - PNG_MAX_GAMMA_8))
  194755. shift = (16 - PNG_MAX_GAMMA_8);
  194756. }
  194757. if (shift > 8)
  194758. shift = 8;
  194759. if (shift < 0)
  194760. shift = 0;
  194761. png_ptr->gamma_shift = (png_byte)shift;
  194762. num = (1 << (8 - shift));
  194763. if (png_ptr->screen_gamma > .000001)
  194764. g = 1.0 / (png_ptr->gamma * png_ptr->screen_gamma);
  194765. else
  194766. g = 1.0;
  194767. png_ptr->gamma_16_table = (png_uint_16pp)png_malloc(png_ptr,
  194768. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194769. if (png_ptr->transformations & (PNG_16_TO_8 | PNG_BACKGROUND))
  194770. {
  194771. double fin, fout;
  194772. png_uint_32 last, max;
  194773. for (i = 0; i < num; i++)
  194774. {
  194775. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194776. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194777. }
  194778. g = 1.0 / g;
  194779. last = 0;
  194780. for (i = 0; i < 256; i++)
  194781. {
  194782. fout = ((double)i + 0.5) / 256.0;
  194783. fin = pow(fout, g);
  194784. max = (png_uint_32)(fin * (double)((png_uint_32)num << 8));
  194785. while (last <= max)
  194786. {
  194787. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194788. [(int)(last >> (8 - shift))] = (png_uint_16)(
  194789. (png_uint_16)i | ((png_uint_16)i << 8));
  194790. last++;
  194791. }
  194792. }
  194793. while (last < ((png_uint_32)num << 8))
  194794. {
  194795. png_ptr->gamma_16_table[(int)(last & (0xff >> shift))]
  194796. [(int)(last >> (8 - shift))] = (png_uint_16)65535L;
  194797. last++;
  194798. }
  194799. }
  194800. else
  194801. {
  194802. for (i = 0; i < num; i++)
  194803. {
  194804. png_ptr->gamma_16_table[i] = (png_uint_16p)png_malloc(png_ptr,
  194805. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194806. ig = (((png_uint_32)i * (png_uint_32)png_gamma_shift[shift]) >> 4);
  194807. for (j = 0; j < 256; j++)
  194808. {
  194809. png_ptr->gamma_16_table[i][j] =
  194810. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194811. 65535.0, g) * 65535.0 + .5);
  194812. }
  194813. }
  194814. }
  194815. #if defined(PNG_READ_BACKGROUND_SUPPORTED) || \
  194816. defined(PNG_READ_RGB_TO_GRAY_SUPPORTED)
  194817. if (png_ptr->transformations & (PNG_BACKGROUND | PNG_RGB_TO_GRAY))
  194818. {
  194819. g = 1.0 / (png_ptr->gamma);
  194820. png_ptr->gamma_16_to_1 = (png_uint_16pp)png_malloc(png_ptr,
  194821. (png_uint_32)(num * png_sizeof (png_uint_16p )));
  194822. for (i = 0; i < num; i++)
  194823. {
  194824. png_ptr->gamma_16_to_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194825. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194826. ig = (((png_uint_32)i *
  194827. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194828. for (j = 0; j < 256; j++)
  194829. {
  194830. png_ptr->gamma_16_to_1[i][j] =
  194831. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194832. 65535.0, g) * 65535.0 + .5);
  194833. }
  194834. }
  194835. if(png_ptr->screen_gamma > 0.000001)
  194836. g = 1.0 / png_ptr->screen_gamma;
  194837. else
  194838. g = png_ptr->gamma; /* probably doing rgb_to_gray */
  194839. png_ptr->gamma_16_from_1 = (png_uint_16pp)png_malloc(png_ptr,
  194840. (png_uint_32)(num * png_sizeof (png_uint_16p)));
  194841. for (i = 0; i < num; i++)
  194842. {
  194843. png_ptr->gamma_16_from_1[i] = (png_uint_16p)png_malloc(png_ptr,
  194844. (png_uint_32)(256 * png_sizeof (png_uint_16)));
  194845. ig = (((png_uint_32)i *
  194846. (png_uint_32)png_gamma_shift[shift]) >> 4);
  194847. for (j = 0; j < 256; j++)
  194848. {
  194849. png_ptr->gamma_16_from_1[i][j] =
  194850. (png_uint_16)(pow((double)(ig + ((png_uint_32)j << 8)) /
  194851. 65535.0, g) * 65535.0 + .5);
  194852. }
  194853. }
  194854. }
  194855. #endif /* PNG_READ_BACKGROUND_SUPPORTED || PNG_RGB_TO_GRAY_SUPPORTED */
  194856. }
  194857. }
  194858. #endif
  194859. /* To do: install integer version of png_build_gamma_table here */
  194860. #endif
  194861. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  194862. /* undoes intrapixel differencing */
  194863. void /* PRIVATE */
  194864. png_do_read_intrapixel(png_row_infop row_info, png_bytep row)
  194865. {
  194866. png_debug(1, "in png_do_read_intrapixel\n");
  194867. if (
  194868. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  194869. row != NULL && row_info != NULL &&
  194870. #endif
  194871. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  194872. {
  194873. int bytes_per_pixel;
  194874. png_uint_32 row_width = row_info->width;
  194875. if (row_info->bit_depth == 8)
  194876. {
  194877. png_bytep rp;
  194878. png_uint_32 i;
  194879. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194880. bytes_per_pixel = 3;
  194881. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194882. bytes_per_pixel = 4;
  194883. else
  194884. return;
  194885. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194886. {
  194887. *(rp) = (png_byte)((256 + *rp + *(rp+1))&0xff);
  194888. *(rp+2) = (png_byte)((256 + *(rp+2) + *(rp+1))&0xff);
  194889. }
  194890. }
  194891. else if (row_info->bit_depth == 16)
  194892. {
  194893. png_bytep rp;
  194894. png_uint_32 i;
  194895. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  194896. bytes_per_pixel = 6;
  194897. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  194898. bytes_per_pixel = 8;
  194899. else
  194900. return;
  194901. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  194902. {
  194903. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  194904. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  194905. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  194906. png_uint_32 red = (png_uint_32)((s0+s1+65536L) & 0xffffL);
  194907. png_uint_32 blue = (png_uint_32)((s2+s1+65536L) & 0xffffL);
  194908. *(rp ) = (png_byte)((red >> 8) & 0xff);
  194909. *(rp+1) = (png_byte)(red & 0xff);
  194910. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  194911. *(rp+5) = (png_byte)(blue & 0xff);
  194912. }
  194913. }
  194914. }
  194915. }
  194916. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  194917. #endif /* PNG_READ_SUPPORTED */
  194918. /********* End of inlined file: pngrtran.c *********/
  194919. /********* Start of inlined file: pngrutil.c *********/
  194920. /* pngrutil.c - utilities to read a PNG file
  194921. *
  194922. * Last changed in libpng 1.2.21 [October 4, 2007]
  194923. * For conditions of distribution and use, see copyright notice in png.h
  194924. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  194925. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  194926. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  194927. *
  194928. * This file contains routines that are only called from within
  194929. * libpng itself during the course of reading an image.
  194930. */
  194931. #define PNG_INTERNAL
  194932. #if defined(PNG_READ_SUPPORTED)
  194933. #if defined(_WIN32_WCE) && (_WIN32_WCE<0x500)
  194934. # define WIN32_WCE_OLD
  194935. #endif
  194936. #ifdef PNG_FLOATING_POINT_SUPPORTED
  194937. # if defined(WIN32_WCE_OLD)
  194938. /* strtod() function is not supported on WindowsCE */
  194939. __inline double png_strtod(png_structp png_ptr, PNG_CONST char *nptr, char **endptr)
  194940. {
  194941. double result = 0;
  194942. int len;
  194943. wchar_t *str, *end;
  194944. len = MultiByteToWideChar(CP_ACP, 0, nptr, -1, NULL, 0);
  194945. str = (wchar_t *)png_malloc(png_ptr, len * sizeof(wchar_t));
  194946. if ( NULL != str )
  194947. {
  194948. MultiByteToWideChar(CP_ACP, 0, nptr, -1, str, len);
  194949. result = wcstod(str, &end);
  194950. len = WideCharToMultiByte(CP_ACP, 0, end, -1, NULL, 0, NULL, NULL);
  194951. *endptr = (char *)nptr + (png_strlen(nptr) - len + 1);
  194952. png_free(png_ptr, str);
  194953. }
  194954. return result;
  194955. }
  194956. # else
  194957. # define png_strtod(p,a,b) strtod(a,b)
  194958. # endif
  194959. #endif
  194960. png_uint_32 PNGAPI
  194961. png_get_uint_31(png_structp png_ptr, png_bytep buf)
  194962. {
  194963. png_uint_32 i = png_get_uint_32(buf);
  194964. if (i > PNG_UINT_31_MAX)
  194965. png_error(png_ptr, "PNG unsigned integer out of range.");
  194966. return (i);
  194967. }
  194968. #ifndef PNG_READ_BIG_ENDIAN_SUPPORTED
  194969. /* Grab an unsigned 32-bit integer from a buffer in big-endian format. */
  194970. png_uint_32 PNGAPI
  194971. png_get_uint_32(png_bytep buf)
  194972. {
  194973. png_uint_32 i = ((png_uint_32)(*buf) << 24) +
  194974. ((png_uint_32)(*(buf + 1)) << 16) +
  194975. ((png_uint_32)(*(buf + 2)) << 8) +
  194976. (png_uint_32)(*(buf + 3));
  194977. return (i);
  194978. }
  194979. /* Grab a signed 32-bit integer from a buffer in big-endian format. The
  194980. * data is stored in the PNG file in two's complement format, and it is
  194981. * assumed that the machine format for signed integers is the same. */
  194982. png_int_32 PNGAPI
  194983. png_get_int_32(png_bytep buf)
  194984. {
  194985. png_int_32 i = ((png_int_32)(*buf) << 24) +
  194986. ((png_int_32)(*(buf + 1)) << 16) +
  194987. ((png_int_32)(*(buf + 2)) << 8) +
  194988. (png_int_32)(*(buf + 3));
  194989. return (i);
  194990. }
  194991. /* Grab an unsigned 16-bit integer from a buffer in big-endian format. */
  194992. png_uint_16 PNGAPI
  194993. png_get_uint_16(png_bytep buf)
  194994. {
  194995. png_uint_16 i = (png_uint_16)(((png_uint_16)(*buf) << 8) +
  194996. (png_uint_16)(*(buf + 1)));
  194997. return (i);
  194998. }
  194999. #endif /* PNG_READ_BIG_ENDIAN_SUPPORTED */
  195000. /* Read data, and (optionally) run it through the CRC. */
  195001. void /* PRIVATE */
  195002. png_crc_read(png_structp png_ptr, png_bytep buf, png_size_t length)
  195003. {
  195004. if(png_ptr == NULL) return;
  195005. png_read_data(png_ptr, buf, length);
  195006. png_calculate_crc(png_ptr, buf, length);
  195007. }
  195008. /* Optionally skip data and then check the CRC. Depending on whether we
  195009. are reading a ancillary or critical chunk, and how the program has set
  195010. things up, we may calculate the CRC on the data and print a message.
  195011. Returns '1' if there was a CRC error, '0' otherwise. */
  195012. int /* PRIVATE */
  195013. png_crc_finish(png_structp png_ptr, png_uint_32 skip)
  195014. {
  195015. png_size_t i;
  195016. png_size_t istop = png_ptr->zbuf_size;
  195017. for (i = (png_size_t)skip; i > istop; i -= istop)
  195018. {
  195019. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  195020. }
  195021. if (i)
  195022. {
  195023. png_crc_read(png_ptr, png_ptr->zbuf, i);
  195024. }
  195025. if (png_crc_error(png_ptr))
  195026. {
  195027. if (((png_ptr->chunk_name[0] & 0x20) && /* Ancillary */
  195028. !(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)) ||
  195029. (!(png_ptr->chunk_name[0] & 0x20) && /* Critical */
  195030. (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_USE)))
  195031. {
  195032. png_chunk_warning(png_ptr, "CRC error");
  195033. }
  195034. else
  195035. {
  195036. png_chunk_error(png_ptr, "CRC error");
  195037. }
  195038. return (1);
  195039. }
  195040. return (0);
  195041. }
  195042. /* Compare the CRC stored in the PNG file with that calculated by libpng from
  195043. the data it has read thus far. */
  195044. int /* PRIVATE */
  195045. png_crc_error(png_structp png_ptr)
  195046. {
  195047. png_byte crc_bytes[4];
  195048. png_uint_32 crc;
  195049. int need_crc = 1;
  195050. if (png_ptr->chunk_name[0] & 0x20) /* ancillary */
  195051. {
  195052. if ((png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_MASK) ==
  195053. (PNG_FLAG_CRC_ANCILLARY_USE | PNG_FLAG_CRC_ANCILLARY_NOWARN))
  195054. need_crc = 0;
  195055. }
  195056. else /* critical */
  195057. {
  195058. if (png_ptr->flags & PNG_FLAG_CRC_CRITICAL_IGNORE)
  195059. need_crc = 0;
  195060. }
  195061. png_read_data(png_ptr, crc_bytes, 4);
  195062. if (need_crc)
  195063. {
  195064. crc = png_get_uint_32(crc_bytes);
  195065. return ((int)(crc != png_ptr->crc));
  195066. }
  195067. else
  195068. return (0);
  195069. }
  195070. #if defined(PNG_READ_zTXt_SUPPORTED) || defined(PNG_READ_iTXt_SUPPORTED) || \
  195071. defined(PNG_READ_iCCP_SUPPORTED)
  195072. /*
  195073. * Decompress trailing data in a chunk. The assumption is that chunkdata
  195074. * points at an allocated area holding the contents of a chunk with a
  195075. * trailing compressed part. What we get back is an allocated area
  195076. * holding the original prefix part and an uncompressed version of the
  195077. * trailing part (the malloc area passed in is freed).
  195078. */
  195079. png_charp /* PRIVATE */
  195080. png_decompress_chunk(png_structp png_ptr, int comp_type,
  195081. png_charp chunkdata, png_size_t chunklength,
  195082. png_size_t prefix_size, png_size_t *newlength)
  195083. {
  195084. static PNG_CONST char msg[] = "Error decoding compressed text";
  195085. png_charp text;
  195086. png_size_t text_size;
  195087. if (comp_type == PNG_COMPRESSION_TYPE_BASE)
  195088. {
  195089. int ret = Z_OK;
  195090. png_ptr->zstream.next_in = (png_bytep)(chunkdata + prefix_size);
  195091. png_ptr->zstream.avail_in = (uInt)(chunklength - prefix_size);
  195092. png_ptr->zstream.next_out = png_ptr->zbuf;
  195093. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195094. text_size = 0;
  195095. text = NULL;
  195096. while (png_ptr->zstream.avail_in)
  195097. {
  195098. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  195099. if (ret != Z_OK && ret != Z_STREAM_END)
  195100. {
  195101. if (png_ptr->zstream.msg != NULL)
  195102. png_warning(png_ptr, png_ptr->zstream.msg);
  195103. else
  195104. png_warning(png_ptr, msg);
  195105. inflateReset(&png_ptr->zstream);
  195106. png_ptr->zstream.avail_in = 0;
  195107. if (text == NULL)
  195108. {
  195109. text_size = prefix_size + png_sizeof(msg) + 1;
  195110. text = (png_charp)png_malloc_warn(png_ptr, text_size);
  195111. if (text == NULL)
  195112. {
  195113. png_free(png_ptr,chunkdata);
  195114. png_error(png_ptr,"Not enough memory to decompress chunk");
  195115. }
  195116. png_memcpy(text, chunkdata, prefix_size);
  195117. }
  195118. text[text_size - 1] = 0x00;
  195119. /* Copy what we can of the error message into the text chunk */
  195120. text_size = (png_size_t)(chunklength - (text - chunkdata) - 1);
  195121. text_size = png_sizeof(msg) > text_size ? text_size :
  195122. png_sizeof(msg);
  195123. png_memcpy(text + prefix_size, msg, text_size + 1);
  195124. break;
  195125. }
  195126. if (!png_ptr->zstream.avail_out || ret == Z_STREAM_END)
  195127. {
  195128. if (text == NULL)
  195129. {
  195130. text_size = prefix_size +
  195131. png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  195132. text = (png_charp)png_malloc_warn(png_ptr, text_size + 1);
  195133. if (text == NULL)
  195134. {
  195135. png_free(png_ptr,chunkdata);
  195136. png_error(png_ptr,"Not enough memory to decompress chunk.");
  195137. }
  195138. png_memcpy(text + prefix_size, png_ptr->zbuf,
  195139. text_size - prefix_size);
  195140. png_memcpy(text, chunkdata, prefix_size);
  195141. *(text + text_size) = 0x00;
  195142. }
  195143. else
  195144. {
  195145. png_charp tmp;
  195146. tmp = text;
  195147. text = (png_charp)png_malloc_warn(png_ptr,
  195148. (png_uint_32)(text_size +
  195149. png_ptr->zbuf_size - png_ptr->zstream.avail_out + 1));
  195150. if (text == NULL)
  195151. {
  195152. png_free(png_ptr, tmp);
  195153. png_free(png_ptr, chunkdata);
  195154. png_error(png_ptr,"Not enough memory to decompress chunk..");
  195155. }
  195156. png_memcpy(text, tmp, text_size);
  195157. png_free(png_ptr, tmp);
  195158. png_memcpy(text + text_size, png_ptr->zbuf,
  195159. (png_ptr->zbuf_size - png_ptr->zstream.avail_out));
  195160. text_size += png_ptr->zbuf_size - png_ptr->zstream.avail_out;
  195161. *(text + text_size) = 0x00;
  195162. }
  195163. if (ret == Z_STREAM_END)
  195164. break;
  195165. else
  195166. {
  195167. png_ptr->zstream.next_out = png_ptr->zbuf;
  195168. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  195169. }
  195170. }
  195171. }
  195172. if (ret != Z_STREAM_END)
  195173. {
  195174. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  195175. char umsg[52];
  195176. if (ret == Z_BUF_ERROR)
  195177. png_snprintf(umsg, 52,
  195178. "Buffer error in compressed datastream in %s chunk",
  195179. png_ptr->chunk_name);
  195180. else if (ret == Z_DATA_ERROR)
  195181. png_snprintf(umsg, 52,
  195182. "Data error in compressed datastream in %s chunk",
  195183. png_ptr->chunk_name);
  195184. else
  195185. png_snprintf(umsg, 52,
  195186. "Incomplete compressed datastream in %s chunk",
  195187. png_ptr->chunk_name);
  195188. png_warning(png_ptr, umsg);
  195189. #else
  195190. png_warning(png_ptr,
  195191. "Incomplete compressed datastream in chunk other than IDAT");
  195192. #endif
  195193. text_size=prefix_size;
  195194. if (text == NULL)
  195195. {
  195196. text = (png_charp)png_malloc_warn(png_ptr, text_size+1);
  195197. if (text == NULL)
  195198. {
  195199. png_free(png_ptr, chunkdata);
  195200. png_error(png_ptr,"Not enough memory for text.");
  195201. }
  195202. png_memcpy(text, chunkdata, prefix_size);
  195203. }
  195204. *(text + text_size) = 0x00;
  195205. }
  195206. inflateReset(&png_ptr->zstream);
  195207. png_ptr->zstream.avail_in = 0;
  195208. png_free(png_ptr, chunkdata);
  195209. chunkdata = text;
  195210. *newlength=text_size;
  195211. }
  195212. else /* if (comp_type != PNG_COMPRESSION_TYPE_BASE) */
  195213. {
  195214. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  195215. char umsg[50];
  195216. png_snprintf(umsg, 50,
  195217. "Unknown zTXt compression type %d", comp_type);
  195218. png_warning(png_ptr, umsg);
  195219. #else
  195220. png_warning(png_ptr, "Unknown zTXt compression type");
  195221. #endif
  195222. *(chunkdata + prefix_size) = 0x00;
  195223. *newlength=prefix_size;
  195224. }
  195225. return chunkdata;
  195226. }
  195227. #endif
  195228. /* read and check the IDHR chunk */
  195229. void /* PRIVATE */
  195230. png_handle_IHDR(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195231. {
  195232. png_byte buf[13];
  195233. png_uint_32 width, height;
  195234. int bit_depth, color_type, compression_type, filter_type;
  195235. int interlace_type;
  195236. png_debug(1, "in png_handle_IHDR\n");
  195237. if (png_ptr->mode & PNG_HAVE_IHDR)
  195238. png_error(png_ptr, "Out of place IHDR");
  195239. /* check the length */
  195240. if (length != 13)
  195241. png_error(png_ptr, "Invalid IHDR chunk");
  195242. png_ptr->mode |= PNG_HAVE_IHDR;
  195243. png_crc_read(png_ptr, buf, 13);
  195244. png_crc_finish(png_ptr, 0);
  195245. width = png_get_uint_31(png_ptr, buf);
  195246. height = png_get_uint_31(png_ptr, buf + 4);
  195247. bit_depth = buf[8];
  195248. color_type = buf[9];
  195249. compression_type = buf[10];
  195250. filter_type = buf[11];
  195251. interlace_type = buf[12];
  195252. /* set internal variables */
  195253. png_ptr->width = width;
  195254. png_ptr->height = height;
  195255. png_ptr->bit_depth = (png_byte)bit_depth;
  195256. png_ptr->interlaced = (png_byte)interlace_type;
  195257. png_ptr->color_type = (png_byte)color_type;
  195258. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  195259. png_ptr->filter_type = (png_byte)filter_type;
  195260. #endif
  195261. png_ptr->compression_type = (png_byte)compression_type;
  195262. /* find number of channels */
  195263. switch (png_ptr->color_type)
  195264. {
  195265. case PNG_COLOR_TYPE_GRAY:
  195266. case PNG_COLOR_TYPE_PALETTE:
  195267. png_ptr->channels = 1;
  195268. break;
  195269. case PNG_COLOR_TYPE_RGB:
  195270. png_ptr->channels = 3;
  195271. break;
  195272. case PNG_COLOR_TYPE_GRAY_ALPHA:
  195273. png_ptr->channels = 2;
  195274. break;
  195275. case PNG_COLOR_TYPE_RGB_ALPHA:
  195276. png_ptr->channels = 4;
  195277. break;
  195278. }
  195279. /* set up other useful info */
  195280. png_ptr->pixel_depth = (png_byte)(png_ptr->bit_depth *
  195281. png_ptr->channels);
  195282. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->width);
  195283. png_debug1(3,"bit_depth = %d\n", png_ptr->bit_depth);
  195284. png_debug1(3,"channels = %d\n", png_ptr->channels);
  195285. png_debug1(3,"rowbytes = %lu\n", png_ptr->rowbytes);
  195286. png_set_IHDR(png_ptr, info_ptr, width, height, bit_depth,
  195287. color_type, interlace_type, compression_type, filter_type);
  195288. }
  195289. /* read and check the palette */
  195290. void /* PRIVATE */
  195291. png_handle_PLTE(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195292. {
  195293. png_color palette[PNG_MAX_PALETTE_LENGTH];
  195294. int num, i;
  195295. #ifndef PNG_NO_POINTER_INDEXING
  195296. png_colorp pal_ptr;
  195297. #endif
  195298. png_debug(1, "in png_handle_PLTE\n");
  195299. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195300. png_error(png_ptr, "Missing IHDR before PLTE");
  195301. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195302. {
  195303. png_warning(png_ptr, "Invalid PLTE after IDAT");
  195304. png_crc_finish(png_ptr, length);
  195305. return;
  195306. }
  195307. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195308. png_error(png_ptr, "Duplicate PLTE chunk");
  195309. png_ptr->mode |= PNG_HAVE_PLTE;
  195310. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  195311. {
  195312. png_warning(png_ptr,
  195313. "Ignoring PLTE chunk in grayscale PNG");
  195314. png_crc_finish(png_ptr, length);
  195315. return;
  195316. }
  195317. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  195318. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  195319. {
  195320. png_crc_finish(png_ptr, length);
  195321. return;
  195322. }
  195323. #endif
  195324. if (length > 3*PNG_MAX_PALETTE_LENGTH || length % 3)
  195325. {
  195326. if (png_ptr->color_type != PNG_COLOR_TYPE_PALETTE)
  195327. {
  195328. png_warning(png_ptr, "Invalid palette chunk");
  195329. png_crc_finish(png_ptr, length);
  195330. return;
  195331. }
  195332. else
  195333. {
  195334. png_error(png_ptr, "Invalid palette chunk");
  195335. }
  195336. }
  195337. num = (int)length / 3;
  195338. #ifndef PNG_NO_POINTER_INDEXING
  195339. for (i = 0, pal_ptr = palette; i < num; i++, pal_ptr++)
  195340. {
  195341. png_byte buf[3];
  195342. png_crc_read(png_ptr, buf, 3);
  195343. pal_ptr->red = buf[0];
  195344. pal_ptr->green = buf[1];
  195345. pal_ptr->blue = buf[2];
  195346. }
  195347. #else
  195348. for (i = 0; i < num; i++)
  195349. {
  195350. png_byte buf[3];
  195351. png_crc_read(png_ptr, buf, 3);
  195352. /* don't depend upon png_color being any order */
  195353. palette[i].red = buf[0];
  195354. palette[i].green = buf[1];
  195355. palette[i].blue = buf[2];
  195356. }
  195357. #endif
  195358. /* If we actually NEED the PLTE chunk (ie for a paletted image), we do
  195359. whatever the normal CRC configuration tells us. However, if we
  195360. have an RGB image, the PLTE can be considered ancillary, so
  195361. we will act as though it is. */
  195362. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  195363. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195364. #endif
  195365. {
  195366. png_crc_finish(png_ptr, 0);
  195367. }
  195368. #if !defined(PNG_READ_OPT_PLTE_SUPPORTED)
  195369. else if (png_crc_error(png_ptr)) /* Only if we have a CRC error */
  195370. {
  195371. /* If we don't want to use the data from an ancillary chunk,
  195372. we have two options: an error abort, or a warning and we
  195373. ignore the data in this chunk (which should be OK, since
  195374. it's considered ancillary for a RGB or RGBA image). */
  195375. if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_USE))
  195376. {
  195377. if (png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN)
  195378. {
  195379. png_chunk_error(png_ptr, "CRC error");
  195380. }
  195381. else
  195382. {
  195383. png_chunk_warning(png_ptr, "CRC error");
  195384. return;
  195385. }
  195386. }
  195387. /* Otherwise, we (optionally) emit a warning and use the chunk. */
  195388. else if (!(png_ptr->flags & PNG_FLAG_CRC_ANCILLARY_NOWARN))
  195389. {
  195390. png_chunk_warning(png_ptr, "CRC error");
  195391. }
  195392. }
  195393. #endif
  195394. png_set_PLTE(png_ptr, info_ptr, palette, num);
  195395. #if defined(PNG_READ_tRNS_SUPPORTED)
  195396. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195397. {
  195398. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  195399. {
  195400. if (png_ptr->num_trans > (png_uint_16)num)
  195401. {
  195402. png_warning(png_ptr, "Truncating incorrect tRNS chunk length");
  195403. png_ptr->num_trans = (png_uint_16)num;
  195404. }
  195405. if (info_ptr->num_trans > (png_uint_16)num)
  195406. {
  195407. png_warning(png_ptr, "Truncating incorrect info tRNS chunk length");
  195408. info_ptr->num_trans = (png_uint_16)num;
  195409. }
  195410. }
  195411. }
  195412. #endif
  195413. }
  195414. void /* PRIVATE */
  195415. png_handle_IEND(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195416. {
  195417. png_debug(1, "in png_handle_IEND\n");
  195418. if (!(png_ptr->mode & PNG_HAVE_IHDR) || !(png_ptr->mode & PNG_HAVE_IDAT))
  195419. {
  195420. png_error(png_ptr, "No image in file");
  195421. }
  195422. png_ptr->mode |= (PNG_AFTER_IDAT | PNG_HAVE_IEND);
  195423. if (length != 0)
  195424. {
  195425. png_warning(png_ptr, "Incorrect IEND chunk length");
  195426. }
  195427. png_crc_finish(png_ptr, length);
  195428. info_ptr =info_ptr; /* quiet compiler warnings about unused info_ptr */
  195429. }
  195430. #if defined(PNG_READ_gAMA_SUPPORTED)
  195431. void /* PRIVATE */
  195432. png_handle_gAMA(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195433. {
  195434. png_fixed_point igamma;
  195435. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195436. float file_gamma;
  195437. #endif
  195438. png_byte buf[4];
  195439. png_debug(1, "in png_handle_gAMA\n");
  195440. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195441. png_error(png_ptr, "Missing IHDR before gAMA");
  195442. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195443. {
  195444. png_warning(png_ptr, "Invalid gAMA after IDAT");
  195445. png_crc_finish(png_ptr, length);
  195446. return;
  195447. }
  195448. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195449. /* Should be an error, but we can cope with it */
  195450. png_warning(png_ptr, "Out of place gAMA chunk");
  195451. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA)
  195452. #if defined(PNG_READ_sRGB_SUPPORTED)
  195453. && !(info_ptr->valid & PNG_INFO_sRGB)
  195454. #endif
  195455. )
  195456. {
  195457. png_warning(png_ptr, "Duplicate gAMA chunk");
  195458. png_crc_finish(png_ptr, length);
  195459. return;
  195460. }
  195461. if (length != 4)
  195462. {
  195463. png_warning(png_ptr, "Incorrect gAMA chunk length");
  195464. png_crc_finish(png_ptr, length);
  195465. return;
  195466. }
  195467. png_crc_read(png_ptr, buf, 4);
  195468. if (png_crc_finish(png_ptr, 0))
  195469. return;
  195470. igamma = (png_fixed_point)png_get_uint_32(buf);
  195471. /* check for zero gamma */
  195472. if (igamma == 0)
  195473. {
  195474. png_warning(png_ptr,
  195475. "Ignoring gAMA chunk with gamma=0");
  195476. return;
  195477. }
  195478. #if defined(PNG_READ_sRGB_SUPPORTED)
  195479. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  195480. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  195481. {
  195482. png_warning(png_ptr,
  195483. "Ignoring incorrect gAMA value when sRGB is also present");
  195484. #ifndef PNG_NO_CONSOLE_IO
  195485. fprintf(stderr, "gamma = (%d/100000)\n", (int)igamma);
  195486. #endif
  195487. return;
  195488. }
  195489. #endif /* PNG_READ_sRGB_SUPPORTED */
  195490. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195491. file_gamma = (float)igamma / (float)100000.0;
  195492. # ifdef PNG_READ_GAMMA_SUPPORTED
  195493. png_ptr->gamma = file_gamma;
  195494. # endif
  195495. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  195496. #endif
  195497. #ifdef PNG_FIXED_POINT_SUPPORTED
  195498. png_set_gAMA_fixed(png_ptr, info_ptr, igamma);
  195499. #endif
  195500. }
  195501. #endif
  195502. #if defined(PNG_READ_sBIT_SUPPORTED)
  195503. void /* PRIVATE */
  195504. png_handle_sBIT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195505. {
  195506. png_size_t truelen;
  195507. png_byte buf[4];
  195508. png_debug(1, "in png_handle_sBIT\n");
  195509. buf[0] = buf[1] = buf[2] = buf[3] = 0;
  195510. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195511. png_error(png_ptr, "Missing IHDR before sBIT");
  195512. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195513. {
  195514. png_warning(png_ptr, "Invalid sBIT after IDAT");
  195515. png_crc_finish(png_ptr, length);
  195516. return;
  195517. }
  195518. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195519. {
  195520. /* Should be an error, but we can cope with it */
  195521. png_warning(png_ptr, "Out of place sBIT chunk");
  195522. }
  195523. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sBIT))
  195524. {
  195525. png_warning(png_ptr, "Duplicate sBIT chunk");
  195526. png_crc_finish(png_ptr, length);
  195527. return;
  195528. }
  195529. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  195530. truelen = 3;
  195531. else
  195532. truelen = (png_size_t)png_ptr->channels;
  195533. if (length != truelen || length > 4)
  195534. {
  195535. png_warning(png_ptr, "Incorrect sBIT chunk length");
  195536. png_crc_finish(png_ptr, length);
  195537. return;
  195538. }
  195539. png_crc_read(png_ptr, buf, truelen);
  195540. if (png_crc_finish(png_ptr, 0))
  195541. return;
  195542. if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  195543. {
  195544. png_ptr->sig_bit.red = buf[0];
  195545. png_ptr->sig_bit.green = buf[1];
  195546. png_ptr->sig_bit.blue = buf[2];
  195547. png_ptr->sig_bit.alpha = buf[3];
  195548. }
  195549. else
  195550. {
  195551. png_ptr->sig_bit.gray = buf[0];
  195552. png_ptr->sig_bit.red = buf[0];
  195553. png_ptr->sig_bit.green = buf[0];
  195554. png_ptr->sig_bit.blue = buf[0];
  195555. png_ptr->sig_bit.alpha = buf[1];
  195556. }
  195557. png_set_sBIT(png_ptr, info_ptr, &(png_ptr->sig_bit));
  195558. }
  195559. #endif
  195560. #if defined(PNG_READ_cHRM_SUPPORTED)
  195561. void /* PRIVATE */
  195562. png_handle_cHRM(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195563. {
  195564. png_byte buf[4];
  195565. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195566. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  195567. #endif
  195568. png_fixed_point int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  195569. int_y_green, int_x_blue, int_y_blue;
  195570. png_uint_32 uint_x, uint_y;
  195571. png_debug(1, "in png_handle_cHRM\n");
  195572. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195573. png_error(png_ptr, "Missing IHDR before cHRM");
  195574. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195575. {
  195576. png_warning(png_ptr, "Invalid cHRM after IDAT");
  195577. png_crc_finish(png_ptr, length);
  195578. return;
  195579. }
  195580. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195581. /* Should be an error, but we can cope with it */
  195582. png_warning(png_ptr, "Missing PLTE before cHRM");
  195583. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM)
  195584. #if defined(PNG_READ_sRGB_SUPPORTED)
  195585. && !(info_ptr->valid & PNG_INFO_sRGB)
  195586. #endif
  195587. )
  195588. {
  195589. png_warning(png_ptr, "Duplicate cHRM chunk");
  195590. png_crc_finish(png_ptr, length);
  195591. return;
  195592. }
  195593. if (length != 32)
  195594. {
  195595. png_warning(png_ptr, "Incorrect cHRM chunk length");
  195596. png_crc_finish(png_ptr, length);
  195597. return;
  195598. }
  195599. png_crc_read(png_ptr, buf, 4);
  195600. uint_x = png_get_uint_32(buf);
  195601. png_crc_read(png_ptr, buf, 4);
  195602. uint_y = png_get_uint_32(buf);
  195603. if (uint_x > 80000L || uint_y > 80000L ||
  195604. uint_x + uint_y > 100000L)
  195605. {
  195606. png_warning(png_ptr, "Invalid cHRM white point");
  195607. png_crc_finish(png_ptr, 24);
  195608. return;
  195609. }
  195610. int_x_white = (png_fixed_point)uint_x;
  195611. int_y_white = (png_fixed_point)uint_y;
  195612. png_crc_read(png_ptr, buf, 4);
  195613. uint_x = png_get_uint_32(buf);
  195614. png_crc_read(png_ptr, buf, 4);
  195615. uint_y = png_get_uint_32(buf);
  195616. if (uint_x + uint_y > 100000L)
  195617. {
  195618. png_warning(png_ptr, "Invalid cHRM red point");
  195619. png_crc_finish(png_ptr, 16);
  195620. return;
  195621. }
  195622. int_x_red = (png_fixed_point)uint_x;
  195623. int_y_red = (png_fixed_point)uint_y;
  195624. png_crc_read(png_ptr, buf, 4);
  195625. uint_x = png_get_uint_32(buf);
  195626. png_crc_read(png_ptr, buf, 4);
  195627. uint_y = png_get_uint_32(buf);
  195628. if (uint_x + uint_y > 100000L)
  195629. {
  195630. png_warning(png_ptr, "Invalid cHRM green point");
  195631. png_crc_finish(png_ptr, 8);
  195632. return;
  195633. }
  195634. int_x_green = (png_fixed_point)uint_x;
  195635. int_y_green = (png_fixed_point)uint_y;
  195636. png_crc_read(png_ptr, buf, 4);
  195637. uint_x = png_get_uint_32(buf);
  195638. png_crc_read(png_ptr, buf, 4);
  195639. uint_y = png_get_uint_32(buf);
  195640. if (uint_x + uint_y > 100000L)
  195641. {
  195642. png_warning(png_ptr, "Invalid cHRM blue point");
  195643. png_crc_finish(png_ptr, 0);
  195644. return;
  195645. }
  195646. int_x_blue = (png_fixed_point)uint_x;
  195647. int_y_blue = (png_fixed_point)uint_y;
  195648. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195649. white_x = (float)int_x_white / (float)100000.0;
  195650. white_y = (float)int_y_white / (float)100000.0;
  195651. red_x = (float)int_x_red / (float)100000.0;
  195652. red_y = (float)int_y_red / (float)100000.0;
  195653. green_x = (float)int_x_green / (float)100000.0;
  195654. green_y = (float)int_y_green / (float)100000.0;
  195655. blue_x = (float)int_x_blue / (float)100000.0;
  195656. blue_y = (float)int_y_blue / (float)100000.0;
  195657. #endif
  195658. #if defined(PNG_READ_sRGB_SUPPORTED)
  195659. if ((info_ptr != NULL) && (info_ptr->valid & PNG_INFO_sRGB))
  195660. {
  195661. if (PNG_OUT_OF_RANGE(int_x_white, 31270, 1000) ||
  195662. PNG_OUT_OF_RANGE(int_y_white, 32900, 1000) ||
  195663. PNG_OUT_OF_RANGE(int_x_red, 64000L, 1000) ||
  195664. PNG_OUT_OF_RANGE(int_y_red, 33000, 1000) ||
  195665. PNG_OUT_OF_RANGE(int_x_green, 30000, 1000) ||
  195666. PNG_OUT_OF_RANGE(int_y_green, 60000L, 1000) ||
  195667. PNG_OUT_OF_RANGE(int_x_blue, 15000, 1000) ||
  195668. PNG_OUT_OF_RANGE(int_y_blue, 6000, 1000))
  195669. {
  195670. png_warning(png_ptr,
  195671. "Ignoring incorrect cHRM value when sRGB is also present");
  195672. #ifndef PNG_NO_CONSOLE_IO
  195673. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195674. fprintf(stderr,"wx=%f, wy=%f, rx=%f, ry=%f\n",
  195675. white_x, white_y, red_x, red_y);
  195676. fprintf(stderr,"gx=%f, gy=%f, bx=%f, by=%f\n",
  195677. green_x, green_y, blue_x, blue_y);
  195678. #else
  195679. fprintf(stderr,"wx=%ld, wy=%ld, rx=%ld, ry=%ld\n",
  195680. int_x_white, int_y_white, int_x_red, int_y_red);
  195681. fprintf(stderr,"gx=%ld, gy=%ld, bx=%ld, by=%ld\n",
  195682. int_x_green, int_y_green, int_x_blue, int_y_blue);
  195683. #endif
  195684. #endif /* PNG_NO_CONSOLE_IO */
  195685. }
  195686. png_crc_finish(png_ptr, 0);
  195687. return;
  195688. }
  195689. #endif /* PNG_READ_sRGB_SUPPORTED */
  195690. #ifdef PNG_FLOATING_POINT_SUPPORTED
  195691. png_set_cHRM(png_ptr, info_ptr,
  195692. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  195693. #endif
  195694. #ifdef PNG_FIXED_POINT_SUPPORTED
  195695. png_set_cHRM_fixed(png_ptr, info_ptr,
  195696. int_x_white, int_y_white, int_x_red, int_y_red, int_x_green,
  195697. int_y_green, int_x_blue, int_y_blue);
  195698. #endif
  195699. if (png_crc_finish(png_ptr, 0))
  195700. return;
  195701. }
  195702. #endif
  195703. #if defined(PNG_READ_sRGB_SUPPORTED)
  195704. void /* PRIVATE */
  195705. png_handle_sRGB(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195706. {
  195707. int intent;
  195708. png_byte buf[1];
  195709. png_debug(1, "in png_handle_sRGB\n");
  195710. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195711. png_error(png_ptr, "Missing IHDR before sRGB");
  195712. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195713. {
  195714. png_warning(png_ptr, "Invalid sRGB after IDAT");
  195715. png_crc_finish(png_ptr, length);
  195716. return;
  195717. }
  195718. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195719. /* Should be an error, but we can cope with it */
  195720. png_warning(png_ptr, "Out of place sRGB chunk");
  195721. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sRGB))
  195722. {
  195723. png_warning(png_ptr, "Duplicate sRGB chunk");
  195724. png_crc_finish(png_ptr, length);
  195725. return;
  195726. }
  195727. if (length != 1)
  195728. {
  195729. png_warning(png_ptr, "Incorrect sRGB chunk length");
  195730. png_crc_finish(png_ptr, length);
  195731. return;
  195732. }
  195733. png_crc_read(png_ptr, buf, 1);
  195734. if (png_crc_finish(png_ptr, 0))
  195735. return;
  195736. intent = buf[0];
  195737. /* check for bad intent */
  195738. if (intent >= PNG_sRGB_INTENT_LAST)
  195739. {
  195740. png_warning(png_ptr, "Unknown sRGB intent");
  195741. return;
  195742. }
  195743. #if defined(PNG_READ_gAMA_SUPPORTED) && defined(PNG_READ_GAMMA_SUPPORTED)
  195744. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_gAMA))
  195745. {
  195746. png_fixed_point igamma;
  195747. #ifdef PNG_FIXED_POINT_SUPPORTED
  195748. igamma=info_ptr->int_gamma;
  195749. #else
  195750. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195751. igamma=(png_fixed_point)(info_ptr->gamma * 100000.);
  195752. # endif
  195753. #endif
  195754. if (PNG_OUT_OF_RANGE(igamma, 45500L, 500))
  195755. {
  195756. png_warning(png_ptr,
  195757. "Ignoring incorrect gAMA value when sRGB is also present");
  195758. #ifndef PNG_NO_CONSOLE_IO
  195759. # ifdef PNG_FIXED_POINT_SUPPORTED
  195760. fprintf(stderr,"incorrect gamma=(%d/100000)\n",(int)png_ptr->int_gamma);
  195761. # else
  195762. # ifdef PNG_FLOATING_POINT_SUPPORTED
  195763. fprintf(stderr,"incorrect gamma=%f\n",png_ptr->gamma);
  195764. # endif
  195765. # endif
  195766. #endif
  195767. }
  195768. }
  195769. #endif /* PNG_READ_gAMA_SUPPORTED */
  195770. #ifdef PNG_READ_cHRM_SUPPORTED
  195771. #ifdef PNG_FIXED_POINT_SUPPORTED
  195772. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_cHRM))
  195773. if (PNG_OUT_OF_RANGE(info_ptr->int_x_white, 31270, 1000) ||
  195774. PNG_OUT_OF_RANGE(info_ptr->int_y_white, 32900, 1000) ||
  195775. PNG_OUT_OF_RANGE(info_ptr->int_x_red, 64000L, 1000) ||
  195776. PNG_OUT_OF_RANGE(info_ptr->int_y_red, 33000, 1000) ||
  195777. PNG_OUT_OF_RANGE(info_ptr->int_x_green, 30000, 1000) ||
  195778. PNG_OUT_OF_RANGE(info_ptr->int_y_green, 60000L, 1000) ||
  195779. PNG_OUT_OF_RANGE(info_ptr->int_x_blue, 15000, 1000) ||
  195780. PNG_OUT_OF_RANGE(info_ptr->int_y_blue, 6000, 1000))
  195781. {
  195782. png_warning(png_ptr,
  195783. "Ignoring incorrect cHRM value when sRGB is also present");
  195784. }
  195785. #endif /* PNG_FIXED_POINT_SUPPORTED */
  195786. #endif /* PNG_READ_cHRM_SUPPORTED */
  195787. png_set_sRGB_gAMA_and_cHRM(png_ptr, info_ptr, intent);
  195788. }
  195789. #endif /* PNG_READ_sRGB_SUPPORTED */
  195790. #if defined(PNG_READ_iCCP_SUPPORTED)
  195791. void /* PRIVATE */
  195792. png_handle_iCCP(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195793. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195794. {
  195795. png_charp chunkdata;
  195796. png_byte compression_type;
  195797. png_bytep pC;
  195798. png_charp profile;
  195799. png_uint_32 skip = 0;
  195800. png_uint_32 profile_size, profile_length;
  195801. png_size_t slength, prefix_length, data_length;
  195802. png_debug(1, "in png_handle_iCCP\n");
  195803. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195804. png_error(png_ptr, "Missing IHDR before iCCP");
  195805. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195806. {
  195807. png_warning(png_ptr, "Invalid iCCP after IDAT");
  195808. png_crc_finish(png_ptr, length);
  195809. return;
  195810. }
  195811. else if (png_ptr->mode & PNG_HAVE_PLTE)
  195812. /* Should be an error, but we can cope with it */
  195813. png_warning(png_ptr, "Out of place iCCP chunk");
  195814. if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_iCCP))
  195815. {
  195816. png_warning(png_ptr, "Duplicate iCCP chunk");
  195817. png_crc_finish(png_ptr, length);
  195818. return;
  195819. }
  195820. #ifdef PNG_MAX_MALLOC_64K
  195821. if (length > (png_uint_32)65535L)
  195822. {
  195823. png_warning(png_ptr, "iCCP chunk too large to fit in memory");
  195824. skip = length - (png_uint_32)65535L;
  195825. length = (png_uint_32)65535L;
  195826. }
  195827. #endif
  195828. chunkdata = (png_charp)png_malloc(png_ptr, length + 1);
  195829. slength = (png_size_t)length;
  195830. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195831. if (png_crc_finish(png_ptr, skip))
  195832. {
  195833. png_free(png_ptr, chunkdata);
  195834. return;
  195835. }
  195836. chunkdata[slength] = 0x00;
  195837. for (profile = chunkdata; *profile; profile++)
  195838. /* empty loop to find end of name */ ;
  195839. ++profile;
  195840. /* there should be at least one zero (the compression type byte)
  195841. following the separator, and we should be on it */
  195842. if ( profile >= chunkdata + slength - 1)
  195843. {
  195844. png_free(png_ptr, chunkdata);
  195845. png_warning(png_ptr, "Malformed iCCP chunk");
  195846. return;
  195847. }
  195848. /* compression_type should always be zero */
  195849. compression_type = *profile++;
  195850. if (compression_type)
  195851. {
  195852. png_warning(png_ptr, "Ignoring nonzero compression type in iCCP chunk");
  195853. compression_type=0x00; /* Reset it to zero (libpng-1.0.6 through 1.0.8
  195854. wrote nonzero) */
  195855. }
  195856. prefix_length = profile - chunkdata;
  195857. chunkdata = png_decompress_chunk(png_ptr, compression_type, chunkdata,
  195858. slength, prefix_length, &data_length);
  195859. profile_length = data_length - prefix_length;
  195860. if ( prefix_length > data_length || profile_length < 4)
  195861. {
  195862. png_free(png_ptr, chunkdata);
  195863. png_warning(png_ptr, "Profile size field missing from iCCP chunk");
  195864. return;
  195865. }
  195866. /* Check the profile_size recorded in the first 32 bits of the ICC profile */
  195867. pC = (png_bytep)(chunkdata+prefix_length);
  195868. profile_size = ((*(pC ))<<24) |
  195869. ((*(pC+1))<<16) |
  195870. ((*(pC+2))<< 8) |
  195871. ((*(pC+3)) );
  195872. if(profile_size < profile_length)
  195873. profile_length = profile_size;
  195874. if(profile_size > profile_length)
  195875. {
  195876. png_free(png_ptr, chunkdata);
  195877. png_warning(png_ptr, "Ignoring truncated iCCP profile.");
  195878. return;
  195879. }
  195880. png_set_iCCP(png_ptr, info_ptr, chunkdata, compression_type,
  195881. chunkdata + prefix_length, profile_length);
  195882. png_free(png_ptr, chunkdata);
  195883. }
  195884. #endif /* PNG_READ_iCCP_SUPPORTED */
  195885. #if defined(PNG_READ_sPLT_SUPPORTED)
  195886. void /* PRIVATE */
  195887. png_handle_sPLT(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  195888. /* Note: this does not properly handle chunks that are > 64K under DOS */
  195889. {
  195890. png_bytep chunkdata;
  195891. png_bytep entry_start;
  195892. png_sPLT_t new_palette;
  195893. #ifdef PNG_NO_POINTER_INDEXING
  195894. png_sPLT_entryp pp;
  195895. #endif
  195896. int data_length, entry_size, i;
  195897. png_uint_32 skip = 0;
  195898. png_size_t slength;
  195899. png_debug(1, "in png_handle_sPLT\n");
  195900. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  195901. png_error(png_ptr, "Missing IHDR before sPLT");
  195902. else if (png_ptr->mode & PNG_HAVE_IDAT)
  195903. {
  195904. png_warning(png_ptr, "Invalid sPLT after IDAT");
  195905. png_crc_finish(png_ptr, length);
  195906. return;
  195907. }
  195908. #ifdef PNG_MAX_MALLOC_64K
  195909. if (length > (png_uint_32)65535L)
  195910. {
  195911. png_warning(png_ptr, "sPLT chunk too large to fit in memory");
  195912. skip = length - (png_uint_32)65535L;
  195913. length = (png_uint_32)65535L;
  195914. }
  195915. #endif
  195916. chunkdata = (png_bytep)png_malloc(png_ptr, length + 1);
  195917. slength = (png_size_t)length;
  195918. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  195919. if (png_crc_finish(png_ptr, skip))
  195920. {
  195921. png_free(png_ptr, chunkdata);
  195922. return;
  195923. }
  195924. chunkdata[slength] = 0x00;
  195925. for (entry_start = chunkdata; *entry_start; entry_start++)
  195926. /* empty loop to find end of name */ ;
  195927. ++entry_start;
  195928. /* a sample depth should follow the separator, and we should be on it */
  195929. if (entry_start > chunkdata + slength - 2)
  195930. {
  195931. png_free(png_ptr, chunkdata);
  195932. png_warning(png_ptr, "malformed sPLT chunk");
  195933. return;
  195934. }
  195935. new_palette.depth = *entry_start++;
  195936. entry_size = (new_palette.depth == 8 ? 6 : 10);
  195937. data_length = (slength - (entry_start - chunkdata));
  195938. /* integrity-check the data length */
  195939. if (data_length % entry_size)
  195940. {
  195941. png_free(png_ptr, chunkdata);
  195942. png_warning(png_ptr, "sPLT chunk has bad length");
  195943. return;
  195944. }
  195945. new_palette.nentries = (png_int_32) ( data_length / entry_size);
  195946. if ((png_uint_32) new_palette.nentries > (png_uint_32) (PNG_SIZE_MAX /
  195947. png_sizeof(png_sPLT_entry)))
  195948. {
  195949. png_warning(png_ptr, "sPLT chunk too long");
  195950. return;
  195951. }
  195952. new_palette.entries = (png_sPLT_entryp)png_malloc_warn(
  195953. png_ptr, new_palette.nentries * png_sizeof(png_sPLT_entry));
  195954. if (new_palette.entries == NULL)
  195955. {
  195956. png_warning(png_ptr, "sPLT chunk requires too much memory");
  195957. return;
  195958. }
  195959. #ifndef PNG_NO_POINTER_INDEXING
  195960. for (i = 0; i < new_palette.nentries; i++)
  195961. {
  195962. png_sPLT_entryp pp = new_palette.entries + i;
  195963. if (new_palette.depth == 8)
  195964. {
  195965. pp->red = *entry_start++;
  195966. pp->green = *entry_start++;
  195967. pp->blue = *entry_start++;
  195968. pp->alpha = *entry_start++;
  195969. }
  195970. else
  195971. {
  195972. pp->red = png_get_uint_16(entry_start); entry_start += 2;
  195973. pp->green = png_get_uint_16(entry_start); entry_start += 2;
  195974. pp->blue = png_get_uint_16(entry_start); entry_start += 2;
  195975. pp->alpha = png_get_uint_16(entry_start); entry_start += 2;
  195976. }
  195977. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195978. }
  195979. #else
  195980. pp = new_palette.entries;
  195981. for (i = 0; i < new_palette.nentries; i++)
  195982. {
  195983. if (new_palette.depth == 8)
  195984. {
  195985. pp[i].red = *entry_start++;
  195986. pp[i].green = *entry_start++;
  195987. pp[i].blue = *entry_start++;
  195988. pp[i].alpha = *entry_start++;
  195989. }
  195990. else
  195991. {
  195992. pp[i].red = png_get_uint_16(entry_start); entry_start += 2;
  195993. pp[i].green = png_get_uint_16(entry_start); entry_start += 2;
  195994. pp[i].blue = png_get_uint_16(entry_start); entry_start += 2;
  195995. pp[i].alpha = png_get_uint_16(entry_start); entry_start += 2;
  195996. }
  195997. pp->frequency = png_get_uint_16(entry_start); entry_start += 2;
  195998. }
  195999. #endif
  196000. /* discard all chunk data except the name and stash that */
  196001. new_palette.name = (png_charp)chunkdata;
  196002. png_set_sPLT(png_ptr, info_ptr, &new_palette, 1);
  196003. png_free(png_ptr, chunkdata);
  196004. png_free(png_ptr, new_palette.entries);
  196005. }
  196006. #endif /* PNG_READ_sPLT_SUPPORTED */
  196007. #if defined(PNG_READ_tRNS_SUPPORTED)
  196008. void /* PRIVATE */
  196009. png_handle_tRNS(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196010. {
  196011. png_byte readbuf[PNG_MAX_PALETTE_LENGTH];
  196012. int bit_mask;
  196013. png_debug(1, "in png_handle_tRNS\n");
  196014. /* For non-indexed color, mask off any bits in the tRNS value that
  196015. * exceed the bit depth. Some creators were writing extra bits there.
  196016. * This is not needed for indexed color. */
  196017. bit_mask = (1 << png_ptr->bit_depth) - 1;
  196018. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  196019. png_error(png_ptr, "Missing IHDR before tRNS");
  196020. else if (png_ptr->mode & PNG_HAVE_IDAT)
  196021. {
  196022. png_warning(png_ptr, "Invalid tRNS after IDAT");
  196023. png_crc_finish(png_ptr, length);
  196024. return;
  196025. }
  196026. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tRNS))
  196027. {
  196028. png_warning(png_ptr, "Duplicate tRNS chunk");
  196029. png_crc_finish(png_ptr, length);
  196030. return;
  196031. }
  196032. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  196033. {
  196034. png_byte buf[2];
  196035. if (length != 2)
  196036. {
  196037. png_warning(png_ptr, "Incorrect tRNS chunk length");
  196038. png_crc_finish(png_ptr, length);
  196039. return;
  196040. }
  196041. png_crc_read(png_ptr, buf, 2);
  196042. png_ptr->num_trans = 1;
  196043. png_ptr->trans_values.gray = png_get_uint_16(buf) & bit_mask;
  196044. }
  196045. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  196046. {
  196047. png_byte buf[6];
  196048. if (length != 6)
  196049. {
  196050. png_warning(png_ptr, "Incorrect tRNS chunk length");
  196051. png_crc_finish(png_ptr, length);
  196052. return;
  196053. }
  196054. png_crc_read(png_ptr, buf, (png_size_t)length);
  196055. png_ptr->num_trans = 1;
  196056. png_ptr->trans_values.red = png_get_uint_16(buf) & bit_mask;
  196057. png_ptr->trans_values.green = png_get_uint_16(buf + 2) & bit_mask;
  196058. png_ptr->trans_values.blue = png_get_uint_16(buf + 4) & bit_mask;
  196059. }
  196060. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196061. {
  196062. if (!(png_ptr->mode & PNG_HAVE_PLTE))
  196063. {
  196064. /* Should be an error, but we can cope with it. */
  196065. png_warning(png_ptr, "Missing PLTE before tRNS");
  196066. }
  196067. if (length > (png_uint_32)png_ptr->num_palette ||
  196068. length > PNG_MAX_PALETTE_LENGTH)
  196069. {
  196070. png_warning(png_ptr, "Incorrect tRNS chunk length");
  196071. png_crc_finish(png_ptr, length);
  196072. return;
  196073. }
  196074. if (length == 0)
  196075. {
  196076. png_warning(png_ptr, "Zero length tRNS chunk");
  196077. png_crc_finish(png_ptr, length);
  196078. return;
  196079. }
  196080. png_crc_read(png_ptr, readbuf, (png_size_t)length);
  196081. png_ptr->num_trans = (png_uint_16)length;
  196082. }
  196083. else
  196084. {
  196085. png_warning(png_ptr, "tRNS chunk not allowed with alpha channel");
  196086. png_crc_finish(png_ptr, length);
  196087. return;
  196088. }
  196089. if (png_crc_finish(png_ptr, 0))
  196090. {
  196091. png_ptr->num_trans = 0;
  196092. return;
  196093. }
  196094. png_set_tRNS(png_ptr, info_ptr, readbuf, png_ptr->num_trans,
  196095. &(png_ptr->trans_values));
  196096. }
  196097. #endif
  196098. #if defined(PNG_READ_bKGD_SUPPORTED)
  196099. void /* PRIVATE */
  196100. png_handle_bKGD(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196101. {
  196102. png_size_t truelen;
  196103. png_byte buf[6];
  196104. png_debug(1, "in png_handle_bKGD\n");
  196105. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  196106. png_error(png_ptr, "Missing IHDR before bKGD");
  196107. else if (png_ptr->mode & PNG_HAVE_IDAT)
  196108. {
  196109. png_warning(png_ptr, "Invalid bKGD after IDAT");
  196110. png_crc_finish(png_ptr, length);
  196111. return;
  196112. }
  196113. else if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE &&
  196114. !(png_ptr->mode & PNG_HAVE_PLTE))
  196115. {
  196116. png_warning(png_ptr, "Missing PLTE before bKGD");
  196117. png_crc_finish(png_ptr, length);
  196118. return;
  196119. }
  196120. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_bKGD))
  196121. {
  196122. png_warning(png_ptr, "Duplicate bKGD chunk");
  196123. png_crc_finish(png_ptr, length);
  196124. return;
  196125. }
  196126. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196127. truelen = 1;
  196128. else if (png_ptr->color_type & PNG_COLOR_MASK_COLOR)
  196129. truelen = 6;
  196130. else
  196131. truelen = 2;
  196132. if (length != truelen)
  196133. {
  196134. png_warning(png_ptr, "Incorrect bKGD chunk length");
  196135. png_crc_finish(png_ptr, length);
  196136. return;
  196137. }
  196138. png_crc_read(png_ptr, buf, truelen);
  196139. if (png_crc_finish(png_ptr, 0))
  196140. return;
  196141. /* We convert the index value into RGB components so that we can allow
  196142. * arbitrary RGB values for background when we have transparency, and
  196143. * so it is easy to determine the RGB values of the background color
  196144. * from the info_ptr struct. */
  196145. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  196146. {
  196147. png_ptr->background.index = buf[0];
  196148. if(info_ptr->num_palette)
  196149. {
  196150. if(buf[0] > info_ptr->num_palette)
  196151. {
  196152. png_warning(png_ptr, "Incorrect bKGD chunk index value");
  196153. return;
  196154. }
  196155. png_ptr->background.red =
  196156. (png_uint_16)png_ptr->palette[buf[0]].red;
  196157. png_ptr->background.green =
  196158. (png_uint_16)png_ptr->palette[buf[0]].green;
  196159. png_ptr->background.blue =
  196160. (png_uint_16)png_ptr->palette[buf[0]].blue;
  196161. }
  196162. }
  196163. else if (!(png_ptr->color_type & PNG_COLOR_MASK_COLOR)) /* GRAY */
  196164. {
  196165. png_ptr->background.red =
  196166. png_ptr->background.green =
  196167. png_ptr->background.blue =
  196168. png_ptr->background.gray = png_get_uint_16(buf);
  196169. }
  196170. else
  196171. {
  196172. png_ptr->background.red = png_get_uint_16(buf);
  196173. png_ptr->background.green = png_get_uint_16(buf + 2);
  196174. png_ptr->background.blue = png_get_uint_16(buf + 4);
  196175. }
  196176. png_set_bKGD(png_ptr, info_ptr, &(png_ptr->background));
  196177. }
  196178. #endif
  196179. #if defined(PNG_READ_hIST_SUPPORTED)
  196180. void /* PRIVATE */
  196181. png_handle_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196182. {
  196183. unsigned int num, i;
  196184. png_uint_16 readbuf[PNG_MAX_PALETTE_LENGTH];
  196185. png_debug(1, "in png_handle_hIST\n");
  196186. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  196187. png_error(png_ptr, "Missing IHDR before hIST");
  196188. else if (png_ptr->mode & PNG_HAVE_IDAT)
  196189. {
  196190. png_warning(png_ptr, "Invalid hIST after IDAT");
  196191. png_crc_finish(png_ptr, length);
  196192. return;
  196193. }
  196194. else if (!(png_ptr->mode & PNG_HAVE_PLTE))
  196195. {
  196196. png_warning(png_ptr, "Missing PLTE before hIST");
  196197. png_crc_finish(png_ptr, length);
  196198. return;
  196199. }
  196200. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_hIST))
  196201. {
  196202. png_warning(png_ptr, "Duplicate hIST chunk");
  196203. png_crc_finish(png_ptr, length);
  196204. return;
  196205. }
  196206. num = length / 2 ;
  196207. if (num != (unsigned int) png_ptr->num_palette || num >
  196208. (unsigned int) PNG_MAX_PALETTE_LENGTH)
  196209. {
  196210. png_warning(png_ptr, "Incorrect hIST chunk length");
  196211. png_crc_finish(png_ptr, length);
  196212. return;
  196213. }
  196214. for (i = 0; i < num; i++)
  196215. {
  196216. png_byte buf[2];
  196217. png_crc_read(png_ptr, buf, 2);
  196218. readbuf[i] = png_get_uint_16(buf);
  196219. }
  196220. if (png_crc_finish(png_ptr, 0))
  196221. return;
  196222. png_set_hIST(png_ptr, info_ptr, readbuf);
  196223. }
  196224. #endif
  196225. #if defined(PNG_READ_pHYs_SUPPORTED)
  196226. void /* PRIVATE */
  196227. png_handle_pHYs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196228. {
  196229. png_byte buf[9];
  196230. png_uint_32 res_x, res_y;
  196231. int unit_type;
  196232. png_debug(1, "in png_handle_pHYs\n");
  196233. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  196234. png_error(png_ptr, "Missing IHDR before pHYs");
  196235. else if (png_ptr->mode & PNG_HAVE_IDAT)
  196236. {
  196237. png_warning(png_ptr, "Invalid pHYs after IDAT");
  196238. png_crc_finish(png_ptr, length);
  196239. return;
  196240. }
  196241. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pHYs))
  196242. {
  196243. png_warning(png_ptr, "Duplicate pHYs chunk");
  196244. png_crc_finish(png_ptr, length);
  196245. return;
  196246. }
  196247. if (length != 9)
  196248. {
  196249. png_warning(png_ptr, "Incorrect pHYs chunk length");
  196250. png_crc_finish(png_ptr, length);
  196251. return;
  196252. }
  196253. png_crc_read(png_ptr, buf, 9);
  196254. if (png_crc_finish(png_ptr, 0))
  196255. return;
  196256. res_x = png_get_uint_32(buf);
  196257. res_y = png_get_uint_32(buf + 4);
  196258. unit_type = buf[8];
  196259. png_set_pHYs(png_ptr, info_ptr, res_x, res_y, unit_type);
  196260. }
  196261. #endif
  196262. #if defined(PNG_READ_oFFs_SUPPORTED)
  196263. void /* PRIVATE */
  196264. png_handle_oFFs(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196265. {
  196266. png_byte buf[9];
  196267. png_int_32 offset_x, offset_y;
  196268. int unit_type;
  196269. png_debug(1, "in png_handle_oFFs\n");
  196270. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  196271. png_error(png_ptr, "Missing IHDR before oFFs");
  196272. else if (png_ptr->mode & PNG_HAVE_IDAT)
  196273. {
  196274. png_warning(png_ptr, "Invalid oFFs after IDAT");
  196275. png_crc_finish(png_ptr, length);
  196276. return;
  196277. }
  196278. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_oFFs))
  196279. {
  196280. png_warning(png_ptr, "Duplicate oFFs chunk");
  196281. png_crc_finish(png_ptr, length);
  196282. return;
  196283. }
  196284. if (length != 9)
  196285. {
  196286. png_warning(png_ptr, "Incorrect oFFs chunk length");
  196287. png_crc_finish(png_ptr, length);
  196288. return;
  196289. }
  196290. png_crc_read(png_ptr, buf, 9);
  196291. if (png_crc_finish(png_ptr, 0))
  196292. return;
  196293. offset_x = png_get_int_32(buf);
  196294. offset_y = png_get_int_32(buf + 4);
  196295. unit_type = buf[8];
  196296. png_set_oFFs(png_ptr, info_ptr, offset_x, offset_y, unit_type);
  196297. }
  196298. #endif
  196299. #if defined(PNG_READ_pCAL_SUPPORTED)
  196300. /* read the pCAL chunk (described in the PNG Extensions document) */
  196301. void /* PRIVATE */
  196302. png_handle_pCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196303. {
  196304. png_charp purpose;
  196305. png_int_32 X0, X1;
  196306. png_byte type, nparams;
  196307. png_charp buf, units, endptr;
  196308. png_charpp params;
  196309. png_size_t slength;
  196310. int i;
  196311. png_debug(1, "in png_handle_pCAL\n");
  196312. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  196313. png_error(png_ptr, "Missing IHDR before pCAL");
  196314. else if (png_ptr->mode & PNG_HAVE_IDAT)
  196315. {
  196316. png_warning(png_ptr, "Invalid pCAL after IDAT");
  196317. png_crc_finish(png_ptr, length);
  196318. return;
  196319. }
  196320. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_pCAL))
  196321. {
  196322. png_warning(png_ptr, "Duplicate pCAL chunk");
  196323. png_crc_finish(png_ptr, length);
  196324. return;
  196325. }
  196326. png_debug1(2, "Allocating and reading pCAL chunk data (%lu bytes)\n",
  196327. length + 1);
  196328. purpose = (png_charp)png_malloc_warn(png_ptr, length + 1);
  196329. if (purpose == NULL)
  196330. {
  196331. png_warning(png_ptr, "No memory for pCAL purpose.");
  196332. return;
  196333. }
  196334. slength = (png_size_t)length;
  196335. png_crc_read(png_ptr, (png_bytep)purpose, slength);
  196336. if (png_crc_finish(png_ptr, 0))
  196337. {
  196338. png_free(png_ptr, purpose);
  196339. return;
  196340. }
  196341. purpose[slength] = 0x00; /* null terminate the last string */
  196342. png_debug(3, "Finding end of pCAL purpose string\n");
  196343. for (buf = purpose; *buf; buf++)
  196344. /* empty loop */ ;
  196345. endptr = purpose + slength;
  196346. /* We need to have at least 12 bytes after the purpose string
  196347. in order to get the parameter information. */
  196348. if (endptr <= buf + 12)
  196349. {
  196350. png_warning(png_ptr, "Invalid pCAL data");
  196351. png_free(png_ptr, purpose);
  196352. return;
  196353. }
  196354. png_debug(3, "Reading pCAL X0, X1, type, nparams, and units\n");
  196355. X0 = png_get_int_32((png_bytep)buf+1);
  196356. X1 = png_get_int_32((png_bytep)buf+5);
  196357. type = buf[9];
  196358. nparams = buf[10];
  196359. units = buf + 11;
  196360. png_debug(3, "Checking pCAL equation type and number of parameters\n");
  196361. /* Check that we have the right number of parameters for known
  196362. equation types. */
  196363. if ((type == PNG_EQUATION_LINEAR && nparams != 2) ||
  196364. (type == PNG_EQUATION_BASE_E && nparams != 3) ||
  196365. (type == PNG_EQUATION_ARBITRARY && nparams != 3) ||
  196366. (type == PNG_EQUATION_HYPERBOLIC && nparams != 4))
  196367. {
  196368. png_warning(png_ptr, "Invalid pCAL parameters for equation type");
  196369. png_free(png_ptr, purpose);
  196370. return;
  196371. }
  196372. else if (type >= PNG_EQUATION_LAST)
  196373. {
  196374. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  196375. }
  196376. for (buf = units; *buf; buf++)
  196377. /* Empty loop to move past the units string. */ ;
  196378. png_debug(3, "Allocating pCAL parameters array\n");
  196379. params = (png_charpp)png_malloc_warn(png_ptr, (png_uint_32)(nparams
  196380. *png_sizeof(png_charp))) ;
  196381. if (params == NULL)
  196382. {
  196383. png_free(png_ptr, purpose);
  196384. png_warning(png_ptr, "No memory for pCAL params.");
  196385. return;
  196386. }
  196387. /* Get pointers to the start of each parameter string. */
  196388. for (i = 0; i < (int)nparams; i++)
  196389. {
  196390. buf++; /* Skip the null string terminator from previous parameter. */
  196391. png_debug1(3, "Reading pCAL parameter %d\n", i);
  196392. for (params[i] = buf; buf <= endptr && *buf != 0x00; buf++)
  196393. /* Empty loop to move past each parameter string */ ;
  196394. /* Make sure we haven't run out of data yet */
  196395. if (buf > endptr)
  196396. {
  196397. png_warning(png_ptr, "Invalid pCAL data");
  196398. png_free(png_ptr, purpose);
  196399. png_free(png_ptr, params);
  196400. return;
  196401. }
  196402. }
  196403. png_set_pCAL(png_ptr, info_ptr, purpose, X0, X1, type, nparams,
  196404. units, params);
  196405. png_free(png_ptr, purpose);
  196406. png_free(png_ptr, params);
  196407. }
  196408. #endif
  196409. #if defined(PNG_READ_sCAL_SUPPORTED)
  196410. /* read the sCAL chunk */
  196411. void /* PRIVATE */
  196412. png_handle_sCAL(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196413. {
  196414. png_charp buffer, ep;
  196415. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196416. double width, height;
  196417. png_charp vp;
  196418. #else
  196419. #ifdef PNG_FIXED_POINT_SUPPORTED
  196420. png_charp swidth, sheight;
  196421. #endif
  196422. #endif
  196423. png_size_t slength;
  196424. png_debug(1, "in png_handle_sCAL\n");
  196425. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  196426. png_error(png_ptr, "Missing IHDR before sCAL");
  196427. else if (png_ptr->mode & PNG_HAVE_IDAT)
  196428. {
  196429. png_warning(png_ptr, "Invalid sCAL after IDAT");
  196430. png_crc_finish(png_ptr, length);
  196431. return;
  196432. }
  196433. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_sCAL))
  196434. {
  196435. png_warning(png_ptr, "Duplicate sCAL chunk");
  196436. png_crc_finish(png_ptr, length);
  196437. return;
  196438. }
  196439. png_debug1(2, "Allocating and reading sCAL chunk data (%lu bytes)\n",
  196440. length + 1);
  196441. buffer = (png_charp)png_malloc_warn(png_ptr, length + 1);
  196442. if (buffer == NULL)
  196443. {
  196444. png_warning(png_ptr, "Out of memory while processing sCAL chunk");
  196445. return;
  196446. }
  196447. slength = (png_size_t)length;
  196448. png_crc_read(png_ptr, (png_bytep)buffer, slength);
  196449. if (png_crc_finish(png_ptr, 0))
  196450. {
  196451. png_free(png_ptr, buffer);
  196452. return;
  196453. }
  196454. buffer[slength] = 0x00; /* null terminate the last string */
  196455. ep = buffer + 1; /* skip unit byte */
  196456. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196457. width = png_strtod(png_ptr, ep, &vp);
  196458. if (*vp)
  196459. {
  196460. png_warning(png_ptr, "malformed width string in sCAL chunk");
  196461. return;
  196462. }
  196463. #else
  196464. #ifdef PNG_FIXED_POINT_SUPPORTED
  196465. swidth = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  196466. if (swidth == NULL)
  196467. {
  196468. png_warning(png_ptr, "Out of memory while processing sCAL chunk width");
  196469. return;
  196470. }
  196471. png_memcpy(swidth, ep, (png_size_t)png_strlen(ep));
  196472. #endif
  196473. #endif
  196474. for (ep = buffer; *ep; ep++)
  196475. /* empty loop */ ;
  196476. ep++;
  196477. if (buffer + slength < ep)
  196478. {
  196479. png_warning(png_ptr, "Truncated sCAL chunk");
  196480. #if defined(PNG_FIXED_POINT_SUPPORTED) && \
  196481. !defined(PNG_FLOATING_POINT_SUPPORTED)
  196482. png_free(png_ptr, swidth);
  196483. #endif
  196484. png_free(png_ptr, buffer);
  196485. return;
  196486. }
  196487. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196488. height = png_strtod(png_ptr, ep, &vp);
  196489. if (*vp)
  196490. {
  196491. png_warning(png_ptr, "malformed height string in sCAL chunk");
  196492. return;
  196493. }
  196494. #else
  196495. #ifdef PNG_FIXED_POINT_SUPPORTED
  196496. sheight = (png_charp)png_malloc_warn(png_ptr, png_strlen(ep) + 1);
  196497. if (swidth == NULL)
  196498. {
  196499. png_warning(png_ptr, "Out of memory while processing sCAL chunk height");
  196500. return;
  196501. }
  196502. png_memcpy(sheight, ep, (png_size_t)png_strlen(ep));
  196503. #endif
  196504. #endif
  196505. if (buffer + slength < ep
  196506. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196507. || width <= 0. || height <= 0.
  196508. #endif
  196509. )
  196510. {
  196511. png_warning(png_ptr, "Invalid sCAL data");
  196512. png_free(png_ptr, buffer);
  196513. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  196514. png_free(png_ptr, swidth);
  196515. png_free(png_ptr, sheight);
  196516. #endif
  196517. return;
  196518. }
  196519. #ifdef PNG_FLOATING_POINT_SUPPORTED
  196520. png_set_sCAL(png_ptr, info_ptr, buffer[0], width, height);
  196521. #else
  196522. #ifdef PNG_FIXED_POINT_SUPPORTED
  196523. png_set_sCAL_s(png_ptr, info_ptr, buffer[0], swidth, sheight);
  196524. #endif
  196525. #endif
  196526. png_free(png_ptr, buffer);
  196527. #if defined(PNG_FIXED_POINT_SUPPORTED) && !defined(PNG_FLOATING_POINT_SUPPORTED)
  196528. png_free(png_ptr, swidth);
  196529. png_free(png_ptr, sheight);
  196530. #endif
  196531. }
  196532. #endif
  196533. #if defined(PNG_READ_tIME_SUPPORTED)
  196534. void /* PRIVATE */
  196535. png_handle_tIME(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196536. {
  196537. png_byte buf[7];
  196538. png_time mod_time;
  196539. png_debug(1, "in png_handle_tIME\n");
  196540. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  196541. png_error(png_ptr, "Out of place tIME chunk");
  196542. else if (info_ptr != NULL && (info_ptr->valid & PNG_INFO_tIME))
  196543. {
  196544. png_warning(png_ptr, "Duplicate tIME chunk");
  196545. png_crc_finish(png_ptr, length);
  196546. return;
  196547. }
  196548. if (png_ptr->mode & PNG_HAVE_IDAT)
  196549. png_ptr->mode |= PNG_AFTER_IDAT;
  196550. if (length != 7)
  196551. {
  196552. png_warning(png_ptr, "Incorrect tIME chunk length");
  196553. png_crc_finish(png_ptr, length);
  196554. return;
  196555. }
  196556. png_crc_read(png_ptr, buf, 7);
  196557. if (png_crc_finish(png_ptr, 0))
  196558. return;
  196559. mod_time.second = buf[6];
  196560. mod_time.minute = buf[5];
  196561. mod_time.hour = buf[4];
  196562. mod_time.day = buf[3];
  196563. mod_time.month = buf[2];
  196564. mod_time.year = png_get_uint_16(buf);
  196565. png_set_tIME(png_ptr, info_ptr, &mod_time);
  196566. }
  196567. #endif
  196568. #if defined(PNG_READ_tEXt_SUPPORTED)
  196569. /* Note: this does not properly handle chunks that are > 64K under DOS */
  196570. void /* PRIVATE */
  196571. png_handle_tEXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196572. {
  196573. png_textp text_ptr;
  196574. png_charp key;
  196575. png_charp text;
  196576. png_uint_32 skip = 0;
  196577. png_size_t slength;
  196578. int ret;
  196579. png_debug(1, "in png_handle_tEXt\n");
  196580. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  196581. png_error(png_ptr, "Missing IHDR before tEXt");
  196582. if (png_ptr->mode & PNG_HAVE_IDAT)
  196583. png_ptr->mode |= PNG_AFTER_IDAT;
  196584. #ifdef PNG_MAX_MALLOC_64K
  196585. if (length > (png_uint_32)65535L)
  196586. {
  196587. png_warning(png_ptr, "tEXt chunk too large to fit in memory");
  196588. skip = length - (png_uint_32)65535L;
  196589. length = (png_uint_32)65535L;
  196590. }
  196591. #endif
  196592. key = (png_charp)png_malloc_warn(png_ptr, length + 1);
  196593. if (key == NULL)
  196594. {
  196595. png_warning(png_ptr, "No memory to process text chunk.");
  196596. return;
  196597. }
  196598. slength = (png_size_t)length;
  196599. png_crc_read(png_ptr, (png_bytep)key, slength);
  196600. if (png_crc_finish(png_ptr, skip))
  196601. {
  196602. png_free(png_ptr, key);
  196603. return;
  196604. }
  196605. key[slength] = 0x00;
  196606. for (text = key; *text; text++)
  196607. /* empty loop to find end of key */ ;
  196608. if (text != key + slength)
  196609. text++;
  196610. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  196611. (png_uint_32)png_sizeof(png_text));
  196612. if (text_ptr == NULL)
  196613. {
  196614. png_warning(png_ptr, "Not enough memory to process text chunk.");
  196615. png_free(png_ptr, key);
  196616. return;
  196617. }
  196618. text_ptr->compression = PNG_TEXT_COMPRESSION_NONE;
  196619. text_ptr->key = key;
  196620. #ifdef PNG_iTXt_SUPPORTED
  196621. text_ptr->lang = NULL;
  196622. text_ptr->lang_key = NULL;
  196623. text_ptr->itxt_length = 0;
  196624. #endif
  196625. text_ptr->text = text;
  196626. text_ptr->text_length = png_strlen(text);
  196627. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  196628. png_free(png_ptr, key);
  196629. png_free(png_ptr, text_ptr);
  196630. if (ret)
  196631. png_warning(png_ptr, "Insufficient memory to process text chunk.");
  196632. }
  196633. #endif
  196634. #if defined(PNG_READ_zTXt_SUPPORTED)
  196635. /* note: this does not correctly handle chunks that are > 64K under DOS */
  196636. void /* PRIVATE */
  196637. png_handle_zTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196638. {
  196639. png_textp text_ptr;
  196640. png_charp chunkdata;
  196641. png_charp text;
  196642. int comp_type;
  196643. int ret;
  196644. png_size_t slength, prefix_len, data_len;
  196645. png_debug(1, "in png_handle_zTXt\n");
  196646. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  196647. png_error(png_ptr, "Missing IHDR before zTXt");
  196648. if (png_ptr->mode & PNG_HAVE_IDAT)
  196649. png_ptr->mode |= PNG_AFTER_IDAT;
  196650. #ifdef PNG_MAX_MALLOC_64K
  196651. /* We will no doubt have problems with chunks even half this size, but
  196652. there is no hard and fast rule to tell us where to stop. */
  196653. if (length > (png_uint_32)65535L)
  196654. {
  196655. png_warning(png_ptr,"zTXt chunk too large to fit in memory");
  196656. png_crc_finish(png_ptr, length);
  196657. return;
  196658. }
  196659. #endif
  196660. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  196661. if (chunkdata == NULL)
  196662. {
  196663. png_warning(png_ptr,"Out of memory processing zTXt chunk.");
  196664. return;
  196665. }
  196666. slength = (png_size_t)length;
  196667. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  196668. if (png_crc_finish(png_ptr, 0))
  196669. {
  196670. png_free(png_ptr, chunkdata);
  196671. return;
  196672. }
  196673. chunkdata[slength] = 0x00;
  196674. for (text = chunkdata; *text; text++)
  196675. /* empty loop */ ;
  196676. /* zTXt must have some text after the chunkdataword */
  196677. if (text >= chunkdata + slength - 2)
  196678. {
  196679. png_warning(png_ptr, "Truncated zTXt chunk");
  196680. png_free(png_ptr, chunkdata);
  196681. return;
  196682. }
  196683. else
  196684. {
  196685. comp_type = *(++text);
  196686. if (comp_type != PNG_TEXT_COMPRESSION_zTXt)
  196687. {
  196688. png_warning(png_ptr, "Unknown compression type in zTXt chunk");
  196689. comp_type = PNG_TEXT_COMPRESSION_zTXt;
  196690. }
  196691. text++; /* skip the compression_method byte */
  196692. }
  196693. prefix_len = text - chunkdata;
  196694. chunkdata = (png_charp)png_decompress_chunk(png_ptr, comp_type, chunkdata,
  196695. (png_size_t)length, prefix_len, &data_len);
  196696. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  196697. (png_uint_32)png_sizeof(png_text));
  196698. if (text_ptr == NULL)
  196699. {
  196700. png_warning(png_ptr,"Not enough memory to process zTXt chunk.");
  196701. png_free(png_ptr, chunkdata);
  196702. return;
  196703. }
  196704. text_ptr->compression = comp_type;
  196705. text_ptr->key = chunkdata;
  196706. #ifdef PNG_iTXt_SUPPORTED
  196707. text_ptr->lang = NULL;
  196708. text_ptr->lang_key = NULL;
  196709. text_ptr->itxt_length = 0;
  196710. #endif
  196711. text_ptr->text = chunkdata + prefix_len;
  196712. text_ptr->text_length = data_len;
  196713. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  196714. png_free(png_ptr, text_ptr);
  196715. png_free(png_ptr, chunkdata);
  196716. if (ret)
  196717. png_error(png_ptr, "Insufficient memory to store zTXt chunk.");
  196718. }
  196719. #endif
  196720. #if defined(PNG_READ_iTXt_SUPPORTED)
  196721. /* note: this does not correctly handle chunks that are > 64K under DOS */
  196722. void /* PRIVATE */
  196723. png_handle_iTXt(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196724. {
  196725. png_textp text_ptr;
  196726. png_charp chunkdata;
  196727. png_charp key, lang, text, lang_key;
  196728. int comp_flag;
  196729. int comp_type = 0;
  196730. int ret;
  196731. png_size_t slength, prefix_len, data_len;
  196732. png_debug(1, "in png_handle_iTXt\n");
  196733. if (!(png_ptr->mode & PNG_HAVE_IHDR))
  196734. png_error(png_ptr, "Missing IHDR before iTXt");
  196735. if (png_ptr->mode & PNG_HAVE_IDAT)
  196736. png_ptr->mode |= PNG_AFTER_IDAT;
  196737. #ifdef PNG_MAX_MALLOC_64K
  196738. /* We will no doubt have problems with chunks even half this size, but
  196739. there is no hard and fast rule to tell us where to stop. */
  196740. if (length > (png_uint_32)65535L)
  196741. {
  196742. png_warning(png_ptr,"iTXt chunk too large to fit in memory");
  196743. png_crc_finish(png_ptr, length);
  196744. return;
  196745. }
  196746. #endif
  196747. chunkdata = (png_charp)png_malloc_warn(png_ptr, length + 1);
  196748. if (chunkdata == NULL)
  196749. {
  196750. png_warning(png_ptr, "No memory to process iTXt chunk.");
  196751. return;
  196752. }
  196753. slength = (png_size_t)length;
  196754. png_crc_read(png_ptr, (png_bytep)chunkdata, slength);
  196755. if (png_crc_finish(png_ptr, 0))
  196756. {
  196757. png_free(png_ptr, chunkdata);
  196758. return;
  196759. }
  196760. chunkdata[slength] = 0x00;
  196761. for (lang = chunkdata; *lang; lang++)
  196762. /* empty loop */ ;
  196763. lang++; /* skip NUL separator */
  196764. /* iTXt must have a language tag (possibly empty), two compression bytes,
  196765. translated keyword (possibly empty), and possibly some text after the
  196766. keyword */
  196767. if (lang >= chunkdata + slength - 3)
  196768. {
  196769. png_warning(png_ptr, "Truncated iTXt chunk");
  196770. png_free(png_ptr, chunkdata);
  196771. return;
  196772. }
  196773. else
  196774. {
  196775. comp_flag = *lang++;
  196776. comp_type = *lang++;
  196777. }
  196778. for (lang_key = lang; *lang_key; lang_key++)
  196779. /* empty loop */ ;
  196780. lang_key++; /* skip NUL separator */
  196781. if (lang_key >= chunkdata + slength)
  196782. {
  196783. png_warning(png_ptr, "Truncated iTXt chunk");
  196784. png_free(png_ptr, chunkdata);
  196785. return;
  196786. }
  196787. for (text = lang_key; *text; text++)
  196788. /* empty loop */ ;
  196789. text++; /* skip NUL separator */
  196790. if (text >= chunkdata + slength)
  196791. {
  196792. png_warning(png_ptr, "Malformed iTXt chunk");
  196793. png_free(png_ptr, chunkdata);
  196794. return;
  196795. }
  196796. prefix_len = text - chunkdata;
  196797. key=chunkdata;
  196798. if (comp_flag)
  196799. chunkdata = png_decompress_chunk(png_ptr, comp_type, chunkdata,
  196800. (size_t)length, prefix_len, &data_len);
  196801. else
  196802. data_len=png_strlen(chunkdata + prefix_len);
  196803. text_ptr = (png_textp)png_malloc_warn(png_ptr,
  196804. (png_uint_32)png_sizeof(png_text));
  196805. if (text_ptr == NULL)
  196806. {
  196807. png_warning(png_ptr,"Not enough memory to process iTXt chunk.");
  196808. png_free(png_ptr, chunkdata);
  196809. return;
  196810. }
  196811. text_ptr->compression = (int)comp_flag + 1;
  196812. text_ptr->lang_key = chunkdata+(lang_key-key);
  196813. text_ptr->lang = chunkdata+(lang-key);
  196814. text_ptr->itxt_length = data_len;
  196815. text_ptr->text_length = 0;
  196816. text_ptr->key = chunkdata;
  196817. text_ptr->text = chunkdata + prefix_len;
  196818. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, 1);
  196819. png_free(png_ptr, text_ptr);
  196820. png_free(png_ptr, chunkdata);
  196821. if (ret)
  196822. png_error(png_ptr, "Insufficient memory to store iTXt chunk.");
  196823. }
  196824. #endif
  196825. /* This function is called when we haven't found a handler for a
  196826. chunk. If there isn't a problem with the chunk itself (ie bad
  196827. chunk name, CRC, or a critical chunk), the chunk is silently ignored
  196828. -- unless the PNG_FLAG_UNKNOWN_CHUNKS_SUPPORTED flag is on in which
  196829. case it will be saved away to be written out later. */
  196830. void /* PRIVATE */
  196831. png_handle_unknown(png_structp png_ptr, png_infop info_ptr, png_uint_32 length)
  196832. {
  196833. png_uint_32 skip = 0;
  196834. png_debug(1, "in png_handle_unknown\n");
  196835. if (png_ptr->mode & PNG_HAVE_IDAT)
  196836. {
  196837. #ifdef PNG_USE_LOCAL_ARRAYS
  196838. PNG_CONST PNG_IDAT;
  196839. #endif
  196840. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4)) /* not an IDAT */
  196841. png_ptr->mode |= PNG_AFTER_IDAT;
  196842. }
  196843. png_check_chunk_name(png_ptr, png_ptr->chunk_name);
  196844. if (!(png_ptr->chunk_name[0] & 0x20))
  196845. {
  196846. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196847. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196848. PNG_HANDLE_CHUNK_ALWAYS
  196849. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196850. && png_ptr->read_user_chunk_fn == NULL
  196851. #endif
  196852. )
  196853. #endif
  196854. png_chunk_error(png_ptr, "unknown critical chunk");
  196855. }
  196856. #if defined(PNG_READ_UNKNOWN_CHUNKS_SUPPORTED)
  196857. if ((png_ptr->flags & PNG_FLAG_KEEP_UNKNOWN_CHUNKS) ||
  196858. (png_ptr->read_user_chunk_fn != NULL))
  196859. {
  196860. #ifdef PNG_MAX_MALLOC_64K
  196861. if (length > (png_uint_32)65535L)
  196862. {
  196863. png_warning(png_ptr, "unknown chunk too large to fit in memory");
  196864. skip = length - (png_uint_32)65535L;
  196865. length = (png_uint_32)65535L;
  196866. }
  196867. #endif
  196868. png_strncpy((png_charp)png_ptr->unknown_chunk.name,
  196869. (png_charp)png_ptr->chunk_name, 5);
  196870. png_ptr->unknown_chunk.data = (png_bytep)png_malloc(png_ptr, length);
  196871. png_ptr->unknown_chunk.size = (png_size_t)length;
  196872. png_crc_read(png_ptr, (png_bytep)png_ptr->unknown_chunk.data, length);
  196873. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196874. if(png_ptr->read_user_chunk_fn != NULL)
  196875. {
  196876. /* callback to user unknown chunk handler */
  196877. int ret;
  196878. ret = (*(png_ptr->read_user_chunk_fn))
  196879. (png_ptr, &png_ptr->unknown_chunk);
  196880. if (ret < 0)
  196881. png_chunk_error(png_ptr, "error in user chunk");
  196882. if (ret == 0)
  196883. {
  196884. if (!(png_ptr->chunk_name[0] & 0x20))
  196885. if(png_handle_as_unknown(png_ptr, png_ptr->chunk_name) !=
  196886. PNG_HANDLE_CHUNK_ALWAYS)
  196887. png_chunk_error(png_ptr, "unknown critical chunk");
  196888. png_set_unknown_chunks(png_ptr, info_ptr,
  196889. &png_ptr->unknown_chunk, 1);
  196890. }
  196891. }
  196892. #else
  196893. png_set_unknown_chunks(png_ptr, info_ptr, &png_ptr->unknown_chunk, 1);
  196894. #endif
  196895. png_free(png_ptr, png_ptr->unknown_chunk.data);
  196896. png_ptr->unknown_chunk.data = NULL;
  196897. }
  196898. else
  196899. #endif
  196900. skip = length;
  196901. png_crc_finish(png_ptr, skip);
  196902. #if !defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  196903. info_ptr = info_ptr; /* quiet compiler warnings about unused info_ptr */
  196904. #endif
  196905. }
  196906. /* This function is called to verify that a chunk name is valid.
  196907. This function can't have the "critical chunk check" incorporated
  196908. into it, since in the future we will need to be able to call user
  196909. functions to handle unknown critical chunks after we check that
  196910. the chunk name itself is valid. */
  196911. #define isnonalpha(c) ((c) < 65 || (c) > 122 || ((c) > 90 && (c) < 97))
  196912. void /* PRIVATE */
  196913. png_check_chunk_name(png_structp png_ptr, png_bytep chunk_name)
  196914. {
  196915. png_debug(1, "in png_check_chunk_name\n");
  196916. if (isnonalpha(chunk_name[0]) || isnonalpha(chunk_name[1]) ||
  196917. isnonalpha(chunk_name[2]) || isnonalpha(chunk_name[3]))
  196918. {
  196919. png_chunk_error(png_ptr, "invalid chunk type");
  196920. }
  196921. }
  196922. /* Combines the row recently read in with the existing pixels in the
  196923. row. This routine takes care of alpha and transparency if requested.
  196924. This routine also handles the two methods of progressive display
  196925. of interlaced images, depending on the mask value.
  196926. The mask value describes which pixels are to be combined with
  196927. the row. The pattern always repeats every 8 pixels, so just 8
  196928. bits are needed. A one indicates the pixel is to be combined,
  196929. a zero indicates the pixel is to be skipped. This is in addition
  196930. to any alpha or transparency value associated with the pixel. If
  196931. you want all pixels to be combined, pass 0xff (255) in mask. */
  196932. void /* PRIVATE */
  196933. png_combine_row(png_structp png_ptr, png_bytep row, int mask)
  196934. {
  196935. png_debug(1,"in png_combine_row\n");
  196936. if (mask == 0xff)
  196937. {
  196938. png_memcpy(row, png_ptr->row_buf + 1,
  196939. PNG_ROWBYTES(png_ptr->row_info.pixel_depth, png_ptr->width));
  196940. }
  196941. else
  196942. {
  196943. switch (png_ptr->row_info.pixel_depth)
  196944. {
  196945. case 1:
  196946. {
  196947. png_bytep sp = png_ptr->row_buf + 1;
  196948. png_bytep dp = row;
  196949. int s_inc, s_start, s_end;
  196950. int m = 0x80;
  196951. int shift;
  196952. png_uint_32 i;
  196953. png_uint_32 row_width = png_ptr->width;
  196954. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  196955. if (png_ptr->transformations & PNG_PACKSWAP)
  196956. {
  196957. s_start = 0;
  196958. s_end = 7;
  196959. s_inc = 1;
  196960. }
  196961. else
  196962. #endif
  196963. {
  196964. s_start = 7;
  196965. s_end = 0;
  196966. s_inc = -1;
  196967. }
  196968. shift = s_start;
  196969. for (i = 0; i < row_width; i++)
  196970. {
  196971. if (m & mask)
  196972. {
  196973. int value;
  196974. value = (*sp >> shift) & 0x01;
  196975. *dp &= (png_byte)((0x7f7f >> (7 - shift)) & 0xff);
  196976. *dp |= (png_byte)(value << shift);
  196977. }
  196978. if (shift == s_end)
  196979. {
  196980. shift = s_start;
  196981. sp++;
  196982. dp++;
  196983. }
  196984. else
  196985. shift += s_inc;
  196986. if (m == 1)
  196987. m = 0x80;
  196988. else
  196989. m >>= 1;
  196990. }
  196991. break;
  196992. }
  196993. case 2:
  196994. {
  196995. png_bytep sp = png_ptr->row_buf + 1;
  196996. png_bytep dp = row;
  196997. int s_start, s_end, s_inc;
  196998. int m = 0x80;
  196999. int shift;
  197000. png_uint_32 i;
  197001. png_uint_32 row_width = png_ptr->width;
  197002. int value;
  197003. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  197004. if (png_ptr->transformations & PNG_PACKSWAP)
  197005. {
  197006. s_start = 0;
  197007. s_end = 6;
  197008. s_inc = 2;
  197009. }
  197010. else
  197011. #endif
  197012. {
  197013. s_start = 6;
  197014. s_end = 0;
  197015. s_inc = -2;
  197016. }
  197017. shift = s_start;
  197018. for (i = 0; i < row_width; i++)
  197019. {
  197020. if (m & mask)
  197021. {
  197022. value = (*sp >> shift) & 0x03;
  197023. *dp &= (png_byte)((0x3f3f >> (6 - shift)) & 0xff);
  197024. *dp |= (png_byte)(value << shift);
  197025. }
  197026. if (shift == s_end)
  197027. {
  197028. shift = s_start;
  197029. sp++;
  197030. dp++;
  197031. }
  197032. else
  197033. shift += s_inc;
  197034. if (m == 1)
  197035. m = 0x80;
  197036. else
  197037. m >>= 1;
  197038. }
  197039. break;
  197040. }
  197041. case 4:
  197042. {
  197043. png_bytep sp = png_ptr->row_buf + 1;
  197044. png_bytep dp = row;
  197045. int s_start, s_end, s_inc;
  197046. int m = 0x80;
  197047. int shift;
  197048. png_uint_32 i;
  197049. png_uint_32 row_width = png_ptr->width;
  197050. int value;
  197051. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  197052. if (png_ptr->transformations & PNG_PACKSWAP)
  197053. {
  197054. s_start = 0;
  197055. s_end = 4;
  197056. s_inc = 4;
  197057. }
  197058. else
  197059. #endif
  197060. {
  197061. s_start = 4;
  197062. s_end = 0;
  197063. s_inc = -4;
  197064. }
  197065. shift = s_start;
  197066. for (i = 0; i < row_width; i++)
  197067. {
  197068. if (m & mask)
  197069. {
  197070. value = (*sp >> shift) & 0xf;
  197071. *dp &= (png_byte)((0xf0f >> (4 - shift)) & 0xff);
  197072. *dp |= (png_byte)(value << shift);
  197073. }
  197074. if (shift == s_end)
  197075. {
  197076. shift = s_start;
  197077. sp++;
  197078. dp++;
  197079. }
  197080. else
  197081. shift += s_inc;
  197082. if (m == 1)
  197083. m = 0x80;
  197084. else
  197085. m >>= 1;
  197086. }
  197087. break;
  197088. }
  197089. default:
  197090. {
  197091. png_bytep sp = png_ptr->row_buf + 1;
  197092. png_bytep dp = row;
  197093. png_size_t pixel_bytes = (png_ptr->row_info.pixel_depth >> 3);
  197094. png_uint_32 i;
  197095. png_uint_32 row_width = png_ptr->width;
  197096. png_byte m = 0x80;
  197097. for (i = 0; i < row_width; i++)
  197098. {
  197099. if (m & mask)
  197100. {
  197101. png_memcpy(dp, sp, pixel_bytes);
  197102. }
  197103. sp += pixel_bytes;
  197104. dp += pixel_bytes;
  197105. if (m == 1)
  197106. m = 0x80;
  197107. else
  197108. m >>= 1;
  197109. }
  197110. break;
  197111. }
  197112. }
  197113. }
  197114. }
  197115. #ifdef PNG_READ_INTERLACING_SUPPORTED
  197116. /* OLD pre-1.0.9 interface:
  197117. void png_do_read_interlace(png_row_infop row_info, png_bytep row, int pass,
  197118. png_uint_32 transformations)
  197119. */
  197120. void /* PRIVATE */
  197121. png_do_read_interlace(png_structp png_ptr)
  197122. {
  197123. png_row_infop row_info = &(png_ptr->row_info);
  197124. png_bytep row = png_ptr->row_buf + 1;
  197125. int pass = png_ptr->pass;
  197126. png_uint_32 transformations = png_ptr->transformations;
  197127. #ifdef PNG_USE_LOCAL_ARRAYS
  197128. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197129. /* offset to next interlace block */
  197130. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197131. #endif
  197132. png_debug(1,"in png_do_read_interlace\n");
  197133. if (row != NULL && row_info != NULL)
  197134. {
  197135. png_uint_32 final_width;
  197136. final_width = row_info->width * png_pass_inc[pass];
  197137. switch (row_info->pixel_depth)
  197138. {
  197139. case 1:
  197140. {
  197141. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 3);
  197142. png_bytep dp = row + (png_size_t)((final_width - 1) >> 3);
  197143. int sshift, dshift;
  197144. int s_start, s_end, s_inc;
  197145. int jstop = png_pass_inc[pass];
  197146. png_byte v;
  197147. png_uint_32 i;
  197148. int j;
  197149. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  197150. if (transformations & PNG_PACKSWAP)
  197151. {
  197152. sshift = (int)((row_info->width + 7) & 0x07);
  197153. dshift = (int)((final_width + 7) & 0x07);
  197154. s_start = 7;
  197155. s_end = 0;
  197156. s_inc = -1;
  197157. }
  197158. else
  197159. #endif
  197160. {
  197161. sshift = 7 - (int)((row_info->width + 7) & 0x07);
  197162. dshift = 7 - (int)((final_width + 7) & 0x07);
  197163. s_start = 0;
  197164. s_end = 7;
  197165. s_inc = 1;
  197166. }
  197167. for (i = 0; i < row_info->width; i++)
  197168. {
  197169. v = (png_byte)((*sp >> sshift) & 0x01);
  197170. for (j = 0; j < jstop; j++)
  197171. {
  197172. *dp &= (png_byte)((0x7f7f >> (7 - dshift)) & 0xff);
  197173. *dp |= (png_byte)(v << dshift);
  197174. if (dshift == s_end)
  197175. {
  197176. dshift = s_start;
  197177. dp--;
  197178. }
  197179. else
  197180. dshift += s_inc;
  197181. }
  197182. if (sshift == s_end)
  197183. {
  197184. sshift = s_start;
  197185. sp--;
  197186. }
  197187. else
  197188. sshift += s_inc;
  197189. }
  197190. break;
  197191. }
  197192. case 2:
  197193. {
  197194. png_bytep sp = row + (png_uint_32)((row_info->width - 1) >> 2);
  197195. png_bytep dp = row + (png_uint_32)((final_width - 1) >> 2);
  197196. int sshift, dshift;
  197197. int s_start, s_end, s_inc;
  197198. int jstop = png_pass_inc[pass];
  197199. png_uint_32 i;
  197200. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  197201. if (transformations & PNG_PACKSWAP)
  197202. {
  197203. sshift = (int)(((row_info->width + 3) & 0x03) << 1);
  197204. dshift = (int)(((final_width + 3) & 0x03) << 1);
  197205. s_start = 6;
  197206. s_end = 0;
  197207. s_inc = -2;
  197208. }
  197209. else
  197210. #endif
  197211. {
  197212. sshift = (int)((3 - ((row_info->width + 3) & 0x03)) << 1);
  197213. dshift = (int)((3 - ((final_width + 3) & 0x03)) << 1);
  197214. s_start = 0;
  197215. s_end = 6;
  197216. s_inc = 2;
  197217. }
  197218. for (i = 0; i < row_info->width; i++)
  197219. {
  197220. png_byte v;
  197221. int j;
  197222. v = (png_byte)((*sp >> sshift) & 0x03);
  197223. for (j = 0; j < jstop; j++)
  197224. {
  197225. *dp &= (png_byte)((0x3f3f >> (6 - dshift)) & 0xff);
  197226. *dp |= (png_byte)(v << dshift);
  197227. if (dshift == s_end)
  197228. {
  197229. dshift = s_start;
  197230. dp--;
  197231. }
  197232. else
  197233. dshift += s_inc;
  197234. }
  197235. if (sshift == s_end)
  197236. {
  197237. sshift = s_start;
  197238. sp--;
  197239. }
  197240. else
  197241. sshift += s_inc;
  197242. }
  197243. break;
  197244. }
  197245. case 4:
  197246. {
  197247. png_bytep sp = row + (png_size_t)((row_info->width - 1) >> 1);
  197248. png_bytep dp = row + (png_size_t)((final_width - 1) >> 1);
  197249. int sshift, dshift;
  197250. int s_start, s_end, s_inc;
  197251. png_uint_32 i;
  197252. int jstop = png_pass_inc[pass];
  197253. #if defined(PNG_READ_PACKSWAP_SUPPORTED)
  197254. if (transformations & PNG_PACKSWAP)
  197255. {
  197256. sshift = (int)(((row_info->width + 1) & 0x01) << 2);
  197257. dshift = (int)(((final_width + 1) & 0x01) << 2);
  197258. s_start = 4;
  197259. s_end = 0;
  197260. s_inc = -4;
  197261. }
  197262. else
  197263. #endif
  197264. {
  197265. sshift = (int)((1 - ((row_info->width + 1) & 0x01)) << 2);
  197266. dshift = (int)((1 - ((final_width + 1) & 0x01)) << 2);
  197267. s_start = 0;
  197268. s_end = 4;
  197269. s_inc = 4;
  197270. }
  197271. for (i = 0; i < row_info->width; i++)
  197272. {
  197273. png_byte v = (png_byte)((*sp >> sshift) & 0xf);
  197274. int j;
  197275. for (j = 0; j < jstop; j++)
  197276. {
  197277. *dp &= (png_byte)((0xf0f >> (4 - dshift)) & 0xff);
  197278. *dp |= (png_byte)(v << dshift);
  197279. if (dshift == s_end)
  197280. {
  197281. dshift = s_start;
  197282. dp--;
  197283. }
  197284. else
  197285. dshift += s_inc;
  197286. }
  197287. if (sshift == s_end)
  197288. {
  197289. sshift = s_start;
  197290. sp--;
  197291. }
  197292. else
  197293. sshift += s_inc;
  197294. }
  197295. break;
  197296. }
  197297. default:
  197298. {
  197299. png_size_t pixel_bytes = (row_info->pixel_depth >> 3);
  197300. png_bytep sp = row + (png_size_t)(row_info->width - 1) * pixel_bytes;
  197301. png_bytep dp = row + (png_size_t)(final_width - 1) * pixel_bytes;
  197302. int jstop = png_pass_inc[pass];
  197303. png_uint_32 i;
  197304. for (i = 0; i < row_info->width; i++)
  197305. {
  197306. png_byte v[8];
  197307. int j;
  197308. png_memcpy(v, sp, pixel_bytes);
  197309. for (j = 0; j < jstop; j++)
  197310. {
  197311. png_memcpy(dp, v, pixel_bytes);
  197312. dp -= pixel_bytes;
  197313. }
  197314. sp -= pixel_bytes;
  197315. }
  197316. break;
  197317. }
  197318. }
  197319. row_info->width = final_width;
  197320. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,final_width);
  197321. }
  197322. #if !defined(PNG_READ_PACKSWAP_SUPPORTED)
  197323. transformations = transformations; /* silence compiler warning */
  197324. #endif
  197325. }
  197326. #endif /* PNG_READ_INTERLACING_SUPPORTED */
  197327. void /* PRIVATE */
  197328. png_read_filter_row(png_structp png_ptr, png_row_infop row_info, png_bytep row,
  197329. png_bytep prev_row, int filter)
  197330. {
  197331. png_debug(1, "in png_read_filter_row\n");
  197332. png_debug2(2,"row = %lu, filter = %d\n", png_ptr->row_number, filter);
  197333. switch (filter)
  197334. {
  197335. case PNG_FILTER_VALUE_NONE:
  197336. break;
  197337. case PNG_FILTER_VALUE_SUB:
  197338. {
  197339. png_uint_32 i;
  197340. png_uint_32 istop = row_info->rowbytes;
  197341. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  197342. png_bytep rp = row + bpp;
  197343. png_bytep lp = row;
  197344. for (i = bpp; i < istop; i++)
  197345. {
  197346. *rp = (png_byte)(((int)(*rp) + (int)(*lp++)) & 0xff);
  197347. rp++;
  197348. }
  197349. break;
  197350. }
  197351. case PNG_FILTER_VALUE_UP:
  197352. {
  197353. png_uint_32 i;
  197354. png_uint_32 istop = row_info->rowbytes;
  197355. png_bytep rp = row;
  197356. png_bytep pp = prev_row;
  197357. for (i = 0; i < istop; i++)
  197358. {
  197359. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  197360. rp++;
  197361. }
  197362. break;
  197363. }
  197364. case PNG_FILTER_VALUE_AVG:
  197365. {
  197366. png_uint_32 i;
  197367. png_bytep rp = row;
  197368. png_bytep pp = prev_row;
  197369. png_bytep lp = row;
  197370. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  197371. png_uint_32 istop = row_info->rowbytes - bpp;
  197372. for (i = 0; i < bpp; i++)
  197373. {
  197374. *rp = (png_byte)(((int)(*rp) +
  197375. ((int)(*pp++) / 2 )) & 0xff);
  197376. rp++;
  197377. }
  197378. for (i = 0; i < istop; i++)
  197379. {
  197380. *rp = (png_byte)(((int)(*rp) +
  197381. (int)(*pp++ + *lp++) / 2 ) & 0xff);
  197382. rp++;
  197383. }
  197384. break;
  197385. }
  197386. case PNG_FILTER_VALUE_PAETH:
  197387. {
  197388. png_uint_32 i;
  197389. png_bytep rp = row;
  197390. png_bytep pp = prev_row;
  197391. png_bytep lp = row;
  197392. png_bytep cp = prev_row;
  197393. png_uint_32 bpp = (row_info->pixel_depth + 7) >> 3;
  197394. png_uint_32 istop=row_info->rowbytes - bpp;
  197395. for (i = 0; i < bpp; i++)
  197396. {
  197397. *rp = (png_byte)(((int)(*rp) + (int)(*pp++)) & 0xff);
  197398. rp++;
  197399. }
  197400. for (i = 0; i < istop; i++) /* use leftover rp,pp */
  197401. {
  197402. int a, b, c, pa, pb, pc, p;
  197403. a = *lp++;
  197404. b = *pp++;
  197405. c = *cp++;
  197406. p = b - c;
  197407. pc = a - c;
  197408. #ifdef PNG_USE_ABS
  197409. pa = abs(p);
  197410. pb = abs(pc);
  197411. pc = abs(p + pc);
  197412. #else
  197413. pa = p < 0 ? -p : p;
  197414. pb = pc < 0 ? -pc : pc;
  197415. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  197416. #endif
  197417. /*
  197418. if (pa <= pb && pa <= pc)
  197419. p = a;
  197420. else if (pb <= pc)
  197421. p = b;
  197422. else
  197423. p = c;
  197424. */
  197425. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  197426. *rp = (png_byte)(((int)(*rp) + p) & 0xff);
  197427. rp++;
  197428. }
  197429. break;
  197430. }
  197431. default:
  197432. png_warning(png_ptr, "Ignoring bad adaptive filter type");
  197433. *row=0;
  197434. break;
  197435. }
  197436. }
  197437. void /* PRIVATE */
  197438. png_read_finish_row(png_structp png_ptr)
  197439. {
  197440. #ifdef PNG_USE_LOCAL_ARRAYS
  197441. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197442. /* start of interlace block */
  197443. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197444. /* offset to next interlace block */
  197445. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197446. /* start of interlace block in the y direction */
  197447. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  197448. /* offset to next interlace block in the y direction */
  197449. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  197450. #endif
  197451. png_debug(1, "in png_read_finish_row\n");
  197452. png_ptr->row_number++;
  197453. if (png_ptr->row_number < png_ptr->num_rows)
  197454. return;
  197455. if (png_ptr->interlaced)
  197456. {
  197457. png_ptr->row_number = 0;
  197458. png_memset_check(png_ptr, png_ptr->prev_row, 0,
  197459. png_ptr->rowbytes + 1);
  197460. do
  197461. {
  197462. png_ptr->pass++;
  197463. if (png_ptr->pass >= 7)
  197464. break;
  197465. png_ptr->iwidth = (png_ptr->width +
  197466. png_pass_inc[png_ptr->pass] - 1 -
  197467. png_pass_start[png_ptr->pass]) /
  197468. png_pass_inc[png_ptr->pass];
  197469. png_ptr->irowbytes = PNG_ROWBYTES(png_ptr->pixel_depth,
  197470. png_ptr->iwidth) + 1;
  197471. if (!(png_ptr->transformations & PNG_INTERLACE))
  197472. {
  197473. png_ptr->num_rows = (png_ptr->height +
  197474. png_pass_yinc[png_ptr->pass] - 1 -
  197475. png_pass_ystart[png_ptr->pass]) /
  197476. png_pass_yinc[png_ptr->pass];
  197477. if (!(png_ptr->num_rows))
  197478. continue;
  197479. }
  197480. else /* if (png_ptr->transformations & PNG_INTERLACE) */
  197481. break;
  197482. } while (png_ptr->iwidth == 0);
  197483. if (png_ptr->pass < 7)
  197484. return;
  197485. }
  197486. if (!(png_ptr->flags & PNG_FLAG_ZLIB_FINISHED))
  197487. {
  197488. #ifdef PNG_USE_LOCAL_ARRAYS
  197489. PNG_CONST PNG_IDAT;
  197490. #endif
  197491. char extra;
  197492. int ret;
  197493. png_ptr->zstream.next_out = (Bytef *)&extra;
  197494. png_ptr->zstream.avail_out = (uInt)1;
  197495. for(;;)
  197496. {
  197497. if (!(png_ptr->zstream.avail_in))
  197498. {
  197499. while (!png_ptr->idat_size)
  197500. {
  197501. png_byte chunk_length[4];
  197502. png_crc_finish(png_ptr, 0);
  197503. png_read_data(png_ptr, chunk_length, 4);
  197504. png_ptr->idat_size = png_get_uint_31(png_ptr, chunk_length);
  197505. png_reset_crc(png_ptr);
  197506. png_crc_read(png_ptr, png_ptr->chunk_name, 4);
  197507. if (png_memcmp(png_ptr->chunk_name, png_IDAT, 4))
  197508. png_error(png_ptr, "Not enough image data");
  197509. }
  197510. png_ptr->zstream.avail_in = (uInt)png_ptr->zbuf_size;
  197511. png_ptr->zstream.next_in = png_ptr->zbuf;
  197512. if (png_ptr->zbuf_size > png_ptr->idat_size)
  197513. png_ptr->zstream.avail_in = (uInt)png_ptr->idat_size;
  197514. png_crc_read(png_ptr, png_ptr->zbuf, png_ptr->zstream.avail_in);
  197515. png_ptr->idat_size -= png_ptr->zstream.avail_in;
  197516. }
  197517. ret = inflate(&png_ptr->zstream, Z_PARTIAL_FLUSH);
  197518. if (ret == Z_STREAM_END)
  197519. {
  197520. if (!(png_ptr->zstream.avail_out) || png_ptr->zstream.avail_in ||
  197521. png_ptr->idat_size)
  197522. png_warning(png_ptr, "Extra compressed data");
  197523. png_ptr->mode |= PNG_AFTER_IDAT;
  197524. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  197525. break;
  197526. }
  197527. if (ret != Z_OK)
  197528. png_error(png_ptr, png_ptr->zstream.msg ? png_ptr->zstream.msg :
  197529. "Decompression Error");
  197530. if (!(png_ptr->zstream.avail_out))
  197531. {
  197532. png_warning(png_ptr, "Extra compressed data.");
  197533. png_ptr->mode |= PNG_AFTER_IDAT;
  197534. png_ptr->flags |= PNG_FLAG_ZLIB_FINISHED;
  197535. break;
  197536. }
  197537. }
  197538. png_ptr->zstream.avail_out = 0;
  197539. }
  197540. if (png_ptr->idat_size || png_ptr->zstream.avail_in)
  197541. png_warning(png_ptr, "Extra compression data");
  197542. inflateReset(&png_ptr->zstream);
  197543. png_ptr->mode |= PNG_AFTER_IDAT;
  197544. }
  197545. void /* PRIVATE */
  197546. png_read_start_row(png_structp png_ptr)
  197547. {
  197548. #ifdef PNG_USE_LOCAL_ARRAYS
  197549. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  197550. /* start of interlace block */
  197551. PNG_CONST int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  197552. /* offset to next interlace block */
  197553. PNG_CONST int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  197554. /* start of interlace block in the y direction */
  197555. PNG_CONST int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  197556. /* offset to next interlace block in the y direction */
  197557. PNG_CONST int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  197558. #endif
  197559. int max_pixel_depth;
  197560. png_uint_32 row_bytes;
  197561. png_debug(1, "in png_read_start_row\n");
  197562. png_ptr->zstream.avail_in = 0;
  197563. png_init_read_transformations(png_ptr);
  197564. if (png_ptr->interlaced)
  197565. {
  197566. if (!(png_ptr->transformations & PNG_INTERLACE))
  197567. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  197568. png_pass_ystart[0]) / png_pass_yinc[0];
  197569. else
  197570. png_ptr->num_rows = png_ptr->height;
  197571. png_ptr->iwidth = (png_ptr->width +
  197572. png_pass_inc[png_ptr->pass] - 1 -
  197573. png_pass_start[png_ptr->pass]) /
  197574. png_pass_inc[png_ptr->pass];
  197575. row_bytes = PNG_ROWBYTES(png_ptr->pixel_depth,png_ptr->iwidth) + 1;
  197576. png_ptr->irowbytes = (png_size_t)row_bytes;
  197577. if((png_uint_32)png_ptr->irowbytes != row_bytes)
  197578. png_error(png_ptr, "Rowbytes overflow in png_read_start_row");
  197579. }
  197580. else
  197581. {
  197582. png_ptr->num_rows = png_ptr->height;
  197583. png_ptr->iwidth = png_ptr->width;
  197584. png_ptr->irowbytes = png_ptr->rowbytes + 1;
  197585. }
  197586. max_pixel_depth = png_ptr->pixel_depth;
  197587. #if defined(PNG_READ_PACK_SUPPORTED)
  197588. if ((png_ptr->transformations & PNG_PACK) && png_ptr->bit_depth < 8)
  197589. max_pixel_depth = 8;
  197590. #endif
  197591. #if defined(PNG_READ_EXPAND_SUPPORTED)
  197592. if (png_ptr->transformations & PNG_EXPAND)
  197593. {
  197594. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197595. {
  197596. if (png_ptr->num_trans)
  197597. max_pixel_depth = 32;
  197598. else
  197599. max_pixel_depth = 24;
  197600. }
  197601. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  197602. {
  197603. if (max_pixel_depth < 8)
  197604. max_pixel_depth = 8;
  197605. if (png_ptr->num_trans)
  197606. max_pixel_depth *= 2;
  197607. }
  197608. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197609. {
  197610. if (png_ptr->num_trans)
  197611. {
  197612. max_pixel_depth *= 4;
  197613. max_pixel_depth /= 3;
  197614. }
  197615. }
  197616. }
  197617. #endif
  197618. #if defined(PNG_READ_FILLER_SUPPORTED)
  197619. if (png_ptr->transformations & (PNG_FILLER))
  197620. {
  197621. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  197622. max_pixel_depth = 32;
  197623. else if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY)
  197624. {
  197625. if (max_pixel_depth <= 8)
  197626. max_pixel_depth = 16;
  197627. else
  197628. max_pixel_depth = 32;
  197629. }
  197630. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  197631. {
  197632. if (max_pixel_depth <= 32)
  197633. max_pixel_depth = 32;
  197634. else
  197635. max_pixel_depth = 64;
  197636. }
  197637. }
  197638. #endif
  197639. #if defined(PNG_READ_GRAY_TO_RGB_SUPPORTED)
  197640. if (png_ptr->transformations & PNG_GRAY_TO_RGB)
  197641. {
  197642. if (
  197643. #if defined(PNG_READ_EXPAND_SUPPORTED)
  197644. (png_ptr->num_trans && (png_ptr->transformations & PNG_EXPAND)) ||
  197645. #endif
  197646. #if defined(PNG_READ_FILLER_SUPPORTED)
  197647. (png_ptr->transformations & (PNG_FILLER)) ||
  197648. #endif
  197649. png_ptr->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  197650. {
  197651. if (max_pixel_depth <= 16)
  197652. max_pixel_depth = 32;
  197653. else
  197654. max_pixel_depth = 64;
  197655. }
  197656. else
  197657. {
  197658. if (max_pixel_depth <= 8)
  197659. {
  197660. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197661. max_pixel_depth = 32;
  197662. else
  197663. max_pixel_depth = 24;
  197664. }
  197665. else if (png_ptr->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  197666. max_pixel_depth = 64;
  197667. else
  197668. max_pixel_depth = 48;
  197669. }
  197670. }
  197671. #endif
  197672. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) && \
  197673. defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  197674. if(png_ptr->transformations & PNG_USER_TRANSFORM)
  197675. {
  197676. int user_pixel_depth=png_ptr->user_transform_depth*
  197677. png_ptr->user_transform_channels;
  197678. if(user_pixel_depth > max_pixel_depth)
  197679. max_pixel_depth=user_pixel_depth;
  197680. }
  197681. #endif
  197682. /* align the width on the next larger 8 pixels. Mainly used
  197683. for interlacing */
  197684. row_bytes = ((png_ptr->width + 7) & ~((png_uint_32)7));
  197685. /* calculate the maximum bytes needed, adding a byte and a pixel
  197686. for safety's sake */
  197687. row_bytes = PNG_ROWBYTES(max_pixel_depth,row_bytes) +
  197688. 1 + ((max_pixel_depth + 7) >> 3);
  197689. #ifdef PNG_MAX_MALLOC_64K
  197690. if (row_bytes > (png_uint_32)65536L)
  197691. png_error(png_ptr, "This image requires a row greater than 64KB");
  197692. #endif
  197693. png_ptr->big_row_buf = (png_bytep)png_malloc(png_ptr, row_bytes+64);
  197694. png_ptr->row_buf = png_ptr->big_row_buf+32;
  197695. #ifdef PNG_MAX_MALLOC_64K
  197696. if ((png_uint_32)png_ptr->rowbytes + 1 > (png_uint_32)65536L)
  197697. png_error(png_ptr, "This image requires a row greater than 64KB");
  197698. #endif
  197699. if ((png_uint_32)png_ptr->rowbytes > (png_uint_32)(PNG_SIZE_MAX - 1))
  197700. png_error(png_ptr, "Row has too many bytes to allocate in memory.");
  197701. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)(
  197702. png_ptr->rowbytes + 1));
  197703. png_memset_check(png_ptr, png_ptr->prev_row, 0, png_ptr->rowbytes + 1);
  197704. png_debug1(3, "width = %lu,\n", png_ptr->width);
  197705. png_debug1(3, "height = %lu,\n", png_ptr->height);
  197706. png_debug1(3, "iwidth = %lu,\n", png_ptr->iwidth);
  197707. png_debug1(3, "num_rows = %lu\n", png_ptr->num_rows);
  197708. png_debug1(3, "rowbytes = %lu,\n", png_ptr->rowbytes);
  197709. png_debug1(3, "irowbytes = %lu,\n", png_ptr->irowbytes);
  197710. png_ptr->flags |= PNG_FLAG_ROW_INIT;
  197711. }
  197712. #endif /* PNG_READ_SUPPORTED */
  197713. /********* End of inlined file: pngrutil.c *********/
  197714. /********* Start of inlined file: pngset.c *********/
  197715. /* pngset.c - storage of image information into info struct
  197716. *
  197717. * Last changed in libpng 1.2.21 [October 4, 2007]
  197718. * For conditions of distribution and use, see copyright notice in png.h
  197719. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  197720. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  197721. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  197722. *
  197723. * The functions here are used during reads to store data from the file
  197724. * into the info struct, and during writes to store application data
  197725. * into the info struct for writing into the file. This abstracts the
  197726. * info struct and allows us to change the structure in the future.
  197727. */
  197728. #define PNG_INTERNAL
  197729. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  197730. #if defined(PNG_bKGD_SUPPORTED)
  197731. void PNGAPI
  197732. png_set_bKGD(png_structp png_ptr, png_infop info_ptr, png_color_16p background)
  197733. {
  197734. png_debug1(1, "in %s storage function\n", "bKGD");
  197735. if (png_ptr == NULL || info_ptr == NULL)
  197736. return;
  197737. png_memcpy(&(info_ptr->background), background, png_sizeof(png_color_16));
  197738. info_ptr->valid |= PNG_INFO_bKGD;
  197739. }
  197740. #endif
  197741. #if defined(PNG_cHRM_SUPPORTED)
  197742. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197743. void PNGAPI
  197744. png_set_cHRM(png_structp png_ptr, png_infop info_ptr,
  197745. double white_x, double white_y, double red_x, double red_y,
  197746. double green_x, double green_y, double blue_x, double blue_y)
  197747. {
  197748. png_debug1(1, "in %s storage function\n", "cHRM");
  197749. if (png_ptr == NULL || info_ptr == NULL)
  197750. return;
  197751. if (white_x < 0.0 || white_y < 0.0 ||
  197752. red_x < 0.0 || red_y < 0.0 ||
  197753. green_x < 0.0 || green_y < 0.0 ||
  197754. blue_x < 0.0 || blue_y < 0.0)
  197755. {
  197756. png_warning(png_ptr,
  197757. "Ignoring attempt to set negative chromaticity value");
  197758. return;
  197759. }
  197760. if (white_x > 21474.83 || white_y > 21474.83 ||
  197761. red_x > 21474.83 || red_y > 21474.83 ||
  197762. green_x > 21474.83 || green_y > 21474.83 ||
  197763. blue_x > 21474.83 || blue_y > 21474.83)
  197764. {
  197765. png_warning(png_ptr,
  197766. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197767. return;
  197768. }
  197769. info_ptr->x_white = (float)white_x;
  197770. info_ptr->y_white = (float)white_y;
  197771. info_ptr->x_red = (float)red_x;
  197772. info_ptr->y_red = (float)red_y;
  197773. info_ptr->x_green = (float)green_x;
  197774. info_ptr->y_green = (float)green_y;
  197775. info_ptr->x_blue = (float)blue_x;
  197776. info_ptr->y_blue = (float)blue_y;
  197777. #ifdef PNG_FIXED_POINT_SUPPORTED
  197778. info_ptr->int_x_white = (png_fixed_point)(white_x*100000.+0.5);
  197779. info_ptr->int_y_white = (png_fixed_point)(white_y*100000.+0.5);
  197780. info_ptr->int_x_red = (png_fixed_point)( red_x*100000.+0.5);
  197781. info_ptr->int_y_red = (png_fixed_point)( red_y*100000.+0.5);
  197782. info_ptr->int_x_green = (png_fixed_point)(green_x*100000.+0.5);
  197783. info_ptr->int_y_green = (png_fixed_point)(green_y*100000.+0.5);
  197784. info_ptr->int_x_blue = (png_fixed_point)( blue_x*100000.+0.5);
  197785. info_ptr->int_y_blue = (png_fixed_point)( blue_y*100000.+0.5);
  197786. #endif
  197787. info_ptr->valid |= PNG_INFO_cHRM;
  197788. }
  197789. #endif
  197790. #ifdef PNG_FIXED_POINT_SUPPORTED
  197791. void PNGAPI
  197792. png_set_cHRM_fixed(png_structp png_ptr, png_infop info_ptr,
  197793. png_fixed_point white_x, png_fixed_point white_y, png_fixed_point red_x,
  197794. png_fixed_point red_y, png_fixed_point green_x, png_fixed_point green_y,
  197795. png_fixed_point blue_x, png_fixed_point blue_y)
  197796. {
  197797. png_debug1(1, "in %s storage function\n", "cHRM");
  197798. if (png_ptr == NULL || info_ptr == NULL)
  197799. return;
  197800. if (white_x < 0 || white_y < 0 ||
  197801. red_x < 0 || red_y < 0 ||
  197802. green_x < 0 || green_y < 0 ||
  197803. blue_x < 0 || blue_y < 0)
  197804. {
  197805. png_warning(png_ptr,
  197806. "Ignoring attempt to set negative chromaticity value");
  197807. return;
  197808. }
  197809. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197810. if (white_x > (double) PNG_UINT_31_MAX ||
  197811. white_y > (double) PNG_UINT_31_MAX ||
  197812. red_x > (double) PNG_UINT_31_MAX ||
  197813. red_y > (double) PNG_UINT_31_MAX ||
  197814. green_x > (double) PNG_UINT_31_MAX ||
  197815. green_y > (double) PNG_UINT_31_MAX ||
  197816. blue_x > (double) PNG_UINT_31_MAX ||
  197817. blue_y > (double) PNG_UINT_31_MAX)
  197818. #else
  197819. if (white_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197820. white_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197821. red_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197822. red_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197823. green_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197824. green_y > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197825. blue_x > (png_fixed_point) PNG_UINT_31_MAX/100000L ||
  197826. blue_y > (png_fixed_point) PNG_UINT_31_MAX/100000L)
  197827. #endif
  197828. {
  197829. png_warning(png_ptr,
  197830. "Ignoring attempt to set chromaticity value exceeding 21474.83");
  197831. return;
  197832. }
  197833. info_ptr->int_x_white = white_x;
  197834. info_ptr->int_y_white = white_y;
  197835. info_ptr->int_x_red = red_x;
  197836. info_ptr->int_y_red = red_y;
  197837. info_ptr->int_x_green = green_x;
  197838. info_ptr->int_y_green = green_y;
  197839. info_ptr->int_x_blue = blue_x;
  197840. info_ptr->int_y_blue = blue_y;
  197841. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197842. info_ptr->x_white = (float)(white_x/100000.);
  197843. info_ptr->y_white = (float)(white_y/100000.);
  197844. info_ptr->x_red = (float)( red_x/100000.);
  197845. info_ptr->y_red = (float)( red_y/100000.);
  197846. info_ptr->x_green = (float)(green_x/100000.);
  197847. info_ptr->y_green = (float)(green_y/100000.);
  197848. info_ptr->x_blue = (float)( blue_x/100000.);
  197849. info_ptr->y_blue = (float)( blue_y/100000.);
  197850. #endif
  197851. info_ptr->valid |= PNG_INFO_cHRM;
  197852. }
  197853. #endif
  197854. #endif
  197855. #if defined(PNG_gAMA_SUPPORTED)
  197856. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197857. void PNGAPI
  197858. png_set_gAMA(png_structp png_ptr, png_infop info_ptr, double file_gamma)
  197859. {
  197860. double gamma;
  197861. png_debug1(1, "in %s storage function\n", "gAMA");
  197862. if (png_ptr == NULL || info_ptr == NULL)
  197863. return;
  197864. /* Check for overflow */
  197865. if (file_gamma > 21474.83)
  197866. {
  197867. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197868. gamma=21474.83;
  197869. }
  197870. else
  197871. gamma=file_gamma;
  197872. info_ptr->gamma = (float)gamma;
  197873. #ifdef PNG_FIXED_POINT_SUPPORTED
  197874. info_ptr->int_gamma = (int)(gamma*100000.+.5);
  197875. #endif
  197876. info_ptr->valid |= PNG_INFO_gAMA;
  197877. if(gamma == 0.0)
  197878. png_warning(png_ptr, "Setting gamma=0");
  197879. }
  197880. #endif
  197881. void PNGAPI
  197882. png_set_gAMA_fixed(png_structp png_ptr, png_infop info_ptr, png_fixed_point
  197883. int_gamma)
  197884. {
  197885. png_fixed_point gamma;
  197886. png_debug1(1, "in %s storage function\n", "gAMA");
  197887. if (png_ptr == NULL || info_ptr == NULL)
  197888. return;
  197889. if (int_gamma > (png_fixed_point) PNG_UINT_31_MAX)
  197890. {
  197891. png_warning(png_ptr, "Limiting gamma to 21474.83");
  197892. gamma=PNG_UINT_31_MAX;
  197893. }
  197894. else
  197895. {
  197896. if (int_gamma < 0)
  197897. {
  197898. png_warning(png_ptr, "Setting negative gamma to zero");
  197899. gamma=0;
  197900. }
  197901. else
  197902. gamma=int_gamma;
  197903. }
  197904. #ifdef PNG_FLOATING_POINT_SUPPORTED
  197905. info_ptr->gamma = (float)(gamma/100000.);
  197906. #endif
  197907. #ifdef PNG_FIXED_POINT_SUPPORTED
  197908. info_ptr->int_gamma = gamma;
  197909. #endif
  197910. info_ptr->valid |= PNG_INFO_gAMA;
  197911. if(gamma == 0)
  197912. png_warning(png_ptr, "Setting gamma=0");
  197913. }
  197914. #endif
  197915. #if defined(PNG_hIST_SUPPORTED)
  197916. void PNGAPI
  197917. png_set_hIST(png_structp png_ptr, png_infop info_ptr, png_uint_16p hist)
  197918. {
  197919. int i;
  197920. png_debug1(1, "in %s storage function\n", "hIST");
  197921. if (png_ptr == NULL || info_ptr == NULL)
  197922. return;
  197923. if (info_ptr->num_palette == 0 || info_ptr->num_palette
  197924. > PNG_MAX_PALETTE_LENGTH)
  197925. {
  197926. png_warning(png_ptr,
  197927. "Invalid palette size, hIST allocation skipped.");
  197928. return;
  197929. }
  197930. #ifdef PNG_FREE_ME_SUPPORTED
  197931. png_free_data(png_ptr, info_ptr, PNG_FREE_HIST, 0);
  197932. #endif
  197933. /* Changed from info->num_palette to PNG_MAX_PALETTE_LENGTH in version
  197934. 1.2.1 */
  197935. png_ptr->hist = (png_uint_16p)png_malloc_warn(png_ptr,
  197936. (png_uint_32)(PNG_MAX_PALETTE_LENGTH * png_sizeof (png_uint_16)));
  197937. if (png_ptr->hist == NULL)
  197938. {
  197939. png_warning(png_ptr, "Insufficient memory for hIST chunk data.");
  197940. return;
  197941. }
  197942. for (i = 0; i < info_ptr->num_palette; i++)
  197943. png_ptr->hist[i] = hist[i];
  197944. info_ptr->hist = png_ptr->hist;
  197945. info_ptr->valid |= PNG_INFO_hIST;
  197946. #ifdef PNG_FREE_ME_SUPPORTED
  197947. info_ptr->free_me |= PNG_FREE_HIST;
  197948. #else
  197949. png_ptr->flags |= PNG_FLAG_FREE_HIST;
  197950. #endif
  197951. }
  197952. #endif
  197953. void PNGAPI
  197954. png_set_IHDR(png_structp png_ptr, png_infop info_ptr,
  197955. png_uint_32 width, png_uint_32 height, int bit_depth,
  197956. int color_type, int interlace_type, int compression_type,
  197957. int filter_type)
  197958. {
  197959. png_debug1(1, "in %s storage function\n", "IHDR");
  197960. if (png_ptr == NULL || info_ptr == NULL)
  197961. return;
  197962. /* check for width and height valid values */
  197963. if (width == 0 || height == 0)
  197964. png_error(png_ptr, "Image width or height is zero in IHDR");
  197965. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  197966. if (width > png_ptr->user_width_max || height > png_ptr->user_height_max)
  197967. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197968. #else
  197969. if (width > PNG_USER_WIDTH_MAX || height > PNG_USER_HEIGHT_MAX)
  197970. png_error(png_ptr, "image size exceeds user limits in IHDR");
  197971. #endif
  197972. if (width > PNG_UINT_31_MAX || height > PNG_UINT_31_MAX)
  197973. png_error(png_ptr, "Invalid image size in IHDR");
  197974. if ( width > (PNG_UINT_32_MAX
  197975. >> 3) /* 8-byte RGBA pixels */
  197976. - 64 /* bigrowbuf hack */
  197977. - 1 /* filter byte */
  197978. - 7*8 /* rounding of width to multiple of 8 pixels */
  197979. - 8) /* extra max_pixel_depth pad */
  197980. png_warning(png_ptr, "Width is too large for libpng to process pixels");
  197981. /* check other values */
  197982. if (bit_depth != 1 && bit_depth != 2 && bit_depth != 4 &&
  197983. bit_depth != 8 && bit_depth != 16)
  197984. png_error(png_ptr, "Invalid bit depth in IHDR");
  197985. if (color_type < 0 || color_type == 1 ||
  197986. color_type == 5 || color_type > 6)
  197987. png_error(png_ptr, "Invalid color type in IHDR");
  197988. if (((color_type == PNG_COLOR_TYPE_PALETTE) && bit_depth > 8) ||
  197989. ((color_type == PNG_COLOR_TYPE_RGB ||
  197990. color_type == PNG_COLOR_TYPE_GRAY_ALPHA ||
  197991. color_type == PNG_COLOR_TYPE_RGB_ALPHA) && bit_depth < 8))
  197992. png_error(png_ptr, "Invalid color type/bit depth combination in IHDR");
  197993. if (interlace_type >= PNG_INTERLACE_LAST)
  197994. png_error(png_ptr, "Unknown interlace method in IHDR");
  197995. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  197996. png_error(png_ptr, "Unknown compression method in IHDR");
  197997. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  197998. /* Accept filter_method 64 (intrapixel differencing) only if
  197999. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  198000. * 2. Libpng did not read a PNG signature (this filter_method is only
  198001. * used in PNG datastreams that are embedded in MNG datastreams) and
  198002. * 3. The application called png_permit_mng_features with a mask that
  198003. * included PNG_FLAG_MNG_FILTER_64 and
  198004. * 4. The filter_method is 64 and
  198005. * 5. The color_type is RGB or RGBA
  198006. */
  198007. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&png_ptr->mng_features_permitted)
  198008. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  198009. if(filter_type != PNG_FILTER_TYPE_BASE)
  198010. {
  198011. if(!((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  198012. (filter_type == PNG_INTRAPIXEL_DIFFERENCING) &&
  198013. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  198014. (color_type == PNG_COLOR_TYPE_RGB ||
  198015. color_type == PNG_COLOR_TYPE_RGB_ALPHA)))
  198016. png_error(png_ptr, "Unknown filter method in IHDR");
  198017. if(png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)
  198018. png_warning(png_ptr, "Invalid filter method in IHDR");
  198019. }
  198020. #else
  198021. if(filter_type != PNG_FILTER_TYPE_BASE)
  198022. png_error(png_ptr, "Unknown filter method in IHDR");
  198023. #endif
  198024. info_ptr->width = width;
  198025. info_ptr->height = height;
  198026. info_ptr->bit_depth = (png_byte)bit_depth;
  198027. info_ptr->color_type =(png_byte) color_type;
  198028. info_ptr->compression_type = (png_byte)compression_type;
  198029. info_ptr->filter_type = (png_byte)filter_type;
  198030. info_ptr->interlace_type = (png_byte)interlace_type;
  198031. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198032. info_ptr->channels = 1;
  198033. else if (info_ptr->color_type & PNG_COLOR_MASK_COLOR)
  198034. info_ptr->channels = 3;
  198035. else
  198036. info_ptr->channels = 1;
  198037. if (info_ptr->color_type & PNG_COLOR_MASK_ALPHA)
  198038. info_ptr->channels++;
  198039. info_ptr->pixel_depth = (png_byte)(info_ptr->channels * info_ptr->bit_depth);
  198040. /* check for potential overflow */
  198041. if (width > (PNG_UINT_32_MAX
  198042. >> 3) /* 8-byte RGBA pixels */
  198043. - 64 /* bigrowbuf hack */
  198044. - 1 /* filter byte */
  198045. - 7*8 /* rounding of width to multiple of 8 pixels */
  198046. - 8) /* extra max_pixel_depth pad */
  198047. info_ptr->rowbytes = (png_size_t)0;
  198048. else
  198049. info_ptr->rowbytes = PNG_ROWBYTES(info_ptr->pixel_depth,width);
  198050. }
  198051. #if defined(PNG_oFFs_SUPPORTED)
  198052. void PNGAPI
  198053. png_set_oFFs(png_structp png_ptr, png_infop info_ptr,
  198054. png_int_32 offset_x, png_int_32 offset_y, int unit_type)
  198055. {
  198056. png_debug1(1, "in %s storage function\n", "oFFs");
  198057. if (png_ptr == NULL || info_ptr == NULL)
  198058. return;
  198059. info_ptr->x_offset = offset_x;
  198060. info_ptr->y_offset = offset_y;
  198061. info_ptr->offset_unit_type = (png_byte)unit_type;
  198062. info_ptr->valid |= PNG_INFO_oFFs;
  198063. }
  198064. #endif
  198065. #if defined(PNG_pCAL_SUPPORTED)
  198066. void PNGAPI
  198067. png_set_pCAL(png_structp png_ptr, png_infop info_ptr,
  198068. png_charp purpose, png_int_32 X0, png_int_32 X1, int type, int nparams,
  198069. png_charp units, png_charpp params)
  198070. {
  198071. png_uint_32 length;
  198072. int i;
  198073. png_debug1(1, "in %s storage function\n", "pCAL");
  198074. if (png_ptr == NULL || info_ptr == NULL)
  198075. return;
  198076. length = png_strlen(purpose) + 1;
  198077. png_debug1(3, "allocating purpose for info (%lu bytes)\n", length);
  198078. info_ptr->pcal_purpose = (png_charp)png_malloc_warn(png_ptr, length);
  198079. if (info_ptr->pcal_purpose == NULL)
  198080. {
  198081. png_warning(png_ptr, "Insufficient memory for pCAL purpose.");
  198082. return;
  198083. }
  198084. png_memcpy(info_ptr->pcal_purpose, purpose, (png_size_t)length);
  198085. png_debug(3, "storing X0, X1, type, and nparams in info\n");
  198086. info_ptr->pcal_X0 = X0;
  198087. info_ptr->pcal_X1 = X1;
  198088. info_ptr->pcal_type = (png_byte)type;
  198089. info_ptr->pcal_nparams = (png_byte)nparams;
  198090. length = png_strlen(units) + 1;
  198091. png_debug1(3, "allocating units for info (%lu bytes)\n", length);
  198092. info_ptr->pcal_units = (png_charp)png_malloc_warn(png_ptr, length);
  198093. if (info_ptr->pcal_units == NULL)
  198094. {
  198095. png_warning(png_ptr, "Insufficient memory for pCAL units.");
  198096. return;
  198097. }
  198098. png_memcpy(info_ptr->pcal_units, units, (png_size_t)length);
  198099. info_ptr->pcal_params = (png_charpp)png_malloc_warn(png_ptr,
  198100. (png_uint_32)((nparams + 1) * png_sizeof(png_charp)));
  198101. if (info_ptr->pcal_params == NULL)
  198102. {
  198103. png_warning(png_ptr, "Insufficient memory for pCAL params.");
  198104. return;
  198105. }
  198106. info_ptr->pcal_params[nparams] = NULL;
  198107. for (i = 0; i < nparams; i++)
  198108. {
  198109. length = png_strlen(params[i]) + 1;
  198110. png_debug2(3, "allocating parameter %d for info (%lu bytes)\n", i, length);
  198111. info_ptr->pcal_params[i] = (png_charp)png_malloc_warn(png_ptr, length);
  198112. if (info_ptr->pcal_params[i] == NULL)
  198113. {
  198114. png_warning(png_ptr, "Insufficient memory for pCAL parameter.");
  198115. return;
  198116. }
  198117. png_memcpy(info_ptr->pcal_params[i], params[i], (png_size_t)length);
  198118. }
  198119. info_ptr->valid |= PNG_INFO_pCAL;
  198120. #ifdef PNG_FREE_ME_SUPPORTED
  198121. info_ptr->free_me |= PNG_FREE_PCAL;
  198122. #endif
  198123. }
  198124. #endif
  198125. #if defined(PNG_READ_sCAL_SUPPORTED) || defined(PNG_WRITE_sCAL_SUPPORTED)
  198126. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198127. void PNGAPI
  198128. png_set_sCAL(png_structp png_ptr, png_infop info_ptr,
  198129. int unit, double width, double height)
  198130. {
  198131. png_debug1(1, "in %s storage function\n", "sCAL");
  198132. if (png_ptr == NULL || info_ptr == NULL)
  198133. return;
  198134. info_ptr->scal_unit = (png_byte)unit;
  198135. info_ptr->scal_pixel_width = width;
  198136. info_ptr->scal_pixel_height = height;
  198137. info_ptr->valid |= PNG_INFO_sCAL;
  198138. }
  198139. #else
  198140. #ifdef PNG_FIXED_POINT_SUPPORTED
  198141. void PNGAPI
  198142. png_set_sCAL_s(png_structp png_ptr, png_infop info_ptr,
  198143. int unit, png_charp swidth, png_charp sheight)
  198144. {
  198145. png_uint_32 length;
  198146. png_debug1(1, "in %s storage function\n", "sCAL");
  198147. if (png_ptr == NULL || info_ptr == NULL)
  198148. return;
  198149. info_ptr->scal_unit = (png_byte)unit;
  198150. length = png_strlen(swidth) + 1;
  198151. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  198152. info_ptr->scal_s_width = (png_charp)png_malloc_warn(png_ptr, length);
  198153. if (info_ptr->scal_s_width == NULL)
  198154. {
  198155. png_warning(png_ptr,
  198156. "Memory allocation failed while processing sCAL.");
  198157. }
  198158. png_memcpy(info_ptr->scal_s_width, swidth, (png_size_t)length);
  198159. length = png_strlen(sheight) + 1;
  198160. png_debug1(3, "allocating unit for info (%d bytes)\n", length);
  198161. info_ptr->scal_s_height = (png_charp)png_malloc_warn(png_ptr, length);
  198162. if (info_ptr->scal_s_height == NULL)
  198163. {
  198164. png_free (png_ptr, info_ptr->scal_s_width);
  198165. png_warning(png_ptr,
  198166. "Memory allocation failed while processing sCAL.");
  198167. }
  198168. png_memcpy(info_ptr->scal_s_height, sheight, (png_size_t)length);
  198169. info_ptr->valid |= PNG_INFO_sCAL;
  198170. #ifdef PNG_FREE_ME_SUPPORTED
  198171. info_ptr->free_me |= PNG_FREE_SCAL;
  198172. #endif
  198173. }
  198174. #endif
  198175. #endif
  198176. #endif
  198177. #if defined(PNG_pHYs_SUPPORTED)
  198178. void PNGAPI
  198179. png_set_pHYs(png_structp png_ptr, png_infop info_ptr,
  198180. png_uint_32 res_x, png_uint_32 res_y, int unit_type)
  198181. {
  198182. png_debug1(1, "in %s storage function\n", "pHYs");
  198183. if (png_ptr == NULL || info_ptr == NULL)
  198184. return;
  198185. info_ptr->x_pixels_per_unit = res_x;
  198186. info_ptr->y_pixels_per_unit = res_y;
  198187. info_ptr->phys_unit_type = (png_byte)unit_type;
  198188. info_ptr->valid |= PNG_INFO_pHYs;
  198189. }
  198190. #endif
  198191. void PNGAPI
  198192. png_set_PLTE(png_structp png_ptr, png_infop info_ptr,
  198193. png_colorp palette, int num_palette)
  198194. {
  198195. png_debug1(1, "in %s storage function\n", "PLTE");
  198196. if (png_ptr == NULL || info_ptr == NULL)
  198197. return;
  198198. if (num_palette < 0 || num_palette > PNG_MAX_PALETTE_LENGTH)
  198199. {
  198200. if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  198201. png_error(png_ptr, "Invalid palette length");
  198202. else
  198203. {
  198204. png_warning(png_ptr, "Invalid palette length");
  198205. return;
  198206. }
  198207. }
  198208. /*
  198209. * It may not actually be necessary to set png_ptr->palette here;
  198210. * we do it for backward compatibility with the way the png_handle_tRNS
  198211. * function used to do the allocation.
  198212. */
  198213. #ifdef PNG_FREE_ME_SUPPORTED
  198214. png_free_data(png_ptr, info_ptr, PNG_FREE_PLTE, 0);
  198215. #endif
  198216. /* Changed in libpng-1.2.1 to allocate PNG_MAX_PALETTE_LENGTH instead
  198217. of num_palette entries,
  198218. in case of an invalid PNG file that has too-large sample values. */
  198219. png_ptr->palette = (png_colorp)png_malloc(png_ptr,
  198220. PNG_MAX_PALETTE_LENGTH * png_sizeof(png_color));
  198221. png_memset(png_ptr->palette, 0, PNG_MAX_PALETTE_LENGTH *
  198222. png_sizeof(png_color));
  198223. png_memcpy(png_ptr->palette, palette, num_palette * png_sizeof (png_color));
  198224. info_ptr->palette = png_ptr->palette;
  198225. info_ptr->num_palette = png_ptr->num_palette = (png_uint_16)num_palette;
  198226. #ifdef PNG_FREE_ME_SUPPORTED
  198227. info_ptr->free_me |= PNG_FREE_PLTE;
  198228. #else
  198229. png_ptr->flags |= PNG_FLAG_FREE_PLTE;
  198230. #endif
  198231. info_ptr->valid |= PNG_INFO_PLTE;
  198232. }
  198233. #if defined(PNG_sBIT_SUPPORTED)
  198234. void PNGAPI
  198235. png_set_sBIT(png_structp png_ptr, png_infop info_ptr,
  198236. png_color_8p sig_bit)
  198237. {
  198238. png_debug1(1, "in %s storage function\n", "sBIT");
  198239. if (png_ptr == NULL || info_ptr == NULL)
  198240. return;
  198241. png_memcpy(&(info_ptr->sig_bit), sig_bit, png_sizeof (png_color_8));
  198242. info_ptr->valid |= PNG_INFO_sBIT;
  198243. }
  198244. #endif
  198245. #if defined(PNG_sRGB_SUPPORTED)
  198246. void PNGAPI
  198247. png_set_sRGB(png_structp png_ptr, png_infop info_ptr, int intent)
  198248. {
  198249. png_debug1(1, "in %s storage function\n", "sRGB");
  198250. if (png_ptr == NULL || info_ptr == NULL)
  198251. return;
  198252. info_ptr->srgb_intent = (png_byte)intent;
  198253. info_ptr->valid |= PNG_INFO_sRGB;
  198254. }
  198255. void PNGAPI
  198256. png_set_sRGB_gAMA_and_cHRM(png_structp png_ptr, png_infop info_ptr,
  198257. int intent)
  198258. {
  198259. #if defined(PNG_gAMA_SUPPORTED)
  198260. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198261. float file_gamma;
  198262. #endif
  198263. #ifdef PNG_FIXED_POINT_SUPPORTED
  198264. png_fixed_point int_file_gamma;
  198265. #endif
  198266. #endif
  198267. #if defined(PNG_cHRM_SUPPORTED)
  198268. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198269. float white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y;
  198270. #endif
  198271. #ifdef PNG_FIXED_POINT_SUPPORTED
  198272. png_fixed_point int_white_x, int_white_y, int_red_x, int_red_y, int_green_x,
  198273. int_green_y, int_blue_x, int_blue_y;
  198274. #endif
  198275. #endif
  198276. png_debug1(1, "in %s storage function\n", "sRGB_gAMA_and_cHRM");
  198277. if (png_ptr == NULL || info_ptr == NULL)
  198278. return;
  198279. png_set_sRGB(png_ptr, info_ptr, intent);
  198280. #if defined(PNG_gAMA_SUPPORTED)
  198281. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198282. file_gamma = (float).45455;
  198283. png_set_gAMA(png_ptr, info_ptr, file_gamma);
  198284. #endif
  198285. #ifdef PNG_FIXED_POINT_SUPPORTED
  198286. int_file_gamma = 45455L;
  198287. png_set_gAMA_fixed(png_ptr, info_ptr, int_file_gamma);
  198288. #endif
  198289. #endif
  198290. #if defined(PNG_cHRM_SUPPORTED)
  198291. #ifdef PNG_FIXED_POINT_SUPPORTED
  198292. int_white_x = 31270L;
  198293. int_white_y = 32900L;
  198294. int_red_x = 64000L;
  198295. int_red_y = 33000L;
  198296. int_green_x = 30000L;
  198297. int_green_y = 60000L;
  198298. int_blue_x = 15000L;
  198299. int_blue_y = 6000L;
  198300. png_set_cHRM_fixed(png_ptr, info_ptr,
  198301. int_white_x, int_white_y, int_red_x, int_red_y, int_green_x, int_green_y,
  198302. int_blue_x, int_blue_y);
  198303. #endif
  198304. #ifdef PNG_FLOATING_POINT_SUPPORTED
  198305. white_x = (float).3127;
  198306. white_y = (float).3290;
  198307. red_x = (float).64;
  198308. red_y = (float).33;
  198309. green_x = (float).30;
  198310. green_y = (float).60;
  198311. blue_x = (float).15;
  198312. blue_y = (float).06;
  198313. png_set_cHRM(png_ptr, info_ptr,
  198314. white_x, white_y, red_x, red_y, green_x, green_y, blue_x, blue_y);
  198315. #endif
  198316. #endif
  198317. }
  198318. #endif
  198319. #if defined(PNG_iCCP_SUPPORTED)
  198320. void PNGAPI
  198321. png_set_iCCP(png_structp png_ptr, png_infop info_ptr,
  198322. png_charp name, int compression_type,
  198323. png_charp profile, png_uint_32 proflen)
  198324. {
  198325. png_charp new_iccp_name;
  198326. png_charp new_iccp_profile;
  198327. png_debug1(1, "in %s storage function\n", "iCCP");
  198328. if (png_ptr == NULL || info_ptr == NULL || name == NULL || profile == NULL)
  198329. return;
  198330. new_iccp_name = (png_charp)png_malloc_warn(png_ptr, png_strlen(name)+1);
  198331. if (new_iccp_name == NULL)
  198332. {
  198333. png_warning(png_ptr, "Insufficient memory to process iCCP chunk.");
  198334. return;
  198335. }
  198336. png_strncpy(new_iccp_name, name, png_strlen(name)+1);
  198337. new_iccp_profile = (png_charp)png_malloc_warn(png_ptr, proflen);
  198338. if (new_iccp_profile == NULL)
  198339. {
  198340. png_free (png_ptr, new_iccp_name);
  198341. png_warning(png_ptr, "Insufficient memory to process iCCP profile.");
  198342. return;
  198343. }
  198344. png_memcpy(new_iccp_profile, profile, (png_size_t)proflen);
  198345. png_free_data(png_ptr, info_ptr, PNG_FREE_ICCP, 0);
  198346. info_ptr->iccp_proflen = proflen;
  198347. info_ptr->iccp_name = new_iccp_name;
  198348. info_ptr->iccp_profile = new_iccp_profile;
  198349. /* Compression is always zero but is here so the API and info structure
  198350. * does not have to change if we introduce multiple compression types */
  198351. info_ptr->iccp_compression = (png_byte)compression_type;
  198352. #ifdef PNG_FREE_ME_SUPPORTED
  198353. info_ptr->free_me |= PNG_FREE_ICCP;
  198354. #endif
  198355. info_ptr->valid |= PNG_INFO_iCCP;
  198356. }
  198357. #endif
  198358. #if defined(PNG_TEXT_SUPPORTED)
  198359. void PNGAPI
  198360. png_set_text(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  198361. int num_text)
  198362. {
  198363. int ret;
  198364. ret=png_set_text_2(png_ptr, info_ptr, text_ptr, num_text);
  198365. if (ret)
  198366. png_error(png_ptr, "Insufficient memory to store text");
  198367. }
  198368. int /* PRIVATE */
  198369. png_set_text_2(png_structp png_ptr, png_infop info_ptr, png_textp text_ptr,
  198370. int num_text)
  198371. {
  198372. int i;
  198373. png_debug1(1, "in %s storage function\n", (png_ptr->chunk_name[0] == '\0' ?
  198374. "text" : (png_const_charp)png_ptr->chunk_name));
  198375. if (png_ptr == NULL || info_ptr == NULL || num_text == 0)
  198376. return(0);
  198377. /* Make sure we have enough space in the "text" array in info_struct
  198378. * to hold all of the incoming text_ptr objects.
  198379. */
  198380. if (info_ptr->num_text + num_text > info_ptr->max_text)
  198381. {
  198382. if (info_ptr->text != NULL)
  198383. {
  198384. png_textp old_text;
  198385. int old_max;
  198386. old_max = info_ptr->max_text;
  198387. info_ptr->max_text = info_ptr->num_text + num_text + 8;
  198388. old_text = info_ptr->text;
  198389. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  198390. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  198391. if (info_ptr->text == NULL)
  198392. {
  198393. png_free(png_ptr, old_text);
  198394. return(1);
  198395. }
  198396. png_memcpy(info_ptr->text, old_text, (png_size_t)(old_max *
  198397. png_sizeof(png_text)));
  198398. png_free(png_ptr, old_text);
  198399. }
  198400. else
  198401. {
  198402. info_ptr->max_text = num_text + 8;
  198403. info_ptr->num_text = 0;
  198404. info_ptr->text = (png_textp)png_malloc_warn(png_ptr,
  198405. (png_uint_32)(info_ptr->max_text * png_sizeof (png_text)));
  198406. if (info_ptr->text == NULL)
  198407. return(1);
  198408. #ifdef PNG_FREE_ME_SUPPORTED
  198409. info_ptr->free_me |= PNG_FREE_TEXT;
  198410. #endif
  198411. }
  198412. png_debug1(3, "allocated %d entries for info_ptr->text\n",
  198413. info_ptr->max_text);
  198414. }
  198415. for (i = 0; i < num_text; i++)
  198416. {
  198417. png_size_t text_length,key_len;
  198418. png_size_t lang_len,lang_key_len;
  198419. png_textp textp = &(info_ptr->text[info_ptr->num_text]);
  198420. if (text_ptr[i].key == NULL)
  198421. continue;
  198422. key_len = png_strlen(text_ptr[i].key);
  198423. if(text_ptr[i].compression <= 0)
  198424. {
  198425. lang_len = 0;
  198426. lang_key_len = 0;
  198427. }
  198428. else
  198429. #ifdef PNG_iTXt_SUPPORTED
  198430. {
  198431. /* set iTXt data */
  198432. if (text_ptr[i].lang != NULL)
  198433. lang_len = png_strlen(text_ptr[i].lang);
  198434. else
  198435. lang_len = 0;
  198436. if (text_ptr[i].lang_key != NULL)
  198437. lang_key_len = png_strlen(text_ptr[i].lang_key);
  198438. else
  198439. lang_key_len = 0;
  198440. }
  198441. #else
  198442. {
  198443. png_warning(png_ptr, "iTXt chunk not supported.");
  198444. continue;
  198445. }
  198446. #endif
  198447. if (text_ptr[i].text == NULL || text_ptr[i].text[0] == '\0')
  198448. {
  198449. text_length = 0;
  198450. #ifdef PNG_iTXt_SUPPORTED
  198451. if(text_ptr[i].compression > 0)
  198452. textp->compression = PNG_ITXT_COMPRESSION_NONE;
  198453. else
  198454. #endif
  198455. textp->compression = PNG_TEXT_COMPRESSION_NONE;
  198456. }
  198457. else
  198458. {
  198459. text_length = png_strlen(text_ptr[i].text);
  198460. textp->compression = text_ptr[i].compression;
  198461. }
  198462. textp->key = (png_charp)png_malloc_warn(png_ptr,
  198463. (png_uint_32)(key_len + text_length + lang_len + lang_key_len + 4));
  198464. if (textp->key == NULL)
  198465. return(1);
  198466. png_debug2(2, "Allocated %lu bytes at %x in png_set_text\n",
  198467. (png_uint_32)(key_len + lang_len + lang_key_len + text_length + 4),
  198468. (int)textp->key);
  198469. png_memcpy(textp->key, text_ptr[i].key,
  198470. (png_size_t)(key_len));
  198471. *(textp->key+key_len) = '\0';
  198472. #ifdef PNG_iTXt_SUPPORTED
  198473. if (text_ptr[i].compression > 0)
  198474. {
  198475. textp->lang=textp->key + key_len + 1;
  198476. png_memcpy(textp->lang, text_ptr[i].lang, lang_len);
  198477. *(textp->lang+lang_len) = '\0';
  198478. textp->lang_key=textp->lang + lang_len + 1;
  198479. png_memcpy(textp->lang_key, text_ptr[i].lang_key, lang_key_len);
  198480. *(textp->lang_key+lang_key_len) = '\0';
  198481. textp->text=textp->lang_key + lang_key_len + 1;
  198482. }
  198483. else
  198484. #endif
  198485. {
  198486. #ifdef PNG_iTXt_SUPPORTED
  198487. textp->lang=NULL;
  198488. textp->lang_key=NULL;
  198489. #endif
  198490. textp->text=textp->key + key_len + 1;
  198491. }
  198492. if(text_length)
  198493. png_memcpy(textp->text, text_ptr[i].text,
  198494. (png_size_t)(text_length));
  198495. *(textp->text+text_length) = '\0';
  198496. #ifdef PNG_iTXt_SUPPORTED
  198497. if(textp->compression > 0)
  198498. {
  198499. textp->text_length = 0;
  198500. textp->itxt_length = text_length;
  198501. }
  198502. else
  198503. #endif
  198504. {
  198505. textp->text_length = text_length;
  198506. #ifdef PNG_iTXt_SUPPORTED
  198507. textp->itxt_length = 0;
  198508. #endif
  198509. }
  198510. info_ptr->num_text++;
  198511. png_debug1(3, "transferred text chunk %d\n", info_ptr->num_text);
  198512. }
  198513. return(0);
  198514. }
  198515. #endif
  198516. #if defined(PNG_tIME_SUPPORTED)
  198517. void PNGAPI
  198518. png_set_tIME(png_structp png_ptr, png_infop info_ptr, png_timep mod_time)
  198519. {
  198520. png_debug1(1, "in %s storage function\n", "tIME");
  198521. if (png_ptr == NULL || info_ptr == NULL ||
  198522. (png_ptr->mode & PNG_WROTE_tIME))
  198523. return;
  198524. png_memcpy(&(info_ptr->mod_time), mod_time, png_sizeof (png_time));
  198525. info_ptr->valid |= PNG_INFO_tIME;
  198526. }
  198527. #endif
  198528. #if defined(PNG_tRNS_SUPPORTED)
  198529. void PNGAPI
  198530. png_set_tRNS(png_structp png_ptr, png_infop info_ptr,
  198531. png_bytep trans, int num_trans, png_color_16p trans_values)
  198532. {
  198533. png_debug1(1, "in %s storage function\n", "tRNS");
  198534. if (png_ptr == NULL || info_ptr == NULL)
  198535. return;
  198536. if (trans != NULL)
  198537. {
  198538. /*
  198539. * It may not actually be necessary to set png_ptr->trans here;
  198540. * we do it for backward compatibility with the way the png_handle_tRNS
  198541. * function used to do the allocation.
  198542. */
  198543. #ifdef PNG_FREE_ME_SUPPORTED
  198544. png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
  198545. #endif
  198546. /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
  198547. png_ptr->trans = info_ptr->trans = (png_bytep)png_malloc(png_ptr,
  198548. (png_uint_32)PNG_MAX_PALETTE_LENGTH);
  198549. if (num_trans <= PNG_MAX_PALETTE_LENGTH)
  198550. png_memcpy(info_ptr->trans, trans, (png_size_t)num_trans);
  198551. #ifdef PNG_FREE_ME_SUPPORTED
  198552. info_ptr->free_me |= PNG_FREE_TRNS;
  198553. #else
  198554. png_ptr->flags |= PNG_FLAG_FREE_TRNS;
  198555. #endif
  198556. }
  198557. if (trans_values != NULL)
  198558. {
  198559. png_memcpy(&(info_ptr->trans_values), trans_values,
  198560. png_sizeof(png_color_16));
  198561. if (num_trans == 0)
  198562. num_trans = 1;
  198563. }
  198564. info_ptr->num_trans = (png_uint_16)num_trans;
  198565. info_ptr->valid |= PNG_INFO_tRNS;
  198566. }
  198567. #endif
  198568. #if defined(PNG_sPLT_SUPPORTED)
  198569. void PNGAPI
  198570. png_set_sPLT(png_structp png_ptr,
  198571. png_infop info_ptr, png_sPLT_tp entries, int nentries)
  198572. {
  198573. png_sPLT_tp np;
  198574. int i;
  198575. if (png_ptr == NULL || info_ptr == NULL)
  198576. return;
  198577. np = (png_sPLT_tp)png_malloc_warn(png_ptr,
  198578. (info_ptr->splt_palettes_num + nentries) * png_sizeof(png_sPLT_t));
  198579. if (np == NULL)
  198580. {
  198581. png_warning(png_ptr, "No memory for sPLT palettes.");
  198582. return;
  198583. }
  198584. png_memcpy(np, info_ptr->splt_palettes,
  198585. info_ptr->splt_palettes_num * png_sizeof(png_sPLT_t));
  198586. png_free(png_ptr, info_ptr->splt_palettes);
  198587. info_ptr->splt_palettes=NULL;
  198588. for (i = 0; i < nentries; i++)
  198589. {
  198590. png_sPLT_tp to = np + info_ptr->splt_palettes_num + i;
  198591. png_sPLT_tp from = entries + i;
  198592. to->name = (png_charp)png_malloc_warn(png_ptr,
  198593. png_strlen(from->name) + 1);
  198594. if (to->name == NULL)
  198595. {
  198596. png_warning(png_ptr,
  198597. "Out of memory while processing sPLT chunk");
  198598. }
  198599. /* TODO: use png_malloc_warn */
  198600. png_strncpy(to->name, from->name, png_strlen(from->name)+1);
  198601. to->entries = (png_sPLT_entryp)png_malloc_warn(png_ptr,
  198602. from->nentries * png_sizeof(png_sPLT_entry));
  198603. /* TODO: use png_malloc_warn */
  198604. png_memcpy(to->entries, from->entries,
  198605. from->nentries * png_sizeof(png_sPLT_entry));
  198606. if (to->entries == NULL)
  198607. {
  198608. png_warning(png_ptr,
  198609. "Out of memory while processing sPLT chunk");
  198610. png_free(png_ptr,to->name);
  198611. to->name = NULL;
  198612. }
  198613. to->nentries = from->nentries;
  198614. to->depth = from->depth;
  198615. }
  198616. info_ptr->splt_palettes = np;
  198617. info_ptr->splt_palettes_num += nentries;
  198618. info_ptr->valid |= PNG_INFO_sPLT;
  198619. #ifdef PNG_FREE_ME_SUPPORTED
  198620. info_ptr->free_me |= PNG_FREE_SPLT;
  198621. #endif
  198622. }
  198623. #endif /* PNG_sPLT_SUPPORTED */
  198624. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  198625. void PNGAPI
  198626. png_set_unknown_chunks(png_structp png_ptr,
  198627. png_infop info_ptr, png_unknown_chunkp unknowns, int num_unknowns)
  198628. {
  198629. png_unknown_chunkp np;
  198630. int i;
  198631. if (png_ptr == NULL || info_ptr == NULL || num_unknowns == 0)
  198632. return;
  198633. np = (png_unknown_chunkp)png_malloc_warn(png_ptr,
  198634. (info_ptr->unknown_chunks_num + num_unknowns) *
  198635. png_sizeof(png_unknown_chunk));
  198636. if (np == NULL)
  198637. {
  198638. png_warning(png_ptr,
  198639. "Out of memory while processing unknown chunk.");
  198640. return;
  198641. }
  198642. png_memcpy(np, info_ptr->unknown_chunks,
  198643. info_ptr->unknown_chunks_num * png_sizeof(png_unknown_chunk));
  198644. png_free(png_ptr, info_ptr->unknown_chunks);
  198645. info_ptr->unknown_chunks=NULL;
  198646. for (i = 0; i < num_unknowns; i++)
  198647. {
  198648. png_unknown_chunkp to = np + info_ptr->unknown_chunks_num + i;
  198649. png_unknown_chunkp from = unknowns + i;
  198650. png_strncpy((png_charp)to->name, (png_charp)from->name, 5);
  198651. to->data = (png_bytep)png_malloc_warn(png_ptr, from->size);
  198652. if (to->data == NULL)
  198653. {
  198654. png_warning(png_ptr,
  198655. "Out of memory while processing unknown chunk.");
  198656. }
  198657. else
  198658. {
  198659. png_memcpy(to->data, from->data, from->size);
  198660. to->size = from->size;
  198661. /* note our location in the read or write sequence */
  198662. to->location = (png_byte)(png_ptr->mode & 0xff);
  198663. }
  198664. }
  198665. info_ptr->unknown_chunks = np;
  198666. info_ptr->unknown_chunks_num += num_unknowns;
  198667. #ifdef PNG_FREE_ME_SUPPORTED
  198668. info_ptr->free_me |= PNG_FREE_UNKN;
  198669. #endif
  198670. }
  198671. void PNGAPI
  198672. png_set_unknown_chunk_location(png_structp png_ptr, png_infop info_ptr,
  198673. int chunk, int location)
  198674. {
  198675. if(png_ptr != NULL && info_ptr != NULL && chunk >= 0 && chunk <
  198676. (int)info_ptr->unknown_chunks_num)
  198677. info_ptr->unknown_chunks[chunk].location = (png_byte)location;
  198678. }
  198679. #endif
  198680. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  198681. #if defined(PNG_READ_EMPTY_PLTE_SUPPORTED) || \
  198682. defined(PNG_WRITE_EMPTY_PLTE_SUPPORTED)
  198683. void PNGAPI
  198684. png_permit_empty_plte (png_structp png_ptr, int empty_plte_permitted)
  198685. {
  198686. /* This function is deprecated in favor of png_permit_mng_features()
  198687. and will be removed from libpng-1.3.0 */
  198688. png_debug(1, "in png_permit_empty_plte, DEPRECATED.\n");
  198689. if (png_ptr == NULL)
  198690. return;
  198691. png_ptr->mng_features_permitted = (png_byte)
  198692. ((png_ptr->mng_features_permitted & (~(PNG_FLAG_MNG_EMPTY_PLTE))) |
  198693. ((empty_plte_permitted & PNG_FLAG_MNG_EMPTY_PLTE)));
  198694. }
  198695. #endif
  198696. #endif
  198697. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  198698. png_uint_32 PNGAPI
  198699. png_permit_mng_features (png_structp png_ptr, png_uint_32 mng_features)
  198700. {
  198701. png_debug(1, "in png_permit_mng_features\n");
  198702. if (png_ptr == NULL)
  198703. return (png_uint_32)0;
  198704. png_ptr->mng_features_permitted =
  198705. (png_byte)(mng_features & PNG_ALL_MNG_FEATURES);
  198706. return (png_uint_32)png_ptr->mng_features_permitted;
  198707. }
  198708. #endif
  198709. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  198710. void PNGAPI
  198711. png_set_keep_unknown_chunks(png_structp png_ptr, int keep, png_bytep
  198712. chunk_list, int num_chunks)
  198713. {
  198714. png_bytep new_list, p;
  198715. int i, old_num_chunks;
  198716. if (png_ptr == NULL)
  198717. return;
  198718. if (num_chunks == 0)
  198719. {
  198720. if(keep == PNG_HANDLE_CHUNK_ALWAYS || keep == PNG_HANDLE_CHUNK_IF_SAFE)
  198721. png_ptr->flags |= PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  198722. else
  198723. png_ptr->flags &= ~PNG_FLAG_KEEP_UNKNOWN_CHUNKS;
  198724. if(keep == PNG_HANDLE_CHUNK_ALWAYS)
  198725. png_ptr->flags |= PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  198726. else
  198727. png_ptr->flags &= ~PNG_FLAG_KEEP_UNSAFE_CHUNKS;
  198728. return;
  198729. }
  198730. if (chunk_list == NULL)
  198731. return;
  198732. old_num_chunks=png_ptr->num_chunk_list;
  198733. new_list=(png_bytep)png_malloc(png_ptr,
  198734. (png_uint_32)(5*(num_chunks+old_num_chunks)));
  198735. if(png_ptr->chunk_list != NULL)
  198736. {
  198737. png_memcpy(new_list, png_ptr->chunk_list,
  198738. (png_size_t)(5*old_num_chunks));
  198739. png_free(png_ptr, png_ptr->chunk_list);
  198740. png_ptr->chunk_list=NULL;
  198741. }
  198742. png_memcpy(new_list+5*old_num_chunks, chunk_list,
  198743. (png_size_t)(5*num_chunks));
  198744. for (p=new_list+5*old_num_chunks+4, i=0; i<num_chunks; i++, p+=5)
  198745. *p=(png_byte)keep;
  198746. png_ptr->num_chunk_list=old_num_chunks+num_chunks;
  198747. png_ptr->chunk_list=new_list;
  198748. #ifdef PNG_FREE_ME_SUPPORTED
  198749. png_ptr->free_me |= PNG_FREE_LIST;
  198750. #endif
  198751. }
  198752. #endif
  198753. #if defined(PNG_READ_USER_CHUNKS_SUPPORTED)
  198754. void PNGAPI
  198755. png_set_read_user_chunk_fn(png_structp png_ptr, png_voidp user_chunk_ptr,
  198756. png_user_chunk_ptr read_user_chunk_fn)
  198757. {
  198758. png_debug(1, "in png_set_read_user_chunk_fn\n");
  198759. if (png_ptr == NULL)
  198760. return;
  198761. png_ptr->read_user_chunk_fn = read_user_chunk_fn;
  198762. png_ptr->user_chunk_ptr = user_chunk_ptr;
  198763. }
  198764. #endif
  198765. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  198766. void PNGAPI
  198767. png_set_rows(png_structp png_ptr, png_infop info_ptr, png_bytepp row_pointers)
  198768. {
  198769. png_debug1(1, "in %s storage function\n", "rows");
  198770. if (png_ptr == NULL || info_ptr == NULL)
  198771. return;
  198772. if(info_ptr->row_pointers && (info_ptr->row_pointers != row_pointers))
  198773. png_free_data(png_ptr, info_ptr, PNG_FREE_ROWS, 0);
  198774. info_ptr->row_pointers = row_pointers;
  198775. if(row_pointers)
  198776. info_ptr->valid |= PNG_INFO_IDAT;
  198777. }
  198778. #endif
  198779. #ifdef PNG_WRITE_SUPPORTED
  198780. void PNGAPI
  198781. png_set_compression_buffer_size(png_structp png_ptr, png_uint_32 size)
  198782. {
  198783. if (png_ptr == NULL)
  198784. return;
  198785. if(png_ptr->zbuf)
  198786. png_free(png_ptr, png_ptr->zbuf);
  198787. png_ptr->zbuf_size = (png_size_t)size;
  198788. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr, size);
  198789. png_ptr->zstream.next_out = png_ptr->zbuf;
  198790. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  198791. }
  198792. #endif
  198793. void PNGAPI
  198794. png_set_invalid(png_structp png_ptr, png_infop info_ptr, int mask)
  198795. {
  198796. if (png_ptr && info_ptr)
  198797. info_ptr->valid &= ~(mask);
  198798. }
  198799. #ifndef PNG_1_0_X
  198800. #ifdef PNG_ASSEMBLER_CODE_SUPPORTED
  198801. /* function was added to libpng 1.2.0 and should always exist by default */
  198802. void PNGAPI
  198803. png_set_asm_flags (png_structp png_ptr, png_uint_32 asm_flags)
  198804. {
  198805. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198806. if (png_ptr != NULL)
  198807. png_ptr->asm_flags = 0;
  198808. }
  198809. /* this function was added to libpng 1.2.0 */
  198810. void PNGAPI
  198811. png_set_mmx_thresholds (png_structp png_ptr,
  198812. png_byte mmx_bitdepth_threshold,
  198813. png_uint_32 mmx_rowbytes_threshold)
  198814. {
  198815. /* Obsolete as of libpng-1.2.20 and will be removed from libpng-1.4.0 */
  198816. if (png_ptr == NULL)
  198817. return;
  198818. }
  198819. #endif /* ?PNG_ASSEMBLER_CODE_SUPPORTED */
  198820. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  198821. /* this function was added to libpng 1.2.6 */
  198822. void PNGAPI
  198823. png_set_user_limits (png_structp png_ptr, png_uint_32 user_width_max,
  198824. png_uint_32 user_height_max)
  198825. {
  198826. /* Images with dimensions larger than these limits will be
  198827. * rejected by png_set_IHDR(). To accept any PNG datastream
  198828. * regardless of dimensions, set both limits to 0x7ffffffL.
  198829. */
  198830. if(png_ptr == NULL) return;
  198831. png_ptr->user_width_max = user_width_max;
  198832. png_ptr->user_height_max = user_height_max;
  198833. }
  198834. #endif /* ?PNG_SET_USER_LIMITS_SUPPORTED */
  198835. #endif /* ?PNG_1_0_X */
  198836. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  198837. /********* End of inlined file: pngset.c *********/
  198838. /********* Start of inlined file: pngtrans.c *********/
  198839. /* pngtrans.c - transforms the data in a row (used by both readers and writers)
  198840. *
  198841. * Last changed in libpng 1.2.17 May 15, 2007
  198842. * For conditions of distribution and use, see copyright notice in png.h
  198843. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  198844. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  198845. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  198846. */
  198847. #define PNG_INTERNAL
  198848. #if defined(PNG_READ_SUPPORTED) || defined(PNG_WRITE_SUPPORTED)
  198849. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  198850. /* turn on BGR-to-RGB mapping */
  198851. void PNGAPI
  198852. png_set_bgr(png_structp png_ptr)
  198853. {
  198854. png_debug(1, "in png_set_bgr\n");
  198855. if(png_ptr == NULL) return;
  198856. png_ptr->transformations |= PNG_BGR;
  198857. }
  198858. #endif
  198859. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  198860. /* turn on 16 bit byte swapping */
  198861. void PNGAPI
  198862. png_set_swap(png_structp png_ptr)
  198863. {
  198864. png_debug(1, "in png_set_swap\n");
  198865. if(png_ptr == NULL) return;
  198866. if (png_ptr->bit_depth == 16)
  198867. png_ptr->transformations |= PNG_SWAP_BYTES;
  198868. }
  198869. #endif
  198870. #if defined(PNG_READ_PACK_SUPPORTED) || defined(PNG_WRITE_PACK_SUPPORTED)
  198871. /* turn on pixel packing */
  198872. void PNGAPI
  198873. png_set_packing(png_structp png_ptr)
  198874. {
  198875. png_debug(1, "in png_set_packing\n");
  198876. if(png_ptr == NULL) return;
  198877. if (png_ptr->bit_depth < 8)
  198878. {
  198879. png_ptr->transformations |= PNG_PACK;
  198880. png_ptr->usr_bit_depth = 8;
  198881. }
  198882. }
  198883. #endif
  198884. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  198885. /* turn on packed pixel swapping */
  198886. void PNGAPI
  198887. png_set_packswap(png_structp png_ptr)
  198888. {
  198889. png_debug(1, "in png_set_packswap\n");
  198890. if(png_ptr == NULL) return;
  198891. if (png_ptr->bit_depth < 8)
  198892. png_ptr->transformations |= PNG_PACKSWAP;
  198893. }
  198894. #endif
  198895. #if defined(PNG_READ_SHIFT_SUPPORTED) || defined(PNG_WRITE_SHIFT_SUPPORTED)
  198896. void PNGAPI
  198897. png_set_shift(png_structp png_ptr, png_color_8p true_bits)
  198898. {
  198899. png_debug(1, "in png_set_shift\n");
  198900. if(png_ptr == NULL) return;
  198901. png_ptr->transformations |= PNG_SHIFT;
  198902. png_ptr->shift = *true_bits;
  198903. }
  198904. #endif
  198905. #if defined(PNG_READ_INTERLACING_SUPPORTED) || \
  198906. defined(PNG_WRITE_INTERLACING_SUPPORTED)
  198907. int PNGAPI
  198908. png_set_interlace_handling(png_structp png_ptr)
  198909. {
  198910. png_debug(1, "in png_set_interlace handling\n");
  198911. if (png_ptr && png_ptr->interlaced)
  198912. {
  198913. png_ptr->transformations |= PNG_INTERLACE;
  198914. return (7);
  198915. }
  198916. return (1);
  198917. }
  198918. #endif
  198919. #if defined(PNG_READ_FILLER_SUPPORTED) || defined(PNG_WRITE_FILLER_SUPPORTED)
  198920. /* Add a filler byte on read, or remove a filler or alpha byte on write.
  198921. * The filler type has changed in v0.95 to allow future 2-byte fillers
  198922. * for 48-bit input data, as well as to avoid problems with some compilers
  198923. * that don't like bytes as parameters.
  198924. */
  198925. void PNGAPI
  198926. png_set_filler(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198927. {
  198928. png_debug(1, "in png_set_filler\n");
  198929. if(png_ptr == NULL) return;
  198930. png_ptr->transformations |= PNG_FILLER;
  198931. png_ptr->filler = (png_byte)filler;
  198932. if (filler_loc == PNG_FILLER_AFTER)
  198933. png_ptr->flags |= PNG_FLAG_FILLER_AFTER;
  198934. else
  198935. png_ptr->flags &= ~PNG_FLAG_FILLER_AFTER;
  198936. /* This should probably go in the "do_read_filler" routine.
  198937. * I attempted to do that in libpng-1.0.1a but that caused problems
  198938. * so I restored it in libpng-1.0.2a
  198939. */
  198940. if (png_ptr->color_type == PNG_COLOR_TYPE_RGB)
  198941. {
  198942. png_ptr->usr_channels = 4;
  198943. }
  198944. /* Also I added this in libpng-1.0.2a (what happens when we expand
  198945. * a less-than-8-bit grayscale to GA? */
  198946. if (png_ptr->color_type == PNG_COLOR_TYPE_GRAY && png_ptr->bit_depth >= 8)
  198947. {
  198948. png_ptr->usr_channels = 2;
  198949. }
  198950. }
  198951. #if !defined(PNG_1_0_X)
  198952. /* Added to libpng-1.2.7 */
  198953. void PNGAPI
  198954. png_set_add_alpha(png_structp png_ptr, png_uint_32 filler, int filler_loc)
  198955. {
  198956. png_debug(1, "in png_set_add_alpha\n");
  198957. if(png_ptr == NULL) return;
  198958. png_set_filler(png_ptr, filler, filler_loc);
  198959. png_ptr->transformations |= PNG_ADD_ALPHA;
  198960. }
  198961. #endif
  198962. #endif
  198963. #if defined(PNG_READ_SWAP_ALPHA_SUPPORTED) || \
  198964. defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  198965. void PNGAPI
  198966. png_set_swap_alpha(png_structp png_ptr)
  198967. {
  198968. png_debug(1, "in png_set_swap_alpha\n");
  198969. if(png_ptr == NULL) return;
  198970. png_ptr->transformations |= PNG_SWAP_ALPHA;
  198971. }
  198972. #endif
  198973. #if defined(PNG_READ_INVERT_ALPHA_SUPPORTED) || \
  198974. defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  198975. void PNGAPI
  198976. png_set_invert_alpha(png_structp png_ptr)
  198977. {
  198978. png_debug(1, "in png_set_invert_alpha\n");
  198979. if(png_ptr == NULL) return;
  198980. png_ptr->transformations |= PNG_INVERT_ALPHA;
  198981. }
  198982. #endif
  198983. #if defined(PNG_READ_INVERT_SUPPORTED) || defined(PNG_WRITE_INVERT_SUPPORTED)
  198984. void PNGAPI
  198985. png_set_invert_mono(png_structp png_ptr)
  198986. {
  198987. png_debug(1, "in png_set_invert_mono\n");
  198988. if(png_ptr == NULL) return;
  198989. png_ptr->transformations |= PNG_INVERT_MONO;
  198990. }
  198991. /* invert monochrome grayscale data */
  198992. void /* PRIVATE */
  198993. png_do_invert(png_row_infop row_info, png_bytep row)
  198994. {
  198995. png_debug(1, "in png_do_invert\n");
  198996. /* This test removed from libpng version 1.0.13 and 1.2.0:
  198997. * if (row_info->bit_depth == 1 &&
  198998. */
  198999. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199000. if (row == NULL || row_info == NULL)
  199001. return;
  199002. #endif
  199003. if (row_info->color_type == PNG_COLOR_TYPE_GRAY)
  199004. {
  199005. png_bytep rp = row;
  199006. png_uint_32 i;
  199007. png_uint_32 istop = row_info->rowbytes;
  199008. for (i = 0; i < istop; i++)
  199009. {
  199010. *rp = (png_byte)(~(*rp));
  199011. rp++;
  199012. }
  199013. }
  199014. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  199015. row_info->bit_depth == 8)
  199016. {
  199017. png_bytep rp = row;
  199018. png_uint_32 i;
  199019. png_uint_32 istop = row_info->rowbytes;
  199020. for (i = 0; i < istop; i+=2)
  199021. {
  199022. *rp = (png_byte)(~(*rp));
  199023. rp+=2;
  199024. }
  199025. }
  199026. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  199027. row_info->bit_depth == 16)
  199028. {
  199029. png_bytep rp = row;
  199030. png_uint_32 i;
  199031. png_uint_32 istop = row_info->rowbytes;
  199032. for (i = 0; i < istop; i+=4)
  199033. {
  199034. *rp = (png_byte)(~(*rp));
  199035. *(rp+1) = (png_byte)(~(*(rp+1)));
  199036. rp+=4;
  199037. }
  199038. }
  199039. }
  199040. #endif
  199041. #if defined(PNG_READ_SWAP_SUPPORTED) || defined(PNG_WRITE_SWAP_SUPPORTED)
  199042. /* swaps byte order on 16 bit depth images */
  199043. void /* PRIVATE */
  199044. png_do_swap(png_row_infop row_info, png_bytep row)
  199045. {
  199046. png_debug(1, "in png_do_swap\n");
  199047. if (
  199048. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199049. row != NULL && row_info != NULL &&
  199050. #endif
  199051. row_info->bit_depth == 16)
  199052. {
  199053. png_bytep rp = row;
  199054. png_uint_32 i;
  199055. png_uint_32 istop= row_info->width * row_info->channels;
  199056. for (i = 0; i < istop; i++, rp += 2)
  199057. {
  199058. png_byte t = *rp;
  199059. *rp = *(rp + 1);
  199060. *(rp + 1) = t;
  199061. }
  199062. }
  199063. }
  199064. #endif
  199065. #if defined(PNG_READ_PACKSWAP_SUPPORTED)||defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  199066. static PNG_CONST png_byte onebppswaptable[256] = {
  199067. 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
  199068. 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
  199069. 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
  199070. 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
  199071. 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
  199072. 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
  199073. 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
  199074. 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
  199075. 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
  199076. 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
  199077. 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
  199078. 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
  199079. 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
  199080. 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
  199081. 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
  199082. 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
  199083. 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
  199084. 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
  199085. 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
  199086. 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
  199087. 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
  199088. 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
  199089. 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
  199090. 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
  199091. 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
  199092. 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
  199093. 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
  199094. 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
  199095. 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
  199096. 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
  199097. 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
  199098. 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF
  199099. };
  199100. static PNG_CONST png_byte twobppswaptable[256] = {
  199101. 0x00, 0x40, 0x80, 0xC0, 0x10, 0x50, 0x90, 0xD0,
  199102. 0x20, 0x60, 0xA0, 0xE0, 0x30, 0x70, 0xB0, 0xF0,
  199103. 0x04, 0x44, 0x84, 0xC4, 0x14, 0x54, 0x94, 0xD4,
  199104. 0x24, 0x64, 0xA4, 0xE4, 0x34, 0x74, 0xB4, 0xF4,
  199105. 0x08, 0x48, 0x88, 0xC8, 0x18, 0x58, 0x98, 0xD8,
  199106. 0x28, 0x68, 0xA8, 0xE8, 0x38, 0x78, 0xB8, 0xF8,
  199107. 0x0C, 0x4C, 0x8C, 0xCC, 0x1C, 0x5C, 0x9C, 0xDC,
  199108. 0x2C, 0x6C, 0xAC, 0xEC, 0x3C, 0x7C, 0xBC, 0xFC,
  199109. 0x01, 0x41, 0x81, 0xC1, 0x11, 0x51, 0x91, 0xD1,
  199110. 0x21, 0x61, 0xA1, 0xE1, 0x31, 0x71, 0xB1, 0xF1,
  199111. 0x05, 0x45, 0x85, 0xC5, 0x15, 0x55, 0x95, 0xD5,
  199112. 0x25, 0x65, 0xA5, 0xE5, 0x35, 0x75, 0xB5, 0xF5,
  199113. 0x09, 0x49, 0x89, 0xC9, 0x19, 0x59, 0x99, 0xD9,
  199114. 0x29, 0x69, 0xA9, 0xE9, 0x39, 0x79, 0xB9, 0xF9,
  199115. 0x0D, 0x4D, 0x8D, 0xCD, 0x1D, 0x5D, 0x9D, 0xDD,
  199116. 0x2D, 0x6D, 0xAD, 0xED, 0x3D, 0x7D, 0xBD, 0xFD,
  199117. 0x02, 0x42, 0x82, 0xC2, 0x12, 0x52, 0x92, 0xD2,
  199118. 0x22, 0x62, 0xA2, 0xE2, 0x32, 0x72, 0xB2, 0xF2,
  199119. 0x06, 0x46, 0x86, 0xC6, 0x16, 0x56, 0x96, 0xD6,
  199120. 0x26, 0x66, 0xA6, 0xE6, 0x36, 0x76, 0xB6, 0xF6,
  199121. 0x0A, 0x4A, 0x8A, 0xCA, 0x1A, 0x5A, 0x9A, 0xDA,
  199122. 0x2A, 0x6A, 0xAA, 0xEA, 0x3A, 0x7A, 0xBA, 0xFA,
  199123. 0x0E, 0x4E, 0x8E, 0xCE, 0x1E, 0x5E, 0x9E, 0xDE,
  199124. 0x2E, 0x6E, 0xAE, 0xEE, 0x3E, 0x7E, 0xBE, 0xFE,
  199125. 0x03, 0x43, 0x83, 0xC3, 0x13, 0x53, 0x93, 0xD3,
  199126. 0x23, 0x63, 0xA3, 0xE3, 0x33, 0x73, 0xB3, 0xF3,
  199127. 0x07, 0x47, 0x87, 0xC7, 0x17, 0x57, 0x97, 0xD7,
  199128. 0x27, 0x67, 0xA7, 0xE7, 0x37, 0x77, 0xB7, 0xF7,
  199129. 0x0B, 0x4B, 0x8B, 0xCB, 0x1B, 0x5B, 0x9B, 0xDB,
  199130. 0x2B, 0x6B, 0xAB, 0xEB, 0x3B, 0x7B, 0xBB, 0xFB,
  199131. 0x0F, 0x4F, 0x8F, 0xCF, 0x1F, 0x5F, 0x9F, 0xDF,
  199132. 0x2F, 0x6F, 0xAF, 0xEF, 0x3F, 0x7F, 0xBF, 0xFF
  199133. };
  199134. static PNG_CONST png_byte fourbppswaptable[256] = {
  199135. 0x00, 0x10, 0x20, 0x30, 0x40, 0x50, 0x60, 0x70,
  199136. 0x80, 0x90, 0xA0, 0xB0, 0xC0, 0xD0, 0xE0, 0xF0,
  199137. 0x01, 0x11, 0x21, 0x31, 0x41, 0x51, 0x61, 0x71,
  199138. 0x81, 0x91, 0xA1, 0xB1, 0xC1, 0xD1, 0xE1, 0xF1,
  199139. 0x02, 0x12, 0x22, 0x32, 0x42, 0x52, 0x62, 0x72,
  199140. 0x82, 0x92, 0xA2, 0xB2, 0xC2, 0xD2, 0xE2, 0xF2,
  199141. 0x03, 0x13, 0x23, 0x33, 0x43, 0x53, 0x63, 0x73,
  199142. 0x83, 0x93, 0xA3, 0xB3, 0xC3, 0xD3, 0xE3, 0xF3,
  199143. 0x04, 0x14, 0x24, 0x34, 0x44, 0x54, 0x64, 0x74,
  199144. 0x84, 0x94, 0xA4, 0xB4, 0xC4, 0xD4, 0xE4, 0xF4,
  199145. 0x05, 0x15, 0x25, 0x35, 0x45, 0x55, 0x65, 0x75,
  199146. 0x85, 0x95, 0xA5, 0xB5, 0xC5, 0xD5, 0xE5, 0xF5,
  199147. 0x06, 0x16, 0x26, 0x36, 0x46, 0x56, 0x66, 0x76,
  199148. 0x86, 0x96, 0xA6, 0xB6, 0xC6, 0xD6, 0xE6, 0xF6,
  199149. 0x07, 0x17, 0x27, 0x37, 0x47, 0x57, 0x67, 0x77,
  199150. 0x87, 0x97, 0xA7, 0xB7, 0xC7, 0xD7, 0xE7, 0xF7,
  199151. 0x08, 0x18, 0x28, 0x38, 0x48, 0x58, 0x68, 0x78,
  199152. 0x88, 0x98, 0xA8, 0xB8, 0xC8, 0xD8, 0xE8, 0xF8,
  199153. 0x09, 0x19, 0x29, 0x39, 0x49, 0x59, 0x69, 0x79,
  199154. 0x89, 0x99, 0xA9, 0xB9, 0xC9, 0xD9, 0xE9, 0xF9,
  199155. 0x0A, 0x1A, 0x2A, 0x3A, 0x4A, 0x5A, 0x6A, 0x7A,
  199156. 0x8A, 0x9A, 0xAA, 0xBA, 0xCA, 0xDA, 0xEA, 0xFA,
  199157. 0x0B, 0x1B, 0x2B, 0x3B, 0x4B, 0x5B, 0x6B, 0x7B,
  199158. 0x8B, 0x9B, 0xAB, 0xBB, 0xCB, 0xDB, 0xEB, 0xFB,
  199159. 0x0C, 0x1C, 0x2C, 0x3C, 0x4C, 0x5C, 0x6C, 0x7C,
  199160. 0x8C, 0x9C, 0xAC, 0xBC, 0xCC, 0xDC, 0xEC, 0xFC,
  199161. 0x0D, 0x1D, 0x2D, 0x3D, 0x4D, 0x5D, 0x6D, 0x7D,
  199162. 0x8D, 0x9D, 0xAD, 0xBD, 0xCD, 0xDD, 0xED, 0xFD,
  199163. 0x0E, 0x1E, 0x2E, 0x3E, 0x4E, 0x5E, 0x6E, 0x7E,
  199164. 0x8E, 0x9E, 0xAE, 0xBE, 0xCE, 0xDE, 0xEE, 0xFE,
  199165. 0x0F, 0x1F, 0x2F, 0x3F, 0x4F, 0x5F, 0x6F, 0x7F,
  199166. 0x8F, 0x9F, 0xAF, 0xBF, 0xCF, 0xDF, 0xEF, 0xFF
  199167. };
  199168. /* swaps pixel packing order within bytes */
  199169. void /* PRIVATE */
  199170. png_do_packswap(png_row_infop row_info, png_bytep row)
  199171. {
  199172. png_debug(1, "in png_do_packswap\n");
  199173. if (
  199174. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199175. row != NULL && row_info != NULL &&
  199176. #endif
  199177. row_info->bit_depth < 8)
  199178. {
  199179. png_bytep rp, end, table;
  199180. end = row + row_info->rowbytes;
  199181. if (row_info->bit_depth == 1)
  199182. table = (png_bytep)onebppswaptable;
  199183. else if (row_info->bit_depth == 2)
  199184. table = (png_bytep)twobppswaptable;
  199185. else if (row_info->bit_depth == 4)
  199186. table = (png_bytep)fourbppswaptable;
  199187. else
  199188. return;
  199189. for (rp = row; rp < end; rp++)
  199190. *rp = table[*rp];
  199191. }
  199192. }
  199193. #endif /* PNG_READ_PACKSWAP_SUPPORTED or PNG_WRITE_PACKSWAP_SUPPORTED */
  199194. #if defined(PNG_WRITE_FILLER_SUPPORTED) || \
  199195. defined(PNG_READ_STRIP_ALPHA_SUPPORTED)
  199196. /* remove filler or alpha byte(s) */
  199197. void /* PRIVATE */
  199198. png_do_strip_filler(png_row_infop row_info, png_bytep row, png_uint_32 flags)
  199199. {
  199200. png_debug(1, "in png_do_strip_filler\n");
  199201. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199202. if (row != NULL && row_info != NULL)
  199203. #endif
  199204. {
  199205. png_bytep sp=row;
  199206. png_bytep dp=row;
  199207. png_uint_32 row_width=row_info->width;
  199208. png_uint_32 i;
  199209. if ((row_info->color_type == PNG_COLOR_TYPE_RGB ||
  199210. (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA &&
  199211. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  199212. row_info->channels == 4)
  199213. {
  199214. if (row_info->bit_depth == 8)
  199215. {
  199216. /* This converts from RGBX or RGBA to RGB */
  199217. if (flags & PNG_FLAG_FILLER_AFTER)
  199218. {
  199219. dp+=3; sp+=4;
  199220. for (i = 1; i < row_width; i++)
  199221. {
  199222. *dp++ = *sp++;
  199223. *dp++ = *sp++;
  199224. *dp++ = *sp++;
  199225. sp++;
  199226. }
  199227. }
  199228. /* This converts from XRGB or ARGB to RGB */
  199229. else
  199230. {
  199231. for (i = 0; i < row_width; i++)
  199232. {
  199233. sp++;
  199234. *dp++ = *sp++;
  199235. *dp++ = *sp++;
  199236. *dp++ = *sp++;
  199237. }
  199238. }
  199239. row_info->pixel_depth = 24;
  199240. row_info->rowbytes = row_width * 3;
  199241. }
  199242. else /* if (row_info->bit_depth == 16) */
  199243. {
  199244. if (flags & PNG_FLAG_FILLER_AFTER)
  199245. {
  199246. /* This converts from RRGGBBXX or RRGGBBAA to RRGGBB */
  199247. sp += 8; dp += 6;
  199248. for (i = 1; i < row_width; i++)
  199249. {
  199250. /* This could be (although png_memcpy is probably slower):
  199251. png_memcpy(dp, sp, 6);
  199252. sp += 8;
  199253. dp += 6;
  199254. */
  199255. *dp++ = *sp++;
  199256. *dp++ = *sp++;
  199257. *dp++ = *sp++;
  199258. *dp++ = *sp++;
  199259. *dp++ = *sp++;
  199260. *dp++ = *sp++;
  199261. sp += 2;
  199262. }
  199263. }
  199264. else
  199265. {
  199266. /* This converts from XXRRGGBB or AARRGGBB to RRGGBB */
  199267. for (i = 0; i < row_width; i++)
  199268. {
  199269. /* This could be (although png_memcpy is probably slower):
  199270. png_memcpy(dp, sp, 6);
  199271. sp += 8;
  199272. dp += 6;
  199273. */
  199274. sp+=2;
  199275. *dp++ = *sp++;
  199276. *dp++ = *sp++;
  199277. *dp++ = *sp++;
  199278. *dp++ = *sp++;
  199279. *dp++ = *sp++;
  199280. *dp++ = *sp++;
  199281. }
  199282. }
  199283. row_info->pixel_depth = 48;
  199284. row_info->rowbytes = row_width * 6;
  199285. }
  199286. row_info->channels = 3;
  199287. }
  199288. else if ((row_info->color_type == PNG_COLOR_TYPE_GRAY ||
  199289. (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA &&
  199290. (flags & PNG_FLAG_STRIP_ALPHA))) &&
  199291. row_info->channels == 2)
  199292. {
  199293. if (row_info->bit_depth == 8)
  199294. {
  199295. /* This converts from GX or GA to G */
  199296. if (flags & PNG_FLAG_FILLER_AFTER)
  199297. {
  199298. for (i = 0; i < row_width; i++)
  199299. {
  199300. *dp++ = *sp++;
  199301. sp++;
  199302. }
  199303. }
  199304. /* This converts from XG or AG to G */
  199305. else
  199306. {
  199307. for (i = 0; i < row_width; i++)
  199308. {
  199309. sp++;
  199310. *dp++ = *sp++;
  199311. }
  199312. }
  199313. row_info->pixel_depth = 8;
  199314. row_info->rowbytes = row_width;
  199315. }
  199316. else /* if (row_info->bit_depth == 16) */
  199317. {
  199318. if (flags & PNG_FLAG_FILLER_AFTER)
  199319. {
  199320. /* This converts from GGXX or GGAA to GG */
  199321. sp += 4; dp += 2;
  199322. for (i = 1; i < row_width; i++)
  199323. {
  199324. *dp++ = *sp++;
  199325. *dp++ = *sp++;
  199326. sp += 2;
  199327. }
  199328. }
  199329. else
  199330. {
  199331. /* This converts from XXGG or AAGG to GG */
  199332. for (i = 0; i < row_width; i++)
  199333. {
  199334. sp += 2;
  199335. *dp++ = *sp++;
  199336. *dp++ = *sp++;
  199337. }
  199338. }
  199339. row_info->pixel_depth = 16;
  199340. row_info->rowbytes = row_width * 2;
  199341. }
  199342. row_info->channels = 1;
  199343. }
  199344. if (flags & PNG_FLAG_STRIP_ALPHA)
  199345. row_info->color_type &= ~PNG_COLOR_MASK_ALPHA;
  199346. }
  199347. }
  199348. #endif
  199349. #if defined(PNG_READ_BGR_SUPPORTED) || defined(PNG_WRITE_BGR_SUPPORTED)
  199350. /* swaps red and blue bytes within a pixel */
  199351. void /* PRIVATE */
  199352. png_do_bgr(png_row_infop row_info, png_bytep row)
  199353. {
  199354. png_debug(1, "in png_do_bgr\n");
  199355. if (
  199356. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  199357. row != NULL && row_info != NULL &&
  199358. #endif
  199359. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  199360. {
  199361. png_uint_32 row_width = row_info->width;
  199362. if (row_info->bit_depth == 8)
  199363. {
  199364. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  199365. {
  199366. png_bytep rp;
  199367. png_uint_32 i;
  199368. for (i = 0, rp = row; i < row_width; i++, rp += 3)
  199369. {
  199370. png_byte save = *rp;
  199371. *rp = *(rp + 2);
  199372. *(rp + 2) = save;
  199373. }
  199374. }
  199375. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199376. {
  199377. png_bytep rp;
  199378. png_uint_32 i;
  199379. for (i = 0, rp = row; i < row_width; i++, rp += 4)
  199380. {
  199381. png_byte save = *rp;
  199382. *rp = *(rp + 2);
  199383. *(rp + 2) = save;
  199384. }
  199385. }
  199386. }
  199387. else if (row_info->bit_depth == 16)
  199388. {
  199389. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  199390. {
  199391. png_bytep rp;
  199392. png_uint_32 i;
  199393. for (i = 0, rp = row; i < row_width; i++, rp += 6)
  199394. {
  199395. png_byte save = *rp;
  199396. *rp = *(rp + 4);
  199397. *(rp + 4) = save;
  199398. save = *(rp + 1);
  199399. *(rp + 1) = *(rp + 5);
  199400. *(rp + 5) = save;
  199401. }
  199402. }
  199403. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  199404. {
  199405. png_bytep rp;
  199406. png_uint_32 i;
  199407. for (i = 0, rp = row; i < row_width; i++, rp += 8)
  199408. {
  199409. png_byte save = *rp;
  199410. *rp = *(rp + 4);
  199411. *(rp + 4) = save;
  199412. save = *(rp + 1);
  199413. *(rp + 1) = *(rp + 5);
  199414. *(rp + 5) = save;
  199415. }
  199416. }
  199417. }
  199418. }
  199419. }
  199420. #endif /* PNG_READ_BGR_SUPPORTED or PNG_WRITE_BGR_SUPPORTED */
  199421. #if defined(PNG_READ_USER_TRANSFORM_SUPPORTED) || \
  199422. defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED) || \
  199423. defined(PNG_LEGACY_SUPPORTED)
  199424. void PNGAPI
  199425. png_set_user_transform_info(png_structp png_ptr, png_voidp
  199426. user_transform_ptr, int user_transform_depth, int user_transform_channels)
  199427. {
  199428. png_debug(1, "in png_set_user_transform_info\n");
  199429. if(png_ptr == NULL) return;
  199430. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  199431. png_ptr->user_transform_ptr = user_transform_ptr;
  199432. png_ptr->user_transform_depth = (png_byte)user_transform_depth;
  199433. png_ptr->user_transform_channels = (png_byte)user_transform_channels;
  199434. #else
  199435. if(user_transform_ptr || user_transform_depth || user_transform_channels)
  199436. png_warning(png_ptr,
  199437. "This version of libpng does not support user transform info");
  199438. #endif
  199439. }
  199440. #endif
  199441. /* This function returns a pointer to the user_transform_ptr associated with
  199442. * the user transform functions. The application should free any memory
  199443. * associated with this pointer before png_write_destroy and png_read_destroy
  199444. * are called.
  199445. */
  199446. png_voidp PNGAPI
  199447. png_get_user_transform_ptr(png_structp png_ptr)
  199448. {
  199449. #if defined(PNG_USER_TRANSFORM_PTR_SUPPORTED)
  199450. if (png_ptr == NULL) return (NULL);
  199451. return ((png_voidp)png_ptr->user_transform_ptr);
  199452. #else
  199453. return (NULL);
  199454. #endif
  199455. }
  199456. #endif /* PNG_READ_SUPPORTED || PNG_WRITE_SUPPORTED */
  199457. /********* End of inlined file: pngtrans.c *********/
  199458. /********* Start of inlined file: pngwio.c *********/
  199459. /* pngwio.c - functions for data output
  199460. *
  199461. * Last changed in libpng 1.2.13 November 13, 2006
  199462. * For conditions of distribution and use, see copyright notice in png.h
  199463. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  199464. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199465. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199466. *
  199467. * This file provides a location for all output. Users who need
  199468. * special handling are expected to write functions that have the same
  199469. * arguments as these and perform similar functions, but that possibly
  199470. * use different output methods. Note that you shouldn't change these
  199471. * functions, but rather write replacement functions and then change
  199472. * them at run time with png_set_write_fn(...).
  199473. */
  199474. #define PNG_INTERNAL
  199475. #ifdef PNG_WRITE_SUPPORTED
  199476. /* Write the data to whatever output you are using. The default routine
  199477. writes to a file pointer. Note that this routine sometimes gets called
  199478. with very small lengths, so you should implement some kind of simple
  199479. buffering if you are using unbuffered writes. This should never be asked
  199480. to write more than 64K on a 16 bit machine. */
  199481. void /* PRIVATE */
  199482. png_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  199483. {
  199484. if (png_ptr->write_data_fn != NULL )
  199485. (*(png_ptr->write_data_fn))(png_ptr, data, length);
  199486. else
  199487. png_error(png_ptr, "Call to NULL write function");
  199488. }
  199489. #if !defined(PNG_NO_STDIO)
  199490. /* This is the function that does the actual writing of data. If you are
  199491. not writing to a standard C stream, you should create a replacement
  199492. write_data function and use it at run time with png_set_write_fn(), rather
  199493. than changing the library. */
  199494. #ifndef USE_FAR_KEYWORD
  199495. void PNGAPI
  199496. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  199497. {
  199498. png_uint_32 check;
  199499. if(png_ptr == NULL) return;
  199500. #if defined(_WIN32_WCE)
  199501. if ( !WriteFile((HANDLE)(png_ptr->io_ptr), data, length, &check, NULL) )
  199502. check = 0;
  199503. #else
  199504. check = fwrite(data, 1, length, (png_FILE_p)(png_ptr->io_ptr));
  199505. #endif
  199506. if (check != length)
  199507. png_error(png_ptr, "Write Error");
  199508. }
  199509. #else
  199510. /* this is the model-independent version. Since the standard I/O library
  199511. can't handle far buffers in the medium and small models, we have to copy
  199512. the data.
  199513. */
  199514. #define NEAR_BUF_SIZE 1024
  199515. #define MIN(a,b) (a <= b ? a : b)
  199516. void PNGAPI
  199517. png_default_write_data(png_structp png_ptr, png_bytep data, png_size_t length)
  199518. {
  199519. png_uint_32 check;
  199520. png_byte *near_data; /* Needs to be "png_byte *" instead of "png_bytep" */
  199521. png_FILE_p io_ptr;
  199522. if(png_ptr == NULL) return;
  199523. /* Check if data really is near. If so, use usual code. */
  199524. near_data = (png_byte *)CVT_PTR_NOCHECK(data);
  199525. io_ptr = (png_FILE_p)CVT_PTR(png_ptr->io_ptr);
  199526. if ((png_bytep)near_data == data)
  199527. {
  199528. #if defined(_WIN32_WCE)
  199529. if ( !WriteFile(io_ptr, near_data, length, &check, NULL) )
  199530. check = 0;
  199531. #else
  199532. check = fwrite(near_data, 1, length, io_ptr);
  199533. #endif
  199534. }
  199535. else
  199536. {
  199537. png_byte buf[NEAR_BUF_SIZE];
  199538. png_size_t written, remaining, err;
  199539. check = 0;
  199540. remaining = length;
  199541. do
  199542. {
  199543. written = MIN(NEAR_BUF_SIZE, remaining);
  199544. png_memcpy(buf, data, written); /* copy far buffer to near buffer */
  199545. #if defined(_WIN32_WCE)
  199546. if ( !WriteFile(io_ptr, buf, written, &err, NULL) )
  199547. err = 0;
  199548. #else
  199549. err = fwrite(buf, 1, written, io_ptr);
  199550. #endif
  199551. if (err != written)
  199552. break;
  199553. else
  199554. check += err;
  199555. data += written;
  199556. remaining -= written;
  199557. }
  199558. while (remaining != 0);
  199559. }
  199560. if (check != length)
  199561. png_error(png_ptr, "Write Error");
  199562. }
  199563. #endif
  199564. #endif
  199565. /* This function is called to output any data pending writing (normally
  199566. to disk). After png_flush is called, there should be no data pending
  199567. writing in any buffers. */
  199568. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199569. void /* PRIVATE */
  199570. png_flush(png_structp png_ptr)
  199571. {
  199572. if (png_ptr->output_flush_fn != NULL)
  199573. (*(png_ptr->output_flush_fn))(png_ptr);
  199574. }
  199575. #if !defined(PNG_NO_STDIO)
  199576. void PNGAPI
  199577. png_default_flush(png_structp png_ptr)
  199578. {
  199579. #if !defined(_WIN32_WCE)
  199580. png_FILE_p io_ptr;
  199581. #endif
  199582. if(png_ptr == NULL) return;
  199583. #if !defined(_WIN32_WCE)
  199584. io_ptr = (png_FILE_p)CVT_PTR((png_ptr->io_ptr));
  199585. if (io_ptr != NULL)
  199586. fflush(io_ptr);
  199587. #endif
  199588. }
  199589. #endif
  199590. #endif
  199591. /* This function allows the application to supply new output functions for
  199592. libpng if standard C streams aren't being used.
  199593. This function takes as its arguments:
  199594. png_ptr - pointer to a png output data structure
  199595. io_ptr - pointer to user supplied structure containing info about
  199596. the output functions. May be NULL.
  199597. write_data_fn - pointer to a new output function that takes as its
  199598. arguments a pointer to a png_struct, a pointer to
  199599. data to be written, and a 32-bit unsigned int that is
  199600. the number of bytes to be written. The new write
  199601. function should call png_error(png_ptr, "Error msg")
  199602. to exit and output any fatal error messages.
  199603. flush_data_fn - pointer to a new flush function that takes as its
  199604. arguments a pointer to a png_struct. After a call to
  199605. the flush function, there should be no data in any buffers
  199606. or pending transmission. If the output method doesn't do
  199607. any buffering of ouput, a function prototype must still be
  199608. supplied although it doesn't have to do anything. If
  199609. PNG_WRITE_FLUSH_SUPPORTED is not defined at libpng compile
  199610. time, output_flush_fn will be ignored, although it must be
  199611. supplied for compatibility. */
  199612. void PNGAPI
  199613. png_set_write_fn(png_structp png_ptr, png_voidp io_ptr,
  199614. png_rw_ptr write_data_fn, png_flush_ptr output_flush_fn)
  199615. {
  199616. if(png_ptr == NULL) return;
  199617. png_ptr->io_ptr = io_ptr;
  199618. #if !defined(PNG_NO_STDIO)
  199619. if (write_data_fn != NULL)
  199620. png_ptr->write_data_fn = write_data_fn;
  199621. else
  199622. png_ptr->write_data_fn = png_default_write_data;
  199623. #else
  199624. png_ptr->write_data_fn = write_data_fn;
  199625. #endif
  199626. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  199627. #if !defined(PNG_NO_STDIO)
  199628. if (output_flush_fn != NULL)
  199629. png_ptr->output_flush_fn = output_flush_fn;
  199630. else
  199631. png_ptr->output_flush_fn = png_default_flush;
  199632. #else
  199633. png_ptr->output_flush_fn = output_flush_fn;
  199634. #endif
  199635. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  199636. /* It is an error to read while writing a png file */
  199637. if (png_ptr->read_data_fn != NULL)
  199638. {
  199639. png_ptr->read_data_fn = NULL;
  199640. png_warning(png_ptr,
  199641. "Attempted to set both read_data_fn and write_data_fn in");
  199642. png_warning(png_ptr,
  199643. "the same structure. Resetting read_data_fn to NULL.");
  199644. }
  199645. }
  199646. #if defined(USE_FAR_KEYWORD)
  199647. #if defined(_MSC_VER)
  199648. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  199649. {
  199650. void *near_ptr;
  199651. void FAR *far_ptr;
  199652. FP_OFF(near_ptr) = FP_OFF(ptr);
  199653. far_ptr = (void FAR *)near_ptr;
  199654. if(check != 0)
  199655. if(FP_SEG(ptr) != FP_SEG(far_ptr))
  199656. png_error(png_ptr,"segment lost in conversion");
  199657. return(near_ptr);
  199658. }
  199659. # else
  199660. void *png_far_to_near(png_structp png_ptr,png_voidp ptr, int check)
  199661. {
  199662. void *near_ptr;
  199663. void FAR *far_ptr;
  199664. near_ptr = (void FAR *)ptr;
  199665. far_ptr = (void FAR *)near_ptr;
  199666. if(check != 0)
  199667. if(far_ptr != ptr)
  199668. png_error(png_ptr,"segment lost in conversion");
  199669. return(near_ptr);
  199670. }
  199671. # endif
  199672. # endif
  199673. #endif /* PNG_WRITE_SUPPORTED */
  199674. /********* End of inlined file: pngwio.c *********/
  199675. /********* Start of inlined file: pngwrite.c *********/
  199676. /* pngwrite.c - general routines to write a PNG file
  199677. *
  199678. * Last changed in libpng 1.2.15 January 5, 2007
  199679. * For conditions of distribution and use, see copyright notice in png.h
  199680. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  199681. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  199682. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  199683. */
  199684. /* get internal access to png.h */
  199685. #define PNG_INTERNAL
  199686. #ifdef PNG_WRITE_SUPPORTED
  199687. /* Writes all the PNG information. This is the suggested way to use the
  199688. * library. If you have a new chunk to add, make a function to write it,
  199689. * and put it in the correct location here. If you want the chunk written
  199690. * after the image data, put it in png_write_end(). I strongly encourage
  199691. * you to supply a PNG_INFO_ flag, and check info_ptr->valid before writing
  199692. * the chunk, as that will keep the code from breaking if you want to just
  199693. * write a plain PNG file. If you have long comments, I suggest writing
  199694. * them in png_write_end(), and compressing them.
  199695. */
  199696. void PNGAPI
  199697. png_write_info_before_PLTE(png_structp png_ptr, png_infop info_ptr)
  199698. {
  199699. png_debug(1, "in png_write_info_before_PLTE\n");
  199700. if (png_ptr == NULL || info_ptr == NULL)
  199701. return;
  199702. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  199703. {
  199704. png_write_sig(png_ptr); /* write PNG signature */
  199705. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  199706. if((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE)&&(png_ptr->mng_features_permitted))
  199707. {
  199708. png_warning(png_ptr,"MNG features are not allowed in a PNG datastream");
  199709. png_ptr->mng_features_permitted=0;
  199710. }
  199711. #endif
  199712. /* write IHDR information. */
  199713. png_write_IHDR(png_ptr, info_ptr->width, info_ptr->height,
  199714. info_ptr->bit_depth, info_ptr->color_type, info_ptr->compression_type,
  199715. info_ptr->filter_type,
  199716. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  199717. info_ptr->interlace_type);
  199718. #else
  199719. 0);
  199720. #endif
  199721. /* the rest of these check to see if the valid field has the appropriate
  199722. flag set, and if it does, writes the chunk. */
  199723. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  199724. if (info_ptr->valid & PNG_INFO_gAMA)
  199725. {
  199726. # ifdef PNG_FLOATING_POINT_SUPPORTED
  199727. png_write_gAMA(png_ptr, info_ptr->gamma);
  199728. #else
  199729. #ifdef PNG_FIXED_POINT_SUPPORTED
  199730. png_write_gAMA_fixed(png_ptr, info_ptr->int_gamma);
  199731. # endif
  199732. #endif
  199733. }
  199734. #endif
  199735. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  199736. if (info_ptr->valid & PNG_INFO_sRGB)
  199737. png_write_sRGB(png_ptr, (int)info_ptr->srgb_intent);
  199738. #endif
  199739. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  199740. if (info_ptr->valid & PNG_INFO_iCCP)
  199741. png_write_iCCP(png_ptr, info_ptr->iccp_name, PNG_COMPRESSION_TYPE_BASE,
  199742. info_ptr->iccp_profile, (int)info_ptr->iccp_proflen);
  199743. #endif
  199744. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  199745. if (info_ptr->valid & PNG_INFO_sBIT)
  199746. png_write_sBIT(png_ptr, &(info_ptr->sig_bit), info_ptr->color_type);
  199747. #endif
  199748. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  199749. if (info_ptr->valid & PNG_INFO_cHRM)
  199750. {
  199751. #ifdef PNG_FLOATING_POINT_SUPPORTED
  199752. png_write_cHRM(png_ptr,
  199753. info_ptr->x_white, info_ptr->y_white,
  199754. info_ptr->x_red, info_ptr->y_red,
  199755. info_ptr->x_green, info_ptr->y_green,
  199756. info_ptr->x_blue, info_ptr->y_blue);
  199757. #else
  199758. # ifdef PNG_FIXED_POINT_SUPPORTED
  199759. png_write_cHRM_fixed(png_ptr,
  199760. info_ptr->int_x_white, info_ptr->int_y_white,
  199761. info_ptr->int_x_red, info_ptr->int_y_red,
  199762. info_ptr->int_x_green, info_ptr->int_y_green,
  199763. info_ptr->int_x_blue, info_ptr->int_y_blue);
  199764. # endif
  199765. #endif
  199766. }
  199767. #endif
  199768. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199769. if (info_ptr->unknown_chunks_num)
  199770. {
  199771. png_unknown_chunk *up;
  199772. png_debug(5, "writing extra chunks\n");
  199773. for (up = info_ptr->unknown_chunks;
  199774. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199775. up++)
  199776. {
  199777. int keep=png_handle_as_unknown(png_ptr, up->name);
  199778. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199779. up->location && !(up->location & PNG_HAVE_PLTE) &&
  199780. !(up->location & PNG_HAVE_IDAT) &&
  199781. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199782. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199783. {
  199784. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199785. }
  199786. }
  199787. }
  199788. #endif
  199789. png_ptr->mode |= PNG_WROTE_INFO_BEFORE_PLTE;
  199790. }
  199791. }
  199792. void PNGAPI
  199793. png_write_info(png_structp png_ptr, png_infop info_ptr)
  199794. {
  199795. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  199796. int i;
  199797. #endif
  199798. png_debug(1, "in png_write_info\n");
  199799. if (png_ptr == NULL || info_ptr == NULL)
  199800. return;
  199801. png_write_info_before_PLTE(png_ptr, info_ptr);
  199802. if (info_ptr->valid & PNG_INFO_PLTE)
  199803. png_write_PLTE(png_ptr, info_ptr->palette,
  199804. (png_uint_32)info_ptr->num_palette);
  199805. else if (info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199806. png_error(png_ptr, "Valid palette required for paletted images");
  199807. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  199808. if (info_ptr->valid & PNG_INFO_tRNS)
  199809. {
  199810. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  199811. /* invert the alpha channel (in tRNS) */
  199812. if ((png_ptr->transformations & PNG_INVERT_ALPHA) &&
  199813. info_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  199814. {
  199815. int j;
  199816. for (j=0; j<(int)info_ptr->num_trans; j++)
  199817. info_ptr->trans[j] = (png_byte)(255 - info_ptr->trans[j]);
  199818. }
  199819. #endif
  199820. png_write_tRNS(png_ptr, info_ptr->trans, &(info_ptr->trans_values),
  199821. info_ptr->num_trans, info_ptr->color_type);
  199822. }
  199823. #endif
  199824. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  199825. if (info_ptr->valid & PNG_INFO_bKGD)
  199826. png_write_bKGD(png_ptr, &(info_ptr->background), info_ptr->color_type);
  199827. #endif
  199828. #if defined(PNG_WRITE_hIST_SUPPORTED)
  199829. if (info_ptr->valid & PNG_INFO_hIST)
  199830. png_write_hIST(png_ptr, info_ptr->hist, info_ptr->num_palette);
  199831. #endif
  199832. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  199833. if (info_ptr->valid & PNG_INFO_oFFs)
  199834. png_write_oFFs(png_ptr, info_ptr->x_offset, info_ptr->y_offset,
  199835. info_ptr->offset_unit_type);
  199836. #endif
  199837. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  199838. if (info_ptr->valid & PNG_INFO_pCAL)
  199839. png_write_pCAL(png_ptr, info_ptr->pcal_purpose, info_ptr->pcal_X0,
  199840. info_ptr->pcal_X1, info_ptr->pcal_type, info_ptr->pcal_nparams,
  199841. info_ptr->pcal_units, info_ptr->pcal_params);
  199842. #endif
  199843. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  199844. if (info_ptr->valid & PNG_INFO_sCAL)
  199845. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  199846. png_write_sCAL(png_ptr, (int)info_ptr->scal_unit,
  199847. info_ptr->scal_pixel_width, info_ptr->scal_pixel_height);
  199848. #else
  199849. #ifdef PNG_FIXED_POINT_SUPPORTED
  199850. png_write_sCAL_s(png_ptr, (int)info_ptr->scal_unit,
  199851. info_ptr->scal_s_width, info_ptr->scal_s_height);
  199852. #else
  199853. png_warning(png_ptr,
  199854. "png_write_sCAL not supported; sCAL chunk not written.");
  199855. #endif
  199856. #endif
  199857. #endif
  199858. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  199859. if (info_ptr->valid & PNG_INFO_pHYs)
  199860. png_write_pHYs(png_ptr, info_ptr->x_pixels_per_unit,
  199861. info_ptr->y_pixels_per_unit, info_ptr->phys_unit_type);
  199862. #endif
  199863. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199864. if (info_ptr->valid & PNG_INFO_tIME)
  199865. {
  199866. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199867. png_ptr->mode |= PNG_WROTE_tIME;
  199868. }
  199869. #endif
  199870. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  199871. if (info_ptr->valid & PNG_INFO_sPLT)
  199872. for (i = 0; i < (int)info_ptr->splt_palettes_num; i++)
  199873. png_write_sPLT(png_ptr, info_ptr->splt_palettes + i);
  199874. #endif
  199875. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199876. /* Check to see if we need to write text chunks */
  199877. for (i = 0; i < info_ptr->num_text; i++)
  199878. {
  199879. png_debug2(2, "Writing header text chunk %d, type %d\n", i,
  199880. info_ptr->text[i].compression);
  199881. /* an internationalized chunk? */
  199882. if (info_ptr->text[i].compression > 0)
  199883. {
  199884. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199885. /* write international chunk */
  199886. png_write_iTXt(png_ptr,
  199887. info_ptr->text[i].compression,
  199888. info_ptr->text[i].key,
  199889. info_ptr->text[i].lang,
  199890. info_ptr->text[i].lang_key,
  199891. info_ptr->text[i].text);
  199892. #else
  199893. png_warning(png_ptr, "Unable to write international text");
  199894. #endif
  199895. /* Mark this chunk as written */
  199896. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199897. }
  199898. /* If we want a compressed text chunk */
  199899. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_zTXt)
  199900. {
  199901. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  199902. /* write compressed chunk */
  199903. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  199904. info_ptr->text[i].text, 0,
  199905. info_ptr->text[i].compression);
  199906. #else
  199907. png_warning(png_ptr, "Unable to write compressed text");
  199908. #endif
  199909. /* Mark this chunk as written */
  199910. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  199911. }
  199912. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  199913. {
  199914. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  199915. /* write uncompressed chunk */
  199916. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  199917. info_ptr->text[i].text,
  199918. 0);
  199919. #else
  199920. png_warning(png_ptr, "Unable to write uncompressed text");
  199921. #endif
  199922. /* Mark this chunk as written */
  199923. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199924. }
  199925. }
  199926. #endif
  199927. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  199928. if (info_ptr->unknown_chunks_num)
  199929. {
  199930. png_unknown_chunk *up;
  199931. png_debug(5, "writing extra chunks\n");
  199932. for (up = info_ptr->unknown_chunks;
  199933. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  199934. up++)
  199935. {
  199936. int keep=png_handle_as_unknown(png_ptr, up->name);
  199937. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  199938. up->location && (up->location & PNG_HAVE_PLTE) &&
  199939. !(up->location & PNG_HAVE_IDAT) &&
  199940. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  199941. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  199942. {
  199943. png_write_chunk(png_ptr, up->name, up->data, up->size);
  199944. }
  199945. }
  199946. }
  199947. #endif
  199948. }
  199949. /* Writes the end of the PNG file. If you don't want to write comments or
  199950. * time information, you can pass NULL for info. If you already wrote these
  199951. * in png_write_info(), do not write them again here. If you have long
  199952. * comments, I suggest writing them here, and compressing them.
  199953. */
  199954. void PNGAPI
  199955. png_write_end(png_structp png_ptr, png_infop info_ptr)
  199956. {
  199957. png_debug(1, "in png_write_end\n");
  199958. if (png_ptr == NULL)
  199959. return;
  199960. if (!(png_ptr->mode & PNG_HAVE_IDAT))
  199961. png_error(png_ptr, "No IDATs written into file");
  199962. /* see if user wants us to write information chunks */
  199963. if (info_ptr != NULL)
  199964. {
  199965. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199966. int i; /* local index variable */
  199967. #endif
  199968. #if defined(PNG_WRITE_tIME_SUPPORTED)
  199969. /* check to see if user has supplied a time chunk */
  199970. if ((info_ptr->valid & PNG_INFO_tIME) &&
  199971. !(png_ptr->mode & PNG_WROTE_tIME))
  199972. png_write_tIME(png_ptr, &(info_ptr->mod_time));
  199973. #endif
  199974. #if defined(PNG_WRITE_TEXT_SUPPORTED)
  199975. /* loop through comment chunks */
  199976. for (i = 0; i < info_ptr->num_text; i++)
  199977. {
  199978. png_debug2(2, "Writing trailer text chunk %d, type %d\n", i,
  199979. info_ptr->text[i].compression);
  199980. /* an internationalized chunk? */
  199981. if (info_ptr->text[i].compression > 0)
  199982. {
  199983. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  199984. /* write international chunk */
  199985. png_write_iTXt(png_ptr,
  199986. info_ptr->text[i].compression,
  199987. info_ptr->text[i].key,
  199988. info_ptr->text[i].lang,
  199989. info_ptr->text[i].lang_key,
  199990. info_ptr->text[i].text);
  199991. #else
  199992. png_warning(png_ptr, "Unable to write international text");
  199993. #endif
  199994. /* Mark this chunk as written */
  199995. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  199996. }
  199997. else if (info_ptr->text[i].compression >= PNG_TEXT_COMPRESSION_zTXt)
  199998. {
  199999. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  200000. /* write compressed chunk */
  200001. png_write_zTXt(png_ptr, info_ptr->text[i].key,
  200002. info_ptr->text[i].text, 0,
  200003. info_ptr->text[i].compression);
  200004. #else
  200005. png_warning(png_ptr, "Unable to write compressed text");
  200006. #endif
  200007. /* Mark this chunk as written */
  200008. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_zTXt_WR;
  200009. }
  200010. else if (info_ptr->text[i].compression == PNG_TEXT_COMPRESSION_NONE)
  200011. {
  200012. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  200013. /* write uncompressed chunk */
  200014. png_write_tEXt(png_ptr, info_ptr->text[i].key,
  200015. info_ptr->text[i].text, 0);
  200016. #else
  200017. png_warning(png_ptr, "Unable to write uncompressed text");
  200018. #endif
  200019. /* Mark this chunk as written */
  200020. info_ptr->text[i].compression = PNG_TEXT_COMPRESSION_NONE_WR;
  200021. }
  200022. }
  200023. #endif
  200024. #if defined(PNG_WRITE_UNKNOWN_CHUNKS_SUPPORTED)
  200025. if (info_ptr->unknown_chunks_num)
  200026. {
  200027. png_unknown_chunk *up;
  200028. png_debug(5, "writing extra chunks\n");
  200029. for (up = info_ptr->unknown_chunks;
  200030. up < info_ptr->unknown_chunks + info_ptr->unknown_chunks_num;
  200031. up++)
  200032. {
  200033. int keep=png_handle_as_unknown(png_ptr, up->name);
  200034. if (keep != PNG_HANDLE_CHUNK_NEVER &&
  200035. up->location && (up->location & PNG_AFTER_IDAT) &&
  200036. ((up->name[3] & 0x20) || keep == PNG_HANDLE_CHUNK_ALWAYS ||
  200037. (png_ptr->flags & PNG_FLAG_KEEP_UNSAFE_CHUNKS)))
  200038. {
  200039. png_write_chunk(png_ptr, up->name, up->data, up->size);
  200040. }
  200041. }
  200042. }
  200043. #endif
  200044. }
  200045. png_ptr->mode |= PNG_AFTER_IDAT;
  200046. /* write end of PNG file */
  200047. png_write_IEND(png_ptr);
  200048. }
  200049. #if defined(PNG_WRITE_tIME_SUPPORTED)
  200050. #if !defined(_WIN32_WCE)
  200051. /* "time.h" functions are not supported on WindowsCE */
  200052. void PNGAPI
  200053. png_convert_from_struct_tm(png_timep ptime, struct tm FAR * ttime)
  200054. {
  200055. png_debug(1, "in png_convert_from_struct_tm\n");
  200056. ptime->year = (png_uint_16)(1900 + ttime->tm_year);
  200057. ptime->month = (png_byte)(ttime->tm_mon + 1);
  200058. ptime->day = (png_byte)ttime->tm_mday;
  200059. ptime->hour = (png_byte)ttime->tm_hour;
  200060. ptime->minute = (png_byte)ttime->tm_min;
  200061. ptime->second = (png_byte)ttime->tm_sec;
  200062. }
  200063. void PNGAPI
  200064. png_convert_from_time_t(png_timep ptime, time_t ttime)
  200065. {
  200066. struct tm *tbuf;
  200067. png_debug(1, "in png_convert_from_time_t\n");
  200068. tbuf = gmtime(&ttime);
  200069. png_convert_from_struct_tm(ptime, tbuf);
  200070. }
  200071. #endif
  200072. #endif
  200073. /* Initialize png_ptr structure, and allocate any memory needed */
  200074. png_structp PNGAPI
  200075. png_create_write_struct(png_const_charp user_png_ver, png_voidp error_ptr,
  200076. png_error_ptr error_fn, png_error_ptr warn_fn)
  200077. {
  200078. #ifdef PNG_USER_MEM_SUPPORTED
  200079. return (png_create_write_struct_2(user_png_ver, error_ptr, error_fn,
  200080. warn_fn, png_voidp_NULL, png_malloc_ptr_NULL, png_free_ptr_NULL));
  200081. }
  200082. /* Alternate initialize png_ptr structure, and allocate any memory needed */
  200083. png_structp PNGAPI
  200084. png_create_write_struct_2(png_const_charp user_png_ver, png_voidp error_ptr,
  200085. png_error_ptr error_fn, png_error_ptr warn_fn, png_voidp mem_ptr,
  200086. png_malloc_ptr malloc_fn, png_free_ptr free_fn)
  200087. {
  200088. #endif /* PNG_USER_MEM_SUPPORTED */
  200089. png_structp png_ptr;
  200090. #ifdef PNG_SETJMP_SUPPORTED
  200091. #ifdef USE_FAR_KEYWORD
  200092. jmp_buf jmpbuf;
  200093. #endif
  200094. #endif
  200095. int i;
  200096. png_debug(1, "in png_create_write_struct\n");
  200097. #ifdef PNG_USER_MEM_SUPPORTED
  200098. png_ptr = (png_structp)png_create_struct_2(PNG_STRUCT_PNG,
  200099. (png_malloc_ptr)malloc_fn, (png_voidp)mem_ptr);
  200100. #else
  200101. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  200102. #endif /* PNG_USER_MEM_SUPPORTED */
  200103. if (png_ptr == NULL)
  200104. return (NULL);
  200105. /* added at libpng-1.2.6 */
  200106. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  200107. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  200108. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  200109. #endif
  200110. #ifdef PNG_SETJMP_SUPPORTED
  200111. #ifdef USE_FAR_KEYWORD
  200112. if (setjmp(jmpbuf))
  200113. #else
  200114. if (setjmp(png_ptr->jmpbuf))
  200115. #endif
  200116. {
  200117. png_free(png_ptr, png_ptr->zbuf);
  200118. png_ptr->zbuf=NULL;
  200119. png_destroy_struct(png_ptr);
  200120. return (NULL);
  200121. }
  200122. #ifdef USE_FAR_KEYWORD
  200123. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  200124. #endif
  200125. #endif
  200126. #ifdef PNG_USER_MEM_SUPPORTED
  200127. png_set_mem_fn(png_ptr, mem_ptr, malloc_fn, free_fn);
  200128. #endif /* PNG_USER_MEM_SUPPORTED */
  200129. png_set_error_fn(png_ptr, error_ptr, error_fn, warn_fn);
  200130. i=0;
  200131. do
  200132. {
  200133. if(user_png_ver[i] != png_libpng_ver[i])
  200134. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  200135. } while (png_libpng_ver[i++]);
  200136. if (png_ptr->flags & PNG_FLAG_LIBRARY_MISMATCH)
  200137. {
  200138. /* Libpng 0.90 and later are binary incompatible with libpng 0.89, so
  200139. * we must recompile any applications that use any older library version.
  200140. * For versions after libpng 1.0, we will be compatible, so we need
  200141. * only check the first digit.
  200142. */
  200143. if (user_png_ver == NULL || user_png_ver[0] != png_libpng_ver[0] ||
  200144. (user_png_ver[0] == '1' && user_png_ver[2] != png_libpng_ver[2]) ||
  200145. (user_png_ver[0] == '0' && user_png_ver[2] < '9'))
  200146. {
  200147. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200148. char msg[80];
  200149. if (user_png_ver)
  200150. {
  200151. png_snprintf(msg, 80,
  200152. "Application was compiled with png.h from libpng-%.20s",
  200153. user_png_ver);
  200154. png_warning(png_ptr, msg);
  200155. }
  200156. png_snprintf(msg, 80,
  200157. "Application is running with png.c from libpng-%.20s",
  200158. png_libpng_ver);
  200159. png_warning(png_ptr, msg);
  200160. #endif
  200161. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  200162. png_ptr->flags=0;
  200163. #endif
  200164. png_error(png_ptr,
  200165. "Incompatible libpng version in application and library");
  200166. }
  200167. }
  200168. /* initialize zbuf - compression buffer */
  200169. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  200170. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  200171. (png_uint_32)png_ptr->zbuf_size);
  200172. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  200173. png_flush_ptr_NULL);
  200174. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  200175. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  200176. 1, png_doublep_NULL, png_doublep_NULL);
  200177. #endif
  200178. #ifdef PNG_SETJMP_SUPPORTED
  200179. /* Applications that neglect to set up their own setjmp() and then encounter
  200180. a png_error() will longjmp here. Since the jmpbuf is then meaningless we
  200181. abort instead of returning. */
  200182. #ifdef USE_FAR_KEYWORD
  200183. if (setjmp(jmpbuf))
  200184. PNG_ABORT();
  200185. png_memcpy(png_ptr->jmpbuf,jmpbuf,png_sizeof(jmp_buf));
  200186. #else
  200187. if (setjmp(png_ptr->jmpbuf))
  200188. PNG_ABORT();
  200189. #endif
  200190. #endif
  200191. return (png_ptr);
  200192. }
  200193. /* Initialize png_ptr structure, and allocate any memory needed */
  200194. #if defined(PNG_1_0_X) || defined(PNG_1_2_X)
  200195. /* Deprecated. */
  200196. #undef png_write_init
  200197. void PNGAPI
  200198. png_write_init(png_structp png_ptr)
  200199. {
  200200. /* We only come here via pre-1.0.7-compiled applications */
  200201. png_write_init_2(png_ptr, "1.0.6 or earlier", 0, 0);
  200202. }
  200203. void PNGAPI
  200204. png_write_init_2(png_structp png_ptr, png_const_charp user_png_ver,
  200205. png_size_t png_struct_size, png_size_t png_info_size)
  200206. {
  200207. /* We only come here via pre-1.0.12-compiled applications */
  200208. if(png_ptr == NULL) return;
  200209. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  200210. if(png_sizeof(png_struct) > png_struct_size ||
  200211. png_sizeof(png_info) > png_info_size)
  200212. {
  200213. char msg[80];
  200214. png_ptr->warning_fn=NULL;
  200215. if (user_png_ver)
  200216. {
  200217. png_snprintf(msg, 80,
  200218. "Application was compiled with png.h from libpng-%.20s",
  200219. user_png_ver);
  200220. png_warning(png_ptr, msg);
  200221. }
  200222. png_snprintf(msg, 80,
  200223. "Application is running with png.c from libpng-%.20s",
  200224. png_libpng_ver);
  200225. png_warning(png_ptr, msg);
  200226. }
  200227. #endif
  200228. if(png_sizeof(png_struct) > png_struct_size)
  200229. {
  200230. png_ptr->error_fn=NULL;
  200231. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  200232. png_ptr->flags=0;
  200233. #endif
  200234. png_error(png_ptr,
  200235. "The png struct allocated by the application for writing is too small.");
  200236. }
  200237. if(png_sizeof(png_info) > png_info_size)
  200238. {
  200239. png_ptr->error_fn=NULL;
  200240. #ifdef PNG_ERROR_NUMBERS_SUPPORTED
  200241. png_ptr->flags=0;
  200242. #endif
  200243. png_error(png_ptr,
  200244. "The info struct allocated by the application for writing is too small.");
  200245. }
  200246. png_write_init_3(&png_ptr, user_png_ver, png_struct_size);
  200247. }
  200248. #endif /* PNG_1_0_X || PNG_1_2_X */
  200249. void PNGAPI
  200250. png_write_init_3(png_structpp ptr_ptr, png_const_charp user_png_ver,
  200251. png_size_t png_struct_size)
  200252. {
  200253. png_structp png_ptr=*ptr_ptr;
  200254. #ifdef PNG_SETJMP_SUPPORTED
  200255. jmp_buf tmp_jmp; /* to save current jump buffer */
  200256. #endif
  200257. int i = 0;
  200258. if (png_ptr == NULL)
  200259. return;
  200260. do
  200261. {
  200262. if (user_png_ver[i] != png_libpng_ver[i])
  200263. {
  200264. #ifdef PNG_LEGACY_SUPPORTED
  200265. png_ptr->flags |= PNG_FLAG_LIBRARY_MISMATCH;
  200266. #else
  200267. png_ptr->warning_fn=NULL;
  200268. png_warning(png_ptr,
  200269. "Application uses deprecated png_write_init() and should be recompiled.");
  200270. break;
  200271. #endif
  200272. }
  200273. } while (png_libpng_ver[i++]);
  200274. png_debug(1, "in png_write_init_3\n");
  200275. #ifdef PNG_SETJMP_SUPPORTED
  200276. /* save jump buffer and error functions */
  200277. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  200278. #endif
  200279. if (png_sizeof(png_struct) > png_struct_size)
  200280. {
  200281. png_destroy_struct(png_ptr);
  200282. png_ptr = (png_structp)png_create_struct(PNG_STRUCT_PNG);
  200283. *ptr_ptr = png_ptr;
  200284. }
  200285. /* reset all variables to 0 */
  200286. png_memset(png_ptr, 0, png_sizeof (png_struct));
  200287. /* added at libpng-1.2.6 */
  200288. #ifdef PNG_SET_USER_LIMITS_SUPPORTED
  200289. png_ptr->user_width_max=PNG_USER_WIDTH_MAX;
  200290. png_ptr->user_height_max=PNG_USER_HEIGHT_MAX;
  200291. #endif
  200292. #ifdef PNG_SETJMP_SUPPORTED
  200293. /* restore jump buffer */
  200294. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  200295. #endif
  200296. png_set_write_fn(png_ptr, png_voidp_NULL, png_rw_ptr_NULL,
  200297. png_flush_ptr_NULL);
  200298. /* initialize zbuf - compression buffer */
  200299. png_ptr->zbuf_size = PNG_ZBUF_SIZE;
  200300. png_ptr->zbuf = (png_bytep)png_malloc(png_ptr,
  200301. (png_uint_32)png_ptr->zbuf_size);
  200302. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  200303. png_set_filter_heuristics(png_ptr, PNG_FILTER_HEURISTIC_DEFAULT,
  200304. 1, png_doublep_NULL, png_doublep_NULL);
  200305. #endif
  200306. }
  200307. /* Write a few rows of image data. If the image is interlaced,
  200308. * either you will have to write the 7 sub images, or, if you
  200309. * have called png_set_interlace_handling(), you will have to
  200310. * "write" the image seven times.
  200311. */
  200312. void PNGAPI
  200313. png_write_rows(png_structp png_ptr, png_bytepp row,
  200314. png_uint_32 num_rows)
  200315. {
  200316. png_uint_32 i; /* row counter */
  200317. png_bytepp rp; /* row pointer */
  200318. png_debug(1, "in png_write_rows\n");
  200319. if (png_ptr == NULL)
  200320. return;
  200321. /* loop through the rows */
  200322. for (i = 0, rp = row; i < num_rows; i++, rp++)
  200323. {
  200324. png_write_row(png_ptr, *rp);
  200325. }
  200326. }
  200327. /* Write the image. You only need to call this function once, even
  200328. * if you are writing an interlaced image.
  200329. */
  200330. void PNGAPI
  200331. png_write_image(png_structp png_ptr, png_bytepp image)
  200332. {
  200333. png_uint_32 i; /* row index */
  200334. int pass, num_pass; /* pass variables */
  200335. png_bytepp rp; /* points to current row */
  200336. if (png_ptr == NULL)
  200337. return;
  200338. png_debug(1, "in png_write_image\n");
  200339. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  200340. /* intialize interlace handling. If image is not interlaced,
  200341. this will set pass to 1 */
  200342. num_pass = png_set_interlace_handling(png_ptr);
  200343. #else
  200344. num_pass = 1;
  200345. #endif
  200346. /* loop through passes */
  200347. for (pass = 0; pass < num_pass; pass++)
  200348. {
  200349. /* loop through image */
  200350. for (i = 0, rp = image; i < png_ptr->height; i++, rp++)
  200351. {
  200352. png_write_row(png_ptr, *rp);
  200353. }
  200354. }
  200355. }
  200356. /* called by user to write a row of image data */
  200357. void PNGAPI
  200358. png_write_row(png_structp png_ptr, png_bytep row)
  200359. {
  200360. if (png_ptr == NULL)
  200361. return;
  200362. png_debug2(1, "in png_write_row (row %ld, pass %d)\n",
  200363. png_ptr->row_number, png_ptr->pass);
  200364. /* initialize transformations and other stuff if first time */
  200365. if (png_ptr->row_number == 0 && png_ptr->pass == 0)
  200366. {
  200367. /* make sure we wrote the header info */
  200368. if (!(png_ptr->mode & PNG_WROTE_INFO_BEFORE_PLTE))
  200369. png_error(png_ptr,
  200370. "png_write_info was never called before png_write_row.");
  200371. /* check for transforms that have been set but were defined out */
  200372. #if !defined(PNG_WRITE_INVERT_SUPPORTED) && defined(PNG_READ_INVERT_SUPPORTED)
  200373. if (png_ptr->transformations & PNG_INVERT_MONO)
  200374. png_warning(png_ptr, "PNG_WRITE_INVERT_SUPPORTED is not defined.");
  200375. #endif
  200376. #if !defined(PNG_WRITE_FILLER_SUPPORTED) && defined(PNG_READ_FILLER_SUPPORTED)
  200377. if (png_ptr->transformations & PNG_FILLER)
  200378. png_warning(png_ptr, "PNG_WRITE_FILLER_SUPPORTED is not defined.");
  200379. #endif
  200380. #if !defined(PNG_WRITE_PACKSWAP_SUPPORTED) && defined(PNG_READ_PACKSWAP_SUPPORTED)
  200381. if (png_ptr->transformations & PNG_PACKSWAP)
  200382. png_warning(png_ptr, "PNG_WRITE_PACKSWAP_SUPPORTED is not defined.");
  200383. #endif
  200384. #if !defined(PNG_WRITE_PACK_SUPPORTED) && defined(PNG_READ_PACK_SUPPORTED)
  200385. if (png_ptr->transformations & PNG_PACK)
  200386. png_warning(png_ptr, "PNG_WRITE_PACK_SUPPORTED is not defined.");
  200387. #endif
  200388. #if !defined(PNG_WRITE_SHIFT_SUPPORTED) && defined(PNG_READ_SHIFT_SUPPORTED)
  200389. if (png_ptr->transformations & PNG_SHIFT)
  200390. png_warning(png_ptr, "PNG_WRITE_SHIFT_SUPPORTED is not defined.");
  200391. #endif
  200392. #if !defined(PNG_WRITE_BGR_SUPPORTED) && defined(PNG_READ_BGR_SUPPORTED)
  200393. if (png_ptr->transformations & PNG_BGR)
  200394. png_warning(png_ptr, "PNG_WRITE_BGR_SUPPORTED is not defined.");
  200395. #endif
  200396. #if !defined(PNG_WRITE_SWAP_SUPPORTED) && defined(PNG_READ_SWAP_SUPPORTED)
  200397. if (png_ptr->transformations & PNG_SWAP_BYTES)
  200398. png_warning(png_ptr, "PNG_WRITE_SWAP_SUPPORTED is not defined.");
  200399. #endif
  200400. png_write_start_row(png_ptr);
  200401. }
  200402. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  200403. /* if interlaced and not interested in row, return */
  200404. if (png_ptr->interlaced && (png_ptr->transformations & PNG_INTERLACE))
  200405. {
  200406. switch (png_ptr->pass)
  200407. {
  200408. case 0:
  200409. if (png_ptr->row_number & 0x07)
  200410. {
  200411. png_write_finish_row(png_ptr);
  200412. return;
  200413. }
  200414. break;
  200415. case 1:
  200416. if ((png_ptr->row_number & 0x07) || png_ptr->width < 5)
  200417. {
  200418. png_write_finish_row(png_ptr);
  200419. return;
  200420. }
  200421. break;
  200422. case 2:
  200423. if ((png_ptr->row_number & 0x07) != 4)
  200424. {
  200425. png_write_finish_row(png_ptr);
  200426. return;
  200427. }
  200428. break;
  200429. case 3:
  200430. if ((png_ptr->row_number & 0x03) || png_ptr->width < 3)
  200431. {
  200432. png_write_finish_row(png_ptr);
  200433. return;
  200434. }
  200435. break;
  200436. case 4:
  200437. if ((png_ptr->row_number & 0x03) != 2)
  200438. {
  200439. png_write_finish_row(png_ptr);
  200440. return;
  200441. }
  200442. break;
  200443. case 5:
  200444. if ((png_ptr->row_number & 0x01) || png_ptr->width < 2)
  200445. {
  200446. png_write_finish_row(png_ptr);
  200447. return;
  200448. }
  200449. break;
  200450. case 6:
  200451. if (!(png_ptr->row_number & 0x01))
  200452. {
  200453. png_write_finish_row(png_ptr);
  200454. return;
  200455. }
  200456. break;
  200457. }
  200458. }
  200459. #endif
  200460. /* set up row info for transformations */
  200461. png_ptr->row_info.color_type = png_ptr->color_type;
  200462. png_ptr->row_info.width = png_ptr->usr_width;
  200463. png_ptr->row_info.channels = png_ptr->usr_channels;
  200464. png_ptr->row_info.bit_depth = png_ptr->usr_bit_depth;
  200465. png_ptr->row_info.pixel_depth = (png_byte)(png_ptr->row_info.bit_depth *
  200466. png_ptr->row_info.channels);
  200467. png_ptr->row_info.rowbytes = PNG_ROWBYTES(png_ptr->row_info.pixel_depth,
  200468. png_ptr->row_info.width);
  200469. png_debug1(3, "row_info->color_type = %d\n", png_ptr->row_info.color_type);
  200470. png_debug1(3, "row_info->width = %lu\n", png_ptr->row_info.width);
  200471. png_debug1(3, "row_info->channels = %d\n", png_ptr->row_info.channels);
  200472. png_debug1(3, "row_info->bit_depth = %d\n", png_ptr->row_info.bit_depth);
  200473. png_debug1(3, "row_info->pixel_depth = %d\n", png_ptr->row_info.pixel_depth);
  200474. png_debug1(3, "row_info->rowbytes = %lu\n", png_ptr->row_info.rowbytes);
  200475. /* Copy user's row into buffer, leaving room for filter byte. */
  200476. png_memcpy_check(png_ptr, png_ptr->row_buf + 1, row,
  200477. png_ptr->row_info.rowbytes);
  200478. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  200479. /* handle interlacing */
  200480. if (png_ptr->interlaced && png_ptr->pass < 6 &&
  200481. (png_ptr->transformations & PNG_INTERLACE))
  200482. {
  200483. png_do_write_interlace(&(png_ptr->row_info),
  200484. png_ptr->row_buf + 1, png_ptr->pass);
  200485. /* this should always get caught above, but still ... */
  200486. if (!(png_ptr->row_info.width))
  200487. {
  200488. png_write_finish_row(png_ptr);
  200489. return;
  200490. }
  200491. }
  200492. #endif
  200493. /* handle other transformations */
  200494. if (png_ptr->transformations)
  200495. png_do_write_transformations(png_ptr);
  200496. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200497. /* Write filter_method 64 (intrapixel differencing) only if
  200498. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  200499. * 2. Libpng did not write a PNG signature (this filter_method is only
  200500. * used in PNG datastreams that are embedded in MNG datastreams) and
  200501. * 3. The application called png_permit_mng_features with a mask that
  200502. * included PNG_FLAG_MNG_FILTER_64 and
  200503. * 4. The filter_method is 64 and
  200504. * 5. The color_type is RGB or RGBA
  200505. */
  200506. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200507. (png_ptr->filter_type == PNG_INTRAPIXEL_DIFFERENCING))
  200508. {
  200509. /* Intrapixel differencing */
  200510. png_do_write_intrapixel(&(png_ptr->row_info), png_ptr->row_buf + 1);
  200511. }
  200512. #endif
  200513. /* Find a filter if necessary, filter the row and write it out. */
  200514. png_write_find_filter(png_ptr, &(png_ptr->row_info));
  200515. if (png_ptr->write_row_fn != NULL)
  200516. (*(png_ptr->write_row_fn))(png_ptr, png_ptr->row_number, png_ptr->pass);
  200517. }
  200518. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  200519. /* Set the automatic flush interval or 0 to turn flushing off */
  200520. void PNGAPI
  200521. png_set_flush(png_structp png_ptr, int nrows)
  200522. {
  200523. png_debug(1, "in png_set_flush\n");
  200524. if (png_ptr == NULL)
  200525. return;
  200526. png_ptr->flush_dist = (nrows < 0 ? 0 : nrows);
  200527. }
  200528. /* flush the current output buffers now */
  200529. void PNGAPI
  200530. png_write_flush(png_structp png_ptr)
  200531. {
  200532. int wrote_IDAT;
  200533. png_debug(1, "in png_write_flush\n");
  200534. if (png_ptr == NULL)
  200535. return;
  200536. /* We have already written out all of the data */
  200537. if (png_ptr->row_number >= png_ptr->num_rows)
  200538. return;
  200539. do
  200540. {
  200541. int ret;
  200542. /* compress the data */
  200543. ret = deflate(&png_ptr->zstream, Z_SYNC_FLUSH);
  200544. wrote_IDAT = 0;
  200545. /* check for compression errors */
  200546. if (ret != Z_OK)
  200547. {
  200548. if (png_ptr->zstream.msg != NULL)
  200549. png_error(png_ptr, png_ptr->zstream.msg);
  200550. else
  200551. png_error(png_ptr, "zlib error");
  200552. }
  200553. if (!(png_ptr->zstream.avail_out))
  200554. {
  200555. /* write the IDAT and reset the zlib output buffer */
  200556. png_write_IDAT(png_ptr, png_ptr->zbuf,
  200557. png_ptr->zbuf_size);
  200558. png_ptr->zstream.next_out = png_ptr->zbuf;
  200559. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200560. wrote_IDAT = 1;
  200561. }
  200562. } while(wrote_IDAT == 1);
  200563. /* If there is any data left to be output, write it into a new IDAT */
  200564. if (png_ptr->zbuf_size != png_ptr->zstream.avail_out)
  200565. {
  200566. /* write the IDAT and reset the zlib output buffer */
  200567. png_write_IDAT(png_ptr, png_ptr->zbuf,
  200568. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  200569. png_ptr->zstream.next_out = png_ptr->zbuf;
  200570. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  200571. }
  200572. png_ptr->flush_rows = 0;
  200573. png_flush(png_ptr);
  200574. }
  200575. #endif /* PNG_WRITE_FLUSH_SUPPORTED */
  200576. /* free all memory used by the write */
  200577. void PNGAPI
  200578. png_destroy_write_struct(png_structpp png_ptr_ptr, png_infopp info_ptr_ptr)
  200579. {
  200580. png_structp png_ptr = NULL;
  200581. png_infop info_ptr = NULL;
  200582. #ifdef PNG_USER_MEM_SUPPORTED
  200583. png_free_ptr free_fn = NULL;
  200584. png_voidp mem_ptr = NULL;
  200585. #endif
  200586. png_debug(1, "in png_destroy_write_struct\n");
  200587. if (png_ptr_ptr != NULL)
  200588. {
  200589. png_ptr = *png_ptr_ptr;
  200590. #ifdef PNG_USER_MEM_SUPPORTED
  200591. free_fn = png_ptr->free_fn;
  200592. mem_ptr = png_ptr->mem_ptr;
  200593. #endif
  200594. }
  200595. if (info_ptr_ptr != NULL)
  200596. info_ptr = *info_ptr_ptr;
  200597. if (info_ptr != NULL)
  200598. {
  200599. png_free_data(png_ptr, info_ptr, PNG_FREE_ALL, -1);
  200600. #if defined(PNG_UNKNOWN_CHUNKS_SUPPORTED)
  200601. if (png_ptr->num_chunk_list)
  200602. {
  200603. png_free(png_ptr, png_ptr->chunk_list);
  200604. png_ptr->chunk_list=NULL;
  200605. png_ptr->num_chunk_list=0;
  200606. }
  200607. #endif
  200608. #ifdef PNG_USER_MEM_SUPPORTED
  200609. png_destroy_struct_2((png_voidp)info_ptr, (png_free_ptr)free_fn,
  200610. (png_voidp)mem_ptr);
  200611. #else
  200612. png_destroy_struct((png_voidp)info_ptr);
  200613. #endif
  200614. *info_ptr_ptr = NULL;
  200615. }
  200616. if (png_ptr != NULL)
  200617. {
  200618. png_write_destroy(png_ptr);
  200619. #ifdef PNG_USER_MEM_SUPPORTED
  200620. png_destroy_struct_2((png_voidp)png_ptr, (png_free_ptr)free_fn,
  200621. (png_voidp)mem_ptr);
  200622. #else
  200623. png_destroy_struct((png_voidp)png_ptr);
  200624. #endif
  200625. *png_ptr_ptr = NULL;
  200626. }
  200627. }
  200628. /* Free any memory used in png_ptr struct (old method) */
  200629. void /* PRIVATE */
  200630. png_write_destroy(png_structp png_ptr)
  200631. {
  200632. #ifdef PNG_SETJMP_SUPPORTED
  200633. jmp_buf tmp_jmp; /* save jump buffer */
  200634. #endif
  200635. png_error_ptr error_fn;
  200636. png_error_ptr warning_fn;
  200637. png_voidp error_ptr;
  200638. #ifdef PNG_USER_MEM_SUPPORTED
  200639. png_free_ptr free_fn;
  200640. #endif
  200641. png_debug(1, "in png_write_destroy\n");
  200642. /* free any memory zlib uses */
  200643. deflateEnd(&png_ptr->zstream);
  200644. /* free our memory. png_free checks NULL for us. */
  200645. png_free(png_ptr, png_ptr->zbuf);
  200646. png_free(png_ptr, png_ptr->row_buf);
  200647. png_free(png_ptr, png_ptr->prev_row);
  200648. png_free(png_ptr, png_ptr->sub_row);
  200649. png_free(png_ptr, png_ptr->up_row);
  200650. png_free(png_ptr, png_ptr->avg_row);
  200651. png_free(png_ptr, png_ptr->paeth_row);
  200652. #if defined(PNG_TIME_RFC1123_SUPPORTED)
  200653. png_free(png_ptr, png_ptr->time_buffer);
  200654. #endif
  200655. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  200656. png_free(png_ptr, png_ptr->prev_filters);
  200657. png_free(png_ptr, png_ptr->filter_weights);
  200658. png_free(png_ptr, png_ptr->inv_filter_weights);
  200659. png_free(png_ptr, png_ptr->filter_costs);
  200660. png_free(png_ptr, png_ptr->inv_filter_costs);
  200661. #endif
  200662. #ifdef PNG_SETJMP_SUPPORTED
  200663. /* reset structure */
  200664. png_memcpy(tmp_jmp, png_ptr->jmpbuf, png_sizeof (jmp_buf));
  200665. #endif
  200666. error_fn = png_ptr->error_fn;
  200667. warning_fn = png_ptr->warning_fn;
  200668. error_ptr = png_ptr->error_ptr;
  200669. #ifdef PNG_USER_MEM_SUPPORTED
  200670. free_fn = png_ptr->free_fn;
  200671. #endif
  200672. png_memset(png_ptr, 0, png_sizeof (png_struct));
  200673. png_ptr->error_fn = error_fn;
  200674. png_ptr->warning_fn = warning_fn;
  200675. png_ptr->error_ptr = error_ptr;
  200676. #ifdef PNG_USER_MEM_SUPPORTED
  200677. png_ptr->free_fn = free_fn;
  200678. #endif
  200679. #ifdef PNG_SETJMP_SUPPORTED
  200680. png_memcpy(png_ptr->jmpbuf, tmp_jmp, png_sizeof (jmp_buf));
  200681. #endif
  200682. }
  200683. /* Allow the application to select one or more row filters to use. */
  200684. void PNGAPI
  200685. png_set_filter(png_structp png_ptr, int method, int filters)
  200686. {
  200687. png_debug(1, "in png_set_filter\n");
  200688. if (png_ptr == NULL)
  200689. return;
  200690. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  200691. if((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  200692. (method == PNG_INTRAPIXEL_DIFFERENCING))
  200693. method = PNG_FILTER_TYPE_BASE;
  200694. #endif
  200695. if (method == PNG_FILTER_TYPE_BASE)
  200696. {
  200697. switch (filters & (PNG_ALL_FILTERS | 0x07))
  200698. {
  200699. #ifndef PNG_NO_WRITE_FILTER
  200700. case 5:
  200701. case 6:
  200702. case 7: png_warning(png_ptr, "Unknown row filter for method 0");
  200703. #endif /* PNG_NO_WRITE_FILTER */
  200704. case PNG_FILTER_VALUE_NONE:
  200705. png_ptr->do_filter=PNG_FILTER_NONE; break;
  200706. #ifndef PNG_NO_WRITE_FILTER
  200707. case PNG_FILTER_VALUE_SUB:
  200708. png_ptr->do_filter=PNG_FILTER_SUB; break;
  200709. case PNG_FILTER_VALUE_UP:
  200710. png_ptr->do_filter=PNG_FILTER_UP; break;
  200711. case PNG_FILTER_VALUE_AVG:
  200712. png_ptr->do_filter=PNG_FILTER_AVG; break;
  200713. case PNG_FILTER_VALUE_PAETH:
  200714. png_ptr->do_filter=PNG_FILTER_PAETH; break;
  200715. default: png_ptr->do_filter = (png_byte)filters; break;
  200716. #else
  200717. default: png_warning(png_ptr, "Unknown row filter for method 0");
  200718. #endif /* PNG_NO_WRITE_FILTER */
  200719. }
  200720. /* If we have allocated the row_buf, this means we have already started
  200721. * with the image and we should have allocated all of the filter buffers
  200722. * that have been selected. If prev_row isn't already allocated, then
  200723. * it is too late to start using the filters that need it, since we
  200724. * will be missing the data in the previous row. If an application
  200725. * wants to start and stop using particular filters during compression,
  200726. * it should start out with all of the filters, and then add and
  200727. * remove them after the start of compression.
  200728. */
  200729. if (png_ptr->row_buf != NULL)
  200730. {
  200731. #ifndef PNG_NO_WRITE_FILTER
  200732. if ((png_ptr->do_filter & PNG_FILTER_SUB) && png_ptr->sub_row == NULL)
  200733. {
  200734. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  200735. (png_ptr->rowbytes + 1));
  200736. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  200737. }
  200738. if ((png_ptr->do_filter & PNG_FILTER_UP) && png_ptr->up_row == NULL)
  200739. {
  200740. if (png_ptr->prev_row == NULL)
  200741. {
  200742. png_warning(png_ptr, "Can't add Up filter after starting");
  200743. png_ptr->do_filter &= ~PNG_FILTER_UP;
  200744. }
  200745. else
  200746. {
  200747. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  200748. (png_ptr->rowbytes + 1));
  200749. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  200750. }
  200751. }
  200752. if ((png_ptr->do_filter & PNG_FILTER_AVG) && png_ptr->avg_row == NULL)
  200753. {
  200754. if (png_ptr->prev_row == NULL)
  200755. {
  200756. png_warning(png_ptr, "Can't add Average filter after starting");
  200757. png_ptr->do_filter &= ~PNG_FILTER_AVG;
  200758. }
  200759. else
  200760. {
  200761. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  200762. (png_ptr->rowbytes + 1));
  200763. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  200764. }
  200765. }
  200766. if ((png_ptr->do_filter & PNG_FILTER_PAETH) &&
  200767. png_ptr->paeth_row == NULL)
  200768. {
  200769. if (png_ptr->prev_row == NULL)
  200770. {
  200771. png_warning(png_ptr, "Can't add Paeth filter after starting");
  200772. png_ptr->do_filter &= (png_byte)(~PNG_FILTER_PAETH);
  200773. }
  200774. else
  200775. {
  200776. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  200777. (png_ptr->rowbytes + 1));
  200778. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  200779. }
  200780. }
  200781. if (png_ptr->do_filter == PNG_NO_FILTERS)
  200782. #endif /* PNG_NO_WRITE_FILTER */
  200783. png_ptr->do_filter = PNG_FILTER_NONE;
  200784. }
  200785. }
  200786. else
  200787. png_error(png_ptr, "Unknown custom filter method");
  200788. }
  200789. /* This allows us to influence the way in which libpng chooses the "best"
  200790. * filter for the current scanline. While the "minimum-sum-of-absolute-
  200791. * differences metric is relatively fast and effective, there is some
  200792. * question as to whether it can be improved upon by trying to keep the
  200793. * filtered data going to zlib more consistent, hopefully resulting in
  200794. * better compression.
  200795. */
  200796. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED) /* GRR 970116 */
  200797. void PNGAPI
  200798. png_set_filter_heuristics(png_structp png_ptr, int heuristic_method,
  200799. int num_weights, png_doublep filter_weights,
  200800. png_doublep filter_costs)
  200801. {
  200802. int i;
  200803. png_debug(1, "in png_set_filter_heuristics\n");
  200804. if (png_ptr == NULL)
  200805. return;
  200806. if (heuristic_method >= PNG_FILTER_HEURISTIC_LAST)
  200807. {
  200808. png_warning(png_ptr, "Unknown filter heuristic method");
  200809. return;
  200810. }
  200811. if (heuristic_method == PNG_FILTER_HEURISTIC_DEFAULT)
  200812. {
  200813. heuristic_method = PNG_FILTER_HEURISTIC_UNWEIGHTED;
  200814. }
  200815. if (num_weights < 0 || filter_weights == NULL ||
  200816. heuristic_method == PNG_FILTER_HEURISTIC_UNWEIGHTED)
  200817. {
  200818. num_weights = 0;
  200819. }
  200820. png_ptr->num_prev_filters = (png_byte)num_weights;
  200821. png_ptr->heuristic_method = (png_byte)heuristic_method;
  200822. if (num_weights > 0)
  200823. {
  200824. if (png_ptr->prev_filters == NULL)
  200825. {
  200826. png_ptr->prev_filters = (png_bytep)png_malloc(png_ptr,
  200827. (png_uint_32)(png_sizeof(png_byte) * num_weights));
  200828. /* To make sure that the weighting starts out fairly */
  200829. for (i = 0; i < num_weights; i++)
  200830. {
  200831. png_ptr->prev_filters[i] = 255;
  200832. }
  200833. }
  200834. if (png_ptr->filter_weights == NULL)
  200835. {
  200836. png_ptr->filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200837. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200838. png_ptr->inv_filter_weights = (png_uint_16p)png_malloc(png_ptr,
  200839. (png_uint_32)(png_sizeof(png_uint_16) * num_weights));
  200840. for (i = 0; i < num_weights; i++)
  200841. {
  200842. png_ptr->inv_filter_weights[i] =
  200843. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200844. }
  200845. }
  200846. for (i = 0; i < num_weights; i++)
  200847. {
  200848. if (filter_weights[i] < 0.0)
  200849. {
  200850. png_ptr->inv_filter_weights[i] =
  200851. png_ptr->filter_weights[i] = PNG_WEIGHT_FACTOR;
  200852. }
  200853. else
  200854. {
  200855. png_ptr->inv_filter_weights[i] =
  200856. (png_uint_16)((double)PNG_WEIGHT_FACTOR*filter_weights[i]+0.5);
  200857. png_ptr->filter_weights[i] =
  200858. (png_uint_16)((double)PNG_WEIGHT_FACTOR/filter_weights[i]+0.5);
  200859. }
  200860. }
  200861. }
  200862. /* If, in the future, there are other filter methods, this would
  200863. * need to be based on png_ptr->filter.
  200864. */
  200865. if (png_ptr->filter_costs == NULL)
  200866. {
  200867. png_ptr->filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200868. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200869. png_ptr->inv_filter_costs = (png_uint_16p)png_malloc(png_ptr,
  200870. (png_uint_32)(png_sizeof(png_uint_16) * PNG_FILTER_VALUE_LAST));
  200871. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200872. {
  200873. png_ptr->inv_filter_costs[i] =
  200874. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200875. }
  200876. }
  200877. /* Here is where we set the relative costs of the different filters. We
  200878. * should take the desired compression level into account when setting
  200879. * the costs, so that Paeth, for instance, has a high relative cost at low
  200880. * compression levels, while it has a lower relative cost at higher
  200881. * compression settings. The filter types are in order of increasing
  200882. * relative cost, so it would be possible to do this with an algorithm.
  200883. */
  200884. for (i = 0; i < PNG_FILTER_VALUE_LAST; i++)
  200885. {
  200886. if (filter_costs == NULL || filter_costs[i] < 0.0)
  200887. {
  200888. png_ptr->inv_filter_costs[i] =
  200889. png_ptr->filter_costs[i] = PNG_COST_FACTOR;
  200890. }
  200891. else if (filter_costs[i] >= 1.0)
  200892. {
  200893. png_ptr->inv_filter_costs[i] =
  200894. (png_uint_16)((double)PNG_COST_FACTOR / filter_costs[i] + 0.5);
  200895. png_ptr->filter_costs[i] =
  200896. (png_uint_16)((double)PNG_COST_FACTOR * filter_costs[i] + 0.5);
  200897. }
  200898. }
  200899. }
  200900. #endif /* PNG_WRITE_WEIGHTED_FILTER_SUPPORTED */
  200901. void PNGAPI
  200902. png_set_compression_level(png_structp png_ptr, int level)
  200903. {
  200904. png_debug(1, "in png_set_compression_level\n");
  200905. if (png_ptr == NULL)
  200906. return;
  200907. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_LEVEL;
  200908. png_ptr->zlib_level = level;
  200909. }
  200910. void PNGAPI
  200911. png_set_compression_mem_level(png_structp png_ptr, int mem_level)
  200912. {
  200913. png_debug(1, "in png_set_compression_mem_level\n");
  200914. if (png_ptr == NULL)
  200915. return;
  200916. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL;
  200917. png_ptr->zlib_mem_level = mem_level;
  200918. }
  200919. void PNGAPI
  200920. png_set_compression_strategy(png_structp png_ptr, int strategy)
  200921. {
  200922. png_debug(1, "in png_set_compression_strategy\n");
  200923. if (png_ptr == NULL)
  200924. return;
  200925. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_STRATEGY;
  200926. png_ptr->zlib_strategy = strategy;
  200927. }
  200928. void PNGAPI
  200929. png_set_compression_window_bits(png_structp png_ptr, int window_bits)
  200930. {
  200931. if (png_ptr == NULL)
  200932. return;
  200933. if (window_bits > 15)
  200934. png_warning(png_ptr, "Only compression windows <= 32k supported by PNG");
  200935. else if (window_bits < 8)
  200936. png_warning(png_ptr, "Only compression windows >= 256 supported by PNG");
  200937. #ifndef WBITS_8_OK
  200938. /* avoid libpng bug with 256-byte windows */
  200939. if (window_bits == 8)
  200940. {
  200941. png_warning(png_ptr, "Compression window is being reset to 512");
  200942. window_bits=9;
  200943. }
  200944. #endif
  200945. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS;
  200946. png_ptr->zlib_window_bits = window_bits;
  200947. }
  200948. void PNGAPI
  200949. png_set_compression_method(png_structp png_ptr, int method)
  200950. {
  200951. png_debug(1, "in png_set_compression_method\n");
  200952. if (png_ptr == NULL)
  200953. return;
  200954. if (method != 8)
  200955. png_warning(png_ptr, "Only compression method 8 is supported by PNG");
  200956. png_ptr->flags |= PNG_FLAG_ZLIB_CUSTOM_METHOD;
  200957. png_ptr->zlib_method = method;
  200958. }
  200959. void PNGAPI
  200960. png_set_write_status_fn(png_structp png_ptr, png_write_status_ptr write_row_fn)
  200961. {
  200962. if (png_ptr == NULL)
  200963. return;
  200964. png_ptr->write_row_fn = write_row_fn;
  200965. }
  200966. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  200967. void PNGAPI
  200968. png_set_write_user_transform_fn(png_structp png_ptr, png_user_transform_ptr
  200969. write_user_transform_fn)
  200970. {
  200971. png_debug(1, "in png_set_write_user_transform_fn\n");
  200972. if (png_ptr == NULL)
  200973. return;
  200974. png_ptr->transformations |= PNG_USER_TRANSFORM;
  200975. png_ptr->write_user_transform_fn = write_user_transform_fn;
  200976. }
  200977. #endif
  200978. #if defined(PNG_INFO_IMAGE_SUPPORTED)
  200979. void PNGAPI
  200980. png_write_png(png_structp png_ptr, png_infop info_ptr,
  200981. int transforms, voidp params)
  200982. {
  200983. if (png_ptr == NULL || info_ptr == NULL)
  200984. return;
  200985. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  200986. /* invert the alpha channel from opacity to transparency */
  200987. if (transforms & PNG_TRANSFORM_INVERT_ALPHA)
  200988. png_set_invert_alpha(png_ptr);
  200989. #endif
  200990. /* Write the file header information. */
  200991. png_write_info(png_ptr, info_ptr);
  200992. /* ------ these transformations don't touch the info structure ------- */
  200993. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  200994. /* invert monochrome pixels */
  200995. if (transforms & PNG_TRANSFORM_INVERT_MONO)
  200996. png_set_invert_mono(png_ptr);
  200997. #endif
  200998. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  200999. /* Shift the pixels up to a legal bit depth and fill in
  201000. * as appropriate to correctly scale the image.
  201001. */
  201002. if ((transforms & PNG_TRANSFORM_SHIFT)
  201003. && (info_ptr->valid & PNG_INFO_sBIT))
  201004. png_set_shift(png_ptr, &info_ptr->sig_bit);
  201005. #endif
  201006. #if defined(PNG_WRITE_PACK_SUPPORTED)
  201007. /* pack pixels into bytes */
  201008. if (transforms & PNG_TRANSFORM_PACKING)
  201009. png_set_packing(png_ptr);
  201010. #endif
  201011. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  201012. /* swap location of alpha bytes from ARGB to RGBA */
  201013. if (transforms & PNG_TRANSFORM_SWAP_ALPHA)
  201014. png_set_swap_alpha(png_ptr);
  201015. #endif
  201016. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  201017. /* Get rid of filler (OR ALPHA) bytes, pack XRGB/RGBX/ARGB/RGBA into
  201018. * RGB (4 channels -> 3 channels). The second parameter is not used.
  201019. */
  201020. if (transforms & PNG_TRANSFORM_STRIP_FILLER)
  201021. png_set_filler(png_ptr, 0, PNG_FILLER_BEFORE);
  201022. #endif
  201023. #if defined(PNG_WRITE_BGR_SUPPORTED)
  201024. /* flip BGR pixels to RGB */
  201025. if (transforms & PNG_TRANSFORM_BGR)
  201026. png_set_bgr(png_ptr);
  201027. #endif
  201028. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  201029. /* swap bytes of 16-bit files to most significant byte first */
  201030. if (transforms & PNG_TRANSFORM_SWAP_ENDIAN)
  201031. png_set_swap(png_ptr);
  201032. #endif
  201033. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  201034. /* swap bits of 1, 2, 4 bit packed pixel formats */
  201035. if (transforms & PNG_TRANSFORM_PACKSWAP)
  201036. png_set_packswap(png_ptr);
  201037. #endif
  201038. /* ----------------------- end of transformations ------------------- */
  201039. /* write the bits */
  201040. if (info_ptr->valid & PNG_INFO_IDAT)
  201041. png_write_image(png_ptr, info_ptr->row_pointers);
  201042. /* It is REQUIRED to call this to finish writing the rest of the file */
  201043. png_write_end(png_ptr, info_ptr);
  201044. transforms = transforms; /* quiet compiler warnings */
  201045. params = params;
  201046. }
  201047. #endif
  201048. #endif /* PNG_WRITE_SUPPORTED */
  201049. /********* End of inlined file: pngwrite.c *********/
  201050. /********* Start of inlined file: pngwtran.c *********/
  201051. /* pngwtran.c - transforms the data in a row for PNG writers
  201052. *
  201053. * Last changed in libpng 1.2.9 April 14, 2006
  201054. * For conditions of distribution and use, see copyright notice in png.h
  201055. * Copyright (c) 1998-2006 Glenn Randers-Pehrson
  201056. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  201057. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  201058. */
  201059. #define PNG_INTERNAL
  201060. #ifdef PNG_WRITE_SUPPORTED
  201061. /* Transform the data according to the user's wishes. The order of
  201062. * transformations is significant.
  201063. */
  201064. void /* PRIVATE */
  201065. png_do_write_transformations(png_structp png_ptr)
  201066. {
  201067. png_debug(1, "in png_do_write_transformations\n");
  201068. if (png_ptr == NULL)
  201069. return;
  201070. #if defined(PNG_WRITE_USER_TRANSFORM_SUPPORTED)
  201071. if (png_ptr->transformations & PNG_USER_TRANSFORM)
  201072. if(png_ptr->write_user_transform_fn != NULL)
  201073. (*(png_ptr->write_user_transform_fn)) /* user write transform function */
  201074. (png_ptr, /* png_ptr */
  201075. &(png_ptr->row_info), /* row_info: */
  201076. /* png_uint_32 width; width of row */
  201077. /* png_uint_32 rowbytes; number of bytes in row */
  201078. /* png_byte color_type; color type of pixels */
  201079. /* png_byte bit_depth; bit depth of samples */
  201080. /* png_byte channels; number of channels (1-4) */
  201081. /* png_byte pixel_depth; bits per pixel (depth*channels) */
  201082. png_ptr->row_buf + 1); /* start of pixel data for row */
  201083. #endif
  201084. #if defined(PNG_WRITE_FILLER_SUPPORTED)
  201085. if (png_ptr->transformations & PNG_FILLER)
  201086. png_do_strip_filler(&(png_ptr->row_info), png_ptr->row_buf + 1,
  201087. png_ptr->flags);
  201088. #endif
  201089. #if defined(PNG_WRITE_PACKSWAP_SUPPORTED)
  201090. if (png_ptr->transformations & PNG_PACKSWAP)
  201091. png_do_packswap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  201092. #endif
  201093. #if defined(PNG_WRITE_PACK_SUPPORTED)
  201094. if (png_ptr->transformations & PNG_PACK)
  201095. png_do_pack(&(png_ptr->row_info), png_ptr->row_buf + 1,
  201096. (png_uint_32)png_ptr->bit_depth);
  201097. #endif
  201098. #if defined(PNG_WRITE_SWAP_SUPPORTED)
  201099. if (png_ptr->transformations & PNG_SWAP_BYTES)
  201100. png_do_swap(&(png_ptr->row_info), png_ptr->row_buf + 1);
  201101. #endif
  201102. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  201103. if (png_ptr->transformations & PNG_SHIFT)
  201104. png_do_shift(&(png_ptr->row_info), png_ptr->row_buf + 1,
  201105. &(png_ptr->shift));
  201106. #endif
  201107. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  201108. if (png_ptr->transformations & PNG_SWAP_ALPHA)
  201109. png_do_write_swap_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  201110. #endif
  201111. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  201112. if (png_ptr->transformations & PNG_INVERT_ALPHA)
  201113. png_do_write_invert_alpha(&(png_ptr->row_info), png_ptr->row_buf + 1);
  201114. #endif
  201115. #if defined(PNG_WRITE_BGR_SUPPORTED)
  201116. if (png_ptr->transformations & PNG_BGR)
  201117. png_do_bgr(&(png_ptr->row_info), png_ptr->row_buf + 1);
  201118. #endif
  201119. #if defined(PNG_WRITE_INVERT_SUPPORTED)
  201120. if (png_ptr->transformations & PNG_INVERT_MONO)
  201121. png_do_invert(&(png_ptr->row_info), png_ptr->row_buf + 1);
  201122. #endif
  201123. }
  201124. #if defined(PNG_WRITE_PACK_SUPPORTED)
  201125. /* Pack pixels into bytes. Pass the true bit depth in bit_depth. The
  201126. * row_info bit depth should be 8 (one pixel per byte). The channels
  201127. * should be 1 (this only happens on grayscale and paletted images).
  201128. */
  201129. void /* PRIVATE */
  201130. png_do_pack(png_row_infop row_info, png_bytep row, png_uint_32 bit_depth)
  201131. {
  201132. png_debug(1, "in png_do_pack\n");
  201133. if (row_info->bit_depth == 8 &&
  201134. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  201135. row != NULL && row_info != NULL &&
  201136. #endif
  201137. row_info->channels == 1)
  201138. {
  201139. switch ((int)bit_depth)
  201140. {
  201141. case 1:
  201142. {
  201143. png_bytep sp, dp;
  201144. int mask, v;
  201145. png_uint_32 i;
  201146. png_uint_32 row_width = row_info->width;
  201147. sp = row;
  201148. dp = row;
  201149. mask = 0x80;
  201150. v = 0;
  201151. for (i = 0; i < row_width; i++)
  201152. {
  201153. if (*sp != 0)
  201154. v |= mask;
  201155. sp++;
  201156. if (mask > 1)
  201157. mask >>= 1;
  201158. else
  201159. {
  201160. mask = 0x80;
  201161. *dp = (png_byte)v;
  201162. dp++;
  201163. v = 0;
  201164. }
  201165. }
  201166. if (mask != 0x80)
  201167. *dp = (png_byte)v;
  201168. break;
  201169. }
  201170. case 2:
  201171. {
  201172. png_bytep sp, dp;
  201173. int shift, v;
  201174. png_uint_32 i;
  201175. png_uint_32 row_width = row_info->width;
  201176. sp = row;
  201177. dp = row;
  201178. shift = 6;
  201179. v = 0;
  201180. for (i = 0; i < row_width; i++)
  201181. {
  201182. png_byte value;
  201183. value = (png_byte)(*sp & 0x03);
  201184. v |= (value << shift);
  201185. if (shift == 0)
  201186. {
  201187. shift = 6;
  201188. *dp = (png_byte)v;
  201189. dp++;
  201190. v = 0;
  201191. }
  201192. else
  201193. shift -= 2;
  201194. sp++;
  201195. }
  201196. if (shift != 6)
  201197. *dp = (png_byte)v;
  201198. break;
  201199. }
  201200. case 4:
  201201. {
  201202. png_bytep sp, dp;
  201203. int shift, v;
  201204. png_uint_32 i;
  201205. png_uint_32 row_width = row_info->width;
  201206. sp = row;
  201207. dp = row;
  201208. shift = 4;
  201209. v = 0;
  201210. for (i = 0; i < row_width; i++)
  201211. {
  201212. png_byte value;
  201213. value = (png_byte)(*sp & 0x0f);
  201214. v |= (value << shift);
  201215. if (shift == 0)
  201216. {
  201217. shift = 4;
  201218. *dp = (png_byte)v;
  201219. dp++;
  201220. v = 0;
  201221. }
  201222. else
  201223. shift -= 4;
  201224. sp++;
  201225. }
  201226. if (shift != 4)
  201227. *dp = (png_byte)v;
  201228. break;
  201229. }
  201230. }
  201231. row_info->bit_depth = (png_byte)bit_depth;
  201232. row_info->pixel_depth = (png_byte)(bit_depth * row_info->channels);
  201233. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  201234. row_info->width);
  201235. }
  201236. }
  201237. #endif
  201238. #if defined(PNG_WRITE_SHIFT_SUPPORTED)
  201239. /* Shift pixel values to take advantage of whole range. Pass the
  201240. * true number of bits in bit_depth. The row should be packed
  201241. * according to row_info->bit_depth. Thus, if you had a row of
  201242. * bit depth 4, but the pixels only had values from 0 to 7, you
  201243. * would pass 3 as bit_depth, and this routine would translate the
  201244. * data to 0 to 15.
  201245. */
  201246. void /* PRIVATE */
  201247. png_do_shift(png_row_infop row_info, png_bytep row, png_color_8p bit_depth)
  201248. {
  201249. png_debug(1, "in png_do_shift\n");
  201250. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  201251. if (row != NULL && row_info != NULL &&
  201252. #else
  201253. if (
  201254. #endif
  201255. row_info->color_type != PNG_COLOR_TYPE_PALETTE)
  201256. {
  201257. int shift_start[4], shift_dec[4];
  201258. int channels = 0;
  201259. if (row_info->color_type & PNG_COLOR_MASK_COLOR)
  201260. {
  201261. shift_start[channels] = row_info->bit_depth - bit_depth->red;
  201262. shift_dec[channels] = bit_depth->red;
  201263. channels++;
  201264. shift_start[channels] = row_info->bit_depth - bit_depth->green;
  201265. shift_dec[channels] = bit_depth->green;
  201266. channels++;
  201267. shift_start[channels] = row_info->bit_depth - bit_depth->blue;
  201268. shift_dec[channels] = bit_depth->blue;
  201269. channels++;
  201270. }
  201271. else
  201272. {
  201273. shift_start[channels] = row_info->bit_depth - bit_depth->gray;
  201274. shift_dec[channels] = bit_depth->gray;
  201275. channels++;
  201276. }
  201277. if (row_info->color_type & PNG_COLOR_MASK_ALPHA)
  201278. {
  201279. shift_start[channels] = row_info->bit_depth - bit_depth->alpha;
  201280. shift_dec[channels] = bit_depth->alpha;
  201281. channels++;
  201282. }
  201283. /* with low row depths, could only be grayscale, so one channel */
  201284. if (row_info->bit_depth < 8)
  201285. {
  201286. png_bytep bp = row;
  201287. png_uint_32 i;
  201288. png_byte mask;
  201289. png_uint_32 row_bytes = row_info->rowbytes;
  201290. if (bit_depth->gray == 1 && row_info->bit_depth == 2)
  201291. mask = 0x55;
  201292. else if (row_info->bit_depth == 4 && bit_depth->gray == 3)
  201293. mask = 0x11;
  201294. else
  201295. mask = 0xff;
  201296. for (i = 0; i < row_bytes; i++, bp++)
  201297. {
  201298. png_uint_16 v;
  201299. int j;
  201300. v = *bp;
  201301. *bp = 0;
  201302. for (j = shift_start[0]; j > -shift_dec[0]; j -= shift_dec[0])
  201303. {
  201304. if (j > 0)
  201305. *bp |= (png_byte)((v << j) & 0xff);
  201306. else
  201307. *bp |= (png_byte)((v >> (-j)) & mask);
  201308. }
  201309. }
  201310. }
  201311. else if (row_info->bit_depth == 8)
  201312. {
  201313. png_bytep bp = row;
  201314. png_uint_32 i;
  201315. png_uint_32 istop = channels * row_info->width;
  201316. for (i = 0; i < istop; i++, bp++)
  201317. {
  201318. png_uint_16 v;
  201319. int j;
  201320. int c = (int)(i%channels);
  201321. v = *bp;
  201322. *bp = 0;
  201323. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  201324. {
  201325. if (j > 0)
  201326. *bp |= (png_byte)((v << j) & 0xff);
  201327. else
  201328. *bp |= (png_byte)((v >> (-j)) & 0xff);
  201329. }
  201330. }
  201331. }
  201332. else
  201333. {
  201334. png_bytep bp;
  201335. png_uint_32 i;
  201336. png_uint_32 istop = channels * row_info->width;
  201337. for (bp = row, i = 0; i < istop; i++)
  201338. {
  201339. int c = (int)(i%channels);
  201340. png_uint_16 value, v;
  201341. int j;
  201342. v = (png_uint_16)(((png_uint_16)(*bp) << 8) + *(bp + 1));
  201343. value = 0;
  201344. for (j = shift_start[c]; j > -shift_dec[c]; j -= shift_dec[c])
  201345. {
  201346. if (j > 0)
  201347. value |= (png_uint_16)((v << j) & (png_uint_16)0xffff);
  201348. else
  201349. value |= (png_uint_16)((v >> (-j)) & (png_uint_16)0xffff);
  201350. }
  201351. *bp++ = (png_byte)(value >> 8);
  201352. *bp++ = (png_byte)(value & 0xff);
  201353. }
  201354. }
  201355. }
  201356. }
  201357. #endif
  201358. #if defined(PNG_WRITE_SWAP_ALPHA_SUPPORTED)
  201359. void /* PRIVATE */
  201360. png_do_write_swap_alpha(png_row_infop row_info, png_bytep row)
  201361. {
  201362. png_debug(1, "in png_do_write_swap_alpha\n");
  201363. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  201364. if (row != NULL && row_info != NULL)
  201365. #endif
  201366. {
  201367. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  201368. {
  201369. /* This converts from ARGB to RGBA */
  201370. if (row_info->bit_depth == 8)
  201371. {
  201372. png_bytep sp, dp;
  201373. png_uint_32 i;
  201374. png_uint_32 row_width = row_info->width;
  201375. for (i = 0, sp = dp = row; i < row_width; i++)
  201376. {
  201377. png_byte save = *(sp++);
  201378. *(dp++) = *(sp++);
  201379. *(dp++) = *(sp++);
  201380. *(dp++) = *(sp++);
  201381. *(dp++) = save;
  201382. }
  201383. }
  201384. /* This converts from AARRGGBB to RRGGBBAA */
  201385. else
  201386. {
  201387. png_bytep sp, dp;
  201388. png_uint_32 i;
  201389. png_uint_32 row_width = row_info->width;
  201390. for (i = 0, sp = dp = row; i < row_width; i++)
  201391. {
  201392. png_byte save[2];
  201393. save[0] = *(sp++);
  201394. save[1] = *(sp++);
  201395. *(dp++) = *(sp++);
  201396. *(dp++) = *(sp++);
  201397. *(dp++) = *(sp++);
  201398. *(dp++) = *(sp++);
  201399. *(dp++) = *(sp++);
  201400. *(dp++) = *(sp++);
  201401. *(dp++) = save[0];
  201402. *(dp++) = save[1];
  201403. }
  201404. }
  201405. }
  201406. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  201407. {
  201408. /* This converts from AG to GA */
  201409. if (row_info->bit_depth == 8)
  201410. {
  201411. png_bytep sp, dp;
  201412. png_uint_32 i;
  201413. png_uint_32 row_width = row_info->width;
  201414. for (i = 0, sp = dp = row; i < row_width; i++)
  201415. {
  201416. png_byte save = *(sp++);
  201417. *(dp++) = *(sp++);
  201418. *(dp++) = save;
  201419. }
  201420. }
  201421. /* This converts from AAGG to GGAA */
  201422. else
  201423. {
  201424. png_bytep sp, dp;
  201425. png_uint_32 i;
  201426. png_uint_32 row_width = row_info->width;
  201427. for (i = 0, sp = dp = row; i < row_width; i++)
  201428. {
  201429. png_byte save[2];
  201430. save[0] = *(sp++);
  201431. save[1] = *(sp++);
  201432. *(dp++) = *(sp++);
  201433. *(dp++) = *(sp++);
  201434. *(dp++) = save[0];
  201435. *(dp++) = save[1];
  201436. }
  201437. }
  201438. }
  201439. }
  201440. }
  201441. #endif
  201442. #if defined(PNG_WRITE_INVERT_ALPHA_SUPPORTED)
  201443. void /* PRIVATE */
  201444. png_do_write_invert_alpha(png_row_infop row_info, png_bytep row)
  201445. {
  201446. png_debug(1, "in png_do_write_invert_alpha\n");
  201447. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  201448. if (row != NULL && row_info != NULL)
  201449. #endif
  201450. {
  201451. if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  201452. {
  201453. /* This inverts the alpha channel in RGBA */
  201454. if (row_info->bit_depth == 8)
  201455. {
  201456. png_bytep sp, dp;
  201457. png_uint_32 i;
  201458. png_uint_32 row_width = row_info->width;
  201459. for (i = 0, sp = dp = row; i < row_width; i++)
  201460. {
  201461. /* does nothing
  201462. *(dp++) = *(sp++);
  201463. *(dp++) = *(sp++);
  201464. *(dp++) = *(sp++);
  201465. */
  201466. sp+=3; dp = sp;
  201467. *(dp++) = (png_byte)(255 - *(sp++));
  201468. }
  201469. }
  201470. /* This inverts the alpha channel in RRGGBBAA */
  201471. else
  201472. {
  201473. png_bytep sp, dp;
  201474. png_uint_32 i;
  201475. png_uint_32 row_width = row_info->width;
  201476. for (i = 0, sp = dp = row; i < row_width; i++)
  201477. {
  201478. /* does nothing
  201479. *(dp++) = *(sp++);
  201480. *(dp++) = *(sp++);
  201481. *(dp++) = *(sp++);
  201482. *(dp++) = *(sp++);
  201483. *(dp++) = *(sp++);
  201484. *(dp++) = *(sp++);
  201485. */
  201486. sp+=6; dp = sp;
  201487. *(dp++) = (png_byte)(255 - *(sp++));
  201488. *(dp++) = (png_byte)(255 - *(sp++));
  201489. }
  201490. }
  201491. }
  201492. else if (row_info->color_type == PNG_COLOR_TYPE_GRAY_ALPHA)
  201493. {
  201494. /* This inverts the alpha channel in GA */
  201495. if (row_info->bit_depth == 8)
  201496. {
  201497. png_bytep sp, dp;
  201498. png_uint_32 i;
  201499. png_uint_32 row_width = row_info->width;
  201500. for (i = 0, sp = dp = row; i < row_width; i++)
  201501. {
  201502. *(dp++) = *(sp++);
  201503. *(dp++) = (png_byte)(255 - *(sp++));
  201504. }
  201505. }
  201506. /* This inverts the alpha channel in GGAA */
  201507. else
  201508. {
  201509. png_bytep sp, dp;
  201510. png_uint_32 i;
  201511. png_uint_32 row_width = row_info->width;
  201512. for (i = 0, sp = dp = row; i < row_width; i++)
  201513. {
  201514. /* does nothing
  201515. *(dp++) = *(sp++);
  201516. *(dp++) = *(sp++);
  201517. */
  201518. sp+=2; dp = sp;
  201519. *(dp++) = (png_byte)(255 - *(sp++));
  201520. *(dp++) = (png_byte)(255 - *(sp++));
  201521. }
  201522. }
  201523. }
  201524. }
  201525. }
  201526. #endif
  201527. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201528. /* undoes intrapixel differencing */
  201529. void /* PRIVATE */
  201530. png_do_write_intrapixel(png_row_infop row_info, png_bytep row)
  201531. {
  201532. png_debug(1, "in png_do_write_intrapixel\n");
  201533. if (
  201534. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  201535. row != NULL && row_info != NULL &&
  201536. #endif
  201537. (row_info->color_type & PNG_COLOR_MASK_COLOR))
  201538. {
  201539. int bytes_per_pixel;
  201540. png_uint_32 row_width = row_info->width;
  201541. if (row_info->bit_depth == 8)
  201542. {
  201543. png_bytep rp;
  201544. png_uint_32 i;
  201545. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  201546. bytes_per_pixel = 3;
  201547. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  201548. bytes_per_pixel = 4;
  201549. else
  201550. return;
  201551. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  201552. {
  201553. *(rp) = (png_byte)((*rp - *(rp+1))&0xff);
  201554. *(rp+2) = (png_byte)((*(rp+2) - *(rp+1))&0xff);
  201555. }
  201556. }
  201557. else if (row_info->bit_depth == 16)
  201558. {
  201559. png_bytep rp;
  201560. png_uint_32 i;
  201561. if (row_info->color_type == PNG_COLOR_TYPE_RGB)
  201562. bytes_per_pixel = 6;
  201563. else if (row_info->color_type == PNG_COLOR_TYPE_RGB_ALPHA)
  201564. bytes_per_pixel = 8;
  201565. else
  201566. return;
  201567. for (i = 0, rp = row; i < row_width; i++, rp += bytes_per_pixel)
  201568. {
  201569. png_uint_32 s0 = (*(rp ) << 8) | *(rp+1);
  201570. png_uint_32 s1 = (*(rp+2) << 8) | *(rp+3);
  201571. png_uint_32 s2 = (*(rp+4) << 8) | *(rp+5);
  201572. png_uint_32 red = (png_uint_32)((s0-s1) & 0xffffL);
  201573. png_uint_32 blue = (png_uint_32)((s2-s1) & 0xffffL);
  201574. *(rp ) = (png_byte)((red >> 8) & 0xff);
  201575. *(rp+1) = (png_byte)(red & 0xff);
  201576. *(rp+4) = (png_byte)((blue >> 8) & 0xff);
  201577. *(rp+5) = (png_byte)(blue & 0xff);
  201578. }
  201579. }
  201580. }
  201581. }
  201582. #endif /* PNG_MNG_FEATURES_SUPPORTED */
  201583. #endif /* PNG_WRITE_SUPPORTED */
  201584. /********* End of inlined file: pngwtran.c *********/
  201585. /********* Start of inlined file: pngwutil.c *********/
  201586. /* pngwutil.c - utilities to write a PNG file
  201587. *
  201588. * Last changed in libpng 1.2.20 Septhember 3, 2007
  201589. * For conditions of distribution and use, see copyright notice in png.h
  201590. * Copyright (c) 1998-2007 Glenn Randers-Pehrson
  201591. * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  201592. * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  201593. */
  201594. #define PNG_INTERNAL
  201595. #ifdef PNG_WRITE_SUPPORTED
  201596. /* Place a 32-bit number into a buffer in PNG byte order. We work
  201597. * with unsigned numbers for convenience, although one supported
  201598. * ancillary chunk uses signed (two's complement) numbers.
  201599. */
  201600. void PNGAPI
  201601. png_save_uint_32(png_bytep buf, png_uint_32 i)
  201602. {
  201603. buf[0] = (png_byte)((i >> 24) & 0xff);
  201604. buf[1] = (png_byte)((i >> 16) & 0xff);
  201605. buf[2] = (png_byte)((i >> 8) & 0xff);
  201606. buf[3] = (png_byte)(i & 0xff);
  201607. }
  201608. /* The png_save_int_32 function assumes integers are stored in two's
  201609. * complement format. If this isn't the case, then this routine needs to
  201610. * be modified to write data in two's complement format.
  201611. */
  201612. void PNGAPI
  201613. png_save_int_32(png_bytep buf, png_int_32 i)
  201614. {
  201615. buf[0] = (png_byte)((i >> 24) & 0xff);
  201616. buf[1] = (png_byte)((i >> 16) & 0xff);
  201617. buf[2] = (png_byte)((i >> 8) & 0xff);
  201618. buf[3] = (png_byte)(i & 0xff);
  201619. }
  201620. /* Place a 16-bit number into a buffer in PNG byte order.
  201621. * The parameter is declared unsigned int, not png_uint_16,
  201622. * just to avoid potential problems on pre-ANSI C compilers.
  201623. */
  201624. void PNGAPI
  201625. png_save_uint_16(png_bytep buf, unsigned int i)
  201626. {
  201627. buf[0] = (png_byte)((i >> 8) & 0xff);
  201628. buf[1] = (png_byte)(i & 0xff);
  201629. }
  201630. /* Write a PNG chunk all at once. The type is an array of ASCII characters
  201631. * representing the chunk name. The array must be at least 4 bytes in
  201632. * length, and does not need to be null terminated. To be safe, pass the
  201633. * pre-defined chunk names here, and if you need a new one, define it
  201634. * where the others are defined. The length is the length of the data.
  201635. * All the data must be present. If that is not possible, use the
  201636. * png_write_chunk_start(), png_write_chunk_data(), and png_write_chunk_end()
  201637. * functions instead.
  201638. */
  201639. void PNGAPI
  201640. png_write_chunk(png_structp png_ptr, png_bytep chunk_name,
  201641. png_bytep data, png_size_t length)
  201642. {
  201643. if(png_ptr == NULL) return;
  201644. png_write_chunk_start(png_ptr, chunk_name, (png_uint_32)length);
  201645. png_write_chunk_data(png_ptr, data, length);
  201646. png_write_chunk_end(png_ptr);
  201647. }
  201648. /* Write the start of a PNG chunk. The type is the chunk type.
  201649. * The total_length is the sum of the lengths of all the data you will be
  201650. * passing in png_write_chunk_data().
  201651. */
  201652. void PNGAPI
  201653. png_write_chunk_start(png_structp png_ptr, png_bytep chunk_name,
  201654. png_uint_32 length)
  201655. {
  201656. png_byte buf[4];
  201657. png_debug2(0, "Writing %s chunk (%lu bytes)\n", chunk_name, length);
  201658. if(png_ptr == NULL) return;
  201659. /* write the length */
  201660. png_save_uint_32(buf, length);
  201661. png_write_data(png_ptr, buf, (png_size_t)4);
  201662. /* write the chunk name */
  201663. png_write_data(png_ptr, chunk_name, (png_size_t)4);
  201664. /* reset the crc and run it over the chunk name */
  201665. png_reset_crc(png_ptr);
  201666. png_calculate_crc(png_ptr, chunk_name, (png_size_t)4);
  201667. }
  201668. /* Write the data of a PNG chunk started with png_write_chunk_start().
  201669. * Note that multiple calls to this function are allowed, and that the
  201670. * sum of the lengths from these calls *must* add up to the total_length
  201671. * given to png_write_chunk_start().
  201672. */
  201673. void PNGAPI
  201674. png_write_chunk_data(png_structp png_ptr, png_bytep data, png_size_t length)
  201675. {
  201676. /* write the data, and run the CRC over it */
  201677. if(png_ptr == NULL) return;
  201678. if (data != NULL && length > 0)
  201679. {
  201680. png_calculate_crc(png_ptr, data, length);
  201681. png_write_data(png_ptr, data, length);
  201682. }
  201683. }
  201684. /* Finish a chunk started with png_write_chunk_start(). */
  201685. void PNGAPI
  201686. png_write_chunk_end(png_structp png_ptr)
  201687. {
  201688. png_byte buf[4];
  201689. if(png_ptr == NULL) return;
  201690. /* write the crc */
  201691. png_save_uint_32(buf, png_ptr->crc);
  201692. png_write_data(png_ptr, buf, (png_size_t)4);
  201693. }
  201694. /* Simple function to write the signature. If we have already written
  201695. * the magic bytes of the signature, or more likely, the PNG stream is
  201696. * being embedded into another stream and doesn't need its own signature,
  201697. * we should call png_set_sig_bytes() to tell libpng how many of the
  201698. * bytes have already been written.
  201699. */
  201700. void /* PRIVATE */
  201701. png_write_sig(png_structp png_ptr)
  201702. {
  201703. png_byte png_signature[8] = {137, 80, 78, 71, 13, 10, 26, 10};
  201704. /* write the rest of the 8 byte signature */
  201705. png_write_data(png_ptr, &png_signature[png_ptr->sig_bytes],
  201706. (png_size_t)8 - png_ptr->sig_bytes);
  201707. if(png_ptr->sig_bytes < 3)
  201708. png_ptr->mode |= PNG_HAVE_PNG_SIGNATURE;
  201709. }
  201710. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_iCCP_SUPPORTED)
  201711. /*
  201712. * This pair of functions encapsulates the operation of (a) compressing a
  201713. * text string, and (b) issuing it later as a series of chunk data writes.
  201714. * The compression_state structure is shared context for these functions
  201715. * set up by the caller in order to make the whole mess thread-safe.
  201716. */
  201717. typedef struct
  201718. {
  201719. char *input; /* the uncompressed input data */
  201720. int input_len; /* its length */
  201721. int num_output_ptr; /* number of output pointers used */
  201722. int max_output_ptr; /* size of output_ptr */
  201723. png_charpp output_ptr; /* array of pointers to output */
  201724. } compression_state;
  201725. /* compress given text into storage in the png_ptr structure */
  201726. static int /* PRIVATE */
  201727. png_text_compress(png_structp png_ptr,
  201728. png_charp text, png_size_t text_len, int compression,
  201729. compression_state *comp)
  201730. {
  201731. int ret;
  201732. comp->num_output_ptr = 0;
  201733. comp->max_output_ptr = 0;
  201734. comp->output_ptr = NULL;
  201735. comp->input = NULL;
  201736. comp->input_len = 0;
  201737. /* we may just want to pass the text right through */
  201738. if (compression == PNG_TEXT_COMPRESSION_NONE)
  201739. {
  201740. comp->input = text;
  201741. comp->input_len = text_len;
  201742. return((int)text_len);
  201743. }
  201744. if (compression >= PNG_TEXT_COMPRESSION_LAST)
  201745. {
  201746. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  201747. char msg[50];
  201748. png_snprintf(msg, 50, "Unknown compression type %d", compression);
  201749. png_warning(png_ptr, msg);
  201750. #else
  201751. png_warning(png_ptr, "Unknown compression type");
  201752. #endif
  201753. }
  201754. /* We can't write the chunk until we find out how much data we have,
  201755. * which means we need to run the compressor first and save the
  201756. * output. This shouldn't be a problem, as the vast majority of
  201757. * comments should be reasonable, but we will set up an array of
  201758. * malloc'd pointers to be sure.
  201759. *
  201760. * If we knew the application was well behaved, we could simplify this
  201761. * greatly by assuming we can always malloc an output buffer large
  201762. * enough to hold the compressed text ((1001 * text_len / 1000) + 12)
  201763. * and malloc this directly. The only time this would be a bad idea is
  201764. * if we can't malloc more than 64K and we have 64K of random input
  201765. * data, or if the input string is incredibly large (although this
  201766. * wouldn't cause a failure, just a slowdown due to swapping).
  201767. */
  201768. /* set up the compression buffers */
  201769. png_ptr->zstream.avail_in = (uInt)text_len;
  201770. png_ptr->zstream.next_in = (Bytef *)text;
  201771. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201772. png_ptr->zstream.next_out = (Bytef *)png_ptr->zbuf;
  201773. /* this is the same compression loop as in png_write_row() */
  201774. do
  201775. {
  201776. /* compress the data */
  201777. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  201778. if (ret != Z_OK)
  201779. {
  201780. /* error */
  201781. if (png_ptr->zstream.msg != NULL)
  201782. png_error(png_ptr, png_ptr->zstream.msg);
  201783. else
  201784. png_error(png_ptr, "zlib error");
  201785. }
  201786. /* check to see if we need more room */
  201787. if (!(png_ptr->zstream.avail_out))
  201788. {
  201789. /* make sure the output array has room */
  201790. if (comp->num_output_ptr >= comp->max_output_ptr)
  201791. {
  201792. int old_max;
  201793. old_max = comp->max_output_ptr;
  201794. comp->max_output_ptr = comp->num_output_ptr + 4;
  201795. if (comp->output_ptr != NULL)
  201796. {
  201797. png_charpp old_ptr;
  201798. old_ptr = comp->output_ptr;
  201799. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201800. (png_uint_32)(comp->max_output_ptr *
  201801. png_sizeof (png_charpp)));
  201802. png_memcpy(comp->output_ptr, old_ptr, old_max
  201803. * png_sizeof (png_charp));
  201804. png_free(png_ptr, old_ptr);
  201805. }
  201806. else
  201807. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201808. (png_uint_32)(comp->max_output_ptr *
  201809. png_sizeof (png_charp)));
  201810. }
  201811. /* save the data */
  201812. comp->output_ptr[comp->num_output_ptr] = (png_charp)png_malloc(png_ptr,
  201813. (png_uint_32)png_ptr->zbuf_size);
  201814. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201815. png_ptr->zbuf_size);
  201816. comp->num_output_ptr++;
  201817. /* and reset the buffer */
  201818. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201819. png_ptr->zstream.next_out = png_ptr->zbuf;
  201820. }
  201821. /* continue until we don't have any more to compress */
  201822. } while (png_ptr->zstream.avail_in);
  201823. /* finish the compression */
  201824. do
  201825. {
  201826. /* tell zlib we are finished */
  201827. ret = deflate(&png_ptr->zstream, Z_FINISH);
  201828. if (ret == Z_OK)
  201829. {
  201830. /* check to see if we need more room */
  201831. if (!(png_ptr->zstream.avail_out))
  201832. {
  201833. /* check to make sure our output array has room */
  201834. if (comp->num_output_ptr >= comp->max_output_ptr)
  201835. {
  201836. int old_max;
  201837. old_max = comp->max_output_ptr;
  201838. comp->max_output_ptr = comp->num_output_ptr + 4;
  201839. if (comp->output_ptr != NULL)
  201840. {
  201841. png_charpp old_ptr;
  201842. old_ptr = comp->output_ptr;
  201843. /* This could be optimized to realloc() */
  201844. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201845. (png_uint_32)(comp->max_output_ptr *
  201846. png_sizeof (png_charpp)));
  201847. png_memcpy(comp->output_ptr, old_ptr,
  201848. old_max * png_sizeof (png_charp));
  201849. png_free(png_ptr, old_ptr);
  201850. }
  201851. else
  201852. comp->output_ptr = (png_charpp)png_malloc(png_ptr,
  201853. (png_uint_32)(comp->max_output_ptr *
  201854. png_sizeof (png_charp)));
  201855. }
  201856. /* save off the data */
  201857. comp->output_ptr[comp->num_output_ptr] =
  201858. (png_charp)png_malloc(png_ptr, (png_uint_32)png_ptr->zbuf_size);
  201859. png_memcpy(comp->output_ptr[comp->num_output_ptr], png_ptr->zbuf,
  201860. png_ptr->zbuf_size);
  201861. comp->num_output_ptr++;
  201862. /* and reset the buffer pointers */
  201863. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  201864. png_ptr->zstream.next_out = png_ptr->zbuf;
  201865. }
  201866. }
  201867. else if (ret != Z_STREAM_END)
  201868. {
  201869. /* we got an error */
  201870. if (png_ptr->zstream.msg != NULL)
  201871. png_error(png_ptr, png_ptr->zstream.msg);
  201872. else
  201873. png_error(png_ptr, "zlib error");
  201874. }
  201875. } while (ret != Z_STREAM_END);
  201876. /* text length is number of buffers plus last buffer */
  201877. text_len = png_ptr->zbuf_size * comp->num_output_ptr;
  201878. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  201879. text_len += png_ptr->zbuf_size - (png_size_t)png_ptr->zstream.avail_out;
  201880. return((int)text_len);
  201881. }
  201882. /* ship the compressed text out via chunk writes */
  201883. static void /* PRIVATE */
  201884. png_write_compressed_data_out(png_structp png_ptr, compression_state *comp)
  201885. {
  201886. int i;
  201887. /* handle the no-compression case */
  201888. if (comp->input)
  201889. {
  201890. png_write_chunk_data(png_ptr, (png_bytep)comp->input,
  201891. (png_size_t)comp->input_len);
  201892. return;
  201893. }
  201894. /* write saved output buffers, if any */
  201895. for (i = 0; i < comp->num_output_ptr; i++)
  201896. {
  201897. png_write_chunk_data(png_ptr,(png_bytep)comp->output_ptr[i],
  201898. png_ptr->zbuf_size);
  201899. png_free(png_ptr, comp->output_ptr[i]);
  201900. comp->output_ptr[i]=NULL;
  201901. }
  201902. if (comp->max_output_ptr != 0)
  201903. png_free(png_ptr, comp->output_ptr);
  201904. comp->output_ptr=NULL;
  201905. /* write anything left in zbuf */
  201906. if (png_ptr->zstream.avail_out < (png_uint_32)png_ptr->zbuf_size)
  201907. png_write_chunk_data(png_ptr, png_ptr->zbuf,
  201908. png_ptr->zbuf_size - png_ptr->zstream.avail_out);
  201909. /* reset zlib for another zTXt/iTXt or image data */
  201910. deflateReset(&png_ptr->zstream);
  201911. png_ptr->zstream.data_type = Z_BINARY;
  201912. }
  201913. #endif
  201914. /* Write the IHDR chunk, and update the png_struct with the necessary
  201915. * information. Note that the rest of this code depends upon this
  201916. * information being correct.
  201917. */
  201918. void /* PRIVATE */
  201919. png_write_IHDR(png_structp png_ptr, png_uint_32 width, png_uint_32 height,
  201920. int bit_depth, int color_type, int compression_type, int filter_type,
  201921. int interlace_type)
  201922. {
  201923. #ifdef PNG_USE_LOCAL_ARRAYS
  201924. PNG_IHDR;
  201925. #endif
  201926. png_byte buf[13]; /* buffer to store the IHDR info */
  201927. png_debug(1, "in png_write_IHDR\n");
  201928. /* Check that we have valid input data from the application info */
  201929. switch (color_type)
  201930. {
  201931. case PNG_COLOR_TYPE_GRAY:
  201932. switch (bit_depth)
  201933. {
  201934. case 1:
  201935. case 2:
  201936. case 4:
  201937. case 8:
  201938. case 16: png_ptr->channels = 1; break;
  201939. default: png_error(png_ptr,"Invalid bit depth for grayscale image");
  201940. }
  201941. break;
  201942. case PNG_COLOR_TYPE_RGB:
  201943. if (bit_depth != 8 && bit_depth != 16)
  201944. png_error(png_ptr, "Invalid bit depth for RGB image");
  201945. png_ptr->channels = 3;
  201946. break;
  201947. case PNG_COLOR_TYPE_PALETTE:
  201948. switch (bit_depth)
  201949. {
  201950. case 1:
  201951. case 2:
  201952. case 4:
  201953. case 8: png_ptr->channels = 1; break;
  201954. default: png_error(png_ptr, "Invalid bit depth for paletted image");
  201955. }
  201956. break;
  201957. case PNG_COLOR_TYPE_GRAY_ALPHA:
  201958. if (bit_depth != 8 && bit_depth != 16)
  201959. png_error(png_ptr, "Invalid bit depth for grayscale+alpha image");
  201960. png_ptr->channels = 2;
  201961. break;
  201962. case PNG_COLOR_TYPE_RGB_ALPHA:
  201963. if (bit_depth != 8 && bit_depth != 16)
  201964. png_error(png_ptr, "Invalid bit depth for RGBA image");
  201965. png_ptr->channels = 4;
  201966. break;
  201967. default:
  201968. png_error(png_ptr, "Invalid image color type specified");
  201969. }
  201970. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  201971. {
  201972. png_warning(png_ptr, "Invalid compression type specified");
  201973. compression_type = PNG_COMPRESSION_TYPE_BASE;
  201974. }
  201975. /* Write filter_method 64 (intrapixel differencing) only if
  201976. * 1. Libpng was compiled with PNG_MNG_FEATURES_SUPPORTED and
  201977. * 2. Libpng did not write a PNG signature (this filter_method is only
  201978. * used in PNG datastreams that are embedded in MNG datastreams) and
  201979. * 3. The application called png_permit_mng_features with a mask that
  201980. * included PNG_FLAG_MNG_FILTER_64 and
  201981. * 4. The filter_method is 64 and
  201982. * 5. The color_type is RGB or RGBA
  201983. */
  201984. if (
  201985. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  201986. !((png_ptr->mng_features_permitted & PNG_FLAG_MNG_FILTER_64) &&
  201987. ((png_ptr->mode&PNG_HAVE_PNG_SIGNATURE) == 0) &&
  201988. (color_type == PNG_COLOR_TYPE_RGB ||
  201989. color_type == PNG_COLOR_TYPE_RGB_ALPHA) &&
  201990. (filter_type == PNG_INTRAPIXEL_DIFFERENCING)) &&
  201991. #endif
  201992. filter_type != PNG_FILTER_TYPE_BASE)
  201993. {
  201994. png_warning(png_ptr, "Invalid filter type specified");
  201995. filter_type = PNG_FILTER_TYPE_BASE;
  201996. }
  201997. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  201998. if (interlace_type != PNG_INTERLACE_NONE &&
  201999. interlace_type != PNG_INTERLACE_ADAM7)
  202000. {
  202001. png_warning(png_ptr, "Invalid interlace type specified");
  202002. interlace_type = PNG_INTERLACE_ADAM7;
  202003. }
  202004. #else
  202005. interlace_type=PNG_INTERLACE_NONE;
  202006. #endif
  202007. /* save off the relevent information */
  202008. png_ptr->bit_depth = (png_byte)bit_depth;
  202009. png_ptr->color_type = (png_byte)color_type;
  202010. png_ptr->interlaced = (png_byte)interlace_type;
  202011. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  202012. png_ptr->filter_type = (png_byte)filter_type;
  202013. #endif
  202014. png_ptr->compression_type = (png_byte)compression_type;
  202015. png_ptr->width = width;
  202016. png_ptr->height = height;
  202017. png_ptr->pixel_depth = (png_byte)(bit_depth * png_ptr->channels);
  202018. png_ptr->rowbytes = PNG_ROWBYTES(png_ptr->pixel_depth, width);
  202019. /* set the usr info, so any transformations can modify it */
  202020. png_ptr->usr_width = png_ptr->width;
  202021. png_ptr->usr_bit_depth = png_ptr->bit_depth;
  202022. png_ptr->usr_channels = png_ptr->channels;
  202023. /* pack the header information into the buffer */
  202024. png_save_uint_32(buf, width);
  202025. png_save_uint_32(buf + 4, height);
  202026. buf[8] = (png_byte)bit_depth;
  202027. buf[9] = (png_byte)color_type;
  202028. buf[10] = (png_byte)compression_type;
  202029. buf[11] = (png_byte)filter_type;
  202030. buf[12] = (png_byte)interlace_type;
  202031. /* write the chunk */
  202032. png_write_chunk(png_ptr, png_IHDR, buf, (png_size_t)13);
  202033. /* initialize zlib with PNG info */
  202034. png_ptr->zstream.zalloc = png_zalloc;
  202035. png_ptr->zstream.zfree = png_zfree;
  202036. png_ptr->zstream.opaque = (voidpf)png_ptr;
  202037. if (!(png_ptr->do_filter))
  202038. {
  202039. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE ||
  202040. png_ptr->bit_depth < 8)
  202041. png_ptr->do_filter = PNG_FILTER_NONE;
  202042. else
  202043. png_ptr->do_filter = PNG_ALL_FILTERS;
  202044. }
  202045. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_STRATEGY))
  202046. {
  202047. if (png_ptr->do_filter != PNG_FILTER_NONE)
  202048. png_ptr->zlib_strategy = Z_FILTERED;
  202049. else
  202050. png_ptr->zlib_strategy = Z_DEFAULT_STRATEGY;
  202051. }
  202052. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_LEVEL))
  202053. png_ptr->zlib_level = Z_DEFAULT_COMPRESSION;
  202054. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_MEM_LEVEL))
  202055. png_ptr->zlib_mem_level = 8;
  202056. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_WINDOW_BITS))
  202057. png_ptr->zlib_window_bits = 15;
  202058. if (!(png_ptr->flags & PNG_FLAG_ZLIB_CUSTOM_METHOD))
  202059. png_ptr->zlib_method = 8;
  202060. if (deflateInit2(&png_ptr->zstream, png_ptr->zlib_level,
  202061. png_ptr->zlib_method, png_ptr->zlib_window_bits,
  202062. png_ptr->zlib_mem_level, png_ptr->zlib_strategy) != Z_OK)
  202063. png_error(png_ptr, "zlib failed to initialize compressor");
  202064. png_ptr->zstream.next_out = png_ptr->zbuf;
  202065. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  202066. /* libpng is not interested in zstream.data_type */
  202067. /* set it to a predefined value, to avoid its evaluation inside zlib */
  202068. png_ptr->zstream.data_type = Z_BINARY;
  202069. png_ptr->mode = PNG_HAVE_IHDR;
  202070. }
  202071. /* write the palette. We are careful not to trust png_color to be in the
  202072. * correct order for PNG, so people can redefine it to any convenient
  202073. * structure.
  202074. */
  202075. void /* PRIVATE */
  202076. png_write_PLTE(png_structp png_ptr, png_colorp palette, png_uint_32 num_pal)
  202077. {
  202078. #ifdef PNG_USE_LOCAL_ARRAYS
  202079. PNG_PLTE;
  202080. #endif
  202081. png_uint_32 i;
  202082. png_colorp pal_ptr;
  202083. png_byte buf[3];
  202084. png_debug(1, "in png_write_PLTE\n");
  202085. if ((
  202086. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  202087. !(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE) &&
  202088. #endif
  202089. num_pal == 0) || num_pal > 256)
  202090. {
  202091. if (png_ptr->color_type == PNG_COLOR_TYPE_PALETTE)
  202092. {
  202093. png_error(png_ptr, "Invalid number of colors in palette");
  202094. }
  202095. else
  202096. {
  202097. png_warning(png_ptr, "Invalid number of colors in palette");
  202098. return;
  202099. }
  202100. }
  202101. if (!(png_ptr->color_type&PNG_COLOR_MASK_COLOR))
  202102. {
  202103. png_warning(png_ptr,
  202104. "Ignoring request to write a PLTE chunk in grayscale PNG");
  202105. return;
  202106. }
  202107. png_ptr->num_palette = (png_uint_16)num_pal;
  202108. png_debug1(3, "num_palette = %d\n", png_ptr->num_palette);
  202109. png_write_chunk_start(png_ptr, png_PLTE, num_pal * 3);
  202110. #ifndef PNG_NO_POINTER_INDEXING
  202111. for (i = 0, pal_ptr = palette; i < num_pal; i++, pal_ptr++)
  202112. {
  202113. buf[0] = pal_ptr->red;
  202114. buf[1] = pal_ptr->green;
  202115. buf[2] = pal_ptr->blue;
  202116. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  202117. }
  202118. #else
  202119. /* This is a little slower but some buggy compilers need to do this instead */
  202120. pal_ptr=palette;
  202121. for (i = 0; i < num_pal; i++)
  202122. {
  202123. buf[0] = pal_ptr[i].red;
  202124. buf[1] = pal_ptr[i].green;
  202125. buf[2] = pal_ptr[i].blue;
  202126. png_write_chunk_data(png_ptr, buf, (png_size_t)3);
  202127. }
  202128. #endif
  202129. png_write_chunk_end(png_ptr);
  202130. png_ptr->mode |= PNG_HAVE_PLTE;
  202131. }
  202132. /* write an IDAT chunk */
  202133. void /* PRIVATE */
  202134. png_write_IDAT(png_structp png_ptr, png_bytep data, png_size_t length)
  202135. {
  202136. #ifdef PNG_USE_LOCAL_ARRAYS
  202137. PNG_IDAT;
  202138. #endif
  202139. png_debug(1, "in png_write_IDAT\n");
  202140. /* Optimize the CMF field in the zlib stream. */
  202141. /* This hack of the zlib stream is compliant to the stream specification. */
  202142. if (!(png_ptr->mode & PNG_HAVE_IDAT) &&
  202143. png_ptr->compression_type == PNG_COMPRESSION_TYPE_BASE)
  202144. {
  202145. unsigned int z_cmf = data[0]; /* zlib compression method and flags */
  202146. if ((z_cmf & 0x0f) == 8 && (z_cmf & 0xf0) <= 0x70)
  202147. {
  202148. /* Avoid memory underflows and multiplication overflows. */
  202149. /* The conditions below are practically always satisfied;
  202150. however, they still must be checked. */
  202151. if (length >= 2 &&
  202152. png_ptr->height < 16384 && png_ptr->width < 16384)
  202153. {
  202154. png_uint_32 uncompressed_idat_size = png_ptr->height *
  202155. ((png_ptr->width *
  202156. png_ptr->channels * png_ptr->bit_depth + 15) >> 3);
  202157. unsigned int z_cinfo = z_cmf >> 4;
  202158. unsigned int half_z_window_size = 1 << (z_cinfo + 7);
  202159. while (uncompressed_idat_size <= half_z_window_size &&
  202160. half_z_window_size >= 256)
  202161. {
  202162. z_cinfo--;
  202163. half_z_window_size >>= 1;
  202164. }
  202165. z_cmf = (z_cmf & 0x0f) | (z_cinfo << 4);
  202166. if (data[0] != (png_byte)z_cmf)
  202167. {
  202168. data[0] = (png_byte)z_cmf;
  202169. data[1] &= 0xe0;
  202170. data[1] += (png_byte)(0x1f - ((z_cmf << 8) + data[1]) % 0x1f);
  202171. }
  202172. }
  202173. }
  202174. else
  202175. png_error(png_ptr,
  202176. "Invalid zlib compression method or flags in IDAT");
  202177. }
  202178. png_write_chunk(png_ptr, png_IDAT, data, length);
  202179. png_ptr->mode |= PNG_HAVE_IDAT;
  202180. }
  202181. /* write an IEND chunk */
  202182. void /* PRIVATE */
  202183. png_write_IEND(png_structp png_ptr)
  202184. {
  202185. #ifdef PNG_USE_LOCAL_ARRAYS
  202186. PNG_IEND;
  202187. #endif
  202188. png_debug(1, "in png_write_IEND\n");
  202189. png_write_chunk(png_ptr, png_IEND, png_bytep_NULL,
  202190. (png_size_t)0);
  202191. png_ptr->mode |= PNG_HAVE_IEND;
  202192. }
  202193. #if defined(PNG_WRITE_gAMA_SUPPORTED)
  202194. /* write a gAMA chunk */
  202195. #ifdef PNG_FLOATING_POINT_SUPPORTED
  202196. void /* PRIVATE */
  202197. png_write_gAMA(png_structp png_ptr, double file_gamma)
  202198. {
  202199. #ifdef PNG_USE_LOCAL_ARRAYS
  202200. PNG_gAMA;
  202201. #endif
  202202. png_uint_32 igamma;
  202203. png_byte buf[4];
  202204. png_debug(1, "in png_write_gAMA\n");
  202205. /* file_gamma is saved in 1/100,000ths */
  202206. igamma = (png_uint_32)(file_gamma * 100000.0 + 0.5);
  202207. png_save_uint_32(buf, igamma);
  202208. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  202209. }
  202210. #endif
  202211. #ifdef PNG_FIXED_POINT_SUPPORTED
  202212. void /* PRIVATE */
  202213. png_write_gAMA_fixed(png_structp png_ptr, png_fixed_point file_gamma)
  202214. {
  202215. #ifdef PNG_USE_LOCAL_ARRAYS
  202216. PNG_gAMA;
  202217. #endif
  202218. png_byte buf[4];
  202219. png_debug(1, "in png_write_gAMA\n");
  202220. /* file_gamma is saved in 1/100,000ths */
  202221. png_save_uint_32(buf, (png_uint_32)file_gamma);
  202222. png_write_chunk(png_ptr, png_gAMA, buf, (png_size_t)4);
  202223. }
  202224. #endif
  202225. #endif
  202226. #if defined(PNG_WRITE_sRGB_SUPPORTED)
  202227. /* write a sRGB chunk */
  202228. void /* PRIVATE */
  202229. png_write_sRGB(png_structp png_ptr, int srgb_intent)
  202230. {
  202231. #ifdef PNG_USE_LOCAL_ARRAYS
  202232. PNG_sRGB;
  202233. #endif
  202234. png_byte buf[1];
  202235. png_debug(1, "in png_write_sRGB\n");
  202236. if(srgb_intent >= PNG_sRGB_INTENT_LAST)
  202237. png_warning(png_ptr,
  202238. "Invalid sRGB rendering intent specified");
  202239. buf[0]=(png_byte)srgb_intent;
  202240. png_write_chunk(png_ptr, png_sRGB, buf, (png_size_t)1);
  202241. }
  202242. #endif
  202243. #if defined(PNG_WRITE_iCCP_SUPPORTED)
  202244. /* write an iCCP chunk */
  202245. void /* PRIVATE */
  202246. png_write_iCCP(png_structp png_ptr, png_charp name, int compression_type,
  202247. png_charp profile, int profile_len)
  202248. {
  202249. #ifdef PNG_USE_LOCAL_ARRAYS
  202250. PNG_iCCP;
  202251. #endif
  202252. png_size_t name_len;
  202253. png_charp new_name;
  202254. compression_state comp;
  202255. int embedded_profile_len = 0;
  202256. png_debug(1, "in png_write_iCCP\n");
  202257. comp.num_output_ptr = 0;
  202258. comp.max_output_ptr = 0;
  202259. comp.output_ptr = NULL;
  202260. comp.input = NULL;
  202261. comp.input_len = 0;
  202262. if (name == NULL || (name_len = png_check_keyword(png_ptr, name,
  202263. &new_name)) == 0)
  202264. {
  202265. png_warning(png_ptr, "Empty keyword in iCCP chunk");
  202266. return;
  202267. }
  202268. if (compression_type != PNG_COMPRESSION_TYPE_BASE)
  202269. png_warning(png_ptr, "Unknown compression type in iCCP chunk");
  202270. if (profile == NULL)
  202271. profile_len = 0;
  202272. if (profile_len > 3)
  202273. embedded_profile_len =
  202274. ((*( (png_bytep)profile ))<<24) |
  202275. ((*( (png_bytep)profile+1))<<16) |
  202276. ((*( (png_bytep)profile+2))<< 8) |
  202277. ((*( (png_bytep)profile+3)) );
  202278. if (profile_len < embedded_profile_len)
  202279. {
  202280. png_warning(png_ptr,
  202281. "Embedded profile length too large in iCCP chunk");
  202282. return;
  202283. }
  202284. if (profile_len > embedded_profile_len)
  202285. {
  202286. png_warning(png_ptr,
  202287. "Truncating profile to actual length in iCCP chunk");
  202288. profile_len = embedded_profile_len;
  202289. }
  202290. if (profile_len)
  202291. profile_len = png_text_compress(png_ptr, profile, (png_size_t)profile_len,
  202292. PNG_COMPRESSION_TYPE_BASE, &comp);
  202293. /* make sure we include the NULL after the name and the compression type */
  202294. png_write_chunk_start(png_ptr, png_iCCP,
  202295. (png_uint_32)name_len+profile_len+2);
  202296. new_name[name_len+1]=0x00;
  202297. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 2);
  202298. if (profile_len)
  202299. png_write_compressed_data_out(png_ptr, &comp);
  202300. png_write_chunk_end(png_ptr);
  202301. png_free(png_ptr, new_name);
  202302. }
  202303. #endif
  202304. #if defined(PNG_WRITE_sPLT_SUPPORTED)
  202305. /* write a sPLT chunk */
  202306. void /* PRIVATE */
  202307. png_write_sPLT(png_structp png_ptr, png_sPLT_tp spalette)
  202308. {
  202309. #ifdef PNG_USE_LOCAL_ARRAYS
  202310. PNG_sPLT;
  202311. #endif
  202312. png_size_t name_len;
  202313. png_charp new_name;
  202314. png_byte entrybuf[10];
  202315. int entry_size = (spalette->depth == 8 ? 6 : 10);
  202316. int palette_size = entry_size * spalette->nentries;
  202317. png_sPLT_entryp ep;
  202318. #ifdef PNG_NO_POINTER_INDEXING
  202319. int i;
  202320. #endif
  202321. png_debug(1, "in png_write_sPLT\n");
  202322. if (spalette->name == NULL || (name_len = png_check_keyword(png_ptr,
  202323. spalette->name, &new_name))==0)
  202324. {
  202325. png_warning(png_ptr, "Empty keyword in sPLT chunk");
  202326. return;
  202327. }
  202328. /* make sure we include the NULL after the name */
  202329. png_write_chunk_start(png_ptr, png_sPLT,
  202330. (png_uint_32)(name_len + 2 + palette_size));
  202331. png_write_chunk_data(png_ptr, (png_bytep)new_name, name_len + 1);
  202332. png_write_chunk_data(png_ptr, (png_bytep)&spalette->depth, 1);
  202333. /* loop through each palette entry, writing appropriately */
  202334. #ifndef PNG_NO_POINTER_INDEXING
  202335. for (ep = spalette->entries; ep<spalette->entries+spalette->nentries; ep++)
  202336. {
  202337. if (spalette->depth == 8)
  202338. {
  202339. entrybuf[0] = (png_byte)ep->red;
  202340. entrybuf[1] = (png_byte)ep->green;
  202341. entrybuf[2] = (png_byte)ep->blue;
  202342. entrybuf[3] = (png_byte)ep->alpha;
  202343. png_save_uint_16(entrybuf + 4, ep->frequency);
  202344. }
  202345. else
  202346. {
  202347. png_save_uint_16(entrybuf + 0, ep->red);
  202348. png_save_uint_16(entrybuf + 2, ep->green);
  202349. png_save_uint_16(entrybuf + 4, ep->blue);
  202350. png_save_uint_16(entrybuf + 6, ep->alpha);
  202351. png_save_uint_16(entrybuf + 8, ep->frequency);
  202352. }
  202353. png_write_chunk_data(png_ptr, entrybuf, (png_size_t)entry_size);
  202354. }
  202355. #else
  202356. ep=spalette->entries;
  202357. for (i=0; i>spalette->nentries; i++)
  202358. {
  202359. if (spalette->depth == 8)
  202360. {
  202361. entrybuf[0] = (png_byte)ep[i].red;
  202362. entrybuf[1] = (png_byte)ep[i].green;
  202363. entrybuf[2] = (png_byte)ep[i].blue;
  202364. entrybuf[3] = (png_byte)ep[i].alpha;
  202365. png_save_uint_16(entrybuf + 4, ep[i].frequency);
  202366. }
  202367. else
  202368. {
  202369. png_save_uint_16(entrybuf + 0, ep[i].red);
  202370. png_save_uint_16(entrybuf + 2, ep[i].green);
  202371. png_save_uint_16(entrybuf + 4, ep[i].blue);
  202372. png_save_uint_16(entrybuf + 6, ep[i].alpha);
  202373. png_save_uint_16(entrybuf + 8, ep[i].frequency);
  202374. }
  202375. png_write_chunk_data(png_ptr, entrybuf, entry_size);
  202376. }
  202377. #endif
  202378. png_write_chunk_end(png_ptr);
  202379. png_free(png_ptr, new_name);
  202380. }
  202381. #endif
  202382. #if defined(PNG_WRITE_sBIT_SUPPORTED)
  202383. /* write the sBIT chunk */
  202384. void /* PRIVATE */
  202385. png_write_sBIT(png_structp png_ptr, png_color_8p sbit, int color_type)
  202386. {
  202387. #ifdef PNG_USE_LOCAL_ARRAYS
  202388. PNG_sBIT;
  202389. #endif
  202390. png_byte buf[4];
  202391. png_size_t size;
  202392. png_debug(1, "in png_write_sBIT\n");
  202393. /* make sure we don't depend upon the order of PNG_COLOR_8 */
  202394. if (color_type & PNG_COLOR_MASK_COLOR)
  202395. {
  202396. png_byte maxbits;
  202397. maxbits = (png_byte)(color_type==PNG_COLOR_TYPE_PALETTE ? 8 :
  202398. png_ptr->usr_bit_depth);
  202399. if (sbit->red == 0 || sbit->red > maxbits ||
  202400. sbit->green == 0 || sbit->green > maxbits ||
  202401. sbit->blue == 0 || sbit->blue > maxbits)
  202402. {
  202403. png_warning(png_ptr, "Invalid sBIT depth specified");
  202404. return;
  202405. }
  202406. buf[0] = sbit->red;
  202407. buf[1] = sbit->green;
  202408. buf[2] = sbit->blue;
  202409. size = 3;
  202410. }
  202411. else
  202412. {
  202413. if (sbit->gray == 0 || sbit->gray > png_ptr->usr_bit_depth)
  202414. {
  202415. png_warning(png_ptr, "Invalid sBIT depth specified");
  202416. return;
  202417. }
  202418. buf[0] = sbit->gray;
  202419. size = 1;
  202420. }
  202421. if (color_type & PNG_COLOR_MASK_ALPHA)
  202422. {
  202423. if (sbit->alpha == 0 || sbit->alpha > png_ptr->usr_bit_depth)
  202424. {
  202425. png_warning(png_ptr, "Invalid sBIT depth specified");
  202426. return;
  202427. }
  202428. buf[size++] = sbit->alpha;
  202429. }
  202430. png_write_chunk(png_ptr, png_sBIT, buf, size);
  202431. }
  202432. #endif
  202433. #if defined(PNG_WRITE_cHRM_SUPPORTED)
  202434. /* write the cHRM chunk */
  202435. #ifdef PNG_FLOATING_POINT_SUPPORTED
  202436. void /* PRIVATE */
  202437. png_write_cHRM(png_structp png_ptr, double white_x, double white_y,
  202438. double red_x, double red_y, double green_x, double green_y,
  202439. double blue_x, double blue_y)
  202440. {
  202441. #ifdef PNG_USE_LOCAL_ARRAYS
  202442. PNG_cHRM;
  202443. #endif
  202444. png_byte buf[32];
  202445. png_uint_32 itemp;
  202446. png_debug(1, "in png_write_cHRM\n");
  202447. /* each value is saved in 1/100,000ths */
  202448. if (white_x < 0 || white_x > 0.8 || white_y < 0 || white_y > 0.8 ||
  202449. white_x + white_y > 1.0)
  202450. {
  202451. png_warning(png_ptr, "Invalid cHRM white point specified");
  202452. #if !defined(PNG_NO_CONSOLE_IO)
  202453. fprintf(stderr,"white_x=%f, white_y=%f\n",white_x, white_y);
  202454. #endif
  202455. return;
  202456. }
  202457. itemp = (png_uint_32)(white_x * 100000.0 + 0.5);
  202458. png_save_uint_32(buf, itemp);
  202459. itemp = (png_uint_32)(white_y * 100000.0 + 0.5);
  202460. png_save_uint_32(buf + 4, itemp);
  202461. if (red_x < 0 || red_y < 0 || red_x + red_y > 1.0)
  202462. {
  202463. png_warning(png_ptr, "Invalid cHRM red point specified");
  202464. return;
  202465. }
  202466. itemp = (png_uint_32)(red_x * 100000.0 + 0.5);
  202467. png_save_uint_32(buf + 8, itemp);
  202468. itemp = (png_uint_32)(red_y * 100000.0 + 0.5);
  202469. png_save_uint_32(buf + 12, itemp);
  202470. if (green_x < 0 || green_y < 0 || green_x + green_y > 1.0)
  202471. {
  202472. png_warning(png_ptr, "Invalid cHRM green point specified");
  202473. return;
  202474. }
  202475. itemp = (png_uint_32)(green_x * 100000.0 + 0.5);
  202476. png_save_uint_32(buf + 16, itemp);
  202477. itemp = (png_uint_32)(green_y * 100000.0 + 0.5);
  202478. png_save_uint_32(buf + 20, itemp);
  202479. if (blue_x < 0 || blue_y < 0 || blue_x + blue_y > 1.0)
  202480. {
  202481. png_warning(png_ptr, "Invalid cHRM blue point specified");
  202482. return;
  202483. }
  202484. itemp = (png_uint_32)(blue_x * 100000.0 + 0.5);
  202485. png_save_uint_32(buf + 24, itemp);
  202486. itemp = (png_uint_32)(blue_y * 100000.0 + 0.5);
  202487. png_save_uint_32(buf + 28, itemp);
  202488. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  202489. }
  202490. #endif
  202491. #ifdef PNG_FIXED_POINT_SUPPORTED
  202492. void /* PRIVATE */
  202493. png_write_cHRM_fixed(png_structp png_ptr, png_fixed_point white_x,
  202494. png_fixed_point white_y, png_fixed_point red_x, png_fixed_point red_y,
  202495. png_fixed_point green_x, png_fixed_point green_y, png_fixed_point blue_x,
  202496. png_fixed_point blue_y)
  202497. {
  202498. #ifdef PNG_USE_LOCAL_ARRAYS
  202499. PNG_cHRM;
  202500. #endif
  202501. png_byte buf[32];
  202502. png_debug(1, "in png_write_cHRM\n");
  202503. /* each value is saved in 1/100,000ths */
  202504. if (white_x > 80000L || white_y > 80000L || white_x + white_y > 100000L)
  202505. {
  202506. png_warning(png_ptr, "Invalid fixed cHRM white point specified");
  202507. #if !defined(PNG_NO_CONSOLE_IO)
  202508. fprintf(stderr,"white_x=%ld, white_y=%ld\n",white_x, white_y);
  202509. #endif
  202510. return;
  202511. }
  202512. png_save_uint_32(buf, (png_uint_32)white_x);
  202513. png_save_uint_32(buf + 4, (png_uint_32)white_y);
  202514. if (red_x + red_y > 100000L)
  202515. {
  202516. png_warning(png_ptr, "Invalid cHRM fixed red point specified");
  202517. return;
  202518. }
  202519. png_save_uint_32(buf + 8, (png_uint_32)red_x);
  202520. png_save_uint_32(buf + 12, (png_uint_32)red_y);
  202521. if (green_x + green_y > 100000L)
  202522. {
  202523. png_warning(png_ptr, "Invalid fixed cHRM green point specified");
  202524. return;
  202525. }
  202526. png_save_uint_32(buf + 16, (png_uint_32)green_x);
  202527. png_save_uint_32(buf + 20, (png_uint_32)green_y);
  202528. if (blue_x + blue_y > 100000L)
  202529. {
  202530. png_warning(png_ptr, "Invalid fixed cHRM blue point specified");
  202531. return;
  202532. }
  202533. png_save_uint_32(buf + 24, (png_uint_32)blue_x);
  202534. png_save_uint_32(buf + 28, (png_uint_32)blue_y);
  202535. png_write_chunk(png_ptr, png_cHRM, buf, (png_size_t)32);
  202536. }
  202537. #endif
  202538. #endif
  202539. #if defined(PNG_WRITE_tRNS_SUPPORTED)
  202540. /* write the tRNS chunk */
  202541. void /* PRIVATE */
  202542. png_write_tRNS(png_structp png_ptr, png_bytep trans, png_color_16p tran,
  202543. int num_trans, int color_type)
  202544. {
  202545. #ifdef PNG_USE_LOCAL_ARRAYS
  202546. PNG_tRNS;
  202547. #endif
  202548. png_byte buf[6];
  202549. png_debug(1, "in png_write_tRNS\n");
  202550. if (color_type == PNG_COLOR_TYPE_PALETTE)
  202551. {
  202552. if (num_trans <= 0 || num_trans > (int)png_ptr->num_palette)
  202553. {
  202554. png_warning(png_ptr,"Invalid number of transparent colors specified");
  202555. return;
  202556. }
  202557. /* write the chunk out as it is */
  202558. png_write_chunk(png_ptr, png_tRNS, trans, (png_size_t)num_trans);
  202559. }
  202560. else if (color_type == PNG_COLOR_TYPE_GRAY)
  202561. {
  202562. /* one 16 bit value */
  202563. if(tran->gray >= (1 << png_ptr->bit_depth))
  202564. {
  202565. png_warning(png_ptr,
  202566. "Ignoring attempt to write tRNS chunk out-of-range for bit_depth");
  202567. return;
  202568. }
  202569. png_save_uint_16(buf, tran->gray);
  202570. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)2);
  202571. }
  202572. else if (color_type == PNG_COLOR_TYPE_RGB)
  202573. {
  202574. /* three 16 bit values */
  202575. png_save_uint_16(buf, tran->red);
  202576. png_save_uint_16(buf + 2, tran->green);
  202577. png_save_uint_16(buf + 4, tran->blue);
  202578. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  202579. {
  202580. png_warning(png_ptr,
  202581. "Ignoring attempt to write 16-bit tRNS chunk when bit_depth is 8");
  202582. return;
  202583. }
  202584. png_write_chunk(png_ptr, png_tRNS, buf, (png_size_t)6);
  202585. }
  202586. else
  202587. {
  202588. png_warning(png_ptr, "Can't write tRNS with an alpha channel");
  202589. }
  202590. }
  202591. #endif
  202592. #if defined(PNG_WRITE_bKGD_SUPPORTED)
  202593. /* write the background chunk */
  202594. void /* PRIVATE */
  202595. png_write_bKGD(png_structp png_ptr, png_color_16p back, int color_type)
  202596. {
  202597. #ifdef PNG_USE_LOCAL_ARRAYS
  202598. PNG_bKGD;
  202599. #endif
  202600. png_byte buf[6];
  202601. png_debug(1, "in png_write_bKGD\n");
  202602. if (color_type == PNG_COLOR_TYPE_PALETTE)
  202603. {
  202604. if (
  202605. #if defined(PNG_MNG_FEATURES_SUPPORTED)
  202606. (png_ptr->num_palette ||
  202607. (!(png_ptr->mng_features_permitted & PNG_FLAG_MNG_EMPTY_PLTE))) &&
  202608. #endif
  202609. back->index > png_ptr->num_palette)
  202610. {
  202611. png_warning(png_ptr, "Invalid background palette index");
  202612. return;
  202613. }
  202614. buf[0] = back->index;
  202615. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)1);
  202616. }
  202617. else if (color_type & PNG_COLOR_MASK_COLOR)
  202618. {
  202619. png_save_uint_16(buf, back->red);
  202620. png_save_uint_16(buf + 2, back->green);
  202621. png_save_uint_16(buf + 4, back->blue);
  202622. if(png_ptr->bit_depth == 8 && (buf[0] | buf[2] | buf[4]))
  202623. {
  202624. png_warning(png_ptr,
  202625. "Ignoring attempt to write 16-bit bKGD chunk when bit_depth is 8");
  202626. return;
  202627. }
  202628. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)6);
  202629. }
  202630. else
  202631. {
  202632. if(back->gray >= (1 << png_ptr->bit_depth))
  202633. {
  202634. png_warning(png_ptr,
  202635. "Ignoring attempt to write bKGD chunk out-of-range for bit_depth");
  202636. return;
  202637. }
  202638. png_save_uint_16(buf, back->gray);
  202639. png_write_chunk(png_ptr, png_bKGD, buf, (png_size_t)2);
  202640. }
  202641. }
  202642. #endif
  202643. #if defined(PNG_WRITE_hIST_SUPPORTED)
  202644. /* write the histogram */
  202645. void /* PRIVATE */
  202646. png_write_hIST(png_structp png_ptr, png_uint_16p hist, int num_hist)
  202647. {
  202648. #ifdef PNG_USE_LOCAL_ARRAYS
  202649. PNG_hIST;
  202650. #endif
  202651. int i;
  202652. png_byte buf[3];
  202653. png_debug(1, "in png_write_hIST\n");
  202654. if (num_hist > (int)png_ptr->num_palette)
  202655. {
  202656. png_debug2(3, "num_hist = %d, num_palette = %d\n", num_hist,
  202657. png_ptr->num_palette);
  202658. png_warning(png_ptr, "Invalid number of histogram entries specified");
  202659. return;
  202660. }
  202661. png_write_chunk_start(png_ptr, png_hIST, (png_uint_32)(num_hist * 2));
  202662. for (i = 0; i < num_hist; i++)
  202663. {
  202664. png_save_uint_16(buf, hist[i]);
  202665. png_write_chunk_data(png_ptr, buf, (png_size_t)2);
  202666. }
  202667. png_write_chunk_end(png_ptr);
  202668. }
  202669. #endif
  202670. #if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
  202671. defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
  202672. /* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
  202673. * and if invalid, correct the keyword rather than discarding the entire
  202674. * chunk. The PNG 1.0 specification requires keywords 1-79 characters in
  202675. * length, forbids leading or trailing whitespace, multiple internal spaces,
  202676. * and the non-break space (0x80) from ISO 8859-1. Returns keyword length.
  202677. *
  202678. * The new_key is allocated to hold the corrected keyword and must be freed
  202679. * by the calling routine. This avoids problems with trying to write to
  202680. * static keywords without having to have duplicate copies of the strings.
  202681. */
  202682. png_size_t /* PRIVATE */
  202683. png_check_keyword(png_structp png_ptr, png_charp key, png_charpp new_key)
  202684. {
  202685. png_size_t key_len;
  202686. png_charp kp, dp;
  202687. int kflag;
  202688. int kwarn=0;
  202689. png_debug(1, "in png_check_keyword\n");
  202690. *new_key = NULL;
  202691. if (key == NULL || (key_len = png_strlen(key)) == 0)
  202692. {
  202693. png_warning(png_ptr, "zero length keyword");
  202694. return ((png_size_t)0);
  202695. }
  202696. png_debug1(2, "Keyword to be checked is '%s'\n", key);
  202697. *new_key = (png_charp)png_malloc_warn(png_ptr, (png_uint_32)(key_len + 2));
  202698. if (*new_key == NULL)
  202699. {
  202700. png_warning(png_ptr, "Out of memory while procesing keyword");
  202701. return ((png_size_t)0);
  202702. }
  202703. /* Replace non-printing characters with a blank and print a warning */
  202704. for (kp = key, dp = *new_key; *kp != '\0'; kp++, dp++)
  202705. {
  202706. if ((png_byte)*kp < 0x20 ||
  202707. ((png_byte)*kp > 0x7E && (png_byte)*kp < 0xA1))
  202708. {
  202709. #if !defined(PNG_NO_STDIO) && !defined(_WIN32_WCE)
  202710. char msg[40];
  202711. png_snprintf(msg, 40,
  202712. "invalid keyword character 0x%02X", (png_byte)*kp);
  202713. png_warning(png_ptr, msg);
  202714. #else
  202715. png_warning(png_ptr, "invalid character in keyword");
  202716. #endif
  202717. *dp = ' ';
  202718. }
  202719. else
  202720. {
  202721. *dp = *kp;
  202722. }
  202723. }
  202724. *dp = '\0';
  202725. /* Remove any trailing white space. */
  202726. kp = *new_key + key_len - 1;
  202727. if (*kp == ' ')
  202728. {
  202729. png_warning(png_ptr, "trailing spaces removed from keyword");
  202730. while (*kp == ' ')
  202731. {
  202732. *(kp--) = '\0';
  202733. key_len--;
  202734. }
  202735. }
  202736. /* Remove any leading white space. */
  202737. kp = *new_key;
  202738. if (*kp == ' ')
  202739. {
  202740. png_warning(png_ptr, "leading spaces removed from keyword");
  202741. while (*kp == ' ')
  202742. {
  202743. kp++;
  202744. key_len--;
  202745. }
  202746. }
  202747. png_debug1(2, "Checking for multiple internal spaces in '%s'\n", kp);
  202748. /* Remove multiple internal spaces. */
  202749. for (kflag = 0, dp = *new_key; *kp != '\0'; kp++)
  202750. {
  202751. if (*kp == ' ' && kflag == 0)
  202752. {
  202753. *(dp++) = *kp;
  202754. kflag = 1;
  202755. }
  202756. else if (*kp == ' ')
  202757. {
  202758. key_len--;
  202759. kwarn=1;
  202760. }
  202761. else
  202762. {
  202763. *(dp++) = *kp;
  202764. kflag = 0;
  202765. }
  202766. }
  202767. *dp = '\0';
  202768. if(kwarn)
  202769. png_warning(png_ptr, "extra interior spaces removed from keyword");
  202770. if (key_len == 0)
  202771. {
  202772. png_free(png_ptr, *new_key);
  202773. *new_key=NULL;
  202774. png_warning(png_ptr, "Zero length keyword");
  202775. }
  202776. if (key_len > 79)
  202777. {
  202778. png_warning(png_ptr, "keyword length must be 1 - 79 characters");
  202779. new_key[79] = '\0';
  202780. key_len = 79;
  202781. }
  202782. return (key_len);
  202783. }
  202784. #endif
  202785. #if defined(PNG_WRITE_tEXt_SUPPORTED)
  202786. /* write a tEXt chunk */
  202787. void /* PRIVATE */
  202788. png_write_tEXt(png_structp png_ptr, png_charp key, png_charp text,
  202789. png_size_t text_len)
  202790. {
  202791. #ifdef PNG_USE_LOCAL_ARRAYS
  202792. PNG_tEXt;
  202793. #endif
  202794. png_size_t key_len;
  202795. png_charp new_key;
  202796. png_debug(1, "in png_write_tEXt\n");
  202797. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202798. {
  202799. png_warning(png_ptr, "Empty keyword in tEXt chunk");
  202800. return;
  202801. }
  202802. if (text == NULL || *text == '\0')
  202803. text_len = 0;
  202804. else
  202805. text_len = png_strlen(text);
  202806. /* make sure we include the 0 after the key */
  202807. png_write_chunk_start(png_ptr, png_tEXt, (png_uint_32)key_len+text_len+1);
  202808. /*
  202809. * We leave it to the application to meet PNG-1.0 requirements on the
  202810. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202811. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202812. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202813. */
  202814. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202815. if (text_len)
  202816. png_write_chunk_data(png_ptr, (png_bytep)text, text_len);
  202817. png_write_chunk_end(png_ptr);
  202818. png_free(png_ptr, new_key);
  202819. }
  202820. #endif
  202821. #if defined(PNG_WRITE_zTXt_SUPPORTED)
  202822. /* write a compressed text chunk */
  202823. void /* PRIVATE */
  202824. png_write_zTXt(png_structp png_ptr, png_charp key, png_charp text,
  202825. png_size_t text_len, int compression)
  202826. {
  202827. #ifdef PNG_USE_LOCAL_ARRAYS
  202828. PNG_zTXt;
  202829. #endif
  202830. png_size_t key_len;
  202831. char buf[1];
  202832. png_charp new_key;
  202833. compression_state comp;
  202834. png_debug(1, "in png_write_zTXt\n");
  202835. comp.num_output_ptr = 0;
  202836. comp.max_output_ptr = 0;
  202837. comp.output_ptr = NULL;
  202838. comp.input = NULL;
  202839. comp.input_len = 0;
  202840. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202841. {
  202842. png_warning(png_ptr, "Empty keyword in zTXt chunk");
  202843. return;
  202844. }
  202845. if (text == NULL || *text == '\0' || compression==PNG_TEXT_COMPRESSION_NONE)
  202846. {
  202847. png_write_tEXt(png_ptr, new_key, text, (png_size_t)0);
  202848. png_free(png_ptr, new_key);
  202849. return;
  202850. }
  202851. text_len = png_strlen(text);
  202852. /* compute the compressed data; do it now for the length */
  202853. text_len = png_text_compress(png_ptr, text, text_len, compression,
  202854. &comp);
  202855. /* write start of chunk */
  202856. png_write_chunk_start(png_ptr, png_zTXt, (png_uint_32)
  202857. (key_len+text_len+2));
  202858. /* write key */
  202859. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202860. png_free(png_ptr, new_key);
  202861. buf[0] = (png_byte)compression;
  202862. /* write compression */
  202863. png_write_chunk_data(png_ptr, (png_bytep)buf, (png_size_t)1);
  202864. /* write the compressed data */
  202865. png_write_compressed_data_out(png_ptr, &comp);
  202866. /* close the chunk */
  202867. png_write_chunk_end(png_ptr);
  202868. }
  202869. #endif
  202870. #if defined(PNG_WRITE_iTXt_SUPPORTED)
  202871. /* write an iTXt chunk */
  202872. void /* PRIVATE */
  202873. png_write_iTXt(png_structp png_ptr, int compression, png_charp key,
  202874. png_charp lang, png_charp lang_key, png_charp text)
  202875. {
  202876. #ifdef PNG_USE_LOCAL_ARRAYS
  202877. PNG_iTXt;
  202878. #endif
  202879. png_size_t lang_len, key_len, lang_key_len, text_len;
  202880. png_charp new_lang, new_key;
  202881. png_byte cbuf[2];
  202882. compression_state comp;
  202883. png_debug(1, "in png_write_iTXt\n");
  202884. comp.num_output_ptr = 0;
  202885. comp.max_output_ptr = 0;
  202886. comp.output_ptr = NULL;
  202887. comp.input = NULL;
  202888. if (key == NULL || (key_len = png_check_keyword(png_ptr, key, &new_key))==0)
  202889. {
  202890. png_warning(png_ptr, "Empty keyword in iTXt chunk");
  202891. return;
  202892. }
  202893. if (lang == NULL || (lang_len = png_check_keyword(png_ptr, lang, &new_lang))==0)
  202894. {
  202895. png_warning(png_ptr, "Empty language field in iTXt chunk");
  202896. new_lang = NULL;
  202897. lang_len = 0;
  202898. }
  202899. if (lang_key == NULL)
  202900. lang_key_len = 0;
  202901. else
  202902. lang_key_len = png_strlen(lang_key);
  202903. if (text == NULL)
  202904. text_len = 0;
  202905. else
  202906. text_len = png_strlen(text);
  202907. /* compute the compressed data; do it now for the length */
  202908. text_len = png_text_compress(png_ptr, text, text_len, compression-2,
  202909. &comp);
  202910. /* make sure we include the compression flag, the compression byte,
  202911. * and the NULs after the key, lang, and lang_key parts */
  202912. png_write_chunk_start(png_ptr, png_iTXt,
  202913. (png_uint_32)(
  202914. 5 /* comp byte, comp flag, terminators for key, lang and lang_key */
  202915. + key_len
  202916. + lang_len
  202917. + lang_key_len
  202918. + text_len));
  202919. /*
  202920. * We leave it to the application to meet PNG-1.0 requirements on the
  202921. * contents of the text. PNG-1.0 through PNG-1.2 discourage the use of
  202922. * any non-Latin-1 characters except for NEWLINE. ISO PNG will forbid them.
  202923. * The NUL character is forbidden by PNG-1.0 through PNG-1.2 and ISO PNG.
  202924. */
  202925. png_write_chunk_data(png_ptr, (png_bytep)new_key, key_len + 1);
  202926. /* set the compression flag */
  202927. if (compression == PNG_ITXT_COMPRESSION_NONE || \
  202928. compression == PNG_TEXT_COMPRESSION_NONE)
  202929. cbuf[0] = 0;
  202930. else /* compression == PNG_ITXT_COMPRESSION_zTXt */
  202931. cbuf[0] = 1;
  202932. /* set the compression method */
  202933. cbuf[1] = 0;
  202934. png_write_chunk_data(png_ptr, cbuf, 2);
  202935. cbuf[0] = 0;
  202936. png_write_chunk_data(png_ptr, (new_lang ? (png_bytep)new_lang : cbuf), lang_len + 1);
  202937. png_write_chunk_data(png_ptr, (lang_key ? (png_bytep)lang_key : cbuf), lang_key_len + 1);
  202938. png_write_compressed_data_out(png_ptr, &comp);
  202939. png_write_chunk_end(png_ptr);
  202940. png_free(png_ptr, new_key);
  202941. if (new_lang)
  202942. png_free(png_ptr, new_lang);
  202943. }
  202944. #endif
  202945. #if defined(PNG_WRITE_oFFs_SUPPORTED)
  202946. /* write the oFFs chunk */
  202947. void /* PRIVATE */
  202948. png_write_oFFs(png_structp png_ptr, png_int_32 x_offset, png_int_32 y_offset,
  202949. int unit_type)
  202950. {
  202951. #ifdef PNG_USE_LOCAL_ARRAYS
  202952. PNG_oFFs;
  202953. #endif
  202954. png_byte buf[9];
  202955. png_debug(1, "in png_write_oFFs\n");
  202956. if (unit_type >= PNG_OFFSET_LAST)
  202957. png_warning(png_ptr, "Unrecognized unit type for oFFs chunk");
  202958. png_save_int_32(buf, x_offset);
  202959. png_save_int_32(buf + 4, y_offset);
  202960. buf[8] = (png_byte)unit_type;
  202961. png_write_chunk(png_ptr, png_oFFs, buf, (png_size_t)9);
  202962. }
  202963. #endif
  202964. #if defined(PNG_WRITE_pCAL_SUPPORTED)
  202965. /* write the pCAL chunk (described in the PNG extensions document) */
  202966. void /* PRIVATE */
  202967. png_write_pCAL(png_structp png_ptr, png_charp purpose, png_int_32 X0,
  202968. png_int_32 X1, int type, int nparams, png_charp units, png_charpp params)
  202969. {
  202970. #ifdef PNG_USE_LOCAL_ARRAYS
  202971. PNG_pCAL;
  202972. #endif
  202973. png_size_t purpose_len, units_len, total_len;
  202974. png_uint_32p params_len;
  202975. png_byte buf[10];
  202976. png_charp new_purpose;
  202977. int i;
  202978. png_debug1(1, "in png_write_pCAL (%d parameters)\n", nparams);
  202979. if (type >= PNG_EQUATION_LAST)
  202980. png_warning(png_ptr, "Unrecognized equation type for pCAL chunk");
  202981. purpose_len = png_check_keyword(png_ptr, purpose, &new_purpose) + 1;
  202982. png_debug1(3, "pCAL purpose length = %d\n", (int)purpose_len);
  202983. units_len = png_strlen(units) + (nparams == 0 ? 0 : 1);
  202984. png_debug1(3, "pCAL units length = %d\n", (int)units_len);
  202985. total_len = purpose_len + units_len + 10;
  202986. params_len = (png_uint_32p)png_malloc(png_ptr, (png_uint_32)(nparams
  202987. *png_sizeof(png_uint_32)));
  202988. /* Find the length of each parameter, making sure we don't count the
  202989. null terminator for the last parameter. */
  202990. for (i = 0; i < nparams; i++)
  202991. {
  202992. params_len[i] = png_strlen(params[i]) + (i == nparams - 1 ? 0 : 1);
  202993. png_debug2(3, "pCAL parameter %d length = %lu\n", i, params_len[i]);
  202994. total_len += (png_size_t)params_len[i];
  202995. }
  202996. png_debug1(3, "pCAL total length = %d\n", (int)total_len);
  202997. png_write_chunk_start(png_ptr, png_pCAL, (png_uint_32)total_len);
  202998. png_write_chunk_data(png_ptr, (png_bytep)new_purpose, purpose_len);
  202999. png_save_int_32(buf, X0);
  203000. png_save_int_32(buf + 4, X1);
  203001. buf[8] = (png_byte)type;
  203002. buf[9] = (png_byte)nparams;
  203003. png_write_chunk_data(png_ptr, buf, (png_size_t)10);
  203004. png_write_chunk_data(png_ptr, (png_bytep)units, (png_size_t)units_len);
  203005. png_free(png_ptr, new_purpose);
  203006. for (i = 0; i < nparams; i++)
  203007. {
  203008. png_write_chunk_data(png_ptr, (png_bytep)params[i],
  203009. (png_size_t)params_len[i]);
  203010. }
  203011. png_free(png_ptr, params_len);
  203012. png_write_chunk_end(png_ptr);
  203013. }
  203014. #endif
  203015. #if defined(PNG_WRITE_sCAL_SUPPORTED)
  203016. /* write the sCAL chunk */
  203017. #if defined(PNG_FLOATING_POINT_SUPPORTED) && !defined(PNG_NO_STDIO)
  203018. void /* PRIVATE */
  203019. png_write_sCAL(png_structp png_ptr, int unit, double width, double height)
  203020. {
  203021. #ifdef PNG_USE_LOCAL_ARRAYS
  203022. PNG_sCAL;
  203023. #endif
  203024. char buf[64];
  203025. png_size_t total_len;
  203026. png_debug(1, "in png_write_sCAL\n");
  203027. buf[0] = (char)unit;
  203028. #if defined(_WIN32_WCE)
  203029. /* sprintf() function is not supported on WindowsCE */
  203030. {
  203031. wchar_t wc_buf[32];
  203032. size_t wc_len;
  203033. swprintf(wc_buf, TEXT("%12.12e"), width);
  203034. wc_len = wcslen(wc_buf);
  203035. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + 1, wc_len, NULL, NULL);
  203036. total_len = wc_len + 2;
  203037. swprintf(wc_buf, TEXT("%12.12e"), height);
  203038. wc_len = wcslen(wc_buf);
  203039. WideCharToMultiByte(CP_ACP, 0, wc_buf, -1, buf + total_len, wc_len,
  203040. NULL, NULL);
  203041. total_len += wc_len;
  203042. }
  203043. #else
  203044. png_snprintf(buf + 1, 63, "%12.12e", width);
  203045. total_len = 1 + png_strlen(buf + 1) + 1;
  203046. png_snprintf(buf + total_len, 64-total_len, "%12.12e", height);
  203047. total_len += png_strlen(buf + total_len);
  203048. #endif
  203049. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  203050. png_write_chunk(png_ptr, png_sCAL, (png_bytep)buf, total_len);
  203051. }
  203052. #else
  203053. #ifdef PNG_FIXED_POINT_SUPPORTED
  203054. void /* PRIVATE */
  203055. png_write_sCAL_s(png_structp png_ptr, int unit, png_charp width,
  203056. png_charp height)
  203057. {
  203058. #ifdef PNG_USE_LOCAL_ARRAYS
  203059. PNG_sCAL;
  203060. #endif
  203061. png_byte buf[64];
  203062. png_size_t wlen, hlen, total_len;
  203063. png_debug(1, "in png_write_sCAL_s\n");
  203064. wlen = png_strlen(width);
  203065. hlen = png_strlen(height);
  203066. total_len = wlen + hlen + 2;
  203067. if (total_len > 64)
  203068. {
  203069. png_warning(png_ptr, "Can't write sCAL (buffer too small)");
  203070. return;
  203071. }
  203072. buf[0] = (png_byte)unit;
  203073. png_memcpy(buf + 1, width, wlen + 1); /* append the '\0' here */
  203074. png_memcpy(buf + wlen + 2, height, hlen); /* do NOT append the '\0' here */
  203075. png_debug1(3, "sCAL total length = %u\n", (unsigned int)total_len);
  203076. png_write_chunk(png_ptr, png_sCAL, buf, total_len);
  203077. }
  203078. #endif
  203079. #endif
  203080. #endif
  203081. #if defined(PNG_WRITE_pHYs_SUPPORTED)
  203082. /* write the pHYs chunk */
  203083. void /* PRIVATE */
  203084. png_write_pHYs(png_structp png_ptr, png_uint_32 x_pixels_per_unit,
  203085. png_uint_32 y_pixels_per_unit,
  203086. int unit_type)
  203087. {
  203088. #ifdef PNG_USE_LOCAL_ARRAYS
  203089. PNG_pHYs;
  203090. #endif
  203091. png_byte buf[9];
  203092. png_debug(1, "in png_write_pHYs\n");
  203093. if (unit_type >= PNG_RESOLUTION_LAST)
  203094. png_warning(png_ptr, "Unrecognized unit type for pHYs chunk");
  203095. png_save_uint_32(buf, x_pixels_per_unit);
  203096. png_save_uint_32(buf + 4, y_pixels_per_unit);
  203097. buf[8] = (png_byte)unit_type;
  203098. png_write_chunk(png_ptr, png_pHYs, buf, (png_size_t)9);
  203099. }
  203100. #endif
  203101. #if defined(PNG_WRITE_tIME_SUPPORTED)
  203102. /* Write the tIME chunk. Use either png_convert_from_struct_tm()
  203103. * or png_convert_from_time_t(), or fill in the structure yourself.
  203104. */
  203105. void /* PRIVATE */
  203106. png_write_tIME(png_structp png_ptr, png_timep mod_time)
  203107. {
  203108. #ifdef PNG_USE_LOCAL_ARRAYS
  203109. PNG_tIME;
  203110. #endif
  203111. png_byte buf[7];
  203112. png_debug(1, "in png_write_tIME\n");
  203113. if (mod_time->month > 12 || mod_time->month < 1 ||
  203114. mod_time->day > 31 || mod_time->day < 1 ||
  203115. mod_time->hour > 23 || mod_time->second > 60)
  203116. {
  203117. png_warning(png_ptr, "Invalid time specified for tIME chunk");
  203118. return;
  203119. }
  203120. png_save_uint_16(buf, mod_time->year);
  203121. buf[2] = mod_time->month;
  203122. buf[3] = mod_time->day;
  203123. buf[4] = mod_time->hour;
  203124. buf[5] = mod_time->minute;
  203125. buf[6] = mod_time->second;
  203126. png_write_chunk(png_ptr, png_tIME, buf, (png_size_t)7);
  203127. }
  203128. #endif
  203129. /* initializes the row writing capability of libpng */
  203130. void /* PRIVATE */
  203131. png_write_start_row(png_structp png_ptr)
  203132. {
  203133. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  203134. #ifdef PNG_USE_LOCAL_ARRAYS
  203135. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  203136. /* start of interlace block */
  203137. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  203138. /* offset to next interlace block */
  203139. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  203140. /* start of interlace block in the y direction */
  203141. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  203142. /* offset to next interlace block in the y direction */
  203143. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  203144. #endif
  203145. #endif
  203146. png_size_t buf_size;
  203147. png_debug(1, "in png_write_start_row\n");
  203148. buf_size = (png_size_t)(PNG_ROWBYTES(
  203149. png_ptr->usr_channels*png_ptr->usr_bit_depth,png_ptr->width)+1);
  203150. /* set up row buffer */
  203151. png_ptr->row_buf = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  203152. png_ptr->row_buf[0] = PNG_FILTER_VALUE_NONE;
  203153. #ifndef PNG_NO_WRITE_FILTERING
  203154. /* set up filtering buffer, if using this filter */
  203155. if (png_ptr->do_filter & PNG_FILTER_SUB)
  203156. {
  203157. png_ptr->sub_row = (png_bytep)png_malloc(png_ptr,
  203158. (png_ptr->rowbytes + 1));
  203159. png_ptr->sub_row[0] = PNG_FILTER_VALUE_SUB;
  203160. }
  203161. /* We only need to keep the previous row if we are using one of these. */
  203162. if (png_ptr->do_filter & (PNG_FILTER_AVG | PNG_FILTER_UP | PNG_FILTER_PAETH))
  203163. {
  203164. /* set up previous row buffer */
  203165. png_ptr->prev_row = (png_bytep)png_malloc(png_ptr, (png_uint_32)buf_size);
  203166. png_memset(png_ptr->prev_row, 0, buf_size);
  203167. if (png_ptr->do_filter & PNG_FILTER_UP)
  203168. {
  203169. png_ptr->up_row = (png_bytep)png_malloc(png_ptr,
  203170. (png_ptr->rowbytes + 1));
  203171. png_ptr->up_row[0] = PNG_FILTER_VALUE_UP;
  203172. }
  203173. if (png_ptr->do_filter & PNG_FILTER_AVG)
  203174. {
  203175. png_ptr->avg_row = (png_bytep)png_malloc(png_ptr,
  203176. (png_ptr->rowbytes + 1));
  203177. png_ptr->avg_row[0] = PNG_FILTER_VALUE_AVG;
  203178. }
  203179. if (png_ptr->do_filter & PNG_FILTER_PAETH)
  203180. {
  203181. png_ptr->paeth_row = (png_bytep)png_malloc(png_ptr,
  203182. (png_ptr->rowbytes + 1));
  203183. png_ptr->paeth_row[0] = PNG_FILTER_VALUE_PAETH;
  203184. }
  203185. #endif /* PNG_NO_WRITE_FILTERING */
  203186. }
  203187. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  203188. /* if interlaced, we need to set up width and height of pass */
  203189. if (png_ptr->interlaced)
  203190. {
  203191. if (!(png_ptr->transformations & PNG_INTERLACE))
  203192. {
  203193. png_ptr->num_rows = (png_ptr->height + png_pass_yinc[0] - 1 -
  203194. png_pass_ystart[0]) / png_pass_yinc[0];
  203195. png_ptr->usr_width = (png_ptr->width + png_pass_inc[0] - 1 -
  203196. png_pass_start[0]) / png_pass_inc[0];
  203197. }
  203198. else
  203199. {
  203200. png_ptr->num_rows = png_ptr->height;
  203201. png_ptr->usr_width = png_ptr->width;
  203202. }
  203203. }
  203204. else
  203205. #endif
  203206. {
  203207. png_ptr->num_rows = png_ptr->height;
  203208. png_ptr->usr_width = png_ptr->width;
  203209. }
  203210. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203211. png_ptr->zstream.next_out = png_ptr->zbuf;
  203212. }
  203213. /* Internal use only. Called when finished processing a row of data. */
  203214. void /* PRIVATE */
  203215. png_write_finish_row(png_structp png_ptr)
  203216. {
  203217. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  203218. #ifdef PNG_USE_LOCAL_ARRAYS
  203219. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  203220. /* start of interlace block */
  203221. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  203222. /* offset to next interlace block */
  203223. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  203224. /* start of interlace block in the y direction */
  203225. int png_pass_ystart[7] = {0, 0, 4, 0, 2, 0, 1};
  203226. /* offset to next interlace block in the y direction */
  203227. int png_pass_yinc[7] = {8, 8, 8, 4, 4, 2, 2};
  203228. #endif
  203229. #endif
  203230. int ret;
  203231. png_debug(1, "in png_write_finish_row\n");
  203232. /* next row */
  203233. png_ptr->row_number++;
  203234. /* see if we are done */
  203235. if (png_ptr->row_number < png_ptr->num_rows)
  203236. return;
  203237. #ifdef PNG_WRITE_INTERLACING_SUPPORTED
  203238. /* if interlaced, go to next pass */
  203239. if (png_ptr->interlaced)
  203240. {
  203241. png_ptr->row_number = 0;
  203242. if (png_ptr->transformations & PNG_INTERLACE)
  203243. {
  203244. png_ptr->pass++;
  203245. }
  203246. else
  203247. {
  203248. /* loop until we find a non-zero width or height pass */
  203249. do
  203250. {
  203251. png_ptr->pass++;
  203252. if (png_ptr->pass >= 7)
  203253. break;
  203254. png_ptr->usr_width = (png_ptr->width +
  203255. png_pass_inc[png_ptr->pass] - 1 -
  203256. png_pass_start[png_ptr->pass]) /
  203257. png_pass_inc[png_ptr->pass];
  203258. png_ptr->num_rows = (png_ptr->height +
  203259. png_pass_yinc[png_ptr->pass] - 1 -
  203260. png_pass_ystart[png_ptr->pass]) /
  203261. png_pass_yinc[png_ptr->pass];
  203262. if (png_ptr->transformations & PNG_INTERLACE)
  203263. break;
  203264. } while (png_ptr->usr_width == 0 || png_ptr->num_rows == 0);
  203265. }
  203266. /* reset the row above the image for the next pass */
  203267. if (png_ptr->pass < 7)
  203268. {
  203269. if (png_ptr->prev_row != NULL)
  203270. png_memset(png_ptr->prev_row, 0,
  203271. (png_size_t)(PNG_ROWBYTES(png_ptr->usr_channels*
  203272. png_ptr->usr_bit_depth,png_ptr->width))+1);
  203273. return;
  203274. }
  203275. }
  203276. #endif
  203277. /* if we get here, we've just written the last row, so we need
  203278. to flush the compressor */
  203279. do
  203280. {
  203281. /* tell the compressor we are done */
  203282. ret = deflate(&png_ptr->zstream, Z_FINISH);
  203283. /* check for an error */
  203284. if (ret == Z_OK)
  203285. {
  203286. /* check to see if we need more room */
  203287. if (!(png_ptr->zstream.avail_out))
  203288. {
  203289. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  203290. png_ptr->zstream.next_out = png_ptr->zbuf;
  203291. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  203292. }
  203293. }
  203294. else if (ret != Z_STREAM_END)
  203295. {
  203296. if (png_ptr->zstream.msg != NULL)
  203297. png_error(png_ptr, png_ptr->zstream.msg);
  203298. else
  203299. png_error(png_ptr, "zlib error");
  203300. }
  203301. } while (ret != Z_STREAM_END);
  203302. /* write any extra space */
  203303. if (png_ptr->zstream.avail_out < png_ptr->zbuf_size)
  203304. {
  203305. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size -
  203306. png_ptr->zstream.avail_out);
  203307. }
  203308. deflateReset(&png_ptr->zstream);
  203309. png_ptr->zstream.data_type = Z_BINARY;
  203310. }
  203311. #if defined(PNG_WRITE_INTERLACING_SUPPORTED)
  203312. /* Pick out the correct pixels for the interlace pass.
  203313. * The basic idea here is to go through the row with a source
  203314. * pointer and a destination pointer (sp and dp), and copy the
  203315. * correct pixels for the pass. As the row gets compacted,
  203316. * sp will always be >= dp, so we should never overwrite anything.
  203317. * See the default: case for the easiest code to understand.
  203318. */
  203319. void /* PRIVATE */
  203320. png_do_write_interlace(png_row_infop row_info, png_bytep row, int pass)
  203321. {
  203322. #ifdef PNG_USE_LOCAL_ARRAYS
  203323. /* arrays to facilitate easy interlacing - use pass (0 - 6) as index */
  203324. /* start of interlace block */
  203325. int png_pass_start[7] = {0, 4, 0, 2, 0, 1, 0};
  203326. /* offset to next interlace block */
  203327. int png_pass_inc[7] = {8, 8, 4, 4, 2, 2, 1};
  203328. #endif
  203329. png_debug(1, "in png_do_write_interlace\n");
  203330. /* we don't have to do anything on the last pass (6) */
  203331. #if defined(PNG_USELESS_TESTS_SUPPORTED)
  203332. if (row != NULL && row_info != NULL && pass < 6)
  203333. #else
  203334. if (pass < 6)
  203335. #endif
  203336. {
  203337. /* each pixel depth is handled separately */
  203338. switch (row_info->pixel_depth)
  203339. {
  203340. case 1:
  203341. {
  203342. png_bytep sp;
  203343. png_bytep dp;
  203344. int shift;
  203345. int d;
  203346. int value;
  203347. png_uint_32 i;
  203348. png_uint_32 row_width = row_info->width;
  203349. dp = row;
  203350. d = 0;
  203351. shift = 7;
  203352. for (i = png_pass_start[pass]; i < row_width;
  203353. i += png_pass_inc[pass])
  203354. {
  203355. sp = row + (png_size_t)(i >> 3);
  203356. value = (int)(*sp >> (7 - (int)(i & 0x07))) & 0x01;
  203357. d |= (value << shift);
  203358. if (shift == 0)
  203359. {
  203360. shift = 7;
  203361. *dp++ = (png_byte)d;
  203362. d = 0;
  203363. }
  203364. else
  203365. shift--;
  203366. }
  203367. if (shift != 7)
  203368. *dp = (png_byte)d;
  203369. break;
  203370. }
  203371. case 2:
  203372. {
  203373. png_bytep sp;
  203374. png_bytep dp;
  203375. int shift;
  203376. int d;
  203377. int value;
  203378. png_uint_32 i;
  203379. png_uint_32 row_width = row_info->width;
  203380. dp = row;
  203381. shift = 6;
  203382. d = 0;
  203383. for (i = png_pass_start[pass]; i < row_width;
  203384. i += png_pass_inc[pass])
  203385. {
  203386. sp = row + (png_size_t)(i >> 2);
  203387. value = (*sp >> ((3 - (int)(i & 0x03)) << 1)) & 0x03;
  203388. d |= (value << shift);
  203389. if (shift == 0)
  203390. {
  203391. shift = 6;
  203392. *dp++ = (png_byte)d;
  203393. d = 0;
  203394. }
  203395. else
  203396. shift -= 2;
  203397. }
  203398. if (shift != 6)
  203399. *dp = (png_byte)d;
  203400. break;
  203401. }
  203402. case 4:
  203403. {
  203404. png_bytep sp;
  203405. png_bytep dp;
  203406. int shift;
  203407. int d;
  203408. int value;
  203409. png_uint_32 i;
  203410. png_uint_32 row_width = row_info->width;
  203411. dp = row;
  203412. shift = 4;
  203413. d = 0;
  203414. for (i = png_pass_start[pass]; i < row_width;
  203415. i += png_pass_inc[pass])
  203416. {
  203417. sp = row + (png_size_t)(i >> 1);
  203418. value = (*sp >> ((1 - (int)(i & 0x01)) << 2)) & 0x0f;
  203419. d |= (value << shift);
  203420. if (shift == 0)
  203421. {
  203422. shift = 4;
  203423. *dp++ = (png_byte)d;
  203424. d = 0;
  203425. }
  203426. else
  203427. shift -= 4;
  203428. }
  203429. if (shift != 4)
  203430. *dp = (png_byte)d;
  203431. break;
  203432. }
  203433. default:
  203434. {
  203435. png_bytep sp;
  203436. png_bytep dp;
  203437. png_uint_32 i;
  203438. png_uint_32 row_width = row_info->width;
  203439. png_size_t pixel_bytes;
  203440. /* start at the beginning */
  203441. dp = row;
  203442. /* find out how many bytes each pixel takes up */
  203443. pixel_bytes = (row_info->pixel_depth >> 3);
  203444. /* loop through the row, only looking at the pixels that
  203445. matter */
  203446. for (i = png_pass_start[pass]; i < row_width;
  203447. i += png_pass_inc[pass])
  203448. {
  203449. /* find out where the original pixel is */
  203450. sp = row + (png_size_t)i * pixel_bytes;
  203451. /* move the pixel */
  203452. if (dp != sp)
  203453. png_memcpy(dp, sp, pixel_bytes);
  203454. /* next pixel */
  203455. dp += pixel_bytes;
  203456. }
  203457. break;
  203458. }
  203459. }
  203460. /* set new row width */
  203461. row_info->width = (row_info->width +
  203462. png_pass_inc[pass] - 1 -
  203463. png_pass_start[pass]) /
  203464. png_pass_inc[pass];
  203465. row_info->rowbytes = PNG_ROWBYTES(row_info->pixel_depth,
  203466. row_info->width);
  203467. }
  203468. }
  203469. #endif
  203470. /* This filters the row, chooses which filter to use, if it has not already
  203471. * been specified by the application, and then writes the row out with the
  203472. * chosen filter.
  203473. */
  203474. #define PNG_MAXSUM (((png_uint_32)(-1)) >> 1)
  203475. #define PNG_HISHIFT 10
  203476. #define PNG_LOMASK ((png_uint_32)0xffffL)
  203477. #define PNG_HIMASK ((png_uint_32)(~PNG_LOMASK >> PNG_HISHIFT))
  203478. void /* PRIVATE */
  203479. png_write_find_filter(png_structp png_ptr, png_row_infop row_info)
  203480. {
  203481. png_bytep best_row;
  203482. #ifndef PNG_NO_WRITE_FILTER
  203483. png_bytep prev_row, row_buf;
  203484. png_uint_32 mins, bpp;
  203485. png_byte filter_to_do = png_ptr->do_filter;
  203486. png_uint_32 row_bytes = row_info->rowbytes;
  203487. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203488. int num_p_filters = (int)png_ptr->num_prev_filters;
  203489. #endif
  203490. png_debug(1, "in png_write_find_filter\n");
  203491. /* find out how many bytes offset each pixel is */
  203492. bpp = (row_info->pixel_depth + 7) >> 3;
  203493. prev_row = png_ptr->prev_row;
  203494. #endif
  203495. best_row = png_ptr->row_buf;
  203496. #ifndef PNG_NO_WRITE_FILTER
  203497. row_buf = best_row;
  203498. mins = PNG_MAXSUM;
  203499. /* The prediction method we use is to find which method provides the
  203500. * smallest value when summing the absolute values of the distances
  203501. * from zero, using anything >= 128 as negative numbers. This is known
  203502. * as the "minimum sum of absolute differences" heuristic. Other
  203503. * heuristics are the "weighted minimum sum of absolute differences"
  203504. * (experimental and can in theory improve compression), and the "zlib
  203505. * predictive" method (not implemented yet), which does test compressions
  203506. * of lines using different filter methods, and then chooses the
  203507. * (series of) filter(s) that give minimum compressed data size (VERY
  203508. * computationally expensive).
  203509. *
  203510. * GRR 980525: consider also
  203511. * (1) minimum sum of absolute differences from running average (i.e.,
  203512. * keep running sum of non-absolute differences & count of bytes)
  203513. * [track dispersion, too? restart average if dispersion too large?]
  203514. * (1b) minimum sum of absolute differences from sliding average, probably
  203515. * with window size <= deflate window (usually 32K)
  203516. * (2) minimum sum of squared differences from zero or running average
  203517. * (i.e., ~ root-mean-square approach)
  203518. */
  203519. /* We don't need to test the 'no filter' case if this is the only filter
  203520. * that has been chosen, as it doesn't actually do anything to the data.
  203521. */
  203522. if ((filter_to_do & PNG_FILTER_NONE) &&
  203523. filter_to_do != PNG_FILTER_NONE)
  203524. {
  203525. png_bytep rp;
  203526. png_uint_32 sum = 0;
  203527. png_uint_32 i;
  203528. int v;
  203529. for (i = 0, rp = row_buf + 1; i < row_bytes; i++, rp++)
  203530. {
  203531. v = *rp;
  203532. sum += (v < 128) ? v : 256 - v;
  203533. }
  203534. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203535. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203536. {
  203537. png_uint_32 sumhi, sumlo;
  203538. int j;
  203539. sumlo = sum & PNG_LOMASK;
  203540. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK; /* Gives us some footroom */
  203541. /* Reduce the sum if we match any of the previous rows */
  203542. for (j = 0; j < num_p_filters; j++)
  203543. {
  203544. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  203545. {
  203546. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203547. PNG_WEIGHT_SHIFT;
  203548. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203549. PNG_WEIGHT_SHIFT;
  203550. }
  203551. }
  203552. /* Factor in the cost of this filter (this is here for completeness,
  203553. * but it makes no sense to have a "cost" for the NONE filter, as
  203554. * it has the minimum possible computational cost - none).
  203555. */
  203556. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  203557. PNG_COST_SHIFT;
  203558. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_NONE]) >>
  203559. PNG_COST_SHIFT;
  203560. if (sumhi > PNG_HIMASK)
  203561. sum = PNG_MAXSUM;
  203562. else
  203563. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203564. }
  203565. #endif
  203566. mins = sum;
  203567. }
  203568. /* sub filter */
  203569. if (filter_to_do == PNG_FILTER_SUB)
  203570. /* it's the only filter so no testing is needed */
  203571. {
  203572. png_bytep rp, lp, dp;
  203573. png_uint_32 i;
  203574. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  203575. i++, rp++, dp++)
  203576. {
  203577. *dp = *rp;
  203578. }
  203579. for (lp = row_buf + 1; i < row_bytes;
  203580. i++, rp++, lp++, dp++)
  203581. {
  203582. *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  203583. }
  203584. best_row = png_ptr->sub_row;
  203585. }
  203586. else if (filter_to_do & PNG_FILTER_SUB)
  203587. {
  203588. png_bytep rp, dp, lp;
  203589. png_uint_32 sum = 0, lmins = mins;
  203590. png_uint_32 i;
  203591. int v;
  203592. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203593. /* We temporarily increase the "minimum sum" by the factor we
  203594. * would reduce the sum of this filter, so that we can do the
  203595. * early exit comparison without scaling the sum each time.
  203596. */
  203597. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203598. {
  203599. int j;
  203600. png_uint_32 lmhi, lmlo;
  203601. lmlo = lmins & PNG_LOMASK;
  203602. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203603. for (j = 0; j < num_p_filters; j++)
  203604. {
  203605. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  203606. {
  203607. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203608. PNG_WEIGHT_SHIFT;
  203609. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203610. PNG_WEIGHT_SHIFT;
  203611. }
  203612. }
  203613. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  203614. PNG_COST_SHIFT;
  203615. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  203616. PNG_COST_SHIFT;
  203617. if (lmhi > PNG_HIMASK)
  203618. lmins = PNG_MAXSUM;
  203619. else
  203620. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203621. }
  203622. #endif
  203623. for (i = 0, rp = row_buf + 1, dp = png_ptr->sub_row + 1; i < bpp;
  203624. i++, rp++, dp++)
  203625. {
  203626. v = *dp = *rp;
  203627. sum += (v < 128) ? v : 256 - v;
  203628. }
  203629. for (lp = row_buf + 1; i < row_bytes;
  203630. i++, rp++, lp++, dp++)
  203631. {
  203632. v = *dp = (png_byte)(((int)*rp - (int)*lp) & 0xff);
  203633. sum += (v < 128) ? v : 256 - v;
  203634. if (sum > lmins) /* We are already worse, don't continue. */
  203635. break;
  203636. }
  203637. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203638. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203639. {
  203640. int j;
  203641. png_uint_32 sumhi, sumlo;
  203642. sumlo = sum & PNG_LOMASK;
  203643. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203644. for (j = 0; j < num_p_filters; j++)
  203645. {
  203646. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_SUB)
  203647. {
  203648. sumlo = (sumlo * png_ptr->inv_filter_weights[j]) >>
  203649. PNG_WEIGHT_SHIFT;
  203650. sumhi = (sumhi * png_ptr->inv_filter_weights[j]) >>
  203651. PNG_WEIGHT_SHIFT;
  203652. }
  203653. }
  203654. sumlo = (sumlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  203655. PNG_COST_SHIFT;
  203656. sumhi = (sumhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_SUB]) >>
  203657. PNG_COST_SHIFT;
  203658. if (sumhi > PNG_HIMASK)
  203659. sum = PNG_MAXSUM;
  203660. else
  203661. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203662. }
  203663. #endif
  203664. if (sum < mins)
  203665. {
  203666. mins = sum;
  203667. best_row = png_ptr->sub_row;
  203668. }
  203669. }
  203670. /* up filter */
  203671. if (filter_to_do == PNG_FILTER_UP)
  203672. {
  203673. png_bytep rp, dp, pp;
  203674. png_uint_32 i;
  203675. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  203676. pp = prev_row + 1; i < row_bytes;
  203677. i++, rp++, pp++, dp++)
  203678. {
  203679. *dp = (png_byte)(((int)*rp - (int)*pp) & 0xff);
  203680. }
  203681. best_row = png_ptr->up_row;
  203682. }
  203683. else if (filter_to_do & PNG_FILTER_UP)
  203684. {
  203685. png_bytep rp, dp, pp;
  203686. png_uint_32 sum = 0, lmins = mins;
  203687. png_uint_32 i;
  203688. int v;
  203689. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203690. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203691. {
  203692. int j;
  203693. png_uint_32 lmhi, lmlo;
  203694. lmlo = lmins & PNG_LOMASK;
  203695. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203696. for (j = 0; j < num_p_filters; j++)
  203697. {
  203698. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  203699. {
  203700. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203701. PNG_WEIGHT_SHIFT;
  203702. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203703. PNG_WEIGHT_SHIFT;
  203704. }
  203705. }
  203706. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  203707. PNG_COST_SHIFT;
  203708. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_UP]) >>
  203709. PNG_COST_SHIFT;
  203710. if (lmhi > PNG_HIMASK)
  203711. lmins = PNG_MAXSUM;
  203712. else
  203713. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203714. }
  203715. #endif
  203716. for (i = 0, rp = row_buf + 1, dp = png_ptr->up_row + 1,
  203717. pp = prev_row + 1; i < row_bytes; i++)
  203718. {
  203719. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203720. sum += (v < 128) ? v : 256 - v;
  203721. if (sum > lmins) /* We are already worse, don't continue. */
  203722. break;
  203723. }
  203724. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203725. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203726. {
  203727. int j;
  203728. png_uint_32 sumhi, sumlo;
  203729. sumlo = sum & PNG_LOMASK;
  203730. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203731. for (j = 0; j < num_p_filters; j++)
  203732. {
  203733. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_UP)
  203734. {
  203735. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203736. PNG_WEIGHT_SHIFT;
  203737. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203738. PNG_WEIGHT_SHIFT;
  203739. }
  203740. }
  203741. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  203742. PNG_COST_SHIFT;
  203743. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_UP]) >>
  203744. PNG_COST_SHIFT;
  203745. if (sumhi > PNG_HIMASK)
  203746. sum = PNG_MAXSUM;
  203747. else
  203748. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203749. }
  203750. #endif
  203751. if (sum < mins)
  203752. {
  203753. mins = sum;
  203754. best_row = png_ptr->up_row;
  203755. }
  203756. }
  203757. /* avg filter */
  203758. if (filter_to_do == PNG_FILTER_AVG)
  203759. {
  203760. png_bytep rp, dp, pp, lp;
  203761. png_uint_32 i;
  203762. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203763. pp = prev_row + 1; i < bpp; i++)
  203764. {
  203765. *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203766. }
  203767. for (lp = row_buf + 1; i < row_bytes; i++)
  203768. {
  203769. *dp++ = (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2))
  203770. & 0xff);
  203771. }
  203772. best_row = png_ptr->avg_row;
  203773. }
  203774. else if (filter_to_do & PNG_FILTER_AVG)
  203775. {
  203776. png_bytep rp, dp, pp, lp;
  203777. png_uint_32 sum = 0, lmins = mins;
  203778. png_uint_32 i;
  203779. int v;
  203780. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203781. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203782. {
  203783. int j;
  203784. png_uint_32 lmhi, lmlo;
  203785. lmlo = lmins & PNG_LOMASK;
  203786. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203787. for (j = 0; j < num_p_filters; j++)
  203788. {
  203789. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_AVG)
  203790. {
  203791. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203792. PNG_WEIGHT_SHIFT;
  203793. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203794. PNG_WEIGHT_SHIFT;
  203795. }
  203796. }
  203797. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203798. PNG_COST_SHIFT;
  203799. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203800. PNG_COST_SHIFT;
  203801. if (lmhi > PNG_HIMASK)
  203802. lmins = PNG_MAXSUM;
  203803. else
  203804. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203805. }
  203806. #endif
  203807. for (i = 0, rp = row_buf + 1, dp = png_ptr->avg_row + 1,
  203808. pp = prev_row + 1; i < bpp; i++)
  203809. {
  203810. v = *dp++ = (png_byte)(((int)*rp++ - ((int)*pp++ / 2)) & 0xff);
  203811. sum += (v < 128) ? v : 256 - v;
  203812. }
  203813. for (lp = row_buf + 1; i < row_bytes; i++)
  203814. {
  203815. v = *dp++ =
  203816. (png_byte)(((int)*rp++ - (((int)*pp++ + (int)*lp++) / 2)) & 0xff);
  203817. sum += (v < 128) ? v : 256 - v;
  203818. if (sum > lmins) /* We are already worse, don't continue. */
  203819. break;
  203820. }
  203821. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203822. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203823. {
  203824. int j;
  203825. png_uint_32 sumhi, sumlo;
  203826. sumlo = sum & PNG_LOMASK;
  203827. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203828. for (j = 0; j < num_p_filters; j++)
  203829. {
  203830. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_NONE)
  203831. {
  203832. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203833. PNG_WEIGHT_SHIFT;
  203834. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203835. PNG_WEIGHT_SHIFT;
  203836. }
  203837. }
  203838. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203839. PNG_COST_SHIFT;
  203840. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_AVG]) >>
  203841. PNG_COST_SHIFT;
  203842. if (sumhi > PNG_HIMASK)
  203843. sum = PNG_MAXSUM;
  203844. else
  203845. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203846. }
  203847. #endif
  203848. if (sum < mins)
  203849. {
  203850. mins = sum;
  203851. best_row = png_ptr->avg_row;
  203852. }
  203853. }
  203854. /* Paeth filter */
  203855. if (filter_to_do == PNG_FILTER_PAETH)
  203856. {
  203857. png_bytep rp, dp, pp, cp, lp;
  203858. png_uint_32 i;
  203859. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203860. pp = prev_row + 1; i < bpp; i++)
  203861. {
  203862. *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203863. }
  203864. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203865. {
  203866. int a, b, c, pa, pb, pc, p;
  203867. b = *pp++;
  203868. c = *cp++;
  203869. a = *lp++;
  203870. p = b - c;
  203871. pc = a - c;
  203872. #ifdef PNG_USE_ABS
  203873. pa = abs(p);
  203874. pb = abs(pc);
  203875. pc = abs(p + pc);
  203876. #else
  203877. pa = p < 0 ? -p : p;
  203878. pb = pc < 0 ? -pc : pc;
  203879. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203880. #endif
  203881. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203882. *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203883. }
  203884. best_row = png_ptr->paeth_row;
  203885. }
  203886. else if (filter_to_do & PNG_FILTER_PAETH)
  203887. {
  203888. png_bytep rp, dp, pp, cp, lp;
  203889. png_uint_32 sum = 0, lmins = mins;
  203890. png_uint_32 i;
  203891. int v;
  203892. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203893. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203894. {
  203895. int j;
  203896. png_uint_32 lmhi, lmlo;
  203897. lmlo = lmins & PNG_LOMASK;
  203898. lmhi = (lmins >> PNG_HISHIFT) & PNG_HIMASK;
  203899. for (j = 0; j < num_p_filters; j++)
  203900. {
  203901. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203902. {
  203903. lmlo = (lmlo * png_ptr->inv_filter_weights[j]) >>
  203904. PNG_WEIGHT_SHIFT;
  203905. lmhi = (lmhi * png_ptr->inv_filter_weights[j]) >>
  203906. PNG_WEIGHT_SHIFT;
  203907. }
  203908. }
  203909. lmlo = (lmlo * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203910. PNG_COST_SHIFT;
  203911. lmhi = (lmhi * png_ptr->inv_filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203912. PNG_COST_SHIFT;
  203913. if (lmhi > PNG_HIMASK)
  203914. lmins = PNG_MAXSUM;
  203915. else
  203916. lmins = (lmhi << PNG_HISHIFT) + lmlo;
  203917. }
  203918. #endif
  203919. for (i = 0, rp = row_buf + 1, dp = png_ptr->paeth_row + 1,
  203920. pp = prev_row + 1; i < bpp; i++)
  203921. {
  203922. v = *dp++ = (png_byte)(((int)*rp++ - (int)*pp++) & 0xff);
  203923. sum += (v < 128) ? v : 256 - v;
  203924. }
  203925. for (lp = row_buf + 1, cp = prev_row + 1; i < row_bytes; i++)
  203926. {
  203927. int a, b, c, pa, pb, pc, p;
  203928. b = *pp++;
  203929. c = *cp++;
  203930. a = *lp++;
  203931. #ifndef PNG_SLOW_PAETH
  203932. p = b - c;
  203933. pc = a - c;
  203934. #ifdef PNG_USE_ABS
  203935. pa = abs(p);
  203936. pb = abs(pc);
  203937. pc = abs(p + pc);
  203938. #else
  203939. pa = p < 0 ? -p : p;
  203940. pb = pc < 0 ? -pc : pc;
  203941. pc = (p + pc) < 0 ? -(p + pc) : p + pc;
  203942. #endif
  203943. p = (pa <= pb && pa <=pc) ? a : (pb <= pc) ? b : c;
  203944. #else /* PNG_SLOW_PAETH */
  203945. p = a + b - c;
  203946. pa = abs(p - a);
  203947. pb = abs(p - b);
  203948. pc = abs(p - c);
  203949. if (pa <= pb && pa <= pc)
  203950. p = a;
  203951. else if (pb <= pc)
  203952. p = b;
  203953. else
  203954. p = c;
  203955. #endif /* PNG_SLOW_PAETH */
  203956. v = *dp++ = (png_byte)(((int)*rp++ - p) & 0xff);
  203957. sum += (v < 128) ? v : 256 - v;
  203958. if (sum > lmins) /* We are already worse, don't continue. */
  203959. break;
  203960. }
  203961. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203962. if (png_ptr->heuristic_method == PNG_FILTER_HEURISTIC_WEIGHTED)
  203963. {
  203964. int j;
  203965. png_uint_32 sumhi, sumlo;
  203966. sumlo = sum & PNG_LOMASK;
  203967. sumhi = (sum >> PNG_HISHIFT) & PNG_HIMASK;
  203968. for (j = 0; j < num_p_filters; j++)
  203969. {
  203970. if (png_ptr->prev_filters[j] == PNG_FILTER_VALUE_PAETH)
  203971. {
  203972. sumlo = (sumlo * png_ptr->filter_weights[j]) >>
  203973. PNG_WEIGHT_SHIFT;
  203974. sumhi = (sumhi * png_ptr->filter_weights[j]) >>
  203975. PNG_WEIGHT_SHIFT;
  203976. }
  203977. }
  203978. sumlo = (sumlo * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203979. PNG_COST_SHIFT;
  203980. sumhi = (sumhi * png_ptr->filter_costs[PNG_FILTER_VALUE_PAETH]) >>
  203981. PNG_COST_SHIFT;
  203982. if (sumhi > PNG_HIMASK)
  203983. sum = PNG_MAXSUM;
  203984. else
  203985. sum = (sumhi << PNG_HISHIFT) + sumlo;
  203986. }
  203987. #endif
  203988. if (sum < mins)
  203989. {
  203990. best_row = png_ptr->paeth_row;
  203991. }
  203992. }
  203993. #endif /* PNG_NO_WRITE_FILTER */
  203994. /* Do the actual writing of the filtered row data from the chosen filter. */
  203995. png_write_filtered_row(png_ptr, best_row);
  203996. #ifndef PNG_NO_WRITE_FILTER
  203997. #if defined(PNG_WRITE_WEIGHTED_FILTER_SUPPORTED)
  203998. /* Save the type of filter we picked this time for future calculations */
  203999. if (png_ptr->num_prev_filters > 0)
  204000. {
  204001. int j;
  204002. for (j = 1; j < num_p_filters; j++)
  204003. {
  204004. png_ptr->prev_filters[j] = png_ptr->prev_filters[j - 1];
  204005. }
  204006. png_ptr->prev_filters[j] = best_row[0];
  204007. }
  204008. #endif
  204009. #endif /* PNG_NO_WRITE_FILTER */
  204010. }
  204011. /* Do the actual writing of a previously filtered row. */
  204012. void /* PRIVATE */
  204013. png_write_filtered_row(png_structp png_ptr, png_bytep filtered_row)
  204014. {
  204015. png_debug(1, "in png_write_filtered_row\n");
  204016. png_debug1(2, "filter = %d\n", filtered_row[0]);
  204017. /* set up the zlib input buffer */
  204018. png_ptr->zstream.next_in = filtered_row;
  204019. png_ptr->zstream.avail_in = (uInt)png_ptr->row_info.rowbytes + 1;
  204020. /* repeat until we have compressed all the data */
  204021. do
  204022. {
  204023. int ret; /* return of zlib */
  204024. /* compress the data */
  204025. ret = deflate(&png_ptr->zstream, Z_NO_FLUSH);
  204026. /* check for compression errors */
  204027. if (ret != Z_OK)
  204028. {
  204029. if (png_ptr->zstream.msg != NULL)
  204030. png_error(png_ptr, png_ptr->zstream.msg);
  204031. else
  204032. png_error(png_ptr, "zlib error");
  204033. }
  204034. /* see if it is time to write another IDAT */
  204035. if (!(png_ptr->zstream.avail_out))
  204036. {
  204037. /* write the IDAT and reset the zlib output buffer */
  204038. png_write_IDAT(png_ptr, png_ptr->zbuf, png_ptr->zbuf_size);
  204039. png_ptr->zstream.next_out = png_ptr->zbuf;
  204040. png_ptr->zstream.avail_out = (uInt)png_ptr->zbuf_size;
  204041. }
  204042. /* repeat until all data has been compressed */
  204043. } while (png_ptr->zstream.avail_in);
  204044. /* swap the current and previous rows */
  204045. if (png_ptr->prev_row != NULL)
  204046. {
  204047. png_bytep tptr;
  204048. tptr = png_ptr->prev_row;
  204049. png_ptr->prev_row = png_ptr->row_buf;
  204050. png_ptr->row_buf = tptr;
  204051. }
  204052. /* finish row - updates counters and flushes zlib if last row */
  204053. png_write_finish_row(png_ptr);
  204054. #if defined(PNG_WRITE_FLUSH_SUPPORTED)
  204055. png_ptr->flush_rows++;
  204056. if (png_ptr->flush_dist > 0 &&
  204057. png_ptr->flush_rows >= png_ptr->flush_dist)
  204058. {
  204059. png_write_flush(png_ptr);
  204060. }
  204061. #endif
  204062. }
  204063. #endif /* PNG_WRITE_SUPPORTED */
  204064. /********* End of inlined file: pngwutil.c *********/
  204065. }
  204066. #else
  204067. #define PNG_INTERNAL
  204068. #define PNG_SETJMP_NOT_SUPPORTED
  204069. #include <png.h>
  204070. #include <pngconf.h>
  204071. #endif
  204072. }
  204073. #ifdef _MSC_VER
  204074. #pragma warning (pop)
  204075. #endif
  204076. BEGIN_JUCE_NAMESPACE
  204077. using namespace pnglibNamespace;
  204078. using ::malloc;
  204079. using ::free;
  204080. static void pngReadCallback (png_structp pngReadStruct, png_bytep data, png_size_t length) throw()
  204081. {
  204082. InputStream* const in = (InputStream*) png_get_io_ptr (pngReadStruct);
  204083. in->read (data, (int) length);
  204084. }
  204085. struct PNGErrorStruct {};
  204086. static void pngErrorCallback (png_structp, png_const_charp)
  204087. {
  204088. throw PNGErrorStruct();
  204089. }
  204090. Image* juce_loadPNGImageFromStream (InputStream& in) throw()
  204091. {
  204092. Image* image = 0;
  204093. png_structp pngReadStruct;
  204094. png_infop pngInfoStruct;
  204095. pngReadStruct = png_create_read_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  204096. if (pngReadStruct != 0)
  204097. {
  204098. pngInfoStruct = png_create_info_struct (pngReadStruct);
  204099. if (pngInfoStruct == 0)
  204100. {
  204101. png_destroy_read_struct (&pngReadStruct, 0, 0);
  204102. return 0;
  204103. }
  204104. png_set_error_fn (pngReadStruct, 0, pngErrorCallback, pngErrorCallback);
  204105. // read the header..
  204106. png_set_read_fn (pngReadStruct, &in, pngReadCallback);
  204107. png_uint_32 width, height;
  204108. int bitDepth, colorType, interlaceType;
  204109. try
  204110. {
  204111. png_read_info (pngReadStruct, pngInfoStruct);
  204112. png_get_IHDR (pngReadStruct, pngInfoStruct,
  204113. &width, &height,
  204114. &bitDepth, &colorType,
  204115. &interlaceType, 0, 0);
  204116. }
  204117. catch (...)
  204118. {
  204119. png_destroy_read_struct (&pngReadStruct, 0, 0);
  204120. return 0;
  204121. }
  204122. if (bitDepth == 16)
  204123. png_set_strip_16 (pngReadStruct);
  204124. if (colorType == PNG_COLOR_TYPE_PALETTE)
  204125. png_set_expand (pngReadStruct);
  204126. if (bitDepth < 8)
  204127. png_set_expand (pngReadStruct);
  204128. if (png_get_valid (pngReadStruct, pngInfoStruct, PNG_INFO_tRNS))
  204129. png_set_expand (pngReadStruct);
  204130. if (colorType == PNG_COLOR_TYPE_GRAY || colorType == PNG_COLOR_TYPE_GRAY_ALPHA)
  204131. png_set_gray_to_rgb (pngReadStruct);
  204132. png_set_add_alpha (pngReadStruct, 0xff, PNG_FILLER_AFTER);
  204133. const bool hasAlphaChan = (colorType & PNG_COLOR_MASK_ALPHA) != 0
  204134. || pngInfoStruct->num_trans > 0;
  204135. // Load the image into a temp buffer in the pnglib format..
  204136. uint8* const tempBuffer = (uint8*) juce_malloc (height * (width << 2));
  204137. png_bytepp rows = (png_bytepp) juce_malloc (sizeof (png_bytep) * height);
  204138. int y;
  204139. for (y = (int) height; --y >= 0;)
  204140. rows[y] = (png_bytep) (tempBuffer + (width << 2) * y);
  204141. bool crashed = false;
  204142. try
  204143. {
  204144. png_read_image (pngReadStruct, rows);
  204145. png_read_end (pngReadStruct, pngInfoStruct);
  204146. }
  204147. catch (...)
  204148. {
  204149. crashed = true;
  204150. }
  204151. juce_free (rows);
  204152. png_destroy_read_struct (&pngReadStruct, &pngInfoStruct, 0);
  204153. if (crashed)
  204154. return 0;
  204155. // now convert the data to a juce image format..
  204156. image = new Image (hasAlphaChan ? Image::ARGB : Image::RGB,
  204157. width, height, hasAlphaChan);
  204158. int stride, pixelStride;
  204159. uint8* const pixels = image->lockPixelDataReadWrite (0, 0, width, height, stride, pixelStride);
  204160. uint8* srcRow = tempBuffer;
  204161. uint8* destRow = pixels;
  204162. for (y = 0; y < (int) height; ++y)
  204163. {
  204164. const uint8* src = srcRow;
  204165. srcRow += (width << 2);
  204166. uint8* dest = destRow;
  204167. destRow += stride;
  204168. if (hasAlphaChan)
  204169. {
  204170. for (int i = width; --i >= 0;)
  204171. {
  204172. ((PixelARGB*) dest)->setARGB (src[3], src[0], src[1], src[2]);
  204173. ((PixelARGB*) dest)->premultiply();
  204174. dest += pixelStride;
  204175. src += 4;
  204176. }
  204177. }
  204178. else
  204179. {
  204180. for (int i = width; --i >= 0;)
  204181. {
  204182. ((PixelRGB*) dest)->setARGB (0, src[0], src[1], src[2]);
  204183. dest += pixelStride;
  204184. src += 4;
  204185. }
  204186. }
  204187. }
  204188. image->releasePixelDataReadWrite (pixels);
  204189. juce_free (tempBuffer);
  204190. }
  204191. return image;
  204192. }
  204193. static void pngWriteDataCallback (png_structp png_ptr, png_bytep data, png_size_t length) throw()
  204194. {
  204195. OutputStream* const out = (OutputStream*) png_ptr->io_ptr;
  204196. const bool ok = out->write (data, length);
  204197. (void) ok;
  204198. jassert (ok);
  204199. }
  204200. bool juce_writePNGImageToStream (const Image& image, OutputStream& out) throw()
  204201. {
  204202. const int width = image.getWidth();
  204203. const int height = image.getHeight();
  204204. png_structp pngWriteStruct = png_create_write_struct (PNG_LIBPNG_VER_STRING, 0, 0, 0);
  204205. if (pngWriteStruct == 0)
  204206. return false;
  204207. png_infop pngInfoStruct = png_create_info_struct (pngWriteStruct);
  204208. if (pngInfoStruct == 0)
  204209. {
  204210. png_destroy_write_struct (&pngWriteStruct, (png_infopp) 0);
  204211. return false;
  204212. }
  204213. png_set_write_fn (pngWriteStruct, &out, pngWriteDataCallback, 0);
  204214. png_set_IHDR (pngWriteStruct, pngInfoStruct, width, height, 8,
  204215. image.hasAlphaChannel() ? PNG_COLOR_TYPE_RGB_ALPHA
  204216. : PNG_COLOR_TYPE_RGB,
  204217. PNG_INTERLACE_NONE,
  204218. PNG_COMPRESSION_TYPE_BASE,
  204219. PNG_FILTER_TYPE_BASE);
  204220. png_bytep rowData = (png_bytep) juce_malloc (width * 4 * sizeof (png_byte));
  204221. png_color_8 sig_bit;
  204222. sig_bit.red = 8;
  204223. sig_bit.green = 8;
  204224. sig_bit.blue = 8;
  204225. sig_bit.alpha = 8;
  204226. png_set_sBIT (pngWriteStruct, pngInfoStruct, &sig_bit);
  204227. png_write_info (pngWriteStruct, pngInfoStruct);
  204228. png_set_shift (pngWriteStruct, &sig_bit);
  204229. png_set_packing (pngWriteStruct);
  204230. for (int y = 0; y < height; ++y)
  204231. {
  204232. uint8* dst = (uint8*) rowData;
  204233. int stride, pixelStride;
  204234. const uint8* pixels = image.lockPixelDataReadOnly (0, y, width, 1, stride, pixelStride);
  204235. const uint8* src = pixels;
  204236. if (image.hasAlphaChannel())
  204237. {
  204238. for (int i = width; --i >= 0;)
  204239. {
  204240. PixelARGB p (*(const PixelARGB*) src);
  204241. p.unpremultiply();
  204242. *dst++ = p.getRed();
  204243. *dst++ = p.getGreen();
  204244. *dst++ = p.getBlue();
  204245. *dst++ = p.getAlpha();
  204246. src += pixelStride;
  204247. }
  204248. }
  204249. else
  204250. {
  204251. for (int i = width; --i >= 0;)
  204252. {
  204253. *dst++ = ((const PixelRGB*) src)->getRed();
  204254. *dst++ = ((const PixelRGB*) src)->getGreen();
  204255. *dst++ = ((const PixelRGB*) src)->getBlue();
  204256. src += pixelStride;
  204257. }
  204258. }
  204259. png_write_rows (pngWriteStruct, &rowData, 1);
  204260. image.releasePixelDataReadOnly (pixels);
  204261. }
  204262. juce_free (rowData);
  204263. png_write_end (pngWriteStruct, pngInfoStruct);
  204264. png_destroy_write_struct (&pngWriteStruct, &pngInfoStruct);
  204265. out.flush();
  204266. return true;
  204267. }
  204268. END_JUCE_NAMESPACE
  204269. /********* End of inlined file: juce_PNGLoader.cpp *********/
  204270. #endif
  204271. //==============================================================================
  204272. #if JUCE_WIN32
  204273. /********* Start of inlined file: juce_win32_NativeCode.cpp *********/
  204274. /*
  204275. This file wraps together all the win32-specific code, so that
  204276. we can include all the native headers just once, and compile all our
  204277. platform-specific stuff in one big lump, keeping it out of the way of
  204278. the rest of the codebase.
  204279. */
  204280. BEGIN_JUCE_NAMESPACE
  204281. #define JUCE_INCLUDED_FILE 1
  204282. // Now include the actual code files..
  204283. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  204284. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204285. // compiled on its own).
  204286. #if JUCE_INCLUDED_FILE
  204287. /********* Start of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  204288. #ifndef __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  204289. #define __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  204290. #ifndef DOXYGEN
  204291. // use with DynamicLibraryLoader to simplify importing functions
  204292. //
  204293. // functionName: function to import
  204294. // localFunctionName: name you want to use to actually call it (must be different)
  204295. // returnType: the return type
  204296. // object: the DynamicLibraryLoader to use
  204297. // params: list of params (bracketed)
  204298. //
  204299. #define DynamicLibraryImport(functionName, localFunctionName, returnType, object, params) \
  204300. typedef returnType (WINAPI *type##localFunctionName) params; \
  204301. type##localFunctionName localFunctionName \
  204302. = (type##localFunctionName)object.findProcAddress (#functionName);
  204303. // loads and unloads a DLL automatically
  204304. class JUCE_API DynamicLibraryLoader
  204305. {
  204306. public:
  204307. DynamicLibraryLoader (const String& name);
  204308. ~DynamicLibraryLoader();
  204309. void* findProcAddress (const String& functionName);
  204310. private:
  204311. void* libHandle;
  204312. };
  204313. #endif
  204314. #endif // __JUCE_WIN32_DYNAMICLIBRARYLOADER_JUCEHEADER__
  204315. /********* End of inlined file: juce_win32_DynamicLibraryLoader.h *********/
  204316. DynamicLibraryLoader::DynamicLibraryLoader (const String& name)
  204317. {
  204318. libHandle = LoadLibrary (name);
  204319. }
  204320. DynamicLibraryLoader::~DynamicLibraryLoader()
  204321. {
  204322. FreeLibrary ((HMODULE) libHandle);
  204323. }
  204324. void* DynamicLibraryLoader::findProcAddress (const String& functionName)
  204325. {
  204326. return (void*) GetProcAddress ((HMODULE) libHandle, functionName);
  204327. }
  204328. #endif
  204329. /********* End of inlined file: juce_win32_DynamicLibraryLoader.cpp *********/
  204330. /********* Start of inlined file: juce_win32_SystemStats.cpp *********/
  204331. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204332. // compiled on its own).
  204333. #if JUCE_INCLUDED_FILE
  204334. extern void juce_updateMultiMonitorInfo() throw();
  204335. extern void juce_initialiseThreadEvents() throw();
  204336. void Logger::outputDebugString (const String& text) throw()
  204337. {
  204338. OutputDebugString (text + T("\n"));
  204339. }
  204340. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  204341. {
  204342. String text;
  204343. va_list args;
  204344. va_start (args, format);
  204345. text.vprintf(format, args);
  204346. outputDebugString (text);
  204347. }
  204348. static int64 hiResTicksPerSecond;
  204349. static double hiResTicksScaleFactor;
  204350. #if JUCE_USE_INTRINSICS
  204351. // CPU info functions using intrinsics...
  204352. #pragma intrinsic (__cpuid)
  204353. #pragma intrinsic (__rdtsc)
  204354. /*static unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0) throw()
  204355. {
  204356. int info [4];
  204357. __cpuid (info, 1);
  204358. if (familyModel != 0)
  204359. *familyModel = info [0];
  204360. if (extFeatures != 0)
  204361. *extFeatures = info[1];
  204362. return info[3];
  204363. }*/
  204364. const String SystemStats::getCpuVendor() throw()
  204365. {
  204366. int info [4];
  204367. __cpuid (info, 0);
  204368. char v [12];
  204369. memcpy (v, info + 1, 4);
  204370. memcpy (v + 4, info + 3, 4);
  204371. memcpy (v + 8, info + 2, 4);
  204372. return String (v, 12);
  204373. }
  204374. #else
  204375. // CPU info functions using old fashioned inline asm...
  204376. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel = 0, int* extFeatures = 0)
  204377. {
  204378. unsigned int cpu = 0;
  204379. unsigned int ext = 0;
  204380. unsigned int family = 0;
  204381. #if JUCE_GCC
  204382. unsigned int dummy = 0;
  204383. #endif
  204384. #ifndef __MINGW32__
  204385. __try
  204386. #endif
  204387. {
  204388. #if JUCE_GCC
  204389. __asm__ ("cpuid" : "=a" (family), "=b" (ext), "=c" (dummy),"=d" (cpu) : "a" (1));
  204390. #else
  204391. __asm
  204392. {
  204393. mov eax, 1
  204394. cpuid
  204395. mov cpu, edx
  204396. mov family, eax
  204397. mov ext, ebx
  204398. }
  204399. #endif
  204400. }
  204401. #ifndef __MINGW32__
  204402. __except (EXCEPTION_EXECUTE_HANDLER)
  204403. {
  204404. return 0;
  204405. }
  204406. #endif
  204407. if (familyModel != 0)
  204408. *familyModel = family;
  204409. if (extFeatures != 0)
  204410. *extFeatures = ext;
  204411. return cpu;
  204412. }*/
  204413. static void juce_getCpuVendor (char* const v)
  204414. {
  204415. int vendor[4];
  204416. zeromem (vendor, 16);
  204417. #ifdef JUCE_64BIT
  204418. #else
  204419. #ifndef __MINGW32__
  204420. __try
  204421. #endif
  204422. {
  204423. #if JUCE_GCC
  204424. unsigned int dummy = 0;
  204425. __asm__ ("cpuid" : "=a" (dummy), "=b" (vendor[0]), "=c" (vendor[2]),"=d" (vendor[1]) : "a" (0));
  204426. #else
  204427. __asm
  204428. {
  204429. mov eax, 0
  204430. cpuid
  204431. mov [vendor], ebx
  204432. mov [vendor + 4], edx
  204433. mov [vendor + 8], ecx
  204434. }
  204435. #endif
  204436. }
  204437. #ifndef __MINGW32__
  204438. __except (EXCEPTION_EXECUTE_HANDLER)
  204439. {
  204440. *v = 0;
  204441. }
  204442. #endif
  204443. #endif
  204444. memcpy (v, vendor, 16);
  204445. }
  204446. const String SystemStats::getCpuVendor() throw()
  204447. {
  204448. char v [16];
  204449. juce_getCpuVendor (v);
  204450. return String (v, 16);
  204451. }
  204452. #endif
  204453. struct CPUFlags
  204454. {
  204455. bool hasMMX : 1;
  204456. bool hasSSE : 1;
  204457. bool hasSSE2 : 1;
  204458. bool has3DNow : 1;
  204459. };
  204460. static CPUFlags cpuFlags;
  204461. bool SystemStats::hasMMX() throw()
  204462. {
  204463. return cpuFlags.hasMMX;
  204464. }
  204465. bool SystemStats::hasSSE() throw()
  204466. {
  204467. return cpuFlags.hasSSE;
  204468. }
  204469. bool SystemStats::hasSSE2() throw()
  204470. {
  204471. return cpuFlags.hasSSE2;
  204472. }
  204473. bool SystemStats::has3DNow() throw()
  204474. {
  204475. return cpuFlags.has3DNow;
  204476. }
  204477. void SystemStats::initialiseStats() throw()
  204478. {
  204479. juce_initialiseThreadEvents();
  204480. cpuFlags.hasMMX = IsProcessorFeaturePresent (PF_MMX_INSTRUCTIONS_AVAILABLE) != 0;
  204481. cpuFlags.hasSSE = IsProcessorFeaturePresent (PF_XMMI_INSTRUCTIONS_AVAILABLE) != 0;
  204482. cpuFlags.hasSSE2 = IsProcessorFeaturePresent (PF_XMMI64_INSTRUCTIONS_AVAILABLE) != 0;
  204483. #ifdef PF_AMD3D_INSTRUCTIONS_AVAILABLE
  204484. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_AMD3D_INSTRUCTIONS_AVAILABLE) != 0;
  204485. #else
  204486. cpuFlags.has3DNow = IsProcessorFeaturePresent (PF_3DNOW_INSTRUCTIONS_AVAILABLE) != 0;
  204487. #endif
  204488. LARGE_INTEGER f;
  204489. QueryPerformanceFrequency (&f);
  204490. hiResTicksPerSecond = f.QuadPart;
  204491. hiResTicksScaleFactor = 1000.0 / hiResTicksPerSecond;
  204492. String s (SystemStats::getJUCEVersion());
  204493. #ifdef JUCE_DEBUG
  204494. const MMRESULT res = timeBeginPeriod (1);
  204495. jassert (res == TIMERR_NOERROR);
  204496. #else
  204497. timeBeginPeriod (1);
  204498. #endif
  204499. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  204500. _CrtSetDbgFlag (_CRTDBG_ALLOC_MEM_DF | _CRTDBG_LEAK_CHECK_DF);
  204501. #endif
  204502. }
  204503. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  204504. {
  204505. OSVERSIONINFO info;
  204506. info.dwOSVersionInfoSize = sizeof (info);
  204507. GetVersionEx (&info);
  204508. if (info.dwPlatformId == VER_PLATFORM_WIN32_NT)
  204509. {
  204510. switch (info.dwMajorVersion)
  204511. {
  204512. case 5:
  204513. return (info.dwMinorVersion == 0) ? Win2000 : WinXP;
  204514. case 6:
  204515. return WinVista;
  204516. default:
  204517. jassertfalse // !! not a supported OS!
  204518. break;
  204519. }
  204520. }
  204521. else if (info.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS)
  204522. {
  204523. jassert (info.dwMinorVersion != 0); // !! still running on Windows 95??
  204524. return Win98;
  204525. }
  204526. return UnknownOS;
  204527. }
  204528. const String SystemStats::getOperatingSystemName() throw()
  204529. {
  204530. const char* name = "Unknown OS";
  204531. switch (getOperatingSystemType())
  204532. {
  204533. case WinVista:
  204534. name = "Windows Vista";
  204535. break;
  204536. case WinXP:
  204537. name = "Windows XP";
  204538. break;
  204539. case Win2000:
  204540. name = "Windows 2000";
  204541. break;
  204542. case Win98:
  204543. name = "Windows 98";
  204544. break;
  204545. default:
  204546. jassertfalse // !! new type of OS?
  204547. break;
  204548. }
  204549. return name;
  204550. }
  204551. bool SystemStats::isOperatingSystem64Bit() throw()
  204552. {
  204553. #ifdef _WIN64
  204554. return true;
  204555. #else
  204556. typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL);
  204557. LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS) GetProcAddress (GetModuleHandle (L"kernel32"), "IsWow64Process");
  204558. BOOL isWow64 = FALSE;
  204559. return (fnIsWow64Process != 0)
  204560. && fnIsWow64Process (GetCurrentProcess(), &isWow64)
  204561. && (isWow64 != FALSE);
  204562. #endif
  204563. }
  204564. int SystemStats::getMemorySizeInMegabytes() throw()
  204565. {
  204566. MEMORYSTATUS mem;
  204567. GlobalMemoryStatus (&mem);
  204568. return (int) (mem.dwTotalPhys / (1024 * 1024)) + 1;
  204569. }
  204570. int SystemStats::getNumCpus() throw()
  204571. {
  204572. SYSTEM_INFO systemInfo;
  204573. GetSystemInfo (&systemInfo);
  204574. return systemInfo.dwNumberOfProcessors;
  204575. }
  204576. uint32 juce_millisecondsSinceStartup() throw()
  204577. {
  204578. return (uint32) GetTickCount();
  204579. }
  204580. int64 Time::getHighResolutionTicks() throw()
  204581. {
  204582. LARGE_INTEGER ticks;
  204583. QueryPerformanceCounter (&ticks);
  204584. const int64 mainCounterAsHiResTicks = (GetTickCount() * hiResTicksPerSecond) / 1000;
  204585. const int64 newOffset = mainCounterAsHiResTicks - ticks.QuadPart;
  204586. // fix for a very obscure PCI hardware bug that can make the counter
  204587. // sometimes jump forwards by a few seconds..
  204588. static int64 hiResTicksOffset = 0;
  204589. const int64 offsetDrift = abs64 (newOffset - hiResTicksOffset);
  204590. if (offsetDrift > (hiResTicksPerSecond >> 1))
  204591. hiResTicksOffset = newOffset;
  204592. return ticks.QuadPart + hiResTicksOffset;
  204593. }
  204594. double Time::getMillisecondCounterHiRes() throw()
  204595. {
  204596. return getHighResolutionTicks() * hiResTicksScaleFactor;
  204597. }
  204598. int64 Time::getHighResolutionTicksPerSecond() throw()
  204599. {
  204600. return hiResTicksPerSecond;
  204601. }
  204602. int64 SystemStats::getClockCycleCounter() throw()
  204603. {
  204604. #if JUCE_USE_INTRINSICS
  204605. // MS intrinsics version...
  204606. return __rdtsc();
  204607. #elif JUCE_GCC
  204608. // GNU inline asm version...
  204609. unsigned int hi = 0, lo = 0;
  204610. __asm__ __volatile__ (
  204611. "xor %%eax, %%eax \n\
  204612. xor %%edx, %%edx \n\
  204613. rdtsc \n\
  204614. movl %%eax, %[lo] \n\
  204615. movl %%edx, %[hi]"
  204616. :
  204617. : [hi] "m" (hi),
  204618. [lo] "m" (lo)
  204619. : "cc", "eax", "ebx", "ecx", "edx", "memory");
  204620. return (int64) ((((uint64) hi) << 32) | lo);
  204621. #else
  204622. // MSVC inline asm version...
  204623. unsigned int hi = 0, lo = 0;
  204624. __asm
  204625. {
  204626. xor eax, eax
  204627. xor edx, edx
  204628. rdtsc
  204629. mov lo, eax
  204630. mov hi, edx
  204631. }
  204632. return (int64) ((((uint64) hi) << 32) | lo);
  204633. #endif
  204634. }
  204635. int SystemStats::getCpuSpeedInMegaherz() throw()
  204636. {
  204637. const int64 cycles = SystemStats::getClockCycleCounter();
  204638. const uint32 millis = Time::getMillisecondCounter();
  204639. int lastResult = 0;
  204640. for (;;)
  204641. {
  204642. int n = 1000000;
  204643. while (--n > 0) {}
  204644. const uint32 millisElapsed = Time::getMillisecondCounter() - millis;
  204645. const int64 cyclesNow = SystemStats::getClockCycleCounter();
  204646. if (millisElapsed > 80)
  204647. {
  204648. const int newResult = (int) (((cyclesNow - cycles) / millisElapsed) / 1000);
  204649. if (millisElapsed > 500 || (lastResult == newResult && newResult > 100))
  204650. return newResult;
  204651. lastResult = newResult;
  204652. }
  204653. }
  204654. }
  204655. bool Time::setSystemTimeToThisTime() const throw()
  204656. {
  204657. SYSTEMTIME st;
  204658. st.wDayOfWeek = 0;
  204659. st.wYear = (WORD) getYear();
  204660. st.wMonth = (WORD) (getMonth() + 1);
  204661. st.wDay = (WORD) getDayOfMonth();
  204662. st.wHour = (WORD) getHours();
  204663. st.wMinute = (WORD) getMinutes();
  204664. st.wSecond = (WORD) getSeconds();
  204665. st.wMilliseconds = (WORD) (millisSinceEpoch % 1000);
  204666. // do this twice because of daylight saving conversion problems - the
  204667. // first one sets it up, the second one kicks it in.
  204668. return SetLocalTime (&st) != 0
  204669. && SetLocalTime (&st) != 0;
  204670. }
  204671. int SystemStats::getPageSize() throw()
  204672. {
  204673. SYSTEM_INFO systemInfo;
  204674. GetSystemInfo (&systemInfo);
  204675. return systemInfo.dwPageSize;
  204676. }
  204677. #endif
  204678. /********* End of inlined file: juce_win32_SystemStats.cpp *********/
  204679. /********* Start of inlined file: juce_win32_Threads.cpp *********/
  204680. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204681. // compiled on its own).
  204682. #if JUCE_INCLUDED_FILE
  204683. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204684. extern HWND juce_messageWindowHandle;
  204685. #endif
  204686. CriticalSection::CriticalSection() throw()
  204687. {
  204688. // (just to check the MS haven't changed this structure and broken things...)
  204689. #if _MSC_VER >= 1400
  204690. static_jassert (sizeof (CRITICAL_SECTION) <= sizeof (internal));
  204691. #else
  204692. static_jassert (sizeof (CRITICAL_SECTION) <= 24);
  204693. #endif
  204694. InitializeCriticalSection ((CRITICAL_SECTION*) internal);
  204695. }
  204696. CriticalSection::~CriticalSection() throw()
  204697. {
  204698. DeleteCriticalSection ((CRITICAL_SECTION*) internal);
  204699. }
  204700. void CriticalSection::enter() const throw()
  204701. {
  204702. EnterCriticalSection ((CRITICAL_SECTION*) internal);
  204703. }
  204704. bool CriticalSection::tryEnter() const throw()
  204705. {
  204706. return TryEnterCriticalSection ((CRITICAL_SECTION*) internal) != FALSE;
  204707. }
  204708. void CriticalSection::exit() const throw()
  204709. {
  204710. LeaveCriticalSection ((CRITICAL_SECTION*) internal);
  204711. }
  204712. WaitableEvent::WaitableEvent() throw()
  204713. : internal (CreateEvent (0, FALSE, FALSE, 0))
  204714. {
  204715. }
  204716. WaitableEvent::~WaitableEvent() throw()
  204717. {
  204718. CloseHandle (internal);
  204719. }
  204720. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  204721. {
  204722. return WaitForSingleObject (internal, timeOutMillisecs) == WAIT_OBJECT_0;
  204723. }
  204724. void WaitableEvent::signal() const throw()
  204725. {
  204726. SetEvent (internal);
  204727. }
  204728. void WaitableEvent::reset() const throw()
  204729. {
  204730. ResetEvent (internal);
  204731. }
  204732. void JUCE_API juce_threadEntryPoint (void*);
  204733. static unsigned int __stdcall threadEntryProc (void* userData) throw()
  204734. {
  204735. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  204736. AttachThreadInput (GetWindowThreadProcessId (juce_messageWindowHandle, 0),
  204737. GetCurrentThreadId(), TRUE);
  204738. #endif
  204739. juce_threadEntryPoint (userData);
  204740. _endthreadex (0);
  204741. return 0;
  204742. }
  204743. void juce_CloseThreadHandle (void* handle) throw()
  204744. {
  204745. CloseHandle ((HANDLE) handle);
  204746. }
  204747. void* juce_createThread (void* userData) throw()
  204748. {
  204749. unsigned int threadId;
  204750. return (void*) _beginthreadex (0, 0,
  204751. &threadEntryProc,
  204752. userData,
  204753. 0, &threadId);
  204754. }
  204755. void juce_killThread (void* handle) throw()
  204756. {
  204757. if (handle != 0)
  204758. {
  204759. #ifdef JUCE_DEBUG
  204760. OutputDebugString (_T("** Warning - Forced thread termination **\n"));
  204761. #endif
  204762. TerminateThread (handle, 0);
  204763. }
  204764. }
  204765. void juce_setCurrentThreadName (const String& name) throw()
  204766. {
  204767. #if defined (JUCE_DEBUG) && JUCE_MSVC
  204768. struct
  204769. {
  204770. DWORD dwType;
  204771. LPCSTR szName;
  204772. DWORD dwThreadID;
  204773. DWORD dwFlags;
  204774. } info;
  204775. info.dwType = 0x1000;
  204776. info.szName = name;
  204777. info.dwThreadID = GetCurrentThreadId();
  204778. info.dwFlags = 0;
  204779. #define MS_VC_EXCEPTION 0x406d1388
  204780. __try
  204781. {
  204782. RaiseException (MS_VC_EXCEPTION, 0, sizeof (info) / sizeof (ULONG_PTR), (ULONG_PTR*) &info);
  204783. }
  204784. __except (EXCEPTION_CONTINUE_EXECUTION)
  204785. {}
  204786. #else
  204787. (void) name;
  204788. #endif
  204789. }
  204790. int64 Thread::getCurrentThreadId() throw()
  204791. {
  204792. return (int) GetCurrentThreadId();
  204793. }
  204794. // priority 1 to 10 where 5=normal, 1=low
  204795. void juce_setThreadPriority (void* threadHandle, int priority) throw()
  204796. {
  204797. int pri = THREAD_PRIORITY_TIME_CRITICAL;
  204798. if (priority < 1)
  204799. pri = THREAD_PRIORITY_IDLE;
  204800. else if (priority < 2)
  204801. pri = THREAD_PRIORITY_LOWEST;
  204802. else if (priority < 5)
  204803. pri = THREAD_PRIORITY_BELOW_NORMAL;
  204804. else if (priority < 7)
  204805. pri = THREAD_PRIORITY_NORMAL;
  204806. else if (priority < 9)
  204807. pri = THREAD_PRIORITY_ABOVE_NORMAL;
  204808. else if (priority < 10)
  204809. pri = THREAD_PRIORITY_HIGHEST;
  204810. if (threadHandle == 0)
  204811. threadHandle = GetCurrentThread();
  204812. SetThreadPriority (threadHandle, pri);
  204813. }
  204814. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  204815. {
  204816. SetThreadAffinityMask (GetCurrentThread(), affinityMask);
  204817. }
  204818. static HANDLE sleepEvent = 0;
  204819. void juce_initialiseThreadEvents() throw()
  204820. {
  204821. if (sleepEvent == 0)
  204822. #ifdef JUCE_DEBUG
  204823. sleepEvent = CreateEvent (0, 0, 0, _T("Juce Sleep Event"));
  204824. #else
  204825. sleepEvent = CreateEvent (0, 0, 0, 0);
  204826. #endif
  204827. }
  204828. void Thread::yield() throw()
  204829. {
  204830. Sleep (0);
  204831. }
  204832. void JUCE_CALLTYPE Thread::sleep (const int millisecs) throw()
  204833. {
  204834. if (millisecs >= 10)
  204835. {
  204836. Sleep (millisecs);
  204837. }
  204838. else
  204839. {
  204840. jassert (sleepEvent != 0);
  204841. // unlike Sleep() this is guaranteed to return to the current thread after
  204842. // the time expires, so we'll use this for short waits, which are more likely
  204843. // to need to be accurate
  204844. WaitForSingleObject (sleepEvent, millisecs);
  204845. }
  204846. }
  204847. static int lastProcessPriority = -1;
  204848. // called by WindowDriver because Windows does wierd things to process priority
  204849. // when you swap apps, and this forces an update when the app is brought to the front.
  204850. void juce_repeatLastProcessPriority() throw()
  204851. {
  204852. if (lastProcessPriority >= 0) // (avoid changing this if it's not been explicitly set by the app..)
  204853. {
  204854. DWORD p;
  204855. switch (lastProcessPriority)
  204856. {
  204857. case Process::LowPriority:
  204858. p = IDLE_PRIORITY_CLASS;
  204859. break;
  204860. case Process::NormalPriority:
  204861. p = NORMAL_PRIORITY_CLASS;
  204862. break;
  204863. case Process::HighPriority:
  204864. p = HIGH_PRIORITY_CLASS;
  204865. break;
  204866. case Process::RealtimePriority:
  204867. p = REALTIME_PRIORITY_CLASS;
  204868. break;
  204869. default:
  204870. jassertfalse // bad priority value
  204871. return;
  204872. }
  204873. SetPriorityClass (GetCurrentProcess(), p);
  204874. }
  204875. }
  204876. void Process::setPriority (ProcessPriority prior)
  204877. {
  204878. if (lastProcessPriority != (int) prior)
  204879. {
  204880. lastProcessPriority = (int) prior;
  204881. juce_repeatLastProcessPriority();
  204882. }
  204883. }
  204884. bool JUCE_API JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  204885. {
  204886. return IsDebuggerPresent() != FALSE;
  204887. }
  204888. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  204889. {
  204890. return juce_isRunningUnderDebugger();
  204891. }
  204892. void Process::raisePrivilege()
  204893. {
  204894. jassertfalse // xxx not implemented
  204895. }
  204896. void Process::lowerPrivilege()
  204897. {
  204898. jassertfalse // xxx not implemented
  204899. }
  204900. void Process::terminate()
  204901. {
  204902. #if defined (JUCE_DEBUG) && JUCE_MSVC && JUCE_CHECK_MEMORY_LEAKS
  204903. _CrtDumpMemoryLeaks();
  204904. #endif
  204905. // bullet in the head in case there's a problem shutting down..
  204906. ExitProcess (0);
  204907. }
  204908. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  204909. {
  204910. void* result = 0;
  204911. JUCE_TRY
  204912. {
  204913. result = (void*) LoadLibrary (name);
  204914. }
  204915. JUCE_CATCH_ALL
  204916. return result;
  204917. }
  204918. void PlatformUtilities::freeDynamicLibrary (void* h)
  204919. {
  204920. JUCE_TRY
  204921. {
  204922. if (h != 0)
  204923. FreeLibrary ((HMODULE) h);
  204924. }
  204925. JUCE_CATCH_ALL
  204926. }
  204927. void* PlatformUtilities::getProcedureEntryPoint (void* h, const String& name)
  204928. {
  204929. return (h != 0) ? (void*) GetProcAddress ((HMODULE) h, name)
  204930. : 0;
  204931. }
  204932. InterProcessLock::InterProcessLock (const String& name_) throw()
  204933. : internal (0),
  204934. name (name_),
  204935. reentrancyLevel (0)
  204936. {
  204937. }
  204938. InterProcessLock::~InterProcessLock() throw()
  204939. {
  204940. exit();
  204941. }
  204942. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  204943. {
  204944. if (reentrancyLevel++ == 0)
  204945. {
  204946. internal = CreateMutex (0, TRUE, name);
  204947. if (internal != 0 && GetLastError() == ERROR_ALREADY_EXISTS)
  204948. {
  204949. if (timeOutMillisecs == 0
  204950. || WaitForSingleObject (internal, (timeOutMillisecs < 0) ? INFINITE : timeOutMillisecs)
  204951. == WAIT_TIMEOUT)
  204952. {
  204953. ReleaseMutex (internal);
  204954. CloseHandle (internal);
  204955. internal = 0;
  204956. }
  204957. }
  204958. }
  204959. return (internal != 0);
  204960. }
  204961. void InterProcessLock::exit() throw()
  204962. {
  204963. if (--reentrancyLevel == 0 && internal != 0)
  204964. {
  204965. ReleaseMutex (internal);
  204966. CloseHandle (internal);
  204967. internal = 0;
  204968. }
  204969. }
  204970. #endif
  204971. /********* End of inlined file: juce_win32_Threads.cpp *********/
  204972. /********* Start of inlined file: juce_win32_Files.cpp *********/
  204973. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  204974. // compiled on its own).
  204975. #if JUCE_INCLUDED_FILE
  204976. #ifndef CSIDL_MYMUSIC
  204977. #define CSIDL_MYMUSIC 0x000d
  204978. #endif
  204979. #ifndef CSIDL_MYVIDEO
  204980. #define CSIDL_MYVIDEO 0x000e
  204981. #endif
  204982. const tchar File::separator = T('\\');
  204983. const tchar* File::separatorString = T("\\");
  204984. bool juce_fileExists (const String& fileName,
  204985. const bool dontCountDirectories) throw()
  204986. {
  204987. if (fileName.isEmpty())
  204988. return false;
  204989. const DWORD attr = GetFileAttributes (fileName);
  204990. return dontCountDirectories ? ((attr & FILE_ATTRIBUTE_DIRECTORY) == 0)
  204991. : (attr != 0xffffffff);
  204992. }
  204993. bool juce_isDirectory (const String& fileName) throw()
  204994. {
  204995. const DWORD attr = GetFileAttributes (fileName);
  204996. return (attr != 0xffffffff)
  204997. && ((attr & FILE_ATTRIBUTE_DIRECTORY) != 0);
  204998. }
  204999. bool juce_canWriteToFile (const String& fileName) throw()
  205000. {
  205001. const DWORD attr = GetFileAttributes (fileName);
  205002. return ((attr & FILE_ATTRIBUTE_READONLY) == 0);
  205003. }
  205004. bool juce_setFileReadOnly (const String& fileName,
  205005. bool isReadOnly)
  205006. {
  205007. DWORD attr = GetFileAttributes (fileName);
  205008. if (attr == 0xffffffff)
  205009. return false;
  205010. if (isReadOnly != juce_canWriteToFile (fileName))
  205011. return true;
  205012. if (isReadOnly)
  205013. attr |= FILE_ATTRIBUTE_READONLY;
  205014. else
  205015. attr &= ~FILE_ATTRIBUTE_READONLY;
  205016. return SetFileAttributes (fileName, attr) != FALSE;
  205017. }
  205018. bool File::isHidden() const throw()
  205019. {
  205020. return (GetFileAttributes (getFullPathName()) & FILE_ATTRIBUTE_HIDDEN) != 0;
  205021. }
  205022. bool juce_deleteFile (const String& fileName) throw()
  205023. {
  205024. if (juce_isDirectory (fileName))
  205025. return RemoveDirectory (fileName) != 0;
  205026. return DeleteFile (fileName) != 0;
  205027. }
  205028. bool juce_moveFile (const String& source, const String& dest) throw()
  205029. {
  205030. return MoveFile (source, dest) != 0;
  205031. }
  205032. bool juce_copyFile (const String& source, const String& dest) throw()
  205033. {
  205034. return CopyFile (source, dest, false) != 0;
  205035. }
  205036. void juce_createDirectory (const String& fileName) throw()
  205037. {
  205038. if (! juce_fileExists (fileName, true))
  205039. {
  205040. CreateDirectory (fileName, 0);
  205041. }
  205042. }
  205043. // return 0 if not possible
  205044. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  205045. {
  205046. HANDLE h;
  205047. if (forWriting)
  205048. {
  205049. h = CreateFile (fileName, GENERIC_WRITE, FILE_SHARE_READ, 0,
  205050. OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
  205051. if (h != INVALID_HANDLE_VALUE)
  205052. SetFilePointer (h, 0, 0, FILE_END);
  205053. else
  205054. h = 0;
  205055. }
  205056. else
  205057. {
  205058. h = CreateFile (fileName, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, 0,
  205059. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, 0);
  205060. if (h == INVALID_HANDLE_VALUE)
  205061. h = 0;
  205062. }
  205063. return (void*) h;
  205064. }
  205065. void juce_fileClose (void* handle) throw()
  205066. {
  205067. CloseHandle (handle);
  205068. }
  205069. int juce_fileRead (void* handle, void* buffer, int size) throw()
  205070. {
  205071. DWORD num = 0;
  205072. ReadFile ((HANDLE) handle, buffer, size, &num, 0);
  205073. return num;
  205074. }
  205075. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  205076. {
  205077. DWORD num;
  205078. WriteFile ((HANDLE) handle,
  205079. buffer, size,
  205080. &num, 0);
  205081. return num;
  205082. }
  205083. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  205084. {
  205085. LARGE_INTEGER li;
  205086. li.QuadPart = pos;
  205087. li.LowPart = SetFilePointer ((HANDLE) handle,
  205088. li.LowPart,
  205089. &li.HighPart,
  205090. FILE_BEGIN); // (returns -1 if it fails)
  205091. return li.QuadPart;
  205092. }
  205093. int64 juce_fileGetPosition (void* handle) throw()
  205094. {
  205095. LARGE_INTEGER li;
  205096. li.QuadPart = 0;
  205097. li.LowPart = SetFilePointer ((HANDLE) handle,
  205098. 0, &li.HighPart,
  205099. FILE_CURRENT); // (returns -1 if it fails)
  205100. return jmax ((int64) 0, li.QuadPart);
  205101. }
  205102. void juce_fileFlush (void* handle) throw()
  205103. {
  205104. FlushFileBuffers ((HANDLE) handle);
  205105. }
  205106. int64 juce_getFileSize (const String& fileName) throw()
  205107. {
  205108. WIN32_FILE_ATTRIBUTE_DATA attributes;
  205109. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  205110. {
  205111. return (((int64) attributes.nFileSizeHigh) << 32)
  205112. | attributes.nFileSizeLow;
  205113. }
  205114. return 0;
  205115. }
  205116. static int64 fileTimeToTime (const FILETIME* const ft) throw()
  205117. {
  205118. // tell me if this fails!
  205119. static_jassert (sizeof (ULARGE_INTEGER) == sizeof (FILETIME));
  205120. #if JUCE_GCC
  205121. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000LL) / 10000;
  205122. #else
  205123. return (((const ULARGE_INTEGER*) ft)->QuadPart - 116444736000000000) / 10000;
  205124. #endif
  205125. }
  205126. static void timeToFileTime (const int64 time, FILETIME* const ft) throw()
  205127. {
  205128. #if JUCE_GCC
  205129. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000LL;
  205130. #else
  205131. ((ULARGE_INTEGER*) ft)->QuadPart = time * 10000 + 116444736000000000;
  205132. #endif
  205133. }
  205134. void juce_getFileTimes (const String& fileName,
  205135. int64& modificationTime,
  205136. int64& accessTime,
  205137. int64& creationTime) throw()
  205138. {
  205139. WIN32_FILE_ATTRIBUTE_DATA attributes;
  205140. if (GetFileAttributesEx (fileName, GetFileExInfoStandard, &attributes))
  205141. {
  205142. modificationTime = fileTimeToTime (&attributes.ftLastWriteTime);
  205143. creationTime = fileTimeToTime (&attributes.ftCreationTime);
  205144. accessTime = fileTimeToTime (&attributes.ftLastAccessTime);
  205145. }
  205146. else
  205147. {
  205148. creationTime = accessTime = modificationTime = 0;
  205149. }
  205150. }
  205151. bool juce_setFileTimes (const String& fileName,
  205152. int64 modificationTime,
  205153. int64 accessTime,
  205154. int64 creationTime) throw()
  205155. {
  205156. FILETIME m, a, c;
  205157. if (modificationTime > 0)
  205158. timeToFileTime (modificationTime, &m);
  205159. if (accessTime > 0)
  205160. timeToFileTime (accessTime, &a);
  205161. if (creationTime > 0)
  205162. timeToFileTime (creationTime, &c);
  205163. void* const h = juce_fileOpen (fileName, true);
  205164. bool ok = false;
  205165. if (h != 0)
  205166. {
  205167. ok = SetFileTime ((HANDLE) h,
  205168. (creationTime > 0) ? &c : 0,
  205169. (accessTime > 0) ? &a : 0,
  205170. (modificationTime > 0) ? &m : 0) != 0;
  205171. juce_fileClose (h);
  205172. }
  205173. return ok;
  205174. }
  205175. // return '\0' separated list of strings
  205176. const StringArray juce_getFileSystemRoots() throw()
  205177. {
  205178. TCHAR buffer [2048];
  205179. buffer[0] = 0;
  205180. buffer[1] = 0;
  205181. GetLogicalDriveStrings (2048, buffer);
  205182. TCHAR* n = buffer;
  205183. StringArray roots;
  205184. while (*n != 0)
  205185. {
  205186. roots.add (String (n));
  205187. while (*n++ != 0)
  205188. {
  205189. }
  205190. }
  205191. roots.sort (true);
  205192. return roots;
  205193. }
  205194. const String juce_getVolumeLabel (const String& filenameOnVolume,
  205195. int& volumeSerialNumber) throw()
  205196. {
  205197. TCHAR n [4];
  205198. n[0] = *(const TCHAR*) filenameOnVolume;
  205199. n[1] = L':';
  205200. n[2] = L'\\';
  205201. n[3] = 0;
  205202. TCHAR dest [64];
  205203. DWORD serialNum;
  205204. if (! GetVolumeInformation (n, dest, 64, (DWORD*) &serialNum, 0, 0, 0, 0))
  205205. {
  205206. dest[0] = 0;
  205207. serialNum = 0;
  205208. }
  205209. volumeSerialNumber = serialNum;
  205210. return String (dest);
  205211. }
  205212. int64 File::getBytesFreeOnVolume() const throw()
  205213. {
  205214. String fn (getFullPathName());
  205215. if (fn[1] == T(':'))
  205216. fn = fn.substring (0, 2) + T("\\");
  205217. ULARGE_INTEGER spc;
  205218. ULARGE_INTEGER tot;
  205219. ULARGE_INTEGER totFree;
  205220. if (GetDiskFreeSpaceEx (fn, &spc, &tot, &totFree))
  205221. return (int64)(spc.QuadPart);
  205222. return 0;
  205223. }
  205224. static unsigned int getWindowsDriveType (const String& fileName) throw()
  205225. {
  205226. TCHAR n[4];
  205227. n[0] = *(const TCHAR*) fileName;
  205228. n[1] = L':';
  205229. n[2] = L'\\';
  205230. n[3] = 0;
  205231. return GetDriveType (n);
  205232. }
  205233. bool File::isOnCDRomDrive() const throw()
  205234. {
  205235. return getWindowsDriveType (getFullPathName()) == DRIVE_CDROM;
  205236. }
  205237. bool File::isOnHardDisk() const throw()
  205238. {
  205239. if (fullPath.isEmpty())
  205240. return false;
  205241. const unsigned int n = getWindowsDriveType (getFullPathName());
  205242. if (fullPath.toLowerCase()[0] <= 'b'
  205243. && fullPath[1] == T(':'))
  205244. {
  205245. return n != DRIVE_REMOVABLE;
  205246. }
  205247. else
  205248. {
  205249. return n != DRIVE_CDROM && n != DRIVE_REMOTE;
  205250. }
  205251. }
  205252. bool File::isOnRemovableDrive() const throw()
  205253. {
  205254. if (fullPath.isEmpty())
  205255. return false;
  205256. const unsigned int n = getWindowsDriveType (getFullPathName());
  205257. return n == DRIVE_CDROM
  205258. || n == DRIVE_REMOTE
  205259. || n == DRIVE_REMOVABLE
  205260. || n == DRIVE_RAMDISK;
  205261. }
  205262. #define MAX_PATH_CHARS (MAX_PATH + 256)
  205263. static const File juce_getSpecialFolderPath (int type) throw()
  205264. {
  205265. WCHAR path [MAX_PATH_CHARS];
  205266. if (SHGetSpecialFolderPath (0, path, type, 0))
  205267. return File (String (path));
  205268. return File::nonexistent;
  205269. }
  205270. const File JUCE_CALLTYPE File::getSpecialLocation (const SpecialLocationType type)
  205271. {
  205272. int csidlType = 0;
  205273. switch (type)
  205274. {
  205275. case userHomeDirectory:
  205276. case userDocumentsDirectory:
  205277. csidlType = CSIDL_PERSONAL;
  205278. break;
  205279. case userDesktopDirectory:
  205280. csidlType = CSIDL_DESKTOP;
  205281. break;
  205282. case userApplicationDataDirectory:
  205283. csidlType = CSIDL_APPDATA;
  205284. break;
  205285. case commonApplicationDataDirectory:
  205286. csidlType = CSIDL_COMMON_APPDATA;
  205287. break;
  205288. case globalApplicationsDirectory:
  205289. csidlType = CSIDL_PROGRAM_FILES;
  205290. break;
  205291. case userMusicDirectory:
  205292. csidlType = CSIDL_MYMUSIC;
  205293. break;
  205294. case userMoviesDirectory:
  205295. csidlType = CSIDL_MYVIDEO;
  205296. break;
  205297. case tempDirectory:
  205298. {
  205299. WCHAR dest [2048];
  205300. dest[0] = 0;
  205301. GetTempPath (2048, dest);
  205302. return File (String (dest));
  205303. }
  205304. case currentExecutableFile:
  205305. case currentApplicationFile:
  205306. {
  205307. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  205308. WCHAR dest [MAX_PATH_CHARS];
  205309. dest[0] = 0;
  205310. GetModuleFileName (moduleHandle, dest, MAX_PATH_CHARS);
  205311. return File (String (dest));
  205312. }
  205313. break;
  205314. default:
  205315. jassertfalse // unknown type?
  205316. return File::nonexistent;
  205317. }
  205318. return juce_getSpecialFolderPath (csidlType);
  205319. }
  205320. void juce_setCurrentExecutableFileName (const String&) throw()
  205321. {
  205322. // n/a on windows
  205323. }
  205324. const File File::getCurrentWorkingDirectory() throw()
  205325. {
  205326. WCHAR dest [MAX_PATH_CHARS];
  205327. dest[0] = 0;
  205328. GetCurrentDirectory (MAX_PATH_CHARS, dest);
  205329. return File (String (dest));
  205330. }
  205331. bool File::setAsCurrentWorkingDirectory() const throw()
  205332. {
  205333. return SetCurrentDirectory (getFullPathName()) != FALSE;
  205334. }
  205335. template <class FindDataType>
  205336. static void getFindFileInfo (FindDataType& findData,
  205337. String& filename, bool* const isDir, bool* const isHidden,
  205338. int64* const fileSize, Time* const modTime, Time* const creationTime,
  205339. bool* const isReadOnly) throw()
  205340. {
  205341. filename = findData.cFileName;
  205342. if (isDir != 0)
  205343. *isDir = ((findData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0);
  205344. if (isHidden != 0)
  205345. *isHidden = ((findData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) != 0);
  205346. if (fileSize != 0)
  205347. *fileSize = findData.nFileSizeLow + (((int64) findData.nFileSizeHigh) << 32);
  205348. if (modTime != 0)
  205349. *modTime = fileTimeToTime (&findData.ftLastWriteTime);
  205350. if (creationTime != 0)
  205351. *creationTime = fileTimeToTime (&findData.ftCreationTime);
  205352. if (isReadOnly != 0)
  205353. *isReadOnly = ((findData.dwFileAttributes & FILE_ATTRIBUTE_READONLY) != 0);
  205354. }
  205355. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResult,
  205356. bool* isDir, bool* isHidden, int64* fileSize,
  205357. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  205358. {
  205359. String wc (directory);
  205360. if (! wc.endsWithChar (File::separator))
  205361. wc += File::separator;
  205362. wc += wildCard;
  205363. WIN32_FIND_DATA findData;
  205364. HANDLE h = FindFirstFile (wc, &findData);
  205365. if (h != INVALID_HANDLE_VALUE)
  205366. {
  205367. getFindFileInfo (findData, firstResult, isDir, isHidden, fileSize,
  205368. modTime, creationTime, isReadOnly);
  205369. return h;
  205370. }
  205371. firstResult = String::empty;
  205372. return 0;
  205373. }
  205374. bool juce_findFileNext (void* handle, String& resultFile,
  205375. bool* isDir, bool* isHidden, int64* fileSize,
  205376. Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  205377. {
  205378. WIN32_FIND_DATA findData;
  205379. if (handle != 0 && FindNextFile ((HANDLE) handle, &findData) != 0)
  205380. {
  205381. getFindFileInfo (findData, resultFile, isDir, isHidden, fileSize,
  205382. modTime, creationTime, isReadOnly);
  205383. return true;
  205384. }
  205385. resultFile = String::empty;
  205386. return false;
  205387. }
  205388. void juce_findFileClose (void* handle) throw()
  205389. {
  205390. FindClose (handle);
  205391. }
  205392. bool juce_launchFile (const String& fileName,
  205393. const String& parameters) throw()
  205394. {
  205395. HINSTANCE hInstance = 0;
  205396. JUCE_TRY
  205397. {
  205398. hInstance = ShellExecute (0, 0, fileName, parameters, 0, SW_SHOWDEFAULT);
  205399. }
  205400. JUCE_CATCH_ALL
  205401. return hInstance > (HINSTANCE) 32;
  205402. }
  205403. struct NamedPipeInternal
  205404. {
  205405. HANDLE pipeH;
  205406. HANDLE cancelEvent;
  205407. bool connected, createdPipe;
  205408. NamedPipeInternal()
  205409. : pipeH (0),
  205410. cancelEvent (0),
  205411. connected (false),
  205412. createdPipe (false)
  205413. {
  205414. cancelEvent = CreateEvent (0, FALSE, FALSE, 0);
  205415. }
  205416. ~NamedPipeInternal()
  205417. {
  205418. disconnect();
  205419. if (pipeH != 0)
  205420. CloseHandle (pipeH);
  205421. CloseHandle (cancelEvent);
  205422. }
  205423. bool connect (const int timeOutMs)
  205424. {
  205425. if (! createdPipe)
  205426. return true;
  205427. if (! connected)
  205428. {
  205429. OVERLAPPED over;
  205430. zerostruct (over);
  205431. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  205432. if (ConnectNamedPipe (pipeH, &over))
  205433. {
  205434. connected = false; // yes, you read that right. In overlapped mode it should always return 0.
  205435. }
  205436. else
  205437. {
  205438. const int err = GetLastError();
  205439. if (err == ERROR_IO_PENDING || err == ERROR_PIPE_LISTENING)
  205440. {
  205441. HANDLE handles[] = { over.hEvent, cancelEvent };
  205442. if (WaitForMultipleObjects (2, handles, FALSE,
  205443. timeOutMs >= 0 ? timeOutMs : INFINITE) == WAIT_OBJECT_0)
  205444. connected = true;
  205445. }
  205446. else if (err == ERROR_PIPE_CONNECTED)
  205447. {
  205448. connected = true;
  205449. }
  205450. }
  205451. CloseHandle (over.hEvent);
  205452. }
  205453. return connected;
  205454. }
  205455. void disconnect()
  205456. {
  205457. if (connected)
  205458. {
  205459. DisconnectNamedPipe (pipeH);
  205460. connected = false;
  205461. }
  205462. }
  205463. };
  205464. void NamedPipe::close()
  205465. {
  205466. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  205467. delete intern;
  205468. internal = 0;
  205469. }
  205470. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  205471. {
  205472. close();
  205473. NamedPipeInternal* const intern = new NamedPipeInternal();
  205474. String file ("\\\\.\\pipe\\");
  205475. file += pipeName;
  205476. intern->createdPipe = createPipe;
  205477. if (createPipe)
  205478. {
  205479. intern->pipeH = CreateNamedPipe (file, PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED, 0,
  205480. PIPE_UNLIMITED_INSTANCES,
  205481. 4096, 4096, 0, NULL);
  205482. }
  205483. else
  205484. {
  205485. intern->pipeH = CreateFile (file, GENERIC_READ | GENERIC_WRITE, 0, 0, OPEN_EXISTING,
  205486. FILE_FLAG_OVERLAPPED, 0);
  205487. }
  205488. if (intern->pipeH != INVALID_HANDLE_VALUE)
  205489. {
  205490. internal = intern;
  205491. return true;
  205492. }
  205493. delete intern;
  205494. return false;
  205495. }
  205496. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int timeOutMilliseconds)
  205497. {
  205498. int bytesRead = -1;
  205499. bool waitAgain = true;
  205500. while (waitAgain && internal != 0)
  205501. {
  205502. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  205503. waitAgain = false;
  205504. if (! intern->connect (timeOutMilliseconds))
  205505. break;
  205506. if (maxBytesToRead <= 0)
  205507. return 0;
  205508. OVERLAPPED over;
  205509. zerostruct (over);
  205510. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  205511. unsigned long numRead;
  205512. if (ReadFile (intern->pipeH, destBuffer, maxBytesToRead, &numRead, &over))
  205513. {
  205514. bytesRead = (int) numRead;
  205515. }
  205516. else if (GetLastError() == ERROR_IO_PENDING)
  205517. {
  205518. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  205519. DWORD waitResult = WaitForMultipleObjects (2, handles, FALSE,
  205520. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  205521. : INFINITE);
  205522. if (waitResult != WAIT_OBJECT_0)
  205523. {
  205524. // if the operation timed out, let's cancel it...
  205525. CancelIo (intern->pipeH);
  205526. WaitForSingleObject (over.hEvent, INFINITE); // makes sure cancel is complete
  205527. }
  205528. if (GetOverlappedResult (intern->pipeH, &over, &numRead, FALSE))
  205529. {
  205530. bytesRead = (int) numRead;
  205531. }
  205532. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  205533. {
  205534. intern->disconnect();
  205535. waitAgain = true;
  205536. }
  205537. }
  205538. else
  205539. {
  205540. waitAgain = internal != 0;
  205541. Sleep (5);
  205542. }
  205543. CloseHandle (over.hEvent);
  205544. }
  205545. return bytesRead;
  205546. }
  205547. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  205548. {
  205549. int bytesWritten = -1;
  205550. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  205551. if (intern != 0 && intern->connect (timeOutMilliseconds))
  205552. {
  205553. if (numBytesToWrite <= 0)
  205554. return 0;
  205555. OVERLAPPED over;
  205556. zerostruct (over);
  205557. over.hEvent = CreateEvent (0, TRUE, FALSE, 0);
  205558. unsigned long numWritten;
  205559. if (WriteFile (intern->pipeH, sourceBuffer, numBytesToWrite, &numWritten, &over))
  205560. {
  205561. bytesWritten = (int) numWritten;
  205562. }
  205563. else if (GetLastError() == ERROR_IO_PENDING)
  205564. {
  205565. HANDLE handles[] = { over.hEvent, intern->cancelEvent };
  205566. DWORD waitResult;
  205567. waitResult = WaitForMultipleObjects (2, handles, FALSE,
  205568. timeOutMilliseconds >= 0 ? timeOutMilliseconds
  205569. : INFINITE);
  205570. if (waitResult != WAIT_OBJECT_0)
  205571. {
  205572. CancelIo (intern->pipeH);
  205573. WaitForSingleObject (over.hEvent, INFINITE);
  205574. }
  205575. if (GetOverlappedResult (intern->pipeH, &over, &numWritten, FALSE))
  205576. {
  205577. bytesWritten = (int) numWritten;
  205578. }
  205579. else if (GetLastError() == ERROR_BROKEN_PIPE && intern->createdPipe)
  205580. {
  205581. intern->disconnect();
  205582. }
  205583. }
  205584. CloseHandle (over.hEvent);
  205585. }
  205586. return bytesWritten;
  205587. }
  205588. void NamedPipe::cancelPendingReads()
  205589. {
  205590. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  205591. if (intern != 0)
  205592. SetEvent (intern->cancelEvent);
  205593. }
  205594. #endif
  205595. /********* End of inlined file: juce_win32_Files.cpp *********/
  205596. /********* Start of inlined file: juce_win32_Network.cpp *********/
  205597. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205598. // compiled on its own).
  205599. #if JUCE_INCLUDED_FILE
  205600. #ifndef INTERNET_FLAG_NEED_FILE
  205601. #define INTERNET_FLAG_NEED_FILE 0x00000010
  205602. #endif
  205603. bool juce_isOnLine()
  205604. {
  205605. DWORD connectionType;
  205606. return InternetGetConnectedState (&connectionType, 0) != 0
  205607. || (connectionType & (INTERNET_CONNECTION_LAN | INTERNET_CONNECTION_PROXY)) != 0;
  205608. }
  205609. struct ConnectionAndRequestStruct
  205610. {
  205611. HINTERNET connection, request;
  205612. };
  205613. static HINTERNET sessionHandle = 0;
  205614. void* juce_openInternetFile (const String& url,
  205615. const String& headers,
  205616. const MemoryBlock& postData,
  205617. const bool isPost,
  205618. URL::OpenStreamProgressCallback* callback,
  205619. void* callbackContext,
  205620. int timeOutMs)
  205621. {
  205622. if (sessionHandle == 0)
  205623. sessionHandle = InternetOpen (_T("juce"),
  205624. INTERNET_OPEN_TYPE_PRECONFIG,
  205625. 0, 0, 0);
  205626. if (sessionHandle != 0)
  205627. {
  205628. // break up the url..
  205629. TCHAR file[1024], server[1024];
  205630. URL_COMPONENTS uc;
  205631. zerostruct (uc);
  205632. uc.dwStructSize = sizeof (uc);
  205633. uc.dwUrlPathLength = sizeof (file);
  205634. uc.dwHostNameLength = sizeof (server);
  205635. uc.lpszUrlPath = file;
  205636. uc.lpszHostName = server;
  205637. if (InternetCrackUrl (url, 0, 0, &uc))
  205638. {
  205639. if (timeOutMs == 0)
  205640. timeOutMs = 30000;
  205641. else if (timeOutMs < 0)
  205642. timeOutMs = -1;
  205643. InternetSetOption (sessionHandle, INTERNET_OPTION_CONNECT_TIMEOUT, &timeOutMs, sizeof (timeOutMs));
  205644. const bool isFtp = url.startsWithIgnoreCase (T("ftp:"));
  205645. HINTERNET connection = InternetConnect (sessionHandle,
  205646. uc.lpszHostName,
  205647. uc.nPort,
  205648. _T(""), _T(""),
  205649. isFtp ? INTERNET_SERVICE_FTP
  205650. : INTERNET_SERVICE_HTTP,
  205651. 0, 0);
  205652. if (connection != 0)
  205653. {
  205654. if (isFtp)
  205655. {
  205656. HINTERNET request = FtpOpenFile (connection,
  205657. uc.lpszUrlPath,
  205658. GENERIC_READ,
  205659. FTP_TRANSFER_TYPE_BINARY | INTERNET_FLAG_NEED_FILE,
  205660. 0);
  205661. ConnectionAndRequestStruct* const result = new ConnectionAndRequestStruct();
  205662. result->connection = connection;
  205663. result->request = request;
  205664. return result;
  205665. }
  205666. else
  205667. {
  205668. const TCHAR* mimeTypes[] = { _T("*/*"), 0 };
  205669. DWORD flags = INTERNET_FLAG_RELOAD | INTERNET_FLAG_NO_CACHE_WRITE;
  205670. if (url.startsWithIgnoreCase (T("https:")))
  205671. flags |= INTERNET_FLAG_SECURE; // (this flag only seems necessary if the OS is running IE6 -
  205672. // IE7 seems to automatically work out when it's https)
  205673. HINTERNET request = HttpOpenRequest (connection,
  205674. isPost ? _T("POST")
  205675. : _T("GET"),
  205676. uc.lpszUrlPath,
  205677. 0, 0, mimeTypes, flags, 0);
  205678. if (request != 0)
  205679. {
  205680. INTERNET_BUFFERS buffers;
  205681. zerostruct (buffers);
  205682. buffers.dwStructSize = sizeof (INTERNET_BUFFERS);
  205683. buffers.lpcszHeader = (LPCTSTR) headers;
  205684. buffers.dwHeadersLength = headers.length();
  205685. buffers.dwBufferTotal = (DWORD) postData.getSize();
  205686. ConnectionAndRequestStruct* result = 0;
  205687. if (HttpSendRequestEx (request, &buffers, 0, HSR_INITIATE, 0))
  205688. {
  205689. int bytesSent = 0;
  205690. for (;;)
  205691. {
  205692. const int bytesToDo = jmin (1024, postData.getSize() - bytesSent);
  205693. DWORD bytesDone = 0;
  205694. if (bytesToDo > 0
  205695. && ! InternetWriteFile (request,
  205696. ((const char*) postData.getData()) + bytesSent,
  205697. bytesToDo, &bytesDone))
  205698. {
  205699. break;
  205700. }
  205701. if (bytesToDo == 0 || (int) bytesDone < bytesToDo)
  205702. {
  205703. result = new ConnectionAndRequestStruct();
  205704. result->connection = connection;
  205705. result->request = request;
  205706. HttpEndRequest (request, 0, 0, 0);
  205707. return result;
  205708. }
  205709. bytesSent += bytesDone;
  205710. if (callback != 0 && ! callback (callbackContext, bytesSent, postData.getSize()))
  205711. break;
  205712. }
  205713. }
  205714. InternetCloseHandle (request);
  205715. }
  205716. InternetCloseHandle (connection);
  205717. }
  205718. }
  205719. }
  205720. }
  205721. return 0;
  205722. }
  205723. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  205724. {
  205725. DWORD bytesRead = 0;
  205726. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  205727. if (crs != 0)
  205728. InternetReadFile (crs->request,
  205729. buffer, bytesToRead,
  205730. &bytesRead);
  205731. return bytesRead;
  205732. }
  205733. int juce_seekInInternetFile (void* handle, int newPosition)
  205734. {
  205735. if (handle != 0)
  205736. {
  205737. const ConnectionAndRequestStruct* const crs = (const ConnectionAndRequestStruct*) handle;
  205738. return InternetSetFilePointer (crs->request,
  205739. newPosition, 0,
  205740. FILE_BEGIN, 0);
  205741. }
  205742. else
  205743. {
  205744. return -1;
  205745. }
  205746. }
  205747. void juce_closeInternetFile (void* handle)
  205748. {
  205749. if (handle != 0)
  205750. {
  205751. ConnectionAndRequestStruct* const crs = (ConnectionAndRequestStruct*) handle;
  205752. InternetCloseHandle (crs->request);
  205753. InternetCloseHandle (crs->connection);
  205754. delete crs;
  205755. }
  205756. }
  205757. static int getMACAddressViaGetAdaptersInfo (int64* addresses, int maxNum, const bool littleEndian) throw()
  205758. {
  205759. int numFound = 0;
  205760. DynamicLibraryLoader dll ("iphlpapi.dll");
  205761. DynamicLibraryImport (GetAdaptersInfo, getAdaptersInfo, DWORD, dll, (PIP_ADAPTER_INFO, PULONG))
  205762. if (getAdaptersInfo != 0)
  205763. {
  205764. ULONG len = sizeof (IP_ADAPTER_INFO);
  205765. MemoryBlock mb;
  205766. PIP_ADAPTER_INFO adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205767. if (getAdaptersInfo (adapterInfo, &len) == ERROR_BUFFER_OVERFLOW)
  205768. {
  205769. mb.setSize (len);
  205770. adapterInfo = (PIP_ADAPTER_INFO) mb.getData();
  205771. }
  205772. if (getAdaptersInfo (adapterInfo, &len) == NO_ERROR)
  205773. {
  205774. PIP_ADAPTER_INFO adapter = adapterInfo;
  205775. while (adapter != 0)
  205776. {
  205777. int64 mac = 0;
  205778. for (unsigned int i = 0; i < adapter->AddressLength; ++i)
  205779. mac = (mac << 8) | adapter->Address[i];
  205780. if (littleEndian)
  205781. mac = (int64) swapByteOrder ((uint64) mac);
  205782. if (numFound < maxNum && mac != 0)
  205783. addresses [numFound++] = mac;
  205784. adapter = adapter->Next;
  205785. }
  205786. }
  205787. }
  205788. return numFound;
  205789. }
  205790. static int getMACAddressesViaNetBios (int64* addresses, int maxNum, const bool littleEndian) throw()
  205791. {
  205792. int numFound = 0;
  205793. DynamicLibraryLoader dll ("netapi32.dll");
  205794. DynamicLibraryImport (Netbios, NetbiosCall, UCHAR, dll, (PNCB))
  205795. if (NetbiosCall != 0)
  205796. {
  205797. NCB ncb;
  205798. zerostruct (ncb);
  205799. typedef struct _ASTAT_
  205800. {
  205801. ADAPTER_STATUS adapt;
  205802. NAME_BUFFER NameBuff [30];
  205803. } ASTAT;
  205804. ASTAT astat;
  205805. zerostruct (astat);
  205806. LANA_ENUM enums;
  205807. zerostruct (enums);
  205808. ncb.ncb_command = NCBENUM;
  205809. ncb.ncb_buffer = (unsigned char*) &enums;
  205810. ncb.ncb_length = sizeof (LANA_ENUM);
  205811. NetbiosCall (&ncb);
  205812. for (int i = 0; i < enums.length; ++i)
  205813. {
  205814. zerostruct (ncb);
  205815. ncb.ncb_command = NCBRESET;
  205816. ncb.ncb_lana_num = enums.lana[i];
  205817. if (NetbiosCall (&ncb) == 0)
  205818. {
  205819. zerostruct (ncb);
  205820. memcpy (ncb.ncb_callname, "* ", NCBNAMSZ);
  205821. ncb.ncb_command = NCBASTAT;
  205822. ncb.ncb_lana_num = enums.lana[i];
  205823. ncb.ncb_buffer = (unsigned char*) &astat;
  205824. ncb.ncb_length = sizeof (ASTAT);
  205825. if (NetbiosCall (&ncb) == 0)
  205826. {
  205827. if (astat.adapt.adapter_type == 0xfe)
  205828. {
  205829. int64 mac = 0;
  205830. for (unsigned int i = 0; i < 6; ++i)
  205831. mac = (mac << 8) | astat.adapt.adapter_address[i];
  205832. if (littleEndian)
  205833. mac = (int64) swapByteOrder ((uint64) mac);
  205834. if (numFound < maxNum && mac != 0)
  205835. addresses [numFound++] = mac;
  205836. }
  205837. }
  205838. }
  205839. }
  205840. }
  205841. return numFound;
  205842. }
  205843. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  205844. {
  205845. int numFound = getMACAddressViaGetAdaptersInfo (addresses, maxNum, littleEndian);
  205846. if (numFound == 0)
  205847. numFound = getMACAddressesViaNetBios (addresses, maxNum, littleEndian);
  205848. return numFound;
  205849. }
  205850. typedef ULONG (WINAPI *MAPISendMailType) (LHANDLE, ULONG, lpMapiMessage, ::FLAGS, ULONG);
  205851. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  205852. const String& emailSubject,
  205853. const String& bodyText,
  205854. const StringArray& filesToAttach)
  205855. {
  205856. HMODULE h = LoadLibraryA ("MAPI32.dll");
  205857. MAPISendMailType mapiSendMail = (MAPISendMailType) GetProcAddress (h, "MAPISendMail");
  205858. bool ok = false;
  205859. if (mapiSendMail != 0)
  205860. {
  205861. MapiMessage message;
  205862. zerostruct (message);
  205863. message.lpszSubject = (LPSTR) (LPCSTR) emailSubject;
  205864. message.lpszNoteText = (LPSTR) (LPCSTR) bodyText;
  205865. MapiRecipDesc recip;
  205866. zerostruct (recip);
  205867. recip.ulRecipClass = MAPI_TO;
  205868. recip.lpszName = (LPSTR) (LPCSTR) targetEmailAddress;
  205869. message.nRecipCount = 1;
  205870. message.lpRecips = &recip;
  205871. MemoryBlock mb (sizeof (MapiFileDesc) * filesToAttach.size());
  205872. mb.fillWith (0);
  205873. MapiFileDesc* files = (MapiFileDesc*) mb.getData();
  205874. message.nFileCount = filesToAttach.size();
  205875. message.lpFiles = files;
  205876. for (int i = 0; i < filesToAttach.size(); ++i)
  205877. {
  205878. files[i].nPosition = (ULONG) -1;
  205879. files[i].lpszPathName = (LPSTR) (LPCSTR) filesToAttach [i];
  205880. }
  205881. ok = (mapiSendMail (0, 0, &message, MAPI_DIALOG | MAPI_LOGON_UI, 0) == SUCCESS_SUCCESS);
  205882. }
  205883. FreeLibrary (h);
  205884. return ok;
  205885. }
  205886. #endif
  205887. /********* End of inlined file: juce_win32_Network.cpp *********/
  205888. /********* Start of inlined file: juce_win32_PlatformUtils.cpp *********/
  205889. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  205890. // compiled on its own).
  205891. #if JUCE_INCLUDED_FILE
  205892. static HKEY findKeyForPath (String name,
  205893. const bool createForWriting,
  205894. String& valueName) throw()
  205895. {
  205896. HKEY rootKey = 0;
  205897. if (name.startsWithIgnoreCase (T("HKEY_CURRENT_USER\\")))
  205898. rootKey = HKEY_CURRENT_USER;
  205899. else if (name.startsWithIgnoreCase (T("HKEY_LOCAL_MACHINE\\")))
  205900. rootKey = HKEY_LOCAL_MACHINE;
  205901. else if (name.startsWithIgnoreCase (T("HKEY_CLASSES_ROOT\\")))
  205902. rootKey = HKEY_CLASSES_ROOT;
  205903. if (rootKey != 0)
  205904. {
  205905. name = name.substring (name.indexOfChar (T('\\')) + 1);
  205906. const int lastSlash = name.lastIndexOfChar (T('\\'));
  205907. valueName = name.substring (lastSlash + 1);
  205908. name = name.substring (0, lastSlash);
  205909. HKEY key;
  205910. DWORD result;
  205911. if (createForWriting)
  205912. {
  205913. if (RegCreateKeyEx (rootKey, name, 0, L"", REG_OPTION_NON_VOLATILE,
  205914. (KEY_WRITE | KEY_QUERY_VALUE), 0, &key, &result) == ERROR_SUCCESS)
  205915. return key;
  205916. }
  205917. else
  205918. {
  205919. if (RegOpenKeyEx (rootKey, name, 0, KEY_READ, &key) == ERROR_SUCCESS)
  205920. return key;
  205921. }
  205922. }
  205923. return 0;
  205924. }
  205925. const String PlatformUtilities::getRegistryValue (const String& regValuePath,
  205926. const String& defaultValue)
  205927. {
  205928. String valueName, s;
  205929. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205930. if (k != 0)
  205931. {
  205932. WCHAR buffer [2048];
  205933. unsigned long bufferSize = sizeof (buffer);
  205934. DWORD type = REG_SZ;
  205935. if (RegQueryValueEx (k, valueName, 0, &type, (LPBYTE) buffer, &bufferSize) == ERROR_SUCCESS)
  205936. s = buffer;
  205937. else
  205938. s = defaultValue;
  205939. RegCloseKey (k);
  205940. }
  205941. return s;
  205942. }
  205943. void PlatformUtilities::setRegistryValue (const String& regValuePath,
  205944. const String& value)
  205945. {
  205946. String valueName;
  205947. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205948. if (k != 0)
  205949. {
  205950. RegSetValueEx (k, valueName, 0, REG_SZ,
  205951. (const BYTE*) (const WCHAR*) value,
  205952. sizeof (WCHAR) * (value.length() + 1));
  205953. RegCloseKey (k);
  205954. }
  205955. }
  205956. bool PlatformUtilities::registryValueExists (const String& regValuePath)
  205957. {
  205958. bool exists = false;
  205959. String valueName;
  205960. HKEY k = findKeyForPath (regValuePath, false, valueName);
  205961. if (k != 0)
  205962. {
  205963. unsigned char buffer [2048];
  205964. unsigned long bufferSize = sizeof (buffer);
  205965. DWORD type = 0;
  205966. if (RegQueryValueEx (k, valueName, 0, &type, buffer, &bufferSize) == ERROR_SUCCESS)
  205967. exists = true;
  205968. RegCloseKey (k);
  205969. }
  205970. return exists;
  205971. }
  205972. void PlatformUtilities::deleteRegistryValue (const String& regValuePath)
  205973. {
  205974. String valueName;
  205975. HKEY k = findKeyForPath (regValuePath, true, valueName);
  205976. if (k != 0)
  205977. {
  205978. RegDeleteValue (k, valueName);
  205979. RegCloseKey (k);
  205980. }
  205981. }
  205982. void PlatformUtilities::deleteRegistryKey (const String& regKeyPath)
  205983. {
  205984. String valueName;
  205985. HKEY k = findKeyForPath (regKeyPath, true, valueName);
  205986. if (k != 0)
  205987. {
  205988. RegDeleteKey (k, valueName);
  205989. RegCloseKey (k);
  205990. }
  205991. }
  205992. bool juce_IsRunningInWine() throw()
  205993. {
  205994. HKEY key;
  205995. if (RegOpenKeyEx (HKEY_CURRENT_USER, _T("Software\\Wine"), 0, KEY_READ, &key) == ERROR_SUCCESS)
  205996. {
  205997. RegCloseKey (key);
  205998. return true;
  205999. }
  206000. return false;
  206001. }
  206002. const String JUCE_CALLTYPE PlatformUtilities::getCurrentCommandLineParams() throw()
  206003. {
  206004. String s (::GetCommandLineW());
  206005. StringArray tokens;
  206006. tokens.addTokens (s, true); // tokenise so that we can remove the initial filename argument
  206007. return tokens.joinIntoString (T(" "), 1);
  206008. }
  206009. static void* currentModuleHandle = 0;
  206010. void* PlatformUtilities::getCurrentModuleInstanceHandle() throw()
  206011. {
  206012. if (currentModuleHandle == 0)
  206013. currentModuleHandle = GetModuleHandle (0);
  206014. return currentModuleHandle;
  206015. }
  206016. void PlatformUtilities::setCurrentModuleInstanceHandle (void* const newHandle) throw()
  206017. {
  206018. currentModuleHandle = newHandle;
  206019. }
  206020. void PlatformUtilities::fpuReset()
  206021. {
  206022. #if JUCE_MSVC
  206023. _clearfp();
  206024. #endif
  206025. }
  206026. void PlatformUtilities::beep()
  206027. {
  206028. MessageBeep (MB_OK);
  206029. }
  206030. #endif
  206031. /********* End of inlined file: juce_win32_PlatformUtils.cpp *********/
  206032. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  206033. /********* Start of inlined file: juce_win32_Messaging.cpp *********/
  206034. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206035. // compiled on its own).
  206036. #if JUCE_INCLUDED_FILE
  206037. static const unsigned int specialId = WM_APP + 0x4400;
  206038. static const unsigned int broadcastId = WM_APP + 0x4403;
  206039. static const unsigned int specialCallbackId = WM_APP + 0x4402;
  206040. static const TCHAR* const messageWindowName = _T("JUCEWindow");
  206041. HWND juce_messageWindowHandle = 0;
  206042. extern long improbableWindowNumber; // defined in windowing.cpp
  206043. static LRESULT CALLBACK juce_MessageWndProc (HWND h,
  206044. const UINT message,
  206045. const WPARAM wParam,
  206046. const LPARAM lParam) throw()
  206047. {
  206048. JUCE_TRY
  206049. {
  206050. if (h == juce_messageWindowHandle)
  206051. {
  206052. if (message == specialCallbackId)
  206053. {
  206054. MessageCallbackFunction* const func = (MessageCallbackFunction*) wParam;
  206055. return (LRESULT) (*func) ((void*) lParam);
  206056. }
  206057. else if (message == specialId)
  206058. {
  206059. // these are trapped early in the dispatch call, but must also be checked
  206060. // here in case there are windows modal dialog boxes doing their own
  206061. // dispatch loop and not calling our version
  206062. MessageManager::getInstance()->deliverMessage ((void*) lParam);
  206063. return 0;
  206064. }
  206065. else if (message == broadcastId)
  206066. {
  206067. String* const messageString = (String*) lParam;
  206068. MessageManager::getInstance()->deliverBroadcastMessage (*messageString);
  206069. delete messageString;
  206070. return 0;
  206071. }
  206072. else if (message == WM_COPYDATA && ((const COPYDATASTRUCT*) lParam)->dwData == broadcastId)
  206073. {
  206074. const String messageString ((const juce_wchar*) ((const COPYDATASTRUCT*) lParam)->lpData,
  206075. ((const COPYDATASTRUCT*) lParam)->cbData / sizeof (juce_wchar));
  206076. PostMessage (juce_messageWindowHandle, broadcastId, 0, (LPARAM) new String (messageString));
  206077. return 0;
  206078. }
  206079. }
  206080. }
  206081. JUCE_CATCH_EXCEPTION
  206082. return DefWindowProc (h, message, wParam, lParam);
  206083. }
  206084. bool juce_dispatchNextMessageOnSystemQueue (const bool returnIfNoPendingMessages)
  206085. {
  206086. MSG m;
  206087. if (returnIfNoPendingMessages && ! PeekMessage (&m, (HWND) 0, 0, 0, 0))
  206088. return false;
  206089. if (GetMessage (&m, (HWND) 0, 0, 0) > 0)
  206090. {
  206091. if (m.message == specialId
  206092. && m.hwnd == juce_messageWindowHandle)
  206093. {
  206094. MessageManager::getInstance()->deliverMessage ((void*) m.lParam);
  206095. }
  206096. else
  206097. {
  206098. if (GetWindowLong (m.hwnd, GWLP_USERDATA) != improbableWindowNumber
  206099. && (m.message == WM_LBUTTONDOWN || m.message == WM_RBUTTONDOWN))
  206100. {
  206101. // if it's someone else's window being clicked on, and the focus is
  206102. // currently on a juce window, pass the kb focus over..
  206103. HWND currentFocus = GetFocus();
  206104. if (currentFocus == 0 || GetWindowLong (currentFocus, GWLP_USERDATA) == improbableWindowNumber)
  206105. SetFocus (m.hwnd);
  206106. }
  206107. TranslateMessage (&m);
  206108. DispatchMessage (&m);
  206109. }
  206110. }
  206111. return true;
  206112. }
  206113. bool juce_postMessageToSystemQueue (void* message)
  206114. {
  206115. return PostMessage (juce_messageWindowHandle, specialId, 0, (LPARAM) message) != 0;
  206116. }
  206117. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  206118. void* userData)
  206119. {
  206120. if (MessageManager::getInstance()->isThisTheMessageThread())
  206121. {
  206122. return (*callback) (userData);
  206123. }
  206124. else
  206125. {
  206126. // If a thread has a MessageManagerLock and then tries to call this method, it'll
  206127. // deadlock because the message manager is blocked from running, and can't
  206128. // call your function..
  206129. jassert (! MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  206130. return (void*) SendMessage (juce_messageWindowHandle,
  206131. specialCallbackId,
  206132. (WPARAM) callback,
  206133. (LPARAM) userData);
  206134. }
  206135. }
  206136. static BOOL CALLBACK BroadcastEnumWindowProc (HWND hwnd, LPARAM lParam)
  206137. {
  206138. if (hwnd != juce_messageWindowHandle)
  206139. (reinterpret_cast <VoidArray*> (lParam))->add ((void*) hwnd);
  206140. return TRUE;
  206141. }
  206142. void MessageManager::broadcastMessage (const String& value) throw()
  206143. {
  206144. VoidArray windows;
  206145. EnumWindows (&BroadcastEnumWindowProc, (LPARAM) &windows);
  206146. const String localCopy (value);
  206147. COPYDATASTRUCT data;
  206148. data.dwData = broadcastId;
  206149. data.cbData = (localCopy.length() + 1) * sizeof (juce_wchar);
  206150. data.lpData = (void*) (const juce_wchar*) localCopy;
  206151. for (int i = windows.size(); --i >= 0;)
  206152. {
  206153. HWND hwnd = (HWND) windows.getUnchecked(i);
  206154. TCHAR windowName [64]; // no need to read longer strings than this
  206155. GetWindowText (hwnd, windowName, 64);
  206156. windowName [63] = 0;
  206157. if (String (windowName) == String (messageWindowName))
  206158. {
  206159. DWORD_PTR result;
  206160. SendMessageTimeout (hwnd, WM_COPYDATA,
  206161. (WPARAM) juce_messageWindowHandle,
  206162. (LPARAM) &data,
  206163. SMTO_BLOCK | SMTO_ABORTIFHUNG,
  206164. 8000,
  206165. &result);
  206166. }
  206167. }
  206168. }
  206169. static const String getMessageWindowClassName()
  206170. {
  206171. // this name has to be different for each app/dll instance because otherwise
  206172. // poor old Win32 can get a bit confused (even despite it not being a process-global
  206173. // window class).
  206174. static int number = 0;
  206175. if (number == 0)
  206176. number = 0x7fffffff & (int) Time::getHighResolutionTicks();
  206177. return T("JUCEcs_") + String (number);
  206178. }
  206179. void MessageManager::doPlatformSpecificInitialisation()
  206180. {
  206181. OleInitialize (0);
  206182. const String className (getMessageWindowClassName());
  206183. HMODULE hmod = (HMODULE) PlatformUtilities::getCurrentModuleInstanceHandle();
  206184. WNDCLASSEX wc;
  206185. zerostruct (wc);
  206186. wc.cbSize = sizeof (wc);
  206187. wc.lpfnWndProc = (WNDPROC) juce_MessageWndProc;
  206188. wc.cbWndExtra = 4;
  206189. wc.hInstance = hmod;
  206190. wc.lpszClassName = className;
  206191. RegisterClassEx (&wc);
  206192. juce_messageWindowHandle = CreateWindow (wc.lpszClassName,
  206193. messageWindowName,
  206194. 0, 0, 0, 0, 0, 0, 0,
  206195. hmod, 0);
  206196. }
  206197. void MessageManager::doPlatformSpecificShutdown()
  206198. {
  206199. DestroyWindow (juce_messageWindowHandle);
  206200. UnregisterClass (getMessageWindowClassName(), 0);
  206201. OleUninitialize();
  206202. }
  206203. #endif
  206204. /********* End of inlined file: juce_win32_Messaging.cpp *********/
  206205. /********* Start of inlined file: juce_win32_Windowing.cpp *********/
  206206. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  206207. // compiled on its own).
  206208. #if JUCE_INCLUDED_FILE
  206209. #undef GetSystemMetrics // multimon overrides this for some reason and causes a mess..
  206210. // these are in the windows SDK, but need to be repeated here for GCC..
  206211. #ifndef GET_APPCOMMAND_LPARAM
  206212. #define FAPPCOMMAND_MASK 0xF000
  206213. #define GET_APPCOMMAND_LPARAM(lParam) ((short) (HIWORD (lParam) & ~FAPPCOMMAND_MASK))
  206214. #define APPCOMMAND_MEDIA_NEXTTRACK 11
  206215. #define APPCOMMAND_MEDIA_PREVIOUSTRACK 12
  206216. #define APPCOMMAND_MEDIA_STOP 13
  206217. #define APPCOMMAND_MEDIA_PLAY_PAUSE 14
  206218. #define WM_APPCOMMAND 0x0319
  206219. #endif
  206220. extern void juce_repeatLastProcessPriority() throw(); // in juce_win32_Threads.cpp
  206221. extern void juce_CheckCurrentlyFocusedTopLevelWindow() throw(); // in juce_TopLevelWindow.cpp
  206222. extern bool juce_IsRunningInWine() throw();
  206223. #ifndef ULW_ALPHA
  206224. #define ULW_ALPHA 0x00000002
  206225. #endif
  206226. #ifndef AC_SRC_ALPHA
  206227. #define AC_SRC_ALPHA 0x01
  206228. #endif
  206229. #define DEBUG_REPAINT_TIMES 0
  206230. static HPALETTE palette = 0;
  206231. static bool createPaletteIfNeeded = true;
  206232. static bool shouldDeactivateTitleBar = true;
  206233. static bool screenSaverAllowed = true;
  206234. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw();
  206235. #define WM_TRAYNOTIFY WM_USER + 100
  206236. using ::abs;
  206237. typedef BOOL (WINAPI* UpdateLayeredWinFunc) (HWND, HDC, POINT*, SIZE*, HDC, POINT*, COLORREF, BLENDFUNCTION*, DWORD);
  206238. static UpdateLayeredWinFunc updateLayeredWindow = 0;
  206239. bool Desktop::canUseSemiTransparentWindows() throw()
  206240. {
  206241. if (updateLayeredWindow == 0)
  206242. {
  206243. if (! juce_IsRunningInWine())
  206244. {
  206245. HMODULE user32Mod = GetModuleHandle (_T("user32.dll"));
  206246. updateLayeredWindow = (UpdateLayeredWinFunc) GetProcAddress (user32Mod, "UpdateLayeredWindow");
  206247. }
  206248. }
  206249. return updateLayeredWindow != 0;
  206250. }
  206251. #undef DefWindowProc
  206252. #define DefWindowProc DefWindowProcW
  206253. const int extendedKeyModifier = 0x10000;
  206254. const int KeyPress::spaceKey = VK_SPACE;
  206255. const int KeyPress::returnKey = VK_RETURN;
  206256. const int KeyPress::escapeKey = VK_ESCAPE;
  206257. const int KeyPress::backspaceKey = VK_BACK;
  206258. const int KeyPress::deleteKey = VK_DELETE | extendedKeyModifier;
  206259. const int KeyPress::insertKey = VK_INSERT | extendedKeyModifier;
  206260. const int KeyPress::tabKey = VK_TAB;
  206261. const int KeyPress::leftKey = VK_LEFT | extendedKeyModifier;
  206262. const int KeyPress::rightKey = VK_RIGHT | extendedKeyModifier;
  206263. const int KeyPress::upKey = VK_UP | extendedKeyModifier;
  206264. const int KeyPress::downKey = VK_DOWN | extendedKeyModifier;
  206265. const int KeyPress::homeKey = VK_HOME | extendedKeyModifier;
  206266. const int KeyPress::endKey = VK_END | extendedKeyModifier;
  206267. const int KeyPress::pageUpKey = VK_PRIOR | extendedKeyModifier;
  206268. const int KeyPress::pageDownKey = VK_NEXT | extendedKeyModifier;
  206269. const int KeyPress::F1Key = VK_F1 | extendedKeyModifier;
  206270. const int KeyPress::F2Key = VK_F2 | extendedKeyModifier;
  206271. const int KeyPress::F3Key = VK_F3 | extendedKeyModifier;
  206272. const int KeyPress::F4Key = VK_F4 | extendedKeyModifier;
  206273. const int KeyPress::F5Key = VK_F5 | extendedKeyModifier;
  206274. const int KeyPress::F6Key = VK_F6 | extendedKeyModifier;
  206275. const int KeyPress::F7Key = VK_F7 | extendedKeyModifier;
  206276. const int KeyPress::F8Key = VK_F8 | extendedKeyModifier;
  206277. const int KeyPress::F9Key = VK_F9 | extendedKeyModifier;
  206278. const int KeyPress::F10Key = VK_F10 | extendedKeyModifier;
  206279. const int KeyPress::F11Key = VK_F11 | extendedKeyModifier;
  206280. const int KeyPress::F12Key = VK_F12 | extendedKeyModifier;
  206281. const int KeyPress::F13Key = VK_F13 | extendedKeyModifier;
  206282. const int KeyPress::F14Key = VK_F14 | extendedKeyModifier;
  206283. const int KeyPress::F15Key = VK_F15 | extendedKeyModifier;
  206284. const int KeyPress::F16Key = VK_F16 | extendedKeyModifier;
  206285. const int KeyPress::numberPad0 = VK_NUMPAD0 | extendedKeyModifier;
  206286. const int KeyPress::numberPad1 = VK_NUMPAD1 | extendedKeyModifier;
  206287. const int KeyPress::numberPad2 = VK_NUMPAD2 | extendedKeyModifier;
  206288. const int KeyPress::numberPad3 = VK_NUMPAD3 | extendedKeyModifier;
  206289. const int KeyPress::numberPad4 = VK_NUMPAD4 | extendedKeyModifier;
  206290. const int KeyPress::numberPad5 = VK_NUMPAD5 | extendedKeyModifier;
  206291. const int KeyPress::numberPad6 = VK_NUMPAD6 | extendedKeyModifier;
  206292. const int KeyPress::numberPad7 = VK_NUMPAD7 | extendedKeyModifier;
  206293. const int KeyPress::numberPad8 = VK_NUMPAD8 | extendedKeyModifier;
  206294. const int KeyPress::numberPad9 = VK_NUMPAD9 | extendedKeyModifier;
  206295. const int KeyPress::numberPadAdd = VK_ADD | extendedKeyModifier;
  206296. const int KeyPress::numberPadSubtract = VK_SUBTRACT | extendedKeyModifier;
  206297. const int KeyPress::numberPadMultiply = VK_MULTIPLY | extendedKeyModifier;
  206298. const int KeyPress::numberPadDivide = VK_DIVIDE | extendedKeyModifier;
  206299. const int KeyPress::numberPadSeparator = VK_SEPARATOR | extendedKeyModifier;
  206300. const int KeyPress::numberPadDecimalPoint = VK_DECIMAL | extendedKeyModifier;
  206301. const int KeyPress::numberPadEquals = 0x92 /*VK_OEM_NEC_EQUAL*/ | extendedKeyModifier;
  206302. const int KeyPress::numberPadDelete = VK_DELETE | extendedKeyModifier;
  206303. const int KeyPress::playKey = 0x30000;
  206304. const int KeyPress::stopKey = 0x30001;
  206305. const int KeyPress::fastForwardKey = 0x30002;
  206306. const int KeyPress::rewindKey = 0x30003;
  206307. class WindowsBitmapImage : public Image
  206308. {
  206309. public:
  206310. HBITMAP hBitmap;
  206311. BITMAPV4HEADER bitmapInfo;
  206312. HDC hdc;
  206313. unsigned char* bitmapData;
  206314. WindowsBitmapImage (const PixelFormat format_,
  206315. const int w, const int h, const bool clearImage)
  206316. : Image (format_, w, h)
  206317. {
  206318. jassert (format_ == RGB || format_ == ARGB);
  206319. pixelStride = (format_ == RGB) ? 3 : 4;
  206320. zerostruct (bitmapInfo);
  206321. bitmapInfo.bV4Size = sizeof (BITMAPV4HEADER);
  206322. bitmapInfo.bV4Width = w;
  206323. bitmapInfo.bV4Height = h;
  206324. bitmapInfo.bV4Planes = 1;
  206325. bitmapInfo.bV4CSType = 1;
  206326. bitmapInfo.bV4BitCount = (unsigned short) (pixelStride * 8);
  206327. if (format_ == ARGB)
  206328. {
  206329. bitmapInfo.bV4AlphaMask = 0xff000000;
  206330. bitmapInfo.bV4RedMask = 0xff0000;
  206331. bitmapInfo.bV4GreenMask = 0xff00;
  206332. bitmapInfo.bV4BlueMask = 0xff;
  206333. bitmapInfo.bV4V4Compression = BI_BITFIELDS;
  206334. }
  206335. else
  206336. {
  206337. bitmapInfo.bV4V4Compression = BI_RGB;
  206338. }
  206339. lineStride = -((w * pixelStride + 3) & ~3);
  206340. HDC dc = GetDC (0);
  206341. hdc = CreateCompatibleDC (dc);
  206342. ReleaseDC (0, dc);
  206343. SetMapMode (hdc, MM_TEXT);
  206344. hBitmap = CreateDIBSection (hdc,
  206345. (BITMAPINFO*) &(bitmapInfo),
  206346. DIB_RGB_COLORS,
  206347. (void**) &bitmapData,
  206348. 0, 0);
  206349. SelectObject (hdc, hBitmap);
  206350. if (format_ == ARGB && clearImage)
  206351. zeromem (bitmapData, abs (h * lineStride));
  206352. imageData = bitmapData - (lineStride * (h - 1));
  206353. }
  206354. ~WindowsBitmapImage()
  206355. {
  206356. DeleteDC (hdc);
  206357. DeleteObject (hBitmap);
  206358. imageData = 0; // to stop the base class freeing this
  206359. }
  206360. void blitToWindow (HWND hwnd, HDC dc, const bool transparent,
  206361. const int x, const int y,
  206362. const RectangleList& maskedRegion) throw()
  206363. {
  206364. static HDRAWDIB hdd = 0;
  206365. static bool needToCreateDrawDib = true;
  206366. if (needToCreateDrawDib)
  206367. {
  206368. needToCreateDrawDib = false;
  206369. HDC dc = GetDC (0);
  206370. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206371. ReleaseDC (0, dc);
  206372. // only open if we're not palettised
  206373. if (n > 8)
  206374. hdd = DrawDibOpen();
  206375. }
  206376. if (createPaletteIfNeeded)
  206377. {
  206378. HDC dc = GetDC (0);
  206379. const int n = GetDeviceCaps (dc, BITSPIXEL);
  206380. ReleaseDC (0, dc);
  206381. if (n <= 8)
  206382. palette = CreateHalftonePalette (dc);
  206383. createPaletteIfNeeded = false;
  206384. }
  206385. if (palette != 0)
  206386. {
  206387. SelectPalette (dc, palette, FALSE);
  206388. RealizePalette (dc);
  206389. SetStretchBltMode (dc, HALFTONE);
  206390. }
  206391. SetMapMode (dc, MM_TEXT);
  206392. if (transparent)
  206393. {
  206394. POINT p, pos;
  206395. SIZE size;
  206396. RECT windowBounds;
  206397. GetWindowRect (hwnd, &windowBounds);
  206398. p.x = -x;
  206399. p.y = -y;
  206400. pos.x = windowBounds.left;
  206401. pos.y = windowBounds.top;
  206402. size.cx = windowBounds.right - windowBounds.left;
  206403. size.cy = windowBounds.bottom - windowBounds.top;
  206404. BLENDFUNCTION bf;
  206405. bf.AlphaFormat = AC_SRC_ALPHA;
  206406. bf.BlendFlags = 0;
  206407. bf.BlendOp = AC_SRC_OVER;
  206408. bf.SourceConstantAlpha = 0xff;
  206409. if (! maskedRegion.isEmpty())
  206410. {
  206411. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206412. {
  206413. const Rectangle& r = *i.getRectangle();
  206414. ExcludeClipRect (hdc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206415. }
  206416. }
  206417. updateLayeredWindow (hwnd, 0, &pos, &size, hdc, &p, 0, &bf, ULW_ALPHA);
  206418. }
  206419. else
  206420. {
  206421. int savedDC = 0;
  206422. if (! maskedRegion.isEmpty())
  206423. {
  206424. savedDC = SaveDC (dc);
  206425. for (RectangleList::Iterator i (maskedRegion); i.next();)
  206426. {
  206427. const Rectangle& r = *i.getRectangle();
  206428. ExcludeClipRect (dc, r.getX(), r.getY(), r.getRight(), r.getBottom());
  206429. }
  206430. }
  206431. const int w = getWidth();
  206432. const int h = getHeight();
  206433. if (hdd == 0)
  206434. {
  206435. StretchDIBits (dc,
  206436. x, y, w, h,
  206437. 0, 0, w, h,
  206438. bitmapData, (const BITMAPINFO*) &bitmapInfo,
  206439. DIB_RGB_COLORS, SRCCOPY);
  206440. }
  206441. else
  206442. {
  206443. DrawDibDraw (hdd, dc, x, y, -1, -1,
  206444. (BITMAPINFOHEADER*) &bitmapInfo, bitmapData,
  206445. 0, 0, w, h, 0);
  206446. }
  206447. if (! maskedRegion.isEmpty())
  206448. RestoreDC (dc, savedDC);
  206449. }
  206450. }
  206451. juce_UseDebuggingNewOperator
  206452. private:
  206453. WindowsBitmapImage (const WindowsBitmapImage&);
  206454. const WindowsBitmapImage& operator= (const WindowsBitmapImage&);
  206455. };
  206456. long improbableWindowNumber = 0xf965aa01; // also referenced by messaging.cpp
  206457. static int currentModifiers = 0;
  206458. static int modifiersAtLastCallback = 0;
  206459. static void updateKeyModifiers() throw()
  206460. {
  206461. currentModifiers &= ~(ModifierKeys::shiftModifier
  206462. | ModifierKeys::ctrlModifier
  206463. | ModifierKeys::altModifier);
  206464. if ((GetKeyState (VK_SHIFT) & 0x8000) != 0)
  206465. currentModifiers |= ModifierKeys::shiftModifier;
  206466. if ((GetKeyState (VK_CONTROL) & 0x8000) != 0)
  206467. currentModifiers |= ModifierKeys::ctrlModifier;
  206468. if ((GetKeyState (VK_MENU) & 0x8000) != 0)
  206469. currentModifiers |= ModifierKeys::altModifier;
  206470. if ((GetKeyState (VK_RMENU) & 0x8000) != 0)
  206471. currentModifiers &= ~(ModifierKeys::ctrlModifier | ModifierKeys::altModifier);
  206472. }
  206473. void ModifierKeys::updateCurrentModifiers() throw()
  206474. {
  206475. currentModifierFlags = currentModifiers;
  206476. }
  206477. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  206478. {
  206479. SHORT k = (SHORT) keyCode;
  206480. if ((keyCode & extendedKeyModifier) == 0
  206481. && (k >= (SHORT) T('a') && k <= (SHORT) T('z')))
  206482. k += (SHORT) T('A') - (SHORT) T('a');
  206483. const SHORT translatedValues[] = { (SHORT) ',', VK_OEM_COMMA,
  206484. (SHORT) '+', VK_OEM_PLUS,
  206485. (SHORT) '-', VK_OEM_MINUS,
  206486. (SHORT) '.', VK_OEM_PERIOD,
  206487. (SHORT) ';', VK_OEM_1,
  206488. (SHORT) ':', VK_OEM_1,
  206489. (SHORT) '/', VK_OEM_2,
  206490. (SHORT) '?', VK_OEM_2,
  206491. (SHORT) '[', VK_OEM_4,
  206492. (SHORT) ']', VK_OEM_6 };
  206493. for (int i = 0; i < numElementsInArray (translatedValues); i += 2)
  206494. if (k == translatedValues [i])
  206495. k = translatedValues [i + 1];
  206496. return (GetKeyState (k) & 0x8000) != 0;
  206497. }
  206498. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  206499. {
  206500. updateKeyModifiers();
  206501. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  206502. if ((GetKeyState (VK_LBUTTON) & 0x8000) != 0)
  206503. currentModifiers |= ModifierKeys::leftButtonModifier;
  206504. if ((GetKeyState (VK_RBUTTON) & 0x8000) != 0)
  206505. currentModifiers |= ModifierKeys::rightButtonModifier;
  206506. if ((GetKeyState (VK_MBUTTON) & 0x8000) != 0)
  206507. currentModifiers |= ModifierKeys::middleButtonModifier;
  206508. return ModifierKeys (currentModifiers);
  206509. }
  206510. static int64 getMouseEventTime() throw()
  206511. {
  206512. static int64 eventTimeOffset = 0;
  206513. static DWORD lastMessageTime = 0;
  206514. const DWORD thisMessageTime = GetMessageTime();
  206515. if (thisMessageTime < lastMessageTime || lastMessageTime == 0)
  206516. {
  206517. lastMessageTime = thisMessageTime;
  206518. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  206519. }
  206520. return eventTimeOffset + thisMessageTime;
  206521. }
  206522. class Win32ComponentPeer : public ComponentPeer
  206523. {
  206524. public:
  206525. Win32ComponentPeer (Component* const component,
  206526. const int windowStyleFlags)
  206527. : ComponentPeer (component, windowStyleFlags),
  206528. dontRepaint (false),
  206529. fullScreen (false),
  206530. isDragging (false),
  206531. isMouseOver (false),
  206532. hasCreatedCaret (false),
  206533. currentWindowIcon (0),
  206534. taskBarIcon (0),
  206535. dropTarget (0)
  206536. {
  206537. MessageManager::getInstance()
  206538. ->callFunctionOnMessageThread (&createWindowCallback, (void*) this);
  206539. setTitle (component->getName());
  206540. if ((windowStyleFlags & windowHasDropShadow) != 0
  206541. && Desktop::canUseSemiTransparentWindows())
  206542. {
  206543. shadower = component->getLookAndFeel().createDropShadowerForComponent (component);
  206544. if (shadower != 0)
  206545. shadower->setOwner (component);
  206546. }
  206547. else
  206548. {
  206549. shadower = 0;
  206550. }
  206551. }
  206552. ~Win32ComponentPeer()
  206553. {
  206554. setTaskBarIcon (0);
  206555. deleteAndZero (shadower);
  206556. // do this before the next bit to avoid messages arriving for this window
  206557. // before it's destroyed
  206558. SetWindowLongPtr (hwnd, GWLP_USERDATA, 0);
  206559. MessageManager::getInstance()
  206560. ->callFunctionOnMessageThread (&destroyWindowCallback, (void*) hwnd);
  206561. if (currentWindowIcon != 0)
  206562. DestroyIcon (currentWindowIcon);
  206563. if (dropTarget != 0)
  206564. {
  206565. dropTarget->Release();
  206566. dropTarget = 0;
  206567. }
  206568. }
  206569. void* getNativeHandle() const
  206570. {
  206571. return (void*) hwnd;
  206572. }
  206573. void setVisible (bool shouldBeVisible)
  206574. {
  206575. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  206576. if (shouldBeVisible)
  206577. InvalidateRect (hwnd, 0, 0);
  206578. else
  206579. lastPaintTime = 0;
  206580. }
  206581. void setTitle (const String& title)
  206582. {
  206583. SetWindowText (hwnd, title);
  206584. }
  206585. void setPosition (int x, int y)
  206586. {
  206587. offsetWithinParent (x, y);
  206588. SetWindowPos (hwnd, 0,
  206589. x - windowBorder.getLeft(),
  206590. y - windowBorder.getTop(),
  206591. 0, 0,
  206592. SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206593. }
  206594. void repaintNowIfTransparent()
  206595. {
  206596. if (isTransparent() && lastPaintTime > 0 && Time::getMillisecondCounter() > lastPaintTime + 30)
  206597. handlePaintMessage();
  206598. }
  206599. void updateBorderSize()
  206600. {
  206601. WINDOWINFO info;
  206602. info.cbSize = sizeof (info);
  206603. if (GetWindowInfo (hwnd, &info))
  206604. {
  206605. windowBorder = BorderSize (info.rcClient.top - info.rcWindow.top,
  206606. info.rcClient.left - info.rcWindow.left,
  206607. info.rcWindow.bottom - info.rcClient.bottom,
  206608. info.rcWindow.right - info.rcClient.right);
  206609. }
  206610. }
  206611. void setSize (int w, int h)
  206612. {
  206613. SetWindowPos (hwnd, 0, 0, 0,
  206614. w + windowBorder.getLeftAndRight(),
  206615. h + windowBorder.getTopAndBottom(),
  206616. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206617. updateBorderSize();
  206618. repaintNowIfTransparent();
  206619. }
  206620. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  206621. {
  206622. fullScreen = isNowFullScreen;
  206623. offsetWithinParent (x, y);
  206624. SetWindowPos (hwnd, 0,
  206625. x - windowBorder.getLeft(),
  206626. y - windowBorder.getTop(),
  206627. w + windowBorder.getLeftAndRight(),
  206628. h + windowBorder.getTopAndBottom(),
  206629. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  206630. updateBorderSize();
  206631. repaintNowIfTransparent();
  206632. }
  206633. void getBounds (int& x, int& y, int& w, int& h) const
  206634. {
  206635. RECT r;
  206636. GetWindowRect (hwnd, &r);
  206637. x = r.left;
  206638. y = r.top;
  206639. w = r.right - x;
  206640. h = r.bottom - y;
  206641. HWND parentH = GetParent (hwnd);
  206642. if (parentH != 0)
  206643. {
  206644. GetWindowRect (parentH, &r);
  206645. x -= r.left;
  206646. y -= r.top;
  206647. }
  206648. x += windowBorder.getLeft();
  206649. y += windowBorder.getTop();
  206650. w -= windowBorder.getLeftAndRight();
  206651. h -= windowBorder.getTopAndBottom();
  206652. }
  206653. int getScreenX() const
  206654. {
  206655. RECT r;
  206656. GetWindowRect (hwnd, &r);
  206657. return r.left + windowBorder.getLeft();
  206658. }
  206659. int getScreenY() const
  206660. {
  206661. RECT r;
  206662. GetWindowRect (hwnd, &r);
  206663. return r.top + windowBorder.getTop();
  206664. }
  206665. void relativePositionToGlobal (int& x, int& y)
  206666. {
  206667. RECT r;
  206668. GetWindowRect (hwnd, &r);
  206669. x += r.left + windowBorder.getLeft();
  206670. y += r.top + windowBorder.getTop();
  206671. }
  206672. void globalPositionToRelative (int& x, int& y)
  206673. {
  206674. RECT r;
  206675. GetWindowRect (hwnd, &r);
  206676. x -= r.left + windowBorder.getLeft();
  206677. y -= r.top + windowBorder.getTop();
  206678. }
  206679. void setMinimised (bool shouldBeMinimised)
  206680. {
  206681. if (shouldBeMinimised != isMinimised())
  206682. ShowWindow (hwnd, shouldBeMinimised ? SW_MINIMIZE : SW_SHOWNORMAL);
  206683. }
  206684. bool isMinimised() const
  206685. {
  206686. WINDOWPLACEMENT wp;
  206687. wp.length = sizeof (WINDOWPLACEMENT);
  206688. GetWindowPlacement (hwnd, &wp);
  206689. return wp.showCmd == SW_SHOWMINIMIZED;
  206690. }
  206691. void setFullScreen (bool shouldBeFullScreen)
  206692. {
  206693. setMinimised (false);
  206694. if (fullScreen != shouldBeFullScreen)
  206695. {
  206696. fullScreen = shouldBeFullScreen;
  206697. const ComponentDeletionWatcher deletionChecker (component);
  206698. if (! fullScreen)
  206699. {
  206700. const Rectangle boundsCopy (lastNonFullscreenBounds);
  206701. if (hasTitleBar())
  206702. ShowWindow (hwnd, SW_SHOWNORMAL);
  206703. if (! boundsCopy.isEmpty())
  206704. {
  206705. setBounds (boundsCopy.getX(),
  206706. boundsCopy.getY(),
  206707. boundsCopy.getWidth(),
  206708. boundsCopy.getHeight(),
  206709. false);
  206710. }
  206711. }
  206712. else
  206713. {
  206714. if (hasTitleBar())
  206715. ShowWindow (hwnd, SW_SHOWMAXIMIZED);
  206716. else
  206717. SendMessageW (hwnd, WM_SETTINGCHANGE, 0, 0);
  206718. }
  206719. if (! deletionChecker.hasBeenDeleted())
  206720. handleMovedOrResized();
  206721. }
  206722. }
  206723. bool isFullScreen() const
  206724. {
  206725. if (! hasTitleBar())
  206726. return fullScreen;
  206727. WINDOWPLACEMENT wp;
  206728. wp.length = sizeof (wp);
  206729. GetWindowPlacement (hwnd, &wp);
  206730. return wp.showCmd == SW_SHOWMAXIMIZED;
  206731. }
  206732. bool contains (int x, int y, bool trueIfInAChildWindow) const
  206733. {
  206734. RECT r;
  206735. GetWindowRect (hwnd, &r);
  206736. POINT p;
  206737. p.x = x + r.left + windowBorder.getLeft();
  206738. p.y = y + r.top + windowBorder.getTop();
  206739. HWND w = WindowFromPoint (p);
  206740. return w == hwnd || (trueIfInAChildWindow && (IsChild (hwnd, w) != 0));
  206741. }
  206742. const BorderSize getFrameSize() const
  206743. {
  206744. return windowBorder;
  206745. }
  206746. bool setAlwaysOnTop (bool alwaysOnTop)
  206747. {
  206748. const bool oldDeactivate = shouldDeactivateTitleBar;
  206749. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206750. SetWindowPos (hwnd, alwaysOnTop ? HWND_TOPMOST : HWND_NOTOPMOST,
  206751. 0, 0, 0, 0,
  206752. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206753. shouldDeactivateTitleBar = oldDeactivate;
  206754. if (shadower != 0)
  206755. shadower->componentBroughtToFront (*component);
  206756. return true;
  206757. }
  206758. void toFront (bool makeActive)
  206759. {
  206760. setMinimised (false);
  206761. const bool oldDeactivate = shouldDeactivateTitleBar;
  206762. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206763. MessageManager::getInstance()
  206764. ->callFunctionOnMessageThread (makeActive ? &toFrontCallback1
  206765. : &toFrontCallback2,
  206766. (void*) hwnd);
  206767. shouldDeactivateTitleBar = oldDeactivate;
  206768. if (! makeActive)
  206769. {
  206770. // in this case a broughttofront call won't have occured, so do it now..
  206771. handleBroughtToFront();
  206772. }
  206773. }
  206774. void toBehind (ComponentPeer* other)
  206775. {
  206776. Win32ComponentPeer* const otherPeer = dynamic_cast <Win32ComponentPeer*> (other);
  206777. jassert (otherPeer != 0); // wrong type of window?
  206778. if (otherPeer != 0)
  206779. {
  206780. setMinimised (false);
  206781. SetWindowPos (hwnd, otherPeer->hwnd, 0, 0, 0, 0,
  206782. SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  206783. }
  206784. }
  206785. bool isFocused() const
  206786. {
  206787. return MessageManager::getInstance()
  206788. ->callFunctionOnMessageThread (&getFocusCallback, 0) == (void*) hwnd;
  206789. }
  206790. void grabFocus()
  206791. {
  206792. const bool oldDeactivate = shouldDeactivateTitleBar;
  206793. shouldDeactivateTitleBar = ((styleFlags & windowIsTemporary) == 0);
  206794. MessageManager::getInstance()
  206795. ->callFunctionOnMessageThread (&setFocusCallback, (void*) hwnd);
  206796. shouldDeactivateTitleBar = oldDeactivate;
  206797. }
  206798. void textInputRequired (int /*x*/, int /*y*/)
  206799. {
  206800. if (! hasCreatedCaret)
  206801. {
  206802. hasCreatedCaret = true;
  206803. CreateCaret (hwnd, (HBITMAP) 1, 0, 0);
  206804. }
  206805. ShowCaret (hwnd);
  206806. SetCaretPos (0, 0);
  206807. }
  206808. void repaint (int x, int y, int w, int h)
  206809. {
  206810. const RECT r = { x, y, x + w, y + h };
  206811. InvalidateRect (hwnd, &r, FALSE);
  206812. }
  206813. void performAnyPendingRepaintsNow()
  206814. {
  206815. MSG m;
  206816. if (component->isVisible() && PeekMessage (&m, hwnd, WM_PAINT, WM_PAINT, PM_REMOVE))
  206817. DispatchMessage (&m);
  206818. }
  206819. static Win32ComponentPeer* getOwnerOfWindow (HWND h) throw()
  206820. {
  206821. if (h != 0 && GetWindowLongPtr (h, GWLP_USERDATA) == improbableWindowNumber)
  206822. return (Win32ComponentPeer*) GetWindowLongPtr (h, 8);
  206823. return 0;
  206824. }
  206825. void setTaskBarIcon (const Image* const image)
  206826. {
  206827. if (image != 0)
  206828. {
  206829. HICON hicon = createHICONFromImage (*image, TRUE, 0, 0);
  206830. if (taskBarIcon == 0)
  206831. {
  206832. taskBarIcon = new NOTIFYICONDATA();
  206833. taskBarIcon->cbSize = sizeof (NOTIFYICONDATA);
  206834. taskBarIcon->hWnd = (HWND) hwnd;
  206835. taskBarIcon->uID = (int) (pointer_sized_int) hwnd;
  206836. taskBarIcon->uFlags = NIF_ICON | NIF_MESSAGE | NIF_TIP;
  206837. taskBarIcon->uCallbackMessage = WM_TRAYNOTIFY;
  206838. taskBarIcon->hIcon = hicon;
  206839. taskBarIcon->szTip[0] = 0;
  206840. Shell_NotifyIcon (NIM_ADD, taskBarIcon);
  206841. }
  206842. else
  206843. {
  206844. HICON oldIcon = taskBarIcon->hIcon;
  206845. taskBarIcon->hIcon = hicon;
  206846. taskBarIcon->uFlags = NIF_ICON;
  206847. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206848. DestroyIcon (oldIcon);
  206849. }
  206850. DestroyIcon (hicon);
  206851. }
  206852. else if (taskBarIcon != 0)
  206853. {
  206854. taskBarIcon->uFlags = 0;
  206855. Shell_NotifyIcon (NIM_DELETE, taskBarIcon);
  206856. DestroyIcon (taskBarIcon->hIcon);
  206857. deleteAndZero (taskBarIcon);
  206858. }
  206859. }
  206860. void setTaskBarIconToolTip (const String& toolTip) const
  206861. {
  206862. if (taskBarIcon != 0)
  206863. {
  206864. taskBarIcon->uFlags = NIF_TIP;
  206865. toolTip.copyToBuffer (taskBarIcon->szTip, sizeof (taskBarIcon->szTip) - 1);
  206866. Shell_NotifyIcon (NIM_MODIFY, taskBarIcon);
  206867. }
  206868. }
  206869. juce_UseDebuggingNewOperator
  206870. bool dontRepaint;
  206871. private:
  206872. HWND hwnd;
  206873. DropShadower* shadower;
  206874. bool fullScreen, isDragging, isMouseOver, hasCreatedCaret;
  206875. BorderSize windowBorder;
  206876. HICON currentWindowIcon;
  206877. NOTIFYICONDATA* taskBarIcon;
  206878. IDropTarget* dropTarget;
  206879. class TemporaryImage : public Timer
  206880. {
  206881. public:
  206882. TemporaryImage()
  206883. : image (0)
  206884. {
  206885. }
  206886. ~TemporaryImage()
  206887. {
  206888. delete image;
  206889. }
  206890. WindowsBitmapImage* getImage (const bool transparent, const int w, const int h) throw()
  206891. {
  206892. const Image::PixelFormat format = transparent ? Image::ARGB : Image::RGB;
  206893. if (image == 0 || image->getWidth() < w || image->getHeight() < h || image->getFormat() != format)
  206894. {
  206895. delete image;
  206896. image = new WindowsBitmapImage (format, (w + 31) & ~31, (h + 31) & ~31, false);
  206897. }
  206898. startTimer (3000);
  206899. return image;
  206900. }
  206901. void timerCallback()
  206902. {
  206903. stopTimer();
  206904. deleteAndZero (image);
  206905. }
  206906. private:
  206907. WindowsBitmapImage* image;
  206908. TemporaryImage (const TemporaryImage&);
  206909. const TemporaryImage& operator= (const TemporaryImage&);
  206910. };
  206911. TemporaryImage offscreenImageGenerator;
  206912. class WindowClassHolder : public DeletedAtShutdown
  206913. {
  206914. public:
  206915. WindowClassHolder()
  206916. : windowClassName ("JUCE_")
  206917. {
  206918. // this name has to be different for each app/dll instance because otherwise
  206919. // poor old Win32 can get a bit confused (even despite it not being a process-global
  206920. // window class).
  206921. windowClassName << (int) (Time::currentTimeMillis() & 0x7fffffff);
  206922. HINSTANCE moduleHandle = (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle();
  206923. TCHAR moduleFile [1024];
  206924. moduleFile[0] = 0;
  206925. GetModuleFileName (moduleHandle, moduleFile, 1024);
  206926. WORD iconNum = 0;
  206927. WNDCLASSEX wcex;
  206928. wcex.cbSize = sizeof (wcex);
  206929. wcex.style = CS_OWNDC;
  206930. wcex.lpfnWndProc = (WNDPROC) windowProc;
  206931. wcex.lpszClassName = windowClassName;
  206932. wcex.cbClsExtra = 0;
  206933. wcex.cbWndExtra = 32;
  206934. wcex.hInstance = moduleHandle;
  206935. wcex.hIcon = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  206936. iconNum = 1;
  206937. wcex.hIconSm = ExtractAssociatedIcon (moduleHandle, moduleFile, &iconNum);
  206938. wcex.hCursor = 0;
  206939. wcex.hbrBackground = 0;
  206940. wcex.lpszMenuName = 0;
  206941. RegisterClassEx (&wcex);
  206942. }
  206943. ~WindowClassHolder()
  206944. {
  206945. if (ComponentPeer::getNumPeers() == 0)
  206946. UnregisterClass (windowClassName, (HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle());
  206947. clearSingletonInstance();
  206948. }
  206949. String windowClassName;
  206950. juce_DeclareSingleton_SingleThreaded_Minimal (WindowClassHolder);
  206951. };
  206952. static void* createWindowCallback (void* userData)
  206953. {
  206954. ((Win32ComponentPeer*) userData)->createWindow();
  206955. return 0;
  206956. }
  206957. void createWindow()
  206958. {
  206959. DWORD exstyle = WS_EX_ACCEPTFILES;
  206960. DWORD type = WS_CLIPSIBLINGS | WS_CLIPCHILDREN;
  206961. if (hasTitleBar())
  206962. {
  206963. type |= WS_OVERLAPPED;
  206964. exstyle |= WS_EX_APPWINDOW;
  206965. if ((styleFlags & windowHasCloseButton) != 0)
  206966. {
  206967. type |= WS_SYSMENU;
  206968. }
  206969. else
  206970. {
  206971. // annoyingly, windows won't let you have a min/max button without a close button
  206972. jassert ((styleFlags & (windowHasMinimiseButton | windowHasMaximiseButton)) == 0);
  206973. }
  206974. if ((styleFlags & windowIsResizable) != 0)
  206975. type |= WS_THICKFRAME;
  206976. }
  206977. else
  206978. {
  206979. type |= WS_POPUP | WS_SYSMENU;
  206980. if ((styleFlags & windowAppearsOnTaskbar) == 0)
  206981. exstyle |= WS_EX_TOOLWINDOW;
  206982. else
  206983. exstyle |= WS_EX_APPWINDOW;
  206984. }
  206985. if ((styleFlags & windowHasMinimiseButton) != 0)
  206986. type |= WS_MINIMIZEBOX;
  206987. if ((styleFlags & windowHasMaximiseButton) != 0)
  206988. type |= WS_MAXIMIZEBOX;
  206989. if ((styleFlags & windowIgnoresMouseClicks) != 0)
  206990. exstyle |= WS_EX_TRANSPARENT;
  206991. if ((styleFlags & windowIsSemiTransparent) != 0
  206992. && Desktop::canUseSemiTransparentWindows())
  206993. exstyle |= WS_EX_LAYERED;
  206994. hwnd = CreateWindowEx (exstyle, WindowClassHolder::getInstance()->windowClassName, L"", type, 0, 0, 0, 0, 0, 0, 0, 0);
  206995. if (hwnd != 0)
  206996. {
  206997. SetWindowLongPtr (hwnd, 0, 0);
  206998. SetWindowLongPtr (hwnd, 8, (LONG_PTR) this);
  206999. SetWindowLongPtr (hwnd, GWLP_USERDATA, improbableWindowNumber);
  207000. if (dropTarget == 0)
  207001. dropTarget = new JuceDropTarget (this);
  207002. RegisterDragDrop (hwnd, dropTarget);
  207003. updateBorderSize();
  207004. // Calling this function here is (for some reason) necessary to make Windows
  207005. // correctly enable the menu items that we specify in the wm_initmenu message.
  207006. GetSystemMenu (hwnd, false);
  207007. }
  207008. else
  207009. {
  207010. jassertfalse
  207011. }
  207012. }
  207013. static void* destroyWindowCallback (void* handle)
  207014. {
  207015. RevokeDragDrop ((HWND) handle);
  207016. DestroyWindow ((HWND) handle);
  207017. return 0;
  207018. }
  207019. static void* toFrontCallback1 (void* h)
  207020. {
  207021. SetForegroundWindow ((HWND) h);
  207022. return 0;
  207023. }
  207024. static void* toFrontCallback2 (void* h)
  207025. {
  207026. SetWindowPos ((HWND) h, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_NOSENDCHANGING);
  207027. return 0;
  207028. }
  207029. static void* setFocusCallback (void* h)
  207030. {
  207031. SetFocus ((HWND) h);
  207032. return 0;
  207033. }
  207034. static void* getFocusCallback (void*)
  207035. {
  207036. return (void*) GetFocus();
  207037. }
  207038. void offsetWithinParent (int& x, int& y) const
  207039. {
  207040. if (isTransparent())
  207041. {
  207042. HWND parentHwnd = GetParent (hwnd);
  207043. if (parentHwnd != 0)
  207044. {
  207045. RECT parentRect;
  207046. GetWindowRect (parentHwnd, &parentRect);
  207047. x += parentRect.left;
  207048. y += parentRect.top;
  207049. }
  207050. }
  207051. }
  207052. bool isTransparent() const
  207053. {
  207054. return (GetWindowLong (hwnd, GWL_EXSTYLE) & WS_EX_LAYERED) != 0;
  207055. }
  207056. inline bool hasTitleBar() const throw() { return (styleFlags & windowHasTitleBar) != 0; }
  207057. void setIcon (const Image& newIcon)
  207058. {
  207059. HICON hicon = createHICONFromImage (newIcon, TRUE, 0, 0);
  207060. if (hicon != 0)
  207061. {
  207062. SendMessage (hwnd, WM_SETICON, ICON_BIG, (LPARAM) hicon);
  207063. SendMessage (hwnd, WM_SETICON, ICON_SMALL, (LPARAM) hicon);
  207064. if (currentWindowIcon != 0)
  207065. DestroyIcon (currentWindowIcon);
  207066. currentWindowIcon = hicon;
  207067. }
  207068. }
  207069. void handlePaintMessage()
  207070. {
  207071. #if DEBUG_REPAINT_TIMES
  207072. const double paintStart = Time::getMillisecondCounterHiRes();
  207073. #endif
  207074. HRGN rgn = CreateRectRgn (0, 0, 0, 0);
  207075. const int regionType = GetUpdateRgn (hwnd, rgn, false);
  207076. PAINTSTRUCT paintStruct;
  207077. HDC dc = BeginPaint (hwnd, &paintStruct); // Note this can immediately generate a WM_NCPAINT
  207078. // message and become re-entrant, but that's OK
  207079. // if something in a paint handler calls, e.g. a message box, this can become reentrant and
  207080. // corrupt the image it's using to paint into, so do a check here.
  207081. static bool reentrant = false;
  207082. if (reentrant)
  207083. {
  207084. DeleteObject (rgn);
  207085. EndPaint (hwnd, &paintStruct);
  207086. return;
  207087. }
  207088. reentrant = true;
  207089. // this is the rectangle to update..
  207090. int x = paintStruct.rcPaint.left;
  207091. int y = paintStruct.rcPaint.top;
  207092. int w = paintStruct.rcPaint.right - x;
  207093. int h = paintStruct.rcPaint.bottom - y;
  207094. const bool transparent = isTransparent();
  207095. if (transparent)
  207096. {
  207097. // it's not possible to have a transparent window with a title bar at the moment!
  207098. jassert (! hasTitleBar());
  207099. RECT r;
  207100. GetWindowRect (hwnd, &r);
  207101. x = y = 0;
  207102. w = r.right - r.left;
  207103. h = r.bottom - r.top;
  207104. }
  207105. if (w > 0 && h > 0)
  207106. {
  207107. clearMaskedRegion();
  207108. WindowsBitmapImage* const offscreenImage = offscreenImageGenerator.getImage (transparent, w, h);
  207109. LowLevelGraphicsSoftwareRenderer context (*offscreenImage);
  207110. RectangleList* const contextClip = context.getRawClipRegion();
  207111. contextClip->clear();
  207112. context.setOrigin (-x, -y);
  207113. bool needToPaintAll = true;
  207114. if (regionType == COMPLEXREGION && ! transparent)
  207115. {
  207116. HRGN clipRgn = CreateRectRgnIndirect (&paintStruct.rcPaint);
  207117. CombineRgn (rgn, rgn, clipRgn, RGN_AND);
  207118. DeleteObject (clipRgn);
  207119. char rgnData [8192];
  207120. const DWORD res = GetRegionData (rgn, sizeof (rgnData), (RGNDATA*) rgnData);
  207121. if (res > 0 && res <= sizeof (rgnData))
  207122. {
  207123. const RGNDATAHEADER* const hdr = &(((const RGNDATA*) rgnData)->rdh);
  207124. if (hdr->iType == RDH_RECTANGLES
  207125. && hdr->rcBound.right - hdr->rcBound.left >= w
  207126. && hdr->rcBound.bottom - hdr->rcBound.top >= h)
  207127. {
  207128. needToPaintAll = false;
  207129. const RECT* rects = (const RECT*) (rgnData + sizeof (RGNDATAHEADER));
  207130. int num = ((RGNDATA*) rgnData)->rdh.nCount;
  207131. while (--num >= 0)
  207132. {
  207133. // (need to move this one pixel to the left because of a win32 bug)
  207134. const int cx = jmax (x, rects->left - 1);
  207135. const int cy = rects->top;
  207136. const int cw = rects->right - cx;
  207137. const int ch = rects->bottom - rects->top;
  207138. if (cx + cw - x <= w && cy + ch - y <= h)
  207139. {
  207140. contextClip->addWithoutMerging (Rectangle (cx - x, cy - y, cw, ch));
  207141. }
  207142. else
  207143. {
  207144. needToPaintAll = true;
  207145. break;
  207146. }
  207147. ++rects;
  207148. }
  207149. }
  207150. }
  207151. }
  207152. if (needToPaintAll)
  207153. {
  207154. contextClip->clear();
  207155. contextClip->addWithoutMerging (Rectangle (0, 0, w, h));
  207156. }
  207157. if (transparent)
  207158. {
  207159. RectangleList::Iterator i (*contextClip);
  207160. while (i.next())
  207161. {
  207162. const Rectangle& r = *i.getRectangle();
  207163. offscreenImage->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  207164. }
  207165. }
  207166. // if the component's not opaque, this won't draw properly unless the platform can support this
  207167. jassert (Desktop::canUseSemiTransparentWindows() || component->isOpaque());
  207168. updateCurrentModifiers();
  207169. handlePaint (context);
  207170. if (! dontRepaint)
  207171. offscreenImage->blitToWindow (hwnd, dc, transparent, x, y, maskedRegion);
  207172. }
  207173. DeleteObject (rgn);
  207174. EndPaint (hwnd, &paintStruct);
  207175. reentrant = false;
  207176. #ifndef JUCE_GCC //xxx should add this fn for gcc..
  207177. _fpreset(); // because some graphics cards can unmask FP exceptions
  207178. #endif
  207179. lastPaintTime = Time::getMillisecondCounter();
  207180. #if DEBUG_REPAINT_TIMES
  207181. const double elapsed = Time::getMillisecondCounterHiRes() - paintStart;
  207182. Logger::outputDebugString (T("repaint time: ") + String (elapsed, 2));
  207183. #endif
  207184. }
  207185. void doMouseMove (const int x, const int y)
  207186. {
  207187. static uint32 lastMouseTime = 0;
  207188. // this can be set to throttle the mouse-messages to less than a
  207189. // certain number per second, as things can get unresponsive
  207190. // if each drag or move callback has to do a lot of work.
  207191. const int maxMouseMovesPerSecond = 60;
  207192. const int64 mouseEventTime = getMouseEventTime();
  207193. if (! isMouseOver)
  207194. {
  207195. isMouseOver = true;
  207196. TRACKMOUSEEVENT tme;
  207197. tme.cbSize = sizeof (tme);
  207198. tme.dwFlags = TME_LEAVE;
  207199. tme.hwndTrack = hwnd;
  207200. tme.dwHoverTime = 0;
  207201. if (! TrackMouseEvent (&tme))
  207202. {
  207203. jassertfalse;
  207204. }
  207205. updateKeyModifiers();
  207206. handleMouseEnter (x, y, mouseEventTime);
  207207. }
  207208. else if (! isDragging)
  207209. {
  207210. if (((unsigned int) x) < (unsigned int) component->getWidth()
  207211. && ((unsigned int) y) < (unsigned int) component->getHeight())
  207212. {
  207213. RECT r;
  207214. GetWindowRect (hwnd, &r);
  207215. POINT p;
  207216. p.x = x + r.left + windowBorder.getLeft();
  207217. p.y = y + r.top + windowBorder.getTop();
  207218. if (WindowFromPoint (p) == hwnd)
  207219. {
  207220. const uint32 now = Time::getMillisecondCounter();
  207221. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207222. {
  207223. lastMouseTime = now;
  207224. handleMouseMove (x, y, mouseEventTime);
  207225. }
  207226. }
  207227. }
  207228. }
  207229. else
  207230. {
  207231. const uint32 now = Time::getMillisecondCounter();
  207232. if (now > lastMouseTime + 1000 / maxMouseMovesPerSecond)
  207233. {
  207234. lastMouseTime = now;
  207235. handleMouseDrag (x, y, mouseEventTime);
  207236. }
  207237. }
  207238. }
  207239. void doMouseDown (const int x, const int y, const WPARAM wParam)
  207240. {
  207241. if (GetCapture() != hwnd)
  207242. SetCapture (hwnd);
  207243. doMouseMove (x, y);
  207244. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  207245. if ((wParam & MK_LBUTTON) != 0)
  207246. currentModifiers |= ModifierKeys::leftButtonModifier;
  207247. if ((wParam & MK_RBUTTON) != 0)
  207248. currentModifiers |= ModifierKeys::rightButtonModifier;
  207249. if ((wParam & MK_MBUTTON) != 0)
  207250. currentModifiers |= ModifierKeys::middleButtonModifier;
  207251. updateKeyModifiers();
  207252. isDragging = true;
  207253. handleMouseDown (x, y, getMouseEventTime());
  207254. }
  207255. void doMouseUp (const int x, const int y, const WPARAM wParam)
  207256. {
  207257. int numButtons = 0;
  207258. if ((wParam & MK_LBUTTON) != 0)
  207259. ++numButtons;
  207260. if ((wParam & MK_RBUTTON) != 0)
  207261. ++numButtons;
  207262. if ((wParam & MK_MBUTTON) != 0)
  207263. ++numButtons;
  207264. const int oldModifiers = currentModifiers;
  207265. // update the currentmodifiers only after the callback, so the callback
  207266. // knows which button was released.
  207267. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  207268. if ((wParam & MK_LBUTTON) != 0)
  207269. currentModifiers |= ModifierKeys::leftButtonModifier;
  207270. if ((wParam & MK_RBUTTON) != 0)
  207271. currentModifiers |= ModifierKeys::rightButtonModifier;
  207272. if ((wParam & MK_MBUTTON) != 0)
  207273. currentModifiers |= ModifierKeys::middleButtonModifier;
  207274. updateKeyModifiers();
  207275. isDragging = false;
  207276. // release the mouse capture if the user's not still got a button down
  207277. if (numButtons == 0 && hwnd == GetCapture())
  207278. ReleaseCapture();
  207279. handleMouseUp (oldModifiers, x, y, getMouseEventTime());
  207280. }
  207281. void doCaptureChanged()
  207282. {
  207283. if (isDragging)
  207284. {
  207285. RECT wr;
  207286. GetWindowRect (hwnd, &wr);
  207287. const DWORD mp = GetMessagePos();
  207288. doMouseUp (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207289. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  207290. (WPARAM) getMouseEventTime());
  207291. }
  207292. }
  207293. void doMouseExit()
  207294. {
  207295. if (isMouseOver)
  207296. {
  207297. isMouseOver = false;
  207298. RECT wr;
  207299. GetWindowRect (hwnd, &wr);
  207300. const DWORD mp = GetMessagePos();
  207301. handleMouseExit (GET_X_LPARAM (mp) - wr.left - windowBorder.getLeft(),
  207302. GET_Y_LPARAM (mp) - wr.top - windowBorder.getTop(),
  207303. getMouseEventTime());
  207304. }
  207305. }
  207306. void doMouseWheel (const WPARAM wParam, const bool isVertical)
  207307. {
  207308. updateKeyModifiers();
  207309. const int amount = jlimit (-1000, 1000, (int) (0.75f * (short) HIWORD (wParam)));
  207310. handleMouseWheel (isVertical ? 0 : amount,
  207311. isVertical ? amount : 0,
  207312. getMouseEventTime());
  207313. }
  207314. void sendModifierKeyChangeIfNeeded()
  207315. {
  207316. if (modifiersAtLastCallback != currentModifiers)
  207317. {
  207318. modifiersAtLastCallback = currentModifiers;
  207319. handleModifierKeysChange();
  207320. }
  207321. }
  207322. bool doKeyUp (const WPARAM key)
  207323. {
  207324. updateKeyModifiers();
  207325. switch (key)
  207326. {
  207327. case VK_SHIFT:
  207328. case VK_CONTROL:
  207329. case VK_MENU:
  207330. case VK_CAPITAL:
  207331. case VK_LWIN:
  207332. case VK_RWIN:
  207333. case VK_APPS:
  207334. case VK_NUMLOCK:
  207335. case VK_SCROLL:
  207336. case VK_LSHIFT:
  207337. case VK_RSHIFT:
  207338. case VK_LCONTROL:
  207339. case VK_LMENU:
  207340. case VK_RCONTROL:
  207341. case VK_RMENU:
  207342. sendModifierKeyChangeIfNeeded();
  207343. }
  207344. return handleKeyUpOrDown();
  207345. }
  207346. bool doKeyDown (const WPARAM key)
  207347. {
  207348. updateKeyModifiers();
  207349. bool used = false;
  207350. switch (key)
  207351. {
  207352. case VK_SHIFT:
  207353. case VK_LSHIFT:
  207354. case VK_RSHIFT:
  207355. case VK_CONTROL:
  207356. case VK_LCONTROL:
  207357. case VK_RCONTROL:
  207358. case VK_MENU:
  207359. case VK_LMENU:
  207360. case VK_RMENU:
  207361. case VK_LWIN:
  207362. case VK_RWIN:
  207363. case VK_CAPITAL:
  207364. case VK_NUMLOCK:
  207365. case VK_SCROLL:
  207366. case VK_APPS:
  207367. sendModifierKeyChangeIfNeeded();
  207368. break;
  207369. case VK_LEFT:
  207370. case VK_RIGHT:
  207371. case VK_UP:
  207372. case VK_DOWN:
  207373. case VK_PRIOR:
  207374. case VK_NEXT:
  207375. case VK_HOME:
  207376. case VK_END:
  207377. case VK_DELETE:
  207378. case VK_INSERT:
  207379. case VK_F1:
  207380. case VK_F2:
  207381. case VK_F3:
  207382. case VK_F4:
  207383. case VK_F5:
  207384. case VK_F6:
  207385. case VK_F7:
  207386. case VK_F8:
  207387. case VK_F9:
  207388. case VK_F10:
  207389. case VK_F11:
  207390. case VK_F12:
  207391. case VK_F13:
  207392. case VK_F14:
  207393. case VK_F15:
  207394. case VK_F16:
  207395. used = handleKeyUpOrDown();
  207396. used = handleKeyPress (extendedKeyModifier | (int) key, 0) || used;
  207397. break;
  207398. case VK_ADD:
  207399. case VK_SUBTRACT:
  207400. case VK_MULTIPLY:
  207401. case VK_DIVIDE:
  207402. case VK_SEPARATOR:
  207403. case VK_DECIMAL:
  207404. used = handleKeyUpOrDown();
  207405. break;
  207406. default:
  207407. used = handleKeyUpOrDown();
  207408. {
  207409. MSG msg;
  207410. if (! PeekMessage (&msg, hwnd, WM_CHAR, WM_DEADCHAR, PM_NOREMOVE))
  207411. {
  207412. // if there isn't a WM_CHAR or WM_DEADCHAR message pending, we need to
  207413. // manually generate the key-press event that matches this key-down.
  207414. const UINT keyChar = MapVirtualKey (key, 2);
  207415. used = handleKeyPress ((int) LOWORD (keyChar), 0) || used;
  207416. }
  207417. }
  207418. break;
  207419. }
  207420. return used;
  207421. }
  207422. bool doKeyChar (int key, const LPARAM flags)
  207423. {
  207424. updateKeyModifiers();
  207425. juce_wchar textChar = (juce_wchar) key;
  207426. const int virtualScanCode = (flags >> 16) & 0xff;
  207427. if (key >= '0' && key <= '9')
  207428. {
  207429. switch (virtualScanCode) // check for a numeric keypad scan-code
  207430. {
  207431. case 0x52:
  207432. case 0x4f:
  207433. case 0x50:
  207434. case 0x51:
  207435. case 0x4b:
  207436. case 0x4c:
  207437. case 0x4d:
  207438. case 0x47:
  207439. case 0x48:
  207440. case 0x49:
  207441. key = (key - '0') + KeyPress::numberPad0;
  207442. break;
  207443. default:
  207444. break;
  207445. }
  207446. }
  207447. else
  207448. {
  207449. // convert the scan code to an unmodified character code..
  207450. const UINT virtualKey = MapVirtualKey (virtualScanCode, 1);
  207451. UINT keyChar = MapVirtualKey (virtualKey, 2);
  207452. keyChar = LOWORD (keyChar);
  207453. if (keyChar != 0)
  207454. key = (int) keyChar;
  207455. // avoid sending junk text characters for some control-key combinations
  207456. if (textChar < ' ' && (currentModifiers & (ModifierKeys::ctrlModifier | ModifierKeys::altModifier)) != 0)
  207457. textChar = 0;
  207458. }
  207459. return handleKeyPress (key, textChar);
  207460. }
  207461. bool doAppCommand (const LPARAM lParam)
  207462. {
  207463. int key = 0;
  207464. switch (GET_APPCOMMAND_LPARAM (lParam))
  207465. {
  207466. case APPCOMMAND_MEDIA_PLAY_PAUSE:
  207467. key = KeyPress::playKey;
  207468. break;
  207469. case APPCOMMAND_MEDIA_STOP:
  207470. key = KeyPress::stopKey;
  207471. break;
  207472. case APPCOMMAND_MEDIA_NEXTTRACK:
  207473. key = KeyPress::fastForwardKey;
  207474. break;
  207475. case APPCOMMAND_MEDIA_PREVIOUSTRACK:
  207476. key = KeyPress::rewindKey;
  207477. break;
  207478. }
  207479. if (key != 0)
  207480. {
  207481. updateKeyModifiers();
  207482. if (hwnd == GetActiveWindow())
  207483. {
  207484. handleKeyPress (key, 0);
  207485. return true;
  207486. }
  207487. }
  207488. return false;
  207489. }
  207490. class JuceDropTarget : public IDropTarget
  207491. {
  207492. public:
  207493. JuceDropTarget (Win32ComponentPeer* const owner_)
  207494. : owner (owner_),
  207495. refCount (1)
  207496. {
  207497. }
  207498. virtual ~JuceDropTarget()
  207499. {
  207500. jassert (refCount == 0);
  207501. }
  207502. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  207503. {
  207504. if (id == IID_IUnknown || id == IID_IDropTarget)
  207505. {
  207506. AddRef();
  207507. *result = this;
  207508. return S_OK;
  207509. }
  207510. *result = 0;
  207511. return E_NOINTERFACE;
  207512. }
  207513. ULONG __stdcall AddRef() { return ++refCount; }
  207514. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  207515. HRESULT __stdcall DragEnter (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207516. {
  207517. updateFileList (pDataObject);
  207518. int x = mousePos.x, y = mousePos.y;
  207519. owner->globalPositionToRelative (x, y);
  207520. owner->handleFileDragMove (files, x, y);
  207521. *pdwEffect = DROPEFFECT_COPY;
  207522. return S_OK;
  207523. }
  207524. HRESULT __stdcall DragLeave()
  207525. {
  207526. owner->handleFileDragExit (files);
  207527. return S_OK;
  207528. }
  207529. HRESULT __stdcall DragOver (DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207530. {
  207531. int x = mousePos.x, y = mousePos.y;
  207532. owner->globalPositionToRelative (x, y);
  207533. owner->handleFileDragMove (files, x, y);
  207534. *pdwEffect = DROPEFFECT_COPY;
  207535. return S_OK;
  207536. }
  207537. HRESULT __stdcall Drop (IDataObject* pDataObject, DWORD /*grfKeyState*/, POINTL mousePos, DWORD* pdwEffect)
  207538. {
  207539. updateFileList (pDataObject);
  207540. int x = mousePos.x, y = mousePos.y;
  207541. owner->globalPositionToRelative (x, y);
  207542. owner->handleFileDragDrop (files, x, y);
  207543. *pdwEffect = DROPEFFECT_COPY;
  207544. return S_OK;
  207545. }
  207546. private:
  207547. Win32ComponentPeer* const owner;
  207548. int refCount;
  207549. StringArray files;
  207550. void updateFileList (IDataObject* const pDataObject)
  207551. {
  207552. files.clear();
  207553. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  207554. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  207555. if (pDataObject->GetData (&format, &medium) == S_OK)
  207556. {
  207557. const SIZE_T totalLen = GlobalSize (medium.hGlobal);
  207558. const LPDROPFILES pDropFiles = (const LPDROPFILES) GlobalLock (medium.hGlobal);
  207559. unsigned int i = 0;
  207560. if (pDropFiles->fWide)
  207561. {
  207562. const WCHAR* const fname = (WCHAR*) (((const char*) pDropFiles) + sizeof (DROPFILES));
  207563. for (;;)
  207564. {
  207565. unsigned int len = 0;
  207566. while (i + len < totalLen && fname [i + len] != 0)
  207567. ++len;
  207568. if (len == 0)
  207569. break;
  207570. files.add (String (fname + i, len));
  207571. i += len + 1;
  207572. }
  207573. }
  207574. else
  207575. {
  207576. const char* const fname = ((const char*) pDropFiles) + sizeof (DROPFILES);
  207577. for (;;)
  207578. {
  207579. unsigned int len = 0;
  207580. while (i + len < totalLen && fname [i + len] != 0)
  207581. ++len;
  207582. if (len == 0)
  207583. break;
  207584. files.add (String (fname + i, len));
  207585. i += len + 1;
  207586. }
  207587. }
  207588. GlobalUnlock (medium.hGlobal);
  207589. }
  207590. }
  207591. JuceDropTarget (const JuceDropTarget&);
  207592. const JuceDropTarget& operator= (const JuceDropTarget&);
  207593. };
  207594. void doSettingChange()
  207595. {
  207596. Desktop::getInstance().refreshMonitorSizes();
  207597. if (fullScreen && ! isMinimised())
  207598. {
  207599. const Rectangle r (component->getParentMonitorArea());
  207600. SetWindowPos (hwnd, 0,
  207601. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  207602. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER | SWP_NOSENDCHANGING);
  207603. }
  207604. }
  207605. public:
  207606. static LRESULT CALLBACK windowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207607. {
  207608. Win32ComponentPeer* const peer = getOwnerOfWindow (h);
  207609. if (peer != 0)
  207610. return peer->peerWindowProc (h, message, wParam, lParam);
  207611. return DefWindowProc (h, message, wParam, lParam);
  207612. }
  207613. private:
  207614. LRESULT peerWindowProc (HWND h, UINT message, WPARAM wParam, LPARAM lParam)
  207615. {
  207616. {
  207617. const MessageManagerLock messLock;
  207618. if (isValidPeer (this))
  207619. {
  207620. switch (message)
  207621. {
  207622. case WM_NCHITTEST:
  207623. if (hasTitleBar())
  207624. break;
  207625. return HTCLIENT;
  207626. case WM_PAINT:
  207627. handlePaintMessage();
  207628. return 0;
  207629. case WM_NCPAINT:
  207630. if (wParam != 1)
  207631. handlePaintMessage();
  207632. if (hasTitleBar())
  207633. break;
  207634. return 0;
  207635. case WM_ERASEBKGND:
  207636. case WM_NCCALCSIZE:
  207637. if (hasTitleBar())
  207638. break;
  207639. return 1;
  207640. case WM_MOUSEMOVE:
  207641. doMouseMove (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam));
  207642. return 0;
  207643. case WM_MOUSELEAVE:
  207644. doMouseExit();
  207645. return 0;
  207646. case WM_LBUTTONDOWN:
  207647. case WM_MBUTTONDOWN:
  207648. case WM_RBUTTONDOWN:
  207649. doMouseDown (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  207650. return 0;
  207651. case WM_LBUTTONUP:
  207652. case WM_MBUTTONUP:
  207653. case WM_RBUTTONUP:
  207654. doMouseUp (GET_X_LPARAM (lParam), GET_Y_LPARAM (lParam), wParam);
  207655. return 0;
  207656. case WM_CAPTURECHANGED:
  207657. doCaptureChanged();
  207658. return 0;
  207659. case WM_NCMOUSEMOVE:
  207660. if (hasTitleBar())
  207661. break;
  207662. return 0;
  207663. case 0x020A: /* WM_MOUSEWHEEL */
  207664. doMouseWheel (wParam, true);
  207665. return 0;
  207666. case 0x020E: /* WM_MOUSEHWHEEL */
  207667. doMouseWheel (wParam, false);
  207668. return 0;
  207669. case WM_WINDOWPOSCHANGING:
  207670. if ((styleFlags & (windowHasTitleBar | windowIsResizable)) == (windowHasTitleBar | windowIsResizable))
  207671. {
  207672. WINDOWPOS* const wp = (WINDOWPOS*) lParam;
  207673. if ((wp->flags & (SWP_NOMOVE | SWP_NOSIZE)) != (SWP_NOMOVE | SWP_NOSIZE))
  207674. {
  207675. if (constrainer != 0)
  207676. {
  207677. const Rectangle current (component->getX() - windowBorder.getLeft(),
  207678. component->getY() - windowBorder.getTop(),
  207679. component->getWidth() + windowBorder.getLeftAndRight(),
  207680. component->getHeight() + windowBorder.getTopAndBottom());
  207681. constrainer->checkBounds (wp->x, wp->y, wp->cx, wp->cy,
  207682. current,
  207683. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  207684. wp->y != current.getY() && wp->y + wp->cy == current.getBottom(),
  207685. wp->x != current.getX() && wp->x + wp->cx == current.getRight(),
  207686. wp->y == current.getY() && wp->y + wp->cy != current.getBottom(),
  207687. wp->x == current.getX() && wp->x + wp->cx != current.getRight());
  207688. }
  207689. }
  207690. }
  207691. return 0;
  207692. case WM_WINDOWPOSCHANGED:
  207693. handleMovedOrResized();
  207694. if (dontRepaint)
  207695. break; // needed for non-accelerated openGL windows to draw themselves correctly..
  207696. else
  207697. return 0;
  207698. case WM_KEYDOWN:
  207699. case WM_SYSKEYDOWN:
  207700. if (doKeyDown (wParam))
  207701. return 0;
  207702. break;
  207703. case WM_KEYUP:
  207704. case WM_SYSKEYUP:
  207705. if (doKeyUp (wParam))
  207706. return 0;
  207707. break;
  207708. case WM_CHAR:
  207709. if (doKeyChar ((int) wParam, lParam))
  207710. return 0;
  207711. break;
  207712. case WM_APPCOMMAND:
  207713. if (doAppCommand (lParam))
  207714. return TRUE;
  207715. break;
  207716. case WM_SETFOCUS:
  207717. updateKeyModifiers();
  207718. handleFocusGain();
  207719. break;
  207720. case WM_KILLFOCUS:
  207721. if (hasCreatedCaret)
  207722. {
  207723. hasCreatedCaret = false;
  207724. DestroyCaret();
  207725. }
  207726. handleFocusLoss();
  207727. break;
  207728. case WM_ACTIVATEAPP:
  207729. // Windows does weird things to process priority when you swap apps,
  207730. // so this forces an update when the app is brought to the front
  207731. if (wParam != FALSE)
  207732. juce_repeatLastProcessPriority();
  207733. juce_CheckCurrentlyFocusedTopLevelWindow();
  207734. modifiersAtLastCallback = -1;
  207735. return 0;
  207736. case WM_ACTIVATE:
  207737. if (LOWORD (wParam) == WA_ACTIVE || LOWORD (wParam) == WA_CLICKACTIVE)
  207738. {
  207739. modifiersAtLastCallback = -1;
  207740. updateKeyModifiers();
  207741. if (isMinimised())
  207742. {
  207743. component->repaint();
  207744. handleMovedOrResized();
  207745. if (! isValidMessageListener())
  207746. return 0;
  207747. }
  207748. if (LOWORD (wParam) == WA_CLICKACTIVE
  207749. && component->isCurrentlyBlockedByAnotherModalComponent())
  207750. {
  207751. int mx, my;
  207752. component->getMouseXYRelative (mx, my);
  207753. Component* const underMouse = component->getComponentAt (mx, my);
  207754. if (underMouse != 0 && underMouse->isCurrentlyBlockedByAnotherModalComponent())
  207755. Component::getCurrentlyModalComponent()->inputAttemptWhenModal();
  207756. return 0;
  207757. }
  207758. handleBroughtToFront();
  207759. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207760. Component::getCurrentlyModalComponent()->toFront (true);
  207761. return 0;
  207762. }
  207763. break;
  207764. case WM_NCACTIVATE:
  207765. // while a temporary window is being shown, prevent Windows from deactivating the
  207766. // title bars of our main windows.
  207767. if (wParam == 0 && ! shouldDeactivateTitleBar)
  207768. wParam = TRUE; // change this and let it get passed to the DefWindowProc.
  207769. break;
  207770. case WM_MOUSEACTIVATE:
  207771. if (! component->getMouseClickGrabsKeyboardFocus())
  207772. return MA_NOACTIVATE;
  207773. break;
  207774. case WM_SHOWWINDOW:
  207775. if (wParam != 0)
  207776. handleBroughtToFront();
  207777. break;
  207778. case WM_CLOSE:
  207779. handleUserClosingWindow();
  207780. return 0;
  207781. case WM_QUIT:
  207782. JUCEApplication::quit();
  207783. return 0;
  207784. case WM_TRAYNOTIFY:
  207785. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207786. {
  207787. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN
  207788. || lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207789. {
  207790. Component* const current = Component::getCurrentlyModalComponent();
  207791. if (current != 0)
  207792. current->inputAttemptWhenModal();
  207793. }
  207794. }
  207795. else
  207796. {
  207797. const int oldModifiers = currentModifiers;
  207798. MouseEvent e (0, 0, ModifierKeys::getCurrentModifiersRealtime(), component,
  207799. getMouseEventTime(), 0, 0, getMouseEventTime(), 1, false);
  207800. if (lParam == WM_LBUTTONDOWN || lParam == WM_LBUTTONDBLCLK)
  207801. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::leftButtonModifier);
  207802. else if (lParam == WM_RBUTTONDOWN || lParam == WM_RBUTTONDBLCLK)
  207803. e.mods = ModifierKeys (e.mods.getRawFlags() | ModifierKeys::rightButtonModifier);
  207804. if (lParam == WM_LBUTTONDOWN || lParam == WM_RBUTTONDOWN)
  207805. {
  207806. SetFocus (hwnd);
  207807. SetForegroundWindow (hwnd);
  207808. component->mouseDown (e);
  207809. }
  207810. else if (lParam == WM_LBUTTONUP || lParam == WM_RBUTTONUP)
  207811. {
  207812. e.mods = ModifierKeys (oldModifiers);
  207813. component->mouseUp (e);
  207814. }
  207815. else if (lParam == WM_LBUTTONDBLCLK || lParam == WM_LBUTTONDBLCLK)
  207816. {
  207817. e.mods = ModifierKeys (oldModifiers);
  207818. component->mouseDoubleClick (e);
  207819. }
  207820. else if (lParam == WM_MOUSEMOVE)
  207821. {
  207822. component->mouseMove (e);
  207823. }
  207824. }
  207825. break;
  207826. case WM_SYNCPAINT:
  207827. return 0;
  207828. case WM_PALETTECHANGED:
  207829. InvalidateRect (h, 0, 0);
  207830. break;
  207831. case WM_DISPLAYCHANGE:
  207832. InvalidateRect (h, 0, 0);
  207833. createPaletteIfNeeded = true;
  207834. // intentional fall-through...
  207835. case WM_SETTINGCHANGE: // note the fall-through in the previous case!
  207836. doSettingChange();
  207837. break;
  207838. case WM_INITMENU:
  207839. if (! hasTitleBar())
  207840. {
  207841. if (isFullScreen())
  207842. {
  207843. EnableMenuItem ((HMENU) wParam, SC_RESTORE, MF_BYCOMMAND | MF_ENABLED);
  207844. EnableMenuItem ((HMENU) wParam, SC_MOVE, MF_BYCOMMAND | MF_GRAYED);
  207845. }
  207846. else if (! isMinimised())
  207847. {
  207848. EnableMenuItem ((HMENU) wParam, SC_MAXIMIZE, MF_BYCOMMAND | MF_GRAYED);
  207849. }
  207850. }
  207851. break;
  207852. case WM_SYSCOMMAND:
  207853. switch (wParam & 0xfff0)
  207854. {
  207855. case SC_CLOSE:
  207856. if (hasTitleBar())
  207857. {
  207858. PostMessage (h, WM_CLOSE, 0, 0);
  207859. return 0;
  207860. }
  207861. break;
  207862. case SC_KEYMENU:
  207863. if (hasTitleBar() && h == GetCapture())
  207864. ReleaseCapture();
  207865. break;
  207866. case SC_MAXIMIZE:
  207867. setFullScreen (true);
  207868. return 0;
  207869. case SC_MINIMIZE:
  207870. if (! hasTitleBar())
  207871. {
  207872. setMinimised (true);
  207873. return 0;
  207874. }
  207875. break;
  207876. case SC_RESTORE:
  207877. if (hasTitleBar())
  207878. {
  207879. if (isFullScreen())
  207880. {
  207881. setFullScreen (false);
  207882. return 0;
  207883. }
  207884. }
  207885. else
  207886. {
  207887. if (isMinimised())
  207888. setMinimised (false);
  207889. else if (isFullScreen())
  207890. setFullScreen (false);
  207891. return 0;
  207892. }
  207893. break;
  207894. case SC_MONITORPOWER:
  207895. case SC_SCREENSAVE:
  207896. if (! screenSaverAllowed)
  207897. return 0;
  207898. break;
  207899. }
  207900. break;
  207901. case WM_NCLBUTTONDOWN:
  207902. case WM_NCRBUTTONDOWN:
  207903. case WM_NCMBUTTONDOWN:
  207904. if (component->isCurrentlyBlockedByAnotherModalComponent())
  207905. {
  207906. Component* const current = Component::getCurrentlyModalComponent();
  207907. if (current != 0)
  207908. current->inputAttemptWhenModal();
  207909. }
  207910. break;
  207911. //case WM_IME_STARTCOMPOSITION;
  207912. // return 0;
  207913. case WM_GETDLGCODE:
  207914. return DLGC_WANTALLKEYS;
  207915. default:
  207916. break;
  207917. }
  207918. }
  207919. }
  207920. // (the message manager lock exits before calling this, to avoid deadlocks if
  207921. // this calls into non-juce windows)
  207922. return DefWindowProc (h, message, wParam, lParam);
  207923. }
  207924. Win32ComponentPeer (const Win32ComponentPeer&);
  207925. const Win32ComponentPeer& operator= (const Win32ComponentPeer&);
  207926. };
  207927. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  207928. {
  207929. return new Win32ComponentPeer (this, styleFlags);
  207930. }
  207931. juce_ImplementSingleton_SingleThreaded (Win32ComponentPeer::WindowClassHolder);
  207932. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  207933. {
  207934. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  207935. if (wp != 0)
  207936. wp->setTaskBarIcon (&newImage);
  207937. }
  207938. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  207939. {
  207940. Win32ComponentPeer* const wp = dynamic_cast <Win32ComponentPeer*> (getPeer());
  207941. if (wp != 0)
  207942. wp->setTaskBarIconToolTip (tooltip);
  207943. }
  207944. void juce_setWindowStyleBit (HWND h, const int styleType, const int feature, const bool bitIsSet) throw()
  207945. {
  207946. DWORD val = GetWindowLong (h, styleType);
  207947. if (bitIsSet)
  207948. val |= feature;
  207949. else
  207950. val &= ~feature;
  207951. SetWindowLongPtr (h, styleType, val);
  207952. SetWindowPos (h, 0, 0, 0, 0, 0,
  207953. SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER
  207954. | SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOSENDCHANGING);
  207955. }
  207956. bool Process::isForegroundProcess() throw()
  207957. {
  207958. HWND fg = GetForegroundWindow();
  207959. if (fg == 0)
  207960. return true;
  207961. DWORD processId = 0;
  207962. GetWindowThreadProcessId (fg, &processId);
  207963. return processId == GetCurrentProcessId();
  207964. }
  207965. bool AlertWindow::showNativeDialogBox (const String& title,
  207966. const String& bodyText,
  207967. bool isOkCancel)
  207968. {
  207969. return MessageBox (0, bodyText, title,
  207970. MB_SETFOREGROUND | (isOkCancel ? MB_OKCANCEL
  207971. : MB_OK)) == IDOK;
  207972. }
  207973. void Desktop::getMousePosition (int& x, int& y) throw()
  207974. {
  207975. POINT mousePos;
  207976. GetCursorPos (&mousePos);
  207977. x = mousePos.x;
  207978. y = mousePos.y;
  207979. }
  207980. void Desktop::setMousePosition (int x, int y) throw()
  207981. {
  207982. SetCursorPos (x, y);
  207983. }
  207984. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  207985. {
  207986. screenSaverAllowed = isEnabled;
  207987. }
  207988. bool Desktop::isScreenSaverEnabled() throw()
  207989. {
  207990. return screenSaverAllowed;
  207991. }
  207992. static BOOL CALLBACK enumMonitorsProc (HMONITOR, HDC, LPRECT r, LPARAM userInfo)
  207993. {
  207994. Array <Rectangle>* const monitorCoords = (Array <Rectangle>*) userInfo;
  207995. monitorCoords->add (Rectangle (r->left, r->top, r->right - r->left, r->bottom - r->top));
  207996. return TRUE;
  207997. }
  207998. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  207999. {
  208000. EnumDisplayMonitors (0, 0, &enumMonitorsProc, (LPARAM) &monitorCoords);
  208001. // make sure the first in the list is the main monitor
  208002. for (int i = 1; i < monitorCoords.size(); ++i)
  208003. if (monitorCoords[i].getX() == 0 && monitorCoords[i].getY() == 0)
  208004. monitorCoords.swap (i, 0);
  208005. if (monitorCoords.size() == 0)
  208006. {
  208007. RECT r;
  208008. GetWindowRect (GetDesktopWindow(), &r);
  208009. monitorCoords.add (Rectangle (r.left, r.top, r.right - r.left, r.bottom - r.top));
  208010. }
  208011. if (clipToWorkArea)
  208012. {
  208013. // clip the main monitor to the active non-taskbar area
  208014. RECT r;
  208015. SystemParametersInfo (SPI_GETWORKAREA, 0, &r, 0);
  208016. Rectangle& screen = monitorCoords.getReference (0);
  208017. screen.setPosition (jmax (screen.getX(), r.left),
  208018. jmax (screen.getY(), r.top));
  208019. screen.setSize (jmin (screen.getRight(), r.right) - screen.getX(),
  208020. jmin (screen.getBottom(), r.bottom) - screen.getY());
  208021. }
  208022. }
  208023. static Image* createImageFromHBITMAP (HBITMAP bitmap) throw()
  208024. {
  208025. Image* im = 0;
  208026. if (bitmap != 0)
  208027. {
  208028. BITMAP bm;
  208029. if (GetObject (bitmap, sizeof (BITMAP), &bm)
  208030. && bm.bmWidth > 0 && bm.bmHeight > 0)
  208031. {
  208032. HDC tempDC = GetDC (0);
  208033. HDC dc = CreateCompatibleDC (tempDC);
  208034. ReleaseDC (0, tempDC);
  208035. SelectObject (dc, bitmap);
  208036. im = new Image (Image::ARGB, bm.bmWidth, bm.bmHeight, true);
  208037. for (int y = bm.bmHeight; --y >= 0;)
  208038. {
  208039. for (int x = bm.bmWidth; --x >= 0;)
  208040. {
  208041. COLORREF col = GetPixel (dc, x, y);
  208042. im->setPixelAt (x, y, Colour ((uint8) GetRValue (col),
  208043. (uint8) GetGValue (col),
  208044. (uint8) GetBValue (col)));
  208045. }
  208046. }
  208047. DeleteDC (dc);
  208048. }
  208049. }
  208050. return im;
  208051. }
  208052. static Image* createImageFromHICON (HICON icon) throw()
  208053. {
  208054. ICONINFO info;
  208055. if (GetIconInfo (icon, &info))
  208056. {
  208057. Image* const mask = createImageFromHBITMAP (info.hbmMask);
  208058. if (mask == 0)
  208059. return 0;
  208060. Image* const image = createImageFromHBITMAP (info.hbmColor);
  208061. if (image == 0)
  208062. return mask;
  208063. for (int y = image->getHeight(); --y >= 0;)
  208064. {
  208065. for (int x = image->getWidth(); --x >= 0;)
  208066. {
  208067. const float brightness = mask->getPixelAt (x, y).getBrightness();
  208068. if (brightness > 0.0f)
  208069. image->multiplyAlphaAt (x, y, 1.0f - brightness);
  208070. }
  208071. }
  208072. delete mask;
  208073. return image;
  208074. }
  208075. return 0;
  208076. }
  208077. static HICON createHICONFromImage (const Image& image, const BOOL isIcon, int hotspotX, int hotspotY) throw()
  208078. {
  208079. HBITMAP mask = CreateBitmap (image.getWidth(), image.getHeight(), 1, 1, 0);
  208080. ICONINFO info;
  208081. info.fIcon = isIcon;
  208082. info.xHotspot = hotspotX;
  208083. info.yHotspot = hotspotY;
  208084. info.hbmMask = mask;
  208085. HICON hi = 0;
  208086. if (SystemStats::getOperatingSystemType() >= SystemStats::WinXP)
  208087. {
  208088. WindowsBitmapImage bitmap (Image::ARGB, image.getWidth(), image.getHeight(), true);
  208089. Graphics g (bitmap);
  208090. g.drawImageAt (&image, 0, 0);
  208091. info.hbmColor = bitmap.hBitmap;
  208092. hi = CreateIconIndirect (&info);
  208093. }
  208094. else
  208095. {
  208096. HBITMAP colour = CreateCompatibleBitmap (GetDC (0), image.getWidth(), image.getHeight());
  208097. HDC colDC = CreateCompatibleDC (GetDC (0));
  208098. HDC alphaDC = CreateCompatibleDC (GetDC (0));
  208099. SelectObject (colDC, colour);
  208100. SelectObject (alphaDC, mask);
  208101. for (int y = image.getHeight(); --y >= 0;)
  208102. {
  208103. for (int x = image.getWidth(); --x >= 0;)
  208104. {
  208105. const Colour c (image.getPixelAt (x, y));
  208106. SetPixel (colDC, x, y, COLORREF (c.getRed() | (c.getGreen() << 8) | (c.getBlue() << 16)));
  208107. SetPixel (alphaDC, x, y, COLORREF (0xffffff - (c.getAlpha() | (c.getAlpha() << 8) | (c.getAlpha() << 16))));
  208108. }
  208109. }
  208110. DeleteDC (colDC);
  208111. DeleteDC (alphaDC);
  208112. info.hbmColor = colour;
  208113. hi = CreateIconIndirect (&info);
  208114. DeleteObject (colour);
  208115. }
  208116. DeleteObject (mask);
  208117. return hi;
  208118. }
  208119. Image* juce_createIconForFile (const File& file)
  208120. {
  208121. Image* image = 0;
  208122. TCHAR filename [1024];
  208123. file.getFullPathName().copyToBuffer (filename, 1023);
  208124. WORD iconNum = 0;
  208125. HICON icon = ExtractAssociatedIcon ((HINSTANCE) PlatformUtilities::getCurrentModuleInstanceHandle(),
  208126. filename, &iconNum);
  208127. if (icon != 0)
  208128. {
  208129. image = createImageFromHICON (icon);
  208130. DestroyIcon (icon);
  208131. }
  208132. return image;
  208133. }
  208134. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  208135. {
  208136. const int maxW = GetSystemMetrics (SM_CXCURSOR);
  208137. const int maxH = GetSystemMetrics (SM_CYCURSOR);
  208138. const Image* im = &image;
  208139. Image* newIm = 0;
  208140. if (image.getWidth() > maxW || image.getHeight() > maxH)
  208141. {
  208142. im = newIm = image.createCopy (maxW, maxH);
  208143. hotspotX = (hotspotX * maxW) / image.getWidth();
  208144. hotspotY = (hotspotY * maxH) / image.getHeight();
  208145. }
  208146. void* cursorH = 0;
  208147. const SystemStats::OperatingSystemType os = SystemStats::getOperatingSystemType();
  208148. if (os == SystemStats::WinXP)
  208149. {
  208150. cursorH = (void*) createHICONFromImage (*im, FALSE, hotspotX, hotspotY);
  208151. }
  208152. else
  208153. {
  208154. const int stride = (maxW + 7) >> 3;
  208155. uint8* const andPlane = (uint8*) juce_calloc (stride * maxH);
  208156. uint8* const xorPlane = (uint8*) juce_calloc (stride * maxH);
  208157. int index = 0;
  208158. for (int y = 0; y < maxH; ++y)
  208159. {
  208160. for (int x = 0; x < maxW; ++x)
  208161. {
  208162. const unsigned char bit = (unsigned char) (1 << (7 - (x & 7)));
  208163. const Colour pixelColour (im->getPixelAt (x, y));
  208164. if (pixelColour.getAlpha() < 127)
  208165. andPlane [index + (x >> 3)] |= bit;
  208166. else if (pixelColour.getBrightness() >= 0.5f)
  208167. xorPlane [index + (x >> 3)] |= bit;
  208168. }
  208169. index += stride;
  208170. }
  208171. cursorH = CreateCursor (0, hotspotX, hotspotY, maxW, maxH, andPlane, xorPlane);
  208172. juce_free (andPlane);
  208173. juce_free (xorPlane);
  208174. }
  208175. delete newIm;
  208176. return cursorH;
  208177. }
  208178. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  208179. {
  208180. if (cursorHandle != 0 && ! isStandard)
  208181. DestroyCursor ((HCURSOR) cursorHandle);
  208182. }
  208183. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  208184. {
  208185. LPCTSTR cursorName = IDC_ARROW;
  208186. switch (type)
  208187. {
  208188. case MouseCursor::NormalCursor:
  208189. cursorName = IDC_ARROW;
  208190. break;
  208191. case MouseCursor::NoCursor:
  208192. return 0;
  208193. case MouseCursor::DraggingHandCursor:
  208194. {
  208195. static void* dragHandCursor = 0;
  208196. if (dragHandCursor == 0)
  208197. {
  208198. static const unsigned char dragHandData[] =
  208199. { 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,
  208200. 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,
  208201. 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 };
  208202. Image* const image = ImageFileFormat::loadFrom ((const char*) dragHandData, sizeof (dragHandData));
  208203. dragHandCursor = juce_createMouseCursorFromImage (*image, 8, 7);
  208204. delete image;
  208205. }
  208206. return dragHandCursor;
  208207. }
  208208. case MouseCursor::WaitCursor:
  208209. cursorName = IDC_WAIT;
  208210. break;
  208211. case MouseCursor::IBeamCursor:
  208212. cursorName = IDC_IBEAM;
  208213. break;
  208214. case MouseCursor::PointingHandCursor:
  208215. cursorName = MAKEINTRESOURCE(32649);
  208216. break;
  208217. case MouseCursor::LeftRightResizeCursor:
  208218. case MouseCursor::LeftEdgeResizeCursor:
  208219. case MouseCursor::RightEdgeResizeCursor:
  208220. cursorName = IDC_SIZEWE;
  208221. break;
  208222. case MouseCursor::UpDownResizeCursor:
  208223. case MouseCursor::TopEdgeResizeCursor:
  208224. case MouseCursor::BottomEdgeResizeCursor:
  208225. cursorName = IDC_SIZENS;
  208226. break;
  208227. case MouseCursor::TopLeftCornerResizeCursor:
  208228. case MouseCursor::BottomRightCornerResizeCursor:
  208229. cursorName = IDC_SIZENWSE;
  208230. break;
  208231. case MouseCursor::TopRightCornerResizeCursor:
  208232. case MouseCursor::BottomLeftCornerResizeCursor:
  208233. cursorName = IDC_SIZENESW;
  208234. break;
  208235. case MouseCursor::UpDownLeftRightResizeCursor:
  208236. cursorName = IDC_SIZEALL;
  208237. break;
  208238. case MouseCursor::CrosshairCursor:
  208239. cursorName = IDC_CROSS;
  208240. break;
  208241. case MouseCursor::CopyingCursor:
  208242. // can't seem to find one of these in the win32 list..
  208243. break;
  208244. }
  208245. HCURSOR cursorH = LoadCursor (0, cursorName);
  208246. if (cursorH == 0)
  208247. cursorH = LoadCursor (0, IDC_ARROW);
  208248. return (void*) cursorH;
  208249. }
  208250. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  208251. {
  208252. SetCursor ((HCURSOR) getHandle());
  208253. }
  208254. void MouseCursor::showInAllWindows() const throw()
  208255. {
  208256. showInWindow (0);
  208257. }
  208258. class JuceDropSource : public IDropSource
  208259. {
  208260. int refCount;
  208261. public:
  208262. JuceDropSource()
  208263. : refCount (1)
  208264. {
  208265. }
  208266. virtual ~JuceDropSource()
  208267. {
  208268. jassert (refCount == 0);
  208269. }
  208270. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208271. {
  208272. if (id == IID_IUnknown || id == IID_IDropSource)
  208273. {
  208274. AddRef();
  208275. *result = this;
  208276. return S_OK;
  208277. }
  208278. *result = 0;
  208279. return E_NOINTERFACE;
  208280. }
  208281. ULONG __stdcall AddRef() { return ++refCount; }
  208282. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  208283. HRESULT __stdcall QueryContinueDrag (BOOL escapePressed, DWORD keys)
  208284. {
  208285. if (escapePressed)
  208286. return DRAGDROP_S_CANCEL;
  208287. if ((keys & (MK_LBUTTON | MK_RBUTTON)) == 0)
  208288. return DRAGDROP_S_DROP;
  208289. return S_OK;
  208290. }
  208291. HRESULT __stdcall GiveFeedback (DWORD)
  208292. {
  208293. return DRAGDROP_S_USEDEFAULTCURSORS;
  208294. }
  208295. };
  208296. class JuceEnumFormatEtc : public IEnumFORMATETC
  208297. {
  208298. public:
  208299. JuceEnumFormatEtc (const FORMATETC* const format_)
  208300. : refCount (1),
  208301. format (format_),
  208302. index (0)
  208303. {
  208304. }
  208305. virtual ~JuceEnumFormatEtc()
  208306. {
  208307. jassert (refCount == 0);
  208308. }
  208309. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208310. {
  208311. if (id == IID_IUnknown || id == IID_IEnumFORMATETC)
  208312. {
  208313. AddRef();
  208314. *result = this;
  208315. return S_OK;
  208316. }
  208317. *result = 0;
  208318. return E_NOINTERFACE;
  208319. }
  208320. ULONG __stdcall AddRef() { return ++refCount; }
  208321. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  208322. HRESULT __stdcall Clone (IEnumFORMATETC** result)
  208323. {
  208324. if (result == 0)
  208325. return E_POINTER;
  208326. JuceEnumFormatEtc* const newOne = new JuceEnumFormatEtc (format);
  208327. newOne->index = index;
  208328. *result = newOne;
  208329. return S_OK;
  208330. }
  208331. HRESULT __stdcall Next (ULONG celt, LPFORMATETC lpFormatEtc, ULONG* pceltFetched)
  208332. {
  208333. if (pceltFetched != 0)
  208334. *pceltFetched = 0;
  208335. else if (celt != 1)
  208336. return S_FALSE;
  208337. if (index == 0 && celt > 0 && lpFormatEtc != 0)
  208338. {
  208339. copyFormatEtc (lpFormatEtc [0], *format);
  208340. ++index;
  208341. if (pceltFetched != 0)
  208342. *pceltFetched = 1;
  208343. return S_OK;
  208344. }
  208345. return S_FALSE;
  208346. }
  208347. HRESULT __stdcall Skip (ULONG celt)
  208348. {
  208349. if (index + (int) celt >= 1)
  208350. return S_FALSE;
  208351. index += celt;
  208352. return S_OK;
  208353. }
  208354. HRESULT __stdcall Reset()
  208355. {
  208356. index = 0;
  208357. return S_OK;
  208358. }
  208359. private:
  208360. int refCount;
  208361. const FORMATETC* const format;
  208362. int index;
  208363. static void copyFormatEtc (FORMATETC& dest, const FORMATETC& source)
  208364. {
  208365. dest = source;
  208366. if (source.ptd != 0)
  208367. {
  208368. dest.ptd = (DVTARGETDEVICE*) CoTaskMemAlloc (sizeof (DVTARGETDEVICE));
  208369. *(dest.ptd) = *(source.ptd);
  208370. }
  208371. }
  208372. JuceEnumFormatEtc (const JuceEnumFormatEtc&);
  208373. const JuceEnumFormatEtc& operator= (const JuceEnumFormatEtc&);
  208374. };
  208375. class JuceDataObject : public IDataObject
  208376. {
  208377. JuceDropSource* const dropSource;
  208378. const FORMATETC* const format;
  208379. const STGMEDIUM* const medium;
  208380. int refCount;
  208381. JuceDataObject (const JuceDataObject&);
  208382. const JuceDataObject& operator= (const JuceDataObject&);
  208383. public:
  208384. JuceDataObject (JuceDropSource* const dropSource_,
  208385. const FORMATETC* const format_,
  208386. const STGMEDIUM* const medium_)
  208387. : dropSource (dropSource_),
  208388. format (format_),
  208389. medium (medium_),
  208390. refCount (1)
  208391. {
  208392. }
  208393. virtual ~JuceDataObject()
  208394. {
  208395. jassert (refCount == 0);
  208396. }
  208397. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  208398. {
  208399. if (id == IID_IUnknown || id == IID_IDataObject)
  208400. {
  208401. AddRef();
  208402. *result = this;
  208403. return S_OK;
  208404. }
  208405. *result = 0;
  208406. return E_NOINTERFACE;
  208407. }
  208408. ULONG __stdcall AddRef() { return ++refCount; }
  208409. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  208410. HRESULT __stdcall GetData (FORMATETC __RPC_FAR* pFormatEtc, STGMEDIUM __RPC_FAR* pMedium)
  208411. {
  208412. if (pFormatEtc->tymed == format->tymed
  208413. && pFormatEtc->cfFormat == format->cfFormat
  208414. && pFormatEtc->dwAspect == format->dwAspect)
  208415. {
  208416. pMedium->tymed = format->tymed;
  208417. pMedium->pUnkForRelease = 0;
  208418. if (format->tymed == TYMED_HGLOBAL)
  208419. {
  208420. const SIZE_T len = GlobalSize (medium->hGlobal);
  208421. void* const src = GlobalLock (medium->hGlobal);
  208422. void* const dst = GlobalAlloc (GMEM_FIXED, len);
  208423. memcpy (dst, src, len);
  208424. GlobalUnlock (medium->hGlobal);
  208425. pMedium->hGlobal = dst;
  208426. return S_OK;
  208427. }
  208428. }
  208429. return DV_E_FORMATETC;
  208430. }
  208431. HRESULT __stdcall QueryGetData (FORMATETC __RPC_FAR* f)
  208432. {
  208433. if (f == 0)
  208434. return E_INVALIDARG;
  208435. if (f->tymed == format->tymed
  208436. && f->cfFormat == format->cfFormat
  208437. && f->dwAspect == format->dwAspect)
  208438. return S_OK;
  208439. return DV_E_FORMATETC;
  208440. }
  208441. HRESULT __stdcall GetCanonicalFormatEtc (FORMATETC __RPC_FAR*, FORMATETC __RPC_FAR* pFormatEtcOut)
  208442. {
  208443. pFormatEtcOut->ptd = 0;
  208444. return E_NOTIMPL;
  208445. }
  208446. HRESULT __stdcall EnumFormatEtc (DWORD direction, IEnumFORMATETC __RPC_FAR *__RPC_FAR *result)
  208447. {
  208448. if (result == 0)
  208449. return E_POINTER;
  208450. if (direction == DATADIR_GET)
  208451. {
  208452. *result = new JuceEnumFormatEtc (format);
  208453. return S_OK;
  208454. }
  208455. *result = 0;
  208456. return E_NOTIMPL;
  208457. }
  208458. HRESULT __stdcall GetDataHere (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*) { return DATA_E_FORMATETC; }
  208459. HRESULT __stdcall SetData (FORMATETC __RPC_FAR*, STGMEDIUM __RPC_FAR*, BOOL) { return E_NOTIMPL; }
  208460. HRESULT __stdcall DAdvise (FORMATETC __RPC_FAR*, DWORD, IAdviseSink __RPC_FAR*, DWORD __RPC_FAR*) { return OLE_E_ADVISENOTSUPPORTED; }
  208461. HRESULT __stdcall DUnadvise (DWORD) { return E_NOTIMPL; }
  208462. HRESULT __stdcall EnumDAdvise (IEnumSTATDATA __RPC_FAR *__RPC_FAR *) { return OLE_E_ADVISENOTSUPPORTED; }
  208463. };
  208464. static HDROP createHDrop (const StringArray& fileNames) throw()
  208465. {
  208466. int totalChars = 0;
  208467. for (int i = fileNames.size(); --i >= 0;)
  208468. totalChars += fileNames[i].length() + 1;
  208469. HDROP hDrop = (HDROP) GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT,
  208470. sizeof (DROPFILES)
  208471. + sizeof (WCHAR) * (totalChars + 2));
  208472. if (hDrop != 0)
  208473. {
  208474. LPDROPFILES pDropFiles = (LPDROPFILES) GlobalLock (hDrop);
  208475. pDropFiles->pFiles = sizeof (DROPFILES);
  208476. pDropFiles->fWide = true;
  208477. WCHAR* fname = (WCHAR*) (((char*) pDropFiles) + sizeof (DROPFILES));
  208478. for (int i = 0; i < fileNames.size(); ++i)
  208479. {
  208480. fileNames[i].copyToBuffer (fname, 2048);
  208481. fname += fileNames[i].length() + 1;
  208482. }
  208483. *fname = 0;
  208484. GlobalUnlock (hDrop);
  208485. }
  208486. return hDrop;
  208487. }
  208488. static bool performDragDrop (FORMATETC* const format, STGMEDIUM* const medium, const DWORD whatToDo) throw()
  208489. {
  208490. JuceDropSource* const source = new JuceDropSource();
  208491. JuceDataObject* const data = new JuceDataObject (source, format, medium);
  208492. DWORD effect;
  208493. const HRESULT res = DoDragDrop (data, source, whatToDo, &effect);
  208494. data->Release();
  208495. source->Release();
  208496. return res == DRAGDROP_S_DROP;
  208497. }
  208498. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMove)
  208499. {
  208500. FORMATETC format = { CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208501. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208502. medium.hGlobal = createHDrop (files);
  208503. return performDragDrop (&format, &medium, canMove ? (DROPEFFECT_COPY | DROPEFFECT_MOVE)
  208504. : DROPEFFECT_COPY);
  208505. }
  208506. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  208507. {
  208508. FORMATETC format = { CF_TEXT, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL };
  208509. STGMEDIUM medium = { TYMED_HGLOBAL, { 0 }, 0 };
  208510. const int numChars = text.length();
  208511. medium.hGlobal = GlobalAlloc (GMEM_MOVEABLE | GMEM_ZEROINIT, (numChars + 2) * sizeof (WCHAR));
  208512. char* d = (char*) GlobalLock (medium.hGlobal);
  208513. text.copyToBuffer ((WCHAR*) d, numChars + 1);
  208514. format.cfFormat = CF_UNICODETEXT;
  208515. GlobalUnlock (medium.hGlobal);
  208516. return performDragDrop (&format, &medium, DROPEFFECT_COPY | DROPEFFECT_MOVE);
  208517. }
  208518. #endif
  208519. /********* End of inlined file: juce_win32_Windowing.cpp *********/
  208520. /********* Start of inlined file: juce_win32_Fonts.cpp *********/
  208521. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208522. // compiled on its own).
  208523. #if JUCE_INCLUDED_FILE
  208524. static int CALLBACK wfontEnum2 (ENUMLOGFONTEXW* lpelfe,
  208525. NEWTEXTMETRICEXW*,
  208526. int type,
  208527. LPARAM lParam)
  208528. {
  208529. if (lpelfe != 0 && type == TRUETYPE_FONTTYPE)
  208530. {
  208531. const String fontName (lpelfe->elfLogFont.lfFaceName);
  208532. ((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters (T("@")));
  208533. }
  208534. return 1;
  208535. }
  208536. static int CALLBACK wfontEnum1 (ENUMLOGFONTEXW* lpelfe,
  208537. NEWTEXTMETRICEXW*,
  208538. int type,
  208539. LPARAM lParam)
  208540. {
  208541. if (lpelfe != 0
  208542. && ((type & (DEVICE_FONTTYPE | RASTER_FONTTYPE)) == 0))
  208543. {
  208544. LOGFONTW lf;
  208545. zerostruct (lf);
  208546. lf.lfWeight = FW_DONTCARE;
  208547. lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
  208548. lf.lfQuality = DEFAULT_QUALITY;
  208549. lf.lfCharSet = DEFAULT_CHARSET;
  208550. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  208551. lf.lfPitchAndFamily = FF_DONTCARE;
  208552. const String fontName (lpelfe->elfLogFont.lfFaceName);
  208553. fontName.copyToBuffer (lf.lfFaceName, LF_FACESIZE - 1);
  208554. HDC dc = CreateCompatibleDC (0);
  208555. EnumFontFamiliesEx (dc, &lf,
  208556. (FONTENUMPROCW) &wfontEnum2,
  208557. lParam, 0);
  208558. DeleteDC (dc);
  208559. }
  208560. return 1;
  208561. }
  208562. const StringArray Font::findAllTypefaceNames() throw()
  208563. {
  208564. StringArray results;
  208565. HDC dc = CreateCompatibleDC (0);
  208566. {
  208567. LOGFONTW lf;
  208568. zerostruct (lf);
  208569. lf.lfWeight = FW_DONTCARE;
  208570. lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
  208571. lf.lfQuality = DEFAULT_QUALITY;
  208572. lf.lfCharSet = DEFAULT_CHARSET;
  208573. lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  208574. lf.lfPitchAndFamily = FF_DONTCARE;
  208575. lf.lfFaceName[0] = 0;
  208576. EnumFontFamiliesEx (dc, &lf,
  208577. (FONTENUMPROCW) &wfontEnum1,
  208578. (LPARAM) &results, 0);
  208579. }
  208580. DeleteDC (dc);
  208581. results.sort (true);
  208582. return results;
  208583. }
  208584. extern bool juce_IsRunningInWine() throw();
  208585. void Font::getDefaultFontNames (String& defaultSans,
  208586. String& defaultSerif,
  208587. String& defaultFixed) throw()
  208588. {
  208589. if (juce_IsRunningInWine())
  208590. {
  208591. // If we're running in Wine, then use fonts that might be available on Linux..
  208592. defaultSans = "Bitstream Vera Sans";
  208593. defaultSerif = "Bitstream Vera Serif";
  208594. defaultFixed = "Bitstream Vera Sans Mono";
  208595. }
  208596. else
  208597. {
  208598. defaultSans = "Verdana";
  208599. defaultSerif = "Times";
  208600. defaultFixed = "Lucida Console";
  208601. }
  208602. }
  208603. class FontDCHolder : private DeletedAtShutdown
  208604. {
  208605. HDC dc;
  208606. String fontName;
  208607. KERNINGPAIR* kps;
  208608. int numKPs;
  208609. bool bold, italic;
  208610. int size;
  208611. FontDCHolder (const FontDCHolder&);
  208612. const FontDCHolder& operator= (const FontDCHolder&);
  208613. public:
  208614. HFONT fontH;
  208615. FontDCHolder() throw()
  208616. : dc (0),
  208617. kps (0),
  208618. numKPs (0),
  208619. bold (false),
  208620. italic (false),
  208621. size (0)
  208622. {
  208623. }
  208624. ~FontDCHolder() throw()
  208625. {
  208626. if (dc != 0)
  208627. {
  208628. DeleteDC (dc);
  208629. DeleteObject (fontH);
  208630. juce_free (kps);
  208631. }
  208632. clearSingletonInstance();
  208633. }
  208634. juce_DeclareSingleton_SingleThreaded_Minimal (FontDCHolder);
  208635. HDC loadFont (const String& fontName_,
  208636. const bool bold_,
  208637. const bool italic_,
  208638. const int size_) throw()
  208639. {
  208640. if (fontName != fontName_ || bold != bold_ || italic != italic_ || size != size_)
  208641. {
  208642. fontName = fontName_;
  208643. bold = bold_;
  208644. italic = italic_;
  208645. size = size_;
  208646. if (dc != 0)
  208647. {
  208648. DeleteDC (dc);
  208649. DeleteObject (fontH);
  208650. juce_free (kps);
  208651. kps = 0;
  208652. }
  208653. fontH = 0;
  208654. dc = CreateCompatibleDC (0);
  208655. SetMapperFlags (dc, 0);
  208656. SetMapMode (dc, MM_TEXT);
  208657. LOGFONTW lfw;
  208658. zerostruct (lfw);
  208659. lfw.lfCharSet = DEFAULT_CHARSET;
  208660. lfw.lfClipPrecision = CLIP_DEFAULT_PRECIS;
  208661. lfw.lfOutPrecision = OUT_OUTLINE_PRECIS;
  208662. lfw.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
  208663. lfw.lfQuality = PROOF_QUALITY;
  208664. lfw.lfItalic = (BYTE) (italic ? TRUE : FALSE);
  208665. lfw.lfWeight = bold ? FW_BOLD : FW_NORMAL;
  208666. fontName.copyToBuffer (lfw.lfFaceName, LF_FACESIZE - 1);
  208667. lfw.lfHeight = size > 0 ? size : -256;
  208668. HFONT standardSizedFont = CreateFontIndirect (&lfw);
  208669. if (standardSizedFont != 0)
  208670. {
  208671. if (SelectObject (dc, standardSizedFont) != 0)
  208672. {
  208673. fontH = standardSizedFont;
  208674. if (size == 0)
  208675. {
  208676. OUTLINETEXTMETRIC otm;
  208677. if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
  208678. {
  208679. lfw.lfHeight = -(int) otm.otmEMSquare;
  208680. fontH = CreateFontIndirect (&lfw);
  208681. SelectObject (dc, fontH);
  208682. DeleteObject (standardSizedFont);
  208683. }
  208684. }
  208685. }
  208686. else
  208687. {
  208688. jassertfalse
  208689. }
  208690. }
  208691. else
  208692. {
  208693. jassertfalse
  208694. }
  208695. }
  208696. return dc;
  208697. }
  208698. KERNINGPAIR* getKerningPairs (int& numKPs_) throw()
  208699. {
  208700. if (kps == 0)
  208701. {
  208702. numKPs = GetKerningPairs (dc, 0, 0);
  208703. kps = (KERNINGPAIR*) juce_calloc (sizeof (KERNINGPAIR) * numKPs);
  208704. GetKerningPairs (dc, numKPs, kps);
  208705. }
  208706. numKPs_ = numKPs;
  208707. return kps;
  208708. }
  208709. };
  208710. juce_ImplementSingleton_SingleThreaded (FontDCHolder);
  208711. static bool addGlyphToTypeface (HDC dc,
  208712. juce_wchar character,
  208713. Typeface& dest,
  208714. bool addKerning)
  208715. {
  208716. Path destShape;
  208717. GLYPHMETRICS gm;
  208718. float height;
  208719. BOOL ok = false;
  208720. {
  208721. const WCHAR charToTest[] = { (WCHAR) character, 0 };
  208722. WORD index = 0;
  208723. if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR
  208724. && index == 0xffff)
  208725. {
  208726. return false;
  208727. }
  208728. }
  208729. TEXTMETRIC tm;
  208730. ok = GetTextMetrics (dc, &tm);
  208731. height = (float) tm.tmHeight;
  208732. if (! ok)
  208733. {
  208734. dest.addGlyph (character, destShape, 0);
  208735. return true;
  208736. }
  208737. const float scaleX = 1.0f / height;
  208738. const float scaleY = -1.0f / height;
  208739. static const MAT2 identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
  208740. const int bufSize = GetGlyphOutline (dc, character, GGO_NATIVE,
  208741. &gm, 0, 0, &identityMatrix);
  208742. if (bufSize > 0)
  208743. {
  208744. char* const data = (char*) juce_malloc (bufSize);
  208745. GetGlyphOutline (dc, character, GGO_NATIVE, &gm,
  208746. bufSize, data, &identityMatrix);
  208747. const TTPOLYGONHEADER* pheader = (TTPOLYGONHEADER*) data;
  208748. while ((char*) pheader < data + bufSize)
  208749. {
  208750. #define remapX(v) (scaleX * (v).x.value)
  208751. #define remapY(v) (scaleY * (v).y.value)
  208752. float x = remapX (pheader->pfxStart);
  208753. float y = remapY (pheader->pfxStart);
  208754. destShape.startNewSubPath (x, y);
  208755. const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
  208756. const char* const curveEnd = ((const char*) pheader) + pheader->cb;
  208757. while ((const char*) curve < curveEnd)
  208758. {
  208759. if (curve->wType == TT_PRIM_LINE)
  208760. {
  208761. for (int i = 0; i < curve->cpfx; ++i)
  208762. {
  208763. x = remapX (curve->apfx [i]);
  208764. y = remapY (curve->apfx [i]);
  208765. destShape.lineTo (x, y);
  208766. }
  208767. }
  208768. else if (curve->wType == TT_PRIM_QSPLINE)
  208769. {
  208770. for (int i = 0; i < curve->cpfx - 1; ++i)
  208771. {
  208772. const float x2 = remapX (curve->apfx [i]);
  208773. const float y2 = remapY (curve->apfx [i]);
  208774. float x3, y3;
  208775. if (i < curve->cpfx - 2)
  208776. {
  208777. x3 = 0.5f * (x2 + remapX (curve->apfx [i + 1]));
  208778. y3 = 0.5f * (y2 + remapY (curve->apfx [i + 1]));
  208779. }
  208780. else
  208781. {
  208782. x3 = remapX (curve->apfx [i + 1]);
  208783. y3 = remapY (curve->apfx [i + 1]);
  208784. }
  208785. destShape.quadraticTo (x2, y2, x3, y3);
  208786. x = x3;
  208787. y = y3;
  208788. }
  208789. }
  208790. curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
  208791. }
  208792. pheader = (const TTPOLYGONHEADER*) curve;
  208793. destShape.closeSubPath();
  208794. }
  208795. juce_free (data);
  208796. }
  208797. dest.addGlyph (character, destShape, gm.gmCellIncX / height);
  208798. if (addKerning)
  208799. {
  208800. int numKPs;
  208801. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  208802. for (int i = 0; i < numKPs; ++i)
  208803. {
  208804. if (kps[i].wFirst == character)
  208805. {
  208806. dest.addKerningPair (kps[i].wFirst,
  208807. kps[i].wSecond,
  208808. kps[i].iKernAmount / height);
  208809. }
  208810. }
  208811. }
  208812. return true;
  208813. }
  208814. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  208815. {
  208816. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), 0);
  208817. return addGlyphToTypeface (dc, character, *this, true);
  208818. }
  208819. /*Image* Typeface::renderGlyphToImage (juce_wchar character, float& topLeftX, float& topLeftY)
  208820. {
  208821. HDC dc = FontDCHolder::getInstance()->loadFont (getName(), isBold(), isItalic(), hintingSize);
  208822. int bufSize;
  208823. GLYPHMETRICS gm;
  208824. const UINT format = GGO_GRAY2_BITMAP;
  208825. const int shift = 6;
  208826. if (wGetGlyphOutlineW != 0)
  208827. bufSize = wGetGlyphOutlineW (dc, character, format, &gm, 0, 0, &identityMatrix);
  208828. else
  208829. bufSize = GetGlyphOutline (dc, character, format, &gm, 0, 0, &identityMatrix);
  208830. Image* im = new Image (Image::SingleChannel, jmax (1, gm.gmBlackBoxX), jmax (1, gm.gmBlackBoxY), true);
  208831. if (bufSize > 0)
  208832. {
  208833. topLeftX = (float) gm.gmptGlyphOrigin.x;
  208834. topLeftY = (float) -gm.gmptGlyphOrigin.y;
  208835. uint8* const data = (uint8*) juce_calloc (bufSize);
  208836. if (wGetGlyphOutlineW != 0)
  208837. wGetGlyphOutlineW (dc, character, format, &gm, bufSize, data, &identityMatrix);
  208838. else
  208839. GetGlyphOutline (dc, character, format, &gm, bufSize, data, &identityMatrix);
  208840. const int stride = ((gm.gmBlackBoxX + 3) & ~3);
  208841. for (int y = gm.gmBlackBoxY; --y >= 0;)
  208842. {
  208843. for (int x = gm.gmBlackBoxX; --x >= 0;)
  208844. {
  208845. const int level = data [x + y * stride] << shift;
  208846. if (level > 0)
  208847. im->setPixelAt (x, y, Colour ((uint8) 0xff, (uint8) 0xff, (uint8) 0xff, (uint8) jmin (0xff, level)));
  208848. }
  208849. }
  208850. juce_free (data);
  208851. }
  208852. return im;
  208853. }*/
  208854. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  208855. bool bold,
  208856. bool italic,
  208857. bool addAllGlyphsToFont) throw()
  208858. {
  208859. clear();
  208860. HDC dc = FontDCHolder::getInstance()->loadFont (fontName, bold, italic, 0);
  208861. float height;
  208862. int firstChar, lastChar;
  208863. {
  208864. TEXTMETRIC tm;
  208865. GetTextMetrics (dc, &tm);
  208866. height = (float) tm.tmHeight;
  208867. firstChar = tm.tmFirstChar;
  208868. lastChar = tm.tmLastChar;
  208869. setAscent (tm.tmAscent / height);
  208870. setDefaultCharacter (tm.tmDefaultChar);
  208871. }
  208872. setName (fontName);
  208873. setBold (bold);
  208874. setItalic (italic);
  208875. if (addAllGlyphsToFont)
  208876. {
  208877. for (int character = firstChar; character <= lastChar; ++character)
  208878. addGlyphToTypeface (dc, (juce_wchar) character, *this, false);
  208879. int numKPs;
  208880. const KERNINGPAIR* const kps = FontDCHolder::getInstance()->getKerningPairs (numKPs);
  208881. for (int i = 0; i < numKPs; ++i)
  208882. {
  208883. addKerningPair (kps[i].wFirst,
  208884. kps[i].wSecond,
  208885. kps[i].iKernAmount / height);
  208886. }
  208887. }
  208888. }
  208889. #endif
  208890. /********* End of inlined file: juce_win32_Fonts.cpp *********/
  208891. /********* Start of inlined file: juce_win32_FileChooser.cpp *********/
  208892. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  208893. // compiled on its own).
  208894. #if JUCE_INCLUDED_FILE
  208895. static const void* defaultDirPath = 0;
  208896. static String returnedString; // need this to get non-existent pathnames from the directory chooser
  208897. static Component* currentExtraFileWin = 0;
  208898. static bool areThereAnyAlwaysOnTopWindows()
  208899. {
  208900. for (int i = Desktop::getInstance().getNumComponents(); --i >= 0;)
  208901. {
  208902. Component* c = Desktop::getInstance().getComponent (i);
  208903. if (c != 0 && c->isAlwaysOnTop() && c->isShowing())
  208904. return true;
  208905. }
  208906. return false;
  208907. }
  208908. static int CALLBACK browseCallbackProc (HWND hWnd, UINT msg, LPARAM lParam, LPARAM /*lpData*/)
  208909. {
  208910. if (msg == BFFM_INITIALIZED)
  208911. {
  208912. SendMessage (hWnd, BFFM_SETSELECTIONW, TRUE, (LPARAM) defaultDirPath);
  208913. }
  208914. else if (msg == BFFM_VALIDATEFAILEDW)
  208915. {
  208916. returnedString = (LPCWSTR) lParam;
  208917. }
  208918. else if (msg == BFFM_VALIDATEFAILEDA)
  208919. {
  208920. returnedString = (const char*) lParam;
  208921. }
  208922. return 0;
  208923. }
  208924. void juce_setWindowStyleBit (HWND h, int styleType, int feature, bool bitIsSet);
  208925. static UINT_PTR CALLBACK openCallback (HWND hdlg, UINT uiMsg, WPARAM /*wParam*/, LPARAM lParam)
  208926. {
  208927. if (currentExtraFileWin != 0)
  208928. {
  208929. if (uiMsg == WM_INITDIALOG)
  208930. {
  208931. HWND dialogH = GetParent (hdlg);
  208932. jassert (dialogH != 0);
  208933. if (dialogH == 0)
  208934. dialogH = hdlg;
  208935. RECT r, cr;
  208936. GetWindowRect (dialogH, &r);
  208937. GetClientRect (dialogH, &cr);
  208938. SetWindowPos (dialogH, 0,
  208939. r.left, r.top,
  208940. currentExtraFileWin->getWidth() + jmax (150, r.right - r.left),
  208941. jmax (150, r.bottom - r.top),
  208942. SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
  208943. currentExtraFileWin->setBounds (cr.right, cr.top, currentExtraFileWin->getWidth(), cr.bottom - cr.top);
  208944. currentExtraFileWin->getChildComponent(0)->setBounds (0, 0, currentExtraFileWin->getWidth(), currentExtraFileWin->getHeight());
  208945. SetParent ((HWND) currentExtraFileWin->getWindowHandle(), (HWND) dialogH);
  208946. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_CHILD, (dialogH != 0));
  208947. juce_setWindowStyleBit ((HWND)currentExtraFileWin->getWindowHandle(), GWL_STYLE, WS_POPUP, (dialogH == 0));
  208948. }
  208949. else if (uiMsg == WM_NOTIFY)
  208950. {
  208951. LPOFNOTIFY ofn = (LPOFNOTIFY) lParam;
  208952. if (ofn->hdr.code == CDN_SELCHANGE)
  208953. {
  208954. FilePreviewComponent* comp = (FilePreviewComponent*) currentExtraFileWin->getChildComponent(0);
  208955. if (comp != 0)
  208956. {
  208957. TCHAR path [MAX_PATH * 2];
  208958. path[0] = 0;
  208959. CommDlg_OpenSave_GetFilePath (GetParent (hdlg), (LPARAM) &path, MAX_PATH);
  208960. const String fn ((const WCHAR*) path);
  208961. comp->selectedFileChanged (File (fn));
  208962. }
  208963. }
  208964. }
  208965. }
  208966. return 0;
  208967. }
  208968. class FPComponentHolder : public Component
  208969. {
  208970. public:
  208971. FPComponentHolder()
  208972. {
  208973. setVisible (true);
  208974. setOpaque (true);
  208975. }
  208976. ~FPComponentHolder()
  208977. {
  208978. }
  208979. void paint (Graphics& g)
  208980. {
  208981. g.fillAll (Colours::lightgrey);
  208982. }
  208983. private:
  208984. FPComponentHolder (const FPComponentHolder&);
  208985. const FPComponentHolder& operator= (const FPComponentHolder&);
  208986. };
  208987. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  208988. const String& title,
  208989. const File& currentFileOrDirectory,
  208990. const String& filter,
  208991. bool selectsDirectory,
  208992. bool isSaveDialogue,
  208993. bool warnAboutOverwritingExistingFiles,
  208994. bool selectMultipleFiles,
  208995. FilePreviewComponent* extraInfoComponent)
  208996. {
  208997. const int numCharsAvailable = 32768;
  208998. MemoryBlock filenameSpace ((numCharsAvailable + 1) * sizeof (WCHAR), true);
  208999. WCHAR* const fname = (WCHAR*) filenameSpace.getData();
  209000. int fnameIdx = 0;
  209001. JUCE_TRY
  209002. {
  209003. // use a modal window as the parent for this dialog box
  209004. // to block input from other app windows
  209005. const Rectangle mainMon (Desktop::getInstance().getMainMonitorArea());
  209006. Component w (String::empty);
  209007. w.setBounds (mainMon.getX() + mainMon.getWidth() / 4,
  209008. mainMon.getY() + mainMon.getHeight() / 4,
  209009. 0, 0);
  209010. w.setOpaque (true);
  209011. w.setAlwaysOnTop (areThereAnyAlwaysOnTopWindows());
  209012. w.addToDesktop (0);
  209013. if (extraInfoComponent == 0)
  209014. w.enterModalState();
  209015. String initialDir;
  209016. if (currentFileOrDirectory.isDirectory())
  209017. {
  209018. initialDir = currentFileOrDirectory.getFullPathName();
  209019. }
  209020. else
  209021. {
  209022. currentFileOrDirectory.getFileName().copyToBuffer (fname, numCharsAvailable);
  209023. initialDir = currentFileOrDirectory.getParentDirectory().getFullPathName();
  209024. }
  209025. if (currentExtraFileWin->isValidComponent())
  209026. {
  209027. jassertfalse
  209028. return;
  209029. }
  209030. if (selectsDirectory)
  209031. {
  209032. LPITEMIDLIST list = 0;
  209033. filenameSpace.fillWith (0);
  209034. {
  209035. BROWSEINFO bi;
  209036. zerostruct (bi);
  209037. bi.hwndOwner = (HWND) w.getWindowHandle();
  209038. bi.pszDisplayName = fname;
  209039. bi.lpszTitle = title;
  209040. bi.lpfn = browseCallbackProc;
  209041. #ifdef BIF_USENEWUI
  209042. bi.ulFlags = BIF_USENEWUI | BIF_VALIDATE;
  209043. #else
  209044. bi.ulFlags = 0x50;
  209045. #endif
  209046. defaultDirPath = (const WCHAR*) initialDir;
  209047. list = SHBrowseForFolder (&bi);
  209048. if (! SHGetPathFromIDListW (list, fname))
  209049. {
  209050. fname[0] = 0;
  209051. returnedString = String::empty;
  209052. }
  209053. }
  209054. LPMALLOC al;
  209055. if (list != 0 && SUCCEEDED (SHGetMalloc (&al)))
  209056. al->Free (list);
  209057. defaultDirPath = 0;
  209058. if (returnedString.isNotEmpty())
  209059. {
  209060. const String stringFName (fname);
  209061. results.add (new File (File (stringFName).getSiblingFile (returnedString)));
  209062. returnedString = String::empty;
  209063. return;
  209064. }
  209065. }
  209066. else
  209067. {
  209068. DWORD flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY;
  209069. if (warnAboutOverwritingExistingFiles)
  209070. flags |= OFN_OVERWRITEPROMPT;
  209071. if (selectMultipleFiles)
  209072. flags |= OFN_ALLOWMULTISELECT;
  209073. if (extraInfoComponent != 0)
  209074. {
  209075. flags |= OFN_ENABLEHOOK;
  209076. currentExtraFileWin = new FPComponentHolder();
  209077. currentExtraFileWin->addAndMakeVisible (extraInfoComponent);
  209078. currentExtraFileWin->setSize (jlimit (20, 800, extraInfoComponent->getWidth()),
  209079. extraInfoComponent->getHeight());
  209080. currentExtraFileWin->addToDesktop (0);
  209081. currentExtraFileWin->enterModalState();
  209082. }
  209083. {
  209084. WCHAR filters [1024];
  209085. zeromem (filters, sizeof (filters));
  209086. filter.copyToBuffer (filters, 1024);
  209087. filter.copyToBuffer (filters + filter.length() + 1,
  209088. 1022 - filter.length());
  209089. OPENFILENAMEW of;
  209090. zerostruct (of);
  209091. #ifdef OPENFILENAME_SIZE_VERSION_400W
  209092. of.lStructSize = OPENFILENAME_SIZE_VERSION_400W;
  209093. #else
  209094. of.lStructSize = sizeof (of);
  209095. #endif
  209096. of.hwndOwner = (HWND) w.getWindowHandle();
  209097. of.lpstrFilter = filters;
  209098. of.nFilterIndex = 1;
  209099. of.lpstrFile = fname;
  209100. of.nMaxFile = numCharsAvailable;
  209101. of.lpstrInitialDir = initialDir;
  209102. of.lpstrTitle = title;
  209103. of.Flags = flags;
  209104. if (extraInfoComponent != 0)
  209105. of.lpfnHook = &openCallback;
  209106. if (isSaveDialogue)
  209107. {
  209108. if (! GetSaveFileName (&of))
  209109. fname[0] = 0;
  209110. else
  209111. fnameIdx = of.nFileOffset;
  209112. }
  209113. else
  209114. {
  209115. if (! GetOpenFileName (&of))
  209116. fname[0] = 0;
  209117. else
  209118. fnameIdx = of.nFileOffset;
  209119. }
  209120. }
  209121. }
  209122. }
  209123. #if JUCE_CATCH_UNHANDLED_EXCEPTIONS
  209124. catch (...)
  209125. {
  209126. fname[0] = 0;
  209127. }
  209128. #endif
  209129. deleteAndZero (currentExtraFileWin);
  209130. const WCHAR* const files = fname;
  209131. if (selectMultipleFiles && fnameIdx > 0 && files [fnameIdx - 1] == 0)
  209132. {
  209133. const WCHAR* filename = files + fnameIdx;
  209134. while (*filename != 0)
  209135. {
  209136. const String filepath (String (files) + T("\\") + String (filename));
  209137. results.add (new File (filepath));
  209138. filename += CharacterFunctions::length (filename) + 1;
  209139. }
  209140. }
  209141. else if (files[0] != 0)
  209142. {
  209143. results.add (new File (files));
  209144. }
  209145. }
  209146. #endif
  209147. /********* End of inlined file: juce_win32_FileChooser.cpp *********/
  209148. /********* Start of inlined file: juce_win32_Misc.cpp *********/
  209149. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209150. // compiled on its own).
  209151. #if JUCE_INCLUDED_FILE
  209152. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  209153. {
  209154. if (OpenClipboard (0) != 0)
  209155. {
  209156. if (EmptyClipboard() != 0)
  209157. {
  209158. const int len = text.length();
  209159. if (len > 0)
  209160. {
  209161. HGLOBAL bufH = GlobalAlloc (GMEM_MOVEABLE | GMEM_DDESHARE,
  209162. (len + 1) * sizeof (wchar_t));
  209163. if (bufH != 0)
  209164. {
  209165. wchar_t* const data = (wchar_t*) GlobalLock (bufH);
  209166. text.copyToBuffer (data, len);
  209167. GlobalUnlock (bufH);
  209168. SetClipboardData (CF_UNICODETEXT, bufH);
  209169. }
  209170. }
  209171. }
  209172. CloseClipboard();
  209173. }
  209174. }
  209175. const String SystemClipboard::getTextFromClipboard() throw()
  209176. {
  209177. String result;
  209178. if (OpenClipboard (0) != 0)
  209179. {
  209180. HANDLE bufH = GetClipboardData (CF_UNICODETEXT);
  209181. if (bufH != 0)
  209182. {
  209183. const wchar_t* const data = (const wchar_t*) GlobalLock (bufH);
  209184. if (data != 0)
  209185. {
  209186. result = String (data, (int) (GlobalSize (bufH) / sizeof (tchar)));
  209187. GlobalUnlock (bufH);
  209188. }
  209189. }
  209190. CloseClipboard();
  209191. }
  209192. return result;
  209193. }
  209194. #endif
  209195. /********* End of inlined file: juce_win32_Misc.cpp *********/
  209196. /********* Start of inlined file: juce_win32_ActiveXComponent.cpp *********/
  209197. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209198. // compiled on its own).
  209199. #if JUCE_INCLUDED_FILE
  209200. class JuceIStorage : public IStorage
  209201. {
  209202. int refCount;
  209203. public:
  209204. JuceIStorage() : refCount (1) {}
  209205. virtual ~JuceIStorage()
  209206. {
  209207. jassert (refCount == 0);
  209208. }
  209209. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  209210. {
  209211. if (id == IID_IUnknown || id == IID_IStorage)
  209212. {
  209213. AddRef();
  209214. *result = this;
  209215. return S_OK;
  209216. }
  209217. *result = 0;
  209218. return E_NOINTERFACE;
  209219. }
  209220. ULONG __stdcall AddRef() { return ++refCount; }
  209221. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  209222. HRESULT __stdcall CreateStream (const WCHAR*, DWORD, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209223. HRESULT __stdcall OpenStream (const WCHAR*, void*, DWORD, DWORD, IStream**) { return E_NOTIMPL; }
  209224. HRESULT __stdcall CreateStorage (const WCHAR*, DWORD, DWORD, DWORD, IStorage**) { return E_NOTIMPL; }
  209225. HRESULT __stdcall OpenStorage (const WCHAR*, IStorage*, DWORD, SNB, DWORD, IStorage**) { return E_NOTIMPL; }
  209226. HRESULT __stdcall CopyTo (DWORD, IID const*, SNB, IStorage*) { return E_NOTIMPL; }
  209227. HRESULT __stdcall MoveElementTo (const OLECHAR*,IStorage*, const OLECHAR*, DWORD) { return E_NOTIMPL; }
  209228. HRESULT __stdcall Commit (DWORD) { return E_NOTIMPL; }
  209229. HRESULT __stdcall Revert() { return E_NOTIMPL; }
  209230. HRESULT __stdcall EnumElements (DWORD, void*, DWORD, IEnumSTATSTG**) { return E_NOTIMPL; }
  209231. HRESULT __stdcall DestroyElement (const OLECHAR*) { return E_NOTIMPL; }
  209232. HRESULT __stdcall RenameElement (const WCHAR*, const WCHAR*) { return E_NOTIMPL; }
  209233. HRESULT __stdcall SetElementTimes (const WCHAR*, FILETIME const*, FILETIME const*, FILETIME const*) { return E_NOTIMPL; }
  209234. HRESULT __stdcall SetClass (REFCLSID) { return S_OK; }
  209235. HRESULT __stdcall SetStateBits (DWORD, DWORD) { return E_NOTIMPL; }
  209236. HRESULT __stdcall Stat (STATSTG*, DWORD) { return E_NOTIMPL; }
  209237. juce_UseDebuggingNewOperator
  209238. };
  209239. class JuceOleInPlaceFrame : public IOleInPlaceFrame
  209240. {
  209241. int refCount;
  209242. HWND window;
  209243. public:
  209244. JuceOleInPlaceFrame (HWND window_)
  209245. : refCount (1),
  209246. window (window_)
  209247. {
  209248. }
  209249. virtual ~JuceOleInPlaceFrame()
  209250. {
  209251. jassert (refCount == 0);
  209252. }
  209253. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  209254. {
  209255. if (id == IID_IUnknown || id == IID_IOleInPlaceFrame)
  209256. {
  209257. AddRef();
  209258. *result = this;
  209259. return S_OK;
  209260. }
  209261. *result = 0;
  209262. return E_NOINTERFACE;
  209263. }
  209264. ULONG __stdcall AddRef() { return ++refCount; }
  209265. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  209266. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209267. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209268. HRESULT __stdcall GetBorder (LPRECT) { return E_NOTIMPL; }
  209269. HRESULT __stdcall RequestBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209270. HRESULT __stdcall SetBorderSpace (LPCBORDERWIDTHS) { return E_NOTIMPL; }
  209271. HRESULT __stdcall SetActiveObject (IOleInPlaceActiveObject*, LPCOLESTR) { return S_OK; }
  209272. HRESULT __stdcall InsertMenus (HMENU, LPOLEMENUGROUPWIDTHS) { return E_NOTIMPL; }
  209273. HRESULT __stdcall SetMenu (HMENU, HOLEMENU, HWND) { return S_OK; }
  209274. HRESULT __stdcall RemoveMenus (HMENU) { return E_NOTIMPL; }
  209275. HRESULT __stdcall SetStatusText (LPCOLESTR) { return S_OK; }
  209276. HRESULT __stdcall EnableModeless (BOOL) { return S_OK; }
  209277. HRESULT __stdcall TranslateAccelerator(LPMSG, WORD) { return E_NOTIMPL; }
  209278. juce_UseDebuggingNewOperator
  209279. };
  209280. class JuceIOleInPlaceSite : public IOleInPlaceSite
  209281. {
  209282. int refCount;
  209283. HWND window;
  209284. JuceOleInPlaceFrame* frame;
  209285. public:
  209286. JuceIOleInPlaceSite (HWND window_)
  209287. : refCount (1),
  209288. window (window_)
  209289. {
  209290. frame = new JuceOleInPlaceFrame (window);
  209291. }
  209292. virtual ~JuceIOleInPlaceSite()
  209293. {
  209294. jassert (refCount == 0);
  209295. frame->Release();
  209296. }
  209297. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  209298. {
  209299. if (id == IID_IUnknown || id == IID_IOleInPlaceSite)
  209300. {
  209301. AddRef();
  209302. *result = this;
  209303. return S_OK;
  209304. }
  209305. *result = 0;
  209306. return E_NOINTERFACE;
  209307. }
  209308. ULONG __stdcall AddRef() { return ++refCount; }
  209309. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  209310. HRESULT __stdcall GetWindow (HWND* lphwnd) { *lphwnd = window; return S_OK; }
  209311. HRESULT __stdcall ContextSensitiveHelp (BOOL) { return E_NOTIMPL; }
  209312. HRESULT __stdcall CanInPlaceActivate() { return S_OK; }
  209313. HRESULT __stdcall OnInPlaceActivate() { return S_OK; }
  209314. HRESULT __stdcall OnUIActivate() { return S_OK; }
  209315. HRESULT __stdcall GetWindowContext (LPOLEINPLACEFRAME* lplpFrame, LPOLEINPLACEUIWINDOW* lplpDoc, LPRECT, LPRECT, LPOLEINPLACEFRAMEINFO lpFrameInfo)
  209316. {
  209317. frame->AddRef();
  209318. *lplpFrame = frame;
  209319. *lplpDoc = 0;
  209320. lpFrameInfo->fMDIApp = FALSE;
  209321. lpFrameInfo->hwndFrame = window;
  209322. lpFrameInfo->haccel = 0;
  209323. lpFrameInfo->cAccelEntries = 0;
  209324. return S_OK;
  209325. }
  209326. HRESULT __stdcall Scroll (SIZE) { return E_NOTIMPL; }
  209327. HRESULT __stdcall OnUIDeactivate (BOOL) { return S_OK; }
  209328. HRESULT __stdcall OnInPlaceDeactivate() { return S_OK; }
  209329. HRESULT __stdcall DiscardUndoState() { return E_NOTIMPL; }
  209330. HRESULT __stdcall DeactivateAndUndo() { return E_NOTIMPL; }
  209331. HRESULT __stdcall OnPosRectChange (LPCRECT) { return S_OK; }
  209332. juce_UseDebuggingNewOperator
  209333. };
  209334. class JuceIOleClientSite : public IOleClientSite
  209335. {
  209336. int refCount;
  209337. JuceIOleInPlaceSite* inplaceSite;
  209338. public:
  209339. JuceIOleClientSite (HWND window)
  209340. : refCount (1)
  209341. {
  209342. inplaceSite = new JuceIOleInPlaceSite (window);
  209343. }
  209344. virtual ~JuceIOleClientSite()
  209345. {
  209346. jassert (refCount == 0);
  209347. inplaceSite->Release();
  209348. }
  209349. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  209350. {
  209351. if (id == IID_IUnknown || id == IID_IOleClientSite)
  209352. {
  209353. AddRef();
  209354. *result = this;
  209355. return S_OK;
  209356. }
  209357. else if (id == IID_IOleInPlaceSite)
  209358. {
  209359. inplaceSite->AddRef();
  209360. *result = inplaceSite;
  209361. return S_OK;
  209362. }
  209363. *result = 0;
  209364. return E_NOINTERFACE;
  209365. }
  209366. ULONG __stdcall AddRef() { return ++refCount; }
  209367. ULONG __stdcall Release() { const int r = --refCount; if (r == 0) delete this; return r; }
  209368. HRESULT __stdcall SaveObject() { return E_NOTIMPL; }
  209369. HRESULT __stdcall GetMoniker (DWORD, DWORD, IMoniker**) { return E_NOTIMPL; }
  209370. HRESULT __stdcall GetContainer (LPOLECONTAINER* ppContainer) { *ppContainer = 0; return E_NOINTERFACE; }
  209371. HRESULT __stdcall ShowObject() { return S_OK; }
  209372. HRESULT __stdcall OnShowWindow (BOOL) { return E_NOTIMPL; }
  209373. HRESULT __stdcall RequestNewObjectLayout() { return E_NOTIMPL; }
  209374. juce_UseDebuggingNewOperator
  209375. };
  209376. class ActiveXControlData : public ComponentMovementWatcher
  209377. {
  209378. ActiveXControlComponent* const owner;
  209379. bool wasShowing;
  209380. public:
  209381. HWND controlHWND;
  209382. IStorage* storage;
  209383. IOleClientSite* clientSite;
  209384. IOleObject* control;
  209385. ActiveXControlData (HWND hwnd,
  209386. ActiveXControlComponent* const owner_)
  209387. : ComponentMovementWatcher (owner_),
  209388. owner (owner_),
  209389. wasShowing (owner_ != 0 && owner_->isShowing()),
  209390. controlHWND (0),
  209391. storage (new JuceIStorage()),
  209392. clientSite (new JuceIOleClientSite (hwnd)),
  209393. control (0)
  209394. {
  209395. }
  209396. ~ActiveXControlData()
  209397. {
  209398. if (control != 0)
  209399. {
  209400. control->Close (OLECLOSE_NOSAVE);
  209401. control->Release();
  209402. }
  209403. clientSite->Release();
  209404. storage->Release();
  209405. }
  209406. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  209407. {
  209408. Component* const topComp = owner->getTopLevelComponent();
  209409. if (topComp->getPeer() != 0)
  209410. {
  209411. int x = 0, y = 0;
  209412. owner->relativePositionToOtherComponent (topComp, x, y);
  209413. owner->setControlBounds (Rectangle (x, y, owner->getWidth(), owner->getHeight()));
  209414. }
  209415. }
  209416. void componentPeerChanged()
  209417. {
  209418. const bool isShowingNow = owner->isShowing();
  209419. if (wasShowing != isShowingNow)
  209420. {
  209421. wasShowing = isShowingNow;
  209422. owner->setControlVisible (isShowingNow);
  209423. }
  209424. }
  209425. void componentVisibilityChanged (Component&)
  209426. {
  209427. componentPeerChanged();
  209428. }
  209429. static bool doesWindowMatch (const ActiveXControlComponent* const ax, HWND hwnd)
  209430. {
  209431. return ((ActiveXControlData*) ax->control) != 0
  209432. && ((ActiveXControlData*) ax->control)->controlHWND == hwnd;
  209433. }
  209434. };
  209435. static VoidArray activeXComps;
  209436. static HWND getHWND (const ActiveXControlComponent* const component)
  209437. {
  209438. HWND hwnd = 0;
  209439. const IID iid = IID_IOleWindow;
  209440. IOleWindow* const window = (IOleWindow*) component->queryInterface (&iid);
  209441. if (window != 0)
  209442. {
  209443. window->GetWindow (&hwnd);
  209444. window->Release();
  209445. }
  209446. return hwnd;
  209447. }
  209448. static void offerActiveXMouseEventToPeer (ComponentPeer* const peer, HWND hwnd, UINT message, LPARAM lParam)
  209449. {
  209450. RECT activeXRect, peerRect;
  209451. GetWindowRect (hwnd, &activeXRect);
  209452. GetWindowRect ((HWND) peer->getNativeHandle(), &peerRect);
  209453. const int mx = GET_X_LPARAM (lParam) + activeXRect.left - peerRect.left;
  209454. const int my = GET_Y_LPARAM (lParam) + activeXRect.top - peerRect.top;
  209455. const int64 mouseEventTime = getMouseEventTime();
  209456. const int oldModifiers = currentModifiers;
  209457. ModifierKeys::getCurrentModifiersRealtime(); // to update the mouse button flags
  209458. switch (message)
  209459. {
  209460. case WM_MOUSEMOVE:
  209461. if (ModifierKeys (currentModifiers).isAnyMouseButtonDown())
  209462. peer->handleMouseDrag (mx, my, mouseEventTime);
  209463. else
  209464. peer->handleMouseMove (mx, my, mouseEventTime);
  209465. break;
  209466. case WM_LBUTTONDOWN:
  209467. case WM_MBUTTONDOWN:
  209468. case WM_RBUTTONDOWN:
  209469. peer->handleMouseDown (mx, my, mouseEventTime);
  209470. break;
  209471. case WM_LBUTTONUP:
  209472. case WM_MBUTTONUP:
  209473. case WM_RBUTTONUP:
  209474. peer->handleMouseUp (oldModifiers, mx, my, mouseEventTime);
  209475. break;
  209476. default:
  209477. break;
  209478. }
  209479. }
  209480. // intercepts events going to an activeX control, so we can sneakily use the mouse events
  209481. static LRESULT CALLBACK activeXHookWndProc (HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
  209482. {
  209483. for (int i = activeXComps.size(); --i >= 0;)
  209484. {
  209485. const ActiveXControlComponent* const ax = (const ActiveXControlComponent*) activeXComps.getUnchecked(i);
  209486. if (ActiveXControlData::doesWindowMatch (ax, hwnd))
  209487. {
  209488. switch (message)
  209489. {
  209490. case WM_MOUSEMOVE:
  209491. case WM_LBUTTONDOWN:
  209492. case WM_MBUTTONDOWN:
  209493. case WM_RBUTTONDOWN:
  209494. case WM_LBUTTONUP:
  209495. case WM_MBUTTONUP:
  209496. case WM_RBUTTONUP:
  209497. case WM_LBUTTONDBLCLK:
  209498. case WM_MBUTTONDBLCLK:
  209499. case WM_RBUTTONDBLCLK:
  209500. if (ax->isShowing())
  209501. {
  209502. ComponentPeer* const peer = ax->getPeer();
  209503. if (peer != 0)
  209504. {
  209505. offerActiveXMouseEventToPeer (peer, hwnd, message, lParam);
  209506. if (! ax->areMouseEventsAllowed())
  209507. return 0;
  209508. }
  209509. }
  209510. break;
  209511. default:
  209512. break;
  209513. }
  209514. return CallWindowProc ((WNDPROC) (ax->originalWndProc), hwnd, message, wParam, lParam);
  209515. }
  209516. }
  209517. return DefWindowProc (hwnd, message, wParam, lParam);
  209518. }
  209519. ActiveXControlComponent::ActiveXControlComponent()
  209520. : originalWndProc (0),
  209521. control (0),
  209522. mouseEventsAllowed (true)
  209523. {
  209524. activeXComps.add (this);
  209525. }
  209526. ActiveXControlComponent::~ActiveXControlComponent()
  209527. {
  209528. deleteControl();
  209529. activeXComps.removeValue (this);
  209530. }
  209531. void ActiveXControlComponent::paint (Graphics& g)
  209532. {
  209533. if (control == 0)
  209534. g.fillAll (Colours::lightgrey);
  209535. }
  209536. bool ActiveXControlComponent::createControl (const void* controlIID)
  209537. {
  209538. deleteControl();
  209539. ComponentPeer* const peer = getPeer();
  209540. // the component must have already been added to a real window when you call this!
  209541. jassert (dynamic_cast <Win32ComponentPeer*> (peer) != 0);
  209542. if (dynamic_cast <Win32ComponentPeer*> (peer) != 0)
  209543. {
  209544. int x = 0, y = 0;
  209545. relativePositionToOtherComponent (getTopLevelComponent(), x, y);
  209546. HWND hwnd = (HWND) peer->getNativeHandle();
  209547. ActiveXControlData* const info = new ActiveXControlData (hwnd, this);
  209548. HRESULT hr;
  209549. if ((hr = OleCreate (*(const IID*) controlIID, IID_IOleObject, 1 /*OLERENDER_DRAW*/, 0,
  209550. info->clientSite, info->storage,
  209551. (void**) &(info->control))) == S_OK)
  209552. {
  209553. info->control->SetHostNames (L"Juce", 0);
  209554. if (OleSetContainedObject (info->control, TRUE) == S_OK)
  209555. {
  209556. RECT rect;
  209557. rect.left = x;
  209558. rect.top = y;
  209559. rect.right = x + getWidth();
  209560. rect.bottom = y + getHeight();
  209561. if (info->control->DoVerb (OLEIVERB_SHOW, 0, info->clientSite, 0, hwnd, &rect) == S_OK)
  209562. {
  209563. control = info;
  209564. setControlBounds (Rectangle (x, y, getWidth(), getHeight()));
  209565. info->controlHWND = getHWND (this);
  209566. if (info->controlHWND != 0)
  209567. {
  209568. originalWndProc = (void*) GetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC);
  209569. SetWindowLongPtr ((HWND) info->controlHWND, GWLP_WNDPROC, (LONG_PTR) activeXHookWndProc);
  209570. }
  209571. return true;
  209572. }
  209573. }
  209574. }
  209575. delete info;
  209576. }
  209577. return false;
  209578. }
  209579. void ActiveXControlComponent::deleteControl()
  209580. {
  209581. ActiveXControlData* const info = (ActiveXControlData*) control;
  209582. if (info != 0)
  209583. {
  209584. delete info;
  209585. control = 0;
  209586. originalWndProc = 0;
  209587. }
  209588. }
  209589. void* ActiveXControlComponent::queryInterface (const void* iid) const
  209590. {
  209591. ActiveXControlData* const info = (ActiveXControlData*) control;
  209592. void* result = 0;
  209593. if (info != 0 && info->control != 0
  209594. && info->control->QueryInterface (*(const IID*) iid, &result) == S_OK)
  209595. return result;
  209596. return 0;
  209597. }
  209598. void ActiveXControlComponent::setControlBounds (const Rectangle& newBounds) const
  209599. {
  209600. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  209601. if (hwnd != 0)
  209602. MoveWindow (hwnd, newBounds.getX(), newBounds.getY(), newBounds.getWidth(), newBounds.getHeight(), TRUE);
  209603. }
  209604. void ActiveXControlComponent::setControlVisible (const bool shouldBeVisible) const
  209605. {
  209606. HWND hwnd = ((ActiveXControlData*) control)->controlHWND;
  209607. if (hwnd != 0)
  209608. ShowWindow (hwnd, shouldBeVisible ? SW_SHOWNA : SW_HIDE);
  209609. }
  209610. void ActiveXControlComponent::setMouseEventsAllowed (const bool eventsCanReachControl)
  209611. {
  209612. mouseEventsAllowed = eventsCanReachControl;
  209613. }
  209614. #endif
  209615. /********* End of inlined file: juce_win32_ActiveXComponent.cpp *********/
  209616. /********* Start of inlined file: juce_win32_QuickTimeMovieComponent.cpp *********/
  209617. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  209618. // compiled on its own).
  209619. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  209620. using namespace QTOLibrary;
  209621. using namespace QTOControlLib;
  209622. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle);
  209623. static bool hasLoadedQT = false;
  209624. static bool isQTAvailable = false;
  209625. struct QTMovieCompInternal
  209626. {
  209627. QTMovieCompInternal()
  209628. : dataHandle (0)
  209629. {
  209630. }
  209631. ~QTMovieCompInternal()
  209632. {
  209633. clearHandle();
  209634. }
  209635. IQTControlPtr qtControlInternal;
  209636. IQTMoviePtr qtMovieInternal;
  209637. Handle dataHandle;
  209638. void clearHandle()
  209639. {
  209640. if (dataHandle != 0)
  209641. {
  209642. DisposeHandle (dataHandle);
  209643. dataHandle = 0;
  209644. }
  209645. }
  209646. };
  209647. #define qtControl (((QTMovieCompInternal*) internal)->qtControlInternal)
  209648. #define qtMovie (((QTMovieCompInternal*) internal)->qtMovieInternal)
  209649. QuickTimeMovieComponent::QuickTimeMovieComponent()
  209650. : movieLoaded (false),
  209651. controllerVisible (true)
  209652. {
  209653. internal = new QTMovieCompInternal();
  209654. setMouseEventsAllowed (false);
  209655. }
  209656. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  209657. {
  209658. closeMovie();
  209659. qtControl = 0;
  209660. deleteControl();
  209661. delete internal;
  209662. internal = 0;
  209663. }
  209664. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  209665. {
  209666. if (! hasLoadedQT)
  209667. {
  209668. hasLoadedQT = true;
  209669. isQTAvailable = (InitializeQTML (0) == noErr)
  209670. && (EnterMovies() == noErr);
  209671. }
  209672. return isQTAvailable;
  209673. }
  209674. void QuickTimeMovieComponent::createControlIfNeeded()
  209675. {
  209676. if (isShowing() && ! isControlCreated())
  209677. {
  209678. const IID qtIID = __uuidof (QTControl);
  209679. if (createControl (&qtIID))
  209680. {
  209681. const IID qtInterfaceIID = __uuidof (IQTControl);
  209682. qtControl = (IQTControl*) queryInterface (&qtInterfaceIID);
  209683. if (qtControl != 0)
  209684. {
  209685. qtControl->Release(); // it has one ref too many at this point
  209686. qtControl->QuickTimeInitialize();
  209687. qtControl->PutSizing (qtMovieFitsControl);
  209688. if (movieFile != File::nonexistent)
  209689. loadMovie (movieFile, controllerVisible);
  209690. }
  209691. }
  209692. }
  209693. }
  209694. bool QuickTimeMovieComponent::isControlCreated() const
  209695. {
  209696. return isControlOpen();
  209697. }
  209698. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  209699. const bool isControllerVisible)
  209700. {
  209701. movieFile = File::nonexistent;
  209702. movieLoaded = false;
  209703. qtMovie = 0;
  209704. controllerVisible = isControllerVisible;
  209705. createControlIfNeeded();
  209706. if (isControlCreated())
  209707. {
  209708. if (qtControl != 0)
  209709. {
  209710. qtControl->Put_MovieHandle (0);
  209711. ((QTMovieCompInternal*) internal)->clearHandle();
  209712. Movie movie;
  209713. if (juce_OpenQuickTimeMovieFromStream (movieStream, movie, ((QTMovieCompInternal*) internal)->dataHandle))
  209714. {
  209715. qtControl->Put_MovieHandle ((long) (pointer_sized_int) movie);
  209716. qtMovie = qtControl->GetMovie();
  209717. if (qtMovie != 0)
  209718. qtMovie->PutMovieControllerType (isControllerVisible ? qtMovieControllerTypeStandard
  209719. : qtMovieControllerTypeNone);
  209720. }
  209721. if (movie == 0)
  209722. ((QTMovieCompInternal*) internal)->clearHandle();
  209723. }
  209724. movieLoaded = (qtMovie != 0);
  209725. }
  209726. else
  209727. {
  209728. // You're trying to open a movie when the control hasn't yet been created, probably because
  209729. // you've not yet added this component to a Window and made the whole component hierarchy visible.
  209730. jassertfalse
  209731. }
  209732. delete movieStream;
  209733. return movieLoaded;
  209734. }
  209735. void QuickTimeMovieComponent::closeMovie()
  209736. {
  209737. stop();
  209738. movieFile = File::nonexistent;
  209739. movieLoaded = false;
  209740. qtMovie = 0;
  209741. if (qtControl != 0)
  209742. qtControl->Put_MovieHandle (0);
  209743. ((QTMovieCompInternal*) internal)->clearHandle();
  209744. }
  209745. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  209746. {
  209747. return movieFile;
  209748. }
  209749. bool QuickTimeMovieComponent::isMovieOpen() const
  209750. {
  209751. return movieLoaded;
  209752. }
  209753. double QuickTimeMovieComponent::getMovieDuration() const
  209754. {
  209755. if (qtMovie != 0)
  209756. return qtMovie->GetDuration() / (double) qtMovie->GetTimeScale();
  209757. return 0.0;
  209758. }
  209759. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  209760. {
  209761. if (qtMovie != 0)
  209762. {
  209763. struct QTRECT r = qtMovie->GetNaturalRect();
  209764. width = r.right - r.left;
  209765. height = r.bottom - r.top;
  209766. }
  209767. else
  209768. {
  209769. width = height = 0;
  209770. }
  209771. }
  209772. void QuickTimeMovieComponent::play()
  209773. {
  209774. if (qtMovie != 0)
  209775. qtMovie->Play();
  209776. }
  209777. void QuickTimeMovieComponent::stop()
  209778. {
  209779. if (qtMovie != 0)
  209780. qtMovie->Stop();
  209781. }
  209782. bool QuickTimeMovieComponent::isPlaying() const
  209783. {
  209784. return qtMovie != 0 && qtMovie->GetRate() != 0.0f;
  209785. }
  209786. void QuickTimeMovieComponent::setPosition (const double seconds)
  209787. {
  209788. if (qtMovie != 0)
  209789. qtMovie->PutTime ((long) (seconds * qtMovie->GetTimeScale()));
  209790. }
  209791. double QuickTimeMovieComponent::getPosition() const
  209792. {
  209793. if (qtMovie != 0)
  209794. return qtMovie->GetTime() / (double) qtMovie->GetTimeScale();
  209795. return 0.0;
  209796. }
  209797. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  209798. {
  209799. if (qtMovie != 0)
  209800. qtMovie->PutRate (newSpeed);
  209801. }
  209802. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  209803. {
  209804. if (qtMovie != 0)
  209805. {
  209806. qtMovie->PutAudioVolume (newVolume);
  209807. qtMovie->PutAudioMute (newVolume <= 0);
  209808. }
  209809. }
  209810. float QuickTimeMovieComponent::getMovieVolume() const
  209811. {
  209812. if (qtMovie != 0)
  209813. return qtMovie->GetAudioVolume();
  209814. return 0.0f;
  209815. }
  209816. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  209817. {
  209818. if (qtMovie != 0)
  209819. qtMovie->PutLoop (shouldLoop);
  209820. }
  209821. bool QuickTimeMovieComponent::isLooping() const
  209822. {
  209823. return qtMovie != 0 && qtMovie->GetLoop();
  209824. }
  209825. bool QuickTimeMovieComponent::isControllerVisible() const
  209826. {
  209827. return controllerVisible;
  209828. }
  209829. void QuickTimeMovieComponent::parentHierarchyChanged()
  209830. {
  209831. createControlIfNeeded();
  209832. QTCompBaseClass::parentHierarchyChanged();
  209833. }
  209834. void QuickTimeMovieComponent::visibilityChanged()
  209835. {
  209836. createControlIfNeeded();
  209837. QTCompBaseClass::visibilityChanged();
  209838. }
  209839. void QuickTimeMovieComponent::paint (Graphics& g)
  209840. {
  209841. if (! isControlCreated())
  209842. g.fillAll (Colours::black);
  209843. }
  209844. static Handle createHandleDataRef (Handle dataHandle, const char* fileName)
  209845. {
  209846. Handle dataRef = 0;
  209847. OSStatus err = PtrToHand (&dataHandle, &dataRef, sizeof (Handle));
  209848. if (err == noErr)
  209849. {
  209850. Str255 suffix;
  209851. CharacterFunctions::copy ((char*) suffix, fileName, 128);
  209852. StringPtr name = suffix;
  209853. err = PtrAndHand (name, dataRef, name[0] + 1);
  209854. if (err == noErr)
  209855. {
  209856. long atoms[3];
  209857. atoms[0] = EndianU32_NtoB (3 * sizeof (long));
  209858. atoms[1] = EndianU32_NtoB (kDataRefExtensionMacOSFileType);
  209859. atoms[2] = EndianU32_NtoB (MovieFileType);
  209860. err = PtrAndHand (atoms, dataRef, 3 * sizeof (long));
  209861. if (err == noErr)
  209862. return dataRef;
  209863. }
  209864. DisposeHandle (dataRef);
  209865. }
  209866. return 0;
  209867. }
  209868. static CFStringRef juceStringToCFString (const String& s)
  209869. {
  209870. const int len = s.length();
  209871. const juce_wchar* const t = (const juce_wchar*) s;
  209872. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  209873. for (int i = 0; i <= len; ++i)
  209874. temp[i] = t[i];
  209875. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  209876. juce_free (temp);
  209877. return result;
  209878. }
  209879. static bool openMovie (QTNewMoviePropertyElement* props, int prop, Movie& movie)
  209880. {
  209881. Boolean trueBool = true;
  209882. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209883. props[prop].propID = kQTMovieInstantiationPropertyID_DontResolveDataRefs;
  209884. props[prop].propValueSize = sizeof (trueBool);
  209885. props[prop].propValueAddress = &trueBool;
  209886. ++prop;
  209887. props[prop].propClass = kQTPropertyClass_MovieInstantiation;
  209888. props[prop].propID = kQTMovieInstantiationPropertyID_AsyncOK;
  209889. props[prop].propValueSize = sizeof (trueBool);
  209890. props[prop].propValueAddress = &trueBool;
  209891. ++prop;
  209892. Boolean isActive = true;
  209893. props[prop].propClass = kQTPropertyClass_NewMovieProperty;
  209894. props[prop].propID = kQTNewMoviePropertyID_Active;
  209895. props[prop].propValueSize = sizeof (isActive);
  209896. props[prop].propValueAddress = &isActive;
  209897. ++prop;
  209898. MacSetPort (0);
  209899. jassert (prop <= 5);
  209900. OSStatus err = NewMovieFromProperties (prop, props, 0, 0, &movie);
  209901. return err == noErr;
  209902. }
  209903. bool juce_OpenQuickTimeMovieFromStream (InputStream* input, Movie& movie, Handle& dataHandle)
  209904. {
  209905. if (input == 0)
  209906. return false;
  209907. dataHandle = 0;
  209908. bool ok = false;
  209909. QTNewMoviePropertyElement props[5];
  209910. zeromem (props, sizeof (props));
  209911. int prop = 0;
  209912. DataReferenceRecord dr;
  209913. props[prop].propClass = kQTPropertyClass_DataLocation;
  209914. props[prop].propID = kQTDataLocationPropertyID_DataReference;
  209915. props[prop].propValueSize = sizeof (dr);
  209916. props[prop].propValueAddress = (void*) &dr;
  209917. ++prop;
  209918. FileInputStream* const fin = dynamic_cast <FileInputStream*> (input);
  209919. if (fin != 0)
  209920. {
  209921. CFStringRef filePath = juceStringToCFString (fin->getFile().getFullPathName());
  209922. QTNewDataReferenceFromFullPathCFString (filePath, (QTPathStyle) kQTNativeDefaultPathStyle, 0,
  209923. &dr.dataRef, &dr.dataRefType);
  209924. ok = openMovie (props, prop, movie);
  209925. DisposeHandle (dr.dataRef);
  209926. CFRelease (filePath);
  209927. }
  209928. else
  209929. {
  209930. // sanity-check because this currently needs to load the whole stream into memory..
  209931. jassert (input->getTotalLength() < 50 * 1024 * 1024);
  209932. dataHandle = NewHandle ((Size) input->getTotalLength());
  209933. HLock (dataHandle);
  209934. // read the entire stream into memory - this is a pain, but can't get it to work
  209935. // properly using a custom callback to supply the data.
  209936. input->read (*dataHandle, (int) input->getTotalLength());
  209937. HUnlock (dataHandle);
  209938. // different types to get QT to try. (We should really be a bit smarter here by
  209939. // working out in advance which one the stream contains, rather than just trying
  209940. // each one)
  209941. const char* const suffixesToTry[] = { "\04.mov", "\04.mp3",
  209942. "\04.avi", "\04.m4a" };
  209943. for (int i = 0; i < numElementsInArray (suffixesToTry) && ! ok; ++i)
  209944. {
  209945. /* // this fails for some bizarre reason - it can be bodged to work with
  209946. // movies, but can't seem to do it for other file types..
  209947. QTNewMovieUserProcRecord procInfo;
  209948. procInfo.getMovieUserProc = NewGetMovieUPP (readMovieStreamProc);
  209949. procInfo.getMovieUserProcRefcon = this;
  209950. procInfo.defaultDataRef.dataRef = dataRef;
  209951. procInfo.defaultDataRef.dataRefType = HandleDataHandlerSubType;
  209952. props[prop].propClass = kQTPropertyClass_DataLocation;
  209953. props[prop].propID = kQTDataLocationPropertyID_MovieUserProc;
  209954. props[prop].propValueSize = sizeof (procInfo);
  209955. props[prop].propValueAddress = (void*) &procInfo;
  209956. ++prop; */
  209957. dr.dataRef = createHandleDataRef (dataHandle, suffixesToTry [i]);
  209958. dr.dataRefType = HandleDataHandlerSubType;
  209959. ok = openMovie (props, prop, movie);
  209960. DisposeHandle (dr.dataRef);
  209961. }
  209962. }
  209963. return ok;
  209964. }
  209965. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  209966. const bool isControllerVisible)
  209967. {
  209968. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  209969. movieFile = movieFile_;
  209970. return ok;
  209971. }
  209972. void QuickTimeMovieComponent::goToStart()
  209973. {
  209974. setPosition (0.0);
  209975. }
  209976. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  209977. const RectanglePlacement& placement)
  209978. {
  209979. int normalWidth, normalHeight;
  209980. getMovieNormalSize (normalWidth, normalHeight);
  209981. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  209982. {
  209983. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  209984. placement.applyTo (x, y, w, h,
  209985. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  209986. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  209987. if (w > 0 && h > 0)
  209988. {
  209989. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  209990. roundDoubleToInt (w), roundDoubleToInt (h));
  209991. }
  209992. }
  209993. else
  209994. {
  209995. setBounds (spaceToFitWithin);
  209996. }
  209997. }
  209998. #endif
  209999. /********* End of inlined file: juce_win32_QuickTimeMovieComponent.cpp *********/
  210000. /********* Start of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  210001. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210002. // compiled on its own).
  210003. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  210004. class WebBrowserComponentInternal : public ActiveXControlComponent
  210005. {
  210006. public:
  210007. WebBrowserComponentInternal()
  210008. : browser (0),
  210009. connectionPoint (0),
  210010. adviseCookie (0)
  210011. {
  210012. }
  210013. ~WebBrowserComponentInternal()
  210014. {
  210015. if (connectionPoint != 0)
  210016. connectionPoint->Unadvise (adviseCookie);
  210017. if (browser != 0)
  210018. browser->Release();
  210019. }
  210020. void createBrowser()
  210021. {
  210022. createControl (&CLSID_WebBrowser);
  210023. browser = (IWebBrowser2*) queryInterface (&IID_IWebBrowser2);
  210024. IConnectionPointContainer* connectionPointContainer = (IConnectionPointContainer*) queryInterface (&IID_IConnectionPointContainer);
  210025. if (connectionPointContainer != 0)
  210026. {
  210027. connectionPointContainer->FindConnectionPoint (DIID_DWebBrowserEvents2,
  210028. &connectionPoint);
  210029. if (connectionPoint != 0)
  210030. {
  210031. WebBrowserComponent* const owner = dynamic_cast <WebBrowserComponent*> (getParentComponent());
  210032. jassert (owner != 0);
  210033. EventHandler* handler = new EventHandler (owner);
  210034. connectionPoint->Advise (handler, &adviseCookie);
  210035. }
  210036. }
  210037. }
  210038. void goToURL (const String& url,
  210039. const StringArray* headers,
  210040. const MemoryBlock* postData)
  210041. {
  210042. if (browser != 0)
  210043. {
  210044. LPSAFEARRAY sa = 0;
  210045. _variant_t flags, frame, postDataVar, headersVar;
  210046. if (headers != 0)
  210047. headersVar = (const tchar*) headers->joinIntoString ("\r\n");
  210048. if (postData != 0 && postData->getSize() > 0)
  210049. {
  210050. LPSAFEARRAY sa = SafeArrayCreateVector (VT_UI1, 0, postData->getSize());
  210051. if (sa != 0)
  210052. {
  210053. void* data = 0;
  210054. SafeArrayAccessData (sa, &data);
  210055. jassert (data != 0);
  210056. if (data != 0)
  210057. {
  210058. postData->copyTo (data, 0, postData->getSize());
  210059. SafeArrayUnaccessData (sa);
  210060. VARIANT postDataVar2;
  210061. VariantInit (&postDataVar2);
  210062. V_VT (&postDataVar2) = VT_ARRAY | VT_UI1;
  210063. V_ARRAY (&postDataVar2) = sa;
  210064. postDataVar = postDataVar2;
  210065. }
  210066. }
  210067. }
  210068. browser->Navigate ((BSTR) (const OLECHAR*) url,
  210069. &flags, &frame,
  210070. &postDataVar, &headersVar);
  210071. if (sa != 0)
  210072. SafeArrayDestroy (sa);
  210073. }
  210074. }
  210075. IWebBrowser2* browser;
  210076. juce_UseDebuggingNewOperator
  210077. private:
  210078. IConnectionPoint* connectionPoint;
  210079. DWORD adviseCookie;
  210080. class EventHandler : public IDispatch
  210081. {
  210082. public:
  210083. EventHandler (WebBrowserComponent* owner_)
  210084. : owner (owner_),
  210085. refCount (0)
  210086. {
  210087. }
  210088. ~EventHandler()
  210089. {
  210090. }
  210091. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  210092. {
  210093. if (id == IID_IUnknown || id == IID_IDispatch || id == DIID_DWebBrowserEvents2)
  210094. {
  210095. AddRef();
  210096. *result = this;
  210097. return S_OK;
  210098. }
  210099. *result = 0;
  210100. return E_NOINTERFACE;
  210101. }
  210102. ULONG __stdcall AddRef() { return ++refCount; }
  210103. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  210104. HRESULT __stdcall GetTypeInfoCount (UINT __RPC_FAR*) { return E_NOTIMPL; }
  210105. HRESULT __stdcall GetTypeInfo (UINT, LCID, ITypeInfo __RPC_FAR *__RPC_FAR*) { return E_NOTIMPL; }
  210106. HRESULT __stdcall GetIDsOfNames (REFIID, LPOLESTR __RPC_FAR*, UINT, LCID, DISPID __RPC_FAR*) { return E_NOTIMPL; }
  210107. HRESULT __stdcall Invoke (DISPID dispIdMember, REFIID /*riid*/, LCID /*lcid*/,
  210108. WORD /*wFlags*/, DISPPARAMS __RPC_FAR* pDispParams,
  210109. VARIANT __RPC_FAR* /*pVarResult*/, EXCEPINFO __RPC_FAR* /*pExcepInfo*/,
  210110. UINT __RPC_FAR* /*puArgErr*/)
  210111. {
  210112. switch (dispIdMember)
  210113. {
  210114. case DISPID_BEFORENAVIGATE2:
  210115. {
  210116. VARIANT* const vurl = pDispParams->rgvarg[5].pvarVal;
  210117. String url;
  210118. if ((vurl->vt & VT_BYREF) != 0)
  210119. url = *vurl->pbstrVal;
  210120. else
  210121. url = vurl->bstrVal;
  210122. *pDispParams->rgvarg->pboolVal
  210123. = owner->pageAboutToLoad (url) ? VARIANT_FALSE
  210124. : VARIANT_TRUE;
  210125. return S_OK;
  210126. }
  210127. default:
  210128. break;
  210129. }
  210130. return E_NOTIMPL;
  210131. }
  210132. juce_UseDebuggingNewOperator
  210133. private:
  210134. WebBrowserComponent* const owner;
  210135. int refCount;
  210136. EventHandler (const EventHandler&);
  210137. const EventHandler& operator= (const EventHandler&);
  210138. };
  210139. };
  210140. WebBrowserComponent::WebBrowserComponent()
  210141. : browser (0),
  210142. blankPageShown (false)
  210143. {
  210144. setOpaque (true);
  210145. addAndMakeVisible (browser = new WebBrowserComponentInternal());
  210146. }
  210147. WebBrowserComponent::~WebBrowserComponent()
  210148. {
  210149. delete browser;
  210150. }
  210151. void WebBrowserComponent::goToURL (const String& url,
  210152. const StringArray* headers,
  210153. const MemoryBlock* postData)
  210154. {
  210155. lastURL = url;
  210156. lastHeaders.clear();
  210157. if (headers != 0)
  210158. lastHeaders = *headers;
  210159. lastPostData.setSize (0);
  210160. if (postData != 0)
  210161. lastPostData = *postData;
  210162. blankPageShown = false;
  210163. browser->goToURL (url, headers, postData);
  210164. }
  210165. void WebBrowserComponent::stop()
  210166. {
  210167. if (browser->browser != 0)
  210168. browser->browser->Stop();
  210169. }
  210170. void WebBrowserComponent::goBack()
  210171. {
  210172. lastURL = String::empty;
  210173. blankPageShown = false;
  210174. if (browser->browser != 0)
  210175. browser->browser->GoBack();
  210176. }
  210177. void WebBrowserComponent::goForward()
  210178. {
  210179. lastURL = String::empty;
  210180. if (browser->browser != 0)
  210181. browser->browser->GoForward();
  210182. }
  210183. void WebBrowserComponent::paint (Graphics& g)
  210184. {
  210185. if (browser->browser == 0)
  210186. g.fillAll (Colours::white);
  210187. }
  210188. void WebBrowserComponent::checkWindowAssociation()
  210189. {
  210190. if (isShowing())
  210191. {
  210192. if (browser->browser == 0 && getPeer() != 0)
  210193. {
  210194. browser->createBrowser();
  210195. reloadLastURL();
  210196. }
  210197. else
  210198. {
  210199. if (blankPageShown)
  210200. goBack();
  210201. }
  210202. }
  210203. else
  210204. {
  210205. if (browser != 0 && ! blankPageShown)
  210206. {
  210207. // when the component becomes invisible, some stuff like flash
  210208. // carries on playing audio, so we need to force it onto a blank
  210209. // page to avoid this..
  210210. blankPageShown = true;
  210211. browser->goToURL ("about:blank", 0, 0);
  210212. }
  210213. }
  210214. }
  210215. void WebBrowserComponent::reloadLastURL()
  210216. {
  210217. if (lastURL.isNotEmpty())
  210218. {
  210219. goToURL (lastURL, &lastHeaders, &lastPostData);
  210220. lastURL = String::empty;
  210221. }
  210222. }
  210223. void WebBrowserComponent::parentHierarchyChanged()
  210224. {
  210225. checkWindowAssociation();
  210226. }
  210227. void WebBrowserComponent::resized()
  210228. {
  210229. browser->setSize (getWidth(), getHeight());
  210230. }
  210231. void WebBrowserComponent::visibilityChanged()
  210232. {
  210233. checkWindowAssociation();
  210234. }
  210235. bool WebBrowserComponent::pageAboutToLoad (const String&)
  210236. {
  210237. return true;
  210238. }
  210239. #endif
  210240. /********* End of inlined file: juce_win32_WebBrowserComponent.cpp *********/
  210241. /********* Start of inlined file: juce_win32_OpenGLComponent.cpp *********/
  210242. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210243. // compiled on its own).
  210244. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  210245. #define WGL_EXT_FUNCTION_INIT(extType, extFunc) \
  210246. ((extFunc = (extType) wglGetProcAddress (#extFunc)) != 0)
  210247. typedef const char* (WINAPI* PFNWGLGETEXTENSIONSSTRINGARBPROC) (HDC hdc);
  210248. typedef BOOL (WINAPI * PFNWGLGETPIXELFORMATATTRIBIVARBPROC) (HDC hdc, int iPixelFormat, int iLayerPlane, UINT nAttributes, const int *piAttributes, int *piValues);
  210249. typedef BOOL (WINAPI * PFNWGLCHOOSEPIXELFORMATARBPROC) (HDC hdc, const int* piAttribIList, const FLOAT *pfAttribFList, UINT nMaxFormats, int *piFormats, UINT *nNumFormats);
  210250. typedef BOOL (WINAPI * PFNWGLSWAPINTERVALEXTPROC) (int interval);
  210251. typedef int (WINAPI * PFNWGLGETSWAPINTERVALEXTPROC) (void);
  210252. #define WGL_NUMBER_PIXEL_FORMATS_ARB 0x2000
  210253. #define WGL_DRAW_TO_WINDOW_ARB 0x2001
  210254. #define WGL_ACCELERATION_ARB 0x2003
  210255. #define WGL_SWAP_METHOD_ARB 0x2007
  210256. #define WGL_SUPPORT_OPENGL_ARB 0x2010
  210257. #define WGL_PIXEL_TYPE_ARB 0x2013
  210258. #define WGL_DOUBLE_BUFFER_ARB 0x2011
  210259. #define WGL_COLOR_BITS_ARB 0x2014
  210260. #define WGL_RED_BITS_ARB 0x2015
  210261. #define WGL_GREEN_BITS_ARB 0x2017
  210262. #define WGL_BLUE_BITS_ARB 0x2019
  210263. #define WGL_ALPHA_BITS_ARB 0x201B
  210264. #define WGL_DEPTH_BITS_ARB 0x2022
  210265. #define WGL_STENCIL_BITS_ARB 0x2023
  210266. #define WGL_FULL_ACCELERATION_ARB 0x2027
  210267. #define WGL_ACCUM_RED_BITS_ARB 0x201E
  210268. #define WGL_ACCUM_GREEN_BITS_ARB 0x201F
  210269. #define WGL_ACCUM_BLUE_BITS_ARB 0x2020
  210270. #define WGL_ACCUM_ALPHA_BITS_ARB 0x2021
  210271. #define WGL_STEREO_ARB 0x2012
  210272. #define WGL_SAMPLE_BUFFERS_ARB 0x2041
  210273. #define WGL_SAMPLES_ARB 0x2042
  210274. #define WGL_TYPE_RGBA_ARB 0x202B
  210275. static void getWglExtensions (HDC dc, StringArray& result) throw()
  210276. {
  210277. PFNWGLGETEXTENSIONSSTRINGARBPROC wglGetExtensionsStringARB = 0;
  210278. if (WGL_EXT_FUNCTION_INIT (PFNWGLGETEXTENSIONSSTRINGARBPROC, wglGetExtensionsStringARB))
  210279. result.addTokens (String (wglGetExtensionsStringARB (dc)), false);
  210280. else
  210281. jassertfalse // If this fails, it may be because you didn't activate the openGL context
  210282. }
  210283. class WindowedGLContext : public OpenGLContext
  210284. {
  210285. public:
  210286. WindowedGLContext (Component* const component_,
  210287. HGLRC contextToShareWith,
  210288. const OpenGLPixelFormat& pixelFormat)
  210289. : renderContext (0),
  210290. nativeWindow (0),
  210291. dc (0),
  210292. component (component_)
  210293. {
  210294. jassert (component != 0);
  210295. createNativeWindow();
  210296. // Use a default pixel format that should be supported everywhere
  210297. PIXELFORMATDESCRIPTOR pfd;
  210298. zerostruct (pfd);
  210299. pfd.nSize = sizeof (pfd);
  210300. pfd.nVersion = 1;
  210301. pfd.dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER;
  210302. pfd.iPixelType = PFD_TYPE_RGBA;
  210303. pfd.cColorBits = 24;
  210304. pfd.cDepthBits = 16;
  210305. const int format = ChoosePixelFormat (dc, &pfd);
  210306. if (format != 0)
  210307. SetPixelFormat (dc, format, &pfd);
  210308. renderContext = wglCreateContext (dc);
  210309. makeActive();
  210310. setPixelFormat (pixelFormat);
  210311. if (contextToShareWith != 0 && renderContext != 0)
  210312. wglShareLists (contextToShareWith, renderContext);
  210313. }
  210314. ~WindowedGLContext()
  210315. {
  210316. makeInactive();
  210317. wglDeleteContext (renderContext);
  210318. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210319. delete nativeWindow;
  210320. }
  210321. bool makeActive() const throw()
  210322. {
  210323. jassert (renderContext != 0);
  210324. return wglMakeCurrent (dc, renderContext) != 0;
  210325. }
  210326. bool makeInactive() const throw()
  210327. {
  210328. return (! isActive()) || (wglMakeCurrent (0, 0) != 0);
  210329. }
  210330. bool isActive() const throw()
  210331. {
  210332. return wglGetCurrentContext() == renderContext;
  210333. }
  210334. const OpenGLPixelFormat getPixelFormat() const
  210335. {
  210336. OpenGLPixelFormat pf;
  210337. makeActive();
  210338. StringArray availableExtensions;
  210339. getWglExtensions (dc, availableExtensions);
  210340. fillInPixelFormatDetails (GetPixelFormat (dc), pf, availableExtensions);
  210341. return pf;
  210342. }
  210343. void* getRawContext() const throw()
  210344. {
  210345. return renderContext;
  210346. }
  210347. bool setPixelFormat (const OpenGLPixelFormat& pixelFormat)
  210348. {
  210349. makeActive();
  210350. PIXELFORMATDESCRIPTOR pfd;
  210351. zerostruct (pfd);
  210352. pfd.nSize = sizeof (pfd);
  210353. pfd.nVersion = 1;
  210354. pfd.dwFlags = PFD_SUPPORT_OPENGL | PFD_DRAW_TO_WINDOW | PFD_DOUBLEBUFFER;
  210355. pfd.iPixelType = PFD_TYPE_RGBA;
  210356. pfd.iLayerType = PFD_MAIN_PLANE;
  210357. pfd.cColorBits = (BYTE) (pixelFormat.redBits + pixelFormat.greenBits + pixelFormat.blueBits);
  210358. pfd.cRedBits = (BYTE) pixelFormat.redBits;
  210359. pfd.cGreenBits = (BYTE) pixelFormat.greenBits;
  210360. pfd.cBlueBits = (BYTE) pixelFormat.blueBits;
  210361. pfd.cAlphaBits = (BYTE) pixelFormat.alphaBits;
  210362. pfd.cDepthBits = (BYTE) pixelFormat.depthBufferBits;
  210363. pfd.cStencilBits = (BYTE) pixelFormat.stencilBufferBits;
  210364. pfd.cAccumBits = (BYTE) (pixelFormat.accumulationBufferRedBits + pixelFormat.accumulationBufferGreenBits
  210365. + pixelFormat.accumulationBufferBlueBits + pixelFormat.accumulationBufferAlphaBits);
  210366. pfd.cAccumRedBits = (BYTE) pixelFormat.accumulationBufferRedBits;
  210367. pfd.cAccumGreenBits = (BYTE) pixelFormat.accumulationBufferGreenBits;
  210368. pfd.cAccumBlueBits = (BYTE) pixelFormat.accumulationBufferBlueBits;
  210369. pfd.cAccumAlphaBits = (BYTE) pixelFormat.accumulationBufferAlphaBits;
  210370. int format = 0;
  210371. PFNWGLCHOOSEPIXELFORMATARBPROC wglChoosePixelFormatARB = 0;
  210372. StringArray availableExtensions;
  210373. getWglExtensions (dc, availableExtensions);
  210374. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210375. && WGL_EXT_FUNCTION_INIT (PFNWGLCHOOSEPIXELFORMATARBPROC, wglChoosePixelFormatARB))
  210376. {
  210377. int attributes[64];
  210378. int n = 0;
  210379. attributes[n++] = WGL_DRAW_TO_WINDOW_ARB;
  210380. attributes[n++] = GL_TRUE;
  210381. attributes[n++] = WGL_SUPPORT_OPENGL_ARB;
  210382. attributes[n++] = GL_TRUE;
  210383. attributes[n++] = WGL_ACCELERATION_ARB;
  210384. attributes[n++] = WGL_FULL_ACCELERATION_ARB;
  210385. attributes[n++] = WGL_DOUBLE_BUFFER_ARB;
  210386. attributes[n++] = GL_TRUE;
  210387. attributes[n++] = WGL_PIXEL_TYPE_ARB;
  210388. attributes[n++] = WGL_TYPE_RGBA_ARB;
  210389. attributes[n++] = WGL_COLOR_BITS_ARB;
  210390. attributes[n++] = pfd.cColorBits;
  210391. attributes[n++] = WGL_RED_BITS_ARB;
  210392. attributes[n++] = pixelFormat.redBits;
  210393. attributes[n++] = WGL_GREEN_BITS_ARB;
  210394. attributes[n++] = pixelFormat.greenBits;
  210395. attributes[n++] = WGL_BLUE_BITS_ARB;
  210396. attributes[n++] = pixelFormat.blueBits;
  210397. attributes[n++] = WGL_ALPHA_BITS_ARB;
  210398. attributes[n++] = pixelFormat.alphaBits;
  210399. attributes[n++] = WGL_DEPTH_BITS_ARB;
  210400. attributes[n++] = pixelFormat.depthBufferBits;
  210401. if (pixelFormat.stencilBufferBits > 0)
  210402. {
  210403. attributes[n++] = WGL_STENCIL_BITS_ARB;
  210404. attributes[n++] = pixelFormat.stencilBufferBits;
  210405. }
  210406. attributes[n++] = WGL_ACCUM_RED_BITS_ARB;
  210407. attributes[n++] = pixelFormat.accumulationBufferRedBits;
  210408. attributes[n++] = WGL_ACCUM_GREEN_BITS_ARB;
  210409. attributes[n++] = pixelFormat.accumulationBufferGreenBits;
  210410. attributes[n++] = WGL_ACCUM_BLUE_BITS_ARB;
  210411. attributes[n++] = pixelFormat.accumulationBufferBlueBits;
  210412. attributes[n++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210413. attributes[n++] = pixelFormat.accumulationBufferAlphaBits;
  210414. if (availableExtensions.contains ("WGL_ARB_multisample")
  210415. && pixelFormat.fullSceneAntiAliasingNumSamples > 0)
  210416. {
  210417. attributes[n++] = WGL_SAMPLE_BUFFERS_ARB;
  210418. attributes[n++] = 1;
  210419. attributes[n++] = WGL_SAMPLES_ARB;
  210420. attributes[n++] = pixelFormat.fullSceneAntiAliasingNumSamples;
  210421. }
  210422. attributes[n++] = 0;
  210423. UINT formatsCount;
  210424. const BOOL ok = wglChoosePixelFormatARB (dc, attributes, 0, 1, &format, &formatsCount);
  210425. (void) ok;
  210426. jassert (ok);
  210427. }
  210428. else
  210429. {
  210430. format = ChoosePixelFormat (dc, &pfd);
  210431. }
  210432. if (format != 0)
  210433. {
  210434. makeInactive();
  210435. // win32 can't change the pixel format of a window, so need to delete the
  210436. // old one and create a new one..
  210437. jassert (nativeWindow != 0);
  210438. ReleaseDC ((HWND) nativeWindow->getNativeHandle(), dc);
  210439. delete nativeWindow;
  210440. createNativeWindow();
  210441. if (SetPixelFormat (dc, format, &pfd))
  210442. {
  210443. wglDeleteContext (renderContext);
  210444. renderContext = wglCreateContext (dc);
  210445. jassert (renderContext != 0);
  210446. return renderContext != 0;
  210447. }
  210448. }
  210449. return false;
  210450. }
  210451. void updateWindowPosition (int x, int y, int w, int h, int)
  210452. {
  210453. SetWindowPos ((HWND) nativeWindow->getNativeHandle(), 0,
  210454. x, y, w, h,
  210455. SWP_NOACTIVATE | SWP_NOZORDER | SWP_NOOWNERZORDER);
  210456. }
  210457. void repaint()
  210458. {
  210459. int x, y, w, h;
  210460. nativeWindow->getBounds (x, y, w, h);
  210461. nativeWindow->repaint (0, 0, w, h);
  210462. }
  210463. void swapBuffers()
  210464. {
  210465. SwapBuffers (dc);
  210466. }
  210467. bool setSwapInterval (const int numFramesPerSwap)
  210468. {
  210469. makeActive();
  210470. StringArray availableExtensions;
  210471. getWglExtensions (dc, availableExtensions);
  210472. PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = 0;
  210473. return availableExtensions.contains ("WGL_EXT_swap_control")
  210474. && WGL_EXT_FUNCTION_INIT (PFNWGLSWAPINTERVALEXTPROC, wglSwapIntervalEXT)
  210475. && wglSwapIntervalEXT (numFramesPerSwap) != FALSE;
  210476. }
  210477. int getSwapInterval() const
  210478. {
  210479. makeActive();
  210480. StringArray availableExtensions;
  210481. getWglExtensions (dc, availableExtensions);
  210482. PFNWGLGETSWAPINTERVALEXTPROC wglGetSwapIntervalEXT = 0;
  210483. if (availableExtensions.contains ("WGL_EXT_swap_control")
  210484. && WGL_EXT_FUNCTION_INIT (PFNWGLGETSWAPINTERVALEXTPROC, wglGetSwapIntervalEXT))
  210485. return wglGetSwapIntervalEXT();
  210486. return 0;
  210487. }
  210488. void findAlternativeOpenGLPixelFormats (OwnedArray <OpenGLPixelFormat>& results)
  210489. {
  210490. jassert (isActive());
  210491. StringArray availableExtensions;
  210492. getWglExtensions (dc, availableExtensions);
  210493. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210494. int numTypes = 0;
  210495. if (availableExtensions.contains("WGL_ARB_pixel_format")
  210496. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210497. {
  210498. int attributes = WGL_NUMBER_PIXEL_FORMATS_ARB;
  210499. if (! wglGetPixelFormatAttribivARB (dc, 1, 0, 1, &attributes, &numTypes))
  210500. jassertfalse
  210501. }
  210502. else
  210503. {
  210504. numTypes = DescribePixelFormat (dc, 0, 0, 0);
  210505. }
  210506. OpenGLPixelFormat pf;
  210507. for (int i = 0; i < numTypes; ++i)
  210508. {
  210509. if (fillInPixelFormatDetails (i + 1, pf, availableExtensions))
  210510. {
  210511. bool alreadyListed = false;
  210512. for (int j = results.size(); --j >= 0;)
  210513. if (pf == *results.getUnchecked(j))
  210514. alreadyListed = true;
  210515. if (! alreadyListed)
  210516. results.add (new OpenGLPixelFormat (pf));
  210517. }
  210518. }
  210519. }
  210520. void* getNativeWindowHandle() const
  210521. {
  210522. return nativeWindow != 0 ? nativeWindow->getNativeHandle() : 0;
  210523. }
  210524. juce_UseDebuggingNewOperator
  210525. HGLRC renderContext;
  210526. private:
  210527. Win32ComponentPeer* nativeWindow;
  210528. Component* const component;
  210529. HDC dc;
  210530. void createNativeWindow()
  210531. {
  210532. nativeWindow = new Win32ComponentPeer (component, 0);
  210533. nativeWindow->dontRepaint = true;
  210534. nativeWindow->setVisible (true);
  210535. HWND hwnd = (HWND) nativeWindow->getNativeHandle();
  210536. Win32ComponentPeer* const peer = dynamic_cast <Win32ComponentPeer*> (component->getTopLevelComponent()->getPeer());
  210537. if (peer != 0)
  210538. {
  210539. SetParent (hwnd, (HWND) peer->getNativeHandle());
  210540. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_CHILD, true);
  210541. juce_setWindowStyleBit (hwnd, GWL_STYLE, WS_POPUP, false);
  210542. }
  210543. dc = GetDC (hwnd);
  210544. }
  210545. bool fillInPixelFormatDetails (const int pixelFormatIndex,
  210546. OpenGLPixelFormat& result,
  210547. const StringArray& availableExtensions) const throw()
  210548. {
  210549. PFNWGLGETPIXELFORMATATTRIBIVARBPROC wglGetPixelFormatAttribivARB = 0;
  210550. if (availableExtensions.contains ("WGL_ARB_pixel_format")
  210551. && WGL_EXT_FUNCTION_INIT (PFNWGLGETPIXELFORMATATTRIBIVARBPROC, wglGetPixelFormatAttribivARB))
  210552. {
  210553. int attributes[32];
  210554. int numAttributes = 0;
  210555. attributes[numAttributes++] = WGL_DRAW_TO_WINDOW_ARB;
  210556. attributes[numAttributes++] = WGL_SUPPORT_OPENGL_ARB;
  210557. attributes[numAttributes++] = WGL_ACCELERATION_ARB;
  210558. attributes[numAttributes++] = WGL_DOUBLE_BUFFER_ARB;
  210559. attributes[numAttributes++] = WGL_PIXEL_TYPE_ARB;
  210560. attributes[numAttributes++] = WGL_RED_BITS_ARB;
  210561. attributes[numAttributes++] = WGL_GREEN_BITS_ARB;
  210562. attributes[numAttributes++] = WGL_BLUE_BITS_ARB;
  210563. attributes[numAttributes++] = WGL_ALPHA_BITS_ARB;
  210564. attributes[numAttributes++] = WGL_DEPTH_BITS_ARB;
  210565. attributes[numAttributes++] = WGL_STENCIL_BITS_ARB;
  210566. attributes[numAttributes++] = WGL_ACCUM_RED_BITS_ARB;
  210567. attributes[numAttributes++] = WGL_ACCUM_GREEN_BITS_ARB;
  210568. attributes[numAttributes++] = WGL_ACCUM_BLUE_BITS_ARB;
  210569. attributes[numAttributes++] = WGL_ACCUM_ALPHA_BITS_ARB;
  210570. if (availableExtensions.contains ("WGL_ARB_multisample"))
  210571. attributes[numAttributes++] = WGL_SAMPLES_ARB;
  210572. int values[32];
  210573. zeromem (values, sizeof (values));
  210574. if (wglGetPixelFormatAttribivARB (dc, pixelFormatIndex, 0, numAttributes, attributes, values))
  210575. {
  210576. int n = 0;
  210577. bool isValidFormat = (values[n++] == GL_TRUE); // WGL_DRAW_TO_WINDOW_ARB
  210578. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_SUPPORT_OPENGL_ARB
  210579. isValidFormat = (values[n++] == WGL_FULL_ACCELERATION_ARB) && isValidFormat; // WGL_ACCELERATION_ARB
  210580. isValidFormat = (values[n++] == GL_TRUE) && isValidFormat; // WGL_DOUBLE_BUFFER_ARB:
  210581. isValidFormat = (values[n++] == WGL_TYPE_RGBA_ARB) && isValidFormat; // WGL_PIXEL_TYPE_ARB
  210582. result.redBits = values[n++]; // WGL_RED_BITS_ARB
  210583. result.greenBits = values[n++]; // WGL_GREEN_BITS_ARB
  210584. result.blueBits = values[n++]; // WGL_BLUE_BITS_ARB
  210585. result.alphaBits = values[n++]; // WGL_ALPHA_BITS_ARB
  210586. result.depthBufferBits = values[n++]; // WGL_DEPTH_BITS_ARB
  210587. result.stencilBufferBits = values[n++]; // WGL_STENCIL_BITS_ARB
  210588. result.accumulationBufferRedBits = values[n++]; // WGL_ACCUM_RED_BITS_ARB
  210589. result.accumulationBufferGreenBits = values[n++]; // WGL_ACCUM_GREEN_BITS_ARB
  210590. result.accumulationBufferBlueBits = values[n++]; // WGL_ACCUM_BLUE_BITS_ARB
  210591. result.accumulationBufferAlphaBits = values[n++]; // WGL_ACCUM_ALPHA_BITS_ARB
  210592. result.fullSceneAntiAliasingNumSamples = (uint8) values[n++]; // WGL_SAMPLES_ARB
  210593. return isValidFormat;
  210594. }
  210595. else
  210596. {
  210597. jassertfalse
  210598. }
  210599. }
  210600. else
  210601. {
  210602. PIXELFORMATDESCRIPTOR pfd;
  210603. if (DescribePixelFormat (dc, pixelFormatIndex, sizeof (pfd), &pfd))
  210604. {
  210605. result.redBits = pfd.cRedBits;
  210606. result.greenBits = pfd.cGreenBits;
  210607. result.blueBits = pfd.cBlueBits;
  210608. result.alphaBits = pfd.cAlphaBits;
  210609. result.depthBufferBits = pfd.cDepthBits;
  210610. result.stencilBufferBits = pfd.cStencilBits;
  210611. result.accumulationBufferRedBits = pfd.cAccumRedBits;
  210612. result.accumulationBufferGreenBits = pfd.cAccumGreenBits;
  210613. result.accumulationBufferBlueBits = pfd.cAccumBlueBits;
  210614. result.accumulationBufferAlphaBits = pfd.cAccumAlphaBits;
  210615. result.fullSceneAntiAliasingNumSamples = 0;
  210616. return true;
  210617. }
  210618. else
  210619. {
  210620. jassertfalse
  210621. }
  210622. }
  210623. return false;
  210624. }
  210625. WindowedGLContext (const WindowedGLContext&);
  210626. const WindowedGLContext& operator= (const WindowedGLContext&);
  210627. };
  210628. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  210629. const OpenGLPixelFormat& pixelFormat,
  210630. const OpenGLContext* const contextToShareWith)
  210631. {
  210632. WindowedGLContext* c = new WindowedGLContext (component,
  210633. contextToShareWith != 0 ? (HGLRC) contextToShareWith->getRawContext() : 0,
  210634. pixelFormat);
  210635. if (c->renderContext == 0)
  210636. deleteAndZero (c);
  210637. return c;
  210638. }
  210639. void* OpenGLComponent::getNativeWindowHandle() const
  210640. {
  210641. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle() : 0;
  210642. }
  210643. void juce_glViewport (const int w, const int h)
  210644. {
  210645. glViewport (0, 0, w, h);
  210646. }
  210647. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  210648. OwnedArray <OpenGLPixelFormat>& results)
  210649. {
  210650. Component tempComp;
  210651. {
  210652. WindowedGLContext wc (component, 0, OpenGLPixelFormat (8, 8, 16, 0));
  210653. wc.makeActive();
  210654. wc.findAlternativeOpenGLPixelFormats (results);
  210655. }
  210656. }
  210657. #endif
  210658. /********* End of inlined file: juce_win32_OpenGLComponent.cpp *********/
  210659. /********* Start of inlined file: juce_win32_AudioCDReader.cpp *********/
  210660. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  210661. // compiled on its own).
  210662. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  210663. //***************************************************************************
  210664. // %%% TARGET STATUS VALUES %%%
  210665. //***************************************************************************
  210666. #define STATUS_GOOD 0x00 // Status Good
  210667. #define STATUS_CHKCOND 0x02 // Check Condition
  210668. #define STATUS_CONDMET 0x04 // Condition Met
  210669. #define STATUS_BUSY 0x08 // Busy
  210670. #define STATUS_INTERM 0x10 // Intermediate
  210671. #define STATUS_INTCDMET 0x14 // Intermediate-condition met
  210672. #define STATUS_RESCONF 0x18 // Reservation conflict
  210673. #define STATUS_COMTERM 0x22 // Command Terminated
  210674. #define STATUS_QFULL 0x28 // Queue full
  210675. //***************************************************************************
  210676. // %%% SCSI MISCELLANEOUS EQUATES %%%
  210677. //***************************************************************************
  210678. #define MAXLUN 7 // Maximum Logical Unit Id
  210679. #define MAXTARG 7 // Maximum Target Id
  210680. #define MAX_SCSI_LUNS 64 // Maximum Number of SCSI LUNs
  210681. #define MAX_NUM_HA 8 // Maximum Number of SCSI HA's
  210682. //***************************************************************************
  210683. // %%% Commands for all Device Types %%%
  210684. //***************************************************************************
  210685. #define SCSI_CHANGE_DEF 0x40 // Change Definition (Optional)
  210686. #define SCSI_COMPARE 0x39 // Compare (O)
  210687. #define SCSI_COPY 0x18 // Copy (O)
  210688. #define SCSI_COP_VERIFY 0x3A // Copy and Verify (O)
  210689. #define SCSI_INQUIRY 0x12 // Inquiry (MANDATORY)
  210690. #define SCSI_LOG_SELECT 0x4C // Log Select (O)
  210691. #define SCSI_LOG_SENSE 0x4D // Log Sense (O)
  210692. #define SCSI_MODE_SEL6 0x15 // Mode Select 6-byte (Device Specific)
  210693. #define SCSI_MODE_SEL10 0x55 // Mode Select 10-byte (Device Specific)
  210694. #define SCSI_MODE_SEN6 0x1A // Mode Sense 6-byte (Device Specific)
  210695. #define SCSI_MODE_SEN10 0x5A // Mode Sense 10-byte (Device Specific)
  210696. #define SCSI_READ_BUFF 0x3C // Read Buffer (O)
  210697. #define SCSI_REQ_SENSE 0x03 // Request Sense (MANDATORY)
  210698. #define SCSI_SEND_DIAG 0x1D // Send Diagnostic (O)
  210699. #define SCSI_TST_U_RDY 0x00 // Test Unit Ready (MANDATORY)
  210700. #define SCSI_WRITE_BUFF 0x3B // Write Buffer (O)
  210701. //***************************************************************************
  210702. // %%% Commands Unique to Direct Access Devices %%%
  210703. //***************************************************************************
  210704. #define SCSI_COMPARE 0x39 // Compare (O)
  210705. #define SCSI_FORMAT 0x04 // Format Unit (MANDATORY)
  210706. #define SCSI_LCK_UN_CAC 0x36 // Lock Unlock Cache (O)
  210707. #define SCSI_PREFETCH 0x34 // Prefetch (O)
  210708. #define SCSI_MED_REMOVL 0x1E // Prevent/Allow medium Removal (O)
  210709. #define SCSI_READ6 0x08 // Read 6-byte (MANDATORY)
  210710. #define SCSI_READ10 0x28 // Read 10-byte (MANDATORY)
  210711. #define SCSI_RD_CAPAC 0x25 // Read Capacity (MANDATORY)
  210712. #define SCSI_RD_DEFECT 0x37 // Read Defect Data (O)
  210713. #define SCSI_READ_LONG 0x3E // Read Long (O)
  210714. #define SCSI_REASS_BLK 0x07 // Reassign Blocks (O)
  210715. #define SCSI_RCV_DIAG 0x1C // Receive Diagnostic Results (O)
  210716. #define SCSI_RELEASE 0x17 // Release Unit (MANDATORY)
  210717. #define SCSI_REZERO 0x01 // Rezero Unit (O)
  210718. #define SCSI_SRCH_DAT_E 0x31 // Search Data Equal (O)
  210719. #define SCSI_SRCH_DAT_H 0x30 // Search Data High (O)
  210720. #define SCSI_SRCH_DAT_L 0x32 // Search Data Low (O)
  210721. #define SCSI_SEEK6 0x0B // Seek 6-Byte (O)
  210722. #define SCSI_SEEK10 0x2B // Seek 10-Byte (O)
  210723. #define SCSI_SEND_DIAG 0x1D // Send Diagnostics (MANDATORY)
  210724. #define SCSI_SET_LIMIT 0x33 // Set Limits (O)
  210725. #define SCSI_START_STP 0x1B // Start/Stop Unit (O)
  210726. #define SCSI_SYNC_CACHE 0x35 // Synchronize Cache (O)
  210727. #define SCSI_VERIFY 0x2F // Verify (O)
  210728. #define SCSI_WRITE6 0x0A // Write 6-Byte (MANDATORY)
  210729. #define SCSI_WRITE10 0x2A // Write 10-Byte (MANDATORY)
  210730. #define SCSI_WRT_VERIFY 0x2E // Write and Verify (O)
  210731. #define SCSI_WRITE_LONG 0x3F // Write Long (O)
  210732. #define SCSI_WRITE_SAME 0x41 // Write Same (O)
  210733. //***************************************************************************
  210734. // %%% Commands Unique to Sequential Access Devices %%%
  210735. //***************************************************************************
  210736. #define SCSI_ERASE 0x19 // Erase (MANDATORY)
  210737. #define SCSI_LOAD_UN 0x1b // Load/Unload (O)
  210738. #define SCSI_LOCATE 0x2B // Locate (O)
  210739. #define SCSI_RD_BLK_LIM 0x05 // Read Block Limits (MANDATORY)
  210740. #define SCSI_READ_POS 0x34 // Read Position (O)
  210741. #define SCSI_READ_REV 0x0F // Read Reverse (O)
  210742. #define SCSI_REC_BF_DAT 0x14 // Recover Buffer Data (O)
  210743. #define SCSI_RESERVE 0x16 // Reserve Unit (MANDATORY)
  210744. #define SCSI_REWIND 0x01 // Rewind (MANDATORY)
  210745. #define SCSI_SPACE 0x11 // Space (MANDATORY)
  210746. #define SCSI_VERIFY_T 0x13 // Verify (Tape) (O)
  210747. #define SCSI_WRT_FILE 0x10 // Write Filemarks (MANDATORY)
  210748. //***************************************************************************
  210749. // %%% Commands Unique to Printer Devices %%%
  210750. //***************************************************************************
  210751. #define SCSI_PRINT 0x0A // Print (MANDATORY)
  210752. #define SCSI_SLEW_PNT 0x0B // Slew and Print (O)
  210753. #define SCSI_STOP_PNT 0x1B // Stop Print (O)
  210754. #define SCSI_SYNC_BUFF 0x10 // Synchronize Buffer (O)
  210755. //***************************************************************************
  210756. // %%% Commands Unique to Processor Devices %%%
  210757. //***************************************************************************
  210758. #define SCSI_RECEIVE 0x08 // Receive (O)
  210759. #define SCSI_SEND 0x0A // Send (O)
  210760. //***************************************************************************
  210761. // %%% Commands Unique to Write-Once Devices %%%
  210762. //***************************************************************************
  210763. #define SCSI_MEDIUM_SCN 0x38 // Medium Scan (O)
  210764. #define SCSI_SRCHDATE10 0x31 // Search Data Equal 10-Byte (O)
  210765. #define SCSI_SRCHDATE12 0xB1 // Search Data Equal 12-Byte (O)
  210766. #define SCSI_SRCHDATH10 0x30 // Search Data High 10-Byte (O)
  210767. #define SCSI_SRCHDATH12 0xB0 // Search Data High 12-Byte (O)
  210768. #define SCSI_SRCHDATL10 0x32 // Search Data Low 10-Byte (O)
  210769. #define SCSI_SRCHDATL12 0xB2 // Search Data Low 12-Byte (O)
  210770. #define SCSI_SET_LIM_10 0x33 // Set Limits 10-Byte (O)
  210771. #define SCSI_SET_LIM_12 0xB3 // Set Limits 10-Byte (O)
  210772. #define SCSI_VERIFY10 0x2F // Verify 10-Byte (O)
  210773. #define SCSI_VERIFY12 0xAF // Verify 12-Byte (O)
  210774. #define SCSI_WRITE12 0xAA // Write 12-Byte (O)
  210775. #define SCSI_WRT_VER10 0x2E // Write and Verify 10-Byte (O)
  210776. #define SCSI_WRT_VER12 0xAE // Write and Verify 12-Byte (O)
  210777. //***************************************************************************
  210778. // %%% Commands Unique to CD-ROM Devices %%%
  210779. //***************************************************************************
  210780. #define SCSI_PLAYAUD_10 0x45 // Play Audio 10-Byte (O)
  210781. #define SCSI_PLAYAUD_12 0xA5 // Play Audio 12-Byte 12-Byte (O)
  210782. #define SCSI_PLAYAUDMSF 0x47 // Play Audio MSF (O)
  210783. #define SCSI_PLAYA_TKIN 0x48 // Play Audio Track/Index (O)
  210784. #define SCSI_PLYTKREL10 0x49 // Play Track Relative 10-Byte (O)
  210785. #define SCSI_PLYTKREL12 0xA9 // Play Track Relative 12-Byte (O)
  210786. #define SCSI_READCDCAP 0x25 // Read CD-ROM Capacity (MANDATORY)
  210787. #define SCSI_READHEADER 0x44 // Read Header (O)
  210788. #define SCSI_SUBCHANNEL 0x42 // Read Subchannel (O)
  210789. #define SCSI_READ_TOC 0x43 // Read TOC (O)
  210790. //***************************************************************************
  210791. // %%% Commands Unique to Scanner Devices %%%
  210792. //***************************************************************************
  210793. #define SCSI_GETDBSTAT 0x34 // Get Data Buffer Status (O)
  210794. #define SCSI_GETWINDOW 0x25 // Get Window (O)
  210795. #define SCSI_OBJECTPOS 0x31 // Object Postion (O)
  210796. #define SCSI_SCAN 0x1B // Scan (O)
  210797. #define SCSI_SETWINDOW 0x24 // Set Window (MANDATORY)
  210798. //***************************************************************************
  210799. // %%% Commands Unique to Optical Memory Devices %%%
  210800. //***************************************************************************
  210801. #define SCSI_UpdateBlk 0x3D // Update Block (O)
  210802. //***************************************************************************
  210803. // %%% Commands Unique to Medium Changer Devices %%%
  210804. //***************************************************************************
  210805. #define SCSI_EXCHMEDIUM 0xA6 // Exchange Medium (O)
  210806. #define SCSI_INITELSTAT 0x07 // Initialize Element Status (O)
  210807. #define SCSI_POSTOELEM 0x2B // Position to Element (O)
  210808. #define SCSI_REQ_VE_ADD 0xB5 // Request Volume Element Address (O)
  210809. #define SCSI_SENDVOLTAG 0xB6 // Send Volume Tag (O)
  210810. //***************************************************************************
  210811. // %%% Commands Unique to Communication Devices %%%
  210812. //***************************************************************************
  210813. #define SCSI_GET_MSG_6 0x08 // Get Message 6-Byte (MANDATORY)
  210814. #define SCSI_GET_MSG_10 0x28 // Get Message 10-Byte (O)
  210815. #define SCSI_GET_MSG_12 0xA8 // Get Message 12-Byte (O)
  210816. #define SCSI_SND_MSG_6 0x0A // Send Message 6-Byte (MANDATORY)
  210817. #define SCSI_SND_MSG_10 0x2A // Send Message 10-Byte (O)
  210818. #define SCSI_SND_MSG_12 0xAA // Send Message 12-Byte (O)
  210819. //***************************************************************************
  210820. // %%% Request Sense Data Format %%%
  210821. //***************************************************************************
  210822. typedef struct {
  210823. BYTE ErrorCode; // Error Code (70H or 71H)
  210824. BYTE SegmentNum; // Number of current segment descriptor
  210825. BYTE SenseKey; // Sense Key(See bit definitions too)
  210826. BYTE InfoByte0; // Information MSB
  210827. BYTE InfoByte1; // Information MID
  210828. BYTE InfoByte2; // Information MID
  210829. BYTE InfoByte3; // Information LSB
  210830. BYTE AddSenLen; // Additional Sense Length
  210831. BYTE ComSpecInf0; // Command Specific Information MSB
  210832. BYTE ComSpecInf1; // Command Specific Information MID
  210833. BYTE ComSpecInf2; // Command Specific Information MID
  210834. BYTE ComSpecInf3; // Command Specific Information LSB
  210835. BYTE AddSenseCode; // Additional Sense Code
  210836. BYTE AddSenQual; // Additional Sense Code Qualifier
  210837. BYTE FieldRepUCode; // Field Replaceable Unit Code
  210838. BYTE SenKeySpec15; // Sense Key Specific 15th byte
  210839. BYTE SenKeySpec16; // Sense Key Specific 16th byte
  210840. BYTE SenKeySpec17; // Sense Key Specific 17th byte
  210841. BYTE AddSenseBytes; // Additional Sense Bytes
  210842. } SENSE_DATA_FMT;
  210843. //***************************************************************************
  210844. // %%% REQUEST SENSE ERROR CODE %%%
  210845. //***************************************************************************
  210846. #define SERROR_CURRENT 0x70 // Current Errors
  210847. #define SERROR_DEFERED 0x71 // Deferred Errors
  210848. //***************************************************************************
  210849. // %%% REQUEST SENSE BIT DEFINITIONS %%%
  210850. //***************************************************************************
  210851. #define SENSE_VALID 0x80 // Byte 0 Bit 7
  210852. #define SENSE_FILEMRK 0x80 // Byte 2 Bit 7
  210853. #define SENSE_EOM 0x40 // Byte 2 Bit 6
  210854. #define SENSE_ILI 0x20 // Byte 2 Bit 5
  210855. //***************************************************************************
  210856. // %%% REQUEST SENSE SENSE KEY DEFINITIONS %%%
  210857. //***************************************************************************
  210858. #define KEY_NOSENSE 0x00 // No Sense
  210859. #define KEY_RECERROR 0x01 // Recovered Error
  210860. #define KEY_NOTREADY 0x02 // Not Ready
  210861. #define KEY_MEDIUMERR 0x03 // Medium Error
  210862. #define KEY_HARDERROR 0x04 // Hardware Error
  210863. #define KEY_ILLGLREQ 0x05 // Illegal Request
  210864. #define KEY_UNITATT 0x06 // Unit Attention
  210865. #define KEY_DATAPROT 0x07 // Data Protect
  210866. #define KEY_BLANKCHK 0x08 // Blank Check
  210867. #define KEY_VENDSPEC 0x09 // Vendor Specific
  210868. #define KEY_COPYABORT 0x0A // Copy Abort
  210869. #define KEY_EQUAL 0x0C // Equal (Search)
  210870. #define KEY_VOLOVRFLW 0x0D // Volume Overflow
  210871. #define KEY_MISCOMP 0x0E // Miscompare (Search)
  210872. #define KEY_RESERVED 0x0F // Reserved
  210873. //***************************************************************************
  210874. // %%% PERIPHERAL DEVICE TYPE DEFINITIONS %%%
  210875. //***************************************************************************
  210876. #define DTYPE_DASD 0x00 // Disk Device
  210877. #define DTYPE_SEQD 0x01 // Tape Device
  210878. #define DTYPE_PRNT 0x02 // Printer
  210879. #define DTYPE_PROC 0x03 // Processor
  210880. #define DTYPE_WORM 0x04 // Write-once read-multiple
  210881. #define DTYPE_CROM 0x05 // CD-ROM device
  210882. #define DTYPE_SCAN 0x06 // Scanner device
  210883. #define DTYPE_OPTI 0x07 // Optical memory device
  210884. #define DTYPE_JUKE 0x08 // Medium Changer device
  210885. #define DTYPE_COMM 0x09 // Communications device
  210886. #define DTYPE_RESL 0x0A // Reserved (low)
  210887. #define DTYPE_RESH 0x1E // Reserved (high)
  210888. #define DTYPE_UNKNOWN 0x1F // Unknown or no device type
  210889. //***************************************************************************
  210890. // %%% ANSI APPROVED VERSION DEFINITIONS %%%
  210891. //***************************************************************************
  210892. #define ANSI_MAYBE 0x0 // Device may or may not be ANSI approved stand
  210893. #define ANSI_SCSI1 0x1 // Device complies to ANSI X3.131-1986 (SCSI-1)
  210894. #define ANSI_SCSI2 0x2 // Device complies to SCSI-2
  210895. #define ANSI_RESLO 0x3 // Reserved (low)
  210896. #define ANSI_RESHI 0x7 // Reserved (high)
  210897. typedef struct
  210898. {
  210899. USHORT Length;
  210900. UCHAR ScsiStatus;
  210901. UCHAR PathId;
  210902. UCHAR TargetId;
  210903. UCHAR Lun;
  210904. UCHAR CdbLength;
  210905. UCHAR SenseInfoLength;
  210906. UCHAR DataIn;
  210907. ULONG DataTransferLength;
  210908. ULONG TimeOutValue;
  210909. ULONG DataBufferOffset;
  210910. ULONG SenseInfoOffset;
  210911. UCHAR Cdb[16];
  210912. } SCSI_PASS_THROUGH, *PSCSI_PASS_THROUGH;
  210913. typedef struct
  210914. {
  210915. USHORT Length;
  210916. UCHAR ScsiStatus;
  210917. UCHAR PathId;
  210918. UCHAR TargetId;
  210919. UCHAR Lun;
  210920. UCHAR CdbLength;
  210921. UCHAR SenseInfoLength;
  210922. UCHAR DataIn;
  210923. ULONG DataTransferLength;
  210924. ULONG TimeOutValue;
  210925. PVOID DataBuffer;
  210926. ULONG SenseInfoOffset;
  210927. UCHAR Cdb[16];
  210928. } SCSI_PASS_THROUGH_DIRECT, *PSCSI_PASS_THROUGH_DIRECT;
  210929. typedef struct
  210930. {
  210931. SCSI_PASS_THROUGH_DIRECT spt;
  210932. ULONG Filler;
  210933. UCHAR ucSenseBuf[32];
  210934. } SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, *PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER;
  210935. typedef struct
  210936. {
  210937. ULONG Length;
  210938. UCHAR PortNumber;
  210939. UCHAR PathId;
  210940. UCHAR TargetId;
  210941. UCHAR Lun;
  210942. } SCSI_ADDRESS, *PSCSI_ADDRESS;
  210943. #define METHOD_BUFFERED 0
  210944. #define METHOD_IN_DIRECT 1
  210945. #define METHOD_OUT_DIRECT 2
  210946. #define METHOD_NEITHER 3
  210947. #define FILE_ANY_ACCESS 0
  210948. #ifndef FILE_READ_ACCESS
  210949. #define FILE_READ_ACCESS (0x0001)
  210950. #endif
  210951. #ifndef FILE_WRITE_ACCESS
  210952. #define FILE_WRITE_ACCESS (0x0002)
  210953. #endif
  210954. #define IOCTL_SCSI_BASE 0x00000004
  210955. #define SCSI_IOCTL_DATA_OUT 0
  210956. #define SCSI_IOCTL_DATA_IN 1
  210957. #define SCSI_IOCTL_DATA_UNSPECIFIED 2
  210958. #define CTL_CODE2( DevType, Function, Method, Access ) ( \
  210959. ((DevType) << 16) | ((Access) << 14) | ((Function) << 2) | (Method) \
  210960. )
  210961. #define IOCTL_SCSI_PASS_THROUGH CTL_CODE2( IOCTL_SCSI_BASE, 0x0401, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210962. #define IOCTL_SCSI_GET_CAPABILITIES CTL_CODE2( IOCTL_SCSI_BASE, 0x0404, METHOD_BUFFERED, FILE_ANY_ACCESS)
  210963. #define IOCTL_SCSI_PASS_THROUGH_DIRECT CTL_CODE2( IOCTL_SCSI_BASE, 0x0405, METHOD_BUFFERED, FILE_READ_ACCESS | FILE_WRITE_ACCESS )
  210964. #define IOCTL_SCSI_GET_ADDRESS CTL_CODE2( IOCTL_SCSI_BASE, 0x0406, METHOD_BUFFERED, FILE_ANY_ACCESS )
  210965. #define SENSE_LEN 14
  210966. #define SRB_DIR_SCSI 0x00
  210967. #define SRB_POSTING 0x01
  210968. #define SRB_ENABLE_RESIDUAL_COUNT 0x04
  210969. #define SRB_DIR_IN 0x08
  210970. #define SRB_DIR_OUT 0x10
  210971. #define SRB_EVENT_NOTIFY 0x40
  210972. #define RESIDUAL_COUNT_SUPPORTED 0x02
  210973. #define MAX_SRB_TIMEOUT 1080001u
  210974. #define DEFAULT_SRB_TIMEOUT 1080001u
  210975. #define SC_HA_INQUIRY 0x00
  210976. #define SC_GET_DEV_TYPE 0x01
  210977. #define SC_EXEC_SCSI_CMD 0x02
  210978. #define SC_ABORT_SRB 0x03
  210979. #define SC_RESET_DEV 0x04
  210980. #define SC_SET_HA_PARMS 0x05
  210981. #define SC_GET_DISK_INFO 0x06
  210982. #define SC_RESCAN_SCSI_BUS 0x07
  210983. #define SC_GETSET_TIMEOUTS 0x08
  210984. #define SS_PENDING 0x00
  210985. #define SS_COMP 0x01
  210986. #define SS_ABORTED 0x02
  210987. #define SS_ABORT_FAIL 0x03
  210988. #define SS_ERR 0x04
  210989. #define SS_INVALID_CMD 0x80
  210990. #define SS_INVALID_HA 0x81
  210991. #define SS_NO_DEVICE 0x82
  210992. #define SS_INVALID_SRB 0xE0
  210993. #define SS_OLD_MANAGER 0xE1
  210994. #define SS_BUFFER_ALIGN 0xE1
  210995. #define SS_ILLEGAL_MODE 0xE2
  210996. #define SS_NO_ASPI 0xE3
  210997. #define SS_FAILED_INIT 0xE4
  210998. #define SS_ASPI_IS_BUSY 0xE5
  210999. #define SS_BUFFER_TO_BIG 0xE6
  211000. #define SS_BUFFER_TOO_BIG 0xE6
  211001. #define SS_MISMATCHED_COMPONENTS 0xE7
  211002. #define SS_NO_ADAPTERS 0xE8
  211003. #define SS_INSUFFICIENT_RESOURCES 0xE9
  211004. #define SS_ASPI_IS_SHUTDOWN 0xEA
  211005. #define SS_BAD_INSTALL 0xEB
  211006. #define HASTAT_OK 0x00
  211007. #define HASTAT_SEL_TO 0x11
  211008. #define HASTAT_DO_DU 0x12
  211009. #define HASTAT_BUS_FREE 0x13
  211010. #define HASTAT_PHASE_ERR 0x14
  211011. #define HASTAT_TIMEOUT 0x09
  211012. #define HASTAT_COMMAND_TIMEOUT 0x0B
  211013. #define HASTAT_MESSAGE_REJECT 0x0D
  211014. #define HASTAT_BUS_RESET 0x0E
  211015. #define HASTAT_PARITY_ERROR 0x0F
  211016. #define HASTAT_REQUEST_SENSE_FAILED 0x10
  211017. #define PACKED
  211018. #pragma pack(1)
  211019. typedef struct
  211020. {
  211021. BYTE SRB_Cmd;
  211022. BYTE SRB_Status;
  211023. BYTE SRB_HaID;
  211024. BYTE SRB_Flags;
  211025. DWORD SRB_Hdr_Rsvd;
  211026. BYTE HA_Count;
  211027. BYTE HA_SCSI_ID;
  211028. BYTE HA_ManagerId[16];
  211029. BYTE HA_Identifier[16];
  211030. BYTE HA_Unique[16];
  211031. WORD HA_Rsvd1;
  211032. BYTE pad[20];
  211033. } PACKED SRB_HAInquiry, *PSRB_HAInquiry, FAR *LPSRB_HAInquiry;
  211034. typedef struct
  211035. {
  211036. BYTE SRB_Cmd;
  211037. BYTE SRB_Status;
  211038. BYTE SRB_HaID;
  211039. BYTE SRB_Flags;
  211040. DWORD SRB_Hdr_Rsvd;
  211041. BYTE SRB_Target;
  211042. BYTE SRB_Lun;
  211043. BYTE SRB_DeviceType;
  211044. BYTE SRB_Rsvd1;
  211045. BYTE pad[68];
  211046. } PACKED SRB_GDEVBlock, *PSRB_GDEVBlock, FAR *LPSRB_GDEVBlock;
  211047. typedef struct
  211048. {
  211049. BYTE SRB_Cmd;
  211050. BYTE SRB_Status;
  211051. BYTE SRB_HaID;
  211052. BYTE SRB_Flags;
  211053. DWORD SRB_Hdr_Rsvd;
  211054. BYTE SRB_Target;
  211055. BYTE SRB_Lun;
  211056. WORD SRB_Rsvd1;
  211057. DWORD SRB_BufLen;
  211058. BYTE FAR *SRB_BufPointer;
  211059. BYTE SRB_SenseLen;
  211060. BYTE SRB_CDBLen;
  211061. BYTE SRB_HaStat;
  211062. BYTE SRB_TargStat;
  211063. VOID FAR *SRB_PostProc;
  211064. BYTE SRB_Rsvd2[20];
  211065. BYTE CDBByte[16];
  211066. BYTE SenseArea[SENSE_LEN+2];
  211067. } PACKED SRB_ExecSCSICmd, *PSRB_ExecSCSICmd, FAR *LPSRB_ExecSCSICmd;
  211068. typedef struct
  211069. {
  211070. BYTE SRB_Cmd;
  211071. BYTE SRB_Status;
  211072. BYTE SRB_HaId;
  211073. BYTE SRB_Flags;
  211074. DWORD SRB_Hdr_Rsvd;
  211075. } PACKED SRB, *PSRB, FAR *LPSRB;
  211076. #pragma pack()
  211077. struct CDDeviceInfo
  211078. {
  211079. char vendor[9];
  211080. char productId[17];
  211081. char rev[5];
  211082. char vendorSpec[21];
  211083. BYTE ha;
  211084. BYTE tgt;
  211085. BYTE lun;
  211086. char scsiDriveLetter; // will be 0 if not using scsi
  211087. };
  211088. class CDReadBuffer
  211089. {
  211090. public:
  211091. int startFrame;
  211092. int numFrames;
  211093. int dataStartOffset;
  211094. int dataLength;
  211095. BYTE* buffer;
  211096. int bufferSize;
  211097. int index;
  211098. bool wantsIndex;
  211099. CDReadBuffer (const int numberOfFrames)
  211100. : startFrame (0),
  211101. numFrames (0),
  211102. dataStartOffset (0),
  211103. dataLength (0),
  211104. index (0),
  211105. wantsIndex (false)
  211106. {
  211107. bufferSize = 2352 * numberOfFrames;
  211108. buffer = (BYTE*) malloc (bufferSize);
  211109. }
  211110. ~CDReadBuffer()
  211111. {
  211112. free (buffer);
  211113. }
  211114. bool isZero() const
  211115. {
  211116. BYTE* p = buffer + dataStartOffset;
  211117. for (int i = dataLength; --i >= 0;)
  211118. if (*p++ != 0)
  211119. return false;
  211120. return true;
  211121. }
  211122. };
  211123. class CDDeviceHandle;
  211124. class CDController
  211125. {
  211126. public:
  211127. CDController();
  211128. virtual ~CDController();
  211129. virtual bool read (CDReadBuffer* t) = 0;
  211130. virtual void shutDown();
  211131. bool readAudio (CDReadBuffer* t, CDReadBuffer* overlapBuffer = 0);
  211132. int getLastIndex();
  211133. public:
  211134. bool initialised;
  211135. CDDeviceHandle* deviceInfo;
  211136. int framesToCheck, framesOverlap;
  211137. void prepare (SRB_ExecSCSICmd& s);
  211138. void perform (SRB_ExecSCSICmd& s);
  211139. void setPaused (bool paused);
  211140. };
  211141. #pragma pack(1)
  211142. struct TOCTRACK
  211143. {
  211144. BYTE rsvd;
  211145. BYTE ADR;
  211146. BYTE trackNumber;
  211147. BYTE rsvd2;
  211148. BYTE addr[4];
  211149. };
  211150. struct TOC
  211151. {
  211152. WORD tocLen;
  211153. BYTE firstTrack;
  211154. BYTE lastTrack;
  211155. TOCTRACK tracks[100];
  211156. };
  211157. #pragma pack()
  211158. enum
  211159. {
  211160. READTYPE_ANY = 0,
  211161. READTYPE_ATAPI1 = 1,
  211162. READTYPE_ATAPI2 = 2,
  211163. READTYPE_READ6 = 3,
  211164. READTYPE_READ10 = 4,
  211165. READTYPE_READ_D8 = 5,
  211166. READTYPE_READ_D4 = 6,
  211167. READTYPE_READ_D4_1 = 7,
  211168. READTYPE_READ10_2 = 8
  211169. };
  211170. class CDDeviceHandle
  211171. {
  211172. public:
  211173. CDDeviceHandle (const CDDeviceInfo* const device)
  211174. : scsiHandle (0),
  211175. readType (READTYPE_ANY),
  211176. controller (0)
  211177. {
  211178. memcpy (&info, device, sizeof (info));
  211179. }
  211180. ~CDDeviceHandle()
  211181. {
  211182. if (controller != 0)
  211183. {
  211184. controller->shutDown();
  211185. delete controller;
  211186. }
  211187. if (scsiHandle != 0)
  211188. CloseHandle (scsiHandle);
  211189. }
  211190. bool readTOC (TOC* lpToc, bool useMSF);
  211191. bool readAudio (CDReadBuffer* buffer, CDReadBuffer* overlapBuffer = 0);
  211192. void openDrawer (bool shouldBeOpen);
  211193. CDDeviceInfo info;
  211194. HANDLE scsiHandle;
  211195. BYTE readType;
  211196. private:
  211197. CDController* controller;
  211198. bool testController (const int readType,
  211199. CDController* const newController,
  211200. CDReadBuffer* const bufferToUse);
  211201. };
  211202. DWORD (*fGetASPI32SupportInfo)(void);
  211203. DWORD (*fSendASPI32Command)(LPSRB);
  211204. static HINSTANCE winAspiLib = 0;
  211205. static bool usingScsi = false;
  211206. static bool initialised = false;
  211207. static bool InitialiseCDRipper()
  211208. {
  211209. if (! initialised)
  211210. {
  211211. initialised = true;
  211212. OSVERSIONINFO info;
  211213. info.dwOSVersionInfoSize = sizeof (info);
  211214. GetVersionEx (&info);
  211215. usingScsi = (info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4);
  211216. if (! usingScsi)
  211217. {
  211218. fGetASPI32SupportInfo = 0;
  211219. fSendASPI32Command = 0;
  211220. winAspiLib = LoadLibrary (_T("WNASPI32.DLL"));
  211221. if (winAspiLib != 0)
  211222. {
  211223. fGetASPI32SupportInfo = (DWORD(*)(void)) GetProcAddress (winAspiLib, "GetASPI32SupportInfo");
  211224. fSendASPI32Command = (DWORD(*)(LPSRB)) GetProcAddress (winAspiLib, "SendASPI32Command");
  211225. if (fGetASPI32SupportInfo == 0 || fSendASPI32Command == 0)
  211226. return false;
  211227. }
  211228. else
  211229. {
  211230. usingScsi = true;
  211231. }
  211232. }
  211233. }
  211234. return true;
  211235. }
  211236. static void DeinitialiseCDRipper()
  211237. {
  211238. if (winAspiLib != 0)
  211239. {
  211240. fGetASPI32SupportInfo = 0;
  211241. fSendASPI32Command = 0;
  211242. FreeLibrary (winAspiLib);
  211243. winAspiLib = 0;
  211244. }
  211245. initialised = false;
  211246. }
  211247. static HANDLE CreateSCSIDeviceHandle (char driveLetter)
  211248. {
  211249. TCHAR devicePath[8];
  211250. devicePath[0] = '\\';
  211251. devicePath[1] = '\\';
  211252. devicePath[2] = '.';
  211253. devicePath[3] = '\\';
  211254. devicePath[4] = driveLetter;
  211255. devicePath[5] = ':';
  211256. devicePath[6] = 0;
  211257. OSVERSIONINFO info;
  211258. info.dwOSVersionInfoSize = sizeof (info);
  211259. GetVersionEx (&info);
  211260. DWORD flags = GENERIC_READ;
  211261. if ((info.dwPlatformId == VER_PLATFORM_WIN32_NT) && (info.dwMajorVersion > 4))
  211262. flags = GENERIC_READ | GENERIC_WRITE;
  211263. HANDLE h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211264. if (h == INVALID_HANDLE_VALUE)
  211265. {
  211266. flags ^= GENERIC_WRITE;
  211267. h = CreateFile (devicePath, flags, FILE_SHARE_WRITE | FILE_SHARE_READ, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0);
  211268. }
  211269. return h;
  211270. }
  211271. static DWORD performScsiPassThroughCommand (const LPSRB_ExecSCSICmd srb,
  211272. const char driveLetter,
  211273. HANDLE& deviceHandle,
  211274. const bool retryOnFailure = true)
  211275. {
  211276. SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER s;
  211277. zerostruct (s);
  211278. s.spt.Length = sizeof (SCSI_PASS_THROUGH);
  211279. s.spt.CdbLength = srb->SRB_CDBLen;
  211280. s.spt.DataIn = (BYTE) ((srb->SRB_Flags & SRB_DIR_IN)
  211281. ? SCSI_IOCTL_DATA_IN
  211282. : ((srb->SRB_Flags & SRB_DIR_OUT)
  211283. ? SCSI_IOCTL_DATA_OUT
  211284. : SCSI_IOCTL_DATA_UNSPECIFIED));
  211285. s.spt.DataTransferLength = srb->SRB_BufLen;
  211286. s.spt.TimeOutValue = 5;
  211287. s.spt.DataBuffer = srb->SRB_BufPointer;
  211288. s.spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211289. memcpy (s.spt.Cdb, srb->CDBByte, srb->SRB_CDBLen);
  211290. srb->SRB_Status = SS_ERR;
  211291. srb->SRB_TargStat = 0x0004;
  211292. DWORD bytesReturned = 0;
  211293. if (DeviceIoControl (deviceHandle, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211294. &s, sizeof (s),
  211295. &s, sizeof (s),
  211296. &bytesReturned, 0) != 0)
  211297. {
  211298. srb->SRB_Status = SS_COMP;
  211299. }
  211300. else if (retryOnFailure)
  211301. {
  211302. const DWORD error = GetLastError();
  211303. if ((error == ERROR_MEDIA_CHANGED) || (error == ERROR_INVALID_HANDLE))
  211304. {
  211305. if (error != ERROR_INVALID_HANDLE)
  211306. CloseHandle (deviceHandle);
  211307. deviceHandle = CreateSCSIDeviceHandle (driveLetter);
  211308. return performScsiPassThroughCommand (srb, driveLetter, deviceHandle, false);
  211309. }
  211310. }
  211311. return srb->SRB_Status;
  211312. }
  211313. // Controller types..
  211314. class ControllerType1 : public CDController
  211315. {
  211316. public:
  211317. ControllerType1() {}
  211318. ~ControllerType1() {}
  211319. bool read (CDReadBuffer* rb)
  211320. {
  211321. if (rb->numFrames * 2352 > rb->bufferSize)
  211322. return false;
  211323. SRB_ExecSCSICmd s;
  211324. prepare (s);
  211325. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211326. s.SRB_BufLen = rb->bufferSize;
  211327. s.SRB_BufPointer = rb->buffer;
  211328. s.SRB_CDBLen = 12;
  211329. s.CDBByte[0] = 0xBE;
  211330. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211331. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211332. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211333. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211334. s.CDBByte[9] = (BYTE)((deviceInfo->readType == READTYPE_ATAPI1) ? 0x10 : 0xF0);
  211335. perform (s);
  211336. if (s.SRB_Status != SS_COMP)
  211337. return false;
  211338. rb->dataLength = rb->numFrames * 2352;
  211339. rb->dataStartOffset = 0;
  211340. return true;
  211341. }
  211342. };
  211343. class ControllerType2 : public CDController
  211344. {
  211345. public:
  211346. ControllerType2() {}
  211347. ~ControllerType2() {}
  211348. void shutDown()
  211349. {
  211350. if (initialised)
  211351. {
  211352. BYTE bufPointer[] = { 0, 0, 0, 8, 83, 0, 0, 0, 0, 0, 8, 0 };
  211353. SRB_ExecSCSICmd s;
  211354. prepare (s);
  211355. s.SRB_Flags = SRB_EVENT_NOTIFY | SRB_ENABLE_RESIDUAL_COUNT;
  211356. s.SRB_BufLen = 0x0C;
  211357. s.SRB_BufPointer = bufPointer;
  211358. s.SRB_CDBLen = 6;
  211359. s.CDBByte[0] = 0x15;
  211360. s.CDBByte[4] = 0x0C;
  211361. perform (s);
  211362. }
  211363. }
  211364. bool init()
  211365. {
  211366. SRB_ExecSCSICmd s;
  211367. s.SRB_Status = SS_ERR;
  211368. if (deviceInfo->readType == READTYPE_READ10_2)
  211369. {
  211370. BYTE bufPointer1[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 35, 6, 0, 0, 0, 0, 0, 128 };
  211371. BYTE bufPointer2[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48, 1, 6, 32, 7, 0, 0, 0, 0 };
  211372. for (int i = 0; i < 2; ++i)
  211373. {
  211374. prepare (s);
  211375. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211376. s.SRB_BufLen = 0x14;
  211377. s.SRB_BufPointer = (i == 0) ? bufPointer1 : bufPointer2;
  211378. s.SRB_CDBLen = 6;
  211379. s.CDBByte[0] = 0x15;
  211380. s.CDBByte[1] = 0x10;
  211381. s.CDBByte[4] = 0x14;
  211382. perform (s);
  211383. if (s.SRB_Status != SS_COMP)
  211384. return false;
  211385. }
  211386. }
  211387. else
  211388. {
  211389. BYTE bufPointer[] = { 0, 0, 0, 8, 0, 0, 0, 0, 0, 0, 9, 48 };
  211390. prepare (s);
  211391. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211392. s.SRB_BufLen = 0x0C;
  211393. s.SRB_BufPointer = bufPointer;
  211394. s.SRB_CDBLen = 6;
  211395. s.CDBByte[0] = 0x15;
  211396. s.CDBByte[4] = 0x0C;
  211397. perform (s);
  211398. }
  211399. return s.SRB_Status == SS_COMP;
  211400. }
  211401. bool read (CDReadBuffer* rb)
  211402. {
  211403. if (rb->numFrames * 2352 > rb->bufferSize)
  211404. return false;
  211405. if (!initialised)
  211406. {
  211407. initialised = init();
  211408. if (!initialised)
  211409. return false;
  211410. }
  211411. SRB_ExecSCSICmd s;
  211412. prepare (s);
  211413. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211414. s.SRB_BufLen = rb->bufferSize;
  211415. s.SRB_BufPointer = rb->buffer;
  211416. s.SRB_CDBLen = 10;
  211417. s.CDBByte[0] = 0x28;
  211418. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211419. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211420. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211421. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211422. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211423. perform (s);
  211424. if (s.SRB_Status != SS_COMP)
  211425. return false;
  211426. rb->dataLength = rb->numFrames * 2352;
  211427. rb->dataStartOffset = 0;
  211428. return true;
  211429. }
  211430. };
  211431. class ControllerType3 : public CDController
  211432. {
  211433. public:
  211434. ControllerType3() {}
  211435. ~ControllerType3() {}
  211436. bool read (CDReadBuffer* rb)
  211437. {
  211438. if (rb->numFrames * 2352 > rb->bufferSize)
  211439. return false;
  211440. if (!initialised)
  211441. {
  211442. setPaused (false);
  211443. initialised = true;
  211444. }
  211445. SRB_ExecSCSICmd s;
  211446. prepare (s);
  211447. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211448. s.SRB_BufLen = rb->numFrames * 2352;
  211449. s.SRB_BufPointer = rb->buffer;
  211450. s.SRB_CDBLen = 12;
  211451. s.CDBByte[0] = 0xD8;
  211452. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211453. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211454. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211455. s.CDBByte[9] = (BYTE)(rb->numFrames & 0xFF);
  211456. perform (s);
  211457. if (s.SRB_Status != SS_COMP)
  211458. return false;
  211459. rb->dataLength = rb->numFrames * 2352;
  211460. rb->dataStartOffset = 0;
  211461. return true;
  211462. }
  211463. };
  211464. class ControllerType4 : public CDController
  211465. {
  211466. public:
  211467. ControllerType4() {}
  211468. ~ControllerType4() {}
  211469. bool selectD4Mode()
  211470. {
  211471. BYTE bufPointer[12] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 9, 48 };
  211472. SRB_ExecSCSICmd s;
  211473. prepare (s);
  211474. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211475. s.SRB_CDBLen = 6;
  211476. s.SRB_BufLen = 12;
  211477. s.SRB_BufPointer = bufPointer;
  211478. s.CDBByte[0] = 0x15;
  211479. s.CDBByte[1] = 0x10;
  211480. s.CDBByte[4] = 0x08;
  211481. perform (s);
  211482. return s.SRB_Status == SS_COMP;
  211483. }
  211484. bool read (CDReadBuffer* rb)
  211485. {
  211486. if (rb->numFrames * 2352 > rb->bufferSize)
  211487. return false;
  211488. if (!initialised)
  211489. {
  211490. setPaused (true);
  211491. if (deviceInfo->readType == READTYPE_READ_D4_1)
  211492. selectD4Mode();
  211493. initialised = true;
  211494. }
  211495. SRB_ExecSCSICmd s;
  211496. prepare (s);
  211497. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211498. s.SRB_BufLen = rb->bufferSize;
  211499. s.SRB_BufPointer = rb->buffer;
  211500. s.SRB_CDBLen = 10;
  211501. s.CDBByte[0] = 0xD4;
  211502. s.CDBByte[3] = (BYTE)((rb->startFrame >> 16) & 0xFF);
  211503. s.CDBByte[4] = (BYTE)((rb->startFrame >> 8) & 0xFF);
  211504. s.CDBByte[5] = (BYTE)(rb->startFrame & 0xFF);
  211505. s.CDBByte[8] = (BYTE)(rb->numFrames & 0xFF);
  211506. perform (s);
  211507. if (s.SRB_Status != SS_COMP)
  211508. return false;
  211509. rb->dataLength = rb->numFrames * 2352;
  211510. rb->dataStartOffset = 0;
  211511. return true;
  211512. }
  211513. };
  211514. CDController::CDController() : initialised (false)
  211515. {
  211516. }
  211517. CDController::~CDController()
  211518. {
  211519. }
  211520. void CDController::prepare (SRB_ExecSCSICmd& s)
  211521. {
  211522. zerostruct (s);
  211523. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211524. s.SRB_HaID = deviceInfo->info.ha;
  211525. s.SRB_Target = deviceInfo->info.tgt;
  211526. s.SRB_Lun = deviceInfo->info.lun;
  211527. s.SRB_SenseLen = SENSE_LEN;
  211528. }
  211529. void CDController::perform (SRB_ExecSCSICmd& s)
  211530. {
  211531. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211532. s.SRB_PostProc = (void*)event;
  211533. ResetEvent (event);
  211534. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s,
  211535. deviceInfo->info.scsiDriveLetter,
  211536. deviceInfo->scsiHandle)
  211537. : fSendASPI32Command ((LPSRB)&s);
  211538. if (status == SS_PENDING)
  211539. WaitForSingleObject (event, 4000);
  211540. CloseHandle (event);
  211541. }
  211542. void CDController::setPaused (bool paused)
  211543. {
  211544. SRB_ExecSCSICmd s;
  211545. prepare (s);
  211546. s.SRB_Flags = SRB_EVENT_NOTIFY;
  211547. s.SRB_CDBLen = 10;
  211548. s.CDBByte[0] = 0x4B;
  211549. s.CDBByte[8] = (BYTE) (paused ? 0 : 1);
  211550. perform (s);
  211551. }
  211552. void CDController::shutDown()
  211553. {
  211554. }
  211555. bool CDController::readAudio (CDReadBuffer* rb, CDReadBuffer* overlapBuffer)
  211556. {
  211557. if (overlapBuffer != 0)
  211558. {
  211559. const bool canDoJitter = (overlapBuffer->bufferSize >= 2352 * framesToCheck);
  211560. const bool doJitter = canDoJitter && ! overlapBuffer->isZero();
  211561. if (doJitter
  211562. && overlapBuffer->startFrame > 0
  211563. && overlapBuffer->numFrames > 0
  211564. && overlapBuffer->dataLength > 0)
  211565. {
  211566. const int numFrames = rb->numFrames;
  211567. if (overlapBuffer->startFrame == (rb->startFrame - framesToCheck))
  211568. {
  211569. rb->startFrame -= framesOverlap;
  211570. if (framesToCheck < framesOverlap
  211571. && numFrames + framesOverlap <= rb->bufferSize / 2352)
  211572. rb->numFrames += framesOverlap;
  211573. }
  211574. else
  211575. {
  211576. overlapBuffer->dataLength = 0;
  211577. overlapBuffer->startFrame = 0;
  211578. overlapBuffer->numFrames = 0;
  211579. }
  211580. }
  211581. if (! read (rb))
  211582. return false;
  211583. if (doJitter)
  211584. {
  211585. const int checkLen = framesToCheck * 2352;
  211586. const int maxToCheck = rb->dataLength - checkLen;
  211587. if (overlapBuffer->dataLength == 0 || overlapBuffer->isZero())
  211588. return true;
  211589. BYTE* const p = overlapBuffer->buffer + overlapBuffer->dataStartOffset;
  211590. bool found = false;
  211591. for (int i = 0; i < maxToCheck; ++i)
  211592. {
  211593. if (!memcmp (p, rb->buffer + i, checkLen))
  211594. {
  211595. i += checkLen;
  211596. rb->dataStartOffset = i;
  211597. rb->dataLength -= i;
  211598. rb->startFrame = overlapBuffer->startFrame + framesToCheck;
  211599. found = true;
  211600. break;
  211601. }
  211602. }
  211603. rb->numFrames = rb->dataLength / 2352;
  211604. rb->dataLength = 2352 * rb->numFrames;
  211605. if (!found)
  211606. return false;
  211607. }
  211608. if (canDoJitter)
  211609. {
  211610. memcpy (overlapBuffer->buffer,
  211611. rb->buffer + rb->dataStartOffset + 2352 * (rb->numFrames - framesToCheck),
  211612. 2352 * framesToCheck);
  211613. overlapBuffer->startFrame = rb->startFrame + rb->numFrames - framesToCheck;
  211614. overlapBuffer->numFrames = framesToCheck;
  211615. overlapBuffer->dataLength = 2352 * framesToCheck;
  211616. overlapBuffer->dataStartOffset = 0;
  211617. }
  211618. else
  211619. {
  211620. overlapBuffer->startFrame = 0;
  211621. overlapBuffer->numFrames = 0;
  211622. overlapBuffer->dataLength = 0;
  211623. }
  211624. return true;
  211625. }
  211626. else
  211627. {
  211628. return read (rb);
  211629. }
  211630. }
  211631. int CDController::getLastIndex()
  211632. {
  211633. char qdata[100];
  211634. SRB_ExecSCSICmd s;
  211635. prepare (s);
  211636. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211637. s.SRB_BufLen = sizeof (qdata);
  211638. s.SRB_BufPointer = (BYTE*)qdata;
  211639. s.SRB_CDBLen = 12;
  211640. s.CDBByte[0] = 0x42;
  211641. s.CDBByte[1] = (BYTE)(deviceInfo->info.lun << 5);
  211642. s.CDBByte[2] = 64;
  211643. s.CDBByte[3] = 1; // get current position
  211644. s.CDBByte[7] = 0;
  211645. s.CDBByte[8] = (BYTE)sizeof (qdata);
  211646. perform (s);
  211647. if (s.SRB_Status == SS_COMP)
  211648. return qdata[7];
  211649. return 0;
  211650. }
  211651. bool CDDeviceHandle::readTOC (TOC* lpToc, bool useMSF)
  211652. {
  211653. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211654. SRB_ExecSCSICmd s;
  211655. zerostruct (s);
  211656. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211657. s.SRB_HaID = info.ha;
  211658. s.SRB_Target = info.tgt;
  211659. s.SRB_Lun = info.lun;
  211660. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211661. s.SRB_BufLen = 0x324;
  211662. s.SRB_BufPointer = (BYTE*)lpToc;
  211663. s.SRB_SenseLen = 0x0E;
  211664. s.SRB_CDBLen = 0x0A;
  211665. s.SRB_PostProc = (void*)event;
  211666. s.CDBByte[0] = 0x43;
  211667. s.CDBByte[1] = (BYTE)(useMSF ? 0x02 : 0x00);
  211668. s.CDBByte[7] = 0x03;
  211669. s.CDBByte[8] = 0x24;
  211670. ResetEvent (event);
  211671. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211672. : fSendASPI32Command ((LPSRB)&s);
  211673. if (status == SS_PENDING)
  211674. WaitForSingleObject (event, 4000);
  211675. CloseHandle (event);
  211676. return (s.SRB_Status == SS_COMP);
  211677. }
  211678. bool CDDeviceHandle::readAudio (CDReadBuffer* const buffer,
  211679. CDReadBuffer* const overlapBuffer)
  211680. {
  211681. if (controller == 0)
  211682. {
  211683. testController (READTYPE_ATAPI2, new ControllerType1(), buffer)
  211684. || testController (READTYPE_ATAPI1, new ControllerType1(), buffer)
  211685. || testController (READTYPE_READ10_2, new ControllerType2(), buffer)
  211686. || testController (READTYPE_READ10, new ControllerType2(), buffer)
  211687. || testController (READTYPE_READ_D8, new ControllerType3(), buffer)
  211688. || testController (READTYPE_READ_D4, new ControllerType4(), buffer)
  211689. || testController (READTYPE_READ_D4_1, new ControllerType4(), buffer);
  211690. }
  211691. buffer->index = 0;
  211692. if ((controller != 0)
  211693. && controller->readAudio (buffer, overlapBuffer))
  211694. {
  211695. if (buffer->wantsIndex)
  211696. buffer->index = controller->getLastIndex();
  211697. return true;
  211698. }
  211699. return false;
  211700. }
  211701. void CDDeviceHandle::openDrawer (bool shouldBeOpen)
  211702. {
  211703. if (shouldBeOpen)
  211704. {
  211705. if (controller != 0)
  211706. {
  211707. controller->shutDown();
  211708. delete controller;
  211709. controller = 0;
  211710. }
  211711. if (scsiHandle != 0)
  211712. {
  211713. CloseHandle (scsiHandle);
  211714. scsiHandle = 0;
  211715. }
  211716. }
  211717. SRB_ExecSCSICmd s;
  211718. zerostruct (s);
  211719. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211720. s.SRB_HaID = info.ha;
  211721. s.SRB_Target = info.tgt;
  211722. s.SRB_Lun = info.lun;
  211723. s.SRB_SenseLen = SENSE_LEN;
  211724. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211725. s.SRB_BufLen = 0;
  211726. s.SRB_BufPointer = 0;
  211727. s.SRB_CDBLen = 12;
  211728. s.CDBByte[0] = 0x1b;
  211729. s.CDBByte[1] = (BYTE)(info.lun << 5);
  211730. s.CDBByte[4] = (BYTE)((shouldBeOpen) ? 2 : 3);
  211731. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211732. s.SRB_PostProc = (void*)event;
  211733. ResetEvent (event);
  211734. DWORD status = (usingScsi) ? performScsiPassThroughCommand ((LPSRB_ExecSCSICmd)&s, info.scsiDriveLetter, scsiHandle)
  211735. : fSendASPI32Command ((LPSRB)&s);
  211736. if (status == SS_PENDING)
  211737. WaitForSingleObject (event, 4000);
  211738. CloseHandle (event);
  211739. }
  211740. bool CDDeviceHandle::testController (const int type,
  211741. CDController* const newController,
  211742. CDReadBuffer* const rb)
  211743. {
  211744. controller = newController;
  211745. readType = (BYTE)type;
  211746. controller->deviceInfo = this;
  211747. controller->framesToCheck = 1;
  211748. controller->framesOverlap = 3;
  211749. bool passed = false;
  211750. memset (rb->buffer, 0xcd, rb->bufferSize);
  211751. if (controller->read (rb))
  211752. {
  211753. passed = true;
  211754. int* p = (int*) (rb->buffer + rb->dataStartOffset);
  211755. int wrong = 0;
  211756. for (int i = rb->dataLength / 4; --i >= 0;)
  211757. {
  211758. if (*p++ == (int) 0xcdcdcdcd)
  211759. {
  211760. if (++wrong == 4)
  211761. {
  211762. passed = false;
  211763. break;
  211764. }
  211765. }
  211766. else
  211767. {
  211768. wrong = 0;
  211769. }
  211770. }
  211771. }
  211772. if (! passed)
  211773. {
  211774. controller->shutDown();
  211775. delete controller;
  211776. controller = 0;
  211777. }
  211778. return passed;
  211779. }
  211780. static void GetAspiDeviceInfo (CDDeviceInfo* dev, BYTE ha, BYTE tgt, BYTE lun)
  211781. {
  211782. HANDLE event = CreateEvent (0, TRUE, FALSE, 0);
  211783. const int bufSize = 128;
  211784. BYTE buffer[bufSize];
  211785. zeromem (buffer, bufSize);
  211786. SRB_ExecSCSICmd s;
  211787. zerostruct (s);
  211788. s.SRB_Cmd = SC_EXEC_SCSI_CMD;
  211789. s.SRB_HaID = ha;
  211790. s.SRB_Target = tgt;
  211791. s.SRB_Lun = lun;
  211792. s.SRB_Flags = SRB_DIR_IN | SRB_EVENT_NOTIFY;
  211793. s.SRB_BufLen = bufSize;
  211794. s.SRB_BufPointer = buffer;
  211795. s.SRB_SenseLen = SENSE_LEN;
  211796. s.SRB_CDBLen = 6;
  211797. s.SRB_PostProc = (void*)event;
  211798. s.CDBByte[0] = SCSI_INQUIRY;
  211799. s.CDBByte[4] = 100;
  211800. ResetEvent (event);
  211801. if (fSendASPI32Command ((LPSRB)&s) == SS_PENDING)
  211802. WaitForSingleObject (event, 4000);
  211803. CloseHandle (event);
  211804. if (s.SRB_Status == SS_COMP)
  211805. {
  211806. memcpy (dev->vendor, &buffer[8], 8);
  211807. memcpy (dev->productId, &buffer[16], 16);
  211808. memcpy (dev->rev, &buffer[32], 4);
  211809. memcpy (dev->vendorSpec, &buffer[36], 20);
  211810. }
  211811. }
  211812. static int FindCDDevices (CDDeviceInfo* const list,
  211813. int maxItems)
  211814. {
  211815. int count = 0;
  211816. if (usingScsi)
  211817. {
  211818. for (char driveLetter = 'b'; driveLetter <= 'z'; ++driveLetter)
  211819. {
  211820. TCHAR drivePath[8];
  211821. drivePath[0] = driveLetter;
  211822. drivePath[1] = ':';
  211823. drivePath[2] = '\\';
  211824. drivePath[3] = 0;
  211825. if (GetDriveType (drivePath) == DRIVE_CDROM)
  211826. {
  211827. HANDLE h = CreateSCSIDeviceHandle (driveLetter);
  211828. if (h != INVALID_HANDLE_VALUE)
  211829. {
  211830. BYTE buffer[100], passThroughStruct[1024];
  211831. zeromem (buffer, sizeof (buffer));
  211832. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211833. PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER p = (PSCSI_PASS_THROUGH_DIRECT_WITH_BUFFER)passThroughStruct;
  211834. p->spt.Length = sizeof (SCSI_PASS_THROUGH);
  211835. p->spt.CdbLength = 6;
  211836. p->spt.SenseInfoLength = 24;
  211837. p->spt.DataIn = SCSI_IOCTL_DATA_IN;
  211838. p->spt.DataTransferLength = 100;
  211839. p->spt.TimeOutValue = 2;
  211840. p->spt.DataBuffer = buffer;
  211841. p->spt.SenseInfoOffset = offsetof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER, ucSenseBuf);
  211842. p->spt.Cdb[0] = 0x12;
  211843. p->spt.Cdb[4] = 100;
  211844. DWORD bytesReturned = 0;
  211845. if (DeviceIoControl (h, IOCTL_SCSI_PASS_THROUGH_DIRECT,
  211846. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211847. p, sizeof (SCSI_PASS_THROUGH_DIRECT_WITH_BUFFER),
  211848. &bytesReturned, 0) != 0)
  211849. {
  211850. zeromem (&list[count], sizeof (CDDeviceInfo));
  211851. list[count].scsiDriveLetter = driveLetter;
  211852. memcpy (list[count].vendor, &buffer[8], 8);
  211853. memcpy (list[count].productId, &buffer[16], 16);
  211854. memcpy (list[count].rev, &buffer[32], 4);
  211855. memcpy (list[count].vendorSpec, &buffer[36], 20);
  211856. zeromem (passThroughStruct, sizeof (passThroughStruct));
  211857. PSCSI_ADDRESS scsiAddr = (PSCSI_ADDRESS)passThroughStruct;
  211858. scsiAddr->Length = sizeof (SCSI_ADDRESS);
  211859. if (DeviceIoControl (h, IOCTL_SCSI_GET_ADDRESS,
  211860. 0, 0, scsiAddr, sizeof (SCSI_ADDRESS),
  211861. &bytesReturned, 0) != 0)
  211862. {
  211863. list[count].ha = scsiAddr->PortNumber;
  211864. list[count].tgt = scsiAddr->TargetId;
  211865. list[count].lun = scsiAddr->Lun;
  211866. ++count;
  211867. }
  211868. }
  211869. CloseHandle (h);
  211870. }
  211871. }
  211872. }
  211873. }
  211874. else
  211875. {
  211876. const DWORD d = fGetASPI32SupportInfo();
  211877. BYTE status = HIBYTE (LOWORD (d));
  211878. if (status != SS_COMP || status == SS_NO_ADAPTERS)
  211879. return 0;
  211880. const int numAdapters = LOBYTE (LOWORD (d));
  211881. for (BYTE ha = 0; ha < numAdapters; ++ha)
  211882. {
  211883. SRB_HAInquiry s;
  211884. zerostruct (s);
  211885. s.SRB_Cmd = SC_HA_INQUIRY;
  211886. s.SRB_HaID = ha;
  211887. fSendASPI32Command ((LPSRB)&s);
  211888. if (s.SRB_Status == SS_COMP)
  211889. {
  211890. maxItems = (int)s.HA_Unique[3];
  211891. if (maxItems == 0)
  211892. maxItems = 8;
  211893. for (BYTE tgt = 0; tgt < maxItems; ++tgt)
  211894. {
  211895. for (BYTE lun = 0; lun < 8; ++lun)
  211896. {
  211897. SRB_GDEVBlock sb;
  211898. zerostruct (sb);
  211899. sb.SRB_Cmd = SC_GET_DEV_TYPE;
  211900. sb.SRB_HaID = ha;
  211901. sb.SRB_Target = tgt;
  211902. sb.SRB_Lun = lun;
  211903. fSendASPI32Command ((LPSRB) &sb);
  211904. if (sb.SRB_Status == SS_COMP
  211905. && sb.SRB_DeviceType == DTYPE_CROM)
  211906. {
  211907. zeromem (&list[count], sizeof (CDDeviceInfo));
  211908. list[count].ha = ha;
  211909. list[count].tgt = tgt;
  211910. list[count].lun = lun;
  211911. GetAspiDeviceInfo (&(list[count]), ha, tgt, lun);
  211912. ++count;
  211913. }
  211914. }
  211915. }
  211916. }
  211917. }
  211918. }
  211919. return count;
  211920. }
  211921. static int ripperUsers = 0;
  211922. static bool initialisedOk = false;
  211923. class DeinitialiseTimer : private Timer,
  211924. private DeletedAtShutdown
  211925. {
  211926. DeinitialiseTimer (const DeinitialiseTimer&);
  211927. const DeinitialiseTimer& operator= (const DeinitialiseTimer&);
  211928. public:
  211929. DeinitialiseTimer()
  211930. {
  211931. startTimer (4000);
  211932. }
  211933. ~DeinitialiseTimer()
  211934. {
  211935. if (--ripperUsers == 0)
  211936. DeinitialiseCDRipper();
  211937. }
  211938. void timerCallback()
  211939. {
  211940. delete this;
  211941. }
  211942. juce_UseDebuggingNewOperator
  211943. };
  211944. static void incUserCount()
  211945. {
  211946. if (ripperUsers++ == 0)
  211947. initialisedOk = InitialiseCDRipper();
  211948. }
  211949. static void decUserCount()
  211950. {
  211951. new DeinitialiseTimer();
  211952. }
  211953. struct CDDeviceWrapper
  211954. {
  211955. CDDeviceHandle* cdH;
  211956. CDReadBuffer* overlapBuffer;
  211957. bool jitter;
  211958. };
  211959. static int getAddressOf (const TOCTRACK* const t)
  211960. {
  211961. return (((DWORD)t->addr[0]) << 24) + (((DWORD)t->addr[1]) << 16) +
  211962. (((DWORD)t->addr[2]) << 8) + ((DWORD)t->addr[3]);
  211963. }
  211964. static int getMSFAddressOf (const TOCTRACK* const t)
  211965. {
  211966. return 60 * t->addr[1] + t->addr[2];
  211967. }
  211968. static const int samplesPerFrame = 44100 / 75;
  211969. static const int bytesPerFrame = samplesPerFrame * 4;
  211970. const StringArray AudioCDReader::getAvailableCDNames()
  211971. {
  211972. StringArray results;
  211973. incUserCount();
  211974. if (initialisedOk)
  211975. {
  211976. CDDeviceInfo list[8];
  211977. const int num = FindCDDevices (list, 8);
  211978. decUserCount();
  211979. for (int i = 0; i < num; ++i)
  211980. {
  211981. String s;
  211982. if (list[i].scsiDriveLetter > 0)
  211983. s << String::charToString (list[i].scsiDriveLetter).toUpperCase() << T(": ");
  211984. s << String (list[i].vendor).trim()
  211985. << T(" ") << String (list[i].productId).trim()
  211986. << T(" ") << String (list[i].rev).trim();
  211987. results.add (s);
  211988. }
  211989. }
  211990. return results;
  211991. }
  211992. static CDDeviceHandle* openHandle (const CDDeviceInfo* const device)
  211993. {
  211994. SRB_GDEVBlock s;
  211995. zerostruct (s);
  211996. s.SRB_Cmd = SC_GET_DEV_TYPE;
  211997. s.SRB_HaID = device->ha;
  211998. s.SRB_Target = device->tgt;
  211999. s.SRB_Lun = device->lun;
  212000. if (usingScsi)
  212001. {
  212002. HANDLE h = CreateSCSIDeviceHandle (device->scsiDriveLetter);
  212003. if (h != INVALID_HANDLE_VALUE)
  212004. {
  212005. CDDeviceHandle* cdh = new CDDeviceHandle (device);
  212006. cdh->scsiHandle = h;
  212007. return cdh;
  212008. }
  212009. }
  212010. else
  212011. {
  212012. if (fSendASPI32Command ((LPSRB)&s) == SS_COMP
  212013. && s.SRB_DeviceType == DTYPE_CROM)
  212014. {
  212015. return new CDDeviceHandle (device);
  212016. }
  212017. }
  212018. return 0;
  212019. }
  212020. AudioCDReader* AudioCDReader::createReaderForCD (const int deviceIndex)
  212021. {
  212022. incUserCount();
  212023. if (initialisedOk)
  212024. {
  212025. CDDeviceInfo list[8];
  212026. const int num = FindCDDevices (list, 8);
  212027. if (((unsigned int) deviceIndex) < (unsigned int) num)
  212028. {
  212029. CDDeviceHandle* const handle = openHandle (&(list[deviceIndex]));
  212030. if (handle != 0)
  212031. {
  212032. CDDeviceWrapper* const d = new CDDeviceWrapper();
  212033. d->cdH = handle;
  212034. d->overlapBuffer = new CDReadBuffer(3);
  212035. return new AudioCDReader (d);
  212036. }
  212037. }
  212038. }
  212039. decUserCount();
  212040. return 0;
  212041. }
  212042. AudioCDReader::AudioCDReader (void* handle_)
  212043. : AudioFormatReader (0, T("CD Audio")),
  212044. handle (handle_),
  212045. indexingEnabled (false),
  212046. lastIndex (0),
  212047. firstFrameInBuffer (0),
  212048. samplesInBuffer (0)
  212049. {
  212050. jassert (handle_ != 0);
  212051. refreshTrackLengths();
  212052. sampleRate = 44100.0;
  212053. bitsPerSample = 16;
  212054. lengthInSamples = getPositionOfTrackStart (numTracks);
  212055. numChannels = 2;
  212056. usesFloatingPointData = false;
  212057. buffer.setSize (4 * bytesPerFrame, true);
  212058. }
  212059. AudioCDReader::~AudioCDReader()
  212060. {
  212061. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  212062. delete device->cdH;
  212063. delete device->overlapBuffer;
  212064. delete device;
  212065. decUserCount();
  212066. }
  212067. bool AudioCDReader::read (int** destSamples,
  212068. int64 startSampleInFile,
  212069. int numSamples)
  212070. {
  212071. CDDeviceWrapper* const device = (CDDeviceWrapper*)handle;
  212072. bool ok = true;
  212073. int offset = 0;
  212074. if (startSampleInFile < 0)
  212075. {
  212076. int* l = destSamples[0];
  212077. int* r = destSamples[1];
  212078. numSamples += (int) startSampleInFile;
  212079. offset -= (int) startSampleInFile;
  212080. while (++startSampleInFile <= 0)
  212081. {
  212082. *l++ = 0;
  212083. if (r != 0)
  212084. *r++ = 0;
  212085. }
  212086. }
  212087. while (numSamples > 0)
  212088. {
  212089. const int bufferStartSample = firstFrameInBuffer * samplesPerFrame;
  212090. const int bufferEndSample = bufferStartSample + samplesInBuffer;
  212091. if (startSampleInFile >= bufferStartSample
  212092. && startSampleInFile < bufferEndSample)
  212093. {
  212094. const int toDo = (int) jmin ((int64) numSamples, bufferEndSample - startSampleInFile);
  212095. int* const l = destSamples[0] + offset;
  212096. int* const r = destSamples[1] + offset;
  212097. const short* src = (const short*) buffer.getData();
  212098. src += 2 * (startSampleInFile - bufferStartSample);
  212099. for (int i = 0; i < toDo; ++i)
  212100. {
  212101. l[i] = src [i << 1] << 16;
  212102. if (r != 0)
  212103. r[i] = src [(i << 1) + 1] << 16;
  212104. }
  212105. offset += toDo;
  212106. startSampleInFile += toDo;
  212107. numSamples -= toDo;
  212108. }
  212109. else
  212110. {
  212111. const int framesInBuffer = buffer.getSize() / bytesPerFrame;
  212112. const int frameNeeded = (int) (startSampleInFile / samplesPerFrame);
  212113. if (firstFrameInBuffer + framesInBuffer != frameNeeded)
  212114. {
  212115. device->overlapBuffer->dataLength = 0;
  212116. device->overlapBuffer->startFrame = 0;
  212117. device->overlapBuffer->numFrames = 0;
  212118. device->jitter = false;
  212119. }
  212120. firstFrameInBuffer = frameNeeded;
  212121. lastIndex = 0;
  212122. CDReadBuffer readBuffer (framesInBuffer + 4);
  212123. readBuffer.wantsIndex = indexingEnabled;
  212124. int i;
  212125. for (i = 5; --i >= 0;)
  212126. {
  212127. readBuffer.startFrame = frameNeeded;
  212128. readBuffer.numFrames = framesInBuffer;
  212129. if (device->cdH->readAudio (&readBuffer, (device->jitter) ? device->overlapBuffer : 0))
  212130. break;
  212131. else
  212132. device->overlapBuffer->dataLength = 0;
  212133. }
  212134. if (i >= 0)
  212135. {
  212136. memcpy ((char*) buffer.getData(),
  212137. readBuffer.buffer + readBuffer.dataStartOffset,
  212138. readBuffer.dataLength);
  212139. samplesInBuffer = readBuffer.dataLength >> 2;
  212140. lastIndex = readBuffer.index;
  212141. }
  212142. else
  212143. {
  212144. int* l = destSamples[0] + offset;
  212145. int* r = destSamples[1] + offset;
  212146. while (--numSamples >= 0)
  212147. {
  212148. *l++ = 0;
  212149. if (r != 0)
  212150. *r++ = 0;
  212151. }
  212152. // sometimes the read fails for just the very last couple of blocks, so
  212153. // we'll ignore and errors in the last half-second of the disk..
  212154. ok = startSampleInFile > (trackStarts [numTracks] - 20000);
  212155. break;
  212156. }
  212157. }
  212158. }
  212159. return ok;
  212160. }
  212161. bool AudioCDReader::isCDStillPresent() const
  212162. {
  212163. TOC toc;
  212164. zerostruct (toc);
  212165. return ((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false);
  212166. }
  212167. int AudioCDReader::getNumTracks() const
  212168. {
  212169. return numTracks;
  212170. }
  212171. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  212172. {
  212173. return (trackNum >= 0 && trackNum <= numTracks) ? trackStarts [trackNum] * samplesPerFrame
  212174. : 0;
  212175. }
  212176. void AudioCDReader::refreshTrackLengths()
  212177. {
  212178. zeromem (trackStarts, sizeof (trackStarts));
  212179. zeromem (audioTracks, sizeof (audioTracks));
  212180. TOC toc;
  212181. zerostruct (toc);
  212182. if (((CDDeviceWrapper*)handle)->cdH->readTOC (&toc, false))
  212183. {
  212184. numTracks = 1 + toc.lastTrack - toc.firstTrack;
  212185. for (int i = 0; i <= numTracks; ++i)
  212186. {
  212187. trackStarts[i] = getAddressOf (&toc.tracks[i]);
  212188. audioTracks[i] = ((toc.tracks[i].ADR & 4) == 0);
  212189. }
  212190. }
  212191. else
  212192. {
  212193. numTracks = 0;
  212194. }
  212195. }
  212196. bool AudioCDReader::isTrackAudio (int trackNum) const
  212197. {
  212198. return (trackNum >= 0 && trackNum <= numTracks) ? audioTracks [trackNum]
  212199. : false;
  212200. }
  212201. void AudioCDReader::enableIndexScanning (bool b)
  212202. {
  212203. indexingEnabled = b;
  212204. }
  212205. int AudioCDReader::getLastIndex() const
  212206. {
  212207. return lastIndex;
  212208. }
  212209. const int framesPerIndexRead = 4;
  212210. int AudioCDReader::getIndexAt (int samplePos)
  212211. {
  212212. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212213. const int frameNeeded = samplePos / samplesPerFrame;
  212214. device->overlapBuffer->dataLength = 0;
  212215. device->overlapBuffer->startFrame = 0;
  212216. device->overlapBuffer->numFrames = 0;
  212217. device->jitter = false;
  212218. firstFrameInBuffer = 0;
  212219. lastIndex = 0;
  212220. CDReadBuffer readBuffer (4 + framesPerIndexRead);
  212221. readBuffer.wantsIndex = true;
  212222. int i;
  212223. for (i = 5; --i >= 0;)
  212224. {
  212225. readBuffer.startFrame = frameNeeded;
  212226. readBuffer.numFrames = framesPerIndexRead;
  212227. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212228. break;
  212229. }
  212230. if (i >= 0)
  212231. return readBuffer.index;
  212232. return -1;
  212233. }
  212234. const Array <int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  212235. {
  212236. Array <int> indexes;
  212237. const int trackStart = getPositionOfTrackStart (trackNumber);
  212238. const int trackEnd = getPositionOfTrackStart (trackNumber + 1);
  212239. bool needToScan = true;
  212240. if (trackEnd - trackStart > 20 * 44100)
  212241. {
  212242. // check the end of the track for indexes before scanning the whole thing
  212243. needToScan = false;
  212244. int pos = jmax (trackStart, trackEnd - 44100 * 5);
  212245. bool seenAnIndex = false;
  212246. while (pos <= trackEnd - samplesPerFrame)
  212247. {
  212248. const int index = getIndexAt (pos);
  212249. if (index == 0)
  212250. {
  212251. // lead-out, so skip back a bit if we've not found any indexes yet..
  212252. if (seenAnIndex)
  212253. break;
  212254. pos -= 44100 * 5;
  212255. if (pos < trackStart)
  212256. break;
  212257. }
  212258. else
  212259. {
  212260. if (index > 0)
  212261. seenAnIndex = true;
  212262. if (index > 1)
  212263. {
  212264. needToScan = true;
  212265. break;
  212266. }
  212267. pos += samplesPerFrame * framesPerIndexRead;
  212268. }
  212269. }
  212270. }
  212271. if (needToScan)
  212272. {
  212273. CDDeviceWrapper* const device = (CDDeviceWrapper*) handle;
  212274. int pos = trackStart;
  212275. int last = -1;
  212276. while (pos < trackEnd - samplesPerFrame * 10)
  212277. {
  212278. const int frameNeeded = pos / samplesPerFrame;
  212279. device->overlapBuffer->dataLength = 0;
  212280. device->overlapBuffer->startFrame = 0;
  212281. device->overlapBuffer->numFrames = 0;
  212282. device->jitter = false;
  212283. firstFrameInBuffer = 0;
  212284. CDReadBuffer readBuffer (4);
  212285. readBuffer.wantsIndex = true;
  212286. int i;
  212287. for (i = 5; --i >= 0;)
  212288. {
  212289. readBuffer.startFrame = frameNeeded;
  212290. readBuffer.numFrames = framesPerIndexRead;
  212291. if (device->cdH->readAudio (&readBuffer, (false) ? device->overlapBuffer : 0))
  212292. break;
  212293. }
  212294. if (i < 0)
  212295. break;
  212296. if (readBuffer.index > last && readBuffer.index > 1)
  212297. {
  212298. last = readBuffer.index;
  212299. indexes.add (pos);
  212300. }
  212301. pos += samplesPerFrame * framesPerIndexRead;
  212302. }
  212303. indexes.removeValue (trackStart);
  212304. }
  212305. return indexes;
  212306. }
  212307. int AudioCDReader::getCDDBId()
  212308. {
  212309. refreshTrackLengths();
  212310. if (numTracks > 0)
  212311. {
  212312. TOC toc;
  212313. zerostruct (toc);
  212314. if (((CDDeviceWrapper*) handle)->cdH->readTOC (&toc, true))
  212315. {
  212316. int n = 0;
  212317. for (int i = numTracks; --i >= 0;)
  212318. {
  212319. int j = getMSFAddressOf (&toc.tracks[i]);
  212320. while (j > 0)
  212321. {
  212322. n += (j % 10);
  212323. j /= 10;
  212324. }
  212325. }
  212326. if (n != 0)
  212327. {
  212328. const int t = getMSFAddressOf (&toc.tracks[numTracks])
  212329. - getMSFAddressOf (&toc.tracks[0]);
  212330. return ((n % 0xff) << 24) | (t << 8) | numTracks;
  212331. }
  212332. }
  212333. }
  212334. return 0;
  212335. }
  212336. void AudioCDReader::ejectDisk()
  212337. {
  212338. ((CDDeviceWrapper*) handle)->cdH->openDrawer (true);
  212339. }
  212340. static IDiscRecorder* enumCDBurners (StringArray* list, int indexToOpen, IDiscMaster** master)
  212341. {
  212342. CoInitialize (0);
  212343. IDiscMaster* dm;
  212344. IDiscRecorder* result = 0;
  212345. if (SUCCEEDED (CoCreateInstance (CLSID_MSDiscMasterObj, 0,
  212346. CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
  212347. IID_IDiscMaster,
  212348. (void**) &dm)))
  212349. {
  212350. if (SUCCEEDED (dm->Open()))
  212351. {
  212352. IEnumDiscRecorders* drEnum = 0;
  212353. if (SUCCEEDED (dm->EnumDiscRecorders (&drEnum)))
  212354. {
  212355. IDiscRecorder* dr = 0;
  212356. DWORD dummy;
  212357. int index = 0;
  212358. while (drEnum->Next (1, &dr, &dummy) == S_OK)
  212359. {
  212360. if (indexToOpen == index)
  212361. {
  212362. result = dr;
  212363. break;
  212364. }
  212365. else if (list != 0)
  212366. {
  212367. BSTR path;
  212368. if (SUCCEEDED (dr->GetPath (&path)))
  212369. list->add ((const WCHAR*) path);
  212370. }
  212371. ++index;
  212372. dr->Release();
  212373. }
  212374. drEnum->Release();
  212375. }
  212376. /*if (redbookFormat != 0)
  212377. {
  212378. IEnumDiscMasterFormats* mfEnum;
  212379. if (SUCCEEDED (dm->EnumDiscMasterFormats (&mfEnum)))
  212380. {
  212381. IID formatIID;
  212382. DWORD dummy;
  212383. while (mfEnum->Next (1, &formatIID, &dummy) == S_OK)
  212384. {
  212385. }
  212386. mfEnum->Release();
  212387. }
  212388. redbookFormat
  212389. }*/
  212390. if (master == 0)
  212391. dm->Close();
  212392. }
  212393. if (master != 0)
  212394. *master = dm;
  212395. else
  212396. dm->Release();
  212397. }
  212398. return result;
  212399. }
  212400. const StringArray AudioCDBurner::findAvailableDevices()
  212401. {
  212402. StringArray devs;
  212403. enumCDBurners (&devs, -1, 0);
  212404. return devs;
  212405. }
  212406. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  212407. {
  212408. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  212409. if (b->internal == 0)
  212410. deleteAndZero (b);
  212411. return b;
  212412. }
  212413. class CDBurnerInfo : public IDiscMasterProgressEvents
  212414. {
  212415. public:
  212416. CDBurnerInfo()
  212417. : refCount (1),
  212418. progress (0),
  212419. shouldCancel (false),
  212420. listener (0)
  212421. {
  212422. }
  212423. ~CDBurnerInfo()
  212424. {
  212425. }
  212426. HRESULT __stdcall QueryInterface (REFIID id, void __RPC_FAR* __RPC_FAR* result)
  212427. {
  212428. if (result == 0)
  212429. return E_POINTER;
  212430. if (id == IID_IUnknown || id == IID_IDiscMasterProgressEvents)
  212431. {
  212432. AddRef();
  212433. *result = this;
  212434. return S_OK;
  212435. }
  212436. *result = 0;
  212437. return E_NOINTERFACE;
  212438. }
  212439. ULONG __stdcall AddRef() { return ++refCount; }
  212440. ULONG __stdcall Release() { jassert (refCount > 0); const int r = --refCount; if (r == 0) delete this; return r; }
  212441. HRESULT __stdcall QueryCancel (boolean* pbCancel)
  212442. {
  212443. if (listener != 0 && ! shouldCancel)
  212444. shouldCancel = listener->audioCDBurnProgress (progress);
  212445. *pbCancel = shouldCancel;
  212446. return S_OK;
  212447. }
  212448. HRESULT __stdcall NotifyBlockProgress (long nCompleted, long nTotal)
  212449. {
  212450. progress = nCompleted / (float) nTotal;
  212451. shouldCancel = listener != 0 && listener->audioCDBurnProgress (progress);
  212452. return E_NOTIMPL;
  212453. }
  212454. HRESULT __stdcall NotifyPnPActivity (void) { return E_NOTIMPL; }
  212455. HRESULT __stdcall NotifyAddProgress (long /*nCompletedSteps*/, long /*nTotalSteps*/) { return E_NOTIMPL; }
  212456. HRESULT __stdcall NotifyTrackProgress (long /*nCurrentTrack*/, long /*nTotalTracks*/) { return E_NOTIMPL; }
  212457. HRESULT __stdcall NotifyPreparingBurn (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212458. HRESULT __stdcall NotifyClosingDisc (long /*nEstimatedSeconds*/) { return E_NOTIMPL; }
  212459. HRESULT __stdcall NotifyBurnComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212460. HRESULT __stdcall NotifyEraseComplete (HRESULT /*status*/) { return E_NOTIMPL; }
  212461. IDiscMaster* discMaster;
  212462. IDiscRecorder* discRecorder;
  212463. IRedbookDiscMaster* redbook;
  212464. AudioCDBurner::BurnProgressListener* listener;
  212465. float progress;
  212466. bool shouldCancel;
  212467. private:
  212468. int refCount;
  212469. };
  212470. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  212471. : internal (0)
  212472. {
  212473. IDiscMaster* discMaster;
  212474. IDiscRecorder* dr = enumCDBurners (0, deviceIndex, &discMaster);
  212475. if (dr != 0)
  212476. {
  212477. IRedbookDiscMaster* redbook;
  212478. HRESULT hr = discMaster->SetActiveDiscMasterFormat (IID_IRedbookDiscMaster, (void**) &redbook);
  212479. hr = discMaster->SetActiveDiscRecorder (dr);
  212480. CDBurnerInfo* const info = new CDBurnerInfo();
  212481. internal = info;
  212482. info->discMaster = discMaster;
  212483. info->discRecorder = dr;
  212484. info->redbook = redbook;
  212485. }
  212486. }
  212487. AudioCDBurner::~AudioCDBurner()
  212488. {
  212489. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  212490. if (info != 0)
  212491. {
  212492. info->discRecorder->Close();
  212493. info->redbook->Release();
  212494. info->discRecorder->Release();
  212495. info->discMaster->Release();
  212496. info->Release();
  212497. }
  212498. }
  212499. bool AudioCDBurner::isDiskPresent() const
  212500. {
  212501. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  212502. HRESULT hr = info->discRecorder->OpenExclusive();
  212503. long type, flags;
  212504. hr = info->discRecorder->QueryMediaType (&type, &flags);
  212505. info->discRecorder->Close();
  212506. return hr == S_OK && type != 0 && (flags & MEDIA_WRITABLE) != 0;
  212507. }
  212508. int AudioCDBurner::getNumAvailableAudioBlocks() const
  212509. {
  212510. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  212511. long blocksFree = 0;
  212512. info->redbook->GetAvailableAudioTrackBlocks (&blocksFree);
  212513. return blocksFree;
  212514. }
  212515. const String AudioCDBurner::burn (AudioCDBurner::BurnProgressListener* listener,
  212516. const bool ejectDiscAfterwards,
  212517. const bool performFakeBurnForTesting)
  212518. {
  212519. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  212520. info->listener = listener;
  212521. info->progress = 0;
  212522. info->shouldCancel = false;
  212523. UINT_PTR cookie;
  212524. HRESULT hr = info->discMaster->ProgressAdvise (info, &cookie);
  212525. hr = info->discMaster->RecordDisc (performFakeBurnForTesting,
  212526. ejectDiscAfterwards);
  212527. String error;
  212528. if (hr != S_OK)
  212529. {
  212530. const char* e = "Couldn't open or write to the CD device";
  212531. if (hr == IMAPI_E_USERABORT)
  212532. e = "User cancelled the write operation";
  212533. else if (hr == IMAPI_E_MEDIUM_NOTPRESENT || hr == IMAPI_E_TRACKOPEN)
  212534. e = "No Disk present";
  212535. error = e;
  212536. }
  212537. info->discMaster->ProgressUnadvise (cookie);
  212538. info->listener = 0;
  212539. return error;
  212540. }
  212541. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamples)
  212542. {
  212543. if (source == 0)
  212544. return false;
  212545. CDBurnerInfo* const info = (CDBurnerInfo*) internal;
  212546. long bytesPerBlock;
  212547. HRESULT hr = info->redbook->GetAudioBlockSize (&bytesPerBlock);
  212548. const int samplesPerBlock = bytesPerBlock / 4;
  212549. bool ok = true;
  212550. hr = info->redbook->CreateAudioTrack ((long) numSamples / (bytesPerBlock * 4));
  212551. byte* const buffer = (byte*) juce_malloc (bytesPerBlock);
  212552. AudioSampleBuffer sourceBuffer (2, samplesPerBlock);
  212553. int samplesDone = 0;
  212554. source->prepareToPlay (samplesPerBlock, 44100.0);
  212555. while (ok)
  212556. {
  212557. {
  212558. AudioSourceChannelInfo info;
  212559. info.buffer = &sourceBuffer;
  212560. info.numSamples = samplesPerBlock;
  212561. info.startSample = 0;
  212562. sourceBuffer.clear();
  212563. source->getNextAudioBlock (info);
  212564. }
  212565. zeromem (buffer, bytesPerBlock);
  212566. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (0, 0),
  212567. buffer, samplesPerBlock, 4);
  212568. AudioDataConverters::convertFloatToInt16LE (sourceBuffer.getSampleData (1, 0),
  212569. buffer + 2, samplesPerBlock, 4);
  212570. hr = info->redbook->AddAudioTrackBlocks (buffer, bytesPerBlock);
  212571. if (hr != S_OK)
  212572. ok = false;
  212573. samplesDone += samplesPerBlock;
  212574. if (samplesDone >= numSamples)
  212575. break;
  212576. }
  212577. juce_free (buffer);
  212578. hr = info->redbook->CloseAudioTrack();
  212579. delete source;
  212580. return ok && hr == S_OK;
  212581. }
  212582. #endif
  212583. /********* End of inlined file: juce_win32_AudioCDReader.cpp *********/
  212584. /********* Start of inlined file: juce_win32_Midi.cpp *********/
  212585. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  212586. // compiled on its own).
  212587. #if JUCE_INCLUDED_FILE
  212588. static const int midiBufferSize = 1024 * 10;
  212589. static const int numInHeaders = 32;
  212590. static const int inBufferSize = 256;
  212591. static Array <void*, CriticalSection> activeMidiThreads;
  212592. using ::free;
  212593. class MidiInThread : public Thread
  212594. {
  212595. public:
  212596. MidiInThread (MidiInput* const input_,
  212597. MidiInputCallback* const callback_)
  212598. : Thread ("Juce Midi"),
  212599. hIn (0),
  212600. input (input_),
  212601. callback (callback_),
  212602. isStarted (false),
  212603. startTime (0),
  212604. pendingLength(0)
  212605. {
  212606. for (int i = numInHeaders; --i >= 0;)
  212607. {
  212608. zeromem (&hdr[i], sizeof (MIDIHDR));
  212609. hdr[i].lpData = inData[i];
  212610. hdr[i].dwBufferLength = inBufferSize;
  212611. }
  212612. };
  212613. ~MidiInThread()
  212614. {
  212615. stop();
  212616. if (hIn != 0)
  212617. {
  212618. int count = 5;
  212619. while (--count >= 0)
  212620. {
  212621. if (midiInClose (hIn) == MMSYSERR_NOERROR)
  212622. break;
  212623. Sleep (20);
  212624. }
  212625. }
  212626. }
  212627. void handle (const uint32 message, const uint32 timeStamp) throw()
  212628. {
  212629. const int byte = message & 0xff;
  212630. if (byte < 0x80)
  212631. return;
  212632. const int numBytes = MidiMessage::getMessageLengthFromFirstByte ((uint8) byte);
  212633. const double time = timeStampToTime (timeStamp);
  212634. lock.enter();
  212635. if (pendingLength < midiBufferSize - 12)
  212636. {
  212637. char* const p = pending + pendingLength;
  212638. *(double*) p = time;
  212639. *(uint32*) (p + 8) = numBytes;
  212640. *(uint32*) (p + 12) = message;
  212641. pendingLength += 12 + numBytes;
  212642. }
  212643. else
  212644. {
  212645. jassertfalse // midi buffer overflow! You might need to increase the size..
  212646. }
  212647. lock.exit();
  212648. notify();
  212649. }
  212650. void handleSysEx (MIDIHDR* const hdr, const uint32 timeStamp) throw()
  212651. {
  212652. const int num = hdr->dwBytesRecorded;
  212653. if (num > 0)
  212654. {
  212655. const double time = timeStampToTime (timeStamp);
  212656. lock.enter();
  212657. if (pendingLength < midiBufferSize - (8 + num))
  212658. {
  212659. char* const p = pending + pendingLength;
  212660. *(double*) p = time;
  212661. *(uint32*) (p + 8) = num;
  212662. memcpy (p + 12, hdr->lpData, num);
  212663. pendingLength += 12 + num;
  212664. }
  212665. else
  212666. {
  212667. jassertfalse // midi buffer overflow! You might need to increase the size..
  212668. }
  212669. lock.exit();
  212670. notify();
  212671. }
  212672. }
  212673. void writeBlock (const int i) throw()
  212674. {
  212675. hdr[i].dwBytesRecorded = 0;
  212676. MMRESULT res = midiInPrepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  212677. jassert (res == MMSYSERR_NOERROR);
  212678. res = midiInAddBuffer (hIn, &hdr[i], sizeof (MIDIHDR));
  212679. jassert (res == MMSYSERR_NOERROR);
  212680. }
  212681. void run()
  212682. {
  212683. MemoryBlock pendingCopy (64);
  212684. while (! threadShouldExit())
  212685. {
  212686. for (int i = 0; i < numInHeaders; ++i)
  212687. {
  212688. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  212689. {
  212690. MMRESULT res = midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR));
  212691. (void) res;
  212692. jassert (res == MMSYSERR_NOERROR);
  212693. writeBlock (i);
  212694. }
  212695. }
  212696. lock.enter();
  212697. int len = pendingLength;
  212698. if (len > 0)
  212699. {
  212700. pendingCopy.ensureSize (len);
  212701. pendingCopy.copyFrom (pending, 0, len);
  212702. pendingLength = 0;
  212703. }
  212704. lock.exit();
  212705. //xxx needs to figure out if blocks are broken up or not
  212706. if (len == 0)
  212707. {
  212708. wait (500);
  212709. }
  212710. else
  212711. {
  212712. const char* p = (const char*) pendingCopy.getData();
  212713. while (len > 0)
  212714. {
  212715. const double time = *(const double*) p;
  212716. const int messageLen = *(const int*) (p + 8);
  212717. const MidiMessage message ((const uint8*) (p + 12), messageLen, time);
  212718. callback->handleIncomingMidiMessage (input, message);
  212719. p += 12 + messageLen;
  212720. len -= 12 + messageLen;
  212721. }
  212722. }
  212723. }
  212724. }
  212725. void start() throw()
  212726. {
  212727. jassert (hIn != 0);
  212728. if (hIn != 0 && ! isStarted)
  212729. {
  212730. stop();
  212731. activeMidiThreads.addIfNotAlreadyThere (this);
  212732. int i;
  212733. for (i = 0; i < numInHeaders; ++i)
  212734. writeBlock (i);
  212735. startTime = Time::getMillisecondCounter();
  212736. MMRESULT res = midiInStart (hIn);
  212737. jassert (res == MMSYSERR_NOERROR);
  212738. if (res == MMSYSERR_NOERROR)
  212739. {
  212740. isStarted = true;
  212741. pendingLength = 0;
  212742. startThread (6);
  212743. }
  212744. }
  212745. }
  212746. void stop() throw()
  212747. {
  212748. if (isStarted)
  212749. {
  212750. stopThread (5000);
  212751. midiInReset (hIn);
  212752. midiInStop (hIn);
  212753. activeMidiThreads.removeValue (this);
  212754. lock.enter();
  212755. lock.exit();
  212756. for (int i = numInHeaders; --i >= 0;)
  212757. {
  212758. if ((hdr[i].dwFlags & WHDR_DONE) != 0)
  212759. {
  212760. int c = 10;
  212761. while (--c >= 0 && midiInUnprepareHeader (hIn, &hdr[i], sizeof (MIDIHDR)) == MIDIERR_STILLPLAYING)
  212762. Sleep (20);
  212763. jassert (c >= 0);
  212764. }
  212765. }
  212766. isStarted = false;
  212767. pendingLength = 0;
  212768. }
  212769. }
  212770. juce_UseDebuggingNewOperator
  212771. HMIDIIN hIn;
  212772. private:
  212773. MidiInput* input;
  212774. MidiInputCallback* callback;
  212775. bool isStarted;
  212776. uint32 startTime;
  212777. CriticalSection lock;
  212778. MIDIHDR hdr [numInHeaders];
  212779. char inData [numInHeaders] [inBufferSize];
  212780. int pendingLength;
  212781. char pending [midiBufferSize];
  212782. double timeStampToTime (uint32 timeStamp) throw()
  212783. {
  212784. timeStamp += startTime;
  212785. const uint32 now = Time::getMillisecondCounter();
  212786. if (timeStamp > now)
  212787. {
  212788. if (timeStamp > now + 2)
  212789. --startTime;
  212790. timeStamp = now;
  212791. }
  212792. return 0.001 * timeStamp;
  212793. }
  212794. MidiInThread (const MidiInThread&);
  212795. const MidiInThread& operator= (const MidiInThread&);
  212796. };
  212797. static void CALLBACK midiInCallback (HMIDIIN,
  212798. UINT uMsg,
  212799. DWORD_PTR dwInstance,
  212800. DWORD_PTR midiMessage,
  212801. DWORD_PTR timeStamp)
  212802. {
  212803. MidiInThread* const thread = (MidiInThread*) dwInstance;
  212804. if (thread != 0 && activeMidiThreads.contains (thread))
  212805. {
  212806. if (uMsg == MIM_DATA)
  212807. thread->handle ((uint32) midiMessage, (uint32) timeStamp);
  212808. else if (uMsg == MIM_LONGDATA)
  212809. thread->handleSysEx ((MIDIHDR*) midiMessage, (uint32) timeStamp);
  212810. }
  212811. }
  212812. const StringArray MidiInput::getDevices()
  212813. {
  212814. StringArray s;
  212815. const int num = midiInGetNumDevs();
  212816. for (int i = 0; i < num; ++i)
  212817. {
  212818. MIDIINCAPS mc;
  212819. zerostruct (mc);
  212820. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212821. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212822. }
  212823. return s;
  212824. }
  212825. int MidiInput::getDefaultDeviceIndex()
  212826. {
  212827. return 0;
  212828. }
  212829. MidiInput* MidiInput::openDevice (const int index, MidiInputCallback* const callback)
  212830. {
  212831. if (callback == 0)
  212832. return 0;
  212833. UINT deviceId = MIDI_MAPPER;
  212834. int n = 0;
  212835. String name;
  212836. const int num = midiInGetNumDevs();
  212837. for (int i = 0; i < num; ++i)
  212838. {
  212839. MIDIINCAPS mc;
  212840. zerostruct (mc);
  212841. if (midiInGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212842. {
  212843. if (index == n)
  212844. {
  212845. deviceId = i;
  212846. name = String (mc.szPname, sizeof (mc.szPname));
  212847. break;
  212848. }
  212849. ++n;
  212850. }
  212851. }
  212852. MidiInput* const in = new MidiInput (name);
  212853. MidiInThread* const thread = new MidiInThread (in, callback);
  212854. HMIDIIN h;
  212855. HRESULT err = midiInOpen (&h, deviceId,
  212856. (DWORD_PTR) &midiInCallback,
  212857. (DWORD_PTR) thread,
  212858. CALLBACK_FUNCTION);
  212859. if (err == MMSYSERR_NOERROR)
  212860. {
  212861. thread->hIn = h;
  212862. in->internal = (void*) thread;
  212863. return in;
  212864. }
  212865. else
  212866. {
  212867. delete in;
  212868. delete thread;
  212869. return 0;
  212870. }
  212871. }
  212872. MidiInput::MidiInput (const String& name_)
  212873. : name (name_),
  212874. internal (0)
  212875. {
  212876. }
  212877. MidiInput::~MidiInput()
  212878. {
  212879. if (internal != 0)
  212880. {
  212881. MidiInThread* const thread = (MidiInThread*) internal;
  212882. delete thread;
  212883. }
  212884. }
  212885. void MidiInput::start()
  212886. {
  212887. ((MidiInThread*) internal)->start();
  212888. }
  212889. void MidiInput::stop()
  212890. {
  212891. ((MidiInThread*) internal)->stop();
  212892. }
  212893. struct MidiOutHandle
  212894. {
  212895. int refCount;
  212896. UINT deviceId;
  212897. HMIDIOUT handle;
  212898. juce_UseDebuggingNewOperator
  212899. };
  212900. static VoidArray handles (4);
  212901. const StringArray MidiOutput::getDevices()
  212902. {
  212903. StringArray s;
  212904. const int num = midiOutGetNumDevs();
  212905. for (int i = 0; i < num; ++i)
  212906. {
  212907. MIDIOUTCAPS mc;
  212908. zerostruct (mc);
  212909. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212910. s.add (String (mc.szPname, sizeof (mc.szPname)));
  212911. }
  212912. return s;
  212913. }
  212914. int MidiOutput::getDefaultDeviceIndex()
  212915. {
  212916. const int num = midiOutGetNumDevs();
  212917. int n = 0;
  212918. for (int i = 0; i < num; ++i)
  212919. {
  212920. MIDIOUTCAPS mc;
  212921. zerostruct (mc);
  212922. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212923. {
  212924. if ((mc.wTechnology & MOD_MAPPER) != 0)
  212925. return n;
  212926. ++n;
  212927. }
  212928. }
  212929. return 0;
  212930. }
  212931. MidiOutput* MidiOutput::openDevice (int index)
  212932. {
  212933. UINT deviceId = MIDI_MAPPER;
  212934. const int num = midiOutGetNumDevs();
  212935. int i, n = 0;
  212936. for (i = 0; i < num; ++i)
  212937. {
  212938. MIDIOUTCAPS mc;
  212939. zerostruct (mc);
  212940. if (midiOutGetDevCaps (i, &mc, sizeof (mc)) == MMSYSERR_NOERROR)
  212941. {
  212942. // use the microsoft sw synth as a default - best not to allow deviceId
  212943. // to be MIDI_MAPPER, or else device sharing breaks
  212944. if (String (mc.szPname, sizeof (mc.szPname)).containsIgnoreCase (T("microsoft")))
  212945. deviceId = i;
  212946. if (index == n)
  212947. {
  212948. deviceId = i;
  212949. break;
  212950. }
  212951. ++n;
  212952. }
  212953. }
  212954. for (i = handles.size(); --i >= 0;)
  212955. {
  212956. MidiOutHandle* const han = (MidiOutHandle*) handles.getUnchecked(i);
  212957. if (han != 0 && han->deviceId == deviceId)
  212958. {
  212959. han->refCount++;
  212960. MidiOutput* const out = new MidiOutput();
  212961. out->internal = (void*) han;
  212962. return out;
  212963. }
  212964. }
  212965. for (i = 4; --i >= 0;)
  212966. {
  212967. HMIDIOUT h = 0;
  212968. MMRESULT res = midiOutOpen (&h, deviceId, 0, 0, CALLBACK_NULL);
  212969. if (res == MMSYSERR_NOERROR)
  212970. {
  212971. MidiOutHandle* const han = new MidiOutHandle();
  212972. han->deviceId = deviceId;
  212973. han->refCount = 1;
  212974. han->handle = h;
  212975. handles.add (han);
  212976. MidiOutput* const out = new MidiOutput();
  212977. out->internal = (void*) han;
  212978. return out;
  212979. }
  212980. else if (res == MMSYSERR_ALLOCATED)
  212981. {
  212982. Sleep (100);
  212983. }
  212984. else
  212985. {
  212986. break;
  212987. }
  212988. }
  212989. return 0;
  212990. }
  212991. MidiOutput::~MidiOutput()
  212992. {
  212993. MidiOutHandle* const h = (MidiOutHandle*) internal;
  212994. if (handles.contains ((void*) h) && --(h->refCount) == 0)
  212995. {
  212996. midiOutClose (h->handle);
  212997. handles.removeValue ((void*) h);
  212998. delete h;
  212999. }
  213000. }
  213001. void MidiOutput::reset()
  213002. {
  213003. const MidiOutHandle* const h = (MidiOutHandle*) internal;
  213004. midiOutReset (h->handle);
  213005. }
  213006. bool MidiOutput::getVolume (float& leftVol,
  213007. float& rightVol)
  213008. {
  213009. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  213010. DWORD n;
  213011. if (midiOutGetVolume (handle->handle, &n) == MMSYSERR_NOERROR)
  213012. {
  213013. const unsigned short* const nn = (const unsigned short*) &n;
  213014. rightVol = nn[0] / (float) 0xffff;
  213015. leftVol = nn[1] / (float) 0xffff;
  213016. return true;
  213017. }
  213018. else
  213019. {
  213020. rightVol = leftVol = 1.0f;
  213021. return false;
  213022. }
  213023. }
  213024. void MidiOutput::setVolume (float leftVol,
  213025. float rightVol)
  213026. {
  213027. const MidiOutHandle* const handle = (MidiOutHandle*) internal;
  213028. DWORD n;
  213029. unsigned short* const nn = (unsigned short*) &n;
  213030. nn[0] = (unsigned short) jlimit (0, 0xffff, (int)(rightVol * 0xffff));
  213031. nn[1] = (unsigned short) jlimit (0, 0xffff, (int)(leftVol * 0xffff));
  213032. midiOutSetVolume (handle->handle, n);
  213033. }
  213034. void MidiOutput::sendMessageNow (const MidiMessage& message)
  213035. {
  213036. const MidiOutHandle* const handle = (const MidiOutHandle*) internal;
  213037. if (message.getRawDataSize() > 3
  213038. || message.isSysEx())
  213039. {
  213040. MIDIHDR h;
  213041. zerostruct (h);
  213042. h.lpData = (char*) message.getRawData();
  213043. h.dwBufferLength = message.getRawDataSize();
  213044. h.dwBytesRecorded = message.getRawDataSize();
  213045. if (midiOutPrepareHeader (handle->handle, &h, sizeof (MIDIHDR)) == MMSYSERR_NOERROR)
  213046. {
  213047. MMRESULT res = midiOutLongMsg (handle->handle, &h, sizeof (MIDIHDR));
  213048. if (res == MMSYSERR_NOERROR)
  213049. {
  213050. while ((h.dwFlags & MHDR_DONE) == 0)
  213051. Sleep (1);
  213052. int count = 500; // 1 sec timeout
  213053. while (--count >= 0)
  213054. {
  213055. res = midiOutUnprepareHeader (handle->handle, &h, sizeof (MIDIHDR));
  213056. if (res == MIDIERR_STILLPLAYING)
  213057. Sleep (2);
  213058. else
  213059. break;
  213060. }
  213061. }
  213062. }
  213063. }
  213064. else
  213065. {
  213066. midiOutShortMsg (handle->handle,
  213067. *(unsigned int*) message.getRawData());
  213068. }
  213069. }
  213070. #endif
  213071. /********* End of inlined file: juce_win32_Midi.cpp *********/
  213072. /********* Start of inlined file: juce_win32_ASIO.cpp *********/
  213073. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  213074. // compiled on its own).
  213075. #if JUCE_INCLUDED_FILE && JUCE_ASIO
  213076. #undef WINDOWS
  213077. // #define ASIO_DEBUGGING
  213078. #ifdef ASIO_DEBUGGING
  213079. #define log(a) { Logger::writeToLog (a); DBG (a) }
  213080. #else
  213081. #define log(a) {}
  213082. #endif
  213083. #ifdef ASIO_DEBUGGING
  213084. static void logError (const String& context, long error)
  213085. {
  213086. String err ("unknown error");
  213087. if (error == ASE_NotPresent)
  213088. err = "Not Present";
  213089. else if (error == ASE_HWMalfunction)
  213090. err = "Hardware Malfunction";
  213091. else if (error == ASE_InvalidParameter)
  213092. err = "Invalid Parameter";
  213093. else if (error == ASE_InvalidMode)
  213094. err = "Invalid Mode";
  213095. else if (error == ASE_SPNotAdvancing)
  213096. err = "Sample position not advancing";
  213097. else if (error == ASE_NoClock)
  213098. err = "No Clock";
  213099. else if (error == ASE_NoMemory)
  213100. err = "Out of memory";
  213101. log (T("!!error: ") + context + T(" - ") + err);
  213102. }
  213103. #else
  213104. #define logError(a, b) {}
  213105. #endif
  213106. class ASIOAudioIODevice;
  213107. static ASIOAudioIODevice* volatile currentASIODev[3] = { 0, 0, 0 };
  213108. static const int maxASIOChannels = 160;
  213109. class JUCE_API ASIOAudioIODevice : public AudioIODevice,
  213110. private Timer
  213111. {
  213112. public:
  213113. Component ourWindow;
  213114. ASIOAudioIODevice (const String& name_, const CLSID classId_, const int slotNumber)
  213115. : AudioIODevice (name_, T("ASIO")),
  213116. asioObject (0),
  213117. classId (classId_),
  213118. currentBitDepth (16),
  213119. currentSampleRate (0),
  213120. tempBuffer (0),
  213121. isOpen_ (false),
  213122. isStarted (false),
  213123. postOutput (true),
  213124. insideControlPanelModalLoop (false),
  213125. shouldUsePreferredSize (false)
  213126. {
  213127. name = name_;
  213128. ourWindow.addToDesktop (0);
  213129. windowHandle = ourWindow.getWindowHandle();
  213130. jassert (currentASIODev [slotNumber] == 0);
  213131. currentASIODev [slotNumber] = this;
  213132. openDevice();
  213133. }
  213134. ~ASIOAudioIODevice()
  213135. {
  213136. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  213137. if (currentASIODev[i] == this)
  213138. currentASIODev[i] = 0;
  213139. close();
  213140. log ("ASIO - exiting");
  213141. removeCurrentDriver();
  213142. juce_free (tempBuffer);
  213143. }
  213144. void updateSampleRates()
  213145. {
  213146. // find a list of sample rates..
  213147. const double possibleSampleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  213148. sampleRates.clear();
  213149. if (asioObject != 0)
  213150. {
  213151. for (int index = 0; index < numElementsInArray (possibleSampleRates); ++index)
  213152. {
  213153. const long err = asioObject->canSampleRate (possibleSampleRates[index]);
  213154. if (err == 0)
  213155. {
  213156. sampleRates.add ((int) possibleSampleRates[index]);
  213157. log (T("rate: ") + String ((int) possibleSampleRates[index]));
  213158. }
  213159. else if (err != ASE_NoClock)
  213160. {
  213161. logError (T("CanSampleRate"), err);
  213162. }
  213163. }
  213164. if (sampleRates.size() == 0)
  213165. {
  213166. double cr = 0;
  213167. const long err = asioObject->getSampleRate (&cr);
  213168. log (T("No sample rates supported - current rate: ") + String ((int) cr));
  213169. if (err == 0)
  213170. sampleRates.add ((int) cr);
  213171. }
  213172. }
  213173. }
  213174. const StringArray getOutputChannelNames()
  213175. {
  213176. return outputChannelNames;
  213177. }
  213178. const StringArray getInputChannelNames()
  213179. {
  213180. return inputChannelNames;
  213181. }
  213182. int getNumSampleRates()
  213183. {
  213184. return sampleRates.size();
  213185. }
  213186. double getSampleRate (int index)
  213187. {
  213188. return sampleRates [index];
  213189. }
  213190. int getNumBufferSizesAvailable()
  213191. {
  213192. return bufferSizes.size();
  213193. }
  213194. int getBufferSizeSamples (int index)
  213195. {
  213196. return bufferSizes [index];
  213197. }
  213198. int getDefaultBufferSize()
  213199. {
  213200. return preferredSize;
  213201. }
  213202. const String open (const BitArray& inputChannels,
  213203. const BitArray& outputChannels,
  213204. double sr,
  213205. int bufferSizeSamples)
  213206. {
  213207. close();
  213208. currentCallback = 0;
  213209. if (bufferSizeSamples <= 0)
  213210. shouldUsePreferredSize = true;
  213211. if (asioObject == 0 || ! isASIOOpen)
  213212. {
  213213. log ("Warning: device not open");
  213214. const String err (openDevice());
  213215. if (asioObject == 0 || ! isASIOOpen)
  213216. return err;
  213217. }
  213218. isStarted = false;
  213219. bufferIndex = -1;
  213220. long err = 0;
  213221. long newPreferredSize = 0;
  213222. // if the preferred size has just changed, assume it's a control panel thing and use it as the new value.
  213223. minSize = 0;
  213224. maxSize = 0;
  213225. newPreferredSize = 0;
  213226. granularity = 0;
  213227. if (asioObject->getBufferSize (&minSize, &maxSize, &newPreferredSize, &granularity) == 0)
  213228. {
  213229. if (preferredSize != 0 && newPreferredSize != 0 && newPreferredSize != preferredSize)
  213230. shouldUsePreferredSize = true;
  213231. preferredSize = newPreferredSize;
  213232. }
  213233. // unfortunate workaround for certain manufacturers whose drivers crash horribly if you make
  213234. // dynamic changes to the buffer size...
  213235. shouldUsePreferredSize = shouldUsePreferredSize
  213236. || getName().containsIgnoreCase (T("Digidesign"));
  213237. if (shouldUsePreferredSize)
  213238. {
  213239. log ("Using preferred size for buffer..");
  213240. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213241. {
  213242. bufferSizeSamples = preferredSize;
  213243. }
  213244. else
  213245. {
  213246. bufferSizeSamples = 1024;
  213247. logError ("GetBufferSize1", err);
  213248. }
  213249. shouldUsePreferredSize = false;
  213250. }
  213251. int sampleRate = roundDoubleToInt (sr);
  213252. currentSampleRate = sampleRate;
  213253. currentBlockSizeSamples = bufferSizeSamples;
  213254. currentChansOut.clear();
  213255. currentChansIn.clear();
  213256. zeromem (inBuffers, sizeof (inBuffers));
  213257. zeromem (outBuffers, sizeof (outBuffers));
  213258. updateSampleRates();
  213259. if (sampleRate == 0 || (sampleRates.size() > 0 && ! sampleRates.contains (sampleRate)))
  213260. sampleRate = sampleRates[0];
  213261. jassert (sampleRate != 0);
  213262. if (sampleRate == 0)
  213263. sampleRate = 44100;
  213264. long numSources = 32;
  213265. ASIOClockSource clocks[32];
  213266. zeromem (clocks, sizeof (clocks));
  213267. asioObject->getClockSources (clocks, &numSources);
  213268. bool isSourceSet = false;
  213269. // careful not to remove this loop because it does more than just logging!
  213270. int i;
  213271. for (i = 0; i < numSources; ++i)
  213272. {
  213273. String s ("clock: ");
  213274. s += clocks[i].name;
  213275. if (clocks[i].isCurrentSource)
  213276. {
  213277. isSourceSet = true;
  213278. s << " (cur)";
  213279. }
  213280. log (s);
  213281. }
  213282. if (numSources > 1 && ! isSourceSet)
  213283. {
  213284. log ("setting clock source");
  213285. asioObject->setClockSource (clocks[0].index);
  213286. Thread::sleep (20);
  213287. }
  213288. else
  213289. {
  213290. if (numSources == 0)
  213291. {
  213292. log ("ASIO - no clock sources!");
  213293. }
  213294. }
  213295. double cr = 0;
  213296. err = asioObject->getSampleRate (&cr);
  213297. if (err == 0)
  213298. {
  213299. currentSampleRate = cr;
  213300. }
  213301. else
  213302. {
  213303. logError ("GetSampleRate", err);
  213304. currentSampleRate = 0;
  213305. }
  213306. error = String::empty;
  213307. needToReset = false;
  213308. isReSync = false;
  213309. err = 0;
  213310. bool buffersCreated = false;
  213311. if (currentSampleRate != sampleRate)
  213312. {
  213313. log (T("ASIO samplerate: ") + String (currentSampleRate) + T(" to ") + String (sampleRate));
  213314. err = asioObject->setSampleRate (sampleRate);
  213315. if (err == ASE_NoClock && numSources > 0)
  213316. {
  213317. log ("trying to set a clock source..");
  213318. Thread::sleep (10);
  213319. err = asioObject->setClockSource (clocks[0].index);
  213320. if (err != 0)
  213321. {
  213322. logError ("SetClock", err);
  213323. }
  213324. Thread::sleep (10);
  213325. err = asioObject->setSampleRate (sampleRate);
  213326. }
  213327. }
  213328. if (err == 0)
  213329. {
  213330. currentSampleRate = sampleRate;
  213331. if (needToReset)
  213332. {
  213333. if (isReSync)
  213334. {
  213335. log ("Resync request");
  213336. }
  213337. log ("! Resetting ASIO after sample rate change");
  213338. removeCurrentDriver();
  213339. loadDriver();
  213340. const String error (initDriver());
  213341. if (error.isNotEmpty())
  213342. {
  213343. log (T("ASIOInit: ") + error);
  213344. }
  213345. needToReset = false;
  213346. isReSync = false;
  213347. }
  213348. numActiveInputChans = 0;
  213349. numActiveOutputChans = 0;
  213350. ASIOBufferInfo* info = bufferInfos;
  213351. int i;
  213352. for (i = 0; i < totalNumInputChans; ++i)
  213353. {
  213354. if (inputChannels[i])
  213355. {
  213356. currentChansIn.setBit (i);
  213357. info->isInput = 1;
  213358. info->channelNum = i;
  213359. info->buffers[0] = info->buffers[1] = 0;
  213360. ++info;
  213361. ++numActiveInputChans;
  213362. }
  213363. }
  213364. for (i = 0; i < totalNumOutputChans; ++i)
  213365. {
  213366. if (outputChannels[i])
  213367. {
  213368. currentChansOut.setBit (i);
  213369. info->isInput = 0;
  213370. info->channelNum = i;
  213371. info->buffers[0] = info->buffers[1] = 0;
  213372. ++info;
  213373. ++numActiveOutputChans;
  213374. }
  213375. }
  213376. const int totalBuffers = numActiveInputChans + numActiveOutputChans;
  213377. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213378. if (currentASIODev[0] == this)
  213379. {
  213380. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213381. callbacks.asioMessage = &asioMessagesCallback0;
  213382. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213383. }
  213384. else if (currentASIODev[1] == this)
  213385. {
  213386. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213387. callbacks.asioMessage = &asioMessagesCallback1;
  213388. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213389. }
  213390. else if (currentASIODev[2] == this)
  213391. {
  213392. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213393. callbacks.asioMessage = &asioMessagesCallback2;
  213394. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213395. }
  213396. else
  213397. {
  213398. jassertfalse
  213399. }
  213400. log ("disposing buffers");
  213401. err = asioObject->disposeBuffers();
  213402. log (T("creating buffers: ") + String (totalBuffers) + T(", ") + String (currentBlockSizeSamples));
  213403. err = asioObject->createBuffers (bufferInfos,
  213404. totalBuffers,
  213405. currentBlockSizeSamples,
  213406. &callbacks);
  213407. if (err != 0)
  213408. {
  213409. currentBlockSizeSamples = preferredSize;
  213410. logError ("create buffers 2", err);
  213411. asioObject->disposeBuffers();
  213412. err = asioObject->createBuffers (bufferInfos,
  213413. totalBuffers,
  213414. currentBlockSizeSamples,
  213415. &callbacks);
  213416. }
  213417. if (err == 0)
  213418. {
  213419. buffersCreated = true;
  213420. juce_free (tempBuffer);
  213421. tempBuffer = (float*) juce_calloc (totalBuffers * currentBlockSizeSamples * sizeof (float) + 128);
  213422. int n = 0;
  213423. Array <int> types;
  213424. currentBitDepth = 16;
  213425. for (i = 0; i < jmin (totalNumInputChans, maxASIOChannels); ++i)
  213426. {
  213427. if (inputChannels[i])
  213428. {
  213429. inBuffers[n] = tempBuffer + (currentBlockSizeSamples * n);
  213430. ASIOChannelInfo channelInfo;
  213431. zerostruct (channelInfo);
  213432. channelInfo.channel = i;
  213433. channelInfo.isInput = 1;
  213434. asioObject->getChannelInfo (&channelInfo);
  213435. types.addIfNotAlreadyThere (channelInfo.type);
  213436. typeToFormatParameters (channelInfo.type,
  213437. inputChannelBitDepths[n],
  213438. inputChannelBytesPerSample[n],
  213439. inputChannelIsFloat[n],
  213440. inputChannelLittleEndian[n]);
  213441. currentBitDepth = jmax (currentBitDepth, inputChannelBitDepths[n]);
  213442. ++n;
  213443. }
  213444. }
  213445. jassert (numActiveInputChans == n);
  213446. n = 0;
  213447. for (i = 0; i < jmin (totalNumOutputChans, maxASIOChannels); ++i)
  213448. {
  213449. if (outputChannels[i])
  213450. {
  213451. outBuffers[n] = tempBuffer + (currentBlockSizeSamples * (numActiveInputChans + n));
  213452. ASIOChannelInfo channelInfo;
  213453. zerostruct (channelInfo);
  213454. channelInfo.channel = i;
  213455. channelInfo.isInput = 0;
  213456. asioObject->getChannelInfo (&channelInfo);
  213457. types.addIfNotAlreadyThere (channelInfo.type);
  213458. typeToFormatParameters (channelInfo.type,
  213459. outputChannelBitDepths[n],
  213460. outputChannelBytesPerSample[n],
  213461. outputChannelIsFloat[n],
  213462. outputChannelLittleEndian[n]);
  213463. currentBitDepth = jmax (currentBitDepth, outputChannelBitDepths[n]);
  213464. ++n;
  213465. }
  213466. }
  213467. jassert (numActiveOutputChans == n);
  213468. for (i = types.size(); --i >= 0;)
  213469. {
  213470. log (T("channel format: ") + String (types[i]));
  213471. }
  213472. jassert (n <= totalBuffers);
  213473. for (i = 0; i < numActiveOutputChans; ++i)
  213474. {
  213475. const int size = currentBlockSizeSamples * (outputChannelBitDepths[i] >> 3);
  213476. if (bufferInfos [numActiveInputChans + i].buffers[0] == 0
  213477. || bufferInfos [numActiveInputChans + i].buffers[1] == 0)
  213478. {
  213479. log ("!! Null buffers");
  213480. }
  213481. else
  213482. {
  213483. zeromem (bufferInfos[numActiveInputChans + i].buffers[0], size);
  213484. zeromem (bufferInfos[numActiveInputChans + i].buffers[1], size);
  213485. }
  213486. }
  213487. inputLatency = outputLatency = 0;
  213488. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213489. {
  213490. log ("ASIO - no latencies");
  213491. }
  213492. else
  213493. {
  213494. log (T("ASIO latencies: ")
  213495. + String ((int) outputLatency)
  213496. + T(", ")
  213497. + String ((int) inputLatency));
  213498. }
  213499. isOpen_ = true;
  213500. log ("starting ASIO");
  213501. calledback = false;
  213502. err = asioObject->start();
  213503. if (err != 0)
  213504. {
  213505. isOpen_ = false;
  213506. log ("ASIO - stop on failure");
  213507. Thread::sleep (10);
  213508. asioObject->stop();
  213509. error = "Can't start device";
  213510. Thread::sleep (10);
  213511. }
  213512. else
  213513. {
  213514. int count = 300;
  213515. while (--count > 0 && ! calledback)
  213516. Thread::sleep (10);
  213517. isStarted = true;
  213518. if (! calledback)
  213519. {
  213520. error = "Device didn't start correctly";
  213521. log ("ASIO didn't callback - stopping..");
  213522. asioObject->stop();
  213523. }
  213524. }
  213525. }
  213526. else
  213527. {
  213528. error = "Can't create i/o buffers";
  213529. }
  213530. }
  213531. else
  213532. {
  213533. error = "Can't set sample rate: ";
  213534. error << sampleRate;
  213535. }
  213536. if (error.isNotEmpty())
  213537. {
  213538. logError (error, err);
  213539. if (asioObject != 0 && buffersCreated)
  213540. asioObject->disposeBuffers();
  213541. Thread::sleep (20);
  213542. isStarted = false;
  213543. isOpen_ = false;
  213544. close();
  213545. }
  213546. needToReset = false;
  213547. isReSync = false;
  213548. return error;
  213549. }
  213550. void close()
  213551. {
  213552. error = String::empty;
  213553. stopTimer();
  213554. stop();
  213555. if (isASIOOpen && isOpen_)
  213556. {
  213557. const ScopedLock sl (callbackLock);
  213558. isOpen_ = false;
  213559. isStarted = false;
  213560. needToReset = false;
  213561. isReSync = false;
  213562. log ("ASIO - stopping");
  213563. if (asioObject != 0)
  213564. {
  213565. Thread::sleep (20);
  213566. asioObject->stop();
  213567. Thread::sleep (10);
  213568. asioObject->disposeBuffers();
  213569. }
  213570. Thread::sleep (10);
  213571. }
  213572. }
  213573. bool isOpen()
  213574. {
  213575. return isOpen_ || insideControlPanelModalLoop;
  213576. }
  213577. int getCurrentBufferSizeSamples()
  213578. {
  213579. return currentBlockSizeSamples;
  213580. }
  213581. double getCurrentSampleRate()
  213582. {
  213583. return currentSampleRate;
  213584. }
  213585. const BitArray getActiveOutputChannels() const
  213586. {
  213587. return currentChansOut;
  213588. }
  213589. const BitArray getActiveInputChannels() const
  213590. {
  213591. return currentChansIn;
  213592. }
  213593. int getCurrentBitDepth()
  213594. {
  213595. return currentBitDepth;
  213596. }
  213597. int getOutputLatencyInSamples()
  213598. {
  213599. return outputLatency + currentBlockSizeSamples / 4;
  213600. }
  213601. int getInputLatencyInSamples()
  213602. {
  213603. return inputLatency + currentBlockSizeSamples / 4;
  213604. }
  213605. void start (AudioIODeviceCallback* callback)
  213606. {
  213607. if (callback != 0)
  213608. {
  213609. callback->audioDeviceAboutToStart (this);
  213610. const ScopedLock sl (callbackLock);
  213611. currentCallback = callback;
  213612. }
  213613. }
  213614. void stop()
  213615. {
  213616. AudioIODeviceCallback* const lastCallback = currentCallback;
  213617. {
  213618. const ScopedLock sl (callbackLock);
  213619. currentCallback = 0;
  213620. }
  213621. if (lastCallback != 0)
  213622. lastCallback->audioDeviceStopped();
  213623. }
  213624. bool isPlaying()
  213625. {
  213626. return isASIOOpen && (currentCallback != 0);
  213627. }
  213628. const String getLastError()
  213629. {
  213630. return error;
  213631. }
  213632. bool hasControlPanel() const
  213633. {
  213634. return true;
  213635. }
  213636. bool showControlPanel()
  213637. {
  213638. log ("ASIO - showing control panel");
  213639. Component modalWindow (String::empty);
  213640. modalWindow.setOpaque (true);
  213641. modalWindow.addToDesktop (0);
  213642. modalWindow.enterModalState();
  213643. bool done = false;
  213644. JUCE_TRY
  213645. {
  213646. close();
  213647. insideControlPanelModalLoop = true;
  213648. const uint32 started = Time::getMillisecondCounter();
  213649. if (asioObject != 0)
  213650. {
  213651. asioObject->controlPanel();
  213652. const int spent = (int) Time::getMillisecondCounter() - (int) started;
  213653. log (T("spent: ") + String (spent));
  213654. if (spent > 300)
  213655. {
  213656. shouldUsePreferredSize = true;
  213657. done = true;
  213658. }
  213659. }
  213660. }
  213661. JUCE_CATCH_ALL
  213662. insideControlPanelModalLoop = false;
  213663. return done;
  213664. }
  213665. void resetRequest() throw()
  213666. {
  213667. needToReset = true;
  213668. }
  213669. void resyncRequest() throw()
  213670. {
  213671. needToReset = true;
  213672. isReSync = true;
  213673. }
  213674. void timerCallback()
  213675. {
  213676. if (! insideControlPanelModalLoop)
  213677. {
  213678. stopTimer();
  213679. // used to cause a reset
  213680. log ("! ASIO restart request!");
  213681. if (isOpen_)
  213682. {
  213683. AudioIODeviceCallback* const oldCallback = currentCallback;
  213684. close();
  213685. open (BitArray (currentChansIn), BitArray (currentChansOut),
  213686. currentSampleRate, currentBlockSizeSamples);
  213687. if (oldCallback != 0)
  213688. start (oldCallback);
  213689. }
  213690. }
  213691. else
  213692. {
  213693. startTimer (100);
  213694. }
  213695. }
  213696. juce_UseDebuggingNewOperator
  213697. private:
  213698. IASIO* volatile asioObject;
  213699. ASIOCallbacks callbacks;
  213700. void* windowHandle;
  213701. CLSID classId;
  213702. String error;
  213703. long totalNumInputChans, totalNumOutputChans;
  213704. StringArray inputChannelNames, outputChannelNames;
  213705. Array<int> sampleRates, bufferSizes;
  213706. long inputLatency, outputLatency;
  213707. long minSize, maxSize, preferredSize, granularity;
  213708. int volatile currentBlockSizeSamples;
  213709. int volatile currentBitDepth;
  213710. double volatile currentSampleRate;
  213711. BitArray currentChansOut, currentChansIn;
  213712. AudioIODeviceCallback* volatile currentCallback;
  213713. CriticalSection callbackLock;
  213714. ASIOBufferInfo bufferInfos [maxASIOChannels];
  213715. float* inBuffers [maxASIOChannels];
  213716. float* outBuffers [maxASIOChannels];
  213717. int inputChannelBitDepths [maxASIOChannels];
  213718. int outputChannelBitDepths [maxASIOChannels];
  213719. int inputChannelBytesPerSample [maxASIOChannels];
  213720. int outputChannelBytesPerSample [maxASIOChannels];
  213721. bool inputChannelIsFloat [maxASIOChannels];
  213722. bool outputChannelIsFloat [maxASIOChannels];
  213723. bool inputChannelLittleEndian [maxASIOChannels];
  213724. bool outputChannelLittleEndian [maxASIOChannels];
  213725. WaitableEvent event1;
  213726. float* tempBuffer;
  213727. int volatile bufferIndex, numActiveInputChans, numActiveOutputChans;
  213728. bool isOpen_, isStarted;
  213729. bool volatile isASIOOpen;
  213730. bool volatile calledback;
  213731. bool volatile littleEndian, postOutput, needToReset, isReSync;
  213732. bool volatile insideControlPanelModalLoop;
  213733. bool volatile shouldUsePreferredSize;
  213734. void removeCurrentDriver()
  213735. {
  213736. if (asioObject != 0)
  213737. {
  213738. asioObject->Release();
  213739. asioObject = 0;
  213740. }
  213741. }
  213742. bool loadDriver()
  213743. {
  213744. removeCurrentDriver();
  213745. JUCE_TRY
  213746. {
  213747. if (CoCreateInstance (classId, 0, CLSCTX_INPROC_SERVER,
  213748. classId, (void**) &asioObject) == S_OK)
  213749. {
  213750. return true;
  213751. }
  213752. }
  213753. JUCE_CATCH_ALL
  213754. asioObject = 0;
  213755. return false;
  213756. }
  213757. const String initDriver()
  213758. {
  213759. if (asioObject != 0)
  213760. {
  213761. char buffer [256];
  213762. zeromem (buffer, sizeof (buffer));
  213763. if (! asioObject->init (windowHandle))
  213764. {
  213765. asioObject->getErrorMessage (buffer);
  213766. return String (buffer, sizeof (buffer) - 1);
  213767. }
  213768. // just in case any daft drivers expect this to be called..
  213769. asioObject->getDriverName (buffer);
  213770. return String::empty;
  213771. }
  213772. return "No Driver";
  213773. }
  213774. const String openDevice()
  213775. {
  213776. // use this in case the driver starts opening dialog boxes..
  213777. Component modalWindow (String::empty);
  213778. modalWindow.setOpaque (true);
  213779. modalWindow.addToDesktop (0);
  213780. modalWindow.enterModalState();
  213781. // open the device and get its info..
  213782. log (T("opening ASIO device: ") + getName());
  213783. needToReset = false;
  213784. isReSync = false;
  213785. outputChannelNames.clear();
  213786. inputChannelNames.clear();
  213787. bufferSizes.clear();
  213788. sampleRates.clear();
  213789. isASIOOpen = false;
  213790. isOpen_ = false;
  213791. totalNumInputChans = 0;
  213792. totalNumOutputChans = 0;
  213793. numActiveInputChans = 0;
  213794. numActiveOutputChans = 0;
  213795. currentCallback = 0;
  213796. error = String::empty;
  213797. if (getName().isEmpty())
  213798. return error;
  213799. long err = 0;
  213800. if (loadDriver())
  213801. {
  213802. if ((error = initDriver()).isEmpty())
  213803. {
  213804. numActiveInputChans = 0;
  213805. numActiveOutputChans = 0;
  213806. totalNumInputChans = 0;
  213807. totalNumOutputChans = 0;
  213808. if (asioObject != 0
  213809. && (err = asioObject->getChannels (&totalNumInputChans, &totalNumOutputChans)) == 0)
  213810. {
  213811. log (String ((int) totalNumInputChans) + T(" in, ") + String ((int) totalNumOutputChans) + T(" out"));
  213812. if ((err = asioObject->getBufferSize (&minSize, &maxSize, &preferredSize, &granularity)) == 0)
  213813. {
  213814. // find a list of buffer sizes..
  213815. log (String ((int) minSize) + T(" ") + String ((int) maxSize) + T(" ") + String ((int)preferredSize) + T(" ") + String ((int)granularity));
  213816. if (granularity >= 0)
  213817. {
  213818. granularity = jmax (1, (int) granularity);
  213819. for (int i = jmax (minSize, (int) granularity); i < jmin (6400, maxSize); i += granularity)
  213820. bufferSizes.addIfNotAlreadyThere (granularity * (i / granularity));
  213821. }
  213822. else if (granularity < 0)
  213823. {
  213824. for (int i = 0; i < 18; ++i)
  213825. {
  213826. const int s = (1 << i);
  213827. if (s >= minSize && s <= maxSize)
  213828. bufferSizes.add (s);
  213829. }
  213830. }
  213831. if (! bufferSizes.contains (preferredSize))
  213832. bufferSizes.insert (0, preferredSize);
  213833. double currentRate = 0;
  213834. asioObject->getSampleRate (&currentRate);
  213835. if (currentRate <= 0.0 || currentRate > 192001.0)
  213836. {
  213837. log ("setting sample rate");
  213838. err = asioObject->setSampleRate (44100.0);
  213839. if (err != 0)
  213840. {
  213841. logError ("setting sample rate", err);
  213842. }
  213843. asioObject->getSampleRate (&currentRate);
  213844. }
  213845. currentSampleRate = currentRate;
  213846. postOutput = (asioObject->outputReady() == 0);
  213847. if (postOutput)
  213848. {
  213849. log ("ASIO outputReady = ok");
  213850. }
  213851. updateSampleRates();
  213852. // ..because cubase does it at this point
  213853. inputLatency = outputLatency = 0;
  213854. if (asioObject->getLatencies (&inputLatency, &outputLatency) != 0)
  213855. {
  213856. log ("ASIO - no latencies");
  213857. }
  213858. log (String ("latencies: ")
  213859. + String ((int) inputLatency)
  213860. + T(", ") + String ((int) outputLatency));
  213861. // create some dummy buffers now.. because cubase does..
  213862. numActiveInputChans = 0;
  213863. numActiveOutputChans = 0;
  213864. ASIOBufferInfo* info = bufferInfos;
  213865. int i, numChans = 0;
  213866. for (i = 0; i < jmin (2, totalNumInputChans); ++i)
  213867. {
  213868. info->isInput = 1;
  213869. info->channelNum = i;
  213870. info->buffers[0] = info->buffers[1] = 0;
  213871. ++info;
  213872. ++numChans;
  213873. }
  213874. const int outputBufferIndex = numChans;
  213875. for (i = 0; i < jmin (2, totalNumOutputChans); ++i)
  213876. {
  213877. info->isInput = 0;
  213878. info->channelNum = i;
  213879. info->buffers[0] = info->buffers[1] = 0;
  213880. ++info;
  213881. ++numChans;
  213882. }
  213883. callbacks.sampleRateDidChange = &sampleRateChangedCallback;
  213884. if (currentASIODev[0] == this)
  213885. {
  213886. callbacks.bufferSwitch = &bufferSwitchCallback0;
  213887. callbacks.asioMessage = &asioMessagesCallback0;
  213888. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback0;
  213889. }
  213890. else if (currentASIODev[1] == this)
  213891. {
  213892. callbacks.bufferSwitch = &bufferSwitchCallback1;
  213893. callbacks.asioMessage = &asioMessagesCallback1;
  213894. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback1;
  213895. }
  213896. else if (currentASIODev[2] == this)
  213897. {
  213898. callbacks.bufferSwitch = &bufferSwitchCallback2;
  213899. callbacks.asioMessage = &asioMessagesCallback2;
  213900. callbacks.bufferSwitchTimeInfo = &bufferSwitchTimeInfoCallback2;
  213901. }
  213902. else
  213903. {
  213904. jassertfalse
  213905. }
  213906. log (T("creating buffers (dummy): ") + String (numChans)
  213907. + T(", ") + String ((int) preferredSize));
  213908. if (preferredSize > 0)
  213909. {
  213910. err = asioObject->createBuffers (bufferInfos, numChans, preferredSize, &callbacks);
  213911. if (err != 0)
  213912. {
  213913. logError ("dummy buffers", err);
  213914. }
  213915. }
  213916. long newInps = 0, newOuts = 0;
  213917. asioObject->getChannels (&newInps, &newOuts);
  213918. if (totalNumInputChans != newInps || totalNumOutputChans != newOuts)
  213919. {
  213920. totalNumInputChans = newInps;
  213921. totalNumOutputChans = newOuts;
  213922. log (String ((int) totalNumInputChans) + T(" in; ")
  213923. + String ((int) totalNumOutputChans) + T(" out"));
  213924. }
  213925. updateSampleRates();
  213926. ASIOChannelInfo channelInfo;
  213927. channelInfo.type = 0;
  213928. for (i = 0; i < totalNumInputChans; ++i)
  213929. {
  213930. zerostruct (channelInfo);
  213931. channelInfo.channel = i;
  213932. channelInfo.isInput = 1;
  213933. asioObject->getChannelInfo (&channelInfo);
  213934. inputChannelNames.add (String (channelInfo.name));
  213935. }
  213936. for (i = 0; i < totalNumOutputChans; ++i)
  213937. {
  213938. zerostruct (channelInfo);
  213939. channelInfo.channel = i;
  213940. channelInfo.isInput = 0;
  213941. asioObject->getChannelInfo (&channelInfo);
  213942. outputChannelNames.add (String (channelInfo.name));
  213943. typeToFormatParameters (channelInfo.type,
  213944. outputChannelBitDepths[i],
  213945. outputChannelBytesPerSample[i],
  213946. outputChannelIsFloat[i],
  213947. outputChannelLittleEndian[i]);
  213948. if (i < 2)
  213949. {
  213950. // clear the channels that are used with the dummy stuff
  213951. const int bytesPerBuffer = preferredSize * (outputChannelBitDepths[i] >> 3);
  213952. zeromem (bufferInfos [outputBufferIndex + i].buffers[0], bytesPerBuffer);
  213953. zeromem (bufferInfos [outputBufferIndex + i].buffers[1], bytesPerBuffer);
  213954. }
  213955. }
  213956. outputChannelNames.trim();
  213957. inputChannelNames.trim();
  213958. outputChannelNames.appendNumbersToDuplicates (false, true);
  213959. inputChannelNames.appendNumbersToDuplicates (false, true);
  213960. // start and stop because cubase does it..
  213961. asioObject->getLatencies (&inputLatency, &outputLatency);
  213962. if ((err = asioObject->start()) != 0)
  213963. {
  213964. // ignore an error here, as it might start later after setting other stuff up
  213965. logError ("ASIO start", err);
  213966. }
  213967. Thread::sleep (100);
  213968. asioObject->stop();
  213969. }
  213970. else
  213971. {
  213972. error = "Can't detect buffer sizes";
  213973. }
  213974. }
  213975. else
  213976. {
  213977. error = "Can't detect asio channels";
  213978. }
  213979. }
  213980. }
  213981. else
  213982. {
  213983. error = "No such device";
  213984. }
  213985. if (error.isNotEmpty())
  213986. {
  213987. logError (error, err);
  213988. if (asioObject != 0)
  213989. asioObject->disposeBuffers();
  213990. removeCurrentDriver();
  213991. isASIOOpen = false;
  213992. }
  213993. else
  213994. {
  213995. isASIOOpen = true;
  213996. log ("ASIO device open");
  213997. }
  213998. isOpen_ = false;
  213999. needToReset = false;
  214000. isReSync = false;
  214001. return error;
  214002. }
  214003. void callback (const long index) throw()
  214004. {
  214005. if (isStarted)
  214006. {
  214007. bufferIndex = index;
  214008. processBuffer();
  214009. }
  214010. else
  214011. {
  214012. if (postOutput && (asioObject != 0))
  214013. asioObject->outputReady();
  214014. }
  214015. calledback = true;
  214016. }
  214017. void processBuffer() throw()
  214018. {
  214019. const ASIOBufferInfo* const infos = bufferInfos;
  214020. const int bi = bufferIndex;
  214021. const ScopedLock sl (callbackLock);
  214022. if (needToReset)
  214023. {
  214024. needToReset = false;
  214025. if (isReSync)
  214026. {
  214027. log ("! ASIO resync");
  214028. isReSync = false;
  214029. }
  214030. else
  214031. {
  214032. startTimer (20);
  214033. }
  214034. }
  214035. if (bi >= 0)
  214036. {
  214037. const int samps = currentBlockSizeSamples;
  214038. if (currentCallback != 0)
  214039. {
  214040. int i;
  214041. for (i = 0; i < numActiveInputChans; ++i)
  214042. {
  214043. float* const dst = inBuffers[i];
  214044. jassert (dst != 0);
  214045. const char* const src = (const char*) (infos[i].buffers[bi]);
  214046. if (inputChannelIsFloat[i])
  214047. {
  214048. memcpy (dst, src, samps * sizeof (float));
  214049. }
  214050. else
  214051. {
  214052. jassert (dst == tempBuffer + (samps * i));
  214053. switch (inputChannelBitDepths[i])
  214054. {
  214055. case 16:
  214056. convertInt16ToFloat (src, dst, inputChannelBytesPerSample[i],
  214057. samps, inputChannelLittleEndian[i]);
  214058. break;
  214059. case 24:
  214060. convertInt24ToFloat (src, dst, inputChannelBytesPerSample[i],
  214061. samps, inputChannelLittleEndian[i]);
  214062. break;
  214063. case 32:
  214064. convertInt32ToFloat (src, dst, inputChannelBytesPerSample[i],
  214065. samps, inputChannelLittleEndian[i]);
  214066. break;
  214067. case 64:
  214068. jassertfalse
  214069. break;
  214070. }
  214071. }
  214072. }
  214073. currentCallback->audioDeviceIOCallback ((const float**) inBuffers,
  214074. numActiveInputChans,
  214075. outBuffers,
  214076. numActiveOutputChans,
  214077. samps);
  214078. for (i = 0; i < numActiveOutputChans; ++i)
  214079. {
  214080. float* const src = outBuffers[i];
  214081. jassert (src != 0);
  214082. char* const dst = (char*) (infos [numActiveInputChans + i].buffers[bi]);
  214083. if (outputChannelIsFloat[i])
  214084. {
  214085. memcpy (dst, src, samps * sizeof (float));
  214086. }
  214087. else
  214088. {
  214089. jassert (src == tempBuffer + (samps * (numActiveInputChans + i)));
  214090. switch (outputChannelBitDepths[i])
  214091. {
  214092. case 16:
  214093. convertFloatToInt16 (src, dst, outputChannelBytesPerSample[i],
  214094. samps, outputChannelLittleEndian[i]);
  214095. break;
  214096. case 24:
  214097. convertFloatToInt24 (src, dst, outputChannelBytesPerSample[i],
  214098. samps, outputChannelLittleEndian[i]);
  214099. break;
  214100. case 32:
  214101. convertFloatToInt32 (src, dst, outputChannelBytesPerSample[i],
  214102. samps, outputChannelLittleEndian[i]);
  214103. break;
  214104. case 64:
  214105. jassertfalse
  214106. break;
  214107. }
  214108. }
  214109. }
  214110. }
  214111. else
  214112. {
  214113. for (int i = 0; i < numActiveOutputChans; ++i)
  214114. {
  214115. const int bytesPerBuffer = samps * (outputChannelBitDepths[i] >> 3);
  214116. zeromem (infos[numActiveInputChans + i].buffers[bi], bytesPerBuffer);
  214117. }
  214118. }
  214119. }
  214120. if (postOutput)
  214121. asioObject->outputReady();
  214122. }
  214123. static ASIOTime* bufferSwitchTimeInfoCallback0 (ASIOTime*, long index, long) throw()
  214124. {
  214125. if (currentASIODev[0] != 0)
  214126. currentASIODev[0]->callback (index);
  214127. return 0;
  214128. }
  214129. static ASIOTime* bufferSwitchTimeInfoCallback1 (ASIOTime*, long index, long) throw()
  214130. {
  214131. if (currentASIODev[1] != 0)
  214132. currentASIODev[1]->callback (index);
  214133. return 0;
  214134. }
  214135. static ASIOTime* bufferSwitchTimeInfoCallback2 (ASIOTime*, long index, long) throw()
  214136. {
  214137. if (currentASIODev[2] != 0)
  214138. currentASIODev[2]->callback (index);
  214139. return 0;
  214140. }
  214141. static void bufferSwitchCallback0 (long index, long) throw()
  214142. {
  214143. if (currentASIODev[0] != 0)
  214144. currentASIODev[0]->callback (index);
  214145. }
  214146. static void bufferSwitchCallback1 (long index, long) throw()
  214147. {
  214148. if (currentASIODev[1] != 0)
  214149. currentASIODev[1]->callback (index);
  214150. }
  214151. static void bufferSwitchCallback2 (long index, long) throw()
  214152. {
  214153. if (currentASIODev[2] != 0)
  214154. currentASIODev[2]->callback (index);
  214155. }
  214156. static long asioMessagesCallback0 (long selector, long value, void*, double*) throw()
  214157. {
  214158. return asioMessagesCallback (selector, value, 0);
  214159. }
  214160. static long asioMessagesCallback1 (long selector, long value, void*, double*) throw()
  214161. {
  214162. return asioMessagesCallback (selector, value, 1);
  214163. }
  214164. static long asioMessagesCallback2 (long selector, long value, void*, double*) throw()
  214165. {
  214166. return asioMessagesCallback (selector, value, 2);
  214167. }
  214168. static long asioMessagesCallback (long selector, long value, const int deviceIndex) throw()
  214169. {
  214170. switch (selector)
  214171. {
  214172. case kAsioSelectorSupported:
  214173. if (value == kAsioResetRequest
  214174. || value == kAsioEngineVersion
  214175. || value == kAsioResyncRequest
  214176. || value == kAsioLatenciesChanged
  214177. || value == kAsioSupportsInputMonitor)
  214178. return 1;
  214179. break;
  214180. case kAsioBufferSizeChange:
  214181. break;
  214182. case kAsioResetRequest:
  214183. if (currentASIODev[deviceIndex] != 0)
  214184. currentASIODev[deviceIndex]->resetRequest();
  214185. return 1;
  214186. case kAsioResyncRequest:
  214187. if (currentASIODev[deviceIndex] != 0)
  214188. currentASIODev[deviceIndex]->resyncRequest();
  214189. return 1;
  214190. case kAsioLatenciesChanged:
  214191. return 1;
  214192. case kAsioEngineVersion:
  214193. return 2;
  214194. case kAsioSupportsTimeInfo:
  214195. case kAsioSupportsTimeCode:
  214196. return 0;
  214197. }
  214198. return 0;
  214199. }
  214200. static void sampleRateChangedCallback (ASIOSampleRate) throw()
  214201. {
  214202. }
  214203. static void convertInt16ToFloat (const char* src,
  214204. float* dest,
  214205. const int srcStrideBytes,
  214206. int numSamples,
  214207. const bool littleEndian) throw()
  214208. {
  214209. const double g = 1.0 / 32768.0;
  214210. if (littleEndian)
  214211. {
  214212. while (--numSamples >= 0)
  214213. {
  214214. *dest++ = (float) (g * (short) littleEndianShort (src));
  214215. src += srcStrideBytes;
  214216. }
  214217. }
  214218. else
  214219. {
  214220. while (--numSamples >= 0)
  214221. {
  214222. *dest++ = (float) (g * (short) bigEndianShort (src));
  214223. src += srcStrideBytes;
  214224. }
  214225. }
  214226. }
  214227. static void convertFloatToInt16 (const float* src,
  214228. char* dest,
  214229. const int dstStrideBytes,
  214230. int numSamples,
  214231. const bool littleEndian) throw()
  214232. {
  214233. const double maxVal = (double) 0x7fff;
  214234. if (littleEndian)
  214235. {
  214236. while (--numSamples >= 0)
  214237. {
  214238. *(uint16*) dest = swapIfBigEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214239. dest += dstStrideBytes;
  214240. }
  214241. }
  214242. else
  214243. {
  214244. while (--numSamples >= 0)
  214245. {
  214246. *(uint16*) dest = swapIfLittleEndian ((uint16) (short) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214247. dest += dstStrideBytes;
  214248. }
  214249. }
  214250. }
  214251. static void convertInt24ToFloat (const char* src,
  214252. float* dest,
  214253. const int srcStrideBytes,
  214254. int numSamples,
  214255. const bool littleEndian) throw()
  214256. {
  214257. const double g = 1.0 / 0x7fffff;
  214258. if (littleEndian)
  214259. {
  214260. while (--numSamples >= 0)
  214261. {
  214262. *dest++ = (float) (g * littleEndian24Bit (src));
  214263. src += srcStrideBytes;
  214264. }
  214265. }
  214266. else
  214267. {
  214268. while (--numSamples >= 0)
  214269. {
  214270. *dest++ = (float) (g * bigEndian24Bit (src));
  214271. src += srcStrideBytes;
  214272. }
  214273. }
  214274. }
  214275. static void convertFloatToInt24 (const float* src,
  214276. char* dest,
  214277. const int dstStrideBytes,
  214278. int numSamples,
  214279. const bool littleEndian) throw()
  214280. {
  214281. const double maxVal = (double) 0x7fffff;
  214282. if (littleEndian)
  214283. {
  214284. while (--numSamples >= 0)
  214285. {
  214286. littleEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  214287. dest += dstStrideBytes;
  214288. }
  214289. }
  214290. else
  214291. {
  214292. while (--numSamples >= 0)
  214293. {
  214294. bigEndian24BitToChars ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)), dest);
  214295. dest += dstStrideBytes;
  214296. }
  214297. }
  214298. }
  214299. static void convertInt32ToFloat (const char* src,
  214300. float* dest,
  214301. const int srcStrideBytes,
  214302. int numSamples,
  214303. const bool littleEndian) throw()
  214304. {
  214305. const double g = 1.0 / 0x7fffffff;
  214306. if (littleEndian)
  214307. {
  214308. while (--numSamples >= 0)
  214309. {
  214310. *dest++ = (float) (g * (int) littleEndianInt (src));
  214311. src += srcStrideBytes;
  214312. }
  214313. }
  214314. else
  214315. {
  214316. while (--numSamples >= 0)
  214317. {
  214318. *dest++ = (float) (g * (int) bigEndianInt (src));
  214319. src += srcStrideBytes;
  214320. }
  214321. }
  214322. }
  214323. static void convertFloatToInt32 (const float* src,
  214324. char* dest,
  214325. const int dstStrideBytes,
  214326. int numSamples,
  214327. const bool littleEndian) throw()
  214328. {
  214329. const double maxVal = (double) 0x7fffffff;
  214330. if (littleEndian)
  214331. {
  214332. while (--numSamples >= 0)
  214333. {
  214334. *(uint32*) dest = swapIfBigEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214335. dest += dstStrideBytes;
  214336. }
  214337. }
  214338. else
  214339. {
  214340. while (--numSamples >= 0)
  214341. {
  214342. *(uint32*) dest = swapIfLittleEndian ((uint32) roundDoubleToInt (jlimit (-maxVal, maxVal, maxVal * *src++)));
  214343. dest += dstStrideBytes;
  214344. }
  214345. }
  214346. }
  214347. static void typeToFormatParameters (const long type,
  214348. int& bitDepth,
  214349. int& byteStride,
  214350. bool& formatIsFloat,
  214351. bool& littleEndian) throw()
  214352. {
  214353. bitDepth = 0;
  214354. littleEndian = false;
  214355. formatIsFloat = false;
  214356. switch (type)
  214357. {
  214358. case ASIOSTInt16MSB:
  214359. case ASIOSTInt16LSB:
  214360. case ASIOSTInt32MSB16:
  214361. case ASIOSTInt32LSB16:
  214362. bitDepth = 16; break;
  214363. case ASIOSTFloat32MSB:
  214364. case ASIOSTFloat32LSB:
  214365. formatIsFloat = true;
  214366. bitDepth = 32; break;
  214367. case ASIOSTInt32MSB:
  214368. case ASIOSTInt32LSB:
  214369. bitDepth = 32; break;
  214370. case ASIOSTInt24MSB:
  214371. case ASIOSTInt24LSB:
  214372. case ASIOSTInt32MSB24:
  214373. case ASIOSTInt32LSB24:
  214374. case ASIOSTInt32MSB18:
  214375. case ASIOSTInt32MSB20:
  214376. case ASIOSTInt32LSB18:
  214377. case ASIOSTInt32LSB20:
  214378. bitDepth = 24; break;
  214379. case ASIOSTFloat64MSB:
  214380. case ASIOSTFloat64LSB:
  214381. default:
  214382. bitDepth = 64;
  214383. break;
  214384. }
  214385. switch (type)
  214386. {
  214387. case ASIOSTInt16MSB:
  214388. case ASIOSTInt32MSB16:
  214389. case ASIOSTFloat32MSB:
  214390. case ASIOSTFloat64MSB:
  214391. case ASIOSTInt32MSB:
  214392. case ASIOSTInt32MSB18:
  214393. case ASIOSTInt32MSB20:
  214394. case ASIOSTInt32MSB24:
  214395. case ASIOSTInt24MSB:
  214396. littleEndian = false; break;
  214397. case ASIOSTInt16LSB:
  214398. case ASIOSTInt32LSB16:
  214399. case ASIOSTFloat32LSB:
  214400. case ASIOSTFloat64LSB:
  214401. case ASIOSTInt32LSB:
  214402. case ASIOSTInt32LSB18:
  214403. case ASIOSTInt32LSB20:
  214404. case ASIOSTInt32LSB24:
  214405. case ASIOSTInt24LSB:
  214406. littleEndian = true; break;
  214407. default:
  214408. break;
  214409. }
  214410. switch (type)
  214411. {
  214412. case ASIOSTInt16LSB:
  214413. case ASIOSTInt16MSB:
  214414. byteStride = 2; break;
  214415. case ASIOSTInt24LSB:
  214416. case ASIOSTInt24MSB:
  214417. byteStride = 3; break;
  214418. case ASIOSTInt32MSB16:
  214419. case ASIOSTInt32LSB16:
  214420. case ASIOSTInt32MSB:
  214421. case ASIOSTInt32MSB18:
  214422. case ASIOSTInt32MSB20:
  214423. case ASIOSTInt32MSB24:
  214424. case ASIOSTInt32LSB:
  214425. case ASIOSTInt32LSB18:
  214426. case ASIOSTInt32LSB20:
  214427. case ASIOSTInt32LSB24:
  214428. case ASIOSTFloat32LSB:
  214429. case ASIOSTFloat32MSB:
  214430. byteStride = 4; break;
  214431. case ASIOSTFloat64MSB:
  214432. case ASIOSTFloat64LSB:
  214433. byteStride = 8; break;
  214434. default:
  214435. break;
  214436. }
  214437. }
  214438. };
  214439. class ASIOAudioIODeviceType : public AudioIODeviceType
  214440. {
  214441. public:
  214442. ASIOAudioIODeviceType()
  214443. : AudioIODeviceType (T("ASIO")),
  214444. classIds (2),
  214445. hasScanned (false)
  214446. {
  214447. CoInitialize (0);
  214448. }
  214449. ~ASIOAudioIODeviceType()
  214450. {
  214451. }
  214452. void scanForDevices()
  214453. {
  214454. hasScanned = true;
  214455. deviceNames.clear();
  214456. classIds.clear();
  214457. HKEY hk = 0;
  214458. int index = 0;
  214459. if (RegOpenKeyA (HKEY_LOCAL_MACHINE, "software\\asio", &hk) == ERROR_SUCCESS)
  214460. {
  214461. for (;;)
  214462. {
  214463. char name [256];
  214464. if (RegEnumKeyA (hk, index++, name, 256) == ERROR_SUCCESS)
  214465. {
  214466. addDriverInfo (name, hk);
  214467. }
  214468. else
  214469. {
  214470. break;
  214471. }
  214472. }
  214473. RegCloseKey (hk);
  214474. }
  214475. }
  214476. const StringArray getDeviceNames (const bool /*wantInputNames*/) const
  214477. {
  214478. jassert (hasScanned); // need to call scanForDevices() before doing this
  214479. return deviceNames;
  214480. }
  214481. int getDefaultDeviceIndex (const bool) const
  214482. {
  214483. jassert (hasScanned); // need to call scanForDevices() before doing this
  214484. for (int i = deviceNames.size(); --i >= 0;)
  214485. if (deviceNames[i].containsIgnoreCase (T("asio4all")))
  214486. return i; // asio4all is a safe choice for a default..
  214487. #if JUCE_DEBUG
  214488. if (deviceNames.size() > 1 && deviceNames[0].containsIgnoreCase (T("digidesign")))
  214489. return 1; // (the digi m-box driver crashes the app when you run
  214490. // it in the debugger, which can be a bit annoying)
  214491. #endif
  214492. return 0;
  214493. }
  214494. static int findFreeSlot()
  214495. {
  214496. for (int i = 0; i < numElementsInArray (currentASIODev); ++i)
  214497. if (currentASIODev[i] == 0)
  214498. return i;
  214499. jassertfalse; // unfortunately you can only have a finite number
  214500. // of ASIO devices open at the same time..
  214501. return -1;
  214502. }
  214503. int getIndexOfDevice (AudioIODevice* d, const bool /*asInput*/) const
  214504. {
  214505. jassert (hasScanned); // need to call scanForDevices() before doing this
  214506. return d == 0 ? -1 : deviceNames.indexOf (d->getName());
  214507. }
  214508. bool hasSeparateInputsAndOutputs() const { return false; }
  214509. AudioIODevice* createDevice (const String& outputDeviceName,
  214510. const String& inputDeviceName)
  214511. {
  214512. jassert (inputDeviceName == outputDeviceName);
  214513. (void) inputDeviceName;
  214514. jassert (hasScanned); // need to call scanForDevices() before doing this
  214515. const int index = deviceNames.indexOf (outputDeviceName);
  214516. if (index >= 0)
  214517. {
  214518. const int freeSlot = findFreeSlot();
  214519. if (freeSlot >= 0)
  214520. return new ASIOAudioIODevice (outputDeviceName, *(classIds [index]), freeSlot);
  214521. }
  214522. return 0;
  214523. }
  214524. juce_UseDebuggingNewOperator
  214525. private:
  214526. StringArray deviceNames;
  214527. OwnedArray <CLSID> classIds;
  214528. bool hasScanned;
  214529. static bool checkClassIsOk (const String& classId)
  214530. {
  214531. HKEY hk = 0;
  214532. bool ok = false;
  214533. if (RegOpenKeyA (HKEY_CLASSES_ROOT, "clsid", &hk) == ERROR_SUCCESS)
  214534. {
  214535. int index = 0;
  214536. for (;;)
  214537. {
  214538. char buf [512];
  214539. if (RegEnumKeyA (hk, index++, buf, 512) == ERROR_SUCCESS)
  214540. {
  214541. if (classId.equalsIgnoreCase (buf))
  214542. {
  214543. HKEY subKey, pathKey;
  214544. if (RegOpenKeyExA (hk, buf, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214545. {
  214546. if (RegOpenKeyExA (subKey, "InprocServer32", 0, KEY_READ, &pathKey) == ERROR_SUCCESS)
  214547. {
  214548. char pathName [600];
  214549. DWORD dtype = REG_SZ;
  214550. DWORD dsize = sizeof (pathName);
  214551. if (RegQueryValueExA (pathKey, 0, 0, &dtype,
  214552. (LPBYTE) pathName, &dsize) == ERROR_SUCCESS)
  214553. {
  214554. OFSTRUCT of;
  214555. zerostruct (of);
  214556. of.cBytes = sizeof (of);
  214557. ok = (OpenFile (String (pathName), &of, OF_EXIST) != 0);
  214558. }
  214559. RegCloseKey (pathKey);
  214560. }
  214561. RegCloseKey (subKey);
  214562. }
  214563. break;
  214564. }
  214565. }
  214566. else
  214567. {
  214568. break;
  214569. }
  214570. }
  214571. RegCloseKey (hk);
  214572. }
  214573. return ok;
  214574. }
  214575. void addDriverInfo (const String& keyName, HKEY hk)
  214576. {
  214577. HKEY subKey;
  214578. if (RegOpenKeyExA (hk, keyName, 0, KEY_READ, &subKey) == ERROR_SUCCESS)
  214579. {
  214580. char buf [256];
  214581. DWORD dtype = REG_SZ;
  214582. DWORD dsize = sizeof (buf);
  214583. zeromem (buf, dsize);
  214584. if (RegQueryValueExA (subKey, "clsid", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214585. {
  214586. if (dsize > 0 && checkClassIsOk (buf))
  214587. {
  214588. wchar_t classIdStr [130];
  214589. MultiByteToWideChar (CP_ACP, 0, buf, -1, classIdStr, 128);
  214590. String deviceName;
  214591. CLSID classId;
  214592. if (CLSIDFromString ((LPOLESTR) classIdStr, &classId) == S_OK)
  214593. {
  214594. dtype = REG_SZ;
  214595. dsize = sizeof (buf);
  214596. if (RegQueryValueExA (subKey, "description", 0, &dtype, (LPBYTE) buf, &dsize) == ERROR_SUCCESS)
  214597. deviceName = buf;
  214598. else
  214599. deviceName = keyName;
  214600. log (T("found ") + deviceName);
  214601. deviceNames.add (deviceName);
  214602. classIds.add (new CLSID (classId));
  214603. }
  214604. }
  214605. RegCloseKey (subKey);
  214606. }
  214607. }
  214608. }
  214609. ASIOAudioIODeviceType (const ASIOAudioIODeviceType&);
  214610. const ASIOAudioIODeviceType& operator= (const ASIOAudioIODeviceType&);
  214611. };
  214612. AudioIODeviceType* juce_createASIOAudioIODeviceType()
  214613. {
  214614. return new ASIOAudioIODeviceType();
  214615. }
  214616. AudioIODevice* juce_createASIOAudioIODeviceForGUID (const String& name,
  214617. void* guid)
  214618. {
  214619. const int freeSlot = ASIOAudioIODeviceType::findFreeSlot();
  214620. if (freeSlot < 0)
  214621. return 0;
  214622. return new ASIOAudioIODevice (name, *(CLSID*) guid, freeSlot);
  214623. }
  214624. #undef log
  214625. #endif
  214626. /********* End of inlined file: juce_win32_ASIO.cpp *********/
  214627. /********* Start of inlined file: juce_win32_DirectSound.cpp *********/
  214628. // (This file gets included by juce_win32_NativeCode.cpp, rather than being
  214629. // compiled on its own).
  214630. #if JUCE_INCLUDED_FILE
  214631. END_JUCE_NAMESPACE
  214632. extern "C"
  214633. {
  214634. // Declare just the minimum number of interfaces for the DSound objects that we need..
  214635. typedef struct typeDSBUFFERDESC
  214636. {
  214637. DWORD dwSize;
  214638. DWORD dwFlags;
  214639. DWORD dwBufferBytes;
  214640. DWORD dwReserved;
  214641. LPWAVEFORMATEX lpwfxFormat;
  214642. GUID guid3DAlgorithm;
  214643. } DSBUFFERDESC;
  214644. struct IDirectSoundBuffer;
  214645. #undef INTERFACE
  214646. #define INTERFACE IDirectSound
  214647. DECLARE_INTERFACE_(IDirectSound, IUnknown)
  214648. {
  214649. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214650. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214651. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214652. STDMETHOD(CreateSoundBuffer) (THIS_ DSBUFFERDESC*, IDirectSoundBuffer**, LPUNKNOWN) PURE;
  214653. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214654. STDMETHOD(DuplicateSoundBuffer) (THIS_ IDirectSoundBuffer*, IDirectSoundBuffer**) PURE;
  214655. STDMETHOD(SetCooperativeLevel) (THIS_ HWND, DWORD) PURE;
  214656. STDMETHOD(Compact) (THIS) PURE;
  214657. STDMETHOD(GetSpeakerConfig) (THIS_ LPDWORD) PURE;
  214658. STDMETHOD(SetSpeakerConfig) (THIS_ DWORD) PURE;
  214659. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214660. };
  214661. #undef INTERFACE
  214662. #define INTERFACE IDirectSoundBuffer
  214663. DECLARE_INTERFACE_(IDirectSoundBuffer, IUnknown)
  214664. {
  214665. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214666. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214667. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214668. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214669. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214670. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214671. STDMETHOD(GetVolume) (THIS_ LPLONG) PURE;
  214672. STDMETHOD(GetPan) (THIS_ LPLONG) PURE;
  214673. STDMETHOD(GetFrequency) (THIS_ LPDWORD) PURE;
  214674. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214675. STDMETHOD(Initialize) (THIS_ IDirectSound*, DSBUFFERDESC*) PURE;
  214676. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214677. STDMETHOD(Play) (THIS_ DWORD, DWORD, DWORD) PURE;
  214678. STDMETHOD(SetCurrentPosition) (THIS_ DWORD) PURE;
  214679. STDMETHOD(SetFormat) (THIS_ const WAVEFORMATEX*) PURE;
  214680. STDMETHOD(SetVolume) (THIS_ LONG) PURE;
  214681. STDMETHOD(SetPan) (THIS_ LONG) PURE;
  214682. STDMETHOD(SetFrequency) (THIS_ DWORD) PURE;
  214683. STDMETHOD(Stop) (THIS) PURE;
  214684. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214685. STDMETHOD(Restore) (THIS) PURE;
  214686. };
  214687. typedef struct typeDSCBUFFERDESC
  214688. {
  214689. DWORD dwSize;
  214690. DWORD dwFlags;
  214691. DWORD dwBufferBytes;
  214692. DWORD dwReserved;
  214693. LPWAVEFORMATEX lpwfxFormat;
  214694. } DSCBUFFERDESC;
  214695. struct IDirectSoundCaptureBuffer;
  214696. #undef INTERFACE
  214697. #define INTERFACE IDirectSoundCapture
  214698. DECLARE_INTERFACE_(IDirectSoundCapture, IUnknown)
  214699. {
  214700. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214701. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214702. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214703. STDMETHOD(CreateCaptureBuffer) (THIS_ DSCBUFFERDESC*, IDirectSoundCaptureBuffer**, LPUNKNOWN) PURE;
  214704. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214705. STDMETHOD(Initialize) (THIS_ const GUID*) PURE;
  214706. };
  214707. #undef INTERFACE
  214708. #define INTERFACE IDirectSoundCaptureBuffer
  214709. DECLARE_INTERFACE_(IDirectSoundCaptureBuffer, IUnknown)
  214710. {
  214711. STDMETHOD(QueryInterface) (THIS_ REFIID, LPVOID*) PURE;
  214712. STDMETHOD_(ULONG,AddRef) (THIS) PURE;
  214713. STDMETHOD_(ULONG,Release) (THIS) PURE;
  214714. STDMETHOD(GetCaps) (THIS_ void*) PURE;
  214715. STDMETHOD(GetCurrentPosition) (THIS_ LPDWORD, LPDWORD) PURE;
  214716. STDMETHOD(GetFormat) (THIS_ LPWAVEFORMATEX, DWORD, LPDWORD) PURE;
  214717. STDMETHOD(GetStatus) (THIS_ LPDWORD) PURE;
  214718. STDMETHOD(Initialize) (THIS_ IDirectSoundCapture*, DSCBUFFERDESC*) PURE;
  214719. STDMETHOD(Lock) (THIS_ DWORD, DWORD, LPVOID*, LPDWORD, LPVOID*, LPDWORD, DWORD) PURE;
  214720. STDMETHOD(Start) (THIS_ DWORD) PURE;
  214721. STDMETHOD(Stop) (THIS) PURE;
  214722. STDMETHOD(Unlock) (THIS_ LPVOID, DWORD, LPVOID, DWORD) PURE;
  214723. };
  214724. };
  214725. BEGIN_JUCE_NAMESPACE
  214726. static const String getDSErrorMessage (HRESULT hr)
  214727. {
  214728. const char* result = 0;
  214729. switch (hr)
  214730. {
  214731. case MAKE_HRESULT(1, 0x878, 10):
  214732. result = "Device already allocated";
  214733. break;
  214734. case MAKE_HRESULT(1, 0x878, 30):
  214735. result = "Control unavailable";
  214736. break;
  214737. case E_INVALIDARG:
  214738. result = "Invalid parameter";
  214739. break;
  214740. case MAKE_HRESULT(1, 0x878, 50):
  214741. result = "Invalid call";
  214742. break;
  214743. case E_FAIL:
  214744. result = "Generic error";
  214745. break;
  214746. case MAKE_HRESULT(1, 0x878, 70):
  214747. result = "Priority level error";
  214748. break;
  214749. case E_OUTOFMEMORY:
  214750. result = "Out of memory";
  214751. break;
  214752. case MAKE_HRESULT(1, 0x878, 100):
  214753. result = "Bad format";
  214754. break;
  214755. case E_NOTIMPL:
  214756. result = "Unsupported function";
  214757. break;
  214758. case MAKE_HRESULT(1, 0x878, 120):
  214759. result = "No driver";
  214760. break;
  214761. case MAKE_HRESULT(1, 0x878, 130):
  214762. result = "Already initialised";
  214763. break;
  214764. case CLASS_E_NOAGGREGATION:
  214765. result = "No aggregation";
  214766. break;
  214767. case MAKE_HRESULT(1, 0x878, 150):
  214768. result = "Buffer lost";
  214769. break;
  214770. case MAKE_HRESULT(1, 0x878, 160):
  214771. result = "Another app has priority";
  214772. break;
  214773. case MAKE_HRESULT(1, 0x878, 170):
  214774. result = "Uninitialised";
  214775. break;
  214776. case E_NOINTERFACE:
  214777. result = "No interface";
  214778. break;
  214779. case S_OK:
  214780. result = "No error";
  214781. break;
  214782. default:
  214783. return "Unknown error: " + String ((int) hr);
  214784. }
  214785. return result;
  214786. }
  214787. #define DS_DEBUGGING 1
  214788. #ifdef DS_DEBUGGING
  214789. #define CATCH JUCE_CATCH_EXCEPTION
  214790. #undef log
  214791. #define log(a) Logger::writeToLog(a);
  214792. #undef logError
  214793. #define logError(a) logDSError(a, __LINE__);
  214794. static void logDSError (HRESULT hr, int lineNum)
  214795. {
  214796. if (hr != S_OK)
  214797. {
  214798. String error ("DS error at line ");
  214799. error << lineNum << T(" - ") << getDSErrorMessage (hr);
  214800. log (error);
  214801. }
  214802. }
  214803. #else
  214804. #define CATCH JUCE_CATCH_ALL
  214805. #define log(a)
  214806. #define logError(a)
  214807. #endif
  214808. #define DSOUND_FUNCTION(functionName, params) \
  214809. typedef HRESULT (WINAPI *type##functionName) params; \
  214810. static type##functionName ds##functionName = 0;
  214811. #define DSOUND_FUNCTION_LOAD(functionName) \
  214812. ds##functionName = (type##functionName) GetProcAddress (h, #functionName); \
  214813. jassert (ds##functionName != 0);
  214814. typedef BOOL (CALLBACK *LPDSENUMCALLBACKW) (LPGUID, LPCWSTR, LPCWSTR, LPVOID);
  214815. typedef BOOL (CALLBACK *LPDSENUMCALLBACKA) (LPGUID, LPCSTR, LPCSTR, LPVOID);
  214816. DSOUND_FUNCTION (DirectSoundCreate, (const GUID*, IDirectSound**, LPUNKNOWN))
  214817. DSOUND_FUNCTION (DirectSoundCaptureCreate, (const GUID*, IDirectSoundCapture**, LPUNKNOWN))
  214818. DSOUND_FUNCTION (DirectSoundEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214819. DSOUND_FUNCTION (DirectSoundCaptureEnumerateW, (LPDSENUMCALLBACKW, LPVOID))
  214820. static void initialiseDSoundFunctions()
  214821. {
  214822. if (dsDirectSoundCreate == 0)
  214823. {
  214824. HMODULE h = LoadLibraryA ("dsound.dll");
  214825. DSOUND_FUNCTION_LOAD (DirectSoundCreate)
  214826. DSOUND_FUNCTION_LOAD (DirectSoundCaptureCreate)
  214827. DSOUND_FUNCTION_LOAD (DirectSoundEnumerateW)
  214828. DSOUND_FUNCTION_LOAD (DirectSoundCaptureEnumerateW)
  214829. }
  214830. }
  214831. class DSoundInternalOutChannel
  214832. {
  214833. String name;
  214834. LPGUID guid;
  214835. int sampleRate, bufferSizeSamples;
  214836. float* leftBuffer;
  214837. float* rightBuffer;
  214838. IDirectSound* pDirectSound;
  214839. IDirectSoundBuffer* pOutputBuffer;
  214840. DWORD writeOffset;
  214841. int totalBytesPerBuffer;
  214842. int bytesPerBuffer;
  214843. unsigned int lastPlayCursor;
  214844. public:
  214845. int bitDepth;
  214846. bool doneFlag;
  214847. DSoundInternalOutChannel (const String& name_,
  214848. LPGUID guid_,
  214849. int rate,
  214850. int bufferSize,
  214851. float* left,
  214852. float* right)
  214853. : name (name_),
  214854. guid (guid_),
  214855. sampleRate (rate),
  214856. bufferSizeSamples (bufferSize),
  214857. leftBuffer (left),
  214858. rightBuffer (right),
  214859. pDirectSound (0),
  214860. pOutputBuffer (0),
  214861. bitDepth (16)
  214862. {
  214863. }
  214864. ~DSoundInternalOutChannel()
  214865. {
  214866. close();
  214867. }
  214868. void close()
  214869. {
  214870. HRESULT hr;
  214871. if (pOutputBuffer != 0)
  214872. {
  214873. JUCE_TRY
  214874. {
  214875. log (T("closing dsound out: ") + name);
  214876. hr = pOutputBuffer->Stop();
  214877. logError (hr);
  214878. }
  214879. CATCH
  214880. JUCE_TRY
  214881. {
  214882. hr = pOutputBuffer->Release();
  214883. logError (hr);
  214884. }
  214885. CATCH
  214886. pOutputBuffer = 0;
  214887. }
  214888. if (pDirectSound != 0)
  214889. {
  214890. JUCE_TRY
  214891. {
  214892. hr = pDirectSound->Release();
  214893. logError (hr);
  214894. }
  214895. CATCH
  214896. pDirectSound = 0;
  214897. }
  214898. }
  214899. const String open()
  214900. {
  214901. log (T("opening dsound out device: ") + name
  214902. + T(" rate=") + String (sampleRate)
  214903. + T(" bits=") + String (bitDepth)
  214904. + T(" buf=") + String (bufferSizeSamples));
  214905. pDirectSound = 0;
  214906. pOutputBuffer = 0;
  214907. writeOffset = 0;
  214908. String error;
  214909. HRESULT hr = E_NOINTERFACE;
  214910. if (dsDirectSoundCreate != 0)
  214911. hr = dsDirectSoundCreate (guid, &pDirectSound, 0);
  214912. if (hr == S_OK)
  214913. {
  214914. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  214915. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  214916. const int numChannels = 2;
  214917. hr = pDirectSound->SetCooperativeLevel (GetDesktopWindow(), 2 /* DSSCL_PRIORITY */);
  214918. logError (hr);
  214919. if (hr == S_OK)
  214920. {
  214921. IDirectSoundBuffer* pPrimaryBuffer;
  214922. DSBUFFERDESC primaryDesc;
  214923. zerostruct (primaryDesc);
  214924. primaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214925. primaryDesc.dwFlags = 1 /* DSBCAPS_PRIMARYBUFFER */;
  214926. primaryDesc.dwBufferBytes = 0;
  214927. primaryDesc.lpwfxFormat = 0;
  214928. log ("opening dsound out step 2");
  214929. hr = pDirectSound->CreateSoundBuffer (&primaryDesc, &pPrimaryBuffer, 0);
  214930. logError (hr);
  214931. if (hr == S_OK)
  214932. {
  214933. WAVEFORMATEX wfFormat;
  214934. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  214935. wfFormat.nChannels = (unsigned short) numChannels;
  214936. wfFormat.nSamplesPerSec = sampleRate;
  214937. wfFormat.wBitsPerSample = (unsigned short) bitDepth;
  214938. wfFormat.nBlockAlign = (unsigned short) (wfFormat.nChannels * wfFormat.wBitsPerSample / 8);
  214939. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  214940. wfFormat.cbSize = 0;
  214941. hr = pPrimaryBuffer->SetFormat (&wfFormat);
  214942. logError (hr);
  214943. if (hr == S_OK)
  214944. {
  214945. DSBUFFERDESC secondaryDesc;
  214946. zerostruct (secondaryDesc);
  214947. secondaryDesc.dwSize = sizeof (DSBUFFERDESC);
  214948. secondaryDesc.dwFlags = 0x8000 /* DSBCAPS_GLOBALFOCUS */
  214949. | 0x10000 /* DSBCAPS_GETCURRENTPOSITION2 */;
  214950. secondaryDesc.dwBufferBytes = totalBytesPerBuffer;
  214951. secondaryDesc.lpwfxFormat = &wfFormat;
  214952. hr = pDirectSound->CreateSoundBuffer (&secondaryDesc, &pOutputBuffer, 0);
  214953. logError (hr);
  214954. if (hr == S_OK)
  214955. {
  214956. log ("opening dsound out step 3");
  214957. DWORD dwDataLen;
  214958. unsigned char* pDSBuffData;
  214959. hr = pOutputBuffer->Lock (0, totalBytesPerBuffer,
  214960. (LPVOID*) &pDSBuffData, &dwDataLen, 0, 0, 0);
  214961. logError (hr);
  214962. if (hr == S_OK)
  214963. {
  214964. zeromem (pDSBuffData, dwDataLen);
  214965. hr = pOutputBuffer->Unlock (pDSBuffData, dwDataLen, 0, 0);
  214966. if (hr == S_OK)
  214967. {
  214968. hr = pOutputBuffer->SetCurrentPosition (0);
  214969. if (hr == S_OK)
  214970. {
  214971. hr = pOutputBuffer->Play (0, 0, 1 /* DSBPLAY_LOOPING */);
  214972. if (hr == S_OK)
  214973. return String::empty;
  214974. }
  214975. }
  214976. }
  214977. }
  214978. }
  214979. }
  214980. }
  214981. }
  214982. error = getDSErrorMessage (hr);
  214983. close();
  214984. return error;
  214985. }
  214986. void synchronisePosition()
  214987. {
  214988. if (pOutputBuffer != 0)
  214989. {
  214990. DWORD playCursor;
  214991. pOutputBuffer->GetCurrentPosition (&playCursor, &writeOffset);
  214992. }
  214993. }
  214994. bool service()
  214995. {
  214996. if (pOutputBuffer == 0)
  214997. return true;
  214998. DWORD playCursor, writeCursor;
  214999. HRESULT hr = pOutputBuffer->GetCurrentPosition (&playCursor, &writeCursor);
  215000. if (hr != S_OK)
  215001. {
  215002. logError (hr);
  215003. jassertfalse
  215004. return true;
  215005. }
  215006. int playWriteGap = writeCursor - playCursor;
  215007. if (playWriteGap < 0)
  215008. playWriteGap += totalBytesPerBuffer;
  215009. int bytesEmpty = playCursor - writeOffset;
  215010. if (bytesEmpty < 0)
  215011. bytesEmpty += totalBytesPerBuffer;
  215012. if (bytesEmpty > (totalBytesPerBuffer - playWriteGap))
  215013. {
  215014. writeOffset = writeCursor;
  215015. bytesEmpty = totalBytesPerBuffer - playWriteGap;
  215016. }
  215017. if (bytesEmpty >= bytesPerBuffer)
  215018. {
  215019. LPBYTE lpbuf1 = 0;
  215020. LPBYTE lpbuf2 = 0;
  215021. DWORD dwSize1 = 0;
  215022. DWORD dwSize2 = 0;
  215023. HRESULT hr = pOutputBuffer->Lock (writeOffset,
  215024. bytesPerBuffer,
  215025. (void**) &lpbuf1, &dwSize1,
  215026. (void**) &lpbuf2, &dwSize2, 0);
  215027. if (hr == MAKE_HRESULT (1, 0x878, 150)) // DSERR_BUFFERLOST
  215028. {
  215029. pOutputBuffer->Restore();
  215030. hr = pOutputBuffer->Lock (writeOffset,
  215031. bytesPerBuffer,
  215032. (void**) &lpbuf1, &dwSize1,
  215033. (void**) &lpbuf2, &dwSize2, 0);
  215034. }
  215035. if (hr == S_OK)
  215036. {
  215037. if (bitDepth == 16)
  215038. {
  215039. const float gainL = 32767.0f;
  215040. const float gainR = 32767.0f;
  215041. int* dest = (int*)lpbuf1;
  215042. const float* left = leftBuffer;
  215043. const float* right = rightBuffer;
  215044. int samples1 = dwSize1 >> 2;
  215045. int samples2 = dwSize2 >> 2;
  215046. if (left == 0)
  215047. {
  215048. while (--samples1 >= 0)
  215049. {
  215050. int r = roundFloatToInt (gainR * *right++);
  215051. if (r < -32768)
  215052. r = -32768;
  215053. else if (r > 32767)
  215054. r = 32767;
  215055. *dest++ = (r << 16);
  215056. }
  215057. dest = (int*)lpbuf2;
  215058. while (--samples2 >= 0)
  215059. {
  215060. int r = roundFloatToInt (gainR * *right++);
  215061. if (r < -32768)
  215062. r = -32768;
  215063. else if (r > 32767)
  215064. r = 32767;
  215065. *dest++ = (r << 16);
  215066. }
  215067. }
  215068. else if (right == 0)
  215069. {
  215070. while (--samples1 >= 0)
  215071. {
  215072. int l = roundFloatToInt (gainL * *left++);
  215073. if (l < -32768)
  215074. l = -32768;
  215075. else if (l > 32767)
  215076. l = 32767;
  215077. l &= 0xffff;
  215078. *dest++ = l;
  215079. }
  215080. dest = (int*)lpbuf2;
  215081. while (--samples2 >= 0)
  215082. {
  215083. int l = roundFloatToInt (gainL * *left++);
  215084. if (l < -32768)
  215085. l = -32768;
  215086. else if (l > 32767)
  215087. l = 32767;
  215088. l &= 0xffff;
  215089. *dest++ = l;
  215090. }
  215091. }
  215092. else
  215093. {
  215094. while (--samples1 >= 0)
  215095. {
  215096. int l = roundFloatToInt (gainL * *left++);
  215097. if (l < -32768)
  215098. l = -32768;
  215099. else if (l > 32767)
  215100. l = 32767;
  215101. l &= 0xffff;
  215102. int r = roundFloatToInt (gainR * *right++);
  215103. if (r < -32768)
  215104. r = -32768;
  215105. else if (r > 32767)
  215106. r = 32767;
  215107. *dest++ = (r << 16) | l;
  215108. }
  215109. dest = (int*)lpbuf2;
  215110. while (--samples2 >= 0)
  215111. {
  215112. int l = roundFloatToInt (gainL * *left++);
  215113. if (l < -32768)
  215114. l = -32768;
  215115. else if (l > 32767)
  215116. l = 32767;
  215117. l &= 0xffff;
  215118. int r = roundFloatToInt (gainR * *right++);
  215119. if (r < -32768)
  215120. r = -32768;
  215121. else if (r > 32767)
  215122. r = 32767;
  215123. *dest++ = (r << 16) | l;
  215124. }
  215125. }
  215126. }
  215127. else
  215128. {
  215129. jassertfalse
  215130. }
  215131. writeOffset = (writeOffset + dwSize1 + dwSize2) % totalBytesPerBuffer;
  215132. pOutputBuffer->Unlock (lpbuf1, dwSize1, lpbuf2, dwSize2);
  215133. }
  215134. else
  215135. {
  215136. jassertfalse
  215137. logError (hr);
  215138. }
  215139. bytesEmpty -= bytesPerBuffer;
  215140. return true;
  215141. }
  215142. else
  215143. {
  215144. return false;
  215145. }
  215146. }
  215147. };
  215148. struct DSoundInternalInChannel
  215149. {
  215150. String name;
  215151. LPGUID guid;
  215152. int sampleRate, bufferSizeSamples;
  215153. float* leftBuffer;
  215154. float* rightBuffer;
  215155. IDirectSound* pDirectSound;
  215156. IDirectSoundCapture* pDirectSoundCapture;
  215157. IDirectSoundCaptureBuffer* pInputBuffer;
  215158. public:
  215159. unsigned int readOffset;
  215160. int bytesPerBuffer, totalBytesPerBuffer;
  215161. int bitDepth;
  215162. bool doneFlag;
  215163. DSoundInternalInChannel (const String& name_,
  215164. LPGUID guid_,
  215165. int rate,
  215166. int bufferSize,
  215167. float* left,
  215168. float* right)
  215169. : name (name_),
  215170. guid (guid_),
  215171. sampleRate (rate),
  215172. bufferSizeSamples (bufferSize),
  215173. leftBuffer (left),
  215174. rightBuffer (right),
  215175. pDirectSound (0),
  215176. pDirectSoundCapture (0),
  215177. pInputBuffer (0),
  215178. bitDepth (16)
  215179. {
  215180. }
  215181. ~DSoundInternalInChannel()
  215182. {
  215183. close();
  215184. }
  215185. void close()
  215186. {
  215187. HRESULT hr;
  215188. if (pInputBuffer != 0)
  215189. {
  215190. JUCE_TRY
  215191. {
  215192. log (T("closing dsound in: ") + name);
  215193. hr = pInputBuffer->Stop();
  215194. logError (hr);
  215195. }
  215196. CATCH
  215197. JUCE_TRY
  215198. {
  215199. hr = pInputBuffer->Release();
  215200. logError (hr);
  215201. }
  215202. CATCH
  215203. pInputBuffer = 0;
  215204. }
  215205. if (pDirectSoundCapture != 0)
  215206. {
  215207. JUCE_TRY
  215208. {
  215209. hr = pDirectSoundCapture->Release();
  215210. logError (hr);
  215211. }
  215212. CATCH
  215213. pDirectSoundCapture = 0;
  215214. }
  215215. if (pDirectSound != 0)
  215216. {
  215217. JUCE_TRY
  215218. {
  215219. hr = pDirectSound->Release();
  215220. logError (hr);
  215221. }
  215222. CATCH
  215223. pDirectSound = 0;
  215224. }
  215225. }
  215226. const String open()
  215227. {
  215228. log (T("opening dsound in device: ") + name
  215229. + T(" rate=") + String (sampleRate) + T(" bits=") + String (bitDepth) + T(" buf=") + String (bufferSizeSamples));
  215230. pDirectSound = 0;
  215231. pDirectSoundCapture = 0;
  215232. pInputBuffer = 0;
  215233. readOffset = 0;
  215234. totalBytesPerBuffer = 0;
  215235. String error;
  215236. HRESULT hr = E_NOINTERFACE;
  215237. if (dsDirectSoundCaptureCreate != 0)
  215238. hr = dsDirectSoundCaptureCreate (guid, &pDirectSoundCapture, 0);
  215239. logError (hr);
  215240. if (hr == S_OK)
  215241. {
  215242. const int numChannels = 2;
  215243. bytesPerBuffer = (bufferSizeSamples * (bitDepth >> 2)) & ~15;
  215244. totalBytesPerBuffer = (3 * bytesPerBuffer) & ~15;
  215245. WAVEFORMATEX wfFormat;
  215246. wfFormat.wFormatTag = WAVE_FORMAT_PCM;
  215247. wfFormat.nChannels = (unsigned short)numChannels;
  215248. wfFormat.nSamplesPerSec = sampleRate;
  215249. wfFormat.wBitsPerSample = (unsigned short)bitDepth;
  215250. wfFormat.nBlockAlign = (unsigned short)(wfFormat.nChannels * (wfFormat.wBitsPerSample / 8));
  215251. wfFormat.nAvgBytesPerSec = wfFormat.nSamplesPerSec * wfFormat.nBlockAlign;
  215252. wfFormat.cbSize = 0;
  215253. DSCBUFFERDESC captureDesc;
  215254. zerostruct (captureDesc);
  215255. captureDesc.dwSize = sizeof (DSCBUFFERDESC);
  215256. captureDesc.dwFlags = 0;
  215257. captureDesc.dwBufferBytes = totalBytesPerBuffer;
  215258. captureDesc.lpwfxFormat = &wfFormat;
  215259. log (T("opening dsound in step 2"));
  215260. hr = pDirectSoundCapture->CreateCaptureBuffer (&captureDesc, &pInputBuffer, 0);
  215261. logError (hr);
  215262. if (hr == S_OK)
  215263. {
  215264. hr = pInputBuffer->Start (1 /* DSCBSTART_LOOPING */);
  215265. logError (hr);
  215266. if (hr == S_OK)
  215267. return String::empty;
  215268. }
  215269. }
  215270. error = getDSErrorMessage (hr);
  215271. close();
  215272. return error;
  215273. }
  215274. void synchronisePosition()
  215275. {
  215276. if (pInputBuffer != 0)
  215277. {
  215278. DWORD capturePos;
  215279. pInputBuffer->GetCurrentPosition (&capturePos, (DWORD*)&readOffset);
  215280. }
  215281. }
  215282. bool service()
  215283. {
  215284. if (pInputBuffer == 0)
  215285. return true;
  215286. DWORD capturePos, readPos;
  215287. HRESULT hr = pInputBuffer->GetCurrentPosition (&capturePos, &readPos);
  215288. logError (hr);
  215289. if (hr != S_OK)
  215290. return true;
  215291. int bytesFilled = readPos - readOffset;
  215292. if (bytesFilled < 0)
  215293. bytesFilled += totalBytesPerBuffer;
  215294. if (bytesFilled >= bytesPerBuffer)
  215295. {
  215296. LPBYTE lpbuf1 = 0;
  215297. LPBYTE lpbuf2 = 0;
  215298. DWORD dwsize1 = 0;
  215299. DWORD dwsize2 = 0;
  215300. HRESULT hr = pInputBuffer->Lock (readOffset,
  215301. bytesPerBuffer,
  215302. (void**) &lpbuf1, &dwsize1,
  215303. (void**) &lpbuf2, &dwsize2, 0);
  215304. if (hr == S_OK)
  215305. {
  215306. if (bitDepth == 16)
  215307. {
  215308. const float g = 1.0f / 32768.0f;
  215309. float* destL = leftBuffer;
  215310. float* destR = rightBuffer;
  215311. int samples1 = dwsize1 >> 2;
  215312. int samples2 = dwsize2 >> 2;
  215313. const short* src = (const short*)lpbuf1;
  215314. if (destL == 0)
  215315. {
  215316. while (--samples1 >= 0)
  215317. {
  215318. ++src;
  215319. *destR++ = *src++ * g;
  215320. }
  215321. src = (const short*)lpbuf2;
  215322. while (--samples2 >= 0)
  215323. {
  215324. ++src;
  215325. *destR++ = *src++ * g;
  215326. }
  215327. }
  215328. else if (destR == 0)
  215329. {
  215330. while (--samples1 >= 0)
  215331. {
  215332. *destL++ = *src++ * g;
  215333. ++src;
  215334. }
  215335. src = (const short*)lpbuf2;
  215336. while (--samples2 >= 0)
  215337. {
  215338. *destL++ = *src++ * g;
  215339. ++src;
  215340. }
  215341. }
  215342. else
  215343. {
  215344. while (--samples1 >= 0)
  215345. {
  215346. *destL++ = *src++ * g;
  215347. *destR++ = *src++ * g;
  215348. }
  215349. src = (const short*)lpbuf2;
  215350. while (--samples2 >= 0)
  215351. {
  215352. *destL++ = *src++ * g;
  215353. *destR++ = *src++ * g;
  215354. }
  215355. }
  215356. }
  215357. else
  215358. {
  215359. jassertfalse
  215360. }
  215361. readOffset = (readOffset + dwsize1 + dwsize2) % totalBytesPerBuffer;
  215362. pInputBuffer->Unlock (lpbuf1, dwsize1, lpbuf2, dwsize2);
  215363. }
  215364. else
  215365. {
  215366. logError (hr);
  215367. jassertfalse
  215368. }
  215369. bytesFilled -= bytesPerBuffer;
  215370. return true;
  215371. }
  215372. else
  215373. {
  215374. return false;
  215375. }
  215376. }
  215377. };
  215378. class DSoundAudioIODevice : public AudioIODevice,
  215379. public Thread
  215380. {
  215381. public:
  215382. DSoundAudioIODevice (const String& deviceName,
  215383. const int outputDeviceIndex_,
  215384. const int inputDeviceIndex_)
  215385. : AudioIODevice (deviceName, "DirectSound"),
  215386. Thread ("Juce DSound"),
  215387. isOpen_ (false),
  215388. isStarted (false),
  215389. outputDeviceIndex (outputDeviceIndex_),
  215390. inputDeviceIndex (inputDeviceIndex_),
  215391. inChans (4),
  215392. outChans (4),
  215393. numInputBuffers (0),
  215394. numOutputBuffers (0),
  215395. totalSamplesOut (0),
  215396. sampleRate (0.0),
  215397. inputBuffers (0),
  215398. outputBuffers (0),
  215399. callback (0),
  215400. bufferSizeSamples (0)
  215401. {
  215402. if (outputDeviceIndex_ >= 0)
  215403. {
  215404. outChannels.add (TRANS("Left"));
  215405. outChannels.add (TRANS("Right"));
  215406. }
  215407. if (inputDeviceIndex_ >= 0)
  215408. {
  215409. inChannels.add (TRANS("Left"));
  215410. inChannels.add (TRANS("Right"));
  215411. }
  215412. }
  215413. ~DSoundAudioIODevice()
  215414. {
  215415. close();
  215416. }
  215417. const StringArray getOutputChannelNames()
  215418. {
  215419. return outChannels;
  215420. }
  215421. const StringArray getInputChannelNames()
  215422. {
  215423. return inChannels;
  215424. }
  215425. int getNumSampleRates()
  215426. {
  215427. return 4;
  215428. }
  215429. double getSampleRate (int index)
  215430. {
  215431. const double samps[] = { 44100.0, 48000.0, 88200.0, 96000.0 };
  215432. return samps [jlimit (0, 3, index)];
  215433. }
  215434. int getNumBufferSizesAvailable()
  215435. {
  215436. return 50;
  215437. }
  215438. int getBufferSizeSamples (int index)
  215439. {
  215440. int n = 64;
  215441. for (int i = 0; i < index; ++i)
  215442. n += (n < 512) ? 32
  215443. : ((n < 1024) ? 64
  215444. : ((n < 2048) ? 128 : 256));
  215445. return n;
  215446. }
  215447. int getDefaultBufferSize()
  215448. {
  215449. return 2560;
  215450. }
  215451. const String open (const BitArray& inputChannels,
  215452. const BitArray& outputChannels,
  215453. double sampleRate,
  215454. int bufferSizeSamples)
  215455. {
  215456. lastError = openDevice (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  215457. isOpen_ = lastError.isEmpty();
  215458. return lastError;
  215459. }
  215460. void close()
  215461. {
  215462. stop();
  215463. if (isOpen_)
  215464. {
  215465. closeDevice();
  215466. isOpen_ = false;
  215467. }
  215468. }
  215469. bool isOpen()
  215470. {
  215471. return isOpen_ && isThreadRunning();
  215472. }
  215473. int getCurrentBufferSizeSamples()
  215474. {
  215475. return bufferSizeSamples;
  215476. }
  215477. double getCurrentSampleRate()
  215478. {
  215479. return sampleRate;
  215480. }
  215481. int getCurrentBitDepth()
  215482. {
  215483. int i, bits = 256;
  215484. for (i = inChans.size(); --i >= 0;)
  215485. bits = jmin (bits, inChans[i]->bitDepth);
  215486. for (i = outChans.size(); --i >= 0;)
  215487. bits = jmin (bits, outChans[i]->bitDepth);
  215488. if (bits > 32)
  215489. bits = 16;
  215490. return bits;
  215491. }
  215492. const BitArray getActiveOutputChannels() const
  215493. {
  215494. return enabledOutputs;
  215495. }
  215496. const BitArray getActiveInputChannels() const
  215497. {
  215498. return enabledInputs;
  215499. }
  215500. int getOutputLatencyInSamples()
  215501. {
  215502. return (int) (getCurrentBufferSizeSamples() * 1.5);
  215503. }
  215504. int getInputLatencyInSamples()
  215505. {
  215506. return getOutputLatencyInSamples();
  215507. }
  215508. void start (AudioIODeviceCallback* call)
  215509. {
  215510. if (isOpen_ && call != 0 && ! isStarted)
  215511. {
  215512. if (! isThreadRunning())
  215513. {
  215514. // something gone wrong and the thread's stopped..
  215515. isOpen_ = false;
  215516. return;
  215517. }
  215518. call->audioDeviceAboutToStart (this);
  215519. const ScopedLock sl (startStopLock);
  215520. callback = call;
  215521. isStarted = true;
  215522. }
  215523. }
  215524. void stop()
  215525. {
  215526. if (isStarted)
  215527. {
  215528. AudioIODeviceCallback* const callbackLocal = callback;
  215529. {
  215530. const ScopedLock sl (startStopLock);
  215531. isStarted = false;
  215532. }
  215533. if (callbackLocal != 0)
  215534. callbackLocal->audioDeviceStopped();
  215535. }
  215536. }
  215537. bool isPlaying()
  215538. {
  215539. return isStarted && isOpen_ && isThreadRunning();
  215540. }
  215541. const String getLastError()
  215542. {
  215543. return lastError;
  215544. }
  215545. juce_UseDebuggingNewOperator
  215546. StringArray inChannels, outChannels;
  215547. int outputDeviceIndex, inputDeviceIndex;
  215548. private:
  215549. bool isOpen_;
  215550. bool isStarted;
  215551. String lastError;
  215552. OwnedArray <DSoundInternalInChannel> inChans;
  215553. OwnedArray <DSoundInternalOutChannel> outChans;
  215554. WaitableEvent startEvent;
  215555. int numInputBuffers, numOutputBuffers, bufferSizeSamples;
  215556. int volatile totalSamplesOut;
  215557. int64 volatile lastBlockTime;
  215558. double sampleRate;
  215559. BitArray enabledInputs, enabledOutputs;
  215560. float** inputBuffers;
  215561. float** outputBuffers;
  215562. AudioIODeviceCallback* callback;
  215563. CriticalSection startStopLock;
  215564. DSoundAudioIODevice (const DSoundAudioIODevice&);
  215565. const DSoundAudioIODevice& operator= (const DSoundAudioIODevice&);
  215566. const String openDevice (const BitArray& inputChannels,
  215567. const BitArray& outputChannels,
  215568. double sampleRate_,
  215569. int bufferSizeSamples_);
  215570. void closeDevice()
  215571. {
  215572. isStarted = false;
  215573. stopThread (5000);
  215574. inChans.clear();
  215575. outChans.clear();
  215576. int i;
  215577. for (i = 0; i < numInputBuffers; ++i)
  215578. juce_free (inputBuffers[i]);
  215579. delete[] inputBuffers;
  215580. inputBuffers = 0;
  215581. numInputBuffers = 0;
  215582. for (i = 0; i < numOutputBuffers; ++i)
  215583. juce_free (outputBuffers[i]);
  215584. delete[] outputBuffers;
  215585. outputBuffers = 0;
  215586. numOutputBuffers = 0;
  215587. }
  215588. void resync()
  215589. {
  215590. if (! threadShouldExit())
  215591. {
  215592. sleep (5);
  215593. int i;
  215594. for (i = 0; i < outChans.size(); ++i)
  215595. outChans.getUnchecked(i)->synchronisePosition();
  215596. for (i = 0; i < inChans.size(); ++i)
  215597. inChans.getUnchecked(i)->synchronisePosition();
  215598. }
  215599. }
  215600. public:
  215601. void run()
  215602. {
  215603. while (! threadShouldExit())
  215604. {
  215605. if (wait (100))
  215606. break;
  215607. }
  215608. const int latencyMs = (int) (bufferSizeSamples * 1000.0 / sampleRate);
  215609. const int maxTimeMS = jmax (5, 3 * latencyMs);
  215610. while (! threadShouldExit())
  215611. {
  215612. int numToDo = 0;
  215613. uint32 startTime = Time::getMillisecondCounter();
  215614. int i;
  215615. for (i = inChans.size(); --i >= 0;)
  215616. {
  215617. inChans.getUnchecked(i)->doneFlag = false;
  215618. ++numToDo;
  215619. }
  215620. for (i = outChans.size(); --i >= 0;)
  215621. {
  215622. outChans.getUnchecked(i)->doneFlag = false;
  215623. ++numToDo;
  215624. }
  215625. if (numToDo > 0)
  215626. {
  215627. const int maxCount = 3;
  215628. int count = maxCount;
  215629. for (;;)
  215630. {
  215631. for (i = inChans.size(); --i >= 0;)
  215632. {
  215633. DSoundInternalInChannel* const in = inChans.getUnchecked(i);
  215634. if ((! in->doneFlag) && in->service())
  215635. {
  215636. in->doneFlag = true;
  215637. --numToDo;
  215638. }
  215639. }
  215640. for (i = outChans.size(); --i >= 0;)
  215641. {
  215642. DSoundInternalOutChannel* const out = outChans.getUnchecked(i);
  215643. if ((! out->doneFlag) && out->service())
  215644. {
  215645. out->doneFlag = true;
  215646. --numToDo;
  215647. }
  215648. }
  215649. if (numToDo <= 0)
  215650. break;
  215651. if (Time::getMillisecondCounter() > startTime + maxTimeMS)
  215652. {
  215653. resync();
  215654. break;
  215655. }
  215656. if (--count <= 0)
  215657. {
  215658. Sleep (1);
  215659. count = maxCount;
  215660. }
  215661. if (threadShouldExit())
  215662. return;
  215663. }
  215664. }
  215665. else
  215666. {
  215667. sleep (1);
  215668. }
  215669. const ScopedLock sl (startStopLock);
  215670. if (isStarted)
  215671. {
  215672. JUCE_TRY
  215673. {
  215674. callback->audioDeviceIOCallback ((const float**) inputBuffers,
  215675. numInputBuffers,
  215676. outputBuffers,
  215677. numOutputBuffers,
  215678. bufferSizeSamples);
  215679. }
  215680. JUCE_CATCH_EXCEPTION
  215681. totalSamplesOut += bufferSizeSamples;
  215682. }
  215683. else
  215684. {
  215685. for (i = 0; i < numOutputBuffers; ++i)
  215686. if (outputBuffers[i] != 0)
  215687. zeromem (outputBuffers[i], bufferSizeSamples * sizeof (float));
  215688. totalSamplesOut = 0;
  215689. sleep (1);
  215690. }
  215691. }
  215692. }
  215693. };
  215694. class DSoundAudioIODeviceType : public AudioIODeviceType
  215695. {
  215696. public:
  215697. DSoundAudioIODeviceType()
  215698. : AudioIODeviceType (T("DirectSound")),
  215699. hasScanned (false)
  215700. {
  215701. initialiseDSoundFunctions();
  215702. }
  215703. ~DSoundAudioIODeviceType()
  215704. {
  215705. }
  215706. void scanForDevices()
  215707. {
  215708. hasScanned = true;
  215709. outputDeviceNames.clear();
  215710. outputGuids.clear();
  215711. inputDeviceNames.clear();
  215712. inputGuids.clear();
  215713. if (dsDirectSoundEnumerateW != 0)
  215714. {
  215715. dsDirectSoundEnumerateW (outputEnumProcW, this);
  215716. dsDirectSoundCaptureEnumerateW (inputEnumProcW, this);
  215717. }
  215718. }
  215719. const StringArray getDeviceNames (const bool wantInputNames) const
  215720. {
  215721. jassert (hasScanned); // need to call scanForDevices() before doing this
  215722. return wantInputNames ? inputDeviceNames
  215723. : outputDeviceNames;
  215724. }
  215725. int getDefaultDeviceIndex (const bool /*forInput*/) const
  215726. {
  215727. jassert (hasScanned); // need to call scanForDevices() before doing this
  215728. return 0;
  215729. }
  215730. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  215731. {
  215732. jassert (hasScanned); // need to call scanForDevices() before doing this
  215733. DSoundAudioIODevice* const d = dynamic_cast <DSoundAudioIODevice*> (device);
  215734. if (d == 0)
  215735. return -1;
  215736. return asInput ? d->inputDeviceIndex
  215737. : d->outputDeviceIndex;
  215738. }
  215739. bool hasSeparateInputsAndOutputs() const { return true; }
  215740. AudioIODevice* createDevice (const String& outputDeviceName,
  215741. const String& inputDeviceName)
  215742. {
  215743. jassert (hasScanned); // need to call scanForDevices() before doing this
  215744. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  215745. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  215746. if (outputIndex >= 0 || inputIndex >= 0)
  215747. return new DSoundAudioIODevice (outputDeviceName.isNotEmpty() ? outputDeviceName
  215748. : inputDeviceName,
  215749. outputIndex, inputIndex);
  215750. return 0;
  215751. }
  215752. juce_UseDebuggingNewOperator
  215753. StringArray outputDeviceNames;
  215754. OwnedArray <GUID> outputGuids;
  215755. StringArray inputDeviceNames;
  215756. OwnedArray <GUID> inputGuids;
  215757. private:
  215758. bool hasScanned;
  215759. BOOL outputEnumProc (LPGUID lpGUID, String desc)
  215760. {
  215761. desc = desc.trim();
  215762. if (desc.isNotEmpty())
  215763. {
  215764. const String origDesc (desc);
  215765. int n = 2;
  215766. while (outputDeviceNames.contains (desc))
  215767. desc = origDesc + T(" (") + String (n++) + T(")");
  215768. outputDeviceNames.add (desc);
  215769. if (lpGUID != 0)
  215770. outputGuids.add (new GUID (*lpGUID));
  215771. else
  215772. outputGuids.add (0);
  215773. }
  215774. return TRUE;
  215775. }
  215776. static BOOL CALLBACK outputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215777. {
  215778. return ((DSoundAudioIODeviceType*) object)
  215779. ->outputEnumProc (lpGUID, String (description));
  215780. }
  215781. static BOOL CALLBACK outputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215782. {
  215783. return ((DSoundAudioIODeviceType*) object)
  215784. ->outputEnumProc (lpGUID, String (description));
  215785. }
  215786. BOOL CALLBACK inputEnumProc (LPGUID lpGUID, String desc)
  215787. {
  215788. desc = desc.trim();
  215789. if (desc.isNotEmpty())
  215790. {
  215791. const String origDesc (desc);
  215792. int n = 2;
  215793. while (inputDeviceNames.contains (desc))
  215794. desc = origDesc + T(" (") + String (n++) + T(")");
  215795. inputDeviceNames.add (desc);
  215796. if (lpGUID != 0)
  215797. inputGuids.add (new GUID (*lpGUID));
  215798. else
  215799. inputGuids.add (0);
  215800. }
  215801. return TRUE;
  215802. }
  215803. static BOOL CALLBACK inputEnumProcW (LPGUID lpGUID, LPCWSTR description, LPCWSTR, LPVOID object)
  215804. {
  215805. return ((DSoundAudioIODeviceType*) object)
  215806. ->inputEnumProc (lpGUID, String (description));
  215807. }
  215808. static BOOL CALLBACK inputEnumProcA (LPGUID lpGUID, LPCTSTR description, LPCTSTR, LPVOID object)
  215809. {
  215810. return ((DSoundAudioIODeviceType*) object)
  215811. ->inputEnumProc (lpGUID, String (description));
  215812. }
  215813. DSoundAudioIODeviceType (const DSoundAudioIODeviceType&);
  215814. const DSoundAudioIODeviceType& operator= (const DSoundAudioIODeviceType&);
  215815. };
  215816. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  215817. {
  215818. return new DSoundAudioIODeviceType();
  215819. }
  215820. const String DSoundAudioIODevice::openDevice (const BitArray& inputChannels,
  215821. const BitArray& outputChannels,
  215822. double sampleRate_,
  215823. int bufferSizeSamples_)
  215824. {
  215825. closeDevice();
  215826. totalSamplesOut = 0;
  215827. sampleRate = sampleRate_;
  215828. if (bufferSizeSamples_ <= 0)
  215829. bufferSizeSamples_ = 960; // use as a default size if none is set.
  215830. bufferSizeSamples = bufferSizeSamples_ & ~7;
  215831. DSoundAudioIODeviceType dlh;
  215832. dlh.scanForDevices();
  215833. enabledInputs = inputChannels;
  215834. enabledInputs.setRange (inChannels.size(),
  215835. enabledInputs.getHighestBit() + 1 - inChannels.size(),
  215836. false);
  215837. numInputBuffers = enabledInputs.countNumberOfSetBits();
  215838. inputBuffers = new float* [numInputBuffers + 2];
  215839. zeromem (inputBuffers, sizeof (float*) * numInputBuffers + 2);
  215840. int i, numIns = 0;
  215841. for (i = 0; i <= enabledInputs.getHighestBit(); i += 2)
  215842. {
  215843. float* left = 0;
  215844. float* right = 0;
  215845. if (enabledInputs[i])
  215846. left = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  215847. if (enabledInputs[i + 1])
  215848. right = inputBuffers[numIns++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  215849. if (left != 0 || right != 0)
  215850. inChans.add (new DSoundInternalInChannel (dlh.inputDeviceNames [inputDeviceIndex],
  215851. dlh.inputGuids [inputDeviceIndex],
  215852. (int) sampleRate, bufferSizeSamples,
  215853. left, right));
  215854. }
  215855. enabledOutputs = outputChannels;
  215856. enabledOutputs.setRange (outChannels.size(),
  215857. enabledOutputs.getHighestBit() + 1 - outChannels.size(),
  215858. false);
  215859. numOutputBuffers = enabledOutputs.countNumberOfSetBits();
  215860. outputBuffers = new float* [numOutputBuffers + 2];
  215861. zeromem (outputBuffers, sizeof (float*) * numOutputBuffers + 2);
  215862. int numOuts = 0;
  215863. for (i = 0; i <= enabledOutputs.getHighestBit(); i += 2)
  215864. {
  215865. float* left = 0;
  215866. float* right = 0;
  215867. if (enabledOutputs[i])
  215868. left = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  215869. if (enabledOutputs[i + 1])
  215870. right = outputBuffers[numOuts++] = (float*) juce_calloc ((bufferSizeSamples + 16) * sizeof (float));
  215871. if (left != 0 || right != 0)
  215872. outChans.add (new DSoundInternalOutChannel (dlh.outputDeviceNames[outputDeviceIndex],
  215873. dlh.outputGuids [outputDeviceIndex],
  215874. (int) sampleRate, bufferSizeSamples,
  215875. left, right));
  215876. }
  215877. String error;
  215878. // boost our priority while opening the devices to try to get better sync between them
  215879. const int oldThreadPri = GetThreadPriority (GetCurrentThread());
  215880. const int oldProcPri = GetPriorityClass (GetCurrentProcess());
  215881. SetThreadPriority (GetCurrentThread(), THREAD_PRIORITY_TIME_CRITICAL);
  215882. SetPriorityClass (GetCurrentProcess(), REALTIME_PRIORITY_CLASS);
  215883. for (i = 0; i < outChans.size(); ++i)
  215884. {
  215885. error = outChans[i]->open();
  215886. if (error.isNotEmpty())
  215887. {
  215888. error = T("Error opening ") + dlh.outputDeviceNames[i]
  215889. + T(": \"") + error + T("\"");
  215890. break;
  215891. }
  215892. }
  215893. if (error.isEmpty())
  215894. {
  215895. for (i = 0; i < inChans.size(); ++i)
  215896. {
  215897. error = inChans[i]->open();
  215898. if (error.isNotEmpty())
  215899. {
  215900. error = T("Error opening ") + dlh.inputDeviceNames[i]
  215901. + T(": \"") + error + T("\"");
  215902. break;
  215903. }
  215904. }
  215905. }
  215906. if (error.isEmpty())
  215907. {
  215908. totalSamplesOut = 0;
  215909. for (i = 0; i < outChans.size(); ++i)
  215910. outChans.getUnchecked(i)->synchronisePosition();
  215911. for (i = 0; i < inChans.size(); ++i)
  215912. inChans.getUnchecked(i)->synchronisePosition();
  215913. startThread (9);
  215914. sleep (10);
  215915. notify();
  215916. }
  215917. else
  215918. {
  215919. log (error);
  215920. }
  215921. SetThreadPriority (GetCurrentThread(), oldThreadPri);
  215922. SetPriorityClass (GetCurrentProcess(), oldProcPri);
  215923. return error;
  215924. }
  215925. #undef log
  215926. #endif
  215927. /********* End of inlined file: juce_win32_DirectSound.cpp *********/
  215928. #endif
  215929. // Auto-link the other win32 libs that are needed by library calls..
  215930. #if defined (JUCE_DLL_BUILD) && JUCE_MSVC
  215931. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  215932. // Auto-links to various win32 libs that are needed by library calls..
  215933. #pragma comment(lib, "kernel32.lib")
  215934. #pragma comment(lib, "user32.lib")
  215935. #pragma comment(lib, "shell32.lib")
  215936. #pragma comment(lib, "gdi32.lib")
  215937. #pragma comment(lib, "vfw32.lib")
  215938. #pragma comment(lib, "comdlg32.lib")
  215939. #pragma comment(lib, "winmm.lib")
  215940. #pragma comment(lib, "wininet.lib")
  215941. #pragma comment(lib, "ole32.lib")
  215942. #pragma comment(lib, "advapi32.lib")
  215943. #pragma comment(lib, "ws2_32.lib")
  215944. #pragma comment(lib, "comsupp.lib")
  215945. #if JUCE_OPENGL
  215946. #pragma comment(lib, "OpenGL32.Lib")
  215947. #pragma comment(lib, "GlU32.Lib")
  215948. #endif
  215949. #if JUCE_QUICKTIME
  215950. #pragma comment (lib, "QTMLClient.lib")
  215951. #endif
  215952. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  215953. #endif
  215954. END_JUCE_NAMESPACE
  215955. /********* End of inlined file: juce_win32_NativeCode.cpp *********/
  215956. /********* Start of inlined file: juce_win32_AutoLinkLibraries.h *********/
  215957. // Auto-links to various win32 libs that are needed by library calls..
  215958. #pragma comment(lib, "kernel32.lib")
  215959. #pragma comment(lib, "user32.lib")
  215960. #pragma comment(lib, "shell32.lib")
  215961. #pragma comment(lib, "gdi32.lib")
  215962. #pragma comment(lib, "vfw32.lib")
  215963. #pragma comment(lib, "comdlg32.lib")
  215964. #pragma comment(lib, "winmm.lib")
  215965. #pragma comment(lib, "wininet.lib")
  215966. #pragma comment(lib, "ole32.lib")
  215967. #pragma comment(lib, "advapi32.lib")
  215968. #pragma comment(lib, "ws2_32.lib")
  215969. #pragma comment(lib, "comsupp.lib")
  215970. #if JUCE_OPENGL
  215971. #pragma comment(lib, "OpenGL32.Lib")
  215972. #pragma comment(lib, "GlU32.Lib")
  215973. #endif
  215974. #if JUCE_QUICKTIME
  215975. #pragma comment (lib, "QTMLClient.lib")
  215976. #endif
  215977. /********* End of inlined file: juce_win32_AutoLinkLibraries.h *********/
  215978. #endif
  215979. //==============================================================================
  215980. #if JUCE_LINUX
  215981. /********* Start of inlined file: juce_linux_Files.cpp *********/
  215982. /********* Start of inlined file: linuxincludes.h *********/
  215983. #ifndef __LINUXINCLUDES_JUCEHEADER__
  215984. #define __LINUXINCLUDES_JUCEHEADER__
  215985. // Linux Header Files:
  215986. #include <unistd.h>
  215987. #include <stdlib.h>
  215988. #include <sched.h>
  215989. #include <pthread.h>
  215990. #include <sys/time.h>
  215991. #include <errno.h>
  215992. /********* Start of inlined file: juce_Config.h *********/
  215993. #ifndef __JUCE_CONFIG_JUCEHEADER__
  215994. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  215995. /*
  215996. This file contains macros that enable/disable various JUCE features.
  215997. */
  215998. /** The name of the namespace that all Juce classes and functions will be
  215999. put inside. If this is not defined, no namespace will be used.
  216000. */
  216001. #ifndef JUCE_NAMESPACE
  216002. #define JUCE_NAMESPACE juce
  216003. #endif
  216004. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  216005. but if you define this value, you can override this can force it to be true or
  216006. false.
  216007. */
  216008. #ifndef JUCE_FORCE_DEBUG
  216009. //#define JUCE_FORCE_DEBUG 1
  216010. #endif
  216011. /** If this flag is enabled, the the jassert and jassertfalse macros will
  216012. always use Logger::writeToLog() to write a message when an assertion happens.
  216013. Enabling it will also leave this turned on in release builds. When it's disabled,
  216014. however, the jassert and jassertfalse macros will not be compiled in a
  216015. release build.
  216016. @see jassert, jassertfalse, Logger
  216017. */
  216018. #ifndef JUCE_LOG_ASSERTIONS
  216019. // #define JUCE_LOG_ASSERTIONS 1
  216020. #endif
  216021. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  216022. which the ASIOAudioIODevice class can't be built. See the comments in the
  216023. ASIOAudioIODevice class's header file for more info about this.
  216024. (This only affects a Win32 build)
  216025. */
  216026. #ifndef JUCE_ASIO
  216027. #define JUCE_ASIO 1
  216028. #endif
  216029. /** Comment out this macro to disable building of ALSA device support on Linux.
  216030. */
  216031. #ifndef JUCE_ALSA
  216032. #define JUCE_ALSA 1
  216033. #endif
  216034. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  216035. have the SDK installed.
  216036. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  216037. classes will be unavailable.
  216038. On Windows, if you enable this, you'll need to have the QuickTime SDK
  216039. installed, and its header files will need to be on your include path.
  216040. */
  216041. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  216042. #define JUCE_QUICKTIME 1
  216043. #endif
  216044. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  216045. have the appropriate headers and libraries available. If it's not enabled, the
  216046. OpenGLComponent class will be unavailable.
  216047. */
  216048. #ifndef JUCE_OPENGL
  216049. #define JUCE_OPENGL 1
  216050. #endif
  216051. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  216052. If you're not going to need either of these formats, turn off the flags to
  216053. avoid bloating your codebase with them.
  216054. */
  216055. #ifndef JUCE_USE_FLAC
  216056. #define JUCE_USE_FLAC 1
  216057. #endif
  216058. #ifndef JUCE_USE_OGGVORBIS
  216059. #define JUCE_USE_OGGVORBIS 1
  216060. #endif
  216061. /** This flag lets you enable support for CD-burning. You might want to disable
  216062. it to build without the MS SDK under windows.
  216063. */
  216064. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  216065. #define JUCE_USE_CDBURNER 1
  216066. #endif
  216067. /** Enabling this macro means that all regions that get repainted will have a coloured
  216068. line drawn around them.
  216069. This is handy if you're trying to optimise drawing, because it lets you easily see
  216070. when anything is being repainted unnecessarily.
  216071. */
  216072. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  216073. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  216074. #endif
  216075. /** Enable this under Linux to use Xinerama for multi-monitor support.
  216076. */
  216077. #ifndef JUCE_USE_XINERAMA
  216078. #define JUCE_USE_XINERAMA 1
  216079. #endif
  216080. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  216081. */
  216082. #ifndef JUCE_USE_XSHM
  216083. #define JUCE_USE_XSHM 1
  216084. #endif
  216085. /** Enabling this builds support for VST audio plugins.
  216086. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  216087. */
  216088. #ifndef JUCE_PLUGINHOST_VST
  216089. // #define JUCE_PLUGINHOST_VST 1
  216090. #endif
  216091. /** Enabling this builds support for AudioUnit audio plugins.
  216092. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  216093. */
  216094. #ifndef JUCE_PLUGINHOST_AU
  216095. // #define JUCE_PLUGINHOST_AU 1
  216096. #endif
  216097. /** Disabling this will avoid linking to any UI code. This is handy for
  216098. writing command-line utilities, e.g. on linux boxes which don't have some
  216099. of the UI libraries installed.
  216100. (On mac and windows, this won't generally make much difference to the build).
  216101. */
  216102. #ifndef JUCE_BUILD_GUI_CLASSES
  216103. #define JUCE_BUILD_GUI_CLASSES 1
  216104. #endif
  216105. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  216106. */
  216107. #ifndef JUCE_WEB_BROWSER
  216108. #define JUCE_WEB_BROWSER 1
  216109. #endif
  216110. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  216111. codebase - you might need to use this if you're linking to some of these libraries
  216112. yourself.
  216113. */
  216114. #ifndef JUCE_INCLUDE_ZLIB_CODE
  216115. #define JUCE_INCLUDE_ZLIB_CODE 1
  216116. #endif
  216117. #ifndef JUCE_INCLUDE_FLAC_CODE
  216118. #define JUCE_INCLUDE_FLAC_CODE 1
  216119. #endif
  216120. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  216121. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  216122. #endif
  216123. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  216124. #define JUCE_INCLUDE_PNGLIB_CODE 1
  216125. #endif
  216126. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  216127. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  216128. #endif
  216129. /** Enable this to add extra memory-leak info to the new and delete operators.
  216130. (Currently, this only affects Windows builds in debug mode).
  216131. */
  216132. #ifndef JUCE_CHECK_MEMORY_LEAKS
  216133. #define JUCE_CHECK_MEMORY_LEAKS 1
  216134. #endif
  216135. /** Enable this to turn on juce's internal catching of exceptions.
  216136. Turning it off will avoid any exception catching. With it on, all exceptions
  216137. are passed to the JUCEApplication::unhandledException() callback for logging.
  216138. */
  216139. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  216140. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  216141. #endif
  216142. /** If this macro is set, the Juce String class will use unicode as its
  216143. internal representation. If it isn't set, it'll use ANSI.
  216144. */
  216145. #ifndef JUCE_STRINGS_ARE_UNICODE
  216146. #define JUCE_STRINGS_ARE_UNICODE 1
  216147. #endif
  216148. #endif
  216149. /********* End of inlined file: juce_Config.h *********/
  216150. /* Remove this macro if you're having problems compiling the cpu affinity
  216151. calls (the API for these has changed about quite a bit in various Linux
  216152. versions, and a lot of distros seem to ship with obsolete versions)
  216153. */
  216154. #ifndef SUPPORT_AFFINITIES
  216155. #define SUPPORT_AFFINITIES 1
  216156. #endif
  216157. #endif // __LINUXINCLUDES_JUCEHEADER__
  216158. /********* End of inlined file: linuxincludes.h *********/
  216159. #include <sys/stat.h>
  216160. #include <sys/dir.h>
  216161. #include <sys/ptrace.h>
  216162. #include <sys/vfs.h> // for statfs
  216163. #include <sys/wait.h>
  216164. #include <unistd.h>
  216165. #include <fnmatch.h>
  216166. #include <utime.h>
  216167. #include <pwd.h>
  216168. #include <fcntl.h>
  216169. #define U_ISOFS_SUPER_MAGIC (short) 0x9660 // linux/iso_fs.h
  216170. #define U_MSDOS_SUPER_MAGIC (short) 0x4d44 // linux/msdos_fs.h
  216171. #define U_NFS_SUPER_MAGIC (short) 0x6969 // linux/nfs_fs.h
  216172. #define U_SMB_SUPER_MAGIC (short) 0x517B // linux/smb_fs.h
  216173. BEGIN_JUCE_NAMESPACE
  216174. /*
  216175. Note that a lot of methods that you'd expect to find in this file actually
  216176. live in juce_posix_SharedCode.h!
  216177. */
  216178. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  216179. /*
  216180. This file contains posix routines that are common to both the Linux and Mac builds.
  216181. It gets included directly in the cpp files for these platforms.
  216182. */
  216183. CriticalSection::CriticalSection() throw()
  216184. {
  216185. pthread_mutexattr_t atts;
  216186. pthread_mutexattr_init (&atts);
  216187. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  216188. pthread_mutex_init (&internal, &atts);
  216189. }
  216190. CriticalSection::~CriticalSection() throw()
  216191. {
  216192. pthread_mutex_destroy (&internal);
  216193. }
  216194. void CriticalSection::enter() const throw()
  216195. {
  216196. pthread_mutex_lock (&internal);
  216197. }
  216198. bool CriticalSection::tryEnter() const throw()
  216199. {
  216200. return pthread_mutex_trylock (&internal) == 0;
  216201. }
  216202. void CriticalSection::exit() const throw()
  216203. {
  216204. pthread_mutex_unlock (&internal);
  216205. }
  216206. struct EventStruct
  216207. {
  216208. pthread_cond_t condition;
  216209. pthread_mutex_t mutex;
  216210. bool triggered;
  216211. };
  216212. WaitableEvent::WaitableEvent() throw()
  216213. {
  216214. EventStruct* const es = new EventStruct();
  216215. es->triggered = false;
  216216. pthread_cond_init (&es->condition, 0);
  216217. pthread_mutex_init (&es->mutex, 0);
  216218. internal = es;
  216219. }
  216220. WaitableEvent::~WaitableEvent() throw()
  216221. {
  216222. EventStruct* const es = (EventStruct*) internal;
  216223. pthread_cond_destroy (&es->condition);
  216224. pthread_mutex_destroy (&es->mutex);
  216225. delete es;
  216226. }
  216227. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  216228. {
  216229. EventStruct* const es = (EventStruct*) internal;
  216230. bool ok = true;
  216231. pthread_mutex_lock (&es->mutex);
  216232. if (timeOutMillisecs < 0)
  216233. {
  216234. while (! es->triggered)
  216235. pthread_cond_wait (&es->condition, &es->mutex);
  216236. }
  216237. else
  216238. {
  216239. while (! es->triggered)
  216240. {
  216241. struct timeval t;
  216242. gettimeofday (&t, 0);
  216243. struct timespec time;
  216244. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  216245. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  216246. if (time.tv_nsec >= 1000000000)
  216247. {
  216248. time.tv_nsec -= 1000000000;
  216249. time.tv_sec++;
  216250. }
  216251. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  216252. {
  216253. ok = false;
  216254. break;
  216255. }
  216256. }
  216257. }
  216258. es->triggered = false;
  216259. pthread_mutex_unlock (&es->mutex);
  216260. return ok;
  216261. }
  216262. void WaitableEvent::signal() const throw()
  216263. {
  216264. EventStruct* const es = (EventStruct*) internal;
  216265. pthread_mutex_lock (&es->mutex);
  216266. es->triggered = true;
  216267. pthread_cond_broadcast (&es->condition);
  216268. pthread_mutex_unlock (&es->mutex);
  216269. }
  216270. void WaitableEvent::reset() const throw()
  216271. {
  216272. EventStruct* const es = (EventStruct*) internal;
  216273. pthread_mutex_lock (&es->mutex);
  216274. es->triggered = false;
  216275. pthread_mutex_unlock (&es->mutex);
  216276. }
  216277. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  216278. {
  216279. struct timespec time;
  216280. time.tv_sec = millisecs / 1000;
  216281. time.tv_nsec = (millisecs % 1000) * 1000000;
  216282. nanosleep (&time, 0);
  216283. }
  216284. const tchar File::separator = T('/');
  216285. const tchar* File::separatorString = T("/");
  216286. bool juce_copyFile (const String& s, const String& d) throw();
  216287. static bool juce_stat (const String& fileName, struct stat& info) throw()
  216288. {
  216289. return fileName.isNotEmpty()
  216290. && (stat (fileName.toUTF8(), &info) == 0);
  216291. }
  216292. bool juce_isDirectory (const String& fileName) throw()
  216293. {
  216294. struct stat info;
  216295. return fileName.isEmpty()
  216296. || (juce_stat (fileName, info)
  216297. && ((info.st_mode & S_IFDIR) != 0));
  216298. }
  216299. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  216300. {
  216301. if (fileName.isEmpty())
  216302. return false;
  216303. const char* const fileNameUTF8 = fileName.toUTF8();
  216304. bool exists = access (fileNameUTF8, F_OK) == 0;
  216305. if (exists && dontCountDirectories)
  216306. {
  216307. struct stat info;
  216308. const int res = stat (fileNameUTF8, &info);
  216309. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  216310. exists = false;
  216311. }
  216312. return exists;
  216313. }
  216314. int64 juce_getFileSize (const String& fileName) throw()
  216315. {
  216316. struct stat info;
  216317. return juce_stat (fileName, info) ? info.st_size : 0;
  216318. }
  216319. bool juce_canWriteToFile (const String& fileName) throw()
  216320. {
  216321. return access (fileName.toUTF8(), W_OK) == 0;
  216322. }
  216323. bool juce_deleteFile (const String& fileName) throw()
  216324. {
  216325. const char* const fileNameUTF8 = fileName.toUTF8();
  216326. if (juce_isDirectory (fileName))
  216327. return rmdir (fileNameUTF8) == 0;
  216328. else
  216329. return remove (fileNameUTF8) == 0;
  216330. }
  216331. bool juce_moveFile (const String& source, const String& dest) throw()
  216332. {
  216333. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  216334. return true;
  216335. if (juce_canWriteToFile (source)
  216336. && juce_copyFile (source, dest))
  216337. {
  216338. if (juce_deleteFile (source))
  216339. return true;
  216340. juce_deleteFile (dest);
  216341. }
  216342. return false;
  216343. }
  216344. void juce_createDirectory (const String& fileName) throw()
  216345. {
  216346. mkdir (fileName.toUTF8(), 0777);
  216347. }
  216348. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  216349. {
  216350. const char* const fileNameUTF8 = fileName.toUTF8();
  216351. int flags = O_RDONLY;
  216352. if (forWriting)
  216353. {
  216354. if (juce_fileExists (fileName, false))
  216355. {
  216356. const int f = open (fileNameUTF8, O_RDWR, 00644);
  216357. if (f != -1)
  216358. lseek (f, 0, SEEK_END);
  216359. return (void*) f;
  216360. }
  216361. else
  216362. {
  216363. flags = O_RDWR + O_CREAT;
  216364. }
  216365. }
  216366. return (void*) open (fileNameUTF8, flags, 00644);
  216367. }
  216368. void juce_fileClose (void* handle) throw()
  216369. {
  216370. if (handle != 0)
  216371. close ((int) (pointer_sized_int) handle);
  216372. }
  216373. int juce_fileRead (void* handle, void* buffer, int size) throw()
  216374. {
  216375. if (handle != 0)
  216376. return read ((int) (pointer_sized_int) handle, buffer, size);
  216377. return 0;
  216378. }
  216379. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  216380. {
  216381. if (handle != 0)
  216382. return write ((int) (pointer_sized_int) handle, buffer, size);
  216383. return 0;
  216384. }
  216385. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  216386. {
  216387. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  216388. return pos;
  216389. return -1;
  216390. }
  216391. int64 juce_fileGetPosition (void* handle) throw()
  216392. {
  216393. if (handle != 0)
  216394. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  216395. else
  216396. return -1;
  216397. }
  216398. void juce_fileFlush (void* handle) throw()
  216399. {
  216400. if (handle != 0)
  216401. fsync ((int) (pointer_sized_int) handle);
  216402. }
  216403. // if this file doesn't exist, find a parent of it that does..
  216404. static bool doStatFS (const File* file, struct statfs& result) throw()
  216405. {
  216406. File f (*file);
  216407. for (int i = 5; --i >= 0;)
  216408. {
  216409. if (f.exists())
  216410. break;
  216411. f = f.getParentDirectory();
  216412. }
  216413. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  216414. }
  216415. int64 File::getBytesFreeOnVolume() const throw()
  216416. {
  216417. int64 free_space = 0;
  216418. struct statfs buf;
  216419. if (doStatFS (this, buf))
  216420. // Note: this returns space available to non-super user
  216421. free_space = (int64) buf.f_bsize * (int64) buf.f_bavail;
  216422. return free_space;
  216423. }
  216424. const String juce_getVolumeLabel (const String& filenameOnVolume,
  216425. int& volumeSerialNumber) throw()
  216426. {
  216427. // There is no equivalent on Linux
  216428. volumeSerialNumber = 0;
  216429. return String::empty;
  216430. }
  216431. #if JUCE_64BIT
  216432. #define filedesc ((long long) internal)
  216433. #else
  216434. #define filedesc ((int) internal)
  216435. #endif
  216436. InterProcessLock::InterProcessLock (const String& name_) throw()
  216437. : internal (0),
  216438. name (name_),
  216439. reentrancyLevel (0)
  216440. {
  216441. #if JUCE_MAC
  216442. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  216443. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  216444. #else
  216445. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  216446. #endif
  216447. temp.create();
  216448. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  216449. }
  216450. InterProcessLock::~InterProcessLock() throw()
  216451. {
  216452. while (reentrancyLevel > 0)
  216453. this->exit();
  216454. close (filedesc);
  216455. }
  216456. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  216457. {
  216458. if (internal == 0)
  216459. return false;
  216460. if (reentrancyLevel != 0)
  216461. return true;
  216462. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  216463. struct flock fl;
  216464. zerostruct (fl);
  216465. fl.l_whence = SEEK_SET;
  216466. fl.l_type = F_WRLCK;
  216467. for (;;)
  216468. {
  216469. const int result = fcntl (filedesc, F_SETLK, &fl);
  216470. if (result >= 0)
  216471. {
  216472. ++reentrancyLevel;
  216473. return true;
  216474. }
  216475. if (errno != EINTR)
  216476. {
  216477. if (timeOutMillisecs == 0
  216478. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  216479. break;
  216480. Thread::sleep (10);
  216481. }
  216482. }
  216483. return false;
  216484. }
  216485. void InterProcessLock::exit() throw()
  216486. {
  216487. if (reentrancyLevel > 0 && internal != 0)
  216488. {
  216489. --reentrancyLevel;
  216490. struct flock fl;
  216491. zerostruct (fl);
  216492. fl.l_whence = SEEK_SET;
  216493. fl.l_type = F_UNLCK;
  216494. for (;;)
  216495. {
  216496. const int result = fcntl (filedesc, F_SETLKW, &fl);
  216497. if (result >= 0 || errno != EINTR)
  216498. break;
  216499. }
  216500. }
  216501. }
  216502. /********* End of inlined file: juce_posix_SharedCode.h *********/
  216503. static File executableFile;
  216504. void juce_getFileTimes (const String& fileName,
  216505. int64& modificationTime,
  216506. int64& accessTime,
  216507. int64& creationTime) throw()
  216508. {
  216509. modificationTime = 0;
  216510. accessTime = 0;
  216511. creationTime = 0;
  216512. struct stat info;
  216513. const int res = stat (fileName.toUTF8(), &info);
  216514. if (res == 0)
  216515. {
  216516. modificationTime = (int64) info.st_mtime * 1000;
  216517. accessTime = (int64) info.st_atime * 1000;
  216518. creationTime = (int64) info.st_ctime * 1000;
  216519. }
  216520. }
  216521. bool juce_setFileTimes (const String& fileName,
  216522. int64 modificationTime,
  216523. int64 accessTime,
  216524. int64 creationTime) throw()
  216525. {
  216526. struct utimbuf times;
  216527. times.actime = (time_t) (accessTime / 1000);
  216528. times.modtime = (time_t) (modificationTime / 1000);
  216529. return utime (fileName.toUTF8(), &times) == 0;
  216530. }
  216531. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  216532. {
  216533. struct stat info;
  216534. const int res = stat (fileName.toUTF8(), &info);
  216535. if (res != 0)
  216536. return false;
  216537. info.st_mode &= 0777; // Just permissions
  216538. if( isReadOnly )
  216539. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  216540. else
  216541. // Give everybody write permission?
  216542. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  216543. return chmod (fileName.toUTF8(), info.st_mode) == 0;
  216544. }
  216545. bool juce_copyFile (const String& s, const String& d) throw()
  216546. {
  216547. const File source (s), dest (d);
  216548. FileInputStream* in = source.createInputStream();
  216549. bool ok = false;
  216550. if (in != 0)
  216551. {
  216552. if (dest.deleteFile())
  216553. {
  216554. FileOutputStream* const out = dest.createOutputStream();
  216555. if (out != 0)
  216556. {
  216557. const int bytesCopied = out->writeFromInputStream (*in, -1);
  216558. delete out;
  216559. ok = (bytesCopied == source.getSize());
  216560. if (! ok)
  216561. dest.deleteFile();
  216562. }
  216563. }
  216564. delete in;
  216565. }
  216566. return ok;
  216567. }
  216568. const StringArray juce_getFileSystemRoots() throw()
  216569. {
  216570. StringArray s;
  216571. s.add (T("/"));
  216572. return s;
  216573. }
  216574. bool File::isOnCDRomDrive() const throw()
  216575. {
  216576. struct statfs buf;
  216577. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  216578. return (buf.f_type == U_ISOFS_SUPER_MAGIC);
  216579. // Assume not if this fails for some reason
  216580. return false;
  216581. }
  216582. bool File::isOnHardDisk() const throw()
  216583. {
  216584. struct statfs buf;
  216585. if (statfs (getFullPathName().toUTF8(), &buf) == 0)
  216586. {
  216587. switch (buf.f_type)
  216588. {
  216589. case U_ISOFS_SUPER_MAGIC: // CD-ROM
  216590. case U_MSDOS_SUPER_MAGIC: // Probably floppy (but could be mounted FAT filesystem)
  216591. case U_NFS_SUPER_MAGIC: // Network NFS
  216592. case U_SMB_SUPER_MAGIC: // Network Samba
  216593. return false;
  216594. default:
  216595. // Assume anything else is a hard-disk (but note it could
  216596. // be a RAM disk. There isn't a good way of determining
  216597. // this for sure)
  216598. return true;
  216599. }
  216600. }
  216601. // Assume so if this fails for some reason
  216602. return true;
  216603. }
  216604. bool File::isOnRemovableDrive() const throw()
  216605. {
  216606. jassertfalse // xxx not implemented for linux!
  216607. return false;
  216608. }
  216609. bool File::isHidden() const throw()
  216610. {
  216611. return getFileName().startsWithChar (T('.'));
  216612. }
  216613. const File File::getSpecialLocation (const SpecialLocationType type)
  216614. {
  216615. switch (type)
  216616. {
  216617. case userHomeDirectory:
  216618. {
  216619. const char* homeDir = getenv ("HOME");
  216620. if (homeDir == 0)
  216621. {
  216622. struct passwd* const pw = getpwuid (getuid());
  216623. if (pw != 0)
  216624. homeDir = pw->pw_dir;
  216625. }
  216626. return File (String::fromUTF8 ((const uint8*) homeDir));
  216627. }
  216628. case userDocumentsDirectory:
  216629. case userMusicDirectory:
  216630. case userMoviesDirectory:
  216631. case userApplicationDataDirectory:
  216632. return File ("~");
  216633. case userDesktopDirectory:
  216634. return File ("~/Desktop");
  216635. case commonApplicationDataDirectory:
  216636. return File ("/var");
  216637. case globalApplicationsDirectory:
  216638. return File ("/usr");
  216639. case tempDirectory:
  216640. {
  216641. File tmp ("/var/tmp");
  216642. if (! tmp.isDirectory())
  216643. {
  216644. tmp = T("/tmp");
  216645. if (! tmp.isDirectory())
  216646. tmp = File::getCurrentWorkingDirectory();
  216647. }
  216648. return tmp;
  216649. }
  216650. case currentExecutableFile:
  216651. case currentApplicationFile:
  216652. // if this fails, it's probably because juce_setCurrentExecutableFileName()
  216653. // was never called to set the filename - this should be done by the juce
  216654. // main() function, so maybe you've hacked it to use your own custom main()?
  216655. jassert (executableFile.exists());
  216656. return executableFile;
  216657. default:
  216658. jassertfalse // unknown type?
  216659. break;
  216660. }
  216661. return File::nonexistent;
  216662. }
  216663. void juce_setCurrentExecutableFileName (const String& filename) throw()
  216664. {
  216665. executableFile = File::getCurrentWorkingDirectory().getChildFile (filename);
  216666. }
  216667. const File File::getCurrentWorkingDirectory() throw()
  216668. {
  216669. char buf [2048];
  216670. getcwd (buf, sizeof(buf));
  216671. return File (String::fromUTF8 ((const uint8*) buf));
  216672. }
  216673. bool File::setAsCurrentWorkingDirectory() const throw()
  216674. {
  216675. return chdir (getFullPathName().toUTF8()) == 0;
  216676. }
  216677. struct FindFileStruct
  216678. {
  216679. String parentDir, wildCard;
  216680. DIR* dir;
  216681. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  216682. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  216683. {
  216684. const char* const wildcardUTF8 = wildCard.toUTF8();
  216685. for (;;)
  216686. {
  216687. struct dirent* const de = readdir (dir);
  216688. if (de == 0)
  216689. break;
  216690. if (fnmatch (wildcardUTF8, de->d_name, FNM_CASEFOLD) == 0)
  216691. {
  216692. result = String::fromUTF8 ((const uint8*) de->d_name);
  216693. const String path (parentDir + result);
  216694. if (isDir != 0 || fileSize != 0)
  216695. {
  216696. struct stat info;
  216697. const bool statOk = (stat (path.toUTF8(), &info) == 0);
  216698. if (isDir != 0)
  216699. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  216700. if (isHidden != 0)
  216701. *isHidden = (de->d_name[0] == '.');
  216702. if (fileSize != 0)
  216703. *fileSize = statOk ? info.st_size : 0;
  216704. }
  216705. if (modTime != 0 || creationTime != 0)
  216706. {
  216707. int64 m, a, c;
  216708. juce_getFileTimes (path, m, a, c);
  216709. if (modTime != 0)
  216710. *modTime = m;
  216711. if (creationTime != 0)
  216712. *creationTime = c;
  216713. }
  216714. if (isReadOnly != 0)
  216715. *isReadOnly = ! juce_canWriteToFile (path);
  216716. return true;
  216717. }
  216718. }
  216719. return false;
  216720. }
  216721. };
  216722. // returns 0 on failure
  216723. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  216724. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  216725. Time* creationTime, bool* isReadOnly) throw()
  216726. {
  216727. DIR* d = opendir (directory.toUTF8());
  216728. if (d != 0)
  216729. {
  216730. FindFileStruct* ff = new FindFileStruct();
  216731. ff->parentDir = directory;
  216732. if (!ff->parentDir.endsWithChar (File::separator))
  216733. ff->parentDir += File::separator;
  216734. ff->wildCard = wildCard;
  216735. if (wildCard == T("*.*"))
  216736. ff->wildCard = T("*");
  216737. ff->dir = d;
  216738. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  216739. {
  216740. return ff;
  216741. }
  216742. else
  216743. {
  216744. firstResultFile = String::empty;
  216745. isDir = false;
  216746. isHidden = false;
  216747. closedir (d);
  216748. delete ff;
  216749. }
  216750. }
  216751. return 0;
  216752. }
  216753. bool juce_findFileNext (void* handle, String& resultFile,
  216754. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  216755. {
  216756. FindFileStruct* const ff = (FindFileStruct*) handle;
  216757. if (ff != 0)
  216758. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  216759. return false;
  216760. }
  216761. void juce_findFileClose (void* handle) throw()
  216762. {
  216763. FindFileStruct* const ff = (FindFileStruct*) handle;
  216764. if (ff != 0)
  216765. {
  216766. closedir (ff->dir);
  216767. delete ff;
  216768. }
  216769. }
  216770. bool juce_launchFile (const String& fileName,
  216771. const String& parameters) throw()
  216772. {
  216773. String cmdString (fileName);
  216774. cmdString << " " << parameters;
  216775. if (URL::isProbablyAWebsiteURL (cmdString) || URL::isProbablyAnEmailAddress (cmdString))
  216776. {
  216777. // create a command that tries to launch a bunch of likely browsers
  216778. const char* const browserNames[] = { "/etc/alternatives/x-www-browser", "firefox", "mozilla", "konqueror", "opera" };
  216779. StringArray cmdLines;
  216780. for (int i = 0; i < numElementsInArray (browserNames); ++i)
  216781. cmdLines.add (String (browserNames[i]) + T(" ") + cmdString.trim().quoted());
  216782. cmdString = cmdLines.joinIntoString (T(" || "));
  216783. }
  216784. char* const argv[4] = { "/bin/sh", "-c", (char*) cmdString.toUTF8(), 0 };
  216785. const int cpid = fork();
  216786. if (cpid == 0)
  216787. {
  216788. setsid();
  216789. // Child process
  216790. execve (argv[0], argv, environ);
  216791. exit (0);
  216792. }
  216793. return cpid >= 0;
  216794. }
  216795. END_JUCE_NAMESPACE
  216796. /********* End of inlined file: juce_linux_Files.cpp *********/
  216797. /********* Start of inlined file: juce_linux_NamedPipe.cpp *********/
  216798. /********* Start of inlined file: juce_mac_NamedPipe.cpp *********/
  216799. #include <sys/stat.h>
  216800. #include <sys/dir.h>
  216801. #include <fcntl.h>
  216802. // As well as being for the mac, this file is included by the linux build.
  216803. #if ! JUCE_MAC
  216804. #include <sys/wait.h>
  216805. #include <errno.h>
  216806. #include <unistd.h>
  216807. #endif
  216808. BEGIN_JUCE_NAMESPACE
  216809. struct NamedPipeInternal
  216810. {
  216811. String pipeInName, pipeOutName;
  216812. int pipeIn, pipeOut;
  216813. bool volatile createdPipe, blocked, stopReadOperation;
  216814. static void signalHandler (int) {}
  216815. };
  216816. void NamedPipe::cancelPendingReads()
  216817. {
  216818. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  216819. {
  216820. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216821. intern->stopReadOperation = true;
  216822. char buffer [1] = { 0 };
  216823. ::write (intern->pipeIn, buffer, 1);
  216824. int timeout = 2000;
  216825. while (intern->blocked && --timeout >= 0)
  216826. Thread::sleep (2);
  216827. intern->stopReadOperation = false;
  216828. }
  216829. }
  216830. void NamedPipe::close()
  216831. {
  216832. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216833. if (intern != 0)
  216834. {
  216835. internal = 0;
  216836. if (intern->pipeIn != -1)
  216837. ::close (intern->pipeIn);
  216838. if (intern->pipeOut != -1)
  216839. ::close (intern->pipeOut);
  216840. if (intern->createdPipe)
  216841. {
  216842. unlink (intern->pipeInName);
  216843. unlink (intern->pipeOutName);
  216844. }
  216845. delete intern;
  216846. }
  216847. }
  216848. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  216849. {
  216850. close();
  216851. NamedPipeInternal* const intern = new NamedPipeInternal();
  216852. internal = intern;
  216853. intern->createdPipe = createPipe;
  216854. intern->blocked = false;
  216855. intern->stopReadOperation = false;
  216856. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  216857. siginterrupt (SIGPIPE, 1);
  216858. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  216859. intern->pipeInName = pipePath + T("_in");
  216860. intern->pipeOutName = pipePath + T("_out");
  216861. intern->pipeIn = -1;
  216862. intern->pipeOut = -1;
  216863. if (createPipe)
  216864. {
  216865. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  216866. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  216867. {
  216868. delete intern;
  216869. internal = 0;
  216870. return false;
  216871. }
  216872. }
  216873. return true;
  216874. }
  216875. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  216876. {
  216877. int bytesRead = -1;
  216878. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216879. if (intern != 0)
  216880. {
  216881. intern->blocked = true;
  216882. if (intern->pipeIn == -1)
  216883. {
  216884. if (intern->createdPipe)
  216885. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  216886. else
  216887. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  216888. if (intern->pipeIn == -1)
  216889. {
  216890. intern->blocked = false;
  216891. return -1;
  216892. }
  216893. }
  216894. bytesRead = 0;
  216895. char* p = (char*) destBuffer;
  216896. while (bytesRead < maxBytesToRead)
  216897. {
  216898. const int bytesThisTime = maxBytesToRead - bytesRead;
  216899. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  216900. if (numRead <= 0 || intern->stopReadOperation)
  216901. {
  216902. bytesRead = -1;
  216903. break;
  216904. }
  216905. bytesRead += numRead;
  216906. p += bytesRead;
  216907. }
  216908. intern->blocked = false;
  216909. }
  216910. return bytesRead;
  216911. }
  216912. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  216913. {
  216914. int bytesWritten = -1;
  216915. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  216916. if (intern != 0)
  216917. {
  216918. if (intern->pipeOut == -1)
  216919. {
  216920. if (intern->createdPipe)
  216921. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  216922. else
  216923. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  216924. if (intern->pipeOut == -1)
  216925. {
  216926. return -1;
  216927. }
  216928. }
  216929. const char* p = (const char*) sourceBuffer;
  216930. bytesWritten = 0;
  216931. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  216932. while (bytesWritten < numBytesToWrite
  216933. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  216934. {
  216935. const int bytesThisTime = numBytesToWrite - bytesWritten;
  216936. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  216937. if (numWritten <= 0)
  216938. {
  216939. bytesWritten = -1;
  216940. break;
  216941. }
  216942. bytesWritten += numWritten;
  216943. p += bytesWritten;
  216944. }
  216945. }
  216946. return bytesWritten;
  216947. }
  216948. END_JUCE_NAMESPACE
  216949. /********* End of inlined file: juce_mac_NamedPipe.cpp *********/
  216950. /********* End of inlined file: juce_linux_NamedPipe.cpp *********/
  216951. /********* Start of inlined file: juce_linux_Network.cpp *********/
  216952. #include <netdb.h>
  216953. #include <arpa/inet.h>
  216954. #include <netinet/in.h>
  216955. #include <sys/types.h>
  216956. #include <sys/ioctl.h>
  216957. #include <sys/socket.h>
  216958. #include <sys/wait.h>
  216959. #include <linux/if.h>
  216960. BEGIN_JUCE_NAMESPACE
  216961. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  216962. {
  216963. int numResults = 0;
  216964. const int s = socket (AF_INET, SOCK_DGRAM, 0);
  216965. if (s != -1)
  216966. {
  216967. char buf [1024];
  216968. struct ifconf ifc;
  216969. ifc.ifc_len = sizeof (buf);
  216970. ifc.ifc_buf = buf;
  216971. ioctl (s, SIOCGIFCONF, &ifc);
  216972. for (unsigned int i = 0; i < ifc.ifc_len / sizeof (struct ifreq); ++i)
  216973. {
  216974. struct ifreq ifr;
  216975. strcpy (ifr.ifr_name, ifc.ifc_req[i].ifr_name);
  216976. if (ioctl (s, SIOCGIFFLAGS, &ifr) == 0
  216977. && (ifr.ifr_flags & IFF_LOOPBACK) == 0
  216978. && ioctl (s, SIOCGIFHWADDR, &ifr) == 0
  216979. && numResults < maxNum)
  216980. {
  216981. int64 a = 0;
  216982. for (int j = 6; --j >= 0;)
  216983. a = (a << 8) | (uint8) ifr.ifr_hwaddr.sa_data[j];
  216984. *addresses++ = a;
  216985. ++numResults;
  216986. }
  216987. }
  216988. close (s);
  216989. }
  216990. return numResults;
  216991. }
  216992. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  216993. const String& emailSubject,
  216994. const String& bodyText,
  216995. const StringArray& filesToAttach)
  216996. {
  216997. jassertfalse // xxx todo
  216998. return false;
  216999. }
  217000. /** A HTTP input stream that uses sockets.
  217001. */
  217002. class JUCE_HTTPSocketStream
  217003. {
  217004. public:
  217005. JUCE_HTTPSocketStream()
  217006. : readPosition (0),
  217007. socketHandle (-1),
  217008. levelsOfRedirection (0),
  217009. timeoutSeconds (15)
  217010. {
  217011. }
  217012. ~JUCE_HTTPSocketStream()
  217013. {
  217014. closeSocket();
  217015. }
  217016. bool open (const String& url,
  217017. const String& headers,
  217018. const MemoryBlock& postData,
  217019. const bool isPost,
  217020. URL::OpenStreamProgressCallback* callback,
  217021. void* callbackContext,
  217022. int timeOutMs)
  217023. {
  217024. closeSocket();
  217025. uint32 timeOutTime = Time::getMillisecondCounter();
  217026. if (timeOutMs == 0)
  217027. timeOutTime += 60000;
  217028. else if (timeOutMs < 0)
  217029. timeOutTime = 0xffffffff;
  217030. else
  217031. timeOutTime += timeOutMs;
  217032. String hostName, hostPath;
  217033. int hostPort;
  217034. if (! decomposeURL (url, hostName, hostPath, hostPort))
  217035. return false;
  217036. const struct hostent* host = 0;
  217037. int port = 0;
  217038. String proxyName, proxyPath;
  217039. int proxyPort = 0;
  217040. String proxyURL (getenv ("http_proxy"));
  217041. if (proxyURL.startsWithIgnoreCase (T("http://")))
  217042. {
  217043. if (! decomposeURL (proxyURL, proxyName, proxyPath, proxyPort))
  217044. return false;
  217045. host = gethostbyname ((const char*) proxyName.toUTF8());
  217046. port = proxyPort;
  217047. }
  217048. else
  217049. {
  217050. host = gethostbyname ((const char*) hostName.toUTF8());
  217051. port = hostPort;
  217052. }
  217053. if (host == 0)
  217054. return false;
  217055. struct sockaddr_in address;
  217056. zerostruct (address);
  217057. memcpy ((void*) &address.sin_addr, (const void*) host->h_addr, host->h_length);
  217058. address.sin_family = host->h_addrtype;
  217059. address.sin_port = htons (port);
  217060. socketHandle = socket (host->h_addrtype, SOCK_STREAM, 0);
  217061. if (socketHandle == -1)
  217062. return false;
  217063. int receiveBufferSize = 16384;
  217064. setsockopt (socketHandle, SOL_SOCKET, SO_RCVBUF, (char*) &receiveBufferSize, sizeof (receiveBufferSize));
  217065. setsockopt (socketHandle, SOL_SOCKET, SO_KEEPALIVE, 0, 0);
  217066. #if JUCE_MAC
  217067. setsockopt (socketHandle, SOL_SOCKET, SO_NOSIGPIPE, 0, 0);
  217068. #endif
  217069. if (connect (socketHandle, (struct sockaddr*) &address, sizeof (address)) == -1)
  217070. {
  217071. closeSocket();
  217072. return false;
  217073. }
  217074. const MemoryBlock requestHeader (createRequestHeader (hostName, hostPort,
  217075. proxyName, proxyPort,
  217076. hostPath, url,
  217077. headers, postData,
  217078. isPost));
  217079. int totalHeaderSent = 0;
  217080. while (totalHeaderSent < requestHeader.getSize())
  217081. {
  217082. if (Time::getMillisecondCounter() > timeOutTime)
  217083. {
  217084. closeSocket();
  217085. return false;
  217086. }
  217087. const int numToSend = jmin (1024, requestHeader.getSize() - totalHeaderSent);
  217088. if (send (socketHandle,
  217089. ((const char*) requestHeader.getData()) + totalHeaderSent,
  217090. numToSend, 0)
  217091. != numToSend)
  217092. {
  217093. closeSocket();
  217094. return false;
  217095. }
  217096. totalHeaderSent += numToSend;
  217097. if (callback != 0 && ! callback (callbackContext, totalHeaderSent, requestHeader.getSize()))
  217098. {
  217099. closeSocket();
  217100. return false;
  217101. }
  217102. }
  217103. const String responseHeader (readResponse (timeOutTime));
  217104. if (responseHeader.isNotEmpty())
  217105. {
  217106. //DBG (responseHeader);
  217107. StringArray lines;
  217108. lines.addLines (responseHeader);
  217109. // NB - using charToString() here instead of just T(" "), because that was
  217110. // causing a mysterious gcc internal compiler error...
  217111. const int statusCode = responseHeader.fromFirstOccurrenceOf (String::charToString (T(' ')), false, false)
  217112. .substring (0, 3)
  217113. .getIntValue();
  217114. //int contentLength = findHeaderItem (lines, T("Content-Length:")).getIntValue();
  217115. //bool isChunked = findHeaderItem (lines, T("Transfer-Encoding:")).equalsIgnoreCase ("chunked");
  217116. String location (findHeaderItem (lines, T("Location:")));
  217117. if (statusCode >= 300 && statusCode < 400
  217118. && location.isNotEmpty())
  217119. {
  217120. if (! location.startsWithIgnoreCase (T("http://")))
  217121. location = T("http://") + location;
  217122. if (levelsOfRedirection++ < 3)
  217123. return open (location, headers, postData, isPost, callback, callbackContext, timeOutMs);
  217124. }
  217125. else
  217126. {
  217127. levelsOfRedirection = 0;
  217128. return true;
  217129. }
  217130. }
  217131. closeSocket();
  217132. return false;
  217133. }
  217134. int read (void* buffer, int bytesToRead)
  217135. {
  217136. fd_set readbits;
  217137. FD_ZERO (&readbits);
  217138. FD_SET (socketHandle, &readbits);
  217139. struct timeval tv;
  217140. tv.tv_sec = timeoutSeconds;
  217141. tv.tv_usec = 0;
  217142. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217143. return 0; // (timeout)
  217144. const int bytesRead = jmax (0, recv (socketHandle, buffer, bytesToRead, MSG_WAITALL));
  217145. readPosition += bytesRead;
  217146. return bytesRead;
  217147. }
  217148. int readPosition;
  217149. juce_UseDebuggingNewOperator
  217150. private:
  217151. int socketHandle, levelsOfRedirection;
  217152. const int timeoutSeconds;
  217153. void closeSocket()
  217154. {
  217155. if (socketHandle >= 0)
  217156. close (socketHandle);
  217157. socketHandle = -1;
  217158. }
  217159. const MemoryBlock createRequestHeader (const String& hostName,
  217160. const int hostPort,
  217161. const String& proxyName,
  217162. const int proxyPort,
  217163. const String& hostPath,
  217164. const String& originalURL,
  217165. const String& headers,
  217166. const MemoryBlock& postData,
  217167. const bool isPost)
  217168. {
  217169. String header (isPost ? "POST " : "GET ");
  217170. if (proxyName.isEmpty())
  217171. {
  217172. header << hostPath << " HTTP/1.0\r\nHost: "
  217173. << hostName << ':' << hostPort;
  217174. }
  217175. else
  217176. {
  217177. header << originalURL << " HTTP/1.0\r\nHost: "
  217178. << proxyName << ':' << proxyPort;
  217179. }
  217180. header << "\r\nUser-Agent: JUCE/"
  217181. << JUCE_MAJOR_VERSION << '.' << JUCE_MINOR_VERSION
  217182. << "\r\nConnection: Close\r\nContent-Length: "
  217183. << postData.getSize() << "\r\n"
  217184. << headers << "\r\n";
  217185. MemoryBlock mb;
  217186. mb.append (header.toUTF8(), (int) strlen (header.toUTF8()));
  217187. mb.append (postData.getData(), postData.getSize());
  217188. return mb;
  217189. }
  217190. const String readResponse (const uint32 timeOutTime)
  217191. {
  217192. int bytesRead = 0, numConsecutiveLFs = 0;
  217193. MemoryBlock buffer (1024, true);
  217194. while (numConsecutiveLFs < 2 && bytesRead < 32768
  217195. && Time::getMillisecondCounter() <= timeOutTime)
  217196. {
  217197. fd_set readbits;
  217198. FD_ZERO (&readbits);
  217199. FD_SET (socketHandle, &readbits);
  217200. struct timeval tv;
  217201. tv.tv_sec = timeoutSeconds;
  217202. tv.tv_usec = 0;
  217203. if (select (socketHandle + 1, &readbits, 0, 0, &tv) <= 0)
  217204. return String::empty; // (timeout)
  217205. buffer.ensureSize (bytesRead + 8, true);
  217206. char* const dest = (char*) buffer.getData() + bytesRead;
  217207. if (recv (socketHandle, dest, 1, 0) == -1)
  217208. return String::empty;
  217209. const char lastByte = *dest;
  217210. ++bytesRead;
  217211. if (lastByte == '\n')
  217212. ++numConsecutiveLFs;
  217213. else if (lastByte != '\r')
  217214. numConsecutiveLFs = 0;
  217215. }
  217216. const String header (String::fromUTF8 ((const uint8*) buffer.getData()));
  217217. if (header.startsWithIgnoreCase (T("HTTP/")))
  217218. return header.trimEnd();
  217219. return String::empty;
  217220. }
  217221. static bool decomposeURL (const String& url,
  217222. String& host, String& path, int& port)
  217223. {
  217224. if (! url.startsWithIgnoreCase (T("http://")))
  217225. return false;
  217226. const int nextSlash = url.indexOfChar (7, '/');
  217227. int nextColon = url.indexOfChar (7, ':');
  217228. if (nextColon > nextSlash && nextSlash > 0)
  217229. nextColon = -1;
  217230. if (nextColon >= 0)
  217231. {
  217232. host = url.substring (7, nextColon);
  217233. if (nextSlash >= 0)
  217234. port = url.substring (nextColon + 1, nextSlash).getIntValue();
  217235. else
  217236. port = url.substring (nextColon + 1).getIntValue();
  217237. }
  217238. else
  217239. {
  217240. port = 80;
  217241. if (nextSlash >= 0)
  217242. host = url.substring (7, nextSlash);
  217243. else
  217244. host = url.substring (7);
  217245. }
  217246. if (nextSlash >= 0)
  217247. path = url.substring (nextSlash);
  217248. else
  217249. path = T("/");
  217250. return true;
  217251. }
  217252. static const String findHeaderItem (const StringArray& lines, const String& itemName)
  217253. {
  217254. for (int i = 0; i < lines.size(); ++i)
  217255. if (lines[i].startsWithIgnoreCase (itemName))
  217256. return lines[i].substring (itemName.length()).trim();
  217257. return String::empty;
  217258. }
  217259. };
  217260. bool juce_isOnLine()
  217261. {
  217262. return true;
  217263. }
  217264. void* juce_openInternetFile (const String& url,
  217265. const String& headers,
  217266. const MemoryBlock& postData,
  217267. const bool isPost,
  217268. URL::OpenStreamProgressCallback* callback,
  217269. void* callbackContext,
  217270. int timeOutMs)
  217271. {
  217272. JUCE_HTTPSocketStream* const s = new JUCE_HTTPSocketStream();
  217273. if (s->open (url, headers, postData, isPost,
  217274. callback, callbackContext, timeOutMs))
  217275. return s;
  217276. delete s;
  217277. return 0;
  217278. }
  217279. void juce_closeInternetFile (void* handle)
  217280. {
  217281. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  217282. if (s != 0)
  217283. delete s;
  217284. }
  217285. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  217286. {
  217287. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  217288. if (s != 0)
  217289. return s->read (buffer, bytesToRead);
  217290. return 0;
  217291. }
  217292. int juce_seekInInternetFile (void* handle, int newPosition)
  217293. {
  217294. JUCE_HTTPSocketStream* const s = (JUCE_HTTPSocketStream*) handle;
  217295. if (s != 0)
  217296. return s->readPosition;
  217297. return 0;
  217298. }
  217299. END_JUCE_NAMESPACE
  217300. /********* End of inlined file: juce_linux_Network.cpp *********/
  217301. /********* Start of inlined file: juce_linux_SystemStats.cpp *********/
  217302. #include <sys/sysinfo.h>
  217303. #include <dlfcn.h>
  217304. #ifndef CPU_ISSET
  217305. #undef SUPPORT_AFFINITIES
  217306. #endif
  217307. BEGIN_JUCE_NAMESPACE
  217308. /*static juce_noinline unsigned int getCPUIDWord (int* familyModel, int* extFeatures) throw()
  217309. {
  217310. unsigned int cpu = 0;
  217311. unsigned int ext = 0;
  217312. unsigned int family = 0;
  217313. unsigned int dummy = 0;
  217314. #if JUCE_64BIT
  217315. __asm__ ("cpuid"
  217316. : "=a" (family), "=b" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  217317. #else
  217318. __asm__ ("push %%ebx; cpuid; mov %%ebx, %%edi; pop %%ebx"
  217319. : "=a" (family), "=D" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  217320. #endif
  217321. if (familyModel != 0)
  217322. *familyModel = family;
  217323. if (extFeatures != 0)
  217324. *extFeatures = ext;
  217325. return cpu;
  217326. }*/
  217327. void Logger::outputDebugString (const String& text) throw()
  217328. {
  217329. fprintf (stdout, text.toUTF8());
  217330. fprintf (stdout, "\n");
  217331. }
  217332. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  217333. {
  217334. String text;
  217335. va_list args;
  217336. va_start (args, format);
  217337. text.vprintf(format, args);
  217338. outputDebugString(text);
  217339. }
  217340. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  217341. {
  217342. return Linux;
  217343. }
  217344. const String SystemStats::getOperatingSystemName() throw()
  217345. {
  217346. return T("Linux");
  217347. }
  217348. bool SystemStats::isOperatingSystem64Bit() throw()
  217349. {
  217350. #if JUCE_64BIT
  217351. return true;
  217352. #else
  217353. //xxx not sure how to find this out?..
  217354. return false;
  217355. #endif
  217356. }
  217357. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  217358. {
  217359. String info;
  217360. char buf [256];
  217361. FILE* f = fopen ("/proc/cpuinfo", "r");
  217362. while (f != 0 && fgets (buf, sizeof(buf), f))
  217363. {
  217364. if (strncmp (buf, key, strlen (key)) == 0)
  217365. {
  217366. char* p = buf;
  217367. while (*p && *p != '\n')
  217368. ++p;
  217369. if (*p != 0)
  217370. *p = 0;
  217371. p = buf;
  217372. while (*p != 0 && *p != ':')
  217373. ++p;
  217374. if (*p != 0 && *(p + 1) != 0)
  217375. info = p + 2;
  217376. if (! lastOne)
  217377. break;
  217378. }
  217379. }
  217380. fclose (f);
  217381. return info;
  217382. }
  217383. bool SystemStats::hasMMX() throw()
  217384. {
  217385. return getCpuInfo ("flags").contains (T("mmx"));
  217386. }
  217387. bool SystemStats::hasSSE() throw()
  217388. {
  217389. return getCpuInfo ("flags").contains (T("sse"));
  217390. }
  217391. bool SystemStats::hasSSE2() throw()
  217392. {
  217393. return getCpuInfo ("flags").contains (T("sse2"));
  217394. }
  217395. bool SystemStats::has3DNow() throw()
  217396. {
  217397. return getCpuInfo ("flags").contains (T("3dnow"));
  217398. }
  217399. const String SystemStats::getCpuVendor() throw()
  217400. {
  217401. return getCpuInfo ("vendor_id");
  217402. }
  217403. int SystemStats::getCpuSpeedInMegaherz() throw()
  217404. {
  217405. const String speed (getCpuInfo ("cpu MHz"));
  217406. return (int) (speed.getFloatValue() + 0.5f);
  217407. }
  217408. int SystemStats::getMemorySizeInMegabytes() throw()
  217409. {
  217410. struct sysinfo sysi;
  217411. if (sysinfo (&sysi) == 0)
  217412. return (sysi.totalram * sysi.mem_unit / (1024 * 1024));
  217413. return 0;
  217414. }
  217415. uint32 juce_millisecondsSinceStartup() throw()
  217416. {
  217417. static unsigned int calibrate = 0;
  217418. static bool calibrated = false;
  217419. timeval t;
  217420. unsigned int ret = 0;
  217421. if (! gettimeofday (&t, 0))
  217422. {
  217423. if (! calibrated)
  217424. {
  217425. struct sysinfo sysi;
  217426. if (sysinfo (&sysi) == 0)
  217427. // Safe to assume system was not brought up earlier than 1970!
  217428. calibrate = t.tv_sec - sysi.uptime;
  217429. calibrated = true;
  217430. }
  217431. ret = 1000 * (t.tv_sec - calibrate) + (t.tv_usec / 1000);
  217432. }
  217433. return ret;
  217434. }
  217435. double Time::getMillisecondCounterHiRes() throw()
  217436. {
  217437. return getHighResolutionTicks() * 0.001;
  217438. }
  217439. int64 Time::getHighResolutionTicks() throw()
  217440. {
  217441. timeval t;
  217442. if (gettimeofday (&t, 0))
  217443. return 0;
  217444. return ((int64) t.tv_sec * (int64) 1000000) + (int64) t.tv_usec;
  217445. }
  217446. int64 Time::getHighResolutionTicksPerSecond() throw()
  217447. {
  217448. // Microseconds
  217449. return 1000000;
  217450. }
  217451. bool Time::setSystemTimeToThisTime() const throw()
  217452. {
  217453. timeval t;
  217454. t.tv_sec = millisSinceEpoch % 1000000;
  217455. t.tv_usec = millisSinceEpoch - t.tv_sec;
  217456. return settimeofday (&t, NULL) ? false : true;
  217457. }
  217458. int SystemStats::getPageSize() throw()
  217459. {
  217460. static int systemPageSize = 0;
  217461. if (systemPageSize == 0)
  217462. systemPageSize = sysconf (_SC_PAGESIZE);
  217463. return systemPageSize;
  217464. }
  217465. int SystemStats::getNumCpus() throw()
  217466. {
  217467. const int lastCpu = getCpuInfo ("processor", true).getIntValue();
  217468. return lastCpu + 1;
  217469. }
  217470. void SystemStats::initialiseStats() throw()
  217471. {
  217472. // Process starts off as root when running suid
  217473. Process::lowerPrivilege();
  217474. String s (SystemStats::getJUCEVersion());
  217475. }
  217476. void PlatformUtilities::fpuReset()
  217477. {
  217478. }
  217479. END_JUCE_NAMESPACE
  217480. /********* End of inlined file: juce_linux_SystemStats.cpp *********/
  217481. /********* Start of inlined file: juce_linux_Threads.cpp *********/
  217482. #include <dlfcn.h>
  217483. #include <sys/file.h>
  217484. #include <sys/types.h>
  217485. #include <sys/ptrace.h>
  217486. BEGIN_JUCE_NAMESPACE
  217487. /*
  217488. Note that a lot of methods that you'd expect to find in this file actually
  217489. live in juce_posix_SharedCode.h!
  217490. */
  217491. #ifndef CPU_ISSET
  217492. #undef SUPPORT_AFFINITIES
  217493. #endif
  217494. void JUCE_API juce_threadEntryPoint (void*);
  217495. void* threadEntryProc (void* value) throw()
  217496. {
  217497. // New threads start off as root when running suid
  217498. Process::lowerPrivilege();
  217499. juce_threadEntryPoint (value);
  217500. return 0;
  217501. }
  217502. void* juce_createThread (void* userData) throw()
  217503. {
  217504. pthread_t handle = 0;
  217505. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  217506. {
  217507. pthread_detach (handle);
  217508. return (void*)handle;
  217509. }
  217510. return 0;
  217511. }
  217512. void juce_killThread (void* handle) throw()
  217513. {
  217514. if (handle != 0)
  217515. pthread_cancel ((pthread_t)handle);
  217516. }
  217517. void juce_setCurrentThreadName (const String& /*name*/) throw()
  217518. {
  217519. }
  217520. int64 Thread::getCurrentThreadId() throw()
  217521. {
  217522. return pthread_self();
  217523. }
  217524. /*
  217525. * This is all a bit non-ideal... the trouble is that on Linux you
  217526. * need to call setpriority to affect the dynamic priority for
  217527. * non-realtime processes, but this requires the pid, which is not
  217528. * accessible from the pthread_t. We could get it by calling getpid
  217529. * once each thread has started, but then we would need a list of
  217530. * running threads etc etc.
  217531. * Also there is no such thing as IDLE priority on Linux.
  217532. * For the moment, map idle, low and normal process priorities to
  217533. * SCHED_OTHER, with the thread priority ignored for these classes.
  217534. * Map high priority processes to the lower half of the SCHED_RR
  217535. * range, and realtime to the upper half
  217536. */
  217537. // priority 1 to 10 where 5=normal, 1=low. If the handle is 0, sets the
  217538. // priority of the current thread
  217539. void juce_setThreadPriority (void* handle, int priority) throw()
  217540. {
  217541. struct sched_param param;
  217542. int policy, maxp, minp, pri;
  217543. if (handle == 0)
  217544. handle = (void*) pthread_self();
  217545. if (pthread_getschedparam ((pthread_t) handle, &policy, &param) == 0
  217546. && policy != SCHED_OTHER)
  217547. {
  217548. minp = sched_get_priority_min(policy);
  217549. maxp = sched_get_priority_max(policy);
  217550. pri = ((maxp - minp) / 2) * (priority - 1) / 9;
  217551. if (param.__sched_priority >= (minp + (maxp - minp) / 2))
  217552. // Realtime process priority
  217553. param.__sched_priority = minp + ((maxp - minp) / 2) + pri;
  217554. else
  217555. // High process priority
  217556. param.__sched_priority = minp + pri;
  217557. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  217558. pthread_setschedparam ((pthread_t) handle, policy, &param);
  217559. }
  217560. }
  217561. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  217562. {
  217563. #if SUPPORT_AFFINITIES
  217564. cpu_set_t affinity;
  217565. CPU_ZERO (&affinity);
  217566. for (int i = 0; i < 32; ++i)
  217567. if ((affinityMask & (1 << i)) != 0)
  217568. CPU_SET (i, &affinity);
  217569. /*
  217570. N.B. If this line causes a compile error, then you've probably not got the latest
  217571. version of glibc installed.
  217572. If you don't want to update your copy of glibc and don't care about cpu affinities,
  217573. then you can just disable all this stuff by removing the SUPPORT_AFFINITIES macro
  217574. from the linuxincludes.h file.
  217575. */
  217576. sched_setaffinity (getpid(), sizeof (cpu_set_t), &affinity);
  217577. sched_yield();
  217578. #else
  217579. /* affinities aren't supported because either the appropriate header files weren't found,
  217580. or the SUPPORT_AFFINITIES macro was turned off in linuxheaders.h
  217581. */
  217582. jassertfalse
  217583. #endif
  217584. }
  217585. void Thread::yield() throw()
  217586. {
  217587. sched_yield();
  217588. }
  217589. // sets the process to 0=low priority, 1=normal, 2=high, 3=realtime
  217590. void Process::setPriority (ProcessPriority prior)
  217591. {
  217592. struct sched_param param;
  217593. int policy, maxp, minp;
  217594. const int p = (int) prior;
  217595. if (p <= 1)
  217596. policy = SCHED_OTHER;
  217597. else
  217598. policy = SCHED_RR;
  217599. minp = sched_get_priority_min (policy);
  217600. maxp = sched_get_priority_max (policy);
  217601. if (p < 2)
  217602. param.__sched_priority = 0;
  217603. else if (p == 2 )
  217604. // Set to middle of lower realtime priority range
  217605. param.__sched_priority = minp + (maxp - minp) / 4;
  217606. else
  217607. // Set to middle of higher realtime priority range
  217608. param.__sched_priority = minp + (3 * (maxp - minp) / 4);
  217609. pthread_setschedparam (pthread_self(), policy, &param);
  217610. }
  217611. void Process::terminate()
  217612. {
  217613. exit (0);
  217614. }
  217615. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  217616. {
  217617. static char testResult = 0;
  217618. if (testResult == 0)
  217619. {
  217620. testResult = (char) ptrace (PT_TRACE_ME, 0, 0, 0);
  217621. if (testResult >= 0)
  217622. {
  217623. ptrace (PT_DETACH, 0, (caddr_t) 1, 0);
  217624. testResult = 1;
  217625. }
  217626. }
  217627. return testResult < 0;
  217628. }
  217629. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  217630. {
  217631. return juce_isRunningUnderDebugger();
  217632. }
  217633. void Process::raisePrivilege()
  217634. {
  217635. // If running suid root, change effective user
  217636. // to root
  217637. if (geteuid() != 0 && getuid() == 0)
  217638. {
  217639. setreuid (geteuid(), getuid());
  217640. setregid (getegid(), getgid());
  217641. }
  217642. }
  217643. void Process::lowerPrivilege()
  217644. {
  217645. // If runing suid root, change effective user
  217646. // back to real user
  217647. if (geteuid() == 0 && getuid() != 0)
  217648. {
  217649. setreuid (geteuid(), getuid());
  217650. setregid (getegid(), getgid());
  217651. }
  217652. }
  217653. #if JUCE_BUILD_GUI_CLASSES
  217654. void* PlatformUtilities::loadDynamicLibrary (const String& name)
  217655. {
  217656. return dlopen ((const char*) name.toUTF8(), RTLD_LOCAL | RTLD_NOW);
  217657. }
  217658. void PlatformUtilities::freeDynamicLibrary (void* handle)
  217659. {
  217660. dlclose(handle);
  217661. }
  217662. void* PlatformUtilities::getProcedureEntryPoint (void* libraryHandle, const String& procedureName)
  217663. {
  217664. return dlsym (libraryHandle, (const char*) procedureName);
  217665. }
  217666. #endif
  217667. END_JUCE_NAMESPACE
  217668. /********* End of inlined file: juce_linux_Threads.cpp *********/
  217669. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  217670. /********* Start of inlined file: juce_linux_Audio.cpp *********/
  217671. /********* Start of inlined file: juce_Config.h *********/
  217672. #ifndef __JUCE_CONFIG_JUCEHEADER__
  217673. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  217674. /*
  217675. This file contains macros that enable/disable various JUCE features.
  217676. */
  217677. /** The name of the namespace that all Juce classes and functions will be
  217678. put inside. If this is not defined, no namespace will be used.
  217679. */
  217680. #ifndef JUCE_NAMESPACE
  217681. #define JUCE_NAMESPACE juce
  217682. #endif
  217683. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  217684. but if you define this value, you can override this can force it to be true or
  217685. false.
  217686. */
  217687. #ifndef JUCE_FORCE_DEBUG
  217688. //#define JUCE_FORCE_DEBUG 1
  217689. #endif
  217690. /** If this flag is enabled, the the jassert and jassertfalse macros will
  217691. always use Logger::writeToLog() to write a message when an assertion happens.
  217692. Enabling it will also leave this turned on in release builds. When it's disabled,
  217693. however, the jassert and jassertfalse macros will not be compiled in a
  217694. release build.
  217695. @see jassert, jassertfalse, Logger
  217696. */
  217697. #ifndef JUCE_LOG_ASSERTIONS
  217698. // #define JUCE_LOG_ASSERTIONS 1
  217699. #endif
  217700. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  217701. which the ASIOAudioIODevice class can't be built. See the comments in the
  217702. ASIOAudioIODevice class's header file for more info about this.
  217703. (This only affects a Win32 build)
  217704. */
  217705. #ifndef JUCE_ASIO
  217706. #define JUCE_ASIO 1
  217707. #endif
  217708. /** Comment out this macro to disable building of ALSA device support on Linux.
  217709. */
  217710. #ifndef JUCE_ALSA
  217711. #define JUCE_ALSA 1
  217712. #endif
  217713. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  217714. have the SDK installed.
  217715. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  217716. classes will be unavailable.
  217717. On Windows, if you enable this, you'll need to have the QuickTime SDK
  217718. installed, and its header files will need to be on your include path.
  217719. */
  217720. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  217721. #define JUCE_QUICKTIME 1
  217722. #endif
  217723. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  217724. have the appropriate headers and libraries available. If it's not enabled, the
  217725. OpenGLComponent class will be unavailable.
  217726. */
  217727. #ifndef JUCE_OPENGL
  217728. #define JUCE_OPENGL 1
  217729. #endif
  217730. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  217731. If you're not going to need either of these formats, turn off the flags to
  217732. avoid bloating your codebase with them.
  217733. */
  217734. #ifndef JUCE_USE_FLAC
  217735. #define JUCE_USE_FLAC 1
  217736. #endif
  217737. #ifndef JUCE_USE_OGGVORBIS
  217738. #define JUCE_USE_OGGVORBIS 1
  217739. #endif
  217740. /** This flag lets you enable support for CD-burning. You might want to disable
  217741. it to build without the MS SDK under windows.
  217742. */
  217743. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  217744. #define JUCE_USE_CDBURNER 1
  217745. #endif
  217746. /** Enabling this macro means that all regions that get repainted will have a coloured
  217747. line drawn around them.
  217748. This is handy if you're trying to optimise drawing, because it lets you easily see
  217749. when anything is being repainted unnecessarily.
  217750. */
  217751. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  217752. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  217753. #endif
  217754. /** Enable this under Linux to use Xinerama for multi-monitor support.
  217755. */
  217756. #ifndef JUCE_USE_XINERAMA
  217757. #define JUCE_USE_XINERAMA 1
  217758. #endif
  217759. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  217760. */
  217761. #ifndef JUCE_USE_XSHM
  217762. #define JUCE_USE_XSHM 1
  217763. #endif
  217764. /** Enabling this builds support for VST audio plugins.
  217765. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  217766. */
  217767. #ifndef JUCE_PLUGINHOST_VST
  217768. // #define JUCE_PLUGINHOST_VST 1
  217769. #endif
  217770. /** Enabling this builds support for AudioUnit audio plugins.
  217771. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  217772. */
  217773. #ifndef JUCE_PLUGINHOST_AU
  217774. // #define JUCE_PLUGINHOST_AU 1
  217775. #endif
  217776. /** Disabling this will avoid linking to any UI code. This is handy for
  217777. writing command-line utilities, e.g. on linux boxes which don't have some
  217778. of the UI libraries installed.
  217779. (On mac and windows, this won't generally make much difference to the build).
  217780. */
  217781. #ifndef JUCE_BUILD_GUI_CLASSES
  217782. #define JUCE_BUILD_GUI_CLASSES 1
  217783. #endif
  217784. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  217785. */
  217786. #ifndef JUCE_WEB_BROWSER
  217787. #define JUCE_WEB_BROWSER 1
  217788. #endif
  217789. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  217790. codebase - you might need to use this if you're linking to some of these libraries
  217791. yourself.
  217792. */
  217793. #ifndef JUCE_INCLUDE_ZLIB_CODE
  217794. #define JUCE_INCLUDE_ZLIB_CODE 1
  217795. #endif
  217796. #ifndef JUCE_INCLUDE_FLAC_CODE
  217797. #define JUCE_INCLUDE_FLAC_CODE 1
  217798. #endif
  217799. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  217800. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  217801. #endif
  217802. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  217803. #define JUCE_INCLUDE_PNGLIB_CODE 1
  217804. #endif
  217805. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  217806. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  217807. #endif
  217808. /** Enable this to add extra memory-leak info to the new and delete operators.
  217809. (Currently, this only affects Windows builds in debug mode).
  217810. */
  217811. #ifndef JUCE_CHECK_MEMORY_LEAKS
  217812. #define JUCE_CHECK_MEMORY_LEAKS 1
  217813. #endif
  217814. /** Enable this to turn on juce's internal catching of exceptions.
  217815. Turning it off will avoid any exception catching. With it on, all exceptions
  217816. are passed to the JUCEApplication::unhandledException() callback for logging.
  217817. */
  217818. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  217819. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  217820. #endif
  217821. /** If this macro is set, the Juce String class will use unicode as its
  217822. internal representation. If it isn't set, it'll use ANSI.
  217823. */
  217824. #ifndef JUCE_STRINGS_ARE_UNICODE
  217825. #define JUCE_STRINGS_ARE_UNICODE 1
  217826. #endif
  217827. #endif
  217828. /********* End of inlined file: juce_Config.h *********/
  217829. #if JUCE_BUILD_GUI_CLASSES
  217830. #if JUCE_ALSA
  217831. /* Got an include error here? If so, you've either not got ALSA installed, or you've
  217832. not got your paths set up correctly to find its header files.
  217833. The package you need to install to get ASLA support is "libasound2-dev".
  217834. If you don't have the ALSA library and don't want to build Juce with audio support,
  217835. just disable the JUCE_ALSA flag in juce_Config.h
  217836. */
  217837. #include <alsa/asoundlib.h>
  217838. BEGIN_JUCE_NAMESPACE
  217839. static const int maxNumChans = 64;
  217840. static void getDeviceSampleRates (snd_pcm_t* handle, Array <int>& rates)
  217841. {
  217842. const int ratesToTry[] = { 22050, 32000, 44100, 48000, 88200, 96000, 176400, 192000, 0 };
  217843. snd_pcm_hw_params_t* hwParams;
  217844. snd_pcm_hw_params_alloca (&hwParams);
  217845. for (int i = 0; ratesToTry[i] != 0; ++i)
  217846. {
  217847. if (snd_pcm_hw_params_any (handle, hwParams) >= 0
  217848. && snd_pcm_hw_params_test_rate (handle, hwParams, ratesToTry[i], 0) == 0)
  217849. {
  217850. rates.addIfNotAlreadyThere (ratesToTry[i]);
  217851. }
  217852. }
  217853. }
  217854. static void getDeviceNumChannels (snd_pcm_t* handle, unsigned int* minChans, unsigned int* maxChans)
  217855. {
  217856. snd_pcm_hw_params_t *params;
  217857. snd_pcm_hw_params_alloca (&params);
  217858. if (snd_pcm_hw_params_any (handle, params) >= 0)
  217859. {
  217860. snd_pcm_hw_params_get_channels_min (params, minChans);
  217861. snd_pcm_hw_params_get_channels_max (params, maxChans);
  217862. }
  217863. }
  217864. static void getDeviceProperties (const String& id,
  217865. unsigned int& minChansOut,
  217866. unsigned int& maxChansOut,
  217867. unsigned int& minChansIn,
  217868. unsigned int& maxChansIn,
  217869. Array <int>& rates)
  217870. {
  217871. if (id.isEmpty())
  217872. return;
  217873. snd_ctl_t* handle;
  217874. if (snd_ctl_open (&handle, id.upToLastOccurrenceOf (T(","), false, false), SND_CTL_NONBLOCK) >= 0)
  217875. {
  217876. snd_pcm_info_t* info;
  217877. snd_pcm_info_alloca (&info);
  217878. snd_pcm_info_set_stream (info, SND_PCM_STREAM_PLAYBACK);
  217879. snd_pcm_info_set_device (info, id.fromLastOccurrenceOf (T(","), false, false).getIntValue());
  217880. snd_pcm_info_set_subdevice (info, 0);
  217881. if (snd_ctl_pcm_info (handle, info) >= 0)
  217882. {
  217883. snd_pcm_t* pcmHandle;
  217884. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_PLAYBACK, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  217885. {
  217886. getDeviceNumChannels (pcmHandle, &minChansOut, &maxChansOut);
  217887. getDeviceSampleRates (pcmHandle, rates);
  217888. snd_pcm_close (pcmHandle);
  217889. }
  217890. }
  217891. snd_pcm_info_set_stream (info, SND_PCM_STREAM_CAPTURE);
  217892. if (snd_ctl_pcm_info (handle, info) >= 0)
  217893. {
  217894. snd_pcm_t* pcmHandle;
  217895. if (snd_pcm_open (&pcmHandle, id, SND_PCM_STREAM_CAPTURE, SND_PCM_ASYNC | SND_PCM_NONBLOCK ) >= 0)
  217896. {
  217897. getDeviceNumChannels (pcmHandle, &minChansIn, &maxChansIn);
  217898. if (rates.size() == 0)
  217899. getDeviceSampleRates (pcmHandle, rates);
  217900. snd_pcm_close (pcmHandle);
  217901. }
  217902. }
  217903. snd_ctl_close (handle);
  217904. }
  217905. }
  217906. class ALSADevice
  217907. {
  217908. public:
  217909. ALSADevice (const String& id,
  217910. const bool forInput)
  217911. : handle (0),
  217912. bitDepth (16),
  217913. numChannelsRunning (0),
  217914. isInput (forInput),
  217915. sampleFormat (AudioDataConverters::int16LE)
  217916. {
  217917. failed (snd_pcm_open (&handle, id,
  217918. forInput ? SND_PCM_STREAM_CAPTURE : SND_PCM_STREAM_PLAYBACK,
  217919. SND_PCM_ASYNC));
  217920. }
  217921. ~ALSADevice()
  217922. {
  217923. if (handle != 0)
  217924. snd_pcm_close (handle);
  217925. }
  217926. bool setParameters (unsigned int sampleRate, int numChannels, int bufferSize)
  217927. {
  217928. if (handle == 0)
  217929. return false;
  217930. snd_pcm_hw_params_t* hwParams;
  217931. snd_pcm_hw_params_alloca (&hwParams);
  217932. if (failed (snd_pcm_hw_params_any (handle, hwParams)))
  217933. return false;
  217934. if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_NONINTERLEAVED) >= 0)
  217935. isInterleaved = false;
  217936. else if (snd_pcm_hw_params_set_access (handle, hwParams, SND_PCM_ACCESS_RW_INTERLEAVED) >= 0)
  217937. isInterleaved = true;
  217938. else
  217939. {
  217940. jassertfalse
  217941. return false;
  217942. }
  217943. const int formatsToTry[] = { SND_PCM_FORMAT_FLOAT_LE, 32, AudioDataConverters::float32LE,
  217944. SND_PCM_FORMAT_FLOAT_BE, 32, AudioDataConverters::float32BE,
  217945. SND_PCM_FORMAT_S32_LE, 32, AudioDataConverters::int32LE,
  217946. SND_PCM_FORMAT_S32_BE, 32, AudioDataConverters::int32BE,
  217947. SND_PCM_FORMAT_S24_LE, 24, AudioDataConverters::int24LE,
  217948. SND_PCM_FORMAT_S24_BE, 24, AudioDataConverters::int24BE,
  217949. SND_PCM_FORMAT_S16_LE, 16, AudioDataConverters::int16LE,
  217950. SND_PCM_FORMAT_S16_BE, 16, AudioDataConverters::int16BE };
  217951. bitDepth = 0;
  217952. for (int i = 0; i < numElementsInArray (formatsToTry); i += 3)
  217953. {
  217954. if (snd_pcm_hw_params_set_format (handle, hwParams, (_snd_pcm_format) formatsToTry [i]) >= 0)
  217955. {
  217956. bitDepth = formatsToTry [i + 1];
  217957. sampleFormat = (AudioDataConverters::DataFormat) formatsToTry [i + 2];
  217958. break;
  217959. }
  217960. }
  217961. if (bitDepth == 0)
  217962. {
  217963. error = "device doesn't support a compatible PCM format";
  217964. DBG (T("ALSA error: ") + error + T("\n"));
  217965. return false;
  217966. }
  217967. int dir = 0;
  217968. unsigned int periods = 4;
  217969. snd_pcm_uframes_t samplesPerPeriod = bufferSize;
  217970. if (failed (snd_pcm_hw_params_set_rate_near (handle, hwParams, &sampleRate, 0))
  217971. || failed (snd_pcm_hw_params_set_channels (handle, hwParams, numChannels))
  217972. || failed (snd_pcm_hw_params_set_periods_near (handle, hwParams, &periods, &dir))
  217973. || failed (snd_pcm_hw_params_set_period_size_near (handle, hwParams, &samplesPerPeriod, &dir))
  217974. || failed (snd_pcm_hw_params (handle, hwParams)))
  217975. {
  217976. return false;
  217977. }
  217978. snd_pcm_sw_params_t* swParams;
  217979. snd_pcm_sw_params_alloca (&swParams);
  217980. if (failed (snd_pcm_sw_params_current (handle, swParams))
  217981. || failed (snd_pcm_sw_params_set_silence_threshold (handle, swParams, 0))
  217982. || failed (snd_pcm_sw_params_set_silence_size (handle, swParams, 0))
  217983. || failed (snd_pcm_sw_params_set_start_threshold (handle, swParams, samplesPerPeriod))
  217984. || failed (snd_pcm_sw_params_set_stop_threshold (handle, swParams, INT_MAX))
  217985. || failed (snd_pcm_sw_params (handle, swParams)))
  217986. {
  217987. return false;
  217988. }
  217989. /*
  217990. #ifdef JUCE_DEBUG
  217991. // enable this to dump the config of the devices that get opened
  217992. snd_output_t* out;
  217993. snd_output_stdio_attach (&out, stderr, 0);
  217994. snd_pcm_hw_params_dump (hwParams, out);
  217995. snd_pcm_sw_params_dump (swParams, out);
  217996. #endif
  217997. */
  217998. numChannelsRunning = numChannels;
  217999. return true;
  218000. }
  218001. bool write (float** const data, const int numSamples)
  218002. {
  218003. if (isInterleaved)
  218004. {
  218005. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  218006. float* interleaved = (float*) scratch;
  218007. AudioDataConverters::interleaveSamples ((const float**) data, interleaved, numSamples, numChannelsRunning);
  218008. AudioDataConverters::convertFloatToFormat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  218009. snd_pcm_sframes_t num = snd_pcm_writei (handle, (void*) interleaved, numSamples);
  218010. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  218011. return false;
  218012. }
  218013. else
  218014. {
  218015. for (int i = 0; i < numChannelsRunning; ++i)
  218016. if (data[i] != 0)
  218017. AudioDataConverters::convertFloatToFormat (sampleFormat, data[i], data[i], numSamples);
  218018. snd_pcm_sframes_t num = snd_pcm_writen (handle, (void**) data, numSamples);
  218019. if (failed (num))
  218020. {
  218021. if (num == -EPIPE)
  218022. {
  218023. if (failed (snd_pcm_prepare (handle)))
  218024. return false;
  218025. }
  218026. else if (num != -ESTRPIPE)
  218027. return false;
  218028. }
  218029. }
  218030. return true;
  218031. }
  218032. bool read (float** const data, const int numSamples)
  218033. {
  218034. if (isInterleaved)
  218035. {
  218036. scratch.ensureSize (sizeof (float) * numSamples * numChannelsRunning, false);
  218037. float* interleaved = (float*) scratch;
  218038. snd_pcm_sframes_t num = snd_pcm_readi (handle, (void*) interleaved, numSamples);
  218039. if (failed (num))
  218040. {
  218041. if (num == -EPIPE)
  218042. {
  218043. if (failed (snd_pcm_prepare (handle)))
  218044. return false;
  218045. }
  218046. else if (num != -ESTRPIPE)
  218047. return false;
  218048. }
  218049. AudioDataConverters::convertFormatToFloat (sampleFormat, interleaved, interleaved, numSamples * numChannelsRunning);
  218050. AudioDataConverters::deinterleaveSamples (interleaved, data, numSamples, numChannelsRunning);
  218051. }
  218052. else
  218053. {
  218054. snd_pcm_sframes_t num = snd_pcm_readn (handle, (void**) data, numSamples);
  218055. if (failed (num) && num != -EPIPE && num != -ESTRPIPE)
  218056. return false;
  218057. for (int i = 0; i < numChannelsRunning; ++i)
  218058. if (data[i] != 0)
  218059. AudioDataConverters::convertFormatToFloat (sampleFormat, data[i], data[i], numSamples);
  218060. }
  218061. return true;
  218062. }
  218063. juce_UseDebuggingNewOperator
  218064. snd_pcm_t* handle;
  218065. String error;
  218066. int bitDepth, numChannelsRunning;
  218067. private:
  218068. const bool isInput;
  218069. bool isInterleaved;
  218070. MemoryBlock scratch;
  218071. AudioDataConverters::DataFormat sampleFormat;
  218072. bool failed (const int errorNum)
  218073. {
  218074. if (errorNum >= 0)
  218075. return false;
  218076. error = snd_strerror (errorNum);
  218077. DBG (T("ALSA error: ") + error + T("\n"));
  218078. return true;
  218079. }
  218080. };
  218081. class ALSAThread : public Thread
  218082. {
  218083. public:
  218084. ALSAThread (const String& inputId_,
  218085. const String& outputId_)
  218086. : Thread ("Juce ALSA"),
  218087. sampleRate (0),
  218088. bufferSize (0),
  218089. callback (0),
  218090. inputId (inputId_),
  218091. outputId (outputId_),
  218092. outputDevice (0),
  218093. inputDevice (0),
  218094. numCallbacks (0),
  218095. totalNumInputChannels (0),
  218096. totalNumOutputChannels (0)
  218097. {
  218098. zeromem (outputChannelData, sizeof (outputChannelData));
  218099. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  218100. zeromem (inputChannelData, sizeof (inputChannelData));
  218101. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  218102. initialiseRatesAndChannels();
  218103. }
  218104. ~ALSAThread()
  218105. {
  218106. close();
  218107. }
  218108. void open (const BitArray& inputChannels,
  218109. const BitArray& outputChannels,
  218110. const double sampleRate_,
  218111. const int bufferSize_)
  218112. {
  218113. close();
  218114. error = String::empty;
  218115. sampleRate = sampleRate_;
  218116. bufferSize = bufferSize_;
  218117. currentInputChans.clear();
  218118. currentOutputChans.clear();
  218119. if (inputChannels.getHighestBit() >= 0)
  218120. {
  218121. for (int i = 0; i <= inputChannels.getHighestBit(); ++i)
  218122. {
  218123. inputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  218124. if (inputChannels[i])
  218125. {
  218126. inputChannelDataForCallback [totalNumInputChannels++] = inputChannelData [i];
  218127. currentInputChans.setBit (i);
  218128. }
  218129. }
  218130. }
  218131. if (outputChannels.getHighestBit() >= 0)
  218132. {
  218133. for (int i = 0; i <= outputChannels.getHighestBit(); ++i)
  218134. {
  218135. outputChannelData [i] = (float*) juce_calloc (sizeof (float) * bufferSize);
  218136. if (outputChannels[i])
  218137. {
  218138. outputChannelDataForCallback [totalNumOutputChannels++] = outputChannelData [i];
  218139. currentOutputChans.setBit (i);
  218140. }
  218141. }
  218142. }
  218143. if (totalNumOutputChannels > 0 && outputId.isNotEmpty())
  218144. {
  218145. outputDevice = new ALSADevice (outputId, false);
  218146. if (outputDevice->error.isNotEmpty())
  218147. {
  218148. error = outputDevice->error;
  218149. deleteAndZero (outputDevice);
  218150. return;
  218151. }
  218152. if (! outputDevice->setParameters ((unsigned int) sampleRate,
  218153. currentOutputChans.getHighestBit() + 1,
  218154. bufferSize))
  218155. {
  218156. error = outputDevice->error;
  218157. deleteAndZero (outputDevice);
  218158. return;
  218159. }
  218160. }
  218161. if (totalNumInputChannels > 0 && inputId.isNotEmpty())
  218162. {
  218163. inputDevice = new ALSADevice (inputId, true);
  218164. if (inputDevice->error.isNotEmpty())
  218165. {
  218166. error = inputDevice->error;
  218167. deleteAndZero (inputDevice);
  218168. return;
  218169. }
  218170. if (! inputDevice->setParameters ((unsigned int) sampleRate,
  218171. currentInputChans.getHighestBit() + 1,
  218172. bufferSize))
  218173. {
  218174. error = inputDevice->error;
  218175. deleteAndZero (inputDevice);
  218176. return;
  218177. }
  218178. }
  218179. if (outputDevice == 0 && inputDevice == 0)
  218180. {
  218181. error = "no channels";
  218182. return;
  218183. }
  218184. if (outputDevice != 0 && inputDevice != 0)
  218185. {
  218186. snd_pcm_link (outputDevice->handle, inputDevice->handle);
  218187. }
  218188. if (inputDevice != 0 && failed (snd_pcm_prepare (inputDevice->handle)))
  218189. return;
  218190. if (outputDevice != 0 && failed (snd_pcm_prepare (outputDevice->handle)))
  218191. return;
  218192. startThread (9);
  218193. int count = 1000;
  218194. while (numCallbacks == 0)
  218195. {
  218196. sleep (5);
  218197. if (--count < 0 || ! isThreadRunning())
  218198. {
  218199. error = "device didn't start";
  218200. break;
  218201. }
  218202. }
  218203. }
  218204. void close()
  218205. {
  218206. stopThread (6000);
  218207. deleteAndZero (inputDevice);
  218208. deleteAndZero (outputDevice);
  218209. for (int i = 0; i < maxNumChans; ++i)
  218210. {
  218211. juce_free (inputChannelData [i]);
  218212. juce_free (outputChannelData [i]);
  218213. }
  218214. zeromem (outputChannelData, sizeof (outputChannelData));
  218215. zeromem (outputChannelDataForCallback, sizeof (outputChannelDataForCallback));
  218216. zeromem (inputChannelData, sizeof (inputChannelData));
  218217. zeromem (inputChannelDataForCallback, sizeof (inputChannelDataForCallback));
  218218. totalNumOutputChannels = 0;
  218219. totalNumInputChannels = 0;
  218220. numCallbacks = 0;
  218221. }
  218222. void setCallback (AudioIODeviceCallback* const newCallback) throw()
  218223. {
  218224. const ScopedLock sl (callbackLock);
  218225. callback = newCallback;
  218226. }
  218227. void run()
  218228. {
  218229. while (! threadShouldExit())
  218230. {
  218231. if (inputDevice != 0)
  218232. {
  218233. if (! inputDevice->read (inputChannelData, bufferSize))
  218234. {
  218235. DBG ("ALSA: read failure");
  218236. break;
  218237. }
  218238. }
  218239. if (threadShouldExit())
  218240. break;
  218241. {
  218242. const ScopedLock sl (callbackLock);
  218243. ++numCallbacks;
  218244. if (callback != 0)
  218245. {
  218246. callback->audioDeviceIOCallback ((const float**) inputChannelDataForCallback,
  218247. totalNumInputChannels,
  218248. outputChannelDataForCallback,
  218249. totalNumOutputChannels,
  218250. bufferSize);
  218251. }
  218252. else
  218253. {
  218254. for (int i = 0; i < totalNumOutputChannels; ++i)
  218255. zeromem (outputChannelDataForCallback[i], sizeof (float) * bufferSize);
  218256. }
  218257. }
  218258. if (outputDevice != 0)
  218259. {
  218260. failed (snd_pcm_wait (outputDevice->handle, 2000));
  218261. if (threadShouldExit())
  218262. break;
  218263. failed (snd_pcm_avail_update (outputDevice->handle));
  218264. if (! outputDevice->write (outputChannelData, bufferSize))
  218265. {
  218266. DBG ("ALSA: write failure");
  218267. break;
  218268. }
  218269. }
  218270. }
  218271. }
  218272. int getBitDepth() const throw()
  218273. {
  218274. if (outputDevice != 0)
  218275. return outputDevice->bitDepth;
  218276. if (inputDevice != 0)
  218277. return inputDevice->bitDepth;
  218278. return 16;
  218279. }
  218280. juce_UseDebuggingNewOperator
  218281. String error;
  218282. double sampleRate;
  218283. int bufferSize;
  218284. BitArray currentInputChans, currentOutputChans;
  218285. Array <int> sampleRates;
  218286. StringArray channelNamesOut, channelNamesIn;
  218287. AudioIODeviceCallback* callback;
  218288. private:
  218289. const String inputId, outputId;
  218290. ALSADevice* outputDevice;
  218291. ALSADevice* inputDevice;
  218292. int numCallbacks;
  218293. CriticalSection callbackLock;
  218294. float* outputChannelData [maxNumChans];
  218295. float* outputChannelDataForCallback [maxNumChans];
  218296. int totalNumInputChannels;
  218297. float* inputChannelData [maxNumChans];
  218298. float* inputChannelDataForCallback [maxNumChans];
  218299. int totalNumOutputChannels;
  218300. unsigned int minChansOut, maxChansOut;
  218301. unsigned int minChansIn, maxChansIn;
  218302. bool failed (const int errorNum) throw()
  218303. {
  218304. if (errorNum >= 0)
  218305. return false;
  218306. error = snd_strerror (errorNum);
  218307. DBG (T("ALSA error: ") + error + T("\n"));
  218308. return true;
  218309. }
  218310. void initialiseRatesAndChannels() throw()
  218311. {
  218312. sampleRates.clear();
  218313. channelNamesOut.clear();
  218314. channelNamesIn.clear();
  218315. minChansOut = 0;
  218316. maxChansOut = 0;
  218317. minChansIn = 0;
  218318. maxChansIn = 0;
  218319. unsigned int dummy = 0;
  218320. getDeviceProperties (inputId, dummy, dummy, minChansIn, maxChansIn, sampleRates);
  218321. getDeviceProperties (outputId, minChansOut, maxChansOut, dummy, dummy, sampleRates);
  218322. unsigned int i;
  218323. for (i = 0; i < maxChansOut; ++i)
  218324. channelNamesOut.add (T("channel ") + String ((int) i + 1));
  218325. for (i = 0; i < maxChansIn; ++i)
  218326. channelNamesIn.add (T("channel ") + String ((int) i + 1));
  218327. }
  218328. };
  218329. class ALSAAudioIODevice : public AudioIODevice
  218330. {
  218331. public:
  218332. ALSAAudioIODevice (const String& deviceName,
  218333. const String& inputId_,
  218334. const String& outputId_)
  218335. : AudioIODevice (deviceName, T("ALSA")),
  218336. inputId (inputId_),
  218337. outputId (outputId_),
  218338. isOpen_ (false),
  218339. isStarted (false),
  218340. internal (0)
  218341. {
  218342. internal = new ALSAThread (inputId, outputId);
  218343. }
  218344. ~ALSAAudioIODevice()
  218345. {
  218346. delete internal;
  218347. }
  218348. const StringArray getOutputChannelNames()
  218349. {
  218350. return internal->channelNamesOut;
  218351. }
  218352. const StringArray getInputChannelNames()
  218353. {
  218354. return internal->channelNamesIn;
  218355. }
  218356. int getNumSampleRates()
  218357. {
  218358. return internal->sampleRates.size();
  218359. }
  218360. double getSampleRate (int index)
  218361. {
  218362. return internal->sampleRates [index];
  218363. }
  218364. int getNumBufferSizesAvailable()
  218365. {
  218366. return 50;
  218367. }
  218368. int getBufferSizeSamples (int index)
  218369. {
  218370. int n = 16;
  218371. for (int i = 0; i < index; ++i)
  218372. n += n < 64 ? 16
  218373. : (n < 512 ? 32
  218374. : (n < 1024 ? 64
  218375. : (n < 2048 ? 128 : 256)));
  218376. return n;
  218377. }
  218378. int getDefaultBufferSize()
  218379. {
  218380. return 512;
  218381. }
  218382. const String open (const BitArray& inputChannels,
  218383. const BitArray& outputChannels,
  218384. double sampleRate,
  218385. int bufferSizeSamples)
  218386. {
  218387. close();
  218388. if (bufferSizeSamples <= 0)
  218389. bufferSizeSamples = getDefaultBufferSize();
  218390. if (sampleRate <= 0)
  218391. {
  218392. for (int i = 0; i < getNumSampleRates(); ++i)
  218393. {
  218394. if (getSampleRate (i) >= 44100)
  218395. {
  218396. sampleRate = getSampleRate (i);
  218397. break;
  218398. }
  218399. }
  218400. }
  218401. internal->open (inputChannels, outputChannels,
  218402. sampleRate, bufferSizeSamples);
  218403. isOpen_ = internal->error.isEmpty();
  218404. return internal->error;
  218405. }
  218406. void close()
  218407. {
  218408. stop();
  218409. internal->close();
  218410. isOpen_ = false;
  218411. }
  218412. bool isOpen()
  218413. {
  218414. return isOpen_;
  218415. }
  218416. int getCurrentBufferSizeSamples()
  218417. {
  218418. return internal->bufferSize;
  218419. }
  218420. double getCurrentSampleRate()
  218421. {
  218422. return internal->sampleRate;
  218423. }
  218424. int getCurrentBitDepth()
  218425. {
  218426. return internal->getBitDepth();
  218427. }
  218428. const BitArray getActiveOutputChannels() const
  218429. {
  218430. return internal->currentOutputChans;
  218431. }
  218432. const BitArray getActiveInputChannels() const
  218433. {
  218434. return internal->currentInputChans;
  218435. }
  218436. int getOutputLatencyInSamples()
  218437. {
  218438. return 0;
  218439. }
  218440. int getInputLatencyInSamples()
  218441. {
  218442. return 0;
  218443. }
  218444. void start (AudioIODeviceCallback* callback)
  218445. {
  218446. if (! isOpen_)
  218447. callback = 0;
  218448. internal->setCallback (callback);
  218449. if (callback != 0)
  218450. callback->audioDeviceAboutToStart (this);
  218451. isStarted = (callback != 0);
  218452. }
  218453. void stop()
  218454. {
  218455. AudioIODeviceCallback* const oldCallback = internal->callback;
  218456. start (0);
  218457. if (oldCallback != 0)
  218458. oldCallback->audioDeviceStopped();
  218459. }
  218460. bool isPlaying()
  218461. {
  218462. return isStarted && internal->error.isEmpty();
  218463. }
  218464. const String getLastError()
  218465. {
  218466. return internal->error;
  218467. }
  218468. String inputId, outputId;
  218469. private:
  218470. bool isOpen_, isStarted;
  218471. ALSAThread* internal;
  218472. };
  218473. class ALSAAudioIODeviceType : public AudioIODeviceType
  218474. {
  218475. public:
  218476. ALSAAudioIODeviceType()
  218477. : AudioIODeviceType (T("ALSA")),
  218478. hasScanned (false)
  218479. {
  218480. }
  218481. ~ALSAAudioIODeviceType()
  218482. {
  218483. }
  218484. void scanForDevices()
  218485. {
  218486. if (hasScanned)
  218487. return;
  218488. hasScanned = true;
  218489. inputNames.clear();
  218490. inputIds.clear();
  218491. outputNames.clear();
  218492. outputIds.clear();
  218493. snd_ctl_t* handle;
  218494. snd_ctl_card_info_t* info;
  218495. snd_ctl_card_info_alloca (&info);
  218496. int cardNum = -1;
  218497. while (outputIds.size() + inputIds.size() <= 32)
  218498. {
  218499. snd_card_next (&cardNum);
  218500. if (cardNum < 0)
  218501. break;
  218502. if (snd_ctl_open (&handle, T("hw:") + String (cardNum), SND_CTL_NONBLOCK) >= 0)
  218503. {
  218504. if (snd_ctl_card_info (handle, info) >= 0)
  218505. {
  218506. String cardId (snd_ctl_card_info_get_id (info));
  218507. if (cardId.removeCharacters (T("0123456789")).isEmpty())
  218508. cardId = String (cardNum);
  218509. int device = -1;
  218510. for (;;)
  218511. {
  218512. if (snd_ctl_pcm_next_device (handle, &device) < 0 || device < 0)
  218513. break;
  218514. String id, name;
  218515. id << "hw:" << cardId << ',' << device;
  218516. bool isInput, isOutput;
  218517. if (testDevice (id, isInput, isOutput))
  218518. {
  218519. name << snd_ctl_card_info_get_name (info);
  218520. if (name.isEmpty())
  218521. name = id;
  218522. if (isInput)
  218523. {
  218524. inputNames.add (name);
  218525. inputIds.add (id);
  218526. }
  218527. if (isOutput)
  218528. {
  218529. outputNames.add (name);
  218530. outputIds.add (id);
  218531. }
  218532. }
  218533. }
  218534. }
  218535. snd_ctl_close (handle);
  218536. }
  218537. }
  218538. inputNames.appendNumbersToDuplicates (false, true);
  218539. outputNames.appendNumbersToDuplicates (false, true);
  218540. }
  218541. const StringArray getDeviceNames (const bool wantInputNames) const
  218542. {
  218543. jassert (hasScanned); // need to call scanForDevices() before doing this
  218544. return wantInputNames ? inputNames : outputNames;
  218545. }
  218546. int getDefaultDeviceIndex (const bool forInput) const
  218547. {
  218548. jassert (hasScanned); // need to call scanForDevices() before doing this
  218549. return 0;
  218550. }
  218551. bool hasSeparateInputsAndOutputs() const { return true; }
  218552. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  218553. {
  218554. jassert (hasScanned); // need to call scanForDevices() before doing this
  218555. ALSAAudioIODevice* const d = dynamic_cast <ALSAAudioIODevice*> (device);
  218556. if (d == 0)
  218557. return -1;
  218558. return asInput ? inputIds.indexOf (d->inputId)
  218559. : outputIds.indexOf (d->outputId);
  218560. }
  218561. AudioIODevice* createDevice (const String& outputDeviceName,
  218562. const String& inputDeviceName)
  218563. {
  218564. jassert (hasScanned); // need to call scanForDevices() before doing this
  218565. const int inputIndex = inputNames.indexOf (inputDeviceName);
  218566. const int outputIndex = outputNames.indexOf (outputDeviceName);
  218567. String deviceName (outputDeviceName);
  218568. if (deviceName.isEmpty())
  218569. deviceName = inputDeviceName;
  218570. if (index >= 0)
  218571. return new ALSAAudioIODevice (deviceName,
  218572. inputIds [inputIndex],
  218573. outputIds [outputIndex]);
  218574. return 0;
  218575. }
  218576. juce_UseDebuggingNewOperator
  218577. private:
  218578. StringArray inputNames, outputNames, inputIds, outputIds;
  218579. bool hasScanned;
  218580. static bool testDevice (const String& id, bool& isInput, bool& isOutput)
  218581. {
  218582. unsigned int minChansOut = 0, maxChansOut = 0;
  218583. unsigned int minChansIn = 0, maxChansIn = 0;
  218584. Array <int> rates;
  218585. getDeviceProperties (id, minChansOut, maxChansOut, minChansIn, maxChansIn, rates);
  218586. DBG (T("ALSA device: ") + id
  218587. + T(" outs=") + String ((int) minChansOut) + T("-") + String ((int) maxChansOut)
  218588. + T(" ins=") + String ((int) minChansIn) + T("-") + String ((int) maxChansIn)
  218589. + T(" rates=") + String (rates.size()));
  218590. isInput = maxChansIn > 0;
  218591. isOutput = maxChansOut > 0;
  218592. return (isInput || isOutput) && rates.size() > 0;
  218593. }
  218594. ALSAAudioIODeviceType (const ALSAAudioIODeviceType&);
  218595. const ALSAAudioIODeviceType& operator= (const ALSAAudioIODeviceType&);
  218596. };
  218597. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  218598. {
  218599. return new ALSAAudioIODeviceType();
  218600. }
  218601. END_JUCE_NAMESPACE
  218602. #else // if ALSA is turned off..
  218603. BEGIN_JUCE_NAMESPACE
  218604. AudioIODeviceType* juce_createDefaultAudioIODeviceType() { return 0; }
  218605. END_JUCE_NAMESPACE
  218606. #endif
  218607. #endif
  218608. /********* End of inlined file: juce_linux_Audio.cpp *********/
  218609. /********* Start of inlined file: juce_linux_AudioCDReader.cpp *********/
  218610. BEGIN_JUCE_NAMESPACE
  218611. AudioCDReader::AudioCDReader()
  218612. : AudioFormatReader (0, T("CD Audio"))
  218613. {
  218614. }
  218615. const StringArray AudioCDReader::getAvailableCDNames()
  218616. {
  218617. StringArray names;
  218618. return names;
  218619. }
  218620. AudioCDReader* AudioCDReader::createReaderForCD (const int index)
  218621. {
  218622. return 0;
  218623. }
  218624. AudioCDReader::~AudioCDReader()
  218625. {
  218626. }
  218627. void AudioCDReader::refreshTrackLengths()
  218628. {
  218629. }
  218630. bool AudioCDReader::read (int** destSamples,
  218631. int64 startSampleInFile,
  218632. int numSamples)
  218633. {
  218634. return false;
  218635. }
  218636. bool AudioCDReader::isCDStillPresent() const
  218637. {
  218638. return false;
  218639. }
  218640. int AudioCDReader::getNumTracks() const
  218641. {
  218642. return 0;
  218643. }
  218644. int AudioCDReader::getPositionOfTrackStart (int trackNum) const
  218645. {
  218646. return 0;
  218647. }
  218648. bool AudioCDReader::isTrackAudio (int trackNum) const
  218649. {
  218650. return false;
  218651. }
  218652. void AudioCDReader::enableIndexScanning (bool b)
  218653. {
  218654. }
  218655. int AudioCDReader::getLastIndex() const
  218656. {
  218657. return 0;
  218658. }
  218659. const Array<int> AudioCDReader::findIndexesInTrack (const int trackNumber)
  218660. {
  218661. return Array<int>();
  218662. }
  218663. int AudioCDReader::getCDDBId()
  218664. {
  218665. return 0;
  218666. }
  218667. END_JUCE_NAMESPACE
  218668. /********* End of inlined file: juce_linux_AudioCDReader.cpp *********/
  218669. /********* Start of inlined file: juce_linux_FileChooser.cpp *********/
  218670. /********* Start of inlined file: juce_Config.h *********/
  218671. #ifndef __JUCE_CONFIG_JUCEHEADER__
  218672. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  218673. /*
  218674. This file contains macros that enable/disable various JUCE features.
  218675. */
  218676. /** The name of the namespace that all Juce classes and functions will be
  218677. put inside. If this is not defined, no namespace will be used.
  218678. */
  218679. #ifndef JUCE_NAMESPACE
  218680. #define JUCE_NAMESPACE juce
  218681. #endif
  218682. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  218683. but if you define this value, you can override this can force it to be true or
  218684. false.
  218685. */
  218686. #ifndef JUCE_FORCE_DEBUG
  218687. //#define JUCE_FORCE_DEBUG 1
  218688. #endif
  218689. /** If this flag is enabled, the the jassert and jassertfalse macros will
  218690. always use Logger::writeToLog() to write a message when an assertion happens.
  218691. Enabling it will also leave this turned on in release builds. When it's disabled,
  218692. however, the jassert and jassertfalse macros will not be compiled in a
  218693. release build.
  218694. @see jassert, jassertfalse, Logger
  218695. */
  218696. #ifndef JUCE_LOG_ASSERTIONS
  218697. // #define JUCE_LOG_ASSERTIONS 1
  218698. #endif
  218699. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  218700. which the ASIOAudioIODevice class can't be built. See the comments in the
  218701. ASIOAudioIODevice class's header file for more info about this.
  218702. (This only affects a Win32 build)
  218703. */
  218704. #ifndef JUCE_ASIO
  218705. #define JUCE_ASIO 1
  218706. #endif
  218707. /** Comment out this macro to disable building of ALSA device support on Linux.
  218708. */
  218709. #ifndef JUCE_ALSA
  218710. #define JUCE_ALSA 1
  218711. #endif
  218712. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  218713. have the SDK installed.
  218714. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  218715. classes will be unavailable.
  218716. On Windows, if you enable this, you'll need to have the QuickTime SDK
  218717. installed, and its header files will need to be on your include path.
  218718. */
  218719. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  218720. #define JUCE_QUICKTIME 1
  218721. #endif
  218722. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  218723. have the appropriate headers and libraries available. If it's not enabled, the
  218724. OpenGLComponent class will be unavailable.
  218725. */
  218726. #ifndef JUCE_OPENGL
  218727. #define JUCE_OPENGL 1
  218728. #endif
  218729. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  218730. If you're not going to need either of these formats, turn off the flags to
  218731. avoid bloating your codebase with them.
  218732. */
  218733. #ifndef JUCE_USE_FLAC
  218734. #define JUCE_USE_FLAC 1
  218735. #endif
  218736. #ifndef JUCE_USE_OGGVORBIS
  218737. #define JUCE_USE_OGGVORBIS 1
  218738. #endif
  218739. /** This flag lets you enable support for CD-burning. You might want to disable
  218740. it to build without the MS SDK under windows.
  218741. */
  218742. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  218743. #define JUCE_USE_CDBURNER 1
  218744. #endif
  218745. /** Enabling this macro means that all regions that get repainted will have a coloured
  218746. line drawn around them.
  218747. This is handy if you're trying to optimise drawing, because it lets you easily see
  218748. when anything is being repainted unnecessarily.
  218749. */
  218750. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  218751. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  218752. #endif
  218753. /** Enable this under Linux to use Xinerama for multi-monitor support.
  218754. */
  218755. #ifndef JUCE_USE_XINERAMA
  218756. #define JUCE_USE_XINERAMA 1
  218757. #endif
  218758. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  218759. */
  218760. #ifndef JUCE_USE_XSHM
  218761. #define JUCE_USE_XSHM 1
  218762. #endif
  218763. /** Enabling this builds support for VST audio plugins.
  218764. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  218765. */
  218766. #ifndef JUCE_PLUGINHOST_VST
  218767. // #define JUCE_PLUGINHOST_VST 1
  218768. #endif
  218769. /** Enabling this builds support for AudioUnit audio plugins.
  218770. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  218771. */
  218772. #ifndef JUCE_PLUGINHOST_AU
  218773. // #define JUCE_PLUGINHOST_AU 1
  218774. #endif
  218775. /** Disabling this will avoid linking to any UI code. This is handy for
  218776. writing command-line utilities, e.g. on linux boxes which don't have some
  218777. of the UI libraries installed.
  218778. (On mac and windows, this won't generally make much difference to the build).
  218779. */
  218780. #ifndef JUCE_BUILD_GUI_CLASSES
  218781. #define JUCE_BUILD_GUI_CLASSES 1
  218782. #endif
  218783. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  218784. */
  218785. #ifndef JUCE_WEB_BROWSER
  218786. #define JUCE_WEB_BROWSER 1
  218787. #endif
  218788. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  218789. codebase - you might need to use this if you're linking to some of these libraries
  218790. yourself.
  218791. */
  218792. #ifndef JUCE_INCLUDE_ZLIB_CODE
  218793. #define JUCE_INCLUDE_ZLIB_CODE 1
  218794. #endif
  218795. #ifndef JUCE_INCLUDE_FLAC_CODE
  218796. #define JUCE_INCLUDE_FLAC_CODE 1
  218797. #endif
  218798. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  218799. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  218800. #endif
  218801. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  218802. #define JUCE_INCLUDE_PNGLIB_CODE 1
  218803. #endif
  218804. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  218805. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  218806. #endif
  218807. /** Enable this to add extra memory-leak info to the new and delete operators.
  218808. (Currently, this only affects Windows builds in debug mode).
  218809. */
  218810. #ifndef JUCE_CHECK_MEMORY_LEAKS
  218811. #define JUCE_CHECK_MEMORY_LEAKS 1
  218812. #endif
  218813. /** Enable this to turn on juce's internal catching of exceptions.
  218814. Turning it off will avoid any exception catching. With it on, all exceptions
  218815. are passed to the JUCEApplication::unhandledException() callback for logging.
  218816. */
  218817. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  218818. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  218819. #endif
  218820. /** If this macro is set, the Juce String class will use unicode as its
  218821. internal representation. If it isn't set, it'll use ANSI.
  218822. */
  218823. #ifndef JUCE_STRINGS_ARE_UNICODE
  218824. #define JUCE_STRINGS_ARE_UNICODE 1
  218825. #endif
  218826. #endif
  218827. /********* End of inlined file: juce_Config.h *********/
  218828. #if JUCE_BUILD_GUI_CLASSES
  218829. BEGIN_JUCE_NAMESPACE
  218830. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  218831. const String& title,
  218832. const File& file,
  218833. const String& filters,
  218834. bool isDirectory,
  218835. bool isSave,
  218836. bool warnAboutOverwritingExistingFiles,
  218837. bool selectMultipleFiles,
  218838. FilePreviewComponent* previewComponent)
  218839. {
  218840. //xxx ain't got one!
  218841. jassertfalse
  218842. }
  218843. END_JUCE_NAMESPACE
  218844. #endif
  218845. /********* End of inlined file: juce_linux_FileChooser.cpp *********/
  218846. /********* Start of inlined file: juce_linux_Fonts.cpp *********/
  218847. /********* Start of inlined file: juce_Config.h *********/
  218848. #ifndef __JUCE_CONFIG_JUCEHEADER__
  218849. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  218850. /*
  218851. This file contains macros that enable/disable various JUCE features.
  218852. */
  218853. /** The name of the namespace that all Juce classes and functions will be
  218854. put inside. If this is not defined, no namespace will be used.
  218855. */
  218856. #ifndef JUCE_NAMESPACE
  218857. #define JUCE_NAMESPACE juce
  218858. #endif
  218859. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  218860. but if you define this value, you can override this can force it to be true or
  218861. false.
  218862. */
  218863. #ifndef JUCE_FORCE_DEBUG
  218864. //#define JUCE_FORCE_DEBUG 1
  218865. #endif
  218866. /** If this flag is enabled, the the jassert and jassertfalse macros will
  218867. always use Logger::writeToLog() to write a message when an assertion happens.
  218868. Enabling it will also leave this turned on in release builds. When it's disabled,
  218869. however, the jassert and jassertfalse macros will not be compiled in a
  218870. release build.
  218871. @see jassert, jassertfalse, Logger
  218872. */
  218873. #ifndef JUCE_LOG_ASSERTIONS
  218874. // #define JUCE_LOG_ASSERTIONS 1
  218875. #endif
  218876. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  218877. which the ASIOAudioIODevice class can't be built. See the comments in the
  218878. ASIOAudioIODevice class's header file for more info about this.
  218879. (This only affects a Win32 build)
  218880. */
  218881. #ifndef JUCE_ASIO
  218882. #define JUCE_ASIO 1
  218883. #endif
  218884. /** Comment out this macro to disable building of ALSA device support on Linux.
  218885. */
  218886. #ifndef JUCE_ALSA
  218887. #define JUCE_ALSA 1
  218888. #endif
  218889. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  218890. have the SDK installed.
  218891. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  218892. classes will be unavailable.
  218893. On Windows, if you enable this, you'll need to have the QuickTime SDK
  218894. installed, and its header files will need to be on your include path.
  218895. */
  218896. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  218897. #define JUCE_QUICKTIME 1
  218898. #endif
  218899. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  218900. have the appropriate headers and libraries available. If it's not enabled, the
  218901. OpenGLComponent class will be unavailable.
  218902. */
  218903. #ifndef JUCE_OPENGL
  218904. #define JUCE_OPENGL 1
  218905. #endif
  218906. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  218907. If you're not going to need either of these formats, turn off the flags to
  218908. avoid bloating your codebase with them.
  218909. */
  218910. #ifndef JUCE_USE_FLAC
  218911. #define JUCE_USE_FLAC 1
  218912. #endif
  218913. #ifndef JUCE_USE_OGGVORBIS
  218914. #define JUCE_USE_OGGVORBIS 1
  218915. #endif
  218916. /** This flag lets you enable support for CD-burning. You might want to disable
  218917. it to build without the MS SDK under windows.
  218918. */
  218919. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  218920. #define JUCE_USE_CDBURNER 1
  218921. #endif
  218922. /** Enabling this macro means that all regions that get repainted will have a coloured
  218923. line drawn around them.
  218924. This is handy if you're trying to optimise drawing, because it lets you easily see
  218925. when anything is being repainted unnecessarily.
  218926. */
  218927. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  218928. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  218929. #endif
  218930. /** Enable this under Linux to use Xinerama for multi-monitor support.
  218931. */
  218932. #ifndef JUCE_USE_XINERAMA
  218933. #define JUCE_USE_XINERAMA 1
  218934. #endif
  218935. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  218936. */
  218937. #ifndef JUCE_USE_XSHM
  218938. #define JUCE_USE_XSHM 1
  218939. #endif
  218940. /** Enabling this builds support for VST audio plugins.
  218941. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  218942. */
  218943. #ifndef JUCE_PLUGINHOST_VST
  218944. // #define JUCE_PLUGINHOST_VST 1
  218945. #endif
  218946. /** Enabling this builds support for AudioUnit audio plugins.
  218947. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  218948. */
  218949. #ifndef JUCE_PLUGINHOST_AU
  218950. // #define JUCE_PLUGINHOST_AU 1
  218951. #endif
  218952. /** Disabling this will avoid linking to any UI code. This is handy for
  218953. writing command-line utilities, e.g. on linux boxes which don't have some
  218954. of the UI libraries installed.
  218955. (On mac and windows, this won't generally make much difference to the build).
  218956. */
  218957. #ifndef JUCE_BUILD_GUI_CLASSES
  218958. #define JUCE_BUILD_GUI_CLASSES 1
  218959. #endif
  218960. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  218961. */
  218962. #ifndef JUCE_WEB_BROWSER
  218963. #define JUCE_WEB_BROWSER 1
  218964. #endif
  218965. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  218966. codebase - you might need to use this if you're linking to some of these libraries
  218967. yourself.
  218968. */
  218969. #ifndef JUCE_INCLUDE_ZLIB_CODE
  218970. #define JUCE_INCLUDE_ZLIB_CODE 1
  218971. #endif
  218972. #ifndef JUCE_INCLUDE_FLAC_CODE
  218973. #define JUCE_INCLUDE_FLAC_CODE 1
  218974. #endif
  218975. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  218976. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  218977. #endif
  218978. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  218979. #define JUCE_INCLUDE_PNGLIB_CODE 1
  218980. #endif
  218981. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  218982. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  218983. #endif
  218984. /** Enable this to add extra memory-leak info to the new and delete operators.
  218985. (Currently, this only affects Windows builds in debug mode).
  218986. */
  218987. #ifndef JUCE_CHECK_MEMORY_LEAKS
  218988. #define JUCE_CHECK_MEMORY_LEAKS 1
  218989. #endif
  218990. /** Enable this to turn on juce's internal catching of exceptions.
  218991. Turning it off will avoid any exception catching. With it on, all exceptions
  218992. are passed to the JUCEApplication::unhandledException() callback for logging.
  218993. */
  218994. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  218995. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  218996. #endif
  218997. /** If this macro is set, the Juce String class will use unicode as its
  218998. internal representation. If it isn't set, it'll use ANSI.
  218999. */
  219000. #ifndef JUCE_STRINGS_ARE_UNICODE
  219001. #define JUCE_STRINGS_ARE_UNICODE 1
  219002. #endif
  219003. #endif
  219004. /********* End of inlined file: juce_Config.h *********/
  219005. #if JUCE_BUILD_GUI_CLASSES
  219006. /* Got a build error here? You'll need to install the freetype library...
  219007. The name of the package to install is "libfreetype6-dev".
  219008. */
  219009. #include <ft2build.h>
  219010. #include FT_FREETYPE_H
  219011. BEGIN_JUCE_NAMESPACE
  219012. class FreeTypeFontFace
  219013. {
  219014. public:
  219015. enum FontStyle
  219016. {
  219017. Plain = 0,
  219018. Bold = 1,
  219019. Italic = 2
  219020. };
  219021. struct FontNameIndex
  219022. {
  219023. String fileName;
  219024. int faceIndex;
  219025. };
  219026. FreeTypeFontFace (const String& familyName)
  219027. : hasSerif (false),
  219028. monospaced (false)
  219029. {
  219030. family = familyName;
  219031. }
  219032. void setFileName (const String& name,
  219033. const int faceIndex,
  219034. FontStyle style)
  219035. {
  219036. if (names[(int) style].fileName.isEmpty())
  219037. {
  219038. names[(int) style].fileName = name;
  219039. names[(int) style].faceIndex = faceIndex;
  219040. }
  219041. }
  219042. const String& getFamilyName() const throw()
  219043. {
  219044. return family;
  219045. }
  219046. const String& getFileName (int style, int* faceIndex) const throw()
  219047. {
  219048. *faceIndex = names [style].faceIndex;
  219049. return names[style].fileName;
  219050. }
  219051. void setMonospaced (bool mono) { monospaced = mono; }
  219052. bool getMonospaced () const throw() { return monospaced; }
  219053. void setSerif (const bool serif) { hasSerif = serif; }
  219054. bool getSerif () const throw() { return hasSerif; }
  219055. private:
  219056. String family;
  219057. FontNameIndex names[4];
  219058. bool hasSerif, monospaced;
  219059. };
  219060. class FreeTypeInterface : public DeletedAtShutdown
  219061. {
  219062. public:
  219063. FreeTypeInterface() throw()
  219064. : lastFace (0),
  219065. lastBold (false),
  219066. lastItalic (false)
  219067. {
  219068. if (FT_Init_FreeType (&ftLib) != 0)
  219069. {
  219070. ftLib = 0;
  219071. DBG (T("Failed to initialize FreeType"));
  219072. }
  219073. StringArray fontDirs;
  219074. fontDirs.addTokens (String (getenv ("JUCE_FONT_PATH")), T(";,"), 0);
  219075. fontDirs.removeEmptyStrings (true);
  219076. if (fontDirs.size() == 0)
  219077. {
  219078. XmlDocument fontsConfig (File ("/etc/fonts/fonts.conf"));
  219079. XmlElement* const fontsInfo = fontsConfig.getDocumentElement();
  219080. if (fontsInfo != 0)
  219081. {
  219082. forEachXmlChildElementWithTagName (*fontsInfo, e, T("dir"))
  219083. {
  219084. fontDirs.add (e->getAllSubText().trim());
  219085. }
  219086. delete fontsInfo;
  219087. }
  219088. }
  219089. if (fontDirs.size() == 0)
  219090. fontDirs.add ("/usr/X11R6/lib/X11/fonts");
  219091. for (int i = 0; i < fontDirs.size(); ++i)
  219092. enumerateFaces (fontDirs[i]);
  219093. }
  219094. ~FreeTypeInterface() throw()
  219095. {
  219096. if (lastFace != 0)
  219097. FT_Done_Face (lastFace);
  219098. if (ftLib != 0)
  219099. FT_Done_FreeType (ftLib);
  219100. clearSingletonInstance();
  219101. }
  219102. FreeTypeFontFace* findOrCreate (const String& familyName,
  219103. const bool create = false) throw()
  219104. {
  219105. for (int i = 0; i < faces.size(); i++)
  219106. if (faces[i]->getFamilyName() == familyName)
  219107. return faces[i];
  219108. if (! create)
  219109. return NULL;
  219110. FreeTypeFontFace* newFace = new FreeTypeFontFace (familyName);
  219111. faces.add (newFace);
  219112. return newFace;
  219113. }
  219114. // Enumerate all font faces available in a given directory
  219115. void enumerateFaces (const String& path) throw()
  219116. {
  219117. File dirPath (path);
  219118. if (path.isEmpty() || ! dirPath.isDirectory())
  219119. return;
  219120. DirectoryIterator di (dirPath, true);
  219121. while (di.next())
  219122. {
  219123. File possible (di.getFile());
  219124. if (possible.hasFileExtension (T("ttf"))
  219125. || possible.hasFileExtension (T("pfb"))
  219126. || possible.hasFileExtension (T("pcf")))
  219127. {
  219128. FT_Face face;
  219129. int faceIndex = 0;
  219130. int numFaces = 0;
  219131. do
  219132. {
  219133. if (FT_New_Face (ftLib,
  219134. possible.getFullPathName(),
  219135. faceIndex,
  219136. &face) == 0)
  219137. {
  219138. if (faceIndex == 0)
  219139. numFaces = face->num_faces;
  219140. if ((face->face_flags & FT_FACE_FLAG_SCALABLE) != 0)
  219141. {
  219142. FreeTypeFontFace* const newFace = findOrCreate (face->family_name, true);
  219143. int style = (int) FreeTypeFontFace::Plain;
  219144. if ((face->style_flags & FT_STYLE_FLAG_BOLD) != 0)
  219145. style |= (int) FreeTypeFontFace::Bold;
  219146. if ((face->style_flags & FT_STYLE_FLAG_ITALIC) != 0)
  219147. style |= (int) FreeTypeFontFace::Italic;
  219148. newFace->setFileName (possible.getFullPathName(), faceIndex, (FreeTypeFontFace::FontStyle) style);
  219149. if ((face->face_flags & FT_FACE_FLAG_FIXED_WIDTH) != 0)
  219150. newFace->setMonospaced (true);
  219151. else
  219152. newFace->setMonospaced (false);
  219153. // Surely there must be a better way to do this?
  219154. if (String (face->family_name).containsIgnoreCase (T("Sans"))
  219155. || String (face->family_name).containsIgnoreCase (T("Verdana"))
  219156. || String (face->family_name).containsIgnoreCase (T("Arial")))
  219157. {
  219158. newFace->setSerif (false);
  219159. }
  219160. else
  219161. {
  219162. newFace->setSerif (true);
  219163. }
  219164. }
  219165. FT_Done_Face (face);
  219166. }
  219167. ++faceIndex;
  219168. }
  219169. while (faceIndex < numFaces);
  219170. }
  219171. }
  219172. }
  219173. // Create a FreeType face object for a given font
  219174. FT_Face createFT_Face (const String& fontName,
  219175. const bool bold,
  219176. const bool italic) throw()
  219177. {
  219178. FT_Face face = NULL;
  219179. if (fontName == lastFontName && bold == lastBold && italic == lastItalic)
  219180. {
  219181. face = lastFace;
  219182. }
  219183. else
  219184. {
  219185. if (lastFace)
  219186. {
  219187. FT_Done_Face (lastFace);
  219188. lastFace = NULL;
  219189. }
  219190. lastFontName = fontName;
  219191. lastBold = bold;
  219192. lastItalic = italic;
  219193. FreeTypeFontFace* const ftFace = findOrCreate (fontName);
  219194. if (ftFace != 0)
  219195. {
  219196. int style = (int) FreeTypeFontFace::Plain;
  219197. if (bold)
  219198. style |= (int) FreeTypeFontFace::Bold;
  219199. if (italic)
  219200. style |= (int) FreeTypeFontFace::Italic;
  219201. int faceIndex;
  219202. String fileName (ftFace->getFileName (style, &faceIndex));
  219203. if (fileName.isEmpty())
  219204. {
  219205. style ^= (int) FreeTypeFontFace::Bold;
  219206. fileName = ftFace->getFileName (style, &faceIndex);
  219207. if (fileName.isEmpty())
  219208. {
  219209. style ^= (int) FreeTypeFontFace::Bold;
  219210. style ^= (int) FreeTypeFontFace::Italic;
  219211. fileName = ftFace->getFileName (style, &faceIndex);
  219212. if (! fileName.length())
  219213. {
  219214. style ^= (int) FreeTypeFontFace::Bold;
  219215. fileName = ftFace->getFileName (style, &faceIndex);
  219216. }
  219217. }
  219218. }
  219219. if (! FT_New_Face (ftLib, (const char*) fileName, faceIndex, &lastFace))
  219220. {
  219221. face = lastFace;
  219222. // If there isn't a unicode charmap then select the first one.
  219223. if (FT_Select_Charmap (face, ft_encoding_unicode))
  219224. FT_Set_Charmap (face, face->charmaps[0]);
  219225. }
  219226. }
  219227. }
  219228. return face;
  219229. }
  219230. bool addGlyph (FT_Face face, Typeface& dest, uint32 character) throw()
  219231. {
  219232. const unsigned int glyphIndex = FT_Get_Char_Index (face, character);
  219233. const float height = (float) (face->ascender - face->descender);
  219234. const float scaleX = 1.0f / height;
  219235. const float scaleY = -1.0f / height;
  219236. Path destShape;
  219237. #define CONVERTX(val) (scaleX * (val).x)
  219238. #define CONVERTY(val) (scaleY * (val).y)
  219239. if (FT_Load_Glyph (face, glyphIndex, FT_LOAD_NO_SCALE
  219240. | FT_LOAD_NO_BITMAP
  219241. | FT_LOAD_IGNORE_TRANSFORM) != 0
  219242. || face->glyph->format != ft_glyph_format_outline)
  219243. {
  219244. return false;
  219245. }
  219246. const FT_Outline* const outline = &face->glyph->outline;
  219247. const short* const contours = outline->contours;
  219248. const char* const tags = outline->tags;
  219249. FT_Vector* const points = outline->points;
  219250. for (int c = 0; c < outline->n_contours; c++)
  219251. {
  219252. const int startPoint = (c == 0) ? 0 : contours [c - 1] + 1;
  219253. const int endPoint = contours[c];
  219254. for (int p = startPoint; p <= endPoint; p++)
  219255. {
  219256. const float x = CONVERTX (points[p]);
  219257. const float y = CONVERTY (points[p]);
  219258. if (p == startPoint)
  219259. {
  219260. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219261. {
  219262. float x2 = CONVERTX (points [endPoint]);
  219263. float y2 = CONVERTY (points [endPoint]);
  219264. if (FT_CURVE_TAG (tags[endPoint]) != FT_Curve_Tag_On)
  219265. {
  219266. x2 = (x + x2) * 0.5f;
  219267. y2 = (y + y2) * 0.5f;
  219268. }
  219269. destShape.startNewSubPath (x2, y2);
  219270. }
  219271. else
  219272. {
  219273. destShape.startNewSubPath (x, y);
  219274. }
  219275. }
  219276. if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_On)
  219277. {
  219278. if (p != startPoint)
  219279. destShape.lineTo (x, y);
  219280. }
  219281. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Conic)
  219282. {
  219283. const int nextIndex = (p == endPoint) ? startPoint : p + 1;
  219284. float x2 = CONVERTX (points [nextIndex]);
  219285. float y2 = CONVERTY (points [nextIndex]);
  219286. if (FT_CURVE_TAG (tags [nextIndex]) == FT_Curve_Tag_Conic)
  219287. {
  219288. x2 = (x + x2) * 0.5f;
  219289. y2 = (y + y2) * 0.5f;
  219290. }
  219291. else
  219292. {
  219293. ++p;
  219294. }
  219295. destShape.quadraticTo (x, y, x2, y2);
  219296. }
  219297. else if (FT_CURVE_TAG (tags[p]) == FT_Curve_Tag_Cubic)
  219298. {
  219299. if (p >= endPoint)
  219300. return false;
  219301. const int next1 = p + 1;
  219302. const int next2 = (p == (endPoint - 1)) ? startPoint : p + 2;
  219303. const float x2 = CONVERTX (points [next1]);
  219304. const float y2 = CONVERTY (points [next1]);
  219305. const float x3 = CONVERTX (points [next2]);
  219306. const float y3 = CONVERTY (points [next2]);
  219307. if (FT_CURVE_TAG (tags[next1]) != FT_Curve_Tag_Cubic
  219308. || FT_CURVE_TAG (tags[next2]) != FT_Curve_Tag_On)
  219309. return false;
  219310. destShape.cubicTo (x, y, x2, y2, x3, y3);
  219311. p += 2;
  219312. }
  219313. }
  219314. destShape.closeSubPath();
  219315. }
  219316. dest.addGlyph (character, destShape, face->glyph->metrics.horiAdvance/height);
  219317. if ((face->face_flags & FT_FACE_FLAG_KERNING) != 0)
  219318. addKerning (face, dest, character, glyphIndex);
  219319. return true;
  219320. }
  219321. void addKerning (FT_Face face, Typeface& dest, const uint32 character, const uint32 glyphIndex) throw()
  219322. {
  219323. const float height = (float) (face->ascender - face->descender);
  219324. uint32 rightGlyphIndex;
  219325. uint32 rightCharCode = FT_Get_First_Char (face, &rightGlyphIndex);
  219326. while (rightGlyphIndex != 0)
  219327. {
  219328. FT_Vector kerning;
  219329. if (FT_Get_Kerning (face, glyphIndex, rightGlyphIndex, ft_kerning_unscaled, &kerning) == 0)
  219330. {
  219331. if (kerning.x != 0)
  219332. dest.addKerningPair (character, rightCharCode, kerning.x / height);
  219333. }
  219334. rightCharCode = FT_Get_Next_Char (face, rightCharCode, &rightGlyphIndex);
  219335. }
  219336. }
  219337. // Add a glyph to a font
  219338. bool addGlyphToFont (const uint32 character,
  219339. const tchar* fontName, bool bold, bool italic,
  219340. Typeface& dest) throw()
  219341. {
  219342. FT_Face face = createFT_Face (fontName, bold, italic);
  219343. if (face != 0)
  219344. return addGlyph (face, dest, character);
  219345. return false;
  219346. }
  219347. // Create a Typeface object for given name/style
  219348. bool createTypeface (const String& fontName,
  219349. const bool bold, const bool italic,
  219350. Typeface& dest,
  219351. const bool addAllGlyphs) throw()
  219352. {
  219353. dest.clear();
  219354. dest.setName (fontName);
  219355. dest.setBold (bold);
  219356. dest.setItalic (italic);
  219357. FT_Face face = createFT_Face (fontName, bold, italic);
  219358. if (face == 0)
  219359. {
  219360. #ifdef JUCE_DEBUG
  219361. String msg (T("Failed to create typeface: "));
  219362. msg << fontName << " " << (bold ? 'B' : ' ') << (italic ? 'I' : ' ');
  219363. DBG (msg);
  219364. #endif
  219365. return face;
  219366. }
  219367. const float height = (float) (face->ascender - face->descender);
  219368. dest.setAscent (face->ascender / height);
  219369. dest.setDefaultCharacter (L' ');
  219370. if (addAllGlyphs)
  219371. {
  219372. uint32 glyphIndex;
  219373. uint32 charCode = FT_Get_First_Char (face, &glyphIndex);
  219374. while (glyphIndex != 0)
  219375. {
  219376. addGlyph (face, dest, charCode);
  219377. charCode = FT_Get_Next_Char (face, charCode, &glyphIndex);
  219378. }
  219379. }
  219380. return true;
  219381. }
  219382. void getFamilyNames (StringArray& familyNames) const throw()
  219383. {
  219384. for (int i = 0; i < faces.size(); i++)
  219385. familyNames.add (faces[i]->getFamilyName());
  219386. }
  219387. void getMonospacedNames (StringArray& monoSpaced) const throw()
  219388. {
  219389. for (int i = 0; i < faces.size(); i++)
  219390. if (faces[i]->getMonospaced())
  219391. monoSpaced.add (faces[i]->getFamilyName());
  219392. }
  219393. void getSerifNames (StringArray& serif) const throw()
  219394. {
  219395. for (int i = 0; i < faces.size(); i++)
  219396. if (faces[i]->getSerif())
  219397. serif.add (faces[i]->getFamilyName());
  219398. }
  219399. void getSansSerifNames (StringArray& sansSerif) const throw()
  219400. {
  219401. for (int i = 0; i < faces.size(); i++)
  219402. if (! faces[i]->getSerif())
  219403. sansSerif.add (faces[i]->getFamilyName());
  219404. }
  219405. juce_DeclareSingleton_SingleThreaded_Minimal (FreeTypeInterface)
  219406. private:
  219407. FT_Library ftLib;
  219408. FT_Face lastFace;
  219409. String lastFontName;
  219410. bool lastBold, lastItalic;
  219411. OwnedArray<FreeTypeFontFace> faces;
  219412. };
  219413. juce_ImplementSingleton_SingleThreaded (FreeTypeInterface)
  219414. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  219415. bool bold, bool italic,
  219416. bool addAllGlyphsToFont) throw()
  219417. {
  219418. FreeTypeInterface::getInstance()
  219419. ->createTypeface (fontName, bold, italic, *this, addAllGlyphsToFont);
  219420. }
  219421. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  219422. {
  219423. return FreeTypeInterface::getInstance()
  219424. ->addGlyphToFont (character, getName(), isBold(), isItalic(), *this);
  219425. }
  219426. const StringArray Font::findAllTypefaceNames() throw()
  219427. {
  219428. StringArray s;
  219429. FreeTypeInterface::getInstance()->getFamilyNames (s);
  219430. s.sort (true);
  219431. return s;
  219432. }
  219433. static const String pickBestFont (const StringArray& names,
  219434. const char* const choicesString)
  219435. {
  219436. StringArray choices;
  219437. choices.addTokens (String (choicesString), T(","), 0);
  219438. choices.trim();
  219439. choices.removeEmptyStrings();
  219440. int i, j;
  219441. for (j = 0; j < choices.size(); ++j)
  219442. if (names.contains (choices[j], true))
  219443. return choices[j];
  219444. for (j = 0; j < choices.size(); ++j)
  219445. for (i = 0; i < names.size(); i++)
  219446. if (names[i].startsWithIgnoreCase (choices[j]))
  219447. return names[i];
  219448. for (j = 0; j < choices.size(); ++j)
  219449. for (i = 0; i < names.size(); i++)
  219450. if (names[i].containsIgnoreCase (choices[j]))
  219451. return names[i];
  219452. return names[0];
  219453. }
  219454. static const String linux_getDefaultSansSerifFontName()
  219455. {
  219456. StringArray allFonts;
  219457. FreeTypeInterface::getInstance()->getSansSerifNames (allFonts);
  219458. return pickBestFont (allFonts, "Verdana, Bitstream Vera Sans, Luxi Sans, Sans");
  219459. }
  219460. static const String linux_getDefaultSerifFontName()
  219461. {
  219462. StringArray allFonts;
  219463. FreeTypeInterface::getInstance()->getSerifNames (allFonts);
  219464. return pickBestFont (allFonts, "Bitstream Vera Serif, Times, Nimbus Roman, Serif");
  219465. }
  219466. static const String linux_getDefaultMonospacedFontName()
  219467. {
  219468. StringArray allFonts;
  219469. FreeTypeInterface::getInstance()->getMonospacedNames (allFonts);
  219470. return pickBestFont (allFonts, "Bitstream Vera Sans Mono, Courier, Sans Mono, Mono");
  219471. }
  219472. void Font::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  219473. {
  219474. defaultSans = linux_getDefaultSansSerifFontName();
  219475. defaultSerif = linux_getDefaultSerifFontName();
  219476. defaultFixed = linux_getDefaultMonospacedFontName();
  219477. }
  219478. END_JUCE_NAMESPACE
  219479. #endif
  219480. /********* End of inlined file: juce_linux_Fonts.cpp *********/
  219481. /********* Start of inlined file: juce_linux_Messaging.cpp *********/
  219482. /********* Start of inlined file: juce_Config.h *********/
  219483. #ifndef __JUCE_CONFIG_JUCEHEADER__
  219484. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  219485. /*
  219486. This file contains macros that enable/disable various JUCE features.
  219487. */
  219488. /** The name of the namespace that all Juce classes and functions will be
  219489. put inside. If this is not defined, no namespace will be used.
  219490. */
  219491. #ifndef JUCE_NAMESPACE
  219492. #define JUCE_NAMESPACE juce
  219493. #endif
  219494. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  219495. but if you define this value, you can override this can force it to be true or
  219496. false.
  219497. */
  219498. #ifndef JUCE_FORCE_DEBUG
  219499. //#define JUCE_FORCE_DEBUG 1
  219500. #endif
  219501. /** If this flag is enabled, the the jassert and jassertfalse macros will
  219502. always use Logger::writeToLog() to write a message when an assertion happens.
  219503. Enabling it will also leave this turned on in release builds. When it's disabled,
  219504. however, the jassert and jassertfalse macros will not be compiled in a
  219505. release build.
  219506. @see jassert, jassertfalse, Logger
  219507. */
  219508. #ifndef JUCE_LOG_ASSERTIONS
  219509. // #define JUCE_LOG_ASSERTIONS 1
  219510. #endif
  219511. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  219512. which the ASIOAudioIODevice class can't be built. See the comments in the
  219513. ASIOAudioIODevice class's header file for more info about this.
  219514. (This only affects a Win32 build)
  219515. */
  219516. #ifndef JUCE_ASIO
  219517. #define JUCE_ASIO 1
  219518. #endif
  219519. /** Comment out this macro to disable building of ALSA device support on Linux.
  219520. */
  219521. #ifndef JUCE_ALSA
  219522. #define JUCE_ALSA 1
  219523. #endif
  219524. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  219525. have the SDK installed.
  219526. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  219527. classes will be unavailable.
  219528. On Windows, if you enable this, you'll need to have the QuickTime SDK
  219529. installed, and its header files will need to be on your include path.
  219530. */
  219531. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  219532. #define JUCE_QUICKTIME 1
  219533. #endif
  219534. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  219535. have the appropriate headers and libraries available. If it's not enabled, the
  219536. OpenGLComponent class will be unavailable.
  219537. */
  219538. #ifndef JUCE_OPENGL
  219539. #define JUCE_OPENGL 1
  219540. #endif
  219541. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  219542. If you're not going to need either of these formats, turn off the flags to
  219543. avoid bloating your codebase with them.
  219544. */
  219545. #ifndef JUCE_USE_FLAC
  219546. #define JUCE_USE_FLAC 1
  219547. #endif
  219548. #ifndef JUCE_USE_OGGVORBIS
  219549. #define JUCE_USE_OGGVORBIS 1
  219550. #endif
  219551. /** This flag lets you enable support for CD-burning. You might want to disable
  219552. it to build without the MS SDK under windows.
  219553. */
  219554. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  219555. #define JUCE_USE_CDBURNER 1
  219556. #endif
  219557. /** Enabling this macro means that all regions that get repainted will have a coloured
  219558. line drawn around them.
  219559. This is handy if you're trying to optimise drawing, because it lets you easily see
  219560. when anything is being repainted unnecessarily.
  219561. */
  219562. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  219563. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  219564. #endif
  219565. /** Enable this under Linux to use Xinerama for multi-monitor support.
  219566. */
  219567. #ifndef JUCE_USE_XINERAMA
  219568. #define JUCE_USE_XINERAMA 1
  219569. #endif
  219570. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  219571. */
  219572. #ifndef JUCE_USE_XSHM
  219573. #define JUCE_USE_XSHM 1
  219574. #endif
  219575. /** Enabling this builds support for VST audio plugins.
  219576. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  219577. */
  219578. #ifndef JUCE_PLUGINHOST_VST
  219579. // #define JUCE_PLUGINHOST_VST 1
  219580. #endif
  219581. /** Enabling this builds support for AudioUnit audio plugins.
  219582. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  219583. */
  219584. #ifndef JUCE_PLUGINHOST_AU
  219585. // #define JUCE_PLUGINHOST_AU 1
  219586. #endif
  219587. /** Disabling this will avoid linking to any UI code. This is handy for
  219588. writing command-line utilities, e.g. on linux boxes which don't have some
  219589. of the UI libraries installed.
  219590. (On mac and windows, this won't generally make much difference to the build).
  219591. */
  219592. #ifndef JUCE_BUILD_GUI_CLASSES
  219593. #define JUCE_BUILD_GUI_CLASSES 1
  219594. #endif
  219595. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  219596. */
  219597. #ifndef JUCE_WEB_BROWSER
  219598. #define JUCE_WEB_BROWSER 1
  219599. #endif
  219600. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  219601. codebase - you might need to use this if you're linking to some of these libraries
  219602. yourself.
  219603. */
  219604. #ifndef JUCE_INCLUDE_ZLIB_CODE
  219605. #define JUCE_INCLUDE_ZLIB_CODE 1
  219606. #endif
  219607. #ifndef JUCE_INCLUDE_FLAC_CODE
  219608. #define JUCE_INCLUDE_FLAC_CODE 1
  219609. #endif
  219610. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  219611. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  219612. #endif
  219613. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  219614. #define JUCE_INCLUDE_PNGLIB_CODE 1
  219615. #endif
  219616. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  219617. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  219618. #endif
  219619. /** Enable this to add extra memory-leak info to the new and delete operators.
  219620. (Currently, this only affects Windows builds in debug mode).
  219621. */
  219622. #ifndef JUCE_CHECK_MEMORY_LEAKS
  219623. #define JUCE_CHECK_MEMORY_LEAKS 1
  219624. #endif
  219625. /** Enable this to turn on juce's internal catching of exceptions.
  219626. Turning it off will avoid any exception catching. With it on, all exceptions
  219627. are passed to the JUCEApplication::unhandledException() callback for logging.
  219628. */
  219629. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  219630. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  219631. #endif
  219632. /** If this macro is set, the Juce String class will use unicode as its
  219633. internal representation. If it isn't set, it'll use ANSI.
  219634. */
  219635. #ifndef JUCE_STRINGS_ARE_UNICODE
  219636. #define JUCE_STRINGS_ARE_UNICODE 1
  219637. #endif
  219638. #endif
  219639. /********* End of inlined file: juce_Config.h *********/
  219640. #if JUCE_BUILD_GUI_CLASSES
  219641. #include <stdio.h>
  219642. #include <signal.h>
  219643. #include <X11/Xlib.h>
  219644. #include <X11/Xatom.h>
  219645. #include <X11/Xresource.h>
  219646. #include <X11/Xutil.h>
  219647. BEGIN_JUCE_NAMESPACE
  219648. #ifdef JUCE_DEBUG
  219649. #define JUCE_DEBUG_XERRORS 1
  219650. #endif
  219651. Display* display = 0; // This is also referenced from WindowDriver.cpp
  219652. static Window juce_messageWindowHandle = None;
  219653. #define SpecialAtom "JUCESpecialAtom"
  219654. #define BroadcastAtom "JUCEBroadcastAtom"
  219655. #define SpecialCallbackAtom "JUCESpecialCallbackAtom"
  219656. static Atom specialId;
  219657. static Atom broadcastId;
  219658. static Atom specialCallbackId;
  219659. // This is referenced from WindowDriver.cpp
  219660. XContext improbableNumber;
  219661. // Defined in WindowDriver.cpp
  219662. extern void juce_windowMessageReceive (XEvent* event);
  219663. struct MessageThreadFuncCall
  219664. {
  219665. MessageCallbackFunction* func;
  219666. void* parameter;
  219667. void* result;
  219668. CriticalSection lock;
  219669. WaitableEvent event;
  219670. };
  219671. static bool errorCondition = false;
  219672. static XErrorHandler oldErrorHandler = (XErrorHandler) 0;
  219673. static XIOErrorHandler oldIOErrorHandler = (XIOErrorHandler) 0;
  219674. // (defined in another file to avoid problems including certain headers in this one)
  219675. extern bool juce_isRunningAsApplication();
  219676. // Usually happens when client-server connection is broken
  219677. static int ioErrorHandler (Display* display)
  219678. {
  219679. DBG (T("ERROR: connection to X server broken.. terminating."));
  219680. errorCondition = true;
  219681. if (juce_isRunningAsApplication())
  219682. Process::terminate();
  219683. return 0;
  219684. }
  219685. // A protocol error has occurred
  219686. static int errorHandler (Display* display, XErrorEvent* event)
  219687. {
  219688. #ifdef JUCE_DEBUG_XERRORS
  219689. char errorStr[64] = { 0 };
  219690. char requestStr[64] = { 0 };
  219691. XGetErrorText (display, event->error_code, errorStr, 64);
  219692. XGetErrorDatabaseText (display,
  219693. "XRequest",
  219694. (const char*) String (event->request_code),
  219695. "Unknown",
  219696. requestStr,
  219697. 64);
  219698. DBG (T("ERROR: X returned ") + String (errorStr) + T(" for operation ") + String (requestStr));
  219699. #endif
  219700. return 0;
  219701. }
  219702. static bool breakIn = false;
  219703. // Breakin from keyboard
  219704. static void sig_handler (int sig)
  219705. {
  219706. if (sig == SIGINT)
  219707. {
  219708. breakIn = true;
  219709. return;
  219710. }
  219711. static bool reentrant = false;
  219712. if (reentrant == false)
  219713. {
  219714. reentrant = true;
  219715. // Illegal instruction
  219716. fflush (stdout);
  219717. Logger::outputDebugString ("ERROR: Program executed illegal instruction.. terminating");
  219718. errorCondition = true;
  219719. if (juce_isRunningAsApplication())
  219720. Process::terminate();
  219721. }
  219722. else
  219723. {
  219724. if (juce_isRunningAsApplication())
  219725. exit(0);
  219726. }
  219727. }
  219728. void MessageManager::doPlatformSpecificInitialisation()
  219729. {
  219730. // Initialise xlib for multiple thread support
  219731. static bool initThreadCalled = false;
  219732. if (! initThreadCalled)
  219733. {
  219734. if (! XInitThreads())
  219735. {
  219736. // This is fatal! Print error and closedown
  219737. Logger::outputDebugString ("Failed to initialise xlib thread support.");
  219738. if (juce_isRunningAsApplication())
  219739. Process::terminate();
  219740. return;
  219741. }
  219742. initThreadCalled = true;
  219743. }
  219744. // This is called if the client/server connection is broken
  219745. oldIOErrorHandler = XSetIOErrorHandler (ioErrorHandler);
  219746. // This is called if a protocol error occurs
  219747. oldErrorHandler = XSetErrorHandler (errorHandler);
  219748. // Install signal handler for break-in
  219749. struct sigaction saction;
  219750. sigset_t maskSet;
  219751. sigemptyset (&maskSet);
  219752. saction.sa_handler = sig_handler;
  219753. saction.sa_mask = maskSet;
  219754. saction.sa_flags = 0;
  219755. sigaction (SIGINT, &saction, NULL);
  219756. #ifndef _DEBUG
  219757. // Setup signal handlers for various fatal errors
  219758. sigaction (SIGILL, &saction, NULL);
  219759. sigaction (SIGBUS, &saction, NULL);
  219760. sigaction (SIGFPE, &saction, NULL);
  219761. sigaction (SIGSEGV, &saction, NULL);
  219762. sigaction (SIGSYS, &saction, NULL);
  219763. #endif
  219764. String displayName (getenv ("DISPLAY"));
  219765. if (displayName.isEmpty())
  219766. displayName = T(":0.0");
  219767. display = XOpenDisplay (displayName);
  219768. if (display == 0)
  219769. {
  219770. // This is fatal! Print error and closedown
  219771. Logger::outputDebugString ("Failed to open the X display.");
  219772. if (juce_isRunningAsApplication())
  219773. Process::terminate();
  219774. return;
  219775. }
  219776. // Get defaults for various properties
  219777. int screen = DefaultScreen (display);
  219778. Window root = RootWindow (display, screen);
  219779. Visual* visual = DefaultVisual (display, screen);
  219780. // Create atoms for our ClientMessages (these cannot be deleted)
  219781. specialId = XInternAtom (display, SpecialAtom, false);
  219782. broadcastId = XInternAtom (display, BroadcastAtom, false);
  219783. specialCallbackId = XInternAtom (display, SpecialCallbackAtom, false);
  219784. // Create a context to store user data associated with Windows we
  219785. // create in WindowDriver
  219786. improbableNumber = XUniqueContext();
  219787. // We're only interested in client messages for this window
  219788. // which are always sent
  219789. XSetWindowAttributes swa;
  219790. swa.event_mask = NoEventMask;
  219791. // Create our message window (this will never be mapped)
  219792. juce_messageWindowHandle = XCreateWindow (display, root,
  219793. 0, 0, 1, 1, 0, 0, InputOnly,
  219794. visual, CWEventMask, &swa);
  219795. }
  219796. void MessageManager::doPlatformSpecificShutdown()
  219797. {
  219798. if (errorCondition == false)
  219799. {
  219800. XDestroyWindow (display, juce_messageWindowHandle);
  219801. XCloseDisplay (display);
  219802. // reset pointers
  219803. juce_messageWindowHandle = 0;
  219804. display = 0;
  219805. // Restore original error handlers
  219806. XSetIOErrorHandler (oldIOErrorHandler);
  219807. oldIOErrorHandler = 0;
  219808. XSetErrorHandler (oldErrorHandler);
  219809. oldErrorHandler = 0;
  219810. }
  219811. }
  219812. bool juce_postMessageToSystemQueue (void* message)
  219813. {
  219814. if (errorCondition)
  219815. return false;
  219816. XClientMessageEvent clientMsg;
  219817. clientMsg.display = display;
  219818. clientMsg.window = juce_messageWindowHandle;
  219819. clientMsg.type = ClientMessage;
  219820. clientMsg.format = 32;
  219821. clientMsg.message_type = specialId;
  219822. #if JUCE_64BIT
  219823. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) message) >> 32));
  219824. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (long) message);
  219825. #else
  219826. clientMsg.data.l[0] = (long) message;
  219827. #endif
  219828. XSendEvent (display, juce_messageWindowHandle, false,
  219829. NoEventMask, (XEvent*) &clientMsg);
  219830. XFlush (display); // This is necessary to ensure the event is delivered
  219831. return true;
  219832. }
  219833. void MessageManager::broadcastMessage (const String& value) throw()
  219834. {
  219835. }
  219836. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* func,
  219837. void* parameter)
  219838. {
  219839. void* retVal = 0;
  219840. if (! errorCondition)
  219841. {
  219842. if (! isThisTheMessageThread())
  219843. {
  219844. static MessageThreadFuncCall messageFuncCallContext;
  219845. const ScopedLock sl (messageFuncCallContext.lock);
  219846. XClientMessageEvent clientMsg;
  219847. clientMsg.display = display;
  219848. clientMsg.window = juce_messageWindowHandle;
  219849. clientMsg.type = ClientMessage;
  219850. clientMsg.format = 32;
  219851. clientMsg.message_type = specialCallbackId;
  219852. #if JUCE_64BIT
  219853. clientMsg.data.l[0] = (long) (0x00000000ffffffff & (((uint64) &messageFuncCallContext) >> 32));
  219854. clientMsg.data.l[1] = (long) (0x00000000ffffffff & (uint64) &messageFuncCallContext);
  219855. #else
  219856. clientMsg.data.l[0] = (long) &messageFuncCallContext;
  219857. #endif
  219858. messageFuncCallContext.func = func;
  219859. messageFuncCallContext.parameter = parameter;
  219860. if (XSendEvent (display, juce_messageWindowHandle, false, NoEventMask, (XEvent*) &clientMsg) == 0)
  219861. return 0;
  219862. XFlush (display); // This is necessary to ensure the event is delivered
  219863. // Wait for it to complete before continuing
  219864. messageFuncCallContext.event.wait();
  219865. retVal = messageFuncCallContext.result;
  219866. }
  219867. else
  219868. {
  219869. // Just call the function directly
  219870. retVal = func (parameter);
  219871. }
  219872. }
  219873. return retVal;
  219874. }
  219875. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  219876. {
  219877. if (errorCondition)
  219878. return false;
  219879. if (breakIn)
  219880. {
  219881. errorCondition = true;
  219882. if (juce_isRunningAsApplication())
  219883. Process::terminate();
  219884. return false;
  219885. }
  219886. if (returnIfNoPendingMessages && ! XPending (display))
  219887. return false;
  219888. XEvent evt;
  219889. XNextEvent (display, &evt);
  219890. if (evt.type == ClientMessage && evt.xany.window == juce_messageWindowHandle)
  219891. {
  219892. XClientMessageEvent* const clientMsg = (XClientMessageEvent*) &evt;
  219893. if (clientMsg->format != 32)
  219894. {
  219895. jassertfalse
  219896. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received malformed client message.");
  219897. }
  219898. else
  219899. {
  219900. JUCE_TRY
  219901. {
  219902. #if JUCE_64BIT
  219903. void* const messagePtr
  219904. = (void*) ((0xffffffff00000000 & (((uint64) clientMsg->data.l[0]) << 32))
  219905. | (clientMsg->data.l[1] & 0x00000000ffffffff));
  219906. #else
  219907. void* const messagePtr = (void*) (clientMsg->data.l[0]);
  219908. #endif
  219909. if (clientMsg->message_type == specialId)
  219910. {
  219911. MessageManager::getInstance()->deliverMessage (messagePtr);
  219912. }
  219913. else if (clientMsg->message_type == specialCallbackId)
  219914. {
  219915. MessageThreadFuncCall* const call = (MessageThreadFuncCall*) messagePtr;
  219916. MessageCallbackFunction* func = call->func;
  219917. call->result = (*func) (call->parameter);
  219918. call->event.signal();
  219919. }
  219920. else if (clientMsg->message_type == broadcastId)
  219921. {
  219922. #if 0
  219923. TCHAR buffer[8192];
  219924. zeromem (buffer, sizeof (buffer));
  219925. if (GlobalGetAtomName ((ATOM) lParam, buffer, 8192) != 0)
  219926. mq->deliverBroadcastMessage (String (buffer));
  219927. #endif
  219928. }
  219929. else
  219930. {
  219931. DBG ("Error: juce_dispatchNextMessageOnSystemQueue received unknown client message.");
  219932. }
  219933. }
  219934. JUCE_CATCH_ALL
  219935. }
  219936. }
  219937. else if (evt.xany.window != juce_messageWindowHandle)
  219938. {
  219939. juce_windowMessageReceive (&evt);
  219940. }
  219941. return true;
  219942. }
  219943. END_JUCE_NAMESPACE
  219944. #endif
  219945. /********* End of inlined file: juce_linux_Messaging.cpp *********/
  219946. /********* Start of inlined file: juce_linux_Midi.cpp *********/
  219947. /********* Start of inlined file: juce_Config.h *********/
  219948. #ifndef __JUCE_CONFIG_JUCEHEADER__
  219949. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  219950. /*
  219951. This file contains macros that enable/disable various JUCE features.
  219952. */
  219953. /** The name of the namespace that all Juce classes and functions will be
  219954. put inside. If this is not defined, no namespace will be used.
  219955. */
  219956. #ifndef JUCE_NAMESPACE
  219957. #define JUCE_NAMESPACE juce
  219958. #endif
  219959. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  219960. but if you define this value, you can override this can force it to be true or
  219961. false.
  219962. */
  219963. #ifndef JUCE_FORCE_DEBUG
  219964. //#define JUCE_FORCE_DEBUG 1
  219965. #endif
  219966. /** If this flag is enabled, the the jassert and jassertfalse macros will
  219967. always use Logger::writeToLog() to write a message when an assertion happens.
  219968. Enabling it will also leave this turned on in release builds. When it's disabled,
  219969. however, the jassert and jassertfalse macros will not be compiled in a
  219970. release build.
  219971. @see jassert, jassertfalse, Logger
  219972. */
  219973. #ifndef JUCE_LOG_ASSERTIONS
  219974. // #define JUCE_LOG_ASSERTIONS 1
  219975. #endif
  219976. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  219977. which the ASIOAudioIODevice class can't be built. See the comments in the
  219978. ASIOAudioIODevice class's header file for more info about this.
  219979. (This only affects a Win32 build)
  219980. */
  219981. #ifndef JUCE_ASIO
  219982. #define JUCE_ASIO 1
  219983. #endif
  219984. /** Comment out this macro to disable building of ALSA device support on Linux.
  219985. */
  219986. #ifndef JUCE_ALSA
  219987. #define JUCE_ALSA 1
  219988. #endif
  219989. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  219990. have the SDK installed.
  219991. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  219992. classes will be unavailable.
  219993. On Windows, if you enable this, you'll need to have the QuickTime SDK
  219994. installed, and its header files will need to be on your include path.
  219995. */
  219996. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  219997. #define JUCE_QUICKTIME 1
  219998. #endif
  219999. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  220000. have the appropriate headers and libraries available. If it's not enabled, the
  220001. OpenGLComponent class will be unavailable.
  220002. */
  220003. #ifndef JUCE_OPENGL
  220004. #define JUCE_OPENGL 1
  220005. #endif
  220006. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  220007. If you're not going to need either of these formats, turn off the flags to
  220008. avoid bloating your codebase with them.
  220009. */
  220010. #ifndef JUCE_USE_FLAC
  220011. #define JUCE_USE_FLAC 1
  220012. #endif
  220013. #ifndef JUCE_USE_OGGVORBIS
  220014. #define JUCE_USE_OGGVORBIS 1
  220015. #endif
  220016. /** This flag lets you enable support for CD-burning. You might want to disable
  220017. it to build without the MS SDK under windows.
  220018. */
  220019. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  220020. #define JUCE_USE_CDBURNER 1
  220021. #endif
  220022. /** Enabling this macro means that all regions that get repainted will have a coloured
  220023. line drawn around them.
  220024. This is handy if you're trying to optimise drawing, because it lets you easily see
  220025. when anything is being repainted unnecessarily.
  220026. */
  220027. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  220028. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  220029. #endif
  220030. /** Enable this under Linux to use Xinerama for multi-monitor support.
  220031. */
  220032. #ifndef JUCE_USE_XINERAMA
  220033. #define JUCE_USE_XINERAMA 1
  220034. #endif
  220035. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  220036. */
  220037. #ifndef JUCE_USE_XSHM
  220038. #define JUCE_USE_XSHM 1
  220039. #endif
  220040. /** Enabling this builds support for VST audio plugins.
  220041. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  220042. */
  220043. #ifndef JUCE_PLUGINHOST_VST
  220044. // #define JUCE_PLUGINHOST_VST 1
  220045. #endif
  220046. /** Enabling this builds support for AudioUnit audio plugins.
  220047. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  220048. */
  220049. #ifndef JUCE_PLUGINHOST_AU
  220050. // #define JUCE_PLUGINHOST_AU 1
  220051. #endif
  220052. /** Disabling this will avoid linking to any UI code. This is handy for
  220053. writing command-line utilities, e.g. on linux boxes which don't have some
  220054. of the UI libraries installed.
  220055. (On mac and windows, this won't generally make much difference to the build).
  220056. */
  220057. #ifndef JUCE_BUILD_GUI_CLASSES
  220058. #define JUCE_BUILD_GUI_CLASSES 1
  220059. #endif
  220060. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  220061. */
  220062. #ifndef JUCE_WEB_BROWSER
  220063. #define JUCE_WEB_BROWSER 1
  220064. #endif
  220065. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  220066. codebase - you might need to use this if you're linking to some of these libraries
  220067. yourself.
  220068. */
  220069. #ifndef JUCE_INCLUDE_ZLIB_CODE
  220070. #define JUCE_INCLUDE_ZLIB_CODE 1
  220071. #endif
  220072. #ifndef JUCE_INCLUDE_FLAC_CODE
  220073. #define JUCE_INCLUDE_FLAC_CODE 1
  220074. #endif
  220075. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  220076. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  220077. #endif
  220078. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  220079. #define JUCE_INCLUDE_PNGLIB_CODE 1
  220080. #endif
  220081. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  220082. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  220083. #endif
  220084. /** Enable this to add extra memory-leak info to the new and delete operators.
  220085. (Currently, this only affects Windows builds in debug mode).
  220086. */
  220087. #ifndef JUCE_CHECK_MEMORY_LEAKS
  220088. #define JUCE_CHECK_MEMORY_LEAKS 1
  220089. #endif
  220090. /** Enable this to turn on juce's internal catching of exceptions.
  220091. Turning it off will avoid any exception catching. With it on, all exceptions
  220092. are passed to the JUCEApplication::unhandledException() callback for logging.
  220093. */
  220094. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  220095. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  220096. #endif
  220097. /** If this macro is set, the Juce String class will use unicode as its
  220098. internal representation. If it isn't set, it'll use ANSI.
  220099. */
  220100. #ifndef JUCE_STRINGS_ARE_UNICODE
  220101. #define JUCE_STRINGS_ARE_UNICODE 1
  220102. #endif
  220103. #endif
  220104. /********* End of inlined file: juce_Config.h *********/
  220105. #if JUCE_BUILD_GUI_CLASSES
  220106. #if JUCE_ALSA
  220107. #include <alsa/asoundlib.h>
  220108. BEGIN_JUCE_NAMESPACE
  220109. static snd_seq_t* iterateDevices (const bool forInput,
  220110. StringArray& deviceNamesFound,
  220111. const int deviceIndexToOpen)
  220112. {
  220113. snd_seq_t* returnedHandle = 0;
  220114. snd_seq_t* seqHandle;
  220115. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  220116. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  220117. {
  220118. snd_seq_system_info_t* systemInfo;
  220119. snd_seq_client_info_t* clientInfo;
  220120. if (snd_seq_system_info_malloc (&systemInfo) == 0)
  220121. {
  220122. if (snd_seq_system_info (seqHandle, systemInfo) == 0
  220123. && snd_seq_client_info_malloc (&clientInfo) == 0)
  220124. {
  220125. int numClients = snd_seq_system_info_get_cur_clients (systemInfo);
  220126. while (--numClients >= 0 && returnedHandle == 0)
  220127. {
  220128. if (snd_seq_query_next_client (seqHandle, clientInfo) == 0)
  220129. {
  220130. snd_seq_port_info_t* portInfo;
  220131. if (snd_seq_port_info_malloc (&portInfo) == 0)
  220132. {
  220133. int numPorts = snd_seq_client_info_get_num_ports (clientInfo);
  220134. const int client = snd_seq_client_info_get_client (clientInfo);
  220135. snd_seq_port_info_set_client (portInfo, client);
  220136. snd_seq_port_info_set_port (portInfo, -1);
  220137. while (--numPorts >= 0)
  220138. {
  220139. if (snd_seq_query_next_port (seqHandle, portInfo) == 0
  220140. && (snd_seq_port_info_get_capability (portInfo)
  220141. & (forInput ? SND_SEQ_PORT_CAP_READ
  220142. : SND_SEQ_PORT_CAP_WRITE)) != 0)
  220143. {
  220144. deviceNamesFound.add (snd_seq_client_info_get_name (clientInfo));
  220145. if (deviceNamesFound.size() == deviceIndexToOpen + 1)
  220146. {
  220147. const int sourcePort = snd_seq_port_info_get_port (portInfo);
  220148. const int sourceClient = snd_seq_client_info_get_client (clientInfo);
  220149. if (sourcePort != -1)
  220150. {
  220151. snd_seq_set_client_name (seqHandle,
  220152. forInput ? "Juce Midi Input"
  220153. : "Juce Midi Output");
  220154. const int portId
  220155. = snd_seq_create_simple_port (seqHandle,
  220156. forInput ? "Juce Midi In Port"
  220157. : "Juce Midi Out Port",
  220158. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  220159. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  220160. SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  220161. snd_seq_connect_from (seqHandle, portId, sourceClient, sourcePort);
  220162. returnedHandle = seqHandle;
  220163. break;
  220164. }
  220165. }
  220166. }
  220167. }
  220168. snd_seq_port_info_free (portInfo);
  220169. }
  220170. }
  220171. }
  220172. snd_seq_client_info_free (clientInfo);
  220173. }
  220174. snd_seq_system_info_free (systemInfo);
  220175. }
  220176. if (returnedHandle == 0)
  220177. snd_seq_close (seqHandle);
  220178. }
  220179. deviceNamesFound.appendNumbersToDuplicates (true, true);
  220180. return returnedHandle;
  220181. }
  220182. static snd_seq_t* createDevice (const bool forInput,
  220183. const String& deviceNameToOpen)
  220184. {
  220185. snd_seq_t* seqHandle = 0;
  220186. if (snd_seq_open (&seqHandle, "default", forInput ? SND_SEQ_OPEN_INPUT
  220187. : SND_SEQ_OPEN_OUTPUT, 0) == 0)
  220188. {
  220189. snd_seq_set_client_name (seqHandle,
  220190. (const char*) (forInput ? (deviceNameToOpen + T(" Input"))
  220191. : (deviceNameToOpen + T(" Output"))));
  220192. const int portId
  220193. = snd_seq_create_simple_port (seqHandle,
  220194. forInput ? "in"
  220195. : "out",
  220196. forInput ? (SND_SEQ_PORT_CAP_WRITE | SND_SEQ_PORT_CAP_SUBS_WRITE)
  220197. : (SND_SEQ_PORT_CAP_READ | SND_SEQ_PORT_CAP_SUBS_READ),
  220198. forInput ? SND_SEQ_PORT_TYPE_APPLICATION
  220199. : SND_SEQ_PORT_TYPE_MIDI_GENERIC);
  220200. if (portId < 0)
  220201. {
  220202. snd_seq_close (seqHandle);
  220203. seqHandle = 0;
  220204. }
  220205. }
  220206. return seqHandle;
  220207. }
  220208. class MidiOutputDevice
  220209. {
  220210. public:
  220211. MidiOutputDevice (MidiOutput* const midiOutput_,
  220212. snd_seq_t* const seqHandle_)
  220213. :
  220214. midiOutput (midiOutput_),
  220215. seqHandle (seqHandle_),
  220216. maxEventSize (16 * 1024)
  220217. {
  220218. jassert (seqHandle != 0 && midiOutput != 0);
  220219. snd_midi_event_new (maxEventSize, &midiParser);
  220220. }
  220221. ~MidiOutputDevice()
  220222. {
  220223. snd_midi_event_free (midiParser);
  220224. snd_seq_close (seqHandle);
  220225. }
  220226. void sendMessageNow (const MidiMessage& message)
  220227. {
  220228. if (message.getRawDataSize() > maxEventSize)
  220229. {
  220230. maxEventSize = message.getRawDataSize();
  220231. snd_midi_event_free (midiParser);
  220232. snd_midi_event_new (maxEventSize, &midiParser);
  220233. }
  220234. snd_seq_event_t event;
  220235. snd_seq_ev_clear (&event);
  220236. snd_midi_event_encode (midiParser,
  220237. message.getRawData(),
  220238. message.getRawDataSize(),
  220239. &event);
  220240. snd_midi_event_reset_encode (midiParser);
  220241. snd_seq_ev_set_source (&event, 0);
  220242. snd_seq_ev_set_subs (&event);
  220243. snd_seq_ev_set_direct (&event);
  220244. snd_seq_event_output_direct (seqHandle, &event);
  220245. }
  220246. juce_UseDebuggingNewOperator
  220247. private:
  220248. MidiOutput* const midiOutput;
  220249. snd_seq_t* const seqHandle;
  220250. snd_midi_event_t* midiParser;
  220251. int maxEventSize;
  220252. };
  220253. const StringArray MidiOutput::getDevices()
  220254. {
  220255. StringArray devices;
  220256. iterateDevices (false, devices, -1);
  220257. return devices;
  220258. }
  220259. int MidiOutput::getDefaultDeviceIndex()
  220260. {
  220261. return 0;
  220262. }
  220263. MidiOutput* MidiOutput::openDevice (int deviceIndex)
  220264. {
  220265. MidiOutput* newDevice = 0;
  220266. StringArray devices;
  220267. snd_seq_t* const handle = iterateDevices (false, devices, deviceIndex);
  220268. if (handle != 0)
  220269. {
  220270. newDevice = new MidiOutput();
  220271. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  220272. }
  220273. return newDevice;
  220274. }
  220275. MidiOutput* MidiOutput::createNewDevice (const String& deviceName)
  220276. {
  220277. MidiOutput* newDevice = 0;
  220278. snd_seq_t* const handle = createDevice (false, deviceName);
  220279. if (handle != 0)
  220280. {
  220281. newDevice = new MidiOutput();
  220282. newDevice->internal = new MidiOutputDevice (newDevice, handle);
  220283. }
  220284. return newDevice;
  220285. }
  220286. MidiOutput::~MidiOutput()
  220287. {
  220288. MidiOutputDevice* const device = (MidiOutputDevice*) internal;
  220289. delete device;
  220290. }
  220291. void MidiOutput::reset()
  220292. {
  220293. }
  220294. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  220295. {
  220296. return false;
  220297. }
  220298. void MidiOutput::setVolume (float leftVol, float rightVol)
  220299. {
  220300. }
  220301. void MidiOutput::sendMessageNow (const MidiMessage& message)
  220302. {
  220303. ((MidiOutputDevice*) internal)->sendMessageNow (message);
  220304. }
  220305. class MidiInputThread : public Thread
  220306. {
  220307. public:
  220308. MidiInputThread (MidiInput* const midiInput_,
  220309. snd_seq_t* const seqHandle_,
  220310. MidiInputCallback* const callback_)
  220311. : Thread (T("Juce MIDI Input")),
  220312. midiInput (midiInput_),
  220313. seqHandle (seqHandle_),
  220314. callback (callback_)
  220315. {
  220316. jassert (seqHandle != 0 && callback != 0 && midiInput != 0);
  220317. }
  220318. ~MidiInputThread()
  220319. {
  220320. snd_seq_close (seqHandle);
  220321. }
  220322. void run()
  220323. {
  220324. const int maxEventSize = 16 * 1024;
  220325. snd_midi_event_t* midiParser;
  220326. if (snd_midi_event_new (maxEventSize, &midiParser) >= 0)
  220327. {
  220328. uint8* const buffer = (uint8*) juce_malloc (maxEventSize);
  220329. const int numPfds = snd_seq_poll_descriptors_count (seqHandle, POLLIN);
  220330. struct pollfd* const pfd = (struct pollfd*) alloca (numPfds * sizeof (struct pollfd));
  220331. snd_seq_poll_descriptors (seqHandle, pfd, numPfds, POLLIN);
  220332. while (! threadShouldExit())
  220333. {
  220334. if (poll (pfd, numPfds, 500) > 0)
  220335. {
  220336. snd_seq_event_t* inputEvent = 0;
  220337. snd_seq_nonblock (seqHandle, 1);
  220338. do
  220339. {
  220340. if (snd_seq_event_input (seqHandle, &inputEvent) >= 0)
  220341. {
  220342. // xxx what about SYSEXes that are too big for the buffer?
  220343. const int numBytes = snd_midi_event_decode (midiParser, buffer, maxEventSize, inputEvent);
  220344. snd_midi_event_reset_decode (midiParser);
  220345. if (numBytes > 0)
  220346. {
  220347. const MidiMessage message ((const uint8*) buffer,
  220348. numBytes,
  220349. Time::getMillisecondCounter() * 0.001);
  220350. callback->handleIncomingMidiMessage (midiInput, message);
  220351. }
  220352. snd_seq_free_event (inputEvent);
  220353. }
  220354. }
  220355. while (snd_seq_event_input_pending (seqHandle, 0) > 0);
  220356. snd_seq_free_event (inputEvent);
  220357. }
  220358. }
  220359. snd_midi_event_free (midiParser);
  220360. juce_free (buffer);
  220361. }
  220362. };
  220363. juce_UseDebuggingNewOperator
  220364. private:
  220365. MidiInput* const midiInput;
  220366. snd_seq_t* const seqHandle;
  220367. MidiInputCallback* const callback;
  220368. };
  220369. MidiInput::MidiInput (const String& name_)
  220370. : name (name_),
  220371. internal (0)
  220372. {
  220373. }
  220374. MidiInput::~MidiInput()
  220375. {
  220376. stop();
  220377. MidiInputThread* const thread = (MidiInputThread*) internal;
  220378. delete thread;
  220379. }
  220380. void MidiInput::start()
  220381. {
  220382. ((MidiInputThread*) internal)->startThread();
  220383. }
  220384. void MidiInput::stop()
  220385. {
  220386. ((MidiInputThread*) internal)->stopThread (3000);
  220387. }
  220388. int MidiInput::getDefaultDeviceIndex()
  220389. {
  220390. return 0;
  220391. }
  220392. const StringArray MidiInput::getDevices()
  220393. {
  220394. StringArray devices;
  220395. iterateDevices (true, devices, -1);
  220396. return devices;
  220397. }
  220398. MidiInput* MidiInput::openDevice (int deviceIndex, MidiInputCallback* callback)
  220399. {
  220400. MidiInput* newDevice = 0;
  220401. StringArray devices;
  220402. snd_seq_t* const handle = iterateDevices (true, devices, deviceIndex);
  220403. if (handle != 0)
  220404. {
  220405. newDevice = new MidiInput (devices [deviceIndex]);
  220406. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  220407. }
  220408. return newDevice;
  220409. }
  220410. MidiInput* MidiInput::createNewDevice (const String& deviceName, MidiInputCallback* callback)
  220411. {
  220412. MidiInput* newDevice = 0;
  220413. snd_seq_t* const handle = createDevice (true, deviceName);
  220414. if (handle != 0)
  220415. {
  220416. newDevice = new MidiInput (deviceName);
  220417. newDevice->internal = new MidiInputThread (newDevice, handle, callback);
  220418. }
  220419. return newDevice;
  220420. }
  220421. END_JUCE_NAMESPACE
  220422. #else
  220423. // (These are just stub functions if ALSA is unavailable...)
  220424. BEGIN_JUCE_NAMESPACE
  220425. const StringArray MidiOutput::getDevices() { return StringArray(); }
  220426. int MidiOutput::getDefaultDeviceIndex() { return 0; }
  220427. MidiOutput* MidiOutput::openDevice (int) { return 0; }
  220428. MidiOutput* MidiOutput::createNewDevice (const String&) { return 0; }
  220429. MidiOutput::~MidiOutput() {}
  220430. void MidiOutput::reset() {}
  220431. bool MidiOutput::getVolume (float&, float&) { return false; }
  220432. void MidiOutput::setVolume (float, float) {}
  220433. void MidiOutput::sendMessageNow (const MidiMessage&) {}
  220434. MidiInput::MidiInput (const String& name_)
  220435. : name (name_),
  220436. internal (0)
  220437. {}
  220438. MidiInput::~MidiInput() {}
  220439. void MidiInput::start() {}
  220440. void MidiInput::stop() {}
  220441. int MidiInput::getDefaultDeviceIndex() { return 0; }
  220442. const StringArray MidiInput::getDevices() { return StringArray(); }
  220443. MidiInput* MidiInput::openDevice (int, MidiInputCallback*) { return 0; }
  220444. MidiInput* MidiInput::createNewDevice (const String&, MidiInputCallback*) { return 0; }
  220445. END_JUCE_NAMESPACE
  220446. #endif
  220447. #endif
  220448. /********* End of inlined file: juce_linux_Midi.cpp *********/
  220449. /********* Start of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  220450. BEGIN_JUCE_NAMESPACE
  220451. #if JUCE_WEB_BROWSER
  220452. /*
  220453. Sorry.. This class isn't implemented on Linux!
  220454. */
  220455. WebBrowserComponent::WebBrowserComponent()
  220456. : browser (0),
  220457. blankPageShown (false)
  220458. {
  220459. setOpaque (true);
  220460. }
  220461. WebBrowserComponent::~WebBrowserComponent()
  220462. {
  220463. }
  220464. void WebBrowserComponent::goToURL (const String& url,
  220465. const StringArray* headers,
  220466. const MemoryBlock* postData)
  220467. {
  220468. lastURL = url;
  220469. lastHeaders.clear();
  220470. if (headers != 0)
  220471. lastHeaders = *headers;
  220472. lastPostData.setSize (0);
  220473. if (postData != 0)
  220474. lastPostData = *postData;
  220475. blankPageShown = false;
  220476. }
  220477. void WebBrowserComponent::stop()
  220478. {
  220479. }
  220480. void WebBrowserComponent::goBack()
  220481. {
  220482. lastURL = String::empty;
  220483. blankPageShown = false;
  220484. }
  220485. void WebBrowserComponent::goForward()
  220486. {
  220487. lastURL = String::empty;
  220488. }
  220489. void WebBrowserComponent::paint (Graphics& g)
  220490. {
  220491. g.fillAll (Colours::white);
  220492. }
  220493. void WebBrowserComponent::checkWindowAssociation()
  220494. {
  220495. }
  220496. void WebBrowserComponent::reloadLastURL()
  220497. {
  220498. if (lastURL.isNotEmpty())
  220499. {
  220500. goToURL (lastURL, &lastHeaders, &lastPostData);
  220501. lastURL = String::empty;
  220502. }
  220503. }
  220504. void WebBrowserComponent::parentHierarchyChanged()
  220505. {
  220506. checkWindowAssociation();
  220507. }
  220508. void WebBrowserComponent::resized()
  220509. {
  220510. }
  220511. void WebBrowserComponent::visibilityChanged()
  220512. {
  220513. checkWindowAssociation();
  220514. }
  220515. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  220516. {
  220517. return true;
  220518. }
  220519. #endif
  220520. END_JUCE_NAMESPACE
  220521. /********* End of inlined file: juce_linux_WebBrowserComponent.cpp *********/
  220522. /********* Start of inlined file: juce_linux_Windowing.cpp *********/
  220523. /********* Start of inlined file: juce_Config.h *********/
  220524. #ifndef __JUCE_CONFIG_JUCEHEADER__
  220525. #define __JUCE_CONFIG_JUCEHEADER__ // (this comment is here to force the amalgamator to reinclude this file)
  220526. /*
  220527. This file contains macros that enable/disable various JUCE features.
  220528. */
  220529. /** The name of the namespace that all Juce classes and functions will be
  220530. put inside. If this is not defined, no namespace will be used.
  220531. */
  220532. #ifndef JUCE_NAMESPACE
  220533. #define JUCE_NAMESPACE juce
  220534. #endif
  220535. /** Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
  220536. but if you define this value, you can override this can force it to be true or
  220537. false.
  220538. */
  220539. #ifndef JUCE_FORCE_DEBUG
  220540. //#define JUCE_FORCE_DEBUG 1
  220541. #endif
  220542. /** If this flag is enabled, the the jassert and jassertfalse macros will
  220543. always use Logger::writeToLog() to write a message when an assertion happens.
  220544. Enabling it will also leave this turned on in release builds. When it's disabled,
  220545. however, the jassert and jassertfalse macros will not be compiled in a
  220546. release build.
  220547. @see jassert, jassertfalse, Logger
  220548. */
  220549. #ifndef JUCE_LOG_ASSERTIONS
  220550. // #define JUCE_LOG_ASSERTIONS 1
  220551. #endif
  220552. /** Comment out this macro if you haven't got the Steinberg ASIO SDK, without
  220553. which the ASIOAudioIODevice class can't be built. See the comments in the
  220554. ASIOAudioIODevice class's header file for more info about this.
  220555. (This only affects a Win32 build)
  220556. */
  220557. #ifndef JUCE_ASIO
  220558. #define JUCE_ASIO 1
  220559. #endif
  220560. /** Comment out this macro to disable building of ALSA device support on Linux.
  220561. */
  220562. #ifndef JUCE_ALSA
  220563. #define JUCE_ALSA 1
  220564. #endif
  220565. /** Comment out this macro if you don't want to enable QuickTime or if you don't
  220566. have the SDK installed.
  220567. If this flag is not enabled, the QuickTimeMovieComponent and QuickTimeAudioFormat
  220568. classes will be unavailable.
  220569. On Windows, if you enable this, you'll need to have the QuickTime SDK
  220570. installed, and its header files will need to be on your include path.
  220571. */
  220572. #if ! (defined (JUCE_QUICKTIME) || defined (LINUX) || (defined (_WIN32) && ! defined (_MSC_VER)))
  220573. #define JUCE_QUICKTIME 1
  220574. #endif
  220575. /** Comment out this macro if you don't want to enable OpenGL or if you don't
  220576. have the appropriate headers and libraries available. If it's not enabled, the
  220577. OpenGLComponent class will be unavailable.
  220578. */
  220579. #ifndef JUCE_OPENGL
  220580. #define JUCE_OPENGL 1
  220581. #endif
  220582. /** These flags enable the Ogg-Vorbis and Flac audio formats.
  220583. If you're not going to need either of these formats, turn off the flags to
  220584. avoid bloating your codebase with them.
  220585. */
  220586. #ifndef JUCE_USE_FLAC
  220587. #define JUCE_USE_FLAC 1
  220588. #endif
  220589. #ifndef JUCE_USE_OGGVORBIS
  220590. #define JUCE_USE_OGGVORBIS 1
  220591. #endif
  220592. /** This flag lets you enable support for CD-burning. You might want to disable
  220593. it to build without the MS SDK under windows.
  220594. */
  220595. #if (! defined (JUCE_USE_CDBURNER)) && ! (defined (_WIN32) && ! defined (_MSC_VER))
  220596. #define JUCE_USE_CDBURNER 1
  220597. #endif
  220598. /** Enabling this macro means that all regions that get repainted will have a coloured
  220599. line drawn around them.
  220600. This is handy if you're trying to optimise drawing, because it lets you easily see
  220601. when anything is being repainted unnecessarily.
  220602. */
  220603. #ifndef JUCE_ENABLE_REPAINT_DEBUGGING
  220604. // #define JUCE_ENABLE_REPAINT_DEBUGGING 1
  220605. #endif
  220606. /** Enable this under Linux to use Xinerama for multi-monitor support.
  220607. */
  220608. #ifndef JUCE_USE_XINERAMA
  220609. #define JUCE_USE_XINERAMA 1
  220610. #endif
  220611. /** Enable this under Linux to use XShm for faster shared-memory rendering.
  220612. */
  220613. #ifndef JUCE_USE_XSHM
  220614. #define JUCE_USE_XSHM 1
  220615. #endif
  220616. /** Enabling this builds support for VST audio plugins.
  220617. @see VSTPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_AU
  220618. */
  220619. #ifndef JUCE_PLUGINHOST_VST
  220620. // #define JUCE_PLUGINHOST_VST 1
  220621. #endif
  220622. /** Enabling this builds support for AudioUnit audio plugins.
  220623. @see AudioUnitPluginFormat, AudioPluginFormat, AudioPluginFormatManager, JUCE_PLUGINHOST_VST
  220624. */
  220625. #ifndef JUCE_PLUGINHOST_AU
  220626. // #define JUCE_PLUGINHOST_AU 1
  220627. #endif
  220628. /** Disabling this will avoid linking to any UI code. This is handy for
  220629. writing command-line utilities, e.g. on linux boxes which don't have some
  220630. of the UI libraries installed.
  220631. (On mac and windows, this won't generally make much difference to the build).
  220632. */
  220633. #ifndef JUCE_BUILD_GUI_CLASSES
  220634. #define JUCE_BUILD_GUI_CLASSES 1
  220635. #endif
  220636. /** This lets you disable building of the WebBrowserComponent, if it's not required.
  220637. */
  220638. #ifndef JUCE_WEB_BROWSER
  220639. #define JUCE_WEB_BROWSER 1
  220640. #endif
  220641. /* These flags let you avoid the direct inclusion of some 3rd-party libs in the
  220642. codebase - you might need to use this if you're linking to some of these libraries
  220643. yourself.
  220644. */
  220645. #ifndef JUCE_INCLUDE_ZLIB_CODE
  220646. #define JUCE_INCLUDE_ZLIB_CODE 1
  220647. #endif
  220648. #ifndef JUCE_INCLUDE_FLAC_CODE
  220649. #define JUCE_INCLUDE_FLAC_CODE 1
  220650. #endif
  220651. #ifndef JUCE_INCLUDE_OGGVORBIS_CODE
  220652. #define JUCE_INCLUDE_OGGVORBIS_CODE 1
  220653. #endif
  220654. #ifndef JUCE_INCLUDE_PNGLIB_CODE
  220655. #define JUCE_INCLUDE_PNGLIB_CODE 1
  220656. #endif
  220657. #ifndef JUCE_INCLUDE_JPEGLIB_CODE
  220658. #define JUCE_INCLUDE_JPEGLIB_CODE 1
  220659. #endif
  220660. /** Enable this to add extra memory-leak info to the new and delete operators.
  220661. (Currently, this only affects Windows builds in debug mode).
  220662. */
  220663. #ifndef JUCE_CHECK_MEMORY_LEAKS
  220664. #define JUCE_CHECK_MEMORY_LEAKS 1
  220665. #endif
  220666. /** Enable this to turn on juce's internal catching of exceptions.
  220667. Turning it off will avoid any exception catching. With it on, all exceptions
  220668. are passed to the JUCEApplication::unhandledException() callback for logging.
  220669. */
  220670. #ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
  220671. #define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
  220672. #endif
  220673. /** If this macro is set, the Juce String class will use unicode as its
  220674. internal representation. If it isn't set, it'll use ANSI.
  220675. */
  220676. #ifndef JUCE_STRINGS_ARE_UNICODE
  220677. #define JUCE_STRINGS_ARE_UNICODE 1
  220678. #endif
  220679. #endif
  220680. /********* End of inlined file: juce_Config.h *********/
  220681. #if JUCE_BUILD_GUI_CLASSES
  220682. #include <X11/Xlib.h>
  220683. #include <X11/Xutil.h>
  220684. #include <X11/Xatom.h>
  220685. #include <X11/Xmd.h>
  220686. #include <X11/keysym.h>
  220687. #include <X11/cursorfont.h>
  220688. #include <dlfcn.h>
  220689. #if JUCE_USE_XINERAMA
  220690. /* If you're trying to use Xinerama, you'll need to install the "libxinerama-dev" package..
  220691. */
  220692. #include <X11/extensions/Xinerama.h>
  220693. #endif
  220694. #if JUCE_USE_XSHM
  220695. #include <X11/extensions/XShm.h>
  220696. #include <sys/shm.h>
  220697. #include <sys/ipc.h>
  220698. #endif
  220699. #if JUCE_OPENGL
  220700. /* Got an include error here?
  220701. If you want to install OpenGL support, the packages to get are "mesa-common-dev"
  220702. and "freeglut3-dev".
  220703. Alternatively, you can turn off the JUCE_OPENGL flag in juce_Config.h if you
  220704. want to disable it.
  220705. */
  220706. #include <GL/glx.h>
  220707. #endif
  220708. #undef KeyPress
  220709. BEGIN_JUCE_NAMESPACE
  220710. #define TAKE_FOCUS 0
  220711. #define DELETE_WINDOW 1
  220712. #define SYSTEM_TRAY_REQUEST_DOCK 0
  220713. #define SYSTEM_TRAY_BEGIN_MESSAGE 1
  220714. #define SYSTEM_TRAY_CANCEL_MESSAGE 2
  220715. static const int repaintTimerPeriod = 1000 / 100; // 100 fps maximum
  220716. static Atom wm_ChangeState = None;
  220717. static Atom wm_State = None;
  220718. static Atom wm_Protocols = None;
  220719. static Atom wm_ProtocolList [2] = { None, None };
  220720. static Atom wm_ActiveWin = None;
  220721. #define ourDndVersion 3
  220722. static Atom XA_XdndAware = None;
  220723. static Atom XA_XdndEnter = None;
  220724. static Atom XA_XdndLeave = None;
  220725. static Atom XA_XdndPosition = None;
  220726. static Atom XA_XdndStatus = None;
  220727. static Atom XA_XdndDrop = None;
  220728. static Atom XA_XdndFinished = None;
  220729. static Atom XA_XdndSelection = None;
  220730. static Atom XA_XdndProxy = None;
  220731. static Atom XA_XdndTypeList = None;
  220732. static Atom XA_XdndActionList = None;
  220733. static Atom XA_XdndActionDescription = None;
  220734. static Atom XA_XdndActionCopy = None;
  220735. static Atom XA_XdndActionMove = None;
  220736. static Atom XA_XdndActionLink = None;
  220737. static Atom XA_XdndActionAsk = None;
  220738. static Atom XA_XdndActionPrivate = None;
  220739. static Atom XA_JXSelectionWindowProperty = None;
  220740. static Atom XA_MimeTextPlain = None;
  220741. static Atom XA_MimeTextUriList = None;
  220742. static Atom XA_MimeRootDrop = None;
  220743. static XErrorHandler oldHandler = 0;
  220744. static int trappedErrorCode = 0;
  220745. extern "C" int errorTrapHandler (Display* dpy, XErrorEvent* err)
  220746. {
  220747. trappedErrorCode = err->error_code;
  220748. return 0;
  220749. }
  220750. static void trapErrors()
  220751. {
  220752. trappedErrorCode = 0;
  220753. oldHandler = XSetErrorHandler (errorTrapHandler);
  220754. }
  220755. static bool untrapErrors()
  220756. {
  220757. XSetErrorHandler (oldHandler);
  220758. return (trappedErrorCode == 0);
  220759. }
  220760. static bool isActiveApplication = false;
  220761. bool Process::isForegroundProcess() throw()
  220762. {
  220763. return isActiveApplication;
  220764. }
  220765. // (used in the messaging code, declared here for build reasons)
  220766. bool juce_isRunningAsApplication()
  220767. {
  220768. return JUCEApplication::getInstance() != 0;
  220769. }
  220770. // These are defined in juce_linux_Messaging.cpp
  220771. extern Display* display;
  220772. extern XContext improbableNumber;
  220773. static const int eventMask = NoEventMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask
  220774. | EnterWindowMask | LeaveWindowMask | PointerMotionMask | KeymapStateMask
  220775. | ExposureMask | StructureNotifyMask | FocusChangeMask;
  220776. static int pointerMap[5];
  220777. static int lastMousePosX = 0, lastMousePosY = 0;
  220778. enum MouseButtons
  220779. {
  220780. NoButton = 0,
  220781. LeftButton = 1,
  220782. MiddleButton = 2,
  220783. RightButton = 3,
  220784. WheelUp = 4,
  220785. WheelDown = 5
  220786. };
  220787. static void getMousePos (int& x, int& y, int& mouseMods) throw()
  220788. {
  220789. Window root, child;
  220790. int winx, winy;
  220791. unsigned int mask;
  220792. mouseMods = 0;
  220793. if (XQueryPointer (display,
  220794. RootWindow (display, DefaultScreen (display)),
  220795. &root, &child,
  220796. &x, &y, &winx, &winy, &mask) == False)
  220797. {
  220798. // Pointer not on the default screen
  220799. x = y = -1;
  220800. }
  220801. else
  220802. {
  220803. if ((mask & Button1Mask) != 0)
  220804. mouseMods |= ModifierKeys::leftButtonModifier;
  220805. if ((mask & Button2Mask) != 0)
  220806. mouseMods |= ModifierKeys::middleButtonModifier;
  220807. if ((mask & Button3Mask) != 0)
  220808. mouseMods |= ModifierKeys::rightButtonModifier;
  220809. }
  220810. }
  220811. static int AltMask = 0;
  220812. static int NumLockMask = 0;
  220813. static bool numLock = 0;
  220814. static bool capsLock = 0;
  220815. static char keyStates [32];
  220816. static void updateKeyStates (const int keycode, const bool press) throw()
  220817. {
  220818. const int keybyte = keycode >> 3;
  220819. const int keybit = (1 << (keycode & 7));
  220820. if (press)
  220821. keyStates [keybyte] |= keybit;
  220822. else
  220823. keyStates [keybyte] &= ~keybit;
  220824. }
  220825. static bool keyDown (const int keycode) throw()
  220826. {
  220827. const int keybyte = keycode >> 3;
  220828. const int keybit = (1 << (keycode & 7));
  220829. return (keyStates [keybyte] & keybit) != 0;
  220830. }
  220831. static const int extendedKeyModifier = 0x10000000;
  220832. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  220833. {
  220834. int keysym;
  220835. if (keyCode & extendedKeyModifier)
  220836. {
  220837. keysym = 0xff00 | (keyCode & 0xff);
  220838. }
  220839. else
  220840. {
  220841. keysym = keyCode;
  220842. if (keysym == (XK_Tab & 0xff)
  220843. || keysym == (XK_Return & 0xff)
  220844. || keysym == (XK_Escape & 0xff)
  220845. || keysym == (XK_BackSpace & 0xff))
  220846. {
  220847. keysym |= 0xff00;
  220848. }
  220849. }
  220850. return keyDown (XKeysymToKeycode (display, keysym));
  220851. }
  220852. // Alt and Num lock are not defined by standard X
  220853. // modifier constants: check what they're mapped to
  220854. static void getModifierMapping() throw()
  220855. {
  220856. const int altLeftCode = XKeysymToKeycode (display, XK_Alt_L);
  220857. const int numLockCode = XKeysymToKeycode (display, XK_Num_Lock);
  220858. AltMask = 0;
  220859. NumLockMask = 0;
  220860. XModifierKeymap* mapping = XGetModifierMapping (display);
  220861. if (mapping)
  220862. {
  220863. for (int i = 0; i < 8; i++)
  220864. {
  220865. if (mapping->modifiermap [i << 1] == altLeftCode)
  220866. AltMask = 1 << i;
  220867. else if (mapping->modifiermap [i << 1] == numLockCode)
  220868. NumLockMask = 1 << i;
  220869. }
  220870. XFreeModifiermap (mapping);
  220871. }
  220872. }
  220873. static int currentModifiers = 0;
  220874. void ModifierKeys::updateCurrentModifiers() throw()
  220875. {
  220876. currentModifierFlags = currentModifiers;
  220877. }
  220878. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  220879. {
  220880. int x, y, mouseMods;
  220881. getMousePos (x, y, mouseMods);
  220882. currentModifiers &= ~ModifierKeys::allMouseButtonModifiers;
  220883. currentModifiers |= mouseMods;
  220884. return ModifierKeys (currentModifiers);
  220885. }
  220886. static void updateKeyModifiers (const int status) throw()
  220887. {
  220888. currentModifiers &= ~(ModifierKeys::shiftModifier
  220889. | ModifierKeys::ctrlModifier
  220890. | ModifierKeys::altModifier);
  220891. if (status & ShiftMask)
  220892. currentModifiers |= ModifierKeys::shiftModifier;
  220893. if (status & ControlMask)
  220894. currentModifiers |= ModifierKeys::ctrlModifier;
  220895. if (status & AltMask)
  220896. currentModifiers |= ModifierKeys::altModifier;
  220897. numLock = ((status & NumLockMask) != 0);
  220898. capsLock = ((status & LockMask) != 0);
  220899. }
  220900. static bool updateKeyModifiersFromSym (KeySym sym, const bool press) throw()
  220901. {
  220902. int modifier = 0;
  220903. bool isModifier = true;
  220904. switch (sym)
  220905. {
  220906. case XK_Shift_L:
  220907. case XK_Shift_R:
  220908. modifier = ModifierKeys::shiftModifier;
  220909. break;
  220910. case XK_Control_L:
  220911. case XK_Control_R:
  220912. modifier = ModifierKeys::ctrlModifier;
  220913. break;
  220914. case XK_Alt_L:
  220915. case XK_Alt_R:
  220916. modifier = ModifierKeys::altModifier;
  220917. break;
  220918. case XK_Num_Lock:
  220919. if (press)
  220920. numLock = ! numLock;
  220921. break;
  220922. case XK_Caps_Lock:
  220923. if (press)
  220924. capsLock = ! capsLock;
  220925. break;
  220926. case XK_Scroll_Lock:
  220927. break;
  220928. default:
  220929. isModifier = false;
  220930. break;
  220931. }
  220932. if (modifier != 0)
  220933. {
  220934. if (press)
  220935. currentModifiers |= modifier;
  220936. else
  220937. currentModifiers &= ~modifier;
  220938. }
  220939. return isModifier;
  220940. }
  220941. #if JUCE_USE_XSHM
  220942. static bool isShmAvailable() throw()
  220943. {
  220944. static bool isChecked = false;
  220945. static bool isAvailable = false;
  220946. if (! isChecked)
  220947. {
  220948. isChecked = true;
  220949. int major, minor;
  220950. Bool pixmaps;
  220951. if (XShmQueryVersion (display, &major, &minor, &pixmaps))
  220952. {
  220953. trapErrors();
  220954. XShmSegmentInfo segmentInfo;
  220955. zerostruct (segmentInfo);
  220956. XImage* xImage = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  220957. 24, ZPixmap, 0, &segmentInfo, 50, 50);
  220958. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  220959. xImage->bytes_per_line * xImage->height,
  220960. IPC_CREAT | 0777)) >= 0)
  220961. {
  220962. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  220963. if (segmentInfo.shmaddr != (void*) -1)
  220964. {
  220965. segmentInfo.readOnly = False;
  220966. xImage->data = segmentInfo.shmaddr;
  220967. XSync (display, False);
  220968. if (XShmAttach (display, &segmentInfo) != 0)
  220969. {
  220970. XSync (display, False);
  220971. XShmDetach (display, &segmentInfo);
  220972. isAvailable = true;
  220973. }
  220974. }
  220975. XFlush (display);
  220976. XDestroyImage (xImage);
  220977. shmdt (segmentInfo.shmaddr);
  220978. }
  220979. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  220980. isAvailable &= untrapErrors();
  220981. }
  220982. }
  220983. return isAvailable;
  220984. }
  220985. #endif
  220986. static Pixmap juce_createColourPixmapFromImage (Display* display, const Image& image)
  220987. {
  220988. const int width = image.getWidth();
  220989. const int height = image.getHeight();
  220990. uint32* const colour = (uint32*) juce_malloc (width * height * sizeof (uint32));
  220991. int index = 0;
  220992. for (int y = 0; y < height; ++y)
  220993. for (int x = 0; x < width; ++x)
  220994. colour[index++] = image.getPixelAt (x, y).getARGB();
  220995. XImage* ximage = XCreateImage (display, CopyFromParent, 24, ZPixmap,
  220996. 0, (char*) colour, width, height, 32, 0);
  220997. Pixmap pixmap = XCreatePixmap (display, DefaultRootWindow (display),
  220998. width, height, 24);
  220999. GC gc = XCreateGC (display, pixmap, 0, 0);
  221000. XPutImage (display, pixmap, gc, ximage, 0, 0, 0, 0, width, height);
  221001. XFreeGC (display, gc);
  221002. juce_free (colour);
  221003. return pixmap;
  221004. }
  221005. static Pixmap juce_createMaskPixmapFromImage (Display* display, const Image& image)
  221006. {
  221007. const int width = image.getWidth();
  221008. const int height = image.getHeight();
  221009. const int stride = (width + 7) >> 3;
  221010. uint8* const mask = (uint8*) juce_calloc (stride * height);
  221011. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  221012. for (int y = 0; y < height; ++y)
  221013. {
  221014. for (int x = 0; x < width; ++x)
  221015. {
  221016. const uint8 bit = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  221017. const int offset = y * stride + (x >> 3);
  221018. if (image.getPixelAt (x, y).getAlpha() >= 128)
  221019. mask[offset] |= bit;
  221020. }
  221021. }
  221022. Pixmap pixmap = XCreatePixmapFromBitmapData (display, DefaultRootWindow (display),
  221023. (char*) mask, width, height, 1, 0, 1);
  221024. juce_free (mask);
  221025. return pixmap;
  221026. }
  221027. class XBitmapImage : public Image
  221028. {
  221029. public:
  221030. XBitmapImage (const PixelFormat format_, const int w, const int h,
  221031. const bool clearImage, const bool is16Bit_)
  221032. : Image (format_, w, h),
  221033. is16Bit (is16Bit_)
  221034. {
  221035. jassert (format_ == RGB || format_ == ARGB);
  221036. pixelStride = (format_ == RGB) ? 3 : 4;
  221037. lineStride = ((w * pixelStride + 3) & ~3);
  221038. Visual* const visual = DefaultVisual (display, DefaultScreen (display));
  221039. #if JUCE_USE_XSHM
  221040. usingXShm = false;
  221041. if ((! is16Bit) && isShmAvailable())
  221042. {
  221043. zerostruct (segmentInfo);
  221044. xImage = XShmCreateImage (display, visual, 24, ZPixmap, 0, &segmentInfo, w, h);
  221045. if (xImage != 0)
  221046. {
  221047. if ((segmentInfo.shmid = shmget (IPC_PRIVATE,
  221048. xImage->bytes_per_line * xImage->height,
  221049. IPC_CREAT | 0777)) >= 0)
  221050. {
  221051. segmentInfo.shmaddr = (char*) shmat (segmentInfo.shmid, 0, 0);
  221052. if (segmentInfo.shmaddr != (void*) -1)
  221053. {
  221054. segmentInfo.readOnly = False;
  221055. xImage->data = segmentInfo.shmaddr;
  221056. imageData = (uint8*) segmentInfo.shmaddr;
  221057. XSync (display, False);
  221058. if (XShmAttach (display, &segmentInfo) != 0)
  221059. {
  221060. XSync (display, False);
  221061. usingXShm = true;
  221062. }
  221063. else
  221064. {
  221065. jassertfalse
  221066. }
  221067. }
  221068. else
  221069. {
  221070. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  221071. }
  221072. }
  221073. }
  221074. }
  221075. if (! usingXShm)
  221076. #endif
  221077. {
  221078. imageData = (uint8*) juce_malloc (lineStride * h);
  221079. if (format_ == ARGB && clearImage)
  221080. zeromem (imageData, h * lineStride);
  221081. xImage = (XImage*) juce_calloc (sizeof (XImage));
  221082. xImage->width = w;
  221083. xImage->height = h;
  221084. xImage->xoffset = 0;
  221085. xImage->format = ZPixmap;
  221086. xImage->data = (char*) imageData;
  221087. xImage->byte_order = ImageByteOrder (display);
  221088. xImage->bitmap_unit = BitmapUnit (display);
  221089. xImage->bitmap_bit_order = BitmapBitOrder (display);
  221090. xImage->bitmap_pad = 32;
  221091. xImage->depth = pixelStride * 8;
  221092. xImage->bytes_per_line = lineStride;
  221093. xImage->bits_per_pixel = pixelStride * 8;
  221094. xImage->red_mask = 0x00FF0000;
  221095. xImage->green_mask = 0x0000FF00;
  221096. xImage->blue_mask = 0x000000FF;
  221097. if (is16Bit)
  221098. {
  221099. const int pixelStride = 2;
  221100. const int lineStride = ((w * pixelStride + 3) & ~3);
  221101. xImage->data = (char*) juce_malloc (lineStride * h);
  221102. xImage->bitmap_pad = 16;
  221103. xImage->depth = pixelStride * 8;
  221104. xImage->bytes_per_line = lineStride;
  221105. xImage->bits_per_pixel = pixelStride * 8;
  221106. xImage->red_mask = visual->red_mask;
  221107. xImage->green_mask = visual->green_mask;
  221108. xImage->blue_mask = visual->blue_mask;
  221109. }
  221110. if (! XInitImage (xImage))
  221111. {
  221112. jassertfalse
  221113. }
  221114. }
  221115. }
  221116. ~XBitmapImage()
  221117. {
  221118. #if JUCE_USE_XSHM
  221119. if (usingXShm)
  221120. {
  221121. XShmDetach (display, &segmentInfo);
  221122. XFlush (display);
  221123. XDestroyImage (xImage);
  221124. shmdt (segmentInfo.shmaddr);
  221125. shmctl (segmentInfo.shmid, IPC_RMID, 0);
  221126. }
  221127. else
  221128. #endif
  221129. {
  221130. juce_free (xImage->data);
  221131. xImage->data = 0;
  221132. XDestroyImage (xImage);
  221133. }
  221134. if (! is16Bit)
  221135. imageData = 0; // to stop the base class freeing this (for the 16-bit version we want it to free it)
  221136. }
  221137. void blitToWindow (Window window, int dx, int dy, int dw, int dh, int sx, int sy)
  221138. {
  221139. static GC gc = 0;
  221140. if (gc == 0)
  221141. gc = DefaultGC (display, DefaultScreen (display));
  221142. if (is16Bit)
  221143. {
  221144. const uint32 rMask = xImage->red_mask;
  221145. const uint32 rShiftL = jmax (0, getShiftNeeded (rMask));
  221146. const uint32 rShiftR = jmax (0, -getShiftNeeded (rMask));
  221147. const uint32 gMask = xImage->green_mask;
  221148. const uint32 gShiftL = jmax (0, getShiftNeeded (gMask));
  221149. const uint32 gShiftR = jmax (0, -getShiftNeeded (gMask));
  221150. const uint32 bMask = xImage->blue_mask;
  221151. const uint32 bShiftL = jmax (0, getShiftNeeded (bMask));
  221152. const uint32 bShiftR = jmax (0, -getShiftNeeded (bMask));
  221153. int ls, ps;
  221154. const uint8* const pixels = lockPixelDataReadOnly (0, 0, getWidth(), getHeight(), ls, ps);
  221155. jassert (! isARGB())
  221156. for (int y = sy; y < sy + dh; ++y)
  221157. {
  221158. const uint8* p = pixels + y * ls + sx * ps;
  221159. for (int x = sx; x < sx + dw; ++x)
  221160. {
  221161. const PixelRGB* const pixel = (const PixelRGB*) p;
  221162. p += ps;
  221163. XPutPixel (xImage, x, y,
  221164. (((((uint32) pixel->getRed()) << rShiftL) >> rShiftR) & rMask)
  221165. | (((((uint32) pixel->getGreen()) << gShiftL) >> gShiftR) & gMask)
  221166. | (((((uint32) pixel->getBlue()) << bShiftL) >> bShiftR) & bMask));
  221167. }
  221168. }
  221169. releasePixelDataReadOnly (pixels);
  221170. }
  221171. // blit results to screen.
  221172. #if JUCE_USE_XSHM
  221173. if (usingXShm)
  221174. XShmPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh, False);
  221175. else
  221176. #endif
  221177. XPutImage (display, (::Drawable) window, gc, xImage, sx, sy, dx, dy, dw, dh);
  221178. }
  221179. juce_UseDebuggingNewOperator
  221180. private:
  221181. XImage* xImage;
  221182. const bool is16Bit;
  221183. #if JUCE_USE_XSHM
  221184. XShmSegmentInfo segmentInfo;
  221185. bool usingXShm;
  221186. #endif
  221187. static int getShiftNeeded (const uint32 mask) throw()
  221188. {
  221189. for (int i = 32; --i >= 0;)
  221190. if (((mask >> i) & 1) != 0)
  221191. return i - 7;
  221192. jassertfalse
  221193. return 0;
  221194. }
  221195. };
  221196. #define checkMessageManagerIsLocked jassert (MessageManager::getInstance()->currentThreadHasLockedMessageManager());
  221197. class LinuxComponentPeer : public ComponentPeer
  221198. {
  221199. public:
  221200. LinuxComponentPeer (Component* const component, const int windowStyleFlags)
  221201. : ComponentPeer (component, windowStyleFlags),
  221202. windowH (0),
  221203. parentWindow (0),
  221204. wx (0),
  221205. wy (0),
  221206. ww (0),
  221207. wh (0),
  221208. taskbarImage (0),
  221209. fullScreen (false),
  221210. entered (false),
  221211. mapped (false)
  221212. {
  221213. // it's dangerous to create a window on a thread other than the message thread..
  221214. checkMessageManagerIsLocked
  221215. repainter = new LinuxRepaintManager (this);
  221216. createWindow();
  221217. setTitle (component->getName());
  221218. }
  221219. ~LinuxComponentPeer()
  221220. {
  221221. // it's dangerous to delete a window on a thread other than the message thread..
  221222. checkMessageManagerIsLocked
  221223. deleteTaskBarIcon();
  221224. deleteIconPixmaps();
  221225. destroyWindow();
  221226. windowH = 0;
  221227. delete repainter;
  221228. }
  221229. void* getNativeHandle() const
  221230. {
  221231. return (void*) windowH;
  221232. }
  221233. static LinuxComponentPeer* getPeerFor (Window windowHandle) throw()
  221234. {
  221235. XPointer peer = 0;
  221236. if (! XFindContext (display, (XID) windowHandle, improbableNumber, &peer))
  221237. {
  221238. if (peer != 0 && ! ((LinuxComponentPeer*) peer)->isValidMessageListener())
  221239. peer = 0;
  221240. }
  221241. return (LinuxComponentPeer*) peer;
  221242. }
  221243. void setVisible (bool shouldBeVisible)
  221244. {
  221245. if (shouldBeVisible)
  221246. XMapWindow (display, windowH);
  221247. else
  221248. XUnmapWindow (display, windowH);
  221249. }
  221250. void setTitle (const String& title)
  221251. {
  221252. setWindowTitle (windowH, title);
  221253. }
  221254. void setPosition (int x, int y)
  221255. {
  221256. setBounds (x, y, ww, wh, false);
  221257. }
  221258. void setSize (int w, int h)
  221259. {
  221260. setBounds (wx, wy, w, h, false);
  221261. }
  221262. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  221263. {
  221264. fullScreen = isNowFullScreen;
  221265. if (windowH != 0)
  221266. {
  221267. const ComponentDeletionWatcher deletionChecker (component);
  221268. wx = x;
  221269. wy = y;
  221270. ww = jmax (1, w);
  221271. wh = jmax (1, h);
  221272. if (! mapped)
  221273. {
  221274. // Make sure the Window manager does what we want
  221275. XSizeHints* hints = XAllocSizeHints();
  221276. hints->flags = USSize | USPosition;
  221277. hints->width = ww + windowBorder.getLeftAndRight();
  221278. hints->height = wh + windowBorder.getTopAndBottom();
  221279. hints->x = wx - windowBorder.getLeft();
  221280. hints->y = wy - windowBorder.getTop();
  221281. XSetWMNormalHints (display, windowH, hints);
  221282. XFree (hints);
  221283. }
  221284. XMoveResizeWindow (display, windowH,
  221285. wx - windowBorder.getLeft(),
  221286. wy - windowBorder.getTop(),
  221287. ww + windowBorder.getLeftAndRight(),
  221288. wh + windowBorder.getTopAndBottom());
  221289. if (! deletionChecker.hasBeenDeleted())
  221290. {
  221291. updateBorderSize();
  221292. handleMovedOrResized();
  221293. }
  221294. }
  221295. }
  221296. void getBounds (int& x, int& y, int& w, int& h) const
  221297. {
  221298. x = wx;
  221299. y = wy;
  221300. w = ww;
  221301. h = wh;
  221302. }
  221303. int getScreenX() const
  221304. {
  221305. return wx;
  221306. }
  221307. int getScreenY() const
  221308. {
  221309. return wy;
  221310. }
  221311. void relativePositionToGlobal (int& x, int& y)
  221312. {
  221313. x += wx;
  221314. y += wy;
  221315. }
  221316. void globalPositionToRelative (int& x, int& y)
  221317. {
  221318. x -= wx;
  221319. y -= wy;
  221320. }
  221321. void setMinimised (bool shouldBeMinimised)
  221322. {
  221323. if (shouldBeMinimised)
  221324. {
  221325. Window root = RootWindow (display, DefaultScreen (display));
  221326. XClientMessageEvent clientMsg;
  221327. clientMsg.display = display;
  221328. clientMsg.window = windowH;
  221329. clientMsg.type = ClientMessage;
  221330. clientMsg.format = 32;
  221331. clientMsg.message_type = wm_ChangeState;
  221332. clientMsg.data.l[0] = IconicState;
  221333. XSendEvent (display, root, false,
  221334. SubstructureRedirectMask | SubstructureNotifyMask,
  221335. (XEvent*) &clientMsg);
  221336. }
  221337. else
  221338. {
  221339. setVisible (true);
  221340. }
  221341. }
  221342. bool isMinimised() const
  221343. {
  221344. bool minimised = false;
  221345. unsigned char* stateProp;
  221346. unsigned long nitems, bytesLeft;
  221347. Atom actualType;
  221348. int actualFormat;
  221349. if (XGetWindowProperty (display, windowH, wm_State, 0, 64, False,
  221350. wm_State, &actualType, &actualFormat, &nitems, &bytesLeft,
  221351. &stateProp) == Success
  221352. && actualType == wm_State
  221353. && actualFormat == 32
  221354. && nitems > 0)
  221355. {
  221356. if (((unsigned long*) stateProp)[0] == IconicState)
  221357. minimised = true;
  221358. XFree (stateProp);
  221359. }
  221360. return minimised;
  221361. }
  221362. void setFullScreen (const bool shouldBeFullScreen)
  221363. {
  221364. Rectangle r (lastNonFullscreenBounds); // (get a copy of this before de-minimising)
  221365. setMinimised (false);
  221366. if (fullScreen != shouldBeFullScreen)
  221367. {
  221368. if (shouldBeFullScreen)
  221369. r = Desktop::getInstance().getMainMonitorArea();
  221370. if (! r.isEmpty())
  221371. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  221372. getComponent()->repaint();
  221373. }
  221374. }
  221375. bool isFullScreen() const
  221376. {
  221377. return fullScreen;
  221378. }
  221379. bool isChildWindowOf (Window possibleParent) const
  221380. {
  221381. Window* windowList = 0;
  221382. uint32 windowListSize = 0;
  221383. Window parent, root;
  221384. if (XQueryTree (display, windowH, &root, &parent, &windowList, &windowListSize) != 0)
  221385. {
  221386. if (windowList != 0)
  221387. XFree (windowList);
  221388. return parent == possibleParent;
  221389. }
  221390. return false;
  221391. }
  221392. bool isFrontWindow() const
  221393. {
  221394. Window* windowList = 0;
  221395. uint32 windowListSize = 0;
  221396. bool result = false;
  221397. Window parent, root = RootWindow (display, DefaultScreen (display));
  221398. if (XQueryTree (display, root, &root, &parent, &windowList, &windowListSize) != 0)
  221399. {
  221400. for (int i = windowListSize; --i >= 0;)
  221401. {
  221402. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (windowList[i]);
  221403. if (peer != 0)
  221404. {
  221405. result = (peer == this);
  221406. break;
  221407. }
  221408. }
  221409. }
  221410. if (windowList != 0)
  221411. XFree (windowList);
  221412. return result;
  221413. }
  221414. bool contains (int x, int y, bool trueIfInAChildWindow) const
  221415. {
  221416. jassert (x >= 0 && y >= 0 && x < ww && y < wh); // should only be called for points that are actually inside the bounds
  221417. if (((unsigned int) x) >= (unsigned int) ww
  221418. || ((unsigned int) y) >= (unsigned int) wh)
  221419. return false;
  221420. bool inFront = false;
  221421. for (int i = 0; i < Desktop::getInstance().getNumComponents(); ++i)
  221422. {
  221423. Component* const c = Desktop::getInstance().getComponent (i);
  221424. if (inFront)
  221425. {
  221426. if (c->contains (x + wx - c->getScreenX(),
  221427. y + wy - c->getScreenY()))
  221428. {
  221429. return false;
  221430. }
  221431. }
  221432. else if (c == getComponent())
  221433. {
  221434. inFront = true;
  221435. }
  221436. }
  221437. if (trueIfInAChildWindow)
  221438. return true;
  221439. ::Window root, child;
  221440. unsigned int bw, depth;
  221441. int wx, wy, w, h;
  221442. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  221443. &wx, &wy, (unsigned int*) &w, (unsigned int*) &h,
  221444. &bw, &depth))
  221445. {
  221446. return false;
  221447. }
  221448. if (! XTranslateCoordinates (display, windowH, windowH, x, y, &wx, &wy, &child))
  221449. return false;
  221450. return child == None;
  221451. }
  221452. const BorderSize getFrameSize() const
  221453. {
  221454. return BorderSize();
  221455. }
  221456. bool setAlwaysOnTop (bool alwaysOnTop)
  221457. {
  221458. if (windowH != 0)
  221459. {
  221460. const bool wasVisible = component->isVisible();
  221461. if (wasVisible)
  221462. setVisible (false); // doesn't always seem to work if the window is visible when this is done..
  221463. XSetWindowAttributes swa;
  221464. swa.override_redirect = alwaysOnTop ? True : False;
  221465. XChangeWindowAttributes (display, windowH, CWOverrideRedirect, &swa);
  221466. if (wasVisible)
  221467. setVisible (true);
  221468. }
  221469. return true;
  221470. }
  221471. void toFront (bool makeActive)
  221472. {
  221473. if (makeActive)
  221474. {
  221475. setVisible (true);
  221476. grabFocus();
  221477. }
  221478. XEvent ev;
  221479. ev.xclient.type = ClientMessage;
  221480. ev.xclient.serial = 0;
  221481. ev.xclient.send_event = True;
  221482. ev.xclient.message_type = wm_ActiveWin;
  221483. ev.xclient.window = windowH;
  221484. ev.xclient.format = 32;
  221485. ev.xclient.data.l[0] = 2;
  221486. ev.xclient.data.l[1] = CurrentTime;
  221487. ev.xclient.data.l[2] = 0;
  221488. ev.xclient.data.l[3] = 0;
  221489. ev.xclient.data.l[4] = 0;
  221490. XSendEvent (display, RootWindow (display, DefaultScreen (display)),
  221491. False,
  221492. SubstructureRedirectMask | SubstructureNotifyMask,
  221493. &ev);
  221494. XSync (display, False);
  221495. handleBroughtToFront();
  221496. }
  221497. void toBehind (ComponentPeer* other)
  221498. {
  221499. LinuxComponentPeer* const otherPeer = dynamic_cast <LinuxComponentPeer*> (other);
  221500. jassert (otherPeer != 0); // wrong type of window?
  221501. if (otherPeer != 0)
  221502. {
  221503. setMinimised (false);
  221504. Window newStack[] = { otherPeer->windowH, windowH };
  221505. XRestackWindows (display, newStack, 2);
  221506. }
  221507. }
  221508. bool isFocused() const
  221509. {
  221510. int revert;
  221511. Window focusedWindow = 0;
  221512. XGetInputFocus (display, &focusedWindow, &revert);
  221513. return focusedWindow == windowH;
  221514. }
  221515. void grabFocus()
  221516. {
  221517. XWindowAttributes atts;
  221518. if (windowH != 0
  221519. && XGetWindowAttributes (display, windowH, &atts)
  221520. && atts.map_state == IsViewable
  221521. && ! isFocused())
  221522. {
  221523. XSetInputFocus (display, windowH, RevertToParent, CurrentTime);
  221524. isActiveApplication = true;
  221525. }
  221526. }
  221527. void textInputRequired (int /*x*/, int /*y*/)
  221528. {
  221529. }
  221530. void repaint (int x, int y, int w, int h)
  221531. {
  221532. if (Rectangle::intersectRectangles (x, y, w, h,
  221533. 0, 0,
  221534. getComponent()->getWidth(),
  221535. getComponent()->getHeight()))
  221536. {
  221537. repainter->repaint (x, y, w, h);
  221538. }
  221539. }
  221540. void performAnyPendingRepaintsNow()
  221541. {
  221542. repainter->performAnyPendingRepaintsNow();
  221543. }
  221544. void setIcon (const Image& newIcon)
  221545. {
  221546. const int dataSize = newIcon.getWidth() * newIcon.getHeight() + 2;
  221547. uint32* const data = (uint32*) juce_malloc (dataSize * sizeof (uint32));
  221548. int index = 0;
  221549. data[index++] = newIcon.getWidth();
  221550. data[index++] = newIcon.getHeight();
  221551. for (int y = 0; y < newIcon.getHeight(); ++y)
  221552. for (int x = 0; x < newIcon.getWidth(); ++x)
  221553. data[index++] = newIcon.getPixelAt (x, y).getARGB();
  221554. XChangeProperty (display, windowH,
  221555. XInternAtom (display, "_NET_WM_ICON", False),
  221556. XA_CARDINAL, 32, PropModeReplace,
  221557. (unsigned char*) data, dataSize);
  221558. juce_free (data);
  221559. deleteIconPixmaps();
  221560. XWMHints* wmHints = XGetWMHints (display, windowH);
  221561. if (wmHints == 0)
  221562. wmHints = XAllocWMHints();
  221563. wmHints->flags |= IconPixmapHint | IconMaskHint;
  221564. wmHints->icon_pixmap = juce_createColourPixmapFromImage (display, newIcon);
  221565. wmHints->icon_mask = juce_createMaskPixmapFromImage (display, newIcon);
  221566. XSetWMHints (display, windowH, wmHints);
  221567. XFree (wmHints);
  221568. XSync (display, False);
  221569. }
  221570. void deleteIconPixmaps()
  221571. {
  221572. XWMHints* wmHints = XGetWMHints (display, windowH);
  221573. if (wmHints != 0)
  221574. {
  221575. if ((wmHints->flags & IconPixmapHint) != 0)
  221576. {
  221577. wmHints->flags &= ~IconPixmapHint;
  221578. XFreePixmap (display, wmHints->icon_pixmap);
  221579. }
  221580. if ((wmHints->flags & IconMaskHint) != 0)
  221581. {
  221582. wmHints->flags &= ~IconMaskHint;
  221583. XFreePixmap (display, wmHints->icon_mask);
  221584. }
  221585. XSetWMHints (display, windowH, wmHints);
  221586. XFree (wmHints);
  221587. }
  221588. }
  221589. void handleWindowMessage (XEvent* event)
  221590. {
  221591. switch (event->xany.type)
  221592. {
  221593. case 2: // 'KeyPress'
  221594. {
  221595. XKeyEvent* const keyEvent = (XKeyEvent*) &event->xkey;
  221596. updateKeyStates (keyEvent->keycode, true);
  221597. char utf8 [64];
  221598. zeromem (utf8, sizeof (utf8));
  221599. KeySym sym;
  221600. XLookupString (keyEvent, utf8, sizeof (utf8), &sym, 0);
  221601. const juce_wchar unicodeChar = *(const juce_wchar*) String::fromUTF8 ((const uint8*) utf8, sizeof (utf8) - 1);
  221602. int keyCode = (int) unicodeChar;
  221603. if (keyCode < 0x20)
  221604. keyCode = XKeycodeToKeysym (display, keyEvent->keycode,
  221605. (currentModifiers & ModifierKeys::shiftModifier) != 0 ? 1 : 0);
  221606. const int oldMods = currentModifiers;
  221607. bool keyPressed = false;
  221608. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, true);
  221609. if ((sym & 0xff00) == 0xff00)
  221610. {
  221611. // Translate keypad
  221612. if (sym == XK_KP_Divide)
  221613. keyCode = XK_slash;
  221614. else if (sym == XK_KP_Multiply)
  221615. keyCode = XK_asterisk;
  221616. else if (sym == XK_KP_Subtract)
  221617. keyCode = XK_hyphen;
  221618. else if (sym == XK_KP_Add)
  221619. keyCode = XK_plus;
  221620. else if (sym == XK_KP_Enter)
  221621. keyCode = XK_Return;
  221622. else if (sym == XK_KP_Decimal)
  221623. keyCode = numLock ? XK_period : XK_Delete;
  221624. else if (sym == XK_KP_0)
  221625. keyCode = numLock ? XK_0 : XK_Insert;
  221626. else if (sym == XK_KP_1)
  221627. keyCode = numLock ? XK_1 : XK_End;
  221628. else if (sym == XK_KP_2)
  221629. keyCode = numLock ? XK_2 : XK_Down;
  221630. else if (sym == XK_KP_3)
  221631. keyCode = numLock ? XK_3 : XK_Page_Down;
  221632. else if (sym == XK_KP_4)
  221633. keyCode = numLock ? XK_4 : XK_Left;
  221634. else if (sym == XK_KP_5)
  221635. keyCode = XK_5;
  221636. else if (sym == XK_KP_6)
  221637. keyCode = numLock ? XK_6 : XK_Right;
  221638. else if (sym == XK_KP_7)
  221639. keyCode = numLock ? XK_7 : XK_Home;
  221640. else if (sym == XK_KP_8)
  221641. keyCode = numLock ? XK_8 : XK_Up;
  221642. else if (sym == XK_KP_9)
  221643. keyCode = numLock ? XK_9 : XK_Page_Up;
  221644. switch (sym)
  221645. {
  221646. case XK_Left:
  221647. case XK_Right:
  221648. case XK_Up:
  221649. case XK_Down:
  221650. case XK_Page_Up:
  221651. case XK_Page_Down:
  221652. case XK_End:
  221653. case XK_Home:
  221654. case XK_Delete:
  221655. case XK_Insert:
  221656. keyPressed = true;
  221657. keyCode = (sym & 0xff) | extendedKeyModifier;
  221658. break;
  221659. case XK_Tab:
  221660. case XK_Return:
  221661. case XK_Escape:
  221662. case XK_BackSpace:
  221663. keyPressed = true;
  221664. keyCode &= 0xff;
  221665. break;
  221666. default:
  221667. {
  221668. if (sym >= XK_F1 && sym <= XK_F16)
  221669. {
  221670. keyPressed = true;
  221671. keyCode = (sym & 0xff) | extendedKeyModifier;
  221672. }
  221673. break;
  221674. }
  221675. }
  221676. }
  221677. if (utf8[0] != 0 || ((sym & 0xff00) == 0 && sym >= 8))
  221678. keyPressed = true;
  221679. if (oldMods != currentModifiers)
  221680. handleModifierKeysChange();
  221681. if (keyDownChange)
  221682. handleKeyUpOrDown();
  221683. if (keyPressed)
  221684. handleKeyPress (keyCode, unicodeChar);
  221685. break;
  221686. }
  221687. case KeyRelease:
  221688. {
  221689. const XKeyEvent* const keyEvent = (const XKeyEvent*) &event->xkey;
  221690. updateKeyStates (keyEvent->keycode, false);
  221691. KeySym sym = XKeycodeToKeysym (display, keyEvent->keycode, 0);
  221692. const int oldMods = currentModifiers;
  221693. const bool keyDownChange = (sym != NoSymbol) && ! updateKeyModifiersFromSym (sym, false);
  221694. if (oldMods != currentModifiers)
  221695. handleModifierKeysChange();
  221696. if (keyDownChange)
  221697. handleKeyUpOrDown();
  221698. break;
  221699. }
  221700. case ButtonPress:
  221701. {
  221702. const XButtonPressedEvent* const buttonPressEvent = (const XButtonPressedEvent*) &event->xbutton;
  221703. bool buttonMsg = false;
  221704. bool wheelUpMsg = false;
  221705. bool wheelDownMsg = false;
  221706. const int map = pointerMap [buttonPressEvent->button - Button1];
  221707. if (map == LeftButton)
  221708. {
  221709. currentModifiers |= ModifierKeys::leftButtonModifier;
  221710. buttonMsg = true;
  221711. }
  221712. else if (map == RightButton)
  221713. {
  221714. currentModifiers |= ModifierKeys::rightButtonModifier;
  221715. buttonMsg = true;
  221716. }
  221717. else if (map == MiddleButton)
  221718. {
  221719. currentModifiers |= ModifierKeys::middleButtonModifier;
  221720. buttonMsg = true;
  221721. }
  221722. else if (map == WheelUp)
  221723. {
  221724. wheelUpMsg = true;
  221725. }
  221726. else if (map == WheelDown)
  221727. {
  221728. wheelDownMsg = true;
  221729. }
  221730. updateKeyModifiers (buttonPressEvent->state);
  221731. if (buttonMsg)
  221732. {
  221733. toFront (true);
  221734. handleMouseDown (buttonPressEvent->x, buttonPressEvent->y,
  221735. getEventTime (buttonPressEvent->time));
  221736. }
  221737. else if (wheelUpMsg || wheelDownMsg)
  221738. {
  221739. handleMouseWheel (0, wheelDownMsg ? -84 : 84,
  221740. getEventTime (buttonPressEvent->time));
  221741. }
  221742. lastMousePosX = lastMousePosY = 0x100000;
  221743. break;
  221744. }
  221745. case ButtonRelease:
  221746. {
  221747. const XButtonReleasedEvent* const buttonRelEvent = (const XButtonReleasedEvent*) &event->xbutton;
  221748. const int oldModifiers = currentModifiers;
  221749. const int map = pointerMap [buttonRelEvent->button - Button1];
  221750. if (map == LeftButton)
  221751. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  221752. else if (map == RightButton)
  221753. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  221754. else if (map == MiddleButton)
  221755. currentModifiers &= ~ModifierKeys::middleButtonModifier;
  221756. updateKeyModifiers (buttonRelEvent->state);
  221757. handleMouseUp (oldModifiers,
  221758. buttonRelEvent->x, buttonRelEvent->y,
  221759. getEventTime (buttonRelEvent->time));
  221760. lastMousePosX = lastMousePosY = 0x100000;
  221761. break;
  221762. }
  221763. case MotionNotify:
  221764. {
  221765. const XPointerMovedEvent* const movedEvent = (const XPointerMovedEvent*) &event->xmotion;
  221766. updateKeyModifiers (movedEvent->state);
  221767. int x, y, mouseMods;
  221768. getMousePos (x, y, mouseMods);
  221769. if (lastMousePosX != x || lastMousePosY != y)
  221770. {
  221771. lastMousePosX = x;
  221772. lastMousePosY = y;
  221773. if (parentWindow != 0 && (styleFlags & windowHasTitleBar) == 0)
  221774. {
  221775. Window wRoot = 0, wParent = 0;
  221776. Window* wChild = 0;
  221777. unsigned int numChildren;
  221778. XQueryTree (display, windowH, &wRoot, &wParent, &wChild, &numChildren);
  221779. if (wParent != 0
  221780. && wParent != windowH
  221781. && wParent != wRoot)
  221782. {
  221783. parentWindow = wParent;
  221784. updateBounds();
  221785. x -= getScreenX();
  221786. y -= getScreenY();
  221787. }
  221788. else
  221789. {
  221790. parentWindow = 0;
  221791. x -= getScreenX();
  221792. y -= getScreenY();
  221793. }
  221794. }
  221795. else
  221796. {
  221797. x -= getScreenX();
  221798. y -= getScreenY();
  221799. }
  221800. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0)
  221801. handleMouseMove (x, y, getEventTime (movedEvent->time));
  221802. else
  221803. handleMouseDrag (x, y, getEventTime (movedEvent->time));
  221804. }
  221805. break;
  221806. }
  221807. case EnterNotify:
  221808. {
  221809. lastMousePosX = lastMousePosY = 0x100000;
  221810. const XEnterWindowEvent* const enterEvent = (const XEnterWindowEvent*) &event->xcrossing;
  221811. if ((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  221812. && ! entered)
  221813. {
  221814. updateKeyModifiers (enterEvent->state);
  221815. handleMouseEnter (enterEvent->x, enterEvent->y, getEventTime (enterEvent->time));
  221816. entered = true;
  221817. }
  221818. break;
  221819. }
  221820. case LeaveNotify:
  221821. {
  221822. const XLeaveWindowEvent* const leaveEvent = (const XLeaveWindowEvent*) &event->xcrossing;
  221823. // Suppress the normal leave if we've got a pointer grab, or if
  221824. // it's a bogus one caused by clicking a mouse button when running
  221825. // in a Window manager
  221826. if (((currentModifiers & ModifierKeys::allMouseButtonModifiers) == 0
  221827. && leaveEvent->mode == NotifyNormal)
  221828. || leaveEvent->mode == NotifyUngrab)
  221829. {
  221830. updateKeyModifiers (leaveEvent->state);
  221831. handleMouseExit (leaveEvent->x, leaveEvent->y, getEventTime (leaveEvent->time));
  221832. entered = false;
  221833. }
  221834. break;
  221835. }
  221836. case FocusIn:
  221837. {
  221838. isActiveApplication = true;
  221839. if (isFocused())
  221840. handleFocusGain();
  221841. break;
  221842. }
  221843. case FocusOut:
  221844. {
  221845. isActiveApplication = false;
  221846. if (! isFocused())
  221847. handleFocusLoss();
  221848. break;
  221849. }
  221850. case Expose:
  221851. {
  221852. // Batch together all pending expose events
  221853. XExposeEvent* exposeEvent = (XExposeEvent*) &event->xexpose;
  221854. XEvent nextEvent;
  221855. if (exposeEvent->window != windowH)
  221856. {
  221857. Window child;
  221858. XTranslateCoordinates (display, exposeEvent->window, windowH,
  221859. exposeEvent->x, exposeEvent->y, &exposeEvent->x, &exposeEvent->y,
  221860. &child);
  221861. }
  221862. repaint (exposeEvent->x, exposeEvent->y,
  221863. exposeEvent->width, exposeEvent->height);
  221864. while (XEventsQueued (display, QueuedAfterFlush) > 0)
  221865. {
  221866. XPeekEvent (display, (XEvent*) &nextEvent);
  221867. if (nextEvent.type != Expose || nextEvent.xany.window != event->xany.window)
  221868. break;
  221869. XNextEvent (display, (XEvent*) &nextEvent);
  221870. XExposeEvent* nextExposeEvent = (XExposeEvent*) &nextEvent.xexpose;
  221871. repaint (nextExposeEvent->x, nextExposeEvent->y,
  221872. nextExposeEvent->width, nextExposeEvent->height);
  221873. }
  221874. break;
  221875. }
  221876. case CirculateNotify:
  221877. case CreateNotify:
  221878. case DestroyNotify:
  221879. // Think we can ignore these
  221880. break;
  221881. case ConfigureNotify:
  221882. {
  221883. updateBounds();
  221884. updateBorderSize();
  221885. handleMovedOrResized();
  221886. // if the native title bar is dragged, need to tell any active menus, etc.
  221887. if ((styleFlags & windowHasTitleBar) != 0
  221888. && component->isCurrentlyBlockedByAnotherModalComponent())
  221889. {
  221890. Component* const currentModalComp = Component::getCurrentlyModalComponent();
  221891. if (currentModalComp != 0)
  221892. currentModalComp->inputAttemptWhenModal();
  221893. }
  221894. XConfigureEvent* const confEvent = (XConfigureEvent*) &event->xconfigure;
  221895. if (confEvent->window == windowH
  221896. && confEvent->above != 0
  221897. && isFrontWindow())
  221898. {
  221899. handleBroughtToFront();
  221900. }
  221901. break;
  221902. }
  221903. case ReparentNotify:
  221904. case GravityNotify:
  221905. {
  221906. parentWindow = 0;
  221907. Window wRoot = 0;
  221908. Window* wChild = 0;
  221909. unsigned int numChildren;
  221910. XQueryTree (display, windowH, &wRoot, &parentWindow, &wChild, &numChildren);
  221911. if (parentWindow == windowH || parentWindow == wRoot)
  221912. parentWindow = 0;
  221913. updateBounds();
  221914. updateBorderSize();
  221915. handleMovedOrResized();
  221916. break;
  221917. }
  221918. case MapNotify:
  221919. mapped = true;
  221920. handleBroughtToFront();
  221921. break;
  221922. case UnmapNotify:
  221923. mapped = false;
  221924. break;
  221925. case MappingNotify:
  221926. {
  221927. XMappingEvent* mappingEvent = (XMappingEvent*) &event->xmapping;
  221928. if (mappingEvent->request != MappingPointer)
  221929. {
  221930. // Deal with modifier/keyboard mapping
  221931. XRefreshKeyboardMapping (mappingEvent);
  221932. getModifierMapping();
  221933. }
  221934. break;
  221935. }
  221936. case ClientMessage:
  221937. {
  221938. const XClientMessageEvent* const clientMsg = (const XClientMessageEvent*) &event->xclient;
  221939. if (clientMsg->message_type == wm_Protocols && clientMsg->format == 32)
  221940. {
  221941. const Atom atom = (Atom) clientMsg->data.l[0];
  221942. if (atom == wm_ProtocolList [TAKE_FOCUS])
  221943. {
  221944. XWindowAttributes atts;
  221945. if (clientMsg->window != 0
  221946. && XGetWindowAttributes (display, clientMsg->window, &atts))
  221947. {
  221948. if (atts.map_state == IsViewable)
  221949. XSetInputFocus (display, clientMsg->window, RevertToParent, clientMsg->data.l[1]);
  221950. }
  221951. }
  221952. else if (atom == wm_ProtocolList [DELETE_WINDOW])
  221953. {
  221954. handleUserClosingWindow();
  221955. }
  221956. }
  221957. else if (clientMsg->message_type == XA_XdndEnter)
  221958. {
  221959. handleDragAndDropEnter (clientMsg);
  221960. }
  221961. else if (clientMsg->message_type == XA_XdndLeave)
  221962. {
  221963. resetDragAndDrop();
  221964. }
  221965. else if (clientMsg->message_type == XA_XdndPosition)
  221966. {
  221967. handleDragAndDropPosition (clientMsg);
  221968. }
  221969. else if (clientMsg->message_type == XA_XdndDrop)
  221970. {
  221971. handleDragAndDropDrop (clientMsg);
  221972. }
  221973. else if (clientMsg->message_type == XA_XdndStatus)
  221974. {
  221975. handleDragAndDropStatus (clientMsg);
  221976. }
  221977. else if (clientMsg->message_type == XA_XdndFinished)
  221978. {
  221979. resetDragAndDrop();
  221980. }
  221981. break;
  221982. }
  221983. case SelectionNotify:
  221984. handleDragAndDropSelection (event);
  221985. break;
  221986. case SelectionClear:
  221987. case SelectionRequest:
  221988. break;
  221989. default:
  221990. break;
  221991. }
  221992. }
  221993. void showMouseCursor (Cursor cursor) throw()
  221994. {
  221995. XDefineCursor (display, windowH, cursor);
  221996. }
  221997. void setTaskBarIcon (const Image& image)
  221998. {
  221999. deleteTaskBarIcon();
  222000. taskbarImage = image.createCopy();
  222001. Screen* const screen = XDefaultScreenOfDisplay (display);
  222002. const int screenNumber = XScreenNumberOfScreen (screen);
  222003. char screenAtom[32];
  222004. snprintf (screenAtom, sizeof (screenAtom), "_NET_SYSTEM_TRAY_S%d", screenNumber);
  222005. Atom selectionAtom = XInternAtom (display, screenAtom, false);
  222006. XGrabServer (display);
  222007. Window managerWin = XGetSelectionOwner (display, selectionAtom);
  222008. if (managerWin != None)
  222009. XSelectInput (display, managerWin, StructureNotifyMask);
  222010. XUngrabServer (display);
  222011. XFlush (display);
  222012. if (managerWin != None)
  222013. {
  222014. XEvent ev;
  222015. zerostruct (ev);
  222016. ev.xclient.type = ClientMessage;
  222017. ev.xclient.window = managerWin;
  222018. ev.xclient.message_type = XInternAtom (display, "_NET_SYSTEM_TRAY_OPCODE", False);
  222019. ev.xclient.format = 32;
  222020. ev.xclient.data.l[0] = CurrentTime;
  222021. ev.xclient.data.l[1] = SYSTEM_TRAY_REQUEST_DOCK;
  222022. ev.xclient.data.l[2] = windowH;
  222023. ev.xclient.data.l[3] = 0;
  222024. ev.xclient.data.l[4] = 0;
  222025. XSendEvent (display, managerWin, False, NoEventMask, &ev);
  222026. XSync (display, False);
  222027. }
  222028. // For older KDE's ...
  222029. long atomData = 1;
  222030. Atom trayAtom = XInternAtom (display, "KWM_DOCKWINDOW", false);
  222031. XChangeProperty (display, windowH, trayAtom, trayAtom, 32, PropModeReplace, (unsigned char*) &atomData, 1);
  222032. // For more recent KDE's...
  222033. trayAtom = XInternAtom (display, "_KDE_NET_WM_SYSTEM_TRAY_WINDOW_FOR", false);
  222034. XChangeProperty (display, windowH, trayAtom, XA_WINDOW, 32, PropModeReplace, (unsigned char*) &windowH, 1);
  222035. // a minimum size must be specified for GNOME and Xfce, otherwise the icon is displayed with a width of 1
  222036. XSizeHints* hints = XAllocSizeHints();
  222037. hints->flags = PMinSize;
  222038. hints->min_width = 22;
  222039. hints->min_height = 22;
  222040. XSetWMNormalHints (display, windowH, hints);
  222041. XFree (hints);
  222042. }
  222043. void deleteTaskBarIcon()
  222044. {
  222045. deleteAndZero (taskbarImage);
  222046. }
  222047. const Image* getTaskbarIcon() const throw() { return taskbarImage; }
  222048. juce_UseDebuggingNewOperator
  222049. bool dontRepaint;
  222050. private:
  222051. class LinuxRepaintManager : public Timer
  222052. {
  222053. public:
  222054. LinuxRepaintManager (LinuxComponentPeer* const peer_)
  222055. : peer (peer_),
  222056. image (0),
  222057. lastTimeImageUsed (0)
  222058. {
  222059. #if JUCE_USE_XSHM
  222060. useARGBImagesForRendering = isShmAvailable();
  222061. if (useARGBImagesForRendering)
  222062. {
  222063. XShmSegmentInfo segmentinfo;
  222064. XImage* const testImage
  222065. = XShmCreateImage (display, DefaultVisual (display, DefaultScreen (display)),
  222066. 24, ZPixmap, 0, &segmentinfo, 64, 64);
  222067. useARGBImagesForRendering = (testImage->bits_per_pixel == 32);
  222068. XDestroyImage (testImage);
  222069. }
  222070. #endif
  222071. }
  222072. ~LinuxRepaintManager()
  222073. {
  222074. delete image;
  222075. }
  222076. void timerCallback()
  222077. {
  222078. if (! regionsNeedingRepaint.isEmpty())
  222079. {
  222080. stopTimer();
  222081. performAnyPendingRepaintsNow();
  222082. }
  222083. else if (Time::getApproximateMillisecondCounter() > lastTimeImageUsed + 3000)
  222084. {
  222085. stopTimer();
  222086. deleteAndZero (image);
  222087. }
  222088. }
  222089. void repaint (int x, int y, int w, int h)
  222090. {
  222091. if (! isTimerRunning())
  222092. startTimer (repaintTimerPeriod);
  222093. regionsNeedingRepaint.add (x, y, w, h);
  222094. }
  222095. void performAnyPendingRepaintsNow()
  222096. {
  222097. peer->clearMaskedRegion();
  222098. const Rectangle totalArea (regionsNeedingRepaint.getBounds());
  222099. if (! totalArea.isEmpty())
  222100. {
  222101. if (image == 0 || image->getWidth() < totalArea.getWidth()
  222102. || image->getHeight() < totalArea.getHeight())
  222103. {
  222104. delete image;
  222105. #if JUCE_USE_XSHM
  222106. image = new XBitmapImage (useARGBImagesForRendering ? Image::ARGB
  222107. : Image::RGB,
  222108. #else
  222109. image = new XBitmapImage (Image::RGB,
  222110. #endif
  222111. (totalArea.getWidth() + 31) & ~31,
  222112. (totalArea.getHeight() + 31) & ~31,
  222113. false,
  222114. peer->depthIs16Bit);
  222115. }
  222116. startTimer (repaintTimerPeriod);
  222117. LowLevelGraphicsSoftwareRenderer context (*image);
  222118. context.setOrigin (-totalArea.getX(), -totalArea.getY());
  222119. if (context.reduceClipRegion (regionsNeedingRepaint))
  222120. peer->handlePaint (context);
  222121. if (! peer->maskedRegion.isEmpty())
  222122. regionsNeedingRepaint.subtract (peer->maskedRegion);
  222123. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  222124. {
  222125. const Rectangle& r = *i.getRectangle();
  222126. image->blitToWindow (peer->windowH,
  222127. r.getX(), r.getY(), r.getWidth(), r.getHeight(),
  222128. r.getX() - totalArea.getX(), r.getY() - totalArea.getY());
  222129. }
  222130. }
  222131. regionsNeedingRepaint.clear();
  222132. lastTimeImageUsed = Time::getApproximateMillisecondCounter();
  222133. startTimer (repaintTimerPeriod);
  222134. }
  222135. private:
  222136. LinuxComponentPeer* const peer;
  222137. XBitmapImage* image;
  222138. uint32 lastTimeImageUsed;
  222139. RectangleList regionsNeedingRepaint;
  222140. #if JUCE_USE_XSHM
  222141. bool useARGBImagesForRendering;
  222142. #endif
  222143. LinuxRepaintManager (const LinuxRepaintManager&);
  222144. const LinuxRepaintManager& operator= (const LinuxRepaintManager&);
  222145. };
  222146. LinuxRepaintManager* repainter;
  222147. friend class LinuxRepaintManager;
  222148. Window windowH, parentWindow;
  222149. int wx, wy, ww, wh;
  222150. Image* taskbarImage;
  222151. bool fullScreen, entered, mapped, depthIs16Bit;
  222152. BorderSize windowBorder;
  222153. void removeWindowDecorations (Window wndH)
  222154. {
  222155. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  222156. if (hints != None)
  222157. {
  222158. typedef struct
  222159. {
  222160. unsigned long flags;
  222161. unsigned long functions;
  222162. unsigned long decorations;
  222163. long input_mode;
  222164. unsigned long status;
  222165. } MotifWmHints;
  222166. MotifWmHints motifHints;
  222167. zerostruct (motifHints);
  222168. motifHints.flags = 2; /* MWM_HINTS_DECORATIONS */
  222169. motifHints.decorations = 0;
  222170. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  222171. (unsigned char*) &motifHints, 4);
  222172. }
  222173. hints = XInternAtom (display, "_WIN_HINTS", True);
  222174. if (hints != None)
  222175. {
  222176. long gnomeHints = 0;
  222177. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  222178. (unsigned char*) &gnomeHints, 1);
  222179. }
  222180. hints = XInternAtom (display, "KWM_WIN_DECORATION", True);
  222181. if (hints != None)
  222182. {
  222183. long kwmHints = 2; /*KDE_tinyDecoration*/
  222184. XChangeProperty (display, wndH, hints, hints, 32, PropModeReplace,
  222185. (unsigned char*) &kwmHints, 1);
  222186. }
  222187. hints = XInternAtom (display, "_NET_WM_WINDOW_TYPE", True);
  222188. if (hints != None)
  222189. {
  222190. long netHints [2];
  222191. netHints[0] = XInternAtom (display, "_KDE_NET_WM_WINDOW_TYPE_OVERRIDE", True);
  222192. if ((styleFlags & windowIsTemporary) != 0)
  222193. netHints[1] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_MENU", True);
  222194. else
  222195. netHints[1] = XInternAtom (display, "_NET_WM_WINDOW_TYPE_NORMAL", True);
  222196. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  222197. (unsigned char*) &netHints, 2);
  222198. }
  222199. }
  222200. void addWindowButtons (Window wndH)
  222201. {
  222202. Atom hints = XInternAtom (display, "_MOTIF_WM_HINTS", True);
  222203. if (hints != None)
  222204. {
  222205. typedef struct
  222206. {
  222207. unsigned long flags;
  222208. unsigned long functions;
  222209. unsigned long decorations;
  222210. long input_mode;
  222211. unsigned long status;
  222212. } MotifWmHints;
  222213. MotifWmHints motifHints;
  222214. zerostruct (motifHints);
  222215. motifHints.flags = 1 | 2; /* MWM_HINTS_FUNCTIONS | MWM_HINTS_DECORATIONS */
  222216. motifHints.decorations = 2 /* MWM_DECOR_BORDER */ | 8 /* MWM_DECOR_TITLE */ | 16; /* MWM_DECOR_MENU */
  222217. motifHints.functions = 4 /* MWM_FUNC_MOVE */;
  222218. if ((styleFlags & windowHasCloseButton) != 0)
  222219. motifHints.functions |= 32; /* MWM_FUNC_CLOSE */
  222220. if ((styleFlags & windowHasMinimiseButton) != 0)
  222221. {
  222222. motifHints.functions |= 8; /* MWM_FUNC_MINIMIZE */
  222223. motifHints.decorations |= 0x20; /* MWM_DECOR_MINIMIZE */
  222224. }
  222225. if ((styleFlags & windowHasMaximiseButton) != 0)
  222226. {
  222227. motifHints.functions |= 0x10; /* MWM_FUNC_MAXIMIZE */
  222228. motifHints.decorations |= 0x40; /* MWM_DECOR_MAXIMIZE */
  222229. }
  222230. if ((styleFlags & windowIsResizable) != 0)
  222231. {
  222232. motifHints.functions |= 2; /* MWM_FUNC_RESIZE */
  222233. motifHints.decorations |= 0x4; /* MWM_DECOR_RESIZEH */
  222234. }
  222235. XChangeProperty (display, wndH, hints, hints, 32, 0, (unsigned char*) &motifHints, 5);
  222236. }
  222237. hints = XInternAtom (display, "_NET_WM_ALLOWED_ACTIONS", True);
  222238. if (hints != None)
  222239. {
  222240. long netHints [6];
  222241. int num = 0;
  222242. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_RESIZE", (styleFlags & windowIsResizable) ? True : False);
  222243. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_FULLSCREEN", (styleFlags & windowHasMaximiseButton) ? True : False);
  222244. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_MINIMIZE", (styleFlags & windowHasMinimiseButton) ? True : False);
  222245. netHints [num++] = XInternAtom (display, "_NET_WM_ACTION_CLOSE", (styleFlags & windowHasCloseButton) ? True : False);
  222246. XChangeProperty (display, wndH, hints, XA_ATOM, 32, PropModeReplace,
  222247. (unsigned char*) &netHints, num);
  222248. }
  222249. }
  222250. void createWindow()
  222251. {
  222252. static bool atomsInitialised = false;
  222253. if (! atomsInitialised)
  222254. {
  222255. atomsInitialised = true;
  222256. wm_Protocols = XInternAtom (display, "WM_PROTOCOLS", 1);
  222257. wm_ProtocolList [TAKE_FOCUS] = XInternAtom (display, "WM_TAKE_FOCUS", 1);
  222258. wm_ProtocolList [DELETE_WINDOW] = XInternAtom (display, "WM_DELETE_WINDOW", 1);
  222259. wm_ChangeState = XInternAtom (display, "WM_CHANGE_STATE", 1);
  222260. wm_State = XInternAtom (display, "WM_STATE", 1);
  222261. wm_ActiveWin = XInternAtom (display, "_NET_ACTIVE_WINDOW", False);
  222262. XA_XdndAware = XInternAtom (display, "XdndAware", 0);
  222263. XA_XdndEnter = XInternAtom (display, "XdndEnter", 0);
  222264. XA_XdndLeave = XInternAtom (display, "XdndLeave", 0);
  222265. XA_XdndPosition = XInternAtom (display, "XdndPosition", 0);
  222266. XA_XdndStatus = XInternAtom (display, "XdndStatus", 0);
  222267. XA_XdndDrop = XInternAtom (display, "XdndDrop", 0);
  222268. XA_XdndFinished = XInternAtom (display, "XdndFinished", 0);
  222269. XA_XdndSelection = XInternAtom (display, "XdndSelection", 0);
  222270. XA_XdndProxy = XInternAtom (display, "XdndProxy", 0);
  222271. XA_XdndTypeList = XInternAtom (display, "XdndTypeList", 0);
  222272. XA_XdndActionList = XInternAtom (display, "XdndActionList", 0);
  222273. XA_XdndActionCopy = XInternAtom (display, "XdndActionCopy", 0);
  222274. XA_XdndActionMove = XInternAtom (display, "XdndActionMove", 0);
  222275. XA_XdndActionLink = XInternAtom (display, "XdndActionLink", 0);
  222276. XA_XdndActionAsk = XInternAtom (display, "XdndActionAsk", 0);
  222277. XA_XdndActionPrivate = XInternAtom (display, "XdndActionPrivate", 0);
  222278. XA_XdndActionDescription = XInternAtom (display, "XdndActionDescription", 0);
  222279. XA_JXSelectionWindowProperty = XInternAtom (display, "JXSelectionWindowProperty", 0);
  222280. XA_MimeTextPlain = XInternAtom (display, "text/plain", 0);
  222281. XA_MimeTextUriList = XInternAtom (display, "text/uri-list", 0);
  222282. XA_MimeRootDrop = XInternAtom (display, "application/x-rootwindow-drop", 0);
  222283. }
  222284. resetDragAndDrop();
  222285. XA_OtherMime = XA_MimeTextPlain; // xxx why??
  222286. allowedMimeTypeAtoms [0] = XA_MimeTextPlain;
  222287. allowedMimeTypeAtoms [1] = XA_OtherMime;
  222288. allowedMimeTypeAtoms [2] = XA_MimeTextUriList;
  222289. allowedActions [0] = XA_XdndActionMove;
  222290. allowedActions [1] = XA_XdndActionCopy;
  222291. allowedActions [2] = XA_XdndActionLink;
  222292. allowedActions [3] = XA_XdndActionAsk;
  222293. allowedActions [4] = XA_XdndActionPrivate;
  222294. // Get defaults for various properties
  222295. const int screen = DefaultScreen (display);
  222296. Window root = RootWindow (display, screen);
  222297. // Attempt to create a 24-bit window on the default screen. If this is not
  222298. // possible then exit
  222299. XVisualInfo desiredVisual;
  222300. desiredVisual.screen = screen;
  222301. desiredVisual.depth = 24;
  222302. depthIs16Bit = false;
  222303. int numVisuals;
  222304. XVisualInfo* visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  222305. &desiredVisual, &numVisuals);
  222306. if (numVisuals < 1 || visuals == 0)
  222307. {
  222308. XFree (visuals);
  222309. desiredVisual.depth = 16;
  222310. visuals = XGetVisualInfo (display, VisualScreenMask | VisualDepthMask,
  222311. &desiredVisual, &numVisuals);
  222312. if (numVisuals < 1 || visuals == 0)
  222313. {
  222314. Logger::outputDebugString ("ERROR: System doesn't support 24 or 16 bit RGB display.\n");
  222315. Process::terminate();
  222316. }
  222317. depthIs16Bit = true;
  222318. }
  222319. XFree (visuals);
  222320. // Set up the window attributes
  222321. XSetWindowAttributes swa;
  222322. swa.border_pixel = 0;
  222323. swa.background_pixmap = None;
  222324. swa.colormap = DefaultColormap (display, screen);
  222325. swa.override_redirect = getComponent()->isAlwaysOnTop() ? True : False;
  222326. swa.event_mask = eventMask;
  222327. Window wndH = XCreateWindow (display, root,
  222328. 0, 0, 1, 1,
  222329. 0, 0, InputOutput, (Visual*) CopyFromParent,
  222330. CWBorderPixel | CWColormap | CWBackPixmap | CWEventMask | CWOverrideRedirect,
  222331. &swa);
  222332. XGrabButton (display, AnyButton, AnyModifier, wndH, False,
  222333. ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask,
  222334. GrabModeAsync, GrabModeAsync, None, None);
  222335. // Set the window context to identify the window handle object
  222336. if (XSaveContext (display, (XID) wndH, improbableNumber, (XPointer) this))
  222337. {
  222338. // Failed
  222339. jassertfalse
  222340. Logger::outputDebugString ("Failed to create context information for window.\n");
  222341. XDestroyWindow (display, wndH);
  222342. wndH = 0;
  222343. }
  222344. // Set window manager hints
  222345. XWMHints* wmHints = XAllocWMHints();
  222346. wmHints->flags = InputHint | StateHint;
  222347. wmHints->input = True; // Locally active input model
  222348. wmHints->initial_state = NormalState;
  222349. XSetWMHints (display, wndH, wmHints);
  222350. XFree (wmHints);
  222351. if ((styleFlags & windowIsSemiTransparent) != 0)
  222352. {
  222353. //xxx
  222354. }
  222355. if ((styleFlags & windowAppearsOnTaskbar) != 0)
  222356. {
  222357. //xxx
  222358. }
  222359. //XSetTransientForHint (display, wndH, RootWindow (display, DefaultScreen (display)));
  222360. if ((styleFlags & windowHasTitleBar) == 0)
  222361. removeWindowDecorations (wndH);
  222362. else
  222363. addWindowButtons (wndH);
  222364. // Set window manager protocols
  222365. XChangeProperty (display, wndH, wm_Protocols, XA_ATOM, 32, PropModeReplace,
  222366. (unsigned char*) wm_ProtocolList, 2);
  222367. // Set drag and drop flags
  222368. XChangeProperty (display, wndH, XA_XdndTypeList, XA_ATOM, 32, PropModeReplace,
  222369. (const unsigned char*) allowedMimeTypeAtoms, numElementsInArray (allowedMimeTypeAtoms));
  222370. XChangeProperty (display, wndH, XA_XdndActionList, XA_ATOM, 32, PropModeReplace,
  222371. (const unsigned char*) allowedActions, numElementsInArray (allowedActions));
  222372. XChangeProperty (display, wndH, XA_XdndActionDescription, XA_STRING, 8, PropModeReplace,
  222373. (const unsigned char*) "", 0);
  222374. unsigned long dndVersion = ourDndVersion;
  222375. XChangeProperty (display, wndH, XA_XdndAware, XA_ATOM, 32, PropModeReplace,
  222376. (const unsigned char*) &dndVersion, 1);
  222377. // Set window name
  222378. setWindowTitle (wndH, getComponent()->getName());
  222379. // Initialise the pointer and keyboard mapping
  222380. // This is not the same as the logical pointer mapping the X server uses:
  222381. // we don't mess with this.
  222382. static bool mappingInitialised = false;
  222383. if (! mappingInitialised)
  222384. {
  222385. mappingInitialised = true;
  222386. const int numButtons = XGetPointerMapping (display, 0, 0);
  222387. if (numButtons == 2)
  222388. {
  222389. pointerMap[0] = LeftButton;
  222390. pointerMap[1] = RightButton;
  222391. pointerMap[2] = pointerMap[3] = pointerMap[4] = NoButton;
  222392. }
  222393. else if (numButtons >= 3)
  222394. {
  222395. pointerMap[0] = LeftButton;
  222396. pointerMap[1] = MiddleButton;
  222397. pointerMap[2] = RightButton;
  222398. if (numButtons >= 5)
  222399. {
  222400. pointerMap[3] = WheelUp;
  222401. pointerMap[4] = WheelDown;
  222402. }
  222403. }
  222404. getModifierMapping();
  222405. }
  222406. windowH = wndH;
  222407. }
  222408. void destroyWindow()
  222409. {
  222410. XPointer handlePointer;
  222411. if (! XFindContext (display, (XID) windowH, improbableNumber, &handlePointer))
  222412. XDeleteContext (display, (XID) windowH, improbableNumber);
  222413. XDestroyWindow (display, windowH);
  222414. // Wait for it to complete and then remove any events for this
  222415. // window from the event queue.
  222416. XSync (display, false);
  222417. XEvent event;
  222418. while (XCheckWindowEvent (display, windowH, eventMask, &event) == True)
  222419. {}
  222420. }
  222421. static int64 getEventTime (::Time t) throw()
  222422. {
  222423. static int64 eventTimeOffset = 0x12345678;
  222424. const int64 thisMessageTime = t;
  222425. if (eventTimeOffset == 0x12345678)
  222426. eventTimeOffset = Time::currentTimeMillis() - thisMessageTime;
  222427. return eventTimeOffset + thisMessageTime;
  222428. }
  222429. static void setWindowTitle (Window xwin, const char* const title) throw()
  222430. {
  222431. XTextProperty nameProperty;
  222432. char* strings[] = { (char*) title };
  222433. if (XStringListToTextProperty (strings, 1, &nameProperty))
  222434. {
  222435. XSetWMName (display, xwin, &nameProperty);
  222436. XSetWMIconName (display, xwin, &nameProperty);
  222437. XFree (nameProperty.value);
  222438. }
  222439. }
  222440. void updateBorderSize()
  222441. {
  222442. if ((styleFlags & windowHasTitleBar) == 0)
  222443. {
  222444. windowBorder = BorderSize (0);
  222445. }
  222446. else if (windowBorder.getTopAndBottom() == 0 && windowBorder.getLeftAndRight() == 0)
  222447. {
  222448. Atom hints = XInternAtom (display, "_NET_FRAME_EXTENTS", True);
  222449. if (hints != None)
  222450. {
  222451. unsigned char* data = 0;
  222452. unsigned long nitems, bytesLeft;
  222453. Atom actualType;
  222454. int actualFormat;
  222455. if (XGetWindowProperty (display, windowH, hints, 0, 4, False,
  222456. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  222457. &data) == Success)
  222458. {
  222459. const unsigned long* const sizes = (const unsigned long*) data;
  222460. if (actualFormat == 32)
  222461. windowBorder = BorderSize ((int) sizes[2], (int) sizes[0],
  222462. (int) sizes[3], (int) sizes[1]);
  222463. XFree (data);
  222464. }
  222465. }
  222466. }
  222467. }
  222468. void updateBounds()
  222469. {
  222470. jassert (windowH != 0);
  222471. if (windowH != 0)
  222472. {
  222473. Window root, child;
  222474. unsigned int bw, depth;
  222475. if (! XGetGeometry (display, (::Drawable) windowH, &root,
  222476. &wx, &wy, (unsigned int*) &ww, (unsigned int*) &wh,
  222477. &bw, &depth))
  222478. {
  222479. wx = wy = ww = wh = 0;
  222480. }
  222481. else if (! XTranslateCoordinates (display, windowH, root, 0, 0, &wx, &wy, &child))
  222482. {
  222483. wx = wy = 0;
  222484. }
  222485. }
  222486. }
  222487. void resetDragAndDrop()
  222488. {
  222489. dragAndDropFiles.clear();
  222490. lastDropX = lastDropY = -1;
  222491. dragAndDropCurrentMimeType = 0;
  222492. dragAndDropSourceWindow = 0;
  222493. srcMimeTypeAtomList.clear();
  222494. }
  222495. void sendDragAndDropMessage (XClientMessageEvent& msg)
  222496. {
  222497. msg.type = ClientMessage;
  222498. msg.display = display;
  222499. msg.window = dragAndDropSourceWindow;
  222500. msg.format = 32;
  222501. msg.data.l[0] = windowH;
  222502. XSendEvent (display, dragAndDropSourceWindow, False, 0, (XEvent*) &msg);
  222503. }
  222504. void sendDragAndDropStatus (const bool acceptDrop, Atom dropAction)
  222505. {
  222506. XClientMessageEvent msg;
  222507. zerostruct (msg);
  222508. msg.message_type = XA_XdndStatus;
  222509. msg.data.l[1] = (acceptDrop ? 1 : 0) | 2; // 2 indicates that we want to receive position messages
  222510. msg.data.l[4] = dropAction;
  222511. sendDragAndDropMessage (msg);
  222512. }
  222513. void sendDragAndDropLeave()
  222514. {
  222515. XClientMessageEvent msg;
  222516. zerostruct (msg);
  222517. msg.message_type = XA_XdndLeave;
  222518. sendDragAndDropMessage (msg);
  222519. }
  222520. void sendDragAndDropFinish()
  222521. {
  222522. XClientMessageEvent msg;
  222523. zerostruct (msg);
  222524. msg.message_type = XA_XdndFinished;
  222525. sendDragAndDropMessage (msg);
  222526. }
  222527. void handleDragAndDropStatus (const XClientMessageEvent* const clientMsg)
  222528. {
  222529. if ((clientMsg->data.l[1] & 1) == 0)
  222530. {
  222531. sendDragAndDropLeave();
  222532. if (dragAndDropFiles.size() > 0)
  222533. handleFileDragExit (dragAndDropFiles);
  222534. dragAndDropFiles.clear();
  222535. }
  222536. }
  222537. void handleDragAndDropPosition (const XClientMessageEvent* const clientMsg)
  222538. {
  222539. if (dragAndDropSourceWindow == 0)
  222540. return;
  222541. dragAndDropSourceWindow = clientMsg->data.l[0];
  222542. const int dropX = ((int) clientMsg->data.l[2] >> 16) - getScreenX();
  222543. const int dropY = ((int) clientMsg->data.l[2] & 0xffff) - getScreenY();
  222544. if (lastDropX != dropX || lastDropY != dropY)
  222545. {
  222546. lastDropX = dropX;
  222547. lastDropY = dropY;
  222548. dragAndDropTimestamp = clientMsg->data.l[3];
  222549. Atom targetAction = XA_XdndActionCopy;
  222550. for (int i = numElementsInArray (allowedActions); --i >= 0;)
  222551. {
  222552. if ((Atom) clientMsg->data.l[4] == allowedActions[i])
  222553. {
  222554. targetAction = allowedActions[i];
  222555. break;
  222556. }
  222557. }
  222558. sendDragAndDropStatus (true, targetAction);
  222559. if (dragAndDropFiles.size() == 0)
  222560. updateDraggedFileList (clientMsg);
  222561. if (dragAndDropFiles.size() > 0)
  222562. handleFileDragMove (dragAndDropFiles, dropX, dropY);
  222563. }
  222564. }
  222565. void handleDragAndDropDrop (const XClientMessageEvent* const clientMsg)
  222566. {
  222567. if (dragAndDropFiles.size() == 0)
  222568. updateDraggedFileList (clientMsg);
  222569. const StringArray files (dragAndDropFiles);
  222570. const int lastX = lastDropX, lastY = lastDropY;
  222571. sendDragAndDropFinish();
  222572. resetDragAndDrop();
  222573. if (files.size() > 0)
  222574. handleFileDragDrop (files, lastX, lastY);
  222575. }
  222576. void handleDragAndDropEnter (const XClientMessageEvent* const clientMsg)
  222577. {
  222578. dragAndDropFiles.clear();
  222579. srcMimeTypeAtomList.clear();
  222580. dragAndDropCurrentMimeType = 0;
  222581. const int dndCurrentVersion = (int) (clientMsg->data.l[1] & 0xff000000) >> 24;
  222582. if (dndCurrentVersion < 3 || dndCurrentVersion > ourDndVersion)
  222583. {
  222584. dragAndDropSourceWindow = 0;
  222585. return;
  222586. }
  222587. dragAndDropSourceWindow = clientMsg->data.l[0];
  222588. if ((clientMsg->data.l[1] & 1) != 0)
  222589. {
  222590. Atom actual;
  222591. int format;
  222592. unsigned long count = 0, remaining = 0;
  222593. unsigned char* data = 0;
  222594. XGetWindowProperty (display, dragAndDropSourceWindow, XA_XdndTypeList,
  222595. 0, 0x8000000L, False, XA_ATOM, &actual, &format,
  222596. &count, &remaining, &data);
  222597. if (data != 0)
  222598. {
  222599. if (actual == XA_ATOM && format == 32 && count != 0)
  222600. {
  222601. const unsigned long* const types = (const unsigned long*) data;
  222602. for (unsigned int i = 0; i < count; ++i)
  222603. if (types[i] != None)
  222604. srcMimeTypeAtomList.add (types[i]);
  222605. }
  222606. XFree (data);
  222607. }
  222608. }
  222609. if (srcMimeTypeAtomList.size() == 0)
  222610. {
  222611. for (int i = 2; i < 5; ++i)
  222612. if (clientMsg->data.l[i] != None)
  222613. srcMimeTypeAtomList.add (clientMsg->data.l[i]);
  222614. if (srcMimeTypeAtomList.size() == 0)
  222615. {
  222616. dragAndDropSourceWindow = 0;
  222617. return;
  222618. }
  222619. }
  222620. for (int i = 0; i < srcMimeTypeAtomList.size() && dragAndDropCurrentMimeType == 0; ++i)
  222621. for (int j = 0; j < numElementsInArray (allowedMimeTypeAtoms); ++j)
  222622. if (srcMimeTypeAtomList[i] == allowedMimeTypeAtoms[j])
  222623. dragAndDropCurrentMimeType = allowedMimeTypeAtoms[j];
  222624. handleDragAndDropPosition (clientMsg);
  222625. }
  222626. void handleDragAndDropSelection (const XEvent* const evt)
  222627. {
  222628. dragAndDropFiles.clear();
  222629. if (evt->xselection.property != 0)
  222630. {
  222631. StringArray lines;
  222632. {
  222633. MemoryBlock dropData;
  222634. for (;;)
  222635. {
  222636. Atom actual;
  222637. uint8* data = 0;
  222638. unsigned long count = 0, remaining = 0;
  222639. int format = 0;
  222640. if (XGetWindowProperty (display, evt->xany.window, evt->xselection.property,
  222641. dropData.getSize() / 4, 65536, 1, AnyPropertyType, &actual,
  222642. &format, &count, &remaining, &data) == Success)
  222643. {
  222644. dropData.append (data, count * format / 8);
  222645. XFree (data);
  222646. if (remaining == 0)
  222647. break;
  222648. }
  222649. else
  222650. {
  222651. XFree (data);
  222652. break;
  222653. }
  222654. }
  222655. lines.addLines (dropData.toString());
  222656. }
  222657. for (int i = 0; i < lines.size(); ++i)
  222658. dragAndDropFiles.add (URL::removeEscapeChars (lines[i].fromFirstOccurrenceOf (T("file://"), false, true)));
  222659. dragAndDropFiles.trim();
  222660. dragAndDropFiles.removeEmptyStrings();
  222661. }
  222662. }
  222663. void updateDraggedFileList (const XClientMessageEvent* const clientMsg)
  222664. {
  222665. dragAndDropFiles.clear();
  222666. if (dragAndDropSourceWindow != None
  222667. && dragAndDropCurrentMimeType != 0)
  222668. {
  222669. dragAndDropTimestamp = clientMsg->data.l[2];
  222670. XConvertSelection (display,
  222671. XA_XdndSelection,
  222672. dragAndDropCurrentMimeType,
  222673. XA_JXSelectionWindowProperty,
  222674. windowH,
  222675. dragAndDropTimestamp);
  222676. }
  222677. }
  222678. StringArray dragAndDropFiles;
  222679. int dragAndDropTimestamp, lastDropX, lastDropY;
  222680. Atom XA_OtherMime, dragAndDropCurrentMimeType;
  222681. Window dragAndDropSourceWindow;
  222682. unsigned long allowedActions [5];
  222683. unsigned long allowedMimeTypeAtoms [3];
  222684. Array <Atom> srcMimeTypeAtomList;
  222685. };
  222686. ComponentPeer* Component::createNewPeer (int styleFlags, void* /*nativeWindowToAttachTo*/)
  222687. {
  222688. return new LinuxComponentPeer (this, styleFlags);
  222689. }
  222690. // (this callback is hooked up in the messaging code)
  222691. void juce_windowMessageReceive (XEvent* event)
  222692. {
  222693. if (event->xany.window != None)
  222694. {
  222695. LinuxComponentPeer* const peer = LinuxComponentPeer::getPeerFor (event->xany.window);
  222696. const MessageManagerLock messLock;
  222697. if (ComponentPeer::isValidPeer (peer))
  222698. peer->handleWindowMessage (event);
  222699. }
  222700. else
  222701. {
  222702. switch (event->xany.type)
  222703. {
  222704. case KeymapNotify:
  222705. {
  222706. const XKeymapEvent* const keymapEvent = (const XKeymapEvent*) &event->xkeymap;
  222707. memcpy (keyStates, keymapEvent->key_vector, 32);
  222708. break;
  222709. }
  222710. default:
  222711. break;
  222712. }
  222713. }
  222714. }
  222715. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool /*clipToWorkArea*/) throw()
  222716. {
  222717. #if JUCE_USE_XINERAMA
  222718. int major_opcode, first_event, first_error;
  222719. if (XQueryExtension (display, "XINERAMA", &major_opcode, &first_event, &first_error)
  222720. && XineramaIsActive (display))
  222721. {
  222722. int numMonitors = 0;
  222723. XineramaScreenInfo* const screens = XineramaQueryScreens (display, &numMonitors);
  222724. if (screens != 0)
  222725. {
  222726. for (int i = numMonitors; --i >= 0;)
  222727. {
  222728. int index = screens[i].screen_number;
  222729. if (index >= 0)
  222730. {
  222731. while (monitorCoords.size() < index)
  222732. monitorCoords.add (Rectangle (0, 0, 0, 0));
  222733. monitorCoords.set (index, Rectangle (screens[i].x_org,
  222734. screens[i].y_org,
  222735. screens[i].width,
  222736. screens[i].height));
  222737. }
  222738. }
  222739. XFree (screens);
  222740. }
  222741. }
  222742. if (monitorCoords.size() == 0)
  222743. #endif
  222744. {
  222745. Atom hints = XInternAtom (display, "_NET_WORKAREA", True);
  222746. if (hints != None)
  222747. {
  222748. const int numMonitors = ScreenCount (display);
  222749. for (int i = 0; i < numMonitors; ++i)
  222750. {
  222751. Window root = RootWindow (display, i);
  222752. unsigned long nitems, bytesLeft;
  222753. Atom actualType;
  222754. int actualFormat;
  222755. unsigned char* data = 0;
  222756. if (XGetWindowProperty (display, root, hints, 0, 4, False,
  222757. XA_CARDINAL, &actualType, &actualFormat, &nitems, &bytesLeft,
  222758. &data) == Success)
  222759. {
  222760. const long* const position = (const long*) data;
  222761. if (actualType == XA_CARDINAL && actualFormat == 32 && nitems == 4)
  222762. monitorCoords.add (Rectangle (position[0], position[1],
  222763. position[2], position[3]));
  222764. XFree (data);
  222765. }
  222766. }
  222767. }
  222768. if (monitorCoords.size() == 0)
  222769. {
  222770. monitorCoords.add (Rectangle (0, 0,
  222771. DisplayWidth (display, DefaultScreen (display)),
  222772. DisplayHeight (display, DefaultScreen (display))));
  222773. }
  222774. }
  222775. }
  222776. bool Desktop::canUseSemiTransparentWindows() throw()
  222777. {
  222778. return false;
  222779. }
  222780. void Desktop::getMousePosition (int& x, int& y) throw()
  222781. {
  222782. int mouseMods;
  222783. getMousePos (x, y, mouseMods);
  222784. }
  222785. void Desktop::setMousePosition (int x, int y) throw()
  222786. {
  222787. Window root = RootWindow (display, DefaultScreen (display));
  222788. XWarpPointer (display, None, root, 0, 0, 0, 0, x, y);
  222789. }
  222790. static bool screenSaverAllowed = true;
  222791. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  222792. {
  222793. if (screenSaverAllowed != isEnabled)
  222794. {
  222795. screenSaverAllowed = isEnabled;
  222796. typedef void (*tXScreenSaverSuspend) (Display*, Bool);
  222797. static tXScreenSaverSuspend xScreenSaverSuspend = 0;
  222798. if (xScreenSaverSuspend == 0)
  222799. {
  222800. void* h = dlopen ("libXss.so", RTLD_GLOBAL | RTLD_NOW);
  222801. if (h != 0)
  222802. xScreenSaverSuspend = (tXScreenSaverSuspend) dlsym (h, "XScreenSaverSuspend");
  222803. }
  222804. if (xScreenSaverSuspend != 0)
  222805. xScreenSaverSuspend (display, ! isEnabled);
  222806. }
  222807. }
  222808. bool Desktop::isScreenSaverEnabled() throw()
  222809. {
  222810. return screenSaverAllowed;
  222811. }
  222812. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  222813. {
  222814. Window root = RootWindow (display, DefaultScreen (display));
  222815. const unsigned int imageW = image.getWidth();
  222816. const unsigned int imageH = image.getHeight();
  222817. unsigned int cursorW, cursorH;
  222818. if (! XQueryBestCursor (display, root, imageW, imageH, &cursorW, &cursorH))
  222819. return 0;
  222820. Image im (Image::ARGB, cursorW, cursorH, true);
  222821. Graphics g (im);
  222822. if (imageW > cursorW || imageH > cursorH)
  222823. {
  222824. hotspotX = (hotspotX * cursorW) / imageW;
  222825. hotspotY = (hotspotY * cursorH) / imageH;
  222826. g.drawImageWithin (&image, 0, 0, imageW, imageH,
  222827. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  222828. false);
  222829. }
  222830. else
  222831. {
  222832. g.drawImageAt (&image, 0, 0);
  222833. }
  222834. const int stride = (cursorW + 7) >> 3;
  222835. uint8* const maskPlane = (uint8*) juce_calloc (stride * cursorH);
  222836. uint8* const sourcePlane = (uint8*) juce_calloc (stride * cursorH);
  222837. const bool msbfirst = (BitmapBitOrder (display) == MSBFirst);
  222838. for (int y = cursorH; --y >= 0;)
  222839. {
  222840. for (int x = cursorW; --x >= 0;)
  222841. {
  222842. const uint8 mask = (uint8) (1 << (msbfirst ? (7 - (x & 7)) : (x & 7)));
  222843. const int offset = y * stride + (x >> 3);
  222844. const Colour c (im.getPixelAt (x, y));
  222845. if (c.getAlpha() >= 128)
  222846. maskPlane[offset] |= mask;
  222847. if (c.getBrightness() >= 0.5f)
  222848. sourcePlane[offset] |= mask;
  222849. }
  222850. }
  222851. Pixmap sourcePixmap = XCreatePixmapFromBitmapData (display, root, (char*) sourcePlane, cursorW, cursorH, 0xffff, 0, 1);
  222852. Pixmap maskPixmap = XCreatePixmapFromBitmapData (display, root, (char*) maskPlane, cursorW, cursorH, 0xffff, 0, 1);
  222853. juce_free (maskPlane);
  222854. juce_free (sourcePlane);
  222855. XColor white, black;
  222856. black.red = black.green = black.blue = 0;
  222857. white.red = white.green = white.blue = 0xffff;
  222858. void* result = (void*) XCreatePixmapCursor (display, sourcePixmap, maskPixmap, &white, &black, hotspotX, hotspotY);
  222859. XFreePixmap (display, sourcePixmap);
  222860. XFreePixmap (display, maskPixmap);
  222861. return result;
  222862. }
  222863. void juce_deleteMouseCursor (void* const cursorHandle, const bool) throw()
  222864. {
  222865. if (cursorHandle != None)
  222866. XFreeCursor (display, (Cursor) cursorHandle);
  222867. }
  222868. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  222869. {
  222870. unsigned int shape;
  222871. switch (type)
  222872. {
  222873. case MouseCursor::NoCursor:
  222874. {
  222875. const Image im (Image::ARGB, 16, 16, true);
  222876. return juce_createMouseCursorFromImage (im, 0, 0);
  222877. }
  222878. case MouseCursor::NormalCursor:
  222879. return (void*) None; // Use parent cursor
  222880. case MouseCursor::DraggingHandCursor:
  222881. {
  222882. static unsigned char dragHandData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  222883. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  222884. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  222885. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  222886. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  222887. const int dragHandDataSize = 99;
  222888. Image* const im = ImageFileFormat::loadFrom ((const char*) dragHandData, dragHandDataSize);
  222889. void* const dragHandCursor = juce_createMouseCursorFromImage (*im, 8, 7);
  222890. delete im;
  222891. return dragHandCursor;
  222892. }
  222893. case MouseCursor::CopyingCursor:
  222894. {
  222895. static unsigned char copyCursorData[] = {71,73,70,56,57,97,21,0,21,0,145,0,0,0,0,0,255,255,255,0,
  222896. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,21,0,
  222897. 21,0,0,2,72,4,134,169,171,16,199,98,11,79,90,71,161,93,56,111,
  222898. 78,133,218,215,137,31,82,154,100,200,86,91,202,142,12,108,212,87,235,174,
  222899. 15,54,214,126,237,226,37,96,59,141,16,37,18,201,142,157,230,204,51,112,
  222900. 252,114,147,74,83,5,50,68,147,208,217,16,71,149,252,124,5,0,59,0,0 };
  222901. const int copyCursorSize = 119;
  222902. Image* const im = ImageFileFormat::loadFrom ((const char*) copyCursorData, copyCursorSize);
  222903. void* const copyCursor = juce_createMouseCursorFromImage (*im, 1, 3);
  222904. delete im;
  222905. return copyCursor;
  222906. }
  222907. case MouseCursor::WaitCursor:
  222908. shape = XC_watch;
  222909. break;
  222910. case MouseCursor::IBeamCursor:
  222911. shape = XC_xterm;
  222912. break;
  222913. case MouseCursor::PointingHandCursor:
  222914. shape = XC_hand2;
  222915. break;
  222916. case MouseCursor::LeftRightResizeCursor:
  222917. shape = XC_sb_h_double_arrow;
  222918. break;
  222919. case MouseCursor::UpDownResizeCursor:
  222920. shape = XC_sb_v_double_arrow;
  222921. break;
  222922. case MouseCursor::UpDownLeftRightResizeCursor:
  222923. shape = XC_fleur;
  222924. break;
  222925. case MouseCursor::TopEdgeResizeCursor:
  222926. shape = XC_top_side;
  222927. break;
  222928. case MouseCursor::BottomEdgeResizeCursor:
  222929. shape = XC_bottom_side;
  222930. break;
  222931. case MouseCursor::LeftEdgeResizeCursor:
  222932. shape = XC_left_side;
  222933. break;
  222934. case MouseCursor::RightEdgeResizeCursor:
  222935. shape = XC_right_side;
  222936. break;
  222937. case MouseCursor::TopLeftCornerResizeCursor:
  222938. shape = XC_top_left_corner;
  222939. break;
  222940. case MouseCursor::TopRightCornerResizeCursor:
  222941. shape = XC_top_right_corner;
  222942. break;
  222943. case MouseCursor::BottomLeftCornerResizeCursor:
  222944. shape = XC_bottom_left_corner;
  222945. break;
  222946. case MouseCursor::BottomRightCornerResizeCursor:
  222947. shape = XC_bottom_right_corner;
  222948. break;
  222949. case MouseCursor::CrosshairCursor:
  222950. shape = XC_crosshair;
  222951. break;
  222952. default:
  222953. return (void*) None; // Use parent cursor
  222954. }
  222955. return (void*) XCreateFontCursor (display, shape);
  222956. }
  222957. void MouseCursor::showInWindow (ComponentPeer* peer) const throw()
  222958. {
  222959. LinuxComponentPeer* const lp = dynamic_cast <LinuxComponentPeer*> (peer);
  222960. if (lp != 0)
  222961. lp->showMouseCursor ((Cursor) getHandle());
  222962. }
  222963. void MouseCursor::showInAllWindows() const throw()
  222964. {
  222965. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  222966. showInWindow (ComponentPeer::getPeer (i));
  222967. }
  222968. Image* juce_createIconForFile (const File& file)
  222969. {
  222970. return 0;
  222971. }
  222972. #if JUCE_OPENGL
  222973. class WindowedGLContext : public OpenGLContext
  222974. {
  222975. public:
  222976. WindowedGLContext (Component* const component,
  222977. const OpenGLPixelFormat& pixelFormat_,
  222978. GLXContext sharedContext)
  222979. : renderContext (0),
  222980. embeddedWindow (0),
  222981. pixelFormat (pixelFormat_)
  222982. {
  222983. jassert (component != 0);
  222984. LinuxComponentPeer* const peer = dynamic_cast <LinuxComponentPeer*> (component->getTopLevelComponent()->getPeer());
  222985. if (peer == 0)
  222986. return;
  222987. XSync (display, False);
  222988. GLint attribs [64];
  222989. int n = 0;
  222990. attribs[n++] = GLX_RGBA;
  222991. attribs[n++] = GLX_DOUBLEBUFFER;
  222992. attribs[n++] = GLX_RED_SIZE;
  222993. attribs[n++] = pixelFormat.redBits;
  222994. attribs[n++] = GLX_GREEN_SIZE;
  222995. attribs[n++] = pixelFormat.greenBits;
  222996. attribs[n++] = GLX_BLUE_SIZE;
  222997. attribs[n++] = pixelFormat.blueBits;
  222998. attribs[n++] = GLX_ALPHA_SIZE;
  222999. attribs[n++] = pixelFormat.alphaBits;
  223000. attribs[n++] = GLX_DEPTH_SIZE;
  223001. attribs[n++] = pixelFormat.depthBufferBits;
  223002. attribs[n++] = GLX_STENCIL_SIZE;
  223003. attribs[n++] = pixelFormat.stencilBufferBits;
  223004. attribs[n++] = GLX_ACCUM_RED_SIZE;
  223005. attribs[n++] = pixelFormat.accumulationBufferRedBits;
  223006. attribs[n++] = GLX_ACCUM_GREEN_SIZE;
  223007. attribs[n++] = pixelFormat.accumulationBufferGreenBits;
  223008. attribs[n++] = GLX_ACCUM_BLUE_SIZE;
  223009. attribs[n++] = pixelFormat.accumulationBufferBlueBits;
  223010. attribs[n++] = GLX_ACCUM_ALPHA_SIZE;
  223011. attribs[n++] = pixelFormat.accumulationBufferAlphaBits;
  223012. // xxx not sure how to do fullSceneAntiAliasingNumSamples on linux..
  223013. attribs[n++] = None;
  223014. XVisualInfo* const bestVisual = glXChooseVisual (display, DefaultScreen (display), attribs);
  223015. if (bestVisual == 0)
  223016. return;
  223017. renderContext = glXCreateContext (display, bestVisual, sharedContext, GL_TRUE);
  223018. Window windowH = (Window) peer->getNativeHandle();
  223019. Colormap colourMap = XCreateColormap (display, windowH, bestVisual->visual, AllocNone);
  223020. XSetWindowAttributes swa;
  223021. swa.colormap = colourMap;
  223022. swa.border_pixel = 0;
  223023. swa.event_mask = ExposureMask | StructureNotifyMask;
  223024. embeddedWindow = XCreateWindow (display, windowH,
  223025. 0, 0, 1, 1, 0,
  223026. bestVisual->depth,
  223027. InputOutput,
  223028. bestVisual->visual,
  223029. CWBorderPixel | CWColormap | CWEventMask,
  223030. &swa);
  223031. XSaveContext (display, (XID) embeddedWindow, improbableNumber, (XPointer) peer);
  223032. XMapWindow (display, embeddedWindow);
  223033. XFreeColormap (display, colourMap);
  223034. XFree (bestVisual);
  223035. XSync (display, False);
  223036. }
  223037. ~WindowedGLContext()
  223038. {
  223039. makeInactive();
  223040. glXDestroyContext (display, renderContext);
  223041. XUnmapWindow (display, embeddedWindow);
  223042. XDestroyWindow (display, embeddedWindow);
  223043. }
  223044. bool makeActive() const throw()
  223045. {
  223046. jassert (renderContext != 0);
  223047. return glXMakeCurrent (display, embeddedWindow, renderContext)
  223048. && XSync (display, False);
  223049. }
  223050. bool makeInactive() const throw()
  223051. {
  223052. return (! isActive()) || glXMakeCurrent (display, None, 0);
  223053. }
  223054. bool isActive() const throw()
  223055. {
  223056. return glXGetCurrentContext() == renderContext;
  223057. }
  223058. const OpenGLPixelFormat getPixelFormat() const
  223059. {
  223060. return pixelFormat;
  223061. }
  223062. void* getRawContext() const throw()
  223063. {
  223064. return renderContext;
  223065. }
  223066. void updateWindowPosition (int x, int y, int w, int h, int)
  223067. {
  223068. XMoveResizeWindow (display, embeddedWindow,
  223069. x, y, jmax (1, w), jmax (1, h));
  223070. }
  223071. void swapBuffers()
  223072. {
  223073. glXSwapBuffers (display, embeddedWindow);
  223074. }
  223075. bool setSwapInterval (const int numFramesPerSwap)
  223076. {
  223077. // xxx needs doing..
  223078. return false;
  223079. }
  223080. int getSwapInterval() const
  223081. {
  223082. // xxx needs doing..
  223083. return 0;
  223084. }
  223085. void repaint()
  223086. {
  223087. }
  223088. juce_UseDebuggingNewOperator
  223089. GLXContext renderContext;
  223090. private:
  223091. Window embeddedWindow;
  223092. OpenGLPixelFormat pixelFormat;
  223093. WindowedGLContext (const WindowedGLContext&);
  223094. const WindowedGLContext& operator= (const WindowedGLContext&);
  223095. };
  223096. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  223097. const OpenGLPixelFormat& pixelFormat,
  223098. const OpenGLContext* const contextToShareWith)
  223099. {
  223100. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  223101. contextToShareWith != 0 ? (GLXContext) contextToShareWith->getRawContext() : 0);
  223102. if (c->renderContext == 0)
  223103. deleteAndZero (c);
  223104. return c;
  223105. }
  223106. void juce_glViewport (const int w, const int h)
  223107. {
  223108. glViewport (0, 0, w, h);
  223109. }
  223110. void OpenGLPixelFormat::getAvailablePixelFormats (Component* component,
  223111. OwnedArray <OpenGLPixelFormat>& results)
  223112. {
  223113. results.add (new OpenGLPixelFormat()); // xxx
  223114. }
  223115. #endif
  223116. static void initClipboard (Window root, Atom* cutBuffers) throw()
  223117. {
  223118. static bool init = false;
  223119. if (! init)
  223120. {
  223121. init = true;
  223122. // Make sure all cut buffers exist before use
  223123. for (int i = 0; i < 8; i++)
  223124. {
  223125. XChangeProperty (display, root, cutBuffers[i],
  223126. XA_STRING, 8, PropModeAppend, NULL, 0);
  223127. }
  223128. }
  223129. }
  223130. // Clipboard implemented currently using cut buffers
  223131. // rather than the more powerful selection method
  223132. void SystemClipboard::copyTextToClipboard (const String& clipText) throw()
  223133. {
  223134. Window root = RootWindow (display, DefaultScreen (display));
  223135. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  223136. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  223137. initClipboard (root, cutBuffers);
  223138. XRotateWindowProperties (display, root, cutBuffers, 8, 1);
  223139. XChangeProperty (display, root, cutBuffers[0],
  223140. XA_STRING, 8, PropModeReplace, (const unsigned char*) (const char*) clipText,
  223141. clipText.length());
  223142. }
  223143. const String SystemClipboard::getTextFromClipboard() throw()
  223144. {
  223145. const int bufSize = 64; // in words
  223146. String returnData;
  223147. int byteOffset = 0;
  223148. Window root = RootWindow (display, DefaultScreen (display));
  223149. Atom cutBuffers[8] = { XA_CUT_BUFFER0, XA_CUT_BUFFER1, XA_CUT_BUFFER2, XA_CUT_BUFFER3,
  223150. XA_CUT_BUFFER4, XA_CUT_BUFFER5, XA_CUT_BUFFER6, XA_CUT_BUFFER7 };
  223151. initClipboard (root, cutBuffers);
  223152. for (;;)
  223153. {
  223154. unsigned long bytesLeft = 0, nitems = 0;
  223155. unsigned char* clipData = 0;
  223156. int actualFormat = 0;
  223157. Atom actualType;
  223158. if (XGetWindowProperty (display, root, cutBuffers[0], byteOffset >> 2, bufSize,
  223159. False, XA_STRING, &actualType, &actualFormat, &nitems, &bytesLeft,
  223160. &clipData) == Success)
  223161. {
  223162. if (actualType == XA_STRING && actualFormat == 8)
  223163. {
  223164. byteOffset += nitems;
  223165. returnData += String ((const char*) clipData, nitems);
  223166. }
  223167. else
  223168. {
  223169. bytesLeft = 0;
  223170. }
  223171. if (clipData != 0)
  223172. XFree (clipData);
  223173. }
  223174. if (bytesLeft == 0)
  223175. break;
  223176. }
  223177. return returnData;
  223178. }
  223179. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  223180. {
  223181. jassertfalse // not implemented!
  223182. return false;
  223183. }
  223184. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  223185. {
  223186. jassertfalse // not implemented!
  223187. return false;
  223188. }
  223189. void SystemTrayIconComponent::setIconImage (const Image& newImage)
  223190. {
  223191. if (! isOnDesktop ())
  223192. addToDesktop (0);
  223193. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  223194. if (wp != 0)
  223195. {
  223196. wp->setTaskBarIcon (newImage);
  223197. setVisible (true);
  223198. toFront (false);
  223199. repaint();
  223200. }
  223201. }
  223202. void SystemTrayIconComponent::paint (Graphics& g)
  223203. {
  223204. LinuxComponentPeer* const wp = dynamic_cast <LinuxComponentPeer*> (getPeer());
  223205. if (wp != 0)
  223206. {
  223207. const Image* const image = wp->getTaskbarIcon();
  223208. if (image != 0)
  223209. {
  223210. g.drawImageWithin (image, 0, 0, getWidth(), getHeight(),
  223211. RectanglePlacement::xLeft | RectanglePlacement::yTop | RectanglePlacement::onlyReduceInSize,
  223212. false);
  223213. }
  223214. }
  223215. }
  223216. void SystemTrayIconComponent::setIconTooltip (const String& tooltip)
  223217. {
  223218. // xxx not yet implemented!
  223219. }
  223220. void PlatformUtilities::beep()
  223221. {
  223222. fprintf (stdout, "\a");
  223223. fflush (stdout);
  223224. }
  223225. bool AlertWindow::showNativeDialogBox (const String& title,
  223226. const String& bodyText,
  223227. bool isOkCancel)
  223228. {
  223229. // xxx this is supposed to pop up an alert!
  223230. Logger::outputDebugString (title + ": " + bodyText);
  223231. // use a non-native one for the time being..
  223232. if (isOkCancel)
  223233. return AlertWindow::showOkCancelBox (AlertWindow::NoIcon, title, bodyText);
  223234. else
  223235. AlertWindow::showMessageBox (AlertWindow::NoIcon, title, bodyText);
  223236. return true;
  223237. }
  223238. const int KeyPress::spaceKey = XK_space & 0xff;
  223239. const int KeyPress::returnKey = XK_Return & 0xff;
  223240. const int KeyPress::escapeKey = XK_Escape & 0xff;
  223241. const int KeyPress::backspaceKey = XK_BackSpace & 0xff;
  223242. const int KeyPress::leftKey = (XK_Left & 0xff) | extendedKeyModifier;
  223243. const int KeyPress::rightKey = (XK_Right & 0xff) | extendedKeyModifier;
  223244. const int KeyPress::upKey = (XK_Up & 0xff) | extendedKeyModifier;
  223245. const int KeyPress::downKey = (XK_Down & 0xff) | extendedKeyModifier;
  223246. const int KeyPress::pageUpKey = (XK_Page_Up & 0xff) | extendedKeyModifier;
  223247. const int KeyPress::pageDownKey = (XK_Page_Down & 0xff) | extendedKeyModifier;
  223248. const int KeyPress::endKey = (XK_End & 0xff) | extendedKeyModifier;
  223249. const int KeyPress::homeKey = (XK_Home & 0xff) | extendedKeyModifier;
  223250. const int KeyPress::insertKey = (XK_Insert & 0xff) | extendedKeyModifier;
  223251. const int KeyPress::deleteKey = (XK_Delete & 0xff) | extendedKeyModifier;
  223252. const int KeyPress::tabKey = XK_Tab & 0xff;
  223253. const int KeyPress::F1Key = (XK_F1 & 0xff) | extendedKeyModifier;
  223254. const int KeyPress::F2Key = (XK_F2 & 0xff) | extendedKeyModifier;
  223255. const int KeyPress::F3Key = (XK_F3 & 0xff) | extendedKeyModifier;
  223256. const int KeyPress::F4Key = (XK_F4 & 0xff) | extendedKeyModifier;
  223257. const int KeyPress::F5Key = (XK_F5 & 0xff) | extendedKeyModifier;
  223258. const int KeyPress::F6Key = (XK_F6 & 0xff) | extendedKeyModifier;
  223259. const int KeyPress::F7Key = (XK_F7 & 0xff) | extendedKeyModifier;
  223260. const int KeyPress::F8Key = (XK_F8 & 0xff) | extendedKeyModifier;
  223261. const int KeyPress::F9Key = (XK_F9 & 0xff) | extendedKeyModifier;
  223262. const int KeyPress::F10Key = (XK_F10 & 0xff) | extendedKeyModifier;
  223263. const int KeyPress::F11Key = (XK_F11 & 0xff) | extendedKeyModifier;
  223264. const int KeyPress::F12Key = (XK_F12 & 0xff) | extendedKeyModifier;
  223265. const int KeyPress::F13Key = (XK_F13 & 0xff) | extendedKeyModifier;
  223266. const int KeyPress::F14Key = (XK_F14 & 0xff) | extendedKeyModifier;
  223267. const int KeyPress::F15Key = (XK_F15 & 0xff) | extendedKeyModifier;
  223268. const int KeyPress::F16Key = (XK_F16 & 0xff) | extendedKeyModifier;
  223269. const int KeyPress::numberPad0 = (XK_KP_0 & 0xff) | extendedKeyModifier;
  223270. const int KeyPress::numberPad1 = (XK_KP_1 & 0xff) | extendedKeyModifier;
  223271. const int KeyPress::numberPad2 = (XK_KP_2 & 0xff) | extendedKeyModifier;
  223272. const int KeyPress::numberPad3 = (XK_KP_3 & 0xff) | extendedKeyModifier;
  223273. const int KeyPress::numberPad4 = (XK_KP_4 & 0xff) | extendedKeyModifier;
  223274. const int KeyPress::numberPad5 = (XK_KP_5 & 0xff) | extendedKeyModifier;
  223275. const int KeyPress::numberPad6 = (XK_KP_6 & 0xff) | extendedKeyModifier;
  223276. const int KeyPress::numberPad7 = (XK_KP_7 & 0xff)| extendedKeyModifier;
  223277. const int KeyPress::numberPad8 = (XK_KP_8 & 0xff)| extendedKeyModifier;
  223278. const int KeyPress::numberPad9 = (XK_KP_9 & 0xff)| extendedKeyModifier;
  223279. const int KeyPress::numberPadAdd = (XK_KP_Add & 0xff)| extendedKeyModifier;
  223280. const int KeyPress::numberPadSubtract = (XK_KP_Subtract & 0xff)| extendedKeyModifier;
  223281. const int KeyPress::numberPadMultiply = (XK_KP_Multiply & 0xff)| extendedKeyModifier;
  223282. const int KeyPress::numberPadDivide = (XK_KP_Divide & 0xff)| extendedKeyModifier;
  223283. const int KeyPress::numberPadSeparator = (XK_KP_Separator & 0xff)| extendedKeyModifier;
  223284. const int KeyPress::numberPadDecimalPoint = (XK_KP_Decimal & 0xff)| extendedKeyModifier;
  223285. const int KeyPress::numberPadEquals = (XK_KP_Equal & 0xff)| extendedKeyModifier;
  223286. const int KeyPress::numberPadDelete = (XK_KP_Delete & 0xff)| extendedKeyModifier;
  223287. const int KeyPress::playKey = (0xffeeff00) | extendedKeyModifier;
  223288. const int KeyPress::stopKey = (0xffeeff01) | extendedKeyModifier;
  223289. const int KeyPress::fastForwardKey = (0xffeeff02) | extendedKeyModifier;
  223290. const int KeyPress::rewindKey = (0xffeeff03) | extendedKeyModifier;
  223291. END_JUCE_NAMESPACE
  223292. #endif
  223293. /********* End of inlined file: juce_linux_Windowing.cpp *********/
  223294. #endif
  223295. #endif
  223296. //==============================================================================
  223297. #if JUCE_MAC
  223298. /********* Start of inlined file: juce_mac_NativeCode.mm *********/
  223299. /*
  223300. This file wraps together all the mac-specific code, so that
  223301. we can include all the native headers just once, and compile all our
  223302. platform-specific stuff in one big lump, keeping it out of the way of
  223303. the rest of the codebase.
  223304. */
  223305. BEGIN_JUCE_NAMESPACE
  223306. #undef Point
  223307. #define JUCE_INCLUDED_FILE 1
  223308. // Now include the actual code files..
  223309. /********* Start of inlined file: juce_mac_Strings.mm *********/
  223310. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223311. // compiled on its own).
  223312. #ifdef JUCE_INCLUDED_FILE
  223313. static const String nsStringToJuce (NSString* s)
  223314. {
  223315. return String::fromUTF8 ((uint8*) [s UTF8String]);
  223316. }
  223317. static NSString* juceStringToNS (const String& s)
  223318. {
  223319. return [NSString stringWithUTF8String: (const char*) s.toUTF8()];
  223320. }
  223321. static const String convertUTF16ToString (const UniChar* utf16)
  223322. {
  223323. String s;
  223324. while (*utf16 != 0)
  223325. s += (juce_wchar) *utf16++;
  223326. return s;
  223327. }
  223328. const String PlatformUtilities::cfStringToJuceString (CFStringRef cfString)
  223329. {
  223330. String result;
  223331. if (cfString != 0)
  223332. {
  223333. #if JUCE_STRINGS_ARE_UNICODE
  223334. CFRange range = { 0, CFStringGetLength (cfString) };
  223335. UniChar* const u = (UniChar*) juce_malloc (sizeof (UniChar) * (range.length + 1));
  223336. CFStringGetCharacters (cfString, range, u);
  223337. u[range.length] = 0;
  223338. result = convertUTF16ToString (u);
  223339. juce_free (u);
  223340. #else
  223341. const int len = CFStringGetLength (cfString);
  223342. char* buffer = (char*) juce_malloc (len + 1);
  223343. CFStringGetCString (cfString, buffer, len + 1, CFStringGetSystemEncoding());
  223344. result = buffer;
  223345. juce_free (buffer);
  223346. #endif
  223347. }
  223348. return result;
  223349. }
  223350. CFStringRef PlatformUtilities::juceStringToCFString (const String& s)
  223351. {
  223352. #if JUCE_STRINGS_ARE_UNICODE
  223353. const int len = s.length();
  223354. const juce_wchar* t = (const juce_wchar*) s;
  223355. UniChar* temp = (UniChar*) juce_malloc (sizeof (UniChar) * len + 4);
  223356. for (int i = 0; i <= len; ++i)
  223357. temp[i] = t[i];
  223358. CFStringRef result = CFStringCreateWithCharacters (kCFAllocatorDefault, temp, len);
  223359. juce_free (temp);
  223360. return result;
  223361. #else
  223362. return CFStringCreateWithCString (kCFAllocatorDefault,
  223363. (const char*) s,
  223364. CFStringGetSystemEncoding());
  223365. #endif
  223366. }
  223367. const String PlatformUtilities::convertToPrecomposedUnicode (const String& s)
  223368. {
  223369. UnicodeMapping map;
  223370. map.unicodeEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223371. kUnicodeNoSubset,
  223372. kTextEncodingDefaultFormat);
  223373. map.otherEncoding = CreateTextEncoding (kTextEncodingUnicodeDefault,
  223374. kUnicodeCanonicalCompVariant,
  223375. kTextEncodingDefaultFormat);
  223376. map.mappingVersion = kUnicodeUseLatestMapping;
  223377. UnicodeToTextInfo conversionInfo = 0;
  223378. String result;
  223379. if (CreateUnicodeToTextInfo (&map, &conversionInfo) == noErr)
  223380. {
  223381. const int len = s.length();
  223382. UniChar* const tempIn = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  223383. UniChar* const tempOut = (UniChar*) juce_calloc (sizeof (UniChar) * len + 4);
  223384. for (int i = 0; i <= len; ++i)
  223385. tempIn[i] = s[i];
  223386. ByteCount bytesRead = 0;
  223387. ByteCount outputBufferSize = 0;
  223388. if (ConvertFromUnicodeToText (conversionInfo,
  223389. len * sizeof (UniChar), tempIn,
  223390. kUnicodeDefaultDirectionMask,
  223391. 0, 0, 0, 0,
  223392. len * sizeof (UniChar), &bytesRead,
  223393. &outputBufferSize, tempOut) == noErr)
  223394. {
  223395. result.preallocateStorage (bytesRead / sizeof (UniChar) + 2);
  223396. tchar* t = const_cast <tchar*> ((const tchar*) result);
  223397. int i;
  223398. for (i = 0; i < bytesRead / sizeof (UniChar); ++i)
  223399. t[i] = (tchar) tempOut[i];
  223400. t[i] = 0;
  223401. }
  223402. juce_free (tempIn);
  223403. juce_free (tempOut);
  223404. DisposeUnicodeToTextInfo (&conversionInfo);
  223405. }
  223406. return result;
  223407. }
  223408. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  223409. {
  223410. [[NSPasteboard generalPasteboard] declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  223411. owner: nil];
  223412. [[NSPasteboard generalPasteboard] setString: juceStringToNS (text)
  223413. forType: NSStringPboardType];
  223414. }
  223415. const String SystemClipboard::getTextFromClipboard() throw()
  223416. {
  223417. NSString* text = [[NSPasteboard generalPasteboard] stringForType: NSStringPboardType];
  223418. return text == 0 ? String::empty
  223419. : nsStringToJuce (text);
  223420. }
  223421. #endif
  223422. /********* End of inlined file: juce_mac_Strings.mm *********/
  223423. /********* Start of inlined file: juce_mac_SystemStats.mm *********/
  223424. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223425. // compiled on its own).
  223426. #ifdef JUCE_INCLUDED_FILE
  223427. static int64 highResTimerFrequency;
  223428. #if JUCE_INTEL
  223429. static void juce_getCpuVendor (char* const v) throw()
  223430. {
  223431. int vendor[4];
  223432. zerostruct (vendor);
  223433. int dummy = 0;
  223434. asm ("mov %%ebx, %%esi \n\t"
  223435. "cpuid \n\t"
  223436. "xchg %%esi, %%ebx"
  223437. : "=a" (dummy), "=S" (vendor[0]), "=c" (vendor[2]), "=d" (vendor[1]) : "a" (0));
  223438. memcpy (v, vendor, 16);
  223439. }
  223440. static unsigned int getCPUIDWord (unsigned int& familyModel, unsigned int& extFeatures) throw()
  223441. {
  223442. unsigned int cpu = 0;
  223443. unsigned int ext = 0;
  223444. unsigned int family = 0;
  223445. unsigned int dummy = 0;
  223446. asm ("mov %%ebx, %%esi \n\t"
  223447. "cpuid \n\t"
  223448. "xchg %%esi, %%ebx"
  223449. : "=a" (family), "=S" (ext), "=c" (dummy), "=d" (cpu) : "a" (1));
  223450. familyModel = family;
  223451. extFeatures = ext;
  223452. return cpu;
  223453. }
  223454. struct CPUFlags
  223455. {
  223456. bool hasMMX : 1;
  223457. bool hasSSE : 1;
  223458. bool hasSSE2 : 1;
  223459. bool has3DNow : 1;
  223460. };
  223461. static CPUFlags cpuFlags;
  223462. #endif
  223463. void SystemStats::initialiseStats() throw()
  223464. {
  223465. static bool initialised = false;
  223466. if (! initialised)
  223467. {
  223468. initialised = true;
  223469. NSApplicationLoad();
  223470. [NSApplication sharedApplication];
  223471. #if JUCE_INTEL
  223472. {
  223473. unsigned int familyModel, extFeatures;
  223474. const unsigned int features = getCPUIDWord (familyModel, extFeatures);
  223475. cpuFlags.hasMMX = ((features & (1 << 23)) != 0);
  223476. cpuFlags.hasSSE = ((features & (1 << 25)) != 0);
  223477. cpuFlags.hasSSE2 = ((features & (1 << 26)) != 0);
  223478. cpuFlags.has3DNow = ((extFeatures & (1 << 31)) != 0);
  223479. }
  223480. #endif
  223481. highResTimerFrequency = (int64) AudioGetHostClockFrequency();
  223482. String s (SystemStats::getJUCEVersion());
  223483. rlimit lim;
  223484. getrlimit (RLIMIT_NOFILE, &lim);
  223485. lim.rlim_cur = lim.rlim_max = RLIM_INFINITY;
  223486. setrlimit (RLIMIT_NOFILE, &lim);
  223487. }
  223488. }
  223489. static const String getCpuInfo (const char* key, bool lastOne = false) throw()
  223490. {
  223491. String info;
  223492. char buf [256];
  223493. FILE* f = fopen ("/proc/cpuinfo", "r");
  223494. while (f != 0 && fgets (buf, sizeof(buf), f))
  223495. {
  223496. if (strncmp (buf, key, strlen (key)) == 0)
  223497. {
  223498. char* p = buf;
  223499. while (*p && *p != '\n')
  223500. ++p;
  223501. if (*p != 0)
  223502. *p = 0;
  223503. p = buf;
  223504. while (*p != 0 && *p != ':')
  223505. ++p;
  223506. if (*p != 0 && *(p + 1) != 0)
  223507. info = p + 2;
  223508. if (! lastOne)
  223509. break;
  223510. }
  223511. }
  223512. fclose (f);
  223513. return info;
  223514. }
  223515. SystemStats::OperatingSystemType SystemStats::getOperatingSystemType() throw()
  223516. {
  223517. return MacOSX;
  223518. }
  223519. const String SystemStats::getOperatingSystemName() throw()
  223520. {
  223521. return T("Mac OS X");
  223522. }
  223523. bool SystemStats::isOperatingSystem64Bit() throw()
  223524. {
  223525. #if JUCE_64BIT
  223526. return true;
  223527. #else
  223528. //xxx not sure how to find this out?..
  223529. return false;
  223530. #endif
  223531. }
  223532. int SystemStats::getMemorySizeInMegabytes() throw()
  223533. {
  223534. #if MACOS_10_4_OR_EARLIER
  223535. long bytes;
  223536. if (Gestalt (gestaltPhysicalRAMSize, &bytes) == noErr)
  223537. return (int) (((unsigned long) bytes) / (1024 * 1024));
  223538. return 0;
  223539. #else
  223540. return (int) ([[NSProcessInfo processInfo] physicalMemory] / (1024 * 1024));
  223541. #endif
  223542. }
  223543. bool SystemStats::hasMMX() throw()
  223544. {
  223545. #if JUCE_INTEL
  223546. return cpuFlags.hasMMX;
  223547. #else
  223548. return false;
  223549. #endif
  223550. }
  223551. bool SystemStats::hasSSE() throw()
  223552. {
  223553. #if JUCE_INTEL
  223554. return cpuFlags.hasSSE;
  223555. #else
  223556. return false;
  223557. #endif
  223558. }
  223559. bool SystemStats::hasSSE2() throw()
  223560. {
  223561. #if JUCE_INTEL
  223562. return cpuFlags.hasSSE2;
  223563. #else
  223564. return false;
  223565. #endif
  223566. }
  223567. bool SystemStats::has3DNow() throw()
  223568. {
  223569. #if JUCE_INTEL
  223570. return cpuFlags.has3DNow;
  223571. #else
  223572. return false;
  223573. #endif
  223574. }
  223575. const String SystemStats::getCpuVendor() throw()
  223576. {
  223577. #if JUCE_INTEL
  223578. char v [16];
  223579. juce_getCpuVendor (v);
  223580. return String (v, 16);
  223581. #else
  223582. return String::empty;
  223583. #endif
  223584. }
  223585. int SystemStats::getCpuSpeedInMegaherz() throw()
  223586. {
  223587. #if MACOS_10_4_OR_EARLIER
  223588. return GetCPUSpeed();
  223589. #else
  223590. return roundDoubleToInt (getCpuInfo ("cpu MHz").getDoubleValue());
  223591. #endif
  223592. }
  223593. int SystemStats::getNumCpus() throw()
  223594. {
  223595. #if MACOS_10_4_OR_EARLIER
  223596. return MPProcessors();
  223597. #else
  223598. return [[NSProcessInfo processInfo] activeProcessorCount];
  223599. #endif
  223600. }
  223601. static int64 juce_getMicroseconds() throw()
  223602. {
  223603. UnsignedWide t;
  223604. Microseconds (&t);
  223605. return (((int64) t.hi) << 32) | t.lo;
  223606. }
  223607. uint32 juce_millisecondsSinceStartup() throw()
  223608. {
  223609. return (uint32) (juce_getMicroseconds() / 1000);
  223610. }
  223611. double Time::getMillisecondCounterHiRes() throw()
  223612. {
  223613. // xxx might be more accurate to use a scaled AudioGetCurrentHostTime?
  223614. return juce_getMicroseconds() * 0.001;
  223615. }
  223616. int64 Time::getHighResolutionTicks() throw()
  223617. {
  223618. return (int64) AudioGetCurrentHostTime();
  223619. }
  223620. int64 Time::getHighResolutionTicksPerSecond() throw()
  223621. {
  223622. return highResTimerFrequency;
  223623. }
  223624. int64 SystemStats::getClockCycleCounter() throw()
  223625. {
  223626. jassertfalse
  223627. return 0;
  223628. }
  223629. bool Time::setSystemTimeToThisTime() const throw()
  223630. {
  223631. jassertfalse
  223632. return false;
  223633. }
  223634. int SystemStats::getPageSize() throw()
  223635. {
  223636. return NSPageSize();
  223637. }
  223638. void PlatformUtilities::fpuReset()
  223639. {
  223640. }
  223641. #endif
  223642. /********* End of inlined file: juce_mac_SystemStats.mm *********/
  223643. /********* Start of inlined file: juce_mac_Network.mm *********/
  223644. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223645. // compiled on its own).
  223646. #if JUCE_INCLUDED_FILE
  223647. static bool getEthernetIterator (io_iterator_t* matchingServices) throw()
  223648. {
  223649. mach_port_t masterPort;
  223650. if (IOMasterPort (MACH_PORT_NULL, &masterPort) == KERN_SUCCESS)
  223651. {
  223652. CFMutableDictionaryRef dict = IOServiceMatching (kIOEthernetInterfaceClass);
  223653. if (dict != 0)
  223654. {
  223655. CFMutableDictionaryRef propDict = CFDictionaryCreateMutable (kCFAllocatorDefault,
  223656. 0,
  223657. &kCFTypeDictionaryKeyCallBacks,
  223658. &kCFTypeDictionaryValueCallBacks);
  223659. if (propDict != 0)
  223660. {
  223661. CFDictionarySetValue (propDict, CFSTR (kIOPrimaryInterface), kCFBooleanTrue);
  223662. CFDictionarySetValue (dict, CFSTR (kIOPropertyMatchKey), propDict);
  223663. CFRelease (propDict);
  223664. }
  223665. }
  223666. return IOServiceGetMatchingServices (masterPort, dict, matchingServices) == KERN_SUCCESS;
  223667. }
  223668. return false;
  223669. }
  223670. int SystemStats::getMACAddresses (int64* addresses, int maxNum, const bool littleEndian) throw()
  223671. {
  223672. int numResults = 0;
  223673. io_iterator_t it;
  223674. if (getEthernetIterator (&it))
  223675. {
  223676. io_object_t i;
  223677. while ((i = IOIteratorNext (it)) != 0)
  223678. {
  223679. io_object_t controller;
  223680. if (IORegistryEntryGetParentEntry (i, kIOServicePlane, &controller) == KERN_SUCCESS)
  223681. {
  223682. CFTypeRef data = IORegistryEntryCreateCFProperty (controller,
  223683. CFSTR (kIOMACAddress),
  223684. kCFAllocatorDefault,
  223685. 0);
  223686. if (data != 0)
  223687. {
  223688. UInt8 addr [kIOEthernetAddressSize];
  223689. zeromem (addr, sizeof (addr));
  223690. CFDataGetBytes ((CFDataRef) data, CFRangeMake (0, sizeof (addr)), addr);
  223691. CFRelease (data);
  223692. int64 a = 0;
  223693. for (int i = 6; --i >= 0;)
  223694. a = (a << 8) | addr[i];
  223695. if (! littleEndian)
  223696. a = (int64) swapByteOrder ((uint64) a);
  223697. if (numResults < maxNum)
  223698. {
  223699. *addresses++ = a;
  223700. ++numResults;
  223701. }
  223702. }
  223703. IOObjectRelease (controller);
  223704. }
  223705. IOObjectRelease (i);
  223706. }
  223707. IOObjectRelease (it);
  223708. }
  223709. return numResults;
  223710. }
  223711. bool PlatformUtilities::launchEmailWithAttachments (const String& targetEmailAddress,
  223712. const String& emailSubject,
  223713. const String& bodyText,
  223714. const StringArray& filesToAttach)
  223715. {
  223716. const ScopedAutoReleasePool pool;
  223717. String script;
  223718. script << "tell application \"Mail\"\r\n"
  223719. "set newMessage to make new outgoing message with properties {subject:\""
  223720. << emailSubject.replace (T("\""), T("\\\""))
  223721. << "\", content:\""
  223722. << bodyText.replace (T("\""), T("\\\""))
  223723. << "\" & return & return}\r\n"
  223724. "tell newMessage\r\n"
  223725. "set visible to true\r\n"
  223726. "set sender to \"sdfsdfsdfewf\"\r\n"
  223727. "make new to recipient at end of to recipients with properties {address:\""
  223728. << targetEmailAddress
  223729. << "\"}\r\n";
  223730. for (int i = 0; i < filesToAttach.size(); ++i)
  223731. {
  223732. script << "tell content\r\n"
  223733. "make new attachment with properties {file name:\""
  223734. << filesToAttach[i].replace (T("\""), T("\\\""))
  223735. << "\"} at after the last paragraph\r\n"
  223736. "end tell\r\n";
  223737. }
  223738. script << "end tell\r\n"
  223739. "end tell\r\n";
  223740. NSAppleScript* s = [[NSAppleScript alloc]
  223741. initWithSource: juceStringToNS (script)];
  223742. NSDictionary* error = 0;
  223743. const bool ok = [s executeAndReturnError: &error] != nil;
  223744. [s release];
  223745. return ok;
  223746. }
  223747. END_JUCE_NAMESPACE
  223748. using namespace JUCE_NAMESPACE;
  223749. @interface JuceURLConnection : NSObject
  223750. {
  223751. NSURLRequest* request;
  223752. NSURLConnection* connection;
  223753. NSMutableData* data;
  223754. Thread* runLoopThread;
  223755. bool initialised, hasFailed, hasFinished;
  223756. int position;
  223757. NSLock* dataLock;
  223758. }
  223759. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req withCallback: (URL::OpenStreamProgressCallback*) callback withContext: (void*) context;
  223760. - (void) dealloc;
  223761. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response;
  223762. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error;
  223763. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) data;
  223764. - (void) connectionDidFinishLoading: (NSURLConnection*) connection;
  223765. - (BOOL) isOpen;
  223766. - (int) read: (char*) dest numBytes: (int) num;
  223767. - (int) readPosition;
  223768. - (void) stop;
  223769. - (void) createConnection;
  223770. @end
  223771. class JuceURLConnectionMessageThread : public Thread
  223772. {
  223773. JuceURLConnection* owner;
  223774. public:
  223775. JuceURLConnectionMessageThread (JuceURLConnection* owner_)
  223776. : Thread (T("http connection")),
  223777. owner (owner_)
  223778. {
  223779. startThread();
  223780. }
  223781. ~JuceURLConnectionMessageThread()
  223782. {
  223783. stopThread (10000);
  223784. }
  223785. void run()
  223786. {
  223787. [owner createConnection];
  223788. while (! threadShouldExit())
  223789. {
  223790. const ScopedAutoReleasePool pool;
  223791. [[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
  223792. }
  223793. }
  223794. };
  223795. @implementation JuceURLConnection
  223796. - (JuceURLConnection*) initWithRequest: (NSURLRequest*) req
  223797. withCallback: (URL::OpenStreamProgressCallback*) callback
  223798. withContext: (void*) context;
  223799. {
  223800. [super init];
  223801. request = req;
  223802. [request retain];
  223803. data = [[NSMutableData data] retain];
  223804. dataLock = [[NSLock alloc] init];
  223805. connection = 0;
  223806. initialised = false;
  223807. hasFailed = false;
  223808. hasFinished = false;
  223809. runLoopThread = new JuceURLConnectionMessageThread (self);
  223810. while (runLoopThread->isThreadRunning() && ! initialised)
  223811. {
  223812. if (callback != 0)
  223813. callback (context, -1, [[request HTTPBody] length]);
  223814. Thread::sleep (1);
  223815. }
  223816. return self;
  223817. }
  223818. - (void) dealloc
  223819. {
  223820. [self stop];
  223821. delete runLoopThread;
  223822. [connection release];
  223823. [data release];
  223824. [dataLock release];
  223825. [request release];
  223826. [super dealloc];
  223827. }
  223828. - (void) createConnection
  223829. {
  223830. connection = [[NSURLConnection alloc] initWithRequest: request
  223831. delegate: self];
  223832. if (connection == nil)
  223833. runLoopThread->signalThreadShouldExit();
  223834. }
  223835. - (void) connection: (NSURLConnection*) connection didReceiveResponse: (NSURLResponse*) response
  223836. {
  223837. [dataLock lock];
  223838. [data setLength: 0];
  223839. [dataLock unlock];
  223840. initialised = true;
  223841. }
  223842. - (void) connection: (NSURLConnection*) connection didFailWithError: (NSError*) error
  223843. {
  223844. NSLog ([error description]);
  223845. hasFailed = true;
  223846. initialised = true;
  223847. runLoopThread->signalThreadShouldExit();
  223848. }
  223849. - (void) connection: (NSURLConnection*) connection didReceiveData: (NSData*) newData
  223850. {
  223851. [dataLock lock];
  223852. [data appendData: newData];
  223853. [dataLock unlock];
  223854. initialised = true;
  223855. }
  223856. - (void) connectionDidFinishLoading: (NSURLConnection*) connection
  223857. {
  223858. hasFinished = true;
  223859. initialised = true;
  223860. runLoopThread->signalThreadShouldExit();
  223861. }
  223862. - (BOOL) isOpen
  223863. {
  223864. return connection != 0 && ! hasFailed;
  223865. }
  223866. - (int) readPosition
  223867. {
  223868. return position;
  223869. }
  223870. - (int) read: (char*) dest numBytes: (int) numNeeded
  223871. {
  223872. int numDone = 0;
  223873. while (numNeeded > 0)
  223874. {
  223875. int available = jmin (numNeeded, [data length]);
  223876. if (available > 0)
  223877. {
  223878. [dataLock lock];
  223879. [data getBytes: dest length: available];
  223880. [data replaceBytesInRange: NSMakeRange (0, available) withBytes: nil length: 0];
  223881. [dataLock unlock];
  223882. numDone += available;
  223883. numNeeded -= available;
  223884. dest += available;
  223885. }
  223886. else
  223887. {
  223888. if (hasFailed || hasFinished)
  223889. break;
  223890. Thread::sleep (1);
  223891. }
  223892. }
  223893. position += numDone;
  223894. return numDone;
  223895. }
  223896. - (void) stop
  223897. {
  223898. [connection cancel];
  223899. runLoopThread->stopThread (10000);
  223900. }
  223901. @end
  223902. BEGIN_JUCE_NAMESPACE
  223903. bool juce_isOnLine()
  223904. {
  223905. return true;
  223906. }
  223907. void* juce_openInternetFile (const String& url,
  223908. const String& headers,
  223909. const MemoryBlock& postData,
  223910. const bool isPost,
  223911. URL::OpenStreamProgressCallback* callback,
  223912. void* callbackContext,
  223913. int timeOutMs)
  223914. {
  223915. const ScopedAutoReleasePool pool;
  223916. NSMutableURLRequest* req = [NSMutableURLRequest
  223917. requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  223918. cachePolicy: NSURLRequestUseProtocolCachePolicy
  223919. timeoutInterval: timeOutMs <= 0 ? 60.0 : (timeOutMs / 1000.0)];
  223920. if (req == nil)
  223921. return 0;
  223922. [req setHTTPMethod: isPost ? @"POST" : @"GET"];
  223923. //[req setCachePolicy: NSURLRequestReloadIgnoringLocalAndRemoteCacheData];
  223924. StringArray headerLines;
  223925. headerLines.addLines (headers);
  223926. headerLines.removeEmptyStrings (true);
  223927. for (int i = 0; i < headerLines.size(); ++i)
  223928. {
  223929. const String key (headerLines[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  223930. const String value (headerLines[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  223931. if (key.isNotEmpty() && value.isNotEmpty())
  223932. [req addValue: juceStringToNS (value) forHTTPHeaderField: juceStringToNS (key)];
  223933. }
  223934. if (isPost && postData.getSize() > 0)
  223935. {
  223936. [req setHTTPBody: [NSData dataWithBytes: postData.getData()
  223937. length: postData.getSize()]];
  223938. }
  223939. JuceURLConnection* const s = [[JuceURLConnection alloc] initWithRequest: req
  223940. withCallback: callback
  223941. withContext: callbackContext];
  223942. if ([s isOpen])
  223943. return s;
  223944. [s release];
  223945. return 0;
  223946. }
  223947. void juce_closeInternetFile (void* handle)
  223948. {
  223949. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223950. if (s != 0)
  223951. {
  223952. const ScopedAutoReleasePool pool;
  223953. [s stop];
  223954. [s release];
  223955. }
  223956. }
  223957. int juce_readFromInternetFile (void* handle, void* buffer, int bytesToRead)
  223958. {
  223959. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223960. if (s != 0)
  223961. {
  223962. const ScopedAutoReleasePool pool;
  223963. return [s read: (char*) buffer numBytes: bytesToRead];
  223964. }
  223965. return 0;
  223966. }
  223967. int juce_seekInInternetFile (void* handle, int newPosition)
  223968. {
  223969. JuceURLConnection* const s = (JuceURLConnection*) handle;
  223970. if (s != 0)
  223971. return [s readPosition];
  223972. return 0;
  223973. }
  223974. #endif
  223975. /********* End of inlined file: juce_mac_Network.mm *********/
  223976. /********* Start of inlined file: juce_mac_Threads.mm *********/
  223977. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  223978. // compiled on its own).
  223979. #ifdef JUCE_INCLUDED_FILE
  223980. /*
  223981. Note that a lot of methods that you'd expect to find in this file actually
  223982. live in juce_posix_SharedCode.h!
  223983. */
  223984. void JUCE_API juce_threadEntryPoint (void*);
  223985. void* threadEntryProc (void* userData) throw()
  223986. {
  223987. const ScopedAutoReleasePool pool;
  223988. juce_threadEntryPoint (userData);
  223989. return 0;
  223990. }
  223991. void* juce_createThread (void* userData) throw()
  223992. {
  223993. pthread_t handle = 0;
  223994. if (pthread_create (&handle, 0, threadEntryProc, userData) == 0)
  223995. {
  223996. pthread_detach (handle);
  223997. return (void*) handle;
  223998. }
  223999. return 0;
  224000. }
  224001. void juce_killThread (void* handle) throw()
  224002. {
  224003. if (handle != 0)
  224004. pthread_cancel ((pthread_t) handle);
  224005. }
  224006. void juce_setCurrentThreadName (const String& /*name*/) throw()
  224007. {
  224008. }
  224009. int64 Thread::getCurrentThreadId() throw()
  224010. {
  224011. return (int64) pthread_self();
  224012. }
  224013. void juce_setThreadPriority (void* handle, int priority) throw()
  224014. {
  224015. if (handle == 0)
  224016. handle = (void*) pthread_self();
  224017. struct sched_param param;
  224018. int policy;
  224019. pthread_getschedparam ((pthread_t) handle, &policy, &param);
  224020. param.sched_priority = jlimit (1, 127, 1 + (priority * 126) / 11);
  224021. pthread_setschedparam ((pthread_t) handle, policy, &param);
  224022. }
  224023. void Thread::yield() throw()
  224024. {
  224025. sched_yield();
  224026. }
  224027. void Thread::setCurrentThreadAffinityMask (const uint32 affinityMask) throw()
  224028. {
  224029. // xxx
  224030. jassertfalse
  224031. }
  224032. bool Process::isForegroundProcess() throw()
  224033. {
  224034. return [NSApp isActive];
  224035. }
  224036. void Process::raisePrivilege()
  224037. {
  224038. jassertfalse
  224039. }
  224040. void Process::lowerPrivilege()
  224041. {
  224042. jassertfalse
  224043. }
  224044. void Process::terminate()
  224045. {
  224046. exit (0);
  224047. }
  224048. void Process::setPriority (ProcessPriority p)
  224049. {
  224050. // xxx
  224051. }
  224052. #endif
  224053. /********* End of inlined file: juce_mac_Threads.mm *********/
  224054. /********* Start of inlined file: juce_posix_SharedCode.h *********/
  224055. /*
  224056. This file contains posix routines that are common to both the Linux and Mac builds.
  224057. It gets included directly in the cpp files for these platforms.
  224058. */
  224059. CriticalSection::CriticalSection() throw()
  224060. {
  224061. pthread_mutexattr_t atts;
  224062. pthread_mutexattr_init (&atts);
  224063. pthread_mutexattr_settype (&atts, PTHREAD_MUTEX_RECURSIVE);
  224064. pthread_mutex_init (&internal, &atts);
  224065. }
  224066. CriticalSection::~CriticalSection() throw()
  224067. {
  224068. pthread_mutex_destroy (&internal);
  224069. }
  224070. void CriticalSection::enter() const throw()
  224071. {
  224072. pthread_mutex_lock (&internal);
  224073. }
  224074. bool CriticalSection::tryEnter() const throw()
  224075. {
  224076. return pthread_mutex_trylock (&internal) == 0;
  224077. }
  224078. void CriticalSection::exit() const throw()
  224079. {
  224080. pthread_mutex_unlock (&internal);
  224081. }
  224082. struct EventStruct
  224083. {
  224084. pthread_cond_t condition;
  224085. pthread_mutex_t mutex;
  224086. bool triggered;
  224087. };
  224088. WaitableEvent::WaitableEvent() throw()
  224089. {
  224090. EventStruct* const es = new EventStruct();
  224091. es->triggered = false;
  224092. pthread_cond_init (&es->condition, 0);
  224093. pthread_mutex_init (&es->mutex, 0);
  224094. internal = es;
  224095. }
  224096. WaitableEvent::~WaitableEvent() throw()
  224097. {
  224098. EventStruct* const es = (EventStruct*) internal;
  224099. pthread_cond_destroy (&es->condition);
  224100. pthread_mutex_destroy (&es->mutex);
  224101. delete es;
  224102. }
  224103. bool WaitableEvent::wait (const int timeOutMillisecs) const throw()
  224104. {
  224105. EventStruct* const es = (EventStruct*) internal;
  224106. bool ok = true;
  224107. pthread_mutex_lock (&es->mutex);
  224108. if (timeOutMillisecs < 0)
  224109. {
  224110. while (! es->triggered)
  224111. pthread_cond_wait (&es->condition, &es->mutex);
  224112. }
  224113. else
  224114. {
  224115. while (! es->triggered)
  224116. {
  224117. struct timeval t;
  224118. gettimeofday (&t, 0);
  224119. struct timespec time;
  224120. time.tv_sec = t.tv_sec + (timeOutMillisecs / 1000);
  224121. time.tv_nsec = (t.tv_usec + ((timeOutMillisecs % 1000) * 1000)) * 1000;
  224122. if (time.tv_nsec >= 1000000000)
  224123. {
  224124. time.tv_nsec -= 1000000000;
  224125. time.tv_sec++;
  224126. }
  224127. if (pthread_cond_timedwait (&es->condition, &es->mutex, &time) == ETIMEDOUT)
  224128. {
  224129. ok = false;
  224130. break;
  224131. }
  224132. }
  224133. }
  224134. es->triggered = false;
  224135. pthread_mutex_unlock (&es->mutex);
  224136. return ok;
  224137. }
  224138. void WaitableEvent::signal() const throw()
  224139. {
  224140. EventStruct* const es = (EventStruct*) internal;
  224141. pthread_mutex_lock (&es->mutex);
  224142. es->triggered = true;
  224143. pthread_cond_broadcast (&es->condition);
  224144. pthread_mutex_unlock (&es->mutex);
  224145. }
  224146. void WaitableEvent::reset() const throw()
  224147. {
  224148. EventStruct* const es = (EventStruct*) internal;
  224149. pthread_mutex_lock (&es->mutex);
  224150. es->triggered = false;
  224151. pthread_mutex_unlock (&es->mutex);
  224152. }
  224153. void JUCE_CALLTYPE Thread::sleep (int millisecs) throw()
  224154. {
  224155. struct timespec time;
  224156. time.tv_sec = millisecs / 1000;
  224157. time.tv_nsec = (millisecs % 1000) * 1000000;
  224158. nanosleep (&time, 0);
  224159. }
  224160. const tchar File::separator = T('/');
  224161. const tchar* File::separatorString = T("/");
  224162. bool juce_copyFile (const String& s, const String& d) throw();
  224163. static bool juce_stat (const String& fileName, struct stat& info) throw()
  224164. {
  224165. return fileName.isNotEmpty()
  224166. && (stat (fileName.toUTF8(), &info) == 0);
  224167. }
  224168. bool juce_isDirectory (const String& fileName) throw()
  224169. {
  224170. struct stat info;
  224171. return fileName.isEmpty()
  224172. || (juce_stat (fileName, info)
  224173. && ((info.st_mode & S_IFDIR) != 0));
  224174. }
  224175. bool juce_fileExists (const String& fileName, const bool dontCountDirectories) throw()
  224176. {
  224177. if (fileName.isEmpty())
  224178. return false;
  224179. const char* const fileNameUTF8 = fileName.toUTF8();
  224180. bool exists = access (fileNameUTF8, F_OK) == 0;
  224181. if (exists && dontCountDirectories)
  224182. {
  224183. struct stat info;
  224184. const int res = stat (fileNameUTF8, &info);
  224185. if (res == 0 && (info.st_mode & S_IFDIR) != 0)
  224186. exists = false;
  224187. }
  224188. return exists;
  224189. }
  224190. int64 juce_getFileSize (const String& fileName) throw()
  224191. {
  224192. struct stat info;
  224193. return juce_stat (fileName, info) ? info.st_size : 0;
  224194. }
  224195. bool juce_canWriteToFile (const String& fileName) throw()
  224196. {
  224197. return access (fileName.toUTF8(), W_OK) == 0;
  224198. }
  224199. bool juce_deleteFile (const String& fileName) throw()
  224200. {
  224201. const char* const fileNameUTF8 = fileName.toUTF8();
  224202. if (juce_isDirectory (fileName))
  224203. return rmdir (fileNameUTF8) == 0;
  224204. else
  224205. return remove (fileNameUTF8) == 0;
  224206. }
  224207. bool juce_moveFile (const String& source, const String& dest) throw()
  224208. {
  224209. if (rename (source.toUTF8(), dest.toUTF8()) == 0)
  224210. return true;
  224211. if (juce_canWriteToFile (source)
  224212. && juce_copyFile (source, dest))
  224213. {
  224214. if (juce_deleteFile (source))
  224215. return true;
  224216. juce_deleteFile (dest);
  224217. }
  224218. return false;
  224219. }
  224220. void juce_createDirectory (const String& fileName) throw()
  224221. {
  224222. mkdir (fileName.toUTF8(), 0777);
  224223. }
  224224. void* juce_fileOpen (const String& fileName, bool forWriting) throw()
  224225. {
  224226. const char* const fileNameUTF8 = fileName.toUTF8();
  224227. int flags = O_RDONLY;
  224228. if (forWriting)
  224229. {
  224230. if (juce_fileExists (fileName, false))
  224231. {
  224232. const int f = open (fileNameUTF8, O_RDWR, 00644);
  224233. if (f != -1)
  224234. lseek (f, 0, SEEK_END);
  224235. return (void*) f;
  224236. }
  224237. else
  224238. {
  224239. flags = O_RDWR + O_CREAT;
  224240. }
  224241. }
  224242. return (void*) open (fileNameUTF8, flags, 00644);
  224243. }
  224244. void juce_fileClose (void* handle) throw()
  224245. {
  224246. if (handle != 0)
  224247. close ((int) (pointer_sized_int) handle);
  224248. }
  224249. int juce_fileRead (void* handle, void* buffer, int size) throw()
  224250. {
  224251. if (handle != 0)
  224252. return read ((int) (pointer_sized_int) handle, buffer, size);
  224253. return 0;
  224254. }
  224255. int juce_fileWrite (void* handle, const void* buffer, int size) throw()
  224256. {
  224257. if (handle != 0)
  224258. return write ((int) (pointer_sized_int) handle, buffer, size);
  224259. return 0;
  224260. }
  224261. int64 juce_fileSetPosition (void* handle, int64 pos) throw()
  224262. {
  224263. if (handle != 0 && lseek ((int) (pointer_sized_int) handle, pos, SEEK_SET) == pos)
  224264. return pos;
  224265. return -1;
  224266. }
  224267. int64 juce_fileGetPosition (void* handle) throw()
  224268. {
  224269. if (handle != 0)
  224270. return lseek ((int) (pointer_sized_int) handle, 0, SEEK_CUR);
  224271. else
  224272. return -1;
  224273. }
  224274. void juce_fileFlush (void* handle) throw()
  224275. {
  224276. if (handle != 0)
  224277. fsync ((int) (pointer_sized_int) handle);
  224278. }
  224279. // if this file doesn't exist, find a parent of it that does..
  224280. static bool doStatFS (const File* file, struct statfs& result) throw()
  224281. {
  224282. File f (*file);
  224283. for (int i = 5; --i >= 0;)
  224284. {
  224285. if (f.exists())
  224286. break;
  224287. f = f.getParentDirectory();
  224288. }
  224289. return statfs (f.getFullPathName().toUTF8(), &result) == 0;
  224290. }
  224291. int64 File::getBytesFreeOnVolume() const throw()
  224292. {
  224293. int64 free_space = 0;
  224294. struct statfs buf;
  224295. if (doStatFS (this, buf))
  224296. // Note: this returns space available to non-super user
  224297. free_space = (int64) buf.f_bsize * (int64) buf.f_bavail;
  224298. return free_space;
  224299. }
  224300. const String juce_getVolumeLabel (const String& filenameOnVolume,
  224301. int& volumeSerialNumber) throw()
  224302. {
  224303. // There is no equivalent on Linux
  224304. volumeSerialNumber = 0;
  224305. return String::empty;
  224306. }
  224307. #if JUCE_64BIT
  224308. #define filedesc ((long long) internal)
  224309. #else
  224310. #define filedesc ((int) internal)
  224311. #endif
  224312. InterProcessLock::InterProcessLock (const String& name_) throw()
  224313. : internal (0),
  224314. name (name_),
  224315. reentrancyLevel (0)
  224316. {
  224317. #if JUCE_MAC
  224318. // (don't use getSpecialLocation() to avoid the temp folder being different for each app)
  224319. const File temp (File (T("~/Library/Caches/Juce")).getChildFile (name));
  224320. #else
  224321. const File temp (File::getSpecialLocation (File::tempDirectory).getChildFile (name));
  224322. #endif
  224323. temp.create();
  224324. internal = (void*) open (temp.getFullPathName().toUTF8(), O_RDWR);
  224325. }
  224326. InterProcessLock::~InterProcessLock() throw()
  224327. {
  224328. while (reentrancyLevel > 0)
  224329. this->exit();
  224330. close (filedesc);
  224331. }
  224332. bool InterProcessLock::enter (const int timeOutMillisecs) throw()
  224333. {
  224334. if (internal == 0)
  224335. return false;
  224336. if (reentrancyLevel != 0)
  224337. return true;
  224338. const int64 endTime = Time::currentTimeMillis() + timeOutMillisecs;
  224339. struct flock fl;
  224340. zerostruct (fl);
  224341. fl.l_whence = SEEK_SET;
  224342. fl.l_type = F_WRLCK;
  224343. for (;;)
  224344. {
  224345. const int result = fcntl (filedesc, F_SETLK, &fl);
  224346. if (result >= 0)
  224347. {
  224348. ++reentrancyLevel;
  224349. return true;
  224350. }
  224351. if (errno != EINTR)
  224352. {
  224353. if (timeOutMillisecs == 0
  224354. || (timeOutMillisecs > 0 && Time::currentTimeMillis() >= endTime))
  224355. break;
  224356. Thread::sleep (10);
  224357. }
  224358. }
  224359. return false;
  224360. }
  224361. void InterProcessLock::exit() throw()
  224362. {
  224363. if (reentrancyLevel > 0 && internal != 0)
  224364. {
  224365. --reentrancyLevel;
  224366. struct flock fl;
  224367. zerostruct (fl);
  224368. fl.l_whence = SEEK_SET;
  224369. fl.l_type = F_UNLCK;
  224370. for (;;)
  224371. {
  224372. const int result = fcntl (filedesc, F_SETLKW, &fl);
  224373. if (result >= 0 || errno != EINTR)
  224374. break;
  224375. }
  224376. }
  224377. }
  224378. /********* End of inlined file: juce_posix_SharedCode.h *********/
  224379. /********* Start of inlined file: juce_mac_Files.mm *********/
  224380. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224381. // compiled on its own).
  224382. #ifdef JUCE_INCLUDED_FILE
  224383. /*
  224384. Note that a lot of methods that you'd expect to find in this file actually
  224385. live in juce_posix_SharedCode.h!
  224386. */
  224387. static File executableFile;
  224388. const unsigned int macTimeToUnixTimeDiff = 0x7c25be90;
  224389. static uint64 utcDateTimeToUnixTime (const UTCDateTime& d) throw()
  224390. {
  224391. if (d.highSeconds == 0 && d.lowSeconds == 0 && d.fraction == 0)
  224392. return 0;
  224393. return (((((uint64) d.highSeconds) << 32) | (uint64) d.lowSeconds) * 1000)
  224394. + ((d.fraction * 1000) >> 16)
  224395. - 2082844800000ll;
  224396. }
  224397. static void unixTimeToUtcDateTime (uint64 t, UTCDateTime& d) throw()
  224398. {
  224399. if (t != 0)
  224400. t += 2082844800000ll;
  224401. d.highSeconds = (t / 1000) >> 32;
  224402. d.lowSeconds = (t / 1000) & (uint64) 0xffffffff;
  224403. d.fraction = ((t % 1000) << 16) / 1000;
  224404. }
  224405. void juce_getFileTimes (const String& fileName,
  224406. int64& modificationTime,
  224407. int64& accessTime,
  224408. int64& creationTime) throw()
  224409. {
  224410. modificationTime = 0;
  224411. accessTime = 0;
  224412. creationTime = 0;
  224413. FSRef fileRef;
  224414. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  224415. {
  224416. FSRefParam info;
  224417. zerostruct (info);
  224418. info.ref = &fileRef;
  224419. info.whichInfo = kFSCatInfoAllDates;
  224420. FSCatalogInfo catInfo;
  224421. info.catInfo = &catInfo;
  224422. if (PBGetCatalogInfoSync (&info) == noErr)
  224423. {
  224424. creationTime = utcDateTimeToUnixTime (catInfo.createDate);
  224425. accessTime = utcDateTimeToUnixTime (catInfo.accessDate);
  224426. modificationTime = utcDateTimeToUnixTime (catInfo.contentModDate);
  224427. }
  224428. }
  224429. }
  224430. bool juce_setFileTimes (const String& fileName,
  224431. int64 modificationTime,
  224432. int64 accessTime,
  224433. int64 creationTime) throw()
  224434. {
  224435. FSRef fileRef;
  224436. if (PlatformUtilities::makeFSRefFromPath (&fileRef, fileName))
  224437. {
  224438. FSRefParam info;
  224439. zerostruct (info);
  224440. info.ref = &fileRef;
  224441. info.whichInfo = kFSCatInfoAllDates;
  224442. FSCatalogInfo catInfo;
  224443. info.catInfo = &catInfo;
  224444. if (PBGetCatalogInfoSync (&info) == noErr)
  224445. {
  224446. if (creationTime != 0)
  224447. unixTimeToUtcDateTime (creationTime, catInfo.createDate);
  224448. if (modificationTime != 0)
  224449. unixTimeToUtcDateTime (modificationTime, catInfo.contentModDate);
  224450. if (accessTime != 0)
  224451. unixTimeToUtcDateTime (accessTime, catInfo.accessDate);
  224452. return PBSetCatalogInfoSync (&info) == noErr;
  224453. }
  224454. }
  224455. return false;
  224456. }
  224457. bool juce_setFileReadOnly (const String& fileName, bool isReadOnly) throw()
  224458. {
  224459. const char* const fileNameUTF8 = fileName.toUTF8();
  224460. struct stat info;
  224461. const int res = stat (fileNameUTF8, &info);
  224462. bool ok = false;
  224463. if (res == 0)
  224464. {
  224465. info.st_mode &= 0777; // Just permissions
  224466. if (isReadOnly)
  224467. info.st_mode &= ~(S_IWUSR | S_IWGRP | S_IWOTH);
  224468. else
  224469. // Give everybody write permission?
  224470. info.st_mode |= S_IWUSR | S_IWGRP | S_IWOTH;
  224471. ok = chmod (fileNameUTF8, info.st_mode) == 0;
  224472. }
  224473. return ok;
  224474. }
  224475. bool juce_copyFile (const String& src, const String& dst) throw()
  224476. {
  224477. const ScopedAutoReleasePool pool;
  224478. NSFileManager* fm = [NSFileManager defaultManager];
  224479. return [fm fileExistsAtPath: juceStringToNS (src)]
  224480. && [fm copyPath: juceStringToNS (src)
  224481. toPath: juceStringToNS (dst)
  224482. handler: nil];
  224483. }
  224484. const StringArray juce_getFileSystemRoots() throw()
  224485. {
  224486. StringArray s;
  224487. s.add (T("/"));
  224488. return s;
  224489. }
  224490. static bool isFileOnDriveType (const File* const f, const char** types) throw()
  224491. {
  224492. struct statfs buf;
  224493. if (doStatFS (f, buf))
  224494. {
  224495. const String type (buf.f_fstypename);
  224496. while (*types != 0)
  224497. if (type.equalsIgnoreCase (*types++))
  224498. return true;
  224499. }
  224500. return false;
  224501. }
  224502. bool File::isOnCDRomDrive() const throw()
  224503. {
  224504. static const char* const cdTypes[] = { "cd9660", "cdfs", "cddafs", "udf", 0 };
  224505. return isFileOnDriveType (this, (const char**) cdTypes);
  224506. }
  224507. bool File::isOnHardDisk() const throw()
  224508. {
  224509. static const char* const nonHDTypes[] = { "nfs", "smbfs", "ramfs", 0 };
  224510. return ! (isOnCDRomDrive() || isFileOnDriveType (this, (const char**) nonHDTypes));
  224511. }
  224512. bool File::isOnRemovableDrive() const throw()
  224513. {
  224514. jassertfalse // xxx not implemented for mac!
  224515. return false;
  224516. }
  224517. static bool juce_isHiddenFile (const String& path) throw()
  224518. {
  224519. FSRef ref;
  224520. if (! PlatformUtilities::makeFSRefFromPath (&ref, path))
  224521. return false;
  224522. FSCatalogInfo info;
  224523. FSGetCatalogInfo (&ref, kFSCatInfoNodeFlags | kFSCatInfoFinderInfo, &info, 0, 0, 0);
  224524. if ((info.nodeFlags & kFSNodeIsDirectoryBit) != 0)
  224525. return (((FolderInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  224526. return (((FileInfo*) &info.finderInfo)->finderFlags & kIsInvisible) != 0;
  224527. }
  224528. bool File::isHidden() const throw()
  224529. {
  224530. return juce_isHiddenFile (getFullPathName());
  224531. }
  224532. const File File::getSpecialLocation (const SpecialLocationType type)
  224533. {
  224534. const char* resultPath = 0;
  224535. switch (type)
  224536. {
  224537. case userHomeDirectory:
  224538. resultPath = nsStringToJuce (NSHomeDirectory());
  224539. break;
  224540. case userDocumentsDirectory:
  224541. resultPath = "~/Documents";
  224542. break;
  224543. case userDesktopDirectory:
  224544. resultPath = "~/Desktop";
  224545. break;
  224546. case userApplicationDataDirectory:
  224547. resultPath = "~/Library";
  224548. break;
  224549. case commonApplicationDataDirectory:
  224550. resultPath = "/Library";
  224551. break;
  224552. case globalApplicationsDirectory:
  224553. resultPath = "/Applications";
  224554. break;
  224555. case userMusicDirectory:
  224556. resultPath = "~/Music";
  224557. break;
  224558. case userMoviesDirectory:
  224559. resultPath = "~/Movies";
  224560. break;
  224561. case tempDirectory:
  224562. {
  224563. File tmp (T("~/Library/Caches/") + executableFile.getFileNameWithoutExtension());
  224564. tmp.createDirectory();
  224565. return tmp.getFullPathName();
  224566. }
  224567. case currentExecutableFile:
  224568. return executableFile;
  224569. case currentApplicationFile:
  224570. {
  224571. const File parent (executableFile.getParentDirectory());
  224572. return parent.getFullPathName().endsWithIgnoreCase (T("Contents/MacOS"))
  224573. ? parent.getParentDirectory().getParentDirectory()
  224574. : executableFile;
  224575. }
  224576. default:
  224577. jassertfalse // unknown type?
  224578. break;
  224579. }
  224580. if (resultPath != 0)
  224581. return File (PlatformUtilities::convertToPrecomposedUnicode (resultPath));
  224582. return File::nonexistent;
  224583. }
  224584. void juce_setCurrentExecutableFileName (const String& filename) throw()
  224585. {
  224586. executableFile = File::getCurrentWorkingDirectory()
  224587. .getChildFile (PlatformUtilities::convertToPrecomposedUnicode (filename));
  224588. }
  224589. void juce_setCurrentExecutableFileNameFromBundleId (const String& bundleId) throw()
  224590. {
  224591. const ScopedAutoReleasePool pool;
  224592. NSBundle* b = [NSBundle bundleWithIdentifier: juceStringToNS (bundleId)];
  224593. if (b != nil)
  224594. executableFile = nsStringToJuce ([b executablePath]);
  224595. }
  224596. const File File::getCurrentWorkingDirectory() throw()
  224597. {
  224598. char buf [2048];
  224599. getcwd (buf, sizeof(buf));
  224600. return File (PlatformUtilities::convertToPrecomposedUnicode (buf));
  224601. }
  224602. bool File::setAsCurrentWorkingDirectory() const throw()
  224603. {
  224604. return chdir (getFullPathName().toUTF8()) == 0;
  224605. }
  224606. struct FindFileStruct
  224607. {
  224608. String parentDir, wildCard;
  224609. DIR* dir;
  224610. bool getNextMatch (String& result, bool* const isDir, bool* const isHidden, int64* const fileSize,
  224611. Time* const modTime, Time* const creationTime, bool* const isReadOnly) throw()
  224612. {
  224613. const char* const wildCardUTF8 = wildCard.toUTF8();
  224614. for (;;)
  224615. {
  224616. struct dirent* const de = readdir (dir);
  224617. if (de == 0)
  224618. break;
  224619. if (fnmatch (wildCardUTF8, de->d_name, 0) == 0)
  224620. {
  224621. result = PlatformUtilities::convertToPrecomposedUnicode (String::fromUTF8 ((const uint8*) de->d_name));
  224622. const String path (parentDir + result);
  224623. if (isDir != 0 || fileSize != 0)
  224624. {
  224625. struct stat info;
  224626. const bool statOk = juce_stat (path, info);
  224627. if (isDir != 0)
  224628. *isDir = path.isEmpty() || (statOk && ((info.st_mode & S_IFDIR) != 0));
  224629. if (isHidden != 0)
  224630. *isHidden = (de->d_name[0] == '.')
  224631. || juce_isHiddenFile (path);
  224632. if (fileSize != 0)
  224633. *fileSize = statOk ? info.st_size : 0;
  224634. }
  224635. if (modTime != 0 || creationTime != 0)
  224636. {
  224637. int64 m, a, c;
  224638. juce_getFileTimes (path, m, a, c);
  224639. if (modTime != 0)
  224640. *modTime = m;
  224641. if (creationTime != 0)
  224642. *creationTime = c;
  224643. }
  224644. if (isReadOnly != 0)
  224645. *isReadOnly = ! juce_canWriteToFile (path);
  224646. return true;
  224647. }
  224648. }
  224649. return false;
  224650. }
  224651. };
  224652. // returns 0 on failure
  224653. void* juce_findFileStart (const String& directory, const String& wildCard, String& firstResultFile,
  224654. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime,
  224655. Time* creationTime, bool* isReadOnly) throw()
  224656. {
  224657. DIR* const d = opendir (directory.toUTF8());
  224658. if (d != 0)
  224659. {
  224660. FindFileStruct* const ff = new FindFileStruct();
  224661. ff->parentDir = directory;
  224662. if (!ff->parentDir.endsWithChar (File::separator))
  224663. ff->parentDir += File::separator;
  224664. ff->wildCard = wildCard;
  224665. ff->dir = d;
  224666. if (ff->getNextMatch (firstResultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly))
  224667. {
  224668. return ff;
  224669. }
  224670. else
  224671. {
  224672. firstResultFile = String::empty;
  224673. isDir = false;
  224674. closedir (d);
  224675. delete ff;
  224676. }
  224677. }
  224678. return 0;
  224679. }
  224680. bool juce_findFileNext (void* handle, String& resultFile,
  224681. bool* isDir, bool* isHidden, int64* fileSize, Time* modTime, Time* creationTime, bool* isReadOnly) throw()
  224682. {
  224683. FindFileStruct* const ff = (FindFileStruct*) handle;
  224684. if (ff != 0)
  224685. return ff->getNextMatch (resultFile, isDir, isHidden, fileSize, modTime, creationTime, isReadOnly);
  224686. return false;
  224687. }
  224688. void juce_findFileClose (void* handle) throw()
  224689. {
  224690. FindFileStruct* const ff = (FindFileStruct*)handle;
  224691. if (ff != 0)
  224692. {
  224693. closedir (ff->dir);
  224694. delete ff;
  224695. }
  224696. }
  224697. bool juce_launchExecutable (const String& pathAndArguments) throw()
  224698. {
  224699. char* const argv[4] = { "/bin/sh", "-c", (char*) (const char*) pathAndArguments, 0 };
  224700. const int cpid = fork();
  224701. if (cpid == 0)
  224702. {
  224703. // Child process
  224704. if (execve (argv[0], argv, 0) < 0)
  224705. exit (0);
  224706. }
  224707. else
  224708. {
  224709. if (cpid < 0)
  224710. return false;
  224711. }
  224712. return true;
  224713. }
  224714. bool juce_launchFile (const String& fileName,
  224715. const String& parameters) throw()
  224716. {
  224717. const ScopedAutoReleasePool pool;
  224718. if (parameters.isEmpty())
  224719. return [[NSWorkspace sharedWorkspace] openFile: juceStringToNS (fileName)];
  224720. bool ok = false;
  224721. FSRef ref;
  224722. if (PlatformUtilities::makeFSRefFromPath (&ref, fileName))
  224723. {
  224724. if (PlatformUtilities::isBundle (fileName))
  224725. {
  224726. NSMutableArray* urls = [NSMutableArray array];
  224727. StringArray docs;
  224728. docs.addTokens (parameters, true);
  224729. for (int i = 0; i < docs.size(); ++i)
  224730. [urls addObject: juceStringToNS (docs[i])];
  224731. ok = [[NSWorkspace sharedWorkspace] openURLs: urls
  224732. withAppBundleIdentifier: [[NSBundle bundleWithPath: juceStringToNS (fileName)] bundleIdentifier]
  224733. options: nil
  224734. additionalEventParamDescriptor: nil
  224735. launchIdentifiers: nil];
  224736. }
  224737. else
  224738. {
  224739. ok = juce_launchExecutable (T("\"") + fileName + T("\" ") + parameters);
  224740. }
  224741. }
  224742. return ok;
  224743. }
  224744. bool PlatformUtilities::makeFSRefFromPath (FSRef* destFSRef, const String& path)
  224745. {
  224746. return FSPathMakeRef ((const UInt8*) path.toUTF8(), destFSRef, 0) == noErr;
  224747. }
  224748. const String PlatformUtilities::makePathFromFSRef (FSRef* file)
  224749. {
  224750. uint8 path [2048];
  224751. zeromem (path, sizeof (path));
  224752. String result;
  224753. if (FSRefMakePath (file, (UInt8*) path, sizeof (path) - 1) == noErr)
  224754. result = String::fromUTF8 (path);
  224755. return PlatformUtilities::convertToPrecomposedUnicode (result);
  224756. }
  224757. OSType PlatformUtilities::getTypeOfFile (const String& filename)
  224758. {
  224759. const ScopedAutoReleasePool pool;
  224760. return NSHFSTypeCodeFromFileType (NSHFSTypeOfFile (juceStringToNS (filename)));
  224761. }
  224762. bool PlatformUtilities::isBundle (const String& filename)
  224763. {
  224764. const ScopedAutoReleasePool pool;
  224765. return [[NSWorkspace sharedWorkspace] isFilePackageAtPath: juceStringToNS (filename)];
  224766. }
  224767. #endif
  224768. /********* End of inlined file: juce_mac_Files.mm *********/
  224769. /********* Start of inlined file: juce_mac_MiscUtilities.mm *********/
  224770. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224771. // compiled on its own).
  224772. #ifdef JUCE_INCLUDED_FILE
  224773. ScopedAutoReleasePool::ScopedAutoReleasePool()
  224774. {
  224775. pool = [[NSAutoreleasePool alloc] init];
  224776. }
  224777. ScopedAutoReleasePool::~ScopedAutoReleasePool()
  224778. {
  224779. [((NSAutoreleasePool*) pool) release];
  224780. }
  224781. void PlatformUtilities::beep()
  224782. {
  224783. NSBeep();
  224784. }
  224785. bool AlertWindow::showNativeDialogBox (const String& title,
  224786. const String& bodyText,
  224787. bool isOkCancel)
  224788. {
  224789. const ScopedAutoReleasePool pool;
  224790. return NSRunAlertPanel (juceStringToNS (title),
  224791. juceStringToNS (bodyText),
  224792. @"Ok",
  224793. isOkCancel ? @"Cancel" : nil,
  224794. nil) == 0;
  224795. }
  224796. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  224797. {
  224798. if (files.size() == 0)
  224799. return false;
  224800. Component* sourceComp = Component::getComponentUnderMouse();
  224801. if (sourceComp == 0)
  224802. {
  224803. jassertfalse // this method must be called in response to a
  224804. // component's mouseDrag event!
  224805. return false;
  224806. }
  224807. const ScopedAutoReleasePool pool;
  224808. NSView* view = (NSView*) sourceComp->getWindowHandle();
  224809. if (view == 0)
  224810. return false;
  224811. NSPasteboard* pboard = [NSPasteboard pasteboardWithName: NSDragPboard];
  224812. [pboard declareTypes: [NSArray arrayWithObject: NSFilenamesPboardType]
  224813. owner: nil];
  224814. NSMutableArray* filesArray = [NSMutableArray arrayWithCapacity: 4];
  224815. for (int i = 0; i < files.size(); ++i)
  224816. [filesArray addObject: juceStringToNS (files[i])];
  224817. [pboard setPropertyList: filesArray
  224818. forType: NSFilenamesPboardType];
  224819. NSPoint dragPosition = [view convertPoint: [[[view window] currentEvent] locationInWindow]
  224820. fromView: nil];
  224821. dragPosition.x -= 16;
  224822. dragPosition.y -= 16;
  224823. [view dragImage: [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (files[0])]
  224824. at: dragPosition
  224825. offset: NSMakeSize (0, 0)
  224826. event: [[view window] currentEvent]
  224827. pasteboard: pboard
  224828. source: view
  224829. slideBack: YES];
  224830. return true;
  224831. }
  224832. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  224833. {
  224834. jassertfalse // not implemented!
  224835. return false;
  224836. }
  224837. bool Desktop::canUseSemiTransparentWindows() throw()
  224838. {
  224839. return true;
  224840. }
  224841. void Desktop::getMousePosition (int& x, int& y) throw()
  224842. {
  224843. const ScopedAutoReleasePool pool;
  224844. const NSPoint p ([NSEvent mouseLocation]);
  224845. x = roundFloatToInt (p.x);
  224846. y = roundFloatToInt ([[NSScreen mainScreen] frame].size.height - p.y);
  224847. }
  224848. void Desktop::setMousePosition (int x, int y) throw()
  224849. {
  224850. // this rubbish needs to be done around the warp call, to avoid causing a
  224851. // bizarre glitch..
  224852. CGAssociateMouseAndMouseCursorPosition (false);
  224853. CGSetLocalEventsSuppressionInterval (0);
  224854. CGPoint pos = { x, y };
  224855. CGWarpMouseCursorPosition (pos);
  224856. CGAssociateMouseAndMouseCursorPosition (true);
  224857. }
  224858. #if MACOS_10_4_OR_EARLIER
  224859. class ScreenSaverDefeater : public Timer,
  224860. public DeletedAtShutdown
  224861. {
  224862. public:
  224863. ScreenSaverDefeater() throw()
  224864. {
  224865. startTimer (10000);
  224866. timerCallback();
  224867. }
  224868. ~ScreenSaverDefeater() {}
  224869. void timerCallback()
  224870. {
  224871. if (Process::isForegroundProcess())
  224872. UpdateSystemActivity (UsrActivity);
  224873. }
  224874. };
  224875. static ScreenSaverDefeater* screenSaverDefeater = 0;
  224876. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  224877. {
  224878. if (screenSaverDefeater == 0)
  224879. screenSaverDefeater = new ScreenSaverDefeater();
  224880. }
  224881. bool Desktop::isScreenSaverEnabled() throw()
  224882. {
  224883. return screenSaverDefeater == 0;
  224884. }
  224885. #else
  224886. static IOPMAssertionID screenSaverDisablerID = 0;
  224887. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  224888. {
  224889. if (isEnabled)
  224890. {
  224891. if (screenSaverDisablerID != 0)
  224892. {
  224893. IOPMAssertionRelease (screenSaverDisablerID);
  224894. screenSaverDisablerID = 0;
  224895. }
  224896. }
  224897. else
  224898. {
  224899. if (screenSaverDisablerID == 0)
  224900. {
  224901. IOPMAssertionCreate (kIOPMAssertionTypeNoIdleSleep,
  224902. kIOPMAssertionLevelOn, &screenSaverDisablerID);
  224903. }
  224904. }
  224905. }
  224906. bool Desktop::isScreenSaverEnabled() throw()
  224907. {
  224908. return screenSaverDisablerID == 0;
  224909. }
  224910. #endif
  224911. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  224912. {
  224913. const ScopedAutoReleasePool pool;
  224914. monitorCoords.clear();
  224915. NSArray* screens = [NSScreen screens];
  224916. const float mainScreenBottom = [[NSScreen mainScreen] frame].size.height;
  224917. for (int i = 0; i < [screens count]; ++i)
  224918. {
  224919. NSScreen* s = (NSScreen*) [screens objectAtIndex: i];
  224920. NSRect r = clipToWorkArea ? [s visibleFrame]
  224921. : [s frame];
  224922. monitorCoords.add (Rectangle ((int) r.origin.x,
  224923. (int) (mainScreenBottom - (r.origin.y + r.size.height)),
  224924. (int) r.size.width,
  224925. (int) r.size.height));
  224926. }
  224927. jassert (monitorCoords.size() > 0);
  224928. }
  224929. #endif
  224930. /********* End of inlined file: juce_mac_MiscUtilities.mm *********/
  224931. /********* Start of inlined file: juce_mac_Debugging.mm *********/
  224932. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224933. // compiled on its own).
  224934. #ifdef JUCE_INCLUDED_FILE
  224935. void Logger::outputDebugString (const String& text) throw()
  224936. {
  224937. const ScopedAutoReleasePool pool;
  224938. NSLog (juceStringToNS (text + T("\n")));
  224939. }
  224940. void Logger::outputDebugPrintf (const tchar* format, ...) throw()
  224941. {
  224942. String text;
  224943. va_list args;
  224944. va_start (args, format);
  224945. text.vprintf(format, args);
  224946. outputDebugString (text);
  224947. }
  224948. bool JUCE_CALLTYPE juce_isRunningUnderDebugger() throw()
  224949. {
  224950. static char testResult = 0;
  224951. if (testResult == 0)
  224952. {
  224953. struct kinfo_proc info;
  224954. int m[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid() };
  224955. size_t sz = sizeof (info);
  224956. sysctl (m, 4, &info, &sz, 0, 0);
  224957. testResult = ((info.kp_proc.p_flag & P_TRACED) != 0) ? 1 : -1;
  224958. }
  224959. return testResult > 0;
  224960. }
  224961. bool JUCE_CALLTYPE Process::isRunningUnderDebugger() throw()
  224962. {
  224963. return juce_isRunningUnderDebugger();
  224964. }
  224965. #endif
  224966. /********* End of inlined file: juce_mac_Debugging.mm *********/
  224967. #if ! JUCE_ONLY_BUILD_CORE_LIBRARY
  224968. /********* Start of inlined file: juce_mac_NSViewComponentPeer.mm *********/
  224969. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  224970. // compiled on its own).
  224971. #ifdef JUCE_INCLUDED_FILE
  224972. class NSViewComponentPeer;
  224973. static int currentModifiers = 0;
  224974. END_JUCE_NAMESPACE
  224975. static void updateModifiers (NSEvent* e);
  224976. using namespace JUCE_NAMESPACE;
  224977. @interface JuceNSView : NSView
  224978. {
  224979. @public
  224980. NSViewComponentPeer* owner;
  224981. }
  224982. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner withFrame: (NSRect) frame;
  224983. - (void) dealloc;
  224984. - (BOOL) isOpaque;
  224985. - (void) drawRect: (NSRect) r;
  224986. - (void) mouseDown: (NSEvent*) ev;
  224987. - (void) mouseUp: (NSEvent*) ev;
  224988. - (void) mouseDragged: (NSEvent*) ev;
  224989. - (void) mouseMoved: (NSEvent*) ev;
  224990. - (void) mouseEntered: (NSEvent*) ev;
  224991. - (void) mouseExited: (NSEvent*) ev;
  224992. - (void) rightMouseDown: (NSEvent*) ev;
  224993. - (void) rightMouseDragged: (NSEvent*) ev;
  224994. - (void) rightMouseUp: (NSEvent*) ev;
  224995. - (void) scrollWheel: (NSEvent*) ev;
  224996. - (BOOL) acceptsFirstMouse: (NSEvent*) ev;
  224997. - (void) frameChanged: (NSNotification*) n;
  224998. - (void) keyDown: (NSEvent*) ev;
  224999. - (void) keyUp: (NSEvent*) ev;
  225000. - (void) flagsChanged: (NSEvent*) ev;
  225001. #if MACOS_10_4_OR_EARLIER
  225002. - (BOOL) performKeyEquivalent: (NSEvent*) ev;
  225003. #endif
  225004. - (BOOL) becomeFirstResponder;
  225005. - (BOOL) resignFirstResponder;
  225006. - (NSArray*) getSupportedDragTypes;
  225007. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender;
  225008. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender;
  225009. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender;
  225010. - (void) draggingEnded: (id <NSDraggingInfo>) sender;
  225011. - (void) draggingExited: (id <NSDraggingInfo>) sender;
  225012. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender;
  225013. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender;
  225014. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender;
  225015. @end
  225016. @interface JuceNSWindow : NSWindow
  225017. {
  225018. NSViewComponentPeer* owner;
  225019. }
  225020. - (void) setOwner: (NSViewComponentPeer*) owner;
  225021. - (BOOL) canBecomeKeyWindow;
  225022. - (BOOL) windowShouldClose: (id) window;
  225023. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen;
  225024. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize;
  225025. @end
  225026. BEGIN_JUCE_NAMESPACE
  225027. class NSViewComponentPeer : public ComponentPeer
  225028. {
  225029. public:
  225030. NSViewComponentPeer (Component* const component,
  225031. const int windowStyleFlags,
  225032. NSView* viewToAttachTo);
  225033. ~NSViewComponentPeer();
  225034. void* getNativeHandle() const;
  225035. void setVisible (bool shouldBeVisible);
  225036. void setTitle (const String& title);
  225037. void setPosition (int x, int y);
  225038. void setSize (int w, int h);
  225039. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen);
  225040. void getBounds (int& x, int& y, int& w, int& h, const bool global) const;
  225041. void getBounds (int& x, int& y, int& w, int& h) const;
  225042. int getScreenX() const;
  225043. int getScreenY() const;
  225044. void relativePositionToGlobal (int& x, int& y);
  225045. void globalPositionToRelative (int& x, int& y);
  225046. void setMinimised (bool shouldBeMinimised);
  225047. bool isMinimised() const;
  225048. void setFullScreen (bool shouldBeFullScreen);
  225049. bool isFullScreen() const;
  225050. bool contains (int x, int y, bool trueIfInAChildWindow) const;
  225051. const BorderSize getFrameSize() const;
  225052. bool setAlwaysOnTop (bool alwaysOnTop);
  225053. void toFront (bool makeActiveWindow);
  225054. void toBehind (ComponentPeer* other);
  225055. void setIcon (const Image& newIcon);
  225056. bool handleKeyEvent (NSEvent* ev, bool isKeyDown);
  225057. void viewFocusGain();
  225058. void viewFocusLoss();
  225059. bool isFocused() const;
  225060. void grabFocus();
  225061. void textInputRequired (int x, int y);
  225062. NSRect constrainRect (NSRect r);
  225063. void repaint (int x, int y, int w, int h);
  225064. void performAnyPendingRepaintsNow();
  225065. juce_UseDebuggingNewOperator
  225066. NSWindow* window;
  225067. JuceNSView* view;
  225068. bool isSharedWindow, fullScreen;
  225069. };
  225070. class JuceNSImage
  225071. {
  225072. public:
  225073. JuceNSImage (const int width, const int height, const bool hasAlpha)
  225074. : juceImage (hasAlpha ? Image::ARGB : Image::RGB,
  225075. width, height, hasAlpha)
  225076. {
  225077. lineStride = 0;
  225078. pixelStride = 0;
  225079. imageData = juceImage.lockPixelDataReadWrite (0, 0, width, height,
  225080. lineStride, pixelStride);
  225081. imageRep = [[NSBitmapImageRep alloc]
  225082. initWithBitmapDataPlanes: &imageData
  225083. pixelsWide: width
  225084. pixelsHigh: height
  225085. bitsPerSample: 8
  225086. samplesPerPixel: pixelStride
  225087. hasAlpha: hasAlpha
  225088. isPlanar: NO
  225089. colorSpaceName: NSCalibratedRGBColorSpace
  225090. bitmapFormat: /*NSAlphaFirstBitmapFormat*/ (NSBitmapFormat) 0
  225091. bytesPerRow: lineStride
  225092. bitsPerPixel: 8 * pixelStride ];
  225093. juceImage.releasePixelDataReadWrite (imageData);
  225094. }
  225095. ~JuceNSImage()
  225096. {
  225097. [imageRep release];
  225098. }
  225099. Image& getJuceImage() throw() { return juceImage; }
  225100. void draw (const float x, const float y,
  225101. const RectangleList& clip,
  225102. const int originX, const int originY) const
  225103. {
  225104. // Our data is BGRA and the damned image rep only takes RGBA, so
  225105. // we need to byte-swap the active areas if there's an alpha channel...
  225106. if (juceImage.hasAlphaChannel())
  225107. {
  225108. RectangleList::Iterator iter (clip);
  225109. while (iter.next())
  225110. {
  225111. const Rectangle* const r = iter.getRectangle();
  225112. swapRGBOrder (r->getX() + originX,
  225113. r->getY() + originY,
  225114. r->getWidth(),
  225115. r->getHeight());
  225116. }
  225117. }
  225118. NSPoint p;
  225119. p.x = x;
  225120. p.y = y;
  225121. [imageRep drawAtPoint: p];
  225122. }
  225123. void drawNSImage (NSImage* imageToDraw)
  225124. {
  225125. const ScopedAutoReleasePool pool;
  225126. [NSGraphicsContext setCurrentContext:
  225127. [NSGraphicsContext graphicsContextWithBitmapImageRep: imageRep]];
  225128. [imageToDraw drawAtPoint: NSZeroPoint
  225129. fromRect: NSMakeRect (0, 0, [imageToDraw size].width, [imageToDraw size].height)
  225130. operation: NSCompositeSourceOver
  225131. fraction: 1.0f];
  225132. [[NSGraphicsContext currentContext] flushGraphics];
  225133. if (juceImage.hasAlphaChannel())
  225134. swapRGBOrder (0, 0, juceImage.getWidth(), juceImage.getHeight());
  225135. }
  225136. private:
  225137. Image juceImage;
  225138. NSBitmapImageRep* imageRep;
  225139. uint8* imageData;
  225140. int pixelStride, lineStride;
  225141. void swapRGBOrder (const int x, const int y, const int w, int h) const
  225142. {
  225143. jassert (Rectangle (0, 0, juceImage.getWidth(), juceImage.getHeight())
  225144. .contains (Rectangle (x, y, w, h)));
  225145. uint8* start = imageData + x * pixelStride + y * lineStride;
  225146. while (--h >= 0)
  225147. {
  225148. uint8* p = start;
  225149. start += lineStride;
  225150. for (int i = w; --i >= 0;)
  225151. {
  225152. const uint8 temp = p[0];
  225153. p[0] = p[2];
  225154. p[2] = temp;
  225155. p += pixelStride;
  225156. }
  225157. }
  225158. }
  225159. };
  225160. static ComponentPeer* currentlyFocusedPeer = 0;
  225161. static VoidArray keysCurrentlyDown;
  225162. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  225163. {
  225164. if (keysCurrentlyDown.contains ((void*) keyCode))
  225165. return true;
  225166. if (keyCode >= 'A' && keyCode <= 'Z'
  225167. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toLowerCase ((tchar) keyCode)))
  225168. return true;
  225169. if (keyCode >= 'a' && keyCode <= 'z'
  225170. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toUpperCase ((tchar) keyCode)))
  225171. return true;
  225172. return false;
  225173. }
  225174. static int getKeyCodeFromEvent (NSEvent* ev)
  225175. {
  225176. String unicode (nsStringToJuce ([ev characters]));
  225177. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  225178. int keyCode = unmodified[0];
  225179. if (keyCode == 0x19) // (backwards-tab)
  225180. keyCode = 9;
  225181. return keyCode;
  225182. }
  225183. static void updateKeysDown (NSEvent* ev, bool isKeyDown)
  225184. {
  225185. updateModifiers (ev);
  225186. int keyCode = getKeyCodeFromEvent (ev);
  225187. if (keyCode != 0)
  225188. {
  225189. if (isKeyDown)
  225190. keysCurrentlyDown.addIfNotAlreadyThere ((void*) keyCode);
  225191. else
  225192. keysCurrentlyDown.removeValue ((void*) keyCode);
  225193. }
  225194. }
  225195. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  225196. {
  225197. return ModifierKeys (currentModifiers);
  225198. }
  225199. void ModifierKeys::updateCurrentModifiers() throw()
  225200. {
  225201. currentModifierFlags = currentModifiers;
  225202. }
  225203. END_JUCE_NAMESPACE
  225204. @implementation JuceNSView
  225205. - (JuceNSView*) initWithOwner: (NSViewComponentPeer*) owner_
  225206. withFrame: (NSRect) frame
  225207. {
  225208. [super initWithFrame: frame];
  225209. owner = owner_;
  225210. [[NSNotificationCenter defaultCenter]
  225211. addObserver: self
  225212. selector: @selector (frameChanged:)
  225213. name: NSViewFrameDidChangeNotification
  225214. object: self];
  225215. if (! owner_->isSharedWindow)
  225216. {
  225217. [[NSNotificationCenter defaultCenter]
  225218. addObserver: self
  225219. selector: @selector (frameChanged:)
  225220. name: NSWindowDidMoveNotification
  225221. object: owner_->window];
  225222. }
  225223. [self registerForDraggedTypes: [self getSupportedDragTypes]];
  225224. return self;
  225225. }
  225226. - (void) dealloc
  225227. {
  225228. [[NSNotificationCenter defaultCenter] removeObserver: self];
  225229. [super dealloc];
  225230. }
  225231. - (void) drawRect: (NSRect) r
  225232. {
  225233. if (r.size.width < 1.0f || r.size.height < 1.0f || owner == 0)
  225234. return;
  225235. const float y = [self frame].size.height - (r.origin.y + r.size.height);
  225236. JuceNSImage temp ((int) (r.size.width + 0.5f),
  225237. (int) (r.size.height + 0.5f),
  225238. ! owner->getComponent()->isOpaque());
  225239. LowLevelGraphicsSoftwareRenderer context (temp.getJuceImage());
  225240. const int originX = -roundFloatToInt (r.origin.x);
  225241. const int originY = -roundFloatToInt (y);
  225242. context.setOrigin (originX, originY);
  225243. const NSRect* rects = 0;
  225244. int numRects = 0;
  225245. [self getRectsBeingDrawn: &rects count: &numRects];
  225246. RectangleList clip;
  225247. for (int i = 0; i < numRects; ++i)
  225248. {
  225249. clip.addWithoutMerging (Rectangle (roundFloatToInt (rects[i].origin.x),
  225250. roundFloatToInt ([self frame].size.height - (rects[i].origin.y + rects[i].size.height)),
  225251. roundFloatToInt (rects[i].size.width),
  225252. roundFloatToInt (rects[i].size.height)));
  225253. }
  225254. if (context.reduceClipRegion (clip))
  225255. {
  225256. owner->handlePaint (context);
  225257. temp.draw (r.origin.x, r.origin.y, clip, originX, originY);
  225258. }
  225259. }
  225260. - (BOOL) isOpaque
  225261. {
  225262. if (owner == 0)
  225263. return true;
  225264. if (! owner->getComponent()->isValidComponent())
  225265. return false;
  225266. return owner->getComponent()->isOpaque();
  225267. }
  225268. static int64 getMouseTime (NSEvent* e) { return (int64) [e timestamp] * 1000.0; }
  225269. static void getMousePos (NSEvent* e, NSView* view, int& x, int& y)
  225270. {
  225271. NSPoint p = [view convertPoint: [e locationInWindow] fromView: nil];
  225272. x = roundFloatToInt (p.x);
  225273. y = roundFloatToInt ([view frame].size.height - p.y);
  225274. }
  225275. static void updateModifiers (NSEvent* e)
  225276. {
  225277. int m = currentModifiers & ~(ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier
  225278. | ModifierKeys::altModifier | ModifierKeys::commandModifier);
  225279. if (([e modifierFlags] & NSShiftKeyMask) != 0)
  225280. m |= ModifierKeys::shiftModifier;
  225281. if (([e modifierFlags] & NSControlKeyMask) != 0)
  225282. m |= ModifierKeys::ctrlModifier;
  225283. if (([e modifierFlags] & NSAlternateKeyMask) != 0)
  225284. m |= ModifierKeys::altModifier;
  225285. if (([e modifierFlags] & NSCommandKeyMask) != 0)
  225286. m |= ModifierKeys::commandModifier;
  225287. currentModifiers = m;
  225288. }
  225289. static int getModifierForButtonNumber (const int num) throw()
  225290. {
  225291. return num == 0 ? ModifierKeys::leftButtonModifier
  225292. : (num == 1 ? ModifierKeys::rightButtonModifier
  225293. : (num == 2 ? ModifierKeys::middleButtonModifier : 0));
  225294. }
  225295. - (void) mouseDown: (NSEvent*) ev
  225296. {
  225297. updateModifiers (ev);
  225298. currentModifiers |= getModifierForButtonNumber ([ev buttonNumber]);
  225299. int x, y;
  225300. getMousePos (ev, self, x, y);
  225301. if (owner != 0)
  225302. owner->handleMouseDown (x, y, getMouseTime (ev));
  225303. }
  225304. - (void) mouseUp: (NSEvent*) ev
  225305. {
  225306. const int oldMods = currentModifiers;
  225307. updateModifiers (ev);
  225308. currentModifiers &= ~getModifierForButtonNumber ([ev buttonNumber]);
  225309. int x, y;
  225310. getMousePos (ev, self, x, y);
  225311. if (owner != 0)
  225312. owner->handleMouseUp (oldMods, x, y, getMouseTime (ev));
  225313. }
  225314. - (void) mouseDragged: (NSEvent*) ev
  225315. {
  225316. updateModifiers (ev);
  225317. currentModifiers |= getModifierForButtonNumber ([ev buttonNumber]);
  225318. int x, y;
  225319. getMousePos (ev, self, x, y);
  225320. if (owner != 0)
  225321. owner->handleMouseDrag (x, y, getMouseTime (ev));
  225322. }
  225323. - (void) mouseMoved: (NSEvent*) ev
  225324. {
  225325. updateModifiers (ev);
  225326. int x, y;
  225327. getMousePos (ev, self, x, y);
  225328. if (owner != 0)
  225329. owner->handleMouseMove (x, y, getMouseTime (ev));
  225330. }
  225331. - (void) mouseEntered: (NSEvent*) ev
  225332. {
  225333. updateModifiers (ev);
  225334. int x, y;
  225335. getMousePos (ev, self, x, y);
  225336. if (owner != 0)
  225337. owner->handleMouseEnter (x, y, getMouseTime (ev));
  225338. }
  225339. - (void) mouseExited: (NSEvent*) ev
  225340. {
  225341. updateModifiers (ev);
  225342. int x, y;
  225343. getMousePos (ev, self, x, y);
  225344. if (owner != 0)
  225345. owner->handleMouseExit (x, y, getMouseTime (ev));
  225346. }
  225347. - (void) rightMouseDown: (NSEvent*) ev
  225348. {
  225349. [self mouseDown: ev];
  225350. }
  225351. - (void) rightMouseDragged: (NSEvent*) ev
  225352. {
  225353. [self mouseDragged: ev];
  225354. }
  225355. - (void) rightMouseUp: (NSEvent*) ev
  225356. {
  225357. [self mouseUp: ev];
  225358. }
  225359. - (void) scrollWheel: (NSEvent*) ev
  225360. {
  225361. updateModifiers (ev);
  225362. if (owner != 0)
  225363. owner->handleMouseWheel (roundFloatToInt ([ev deltaX] * 10.0f),
  225364. roundFloatToInt ([ev deltaY] * 10.0f),
  225365. getMouseTime (ev));
  225366. }
  225367. - (BOOL) acceptsFirstMouse: (NSEvent*) ev
  225368. {
  225369. return YES;
  225370. }
  225371. - (void) frameChanged: (NSNotification*) n
  225372. {
  225373. if (owner != 0)
  225374. owner->handleMovedOrResized();
  225375. }
  225376. - (void) keyDown: (NSEvent*) ev
  225377. {
  225378. bool used = false;
  225379. if (owner != 0)
  225380. {
  225381. updateKeysDown (ev, true);
  225382. used = owner->handleKeyEvent (ev, true);
  225383. if (([ev modifierFlags] & NSCommandKeyMask) != 0)
  225384. {
  225385. // for command keys, the key-up event is thrown away, so simulate one..
  225386. updateKeysDown (ev, false);
  225387. used = owner->handleKeyEvent (ev, false) || used;
  225388. }
  225389. }
  225390. if (! used)
  225391. [super keyDown: ev];
  225392. }
  225393. - (void) keyUp: (NSEvent*) ev
  225394. {
  225395. updateKeysDown (ev, false);
  225396. if (owner == 0 || ! owner->handleKeyEvent (ev, false))
  225397. [super keyUp: ev];
  225398. }
  225399. - (void) flagsChanged: (NSEvent*) ev
  225400. {
  225401. updateModifiers (ev);
  225402. if (owner != 0)
  225403. owner->handleModifierKeysChange();
  225404. }
  225405. #if MACOS_10_4_OR_EARLIER
  225406. - (BOOL) performKeyEquivalent: (NSEvent*) ev
  225407. {
  225408. if (owner != 0)
  225409. {
  225410. updateKeysDown (ev, true);
  225411. const bool used1 = owner->handleKeyEvent (ev, true);
  225412. updateKeysDown (ev, false);
  225413. const bool used2 = owner->handleKeyEvent (ev, false);
  225414. if (used1 || used2)
  225415. return true;
  225416. }
  225417. return [super performKeyEquivalent: ev];
  225418. }
  225419. #endif
  225420. - (BOOL) becomeFirstResponder
  225421. {
  225422. if (owner != 0)
  225423. owner->viewFocusGain();
  225424. return true;
  225425. }
  225426. - (BOOL) resignFirstResponder
  225427. {
  225428. if (owner != 0)
  225429. owner->viewFocusLoss();
  225430. return true;
  225431. }
  225432. - (NSArray*) getSupportedDragTypes
  225433. {
  225434. return [NSArray arrayWithObjects: NSFilenamesPboardType, /*NSFilesPromisePboardType, NSStringPboardType,*/ nil];
  225435. }
  225436. - (BOOL) sendDragCallback: (int) type sender: (id <NSDraggingInfo>) sender
  225437. {
  225438. NSString* bestType
  225439. = [[sender draggingPasteboard] availableTypeFromArray: [self getSupportedDragTypes]];
  225440. if (bestType == nil)
  225441. return false;
  225442. NSPoint p = [self convertPoint: [sender draggingLocation] fromView: nil];
  225443. int x = (int) p.x;
  225444. int y = (int) ([self frame].size.height - p.y);
  225445. StringArray files;
  225446. id list = [[sender draggingPasteboard] propertyListForType: bestType];
  225447. if (list == nil)
  225448. return false;
  225449. if ([list isKindOfClass: [NSArray class]])
  225450. {
  225451. NSArray* items = (NSArray*) list;
  225452. for (int i = 0; i < [items count]; ++i)
  225453. files.add (nsStringToJuce ((NSString*) [items objectAtIndex: i]));
  225454. }
  225455. if (files.size() == 0)
  225456. return false;
  225457. if (type == 0)
  225458. owner->handleFileDragMove (files, x, y);
  225459. else if (type == 1)
  225460. owner->handleFileDragExit (files);
  225461. else if (type == 2)
  225462. owner->handleFileDragDrop (files, x, y);
  225463. return true;
  225464. }
  225465. - (NSDragOperation) draggingEntered: (id <NSDraggingInfo>) sender
  225466. {
  225467. if ([self sendDragCallback: 0 sender: sender])
  225468. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  225469. else
  225470. return NSDragOperationNone;
  225471. }
  225472. - (NSDragOperation) draggingUpdated: (id <NSDraggingInfo>) sender
  225473. {
  225474. if ([self sendDragCallback: 0 sender: sender])
  225475. return NSDragOperationCopy | NSDragOperationMove | NSDragOperationGeneric;
  225476. else
  225477. return NSDragOperationNone;
  225478. }
  225479. - (void) draggingEnded: (id <NSDraggingInfo>) sender
  225480. {
  225481. [self sendDragCallback: 1 sender: sender];
  225482. }
  225483. - (void) draggingExited: (id <NSDraggingInfo>) sender
  225484. {
  225485. [self sendDragCallback: 1 sender: sender];
  225486. }
  225487. - (BOOL) prepareForDragOperation: (id <NSDraggingInfo>) sender
  225488. {
  225489. return YES;
  225490. }
  225491. - (BOOL) performDragOperation: (id <NSDraggingInfo>) sender
  225492. {
  225493. return [self sendDragCallback: 2 sender: sender];
  225494. }
  225495. - (void) concludeDragOperation: (id <NSDraggingInfo>) sender
  225496. {
  225497. }
  225498. @end
  225499. @implementation JuceNSWindow
  225500. - (void) setOwner: (NSViewComponentPeer*) owner_
  225501. {
  225502. owner = owner_;
  225503. }
  225504. - (BOOL) canBecomeKeyWindow
  225505. {
  225506. // If runnin as a plugin, let the component decide whether it's
  225507. // going to allow the window to get focused.
  225508. return JUCEApplication::getInstance() != 0
  225509. || (ComponentPeer::isValidPeer (owner)
  225510. && owner->getComponent()->getWantsKeyboardFocus());
  225511. }
  225512. - (BOOL) windowShouldClose: (id) window
  225513. {
  225514. if (! ComponentPeer::isValidPeer (owner))
  225515. return YES;
  225516. owner->handleUserClosingWindow();
  225517. return NO;
  225518. }
  225519. - (NSRect) constrainFrameRect: (NSRect) frameRect toScreen: (NSScreen*) screen
  225520. {
  225521. if (owner == 0)
  225522. return frameRect;
  225523. DBG (String (frameRect.origin.x) + " " + String (frameRect.origin.y) + " " + String (frameRect.size.width) + " " + String (frameRect.size.height));
  225524. frameRect = owner->constrainRect (frameRect);
  225525. DBG (String (frameRect.origin.x) + " " + String (frameRect.origin.y) + " " + String (frameRect.size.width) + " " + String (frameRect.size.height));
  225526. return frameRect;
  225527. }
  225528. - (NSSize) windowWillResize: (NSWindow*) window toSize: (NSSize) proposedFrameSize
  225529. {
  225530. if (owner == 0)
  225531. return proposedFrameSize;
  225532. NSRect frameRect = [self frame];
  225533. frameRect.size = proposedFrameSize;
  225534. DBG (String (frameRect.origin.x) + " " + String (frameRect.origin.y) + " " + String (frameRect.size.width) + " " + String (frameRect.size.height));
  225535. frameRect = owner->constrainRect (frameRect);
  225536. DBG (String (frameRect.origin.x) + " " + String (frameRect.origin.y) + " " + String (frameRect.size.width) + " " + String (frameRect.size.height));
  225537. return frameRect.size;
  225538. }
  225539. @end
  225540. BEGIN_JUCE_NAMESPACE
  225541. NSViewComponentPeer::NSViewComponentPeer (Component* const component,
  225542. const int windowStyleFlags,
  225543. NSView* viewToAttachTo)
  225544. : ComponentPeer (component, windowStyleFlags),
  225545. view (0),
  225546. window (0)
  225547. {
  225548. NSRect r;
  225549. r.origin.x = 0;
  225550. r.origin.y = 0;
  225551. r.size.width = (float) component->getWidth();
  225552. r.size.height = (float) component->getHeight();
  225553. view = [[JuceNSView alloc] initWithOwner: this withFrame: r];
  225554. [view setPostsFrameChangedNotifications: YES];
  225555. if (viewToAttachTo != 0)
  225556. {
  225557. window = [viewToAttachTo window];
  225558. [viewToAttachTo addSubview: view];
  225559. isSharedWindow = true;
  225560. }
  225561. else
  225562. {
  225563. isSharedWindow = false;
  225564. r.origin.x = (float) component->getX();
  225565. r.origin.y = (float) component->getY();
  225566. unsigned int style = 0;
  225567. if ((windowStyleFlags & windowHasTitleBar) == 0)
  225568. style = NSBorderlessWindowMask;
  225569. else
  225570. style = NSTitledWindowMask;
  225571. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  225572. style |= NSMiniaturizableWindowMask;
  225573. if ((windowStyleFlags & windowHasCloseButton) != 0)
  225574. style |= NSClosableWindowMask;
  225575. if ((windowStyleFlags & windowIsResizable) != 0)
  225576. style |= NSResizableWindowMask;
  225577. window = [[JuceNSWindow alloc] initWithContentRect: r
  225578. styleMask: style
  225579. backing: NSBackingStoreBuffered
  225580. defer: YES ];
  225581. [((JuceNSWindow*) window) setOwner: this];
  225582. [window setDelegate: window];
  225583. [window setOpaque: component->isOpaque()];
  225584. [window setHasShadow: ((windowStyleFlags & windowHasDropShadow) != 0)];
  225585. if (component->isAlwaysOnTop())
  225586. [window setLevel: NSFloatingWindowLevel];
  225587. [window setContentView: view];
  225588. [window setAutodisplay: YES];
  225589. [window setAcceptsMouseMovedEvents: YES];
  225590. [window setReleasedWhenClosed: YES];
  225591. [window setExcludedFromWindowsMenu: (windowStyleFlags & windowIsTemporary) != 0];
  225592. [window setIgnoresMouseEvents: (windowStyleFlags & windowIgnoresMouseClicks) != 0];
  225593. }
  225594. setVisible (component->isVisible());
  225595. }
  225596. NSViewComponentPeer::~NSViewComponentPeer()
  225597. {
  225598. view->owner = 0;
  225599. [view removeFromSuperview];
  225600. [view release];
  225601. if (! isSharedWindow)
  225602. [window close];
  225603. }
  225604. void* NSViewComponentPeer::getNativeHandle() const
  225605. {
  225606. return view;
  225607. }
  225608. void NSViewComponentPeer::setVisible (bool shouldBeVisible)
  225609. {
  225610. if (isSharedWindow)
  225611. {
  225612. [view setHidden: ! shouldBeVisible];
  225613. }
  225614. else
  225615. {
  225616. if (shouldBeVisible)
  225617. [window orderFront: nil];
  225618. else
  225619. [window orderOut: nil];
  225620. }
  225621. }
  225622. void NSViewComponentPeer::setTitle (const String& title)
  225623. {
  225624. const ScopedAutoReleasePool pool;
  225625. if (! isSharedWindow)
  225626. [window setTitle: juceStringToNS (title)];
  225627. }
  225628. void NSViewComponentPeer::setPosition (int x, int y)
  225629. {
  225630. setBounds (x, y, component->getWidth(), component->getHeight(), false);
  225631. }
  225632. void NSViewComponentPeer::setSize (int w, int h)
  225633. {
  225634. setBounds (component->getX(), component->getY(), w, h, false);
  225635. }
  225636. void NSViewComponentPeer::setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  225637. {
  225638. fullScreen = isNowFullScreen;
  225639. w = jmax (0, w);
  225640. h = jmax (0, h);
  225641. NSRect r;
  225642. r.origin.x = (float) x;
  225643. r.origin.y = (float) y;
  225644. r.size.width = (float) w;
  225645. r.size.height = (float) h;
  225646. if (isSharedWindow)
  225647. {
  225648. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  225649. if ([view frame].size.width != r.size.width
  225650. || [view frame].size.height != r.size.height)
  225651. [view setNeedsDisplay: true];
  225652. [view setFrame: r];
  225653. }
  225654. else
  225655. {
  225656. r.origin.y = [[NSScreen mainScreen] frame].size.height - (r.origin.y + r.size.height);
  225657. [window setFrame: r
  225658. display: true];
  225659. }
  225660. }
  225661. void NSViewComponentPeer::getBounds (int& x, int& y, int& w, int& h, const bool global) const
  225662. {
  225663. NSRect r = [view frame];
  225664. if (global && [view window] != 0)
  225665. {
  225666. r = [view convertRect: r toView: nil];
  225667. NSRect wr = [[view window] frame];
  225668. r.origin.x += wr.origin.x;
  225669. r.origin.y += wr.origin.y;
  225670. y = (int) ([[NSScreen mainScreen] frame].size.height - r.origin.y - r.size.height);
  225671. }
  225672. else
  225673. {
  225674. y = (int) ([[view superview] frame].size.height - r.origin.y - r.size.height);
  225675. }
  225676. x = (int) r.origin.x;
  225677. w = (int) r.size.width;
  225678. h = (int) r.size.height;
  225679. }
  225680. void NSViewComponentPeer::getBounds (int& x, int& y, int& w, int& h) const
  225681. {
  225682. getBounds (x, y, w, h, ! isSharedWindow);
  225683. }
  225684. int NSViewComponentPeer::getScreenX() const
  225685. {
  225686. int x, y, w, h;
  225687. getBounds (x, y, w, h, true);
  225688. return x;
  225689. }
  225690. int NSViewComponentPeer::getScreenY() const
  225691. {
  225692. int x, y, w, h;
  225693. getBounds (x, y, w, h, true);
  225694. return y;
  225695. }
  225696. void NSViewComponentPeer::relativePositionToGlobal (int& x, int& y)
  225697. {
  225698. int wx, wy, ww, wh;
  225699. getBounds (wx, wy, ww, wh, true);
  225700. x += wx;
  225701. y += wy;
  225702. }
  225703. void NSViewComponentPeer::globalPositionToRelative (int& x, int& y)
  225704. {
  225705. int wx, wy, ww, wh;
  225706. getBounds (wx, wy, ww, wh, true);
  225707. x -= wx;
  225708. y -= wy;
  225709. }
  225710. NSRect NSViewComponentPeer::constrainRect (NSRect r)
  225711. {
  225712. if (constrainer != 0)
  225713. {
  225714. NSRect current = [window frame];
  225715. current.origin.y = [[NSScreen mainScreen] frame].size.height - current.origin.y - current.size.height;
  225716. r.origin.y = [[NSScreen mainScreen] frame].size.height - r.origin.y - r.size.height;
  225717. int x = (int) r.origin.x;
  225718. int y = (int) r.origin.y;
  225719. int w = (int) r.size.width;
  225720. int h = (int) r.size.height;
  225721. Rectangle original ((int) current.origin.x, (int) current.origin.y,
  225722. (int) current.size.width, (int) current.size.height);
  225723. constrainer->checkBounds (x, y, w, h,
  225724. original,
  225725. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  225726. y != original.getY() && y + h == original.getBottom(),
  225727. x != original.getX() && x + w == original.getRight(),
  225728. y == original.getY() && y + h != original.getBottom(),
  225729. x == original.getX() && x + w != original.getRight());
  225730. r.origin.x = x;
  225731. r.origin.y = [[NSScreen mainScreen] frame].size.height - r.size.height - y;
  225732. r.size.width = w;
  225733. r.size.height = h;
  225734. }
  225735. return r;
  225736. }
  225737. void NSViewComponentPeer::setMinimised (bool shouldBeMinimised)
  225738. {
  225739. if (! isSharedWindow)
  225740. {
  225741. if (shouldBeMinimised)
  225742. [window miniaturize: nil];
  225743. else
  225744. [window deminiaturize: nil];
  225745. }
  225746. }
  225747. bool NSViewComponentPeer::isMinimised() const
  225748. {
  225749. return window != 0 && [window isMiniaturized];
  225750. }
  225751. void NSViewComponentPeer::setFullScreen (bool shouldBeFullScreen)
  225752. {
  225753. if (! isSharedWindow)
  225754. {
  225755. Rectangle r (lastNonFullscreenBounds);
  225756. setMinimised (false);
  225757. if (fullScreen != shouldBeFullScreen)
  225758. {
  225759. if (shouldBeFullScreen)
  225760. r = Desktop::getInstance().getMainMonitorArea();
  225761. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  225762. if (r != getComponent()->getBounds() && ! r.isEmpty())
  225763. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  225764. }
  225765. }
  225766. }
  225767. bool NSViewComponentPeer::isFullScreen() const
  225768. {
  225769. return fullScreen;
  225770. }
  225771. bool NSViewComponentPeer::contains (int x, int y, bool trueIfInAChildWindow) const
  225772. {
  225773. if (((unsigned int) x) >= (unsigned int) component->getWidth()
  225774. || ((unsigned int) y) >= (unsigned int) component->getHeight())
  225775. return false;
  225776. NSPoint p;
  225777. p.x = (float) x;
  225778. p.y = (float) y;
  225779. NSView* v = [view hitTest: p];
  225780. if (trueIfInAChildWindow)
  225781. return v != nil;
  225782. return v == view;
  225783. }
  225784. const BorderSize NSViewComponentPeer::getFrameSize() const
  225785. {
  225786. BorderSize b;
  225787. if (! isSharedWindow)
  225788. {
  225789. NSRect v = [view convertRect: [view frame] toView: nil];
  225790. NSRect w = [window frame];
  225791. b.setTop ((int) (w.size.height - (v.origin.y + v.size.height)));
  225792. b.setBottom ((int) v.origin.y);
  225793. b.setLeft ((int) v.origin.x);
  225794. b.setRight ((int) (w.size.width - (v.origin.x + v.size.width)));
  225795. }
  225796. return b;
  225797. }
  225798. bool NSViewComponentPeer::setAlwaysOnTop (bool alwaysOnTop)
  225799. {
  225800. if (! isSharedWindow)
  225801. {
  225802. [window setLevel: alwaysOnTop ? NSFloatingWindowLevel
  225803. : NSNormalWindowLevel];
  225804. }
  225805. return true;
  225806. }
  225807. void NSViewComponentPeer::toFront (bool makeActiveWindow)
  225808. {
  225809. if (isSharedWindow)
  225810. {
  225811. [[view superview] addSubview: view
  225812. positioned: NSWindowAbove
  225813. relativeTo: nil];
  225814. }
  225815. if (window != 0)
  225816. {
  225817. if (makeActiveWindow)
  225818. [window makeKeyAndOrderFront: nil];
  225819. else
  225820. [window orderFront: nil];
  225821. }
  225822. }
  225823. void NSViewComponentPeer::toBehind (ComponentPeer* other)
  225824. {
  225825. NSViewComponentPeer* o = (NSViewComponentPeer*) other;
  225826. if (isSharedWindow)
  225827. {
  225828. [[view superview] addSubview: view
  225829. positioned: NSWindowBelow
  225830. relativeTo: o->view];
  225831. }
  225832. else
  225833. {
  225834. [window orderWindow: NSWindowBelow
  225835. relativeTo: o->window != 0 ? [o->window windowNumber]
  225836. : nil ];
  225837. }
  225838. }
  225839. void NSViewComponentPeer::setIcon (const Image& /*newIcon*/)
  225840. {
  225841. // to do..
  225842. }
  225843. void NSViewComponentPeer::viewFocusGain()
  225844. {
  225845. const MessageManagerLock messLock;
  225846. if (currentlyFocusedPeer != this)
  225847. {
  225848. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  225849. currentlyFocusedPeer->handleFocusLoss();
  225850. currentlyFocusedPeer = this;
  225851. handleFocusGain();
  225852. }
  225853. }
  225854. void NSViewComponentPeer::viewFocusLoss()
  225855. {
  225856. if (currentlyFocusedPeer == this)
  225857. {
  225858. currentlyFocusedPeer = 0;
  225859. handleFocusLoss();
  225860. }
  225861. }
  225862. void juce_HandleProcessFocusChange()
  225863. {
  225864. keysCurrentlyDown.clear();
  225865. if (NSViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  225866. {
  225867. if (Process::isForegroundProcess())
  225868. currentlyFocusedPeer->handleFocusGain();
  225869. else
  225870. currentlyFocusedPeer->handleFocusLoss();
  225871. }
  225872. }
  225873. bool NSViewComponentPeer::isFocused() const
  225874. {
  225875. return window != 0 && [window isKeyWindow];
  225876. }
  225877. void NSViewComponentPeer::grabFocus()
  225878. {
  225879. if (window != 0)
  225880. {
  225881. [window makeKeyWindow];
  225882. [window makeFirstResponder: view];
  225883. }
  225884. }
  225885. void NSViewComponentPeer::textInputRequired (int /*x*/, int /*y*/)
  225886. {
  225887. }
  225888. bool NSViewComponentPeer::handleKeyEvent (NSEvent* ev, bool isKeyDown)
  225889. {
  225890. String unicode (nsStringToJuce ([ev characters]));
  225891. String unmodified (nsStringToJuce ([ev charactersIgnoringModifiers]));
  225892. int keyCode = getKeyCodeFromEvent (ev);
  225893. //DBG ("unicode: " + unicode + " " + String::toHexString ((int) unicode[0]));
  225894. //DBG ("unmodified: " + unmodified + " " + String::toHexString ((int) unmodified[0]));
  225895. if (unicode.isNotEmpty() || keyCode != 0)
  225896. {
  225897. if (isKeyDown)
  225898. {
  225899. bool used = false;
  225900. while (unicode.length() > 0)
  225901. {
  225902. juce_wchar textCharacter = unicode[0];
  225903. unicode = unicode.substring (1);
  225904. used = handleKeyUpOrDown() || used;
  225905. used = handleKeyPress (keyCode, textCharacter) || used;
  225906. }
  225907. return used;
  225908. }
  225909. else
  225910. {
  225911. if (handleKeyUpOrDown())
  225912. return true;
  225913. }
  225914. }
  225915. return false;
  225916. }
  225917. void NSViewComponentPeer::repaint (int x, int y, int w, int h)
  225918. {
  225919. [view setNeedsDisplayInRect:
  225920. NSMakeRect ((float) x, (float) ([view frame].size.height - (y + h)),
  225921. (float) w, (float) h)];
  225922. }
  225923. void NSViewComponentPeer::performAnyPendingRepaintsNow()
  225924. {
  225925. [view displayIfNeeded];
  225926. }
  225927. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  225928. {
  225929. return new NSViewComponentPeer (this, styleFlags, (NSView*) windowToAttachTo);
  225930. }
  225931. static Image* NSImageToJuceImage (NSImage* image)
  225932. {
  225933. JuceNSImage juceIm ((int) [image size].width,
  225934. (int) [image size].height,
  225935. true);
  225936. juceIm.drawNSImage (image);
  225937. return juceIm.getJuceImage().createCopy();
  225938. }
  225939. Image* juce_createIconForFile (const File& file)
  225940. {
  225941. const ScopedAutoReleasePool pool;
  225942. NSImage* im = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  225943. return NSImageToJuceImage (im);
  225944. }
  225945. const int KeyPress::spaceKey = ' ';
  225946. const int KeyPress::returnKey = 0x0d;
  225947. const int KeyPress::escapeKey = 0x1b;
  225948. const int KeyPress::backspaceKey = 0x7f;
  225949. const int KeyPress::leftKey = NSLeftArrowFunctionKey;
  225950. const int KeyPress::rightKey = NSRightArrowFunctionKey;
  225951. const int KeyPress::upKey = NSUpArrowFunctionKey;
  225952. const int KeyPress::downKey = NSDownArrowFunctionKey;
  225953. const int KeyPress::pageUpKey = NSPageUpFunctionKey;
  225954. const int KeyPress::pageDownKey = NSPageDownFunctionKey;
  225955. const int KeyPress::endKey = NSEndFunctionKey;
  225956. const int KeyPress::homeKey = NSHomeFunctionKey;
  225957. const int KeyPress::deleteKey = NSDeleteFunctionKey;
  225958. const int KeyPress::insertKey = -1;
  225959. const int KeyPress::tabKey = 9;
  225960. const int KeyPress::F1Key = NSF1FunctionKey;
  225961. const int KeyPress::F2Key = NSF2FunctionKey;
  225962. const int KeyPress::F3Key = NSF3FunctionKey;
  225963. const int KeyPress::F4Key = NSF4FunctionKey;
  225964. const int KeyPress::F5Key = NSF5FunctionKey;
  225965. const int KeyPress::F6Key = NSF6FunctionKey;
  225966. const int KeyPress::F7Key = NSF7FunctionKey;
  225967. const int KeyPress::F8Key = NSF8FunctionKey;
  225968. const int KeyPress::F9Key = NSF9FunctionKey;
  225969. const int KeyPress::F10Key = NSF10FunctionKey;
  225970. const int KeyPress::F11Key = NSF1FunctionKey;
  225971. const int KeyPress::F12Key = NSF12FunctionKey;
  225972. const int KeyPress::F13Key = NSF13FunctionKey;
  225973. const int KeyPress::F14Key = NSF14FunctionKey;
  225974. const int KeyPress::F15Key = NSF15FunctionKey;
  225975. const int KeyPress::F16Key = NSF16FunctionKey;
  225976. const int KeyPress::numberPad0 = 0x30020;
  225977. const int KeyPress::numberPad1 = 0x30021;
  225978. const int KeyPress::numberPad2 = 0x30022;
  225979. const int KeyPress::numberPad3 = 0x30023;
  225980. const int KeyPress::numberPad4 = 0x30024;
  225981. const int KeyPress::numberPad5 = 0x30025;
  225982. const int KeyPress::numberPad6 = 0x30026;
  225983. const int KeyPress::numberPad7 = 0x30027;
  225984. const int KeyPress::numberPad8 = 0x30028;
  225985. const int KeyPress::numberPad9 = 0x30029;
  225986. const int KeyPress::numberPadAdd = 0x3002a;
  225987. const int KeyPress::numberPadSubtract = 0x3002b;
  225988. const int KeyPress::numberPadMultiply = 0x3002c;
  225989. const int KeyPress::numberPadDivide = 0x3002d;
  225990. const int KeyPress::numberPadSeparator = 0x3002e;
  225991. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  225992. const int KeyPress::numberPadEquals = 0x30030;
  225993. const int KeyPress::numberPadDelete = 0x30031;
  225994. const int KeyPress::playKey = 0x30000;
  225995. const int KeyPress::stopKey = 0x30001;
  225996. const int KeyPress::fastForwardKey = 0x30002;
  225997. const int KeyPress::rewindKey = 0x30003;
  225998. #endif
  225999. /********* End of inlined file: juce_mac_NSViewComponentPeer.mm *********/
  226000. /********* Start of inlined file: juce_mac_MouseCursor.mm *********/
  226001. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226002. // compiled on its own).
  226003. #ifdef JUCE_INCLUDED_FILE
  226004. static NSImage* juceImageToNSImage (const Image& image)
  226005. {
  226006. const ScopedAutoReleasePool pool;
  226007. int lineStride, pixelStride;
  226008. const uint8* pixels = image.lockPixelDataReadOnly (0, 0, image.getWidth(), image.getHeight(),
  226009. lineStride, pixelStride);
  226010. NSBitmapImageRep* rep = [[NSBitmapImageRep alloc]
  226011. initWithBitmapDataPlanes: NULL
  226012. pixelsWide: image.getWidth()
  226013. pixelsHigh: image.getHeight()
  226014. bitsPerSample: 8
  226015. samplesPerPixel: image.hasAlphaChannel() ? 4 : 3
  226016. hasAlpha: image.hasAlphaChannel()
  226017. isPlanar: NO
  226018. colorSpaceName: NSCalibratedRGBColorSpace
  226019. bitmapFormat: (NSBitmapFormat) 0
  226020. bytesPerRow: lineStride
  226021. bitsPerPixel: pixelStride * 8];
  226022. unsigned char* newData = [rep bitmapData];
  226023. memcpy (newData, pixels, lineStride * image.getHeight());
  226024. image.releasePixelDataReadOnly (pixels);
  226025. NSImage* im = [[NSImage alloc] init];
  226026. [im addRepresentation: rep];
  226027. [rep release];
  226028. return im;
  226029. }
  226030. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  226031. {
  226032. NSImage* im = juceImageToNSImage (image);
  226033. NSCursor* c = [[NSCursor alloc] initWithImage: im
  226034. hotSpot: NSMakePoint (hotspotX, hotspotY)];
  226035. [im release];
  226036. return (void*) c;
  226037. }
  226038. static void* juce_cursorFromData (const unsigned char* data, const int size, float hx, float hy) throw()
  226039. {
  226040. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  226041. jassert (im != 0);
  226042. if (im == 0)
  226043. return 0;
  226044. void* const curs = juce_createMouseCursorFromImage (*im,
  226045. (int) (hx * im->getWidth()),
  226046. (int) (hy * im->getHeight()));
  226047. delete im;
  226048. return curs;
  226049. }
  226050. static void* juce_cursorFromWebKitFile (const char* filename, float hx, float hy)
  226051. {
  226052. File f ("/System/Library/Frameworks/WebKit.framework/Frameworks/WebCore.framework/Resources");
  226053. MemoryBlock mb;
  226054. if (f.getChildFile (filename).loadFileAsData (mb))
  226055. return juce_cursorFromData ((const unsigned char*) mb.getData(), mb.getSize(), hx, hy);
  226056. return 0;
  226057. }
  226058. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  226059. {
  226060. const ScopedAutoReleasePool pool;
  226061. NSCursor* c = 0;
  226062. switch (type)
  226063. {
  226064. case MouseCursor::NormalCursor:
  226065. c = [NSCursor arrowCursor];
  226066. break;
  226067. case MouseCursor::NoCursor:
  226068. {
  226069. Image blank (Image::ARGB, 8, 8, true);
  226070. return juce_createMouseCursorFromImage (blank, 0, 0);
  226071. }
  226072. case MouseCursor::DraggingHandCursor:
  226073. c = [NSCursor openHandCursor];
  226074. break;
  226075. case MouseCursor::CopyingCursor:
  226076. return juce_cursorFromWebKitFile ("copyCursor.png", 0, 0);
  226077. case MouseCursor::WaitCursor:
  226078. c = [NSCursor arrowCursor]; // avoid this on the mac, let the OS provide the beachball
  226079. break;
  226080. //return juce_cursorFromWebKitFile ("waitCursor.png", 0.5f, 0.5f);
  226081. case MouseCursor::IBeamCursor:
  226082. c = [NSCursor IBeamCursor];
  226083. break;
  226084. case MouseCursor::PointingHandCursor:
  226085. c = [NSCursor pointingHandCursor];
  226086. break;
  226087. case MouseCursor::LeftRightResizeCursor:
  226088. c = [NSCursor resizeLeftRightCursor];
  226089. break;
  226090. case MouseCursor::LeftEdgeResizeCursor:
  226091. c = [NSCursor resizeLeftCursor];
  226092. break;
  226093. case MouseCursor::RightEdgeResizeCursor:
  226094. c = [NSCursor resizeRightCursor];
  226095. break;
  226096. case MouseCursor::UpDownResizeCursor:
  226097. case MouseCursor::TopEdgeResizeCursor:
  226098. case MouseCursor::BottomEdgeResizeCursor:
  226099. return juce_cursorFromWebKitFile ("northSouthResizeCursor.png", 0.5f, 0.5f);
  226100. case MouseCursor::TopLeftCornerResizeCursor:
  226101. case MouseCursor::BottomRightCornerResizeCursor:
  226102. return juce_cursorFromWebKitFile ("northWestSouthEastResizeCursor.png", 0.5f, 0.5f);
  226103. case MouseCursor::TopRightCornerResizeCursor:
  226104. case MouseCursor::BottomLeftCornerResizeCursor:
  226105. return juce_cursorFromWebKitFile ("northEastSouthWestResizeCursor.png", 0.5f, 0.5f);
  226106. case MouseCursor::UpDownLeftRightResizeCursor:
  226107. return juce_cursorFromWebKitFile ("moveCursor.png", 0.5f, 0.5f);
  226108. case MouseCursor::CrosshairCursor:
  226109. c = [NSCursor crosshairCursor];
  226110. break;
  226111. }
  226112. [c retain];
  226113. return (void*) c;
  226114. }
  226115. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  226116. {
  226117. NSCursor* c = (NSCursor*) cursorHandle;
  226118. [c release];
  226119. }
  226120. void MouseCursor::showInAllWindows() const throw()
  226121. {
  226122. showInWindow (0);
  226123. }
  226124. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  226125. {
  226126. NSCursor* const c = (NSCursor*) getHandle();
  226127. [c set];
  226128. }
  226129. #endif
  226130. /********* End of inlined file: juce_mac_MouseCursor.mm *********/
  226131. /********* Start of inlined file: juce_mac_NSViewComponent.mm *********/
  226132. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226133. // compiled on its own).
  226134. #ifdef JUCE_INCLUDED_FILE
  226135. class NSViewComponentInternal : public ComponentMovementWatcher
  226136. {
  226137. Component* const owner;
  226138. NSViewComponentPeer* currentPeer;
  226139. bool wasShowing;
  226140. public:
  226141. NSView* view;
  226142. NSViewComponentInternal (NSView* view_, Component* const owner_)
  226143. : ComponentMovementWatcher (owner_),
  226144. owner (owner_),
  226145. wasShowing (false),
  226146. currentPeer (0),
  226147. view (view_)
  226148. {
  226149. [view retain];
  226150. if (owner_->isShowing())
  226151. componentPeerChanged();
  226152. }
  226153. ~NSViewComponentInternal()
  226154. {
  226155. [view removeFromSuperview];
  226156. [view release];
  226157. }
  226158. void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/)
  226159. {
  226160. Component* const topComp = owner->getTopLevelComponent();
  226161. if (topComp->getPeer() != 0)
  226162. {
  226163. int x = 0, y = 0;
  226164. owner->relativePositionToOtherComponent (topComp, x, y);
  226165. NSRect r;
  226166. r.origin.x = (float) x;
  226167. r.origin.y = (float) y;
  226168. r.size.width = (float) owner->getWidth();
  226169. r.size.height = (float) owner->getHeight();
  226170. r.origin.y = [[view superview] frame].size.height - (r.origin.y + r.size.height);
  226171. [view setFrame: r];
  226172. }
  226173. }
  226174. void componentPeerChanged()
  226175. {
  226176. NSViewComponentPeer* const peer = dynamic_cast <NSViewComponentPeer*> (owner->getPeer());
  226177. if (currentPeer != peer)
  226178. {
  226179. [view removeFromSuperview];
  226180. currentPeer = peer;
  226181. if (peer != 0)
  226182. {
  226183. [peer->view addSubview: view];
  226184. componentMovedOrResized (false, false);
  226185. }
  226186. }
  226187. [view setHidden: ! owner->isShowing()];
  226188. }
  226189. void componentVisibilityChanged (Component&)
  226190. {
  226191. componentPeerChanged();
  226192. }
  226193. juce_UseDebuggingNewOperator
  226194. private:
  226195. NSViewComponentInternal (const NSViewComponentInternal&);
  226196. const NSViewComponentInternal& operator= (const NSViewComponentInternal&);
  226197. };
  226198. NSViewComponent::NSViewComponent()
  226199. : info (0)
  226200. {
  226201. }
  226202. NSViewComponent::~NSViewComponent()
  226203. {
  226204. delete info;
  226205. }
  226206. void NSViewComponent::setView (void* view)
  226207. {
  226208. if (view != getView())
  226209. {
  226210. deleteAndZero (info);
  226211. if (view != 0)
  226212. info = new NSViewComponentInternal ((NSView*) view, this);
  226213. }
  226214. }
  226215. void* NSViewComponent::getView() const
  226216. {
  226217. return info == 0 ? 0 : info->view;
  226218. }
  226219. void NSViewComponent::paint (Graphics& g)
  226220. {
  226221. }
  226222. #endif
  226223. /********* End of inlined file: juce_mac_NSViewComponent.mm *********/
  226224. /********* Start of inlined file: juce_mac_AppleRemote.mm *********/
  226225. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226226. // compiled on its own).
  226227. #ifdef JUCE_INCLUDED_FILE
  226228. AppleRemoteDevice::AppleRemoteDevice()
  226229. : device (0),
  226230. queue (0),
  226231. remoteId (0)
  226232. {
  226233. }
  226234. AppleRemoteDevice::~AppleRemoteDevice()
  226235. {
  226236. stop();
  226237. }
  226238. static io_object_t getAppleRemoteDevice() throw()
  226239. {
  226240. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  226241. io_iterator_t iter = 0;
  226242. io_object_t iod = 0;
  226243. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  226244. && iter != 0)
  226245. {
  226246. iod = IOIteratorNext (iter);
  226247. }
  226248. IOObjectRelease (iter);
  226249. return iod;
  226250. }
  226251. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  226252. {
  226253. jassert (*device == 0);
  226254. io_name_t classname;
  226255. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  226256. {
  226257. IOCFPlugInInterface** cfPlugInInterface = 0;
  226258. SInt32 score = 0;
  226259. if (IOCreatePlugInInterfaceForService (iod,
  226260. kIOHIDDeviceUserClientTypeID,
  226261. kIOCFPlugInInterfaceID,
  226262. &cfPlugInInterface,
  226263. &score) == kIOReturnSuccess)
  226264. {
  226265. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  226266. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  226267. device);
  226268. (void) hr;
  226269. (*cfPlugInInterface)->Release (cfPlugInInterface);
  226270. }
  226271. }
  226272. return *device != 0;
  226273. }
  226274. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  226275. {
  226276. if (queue != 0)
  226277. return true;
  226278. stop();
  226279. bool result = false;
  226280. io_object_t iod = getAppleRemoteDevice();
  226281. if (iod != 0)
  226282. {
  226283. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  226284. result = true;
  226285. else
  226286. stop();
  226287. IOObjectRelease (iod);
  226288. }
  226289. return result;
  226290. }
  226291. void AppleRemoteDevice::stop() throw()
  226292. {
  226293. if (queue != 0)
  226294. {
  226295. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  226296. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  226297. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  226298. queue = 0;
  226299. }
  226300. if (device != 0)
  226301. {
  226302. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  226303. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  226304. device = 0;
  226305. }
  226306. }
  226307. bool AppleRemoteDevice::isActive() const throw()
  226308. {
  226309. return queue != 0;
  226310. }
  226311. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  226312. {
  226313. if (result == kIOReturnSuccess)
  226314. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  226315. }
  226316. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  226317. {
  226318. #if ! MACOS_10_2_OR_EARLIER
  226319. Array <int> cookies;
  226320. CFArrayRef elements;
  226321. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  226322. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  226323. return false;
  226324. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  226325. {
  226326. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  226327. // get the cookie
  226328. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  226329. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  226330. continue;
  226331. long number;
  226332. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  226333. continue;
  226334. cookies.add ((int) number);
  226335. }
  226336. CFRelease (elements);
  226337. if ((*(IOHIDDeviceInterface**) device)
  226338. ->open ((IOHIDDeviceInterface**) device,
  226339. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  226340. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  226341. {
  226342. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  226343. if (queue != 0)
  226344. {
  226345. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  226346. for (int i = 0; i < cookies.size(); ++i)
  226347. {
  226348. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  226349. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  226350. }
  226351. CFRunLoopSourceRef eventSource;
  226352. if ((*(IOHIDQueueInterface**) queue)
  226353. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  226354. {
  226355. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  226356. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  226357. {
  226358. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  226359. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  226360. return true;
  226361. }
  226362. }
  226363. }
  226364. }
  226365. #endif
  226366. return false;
  226367. }
  226368. void AppleRemoteDevice::handleCallbackInternal()
  226369. {
  226370. #if ! MACOS_10_2_OR_EARLIER
  226371. int totalValues = 0;
  226372. AbsoluteTime nullTime = { 0, 0 };
  226373. char cookies [12];
  226374. int numCookies = 0;
  226375. while (numCookies < numElementsInArray (cookies))
  226376. {
  226377. IOHIDEventStruct e;
  226378. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  226379. break;
  226380. if ((int) e.elementCookie == 19)
  226381. {
  226382. remoteId = e.value;
  226383. buttonPressed (switched, false);
  226384. }
  226385. else
  226386. {
  226387. totalValues += e.value;
  226388. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  226389. }
  226390. }
  226391. cookies [numCookies++] = 0;
  226392. //DBG (String::toHexString ((uint8*) cookies, numCookies, 1) + " " + String (totalValues));
  226393. static const char buttonPatterns[] =
  226394. {
  226395. 0x1f, 0x14, 0x12, 0x1f, 0x14, 0x12, 0,
  226396. 0x1f, 0x15, 0x12, 0x1f, 0x15, 0x12, 0,
  226397. 0x1f, 0x1d, 0x1c, 0x12, 0,
  226398. 0x1f, 0x1e, 0x1c, 0x12, 0,
  226399. 0x1f, 0x16, 0x12, 0x1f, 0x16, 0x12, 0,
  226400. 0x1f, 0x17, 0x12, 0x1f, 0x17, 0x12, 0,
  226401. 0x1f, 0x12, 0x04, 0x02, 0,
  226402. 0x1f, 0x12, 0x03, 0x02, 0,
  226403. 0x1f, 0x12, 0x1f, 0x12, 0,
  226404. 0x23, 0x1f, 0x12, 0x23, 0x1f, 0x12, 0,
  226405. 19, 0
  226406. };
  226407. int buttonNum = (int) menuButton;
  226408. int i = 0;
  226409. while (i < numElementsInArray (buttonPatterns))
  226410. {
  226411. if (strcmp (cookies, buttonPatterns + i) == 0)
  226412. {
  226413. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  226414. break;
  226415. }
  226416. i += strlen (buttonPatterns + i) + 1;
  226417. ++buttonNum;
  226418. }
  226419. #endif
  226420. }
  226421. #endif
  226422. /********* End of inlined file: juce_mac_AppleRemote.mm *********/
  226423. /********* Start of inlined file: juce_mac_OpenGLComponent.mm *********/
  226424. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226425. // compiled on its own).
  226426. #if JUCE_INCLUDED_FILE && JUCE_OPENGL
  226427. class WindowedGLContext : public OpenGLContext
  226428. {
  226429. public:
  226430. WindowedGLContext (Component* const component,
  226431. const OpenGLPixelFormat& pixelFormat_,
  226432. NSOpenGLContext* sharedContext)
  226433. : renderContext (0),
  226434. pixelFormat (pixelFormat_)
  226435. {
  226436. jassert (component != 0);
  226437. NSOpenGLPixelFormatAttribute attribs [64];
  226438. int n = 0;
  226439. attribs[n++] = NSOpenGLPFADoubleBuffer;
  226440. attribs[n++] = NSOpenGLPFAAccelerated;
  226441. attribs[n++] = NSOpenGLPFAColorSize;
  226442. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.redBits,
  226443. pixelFormat.greenBits,
  226444. pixelFormat.blueBits);
  226445. attribs[n++] = NSOpenGLPFAAlphaSize;
  226446. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.alphaBits;
  226447. attribs[n++] = NSOpenGLPFADepthSize;
  226448. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.depthBufferBits;
  226449. attribs[n++] = NSOpenGLPFAStencilSize;
  226450. attribs[n++] = (NSOpenGLPixelFormatAttribute) pixelFormat.stencilBufferBits;
  226451. attribs[n++] = NSOpenGLPFAAccumSize;
  226452. attribs[n++] = (NSOpenGLPixelFormatAttribute) jmax (pixelFormat.accumulationBufferRedBits,
  226453. pixelFormat.accumulationBufferGreenBits,
  226454. pixelFormat.accumulationBufferBlueBits,
  226455. pixelFormat.accumulationBufferAlphaBits);
  226456. // xxx not sure how to do fullSceneAntiAliasingNumSamples..
  226457. attribs[n++] = NSOpenGLPFASampleBuffers;
  226458. attribs[n++] = (NSOpenGLPixelFormatAttribute) 1;
  226459. attribs[n++] = NSOpenGLPFAClosestPolicy;
  226460. attribs[n++] = NSOpenGLPFANoRecovery;
  226461. attribs[n++] = (NSOpenGLPixelFormatAttribute) 0;
  226462. NSOpenGLPixelFormat* format
  226463. = [[NSOpenGLPixelFormat alloc] initWithAttributes: attribs];
  226464. NSOpenGLView* view
  226465. = [[NSOpenGLView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  226466. pixelFormat: format];
  226467. renderContext = [view openGLContext];
  226468. [format release];
  226469. viewHolder = new NSViewComponentInternal (view, component);
  226470. }
  226471. ~WindowedGLContext()
  226472. {
  226473. makeInactive();
  226474. [renderContext setView: nil];
  226475. delete viewHolder;
  226476. }
  226477. bool makeActive() const throw()
  226478. {
  226479. jassert (renderContext != 0);
  226480. [renderContext makeCurrentContext];
  226481. return renderContext != 0;
  226482. }
  226483. bool makeInactive() const throw()
  226484. {
  226485. if (! isActive())
  226486. [NSOpenGLContext clearCurrentContext];
  226487. return true;
  226488. }
  226489. bool isActive() const throw()
  226490. {
  226491. return [NSOpenGLContext currentContext] == renderContext;
  226492. }
  226493. const OpenGLPixelFormat getPixelFormat() const { return pixelFormat; }
  226494. void* getRawContext() const throw() { return renderContext; }
  226495. void updateWindowPosition (int x, int y, int w, int h, int outerWindowHeight)
  226496. {
  226497. }
  226498. void swapBuffers()
  226499. {
  226500. glFlush();
  226501. [renderContext flushBuffer];
  226502. }
  226503. bool setSwapInterval (const int numFramesPerSwap)
  226504. {
  226505. [renderContext setValues: (const GLint*) &numFramesPerSwap
  226506. forParameter: NSOpenGLCPSwapInterval];
  226507. return true;
  226508. }
  226509. int getSwapInterval() const
  226510. {
  226511. GLint numFrames = 0;
  226512. [renderContext getValues: &numFrames
  226513. forParameter: NSOpenGLCPSwapInterval];
  226514. return numFrames;
  226515. }
  226516. void repaint()
  226517. {
  226518. // we need to invalidate the juce view that holds this gl view, to make it
  226519. // cause a repaint callback
  226520. NSView* v = (NSView*) viewHolder->view;
  226521. NSRect r = [v frame];
  226522. // bit of a bodge here.. if we only invalidate the area of the gl component,
  226523. // it's completely covered by the NSOpenGLView, so the OS throws away the
  226524. // repaint message, thus never causing our paint() callback, and never repainting
  226525. // the comp. So invalidating just a little bit around the edge helps..
  226526. [[v superview] setNeedsDisplayInRect: NSInsetRect (r, -2.0f, -2.0f)];
  226527. }
  226528. void* getNativeWindowHandle() const { return viewHolder->view; }
  226529. juce_UseDebuggingNewOperator
  226530. NSOpenGLContext* renderContext;
  226531. private:
  226532. OpenGLPixelFormat pixelFormat;
  226533. NSViewComponentInternal* viewHolder;
  226534. WindowedGLContext (const WindowedGLContext&);
  226535. const WindowedGLContext& operator= (const WindowedGLContext&);
  226536. };
  226537. OpenGLContext* OpenGLContext::createContextForWindow (Component* const component,
  226538. const OpenGLPixelFormat& pixelFormat,
  226539. const OpenGLContext* const contextToShareWith)
  226540. {
  226541. WindowedGLContext* c = new WindowedGLContext (component, pixelFormat,
  226542. contextToShareWith != 0 ? (NSOpenGLContext*) contextToShareWith->getRawContext() : 0);
  226543. if (c->renderContext == 0)
  226544. deleteAndZero (c);
  226545. return c;
  226546. }
  226547. void* OpenGLComponent::getNativeWindowHandle() const
  226548. {
  226549. return context != 0 ? ((WindowedGLContext*) context)->getNativeWindowHandle()
  226550. : 0;
  226551. }
  226552. void juce_glViewport (const int w, const int h)
  226553. {
  226554. glViewport (0, 0, w, h);
  226555. }
  226556. void OpenGLPixelFormat::getAvailablePixelFormats (Component* /*component*/,
  226557. OwnedArray <OpenGLPixelFormat>& results)
  226558. {
  226559. /* GLint attribs [64];
  226560. int n = 0;
  226561. attribs[n++] = AGL_RGBA;
  226562. attribs[n++] = AGL_DOUBLEBUFFER;
  226563. attribs[n++] = AGL_ACCELERATED;
  226564. attribs[n++] = AGL_NO_RECOVERY;
  226565. attribs[n++] = AGL_NONE;
  226566. AGLPixelFormat p = aglChoosePixelFormat (0, 0, attribs);
  226567. while (p != 0)
  226568. {
  226569. OpenGLPixelFormat* const pf = new OpenGLPixelFormat();
  226570. pf->redBits = getAGLAttribute (p, AGL_RED_SIZE);
  226571. pf->greenBits = getAGLAttribute (p, AGL_GREEN_SIZE);
  226572. pf->blueBits = getAGLAttribute (p, AGL_BLUE_SIZE);
  226573. pf->alphaBits = getAGLAttribute (p, AGL_ALPHA_SIZE);
  226574. pf->depthBufferBits = getAGLAttribute (p, AGL_DEPTH_SIZE);
  226575. pf->stencilBufferBits = getAGLAttribute (p, AGL_STENCIL_SIZE);
  226576. pf->accumulationBufferRedBits = getAGLAttribute (p, AGL_ACCUM_RED_SIZE);
  226577. pf->accumulationBufferGreenBits = getAGLAttribute (p, AGL_ACCUM_GREEN_SIZE);
  226578. pf->accumulationBufferBlueBits = getAGLAttribute (p, AGL_ACCUM_BLUE_SIZE);
  226579. pf->accumulationBufferAlphaBits = getAGLAttribute (p, AGL_ACCUM_ALPHA_SIZE);
  226580. results.add (pf);
  226581. p = aglNextPixelFormat (p);
  226582. }*/
  226583. //jassertfalse //xxx can't see how you do this in cocoa!
  226584. }
  226585. #endif
  226586. /********* End of inlined file: juce_mac_OpenGLComponent.mm *********/
  226587. /********* Start of inlined file: juce_mac_MainMenu.mm *********/
  226588. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226589. // compiled on its own).
  226590. #ifdef JUCE_INCLUDED_FILE
  226591. class JuceMainMenuHandler;
  226592. END_JUCE_NAMESPACE
  226593. using namespace JUCE_NAMESPACE;
  226594. @interface JuceMenuCallback : NSObject
  226595. {
  226596. JuceMainMenuHandler* owner;
  226597. }
  226598. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_;
  226599. - (void) dealloc;
  226600. - (void) menuItemInvoked: (id) menu;
  226601. @end
  226602. BEGIN_JUCE_NAMESPACE
  226603. class JuceMainMenuHandler : private MenuBarModelListener,
  226604. private DeletedAtShutdown
  226605. {
  226606. public:
  226607. static JuceMainMenuHandler* instance;
  226608. JuceMainMenuHandler() throw()
  226609. : currentModel (0)
  226610. {
  226611. callback = [[JuceMenuCallback alloc] initWithOwner: this];
  226612. }
  226613. ~JuceMainMenuHandler() throw()
  226614. {
  226615. setMenu (0);
  226616. jassert (instance == this);
  226617. instance = 0;
  226618. [callback release];
  226619. }
  226620. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  226621. {
  226622. if (currentModel != newMenuBarModel)
  226623. {
  226624. if (currentModel != 0)
  226625. currentModel->removeListener (this);
  226626. currentModel = newMenuBarModel;
  226627. if (currentModel != 0)
  226628. currentModel->addListener (this);
  226629. menuBarItemsChanged (0);
  226630. }
  226631. }
  226632. void addSubMenu (NSMenu* parent, const PopupMenu& child,
  226633. const String& name, int& menuId, int& tag)
  226634. {
  226635. NSMenuItem* item = [parent addItemWithTitle: juceStringToNS (name)
  226636. action: nil
  226637. keyEquivalent: @""];
  226638. [item setTag: tag];
  226639. NSMenu* sub = createMenu (child, name, menuId, tag);
  226640. [parent setSubmenu: sub forItem: item];
  226641. [sub setAutoenablesItems: false];
  226642. [sub release];
  226643. }
  226644. void menuBarItemsChanged (MenuBarModel*)
  226645. {
  226646. NSMenu* menuBar = [NSApp mainMenu];
  226647. while ([menuBar numberOfItems] > 1)
  226648. [menuBar removeItemAtIndex: 1];
  226649. if (currentModel != 0)
  226650. {
  226651. const StringArray menuNames (currentModel->getMenuBarNames());
  226652. int menuId = 1;
  226653. for (int i = 0; i < menuNames.size(); ++i)
  226654. {
  226655. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  226656. addSubMenu (menuBar, menu, menuNames [i], menuId, i);
  226657. }
  226658. }
  226659. }
  226660. static void flashMenuBar (NSMenu* menu)
  226661. {
  226662. const unichar f35Key = NSF35FunctionKey;
  226663. NSString* f35String = [NSString stringWithCharacters: &f35Key length: 1];
  226664. NSMenuItem* item = [[NSMenuItem alloc] initWithTitle: @"x"
  226665. action: nil
  226666. keyEquivalent: f35String];
  226667. [item setTarget: nil];
  226668. [menu insertItem: item atIndex: [menu numberOfItems]];
  226669. [item release];
  226670. NSEvent* f35Event = [NSEvent keyEventWithType: NSKeyDown
  226671. location: NSZeroPoint
  226672. modifierFlags: NSCommandKeyMask
  226673. timestamp: 0
  226674. windowNumber: 0
  226675. context: [NSGraphicsContext currentContext]
  226676. characters: f35String
  226677. charactersIgnoringModifiers: f35String
  226678. isARepeat: NO
  226679. keyCode: 0];
  226680. [menu performKeyEquivalent: f35Event];
  226681. [menu removeItem: item];
  226682. }
  226683. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  226684. {
  226685. NSMenuItem* item = [[NSApp mainMenu] itemWithTag: info.commandID];
  226686. if (item != 0)
  226687. flashMenuBar ([item menu]);
  226688. }
  226689. void invoke (const int commandId, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  226690. {
  226691. if (currentModel != 0)
  226692. {
  226693. if (commandManager != 0)
  226694. {
  226695. ApplicationCommandTarget::InvocationInfo info (commandId);
  226696. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  226697. commandManager->invoke (info, true);
  226698. }
  226699. currentModel->menuItemSelected (commandId, topLevelIndex);
  226700. }
  226701. }
  226702. MenuBarModel* currentModel;
  226703. private:
  226704. JuceMenuCallback* callback;
  226705. NSMenu* createMenu (const PopupMenu menu,
  226706. const String& menuName,
  226707. int& id,
  226708. const int topLevelIndex)
  226709. {
  226710. NSMenu* m = [[NSMenu alloc] initWithTitle: juceStringToNS (menuName)];
  226711. [m setAutoenablesItems: false];
  226712. PopupMenu::MenuItemIterator iter (menu);
  226713. while (iter.next())
  226714. {
  226715. NSString* text = juceStringToNS (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  226716. if (iter.isSeparator)
  226717. {
  226718. [m addItem: [NSMenuItem separatorItem]];
  226719. }
  226720. else if (iter.isSectionHeader)
  226721. {
  226722. NSMenuItem* item = [m addItemWithTitle: text
  226723. action: nil
  226724. keyEquivalent: @""];
  226725. [item setEnabled: iter.isEnabled];
  226726. }
  226727. else if (iter.subMenu != 0)
  226728. {
  226729. NSMenuItem* item = [m addItemWithTitle: text
  226730. action: nil
  226731. keyEquivalent: @""];
  226732. [item setTag: iter.itemId];
  226733. [item setEnabled: iter.isEnabled];
  226734. NSMenu* sub = createMenu (*iter.subMenu, iter.itemName, id, topLevelIndex);
  226735. [m setSubmenu: sub forItem: item];
  226736. [sub release];
  226737. }
  226738. else
  226739. {
  226740. NSMenuItem* item = [m addItemWithTitle: text
  226741. action: @selector (menuItemInvoked:)
  226742. keyEquivalent: @""];
  226743. [item setTag: iter.itemId];
  226744. [item setEnabled: iter.isEnabled];
  226745. [item setState: iter.isTicked ? NSOnState : NSOffState];
  226746. [item setTarget: (id) callback];
  226747. NSMutableArray* info = [NSMutableArray arrayWithObject: [NSNumber numberWithUnsignedLongLong: (pointer_sized_int) (void*) iter.commandManager]];
  226748. [info addObject: [NSNumber numberWithInt: topLevelIndex]];
  226749. [item setRepresentedObject: info];
  226750. if (iter.commandManager != 0)
  226751. {
  226752. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  226753. ->getKeyPressesAssignedToCommand (iter.itemId));
  226754. if (keyPresses.size() > 0)
  226755. {
  226756. const KeyPress& kp = keyPresses.getReference(0);
  226757. juce_wchar key = kp.getTextCharacter();
  226758. if (kp.getKeyCode() == KeyPress::backspaceKey)
  226759. key = NSBackspaceCharacter;
  226760. else if (kp.getKeyCode() == KeyPress::deleteKey)
  226761. key = NSDeleteCharacter;
  226762. else if (key == 0)
  226763. key = (juce_wchar) kp.getKeyCode();
  226764. unsigned int mods = 0;
  226765. if (kp.getModifiers().isShiftDown())
  226766. mods |= NSShiftKeyMask;
  226767. if (kp.getModifiers().isCtrlDown())
  226768. mods |= NSControlKeyMask;
  226769. if (kp.getModifiers().isAltDown())
  226770. mods |= NSAlternateKeyMask;
  226771. if (kp.getModifiers().isCommandDown())
  226772. mods |= NSCommandKeyMask;
  226773. [item setKeyEquivalent: juceStringToNS (String::charToString (key))];
  226774. [item setKeyEquivalentModifierMask: mods];
  226775. }
  226776. }
  226777. }
  226778. }
  226779. [m update];
  226780. return m;
  226781. }
  226782. };
  226783. JuceMainMenuHandler* JuceMainMenuHandler::instance = 0;
  226784. END_JUCE_NAMESPACE
  226785. @implementation JuceMenuCallback
  226786. - (JuceMenuCallback*) initWithOwner: (JuceMainMenuHandler*) owner_
  226787. {
  226788. [super init];
  226789. owner = owner_;
  226790. return self;
  226791. }
  226792. - (void) dealloc
  226793. {
  226794. [super dealloc];
  226795. }
  226796. - (void) menuItemInvoked: (id) menu
  226797. {
  226798. NSMenuItem* item = (NSMenuItem*) menu;
  226799. if ([[item representedObject] isKindOfClass: [NSArray class]])
  226800. {
  226801. NSArray* info = (NSArray*) [item representedObject];
  226802. owner->invoke ([item tag],
  226803. (ApplicationCommandManager*) (pointer_sized_int)
  226804. [((NSNumber*) [info objectAtIndex: 0]) unsignedLongLongValue],
  226805. (int) [((NSNumber*) [info objectAtIndex: 1]) intValue]);
  226806. }
  226807. }
  226808. @end
  226809. BEGIN_JUCE_NAMESPACE
  226810. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel) throw()
  226811. {
  226812. if (getMacMainMenu() != newMenuBarModel)
  226813. {
  226814. if (newMenuBarModel == 0)
  226815. {
  226816. delete JuceMainMenuHandler::instance;
  226817. jassert (JuceMainMenuHandler::instance == 0); // should be zeroed in the destructor
  226818. }
  226819. else
  226820. {
  226821. if (JuceMainMenuHandler::instance == 0)
  226822. JuceMainMenuHandler::instance = new JuceMainMenuHandler();
  226823. JuceMainMenuHandler::instance->setMenu (newMenuBarModel);
  226824. }
  226825. }
  226826. }
  226827. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  226828. {
  226829. return JuceMainMenuHandler::instance != 0
  226830. ? JuceMainMenuHandler::instance->currentModel : 0;
  226831. }
  226832. static NSMenu* createStandardAppMenu (const String& appName)
  226833. {
  226834. NSMenu* menu = [[NSMenu alloc] initWithTitle: @"Apple"];
  226835. NSMenuItem* item;
  226836. // xxx should allow the 'about' and 'preferences' items to be turned on programatically...
  226837. /* item = [menu addItemWithTitle: juceStringToNS ("About " + appName)]
  226838. action: @selector(orderFrontStandardAboutPanel:) keyEquivalent: @""];
  226839. [item setTarget: NSApp];
  226840. [menu addItem: [NSMenuItem separatorItem]];
  226841. */
  226842. /* item = [menu addItemWithTitle: NSLocalizedString (@"Preferences...", nil)
  226843. action: nil keyEquivalent: @","];
  226844. [menu addItem: [NSMenuItem separatorItem]];
  226845. */
  226846. // Services...
  226847. item = [menu addItemWithTitle: NSLocalizedString (@"Services", nil)
  226848. action: nil keyEquivalent: @""];
  226849. NSMenu* servicesMenu = [[NSMenu alloc] initWithTitle: @"Services"];
  226850. [menu setSubmenu: servicesMenu forItem: item];
  226851. [NSApp setServicesMenu: servicesMenu];
  226852. [servicesMenu release];
  226853. [menu addItem: [NSMenuItem separatorItem]];
  226854. // Hide + Show stuff...
  226855. item = [menu addItemWithTitle: juceStringToNS ("Hide " + appName)
  226856. action: @selector (hide:) keyEquivalent: @"h"];
  226857. [item setTarget: NSApp];
  226858. item = [menu addItemWithTitle: NSLocalizedString (@"Hide Others", nil)
  226859. action: @selector (hideOtherApplications:) keyEquivalent: @"h"];
  226860. [item setKeyEquivalentModifierMask: NSCommandKeyMask | NSAlternateKeyMask];
  226861. [item setTarget: NSApp];
  226862. item = [menu addItemWithTitle: NSLocalizedString (@"Show All", nil)
  226863. action: @selector (unhideAllApplications:) keyEquivalent: @""];
  226864. [item setTarget: NSApp];
  226865. [menu addItem: [NSMenuItem separatorItem]];
  226866. // Quit item....
  226867. item = [menu addItemWithTitle: juceStringToNS ("Quit " + appName)
  226868. action: @selector (terminate:) keyEquivalent: @"q"];
  226869. [item setTarget: NSApp];
  226870. return menu;
  226871. }
  226872. // Since our app has no NIB, this initialises a standard app menu...
  226873. void initialiseMainMenu()
  226874. {
  226875. if (JUCEApplication::getInstance() != 0) // only needed in an app
  226876. {
  226877. const ScopedAutoReleasePool pool;
  226878. NSMenu* mainMenu = [[NSMenu alloc] initWithTitle: @"MainMenu"];
  226879. NSMenuItem* item = [mainMenu addItemWithTitle: @"Apple" action: nil keyEquivalent: @""];
  226880. NSMenu* appMenu = createStandardAppMenu (JUCEApplication::getInstance()->getApplicationName());
  226881. [NSApp performSelector: @selector (setAppleMenu:) withObject: appMenu];
  226882. [mainMenu setSubmenu: appMenu forItem: item];
  226883. [NSApp setMainMenu: mainMenu];
  226884. [appMenu release];
  226885. [mainMenu release];
  226886. }
  226887. }
  226888. #endif
  226889. /********* End of inlined file: juce_mac_MainMenu.mm *********/
  226890. /********* Start of inlined file: juce_mac_FileChooser.mm *********/
  226891. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226892. // compiled on its own).
  226893. #ifdef JUCE_INCLUDED_FILE
  226894. END_JUCE_NAMESPACE
  226895. using namespace JUCE_NAMESPACE;
  226896. @interface JuceFileChooserDelegate : NSObject
  226897. {
  226898. StringArray* filters;
  226899. }
  226900. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_;
  226901. - (void) dealloc;
  226902. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename;
  226903. @end
  226904. @implementation JuceFileChooserDelegate
  226905. - (JuceFileChooserDelegate*) initWithFilters: (StringArray*) filters_
  226906. {
  226907. [super init];
  226908. filters = filters_;
  226909. return self;
  226910. }
  226911. - (void) dealloc
  226912. {
  226913. delete filters;
  226914. [super dealloc];
  226915. }
  226916. - (BOOL) panel: (id) sender shouldShowFilename: (NSString*) filename
  226917. {
  226918. const String fname (nsStringToJuce (filename));
  226919. for (int i = filters->size(); --i >= 0;)
  226920. if (fname.matchesWildcard ((*filters)[i], true))
  226921. return true;
  226922. return File (fname).isDirectory();
  226923. }
  226924. @end
  226925. BEGIN_JUCE_NAMESPACE
  226926. void FileChooser::showPlatformDialog (OwnedArray<File>& results,
  226927. const String& title,
  226928. const File& currentFileOrDirectory,
  226929. const String& filter,
  226930. bool selectsDirectory,
  226931. bool isSaveDialogue,
  226932. bool warnAboutOverwritingExistingFiles,
  226933. bool selectMultipleFiles,
  226934. FilePreviewComponent* extraInfoComponent)
  226935. {
  226936. const ScopedAutoReleasePool pool;
  226937. StringArray* filters = new StringArray();
  226938. filters->addTokens (filter.replaceCharacters (T(",:"), T(";;")), T(";"), 0);
  226939. filters->trim();
  226940. filters->removeEmptyStrings();
  226941. JuceFileChooserDelegate* delegate = [[JuceFileChooserDelegate alloc] initWithFilters: filters];
  226942. [delegate autorelease];
  226943. NSSavePanel* panel = isSaveDialogue ? [NSSavePanel savePanel]
  226944. : [NSOpenPanel openPanel];
  226945. [panel setTitle: juceStringToNS (title)];
  226946. if (! isSaveDialogue)
  226947. {
  226948. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226949. [openPanel setCanChooseDirectories: selectsDirectory];
  226950. [openPanel setCanChooseFiles: ! selectsDirectory];
  226951. [openPanel setAllowsMultipleSelection: selectMultipleFiles];
  226952. }
  226953. [panel setDelegate: delegate];
  226954. String directory, filename;
  226955. if (currentFileOrDirectory.isDirectory())
  226956. {
  226957. directory = currentFileOrDirectory.getFullPathName();
  226958. }
  226959. else
  226960. {
  226961. directory = currentFileOrDirectory.getParentDirectory().getFullPathName();
  226962. filename = currentFileOrDirectory.getFileName();
  226963. }
  226964. if ([panel runModalForDirectory: juceStringToNS (directory)
  226965. file: juceStringToNS (filename)]
  226966. == NSOKButton)
  226967. {
  226968. if (isSaveDialogue)
  226969. {
  226970. results.add (new File (nsStringToJuce ([panel filename])));
  226971. }
  226972. else
  226973. {
  226974. NSOpenPanel* openPanel = (NSOpenPanel*) panel;
  226975. NSArray* urls = [openPanel filenames];
  226976. for (int i = 0; i < [urls count]; ++i)
  226977. {
  226978. NSString* f = [urls objectAtIndex: i];
  226979. results.add (new File (nsStringToJuce (f)));
  226980. }
  226981. }
  226982. }
  226983. [panel setDelegate: nil];
  226984. }
  226985. #endif
  226986. /********* End of inlined file: juce_mac_FileChooser.mm *********/
  226987. /********* Start of inlined file: juce_mac_QuickTimeMovieComponent.mm *********/
  226988. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  226989. // compiled on its own).
  226990. #if JUCE_INCLUDED_FILE && JUCE_QUICKTIME
  226991. #define theMovie ((QTMovie*) movie)
  226992. QuickTimeMovieComponent::QuickTimeMovieComponent()
  226993. : movie (0)
  226994. {
  226995. setOpaque (true);
  226996. setVisible (true);
  226997. QTMovieView* view = [[QTMovieView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)];
  226998. setView (view);
  226999. }
  227000. QuickTimeMovieComponent::~QuickTimeMovieComponent()
  227001. {
  227002. closeMovie();
  227003. setView (0);
  227004. }
  227005. bool QuickTimeMovieComponent::isQuickTimeAvailable() throw()
  227006. {
  227007. return true;
  227008. }
  227009. bool QuickTimeMovieComponent::loadMovie (InputStream* movieStream,
  227010. const bool controllerVisible)
  227011. {
  227012. closeMovie();
  227013. if (getPeer() == 0)
  227014. {
  227015. // To open a movie, this component must be visible inside a functioning window, so that
  227016. // the QT control can be assigned to the window.
  227017. jassertfalse
  227018. return false;
  227019. }
  227020. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  227021. if (fin != 0)
  227022. {
  227023. movieFile = fin->getFile();
  227024. movie = [QTMovie movieWithFile: juceStringToNS (movieFile.getFullPathName())
  227025. error: nil];
  227026. }
  227027. else
  227028. {
  227029. MemoryBlock temp;
  227030. movieStream->readIntoMemoryBlock (temp);
  227031. movie = [QTMovie movieWithData: [NSData dataWithBytes: temp.getData()
  227032. length: temp.getSize()]
  227033. error: nil];
  227034. }
  227035. [theMovie retain];
  227036. QTMovieView* view = (QTMovieView*) getView();
  227037. [view setMovie: theMovie];
  227038. [view setControllerVisible: controllerVisible];
  227039. setLooping (looping);
  227040. return movie != nil;
  227041. }
  227042. void QuickTimeMovieComponent::closeMovie()
  227043. {
  227044. stop();
  227045. QTMovieView* view = (QTMovieView*) getView();
  227046. [view setMovie: nil];
  227047. [theMovie release];
  227048. movie = 0;
  227049. movieFile = File::nonexistent;
  227050. }
  227051. bool QuickTimeMovieComponent::isMovieOpen() const
  227052. {
  227053. return movie != nil;
  227054. }
  227055. const File QuickTimeMovieComponent::getCurrentMovieFile() const
  227056. {
  227057. return movieFile;
  227058. }
  227059. void QuickTimeMovieComponent::play()
  227060. {
  227061. [theMovie play];
  227062. }
  227063. void QuickTimeMovieComponent::stop()
  227064. {
  227065. [theMovie stop];
  227066. }
  227067. bool QuickTimeMovieComponent::isPlaying() const
  227068. {
  227069. return movie != 0 && [theMovie rate] != 0;
  227070. }
  227071. void QuickTimeMovieComponent::setPosition (const double seconds)
  227072. {
  227073. if (movie != 0)
  227074. {
  227075. QTTime t;
  227076. t.timeValue = (uint64) (100000.0 * seconds);
  227077. t.timeScale = 100000;
  227078. t.flags = 0;
  227079. [theMovie setCurrentTime: t];
  227080. }
  227081. }
  227082. double QuickTimeMovieComponent::getPosition() const
  227083. {
  227084. if (movie == 0)
  227085. return 0.0;
  227086. QTTime t = [theMovie currentTime];
  227087. return t.timeValue / (double) t.timeScale;
  227088. }
  227089. void QuickTimeMovieComponent::setSpeed (const float newSpeed)
  227090. {
  227091. [theMovie setRate: newSpeed];
  227092. }
  227093. double QuickTimeMovieComponent::getMovieDuration() const
  227094. {
  227095. if (movie == 0)
  227096. return 0.0;
  227097. QTTime t = [theMovie duration];
  227098. return t.timeValue / (double) t.timeScale;
  227099. }
  227100. void QuickTimeMovieComponent::setLooping (const bool shouldLoop)
  227101. {
  227102. looping = shouldLoop;
  227103. [theMovie setAttribute: [NSNumber numberWithBool: shouldLoop]
  227104. forKey: QTMovieLoopsAttribute];
  227105. }
  227106. bool QuickTimeMovieComponent::isLooping() const
  227107. {
  227108. return looping;
  227109. }
  227110. void QuickTimeMovieComponent::setMovieVolume (const float newVolume)
  227111. {
  227112. [theMovie setVolume: newVolume];
  227113. }
  227114. float QuickTimeMovieComponent::getMovieVolume() const
  227115. {
  227116. return movie != 0 ? [theMovie volume] : 0.0f;
  227117. }
  227118. void QuickTimeMovieComponent::getMovieNormalSize (int& width, int& height) const
  227119. {
  227120. width = 0;
  227121. height = 0;
  227122. if (movie != 0)
  227123. {
  227124. NSSize s = [[theMovie attributeForKey: QTMovieNaturalSizeAttribute] sizeValue];
  227125. width = s.width;
  227126. height = s.height;
  227127. }
  227128. }
  227129. void QuickTimeMovieComponent::paint (Graphics& g)
  227130. {
  227131. if (movie == 0)
  227132. g.fillAll (Colours::black);
  227133. }
  227134. bool QuickTimeMovieComponent::isControllerVisible() const
  227135. {
  227136. return controllerVisible;
  227137. }
  227138. bool QuickTimeMovieComponent::loadMovie (const File& movieFile_,
  227139. const bool isControllerVisible)
  227140. {
  227141. const bool ok = loadMovie ((InputStream*) movieFile_.createInputStream(), isControllerVisible);
  227142. movieFile = movieFile_;
  227143. return ok;
  227144. }
  227145. void QuickTimeMovieComponent::goToStart()
  227146. {
  227147. setPosition (0.0);
  227148. }
  227149. void QuickTimeMovieComponent::setBoundsWithCorrectAspectRatio (const Rectangle& spaceToFitWithin,
  227150. const RectanglePlacement& placement)
  227151. {
  227152. int normalWidth, normalHeight;
  227153. getMovieNormalSize (normalWidth, normalHeight);
  227154. if (normalWidth > 0 && normalHeight > 0 && ! spaceToFitWithin.isEmpty())
  227155. {
  227156. double x = 0.0, y = 0.0, w = normalWidth, h = normalHeight;
  227157. placement.applyTo (x, y, w, h,
  227158. spaceToFitWithin.getX(), spaceToFitWithin.getY(),
  227159. spaceToFitWithin.getWidth(), spaceToFitWithin.getHeight());
  227160. if (w > 0 && h > 0)
  227161. {
  227162. setBounds (roundDoubleToInt (x), roundDoubleToInt (y),
  227163. roundDoubleToInt (w), roundDoubleToInt (h));
  227164. }
  227165. }
  227166. else
  227167. {
  227168. setBounds (spaceToFitWithin);
  227169. }
  227170. }
  227171. #if ! (JUCE_MAC && JUCE_64BIT)
  227172. bool juce_OpenQuickTimeMovieFromStream (InputStream* movieStream, Movie& result, Handle& dataHandle)
  227173. {
  227174. if (movieStream == 0)
  227175. return false;
  227176. QTMovie* movie = nil;
  227177. FileInputStream* const fin = dynamic_cast <FileInputStream*> (movieStream);
  227178. if (fin != 0)
  227179. {
  227180. movie = [QTMovie movieWithFile: juceStringToNS (fin->getFile().getFullPathName())
  227181. error: nil];
  227182. }
  227183. else
  227184. {
  227185. MemoryBlock temp;
  227186. movieStream->readIntoMemoryBlock (temp);
  227187. movie = [QTMovie movieWithData: [NSData dataWithBytes: temp.getData()
  227188. length: temp.getSize()]
  227189. error: nil];
  227190. }
  227191. if (movie != nil)
  227192. result = [movie quickTimeMovie];
  227193. return movie != nil;
  227194. }
  227195. #endif
  227196. #endif
  227197. /********* End of inlined file: juce_mac_QuickTimeMovieComponent.mm *********/
  227198. /********* Start of inlined file: juce_mac_AudioCDBurner.mm *********/
  227199. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227200. // compiled on its own).
  227201. #if JUCE_INCLUDED_FILE && JUCE_USE_CDBURNER
  227202. END_JUCE_NAMESPACE
  227203. @interface OpenDiskDevice : NSObject
  227204. {
  227205. DRDevice* device;
  227206. NSMutableArray* tracks;
  227207. }
  227208. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device;
  227209. - (void) dealloc;
  227210. - (bool) isDiskPresent;
  227211. - (int) getNumAvailableAudioBlocks;
  227212. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) numSamples_;
  227213. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  227214. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting;
  227215. @end
  227216. @interface AudioTrackProducer : NSObject
  227217. {
  227218. JUCE_NAMESPACE::AudioSource* source;
  227219. int readPosition, lengthInFrames;
  227220. }
  227221. - (AudioTrackProducer*) init: (int) lengthInFrames;
  227222. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source numSamples: (int) lengthInSamples;
  227223. - (void) dealloc;
  227224. - (void) setupTrackProperties: (DRTrack*) track;
  227225. - (void) cleanupTrackAfterBurn: (DRTrack*) track;
  227226. - (BOOL) cleanupTrackAfterVerification:(DRTrack*)track;
  227227. - (uint64_t) estimateLengthOfTrack:(DRTrack*)track;
  227228. - (BOOL) prepareTrack:(DRTrack*)track forBurn:(DRBurn*)burn
  227229. toMedia:(NSDictionary*)mediaInfo;
  227230. - (BOOL) prepareTrackForVerification:(DRTrack*)track;
  227231. - (uint32_t) produceDataForTrack:(DRTrack*)track intoBuffer:(char*)buffer
  227232. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  227233. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  227234. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  227235. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  227236. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  227237. ioFlags:(uint32_t*)flags;
  227238. - (BOOL) verifyDataForTrack:(DRTrack*)track inBuffer:(const char*)buffer
  227239. length:(uint32_t)bufferLength atAddress:(uint64_t)address
  227240. blockSize:(uint32_t)blockSize ioFlags:(uint32_t*)flags;
  227241. - (uint32_t) producePreGapForTrack:(DRTrack*)track
  227242. intoBuffer:(char*)buffer length:(uint32_t)bufferLength
  227243. atAddress:(uint64_t)address blockSize:(uint32_t)blockSize
  227244. ioFlags:(uint32_t*)flags;
  227245. @end
  227246. @implementation OpenDiskDevice
  227247. - (OpenDiskDevice*) initWithDevice: (DRDevice*) device_
  227248. {
  227249. [super init];
  227250. device = device_;
  227251. tracks = [[NSMutableArray alloc] init];
  227252. return self;
  227253. }
  227254. - (void) dealloc
  227255. {
  227256. [tracks release];
  227257. [super dealloc];
  227258. }
  227259. - (bool) isDiskPresent
  227260. {
  227261. return [device isValid]
  227262. && [[[device status] objectForKey: DRDeviceMediaStateKey]
  227263. isEqualTo: DRDeviceMediaStateMediaPresent];
  227264. }
  227265. - (int) getNumAvailableAudioBlocks
  227266. {
  227267. return [[[[device status] objectForKey: DRDeviceMediaInfoKey]
  227268. objectForKey: DRDeviceMediaBlocksFreeKey] intValue];
  227269. }
  227270. - (void) addSourceTrack: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) numSamples_
  227271. {
  227272. AudioTrackProducer* p = [[AudioTrackProducer alloc] initWithAudioSource: source_ numSamples: numSamples_];
  227273. DRTrack* t = [[DRTrack alloc] initWithProducer: p];
  227274. [p setupTrackProperties: t];
  227275. [tracks addObject: t];
  227276. [t release];
  227277. [p release];
  227278. }
  227279. - (void) burn: (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener*) listener errorString: (JUCE_NAMESPACE::String*) error
  227280. ejectAfterwards: (bool) shouldEject isFake: (bool) peformFakeBurnForTesting
  227281. {
  227282. DRBurn* burn = [DRBurn burnForDevice: device];
  227283. if (! [device acquireExclusiveAccess])
  227284. {
  227285. *error = "Couldn't open or write to the CD device";
  227286. return;
  227287. }
  227288. [device acquireMediaReservation];
  227289. NSMutableDictionary* d = [[burn properties] mutableCopy];
  227290. [d autorelease];
  227291. [d setObject: [NSNumber numberWithBool: peformFakeBurnForTesting] forKey: DRBurnTestingKey];
  227292. [d setObject: [NSNumber numberWithBool: false] forKey: DRBurnVerifyDiscKey];
  227293. [d setObject: (shouldEject ? DRBurnCompletionActionEject : DRBurnCompletionActionMount)
  227294. forKey: DRBurnCompletionActionKey];
  227295. [burn setProperties: d];
  227296. [burn writeLayout: tracks];
  227297. for (;;)
  227298. {
  227299. JUCE_NAMESPACE::Thread::sleep (300);
  227300. float progress = [[[burn status] objectForKey: DRStatusPercentCompleteKey] floatValue];
  227301. NSLog ([[burn status] description]);
  227302. if (listener != 0 && listener->audioCDBurnProgress (progress))
  227303. {
  227304. [burn abort];
  227305. *error = "User cancelled the write operation";
  227306. break;
  227307. }
  227308. if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateFailed])
  227309. {
  227310. *error = "Write operation failed";
  227311. break;
  227312. }
  227313. else if ([[[burn status] objectForKey: DRStatusStateKey] isEqualTo: DRStatusStateDone])
  227314. {
  227315. break;
  227316. }
  227317. NSString* err = (NSString*) [[[burn status] objectForKey: DRErrorStatusKey]
  227318. objectForKey: DRErrorStatusErrorStringKey];
  227319. if ([err length] > 0)
  227320. {
  227321. *error = JUCE_NAMESPACE::String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [err UTF8String]);
  227322. break;
  227323. }
  227324. }
  227325. [device releaseMediaReservation];
  227326. [device releaseExclusiveAccess];
  227327. }
  227328. @end
  227329. @implementation AudioTrackProducer
  227330. - (AudioTrackProducer*) init: (int) lengthInFrames_
  227331. {
  227332. lengthInFrames = lengthInFrames_;
  227333. readPosition = 0;
  227334. return self;
  227335. }
  227336. - (void) setupTrackProperties: (DRTrack*) track
  227337. {
  227338. NSMutableDictionary* p = [[track properties] mutableCopy];
  227339. [p setObject:[DRMSF msfWithFrames: lengthInFrames] forKey: DRTrackLengthKey];
  227340. [p setObject:[NSNumber numberWithUnsignedShort:2352] forKey: DRBlockSizeKey];
  227341. [p setObject:[NSNumber numberWithInt:0] forKey: DRDataFormKey];
  227342. [p setObject:[NSNumber numberWithInt:0] forKey: DRBlockTypeKey];
  227343. [p setObject:[NSNumber numberWithInt:0] forKey: DRTrackModeKey];
  227344. [p setObject:[NSNumber numberWithInt:0] forKey: DRSessionFormatKey];
  227345. [track setProperties: p];
  227346. [p release];
  227347. }
  227348. - (AudioTrackProducer*) initWithAudioSource: (JUCE_NAMESPACE::AudioSource*) source_ numSamples: (int) lengthInSamples
  227349. {
  227350. AudioTrackProducer* s = [self init: (lengthInSamples + 587) / 588];
  227351. if (s != nil)
  227352. s->source = source_;
  227353. return s;
  227354. }
  227355. - (void) dealloc
  227356. {
  227357. if (source != 0)
  227358. {
  227359. source->releaseResources();
  227360. delete source;
  227361. }
  227362. [super dealloc];
  227363. }
  227364. - (void) cleanupTrackAfterBurn: (DRTrack*) track
  227365. {
  227366. }
  227367. - (BOOL) cleanupTrackAfterVerification: (DRTrack*) track
  227368. {
  227369. return true;
  227370. }
  227371. - (uint64_t) estimateLengthOfTrack: (DRTrack*) track
  227372. {
  227373. return lengthInFrames;
  227374. }
  227375. - (BOOL) prepareTrack: (DRTrack*) track forBurn: (DRBurn*) burn
  227376. toMedia: (NSDictionary*) mediaInfo
  227377. {
  227378. if (source != 0)
  227379. source->prepareToPlay (44100 / 75, 44100);
  227380. readPosition = 0;
  227381. return true;
  227382. }
  227383. - (BOOL) prepareTrackForVerification: (DRTrack*) track
  227384. {
  227385. if (source != 0)
  227386. source->prepareToPlay (44100 / 75, 44100);
  227387. return true;
  227388. }
  227389. - (uint32_t) produceDataForTrack: (DRTrack*) track intoBuffer: (char*) buffer
  227390. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  227391. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  227392. {
  227393. if (source != 0)
  227394. {
  227395. const int numSamples = JUCE_NAMESPACE::jmin (bufferLength / 4, (lengthInFrames * (44100 / 75)) - readPosition);
  227396. if (numSamples > 0)
  227397. {
  227398. JUCE_NAMESPACE::AudioSampleBuffer tempBuffer (2, numSamples);
  227399. JUCE_NAMESPACE::AudioSourceChannelInfo info;
  227400. info.buffer = &tempBuffer;
  227401. info.startSample = 0;
  227402. info.numSamples = numSamples;
  227403. source->getNextAudioBlock (info);
  227404. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (0),
  227405. buffer, numSamples, 4);
  227406. JUCE_NAMESPACE::AudioDataConverters::convertFloatToInt16LE (tempBuffer.getSampleData (1),
  227407. buffer + 2, numSamples, 4);
  227408. readPosition += numSamples;
  227409. }
  227410. return numSamples * 4;
  227411. }
  227412. return 0;
  227413. }
  227414. - (uint32_t) producePreGapForTrack: (DRTrack*) track
  227415. intoBuffer: (char*) buffer length: (uint32_t) bufferLength
  227416. atAddress: (uint64_t) address blockSize: (uint32_t) blockSize
  227417. ioFlags: (uint32_t*) flags
  227418. {
  227419. zeromem (buffer, bufferLength);
  227420. return bufferLength;
  227421. }
  227422. - (BOOL) verifyDataForTrack: (DRTrack*) track inBuffer: (const char*) buffer
  227423. length: (uint32_t) bufferLength atAddress: (uint64_t) address
  227424. blockSize: (uint32_t) blockSize ioFlags: (uint32_t*) flags
  227425. {
  227426. return true;
  227427. }
  227428. @end
  227429. BEGIN_JUCE_NAMESPACE
  227430. AudioCDBurner::AudioCDBurner (const int deviceIndex)
  227431. : internal (0)
  227432. {
  227433. OpenDiskDevice* dev = [[OpenDiskDevice alloc] initWithDevice: [[DRDevice devices] objectAtIndex: deviceIndex]];
  227434. internal = (void*) dev;
  227435. }
  227436. AudioCDBurner::~AudioCDBurner()
  227437. {
  227438. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  227439. if (dev != 0)
  227440. [dev release];
  227441. }
  227442. AudioCDBurner* AudioCDBurner::openDevice (const int deviceIndex)
  227443. {
  227444. AudioCDBurner* b = new AudioCDBurner (deviceIndex);
  227445. if (b->internal == 0)
  227446. deleteAndZero (b);
  227447. return b;
  227448. }
  227449. static NSArray* findDiskBurnerDevices()
  227450. {
  227451. NSMutableArray* results = [NSMutableArray array];
  227452. NSArray* devs = [DRDevice devices];
  227453. if (devs != 0)
  227454. {
  227455. int num = [devs count];
  227456. int i;
  227457. for (i = 0; i < num; ++i)
  227458. {
  227459. NSDictionary* dic = [[devs objectAtIndex: i] info];
  227460. NSString* name = [dic valueForKey: DRDeviceProductNameKey];
  227461. if (name != nil)
  227462. [results addObject: name];
  227463. }
  227464. }
  227465. return results;
  227466. }
  227467. const StringArray AudioCDBurner::findAvailableDevices()
  227468. {
  227469. NSArray* names = findDiskBurnerDevices();
  227470. StringArray s;
  227471. for (int i = 0; i < [names count]; ++i)
  227472. s.add (String::fromUTF8 ((JUCE_NAMESPACE::uint8*) [[names objectAtIndex: i] UTF8String]));
  227473. return s;
  227474. }
  227475. bool AudioCDBurner::isDiskPresent() const
  227476. {
  227477. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  227478. return dev != 0 && [dev isDiskPresent];
  227479. }
  227480. int AudioCDBurner::getNumAvailableAudioBlocks() const
  227481. {
  227482. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  227483. return [dev getNumAvailableAudioBlocks];
  227484. }
  227485. bool AudioCDBurner::addAudioTrack (AudioSource* source, int numSamps)
  227486. {
  227487. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  227488. if (dev != 0)
  227489. {
  227490. [dev addSourceTrack: source numSamples: numSamps];
  227491. return true;
  227492. }
  227493. return false;
  227494. }
  227495. const String AudioCDBurner::burn (JUCE_NAMESPACE::AudioCDBurner::BurnProgressListener* listener,
  227496. const bool ejectDiscAfterwards,
  227497. const bool peformFakeBurnForTesting)
  227498. {
  227499. String error ("Couldn't open or write to the CD device");
  227500. OpenDiskDevice* dev = (OpenDiskDevice*) internal;
  227501. if (dev != 0)
  227502. {
  227503. error = String::empty;
  227504. [dev burn: listener
  227505. errorString: &error
  227506. ejectAfterwards: ejectDiscAfterwards
  227507. isFake: peformFakeBurnForTesting];
  227508. }
  227509. return error;
  227510. }
  227511. #endif
  227512. /********* End of inlined file: juce_mac_AudioCDBurner.mm *********/
  227513. /********* Start of inlined file: juce_mac_Fonts.mm *********/
  227514. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227515. // compiled on its own).
  227516. #ifdef JUCE_INCLUDED_FILE
  227517. static OSStatus pascal CubicMoveTo (const Float32Point *pt,
  227518. void* callBackDataPtr)
  227519. {
  227520. Path* const p = (Path*) callBackDataPtr;
  227521. p->startNewSubPath (pt->x, pt->y);
  227522. return noErr;
  227523. }
  227524. static OSStatus pascal CubicLineTo (const Float32Point *pt,
  227525. void* callBackDataPtr)
  227526. {
  227527. Path* const p = (Path*) callBackDataPtr;
  227528. p->lineTo (pt->x, pt->y);
  227529. return noErr;
  227530. }
  227531. static OSStatus pascal CubicCurveTo (const Float32Point *pt1,
  227532. const Float32Point *pt2,
  227533. const Float32Point *pt3,
  227534. void* callBackDataPtr)
  227535. {
  227536. Path* const p = (Path*) callBackDataPtr;
  227537. p->cubicTo (pt1->x, pt1->y,
  227538. pt2->x, pt2->y,
  227539. pt3->x, pt3->y);
  227540. return noErr;
  227541. }
  227542. static OSStatus pascal CubicClosePath (void* callBackDataPtr)
  227543. {
  227544. Path* const p = (Path*) callBackDataPtr;
  227545. p->closeSubPath();
  227546. return noErr;
  227547. }
  227548. class ATSFontHelper
  227549. {
  227550. ATSUFontID fontId;
  227551. ATSUStyle style;
  227552. ATSCubicMoveToUPP moveToProc;
  227553. ATSCubicLineToUPP lineToProc;
  227554. ATSCubicCurveToUPP curveToProc;
  227555. ATSCubicClosePathUPP closePathProc;
  227556. float totalSize, ascent;
  227557. TextToUnicodeInfo encodingInfo;
  227558. public:
  227559. String name;
  227560. bool isBold, isItalic;
  227561. float fontSize;
  227562. int refCount;
  227563. ATSFontHelper (const String& name_,
  227564. const bool bold_,
  227565. const bool italic_,
  227566. const float size_)
  227567. : fontId (0),
  227568. name (name_),
  227569. isBold (bold_),
  227570. isItalic (italic_),
  227571. fontSize (size_),
  227572. refCount (1)
  227573. {
  227574. const char* const nameUtf8 = name_.toUTF8();
  227575. ATSUFindFontFromName (const_cast <char*> (nameUtf8),
  227576. strlen (nameUtf8),
  227577. kFontFullName,
  227578. kFontNoPlatformCode,
  227579. kFontNoScriptCode,
  227580. kFontNoLanguageCode,
  227581. &fontId);
  227582. ATSUCreateStyle (&style);
  227583. ATSUAttributeTag attTypes[] = { kATSUFontTag,
  227584. kATSUQDBoldfaceTag,
  227585. kATSUQDItalicTag,
  227586. kATSUSizeTag };
  227587. ByteCount attSizes[] = { sizeof (ATSUFontID),
  227588. sizeof (Boolean),
  227589. sizeof (Boolean),
  227590. sizeof (Fixed) };
  227591. Boolean bold = bold_, italic = italic_;
  227592. Fixed size = X2Fix (size_);
  227593. ATSUAttributeValuePtr attValues[] = { &fontId,
  227594. &bold,
  227595. &italic,
  227596. &size };
  227597. ATSUSetAttributes (style, 4, attTypes, attSizes, attValues);
  227598. moveToProc = NewATSCubicMoveToUPP (CubicMoveTo);
  227599. lineToProc = NewATSCubicLineToUPP (CubicLineTo);
  227600. curveToProc = NewATSCubicCurveToUPP (CubicCurveTo);
  227601. closePathProc = NewATSCubicClosePathUPP (CubicClosePath);
  227602. ascent = 0.0f;
  227603. float kern, descent = 0.0f;
  227604. getPathAndKerning (T('N'), T('O'), 0, kern, &ascent, &descent);
  227605. totalSize = ascent + descent;
  227606. }
  227607. ~ATSFontHelper()
  227608. {
  227609. ATSUDisposeStyle (style);
  227610. DisposeATSCubicMoveToUPP (moveToProc);
  227611. DisposeATSCubicLineToUPP (lineToProc);
  227612. DisposeATSCubicCurveToUPP (curveToProc);
  227613. DisposeATSCubicClosePathUPP (closePathProc);
  227614. }
  227615. bool getPathAndKerning (const juce_wchar char1,
  227616. const juce_wchar char2,
  227617. Path* path,
  227618. float& kerning,
  227619. float* ascent,
  227620. float* descent)
  227621. {
  227622. bool ok = false;
  227623. UniChar buffer[4];
  227624. buffer[0] = T(' ');
  227625. buffer[1] = char1;
  227626. buffer[2] = char2;
  227627. buffer[3] = 0;
  227628. UniCharCount count = kATSUToTextEnd;
  227629. ATSUTextLayout layout;
  227630. OSStatus err = ATSUCreateTextLayoutWithTextPtr (buffer,
  227631. 0,
  227632. 2,
  227633. 2,
  227634. 1,
  227635. &count,
  227636. &style,
  227637. &layout);
  227638. if (err == noErr)
  227639. {
  227640. ATSUSetTransientFontMatching (layout, true);
  227641. ATSLayoutRecord* layoutRecords;
  227642. ItemCount numRecords;
  227643. Fixed* deltaYs;
  227644. ItemCount numDeltaYs;
  227645. ATSUDirectGetLayoutDataArrayPtrFromTextLayout (layout,
  227646. 0,
  227647. kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
  227648. (void**) &layoutRecords,
  227649. &numRecords);
  227650. ATSUDirectGetLayoutDataArrayPtrFromTextLayout (layout,
  227651. 0,
  227652. kATSUDirectDataBaselineDeltaFixedArray,
  227653. (void**) &deltaYs,
  227654. &numDeltaYs);
  227655. if (numRecords > 2)
  227656. {
  227657. kerning = (float) (Fix2X (layoutRecords[2].realPos)
  227658. - Fix2X (layoutRecords[1].realPos));
  227659. if (ascent != 0)
  227660. {
  227661. ATSUTextMeasurement asc;
  227662. ByteCount actualSize;
  227663. ATSUGetLineControl (layout,
  227664. 0,
  227665. kATSULineAscentTag,
  227666. sizeof (ATSUTextMeasurement),
  227667. &asc,
  227668. &actualSize);
  227669. *ascent = (float) Fix2X (asc);
  227670. }
  227671. if (descent != 0)
  227672. {
  227673. ATSUTextMeasurement desc;
  227674. ByteCount actualSize;
  227675. ATSUGetLineControl (layout,
  227676. 0,
  227677. kATSULineDescentTag,
  227678. sizeof (ATSUTextMeasurement),
  227679. &desc,
  227680. &actualSize);
  227681. *descent = (float) Fix2X (desc);
  227682. }
  227683. if (path != 0)
  227684. {
  227685. OSStatus callbackResult;
  227686. ok = (ATSUGlyphGetCubicPaths (style,
  227687. layoutRecords[1].glyphID,
  227688. moveToProc,
  227689. lineToProc,
  227690. curveToProc,
  227691. closePathProc,
  227692. (void*) path,
  227693. &callbackResult) == noErr);
  227694. if (numDeltaYs > 0 && ok)
  227695. {
  227696. const float dy = (float) Fix2X (deltaYs[1]);
  227697. path->applyTransform (AffineTransform::translation (0.0f, dy));
  227698. }
  227699. }
  227700. else
  227701. {
  227702. ok = true;
  227703. }
  227704. }
  227705. if (deltaYs != 0)
  227706. ATSUDirectReleaseLayoutDataArrayPtr (0, kATSUDirectDataBaselineDeltaFixedArray,
  227707. (void**) &deltaYs);
  227708. if (layoutRecords != 0)
  227709. ATSUDirectReleaseLayoutDataArrayPtr (0, kATSUDirectDataLayoutRecordATSLayoutRecordCurrent,
  227710. (void**) &layoutRecords);
  227711. ATSUDisposeTextLayout (layout);
  227712. }
  227713. return kerning;
  227714. }
  227715. float getAscent()
  227716. {
  227717. return ascent;
  227718. }
  227719. float getTotalHeight()
  227720. {
  227721. return totalSize;
  227722. }
  227723. juce_wchar getDefaultChar()
  227724. {
  227725. return 0;
  227726. }
  227727. };
  227728. class ATSFontHelperCache : public Timer,
  227729. public DeletedAtShutdown
  227730. {
  227731. VoidArray cache;
  227732. public:
  227733. ATSFontHelperCache()
  227734. {
  227735. }
  227736. ~ATSFontHelperCache()
  227737. {
  227738. for (int i = cache.size(); --i >= 0;)
  227739. {
  227740. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  227741. delete f;
  227742. }
  227743. clearSingletonInstance();
  227744. }
  227745. ATSFontHelper* getFont (const String& name,
  227746. const bool bold,
  227747. const bool italic,
  227748. const float size = 1024)
  227749. {
  227750. for (int i = cache.size(); --i >= 0;)
  227751. {
  227752. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  227753. if (f->name == name
  227754. && f->isBold == bold
  227755. && f->isItalic == italic
  227756. && f->fontSize == size)
  227757. {
  227758. f->refCount++;
  227759. return f;
  227760. }
  227761. }
  227762. ATSFontHelper* const f = new ATSFontHelper (name, bold, italic, size);
  227763. cache.add (f);
  227764. return f;
  227765. }
  227766. void releaseFont (ATSFontHelper* f)
  227767. {
  227768. for (int i = cache.size(); --i >= 0;)
  227769. {
  227770. ATSFontHelper* const f2 = (ATSFontHelper*) cache.getUnchecked(i);
  227771. if (f == f2)
  227772. {
  227773. f->refCount--;
  227774. if (f->refCount == 0)
  227775. startTimer (5000);
  227776. break;
  227777. }
  227778. }
  227779. }
  227780. void timerCallback()
  227781. {
  227782. stopTimer();
  227783. for (int i = cache.size(); --i >= 0;)
  227784. {
  227785. ATSFontHelper* const f = (ATSFontHelper*) cache.getUnchecked(i);
  227786. if (f->refCount == 0)
  227787. {
  227788. cache.remove (i);
  227789. delete f;
  227790. }
  227791. }
  227792. if (cache.size() == 0)
  227793. delete this;
  227794. }
  227795. juce_DeclareSingleton_SingleThreaded_Minimal (ATSFontHelperCache)
  227796. };
  227797. juce_ImplementSingleton_SingleThreaded (ATSFontHelperCache)
  227798. void Typeface::initialiseTypefaceCharacteristics (const String& fontName,
  227799. bool bold,
  227800. bool italic,
  227801. bool addAllGlyphsToFont) throw()
  227802. {
  227803. // This method is only safe to be called from the normal UI thread..
  227804. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  227805. ATSFontHelper* const helper = ATSFontHelperCache::getInstance()
  227806. ->getFont (fontName, bold, italic);
  227807. clear();
  227808. setAscent (helper->getAscent() / helper->getTotalHeight());
  227809. setName (fontName);
  227810. setDefaultCharacter (helper->getDefaultChar());
  227811. setBold (bold);
  227812. setItalic (italic);
  227813. if (addAllGlyphsToFont)
  227814. {
  227815. //xxx
  227816. jassertfalse
  227817. }
  227818. ATSFontHelperCache::getInstance()->releaseFont (helper);
  227819. }
  227820. bool Typeface::findAndAddSystemGlyph (juce_wchar character) throw()
  227821. {
  227822. // This method is only safe to be called from the normal UI thread..
  227823. jassert (MessageManager::getInstance()->isThisTheMessageThread());
  227824. ATSFontHelper* const helper = ATSFontHelperCache::getInstance()
  227825. ->getFont (getName(), isBold(), isItalic());
  227826. Path path;
  227827. float width;
  227828. bool foundOne = false;
  227829. if (helper->getPathAndKerning (character, T('I'), &path, width, 0, 0))
  227830. {
  227831. path.applyTransform (AffineTransform::scale (1.0f / helper->getTotalHeight(),
  227832. 1.0f / helper->getTotalHeight()));
  227833. addGlyph (character, path, width / helper->getTotalHeight());
  227834. for (int i = 0; i < glyphs.size(); ++i)
  227835. {
  227836. const TypefaceGlyphInfo* const g = (const TypefaceGlyphInfo*) glyphs.getUnchecked(i);
  227837. float kerning;
  227838. if (helper->getPathAndKerning (character, g->getCharacter(), 0, kerning, 0, 0))
  227839. {
  227840. kerning = (kerning - width) / helper->getTotalHeight();
  227841. if (kerning != 0)
  227842. addKerningPair (character, g->getCharacter(), kerning);
  227843. }
  227844. if (helper->getPathAndKerning (g->getCharacter(), character, 0, kerning, 0, 0))
  227845. {
  227846. kerning = kerning / helper->getTotalHeight() - g->width;
  227847. if (kerning != 0)
  227848. addKerningPair (g->getCharacter(), character, kerning);
  227849. }
  227850. }
  227851. foundOne = true;
  227852. }
  227853. ATSFontHelperCache::getInstance()->releaseFont (helper);
  227854. return foundOne;
  227855. }
  227856. const StringArray Font::findAllTypefaceNames() throw()
  227857. {
  227858. StringArray names;
  227859. ATSFontIterator iter;
  227860. if (ATSFontIteratorCreate (kATSFontContextGlobal,
  227861. 0,
  227862. 0,
  227863. kATSOptionFlagsRestrictedScope,
  227864. &iter) == noErr)
  227865. {
  227866. ATSFontRef font;
  227867. while (ATSFontIteratorNext (iter, &font) == noErr)
  227868. {
  227869. CFStringRef name;
  227870. if (ATSFontGetName (font,
  227871. kATSOptionFlagsDefault,
  227872. &name) == noErr)
  227873. {
  227874. const String nm (PlatformUtilities::cfStringToJuceString (name));
  227875. if (nm.isNotEmpty())
  227876. names.add (nm);
  227877. CFRelease (name);
  227878. }
  227879. }
  227880. ATSFontIteratorRelease (&iter);
  227881. }
  227882. // Use some totuous logic to eliminate bold/italic versions of fonts that we've already got
  227883. // a plain version of. This is only necessary because of Carbon's total lack of support
  227884. // for dealing with font families...
  227885. for (int j = names.size(); --j >= 0;)
  227886. {
  227887. const char* const endings[] = { " bold", " italic", " bold italic", " bolditalic",
  227888. " oblque", " bold oblique", " boldoblique" };
  227889. for (int i = 0; i < numElementsInArray (endings); ++i)
  227890. {
  227891. const String ending (endings[i]);
  227892. if (names[j].endsWithIgnoreCase (ending))
  227893. {
  227894. const String root (names[j].dropLastCharacters (ending.length()).trimEnd());
  227895. if (names.contains (root)
  227896. || names.contains (root + T(" plain"), true))
  227897. {
  227898. names.remove (j);
  227899. break;
  227900. }
  227901. }
  227902. }
  227903. }
  227904. names.sort (true);
  227905. return names;
  227906. }
  227907. void Font::getDefaultFontNames (String& defaultSans, String& defaultSerif, String& defaultFixed) throw()
  227908. {
  227909. defaultSans = "Lucida Grande";
  227910. defaultSerif = "Times New Roman";
  227911. defaultFixed = "Monaco";
  227912. }
  227913. #endif
  227914. /********* End of inlined file: juce_mac_Fonts.mm *********/
  227915. /********* Start of inlined file: juce_mac_MessageManager.mm *********/
  227916. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  227917. // compiled on its own).
  227918. #ifdef JUCE_INCLUDED_FILE
  227919. struct CallbackMessagePayload
  227920. {
  227921. MessageCallbackFunction* function;
  227922. void* parameter;
  227923. void* volatile result;
  227924. bool volatile hasBeenExecuted;
  227925. };
  227926. END_JUCE_NAMESPACE
  227927. using namespace JUCE_NAMESPACE;
  227928. @interface JuceAppDelegate : NSObject
  227929. {
  227930. id oldDelegate;
  227931. }
  227932. - (JuceAppDelegate*) init;
  227933. - (void) dealloc;
  227934. - (BOOL) application: (NSApplication*) theApplication openFile: (NSString*) filename;
  227935. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames;
  227936. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app;
  227937. - (void) applicationDidBecomeActive: (NSNotification*) aNotification;
  227938. - (void) applicationDidResignActive: (NSNotification*) aNotification;
  227939. - (void) applicationWillUnhide: (NSNotification*) aNotification;
  227940. - (void) customEvent: (id) data;
  227941. - (void) performCallback: (id) info;
  227942. - (void) dummyMethod;
  227943. @end
  227944. @implementation JuceAppDelegate
  227945. - (JuceAppDelegate*) init
  227946. {
  227947. [super init];
  227948. NSNotificationCenter* center = [NSNotificationCenter defaultCenter];
  227949. if (JUCEApplication::getInstance() != 0)
  227950. {
  227951. oldDelegate = [NSApp delegate];
  227952. [NSApp setDelegate: self];
  227953. }
  227954. else
  227955. {
  227956. oldDelegate = 0;
  227957. [center addObserver: self selector: @selector (applicationDidResignActive:)
  227958. name: NSApplicationDidResignActiveNotification object: NSApp];
  227959. [center addObserver: self selector: @selector (applicationDidBecomeActive:)
  227960. name: NSApplicationDidBecomeActiveNotification object: NSApp];
  227961. [center addObserver: self selector: @selector (applicationWillUnhide:)
  227962. name: NSApplicationWillUnhideNotification object: NSApp];
  227963. }
  227964. return self;
  227965. }
  227966. - (void) dealloc
  227967. {
  227968. if (oldDelegate != 0)
  227969. [NSApp setDelegate: oldDelegate];
  227970. [super dealloc];
  227971. }
  227972. - (NSApplicationTerminateReply) applicationShouldTerminate: (NSApplication*) app
  227973. {
  227974. if (JUCEApplication::getInstance() != 0)
  227975. {
  227976. JUCEApplication::getInstance()->systemRequestedQuit();
  227977. if (! MessageManager::getInstance()->hasStopMessageBeenSent())
  227978. return NSTerminateCancel;
  227979. }
  227980. return NSTerminateNow;
  227981. }
  227982. - (BOOL) application: (NSApplication*) app openFile: (NSString*) filename
  227983. {
  227984. if (JUCEApplication::getInstance() != 0)
  227985. {
  227986. JUCEApplication::getInstance()->anotherInstanceStarted (nsStringToJuce (filename));
  227987. return YES;
  227988. }
  227989. return NO;
  227990. }
  227991. - (void) application: (NSApplication*) sender openFiles: (NSArray*) filenames
  227992. {
  227993. StringArray files;
  227994. for (int i = 0; i < [filenames count]; ++i)
  227995. files.add (nsStringToJuce ((NSString*) [filenames objectAtIndex: i]));
  227996. if (files.size() > 0 && JUCEApplication::getInstance() != 0)
  227997. JUCEApplication::getInstance()->anotherInstanceStarted (files.joinIntoString (T(" ")));
  227998. }
  227999. - (void) applicationDidBecomeActive: (NSNotification*) aNotification
  228000. {
  228001. juce_HandleProcessFocusChange();
  228002. }
  228003. - (void) applicationDidResignActive: (NSNotification*) aNotification
  228004. {
  228005. juce_HandleProcessFocusChange();
  228006. }
  228007. - (void) applicationWillUnhide: (NSNotification*) aNotification
  228008. {
  228009. juce_HandleProcessFocusChange();
  228010. }
  228011. - (void) customEvent: (id) n
  228012. {
  228013. NSData* data = (NSData*) n;
  228014. void* message = 0;
  228015. [data getBytes: &message length: sizeof (message)];
  228016. if (message != 0)
  228017. MessageManager::getInstance()->deliverMessage (message);
  228018. [data release];
  228019. }
  228020. - (void) performCallback: (id) info
  228021. {
  228022. CallbackMessagePayload* pl = (CallbackMessagePayload*) info;
  228023. if (pl != 0)
  228024. {
  228025. pl->result = (*pl->function) (pl->parameter);
  228026. pl->hasBeenExecuted = true;
  228027. }
  228028. }
  228029. - (void) dummyMethod {} // (used as a way of running a dummy thread)
  228030. @end
  228031. BEGIN_JUCE_NAMESPACE
  228032. static JuceAppDelegate* juceAppDelegate = 0;
  228033. void MessageManager::runDispatchLoop()
  228034. {
  228035. const ScopedAutoReleasePool pool;
  228036. MessageManagerLock mml;
  228037. // must only be called by the message thread!
  228038. jassert (isThisTheMessageThread());
  228039. [NSApp run];
  228040. }
  228041. void MessageManager::stopDispatchLoop()
  228042. {
  228043. quitMessagePosted = true;
  228044. [NSApp stop: nil];
  228045. }
  228046. bool MessageManager::runDispatchLoopUntil (int millisecondsToRunFor)
  228047. {
  228048. const ScopedAutoReleasePool pool;
  228049. jassert (isThisTheMessageThread()); // must only be called by the message thread
  228050. uint32 endTime = Time::getMillisecondCounter() + millisecondsToRunFor;
  228051. NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow: millisecondsToRunFor * 0.001];
  228052. while (Time::getMillisecondCounter() < endTime)
  228053. {
  228054. const ScopedAutoReleasePool pool;
  228055. [[NSRunLoop currentRunLoop] runMode: NSDefaultRunLoopMode
  228056. beforeDate: endDate];
  228057. NSEvent* e = [NSApp nextEventMatchingMask: NSAnyEventMask
  228058. untilDate: endDate
  228059. inMode: NSDefaultRunLoopMode
  228060. dequeue: YES];
  228061. [NSApp sendEvent: e];
  228062. }
  228063. return ! quitMessagePosted;
  228064. }
  228065. void MessageManager::doPlatformSpecificInitialisation()
  228066. {
  228067. if (juceAppDelegate == 0)
  228068. juceAppDelegate = [[JuceAppDelegate alloc] init];
  228069. // This launches a dummy thread, which forces Cocoa to initialise NSThreads
  228070. // correctly (needed prior to 10.5)
  228071. if (! [NSThread isMultiThreaded])
  228072. [NSThread detachNewThreadSelector: @selector (dummyMethod)
  228073. toTarget: juceAppDelegate
  228074. withObject: nil];
  228075. initialiseMainMenu();
  228076. }
  228077. void MessageManager::doPlatformSpecificShutdown()
  228078. {
  228079. [[NSRunLoop currentRunLoop] cancelPerformSelectorsWithTarget: juceAppDelegate];
  228080. [[NSNotificationCenter defaultCenter] removeObserver: juceAppDelegate];
  228081. [juceAppDelegate release];
  228082. juceAppDelegate = 0;
  228083. }
  228084. bool juce_postMessageToSystemQueue (void* message)
  228085. {
  228086. [juceAppDelegate performSelectorOnMainThread: @selector (customEvent:)
  228087. withObject: (id) [[NSData alloc] initWithBytes: &message
  228088. length: (int) sizeof (message)]
  228089. waitUntilDone: NO];
  228090. return true;
  228091. }
  228092. void MessageManager::broadcastMessage (const String& value) throw()
  228093. {
  228094. }
  228095. void* MessageManager::callFunctionOnMessageThread (MessageCallbackFunction* callback,
  228096. void* data)
  228097. {
  228098. if (isThisTheMessageThread())
  228099. {
  228100. return (*callback) (data);
  228101. }
  228102. else
  228103. {
  228104. CallbackMessagePayload cmp;
  228105. cmp.function = callback;
  228106. cmp.parameter = data;
  228107. cmp.result = 0;
  228108. cmp.hasBeenExecuted = false;
  228109. [juceAppDelegate performSelectorOnMainThread: @selector (performCallback:)
  228110. withObject: (id) &cmp
  228111. waitUntilDone: YES];
  228112. return cmp.result;
  228113. }
  228114. }
  228115. #endif
  228116. /********* End of inlined file: juce_mac_MessageManager.mm *********/
  228117. /********* Start of inlined file: juce_mac_WebBrowserComponent.mm *********/
  228118. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228119. // compiled on its own).
  228120. #if JUCE_INCLUDED_FILE && JUCE_WEB_BROWSER
  228121. END_JUCE_NAMESPACE
  228122. @interface DownloadClickDetector : NSObject
  228123. {
  228124. JUCE_NAMESPACE::WebBrowserComponent* ownerComponent;
  228125. }
  228126. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent;
  228127. - (void) webView: (WebView*) webView decidePolicyForNavigationAction: (NSDictionary*) actionInformation
  228128. request: (NSURLRequest*) request
  228129. frame: (WebFrame*) frame
  228130. decisionListener: (id<WebPolicyDecisionListener>) listener;
  228131. @end
  228132. @implementation DownloadClickDetector
  228133. - (DownloadClickDetector*) initWithWebBrowserOwner: (JUCE_NAMESPACE::WebBrowserComponent*) ownerComponent_
  228134. {
  228135. [super init];
  228136. ownerComponent = ownerComponent_;
  228137. return self;
  228138. }
  228139. - (void) webView: (WebView*) sender decidePolicyForNavigationAction: (NSDictionary *)actionInformation request:(NSURLRequest *)request frame:(WebFrame *)frame decisionListener:(id < WebPolicyDecisionListener >)listener
  228140. {
  228141. NSURL* url = [actionInformation valueForKey: @"WebActionOriginalURLKey"];
  228142. if (ownerComponent->pageAboutToLoad (JUCE_NAMESPACE::String::fromUTF8 ((const JUCE_NAMESPACE::uint8*) [[url absoluteString] UTF8String])))
  228143. [listener use];
  228144. else
  228145. [listener ignore];
  228146. }
  228147. @end
  228148. BEGIN_JUCE_NAMESPACE
  228149. class WebBrowserComponentInternal : public NSViewComponent
  228150. {
  228151. public:
  228152. WebBrowserComponentInternal (WebBrowserComponent* owner)
  228153. {
  228154. webView = [[WebView alloc] initWithFrame: NSMakeRect (0, 0, 100.0f, 100.0f)
  228155. frameName: @""
  228156. groupName: @""];
  228157. setView (webView);
  228158. clickListener = [[DownloadClickDetector alloc] initWithWebBrowserOwner: owner];
  228159. [webView setPolicyDelegate: clickListener];
  228160. }
  228161. ~WebBrowserComponentInternal()
  228162. {
  228163. [webView setPolicyDelegate: nil];
  228164. [clickListener release];
  228165. setView (0);
  228166. }
  228167. void goToURL (const String& url,
  228168. const StringArray* headers,
  228169. const MemoryBlock* postData)
  228170. {
  228171. NSMutableURLRequest* r
  228172. = [NSMutableURLRequest requestWithURL: [NSURL URLWithString: juceStringToNS (url)]
  228173. cachePolicy: NSURLRequestUseProtocolCachePolicy
  228174. timeoutInterval: 30.0];
  228175. if (postData != 0 && postData->getSize() > 0)
  228176. {
  228177. [r setHTTPMethod: @"POST"];
  228178. [r setHTTPBody: [NSData dataWithBytes: postData->getData()
  228179. length: postData->getSize()]];
  228180. }
  228181. if (headers != 0)
  228182. {
  228183. for (int i = 0; i < headers->size(); ++i)
  228184. {
  228185. const String headerName ((*headers)[i].upToFirstOccurrenceOf (T(":"), false, false).trim());
  228186. const String headerValue ((*headers)[i].fromFirstOccurrenceOf (T(":"), false, false).trim());
  228187. [r setValue: juceStringToNS (headerValue)
  228188. forHTTPHeaderField: juceStringToNS (headerName)];
  228189. }
  228190. }
  228191. stop();
  228192. [[webView mainFrame] loadRequest: r];
  228193. }
  228194. void goBack()
  228195. {
  228196. [webView goBack];
  228197. }
  228198. void goForward()
  228199. {
  228200. [webView goForward];
  228201. }
  228202. void stop()
  228203. {
  228204. [webView stopLoading: nil];
  228205. }
  228206. private:
  228207. WebView* webView;
  228208. DownloadClickDetector* clickListener;
  228209. };
  228210. WebBrowserComponent::WebBrowserComponent()
  228211. : browser (0),
  228212. blankPageShown (false)
  228213. {
  228214. setOpaque (true);
  228215. addAndMakeVisible (browser = new WebBrowserComponentInternal (this));
  228216. }
  228217. WebBrowserComponent::~WebBrowserComponent()
  228218. {
  228219. deleteAndZero (browser);
  228220. }
  228221. void WebBrowserComponent::goToURL (const String& url,
  228222. const StringArray* headers,
  228223. const MemoryBlock* postData)
  228224. {
  228225. lastURL = url;
  228226. lastHeaders.clear();
  228227. if (headers != 0)
  228228. lastHeaders = *headers;
  228229. lastPostData.setSize (0);
  228230. if (postData != 0)
  228231. lastPostData = *postData;
  228232. blankPageShown = false;
  228233. browser->goToURL (url, headers, postData);
  228234. }
  228235. void WebBrowserComponent::stop()
  228236. {
  228237. browser->stop();
  228238. }
  228239. void WebBrowserComponent::goBack()
  228240. {
  228241. lastURL = String::empty;
  228242. blankPageShown = false;
  228243. browser->goBack();
  228244. }
  228245. void WebBrowserComponent::goForward()
  228246. {
  228247. lastURL = String::empty;
  228248. browser->goForward();
  228249. }
  228250. void WebBrowserComponent::paint (Graphics& g)
  228251. {
  228252. }
  228253. void WebBrowserComponent::checkWindowAssociation()
  228254. {
  228255. // when the component becomes invisible, some stuff like flash
  228256. // carries on playing audio, so we need to force it onto a blank
  228257. // page to avoid this, (and send it back when it's made visible again).
  228258. if (isShowing())
  228259. {
  228260. if (blankPageShown)
  228261. goBack();
  228262. }
  228263. else
  228264. {
  228265. if (! blankPageShown)
  228266. {
  228267. blankPageShown = true;
  228268. browser->goToURL ("about:blank", 0, 0);
  228269. }
  228270. }
  228271. }
  228272. void WebBrowserComponent::reloadLastURL()
  228273. {
  228274. if (lastURL.isNotEmpty())
  228275. {
  228276. goToURL (lastURL, &lastHeaders, &lastPostData);
  228277. lastURL = String::empty;
  228278. }
  228279. }
  228280. void WebBrowserComponent::parentHierarchyChanged()
  228281. {
  228282. checkWindowAssociation();
  228283. }
  228284. void WebBrowserComponent::resized()
  228285. {
  228286. browser->setSize (getWidth(), getHeight());
  228287. }
  228288. void WebBrowserComponent::visibilityChanged()
  228289. {
  228290. checkWindowAssociation();
  228291. }
  228292. bool WebBrowserComponent::pageAboutToLoad (const String& url)
  228293. {
  228294. return true;
  228295. }
  228296. #endif
  228297. /********* End of inlined file: juce_mac_WebBrowserComponent.mm *********/
  228298. /********* Start of inlined file: juce_mac_CoreAudio.cpp *********/
  228299. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  228300. // compiled on its own).
  228301. #ifdef JUCE_INCLUDED_FILE
  228302. #ifndef JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  228303. #define JUCE_COREAUDIO_ERROR_LOGGING_ENABLED 1
  228304. #endif
  228305. #undef log
  228306. #if JUCE_COREAUDIO_LOGGING_ENABLED
  228307. #define log(a) Logger::writeToLog (a)
  228308. #else
  228309. #define log(a)
  228310. #endif
  228311. #undef OK
  228312. #if JUCE_COREAUDIO_ERROR_LOGGING_ENABLED
  228313. static bool logAnyErrors_CoreAudio (const OSStatus err, const int lineNum)
  228314. {
  228315. if (err == noErr)
  228316. return true;
  228317. Logger::writeToLog (T("CoreAudio error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  228318. jassertfalse
  228319. return false;
  228320. }
  228321. #define OK(a) logAnyErrors_CoreAudio (a, __LINE__)
  228322. #else
  228323. #define OK(a) (a == noErr)
  228324. #endif
  228325. static const int maxNumChans = 96;
  228326. class CoreAudioInternal : public Timer
  228327. {
  228328. public:
  228329. CoreAudioInternal (AudioDeviceID id)
  228330. : deviceID (id),
  228331. started (false),
  228332. audioBuffer (0),
  228333. numInputChans (0),
  228334. numOutputChans (0),
  228335. callbacksAllowed (true),
  228336. numInputChannelInfos (0),
  228337. numOutputChannelInfos (0),
  228338. inputLatency (0),
  228339. outputLatency (0),
  228340. callback (0),
  228341. #if ! MACOS_10_4_OR_EARLIER
  228342. audioProcID (0),
  228343. #endif
  228344. inputDevice (0),
  228345. isSlaveDevice (false)
  228346. {
  228347. sampleRate = 0;
  228348. bufferSize = 512;
  228349. if (deviceID == 0)
  228350. {
  228351. error = TRANS("can't open device");
  228352. }
  228353. else
  228354. {
  228355. updateDetailsFromDevice();
  228356. AudioDeviceAddPropertyListener (deviceID,
  228357. kAudioPropertyWildcardChannel,
  228358. kAudioPropertyWildcardSection,
  228359. kAudioPropertyWildcardPropertyID,
  228360. deviceListenerProc, this);
  228361. }
  228362. }
  228363. ~CoreAudioInternal()
  228364. {
  228365. AudioDeviceRemovePropertyListener (deviceID,
  228366. kAudioPropertyWildcardChannel,
  228367. kAudioPropertyWildcardSection,
  228368. kAudioPropertyWildcardPropertyID,
  228369. deviceListenerProc);
  228370. stop (false);
  228371. juce_free (audioBuffer);
  228372. delete inputDevice;
  228373. }
  228374. void setTempBufferSize (const int numChannels, const int numSamples)
  228375. {
  228376. juce_free (audioBuffer);
  228377. audioBuffer = (float*) juce_calloc (32 + numChannels * numSamples * sizeof (float));
  228378. zeromem (tempInputBuffers, sizeof (tempInputBuffers));
  228379. zeromem (tempOutputBuffers, sizeof (tempOutputBuffers));
  228380. int count = 0;
  228381. int i;
  228382. for (i = 0; i < numInputChans; ++i)
  228383. tempInputBuffers[i] = audioBuffer + count++ * numSamples;
  228384. for (i = 0; i < numOutputChans; ++i)
  228385. tempOutputBuffers[i] = audioBuffer + count++ * numSamples;
  228386. }
  228387. // returns the number of actual available channels
  228388. void fillInChannelInfo (bool input)
  228389. {
  228390. int chanNum = 0, activeChans = 0;
  228391. UInt32 size;
  228392. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  228393. {
  228394. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  228395. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  228396. {
  228397. const int numStreams = bufList->mNumberBuffers;
  228398. for (int i = 0; i < numStreams; ++i)
  228399. {
  228400. const AudioBuffer& b = bufList->mBuffers[i];
  228401. for (unsigned int j = 0; j < b.mNumberChannels; ++j)
  228402. {
  228403. if (input)
  228404. {
  228405. if (activeInputChans[chanNum])
  228406. {
  228407. inputChannelInfo [activeChans].sourceChannelNum = chanNum;
  228408. inputChannelInfo [activeChans].streamNum = i;
  228409. inputChannelInfo [activeChans].dataOffsetSamples = j;
  228410. inputChannelInfo [activeChans].dataStrideSamples = b.mNumberChannels;
  228411. ++activeChans;
  228412. numInputChannelInfos = activeChans;
  228413. }
  228414. inChanNames.add (T("input ") + String (chanNum + 1));
  228415. }
  228416. else
  228417. {
  228418. if (activeOutputChans[chanNum])
  228419. {
  228420. outputChannelInfo [activeChans].sourceChannelNum = chanNum;
  228421. outputChannelInfo [activeChans].streamNum = i;
  228422. outputChannelInfo [activeChans].dataOffsetSamples = j;
  228423. outputChannelInfo [activeChans].dataStrideSamples = b.mNumberChannels;
  228424. ++activeChans;
  228425. numOutputChannelInfos = activeChans;
  228426. }
  228427. outChanNames.add (T("output ") + String (chanNum + 1));
  228428. }
  228429. ++chanNum;
  228430. }
  228431. }
  228432. }
  228433. juce_free (bufList);
  228434. }
  228435. }
  228436. void updateDetailsFromDevice()
  228437. {
  228438. stopTimer();
  228439. if (deviceID == 0)
  228440. return;
  228441. const ScopedLock sl (callbackLock);
  228442. Float64 sr;
  228443. UInt32 size = sizeof (Float64);
  228444. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyNominalSampleRate, &size, &sr)))
  228445. sampleRate = sr;
  228446. UInt32 framesPerBuf;
  228447. size = sizeof (framesPerBuf);
  228448. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSize, &size, &framesPerBuf)))
  228449. {
  228450. bufferSize = framesPerBuf;
  228451. if (bufferSize > 0)
  228452. setTempBufferSize (numInputChans + numOutputChans, bufferSize);
  228453. }
  228454. bufferSizes.clear();
  228455. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, 0)))
  228456. {
  228457. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  228458. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyBufferFrameSizeRange, &size, ranges)))
  228459. {
  228460. bufferSizes.add ((int) ranges[0].mMinimum);
  228461. for (int i = 32; i < 8192; i += 32)
  228462. {
  228463. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  228464. {
  228465. if (i >= ranges[j].mMinimum && i <= ranges[j].mMaximum)
  228466. {
  228467. bufferSizes.addIfNotAlreadyThere (i);
  228468. break;
  228469. }
  228470. }
  228471. }
  228472. if (bufferSize > 0)
  228473. bufferSizes.addIfNotAlreadyThere (bufferSize);
  228474. }
  228475. juce_free (ranges);
  228476. }
  228477. if (bufferSizes.size() == 0 && bufferSize > 0)
  228478. bufferSizes.add (bufferSize);
  228479. sampleRates.clear();
  228480. const double possibleRates[] = { 44100.0, 48000.0, 88200.0, 96000.0, 176400.0, 192000.0 };
  228481. String rates;
  228482. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, 0)))
  228483. {
  228484. AudioValueRange* ranges = (AudioValueRange*) juce_calloc (size);
  228485. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyAvailableNominalSampleRates, &size, ranges)))
  228486. {
  228487. for (int i = 0; i < numElementsInArray (possibleRates); ++i)
  228488. {
  228489. bool ok = false;
  228490. for (int j = size / sizeof (AudioValueRange); --j >= 0;)
  228491. if (possibleRates[i] >= ranges[j].mMinimum - 2 && possibleRates[i] <= ranges[j].mMaximum + 2)
  228492. ok = true;
  228493. if (ok)
  228494. {
  228495. sampleRates.add (possibleRates[i]);
  228496. rates << possibleRates[i] << T(" ");
  228497. }
  228498. }
  228499. }
  228500. juce_free (ranges);
  228501. }
  228502. if (sampleRates.size() == 0 && sampleRate > 0)
  228503. {
  228504. sampleRates.add (sampleRate);
  228505. rates << sampleRate;
  228506. }
  228507. log (T("sr: ") + rates);
  228508. inputLatency = 0;
  228509. outputLatency = 0;
  228510. UInt32 lat;
  228511. size = sizeof (UInt32);
  228512. if (AudioDeviceGetProperty (deviceID, 0, true, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  228513. inputLatency = (int) lat;
  228514. if (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyLatency, &size, &lat) == noErr)
  228515. outputLatency = (int) lat;
  228516. log (T("lat: ") + String (inputLatency) + T(" ") + String (outputLatency));
  228517. inChanNames.clear();
  228518. outChanNames.clear();
  228519. zeromem (inputChannelInfo, sizeof (inputChannelInfo));
  228520. zeromem (outputChannelInfo, sizeof (outputChannelInfo));
  228521. fillInChannelInfo (true);
  228522. fillInChannelInfo (false);
  228523. }
  228524. const StringArray getSources (bool input)
  228525. {
  228526. StringArray s;
  228527. int num = 0;
  228528. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  228529. if (types != 0)
  228530. {
  228531. for (int i = 0; i < num; ++i)
  228532. {
  228533. AudioValueTranslation avt;
  228534. char buffer[256];
  228535. avt.mInputData = (void*) &(types[i]);
  228536. avt.mInputDataSize = sizeof (UInt32);
  228537. avt.mOutputData = buffer;
  228538. avt.mOutputDataSize = 256;
  228539. UInt32 transSize = sizeof (avt);
  228540. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSourceNameForID, &transSize, &avt)))
  228541. {
  228542. DBG (buffer);
  228543. s.add (buffer);
  228544. }
  228545. }
  228546. juce_free (types);
  228547. }
  228548. return s;
  228549. }
  228550. int getCurrentSourceIndex (bool input) const
  228551. {
  228552. OSType currentSourceID = 0;
  228553. UInt32 size = 0;
  228554. int result = -1;
  228555. if (deviceID != 0
  228556. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, 0)))
  228557. {
  228558. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSource, &size, &currentSourceID)))
  228559. {
  228560. int num = 0;
  228561. OSType* const types = getAllDataSourcesForDevice (deviceID, input, num);
  228562. if (types != 0)
  228563. {
  228564. for (int i = 0; i < num; ++i)
  228565. {
  228566. if (types[num] == currentSourceID)
  228567. {
  228568. result = i;
  228569. break;
  228570. }
  228571. }
  228572. juce_free (types);
  228573. }
  228574. }
  228575. }
  228576. return result;
  228577. }
  228578. void setCurrentSourceIndex (int index, bool input)
  228579. {
  228580. if (deviceID != 0)
  228581. {
  228582. int num = 0;
  228583. OSType* types = getAllDataSourcesForDevice (deviceID, input, num);
  228584. if (types != 0)
  228585. {
  228586. if (((unsigned int) index) < num)
  228587. {
  228588. OSType typeId = types[index];
  228589. AudioDeviceSetProperty (deviceID, 0, 0, input, kAudioDevicePropertyDataSource, sizeof (typeId), &typeId);
  228590. }
  228591. juce_free (types);
  228592. }
  228593. }
  228594. }
  228595. const String reopen (const BitArray& inputChannels,
  228596. const BitArray& outputChannels,
  228597. double newSampleRate,
  228598. int bufferSizeSamples)
  228599. {
  228600. error = String::empty;
  228601. log ("CoreAudio reopen");
  228602. callbacksAllowed = false;
  228603. stopTimer();
  228604. stop (false);
  228605. activeInputChans = inputChannels;
  228606. activeOutputChans = outputChannels;
  228607. activeInputChans.setRange (inChanNames.size(),
  228608. activeInputChans.getHighestBit() + 1 - inChanNames.size(),
  228609. false);
  228610. activeOutputChans.setRange (outChanNames.size(),
  228611. activeOutputChans.getHighestBit() + 1 - outChanNames.size(),
  228612. false);
  228613. numInputChans = activeInputChans.countNumberOfSetBits();
  228614. numOutputChans = activeOutputChans.countNumberOfSetBits();
  228615. // set sample rate
  228616. Float64 sr = newSampleRate;
  228617. UInt32 size = sizeof (sr);
  228618. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyNominalSampleRate, size, &sr));
  228619. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyNominalSampleRate, size, &sr));
  228620. // change buffer size
  228621. UInt32 framesPerBuf = bufferSizeSamples;
  228622. size = sizeof (framesPerBuf);
  228623. OK (AudioDeviceSetProperty (deviceID, 0, 0, false, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  228624. OK (AudioDeviceSetProperty (deviceID, 0, 0, true, kAudioDevicePropertyBufferFrameSize, size, &framesPerBuf));
  228625. // wait for the changes to happen (on some devices)
  228626. int i = 30;
  228627. while (--i >= 0)
  228628. {
  228629. updateDetailsFromDevice();
  228630. if (sampleRate == newSampleRate && bufferSizeSamples == bufferSize)
  228631. break;
  228632. Thread::sleep (100);
  228633. }
  228634. if (i < 0)
  228635. error = "Couldn't change sample rate/buffer size";
  228636. if (sampleRates.size() == 0)
  228637. error = "Device has no available sample-rates";
  228638. if (bufferSizes.size() == 0)
  228639. error = "Device has no available buffer-sizes";
  228640. if (inputDevice != 0 && error.isEmpty())
  228641. error = inputDevice->reopen (inputChannels,
  228642. outputChannels,
  228643. newSampleRate,
  228644. bufferSizeSamples);
  228645. callbacksAllowed = true;
  228646. return error;
  228647. }
  228648. bool start (AudioIODeviceCallback* cb)
  228649. {
  228650. if (! started)
  228651. {
  228652. callback = 0;
  228653. if (deviceID != 0)
  228654. {
  228655. #if MACOS_10_4_OR_EARLIER
  228656. if (OK (AudioDeviceAddIOProc (deviceID, audioIOProc, (void*) this)))
  228657. #else
  228658. if (OK (AudioDeviceCreateIOProcID (deviceID, audioIOProc, (void*) this, &audioProcID)))
  228659. #endif
  228660. {
  228661. if (OK (AudioDeviceStart (deviceID, audioIOProc)))
  228662. {
  228663. started = true;
  228664. }
  228665. else
  228666. {
  228667. #if MACOS_10_4_OR_EARLIER
  228668. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  228669. #else
  228670. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  228671. audioProcID = 0;
  228672. #endif
  228673. }
  228674. }
  228675. }
  228676. }
  228677. if (started)
  228678. {
  228679. const ScopedLock sl (callbackLock);
  228680. callback = cb;
  228681. }
  228682. if (inputDevice != 0)
  228683. return started && inputDevice->start (cb);
  228684. else
  228685. return started;
  228686. }
  228687. void stop (bool leaveInterruptRunning)
  228688. {
  228689. callbackLock.enter();
  228690. callback = 0;
  228691. callbackLock.exit();
  228692. if (started
  228693. && (deviceID != 0)
  228694. && ! leaveInterruptRunning)
  228695. {
  228696. OK (AudioDeviceStop (deviceID, audioIOProc));
  228697. #if MACOS_10_4_OR_EARLIER
  228698. OK (AudioDeviceRemoveIOProc (deviceID, audioIOProc));
  228699. #else
  228700. OK (AudioDeviceDestroyIOProcID (deviceID, audioProcID));
  228701. audioProcID = 0;
  228702. #endif
  228703. started = false;
  228704. callbackLock.enter();
  228705. callbackLock.exit();
  228706. // wait until it's definately stopped calling back..
  228707. for (int i = 40; --i >= 0;)
  228708. {
  228709. Thread::sleep (50);
  228710. UInt32 running = 0;
  228711. UInt32 size = sizeof (running);
  228712. OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyDeviceIsRunning, &size, &running));
  228713. if (running == 0)
  228714. break;
  228715. }
  228716. callbackLock.enter();
  228717. callbackLock.exit();
  228718. }
  228719. if (inputDevice != 0)
  228720. inputDevice->stop (leaveInterruptRunning);
  228721. }
  228722. double getSampleRate() const
  228723. {
  228724. return sampleRate;
  228725. }
  228726. int getBufferSize() const
  228727. {
  228728. return bufferSize;
  228729. }
  228730. void audioCallback (const AudioBufferList* inInputData,
  228731. AudioBufferList* outOutputData)
  228732. {
  228733. int i;
  228734. const ScopedLock sl (callbackLock);
  228735. if (callback != 0)
  228736. {
  228737. if (inputDevice == 0)
  228738. {
  228739. for (i = numInputChans; --i >= 0;)
  228740. {
  228741. const CallbackDetailsForChannel& info = inputChannelInfo[i];
  228742. float* dest = tempInputBuffers [info.sourceChannelNum];
  228743. const float* src = ((const float*) inInputData->mBuffers[info.streamNum].mData)
  228744. + info.dataOffsetSamples;
  228745. const int stride = info.dataStrideSamples;
  228746. if (stride != 0) // if this is zero, info is invalid
  228747. {
  228748. for (int j = bufferSize; --j >= 0;)
  228749. {
  228750. *dest++ = *src;
  228751. src += stride;
  228752. }
  228753. }
  228754. }
  228755. }
  228756. if (! isSlaveDevice)
  228757. {
  228758. if (inputDevice == 0)
  228759. {
  228760. callback->audioDeviceIOCallback ((const float**) tempInputBuffers,
  228761. numInputChans,
  228762. tempOutputBuffers,
  228763. numOutputChans,
  228764. bufferSize);
  228765. }
  228766. else
  228767. {
  228768. jassert (inputDevice->bufferSize == bufferSize);
  228769. callback->audioDeviceIOCallback ((const float**) inputDevice->tempInputBuffers,
  228770. inputDevice->numInputChans,
  228771. tempOutputBuffers,
  228772. numOutputChans,
  228773. bufferSize);
  228774. }
  228775. for (i = numOutputChans; --i >= 0;)
  228776. {
  228777. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  228778. const float* src = tempOutputBuffers [i];
  228779. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  228780. + info.dataOffsetSamples;
  228781. const int stride = info.dataStrideSamples;
  228782. if (stride != 0) // if this is zero, info is invalid
  228783. {
  228784. for (int j = bufferSize; --j >= 0;)
  228785. {
  228786. *dest = *src++;
  228787. dest += stride;
  228788. }
  228789. }
  228790. }
  228791. }
  228792. }
  228793. else
  228794. {
  228795. for (i = jmin (numOutputChans, numOutputChannelInfos); --i >= 0;)
  228796. {
  228797. const CallbackDetailsForChannel& info = outputChannelInfo[i];
  228798. float* dest = ((float*) outOutputData->mBuffers[info.streamNum].mData)
  228799. + info.dataOffsetSamples;
  228800. const int stride = info.dataStrideSamples;
  228801. if (stride != 0) // if this is zero, info is invalid
  228802. {
  228803. for (int j = bufferSize; --j >= 0;)
  228804. {
  228805. *dest = 0.0f;
  228806. dest += stride;
  228807. }
  228808. }
  228809. }
  228810. }
  228811. }
  228812. // called by callbacks
  228813. void deviceDetailsChanged()
  228814. {
  228815. if (callbacksAllowed)
  228816. startTimer (100);
  228817. }
  228818. void timerCallback()
  228819. {
  228820. stopTimer();
  228821. log ("CoreAudio device changed callback");
  228822. const double oldSampleRate = sampleRate;
  228823. const int oldBufferSize = bufferSize;
  228824. updateDetailsFromDevice();
  228825. if (oldBufferSize != bufferSize || oldSampleRate != sampleRate)
  228826. {
  228827. callbacksAllowed = false;
  228828. stop (false);
  228829. updateDetailsFromDevice();
  228830. callbacksAllowed = true;
  228831. }
  228832. }
  228833. CoreAudioInternal* getRelatedDevice() const
  228834. {
  228835. UInt32 size = 0;
  228836. CoreAudioInternal* result = 0;
  228837. if (deviceID != 0
  228838. && AudioDeviceGetPropertyInfo (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, 0) == noErr
  228839. && size > 0)
  228840. {
  228841. AudioDeviceID* devs = (AudioDeviceID*) juce_calloc (size);
  228842. if (OK (AudioDeviceGetProperty (deviceID, 0, false, kAudioDevicePropertyRelatedDevices, &size, devs)))
  228843. {
  228844. for (unsigned int i = 0; i < size / sizeof (AudioDeviceID); ++i)
  228845. {
  228846. if (devs[i] != deviceID && devs[i] != 0)
  228847. {
  228848. result = new CoreAudioInternal (devs[i]);
  228849. if (result->error.isEmpty())
  228850. {
  228851. const bool thisIsInput = inChanNames.size() > 0 && outChanNames.size() == 0;
  228852. const bool otherIsInput = result->inChanNames.size() > 0 && result->outChanNames.size() == 0;
  228853. if (thisIsInput != otherIsInput
  228854. || (inChanNames.size() + outChanNames.size() == 0)
  228855. || (result->inChanNames.size() + result->outChanNames.size()) == 0)
  228856. break;
  228857. }
  228858. deleteAndZero (result);
  228859. }
  228860. }
  228861. }
  228862. juce_free (devs);
  228863. }
  228864. return result;
  228865. }
  228866. juce_UseDebuggingNewOperator
  228867. String error;
  228868. int inputLatency, outputLatency;
  228869. BitArray activeInputChans, activeOutputChans;
  228870. StringArray inChanNames, outChanNames;
  228871. Array <double> sampleRates;
  228872. Array <int> bufferSizes;
  228873. AudioIODeviceCallback* callback;
  228874. #if ! MACOS_10_4_OR_EARLIER
  228875. AudioDeviceIOProcID audioProcID;
  228876. #endif
  228877. CoreAudioInternal* inputDevice;
  228878. bool isSlaveDevice;
  228879. private:
  228880. CriticalSection callbackLock;
  228881. AudioDeviceID deviceID;
  228882. bool started;
  228883. double sampleRate;
  228884. int bufferSize;
  228885. float* audioBuffer;
  228886. int numInputChans, numOutputChans;
  228887. bool callbacksAllowed;
  228888. struct CallbackDetailsForChannel
  228889. {
  228890. int sourceChannelNum;
  228891. int streamNum;
  228892. int dataOffsetSamples;
  228893. int dataStrideSamples;
  228894. };
  228895. int numInputChannelInfos, numOutputChannelInfos;
  228896. CallbackDetailsForChannel inputChannelInfo [maxNumChans];
  228897. CallbackDetailsForChannel outputChannelInfo [maxNumChans];
  228898. float* tempInputBuffers [maxNumChans];
  228899. float* tempOutputBuffers [maxNumChans];
  228900. CoreAudioInternal (const CoreAudioInternal&);
  228901. const CoreAudioInternal& operator= (const CoreAudioInternal&);
  228902. static OSStatus audioIOProc (AudioDeviceID inDevice,
  228903. const AudioTimeStamp* inNow,
  228904. const AudioBufferList* inInputData,
  228905. const AudioTimeStamp* inInputTime,
  228906. AudioBufferList* outOutputData,
  228907. const AudioTimeStamp* inOutputTime,
  228908. void* device)
  228909. {
  228910. ((CoreAudioInternal*) device)->audioCallback (inInputData, outOutputData);
  228911. return noErr;
  228912. }
  228913. static OSStatus deviceListenerProc (AudioDeviceID inDevice,
  228914. UInt32 inLine,
  228915. Boolean isInput,
  228916. AudioDevicePropertyID inPropertyID,
  228917. void* inClientData)
  228918. {
  228919. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  228920. switch (inPropertyID)
  228921. {
  228922. case kAudioDevicePropertyBufferSize:
  228923. case kAudioDevicePropertyBufferFrameSize:
  228924. case kAudioDevicePropertyNominalSampleRate:
  228925. case kAudioDevicePropertyStreamFormat:
  228926. case kAudioDevicePropertyDeviceIsAlive:
  228927. intern->deviceDetailsChanged();
  228928. break;
  228929. case kAudioDevicePropertyBufferSizeRange:
  228930. case kAudioDevicePropertyVolumeScalar:
  228931. case kAudioDevicePropertyMute:
  228932. case kAudioDevicePropertyPlayThru:
  228933. case kAudioDevicePropertyDataSource:
  228934. case kAudioDevicePropertyDeviceIsRunning:
  228935. break;
  228936. }
  228937. return noErr;
  228938. }
  228939. static OSType* getAllDataSourcesForDevice (AudioDeviceID deviceID, const bool input, int& num)
  228940. {
  228941. OSType* types = 0;
  228942. UInt32 size = 0;
  228943. num = 0;
  228944. if (deviceID != 0
  228945. && OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, 0)))
  228946. {
  228947. types = (OSType*) juce_calloc (size);
  228948. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyDataSources, &size, types)))
  228949. {
  228950. num = size / sizeof (OSType);
  228951. }
  228952. else
  228953. {
  228954. juce_free (types);
  228955. types = 0;
  228956. }
  228957. }
  228958. return types;
  228959. }
  228960. };
  228961. class CoreAudioIODevice : public AudioIODevice
  228962. {
  228963. public:
  228964. CoreAudioIODevice (const String& deviceName,
  228965. AudioDeviceID inputDeviceId,
  228966. const int inputIndex_,
  228967. AudioDeviceID outputDeviceId,
  228968. const int outputIndex_)
  228969. : AudioIODevice (deviceName, "CoreAudio"),
  228970. inputIndex (inputIndex_),
  228971. outputIndex (outputIndex_),
  228972. isOpen_ (false),
  228973. isStarted (false)
  228974. {
  228975. internal = 0;
  228976. CoreAudioInternal* device = 0;
  228977. if (outputDeviceId == 0 || outputDeviceId == inputDeviceId)
  228978. {
  228979. jassert (inputDeviceId != 0);
  228980. device = new CoreAudioInternal (inputDeviceId);
  228981. lastError = device->error;
  228982. if (lastError.isNotEmpty())
  228983. deleteAndZero (device);
  228984. }
  228985. else
  228986. {
  228987. device = new CoreAudioInternal (outputDeviceId);
  228988. lastError = device->error;
  228989. if (lastError.isNotEmpty())
  228990. {
  228991. deleteAndZero (device);
  228992. }
  228993. else if (inputDeviceId != 0)
  228994. {
  228995. CoreAudioInternal* secondDevice = new CoreAudioInternal (inputDeviceId);
  228996. lastError = device->error;
  228997. if (lastError.isNotEmpty())
  228998. {
  228999. delete secondDevice;
  229000. }
  229001. else
  229002. {
  229003. device->inputDevice = secondDevice;
  229004. secondDevice->isSlaveDevice = true;
  229005. }
  229006. }
  229007. }
  229008. internal = device;
  229009. AudioHardwareAddPropertyListener (kAudioPropertyWildcardPropertyID,
  229010. hardwareListenerProc, internal);
  229011. }
  229012. ~CoreAudioIODevice()
  229013. {
  229014. AudioHardwareRemovePropertyListener (kAudioPropertyWildcardPropertyID,
  229015. hardwareListenerProc);
  229016. delete internal;
  229017. }
  229018. const StringArray getOutputChannelNames()
  229019. {
  229020. return internal->outChanNames;
  229021. }
  229022. const StringArray getInputChannelNames()
  229023. {
  229024. if (internal->inputDevice != 0)
  229025. return internal->inputDevice->inChanNames;
  229026. else
  229027. return internal->inChanNames;
  229028. }
  229029. int getNumSampleRates()
  229030. {
  229031. return internal->sampleRates.size();
  229032. }
  229033. double getSampleRate (int index)
  229034. {
  229035. return internal->sampleRates [index];
  229036. }
  229037. int getNumBufferSizesAvailable()
  229038. {
  229039. return internal->bufferSizes.size();
  229040. }
  229041. int getBufferSizeSamples (int index)
  229042. {
  229043. return internal->bufferSizes [index];
  229044. }
  229045. int getDefaultBufferSize()
  229046. {
  229047. for (int i = 0; i < getNumBufferSizesAvailable(); ++i)
  229048. if (getBufferSizeSamples(i) >= 512)
  229049. return getBufferSizeSamples(i);
  229050. return 512;
  229051. }
  229052. const String open (const BitArray& inputChannels,
  229053. const BitArray& outputChannels,
  229054. double sampleRate,
  229055. int bufferSizeSamples)
  229056. {
  229057. isOpen_ = true;
  229058. if (bufferSizeSamples <= 0)
  229059. bufferSizeSamples = getDefaultBufferSize();
  229060. internal->reopen (inputChannels, outputChannels, sampleRate, bufferSizeSamples);
  229061. lastError = internal->error;
  229062. return lastError;
  229063. }
  229064. void close()
  229065. {
  229066. isOpen_ = false;
  229067. }
  229068. bool isOpen()
  229069. {
  229070. return isOpen_;
  229071. }
  229072. int getCurrentBufferSizeSamples()
  229073. {
  229074. return internal != 0 ? internal->getBufferSize() : 512;
  229075. }
  229076. double getCurrentSampleRate()
  229077. {
  229078. return internal != 0 ? internal->getSampleRate() : 0;
  229079. }
  229080. int getCurrentBitDepth()
  229081. {
  229082. return 32; // no way to find out, so just assume it's high..
  229083. }
  229084. const BitArray getActiveOutputChannels() const
  229085. {
  229086. return internal != 0 ? internal->activeOutputChans : BitArray();
  229087. }
  229088. const BitArray getActiveInputChannels() const
  229089. {
  229090. BitArray chans;
  229091. if (internal != 0)
  229092. {
  229093. chans = internal->activeInputChans;
  229094. if (internal->inputDevice != 0)
  229095. chans.orWith (internal->inputDevice->activeInputChans);
  229096. }
  229097. return chans;
  229098. }
  229099. int getOutputLatencyInSamples()
  229100. {
  229101. if (internal == 0)
  229102. return 0;
  229103. // this seems like a good guess at getting the latency right - comparing
  229104. // this with a round-trip measurement, it gets it to within a few millisecs
  229105. // for the built-in mac soundcard
  229106. return internal->outputLatency + internal->getBufferSize() * 2;
  229107. }
  229108. int getInputLatencyInSamples()
  229109. {
  229110. if (internal == 0)
  229111. return 0;
  229112. return internal->inputLatency + internal->getBufferSize() * 2;
  229113. }
  229114. void start (AudioIODeviceCallback* callback)
  229115. {
  229116. if (internal != 0 && ! isStarted)
  229117. {
  229118. if (callback != 0)
  229119. callback->audioDeviceAboutToStart (this);
  229120. isStarted = true;
  229121. internal->start (callback);
  229122. }
  229123. }
  229124. void stop()
  229125. {
  229126. if (isStarted && internal != 0)
  229127. {
  229128. AudioIODeviceCallback* const lastCallback = internal->callback;
  229129. isStarted = false;
  229130. internal->stop (true);
  229131. if (lastCallback != 0)
  229132. lastCallback->audioDeviceStopped();
  229133. }
  229134. }
  229135. bool isPlaying()
  229136. {
  229137. if (internal->callback == 0)
  229138. isStarted = false;
  229139. return isStarted;
  229140. }
  229141. const String getLastError()
  229142. {
  229143. return lastError;
  229144. }
  229145. int inputIndex, outputIndex;
  229146. juce_UseDebuggingNewOperator
  229147. private:
  229148. CoreAudioInternal* internal;
  229149. bool isOpen_, isStarted;
  229150. String lastError;
  229151. static OSStatus hardwareListenerProc (AudioHardwarePropertyID inPropertyID, void* inClientData)
  229152. {
  229153. CoreAudioInternal* const intern = (CoreAudioInternal*) inClientData;
  229154. switch (inPropertyID)
  229155. {
  229156. case kAudioHardwarePropertyDevices:
  229157. intern->deviceDetailsChanged();
  229158. break;
  229159. case kAudioHardwarePropertyDefaultOutputDevice:
  229160. case kAudioHardwarePropertyDefaultInputDevice:
  229161. case kAudioHardwarePropertyDefaultSystemOutputDevice:
  229162. break;
  229163. }
  229164. return noErr;
  229165. }
  229166. CoreAudioIODevice (const CoreAudioIODevice&);
  229167. const CoreAudioIODevice& operator= (const CoreAudioIODevice&);
  229168. };
  229169. class CoreAudioIODeviceType : public AudioIODeviceType
  229170. {
  229171. public:
  229172. CoreAudioIODeviceType()
  229173. : AudioIODeviceType (T("CoreAudio")),
  229174. hasScanned (false)
  229175. {
  229176. }
  229177. ~CoreAudioIODeviceType()
  229178. {
  229179. }
  229180. void scanForDevices()
  229181. {
  229182. hasScanned = true;
  229183. inputDeviceNames.clear();
  229184. outputDeviceNames.clear();
  229185. inputIds.clear();
  229186. outputIds.clear();
  229187. UInt32 size;
  229188. if (OK (AudioHardwareGetPropertyInfo (kAudioHardwarePropertyDevices, &size, 0)))
  229189. {
  229190. AudioDeviceID* const devs = (AudioDeviceID*) juce_calloc (size);
  229191. if (OK (AudioHardwareGetProperty (kAudioHardwarePropertyDevices, &size, devs)))
  229192. {
  229193. static bool alreadyLogged = false;
  229194. const int num = size / sizeof (AudioDeviceID);
  229195. for (int i = 0; i < num; ++i)
  229196. {
  229197. char name[1024];
  229198. size = sizeof (name);
  229199. if (OK (AudioDeviceGetProperty (devs[i], 0, false, kAudioDevicePropertyDeviceName, &size, name)))
  229200. {
  229201. const String nameString (String::fromUTF8 ((const uint8*) name, strlen (name)));
  229202. if (! alreadyLogged)
  229203. log (T("CoreAudio device: ") + nameString);
  229204. const int numIns = getNumChannels (devs[i], true);
  229205. const int numOuts = getNumChannels (devs[i], false);
  229206. if (numIns > 0)
  229207. {
  229208. inputDeviceNames.add (nameString);
  229209. inputIds.add (devs[i]);
  229210. }
  229211. if (numOuts > 0)
  229212. {
  229213. outputDeviceNames.add (nameString);
  229214. outputIds.add (devs[i]);
  229215. }
  229216. }
  229217. }
  229218. alreadyLogged = true;
  229219. }
  229220. juce_free (devs);
  229221. }
  229222. inputDeviceNames.appendNumbersToDuplicates (false, true);
  229223. outputDeviceNames.appendNumbersToDuplicates (false, true);
  229224. }
  229225. const StringArray getDeviceNames (const bool wantInputNames) const
  229226. {
  229227. jassert (hasScanned); // need to call scanForDevices() before doing this
  229228. if (wantInputNames)
  229229. return inputDeviceNames;
  229230. else
  229231. return outputDeviceNames;
  229232. }
  229233. int getDefaultDeviceIndex (const bool forInput) const
  229234. {
  229235. jassert (hasScanned); // need to call scanForDevices() before doing this
  229236. AudioDeviceID deviceID;
  229237. UInt32 size = sizeof (deviceID);
  229238. // if they're asking for any input channels at all, use the default input, so we
  229239. // get the built-in mic rather than the built-in output with no inputs..
  229240. if (AudioHardwareGetProperty (forInput ? kAudioHardwarePropertyDefaultInputDevice
  229241. : kAudioHardwarePropertyDefaultOutputDevice,
  229242. &size, &deviceID) == noErr)
  229243. {
  229244. if (forInput)
  229245. {
  229246. for (int i = inputIds.size(); --i >= 0;)
  229247. if (inputIds[i] == deviceID)
  229248. return i;
  229249. }
  229250. else
  229251. {
  229252. for (int i = outputIds.size(); --i >= 0;)
  229253. if (outputIds[i] == deviceID)
  229254. return i;
  229255. }
  229256. }
  229257. return 0;
  229258. }
  229259. int getIndexOfDevice (AudioIODevice* device, const bool asInput) const
  229260. {
  229261. jassert (hasScanned); // need to call scanForDevices() before doing this
  229262. CoreAudioIODevice* const d = dynamic_cast <CoreAudioIODevice*> (device);
  229263. if (d == 0)
  229264. return -1;
  229265. return asInput ? d->inputIndex
  229266. : d->outputIndex;
  229267. }
  229268. bool hasSeparateInputsAndOutputs() const { return true; }
  229269. AudioIODevice* createDevice (const String& outputDeviceName,
  229270. const String& inputDeviceName)
  229271. {
  229272. jassert (hasScanned); // need to call scanForDevices() before doing this
  229273. const int inputIndex = inputDeviceNames.indexOf (inputDeviceName);
  229274. const int outputIndex = outputDeviceNames.indexOf (outputDeviceName);
  229275. String deviceName (outputDeviceName);
  229276. if (deviceName.isEmpty())
  229277. deviceName = inputDeviceName;
  229278. if (index >= 0)
  229279. return new CoreAudioIODevice (deviceName,
  229280. inputIds [inputIndex],
  229281. inputIndex,
  229282. outputIds [outputIndex],
  229283. outputIndex);
  229284. return 0;
  229285. }
  229286. juce_UseDebuggingNewOperator
  229287. private:
  229288. StringArray inputDeviceNames, outputDeviceNames;
  229289. Array <AudioDeviceID> inputIds, outputIds;
  229290. bool hasScanned;
  229291. static int getNumChannels (AudioDeviceID deviceID, bool input)
  229292. {
  229293. int total = 0;
  229294. UInt32 size;
  229295. if (OK (AudioDeviceGetPropertyInfo (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, 0)))
  229296. {
  229297. AudioBufferList* const bufList = (AudioBufferList*) juce_calloc (size);
  229298. if (OK (AudioDeviceGetProperty (deviceID, 0, input, kAudioDevicePropertyStreamConfiguration, &size, bufList)))
  229299. {
  229300. const int numStreams = bufList->mNumberBuffers;
  229301. for (int i = 0; i < numStreams; ++i)
  229302. {
  229303. const AudioBuffer& b = bufList->mBuffers[i];
  229304. total += b.mNumberChannels;
  229305. }
  229306. }
  229307. juce_free (bufList);
  229308. }
  229309. return total;
  229310. }
  229311. CoreAudioIODeviceType (const CoreAudioIODeviceType&);
  229312. const CoreAudioIODeviceType& operator= (const CoreAudioIODeviceType&);
  229313. };
  229314. AudioIODeviceType* juce_createDefaultAudioIODeviceType()
  229315. {
  229316. return new CoreAudioIODeviceType();
  229317. }
  229318. #undef log
  229319. #endif
  229320. /********* End of inlined file: juce_mac_CoreAudio.cpp *********/
  229321. /********* Start of inlined file: juce_mac_CoreMidi.cpp *********/
  229322. // (This file gets included by juce_mac_NativeCode.mm, rather than being
  229323. // compiled on its own).
  229324. #ifdef JUCE_INCLUDED_FILE
  229325. #undef log
  229326. #define log(a) Logger::writeToLog(a)
  229327. static bool logAnyErrorsMidi (const OSStatus err, const int lineNum)
  229328. {
  229329. if (err == noErr)
  229330. return true;
  229331. log (T("CoreMidi error: ") + String (lineNum) + T(" - ") + String::toHexString ((int)err));
  229332. jassertfalse
  229333. return false;
  229334. }
  229335. #undef OK
  229336. #define OK(a) logAnyErrorsMidi(a, __LINE__)
  229337. static const String getEndpointName (MIDIEndpointRef endpoint, bool isExternal)
  229338. {
  229339. String result;
  229340. CFStringRef str = 0;
  229341. MIDIObjectGetStringProperty (endpoint, kMIDIPropertyName, &str);
  229342. if (str != 0)
  229343. {
  229344. result = PlatformUtilities::cfStringToJuceString (str);
  229345. CFRelease (str);
  229346. str = 0;
  229347. }
  229348. MIDIEntityRef entity = 0;
  229349. MIDIEndpointGetEntity (endpoint, &entity);
  229350. if (entity == 0)
  229351. return result; // probably virtual
  229352. if (result.isEmpty())
  229353. {
  229354. // endpoint name has zero length - try the entity
  229355. MIDIObjectGetStringProperty (entity, kMIDIPropertyName, &str);
  229356. if (str != 0)
  229357. {
  229358. result += PlatformUtilities::cfStringToJuceString (str);
  229359. CFRelease (str);
  229360. str = 0;
  229361. }
  229362. }
  229363. // now consider the device's name
  229364. MIDIDeviceRef device = 0;
  229365. MIDIEntityGetDevice (entity, &device);
  229366. if (device == 0)
  229367. return result;
  229368. MIDIObjectGetStringProperty (device, kMIDIPropertyName, &str);
  229369. if (str != 0)
  229370. {
  229371. const String s (PlatformUtilities::cfStringToJuceString (str));
  229372. CFRelease (str);
  229373. // if an external device has only one entity, throw away
  229374. // the endpoint name and just use the device name
  229375. if (isExternal && MIDIDeviceGetNumberOfEntities (device) < 2)
  229376. {
  229377. result = s;
  229378. }
  229379. else if (! result.startsWithIgnoreCase (s))
  229380. {
  229381. // prepend the device name to the entity name
  229382. result = (s + T(" ") + result).trimEnd();
  229383. }
  229384. }
  229385. return result;
  229386. }
  229387. static const String getConnectedEndpointName (MIDIEndpointRef endpoint)
  229388. {
  229389. String result;
  229390. // Does the endpoint have connections?
  229391. CFDataRef connections = 0;
  229392. int numConnections = 0;
  229393. MIDIObjectGetDataProperty (endpoint, kMIDIPropertyConnectionUniqueID, &connections);
  229394. if (connections != 0)
  229395. {
  229396. numConnections = CFDataGetLength (connections) / sizeof (MIDIUniqueID);
  229397. if (numConnections > 0)
  229398. {
  229399. const SInt32* pid = reinterpret_cast <const SInt32*> (CFDataGetBytePtr (connections));
  229400. for (int i = 0; i < numConnections; ++i, ++pid)
  229401. {
  229402. MIDIUniqueID uid = EndianS32_BtoN (*pid);
  229403. MIDIObjectRef connObject;
  229404. MIDIObjectType connObjectType;
  229405. OSStatus err = MIDIObjectFindByUniqueID (uid, &connObject, &connObjectType);
  229406. if (err == noErr)
  229407. {
  229408. String s;
  229409. if (connObjectType == kMIDIObjectType_ExternalSource
  229410. || connObjectType == kMIDIObjectType_ExternalDestination)
  229411. {
  229412. // Connected to an external device's endpoint (10.3 and later).
  229413. s = getEndpointName (static_cast <MIDIEndpointRef> (connObject), true);
  229414. }
  229415. else
  229416. {
  229417. // Connected to an external device (10.2) (or something else, catch-all)
  229418. CFStringRef str = 0;
  229419. MIDIObjectGetStringProperty (connObject, kMIDIPropertyName, &str);
  229420. if (str != 0)
  229421. {
  229422. s = PlatformUtilities::cfStringToJuceString (str);
  229423. CFRelease (str);
  229424. }
  229425. }
  229426. if (s.isNotEmpty())
  229427. {
  229428. if (result.isNotEmpty())
  229429. result += (", ");
  229430. result += s;
  229431. }
  229432. }
  229433. }
  229434. }
  229435. CFRelease (connections);
  229436. }
  229437. if (result.isNotEmpty())
  229438. return result;
  229439. // Here, either the endpoint had no connections, or we failed to obtain names for any of them.
  229440. return getEndpointName (endpoint, false);
  229441. }
  229442. const StringArray MidiOutput::getDevices()
  229443. {
  229444. StringArray s;
  229445. const ItemCount num = MIDIGetNumberOfDestinations();
  229446. for (ItemCount i = 0; i < num; ++i)
  229447. {
  229448. MIDIEndpointRef dest = MIDIGetDestination (i);
  229449. if (dest != 0)
  229450. {
  229451. String name (getConnectedEndpointName (dest));
  229452. if (name.isEmpty())
  229453. name = "<error>";
  229454. s.add (name);
  229455. }
  229456. else
  229457. {
  229458. s.add ("<error>");
  229459. }
  229460. }
  229461. return s;
  229462. }
  229463. int MidiOutput::getDefaultDeviceIndex()
  229464. {
  229465. return 0;
  229466. }
  229467. static MIDIClientRef globalMidiClient;
  229468. static bool hasGlobalClientBeenCreated = false;
  229469. static bool makeSureClientExists()
  229470. {
  229471. if (! hasGlobalClientBeenCreated)
  229472. {
  229473. String name (T("JUCE"));
  229474. if (JUCEApplication::getInstance() != 0)
  229475. name = JUCEApplication::getInstance()->getApplicationName();
  229476. CFStringRef appName = PlatformUtilities::juceStringToCFString (name);
  229477. hasGlobalClientBeenCreated = OK (MIDIClientCreate (appName, 0, 0, &globalMidiClient));
  229478. CFRelease (appName);
  229479. }
  229480. return hasGlobalClientBeenCreated;
  229481. }
  229482. struct MidiPortAndEndpoint
  229483. {
  229484. MIDIPortRef port;
  229485. MIDIEndpointRef endPoint;
  229486. };
  229487. MidiOutput* MidiOutput::openDevice (int index)
  229488. {
  229489. MidiOutput* mo = 0;
  229490. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfDestinations())
  229491. {
  229492. MIDIEndpointRef endPoint = MIDIGetDestination (index);
  229493. CFStringRef pname;
  229494. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229495. {
  229496. log (T("CoreMidi - opening out: ") + PlatformUtilities::cfStringToJuceString (pname));
  229497. if (makeSureClientExists())
  229498. {
  229499. MIDIPortRef port;
  229500. if (OK (MIDIOutputPortCreate (globalMidiClient, pname, &port)))
  229501. {
  229502. MidiPortAndEndpoint* mpe = new MidiPortAndEndpoint();
  229503. mpe->port = port;
  229504. mpe->endPoint = endPoint;
  229505. mo = new MidiOutput();
  229506. mo->internal = (void*)mpe;
  229507. }
  229508. }
  229509. CFRelease (pname);
  229510. }
  229511. }
  229512. return mo;
  229513. }
  229514. MidiOutput::~MidiOutput()
  229515. {
  229516. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  229517. MIDIPortDispose (mpe->port);
  229518. delete mpe;
  229519. }
  229520. void MidiOutput::reset()
  229521. {
  229522. }
  229523. bool MidiOutput::getVolume (float& leftVol, float& rightVol)
  229524. {
  229525. return false;
  229526. }
  229527. void MidiOutput::setVolume (float leftVol, float rightVol)
  229528. {
  229529. }
  229530. void MidiOutput::sendMessageNow (const MidiMessage& message)
  229531. {
  229532. MidiPortAndEndpoint* const mpe = (MidiPortAndEndpoint*)internal;
  229533. if (message.isSysEx())
  229534. {
  229535. MIDIPacketList* const packets = (MIDIPacketList*) juce_malloc (32 + message.getRawDataSize());
  229536. packets->numPackets = 1;
  229537. packets->packet[0].timeStamp = 0;
  229538. packets->packet[0].length = message.getRawDataSize();
  229539. memcpy (packets->packet[0].data, message.getRawData(), message.getRawDataSize());
  229540. MIDISend (mpe->port, mpe->endPoint, packets);
  229541. juce_free (packets);
  229542. }
  229543. else
  229544. {
  229545. MIDIPacketList packets;
  229546. packets.numPackets = 1;
  229547. packets.packet[0].timeStamp = 0;
  229548. packets.packet[0].length = message.getRawDataSize();
  229549. *(int*) (packets.packet[0].data) = *(const int*) message.getRawData();
  229550. MIDISend (mpe->port, mpe->endPoint, &packets);
  229551. }
  229552. }
  229553. const StringArray MidiInput::getDevices()
  229554. {
  229555. StringArray s;
  229556. const ItemCount num = MIDIGetNumberOfSources();
  229557. for (ItemCount i = 0; i < num; ++i)
  229558. {
  229559. MIDIEndpointRef source = MIDIGetSource (i);
  229560. if (source != 0)
  229561. {
  229562. String name (getConnectedEndpointName (source));
  229563. if (name.isEmpty())
  229564. name = "<error>";
  229565. s.add (name);
  229566. }
  229567. else
  229568. {
  229569. s.add ("<error>");
  229570. }
  229571. }
  229572. return s;
  229573. }
  229574. int MidiInput::getDefaultDeviceIndex()
  229575. {
  229576. return 0;
  229577. }
  229578. struct MidiPortAndCallback
  229579. {
  229580. MidiInput* input;
  229581. MIDIPortRef port;
  229582. MIDIEndpointRef endPoint;
  229583. MidiInputCallback* callback;
  229584. MemoryBlock pendingData;
  229585. int pendingBytes;
  229586. double pendingDataTime;
  229587. bool active;
  229588. };
  229589. static CriticalSection callbackLock;
  229590. static VoidArray activeCallbacks;
  229591. static void processSysex (MidiPortAndCallback* const mpe, const uint8*& d, int& size, const double time)
  229592. {
  229593. if (*d == 0xf0)
  229594. {
  229595. mpe->pendingBytes = 0;
  229596. mpe->pendingDataTime = time;
  229597. }
  229598. mpe->pendingData.ensureSize (mpe->pendingBytes + size, false);
  229599. uint8* totalMessage = (uint8*) mpe->pendingData.getData();
  229600. uint8* dest = totalMessage + mpe->pendingBytes;
  229601. while (size > 0)
  229602. {
  229603. if (mpe->pendingBytes > 0 && *d >= 0x80)
  229604. {
  229605. if (*d >= 0xfa || *d == 0xf8)
  229606. {
  229607. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (*d, time));
  229608. ++d;
  229609. --size;
  229610. }
  229611. else
  229612. {
  229613. if (*d == 0xf7)
  229614. {
  229615. *dest++ = *d++;
  229616. mpe->pendingBytes++;
  229617. --size;
  229618. }
  229619. break;
  229620. }
  229621. }
  229622. else
  229623. {
  229624. *dest++ = *d++;
  229625. mpe->pendingBytes++;
  229626. --size;
  229627. }
  229628. }
  229629. if (totalMessage [mpe->pendingBytes - 1] == 0xf7)
  229630. {
  229631. mpe->callback->handleIncomingMidiMessage (mpe->input, MidiMessage (totalMessage,
  229632. mpe->pendingBytes,
  229633. mpe->pendingDataTime));
  229634. mpe->pendingBytes = 0;
  229635. }
  229636. else
  229637. {
  229638. mpe->callback->handlePartialSysexMessage (mpe->input,
  229639. totalMessage,
  229640. mpe->pendingBytes,
  229641. mpe->pendingDataTime);
  229642. }
  229643. }
  229644. static void midiInputProc (const MIDIPacketList* pktlist,
  229645. void* readProcRefCon,
  229646. void* srcConnRefCon)
  229647. {
  229648. double time = Time::getMillisecondCounterHiRes() * 0.001;
  229649. const double originalTime = time;
  229650. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) readProcRefCon;
  229651. const ScopedLock sl (callbackLock);
  229652. if (activeCallbacks.contains (mpe) && mpe->active)
  229653. {
  229654. const MIDIPacket* packet = &pktlist->packet[0];
  229655. for (unsigned int i = 0; i < pktlist->numPackets; ++i)
  229656. {
  229657. const uint8* d = (const uint8*) (packet->data);
  229658. int size = packet->length;
  229659. while (size > 0)
  229660. {
  229661. time = originalTime;
  229662. if (mpe->pendingBytes > 0 || d[0] == 0xf0)
  229663. {
  229664. processSysex (mpe, d, size, time);
  229665. }
  229666. else
  229667. {
  229668. int used = 0;
  229669. const MidiMessage m (d, size, used, 0, time);
  229670. if (used <= 0)
  229671. {
  229672. jassertfalse // malformed midi message
  229673. break;
  229674. }
  229675. else
  229676. {
  229677. mpe->callback->handleIncomingMidiMessage (mpe->input, m);
  229678. }
  229679. size -= used;
  229680. d += used;
  229681. }
  229682. }
  229683. packet = MIDIPacketNext (packet);
  229684. }
  229685. }
  229686. }
  229687. MidiInput* MidiInput::openDevice (int index, MidiInputCallback* callback)
  229688. {
  229689. MidiInput* mi = 0;
  229690. if (((unsigned int) index) < (unsigned int) MIDIGetNumberOfSources())
  229691. {
  229692. MIDIEndpointRef endPoint = MIDIGetSource (index);
  229693. if (endPoint != 0)
  229694. {
  229695. CFStringRef pname;
  229696. if (OK (MIDIObjectGetStringProperty (endPoint, kMIDIPropertyName, &pname)))
  229697. {
  229698. log (T("CoreMidi - opening inp: ") + PlatformUtilities::cfStringToJuceString (pname));
  229699. if (makeSureClientExists())
  229700. {
  229701. MIDIPortRef port;
  229702. MidiPortAndCallback* const mpe = new MidiPortAndCallback();
  229703. mpe->active = false;
  229704. if (OK (MIDIInputPortCreate (globalMidiClient, pname, midiInputProc, mpe, &port)))
  229705. {
  229706. if (OK (MIDIPortConnectSource (port, endPoint, 0)))
  229707. {
  229708. mpe->port = port;
  229709. mpe->endPoint = endPoint;
  229710. mpe->callback = callback;
  229711. mpe->pendingBytes = 0;
  229712. mpe->pendingData.ensureSize (128);
  229713. mi = new MidiInput (getDevices() [index]);
  229714. mpe->input = mi;
  229715. mi->internal = (void*) mpe;
  229716. const ScopedLock sl (callbackLock);
  229717. activeCallbacks.add (mpe);
  229718. }
  229719. else
  229720. {
  229721. OK (MIDIPortDispose (port));
  229722. delete mpe;
  229723. }
  229724. }
  229725. else
  229726. {
  229727. delete mpe;
  229728. }
  229729. }
  229730. }
  229731. CFRelease (pname);
  229732. }
  229733. }
  229734. return mi;
  229735. }
  229736. MidiInput::MidiInput (const String& name_)
  229737. : name (name_)
  229738. {
  229739. }
  229740. MidiInput::~MidiInput()
  229741. {
  229742. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  229743. mpe->active = false;
  229744. callbackLock.enter();
  229745. activeCallbacks.removeValue (mpe);
  229746. callbackLock.exit();
  229747. OK (MIDIPortDisconnectSource (mpe->port, mpe->endPoint));
  229748. OK (MIDIPortDispose (mpe->port));
  229749. delete mpe;
  229750. }
  229751. void MidiInput::start()
  229752. {
  229753. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  229754. const ScopedLock sl (callbackLock);
  229755. mpe->active = true;
  229756. }
  229757. void MidiInput::stop()
  229758. {
  229759. MidiPortAndCallback* const mpe = (MidiPortAndCallback*) internal;
  229760. const ScopedLock sl (callbackLock);
  229761. mpe->active = false;
  229762. }
  229763. #undef log
  229764. #endif
  229765. /********* End of inlined file: juce_mac_CoreMidi.cpp *********/
  229766. #endif
  229767. END_JUCE_NAMESPACE
  229768. /********* End of inlined file: juce_mac_NativeCode.mm *********/
  229769. /********* Start of inlined file: juce_mac_NamedPipe.cpp *********/
  229770. #include <sys/stat.h>
  229771. #include <sys/dir.h>
  229772. #include <fcntl.h>
  229773. // As well as being for the mac, this file is included by the linux build.
  229774. #if ! JUCE_MAC
  229775. #include <sys/wait.h>
  229776. #include <errno.h>
  229777. #include <unistd.h>
  229778. #endif
  229779. BEGIN_JUCE_NAMESPACE
  229780. struct NamedPipeInternal
  229781. {
  229782. String pipeInName, pipeOutName;
  229783. int pipeIn, pipeOut;
  229784. bool volatile createdPipe, blocked, stopReadOperation;
  229785. static void signalHandler (int) {}
  229786. };
  229787. void NamedPipe::cancelPendingReads()
  229788. {
  229789. while (internal != 0 && ((NamedPipeInternal*) internal)->blocked)
  229790. {
  229791. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  229792. intern->stopReadOperation = true;
  229793. char buffer [1] = { 0 };
  229794. ::write (intern->pipeIn, buffer, 1);
  229795. int timeout = 2000;
  229796. while (intern->blocked && --timeout >= 0)
  229797. Thread::sleep (2);
  229798. intern->stopReadOperation = false;
  229799. }
  229800. }
  229801. void NamedPipe::close()
  229802. {
  229803. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  229804. if (intern != 0)
  229805. {
  229806. internal = 0;
  229807. if (intern->pipeIn != -1)
  229808. ::close (intern->pipeIn);
  229809. if (intern->pipeOut != -1)
  229810. ::close (intern->pipeOut);
  229811. if (intern->createdPipe)
  229812. {
  229813. unlink (intern->pipeInName);
  229814. unlink (intern->pipeOutName);
  229815. }
  229816. delete intern;
  229817. }
  229818. }
  229819. bool NamedPipe::openInternal (const String& pipeName, const bool createPipe)
  229820. {
  229821. close();
  229822. NamedPipeInternal* const intern = new NamedPipeInternal();
  229823. internal = intern;
  229824. intern->createdPipe = createPipe;
  229825. intern->blocked = false;
  229826. intern->stopReadOperation = false;
  229827. signal (SIGPIPE, NamedPipeInternal::signalHandler);
  229828. siginterrupt (SIGPIPE, 1);
  229829. const String pipePath (T("/tmp/") + File::createLegalFileName (pipeName));
  229830. intern->pipeInName = pipePath + T("_in");
  229831. intern->pipeOutName = pipePath + T("_out");
  229832. intern->pipeIn = -1;
  229833. intern->pipeOut = -1;
  229834. if (createPipe)
  229835. {
  229836. if ((mkfifo (intern->pipeInName, 0666) && errno != EEXIST)
  229837. || (mkfifo (intern->pipeOutName, 0666) && errno != EEXIST))
  229838. {
  229839. delete intern;
  229840. internal = 0;
  229841. return false;
  229842. }
  229843. }
  229844. return true;
  229845. }
  229846. int NamedPipe::read (void* destBuffer, int maxBytesToRead, int /*timeOutMilliseconds*/)
  229847. {
  229848. int bytesRead = -1;
  229849. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  229850. if (intern != 0)
  229851. {
  229852. intern->blocked = true;
  229853. if (intern->pipeIn == -1)
  229854. {
  229855. if (intern->createdPipe)
  229856. intern->pipeIn = ::open (intern->pipeInName, O_RDWR);
  229857. else
  229858. intern->pipeIn = ::open (intern->pipeOutName, O_RDWR);
  229859. if (intern->pipeIn == -1)
  229860. {
  229861. intern->blocked = false;
  229862. return -1;
  229863. }
  229864. }
  229865. bytesRead = 0;
  229866. char* p = (char*) destBuffer;
  229867. while (bytesRead < maxBytesToRead)
  229868. {
  229869. const int bytesThisTime = maxBytesToRead - bytesRead;
  229870. const int numRead = ::read (intern->pipeIn, p, bytesThisTime);
  229871. if (numRead <= 0 || intern->stopReadOperation)
  229872. {
  229873. bytesRead = -1;
  229874. break;
  229875. }
  229876. bytesRead += numRead;
  229877. p += bytesRead;
  229878. }
  229879. intern->blocked = false;
  229880. }
  229881. return bytesRead;
  229882. }
  229883. int NamedPipe::write (const void* sourceBuffer, int numBytesToWrite, int timeOutMilliseconds)
  229884. {
  229885. int bytesWritten = -1;
  229886. NamedPipeInternal* const intern = (NamedPipeInternal*) internal;
  229887. if (intern != 0)
  229888. {
  229889. if (intern->pipeOut == -1)
  229890. {
  229891. if (intern->createdPipe)
  229892. intern->pipeOut = ::open (intern->pipeOutName, O_WRONLY);
  229893. else
  229894. intern->pipeOut = ::open (intern->pipeInName, O_WRONLY);
  229895. if (intern->pipeOut == -1)
  229896. {
  229897. return -1;
  229898. }
  229899. }
  229900. const char* p = (const char*) sourceBuffer;
  229901. bytesWritten = 0;
  229902. const uint32 timeOutTime = Time::getMillisecondCounter() + timeOutMilliseconds;
  229903. while (bytesWritten < numBytesToWrite
  229904. && (timeOutMilliseconds < 0 || Time::getMillisecondCounter() < timeOutTime))
  229905. {
  229906. const int bytesThisTime = numBytesToWrite - bytesWritten;
  229907. const int numWritten = ::write (intern->pipeOut, p, bytesThisTime);
  229908. if (numWritten <= 0)
  229909. {
  229910. bytesWritten = -1;
  229911. break;
  229912. }
  229913. bytesWritten += numWritten;
  229914. p += bytesWritten;
  229915. }
  229916. }
  229917. return bytesWritten;
  229918. }
  229919. END_JUCE_NAMESPACE
  229920. /********* End of inlined file: juce_mac_NamedPipe.cpp *********/
  229921. #endif